spirv_glsl.hpp 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084
  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. #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. ACCESS_CHAIN_FORCE_COMPOSITE_BIT = 1 << 6,
  61. ACCESS_CHAIN_PTR_CHAIN_POINTER_ARITH_BIT = 1 << 7,
  62. ACCESS_CHAIN_PTR_CHAIN_CAST_TO_SCALAR_BIT = 1 << 8
  63. };
  64. typedef uint32_t AccessChainFlags;
  65. class CompilerGLSL : public Compiler
  66. {
  67. public:
  68. struct Options
  69. {
  70. // The shading language version. Corresponds to #version $VALUE.
  71. uint32_t version = 450;
  72. // Emit the OpenGL ES shading language instead of desktop OpenGL.
  73. bool es = false;
  74. // Debug option to always emit temporary variables for all expressions.
  75. bool force_temporary = false;
  76. // Debug option, can be increased in an attempt to workaround SPIRV-Cross bugs temporarily.
  77. // If this limit has to be increased, it points to an implementation bug.
  78. // In certain scenarios, the maximum number of debug iterations may increase beyond this limit
  79. // as long as we can prove we're making certain kinds of forward progress.
  80. uint32_t force_recompile_max_debug_iterations = 3;
  81. // If true, Vulkan GLSL features are used instead of GL-compatible features.
  82. // Mostly useful for debugging SPIR-V files.
  83. bool vulkan_semantics = false;
  84. // If true, gl_PerVertex is explicitly redeclared in vertex, geometry and tessellation shaders.
  85. // The members of gl_PerVertex is determined by which built-ins are declared by the shader.
  86. // This option is ignored in ES versions, as redeclaration in ES is not required, and it depends on a different extension
  87. // (EXT_shader_io_blocks) which makes things a bit more fuzzy.
  88. bool separate_shader_objects = false;
  89. // Flattens multidimensional arrays, e.g. float foo[a][b][c] into single-dimensional arrays,
  90. // e.g. float foo[a * b * c].
  91. // This function does not change the actual SPIRType of any object.
  92. // Only the generated code, including declarations of interface variables are changed to be single array dimension.
  93. bool flatten_multidimensional_arrays = false;
  94. // For older desktop GLSL targets than version 420, the
  95. // GL_ARB_shading_language_420pack extensions is used to be able to support
  96. // layout(binding) on UBOs and samplers.
  97. // If disabled on older targets, binding decorations will be stripped.
  98. bool enable_420pack_extension = true;
  99. // In non-Vulkan GLSL, emit push constant blocks as UBOs rather than plain uniforms.
  100. bool emit_push_constant_as_uniform_buffer = false;
  101. // Always emit uniform blocks as plain uniforms, regardless of the GLSL version, even when UBOs are supported.
  102. // Does not apply to shader storage or push constant blocks.
  103. bool emit_uniform_buffer_as_plain_uniforms = false;
  104. // Emit OpLine directives if present in the module.
  105. // May not correspond exactly to original source, but should be a good approximation.
  106. bool emit_line_directives = false;
  107. // In cases where readonly/writeonly decoration are not used at all,
  108. // we try to deduce which qualifier(s) we should actually used, since actually emitting
  109. // read-write decoration is very rare, and older glslang/HLSL compilers tend to just emit readwrite as a matter of fact.
  110. // The default (true) is to enable automatic deduction for these cases, but if you trust the decorations set
  111. // by the SPIR-V, it's recommended to set this to false.
  112. bool enable_storage_image_qualifier_deduction = true;
  113. // On some targets (WebGPU), uninitialized variables are banned.
  114. // If this is enabled, all variables (temporaries, Private, Function)
  115. // which would otherwise be uninitialized will now be initialized to 0 instead.
  116. bool force_zero_initialized_variables = false;
  117. // In GLSL, force use of I/O block flattening, similar to
  118. // what happens on legacy GLSL targets for blocks and structs.
  119. bool force_flattened_io_blocks = false;
  120. // For opcodes where we have to perform explicit additional nan checks, very ugly code is generated.
  121. // If we opt-in, ignore these requirements.
  122. // In opcodes like NClamp/NMin/NMax and FP compare, ignore NaN behavior.
  123. // Use FClamp/FMin/FMax semantics for clamps and lets implementation choose ordered or unordered
  124. // compares.
  125. bool relax_nan_checks = false;
  126. // Loading row-major matrices from UBOs on older AMD Windows OpenGL drivers is problematic.
  127. // To load these types correctly, we must generate a wrapper. them in a dummy function which only purpose is to
  128. // ensure row_major decoration is actually respected.
  129. // This workaround may cause significant performance degeneration on some Android devices.
  130. bool enable_row_major_load_workaround = true;
  131. // If non-zero, controls layout(num_views = N) in; in GL_OVR_multiview2.
  132. uint32_t ovr_multiview_view_count = 0;
  133. enum Precision
  134. {
  135. DontCare,
  136. Lowp,
  137. Mediump,
  138. Highp
  139. };
  140. struct VertexOptions
  141. {
  142. // "Vertex-like shader" here is any shader stage that can write BuiltInPosition.
  143. // GLSL: In vertex-like shaders, rewrite [0, w] depth (Vulkan/D3D style) to [-w, w] depth (GL style).
  144. // MSL: In vertex-like shaders, rewrite [-w, w] depth (GL style) to [0, w] depth.
  145. // HLSL: In vertex-like shaders, rewrite [-w, w] depth (GL style) to [0, w] depth.
  146. bool fixup_clipspace = false;
  147. // In vertex-like shaders, inverts gl_Position.y or equivalent.
  148. bool flip_vert_y = false;
  149. // GLSL only, for HLSL version of this option, see CompilerHLSL.
  150. // If true, the backend will assume that InstanceIndex will need to apply
  151. // a base instance offset. Set to false if you know you will never use base instance
  152. // functionality as it might remove some internal uniforms.
  153. bool support_nonzero_base_instance = true;
  154. } vertex;
  155. struct FragmentOptions
  156. {
  157. // Add precision mediump float in ES targets when emitting GLES source.
  158. // Add precision highp int in ES targets when emitting GLES source.
  159. Precision default_float_precision = Mediump;
  160. Precision default_int_precision = Highp;
  161. } fragment;
  162. };
  163. void remap_pixel_local_storage(std::vector<PlsRemap> inputs, std::vector<PlsRemap> outputs)
  164. {
  165. pls_inputs = std::move(inputs);
  166. pls_outputs = std::move(outputs);
  167. remap_pls_variables();
  168. }
  169. // Redirect a subpassInput reading from input_attachment_index to instead load its value from
  170. // the color attachment at location = color_location. Requires ESSL.
  171. // If coherent, uses GL_EXT_shader_framebuffer_fetch, if not, uses noncoherent variant.
  172. void remap_ext_framebuffer_fetch(uint32_t input_attachment_index, uint32_t color_location, bool coherent);
  173. explicit CompilerGLSL(std::vector<uint32_t> spirv_)
  174. : Compiler(std::move(spirv_))
  175. {
  176. init();
  177. }
  178. CompilerGLSL(const uint32_t *ir_, size_t word_count)
  179. : Compiler(ir_, word_count)
  180. {
  181. init();
  182. }
  183. explicit CompilerGLSL(const ParsedIR &ir_)
  184. : Compiler(ir_)
  185. {
  186. init();
  187. }
  188. explicit CompilerGLSL(ParsedIR &&ir_)
  189. : Compiler(std::move(ir_))
  190. {
  191. init();
  192. }
  193. const Options &get_common_options() const
  194. {
  195. return options;
  196. }
  197. void set_common_options(const Options &opts)
  198. {
  199. options = opts;
  200. }
  201. std::string compile() override;
  202. // Returns the current string held in the conversion buffer. Useful for
  203. // capturing what has been converted so far when compile() throws an error.
  204. std::string get_partial_source();
  205. // Adds a line to be added right after #version in GLSL backend.
  206. // This is useful for enabling custom extensions which are outside the scope of SPIRV-Cross.
  207. // This can be combined with variable remapping.
  208. // A new-line will be added.
  209. //
  210. // While add_header_line() is a more generic way of adding arbitrary text to the header
  211. // of a GLSL file, require_extension() should be used when adding extensions since it will
  212. // avoid creating collisions with SPIRV-Cross generated extensions.
  213. //
  214. // Code added via add_header_line() is typically backend-specific.
  215. void add_header_line(const std::string &str);
  216. // Adds an extension which is required to run this shader, e.g.
  217. // require_extension("GL_KHR_my_extension");
  218. void require_extension(const std::string &ext);
  219. // Returns the list of required extensions. After compilation this will contains any other
  220. // extensions that the compiler used automatically, in addition to the user specified ones.
  221. const SmallVector<std::string> &get_required_extensions() const;
  222. // Legacy GLSL compatibility method.
  223. // Takes a uniform or push constant variable and flattens it into a (i|u)vec4 array[N]; array instead.
  224. // For this to work, all types in the block must be the same basic type, e.g. mixing vec2 and vec4 is fine, but
  225. // mixing int and float is not.
  226. // The name of the uniform array will be the same as the interface block name.
  227. void flatten_buffer_block(VariableID id);
  228. // After compilation, query if a variable ID was used as a depth resource.
  229. // This is meaningful for MSL since descriptor types depend on this knowledge.
  230. // Cases which return true:
  231. // - Images which are declared with depth = 1 image type.
  232. // - Samplers which are statically used at least once with Dref opcodes.
  233. // - Images which are statically used at least once with Dref opcodes.
  234. bool variable_is_depth_or_compare(VariableID id) const;
  235. // If a shader output is active in this stage, but inactive in a subsequent stage,
  236. // this can be signalled here. This can be used to work around certain cross-stage matching problems
  237. // which plagues MSL and HLSL in certain scenarios.
  238. // An output which matches one of these will not be emitted in stage output interfaces, but rather treated as a private
  239. // variable.
  240. // This option is only meaningful for MSL and HLSL, since GLSL matches by location directly.
  241. // Masking builtins only takes effect if the builtin in question is part of the stage output interface.
  242. void mask_stage_output_by_location(uint32_t location, uint32_t component);
  243. void mask_stage_output_by_builtin(spv::BuiltIn builtin);
  244. // Allow to control how to format float literals in the output.
  245. // Set to "nullptr" to use the default "convert_to_string" function.
  246. // This handle is not owned by SPIRV-Cross and must remain valid until compile() has been called.
  247. void set_float_formatter(FloatFormatter *formatter)
  248. {
  249. float_formatter = formatter;
  250. }
  251. // Returns the macro name corresponding to constant id
  252. std::string constant_value_macro_name(uint32_t id) const;
  253. protected:
  254. struct ShaderSubgroupSupportHelper
  255. {
  256. // lower enum value = greater priority
  257. enum Candidate
  258. {
  259. KHR_shader_subgroup_ballot,
  260. KHR_shader_subgroup_basic,
  261. KHR_shader_subgroup_vote,
  262. KHR_shader_subgroup_arithmetic,
  263. NV_gpu_shader_5,
  264. NV_shader_thread_group,
  265. NV_shader_thread_shuffle,
  266. ARB_shader_ballot,
  267. ARB_shader_group_vote,
  268. AMD_gcn_shader,
  269. CandidateCount
  270. };
  271. static const char *get_extension_name(Candidate c);
  272. static SmallVector<std::string> get_extra_required_extension_names(Candidate c);
  273. static const char *get_extra_required_extension_predicate(Candidate c);
  274. enum Feature
  275. {
  276. SubgroupMask = 0,
  277. SubgroupSize = 1,
  278. SubgroupInvocationID = 2,
  279. SubgroupID = 3,
  280. NumSubgroups = 4,
  281. SubgroupBroadcast_First = 5,
  282. SubgroupBallotFindLSB_MSB = 6,
  283. SubgroupAll_Any_AllEqualBool = 7,
  284. SubgroupAllEqualT = 8,
  285. SubgroupElect = 9,
  286. SubgroupBarrier = 10,
  287. SubgroupMemBarrier = 11,
  288. SubgroupBallot = 12,
  289. SubgroupInverseBallot_InclBitCount_ExclBitCout = 13,
  290. SubgroupBallotBitExtract = 14,
  291. SubgroupBallotBitCount = 15,
  292. SubgroupArithmeticIAddReduce = 16,
  293. SubgroupArithmeticIAddExclusiveScan = 17,
  294. SubgroupArithmeticIAddInclusiveScan = 18,
  295. SubgroupArithmeticFAddReduce = 19,
  296. SubgroupArithmeticFAddExclusiveScan = 20,
  297. SubgroupArithmeticFAddInclusiveScan = 21,
  298. SubgroupArithmeticIMulReduce = 22,
  299. SubgroupArithmeticIMulExclusiveScan = 23,
  300. SubgroupArithmeticIMulInclusiveScan = 24,
  301. SubgroupArithmeticFMulReduce = 25,
  302. SubgroupArithmeticFMulExclusiveScan = 26,
  303. SubgroupArithmeticFMulInclusiveScan = 27,
  304. FeatureCount
  305. };
  306. using FeatureMask = uint32_t;
  307. static_assert(sizeof(FeatureMask) * 8u >= FeatureCount, "Mask type needs more bits.");
  308. using CandidateVector = SmallVector<Candidate, CandidateCount>;
  309. using FeatureVector = SmallVector<Feature>;
  310. static FeatureVector get_feature_dependencies(Feature feature);
  311. static FeatureMask get_feature_dependency_mask(Feature feature);
  312. static bool can_feature_be_implemented_without_extensions(Feature feature);
  313. static Candidate get_KHR_extension_for_feature(Feature feature);
  314. struct Result
  315. {
  316. Result();
  317. uint32_t weights[CandidateCount];
  318. };
  319. void request_feature(Feature feature);
  320. bool is_feature_requested(Feature feature) const;
  321. Result resolve() const;
  322. static CandidateVector get_candidates_for_feature(Feature ft, const Result &r);
  323. private:
  324. static CandidateVector get_candidates_for_feature(Feature ft);
  325. static FeatureMask build_mask(const SmallVector<Feature> &features);
  326. FeatureMask feature_mask = 0;
  327. };
  328. // TODO remove this function when all subgroup ops are supported (or make it always return true)
  329. static bool is_supported_subgroup_op_in_opengl(spv::Op op, const uint32_t *ops);
  330. void reset(uint32_t iteration_count);
  331. void emit_function(SPIRFunction &func, const Bitset &return_flags);
  332. bool has_extension(const std::string &ext) const;
  333. void require_extension_internal(const std::string &ext);
  334. // Virtualize methods which need to be overridden by subclass targets like C++ and such.
  335. virtual void emit_function_prototype(SPIRFunction &func, const Bitset &return_flags);
  336. SPIRBlock *current_emitting_block = nullptr;
  337. SmallVector<SPIRBlock *> current_emitting_switch_stack;
  338. bool current_emitting_switch_fallthrough = false;
  339. virtual void emit_instruction(const Instruction &instr);
  340. struct TemporaryCopy
  341. {
  342. uint32_t dst_id;
  343. uint32_t src_id;
  344. };
  345. TemporaryCopy handle_instruction_precision(const Instruction &instr);
  346. void emit_block_instructions(SPIRBlock &block);
  347. void emit_block_instructions_with_masked_debug(SPIRBlock &block);
  348. // For relax_nan_checks.
  349. GLSLstd450 get_remapped_glsl_op(GLSLstd450 std450_op) const;
  350. spv::Op get_remapped_spirv_op(spv::Op op) const;
  351. virtual void emit_glsl_op(uint32_t result_type, uint32_t result_id, uint32_t op, const uint32_t *args,
  352. uint32_t count);
  353. virtual void emit_spv_amd_shader_ballot_op(uint32_t result_type, uint32_t result_id, uint32_t op,
  354. const uint32_t *args, uint32_t count);
  355. virtual void emit_spv_amd_shader_explicit_vertex_parameter_op(uint32_t result_type, uint32_t result_id, uint32_t op,
  356. const uint32_t *args, uint32_t count);
  357. virtual void emit_spv_amd_shader_trinary_minmax_op(uint32_t result_type, uint32_t result_id, uint32_t op,
  358. const uint32_t *args, uint32_t count);
  359. virtual void emit_spv_amd_gcn_shader_op(uint32_t result_type, uint32_t result_id, uint32_t op, const uint32_t *args,
  360. uint32_t count);
  361. virtual void emit_header();
  362. void emit_line_directive(uint32_t file_id, uint32_t line_literal);
  363. void build_workgroup_size(SmallVector<std::string> &arguments, const SpecializationConstant &x,
  364. const SpecializationConstant &y, const SpecializationConstant &z);
  365. void request_subgroup_feature(ShaderSubgroupSupportHelper::Feature feature);
  366. virtual void emit_sampled_image_op(uint32_t result_type, uint32_t result_id, uint32_t image_id, uint32_t samp_id);
  367. virtual void emit_texture_op(const Instruction &i, bool sparse);
  368. virtual std::string to_texture_op(const Instruction &i, bool sparse, bool *forward,
  369. SmallVector<uint32_t> &inherited_expressions);
  370. virtual void emit_subgroup_op(const Instruction &i);
  371. virtual std::string type_to_glsl(const SPIRType &type, uint32_t id = 0);
  372. virtual std::string builtin_to_glsl(spv::BuiltIn builtin, spv::StorageClass storage);
  373. virtual void emit_struct_member(const SPIRType &type, uint32_t member_type_id, uint32_t index,
  374. const std::string &qualifier = "", uint32_t base_offset = 0);
  375. virtual void emit_struct_padding_target(const SPIRType &type);
  376. virtual std::string image_type_glsl(const SPIRType &type, uint32_t id = 0, bool member = false);
  377. std::string constant_expression(const SPIRConstant &c,
  378. bool inside_block_like_struct_scope = false,
  379. bool inside_struct_scope = false);
  380. virtual std::string constant_op_expression(const SPIRConstantOp &cop);
  381. virtual std::string constant_expression_vector(const SPIRConstant &c, uint32_t vector);
  382. virtual void emit_fixup();
  383. virtual std::string variable_decl(const SPIRType &type, const std::string &name, uint32_t id = 0);
  384. virtual bool variable_decl_is_remapped_storage(const SPIRVariable &var, spv::StorageClass storage) const;
  385. virtual std::string to_func_call_arg(const SPIRFunction::Parameter &arg, uint32_t id);
  386. virtual void emit_workgroup_initialization(const SPIRVariable &var);
  387. struct TextureFunctionBaseArguments
  388. {
  389. // GCC 4.8 workarounds, it doesn't understand '{}' constructor here, use explicit default constructor.
  390. TextureFunctionBaseArguments() = default;
  391. VariableID img = 0;
  392. const SPIRType *imgtype = nullptr;
  393. bool is_fetch = false, is_gather = false, is_proj = false;
  394. };
  395. struct TextureFunctionNameArguments
  396. {
  397. // GCC 4.8 workarounds, it doesn't understand '{}' constructor here, use explicit default constructor.
  398. TextureFunctionNameArguments() = default;
  399. TextureFunctionBaseArguments base;
  400. bool has_array_offsets = false, has_offset = false, has_grad = false;
  401. bool has_dref = false, is_sparse_feedback = false, has_min_lod = false;
  402. uint32_t lod = 0;
  403. };
  404. virtual std::string to_function_name(const TextureFunctionNameArguments &args);
  405. struct TextureFunctionArguments
  406. {
  407. // GCC 4.8 workarounds, it doesn't understand '{}' constructor here, use explicit default constructor.
  408. TextureFunctionArguments() = default;
  409. TextureFunctionBaseArguments base;
  410. uint32_t coord = 0, coord_components = 0, dref = 0;
  411. uint32_t grad_x = 0, grad_y = 0, lod = 0, offset = 0;
  412. uint32_t bias = 0, component = 0, sample = 0, sparse_texel = 0, min_lod = 0;
  413. bool nonuniform_expression = false, has_array_offsets = false;
  414. };
  415. virtual std::string to_function_args(const TextureFunctionArguments &args, bool *p_forward);
  416. void emit_sparse_feedback_temporaries(uint32_t result_type_id, uint32_t id, uint32_t &feedback_id,
  417. uint32_t &texel_id);
  418. uint32_t get_sparse_feedback_texel_id(uint32_t id) const;
  419. virtual void emit_buffer_block(const SPIRVariable &type);
  420. virtual void emit_push_constant_block(const SPIRVariable &var);
  421. virtual void emit_uniform(const SPIRVariable &var);
  422. virtual std::string unpack_expression_type(std::string expr_str, const SPIRType &type, uint32_t physical_type_id,
  423. bool packed_type, bool row_major);
  424. virtual bool builtin_translates_to_nonarray(spv::BuiltIn builtin) const;
  425. virtual bool is_user_type_structured(uint32_t id) const;
  426. void emit_copy_logical_type(uint32_t lhs_id, uint32_t lhs_type_id, uint32_t rhs_id, uint32_t rhs_type_id,
  427. SmallVector<uint32_t> chain);
  428. StringStream<> buffer;
  429. template <typename T>
  430. inline void statement_inner(T &&t)
  431. {
  432. buffer << std::forward<T>(t);
  433. statement_count++;
  434. }
  435. template <typename T, typename... Ts>
  436. inline void statement_inner(T &&t, Ts &&... ts)
  437. {
  438. buffer << std::forward<T>(t);
  439. statement_count++;
  440. statement_inner(std::forward<Ts>(ts)...);
  441. }
  442. template <typename... Ts>
  443. inline void statement(Ts &&... ts)
  444. {
  445. if (is_forcing_recompilation())
  446. {
  447. // Do not bother emitting code while force_recompile is active.
  448. // We will compile again.
  449. statement_count++;
  450. return;
  451. }
  452. if (redirect_statement)
  453. {
  454. redirect_statement->push_back(join(std::forward<Ts>(ts)...));
  455. statement_count++;
  456. }
  457. else
  458. {
  459. for (uint32_t i = 0; i < indent; i++)
  460. buffer << " ";
  461. statement_inner(std::forward<Ts>(ts)...);
  462. buffer << '\n';
  463. }
  464. }
  465. template <typename... Ts>
  466. inline void statement_no_indent(Ts &&... ts)
  467. {
  468. auto old_indent = indent;
  469. indent = 0;
  470. statement(std::forward<Ts>(ts)...);
  471. indent = old_indent;
  472. }
  473. // Used for implementing continue blocks where
  474. // we want to obtain a list of statements we can merge
  475. // on a single line separated by comma.
  476. SmallVector<std::string> *redirect_statement = nullptr;
  477. const SPIRBlock *current_continue_block = nullptr;
  478. bool block_temporary_hoisting = false;
  479. bool block_debug_directives = false;
  480. void begin_scope();
  481. void end_scope();
  482. void end_scope(const std::string &trailer);
  483. void end_scope_decl();
  484. void end_scope_decl(const std::string &decl);
  485. Options options;
  486. // Allow Metal to use the array<T> template to make arrays a value type
  487. virtual std::string type_to_array_glsl(const SPIRType &type, uint32_t variable_id);
  488. std::string to_array_size(const SPIRType &type, uint32_t index);
  489. uint32_t to_array_size_literal(const SPIRType &type, uint32_t index) const;
  490. uint32_t to_array_size_literal(const SPIRType &type) const;
  491. virtual std::string variable_decl(const SPIRVariable &variable); // Threadgroup arrays can't have a wrapper type
  492. std::string variable_decl_function_local(SPIRVariable &variable);
  493. void add_local_variable_name(uint32_t id);
  494. void add_resource_name(uint32_t id);
  495. void add_member_name(SPIRType &type, uint32_t name);
  496. void add_function_overload(const SPIRFunction &func);
  497. virtual bool is_non_native_row_major_matrix(uint32_t id);
  498. virtual bool member_is_non_native_row_major_matrix(const SPIRType &type, uint32_t index);
  499. bool member_is_remapped_physical_type(const SPIRType &type, uint32_t index) const;
  500. bool member_is_packed_physical_type(const SPIRType &type, uint32_t index) const;
  501. virtual std::string convert_row_major_matrix(std::string exp_str, const SPIRType &exp_type,
  502. uint32_t physical_type_id, bool is_packed,
  503. bool relaxed = false);
  504. std::unordered_set<std::string> local_variable_names;
  505. std::unordered_set<std::string> resource_names;
  506. std::unordered_set<std::string> block_input_names;
  507. std::unordered_set<std::string> block_output_names;
  508. std::unordered_set<std::string> block_ubo_names;
  509. std::unordered_set<std::string> block_ssbo_names;
  510. std::unordered_set<std::string> block_names; // A union of all block_*_names.
  511. std::unordered_map<std::string, std::unordered_set<uint64_t>> function_overloads;
  512. std::unordered_map<uint32_t, std::string> preserved_aliases;
  513. void preserve_alias_on_reset(uint32_t id);
  514. void reset_name_caches();
  515. bool processing_entry_point = false;
  516. // Can be overriden by subclass backends for trivial things which
  517. // shouldn't need polymorphism.
  518. struct BackendVariations
  519. {
  520. std::string discard_literal = "discard";
  521. std::string demote_literal = "demote";
  522. std::string null_pointer_literal = "";
  523. bool float_literal_suffix = false;
  524. bool double_literal_suffix = true;
  525. bool uint32_t_literal_suffix = true;
  526. bool long_long_literal_suffix = false;
  527. const char *basic_int_type = "int";
  528. const char *basic_uint_type = "uint";
  529. const char *basic_int8_type = "int8_t";
  530. const char *basic_uint8_type = "uint8_t";
  531. const char *basic_int16_type = "int16_t";
  532. const char *basic_uint16_type = "uint16_t";
  533. const char *int16_t_literal_suffix = "s";
  534. const char *uint16_t_literal_suffix = "us";
  535. const char *nonuniform_qualifier = "nonuniformEXT";
  536. const char *boolean_mix_function = "mix";
  537. const char *printf_function = "debugPrintfEXT";
  538. std::string constant_null_initializer = "";
  539. SPIRType::BaseType boolean_in_struct_remapped_type = SPIRType::Boolean;
  540. bool swizzle_is_function = false;
  541. bool shared_is_implied = false;
  542. bool unsized_array_supported = true;
  543. bool explicit_struct_type = false;
  544. bool use_initializer_list = false;
  545. bool use_typed_initializer_list = false;
  546. bool requires_matching_array_initializer = false;
  547. bool can_declare_struct_inline = true;
  548. bool can_declare_arrays_inline = true;
  549. bool native_row_major_matrix = true;
  550. bool use_constructor_splatting = true;
  551. bool allow_precision_qualifiers = false;
  552. bool can_swizzle_scalar = false;
  553. bool force_gl_in_out_block = false;
  554. bool force_merged_mesh_block = false;
  555. bool can_return_array = true;
  556. bool allow_truncated_access_chain = false;
  557. bool supports_extensions = false;
  558. bool supports_empty_struct = false;
  559. bool array_is_value_type = true;
  560. bool array_is_value_type_in_buffer_blocks = true;
  561. bool comparison_image_samples_scalar = false;
  562. bool native_pointers = false;
  563. bool support_small_type_sampling_result = false;
  564. bool support_case_fallthrough = true;
  565. bool use_array_constructor = false;
  566. bool needs_row_major_load_workaround = false;
  567. bool support_pointer_to_pointer = false;
  568. bool support_precise_qualifier = false;
  569. bool support_64bit_switch = false;
  570. bool workgroup_size_is_hidden = false;
  571. bool requires_relaxed_precision_analysis = false;
  572. bool implicit_c_integer_promotion_rules = false;
  573. } backend;
  574. void emit_struct(SPIRType &type);
  575. void emit_resources();
  576. void emit_extension_workarounds(spv::ExecutionModel model);
  577. void emit_subgroup_arithmetic_workaround(const std::string &func, spv::Op op, spv::GroupOperation group_op);
  578. void emit_polyfills(uint32_t polyfills, bool relaxed);
  579. void emit_buffer_block_native(const SPIRVariable &var);
  580. void emit_buffer_reference_block(uint32_t type_id, bool forward_declaration);
  581. void emit_buffer_block_legacy(const SPIRVariable &var);
  582. void emit_buffer_block_flattened(const SPIRVariable &type);
  583. void fixup_implicit_builtin_block_names(spv::ExecutionModel model);
  584. void emit_declared_builtin_block(spv::StorageClass storage, spv::ExecutionModel model);
  585. bool should_force_emit_builtin_block(spv::StorageClass storage);
  586. void emit_push_constant_block_vulkan(const SPIRVariable &var);
  587. void emit_push_constant_block_glsl(const SPIRVariable &var);
  588. void emit_interface_block(const SPIRVariable &type);
  589. void emit_flattened_io_block(const SPIRVariable &var, const char *qual);
  590. void emit_flattened_io_block_struct(const std::string &basename, const SPIRType &type, const char *qual,
  591. const SmallVector<uint32_t> &indices);
  592. void emit_flattened_io_block_member(const std::string &basename, const SPIRType &type, const char *qual,
  593. const SmallVector<uint32_t> &indices);
  594. void emit_block_chain(SPIRBlock &block);
  595. void emit_hoisted_temporaries(SmallVector<std::pair<TypeID, ID>> &temporaries);
  596. int get_constant_mapping_to_workgroup_component(const SPIRConstant &constant) const;
  597. void emit_constant(const SPIRConstant &constant);
  598. void emit_specialization_constant_op(const SPIRConstantOp &constant);
  599. std::string emit_continue_block(uint32_t continue_block, bool follow_true_block, bool follow_false_block);
  600. bool attempt_emit_loop_header(SPIRBlock &block, SPIRBlock::Method method);
  601. void branch(BlockID from, BlockID to);
  602. void branch_to_continue(BlockID from, BlockID to);
  603. void branch(BlockID from, uint32_t cond, BlockID true_block, BlockID false_block);
  604. void flush_phi(BlockID from, BlockID to);
  605. void flush_variable_declaration(uint32_t id);
  606. void flush_undeclared_variables(SPIRBlock &block);
  607. void emit_variable_temporary_copies(const SPIRVariable &var);
  608. bool should_dereference(uint32_t id);
  609. bool should_dereference_caller_param(uint32_t id);
  610. bool should_forward(uint32_t id) const;
  611. bool should_suppress_usage_tracking(uint32_t id) const;
  612. void emit_mix_op(uint32_t result_type, uint32_t id, uint32_t left, uint32_t right, uint32_t lerp);
  613. void emit_nminmax_op(uint32_t result_type, uint32_t id, uint32_t op0, uint32_t op1, GLSLstd450 op);
  614. void emit_emulated_ahyper_op(uint32_t result_type, uint32_t result_id, uint32_t op0, GLSLstd450 op);
  615. bool to_trivial_mix_op(const SPIRType &type, std::string &op, uint32_t left, uint32_t right, uint32_t lerp);
  616. void emit_quaternary_func_op(uint32_t result_type, uint32_t result_id, uint32_t op0, uint32_t op1, uint32_t op2,
  617. uint32_t op3, const char *op);
  618. void emit_trinary_func_op(uint32_t result_type, uint32_t result_id, uint32_t op0, uint32_t op1, uint32_t op2,
  619. const char *op);
  620. void emit_binary_func_op(uint32_t result_type, uint32_t result_id, uint32_t op0, uint32_t op1, const char *op);
  621. void emit_atomic_func_op(uint32_t result_type, uint32_t result_id, uint32_t op0, uint32_t op1, const char *op);
  622. void emit_atomic_func_op(uint32_t result_type, uint32_t result_id, uint32_t op0, uint32_t op1, uint32_t op2, const char *op);
  623. void emit_unary_func_op_cast(uint32_t result_type, uint32_t result_id, uint32_t op0, const char *op,
  624. SPIRType::BaseType input_type, SPIRType::BaseType expected_result_type);
  625. void emit_binary_func_op_cast(uint32_t result_type, uint32_t result_id, uint32_t op0, uint32_t op1, const char *op,
  626. SPIRType::BaseType input_type, bool skip_cast_if_equal_type);
  627. void emit_binary_func_op_cast_clustered(uint32_t result_type, uint32_t result_id, uint32_t op0, uint32_t op1,
  628. const char *op, SPIRType::BaseType input_type);
  629. void emit_trinary_func_op_cast(uint32_t result_type, uint32_t result_id, uint32_t op0, uint32_t op1, uint32_t op2,
  630. const char *op, SPIRType::BaseType input_type);
  631. void emit_trinary_func_op_bitextract(uint32_t result_type, uint32_t result_id, uint32_t op0, uint32_t op1,
  632. uint32_t op2, const char *op, SPIRType::BaseType expected_result_type,
  633. SPIRType::BaseType input_type0, SPIRType::BaseType input_type1,
  634. SPIRType::BaseType input_type2);
  635. void emit_bitfield_insert_op(uint32_t result_type, uint32_t result_id, uint32_t op0, uint32_t op1, uint32_t op2,
  636. uint32_t op3, const char *op, SPIRType::BaseType offset_count_type);
  637. void emit_unary_func_op(uint32_t result_type, uint32_t result_id, uint32_t op0, const char *op);
  638. void emit_unrolled_unary_op(uint32_t result_type, uint32_t result_id, uint32_t operand, const char *op);
  639. void emit_binary_op(uint32_t result_type, uint32_t result_id, uint32_t op0, uint32_t op1, const char *op);
  640. void emit_unrolled_binary_op(uint32_t result_type, uint32_t result_id, uint32_t op0, uint32_t op1, const char *op,
  641. bool negate, SPIRType::BaseType expected_type);
  642. void emit_binary_op_cast(uint32_t result_type, uint32_t result_id, uint32_t op0, uint32_t op1, const char *op,
  643. SPIRType::BaseType input_type, bool skip_cast_if_equal_type, bool implicit_integer_promotion);
  644. SPIRType binary_op_bitcast_helper(std::string &cast_op0, std::string &cast_op1, SPIRType::BaseType &input_type,
  645. uint32_t op0, uint32_t op1, bool skip_cast_if_equal_type);
  646. virtual bool emit_complex_bitcast(uint32_t result_type, uint32_t id, uint32_t op0);
  647. std::string to_ternary_expression(const SPIRType &result_type, uint32_t select, uint32_t true_value,
  648. uint32_t false_value);
  649. void emit_unary_op(uint32_t result_type, uint32_t result_id, uint32_t op0, const char *op);
  650. void emit_unary_op_cast(uint32_t result_type, uint32_t result_id, uint32_t op0, const char *op);
  651. virtual void emit_mesh_tasks(SPIRBlock &block);
  652. bool expression_is_forwarded(uint32_t id) const;
  653. bool expression_suppresses_usage_tracking(uint32_t id) const;
  654. bool expression_read_implies_multiple_reads(uint32_t id) const;
  655. SPIRExpression &emit_op(uint32_t result_type, uint32_t result_id, const std::string &rhs, bool forward_rhs,
  656. bool suppress_usage_tracking = false);
  657. void access_chain_internal_append_index(std::string &expr, uint32_t base, const SPIRType *type,
  658. AccessChainFlags flags, bool &access_chain_is_arrayed, uint32_t index);
  659. std::string access_chain_internal(uint32_t base, const uint32_t *indices, uint32_t count, AccessChainFlags flags,
  660. AccessChainMeta *meta);
  661. // Only meaningful on backends with physical pointer support ala MSL.
  662. // Relevant for PtrAccessChain / BDA.
  663. virtual uint32_t get_physical_type_stride(const SPIRType &type) const;
  664. spv::StorageClass get_expression_effective_storage_class(uint32_t ptr);
  665. virtual bool access_chain_needs_stage_io_builtin_translation(uint32_t base);
  666. virtual bool check_physical_type_cast(std::string &expr, const SPIRType *type, uint32_t physical_type);
  667. virtual bool prepare_access_chain_for_scalar_access(std::string &expr, const SPIRType &type,
  668. spv::StorageClass storage, bool &is_packed);
  669. std::string access_chain(uint32_t base, const uint32_t *indices, uint32_t count, const SPIRType &target_type,
  670. AccessChainMeta *meta = nullptr, bool ptr_chain = false);
  671. std::string flattened_access_chain(uint32_t base, const uint32_t *indices, uint32_t count,
  672. const SPIRType &target_type, uint32_t offset, uint32_t matrix_stride,
  673. uint32_t array_stride, bool need_transpose);
  674. std::string flattened_access_chain_struct(uint32_t base, const uint32_t *indices, uint32_t count,
  675. const SPIRType &target_type, uint32_t offset);
  676. std::string flattened_access_chain_matrix(uint32_t base, const uint32_t *indices, uint32_t count,
  677. const SPIRType &target_type, uint32_t offset, uint32_t matrix_stride,
  678. bool need_transpose);
  679. std::string flattened_access_chain_vector(uint32_t base, const uint32_t *indices, uint32_t count,
  680. const SPIRType &target_type, uint32_t offset, uint32_t matrix_stride,
  681. bool need_transpose);
  682. std::pair<std::string, uint32_t> flattened_access_chain_offset(const SPIRType &basetype, const uint32_t *indices,
  683. uint32_t count, uint32_t offset,
  684. uint32_t word_stride, bool *need_transpose = nullptr,
  685. uint32_t *matrix_stride = nullptr,
  686. uint32_t *array_stride = nullptr,
  687. bool ptr_chain = false);
  688. const char *index_to_swizzle(uint32_t index);
  689. std::string remap_swizzle(const SPIRType &result_type, uint32_t input_components, const std::string &expr);
  690. std::string declare_temporary(uint32_t type, uint32_t id);
  691. void emit_uninitialized_temporary(uint32_t type, uint32_t id);
  692. SPIRExpression &emit_uninitialized_temporary_expression(uint32_t type, uint32_t id);
  693. virtual void append_global_func_args(const SPIRFunction &func, uint32_t index, SmallVector<std::string> &arglist);
  694. std::string to_non_uniform_aware_expression(uint32_t id);
  695. std::string to_atomic_ptr_expression(uint32_t id);
  696. std::string to_expression(uint32_t id, bool register_expression_read = true);
  697. std::string to_composite_constructor_expression(const SPIRType &parent_type, uint32_t id, bool block_like_type);
  698. std::string to_rerolled_array_expression(const SPIRType &parent_type, const std::string &expr, const SPIRType &type);
  699. std::string to_enclosed_expression(uint32_t id, bool register_expression_read = true);
  700. std::string to_unpacked_expression(uint32_t id, bool register_expression_read = true);
  701. std::string to_unpacked_row_major_matrix_expression(uint32_t id);
  702. std::string to_enclosed_unpacked_expression(uint32_t id, bool register_expression_read = true);
  703. std::string to_dereferenced_expression(uint32_t id, bool register_expression_read = true);
  704. std::string to_pointer_expression(uint32_t id, bool register_expression_read = true);
  705. std::string to_enclosed_pointer_expression(uint32_t id, bool register_expression_read = true);
  706. std::string to_extract_component_expression(uint32_t id, uint32_t index);
  707. std::string to_extract_constant_composite_expression(uint32_t result_type, const SPIRConstant &c,
  708. const uint32_t *chain, uint32_t length);
  709. static bool needs_enclose_expression(const std::string &expr);
  710. std::string enclose_expression(const std::string &expr);
  711. std::string dereference_expression(const SPIRType &expression_type, const std::string &expr);
  712. std::string address_of_expression(const std::string &expr);
  713. void strip_enclosed_expression(std::string &expr);
  714. std::string to_member_name(const SPIRType &type, uint32_t index);
  715. virtual std::string to_member_reference(uint32_t base, const SPIRType &type, uint32_t index, bool ptr_chain_is_resolved);
  716. std::string to_multi_member_reference(const SPIRType &type, const SmallVector<uint32_t> &indices);
  717. std::string type_to_glsl_constructor(const SPIRType &type);
  718. std::string argument_decl(const SPIRFunction::Parameter &arg);
  719. virtual std::string to_qualifiers_glsl(uint32_t id);
  720. void fixup_io_block_patch_primitive_qualifiers(const SPIRVariable &var);
  721. void emit_output_variable_initializer(const SPIRVariable &var);
  722. std::string to_precision_qualifiers_glsl(uint32_t id);
  723. virtual const char *to_storage_qualifiers_glsl(const SPIRVariable &var);
  724. std::string flags_to_qualifiers_glsl(const SPIRType &type, const Bitset &flags);
  725. const char *format_to_glsl(spv::ImageFormat format);
  726. virtual std::string layout_for_member(const SPIRType &type, uint32_t index);
  727. virtual std::string to_interpolation_qualifiers(const Bitset &flags);
  728. std::string layout_for_variable(const SPIRVariable &variable);
  729. std::string to_combined_image_sampler(VariableID image_id, VariableID samp_id);
  730. virtual bool skip_argument(uint32_t id) const;
  731. virtual bool emit_array_copy(const char *expr, uint32_t lhs_id, uint32_t rhs_id,
  732. spv::StorageClass lhs_storage, spv::StorageClass rhs_storage);
  733. virtual void emit_block_hints(const SPIRBlock &block);
  734. virtual std::string to_initializer_expression(const SPIRVariable &var);
  735. virtual std::string to_zero_initialized_expression(uint32_t type_id);
  736. bool type_can_zero_initialize(const SPIRType &type) const;
  737. bool buffer_is_packing_standard(const SPIRType &type, BufferPackingStandard packing,
  738. uint32_t *failed_index = nullptr, uint32_t start_offset = 0,
  739. uint32_t end_offset = ~(0u));
  740. std::string buffer_to_packing_standard(const SPIRType &type,
  741. bool support_std430_without_scalar_layout,
  742. bool support_enhanced_layouts);
  743. uint32_t type_to_packed_base_size(const SPIRType &type, BufferPackingStandard packing);
  744. uint32_t type_to_packed_alignment(const SPIRType &type, const Bitset &flags, BufferPackingStandard packing);
  745. uint32_t type_to_packed_array_stride(const SPIRType &type, const Bitset &flags, BufferPackingStandard packing);
  746. uint32_t type_to_packed_size(const SPIRType &type, const Bitset &flags, BufferPackingStandard packing);
  747. uint32_t type_to_location_count(const SPIRType &type) const;
  748. std::string bitcast_glsl(const SPIRType &result_type, uint32_t arg);
  749. virtual std::string bitcast_glsl_op(const SPIRType &result_type, const SPIRType &argument_type);
  750. std::string bitcast_expression(SPIRType::BaseType target_type, uint32_t arg);
  751. std::string bitcast_expression(const SPIRType &target_type, SPIRType::BaseType expr_type, const std::string &expr);
  752. std::string build_composite_combiner(uint32_t result_type, const uint32_t *elems, uint32_t length);
  753. bool remove_duplicate_swizzle(std::string &op);
  754. bool remove_unity_swizzle(uint32_t base, std::string &op);
  755. // Can modify flags to remote readonly/writeonly if image type
  756. // and force recompile.
  757. bool check_atomic_image(uint32_t id);
  758. virtual void replace_illegal_names();
  759. void replace_illegal_names(const std::unordered_set<std::string> &keywords);
  760. virtual void emit_entry_point_declarations();
  761. void replace_fragment_output(SPIRVariable &var);
  762. void replace_fragment_outputs();
  763. std::string legacy_tex_op(const std::string &op, const SPIRType &imgtype, uint32_t id);
  764. void forward_relaxed_precision(uint32_t dst_id, const uint32_t *args, uint32_t length);
  765. void analyze_precision_requirements(uint32_t type_id, uint32_t dst_id, uint32_t *args, uint32_t length);
  766. Options::Precision analyze_expression_precision(const uint32_t *args, uint32_t length) const;
  767. uint32_t indent = 0;
  768. std::unordered_set<uint32_t> emitted_functions;
  769. // Ensure that we declare phi-variable copies even if the original declaration isn't deferred
  770. std::unordered_set<uint32_t> flushed_phi_variables;
  771. std::unordered_set<uint32_t> flattened_buffer_blocks;
  772. std::unordered_map<uint32_t, bool> flattened_structs;
  773. ShaderSubgroupSupportHelper shader_subgroup_supporter;
  774. std::string load_flattened_struct(const std::string &basename, const SPIRType &type);
  775. std::string to_flattened_struct_member(const std::string &basename, const SPIRType &type, uint32_t index);
  776. void store_flattened_struct(uint32_t lhs_id, uint32_t value);
  777. void store_flattened_struct(const std::string &basename, uint32_t rhs, const SPIRType &type,
  778. const SmallVector<uint32_t> &indices);
  779. std::string to_flattened_access_chain_expression(uint32_t id);
  780. // Usage tracking. If a temporary is used more than once, use the temporary instead to
  781. // avoid AST explosion when SPIRV is generated with pure SSA and doesn't write stuff to variables.
  782. std::unordered_map<uint32_t, uint32_t> expression_usage_counts;
  783. void track_expression_read(uint32_t id);
  784. SmallVector<std::string> forced_extensions;
  785. SmallVector<std::string> header_lines;
  786. // Used when expressions emit extra opcodes with their own unique IDs,
  787. // and we need to reuse the IDs across recompilation loops.
  788. // Currently used by NMin/Max/Clamp implementations.
  789. std::unordered_map<uint32_t, uint32_t> extra_sub_expressions;
  790. SmallVector<TypeID> workaround_ubo_load_overload_types;
  791. void request_workaround_wrapper_overload(TypeID id);
  792. void rewrite_load_for_wrapped_row_major(std::string &expr, TypeID loaded_type, ID ptr);
  793. uint32_t statement_count = 0;
  794. inline bool is_legacy() const
  795. {
  796. return (options.es && options.version < 300) || (!options.es && options.version < 130);
  797. }
  798. inline bool is_legacy_es() const
  799. {
  800. return options.es && options.version < 300;
  801. }
  802. inline bool is_legacy_desktop() const
  803. {
  804. return !options.es && options.version < 130;
  805. }
  806. enum Polyfill : uint32_t
  807. {
  808. PolyfillTranspose2x2 = 1 << 0,
  809. PolyfillTranspose3x3 = 1 << 1,
  810. PolyfillTranspose4x4 = 1 << 2,
  811. PolyfillDeterminant2x2 = 1 << 3,
  812. PolyfillDeterminant3x3 = 1 << 4,
  813. PolyfillDeterminant4x4 = 1 << 5,
  814. PolyfillMatrixInverse2x2 = 1 << 6,
  815. PolyfillMatrixInverse3x3 = 1 << 7,
  816. PolyfillMatrixInverse4x4 = 1 << 8,
  817. PolyfillNMin16 = 1 << 9,
  818. PolyfillNMin32 = 1 << 10,
  819. PolyfillNMin64 = 1 << 11,
  820. PolyfillNMax16 = 1 << 12,
  821. PolyfillNMax32 = 1 << 13,
  822. PolyfillNMax64 = 1 << 14,
  823. PolyfillNClamp16 = 1 << 15,
  824. PolyfillNClamp32 = 1 << 16,
  825. PolyfillNClamp64 = 1 << 17,
  826. };
  827. uint32_t required_polyfills = 0;
  828. uint32_t required_polyfills_relaxed = 0;
  829. void require_polyfill(Polyfill polyfill, bool relaxed);
  830. bool ray_tracing_is_khr = false;
  831. bool barycentric_is_nv = false;
  832. void ray_tracing_khr_fixup_locations();
  833. bool args_will_forward(uint32_t id, const uint32_t *args, uint32_t num_args, bool pure);
  834. void register_call_out_argument(uint32_t id);
  835. void register_impure_function_call();
  836. void register_control_dependent_expression(uint32_t expr);
  837. // GL_EXT_shader_pixel_local_storage support.
  838. std::vector<PlsRemap> pls_inputs;
  839. std::vector<PlsRemap> pls_outputs;
  840. std::string pls_decl(const PlsRemap &variable);
  841. const char *to_pls_qualifiers_glsl(const SPIRVariable &variable);
  842. void emit_pls();
  843. void remap_pls_variables();
  844. // GL_EXT_shader_framebuffer_fetch support.
  845. std::vector<std::pair<uint32_t, uint32_t>> subpass_to_framebuffer_fetch_attachment;
  846. std::vector<std::pair<uint32_t, bool>> inout_color_attachments;
  847. bool location_is_framebuffer_fetch(uint32_t location) const;
  848. bool location_is_non_coherent_framebuffer_fetch(uint32_t location) const;
  849. bool subpass_input_is_framebuffer_fetch(uint32_t id) const;
  850. void emit_inout_fragment_outputs_copy_to_subpass_inputs();
  851. const SPIRVariable *find_subpass_input_by_attachment_index(uint32_t index) const;
  852. const SPIRVariable *find_color_output_by_location(uint32_t location) const;
  853. // A variant which takes two sets of name. The secondary is only used to verify there are no collisions,
  854. // but the set is not updated when we have found a new name.
  855. // Used primarily when adding block interface names.
  856. void add_variable(std::unordered_set<std::string> &variables_primary,
  857. const std::unordered_set<std::string> &variables_secondary, std::string &name);
  858. void check_function_call_constraints(const uint32_t *args, uint32_t length);
  859. void handle_invalid_expression(uint32_t id);
  860. void force_temporary_and_recompile(uint32_t id);
  861. void find_static_extensions();
  862. uint32_t consume_temporary_in_precision_context(uint32_t type_id, uint32_t id, Options::Precision precision);
  863. std::unordered_map<uint32_t, uint32_t> temporary_to_mirror_precision_alias;
  864. std::unordered_set<uint32_t> composite_insert_overwritten;
  865. std::unordered_set<uint32_t> block_composite_insert_overwrite;
  866. std::string emit_for_loop_initializers(const SPIRBlock &block);
  867. void emit_while_loop_initializers(const SPIRBlock &block);
  868. bool for_loop_initializers_are_same_type(const SPIRBlock &block);
  869. bool optimize_read_modify_write(const SPIRType &type, const std::string &lhs, const std::string &rhs);
  870. void fixup_image_load_store_access();
  871. bool type_is_empty(const SPIRType &type);
  872. bool can_use_io_location(spv::StorageClass storage, bool block);
  873. const Instruction *get_next_instruction_in_block(const Instruction &instr);
  874. static uint32_t mask_relevant_memory_semantics(uint32_t semantics);
  875. std::string convert_floate4m3_to_string(const SPIRConstant &value, uint32_t col, uint32_t row);
  876. std::string convert_floate5m2_to_string(const SPIRConstant &value, uint32_t col, uint32_t row);
  877. std::string convert_half_to_string(const SPIRConstant &value, uint32_t col, uint32_t row);
  878. std::string convert_float_to_string(const SPIRConstant &value, uint32_t col, uint32_t row);
  879. std::string convert_double_to_string(const SPIRConstant &value, uint32_t col, uint32_t row);
  880. std::string convert_separate_image_to_expression(uint32_t id);
  881. // Builtins in GLSL are always specific signedness, but the SPIR-V can declare them
  882. // as either unsigned or signed.
  883. // Sometimes we will need to automatically perform casts on load and store to make this work.
  884. virtual SPIRType::BaseType get_builtin_basetype(spv::BuiltIn builtin, SPIRType::BaseType default_type);
  885. virtual void cast_to_variable_store(uint32_t target_id, std::string &expr, const SPIRType &expr_type);
  886. virtual void cast_from_variable_load(uint32_t source_id, std::string &expr, const SPIRType &expr_type);
  887. void unroll_array_from_complex_load(uint32_t target_id, uint32_t source_id, std::string &expr);
  888. bool unroll_array_to_complex_store(uint32_t target_id, uint32_t source_id);
  889. void convert_non_uniform_expression(std::string &expr, uint32_t ptr_id);
  890. void handle_store_to_invariant_variable(uint32_t store_id, uint32_t value_id);
  891. void disallow_forwarding_in_expression_chain(const SPIRExpression &expr);
  892. bool expression_is_constant_null(uint32_t id) const;
  893. bool expression_is_non_value_type_array(uint32_t ptr);
  894. virtual void emit_store_statement(uint32_t lhs_expression, uint32_t rhs_expression);
  895. uint32_t get_integer_width_for_instruction(const Instruction &instr) const;
  896. uint32_t get_integer_width_for_glsl_instruction(GLSLstd450 op, const uint32_t *arguments, uint32_t length) const;
  897. bool variable_is_lut(const SPIRVariable &var) const;
  898. char current_locale_radix_character = '.';
  899. void fixup_type_alias();
  900. void reorder_type_alias();
  901. void fixup_anonymous_struct_names();
  902. void fixup_anonymous_struct_names(std::unordered_set<uint32_t> &visited, const SPIRType &type);
  903. static const char *vector_swizzle(int vecsize, int index);
  904. bool is_stage_output_location_masked(uint32_t location, uint32_t component) const;
  905. bool is_stage_output_builtin_masked(spv::BuiltIn builtin) const;
  906. bool is_stage_output_variable_masked(const SPIRVariable &var) const;
  907. bool is_stage_output_block_member_masked(const SPIRVariable &var, uint32_t index, bool strip_array) const;
  908. bool is_per_primitive_variable(const SPIRVariable &var) const;
  909. uint32_t get_accumulated_member_location(const SPIRVariable &var, uint32_t mbr_idx, bool strip_array) const;
  910. uint32_t get_declared_member_location(const SPIRVariable &var, uint32_t mbr_idx, bool strip_array) const;
  911. std::unordered_set<LocationComponentPair, InternalHasher> masked_output_locations;
  912. std::unordered_set<uint32_t> masked_output_builtins;
  913. FloatFormatter *float_formatter = nullptr;
  914. std::string format_float(float value) const;
  915. std::string format_double(double value) const;
  916. private:
  917. void init();
  918. SmallVector<ConstantID> get_composite_constant_ids(ConstantID const_id);
  919. void fill_composite_constant(SPIRConstant &constant, TypeID type_id, const SmallVector<ConstantID> &initializers);
  920. void set_composite_constant(ConstantID const_id, TypeID type_id, const SmallVector<ConstantID> &initializers);
  921. TypeID get_composite_member_type(TypeID type_id, uint32_t member_idx);
  922. std::unordered_map<uint32_t, SmallVector<ConstantID>> const_composite_insert_ids;
  923. };
  924. } // namespace SPIRV_CROSS_NAMESPACE
  925. #endif