spirv_glsl.hpp 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910
  1. /*
  2. * Copyright 2015-2021 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. /*
  17. * At your option, you may choose to accept this material under either:
  18. * 1. The Apache License, Version 2.0, found at <http://www.apache.org/licenses/LICENSE-2.0>, or
  19. * 2. The MIT License, found at <http://opensource.org/licenses/MIT>.
  20. * SPDX-License-Identifier: Apache-2.0 OR MIT.
  21. */
  22. #ifndef SPIRV_CROSS_GLSL_HPP
  23. #define SPIRV_CROSS_GLSL_HPP
  24. #include "GLSL.std.450.h"
  25. #include "spirv_cross.hpp"
  26. #include <unordered_map>
  27. #include <unordered_set>
  28. #include <utility>
  29. namespace SPIRV_CROSS_NAMESPACE
  30. {
  31. enum PlsFormat
  32. {
  33. PlsNone = 0,
  34. PlsR11FG11FB10F,
  35. PlsR32F,
  36. PlsRG16F,
  37. PlsRGB10A2,
  38. PlsRGBA8,
  39. PlsRG16,
  40. PlsRGBA8I,
  41. PlsRG16I,
  42. PlsRGB10A2UI,
  43. PlsRGBA8UI,
  44. PlsRG16UI,
  45. PlsR32UI
  46. };
  47. struct PlsRemap
  48. {
  49. uint32_t id;
  50. PlsFormat format;
  51. };
  52. enum AccessChainFlagBits
  53. {
  54. ACCESS_CHAIN_INDEX_IS_LITERAL_BIT = 1 << 0,
  55. ACCESS_CHAIN_CHAIN_ONLY_BIT = 1 << 1,
  56. ACCESS_CHAIN_PTR_CHAIN_BIT = 1 << 2,
  57. ACCESS_CHAIN_SKIP_REGISTER_EXPRESSION_READ_BIT = 1 << 3,
  58. ACCESS_CHAIN_LITERAL_MSB_FORCE_ID = 1 << 4,
  59. ACCESS_CHAIN_FLATTEN_ALL_MEMBERS_BIT = 1 << 5
  60. };
  61. typedef uint32_t AccessChainFlags;
  62. class CompilerGLSL : public Compiler
  63. {
  64. public:
  65. struct Options
  66. {
  67. // The shading language version. Corresponds to #version $VALUE.
  68. uint32_t version = 450;
  69. // Emit the OpenGL ES shading language instead of desktop OpenGL.
  70. bool es = false;
  71. // Debug option to always emit temporary variables for all expressions.
  72. bool force_temporary = false;
  73. // If true, Vulkan GLSL features are used instead of GL-compatible features.
  74. // Mostly useful for debugging SPIR-V files.
  75. bool vulkan_semantics = false;
  76. // If true, gl_PerVertex is explicitly redeclared in vertex, geometry and tessellation shaders.
  77. // The members of gl_PerVertex is determined by which built-ins are declared by the shader.
  78. // This option is ignored in ES versions, as redeclaration in ES is not required, and it depends on a different extension
  79. // (EXT_shader_io_blocks) which makes things a bit more fuzzy.
  80. bool separate_shader_objects = false;
  81. // Flattens multidimensional arrays, e.g. float foo[a][b][c] into single-dimensional arrays,
  82. // e.g. float foo[a * b * c].
  83. // This function does not change the actual SPIRType of any object.
  84. // Only the generated code, including declarations of interface variables are changed to be single array dimension.
  85. bool flatten_multidimensional_arrays = false;
  86. // For older desktop GLSL targets than version 420, the
  87. // GL_ARB_shading_language_420pack extensions is used to be able to support
  88. // layout(binding) on UBOs and samplers.
  89. // If disabled on older targets, binding decorations will be stripped.
  90. bool enable_420pack_extension = true;
  91. // In non-Vulkan GLSL, emit push constant blocks as UBOs rather than plain uniforms.
  92. bool emit_push_constant_as_uniform_buffer = false;
  93. // Always emit uniform blocks as plain uniforms, regardless of the GLSL version, even when UBOs are supported.
  94. // Does not apply to shader storage or push constant blocks.
  95. bool emit_uniform_buffer_as_plain_uniforms = false;
  96. // Emit OpLine directives if present in the module.
  97. // May not correspond exactly to original source, but should be a good approximation.
  98. bool emit_line_directives = false;
  99. // In cases where readonly/writeonly decoration are not used at all,
  100. // we try to deduce which qualifier(s) we should actually used, since actually emitting
  101. // read-write decoration is very rare, and older glslang/HLSL compilers tend to just emit readwrite as a matter of fact.
  102. // The default (true) is to enable automatic deduction for these cases, but if you trust the decorations set
  103. // by the SPIR-V, it's recommended to set this to false.
  104. bool enable_storage_image_qualifier_deduction = true;
  105. // On some targets (WebGPU), uninitialized variables are banned.
  106. // If this is enabled, all variables (temporaries, Private, Function)
  107. // which would otherwise be uninitialized will now be initialized to 0 instead.
  108. bool force_zero_initialized_variables = false;
  109. // In GLSL, force use of I/O block flattening, similar to
  110. // what happens on legacy GLSL targets for blocks and structs.
  111. bool force_flattened_io_blocks = false;
  112. enum Precision
  113. {
  114. DontCare,
  115. Lowp,
  116. Mediump,
  117. Highp
  118. };
  119. struct VertexOptions
  120. {
  121. // "Vertex-like shader" here is any shader stage that can write BuiltInPosition.
  122. // GLSL: In vertex-like shaders, rewrite [0, w] depth (Vulkan/D3D style) to [-w, w] depth (GL style).
  123. // MSL: In vertex-like shaders, rewrite [-w, w] depth (GL style) to [0, w] depth.
  124. // HLSL: In vertex-like shaders, rewrite [-w, w] depth (GL style) to [0, w] depth.
  125. bool fixup_clipspace = false;
  126. // In vertex-like shaders, inverts gl_Position.y or equivalent.
  127. bool flip_vert_y = false;
  128. // GLSL only, for HLSL version of this option, see CompilerHLSL.
  129. // If true, the backend will assume that InstanceIndex will need to apply
  130. // a base instance offset. Set to false if you know you will never use base instance
  131. // functionality as it might remove some internal uniforms.
  132. bool support_nonzero_base_instance = true;
  133. } vertex;
  134. struct FragmentOptions
  135. {
  136. // Add precision mediump float in ES targets when emitting GLES source.
  137. // Add precision highp int in ES targets when emitting GLES source.
  138. Precision default_float_precision = Mediump;
  139. Precision default_int_precision = Highp;
  140. } fragment;
  141. };
  142. void remap_pixel_local_storage(std::vector<PlsRemap> inputs, std::vector<PlsRemap> outputs)
  143. {
  144. pls_inputs = std::move(inputs);
  145. pls_outputs = std::move(outputs);
  146. remap_pls_variables();
  147. }
  148. // Redirect a subpassInput reading from input_attachment_index to instead load its value from
  149. // the color attachment at location = color_location. Requires ESSL.
  150. void remap_ext_framebuffer_fetch(uint32_t input_attachment_index, uint32_t color_location);
  151. explicit CompilerGLSL(std::vector<uint32_t> spirv_)
  152. : Compiler(std::move(spirv_))
  153. {
  154. init();
  155. }
  156. CompilerGLSL(const uint32_t *ir_, size_t word_count)
  157. : Compiler(ir_, word_count)
  158. {
  159. init();
  160. }
  161. explicit CompilerGLSL(const ParsedIR &ir_)
  162. : Compiler(ir_)
  163. {
  164. init();
  165. }
  166. explicit CompilerGLSL(ParsedIR &&ir_)
  167. : Compiler(std::move(ir_))
  168. {
  169. init();
  170. }
  171. const Options &get_common_options() const
  172. {
  173. return options;
  174. }
  175. void set_common_options(const Options &opts)
  176. {
  177. options = opts;
  178. }
  179. std::string compile() override;
  180. // Returns the current string held in the conversion buffer. Useful for
  181. // capturing what has been converted so far when compile() throws an error.
  182. std::string get_partial_source();
  183. // Adds a line to be added right after #version in GLSL backend.
  184. // This is useful for enabling custom extensions which are outside the scope of SPIRV-Cross.
  185. // This can be combined with variable remapping.
  186. // A new-line will be added.
  187. //
  188. // While add_header_line() is a more generic way of adding arbitrary text to the header
  189. // of a GLSL file, require_extension() should be used when adding extensions since it will
  190. // avoid creating collisions with SPIRV-Cross generated extensions.
  191. //
  192. // Code added via add_header_line() is typically backend-specific.
  193. void add_header_line(const std::string &str);
  194. // Adds an extension which is required to run this shader, e.g.
  195. // require_extension("GL_KHR_my_extension");
  196. void require_extension(const std::string &ext);
  197. // Legacy GLSL compatibility method.
  198. // Takes a uniform or push constant variable and flattens it into a (i|u)vec4 array[N]; array instead.
  199. // For this to work, all types in the block must be the same basic type, e.g. mixing vec2 and vec4 is fine, but
  200. // mixing int and float is not.
  201. // The name of the uniform array will be the same as the interface block name.
  202. void flatten_buffer_block(VariableID id);
  203. // After compilation, query if a variable ID was used as a depth resource.
  204. // This is meaningful for MSL since descriptor types depend on this knowledge.
  205. // Cases which return true:
  206. // - Images which are declared with depth = 1 image type.
  207. // - Samplers which are statically used at least once with Dref opcodes.
  208. // - Images which are statically used at least once with Dref opcodes.
  209. bool variable_is_depth_or_compare(VariableID id) const;
  210. protected:
  211. struct ShaderSubgroupSupportHelper
  212. {
  213. // lower enum value = greater priority
  214. enum Candidate
  215. {
  216. KHR_shader_subgroup_ballot,
  217. KHR_shader_subgroup_basic,
  218. KHR_shader_subgroup_vote,
  219. NV_gpu_shader_5,
  220. NV_shader_thread_group,
  221. NV_shader_thread_shuffle,
  222. ARB_shader_ballot,
  223. ARB_shader_group_vote,
  224. AMD_gcn_shader,
  225. CandidateCount
  226. };
  227. static const char *get_extension_name(Candidate c);
  228. static SmallVector<std::string> get_extra_required_extension_names(Candidate c);
  229. static const char *get_extra_required_extension_predicate(Candidate c);
  230. enum Feature
  231. {
  232. SubgroupMask = 0,
  233. SubgroupSize = 1,
  234. SubgroupInvocationID = 2,
  235. SubgroupID = 3,
  236. NumSubgroups = 4,
  237. SubgroupBroadcast_First = 5,
  238. SubgroupBallotFindLSB_MSB = 6,
  239. SubgroupAll_Any_AllEqualBool = 7,
  240. SubgroupAllEqualT = 8,
  241. SubgroupElect = 9,
  242. SubgroupBarrier = 10,
  243. SubgroupMemBarrier = 11,
  244. SubgroupBallot = 12,
  245. SubgroupInverseBallot_InclBitCount_ExclBitCout = 13,
  246. SubgroupBallotBitExtract = 14,
  247. SubgroupBallotBitCount = 15,
  248. FeatureCount
  249. };
  250. using FeatureMask = uint32_t;
  251. static_assert(sizeof(FeatureMask) * 8u >= FeatureCount, "Mask type needs more bits.");
  252. using CandidateVector = SmallVector<Candidate, CandidateCount>;
  253. using FeatureVector = SmallVector<Feature>;
  254. static FeatureVector get_feature_dependencies(Feature feature);
  255. static FeatureMask get_feature_dependency_mask(Feature feature);
  256. static bool can_feature_be_implemented_without_extensions(Feature feature);
  257. static Candidate get_KHR_extension_for_feature(Feature feature);
  258. struct Result
  259. {
  260. Result();
  261. uint32_t weights[CandidateCount];
  262. };
  263. void request_feature(Feature feature);
  264. bool is_feature_requested(Feature feature) const;
  265. Result resolve() const;
  266. static CandidateVector get_candidates_for_feature(Feature ft, const Result &r);
  267. private:
  268. static CandidateVector get_candidates_for_feature(Feature ft);
  269. static FeatureMask build_mask(const SmallVector<Feature> &features);
  270. FeatureMask feature_mask = 0;
  271. };
  272. // TODO remove this function when all subgroup ops are supported (or make it always return true)
  273. static bool is_supported_subgroup_op_in_opengl(spv::Op op);
  274. void reset();
  275. void emit_function(SPIRFunction &func, const Bitset &return_flags);
  276. bool has_extension(const std::string &ext) const;
  277. void require_extension_internal(const std::string &ext);
  278. // Virtualize methods which need to be overridden by subclass targets like C++ and such.
  279. virtual void emit_function_prototype(SPIRFunction &func, const Bitset &return_flags);
  280. SPIRBlock *current_emitting_block = nullptr;
  281. SPIRBlock *current_emitting_switch = nullptr;
  282. bool current_emitting_switch_fallthrough = false;
  283. virtual void emit_instruction(const Instruction &instr);
  284. void emit_block_instructions(SPIRBlock &block);
  285. virtual void emit_glsl_op(uint32_t result_type, uint32_t result_id, uint32_t op, const uint32_t *args,
  286. uint32_t count);
  287. virtual void emit_spv_amd_shader_ballot_op(uint32_t result_type, uint32_t result_id, uint32_t op,
  288. const uint32_t *args, uint32_t count);
  289. virtual void emit_spv_amd_shader_explicit_vertex_parameter_op(uint32_t result_type, uint32_t result_id, uint32_t op,
  290. const uint32_t *args, uint32_t count);
  291. virtual void emit_spv_amd_shader_trinary_minmax_op(uint32_t result_type, uint32_t result_id, uint32_t op,
  292. const uint32_t *args, uint32_t count);
  293. virtual void emit_spv_amd_gcn_shader_op(uint32_t result_type, uint32_t result_id, uint32_t op, const uint32_t *args,
  294. uint32_t count);
  295. virtual void emit_header();
  296. void emit_line_directive(uint32_t file_id, uint32_t line_literal);
  297. void build_workgroup_size(SmallVector<std::string> &arguments, const SpecializationConstant &x,
  298. const SpecializationConstant &y, const SpecializationConstant &z);
  299. void request_subgroup_feature(ShaderSubgroupSupportHelper::Feature feature);
  300. virtual void emit_sampled_image_op(uint32_t result_type, uint32_t result_id, uint32_t image_id, uint32_t samp_id);
  301. virtual void emit_texture_op(const Instruction &i, bool sparse);
  302. virtual std::string to_texture_op(const Instruction &i, bool sparse, bool *forward,
  303. SmallVector<uint32_t> &inherited_expressions);
  304. virtual void emit_subgroup_op(const Instruction &i);
  305. virtual std::string type_to_glsl(const SPIRType &type, uint32_t id = 0);
  306. virtual std::string builtin_to_glsl(spv::BuiltIn builtin, spv::StorageClass storage);
  307. virtual void emit_struct_member(const SPIRType &type, uint32_t member_type_id, uint32_t index,
  308. const std::string &qualifier = "", uint32_t base_offset = 0);
  309. virtual void emit_struct_padding_target(const SPIRType &type);
  310. virtual std::string image_type_glsl(const SPIRType &type, uint32_t id = 0);
  311. std::string constant_expression(const SPIRConstant &c);
  312. std::string constant_op_expression(const SPIRConstantOp &cop);
  313. virtual std::string constant_expression_vector(const SPIRConstant &c, uint32_t vector);
  314. virtual void emit_fixup();
  315. virtual std::string variable_decl(const SPIRType &type, const std::string &name, uint32_t id = 0);
  316. virtual std::string to_func_call_arg(const SPIRFunction::Parameter &arg, uint32_t id);
  317. struct TextureFunctionBaseArguments
  318. {
  319. // GCC 4.8 workarounds, it doesn't understand '{}' constructor here, use explicit default constructor.
  320. TextureFunctionBaseArguments() = default;
  321. VariableID img = 0;
  322. const SPIRType *imgtype = nullptr;
  323. bool is_fetch = false, is_gather = false, is_proj = false;
  324. };
  325. struct TextureFunctionNameArguments
  326. {
  327. // GCC 4.8 workarounds, it doesn't understand '{}' constructor here, use explicit default constructor.
  328. TextureFunctionNameArguments() = default;
  329. TextureFunctionBaseArguments base;
  330. bool has_array_offsets = false, has_offset = false, has_grad = false;
  331. bool has_dref = false, is_sparse_feedback = false, has_min_lod = false;
  332. uint32_t lod = 0;
  333. };
  334. virtual std::string to_function_name(const TextureFunctionNameArguments &args);
  335. struct TextureFunctionArguments
  336. {
  337. // GCC 4.8 workarounds, it doesn't understand '{}' constructor here, use explicit default constructor.
  338. TextureFunctionArguments() = default;
  339. TextureFunctionBaseArguments base;
  340. uint32_t coord = 0, coord_components = 0, dref = 0;
  341. uint32_t grad_x = 0, grad_y = 0, lod = 0, coffset = 0, offset = 0;
  342. uint32_t bias = 0, component = 0, sample = 0, sparse_texel = 0, min_lod = 0;
  343. bool nonuniform_expression = false;
  344. };
  345. virtual std::string to_function_args(const TextureFunctionArguments &args, bool *p_forward);
  346. void emit_sparse_feedback_temporaries(uint32_t result_type_id, uint32_t id, uint32_t &feedback_id,
  347. uint32_t &texel_id);
  348. uint32_t get_sparse_feedback_texel_id(uint32_t id) const;
  349. virtual void emit_buffer_block(const SPIRVariable &type);
  350. virtual void emit_push_constant_block(const SPIRVariable &var);
  351. virtual void emit_uniform(const SPIRVariable &var);
  352. virtual std::string unpack_expression_type(std::string expr_str, const SPIRType &type, uint32_t physical_type_id,
  353. bool packed_type, bool row_major);
  354. virtual bool builtin_translates_to_nonarray(spv::BuiltIn builtin) const;
  355. void emit_copy_logical_type(uint32_t lhs_id, uint32_t lhs_type_id, uint32_t rhs_id, uint32_t rhs_type_id,
  356. SmallVector<uint32_t> chain);
  357. StringStream<> buffer;
  358. template <typename T>
  359. inline void statement_inner(T &&t)
  360. {
  361. buffer << std::forward<T>(t);
  362. statement_count++;
  363. }
  364. template <typename T, typename... Ts>
  365. inline void statement_inner(T &&t, Ts &&... ts)
  366. {
  367. buffer << std::forward<T>(t);
  368. statement_count++;
  369. statement_inner(std::forward<Ts>(ts)...);
  370. }
  371. template <typename... Ts>
  372. inline void statement(Ts &&... ts)
  373. {
  374. if (is_forcing_recompilation())
  375. {
  376. // Do not bother emitting code while force_recompile is active.
  377. // We will compile again.
  378. statement_count++;
  379. return;
  380. }
  381. if (redirect_statement)
  382. {
  383. redirect_statement->push_back(join(std::forward<Ts>(ts)...));
  384. statement_count++;
  385. }
  386. else
  387. {
  388. for (uint32_t i = 0; i < indent; i++)
  389. buffer << " ";
  390. statement_inner(std::forward<Ts>(ts)...);
  391. buffer << '\n';
  392. }
  393. }
  394. template <typename... Ts>
  395. inline void statement_no_indent(Ts &&... ts)
  396. {
  397. auto old_indent = indent;
  398. indent = 0;
  399. statement(std::forward<Ts>(ts)...);
  400. indent = old_indent;
  401. }
  402. // Used for implementing continue blocks where
  403. // we want to obtain a list of statements we can merge
  404. // on a single line separated by comma.
  405. SmallVector<std::string> *redirect_statement = nullptr;
  406. const SPIRBlock *current_continue_block = nullptr;
  407. void begin_scope();
  408. void end_scope();
  409. void end_scope(const std::string &trailer);
  410. void end_scope_decl();
  411. void end_scope_decl(const std::string &decl);
  412. Options options;
  413. virtual std::string type_to_array_glsl(
  414. const SPIRType &type); // Allow Metal to use the array<T> template to make arrays a value type
  415. std::string to_array_size(const SPIRType &type, uint32_t index);
  416. uint32_t to_array_size_literal(const SPIRType &type, uint32_t index) const;
  417. uint32_t to_array_size_literal(const SPIRType &type) const;
  418. virtual std::string variable_decl(const SPIRVariable &variable); // Threadgroup arrays can't have a wrapper type
  419. std::string variable_decl_function_local(SPIRVariable &variable);
  420. void add_local_variable_name(uint32_t id);
  421. void add_resource_name(uint32_t id);
  422. void add_member_name(SPIRType &type, uint32_t name);
  423. void add_function_overload(const SPIRFunction &func);
  424. virtual bool is_non_native_row_major_matrix(uint32_t id);
  425. virtual bool member_is_non_native_row_major_matrix(const SPIRType &type, uint32_t index);
  426. bool member_is_remapped_physical_type(const SPIRType &type, uint32_t index) const;
  427. bool member_is_packed_physical_type(const SPIRType &type, uint32_t index) const;
  428. virtual std::string convert_row_major_matrix(std::string exp_str, const SPIRType &exp_type,
  429. uint32_t physical_type_id, bool is_packed);
  430. std::unordered_set<std::string> local_variable_names;
  431. std::unordered_set<std::string> resource_names;
  432. std::unordered_set<std::string> block_input_names;
  433. std::unordered_set<std::string> block_output_names;
  434. std::unordered_set<std::string> block_ubo_names;
  435. std::unordered_set<std::string> block_ssbo_names;
  436. std::unordered_set<std::string> block_names; // A union of all block_*_names.
  437. std::unordered_map<std::string, std::unordered_set<uint64_t>> function_overloads;
  438. std::unordered_map<uint32_t, std::string> preserved_aliases;
  439. void preserve_alias_on_reset(uint32_t id);
  440. void reset_name_caches();
  441. bool processing_entry_point = false;
  442. // Can be overriden by subclass backends for trivial things which
  443. // shouldn't need polymorphism.
  444. struct BackendVariations
  445. {
  446. std::string discard_literal = "discard";
  447. std::string demote_literal = "demote";
  448. std::string null_pointer_literal = "";
  449. bool float_literal_suffix = false;
  450. bool double_literal_suffix = true;
  451. bool uint32_t_literal_suffix = true;
  452. bool long_long_literal_suffix = false;
  453. const char *basic_int_type = "int";
  454. const char *basic_uint_type = "uint";
  455. const char *basic_int8_type = "int8_t";
  456. const char *basic_uint8_type = "uint8_t";
  457. const char *basic_int16_type = "int16_t";
  458. const char *basic_uint16_type = "uint16_t";
  459. const char *int16_t_literal_suffix = "s";
  460. const char *uint16_t_literal_suffix = "us";
  461. const char *nonuniform_qualifier = "nonuniformEXT";
  462. const char *boolean_mix_function = "mix";
  463. bool swizzle_is_function = false;
  464. bool shared_is_implied = false;
  465. bool unsized_array_supported = true;
  466. bool explicit_struct_type = false;
  467. bool use_initializer_list = false;
  468. bool use_typed_initializer_list = false;
  469. bool can_declare_struct_inline = true;
  470. bool can_declare_arrays_inline = true;
  471. bool native_row_major_matrix = true;
  472. bool use_constructor_splatting = true;
  473. bool allow_precision_qualifiers = false;
  474. bool can_swizzle_scalar = false;
  475. bool force_gl_in_out_block = false;
  476. bool can_return_array = true;
  477. bool allow_truncated_access_chain = false;
  478. bool supports_extensions = false;
  479. bool supports_empty_struct = false;
  480. bool array_is_value_type = true;
  481. bool buffer_offset_array_is_value_type = true;
  482. bool comparison_image_samples_scalar = false;
  483. bool native_pointers = false;
  484. bool support_small_type_sampling_result = false;
  485. bool support_case_fallthrough = true;
  486. bool use_array_constructor = false;
  487. bool needs_row_major_load_workaround = false;
  488. } backend;
  489. void emit_struct(SPIRType &type);
  490. void emit_resources();
  491. void emit_extension_workarounds(spv::ExecutionModel model);
  492. void emit_buffer_block_native(const SPIRVariable &var);
  493. void emit_buffer_reference_block(SPIRType &type, bool forward_declaration);
  494. void emit_buffer_block_legacy(const SPIRVariable &var);
  495. void emit_buffer_block_flattened(const SPIRVariable &type);
  496. void fixup_implicit_builtin_block_names();
  497. void emit_declared_builtin_block(spv::StorageClass storage, spv::ExecutionModel model);
  498. bool should_force_emit_builtin_block(spv::StorageClass storage);
  499. void emit_push_constant_block_vulkan(const SPIRVariable &var);
  500. void emit_push_constant_block_glsl(const SPIRVariable &var);
  501. void emit_interface_block(const SPIRVariable &type);
  502. void emit_flattened_io_block(const SPIRVariable &var, const char *qual);
  503. void emit_flattened_io_block_struct(const std::string &basename, const SPIRType &type, const char *qual,
  504. const SmallVector<uint32_t> &indices);
  505. void emit_flattened_io_block_member(const std::string &basename, const SPIRType &type, const char *qual,
  506. const SmallVector<uint32_t> &indices);
  507. void emit_block_chain(SPIRBlock &block);
  508. void emit_hoisted_temporaries(SmallVector<std::pair<TypeID, ID>> &temporaries);
  509. std::string constant_value_macro_name(uint32_t id);
  510. void emit_constant(const SPIRConstant &constant);
  511. void emit_specialization_constant_op(const SPIRConstantOp &constant);
  512. std::string emit_continue_block(uint32_t continue_block, bool follow_true_block, bool follow_false_block);
  513. bool attempt_emit_loop_header(SPIRBlock &block, SPIRBlock::Method method);
  514. void branch(BlockID from, BlockID to);
  515. void branch_to_continue(BlockID from, BlockID to);
  516. void branch(BlockID from, uint32_t cond, BlockID true_block, BlockID false_block);
  517. void flush_phi(BlockID from, BlockID to);
  518. void flush_variable_declaration(uint32_t id);
  519. void flush_undeclared_variables(SPIRBlock &block);
  520. void emit_variable_temporary_copies(const SPIRVariable &var);
  521. bool should_dereference(uint32_t id);
  522. bool should_forward(uint32_t id) const;
  523. bool should_suppress_usage_tracking(uint32_t id) const;
  524. void emit_mix_op(uint32_t result_type, uint32_t id, uint32_t left, uint32_t right, uint32_t lerp);
  525. void emit_nminmax_op(uint32_t result_type, uint32_t id, uint32_t op0, uint32_t op1, GLSLstd450 op);
  526. bool to_trivial_mix_op(const SPIRType &type, std::string &op, uint32_t left, uint32_t right, uint32_t lerp);
  527. void emit_quaternary_func_op(uint32_t result_type, uint32_t result_id, uint32_t op0, uint32_t op1, uint32_t op2,
  528. uint32_t op3, const char *op);
  529. void emit_trinary_func_op(uint32_t result_type, uint32_t result_id, uint32_t op0, uint32_t op1, uint32_t op2,
  530. const char *op);
  531. void emit_binary_func_op(uint32_t result_type, uint32_t result_id, uint32_t op0, uint32_t op1, const char *op);
  532. void emit_unary_func_op_cast(uint32_t result_type, uint32_t result_id, uint32_t op0, const char *op,
  533. SPIRType::BaseType input_type, SPIRType::BaseType expected_result_type);
  534. void emit_binary_func_op_cast(uint32_t result_type, uint32_t result_id, uint32_t op0, uint32_t op1, const char *op,
  535. SPIRType::BaseType input_type, bool skip_cast_if_equal_type);
  536. void emit_binary_func_op_cast_clustered(uint32_t result_type, uint32_t result_id, uint32_t op0, uint32_t op1,
  537. const char *op, SPIRType::BaseType input_type);
  538. void emit_trinary_func_op_cast(uint32_t result_type, uint32_t result_id, uint32_t op0, uint32_t op1, uint32_t op2,
  539. const char *op, SPIRType::BaseType input_type);
  540. void emit_trinary_func_op_bitextract(uint32_t result_type, uint32_t result_id, uint32_t op0, uint32_t op1,
  541. uint32_t op2, const char *op, SPIRType::BaseType expected_result_type,
  542. SPIRType::BaseType input_type0, SPIRType::BaseType input_type1,
  543. SPIRType::BaseType input_type2);
  544. void emit_bitfield_insert_op(uint32_t result_type, uint32_t result_id, uint32_t op0, uint32_t op1, uint32_t op2,
  545. uint32_t op3, const char *op, SPIRType::BaseType offset_count_type);
  546. void emit_unary_func_op(uint32_t result_type, uint32_t result_id, uint32_t op0, const char *op);
  547. void emit_unrolled_unary_op(uint32_t result_type, uint32_t result_id, uint32_t operand, const char *op);
  548. void emit_binary_op(uint32_t result_type, uint32_t result_id, uint32_t op0, uint32_t op1, const char *op);
  549. void emit_unrolled_binary_op(uint32_t result_type, uint32_t result_id, uint32_t op0, uint32_t op1, const char *op,
  550. bool negate, SPIRType::BaseType expected_type);
  551. void emit_binary_op_cast(uint32_t result_type, uint32_t result_id, uint32_t op0, uint32_t op1, const char *op,
  552. SPIRType::BaseType input_type, bool skip_cast_if_equal_type);
  553. SPIRType binary_op_bitcast_helper(std::string &cast_op0, std::string &cast_op1, SPIRType::BaseType &input_type,
  554. uint32_t op0, uint32_t op1, bool skip_cast_if_equal_type);
  555. virtual bool emit_complex_bitcast(uint32_t result_type, uint32_t id, uint32_t op0);
  556. std::string to_ternary_expression(const SPIRType &result_type, uint32_t select, uint32_t true_value,
  557. uint32_t false_value);
  558. void emit_unary_op(uint32_t result_type, uint32_t result_id, uint32_t op0, const char *op);
  559. bool expression_is_forwarded(uint32_t id) const;
  560. bool expression_suppresses_usage_tracking(uint32_t id) const;
  561. bool expression_read_implies_multiple_reads(uint32_t id) const;
  562. SPIRExpression &emit_op(uint32_t result_type, uint32_t result_id, const std::string &rhs, bool forward_rhs,
  563. bool suppress_usage_tracking = false);
  564. void access_chain_internal_append_index(std::string &expr, uint32_t base, const SPIRType *type,
  565. AccessChainFlags flags, bool &access_chain_is_arrayed, uint32_t index);
  566. std::string access_chain_internal(uint32_t base, const uint32_t *indices, uint32_t count, AccessChainFlags flags,
  567. AccessChainMeta *meta);
  568. virtual void prepare_access_chain_for_scalar_access(std::string &expr, const SPIRType &type,
  569. spv::StorageClass storage, bool &is_packed);
  570. std::string access_chain(uint32_t base, const uint32_t *indices, uint32_t count, const SPIRType &target_type,
  571. AccessChainMeta *meta = nullptr, bool ptr_chain = false);
  572. std::string flattened_access_chain(uint32_t base, const uint32_t *indices, uint32_t count,
  573. const SPIRType &target_type, uint32_t offset, uint32_t matrix_stride,
  574. uint32_t array_stride, bool need_transpose);
  575. std::string flattened_access_chain_struct(uint32_t base, const uint32_t *indices, uint32_t count,
  576. const SPIRType &target_type, uint32_t offset);
  577. std::string flattened_access_chain_matrix(uint32_t base, const uint32_t *indices, uint32_t count,
  578. const SPIRType &target_type, uint32_t offset, uint32_t matrix_stride,
  579. bool need_transpose);
  580. std::string flattened_access_chain_vector(uint32_t base, const uint32_t *indices, uint32_t count,
  581. const SPIRType &target_type, uint32_t offset, uint32_t matrix_stride,
  582. bool need_transpose);
  583. std::pair<std::string, uint32_t> flattened_access_chain_offset(const SPIRType &basetype, const uint32_t *indices,
  584. uint32_t count, uint32_t offset,
  585. uint32_t word_stride, bool *need_transpose = nullptr,
  586. uint32_t *matrix_stride = nullptr,
  587. uint32_t *array_stride = nullptr,
  588. bool ptr_chain = false);
  589. const char *index_to_swizzle(uint32_t index);
  590. std::string remap_swizzle(const SPIRType &result_type, uint32_t input_components, const std::string &expr);
  591. std::string declare_temporary(uint32_t type, uint32_t id);
  592. void emit_uninitialized_temporary(uint32_t type, uint32_t id);
  593. SPIRExpression &emit_uninitialized_temporary_expression(uint32_t type, uint32_t id);
  594. void append_global_func_args(const SPIRFunction &func, uint32_t index, SmallVector<std::string> &arglist);
  595. std::string to_expression(uint32_t id, bool register_expression_read = true);
  596. std::string to_composite_constructor_expression(uint32_t id, bool uses_buffer_offset);
  597. std::string to_rerolled_array_expression(const std::string &expr, const SPIRType &type);
  598. std::string to_enclosed_expression(uint32_t id, bool register_expression_read = true);
  599. std::string to_unpacked_expression(uint32_t id, bool register_expression_read = true);
  600. std::string to_unpacked_row_major_matrix_expression(uint32_t id);
  601. std::string to_enclosed_unpacked_expression(uint32_t id, bool register_expression_read = true);
  602. std::string to_dereferenced_expression(uint32_t id, bool register_expression_read = true);
  603. std::string to_pointer_expression(uint32_t id, bool register_expression_read = true);
  604. std::string to_enclosed_pointer_expression(uint32_t id, bool register_expression_read = true);
  605. std::string to_extract_component_expression(uint32_t id, uint32_t index);
  606. std::string to_extract_constant_composite_expression(uint32_t result_type, const SPIRConstant &c,
  607. const uint32_t *chain, uint32_t length);
  608. std::string enclose_expression(const std::string &expr);
  609. std::string dereference_expression(const SPIRType &expression_type, const std::string &expr);
  610. std::string address_of_expression(const std::string &expr);
  611. void strip_enclosed_expression(std::string &expr);
  612. std::string to_member_name(const SPIRType &type, uint32_t index);
  613. virtual std::string to_member_reference(uint32_t base, const SPIRType &type, uint32_t index, bool ptr_chain);
  614. std::string to_multi_member_reference(const SPIRType &type, const SmallVector<uint32_t> &indices);
  615. std::string type_to_glsl_constructor(const SPIRType &type);
  616. std::string argument_decl(const SPIRFunction::Parameter &arg);
  617. virtual std::string to_qualifiers_glsl(uint32_t id);
  618. void fixup_io_block_patch_qualifiers(const SPIRVariable &var);
  619. void emit_output_variable_initializer(const SPIRVariable &var);
  620. const char *to_precision_qualifiers_glsl(uint32_t id);
  621. virtual const char *to_storage_qualifiers_glsl(const SPIRVariable &var);
  622. const char *flags_to_qualifiers_glsl(const SPIRType &type, const Bitset &flags);
  623. const char *format_to_glsl(spv::ImageFormat format);
  624. virtual std::string layout_for_member(const SPIRType &type, uint32_t index);
  625. virtual std::string to_interpolation_qualifiers(const Bitset &flags);
  626. std::string layout_for_variable(const SPIRVariable &variable);
  627. std::string to_combined_image_sampler(VariableID image_id, VariableID samp_id);
  628. virtual bool skip_argument(uint32_t id) const;
  629. virtual void emit_array_copy(const std::string &lhs, uint32_t rhs_id, spv::StorageClass lhs_storage,
  630. spv::StorageClass rhs_storage);
  631. virtual void emit_block_hints(const SPIRBlock &block);
  632. virtual std::string to_initializer_expression(const SPIRVariable &var);
  633. virtual std::string to_zero_initialized_expression(uint32_t type_id);
  634. bool type_can_zero_initialize(const SPIRType &type) const;
  635. bool buffer_is_packing_standard(const SPIRType &type, BufferPackingStandard packing,
  636. uint32_t *failed_index = nullptr, uint32_t start_offset = 0,
  637. uint32_t end_offset = ~(0u));
  638. std::string buffer_to_packing_standard(const SPIRType &type, bool support_std430_without_scalar_layout);
  639. uint32_t type_to_packed_base_size(const SPIRType &type, BufferPackingStandard packing);
  640. uint32_t type_to_packed_alignment(const SPIRType &type, const Bitset &flags, BufferPackingStandard packing);
  641. uint32_t type_to_packed_array_stride(const SPIRType &type, const Bitset &flags, BufferPackingStandard packing);
  642. uint32_t type_to_packed_size(const SPIRType &type, const Bitset &flags, BufferPackingStandard packing);
  643. std::string bitcast_glsl(const SPIRType &result_type, uint32_t arg);
  644. virtual std::string bitcast_glsl_op(const SPIRType &result_type, const SPIRType &argument_type);
  645. std::string bitcast_expression(SPIRType::BaseType target_type, uint32_t arg);
  646. std::string bitcast_expression(const SPIRType &target_type, SPIRType::BaseType expr_type, const std::string &expr);
  647. std::string build_composite_combiner(uint32_t result_type, const uint32_t *elems, uint32_t length);
  648. bool remove_duplicate_swizzle(std::string &op);
  649. bool remove_unity_swizzle(uint32_t base, std::string &op);
  650. // Can modify flags to remote readonly/writeonly if image type
  651. // and force recompile.
  652. bool check_atomic_image(uint32_t id);
  653. virtual void replace_illegal_names();
  654. void replace_illegal_names(const std::unordered_set<std::string> &keywords);
  655. virtual void emit_entry_point_declarations();
  656. void replace_fragment_output(SPIRVariable &var);
  657. void replace_fragment_outputs();
  658. std::string legacy_tex_op(const std::string &op, const SPIRType &imgtype, uint32_t id);
  659. uint32_t indent = 0;
  660. std::unordered_set<uint32_t> emitted_functions;
  661. // Ensure that we declare phi-variable copies even if the original declaration isn't deferred
  662. std::unordered_set<uint32_t> flushed_phi_variables;
  663. std::unordered_set<uint32_t> flattened_buffer_blocks;
  664. std::unordered_map<uint32_t, bool> flattened_structs;
  665. ShaderSubgroupSupportHelper shader_subgroup_supporter;
  666. std::string load_flattened_struct(const std::string &basename, const SPIRType &type);
  667. std::string to_flattened_struct_member(const std::string &basename, const SPIRType &type, uint32_t index);
  668. void store_flattened_struct(uint32_t lhs_id, uint32_t value);
  669. void store_flattened_struct(const std::string &basename, uint32_t rhs, const SPIRType &type,
  670. const SmallVector<uint32_t> &indices);
  671. std::string to_flattened_access_chain_expression(uint32_t id);
  672. // Usage tracking. If a temporary is used more than once, use the temporary instead to
  673. // avoid AST explosion when SPIRV is generated with pure SSA and doesn't write stuff to variables.
  674. std::unordered_map<uint32_t, uint32_t> expression_usage_counts;
  675. void track_expression_read(uint32_t id);
  676. SmallVector<std::string> forced_extensions;
  677. SmallVector<std::string> header_lines;
  678. // Used when expressions emit extra opcodes with their own unique IDs,
  679. // and we need to reuse the IDs across recompilation loops.
  680. // Currently used by NMin/Max/Clamp implementations.
  681. std::unordered_map<uint32_t, uint32_t> extra_sub_expressions;
  682. SmallVector<TypeID> workaround_ubo_load_overload_types;
  683. void request_workaround_wrapper_overload(TypeID id);
  684. void rewrite_load_for_wrapped_row_major(std::string &expr, TypeID loaded_type, ID ptr);
  685. uint32_t statement_count = 0;
  686. inline bool is_legacy() const
  687. {
  688. return (options.es && options.version < 300) || (!options.es && options.version < 130);
  689. }
  690. inline bool is_legacy_es() const
  691. {
  692. return options.es && options.version < 300;
  693. }
  694. inline bool is_legacy_desktop() const
  695. {
  696. return !options.es && options.version < 130;
  697. }
  698. bool requires_transpose_2x2 = false;
  699. bool requires_transpose_3x3 = false;
  700. bool requires_transpose_4x4 = false;
  701. bool ray_tracing_is_khr = false;
  702. void ray_tracing_khr_fixup_locations();
  703. bool args_will_forward(uint32_t id, const uint32_t *args, uint32_t num_args, bool pure);
  704. void register_call_out_argument(uint32_t id);
  705. void register_impure_function_call();
  706. void register_control_dependent_expression(uint32_t expr);
  707. // GL_EXT_shader_pixel_local_storage support.
  708. std::vector<PlsRemap> pls_inputs;
  709. std::vector<PlsRemap> pls_outputs;
  710. std::string pls_decl(const PlsRemap &variable);
  711. const char *to_pls_qualifiers_glsl(const SPIRVariable &variable);
  712. void emit_pls();
  713. void remap_pls_variables();
  714. // GL_EXT_shader_framebuffer_fetch support.
  715. std::vector<std::pair<uint32_t, uint32_t>> subpass_to_framebuffer_fetch_attachment;
  716. std::unordered_set<uint32_t> inout_color_attachments;
  717. bool subpass_input_is_framebuffer_fetch(uint32_t id) const;
  718. void emit_inout_fragment_outputs_copy_to_subpass_inputs();
  719. const SPIRVariable *find_subpass_input_by_attachment_index(uint32_t index) const;
  720. const SPIRVariable *find_color_output_by_location(uint32_t location) const;
  721. // A variant which takes two sets of name. The secondary is only used to verify there are no collisions,
  722. // but the set is not updated when we have found a new name.
  723. // Used primarily when adding block interface names.
  724. void add_variable(std::unordered_set<std::string> &variables_primary,
  725. const std::unordered_set<std::string> &variables_secondary, std::string &name);
  726. void check_function_call_constraints(const uint32_t *args, uint32_t length);
  727. void handle_invalid_expression(uint32_t id);
  728. void find_static_extensions();
  729. std::string emit_for_loop_initializers(const SPIRBlock &block);
  730. void emit_while_loop_initializers(const SPIRBlock &block);
  731. bool for_loop_initializers_are_same_type(const SPIRBlock &block);
  732. bool optimize_read_modify_write(const SPIRType &type, const std::string &lhs, const std::string &rhs);
  733. void fixup_image_load_store_access();
  734. bool type_is_empty(const SPIRType &type);
  735. virtual void declare_undefined_values();
  736. bool can_use_io_location(spv::StorageClass storage, bool block);
  737. const Instruction *get_next_instruction_in_block(const Instruction &instr);
  738. static uint32_t mask_relevant_memory_semantics(uint32_t semantics);
  739. std::string convert_half_to_string(const SPIRConstant &value, uint32_t col, uint32_t row);
  740. std::string convert_float_to_string(const SPIRConstant &value, uint32_t col, uint32_t row);
  741. std::string convert_double_to_string(const SPIRConstant &value, uint32_t col, uint32_t row);
  742. std::string convert_separate_image_to_expression(uint32_t id);
  743. // Builtins in GLSL are always specific signedness, but the SPIR-V can declare them
  744. // as either unsigned or signed.
  745. // Sometimes we will need to automatically perform casts on load and store to make this work.
  746. virtual void cast_to_builtin_store(uint32_t target_id, std::string &expr, const SPIRType &expr_type);
  747. virtual void cast_from_builtin_load(uint32_t source_id, std::string &expr, const SPIRType &expr_type);
  748. void unroll_array_from_complex_load(uint32_t target_id, uint32_t source_id, std::string &expr);
  749. void convert_non_uniform_expression(const SPIRType &type, std::string &expr);
  750. void handle_store_to_invariant_variable(uint32_t store_id, uint32_t value_id);
  751. void disallow_forwarding_in_expression_chain(const SPIRExpression &expr);
  752. bool expression_is_constant_null(uint32_t id) const;
  753. bool expression_is_non_value_type_array(uint32_t ptr);
  754. virtual void emit_store_statement(uint32_t lhs_expression, uint32_t rhs_expression);
  755. uint32_t get_integer_width_for_instruction(const Instruction &instr) const;
  756. uint32_t get_integer_width_for_glsl_instruction(GLSLstd450 op, const uint32_t *arguments, uint32_t length) const;
  757. bool variable_is_lut(const SPIRVariable &var) const;
  758. char current_locale_radix_character = '.';
  759. void fixup_type_alias();
  760. void reorder_type_alias();
  761. void propagate_nonuniform_qualifier(uint32_t id);
  762. static const char *vector_swizzle(int vecsize, int index);
  763. private:
  764. void init();
  765. };
  766. } // namespace SPIRV_CROSS_NAMESPACE
  767. #endif