spirv_cpp.cpp 15 KB

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