spirv_cpp.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558
  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 spv;
  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), "> ", 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), "> ", 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), "> ", 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), "> ", 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), "> ", 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. declare_undefined_values();
  237. statement("inline void init(spirv_cross_shader& s)");
  238. begin_scope();
  239. statement(resource_type, "::init(s);");
  240. for (auto &reg : resource_registrations)
  241. statement(reg);
  242. end_scope();
  243. resource_registrations.clear();
  244. end_scope_decl();
  245. statement("");
  246. statement("Resources* __res;");
  247. if (get_entry_point().model == ExecutionModelGLCompute)
  248. statement("ComputePrivateResources __priv_res;");
  249. statement("");
  250. // Emit regular globals which are allocated per invocation.
  251. emitted = false;
  252. for (auto global : global_variables)
  253. {
  254. auto &var = get<SPIRVariable>(global);
  255. if (var.storage == StorageClassPrivate)
  256. {
  257. if (var.storage == StorageClassWorkgroup)
  258. emit_shared(var);
  259. else
  260. statement(CompilerGLSL::variable_decl(var), ";");
  261. emitted = true;
  262. }
  263. }
  264. if (emitted)
  265. statement("");
  266. }
  267. string CompilerCPP::compile()
  268. {
  269. ir.fixup_reserved_names();
  270. // Do not deal with ES-isms like precision, older extensions and such.
  271. options.es = false;
  272. options.version = 450;
  273. backend.float_literal_suffix = true;
  274. backend.double_literal_suffix = false;
  275. backend.long_long_literal_suffix = true;
  276. backend.uint32_t_literal_suffix = true;
  277. backend.basic_int_type = "int32_t";
  278. backend.basic_uint_type = "uint32_t";
  279. backend.swizzle_is_function = true;
  280. backend.shared_is_implied = true;
  281. backend.unsized_array_supported = false;
  282. backend.explicit_struct_type = true;
  283. backend.use_initializer_list = true;
  284. fixup_type_alias();
  285. reorder_type_alias();
  286. build_function_control_flow_graphs_and_analyze();
  287. update_active_builtins();
  288. uint32_t pass_count = 0;
  289. do
  290. {
  291. if (pass_count >= 3)
  292. SPIRV_CROSS_THROW("Over 3 compilation loops detected. Must be a bug!");
  293. resource_registrations.clear();
  294. reset();
  295. // Move constructor for this type is broken on GCC 4.9 ...
  296. buffer.reset();
  297. emit_header();
  298. emit_resources();
  299. emit_function(get<SPIRFunction>(ir.default_entry_point), Bitset());
  300. pass_count++;
  301. } while (is_forcing_recompilation());
  302. // Match opening scope of emit_header().
  303. end_scope_decl();
  304. // namespace
  305. end_scope();
  306. // Emit C entry points
  307. emit_c_linkage();
  308. // Entry point in CPP is always main() for the time being.
  309. get_entry_point().name = "main";
  310. return buffer.str();
  311. }
  312. void CompilerCPP::emit_c_linkage()
  313. {
  314. statement("");
  315. statement("spirv_cross_shader_t *spirv_cross_construct(void)");
  316. begin_scope();
  317. statement("return new ", impl_type, "();");
  318. end_scope();
  319. statement("");
  320. statement("void spirv_cross_destruct(spirv_cross_shader_t *shader)");
  321. begin_scope();
  322. statement("delete static_cast<", impl_type, "*>(shader);");
  323. end_scope();
  324. statement("");
  325. statement("void spirv_cross_invoke(spirv_cross_shader_t *shader)");
  326. begin_scope();
  327. statement("static_cast<", impl_type, "*>(shader)->invoke();");
  328. end_scope();
  329. statement("");
  330. statement("static const struct spirv_cross_interface vtable =");
  331. begin_scope();
  332. statement("spirv_cross_construct,");
  333. statement("spirv_cross_destruct,");
  334. statement("spirv_cross_invoke,");
  335. end_scope_decl();
  336. statement("");
  337. statement("const struct spirv_cross_interface *",
  338. interface_name.empty() ? string("spirv_cross_get_interface") : interface_name, "(void)");
  339. begin_scope();
  340. statement("return &vtable;");
  341. end_scope();
  342. }
  343. void CompilerCPP::emit_function_prototype(SPIRFunction &func, const Bitset &)
  344. {
  345. if (func.self != ir.default_entry_point)
  346. add_function_overload(func);
  347. local_variable_names = resource_names;
  348. string decl;
  349. auto &type = get<SPIRType>(func.return_type);
  350. decl += "inline ";
  351. decl += type_to_glsl(type);
  352. decl += " ";
  353. if (func.self == ir.default_entry_point)
  354. {
  355. decl += "main";
  356. processing_entry_point = true;
  357. }
  358. else
  359. decl += to_name(func.self);
  360. decl += "(";
  361. for (auto &arg : func.arguments)
  362. {
  363. add_local_variable_name(arg.id);
  364. decl += argument_decl(arg);
  365. if (&arg != &func.arguments.back())
  366. decl += ", ";
  367. // Hold a pointer to the parameter so we can invalidate the readonly field if needed.
  368. auto *var = maybe_get<SPIRVariable>(arg.id);
  369. if (var)
  370. var->parameter = &arg;
  371. }
  372. decl += ")";
  373. statement(decl);
  374. }
  375. string CompilerCPP::argument_decl(const SPIRFunction::Parameter &arg)
  376. {
  377. auto &type = expression_type(arg.id);
  378. bool constref = !type.pointer || arg.write_count == 0;
  379. auto &var = get<SPIRVariable>(arg.id);
  380. string base = type_to_glsl(type);
  381. string variable_name = to_name(var.self);
  382. remap_variable_type_name(type, variable_name, base);
  383. for (uint32_t i = 0; i < type.array.size(); i++)
  384. base = join("std::array<", base, ", ", to_array_size(type, i), ">");
  385. return join(constref ? "const " : "", base, " &", variable_name);
  386. }
  387. string CompilerCPP::variable_decl(const SPIRType &type, const string &name, uint32_t /* id */)
  388. {
  389. string base = type_to_glsl(type);
  390. remap_variable_type_name(type, name, base);
  391. bool runtime = false;
  392. for (uint32_t i = 0; i < type.array.size(); i++)
  393. {
  394. auto &array = type.array[i];
  395. if (!array && type.array_size_literal[i])
  396. {
  397. // Avoid using runtime arrays with std::array since this is undefined.
  398. // Runtime arrays cannot be passed around as values, so this is fine.
  399. runtime = true;
  400. }
  401. else
  402. base = join("std::array<", base, ", ", to_array_size(type, i), ">");
  403. }
  404. base += ' ';
  405. return base + name + (runtime ? "[1]" : "");
  406. }
  407. void CompilerCPP::emit_header()
  408. {
  409. auto &execution = get_entry_point();
  410. statement("// This C++ shader is autogenerated by spirv-cross.");
  411. statement("#include \"spirv_cross/internal_interface.hpp\"");
  412. statement("#include \"spirv_cross/external_interface.h\"");
  413. // Needed to properly implement GLSL-style arrays.
  414. statement("#include <array>");
  415. statement("#include <stdint.h>");
  416. statement("");
  417. statement("using namespace spirv_cross;");
  418. statement("using namespace glm;");
  419. statement("");
  420. statement("namespace Impl");
  421. begin_scope();
  422. switch (execution.model)
  423. {
  424. case ExecutionModelGeometry:
  425. case ExecutionModelTessellationControl:
  426. case ExecutionModelTessellationEvaluation:
  427. case ExecutionModelGLCompute:
  428. case ExecutionModelFragment:
  429. case ExecutionModelVertex:
  430. statement("struct Shader");
  431. begin_scope();
  432. break;
  433. default:
  434. SPIRV_CROSS_THROW("Unsupported execution model.");
  435. }
  436. switch (execution.model)
  437. {
  438. case ExecutionModelGeometry:
  439. impl_type = "GeometryShader<Impl::Shader, Impl::Shader::Resources>";
  440. resource_type = "GeometryResources";
  441. break;
  442. case ExecutionModelVertex:
  443. impl_type = "VertexShader<Impl::Shader, Impl::Shader::Resources>";
  444. resource_type = "VertexResources";
  445. break;
  446. case ExecutionModelFragment:
  447. impl_type = "FragmentShader<Impl::Shader, Impl::Shader::Resources>";
  448. resource_type = "FragmentResources";
  449. break;
  450. case ExecutionModelGLCompute:
  451. impl_type = join("ComputeShader<Impl::Shader, Impl::Shader::Resources, ", execution.workgroup_size.x, ", ",
  452. execution.workgroup_size.y, ", ", execution.workgroup_size.z, ">");
  453. resource_type = "ComputeResources";
  454. break;
  455. case ExecutionModelTessellationControl:
  456. impl_type = "TessControlShader<Impl::Shader, Impl::Shader::Resources>";
  457. resource_type = "TessControlResources";
  458. break;
  459. case ExecutionModelTessellationEvaluation:
  460. impl_type = "TessEvaluationShader<Impl::Shader, Impl::Shader::Resources>";
  461. resource_type = "TessEvaluationResources";
  462. break;
  463. default:
  464. SPIRV_CROSS_THROW("Unsupported execution model.");
  465. }
  466. }