blob: def946ac038d5a22af2e2d7d8d628f5c57ad3461 [file] [log] [blame]
Ryan Harrisondbc13af2022-02-21 15:19:07 +00001/// Copyright 2020 The Tint Authors.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15#include "src/tint/writer/hlsl/generator_impl.h"
16
17#include <algorithm>
18#include <cmath>
19#include <functional>
20#include <iomanip>
21#include <set>
22#include <utility>
23#include <vector>
24
25#include "src/tint/ast/call_statement.h"
Ryan Harrisondbc13af2022-02-21 15:19:07 +000026#include "src/tint/ast/id_attribute.h"
27#include "src/tint/ast/internal_attribute.h"
28#include "src/tint/ast/interpolate_attribute.h"
James Price7d2e2042023-05-11 13:10:59 +000029#include "src/tint/ast/transform/add_empty_entry_point.h"
30#include "src/tint/ast/transform/array_length_from_uniform.h"
31#include "src/tint/ast/transform/binding_remapper.h"
32#include "src/tint/ast/transform/builtin_polyfill.h"
33#include "src/tint/ast/transform/calculate_array_length.h"
34#include "src/tint/ast/transform/canonicalize_entry_point_io.h"
35#include "src/tint/ast/transform/decompose_memory_access.h"
36#include "src/tint/ast/transform/demote_to_helper.h"
37#include "src/tint/ast/transform/direct_variable_access.h"
38#include "src/tint/ast/transform/disable_uniformity_analysis.h"
39#include "src/tint/ast/transform/expand_compound_assignment.h"
40#include "src/tint/ast/transform/localize_struct_array_assignment.h"
41#include "src/tint/ast/transform/multiplanar_external_texture.h"
42#include "src/tint/ast/transform/num_workgroups_from_uniform.h"
43#include "src/tint/ast/transform/promote_initializers_to_let.h"
44#include "src/tint/ast/transform/promote_side_effects_to_decl.h"
45#include "src/tint/ast/transform/remove_continue_in_switch.h"
46#include "src/tint/ast/transform/remove_phonies.h"
47#include "src/tint/ast/transform/robustness.h"
48#include "src/tint/ast/transform/simplify_pointers.h"
49#include "src/tint/ast/transform/truncate_interstage_variables.h"
50#include "src/tint/ast/transform/unshadow.h"
51#include "src/tint/ast/transform/vectorize_scalar_matrix_initializers.h"
52#include "src/tint/ast/transform/zero_init_workgroup_memory.h"
Ryan Harrisondbc13af2022-02-21 15:19:07 +000053#include "src/tint/ast/variable_decl_statement.h"
Ben Clayton1e67e532023-05-24 23:07:36 +000054#include "src/tint/constant/splat.h"
dan sinclairb53b8cf2022-12-15 16:25:31 +000055#include "src/tint/constant/value.h"
Ryan Harrisondbc13af2022-02-21 15:19:07 +000056#include "src/tint/debug.h"
Ryan Harrisondbc13af2022-02-21 15:19:07 +000057#include "src/tint/sem/block_statement.h"
58#include "src/tint/sem/call.h"
Ryan Harrisondbc13af2022-02-21 15:19:07 +000059#include "src/tint/sem/function.h"
60#include "src/tint/sem/member_accessor_expression.h"
61#include "src/tint/sem/module.h"
Ryan Harrisondbc13af2022-02-21 15:19:07 +000062#include "src/tint/sem/statement.h"
Ryan Harrisondbc13af2022-02-21 15:19:07 +000063#include "src/tint/sem/struct.h"
dan sinclaird32fbe02022-10-19 00:43:41 +000064#include "src/tint/sem/switch_statement.h"
Ben Clayton54a104e2023-02-22 20:04:40 +000065#include "src/tint/sem/value_constructor.h"
66#include "src/tint/sem/value_conversion.h"
Ryan Harrisondbc13af2022-02-21 15:19:07 +000067#include "src/tint/sem/variable.h"
Ben Clayton23946b32023-03-09 16:50:19 +000068#include "src/tint/switch.h"
Ryan Harrisondbc13af2022-02-21 15:19:07 +000069#include "src/tint/transform/manager.h"
dan sinclair946858a2022-12-08 22:21:24 +000070#include "src/tint/type/array.h"
dan sinclaird8a08452022-12-08 22:21:24 +000071#include "src/tint/type/atomic.h"
dan sinclair4595fb72022-12-08 14:14:10 +000072#include "src/tint/type/depth_multisampled_texture.h"
73#include "src/tint/type/depth_texture.h"
74#include "src/tint/type/multisampled_texture.h"
75#include "src/tint/type/sampled_texture.h"
76#include "src/tint/type/storage_texture.h"
dan sinclair3cbf3fc2023-01-21 19:16:15 +000077#include "src/tint/type/texture_dimension.h"
Ben Clayton884f9522023-01-12 22:52:57 +000078#include "src/tint/utils/compiler_macros.h"
Ryan Harrisondbc13af2022-02-21 15:19:07 +000079#include "src/tint/utils/defer.h"
80#include "src/tint/utils/map.h"
81#include "src/tint/utils/scoped_assignment.h"
dan sinclair4abf28e2022-08-02 15:55:35 +000082#include "src/tint/utils/string.h"
dan sinclair2b9d5b32023-02-28 14:49:25 +000083#include "src/tint/utils/string_stream.h"
Ryan Harrisondbc13af2022-02-21 15:19:07 +000084#include "src/tint/writer/append_vector.h"
Ben Clayton1a567782022-10-14 13:38:27 +000085#include "src/tint/writer/check_supported_extensions.h"
Ryan Harrisondbc13af2022-02-21 15:19:07 +000086#include "src/tint/writer/float_to_string.h"
87
Ben Clayton0ce9ab02022-05-05 20:23:40 +000088using namespace tint::number_suffixes; // NOLINT
89
dan sinclair6a5bef12022-04-07 14:30:24 +000090namespace tint::writer::hlsl {
Ryan Harrisondbc13af2022-02-21 15:19:07 +000091namespace {
92
93const char kTempNamePrefix[] = "tint_tmp";
Ryan Harrisondbc13af2022-02-21 15:19:07 +000094
dan sinclairba082fd2023-02-19 04:14:19 +000095const char* image_format_to_rwtexture_type(builtin::TexelFormat image_format) {
dan sinclair41e4d9a2022-05-01 14:40:55 +000096 switch (image_format) {
dan sinclairba082fd2023-02-19 04:14:19 +000097 case builtin::TexelFormat::kBgra8Unorm:
98 case builtin::TexelFormat::kRgba8Unorm:
99 case builtin::TexelFormat::kRgba8Snorm:
100 case builtin::TexelFormat::kRgba16Float:
101 case builtin::TexelFormat::kR32Float:
102 case builtin::TexelFormat::kRg32Float:
103 case builtin::TexelFormat::kRgba32Float:
dan sinclair41e4d9a2022-05-01 14:40:55 +0000104 return "float4";
dan sinclairba082fd2023-02-19 04:14:19 +0000105 case builtin::TexelFormat::kRgba8Uint:
106 case builtin::TexelFormat::kRgba16Uint:
107 case builtin::TexelFormat::kR32Uint:
108 case builtin::TexelFormat::kRg32Uint:
109 case builtin::TexelFormat::kRgba32Uint:
dan sinclair41e4d9a2022-05-01 14:40:55 +0000110 return "uint4";
dan sinclairba082fd2023-02-19 04:14:19 +0000111 case builtin::TexelFormat::kRgba8Sint:
112 case builtin::TexelFormat::kRgba16Sint:
113 case builtin::TexelFormat::kR32Sint:
114 case builtin::TexelFormat::kRg32Sint:
115 case builtin::TexelFormat::kRgba32Sint:
dan sinclair41e4d9a2022-05-01 14:40:55 +0000116 return "int4";
117 default:
118 return nullptr;
119 }
Ryan Harrisondbc13af2022-02-21 15:19:07 +0000120}
121
dan sinclair2b9d5b32023-02-28 14:49:25 +0000122void PrintF32(utils::StringStream& out, float value) {
Ben Claytone9f8b092022-06-01 13:14:39 +0000123 if (std::isinf(value)) {
Antonio Maiorano679cf4f2022-09-03 21:43:01 +0000124 out << "0.0f " << (value >= 0 ? "/* inf */" : "/* -inf */");
Ben Claytone9f8b092022-06-01 13:14:39 +0000125 } else if (std::isnan(value)) {
Antonio Maiorano679cf4f2022-09-03 21:43:01 +0000126 out << "0.0f /* nan */";
Ben Claytone9f8b092022-06-01 13:14:39 +0000127 } else {
128 out << FloatToString(value) << "f";
129 }
130}
131
dan sinclair2b9d5b32023-02-28 14:49:25 +0000132void PrintF16(utils::StringStream& out, float value) {
Antonio Maiorano679cf4f2022-09-03 21:43:01 +0000133 if (std::isinf(value)) {
134 out << "0.0h " << (value >= 0 ? "/* inf */" : "/* -inf */");
135 } else if (std::isnan(value)) {
136 out << "0.0h /* nan */";
Zhaoming Jianga5988a32022-07-11 15:43:38 +0000137 } else {
138 out << FloatToString(value) << "h";
Zhaoming Jianga5988a32022-07-11 15:43:38 +0000139 }
140}
141
Ryan Harrisondbc13af2022-02-21 15:19:07 +0000142// Helper for writing " : register(RX, spaceY)", where R is the register, X is
143// the binding point binding value, and Y is the binding point group value.
144struct RegisterAndSpace {
dan sinclairacdf6e12022-08-24 15:47:25 +0000145 RegisterAndSpace(char r, sem::BindingPoint bp) : reg(r), binding_point(bp) {}
Ryan Harrisondbc13af2022-02-21 15:19:07 +0000146
dan sinclair41e4d9a2022-05-01 14:40:55 +0000147 const char reg;
dan sinclairacdf6e12022-08-24 15:47:25 +0000148 sem::BindingPoint const binding_point;
Ryan Harrisondbc13af2022-02-21 15:19:07 +0000149};
150
dan sinclair2b9d5b32023-02-28 14:49:25 +0000151utils::StringStream& operator<<(utils::StringStream& s, const RegisterAndSpace& rs) {
Peng Huangc00ff7f2023-03-31 17:55:19 +0000152 s << " : register(" << rs.reg << rs.binding_point.binding;
153 // Omit the space if it's 0, as it's the default.
154 // SM 5.0 doesn't support spaces, so we don't emit them if group is 0 for better compatibility.
155 if (rs.binding_point.group == 0) {
156 s << ")";
157 } else {
158 s << ", space" << rs.binding_point.group << ")";
159 }
dan sinclair41e4d9a2022-05-01 14:40:55 +0000160 return s;
Ryan Harrisondbc13af2022-02-21 15:19:07 +0000161}
162
Ryan Harrisondbc13af2022-02-21 15:19:07 +0000163} // namespace
164
165SanitizedResult::SanitizedResult() = default;
166SanitizedResult::~SanitizedResult() = default;
167SanitizedResult::SanitizedResult(SanitizedResult&&) = default;
168
Antonio Maiorano7eaab382022-04-11 16:33:30 +0000169SanitizedResult Sanitize(const Program* in, const Options& options) {
dan sinclair41e4d9a2022-05-01 14:40:55 +0000170 transform::Manager manager;
James Price0e6534e2023-05-17 01:21:45 +0000171 transform::DataMap data;
Ryan Harrisondbc13af2022-02-21 15:19:07 +0000172
James Priceb4acbb82023-05-11 21:27:16 +0000173 manager.Add<ast::transform::DisableUniformityAnalysis>();
James Price791b4352022-05-11 13:50:33 +0000174
Ben Clayton46ee6392022-11-09 22:04:11 +0000175 // ExpandCompoundAssignment must come before BuiltinPolyfill
James Priceb4acbb82023-05-11 21:27:16 +0000176 manager.Add<ast::transform::ExpandCompoundAssignment>();
Ben Clayton46ee6392022-11-09 22:04:11 +0000177
James Priceb4acbb82023-05-11 21:27:16 +0000178 manager.Add<ast::transform::Unshadow>(); // Must come before DirectVariableAccess
Ben Clayton03de0e82023-03-02 20:48:48 +0000179
Ben Clayton03de0e82023-03-02 20:48:48 +0000180 // LocalizeStructArrayAssignment must come after:
181 // * SimplifyPointers, because it assumes assignment to arrays in structs are
182 // done directly, not indirectly.
183 // TODO(crbug.com/tint/1340): See if we can get rid of the duplicate
184 // SimplifyPointers transform. Can't do it right now because
185 // LocalizeStructArrayAssignment introduces pointers.
James Priceb4acbb82023-05-11 21:27:16 +0000186 manager.Add<ast::transform::SimplifyPointers>();
187 manager.Add<ast::transform::LocalizeStructArrayAssignment>();
Ben Clayton03de0e82023-03-02 20:48:48 +0000188
James Priceb4acbb82023-05-11 21:27:16 +0000189 manager.Add<ast::transform::PromoteSideEffectsToDecl>();
Ben Clayton03de0e82023-03-02 20:48:48 +0000190
191 if (!options.disable_robustness) {
Ben Clayton8525ff22023-03-06 21:05:01 +0000192 // Robustness must come after PromoteSideEffectsToDecl
193 // Robustness must come before BuiltinPolyfill and CanonicalizeEntryPointIO
James Priceb4acbb82023-05-11 21:27:16 +0000194 manager.Add<ast::transform::Robustness>();
Jiawei Shao455e4b82023-06-10 00:32:22 +0000195
196 ast::transform::Robustness::Config config = {};
197 config.bindings_ignored = std::unordered_set<sem::BindingPoint>(
198 options.binding_points_ignored_in_robustness_transform.cbegin(),
199 options.binding_points_ignored_in_robustness_transform.cend());
200 data.Add<ast::transform::Robustness::Config>(config);
Ben Clayton03de0e82023-03-02 20:48:48 +0000201 }
202
dan sinclair04d61c82023-04-11 23:02:45 +0000203 // Note: it is more efficient for MultiplanarExternalTexture to come after Robustness
James Priceb4acbb82023-05-11 21:27:16 +0000204 data.Add<ast::transform::MultiplanarExternalTexture::NewBindingPoints>(
dan sinclair04d61c82023-04-11 23:02:45 +0000205 options.external_texture_options.bindings_map);
James Priceb4acbb82023-05-11 21:27:16 +0000206 manager.Add<ast::transform::MultiplanarExternalTexture>();
Ben Clayton03de0e82023-03-02 20:48:48 +0000207
dan sinclair39d40652023-03-15 13:41:46 +0000208 // BindingRemapper must come after MultiplanarExternalTexture
James Priceb4acbb82023-05-11 21:27:16 +0000209 manager.Add<ast::transform::BindingRemapper>();
210 data.Add<ast::transform::BindingRemapper::Remappings>(
dan sinclair39d40652023-03-15 13:41:46 +0000211 options.binding_remapper_options.binding_points,
212 options.binding_remapper_options.access_controls,
213 options.binding_remapper_options.allow_collisions);
214
dan sinclair41e4d9a2022-05-01 14:40:55 +0000215 { // Builtin polyfills
James Priceb4acbb82023-05-11 21:27:16 +0000216 ast::transform::BuiltinPolyfill::Builtins polyfills;
217 polyfills.acosh = ast::transform::BuiltinPolyfill::Level::kFull;
dan sinclaird23f2962022-06-28 15:27:44 +0000218 polyfills.asinh = true;
James Priceb4acbb82023-05-11 21:27:16 +0000219 polyfills.atanh = ast::transform::BuiltinPolyfill::Level::kFull;
Ben Clayton02f04d92022-11-03 19:15:17 +0000220 polyfills.bitshift_modulo = true;
Ben Clayton6dbb4632022-10-31 17:54:49 +0000221 polyfills.clamp_int = true;
dan sinclair41e4d9a2022-05-01 14:40:55 +0000222 // TODO(crbug.com/tint/1449): Some of these can map to HLSL's `firstbitlow`
223 // and `firstbithigh`.
Ben Claytoncc3f8512023-03-09 21:26:12 +0000224 polyfills.conv_f32_to_iu32 = true;
dan sinclair41e4d9a2022-05-01 14:40:55 +0000225 polyfills.count_leading_zeros = true;
226 polyfills.count_trailing_zeros = true;
James Priceb4acbb82023-05-11 21:27:16 +0000227 polyfills.extract_bits = ast::transform::BuiltinPolyfill::Level::kFull;
dan sinclair41e4d9a2022-05-01 14:40:55 +0000228 polyfills.first_leading_bit = true;
229 polyfills.first_trailing_bit = true;
James Priceb4acbb82023-05-11 21:27:16 +0000230 polyfills.insert_bits = ast::transform::BuiltinPolyfill::Level::kFull;
Ben Clayton46ee6392022-11-09 22:04:11 +0000231 polyfills.int_div_mod = true;
Antonio Maioranoee665a42023-02-14 16:12:59 +0000232 polyfills.precise_float_mod = true;
Zhaoming Jiang04529be2023-02-27 02:59:50 +0000233 polyfills.reflect_vec2_f32 = options.polyfill_reflect_vec2_f32;
Ben Claytonc4ebf2c2022-09-22 22:59:16 +0000234 polyfills.texture_sample_base_clamp_to_edge_2d_f32 = true;
James Price128980f2023-01-06 02:25:06 +0000235 polyfills.workgroup_uniform_load = true;
James Priceb4acbb82023-05-11 21:27:16 +0000236 data.Add<ast::transform::BuiltinPolyfill::Config>(polyfills);
237 manager.Add<ast::transform::BuiltinPolyfill>(); // Must come before DirectVariableAccess
dan sinclair41e4d9a2022-05-01 14:40:55 +0000238 }
Ben Clayton27aa57c2022-02-22 23:13:39 +0000239
James Priceb4acbb82023-05-11 21:27:16 +0000240 manager.Add<ast::transform::DirectVariableAccess>();
Antonio Maioranofa00fe92023-05-03 15:30:54 +0000241
dan sinclair41e4d9a2022-05-01 14:40:55 +0000242 if (!options.disable_workgroup_init) {
243 // ZeroInitWorkgroupMemory must come before CanonicalizeEntryPointIO as
244 // ZeroInitWorkgroupMemory may inject new builtin parameters.
James Priceb4acbb82023-05-11 21:27:16 +0000245 manager.Add<ast::transform::ZeroInitWorkgroupMemory>();
dan sinclair41e4d9a2022-05-01 14:40:55 +0000246 }
Ben Clayton03de0e82023-03-02 20:48:48 +0000247
248 // CanonicalizeEntryPointIO must come after Robustness
James Priceb4acbb82023-05-11 21:27:16 +0000249 manager.Add<ast::transform::CanonicalizeEntryPointIO>();
shrekshaof9c66332022-11-22 21:36:27 +0000250
shrekshao8f0607a2023-04-18 01:34:41 +0000251 if (options.truncate_interstage_variables) {
shrekshaof9c66332022-11-22 21:36:27 +0000252 // When interstage_locations is empty, it means there's no user-defined interstage variables
shrekshao8f0607a2023-04-18 01:34:41 +0000253 // being used in the next stage. Still, HLSL compiler register mismatch could happen, if
254 // there's builtin inputs used in the next stage. So we still run
255 // TruncateInterstageVariables transform.
shrekshaof9c66332022-11-22 21:36:27 +0000256
257 // TruncateInterstageVariables itself will skip when interstage_locations matches exactly
258 // with the current stage output.
259
260 // Build the config for internal TruncateInterstageVariables transform.
James Priceb4acbb82023-05-11 21:27:16 +0000261 ast::transform::TruncateInterstageVariables::Config truncate_interstage_variables_cfg;
shrekshaof9c66332022-11-22 21:36:27 +0000262 truncate_interstage_variables_cfg.interstage_locations =
263 std::move(options.interstage_locations);
James Priceb4acbb82023-05-11 21:27:16 +0000264 manager.Add<ast::transform::TruncateInterstageVariables>();
265 data.Add<ast::transform::TruncateInterstageVariables::Config>(
shrekshaof9c66332022-11-22 21:36:27 +0000266 std::move(truncate_interstage_variables_cfg));
267 }
268
dan sinclair41e4d9a2022-05-01 14:40:55 +0000269 // NumWorkgroupsFromUniform must come after CanonicalizeEntryPointIO, as it
270 // assumes that num_workgroups builtins only appear as struct members and are
271 // only accessed directly via member accessors.
James Priceb4acbb82023-05-11 21:27:16 +0000272 manager.Add<ast::transform::NumWorkgroupsFromUniform>();
273 manager.Add<ast::transform::VectorizeScalarMatrixInitializers>();
274 manager.Add<ast::transform::SimplifyPointers>();
275 manager.Add<ast::transform::RemovePhonies>();
James Price744d0eb2022-11-09 19:58:59 +0000276
Ben Clayton03de0e82023-03-02 20:48:48 +0000277 // Build the config for the internal ArrayLengthFromUniform transform.
278 auto& array_length_from_uniform = options.array_length_from_uniform;
James Priceb4acbb82023-05-11 21:27:16 +0000279 ast::transform::ArrayLengthFromUniform::Config array_length_from_uniform_cfg(
Ben Clayton03de0e82023-03-02 20:48:48 +0000280 array_length_from_uniform.ubo_binding);
281 array_length_from_uniform_cfg.bindpoint_to_size_index =
282 array_length_from_uniform.bindpoint_to_size_index;
283
James Price744d0eb2022-11-09 19:58:59 +0000284 // DemoteToHelper must come after CanonicalizeEntryPointIO, PromoteSideEffectsToDecl, and
285 // ExpandCompoundAssignment.
286 // TODO(crbug.com/tint/1752): This is only necessary when FXC is being used.
James Priceb4acbb82023-05-11 21:27:16 +0000287 manager.Add<ast::transform::DemoteToHelper>();
James Price744d0eb2022-11-09 19:58:59 +0000288
Ben Clayton559e5a22023-04-17 14:24:58 +0000289 // ArrayLengthFromUniform must come after SimplifyPointers as it assumes that the form of the
290 // array length argument is &var.array.
James Priceb4acbb82023-05-11 21:27:16 +0000291 manager.Add<ast::transform::ArrayLengthFromUniform>();
292 data.Add<ast::transform::ArrayLengthFromUniform::Config>(
293 std::move(array_length_from_uniform_cfg));
dan sinclair41e4d9a2022-05-01 14:40:55 +0000294 // DecomposeMemoryAccess must come after:
Ben Clayton559e5a22023-04-17 14:24:58 +0000295 // * SimplifyPointers, as we cannot take the address of calls to
296 // DecomposeMemoryAccess::Intrinsic and we need to fold away the address-of and dereferences
297 // of `*(&(intrinsic_load()))` expressions.
dan sinclair41e4d9a2022-05-01 14:40:55 +0000298 // * RemovePhonies, as phonies can be assigned a pointer to a
299 // non-constructible buffer, or dynamic array, which DMA cannot cope with.
James Priceb4acbb82023-05-11 21:27:16 +0000300 manager.Add<ast::transform::DecomposeMemoryAccess>();
dan sinclair41e4d9a2022-05-01 14:40:55 +0000301 // CalculateArrayLength must come after DecomposeMemoryAccess, as
302 // DecomposeMemoryAccess special-cases the arrayLength() intrinsic, which
303 // will be transformed by CalculateArrayLength
James Priceb4acbb82023-05-11 21:27:16 +0000304 manager.Add<ast::transform::CalculateArrayLength>();
305 manager.Add<ast::transform::PromoteInitializersToLet>();
Ryan Harrisondbc13af2022-02-21 15:19:07 +0000306
James Priceb4acbb82023-05-11 21:27:16 +0000307 manager.Add<ast::transform::RemoveContinueInSwitch>();
Antonio Maioranob3497102022-03-31 15:02:25 +0000308
James Priceb4acbb82023-05-11 21:27:16 +0000309 manager.Add<ast::transform::AddEmptyEntryPoint>();
Ryan Harrisondbc13af2022-02-21 15:19:07 +0000310
James Priceb4acbb82023-05-11 21:27:16 +0000311 data.Add<ast::transform::CanonicalizeEntryPointIO::Config>(
312 ast::transform::CanonicalizeEntryPointIO::ShaderStyle::kHlsl);
313 data.Add<ast::transform::NumWorkgroupsFromUniform::Config>(options.root_constant_binding_point);
Ryan Harrisondbc13af2022-02-21 15:19:07 +0000314
dan sinclair41e4d9a2022-05-01 14:40:55 +0000315 SanitizedResult result;
James Price0e6534e2023-05-17 01:21:45 +0000316 transform::DataMap outputs;
317 result.program = manager.Run(in, data, outputs);
318 if (auto* res = outputs.Get<ast::transform::ArrayLengthFromUniform::Result>()) {
dan sinclair41e4d9a2022-05-01 14:40:55 +0000319 result.used_array_length_from_uniform_indices = std::move(res->used_size_indices);
320 }
321 return result;
Ryan Harrisondbc13af2022-02-21 15:19:07 +0000322}
323
324GeneratorImpl::GeneratorImpl(const Program* program) : TextGenerator(program) {}
325
326GeneratorImpl::~GeneratorImpl() = default;
327
328bool GeneratorImpl::Generate() {
Ben Clayton1a567782022-10-14 13:38:27 +0000329 if (!CheckSupportedExtensions("HLSL", program_->AST(), diagnostics_,
330 utils::Vector{
dan sinclaire4039c72023-02-17 21:58:59 +0000331 builtin::Extension::kChromiumDisableUniformityAnalysis,
332 builtin::Extension::kChromiumExperimentalDp4A,
333 builtin::Extension::kChromiumExperimentalFullPtrParameters,
334 builtin::Extension::kChromiumExperimentalPushConstant,
335 builtin::Extension::kF16,
Ben Clayton1a567782022-10-14 13:38:27 +0000336 })) {
337 return false;
338 }
339
dan sinclair12fa3032023-04-19 23:52:33 +0000340 const utils::TypeInfo* last_kind = nullptr;
dan sinclair41e4d9a2022-05-01 14:40:55 +0000341 size_t last_padding_line = 0;
Ryan Harrisondbc13af2022-02-21 15:19:07 +0000342
dan sinclair41e4d9a2022-05-01 14:40:55 +0000343 auto* mod = builder_.Sem().Module();
344 for (auto* decl : mod->DependencyOrderedDeclarations()) {
James Price98dc5a82023-02-04 12:20:55 +0000345 if (decl->IsAnyOf<ast::Alias, ast::DiagnosticDirective, ast::Enable, ast::ConstAssert>()) {
Ben Claytonb4744ac2022-08-03 07:01:08 +0000346 continue; // These are not emitted.
James Price791b4352022-05-11 13:50:33 +0000347 }
Ryan Harrisondbc13af2022-02-21 15:19:07 +0000348
dan sinclair41e4d9a2022-05-01 14:40:55 +0000349 // Emit a new line between declarations if the type of declaration has
350 // changed, or we're about to emit a function
351 auto* kind = &decl->TypeInfo();
352 if (current_buffer_->lines.size() != last_padding_line) {
353 if (last_kind && (last_kind != kind || decl->Is<ast::Function>())) {
354 line();
355 last_padding_line = current_buffer_->lines.size();
Ryan Harrisondbc13af2022-02-21 15:19:07 +0000356 }
Ryan Harrisondbc13af2022-02-21 15:19:07 +0000357 }
dan sinclair41e4d9a2022-05-01 14:40:55 +0000358 last_kind = kind;
Ryan Harrisondbc13af2022-02-21 15:19:07 +0000359
dan sinclair41e4d9a2022-05-01 14:40:55 +0000360 bool ok = Switch(
361 decl,
362 [&](const ast::Variable* global) { //
363 return EmitGlobalVariable(global);
364 },
365 [&](const ast::Struct* str) {
366 auto* ty = builder_.Sem().Get(str);
dan sinclairff7cf212022-10-03 14:05:23 +0000367 auto address_space_uses = ty->AddressSpaceUsage();
368 if (address_space_uses.size() !=
dan sinclair2a651632023-02-19 04:03:55 +0000369 (address_space_uses.count(builtin::AddressSpace::kStorage) +
370 address_space_uses.count(builtin::AddressSpace::kUniform))) {
dan sinclair41e4d9a2022-05-01 14:40:55 +0000371 // The structure is used as something other than a storage buffer or
372 // uniform buffer, so it needs to be emitted.
373 // Storage buffer are read and written to via a ByteAddressBuffer
374 // instead of true structure.
375 // Structures used as uniform buffer are read from an array of
376 // vectors instead of true structure.
377 return EmitStructType(current_buffer_, ty);
Ryan Harrisondbc13af2022-02-21 15:19:07 +0000378 }
dan sinclair41e4d9a2022-05-01 14:40:55 +0000379 return true;
380 },
381 [&](const ast::Function* func) {
382 if (func->IsEntryPoint()) {
383 return EmitEntryPointFunction(func);
384 }
385 return EmitFunction(func);
386 },
dan sinclair41e4d9a2022-05-01 14:40:55 +0000387 [&](Default) {
388 TINT_ICE(Writer, diagnostics_)
389 << "unhandled module-scope declaration: " << decl->TypeInfo().name;
390 return false;
391 });
392
393 if (!ok) {
394 return false;
395 }
396 }
397
398 if (!helpers_.lines.empty()) {
399 current_buffer_->Insert(helpers_, 0, 0);
400 }
401
402 return true;
403}
404
405bool GeneratorImpl::EmitDynamicVectorAssignment(const ast::AssignmentStatement* stmt,
dan sinclair0e780da2022-12-08 22:21:24 +0000406 const type::Vector* vec) {
dan sinclair41e4d9a2022-05-01 14:40:55 +0000407 auto name = utils::GetOrCreate(dynamic_vector_write_, vec, [&]() -> std::string {
408 std::string fn;
409 {
dan sinclair2b9d5b32023-02-28 14:49:25 +0000410 utils::StringStream ss;
dan sinclair2a651632023-02-19 04:03:55 +0000411 if (!EmitType(ss, vec, tint::builtin::AddressSpace::kUndefined,
dan sinclairb6cc4cb2023-02-19 04:01:29 +0000412 builtin::Access::kUndefined, "")) {
dan sinclair41e4d9a2022-05-01 14:40:55 +0000413 return "";
Ryan Harrisondbc13af2022-02-21 15:19:07 +0000414 }
dan sinclair41e4d9a2022-05-01 14:40:55 +0000415 fn = UniqueIdentifier("set_" + ss.str());
416 }
417 {
418 auto out = line(&helpers_);
419 out << "void " << fn << "(inout ";
dan sinclair2a651632023-02-19 04:03:55 +0000420 if (!EmitTypeAndName(out, vec, builtin::AddressSpace::kUndefined,
dan sinclairb6cc4cb2023-02-19 04:01:29 +0000421 builtin::Access::kUndefined, "vec")) {
dan sinclair41e4d9a2022-05-01 14:40:55 +0000422 return "";
423 }
424 out << ", int idx, ";
dan sinclair2a651632023-02-19 04:03:55 +0000425 if (!EmitTypeAndName(out, vec->type(), builtin::AddressSpace::kUndefined,
dan sinclairb6cc4cb2023-02-19 04:01:29 +0000426 builtin::Access::kUndefined, "val")) {
dan sinclair41e4d9a2022-05-01 14:40:55 +0000427 return "";
428 }
429 out << ") {";
430 }
431 {
432 ScopedIndent si(&helpers_);
433 auto out = line(&helpers_);
434 switch (vec->Width()) {
435 case 2:
436 out << "vec = (idx.xx == int2(0, 1)) ? val.xx : vec;";
437 break;
438 case 3:
439 out << "vec = (idx.xxx == int3(0, 1, 2)) ? val.xxx : vec;";
440 break;
441 case 4:
442 out << "vec = (idx.xxxx == int4(0, 1, 2, 3)) ? val.xxxx : vec;";
443 break;
444 default:
Ben Claytondcdf66e2022-06-17 12:48:51 +0000445 TINT_UNREACHABLE(Writer, diagnostics_)
dan sinclair41e4d9a2022-05-01 14:40:55 +0000446 << "invalid vector size " << vec->Width();
447 break;
448 }
Ryan Harrisondbc13af2022-02-21 15:19:07 +0000449 }
450 line(&helpers_) << "}";
451 line(&helpers_);
452 return fn;
dan sinclair41e4d9a2022-05-01 14:40:55 +0000453 });
Ryan Harrisondbc13af2022-02-21 15:19:07 +0000454
dan sinclair41e4d9a2022-05-01 14:40:55 +0000455 if (name.empty()) {
Ryan Harrisondbc13af2022-02-21 15:19:07 +0000456 return false;
Ryan Harrisondbc13af2022-02-21 15:19:07 +0000457 }
458
dan sinclair41e4d9a2022-05-01 14:40:55 +0000459 auto* ast_access_expr = stmt->lhs->As<ast::IndexAccessorExpression>();
Ryan Harrisondbc13af2022-02-21 15:19:07 +0000460
dan sinclair41e4d9a2022-05-01 14:40:55 +0000461 auto out = line();
462 out << name << "(";
463 if (!EmitExpression(out, ast_access_expr->object)) {
464 return false;
465 }
466 out << ", ";
467 if (!EmitExpression(out, ast_access_expr->index)) {
468 return false;
469 }
470 out << ", ";
471 if (!EmitExpression(out, stmt->rhs)) {
472 return false;
473 }
474 out << ");";
Ryan Harrisondbc13af2022-02-21 15:19:07 +0000475
dan sinclair41e4d9a2022-05-01 14:40:55 +0000476 return true;
477}
Ryan Harrisondbc13af2022-02-21 15:19:07 +0000478
dan sinclair41e4d9a2022-05-01 14:40:55 +0000479bool GeneratorImpl::EmitDynamicMatrixVectorAssignment(const ast::AssignmentStatement* stmt,
dan sinclair0e780da2022-12-08 22:21:24 +0000480 const type::Matrix* mat) {
dan sinclair41e4d9a2022-05-01 14:40:55 +0000481 auto name = utils::GetOrCreate(dynamic_matrix_vector_write_, mat, [&]() -> std::string {
482 std::string fn;
483 {
dan sinclair2b9d5b32023-02-28 14:49:25 +0000484 utils::StringStream ss;
dan sinclair2a651632023-02-19 04:03:55 +0000485 if (!EmitType(ss, mat, tint::builtin::AddressSpace::kUndefined,
dan sinclairb6cc4cb2023-02-19 04:01:29 +0000486 builtin::Access::kUndefined, "")) {
dan sinclair41e4d9a2022-05-01 14:40:55 +0000487 return "";
488 }
489 fn = UniqueIdentifier("set_vector_" + ss.str());
490 }
491 {
492 auto out = line(&helpers_);
493 out << "void " << fn << "(inout ";
dan sinclair2a651632023-02-19 04:03:55 +0000494 if (!EmitTypeAndName(out, mat, builtin::AddressSpace::kUndefined,
dan sinclairb6cc4cb2023-02-19 04:01:29 +0000495 builtin::Access::kUndefined, "mat")) {
dan sinclair41e4d9a2022-05-01 14:40:55 +0000496 return "";
497 }
498 out << ", int col, ";
dan sinclair2a651632023-02-19 04:03:55 +0000499 if (!EmitTypeAndName(out, mat->ColumnType(), builtin::AddressSpace::kUndefined,
dan sinclairb6cc4cb2023-02-19 04:01:29 +0000500 builtin::Access::kUndefined, "val")) {
dan sinclair41e4d9a2022-05-01 14:40:55 +0000501 return "";
502 }
503 out << ") {";
504 }
505 {
506 ScopedIndent si(&helpers_);
507 line(&helpers_) << "switch (col) {";
508 {
509 ScopedIndent si2(&helpers_);
510 for (uint32_t i = 0; i < mat->columns(); ++i) {
511 line(&helpers_) << "case " << i << ": mat[" << i << "] = val; break;";
512 }
513 }
514 line(&helpers_) << "}";
515 }
516 line(&helpers_) << "}";
517 line(&helpers_);
518 return fn;
519 });
520
521 if (name.empty()) {
522 return false;
523 }
524
525 auto* ast_access_expr = stmt->lhs->As<ast::IndexAccessorExpression>();
526
527 auto out = line();
528 out << name << "(";
529 if (!EmitExpression(out, ast_access_expr->object)) {
530 return false;
531 }
532 out << ", ";
533 if (!EmitExpression(out, ast_access_expr->index)) {
534 return false;
535 }
536 out << ", ";
537 if (!EmitExpression(out, stmt->rhs)) {
538 return false;
539 }
540 out << ");";
541
542 return true;
543}
544
545bool GeneratorImpl::EmitDynamicMatrixScalarAssignment(const ast::AssignmentStatement* stmt,
dan sinclair0e780da2022-12-08 22:21:24 +0000546 const type::Matrix* mat) {
Antonio Maioranof031ca22023-02-02 22:16:42 +0000547 auto* lhs_row_access = stmt->lhs->As<ast::IndexAccessorExpression>();
548 auto* lhs_col_access = lhs_row_access->object->As<ast::IndexAccessorExpression>();
dan sinclair41e4d9a2022-05-01 14:40:55 +0000549
550 auto name = utils::GetOrCreate(dynamic_matrix_scalar_write_, mat, [&]() -> std::string {
551 std::string fn;
552 {
dan sinclair2b9d5b32023-02-28 14:49:25 +0000553 utils::StringStream ss;
dan sinclair2a651632023-02-19 04:03:55 +0000554 if (!EmitType(ss, mat, tint::builtin::AddressSpace::kUndefined,
dan sinclairb6cc4cb2023-02-19 04:01:29 +0000555 builtin::Access::kUndefined, "")) {
dan sinclair41e4d9a2022-05-01 14:40:55 +0000556 return "";
557 }
558 fn = UniqueIdentifier("set_scalar_" + ss.str());
559 }
560 {
561 auto out = line(&helpers_);
562 out << "void " << fn << "(inout ";
dan sinclair2a651632023-02-19 04:03:55 +0000563 if (!EmitTypeAndName(out, mat, builtin::AddressSpace::kUndefined,
dan sinclairb6cc4cb2023-02-19 04:01:29 +0000564 builtin::Access::kUndefined, "mat")) {
dan sinclair41e4d9a2022-05-01 14:40:55 +0000565 return "";
566 }
567 out << ", int col, int row, ";
dan sinclair2a651632023-02-19 04:03:55 +0000568 if (!EmitTypeAndName(out, mat->type(), builtin::AddressSpace::kUndefined,
dan sinclairb6cc4cb2023-02-19 04:01:29 +0000569 builtin::Access::kUndefined, "val")) {
dan sinclair41e4d9a2022-05-01 14:40:55 +0000570 return "";
571 }
572 out << ") {";
573 }
574 {
575 ScopedIndent si(&helpers_);
576 line(&helpers_) << "switch (col) {";
577 {
578 ScopedIndent si2(&helpers_);
dan sinclair41e4d9a2022-05-01 14:40:55 +0000579 for (uint32_t i = 0; i < mat->columns(); ++i) {
580 line(&helpers_) << "case " << i << ":";
581 {
582 auto vec_name = "mat[" + std::to_string(i) + "]";
583 ScopedIndent si3(&helpers_);
584 {
585 auto out = line(&helpers_);
586 switch (mat->rows()) {
587 case 2:
588 out << vec_name
589 << " = (row.xx == int2(0, 1)) ? val.xx : " << vec_name
590 << ";";
591 break;
592 case 3:
593 out << vec_name
594 << " = (row.xxx == int3(0, 1, 2)) ? val.xxx : " << vec_name
595 << ";";
596 break;
597 case 4:
598 out << vec_name
599 << " = (row.xxxx == int4(0, 1, 2, 3)) ? val.xxxx : "
600 << vec_name << ";";
601 break;
Antonio Maioranof031ca22023-02-02 22:16:42 +0000602 default: {
603 auto* vec = TypeOf(lhs_row_access->object)
604 ->UnwrapRef()
605 ->As<type::Vector>();
Ben Claytondcdf66e2022-06-17 12:48:51 +0000606 TINT_UNREACHABLE(Writer, diagnostics_)
dan sinclair41e4d9a2022-05-01 14:40:55 +0000607 << "invalid vector size " << vec->Width();
608 break;
Antonio Maioranof031ca22023-02-02 22:16:42 +0000609 }
dan sinclair41e4d9a2022-05-01 14:40:55 +0000610 }
611 }
612 line(&helpers_) << "break;";
613 }
614 }
615 }
616 line(&helpers_) << "}";
617 }
618 line(&helpers_) << "}";
619 line(&helpers_);
620 return fn;
621 });
622
623 if (name.empty()) {
624 return false;
625 }
626
627 auto out = line();
628 out << name << "(";
Antonio Maioranof031ca22023-02-02 22:16:42 +0000629 if (!EmitExpression(out, lhs_col_access->object)) {
dan sinclair41e4d9a2022-05-01 14:40:55 +0000630 return false;
631 }
632 out << ", ";
633 if (!EmitExpression(out, lhs_col_access->index)) {
634 return false;
635 }
636 out << ", ";
637 if (!EmitExpression(out, lhs_row_access->index)) {
638 return false;
639 }
640 out << ", ";
641 if (!EmitExpression(out, stmt->rhs)) {
642 return false;
643 }
644 out << ");";
645
646 return true;
647}
648
dan sinclair2b9d5b32023-02-28 14:49:25 +0000649bool GeneratorImpl::EmitIndexAccessor(utils::StringStream& out,
650 const ast::IndexAccessorExpression* expr) {
dan sinclair41e4d9a2022-05-01 14:40:55 +0000651 if (!EmitExpression(out, expr->object)) {
652 return false;
653 }
654 out << "[";
655
656 if (!EmitExpression(out, expr->index)) {
657 return false;
658 }
659 out << "]";
660
661 return true;
662}
663
dan sinclair2b9d5b32023-02-28 14:49:25 +0000664bool GeneratorImpl::EmitBitcast(utils::StringStream& out, const ast::BitcastExpression* expr) {
dan sinclair41e4d9a2022-05-01 14:40:55 +0000665 auto* type = TypeOf(expr);
dan sinclair0e780da2022-12-08 22:21:24 +0000666 if (auto* vec = type->UnwrapRef()->As<type::Vector>()) {
dan sinclair41e4d9a2022-05-01 14:40:55 +0000667 type = vec->type();
668 }
669
670 if (!type->is_integer_scalar() && !type->is_float_scalar()) {
dan sinclaird026e132023-04-18 19:38:25 +0000671 diagnostics_.add_error(diag::System::Writer,
672 "Unable to do bitcast to type " + type->FriendlyName());
dan sinclair41e4d9a2022-05-01 14:40:55 +0000673 return false;
674 }
675
676 out << "as";
dan sinclair2a651632023-02-19 04:03:55 +0000677 if (!EmitType(out, type, builtin::AddressSpace::kUndefined, builtin::Access::kReadWrite, "")) {
dan sinclair41e4d9a2022-05-01 14:40:55 +0000678 return false;
679 }
Ryan Harrisondbc13af2022-02-21 15:19:07 +0000680 out << "(";
dan sinclair41e4d9a2022-05-01 14:40:55 +0000681 if (!EmitExpression(out, expr->expr)) {
682 return false;
Ryan Harrisondbc13af2022-02-21 15:19:07 +0000683 }
684 out << ")";
685 return true;
dan sinclair41e4d9a2022-05-01 14:40:55 +0000686}
Ryan Harrisondbc13af2022-02-21 15:19:07 +0000687
dan sinclair41e4d9a2022-05-01 14:40:55 +0000688bool GeneratorImpl::EmitAssign(const ast::AssignmentStatement* stmt) {
689 if (auto* lhs_access = stmt->lhs->As<ast::IndexAccessorExpression>()) {
690 // BUG(crbug.com/tint/1333): work around assignment of scalar to matrices
691 // with at least one dynamic index
692 if (auto* lhs_sub_access = lhs_access->object->As<ast::IndexAccessorExpression>()) {
dan sinclair0e780da2022-12-08 22:21:24 +0000693 if (auto* mat = TypeOf(lhs_sub_access->object)->UnwrapRef()->As<type::Matrix>()) {
Ben Clayton0b4a2f12023-02-05 22:59:40 +0000694 auto* rhs_row_idx_sem = builder_.Sem().GetVal(lhs_access->index);
695 auto* rhs_col_idx_sem = builder_.Sem().GetVal(lhs_sub_access->index);
Antonio Maioranof031ca22023-02-02 22:16:42 +0000696 if (!rhs_row_idx_sem->ConstantValue() || !rhs_col_idx_sem->ConstantValue()) {
dan sinclair41e4d9a2022-05-01 14:40:55 +0000697 return EmitDynamicMatrixScalarAssignment(stmt, mat);
698 }
699 }
700 }
701 // BUG(crbug.com/tint/1333): work around assignment of vector to matrices
702 // with dynamic indices
703 const auto* lhs_access_type = TypeOf(lhs_access->object)->UnwrapRef();
dan sinclair0e780da2022-12-08 22:21:24 +0000704 if (auto* mat = lhs_access_type->As<type::Matrix>()) {
Ben Clayton0b4a2f12023-02-05 22:59:40 +0000705 auto* lhs_index_sem = builder_.Sem().GetVal(lhs_access->index);
Ben Claytonaa037ac2022-06-29 19:07:30 +0000706 if (!lhs_index_sem->ConstantValue()) {
dan sinclair41e4d9a2022-05-01 14:40:55 +0000707 return EmitDynamicMatrixVectorAssignment(stmt, mat);
708 }
709 }
710 // BUG(crbug.com/tint/534): work around assignment to vectors with dynamic
711 // indices
dan sinclair0e780da2022-12-08 22:21:24 +0000712 if (auto* vec = lhs_access_type->As<type::Vector>()) {
Ben Clayton0b4a2f12023-02-05 22:59:40 +0000713 auto* rhs_sem = builder_.Sem().GetVal(lhs_access->index);
Ben Claytonaa037ac2022-06-29 19:07:30 +0000714 if (!rhs_sem->ConstantValue()) {
dan sinclair41e4d9a2022-05-01 14:40:55 +0000715 return EmitDynamicVectorAssignment(stmt, vec);
716 }
717 }
718 }
719
720 auto out = line();
721 if (!EmitExpression(out, stmt->lhs)) {
722 return false;
723 }
724 out << " = ";
725 if (!EmitExpression(out, stmt->rhs)) {
726 return false;
727 }
728 out << ";";
729 return true;
730}
731
dan sinclair2b9d5b32023-02-28 14:49:25 +0000732bool GeneratorImpl::EmitBinary(utils::StringStream& out, const ast::BinaryExpression* expr) {
dan sinclair41e4d9a2022-05-01 14:40:55 +0000733 if (expr->op == ast::BinaryOp::kLogicalAnd || expr->op == ast::BinaryOp::kLogicalOr) {
734 auto name = UniqueIdentifier(kTempNamePrefix);
735
736 {
737 auto pre = line();
738 pre << "bool " << name << " = ";
739 if (!EmitExpression(pre, expr->lhs)) {
740 return false;
741 }
742 pre << ";";
743 }
744
745 if (expr->op == ast::BinaryOp::kLogicalOr) {
746 line() << "if (!" << name << ") {";
747 } else {
748 line() << "if (" << name << ") {";
749 }
750
751 {
752 ScopedIndent si(this);
753 auto pre = line();
754 pre << name << " = ";
755 if (!EmitExpression(pre, expr->rhs)) {
756 return false;
757 }
758 pre << ";";
759 }
760
761 line() << "}";
762
763 out << "(" << name << ")";
764 return true;
765 }
766
767 auto* lhs_type = TypeOf(expr->lhs)->UnwrapRef();
768 auto* rhs_type = TypeOf(expr->rhs)->UnwrapRef();
769 // Multiplying by a matrix requires the use of `mul` in order to get the
770 // type of multiply we desire.
771 if (expr->op == ast::BinaryOp::kMultiply &&
dan sinclair0e780da2022-12-08 22:21:24 +0000772 ((lhs_type->Is<type::Vector>() && rhs_type->Is<type::Matrix>()) ||
773 (lhs_type->Is<type::Matrix>() && rhs_type->Is<type::Vector>()) ||
774 (lhs_type->Is<type::Matrix>() && rhs_type->Is<type::Matrix>()))) {
dan sinclair41e4d9a2022-05-01 14:40:55 +0000775 // Matrices are transposed, so swap LHS and RHS.
776 out << "mul(";
777 if (!EmitExpression(out, expr->rhs)) {
778 return false;
779 }
780 out << ", ";
781 if (!EmitExpression(out, expr->lhs)) {
782 return false;
783 }
784 out << ")";
785
786 return true;
787 }
788
dan sinclairb2ba57b2023-02-28 15:14:09 +0000789 ScopedParen sp(out);
dan sinclair41e4d9a2022-05-01 14:40:55 +0000790
791 if (!EmitExpression(out, expr->lhs)) {
792 return false;
793 }
794 out << " ";
795
796 switch (expr->op) {
797 case ast::BinaryOp::kAnd:
798 out << "&";
799 break;
800 case ast::BinaryOp::kOr:
801 out << "|";
802 break;
803 case ast::BinaryOp::kXor:
804 out << "^";
805 break;
806 case ast::BinaryOp::kLogicalAnd:
807 case ast::BinaryOp::kLogicalOr: {
808 // These are both handled above.
809 TINT_UNREACHABLE(Writer, diagnostics_);
810 return false;
811 }
812 case ast::BinaryOp::kEqual:
813 out << "==";
814 break;
815 case ast::BinaryOp::kNotEqual:
816 out << "!=";
817 break;
818 case ast::BinaryOp::kLessThan:
819 out << "<";
820 break;
821 case ast::BinaryOp::kGreaterThan:
822 out << ">";
823 break;
824 case ast::BinaryOp::kLessThanEqual:
825 out << "<=";
826 break;
827 case ast::BinaryOp::kGreaterThanEqual:
828 out << ">=";
829 break;
830 case ast::BinaryOp::kShiftLeft:
831 out << "<<";
832 break;
833 case ast::BinaryOp::kShiftRight:
834 // TODO(dsinclair): MSL is based on C++14, and >> in C++14 has
835 // implementation-defined behaviour for negative LHS. We may have to
836 // generate extra code to implement WGSL-specified behaviour for negative
837 // LHS.
838 out << R"(>>)";
839 break;
840
841 case ast::BinaryOp::kAdd:
842 out << "+";
843 break;
844 case ast::BinaryOp::kSubtract:
845 out << "-";
846 break;
847 case ast::BinaryOp::kMultiply:
848 out << "*";
849 break;
850 case ast::BinaryOp::kDivide:
851 out << "/";
dan sinclair41e4d9a2022-05-01 14:40:55 +0000852 break;
853 case ast::BinaryOp::kModulo:
854 out << "%";
dan sinclair41e4d9a2022-05-01 14:40:55 +0000855 break;
856 case ast::BinaryOp::kNone:
857 diagnostics_.add_error(diag::System::Writer, "missing binary operation type");
858 return false;
859 }
860 out << " ";
861
862 if (!EmitExpression(out, expr->rhs)) {
863 return false;
864 }
Ryan Harrisondbc13af2022-02-21 15:19:07 +0000865
866 return true;
Ryan Harrisondbc13af2022-02-21 15:19:07 +0000867}
868
Ben Clayton783b1692022-08-02 17:03:35 +0000869bool GeneratorImpl::EmitStatements(utils::VectorRef<const ast::Statement*> stmts) {
dan sinclair41e4d9a2022-05-01 14:40:55 +0000870 for (auto* s : stmts) {
871 if (!EmitStatement(s)) {
872 return false;
873 }
Ryan Harrisondbc13af2022-02-21 15:19:07 +0000874 }
dan sinclair41e4d9a2022-05-01 14:40:55 +0000875 return true;
Ryan Harrisondbc13af2022-02-21 15:19:07 +0000876}
877
Ben Clayton783b1692022-08-02 17:03:35 +0000878bool GeneratorImpl::EmitStatementsWithIndent(utils::VectorRef<const ast::Statement*> stmts) {
dan sinclair41e4d9a2022-05-01 14:40:55 +0000879 ScopedIndent si(this);
880 return EmitStatements(stmts);
Ryan Harrisondbc13af2022-02-21 15:19:07 +0000881}
882
883bool GeneratorImpl::EmitBlock(const ast::BlockStatement* stmt) {
dan sinclair41e4d9a2022-05-01 14:40:55 +0000884 line() << "{";
885 if (!EmitStatementsWithIndent(stmt->statements)) {
886 return false;
887 }
888 line() << "}";
889 return true;
Ryan Harrisondbc13af2022-02-21 15:19:07 +0000890}
891
892bool GeneratorImpl::EmitBreak(const ast::BreakStatement*) {
dan sinclair41e4d9a2022-05-01 14:40:55 +0000893 line() << "break;";
894 return true;
Ryan Harrisondbc13af2022-02-21 15:19:07 +0000895}
896
dan sinclairb8b0c212022-10-20 22:45:50 +0000897bool GeneratorImpl::EmitBreakIf(const ast::BreakIfStatement* b) {
898 auto out = line();
899 out << "if (";
900 if (!EmitExpression(out, b->condition)) {
901 return false;
902 }
903 out << ") { break; }";
904 return true;
905}
906
dan sinclair2b9d5b32023-02-28 14:49:25 +0000907bool GeneratorImpl::EmitCall(utils::StringStream& out, const ast::CallExpression* expr) {
Ben Claytone9f8b092022-06-01 13:14:39 +0000908 auto* call = builder_.Sem().Get<sem::Call>(expr);
dan sinclair41e4d9a2022-05-01 14:40:55 +0000909 auto* target = call->Target();
910 return Switch(
Ben Clayton54a104e2023-02-22 20:04:40 +0000911 target, //
912 [&](const sem::Function* func) { return EmitFunctionCall(out, call, func); },
dan sinclair41e4d9a2022-05-01 14:40:55 +0000913 [&](const sem::Builtin* builtin) { return EmitBuiltinCall(out, call, builtin); },
Ben Clayton54a104e2023-02-22 20:04:40 +0000914 [&](const sem::ValueConversion* conv) { return EmitValueConversion(out, call, conv); },
915 [&](const sem::ValueConstructor* ctor) { return EmitValueConstructor(out, call, ctor); },
dan sinclair41e4d9a2022-05-01 14:40:55 +0000916 [&](Default) {
917 TINT_ICE(Writer, diagnostics_) << "unhandled call target: " << target->TypeInfo().name;
918 return false;
919 });
Ryan Harrisondbc13af2022-02-21 15:19:07 +0000920}
921
dan sinclair2b9d5b32023-02-28 14:49:25 +0000922bool GeneratorImpl::EmitFunctionCall(utils::StringStream& out,
Ryan Harrisondbc13af2022-02-21 15:19:07 +0000923 const sem::Call* call,
924 const sem::Function* func) {
dan sinclair41e4d9a2022-05-01 14:40:55 +0000925 auto* expr = call->Declaration();
Ryan Harrisondbc13af2022-02-21 15:19:07 +0000926
James Priceb4acbb82023-05-11 21:27:16 +0000927 if (ast::HasAttribute<ast::transform::CalculateArrayLength::BufferSizeIntrinsic>(
dan sinclair41e4d9a2022-05-01 14:40:55 +0000928 func->Declaration()->attributes)) {
929 // Special function generated by the CalculateArrayLength transform for
930 // calling X.GetDimensions(Y)
931 if (!EmitExpression(out, call->Arguments()[0]->Declaration())) {
932 return false;
933 }
934 out << ".GetDimensions(";
935 if (!EmitExpression(out, call->Arguments()[1]->Declaration())) {
936 return false;
937 }
938 out << ")";
939 return true;
Ryan Harrisondbc13af2022-02-21 15:19:07 +0000940 }
dan sinclair41e4d9a2022-05-01 14:40:55 +0000941
James Priceb4acbb82023-05-11 21:27:16 +0000942 if (auto* intrinsic = ast::GetAttribute<ast::transform::DecomposeMemoryAccess::Intrinsic>(
dan sinclair41e4d9a2022-05-01 14:40:55 +0000943 func->Declaration()->attributes)) {
dan sinclairff7cf212022-10-03 14:05:23 +0000944 switch (intrinsic->address_space) {
dan sinclair2a651632023-02-19 04:03:55 +0000945 case builtin::AddressSpace::kUniform:
dan sinclair41e4d9a2022-05-01 14:40:55 +0000946 return EmitUniformBufferAccess(out, expr, intrinsic);
dan sinclair2a651632023-02-19 04:03:55 +0000947 case builtin::AddressSpace::kStorage:
Antonio Maiorano08f4b552022-05-31 13:20:28 +0000948 if (!intrinsic->IsAtomic()) {
949 return EmitStorageBufferAccess(out, expr, intrinsic);
950 }
951 break;
dan sinclair41e4d9a2022-05-01 14:40:55 +0000952 default:
953 TINT_UNREACHABLE(Writer, diagnostics_)
dan sinclairff7cf212022-10-03 14:05:23 +0000954 << "unsupported DecomposeMemoryAccess::Intrinsic address space:"
955 << intrinsic->address_space;
dan sinclair41e4d9a2022-05-01 14:40:55 +0000956 return false;
957 }
Ryan Harrisondbc13af2022-02-21 15:19:07 +0000958 }
dan sinclair41e4d9a2022-05-01 14:40:55 +0000959
dan sinclaird026e132023-04-18 19:38:25 +0000960 out << func->Declaration()->name->symbol.Name() << "(";
dan sinclair41e4d9a2022-05-01 14:40:55 +0000961
962 bool first = true;
963 for (auto* arg : call->Arguments()) {
964 if (!first) {
965 out << ", ";
966 }
967 first = false;
968
969 if (!EmitExpression(out, arg->Declaration())) {
970 return false;
971 }
972 }
973
Ryan Harrisondbc13af2022-02-21 15:19:07 +0000974 out << ")";
975 return true;
Ryan Harrisondbc13af2022-02-21 15:19:07 +0000976}
977
dan sinclair2b9d5b32023-02-28 14:49:25 +0000978bool GeneratorImpl::EmitBuiltinCall(utils::StringStream& out,
Ryan Harrisondbc13af2022-02-21 15:19:07 +0000979 const sem::Call* call,
980 const sem::Builtin* builtin) {
Antonio Maioranoab4c0352022-05-20 01:58:40 +0000981 const auto type = builtin->Type();
982
dan sinclair41e4d9a2022-05-01 14:40:55 +0000983 auto* expr = call->Declaration();
984 if (builtin->IsTexture()) {
985 return EmitTextureCall(out, call, builtin);
Ryan Harrisondbc13af2022-02-21 15:19:07 +0000986 }
dan sinclair9543f742023-03-09 01:20:16 +0000987 if (type == builtin::Function::kSelect) {
dan sinclair41e4d9a2022-05-01 14:40:55 +0000988 return EmitSelectCall(out, expr);
Ryan Harrisondbc13af2022-02-21 15:19:07 +0000989 }
dan sinclair9543f742023-03-09 01:20:16 +0000990 if (type == builtin::Function::kModf) {
dan sinclair41e4d9a2022-05-01 14:40:55 +0000991 return EmitModfCall(out, expr, builtin);
992 }
dan sinclair9543f742023-03-09 01:20:16 +0000993 if (type == builtin::Function::kFrexp) {
dan sinclair41e4d9a2022-05-01 14:40:55 +0000994 return EmitFrexpCall(out, expr, builtin);
995 }
dan sinclair9543f742023-03-09 01:20:16 +0000996 if (type == builtin::Function::kDegrees) {
dan sinclair41e4d9a2022-05-01 14:40:55 +0000997 return EmitDegreesCall(out, expr, builtin);
998 }
dan sinclair9543f742023-03-09 01:20:16 +0000999 if (type == builtin::Function::kRadians) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00001000 return EmitRadiansCall(out, expr, builtin);
1001 }
dan sinclair9543f742023-03-09 01:20:16 +00001002 if (type == builtin::Function::kSign) {
dan sinclair70927862023-01-11 13:18:29 +00001003 return EmitSignCall(out, call, builtin);
1004 }
dan sinclair9543f742023-03-09 01:20:16 +00001005 if (type == builtin::Function::kQuantizeToF16) {
Ben Clayton2bea9052022-11-02 00:09:50 +00001006 return EmitQuantizeToF16Call(out, expr, builtin);
1007 }
Antonio Maiorano5cf943e2023-03-27 18:55:25 +00001008 if (type == builtin::Function::kTrunc) {
1009 return EmitTruncCall(out, expr, builtin);
1010 }
dan sinclair41e4d9a2022-05-01 14:40:55 +00001011 if (builtin->IsDataPacking()) {
1012 return EmitDataPackingCall(out, expr, builtin);
1013 }
1014 if (builtin->IsDataUnpacking()) {
1015 return EmitDataUnpackingCall(out, expr, builtin);
1016 }
1017 if (builtin->IsBarrier()) {
1018 return EmitBarrierCall(out, builtin);
1019 }
1020 if (builtin->IsAtomic()) {
1021 return EmitWorkgroupAtomicCall(out, expr, builtin);
1022 }
Jiawei Shaoab975702022-05-13 00:09:56 +00001023 if (builtin->IsDP4a()) {
1024 return EmitDP4aCall(out, expr, builtin);
1025 }
Antonio Maioranoab4c0352022-05-20 01:58:40 +00001026
dan sinclair41e4d9a2022-05-01 14:40:55 +00001027 auto name = generate_builtin_name(builtin);
1028 if (name.empty()) {
1029 return false;
1030 }
Ryan Harrisondbc13af2022-02-21 15:19:07 +00001031
Antonio Maioranoab4c0352022-05-20 01:58:40 +00001032 // Handle single argument builtins that only accept and return uint (not int overload). We need
1033 // to explicitly cast the return value (we also cast the arg for good measure). See
1034 // crbug.com/tint/1550
dan sinclair9543f742023-03-09 01:20:16 +00001035 if (type == builtin::Function::kCountOneBits || type == builtin::Function::kReverseBits) {
Antonio Maioranoab4c0352022-05-20 01:58:40 +00001036 auto* arg = call->Arguments()[0];
Ben Clayton6c337aa2022-12-07 19:25:17 +00001037 if (arg->Type()->UnwrapRef()->is_signed_integer_scalar_or_vector()) {
Antonio Maioranoab4c0352022-05-20 01:58:40 +00001038 out << "asint(" << name << "(asuint(";
1039 if (!EmitExpression(out, arg->Declaration())) {
1040 return false;
1041 }
1042 out << ")))";
1043 return true;
1044 }
1045 }
1046
dan sinclair41e4d9a2022-05-01 14:40:55 +00001047 out << name << "(";
1048
1049 bool first = true;
1050 for (auto* arg : call->Arguments()) {
1051 if (!first) {
1052 out << ", ";
1053 }
1054 first = false;
1055
1056 if (!EmitExpression(out, arg->Declaration())) {
1057 return false;
1058 }
1059 }
1060
1061 out << ")";
Antonio Maioranoab4c0352022-05-20 01:58:40 +00001062
dan sinclair41e4d9a2022-05-01 14:40:55 +00001063 return true;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00001064}
1065
dan sinclair2b9d5b32023-02-28 14:49:25 +00001066bool GeneratorImpl::EmitValueConversion(utils::StringStream& out,
Ben Clayton54a104e2023-02-22 20:04:40 +00001067 const sem::Call* call,
1068 const sem::ValueConversion* conv) {
dan sinclair2a651632023-02-19 04:03:55 +00001069 if (!EmitType(out, conv->Target(), builtin::AddressSpace::kUndefined,
1070 builtin::Access::kReadWrite, "")) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00001071 return false;
1072 }
1073 out << "(";
Ryan Harrisondbc13af2022-02-21 15:19:07 +00001074
dan sinclair41e4d9a2022-05-01 14:40:55 +00001075 if (!EmitExpression(out, call->Arguments()[0]->Declaration())) {
1076 return false;
1077 }
Ryan Harrisondbc13af2022-02-21 15:19:07 +00001078
dan sinclair41e4d9a2022-05-01 14:40:55 +00001079 out << ")";
1080 return true;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00001081}
1082
dan sinclair2b9d5b32023-02-28 14:49:25 +00001083bool GeneratorImpl::EmitValueConstructor(utils::StringStream& out,
Ben Clayton54a104e2023-02-22 20:04:40 +00001084 const sem::Call* call,
1085 const sem::ValueConstructor* ctor) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00001086 auto* type = call->Type();
Ryan Harrisondbc13af2022-02-21 15:19:07 +00001087
Ben Clayton54a104e2023-02-22 20:04:40 +00001088 // If the value constructor arguments are empty then we need to construct with the zero value
1089 // for all components.
Ben Clayton958a4642022-07-26 07:55:24 +00001090 if (call->Arguments().IsEmpty()) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00001091 return EmitZeroValue(out, type);
Ryan Harrisondbc13af2022-02-21 15:19:07 +00001092 }
Ryan Harrisondbc13af2022-02-21 15:19:07 +00001093
dan sinclair6e77b472022-10-20 13:38:28 +00001094 // Single parameter matrix initializers must be identity initializer.
Zhaoming Jiangc5f7e8f2022-06-24 17:21:59 +00001095 // It could also be conversions between f16 and f32 matrix when f16 is properly supported.
dan sinclair0e780da2022-12-08 22:21:24 +00001096 if (type->Is<type::Matrix>() && call->Arguments().Length() == 1) {
Zhaoming Jiangc5f7e8f2022-06-24 17:21:59 +00001097 if (!ctor->Parameters()[0]->Type()->UnwrapRef()->is_float_matrix()) {
1098 TINT_UNREACHABLE(Writer, diagnostics_)
dan sinclair6e77b472022-10-20 13:38:28 +00001099 << "found a single-parameter matrix initializer that is not identity initializer";
Zhaoming Jiangc5f7e8f2022-06-24 17:21:59 +00001100 return false;
Ben Clayton3b5edf12022-05-16 21:14:11 +00001101 }
1102 }
1103
Ben Claytonbc9e4222023-04-27 18:31:44 +00001104 bool brackets = type->IsAnyOf<type::Array, type::Struct>();
Ryan Harrisondbc13af2022-02-21 15:19:07 +00001105
dan sinclair41e4d9a2022-05-01 14:40:55 +00001106 // For single-value vector initializers, swizzle the scalar to the right
1107 // vector dimension using .x
1108 const bool is_single_value_vector_init = type->is_scalar_vector() &&
Ben Clayton958a4642022-07-26 07:55:24 +00001109 call->Arguments().Length() == 1 &&
Ben Clayton1416b182023-06-08 20:29:30 +00001110 ctor->Parameters()[0]->Type()->Is<type::Scalar>();
dan sinclair41e4d9a2022-05-01 14:40:55 +00001111
Ben Clayton6c098ba2022-07-14 20:46:39 +00001112 if (brackets) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00001113 out << "{";
1114 } else {
dan sinclair2a651632023-02-19 04:03:55 +00001115 if (!EmitType(out, type, builtin::AddressSpace::kUndefined, builtin::Access::kReadWrite,
1116 "")) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00001117 return false;
1118 }
1119 out << "(";
Ryan Harrisondbc13af2022-02-21 15:19:07 +00001120 }
Ryan Harrisondbc13af2022-02-21 15:19:07 +00001121
dan sinclair41e4d9a2022-05-01 14:40:55 +00001122 if (is_single_value_vector_init) {
1123 out << "(";
Ryan Harrisondbc13af2022-02-21 15:19:07 +00001124 }
Ryan Harrisondbc13af2022-02-21 15:19:07 +00001125
dan sinclair41e4d9a2022-05-01 14:40:55 +00001126 bool first = true;
1127 for (auto* e : call->Arguments()) {
1128 if (!first) {
1129 out << ", ";
1130 }
1131 first = false;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00001132
dan sinclair41e4d9a2022-05-01 14:40:55 +00001133 if (!EmitExpression(out, e->Declaration())) {
1134 return false;
1135 }
1136 }
1137
1138 if (is_single_value_vector_init) {
dan sinclair0e780da2022-12-08 22:21:24 +00001139 out << ")." << std::string(type->As<type::Vector>()->Width(), 'x');
dan sinclair41e4d9a2022-05-01 14:40:55 +00001140 }
1141
1142 out << (brackets ? "}" : ")");
1143 return true;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00001144}
1145
1146bool GeneratorImpl::EmitUniformBufferAccess(
dan sinclair2b9d5b32023-02-28 14:49:25 +00001147 utils::StringStream& out,
Ryan Harrisondbc13af2022-02-21 15:19:07 +00001148 const ast::CallExpression* expr,
James Priceb4acbb82023-05-11 21:27:16 +00001149 const ast::transform::DecomposeMemoryAccess::Intrinsic* intrinsic) {
dan sinclaird026e132023-04-18 19:38:25 +00001150 auto const buffer = intrinsic->Buffer()->identifier->symbol.Name();
Ben Clayton1a1b5272023-02-24 17:16:55 +00001151 auto* const offset = expr->args[0];
Ryan Harrisondbc13af2022-02-21 15:19:07 +00001152
Zhaoming Jiangab9b5f32022-11-24 05:25:35 +00001153 // offset in bytes
1154 uint32_t scalar_offset_bytes = 0;
1155 // offset in uint (4 bytes)
1156 uint32_t scalar_offset_index = 0;
1157 // expression to calculate offset in bytes
1158 std::string scalar_offset_bytes_expr;
1159 // expression to calculate offset in uint, by dividing scalar_offset_bytes_expr by 4
1160 std::string scalar_offset_index_expr;
1161 // expression to calculate offset in uint, independently
1162 std::string scalar_offset_index_unified_expr;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00001163
Zhaoming Jiangab9b5f32022-11-24 05:25:35 +00001164 // If true, use scalar_offset_index, otherwise use scalar_offset_index_expr
dan sinclair41e4d9a2022-05-01 14:40:55 +00001165 bool scalar_offset_constant = false;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00001166
Ben Clayton1a1b5272023-02-24 17:16:55 +00001167 if (auto* val = builder_.Sem().GetVal(offset)->ConstantValue()) {
dan sinclaird37ecf92022-12-08 16:39:59 +00001168 TINT_ASSERT(Writer, val->Type()->Is<type::U32>());
dan sinclairb53b8cf2022-12-15 16:25:31 +00001169 scalar_offset_bytes = static_cast<uint32_t>(val->ValueAs<AInt>());
Zhaoming Jiangab9b5f32022-11-24 05:25:35 +00001170 scalar_offset_index = scalar_offset_bytes / 4; // bytes -> scalar index
dan sinclair41e4d9a2022-05-01 14:40:55 +00001171 scalar_offset_constant = true;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00001172 }
Ryan Harrisondbc13af2022-02-21 15:19:07 +00001173
Zhaoming Jiangab9b5f32022-11-24 05:25:35 +00001174 // If true, scalar_offset_bytes or scalar_offset_bytes_expr should be used, otherwise only use
1175 // scalar_offset_index or scalar_offset_index_unified_expr. Currently only loading f16 scalar
1176 // require using offset in bytes.
1177 const bool need_offset_in_bytes =
James Priceb4acbb82023-05-11 21:27:16 +00001178 intrinsic->type == ast::transform::DecomposeMemoryAccess::Intrinsic::DataType::kF16;
Zhaoming Jiangab9b5f32022-11-24 05:25:35 +00001179
dan sinclair41e4d9a2022-05-01 14:40:55 +00001180 if (!scalar_offset_constant) {
1181 // UBO offset not compile-time known.
1182 // Calculate the scalar offset into a temporary.
Zhaoming Jiangab9b5f32022-11-24 05:25:35 +00001183 if (need_offset_in_bytes) {
1184 scalar_offset_bytes_expr = UniqueIdentifier("scalar_offset_bytes");
1185 scalar_offset_index_expr = UniqueIdentifier("scalar_offset_index");
1186 {
1187 auto pre = line();
1188 pre << "const uint " << scalar_offset_bytes_expr << " = (";
Ben Clayton1a1b5272023-02-24 17:16:55 +00001189 if (!EmitExpression(pre, offset)) {
Zhaoming Jiangab9b5f32022-11-24 05:25:35 +00001190 return false;
1191 }
1192 pre << ");";
1193 }
1194 line() << "const uint " << scalar_offset_index_expr << " = " << scalar_offset_bytes_expr
1195 << " / 4;";
1196 } else {
1197 scalar_offset_index_unified_expr = UniqueIdentifier("scalar_offset");
1198 auto pre = line();
1199 pre << "const uint " << scalar_offset_index_unified_expr << " = (";
Ben Clayton1a1b5272023-02-24 17:16:55 +00001200 if (!EmitExpression(pre, offset)) {
Zhaoming Jiangab9b5f32022-11-24 05:25:35 +00001201 return false;
1202 }
1203 pre << ") / 4;";
Ryan Harrisondbc13af2022-02-21 15:19:07 +00001204 }
Ryan Harrisondbc13af2022-02-21 15:19:07 +00001205 }
dan sinclair41e4d9a2022-05-01 14:40:55 +00001206
Austin Enga0e96b52023-02-18 00:39:01 +00001207 const char swizzle[] = {'x', 'y', 'z', 'w'};
Zhaoming Jiangab9b5f32022-11-24 05:25:35 +00001208
James Priceb4acbb82023-05-11 21:27:16 +00001209 using Op = ast::transform::DecomposeMemoryAccess::Intrinsic::Op;
1210 using DataType = ast::transform::DecomposeMemoryAccess::Intrinsic::DataType;
dan sinclair41e4d9a2022-05-01 14:40:55 +00001211 switch (intrinsic->op) {
1212 case Op::kLoad: {
1213 auto cast = [&](const char* to, auto&& load) {
1214 out << to << "(";
1215 auto result = load();
1216 out << ")";
1217 return result;
1218 };
dan sinclair2b9d5b32023-02-28 14:49:25 +00001219 auto load_u32_to = [&](utils::StringStream& target) {
Ben Clayton1a1b5272023-02-24 17:16:55 +00001220 target << buffer;
dan sinclair41e4d9a2022-05-01 14:40:55 +00001221 if (scalar_offset_constant) {
Zhaoming Jiangab9b5f32022-11-24 05:25:35 +00001222 target << "[" << (scalar_offset_index / 4) << "]."
1223 << swizzle[scalar_offset_index & 3];
dan sinclair41e4d9a2022-05-01 14:40:55 +00001224 } else {
Zhaoming Jiangab9b5f32022-11-24 05:25:35 +00001225 target << "[" << scalar_offset_index_unified_expr << " / 4]["
1226 << scalar_offset_index_unified_expr << " % 4]";
dan sinclair41e4d9a2022-05-01 14:40:55 +00001227 }
1228 return true;
1229 };
Zhaoming Jiangab9b5f32022-11-24 05:25:35 +00001230 auto load_u32 = [&] { return load_u32_to(out); };
dan sinclair41e4d9a2022-05-01 14:40:55 +00001231 // Has a minimum alignment of 8 bytes, so is either .xy or .zw
dan sinclair2b9d5b32023-02-28 14:49:25 +00001232 auto load_vec2_u32_to = [&](utils::StringStream& target) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00001233 if (scalar_offset_constant) {
Ben Clayton1a1b5272023-02-24 17:16:55 +00001234 target << buffer << "[" << (scalar_offset_index / 4) << "]"
1235 << ((scalar_offset_index & 2) == 0 ? ".xy" : ".zw");
dan sinclair41e4d9a2022-05-01 14:40:55 +00001236 } else {
1237 std::string ubo_load = UniqueIdentifier("ubo_load");
1238 {
1239 auto pre = line();
Ben Clayton1a1b5272023-02-24 17:16:55 +00001240 pre << "uint4 " << ubo_load << " = " << buffer << "["
1241 << scalar_offset_index_unified_expr << " / 4];";
dan sinclair41e4d9a2022-05-01 14:40:55 +00001242 }
Zhaoming Jiangab9b5f32022-11-24 05:25:35 +00001243 target << "((" << scalar_offset_index_unified_expr << " & 2) ? " << ubo_load
1244 << ".zw : " << ubo_load << ".xy)";
dan sinclair41e4d9a2022-05-01 14:40:55 +00001245 }
1246 return true;
1247 };
Zhaoming Jiangab9b5f32022-11-24 05:25:35 +00001248 auto load_vec2_u32 = [&] { return load_vec2_u32_to(out); };
dan sinclair41e4d9a2022-05-01 14:40:55 +00001249 // vec4 has a minimum alignment of 16 bytes, easiest case
Zhaoming Jiangab9b5f32022-11-24 05:25:35 +00001250 auto load_vec4_u32 = [&] {
Ben Clayton1a1b5272023-02-24 17:16:55 +00001251 out << buffer;
dan sinclair41e4d9a2022-05-01 14:40:55 +00001252 if (scalar_offset_constant) {
Zhaoming Jiangab9b5f32022-11-24 05:25:35 +00001253 out << "[" << (scalar_offset_index / 4) << "]";
dan sinclair41e4d9a2022-05-01 14:40:55 +00001254 } else {
Zhaoming Jiangab9b5f32022-11-24 05:25:35 +00001255 out << "[" << scalar_offset_index_unified_expr << " / 4]";
dan sinclair41e4d9a2022-05-01 14:40:55 +00001256 }
1257 return true;
1258 };
1259 // vec3 has a minimum alignment of 16 bytes, so is just a .xyz swizzle
Zhaoming Jiangab9b5f32022-11-24 05:25:35 +00001260 auto load_vec3_u32 = [&] {
1261 if (!load_vec4_u32()) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00001262 return false;
1263 }
1264 out << ".xyz";
1265 return true;
1266 };
Zhaoming Jiangab9b5f32022-11-24 05:25:35 +00001267 auto load_scalar_f16 = [&] {
1268 // offset bytes = 4k, ((buffer[index].x) & 0xFFFF)
1269 // offset bytes = 4k+2, ((buffer[index].x >> 16) & 0xFFFF)
Ben Clayton1a1b5272023-02-24 17:16:55 +00001270 out << "float16_t(f16tof32(((" << buffer;
Zhaoming Jiangab9b5f32022-11-24 05:25:35 +00001271 if (scalar_offset_constant) {
1272 out << "[" << (scalar_offset_index / 4) << "]."
1273 << swizzle[scalar_offset_index & 3];
1274 // WGSL spec ensure little endian memory layout.
1275 if (scalar_offset_bytes % 4 == 0) {
1276 out << ") & 0xFFFF)";
1277 } else {
1278 out << " >> 16) & 0xFFFF)";
1279 }
1280 } else {
1281 out << "[" << scalar_offset_index_expr << " / 4][" << scalar_offset_index_expr
1282 << " % 4] >> (" << scalar_offset_bytes_expr
1283 << " % 4 == 0 ? 0 : 16)) & 0xFFFF)";
1284 }
1285 out << "))";
1286 return true;
1287 };
1288 auto load_vec2_f16 = [&] {
1289 // vec2<f16> is aligned to 4 bytes
1290 // Preclude code load the vec2<f16> data as a uint:
1291 // uint ubo_load = buffer[id0][id1];
1292 // Loading code convert it to vec2<f16>:
1293 // vector<float16_t, 2>(float16_t(f16tof32(ubo_load & 0xFFFF)),
1294 // float16_t(f16tof32(ubo_load >> 16)))
1295 std::string ubo_load = UniqueIdentifier("ubo_load");
1296 {
1297 auto pre = line();
1298 // Load the 4 bytes f16 vector as an uint
1299 pre << "uint " << ubo_load << " = ";
1300 if (!load_u32_to(pre)) {
1301 return false;
1302 }
1303 pre << ";";
1304 }
1305 out << "vector<float16_t, 2>(float16_t(f16tof32(" << ubo_load
1306 << " & 0xFFFF)), float16_t(f16tof32(" << ubo_load << " >> 16)))";
1307 return true;
1308 };
1309 auto load_vec3_f16 = [&] {
1310 // vec3<f16> is aligned to 8 bytes
1311 // Preclude code load the vec3<f16> data as uint2 and convert its elements to
1312 // float16_t:
1313 // uint2 ubo_load = buffer[id0].xy;
1314 // /* The low 8 bits of two uint are the x and z elements of vec3<f16> */
1315 // vector<float16_t> ubo_load_xz = vector<float16_t, 2>(f16tof32(ubo_load &
1316 // 0xFFFF));
1317 // /* The high 8 bits of first uint is the y element of vec3<f16> */
1318 // float16_t ubo_load_y = f16tof32(ubo_load[0] >> 16);
1319 // Loading code convert it to vec3<f16>:
1320 // vector<float16_t, 3>(ubo_load_xz[0], ubo_load_y, ubo_load_xz[1])
1321 std::string ubo_load = UniqueIdentifier("ubo_load");
1322 std::string ubo_load_xz = UniqueIdentifier(ubo_load + "_xz");
1323 std::string ubo_load_y = UniqueIdentifier(ubo_load + "_y");
1324 {
1325 auto pre = line();
1326 // Load the 8 bytes uint2 with the f16 vector at lower 6 bytes
1327 pre << "uint2 " << ubo_load << " = ";
1328 if (!load_vec2_u32_to(pre)) {
1329 return false;
1330 }
1331 pre << ";";
1332 }
1333 {
1334 auto pre = line();
1335 pre << "vector<float16_t, 2> " << ubo_load_xz
1336 << " = vector<float16_t, 2>(f16tof32(" << ubo_load << " & 0xFFFF));";
1337 }
1338 {
1339 auto pre = line();
1340 pre << "float16_t " << ubo_load_y << " = f16tof32(" << ubo_load
1341 << "[0] >> 16);";
1342 }
1343 out << "vector<float16_t, 3>(" << ubo_load_xz << "[0], " << ubo_load_y << ", "
1344 << ubo_load_xz << "[1])";
1345 return true;
1346 };
1347 auto load_vec4_f16 = [&] {
1348 // vec4<f16> is aligned to 8 bytes
1349 // Preclude code load the vec4<f16> data as uint2 and convert its elements to
1350 // float16_t:
1351 // uint2 ubo_load = buffer[id0].xy;
1352 // /* The low 8 bits of two uint are the x and z elements of vec4<f16> */
1353 // vector<float16_t> ubo_load_xz = vector<float16_t, 2>(f16tof32(ubo_load &
1354 // 0xFFFF));
1355 // /* The high 8 bits of two uint are the y and w elements of vec4<f16> */
1356 // vector<float16_t, 2> ubo_load_yw = vector<float16_t, 2>(f16tof32(ubo_load >>
1357 // 16));
1358 // Loading code convert it to vec4<f16>:
1359 // vector<float16_t, 4>(ubo_load_xz[0], ubo_load_yw[0], ubo_load_xz[1],
1360 // ubo_load_yw[1])
1361 std::string ubo_load = UniqueIdentifier("ubo_load");
1362 std::string ubo_load_xz = UniqueIdentifier(ubo_load + "_xz");
1363 std::string ubo_load_yw = UniqueIdentifier(ubo_load + "_yw");
1364 {
1365 auto pre = line();
1366 // Load the 8 bytes f16 vector as an uint2
1367 pre << "uint2 " << ubo_load << " = ";
1368 if (!load_vec2_u32_to(pre)) {
1369 return false;
1370 }
1371 pre << ";";
1372 }
1373 {
1374 auto pre = line();
1375 pre << "vector<float16_t, 2> " << ubo_load_xz
1376 << " = vector<float16_t, 2>(f16tof32(" << ubo_load << " & 0xFFFF));";
1377 }
1378 {
1379 auto pre = line();
1380 pre << "vector<float16_t, 2> " << ubo_load_yw
1381 << " = vector<float16_t, 2>(f16tof32(" << ubo_load << " >> 16));";
1382 }
1383 out << "vector<float16_t, 4>(" << ubo_load_xz << "[0], " << ubo_load_yw << "[0], "
1384 << ubo_load_xz << "[1], " << ubo_load_yw << "[1])";
1385 return true;
1386 };
dan sinclair41e4d9a2022-05-01 14:40:55 +00001387 switch (intrinsic->type) {
1388 case DataType::kU32:
Zhaoming Jiangab9b5f32022-11-24 05:25:35 +00001389 return load_u32();
dan sinclair41e4d9a2022-05-01 14:40:55 +00001390 case DataType::kF32:
Zhaoming Jiangab9b5f32022-11-24 05:25:35 +00001391 return cast("asfloat", load_u32);
dan sinclair41e4d9a2022-05-01 14:40:55 +00001392 case DataType::kI32:
Zhaoming Jiangab9b5f32022-11-24 05:25:35 +00001393 return cast("asint", load_u32);
1394 case DataType::kF16:
1395 return load_scalar_f16();
dan sinclair41e4d9a2022-05-01 14:40:55 +00001396 case DataType::kVec2U32:
Zhaoming Jiangab9b5f32022-11-24 05:25:35 +00001397 return load_vec2_u32();
dan sinclair41e4d9a2022-05-01 14:40:55 +00001398 case DataType::kVec2F32:
Zhaoming Jiangab9b5f32022-11-24 05:25:35 +00001399 return cast("asfloat", load_vec2_u32);
dan sinclair41e4d9a2022-05-01 14:40:55 +00001400 case DataType::kVec2I32:
Zhaoming Jiangab9b5f32022-11-24 05:25:35 +00001401 return cast("asint", load_vec2_u32);
1402 case DataType::kVec2F16:
1403 return load_vec2_f16();
dan sinclair41e4d9a2022-05-01 14:40:55 +00001404 case DataType::kVec3U32:
Zhaoming Jiangab9b5f32022-11-24 05:25:35 +00001405 return load_vec3_u32();
dan sinclair41e4d9a2022-05-01 14:40:55 +00001406 case DataType::kVec3F32:
Zhaoming Jiangab9b5f32022-11-24 05:25:35 +00001407 return cast("asfloat", load_vec3_u32);
dan sinclair41e4d9a2022-05-01 14:40:55 +00001408 case DataType::kVec3I32:
Zhaoming Jiangab9b5f32022-11-24 05:25:35 +00001409 return cast("asint", load_vec3_u32);
1410 case DataType::kVec3F16:
1411 return load_vec3_f16();
dan sinclair41e4d9a2022-05-01 14:40:55 +00001412 case DataType::kVec4U32:
Zhaoming Jiangab9b5f32022-11-24 05:25:35 +00001413 return load_vec4_u32();
dan sinclair41e4d9a2022-05-01 14:40:55 +00001414 case DataType::kVec4F32:
Zhaoming Jiangab9b5f32022-11-24 05:25:35 +00001415 return cast("asfloat", load_vec4_u32);
dan sinclair41e4d9a2022-05-01 14:40:55 +00001416 case DataType::kVec4I32:
Zhaoming Jiangab9b5f32022-11-24 05:25:35 +00001417 return cast("asint", load_vec4_u32);
1418 case DataType::kVec4F16:
1419 return load_vec4_f16();
dan sinclair41e4d9a2022-05-01 14:40:55 +00001420 }
1421 TINT_UNREACHABLE(Writer, diagnostics_)
1422 << "unsupported DecomposeMemoryAccess::Intrinsic::DataType: "
1423 << static_cast<int>(intrinsic->type);
1424 return false;
1425 }
1426 default:
1427 break;
1428 }
1429 TINT_UNREACHABLE(Writer, diagnostics_)
1430 << "unsupported DecomposeMemoryAccess::Intrinsic::Op: " << static_cast<int>(intrinsic->op);
1431 return false;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00001432}
1433
1434bool GeneratorImpl::EmitStorageBufferAccess(
dan sinclair2b9d5b32023-02-28 14:49:25 +00001435 utils::StringStream& out,
Ryan Harrisondbc13af2022-02-21 15:19:07 +00001436 const ast::CallExpression* expr,
James Priceb4acbb82023-05-11 21:27:16 +00001437 const ast::transform::DecomposeMemoryAccess::Intrinsic* intrinsic) {
dan sinclaird026e132023-04-18 19:38:25 +00001438 auto const buffer = intrinsic->Buffer()->identifier->symbol.Name();
Ben Clayton1a1b5272023-02-24 17:16:55 +00001439 auto* const offset = expr->args[0];
1440 auto* const value = expr->args[1];
Ryan Harrisondbc13af2022-02-21 15:19:07 +00001441
James Priceb4acbb82023-05-11 21:27:16 +00001442 using Op = ast::transform::DecomposeMemoryAccess::Intrinsic::Op;
1443 using DataType = ast::transform::DecomposeMemoryAccess::Intrinsic::DataType;
dan sinclair41e4d9a2022-05-01 14:40:55 +00001444 switch (intrinsic->op) {
1445 case Op::kLoad: {
1446 auto load = [&](const char* cast, int n) {
1447 if (cast) {
1448 out << cast << "(";
1449 }
Ben Clayton1a1b5272023-02-24 17:16:55 +00001450 out << buffer << ".Load";
dan sinclair41e4d9a2022-05-01 14:40:55 +00001451 if (n > 1) {
1452 out << n;
1453 }
dan sinclairb2ba57b2023-02-28 15:14:09 +00001454 ScopedParen sp(out);
Ben Clayton1a1b5272023-02-24 17:16:55 +00001455 if (!EmitExpression(out, offset)) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00001456 return false;
1457 }
1458 if (cast) {
1459 out << ")";
1460 }
1461 return true;
1462 };
Zhaoming Jiangab9b5f32022-11-24 05:25:35 +00001463 // Templated load used for f16 types, requires SM6.2 or higher and DXC
1464 // Used by loading f16 types, e.g. for f16 type, set type parameter to "float16_t"
1465 // to emit `buffer.Load<float16_t>(offset)`.
1466 auto templated_load = [&](const char* type) {
Ben Clayton1a1b5272023-02-24 17:16:55 +00001467 out << buffer << ".Load<" << type << ">"; // templated load
dan sinclairb2ba57b2023-02-28 15:14:09 +00001468 ScopedParen sp(out);
Ben Clayton1a1b5272023-02-24 17:16:55 +00001469 if (!EmitExpression(out, offset)) {
Zhaoming Jiangab9b5f32022-11-24 05:25:35 +00001470 return false;
1471 }
1472 return true;
1473 };
dan sinclair41e4d9a2022-05-01 14:40:55 +00001474 switch (intrinsic->type) {
1475 case DataType::kU32:
1476 return load(nullptr, 1);
1477 case DataType::kF32:
1478 return load("asfloat", 1);
1479 case DataType::kI32:
1480 return load("asint", 1);
Zhaoming Jiangab9b5f32022-11-24 05:25:35 +00001481 case DataType::kF16:
1482 return templated_load("float16_t");
dan sinclair41e4d9a2022-05-01 14:40:55 +00001483 case DataType::kVec2U32:
1484 return load(nullptr, 2);
1485 case DataType::kVec2F32:
1486 return load("asfloat", 2);
1487 case DataType::kVec2I32:
1488 return load("asint", 2);
Zhaoming Jiangab9b5f32022-11-24 05:25:35 +00001489 case DataType::kVec2F16:
1490 return templated_load("vector<float16_t, 2> ");
dan sinclair41e4d9a2022-05-01 14:40:55 +00001491 case DataType::kVec3U32:
1492 return load(nullptr, 3);
1493 case DataType::kVec3F32:
1494 return load("asfloat", 3);
1495 case DataType::kVec3I32:
1496 return load("asint", 3);
Zhaoming Jiangab9b5f32022-11-24 05:25:35 +00001497 case DataType::kVec3F16:
1498 return templated_load("vector<float16_t, 3> ");
dan sinclair41e4d9a2022-05-01 14:40:55 +00001499 case DataType::kVec4U32:
1500 return load(nullptr, 4);
1501 case DataType::kVec4F32:
1502 return load("asfloat", 4);
1503 case DataType::kVec4I32:
1504 return load("asint", 4);
Zhaoming Jiangab9b5f32022-11-24 05:25:35 +00001505 case DataType::kVec4F16:
1506 return templated_load("vector<float16_t, 4> ");
dan sinclair41e4d9a2022-05-01 14:40:55 +00001507 }
1508 TINT_UNREACHABLE(Writer, diagnostics_)
1509 << "unsupported DecomposeMemoryAccess::Intrinsic::DataType: "
1510 << static_cast<int>(intrinsic->type);
1511 return false;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00001512 }
dan sinclair41e4d9a2022-05-01 14:40:55 +00001513
1514 case Op::kStore: {
1515 auto store = [&](int n) {
Ben Clayton1a1b5272023-02-24 17:16:55 +00001516 out << buffer << ".Store";
dan sinclair41e4d9a2022-05-01 14:40:55 +00001517 if (n > 1) {
1518 out << n;
1519 }
dan sinclairb2ba57b2023-02-28 15:14:09 +00001520 ScopedParen sp1(out);
Ben Clayton1a1b5272023-02-24 17:16:55 +00001521 if (!EmitExpression(out, offset)) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00001522 return false;
1523 }
1524 out << ", asuint";
dan sinclairb2ba57b2023-02-28 15:14:09 +00001525 ScopedParen sp2(out);
Ben Clayton1a1b5272023-02-24 17:16:55 +00001526 if (!EmitExpression(out, value)) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00001527 return false;
1528 }
1529 return true;
1530 };
Zhaoming Jiangab9b5f32022-11-24 05:25:35 +00001531 // Templated stored used for f16 types, requires SM6.2 or higher and DXC
1532 // Used by storing f16 types, e.g. for f16 type, set type parameter to "float16_t"
1533 // to emit `buffer.Store<float16_t>(offset)`.
1534 auto templated_store = [&](const char* type) {
Ben Clayton1a1b5272023-02-24 17:16:55 +00001535 out << buffer << ".Store<" << type << ">"; // templated store
dan sinclairb2ba57b2023-02-28 15:14:09 +00001536 ScopedParen sp1(out);
Ben Clayton1a1b5272023-02-24 17:16:55 +00001537 if (!EmitExpression(out, offset)) {
Zhaoming Jiangab9b5f32022-11-24 05:25:35 +00001538 return false;
1539 }
1540 out << ", ";
Ben Clayton1a1b5272023-02-24 17:16:55 +00001541 if (!EmitExpression(out, value)) {
Zhaoming Jiangab9b5f32022-11-24 05:25:35 +00001542 return false;
1543 }
1544 return true;
1545 };
dan sinclair41e4d9a2022-05-01 14:40:55 +00001546 switch (intrinsic->type) {
1547 case DataType::kU32:
1548 return store(1);
1549 case DataType::kF32:
1550 return store(1);
1551 case DataType::kI32:
1552 return store(1);
Zhaoming Jiangab9b5f32022-11-24 05:25:35 +00001553 case DataType::kF16:
1554 return templated_store("float16_t");
dan sinclair41e4d9a2022-05-01 14:40:55 +00001555 case DataType::kVec2U32:
1556 return store(2);
1557 case DataType::kVec2F32:
1558 return store(2);
1559 case DataType::kVec2I32:
1560 return store(2);
Zhaoming Jiangab9b5f32022-11-24 05:25:35 +00001561 case DataType::kVec2F16:
1562 return templated_store("vector<float16_t, 2> ");
dan sinclair41e4d9a2022-05-01 14:40:55 +00001563 case DataType::kVec3U32:
1564 return store(3);
1565 case DataType::kVec3F32:
1566 return store(3);
1567 case DataType::kVec3I32:
1568 return store(3);
Zhaoming Jiangab9b5f32022-11-24 05:25:35 +00001569 case DataType::kVec3F16:
1570 return templated_store("vector<float16_t, 3> ");
dan sinclair41e4d9a2022-05-01 14:40:55 +00001571 case DataType::kVec4U32:
1572 return store(4);
1573 case DataType::kVec4F32:
1574 return store(4);
1575 case DataType::kVec4I32:
1576 return store(4);
Zhaoming Jiangab9b5f32022-11-24 05:25:35 +00001577 case DataType::kVec4F16:
1578 return templated_store("vector<float16_t, 4> ");
dan sinclair41e4d9a2022-05-01 14:40:55 +00001579 }
1580 TINT_UNREACHABLE(Writer, diagnostics_)
1581 << "unsupported DecomposeMemoryAccess::Intrinsic::DataType: "
1582 << static_cast<int>(intrinsic->type);
1583 return false;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00001584 }
Antonio Maiorano08f4b552022-05-31 13:20:28 +00001585 default:
Ben Clayton1a1b5272023-02-24 17:16:55 +00001586 // Break out to error case below
Antonio Maiorano08f4b552022-05-31 13:20:28 +00001587 // Note that atomic intrinsics are generated as functions.
1588 break;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00001589 }
1590
dan sinclair41e4d9a2022-05-01 14:40:55 +00001591 TINT_UNREACHABLE(Writer, diagnostics_)
1592 << "unsupported DecomposeMemoryAccess::Intrinsic::Op: " << static_cast<int>(intrinsic->op);
1593 return false;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00001594}
1595
Antonio Maiorano08f4b552022-05-31 13:20:28 +00001596bool GeneratorImpl::EmitStorageAtomicIntrinsic(
1597 const ast::Function* func,
James Priceb4acbb82023-05-11 21:27:16 +00001598 const ast::transform::DecomposeMemoryAccess::Intrinsic* intrinsic) {
1599 using Op = ast::transform::DecomposeMemoryAccess::Intrinsic::Op;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00001600
Antonio Maiorano08f4b552022-05-31 13:20:28 +00001601 const sem::Function* sem_func = builder_.Sem().Get(func);
1602 auto* result_ty = sem_func->ReturnType();
dan sinclaird026e132023-04-18 19:38:25 +00001603 const auto name = func->name->symbol.Name();
Antonio Maiorano08f4b552022-05-31 13:20:28 +00001604 auto& buf = *current_buffer_;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00001605
dan sinclaird026e132023-04-18 19:38:25 +00001606 auto const buffer = intrinsic->Buffer()->identifier->symbol.Name();
Ben Clayton1a1b5272023-02-24 17:16:55 +00001607
Antonio Maiorano08f4b552022-05-31 13:20:28 +00001608 auto rmw = [&](const char* hlsl) -> bool {
1609 {
1610 auto fn = line(&buf);
dan sinclair2a651632023-02-19 04:03:55 +00001611 if (!EmitTypeAndName(fn, result_ty, builtin::AddressSpace::kUndefined,
dan sinclairb6cc4cb2023-02-19 04:01:29 +00001612 builtin::Access::kUndefined, name)) {
Antonio Maiorano08f4b552022-05-31 13:20:28 +00001613 return false;
1614 }
Ben Clayton1a1b5272023-02-24 17:16:55 +00001615 fn << "(uint offset, ";
dan sinclair2a651632023-02-19 04:03:55 +00001616 if (!EmitTypeAndName(fn, result_ty, builtin::AddressSpace::kUndefined,
dan sinclairb6cc4cb2023-02-19 04:01:29 +00001617 builtin::Access::kUndefined, "value")) {
Antonio Maiorano08f4b552022-05-31 13:20:28 +00001618 return false;
1619 }
1620 fn << ") {";
1621 }
Ryan Harrisondbc13af2022-02-21 15:19:07 +00001622
Antonio Maiorano08f4b552022-05-31 13:20:28 +00001623 buf.IncrementIndent();
1624 TINT_DEFER({
1625 buf.DecrementIndent();
1626 line(&buf) << "}";
1627 line(&buf);
1628 });
1629
1630 {
1631 auto l = line(&buf);
dan sinclair2a651632023-02-19 04:03:55 +00001632 if (!EmitTypeAndName(l, result_ty, builtin::AddressSpace::kUndefined,
dan sinclairb6cc4cb2023-02-19 04:01:29 +00001633 builtin::Access::kUndefined, "original_value")) {
Antonio Maiorano08f4b552022-05-31 13:20:28 +00001634 return false;
1635 }
1636 l << " = 0;";
1637 }
1638 {
1639 auto l = line(&buf);
Ben Clayton1a1b5272023-02-24 17:16:55 +00001640 l << buffer << "." << hlsl << "(offset, ";
Antonio Maiorano08f4b552022-05-31 13:20:28 +00001641 if (intrinsic->op == Op::kAtomicSub) {
1642 l << "-";
1643 }
1644 l << "value, original_value);";
1645 }
1646 line(&buf) << "return original_value;";
1647 return true;
1648 };
1649
1650 switch (intrinsic->op) {
1651 case Op::kAtomicAdd:
1652 return rmw("InterlockedAdd");
1653
1654 case Op::kAtomicSub:
1655 // Use add with the operand negated.
1656 return rmw("InterlockedAdd");
1657
1658 case Op::kAtomicMax:
1659 return rmw("InterlockedMax");
1660
1661 case Op::kAtomicMin:
1662 return rmw("InterlockedMin");
1663
1664 case Op::kAtomicAnd:
1665 return rmw("InterlockedAnd");
1666
1667 case Op::kAtomicOr:
1668 return rmw("InterlockedOr");
1669
1670 case Op::kAtomicXor:
1671 return rmw("InterlockedXor");
1672
1673 case Op::kAtomicExchange:
1674 return rmw("InterlockedExchange");
1675
1676 case Op::kAtomicLoad: {
1677 // HLSL does not have an InterlockedLoad, so we emulate it with
1678 // InterlockedOr using 0 as the OR value
dan sinclair41e4d9a2022-05-01 14:40:55 +00001679 {
1680 auto fn = line(&buf);
dan sinclair2a651632023-02-19 04:03:55 +00001681 if (!EmitTypeAndName(fn, result_ty, builtin::AddressSpace::kUndefined,
dan sinclairb6cc4cb2023-02-19 04:01:29 +00001682 builtin::Access::kUndefined, name)) {
Antonio Maiorano08f4b552022-05-31 13:20:28 +00001683 return false;
dan sinclair41e4d9a2022-05-01 14:40:55 +00001684 }
Ben Clayton1a1b5272023-02-24 17:16:55 +00001685 fn << "(uint offset) {";
Antonio Maiorano08f4b552022-05-31 13:20:28 +00001686 }
1687
1688 buf.IncrementIndent();
1689 TINT_DEFER({
1690 buf.DecrementIndent();
1691 line(&buf) << "}";
1692 line(&buf);
1693 });
1694
1695 {
1696 auto l = line(&buf);
dan sinclair2a651632023-02-19 04:03:55 +00001697 if (!EmitTypeAndName(l, result_ty, builtin::AddressSpace::kUndefined,
dan sinclairb6cc4cb2023-02-19 04:01:29 +00001698 builtin::Access::kUndefined, "value")) {
Antonio Maiorano08f4b552022-05-31 13:20:28 +00001699 return false;
1700 }
1701 l << " = 0;";
1702 }
1703
Ben Clayton1a1b5272023-02-24 17:16:55 +00001704 line(&buf) << buffer << ".InterlockedOr(offset, 0, value);";
Antonio Maiorano08f4b552022-05-31 13:20:28 +00001705 line(&buf) << "return value;";
1706 return true;
1707 }
1708 case Op::kAtomicStore: {
Ben Clayton1a1b5272023-02-24 17:16:55 +00001709 auto* const value_ty = sem_func->Parameters()[1]->Type()->UnwrapRef();
Antonio Maiorano08f4b552022-05-31 13:20:28 +00001710 // HLSL does not have an InterlockedStore, so we emulate it with
1711 // InterlockedExchange and discard the returned value
Antonio Maiorano08f4b552022-05-31 13:20:28 +00001712 {
1713 auto fn = line(&buf);
Ben Clayton1a1b5272023-02-24 17:16:55 +00001714 fn << "void " << name << "(uint offset, ";
dan sinclair2a651632023-02-19 04:03:55 +00001715 if (!EmitTypeAndName(fn, value_ty, builtin::AddressSpace::kUndefined,
dan sinclairb6cc4cb2023-02-19 04:01:29 +00001716 builtin::Access::kUndefined, "value")) {
Antonio Maiorano08f4b552022-05-31 13:20:28 +00001717 return false;
dan sinclair41e4d9a2022-05-01 14:40:55 +00001718 }
1719 fn << ") {";
1720 }
1721
1722 buf.IncrementIndent();
1723 TINT_DEFER({
1724 buf.DecrementIndent();
1725 line(&buf) << "}";
1726 line(&buf);
1727 });
1728
1729 {
1730 auto l = line(&buf);
dan sinclair2a651632023-02-19 04:03:55 +00001731 if (!EmitTypeAndName(l, value_ty, builtin::AddressSpace::kUndefined,
dan sinclairb6cc4cb2023-02-19 04:01:29 +00001732 builtin::Access::kUndefined, "ignored")) {
Antonio Maiorano08f4b552022-05-31 13:20:28 +00001733 return false;
dan sinclair41e4d9a2022-05-01 14:40:55 +00001734 }
Antonio Maiorano08f4b552022-05-31 13:20:28 +00001735 l << ";";
dan sinclair41e4d9a2022-05-01 14:40:55 +00001736 }
Ben Clayton1a1b5272023-02-24 17:16:55 +00001737 line(&buf) << buffer << ".InterlockedExchange(offset, value, ignored);";
Antonio Maiorano08f4b552022-05-31 13:20:28 +00001738 return true;
1739 }
1740 case Op::kAtomicCompareExchangeWeak: {
Ben Clayton4b8a3d32023-06-13 16:55:57 +00001741 if (!EmitStructType(&helpers_, result_ty->As<type::Struct>())) {
1742 return false;
1743 }
1744
Ben Clayton1a1b5272023-02-24 17:16:55 +00001745 auto* const value_ty = sem_func->Parameters()[1]->Type()->UnwrapRef();
Antonio Maiorano08f4b552022-05-31 13:20:28 +00001746 // NOTE: We don't need to emit the return type struct here as DecomposeMemoryAccess
1747 // already added it to the AST, and it should have already been emitted by now.
dan sinclair41e4d9a2022-05-01 14:40:55 +00001748 {
Antonio Maiorano08f4b552022-05-31 13:20:28 +00001749 auto fn = line(&buf);
dan sinclair2a651632023-02-19 04:03:55 +00001750 if (!EmitTypeAndName(fn, result_ty, builtin::AddressSpace::kUndefined,
dan sinclairb6cc4cb2023-02-19 04:01:29 +00001751 builtin::Access::kUndefined, name)) {
Antonio Maiorano08f4b552022-05-31 13:20:28 +00001752 return false;
1753 }
Ben Clayton1a1b5272023-02-24 17:16:55 +00001754 fn << "(uint offset, ";
dan sinclair2a651632023-02-19 04:03:55 +00001755 if (!EmitTypeAndName(fn, value_ty, builtin::AddressSpace::kUndefined,
dan sinclairb6cc4cb2023-02-19 04:01:29 +00001756 builtin::Access::kUndefined, "compare")) {
Antonio Maiorano08f4b552022-05-31 13:20:28 +00001757 return false;
1758 }
1759 fn << ", ";
dan sinclair2a651632023-02-19 04:03:55 +00001760 if (!EmitTypeAndName(fn, value_ty, builtin::AddressSpace::kUndefined,
dan sinclairb6cc4cb2023-02-19 04:01:29 +00001761 builtin::Access::kUndefined, "value")) {
Antonio Maiorano08f4b552022-05-31 13:20:28 +00001762 return false;
1763 }
1764 fn << ") {";
1765 }
1766
1767 buf.IncrementIndent();
1768 TINT_DEFER({
1769 buf.DecrementIndent();
1770 line(&buf) << "}";
1771 line(&buf);
1772 });
1773
1774 { // T result = {0};
dan sinclair41e4d9a2022-05-01 14:40:55 +00001775 auto l = line(&buf);
dan sinclair2a651632023-02-19 04:03:55 +00001776 if (!EmitTypeAndName(l, result_ty, builtin::AddressSpace::kUndefined,
dan sinclairb6cc4cb2023-02-19 04:01:29 +00001777 builtin::Access::kUndefined, "result")) {
Antonio Maiorano08f4b552022-05-31 13:20:28 +00001778 return false;
dan sinclair41e4d9a2022-05-01 14:40:55 +00001779 }
Antonio Maiorano08f4b552022-05-31 13:20:28 +00001780 l << "=";
1781 if (!EmitZeroValue(l, result_ty)) {
1782 return false;
1783 }
1784 l << ";";
dan sinclair41e4d9a2022-05-01 14:40:55 +00001785 }
dan sinclair41e4d9a2022-05-01 14:40:55 +00001786
Ben Clayton1a1b5272023-02-24 17:16:55 +00001787 line(&buf) << buffer
1788 << ".InterlockedCompareExchange(offset, compare, value, result.old_value);";
Antonio Maiorano08f4b552022-05-31 13:20:28 +00001789 line(&buf) << "result.exchanged = result.old_value == compare;";
1790 line(&buf) << "return result;";
dan sinclair41e4d9a2022-05-01 14:40:55 +00001791
Antonio Maiorano08f4b552022-05-31 13:20:28 +00001792 return true;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00001793 }
Antonio Maiorano08f4b552022-05-31 13:20:28 +00001794 default:
1795 break;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00001796 }
Ryan Harrisondbc13af2022-02-21 15:19:07 +00001797
Antonio Maiorano08f4b552022-05-31 13:20:28 +00001798 TINT_UNREACHABLE(Writer, diagnostics_)
1799 << "unsupported atomic DecomposeMemoryAccess::Intrinsic::Op: "
1800 << static_cast<int>(intrinsic->op);
1801 return false;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00001802}
1803
dan sinclair2b9d5b32023-02-28 14:49:25 +00001804bool GeneratorImpl::EmitWorkgroupAtomicCall(utils::StringStream& out,
Ryan Harrisondbc13af2022-02-21 15:19:07 +00001805 const ast::CallExpression* expr,
1806 const sem::Builtin* builtin) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00001807 std::string result = UniqueIdentifier("atomic_result");
Ryan Harrisondbc13af2022-02-21 15:19:07 +00001808
dan sinclaird37ecf92022-12-08 16:39:59 +00001809 if (!builtin->ReturnType()->Is<type::Void>()) {
Ryan Harrisondbc13af2022-02-21 15:19:07 +00001810 auto pre = line();
dan sinclair2a651632023-02-19 04:03:55 +00001811 if (!EmitTypeAndName(pre, builtin->ReturnType(), builtin::AddressSpace::kUndefined,
dan sinclairb6cc4cb2023-02-19 04:01:29 +00001812 builtin::Access::kUndefined, result)) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00001813 return false;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00001814 }
1815 pre << " = ";
dan sinclair41e4d9a2022-05-01 14:40:55 +00001816 if (!EmitZeroValue(pre, builtin->ReturnType())) {
1817 return false;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00001818 }
1819 pre << ";";
Ryan Harrisondbc13af2022-02-21 15:19:07 +00001820 }
Ryan Harrisondbc13af2022-02-21 15:19:07 +00001821
dan sinclair41e4d9a2022-05-01 14:40:55 +00001822 auto call = [&](const char* name) {
Ryan Harrisondbc13af2022-02-21 15:19:07 +00001823 auto pre = line();
dan sinclair41e4d9a2022-05-01 14:40:55 +00001824 pre << name;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00001825
Ryan Harrisondbc13af2022-02-21 15:19:07 +00001826 {
dan sinclair41e4d9a2022-05-01 14:40:55 +00001827 ScopedParen sp(pre);
Ben Clayton783b1692022-08-02 17:03:35 +00001828 for (size_t i = 0; i < expr->args.Length(); i++) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00001829 auto* arg = expr->args[i];
1830 if (i > 0) {
1831 pre << ", ";
1832 }
dan sinclair9543f742023-03-09 01:20:16 +00001833 if (i == 1 && builtin->Type() == builtin::Function::kAtomicSub) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00001834 // Sub uses InterlockedAdd with the operand negated.
1835 pre << "-";
1836 }
1837 if (!EmitExpression(pre, arg)) {
1838 return false;
1839 }
1840 }
1841
1842 pre << ", " << result;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00001843 }
dan sinclair41e4d9a2022-05-01 14:40:55 +00001844
Ryan Harrisondbc13af2022-02-21 15:19:07 +00001845 pre << ";";
Ryan Harrisondbc13af2022-02-21 15:19:07 +00001846
dan sinclair41e4d9a2022-05-01 14:40:55 +00001847 out << result;
1848 return true;
1849 };
Ryan Harrisondbc13af2022-02-21 15:19:07 +00001850
dan sinclair41e4d9a2022-05-01 14:40:55 +00001851 switch (builtin->Type()) {
dan sinclair9543f742023-03-09 01:20:16 +00001852 case builtin::Function::kAtomicLoad: {
dan sinclair41e4d9a2022-05-01 14:40:55 +00001853 // HLSL does not have an InterlockedLoad, so we emulate it with
1854 // InterlockedOr using 0 as the OR value
1855 auto pre = line();
1856 pre << "InterlockedOr";
1857 {
1858 ScopedParen sp(pre);
1859 if (!EmitExpression(pre, expr->args[0])) {
1860 return false;
1861 }
1862 pre << ", 0, " << result;
1863 }
1864 pre << ";";
1865
1866 out << result;
1867 return true;
1868 }
dan sinclair9543f742023-03-09 01:20:16 +00001869 case builtin::Function::kAtomicStore: {
dan sinclair41e4d9a2022-05-01 14:40:55 +00001870 // HLSL does not have an InterlockedStore, so we emulate it with
1871 // InterlockedExchange and discard the returned value
1872 { // T result = 0;
1873 auto pre = line();
1874 auto* value_ty = builtin->Parameters()[1]->Type()->UnwrapRef();
dan sinclair2a651632023-02-19 04:03:55 +00001875 if (!EmitTypeAndName(pre, value_ty, builtin::AddressSpace::kUndefined,
dan sinclairb6cc4cb2023-02-19 04:01:29 +00001876 builtin::Access::kUndefined, result)) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00001877 return false;
1878 }
1879 pre << " = ";
1880 if (!EmitZeroValue(pre, value_ty)) {
1881 return false;
1882 }
1883 pre << ";";
1884 }
1885
1886 out << "InterlockedExchange";
1887 {
dan sinclairb2ba57b2023-02-28 15:14:09 +00001888 ScopedParen sp(out);
dan sinclair41e4d9a2022-05-01 14:40:55 +00001889 if (!EmitExpression(out, expr->args[0])) {
1890 return false;
1891 }
1892 out << ", ";
1893 if (!EmitExpression(out, expr->args[1])) {
1894 return false;
1895 }
1896 out << ", " << result;
1897 }
1898 return true;
1899 }
dan sinclair9543f742023-03-09 01:20:16 +00001900 case builtin::Function::kAtomicCompareExchangeWeak: {
Ben Claytonbc9e4222023-04-27 18:31:44 +00001901 if (!EmitStructType(&helpers_, builtin->ReturnType()->As<type::Struct>())) {
Antonio Maiorano08f4b552022-05-31 13:20:28 +00001902 return false;
1903 }
1904
dan sinclair41e4d9a2022-05-01 14:40:55 +00001905 auto* dest = expr->args[0];
1906 auto* compare_value = expr->args[1];
1907 auto* value = expr->args[2];
1908
1909 std::string compare = UniqueIdentifier("atomic_compare_value");
1910
1911 { // T compare_value = <compare_value>;
1912 auto pre = line();
Antonio Maioranof99671b2022-06-23 13:14:54 +00001913 if (!EmitTypeAndName(pre, TypeOf(compare_value)->UnwrapRef(),
dan sinclair2a651632023-02-19 04:03:55 +00001914 builtin::AddressSpace::kUndefined, builtin::Access::kUndefined,
dan sinclair61c16eb2023-01-21 23:44:38 +00001915 compare)) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00001916 return false;
1917 }
1918 pre << " = ";
1919 if (!EmitExpression(pre, compare_value)) {
1920 return false;
1921 }
1922 pre << ";";
1923 }
1924
Antonio Maiorano08f4b552022-05-31 13:20:28 +00001925 { // InterlockedCompareExchange(dst, compare, value, result.old_value);
dan sinclair41e4d9a2022-05-01 14:40:55 +00001926 auto pre = line();
1927 pre << "InterlockedCompareExchange";
1928 {
1929 ScopedParen sp(pre);
1930 if (!EmitExpression(pre, dest)) {
1931 return false;
1932 }
1933 pre << ", " << compare << ", ";
1934 if (!EmitExpression(pre, value)) {
1935 return false;
1936 }
Antonio Maiorano08f4b552022-05-31 13:20:28 +00001937 pre << ", " << result << ".old_value";
dan sinclair41e4d9a2022-05-01 14:40:55 +00001938 }
1939 pre << ";";
1940 }
1941
Antonio Maiorano08f4b552022-05-31 13:20:28 +00001942 // result.exchanged = result.old_value == compare;
1943 line() << result << ".exchanged = " << result << ".old_value == " << compare << ";";
dan sinclair41e4d9a2022-05-01 14:40:55 +00001944
1945 out << result;
1946 return true;
1947 }
1948
dan sinclair9543f742023-03-09 01:20:16 +00001949 case builtin::Function::kAtomicAdd:
1950 case builtin::Function::kAtomicSub:
dan sinclair41e4d9a2022-05-01 14:40:55 +00001951 return call("InterlockedAdd");
1952
dan sinclair9543f742023-03-09 01:20:16 +00001953 case builtin::Function::kAtomicMax:
dan sinclair41e4d9a2022-05-01 14:40:55 +00001954 return call("InterlockedMax");
1955
dan sinclair9543f742023-03-09 01:20:16 +00001956 case builtin::Function::kAtomicMin:
dan sinclair41e4d9a2022-05-01 14:40:55 +00001957 return call("InterlockedMin");
1958
dan sinclair9543f742023-03-09 01:20:16 +00001959 case builtin::Function::kAtomicAnd:
dan sinclair41e4d9a2022-05-01 14:40:55 +00001960 return call("InterlockedAnd");
1961
dan sinclair9543f742023-03-09 01:20:16 +00001962 case builtin::Function::kAtomicOr:
dan sinclair41e4d9a2022-05-01 14:40:55 +00001963 return call("InterlockedOr");
1964
dan sinclair9543f742023-03-09 01:20:16 +00001965 case builtin::Function::kAtomicXor:
dan sinclair41e4d9a2022-05-01 14:40:55 +00001966 return call("InterlockedXor");
1967
dan sinclair9543f742023-03-09 01:20:16 +00001968 case builtin::Function::kAtomicExchange:
dan sinclair41e4d9a2022-05-01 14:40:55 +00001969 return call("InterlockedExchange");
1970
1971 default:
1972 break;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00001973 }
1974
dan sinclair41e4d9a2022-05-01 14:40:55 +00001975 TINT_UNREACHABLE(Writer, diagnostics_) << "unsupported atomic builtin: " << builtin->Type();
1976 return false;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00001977}
1978
dan sinclair2b9d5b32023-02-28 14:49:25 +00001979bool GeneratorImpl::EmitSelectCall(utils::StringStream& out, const ast::CallExpression* expr) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00001980 auto* expr_false = expr->args[0];
1981 auto* expr_true = expr->args[1];
1982 auto* expr_cond = expr->args[2];
dan sinclairb2ba57b2023-02-28 15:14:09 +00001983 ScopedParen paren(out);
dan sinclair41e4d9a2022-05-01 14:40:55 +00001984 if (!EmitExpression(out, expr_cond)) {
1985 return false;
1986 }
Ryan Harrisondbc13af2022-02-21 15:19:07 +00001987
dan sinclair41e4d9a2022-05-01 14:40:55 +00001988 out << " ? ";
Ryan Harrisondbc13af2022-02-21 15:19:07 +00001989
dan sinclair41e4d9a2022-05-01 14:40:55 +00001990 if (!EmitExpression(out, expr_true)) {
1991 return false;
1992 }
Ryan Harrisondbc13af2022-02-21 15:19:07 +00001993
dan sinclair41e4d9a2022-05-01 14:40:55 +00001994 out << " : ";
Ryan Harrisondbc13af2022-02-21 15:19:07 +00001995
dan sinclair41e4d9a2022-05-01 14:40:55 +00001996 if (!EmitExpression(out, expr_false)) {
1997 return false;
1998 }
Ryan Harrisondbc13af2022-02-21 15:19:07 +00001999
dan sinclair41e4d9a2022-05-01 14:40:55 +00002000 return true;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00002001}
2002
dan sinclair2b9d5b32023-02-28 14:49:25 +00002003bool GeneratorImpl::EmitModfCall(utils::StringStream& out,
Ryan Harrisondbc13af2022-02-21 15:19:07 +00002004 const ast::CallExpression* expr,
2005 const sem::Builtin* builtin) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00002006 return CallBuiltinHelper(
2007 out, expr, builtin, [&](TextBuffer* b, const std::vector<std::string>& params) {
2008 auto* ty = builtin->Parameters()[0]->Type();
2009 auto in = params[0];
Ryan Harrisondbc13af2022-02-21 15:19:07 +00002010
dan sinclair41e4d9a2022-05-01 14:40:55 +00002011 std::string width;
dan sinclair0e780da2022-12-08 22:21:24 +00002012 if (auto* vec = ty->As<type::Vector>()) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00002013 width = std::to_string(vec->Width());
2014 }
Ryan Harrisondbc13af2022-02-21 15:19:07 +00002015
dan sinclair41e4d9a2022-05-01 14:40:55 +00002016 // Emit the builtin return type unique to this overload. This does not
2017 // exist in the AST, so it will not be generated in Generate().
Ben Claytonbc9e4222023-04-27 18:31:44 +00002018 if (!EmitStructType(&helpers_, builtin->ReturnType()->As<type::Struct>())) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00002019 return false;
2020 }
Ryan Harrisondbc13af2022-02-21 15:19:07 +00002021
dan sinclair41e4d9a2022-05-01 14:40:55 +00002022 {
2023 auto l = line(b);
dan sinclair2a651632023-02-19 04:03:55 +00002024 if (!EmitType(l, builtin->ReturnType(), builtin::AddressSpace::kUndefined,
dan sinclairb6cc4cb2023-02-19 04:01:29 +00002025 builtin::Access::kUndefined, "")) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00002026 return false;
2027 }
Zhaoming Jiang20cddbf2022-08-05 15:11:44 +00002028 l << " result;";
dan sinclair41e4d9a2022-05-01 14:40:55 +00002029 }
Zhaoming Jiang20cddbf2022-08-05 15:11:44 +00002030 line(b) << "result.fract = modf(" << params[0] << ", result.whole);";
dan sinclair41e4d9a2022-05-01 14:40:55 +00002031 line(b) << "return result;";
2032 return true;
2033 });
Ryan Harrisondbc13af2022-02-21 15:19:07 +00002034}
2035
dan sinclair2b9d5b32023-02-28 14:49:25 +00002036bool GeneratorImpl::EmitFrexpCall(utils::StringStream& out,
Ryan Harrisondbc13af2022-02-21 15:19:07 +00002037 const ast::CallExpression* expr,
2038 const sem::Builtin* builtin) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00002039 return CallBuiltinHelper(
2040 out, expr, builtin, [&](TextBuffer* b, const std::vector<std::string>& params) {
2041 auto* ty = builtin->Parameters()[0]->Type();
2042 auto in = params[0];
Ryan Harrisondbc13af2022-02-21 15:19:07 +00002043
dan sinclair41e4d9a2022-05-01 14:40:55 +00002044 std::string width;
dan sinclair0e780da2022-12-08 22:21:24 +00002045 if (auto* vec = ty->As<type::Vector>()) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00002046 width = std::to_string(vec->Width());
2047 }
Ryan Harrisondbc13af2022-02-21 15:19:07 +00002048
dan sinclair41e4d9a2022-05-01 14:40:55 +00002049 // Emit the builtin return type unique to this overload. This does not
2050 // exist in the AST, so it will not be generated in Generate().
Ben Claytonbc9e4222023-04-27 18:31:44 +00002051 if (!EmitStructType(&helpers_, builtin->ReturnType()->As<type::Struct>())) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00002052 return false;
2053 }
Ryan Harrisondbc13af2022-02-21 15:19:07 +00002054
Zhaoming Jiang20cddbf2022-08-05 15:11:44 +00002055 std::string member_type;
Ben Clayton471a0152023-06-09 10:07:16 +00002056 if (Is<type::F16>(ty->DeepestElement())) {
Zhaoming Jiang20cddbf2022-08-05 15:11:44 +00002057 member_type = width.empty() ? "float16_t" : ("vector<float16_t, " + width + ">");
2058 } else {
2059 member_type = "float" + width;
2060 }
2061
2062 line(b) << member_type << " exp;";
Antonio Maiorano52cd8ca2023-03-16 21:31:15 +00002063 line(b) << member_type << " fract = sign(" << in << ") * frexp(" << in << ", exp);";
dan sinclair41e4d9a2022-05-01 14:40:55 +00002064 {
2065 auto l = line(b);
dan sinclair2a651632023-02-19 04:03:55 +00002066 if (!EmitType(l, builtin->ReturnType(), builtin::AddressSpace::kUndefined,
dan sinclairb6cc4cb2023-02-19 04:01:29 +00002067 builtin::Access::kUndefined, "")) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00002068 return false;
2069 }
Ben Clayton10fae7a2022-11-14 15:29:29 +00002070 l << " result = {fract, int" << width << "(exp)};";
dan sinclair41e4d9a2022-05-01 14:40:55 +00002071 }
2072 line(b) << "return result;";
2073 return true;
2074 });
Ryan Harrisondbc13af2022-02-21 15:19:07 +00002075}
2076
dan sinclair2b9d5b32023-02-28 14:49:25 +00002077bool GeneratorImpl::EmitDegreesCall(utils::StringStream& out,
Ryan Harrisondbc13af2022-02-21 15:19:07 +00002078 const ast::CallExpression* expr,
2079 const sem::Builtin* builtin) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00002080 return CallBuiltinHelper(out, expr, builtin,
2081 [&](TextBuffer* b, const std::vector<std::string>& params) {
2082 line(b) << "return " << params[0] << " * " << std::setprecision(20)
2083 << sem::kRadToDeg << ";";
2084 return true;
2085 });
Ryan Harrisondbc13af2022-02-21 15:19:07 +00002086}
2087
dan sinclair2b9d5b32023-02-28 14:49:25 +00002088bool GeneratorImpl::EmitRadiansCall(utils::StringStream& out,
Ryan Harrisondbc13af2022-02-21 15:19:07 +00002089 const ast::CallExpression* expr,
2090 const sem::Builtin* builtin) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00002091 return CallBuiltinHelper(out, expr, builtin,
2092 [&](TextBuffer* b, const std::vector<std::string>& params) {
2093 line(b) << "return " << params[0] << " * " << std::setprecision(20)
2094 << sem::kDegToRad << ";";
2095 return true;
2096 });
Ryan Harrisondbc13af2022-02-21 15:19:07 +00002097}
2098
dan sinclair70927862023-01-11 13:18:29 +00002099// The HLSL `sign` method always returns an `int` result (scalar or vector). In WGSL the result is
2100// expected to be the same type as the argument. This injects a cast to the expected WGSL result
2101// type after the call to `sign`.
dan sinclair2b9d5b32023-02-28 14:49:25 +00002102bool GeneratorImpl::EmitSignCall(utils::StringStream& out,
2103 const sem::Call* call,
2104 const sem::Builtin*) {
dan sinclair70927862023-01-11 13:18:29 +00002105 auto* arg = call->Arguments()[0];
dan sinclair2a651632023-02-19 04:03:55 +00002106 if (!EmitType(out, arg->Type(), builtin::AddressSpace::kUndefined, builtin::Access::kReadWrite,
dan sinclairb6cc4cb2023-02-19 04:01:29 +00002107 "")) {
dan sinclair70927862023-01-11 13:18:29 +00002108 return false;
2109 }
2110 out << "(sign(";
2111 if (!EmitExpression(out, arg->Declaration())) {
2112 return false;
2113 }
2114 out << "))";
2115 return true;
2116}
2117
dan sinclair2b9d5b32023-02-28 14:49:25 +00002118bool GeneratorImpl::EmitQuantizeToF16Call(utils::StringStream& out,
Ben Clayton2bea9052022-11-02 00:09:50 +00002119 const ast::CallExpression* expr,
2120 const sem::Builtin* builtin) {
Antonio Maiorano51249b82023-03-31 08:00:33 +00002121 // Cast to f16 and back
Ben Clayton2bea9052022-11-02 00:09:50 +00002122 std::string width;
dan sinclair0e780da2022-12-08 22:21:24 +00002123 if (auto* vec = builtin->ReturnType()->As<type::Vector>()) {
Ben Clayton2bea9052022-11-02 00:09:50 +00002124 width = std::to_string(vec->Width());
2125 }
Antonio Maiorano51249b82023-03-31 08:00:33 +00002126 out << "f16tof32(f32tof16"
2127 << "(";
Ben Clayton2bea9052022-11-02 00:09:50 +00002128 if (!EmitExpression(out, expr->args[0])) {
2129 return false;
2130 }
2131 out << "))";
2132 return true;
2133}
2134
Antonio Maiorano5cf943e2023-03-27 18:55:25 +00002135bool GeneratorImpl::EmitTruncCall(utils::StringStream& out,
2136 const ast::CallExpression* expr,
2137 const sem::Builtin* builtin) {
2138 // HLSL's trunc is broken for very large/small float values.
2139 // See crbug.com/tint/1883
2140 return CallBuiltinHelper( //
2141 out, expr, builtin, [&](TextBuffer* b, const std::vector<std::string>& params) {
2142 // value < 0 ? ceil(value) : floor(value)
2143 line(b) << "return " << params[0] << " < 0 ? ceil(" << params[0] << ") : floor("
2144 << params[0] << ");";
2145 return true;
2146 });
2147}
2148
dan sinclair2b9d5b32023-02-28 14:49:25 +00002149bool GeneratorImpl::EmitDataPackingCall(utils::StringStream& out,
Ryan Harrisondbc13af2022-02-21 15:19:07 +00002150 const ast::CallExpression* expr,
2151 const sem::Builtin* builtin) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00002152 return CallBuiltinHelper(
2153 out, expr, builtin, [&](TextBuffer* b, const std::vector<std::string>& params) {
2154 uint32_t dims = 2;
2155 bool is_signed = false;
2156 uint32_t scale = 65535;
dan sinclair9543f742023-03-09 01:20:16 +00002157 if (builtin->Type() == builtin::Function::kPack4X8Snorm ||
2158 builtin->Type() == builtin::Function::kPack4X8Unorm) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00002159 dims = 4;
2160 scale = 255;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00002161 }
dan sinclair9543f742023-03-09 01:20:16 +00002162 if (builtin->Type() == builtin::Function::kPack4X8Snorm ||
2163 builtin->Type() == builtin::Function::kPack2X16Snorm) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00002164 is_signed = true;
2165 scale = (scale - 1) / 2;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00002166 }
dan sinclair41e4d9a2022-05-01 14:40:55 +00002167 switch (builtin->Type()) {
dan sinclair9543f742023-03-09 01:20:16 +00002168 case builtin::Function::kPack4X8Snorm:
2169 case builtin::Function::kPack4X8Unorm:
2170 case builtin::Function::kPack2X16Snorm:
2171 case builtin::Function::kPack2X16Unorm: {
dan sinclair41e4d9a2022-05-01 14:40:55 +00002172 {
2173 auto l = line(b);
2174 l << (is_signed ? "" : "u") << "int" << dims
2175 << " i = " << (is_signed ? "" : "u") << "int" << dims << "(round(clamp("
2176 << params[0] << ", " << (is_signed ? "-1.0" : "0.0") << ", 1.0) * "
2177 << scale << ".0))";
2178 if (is_signed) {
2179 l << " & " << (dims == 4 ? "0xff" : "0xffff");
2180 }
2181 l << ";";
2182 }
2183 {
2184 auto l = line(b);
2185 l << "return ";
2186 if (is_signed) {
2187 l << "asuint";
2188 }
2189 l << "(i.x | i.y << " << (32 / dims);
2190 if (dims == 4) {
2191 l << " | i.z << 16 | i.w << 24";
2192 }
2193 l << ");";
2194 }
2195 break;
2196 }
dan sinclair9543f742023-03-09 01:20:16 +00002197 case builtin::Function::kPack2X16Float: {
dan sinclair41e4d9a2022-05-01 14:40:55 +00002198 line(b) << "uint2 i = f32tof16(" << params[0] << ");";
2199 line(b) << "return i.x | (i.y << 16);";
2200 break;
2201 }
2202 default:
2203 diagnostics_.add_error(diag::System::Writer,
2204 "Internal error: unhandled data packing builtin");
2205 return false;
2206 }
Ryan Harrisondbc13af2022-02-21 15:19:07 +00002207
dan sinclair41e4d9a2022-05-01 14:40:55 +00002208 return true;
2209 });
Ryan Harrisondbc13af2022-02-21 15:19:07 +00002210}
2211
dan sinclair2b9d5b32023-02-28 14:49:25 +00002212bool GeneratorImpl::EmitDataUnpackingCall(utils::StringStream& out,
Ryan Harrisondbc13af2022-02-21 15:19:07 +00002213 const ast::CallExpression* expr,
2214 const sem::Builtin* builtin) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00002215 return CallBuiltinHelper(
2216 out, expr, builtin, [&](TextBuffer* b, const std::vector<std::string>& params) {
2217 uint32_t dims = 2;
2218 bool is_signed = false;
2219 uint32_t scale = 65535;
dan sinclair9543f742023-03-09 01:20:16 +00002220 if (builtin->Type() == builtin::Function::kUnpack4X8Snorm ||
2221 builtin->Type() == builtin::Function::kUnpack4X8Unorm) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00002222 dims = 4;
2223 scale = 255;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00002224 }
dan sinclair9543f742023-03-09 01:20:16 +00002225 if (builtin->Type() == builtin::Function::kUnpack4X8Snorm ||
2226 builtin->Type() == builtin::Function::kUnpack2X16Snorm) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00002227 is_signed = true;
2228 scale = (scale - 1) / 2;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00002229 }
dan sinclair41e4d9a2022-05-01 14:40:55 +00002230 switch (builtin->Type()) {
dan sinclair9543f742023-03-09 01:20:16 +00002231 case builtin::Function::kUnpack4X8Snorm:
2232 case builtin::Function::kUnpack2X16Snorm: {
dan sinclair41e4d9a2022-05-01 14:40:55 +00002233 line(b) << "int j = int(" << params[0] << ");";
2234 { // Perform sign extension on the converted values.
2235 auto l = line(b);
2236 l << "int" << dims << " i = int" << dims << "(";
2237 if (dims == 2) {
2238 l << "j << 16, j) >> 16";
2239 } else {
2240 l << "j << 24, j << 16, j << 8, j) >> 24";
2241 }
2242 l << ";";
2243 }
2244 line(b) << "return clamp(float" << dims << "(i) / " << scale << ".0, "
2245 << (is_signed ? "-1.0" : "0.0") << ", 1.0);";
2246 break;
2247 }
dan sinclair9543f742023-03-09 01:20:16 +00002248 case builtin::Function::kUnpack4X8Unorm:
2249 case builtin::Function::kUnpack2X16Unorm: {
dan sinclair41e4d9a2022-05-01 14:40:55 +00002250 line(b) << "uint j = " << params[0] << ";";
2251 {
2252 auto l = line(b);
2253 l << "uint" << dims << " i = uint" << dims << "(";
2254 l << "j & " << (dims == 2 ? "0xffff" : "0xff") << ", ";
2255 if (dims == 4) {
2256 l << "(j >> " << (32 / dims) << ") & 0xff, (j >> 16) & 0xff, j >> 24";
2257 } else {
2258 l << "j >> " << (32 / dims);
2259 }
2260 l << ");";
2261 }
2262 line(b) << "return float" << dims << "(i) / " << scale << ".0;";
2263 break;
2264 }
dan sinclair9543f742023-03-09 01:20:16 +00002265 case builtin::Function::kUnpack2X16Float:
dan sinclair41e4d9a2022-05-01 14:40:55 +00002266 line(b) << "uint i = " << params[0] << ";";
2267 line(b) << "return f16tof32(uint2(i & 0xffff, i >> 16));";
2268 break;
2269 default:
2270 diagnostics_.add_error(diag::System::Writer,
2271 "Internal error: unhandled data packing builtin");
2272 return false;
2273 }
Ryan Harrisondbc13af2022-02-21 15:19:07 +00002274
dan sinclair41e4d9a2022-05-01 14:40:55 +00002275 return true;
2276 });
Ryan Harrisondbc13af2022-02-21 15:19:07 +00002277}
2278
dan sinclair2b9d5b32023-02-28 14:49:25 +00002279bool GeneratorImpl::EmitDP4aCall(utils::StringStream& out,
Jiawei Shaoab975702022-05-13 00:09:56 +00002280 const ast::CallExpression* expr,
2281 const sem::Builtin* builtin) {
2282 // TODO(crbug.com/tint/1497): support the polyfill version of DP4a functions.
2283 return CallBuiltinHelper(
2284 out, expr, builtin, [&](TextBuffer* b, const std::vector<std::string>& params) {
2285 std::string functionName;
2286 switch (builtin->Type()) {
dan sinclair9543f742023-03-09 01:20:16 +00002287 case builtin::Function::kDot4I8Packed:
Jiawei Shao1c759212022-05-15 13:53:21 +00002288 line(b) << "int accumulator = 0;";
Jiawei Shaoab975702022-05-13 00:09:56 +00002289 functionName = "dot4add_i8packed";
2290 break;
dan sinclair9543f742023-03-09 01:20:16 +00002291 case builtin::Function::kDot4U8Packed:
Jiawei Shao1c759212022-05-15 13:53:21 +00002292 line(b) << "uint accumulator = 0u;";
Jiawei Shaoab975702022-05-13 00:09:56 +00002293 functionName = "dot4add_u8packed";
2294 break;
2295 default:
2296 diagnostics_.add_error(diag::System::Writer,
2297 "Internal error: unhandled DP4a builtin");
2298 return false;
2299 }
2300 line(b) << "return " << functionName << "(" << params[0] << ", " << params[1]
Jiawei Shao1c759212022-05-15 13:53:21 +00002301 << ", accumulator);";
Jiawei Shaoab975702022-05-13 00:09:56 +00002302
2303 return true;
2304 });
2305}
2306
dan sinclair2b9d5b32023-02-28 14:49:25 +00002307bool GeneratorImpl::EmitBarrierCall(utils::StringStream& out, const sem::Builtin* builtin) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00002308 // TODO(crbug.com/tint/661): Combine sequential barriers to a single
2309 // instruction.
dan sinclair9543f742023-03-09 01:20:16 +00002310 if (builtin->Type() == builtin::Function::kWorkgroupBarrier) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00002311 out << "GroupMemoryBarrierWithGroupSync()";
dan sinclair9543f742023-03-09 01:20:16 +00002312 } else if (builtin->Type() == builtin::Function::kStorageBarrier) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00002313 out << "DeviceMemoryBarrierWithGroupSync()";
2314 } else {
2315 TINT_UNREACHABLE(Writer, diagnostics_)
dan sinclair9543f742023-03-09 01:20:16 +00002316 << "unexpected barrier builtin type " << builtin::str(builtin->Type());
dan sinclair41e4d9a2022-05-01 14:40:55 +00002317 return false;
2318 }
2319 return true;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00002320}
2321
dan sinclair2b9d5b32023-02-28 14:49:25 +00002322bool GeneratorImpl::EmitTextureCall(utils::StringStream& out,
Ryan Harrisondbc13af2022-02-21 15:19:07 +00002323 const sem::Call* call,
2324 const sem::Builtin* builtin) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00002325 using Usage = sem::ParameterUsage;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00002326
dan sinclair41e4d9a2022-05-01 14:40:55 +00002327 auto& signature = builtin->Signature();
2328 auto* expr = call->Declaration();
2329 auto arguments = expr->args;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00002330
dan sinclair41e4d9a2022-05-01 14:40:55 +00002331 // Returns the argument with the given usage
2332 auto arg = [&](Usage usage) {
2333 int idx = signature.IndexOf(usage);
dan sinclair3a2a2792022-06-29 14:38:15 +00002334 return (idx >= 0) ? arguments[static_cast<size_t>(idx)] : nullptr;
dan sinclair41e4d9a2022-05-01 14:40:55 +00002335 };
Ryan Harrisondbc13af2022-02-21 15:19:07 +00002336
dan sinclair41e4d9a2022-05-01 14:40:55 +00002337 auto* texture = arg(Usage::kTexture);
Ben Clayton884f9522023-01-12 22:52:57 +00002338 if (TINT_UNLIKELY(!texture)) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00002339 TINT_ICE(Writer, diagnostics_) << "missing texture argument";
2340 return false;
2341 }
Ryan Harrisondbc13af2022-02-21 15:19:07 +00002342
dan sinclair4595fb72022-12-08 14:14:10 +00002343 auto* texture_type = TypeOf(texture)->UnwrapRef()->As<type::Texture>();
Ryan Harrisondbc13af2022-02-21 15:19:07 +00002344
dan sinclair41e4d9a2022-05-01 14:40:55 +00002345 switch (builtin->Type()) {
dan sinclair9543f742023-03-09 01:20:16 +00002346 case builtin::Function::kTextureDimensions:
2347 case builtin::Function::kTextureNumLayers:
2348 case builtin::Function::kTextureNumLevels:
2349 case builtin::Function::kTextureNumSamples: {
dan sinclair41e4d9a2022-05-01 14:40:55 +00002350 // All of these builtins use the GetDimensions() method on the texture
2351 bool is_ms =
dan sinclair4595fb72022-12-08 14:14:10 +00002352 texture_type->IsAnyOf<type::MultisampledTexture, type::DepthMultisampledTexture>();
dan sinclair41e4d9a2022-05-01 14:40:55 +00002353 int num_dimensions = 0;
2354 std::string swizzle;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00002355
dan sinclair41e4d9a2022-05-01 14:40:55 +00002356 switch (builtin->Type()) {
dan sinclair9543f742023-03-09 01:20:16 +00002357 case builtin::Function::kTextureDimensions:
dan sinclair41e4d9a2022-05-01 14:40:55 +00002358 switch (texture_type->dim()) {
dan sinclair3cbf3fc2023-01-21 19:16:15 +00002359 case type::TextureDimension::kNone:
dan sinclair41e4d9a2022-05-01 14:40:55 +00002360 TINT_ICE(Writer, diagnostics_) << "texture dimension is kNone";
2361 return false;
dan sinclair3cbf3fc2023-01-21 19:16:15 +00002362 case type::TextureDimension::k1d:
dan sinclair41e4d9a2022-05-01 14:40:55 +00002363 num_dimensions = 1;
2364 break;
dan sinclair3cbf3fc2023-01-21 19:16:15 +00002365 case type::TextureDimension::k2d:
dan sinclair41e4d9a2022-05-01 14:40:55 +00002366 num_dimensions = is_ms ? 3 : 2;
2367 swizzle = is_ms ? ".xy" : "";
2368 break;
dan sinclair3cbf3fc2023-01-21 19:16:15 +00002369 case type::TextureDimension::k2dArray:
dan sinclair41e4d9a2022-05-01 14:40:55 +00002370 num_dimensions = is_ms ? 4 : 3;
2371 swizzle = ".xy";
2372 break;
dan sinclair3cbf3fc2023-01-21 19:16:15 +00002373 case type::TextureDimension::k3d:
dan sinclair41e4d9a2022-05-01 14:40:55 +00002374 num_dimensions = 3;
2375 break;
dan sinclair3cbf3fc2023-01-21 19:16:15 +00002376 case type::TextureDimension::kCube:
dan sinclair41e4d9a2022-05-01 14:40:55 +00002377 num_dimensions = 2;
2378 break;
dan sinclair3cbf3fc2023-01-21 19:16:15 +00002379 case type::TextureDimension::kCubeArray:
dan sinclair41e4d9a2022-05-01 14:40:55 +00002380 num_dimensions = 3;
2381 swizzle = ".xy";
2382 break;
2383 }
2384 break;
dan sinclair9543f742023-03-09 01:20:16 +00002385 case builtin::Function::kTextureNumLayers:
dan sinclair41e4d9a2022-05-01 14:40:55 +00002386 switch (texture_type->dim()) {
2387 default:
2388 TINT_ICE(Writer, diagnostics_) << "texture dimension is not arrayed";
2389 return false;
dan sinclair3cbf3fc2023-01-21 19:16:15 +00002390 case type::TextureDimension::k2dArray:
dan sinclair41e4d9a2022-05-01 14:40:55 +00002391 num_dimensions = is_ms ? 4 : 3;
2392 swizzle = ".z";
2393 break;
dan sinclair3cbf3fc2023-01-21 19:16:15 +00002394 case type::TextureDimension::kCubeArray:
dan sinclair41e4d9a2022-05-01 14:40:55 +00002395 num_dimensions = 3;
2396 swizzle = ".z";
2397 break;
2398 }
2399 break;
dan sinclair9543f742023-03-09 01:20:16 +00002400 case builtin::Function::kTextureNumLevels:
dan sinclair41e4d9a2022-05-01 14:40:55 +00002401 switch (texture_type->dim()) {
2402 default:
2403 TINT_ICE(Writer, diagnostics_)
2404 << "texture dimension does not support mips";
2405 return false;
dan sinclair3cbf3fc2023-01-21 19:16:15 +00002406 case type::TextureDimension::k1d:
dan sinclair41e4d9a2022-05-01 14:40:55 +00002407 num_dimensions = 2;
2408 swizzle = ".y";
2409 break;
dan sinclair3cbf3fc2023-01-21 19:16:15 +00002410 case type::TextureDimension::k2d:
2411 case type::TextureDimension::kCube:
dan sinclair41e4d9a2022-05-01 14:40:55 +00002412 num_dimensions = 3;
2413 swizzle = ".z";
2414 break;
dan sinclair3cbf3fc2023-01-21 19:16:15 +00002415 case type::TextureDimension::k2dArray:
2416 case type::TextureDimension::k3d:
2417 case type::TextureDimension::kCubeArray:
dan sinclair41e4d9a2022-05-01 14:40:55 +00002418 num_dimensions = 4;
2419 swizzle = ".w";
2420 break;
2421 }
2422 break;
dan sinclair9543f742023-03-09 01:20:16 +00002423 case builtin::Function::kTextureNumSamples:
dan sinclair41e4d9a2022-05-01 14:40:55 +00002424 switch (texture_type->dim()) {
2425 default:
2426 TINT_ICE(Writer, diagnostics_)
2427 << "texture dimension does not support multisampling";
2428 return false;
dan sinclair3cbf3fc2023-01-21 19:16:15 +00002429 case type::TextureDimension::k2d:
dan sinclair41e4d9a2022-05-01 14:40:55 +00002430 num_dimensions = 3;
2431 swizzle = ".z";
2432 break;
dan sinclair3cbf3fc2023-01-21 19:16:15 +00002433 case type::TextureDimension::k2dArray:
dan sinclair41e4d9a2022-05-01 14:40:55 +00002434 num_dimensions = 4;
2435 swizzle = ".w";
2436 break;
2437 }
2438 break;
2439 default:
2440 TINT_ICE(Writer, diagnostics_) << "unexpected builtin";
2441 return false;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00002442 }
dan sinclair41e4d9a2022-05-01 14:40:55 +00002443
2444 auto* level_arg = arg(Usage::kLevel);
2445
2446 if (level_arg) {
2447 // `NumberOfLevels` is a non-optional argument if `MipLevel` was passed.
2448 // Increment the number of dimensions for the temporary vector to
2449 // accommodate this.
2450 num_dimensions++;
2451
2452 // If the swizzle was empty, the expression will evaluate to the whole
2453 // vector. As we've grown the vector by one element, we now need to
2454 // swizzle to keep the result expression equivalent.
2455 if (swizzle.empty()) {
2456 static constexpr const char* swizzles[] = {"", ".x", ".xy", ".xyz"};
2457 swizzle = swizzles[num_dimensions - 1];
2458 }
2459 }
2460
Ben Clayton884f9522023-01-12 22:52:57 +00002461 if (TINT_UNLIKELY(num_dimensions > 4)) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00002462 TINT_ICE(Writer, diagnostics_) << "Texture query builtin temporary vector has "
2463 << num_dimensions << " dimensions";
2464 return false;
2465 }
2466
2467 // Declare a variable to hold the queried texture info
2468 auto dims = UniqueIdentifier(kTempNamePrefix);
2469 if (num_dimensions == 1) {
Ben Clayton068eb3e2023-03-08 02:48:34 +00002470 line() << "uint " << dims << ";";
dan sinclair41e4d9a2022-05-01 14:40:55 +00002471 } else {
Ben Clayton068eb3e2023-03-08 02:48:34 +00002472 line() << "uint" << num_dimensions << " " << dims << ";";
dan sinclair41e4d9a2022-05-01 14:40:55 +00002473 }
2474
2475 { // texture.GetDimensions(...)
2476 auto pre = line();
2477 if (!EmitExpression(pre, texture)) {
2478 return false;
2479 }
2480 pre << ".GetDimensions(";
2481
2482 if (level_arg) {
2483 if (!EmitExpression(pre, level_arg)) {
2484 return false;
2485 }
2486 pre << ", ";
dan sinclair9543f742023-03-09 01:20:16 +00002487 } else if (builtin->Type() == builtin::Function::kTextureNumLevels) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00002488 pre << "0, ";
2489 }
2490
2491 if (num_dimensions == 1) {
2492 pre << dims;
2493 } else {
2494 static constexpr char xyzw[] = {'x', 'y', 'z', 'w'};
Ben Clayton884f9522023-01-12 22:52:57 +00002495 if (TINT_UNLIKELY(num_dimensions < 0 || num_dimensions > 4)) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00002496 TINT_ICE(Writer, diagnostics_)
2497 << "vector dimensions are " << num_dimensions;
2498 return false;
2499 }
2500 for (int i = 0; i < num_dimensions; i++) {
2501 if (i > 0) {
2502 pre << ", ";
2503 }
2504 pre << dims << "." << xyzw[i];
2505 }
2506 }
2507
2508 pre << ");";
2509 }
2510
2511 // The out parameters of the GetDimensions() call is now in temporary
2512 // `dims` variable. This may be packed with other data, so the final
2513 // expression may require a swizzle.
2514 out << dims << swizzle;
2515 return true;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00002516 }
dan sinclair41e4d9a2022-05-01 14:40:55 +00002517 default:
2518 break;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00002519 }
Ryan Harrisondbc13af2022-02-21 15:19:07 +00002520
Austin Eng86a617f2022-05-19 20:08:19 +00002521 if (!EmitExpression(out, texture)) {
Ryan Harrisondbc13af2022-02-21 15:19:07 +00002522 return false;
Austin Eng86a617f2022-05-19 20:08:19 +00002523 }
dan sinclair41e4d9a2022-05-01 14:40:55 +00002524
2525 // If pack_level_in_coords is true, then the mip level will be appended as the
2526 // last value of the coordinates argument. If the WGSL builtin overload does
2527 // not have a level parameter and pack_level_in_coords is true, then a zero
2528 // mip level will be inserted.
2529 bool pack_level_in_coords = false;
2530
2531 uint32_t hlsl_ret_width = 4u;
2532
2533 switch (builtin->Type()) {
dan sinclair9543f742023-03-09 01:20:16 +00002534 case builtin::Function::kTextureSample:
dan sinclair41e4d9a2022-05-01 14:40:55 +00002535 out << ".Sample(";
2536 break;
dan sinclair9543f742023-03-09 01:20:16 +00002537 case builtin::Function::kTextureSampleBias:
dan sinclair41e4d9a2022-05-01 14:40:55 +00002538 out << ".SampleBias(";
2539 break;
dan sinclair9543f742023-03-09 01:20:16 +00002540 case builtin::Function::kTextureSampleLevel:
dan sinclair41e4d9a2022-05-01 14:40:55 +00002541 out << ".SampleLevel(";
2542 break;
dan sinclair9543f742023-03-09 01:20:16 +00002543 case builtin::Function::kTextureSampleGrad:
dan sinclair41e4d9a2022-05-01 14:40:55 +00002544 out << ".SampleGrad(";
2545 break;
dan sinclair9543f742023-03-09 01:20:16 +00002546 case builtin::Function::kTextureSampleCompare:
dan sinclair41e4d9a2022-05-01 14:40:55 +00002547 out << ".SampleCmp(";
2548 hlsl_ret_width = 1;
2549 break;
dan sinclair9543f742023-03-09 01:20:16 +00002550 case builtin::Function::kTextureSampleCompareLevel:
dan sinclair41e4d9a2022-05-01 14:40:55 +00002551 out << ".SampleCmpLevelZero(";
2552 hlsl_ret_width = 1;
2553 break;
dan sinclair9543f742023-03-09 01:20:16 +00002554 case builtin::Function::kTextureLoad:
dan sinclair41e4d9a2022-05-01 14:40:55 +00002555 out << ".Load(";
2556 // Multisampled textures do not support mip-levels.
dan sinclair4595fb72022-12-08 14:14:10 +00002557 if (!texture_type->Is<type::MultisampledTexture>()) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00002558 pack_level_in_coords = true;
2559 }
2560 break;
dan sinclair9543f742023-03-09 01:20:16 +00002561 case builtin::Function::kTextureGather:
dan sinclair41e4d9a2022-05-01 14:40:55 +00002562 out << ".Gather";
2563 if (builtin->Parameters()[0]->Usage() == sem::ParameterUsage::kComponent) {
dan sinclair5addefb2022-12-14 20:46:32 +00002564 switch (call->Arguments()[0]->ConstantValue()->ValueAs<AInt>()) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00002565 case 0:
2566 out << "Red";
2567 break;
2568 case 1:
2569 out << "Green";
2570 break;
2571 case 2:
2572 out << "Blue";
2573 break;
2574 case 3:
2575 out << "Alpha";
2576 break;
2577 }
2578 }
2579 out << "(";
2580 break;
dan sinclair9543f742023-03-09 01:20:16 +00002581 case builtin::Function::kTextureGatherCompare:
dan sinclair41e4d9a2022-05-01 14:40:55 +00002582 out << ".GatherCmp(";
2583 break;
dan sinclair9543f742023-03-09 01:20:16 +00002584 case builtin::Function::kTextureStore:
dan sinclair41e4d9a2022-05-01 14:40:55 +00002585 out << "[";
2586 break;
2587 default:
2588 diagnostics_.add_error(diag::System::Writer,
2589 "Internal compiler error: Unhandled texture builtin '" +
2590 std::string(builtin->str()) + "'");
2591 return false;
2592 }
2593
2594 if (auto* sampler = arg(Usage::kSampler)) {
Austin Eng86a617f2022-05-19 20:08:19 +00002595 if (!EmitExpression(out, sampler)) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00002596 return false;
Austin Eng86a617f2022-05-19 20:08:19 +00002597 }
dan sinclair41e4d9a2022-05-01 14:40:55 +00002598 out << ", ";
2599 }
2600
2601 auto* param_coords = arg(Usage::kCoords);
Ben Clayton884f9522023-01-12 22:52:57 +00002602 if (TINT_UNLIKELY(!param_coords)) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00002603 TINT_ICE(Writer, diagnostics_) << "missing coords argument";
2604 return false;
2605 }
2606
2607 auto emit_vector_appended_with_i32_zero = [&](const ast::Expression* vector) {
dan sinclaird37ecf92022-12-08 16:39:59 +00002608 auto* i32 = builder_.create<type::I32>();
Ben Clayton0ce9ab02022-05-05 20:23:40 +00002609 auto* zero = builder_.Expr(0_i);
dan sinclair41e4d9a2022-05-01 14:40:55 +00002610 auto* stmt = builder_.Sem().Get(vector)->Stmt();
Ben Clayton3fb9a3f2023-02-04 21:20:26 +00002611 builder_.Sem().Add(zero, builder_.create<sem::ValueExpression>(
2612 zero, i32, sem::EvaluationStage::kRuntime, stmt,
2613 /* constant_value */ nullptr,
2614 /* has_side_effects */ false));
dan sinclair41e4d9a2022-05-01 14:40:55 +00002615 auto* packed = AppendVector(&builder_, vector, zero);
2616 return EmitExpression(out, packed->Declaration());
2617 };
2618
2619 auto emit_vector_appended_with_level = [&](const ast::Expression* vector) {
2620 if (auto* level = arg(Usage::kLevel)) {
2621 auto* packed = AppendVector(&builder_, vector, level);
2622 return EmitExpression(out, packed->Declaration());
2623 }
2624 return emit_vector_appended_with_i32_zero(vector);
2625 };
2626
2627 if (auto* array_index = arg(Usage::kArrayIndex)) {
2628 // Array index needs to be appended to the coordinates.
2629 auto* packed = AppendVector(&builder_, param_coords, array_index);
2630 if (pack_level_in_coords) {
2631 // Then mip level needs to be appended to the coordinates.
2632 if (!emit_vector_appended_with_level(packed->Declaration())) {
2633 return false;
2634 }
2635 } else {
2636 if (!EmitExpression(out, packed->Declaration())) {
2637 return false;
2638 }
2639 }
2640 } else if (pack_level_in_coords) {
2641 // Mip level needs to be appended to the coordinates.
2642 if (!emit_vector_appended_with_level(param_coords)) {
2643 return false;
2644 }
Ryan Harrisondbc13af2022-02-21 15:19:07 +00002645 } else {
dan sinclair41e4d9a2022-05-01 14:40:55 +00002646 if (!EmitExpression(out, param_coords)) {
2647 return false;
2648 }
Ryan Harrisondbc13af2022-02-21 15:19:07 +00002649 }
Ryan Harrisondbc13af2022-02-21 15:19:07 +00002650
dan sinclair41e4d9a2022-05-01 14:40:55 +00002651 for (auto usage : {Usage::kDepthRef, Usage::kBias, Usage::kLevel, Usage::kDdx, Usage::kDdy,
2652 Usage::kSampleIndex, Usage::kOffset}) {
2653 if (usage == Usage::kLevel && pack_level_in_coords) {
2654 continue; // mip level already packed in coordinates.
2655 }
2656 if (auto* e = arg(usage)) {
2657 out << ", ";
2658 if (!EmitExpression(out, e)) {
2659 return false;
2660 }
2661 }
Ryan Harrisondbc13af2022-02-21 15:19:07 +00002662 }
Ryan Harrisondbc13af2022-02-21 15:19:07 +00002663
dan sinclair9543f742023-03-09 01:20:16 +00002664 if (builtin->Type() == builtin::Function::kTextureStore) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00002665 out << "] = ";
2666 if (!EmitExpression(out, arg(Usage::kValue))) {
2667 return false;
2668 }
2669 } else {
2670 out << ")";
Ryan Harrisondbc13af2022-02-21 15:19:07 +00002671
dan sinclair41e4d9a2022-05-01 14:40:55 +00002672 // If the builtin return type does not match the number of elements of the
2673 // HLSL builtin, we need to swizzle the expression to generate the correct
2674 // number of components.
2675 uint32_t wgsl_ret_width = 1;
dan sinclair0e780da2022-12-08 22:21:24 +00002676 if (auto* vec = builtin->ReturnType()->As<type::Vector>()) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00002677 wgsl_ret_width = vec->Width();
2678 }
2679 if (wgsl_ret_width < hlsl_ret_width) {
2680 out << ".";
2681 for (uint32_t i = 0; i < wgsl_ret_width; i++) {
2682 out << "xyz"[i];
2683 }
2684 }
Ben Clayton884f9522023-01-12 22:52:57 +00002685 if (TINT_UNLIKELY(wgsl_ret_width > hlsl_ret_width)) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00002686 TINT_ICE(Writer, diagnostics_)
2687 << "WGSL return width (" << wgsl_ret_width << ") is wider than HLSL return width ("
2688 << hlsl_ret_width << ") for " << builtin->Type();
2689 return false;
2690 }
Ryan Harrisondbc13af2022-02-21 15:19:07 +00002691 }
Ryan Harrisondbc13af2022-02-21 15:19:07 +00002692
dan sinclair41e4d9a2022-05-01 14:40:55 +00002693 return true;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00002694}
2695
2696std::string GeneratorImpl::generate_builtin_name(const sem::Builtin* builtin) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00002697 switch (builtin->Type()) {
dan sinclair9543f742023-03-09 01:20:16 +00002698 case builtin::Function::kAbs:
2699 case builtin::Function::kAcos:
2700 case builtin::Function::kAll:
2701 case builtin::Function::kAny:
2702 case builtin::Function::kAsin:
2703 case builtin::Function::kAtan:
2704 case builtin::Function::kAtan2:
2705 case builtin::Function::kCeil:
2706 case builtin::Function::kClamp:
2707 case builtin::Function::kCos:
2708 case builtin::Function::kCosh:
2709 case builtin::Function::kCross:
2710 case builtin::Function::kDeterminant:
2711 case builtin::Function::kDistance:
2712 case builtin::Function::kDot:
2713 case builtin::Function::kExp:
2714 case builtin::Function::kExp2:
2715 case builtin::Function::kFloor:
2716 case builtin::Function::kFrexp:
2717 case builtin::Function::kLdexp:
2718 case builtin::Function::kLength:
2719 case builtin::Function::kLog:
2720 case builtin::Function::kLog2:
2721 case builtin::Function::kMax:
2722 case builtin::Function::kMin:
2723 case builtin::Function::kModf:
2724 case builtin::Function::kNormalize:
2725 case builtin::Function::kPow:
2726 case builtin::Function::kReflect:
2727 case builtin::Function::kRefract:
2728 case builtin::Function::kRound:
2729 case builtin::Function::kSaturate:
2730 case builtin::Function::kSin:
2731 case builtin::Function::kSinh:
2732 case builtin::Function::kSqrt:
2733 case builtin::Function::kStep:
2734 case builtin::Function::kTan:
2735 case builtin::Function::kTanh:
2736 case builtin::Function::kTranspose:
dan sinclair41e4d9a2022-05-01 14:40:55 +00002737 return builtin->str();
dan sinclair9543f742023-03-09 01:20:16 +00002738 case builtin::Function::kCountOneBits: // uint
dan sinclair41e4d9a2022-05-01 14:40:55 +00002739 return "countbits";
dan sinclair9543f742023-03-09 01:20:16 +00002740 case builtin::Function::kDpdx:
dan sinclair41e4d9a2022-05-01 14:40:55 +00002741 return "ddx";
dan sinclair9543f742023-03-09 01:20:16 +00002742 case builtin::Function::kDpdxCoarse:
dan sinclair41e4d9a2022-05-01 14:40:55 +00002743 return "ddx_coarse";
dan sinclair9543f742023-03-09 01:20:16 +00002744 case builtin::Function::kDpdxFine:
dan sinclair41e4d9a2022-05-01 14:40:55 +00002745 return "ddx_fine";
dan sinclair9543f742023-03-09 01:20:16 +00002746 case builtin::Function::kDpdy:
dan sinclair41e4d9a2022-05-01 14:40:55 +00002747 return "ddy";
dan sinclair9543f742023-03-09 01:20:16 +00002748 case builtin::Function::kDpdyCoarse:
dan sinclair41e4d9a2022-05-01 14:40:55 +00002749 return "ddy_coarse";
dan sinclair9543f742023-03-09 01:20:16 +00002750 case builtin::Function::kDpdyFine:
dan sinclair41e4d9a2022-05-01 14:40:55 +00002751 return "ddy_fine";
dan sinclair9543f742023-03-09 01:20:16 +00002752 case builtin::Function::kFaceForward:
dan sinclair41e4d9a2022-05-01 14:40:55 +00002753 return "faceforward";
dan sinclair9543f742023-03-09 01:20:16 +00002754 case builtin::Function::kFract:
dan sinclair41e4d9a2022-05-01 14:40:55 +00002755 return "frac";
dan sinclair9543f742023-03-09 01:20:16 +00002756 case builtin::Function::kFma:
dan sinclair41e4d9a2022-05-01 14:40:55 +00002757 return "mad";
dan sinclair9543f742023-03-09 01:20:16 +00002758 case builtin::Function::kFwidth:
2759 case builtin::Function::kFwidthCoarse:
2760 case builtin::Function::kFwidthFine:
dan sinclair41e4d9a2022-05-01 14:40:55 +00002761 return "fwidth";
dan sinclair9543f742023-03-09 01:20:16 +00002762 case builtin::Function::kInverseSqrt:
dan sinclair41e4d9a2022-05-01 14:40:55 +00002763 return "rsqrt";
dan sinclair9543f742023-03-09 01:20:16 +00002764 case builtin::Function::kMix:
dan sinclair41e4d9a2022-05-01 14:40:55 +00002765 return "lerp";
dan sinclair9543f742023-03-09 01:20:16 +00002766 case builtin::Function::kReverseBits: // uint
dan sinclair41e4d9a2022-05-01 14:40:55 +00002767 return "reversebits";
dan sinclair9543f742023-03-09 01:20:16 +00002768 case builtin::Function::kSmoothstep:
dan sinclair41e4d9a2022-05-01 14:40:55 +00002769 return "smoothstep";
2770 default:
2771 diagnostics_.add_error(diag::System::Writer,
2772 "Unknown builtin method: " + std::string(builtin->str()));
2773 }
Ryan Harrisondbc13af2022-02-21 15:19:07 +00002774
dan sinclair41e4d9a2022-05-01 14:40:55 +00002775 return "";
Ryan Harrisondbc13af2022-02-21 15:19:07 +00002776}
2777
2778bool GeneratorImpl::EmitCase(const ast::SwitchStatement* s, size_t case_idx) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00002779 auto* stmt = s->body[case_idx];
dan sinclairf148f082022-10-19 15:55:02 +00002780 auto* sem = builder_.Sem().Get<sem::CaseStatement>(stmt);
2781 for (auto* selector : sem->Selectors()) {
2782 auto out = line();
2783 if (selector->IsDefault()) {
2784 out << "default";
2785 } else {
dan sinclair41e4d9a2022-05-01 14:40:55 +00002786 out << "case ";
Ben Clayton329dfd72022-11-23 00:05:05 +00002787 if (!EmitConstant(out, selector->Value(), /* is_variable_initializer */ false)) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00002788 return false;
2789 }
dan sinclairf148f082022-10-19 15:55:02 +00002790 }
2791 out << ":";
2792 if (selector == sem->Selectors().back()) {
2793 out << " {";
dan sinclair41e4d9a2022-05-01 14:40:55 +00002794 }
2795 }
2796
2797 increment_indent();
2798 TINT_DEFER({
2799 decrement_indent();
2800 line() << "}";
2801 });
2802
2803 // Emit the case statement
2804 if (!EmitStatements(stmt->body->statements)) {
Ryan Harrisondbc13af2022-02-21 15:19:07 +00002805 return false;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00002806 }
Ryan Harrisondbc13af2022-02-21 15:19:07 +00002807
dan sinclair12fa3032023-04-19 23:52:33 +00002808 if (!tint::utils::IsAnyOf<ast::BreakStatement>(stmt->body->Last())) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00002809 line() << "break;";
2810 }
Ryan Harrisondbc13af2022-02-21 15:19:07 +00002811
dan sinclair41e4d9a2022-05-01 14:40:55 +00002812 return true;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00002813}
2814
2815bool GeneratorImpl::EmitContinue(const ast::ContinueStatement*) {
dan sinclair4b88dbc2022-06-16 15:27:38 +00002816 if (!emit_continuing_ || !emit_continuing_()) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00002817 return false;
2818 }
2819 line() << "continue;";
2820 return true;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00002821}
2822
2823bool GeneratorImpl::EmitDiscard(const ast::DiscardStatement*) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00002824 // TODO(dsinclair): Verify this is correct when the discard semantics are
2825 // defined for WGSL (https://github.com/gpuweb/gpuweb/issues/361)
2826 line() << "discard;";
2827 return true;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00002828}
2829
dan sinclair2b9d5b32023-02-28 14:49:25 +00002830bool GeneratorImpl::EmitExpression(utils::StringStream& out, const ast::Expression* expr) {
Ben Clayton0b4a2f12023-02-05 22:59:40 +00002831 if (auto* sem = builder_.Sem().GetVal(expr)) {
Ben Claytonaa037ac2022-06-29 19:07:30 +00002832 if (auto* constant = sem->ConstantValue()) {
Ben Clayton329dfd72022-11-23 00:05:05 +00002833 bool is_variable_initializer = false;
2834 if (auto* stmt = sem->Stmt()) {
2835 if (auto* decl = As<ast::VariableDeclStatement>(stmt->Declaration())) {
2836 is_variable_initializer = decl->variable->initializer == expr;
2837 }
2838 }
2839 return EmitConstant(out, constant, is_variable_initializer);
Ben Claytone9f8b092022-06-01 13:14:39 +00002840 }
2841 }
dan sinclair41e4d9a2022-05-01 14:40:55 +00002842 return Switch(
Ben Claytonb90b6bf2022-08-23 16:23:05 +00002843 expr, //
2844 [&](const ast::IndexAccessorExpression* a) { return EmitIndexAccessor(out, a); },
2845 [&](const ast::BinaryExpression* b) { return EmitBinary(out, b); },
2846 [&](const ast::BitcastExpression* b) { return EmitBitcast(out, b); },
2847 [&](const ast::CallExpression* c) { return EmitCall(out, c); },
2848 [&](const ast::IdentifierExpression* i) { return EmitIdentifier(out, i); },
2849 [&](const ast::LiteralExpression* l) { return EmitLiteral(out, l); },
2850 [&](const ast::MemberAccessorExpression* m) { return EmitMemberAccessor(out, m); },
2851 [&](const ast::UnaryOpExpression* u) { return EmitUnaryOp(out, u); },
2852 [&](Default) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00002853 diagnostics_.add_error(diag::System::Writer, "unknown expression type: " +
2854 std::string(expr->TypeInfo().name));
2855 return false;
2856 });
Ryan Harrisondbc13af2022-02-21 15:19:07 +00002857}
2858
dan sinclair2b9d5b32023-02-28 14:49:25 +00002859bool GeneratorImpl::EmitIdentifier(utils::StringStream& out,
2860 const ast::IdentifierExpression* expr) {
dan sinclaird026e132023-04-18 19:38:25 +00002861 out << expr->identifier->symbol.Name();
dan sinclair41e4d9a2022-05-01 14:40:55 +00002862 return true;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00002863}
2864
2865bool GeneratorImpl::EmitIf(const ast::IfStatement* stmt) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00002866 {
2867 auto out = line();
2868 out << "if (";
2869 if (!EmitExpression(out, stmt->condition)) {
2870 return false;
2871 }
2872 out << ") {";
Ryan Harrisondbc13af2022-02-21 15:19:07 +00002873 }
Ryan Harrisondbc13af2022-02-21 15:19:07 +00002874
dan sinclair41e4d9a2022-05-01 14:40:55 +00002875 if (!EmitStatementsWithIndent(stmt->body->statements)) {
James Price26ebe5e2022-04-29 00:14:53 +00002876 return false;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00002877 }
Ryan Harrisondbc13af2022-02-21 15:19:07 +00002878
dan sinclair41e4d9a2022-05-01 14:40:55 +00002879 if (stmt->else_statement) {
2880 line() << "} else {";
2881 if (auto* block = stmt->else_statement->As<ast::BlockStatement>()) {
2882 if (!EmitStatementsWithIndent(block->statements)) {
2883 return false;
2884 }
2885 } else {
Ben Clayton783b1692022-08-02 17:03:35 +00002886 if (!EmitStatementsWithIndent(utils::Vector{stmt->else_statement})) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00002887 return false;
2888 }
2889 }
2890 }
2891 line() << "}";
2892
2893 return true;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00002894}
2895
2896bool GeneratorImpl::EmitFunction(const ast::Function* func) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00002897 auto* sem = builder_.Sem().Get(func);
Ryan Harrisondbc13af2022-02-21 15:19:07 +00002898
Antonio Maiorano08f4b552022-05-31 13:20:28 +00002899 // Emit storage atomic helpers
2900 if (auto* intrinsic =
James Priceb4acbb82023-05-11 21:27:16 +00002901 ast::GetAttribute<ast::transform::DecomposeMemoryAccess::Intrinsic>(func->attributes)) {
dan sinclair2a651632023-02-19 04:03:55 +00002902 if (intrinsic->address_space == builtin::AddressSpace::kStorage && intrinsic->IsAtomic()) {
Antonio Maiorano08f4b552022-05-31 13:20:28 +00002903 if (!EmitStorageAtomicIntrinsic(func, intrinsic)) {
2904 return false;
2905 }
2906 }
2907 return true;
2908 }
2909
dan sinclair41e4d9a2022-05-01 14:40:55 +00002910 if (ast::HasAttribute<ast::InternalAttribute>(func->attributes)) {
2911 // An internal function. Do not emit.
2912 return true;
2913 }
Ryan Harrisondbc13af2022-02-21 15:19:07 +00002914
dan sinclair41e4d9a2022-05-01 14:40:55 +00002915 {
2916 auto out = line();
dan sinclaird026e132023-04-18 19:38:25 +00002917 auto name = func->name->symbol.Name();
dan sinclair41e4d9a2022-05-01 14:40:55 +00002918 // If the function returns an array, then we need to declare a typedef for
2919 // this.
dan sinclair946858a2022-12-08 22:21:24 +00002920 if (sem->ReturnType()->Is<type::Array>()) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00002921 auto typedef_name = UniqueIdentifier(name + "_ret");
2922 auto pre = line();
2923 pre << "typedef ";
dan sinclair2a651632023-02-19 04:03:55 +00002924 if (!EmitTypeAndName(pre, sem->ReturnType(), builtin::AddressSpace::kUndefined,
dan sinclairb6cc4cb2023-02-19 04:01:29 +00002925 builtin::Access::kReadWrite, typedef_name)) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00002926 return false;
2927 }
2928 pre << ";";
2929 out << typedef_name;
2930 } else {
dan sinclair2a651632023-02-19 04:03:55 +00002931 if (!EmitType(out, sem->ReturnType(), builtin::AddressSpace::kUndefined,
dan sinclairb6cc4cb2023-02-19 04:01:29 +00002932 builtin::Access::kReadWrite, "")) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00002933 return false;
2934 }
2935 }
2936
2937 out << " " << name << "(";
2938
2939 bool first = true;
2940
2941 for (auto* v : sem->Parameters()) {
2942 if (!first) {
2943 out << ", ";
2944 }
2945 first = false;
2946
2947 auto const* type = v->Type();
dan sinclair2a651632023-02-19 04:03:55 +00002948 auto address_space = builtin::AddressSpace::kUndefined;
dan sinclairb6cc4cb2023-02-19 04:01:29 +00002949 auto access = builtin::Access::kUndefined;
dan sinclair41e4d9a2022-05-01 14:40:55 +00002950
dan sinclair4d56b482022-12-08 17:50:50 +00002951 if (auto* ptr = type->As<type::Pointer>()) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00002952 type = ptr->StoreType();
dan sinclairff7cf212022-10-03 14:05:23 +00002953 switch (ptr->AddressSpace()) {
dan sinclair2a651632023-02-19 04:03:55 +00002954 case builtin::AddressSpace::kStorage:
2955 case builtin::AddressSpace::kUniform:
Ben Clayton2032d032022-06-15 19:32:37 +00002956 // Not allowed by WGSL, but is used by certain transforms (e.g. DMA) to pass
2957 // storage buffers and uniform buffers down into transform-generated
2958 // functions. In this situation we want to generate the parameter without an
dan sinclairff7cf212022-10-03 14:05:23 +00002959 // 'inout', using the address space and access from the pointer.
2960 address_space = ptr->AddressSpace();
Ben Clayton2032d032022-06-15 19:32:37 +00002961 access = ptr->Access();
2962 break;
2963 default:
2964 // Transform regular WGSL pointer parameters in to `inout` parameters.
2965 out << "inout ";
2966 }
dan sinclair41e4d9a2022-05-01 14:40:55 +00002967 }
2968
Ben Clayton1b90f932023-02-18 12:37:34 +00002969 // Note: WGSL only allows for AddressSpace::kUndefined on parameters, however
dan sinclair41e4d9a2022-05-01 14:40:55 +00002970 // the sanitizer transforms generates load / store functions for storage
2971 // or uniform buffers. These functions have a buffer parameter with
dan sinclairff7cf212022-10-03 14:05:23 +00002972 // AddressSpace::kStorage or AddressSpace::kUniform. This is required to
dan sinclair41e4d9a2022-05-01 14:40:55 +00002973 // correctly translate the parameter to a [RW]ByteAddressBuffer for
2974 // storage buffers and a uint4[N] for uniform buffers.
dan sinclairff7cf212022-10-03 14:05:23 +00002975 if (!EmitTypeAndName(out, type, address_space, access,
dan sinclaird026e132023-04-18 19:38:25 +00002976 v->Declaration()->name->symbol.Name())) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00002977 return false;
2978 }
2979 }
2980 out << ") {";
2981 }
2982
dan sinclaird37ecf92022-12-08 16:39:59 +00002983 if (sem->DiscardStatement() && !sem->ReturnType()->Is<type::Void>()) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00002984 // BUG(crbug.com/tint/1081): work around non-void functions with discard
2985 // failing compilation sometimes
2986 if (!EmitFunctionBodyWithDiscard(func)) {
2987 return false;
2988 }
Ryan Harrisondbc13af2022-02-21 15:19:07 +00002989 } else {
dan sinclair41e4d9a2022-05-01 14:40:55 +00002990 if (!EmitStatementsWithIndent(func->body->statements)) {
2991 return false;
2992 }
Ryan Harrisondbc13af2022-02-21 15:19:07 +00002993 }
2994
dan sinclair41e4d9a2022-05-01 14:40:55 +00002995 line() << "}";
Ryan Harrisondbc13af2022-02-21 15:19:07 +00002996
dan sinclair41e4d9a2022-05-01 14:40:55 +00002997 return true;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00002998}
2999
3000bool GeneratorImpl::EmitFunctionBodyWithDiscard(const ast::Function* func) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00003001 // FXC sometimes fails to compile functions that discard with 'Not all control
3002 // paths return a value'. We work around this by wrapping the function body
3003 // within an "if (true) { <body> } return <default return type obj>;" so that
3004 // there is always an (unused) return statement.
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003005
dan sinclair41e4d9a2022-05-01 14:40:55 +00003006 auto* sem = builder_.Sem().Get(func);
dan sinclaird37ecf92022-12-08 16:39:59 +00003007 TINT_ASSERT(Writer, sem->DiscardStatement() && !sem->ReturnType()->Is<type::Void>());
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003008
dan sinclair41e4d9a2022-05-01 14:40:55 +00003009 ScopedIndent si(this);
3010 line() << "if (true) {";
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003011
dan sinclair41e4d9a2022-05-01 14:40:55 +00003012 if (!EmitStatementsWithIndent(func->body->statements)) {
3013 return false;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003014 }
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003015
dan sinclair41e4d9a2022-05-01 14:40:55 +00003016 line() << "}";
3017
3018 // Return an unused result that matches the type of the return value
dan sinclaird026e132023-04-18 19:38:25 +00003019 auto name = builder_.Symbols().New("unused").Name();
dan sinclair41e4d9a2022-05-01 14:40:55 +00003020 {
3021 auto out = line();
dan sinclair2a651632023-02-19 04:03:55 +00003022 if (!EmitTypeAndName(out, sem->ReturnType(), builtin::AddressSpace::kUndefined,
dan sinclairb6cc4cb2023-02-19 04:01:29 +00003023 builtin::Access::kReadWrite, name)) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00003024 return false;
3025 }
3026 out << ";";
3027 }
3028 line() << "return " << name << ";";
3029
3030 return true;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003031}
3032
3033bool GeneratorImpl::EmitGlobalVariable(const ast::Variable* global) {
Ben Claytondcdf66e2022-06-17 12:48:51 +00003034 return Switch(
3035 global, //
3036 [&](const ast::Var* var) {
3037 auto* sem = builder_.Sem().Get(global);
dan sinclairff7cf212022-10-03 14:05:23 +00003038 switch (sem->AddressSpace()) {
dan sinclair2a651632023-02-19 04:03:55 +00003039 case builtin::AddressSpace::kUniform:
Ben Claytondcdf66e2022-06-17 12:48:51 +00003040 return EmitUniformVariable(var, sem);
dan sinclair2a651632023-02-19 04:03:55 +00003041 case builtin::AddressSpace::kStorage:
Ben Claytondcdf66e2022-06-17 12:48:51 +00003042 return EmitStorageVariable(var, sem);
dan sinclair2a651632023-02-19 04:03:55 +00003043 case builtin::AddressSpace::kHandle:
Ben Claytondcdf66e2022-06-17 12:48:51 +00003044 return EmitHandleVariable(var, sem);
dan sinclair2a651632023-02-19 04:03:55 +00003045 case builtin::AddressSpace::kPrivate:
Ben Claytondcdf66e2022-06-17 12:48:51 +00003046 return EmitPrivateVariable(sem);
dan sinclair2a651632023-02-19 04:03:55 +00003047 case builtin::AddressSpace::kWorkgroup:
Ben Claytondcdf66e2022-06-17 12:48:51 +00003048 return EmitWorkgroupVariable(sem);
dan sinclair2a651632023-02-19 04:03:55 +00003049 case builtin::AddressSpace::kPushConstant:
dan sinclair4abf28e2022-08-02 15:55:35 +00003050 diagnostics_.add_error(
3051 diag::System::Writer,
dan sinclairff7cf212022-10-03 14:05:23 +00003052 "unhandled address space " + utils::ToString(sem->AddressSpace()));
dan sinclair4abf28e2022-08-02 15:55:35 +00003053 return false;
dan sinclair8dbd4d02022-07-27 18:54:05 +00003054 default: {
Ben Claytondcdf66e2022-06-17 12:48:51 +00003055 TINT_ICE(Writer, diagnostics_)
dan sinclairff7cf212022-10-03 14:05:23 +00003056 << "unhandled address space " << sem->AddressSpace();
Ben Claytondcdf66e2022-06-17 12:48:51 +00003057 return false;
dan sinclair8dbd4d02022-07-27 18:54:05 +00003058 }
Ben Claytondcdf66e2022-06-17 12:48:51 +00003059 }
3060 },
dan sinclairf6a94042022-09-09 16:16:19 +00003061 [&](const ast::Override*) {
3062 // Override is removed with SubstituteOverride
Ben Clayton490d9882022-09-21 21:05:45 +00003063 diagnostics_.add_error(diag::System::Writer,
Ben Claytonf10a5792022-10-13 13:47:39 +00003064 "override-expressions should have been removed with the "
Ben Clayton490d9882022-09-21 21:05:45 +00003065 "SubstituteOverride transform");
dan sinclairf6a94042022-09-09 16:16:19 +00003066 return false;
3067 },
Ben Clayton19576e92022-06-28 12:44:16 +00003068 [&](const ast::Const*) {
3069 return true; // Constants are embedded at their use
3070 },
Ben Claytondcdf66e2022-06-17 12:48:51 +00003071 [&](Default) {
3072 TINT_ICE(Writer, diagnostics_)
3073 << "unhandled global variable type " << global->TypeInfo().name;
dan sinclair4abf28e2022-08-02 15:55:35 +00003074
Ben Claytondcdf66e2022-06-17 12:48:51 +00003075 return false;
3076 });
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003077}
3078
Ben Claytondcdf66e2022-06-17 12:48:51 +00003079bool GeneratorImpl::EmitUniformVariable(const ast::Var* var, const sem::Variable* sem) {
Ben Clayton5f4847c2023-04-19 13:24:27 +00003080 auto binding_point = *sem->As<sem::GlobalVariable>()->BindingPoint();
Ben Claytondcdf66e2022-06-17 12:48:51 +00003081 auto* type = sem->Type()->UnwrapRef();
dan sinclaird026e132023-04-18 19:38:25 +00003082 auto name = var->name->symbol.Name();
dan sinclair41e4d9a2022-05-01 14:40:55 +00003083 line() << "cbuffer cbuffer_" << name << RegisterAndSpace('b', binding_point) << " {";
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003084
dan sinclair41e4d9a2022-05-01 14:40:55 +00003085 {
3086 ScopedIndent si(this);
3087 auto out = line();
dan sinclair2a651632023-02-19 04:03:55 +00003088 if (!EmitTypeAndName(out, type, builtin::AddressSpace::kUniform, sem->Access(), name)) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00003089 return false;
3090 }
3091 out << ";";
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003092 }
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003093
dan sinclair41e4d9a2022-05-01 14:40:55 +00003094 line() << "};";
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003095
dan sinclair41e4d9a2022-05-01 14:40:55 +00003096 return true;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003097}
3098
Ben Claytondcdf66e2022-06-17 12:48:51 +00003099bool GeneratorImpl::EmitStorageVariable(const ast::Var* var, const sem::Variable* sem) {
3100 auto* type = sem->Type()->UnwrapRef();
dan sinclair41e4d9a2022-05-01 14:40:55 +00003101 auto out = line();
dan sinclair2a651632023-02-19 04:03:55 +00003102 if (!EmitTypeAndName(out, type, builtin::AddressSpace::kStorage, sem->Access(),
dan sinclaird026e132023-04-18 19:38:25 +00003103 var->name->symbol.Name())) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00003104 return false;
3105 }
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003106
dan sinclairacdf6e12022-08-24 15:47:25 +00003107 auto* global_sem = sem->As<sem::GlobalVariable>();
dan sinclairb6cc4cb2023-02-19 04:01:29 +00003108 out << RegisterAndSpace(sem->Access() == builtin::Access::kRead ? 't' : 'u',
Ben Clayton5f4847c2023-04-19 13:24:27 +00003109 *global_sem->BindingPoint())
dan sinclair41e4d9a2022-05-01 14:40:55 +00003110 << ";";
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003111
dan sinclair41e4d9a2022-05-01 14:40:55 +00003112 return true;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003113}
3114
Ben Claytondcdf66e2022-06-17 12:48:51 +00003115bool GeneratorImpl::EmitHandleVariable(const ast::Var* var, const sem::Variable* sem) {
3116 auto* unwrapped_type = sem->Type()->UnwrapRef();
dan sinclair41e4d9a2022-05-01 14:40:55 +00003117 auto out = line();
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003118
dan sinclaird026e132023-04-18 19:38:25 +00003119 auto name = var->name->symbol.Name();
Ben Claytondcdf66e2022-06-17 12:48:51 +00003120 auto* type = sem->Type()->UnwrapRef();
dan sinclairff7cf212022-10-03 14:05:23 +00003121 if (!EmitTypeAndName(out, type, sem->AddressSpace(), sem->Access(), name)) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00003122 return false;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003123 }
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003124
dan sinclair41e4d9a2022-05-01 14:40:55 +00003125 const char* register_space = nullptr;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003126
dan sinclair4595fb72022-12-08 14:14:10 +00003127 if (unwrapped_type->Is<type::Texture>()) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00003128 register_space = "t";
dan sinclair4595fb72022-12-08 14:14:10 +00003129 if (unwrapped_type->Is<type::StorageTexture>()) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00003130 register_space = "u";
3131 }
dan sinclair5ee58b62022-12-08 15:25:18 +00003132 } else if (unwrapped_type->Is<type::Sampler>()) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00003133 register_space = "s";
3134 }
3135
3136 if (register_space) {
dan sinclairacdf6e12022-08-24 15:47:25 +00003137 auto bp = sem->As<sem::GlobalVariable>()->BindingPoint();
Ben Clayton5f4847c2023-04-19 13:24:27 +00003138 out << " : register(" << register_space << bp->binding;
Peng Huangc00ff7f2023-03-31 17:55:19 +00003139 // Omit the space if it's 0, as it's the default.
3140 // SM 5.0 doesn't support spaces, so we don't emit them if group is 0 for better
3141 // compatibility.
Ben Clayton5f4847c2023-04-19 13:24:27 +00003142 if (bp->group == 0) {
Peng Huangc00ff7f2023-03-31 17:55:19 +00003143 out << ")";
3144 } else {
Ben Clayton5f4847c2023-04-19 13:24:27 +00003145 out << ", space" << bp->group << ")";
Peng Huangc00ff7f2023-03-31 17:55:19 +00003146 }
dan sinclair41e4d9a2022-05-01 14:40:55 +00003147 }
3148
3149 out << ";";
3150 return true;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003151}
3152
3153bool GeneratorImpl::EmitPrivateVariable(const sem::Variable* var) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00003154 auto* decl = var->Declaration();
3155 auto out = line();
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003156
dan sinclair41e4d9a2022-05-01 14:40:55 +00003157 out << "static ";
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003158
dan sinclaird026e132023-04-18 19:38:25 +00003159 auto name = decl->name->symbol.Name();
dan sinclair41e4d9a2022-05-01 14:40:55 +00003160 auto* type = var->Type()->UnwrapRef();
dan sinclairff7cf212022-10-03 14:05:23 +00003161 if (!EmitTypeAndName(out, type, var->AddressSpace(), var->Access(), name)) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00003162 return false;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003163 }
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003164
dan sinclair41e4d9a2022-05-01 14:40:55 +00003165 out << " = ";
dan sinclair6e77b472022-10-20 13:38:28 +00003166 if (auto* initializer = decl->initializer) {
3167 if (!EmitExpression(out, initializer)) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00003168 return false;
3169 }
3170 } else {
3171 if (!EmitZeroValue(out, var->Type()->UnwrapRef())) {
3172 return false;
3173 }
3174 }
3175
3176 out << ";";
3177 return true;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003178}
3179
3180bool GeneratorImpl::EmitWorkgroupVariable(const sem::Variable* var) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00003181 auto* decl = var->Declaration();
3182 auto out = line();
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003183
dan sinclair41e4d9a2022-05-01 14:40:55 +00003184 out << "groupshared ";
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003185
dan sinclaird026e132023-04-18 19:38:25 +00003186 auto name = decl->name->symbol.Name();
dan sinclair41e4d9a2022-05-01 14:40:55 +00003187 auto* type = var->Type()->UnwrapRef();
dan sinclairff7cf212022-10-03 14:05:23 +00003188 if (!EmitTypeAndName(out, type, var->AddressSpace(), var->Access(), name)) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00003189 return false;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003190 }
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003191
dan sinclair6e77b472022-10-20 13:38:28 +00003192 if (auto* initializer = decl->initializer) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00003193 out << " = ";
dan sinclair6e77b472022-10-20 13:38:28 +00003194 if (!EmitExpression(out, initializer)) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00003195 return false;
3196 }
3197 }
3198
3199 out << ";";
3200 return true;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003201}
3202
dan sinclair63925792023-02-17 21:56:35 +00003203std::string GeneratorImpl::builtin_to_attribute(builtin::BuiltinValue builtin) const {
dan sinclair41e4d9a2022-05-01 14:40:55 +00003204 switch (builtin) {
dan sinclair63925792023-02-17 21:56:35 +00003205 case builtin::BuiltinValue::kPosition:
dan sinclair41e4d9a2022-05-01 14:40:55 +00003206 return "SV_Position";
dan sinclair63925792023-02-17 21:56:35 +00003207 case builtin::BuiltinValue::kVertexIndex:
dan sinclair41e4d9a2022-05-01 14:40:55 +00003208 return "SV_VertexID";
dan sinclair63925792023-02-17 21:56:35 +00003209 case builtin::BuiltinValue::kInstanceIndex:
dan sinclair41e4d9a2022-05-01 14:40:55 +00003210 return "SV_InstanceID";
dan sinclair63925792023-02-17 21:56:35 +00003211 case builtin::BuiltinValue::kFrontFacing:
dan sinclair41e4d9a2022-05-01 14:40:55 +00003212 return "SV_IsFrontFace";
dan sinclair63925792023-02-17 21:56:35 +00003213 case builtin::BuiltinValue::kFragDepth:
dan sinclair41e4d9a2022-05-01 14:40:55 +00003214 return "SV_Depth";
dan sinclair63925792023-02-17 21:56:35 +00003215 case builtin::BuiltinValue::kLocalInvocationId:
dan sinclair41e4d9a2022-05-01 14:40:55 +00003216 return "SV_GroupThreadID";
dan sinclair63925792023-02-17 21:56:35 +00003217 case builtin::BuiltinValue::kLocalInvocationIndex:
dan sinclair41e4d9a2022-05-01 14:40:55 +00003218 return "SV_GroupIndex";
dan sinclair63925792023-02-17 21:56:35 +00003219 case builtin::BuiltinValue::kGlobalInvocationId:
dan sinclair41e4d9a2022-05-01 14:40:55 +00003220 return "SV_DispatchThreadID";
dan sinclair63925792023-02-17 21:56:35 +00003221 case builtin::BuiltinValue::kWorkgroupId:
dan sinclair41e4d9a2022-05-01 14:40:55 +00003222 return "SV_GroupID";
dan sinclair63925792023-02-17 21:56:35 +00003223 case builtin::BuiltinValue::kSampleIndex:
dan sinclair41e4d9a2022-05-01 14:40:55 +00003224 return "SV_SampleIndex";
dan sinclair63925792023-02-17 21:56:35 +00003225 case builtin::BuiltinValue::kSampleMask:
dan sinclair41e4d9a2022-05-01 14:40:55 +00003226 return "SV_Coverage";
3227 default:
3228 break;
3229 }
3230 return "";
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003231}
3232
dan sinclair993a6582023-02-20 08:37:45 +00003233std::string GeneratorImpl::interpolation_to_modifiers(
3234 builtin::InterpolationType type,
3235 builtin::InterpolationSampling sampling) const {
dan sinclair41e4d9a2022-05-01 14:40:55 +00003236 std::string modifiers;
3237 switch (type) {
dan sinclair993a6582023-02-20 08:37:45 +00003238 case builtin::InterpolationType::kPerspective:
dan sinclair41e4d9a2022-05-01 14:40:55 +00003239 modifiers += "linear ";
3240 break;
dan sinclair993a6582023-02-20 08:37:45 +00003241 case builtin::InterpolationType::kLinear:
dan sinclair41e4d9a2022-05-01 14:40:55 +00003242 modifiers += "noperspective ";
3243 break;
dan sinclair993a6582023-02-20 08:37:45 +00003244 case builtin::InterpolationType::kFlat:
dan sinclair41e4d9a2022-05-01 14:40:55 +00003245 modifiers += "nointerpolation ";
3246 break;
dan sinclair993a6582023-02-20 08:37:45 +00003247 case builtin::InterpolationType::kUndefined:
Ben Claytonf9ed9d32022-10-11 19:49:17 +00003248 break;
dan sinclair41e4d9a2022-05-01 14:40:55 +00003249 }
3250 switch (sampling) {
dan sinclair993a6582023-02-20 08:37:45 +00003251 case builtin::InterpolationSampling::kCentroid:
dan sinclair41e4d9a2022-05-01 14:40:55 +00003252 modifiers += "centroid ";
3253 break;
dan sinclair993a6582023-02-20 08:37:45 +00003254 case builtin::InterpolationSampling::kSample:
dan sinclair41e4d9a2022-05-01 14:40:55 +00003255 modifiers += "sample ";
3256 break;
dan sinclair993a6582023-02-20 08:37:45 +00003257 case builtin::InterpolationSampling::kCenter:
3258 case builtin::InterpolationSampling::kUndefined:
dan sinclair41e4d9a2022-05-01 14:40:55 +00003259 break;
3260 }
3261 return modifiers;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003262}
3263
3264bool GeneratorImpl::EmitEntryPointFunction(const ast::Function* func) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00003265 auto* func_sem = builder_.Sem().Get(func);
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003266
dan sinclair41e4d9a2022-05-01 14:40:55 +00003267 {
3268 auto out = line();
3269 if (func->PipelineStage() == ast::PipelineStage::kCompute) {
3270 // Emit the workgroup_size attribute.
3271 auto wgsize = func_sem->WorkgroupSize();
3272 out << "[numthreads(";
dan sinclair3a2a2792022-06-29 14:38:15 +00003273 for (size_t i = 0; i < 3; i++) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00003274 if (i > 0) {
3275 out << ", ";
3276 }
Ben Clayton490d9882022-09-21 21:05:45 +00003277 if (!wgsize[i].has_value()) {
3278 diagnostics_.add_error(
3279 diag::System::Writer,
Ben Claytonf10a5792022-10-13 13:47:39 +00003280 "override-expressions should have been removed with the SubstituteOverride "
Ben Clayton490d9882022-09-21 21:05:45 +00003281 "transform");
3282 return false;
dan sinclair41e4d9a2022-05-01 14:40:55 +00003283 }
Ben Clayton490d9882022-09-21 21:05:45 +00003284 out << std::to_string(wgsize[i].value());
dan sinclair41e4d9a2022-05-01 14:40:55 +00003285 }
3286 out << ")]" << std::endl;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003287 }
3288
dan sinclair2a651632023-02-19 04:03:55 +00003289 if (!EmitTypeAndName(out, func_sem->ReturnType(), builtin::AddressSpace::kUndefined,
dan sinclaird026e132023-04-18 19:38:25 +00003290 builtin::Access::kUndefined, func->name->symbol.Name())) {
Ben Clayton19068572023-02-07 21:28:09 +00003291 return false;
3292 }
3293 out << "(";
dan sinclair41e4d9a2022-05-01 14:40:55 +00003294
3295 bool first = true;
3296
3297 // Emit entry point parameters.
3298 for (auto* var : func->params) {
3299 auto* sem = builder_.Sem().Get(var);
3300 auto* type = sem->Type();
Ben Claytonbc9e4222023-04-27 18:31:44 +00003301 if (TINT_UNLIKELY(!type->Is<type::Struct>())) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00003302 // ICE likely indicates that the CanonicalizeEntryPointIO transform was
3303 // not run, or a builtin parameter was added after it was run.
3304 TINT_ICE(Writer, diagnostics_) << "Unsupported non-struct entry point parameter";
3305 }
3306
3307 if (!first) {
3308 out << ", ";
3309 }
3310 first = false;
3311
dan sinclairff7cf212022-10-03 14:05:23 +00003312 if (!EmitTypeAndName(out, type, sem->AddressSpace(), sem->Access(),
dan sinclaird026e132023-04-18 19:38:25 +00003313 var->name->symbol.Name())) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00003314 return false;
3315 }
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003316 }
dan sinclair41e4d9a2022-05-01 14:40:55 +00003317
3318 out << ") {";
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003319 }
3320
dan sinclair41e4d9a2022-05-01 14:40:55 +00003321 {
3322 ScopedIndent si(this);
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003323
dan sinclair41e4d9a2022-05-01 14:40:55 +00003324 if (!EmitStatements(func->body->statements)) {
3325 return false;
3326 }
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003327
dan sinclair41e4d9a2022-05-01 14:40:55 +00003328 if (!Is<ast::ReturnStatement>(func->body->Last())) {
Ben Clayton4a92a3c2022-07-18 20:50:02 +00003329 ast::ReturnStatement ret(ProgramID(), ast::NodeID{}, Source{});
dan sinclair41e4d9a2022-05-01 14:40:55 +00003330 if (!EmitStatement(&ret)) {
3331 return false;
3332 }
3333 }
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003334 }
3335
dan sinclair41e4d9a2022-05-01 14:40:55 +00003336 line() << "}";
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003337
dan sinclair41e4d9a2022-05-01 14:40:55 +00003338 return true;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003339}
3340
dan sinclair2b9d5b32023-02-28 14:49:25 +00003341bool GeneratorImpl::EmitConstant(utils::StringStream& out,
dan sinclairb53b8cf2022-12-15 16:25:31 +00003342 const constant::Value* constant,
Ben Clayton329dfd72022-11-23 00:05:05 +00003343 bool is_variable_initializer) {
Ben Clayton50414802022-06-24 08:06:19 +00003344 return Switch(
Ben Claytonaa037ac2022-06-29 19:07:30 +00003345 constant->Type(), //
dan sinclaird37ecf92022-12-08 16:39:59 +00003346 [&](const type::Bool*) {
dan sinclair5addefb2022-12-14 20:46:32 +00003347 out << (constant->ValueAs<AInt>() ? "true" : "false");
Ben Claytone9f8b092022-06-01 13:14:39 +00003348 return true;
Ben Clayton50414802022-06-24 08:06:19 +00003349 },
dan sinclaird37ecf92022-12-08 16:39:59 +00003350 [&](const type::F32*) {
dan sinclair5addefb2022-12-14 20:46:32 +00003351 PrintF32(out, constant->ValueAs<f32>());
Ben Clayton50414802022-06-24 08:06:19 +00003352 return true;
3353 },
dan sinclaird37ecf92022-12-08 16:39:59 +00003354 [&](const type::F16*) {
Zhaoming Jianga5988a32022-07-11 15:43:38 +00003355 // emit a f16 scalar with explicit float16_t type declaration.
3356 out << "float16_t(";
dan sinclair5addefb2022-12-14 20:46:32 +00003357 PrintF16(out, constant->ValueAs<f16>());
Zhaoming Jianga5988a32022-07-11 15:43:38 +00003358 out << ")";
Antonio Maiorano679cf4f2022-09-03 21:43:01 +00003359 return true;
Zhaoming Jianga5988a32022-07-11 15:43:38 +00003360 },
dan sinclaird37ecf92022-12-08 16:39:59 +00003361 [&](const type::I32*) {
dan sinclair5addefb2022-12-14 20:46:32 +00003362 out << constant->ValueAs<AInt>();
Ben Clayton50414802022-06-24 08:06:19 +00003363 return true;
3364 },
dan sinclaird37ecf92022-12-08 16:39:59 +00003365 [&](const type::U32*) {
dan sinclair5addefb2022-12-14 20:46:32 +00003366 out << constant->ValueAs<AInt>() << "u";
Ben Clayton50414802022-06-24 08:06:19 +00003367 return true;
3368 },
dan sinclair0e780da2022-12-08 22:21:24 +00003369 [&](const type::Vector* v) {
James Price7bca4d72023-03-13 19:05:16 +00003370 if (auto* splat = constant->As<constant::Splat>()) {
Ben Clayton50414802022-06-24 08:06:19 +00003371 {
dan sinclairb2ba57b2023-02-28 15:14:09 +00003372 ScopedParen sp(out);
James Price7bca4d72023-03-13 19:05:16 +00003373 if (!EmitConstant(out, splat->el, is_variable_initializer)) {
Ben Clayton50414802022-06-24 08:06:19 +00003374 return false;
3375 }
3376 }
3377 out << ".";
Ben Claytonaa037ac2022-06-29 19:07:30 +00003378 for (size_t i = 0; i < v->Width(); i++) {
Ben Clayton50414802022-06-24 08:06:19 +00003379 out << "x";
3380 }
3381 return true;
3382 }
Ben Claytone9f8b092022-06-01 13:14:39 +00003383
dan sinclair2a651632023-02-19 04:03:55 +00003384 if (!EmitType(out, v, builtin::AddressSpace::kUndefined, builtin::Access::kUndefined,
dan sinclairb6cc4cb2023-02-19 04:01:29 +00003385 "")) {
Ben Clayton50414802022-06-24 08:06:19 +00003386 return false;
3387 }
Ben Claytone9f8b092022-06-01 13:14:39 +00003388
dan sinclairb2ba57b2023-02-28 15:14:09 +00003389 ScopedParen sp(out);
Ben Claytone9f8b092022-06-01 13:14:39 +00003390
Ben Claytonaa037ac2022-06-29 19:07:30 +00003391 for (size_t i = 0; i < v->Width(); i++) {
3392 if (i > 0) {
Ben Claytone9f8b092022-06-01 13:14:39 +00003393 out << ", ";
3394 }
Ben Clayton329dfd72022-11-23 00:05:05 +00003395 if (!EmitConstant(out, constant->Index(i), is_variable_initializer)) {
Ben Claytone9f8b092022-06-01 13:14:39 +00003396 return false;
3397 }
3398 }
3399 return true;
Ben Clayton50414802022-06-24 08:06:19 +00003400 },
dan sinclair0e780da2022-12-08 22:21:24 +00003401 [&](const type::Matrix* m) {
dan sinclair2a651632023-02-19 04:03:55 +00003402 if (!EmitType(out, m, builtin::AddressSpace::kUndefined, builtin::Access::kUndefined,
dan sinclairb6cc4cb2023-02-19 04:01:29 +00003403 "")) {
Ben Claytone9f8b092022-06-01 13:14:39 +00003404 return false;
3405 }
Ben Clayton50414802022-06-24 08:06:19 +00003406
dan sinclairb2ba57b2023-02-28 15:14:09 +00003407 ScopedParen sp(out);
Ben Clayton50414802022-06-24 08:06:19 +00003408
Ben Claytonaa037ac2022-06-29 19:07:30 +00003409 for (size_t i = 0; i < m->columns(); i++) {
3410 if (i > 0) {
Ben Clayton50414802022-06-24 08:06:19 +00003411 out << ", ";
3412 }
Ben Clayton329dfd72022-11-23 00:05:05 +00003413 if (!EmitConstant(out, constant->Index(i), is_variable_initializer)) {
Ben Clayton50414802022-06-24 08:06:19 +00003414 return false;
3415 }
3416 }
3417 return true;
3418 },
dan sinclair946858a2022-12-08 22:21:24 +00003419 [&](const type::Array* a) {
Ben Claytonaa037ac2022-06-29 19:07:30 +00003420 if (constant->AllZero()) {
Ben Clayton19576e92022-06-28 12:44:16 +00003421 out << "(";
dan sinclair2a651632023-02-19 04:03:55 +00003422 if (!EmitType(out, a, builtin::AddressSpace::kUndefined,
3423 builtin::Access::kUndefined, "")) {
Ben Clayton19576e92022-06-28 12:44:16 +00003424 return false;
3425 }
3426 out << ")0";
3427 return true;
3428 }
3429
3430 out << "{";
3431 TINT_DEFER(out << "}");
3432
dan sinclair78f80672022-09-22 22:28:21 +00003433 auto count = a->ConstantCount();
3434 if (!count) {
dan sinclair946858a2022-12-08 22:21:24 +00003435 diagnostics_.add_error(diag::System::Writer,
3436 type::Array::kErrExpectedConstantCount);
dan sinclair78f80672022-09-22 22:28:21 +00003437 return false;
3438 }
3439
3440 for (size_t i = 0; i < count; i++) {
Ben Claytonaa037ac2022-06-29 19:07:30 +00003441 if (i > 0) {
Ben Clayton19576e92022-06-28 12:44:16 +00003442 out << ", ";
3443 }
Ben Clayton329dfd72022-11-23 00:05:05 +00003444 if (!EmitConstant(out, constant->Index(i), is_variable_initializer)) {
Ben Clayton19576e92022-06-28 12:44:16 +00003445 return false;
3446 }
3447 }
3448
3449 return true;
3450 },
Ben Claytonbc9e4222023-04-27 18:31:44 +00003451 [&](const type::Struct* s) {
Ben Clayton329dfd72022-11-23 00:05:05 +00003452 if (!EmitStructType(&helpers_, s)) {
3453 return false;
3454 }
3455
Ben Clayton6c098ba2022-07-14 20:46:39 +00003456 if (constant->AllZero()) {
Ben Clayton329dfd72022-11-23 00:05:05 +00003457 out << "(" << StructName(s) << ")0";
Ben Clayton6c098ba2022-07-14 20:46:39 +00003458 return true;
3459 }
3460
dan sinclair2b9d5b32023-02-28 14:49:25 +00003461 auto emit_member_values = [&](utils::StringStream& o) {
Ben Clayton329dfd72022-11-23 00:05:05 +00003462 o << "{";
dan sinclairad9cd0a2022-12-06 20:01:54 +00003463 for (size_t i = 0; i < s->Members().Length(); i++) {
Ben Clayton329dfd72022-11-23 00:05:05 +00003464 if (i > 0) {
3465 o << ", ";
3466 }
3467 if (!EmitConstant(o, constant->Index(i), is_variable_initializer)) {
3468 return false;
3469 }
Ben Clayton6c098ba2022-07-14 20:46:39 +00003470 }
Ben Clayton329dfd72022-11-23 00:05:05 +00003471 o << "}";
3472 return true;
3473 };
3474
3475 if (is_variable_initializer) {
3476 if (!emit_member_values(out)) {
Ben Clayton6c098ba2022-07-14 20:46:39 +00003477 return false;
3478 }
Ben Clayton329dfd72022-11-23 00:05:05 +00003479 } else {
3480 // HLSL requires structure initializers to be assigned directly to a variable.
3481 auto name = UniqueIdentifier("c");
3482 {
3483 auto decl = line();
3484 decl << "const " << StructName(s) << " " << name << " = ";
3485 if (!emit_member_values(decl)) {
3486 return false;
3487 }
3488 decl << ";";
3489 }
3490 out << name;
Ben Clayton6c098ba2022-07-14 20:46:39 +00003491 }
3492
3493 return true;
3494 },
Ben Claytone9f8b092022-06-01 13:14:39 +00003495 [&](Default) {
Ben Clayton1545ca12023-05-03 16:26:40 +00003496 diagnostics_.add_error(diag::System::Writer,
3497 "unhandled constant type: " + constant->Type()->FriendlyName());
Ben Claytone9f8b092022-06-01 13:14:39 +00003498 return false;
3499 });
3500}
3501
dan sinclair2b9d5b32023-02-28 14:49:25 +00003502bool GeneratorImpl::EmitLiteral(utils::StringStream& out, const ast::LiteralExpression* lit) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00003503 return Switch(
3504 lit,
3505 [&](const ast::BoolLiteralExpression* l) {
3506 out << (l->value ? "true" : "false");
3507 return true;
3508 },
Ben Clayton3ad927c2022-05-25 23:12:14 +00003509 [&](const ast::FloatLiteralExpression* l) {
Zhaoming Jianga5988a32022-07-11 15:43:38 +00003510 if (l->suffix == ast::FloatLiteralExpression::Suffix::kH) {
3511 // Emit f16 literal with explicit float16_t type declaration.
3512 out << "float16_t(";
Antonio Maiorano679cf4f2022-09-03 21:43:01 +00003513 PrintF16(out, static_cast<float>(l->value));
Zhaoming Jianga5988a32022-07-11 15:43:38 +00003514 out << ")";
Zhaoming Jianga5988a32022-07-11 15:43:38 +00003515 }
Ben Claytone9f8b092022-06-01 13:14:39 +00003516 PrintF32(out, static_cast<float>(l->value));
dan sinclair41e4d9a2022-05-01 14:40:55 +00003517 return true;
3518 },
Ben Clayton8822e292022-05-04 22:18:49 +00003519 [&](const ast::IntLiteralExpression* i) {
3520 out << i->value;
3521 switch (i->suffix) {
3522 case ast::IntLiteralExpression::Suffix::kNone:
3523 case ast::IntLiteralExpression::Suffix::kI:
3524 return true;
3525 case ast::IntLiteralExpression::Suffix::kU:
3526 out << "u";
3527 return true;
3528 }
3529 diagnostics_.add_error(diag::System::Writer, "unknown integer literal suffix type");
3530 return false;
dan sinclair41e4d9a2022-05-01 14:40:55 +00003531 },
3532 [&](Default) {
3533 diagnostics_.add_error(diag::System::Writer, "unknown literal type");
3534 return false;
3535 });
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003536}
3537
dan sinclair2b9d5b32023-02-28 14:49:25 +00003538bool GeneratorImpl::EmitValue(utils::StringStream& out, const type::Type* type, int value) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00003539 return Switch(
3540 type,
dan sinclaird37ecf92022-12-08 16:39:59 +00003541 [&](const type::Bool*) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00003542 out << (value == 0 ? "false" : "true");
3543 return true;
3544 },
dan sinclaird37ecf92022-12-08 16:39:59 +00003545 [&](const type::F32*) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00003546 out << value << ".0f";
3547 return true;
3548 },
dan sinclaird37ecf92022-12-08 16:39:59 +00003549 [&](const type::F16*) {
Zhaoming Jianga5988a32022-07-11 15:43:38 +00003550 out << "float16_t(" << value << ".0h)";
3551 return true;
3552 },
dan sinclaird37ecf92022-12-08 16:39:59 +00003553 [&](const type::I32*) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00003554 out << value;
3555 return true;
3556 },
dan sinclaird37ecf92022-12-08 16:39:59 +00003557 [&](const type::U32*) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00003558 out << value << "u";
3559 return true;
3560 },
dan sinclair0e780da2022-12-08 22:21:24 +00003561 [&](const type::Vector* vec) {
dan sinclair2a651632023-02-19 04:03:55 +00003562 if (!EmitType(out, type, builtin::AddressSpace::kUndefined, builtin::Access::kReadWrite,
Ben Clayton1b90f932023-02-18 12:37:34 +00003563 "")) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00003564 return false;
3565 }
dan sinclairb2ba57b2023-02-28 15:14:09 +00003566 ScopedParen sp(out);
dan sinclair41e4d9a2022-05-01 14:40:55 +00003567 for (uint32_t i = 0; i < vec->Width(); i++) {
3568 if (i != 0) {
3569 out << ", ";
3570 }
3571 if (!EmitValue(out, vec->type(), value)) {
3572 return false;
3573 }
3574 }
3575 return true;
3576 },
dan sinclair0e780da2022-12-08 22:21:24 +00003577 [&](const type::Matrix* mat) {
dan sinclair2a651632023-02-19 04:03:55 +00003578 if (!EmitType(out, type, builtin::AddressSpace::kUndefined, builtin::Access::kReadWrite,
Ben Clayton1b90f932023-02-18 12:37:34 +00003579 "")) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00003580 return false;
3581 }
dan sinclairb2ba57b2023-02-28 15:14:09 +00003582 ScopedParen sp(out);
dan sinclair41e4d9a2022-05-01 14:40:55 +00003583 for (uint32_t i = 0; i < (mat->rows() * mat->columns()); i++) {
3584 if (i != 0) {
3585 out << ", ";
3586 }
3587 if (!EmitValue(out, mat->type(), value)) {
3588 return false;
3589 }
3590 }
3591 return true;
3592 },
Ben Claytonbc9e4222023-04-27 18:31:44 +00003593 [&](const type::Struct*) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00003594 out << "(";
3595 TINT_DEFER(out << ")" << value);
dan sinclair2a651632023-02-19 04:03:55 +00003596 return EmitType(out, type, builtin::AddressSpace::kUndefined,
3597 builtin::Access::kUndefined, "");
dan sinclair41e4d9a2022-05-01 14:40:55 +00003598 },
dan sinclair946858a2022-12-08 22:21:24 +00003599 [&](const type::Array*) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00003600 out << "(";
3601 TINT_DEFER(out << ")" << value);
dan sinclair2a651632023-02-19 04:03:55 +00003602 return EmitType(out, type, builtin::AddressSpace::kUndefined,
3603 builtin::Access::kUndefined, "");
dan sinclair41e4d9a2022-05-01 14:40:55 +00003604 },
3605 [&](Default) {
dan sinclaird026e132023-04-18 19:38:25 +00003606 diagnostics_.add_error(diag::System::Writer,
3607 "Invalid type for value emission: " + type->FriendlyName());
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003608 return false;
dan sinclair41e4d9a2022-05-01 14:40:55 +00003609 });
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003610}
3611
dan sinclair2b9d5b32023-02-28 14:49:25 +00003612bool GeneratorImpl::EmitZeroValue(utils::StringStream& out, const type::Type* type) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00003613 return EmitValue(out, type, 0);
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003614}
3615
3616bool GeneratorImpl::EmitLoop(const ast::LoopStatement* stmt) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00003617 auto emit_continuing = [this, stmt]() {
3618 if (stmt->continuing && !stmt->continuing->Empty()) {
3619 if (!EmitBlock(stmt->continuing)) {
3620 return false;
3621 }
3622 }
3623 return true;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003624 };
3625
3626 TINT_SCOPED_ASSIGNMENT(emit_continuing_, emit_continuing);
Antonio Maiorano06844a52022-09-29 16:53:58 +00003627 line() << "while (true) {";
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003628 {
dan sinclair41e4d9a2022-05-01 14:40:55 +00003629 ScopedIndent si(this);
3630 if (!EmitStatements(stmt->body->statements)) {
3631 return false;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003632 }
dan sinclair41e4d9a2022-05-01 14:40:55 +00003633 if (!emit_continuing_()) {
3634 return false;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003635 }
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003636 }
3637 line() << "}";
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003638
dan sinclair41e4d9a2022-05-01 14:40:55 +00003639 return true;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003640}
3641
dan sinclair41e4d9a2022-05-01 14:40:55 +00003642bool GeneratorImpl::EmitForLoop(const ast::ForLoopStatement* stmt) {
3643 // Nest a for loop with a new block. In HLSL the initializer scope is not
3644 // nested by the for-loop, so we may get variable redefinitions.
3645 line() << "{";
3646 increment_indent();
3647 TINT_DEFER({
3648 decrement_indent();
3649 line() << "}";
3650 });
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003651
dan sinclair41e4d9a2022-05-01 14:40:55 +00003652 TextBuffer init_buf;
3653 if (auto* init = stmt->initializer) {
3654 TINT_SCOPED_ASSIGNMENT(current_buffer_, &init_buf);
3655 if (!EmitStatement(init)) {
3656 return false;
3657 }
3658 }
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003659
dan sinclair41e4d9a2022-05-01 14:40:55 +00003660 TextBuffer cond_pre;
dan sinclair2b9d5b32023-02-28 14:49:25 +00003661 utils::StringStream cond_buf;
dan sinclair41e4d9a2022-05-01 14:40:55 +00003662 if (auto* cond = stmt->condition) {
3663 TINT_SCOPED_ASSIGNMENT(current_buffer_, &cond_pre);
3664 if (!EmitExpression(cond_buf, cond)) {
3665 return false;
3666 }
3667 }
3668
3669 TextBuffer cont_buf;
3670 if (auto* cont = stmt->continuing) {
3671 TINT_SCOPED_ASSIGNMENT(current_buffer_, &cont_buf);
3672 if (!EmitStatement(cont)) {
3673 return false;
3674 }
3675 }
3676
3677 // If the for-loop has a multi-statement conditional and / or continuing, then
3678 // we cannot emit this as a regular for-loop in HLSL. Instead we need to
3679 // generate a `while(true)` loop.
3680 bool emit_as_loop = cond_pre.lines.size() > 0 || cont_buf.lines.size() > 1;
3681
3682 // If the for-loop has multi-statement initializer, or is going to be emitted
3683 // as a `while(true)` loop, then declare the initializer statement(s) before
3684 // the loop.
3685 if (init_buf.lines.size() > 1 || (stmt->initializer && emit_as_loop)) {
3686 current_buffer_->Append(init_buf);
3687 init_buf.lines.clear(); // Don't emit the initializer again in the 'for'
3688 }
3689
3690 if (emit_as_loop) {
3691 auto emit_continuing = [&]() {
3692 current_buffer_->Append(cont_buf);
3693 return true;
3694 };
3695
3696 TINT_SCOPED_ASSIGNMENT(emit_continuing_, emit_continuing);
Antonio Maiorano06844a52022-09-29 16:53:58 +00003697 line() << "while (true) {";
dan sinclair41e4d9a2022-05-01 14:40:55 +00003698 increment_indent();
3699 TINT_DEFER({
3700 decrement_indent();
3701 line() << "}";
3702 });
3703
3704 if (stmt->condition) {
3705 current_buffer_->Append(cond_pre);
3706 line() << "if (!(" << cond_buf.str() << ")) { break; }";
3707 }
3708
3709 if (!EmitStatements(stmt->body->statements)) {
3710 return false;
3711 }
3712
3713 if (!emit_continuing_()) {
3714 return false;
3715 }
3716 } else {
3717 // For-loop can be generated.
3718 {
3719 auto out = line();
Antonio Maiorano06844a52022-09-29 16:53:58 +00003720 out << "for";
dan sinclair41e4d9a2022-05-01 14:40:55 +00003721 {
3722 ScopedParen sp(out);
3723
3724 if (!init_buf.lines.empty()) {
3725 out << init_buf.lines[0].content << " ";
3726 } else {
3727 out << "; ";
3728 }
3729
3730 out << cond_buf.str() << "; ";
3731
3732 if (!cont_buf.lines.empty()) {
Ben Clayton3731ce82023-05-09 17:34:08 +00003733 out << utils::TrimSuffix(cont_buf.lines[0].content, ";");
dan sinclair41e4d9a2022-05-01 14:40:55 +00003734 }
3735 }
3736 out << " {";
3737 }
3738 {
3739 auto emit_continuing = [] { return true; };
3740 TINT_SCOPED_ASSIGNMENT(emit_continuing_, emit_continuing);
3741 if (!EmitStatementsWithIndent(stmt->body->statements)) {
3742 return false;
3743 }
3744 }
3745 line() << "}";
3746 }
3747
3748 return true;
3749}
3750
dan sinclair49d1a2d2022-06-16 12:01:27 +00003751bool GeneratorImpl::EmitWhile(const ast::WhileStatement* stmt) {
3752 TextBuffer cond_pre;
dan sinclair2b9d5b32023-02-28 14:49:25 +00003753 utils::StringStream cond_buf;
dan sinclair49d1a2d2022-06-16 12:01:27 +00003754 {
3755 auto* cond = stmt->condition;
3756 TINT_SCOPED_ASSIGNMENT(current_buffer_, &cond_pre);
3757 if (!EmitExpression(cond_buf, cond)) {
3758 return false;
3759 }
3760 }
3761
dan sinclair4b88dbc2022-06-16 15:27:38 +00003762 auto emit_continuing = [&]() { return true; };
3763 TINT_SCOPED_ASSIGNMENT(emit_continuing_, emit_continuing);
3764
dan sinclair49d1a2d2022-06-16 12:01:27 +00003765 // If the while has a multi-statement conditional, then we cannot emit this
3766 // as a regular while in HLSL. Instead we need to generate a `while(true)` loop.
3767 bool emit_as_loop = cond_pre.lines.size() > 0;
3768 if (emit_as_loop) {
Antonio Maiorano06844a52022-09-29 16:53:58 +00003769 line() << "while (true) {";
dan sinclair49d1a2d2022-06-16 12:01:27 +00003770 increment_indent();
3771 TINT_DEFER({
3772 decrement_indent();
3773 line() << "}";
3774 });
3775
3776 current_buffer_->Append(cond_pre);
3777 line() << "if (!(" << cond_buf.str() << ")) { break; }";
3778 if (!EmitStatements(stmt->body->statements)) {
3779 return false;
3780 }
3781 } else {
3782 // While can be generated.
3783 {
3784 auto out = line();
Antonio Maiorano06844a52022-09-29 16:53:58 +00003785 out << "while";
dan sinclair49d1a2d2022-06-16 12:01:27 +00003786 {
3787 ScopedParen sp(out);
3788 out << cond_buf.str();
3789 }
3790 out << " {";
3791 }
3792 if (!EmitStatementsWithIndent(stmt->body->statements)) {
3793 return false;
3794 }
3795 line() << "}";
3796 }
3797
3798 return true;
3799}
3800
dan sinclair2b9d5b32023-02-28 14:49:25 +00003801bool GeneratorImpl::EmitMemberAccessor(utils::StringStream& out,
dan sinclair41e4d9a2022-05-01 14:40:55 +00003802 const ast::MemberAccessorExpression* expr) {
Ben Claytonad315652023-02-05 12:36:50 +00003803 if (!EmitExpression(out, expr->object)) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00003804 return false;
3805 }
3806 out << ".";
3807
Ben Clayton2f9a9882022-12-17 02:20:04 +00003808 auto* sem = builder_.Sem().Get(expr)->UnwrapLoad();
dan sinclair41e4d9a2022-05-01 14:40:55 +00003809
Ben Clayton10fae7a2022-11-14 15:29:29 +00003810 return Switch(
3811 sem,
3812 [&](const sem::Swizzle*) {
3813 // Swizzles output the name directly
dan sinclaird026e132023-04-18 19:38:25 +00003814 out << expr->member->symbol.Name();
Ben Clayton10fae7a2022-11-14 15:29:29 +00003815 return true;
3816 },
3817 [&](const sem::StructMemberAccess* member_access) {
dan sinclaird026e132023-04-18 19:38:25 +00003818 out << member_access->Member()->Name().Name();
Ben Clayton10fae7a2022-11-14 15:29:29 +00003819 return true;
3820 },
3821 [&](Default) {
3822 TINT_ICE(Writer, diagnostics_)
3823 << "unknown member access type: " << sem->TypeInfo().name;
3824 return false;
3825 });
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003826}
3827
3828bool GeneratorImpl::EmitReturn(const ast::ReturnStatement* stmt) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00003829 if (stmt->value) {
3830 auto out = line();
3831 out << "return ";
3832 if (!EmitExpression(out, stmt->value)) {
3833 return false;
3834 }
3835 out << ";";
3836 } else {
3837 line() << "return;";
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003838 }
dan sinclair41e4d9a2022-05-01 14:40:55 +00003839 return true;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003840}
3841
3842bool GeneratorImpl::EmitStatement(const ast::Statement* stmt) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00003843 return Switch(
3844 stmt,
3845 [&](const ast::AssignmentStatement* a) { //
3846 return EmitAssign(a);
3847 },
3848 [&](const ast::BlockStatement* b) { //
3849 return EmitBlock(b);
3850 },
3851 [&](const ast::BreakStatement* b) { //
3852 return EmitBreak(b);
3853 },
dan sinclairb8b0c212022-10-20 22:45:50 +00003854 [&](const ast::BreakIfStatement* b) { //
3855 return EmitBreakIf(b);
3856 },
dan sinclair41e4d9a2022-05-01 14:40:55 +00003857 [&](const ast::CallStatement* c) { //
3858 auto out = line();
3859 if (!EmitCall(out, c->expr)) {
3860 return false;
3861 }
3862 out << ";";
3863 return true;
3864 },
3865 [&](const ast::ContinueStatement* c) { //
3866 return EmitContinue(c);
3867 },
3868 [&](const ast::DiscardStatement* d) { //
3869 return EmitDiscard(d);
3870 },
dan sinclair41e4d9a2022-05-01 14:40:55 +00003871 [&](const ast::IfStatement* i) { //
3872 return EmitIf(i);
3873 },
3874 [&](const ast::LoopStatement* l) { //
3875 return EmitLoop(l);
3876 },
3877 [&](const ast::ForLoopStatement* l) { //
3878 return EmitForLoop(l);
3879 },
dan sinclair49d1a2d2022-06-16 12:01:27 +00003880 [&](const ast::WhileStatement* l) { //
3881 return EmitWhile(l);
3882 },
dan sinclair41e4d9a2022-05-01 14:40:55 +00003883 [&](const ast::ReturnStatement* r) { //
3884 return EmitReturn(r);
3885 },
3886 [&](const ast::SwitchStatement* s) { //
3887 return EmitSwitch(s);
3888 },
3889 [&](const ast::VariableDeclStatement* v) { //
Ben Claytondcdf66e2022-06-17 12:48:51 +00003890 return Switch(
3891 v->variable, //
3892 [&](const ast::Var* var) { return EmitVar(var); },
3893 [&](const ast::Let* let) { return EmitLet(let); },
Ben Clayton19576e92022-06-28 12:44:16 +00003894 [&](const ast::Const*) {
3895 return true; // Constants are embedded at their use
3896 },
Ben Claytondcdf66e2022-06-17 12:48:51 +00003897 [&](Default) { //
3898 TINT_ICE(Writer, diagnostics_)
3899 << "unknown variable type: " << v->variable->TypeInfo().name;
3900 return false;
3901 });
dan sinclair41e4d9a2022-05-01 14:40:55 +00003902 },
Ben Claytonc98d57d2023-01-24 14:59:43 +00003903 [&](const ast::ConstAssert*) {
Ben Claytonb4744ac2022-08-03 07:01:08 +00003904 return true; // Not emitted
3905 },
dan sinclair41e4d9a2022-05-01 14:40:55 +00003906 [&](Default) { //
3907 diagnostics_.add_error(diag::System::Writer,
3908 "unknown statement type: " + std::string(stmt->TypeInfo().name));
3909 return false;
3910 });
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003911}
3912
3913bool GeneratorImpl::EmitDefaultOnlySwitch(const ast::SwitchStatement* stmt) {
dan sinclairf148f082022-10-19 15:55:02 +00003914 TINT_ASSERT(Writer, stmt->body.Length() == 1 && stmt->body[0]->ContainsDefault());
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003915
dan sinclair41e4d9a2022-05-01 14:40:55 +00003916 // FXC fails to compile a switch with just a default case, ignoring the
3917 // default case body. We work around this here by emitting the default case
3918 // without the switch.
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003919
Antonio Maioranoeab1f622023-02-01 15:46:34 +00003920 // Emit the switch condition as-is if it has side-effects (e.g.
3921 // function call). Note that we can ignore the result of the expression (if any).
Ben Clayton0b4a2f12023-02-05 22:59:40 +00003922 if (auto* sem_cond = builder_.Sem().GetVal(stmt->condition); sem_cond->HasSideEffects()) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00003923 auto out = line();
3924 if (!EmitExpression(out, stmt->condition)) {
3925 return false;
3926 }
3927 out << ";";
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003928 }
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003929
dan sinclair41e4d9a2022-05-01 14:40:55 +00003930 // Emit "do { <default case body> } while(false);". We use a 'do' loop so
3931 // that break statements work as expected, and make it 'while (false)' in
3932 // case there isn't a break statement.
3933 line() << "do {";
3934 {
3935 ScopedIndent si(this);
3936 if (!EmitStatements(stmt->body[0]->body->statements)) {
3937 return false;
3938 }
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003939 }
dan sinclair41e4d9a2022-05-01 14:40:55 +00003940 line() << "} while (false);";
3941 return true;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003942}
3943
3944bool GeneratorImpl::EmitSwitch(const ast::SwitchStatement* stmt) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00003945 // BUG(crbug.com/tint/1188): work around default-only switches
dan sinclairf148f082022-10-19 15:55:02 +00003946 if (stmt->body.Length() == 1 && stmt->body[0]->selectors.Length() == 1 &&
3947 stmt->body[0]->ContainsDefault()) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00003948 return EmitDefaultOnlySwitch(stmt);
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003949 }
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003950
dan sinclair41e4d9a2022-05-01 14:40:55 +00003951 { // switch(expr) {
3952 auto out = line();
3953 out << "switch(";
3954 if (!EmitExpression(out, stmt->condition)) {
3955 return false;
3956 }
3957 out << ") {";
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003958 }
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003959
dan sinclair41e4d9a2022-05-01 14:40:55 +00003960 {
3961 ScopedIndent si(this);
Ben Clayton783b1692022-08-02 17:03:35 +00003962 for (size_t i = 0; i < stmt->body.Length(); i++) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00003963 if (!EmitCase(stmt, i)) {
3964 return false;
3965 }
3966 }
3967 }
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003968
dan sinclair41e4d9a2022-05-01 14:40:55 +00003969 line() << "}";
3970
3971 return true;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003972}
3973
dan sinclair2b9d5b32023-02-28 14:49:25 +00003974bool GeneratorImpl::EmitType(utils::StringStream& out,
dan sinclair5f764d82022-12-08 00:32:27 +00003975 const type::Type* type,
dan sinclair2a651632023-02-19 04:03:55 +00003976 builtin::AddressSpace address_space,
dan sinclairb6cc4cb2023-02-19 04:01:29 +00003977 builtin::Access access,
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003978 const std::string& name,
3979 bool* name_printed /* = nullptr */) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00003980 if (name_printed) {
3981 *name_printed = false;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003982 }
dan sinclairff7cf212022-10-03 14:05:23 +00003983 switch (address_space) {
dan sinclair2a651632023-02-19 04:03:55 +00003984 case builtin::AddressSpace::kStorage:
dan sinclairb6cc4cb2023-02-19 04:01:29 +00003985 if (access != builtin::Access::kRead) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00003986 out << "RW";
3987 }
3988 out << "ByteAddressBuffer";
3989 return true;
dan sinclair2a651632023-02-19 04:03:55 +00003990 case builtin::AddressSpace::kUniform: {
dan sinclair41e4d9a2022-05-01 14:40:55 +00003991 auto array_length = (type->Size() + 15) / 16;
3992 out << "uint4 " << name << "[" << array_length << "]";
3993 if (name_printed) {
3994 *name_printed = true;
3995 }
3996 return true;
3997 }
3998 default:
3999 break;
4000 }
Ryan Harrisondbc13af2022-02-21 15:19:07 +00004001
dan sinclair41e4d9a2022-05-01 14:40:55 +00004002 return Switch(
4003 type,
dan sinclair946858a2022-12-08 22:21:24 +00004004 [&](const type::Array* ary) {
dan sinclair5f764d82022-12-08 00:32:27 +00004005 const type::Type* base_type = ary;
dan sinclair41e4d9a2022-05-01 14:40:55 +00004006 std::vector<uint32_t> sizes;
dan sinclair946858a2022-12-08 22:21:24 +00004007 while (auto* arr = base_type->As<type::Array>()) {
Ben Clayton884f9522023-01-12 22:52:57 +00004008 if (TINT_UNLIKELY(arr->Count()->Is<type::RuntimeArrayCount>())) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00004009 TINT_ICE(Writer, diagnostics_)
dan sinclair78f80672022-09-22 22:28:21 +00004010 << "runtime arrays may only exist in storage buffers, which should have "
Ben Clayton3a68ab42022-06-24 08:30:28 +00004011 "been transformed into a ByteAddressBuffer";
dan sinclair41e4d9a2022-05-01 14:40:55 +00004012 return false;
4013 }
dan sinclair78f80672022-09-22 22:28:21 +00004014 const auto count = arr->ConstantCount();
4015 if (!count) {
4016 diagnostics_.add_error(diag::System::Writer,
dan sinclair946858a2022-12-08 22:21:24 +00004017 type::Array::kErrExpectedConstantCount);
dan sinclair78f80672022-09-22 22:28:21 +00004018 return false;
4019 }
4020
4021 sizes.push_back(count.value());
dan sinclair41e4d9a2022-05-01 14:40:55 +00004022 base_type = arr->ElemType();
4023 }
dan sinclairff7cf212022-10-03 14:05:23 +00004024 if (!EmitType(out, base_type, address_space, access, "")) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00004025 return false;
4026 }
4027 if (!name.empty()) {
4028 out << " " << name;
4029 if (name_printed) {
4030 *name_printed = true;
4031 }
4032 }
4033 for (uint32_t size : sizes) {
4034 out << "[" << size << "]";
4035 }
4036 return true;
4037 },
dan sinclaird37ecf92022-12-08 16:39:59 +00004038 [&](const type::Bool*) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00004039 out << "bool";
4040 return true;
4041 },
dan sinclaird37ecf92022-12-08 16:39:59 +00004042 [&](const type::F32*) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00004043 out << "float";
4044 return true;
4045 },
dan sinclaird37ecf92022-12-08 16:39:59 +00004046 [&](const type::F16*) {
Zhaoming Jianga5988a32022-07-11 15:43:38 +00004047 out << "float16_t";
4048 return true;
Zhaoming Jiang62bfd312022-05-13 12:01:11 +00004049 },
dan sinclaird37ecf92022-12-08 16:39:59 +00004050 [&](const type::I32*) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00004051 out << "int";
4052 return true;
4053 },
dan sinclair0e780da2022-12-08 22:21:24 +00004054 [&](const type::Matrix* mat) {
dan sinclaird37ecf92022-12-08 16:39:59 +00004055 if (mat->type()->Is<type::F16>()) {
Zhaoming Jianga5988a32022-07-11 15:43:38 +00004056 // Use matrix<type, N, M> for f16 matrix
4057 out << "matrix<";
dan sinclairff7cf212022-10-03 14:05:23 +00004058 if (!EmitType(out, mat->type(), address_space, access, "")) {
Zhaoming Jianga5988a32022-07-11 15:43:38 +00004059 return false;
4060 }
4061 out << ", " << mat->columns() << ", " << mat->rows() << ">";
4062 return true;
4063 }
dan sinclairff7cf212022-10-03 14:05:23 +00004064 if (!EmitType(out, mat->type(), address_space, access, "")) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00004065 return false;
4066 }
4067 // Note: HLSL's matrices are declared as <type>NxM, where N is the
4068 // number of rows and M is the number of columns. Despite HLSL's
4069 // matrices being column-major by default, the index operator and
dan sinclair6e77b472022-10-20 13:38:28 +00004070 // initializers actually operate on row-vectors, where as WGSL operates
dan sinclair41e4d9a2022-05-01 14:40:55 +00004071 // on column vectors. To simplify everything we use the transpose of the
4072 // matrices. See:
4073 // https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-per-component-math#matrix-ordering
4074 out << mat->columns() << "x" << mat->rows();
4075 return true;
4076 },
dan sinclair4d56b482022-12-08 17:50:50 +00004077 [&](const type::Pointer*) {
Ben Clayton559e5a22023-04-17 14:24:58 +00004078 TINT_ICE(Writer, diagnostics_) << "Attempting to emit pointer type. These should have "
4079 "been removed with the SimplifyPointers transform";
Ryan Harrisondbc13af2022-02-21 15:19:07 +00004080 return false;
dan sinclair41e4d9a2022-05-01 14:40:55 +00004081 },
dan sinclair5ee58b62022-12-08 15:25:18 +00004082 [&](const type::Sampler* sampler) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00004083 out << "Sampler";
4084 if (sampler->IsComparison()) {
4085 out << "Comparison";
4086 }
4087 out << "State";
4088 return true;
4089 },
Ben Claytonbc9e4222023-04-27 18:31:44 +00004090 [&](const type::Struct* str) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00004091 out << StructName(str);
4092 return true;
4093 },
dan sinclair4595fb72022-12-08 14:14:10 +00004094 [&](const type::Texture* tex) {
Ben Clayton884f9522023-01-12 22:52:57 +00004095 if (TINT_UNLIKELY(tex->Is<type::ExternalTexture>())) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00004096 TINT_ICE(Writer, diagnostics_)
4097 << "Multiplanar external texture transform was not run.";
4098 return false;
4099 }
Brandon Jones6661b282022-02-25 20:14:52 +00004100
dan sinclair4595fb72022-12-08 14:14:10 +00004101 auto* storage = tex->As<type::StorageTexture>();
4102 auto* ms = tex->As<type::MultisampledTexture>();
4103 auto* depth_ms = tex->As<type::DepthMultisampledTexture>();
4104 auto* sampled = tex->As<type::SampledTexture>();
Ryan Harrisondbc13af2022-02-21 15:19:07 +00004105
dan sinclairb6cc4cb2023-02-19 04:01:29 +00004106 if (storage && storage->access() != builtin::Access::kRead) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00004107 out << "RW";
4108 }
4109 out << "Texture";
Ryan Harrisondbc13af2022-02-21 15:19:07 +00004110
dan sinclair41e4d9a2022-05-01 14:40:55 +00004111 switch (tex->dim()) {
dan sinclair3cbf3fc2023-01-21 19:16:15 +00004112 case type::TextureDimension::k1d:
dan sinclair41e4d9a2022-05-01 14:40:55 +00004113 out << "1D";
4114 break;
dan sinclair3cbf3fc2023-01-21 19:16:15 +00004115 case type::TextureDimension::k2d:
dan sinclair41e4d9a2022-05-01 14:40:55 +00004116 out << ((ms || depth_ms) ? "2DMS" : "2D");
4117 break;
dan sinclair3cbf3fc2023-01-21 19:16:15 +00004118 case type::TextureDimension::k2dArray:
dan sinclair41e4d9a2022-05-01 14:40:55 +00004119 out << ((ms || depth_ms) ? "2DMSArray" : "2DArray");
4120 break;
dan sinclair3cbf3fc2023-01-21 19:16:15 +00004121 case type::TextureDimension::k3d:
dan sinclair41e4d9a2022-05-01 14:40:55 +00004122 out << "3D";
4123 break;
dan sinclair3cbf3fc2023-01-21 19:16:15 +00004124 case type::TextureDimension::kCube:
dan sinclair41e4d9a2022-05-01 14:40:55 +00004125 out << "Cube";
4126 break;
dan sinclair3cbf3fc2023-01-21 19:16:15 +00004127 case type::TextureDimension::kCubeArray:
dan sinclair41e4d9a2022-05-01 14:40:55 +00004128 out << "CubeArray";
4129 break;
4130 default:
4131 TINT_UNREACHABLE(Writer, diagnostics_)
4132 << "unexpected TextureDimension " << tex->dim();
4133 return false;
4134 }
Ryan Harrisondbc13af2022-02-21 15:19:07 +00004135
dan sinclair41e4d9a2022-05-01 14:40:55 +00004136 if (storage) {
4137 auto* component = image_format_to_rwtexture_type(storage->texel_format());
Ben Clayton884f9522023-01-12 22:52:57 +00004138 if (TINT_UNLIKELY(!component)) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00004139 TINT_ICE(Writer, diagnostics_) << "Unsupported StorageTexture TexelFormat: "
4140 << static_cast<int>(storage->texel_format());
4141 return false;
4142 }
4143 out << "<" << component << ">";
4144 } else if (depth_ms) {
4145 out << "<float4>";
4146 } else if (sampled || ms) {
4147 auto* subtype = sampled ? sampled->type() : ms->type();
4148 out << "<";
dan sinclaird37ecf92022-12-08 16:39:59 +00004149 if (subtype->Is<type::F32>()) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00004150 out << "float4";
dan sinclaird37ecf92022-12-08 16:39:59 +00004151 } else if (subtype->Is<type::I32>()) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00004152 out << "int4";
Ben Clayton884f9522023-01-12 22:52:57 +00004153 } else if (TINT_LIKELY(subtype->Is<type::U32>())) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00004154 out << "uint4";
4155 } else {
4156 TINT_ICE(Writer, diagnostics_) << "Unsupported multisampled texture type";
4157 return false;
4158 }
4159 out << ">";
4160 }
4161 return true;
4162 },
dan sinclaird37ecf92022-12-08 16:39:59 +00004163 [&](const type::U32*) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00004164 out << "uint";
4165 return true;
4166 },
dan sinclair0e780da2022-12-08 22:21:24 +00004167 [&](const type::Vector* vec) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00004168 auto width = vec->Width();
dan sinclaird37ecf92022-12-08 16:39:59 +00004169 if (vec->type()->Is<type::F32>() && width >= 1 && width <= 4) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00004170 out << "float" << width;
dan sinclaird37ecf92022-12-08 16:39:59 +00004171 } else if (vec->type()->Is<type::I32>() && width >= 1 && width <= 4) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00004172 out << "int" << width;
dan sinclaird37ecf92022-12-08 16:39:59 +00004173 } else if (vec->type()->Is<type::U32>() && width >= 1 && width <= 4) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00004174 out << "uint" << width;
dan sinclaird37ecf92022-12-08 16:39:59 +00004175 } else if (vec->type()->Is<type::Bool>() && width >= 1 && width <= 4) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00004176 out << "bool" << width;
4177 } else {
Zhaoming Jianga5988a32022-07-11 15:43:38 +00004178 // For example, use "vector<float16_t, N>" for f16 vector.
dan sinclair41e4d9a2022-05-01 14:40:55 +00004179 out << "vector<";
dan sinclairff7cf212022-10-03 14:05:23 +00004180 if (!EmitType(out, vec->type(), address_space, access, "")) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00004181 return false;
4182 }
4183 out << ", " << width << ">";
4184 }
4185 return true;
4186 },
dan sinclaird8a08452022-12-08 22:21:24 +00004187 [&](const type::Atomic* atomic) {
dan sinclairff7cf212022-10-03 14:05:23 +00004188 return EmitType(out, atomic->Type(), address_space, access, name);
dan sinclair41e4d9a2022-05-01 14:40:55 +00004189 },
dan sinclaird37ecf92022-12-08 16:39:59 +00004190 [&](const type::Void*) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00004191 out << "void";
4192 return true;
4193 },
4194 [&](Default) {
4195 diagnostics_.add_error(diag::System::Writer, "unknown type in EmitType");
Ryan Harrisondbc13af2022-02-21 15:19:07 +00004196 return false;
dan sinclair41e4d9a2022-05-01 14:40:55 +00004197 });
Ryan Harrisondbc13af2022-02-21 15:19:07 +00004198}
4199
dan sinclair2b9d5b32023-02-28 14:49:25 +00004200bool GeneratorImpl::EmitTypeAndName(utils::StringStream& out,
dan sinclair5f764d82022-12-08 00:32:27 +00004201 const type::Type* type,
dan sinclair2a651632023-02-19 04:03:55 +00004202 builtin::AddressSpace address_space,
dan sinclairb6cc4cb2023-02-19 04:01:29 +00004203 builtin::Access access,
Ryan Harrisondbc13af2022-02-21 15:19:07 +00004204 const std::string& name) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00004205 bool name_printed = false;
dan sinclairff7cf212022-10-03 14:05:23 +00004206 if (!EmitType(out, type, address_space, access, name, &name_printed)) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00004207 return false;
4208 }
4209 if (!name.empty() && !name_printed) {
4210 out << " " << name;
4211 }
4212 return true;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00004213}
4214
Ben Claytonbc9e4222023-04-27 18:31:44 +00004215bool GeneratorImpl::EmitStructType(TextBuffer* b, const type::Struct* str) {
Ben Clayton329dfd72022-11-23 00:05:05 +00004216 auto it = emitted_structs_.emplace(str);
4217 if (!it.second) {
4218 return true;
4219 }
4220
dan sinclair41e4d9a2022-05-01 14:40:55 +00004221 line(b) << "struct " << StructName(str) << " {";
4222 {
4223 ScopedIndent si(b);
4224 for (auto* mem : str->Members()) {
dan sinclaird026e132023-04-18 19:38:25 +00004225 auto mem_name = mem->Name().Name();
dan sinclair41e4d9a2022-05-01 14:40:55 +00004226 auto* ty = mem->Type();
dan sinclair41e4d9a2022-05-01 14:40:55 +00004227 auto out = line(b);
dan sinclair41e4d9a2022-05-01 14:40:55 +00004228 std::string pre, post;
dan sinclair41e4d9a2022-05-01 14:40:55 +00004229
Ben Clayton576ba1c2023-04-27 17:58:25 +00004230 auto& attributes = mem->Attributes();
Ben Claytonf0b4dbb2023-02-21 21:05:28 +00004231
Ben Clayton576ba1c2023-04-27 17:58:25 +00004232 if (auto location = attributes.location) {
4233 auto& pipeline_stage_uses = str->PipelineStageUses();
4234 if (TINT_UNLIKELY(pipeline_stage_uses.size() != 1)) {
4235 TINT_ICE(Writer, diagnostics_) << "invalid entry point IO struct uses";
dan sinclair41e4d9a2022-05-01 14:40:55 +00004236 }
Ben Clayton576ba1c2023-04-27 17:58:25 +00004237 if (pipeline_stage_uses.count(type::PipelineStageUsage::kVertexInput)) {
4238 post += " : TEXCOORD" + std::to_string(location.value());
4239 } else if (pipeline_stage_uses.count(type::PipelineStageUsage::kVertexOutput)) {
4240 post += " : TEXCOORD" + std::to_string(location.value());
4241 } else if (pipeline_stage_uses.count(type::PipelineStageUsage::kFragmentInput)) {
4242 post += " : TEXCOORD" + std::to_string(location.value());
4243 } else if (TINT_LIKELY(pipeline_stage_uses.count(
4244 type::PipelineStageUsage::kFragmentOutput))) {
4245 post += " : SV_Target" + std::to_string(location.value());
4246 } else {
4247 TINT_ICE(Writer, diagnostics_) << "invalid use of location attribute";
4248 }
4249 }
4250 if (auto builtin = attributes.builtin) {
4251 auto name = builtin_to_attribute(builtin.value());
4252 if (name.empty()) {
4253 diagnostics_.add_error(diag::System::Writer, "unsupported builtin");
4254 return false;
4255 }
4256 post += " : " + name;
4257 }
4258 if (auto interpolation = attributes.interpolation) {
4259 auto mod = interpolation_to_modifiers(interpolation->type, interpolation->sampling);
4260 if (mod.empty()) {
4261 diagnostics_.add_error(diag::System::Writer, "unsupported interpolation");
4262 return false;
4263 }
4264 pre += mod;
4265 }
4266 if (attributes.invariant) {
4267 // Note: `precise` is not exactly the same as `invariant`, but is
4268 // stricter and therefore provides the necessary guarantees.
4269 // See discussion here: https://github.com/gpuweb/gpuweb/issues/893
4270 pre += "precise ";
Ryan Harrisondbc13af2022-02-21 15:19:07 +00004271 }
4272
dan sinclair41e4d9a2022-05-01 14:40:55 +00004273 out << pre;
dan sinclair2a651632023-02-19 04:03:55 +00004274 if (!EmitTypeAndName(out, ty, builtin::AddressSpace::kUndefined,
dan sinclairb6cc4cb2023-02-19 04:01:29 +00004275 builtin::Access::kReadWrite, mem_name)) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00004276 return false;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00004277 }
dan sinclair41e4d9a2022-05-01 14:40:55 +00004278 out << post << ";";
Ryan Harrisondbc13af2022-02-21 15:19:07 +00004279 }
Ryan Harrisondbc13af2022-02-21 15:19:07 +00004280 }
Ryan Harrisondbc13af2022-02-21 15:19:07 +00004281
dan sinclair41e4d9a2022-05-01 14:40:55 +00004282 line(b) << "};";
dan sinclair41e4d9a2022-05-01 14:40:55 +00004283 return true;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00004284}
4285
dan sinclair2b9d5b32023-02-28 14:49:25 +00004286bool GeneratorImpl::EmitUnaryOp(utils::StringStream& out, const ast::UnaryOpExpression* expr) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00004287 switch (expr->op) {
4288 case ast::UnaryOp::kIndirection:
4289 case ast::UnaryOp::kAddressOf:
4290 return EmitExpression(out, expr->expr);
4291 case ast::UnaryOp::kComplement:
4292 out << "~";
4293 break;
4294 case ast::UnaryOp::kNot:
4295 out << "!";
4296 break;
4297 case ast::UnaryOp::kNegation:
4298 out << "-";
4299 break;
4300 }
4301 out << "(";
Ryan Harrisondbc13af2022-02-21 15:19:07 +00004302
dan sinclair41e4d9a2022-05-01 14:40:55 +00004303 if (!EmitExpression(out, expr->expr)) {
4304 return false;
4305 }
Ryan Harrisondbc13af2022-02-21 15:19:07 +00004306
dan sinclair41e4d9a2022-05-01 14:40:55 +00004307 out << ")";
Ryan Harrisondbc13af2022-02-21 15:19:07 +00004308
dan sinclair41e4d9a2022-05-01 14:40:55 +00004309 return true;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00004310}
4311
Ben Claytondcdf66e2022-06-17 12:48:51 +00004312bool GeneratorImpl::EmitVar(const ast::Var* var) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00004313 auto* sem = builder_.Sem().Get(var);
4314 auto* type = sem->Type()->UnwrapRef();
Ryan Harrisondbc13af2022-02-21 15:19:07 +00004315
dan sinclair41e4d9a2022-05-01 14:40:55 +00004316 auto out = line();
dan sinclaird026e132023-04-18 19:38:25 +00004317 if (!EmitTypeAndName(out, type, sem->AddressSpace(), sem->Access(), var->name->symbol.Name())) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00004318 return false;
4319 }
4320
4321 out << " = ";
4322
dan sinclair6e77b472022-10-20 13:38:28 +00004323 if (var->initializer) {
4324 if (!EmitExpression(out, var->initializer)) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00004325 return false;
4326 }
4327 } else {
4328 if (!EmitZeroValue(out, type)) {
4329 return false;
4330 }
4331 }
4332 out << ";";
4333
4334 return true;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00004335}
4336
Ben Claytondcdf66e2022-06-17 12:48:51 +00004337bool GeneratorImpl::EmitLet(const ast::Let* let) {
4338 auto* sem = builder_.Sem().Get(let);
4339 auto* type = sem->Type()->UnwrapRef();
4340
4341 auto out = line();
4342 out << "const ";
dan sinclair2a651632023-02-19 04:03:55 +00004343 if (!EmitTypeAndName(out, type, builtin::AddressSpace::kUndefined, builtin::Access::kUndefined,
dan sinclaird026e132023-04-18 19:38:25 +00004344 let->name->symbol.Name())) {
Ryan Harrisondbc13af2022-02-21 15:19:07 +00004345 return false;
dan sinclair41e4d9a2022-05-01 14:40:55 +00004346 }
Ben Claytondcdf66e2022-06-17 12:48:51 +00004347 out << " = ";
dan sinclair6e77b472022-10-20 13:38:28 +00004348 if (!EmitExpression(out, let->initializer)) {
Ben Claytondcdf66e2022-06-17 12:48:51 +00004349 return false;
4350 }
4351 out << ";";
dan sinclair41e4d9a2022-05-01 14:40:55 +00004352
Ben Claytondcdf66e2022-06-17 12:48:51 +00004353 return true;
4354}
4355
Ryan Harrisondbc13af2022-02-21 15:19:07 +00004356template <typename F>
dan sinclair2b9d5b32023-02-28 14:49:25 +00004357bool GeneratorImpl::CallBuiltinHelper(utils::StringStream& out,
Ryan Harrisondbc13af2022-02-21 15:19:07 +00004358 const ast::CallExpression* call,
4359 const sem::Builtin* builtin,
4360 F&& build) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00004361 // Generate the helper function if it hasn't been created already
4362 auto fn = utils::GetOrCreate(builtins_, builtin, [&]() -> std::string {
4363 TextBuffer b;
4364 TINT_DEFER(helpers_.Append(b));
Ryan Harrisondbc13af2022-02-21 15:19:07 +00004365
dan sinclair9543f742023-03-09 01:20:16 +00004366 auto fn_name = UniqueIdentifier(std::string("tint_") + builtin::str(builtin->Type()));
dan sinclair41e4d9a2022-05-01 14:40:55 +00004367 std::vector<std::string> parameter_names;
4368 {
4369 auto decl = line(&b);
dan sinclair2a651632023-02-19 04:03:55 +00004370 if (!EmitTypeAndName(decl, builtin->ReturnType(), builtin::AddressSpace::kUndefined,
dan sinclairb6cc4cb2023-02-19 04:01:29 +00004371 builtin::Access::kUndefined, fn_name)) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00004372 return "";
4373 }
4374 {
4375 ScopedParen sp(decl);
4376 for (auto* param : builtin->Parameters()) {
4377 if (!parameter_names.empty()) {
4378 decl << ", ";
4379 }
4380 auto param_name = "param_" + std::to_string(parameter_names.size());
4381 const auto* ty = param->Type();
dan sinclair4d56b482022-12-08 17:50:50 +00004382 if (auto* ptr = ty->As<type::Pointer>()) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00004383 decl << "inout ";
4384 ty = ptr->StoreType();
4385 }
dan sinclair2a651632023-02-19 04:03:55 +00004386 if (!EmitTypeAndName(decl, ty, builtin::AddressSpace::kUndefined,
dan sinclairb6cc4cb2023-02-19 04:01:29 +00004387 builtin::Access::kUndefined, param_name)) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00004388 return "";
4389 }
4390 parameter_names.emplace_back(std::move(param_name));
4391 }
4392 }
4393 decl << " {";
Ryan Harrisondbc13af2022-02-21 15:19:07 +00004394 }
dan sinclair41e4d9a2022-05-01 14:40:55 +00004395 {
4396 ScopedIndent si(&b);
4397 if (!build(&b, parameter_names)) {
4398 return "";
4399 }
4400 }
4401 line(&b) << "}";
4402 line(&b);
4403 return fn_name;
4404 });
Ryan Harrisondbc13af2022-02-21 15:19:07 +00004405
dan sinclair41e4d9a2022-05-01 14:40:55 +00004406 if (fn.empty()) {
Ryan Harrisondbc13af2022-02-21 15:19:07 +00004407 return false;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00004408 }
dan sinclair41e4d9a2022-05-01 14:40:55 +00004409
4410 // Call the helper
4411 out << fn;
4412 {
dan sinclairb2ba57b2023-02-28 15:14:09 +00004413 ScopedParen sp(out);
dan sinclair41e4d9a2022-05-01 14:40:55 +00004414 bool first = true;
4415 for (auto* arg : call->args) {
4416 if (!first) {
4417 out << ", ";
4418 }
4419 first = false;
4420 if (!EmitExpression(out, arg)) {
4421 return false;
4422 }
4423 }
4424 }
4425 return true;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00004426}
4427
dan sinclair6a5bef12022-04-07 14:30:24 +00004428} // namespace tint::writer::hlsl