blob: aeae383ac6bde46fb9b29b32c95fbc9e6a128828 [file] [log] [blame]
ethannicholasb3058bd2016-07-01 08:22:01 -07001/*
2 * Copyright 2016 Google Inc.
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
Ethan Nicholasbcf35f82017-03-30 18:42:48 +00007
John Stiles3738ef52021-04-13 10:41:57 -04008#include "src/sksl/codegen/SkSLSPIRVCodeGenerator.h"
Ethan Nicholas9bd301d2017-03-31 16:04:34 +00009
Mike Kleinc0bd9f92019-04-23 12:05:21 -050010#include "src/sksl/GLSL.std.450.h"
ethannicholasb3058bd2016-07-01 08:22:01 -070011
Brian Salomond8d85b92021-07-07 09:41:17 -040012#include "include/sksl/DSLCore.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050013#include "src/sksl/SkSLCompiler.h"
Brian Osman00185012021-02-04 16:07:11 -050014#include "src/sksl/SkSLOperators.h"
Brian Salomond8d85b92021-07-07 09:41:17 -040015#include "src/sksl/dsl/priv/DSLWriter.h"
John Stiles4d6310a2021-01-26 19:58:22 -050016#include "src/sksl/ir/SkSLBlock.h"
John Stilese3ae9682021-08-05 10:35:01 -040017#include "src/sksl/ir/SkSLConstructorArrayCast.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050018#include "src/sksl/ir/SkSLExpressionStatement.h"
19#include "src/sksl/ir/SkSLExtension.h"
Brian Salomond8d85b92021-07-07 09:41:17 -040020#include "src/sksl/ir/SkSLField.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050021#include "src/sksl/ir/SkSLIndexExpression.h"
22#include "src/sksl/ir/SkSLVariableReference.h"
ethannicholasb3058bd2016-07-01 08:22:01 -070023
Ethan Nicholas0be34802019-08-15 12:36:58 -040024#ifdef SK_VULKAN
25#include "src/gpu/vk/GrVkCaps.h"
26#endif
27
John Stilescd806892021-01-06 13:33:31 -050028#define kLast_Capability SpvCapabilityMultiViewport
29
Brian Salomond8d85b92021-07-07 09:41:17 -040030constexpr int DEVICE_FRAGCOORDS_BUILTIN = -1000;
31constexpr int DEVICE_CLOCKWISE_BUILTIN = -1001;
32
ethannicholasb3058bd2016-07-01 08:22:01 -070033namespace SkSL {
34
ethannicholasb3058bd2016-07-01 08:22:01 -070035static const int32_t SKSL_MAGIC = 0x0; // FIXME: we should probably register a magic number
36
37void SPIRVCodeGenerator::setupIntrinsics() {
John Stilesaaac4e42021-05-06 14:08:28 -040038#define ALL_GLSL(x) std::make_tuple(kGLSL_STD_450_IntrinsicOpcodeKind, GLSLstd450 ## x, \
39 GLSLstd450 ## x, GLSLstd450 ## x, GLSLstd450 ## x)
40#define BY_TYPE_GLSL(ifFloat, ifInt, ifUInt) std::make_tuple(kGLSL_STD_450_IntrinsicOpcodeKind, \
41 GLSLstd450 ## ifFloat, \
42 GLSLstd450 ## ifInt, \
43 GLSLstd450 ## ifUInt, \
ethannicholasb3058bd2016-07-01 08:22:01 -070044 SpvOpUndef)
John Stilesaaac4e42021-05-06 14:08:28 -040045#define ALL_SPIRV(x) std::make_tuple(kSPIRV_IntrinsicOpcodeKind, \
46 SpvOp ## x, SpvOp ## x, SpvOp ## x, SpvOp ## x)
47#define SPECIAL(x) std::make_tuple(kSpecial_IntrinsicOpcodeKind, k ## x ## _SpecialIntrinsic, \
48 k ## x ## _SpecialIntrinsic, k ## x ## _SpecialIntrinsic, \
ethannicholasb3058bd2016-07-01 08:22:01 -070049 k ## x ## _SpecialIntrinsic)
John Stilesaaac4e42021-05-06 14:08:28 -040050 fIntrinsicMap[k_round_IntrinsicKind] = ALL_GLSL(Round);
51 fIntrinsicMap[k_roundEven_IntrinsicKind] = ALL_GLSL(RoundEven);
52 fIntrinsicMap[k_trunc_IntrinsicKind] = ALL_GLSL(Trunc);
53 fIntrinsicMap[k_abs_IntrinsicKind] = BY_TYPE_GLSL(FAbs, SAbs, SAbs);
54 fIntrinsicMap[k_sign_IntrinsicKind] = BY_TYPE_GLSL(FSign, SSign, SSign);
55 fIntrinsicMap[k_floor_IntrinsicKind] = ALL_GLSL(Floor);
56 fIntrinsicMap[k_ceil_IntrinsicKind] = ALL_GLSL(Ceil);
57 fIntrinsicMap[k_fract_IntrinsicKind] = ALL_GLSL(Fract);
58 fIntrinsicMap[k_radians_IntrinsicKind] = ALL_GLSL(Radians);
59 fIntrinsicMap[k_degrees_IntrinsicKind] = ALL_GLSL(Degrees);
60 fIntrinsicMap[k_sin_IntrinsicKind] = ALL_GLSL(Sin);
61 fIntrinsicMap[k_cos_IntrinsicKind] = ALL_GLSL(Cos);
62 fIntrinsicMap[k_tan_IntrinsicKind] = ALL_GLSL(Tan);
63 fIntrinsicMap[k_asin_IntrinsicKind] = ALL_GLSL(Asin);
64 fIntrinsicMap[k_acos_IntrinsicKind] = ALL_GLSL(Acos);
65 fIntrinsicMap[k_atan_IntrinsicKind] = SPECIAL(Atan);
66 fIntrinsicMap[k_sinh_IntrinsicKind] = ALL_GLSL(Sinh);
67 fIntrinsicMap[k_cosh_IntrinsicKind] = ALL_GLSL(Cosh);
68 fIntrinsicMap[k_tanh_IntrinsicKind] = ALL_GLSL(Tanh);
69 fIntrinsicMap[k_asinh_IntrinsicKind] = ALL_GLSL(Asinh);
70 fIntrinsicMap[k_acosh_IntrinsicKind] = ALL_GLSL(Acosh);
71 fIntrinsicMap[k_atanh_IntrinsicKind] = ALL_GLSL(Atanh);
72 fIntrinsicMap[k_pow_IntrinsicKind] = ALL_GLSL(Pow);
73 fIntrinsicMap[k_exp_IntrinsicKind] = ALL_GLSL(Exp);
74 fIntrinsicMap[k_log_IntrinsicKind] = ALL_GLSL(Log);
75 fIntrinsicMap[k_exp2_IntrinsicKind] = ALL_GLSL(Exp2);
76 fIntrinsicMap[k_log2_IntrinsicKind] = ALL_GLSL(Log2);
77 fIntrinsicMap[k_sqrt_IntrinsicKind] = ALL_GLSL(Sqrt);
78 fIntrinsicMap[k_inverse_IntrinsicKind] = ALL_GLSL(MatrixInverse);
79 fIntrinsicMap[k_outerProduct_IntrinsicKind] = ALL_SPIRV(OuterProduct);
80 fIntrinsicMap[k_transpose_IntrinsicKind] = ALL_SPIRV(Transpose);
81 fIntrinsicMap[k_isinf_IntrinsicKind] = ALL_SPIRV(IsInf);
82 fIntrinsicMap[k_isnan_IntrinsicKind] = ALL_SPIRV(IsNan);
83 fIntrinsicMap[k_inversesqrt_IntrinsicKind] = ALL_GLSL(InverseSqrt);
84 fIntrinsicMap[k_determinant_IntrinsicKind] = ALL_GLSL(Determinant);
85 fIntrinsicMap[k_matrixCompMult_IntrinsicKind] = SPECIAL(MatrixCompMult);
86 fIntrinsicMap[k_matrixInverse_IntrinsicKind] = ALL_GLSL(MatrixInverse);
87 fIntrinsicMap[k_mod_IntrinsicKind] = SPECIAL(Mod);
88 fIntrinsicMap[k_modf_IntrinsicKind] = ALL_GLSL(Modf);
89 fIntrinsicMap[k_min_IntrinsicKind] = SPECIAL(Min);
90 fIntrinsicMap[k_max_IntrinsicKind] = SPECIAL(Max);
91 fIntrinsicMap[k_clamp_IntrinsicKind] = SPECIAL(Clamp);
92 fIntrinsicMap[k_saturate_IntrinsicKind] = SPECIAL(Saturate);
93 fIntrinsicMap[k_dot_IntrinsicKind] = std::make_tuple(kSPIRV_IntrinsicOpcodeKind,
94 SpvOpDot, SpvOpUndef, SpvOpUndef, SpvOpUndef);
95 fIntrinsicMap[k_mix_IntrinsicKind] = SPECIAL(Mix);
96 fIntrinsicMap[k_step_IntrinsicKind] = SPECIAL(Step);
97 fIntrinsicMap[k_smoothstep_IntrinsicKind] = SPECIAL(SmoothStep);
98 fIntrinsicMap[k_fma_IntrinsicKind] = ALL_GLSL(Fma);
99 fIntrinsicMap[k_frexp_IntrinsicKind] = ALL_GLSL(Frexp);
100 fIntrinsicMap[k_ldexp_IntrinsicKind] = ALL_GLSL(Ldexp);
ethannicholasb3058bd2016-07-01 08:22:01 -0700101
John Stilesaaac4e42021-05-06 14:08:28 -0400102#define PACK(type) fIntrinsicMap[k_pack##type##_IntrinsicKind] = ALL_GLSL(Pack##type); \
103 fIntrinsicMap[k_unpack##type##_IntrinsicKind] = ALL_GLSL(Unpack##type)
ethannicholasb3058bd2016-07-01 08:22:01 -0700104 PACK(Snorm4x8);
105 PACK(Unorm4x8);
106 PACK(Snorm2x16);
107 PACK(Unorm2x16);
108 PACK(Half2x16);
109 PACK(Double2x32);
John Stilesaaac4e42021-05-06 14:08:28 -0400110#undef PACK
111 fIntrinsicMap[k_length_IntrinsicKind] = ALL_GLSL(Length);
112 fIntrinsicMap[k_distance_IntrinsicKind] = ALL_GLSL(Distance);
113 fIntrinsicMap[k_cross_IntrinsicKind] = ALL_GLSL(Cross);
114 fIntrinsicMap[k_normalize_IntrinsicKind] = ALL_GLSL(Normalize);
115 fIntrinsicMap[k_faceforward_IntrinsicKind] = ALL_GLSL(FaceForward);
116 fIntrinsicMap[k_reflect_IntrinsicKind] = ALL_GLSL(Reflect);
117 fIntrinsicMap[k_refract_IntrinsicKind] = ALL_GLSL(Refract);
118 fIntrinsicMap[k_bitCount_IntrinsicKind] = ALL_SPIRV(BitCount);
119 fIntrinsicMap[k_findLSB_IntrinsicKind] = ALL_GLSL(FindILsb);
120 fIntrinsicMap[k_findMSB_IntrinsicKind] = BY_TYPE_GLSL(FindSMsb, FindSMsb, FindUMsb);
121 fIntrinsicMap[k_dFdx_IntrinsicKind] = std::make_tuple(kSPIRV_IntrinsicOpcodeKind,
122 SpvOpDPdx, SpvOpUndef,
123 SpvOpUndef, SpvOpUndef);
124 fIntrinsicMap[k_dFdy_IntrinsicKind] = SPECIAL(DFdy);
125 fIntrinsicMap[k_fwidth_IntrinsicKind] = std::make_tuple(kSPIRV_IntrinsicOpcodeKind,
126 SpvOpFwidth, SpvOpUndef,
127 SpvOpUndef, SpvOpUndef);
128 fIntrinsicMap[k_makeSampler2D_IntrinsicKind] = SPECIAL(SampledImage);
Stephen Whiteff5d7a22019-07-26 17:42:06 -0400129
John Stilesaaac4e42021-05-06 14:08:28 -0400130 fIntrinsicMap[k_sample_IntrinsicKind] = SPECIAL(Texture);
131 fIntrinsicMap[k_subpassLoad_IntrinsicKind] = SPECIAL(SubpassLoad);
Greg Daniel64773e62016-11-22 09:44:03 -0500132
John Stilesaaac4e42021-05-06 14:08:28 -0400133 fIntrinsicMap[k_floatBitsToInt_IntrinsicKind] = ALL_SPIRV(Bitcast);
134 fIntrinsicMap[k_floatBitsToUint_IntrinsicKind] = ALL_SPIRV(Bitcast);
135 fIntrinsicMap[k_intBitsToFloat_IntrinsicKind] = ALL_SPIRV(Bitcast);
136 fIntrinsicMap[k_uintBitsToFloat_IntrinsicKind] = ALL_SPIRV(Bitcast);
John Stilescc9ff002020-12-09 18:39:41 -0500137
John Stilesaaac4e42021-05-06 14:08:28 -0400138 fIntrinsicMap[k_any_IntrinsicKind] = std::make_tuple(kSPIRV_IntrinsicOpcodeKind,
Brian Osman540c13a2020-11-24 16:55:34 -0500139 SpvOpUndef, SpvOpUndef,
John Stilesaaac4e42021-05-06 14:08:28 -0400140 SpvOpUndef, SpvOpAny);
141 fIntrinsicMap[k_all_IntrinsicKind] = std::make_tuple(kSPIRV_IntrinsicOpcodeKind,
142 SpvOpUndef, SpvOpUndef,
143 SpvOpUndef, SpvOpAll);
144 fIntrinsicMap[k_not_IntrinsicKind] = std::make_tuple(kSPIRV_IntrinsicOpcodeKind,
145 SpvOpUndef, SpvOpUndef, SpvOpUndef,
Brian Osman540c13a2020-11-24 16:55:34 -0500146 SpvOpLogicalNot);
John Stilesaaac4e42021-05-06 14:08:28 -0400147 fIntrinsicMap[k_equal_IntrinsicKind] = std::make_tuple(kSPIRV_IntrinsicOpcodeKind,
Ethan Nicholas0187ae62017-05-03 11:03:44 -0400148 SpvOpFOrdEqual, SpvOpIEqual,
149 SpvOpIEqual, SpvOpLogicalEqual);
John Stilesaaac4e42021-05-06 14:08:28 -0400150 fIntrinsicMap[k_notEqual_IntrinsicKind] = std::make_tuple(kSPIRV_IntrinsicOpcodeKind,
Ethan Nicholas0187ae62017-05-03 11:03:44 -0400151 SpvOpFOrdNotEqual, SpvOpINotEqual,
152 SpvOpINotEqual,
153 SpvOpLogicalNotEqual);
John Stilesaaac4e42021-05-06 14:08:28 -0400154 fIntrinsicMap[k_lessThan_IntrinsicKind] = std::make_tuple(kSPIRV_IntrinsicOpcodeKind,
155 SpvOpFOrdLessThan,
156 SpvOpSLessThan,
157 SpvOpULessThan,
158 SpvOpUndef);
159 fIntrinsicMap[k_lessThanEqual_IntrinsicKind] = std::make_tuple(kSPIRV_IntrinsicOpcodeKind,
160 SpvOpFOrdLessThanEqual,
161 SpvOpSLessThanEqual,
162 SpvOpULessThanEqual,
163 SpvOpUndef);
164 fIntrinsicMap[k_greaterThan_IntrinsicKind] = std::make_tuple(kSPIRV_IntrinsicOpcodeKind,
165 SpvOpFOrdGreaterThan,
166 SpvOpSGreaterThan,
167 SpvOpUGreaterThan,
168 SpvOpUndef);
169 fIntrinsicMap[k_greaterThanEqual_IntrinsicKind] = std::make_tuple(kSPIRV_IntrinsicOpcodeKind,
170 SpvOpFOrdGreaterThanEqual,
171 SpvOpSGreaterThanEqual,
172 SpvOpUGreaterThanEqual,
173 SpvOpUndef);
ethannicholasb3058bd2016-07-01 08:22:01 -0700174// interpolateAt* not yet supported...
175}
176
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400177void SPIRVCodeGenerator::writeWord(int32_t word, OutputStream& out) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700178 out.write((const char*) &word, sizeof(word));
ethannicholasb3058bd2016-07-01 08:22:01 -0700179}
180
ethannicholasd598f792016-07-25 10:08:54 -0700181static bool is_float(const Context& context, const Type& type) {
John Stiles4c151702021-02-09 18:31:34 -0500182 return (type.isScalar() || type.isVector() || type.isMatrix()) &&
183 type.componentType().isFloat();
ethannicholasb3058bd2016-07-01 08:22:01 -0700184}
185
ethannicholasd598f792016-07-25 10:08:54 -0700186static bool is_signed(const Context& context, const Type& type) {
Brian Osmanc9145f32021-07-08 13:40:10 -0400187 return (type.isScalar() || type.isVector()) && type.componentType().isSigned();
ethannicholasb3058bd2016-07-01 08:22:01 -0700188}
189
ethannicholasd598f792016-07-25 10:08:54 -0700190static bool is_unsigned(const Context& context, const Type& type) {
John Stiles4c151702021-02-09 18:31:34 -0500191 return (type.isScalar() || type.isVector()) && type.componentType().isUnsigned();
ethannicholasb3058bd2016-07-01 08:22:01 -0700192}
193
ethannicholasd598f792016-07-25 10:08:54 -0700194static bool is_bool(const Context& context, const Type& type) {
John Stiles4c151702021-02-09 18:31:34 -0500195 return (type.isScalar() || type.isVector()) && type.componentType().isBoolean();
ethannicholasb3058bd2016-07-01 08:22:01 -0700196}
197
John Stiles07367122021-09-08 13:12:26 -0400198static bool is_out(const Modifiers& m) {
199 return (m.fFlags & Modifiers::kOut_Flag) != 0;
ethannicholasb3058bd2016-07-01 08:22:01 -0700200}
201
John Stiles07367122021-09-08 13:12:26 -0400202static bool is_in(const Modifiers& m) {
203 switch (m.fFlags & (Modifiers::kOut_Flag | Modifiers::kIn_Flag)) {
John Stiles6a51b202021-09-08 10:45:08 -0400204 case Modifiers::kOut_Flag: // out
205 return false;
206
207 case 0: // implicit in
208 case Modifiers::kIn_Flag: // explicit in
209 case Modifiers::kOut_Flag | Modifiers::kIn_Flag: // inout
210 return true;
211
212 default: SkUNREACHABLE;
213 }
214}
215
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400216void SPIRVCodeGenerator::writeOpCode(SpvOp_ opCode, int length, OutputStream& out) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400217 SkASSERT(opCode != SpvOpLoad || &out != &fConstantBuffer);
218 SkASSERT(opCode != SpvOpUndef);
ethannicholasb3058bd2016-07-01 08:22:01 -0700219 switch (opCode) {
220 case SpvOpReturn: // fall through
221 case SpvOpReturnValue: // fall through
ethannicholas552882f2016-07-07 06:30:48 -0700222 case SpvOpKill: // fall through
Ethan Nicholas7fb39362020-12-16 15:25:19 -0500223 case SpvOpSwitch: // fall through
ethannicholasb3058bd2016-07-01 08:22:01 -0700224 case SpvOpBranch: // fall through
225 case SpvOpBranchConditional:
John Stilesf2b08cc2021-05-17 14:46:05 -0400226 if (fCurrentBlock == 0) {
227 // We just encountered dead code--instructions that don't have an associated block.
228 // Synthesize a label if this happens; this is necessary to satisfy the validator.
229 this->writeLabel(this->nextId(nullptr), out);
230 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700231 fCurrentBlock = 0;
232 break;
233 case SpvOpConstant: // fall through
234 case SpvOpConstantTrue: // fall through
235 case SpvOpConstantFalse: // fall through
236 case SpvOpConstantComposite: // fall through
237 case SpvOpTypeVoid: // fall through
238 case SpvOpTypeInt: // fall through
239 case SpvOpTypeFloat: // fall through
240 case SpvOpTypeBool: // fall through
241 case SpvOpTypeVector: // fall through
242 case SpvOpTypeMatrix: // fall through
243 case SpvOpTypeArray: // fall through
244 case SpvOpTypePointer: // fall through
245 case SpvOpTypeFunction: // fall through
246 case SpvOpTypeRuntimeArray: // fall through
247 case SpvOpTypeStruct: // fall through
248 case SpvOpTypeImage: // fall through
249 case SpvOpTypeSampledImage: // fall through
Stephen Whiteff5d7a22019-07-26 17:42:06 -0400250 case SpvOpTypeSampler: // fall through
ethannicholasb3058bd2016-07-01 08:22:01 -0700251 case SpvOpVariable: // fall through
252 case SpvOpFunction: // fall through
253 case SpvOpFunctionParameter: // fall through
254 case SpvOpFunctionEnd: // fall through
255 case SpvOpExecutionMode: // fall through
256 case SpvOpMemoryModel: // fall through
257 case SpvOpCapability: // fall through
258 case SpvOpExtInstImport: // fall through
259 case SpvOpEntryPoint: // fall through
260 case SpvOpSource: // fall through
261 case SpvOpSourceExtension: // fall through
262 case SpvOpName: // fall through
263 case SpvOpMemberName: // fall through
264 case SpvOpDecorate: // fall through
265 case SpvOpMemberDecorate:
266 break;
267 default:
John Stilesf3a28db2021-03-10 23:00:47 -0500268 // We may find ourselves with dead code--instructions that don't have an associated
269 // block. This should be a rare event, but if it happens, synthesize a label; this is
270 // necessary to satisfy the validator.
271 if (fCurrentBlock == 0) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -0400272 this->writeLabel(this->nextId(nullptr), out);
John Stiles7142e402021-02-23 12:28:18 -0500273 }
John Stiles453f1432021-02-25 16:58:04 -0500274 break;
ethannicholasb3058bd2016-07-01 08:22:01 -0700275 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700276 this->writeWord((length << 16) | opCode, out);
ethannicholasb3058bd2016-07-01 08:22:01 -0700277}
278
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400279void SPIRVCodeGenerator::writeLabel(SpvId label, OutputStream& out) {
Ethan Nicholas7fb39362020-12-16 15:25:19 -0500280 SkASSERT(!fCurrentBlock);
ethannicholasb3058bd2016-07-01 08:22:01 -0700281 fCurrentBlock = label;
282 this->writeInstruction(SpvOpLabel, label, out);
283}
284
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400285void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, OutputStream& out) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700286 this->writeOpCode(opCode, 1, out);
287}
288
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400289void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, int32_t word1, OutputStream& out) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700290 this->writeOpCode(opCode, 2, out);
291 this->writeWord(word1, out);
292}
293
Ethan Nicholas962dec42021-06-10 13:06:39 -0400294void SPIRVCodeGenerator::writeString(skstd::string_view s, OutputStream& out) {
Ethan Nicholasd2e09602021-06-10 11:21:59 -0400295 out.write(s.data(), s.length());
296 switch (s.length() % 4) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700297 case 1:
Ethan Nicholas9e1138d2016-11-21 10:39:35 -0500298 out.write8(0);
John Stiles30212b72020-06-11 17:55:07 -0400299 [[fallthrough]];
ethannicholasb3058bd2016-07-01 08:22:01 -0700300 case 2:
Ethan Nicholas9e1138d2016-11-21 10:39:35 -0500301 out.write8(0);
John Stiles30212b72020-06-11 17:55:07 -0400302 [[fallthrough]];
ethannicholasb3058bd2016-07-01 08:22:01 -0700303 case 3:
Ethan Nicholas9e1138d2016-11-21 10:39:35 -0500304 out.write8(0);
ethannicholasb3058bd2016-07-01 08:22:01 -0700305 break;
306 default:
307 this->writeWord(0, out);
Ethan Nicholasb13f3692021-09-10 16:49:42 -0400308 break;
ethannicholasb3058bd2016-07-01 08:22:01 -0700309 }
310}
311
Ethan Nicholas962dec42021-06-10 13:06:39 -0400312void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, skstd::string_view string,
313 OutputStream& out) {
Ethan Nicholasd2e09602021-06-10 11:21:59 -0400314 this->writeOpCode(opCode, 1 + (string.length() + 4) / 4, out);
315 this->writeString(string, out);
ethannicholasb3058bd2016-07-01 08:22:01 -0700316}
317
318
Ethan Nicholas962dec42021-06-10 13:06:39 -0400319void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, int32_t word1, skstd::string_view string,
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400320 OutputStream& out) {
Ethan Nicholasd2e09602021-06-10 11:21:59 -0400321 this->writeOpCode(opCode, 2 + (string.length() + 4) / 4, out);
ethannicholasb3058bd2016-07-01 08:22:01 -0700322 this->writeWord(word1, out);
Ethan Nicholasd2e09602021-06-10 11:21:59 -0400323 this->writeString(string, out);
ethannicholasb3058bd2016-07-01 08:22:01 -0700324}
325
Greg Daniel64773e62016-11-22 09:44:03 -0500326void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, int32_t word1, int32_t word2,
Ethan Nicholas962dec42021-06-10 13:06:39 -0400327 skstd::string_view string, OutputStream& out) {
Ethan Nicholasd2e09602021-06-10 11:21:59 -0400328 this->writeOpCode(opCode, 3 + (string.length() + 4) / 4, out);
ethannicholasb3058bd2016-07-01 08:22:01 -0700329 this->writeWord(word1, out);
330 this->writeWord(word2, out);
Ethan Nicholasd2e09602021-06-10 11:21:59 -0400331 this->writeString(string, out);
ethannicholasb3058bd2016-07-01 08:22:01 -0700332}
333
Greg Daniel64773e62016-11-22 09:44:03 -0500334void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, int32_t word1, int32_t word2,
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400335 OutputStream& out) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700336 this->writeOpCode(opCode, 3, out);
337 this->writeWord(word1, out);
338 this->writeWord(word2, out);
339}
340
Greg Daniel64773e62016-11-22 09:44:03 -0500341void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, int32_t word1, int32_t word2,
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400342 int32_t word3, OutputStream& out) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700343 this->writeOpCode(opCode, 4, out);
344 this->writeWord(word1, out);
345 this->writeWord(word2, out);
346 this->writeWord(word3, out);
347}
348
Greg Daniel64773e62016-11-22 09:44:03 -0500349void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, int32_t word1, int32_t word2,
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400350 int32_t word3, int32_t word4, OutputStream& out) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700351 this->writeOpCode(opCode, 5, out);
352 this->writeWord(word1, out);
353 this->writeWord(word2, out);
354 this->writeWord(word3, out);
355 this->writeWord(word4, out);
356}
357
Greg Daniel64773e62016-11-22 09:44:03 -0500358void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, int32_t word1, int32_t word2,
359 int32_t word3, int32_t word4, int32_t word5,
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400360 OutputStream& out) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700361 this->writeOpCode(opCode, 6, out);
362 this->writeWord(word1, out);
363 this->writeWord(word2, out);
364 this->writeWord(word3, out);
365 this->writeWord(word4, out);
366 this->writeWord(word5, out);
367}
368
Greg Daniel64773e62016-11-22 09:44:03 -0500369void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, int32_t word1, int32_t word2,
ethannicholasb3058bd2016-07-01 08:22:01 -0700370 int32_t word3, int32_t word4, int32_t word5,
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400371 int32_t word6, OutputStream& out) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700372 this->writeOpCode(opCode, 7, out);
373 this->writeWord(word1, out);
374 this->writeWord(word2, out);
375 this->writeWord(word3, out);
376 this->writeWord(word4, out);
377 this->writeWord(word5, out);
378 this->writeWord(word6, out);
379}
380
Greg Daniel64773e62016-11-22 09:44:03 -0500381void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, int32_t word1, int32_t word2,
ethannicholasb3058bd2016-07-01 08:22:01 -0700382 int32_t word3, int32_t word4, int32_t word5,
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400383 int32_t word6, int32_t word7, OutputStream& out) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700384 this->writeOpCode(opCode, 8, out);
385 this->writeWord(word1, out);
386 this->writeWord(word2, out);
387 this->writeWord(word3, out);
388 this->writeWord(word4, out);
389 this->writeWord(word5, out);
390 this->writeWord(word6, out);
391 this->writeWord(word7, out);
392}
393
Greg Daniel64773e62016-11-22 09:44:03 -0500394void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, int32_t word1, int32_t word2,
ethannicholasb3058bd2016-07-01 08:22:01 -0700395 int32_t word3, int32_t word4, int32_t word5,
396 int32_t word6, int32_t word7, int32_t word8,
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400397 OutputStream& out) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700398 this->writeOpCode(opCode, 9, out);
399 this->writeWord(word1, out);
400 this->writeWord(word2, out);
401 this->writeWord(word3, out);
402 this->writeWord(word4, out);
403 this->writeWord(word5, out);
404 this->writeWord(word6, out);
405 this->writeWord(word7, out);
406 this->writeWord(word8, out);
407}
408
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400409void SPIRVCodeGenerator::writeCapabilities(OutputStream& out) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700410 for (uint64_t i = 0, bit = 1; i <= kLast_Capability; i++, bit <<= 1) {
411 if (fCapabilities & bit) {
412 this->writeInstruction(SpvOpCapability, (SpvId) i, out);
413 }
414 }
Brian Osman99ddd2a2021-08-27 11:21:12 -0400415 this->writeInstruction(SpvOpCapability, SpvCapabilityShader, out);
ethannicholasb3058bd2016-07-01 08:22:01 -0700416}
417
Ethan Nicholas8f352ce2021-03-17 14:12:20 -0400418SpvId SPIRVCodeGenerator::nextId(const Type* type) {
419 return this->nextId(type && type->hasPrecision() && !type->highPrecision()
420 ? Precision::kRelaxed
421 : Precision::kDefault);
422}
423
424SpvId SPIRVCodeGenerator::nextId(Precision precision) {
425 if (precision == Precision::kRelaxed && !fProgram.fConfig->fSettings.fForceHighPrecision) {
426 this->writeInstruction(SpvOpDecorate, fIdCount, SpvDecorationRelaxedPrecision,
427 fDecorationBuffer);
428 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700429 return fIdCount++;
430}
431
Ethan Nicholas19671772016-11-28 16:30:17 -0500432void SPIRVCodeGenerator::writeStruct(const Type& type, const MemoryLayout& memoryLayout,
433 SpvId resultId) {
Ethan Nicholase2c49992020-10-05 11:49:11 -0400434 this->writeInstruction(SpvOpName, resultId, String(type.name()).c_str(), fNameBuffer);
ethannicholasb3058bd2016-07-01 08:22:01 -0700435 // go ahead and write all of the field types, so we don't inadvertently write them while we're
436 // in the middle of writing the struct instruction
437 std::vector<SpvId> types;
438 for (const auto& f : type.fields()) {
Ethan Nicholas19671772016-11-28 16:30:17 -0500439 types.push_back(this->getType(*f.fType, memoryLayout));
ethannicholasb3058bd2016-07-01 08:22:01 -0700440 }
441 this->writeOpCode(SpvOpTypeStruct, 2 + (int32_t) types.size(), fConstantBuffer);
442 this->writeWord(resultId, fConstantBuffer);
443 for (SpvId id : types) {
444 this->writeWord(id, fConstantBuffer);
445 }
446 size_t offset = 0;
447 for (int32_t i = 0; i < (int32_t) type.fields().size(); i++) {
Ethan Nicholascc5d3e02019-04-19 09:50:56 -0400448 const Type::Field& field = type.fields()[i];
John Stiles21f5f452020-11-30 09:57:59 -0500449 if (!MemoryLayout::LayoutIsSupported(*field.fType)) {
Ethan Nicholas89cfde12021-09-27 11:20:34 -0400450 fContext.fErrors->error(type.fLine, "type '" + field.fType->name() +
Ethan Nicholas3abc6c62021-08-13 11:20:09 -0400451 "' is not permitted here");
John Stiles0023c0c2020-11-16 13:32:18 -0500452 return;
453 }
Ethan Nicholascc5d3e02019-04-19 09:50:56 -0400454 size_t size = memoryLayout.size(*field.fType);
455 size_t alignment = memoryLayout.alignment(*field.fType);
456 const Layout& fieldLayout = field.fModifiers.fLayout;
Ethan Nicholas19671772016-11-28 16:30:17 -0500457 if (fieldLayout.fOffset >= 0) {
Greg Danieldbd44c72017-01-24 15:12:12 -0500458 if (fieldLayout.fOffset < (int) offset) {
Ethan Nicholas89cfde12021-09-27 11:20:34 -0400459 fContext.fErrors->error(type.fLine,
Ethan Nicholas3abc6c62021-08-13 11:20:09 -0400460 "offset of field '" + field.fName + "' must be at "
461 "least " + to_string((int) offset));
Ethan Nicholas19671772016-11-28 16:30:17 -0500462 }
463 if (fieldLayout.fOffset % alignment) {
Ethan Nicholas89cfde12021-09-27 11:20:34 -0400464 fContext.fErrors->error(type.fLine,
Ethan Nicholas3abc6c62021-08-13 11:20:09 -0400465 "offset of field '" + field.fName + "' must be a multiple"
466 " of " + to_string((int) alignment));
Ethan Nicholas19671772016-11-28 16:30:17 -0500467 }
468 offset = fieldLayout.fOffset;
469 } else {
470 size_t mod = offset % alignment;
471 if (mod) {
472 offset += alignment - mod;
473 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700474 }
Ethan Nicholascc5d3e02019-04-19 09:50:56 -0400475 this->writeInstruction(SpvOpMemberName, resultId, i, field.fName, fNameBuffer);
Ethan Nicholas19671772016-11-28 16:30:17 -0500476 this->writeLayout(fieldLayout, resultId, i);
Ethan Nicholascc5d3e02019-04-19 09:50:56 -0400477 if (field.fModifiers.fLayout.fBuiltin < 0) {
Greg Daniel64773e62016-11-22 09:44:03 -0500478 this->writeInstruction(SpvOpMemberDecorate, resultId, (SpvId) i, SpvDecorationOffset,
ethannicholasb3058bd2016-07-01 08:22:01 -0700479 (SpvId) offset, fDecorationBuffer);
480 }
John Stiles9aeed132020-11-24 17:36:06 -0500481 if (field.fType->isMatrix()) {
Greg Daniel64773e62016-11-22 09:44:03 -0500482 this->writeInstruction(SpvOpMemberDecorate, resultId, i, SpvDecorationColMajor,
ethannicholasb3058bd2016-07-01 08:22:01 -0700483 fDecorationBuffer);
Greg Daniel64773e62016-11-22 09:44:03 -0500484 this->writeInstruction(SpvOpMemberDecorate, resultId, i, SpvDecorationMatrixStride,
Ethan Nicholascc5d3e02019-04-19 09:50:56 -0400485 (SpvId) memoryLayout.stride(*field.fType),
ethannicholas8ac838d2016-11-22 08:39:36 -0800486 fDecorationBuffer);
ethannicholasb3058bd2016-07-01 08:22:01 -0700487 }
Ethan Nicholascc5d3e02019-04-19 09:50:56 -0400488 if (!field.fType->highPrecision()) {
489 this->writeInstruction(SpvOpMemberDecorate, resultId, (SpvId) i,
490 SpvDecorationRelaxedPrecision, fDecorationBuffer);
491 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700492 offset += size;
John Stilesc0c51062020-12-03 17:16:29 -0500493 if ((field.fType->isArray() || field.fType->isStruct()) && offset % alignment != 0) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700494 offset += alignment - offset % alignment;
495 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700496 }
497}
498
Ethan Nicholase2c49992020-10-05 11:49:11 -0400499const Type& SPIRVCodeGenerator::getActualType(const Type& type) {
Ethan Nicholase1f55022019-02-05 17:17:40 -0500500 if (type.isFloat()) {
John Stiles54e7c052021-01-11 14:22:36 -0500501 return *fContext.fTypes.fFloat;
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400502 }
Brian Osmanc9145f32021-07-08 13:40:10 -0400503 if (type.isSigned()) {
John Stiles54e7c052021-01-11 14:22:36 -0500504 return *fContext.fTypes.fInt;
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400505 }
Ethan Nicholase1f55022019-02-05 17:17:40 -0500506 if (type.isUnsigned()) {
John Stiles54e7c052021-01-11 14:22:36 -0500507 return *fContext.fTypes.fUInt;
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400508 }
John Stiles9aeed132020-11-24 17:36:06 -0500509 if (type.isMatrix() || type.isVector()) {
John Stiles54e7c052021-01-11 14:22:36 -0500510 if (type.componentType() == *fContext.fTypes.fHalf) {
511 return fContext.fTypes.fFloat->toCompound(fContext, type.columns(), type.rows());
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400512 }
Ethan Nicholas722c83e2021-05-04 11:39:30 -0400513 if (type.componentType() == *fContext.fTypes.fShort) {
John Stiles54e7c052021-01-11 14:22:36 -0500514 return fContext.fTypes.fInt->toCompound(fContext, type.columns(), type.rows());
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400515 }
Ethan Nicholas722c83e2021-05-04 11:39:30 -0400516 if (type.componentType() == *fContext.fTypes.fUShort) {
John Stiles54e7c052021-01-11 14:22:36 -0500517 return fContext.fTypes.fUInt->toCompound(fContext, type.columns(), type.rows());
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400518 }
519 }
520 return type;
521}
522
ethannicholasb3058bd2016-07-01 08:22:01 -0700523SpvId SPIRVCodeGenerator::getType(const Type& type) {
ethannicholas8ac838d2016-11-22 08:39:36 -0800524 return this->getType(type, fDefaultLayout);
525}
526
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400527SpvId SPIRVCodeGenerator::getType(const Type& rawType, const MemoryLayout& layout) {
John Stiles3c991fd2021-08-09 14:19:58 -0400528 const Type* type;
529 std::unique_ptr<Type> arrayType;
530 String arrayName;
531
532 if (rawType.isArray()) {
533 // For arrays, we need to synthesize a temporary Array type using the "actual" component
534 // type. That is, if `short[10]` is passed in, we need to synthesize a `int[10]` Type.
535 // Otherwise, we can end up with two different SpvIds for the same array type.
536 const Type& component = this->getActualType(rawType.componentType());
537 arrayName = component.getArrayName(rawType.columns());
538 arrayType = Type::MakeArrayType(arrayName, component, rawType.columns());
539 type = arrayType.get();
540 } else {
541 // For non-array types, we can simply look up the "actual" type and use it.
542 type = &this->getActualType(rawType);
543 }
544
545 String key(type->name());
546 if (type->isStruct() || type->isArray()) {
Jim Van Verthf3ec9832020-10-21 16:09:57 -0400547 key += to_string((int)layout.fStd);
Brian Osman2a4c0fb2021-01-22 13:41:40 -0500548#ifdef SK_DEBUG
549 SkASSERT(layout.fStd == MemoryLayout::Standard::k140_Standard ||
550 layout.fStd == MemoryLayout::Standard::k430_Standard);
551 MemoryLayout::Standard otherStd = layout.fStd == MemoryLayout::Standard::k140_Standard
552 ? MemoryLayout::Standard::k430_Standard
553 : MemoryLayout::Standard::k140_Standard;
John Stiles3c991fd2021-08-09 14:19:58 -0400554 String otherKey = type->name() + to_string((int)otherStd);
Brian Osman2a4c0fb2021-01-22 13:41:40 -0500555 SkASSERT(fTypeMap.find(otherKey) == fTypeMap.end());
556#endif
Jim Van Verthf3ec9832020-10-21 16:09:57 -0400557 }
ethannicholas8ac838d2016-11-22 08:39:36 -0800558 auto entry = fTypeMap.find(key);
ethannicholasb3058bd2016-07-01 08:22:01 -0700559 if (entry == fTypeMap.end()) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -0400560 SpvId result = this->nextId(nullptr);
John Stiles3c991fd2021-08-09 14:19:58 -0400561 switch (type->typeKind()) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400562 case Type::TypeKind::kScalar:
John Stiles3c991fd2021-08-09 14:19:58 -0400563 if (type->isBoolean()) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700564 this->writeInstruction(SpvOpTypeBool, result, fConstantBuffer);
John Stiles3c991fd2021-08-09 14:19:58 -0400565 } else if (type->isSigned()) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700566 this->writeInstruction(SpvOpTypeInt, result, 32, 1, fConstantBuffer);
John Stiles3c991fd2021-08-09 14:19:58 -0400567 } else if (type->isUnsigned()) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700568 this->writeInstruction(SpvOpTypeInt, result, 32, 0, fConstantBuffer);
John Stiles3c991fd2021-08-09 14:19:58 -0400569 } else if (type->isFloat()) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700570 this->writeInstruction(SpvOpTypeFloat, result, 32, fConstantBuffer);
ethannicholasb3058bd2016-07-01 08:22:01 -0700571 } else {
John Stiles3c991fd2021-08-09 14:19:58 -0400572 SkDEBUGFAILF("unrecognized scalar type '%s'", type->description().c_str());
ethannicholasb3058bd2016-07-01 08:22:01 -0700573 }
574 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400575 case Type::TypeKind::kVector:
Greg Daniel64773e62016-11-22 09:44:03 -0500576 this->writeInstruction(SpvOpTypeVector, result,
John Stiles3c991fd2021-08-09 14:19:58 -0400577 this->getType(type->componentType(), layout),
578 type->columns(), fConstantBuffer);
ethannicholasb3058bd2016-07-01 08:22:01 -0700579 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400580 case Type::TypeKind::kMatrix:
John Stiles51d33982021-03-08 09:18:07 -0500581 this->writeInstruction(
582 SpvOpTypeMatrix,
583 result,
John Stiles3c991fd2021-08-09 14:19:58 -0400584 this->getType(IndexExpression::IndexType(fContext, *type), layout),
585 type->columns(),
John Stiles51d33982021-03-08 09:18:07 -0500586 fConstantBuffer);
ethannicholasb3058bd2016-07-01 08:22:01 -0700587 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400588 case Type::TypeKind::kStruct:
John Stiles3c991fd2021-08-09 14:19:58 -0400589 this->writeStruct(*type, layout, result);
ethannicholasb3058bd2016-07-01 08:22:01 -0700590 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400591 case Type::TypeKind::kArray: {
John Stiles3c991fd2021-08-09 14:19:58 -0400592 if (!MemoryLayout::LayoutIsSupported(*type)) {
Ethan Nicholas89cfde12021-09-27 11:20:34 -0400593 fContext.fErrors->error(type->fLine,
Ethan Nicholas3abc6c62021-08-13 11:20:09 -0400594 "type '" + type->name() + "' is not permitted here");
Ethan Nicholas8f352ce2021-03-17 14:12:20 -0400595 return this->nextId(nullptr);
John Stiles21f5f452020-11-30 09:57:59 -0500596 }
John Stiles3c991fd2021-08-09 14:19:58 -0400597 if (type->columns() > 0) {
598 SpvId typeId = this->getType(type->componentType(), layout);
Ethan Nicholas89cfde12021-09-27 11:20:34 -0400599 Literal countLiteral(/*line=*/-1, type->columns(),
John Stiles7591d4b2021-09-13 13:32:06 -0400600 fContext.fTypes.fInt.get());
601 SpvId countId = this->writeLiteral(countLiteral);
John Stilesb5db4822021-01-21 13:04:40 -0500602 this->writeInstruction(SpvOpTypeArray, result, typeId, countId,
603 fConstantBuffer);
Greg Daniel64773e62016-11-22 09:44:03 -0500604 this->writeInstruction(SpvOpDecorate, result, SpvDecorationArrayStride,
John Stiles3c991fd2021-08-09 14:19:58 -0400605 (int32_t) layout.stride(*type),
ethannicholas8ac838d2016-11-22 08:39:36 -0800606 fDecorationBuffer);
ethannicholasb3058bd2016-07-01 08:22:01 -0700607 } else {
John Stiles5570c512020-11-19 17:58:07 -0500608 // We shouldn't have any runtime-sized arrays right now
Ethan Nicholas89cfde12021-09-27 11:20:34 -0400609 fContext.fErrors->error(type->fLine,
Ethan Nicholas3abc6c62021-08-13 11:20:09 -0400610 "runtime-sized arrays are not supported in SPIR-V");
Greg Daniel64773e62016-11-22 09:44:03 -0500611 this->writeInstruction(SpvOpTypeRuntimeArray, result,
John Stiles3c991fd2021-08-09 14:19:58 -0400612 this->getType(type->componentType(), layout),
ethannicholas8ac838d2016-11-22 08:39:36 -0800613 fConstantBuffer);
Ethan Nicholas0dd30d92017-05-01 16:57:07 -0400614 this->writeInstruction(SpvOpDecorate, result, SpvDecorationArrayStride,
John Stiles3c991fd2021-08-09 14:19:58 -0400615 (int32_t) layout.stride(*type),
Ethan Nicholas0dd30d92017-05-01 16:57:07 -0400616 fDecorationBuffer);
ethannicholasb3058bd2016-07-01 08:22:01 -0700617 }
618 break;
619 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400620 case Type::TypeKind::kSampler: {
Greg Daniel64773e62016-11-22 09:44:03 -0500621 SpvId image = result;
John Stiles3c991fd2021-08-09 14:19:58 -0400622 if (SpvDimSubpassData != type->dimensions()) {
623 image = this->getType(type->textureType(), layout);
Greg Daniel64773e62016-11-22 09:44:03 -0500624 }
John Stiles3c991fd2021-08-09 14:19:58 -0400625 if (SpvDimBuffer == type->dimensions()) {
Ethan Nicholas0187ae62017-05-03 11:03:44 -0400626 fCapabilities |= (((uint64_t) 1) << SpvCapabilitySampledBuffer);
627 }
John Stiles3c991fd2021-08-09 14:19:58 -0400628 if (SpvDimSubpassData != type->dimensions()) {
Greg Daniel64773e62016-11-22 09:44:03 -0500629 this->writeInstruction(SpvOpTypeSampledImage, result, image, fConstantBuffer);
630 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700631 break;
632 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400633 case Type::TypeKind::kSeparateSampler: {
Stephen Whiteff5d7a22019-07-26 17:42:06 -0400634 this->writeInstruction(SpvOpTypeSampler, result, fConstantBuffer);
635 break;
636 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400637 case Type::TypeKind::kTexture: {
Stephen Whiteff5d7a22019-07-26 17:42:06 -0400638 this->writeInstruction(SpvOpTypeImage, result,
John Stiles54e7c052021-01-11 14:22:36 -0500639 this->getType(*fContext.fTypes.fFloat, layout),
John Stiles3c991fd2021-08-09 14:19:58 -0400640 type->dimensions(), type->isDepth(),
641 type->isArrayedTexture(), type->isMultisampled(),
642 type->isSampled() ? 1 : 2, SpvImageFormatUnknown,
643 fConstantBuffer);
Stephen Whiteff5d7a22019-07-26 17:42:06 -0400644 fImageTypeMap[key] = result;
645 break;
646 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700647 default:
John Stiles3c991fd2021-08-09 14:19:58 -0400648 if (type->isVoid()) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700649 this->writeInstruction(SpvOpTypeVoid, result, fConstantBuffer);
650 } else {
John Stiles3c991fd2021-08-09 14:19:58 -0400651 SkDEBUGFAILF("invalid type: %s", type->description().c_str());
ethannicholasb3058bd2016-07-01 08:22:01 -0700652 }
Ethan Nicholasb13f3692021-09-10 16:49:42 -0400653 break;
ethannicholasb3058bd2016-07-01 08:22:01 -0700654 }
ethannicholas8ac838d2016-11-22 08:39:36 -0800655 fTypeMap[key] = result;
ethannicholasb3058bd2016-07-01 08:22:01 -0700656 return result;
657 }
658 return entry->second;
659}
660
Ethan Nicholas0187ae62017-05-03 11:03:44 -0400661SpvId SPIRVCodeGenerator::getImageType(const Type& type) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400662 SkASSERT(type.typeKind() == Type::TypeKind::kSampler);
Ethan Nicholas0187ae62017-05-03 11:03:44 -0400663 this->getType(type);
664 String key = type.name() + to_string((int) fDefaultLayout.fStd);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400665 SkASSERT(fImageTypeMap.find(key) != fImageTypeMap.end());
Ethan Nicholas0187ae62017-05-03 11:03:44 -0400666 return fImageTypeMap[key];
667}
668
ethannicholasd598f792016-07-25 10:08:54 -0700669SpvId SPIRVCodeGenerator::getFunctionType(const FunctionDeclaration& function) {
Ethan Nicholased84b732020-10-08 11:45:44 -0400670 String key = to_string(this->getType(function.returnType())) + "(";
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400671 String separator;
Brian Osman5bf3e202020-10-13 10:34:18 -0400672 const std::vector<const Variable*>& parameters = function.parameters();
Ethan Nicholased84b732020-10-08 11:45:44 -0400673 for (size_t i = 0; i < parameters.size(); i++) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700674 key += separator;
675 separator = ", ";
Ethan Nicholased84b732020-10-08 11:45:44 -0400676 key += to_string(this->getType(parameters[i]->type()));
ethannicholasb3058bd2016-07-01 08:22:01 -0700677 }
678 key += ")";
679 auto entry = fTypeMap.find(key);
680 if (entry == fTypeMap.end()) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -0400681 SpvId result = this->nextId(nullptr);
Ethan Nicholased84b732020-10-08 11:45:44 -0400682 int32_t length = 3 + (int32_t) parameters.size();
683 SpvId returnType = this->getType(function.returnType());
ethannicholasb3058bd2016-07-01 08:22:01 -0700684 std::vector<SpvId> parameterTypes;
Ethan Nicholased84b732020-10-08 11:45:44 -0400685 for (size_t i = 0; i < parameters.size(); i++) {
Greg Daniel64773e62016-11-22 09:44:03 -0500686 // glslang seems to treat all function arguments as pointers whether they need to be or
687 // not. I was initially puzzled by this until I ran bizarre failures with certain
688 // patterns of function calls and control constructs, as exemplified by this minimal
ethannicholasb3058bd2016-07-01 08:22:01 -0700689 // failure case:
690 //
691 // void sphere(float x) {
692 // }
Greg Daniel64773e62016-11-22 09:44:03 -0500693 //
ethannicholasb3058bd2016-07-01 08:22:01 -0700694 // void map() {
695 // sphere(1.0);
696 // }
Greg Daniel64773e62016-11-22 09:44:03 -0500697 //
ethannicholasb3058bd2016-07-01 08:22:01 -0700698 // void main() {
699 // for (int i = 0; i < 1; i++) {
700 // map();
701 // }
702 // }
703 //
Greg Daniel64773e62016-11-22 09:44:03 -0500704 // As of this writing, compiling this in the "obvious" way (with sphere taking a float)
705 // crashes. Making it take a float* and storing the argument in a temporary variable,
ethannicholasb3058bd2016-07-01 08:22:01 -0700706 // as glslang does, fixes it. It's entirely possible I simply missed whichever part of
707 // the spec makes this make sense.
John Stiles07367122021-09-08 13:12:26 -0400708 parameterTypes.push_back(this->getPointerType(parameters[i]->type(),
709 SpvStorageClassFunction));
ethannicholasb3058bd2016-07-01 08:22:01 -0700710 }
711 this->writeOpCode(SpvOpTypeFunction, length, fConstantBuffer);
712 this->writeWord(result, fConstantBuffer);
713 this->writeWord(returnType, fConstantBuffer);
714 for (SpvId id : parameterTypes) {
715 this->writeWord(id, fConstantBuffer);
716 }
717 fTypeMap[key] = result;
718 return result;
719 }
720 return entry->second;
721}
722
ethannicholas8ac838d2016-11-22 08:39:36 -0800723SpvId SPIRVCodeGenerator::getPointerType(const Type& type, SpvStorageClass_ storageClass) {
724 return this->getPointerType(type, fDefaultLayout, storageClass);
725}
726
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400727SpvId SPIRVCodeGenerator::getPointerType(const Type& rawType, const MemoryLayout& layout,
ethannicholasb3058bd2016-07-01 08:22:01 -0700728 SpvStorageClass_ storageClass) {
Ethan Nicholase2c49992020-10-05 11:49:11 -0400729 const Type& type = this->getActualType(rawType);
Ethan Nicholas2a099da2020-01-02 14:40:54 -0500730 String key = type.displayName() + "*" + to_string(layout.fStd) + to_string(storageClass);
ethannicholasb3058bd2016-07-01 08:22:01 -0700731 auto entry = fTypeMap.find(key);
732 if (entry == fTypeMap.end()) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -0400733 SpvId result = this->nextId(nullptr);
Greg Daniel64773e62016-11-22 09:44:03 -0500734 this->writeInstruction(SpvOpTypePointer, result, storageClass,
ethannicholasd598f792016-07-25 10:08:54 -0700735 this->getType(type), fConstantBuffer);
ethannicholasb3058bd2016-07-01 08:22:01 -0700736 fTypeMap[key] = result;
737 return result;
738 }
739 return entry->second;
740}
741
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400742SpvId SPIRVCodeGenerator::writeExpression(const Expression& expr, OutputStream& out) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400743 switch (expr.kind()) {
744 case Expression::Kind::kBinary:
John Stiles81365af2020-08-18 09:24:00 -0400745 return this->writeBinaryExpression(expr.as<BinaryExpression>(), out);
John Stilese3ae9682021-08-05 10:35:01 -0400746 case Expression::Kind::kConstructorArrayCast:
747 return this->writeExpression(*expr.as<ConstructorArrayCast>().argument(), out);
John Stiles7384b372021-04-01 13:48:15 -0400748 case Expression::Kind::kConstructorArray:
John Stilesd47330f2021-04-08 23:25:52 -0400749 case Expression::Kind::kConstructorStruct:
750 return this->writeCompositeConstructor(expr.asAnyConstructor(), out);
John Stilese1182782021-03-30 22:09:37 -0400751 case Expression::Kind::kConstructorDiagonalMatrix:
752 return this->writeConstructorDiagonalMatrix(expr.as<ConstructorDiagonalMatrix>(), out);
John Stiles5abb9e12021-04-06 13:47:19 -0400753 case Expression::Kind::kConstructorMatrixResize:
754 return this->writeConstructorMatrixResize(expr.as<ConstructorMatrixResize>(), out);
John Stilesfd7252f2021-04-04 22:24:40 -0400755 case Expression::Kind::kConstructorScalarCast:
756 return this->writeConstructorScalarCast(expr.as<ConstructorScalarCast>(), out);
John Stiles2938eea2021-04-01 18:58:25 -0400757 case Expression::Kind::kConstructorSplat:
758 return this->writeConstructorSplat(expr.as<ConstructorSplat>(), out);
John Stiles8cad6372021-04-07 12:31:13 -0400759 case Expression::Kind::kConstructorCompound:
760 return this->writeConstructorCompound(expr.as<ConstructorCompound>(), out);
761 case Expression::Kind::kConstructorCompoundCast:
762 return this->writeConstructorCompoundCast(expr.as<ConstructorCompoundCast>(), out);
Ethan Nicholase6592142020-09-08 10:22:09 -0400763 case Expression::Kind::kFieldAccess:
John Stiles81365af2020-08-18 09:24:00 -0400764 return this->writeFieldAccess(expr.as<FieldAccess>(), out);
Ethan Nicholase6592142020-09-08 10:22:09 -0400765 case Expression::Kind::kFunctionCall:
John Stiles81365af2020-08-18 09:24:00 -0400766 return this->writeFunctionCall(expr.as<FunctionCall>(), out);
John Stiles7591d4b2021-09-13 13:32:06 -0400767 case Expression::Kind::kLiteral:
768 return this->writeLiteral(expr.as<Literal>());
Ethan Nicholase6592142020-09-08 10:22:09 -0400769 case Expression::Kind::kPrefix:
John Stiles81365af2020-08-18 09:24:00 -0400770 return this->writePrefixExpression(expr.as<PrefixExpression>(), out);
Ethan Nicholase6592142020-09-08 10:22:09 -0400771 case Expression::Kind::kPostfix:
John Stiles81365af2020-08-18 09:24:00 -0400772 return this->writePostfixExpression(expr.as<PostfixExpression>(), out);
Ethan Nicholase6592142020-09-08 10:22:09 -0400773 case Expression::Kind::kSwizzle:
John Stiles81365af2020-08-18 09:24:00 -0400774 return this->writeSwizzle(expr.as<Swizzle>(), out);
Ethan Nicholase6592142020-09-08 10:22:09 -0400775 case Expression::Kind::kVariableReference:
John Stiles81365af2020-08-18 09:24:00 -0400776 return this->writeVariableReference(expr.as<VariableReference>(), out);
Ethan Nicholase6592142020-09-08 10:22:09 -0400777 case Expression::Kind::kTernary:
John Stiles81365af2020-08-18 09:24:00 -0400778 return this->writeTernaryExpression(expr.as<TernaryExpression>(), out);
Ethan Nicholase6592142020-09-08 10:22:09 -0400779 case Expression::Kind::kIndex:
John Stiles81365af2020-08-18 09:24:00 -0400780 return this->writeIndexExpression(expr.as<IndexExpression>(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -0700781 default:
John Stileseada7bc2021-02-02 16:29:32 -0500782 SkDEBUGFAILF("unsupported expression: %s", expr.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -0500783 break;
ethannicholasb3058bd2016-07-01 08:22:01 -0700784 }
785 return -1;
786}
787
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400788SpvId SPIRVCodeGenerator::writeIntrinsicCall(const FunctionCall& c, OutputStream& out) {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400789 const FunctionDeclaration& function = c.function();
John Stilesaaac4e42021-05-06 14:08:28 -0400790 auto intrinsic = fIntrinsicMap.find(function.intrinsicKind());
John Stiles93e661a2020-12-08 16:17:00 -0500791 if (intrinsic == fIntrinsicMap.end()) {
Ethan Nicholas89cfde12021-09-27 11:20:34 -0400792 fContext.fErrors->error(c.fLine, "unsupported intrinsic '" + function.description() + "'");
John Stiles93e661a2020-12-08 16:17:00 -0500793 return -1;
794 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700795 int32_t intrinsicId;
John Stiles89ac7c22020-12-30 17:47:31 -0500796 const ExpressionArray& arguments = c.arguments();
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400797 if (arguments.size() > 0) {
798 const Type& type = arguments[0]->type();
John Stilesaaac4e42021-05-06 14:08:28 -0400799 if (std::get<0>(intrinsic->second) == kSpecial_IntrinsicOpcodeKind ||
800 is_float(fContext, type)) {
Ethan Nicholasbb155e22017-07-24 10:05:09 -0400801 intrinsicId = std::get<1>(intrinsic->second);
802 } else if (is_signed(fContext, type)) {
803 intrinsicId = std::get<2>(intrinsic->second);
804 } else if (is_unsigned(fContext, type)) {
805 intrinsicId = std::get<3>(intrinsic->second);
806 } else if (is_bool(fContext, type)) {
807 intrinsicId = std::get<4>(intrinsic->second);
808 } else {
809 intrinsicId = std::get<1>(intrinsic->second);
810 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700811 } else {
Ethan Nicholasbb155e22017-07-24 10:05:09 -0400812 intrinsicId = std::get<1>(intrinsic->second);
ethannicholasb3058bd2016-07-01 08:22:01 -0700813 }
814 switch (std::get<0>(intrinsic->second)) {
John Stilesaaac4e42021-05-06 14:08:28 -0400815 case kGLSL_STD_450_IntrinsicOpcodeKind: {
Ethan Nicholas7f015882021-03-23 14:16:52 -0400816 SpvId result = this->nextId(&c.type());
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400817 std::vector<SpvId> argumentIds;
John Stiles07367122021-09-08 13:12:26 -0400818 std::vector<TempVar> tempVars;
819 argumentIds.reserve(arguments.size());
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400820 for (size_t i = 0; i < arguments.size(); i++) {
John Stiles07367122021-09-08 13:12:26 -0400821 if (is_out(function.parameters()[i]->modifiers())) {
822 argumentIds.push_back(
823 this->writeFunctionCallArgument(*arguments[i],
824 function.parameters()[i]->modifiers(),
825 &tempVars,
826 out));
Ethan Nicholas8f7e28f2018-03-26 14:24:27 -0400827 } else {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400828 argumentIds.push_back(this->writeExpression(*arguments[i], out));
Ethan Nicholas8f7e28f2018-03-26 14:24:27 -0400829 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700830 }
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400831 this->writeOpCode(SpvOpExtInst, 5 + (int32_t) argumentIds.size(), out);
Ethan Nicholas30d30222020-09-11 12:27:26 -0400832 this->writeWord(this->getType(c.type()), out);
ethannicholasb3058bd2016-07-01 08:22:01 -0700833 this->writeWord(result, out);
834 this->writeWord(fGLSLExtendedInstructions, out);
835 this->writeWord(intrinsicId, out);
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400836 for (SpvId id : argumentIds) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700837 this->writeWord(id, out);
838 }
John Stiles07367122021-09-08 13:12:26 -0400839 this->copyBackTempVars(tempVars, out);
ethannicholasb3058bd2016-07-01 08:22:01 -0700840 return result;
841 }
John Stilesaaac4e42021-05-06 14:08:28 -0400842 case kSPIRV_IntrinsicOpcodeKind: {
Brian Osman46787d52020-11-24 14:18:23 -0500843 // GLSL supports dot(float, float), but SPIR-V does not. Convert it to FMul
John Stiles9aeed132020-11-24 17:36:06 -0500844 if (intrinsicId == SpvOpDot && arguments[0]->type().isScalar()) {
Brian Osman46787d52020-11-24 14:18:23 -0500845 intrinsicId = SpvOpFMul;
846 }
Ethan Nicholas7f015882021-03-23 14:16:52 -0400847 SpvId result = this->nextId(&c.type());
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400848 std::vector<SpvId> argumentIds;
John Stiles07367122021-09-08 13:12:26 -0400849 std::vector<TempVar> tempVars;
850 argumentIds.reserve(arguments.size());
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400851 for (size_t i = 0; i < arguments.size(); i++) {
John Stiles07367122021-09-08 13:12:26 -0400852 if (is_out(function.parameters()[i]->modifiers())) {
853 argumentIds.push_back(
854 this->writeFunctionCallArgument(*arguments[i],
855 function.parameters()[i]->modifiers(),
856 &tempVars,
857 out));
Ethan Nicholas8f7e28f2018-03-26 14:24:27 -0400858 } else {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400859 argumentIds.push_back(this->writeExpression(*arguments[i], out));
Ethan Nicholas8f7e28f2018-03-26 14:24:27 -0400860 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700861 }
John Stiles2558c462021-03-16 17:49:20 -0400862 if (!c.type().isVoid()) {
Ethan Nicholasbb155e22017-07-24 10:05:09 -0400863 this->writeOpCode((SpvOp_) intrinsicId, 3 + (int32_t) arguments.size(), out);
Ethan Nicholas30d30222020-09-11 12:27:26 -0400864 this->writeWord(this->getType(c.type()), out);
Ethan Nicholasbb155e22017-07-24 10:05:09 -0400865 this->writeWord(result, out);
866 } else {
867 this->writeOpCode((SpvOp_) intrinsicId, 1 + (int32_t) arguments.size(), out);
868 }
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400869 for (SpvId id : argumentIds) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700870 this->writeWord(id, out);
871 }
John Stiles07367122021-09-08 13:12:26 -0400872 this->copyBackTempVars(tempVars, out);
ethannicholasb3058bd2016-07-01 08:22:01 -0700873 return result;
874 }
John Stilesaaac4e42021-05-06 14:08:28 -0400875 case kSpecial_IntrinsicOpcodeKind:
ethannicholasb3058bd2016-07-01 08:22:01 -0700876 return this->writeSpecialIntrinsic(c, (SpecialIntrinsic) intrinsicId, out);
877 default:
Ethan Nicholas89cfde12021-09-27 11:20:34 -0400878 fContext.fErrors->error(c.fLine, "unsupported intrinsic '" + function.description() +
879 "'");
John Stiles93e661a2020-12-08 16:17:00 -0500880 return -1;
ethannicholasb3058bd2016-07-01 08:22:01 -0700881 }
882}
883
Brian Salomond8d85b92021-07-07 09:41:17 -0400884SpvId SPIRVCodeGenerator::vectorize(const Expression& arg, int vectorSize, OutputStream& out) {
885 SkASSERT(vectorSize >= 1 && vectorSize <= 4);
886 const Type& argType = arg.type();
887 SpvId raw = this->writeExpression(arg, out);
888 if (argType.isScalar()) {
889 if (vectorSize == 1) {
890 return raw;
891 }
892 SpvId vector = this->nextId(&argType);
893 this->writeOpCode(SpvOpCompositeConstruct, 3 + vectorSize, out);
894 this->writeWord(this->getType(argType.toCompound(fContext, vectorSize, 1)), out);
895 this->writeWord(vector, out);
896 for (int i = 0; i < vectorSize; i++) {
897 this->writeWord(raw, out);
898 }
899 return vector;
900 } else {
901 SkASSERT(vectorSize == argType.columns());
902 return raw;
903 }
904}
905
John Stiles8e3b6be2020-10-13 11:14:08 -0400906std::vector<SpvId> SPIRVCodeGenerator::vectorize(const ExpressionArray& args, OutputStream& out) {
Brian Salomond8d85b92021-07-07 09:41:17 -0400907 int vectorSize = 1;
Ethan Nicholas0fc07f92018-02-27 15:25:47 -0500908 for (const auto& a : args) {
John Stiles9aeed132020-11-24 17:36:06 -0500909 if (a->type().isVector()) {
Brian Salomond8d85b92021-07-07 09:41:17 -0400910 if (vectorSize > 1) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400911 SkASSERT(a->type().columns() == vectorSize);
Brian Salomond8d85b92021-07-07 09:41:17 -0400912 } else {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400913 vectorSize = a->type().columns();
Ethan Nicholas0fc07f92018-02-27 15:25:47 -0500914 }
915 }
916 }
917 std::vector<SpvId> result;
John Stiles8e3b6be2020-10-13 11:14:08 -0400918 result.reserve(args.size());
Ethan Nicholas30d30222020-09-11 12:27:26 -0400919 for (const auto& arg : args) {
Brian Salomond8d85b92021-07-07 09:41:17 -0400920 result.push_back(this->vectorize(*arg, vectorSize, out));
Ethan Nicholas0fc07f92018-02-27 15:25:47 -0500921 }
922 return result;
923}
924
925void SPIRVCodeGenerator::writeGLSLExtendedInstruction(const Type& type, SpvId id, SpvId floatInst,
926 SpvId signedInst, SpvId unsignedInst,
927 const std::vector<SpvId>& args,
928 OutputStream& out) {
929 this->writeOpCode(SpvOpExtInst, 5 + args.size(), out);
930 this->writeWord(this->getType(type), out);
931 this->writeWord(id, out);
932 this->writeWord(fGLSLExtendedInstructions, out);
933
934 if (is_float(fContext, type)) {
935 this->writeWord(floatInst, out);
936 } else if (is_signed(fContext, type)) {
937 this->writeWord(signedInst, out);
938 } else if (is_unsigned(fContext, type)) {
939 this->writeWord(unsignedInst, out);
940 } else {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400941 SkASSERT(false);
Ethan Nicholas0fc07f92018-02-27 15:25:47 -0500942 }
943 for (SpvId a : args) {
944 this->writeWord(a, out);
945 }
946}
947
Greg Daniel64773e62016-11-22 09:44:03 -0500948SpvId SPIRVCodeGenerator::writeSpecialIntrinsic(const FunctionCall& c, SpecialIntrinsic kind,
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400949 OutputStream& out) {
John Stiles8e3b6be2020-10-13 11:14:08 -0400950 const ExpressionArray& arguments = c.arguments();
Ethan Nicholas30d30222020-09-11 12:27:26 -0400951 const Type& callType = c.type();
Ethan Nicholas8f352ce2021-03-17 14:12:20 -0400952 SpvId result = this->nextId(nullptr);
ethannicholasb3058bd2016-07-01 08:22:01 -0700953 switch (kind) {
954 case kAtan_SpecialIntrinsic: {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400955 std::vector<SpvId> argumentIds;
John Stiles07367122021-09-08 13:12:26 -0400956 argumentIds.reserve(arguments.size());
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400957 for (const std::unique_ptr<Expression>& arg : arguments) {
958 argumentIds.push_back(this->writeExpression(*arg, out));
ethannicholasb3058bd2016-07-01 08:22:01 -0700959 }
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400960 this->writeOpCode(SpvOpExtInst, 5 + (int32_t) argumentIds.size(), out);
Ethan Nicholas30d30222020-09-11 12:27:26 -0400961 this->writeWord(this->getType(callType), out);
ethannicholasb3058bd2016-07-01 08:22:01 -0700962 this->writeWord(result, out);
963 this->writeWord(fGLSLExtendedInstructions, out);
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400964 this->writeWord(argumentIds.size() == 2 ? GLSLstd450Atan2 : GLSLstd450Atan, out);
965 for (SpvId id : argumentIds) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700966 this->writeWord(id, out);
967 }
Ethan Nicholas0187ae62017-05-03 11:03:44 -0400968 break;
969 }
Stephen Whiteff5d7a22019-07-26 17:42:06 -0400970 case kSampledImage_SpecialIntrinsic: {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400971 SkASSERT(arguments.size() == 2);
972 SpvId img = this->writeExpression(*arguments[0], out);
973 SpvId sampler = this->writeExpression(*arguments[1], out);
Stephen Whiteff5d7a22019-07-26 17:42:06 -0400974 this->writeInstruction(SpvOpSampledImage,
Ethan Nicholas30d30222020-09-11 12:27:26 -0400975 this->getType(callType),
Stephen Whiteff5d7a22019-07-26 17:42:06 -0400976 result,
977 img,
978 sampler,
979 out);
980 break;
981 }
Ethan Nicholas0187ae62017-05-03 11:03:44 -0400982 case kSubpassLoad_SpecialIntrinsic: {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400983 SpvId img = this->writeExpression(*arguments[0], out);
John Stiles8e3b6be2020-10-13 11:14:08 -0400984 ExpressionArray args;
John Stilesf4bda742020-10-14 16:57:41 -0400985 args.reserve_back(2);
Ethan Nicholas89cfde12021-09-27 11:20:34 -0400986 args.push_back(Literal::MakeInt(fContext, /*line=*/-1, /*value=*/0));
987 args.push_back(Literal::MakeInt(fContext, /*line=*/-1, /*value=*/0));
988 ConstructorCompound ctor(/*line=*/-1, *fContext.fTypes.fInt2, std::move(args));
Ethan Nicholas0187ae62017-05-03 11:03:44 -0400989 SpvId coords = this->writeConstantVector(ctor);
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400990 if (arguments.size() == 1) {
Ethan Nicholas0187ae62017-05-03 11:03:44 -0400991 this->writeInstruction(SpvOpImageRead,
Ethan Nicholas30d30222020-09-11 12:27:26 -0400992 this->getType(callType),
Ethan Nicholas0187ae62017-05-03 11:03:44 -0400993 result,
994 img,
995 coords,
996 out);
997 } else {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400998 SkASSERT(arguments.size() == 2);
999 SpvId sample = this->writeExpression(*arguments[1], out);
Ethan Nicholas0187ae62017-05-03 11:03:44 -04001000 this->writeInstruction(SpvOpImageRead,
Ethan Nicholas30d30222020-09-11 12:27:26 -04001001 this->getType(callType),
Ethan Nicholas0187ae62017-05-03 11:03:44 -04001002 result,
1003 img,
1004 coords,
1005 SpvImageOperandsSampleMask,
1006 sample,
1007 out);
1008 }
1009 break;
1010 }
ethannicholasb3058bd2016-07-01 08:22:01 -07001011 case kTexture_SpecialIntrinsic: {
Ethan Nicholas2b3dab62016-11-28 12:03:26 -05001012 SpvOp_ op = SpvOpImageSampleImplicitLod;
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001013 const Type& arg1Type = arguments[1]->type();
1014 switch (arguments[0]->type().dimensions()) {
Ethan Nicholas2b3dab62016-11-28 12:03:26 -05001015 case SpvDim1D:
John Stiles54e7c052021-01-11 14:22:36 -05001016 if (arg1Type == *fContext.fTypes.fFloat2) {
Ethan Nicholas2b3dab62016-11-28 12:03:26 -05001017 op = SpvOpImageSampleProjImplicitLod;
1018 } else {
John Stiles54e7c052021-01-11 14:22:36 -05001019 SkASSERT(arg1Type == *fContext.fTypes.fFloat);
Ethan Nicholas2b3dab62016-11-28 12:03:26 -05001020 }
1021 break;
1022 case SpvDim2D:
John Stiles54e7c052021-01-11 14:22:36 -05001023 if (arg1Type == *fContext.fTypes.fFloat3) {
Ethan Nicholas2b3dab62016-11-28 12:03:26 -05001024 op = SpvOpImageSampleProjImplicitLod;
1025 } else {
John Stiles54e7c052021-01-11 14:22:36 -05001026 SkASSERT(arg1Type == *fContext.fTypes.fFloat2);
Ethan Nicholas2b3dab62016-11-28 12:03:26 -05001027 }
1028 break;
1029 case SpvDim3D:
John Stiles54e7c052021-01-11 14:22:36 -05001030 if (arg1Type == *fContext.fTypes.fFloat4) {
Ethan Nicholas2b3dab62016-11-28 12:03:26 -05001031 op = SpvOpImageSampleProjImplicitLod;
1032 } else {
John Stiles54e7c052021-01-11 14:22:36 -05001033 SkASSERT(arg1Type == *fContext.fTypes.fFloat3);
Ethan Nicholas2b3dab62016-11-28 12:03:26 -05001034 }
1035 break;
1036 case SpvDimCube: // fall through
1037 case SpvDimRect: // fall through
1038 case SpvDimBuffer: // fall through
1039 case SpvDimSubpassData:
1040 break;
1041 }
Ethan Nicholas30d30222020-09-11 12:27:26 -04001042 SpvId type = this->getType(callType);
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001043 SpvId sampler = this->writeExpression(*arguments[0], out);
1044 SpvId uv = this->writeExpression(*arguments[1], out);
1045 if (arguments.size() == 3) {
Ethan Nicholas2b3dab62016-11-28 12:03:26 -05001046 this->writeInstruction(op, type, result, sampler, uv,
ethannicholasb3058bd2016-07-01 08:22:01 -07001047 SpvImageOperandsBiasMask,
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001048 this->writeExpression(*arguments[2], out),
ethannicholasb3058bd2016-07-01 08:22:01 -07001049 out);
1050 } else {
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001051 SkASSERT(arguments.size() == 2);
John Stiles270cec22021-02-17 12:59:36 -05001052 if (fProgram.fConfig->fSettings.fSharpenTextures) {
Ethan Nicholas89cfde12021-09-27 11:20:34 -04001053 Literal lodBias(/*line=*/-1, /*value=*/-0.5, fContext.fTypes.fFloat.get());
Brian Osman8a83ca42018-02-12 14:32:17 -05001054 this->writeInstruction(op, type, result, sampler, uv,
1055 SpvImageOperandsBiasMask,
John Stiles7591d4b2021-09-13 13:32:06 -04001056 this->writeLiteral(lodBias),
Brian Osman8a83ca42018-02-12 14:32:17 -05001057 out);
1058 } else {
1059 this->writeInstruction(op, type, result, sampler, uv,
1060 out);
1061 }
ethannicholasb3058bd2016-07-01 08:22:01 -07001062 }
1063 break;
1064 }
Ethan Nicholas70a44b22017-11-30 09:09:16 -05001065 case kMod_SpecialIntrinsic: {
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001066 std::vector<SpvId> args = this->vectorize(arguments, out);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001067 SkASSERT(args.size() == 2);
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001068 const Type& operandType = arguments[0]->type();
Ethan Nicholas70a44b22017-11-30 09:09:16 -05001069 SpvOp_ op;
1070 if (is_float(fContext, operandType)) {
1071 op = SpvOpFMod;
1072 } else if (is_signed(fContext, operandType)) {
1073 op = SpvOpSMod;
1074 } else if (is_unsigned(fContext, operandType)) {
1075 op = SpvOpUMod;
1076 } else {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001077 SkASSERT(false);
Ethan Nicholas70a44b22017-11-30 09:09:16 -05001078 return 0;
1079 }
1080 this->writeOpCode(op, 5, out);
1081 this->writeWord(this->getType(operandType), out);
1082 this->writeWord(result, out);
Ethan Nicholas0fc07f92018-02-27 15:25:47 -05001083 this->writeWord(args[0], out);
1084 this->writeWord(args[1], out);
1085 break;
1086 }
Chris Daltonb8af5ad2019-02-25 14:54:21 -07001087 case kDFdy_SpecialIntrinsic: {
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001088 SpvId fn = this->writeExpression(*arguments[0], out);
Chris Daltonb8af5ad2019-02-25 14:54:21 -07001089 this->writeOpCode(SpvOpDPdy, 4, out);
Ethan Nicholas30d30222020-09-11 12:27:26 -04001090 this->writeWord(this->getType(callType), out);
Chris Daltonb8af5ad2019-02-25 14:54:21 -07001091 this->writeWord(result, out);
1092 this->writeWord(fn, out);
Ethan Nicholas89cfde12021-09-27 11:20:34 -04001093 this->addRTFlipUniform(c.fLine);
Brian Salomond8d85b92021-07-07 09:41:17 -04001094 using namespace dsl;
Ethan Nicholas89cfde12021-09-27 11:20:34 -04001095 DSLExpression rtFlip(DSLWriter::IRGenerator().convertIdentifier(/*line=*/-1,
Brian Salomond8d85b92021-07-07 09:41:17 -04001096 SKSL_RTFLIP_NAME));
1097 SpvId rtFlipY = this->vectorize(*rtFlip.y().release(), callType.columns(), out);
1098 SpvId flipped = this->nextId(&callType);
1099 this->writeInstruction(SpvOpFMul, this->getType(callType), flipped, result, rtFlipY,
1100 out);
1101 result = flipped;
Chris Daltonb8af5ad2019-02-25 14:54:21 -07001102 break;
1103 }
Ethan Nicholas0fc07f92018-02-27 15:25:47 -05001104 case kClamp_SpecialIntrinsic: {
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001105 std::vector<SpvId> args = this->vectorize(arguments, out);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001106 SkASSERT(args.size() == 3);
Ethan Nicholas30d30222020-09-11 12:27:26 -04001107 this->writeGLSLExtendedInstruction(callType, result, GLSLstd450FClamp, GLSLstd450SClamp,
Ethan Nicholas0fc07f92018-02-27 15:25:47 -05001108 GLSLstd450UClamp, args, out);
1109 break;
1110 }
1111 case kMax_SpecialIntrinsic: {
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001112 std::vector<SpvId> args = this->vectorize(arguments, out);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001113 SkASSERT(args.size() == 2);
Ethan Nicholas30d30222020-09-11 12:27:26 -04001114 this->writeGLSLExtendedInstruction(callType, result, GLSLstd450FMax, GLSLstd450SMax,
Ethan Nicholas0fc07f92018-02-27 15:25:47 -05001115 GLSLstd450UMax, args, out);
1116 break;
1117 }
1118 case kMin_SpecialIntrinsic: {
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001119 std::vector<SpvId> args = this->vectorize(arguments, out);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001120 SkASSERT(args.size() == 2);
Ethan Nicholas30d30222020-09-11 12:27:26 -04001121 this->writeGLSLExtendedInstruction(callType, result, GLSLstd450FMin, GLSLstd450SMin,
Ethan Nicholas0fc07f92018-02-27 15:25:47 -05001122 GLSLstd450UMin, args, out);
1123 break;
1124 }
1125 case kMix_SpecialIntrinsic: {
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001126 std::vector<SpvId> args = this->vectorize(arguments, out);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001127 SkASSERT(args.size() == 3);
John Stilescc2d9cc2021-07-09 17:38:41 -04001128 if (arguments[2]->type().componentType().isBoolean()) {
1129 // Use OpSelect to implement Boolean mix().
1130 SpvId falseId = this->writeExpression(*arguments[0], out);
1131 SpvId trueId = this->writeExpression(*arguments[1], out);
1132 SpvId conditionId = this->writeExpression(*arguments[2], out);
1133 this->writeInstruction(SpvOpSelect, this->getType(arguments[0]->type()), result,
1134 conditionId, trueId, falseId, out);
1135 } else {
1136 this->writeGLSLExtendedInstruction(callType, result, GLSLstd450FMix, SpvOpUndef,
1137 SpvOpUndef, args, out);
1138 }
Ethan Nicholas0fc07f92018-02-27 15:25:47 -05001139 break;
Ethan Nicholas70a44b22017-11-30 09:09:16 -05001140 }
Ethan Nicholas12fb9cf2018-08-03 16:16:57 -04001141 case kSaturate_SpecialIntrinsic: {
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001142 SkASSERT(arguments.size() == 1);
John Stiles8e3b6be2020-10-13 11:14:08 -04001143 ExpressionArray finalArgs;
John Stilesf4bda742020-10-14 16:57:41 -04001144 finalArgs.reserve_back(3);
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001145 finalArgs.push_back(arguments[0]->clone());
Ethan Nicholas89cfde12021-09-27 11:20:34 -04001146 finalArgs.push_back(Literal::MakeFloat(fContext, /*line=*/-1, /*value=*/0));
1147 finalArgs.push_back(Literal::MakeFloat(fContext, /*line=*/-1, /*value=*/1));
Ethan Nicholas12fb9cf2018-08-03 16:16:57 -04001148 std::vector<SpvId> spvArgs = this->vectorize(finalArgs, out);
Ethan Nicholas30d30222020-09-11 12:27:26 -04001149 this->writeGLSLExtendedInstruction(callType, result, GLSLstd450FClamp, GLSLstd450SClamp,
Ethan Nicholas12fb9cf2018-08-03 16:16:57 -04001150 GLSLstd450UClamp, spvArgs, out);
1151 break;
1152 }
Brian Osman6ba3be12020-11-13 16:32:52 -05001153 case kSmoothStep_SpecialIntrinsic: {
1154 std::vector<SpvId> args = this->vectorize(arguments, out);
1155 SkASSERT(args.size() == 3);
1156 this->writeGLSLExtendedInstruction(callType, result, GLSLstd450SmoothStep, SpvOpUndef,
1157 SpvOpUndef, args, out);
1158 break;
1159 }
1160 case kStep_SpecialIntrinsic: {
1161 std::vector<SpvId> args = this->vectorize(arguments, out);
1162 SkASSERT(args.size() == 2);
1163 this->writeGLSLExtendedInstruction(callType, result, GLSLstd450Step, SpvOpUndef,
1164 SpvOpUndef, args, out);
1165 break;
1166 }
Brian Osmand1b593f2020-12-28 13:00:46 -05001167 case kMatrixCompMult_SpecialIntrinsic: {
1168 SkASSERT(arguments.size() == 2);
1169 SpvId lhs = this->writeExpression(*arguments[0], out);
1170 SpvId rhs = this->writeExpression(*arguments[1], out);
John Stiles43b593c2021-05-13 22:03:27 -04001171 result = this->writeComponentwiseMatrixBinary(callType, lhs, rhs, SpvOpFMul, out);
Brian Osmand1b593f2020-12-28 13:00:46 -05001172 break;
1173 }
ethannicholasb3058bd2016-07-01 08:22:01 -07001174 }
1175 return result;
1176}
1177
John Stiles07367122021-09-08 13:12:26 -04001178SpvId SPIRVCodeGenerator::writeFunctionCallArgument(const Expression& arg,
1179 const Modifiers& paramModifiers,
1180 std::vector<TempVar>* tempVars,
1181 OutputStream& out) {
1182 // ID of temporary variable that we will use to hold this argument, or 0 if it is being
1183 // passed directly
1184 SpvId tmpVar;
1185 // if we need a temporary var to store this argument, this is the value to store in the var
1186 SpvId tmpValueId = -1;
1187
1188 if (is_out(paramModifiers)) {
1189 std::unique_ptr<LValue> lv = this->getLValue(arg, out);
1190 SpvId ptr = lv->getPointer();
1191 if (ptr != (SpvId) -1 && lv->isMemoryObjectPointer()) {
1192 return ptr;
1193 }
1194
1195 // lvalue cannot simply be read and written via a pointer (e.g. it's a swizzle). We need to
1196 // to use a temp variable.
1197 if (is_in(paramModifiers)) {
1198 tmpValueId = lv->load(out);
1199 }
1200 tmpVar = this->nextId(&arg.type());
1201 tempVars->push_back(TempVar{tmpVar, &arg.type(), std::move(lv)});
1202 } else {
1203 // See getFunctionType for an explanation of why we're always using pointer parameters.
1204 tmpValueId = this->writeExpression(arg, out);
1205 tmpVar = this->nextId(nullptr);
1206 }
1207 this->writeInstruction(SpvOpVariable,
1208 this->getPointerType(arg.type(), SpvStorageClassFunction),
1209 tmpVar,
1210 SpvStorageClassFunction,
1211 fVariableBuffer);
1212 if (tmpValueId != (SpvId)-1) {
1213 this->writeInstruction(SpvOpStore, tmpVar, tmpValueId, out);
1214 }
1215 return tmpVar;
1216}
1217
1218void SPIRVCodeGenerator::copyBackTempVars(const std::vector<TempVar>& tempVars, OutputStream& out) {
1219 for (const TempVar& tempVar : tempVars) {
1220 SpvId load = this->nextId(tempVar.type);
1221 this->writeInstruction(SpvOpLoad, this->getType(*tempVar.type), load, tempVar.spvId, out);
1222 tempVar.lvalue->store(load, out);
1223 }
John Stilesec241542021-02-11 17:50:09 -05001224}
1225
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001226SpvId SPIRVCodeGenerator::writeFunctionCall(const FunctionCall& c, OutputStream& out) {
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001227 const FunctionDeclaration& function = c.function();
John Stilesaaac4e42021-05-06 14:08:28 -04001228 if (function.isIntrinsic() && !function.definition()) {
John Stiles89ac7c22020-12-30 17:47:31 -05001229 return this->writeIntrinsicCall(c, out);
1230 }
John Stiles8e3b6be2020-10-13 11:14:08 -04001231 const ExpressionArray& arguments = c.arguments();
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001232 const auto& entry = fFunctionMap.find(&function);
ethannicholasb3058bd2016-07-01 08:22:01 -07001233 if (entry == fFunctionMap.end()) {
Ethan Nicholas89cfde12021-09-27 11:20:34 -04001234 fContext.fErrors->error(c.fLine, "function '" + function.description() +
1235 "' is not defined");
John Stiles89ac7c22020-12-30 17:47:31 -05001236 return -1;
ethannicholasb3058bd2016-07-01 08:22:01 -07001237 }
John Stilesec241542021-02-11 17:50:09 -05001238 // Temp variables are used to write back out-parameters after the function call is complete.
1239 std::vector<TempVar> tempVars;
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001240 std::vector<SpvId> argumentIds;
John Stiles07367122021-09-08 13:12:26 -04001241 argumentIds.reserve(arguments.size());
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001242 for (size_t i = 0; i < arguments.size(); i++) {
John Stiles07367122021-09-08 13:12:26 -04001243 argumentIds.push_back(this->writeFunctionCallArgument(*arguments[i],
1244 function.parameters()[i]->modifiers(),
1245 &tempVars,
1246 out));
ethannicholasb3058bd2016-07-01 08:22:01 -07001247 }
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001248 SpvId result = this->nextId(nullptr);
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001249 this->writeOpCode(SpvOpFunctionCall, 4 + (int32_t) arguments.size(), out);
Ethan Nicholas30d30222020-09-11 12:27:26 -04001250 this->writeWord(this->getType(c.type()), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07001251 this->writeWord(result, out);
1252 this->writeWord(entry->second, out);
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001253 for (SpvId id : argumentIds) {
ethannicholasb3058bd2016-07-01 08:22:01 -07001254 this->writeWord(id, out);
1255 }
John Stilesec241542021-02-11 17:50:09 -05001256 // Now that the call is complete, we copy temp out-variables back to their real lvalues.
John Stiles07367122021-09-08 13:12:26 -04001257 this->copyBackTempVars(tempVars, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07001258 return result;
1259}
1260
John Stiles2938eea2021-04-01 18:58:25 -04001261SpvId SPIRVCodeGenerator::writeConstantVector(const AnyConstructor& c) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001262 const Type& type = c.type();
John Stiles9aeed132020-11-24 17:36:06 -05001263 SkASSERT(type.isVector() && c.isCompileTimeConstant());
John Stilescd806892021-01-06 13:33:31 -05001264
John Stiles9cfaa4f2021-01-06 17:52:00 -05001265 // Get each of the constructor components as SPIR-V constants.
John Stilescd806892021-01-06 13:33:31 -05001266 SPIRVVectorConstant key{this->getType(type),
1267 /*fValueId=*/{SpvId(-1), SpvId(-1), SpvId(-1), SpvId(-1)}};
John Stiles9cfaa4f2021-01-06 17:52:00 -05001268
John Stiles21a50ec2021-04-06 14:49:36 -04001269 for (int n = 0; n < type.columns(); n++) {
1270 const Expression* expr = c.getConstantSubexpression(n);
1271 if (!expr) {
1272 SkDEBUGFAILF("writeConstantVector: %s not actually constant", c.description().c_str());
1273 return (SpvId)-1;
John Stiles9cfaa4f2021-01-06 17:52:00 -05001274 }
John Stiles21a50ec2021-04-06 14:49:36 -04001275 key.fValueId[n] = this->writeExpression(*expr, fConstantBuffer);
ethannicholasb3058bd2016-07-01 08:22:01 -07001276 }
John Stilescd806892021-01-06 13:33:31 -05001277
1278 // Check to see if we've already synthesized this vector constant.
1279 auto [iter, newlyCreated] = fVectorConstants.insert({key, (SpvId)-1});
1280 if (newlyCreated) {
1281 // Emit an OpConstantComposite instruction for this constant.
Ethan Nicholas7f015882021-03-23 14:16:52 -04001282 SpvId result = this->nextId(&type);
John Stiles9cfaa4f2021-01-06 17:52:00 -05001283 this->writeOpCode(SpvOpConstantComposite, 3 + type.columns(), fConstantBuffer);
John Stilescd806892021-01-06 13:33:31 -05001284 this->writeWord(key.fTypeId, fConstantBuffer);
1285 this->writeWord(result, fConstantBuffer);
John Stiles9cfaa4f2021-01-06 17:52:00 -05001286 for (int i = 0; i < type.columns(); i++) {
John Stilescd806892021-01-06 13:33:31 -05001287 this->writeWord(key.fValueId[i], fConstantBuffer);
1288 }
1289 iter->second = result;
1290 }
1291 return iter->second;
ethannicholasb3058bd2016-07-01 08:22:01 -07001292}
1293
John Stilesb14a8192021-04-05 11:40:46 -04001294SpvId SPIRVCodeGenerator::castScalarToType(SpvId inputExprId,
1295 const Type& inputType,
1296 const Type& outputType,
1297 OutputStream& out) {
1298 if (outputType.isFloat()) {
1299 return this->castScalarToFloat(inputExprId, inputType, outputType, out);
1300 }
1301 if (outputType.isSigned()) {
1302 return this->castScalarToSignedInt(inputExprId, inputType, outputType, out);
1303 }
1304 if (outputType.isUnsigned()) {
1305 return this->castScalarToUnsignedInt(inputExprId, inputType, outputType, out);
1306 }
1307 if (outputType.isBoolean()) {
1308 return this->castScalarToBoolean(inputExprId, inputType, outputType, out);
1309 }
1310
Ethan Nicholas39f6da42021-08-23 13:10:07 -04001311 fContext.fErrors->error(-1, "unsupported cast: " + inputType.description() +
Ethan Nicholas3abc6c62021-08-13 11:20:09 -04001312 " to " + outputType.description());
John Stilesb14a8192021-04-05 11:40:46 -04001313 return inputExprId;
1314}
1315
John Stilesfd7252f2021-04-04 22:24:40 -04001316SpvId SPIRVCodeGenerator::writeFloatConstructor(const AnyConstructor& c, OutputStream& out) {
1317 SkASSERT(c.argumentSpan().size() == 1);
John Stilesd9d52712021-01-13 17:15:02 -05001318 SkASSERT(c.type().isFloat());
John Stilesfd7252f2021-04-04 22:24:40 -04001319 const Expression& ctorExpr = *c.argumentSpan().front();
John Stilesd9d52712021-01-13 17:15:02 -05001320 SpvId expressionId = this->writeExpression(ctorExpr, out);
1321 return this->castScalarToFloat(expressionId, ctorExpr.type(), c.type(), out);
1322}
1323
1324SpvId SPIRVCodeGenerator::castScalarToFloat(SpvId inputId, const Type& inputType,
1325 const Type& outputType, OutputStream& out) {
1326 // Casting a float to float is a no-op.
1327 if (inputType.isFloat()) {
1328 return inputId;
1329 }
1330
1331 // Given the input type, generate the appropriate instruction to cast to float.
Ethan Nicholas7f015882021-03-23 14:16:52 -04001332 SpvId result = this->nextId(&outputType);
John Stilesd9d52712021-01-13 17:15:02 -05001333 if (inputType.isBoolean()) {
John Stilesba4b0e92021-01-05 13:55:39 -05001334 // Use OpSelect to convert the boolean argument to a literal 1.0 or 0.0.
Ethan Nicholas89cfde12021-09-27 11:20:34 -04001335 Literal one(/*line=*/-1, /*value=*/1, fContext.fTypes.fFloat.get());
John Stiles7591d4b2021-09-13 13:32:06 -04001336 const SpvId oneID = this->writeLiteral(one);
Ethan Nicholas89cfde12021-09-27 11:20:34 -04001337 Literal zero(/*line=*/-1, /*value=*/0, fContext.fTypes.fFloat.get());
John Stiles7591d4b2021-09-13 13:32:06 -04001338 const SpvId zeroID = this->writeLiteral(zero);
John Stilesd9d52712021-01-13 17:15:02 -05001339 this->writeInstruction(SpvOpSelect, this->getType(outputType), result,
1340 inputId, oneID, zeroID, out);
1341 } else if (inputType.isSigned()) {
1342 this->writeInstruction(SpvOpConvertSToF, this->getType(outputType), result, inputId, out);
1343 } else if (inputType.isUnsigned()) {
1344 this->writeInstruction(SpvOpConvertUToF, this->getType(outputType), result, inputId, out);
Ethan Nicholasf7b88202017-09-18 14:10:39 -04001345 } else {
John Stilesd9d52712021-01-13 17:15:02 -05001346 SkDEBUGFAILF("unsupported type for float typecast: %s", inputType.description().c_str());
1347 return (SpvId)-1;
ethannicholasb3058bd2016-07-01 08:22:01 -07001348 }
1349 return result;
1350}
1351
John Stilesfd7252f2021-04-04 22:24:40 -04001352SpvId SPIRVCodeGenerator::writeIntConstructor(const AnyConstructor& c, OutputStream& out) {
1353 SkASSERT(c.argumentSpan().size() == 1);
John Stilesd9d52712021-01-13 17:15:02 -05001354 SkASSERT(c.type().isSigned());
John Stilesfd7252f2021-04-04 22:24:40 -04001355 const Expression& ctorExpr = *c.argumentSpan().front();
John Stilesd9d52712021-01-13 17:15:02 -05001356 SpvId expressionId = this->writeExpression(ctorExpr, out);
1357 return this->castScalarToSignedInt(expressionId, ctorExpr.type(), c.type(), out);
1358}
1359
1360SpvId SPIRVCodeGenerator::castScalarToSignedInt(SpvId inputId, const Type& inputType,
1361 const Type& outputType, OutputStream& out) {
1362 // Casting a signed int to signed int is a no-op.
1363 if (inputType.isSigned()) {
1364 return inputId;
1365 }
1366
1367 // Given the input type, generate the appropriate instruction to cast to signed int.
Ethan Nicholas7f015882021-03-23 14:16:52 -04001368 SpvId result = this->nextId(&outputType);
John Stilesd9d52712021-01-13 17:15:02 -05001369 if (inputType.isBoolean()) {
John Stilesba4b0e92021-01-05 13:55:39 -05001370 // Use OpSelect to convert the boolean argument to a literal 1 or 0.
Ethan Nicholas89cfde12021-09-27 11:20:34 -04001371 Literal one(/*line=*/-1, /*value=*/1, fContext.fTypes.fInt.get());
John Stiles7591d4b2021-09-13 13:32:06 -04001372 const SpvId oneID = this->writeLiteral(one);
Ethan Nicholas89cfde12021-09-27 11:20:34 -04001373 Literal zero(/*line=*/-1, /*value=*/0, fContext.fTypes.fInt.get());
John Stiles7591d4b2021-09-13 13:32:06 -04001374 const SpvId zeroID = this->writeLiteral(zero);
John Stilesd9d52712021-01-13 17:15:02 -05001375 this->writeInstruction(SpvOpSelect, this->getType(outputType), result,
1376 inputId, oneID, zeroID, out);
1377 } else if (inputType.isFloat()) {
1378 this->writeInstruction(SpvOpConvertFToS, this->getType(outputType), result, inputId, out);
1379 } else if (inputType.isUnsigned()) {
1380 this->writeInstruction(SpvOpBitcast, this->getType(outputType), result, inputId, out);
1381 } else {
1382 SkDEBUGFAILF("unsupported type for signed int typecast: %s",
1383 inputType.description().c_str());
1384 return (SpvId)-1;
ethannicholasb3058bd2016-07-01 08:22:01 -07001385 }
1386 return result;
1387}
1388
John Stilesfd7252f2021-04-04 22:24:40 -04001389SpvId SPIRVCodeGenerator::writeUIntConstructor(const AnyConstructor& c, OutputStream& out) {
1390 SkASSERT(c.argumentSpan().size() == 1);
John Stilesd9d52712021-01-13 17:15:02 -05001391 SkASSERT(c.type().isUnsigned());
John Stilesfd7252f2021-04-04 22:24:40 -04001392 const Expression& ctorExpr = *c.argumentSpan().front();
John Stilesd9d52712021-01-13 17:15:02 -05001393 SpvId expressionId = this->writeExpression(ctorExpr, out);
1394 return this->castScalarToUnsignedInt(expressionId, ctorExpr.type(), c.type(), out);
1395}
1396
1397SpvId SPIRVCodeGenerator::castScalarToUnsignedInt(SpvId inputId, const Type& inputType,
1398 const Type& outputType, OutputStream& out) {
1399 // Casting an unsigned int to unsigned int is a no-op.
1400 if (inputType.isUnsigned()) {
1401 return inputId;
1402 }
1403
John Stiles48c28842021-01-14 11:05:03 -05001404 // Given the input type, generate the appropriate instruction to cast to unsigned int.
Ethan Nicholas7f015882021-03-23 14:16:52 -04001405 SpvId result = this->nextId(&outputType);
John Stilesd9d52712021-01-13 17:15:02 -05001406 if (inputType.isBoolean()) {
John Stilesba4b0e92021-01-05 13:55:39 -05001407 // Use OpSelect to convert the boolean argument to a literal 1u or 0u.
Ethan Nicholas89cfde12021-09-27 11:20:34 -04001408 Literal one(/*line=*/-1, /*value=*/1, fContext.fTypes.fUInt.get());
John Stiles7591d4b2021-09-13 13:32:06 -04001409 const SpvId oneID = this->writeLiteral(one);
Ethan Nicholas89cfde12021-09-27 11:20:34 -04001410 Literal zero(/*line=*/-1, /*value=*/0, fContext.fTypes.fUInt.get());
John Stiles7591d4b2021-09-13 13:32:06 -04001411 const SpvId zeroID = this->writeLiteral(zero);
John Stilesd9d52712021-01-13 17:15:02 -05001412 this->writeInstruction(SpvOpSelect, this->getType(outputType), result,
1413 inputId, oneID, zeroID, out);
1414 } else if (inputType.isFloat()) {
1415 this->writeInstruction(SpvOpConvertFToU, this->getType(outputType), result, inputId, out);
1416 } else if (inputType.isSigned()) {
1417 this->writeInstruction(SpvOpBitcast, this->getType(outputType), result, inputId, out);
Ethan Nicholasf7b88202017-09-18 14:10:39 -04001418 } else {
John Stilesd9d52712021-01-13 17:15:02 -05001419 SkDEBUGFAILF("unsupported type for unsigned int typecast: %s",
1420 inputType.description().c_str());
1421 return (SpvId)-1;
Ethan Nicholas925f52d2017-07-19 10:42:50 -04001422 }
1423 return result;
1424}
1425
John Stilesfd7252f2021-04-04 22:24:40 -04001426SpvId SPIRVCodeGenerator::writeBooleanConstructor(const AnyConstructor& c, OutputStream& out) {
1427 SkASSERT(c.argumentSpan().size() == 1);
John Stilesa60fb172021-01-14 11:06:20 -05001428 SkASSERT(c.type().isBoolean());
John Stilesfd7252f2021-04-04 22:24:40 -04001429 const Expression& ctorExpr = *c.argumentSpan().front();
John Stilesa60fb172021-01-14 11:06:20 -05001430 SpvId expressionId = this->writeExpression(ctorExpr, out);
1431 return this->castScalarToBoolean(expressionId, ctorExpr.type(), c.type(), out);
1432}
1433
John Stiles48c28842021-01-14 11:05:03 -05001434SpvId SPIRVCodeGenerator::castScalarToBoolean(SpvId inputId, const Type& inputType,
1435 const Type& outputType, OutputStream& out) {
1436 // Casting a bool to bool is a no-op.
1437 if (inputType.isBoolean()) {
1438 return inputId;
1439 }
1440
1441 // Given the input type, generate the appropriate instruction to cast to bool.
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001442 SpvId result = this->nextId(nullptr);
John Stiles48c28842021-01-14 11:05:03 -05001443 if (inputType.isSigned()) {
1444 // Synthesize a boolean result by comparing the input against a signed zero literal.
Ethan Nicholas89cfde12021-09-27 11:20:34 -04001445 Literal zero(/*line=*/-1, /*value=*/0, fContext.fTypes.fInt.get());
John Stiles7591d4b2021-09-13 13:32:06 -04001446 const SpvId zeroID = this->writeLiteral(zero);
John Stiles48c28842021-01-14 11:05:03 -05001447 this->writeInstruction(SpvOpINotEqual, this->getType(outputType), result,
1448 inputId, zeroID, out);
1449 } else if (inputType.isUnsigned()) {
1450 // Synthesize a boolean result by comparing the input against an unsigned zero literal.
Ethan Nicholas89cfde12021-09-27 11:20:34 -04001451 Literal zero(/*line=*/-1, /*value=*/0, fContext.fTypes.fUInt.get());
John Stiles7591d4b2021-09-13 13:32:06 -04001452 const SpvId zeroID = this->writeLiteral(zero);
John Stiles48c28842021-01-14 11:05:03 -05001453 this->writeInstruction(SpvOpINotEqual, this->getType(outputType), result,
1454 inputId, zeroID, out);
1455 } else if (inputType.isFloat()) {
1456 // Synthesize a boolean result by comparing the input against a floating-point zero literal.
Ethan Nicholas89cfde12021-09-27 11:20:34 -04001457 Literal zero(/*line=*/-1, /*value=*/0, fContext.fTypes.fFloat.get());
John Stiles7591d4b2021-09-13 13:32:06 -04001458 const SpvId zeroID = this->writeLiteral(zero);
John Stiles48c28842021-01-14 11:05:03 -05001459 this->writeInstruction(SpvOpFUnordNotEqual, this->getType(outputType), result,
1460 inputId, zeroID, out);
1461 } else {
1462 SkDEBUGFAILF("unsupported type for boolean typecast: %s", inputType.description().c_str());
1463 return (SpvId)-1;
1464 }
1465 return result;
1466}
1467
Ethan Nicholas84645e32017-02-09 13:57:14 -05001468void SPIRVCodeGenerator::writeUniformScaleMatrix(SpvId id, SpvId diagonal, const Type& type,
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001469 OutputStream& out) {
Ethan Nicholas89cfde12021-09-27 11:20:34 -04001470 Literal zero(/*line=*/-1, /*value=*/0, fContext.fTypes.fFloat.get());
John Stiles7591d4b2021-09-13 13:32:06 -04001471 SpvId zeroId = this->writeLiteral(zero);
Ethan Nicholas84645e32017-02-09 13:57:14 -05001472 std::vector<SpvId> columnIds;
John Stiles392d8292021-04-09 12:14:03 -04001473 columnIds.reserve(type.columns());
Ethan Nicholas84645e32017-02-09 13:57:14 -05001474 for (int column = 0; column < type.columns(); column++) {
1475 this->writeOpCode(SpvOpCompositeConstruct, 3 + type.rows(),
1476 out);
John Stiles392d8292021-04-09 12:14:03 -04001477 this->writeWord(this->getType(type.componentType().toCompound(
1478 fContext, /*columns=*/type.rows(), /*rows=*/1)),
Ethan Nicholas84645e32017-02-09 13:57:14 -05001479 out);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001480 SpvId columnId = this->nextId(&type);
Ethan Nicholas84645e32017-02-09 13:57:14 -05001481 this->writeWord(columnId, out);
1482 columnIds.push_back(columnId);
John Stiles392d8292021-04-09 12:14:03 -04001483 for (int row = 0; row < type.rows(); row++) {
Ethan Nicholas84645e32017-02-09 13:57:14 -05001484 this->writeWord(row == column ? diagonal : zeroId, out);
1485 }
1486 }
1487 this->writeOpCode(SpvOpCompositeConstruct, 3 + type.columns(),
1488 out);
1489 this->writeWord(this->getType(type), out);
1490 this->writeWord(id, out);
John Stilesf621e232020-08-25 13:33:02 -04001491 for (SpvId columnId : columnIds) {
1492 this->writeWord(columnId, out);
Ethan Nicholas84645e32017-02-09 13:57:14 -05001493 }
1494}
1495
John Stiles268a73f2021-04-07 12:30:22 -04001496SpvId SPIRVCodeGenerator::writeMatrixCopy(SpvId src, const Type& srcType, const Type& dstType,
1497 OutputStream& out) {
John Stiles9aeed132020-11-24 17:36:06 -05001498 SkASSERT(srcType.isMatrix());
1499 SkASSERT(dstType.isMatrix());
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001500 SkASSERT(srcType.componentType() == dstType.componentType());
John Stiles268a73f2021-04-07 12:30:22 -04001501 SpvId id = this->nextId(&dstType);
Ethan Nicholasdc0e1c32017-07-21 13:23:34 -04001502 SpvId srcColumnType = this->getType(srcType.componentType().toCompound(fContext,
1503 srcType.rows(),
1504 1));
1505 SpvId dstColumnType = this->getType(dstType.componentType().toCompound(fContext,
1506 dstType.rows(),
1507 1));
John Stiles92671832021-04-06 09:24:55 -04001508 SkASSERT(dstType.componentType().isFloat());
Ethan Nicholas89cfde12021-09-27 11:20:34 -04001509 Literal zero(/*line=*/-1, /*value=*/0.0, &dstType.componentType());
John Stiles7591d4b2021-09-13 13:32:06 -04001510 const SpvId zeroId = this->writeLiteral(zero);
Ethan Nicholas89cfde12021-09-27 11:20:34 -04001511 Literal one(/*line=*/-1, /*value=*/1.0, &dstType.componentType());
John Stiles7591d4b2021-09-13 13:32:06 -04001512 const SpvId oneId = this->writeLiteral(one);
John Stiles92671832021-04-06 09:24:55 -04001513
Ethan Nicholasdc0e1c32017-07-21 13:23:34 -04001514 SpvId columns[4];
1515 for (int i = 0; i < dstType.columns(); i++) {
1516 if (i < srcType.columns()) {
1517 // we're still inside the src matrix, copy the column
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001518 SpvId srcColumn = this->nextId(&dstType);
Ethan Nicholasdc0e1c32017-07-21 13:23:34 -04001519 this->writeInstruction(SpvOpCompositeExtract, srcColumnType, srcColumn, src, i, out);
1520 SpvId dstColumn;
1521 if (srcType.rows() == dstType.rows()) {
1522 // columns are equal size, don't need to do anything
1523 dstColumn = srcColumn;
1524 }
1525 else if (dstType.rows() > srcType.rows()) {
1526 // dst column is bigger, need to zero-pad it
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001527 dstColumn = this->nextId(&dstType);
Ethan Nicholasdc0e1c32017-07-21 13:23:34 -04001528 int delta = dstType.rows() - srcType.rows();
1529 this->writeOpCode(SpvOpCompositeConstruct, 4 + delta, out);
1530 this->writeWord(dstColumnType, out);
1531 this->writeWord(dstColumn, out);
1532 this->writeWord(srcColumn, out);
John Stiles92671832021-04-06 09:24:55 -04001533 for (int j = srcType.rows(); j < dstType.rows(); ++j) {
1534 this->writeWord((i == j) ? oneId : zeroId, out);
Ethan Nicholasdc0e1c32017-07-21 13:23:34 -04001535 }
1536 }
1537 else {
1538 // dst column is smaller, need to swizzle the src column
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001539 dstColumn = this->nextId(&dstType);
John Stiles92671832021-04-06 09:24:55 -04001540 this->writeOpCode(SpvOpVectorShuffle, 5 + dstType.rows(), out);
Ethan Nicholasdc0e1c32017-07-21 13:23:34 -04001541 this->writeWord(dstColumnType, out);
1542 this->writeWord(dstColumn, out);
1543 this->writeWord(srcColumn, out);
1544 this->writeWord(srcColumn, out);
John Stiles92671832021-04-06 09:24:55 -04001545 for (int j = 0; j < dstType.rows(); j++) {
John Stilesf621e232020-08-25 13:33:02 -04001546 this->writeWord(j, out);
Ethan Nicholasdc0e1c32017-07-21 13:23:34 -04001547 }
1548 }
1549 columns[i] = dstColumn;
1550 } else {
John Stiles92671832021-04-06 09:24:55 -04001551 // we're past the end of the src matrix, need to synthesize an identity-matrix column
1552 SpvId identityColumn = this->nextId(&dstType);
1553 this->writeOpCode(SpvOpCompositeConstruct, 3 + dstType.rows(), out);
1554 this->writeWord(dstColumnType, out);
1555 this->writeWord(identityColumn, out);
1556 for (int j = 0; j < dstType.rows(); ++j) {
1557 this->writeWord((i == j) ? oneId : zeroId, out);
Ethan Nicholasdc0e1c32017-07-21 13:23:34 -04001558 }
John Stiles92671832021-04-06 09:24:55 -04001559 columns[i] = identityColumn;
Ethan Nicholasdc0e1c32017-07-21 13:23:34 -04001560 }
1561 }
1562 this->writeOpCode(SpvOpCompositeConstruct, 3 + dstType.columns(), out);
1563 this->writeWord(this->getType(dstType), out);
1564 this->writeWord(id, out);
1565 for (int i = 0; i < dstType.columns(); i++) {
1566 this->writeWord(columns[i], out);
1567 }
John Stiles268a73f2021-04-07 12:30:22 -04001568 return id;
Ethan Nicholas84645e32017-02-09 13:57:14 -05001569}
1570
John Stilesbeb2fbf2021-07-08 18:54:39 -04001571void SPIRVCodeGenerator::addColumnEntry(const Type& columnType,
Ethan Nicholascc5d3e02019-04-19 09:50:56 -04001572 std::vector<SpvId>* currentColumn,
Ethan Nicholas5c46b722019-03-22 14:32:37 -04001573 std::vector<SpvId>* columnIds,
John Stilesbeb2fbf2021-07-08 18:54:39 -04001574 int rows,
1575 SpvId entry,
Ethan Nicholas5c46b722019-03-22 14:32:37 -04001576 OutputStream& out) {
John Stilesbeb2fbf2021-07-08 18:54:39 -04001577 SkASSERT((int)currentColumn->size() < rows);
Ethan Nicholas5c46b722019-03-22 14:32:37 -04001578 currentColumn->push_back(entry);
John Stilesbeb2fbf2021-07-08 18:54:39 -04001579 if ((int)currentColumn->size() == rows) {
1580 // Synthesize this column into a vector.
1581 SpvId columnId = this->writeComposite(*currentColumn, columnType, out);
Ethan Nicholas5c46b722019-03-22 14:32:37 -04001582 columnIds->push_back(columnId);
Ethan Nicholas5c46b722019-03-22 14:32:37 -04001583 currentColumn->clear();
1584 }
1585}
1586
John Stiles8cad6372021-04-07 12:31:13 -04001587SpvId SPIRVCodeGenerator::writeMatrixConstructor(const ConstructorCompound& c, OutputStream& out) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001588 const Type& type = c.type();
John Stiles9aeed132020-11-24 17:36:06 -05001589 SkASSERT(type.isMatrix());
John Stiles2bec8ab2021-04-06 18:40:04 -04001590 SkASSERT(!c.arguments().empty());
Ethan Nicholasf70f0442020-09-29 12:41:35 -04001591 const Type& arg0Type = c.arguments()[0]->type();
ethannicholasb3058bd2016-07-01 08:22:01 -07001592 // go ahead and write the arguments so we don't try to write new instructions in the middle of
1593 // an instruction
1594 std::vector<SpvId> arguments;
John Stiles2bec8ab2021-04-06 18:40:04 -04001595 arguments.reserve(c.arguments().size());
1596 for (const std::unique_ptr<Expression>& arg : c.arguments()) {
1597 arguments.push_back(this->writeExpression(*arg, out));
ethannicholasb3058bd2016-07-01 08:22:01 -07001598 }
John Stilesbeb2fbf2021-07-08 18:54:39 -04001599
John Stiles268a73f2021-04-07 12:30:22 -04001600 if (arguments.size() == 1 && arg0Type.isVector()) {
1601 // Special-case handling of float4 -> mat2x2.
Ethan Nicholas30d30222020-09-11 12:27:26 -04001602 SkASSERT(type.rows() == 2 && type.columns() == 2);
1603 SkASSERT(arg0Type.columns() == 4);
1604 SpvId componentType = this->getType(type.componentType());
Ethan Nicholasdc0e1c32017-07-21 13:23:34 -04001605 SpvId v[4];
1606 for (int i = 0; i < 4; ++i) {
Ethan Nicholas7f015882021-03-23 14:16:52 -04001607 v[i] = this->nextId(&type);
Ethan Nicholas30d30222020-09-11 12:27:26 -04001608 this->writeInstruction(SpvOpCompositeExtract, componentType, v[i], arguments[0], i,
1609 out);
Ethan Nicholasdc0e1c32017-07-21 13:23:34 -04001610 }
John Stilesbeb2fbf2021-07-08 18:54:39 -04001611 const Type& vecType = type.componentType().toCompound(fContext, /*columns=*/2, /*rows=*/1);
1612 SpvId v0v1 = this->writeComposite({v[0], v[1]}, vecType, out);
1613 SpvId v2v3 = this->writeComposite({v[2], v[3]}, vecType, out);
1614 return this->writeComposite({v0v1, v2v3}, type, out);
1615 }
1616
1617 int rows = type.rows();
1618 const Type& columnType = type.componentType().toCompound(fContext,
1619 /*columns=*/rows, /*rows=*/1);
1620 // SpvIds of completed columns of the matrix.
1621 std::vector<SpvId> columnIds;
1622 // SpvIds of scalars we have written to the current column so far.
1623 std::vector<SpvId> currentColumn;
1624 for (size_t i = 0; i < arguments.size(); i++) {
1625 const Type& argType = c.arguments()[i]->type();
1626 if (currentColumn.empty() && argType.isVector() && argType.columns() == rows) {
1627 // This vector is a complete matrix column by itself and can be used as-is.
1628 columnIds.push_back(arguments[i]);
1629 } else if (argType.columns() == 1) {
1630 // This argument is a lone scalar and can be added to the current column as-is.
1631 this->addColumnEntry(columnType, &currentColumn, &columnIds, rows, arguments[i], out);
1632 } else {
1633 // This argument needs to be decomposed into its constituent scalars.
1634 SpvId componentType = this->getType(argType.componentType());
1635 for (int j = 0; j < argType.columns(); ++j) {
1636 SpvId swizzle = this->nextId(&argType);
1637 this->writeInstruction(SpvOpCompositeExtract, componentType, swizzle,
1638 arguments[i], j, out);
1639 this->addColumnEntry(columnType, &currentColumn, &columnIds, rows, swizzle, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07001640 }
1641 }
ethannicholasb3058bd2016-07-01 08:22:01 -07001642 }
John Stilesbeb2fbf2021-07-08 18:54:39 -04001643 SkASSERT(columnIds.size() == (size_t) type.columns());
1644 return this->writeComposite(columnIds, type, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07001645}
1646
John Stiles8cad6372021-04-07 12:31:13 -04001647SpvId SPIRVCodeGenerator::writeConstructorCompound(const ConstructorCompound& c,
1648 OutputStream& out) {
John Stiles2bec8ab2021-04-06 18:40:04 -04001649 return c.type().isMatrix() ? this->writeMatrixConstructor(c, out)
1650 : this->writeVectorConstructor(c, out);
1651}
1652
John Stiles8cad6372021-04-07 12:31:13 -04001653SpvId SPIRVCodeGenerator::writeVectorConstructor(const ConstructorCompound& c, OutputStream& out) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001654 const Type& type = c.type();
John Stilesd986f472021-04-06 15:54:43 -04001655 const Type& componentType = type.componentType();
John Stiles9aeed132020-11-24 17:36:06 -05001656 SkASSERT(type.isVector());
John Stilesd986f472021-04-06 15:54:43 -04001657
1658 if (c.isCompileTimeConstant()) {
ethannicholasb3058bd2016-07-01 08:22:01 -07001659 return this->writeConstantVector(c);
1660 }
John Stilesd986f472021-04-06 15:54:43 -04001661
ethannicholasb3058bd2016-07-01 08:22:01 -07001662 std::vector<SpvId> arguments;
John Stiles6de2e1d2021-07-09 12:41:55 -04001663 arguments.reserve(c.arguments().size());
Ethan Nicholasf70f0442020-09-29 12:41:35 -04001664 for (size_t i = 0; i < c.arguments().size(); i++) {
1665 const Type& argType = c.arguments()[i]->type();
John Stilesd986f472021-04-06 15:54:43 -04001666 SkASSERT(componentType == argType.componentType());
John Stiles48c28842021-01-14 11:05:03 -05001667
John Stiles6de2e1d2021-07-09 12:41:55 -04001668 SpvId arg = this->writeExpression(*c.arguments()[i], out);
1669 if (argType.isMatrix()) {
1670 // CompositeConstruct cannot take a 2x2 matrix as an input, so we need to extract out
1671 // each scalar separately.
1672 SkASSERT(argType.rows() == 2);
1673 SkASSERT(argType.columns() == 2);
1674 for (int j = 0; j < 4; ++j) {
1675 SpvId componentId = this->nextId(&componentType);
1676 this->writeInstruction(SpvOpCompositeExtract, this->getType(componentType),
1677 componentId, arg, j / 2, j % 2, out);
1678 arguments.push_back(componentId);
1679 }
1680 } else if (argType.isVector()) {
John Stilesd986f472021-04-06 15:54:43 -04001681 // There's a bug in the Intel Vulkan driver where OpCompositeConstruct doesn't handle
1682 // vector arguments at all, so we always extract each vector component and pass them
1683 // into OpCompositeConstruct individually.
Ethan Nicholas30d30222020-09-11 12:27:26 -04001684 for (int j = 0; j < argType.columns(); j++) {
John Stilesd986f472021-04-06 15:54:43 -04001685 SpvId componentId = this->nextId(&componentType);
1686 this->writeInstruction(SpvOpCompositeExtract, this->getType(componentType),
John Stiles6de2e1d2021-07-09 12:41:55 -04001687 componentId, arg, j, out);
John Stilesd986f472021-04-06 15:54:43 -04001688 arguments.push_back(componentId);
Ethan Nicholas26a8d902018-01-29 09:25:51 -05001689 }
Ethan Nicholas11e5bff2018-01-29 11:08:38 -05001690 } else {
John Stiles6de2e1d2021-07-09 12:41:55 -04001691 arguments.push_back(arg);
Ethan Nicholas26a8d902018-01-29 09:25:51 -05001692 }
ethannicholasb3058bd2016-07-01 08:22:01 -07001693 }
John Stilesb14a8192021-04-05 11:40:46 -04001694
1695 return this->writeComposite(arguments, type, out);
1696}
1697
1698SpvId SPIRVCodeGenerator::writeComposite(const std::vector<SpvId>& arguments,
1699 const Type& type,
1700 OutputStream& out) {
John Stilesd47330f2021-04-08 23:25:52 -04001701 SkASSERT(arguments.size() == (type.isStruct() ? type.fields().size() : (size_t)type.columns()));
John Stiles2938eea2021-04-01 18:58:25 -04001702
Ethan Nicholas7f015882021-03-23 14:16:52 -04001703 SpvId result = this->nextId(&type);
John Stiles2938eea2021-04-01 18:58:25 -04001704 this->writeOpCode(SpvOpCompositeConstruct, 3 + (int32_t) arguments.size(), out);
1705 this->writeWord(this->getType(type), out);
1706 this->writeWord(result, out);
1707 for (SpvId id : arguments) {
1708 this->writeWord(id, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07001709 }
1710 return result;
1711}
1712
John Stiles2938eea2021-04-01 18:58:25 -04001713SpvId SPIRVCodeGenerator::writeConstructorSplat(const ConstructorSplat& c, OutputStream& out) {
1714 // Use writeConstantVector to deduplicate constant splats.
1715 if (c.isCompileTimeConstant()) {
1716 return this->writeConstantVector(c);
1717 }
1718
1719 // Write the splat argument.
1720 SpvId argument = this->writeExpression(*c.argument(), out);
1721
1722 // Generate a OpCompositeConstruct which repeats the argument N times.
John Stilesb14a8192021-04-05 11:40:46 -04001723 std::vector<SpvId> arguments(/*count*/ c.type().columns(), /*value*/ argument);
1724 return this->writeComposite(arguments, c.type(), out);
John Stiles2938eea2021-04-01 18:58:25 -04001725}
1726
1727
John Stilesd47330f2021-04-08 23:25:52 -04001728SpvId SPIRVCodeGenerator::writeCompositeConstructor(const AnyConstructor& c, OutputStream& out) {
1729 SkASSERT(c.type().isArray() || c.type().isStruct());
1730 auto ctorArgs = c.argumentSpan();
1731
Ethan Nicholasbd553222017-07-18 15:54:59 -04001732 std::vector<SpvId> arguments;
John Stilesd47330f2021-04-08 23:25:52 -04001733 arguments.reserve(ctorArgs.size());
1734 for (const std::unique_ptr<Expression>& arg : ctorArgs) {
1735 arguments.push_back(this->writeExpression(*arg, out));
Ethan Nicholasbd553222017-07-18 15:54:59 -04001736 }
John Stilesd47330f2021-04-08 23:25:52 -04001737
1738 return this->writeComposite(arguments, c.type(), out);
Ethan Nicholasbd553222017-07-18 15:54:59 -04001739}
1740
John Stilesfd7252f2021-04-04 22:24:40 -04001741SpvId SPIRVCodeGenerator::writeConstructorScalarCast(const ConstructorScalarCast& c,
1742 OutputStream& out) {
1743 const Type& type = c.type();
1744 if (this->getActualType(type) == this->getActualType(c.argument()->type())) {
1745 return this->writeExpression(*c.argument(), out);
1746 }
John Stilesb14a8192021-04-05 11:40:46 -04001747
1748 const Expression& ctorExpr = *c.argument();
1749 SpvId expressionId = this->writeExpression(ctorExpr, out);
1750 return this->castScalarToType(expressionId, ctorExpr.type(), type, out);
1751}
1752
John Stiles8cad6372021-04-07 12:31:13 -04001753SpvId SPIRVCodeGenerator::writeConstructorCompoundCast(const ConstructorCompoundCast& c,
1754 OutputStream& out) {
John Stilesb14a8192021-04-05 11:40:46 -04001755 const Type& ctorType = c.type();
1756 const Type& argType = c.argument()->type();
John Stiles268a73f2021-04-07 12:30:22 -04001757 SkASSERT(ctorType.isVector() || ctorType.isMatrix());
John Stilesb14a8192021-04-05 11:40:46 -04001758
John Stiles268a73f2021-04-07 12:30:22 -04001759 // Write the composite that we are casting. If the actual type matches, we are done.
1760 SpvId compositeId = this->writeExpression(*c.argument(), out);
John Stilesb14a8192021-04-05 11:40:46 -04001761 if (this->getActualType(ctorType) == this->getActualType(argType)) {
John Stiles268a73f2021-04-07 12:30:22 -04001762 return compositeId;
1763 }
1764
1765 // writeMatrixCopy can cast matrices to a different type.
1766 if (ctorType.isMatrix()) {
1767 return this->writeMatrixCopy(compositeId, argType, ctorType, out);
John Stilesfd7252f2021-04-04 22:24:40 -04001768 }
John Stilesb14a8192021-04-05 11:40:46 -04001769
1770 // SPIR-V doesn't support vector(vector-of-different-type) directly, so we need to extract the
John Stilesd986f472021-04-06 15:54:43 -04001771 // components and convert each one manually.
John Stilesb14a8192021-04-05 11:40:46 -04001772 const Type& srcType = argType.componentType();
1773 const Type& dstType = ctorType.componentType();
1774
1775 std::vector<SpvId> arguments;
John Stiles268a73f2021-04-07 12:30:22 -04001776 arguments.reserve(argType.columns());
John Stilesb14a8192021-04-05 11:40:46 -04001777 for (int index = 0; index < argType.columns(); ++index) {
1778 SpvId componentId = this->nextId(&srcType);
1779 this->writeInstruction(SpvOpCompositeExtract, this->getType(srcType), componentId,
John Stiles268a73f2021-04-07 12:30:22 -04001780 compositeId, index, out);
John Stilesb14a8192021-04-05 11:40:46 -04001781 arguments.push_back(this->castScalarToType(componentId, srcType, dstType, out));
John Stilesfd7252f2021-04-04 22:24:40 -04001782 }
John Stilesb14a8192021-04-05 11:40:46 -04001783
1784 return this->writeComposite(arguments, ctorType, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07001785}
1786
John Stilese1182782021-03-30 22:09:37 -04001787SpvId SPIRVCodeGenerator::writeConstructorDiagonalMatrix(const ConstructorDiagonalMatrix& c,
1788 OutputStream& out) {
1789 const Type& type = c.type();
1790 SkASSERT(type.isMatrix());
1791 SkASSERT(c.argument()->type().isScalar());
1792
1793 // Write out the scalar argument.
1794 SpvId argument = this->writeExpression(*c.argument(), out);
1795
1796 // Build the diagonal matrix.
1797 SpvId result = this->nextId(&type);
1798 this->writeUniformScaleMatrix(result, argument, type, out);
1799 return result;
1800}
1801
John Stiles5abb9e12021-04-06 13:47:19 -04001802SpvId SPIRVCodeGenerator::writeConstructorMatrixResize(const ConstructorMatrixResize& c,
1803 OutputStream& out) {
1804 // Write the input matrix.
1805 SpvId argument = this->writeExpression(*c.argument(), out);
1806
1807 // Use matrix-copy to resize the input matrix to its new size.
John Stiles268a73f2021-04-07 12:30:22 -04001808 return this->writeMatrixCopy(argument, c.argument()->type(), c.type(), out);
John Stiles5abb9e12021-04-06 13:47:19 -04001809}
1810
John Stiles9485b552021-01-27 11:47:00 -05001811static SpvStorageClass_ get_storage_class(const Variable& var,
1812 SpvStorageClass_ fallbackStorageClass) {
1813 const Modifiers& modifiers = var.modifiers();
ethannicholasb3058bd2016-07-01 08:22:01 -07001814 if (modifiers.fFlags & Modifiers::kIn_Flag) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001815 SkASSERT(!(modifiers.fLayout.fFlags & Layout::kPushConstant_Flag));
ethannicholasb3058bd2016-07-01 08:22:01 -07001816 return SpvStorageClassInput;
John Stiles9485b552021-01-27 11:47:00 -05001817 }
1818 if (modifiers.fFlags & Modifiers::kOut_Flag) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001819 SkASSERT(!(modifiers.fLayout.fFlags & Layout::kPushConstant_Flag));
ethannicholasb3058bd2016-07-01 08:22:01 -07001820 return SpvStorageClassOutput;
John Stiles9485b552021-01-27 11:47:00 -05001821 }
1822 if (modifiers.fFlags & Modifiers::kUniform_Flag) {
Ethan Nicholas39204fd2017-11-27 13:12:30 -05001823 if (modifiers.fLayout.fFlags & Layout::kPushConstant_Flag) {
ethannicholas8ac838d2016-11-22 08:39:36 -08001824 return SpvStorageClassPushConstant;
1825 }
John Stiles9485b552021-01-27 11:47:00 -05001826 if (var.type().typeKind() == Type::TypeKind::kSampler ||
1827 var.type().typeKind() == Type::TypeKind::kSeparateSampler ||
1828 var.type().typeKind() == Type::TypeKind::kTexture) {
1829 return SpvStorageClassUniformConstant;
1830 }
ethannicholasb3058bd2016-07-01 08:22:01 -07001831 return SpvStorageClassUniform;
ethannicholasb3058bd2016-07-01 08:22:01 -07001832 }
John Stiles9485b552021-01-27 11:47:00 -05001833 return fallbackStorageClass;
ethannicholasb3058bd2016-07-01 08:22:01 -07001834}
1835
John Stiles9485b552021-01-27 11:47:00 -05001836static SpvStorageClass_ get_storage_class(const Expression& expr) {
Ethan Nicholase6592142020-09-08 10:22:09 -04001837 switch (expr.kind()) {
1838 case Expression::Kind::kVariableReference: {
Ethan Nicholas78686922020-10-08 06:46:27 -04001839 const Variable& var = *expr.as<VariableReference>().variable();
Ethan Nicholas453f67f2020-10-09 10:43:45 -04001840 if (var.storage() != Variable::Storage::kGlobal) {
Ethan Nicholasc6f5e102017-03-31 14:53:17 -04001841 return SpvStorageClassFunction;
1842 }
John Stiles9485b552021-01-27 11:47:00 -05001843 return get_storage_class(var, SpvStorageClassPrivate);
Ethan Nicholasc6f5e102017-03-31 14:53:17 -04001844 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001845 case Expression::Kind::kFieldAccess:
Ethan Nicholas7a95b202020-10-09 11:55:40 -04001846 return get_storage_class(*expr.as<FieldAccess>().base());
Ethan Nicholase6592142020-09-08 10:22:09 -04001847 case Expression::Kind::kIndex:
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04001848 return get_storage_class(*expr.as<IndexExpression>().base());
ethannicholasb3058bd2016-07-01 08:22:01 -07001849 default:
1850 return SpvStorageClassFunction;
1851 }
1852}
1853
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001854std::vector<SpvId> SPIRVCodeGenerator::getAccessChain(const Expression& expr, OutputStream& out) {
ethannicholasb3058bd2016-07-01 08:22:01 -07001855 std::vector<SpvId> chain;
Ethan Nicholase6592142020-09-08 10:22:09 -04001856 switch (expr.kind()) {
1857 case Expression::Kind::kIndex: {
John Stiles0693fb82021-01-22 18:27:52 -05001858 const IndexExpression& indexExpr = expr.as<IndexExpression>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04001859 chain = this->getAccessChain(*indexExpr.base(), out);
1860 chain.push_back(this->writeExpression(*indexExpr.index(), out));
ethannicholasb3058bd2016-07-01 08:22:01 -07001861 break;
1862 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001863 case Expression::Kind::kFieldAccess: {
John Stiles0693fb82021-01-22 18:27:52 -05001864 const FieldAccess& fieldExpr = expr.as<FieldAccess>();
Ethan Nicholas7a95b202020-10-09 11:55:40 -04001865 chain = this->getAccessChain(*fieldExpr.base(), out);
Ethan Nicholas89cfde12021-09-27 11:20:34 -04001866 Literal index(/*line=*/-1, fieldExpr.fieldIndex(), fContext.fTypes.fInt.get());
John Stiles7591d4b2021-09-13 13:32:06 -04001867 chain.push_back(this->writeLiteral(index));
ethannicholasb3058bd2016-07-01 08:22:01 -07001868 break;
1869 }
Ethan Nicholasa9a06902019-01-07 14:42:40 -05001870 default: {
1871 SpvId id = this->getLValue(expr, out)->getPointer();
John Stiles3f14d282021-02-05 09:31:04 -05001872 SkASSERT(id != (SpvId) -1);
Ethan Nicholasa9a06902019-01-07 14:42:40 -05001873 chain.push_back(id);
Ethan Nicholasb13f3692021-09-10 16:49:42 -04001874 break;
Ethan Nicholasa9a06902019-01-07 14:42:40 -05001875 }
ethannicholasb3058bd2016-07-01 08:22:01 -07001876 }
1877 return chain;
1878}
1879
1880class PointerLValue : public SPIRVCodeGenerator::LValue {
1881public:
Ethan Nicholase0707b72021-03-17 11:16:41 -04001882 PointerLValue(SPIRVCodeGenerator& gen, SpvId pointer, bool isMemoryObject, SpvId type,
Ethan Nicholas10e93b62019-03-20 10:46:14 -04001883 SPIRVCodeGenerator::Precision precision)
ethannicholasb3058bd2016-07-01 08:22:01 -07001884 : fGen(gen)
1885 , fPointer(pointer)
Ethan Nicholase0707b72021-03-17 11:16:41 -04001886 , fIsMemoryObject(isMemoryObject)
Ethan Nicholas10e93b62019-03-20 10:46:14 -04001887 , fType(type)
1888 , fPrecision(precision) {}
ethannicholasb3058bd2016-07-01 08:22:01 -07001889
John Stiles1cf2c8d2020-08-13 22:58:04 -04001890 SpvId getPointer() override {
ethannicholasb3058bd2016-07-01 08:22:01 -07001891 return fPointer;
1892 }
1893
Ethan Nicholase0707b72021-03-17 11:16:41 -04001894 bool isMemoryObjectPointer() const override {
1895 return fIsMemoryObject;
1896 }
1897
John Stiles1cf2c8d2020-08-13 22:58:04 -04001898 SpvId load(OutputStream& out) override {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001899 SpvId result = fGen.nextId(fPrecision);
ethannicholasb3058bd2016-07-01 08:22:01 -07001900 fGen.writeInstruction(SpvOpLoad, fType, result, fPointer, out);
1901 return result;
1902 }
1903
John Stiles1cf2c8d2020-08-13 22:58:04 -04001904 void store(SpvId value, OutputStream& out) override {
ethannicholasb3058bd2016-07-01 08:22:01 -07001905 fGen.writeInstruction(SpvOpStore, fPointer, value, out);
1906 }
1907
1908private:
1909 SPIRVCodeGenerator& fGen;
1910 const SpvId fPointer;
Ethan Nicholase0707b72021-03-17 11:16:41 -04001911 const bool fIsMemoryObject;
ethannicholasb3058bd2016-07-01 08:22:01 -07001912 const SpvId fType;
Ethan Nicholas10e93b62019-03-20 10:46:14 -04001913 const SPIRVCodeGenerator::Precision fPrecision;
ethannicholasb3058bd2016-07-01 08:22:01 -07001914};
1915
1916class SwizzleLValue : public SPIRVCodeGenerator::LValue {
1917public:
John Stiles750109b2020-10-30 13:45:46 -04001918 SwizzleLValue(SPIRVCodeGenerator& gen, SpvId vecPointer, const ComponentArray& components,
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001919 const Type& baseType, const Type& swizzleType)
ethannicholasb3058bd2016-07-01 08:22:01 -07001920 : fGen(gen)
1921 , fVecPointer(vecPointer)
1922 , fComponents(components)
John Stiles3f14d282021-02-05 09:31:04 -05001923 , fBaseType(&baseType)
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001924 , fSwizzleType(&swizzleType) {}
ethannicholasb3058bd2016-07-01 08:22:01 -07001925
John Stiles3f14d282021-02-05 09:31:04 -05001926 bool applySwizzle(const ComponentArray& components, const Type& newType) override {
1927 ComponentArray updatedSwizzle;
1928 for (int8_t component : components) {
1929 if (component < 0 || component >= fComponents.count()) {
1930 SkDEBUGFAILF("swizzle accessed nonexistent component %d", (int)component);
1931 return false;
1932 }
1933 updatedSwizzle.push_back(fComponents[component]);
1934 }
1935 fComponents = updatedSwizzle;
1936 fSwizzleType = &newType;
1937 return true;
ethannicholasb3058bd2016-07-01 08:22:01 -07001938 }
1939
John Stiles1cf2c8d2020-08-13 22:58:04 -04001940 SpvId load(OutputStream& out) override {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001941 SpvId base = fGen.nextId(fBaseType);
John Stiles3f14d282021-02-05 09:31:04 -05001942 fGen.writeInstruction(SpvOpLoad, fGen.getType(*fBaseType), base, fVecPointer, out);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001943 SpvId result = fGen.nextId(fBaseType);
ethannicholasb3058bd2016-07-01 08:22:01 -07001944 fGen.writeOpCode(SpvOpVectorShuffle, 5 + (int32_t) fComponents.size(), out);
John Stiles3f14d282021-02-05 09:31:04 -05001945 fGen.writeWord(fGen.getType(*fSwizzleType), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07001946 fGen.writeWord(result, out);
1947 fGen.writeWord(base, out);
1948 fGen.writeWord(base, out);
1949 for (int component : fComponents) {
1950 fGen.writeWord(component, out);
1951 }
1952 return result;
1953 }
1954
John Stiles1cf2c8d2020-08-13 22:58:04 -04001955 void store(SpvId value, OutputStream& out) override {
ethannicholasb3058bd2016-07-01 08:22:01 -07001956 // use OpVectorShuffle to mix and match the vector components. We effectively create
1957 // a virtual vector out of the concatenation of the left and right vectors, and then
Greg Daniel64773e62016-11-22 09:44:03 -05001958 // select components from this virtual vector to make the result vector. For
ethannicholasb3058bd2016-07-01 08:22:01 -07001959 // instance, given:
Ethan Nicholas5af9ea32017-07-28 15:19:46 -04001960 // float3L = ...;
1961 // float3R = ...;
ethannicholasb3058bd2016-07-01 08:22:01 -07001962 // L.xz = R.xy;
Greg Daniel64773e62016-11-22 09:44:03 -05001963 // we end up with the virtual vector (L.x, L.y, L.z, R.x, R.y, R.z). Then we want
ethannicholasb3058bd2016-07-01 08:22:01 -07001964 // our result vector to look like (R.x, L.y, R.y), so we need to select indices
1965 // (3, 1, 4).
Ethan Nicholas7f015882021-03-23 14:16:52 -04001966 SpvId base = fGen.nextId(fBaseType);
John Stiles3f14d282021-02-05 09:31:04 -05001967 fGen.writeInstruction(SpvOpLoad, fGen.getType(*fBaseType), base, fVecPointer, out);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001968 SpvId shuffle = fGen.nextId(fBaseType);
John Stiles3f14d282021-02-05 09:31:04 -05001969 fGen.writeOpCode(SpvOpVectorShuffle, 5 + fBaseType->columns(), out);
1970 fGen.writeWord(fGen.getType(*fBaseType), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07001971 fGen.writeWord(shuffle, out);
1972 fGen.writeWord(base, out);
1973 fGen.writeWord(value, out);
John Stiles3f14d282021-02-05 09:31:04 -05001974 for (int i = 0; i < fBaseType->columns(); i++) {
ethannicholasb3058bd2016-07-01 08:22:01 -07001975 // current offset into the virtual vector, defaults to pulling the unmodified
1976 // value from the left side
1977 int offset = i;
1978 // check to see if we are writing this component
1979 for (size_t j = 0; j < fComponents.size(); j++) {
1980 if (fComponents[j] == i) {
Greg Daniel64773e62016-11-22 09:44:03 -05001981 // we're writing to this component, so adjust the offset to pull from
ethannicholasb3058bd2016-07-01 08:22:01 -07001982 // the correct component of the right side instead of preserving the
1983 // value from the left
John Stiles3f14d282021-02-05 09:31:04 -05001984 offset = (int) (j + fBaseType->columns());
ethannicholasb3058bd2016-07-01 08:22:01 -07001985 break;
1986 }
1987 }
1988 fGen.writeWord(offset, out);
1989 }
1990 fGen.writeInstruction(SpvOpStore, fVecPointer, shuffle, out);
1991 }
1992
1993private:
1994 SPIRVCodeGenerator& fGen;
1995 const SpvId fVecPointer;
John Stiles3f14d282021-02-05 09:31:04 -05001996 ComponentArray fComponents;
1997 const Type* fBaseType;
1998 const Type* fSwizzleType;
ethannicholasb3058bd2016-07-01 08:22:01 -07001999};
2000
John Stilese40d1662021-01-29 10:08:50 -05002001int SPIRVCodeGenerator::findUniformFieldIndex(const Variable& var) const {
2002 auto iter = fTopLevelUniformMap.find(&var);
2003 return (iter != fTopLevelUniformMap.end()) ? iter->second : -1;
2004}
2005
Greg Daniel64773e62016-11-22 09:44:03 -05002006std::unique_ptr<SPIRVCodeGenerator::LValue> SPIRVCodeGenerator::getLValue(const Expression& expr,
Ethan Nicholas0df1b042017-03-31 13:56:23 -04002007 OutputStream& out) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04002008 const Type& type = expr.type();
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002009 Precision precision = type.highPrecision() ? Precision::kDefault : Precision::kRelaxed;
Ethan Nicholase6592142020-09-08 10:22:09 -04002010 switch (expr.kind()) {
2011 case Expression::Kind::kVariableReference: {
John Stiles0de76f72021-01-29 09:19:39 -05002012 const Variable& var = *expr.as<VariableReference>().variable();
John Stilese40d1662021-01-29 10:08:50 -05002013 int uniformIdx = this->findUniformFieldIndex(var);
2014 if (uniformIdx >= 0) {
Ethan Nicholas89cfde12021-09-27 11:20:34 -04002015 Literal uniformIdxLiteral{/*line=*/-1, (double)uniformIdx,
John Stiles7591d4b2021-09-13 13:32:06 -04002016 fContext.fTypes.fInt.get()};
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002017 SpvId memberId = this->nextId(nullptr);
John Stilese40d1662021-01-29 10:08:50 -05002018 SpvId typeId = this->getPointerType(type, SpvStorageClassUniform);
John Stiles7591d4b2021-09-13 13:32:06 -04002019 SpvId uniformIdxId = this->writeLiteral(uniformIdxLiteral);
John Stilese40d1662021-01-29 10:08:50 -05002020 this->writeInstruction(SpvOpAccessChain, typeId, memberId, fUniformBufferId,
2021 uniformIdxId, out);
Ethan Nicholase0707b72021-03-17 11:16:41 -04002022 return std::make_unique<PointerLValue>(*this, memberId,
2023 /*isMemoryObjectPointer=*/true,
2024 this->getType(type), precision);
John Stilese40d1662021-01-29 10:08:50 -05002025 }
Brian Osman99ddd2a2021-08-27 11:21:12 -04002026 SpvId typeId = this->getType(type, this->memoryLayoutForVariable(var));
ethannicholasd598f792016-07-25 10:08:54 -07002027 auto entry = fVariableMap.find(&var);
John Stiles9078a892021-08-18 15:03:17 -04002028 SkASSERTF(entry != fVariableMap.end(), "%s", expr.description().c_str());
Ethan Nicholase0707b72021-03-17 11:16:41 -04002029 return std::make_unique<PointerLValue>(*this, entry->second,
2030 /*isMemoryObjectPointer=*/true,
2031 typeId, precision);
ethannicholasb3058bd2016-07-01 08:22:01 -07002032 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002033 case Expression::Kind::kIndex: // fall through
2034 case Expression::Kind::kFieldAccess: {
ethannicholasb3058bd2016-07-01 08:22:01 -07002035 std::vector<SpvId> chain = this->getAccessChain(expr, out);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002036 SpvId member = this->nextId(nullptr);
ethannicholasb3058bd2016-07-01 08:22:01 -07002037 this->writeOpCode(SpvOpAccessChain, (SpvId) (3 + chain.size()), out);
Ethan Nicholas30d30222020-09-11 12:27:26 -04002038 this->writeWord(this->getPointerType(type, get_storage_class(expr)), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002039 this->writeWord(member, out);
2040 for (SpvId idx : chain) {
2041 this->writeWord(idx, out);
2042 }
Ethan Nicholase0707b72021-03-17 11:16:41 -04002043 return std::make_unique<PointerLValue>(*this, member, /*isMemoryObjectPointer=*/false,
2044 this->getType(type), precision);
ethannicholasb3058bd2016-07-01 08:22:01 -07002045 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002046 case Expression::Kind::kSwizzle: {
John Stiles0693fb82021-01-22 18:27:52 -05002047 const Swizzle& swizzle = expr.as<Swizzle>();
John Stiles3f14d282021-02-05 09:31:04 -05002048 std::unique_ptr<LValue> lvalue = this->getLValue(*swizzle.base(), out);
2049 if (lvalue->applySwizzle(swizzle.components(), type)) {
2050 return lvalue;
2051 }
2052 SpvId base = lvalue->getPointer();
2053 if (base == (SpvId) -1) {
Ethan Nicholas89cfde12021-09-27 11:20:34 -04002054 fContext.fErrors->error(swizzle.fLine, "unable to retrieve lvalue from swizzle");
John Stiles5570c512020-11-19 17:58:07 -05002055 }
John Stiles3f14d282021-02-05 09:31:04 -05002056 if (swizzle.components().size() == 1) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002057 SpvId member = this->nextId(nullptr);
John Stilesb5db4822021-01-21 13:04:40 -05002058 SpvId typeId = this->getPointerType(type, get_storage_class(*swizzle.base()));
Ethan Nicholas89cfde12021-09-27 11:20:34 -04002059 Literal index(/*line=*/-1, swizzle.components()[0], fContext.fTypes.fInt.get());
John Stiles7591d4b2021-09-13 13:32:06 -04002060 SpvId indexId = this->writeLiteral(index);
John Stilesb5db4822021-01-21 13:04:40 -05002061 this->writeInstruction(SpvOpAccessChain, typeId, member, base, indexId, out);
Ethan Nicholase0707b72021-03-17 11:16:41 -04002062 return std::make_unique<PointerLValue>(*this,
2063 member,
2064 /*isMemoryObjectPointer=*/false,
2065 this->getType(type),
John Stiles5570c512020-11-19 17:58:07 -05002066 precision);
ethannicholasb3058bd2016-07-01 08:22:01 -07002067 } else {
John Stiles5570c512020-11-19 17:58:07 -05002068 return std::make_unique<SwizzleLValue>(*this, base, swizzle.components(),
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002069 swizzle.base()->type(), type);
ethannicholasb3058bd2016-07-01 08:22:01 -07002070 }
2071 }
Ethan Nicholas30d30222020-09-11 12:27:26 -04002072 default: {
Kevin Lubickbe03ef12021-06-16 15:28:00 -04002073 // expr isn't actually an lvalue, create a placeholder variable for it. This case
2074 // happens due to the need to store values in temporary variables during function
2075 // calls (see comments in getFunctionType); erroneous uses of rvalues as lvalues
2076 // should have been caught by IRGenerator
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002077 SpvId result = this->nextId(nullptr);
Ethan Nicholas30d30222020-09-11 12:27:26 -04002078 SpvId pointerType = this->getPointerType(type, SpvStorageClassFunction);
2079 this->writeInstruction(SpvOpVariable, pointerType, result, SpvStorageClassFunction,
ethannicholasd598f792016-07-25 10:08:54 -07002080 fVariableBuffer);
ethannicholasb3058bd2016-07-01 08:22:01 -07002081 this->writeInstruction(SpvOpStore, result, this->writeExpression(expr, out), out);
Ethan Nicholase0707b72021-03-17 11:16:41 -04002082 return std::make_unique<PointerLValue>(*this, result, /*isMemoryObjectPointer=*/true,
2083 this->getType(type), precision);
Ethan Nicholas30d30222020-09-11 12:27:26 -04002084 }
ethannicholasb3058bd2016-07-01 08:22:01 -07002085 }
2086}
2087
Ethan Nicholas0df1b042017-03-31 13:56:23 -04002088SpvId SPIRVCodeGenerator::writeVariableReference(const VariableReference& ref, OutputStream& out) {
John Stiles9078a892021-08-18 15:03:17 -04002089 const Variable* variable = ref.variable();
2090 if (variable->modifiers().fLayout.fBuiltin == DEVICE_FRAGCOORDS_BUILTIN) {
Brian Salomond8d85b92021-07-07 09:41:17 -04002091 // Down below, we rewrite raw references to sk_FragCoord with expressions that reference
2092 // DEVICE_FRAGCOORDS_BUILTIN. This is a fake variable that means we need to directly access
2093 // the fragcoord; do so now.
Ethan Nicholasa2d22b22021-07-15 10:35:54 -04002094 dsl::DSLGlobalVar fragCoord("sk_FragCoord");
Brian Salomond8d85b92021-07-07 09:41:17 -04002095 return this->getLValue(*dsl::DSLExpression(fragCoord).release(), out)->load(out);
2096 }
John Stiles9078a892021-08-18 15:03:17 -04002097 if (variable->modifiers().fLayout.fBuiltin == DEVICE_CLOCKWISE_BUILTIN) {
Brian Salomond8d85b92021-07-07 09:41:17 -04002098 // Down below, we rewrite raw references to sk_Clockwise with expressions that reference
2099 // DEVICE_CLOCKWISE_BUILTIN. This is a fake variable that means we need to directly
2100 // access front facing; do so now.
Ethan Nicholasa2d22b22021-07-15 10:35:54 -04002101 dsl::DSLGlobalVar clockwise("sk_Clockwise");
Brian Salomond8d85b92021-07-07 09:41:17 -04002102 return this->getLValue(*dsl::DSLExpression(clockwise).release(), out)->load(out);
2103 }
John Stilese40d1662021-01-29 10:08:50 -05002104
Brian Salomond8d85b92021-07-07 09:41:17 -04002105 // Handle inserting use of uniform to flip y when referencing sk_FragCoord.
Brian Salomond8d85b92021-07-07 09:41:17 -04002106 if (variable->modifiers().fLayout.fBuiltin == SK_FRAGCOORD_BUILTIN) {
Ethan Nicholas89cfde12021-09-27 11:20:34 -04002107 this->addRTFlipUniform(ref.fLine);
Brian Salomond8d85b92021-07-07 09:41:17 -04002108 // Use sk_RTAdjust to compute the flipped coordinate
2109 using namespace dsl;
2110 const char* DEVICE_COORDS_NAME = "__device_FragCoords";
2111 SymbolTable& symbols = *dsl::DSLWriter::SymbolTable();
2112 // Use a uniform to flip the Y coordinate. The new expression will be written in
2113 // terms of __device_FragCoords, which is a fake variable that means "access the
2114 // underlying fragcoords directly without flipping it".
Ethan Nicholas89cfde12021-09-27 11:20:34 -04002115 DSLExpression rtFlip(DSLWriter::IRGenerator().convertIdentifier(/*line=*/-1,
Brian Salomond8d85b92021-07-07 09:41:17 -04002116 SKSL_RTFLIP_NAME));
2117 if (!symbols[DEVICE_COORDS_NAME]) {
John Stiles0cac5ed2021-08-06 11:40:39 -04002118 AutoAttachPoolToThread attach(fProgram.fPool.get());
Brian Salomond8d85b92021-07-07 09:41:17 -04002119 Modifiers modifiers;
2120 modifiers.fLayout.fBuiltin = DEVICE_FRAGCOORDS_BUILTIN;
Ethan Nicholas89cfde12021-09-27 11:20:34 -04002121 auto coordsVar = std::make_unique<Variable>(/*line=*/-1,
John Stilesd7437ee2021-08-02 11:56:16 -04002122 fContext.fModifiersPool->add(modifiers),
2123 DEVICE_COORDS_NAME,
2124 fContext.fTypes.fFloat4.get(),
2125 true,
2126 Variable::Storage::kGlobal);
2127 fSPIRVBonusVariables.insert(coordsVar.get());
2128 symbols.add(std::move(coordsVar));
Greg Daniela85e4bf2020-06-17 16:32:45 -04002129 }
Ethan Nicholasa2d22b22021-07-15 10:35:54 -04002130 DSLGlobalVar deviceCoord(DEVICE_COORDS_NAME);
Brian Salomond8d85b92021-07-07 09:41:17 -04002131 std::unique_ptr<Expression> rtFlipSkSLExpr = rtFlip.release();
2132 DSLExpression x = DSLExpression(rtFlipSkSLExpr->clone()).x();
2133 DSLExpression y = DSLExpression(std::move(rtFlipSkSLExpr)).y();
2134 return this->writeExpression(*dsl::Float4(deviceCoord.x(),
2135 std::move(x) + std::move(y) * deviceCoord.y(),
2136 deviceCoord.z(),
2137 deviceCoord.w()).release(),
2138 out);
Ethan Nicholas941e7e22016-12-12 15:33:30 -05002139 }
John Stiles1e1fe122021-01-29 12:18:46 -05002140
Brian Salomond8d85b92021-07-07 09:41:17 -04002141 // Handle flipping sk_Clockwise.
2142 if (variable->modifiers().fLayout.fBuiltin == SK_CLOCKWISE_BUILTIN) {
Ethan Nicholas89cfde12021-09-27 11:20:34 -04002143 this->addRTFlipUniform(ref.fLine);
Brian Salomond8d85b92021-07-07 09:41:17 -04002144 using namespace dsl;
2145 const char* DEVICE_CLOCKWISE_NAME = "__device_Clockwise";
2146 SymbolTable& symbols = *dsl::DSLWriter::SymbolTable();
2147 // Use a uniform to flip the Y coordinate. The new expression will be written in
2148 // terms of __device_Clockwise, which is a fake variable that means "access the
2149 // underlying FrontFacing directly".
Ethan Nicholas89cfde12021-09-27 11:20:34 -04002150 DSLExpression rtFlip(DSLWriter::IRGenerator().convertIdentifier(/*line=*/-1,
Brian Salomond8d85b92021-07-07 09:41:17 -04002151 SKSL_RTFLIP_NAME));
2152 if (!symbols[DEVICE_CLOCKWISE_NAME]) {
John Stiles0cac5ed2021-08-06 11:40:39 -04002153 AutoAttachPoolToThread attach(fProgram.fPool.get());
Brian Salomond8d85b92021-07-07 09:41:17 -04002154 Modifiers modifiers;
2155 modifiers.fLayout.fBuiltin = DEVICE_CLOCKWISE_BUILTIN;
Ethan Nicholas89cfde12021-09-27 11:20:34 -04002156 auto clockwiseVar = std::make_unique<Variable>(/*line=*/-1,
John Stilesd7437ee2021-08-02 11:56:16 -04002157 fContext.fModifiersPool->add(modifiers),
2158 DEVICE_CLOCKWISE_NAME,
2159 fContext.fTypes.fBool.get(),
2160 true,
2161 Variable::Storage::kGlobal);
2162 fSPIRVBonusVariables.insert(clockwiseVar.get());
2163 symbols.add(std::move(clockwiseVar));
Brian Salomond8d85b92021-07-07 09:41:17 -04002164 }
Ethan Nicholasa2d22b22021-07-15 10:35:54 -04002165 DSLGlobalVar deviceClockwise(DEVICE_CLOCKWISE_NAME);
Brian Salomond8d85b92021-07-07 09:41:17 -04002166 // FrontFacing in Vulkan is defined in terms of a top-down render target. In skia,
2167 // we use the default convention of "counter-clockwise face is front".
2168 return this->writeExpression(*dsl::Bool(Select(rtFlip.y() > 0,
2169 !deviceClockwise,
2170 deviceClockwise)).release(),
2171 out);
Chris Daltonb91c4662018-08-01 10:46:22 -06002172 }
John Stiles1e1fe122021-01-29 12:18:46 -05002173
Brian Salomond8d85b92021-07-07 09:41:17 -04002174 return this->getLValue(ref, out)->load(out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002175}
2176
Ethan Nicholas0df1b042017-03-31 13:56:23 -04002177SpvId SPIRVCodeGenerator::writeIndexExpression(const IndexExpression& expr, OutputStream& out) {
John Stiles9aeed132020-11-24 17:36:06 -05002178 if (expr.base()->type().isVector()) {
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04002179 SpvId base = this->writeExpression(*expr.base(), out);
2180 SpvId index = this->writeExpression(*expr.index(), out);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002181 SpvId result = this->nextId(nullptr);
Ethan Nicholas30d30222020-09-11 12:27:26 -04002182 this->writeInstruction(SpvOpVectorExtractDynamic, this->getType(expr.type()), result, base,
Ethan Nicholasa9a06902019-01-07 14:42:40 -05002183 index, out);
2184 return result;
2185 }
ethannicholasb3058bd2016-07-01 08:22:01 -07002186 return getLValue(expr, out)->load(out);
2187}
2188
Ethan Nicholas0df1b042017-03-31 13:56:23 -04002189SpvId SPIRVCodeGenerator::writeFieldAccess(const FieldAccess& f, OutputStream& out) {
ethannicholasb3058bd2016-07-01 08:22:01 -07002190 return getLValue(f, out)->load(out);
2191}
2192
Ethan Nicholas0df1b042017-03-31 13:56:23 -04002193SpvId SPIRVCodeGenerator::writeSwizzle(const Swizzle& swizzle, OutputStream& out) {
Ethan Nicholas6b4d5812020-10-12 16:11:51 -04002194 SpvId base = this->writeExpression(*swizzle.base(), out);
Ethan Nicholas7f015882021-03-23 14:16:52 -04002195 SpvId result = this->nextId(&swizzle.type());
Ethan Nicholas6b4d5812020-10-12 16:11:51 -04002196 size_t count = swizzle.components().size();
ethannicholasb3058bd2016-07-01 08:22:01 -07002197 if (count == 1) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04002198 this->writeInstruction(SpvOpCompositeExtract, this->getType(swizzle.type()), result, base,
Ethan Nicholas6b4d5812020-10-12 16:11:51 -04002199 swizzle.components()[0], out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002200 } else {
2201 this->writeOpCode(SpvOpVectorShuffle, 5 + (int32_t) count, out);
Ethan Nicholas30d30222020-09-11 12:27:26 -04002202 this->writeWord(this->getType(swizzle.type()), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002203 this->writeWord(result, out);
2204 this->writeWord(base, out);
Brian Osman25647672020-09-15 15:16:56 -04002205 this->writeWord(base, out);
Ethan Nicholas6b4d5812020-10-12 16:11:51 -04002206 for (int component : swizzle.components()) {
Brian Osman25647672020-09-15 15:16:56 -04002207 this->writeWord(component, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002208 }
2209 }
2210 return result;
2211}
2212
Greg Daniel64773e62016-11-22 09:44:03 -05002213SpvId SPIRVCodeGenerator::writeBinaryOperation(const Type& resultType,
2214 const Type& operandType, SpvId lhs,
2215 SpvId rhs, SpvOp_ ifFloat, SpvOp_ ifInt,
Ethan Nicholas0df1b042017-03-31 13:56:23 -04002216 SpvOp_ ifUInt, SpvOp_ ifBool, OutputStream& out) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002217 SpvId result = this->nextId(&resultType);
ethannicholasd598f792016-07-25 10:08:54 -07002218 if (is_float(fContext, operandType)) {
ethannicholasb3058bd2016-07-01 08:22:01 -07002219 this->writeInstruction(ifFloat, this->getType(resultType), result, lhs, rhs, out);
ethannicholasd598f792016-07-25 10:08:54 -07002220 } else if (is_signed(fContext, operandType)) {
ethannicholasb3058bd2016-07-01 08:22:01 -07002221 this->writeInstruction(ifInt, this->getType(resultType), result, lhs, rhs, out);
ethannicholasd598f792016-07-25 10:08:54 -07002222 } else if (is_unsigned(fContext, operandType)) {
ethannicholasb3058bd2016-07-01 08:22:01 -07002223 this->writeInstruction(ifUInt, this->getType(resultType), result, lhs, rhs, out);
John Stiles123501f2020-12-09 10:08:13 -05002224 } else if (is_bool(fContext, operandType)) {
ethannicholasb3058bd2016-07-01 08:22:01 -07002225 this->writeInstruction(ifBool, this->getType(resultType), result, lhs, rhs, out);
2226 } else {
Ethan Nicholas89cfde12021-09-27 11:20:34 -04002227 fContext.fErrors->error(operandType.fLine,
Ethan Nicholas3abc6c62021-08-13 11:20:09 -04002228 "unsupported operand for binary expression: " + operandType.description());
Ethan Nicholas2f4652f2021-03-12 18:48:48 +00002229 }
ethannicholasb3058bd2016-07-01 08:22:01 -07002230 return result;
2231}
2232
Ethan Nicholas48e24052018-03-14 13:51:39 -04002233SpvId SPIRVCodeGenerator::foldToBool(SpvId id, const Type& operandType, SpvOp op,
2234 OutputStream& out) {
John Stiles9aeed132020-11-24 17:36:06 -05002235 if (operandType.isVector()) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002236 SpvId result = this->nextId(nullptr);
John Stiles54e7c052021-01-11 14:22:36 -05002237 this->writeInstruction(op, this->getType(*fContext.fTypes.fBool), result, id, out);
Ethan Nicholasef653b82017-02-21 13:50:00 -05002238 return result;
2239 }
2240 return id;
2241}
2242
Ethan Nicholas68990be2017-07-13 09:36:52 -04002243SpvId SPIRVCodeGenerator::writeMatrixComparison(const Type& operandType, SpvId lhs, SpvId rhs,
2244 SpvOp_ floatOperator, SpvOp_ intOperator,
Ethan Nicholas0df21132018-07-10 09:37:51 -04002245 SpvOp_ vectorMergeOperator, SpvOp_ mergeOperator,
Ethan Nicholas68990be2017-07-13 09:36:52 -04002246 OutputStream& out) {
2247 SpvOp_ compareOp = is_float(fContext, operandType) ? floatOperator : intOperator;
John Stiles9aeed132020-11-24 17:36:06 -05002248 SkASSERT(operandType.isMatrix());
Ethan Nicholas0df21132018-07-10 09:37:51 -04002249 SpvId columnType = this->getType(operandType.componentType().toCompound(fContext,
2250 operandType.rows(),
2251 1));
John Stiles54e7c052021-01-11 14:22:36 -05002252 SpvId bvecType = this->getType(fContext.fTypes.fBool->toCompound(fContext,
Ethan Nicholas0df21132018-07-10 09:37:51 -04002253 operandType.rows(),
Ethan Nicholas68990be2017-07-13 09:36:52 -04002254 1));
John Stiles54e7c052021-01-11 14:22:36 -05002255 SpvId boolType = this->getType(*fContext.fTypes.fBool);
Ethan Nicholas68990be2017-07-13 09:36:52 -04002256 SpvId result = 0;
Ethan Nicholas0df21132018-07-10 09:37:51 -04002257 for (int i = 0; i < operandType.columns(); i++) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002258 SpvId columnL = this->nextId(&operandType);
Ethan Nicholas0df21132018-07-10 09:37:51 -04002259 this->writeInstruction(SpvOpCompositeExtract, columnType, columnL, lhs, i, out);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002260 SpvId columnR = this->nextId(&operandType);
Ethan Nicholas0df21132018-07-10 09:37:51 -04002261 this->writeInstruction(SpvOpCompositeExtract, columnType, columnR, rhs, i, out);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002262 SpvId compare = this->nextId(&operandType);
Ethan Nicholas0df21132018-07-10 09:37:51 -04002263 this->writeInstruction(compareOp, bvecType, compare, columnL, columnR, out);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002264 SpvId merge = this->nextId(nullptr);
Ethan Nicholas0df21132018-07-10 09:37:51 -04002265 this->writeInstruction(vectorMergeOperator, boolType, merge, compare, out);
Ethan Nicholas68990be2017-07-13 09:36:52 -04002266 if (result != 0) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002267 SpvId next = this->nextId(nullptr);
Ethan Nicholas0df21132018-07-10 09:37:51 -04002268 this->writeInstruction(mergeOperator, boolType, next, result, merge, out);
Ethan Nicholas68990be2017-07-13 09:36:52 -04002269 result = next;
2270 }
2271 else {
Ethan Nicholas0df21132018-07-10 09:37:51 -04002272 result = merge;
Ethan Nicholas68990be2017-07-13 09:36:52 -04002273 }
2274 }
2275 return result;
2276}
2277
Ethan Nicholas0df21132018-07-10 09:37:51 -04002278SpvId SPIRVCodeGenerator::writeComponentwiseMatrixBinary(const Type& operandType, SpvId lhs,
John Stiles43b593c2021-05-13 22:03:27 -04002279 SpvId rhs, SpvOp_ op, OutputStream& out) {
John Stiles9aeed132020-11-24 17:36:06 -05002280 SkASSERT(operandType.isMatrix());
Ethan Nicholas2f4652f2021-03-12 18:48:48 +00002281 SpvId columnType = this->getType(operandType.componentType().toCompound(fContext,
2282 operandType.rows(),
2283 1));
John Stiles43b593c2021-05-13 22:03:27 -04002284 std::vector<SpvId> columns;
2285 columns.reserve(operandType.columns());
Ethan Nicholas0df21132018-07-10 09:37:51 -04002286 for (int i = 0; i < operandType.columns(); i++) {
Ethan Nicholas7f015882021-03-23 14:16:52 -04002287 SpvId columnL = this->nextId(&operandType);
Ethan Nicholas2f4652f2021-03-12 18:48:48 +00002288 this->writeInstruction(SpvOpCompositeExtract, columnType, columnL, lhs, i, out);
Ethan Nicholas7f015882021-03-23 14:16:52 -04002289 SpvId columnR = this->nextId(&operandType);
Ethan Nicholas2f4652f2021-03-12 18:48:48 +00002290 this->writeInstruction(SpvOpCompositeExtract, columnType, columnR, rhs, i, out);
John Stiles43b593c2021-05-13 22:03:27 -04002291 columns.push_back(this->nextId(&operandType));
Ethan Nicholas2f4652f2021-03-12 18:48:48 +00002292 this->writeInstruction(op, columnType, columns[i], columnL, columnR, out);
Ethan Nicholas0df21132018-07-10 09:37:51 -04002293 }
John Stiles43b593c2021-05-13 22:03:27 -04002294 return this->writeComposite(columns, operandType, out);
Ethan Nicholas0df21132018-07-10 09:37:51 -04002295}
2296
John Stiles9485b552021-01-27 11:47:00 -05002297static std::unique_ptr<Expression> create_literal_1(const Context& context, const Type& type) {
John Stiles7591d4b2021-09-13 13:32:06 -04002298 SkASSERT(type.isInteger() || type.isFloat());
Ethan Nicholas89cfde12021-09-27 11:20:34 -04002299 return Literal::Make(/*line=*/-1, /*value=*/1.0, &type);
Ethan Nicholas49465b42019-04-17 12:22:21 -04002300}
2301
John Stilesd94bfdd2021-03-25 11:44:08 -04002302SpvId SPIRVCodeGenerator::writeReciprocal(const Type& type, SpvId value, OutputStream& out) {
2303 SkASSERT(type.isFloat());
Ethan Nicholas89cfde12021-09-27 11:20:34 -04002304 SpvId one = this->writeLiteral({/*line=*/-1, /*value=*/1, &type});
John Stilesd94bfdd2021-03-25 11:44:08 -04002305 SpvId reciprocal = this->nextId(&type);
2306 this->writeInstruction(SpvOpFDiv, this->getType(type), reciprocal, one, value, out);
2307 return reciprocal;
2308}
2309
John Stilesa91bf052021-05-17 09:34:03 -04002310SpvId SPIRVCodeGenerator::writeScalarToMatrixSplat(const Type& matrixType,
2311 SpvId scalarId,
2312 OutputStream& out) {
2313 // Splat the scalar into a vector.
2314 const Type& vectorType = matrixType.componentType().toCompound(fContext,
2315 /*columns=*/matrixType.rows(),
2316 /*rows=*/1);
2317 std::vector<SpvId> vecArguments(/*count*/ matrixType.rows(), /*value*/ scalarId);
2318 SpvId vectorId = this->writeComposite(vecArguments, vectorType, out);
2319
2320 // Splat the vector into a matrix.
2321 std::vector<SpvId> matArguments(/*count*/ matrixType.columns(), /*value*/ vectorId);
2322 return this->writeComposite(matArguments, matrixType, out);
2323}
2324
John Stiles45990502021-02-16 10:55:27 -05002325SpvId SPIRVCodeGenerator::writeBinaryExpression(const Type& leftType, SpvId lhs, Operator op,
Ethan Nicholas49465b42019-04-17 12:22:21 -04002326 const Type& rightType, SpvId rhs,
2327 const Type& resultType, OutputStream& out) {
John Stilesd0614f22020-12-09 11:11:41 -05002328 // The comma operator ignores the type of the left-hand side entirely.
John Stiles45990502021-02-16 10:55:27 -05002329 if (op.kind() == Token::Kind::TK_COMMA) {
John Stilesd0614f22020-12-09 11:11:41 -05002330 return rhs;
2331 }
Ethan Nicholas48e24052018-03-14 13:51:39 -04002332 // overall type we are operating on: float2, int, uint4...
ethannicholasb3058bd2016-07-01 08:22:01 -07002333 const Type* operandType;
Ethan Nicholas48e24052018-03-14 13:51:39 -04002334 // IR allows mismatched types in expressions (e.g. float2 * float), but they need special
2335 // handling in SPIR-V
Ethan Nicholas49465b42019-04-17 12:22:21 -04002336 if (this->getActualType(leftType) != this->getActualType(rightType)) {
John Stiles9aeed132020-11-24 17:36:06 -05002337 if (leftType.isVector() && rightType.isNumber()) {
John Stilesd94bfdd2021-03-25 11:44:08 -04002338 if (resultType.componentType().isFloat()) {
2339 switch (op.kind()) {
2340 case Token::Kind::TK_SLASH: {
2341 rhs = this->writeReciprocal(rightType, rhs, out);
2342 [[fallthrough]];
2343 }
2344 case Token::Kind::TK_STAR: {
2345 SpvId result = this->nextId(&resultType);
2346 this->writeInstruction(SpvOpVectorTimesScalar, this->getType(resultType),
2347 result, lhs, rhs, out);
2348 return result;
2349 }
2350 default:
2351 break;
2352 }
Ethan Nicholas49465b42019-04-17 12:22:21 -04002353 }
ethannicholasb3058bd2016-07-01 08:22:01 -07002354 // promote number to vector
Ethan Nicholas49465b42019-04-17 12:22:21 -04002355 const Type& vecType = leftType;
Ethan Nicholas7f015882021-03-23 14:16:52 -04002356 SpvId vec = this->nextId(&vecType);
Ethan Nicholas48e24052018-03-14 13:51:39 -04002357 this->writeOpCode(SpvOpCompositeConstruct, 3 + vecType.columns(), out);
2358 this->writeWord(this->getType(vecType), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002359 this->writeWord(vec, out);
Ethan Nicholas48e24052018-03-14 13:51:39 -04002360 for (int i = 0; i < vecType.columns(); i++) {
ethannicholasb3058bd2016-07-01 08:22:01 -07002361 this->writeWord(rhs, out);
2362 }
2363 rhs = vec;
Ethan Nicholas49465b42019-04-17 12:22:21 -04002364 operandType = &leftType;
John Stiles9aeed132020-11-24 17:36:06 -05002365 } else if (rightType.isVector() && leftType.isNumber()) {
John Stilesd94bfdd2021-03-25 11:44:08 -04002366 if (resultType.componentType().isFloat()) {
2367 if (op.kind() == Token::Kind::TK_STAR) {
2368 SpvId result = this->nextId(&resultType);
2369 this->writeInstruction(SpvOpVectorTimesScalar, this->getType(resultType),
2370 result, rhs, lhs, out);
2371 return result;
2372 }
Ethan Nicholas49465b42019-04-17 12:22:21 -04002373 }
ethannicholasb3058bd2016-07-01 08:22:01 -07002374 // promote number to vector
Ethan Nicholas49465b42019-04-17 12:22:21 -04002375 const Type& vecType = rightType;
Ethan Nicholas7f015882021-03-23 14:16:52 -04002376 SpvId vec = this->nextId(&vecType);
Ethan Nicholas48e24052018-03-14 13:51:39 -04002377 this->writeOpCode(SpvOpCompositeConstruct, 3 + vecType.columns(), out);
2378 this->writeWord(this->getType(vecType), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002379 this->writeWord(vec, out);
Ethan Nicholas48e24052018-03-14 13:51:39 -04002380 for (int i = 0; i < vecType.columns(); i++) {
ethannicholasb3058bd2016-07-01 08:22:01 -07002381 this->writeWord(lhs, out);
2382 }
2383 lhs = vec;
Ethan Nicholas49465b42019-04-17 12:22:21 -04002384 operandType = &rightType;
John Stiles9aeed132020-11-24 17:36:06 -05002385 } else if (leftType.isMatrix()) {
John Stilesa91bf052021-05-17 09:34:03 -04002386 if (op.kind() == Token::Kind::TK_STAR) {
2387 // Matrix-times-vector and matrix-times-scalar have dedicated ops in SPIR-V.
2388 SpvOp_ spvop;
2389 if (rightType.isMatrix()) {
2390 spvop = SpvOpMatrixTimesMatrix;
2391 } else if (rightType.isVector()) {
2392 spvop = SpvOpMatrixTimesVector;
2393 } else {
2394 SkASSERT(rightType.isScalar());
2395 spvop = SpvOpMatrixTimesScalar;
2396 }
2397 SpvId result = this->nextId(&resultType);
2398 this->writeInstruction(spvop, this->getType(resultType), result, lhs, rhs, out);
2399 return result;
ethannicholasb3058bd2016-07-01 08:22:01 -07002400 } else {
John Stilesa91bf052021-05-17 09:34:03 -04002401 // Matrix-op-vector is not supported in GLSL/SkSL for non-multiplication ops; we
2402 // expect to have a scalar here.
John Stiles9aeed132020-11-24 17:36:06 -05002403 SkASSERT(rightType.isScalar());
John Stilesa91bf052021-05-17 09:34:03 -04002404
2405 // Splat rhs across an entire matrix so we can reuse the matrix-op-matrix path.
2406 SpvId rhsMatrix = this->writeScalarToMatrixSplat(leftType, rhs, out);
2407
2408 // Perform this operation as matrix-op-matrix.
2409 return this->writeBinaryExpression(leftType, lhs, op, leftType, rhsMatrix,
2410 resultType, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002411 }
John Stiles9aeed132020-11-24 17:36:06 -05002412 } else if (rightType.isMatrix()) {
John Stilesa91bf052021-05-17 09:34:03 -04002413 if (op.kind() == Token::Kind::TK_STAR) {
2414 // Matrix-times-vector and matrix-times-scalar have dedicated ops in SPIR-V.
2415 SpvId result = this->nextId(&resultType);
2416 if (leftType.isVector()) {
2417 this->writeInstruction(SpvOpVectorTimesMatrix, this->getType(resultType),
2418 result, lhs, rhs, out);
2419 } else {
2420 SkASSERT(leftType.isScalar());
2421 this->writeInstruction(SpvOpMatrixTimesScalar, this->getType(resultType),
2422 result, rhs, lhs, out);
2423 }
2424 return result;
ethannicholasb3058bd2016-07-01 08:22:01 -07002425 } else {
John Stilesa91bf052021-05-17 09:34:03 -04002426 // Vector-op-matrix is not supported in GLSL/SkSL for non-multiplication ops; we
2427 // expect to have a scalar here.
John Stiles9aeed132020-11-24 17:36:06 -05002428 SkASSERT(leftType.isScalar());
John Stilesa91bf052021-05-17 09:34:03 -04002429
2430 // Splat lhs across an entire matrix so we can reuse the matrix-op-matrix path.
2431 SpvId lhsMatrix = this->writeScalarToMatrixSplat(rightType, lhs, out);
2432
2433 // Perform this operation as matrix-op-matrix.
2434 return this->writeBinaryExpression(rightType, lhsMatrix, op, rightType, rhs,
2435 resultType, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002436 }
ethannicholasb3058bd2016-07-01 08:22:01 -07002437 } else {
Ethan Nicholas89cfde12021-09-27 11:20:34 -04002438 fContext.fErrors->error(leftType.fLine, "unsupported mixed-type expression");
Ethan Nicholas49465b42019-04-17 12:22:21 -04002439 return -1;
ethannicholasb3058bd2016-07-01 08:22:01 -07002440 }
2441 } else {
John Stiles2d4f9592020-10-30 10:29:12 -04002442 operandType = &this->getActualType(leftType);
Ethan Nicholas49465b42019-04-17 12:22:21 -04002443 SkASSERT(*operandType == this->getActualType(rightType));
ethannicholasb3058bd2016-07-01 08:22:01 -07002444 }
John Stiles45990502021-02-16 10:55:27 -05002445 switch (op.kind()) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002446 case Token::Kind::TK_EQEQ: {
John Stiles9aeed132020-11-24 17:36:06 -05002447 if (operandType->isMatrix()) {
Ethan Nicholas68990be2017-07-13 09:36:52 -04002448 return this->writeMatrixComparison(*operandType, lhs, rhs, SpvOpFOrdEqual,
Ethan Nicholas0df21132018-07-10 09:37:51 -04002449 SpvOpIEqual, SpvOpAll, SpvOpLogicalAnd, out);
Ethan Nicholas68990be2017-07-13 09:36:52 -04002450 }
John Stilesbc5c2a02021-04-08 11:44:53 -04002451 if (operandType->isStruct()) {
2452 return this->writeStructComparison(*operandType, lhs, op, rhs, out);
2453 }
John Stiles35092102021-04-08 23:30:51 -04002454 if (operandType->isArray()) {
2455 return this->writeArrayComparison(*operandType, lhs, op, rhs, out);
2456 }
John Stiles4a7dc462020-11-25 11:08:08 -05002457 SkASSERT(resultType.isBoolean());
Ethan Nicholas48e24052018-03-14 13:51:39 -04002458 const Type* tmpType;
John Stiles9aeed132020-11-24 17:36:06 -05002459 if (operandType->isVector()) {
John Stiles54e7c052021-01-11 14:22:36 -05002460 tmpType = &fContext.fTypes.fBool->toCompound(fContext,
2461 operandType->columns(),
2462 operandType->rows());
Ethan Nicholas48e24052018-03-14 13:51:39 -04002463 } else {
2464 tmpType = &resultType;
2465 }
2466 return this->foldToBool(this->writeBinaryOperation(*tmpType, *operandType, lhs, rhs,
Ethan Nicholasef653b82017-02-21 13:50:00 -05002467 SpvOpFOrdEqual, SpvOpIEqual,
2468 SpvOpIEqual, SpvOpLogicalEqual, out),
Ethan Nicholas48e24052018-03-14 13:51:39 -04002469 *operandType, SpvOpAll, out);
Ethan Nicholasef653b82017-02-21 13:50:00 -05002470 }
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002471 case Token::Kind::TK_NEQ:
John Stiles9aeed132020-11-24 17:36:06 -05002472 if (operandType->isMatrix()) {
Ethan Nicholas68990be2017-07-13 09:36:52 -04002473 return this->writeMatrixComparison(*operandType, lhs, rhs, SpvOpFOrdNotEqual,
Ethan Nicholas0df21132018-07-10 09:37:51 -04002474 SpvOpINotEqual, SpvOpAny, SpvOpLogicalOr, out);
Ethan Nicholas68990be2017-07-13 09:36:52 -04002475 }
John Stilesbc5c2a02021-04-08 11:44:53 -04002476 if (operandType->isStruct()) {
2477 return this->writeStructComparison(*operandType, lhs, op, rhs, out);
2478 }
John Stiles35092102021-04-08 23:30:51 -04002479 if (operandType->isArray()) {
2480 return this->writeArrayComparison(*operandType, lhs, op, rhs, out);
2481 }
John Stiles4a7dc462020-11-25 11:08:08 -05002482 [[fallthrough]];
2483 case Token::Kind::TK_LOGICALXOR:
2484 SkASSERT(resultType.isBoolean());
Ethan Nicholas48e24052018-03-14 13:51:39 -04002485 const Type* tmpType;
John Stiles9aeed132020-11-24 17:36:06 -05002486 if (operandType->isVector()) {
John Stiles54e7c052021-01-11 14:22:36 -05002487 tmpType = &fContext.fTypes.fBool->toCompound(fContext,
2488 operandType->columns(),
2489 operandType->rows());
Ethan Nicholas48e24052018-03-14 13:51:39 -04002490 } else {
2491 tmpType = &resultType;
2492 }
2493 return this->foldToBool(this->writeBinaryOperation(*tmpType, *operandType, lhs, rhs,
Ethan Nicholasef653b82017-02-21 13:50:00 -05002494 SpvOpFOrdNotEqual, SpvOpINotEqual,
2495 SpvOpINotEqual, SpvOpLogicalNotEqual,
2496 out),
Ethan Nicholas48e24052018-03-14 13:51:39 -04002497 *operandType, SpvOpAny, out);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002498 case Token::Kind::TK_GT:
John Stiles4a7dc462020-11-25 11:08:08 -05002499 SkASSERT(resultType.isBoolean());
Greg Daniel64773e62016-11-22 09:44:03 -05002500 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs,
2501 SpvOpFOrdGreaterThan, SpvOpSGreaterThan,
ethannicholasb3058bd2016-07-01 08:22:01 -07002502 SpvOpUGreaterThan, SpvOpUndef, out);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002503 case Token::Kind::TK_LT:
John Stiles4a7dc462020-11-25 11:08:08 -05002504 SkASSERT(resultType.isBoolean());
Greg Daniel64773e62016-11-22 09:44:03 -05002505 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs, SpvOpFOrdLessThan,
ethannicholasb3058bd2016-07-01 08:22:01 -07002506 SpvOpSLessThan, SpvOpULessThan, SpvOpUndef, out);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002507 case Token::Kind::TK_GTEQ:
John Stiles4a7dc462020-11-25 11:08:08 -05002508 SkASSERT(resultType.isBoolean());
Greg Daniel64773e62016-11-22 09:44:03 -05002509 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs,
2510 SpvOpFOrdGreaterThanEqual, SpvOpSGreaterThanEqual,
ethannicholasb3058bd2016-07-01 08:22:01 -07002511 SpvOpUGreaterThanEqual, SpvOpUndef, out);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002512 case Token::Kind::TK_LTEQ:
John Stiles4a7dc462020-11-25 11:08:08 -05002513 SkASSERT(resultType.isBoolean());
Greg Daniel64773e62016-11-22 09:44:03 -05002514 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs,
2515 SpvOpFOrdLessThanEqual, SpvOpSLessThanEqual,
ethannicholasb3058bd2016-07-01 08:22:01 -07002516 SpvOpULessThanEqual, SpvOpUndef, out);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002517 case Token::Kind::TK_PLUS:
John Stiles9aeed132020-11-24 17:36:06 -05002518 if (leftType.isMatrix() && rightType.isMatrix()) {
Ethan Nicholas49465b42019-04-17 12:22:21 -04002519 SkASSERT(leftType == rightType);
John Stiles43b593c2021-05-13 22:03:27 -04002520 return this->writeComponentwiseMatrixBinary(leftType, lhs, rhs, SpvOpFAdd, out);
Ethan Nicholas0df21132018-07-10 09:37:51 -04002521 }
Greg Daniel64773e62016-11-22 09:44:03 -05002522 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs, SpvOpFAdd,
ethannicholasb3058bd2016-07-01 08:22:01 -07002523 SpvOpIAdd, SpvOpIAdd, SpvOpUndef, out);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002524 case Token::Kind::TK_MINUS:
John Stiles9aeed132020-11-24 17:36:06 -05002525 if (leftType.isMatrix() && rightType.isMatrix()) {
Ethan Nicholas49465b42019-04-17 12:22:21 -04002526 SkASSERT(leftType == rightType);
John Stiles43b593c2021-05-13 22:03:27 -04002527 return this->writeComponentwiseMatrixBinary(leftType, lhs, rhs, SpvOpFSub, out);
Ethan Nicholas0df21132018-07-10 09:37:51 -04002528 }
Greg Daniel64773e62016-11-22 09:44:03 -05002529 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs, SpvOpFSub,
ethannicholasb3058bd2016-07-01 08:22:01 -07002530 SpvOpISub, SpvOpISub, SpvOpUndef, out);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002531 case Token::Kind::TK_STAR:
John Stiles9aeed132020-11-24 17:36:06 -05002532 if (leftType.isMatrix() && rightType.isMatrix()) {
ethannicholasb3058bd2016-07-01 08:22:01 -07002533 // matrix multiply
Ethan Nicholas7f015882021-03-23 14:16:52 -04002534 SpvId result = this->nextId(&resultType);
ethannicholasb3058bd2016-07-01 08:22:01 -07002535 this->writeInstruction(SpvOpMatrixTimesMatrix, this->getType(resultType), result,
2536 lhs, rhs, out);
2537 return result;
2538 }
Greg Daniel64773e62016-11-22 09:44:03 -05002539 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs, SpvOpFMul,
ethannicholasb3058bd2016-07-01 08:22:01 -07002540 SpvOpIMul, SpvOpIMul, SpvOpUndef, out);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002541 case Token::Kind::TK_SLASH:
John Stilesbdf3bb72021-05-17 09:34:23 -04002542 if (leftType.isMatrix() && rightType.isMatrix()) {
2543 SkASSERT(leftType == rightType);
2544 return this->writeComponentwiseMatrixBinary(leftType, lhs, rhs, SpvOpFDiv, out);
2545 }
Greg Daniel64773e62016-11-22 09:44:03 -05002546 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs, SpvOpFDiv,
ethannicholasb3058bd2016-07-01 08:22:01 -07002547 SpvOpSDiv, SpvOpUDiv, SpvOpUndef, out);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002548 case Token::Kind::TK_PERCENT:
Ethan Nicholasb3d0f7c2017-05-17 13:13:21 -04002549 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs, SpvOpFMod,
2550 SpvOpSMod, SpvOpUMod, SpvOpUndef, out);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002551 case Token::Kind::TK_SHL:
Ethan Nicholasfd444be2017-07-05 10:05:54 -04002552 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs, SpvOpUndef,
2553 SpvOpShiftLeftLogical, SpvOpShiftLeftLogical,
2554 SpvOpUndef, out);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002555 case Token::Kind::TK_SHR:
Ethan Nicholasfd444be2017-07-05 10:05:54 -04002556 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs, SpvOpUndef,
2557 SpvOpShiftRightArithmetic, SpvOpShiftRightLogical,
2558 SpvOpUndef, out);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002559 case Token::Kind::TK_BITWISEAND:
Ethan Nicholasfd444be2017-07-05 10:05:54 -04002560 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs, SpvOpUndef,
2561 SpvOpBitwiseAnd, SpvOpBitwiseAnd, SpvOpUndef, out);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002562 case Token::Kind::TK_BITWISEOR:
Ethan Nicholasfd444be2017-07-05 10:05:54 -04002563 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs, SpvOpUndef,
2564 SpvOpBitwiseOr, SpvOpBitwiseOr, SpvOpUndef, out);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002565 case Token::Kind::TK_BITWISEXOR:
Ethan Nicholasfd444be2017-07-05 10:05:54 -04002566 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs, SpvOpUndef,
2567 SpvOpBitwiseXor, SpvOpBitwiseXor, SpvOpUndef, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002568 default:
Ethan Nicholas39f6da42021-08-23 13:10:07 -04002569 fContext.fErrors->error(0, "unsupported token");
Ethan Nicholas49465b42019-04-17 12:22:21 -04002570 return -1;
ethannicholasb3058bd2016-07-01 08:22:01 -07002571 }
2572}
2573
John Stiles35092102021-04-08 23:30:51 -04002574SpvId SPIRVCodeGenerator::writeArrayComparison(const Type& arrayType, SpvId lhs, Operator op,
2575 SpvId rhs, OutputStream& out) {
2576 // The inputs must be arrays, and the op must be == or !=.
2577 SkASSERT(op.kind() == Token::Kind::TK_EQEQ || op.kind() == Token::Kind::TK_NEQ);
2578 SkASSERT(arrayType.isArray());
2579 const Type& componentType = arrayType.componentType();
2580 const SpvId componentTypeId = this->getType(componentType);
2581 const int arraySize = arrayType.columns();
2582 SkASSERT(arraySize > 0);
2583
2584 // Synthesize equality checks for each item in the array.
2585 const Type& boolType = *fContext.fTypes.fBool;
2586 SpvId allComparisons = (SpvId)-1;
2587 for (int index = 0; index < arraySize; ++index) {
2588 // Get the left and right item in the array.
2589 SpvId itemL = this->nextId(&componentType);
2590 this->writeInstruction(SpvOpCompositeExtract, componentTypeId, itemL, lhs, index, out);
2591 SpvId itemR = this->nextId(&componentType);
2592 this->writeInstruction(SpvOpCompositeExtract, componentTypeId, itemR, rhs, index, out);
2593 // Use `writeBinaryExpression` with the requested == or != operator on these items.
2594 SpvId comparison = this->writeBinaryExpression(componentType, itemL, op,
2595 componentType, itemR, boolType, out);
2596 // Merge this comparison result with all the other comparisons we've done.
2597 allComparisons = this->mergeComparisons(comparison, allComparisons, op, out);
2598 }
2599 return allComparisons;
2600}
2601
John Stilesbc5c2a02021-04-08 11:44:53 -04002602SpvId SPIRVCodeGenerator::writeStructComparison(const Type& structType, SpvId lhs, Operator op,
2603 SpvId rhs, OutputStream& out) {
2604 // The inputs must be structs containing fields, and the op must be == or !=.
John Stilesbc5c2a02021-04-08 11:44:53 -04002605 SkASSERT(op.kind() == Token::Kind::TK_EQEQ || op.kind() == Token::Kind::TK_NEQ);
John Stiles35092102021-04-08 23:30:51 -04002606 SkASSERT(structType.isStruct());
John Stilesbc5c2a02021-04-08 11:44:53 -04002607 const std::vector<Type::Field>& fields = structType.fields();
2608 SkASSERT(!fields.empty());
2609
2610 // Synthesize equality checks for each field in the struct.
2611 const Type& boolType = *fContext.fTypes.fBool;
John Stilesbc5c2a02021-04-08 11:44:53 -04002612 SpvId allComparisons = (SpvId)-1;
2613 for (int index = 0; index < (int)fields.size(); ++index) {
2614 // Get the left and right versions of this field.
2615 const Type& fieldType = *fields[index].fType;
John Stiles35092102021-04-08 23:30:51 -04002616 const SpvId fieldTypeId = this->getType(fieldType);
John Stilesbc5c2a02021-04-08 11:44:53 -04002617
2618 SpvId fieldL = this->nextId(&fieldType);
2619 this->writeInstruction(SpvOpCompositeExtract, fieldTypeId, fieldL, lhs, index, out);
2620 SpvId fieldR = this->nextId(&fieldType);
2621 this->writeInstruction(SpvOpCompositeExtract, fieldTypeId, fieldR, rhs, index, out);
2622 // Use `writeBinaryExpression` with the requested == or != operator on these fields.
2623 SpvId comparison = this->writeBinaryExpression(fieldType, fieldL, op, fieldType, fieldR,
2624 boolType, out);
John Stiles35092102021-04-08 23:30:51 -04002625 // Merge this comparison result with all the other comparisons we've done.
2626 allComparisons = this->mergeComparisons(comparison, allComparisons, op, out);
John Stilesbc5c2a02021-04-08 11:44:53 -04002627 }
2628 return allComparisons;
2629}
2630
John Stiles35092102021-04-08 23:30:51 -04002631SpvId SPIRVCodeGenerator::mergeComparisons(SpvId comparison, SpvId allComparisons, Operator op,
2632 OutputStream& out) {
2633 // If this is the first entry, we don't need to merge comparison results with anything.
2634 if (allComparisons == (SpvId)-1) {
2635 return comparison;
2636 }
2637 // Use LogicalAnd or LogicalOr to combine the comparison with all the other comparisons.
2638 const Type& boolType = *fContext.fTypes.fBool;
2639 SpvId boolTypeId = this->getType(boolType);
2640 SpvId logicalOp = this->nextId(&boolType);
2641 switch (op.kind()) {
2642 case Token::Kind::TK_EQEQ:
2643 this->writeInstruction(SpvOpLogicalAnd, boolTypeId, logicalOp,
2644 comparison, allComparisons, out);
2645 break;
2646 case Token::Kind::TK_NEQ:
2647 this->writeInstruction(SpvOpLogicalOr, boolTypeId, logicalOp,
2648 comparison, allComparisons, out);
2649 break;
2650 default:
2651 SkDEBUGFAILF("mergeComparisons only supports == and !=, not %s", op.operatorName());
2652 return (SpvId)-1;
2653 }
2654 return logicalOp;
2655}
2656
John Stilesbc5c2a02021-04-08 11:44:53 -04002657static float division_by_literal_value(Operator op, const Expression& right) {
2658 // If this is a division by a literal value, returns that literal value. Otherwise, returns 0.
John Stiles7591d4b2021-09-13 13:32:06 -04002659 if (op.kind() == Token::Kind::TK_SLASH && right.isFloatLiteral()) {
2660 float rhsValue = right.as<Literal>().floatValue();
John Stilesbc5c2a02021-04-08 11:44:53 -04002661 if (std::isfinite(rhsValue)) {
2662 return rhsValue;
2663 }
2664 }
2665 return 0.0f;
2666}
2667
Ethan Nicholas49465b42019-04-17 12:22:21 -04002668SpvId SPIRVCodeGenerator::writeBinaryExpression(const BinaryExpression& b, OutputStream& out) {
John Stiles2396fb82021-03-25 11:44:55 -04002669 const Expression* left = b.left().get();
2670 const Expression* right = b.right().get();
John Stiles45990502021-02-16 10:55:27 -05002671 Operator op = b.getOperator();
John Stilesbc5c2a02021-04-08 11:44:53 -04002672
John Stiles45990502021-02-16 10:55:27 -05002673 switch (op.kind()) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002674 case Token::Kind::TK_EQ: {
John Stilesbc5c2a02021-04-08 11:44:53 -04002675 // Handles assignment.
John Stiles2396fb82021-03-25 11:44:55 -04002676 SpvId rhs = this->writeExpression(*right, out);
2677 this->getLValue(*left, out)->store(rhs, out);
Ethan Nicholas49465b42019-04-17 12:22:21 -04002678 return rhs;
2679 }
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002680 case Token::Kind::TK_LOGICALAND:
John Stilesbc5c2a02021-04-08 11:44:53 -04002681 // Handles short-circuiting; we don't necessarily evaluate both LHS and RHS.
2682 return this->writeLogicalAnd(*b.left(), *b.right(), out);
2683
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002684 case Token::Kind::TK_LOGICALOR:
John Stilesbc5c2a02021-04-08 11:44:53 -04002685 // Handles short-circuiting; we don't necessarily evaluate both LHS and RHS.
2686 return this->writeLogicalOr(*b.left(), *b.right(), out);
2687
Ethan Nicholas49465b42019-04-17 12:22:21 -04002688 default:
2689 break;
2690 }
2691
2692 std::unique_ptr<LValue> lvalue;
2693 SpvId lhs;
John Stiles45990502021-02-16 10:55:27 -05002694 if (op.isAssignment()) {
John Stiles2396fb82021-03-25 11:44:55 -04002695 lvalue = this->getLValue(*left, out);
Ethan Nicholas49465b42019-04-17 12:22:21 -04002696 lhs = lvalue->load(out);
2697 } else {
2698 lvalue = nullptr;
John Stiles2396fb82021-03-25 11:44:55 -04002699 lhs = this->writeExpression(*left, out);
Ethan Nicholas49465b42019-04-17 12:22:21 -04002700 }
John Stiles2396fb82021-03-25 11:44:55 -04002701
John Stilesbc5c2a02021-04-08 11:44:53 -04002702 SpvId rhs;
2703 float rhsValue = division_by_literal_value(op, *right);
2704 if (rhsValue != 0.0f) {
2705 // Rewrite floating-point division by a literal into multiplication by the reciprocal.
2706 // This converts `expr / 2` into `expr * 0.5`
2707 // This improves codegen, especially for certain types of divides (e.g. vector/scalar).
2708 op = Operator(Token::Kind::TK_STAR);
Ethan Nicholas89cfde12021-09-27 11:20:34 -04002709 Literal reciprocal{right->fLine, 1.0f / rhsValue, &right->type()};
John Stilesbc5c2a02021-04-08 11:44:53 -04002710 rhs = this->writeExpression(reciprocal, out);
2711 } else {
2712 // Write the right-hand side expression normally.
John Stiles2396fb82021-03-25 11:44:55 -04002713 rhs = this->writeExpression(*right, out);
2714 }
2715
2716 SpvId result = this->writeBinaryExpression(left->type(), lhs, op.removeAssignment(),
2717 right->type(), rhs, b.type(), out);
Ethan Nicholas49465b42019-04-17 12:22:21 -04002718 if (lvalue) {
2719 lvalue->store(result, out);
2720 }
2721 return result;
2722}
2723
John Stilesbc5c2a02021-04-08 11:44:53 -04002724SpvId SPIRVCodeGenerator::writeLogicalAnd(const Expression& left, const Expression& right,
2725 OutputStream& out) {
Ethan Nicholas89cfde12021-09-27 11:20:34 -04002726 Literal falseLiteral(/*line=*/-1, /*value=*/false, fContext.fTypes.fBool.get());
John Stiles7591d4b2021-09-13 13:32:06 -04002727 SpvId falseConstant = this->writeLiteral(falseLiteral);
John Stilesbc5c2a02021-04-08 11:44:53 -04002728 SpvId lhs = this->writeExpression(left, out);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002729 SpvId rhsLabel = this->nextId(nullptr);
2730 SpvId end = this->nextId(nullptr);
ethannicholasb3058bd2016-07-01 08:22:01 -07002731 SpvId lhsBlock = fCurrentBlock;
2732 this->writeInstruction(SpvOpSelectionMerge, end, SpvSelectionControlMaskNone, out);
2733 this->writeInstruction(SpvOpBranchConditional, lhs, rhsLabel, end, out);
2734 this->writeLabel(rhsLabel, out);
John Stilesbc5c2a02021-04-08 11:44:53 -04002735 SpvId rhs = this->writeExpression(right, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002736 SpvId rhsBlock = fCurrentBlock;
2737 this->writeInstruction(SpvOpBranch, end, out);
2738 this->writeLabel(end, out);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002739 SpvId result = this->nextId(nullptr);
John Stiles54e7c052021-01-11 14:22:36 -05002740 this->writeInstruction(SpvOpPhi, this->getType(*fContext.fTypes.fBool), result, falseConstant,
ethannicholasd598f792016-07-25 10:08:54 -07002741 lhsBlock, rhs, rhsBlock, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002742 return result;
2743}
2744
John Stilesbc5c2a02021-04-08 11:44:53 -04002745SpvId SPIRVCodeGenerator::writeLogicalOr(const Expression& left, const Expression& right,
2746 OutputStream& out) {
Ethan Nicholas89cfde12021-09-27 11:20:34 -04002747 Literal trueLiteral(/*line=*/-1, /*value=*/true, fContext.fTypes.fBool.get());
John Stiles7591d4b2021-09-13 13:32:06 -04002748 SpvId trueConstant = this->writeLiteral(trueLiteral);
John Stilesbc5c2a02021-04-08 11:44:53 -04002749 SpvId lhs = this->writeExpression(left, out);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002750 SpvId rhsLabel = this->nextId(nullptr);
2751 SpvId end = this->nextId(nullptr);
ethannicholasb3058bd2016-07-01 08:22:01 -07002752 SpvId lhsBlock = fCurrentBlock;
2753 this->writeInstruction(SpvOpSelectionMerge, end, SpvSelectionControlMaskNone, out);
2754 this->writeInstruction(SpvOpBranchConditional, lhs, end, rhsLabel, out);
2755 this->writeLabel(rhsLabel, out);
John Stilesbc5c2a02021-04-08 11:44:53 -04002756 SpvId rhs = this->writeExpression(right, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002757 SpvId rhsBlock = fCurrentBlock;
2758 this->writeInstruction(SpvOpBranch, end, out);
2759 this->writeLabel(end, out);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002760 SpvId result = this->nextId(nullptr);
John Stiles54e7c052021-01-11 14:22:36 -05002761 this->writeInstruction(SpvOpPhi, this->getType(*fContext.fTypes.fBool), result, trueConstant,
ethannicholasd598f792016-07-25 10:08:54 -07002762 lhsBlock, rhs, rhsBlock, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002763 return result;
2764}
2765
Ethan Nicholas0df1b042017-03-31 13:56:23 -04002766SpvId SPIRVCodeGenerator::writeTernaryExpression(const TernaryExpression& t, OutputStream& out) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04002767 const Type& type = t.type();
Ethan Nicholasdd218162020-10-08 05:48:01 -04002768 SpvId test = this->writeExpression(*t.test(), out);
2769 if (t.ifTrue()->type().columns() == 1 &&
2770 t.ifTrue()->isCompileTimeConstant() &&
2771 t.ifFalse()->isCompileTimeConstant()) {
ethannicholasb3058bd2016-07-01 08:22:01 -07002772 // both true and false are constants, can just use OpSelect
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002773 SpvId result = this->nextId(nullptr);
Ethan Nicholasdd218162020-10-08 05:48:01 -04002774 SpvId trueId = this->writeExpression(*t.ifTrue(), out);
2775 SpvId falseId = this->writeExpression(*t.ifFalse(), out);
Ethan Nicholas30d30222020-09-11 12:27:26 -04002776 this->writeInstruction(SpvOpSelect, this->getType(type), result, test, trueId, falseId,
ethannicholasb3058bd2016-07-01 08:22:01 -07002777 out);
2778 return result;
2779 }
Greg Daniel64773e62016-11-22 09:44:03 -05002780 // was originally using OpPhi to choose the result, but for some reason that is crashing on
ethannicholasb3058bd2016-07-01 08:22:01 -07002781 // Adreno. Switched to storing the result in a temp variable as glslang does.
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002782 SpvId var = this->nextId(nullptr);
Ethan Nicholas30d30222020-09-11 12:27:26 -04002783 this->writeInstruction(SpvOpVariable, this->getPointerType(type, SpvStorageClassFunction),
ethannicholasd598f792016-07-25 10:08:54 -07002784 var, SpvStorageClassFunction, fVariableBuffer);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002785 SpvId trueLabel = this->nextId(nullptr);
2786 SpvId falseLabel = this->nextId(nullptr);
2787 SpvId end = this->nextId(nullptr);
ethannicholasb3058bd2016-07-01 08:22:01 -07002788 this->writeInstruction(SpvOpSelectionMerge, end, SpvSelectionControlMaskNone, out);
2789 this->writeInstruction(SpvOpBranchConditional, test, trueLabel, falseLabel, out);
2790 this->writeLabel(trueLabel, out);
Ethan Nicholasdd218162020-10-08 05:48:01 -04002791 this->writeInstruction(SpvOpStore, var, this->writeExpression(*t.ifTrue(), out), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002792 this->writeInstruction(SpvOpBranch, end, out);
2793 this->writeLabel(falseLabel, out);
Ethan Nicholasdd218162020-10-08 05:48:01 -04002794 this->writeInstruction(SpvOpStore, var, this->writeExpression(*t.ifFalse(), out), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002795 this->writeInstruction(SpvOpBranch, end, out);
2796 this->writeLabel(end, out);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002797 SpvId result = this->nextId(&type);
Ethan Nicholas30d30222020-09-11 12:27:26 -04002798 this->writeInstruction(SpvOpLoad, this->getType(type), result, var, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002799 return result;
2800}
2801
Ethan Nicholas0df1b042017-03-31 13:56:23 -04002802SpvId SPIRVCodeGenerator::writePrefixExpression(const PrefixExpression& p, OutputStream& out) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04002803 const Type& type = p.type();
John Stiles45990502021-02-16 10:55:27 -05002804 if (p.getOperator().kind() == Token::Kind::TK_MINUS) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002805 SpvId result = this->nextId(&type);
Ethan Nicholas30d30222020-09-11 12:27:26 -04002806 SpvId typeId = this->getType(type);
Ethan Nicholas444ccc62020-10-09 10:16:22 -04002807 SpvId expr = this->writeExpression(*p.operand(), out);
Ethan Nicholas30d30222020-09-11 12:27:26 -04002808 if (is_float(fContext, type)) {
ethannicholasb3058bd2016-07-01 08:22:01 -07002809 this->writeInstruction(SpvOpFNegate, typeId, result, expr, out);
John Stiles43ac7e62021-08-25 12:43:22 -04002810 } else if (is_signed(fContext, type) || is_unsigned(fContext, type)) {
ethannicholasb3058bd2016-07-01 08:22:01 -07002811 this->writeInstruction(SpvOpSNegate, typeId, result, expr, out);
2812 } else {
John Stileseada7bc2021-02-02 16:29:32 -05002813 SkDEBUGFAILF("unsupported prefix expression %s", p.description().c_str());
Brian Salomon23356442018-11-30 15:33:19 -05002814 }
ethannicholasb3058bd2016-07-01 08:22:01 -07002815 return result;
2816 }
John Stiles45990502021-02-16 10:55:27 -05002817 switch (p.getOperator().kind()) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002818 case Token::Kind::TK_PLUS:
Ethan Nicholas444ccc62020-10-09 10:16:22 -04002819 return this->writeExpression(*p.operand(), out);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002820 case Token::Kind::TK_PLUSPLUS: {
Ethan Nicholas444ccc62020-10-09 10:16:22 -04002821 std::unique_ptr<LValue> lv = this->getLValue(*p.operand(), out);
Ethan Nicholas30d30222020-09-11 12:27:26 -04002822 SpvId one = this->writeExpression(*create_literal_1(fContext, type), out);
2823 SpvId result = this->writeBinaryOperation(type, type, lv->load(out), one,
Greg Daniel64773e62016-11-22 09:44:03 -05002824 SpvOpFAdd, SpvOpIAdd, SpvOpIAdd, SpvOpUndef,
ethannicholasb3058bd2016-07-01 08:22:01 -07002825 out);
2826 lv->store(result, out);
2827 return result;
2828 }
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002829 case Token::Kind::TK_MINUSMINUS: {
Ethan Nicholas444ccc62020-10-09 10:16:22 -04002830 std::unique_ptr<LValue> lv = this->getLValue(*p.operand(), out);
Ethan Nicholas30d30222020-09-11 12:27:26 -04002831 SpvId one = this->writeExpression(*create_literal_1(fContext, type), out);
2832 SpvId result = this->writeBinaryOperation(type, type, lv->load(out), one, SpvOpFSub,
2833 SpvOpISub, SpvOpISub, SpvOpUndef, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002834 lv->store(result, out);
2835 return result;
2836 }
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002837 case Token::Kind::TK_LOGICALNOT: {
John Stiles4a7dc462020-11-25 11:08:08 -05002838 SkASSERT(p.operand()->type().isBoolean());
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002839 SpvId result = this->nextId(nullptr);
Ethan Nicholas444ccc62020-10-09 10:16:22 -04002840 this->writeInstruction(SpvOpLogicalNot, this->getType(type), result,
2841 this->writeExpression(*p.operand(), out), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002842 return result;
2843 }
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002844 case Token::Kind::TK_BITWISENOT: {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002845 SpvId result = this->nextId(nullptr);
Ethan Nicholas444ccc62020-10-09 10:16:22 -04002846 this->writeInstruction(SpvOpNot, this->getType(type), result,
2847 this->writeExpression(*p.operand(), out), out);
ethannicholas5961bc92016-10-12 06:39:56 -07002848 return result;
2849 }
ethannicholasb3058bd2016-07-01 08:22:01 -07002850 default:
John Stileseada7bc2021-02-02 16:29:32 -05002851 SkDEBUGFAILF("unsupported prefix expression: %s", p.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -05002852 return -1;
ethannicholasb3058bd2016-07-01 08:22:01 -07002853 }
2854}
2855
Ethan Nicholas0df1b042017-03-31 13:56:23 -04002856SpvId SPIRVCodeGenerator::writePostfixExpression(const PostfixExpression& p, OutputStream& out) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04002857 const Type& type = p.type();
Ethan Nicholas444ccc62020-10-09 10:16:22 -04002858 std::unique_ptr<LValue> lv = this->getLValue(*p.operand(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002859 SpvId result = lv->load(out);
Ethan Nicholas30d30222020-09-11 12:27:26 -04002860 SpvId one = this->writeExpression(*create_literal_1(fContext, type), out);
John Stiles45990502021-02-16 10:55:27 -05002861 switch (p.getOperator().kind()) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002862 case Token::Kind::TK_PLUSPLUS: {
Ethan Nicholas30d30222020-09-11 12:27:26 -04002863 SpvId temp = this->writeBinaryOperation(type, type, result, one, SpvOpFAdd,
ethannicholasb3058bd2016-07-01 08:22:01 -07002864 SpvOpIAdd, SpvOpIAdd, SpvOpUndef, out);
2865 lv->store(temp, out);
2866 return result;
2867 }
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002868 case Token::Kind::TK_MINUSMINUS: {
Ethan Nicholas30d30222020-09-11 12:27:26 -04002869 SpvId temp = this->writeBinaryOperation(type, type, result, one, SpvOpFSub,
ethannicholasb3058bd2016-07-01 08:22:01 -07002870 SpvOpISub, SpvOpISub, SpvOpUndef, out);
2871 lv->store(temp, out);
2872 return result;
2873 }
2874 default:
John Stileseada7bc2021-02-02 16:29:32 -05002875 SkDEBUGFAILF("unsupported postfix expression %s", p.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -05002876 return -1;
ethannicholasb3058bd2016-07-01 08:22:01 -07002877 }
2878}
2879
John Stiles7591d4b2021-09-13 13:32:06 -04002880SpvId SPIRVCodeGenerator::writeLiteral(const Literal& l) {
2881 int32_t valueBits;
2882 if (l.isFloatLiteral()) {
2883 float value = l.floatValue();
2884 memcpy(&valueBits, &value, sizeof(valueBits));
2885 } else if (l.isIntLiteral()) {
2886 // intValue() returns a 64-bit signed value, which will be truncated here.
2887 // The hash key also contains the numberKind, so -1 won't overlap with 0xFFFFFFFFu.
2888 valueBits = l.intValue();
ethannicholasb3058bd2016-07-01 08:22:01 -07002889 } else {
John Stiles7591d4b2021-09-13 13:32:06 -04002890 valueBits = l.boolValue();
2891 }
2892
2893 SPIRVNumberConstant key{valueBits, l.type().numberKind()};
2894 auto [iter, newlyCreated] = fNumberConstants.insert({key, (SpvId)-1});
2895 if (newlyCreated) {
2896 SpvId result = this->nextId(nullptr);
2897 iter->second = result;
2898
2899 if (l.isBoolLiteral()) {
2900 this->writeInstruction(l.boolValue() ? SpvOpConstantTrue : SpvOpConstantFalse,
2901 this->getType(l.type()), result, fConstantBuffer);
2902 } else {
2903 this->writeInstruction(SpvOpConstant, this->getType(l.type()), result,
2904 (SpvId)valueBits, fConstantBuffer);
ethannicholasb3058bd2016-07-01 08:22:01 -07002905 }
ethannicholasb3058bd2016-07-01 08:22:01 -07002906 }
ethannicholasb3058bd2016-07-01 08:22:01 -07002907
John Stilesacb091f2021-01-06 11:57:58 -05002908 return iter->second;
ethannicholasb3058bd2016-07-01 08:22:01 -07002909}
2910
Ethan Nicholas0df1b042017-03-31 13:56:23 -04002911SpvId SPIRVCodeGenerator::writeFunctionStart(const FunctionDeclaration& f, OutputStream& out) {
ethannicholasd598f792016-07-25 10:08:54 -07002912 SpvId result = fFunctionMap[&f];
John Stilesb5db4822021-01-21 13:04:40 -05002913 SpvId returnTypeId = this->getType(f.returnType());
2914 SpvId functionTypeId = this->getFunctionType(f);
2915 this->writeInstruction(SpvOpFunction, returnTypeId, result,
2916 SpvFunctionControlMaskNone, functionTypeId, out);
John Stilesf9e85512021-03-22 12:05:31 -04002917 String mangledName = f.mangledName();
2918 this->writeInstruction(SpvOpName,
2919 result,
Ethan Nicholas962dec42021-06-10 13:06:39 -04002920 skstd::string_view(mangledName.c_str(), mangledName.size()),
John Stilesf9e85512021-03-22 12:05:31 -04002921 fNameBuffer);
2922 for (const Variable* parameter : f.parameters()) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002923 SpvId id = this->nextId(nullptr);
John Stilesf9e85512021-03-22 12:05:31 -04002924 fVariableMap[parameter] = id;
2925 SpvId type = this->getPointerType(parameter->type(), SpvStorageClassFunction);
ethannicholasb3058bd2016-07-01 08:22:01 -07002926 this->writeInstruction(SpvOpFunctionParameter, type, id, out);
2927 }
2928 return result;
2929}
2930
Ethan Nicholas0df1b042017-03-31 13:56:23 -04002931SpvId SPIRVCodeGenerator::writeFunction(const FunctionDefinition& f, OutputStream& out) {
2932 fVariableBuffer.reset();
Ethan Nicholas0a5d0962020-10-14 13:33:18 -04002933 SpvId result = this->writeFunctionStart(f.declaration(), out);
Ethan Nicholas7fb39362020-12-16 15:25:19 -05002934 fCurrentBlock = 0;
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002935 this->writeLabel(this->nextId(nullptr), out);
Ethan Nicholas0df1b042017-03-31 13:56:23 -04002936 StringStream bodyBuffer;
John Stiles0693fb82021-01-22 18:27:52 -05002937 this->writeBlock(f.body()->as<Block>(), bodyBuffer);
Ethan Nicholas0df1b042017-03-31 13:56:23 -04002938 write_stringstream(fVariableBuffer, out);
John Stilese8da4d22021-03-24 09:19:45 -04002939 if (f.declaration().isMain()) {
Ethan Nicholas8eb64d32018-12-21 14:50:42 -05002940 write_stringstream(fGlobalInitializersBuffer, out);
2941 }
Ethan Nicholas0df1b042017-03-31 13:56:23 -04002942 write_stringstream(bodyBuffer, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002943 if (fCurrentBlock) {
John Stiles2558c462021-03-16 17:49:20 -04002944 if (f.declaration().returnType().isVoid()) {
Ethan Nicholas70a44b22017-11-30 09:09:16 -05002945 this->writeInstruction(SpvOpReturn, out);
2946 } else {
2947 this->writeInstruction(SpvOpUnreachable, out);
2948 }
ethannicholasb3058bd2016-07-01 08:22:01 -07002949 }
2950 this->writeInstruction(SpvOpFunctionEnd, out);
2951 return result;
2952}
2953
2954void SPIRVCodeGenerator::writeLayout(const Layout& layout, SpvId target) {
2955 if (layout.fLocation >= 0) {
Greg Daniel64773e62016-11-22 09:44:03 -05002956 this->writeInstruction(SpvOpDecorate, target, SpvDecorationLocation, layout.fLocation,
ethannicholasb3058bd2016-07-01 08:22:01 -07002957 fDecorationBuffer);
2958 }
2959 if (layout.fBinding >= 0) {
Greg Daniel64773e62016-11-22 09:44:03 -05002960 this->writeInstruction(SpvOpDecorate, target, SpvDecorationBinding, layout.fBinding,
ethannicholasb3058bd2016-07-01 08:22:01 -07002961 fDecorationBuffer);
2962 }
2963 if (layout.fIndex >= 0) {
Greg Daniel64773e62016-11-22 09:44:03 -05002964 this->writeInstruction(SpvOpDecorate, target, SpvDecorationIndex, layout.fIndex,
ethannicholasb3058bd2016-07-01 08:22:01 -07002965 fDecorationBuffer);
2966 }
2967 if (layout.fSet >= 0) {
Greg Daniel64773e62016-11-22 09:44:03 -05002968 this->writeInstruction(SpvOpDecorate, target, SpvDecorationDescriptorSet, layout.fSet,
ethannicholasb3058bd2016-07-01 08:22:01 -07002969 fDecorationBuffer);
2970 }
Greg Daniel64773e62016-11-22 09:44:03 -05002971 if (layout.fInputAttachmentIndex >= 0) {
2972 this->writeInstruction(SpvOpDecorate, target, SpvDecorationInputAttachmentIndex,
2973 layout.fInputAttachmentIndex, fDecorationBuffer);
Ethan Nicholasbe1099f2018-01-11 16:09:05 -05002974 fCapabilities |= (((uint64_t) 1) << SpvCapabilityInputAttachment);
Greg Daniel64773e62016-11-22 09:44:03 -05002975 }
Brian Osman99ddd2a2021-08-27 11:21:12 -04002976 if (layout.fBuiltin >= 0 && layout.fBuiltin != SK_FRAGCOLOR_BUILTIN) {
Greg Daniel64773e62016-11-22 09:44:03 -05002977 this->writeInstruction(SpvOpDecorate, target, SpvDecorationBuiltIn, layout.fBuiltin,
ethannicholasb3058bd2016-07-01 08:22:01 -07002978 fDecorationBuffer);
2979 }
2980}
2981
2982void SPIRVCodeGenerator::writeLayout(const Layout& layout, SpvId target, int member) {
2983 if (layout.fLocation >= 0) {
Greg Daniel64773e62016-11-22 09:44:03 -05002984 this->writeInstruction(SpvOpMemberDecorate, target, member, SpvDecorationLocation,
ethannicholasb3058bd2016-07-01 08:22:01 -07002985 layout.fLocation, fDecorationBuffer);
2986 }
2987 if (layout.fBinding >= 0) {
Greg Daniel64773e62016-11-22 09:44:03 -05002988 this->writeInstruction(SpvOpMemberDecorate, target, member, SpvDecorationBinding,
ethannicholasb3058bd2016-07-01 08:22:01 -07002989 layout.fBinding, fDecorationBuffer);
2990 }
2991 if (layout.fIndex >= 0) {
Greg Daniel64773e62016-11-22 09:44:03 -05002992 this->writeInstruction(SpvOpMemberDecorate, target, member, SpvDecorationIndex,
ethannicholasb3058bd2016-07-01 08:22:01 -07002993 layout.fIndex, fDecorationBuffer);
2994 }
2995 if (layout.fSet >= 0) {
Greg Daniel64773e62016-11-22 09:44:03 -05002996 this->writeInstruction(SpvOpMemberDecorate, target, member, SpvDecorationDescriptorSet,
ethannicholasb3058bd2016-07-01 08:22:01 -07002997 layout.fSet, fDecorationBuffer);
2998 }
Greg Daniel64773e62016-11-22 09:44:03 -05002999 if (layout.fInputAttachmentIndex >= 0) {
3000 this->writeInstruction(SpvOpDecorate, target, member, SpvDecorationInputAttachmentIndex,
3001 layout.fInputAttachmentIndex, fDecorationBuffer);
3002 }
ethannicholasb3058bd2016-07-01 08:22:01 -07003003 if (layout.fBuiltin >= 0) {
Greg Daniel64773e62016-11-22 09:44:03 -05003004 this->writeInstruction(SpvOpMemberDecorate, target, member, SpvDecorationBuiltIn,
ethannicholasb3058bd2016-07-01 08:22:01 -07003005 layout.fBuiltin, fDecorationBuffer);
3006 }
3007}
3008
Brian Osman2a4c0fb2021-01-22 13:41:40 -05003009MemoryLayout SPIRVCodeGenerator::memoryLayoutForVariable(const Variable& v) const {
Brian Osman2a4c0fb2021-01-22 13:41:40 -05003010 bool pushConstant = ((v.modifiers().fLayout.fFlags & Layout::kPushConstant_Flag) != 0);
Brian Osman58ee8982021-02-18 15:39:38 -05003011 return pushConstant ? MemoryLayout(MemoryLayout::k430_Standard) : fDefaultLayout;
Brian Osman2a4c0fb2021-01-22 13:41:40 -05003012}
3013
Brian Salomond8d85b92021-07-07 09:41:17 -04003014SpvId SPIRVCodeGenerator::writeInterfaceBlock(const InterfaceBlock& intf, bool appendRTFlip) {
Brian Osman2a4c0fb2021-01-22 13:41:40 -05003015 MemoryLayout memoryLayout = this->memoryLayoutForVariable(intf.variable());
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04003016 SpvId result = this->nextId(nullptr);
Brian Salomond8d85b92021-07-07 09:41:17 -04003017 const Variable& intfVar = intf.variable();
3018 const Type& type = intfVar.type();
3019 if (!MemoryLayout::LayoutIsSupported(type)) {
Ethan Nicholas89cfde12021-09-27 11:20:34 -04003020 fContext.fErrors->error(type.fLine, "type '" + type.name() + "' is not permitted here");
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04003021 return this->nextId(nullptr);
John Stiles0023c0c2020-11-16 13:32:18 -05003022 }
John Stiles9485b552021-01-27 11:47:00 -05003023 SpvStorageClass_ storageClass = get_storage_class(intf.variable(), SpvStorageClassFunction);
John Stilesded41aa2021-08-05 12:19:35 -04003024 if (fProgram.fInputs.fUseFlipRTUniform && appendRTFlip && type.isStruct()) {
Brian Salomond8d85b92021-07-07 09:41:17 -04003025 // We can only have one interface block (because we use push_constant and that is limited
3026 // to one per program), so we need to append rtflip to this one rather than synthesize an
3027 // entirely new block when the variable is referenced. And we can't modify the existing
3028 // block, so we instead create a modified copy of it and write that.
3029 std::vector<Type::Field> fields = type.fields();
3030 fields.emplace_back(Modifiers(Layout(/*flags=*/0,
3031 /*location=*/-1,
3032 fProgram.fConfig->fSettings.fRTFlipOffset,
3033 /*binding=*/-1,
3034 /*index=*/-1,
3035 /*set=*/-1,
3036 /*builtin=*/-1,
Brian Osman99ddd2a2021-08-27 11:21:12 -04003037 /*inputAttachmentIndex=*/-1),
Brian Salomond8d85b92021-07-07 09:41:17 -04003038 /*flags=*/0),
3039 SKSL_RTFLIP_NAME,
3040 fContext.fTypes.fFloat2.get());
John Stiles0cac5ed2021-08-06 11:40:39 -04003041 {
3042 AutoAttachPoolToThread attach(fProgram.fPool.get());
3043 const Type* rtFlipStructType = fProgram.fSymbols->takeOwnershipOfSymbol(
Ethan Nicholas89cfde12021-09-27 11:20:34 -04003044 Type::MakeStructType(type.fLine, type.name(), std::move(fields)));
John Stiles0cac5ed2021-08-06 11:40:39 -04003045 const Variable* modifiedVar = fProgram.fSymbols->takeOwnershipOfSymbol(
Ethan Nicholas89cfde12021-09-27 11:20:34 -04003046 std::make_unique<Variable>(intfVar.fLine,
John Stiles0cac5ed2021-08-06 11:40:39 -04003047 &intfVar.modifiers(),
3048 intfVar.name(),
3049 rtFlipStructType,
3050 intfVar.isBuiltin(),
3051 intfVar.storage()));
3052 fSPIRVBonusVariables.insert(modifiedVar);
Ethan Nicholas89cfde12021-09-27 11:20:34 -04003053 InterfaceBlock modifiedCopy(intf.fLine,
Ethan Nicholas2816dcf2021-09-21 09:18:47 -04003054 *modifiedVar,
John Stiles0cac5ed2021-08-06 11:40:39 -04003055 intf.typeName(),
3056 intf.instanceName(),
3057 intf.arraySize(),
3058 intf.typeOwner());
3059 result = this->writeInterfaceBlock(modifiedCopy, false);
3060 fProgram.fSymbols->add(std::make_unique<Field>(
Ethan Nicholas89cfde12021-09-27 11:20:34 -04003061 /*line=*/-1, modifiedVar, rtFlipStructType->fields().size() - 1));
Brian Salomond8d85b92021-07-07 09:41:17 -04003062 }
3063 fVariableMap[&intfVar] = result;
3064 fWroteRTFlip = true;
3065 return result;
Ethan Nicholas941e7e22016-12-12 15:33:30 -05003066 }
Brian Salomond8d85b92021-07-07 09:41:17 -04003067 const Modifiers& intfModifiers = intfVar.modifiers();
Brian Osman99ddd2a2021-08-27 11:21:12 -04003068 SpvId typeId = this->getType(type, memoryLayout);
Brian Osman58ee8982021-02-18 15:39:38 -05003069 if (intfModifiers.fLayout.fBuiltin == -1) {
Ethan Nicholas6ac8d362019-01-22 21:43:55 +00003070 this->writeInstruction(SpvOpDecorate, typeId, SpvDecorationBlock, fDecorationBuffer);
Ethan Nicholas0dd30d92017-05-01 16:57:07 -04003071 }
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04003072 SpvId ptrType = this->nextId(nullptr);
Ethan Nicholas941e7e22016-12-12 15:33:30 -05003073 this->writeInstruction(SpvOpTypePointer, ptrType, storageClass, typeId, fConstantBuffer);
ethannicholasb3058bd2016-07-01 08:22:01 -07003074 this->writeInstruction(SpvOpVariable, ptrType, result, storageClass, fConstantBuffer);
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04003075 Layout layout = intfModifiers.fLayout;
3076 if (intfModifiers.fFlags & Modifiers::kUniform_Flag && layout.fSet == -1) {
Ethan Nicholas8d2ba442018-03-16 16:40:36 -04003077 layout.fSet = 0;
3078 }
3079 this->writeLayout(layout, result);
Brian Salomond8d85b92021-07-07 09:41:17 -04003080 fVariableMap[&intfVar] = result;
ethannicholasb3058bd2016-07-01 08:22:01 -07003081 return result;
3082}
3083
John Stilesd7437ee2021-08-02 11:56:16 -04003084bool SPIRVCodeGenerator::isDead(const Variable& var) const {
3085 // During SPIR-V code generation, we synthesize some extra bonus variables that don't actually
3086 // exist in the Program at all and aren't tracked by the ProgramUsage. They aren't dead, though.
3087 if (fSPIRVBonusVariables.count(&var)) {
3088 return false;
3089 }
3090 ProgramUsage::VariableCounts counts = fProgram.usage()->get(var);
Brian Osman010ce6a2020-10-19 16:34:10 -04003091 if (counts.fRead || counts.fWrite) {
Chris Dalton2284aab2019-11-15 11:02:24 -07003092 return false;
3093 }
Brian Osmand1f3b972021-03-22 17:03:42 -04003094 // It's not entirely clear what the rules are for eliding interface variables. Generally, it
3095 // causes problems to elide them, even when they're dead.
3096 return !(var.modifiers().fFlags &
3097 (Modifiers::kIn_Flag | Modifiers::kOut_Flag | Modifiers::kUniform_Flag));
Chris Dalton2284aab2019-11-15 11:02:24 -07003098}
3099
John Stilesdbd4e6f2021-02-16 13:29:15 -05003100void SPIRVCodeGenerator::writeGlobalVar(ProgramKind kind, const VarDeclaration& varDecl) {
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04003101 const Variable& var = varDecl.var();
John Stiles0ca2f592021-01-27 10:58:10 -05003102 // 9999 is a sentinel value used in our built-in modules that causes us to ignore these
3103 // declarations, beyond adding them to the symbol table.
3104 constexpr int kBuiltinIgnore = 9999;
3105 if (var.modifiers().fLayout.fBuiltin == kBuiltinIgnore) {
Brian Osmanc0213602020-10-06 14:43:32 -04003106 return;
3107 }
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04003108 if (var.modifiers().fLayout.fBuiltin == SK_FRAGCOLOR_BUILTIN &&
John Stilesdbd4e6f2021-02-16 13:29:15 -05003109 kind != ProgramKind::kFragment) {
John Stiles270cec22021-02-17 12:59:36 -05003110 SkASSERT(!fProgram.fConfig->fSettings.fFragColorIsInOut);
Brian Osmanc0213602020-10-06 14:43:32 -04003111 return;
3112 }
John Stilesd7437ee2021-08-02 11:56:16 -04003113 if (this->isDead(var)) {
Brian Osmanc0213602020-10-06 14:43:32 -04003114 return;
3115 }
John Stiles0de76f72021-01-29 09:19:39 -05003116 SpvStorageClass_ storageClass = get_storage_class(var, SpvStorageClassPrivate);
John Stilese40d1662021-01-29 10:08:50 -05003117 if (storageClass == SpvStorageClassUniform) {
3118 // Top-level uniforms are emitted in writeUniformBuffer.
3119 fTopLevelUniforms.push_back(&varDecl);
3120 return;
3121 }
3122 const Type& type = var.type();
John Stilesd8fc95d2021-01-26 16:22:53 -05003123 Layout layout = var.modifiers().fLayout;
John Stilese40d1662021-01-29 10:08:50 -05003124 if (layout.fSet < 0 && storageClass == SpvStorageClassUniformConstant) {
John Stiles270cec22021-02-17 12:59:36 -05003125 layout.fSet = fProgram.fConfig->fSettings.fDefaultUniformSet;
Brian Osmanc0213602020-10-06 14:43:32 -04003126 }
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04003127 SpvId id = this->nextId(&type);
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04003128 fVariableMap[&var] = id;
Brian Osman99ddd2a2021-08-27 11:21:12 -04003129 SpvId typeId = this->getPointerType(type, storageClass);
Brian Osmanc0213602020-10-06 14:43:32 -04003130 this->writeInstruction(SpvOpVariable, typeId, id, storageClass, fConstantBuffer);
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04003131 this->writeInstruction(SpvOpName, id, var.name(), fNameBuffer);
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04003132 if (varDecl.value()) {
Brian Osmanc0213602020-10-06 14:43:32 -04003133 SkASSERT(!fCurrentBlock);
3134 fCurrentBlock = -1;
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04003135 SpvId value = this->writeExpression(*varDecl.value(), fGlobalInitializersBuffer);
Brian Osmanc0213602020-10-06 14:43:32 -04003136 this->writeInstruction(SpvOpStore, id, value, fGlobalInitializersBuffer);
3137 fCurrentBlock = 0;
3138 }
John Stilesd8fc95d2021-01-26 16:22:53 -05003139 this->writeLayout(layout, id);
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04003140 if (var.modifiers().fFlags & Modifiers::kFlat_Flag) {
Brian Osmanc0213602020-10-06 14:43:32 -04003141 this->writeInstruction(SpvOpDecorate, id, SpvDecorationFlat, fDecorationBuffer);
3142 }
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04003143 if (var.modifiers().fFlags & Modifiers::kNoPerspective_Flag) {
Brian Osmanc0213602020-10-06 14:43:32 -04003144 this->writeInstruction(SpvOpDecorate, id, SpvDecorationNoPerspective,
3145 fDecorationBuffer);
ethannicholasb3058bd2016-07-01 08:22:01 -07003146 }
3147}
3148
Brian Osmanc0213602020-10-06 14:43:32 -04003149void SPIRVCodeGenerator::writeVarDeclaration(const VarDeclaration& varDecl, OutputStream& out) {
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04003150 const Variable& var = varDecl.var();
Ethan Nicholas7f015882021-03-23 14:16:52 -04003151 SpvId id = this->nextId(&var.type());
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04003152 fVariableMap[&var] = id;
3153 SpvId type = this->getPointerType(var.type(), SpvStorageClassFunction);
Brian Osmanc0213602020-10-06 14:43:32 -04003154 this->writeInstruction(SpvOpVariable, type, id, SpvStorageClassFunction, fVariableBuffer);
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04003155 this->writeInstruction(SpvOpName, id, var.name(), fNameBuffer);
3156 if (varDecl.value()) {
3157 SpvId value = this->writeExpression(*varDecl.value(), out);
Brian Osmanc0213602020-10-06 14:43:32 -04003158 this->writeInstruction(SpvOpStore, id, value, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003159 }
3160}
3161
Ethan Nicholas0df1b042017-03-31 13:56:23 -04003162void SPIRVCodeGenerator::writeStatement(const Statement& s, OutputStream& out) {
Ethan Nicholase6592142020-09-08 10:22:09 -04003163 switch (s.kind()) {
John Stiles98c1f822020-09-09 14:18:53 -04003164 case Statement::Kind::kInlineMarker:
Ethan Nicholase6592142020-09-08 10:22:09 -04003165 case Statement::Kind::kNop:
Ethan Nicholascb670962017-04-20 19:31:52 -04003166 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04003167 case Statement::Kind::kBlock:
John Stiles0693fb82021-01-22 18:27:52 -05003168 this->writeBlock(s.as<Block>(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003169 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04003170 case Statement::Kind::kExpression:
Ethan Nicholasd503a5a2020-09-30 09:29:55 -04003171 this->writeExpression(*s.as<ExpressionStatement>().expression(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003172 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04003173 case Statement::Kind::kReturn:
John Stiles26f98502020-08-18 09:30:51 -04003174 this->writeReturnStatement(s.as<ReturnStatement>(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003175 break;
Brian Osmanc0213602020-10-06 14:43:32 -04003176 case Statement::Kind::kVarDeclaration:
3177 this->writeVarDeclaration(s.as<VarDeclaration>(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003178 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04003179 case Statement::Kind::kIf:
John Stiles26f98502020-08-18 09:30:51 -04003180 this->writeIfStatement(s.as<IfStatement>(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003181 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04003182 case Statement::Kind::kFor:
John Stiles26f98502020-08-18 09:30:51 -04003183 this->writeForStatement(s.as<ForStatement>(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003184 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04003185 case Statement::Kind::kDo:
John Stiles26f98502020-08-18 09:30:51 -04003186 this->writeDoStatement(s.as<DoStatement>(), out);
Ethan Nicholasfd146aa2017-01-13 16:40:35 -05003187 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04003188 case Statement::Kind::kSwitch:
John Stiles26f98502020-08-18 09:30:51 -04003189 this->writeSwitchStatement(s.as<SwitchStatement>(), out);
Ethan Nicholase92b1b12017-11-13 16:13:21 -05003190 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04003191 case Statement::Kind::kBreak:
ethannicholasb3058bd2016-07-01 08:22:01 -07003192 this->writeInstruction(SpvOpBranch, fBreakTarget.top(), out);
3193 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04003194 case Statement::Kind::kContinue:
ethannicholasb3058bd2016-07-01 08:22:01 -07003195 this->writeInstruction(SpvOpBranch, fContinueTarget.top(), out);
3196 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04003197 case Statement::Kind::kDiscard:
ethannicholasb3058bd2016-07-01 08:22:01 -07003198 this->writeInstruction(SpvOpKill, out);
3199 break;
3200 default:
John Stileseada7bc2021-02-02 16:29:32 -05003201 SkDEBUGFAILF("unsupported statement: %s", s.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -05003202 break;
ethannicholasb3058bd2016-07-01 08:22:01 -07003203 }
3204}
3205
Ethan Nicholas0df1b042017-03-31 13:56:23 -04003206void SPIRVCodeGenerator::writeBlock(const Block& b, OutputStream& out) {
Ethan Nicholas7bd60432020-09-25 14:31:59 -04003207 for (const std::unique_ptr<Statement>& stmt : b.children()) {
3208 this->writeStatement(*stmt, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003209 }
3210}
3211
Ethan Nicholas0df1b042017-03-31 13:56:23 -04003212void SPIRVCodeGenerator::writeIfStatement(const IfStatement& stmt, OutputStream& out) {
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04003213 SpvId test = this->writeExpression(*stmt.test(), out);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04003214 SpvId ifTrue = this->nextId(nullptr);
3215 SpvId ifFalse = this->nextId(nullptr);
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04003216 if (stmt.ifFalse()) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04003217 SpvId end = this->nextId(nullptr);
ethannicholasb3058bd2016-07-01 08:22:01 -07003218 this->writeInstruction(SpvOpSelectionMerge, end, SpvSelectionControlMaskNone, out);
3219 this->writeInstruction(SpvOpBranchConditional, test, ifTrue, ifFalse, out);
3220 this->writeLabel(ifTrue, out);
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04003221 this->writeStatement(*stmt.ifTrue(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003222 if (fCurrentBlock) {
3223 this->writeInstruction(SpvOpBranch, end, out);
3224 }
3225 this->writeLabel(ifFalse, out);
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04003226 this->writeStatement(*stmt.ifFalse(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003227 if (fCurrentBlock) {
3228 this->writeInstruction(SpvOpBranch, end, out);
3229 }
3230 this->writeLabel(end, out);
3231 } else {
3232 this->writeInstruction(SpvOpSelectionMerge, ifFalse, SpvSelectionControlMaskNone, out);
3233 this->writeInstruction(SpvOpBranchConditional, test, ifTrue, ifFalse, out);
3234 this->writeLabel(ifTrue, out);
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04003235 this->writeStatement(*stmt.ifTrue(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003236 if (fCurrentBlock) {
3237 this->writeInstruction(SpvOpBranch, ifFalse, out);
3238 }
3239 this->writeLabel(ifFalse, out);
3240 }
3241}
3242
Ethan Nicholas0df1b042017-03-31 13:56:23 -04003243void SPIRVCodeGenerator::writeForStatement(const ForStatement& f, OutputStream& out) {
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04003244 if (f.initializer()) {
3245 this->writeStatement(*f.initializer(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003246 }
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04003247 SpvId header = this->nextId(nullptr);
3248 SpvId start = this->nextId(nullptr);
3249 SpvId body = this->nextId(nullptr);
3250 SpvId next = this->nextId(nullptr);
ethannicholasb3058bd2016-07-01 08:22:01 -07003251 fContinueTarget.push(next);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04003252 SpvId end = this->nextId(nullptr);
ethannicholasb3058bd2016-07-01 08:22:01 -07003253 fBreakTarget.push(end);
3254 this->writeInstruction(SpvOpBranch, header, out);
3255 this->writeLabel(header, out);
3256 this->writeInstruction(SpvOpLoopMerge, end, next, SpvLoopControlMaskNone, out);
ethannicholasf789b382016-08-03 12:43:36 -07003257 this->writeInstruction(SpvOpBranch, start, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003258 this->writeLabel(start, out);
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04003259 if (f.test()) {
3260 SpvId test = this->writeExpression(*f.test(), out);
ethannicholas22f939e2016-10-13 13:25:34 -07003261 this->writeInstruction(SpvOpBranchConditional, test, body, end, out);
Ethan Nicholas7fb39362020-12-16 15:25:19 -05003262 } else {
3263 this->writeInstruction(SpvOpBranch, body, out);
ethannicholas22f939e2016-10-13 13:25:34 -07003264 }
ethannicholasb3058bd2016-07-01 08:22:01 -07003265 this->writeLabel(body, out);
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04003266 this->writeStatement(*f.statement(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003267 if (fCurrentBlock) {
3268 this->writeInstruction(SpvOpBranch, next, out);
3269 }
3270 this->writeLabel(next, out);
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04003271 if (f.next()) {
3272 this->writeExpression(*f.next(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003273 }
3274 this->writeInstruction(SpvOpBranch, header, out);
3275 this->writeLabel(end, out);
3276 fBreakTarget.pop();
3277 fContinueTarget.pop();
3278}
3279
Ethan Nicholas0df1b042017-03-31 13:56:23 -04003280void SPIRVCodeGenerator::writeDoStatement(const DoStatement& d, OutputStream& out) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04003281 SpvId header = this->nextId(nullptr);
3282 SpvId start = this->nextId(nullptr);
3283 SpvId next = this->nextId(nullptr);
3284 SpvId continueTarget = this->nextId(nullptr);
Ethan Nicholas0d997662019-04-08 09:46:01 -04003285 fContinueTarget.push(continueTarget);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04003286 SpvId end = this->nextId(nullptr);
Ethan Nicholasfd146aa2017-01-13 16:40:35 -05003287 fBreakTarget.push(end);
3288 this->writeInstruction(SpvOpBranch, header, out);
3289 this->writeLabel(header, out);
Ethan Nicholas0d997662019-04-08 09:46:01 -04003290 this->writeInstruction(SpvOpLoopMerge, end, continueTarget, SpvLoopControlMaskNone, out);
Ethan Nicholasfd146aa2017-01-13 16:40:35 -05003291 this->writeInstruction(SpvOpBranch, start, out);
3292 this->writeLabel(start, out);
Ethan Nicholas1fd61162020-09-28 13:14:19 -04003293 this->writeStatement(*d.statement(), out);
Ethan Nicholasfd146aa2017-01-13 16:40:35 -05003294 if (fCurrentBlock) {
3295 this->writeInstruction(SpvOpBranch, next, out);
3296 }
3297 this->writeLabel(next, out);
John Stiles68072a42021-04-16 17:25:55 -04003298 this->writeInstruction(SpvOpBranch, continueTarget, out);
Ethan Nicholas0d997662019-04-08 09:46:01 -04003299 this->writeLabel(continueTarget, out);
John Stiles68072a42021-04-16 17:25:55 -04003300 SpvId test = this->writeExpression(*d.test(), out);
3301 this->writeInstruction(SpvOpBranchConditional, test, header, end, out);
Ethan Nicholasfd146aa2017-01-13 16:40:35 -05003302 this->writeLabel(end, out);
3303 fBreakTarget.pop();
3304 fContinueTarget.pop();
3305}
3306
Ethan Nicholase92b1b12017-11-13 16:13:21 -05003307void SPIRVCodeGenerator::writeSwitchStatement(const SwitchStatement& s, OutputStream& out) {
Ethan Nicholas01b05e52020-10-22 15:53:41 -04003308 SpvId value = this->writeExpression(*s.value(), out);
Ethan Nicholase92b1b12017-11-13 16:13:21 -05003309 std::vector<SpvId> labels;
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04003310 SpvId end = this->nextId(nullptr);
Ethan Nicholase92b1b12017-11-13 16:13:21 -05003311 SpvId defaultLabel = end;
3312 fBreakTarget.push(end);
3313 int size = 3;
John Stiles2d4f9592020-10-30 10:29:12 -04003314 auto& cases = s.cases();
John Stilesb23a64b2021-03-11 08:27:59 -05003315 for (const std::unique_ptr<Statement>& stmt : cases) {
3316 const SwitchCase& c = stmt->as<SwitchCase>();
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04003317 SpvId label = this->nextId(nullptr);
Ethan Nicholase92b1b12017-11-13 16:13:21 -05003318 labels.push_back(label);
John Stilesb23a64b2021-03-11 08:27:59 -05003319 if (c.value()) {
Ethan Nicholase92b1b12017-11-13 16:13:21 -05003320 size += 2;
3321 } else {
3322 defaultLabel = label;
3323 }
3324 }
3325 labels.push_back(end);
3326 this->writeInstruction(SpvOpSelectionMerge, end, SpvSelectionControlMaskNone, out);
3327 this->writeOpCode(SpvOpSwitch, size, out);
3328 this->writeWord(value, out);
3329 this->writeWord(defaultLabel, out);
John Stiles2d4f9592020-10-30 10:29:12 -04003330 for (size_t i = 0; i < cases.size(); ++i) {
John Stilesb23a64b2021-03-11 08:27:59 -05003331 const SwitchCase& c = cases[i]->as<SwitchCase>();
3332 if (!c.value()) {
Ethan Nicholase92b1b12017-11-13 16:13:21 -05003333 continue;
3334 }
John Stiles7591d4b2021-09-13 13:32:06 -04003335 this->writeWord(c.value()->as<Literal>().intValue(), out);
Ethan Nicholase92b1b12017-11-13 16:13:21 -05003336 this->writeWord(labels[i], out);
3337 }
John Stiles2d4f9592020-10-30 10:29:12 -04003338 for (size_t i = 0; i < cases.size(); ++i) {
John Stilesb23a64b2021-03-11 08:27:59 -05003339 const SwitchCase& c = cases[i]->as<SwitchCase>();
Ethan Nicholase92b1b12017-11-13 16:13:21 -05003340 this->writeLabel(labels[i], out);
John Stilesb23a64b2021-03-11 08:27:59 -05003341 this->writeStatement(*c.statement(), out);
Ethan Nicholase92b1b12017-11-13 16:13:21 -05003342 if (fCurrentBlock) {
3343 this->writeInstruction(SpvOpBranch, labels[i + 1], out);
3344 }
3345 }
3346 this->writeLabel(end, out);
3347 fBreakTarget.pop();
3348}
3349
Ethan Nicholas0df1b042017-03-31 13:56:23 -04003350void SPIRVCodeGenerator::writeReturnStatement(const ReturnStatement& r, OutputStream& out) {
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04003351 if (r.expression()) {
3352 this->writeInstruction(SpvOpReturnValue, this->writeExpression(*r.expression(), out),
ethannicholasb3058bd2016-07-01 08:22:01 -07003353 out);
3354 } else {
3355 this->writeInstruction(SpvOpReturn, out);
3356 }
3357}
3358
John Stilese40d1662021-01-29 10:08:50 -05003359// Given any function, returns the top-level symbol table (OUTSIDE of the function's scope).
3360static std::shared_ptr<SymbolTable> get_top_level_symbol_table(const FunctionDeclaration& anyFunc) {
3361 return anyFunc.definition()->body()->as<Block>().symbolTable()->fParent;
3362}
3363
John Stiles4d6310a2021-01-26 19:58:22 -05003364SPIRVCodeGenerator::EntrypointAdapter SPIRVCodeGenerator::writeEntrypointAdapter(
3365 const FunctionDeclaration& main) {
3366 // Our goal is to synthesize a tiny helper function which looks like this:
3367 // void _entrypoint() { sk_FragColor = main(); }
3368
3369 // Fish a symbol table out of main().
John Stilese40d1662021-01-29 10:08:50 -05003370 std::shared_ptr<SymbolTable> symbolTable = get_top_level_symbol_table(main);
John Stiles4d6310a2021-01-26 19:58:22 -05003371
3372 // Get `sk_FragColor` as a writable reference.
3373 const Symbol* skFragColorSymbol = (*symbolTable)["sk_FragColor"];
3374 SkASSERT(skFragColorSymbol);
3375 const Variable& skFragColorVar = skFragColorSymbol->as<Variable>();
Ethan Nicholas89cfde12021-09-27 11:20:34 -04003376 auto skFragColorRef = std::make_unique<VariableReference>(/*line=*/-1, &skFragColorVar,
John Stiles4d6310a2021-01-26 19:58:22 -05003377 VariableReference::RefKind::kWrite);
3378 // Synthesize a call to the `main()` function.
3379 if (main.returnType() != skFragColorRef->type()) {
Ethan Nicholas89cfde12021-09-27 11:20:34 -04003380 fContext.fErrors->error(main.fLine, "SPIR-V does not support returning '" +
3381 main.returnType().description() + "' from main()");
John Stiles4d6310a2021-01-26 19:58:22 -05003382 return {};
3383 }
Brian Osman716aeb92021-04-21 13:20:00 -04003384 ExpressionArray args;
3385 if (main.parameters().size() == 1) {
3386 if (main.parameters()[0]->type() != *fContext.fTypes.fFloat2) {
Ethan Nicholas89cfde12021-09-27 11:20:34 -04003387 fContext.fErrors->error(main.fLine,
Ethan Nicholas3abc6c62021-08-13 11:20:09 -04003388 "SPIR-V does not support parameter of type '" +
3389 main.parameters()[0]->type().description() + "' to main()");
Brian Osman716aeb92021-04-21 13:20:00 -04003390 return {};
3391 }
John Stiles7591d4b2021-09-13 13:32:06 -04003392 args.push_back(dsl::Float2(0).release());
Brian Osman716aeb92021-04-21 13:20:00 -04003393 }
Ethan Nicholas89cfde12021-09-27 11:20:34 -04003394 auto callMainFn = std::make_unique<FunctionCall>(/*line=*/-1, &main.returnType(), &main,
Brian Osman716aeb92021-04-21 13:20:00 -04003395 std::move(args));
John Stiles4d6310a2021-01-26 19:58:22 -05003396
3397 // Synthesize `skFragColor = main()` as a BinaryExpression.
3398 auto assignmentStmt = std::make_unique<ExpressionStatement>(std::make_unique<BinaryExpression>(
Ethan Nicholas89cfde12021-09-27 11:20:34 -04003399 /*line=*/-1,
John Stiles4d6310a2021-01-26 19:58:22 -05003400 std::move(skFragColorRef),
3401 Token::Kind::TK_EQ,
3402 std::move(callMainFn),
3403 &main.returnType()));
3404
3405 // Function bodies are always wrapped in a Block.
3406 StatementArray entrypointStmts;
3407 entrypointStmts.push_back(std::move(assignmentStmt));
Ethan Nicholas89cfde12021-09-27 11:20:34 -04003408 auto entrypointBlock = Block::Make(/*line=*/-1, std::move(entrypointStmts),
John Stilesbf16b6c2021-03-12 19:24:31 -05003409 symbolTable, /*isScope=*/true);
John Stiles4d6310a2021-01-26 19:58:22 -05003410 // Declare an entrypoint function.
3411 EntrypointAdapter adapter;
3412 adapter.fLayout = {};
3413 adapter.fModifiers = Modifiers{adapter.fLayout, Modifiers::kHasSideEffects_Flag};
3414 adapter.entrypointDecl =
Ethan Nicholas89cfde12021-09-27 11:20:34 -04003415 std::make_unique<FunctionDeclaration>(/*line=*/-1,
John Stiles4d6310a2021-01-26 19:58:22 -05003416 &adapter.fModifiers,
3417 "_entrypoint",
3418 /*parameters=*/std::vector<const Variable*>{},
3419 /*returnType=*/fContext.fTypes.fVoid.get(),
3420 /*builtin=*/false);
3421 // Define it.
John Stiles3b204892021-08-27 17:35:35 -04003422 adapter.entrypointDef = FunctionDefinition::Convert(fContext,
Ethan Nicholas89cfde12021-09-27 11:20:34 -04003423 /*line=*/-1,
John Stiles3b204892021-08-27 17:35:35 -04003424 *adapter.entrypointDecl,
3425 std::move(entrypointBlock),
3426 /*builtin=*/false);
John Stiles4d6310a2021-01-26 19:58:22 -05003427
3428 adapter.entrypointDecl->setDefinition(adapter.entrypointDef.get());
3429 return adapter;
3430}
3431
John Stilese40d1662021-01-29 10:08:50 -05003432void SPIRVCodeGenerator::writeUniformBuffer(std::shared_ptr<SymbolTable> topLevelSymbolTable) {
3433 SkASSERT(!fTopLevelUniforms.empty());
3434 static constexpr char kUniformBufferName[] = "_UniformBuffer";
3435
3436 // Convert the list of top-level uniforms into a matching struct named _UniformBuffer, and build
3437 // a lookup table of variables to UniformBuffer field indices.
3438 std::vector<Type::Field> fields;
3439 fields.reserve(fTopLevelUniforms.size());
3440 fTopLevelUniformMap.reserve(fTopLevelUniforms.size());
3441 for (const VarDeclaration* topLevelUniform : fTopLevelUniforms) {
3442 const Variable* var = &topLevelUniform->var();
3443 fTopLevelUniformMap[var] = (int)fields.size();
3444 fields.emplace_back(var->modifiers(), var->name(), &var->type());
3445 }
Ethan Nicholas89cfde12021-09-27 11:20:34 -04003446 fUniformBuffer.fStruct = Type::MakeStructType(/*line=*/-1, kUniformBufferName,
John Stilese40d1662021-01-29 10:08:50 -05003447 std::move(fields));
3448
3449 // Create a global variable to contain this struct.
3450 Layout layout;
John Stiles270cec22021-02-17 12:59:36 -05003451 layout.fBinding = fProgram.fConfig->fSettings.fDefaultUniformBinding;
3452 layout.fSet = fProgram.fConfig->fSettings.fDefaultUniformSet;
John Stilese40d1662021-01-29 10:08:50 -05003453 Modifiers modifiers{layout, Modifiers::kUniform_Flag};
3454
3455 fUniformBuffer.fInnerVariable = std::make_unique<Variable>(
Ethan Nicholas89cfde12021-09-27 11:20:34 -04003456 /*line=*/-1, fProgram.fModifiers->add(modifiers), kUniformBufferName,
John Stilese40d1662021-01-29 10:08:50 -05003457 fUniformBuffer.fStruct.get(), /*builtin=*/false, Variable::Storage::kGlobal);
3458
3459 // Create an interface block object for this global variable.
3460 fUniformBuffer.fInterfaceBlock = std::make_unique<InterfaceBlock>(
Ethan Nicholas2816dcf2021-09-21 09:18:47 -04003461 /*offset=*/-1, *fUniformBuffer.fInnerVariable, kUniformBufferName,
John Stilese40d1662021-01-29 10:08:50 -05003462 kUniformBufferName, /*arraySize=*/0, topLevelSymbolTable);
3463
3464 // Generate an interface block and hold onto its ID.
3465 fUniformBufferId = this->writeInterfaceBlock(*fUniformBuffer.fInterfaceBlock);
3466}
3467
Ethan Nicholas89cfde12021-09-27 11:20:34 -04003468void SPIRVCodeGenerator::addRTFlipUniform(int line) {
Brian Salomond8d85b92021-07-07 09:41:17 -04003469 if (fWroteRTFlip) {
3470 return;
3471 }
3472 // Flip variable hasn't been written yet. This means we don't have an existing
3473 // interface block, so we're free to just synthesize one.
3474 fWroteRTFlip = true;
3475 std::vector<Type::Field> fields;
3476 if (fProgram.fConfig->fSettings.fRTFlipOffset < 0) {
Ethan Nicholas89cfde12021-09-27 11:20:34 -04003477 fContext.fErrors->error(line, "RTFlipOffset is negative");
Brian Salomond8d85b92021-07-07 09:41:17 -04003478 }
3479 fields.emplace_back(Modifiers(Layout(/*flags=*/0,
3480 /*location=*/-1,
3481 fProgram.fConfig->fSettings.fRTFlipOffset,
3482 /*binding=*/-1,
3483 /*index=*/-1,
3484 /*set=*/-1,
3485 /*builtin=*/-1,
Brian Osman99ddd2a2021-08-27 11:21:12 -04003486 /*inputAttachmentIndex=*/-1),
Brian Salomond8d85b92021-07-07 09:41:17 -04003487 /*flags=*/0),
3488 SKSL_RTFLIP_NAME,
3489 fContext.fTypes.fFloat2.get());
Ethan Nicholas27f06eb2021-07-26 16:39:40 -04003490 skstd::string_view name = "sksl_synthetic_uniforms";
Brian Salomond8d85b92021-07-07 09:41:17 -04003491 const Type* intfStruct =
Ethan Nicholas89cfde12021-09-27 11:20:34 -04003492 fSynthetics.takeOwnershipOfSymbol(Type::MakeStructType(/*line=*/-1, name, fields));
Brian Salomond8d85b92021-07-07 09:41:17 -04003493 int binding = fProgram.fConfig->fSettings.fRTFlipBinding;
3494 if (binding == -1) {
Ethan Nicholas89cfde12021-09-27 11:20:34 -04003495 fContext.fErrors->error(line, "layout(binding=...) is required in SPIR-V");
Brian Salomond8d85b92021-07-07 09:41:17 -04003496 }
3497 int set = fProgram.fConfig->fSettings.fRTFlipSet;
3498 if (set == -1) {
Ethan Nicholas89cfde12021-09-27 11:20:34 -04003499 fContext.fErrors->error(line, "layout(set=...) is required in SPIR-V");
Brian Salomond8d85b92021-07-07 09:41:17 -04003500 }
3501 bool usePushConstants = fProgram.fConfig->fSettings.fUsePushConstants;
3502 int flags = usePushConstants ? Layout::Flag::kPushConstant_Flag : 0;
John Stiles0cac5ed2021-08-06 11:40:39 -04003503 const Modifiers* modsPtr;
3504 {
3505 AutoAttachPoolToThread attach(fProgram.fPool.get());
3506 Modifiers modifiers(Layout(flags,
3507 /*location=*/-1,
3508 /*offset=*/-1,
3509 binding,
3510 /*index=*/-1,
3511 set,
3512 /*builtin=*/-1,
Brian Osman99ddd2a2021-08-27 11:21:12 -04003513 /*inputAttachmentIndex=*/-1),
John Stiles0cac5ed2021-08-06 11:40:39 -04003514 Modifiers::kUniform_Flag);
3515 modsPtr = fProgram.fModifiers->add(modifiers);
Brian Salomond8d85b92021-07-07 09:41:17 -04003516 }
3517 const Variable* intfVar = fSynthetics.takeOwnershipOfSymbol(
Ethan Nicholas89cfde12021-09-27 11:20:34 -04003518 std::make_unique<Variable>(/*line=*/-1,
Brian Salomond8d85b92021-07-07 09:41:17 -04003519 modsPtr,
3520 name,
3521 intfStruct,
3522 /*builtin=*/false,
3523 Variable::Storage::kGlobal));
John Stilesd7437ee2021-08-02 11:56:16 -04003524 fSPIRVBonusVariables.insert(intfVar);
John Stiles0cac5ed2021-08-06 11:40:39 -04003525 {
3526 AutoAttachPoolToThread attach(fProgram.fPool.get());
Ethan Nicholas89cfde12021-09-27 11:20:34 -04003527 fProgram.fSymbols->add(std::make_unique<Field>(/*line=*/-1, intfVar, /*field=*/0));
Brian Salomond8d85b92021-07-07 09:41:17 -04003528 }
Ethan Nicholas89cfde12021-09-27 11:20:34 -04003529 InterfaceBlock intf(/*line=*/-1,
Ethan Nicholas2816dcf2021-09-21 09:18:47 -04003530 *intfVar,
Ethan Nicholas3533ff12021-08-02 12:53:29 -04003531 name,
Brian Salomond8d85b92021-07-07 09:41:17 -04003532 /*instanceName=*/"",
3533 /*arraySize=*/0,
Ethan Nicholasc7774a72021-08-27 15:34:05 -04003534 std::make_shared<SymbolTable>(fContext, /*builtin=*/false));
Brian Salomond8d85b92021-07-07 09:41:17 -04003535
3536 this->writeInterfaceBlock(intf, false);
3537}
3538
Ethan Nicholas0df1b042017-03-31 13:56:23 -04003539void SPIRVCodeGenerator::writeInstructions(const Program& program, OutputStream& out) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04003540 fGLSLExtendedInstructions = this->nextId(nullptr);
Ethan Nicholas0df1b042017-03-31 13:56:23 -04003541 StringStream body;
John Stiles4d6310a2021-01-26 19:58:22 -05003542 // Assign SpvIds to functions.
3543 const FunctionDeclaration* main = nullptr;
Brian Osman133724c2020-10-28 14:14:39 -04003544 for (const ProgramElement* e : program.elements()) {
John Stiles4d6310a2021-01-26 19:58:22 -05003545 if (e->is<FunctionDefinition>()) {
3546 const FunctionDefinition& funcDef = e->as<FunctionDefinition>();
3547 const FunctionDeclaration& funcDecl = funcDef.declaration();
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04003548 fFunctionMap[&funcDecl] = this->nextId(nullptr);
John Stilese8da4d22021-03-24 09:19:45 -04003549 if (funcDecl.isMain()) {
John Stiles4d6310a2021-01-26 19:58:22 -05003550 main = &funcDecl;
Ethan Nicholasb6ba82c2018-01-17 15:21:50 -05003551 }
ethannicholasb3058bd2016-07-01 08:22:01 -07003552 }
3553 }
John Stiles4d6310a2021-01-26 19:58:22 -05003554 // Make sure we have a main() function.
3555 if (!main) {
Ethan Nicholas89cfde12021-09-27 11:20:34 -04003556 fContext.fErrors->error(/*line=*/-1, "program does not contain a main() function");
John Stiles4d6310a2021-01-26 19:58:22 -05003557 return;
3558 }
3559 // Emit interface blocks.
3560 std::set<SpvId> interfaceVars;
Brian Osman133724c2020-10-28 14:14:39 -04003561 for (const ProgramElement* e : program.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04003562 if (e->is<InterfaceBlock>()) {
Brian Osman1f8f5752020-10-28 14:46:21 -04003563 const InterfaceBlock& intf = e->as<InterfaceBlock>();
ethannicholasb3058bd2016-07-01 08:22:01 -07003564 SpvId id = this->writeInterfaceBlock(intf);
Brian Osman1f8f5752020-10-28 14:46:21 -04003565
3566 const Modifiers& modifiers = intf.variable().modifiers();
John Stiles8e2a84b2021-04-19 09:35:38 -04003567 if ((modifiers.fFlags & (Modifiers::kIn_Flag | Modifiers::kOut_Flag)) &&
John Stilesd7437ee2021-08-02 11:56:16 -04003568 modifiers.fLayout.fBuiltin == -1 && !this->isDead(intf.variable())) {
Ethan Nicholas8e48c1e2017-03-02 14:33:31 -05003569 interfaceVars.insert(id);
ethannicholasb3058bd2016-07-01 08:22:01 -07003570 }
3571 }
3572 }
John Stiles4d6310a2021-01-26 19:58:22 -05003573 // Emit global variable declarations.
Brian Osman133724c2020-10-28 14:14:39 -04003574 for (const ProgramElement* e : program.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04003575 if (e->is<GlobalVarDeclaration>()) {
John Stiles270cec22021-02-17 12:59:36 -05003576 this->writeGlobalVar(program.fConfig->fKind,
John Stilese40d1662021-01-29 10:08:50 -05003577 e->as<GlobalVarDeclaration>().declaration()->as<VarDeclaration>());
ethannicholasb3058bd2016-07-01 08:22:01 -07003578 }
3579 }
John Stilese40d1662021-01-29 10:08:50 -05003580 // Emit top-level uniforms into a dedicated uniform buffer.
3581 if (!fTopLevelUniforms.empty()) {
3582 this->writeUniformBuffer(get_top_level_symbol_table(*main));
3583 }
John Stiles4d6310a2021-01-26 19:58:22 -05003584 // If main() returns a half4, synthesize a tiny entrypoint function which invokes the real
3585 // main() and stores the result into sk_FragColor.
3586 EntrypointAdapter adapter;
3587 if (main->returnType() == *fContext.fTypes.fHalf4) {
3588 adapter = this->writeEntrypointAdapter(*main);
3589 if (adapter.entrypointDecl) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04003590 fFunctionMap[adapter.entrypointDecl.get()] = this->nextId(nullptr);
John Stiles4d6310a2021-01-26 19:58:22 -05003591 this->writeFunction(*adapter.entrypointDef, body);
3592 main = adapter.entrypointDecl.get();
3593 }
3594 }
3595 // Emit all the functions.
Brian Osman133724c2020-10-28 14:14:39 -04003596 for (const ProgramElement* e : program.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04003597 if (e->is<FunctionDefinition>()) {
3598 this->writeFunction(e->as<FunctionDefinition>(), body);
ethannicholasb3058bd2016-07-01 08:22:01 -07003599 }
3600 }
John Stiles4d6310a2021-01-26 19:58:22 -05003601 // Add global in/out variables to the list of interface variables.
ethannicholasb3058bd2016-07-01 08:22:01 -07003602 for (auto entry : fVariableMap) {
ethannicholasd598f792016-07-25 10:08:54 -07003603 const Variable* var = entry.first;
Ethan Nicholas453f67f2020-10-09 10:43:45 -04003604 if (var->storage() == Variable::Storage::kGlobal &&
John Stiles8e2a84b2021-04-19 09:35:38 -04003605 (var->modifiers().fFlags & (Modifiers::kIn_Flag | Modifiers::kOut_Flag)) &&
John Stilesd7437ee2021-08-02 11:56:16 -04003606 !this->isDead(*var)) {
Ethan Nicholas8e48c1e2017-03-02 14:33:31 -05003607 interfaceVars.insert(entry.second);
ethannicholasb3058bd2016-07-01 08:22:01 -07003608 }
3609 }
3610 this->writeCapabilities(out);
3611 this->writeInstruction(SpvOpExtInstImport, fGLSLExtendedInstructions, "GLSL.std.450", out);
3612 this->writeInstruction(SpvOpMemoryModel, SpvAddressingModelLogical, SpvMemoryModelGLSL450, out);
Ethan Nicholasd2e09602021-06-10 11:21:59 -04003613 this->writeOpCode(SpvOpEntryPoint, (SpvId) (3 + (main->name().length() + 4) / 4) +
ethannicholasb3058bd2016-07-01 08:22:01 -07003614 (int32_t) interfaceVars.size(), out);
John Stiles270cec22021-02-17 12:59:36 -05003615 switch (program.fConfig->fKind) {
John Stilesdbd4e6f2021-02-16 13:29:15 -05003616 case ProgramKind::kVertex:
ethannicholasb3058bd2016-07-01 08:22:01 -07003617 this->writeWord(SpvExecutionModelVertex, out);
3618 break;
John Stilesdbd4e6f2021-02-16 13:29:15 -05003619 case ProgramKind::kFragment:
ethannicholasb3058bd2016-07-01 08:22:01 -07003620 this->writeWord(SpvExecutionModelFragment, out);
3621 break;
Ethan Nicholas762466e2017-06-29 10:03:38 -04003622 default:
John Stilesf57207b2021-02-02 17:50:34 -05003623 SK_ABORT("cannot write this kind of program to SPIR-V\n");
ethannicholasb3058bd2016-07-01 08:22:01 -07003624 }
Ethan Nicholasbb155e22017-07-24 10:05:09 -04003625 SpvId entryPoint = fFunctionMap[main];
3626 this->writeWord(entryPoint, out);
Ethan Nicholasd2e09602021-06-10 11:21:59 -04003627 this->writeString(main->name(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003628 for (int var : interfaceVars) {
3629 this->writeWord(var, out);
3630 }
John Stiles270cec22021-02-17 12:59:36 -05003631 if (program.fConfig->fKind == ProgramKind::kFragment) {
Greg Daniel64773e62016-11-22 09:44:03 -05003632 this->writeInstruction(SpvOpExecutionMode,
3633 fFunctionMap[main],
ethannicholasb3058bd2016-07-01 08:22:01 -07003634 SpvExecutionModeOriginUpperLeft,
3635 out);
3636 }
Brian Osman133724c2020-10-28 14:14:39 -04003637 for (const ProgramElement* e : program.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04003638 if (e->is<Extension>()) {
Ethan Nicholasd2e09602021-06-10 11:21:59 -04003639 this->writeInstruction(SpvOpSourceExtension, e->as<Extension>().name(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003640 }
3641 }
Greg Daniel64773e62016-11-22 09:44:03 -05003642
Ethan Nicholas0df1b042017-03-31 13:56:23 -04003643 write_stringstream(fExtraGlobalsBuffer, out);
3644 write_stringstream(fNameBuffer, out);
3645 write_stringstream(fDecorationBuffer, out);
3646 write_stringstream(fConstantBuffer, out);
Ethan Nicholas0df1b042017-03-31 13:56:23 -04003647 write_stringstream(body, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003648}
3649
Ethan Nicholas941e7e22016-12-12 15:33:30 -05003650bool SPIRVCodeGenerator::generateCode() {
Ethan Nicholas39f6da42021-08-23 13:10:07 -04003651 SkASSERT(!fContext.fErrors->errorCount());
Ethan Nicholas941e7e22016-12-12 15:33:30 -05003652 this->writeWord(SpvMagicNumber, *fOut);
3653 this->writeWord(SpvVersion, *fOut);
3654 this->writeWord(SKSL_MAGIC, *fOut);
Ethan Nicholas0df1b042017-03-31 13:56:23 -04003655 StringStream buffer;
Ethan Nicholas941e7e22016-12-12 15:33:30 -05003656 this->writeInstructions(fProgram, buffer);
3657 this->writeWord(fIdCount, *fOut);
3658 this->writeWord(0, *fOut); // reserved, always zero
Ethan Nicholas0df1b042017-03-31 13:56:23 -04003659 write_stringstream(buffer, *fOut);
Ethan Nicholas553239b2021-08-23 15:40:20 -04003660 fContext.fErrors->reportPendingErrors(PositionInfo());
Ethan Nicholas39f6da42021-08-23 13:10:07 -04003661 return fContext.fErrors->errorCount() == 0;
ethannicholasb3058bd2016-07-01 08:22:01 -07003662}
3663
John Stilesa6841be2020-08-06 14:11:56 -04003664} // namespace SkSL