spirv_cpp.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553
  1. /*
  2. * Copyright 2015-2021 Arm Limited
  3. * SPDX-License-Identifier: Apache-2.0 OR MIT
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. */
  17. /*
  18. * At your option, you may choose to accept this material under either:
  19. * 1. The Apache License, Version 2.0, found at <http://www.apache.org/licenses/LICENSE-2.0>, or
  20. * 2. The MIT License, found at <http://opensource.org/licenses/MIT>.
  21. */
  22. #include "spirv_cpp.hpp"
  23. using namespace SPIRV_CROSS_SPV_HEADER_NAMESPACE;
  24. using namespace SPIRV_CROSS_NAMESPACE;
  25. using namespace std;
  26. void CompilerCPP::emit_buffer_block(const SPIRVariable &var)
  27. {
  28. add_resource_name(var.self);
  29. auto &type = get<SPIRType>(var.basetype);
  30. auto instance_name = to_name(var.self);
  31. uint32_t descriptor_set = ir.meta[var.self].decoration.set;
  32. uint32_t binding = ir.meta[var.self].decoration.binding;
  33. emit_block_struct(type);
  34. auto buffer_name = to_name(type.self);
  35. statement("internal::Resource<", buffer_name, type_to_array_glsl(type, var.self), "> ", instance_name, "__;");
  36. statement_no_indent("#define ", instance_name, " __res->", instance_name, "__.get()");
  37. resource_registrations.push_back(
  38. join("s.register_resource(", instance_name, "__", ", ", descriptor_set, ", ", binding, ");"));
  39. statement("");
  40. }
  41. void CompilerCPP::emit_interface_block(const SPIRVariable &var)
  42. {
  43. add_resource_name(var.self);
  44. auto &type = get<SPIRType>(var.basetype);
  45. const char *qual = var.storage == StorageClassInput ? "StageInput" : "StageOutput";
  46. const char *lowerqual = var.storage == StorageClassInput ? "stage_input" : "stage_output";
  47. auto instance_name = to_name(var.self);
  48. uint32_t location = ir.meta[var.self].decoration.location;
  49. string buffer_name;
  50. auto flags = ir.meta[type.self].decoration.decoration_flags;
  51. if (flags.get(DecorationBlock))
  52. {
  53. emit_block_struct(type);
  54. buffer_name = to_name(type.self);
  55. }
  56. else
  57. buffer_name = type_to_glsl(type);
  58. statement("internal::", qual, "<", buffer_name, type_to_array_glsl(type, var.self), "> ", instance_name, "__;");
  59. statement_no_indent("#define ", instance_name, " __res->", instance_name, "__.get()");
  60. resource_registrations.push_back(join("s.register_", lowerqual, "(", instance_name, "__", ", ", location, ");"));
  61. statement("");
  62. }
  63. void CompilerCPP::emit_shared(const SPIRVariable &var)
  64. {
  65. add_resource_name(var.self);
  66. auto instance_name = to_name(var.self);
  67. statement(CompilerGLSL::variable_decl(var), ";");
  68. statement_no_indent("#define ", instance_name, " __res->", instance_name);
  69. }
  70. void CompilerCPP::emit_uniform(const SPIRVariable &var)
  71. {
  72. add_resource_name(var.self);
  73. auto &type = get<SPIRType>(var.basetype);
  74. auto instance_name = to_name(var.self);
  75. uint32_t descriptor_set = ir.meta[var.self].decoration.set;
  76. uint32_t binding = ir.meta[var.self].decoration.binding;
  77. uint32_t location = ir.meta[var.self].decoration.location;
  78. string type_name = type_to_glsl(type);
  79. remap_variable_type_name(type, instance_name, type_name);
  80. if (type.basetype == SPIRType::Image || type.basetype == SPIRType::SampledImage ||
  81. type.basetype == SPIRType::AtomicCounter)
  82. {
  83. statement("internal::Resource<", type_name, type_to_array_glsl(type, var.self), "> ", instance_name, "__;");
  84. statement_no_indent("#define ", instance_name, " __res->", instance_name, "__.get()");
  85. resource_registrations.push_back(
  86. join("s.register_resource(", instance_name, "__", ", ", descriptor_set, ", ", binding, ");"));
  87. }
  88. else
  89. {
  90. statement("internal::UniformConstant<", type_name, type_to_array_glsl(type, var.self), "> ", instance_name, "__;");
  91. statement_no_indent("#define ", instance_name, " __res->", instance_name, "__.get()");
  92. resource_registrations.push_back(
  93. join("s.register_uniform_constant(", instance_name, "__", ", ", location, ");"));
  94. }
  95. statement("");
  96. }
  97. void CompilerCPP::emit_push_constant_block(const SPIRVariable &var)
  98. {
  99. add_resource_name(var.self);
  100. auto &type = get<SPIRType>(var.basetype);
  101. auto &flags = ir.meta[var.self].decoration.decoration_flags;
  102. if (flags.get(DecorationBinding) || flags.get(DecorationDescriptorSet))
  103. SPIRV_CROSS_THROW("Push constant blocks cannot be compiled to GLSL with Binding or Set syntax. "
  104. "Remap to location with reflection API first or disable these decorations.");
  105. emit_block_struct(type);
  106. auto buffer_name = to_name(type.self);
  107. auto instance_name = to_name(var.self);
  108. statement("internal::PushConstant<", buffer_name, type_to_array_glsl(type, var.self), "> ", instance_name, ";");
  109. statement_no_indent("#define ", instance_name, " __res->", instance_name, ".get()");
  110. resource_registrations.push_back(join("s.register_push_constant(", instance_name, "__", ");"));
  111. statement("");
  112. }
  113. void CompilerCPP::emit_block_struct(SPIRType &type)
  114. {
  115. // C++ can't do interface blocks, so we fake it by emitting a separate struct.
  116. // However, these structs are not allowed to alias anything, so remove it before
  117. // emitting the struct.
  118. //
  119. // The type we have here needs to be resolved to the non-pointer type so we can remove aliases.
  120. auto &self = get<SPIRType>(type.self);
  121. self.type_alias = 0;
  122. emit_struct(self);
  123. }
  124. void CompilerCPP::emit_resources()
  125. {
  126. for (auto &id : ir.ids)
  127. {
  128. if (id.get_type() == TypeConstant)
  129. {
  130. auto &c = id.get<SPIRConstant>();
  131. bool needs_declaration = c.specialization || c.is_used_as_lut;
  132. if (needs_declaration)
  133. {
  134. if (!options.vulkan_semantics && c.specialization)
  135. {
  136. c.specialization_constant_macro_name =
  137. constant_value_macro_name(get_decoration(c.self, DecorationSpecId));
  138. }
  139. emit_constant(c);
  140. }
  141. }
  142. else if (id.get_type() == TypeConstantOp)
  143. {
  144. emit_specialization_constant_op(id.get<SPIRConstantOp>());
  145. }
  146. }
  147. // Output all basic struct types which are not Block or BufferBlock as these are declared inplace
  148. // when such variables are instantiated.
  149. for (auto &id : ir.ids)
  150. {
  151. if (id.get_type() == TypeType)
  152. {
  153. auto &type = id.get<SPIRType>();
  154. if (type.basetype == SPIRType::Struct && type.array.empty() && !type.pointer &&
  155. (!ir.meta[type.self].decoration.decoration_flags.get(DecorationBlock) &&
  156. !ir.meta[type.self].decoration.decoration_flags.get(DecorationBufferBlock)))
  157. {
  158. emit_struct(type);
  159. }
  160. }
  161. }
  162. statement("struct Resources : ", resource_type);
  163. begin_scope();
  164. // Output UBOs and SSBOs
  165. for (auto &id : ir.ids)
  166. {
  167. if (id.get_type() == TypeVariable)
  168. {
  169. auto &var = id.get<SPIRVariable>();
  170. auto &type = get<SPIRType>(var.basetype);
  171. if (var.storage != StorageClassFunction && type.pointer && type.storage == StorageClassUniform &&
  172. !is_hidden_variable(var) &&
  173. (ir.meta[type.self].decoration.decoration_flags.get(DecorationBlock) ||
  174. ir.meta[type.self].decoration.decoration_flags.get(DecorationBufferBlock)))
  175. {
  176. emit_buffer_block(var);
  177. }
  178. }
  179. }
  180. // Output push constant blocks
  181. for (auto &id : ir.ids)
  182. {
  183. if (id.get_type() == TypeVariable)
  184. {
  185. auto &var = id.get<SPIRVariable>();
  186. auto &type = get<SPIRType>(var.basetype);
  187. if (!is_hidden_variable(var) && var.storage != StorageClassFunction && type.pointer &&
  188. type.storage == StorageClassPushConstant)
  189. {
  190. emit_push_constant_block(var);
  191. }
  192. }
  193. }
  194. // Output in/out interfaces.
  195. for (auto &id : ir.ids)
  196. {
  197. if (id.get_type() == TypeVariable)
  198. {
  199. auto &var = id.get<SPIRVariable>();
  200. auto &type = get<SPIRType>(var.basetype);
  201. if (var.storage != StorageClassFunction && !is_hidden_variable(var) && type.pointer &&
  202. (var.storage == StorageClassInput || var.storage == StorageClassOutput) &&
  203. interface_variable_exists_in_entry_point(var.self))
  204. {
  205. emit_interface_block(var);
  206. }
  207. }
  208. }
  209. // Output Uniform Constants (values, samplers, images, etc).
  210. for (auto &id : ir.ids)
  211. {
  212. if (id.get_type() == TypeVariable)
  213. {
  214. auto &var = id.get<SPIRVariable>();
  215. auto &type = get<SPIRType>(var.basetype);
  216. if (var.storage != StorageClassFunction && !is_hidden_variable(var) && type.pointer &&
  217. (type.storage == StorageClassUniformConstant || type.storage == StorageClassAtomicCounter))
  218. {
  219. emit_uniform(var);
  220. }
  221. }
  222. }
  223. // Global variables.
  224. bool emitted = false;
  225. for (auto global : global_variables)
  226. {
  227. auto &var = get<SPIRVariable>(global);
  228. if (var.storage == StorageClassWorkgroup)
  229. {
  230. emit_shared(var);
  231. emitted = true;
  232. }
  233. }
  234. if (emitted)
  235. statement("");
  236. statement("inline void init(spirv_cross_shader& s)");
  237. begin_scope();
  238. statement(resource_type, "::init(s);");
  239. for (auto &reg : resource_registrations)
  240. statement(reg);
  241. end_scope();
  242. resource_registrations.clear();
  243. end_scope_decl();
  244. statement("");
  245. statement("Resources* __res;");
  246. if (get_entry_point().model == ExecutionModelGLCompute)
  247. statement("ComputePrivateResources __priv_res;");
  248. statement("");
  249. // Emit regular globals which are allocated per invocation.
  250. emitted = false;
  251. for (auto global : global_variables)
  252. {
  253. auto &var = get<SPIRVariable>(global);
  254. if (var.storage == StorageClassPrivate)
  255. {
  256. if (var.storage == StorageClassWorkgroup)
  257. emit_shared(var);
  258. else
  259. statement(CompilerGLSL::variable_decl(var), ";");
  260. emitted = true;
  261. }
  262. }
  263. if (emitted)
  264. statement("");
  265. }
  266. string CompilerCPP::compile()
  267. {
  268. ir.fixup_reserved_names();
  269. // Do not deal with ES-isms like precision, older extensions and such.
  270. options.es = false;
  271. options.version = 450;
  272. backend.float_literal_suffix = true;
  273. backend.double_literal_suffix = false;
  274. backend.long_long_literal_suffix = true;
  275. backend.uint32_t_literal_suffix = true;
  276. backend.basic_int_type = "int32_t";
  277. backend.basic_uint_type = "uint32_t";
  278. backend.swizzle_is_function = true;
  279. backend.shared_is_implied = true;
  280. backend.unsized_array_supported = false;
  281. backend.explicit_struct_type = true;
  282. backend.use_initializer_list = true;
  283. fixup_type_alias();
  284. reorder_type_alias();
  285. build_function_control_flow_graphs_and_analyze();
  286. update_active_builtins();
  287. uint32_t pass_count = 0;
  288. do
  289. {
  290. resource_registrations.clear();
  291. reset(pass_count);
  292. // Move constructor for this type is broken on GCC 4.9 ...
  293. buffer.reset();
  294. emit_header();
  295. emit_resources();
  296. emit_function(get<SPIRFunction>(ir.default_entry_point), Bitset());
  297. pass_count++;
  298. } while (is_forcing_recompilation());
  299. // Match opening scope of emit_header().
  300. end_scope_decl();
  301. // namespace
  302. end_scope();
  303. // Emit C entry points
  304. emit_c_linkage();
  305. // Entry point in CPP is always main() for the time being.
  306. get_entry_point().name = "main";
  307. return buffer.str();
  308. }
  309. void CompilerCPP::emit_c_linkage()
  310. {
  311. statement("");
  312. statement("spirv_cross_shader_t *spirv_cross_construct(void)");
  313. begin_scope();
  314. statement("return new ", impl_type, "();");
  315. end_scope();
  316. statement("");
  317. statement("void spirv_cross_destruct(spirv_cross_shader_t *shader)");
  318. begin_scope();
  319. statement("delete static_cast<", impl_type, "*>(shader);");
  320. end_scope();
  321. statement("");
  322. statement("void spirv_cross_invoke(spirv_cross_shader_t *shader)");
  323. begin_scope();
  324. statement("static_cast<", impl_type, "*>(shader)->invoke();");
  325. end_scope();
  326. statement("");
  327. statement("static const struct spirv_cross_interface vtable =");
  328. begin_scope();
  329. statement("spirv_cross_construct,");
  330. statement("spirv_cross_destruct,");
  331. statement("spirv_cross_invoke,");
  332. end_scope_decl();
  333. statement("");
  334. statement("const struct spirv_cross_interface *",
  335. interface_name.empty() ? string("spirv_cross_get_interface") : interface_name, "(void)");
  336. begin_scope();
  337. statement("return &vtable;");
  338. end_scope();
  339. }
  340. void CompilerCPP::emit_function_prototype(SPIRFunction &func, const Bitset &)
  341. {
  342. if (func.self != ir.default_entry_point)
  343. add_function_overload(func);
  344. local_variable_names = resource_names;
  345. string decl;
  346. auto &type = get<SPIRType>(func.return_type);
  347. decl += "inline ";
  348. decl += type_to_glsl(type);
  349. decl += " ";
  350. if (func.self == ir.default_entry_point)
  351. {
  352. decl += "main";
  353. processing_entry_point = true;
  354. }
  355. else
  356. decl += to_name(func.self);
  357. decl += "(";
  358. for (auto &arg : func.arguments)
  359. {
  360. add_local_variable_name(arg.id);
  361. decl += argument_decl(arg);
  362. if (&arg != &func.arguments.back())
  363. decl += ", ";
  364. // Hold a pointer to the parameter so we can invalidate the readonly field if needed.
  365. auto *var = maybe_get<SPIRVariable>(arg.id);
  366. if (var)
  367. var->parameter = &arg;
  368. }
  369. decl += ")";
  370. statement(decl);
  371. }
  372. string CompilerCPP::argument_decl(const SPIRFunction::Parameter &arg)
  373. {
  374. auto &type = expression_type(arg.id);
  375. bool constref = !type.pointer || arg.write_count == 0;
  376. auto &var = get<SPIRVariable>(arg.id);
  377. string base = type_to_glsl(type);
  378. string variable_name = to_name(var.self);
  379. remap_variable_type_name(type, variable_name, base);
  380. for (uint32_t i = 0; i < type.array.size(); i++)
  381. base = join("std::array<", base, ", ", to_array_size(type, i), ">");
  382. return join(constref ? "const " : "", base, " &", variable_name);
  383. }
  384. string CompilerCPP::variable_decl(const SPIRType &type, const string &name, uint32_t /* id */)
  385. {
  386. string base = type_to_glsl(type);
  387. remap_variable_type_name(type, name, base);
  388. bool runtime = false;
  389. for (uint32_t i = 0; i < type.array.size(); i++)
  390. {
  391. auto &array = type.array[i];
  392. if (!array && type.array_size_literal[i])
  393. {
  394. // Avoid using runtime arrays with std::array since this is undefined.
  395. // Runtime arrays cannot be passed around as values, so this is fine.
  396. runtime = true;
  397. }
  398. else
  399. base = join("std::array<", base, ", ", to_array_size(type, i), ">");
  400. }
  401. base += ' ';
  402. return base + name + (runtime ? "[1]" : "");
  403. }
  404. void CompilerCPP::emit_header()
  405. {
  406. auto &execution = get_entry_point();
  407. statement("// This C++ shader is autogenerated by spirv-cross.");
  408. statement("#include \"spirv_cross/internal_interface.hpp\"");
  409. statement("#include \"spirv_cross/external_interface.h\"");
  410. // Needed to properly implement GLSL-style arrays.
  411. statement("#include <array>");
  412. statement("#include <stdint.h>");
  413. statement("");
  414. statement("using namespace spirv_cross;");
  415. statement("using namespace glm;");
  416. statement("");
  417. statement("namespace Impl");
  418. begin_scope();
  419. switch (execution.model)
  420. {
  421. case ExecutionModelGeometry:
  422. case ExecutionModelTessellationControl:
  423. case ExecutionModelTessellationEvaluation:
  424. case ExecutionModelGLCompute:
  425. case ExecutionModelFragment:
  426. case ExecutionModelVertex:
  427. statement("struct Shader");
  428. begin_scope();
  429. break;
  430. default:
  431. SPIRV_CROSS_THROW("Unsupported execution model.");
  432. }
  433. switch (execution.model)
  434. {
  435. case ExecutionModelGeometry:
  436. impl_type = "GeometryShader<Impl::Shader, Impl::Shader::Resources>";
  437. resource_type = "GeometryResources";
  438. break;
  439. case ExecutionModelVertex:
  440. impl_type = "VertexShader<Impl::Shader, Impl::Shader::Resources>";
  441. resource_type = "VertexResources";
  442. break;
  443. case ExecutionModelFragment:
  444. impl_type = "FragmentShader<Impl::Shader, Impl::Shader::Resources>";
  445. resource_type = "FragmentResources";
  446. break;
  447. case ExecutionModelGLCompute:
  448. impl_type = join("ComputeShader<Impl::Shader, Impl::Shader::Resources, ", execution.workgroup_size.x, ", ",
  449. execution.workgroup_size.y, ", ", execution.workgroup_size.z, ">");
  450. resource_type = "ComputeResources";
  451. break;
  452. case ExecutionModelTessellationControl:
  453. impl_type = "TessControlShader<Impl::Shader, Impl::Shader::Resources>";
  454. resource_type = "TessControlResources";
  455. break;
  456. case ExecutionModelTessellationEvaluation:
  457. impl_type = "TessEvaluationShader<Impl::Shader, Impl::Shader::Resources>";
  458. resource_type = "TessEvaluationResources";
  459. break;
  460. default:
  461. SPIRV_CROSS_THROW("Unsupported execution model.");
  462. }
  463. }