blob: 238c6851aa72a748356d63fcd0908e5e1ae20ec5 [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
Mike Kleinc0bd9f92019-04-23 12:05:21 -050012#include "src/sksl/SkSLCompiler.h"
Brian Osman00185012021-02-04 16:07:11 -050013#include "src/sksl/SkSLOperators.h"
John Stiles4d6310a2021-01-26 19:58:22 -050014#include "src/sksl/ir/SkSLBlock.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050015#include "src/sksl/ir/SkSLExpressionStatement.h"
16#include "src/sksl/ir/SkSLExtension.h"
17#include "src/sksl/ir/SkSLIndexExpression.h"
18#include "src/sksl/ir/SkSLVariableReference.h"
ethannicholasb3058bd2016-07-01 08:22:01 -070019
Ethan Nicholas0be34802019-08-15 12:36:58 -040020#ifdef SK_VULKAN
21#include "src/gpu/vk/GrVkCaps.h"
22#endif
23
John Stilescd806892021-01-06 13:33:31 -050024#define kLast_Capability SpvCapabilityMultiViewport
25
ethannicholasb3058bd2016-07-01 08:22:01 -070026namespace SkSL {
27
ethannicholasb3058bd2016-07-01 08:22:01 -070028static const int32_t SKSL_MAGIC = 0x0; // FIXME: we should probably register a magic number
29
30void SPIRVCodeGenerator::setupIntrinsics() {
John Stilesaaac4e42021-05-06 14:08:28 -040031#define ALL_GLSL(x) std::make_tuple(kGLSL_STD_450_IntrinsicOpcodeKind, GLSLstd450 ## x, \
32 GLSLstd450 ## x, GLSLstd450 ## x, GLSLstd450 ## x)
33#define BY_TYPE_GLSL(ifFloat, ifInt, ifUInt) std::make_tuple(kGLSL_STD_450_IntrinsicOpcodeKind, \
34 GLSLstd450 ## ifFloat, \
35 GLSLstd450 ## ifInt, \
36 GLSLstd450 ## ifUInt, \
ethannicholasb3058bd2016-07-01 08:22:01 -070037 SpvOpUndef)
John Stilesaaac4e42021-05-06 14:08:28 -040038#define ALL_SPIRV(x) std::make_tuple(kSPIRV_IntrinsicOpcodeKind, \
39 SpvOp ## x, SpvOp ## x, SpvOp ## x, SpvOp ## x)
40#define SPECIAL(x) std::make_tuple(kSpecial_IntrinsicOpcodeKind, k ## x ## _SpecialIntrinsic, \
41 k ## x ## _SpecialIntrinsic, k ## x ## _SpecialIntrinsic, \
ethannicholasb3058bd2016-07-01 08:22:01 -070042 k ## x ## _SpecialIntrinsic)
John Stilesaaac4e42021-05-06 14:08:28 -040043 fIntrinsicMap[k_round_IntrinsicKind] = ALL_GLSL(Round);
44 fIntrinsicMap[k_roundEven_IntrinsicKind] = ALL_GLSL(RoundEven);
45 fIntrinsicMap[k_trunc_IntrinsicKind] = ALL_GLSL(Trunc);
46 fIntrinsicMap[k_abs_IntrinsicKind] = BY_TYPE_GLSL(FAbs, SAbs, SAbs);
47 fIntrinsicMap[k_sign_IntrinsicKind] = BY_TYPE_GLSL(FSign, SSign, SSign);
48 fIntrinsicMap[k_floor_IntrinsicKind] = ALL_GLSL(Floor);
49 fIntrinsicMap[k_ceil_IntrinsicKind] = ALL_GLSL(Ceil);
50 fIntrinsicMap[k_fract_IntrinsicKind] = ALL_GLSL(Fract);
51 fIntrinsicMap[k_radians_IntrinsicKind] = ALL_GLSL(Radians);
52 fIntrinsicMap[k_degrees_IntrinsicKind] = ALL_GLSL(Degrees);
53 fIntrinsicMap[k_sin_IntrinsicKind] = ALL_GLSL(Sin);
54 fIntrinsicMap[k_cos_IntrinsicKind] = ALL_GLSL(Cos);
55 fIntrinsicMap[k_tan_IntrinsicKind] = ALL_GLSL(Tan);
56 fIntrinsicMap[k_asin_IntrinsicKind] = ALL_GLSL(Asin);
57 fIntrinsicMap[k_acos_IntrinsicKind] = ALL_GLSL(Acos);
58 fIntrinsicMap[k_atan_IntrinsicKind] = SPECIAL(Atan);
59 fIntrinsicMap[k_sinh_IntrinsicKind] = ALL_GLSL(Sinh);
60 fIntrinsicMap[k_cosh_IntrinsicKind] = ALL_GLSL(Cosh);
61 fIntrinsicMap[k_tanh_IntrinsicKind] = ALL_GLSL(Tanh);
62 fIntrinsicMap[k_asinh_IntrinsicKind] = ALL_GLSL(Asinh);
63 fIntrinsicMap[k_acosh_IntrinsicKind] = ALL_GLSL(Acosh);
64 fIntrinsicMap[k_atanh_IntrinsicKind] = ALL_GLSL(Atanh);
65 fIntrinsicMap[k_pow_IntrinsicKind] = ALL_GLSL(Pow);
66 fIntrinsicMap[k_exp_IntrinsicKind] = ALL_GLSL(Exp);
67 fIntrinsicMap[k_log_IntrinsicKind] = ALL_GLSL(Log);
68 fIntrinsicMap[k_exp2_IntrinsicKind] = ALL_GLSL(Exp2);
69 fIntrinsicMap[k_log2_IntrinsicKind] = ALL_GLSL(Log2);
70 fIntrinsicMap[k_sqrt_IntrinsicKind] = ALL_GLSL(Sqrt);
71 fIntrinsicMap[k_inverse_IntrinsicKind] = ALL_GLSL(MatrixInverse);
72 fIntrinsicMap[k_outerProduct_IntrinsicKind] = ALL_SPIRV(OuterProduct);
73 fIntrinsicMap[k_transpose_IntrinsicKind] = ALL_SPIRV(Transpose);
74 fIntrinsicMap[k_isinf_IntrinsicKind] = ALL_SPIRV(IsInf);
75 fIntrinsicMap[k_isnan_IntrinsicKind] = ALL_SPIRV(IsNan);
76 fIntrinsicMap[k_inversesqrt_IntrinsicKind] = ALL_GLSL(InverseSqrt);
77 fIntrinsicMap[k_determinant_IntrinsicKind] = ALL_GLSL(Determinant);
78 fIntrinsicMap[k_matrixCompMult_IntrinsicKind] = SPECIAL(MatrixCompMult);
79 fIntrinsicMap[k_matrixInverse_IntrinsicKind] = ALL_GLSL(MatrixInverse);
80 fIntrinsicMap[k_mod_IntrinsicKind] = SPECIAL(Mod);
81 fIntrinsicMap[k_modf_IntrinsicKind] = ALL_GLSL(Modf);
82 fIntrinsicMap[k_min_IntrinsicKind] = SPECIAL(Min);
83 fIntrinsicMap[k_max_IntrinsicKind] = SPECIAL(Max);
84 fIntrinsicMap[k_clamp_IntrinsicKind] = SPECIAL(Clamp);
85 fIntrinsicMap[k_saturate_IntrinsicKind] = SPECIAL(Saturate);
86 fIntrinsicMap[k_dot_IntrinsicKind] = std::make_tuple(kSPIRV_IntrinsicOpcodeKind,
87 SpvOpDot, SpvOpUndef, SpvOpUndef, SpvOpUndef);
88 fIntrinsicMap[k_mix_IntrinsicKind] = SPECIAL(Mix);
89 fIntrinsicMap[k_step_IntrinsicKind] = SPECIAL(Step);
90 fIntrinsicMap[k_smoothstep_IntrinsicKind] = SPECIAL(SmoothStep);
91 fIntrinsicMap[k_fma_IntrinsicKind] = ALL_GLSL(Fma);
92 fIntrinsicMap[k_frexp_IntrinsicKind] = ALL_GLSL(Frexp);
93 fIntrinsicMap[k_ldexp_IntrinsicKind] = ALL_GLSL(Ldexp);
ethannicholasb3058bd2016-07-01 08:22:01 -070094
John Stilesaaac4e42021-05-06 14:08:28 -040095#define PACK(type) fIntrinsicMap[k_pack##type##_IntrinsicKind] = ALL_GLSL(Pack##type); \
96 fIntrinsicMap[k_unpack##type##_IntrinsicKind] = ALL_GLSL(Unpack##type)
ethannicholasb3058bd2016-07-01 08:22:01 -070097 PACK(Snorm4x8);
98 PACK(Unorm4x8);
99 PACK(Snorm2x16);
100 PACK(Unorm2x16);
101 PACK(Half2x16);
102 PACK(Double2x32);
John Stilesaaac4e42021-05-06 14:08:28 -0400103#undef PACK
104 fIntrinsicMap[k_length_IntrinsicKind] = ALL_GLSL(Length);
105 fIntrinsicMap[k_distance_IntrinsicKind] = ALL_GLSL(Distance);
106 fIntrinsicMap[k_cross_IntrinsicKind] = ALL_GLSL(Cross);
107 fIntrinsicMap[k_normalize_IntrinsicKind] = ALL_GLSL(Normalize);
108 fIntrinsicMap[k_faceforward_IntrinsicKind] = ALL_GLSL(FaceForward);
109 fIntrinsicMap[k_reflect_IntrinsicKind] = ALL_GLSL(Reflect);
110 fIntrinsicMap[k_refract_IntrinsicKind] = ALL_GLSL(Refract);
111 fIntrinsicMap[k_bitCount_IntrinsicKind] = ALL_SPIRV(BitCount);
112 fIntrinsicMap[k_findLSB_IntrinsicKind] = ALL_GLSL(FindILsb);
113 fIntrinsicMap[k_findMSB_IntrinsicKind] = BY_TYPE_GLSL(FindSMsb, FindSMsb, FindUMsb);
114 fIntrinsicMap[k_dFdx_IntrinsicKind] = std::make_tuple(kSPIRV_IntrinsicOpcodeKind,
115 SpvOpDPdx, SpvOpUndef,
116 SpvOpUndef, SpvOpUndef);
117 fIntrinsicMap[k_dFdy_IntrinsicKind] = SPECIAL(DFdy);
118 fIntrinsicMap[k_fwidth_IntrinsicKind] = std::make_tuple(kSPIRV_IntrinsicOpcodeKind,
119 SpvOpFwidth, SpvOpUndef,
120 SpvOpUndef, SpvOpUndef);
121 fIntrinsicMap[k_makeSampler2D_IntrinsicKind] = SPECIAL(SampledImage);
Stephen Whiteff5d7a22019-07-26 17:42:06 -0400122
John Stilesaaac4e42021-05-06 14:08:28 -0400123 fIntrinsicMap[k_sample_IntrinsicKind] = SPECIAL(Texture);
124 fIntrinsicMap[k_subpassLoad_IntrinsicKind] = SPECIAL(SubpassLoad);
Greg Daniel64773e62016-11-22 09:44:03 -0500125
John Stilesaaac4e42021-05-06 14:08:28 -0400126 fIntrinsicMap[k_floatBitsToInt_IntrinsicKind] = ALL_SPIRV(Bitcast);
127 fIntrinsicMap[k_floatBitsToUint_IntrinsicKind] = ALL_SPIRV(Bitcast);
128 fIntrinsicMap[k_intBitsToFloat_IntrinsicKind] = ALL_SPIRV(Bitcast);
129 fIntrinsicMap[k_uintBitsToFloat_IntrinsicKind] = ALL_SPIRV(Bitcast);
John Stilescc9ff002020-12-09 18:39:41 -0500130
John Stilesaaac4e42021-05-06 14:08:28 -0400131 fIntrinsicMap[k_any_IntrinsicKind] = std::make_tuple(kSPIRV_IntrinsicOpcodeKind,
Brian Osman540c13a2020-11-24 16:55:34 -0500132 SpvOpUndef, SpvOpUndef,
John Stilesaaac4e42021-05-06 14:08:28 -0400133 SpvOpUndef, SpvOpAny);
134 fIntrinsicMap[k_all_IntrinsicKind] = std::make_tuple(kSPIRV_IntrinsicOpcodeKind,
135 SpvOpUndef, SpvOpUndef,
136 SpvOpUndef, SpvOpAll);
137 fIntrinsicMap[k_not_IntrinsicKind] = std::make_tuple(kSPIRV_IntrinsicOpcodeKind,
138 SpvOpUndef, SpvOpUndef, SpvOpUndef,
Brian Osman540c13a2020-11-24 16:55:34 -0500139 SpvOpLogicalNot);
John Stilesaaac4e42021-05-06 14:08:28 -0400140 fIntrinsicMap[k_equal_IntrinsicKind] = std::make_tuple(kSPIRV_IntrinsicOpcodeKind,
Ethan Nicholas0187ae62017-05-03 11:03:44 -0400141 SpvOpFOrdEqual, SpvOpIEqual,
142 SpvOpIEqual, SpvOpLogicalEqual);
John Stilesaaac4e42021-05-06 14:08:28 -0400143 fIntrinsicMap[k_notEqual_IntrinsicKind] = std::make_tuple(kSPIRV_IntrinsicOpcodeKind,
Ethan Nicholas0187ae62017-05-03 11:03:44 -0400144 SpvOpFOrdNotEqual, SpvOpINotEqual,
145 SpvOpINotEqual,
146 SpvOpLogicalNotEqual);
John Stilesaaac4e42021-05-06 14:08:28 -0400147 fIntrinsicMap[k_lessThan_IntrinsicKind] = std::make_tuple(kSPIRV_IntrinsicOpcodeKind,
148 SpvOpFOrdLessThan,
149 SpvOpSLessThan,
150 SpvOpULessThan,
151 SpvOpUndef);
152 fIntrinsicMap[k_lessThanEqual_IntrinsicKind] = std::make_tuple(kSPIRV_IntrinsicOpcodeKind,
153 SpvOpFOrdLessThanEqual,
154 SpvOpSLessThanEqual,
155 SpvOpULessThanEqual,
156 SpvOpUndef);
157 fIntrinsicMap[k_greaterThan_IntrinsicKind] = std::make_tuple(kSPIRV_IntrinsicOpcodeKind,
158 SpvOpFOrdGreaterThan,
159 SpvOpSGreaterThan,
160 SpvOpUGreaterThan,
161 SpvOpUndef);
162 fIntrinsicMap[k_greaterThanEqual_IntrinsicKind] = std::make_tuple(kSPIRV_IntrinsicOpcodeKind,
163 SpvOpFOrdGreaterThanEqual,
164 SpvOpSGreaterThanEqual,
165 SpvOpUGreaterThanEqual,
166 SpvOpUndef);
167 fIntrinsicMap[k_EmitVertex_IntrinsicKind] = ALL_SPIRV(EmitVertex);
168 fIntrinsicMap[k_EndPrimitive_IntrinsicKind] = ALL_SPIRV(EndPrimitive);
ethannicholasb3058bd2016-07-01 08:22:01 -0700169// interpolateAt* not yet supported...
170}
171
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400172void SPIRVCodeGenerator::writeWord(int32_t word, OutputStream& out) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700173 out.write((const char*) &word, sizeof(word));
ethannicholasb3058bd2016-07-01 08:22:01 -0700174}
175
ethannicholasd598f792016-07-25 10:08:54 -0700176static bool is_float(const Context& context, const Type& type) {
John Stiles4c151702021-02-09 18:31:34 -0500177 return (type.isScalar() || type.isVector() || type.isMatrix()) &&
178 type.componentType().isFloat();
ethannicholasb3058bd2016-07-01 08:22:01 -0700179}
180
ethannicholasd598f792016-07-25 10:08:54 -0700181static bool is_signed(const Context& context, const Type& type) {
John Stiles4c151702021-02-09 18:31:34 -0500182 return type.isEnum() ||
183 ((type.isScalar() || type.isVector()) && type.componentType().isSigned());
ethannicholasb3058bd2016-07-01 08:22:01 -0700184}
185
ethannicholasd598f792016-07-25 10:08:54 -0700186static bool is_unsigned(const Context& context, const Type& type) {
John Stiles4c151702021-02-09 18:31:34 -0500187 return (type.isScalar() || type.isVector()) && type.componentType().isUnsigned();
ethannicholasb3058bd2016-07-01 08:22:01 -0700188}
189
ethannicholasd598f792016-07-25 10:08:54 -0700190static bool is_bool(const Context& context, const Type& type) {
John Stiles4c151702021-02-09 18:31:34 -0500191 return (type.isScalar() || type.isVector()) && type.componentType().isBoolean();
ethannicholasb3058bd2016-07-01 08:22:01 -0700192}
193
ethannicholasd598f792016-07-25 10:08:54 -0700194static bool is_out(const Variable& var) {
Ethan Nicholas041fd0a2020-10-07 16:42:04 -0400195 return (var.modifiers().fFlags & Modifiers::kOut_Flag) != 0;
ethannicholasb3058bd2016-07-01 08:22:01 -0700196}
197
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400198void SPIRVCodeGenerator::writeOpCode(SpvOp_ opCode, int length, OutputStream& out) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400199 SkASSERT(opCode != SpvOpLoad || &out != &fConstantBuffer);
200 SkASSERT(opCode != SpvOpUndef);
ethannicholasb3058bd2016-07-01 08:22:01 -0700201 switch (opCode) {
202 case SpvOpReturn: // fall through
203 case SpvOpReturnValue: // fall through
ethannicholas552882f2016-07-07 06:30:48 -0700204 case SpvOpKill: // fall through
Ethan Nicholas7fb39362020-12-16 15:25:19 -0500205 case SpvOpSwitch: // fall through
ethannicholasb3058bd2016-07-01 08:22:01 -0700206 case SpvOpBranch: // fall through
207 case SpvOpBranchConditional:
John Stiles7142e402021-02-23 12:28:18 -0500208 SkASSERT(fCurrentBlock);
ethannicholasb3058bd2016-07-01 08:22:01 -0700209 fCurrentBlock = 0;
210 break;
211 case SpvOpConstant: // fall through
212 case SpvOpConstantTrue: // fall through
213 case SpvOpConstantFalse: // fall through
214 case SpvOpConstantComposite: // fall through
215 case SpvOpTypeVoid: // fall through
216 case SpvOpTypeInt: // fall through
217 case SpvOpTypeFloat: // fall through
218 case SpvOpTypeBool: // fall through
219 case SpvOpTypeVector: // fall through
220 case SpvOpTypeMatrix: // fall through
221 case SpvOpTypeArray: // fall through
222 case SpvOpTypePointer: // fall through
223 case SpvOpTypeFunction: // fall through
224 case SpvOpTypeRuntimeArray: // fall through
225 case SpvOpTypeStruct: // fall through
226 case SpvOpTypeImage: // fall through
227 case SpvOpTypeSampledImage: // fall through
Stephen Whiteff5d7a22019-07-26 17:42:06 -0400228 case SpvOpTypeSampler: // fall through
ethannicholasb3058bd2016-07-01 08:22:01 -0700229 case SpvOpVariable: // fall through
230 case SpvOpFunction: // fall through
231 case SpvOpFunctionParameter: // fall through
232 case SpvOpFunctionEnd: // fall through
233 case SpvOpExecutionMode: // fall through
234 case SpvOpMemoryModel: // fall through
235 case SpvOpCapability: // fall through
236 case SpvOpExtInstImport: // fall through
237 case SpvOpEntryPoint: // fall through
238 case SpvOpSource: // fall through
239 case SpvOpSourceExtension: // fall through
240 case SpvOpName: // fall through
241 case SpvOpMemberName: // fall through
242 case SpvOpDecorate: // fall through
243 case SpvOpMemberDecorate:
244 break;
245 default:
John Stilesf3a28db2021-03-10 23:00:47 -0500246 // We may find ourselves with dead code--instructions that don't have an associated
247 // block. This should be a rare event, but if it happens, synthesize a label; this is
248 // necessary to satisfy the validator.
249 if (fCurrentBlock == 0) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -0400250 this->writeLabel(this->nextId(nullptr), out);
John Stiles7142e402021-02-23 12:28:18 -0500251 }
John Stiles453f1432021-02-25 16:58:04 -0500252 break;
ethannicholasb3058bd2016-07-01 08:22:01 -0700253 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700254 this->writeWord((length << 16) | opCode, out);
ethannicholasb3058bd2016-07-01 08:22:01 -0700255}
256
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400257void SPIRVCodeGenerator::writeLabel(SpvId label, OutputStream& out) {
Ethan Nicholas7fb39362020-12-16 15:25:19 -0500258 SkASSERT(!fCurrentBlock);
ethannicholasb3058bd2016-07-01 08:22:01 -0700259 fCurrentBlock = label;
260 this->writeInstruction(SpvOpLabel, label, out);
261}
262
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400263void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, OutputStream& out) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700264 this->writeOpCode(opCode, 1, out);
265}
266
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400267void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, int32_t word1, OutputStream& out) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700268 this->writeOpCode(opCode, 2, out);
269 this->writeWord(word1, out);
270}
271
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700272void SPIRVCodeGenerator::writeString(const char* string, size_t length, OutputStream& out) {
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400273 out.write(string, length);
ethannicholasb3058bd2016-07-01 08:22:01 -0700274 switch (length % 4) {
275 case 1:
Ethan Nicholas9e1138d2016-11-21 10:39:35 -0500276 out.write8(0);
John Stiles30212b72020-06-11 17:55:07 -0400277 [[fallthrough]];
ethannicholasb3058bd2016-07-01 08:22:01 -0700278 case 2:
Ethan Nicholas9e1138d2016-11-21 10:39:35 -0500279 out.write8(0);
John Stiles30212b72020-06-11 17:55:07 -0400280 [[fallthrough]];
ethannicholasb3058bd2016-07-01 08:22:01 -0700281 case 3:
Ethan Nicholas9e1138d2016-11-21 10:39:35 -0500282 out.write8(0);
ethannicholasb3058bd2016-07-01 08:22:01 -0700283 break;
284 default:
285 this->writeWord(0, out);
286 }
287}
288
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700289void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, StringFragment string, OutputStream& out) {
290 this->writeOpCode(opCode, 1 + (string.fLength + 4) / 4, out);
291 this->writeString(string.fChars, string.fLength, out);
ethannicholasb3058bd2016-07-01 08:22:01 -0700292}
293
294
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700295void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, int32_t word1, StringFragment string,
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400296 OutputStream& out) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700297 this->writeOpCode(opCode, 2 + (string.fLength + 4) / 4, out);
ethannicholasb3058bd2016-07-01 08:22:01 -0700298 this->writeWord(word1, out);
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700299 this->writeString(string.fChars, string.fLength, out);
ethannicholasb3058bd2016-07-01 08:22:01 -0700300}
301
Greg Daniel64773e62016-11-22 09:44:03 -0500302void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, int32_t word1, int32_t word2,
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700303 StringFragment string, OutputStream& out) {
304 this->writeOpCode(opCode, 3 + (string.fLength + 4) / 4, out);
ethannicholasb3058bd2016-07-01 08:22:01 -0700305 this->writeWord(word1, out);
306 this->writeWord(word2, out);
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700307 this->writeString(string.fChars, string.fLength, out);
ethannicholasb3058bd2016-07-01 08:22:01 -0700308}
309
Greg Daniel64773e62016-11-22 09:44:03 -0500310void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, int32_t word1, int32_t word2,
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400311 OutputStream& out) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700312 this->writeOpCode(opCode, 3, out);
313 this->writeWord(word1, out);
314 this->writeWord(word2, out);
315}
316
Greg Daniel64773e62016-11-22 09:44:03 -0500317void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, int32_t word1, int32_t word2,
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400318 int32_t word3, OutputStream& out) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700319 this->writeOpCode(opCode, 4, out);
320 this->writeWord(word1, out);
321 this->writeWord(word2, out);
322 this->writeWord(word3, out);
323}
324
Greg Daniel64773e62016-11-22 09:44:03 -0500325void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, int32_t word1, int32_t word2,
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400326 int32_t word3, int32_t word4, OutputStream& out) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700327 this->writeOpCode(opCode, 5, out);
328 this->writeWord(word1, out);
329 this->writeWord(word2, out);
330 this->writeWord(word3, out);
331 this->writeWord(word4, out);
332}
333
Greg Daniel64773e62016-11-22 09:44:03 -0500334void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, int32_t word1, int32_t word2,
335 int32_t word3, int32_t word4, int32_t word5,
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400336 OutputStream& out) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700337 this->writeOpCode(opCode, 6, out);
338 this->writeWord(word1, out);
339 this->writeWord(word2, out);
340 this->writeWord(word3, out);
341 this->writeWord(word4, out);
342 this->writeWord(word5, out);
343}
344
Greg Daniel64773e62016-11-22 09:44:03 -0500345void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, int32_t word1, int32_t word2,
ethannicholasb3058bd2016-07-01 08:22:01 -0700346 int32_t word3, int32_t word4, int32_t word5,
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400347 int32_t word6, OutputStream& out) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700348 this->writeOpCode(opCode, 7, out);
349 this->writeWord(word1, out);
350 this->writeWord(word2, out);
351 this->writeWord(word3, out);
352 this->writeWord(word4, out);
353 this->writeWord(word5, out);
354 this->writeWord(word6, out);
355}
356
Greg Daniel64773e62016-11-22 09:44:03 -0500357void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, int32_t word1, int32_t word2,
ethannicholasb3058bd2016-07-01 08:22:01 -0700358 int32_t word3, int32_t word4, int32_t word5,
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400359 int32_t word6, int32_t word7, OutputStream& out) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700360 this->writeOpCode(opCode, 8, out);
361 this->writeWord(word1, out);
362 this->writeWord(word2, out);
363 this->writeWord(word3, out);
364 this->writeWord(word4, out);
365 this->writeWord(word5, out);
366 this->writeWord(word6, out);
367 this->writeWord(word7, out);
368}
369
Greg Daniel64773e62016-11-22 09:44:03 -0500370void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, int32_t word1, int32_t word2,
ethannicholasb3058bd2016-07-01 08:22:01 -0700371 int32_t word3, int32_t word4, int32_t word5,
372 int32_t word6, int32_t word7, int32_t word8,
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400373 OutputStream& out) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700374 this->writeOpCode(opCode, 9, out);
375 this->writeWord(word1, out);
376 this->writeWord(word2, out);
377 this->writeWord(word3, out);
378 this->writeWord(word4, out);
379 this->writeWord(word5, out);
380 this->writeWord(word6, out);
381 this->writeWord(word7, out);
382 this->writeWord(word8, out);
383}
384
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400385void SPIRVCodeGenerator::writeCapabilities(OutputStream& out) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700386 for (uint64_t i = 0, bit = 1; i <= kLast_Capability; i++, bit <<= 1) {
387 if (fCapabilities & bit) {
388 this->writeInstruction(SpvOpCapability, (SpvId) i, out);
389 }
390 }
John Stiles270cec22021-02-17 12:59:36 -0500391 if (fProgram.fConfig->fKind == ProgramKind::kGeometry) {
Ethan Nicholasbb155e22017-07-24 10:05:09 -0400392 this->writeInstruction(SpvOpCapability, SpvCapabilityGeometry, out);
393 }
Ethan Nicholas81d15112018-07-13 12:48:50 -0400394 else {
395 this->writeInstruction(SpvOpCapability, SpvCapabilityShader, out);
396 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700397}
398
Ethan Nicholas8f352ce2021-03-17 14:12:20 -0400399SpvId SPIRVCodeGenerator::nextId(const Type* type) {
400 return this->nextId(type && type->hasPrecision() && !type->highPrecision()
401 ? Precision::kRelaxed
402 : Precision::kDefault);
403}
404
405SpvId SPIRVCodeGenerator::nextId(Precision precision) {
406 if (precision == Precision::kRelaxed && !fProgram.fConfig->fSettings.fForceHighPrecision) {
407 this->writeInstruction(SpvOpDecorate, fIdCount, SpvDecorationRelaxedPrecision,
408 fDecorationBuffer);
409 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700410 return fIdCount++;
411}
412
Ethan Nicholas19671772016-11-28 16:30:17 -0500413void SPIRVCodeGenerator::writeStruct(const Type& type, const MemoryLayout& memoryLayout,
414 SpvId resultId) {
Ethan Nicholase2c49992020-10-05 11:49:11 -0400415 this->writeInstruction(SpvOpName, resultId, String(type.name()).c_str(), fNameBuffer);
ethannicholasb3058bd2016-07-01 08:22:01 -0700416 // go ahead and write all of the field types, so we don't inadvertently write them while we're
417 // in the middle of writing the struct instruction
418 std::vector<SpvId> types;
419 for (const auto& f : type.fields()) {
Ethan Nicholas19671772016-11-28 16:30:17 -0500420 types.push_back(this->getType(*f.fType, memoryLayout));
ethannicholasb3058bd2016-07-01 08:22:01 -0700421 }
422 this->writeOpCode(SpvOpTypeStruct, 2 + (int32_t) types.size(), fConstantBuffer);
423 this->writeWord(resultId, fConstantBuffer);
424 for (SpvId id : types) {
425 this->writeWord(id, fConstantBuffer);
426 }
427 size_t offset = 0;
428 for (int32_t i = 0; i < (int32_t) type.fields().size(); i++) {
Ethan Nicholascc5d3e02019-04-19 09:50:56 -0400429 const Type::Field& field = type.fields()[i];
John Stiles21f5f452020-11-30 09:57:59 -0500430 if (!MemoryLayout::LayoutIsSupported(*field.fType)) {
John Stiles0023c0c2020-11-16 13:32:18 -0500431 fErrors.error(type.fOffset, "type '" + field.fType->name() + "' is not permitted here");
432 return;
433 }
Ethan Nicholascc5d3e02019-04-19 09:50:56 -0400434 size_t size = memoryLayout.size(*field.fType);
435 size_t alignment = memoryLayout.alignment(*field.fType);
436 const Layout& fieldLayout = field.fModifiers.fLayout;
Ethan Nicholas19671772016-11-28 16:30:17 -0500437 if (fieldLayout.fOffset >= 0) {
Greg Danieldbd44c72017-01-24 15:12:12 -0500438 if (fieldLayout.fOffset < (int) offset) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700439 fErrors.error(type.fOffset,
Ethan Nicholascc5d3e02019-04-19 09:50:56 -0400440 "offset of field '" + field.fName + "' must be at "
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500441 "least " + to_string((int) offset));
Ethan Nicholas19671772016-11-28 16:30:17 -0500442 }
443 if (fieldLayout.fOffset % alignment) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700444 fErrors.error(type.fOffset,
Ethan Nicholascc5d3e02019-04-19 09:50:56 -0400445 "offset of field '" + field.fName + "' must be a multiple"
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500446 " of " + to_string((int) alignment));
Ethan Nicholas19671772016-11-28 16:30:17 -0500447 }
448 offset = fieldLayout.fOffset;
449 } else {
450 size_t mod = offset % alignment;
451 if (mod) {
452 offset += alignment - mod;
453 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700454 }
Ethan Nicholascc5d3e02019-04-19 09:50:56 -0400455 this->writeInstruction(SpvOpMemberName, resultId, i, field.fName, fNameBuffer);
Ethan Nicholas19671772016-11-28 16:30:17 -0500456 this->writeLayout(fieldLayout, resultId, i);
Ethan Nicholascc5d3e02019-04-19 09:50:56 -0400457 if (field.fModifiers.fLayout.fBuiltin < 0) {
Greg Daniel64773e62016-11-22 09:44:03 -0500458 this->writeInstruction(SpvOpMemberDecorate, resultId, (SpvId) i, SpvDecorationOffset,
ethannicholasb3058bd2016-07-01 08:22:01 -0700459 (SpvId) offset, fDecorationBuffer);
460 }
John Stiles9aeed132020-11-24 17:36:06 -0500461 if (field.fType->isMatrix()) {
Greg Daniel64773e62016-11-22 09:44:03 -0500462 this->writeInstruction(SpvOpMemberDecorate, resultId, i, SpvDecorationColMajor,
ethannicholasb3058bd2016-07-01 08:22:01 -0700463 fDecorationBuffer);
Greg Daniel64773e62016-11-22 09:44:03 -0500464 this->writeInstruction(SpvOpMemberDecorate, resultId, i, SpvDecorationMatrixStride,
Ethan Nicholascc5d3e02019-04-19 09:50:56 -0400465 (SpvId) memoryLayout.stride(*field.fType),
ethannicholas8ac838d2016-11-22 08:39:36 -0800466 fDecorationBuffer);
ethannicholasb3058bd2016-07-01 08:22:01 -0700467 }
Ethan Nicholascc5d3e02019-04-19 09:50:56 -0400468 if (!field.fType->highPrecision()) {
469 this->writeInstruction(SpvOpMemberDecorate, resultId, (SpvId) i,
470 SpvDecorationRelaxedPrecision, fDecorationBuffer);
471 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700472 offset += size;
John Stilesc0c51062020-12-03 17:16:29 -0500473 if ((field.fType->isArray() || field.fType->isStruct()) && offset % alignment != 0) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700474 offset += alignment - offset % alignment;
475 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700476 }
477}
478
Ethan Nicholase2c49992020-10-05 11:49:11 -0400479const Type& SPIRVCodeGenerator::getActualType(const Type& type) {
Ethan Nicholase1f55022019-02-05 17:17:40 -0500480 if (type.isFloat()) {
John Stiles54e7c052021-01-11 14:22:36 -0500481 return *fContext.fTypes.fFloat;
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400482 }
John Stiles4c151702021-02-09 18:31:34 -0500483 if (type.isSigned() || type.isEnum()) {
John Stiles54e7c052021-01-11 14:22:36 -0500484 return *fContext.fTypes.fInt;
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400485 }
Ethan Nicholase1f55022019-02-05 17:17:40 -0500486 if (type.isUnsigned()) {
John Stiles54e7c052021-01-11 14:22:36 -0500487 return *fContext.fTypes.fUInt;
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400488 }
John Stiles9aeed132020-11-24 17:36:06 -0500489 if (type.isMatrix() || type.isVector()) {
John Stiles54e7c052021-01-11 14:22:36 -0500490 if (type.componentType() == *fContext.fTypes.fHalf) {
491 return fContext.fTypes.fFloat->toCompound(fContext, type.columns(), type.rows());
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400492 }
Ethan Nicholas722c83e2021-05-04 11:39:30 -0400493 if (type.componentType() == *fContext.fTypes.fShort) {
John Stiles54e7c052021-01-11 14:22:36 -0500494 return fContext.fTypes.fInt->toCompound(fContext, type.columns(), type.rows());
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400495 }
Ethan Nicholas722c83e2021-05-04 11:39:30 -0400496 if (type.componentType() == *fContext.fTypes.fUShort) {
John Stiles54e7c052021-01-11 14:22:36 -0500497 return fContext.fTypes.fUInt->toCompound(fContext, type.columns(), type.rows());
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400498 }
499 }
500 return type;
501}
502
ethannicholasb3058bd2016-07-01 08:22:01 -0700503SpvId SPIRVCodeGenerator::getType(const Type& type) {
ethannicholas8ac838d2016-11-22 08:39:36 -0800504 return this->getType(type, fDefaultLayout);
505}
506
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400507SpvId SPIRVCodeGenerator::getType(const Type& rawType, const MemoryLayout& layout) {
Ethan Nicholase2c49992020-10-05 11:49:11 -0400508 const Type& type = this->getActualType(rawType);
Jim Van Verthf3ec9832020-10-21 16:09:57 -0400509 String key = type.name();
John Stilesc0c51062020-12-03 17:16:29 -0500510 if (type.isStruct() || type.isArray()) {
Jim Van Verthf3ec9832020-10-21 16:09:57 -0400511 key += to_string((int)layout.fStd);
Brian Osman2a4c0fb2021-01-22 13:41:40 -0500512#ifdef SK_DEBUG
513 SkASSERT(layout.fStd == MemoryLayout::Standard::k140_Standard ||
514 layout.fStd == MemoryLayout::Standard::k430_Standard);
515 MemoryLayout::Standard otherStd = layout.fStd == MemoryLayout::Standard::k140_Standard
516 ? MemoryLayout::Standard::k430_Standard
517 : MemoryLayout::Standard::k140_Standard;
518 String otherKey = type.name() + to_string((int)otherStd);
519 SkASSERT(fTypeMap.find(otherKey) == fTypeMap.end());
520#endif
Jim Van Verthf3ec9832020-10-21 16:09:57 -0400521 }
ethannicholas8ac838d2016-11-22 08:39:36 -0800522 auto entry = fTypeMap.find(key);
ethannicholasb3058bd2016-07-01 08:22:01 -0700523 if (entry == fTypeMap.end()) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -0400524 SpvId result = this->nextId(nullptr);
Ethan Nicholase6592142020-09-08 10:22:09 -0400525 switch (type.typeKind()) {
526 case Type::TypeKind::kScalar:
John Stiles4a7dc462020-11-25 11:08:08 -0500527 if (type.isBoolean()) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700528 this->writeInstruction(SpvOpTypeBool, result, fConstantBuffer);
John Stiles54e7c052021-01-11 14:22:36 -0500529 } else if (type == *fContext.fTypes.fInt || type == *fContext.fTypes.fShort ||
530 type == *fContext.fTypes.fIntLiteral) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700531 this->writeInstruction(SpvOpTypeInt, result, 32, 1, fConstantBuffer);
John Stiles54e7c052021-01-11 14:22:36 -0500532 } else if (type == *fContext.fTypes.fUInt || type == *fContext.fTypes.fUShort) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700533 this->writeInstruction(SpvOpTypeInt, result, 32, 0, fConstantBuffer);
John Stiles54e7c052021-01-11 14:22:36 -0500534 } else if (type == *fContext.fTypes.fFloat || type == *fContext.fTypes.fHalf ||
535 type == *fContext.fTypes.fFloatLiteral) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700536 this->writeInstruction(SpvOpTypeFloat, result, 32, fConstantBuffer);
ethannicholasb3058bd2016-07-01 08:22:01 -0700537 } else {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400538 SkASSERT(false);
ethannicholasb3058bd2016-07-01 08:22:01 -0700539 }
540 break;
John Stilesfd41d872020-11-25 22:39:45 -0500541 case Type::TypeKind::kEnum:
542 this->writeInstruction(SpvOpTypeInt, result, 32, 1, fConstantBuffer);
543 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400544 case Type::TypeKind::kVector:
Greg Daniel64773e62016-11-22 09:44:03 -0500545 this->writeInstruction(SpvOpTypeVector, result,
ethannicholas8ac838d2016-11-22 08:39:36 -0800546 this->getType(type.componentType(), layout),
ethannicholasb3058bd2016-07-01 08:22:01 -0700547 type.columns(), fConstantBuffer);
548 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400549 case Type::TypeKind::kMatrix:
John Stiles51d33982021-03-08 09:18:07 -0500550 this->writeInstruction(
551 SpvOpTypeMatrix,
552 result,
553 this->getType(IndexExpression::IndexType(fContext, type), layout),
554 type.columns(),
555 fConstantBuffer);
ethannicholasb3058bd2016-07-01 08:22:01 -0700556 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400557 case Type::TypeKind::kStruct:
ethannicholas8ac838d2016-11-22 08:39:36 -0800558 this->writeStruct(type, layout, result);
ethannicholasb3058bd2016-07-01 08:22:01 -0700559 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400560 case Type::TypeKind::kArray: {
John Stiles21f5f452020-11-30 09:57:59 -0500561 if (!MemoryLayout::LayoutIsSupported(type)) {
562 fErrors.error(type.fOffset, "type '" + type.name() + "' is not permitted here");
Ethan Nicholas8f352ce2021-03-17 14:12:20 -0400563 return this->nextId(nullptr);
John Stiles21f5f452020-11-30 09:57:59 -0500564 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700565 if (type.columns() > 0) {
John Stilesb5db4822021-01-21 13:04:40 -0500566 SpvId typeId = this->getType(type.componentType(), layout);
John Stiles9ce80f72021-03-11 22:35:19 -0500567 IntLiteral countLiteral(/*offset=*/-1, type.columns(),
568 fContext.fTypes.fInt.get());
John Stilesb5db4822021-01-21 13:04:40 -0500569 SpvId countId = this->writeIntLiteral(countLiteral);
570 this->writeInstruction(SpvOpTypeArray, result, typeId, countId,
571 fConstantBuffer);
Greg Daniel64773e62016-11-22 09:44:03 -0500572 this->writeInstruction(SpvOpDecorate, result, SpvDecorationArrayStride,
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400573 (int32_t) layout.stride(type),
ethannicholas8ac838d2016-11-22 08:39:36 -0800574 fDecorationBuffer);
ethannicholasb3058bd2016-07-01 08:22:01 -0700575 } else {
John Stiles5570c512020-11-19 17:58:07 -0500576 // We shouldn't have any runtime-sized arrays right now
577 fErrors.error(type.fOffset, "runtime-sized arrays are not supported in SPIR-V");
Greg Daniel64773e62016-11-22 09:44:03 -0500578 this->writeInstruction(SpvOpTypeRuntimeArray, result,
ethannicholas8ac838d2016-11-22 08:39:36 -0800579 this->getType(type.componentType(), layout),
580 fConstantBuffer);
Ethan Nicholas0dd30d92017-05-01 16:57:07 -0400581 this->writeInstruction(SpvOpDecorate, result, SpvDecorationArrayStride,
582 (int32_t) layout.stride(type),
583 fDecorationBuffer);
ethannicholasb3058bd2016-07-01 08:22:01 -0700584 }
585 break;
586 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400587 case Type::TypeKind::kSampler: {
Greg Daniel64773e62016-11-22 09:44:03 -0500588 SpvId image = result;
589 if (SpvDimSubpassData != type.dimensions()) {
Stephen White792e2302019-08-09 13:33:51 -0400590 image = this->getType(type.textureType(), layout);
Greg Daniel64773e62016-11-22 09:44:03 -0500591 }
Ethan Nicholas0187ae62017-05-03 11:03:44 -0400592 if (SpvDimBuffer == type.dimensions()) {
593 fCapabilities |= (((uint64_t) 1) << SpvCapabilitySampledBuffer);
594 }
Greg Daniel64773e62016-11-22 09:44:03 -0500595 if (SpvDimSubpassData != type.dimensions()) {
596 this->writeInstruction(SpvOpTypeSampledImage, result, image, fConstantBuffer);
597 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700598 break;
599 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400600 case Type::TypeKind::kSeparateSampler: {
Stephen Whiteff5d7a22019-07-26 17:42:06 -0400601 this->writeInstruction(SpvOpTypeSampler, result, fConstantBuffer);
602 break;
603 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400604 case Type::TypeKind::kTexture: {
Stephen Whiteff5d7a22019-07-26 17:42:06 -0400605 this->writeInstruction(SpvOpTypeImage, result,
John Stiles54e7c052021-01-11 14:22:36 -0500606 this->getType(*fContext.fTypes.fFloat, layout),
John Stilesc0c51062020-12-03 17:16:29 -0500607 type.dimensions(), type.isDepth(), type.isArrayedTexture(),
Stephen White792e2302019-08-09 13:33:51 -0400608 type.isMultisampled(), type.isSampled() ? 1 : 2,
Stephen Whiteff5d7a22019-07-26 17:42:06 -0400609 SpvImageFormatUnknown, fConstantBuffer);
610 fImageTypeMap[key] = result;
611 break;
612 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700613 default:
John Stiles2558c462021-03-16 17:49:20 -0400614 if (type.isVoid()) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700615 this->writeInstruction(SpvOpTypeVoid, result, fConstantBuffer);
616 } else {
John Stileseada7bc2021-02-02 16:29:32 -0500617 SkDEBUGFAILF("invalid type: %s", type.description().c_str());
ethannicholasb3058bd2016-07-01 08:22:01 -0700618 }
619 }
ethannicholas8ac838d2016-11-22 08:39:36 -0800620 fTypeMap[key] = result;
ethannicholasb3058bd2016-07-01 08:22:01 -0700621 return result;
622 }
623 return entry->second;
624}
625
Ethan Nicholas0187ae62017-05-03 11:03:44 -0400626SpvId SPIRVCodeGenerator::getImageType(const Type& type) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400627 SkASSERT(type.typeKind() == Type::TypeKind::kSampler);
Ethan Nicholas0187ae62017-05-03 11:03:44 -0400628 this->getType(type);
629 String key = type.name() + to_string((int) fDefaultLayout.fStd);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400630 SkASSERT(fImageTypeMap.find(key) != fImageTypeMap.end());
Ethan Nicholas0187ae62017-05-03 11:03:44 -0400631 return fImageTypeMap[key];
632}
633
ethannicholasd598f792016-07-25 10:08:54 -0700634SpvId SPIRVCodeGenerator::getFunctionType(const FunctionDeclaration& function) {
Ethan Nicholased84b732020-10-08 11:45:44 -0400635 String key = to_string(this->getType(function.returnType())) + "(";
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400636 String separator;
Brian Osman5bf3e202020-10-13 10:34:18 -0400637 const std::vector<const Variable*>& parameters = function.parameters();
Ethan Nicholased84b732020-10-08 11:45:44 -0400638 for (size_t i = 0; i < parameters.size(); i++) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700639 key += separator;
640 separator = ", ";
Ethan Nicholased84b732020-10-08 11:45:44 -0400641 key += to_string(this->getType(parameters[i]->type()));
ethannicholasb3058bd2016-07-01 08:22:01 -0700642 }
643 key += ")";
644 auto entry = fTypeMap.find(key);
645 if (entry == fTypeMap.end()) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -0400646 SpvId result = this->nextId(nullptr);
Ethan Nicholased84b732020-10-08 11:45:44 -0400647 int32_t length = 3 + (int32_t) parameters.size();
648 SpvId returnType = this->getType(function.returnType());
ethannicholasb3058bd2016-07-01 08:22:01 -0700649 std::vector<SpvId> parameterTypes;
Ethan Nicholased84b732020-10-08 11:45:44 -0400650 for (size_t i = 0; i < parameters.size(); i++) {
Greg Daniel64773e62016-11-22 09:44:03 -0500651 // glslang seems to treat all function arguments as pointers whether they need to be or
652 // not. I was initially puzzled by this until I ran bizarre failures with certain
653 // patterns of function calls and control constructs, as exemplified by this minimal
ethannicholasb3058bd2016-07-01 08:22:01 -0700654 // failure case:
655 //
656 // void sphere(float x) {
657 // }
Greg Daniel64773e62016-11-22 09:44:03 -0500658 //
ethannicholasb3058bd2016-07-01 08:22:01 -0700659 // void map() {
660 // sphere(1.0);
661 // }
Greg Daniel64773e62016-11-22 09:44:03 -0500662 //
ethannicholasb3058bd2016-07-01 08:22:01 -0700663 // void main() {
664 // for (int i = 0; i < 1; i++) {
665 // map();
666 // }
667 // }
668 //
Greg Daniel64773e62016-11-22 09:44:03 -0500669 // As of this writing, compiling this in the "obvious" way (with sphere taking a float)
670 // crashes. Making it take a float* and storing the argument in a temporary variable,
ethannicholasb3058bd2016-07-01 08:22:01 -0700671 // as glslang does, fixes it. It's entirely possible I simply missed whichever part of
672 // the spec makes this make sense.
673// if (is_out(function->fParameters[i])) {
Ethan Nicholased84b732020-10-08 11:45:44 -0400674 parameterTypes.push_back(this->getPointerType(parameters[i]->type(),
ethannicholasb3058bd2016-07-01 08:22:01 -0700675 SpvStorageClassFunction));
676// } else {
ethannicholasd598f792016-07-25 10:08:54 -0700677// parameterTypes.push_back(this->getType(function.fParameters[i]->fType));
ethannicholasb3058bd2016-07-01 08:22:01 -0700678// }
679 }
680 this->writeOpCode(SpvOpTypeFunction, length, fConstantBuffer);
681 this->writeWord(result, fConstantBuffer);
682 this->writeWord(returnType, fConstantBuffer);
683 for (SpvId id : parameterTypes) {
684 this->writeWord(id, fConstantBuffer);
685 }
686 fTypeMap[key] = result;
687 return result;
688 }
689 return entry->second;
690}
691
ethannicholas8ac838d2016-11-22 08:39:36 -0800692SpvId SPIRVCodeGenerator::getPointerType(const Type& type, SpvStorageClass_ storageClass) {
693 return this->getPointerType(type, fDefaultLayout, storageClass);
694}
695
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400696SpvId SPIRVCodeGenerator::getPointerType(const Type& rawType, const MemoryLayout& layout,
ethannicholasb3058bd2016-07-01 08:22:01 -0700697 SpvStorageClass_ storageClass) {
Ethan Nicholase2c49992020-10-05 11:49:11 -0400698 const Type& type = this->getActualType(rawType);
Ethan Nicholas2a099da2020-01-02 14:40:54 -0500699 String key = type.displayName() + "*" + to_string(layout.fStd) + to_string(storageClass);
ethannicholasb3058bd2016-07-01 08:22:01 -0700700 auto entry = fTypeMap.find(key);
701 if (entry == fTypeMap.end()) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -0400702 SpvId result = this->nextId(nullptr);
Greg Daniel64773e62016-11-22 09:44:03 -0500703 this->writeInstruction(SpvOpTypePointer, result, storageClass,
ethannicholasd598f792016-07-25 10:08:54 -0700704 this->getType(type), fConstantBuffer);
ethannicholasb3058bd2016-07-01 08:22:01 -0700705 fTypeMap[key] = result;
706 return result;
707 }
708 return entry->second;
709}
710
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400711SpvId SPIRVCodeGenerator::writeExpression(const Expression& expr, OutputStream& out) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400712 switch (expr.kind()) {
713 case Expression::Kind::kBinary:
John Stiles81365af2020-08-18 09:24:00 -0400714 return this->writeBinaryExpression(expr.as<BinaryExpression>(), out);
Ethan Nicholase6592142020-09-08 10:22:09 -0400715 case Expression::Kind::kBoolLiteral:
John Stiles81365af2020-08-18 09:24:00 -0400716 return this->writeBoolLiteral(expr.as<BoolLiteral>());
John Stiles7384b372021-04-01 13:48:15 -0400717 case Expression::Kind::kConstructorArray:
John Stilesd47330f2021-04-08 23:25:52 -0400718 case Expression::Kind::kConstructorStruct:
719 return this->writeCompositeConstructor(expr.asAnyConstructor(), out);
John Stilese1182782021-03-30 22:09:37 -0400720 case Expression::Kind::kConstructorDiagonalMatrix:
721 return this->writeConstructorDiagonalMatrix(expr.as<ConstructorDiagonalMatrix>(), out);
John Stiles5abb9e12021-04-06 13:47:19 -0400722 case Expression::Kind::kConstructorMatrixResize:
723 return this->writeConstructorMatrixResize(expr.as<ConstructorMatrixResize>(), out);
John Stilesfd7252f2021-04-04 22:24:40 -0400724 case Expression::Kind::kConstructorScalarCast:
725 return this->writeConstructorScalarCast(expr.as<ConstructorScalarCast>(), out);
John Stiles2938eea2021-04-01 18:58:25 -0400726 case Expression::Kind::kConstructorSplat:
727 return this->writeConstructorSplat(expr.as<ConstructorSplat>(), out);
John Stiles8cad6372021-04-07 12:31:13 -0400728 case Expression::Kind::kConstructorCompound:
729 return this->writeConstructorCompound(expr.as<ConstructorCompound>(), out);
730 case Expression::Kind::kConstructorCompoundCast:
731 return this->writeConstructorCompoundCast(expr.as<ConstructorCompoundCast>(), out);
Ethan Nicholase6592142020-09-08 10:22:09 -0400732 case Expression::Kind::kIntLiteral:
John Stiles81365af2020-08-18 09:24:00 -0400733 return this->writeIntLiteral(expr.as<IntLiteral>());
Ethan Nicholase6592142020-09-08 10:22:09 -0400734 case Expression::Kind::kFieldAccess:
John Stiles81365af2020-08-18 09:24:00 -0400735 return this->writeFieldAccess(expr.as<FieldAccess>(), out);
Ethan Nicholase6592142020-09-08 10:22:09 -0400736 case Expression::Kind::kFloatLiteral:
John Stiles81365af2020-08-18 09:24:00 -0400737 return this->writeFloatLiteral(expr.as<FloatLiteral>());
Ethan Nicholase6592142020-09-08 10:22:09 -0400738 case Expression::Kind::kFunctionCall:
John Stiles81365af2020-08-18 09:24:00 -0400739 return this->writeFunctionCall(expr.as<FunctionCall>(), out);
Ethan Nicholase6592142020-09-08 10:22:09 -0400740 case Expression::Kind::kPrefix:
John Stiles81365af2020-08-18 09:24:00 -0400741 return this->writePrefixExpression(expr.as<PrefixExpression>(), out);
Ethan Nicholase6592142020-09-08 10:22:09 -0400742 case Expression::Kind::kPostfix:
John Stiles81365af2020-08-18 09:24:00 -0400743 return this->writePostfixExpression(expr.as<PostfixExpression>(), out);
Ethan Nicholase6592142020-09-08 10:22:09 -0400744 case Expression::Kind::kSwizzle:
John Stiles81365af2020-08-18 09:24:00 -0400745 return this->writeSwizzle(expr.as<Swizzle>(), out);
Ethan Nicholase6592142020-09-08 10:22:09 -0400746 case Expression::Kind::kVariableReference:
John Stiles81365af2020-08-18 09:24:00 -0400747 return this->writeVariableReference(expr.as<VariableReference>(), out);
Ethan Nicholase6592142020-09-08 10:22:09 -0400748 case Expression::Kind::kTernary:
John Stiles81365af2020-08-18 09:24:00 -0400749 return this->writeTernaryExpression(expr.as<TernaryExpression>(), out);
Ethan Nicholase6592142020-09-08 10:22:09 -0400750 case Expression::Kind::kIndex:
John Stiles81365af2020-08-18 09:24:00 -0400751 return this->writeIndexExpression(expr.as<IndexExpression>(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -0700752 default:
John Stileseada7bc2021-02-02 16:29:32 -0500753 SkDEBUGFAILF("unsupported expression: %s", expr.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -0500754 break;
ethannicholasb3058bd2016-07-01 08:22:01 -0700755 }
756 return -1;
757}
758
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400759SpvId SPIRVCodeGenerator::writeIntrinsicCall(const FunctionCall& c, OutputStream& out) {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400760 const FunctionDeclaration& function = c.function();
John Stilesaaac4e42021-05-06 14:08:28 -0400761 auto intrinsic = fIntrinsicMap.find(function.intrinsicKind());
John Stiles93e661a2020-12-08 16:17:00 -0500762 if (intrinsic == fIntrinsicMap.end()) {
763 fErrors.error(c.fOffset, "unsupported intrinsic '" + function.description() + "'");
764 return -1;
765 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700766 int32_t intrinsicId;
John Stiles89ac7c22020-12-30 17:47:31 -0500767 const ExpressionArray& arguments = c.arguments();
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400768 if (arguments.size() > 0) {
769 const Type& type = arguments[0]->type();
John Stilesaaac4e42021-05-06 14:08:28 -0400770 if (std::get<0>(intrinsic->second) == kSpecial_IntrinsicOpcodeKind ||
771 is_float(fContext, type)) {
Ethan Nicholasbb155e22017-07-24 10:05:09 -0400772 intrinsicId = std::get<1>(intrinsic->second);
773 } else if (is_signed(fContext, type)) {
774 intrinsicId = std::get<2>(intrinsic->second);
775 } else if (is_unsigned(fContext, type)) {
776 intrinsicId = std::get<3>(intrinsic->second);
777 } else if (is_bool(fContext, type)) {
778 intrinsicId = std::get<4>(intrinsic->second);
779 } else {
780 intrinsicId = std::get<1>(intrinsic->second);
781 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700782 } else {
Ethan Nicholasbb155e22017-07-24 10:05:09 -0400783 intrinsicId = std::get<1>(intrinsic->second);
ethannicholasb3058bd2016-07-01 08:22:01 -0700784 }
785 switch (std::get<0>(intrinsic->second)) {
John Stilesaaac4e42021-05-06 14:08:28 -0400786 case kGLSL_STD_450_IntrinsicOpcodeKind: {
Ethan Nicholas7f015882021-03-23 14:16:52 -0400787 SpvId result = this->nextId(&c.type());
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400788 std::vector<SpvId> argumentIds;
789 for (size_t i = 0; i < arguments.size(); i++) {
Ethan Nicholased84b732020-10-08 11:45:44 -0400790 if (function.parameters()[i]->modifiers().fFlags & Modifiers::kOut_Flag) {
John Stilesec241542021-02-11 17:50:09 -0500791 // TODO(skia:11052): swizzled lvalues won't work with getPointer()
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400792 argumentIds.push_back(this->getLValue(*arguments[i], out)->getPointer());
Ethan Nicholas8f7e28f2018-03-26 14:24:27 -0400793 } else {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400794 argumentIds.push_back(this->writeExpression(*arguments[i], out));
Ethan Nicholas8f7e28f2018-03-26 14:24:27 -0400795 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700796 }
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400797 this->writeOpCode(SpvOpExtInst, 5 + (int32_t) argumentIds.size(), out);
Ethan Nicholas30d30222020-09-11 12:27:26 -0400798 this->writeWord(this->getType(c.type()), out);
ethannicholasb3058bd2016-07-01 08:22:01 -0700799 this->writeWord(result, out);
800 this->writeWord(fGLSLExtendedInstructions, out);
801 this->writeWord(intrinsicId, out);
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400802 for (SpvId id : argumentIds) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700803 this->writeWord(id, out);
804 }
805 return result;
806 }
John Stilesaaac4e42021-05-06 14:08:28 -0400807 case kSPIRV_IntrinsicOpcodeKind: {
Brian Osman46787d52020-11-24 14:18:23 -0500808 // GLSL supports dot(float, float), but SPIR-V does not. Convert it to FMul
John Stiles9aeed132020-11-24 17:36:06 -0500809 if (intrinsicId == SpvOpDot && arguments[0]->type().isScalar()) {
Brian Osman46787d52020-11-24 14:18:23 -0500810 intrinsicId = SpvOpFMul;
811 }
Ethan Nicholas7f015882021-03-23 14:16:52 -0400812 SpvId result = this->nextId(&c.type());
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400813 std::vector<SpvId> argumentIds;
814 for (size_t i = 0; i < arguments.size(); i++) {
Ethan Nicholased84b732020-10-08 11:45:44 -0400815 if (function.parameters()[i]->modifiers().fFlags & Modifiers::kOut_Flag) {
John Stilesec241542021-02-11 17:50:09 -0500816 // TODO(skia:11052): swizzled lvalues won't work with getPointer()
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400817 argumentIds.push_back(this->getLValue(*arguments[i], out)->getPointer());
Ethan Nicholas8f7e28f2018-03-26 14:24:27 -0400818 } else {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400819 argumentIds.push_back(this->writeExpression(*arguments[i], out));
Ethan Nicholas8f7e28f2018-03-26 14:24:27 -0400820 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700821 }
John Stiles2558c462021-03-16 17:49:20 -0400822 if (!c.type().isVoid()) {
Ethan Nicholasbb155e22017-07-24 10:05:09 -0400823 this->writeOpCode((SpvOp_) intrinsicId, 3 + (int32_t) arguments.size(), out);
Ethan Nicholas30d30222020-09-11 12:27:26 -0400824 this->writeWord(this->getType(c.type()), out);
Ethan Nicholasbb155e22017-07-24 10:05:09 -0400825 this->writeWord(result, out);
826 } else {
827 this->writeOpCode((SpvOp_) intrinsicId, 1 + (int32_t) arguments.size(), out);
828 }
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400829 for (SpvId id : argumentIds) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700830 this->writeWord(id, out);
831 }
832 return result;
833 }
John Stilesaaac4e42021-05-06 14:08:28 -0400834 case kSpecial_IntrinsicOpcodeKind:
ethannicholasb3058bd2016-07-01 08:22:01 -0700835 return this->writeSpecialIntrinsic(c, (SpecialIntrinsic) intrinsicId, out);
836 default:
John Stiles93e661a2020-12-08 16:17:00 -0500837 fErrors.error(c.fOffset, "unsupported intrinsic '" + function.description() + "'");
838 return -1;
ethannicholasb3058bd2016-07-01 08:22:01 -0700839 }
840}
841
John Stiles8e3b6be2020-10-13 11:14:08 -0400842std::vector<SpvId> SPIRVCodeGenerator::vectorize(const ExpressionArray& args, OutputStream& out) {
Ethan Nicholas0fc07f92018-02-27 15:25:47 -0500843 int vectorSize = 0;
844 for (const auto& a : args) {
John Stiles9aeed132020-11-24 17:36:06 -0500845 if (a->type().isVector()) {
Ethan Nicholas0fc07f92018-02-27 15:25:47 -0500846 if (vectorSize) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400847 SkASSERT(a->type().columns() == vectorSize);
Ethan Nicholas0fc07f92018-02-27 15:25:47 -0500848 }
849 else {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400850 vectorSize = a->type().columns();
Ethan Nicholas0fc07f92018-02-27 15:25:47 -0500851 }
852 }
853 }
854 std::vector<SpvId> result;
John Stiles8e3b6be2020-10-13 11:14:08 -0400855 result.reserve(args.size());
Ethan Nicholas30d30222020-09-11 12:27:26 -0400856 for (const auto& arg : args) {
857 const Type& argType = arg->type();
John Stiles9aeed132020-11-24 17:36:06 -0500858 if (vectorSize && argType.isScalar()) {
John Stiles5d61cc22021-05-13 17:46:19 -0400859 ConstructorSplat splat{/*offset=*/-1,
860 argType.toCompound(fContext, vectorSize, /*rows=*/1),
861 arg->clone()};
862 result.push_back(this->writeConstructorSplat(splat, out));
Ethan Nicholas0fc07f92018-02-27 15:25:47 -0500863 } else {
John Stiles5d61cc22021-05-13 17:46:19 -0400864 result.push_back(this->writeExpression(*arg, out));
Ethan Nicholas0fc07f92018-02-27 15:25:47 -0500865 }
866 }
867 return result;
868}
869
870void SPIRVCodeGenerator::writeGLSLExtendedInstruction(const Type& type, SpvId id, SpvId floatInst,
871 SpvId signedInst, SpvId unsignedInst,
872 const std::vector<SpvId>& args,
873 OutputStream& out) {
874 this->writeOpCode(SpvOpExtInst, 5 + args.size(), out);
875 this->writeWord(this->getType(type), out);
876 this->writeWord(id, out);
877 this->writeWord(fGLSLExtendedInstructions, out);
878
879 if (is_float(fContext, type)) {
880 this->writeWord(floatInst, out);
881 } else if (is_signed(fContext, type)) {
882 this->writeWord(signedInst, out);
883 } else if (is_unsigned(fContext, type)) {
884 this->writeWord(unsignedInst, out);
885 } else {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400886 SkASSERT(false);
Ethan Nicholas0fc07f92018-02-27 15:25:47 -0500887 }
888 for (SpvId a : args) {
889 this->writeWord(a, out);
890 }
891}
892
Greg Daniel64773e62016-11-22 09:44:03 -0500893SpvId SPIRVCodeGenerator::writeSpecialIntrinsic(const FunctionCall& c, SpecialIntrinsic kind,
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400894 OutputStream& out) {
John Stiles8e3b6be2020-10-13 11:14:08 -0400895 const ExpressionArray& arguments = c.arguments();
Ethan Nicholas30d30222020-09-11 12:27:26 -0400896 const Type& callType = c.type();
Ethan Nicholas8f352ce2021-03-17 14:12:20 -0400897 SpvId result = this->nextId(nullptr);
ethannicholasb3058bd2016-07-01 08:22:01 -0700898 switch (kind) {
899 case kAtan_SpecialIntrinsic: {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400900 std::vector<SpvId> argumentIds;
901 for (const std::unique_ptr<Expression>& arg : arguments) {
902 argumentIds.push_back(this->writeExpression(*arg, out));
ethannicholasb3058bd2016-07-01 08:22:01 -0700903 }
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400904 this->writeOpCode(SpvOpExtInst, 5 + (int32_t) argumentIds.size(), out);
Ethan Nicholas30d30222020-09-11 12:27:26 -0400905 this->writeWord(this->getType(callType), out);
ethannicholasb3058bd2016-07-01 08:22:01 -0700906 this->writeWord(result, out);
907 this->writeWord(fGLSLExtendedInstructions, out);
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400908 this->writeWord(argumentIds.size() == 2 ? GLSLstd450Atan2 : GLSLstd450Atan, out);
909 for (SpvId id : argumentIds) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700910 this->writeWord(id, out);
911 }
Ethan Nicholas0187ae62017-05-03 11:03:44 -0400912 break;
913 }
Stephen Whiteff5d7a22019-07-26 17:42:06 -0400914 case kSampledImage_SpecialIntrinsic: {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400915 SkASSERT(arguments.size() == 2);
916 SpvId img = this->writeExpression(*arguments[0], out);
917 SpvId sampler = this->writeExpression(*arguments[1], out);
Stephen Whiteff5d7a22019-07-26 17:42:06 -0400918 this->writeInstruction(SpvOpSampledImage,
Ethan Nicholas30d30222020-09-11 12:27:26 -0400919 this->getType(callType),
Stephen Whiteff5d7a22019-07-26 17:42:06 -0400920 result,
921 img,
922 sampler,
923 out);
924 break;
925 }
Ethan Nicholas0187ae62017-05-03 11:03:44 -0400926 case kSubpassLoad_SpecialIntrinsic: {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400927 SpvId img = this->writeExpression(*arguments[0], out);
John Stiles8e3b6be2020-10-13 11:14:08 -0400928 ExpressionArray args;
John Stilesf4bda742020-10-14 16:57:41 -0400929 args.reserve_back(2);
John Stiles9ce80f72021-03-11 22:35:19 -0500930 args.push_back(IntLiteral::Make(fContext, /*offset=*/-1, /*value=*/0));
931 args.push_back(IntLiteral::Make(fContext, /*offset=*/-1, /*value=*/0));
John Stiles8cad6372021-04-07 12:31:13 -0400932 ConstructorCompound ctor(/*offset=*/-1, *fContext.fTypes.fInt2, std::move(args));
Ethan Nicholas0187ae62017-05-03 11:03:44 -0400933 SpvId coords = this->writeConstantVector(ctor);
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400934 if (arguments.size() == 1) {
Ethan Nicholas0187ae62017-05-03 11:03:44 -0400935 this->writeInstruction(SpvOpImageRead,
Ethan Nicholas30d30222020-09-11 12:27:26 -0400936 this->getType(callType),
Ethan Nicholas0187ae62017-05-03 11:03:44 -0400937 result,
938 img,
939 coords,
940 out);
941 } else {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400942 SkASSERT(arguments.size() == 2);
943 SpvId sample = this->writeExpression(*arguments[1], out);
Ethan Nicholas0187ae62017-05-03 11:03:44 -0400944 this->writeInstruction(SpvOpImageRead,
Ethan Nicholas30d30222020-09-11 12:27:26 -0400945 this->getType(callType),
Ethan Nicholas0187ae62017-05-03 11:03:44 -0400946 result,
947 img,
948 coords,
949 SpvImageOperandsSampleMask,
950 sample,
951 out);
952 }
953 break;
954 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700955 case kTexture_SpecialIntrinsic: {
Ethan Nicholas2b3dab62016-11-28 12:03:26 -0500956 SpvOp_ op = SpvOpImageSampleImplicitLod;
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400957 const Type& arg1Type = arguments[1]->type();
958 switch (arguments[0]->type().dimensions()) {
Ethan Nicholas2b3dab62016-11-28 12:03:26 -0500959 case SpvDim1D:
John Stiles54e7c052021-01-11 14:22:36 -0500960 if (arg1Type == *fContext.fTypes.fFloat2) {
Ethan Nicholas2b3dab62016-11-28 12:03:26 -0500961 op = SpvOpImageSampleProjImplicitLod;
962 } else {
John Stiles54e7c052021-01-11 14:22:36 -0500963 SkASSERT(arg1Type == *fContext.fTypes.fFloat);
Ethan Nicholas2b3dab62016-11-28 12:03:26 -0500964 }
965 break;
966 case SpvDim2D:
John Stiles54e7c052021-01-11 14:22:36 -0500967 if (arg1Type == *fContext.fTypes.fFloat3) {
Ethan Nicholas2b3dab62016-11-28 12:03:26 -0500968 op = SpvOpImageSampleProjImplicitLod;
969 } else {
John Stiles54e7c052021-01-11 14:22:36 -0500970 SkASSERT(arg1Type == *fContext.fTypes.fFloat2);
Ethan Nicholas2b3dab62016-11-28 12:03:26 -0500971 }
972 break;
973 case SpvDim3D:
John Stiles54e7c052021-01-11 14:22:36 -0500974 if (arg1Type == *fContext.fTypes.fFloat4) {
Ethan Nicholas2b3dab62016-11-28 12:03:26 -0500975 op = SpvOpImageSampleProjImplicitLod;
976 } else {
John Stiles54e7c052021-01-11 14:22:36 -0500977 SkASSERT(arg1Type == *fContext.fTypes.fFloat3);
Ethan Nicholas2b3dab62016-11-28 12:03:26 -0500978 }
979 break;
980 case SpvDimCube: // fall through
981 case SpvDimRect: // fall through
982 case SpvDimBuffer: // fall through
983 case SpvDimSubpassData:
984 break;
985 }
Ethan Nicholas30d30222020-09-11 12:27:26 -0400986 SpvId type = this->getType(callType);
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400987 SpvId sampler = this->writeExpression(*arguments[0], out);
988 SpvId uv = this->writeExpression(*arguments[1], out);
989 if (arguments.size() == 3) {
Ethan Nicholas2b3dab62016-11-28 12:03:26 -0500990 this->writeInstruction(op, type, result, sampler, uv,
ethannicholasb3058bd2016-07-01 08:22:01 -0700991 SpvImageOperandsBiasMask,
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400992 this->writeExpression(*arguments[2], out),
ethannicholasb3058bd2016-07-01 08:22:01 -0700993 out);
994 } else {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400995 SkASSERT(arguments.size() == 2);
John Stiles270cec22021-02-17 12:59:36 -0500996 if (fProgram.fConfig->fSettings.fSharpenTextures) {
John Stiles9ce80f72021-03-11 22:35:19 -0500997 FloatLiteral lodBias(/*offset=*/-1, /*value=*/-0.5,
998 fContext.fTypes.fFloat.get());
Brian Osman8a83ca42018-02-12 14:32:17 -0500999 this->writeInstruction(op, type, result, sampler, uv,
1000 SpvImageOperandsBiasMask,
1001 this->writeFloatLiteral(lodBias),
1002 out);
1003 } else {
1004 this->writeInstruction(op, type, result, sampler, uv,
1005 out);
1006 }
ethannicholasb3058bd2016-07-01 08:22:01 -07001007 }
1008 break;
1009 }
Ethan Nicholas70a44b22017-11-30 09:09:16 -05001010 case kMod_SpecialIntrinsic: {
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001011 std::vector<SpvId> args = this->vectorize(arguments, out);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001012 SkASSERT(args.size() == 2);
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001013 const Type& operandType = arguments[0]->type();
Ethan Nicholas70a44b22017-11-30 09:09:16 -05001014 SpvOp_ op;
1015 if (is_float(fContext, operandType)) {
1016 op = SpvOpFMod;
1017 } else if (is_signed(fContext, operandType)) {
1018 op = SpvOpSMod;
1019 } else if (is_unsigned(fContext, operandType)) {
1020 op = SpvOpUMod;
1021 } else {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001022 SkASSERT(false);
Ethan Nicholas70a44b22017-11-30 09:09:16 -05001023 return 0;
1024 }
1025 this->writeOpCode(op, 5, out);
1026 this->writeWord(this->getType(operandType), out);
1027 this->writeWord(result, out);
Ethan Nicholas0fc07f92018-02-27 15:25:47 -05001028 this->writeWord(args[0], out);
1029 this->writeWord(args[1], out);
1030 break;
1031 }
Chris Daltonb8af5ad2019-02-25 14:54:21 -07001032 case kDFdy_SpecialIntrinsic: {
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001033 SpvId fn = this->writeExpression(*arguments[0], out);
Chris Daltonb8af5ad2019-02-25 14:54:21 -07001034 this->writeOpCode(SpvOpDPdy, 4, out);
Ethan Nicholas30d30222020-09-11 12:27:26 -04001035 this->writeWord(this->getType(callType), out);
Chris Daltonb8af5ad2019-02-25 14:54:21 -07001036 this->writeWord(result, out);
1037 this->writeWord(fn, out);
John Stiles270cec22021-02-17 12:59:36 -05001038 if (fProgram.fConfig->fSettings.fFlipY) {
Chris Daltonb8af5ad2019-02-25 14:54:21 -07001039 // Flipping Y also negates the Y derivatives.
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001040 SpvId flipped = this->nextId(&callType);
Ethan Nicholas30d30222020-09-11 12:27:26 -04001041 this->writeInstruction(SpvOpFNegate, this->getType(callType), flipped, result,
1042 out);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001043 result = flipped;
Chris Daltonb8af5ad2019-02-25 14:54:21 -07001044 }
1045 break;
1046 }
Ethan Nicholas0fc07f92018-02-27 15:25:47 -05001047 case kClamp_SpecialIntrinsic: {
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001048 std::vector<SpvId> args = this->vectorize(arguments, out);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001049 SkASSERT(args.size() == 3);
Ethan Nicholas30d30222020-09-11 12:27:26 -04001050 this->writeGLSLExtendedInstruction(callType, result, GLSLstd450FClamp, GLSLstd450SClamp,
Ethan Nicholas0fc07f92018-02-27 15:25:47 -05001051 GLSLstd450UClamp, args, out);
1052 break;
1053 }
1054 case kMax_SpecialIntrinsic: {
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001055 std::vector<SpvId> args = this->vectorize(arguments, out);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001056 SkASSERT(args.size() == 2);
Ethan Nicholas30d30222020-09-11 12:27:26 -04001057 this->writeGLSLExtendedInstruction(callType, result, GLSLstd450FMax, GLSLstd450SMax,
Ethan Nicholas0fc07f92018-02-27 15:25:47 -05001058 GLSLstd450UMax, args, out);
1059 break;
1060 }
1061 case kMin_SpecialIntrinsic: {
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001062 std::vector<SpvId> args = this->vectorize(arguments, out);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001063 SkASSERT(args.size() == 2);
Ethan Nicholas30d30222020-09-11 12:27:26 -04001064 this->writeGLSLExtendedInstruction(callType, result, GLSLstd450FMin, GLSLstd450SMin,
Ethan Nicholas0fc07f92018-02-27 15:25:47 -05001065 GLSLstd450UMin, args, out);
1066 break;
1067 }
1068 case kMix_SpecialIntrinsic: {
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001069 std::vector<SpvId> args = this->vectorize(arguments, out);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001070 SkASSERT(args.size() == 3);
Ethan Nicholas30d30222020-09-11 12:27:26 -04001071 this->writeGLSLExtendedInstruction(callType, result, GLSLstd450FMix, SpvOpUndef,
Ethan Nicholas0fc07f92018-02-27 15:25:47 -05001072 SpvOpUndef, args, out);
1073 break;
Ethan Nicholas70a44b22017-11-30 09:09:16 -05001074 }
Ethan Nicholas12fb9cf2018-08-03 16:16:57 -04001075 case kSaturate_SpecialIntrinsic: {
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001076 SkASSERT(arguments.size() == 1);
John Stiles8e3b6be2020-10-13 11:14:08 -04001077 ExpressionArray finalArgs;
John Stilesf4bda742020-10-14 16:57:41 -04001078 finalArgs.reserve_back(3);
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001079 finalArgs.push_back(arguments[0]->clone());
John Stiles9ce80f72021-03-11 22:35:19 -05001080 finalArgs.push_back(FloatLiteral::Make(fContext, /*offset=*/-1, /*value=*/0));
1081 finalArgs.push_back(FloatLiteral::Make(fContext, /*offset=*/-1, /*value=*/1));
Ethan Nicholas12fb9cf2018-08-03 16:16:57 -04001082 std::vector<SpvId> spvArgs = this->vectorize(finalArgs, out);
Ethan Nicholas30d30222020-09-11 12:27:26 -04001083 this->writeGLSLExtendedInstruction(callType, result, GLSLstd450FClamp, GLSLstd450SClamp,
Ethan Nicholas12fb9cf2018-08-03 16:16:57 -04001084 GLSLstd450UClamp, spvArgs, out);
1085 break;
1086 }
Brian Osman6ba3be12020-11-13 16:32:52 -05001087 case kSmoothStep_SpecialIntrinsic: {
1088 std::vector<SpvId> args = this->vectorize(arguments, out);
1089 SkASSERT(args.size() == 3);
1090 this->writeGLSLExtendedInstruction(callType, result, GLSLstd450SmoothStep, SpvOpUndef,
1091 SpvOpUndef, args, out);
1092 break;
1093 }
1094 case kStep_SpecialIntrinsic: {
1095 std::vector<SpvId> args = this->vectorize(arguments, out);
1096 SkASSERT(args.size() == 2);
1097 this->writeGLSLExtendedInstruction(callType, result, GLSLstd450Step, SpvOpUndef,
1098 SpvOpUndef, args, out);
1099 break;
1100 }
Brian Osmand1b593f2020-12-28 13:00:46 -05001101 case kMatrixCompMult_SpecialIntrinsic: {
1102 SkASSERT(arguments.size() == 2);
1103 SpvId lhs = this->writeExpression(*arguments[0], out);
1104 SpvId rhs = this->writeExpression(*arguments[1], out);
John Stiles43b593c2021-05-13 22:03:27 -04001105 result = this->writeComponentwiseMatrixBinary(callType, lhs, rhs, SpvOpFMul, out);
Brian Osmand1b593f2020-12-28 13:00:46 -05001106 break;
1107 }
ethannicholasb3058bd2016-07-01 08:22:01 -07001108 }
1109 return result;
1110}
1111
John Stilesec241542021-02-11 17:50:09 -05001112namespace {
1113struct TempVar {
1114 SpvId spvId;
1115 const Type* type;
1116 std::unique_ptr<SPIRVCodeGenerator::LValue> lvalue;
1117};
1118}
1119
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001120SpvId SPIRVCodeGenerator::writeFunctionCall(const FunctionCall& c, OutputStream& out) {
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001121 const FunctionDeclaration& function = c.function();
John Stilesaaac4e42021-05-06 14:08:28 -04001122 if (function.isIntrinsic() && !function.definition()) {
John Stiles89ac7c22020-12-30 17:47:31 -05001123 return this->writeIntrinsicCall(c, out);
1124 }
John Stiles8e3b6be2020-10-13 11:14:08 -04001125 const ExpressionArray& arguments = c.arguments();
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001126 const auto& entry = fFunctionMap.find(&function);
ethannicholasb3058bd2016-07-01 08:22:01 -07001127 if (entry == fFunctionMap.end()) {
John Stiles89ac7c22020-12-30 17:47:31 -05001128 fErrors.error(c.fOffset, "function '" + function.description() + "' is not defined");
1129 return -1;
ethannicholasb3058bd2016-07-01 08:22:01 -07001130 }
John Stilesec241542021-02-11 17:50:09 -05001131 // Temp variables are used to write back out-parameters after the function call is complete.
1132 std::vector<TempVar> tempVars;
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001133 std::vector<SpvId> argumentIds;
1134 for (size_t i = 0; i < arguments.size(); i++) {
Greg Daniel64773e62016-11-22 09:44:03 -05001135 // id of temporary variable that we will use to hold this argument, or 0 if it is being
ethannicholasb3058bd2016-07-01 08:22:01 -07001136 // passed directly
1137 SpvId tmpVar;
1138 // if we need a temporary var to store this argument, this is the value to store in the var
1139 SpvId tmpValueId;
Ethan Nicholased84b732020-10-08 11:45:44 -04001140 if (is_out(*function.parameters()[i])) {
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001141 std::unique_ptr<LValue> lv = this->getLValue(*arguments[i], out);
ethannicholasb3058bd2016-07-01 08:22:01 -07001142 SpvId ptr = lv->getPointer();
Ethan Nicholase0707b72021-03-17 11:16:41 -04001143 if (ptr != (SpvId) -1 && lv->isMemoryObjectPointer()) {
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001144 argumentIds.push_back(ptr);
ethannicholasb3058bd2016-07-01 08:22:01 -07001145 continue;
1146 } else {
1147 // lvalue cannot simply be read and written via a pointer (e.g. a swizzle). Need to
1148 // copy it into a temp, call the function, read the value out of the temp, and then
1149 // update the lvalue.
1150 tmpValueId = lv->load(out);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001151 tmpVar = this->nextId(nullptr);
John Stilesec241542021-02-11 17:50:09 -05001152 tempVars.push_back(TempVar{tmpVar, &arguments[i]->type(), std::move(lv)});
ethannicholasb3058bd2016-07-01 08:22:01 -07001153 }
1154 } else {
John Stilesec241542021-02-11 17:50:09 -05001155 // See getFunctionType for an explanation of why we're always using pointer parameters.
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001156 tmpValueId = this->writeExpression(*arguments[i], out);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001157 tmpVar = this->nextId(nullptr);
ethannicholasb3058bd2016-07-01 08:22:01 -07001158 }
Greg Daniel64773e62016-11-22 09:44:03 -05001159 this->writeInstruction(SpvOpVariable,
John Stilesec241542021-02-11 17:50:09 -05001160 this->getPointerType(arguments[i]->type(), SpvStorageClassFunction),
Greg Daniel64773e62016-11-22 09:44:03 -05001161 tmpVar,
ethannicholasb3058bd2016-07-01 08:22:01 -07001162 SpvStorageClassFunction,
ethannicholasd598f792016-07-25 10:08:54 -07001163 fVariableBuffer);
ethannicholasb3058bd2016-07-01 08:22:01 -07001164 this->writeInstruction(SpvOpStore, tmpVar, tmpValueId, out);
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001165 argumentIds.push_back(tmpVar);
ethannicholasb3058bd2016-07-01 08:22:01 -07001166 }
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001167 SpvId result = this->nextId(nullptr);
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001168 this->writeOpCode(SpvOpFunctionCall, 4 + (int32_t) arguments.size(), out);
Ethan Nicholas30d30222020-09-11 12:27:26 -04001169 this->writeWord(this->getType(c.type()), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07001170 this->writeWord(result, out);
1171 this->writeWord(entry->second, out);
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001172 for (SpvId id : argumentIds) {
ethannicholasb3058bd2016-07-01 08:22:01 -07001173 this->writeWord(id, out);
1174 }
John Stilesec241542021-02-11 17:50:09 -05001175 // Now that the call is complete, we copy temp out-variables back to their real lvalues.
1176 for (const TempVar& tempVar : tempVars) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001177 SpvId load = this->nextId(tempVar.type);
John Stilesec241542021-02-11 17:50:09 -05001178 this->writeInstruction(SpvOpLoad, getType(*tempVar.type), load, tempVar.spvId, out);
John Stilesec241542021-02-11 17:50:09 -05001179 tempVar.lvalue->store(load, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07001180 }
1181 return result;
1182}
1183
John Stiles2938eea2021-04-01 18:58:25 -04001184SpvId SPIRVCodeGenerator::writeConstantVector(const AnyConstructor& c) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001185 const Type& type = c.type();
John Stiles9aeed132020-11-24 17:36:06 -05001186 SkASSERT(type.isVector() && c.isCompileTimeConstant());
John Stilescd806892021-01-06 13:33:31 -05001187
John Stiles9cfaa4f2021-01-06 17:52:00 -05001188 // Get each of the constructor components as SPIR-V constants.
John Stilescd806892021-01-06 13:33:31 -05001189 SPIRVVectorConstant key{this->getType(type),
1190 /*fValueId=*/{SpvId(-1), SpvId(-1), SpvId(-1), SpvId(-1)}};
John Stiles9cfaa4f2021-01-06 17:52:00 -05001191
John Stiles21a50ec2021-04-06 14:49:36 -04001192 for (int n = 0; n < type.columns(); n++) {
1193 const Expression* expr = c.getConstantSubexpression(n);
1194 if (!expr) {
1195 SkDEBUGFAILF("writeConstantVector: %s not actually constant", c.description().c_str());
1196 return (SpvId)-1;
John Stiles9cfaa4f2021-01-06 17:52:00 -05001197 }
John Stiles21a50ec2021-04-06 14:49:36 -04001198 key.fValueId[n] = this->writeExpression(*expr, fConstantBuffer);
ethannicholasb3058bd2016-07-01 08:22:01 -07001199 }
John Stilescd806892021-01-06 13:33:31 -05001200
1201 // Check to see if we've already synthesized this vector constant.
1202 auto [iter, newlyCreated] = fVectorConstants.insert({key, (SpvId)-1});
1203 if (newlyCreated) {
1204 // Emit an OpConstantComposite instruction for this constant.
Ethan Nicholas7f015882021-03-23 14:16:52 -04001205 SpvId result = this->nextId(&type);
John Stiles9cfaa4f2021-01-06 17:52:00 -05001206 this->writeOpCode(SpvOpConstantComposite, 3 + type.columns(), fConstantBuffer);
John Stilescd806892021-01-06 13:33:31 -05001207 this->writeWord(key.fTypeId, fConstantBuffer);
1208 this->writeWord(result, fConstantBuffer);
John Stiles9cfaa4f2021-01-06 17:52:00 -05001209 for (int i = 0; i < type.columns(); i++) {
John Stilescd806892021-01-06 13:33:31 -05001210 this->writeWord(key.fValueId[i], fConstantBuffer);
1211 }
1212 iter->second = result;
1213 }
1214 return iter->second;
ethannicholasb3058bd2016-07-01 08:22:01 -07001215}
1216
John Stilesb14a8192021-04-05 11:40:46 -04001217SpvId SPIRVCodeGenerator::castScalarToType(SpvId inputExprId,
1218 const Type& inputType,
1219 const Type& outputType,
1220 OutputStream& out) {
1221 if (outputType.isFloat()) {
1222 return this->castScalarToFloat(inputExprId, inputType, outputType, out);
1223 }
1224 if (outputType.isSigned()) {
1225 return this->castScalarToSignedInt(inputExprId, inputType, outputType, out);
1226 }
1227 if (outputType.isUnsigned()) {
1228 return this->castScalarToUnsignedInt(inputExprId, inputType, outputType, out);
1229 }
1230 if (outputType.isBoolean()) {
1231 return this->castScalarToBoolean(inputExprId, inputType, outputType, out);
1232 }
1233
1234 fErrors.error(-1, "unsupported cast: " + inputType.description() +
1235 " to " + outputType.description());
1236 return inputExprId;
1237}
1238
John Stilesfd7252f2021-04-04 22:24:40 -04001239SpvId SPIRVCodeGenerator::writeFloatConstructor(const AnyConstructor& c, OutputStream& out) {
1240 SkASSERT(c.argumentSpan().size() == 1);
John Stilesd9d52712021-01-13 17:15:02 -05001241 SkASSERT(c.type().isFloat());
John Stilesfd7252f2021-04-04 22:24:40 -04001242 const Expression& ctorExpr = *c.argumentSpan().front();
John Stilesd9d52712021-01-13 17:15:02 -05001243 SpvId expressionId = this->writeExpression(ctorExpr, out);
1244 return this->castScalarToFloat(expressionId, ctorExpr.type(), c.type(), out);
1245}
1246
1247SpvId SPIRVCodeGenerator::castScalarToFloat(SpvId inputId, const Type& inputType,
1248 const Type& outputType, OutputStream& out) {
1249 // Casting a float to float is a no-op.
1250 if (inputType.isFloat()) {
1251 return inputId;
1252 }
1253
1254 // Given the input type, generate the appropriate instruction to cast to float.
Ethan Nicholas7f015882021-03-23 14:16:52 -04001255 SpvId result = this->nextId(&outputType);
John Stilesd9d52712021-01-13 17:15:02 -05001256 if (inputType.isBoolean()) {
John Stilesba4b0e92021-01-05 13:55:39 -05001257 // Use OpSelect to convert the boolean argument to a literal 1.0 or 0.0.
John Stiles9ce80f72021-03-11 22:35:19 -05001258 FloatLiteral one(/*offset=*/-1, /*value=*/1, fContext.fTypes.fFloat.get());
John Stilesba4b0e92021-01-05 13:55:39 -05001259 SpvId oneID = this->writeFloatLiteral(one);
John Stiles9ce80f72021-03-11 22:35:19 -05001260 FloatLiteral zero(/*offset=*/-1, /*value=*/0, fContext.fTypes.fFloat.get());
John Stilesba4b0e92021-01-05 13:55:39 -05001261 SpvId zeroID = this->writeFloatLiteral(zero);
John Stilesd9d52712021-01-13 17:15:02 -05001262 this->writeInstruction(SpvOpSelect, this->getType(outputType), result,
1263 inputId, oneID, zeroID, out);
1264 } else if (inputType.isSigned()) {
1265 this->writeInstruction(SpvOpConvertSToF, this->getType(outputType), result, inputId, out);
1266 } else if (inputType.isUnsigned()) {
1267 this->writeInstruction(SpvOpConvertUToF, this->getType(outputType), result, inputId, out);
Ethan Nicholasf7b88202017-09-18 14:10:39 -04001268 } else {
John Stilesd9d52712021-01-13 17:15:02 -05001269 SkDEBUGFAILF("unsupported type for float typecast: %s", inputType.description().c_str());
1270 return (SpvId)-1;
ethannicholasb3058bd2016-07-01 08:22:01 -07001271 }
1272 return result;
1273}
1274
John Stilesfd7252f2021-04-04 22:24:40 -04001275SpvId SPIRVCodeGenerator::writeIntConstructor(const AnyConstructor& c, OutputStream& out) {
1276 SkASSERT(c.argumentSpan().size() == 1);
John Stilesd9d52712021-01-13 17:15:02 -05001277 SkASSERT(c.type().isSigned());
John Stilesfd7252f2021-04-04 22:24:40 -04001278 const Expression& ctorExpr = *c.argumentSpan().front();
John Stilesd9d52712021-01-13 17:15:02 -05001279 SpvId expressionId = this->writeExpression(ctorExpr, out);
1280 return this->castScalarToSignedInt(expressionId, ctorExpr.type(), c.type(), out);
1281}
1282
1283SpvId SPIRVCodeGenerator::castScalarToSignedInt(SpvId inputId, const Type& inputType,
1284 const Type& outputType, OutputStream& out) {
1285 // Casting a signed int to signed int is a no-op.
1286 if (inputType.isSigned()) {
1287 return inputId;
1288 }
1289
1290 // Given the input type, generate the appropriate instruction to cast to signed int.
Ethan Nicholas7f015882021-03-23 14:16:52 -04001291 SpvId result = this->nextId(&outputType);
John Stilesd9d52712021-01-13 17:15:02 -05001292 if (inputType.isBoolean()) {
John Stilesba4b0e92021-01-05 13:55:39 -05001293 // Use OpSelect to convert the boolean argument to a literal 1 or 0.
John Stiles54e7c052021-01-11 14:22:36 -05001294 IntLiteral one(/*offset=*/-1, /*value=*/1, fContext.fTypes.fInt.get());
John Stilesba4b0e92021-01-05 13:55:39 -05001295 SpvId oneID = this->writeIntLiteral(one);
John Stiles54e7c052021-01-11 14:22:36 -05001296 IntLiteral zero(/*offset=*/-1, /*value=*/0, fContext.fTypes.fInt.get());
John Stilesba4b0e92021-01-05 13:55:39 -05001297 SpvId zeroID = this->writeIntLiteral(zero);
John Stilesd9d52712021-01-13 17:15:02 -05001298 this->writeInstruction(SpvOpSelect, this->getType(outputType), result,
1299 inputId, oneID, zeroID, out);
1300 } else if (inputType.isFloat()) {
1301 this->writeInstruction(SpvOpConvertFToS, this->getType(outputType), result, inputId, out);
1302 } else if (inputType.isUnsigned()) {
1303 this->writeInstruction(SpvOpBitcast, this->getType(outputType), result, inputId, out);
1304 } else {
1305 SkDEBUGFAILF("unsupported type for signed int typecast: %s",
1306 inputType.description().c_str());
1307 return (SpvId)-1;
ethannicholasb3058bd2016-07-01 08:22:01 -07001308 }
1309 return result;
1310}
1311
John Stilesfd7252f2021-04-04 22:24:40 -04001312SpvId SPIRVCodeGenerator::writeUIntConstructor(const AnyConstructor& c, OutputStream& out) {
1313 SkASSERT(c.argumentSpan().size() == 1);
John Stilesd9d52712021-01-13 17:15:02 -05001314 SkASSERT(c.type().isUnsigned());
John Stilesfd7252f2021-04-04 22:24:40 -04001315 const Expression& ctorExpr = *c.argumentSpan().front();
John Stilesd9d52712021-01-13 17:15:02 -05001316 SpvId expressionId = this->writeExpression(ctorExpr, out);
1317 return this->castScalarToUnsignedInt(expressionId, ctorExpr.type(), c.type(), out);
1318}
1319
1320SpvId SPIRVCodeGenerator::castScalarToUnsignedInt(SpvId inputId, const Type& inputType,
1321 const Type& outputType, OutputStream& out) {
1322 // Casting an unsigned int to unsigned int is a no-op.
1323 if (inputType.isUnsigned()) {
1324 return inputId;
1325 }
1326
John Stiles48c28842021-01-14 11:05:03 -05001327 // Given the input type, generate the appropriate instruction to cast to unsigned int.
Ethan Nicholas7f015882021-03-23 14:16:52 -04001328 SpvId result = this->nextId(&outputType);
John Stilesd9d52712021-01-13 17:15:02 -05001329 if (inputType.isBoolean()) {
John Stilesba4b0e92021-01-05 13:55:39 -05001330 // Use OpSelect to convert the boolean argument to a literal 1u or 0u.
John Stiles54e7c052021-01-11 14:22:36 -05001331 IntLiteral one(/*offset=*/-1, /*value=*/1, fContext.fTypes.fUInt.get());
John Stilesba4b0e92021-01-05 13:55:39 -05001332 SpvId oneID = this->writeIntLiteral(one);
John Stiles54e7c052021-01-11 14:22:36 -05001333 IntLiteral zero(/*offset=*/-1, /*value=*/0, fContext.fTypes.fUInt.get());
John Stilesba4b0e92021-01-05 13:55:39 -05001334 SpvId zeroID = this->writeIntLiteral(zero);
John Stilesd9d52712021-01-13 17:15:02 -05001335 this->writeInstruction(SpvOpSelect, this->getType(outputType), result,
1336 inputId, oneID, zeroID, out);
1337 } else if (inputType.isFloat()) {
1338 this->writeInstruction(SpvOpConvertFToU, this->getType(outputType), result, inputId, out);
1339 } else if (inputType.isSigned()) {
1340 this->writeInstruction(SpvOpBitcast, this->getType(outputType), result, inputId, out);
Ethan Nicholasf7b88202017-09-18 14:10:39 -04001341 } else {
John Stilesd9d52712021-01-13 17:15:02 -05001342 SkDEBUGFAILF("unsupported type for unsigned int typecast: %s",
1343 inputType.description().c_str());
1344 return (SpvId)-1;
Ethan Nicholas925f52d2017-07-19 10:42:50 -04001345 }
1346 return result;
1347}
1348
John Stilesfd7252f2021-04-04 22:24:40 -04001349SpvId SPIRVCodeGenerator::writeBooleanConstructor(const AnyConstructor& c, OutputStream& out) {
1350 SkASSERT(c.argumentSpan().size() == 1);
John Stilesa60fb172021-01-14 11:06:20 -05001351 SkASSERT(c.type().isBoolean());
John Stilesfd7252f2021-04-04 22:24:40 -04001352 const Expression& ctorExpr = *c.argumentSpan().front();
John Stilesa60fb172021-01-14 11:06:20 -05001353 SpvId expressionId = this->writeExpression(ctorExpr, out);
1354 return this->castScalarToBoolean(expressionId, ctorExpr.type(), c.type(), out);
1355}
1356
John Stiles48c28842021-01-14 11:05:03 -05001357SpvId SPIRVCodeGenerator::castScalarToBoolean(SpvId inputId, const Type& inputType,
1358 const Type& outputType, OutputStream& out) {
1359 // Casting a bool to bool is a no-op.
1360 if (inputType.isBoolean()) {
1361 return inputId;
1362 }
1363
1364 // Given the input type, generate the appropriate instruction to cast to bool.
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001365 SpvId result = this->nextId(nullptr);
John Stiles48c28842021-01-14 11:05:03 -05001366 if (inputType.isSigned()) {
1367 // Synthesize a boolean result by comparing the input against a signed zero literal.
1368 IntLiteral zero(/*offset=*/-1, /*value=*/0, fContext.fTypes.fInt.get());
1369 SpvId zeroID = this->writeIntLiteral(zero);
1370 this->writeInstruction(SpvOpINotEqual, this->getType(outputType), result,
1371 inputId, zeroID, out);
1372 } else if (inputType.isUnsigned()) {
1373 // Synthesize a boolean result by comparing the input against an unsigned zero literal.
1374 IntLiteral zero(/*offset=*/-1, /*value=*/0, fContext.fTypes.fUInt.get());
1375 SpvId zeroID = this->writeIntLiteral(zero);
1376 this->writeInstruction(SpvOpINotEqual, this->getType(outputType), result,
1377 inputId, zeroID, out);
1378 } else if (inputType.isFloat()) {
1379 // Synthesize a boolean result by comparing the input against a floating-point zero literal.
1380 FloatLiteral zero(/*offset=*/-1, /*value=*/0, fContext.fTypes.fFloat.get());
1381 SpvId zeroID = this->writeFloatLiteral(zero);
1382 this->writeInstruction(SpvOpFUnordNotEqual, this->getType(outputType), result,
1383 inputId, zeroID, out);
1384 } else {
1385 SkDEBUGFAILF("unsupported type for boolean typecast: %s", inputType.description().c_str());
1386 return (SpvId)-1;
1387 }
1388 return result;
1389}
1390
Ethan Nicholas84645e32017-02-09 13:57:14 -05001391void SPIRVCodeGenerator::writeUniformScaleMatrix(SpvId id, SpvId diagonal, const Type& type,
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001392 OutputStream& out) {
John Stiles9ce80f72021-03-11 22:35:19 -05001393 FloatLiteral zero(/*offset=*/-1, /*value=*/0, fContext.fTypes.fFloat.get());
Ethan Nicholas84645e32017-02-09 13:57:14 -05001394 SpvId zeroId = this->writeFloatLiteral(zero);
1395 std::vector<SpvId> columnIds;
John Stiles392d8292021-04-09 12:14:03 -04001396 columnIds.reserve(type.columns());
Ethan Nicholas84645e32017-02-09 13:57:14 -05001397 for (int column = 0; column < type.columns(); column++) {
1398 this->writeOpCode(SpvOpCompositeConstruct, 3 + type.rows(),
1399 out);
John Stiles392d8292021-04-09 12:14:03 -04001400 this->writeWord(this->getType(type.componentType().toCompound(
1401 fContext, /*columns=*/type.rows(), /*rows=*/1)),
Ethan Nicholas84645e32017-02-09 13:57:14 -05001402 out);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001403 SpvId columnId = this->nextId(&type);
Ethan Nicholas84645e32017-02-09 13:57:14 -05001404 this->writeWord(columnId, out);
1405 columnIds.push_back(columnId);
John Stiles392d8292021-04-09 12:14:03 -04001406 for (int row = 0; row < type.rows(); row++) {
Ethan Nicholas84645e32017-02-09 13:57:14 -05001407 this->writeWord(row == column ? diagonal : zeroId, out);
1408 }
1409 }
1410 this->writeOpCode(SpvOpCompositeConstruct, 3 + type.columns(),
1411 out);
1412 this->writeWord(this->getType(type), out);
1413 this->writeWord(id, out);
John Stilesf621e232020-08-25 13:33:02 -04001414 for (SpvId columnId : columnIds) {
1415 this->writeWord(columnId, out);
Ethan Nicholas84645e32017-02-09 13:57:14 -05001416 }
1417}
1418
John Stiles268a73f2021-04-07 12:30:22 -04001419SpvId SPIRVCodeGenerator::writeMatrixCopy(SpvId src, const Type& srcType, const Type& dstType,
1420 OutputStream& out) {
John Stiles9aeed132020-11-24 17:36:06 -05001421 SkASSERT(srcType.isMatrix());
1422 SkASSERT(dstType.isMatrix());
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001423 SkASSERT(srcType.componentType() == dstType.componentType());
John Stiles268a73f2021-04-07 12:30:22 -04001424 SpvId id = this->nextId(&dstType);
Ethan Nicholasdc0e1c32017-07-21 13:23:34 -04001425 SpvId srcColumnType = this->getType(srcType.componentType().toCompound(fContext,
1426 srcType.rows(),
1427 1));
1428 SpvId dstColumnType = this->getType(dstType.componentType().toCompound(fContext,
1429 dstType.rows(),
1430 1));
John Stiles92671832021-04-06 09:24:55 -04001431 SkASSERT(dstType.componentType().isFloat());
1432 FloatLiteral zero(/*offset=*/-1, /*value=*/0.0, &dstType.componentType());
1433 const SpvId zeroId = this->writeFloatLiteral(zero);
1434 FloatLiteral one(/*offset=*/-1, /*value=*/1.0, &dstType.componentType());
1435 const SpvId oneId = this->writeFloatLiteral(one);
1436
Ethan Nicholasdc0e1c32017-07-21 13:23:34 -04001437 SpvId columns[4];
1438 for (int i = 0; i < dstType.columns(); i++) {
1439 if (i < srcType.columns()) {
1440 // we're still inside the src matrix, copy the column
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001441 SpvId srcColumn = this->nextId(&dstType);
Ethan Nicholasdc0e1c32017-07-21 13:23:34 -04001442 this->writeInstruction(SpvOpCompositeExtract, srcColumnType, srcColumn, src, i, out);
1443 SpvId dstColumn;
1444 if (srcType.rows() == dstType.rows()) {
1445 // columns are equal size, don't need to do anything
1446 dstColumn = srcColumn;
1447 }
1448 else if (dstType.rows() > srcType.rows()) {
1449 // dst column is bigger, need to zero-pad it
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001450 dstColumn = this->nextId(&dstType);
Ethan Nicholasdc0e1c32017-07-21 13:23:34 -04001451 int delta = dstType.rows() - srcType.rows();
1452 this->writeOpCode(SpvOpCompositeConstruct, 4 + delta, out);
1453 this->writeWord(dstColumnType, out);
1454 this->writeWord(dstColumn, out);
1455 this->writeWord(srcColumn, out);
John Stiles92671832021-04-06 09:24:55 -04001456 for (int j = srcType.rows(); j < dstType.rows(); ++j) {
1457 this->writeWord((i == j) ? oneId : zeroId, out);
Ethan Nicholasdc0e1c32017-07-21 13:23:34 -04001458 }
1459 }
1460 else {
1461 // dst column is smaller, need to swizzle the src column
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001462 dstColumn = this->nextId(&dstType);
John Stiles92671832021-04-06 09:24:55 -04001463 this->writeOpCode(SpvOpVectorShuffle, 5 + dstType.rows(), out);
Ethan Nicholasdc0e1c32017-07-21 13:23:34 -04001464 this->writeWord(dstColumnType, out);
1465 this->writeWord(dstColumn, out);
1466 this->writeWord(srcColumn, out);
1467 this->writeWord(srcColumn, out);
John Stiles92671832021-04-06 09:24:55 -04001468 for (int j = 0; j < dstType.rows(); j++) {
John Stilesf621e232020-08-25 13:33:02 -04001469 this->writeWord(j, out);
Ethan Nicholasdc0e1c32017-07-21 13:23:34 -04001470 }
1471 }
1472 columns[i] = dstColumn;
1473 } else {
John Stiles92671832021-04-06 09:24:55 -04001474 // we're past the end of the src matrix, need to synthesize an identity-matrix column
1475 SpvId identityColumn = this->nextId(&dstType);
1476 this->writeOpCode(SpvOpCompositeConstruct, 3 + dstType.rows(), out);
1477 this->writeWord(dstColumnType, out);
1478 this->writeWord(identityColumn, out);
1479 for (int j = 0; j < dstType.rows(); ++j) {
1480 this->writeWord((i == j) ? oneId : zeroId, out);
Ethan Nicholasdc0e1c32017-07-21 13:23:34 -04001481 }
John Stiles92671832021-04-06 09:24:55 -04001482 columns[i] = identityColumn;
Ethan Nicholasdc0e1c32017-07-21 13:23:34 -04001483 }
1484 }
1485 this->writeOpCode(SpvOpCompositeConstruct, 3 + dstType.columns(), out);
1486 this->writeWord(this->getType(dstType), out);
1487 this->writeWord(id, out);
1488 for (int i = 0; i < dstType.columns(); i++) {
1489 this->writeWord(columns[i], out);
1490 }
John Stiles268a73f2021-04-07 12:30:22 -04001491 return id;
Ethan Nicholas84645e32017-02-09 13:57:14 -05001492}
1493
Ethan Nicholascc5d3e02019-04-19 09:50:56 -04001494void SPIRVCodeGenerator::addColumnEntry(SpvId columnType, Precision precision,
1495 std::vector<SpvId>* currentColumn,
Ethan Nicholas5c46b722019-03-22 14:32:37 -04001496 std::vector<SpvId>* columnIds,
1497 int* currentCount, int rows, SpvId entry,
1498 OutputStream& out) {
1499 SkASSERT(*currentCount < rows);
1500 ++(*currentCount);
1501 currentColumn->push_back(entry);
1502 if (*currentCount == rows) {
1503 *currentCount = 0;
1504 this->writeOpCode(SpvOpCompositeConstruct, 3 + currentColumn->size(), out);
1505 this->writeWord(columnType, out);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001506 SpvId columnId = this->nextId(precision);
Ethan Nicholas5c46b722019-03-22 14:32:37 -04001507 this->writeWord(columnId, out);
1508 columnIds->push_back(columnId);
1509 for (SpvId id : *currentColumn) {
1510 this->writeWord(id, out);
1511 }
1512 currentColumn->clear();
1513 }
1514}
1515
John Stiles8cad6372021-04-07 12:31:13 -04001516SpvId SPIRVCodeGenerator::writeMatrixConstructor(const ConstructorCompound& c, OutputStream& out) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001517 const Type& type = c.type();
John Stiles9aeed132020-11-24 17:36:06 -05001518 SkASSERT(type.isMatrix());
John Stiles2bec8ab2021-04-06 18:40:04 -04001519 SkASSERT(!c.arguments().empty());
Ethan Nicholasf70f0442020-09-29 12:41:35 -04001520 const Type& arg0Type = c.arguments()[0]->type();
ethannicholasb3058bd2016-07-01 08:22:01 -07001521 // go ahead and write the arguments so we don't try to write new instructions in the middle of
1522 // an instruction
1523 std::vector<SpvId> arguments;
John Stiles2bec8ab2021-04-06 18:40:04 -04001524 arguments.reserve(c.arguments().size());
1525 for (const std::unique_ptr<Expression>& arg : c.arguments()) {
1526 arguments.push_back(this->writeExpression(*arg, out));
ethannicholasb3058bd2016-07-01 08:22:01 -07001527 }
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001528 SpvId result = this->nextId(&type);
Ethan Nicholas30d30222020-09-11 12:27:26 -04001529 int rows = type.rows();
1530 int columns = type.columns();
John Stiles268a73f2021-04-07 12:30:22 -04001531 if (arguments.size() == 1 && arg0Type.isVector()) {
1532 // Special-case handling of float4 -> mat2x2.
Ethan Nicholas30d30222020-09-11 12:27:26 -04001533 SkASSERT(type.rows() == 2 && type.columns() == 2);
1534 SkASSERT(arg0Type.columns() == 4);
1535 SpvId componentType = this->getType(type.componentType());
Ethan Nicholasdc0e1c32017-07-21 13:23:34 -04001536 SpvId v[4];
1537 for (int i = 0; i < 4; ++i) {
Ethan Nicholas7f015882021-03-23 14:16:52 -04001538 v[i] = this->nextId(&type);
Ethan Nicholas30d30222020-09-11 12:27:26 -04001539 this->writeInstruction(SpvOpCompositeExtract, componentType, v[i], arguments[0], i,
1540 out);
Ethan Nicholasdc0e1c32017-07-21 13:23:34 -04001541 }
Ethan Nicholas30d30222020-09-11 12:27:26 -04001542 SpvId columnType = this->getType(type.componentType().toCompound(fContext, 2, 1));
Ethan Nicholas7f015882021-03-23 14:16:52 -04001543 SpvId column1 = this->nextId(&type);
Ethan Nicholasdc0e1c32017-07-21 13:23:34 -04001544 this->writeInstruction(SpvOpCompositeConstruct, columnType, column1, v[0], v[1], out);
Ethan Nicholas7f015882021-03-23 14:16:52 -04001545 SpvId column2 = this->nextId(&type);
Ethan Nicholasdc0e1c32017-07-21 13:23:34 -04001546 this->writeInstruction(SpvOpCompositeConstruct, columnType, column2, v[2], v[3], out);
Ethan Nicholas30d30222020-09-11 12:27:26 -04001547 this->writeInstruction(SpvOpCompositeConstruct, this->getType(type), result, column1,
Ethan Nicholasdc0e1c32017-07-21 13:23:34 -04001548 column2, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07001549 } else {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001550 SpvId columnType = this->getType(type.componentType().toCompound(fContext, rows, 1));
ethannicholasb3058bd2016-07-01 08:22:01 -07001551 std::vector<SpvId> columnIds;
Ethan Nicholasdc0e1c32017-07-21 13:23:34 -04001552 // ids of vectors and scalars we have written to the current column so far
1553 std::vector<SpvId> currentColumn;
1554 // the total number of scalars represented by currentColumn's entries
ethannicholasb3058bd2016-07-01 08:22:01 -07001555 int currentCount = 0;
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001556 Precision precision = type.highPrecision() ? Precision::kDefault : Precision::kRelaxed;
ethannicholasb3058bd2016-07-01 08:22:01 -07001557 for (size_t i = 0; i < arguments.size(); i++) {
Ethan Nicholasf70f0442020-09-29 12:41:35 -04001558 const Type& argType = c.arguments()[i]->type();
John Stiles9aeed132020-11-24 17:36:06 -05001559 if (currentCount == 0 && argType.isVector() &&
Ethan Nicholas30d30222020-09-11 12:27:26 -04001560 argType.columns() == type.rows()) {
Ethan Nicholasdc0e1c32017-07-21 13:23:34 -04001561 // this is a complete column by itself
ethannicholasb3058bd2016-07-01 08:22:01 -07001562 columnIds.push_back(arguments[i]);
ethannicholasb3058bd2016-07-01 08:22:01 -07001563 } else {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001564 if (argType.columns() == 1) {
Ethan Nicholascc5d3e02019-04-19 09:50:56 -04001565 this->addColumnEntry(columnType, precision, &currentColumn, &columnIds,
1566 &currentCount, rows, arguments[i], out);
Ethan Nicholasbe850ad2018-04-27 10:36:31 -04001567 } else {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001568 SpvId componentType = this->getType(argType.componentType());
1569 for (int j = 0; j < argType.columns(); ++j) {
Ethan Nicholas7f015882021-03-23 14:16:52 -04001570 SpvId swizzle = this->nextId(&argType);
Ethan Nicholasbe850ad2018-04-27 10:36:31 -04001571 this->writeInstruction(SpvOpCompositeExtract, componentType, swizzle,
1572 arguments[i], j, out);
Ethan Nicholascc5d3e02019-04-19 09:50:56 -04001573 this->addColumnEntry(columnType, precision, &currentColumn, &columnIds,
1574 &currentCount, rows, swizzle, out);
Ethan Nicholasbe850ad2018-04-27 10:36:31 -04001575 }
1576 }
ethannicholasb3058bd2016-07-01 08:22:01 -07001577 }
1578 }
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001579 SkASSERT(columnIds.size() == (size_t) columns);
ethannicholasb3058bd2016-07-01 08:22:01 -07001580 this->writeOpCode(SpvOpCompositeConstruct, 3 + columns, out);
Ethan Nicholas30d30222020-09-11 12:27:26 -04001581 this->writeWord(this->getType(type), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07001582 this->writeWord(result, out);
1583 for (SpvId id : columnIds) {
1584 this->writeWord(id, out);
1585 }
1586 }
1587 return result;
1588}
1589
John Stiles8cad6372021-04-07 12:31:13 -04001590SpvId SPIRVCodeGenerator::writeConstructorCompound(const ConstructorCompound& c,
1591 OutputStream& out) {
John Stiles2bec8ab2021-04-06 18:40:04 -04001592 return c.type().isMatrix() ? this->writeMatrixConstructor(c, out)
1593 : this->writeVectorConstructor(c, out);
1594}
1595
John Stiles8cad6372021-04-07 12:31:13 -04001596SpvId SPIRVCodeGenerator::writeVectorConstructor(const ConstructorCompound& c, OutputStream& out) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001597 const Type& type = c.type();
John Stilesd986f472021-04-06 15:54:43 -04001598 const Type& componentType = type.componentType();
John Stiles9aeed132020-11-24 17:36:06 -05001599 SkASSERT(type.isVector());
John Stilesd986f472021-04-06 15:54:43 -04001600
1601 if (c.isCompileTimeConstant()) {
ethannicholasb3058bd2016-07-01 08:22:01 -07001602 return this->writeConstantVector(c);
1603 }
John Stilesd986f472021-04-06 15:54:43 -04001604
ethannicholasb3058bd2016-07-01 08:22:01 -07001605 std::vector<SpvId> arguments;
Ethan Nicholasf70f0442020-09-29 12:41:35 -04001606 for (size_t i = 0; i < c.arguments().size(); i++) {
1607 const Type& argType = c.arguments()[i]->type();
John Stilesd986f472021-04-06 15:54:43 -04001608 SkASSERT(componentType == argType.componentType());
John Stiles48c28842021-01-14 11:05:03 -05001609
John Stilesd986f472021-04-06 15:54:43 -04001610 if (argType.isVector()) {
1611 // There's a bug in the Intel Vulkan driver where OpCompositeConstruct doesn't handle
1612 // vector arguments at all, so we always extract each vector component and pass them
1613 // into OpCompositeConstruct individually.
1614 SpvId vec = this->writeExpression(*c.arguments()[i], out);
Ethan Nicholas30d30222020-09-11 12:27:26 -04001615 for (int j = 0; j < argType.columns(); j++) {
John Stilesd986f472021-04-06 15:54:43 -04001616 SpvId componentId = this->nextId(&componentType);
1617 this->writeInstruction(SpvOpCompositeExtract, this->getType(componentType),
1618 componentId, vec, j, out);
1619 arguments.push_back(componentId);
Ethan Nicholas26a8d902018-01-29 09:25:51 -05001620 }
Ethan Nicholas11e5bff2018-01-29 11:08:38 -05001621 } else {
Ethan Nicholasf70f0442020-09-29 12:41:35 -04001622 arguments.push_back(this->writeExpression(*c.arguments()[i], out));
Ethan Nicholas26a8d902018-01-29 09:25:51 -05001623 }
ethannicholasb3058bd2016-07-01 08:22:01 -07001624 }
John Stilesb14a8192021-04-05 11:40:46 -04001625
1626 return this->writeComposite(arguments, type, out);
1627}
1628
1629SpvId SPIRVCodeGenerator::writeComposite(const std::vector<SpvId>& arguments,
1630 const Type& type,
1631 OutputStream& out) {
John Stilesd47330f2021-04-08 23:25:52 -04001632 SkASSERT(arguments.size() == (type.isStruct() ? type.fields().size() : (size_t)type.columns()));
John Stiles2938eea2021-04-01 18:58:25 -04001633
Ethan Nicholas7f015882021-03-23 14:16:52 -04001634 SpvId result = this->nextId(&type);
John Stiles2938eea2021-04-01 18:58:25 -04001635 this->writeOpCode(SpvOpCompositeConstruct, 3 + (int32_t) arguments.size(), out);
1636 this->writeWord(this->getType(type), out);
1637 this->writeWord(result, out);
1638 for (SpvId id : arguments) {
1639 this->writeWord(id, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07001640 }
1641 return result;
1642}
1643
John Stiles2938eea2021-04-01 18:58:25 -04001644SpvId SPIRVCodeGenerator::writeConstructorSplat(const ConstructorSplat& c, OutputStream& out) {
1645 // Use writeConstantVector to deduplicate constant splats.
1646 if (c.isCompileTimeConstant()) {
1647 return this->writeConstantVector(c);
1648 }
1649
1650 // Write the splat argument.
1651 SpvId argument = this->writeExpression(*c.argument(), out);
1652
1653 // Generate a OpCompositeConstruct which repeats the argument N times.
John Stilesb14a8192021-04-05 11:40:46 -04001654 std::vector<SpvId> arguments(/*count*/ c.type().columns(), /*value*/ argument);
1655 return this->writeComposite(arguments, c.type(), out);
John Stiles2938eea2021-04-01 18:58:25 -04001656}
1657
1658
John Stilesd47330f2021-04-08 23:25:52 -04001659SpvId SPIRVCodeGenerator::writeCompositeConstructor(const AnyConstructor& c, OutputStream& out) {
1660 SkASSERT(c.type().isArray() || c.type().isStruct());
1661 auto ctorArgs = c.argumentSpan();
1662
Ethan Nicholasbd553222017-07-18 15:54:59 -04001663 std::vector<SpvId> arguments;
John Stilesd47330f2021-04-08 23:25:52 -04001664 arguments.reserve(ctorArgs.size());
1665 for (const std::unique_ptr<Expression>& arg : ctorArgs) {
1666 arguments.push_back(this->writeExpression(*arg, out));
Ethan Nicholasbd553222017-07-18 15:54:59 -04001667 }
John Stilesd47330f2021-04-08 23:25:52 -04001668
1669 return this->writeComposite(arguments, c.type(), out);
Ethan Nicholasbd553222017-07-18 15:54:59 -04001670}
1671
John Stilesfd7252f2021-04-04 22:24:40 -04001672SpvId SPIRVCodeGenerator::writeConstructorScalarCast(const ConstructorScalarCast& c,
1673 OutputStream& out) {
1674 const Type& type = c.type();
1675 if (this->getActualType(type) == this->getActualType(c.argument()->type())) {
1676 return this->writeExpression(*c.argument(), out);
1677 }
John Stilesb14a8192021-04-05 11:40:46 -04001678
1679 const Expression& ctorExpr = *c.argument();
1680 SpvId expressionId = this->writeExpression(ctorExpr, out);
1681 return this->castScalarToType(expressionId, ctorExpr.type(), type, out);
1682}
1683
John Stiles8cad6372021-04-07 12:31:13 -04001684SpvId SPIRVCodeGenerator::writeConstructorCompoundCast(const ConstructorCompoundCast& c,
1685 OutputStream& out) {
John Stilesb14a8192021-04-05 11:40:46 -04001686 const Type& ctorType = c.type();
1687 const Type& argType = c.argument()->type();
John Stiles268a73f2021-04-07 12:30:22 -04001688 SkASSERT(ctorType.isVector() || ctorType.isMatrix());
John Stilesb14a8192021-04-05 11:40:46 -04001689
John Stiles268a73f2021-04-07 12:30:22 -04001690 // Write the composite that we are casting. If the actual type matches, we are done.
1691 SpvId compositeId = this->writeExpression(*c.argument(), out);
John Stilesb14a8192021-04-05 11:40:46 -04001692 if (this->getActualType(ctorType) == this->getActualType(argType)) {
John Stiles268a73f2021-04-07 12:30:22 -04001693 return compositeId;
1694 }
1695
1696 // writeMatrixCopy can cast matrices to a different type.
1697 if (ctorType.isMatrix()) {
1698 return this->writeMatrixCopy(compositeId, argType, ctorType, out);
John Stilesfd7252f2021-04-04 22:24:40 -04001699 }
John Stilesb14a8192021-04-05 11:40:46 -04001700
1701 // SPIR-V doesn't support vector(vector-of-different-type) directly, so we need to extract the
John Stilesd986f472021-04-06 15:54:43 -04001702 // components and convert each one manually.
John Stilesb14a8192021-04-05 11:40:46 -04001703 const Type& srcType = argType.componentType();
1704 const Type& dstType = ctorType.componentType();
1705
1706 std::vector<SpvId> arguments;
John Stiles268a73f2021-04-07 12:30:22 -04001707 arguments.reserve(argType.columns());
John Stilesb14a8192021-04-05 11:40:46 -04001708 for (int index = 0; index < argType.columns(); ++index) {
1709 SpvId componentId = this->nextId(&srcType);
1710 this->writeInstruction(SpvOpCompositeExtract, this->getType(srcType), componentId,
John Stiles268a73f2021-04-07 12:30:22 -04001711 compositeId, index, out);
John Stilesb14a8192021-04-05 11:40:46 -04001712 arguments.push_back(this->castScalarToType(componentId, srcType, dstType, out));
John Stilesfd7252f2021-04-04 22:24:40 -04001713 }
John Stilesb14a8192021-04-05 11:40:46 -04001714
1715 return this->writeComposite(arguments, ctorType, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07001716}
1717
John Stilese1182782021-03-30 22:09:37 -04001718SpvId SPIRVCodeGenerator::writeConstructorDiagonalMatrix(const ConstructorDiagonalMatrix& c,
1719 OutputStream& out) {
1720 const Type& type = c.type();
1721 SkASSERT(type.isMatrix());
1722 SkASSERT(c.argument()->type().isScalar());
1723
1724 // Write out the scalar argument.
1725 SpvId argument = this->writeExpression(*c.argument(), out);
1726
1727 // Build the diagonal matrix.
1728 SpvId result = this->nextId(&type);
1729 this->writeUniformScaleMatrix(result, argument, type, out);
1730 return result;
1731}
1732
John Stiles5abb9e12021-04-06 13:47:19 -04001733SpvId SPIRVCodeGenerator::writeConstructorMatrixResize(const ConstructorMatrixResize& c,
1734 OutputStream& out) {
1735 // Write the input matrix.
1736 SpvId argument = this->writeExpression(*c.argument(), out);
1737
1738 // Use matrix-copy to resize the input matrix to its new size.
John Stiles268a73f2021-04-07 12:30:22 -04001739 return this->writeMatrixCopy(argument, c.argument()->type(), c.type(), out);
John Stiles5abb9e12021-04-06 13:47:19 -04001740}
1741
John Stiles9485b552021-01-27 11:47:00 -05001742static SpvStorageClass_ get_storage_class(const Variable& var,
1743 SpvStorageClass_ fallbackStorageClass) {
1744 const Modifiers& modifiers = var.modifiers();
ethannicholasb3058bd2016-07-01 08:22:01 -07001745 if (modifiers.fFlags & Modifiers::kIn_Flag) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001746 SkASSERT(!(modifiers.fLayout.fFlags & Layout::kPushConstant_Flag));
ethannicholasb3058bd2016-07-01 08:22:01 -07001747 return SpvStorageClassInput;
John Stiles9485b552021-01-27 11:47:00 -05001748 }
1749 if (modifiers.fFlags & Modifiers::kOut_Flag) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001750 SkASSERT(!(modifiers.fLayout.fFlags & Layout::kPushConstant_Flag));
ethannicholasb3058bd2016-07-01 08:22:01 -07001751 return SpvStorageClassOutput;
John Stiles9485b552021-01-27 11:47:00 -05001752 }
1753 if (modifiers.fFlags & Modifiers::kUniform_Flag) {
Ethan Nicholas39204fd2017-11-27 13:12:30 -05001754 if (modifiers.fLayout.fFlags & Layout::kPushConstant_Flag) {
ethannicholas8ac838d2016-11-22 08:39:36 -08001755 return SpvStorageClassPushConstant;
1756 }
John Stiles9485b552021-01-27 11:47:00 -05001757 if (var.type().typeKind() == Type::TypeKind::kSampler ||
1758 var.type().typeKind() == Type::TypeKind::kSeparateSampler ||
1759 var.type().typeKind() == Type::TypeKind::kTexture) {
1760 return SpvStorageClassUniformConstant;
1761 }
ethannicholasb3058bd2016-07-01 08:22:01 -07001762 return SpvStorageClassUniform;
ethannicholasb3058bd2016-07-01 08:22:01 -07001763 }
John Stiles9485b552021-01-27 11:47:00 -05001764 return fallbackStorageClass;
ethannicholasb3058bd2016-07-01 08:22:01 -07001765}
1766
John Stiles9485b552021-01-27 11:47:00 -05001767static SpvStorageClass_ get_storage_class(const Expression& expr) {
Ethan Nicholase6592142020-09-08 10:22:09 -04001768 switch (expr.kind()) {
1769 case Expression::Kind::kVariableReference: {
Ethan Nicholas78686922020-10-08 06:46:27 -04001770 const Variable& var = *expr.as<VariableReference>().variable();
Ethan Nicholas453f67f2020-10-09 10:43:45 -04001771 if (var.storage() != Variable::Storage::kGlobal) {
Ethan Nicholasc6f5e102017-03-31 14:53:17 -04001772 return SpvStorageClassFunction;
1773 }
John Stiles9485b552021-01-27 11:47:00 -05001774 return get_storage_class(var, SpvStorageClassPrivate);
Ethan Nicholasc6f5e102017-03-31 14:53:17 -04001775 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001776 case Expression::Kind::kFieldAccess:
Ethan Nicholas7a95b202020-10-09 11:55:40 -04001777 return get_storage_class(*expr.as<FieldAccess>().base());
Ethan Nicholase6592142020-09-08 10:22:09 -04001778 case Expression::Kind::kIndex:
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04001779 return get_storage_class(*expr.as<IndexExpression>().base());
ethannicholasb3058bd2016-07-01 08:22:01 -07001780 default:
1781 return SpvStorageClassFunction;
1782 }
1783}
1784
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001785std::vector<SpvId> SPIRVCodeGenerator::getAccessChain(const Expression& expr, OutputStream& out) {
ethannicholasb3058bd2016-07-01 08:22:01 -07001786 std::vector<SpvId> chain;
Ethan Nicholase6592142020-09-08 10:22:09 -04001787 switch (expr.kind()) {
1788 case Expression::Kind::kIndex: {
John Stiles0693fb82021-01-22 18:27:52 -05001789 const IndexExpression& indexExpr = expr.as<IndexExpression>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04001790 chain = this->getAccessChain(*indexExpr.base(), out);
1791 chain.push_back(this->writeExpression(*indexExpr.index(), out));
ethannicholasb3058bd2016-07-01 08:22:01 -07001792 break;
1793 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001794 case Expression::Kind::kFieldAccess: {
John Stiles0693fb82021-01-22 18:27:52 -05001795 const FieldAccess& fieldExpr = expr.as<FieldAccess>();
Ethan Nicholas7a95b202020-10-09 11:55:40 -04001796 chain = this->getAccessChain(*fieldExpr.base(), out);
John Stiles9ce80f72021-03-11 22:35:19 -05001797 IntLiteral index(/*offset=*/-1, fieldExpr.fieldIndex(), fContext.fTypes.fInt.get());
ethannicholasb3058bd2016-07-01 08:22:01 -07001798 chain.push_back(this->writeIntLiteral(index));
1799 break;
1800 }
Ethan Nicholasa9a06902019-01-07 14:42:40 -05001801 default: {
1802 SpvId id = this->getLValue(expr, out)->getPointer();
John Stiles3f14d282021-02-05 09:31:04 -05001803 SkASSERT(id != (SpvId) -1);
Ethan Nicholasa9a06902019-01-07 14:42:40 -05001804 chain.push_back(id);
1805 }
ethannicholasb3058bd2016-07-01 08:22:01 -07001806 }
1807 return chain;
1808}
1809
1810class PointerLValue : public SPIRVCodeGenerator::LValue {
1811public:
Ethan Nicholase0707b72021-03-17 11:16:41 -04001812 PointerLValue(SPIRVCodeGenerator& gen, SpvId pointer, bool isMemoryObject, SpvId type,
Ethan Nicholas10e93b62019-03-20 10:46:14 -04001813 SPIRVCodeGenerator::Precision precision)
ethannicholasb3058bd2016-07-01 08:22:01 -07001814 : fGen(gen)
1815 , fPointer(pointer)
Ethan Nicholase0707b72021-03-17 11:16:41 -04001816 , fIsMemoryObject(isMemoryObject)
Ethan Nicholas10e93b62019-03-20 10:46:14 -04001817 , fType(type)
1818 , fPrecision(precision) {}
ethannicholasb3058bd2016-07-01 08:22:01 -07001819
John Stiles1cf2c8d2020-08-13 22:58:04 -04001820 SpvId getPointer() override {
ethannicholasb3058bd2016-07-01 08:22:01 -07001821 return fPointer;
1822 }
1823
Ethan Nicholase0707b72021-03-17 11:16:41 -04001824 bool isMemoryObjectPointer() const override {
1825 return fIsMemoryObject;
1826 }
1827
John Stiles1cf2c8d2020-08-13 22:58:04 -04001828 SpvId load(OutputStream& out) override {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001829 SpvId result = fGen.nextId(fPrecision);
ethannicholasb3058bd2016-07-01 08:22:01 -07001830 fGen.writeInstruction(SpvOpLoad, fType, result, fPointer, out);
1831 return result;
1832 }
1833
John Stiles1cf2c8d2020-08-13 22:58:04 -04001834 void store(SpvId value, OutputStream& out) override {
ethannicholasb3058bd2016-07-01 08:22:01 -07001835 fGen.writeInstruction(SpvOpStore, fPointer, value, out);
1836 }
1837
1838private:
1839 SPIRVCodeGenerator& fGen;
1840 const SpvId fPointer;
Ethan Nicholase0707b72021-03-17 11:16:41 -04001841 const bool fIsMemoryObject;
ethannicholasb3058bd2016-07-01 08:22:01 -07001842 const SpvId fType;
Ethan Nicholas10e93b62019-03-20 10:46:14 -04001843 const SPIRVCodeGenerator::Precision fPrecision;
ethannicholasb3058bd2016-07-01 08:22:01 -07001844};
1845
1846class SwizzleLValue : public SPIRVCodeGenerator::LValue {
1847public:
John Stiles750109b2020-10-30 13:45:46 -04001848 SwizzleLValue(SPIRVCodeGenerator& gen, SpvId vecPointer, const ComponentArray& components,
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001849 const Type& baseType, const Type& swizzleType)
ethannicholasb3058bd2016-07-01 08:22:01 -07001850 : fGen(gen)
1851 , fVecPointer(vecPointer)
1852 , fComponents(components)
John Stiles3f14d282021-02-05 09:31:04 -05001853 , fBaseType(&baseType)
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001854 , fSwizzleType(&swizzleType) {}
ethannicholasb3058bd2016-07-01 08:22:01 -07001855
John Stiles3f14d282021-02-05 09:31:04 -05001856 bool applySwizzle(const ComponentArray& components, const Type& newType) override {
1857 ComponentArray updatedSwizzle;
1858 for (int8_t component : components) {
1859 if (component < 0 || component >= fComponents.count()) {
1860 SkDEBUGFAILF("swizzle accessed nonexistent component %d", (int)component);
1861 return false;
1862 }
1863 updatedSwizzle.push_back(fComponents[component]);
1864 }
1865 fComponents = updatedSwizzle;
1866 fSwizzleType = &newType;
1867 return true;
ethannicholasb3058bd2016-07-01 08:22:01 -07001868 }
1869
John Stiles1cf2c8d2020-08-13 22:58:04 -04001870 SpvId load(OutputStream& out) override {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001871 SpvId base = fGen.nextId(fBaseType);
John Stiles3f14d282021-02-05 09:31:04 -05001872 fGen.writeInstruction(SpvOpLoad, fGen.getType(*fBaseType), base, fVecPointer, out);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001873 SpvId result = fGen.nextId(fBaseType);
ethannicholasb3058bd2016-07-01 08:22:01 -07001874 fGen.writeOpCode(SpvOpVectorShuffle, 5 + (int32_t) fComponents.size(), out);
John Stiles3f14d282021-02-05 09:31:04 -05001875 fGen.writeWord(fGen.getType(*fSwizzleType), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07001876 fGen.writeWord(result, out);
1877 fGen.writeWord(base, out);
1878 fGen.writeWord(base, out);
1879 for (int component : fComponents) {
1880 fGen.writeWord(component, out);
1881 }
1882 return result;
1883 }
1884
John Stiles1cf2c8d2020-08-13 22:58:04 -04001885 void store(SpvId value, OutputStream& out) override {
ethannicholasb3058bd2016-07-01 08:22:01 -07001886 // use OpVectorShuffle to mix and match the vector components. We effectively create
1887 // a virtual vector out of the concatenation of the left and right vectors, and then
Greg Daniel64773e62016-11-22 09:44:03 -05001888 // select components from this virtual vector to make the result vector. For
ethannicholasb3058bd2016-07-01 08:22:01 -07001889 // instance, given:
Ethan Nicholas5af9ea32017-07-28 15:19:46 -04001890 // float3L = ...;
1891 // float3R = ...;
ethannicholasb3058bd2016-07-01 08:22:01 -07001892 // L.xz = R.xy;
Greg Daniel64773e62016-11-22 09:44:03 -05001893 // 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 -07001894 // our result vector to look like (R.x, L.y, R.y), so we need to select indices
1895 // (3, 1, 4).
Ethan Nicholas7f015882021-03-23 14:16:52 -04001896 SpvId base = fGen.nextId(fBaseType);
John Stiles3f14d282021-02-05 09:31:04 -05001897 fGen.writeInstruction(SpvOpLoad, fGen.getType(*fBaseType), base, fVecPointer, out);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001898 SpvId shuffle = fGen.nextId(fBaseType);
John Stiles3f14d282021-02-05 09:31:04 -05001899 fGen.writeOpCode(SpvOpVectorShuffle, 5 + fBaseType->columns(), out);
1900 fGen.writeWord(fGen.getType(*fBaseType), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07001901 fGen.writeWord(shuffle, out);
1902 fGen.writeWord(base, out);
1903 fGen.writeWord(value, out);
John Stiles3f14d282021-02-05 09:31:04 -05001904 for (int i = 0; i < fBaseType->columns(); i++) {
ethannicholasb3058bd2016-07-01 08:22:01 -07001905 // current offset into the virtual vector, defaults to pulling the unmodified
1906 // value from the left side
1907 int offset = i;
1908 // check to see if we are writing this component
1909 for (size_t j = 0; j < fComponents.size(); j++) {
1910 if (fComponents[j] == i) {
Greg Daniel64773e62016-11-22 09:44:03 -05001911 // we're writing to this component, so adjust the offset to pull from
ethannicholasb3058bd2016-07-01 08:22:01 -07001912 // the correct component of the right side instead of preserving the
1913 // value from the left
John Stiles3f14d282021-02-05 09:31:04 -05001914 offset = (int) (j + fBaseType->columns());
ethannicholasb3058bd2016-07-01 08:22:01 -07001915 break;
1916 }
1917 }
1918 fGen.writeWord(offset, out);
1919 }
1920 fGen.writeInstruction(SpvOpStore, fVecPointer, shuffle, out);
1921 }
1922
1923private:
1924 SPIRVCodeGenerator& fGen;
1925 const SpvId fVecPointer;
John Stiles3f14d282021-02-05 09:31:04 -05001926 ComponentArray fComponents;
1927 const Type* fBaseType;
1928 const Type* fSwizzleType;
ethannicholasb3058bd2016-07-01 08:22:01 -07001929};
1930
John Stilese40d1662021-01-29 10:08:50 -05001931int SPIRVCodeGenerator::findUniformFieldIndex(const Variable& var) const {
1932 auto iter = fTopLevelUniformMap.find(&var);
1933 return (iter != fTopLevelUniformMap.end()) ? iter->second : -1;
1934}
1935
Greg Daniel64773e62016-11-22 09:44:03 -05001936std::unique_ptr<SPIRVCodeGenerator::LValue> SPIRVCodeGenerator::getLValue(const Expression& expr,
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001937 OutputStream& out) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001938 const Type& type = expr.type();
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001939 Precision precision = type.highPrecision() ? Precision::kDefault : Precision::kRelaxed;
Ethan Nicholase6592142020-09-08 10:22:09 -04001940 switch (expr.kind()) {
1941 case Expression::Kind::kVariableReference: {
John Stiles0de76f72021-01-29 09:19:39 -05001942 const Variable& var = *expr.as<VariableReference>().variable();
John Stilese40d1662021-01-29 10:08:50 -05001943 int uniformIdx = this->findUniformFieldIndex(var);
1944 if (uniformIdx >= 0) {
John Stiles9ce80f72021-03-11 22:35:19 -05001945 IntLiteral uniformIdxLiteral{/*offset=*/-1, uniformIdx, fContext.fTypes.fInt.get()};
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001946 SpvId memberId = this->nextId(nullptr);
John Stilese40d1662021-01-29 10:08:50 -05001947 SpvId typeId = this->getPointerType(type, SpvStorageClassUniform);
1948 SpvId uniformIdxId = this->writeIntLiteral(uniformIdxLiteral);
1949 this->writeInstruction(SpvOpAccessChain, typeId, memberId, fUniformBufferId,
1950 uniformIdxId, out);
Ethan Nicholase0707b72021-03-17 11:16:41 -04001951 return std::make_unique<PointerLValue>(*this, memberId,
1952 /*isMemoryObjectPointer=*/true,
1953 this->getType(type), precision);
John Stilese40d1662021-01-29 10:08:50 -05001954 }
1955 SpvId typeId;
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001956 if (var.modifiers().fLayout.fBuiltin == SK_IN_BUILTIN) {
John Stilesad2d4942020-12-11 16:55:58 -05001957 typeId = this->getType(*Type::MakeArrayType("sk_in", var.type().componentType(),
1958 fSkInCount));
Ethan Nicholas5226b772018-05-03 16:20:41 -04001959 } else {
Brian Osman2a4c0fb2021-01-22 13:41:40 -05001960 typeId = this->getType(type, this->memoryLayoutForVariable(var));
Ethan Nicholas5226b772018-05-03 16:20:41 -04001961 }
ethannicholasd598f792016-07-25 10:08:54 -07001962 auto entry = fVariableMap.find(&var);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001963 SkASSERT(entry != fVariableMap.end());
Ethan Nicholase0707b72021-03-17 11:16:41 -04001964 return std::make_unique<PointerLValue>(*this, entry->second,
1965 /*isMemoryObjectPointer=*/true,
1966 typeId, precision);
ethannicholasb3058bd2016-07-01 08:22:01 -07001967 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001968 case Expression::Kind::kIndex: // fall through
1969 case Expression::Kind::kFieldAccess: {
ethannicholasb3058bd2016-07-01 08:22:01 -07001970 std::vector<SpvId> chain = this->getAccessChain(expr, out);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001971 SpvId member = this->nextId(nullptr);
ethannicholasb3058bd2016-07-01 08:22:01 -07001972 this->writeOpCode(SpvOpAccessChain, (SpvId) (3 + chain.size()), out);
Ethan Nicholas30d30222020-09-11 12:27:26 -04001973 this->writeWord(this->getPointerType(type, get_storage_class(expr)), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07001974 this->writeWord(member, out);
1975 for (SpvId idx : chain) {
1976 this->writeWord(idx, out);
1977 }
Ethan Nicholase0707b72021-03-17 11:16:41 -04001978 return std::make_unique<PointerLValue>(*this, member, /*isMemoryObjectPointer=*/false,
1979 this->getType(type), precision);
ethannicholasb3058bd2016-07-01 08:22:01 -07001980 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001981 case Expression::Kind::kSwizzle: {
John Stiles0693fb82021-01-22 18:27:52 -05001982 const Swizzle& swizzle = expr.as<Swizzle>();
John Stiles3f14d282021-02-05 09:31:04 -05001983 std::unique_ptr<LValue> lvalue = this->getLValue(*swizzle.base(), out);
1984 if (lvalue->applySwizzle(swizzle.components(), type)) {
1985 return lvalue;
1986 }
1987 SpvId base = lvalue->getPointer();
1988 if (base == (SpvId) -1) {
John Stiles5570c512020-11-19 17:58:07 -05001989 fErrors.error(swizzle.fOffset, "unable to retrieve lvalue from swizzle");
1990 }
John Stiles3f14d282021-02-05 09:31:04 -05001991 if (swizzle.components().size() == 1) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001992 SpvId member = this->nextId(nullptr);
John Stilesb5db4822021-01-21 13:04:40 -05001993 SpvId typeId = this->getPointerType(type, get_storage_class(*swizzle.base()));
John Stiles9ce80f72021-03-11 22:35:19 -05001994 IntLiteral index(/*offset=*/-1, swizzle.components()[0],
1995 fContext.fTypes.fInt.get());
John Stilesb5db4822021-01-21 13:04:40 -05001996 SpvId indexId = this->writeIntLiteral(index);
1997 this->writeInstruction(SpvOpAccessChain, typeId, member, base, indexId, out);
Ethan Nicholase0707b72021-03-17 11:16:41 -04001998 return std::make_unique<PointerLValue>(*this,
1999 member,
2000 /*isMemoryObjectPointer=*/false,
2001 this->getType(type),
John Stiles5570c512020-11-19 17:58:07 -05002002 precision);
ethannicholasb3058bd2016-07-01 08:22:01 -07002003 } else {
John Stiles5570c512020-11-19 17:58:07 -05002004 return std::make_unique<SwizzleLValue>(*this, base, swizzle.components(),
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002005 swizzle.base()->type(), type);
ethannicholasb3058bd2016-07-01 08:22:01 -07002006 }
2007 }
Ethan Nicholas30d30222020-09-11 12:27:26 -04002008 default: {
ethannicholasb3058bd2016-07-01 08:22:01 -07002009 // expr isn't actually an lvalue, create a dummy variable for it. This case happens due
Greg Daniel64773e62016-11-22 09:44:03 -05002010 // to the need to store values in temporary variables during function calls (see
ethannicholasb3058bd2016-07-01 08:22:01 -07002011 // comments in getFunctionType); erroneous uses of rvalues as lvalues should have been
2012 // caught by IRGenerator
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002013 SpvId result = this->nextId(nullptr);
Ethan Nicholas30d30222020-09-11 12:27:26 -04002014 SpvId pointerType = this->getPointerType(type, SpvStorageClassFunction);
2015 this->writeInstruction(SpvOpVariable, pointerType, result, SpvStorageClassFunction,
ethannicholasd598f792016-07-25 10:08:54 -07002016 fVariableBuffer);
ethannicholasb3058bd2016-07-01 08:22:01 -07002017 this->writeInstruction(SpvOpStore, result, this->writeExpression(expr, out), out);
Ethan Nicholase0707b72021-03-17 11:16:41 -04002018 return std::make_unique<PointerLValue>(*this, result, /*isMemoryObjectPointer=*/true,
2019 this->getType(type), precision);
Ethan Nicholas30d30222020-09-11 12:27:26 -04002020 }
ethannicholasb3058bd2016-07-01 08:22:01 -07002021 }
2022}
2023
Ethan Nicholas0df1b042017-03-31 13:56:23 -04002024SpvId SPIRVCodeGenerator::writeVariableReference(const VariableReference& ref, OutputStream& out) {
John Stiles1e1fe122021-01-29 12:18:46 -05002025 SpvId result = this->getLValue(ref, out)->load(out);
John Stilese40d1662021-01-29 10:08:50 -05002026
John Stiles1e1fe122021-01-29 12:18:46 -05002027 // Handle the "flipY" setting when reading sk_FragCoord.
2028 const Variable* variable = ref.variable();
John Stilese40d1662021-01-29 10:08:50 -05002029 if (variable->modifiers().fLayout.fBuiltin == SK_FRAGCOORD_BUILTIN &&
John Stiles270cec22021-02-17 12:59:36 -05002030 fProgram.fConfig->fSettings.fFlipY) {
Greg Daniela85e4bf2020-06-17 16:32:45 -04002031 // The x component never changes, so just grab it
Ethan Nicholas7f015882021-03-23 14:16:52 -04002032 SpvId xId = this->nextId(Precision::kDefault);
John Stiles54e7c052021-01-11 14:22:36 -05002033 this->writeInstruction(SpvOpCompositeExtract, this->getType(*fContext.fTypes.fFloat), xId,
Ethan Nicholas941e7e22016-12-12 15:33:30 -05002034 result, 0, out);
Greg Daniela85e4bf2020-06-17 16:32:45 -04002035
2036 // Calculate the y component which may need to be flipped
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002037 SpvId rawYId = this->nextId(nullptr);
John Stiles54e7c052021-01-11 14:22:36 -05002038 this->writeInstruction(SpvOpCompositeExtract, this->getType(*fContext.fTypes.fFloat),
2039 rawYId, result, 1, out);
Greg Daniela85e4bf2020-06-17 16:32:45 -04002040 SpvId flippedYId = 0;
John Stiles270cec22021-02-17 12:59:36 -05002041 if (fProgram.fConfig->fSettings.fFlipY) {
Greg Daniela85e4bf2020-06-17 16:32:45 -04002042 // need to remap to a top-left coordinate system
2043 if (fRTHeightStructId == (SpvId)-1) {
2044 // height variable hasn't been written yet
Greg Daniela85e4bf2020-06-17 16:32:45 -04002045 SkASSERT(fRTHeightFieldIndex == (SpvId)-1);
2046 std::vector<Type::Field> fields;
John Stiles270cec22021-02-17 12:59:36 -05002047 if (fProgram.fConfig->fSettings.fRTHeightOffset < 0) {
John Stiles5570c512020-11-19 17:58:07 -05002048 fErrors.error(ref.fOffset, "RTHeightOffset is negative");
2049 }
Greg Daniela85e4bf2020-06-17 16:32:45 -04002050 fields.emplace_back(
John Stilese40d1662021-01-29 10:08:50 -05002051 Modifiers(Layout(/*flags=*/0, /*location=*/-1,
John Stiles270cec22021-02-17 12:59:36 -05002052 fProgram.fConfig->fSettings.fRTHeightOffset,
John Stilese40d1662021-01-29 10:08:50 -05002053 /*binding=*/-1, /*index=*/-1, /*set=*/-1, /*builtin=*/-1,
Brian Osman4717fbb2021-02-23 13:12:09 -05002054 /*inputAttachmentIndex=*/-1,
John Stilese40d1662021-01-29 10:08:50 -05002055 Layout::kUnspecified_Primitive, /*maxVertices=*/1,
Brian Osman8f1dff62021-04-19 13:50:58 -04002056 /*invocations=*/-1, /*when=*/"", Layout::CType::kDefault),
John Stilese40d1662021-01-29 10:08:50 -05002057 /*flags=*/0),
John Stiles54e7c052021-01-11 14:22:36 -05002058 SKSL_RTHEIGHT_NAME, fContext.fTypes.fFloat.get());
Greg Daniela85e4bf2020-06-17 16:32:45 -04002059 StringFragment name("sksl_synthetic_uniforms");
John Stilesad2d4942020-12-11 16:55:58 -05002060 std::unique_ptr<Type> intfStruct = Type::MakeStructType(/*offset=*/-1, name,
2061 fields);
John Stiles270cec22021-02-17 12:59:36 -05002062 int binding = fProgram.fConfig->fSettings.fRTHeightBinding;
John Stiles5570c512020-11-19 17:58:07 -05002063 if (binding == -1) {
2064 fErrors.error(ref.fOffset, "layout(binding=...) is required in SPIR-V");
2065 }
John Stiles270cec22021-02-17 12:59:36 -05002066 int set = fProgram.fConfig->fSettings.fRTHeightSet;
John Stiles5570c512020-11-19 17:58:07 -05002067 if (set == -1) {
2068 fErrors.error(ref.fOffset, "layout(set=...) is required in SPIR-V");
2069 }
John Stiles270cec22021-02-17 12:59:36 -05002070 bool usePushConstants = fProgram.fConfig->fSettings.fUsePushConstants;
John Stilese40d1662021-01-29 10:08:50 -05002071 int flags = usePushConstants ? Layout::Flag::kPushConstant_Flag : 0;
2072 Modifiers modifiers(
2073 Layout(flags, /*location=*/-1, /*offset=*/-1, binding, /*index=*/-1,
2074 set, /*builtin=*/-1, /*inputAttachmentIndex=*/-1,
Brian Osman4717fbb2021-02-23 13:12:09 -05002075 Layout::kUnspecified_Primitive,
Brian Osman8f1dff62021-04-19 13:50:58 -04002076 /*maxVertices=*/-1, /*invocations=*/-1, /*when=*/"",
Brian Osmanba7ef322021-02-23 13:37:22 -05002077 Layout::CType::kDefault),
John Stilese40d1662021-01-29 10:08:50 -05002078 Modifiers::kUniform_Flag);
John Stiles3ae071e2020-08-05 15:29:29 -04002079 const Variable* intfVar = fSynthetics.takeOwnershipOfSymbol(
2080 std::make_unique<Variable>(/*offset=*/-1,
John Stilesf2872e62021-05-04 11:38:43 -04002081 fProgram.fModifiers->add(modifiers),
John Stiles3ae071e2020-08-05 15:29:29 -04002082 name,
John Stilesad2d4942020-12-11 16:55:58 -05002083 intfStruct.get(),
Brian Osman3887a012020-09-30 13:22:27 -04002084 /*builtin=*/false,
Ethan Nicholas453f67f2020-10-09 10:43:45 -04002085 Variable::Storage::kGlobal));
John Stilesd39aec02020-12-03 10:42:26 -05002086 InterfaceBlock intf(/*offset=*/-1, intfVar, name,
2087 /*instanceName=*/"", /*arraySize=*/0,
John Stiles7c3515b2020-10-16 18:38:39 -04002088 std::make_shared<SymbolTable>(&fErrors, /*builtin=*/false));
Stephen White88574972020-06-23 19:09:29 -04002089
2090 fRTHeightStructId = this->writeInterfaceBlock(intf, false);
Greg Daniela85e4bf2020-06-17 16:32:45 -04002091 fRTHeightFieldIndex = 0;
Jim Van Verth46e9b0e2021-01-28 17:26:48 -05002092 fRTHeightStorageClass = usePushConstants ? SpvStorageClassPushConstant
2093 : SpvStorageClassUniform;
Greg Daniela85e4bf2020-06-17 16:32:45 -04002094 }
2095 SkASSERT(fRTHeightFieldIndex != (SpvId)-1);
2096
John Stiles9ce80f72021-03-11 22:35:19 -05002097 IntLiteral fieldIndex(/*offset=*/-1, fRTHeightFieldIndex, fContext.fTypes.fInt.get());
Greg Daniela85e4bf2020-06-17 16:32:45 -04002098 SpvId fieldIndexId = this->writeIntLiteral(fieldIndex);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002099 SpvId heightPtr = this->nextId(nullptr);
Greg Daniela85e4bf2020-06-17 16:32:45 -04002100 this->writeOpCode(SpvOpAccessChain, 5, out);
John Stiles54e7c052021-01-11 14:22:36 -05002101 this->writeWord(this->getPointerType(*fContext.fTypes.fFloat, fRTHeightStorageClass),
Greg Daniela85e4bf2020-06-17 16:32:45 -04002102 out);
2103 this->writeWord(heightPtr, out);
2104 this->writeWord(fRTHeightStructId, out);
2105 this->writeWord(fieldIndexId, out);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002106 SpvId heightRead = this->nextId(nullptr);
John Stiles54e7c052021-01-11 14:22:36 -05002107 this->writeInstruction(SpvOpLoad, this->getType(*fContext.fTypes.fFloat), heightRead,
Greg Daniela85e4bf2020-06-17 16:32:45 -04002108 heightPtr, out);
2109
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002110 flippedYId = this->nextId(nullptr);
John Stiles54e7c052021-01-11 14:22:36 -05002111 this->writeInstruction(SpvOpFSub, this->getType(*fContext.fTypes.fFloat), flippedYId,
Greg Daniela85e4bf2020-06-17 16:32:45 -04002112 heightRead, rawYId, out);
2113 }
2114
2115 // The z component will always be zero so we just get an id to the 0 literal
John Stiles9ce80f72021-03-11 22:35:19 -05002116 FloatLiteral zero(/*offset=*/-1, /*value=*/0.0, fContext.fTypes.fFloat.get());
Ethan Nicholas941e7e22016-12-12 15:33:30 -05002117 SpvId zeroId = writeFloatLiteral(zero);
Greg Daniela85e4bf2020-06-17 16:32:45 -04002118
Brian Osmane38bedd2020-12-21 11:51:54 -05002119 // Calculate the w component
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002120 SpvId rawWId = this->nextId(nullptr);
John Stiles54e7c052021-01-11 14:22:36 -05002121 this->writeInstruction(SpvOpCompositeExtract, this->getType(*fContext.fTypes.fFloat),
2122 rawWId, result, 3, out);
Greg Daniela85e4bf2020-06-17 16:32:45 -04002123
2124 // Fill in the new fragcoord with the components from above
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002125 SpvId adjusted = this->nextId(nullptr);
Ethan Nicholas941e7e22016-12-12 15:33:30 -05002126 this->writeOpCode(SpvOpCompositeConstruct, 7, out);
John Stiles54e7c052021-01-11 14:22:36 -05002127 this->writeWord(this->getType(*fContext.fTypes.fFloat4), out);
Greg Daniela85e4bf2020-06-17 16:32:45 -04002128 this->writeWord(adjusted, out);
Ethan Nicholas941e7e22016-12-12 15:33:30 -05002129 this->writeWord(xId, out);
John Stiles270cec22021-02-17 12:59:36 -05002130 if (fProgram.fConfig->fSettings.fFlipY) {
Greg Daniela85e4bf2020-06-17 16:32:45 -04002131 this->writeWord(flippedYId, out);
2132 } else {
2133 this->writeWord(rawYId, out);
2134 }
Ethan Nicholas941e7e22016-12-12 15:33:30 -05002135 this->writeWord(zeroId, out);
Brian Osmane38bedd2020-12-21 11:51:54 -05002136 this->writeWord(rawWId, out);
Greg Daniela85e4bf2020-06-17 16:32:45 -04002137
2138 return adjusted;
Ethan Nicholas941e7e22016-12-12 15:33:30 -05002139 }
John Stiles1e1fe122021-01-29 12:18:46 -05002140
2141 // Handle the "flipY" setting when reading sk_Clockwise.
John Stilese40d1662021-01-29 10:08:50 -05002142 if (variable->modifiers().fLayout.fBuiltin == SK_CLOCKWISE_BUILTIN &&
John Stiles270cec22021-02-17 12:59:36 -05002143 !fProgram.fConfig->fSettings.fFlipY) {
Chris Daltonb91c4662018-08-01 10:46:22 -06002144 // FrontFacing in Vulkan is defined in terms of a top-down render target. In skia, we use
2145 // the default convention of "counter-clockwise face is front".
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002146 SpvId inverse = this->nextId(nullptr);
John Stiles54e7c052021-01-11 14:22:36 -05002147 this->writeInstruction(SpvOpLogicalNot, this->getType(*fContext.fTypes.fBool), inverse,
Chris Daltonb91c4662018-08-01 10:46:22 -06002148 result, out);
2149 return inverse;
2150 }
John Stiles1e1fe122021-01-29 12:18:46 -05002151
ethannicholasb3058bd2016-07-01 08:22:01 -07002152 return result;
2153}
2154
Ethan Nicholas0df1b042017-03-31 13:56:23 -04002155SpvId SPIRVCodeGenerator::writeIndexExpression(const IndexExpression& expr, OutputStream& out) {
John Stiles9aeed132020-11-24 17:36:06 -05002156 if (expr.base()->type().isVector()) {
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04002157 SpvId base = this->writeExpression(*expr.base(), out);
2158 SpvId index = this->writeExpression(*expr.index(), out);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002159 SpvId result = this->nextId(nullptr);
Ethan Nicholas30d30222020-09-11 12:27:26 -04002160 this->writeInstruction(SpvOpVectorExtractDynamic, this->getType(expr.type()), result, base,
Ethan Nicholasa9a06902019-01-07 14:42:40 -05002161 index, out);
2162 return result;
2163 }
ethannicholasb3058bd2016-07-01 08:22:01 -07002164 return getLValue(expr, out)->load(out);
2165}
2166
Ethan Nicholas0df1b042017-03-31 13:56:23 -04002167SpvId SPIRVCodeGenerator::writeFieldAccess(const FieldAccess& f, OutputStream& out) {
ethannicholasb3058bd2016-07-01 08:22:01 -07002168 return getLValue(f, out)->load(out);
2169}
2170
Ethan Nicholas0df1b042017-03-31 13:56:23 -04002171SpvId SPIRVCodeGenerator::writeSwizzle(const Swizzle& swizzle, OutputStream& out) {
Ethan Nicholas6b4d5812020-10-12 16:11:51 -04002172 SpvId base = this->writeExpression(*swizzle.base(), out);
Ethan Nicholas7f015882021-03-23 14:16:52 -04002173 SpvId result = this->nextId(&swizzle.type());
Ethan Nicholas6b4d5812020-10-12 16:11:51 -04002174 size_t count = swizzle.components().size();
ethannicholasb3058bd2016-07-01 08:22:01 -07002175 if (count == 1) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04002176 this->writeInstruction(SpvOpCompositeExtract, this->getType(swizzle.type()), result, base,
Ethan Nicholas6b4d5812020-10-12 16:11:51 -04002177 swizzle.components()[0], out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002178 } else {
2179 this->writeOpCode(SpvOpVectorShuffle, 5 + (int32_t) count, out);
Ethan Nicholas30d30222020-09-11 12:27:26 -04002180 this->writeWord(this->getType(swizzle.type()), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002181 this->writeWord(result, out);
2182 this->writeWord(base, out);
Brian Osman25647672020-09-15 15:16:56 -04002183 this->writeWord(base, out);
Ethan Nicholas6b4d5812020-10-12 16:11:51 -04002184 for (int component : swizzle.components()) {
Brian Osman25647672020-09-15 15:16:56 -04002185 this->writeWord(component, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002186 }
2187 }
2188 return result;
2189}
2190
Greg Daniel64773e62016-11-22 09:44:03 -05002191SpvId SPIRVCodeGenerator::writeBinaryOperation(const Type& resultType,
2192 const Type& operandType, SpvId lhs,
2193 SpvId rhs, SpvOp_ ifFloat, SpvOp_ ifInt,
Ethan Nicholas0df1b042017-03-31 13:56:23 -04002194 SpvOp_ ifUInt, SpvOp_ ifBool, OutputStream& out) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002195 SpvId result = this->nextId(&resultType);
ethannicholasd598f792016-07-25 10:08:54 -07002196 if (is_float(fContext, operandType)) {
ethannicholasb3058bd2016-07-01 08:22:01 -07002197 this->writeInstruction(ifFloat, this->getType(resultType), result, lhs, rhs, out);
ethannicholasd598f792016-07-25 10:08:54 -07002198 } else if (is_signed(fContext, operandType)) {
ethannicholasb3058bd2016-07-01 08:22:01 -07002199 this->writeInstruction(ifInt, this->getType(resultType), result, lhs, rhs, out);
ethannicholasd598f792016-07-25 10:08:54 -07002200 } else if (is_unsigned(fContext, operandType)) {
ethannicholasb3058bd2016-07-01 08:22:01 -07002201 this->writeInstruction(ifUInt, this->getType(resultType), result, lhs, rhs, out);
John Stiles123501f2020-12-09 10:08:13 -05002202 } else if (is_bool(fContext, operandType)) {
ethannicholasb3058bd2016-07-01 08:22:01 -07002203 this->writeInstruction(ifBool, this->getType(resultType), result, lhs, rhs, out);
2204 } else {
John Stiles123501f2020-12-09 10:08:13 -05002205 fErrors.error(operandType.fOffset,
2206 "unsupported operand for binary expression: " + operandType.description());
Ethan Nicholas2f4652f2021-03-12 18:48:48 +00002207 }
ethannicholasb3058bd2016-07-01 08:22:01 -07002208 return result;
2209}
2210
Ethan Nicholas48e24052018-03-14 13:51:39 -04002211SpvId SPIRVCodeGenerator::foldToBool(SpvId id, const Type& operandType, SpvOp op,
2212 OutputStream& out) {
John Stiles9aeed132020-11-24 17:36:06 -05002213 if (operandType.isVector()) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002214 SpvId result = this->nextId(nullptr);
John Stiles54e7c052021-01-11 14:22:36 -05002215 this->writeInstruction(op, this->getType(*fContext.fTypes.fBool), result, id, out);
Ethan Nicholasef653b82017-02-21 13:50:00 -05002216 return result;
2217 }
2218 return id;
2219}
2220
Ethan Nicholas68990be2017-07-13 09:36:52 -04002221SpvId SPIRVCodeGenerator::writeMatrixComparison(const Type& operandType, SpvId lhs, SpvId rhs,
2222 SpvOp_ floatOperator, SpvOp_ intOperator,
Ethan Nicholas0df21132018-07-10 09:37:51 -04002223 SpvOp_ vectorMergeOperator, SpvOp_ mergeOperator,
Ethan Nicholas68990be2017-07-13 09:36:52 -04002224 OutputStream& out) {
2225 SpvOp_ compareOp = is_float(fContext, operandType) ? floatOperator : intOperator;
John Stiles9aeed132020-11-24 17:36:06 -05002226 SkASSERT(operandType.isMatrix());
Ethan Nicholas0df21132018-07-10 09:37:51 -04002227 SpvId columnType = this->getType(operandType.componentType().toCompound(fContext,
2228 operandType.rows(),
2229 1));
John Stiles54e7c052021-01-11 14:22:36 -05002230 SpvId bvecType = this->getType(fContext.fTypes.fBool->toCompound(fContext,
Ethan Nicholas0df21132018-07-10 09:37:51 -04002231 operandType.rows(),
Ethan Nicholas68990be2017-07-13 09:36:52 -04002232 1));
John Stiles54e7c052021-01-11 14:22:36 -05002233 SpvId boolType = this->getType(*fContext.fTypes.fBool);
Ethan Nicholas68990be2017-07-13 09:36:52 -04002234 SpvId result = 0;
Ethan Nicholas0df21132018-07-10 09:37:51 -04002235 for (int i = 0; i < operandType.columns(); i++) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002236 SpvId columnL = this->nextId(&operandType);
Ethan Nicholas0df21132018-07-10 09:37:51 -04002237 this->writeInstruction(SpvOpCompositeExtract, columnType, columnL, lhs, i, out);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002238 SpvId columnR = this->nextId(&operandType);
Ethan Nicholas0df21132018-07-10 09:37:51 -04002239 this->writeInstruction(SpvOpCompositeExtract, columnType, columnR, rhs, i, out);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002240 SpvId compare = this->nextId(&operandType);
Ethan Nicholas0df21132018-07-10 09:37:51 -04002241 this->writeInstruction(compareOp, bvecType, compare, columnL, columnR, out);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002242 SpvId merge = this->nextId(nullptr);
Ethan Nicholas0df21132018-07-10 09:37:51 -04002243 this->writeInstruction(vectorMergeOperator, boolType, merge, compare, out);
Ethan Nicholas68990be2017-07-13 09:36:52 -04002244 if (result != 0) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002245 SpvId next = this->nextId(nullptr);
Ethan Nicholas0df21132018-07-10 09:37:51 -04002246 this->writeInstruction(mergeOperator, boolType, next, result, merge, out);
Ethan Nicholas68990be2017-07-13 09:36:52 -04002247 result = next;
2248 }
2249 else {
Ethan Nicholas0df21132018-07-10 09:37:51 -04002250 result = merge;
Ethan Nicholas68990be2017-07-13 09:36:52 -04002251 }
2252 }
2253 return result;
2254}
2255
Ethan Nicholas0df21132018-07-10 09:37:51 -04002256SpvId SPIRVCodeGenerator::writeComponentwiseMatrixBinary(const Type& operandType, SpvId lhs,
John Stiles43b593c2021-05-13 22:03:27 -04002257 SpvId rhs, SpvOp_ op, OutputStream& out) {
John Stiles9aeed132020-11-24 17:36:06 -05002258 SkASSERT(operandType.isMatrix());
Ethan Nicholas2f4652f2021-03-12 18:48:48 +00002259 SpvId columnType = this->getType(operandType.componentType().toCompound(fContext,
2260 operandType.rows(),
2261 1));
John Stiles43b593c2021-05-13 22:03:27 -04002262 std::vector<SpvId> columns;
2263 columns.reserve(operandType.columns());
Ethan Nicholas0df21132018-07-10 09:37:51 -04002264 for (int i = 0; i < operandType.columns(); i++) {
Ethan Nicholas7f015882021-03-23 14:16:52 -04002265 SpvId columnL = this->nextId(&operandType);
Ethan Nicholas2f4652f2021-03-12 18:48:48 +00002266 this->writeInstruction(SpvOpCompositeExtract, columnType, columnL, lhs, i, out);
Ethan Nicholas7f015882021-03-23 14:16:52 -04002267 SpvId columnR = this->nextId(&operandType);
Ethan Nicholas2f4652f2021-03-12 18:48:48 +00002268 this->writeInstruction(SpvOpCompositeExtract, columnType, columnR, rhs, i, out);
John Stiles43b593c2021-05-13 22:03:27 -04002269 columns.push_back(this->nextId(&operandType));
Ethan Nicholas2f4652f2021-03-12 18:48:48 +00002270 this->writeInstruction(op, columnType, columns[i], columnL, columnR, out);
Ethan Nicholas0df21132018-07-10 09:37:51 -04002271 }
John Stiles43b593c2021-05-13 22:03:27 -04002272 return this->writeComposite(columns, operandType, out);
Ethan Nicholas0df21132018-07-10 09:37:51 -04002273}
2274
John Stiles9485b552021-01-27 11:47:00 -05002275static std::unique_ptr<Expression> create_literal_1(const Context& context, const Type& type) {
Ethan Nicholas49465b42019-04-17 12:22:21 -04002276 if (type.isInteger()) {
John Stiles9ce80f72021-03-11 22:35:19 -05002277 return IntLiteral::Make(/*offset=*/-1, /*value=*/1, &type);
ethannicholasb3058bd2016-07-01 08:22:01 -07002278 }
Ethan Nicholas49465b42019-04-17 12:22:21 -04002279 else if (type.isFloat()) {
John Stiles9ce80f72021-03-11 22:35:19 -05002280 return FloatLiteral::Make(/*offset=*/-1, /*value=*/1.0, &type);
ethannicholasb3058bd2016-07-01 08:22:01 -07002281 } else {
John Stilesf57207b2021-02-02 17:50:34 -05002282 SK_ABORT("math is unsupported on type '%s'", String(type.name()).c_str());
ethannicholasb3058bd2016-07-01 08:22:01 -07002283 }
Ethan Nicholas49465b42019-04-17 12:22:21 -04002284}
2285
John Stilesd94bfdd2021-03-25 11:44:08 -04002286SpvId SPIRVCodeGenerator::writeReciprocal(const Type& type, SpvId value, OutputStream& out) {
2287 SkASSERT(type.isFloat());
2288 SpvId one = this->writeFloatLiteral({/*offset=*/-1, /*value=*/1, &type});
2289 SpvId reciprocal = this->nextId(&type);
2290 this->writeInstruction(SpvOpFDiv, this->getType(type), reciprocal, one, value, out);
2291 return reciprocal;
2292}
2293
John Stiles45990502021-02-16 10:55:27 -05002294SpvId SPIRVCodeGenerator::writeBinaryExpression(const Type& leftType, SpvId lhs, Operator op,
Ethan Nicholas49465b42019-04-17 12:22:21 -04002295 const Type& rightType, SpvId rhs,
2296 const Type& resultType, OutputStream& out) {
John Stilesd0614f22020-12-09 11:11:41 -05002297 // The comma operator ignores the type of the left-hand side entirely.
John Stiles45990502021-02-16 10:55:27 -05002298 if (op.kind() == Token::Kind::TK_COMMA) {
John Stilesd0614f22020-12-09 11:11:41 -05002299 return rhs;
2300 }
Ethan Nicholas48e24052018-03-14 13:51:39 -04002301 // overall type we are operating on: float2, int, uint4...
ethannicholasb3058bd2016-07-01 08:22:01 -07002302 const Type* operandType;
Ethan Nicholas48e24052018-03-14 13:51:39 -04002303 // IR allows mismatched types in expressions (e.g. float2 * float), but they need special
2304 // handling in SPIR-V
Ethan Nicholas49465b42019-04-17 12:22:21 -04002305 if (this->getActualType(leftType) != this->getActualType(rightType)) {
John Stiles9aeed132020-11-24 17:36:06 -05002306 if (leftType.isVector() && rightType.isNumber()) {
John Stilesd94bfdd2021-03-25 11:44:08 -04002307 if (resultType.componentType().isFloat()) {
2308 switch (op.kind()) {
2309 case Token::Kind::TK_SLASH: {
2310 rhs = this->writeReciprocal(rightType, rhs, out);
2311 [[fallthrough]];
2312 }
2313 case Token::Kind::TK_STAR: {
2314 SpvId result = this->nextId(&resultType);
2315 this->writeInstruction(SpvOpVectorTimesScalar, this->getType(resultType),
2316 result, lhs, rhs, out);
2317 return result;
2318 }
2319 default:
2320 break;
2321 }
Ethan Nicholas49465b42019-04-17 12:22:21 -04002322 }
ethannicholasb3058bd2016-07-01 08:22:01 -07002323 // promote number to vector
Ethan Nicholas49465b42019-04-17 12:22:21 -04002324 const Type& vecType = leftType;
Ethan Nicholas7f015882021-03-23 14:16:52 -04002325 SpvId vec = this->nextId(&vecType);
Ethan Nicholas48e24052018-03-14 13:51:39 -04002326 this->writeOpCode(SpvOpCompositeConstruct, 3 + vecType.columns(), out);
2327 this->writeWord(this->getType(vecType), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002328 this->writeWord(vec, out);
Ethan Nicholas48e24052018-03-14 13:51:39 -04002329 for (int i = 0; i < vecType.columns(); i++) {
ethannicholasb3058bd2016-07-01 08:22:01 -07002330 this->writeWord(rhs, out);
2331 }
2332 rhs = vec;
Ethan Nicholas49465b42019-04-17 12:22:21 -04002333 operandType = &leftType;
John Stiles9aeed132020-11-24 17:36:06 -05002334 } else if (rightType.isVector() && leftType.isNumber()) {
John Stilesd94bfdd2021-03-25 11:44:08 -04002335 if (resultType.componentType().isFloat()) {
2336 if (op.kind() == Token::Kind::TK_STAR) {
2337 SpvId result = this->nextId(&resultType);
2338 this->writeInstruction(SpvOpVectorTimesScalar, this->getType(resultType),
2339 result, rhs, lhs, out);
2340 return result;
2341 }
Ethan Nicholas49465b42019-04-17 12:22:21 -04002342 }
ethannicholasb3058bd2016-07-01 08:22:01 -07002343 // promote number to vector
Ethan Nicholas49465b42019-04-17 12:22:21 -04002344 const Type& vecType = rightType;
Ethan Nicholas7f015882021-03-23 14:16:52 -04002345 SpvId vec = this->nextId(&vecType);
Ethan Nicholas48e24052018-03-14 13:51:39 -04002346 this->writeOpCode(SpvOpCompositeConstruct, 3 + vecType.columns(), out);
2347 this->writeWord(this->getType(vecType), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002348 this->writeWord(vec, out);
Ethan Nicholas48e24052018-03-14 13:51:39 -04002349 for (int i = 0; i < vecType.columns(); i++) {
ethannicholasb3058bd2016-07-01 08:22:01 -07002350 this->writeWord(lhs, out);
2351 }
2352 lhs = vec;
Ethan Nicholas49465b42019-04-17 12:22:21 -04002353 operandType = &rightType;
John Stiles9aeed132020-11-24 17:36:06 -05002354 } else if (leftType.isMatrix()) {
Ethan Nicholas49465b42019-04-17 12:22:21 -04002355 SpvOp_ spvop;
John Stiles9aeed132020-11-24 17:36:06 -05002356 if (rightType.isMatrix()) {
Ethan Nicholas49465b42019-04-17 12:22:21 -04002357 spvop = SpvOpMatrixTimesMatrix;
John Stiles9aeed132020-11-24 17:36:06 -05002358 } else if (rightType.isVector()) {
Ethan Nicholas49465b42019-04-17 12:22:21 -04002359 spvop = SpvOpMatrixTimesVector;
ethannicholasb3058bd2016-07-01 08:22:01 -07002360 } else {
John Stiles9aeed132020-11-24 17:36:06 -05002361 SkASSERT(rightType.isScalar());
Ethan Nicholas49465b42019-04-17 12:22:21 -04002362 spvop = SpvOpMatrixTimesScalar;
ethannicholasb3058bd2016-07-01 08:22:01 -07002363 }
Ethan Nicholas7f015882021-03-23 14:16:52 -04002364 SpvId result = this->nextId(&resultType);
Ethan Nicholas49465b42019-04-17 12:22:21 -04002365 this->writeInstruction(spvop, this->getType(resultType), result, lhs, rhs, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002366 return result;
John Stiles9aeed132020-11-24 17:36:06 -05002367 } else if (rightType.isMatrix()) {
Ethan Nicholas7f015882021-03-23 14:16:52 -04002368 SpvId result = this->nextId(&resultType);
John Stiles9aeed132020-11-24 17:36:06 -05002369 if (leftType.isVector()) {
Ethan Nicholas49465b42019-04-17 12:22:21 -04002370 this->writeInstruction(SpvOpVectorTimesMatrix, this->getType(resultType), result,
ethannicholasb3058bd2016-07-01 08:22:01 -07002371 lhs, rhs, out);
2372 } else {
John Stiles9aeed132020-11-24 17:36:06 -05002373 SkASSERT(leftType.isScalar());
Ethan Nicholas49465b42019-04-17 12:22:21 -04002374 this->writeInstruction(SpvOpMatrixTimesScalar, this->getType(resultType), result,
2375 rhs, lhs, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002376 }
2377 return result;
2378 } else {
John Stilesd8ca6b62020-11-23 14:28:36 -05002379 fErrors.error(leftType.fOffset, "unsupported mixed-type expression");
Ethan Nicholas49465b42019-04-17 12:22:21 -04002380 return -1;
ethannicholasb3058bd2016-07-01 08:22:01 -07002381 }
2382 } else {
John Stiles2d4f9592020-10-30 10:29:12 -04002383 operandType = &this->getActualType(leftType);
Ethan Nicholas49465b42019-04-17 12:22:21 -04002384 SkASSERT(*operandType == this->getActualType(rightType));
ethannicholasb3058bd2016-07-01 08:22:01 -07002385 }
John Stiles45990502021-02-16 10:55:27 -05002386 switch (op.kind()) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002387 case Token::Kind::TK_EQEQ: {
John Stiles9aeed132020-11-24 17:36:06 -05002388 if (operandType->isMatrix()) {
Ethan Nicholas68990be2017-07-13 09:36:52 -04002389 return this->writeMatrixComparison(*operandType, lhs, rhs, SpvOpFOrdEqual,
Ethan Nicholas0df21132018-07-10 09:37:51 -04002390 SpvOpIEqual, SpvOpAll, SpvOpLogicalAnd, out);
Ethan Nicholas68990be2017-07-13 09:36:52 -04002391 }
John Stilesbc5c2a02021-04-08 11:44:53 -04002392 if (operandType->isStruct()) {
2393 return this->writeStructComparison(*operandType, lhs, op, rhs, out);
2394 }
John Stiles35092102021-04-08 23:30:51 -04002395 if (operandType->isArray()) {
2396 return this->writeArrayComparison(*operandType, lhs, op, rhs, out);
2397 }
John Stiles4a7dc462020-11-25 11:08:08 -05002398 SkASSERT(resultType.isBoolean());
Ethan Nicholas48e24052018-03-14 13:51:39 -04002399 const Type* tmpType;
John Stiles9aeed132020-11-24 17:36:06 -05002400 if (operandType->isVector()) {
John Stiles54e7c052021-01-11 14:22:36 -05002401 tmpType = &fContext.fTypes.fBool->toCompound(fContext,
2402 operandType->columns(),
2403 operandType->rows());
Ethan Nicholas48e24052018-03-14 13:51:39 -04002404 } else {
2405 tmpType = &resultType;
2406 }
2407 return this->foldToBool(this->writeBinaryOperation(*tmpType, *operandType, lhs, rhs,
Ethan Nicholasef653b82017-02-21 13:50:00 -05002408 SpvOpFOrdEqual, SpvOpIEqual,
2409 SpvOpIEqual, SpvOpLogicalEqual, out),
Ethan Nicholas48e24052018-03-14 13:51:39 -04002410 *operandType, SpvOpAll, out);
Ethan Nicholasef653b82017-02-21 13:50:00 -05002411 }
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002412 case Token::Kind::TK_NEQ:
John Stiles9aeed132020-11-24 17:36:06 -05002413 if (operandType->isMatrix()) {
Ethan Nicholas68990be2017-07-13 09:36:52 -04002414 return this->writeMatrixComparison(*operandType, lhs, rhs, SpvOpFOrdNotEqual,
Ethan Nicholas0df21132018-07-10 09:37:51 -04002415 SpvOpINotEqual, SpvOpAny, SpvOpLogicalOr, out);
Ethan Nicholas68990be2017-07-13 09:36:52 -04002416 }
John Stilesbc5c2a02021-04-08 11:44:53 -04002417 if (operandType->isStruct()) {
2418 return this->writeStructComparison(*operandType, lhs, op, rhs, out);
2419 }
John Stiles35092102021-04-08 23:30:51 -04002420 if (operandType->isArray()) {
2421 return this->writeArrayComparison(*operandType, lhs, op, rhs, out);
2422 }
John Stiles4a7dc462020-11-25 11:08:08 -05002423 [[fallthrough]];
2424 case Token::Kind::TK_LOGICALXOR:
2425 SkASSERT(resultType.isBoolean());
Ethan Nicholas48e24052018-03-14 13:51:39 -04002426 const Type* tmpType;
John Stiles9aeed132020-11-24 17:36:06 -05002427 if (operandType->isVector()) {
John Stiles54e7c052021-01-11 14:22:36 -05002428 tmpType = &fContext.fTypes.fBool->toCompound(fContext,
2429 operandType->columns(),
2430 operandType->rows());
Ethan Nicholas48e24052018-03-14 13:51:39 -04002431 } else {
2432 tmpType = &resultType;
2433 }
2434 return this->foldToBool(this->writeBinaryOperation(*tmpType, *operandType, lhs, rhs,
Ethan Nicholasef653b82017-02-21 13:50:00 -05002435 SpvOpFOrdNotEqual, SpvOpINotEqual,
2436 SpvOpINotEqual, SpvOpLogicalNotEqual,
2437 out),
Ethan Nicholas48e24052018-03-14 13:51:39 -04002438 *operandType, SpvOpAny, out);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002439 case Token::Kind::TK_GT:
John Stiles4a7dc462020-11-25 11:08:08 -05002440 SkASSERT(resultType.isBoolean());
Greg Daniel64773e62016-11-22 09:44:03 -05002441 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs,
2442 SpvOpFOrdGreaterThan, SpvOpSGreaterThan,
ethannicholasb3058bd2016-07-01 08:22:01 -07002443 SpvOpUGreaterThan, SpvOpUndef, out);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002444 case Token::Kind::TK_LT:
John Stiles4a7dc462020-11-25 11:08:08 -05002445 SkASSERT(resultType.isBoolean());
Greg Daniel64773e62016-11-22 09:44:03 -05002446 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs, SpvOpFOrdLessThan,
ethannicholasb3058bd2016-07-01 08:22:01 -07002447 SpvOpSLessThan, SpvOpULessThan, SpvOpUndef, out);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002448 case Token::Kind::TK_GTEQ:
John Stiles4a7dc462020-11-25 11:08:08 -05002449 SkASSERT(resultType.isBoolean());
Greg Daniel64773e62016-11-22 09:44:03 -05002450 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs,
2451 SpvOpFOrdGreaterThanEqual, SpvOpSGreaterThanEqual,
ethannicholasb3058bd2016-07-01 08:22:01 -07002452 SpvOpUGreaterThanEqual, SpvOpUndef, out);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002453 case Token::Kind::TK_LTEQ:
John Stiles4a7dc462020-11-25 11:08:08 -05002454 SkASSERT(resultType.isBoolean());
Greg Daniel64773e62016-11-22 09:44:03 -05002455 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs,
2456 SpvOpFOrdLessThanEqual, SpvOpSLessThanEqual,
ethannicholasb3058bd2016-07-01 08:22:01 -07002457 SpvOpULessThanEqual, SpvOpUndef, out);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002458 case Token::Kind::TK_PLUS:
John Stiles9aeed132020-11-24 17:36:06 -05002459 if (leftType.isMatrix() && rightType.isMatrix()) {
Ethan Nicholas49465b42019-04-17 12:22:21 -04002460 SkASSERT(leftType == rightType);
John Stiles43b593c2021-05-13 22:03:27 -04002461 return this->writeComponentwiseMatrixBinary(leftType, lhs, rhs, SpvOpFAdd, out);
Ethan Nicholas0df21132018-07-10 09:37:51 -04002462 }
Greg Daniel64773e62016-11-22 09:44:03 -05002463 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs, SpvOpFAdd,
ethannicholasb3058bd2016-07-01 08:22:01 -07002464 SpvOpIAdd, SpvOpIAdd, SpvOpUndef, out);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002465 case Token::Kind::TK_MINUS:
John Stiles9aeed132020-11-24 17:36:06 -05002466 if (leftType.isMatrix() && rightType.isMatrix()) {
Ethan Nicholas49465b42019-04-17 12:22:21 -04002467 SkASSERT(leftType == rightType);
John Stiles43b593c2021-05-13 22:03:27 -04002468 return this->writeComponentwiseMatrixBinary(leftType, lhs, rhs, SpvOpFSub, out);
Ethan Nicholas0df21132018-07-10 09:37:51 -04002469 }
Greg Daniel64773e62016-11-22 09:44:03 -05002470 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs, SpvOpFSub,
ethannicholasb3058bd2016-07-01 08:22:01 -07002471 SpvOpISub, SpvOpISub, SpvOpUndef, out);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002472 case Token::Kind::TK_STAR:
John Stiles9aeed132020-11-24 17:36:06 -05002473 if (leftType.isMatrix() && rightType.isMatrix()) {
ethannicholasb3058bd2016-07-01 08:22:01 -07002474 // matrix multiply
Ethan Nicholas7f015882021-03-23 14:16:52 -04002475 SpvId result = this->nextId(&resultType);
ethannicholasb3058bd2016-07-01 08:22:01 -07002476 this->writeInstruction(SpvOpMatrixTimesMatrix, this->getType(resultType), result,
2477 lhs, rhs, out);
2478 return result;
2479 }
Greg Daniel64773e62016-11-22 09:44:03 -05002480 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs, SpvOpFMul,
ethannicholasb3058bd2016-07-01 08:22:01 -07002481 SpvOpIMul, SpvOpIMul, SpvOpUndef, out);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002482 case Token::Kind::TK_SLASH:
Greg Daniel64773e62016-11-22 09:44:03 -05002483 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs, SpvOpFDiv,
ethannicholasb3058bd2016-07-01 08:22:01 -07002484 SpvOpSDiv, SpvOpUDiv, SpvOpUndef, out);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002485 case Token::Kind::TK_PERCENT:
Ethan Nicholasb3d0f7c2017-05-17 13:13:21 -04002486 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs, SpvOpFMod,
2487 SpvOpSMod, SpvOpUMod, SpvOpUndef, out);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002488 case Token::Kind::TK_SHL:
Ethan Nicholasfd444be2017-07-05 10:05:54 -04002489 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs, SpvOpUndef,
2490 SpvOpShiftLeftLogical, SpvOpShiftLeftLogical,
2491 SpvOpUndef, out);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002492 case Token::Kind::TK_SHR:
Ethan Nicholasfd444be2017-07-05 10:05:54 -04002493 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs, SpvOpUndef,
2494 SpvOpShiftRightArithmetic, SpvOpShiftRightLogical,
2495 SpvOpUndef, out);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002496 case Token::Kind::TK_BITWISEAND:
Ethan Nicholasfd444be2017-07-05 10:05:54 -04002497 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs, SpvOpUndef,
2498 SpvOpBitwiseAnd, SpvOpBitwiseAnd, SpvOpUndef, out);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002499 case Token::Kind::TK_BITWISEOR:
Ethan Nicholasfd444be2017-07-05 10:05:54 -04002500 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs, SpvOpUndef,
2501 SpvOpBitwiseOr, SpvOpBitwiseOr, SpvOpUndef, out);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002502 case Token::Kind::TK_BITWISEXOR:
Ethan Nicholasfd444be2017-07-05 10:05:54 -04002503 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs, SpvOpUndef,
2504 SpvOpBitwiseXor, SpvOpBitwiseXor, SpvOpUndef, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002505 default:
John Stiles5570c512020-11-19 17:58:07 -05002506 fErrors.error(0, "unsupported token");
Ethan Nicholas49465b42019-04-17 12:22:21 -04002507 return -1;
ethannicholasb3058bd2016-07-01 08:22:01 -07002508 }
2509}
2510
John Stiles35092102021-04-08 23:30:51 -04002511SpvId SPIRVCodeGenerator::writeArrayComparison(const Type& arrayType, SpvId lhs, Operator op,
2512 SpvId rhs, OutputStream& out) {
2513 // The inputs must be arrays, and the op must be == or !=.
2514 SkASSERT(op.kind() == Token::Kind::TK_EQEQ || op.kind() == Token::Kind::TK_NEQ);
2515 SkASSERT(arrayType.isArray());
2516 const Type& componentType = arrayType.componentType();
2517 const SpvId componentTypeId = this->getType(componentType);
2518 const int arraySize = arrayType.columns();
2519 SkASSERT(arraySize > 0);
2520
2521 // Synthesize equality checks for each item in the array.
2522 const Type& boolType = *fContext.fTypes.fBool;
2523 SpvId allComparisons = (SpvId)-1;
2524 for (int index = 0; index < arraySize; ++index) {
2525 // Get the left and right item in the array.
2526 SpvId itemL = this->nextId(&componentType);
2527 this->writeInstruction(SpvOpCompositeExtract, componentTypeId, itemL, lhs, index, out);
2528 SpvId itemR = this->nextId(&componentType);
2529 this->writeInstruction(SpvOpCompositeExtract, componentTypeId, itemR, rhs, index, out);
2530 // Use `writeBinaryExpression` with the requested == or != operator on these items.
2531 SpvId comparison = this->writeBinaryExpression(componentType, itemL, op,
2532 componentType, itemR, boolType, out);
2533 // Merge this comparison result with all the other comparisons we've done.
2534 allComparisons = this->mergeComparisons(comparison, allComparisons, op, out);
2535 }
2536 return allComparisons;
2537}
2538
John Stilesbc5c2a02021-04-08 11:44:53 -04002539SpvId SPIRVCodeGenerator::writeStructComparison(const Type& structType, SpvId lhs, Operator op,
2540 SpvId rhs, OutputStream& out) {
2541 // The inputs must be structs containing fields, and the op must be == or !=.
John Stilesbc5c2a02021-04-08 11:44:53 -04002542 SkASSERT(op.kind() == Token::Kind::TK_EQEQ || op.kind() == Token::Kind::TK_NEQ);
John Stiles35092102021-04-08 23:30:51 -04002543 SkASSERT(structType.isStruct());
John Stilesbc5c2a02021-04-08 11:44:53 -04002544 const std::vector<Type::Field>& fields = structType.fields();
2545 SkASSERT(!fields.empty());
2546
2547 // Synthesize equality checks for each field in the struct.
2548 const Type& boolType = *fContext.fTypes.fBool;
John Stilesbc5c2a02021-04-08 11:44:53 -04002549 SpvId allComparisons = (SpvId)-1;
2550 for (int index = 0; index < (int)fields.size(); ++index) {
2551 // Get the left and right versions of this field.
2552 const Type& fieldType = *fields[index].fType;
John Stiles35092102021-04-08 23:30:51 -04002553 const SpvId fieldTypeId = this->getType(fieldType);
John Stilesbc5c2a02021-04-08 11:44:53 -04002554
2555 SpvId fieldL = this->nextId(&fieldType);
2556 this->writeInstruction(SpvOpCompositeExtract, fieldTypeId, fieldL, lhs, index, out);
2557 SpvId fieldR = this->nextId(&fieldType);
2558 this->writeInstruction(SpvOpCompositeExtract, fieldTypeId, fieldR, rhs, index, out);
2559 // Use `writeBinaryExpression` with the requested == or != operator on these fields.
2560 SpvId comparison = this->writeBinaryExpression(fieldType, fieldL, op, fieldType, fieldR,
2561 boolType, out);
John Stiles35092102021-04-08 23:30:51 -04002562 // Merge this comparison result with all the other comparisons we've done.
2563 allComparisons = this->mergeComparisons(comparison, allComparisons, op, out);
John Stilesbc5c2a02021-04-08 11:44:53 -04002564 }
2565 return allComparisons;
2566}
2567
John Stiles35092102021-04-08 23:30:51 -04002568SpvId SPIRVCodeGenerator::mergeComparisons(SpvId comparison, SpvId allComparisons, Operator op,
2569 OutputStream& out) {
2570 // If this is the first entry, we don't need to merge comparison results with anything.
2571 if (allComparisons == (SpvId)-1) {
2572 return comparison;
2573 }
2574 // Use LogicalAnd or LogicalOr to combine the comparison with all the other comparisons.
2575 const Type& boolType = *fContext.fTypes.fBool;
2576 SpvId boolTypeId = this->getType(boolType);
2577 SpvId logicalOp = this->nextId(&boolType);
2578 switch (op.kind()) {
2579 case Token::Kind::TK_EQEQ:
2580 this->writeInstruction(SpvOpLogicalAnd, boolTypeId, logicalOp,
2581 comparison, allComparisons, out);
2582 break;
2583 case Token::Kind::TK_NEQ:
2584 this->writeInstruction(SpvOpLogicalOr, boolTypeId, logicalOp,
2585 comparison, allComparisons, out);
2586 break;
2587 default:
2588 SkDEBUGFAILF("mergeComparisons only supports == and !=, not %s", op.operatorName());
2589 return (SpvId)-1;
2590 }
2591 return logicalOp;
2592}
2593
John Stilesbc5c2a02021-04-08 11:44:53 -04002594static float division_by_literal_value(Operator op, const Expression& right) {
2595 // If this is a division by a literal value, returns that literal value. Otherwise, returns 0.
2596 if (op.kind() == Token::Kind::TK_SLASH && right.is<FloatLiteral>()) {
2597 float rhsValue = right.as<FloatLiteral>().value();
2598 if (std::isfinite(rhsValue)) {
2599 return rhsValue;
2600 }
2601 }
2602 return 0.0f;
2603}
2604
Ethan Nicholas49465b42019-04-17 12:22:21 -04002605SpvId SPIRVCodeGenerator::writeBinaryExpression(const BinaryExpression& b, OutputStream& out) {
John Stiles2396fb82021-03-25 11:44:55 -04002606 const Expression* left = b.left().get();
2607 const Expression* right = b.right().get();
John Stiles45990502021-02-16 10:55:27 -05002608 Operator op = b.getOperator();
John Stilesbc5c2a02021-04-08 11:44:53 -04002609
John Stiles45990502021-02-16 10:55:27 -05002610 switch (op.kind()) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002611 case Token::Kind::TK_EQ: {
John Stilesbc5c2a02021-04-08 11:44:53 -04002612 // Handles assignment.
John Stiles2396fb82021-03-25 11:44:55 -04002613 SpvId rhs = this->writeExpression(*right, out);
2614 this->getLValue(*left, out)->store(rhs, out);
Ethan Nicholas49465b42019-04-17 12:22:21 -04002615 return rhs;
2616 }
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002617 case Token::Kind::TK_LOGICALAND:
John Stilesbc5c2a02021-04-08 11:44:53 -04002618 // Handles short-circuiting; we don't necessarily evaluate both LHS and RHS.
2619 return this->writeLogicalAnd(*b.left(), *b.right(), out);
2620
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002621 case Token::Kind::TK_LOGICALOR:
John Stilesbc5c2a02021-04-08 11:44:53 -04002622 // Handles short-circuiting; we don't necessarily evaluate both LHS and RHS.
2623 return this->writeLogicalOr(*b.left(), *b.right(), out);
2624
Ethan Nicholas49465b42019-04-17 12:22:21 -04002625 default:
2626 break;
2627 }
2628
2629 std::unique_ptr<LValue> lvalue;
2630 SpvId lhs;
John Stiles45990502021-02-16 10:55:27 -05002631 if (op.isAssignment()) {
John Stiles2396fb82021-03-25 11:44:55 -04002632 lvalue = this->getLValue(*left, out);
Ethan Nicholas49465b42019-04-17 12:22:21 -04002633 lhs = lvalue->load(out);
2634 } else {
2635 lvalue = nullptr;
John Stiles2396fb82021-03-25 11:44:55 -04002636 lhs = this->writeExpression(*left, out);
Ethan Nicholas49465b42019-04-17 12:22:21 -04002637 }
John Stiles2396fb82021-03-25 11:44:55 -04002638
John Stilesbc5c2a02021-04-08 11:44:53 -04002639 SpvId rhs;
2640 float rhsValue = division_by_literal_value(op, *right);
2641 if (rhsValue != 0.0f) {
2642 // Rewrite floating-point division by a literal into multiplication by the reciprocal.
2643 // This converts `expr / 2` into `expr * 0.5`
2644 // This improves codegen, especially for certain types of divides (e.g. vector/scalar).
2645 op = Operator(Token::Kind::TK_STAR);
2646 FloatLiteral reciprocal{right->fOffset, 1.0f / rhsValue, &right->type()};
2647 rhs = this->writeExpression(reciprocal, out);
2648 } else {
2649 // Write the right-hand side expression normally.
John Stiles2396fb82021-03-25 11:44:55 -04002650 rhs = this->writeExpression(*right, out);
2651 }
2652
2653 SpvId result = this->writeBinaryExpression(left->type(), lhs, op.removeAssignment(),
2654 right->type(), rhs, b.type(), out);
Ethan Nicholas49465b42019-04-17 12:22:21 -04002655 if (lvalue) {
2656 lvalue->store(result, out);
2657 }
2658 return result;
2659}
2660
John Stilesbc5c2a02021-04-08 11:44:53 -04002661SpvId SPIRVCodeGenerator::writeLogicalAnd(const Expression& left, const Expression& right,
2662 OutputStream& out) {
John Stiles9ce80f72021-03-11 22:35:19 -05002663 BoolLiteral falseLiteral(/*offset=*/-1, /*value=*/false, fContext.fTypes.fBool.get());
ethannicholasb3058bd2016-07-01 08:22:01 -07002664 SpvId falseConstant = this->writeBoolLiteral(falseLiteral);
John Stilesbc5c2a02021-04-08 11:44:53 -04002665 SpvId lhs = this->writeExpression(left, out);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002666 SpvId rhsLabel = this->nextId(nullptr);
2667 SpvId end = this->nextId(nullptr);
ethannicholasb3058bd2016-07-01 08:22:01 -07002668 SpvId lhsBlock = fCurrentBlock;
2669 this->writeInstruction(SpvOpSelectionMerge, end, SpvSelectionControlMaskNone, out);
2670 this->writeInstruction(SpvOpBranchConditional, lhs, rhsLabel, end, out);
2671 this->writeLabel(rhsLabel, out);
John Stilesbc5c2a02021-04-08 11:44:53 -04002672 SpvId rhs = this->writeExpression(right, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002673 SpvId rhsBlock = fCurrentBlock;
2674 this->writeInstruction(SpvOpBranch, end, out);
2675 this->writeLabel(end, out);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002676 SpvId result = this->nextId(nullptr);
John Stiles54e7c052021-01-11 14:22:36 -05002677 this->writeInstruction(SpvOpPhi, this->getType(*fContext.fTypes.fBool), result, falseConstant,
ethannicholasd598f792016-07-25 10:08:54 -07002678 lhsBlock, rhs, rhsBlock, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002679 return result;
2680}
2681
John Stilesbc5c2a02021-04-08 11:44:53 -04002682SpvId SPIRVCodeGenerator::writeLogicalOr(const Expression& left, const Expression& right,
2683 OutputStream& out) {
John Stiles9ce80f72021-03-11 22:35:19 -05002684 BoolLiteral trueLiteral(/*offset=*/-1, /*value=*/true, fContext.fTypes.fBool.get());
ethannicholasb3058bd2016-07-01 08:22:01 -07002685 SpvId trueConstant = this->writeBoolLiteral(trueLiteral);
John Stilesbc5c2a02021-04-08 11:44:53 -04002686 SpvId lhs = this->writeExpression(left, out);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002687 SpvId rhsLabel = this->nextId(nullptr);
2688 SpvId end = this->nextId(nullptr);
ethannicholasb3058bd2016-07-01 08:22:01 -07002689 SpvId lhsBlock = fCurrentBlock;
2690 this->writeInstruction(SpvOpSelectionMerge, end, SpvSelectionControlMaskNone, out);
2691 this->writeInstruction(SpvOpBranchConditional, lhs, end, rhsLabel, out);
2692 this->writeLabel(rhsLabel, out);
John Stilesbc5c2a02021-04-08 11:44:53 -04002693 SpvId rhs = this->writeExpression(right, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002694 SpvId rhsBlock = fCurrentBlock;
2695 this->writeInstruction(SpvOpBranch, end, out);
2696 this->writeLabel(end, out);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002697 SpvId result = this->nextId(nullptr);
John Stiles54e7c052021-01-11 14:22:36 -05002698 this->writeInstruction(SpvOpPhi, this->getType(*fContext.fTypes.fBool), result, trueConstant,
ethannicholasd598f792016-07-25 10:08:54 -07002699 lhsBlock, rhs, rhsBlock, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002700 return result;
2701}
2702
Ethan Nicholas0df1b042017-03-31 13:56:23 -04002703SpvId SPIRVCodeGenerator::writeTernaryExpression(const TernaryExpression& t, OutputStream& out) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04002704 const Type& type = t.type();
Ethan Nicholasdd218162020-10-08 05:48:01 -04002705 SpvId test = this->writeExpression(*t.test(), out);
2706 if (t.ifTrue()->type().columns() == 1 &&
2707 t.ifTrue()->isCompileTimeConstant() &&
2708 t.ifFalse()->isCompileTimeConstant()) {
ethannicholasb3058bd2016-07-01 08:22:01 -07002709 // both true and false are constants, can just use OpSelect
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002710 SpvId result = this->nextId(nullptr);
Ethan Nicholasdd218162020-10-08 05:48:01 -04002711 SpvId trueId = this->writeExpression(*t.ifTrue(), out);
2712 SpvId falseId = this->writeExpression(*t.ifFalse(), out);
Ethan Nicholas30d30222020-09-11 12:27:26 -04002713 this->writeInstruction(SpvOpSelect, this->getType(type), result, test, trueId, falseId,
ethannicholasb3058bd2016-07-01 08:22:01 -07002714 out);
2715 return result;
2716 }
Greg Daniel64773e62016-11-22 09:44:03 -05002717 // was originally using OpPhi to choose the result, but for some reason that is crashing on
ethannicholasb3058bd2016-07-01 08:22:01 -07002718 // Adreno. Switched to storing the result in a temp variable as glslang does.
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002719 SpvId var = this->nextId(nullptr);
Ethan Nicholas30d30222020-09-11 12:27:26 -04002720 this->writeInstruction(SpvOpVariable, this->getPointerType(type, SpvStorageClassFunction),
ethannicholasd598f792016-07-25 10:08:54 -07002721 var, SpvStorageClassFunction, fVariableBuffer);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002722 SpvId trueLabel = this->nextId(nullptr);
2723 SpvId falseLabel = this->nextId(nullptr);
2724 SpvId end = this->nextId(nullptr);
ethannicholasb3058bd2016-07-01 08:22:01 -07002725 this->writeInstruction(SpvOpSelectionMerge, end, SpvSelectionControlMaskNone, out);
2726 this->writeInstruction(SpvOpBranchConditional, test, trueLabel, falseLabel, out);
2727 this->writeLabel(trueLabel, out);
Ethan Nicholasdd218162020-10-08 05:48:01 -04002728 this->writeInstruction(SpvOpStore, var, this->writeExpression(*t.ifTrue(), out), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002729 this->writeInstruction(SpvOpBranch, end, out);
2730 this->writeLabel(falseLabel, out);
Ethan Nicholasdd218162020-10-08 05:48:01 -04002731 this->writeInstruction(SpvOpStore, var, this->writeExpression(*t.ifFalse(), out), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002732 this->writeInstruction(SpvOpBranch, end, out);
2733 this->writeLabel(end, out);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002734 SpvId result = this->nextId(&type);
Ethan Nicholas30d30222020-09-11 12:27:26 -04002735 this->writeInstruction(SpvOpLoad, this->getType(type), result, var, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002736 return result;
2737}
2738
Ethan Nicholas0df1b042017-03-31 13:56:23 -04002739SpvId SPIRVCodeGenerator::writePrefixExpression(const PrefixExpression& p, OutputStream& out) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04002740 const Type& type = p.type();
John Stiles45990502021-02-16 10:55:27 -05002741 if (p.getOperator().kind() == Token::Kind::TK_MINUS) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002742 SpvId result = this->nextId(&type);
Ethan Nicholas30d30222020-09-11 12:27:26 -04002743 SpvId typeId = this->getType(type);
Ethan Nicholas444ccc62020-10-09 10:16:22 -04002744 SpvId expr = this->writeExpression(*p.operand(), out);
Ethan Nicholas30d30222020-09-11 12:27:26 -04002745 if (is_float(fContext, type)) {
ethannicholasb3058bd2016-07-01 08:22:01 -07002746 this->writeInstruction(SpvOpFNegate, typeId, result, expr, out);
Ethan Nicholas30d30222020-09-11 12:27:26 -04002747 } else if (is_signed(fContext, type)) {
ethannicholasb3058bd2016-07-01 08:22:01 -07002748 this->writeInstruction(SpvOpSNegate, typeId, result, expr, out);
2749 } else {
John Stileseada7bc2021-02-02 16:29:32 -05002750 SkDEBUGFAILF("unsupported prefix expression %s", p.description().c_str());
Brian Salomon23356442018-11-30 15:33:19 -05002751 }
ethannicholasb3058bd2016-07-01 08:22:01 -07002752 return result;
2753 }
John Stiles45990502021-02-16 10:55:27 -05002754 switch (p.getOperator().kind()) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002755 case Token::Kind::TK_PLUS:
Ethan Nicholas444ccc62020-10-09 10:16:22 -04002756 return this->writeExpression(*p.operand(), out);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002757 case Token::Kind::TK_PLUSPLUS: {
Ethan Nicholas444ccc62020-10-09 10:16:22 -04002758 std::unique_ptr<LValue> lv = this->getLValue(*p.operand(), out);
Ethan Nicholas30d30222020-09-11 12:27:26 -04002759 SpvId one = this->writeExpression(*create_literal_1(fContext, type), out);
2760 SpvId result = this->writeBinaryOperation(type, type, lv->load(out), one,
Greg Daniel64773e62016-11-22 09:44:03 -05002761 SpvOpFAdd, SpvOpIAdd, SpvOpIAdd, SpvOpUndef,
ethannicholasb3058bd2016-07-01 08:22:01 -07002762 out);
2763 lv->store(result, out);
2764 return result;
2765 }
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002766 case Token::Kind::TK_MINUSMINUS: {
Ethan Nicholas444ccc62020-10-09 10:16:22 -04002767 std::unique_ptr<LValue> lv = this->getLValue(*p.operand(), out);
Ethan Nicholas30d30222020-09-11 12:27:26 -04002768 SpvId one = this->writeExpression(*create_literal_1(fContext, type), out);
2769 SpvId result = this->writeBinaryOperation(type, type, lv->load(out), one, SpvOpFSub,
2770 SpvOpISub, SpvOpISub, SpvOpUndef, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002771 lv->store(result, out);
2772 return result;
2773 }
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002774 case Token::Kind::TK_LOGICALNOT: {
John Stiles4a7dc462020-11-25 11:08:08 -05002775 SkASSERT(p.operand()->type().isBoolean());
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002776 SpvId result = this->nextId(nullptr);
Ethan Nicholas444ccc62020-10-09 10:16:22 -04002777 this->writeInstruction(SpvOpLogicalNot, this->getType(type), result,
2778 this->writeExpression(*p.operand(), out), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002779 return result;
2780 }
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002781 case Token::Kind::TK_BITWISENOT: {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002782 SpvId result = this->nextId(nullptr);
Ethan Nicholas444ccc62020-10-09 10:16:22 -04002783 this->writeInstruction(SpvOpNot, this->getType(type), result,
2784 this->writeExpression(*p.operand(), out), out);
ethannicholas5961bc92016-10-12 06:39:56 -07002785 return result;
2786 }
ethannicholasb3058bd2016-07-01 08:22:01 -07002787 default:
John Stileseada7bc2021-02-02 16:29:32 -05002788 SkDEBUGFAILF("unsupported prefix expression: %s", p.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -05002789 return -1;
ethannicholasb3058bd2016-07-01 08:22:01 -07002790 }
2791}
2792
Ethan Nicholas0df1b042017-03-31 13:56:23 -04002793SpvId SPIRVCodeGenerator::writePostfixExpression(const PostfixExpression& p, OutputStream& out) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04002794 const Type& type = p.type();
Ethan Nicholas444ccc62020-10-09 10:16:22 -04002795 std::unique_ptr<LValue> lv = this->getLValue(*p.operand(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002796 SpvId result = lv->load(out);
Ethan Nicholas30d30222020-09-11 12:27:26 -04002797 SpvId one = this->writeExpression(*create_literal_1(fContext, type), out);
John Stiles45990502021-02-16 10:55:27 -05002798 switch (p.getOperator().kind()) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002799 case Token::Kind::TK_PLUSPLUS: {
Ethan Nicholas30d30222020-09-11 12:27:26 -04002800 SpvId temp = this->writeBinaryOperation(type, type, result, one, SpvOpFAdd,
ethannicholasb3058bd2016-07-01 08:22:01 -07002801 SpvOpIAdd, SpvOpIAdd, SpvOpUndef, out);
2802 lv->store(temp, out);
2803 return result;
2804 }
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002805 case Token::Kind::TK_MINUSMINUS: {
Ethan Nicholas30d30222020-09-11 12:27:26 -04002806 SpvId temp = this->writeBinaryOperation(type, type, result, one, SpvOpFSub,
ethannicholasb3058bd2016-07-01 08:22:01 -07002807 SpvOpISub, SpvOpISub, SpvOpUndef, out);
2808 lv->store(temp, out);
2809 return result;
2810 }
2811 default:
John Stileseada7bc2021-02-02 16:29:32 -05002812 SkDEBUGFAILF("unsupported postfix expression %s", p.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -05002813 return -1;
ethannicholasb3058bd2016-07-01 08:22:01 -07002814 }
2815}
2816
ethannicholasf789b382016-08-03 12:43:36 -07002817SpvId SPIRVCodeGenerator::writeBoolLiteral(const BoolLiteral& b) {
Ethan Nicholas59d660c2020-09-28 09:18:15 -04002818 if (b.value()) {
ethannicholasb3058bd2016-07-01 08:22:01 -07002819 if (fBoolTrue == 0) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002820 fBoolTrue = this->nextId(nullptr);
Ethan Nicholas30d30222020-09-11 12:27:26 -04002821 this->writeInstruction(SpvOpConstantTrue, this->getType(b.type()), fBoolTrue,
ethannicholasb3058bd2016-07-01 08:22:01 -07002822 fConstantBuffer);
2823 }
2824 return fBoolTrue;
2825 } else {
2826 if (fBoolFalse == 0) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002827 fBoolFalse = this->nextId(nullptr);
Ethan Nicholas30d30222020-09-11 12:27:26 -04002828 this->writeInstruction(SpvOpConstantFalse, this->getType(b.type()), fBoolFalse,
ethannicholasb3058bd2016-07-01 08:22:01 -07002829 fConstantBuffer);
2830 }
2831 return fBoolFalse;
2832 }
2833}
2834
ethannicholasf789b382016-08-03 12:43:36 -07002835SpvId SPIRVCodeGenerator::writeIntLiteral(const IntLiteral& i) {
John Stilesbdc3d3c2021-01-06 18:41:40 -05002836 SPIRVNumberConstant key{i.value(), i.type().numberKind()};
John Stilesacb091f2021-01-06 11:57:58 -05002837 auto [iter, newlyCreated] = fNumberConstants.insert({key, (SpvId)-1});
2838 if (newlyCreated) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002839 SpvId result = this->nextId(nullptr);
John Stilesacb091f2021-01-06 11:57:58 -05002840 this->writeInstruction(SpvOpConstant, this->getType(i.type()), result, (SpvId) i.value(),
Ethan Nicholascc5d3e02019-04-19 09:50:56 -04002841 fConstantBuffer);
John Stilesacb091f2021-01-06 11:57:58 -05002842 iter->second = result;
Ethan Nicholascc5d3e02019-04-19 09:50:56 -04002843 }
John Stilesacb091f2021-01-06 11:57:58 -05002844 return iter->second;
ethannicholasb3058bd2016-07-01 08:22:01 -07002845}
2846
ethannicholasf789b382016-08-03 12:43:36 -07002847SpvId SPIRVCodeGenerator::writeFloatLiteral(const FloatLiteral& f) {
John Stilesbdc3d3c2021-01-06 18:41:40 -05002848 // Convert the float literal into its bit-representation.
2849 float value = f.value();
2850 uint32_t valueBits;
2851 static_assert(sizeof(valueBits) == sizeof(value));
2852 memcpy(&valueBits, &value, sizeof(value));
2853
2854 SPIRVNumberConstant key{valueBits, f.type().numberKind()};
John Stilesacb091f2021-01-06 11:57:58 -05002855 auto [iter, newlyCreated] = fNumberConstants.insert({key, (SpvId)-1});
2856 if (newlyCreated) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002857 SpvId result = this->nextId(nullptr);
John Stilesbdc3d3c2021-01-06 18:41:40 -05002858 this->writeInstruction(SpvOpConstant, this->getType(f.type()), result, (SpvId) valueBits,
John Stiles8c578662020-06-01 15:32:47 +00002859 fConstantBuffer);
John Stilesacb091f2021-01-06 11:57:58 -05002860 iter->second = result;
John Stiles8c578662020-06-01 15:32:47 +00002861 }
John Stilesacb091f2021-01-06 11:57:58 -05002862 return iter->second;
ethannicholasb3058bd2016-07-01 08:22:01 -07002863}
2864
Ethan Nicholas0df1b042017-03-31 13:56:23 -04002865SpvId SPIRVCodeGenerator::writeFunctionStart(const FunctionDeclaration& f, OutputStream& out) {
ethannicholasd598f792016-07-25 10:08:54 -07002866 SpvId result = fFunctionMap[&f];
John Stilesb5db4822021-01-21 13:04:40 -05002867 SpvId returnTypeId = this->getType(f.returnType());
2868 SpvId functionTypeId = this->getFunctionType(f);
2869 this->writeInstruction(SpvOpFunction, returnTypeId, result,
2870 SpvFunctionControlMaskNone, functionTypeId, out);
John Stilesf9e85512021-03-22 12:05:31 -04002871 String mangledName = f.mangledName();
2872 this->writeInstruction(SpvOpName,
2873 result,
2874 StringFragment(mangledName.c_str(), mangledName.size()),
2875 fNameBuffer);
2876 for (const Variable* parameter : f.parameters()) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002877 SpvId id = this->nextId(nullptr);
John Stilesf9e85512021-03-22 12:05:31 -04002878 fVariableMap[parameter] = id;
2879 SpvId type = this->getPointerType(parameter->type(), SpvStorageClassFunction);
ethannicholasb3058bd2016-07-01 08:22:01 -07002880 this->writeInstruction(SpvOpFunctionParameter, type, id, out);
2881 }
2882 return result;
2883}
2884
Ethan Nicholas0df1b042017-03-31 13:56:23 -04002885SpvId SPIRVCodeGenerator::writeFunction(const FunctionDefinition& f, OutputStream& out) {
2886 fVariableBuffer.reset();
Ethan Nicholas0a5d0962020-10-14 13:33:18 -04002887 SpvId result = this->writeFunctionStart(f.declaration(), out);
Ethan Nicholas7fb39362020-12-16 15:25:19 -05002888 fCurrentBlock = 0;
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002889 this->writeLabel(this->nextId(nullptr), out);
Ethan Nicholas0df1b042017-03-31 13:56:23 -04002890 StringStream bodyBuffer;
John Stiles0693fb82021-01-22 18:27:52 -05002891 this->writeBlock(f.body()->as<Block>(), bodyBuffer);
Ethan Nicholas0df1b042017-03-31 13:56:23 -04002892 write_stringstream(fVariableBuffer, out);
John Stilese8da4d22021-03-24 09:19:45 -04002893 if (f.declaration().isMain()) {
Ethan Nicholas8eb64d32018-12-21 14:50:42 -05002894 write_stringstream(fGlobalInitializersBuffer, out);
2895 }
Ethan Nicholas0df1b042017-03-31 13:56:23 -04002896 write_stringstream(bodyBuffer, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002897 if (fCurrentBlock) {
John Stiles2558c462021-03-16 17:49:20 -04002898 if (f.declaration().returnType().isVoid()) {
Ethan Nicholas70a44b22017-11-30 09:09:16 -05002899 this->writeInstruction(SpvOpReturn, out);
2900 } else {
2901 this->writeInstruction(SpvOpUnreachable, out);
2902 }
ethannicholasb3058bd2016-07-01 08:22:01 -07002903 }
2904 this->writeInstruction(SpvOpFunctionEnd, out);
2905 return result;
2906}
2907
2908void SPIRVCodeGenerator::writeLayout(const Layout& layout, SpvId target) {
2909 if (layout.fLocation >= 0) {
Greg Daniel64773e62016-11-22 09:44:03 -05002910 this->writeInstruction(SpvOpDecorate, target, SpvDecorationLocation, layout.fLocation,
ethannicholasb3058bd2016-07-01 08:22:01 -07002911 fDecorationBuffer);
2912 }
2913 if (layout.fBinding >= 0) {
Greg Daniel64773e62016-11-22 09:44:03 -05002914 this->writeInstruction(SpvOpDecorate, target, SpvDecorationBinding, layout.fBinding,
ethannicholasb3058bd2016-07-01 08:22:01 -07002915 fDecorationBuffer);
2916 }
2917 if (layout.fIndex >= 0) {
Greg Daniel64773e62016-11-22 09:44:03 -05002918 this->writeInstruction(SpvOpDecorate, target, SpvDecorationIndex, layout.fIndex,
ethannicholasb3058bd2016-07-01 08:22:01 -07002919 fDecorationBuffer);
2920 }
2921 if (layout.fSet >= 0) {
Greg Daniel64773e62016-11-22 09:44:03 -05002922 this->writeInstruction(SpvOpDecorate, target, SpvDecorationDescriptorSet, layout.fSet,
ethannicholasb3058bd2016-07-01 08:22:01 -07002923 fDecorationBuffer);
2924 }
Greg Daniel64773e62016-11-22 09:44:03 -05002925 if (layout.fInputAttachmentIndex >= 0) {
2926 this->writeInstruction(SpvOpDecorate, target, SpvDecorationInputAttachmentIndex,
2927 layout.fInputAttachmentIndex, fDecorationBuffer);
Ethan Nicholasbe1099f2018-01-11 16:09:05 -05002928 fCapabilities |= (((uint64_t) 1) << SpvCapabilityInputAttachment);
Greg Daniel64773e62016-11-22 09:44:03 -05002929 }
Ethan Nicholasbb155e22017-07-24 10:05:09 -04002930 if (layout.fBuiltin >= 0 && layout.fBuiltin != SK_FRAGCOLOR_BUILTIN &&
Greg Daniele6ab9982018-08-22 13:56:32 +00002931 layout.fBuiltin != SK_IN_BUILTIN && layout.fBuiltin != SK_OUT_BUILTIN) {
Greg Daniel64773e62016-11-22 09:44:03 -05002932 this->writeInstruction(SpvOpDecorate, target, SpvDecorationBuiltIn, layout.fBuiltin,
ethannicholasb3058bd2016-07-01 08:22:01 -07002933 fDecorationBuffer);
2934 }
2935}
2936
2937void SPIRVCodeGenerator::writeLayout(const Layout& layout, SpvId target, int member) {
2938 if (layout.fLocation >= 0) {
Greg Daniel64773e62016-11-22 09:44:03 -05002939 this->writeInstruction(SpvOpMemberDecorate, target, member, SpvDecorationLocation,
ethannicholasb3058bd2016-07-01 08:22:01 -07002940 layout.fLocation, fDecorationBuffer);
2941 }
2942 if (layout.fBinding >= 0) {
Greg Daniel64773e62016-11-22 09:44:03 -05002943 this->writeInstruction(SpvOpMemberDecorate, target, member, SpvDecorationBinding,
ethannicholasb3058bd2016-07-01 08:22:01 -07002944 layout.fBinding, fDecorationBuffer);
2945 }
2946 if (layout.fIndex >= 0) {
Greg Daniel64773e62016-11-22 09:44:03 -05002947 this->writeInstruction(SpvOpMemberDecorate, target, member, SpvDecorationIndex,
ethannicholasb3058bd2016-07-01 08:22:01 -07002948 layout.fIndex, fDecorationBuffer);
2949 }
2950 if (layout.fSet >= 0) {
Greg Daniel64773e62016-11-22 09:44:03 -05002951 this->writeInstruction(SpvOpMemberDecorate, target, member, SpvDecorationDescriptorSet,
ethannicholasb3058bd2016-07-01 08:22:01 -07002952 layout.fSet, fDecorationBuffer);
2953 }
Greg Daniel64773e62016-11-22 09:44:03 -05002954 if (layout.fInputAttachmentIndex >= 0) {
2955 this->writeInstruction(SpvOpDecorate, target, member, SpvDecorationInputAttachmentIndex,
2956 layout.fInputAttachmentIndex, fDecorationBuffer);
2957 }
ethannicholasb3058bd2016-07-01 08:22:01 -07002958 if (layout.fBuiltin >= 0) {
Greg Daniel64773e62016-11-22 09:44:03 -05002959 this->writeInstruction(SpvOpMemberDecorate, target, member, SpvDecorationBuiltIn,
ethannicholasb3058bd2016-07-01 08:22:01 -07002960 layout.fBuiltin, fDecorationBuffer);
2961 }
2962}
2963
Brian Osman2a4c0fb2021-01-22 13:41:40 -05002964MemoryLayout SPIRVCodeGenerator::memoryLayoutForVariable(const Variable& v) const {
Brian Osman2a4c0fb2021-01-22 13:41:40 -05002965 bool pushConstant = ((v.modifiers().fLayout.fFlags & Layout::kPushConstant_Flag) != 0);
Brian Osman58ee8982021-02-18 15:39:38 -05002966 return pushConstant ? MemoryLayout(MemoryLayout::k430_Standard) : fDefaultLayout;
Brian Osman2a4c0fb2021-01-22 13:41:40 -05002967}
2968
Ethan Nicholas81d15112018-07-13 12:48:50 -04002969static void update_sk_in_count(const Modifiers& m, int* outSkInCount) {
2970 switch (m.fLayout.fPrimitive) {
2971 case Layout::kPoints_Primitive:
2972 *outSkInCount = 1;
2973 break;
2974 case Layout::kLines_Primitive:
2975 *outSkInCount = 2;
2976 break;
2977 case Layout::kLinesAdjacency_Primitive:
2978 *outSkInCount = 4;
2979 break;
2980 case Layout::kTriangles_Primitive:
2981 *outSkInCount = 3;
2982 break;
2983 case Layout::kTrianglesAdjacency_Primitive:
2984 *outSkInCount = 6;
2985 break;
2986 default:
2987 return;
2988 }
2989}
2990
Stephen White88574972020-06-23 19:09:29 -04002991SpvId SPIRVCodeGenerator::writeInterfaceBlock(const InterfaceBlock& intf, bool appendRTHeight) {
Brian Osman2a4c0fb2021-01-22 13:41:40 -05002992 MemoryLayout memoryLayout = this->memoryLayoutForVariable(intf.variable());
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002993 SpvId result = this->nextId(nullptr);
John Stilesad2d4942020-12-11 16:55:58 -05002994 std::unique_ptr<Type> rtHeightStructType;
Ethan Nicholaseaf47882020-10-15 10:10:08 -04002995 const Type* type = &intf.variable().type();
John Stiles21f5f452020-11-30 09:57:59 -05002996 if (!MemoryLayout::LayoutIsSupported(*type)) {
John Stiles0023c0c2020-11-16 13:32:18 -05002997 fErrors.error(type->fOffset, "type '" + type->name() + "' is not permitted here");
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002998 return this->nextId(nullptr);
John Stiles0023c0c2020-11-16 13:32:18 -05002999 }
John Stiles9485b552021-01-27 11:47:00 -05003000 SpvStorageClass_ storageClass = get_storage_class(intf.variable(), SpvStorageClassFunction);
Stephen White88574972020-06-23 19:09:29 -04003001 if (fProgram.fInputs.fRTHeight && appendRTHeight) {
Greg Daniele6ab9982018-08-22 13:56:32 +00003002 SkASSERT(fRTHeightStructId == (SpvId) -1);
3003 SkASSERT(fRTHeightFieldIndex == (SpvId) -1);
Ethan Nicholas941e7e22016-12-12 15:33:30 -05003004 std::vector<Type::Field> fields = type->fields();
Greg Daniele6ab9982018-08-22 13:56:32 +00003005 fRTHeightStructId = result;
3006 fRTHeightFieldIndex = fields.size();
Jim Van Verthf3ec9832020-10-21 16:09:57 -04003007 fRTHeightStorageClass = storageClass;
John Stilesad2d4942020-12-11 16:55:58 -05003008 fields.emplace_back(Modifiers(), StringFragment(SKSL_RTHEIGHT_NAME),
John Stiles54e7c052021-01-11 14:22:36 -05003009 fContext.fTypes.fFloat.get());
John Stilesad2d4942020-12-11 16:55:58 -05003010 rtHeightStructType = Type::MakeStructType(type->fOffset, type->name(), std::move(fields));
3011 type = rtHeightStructType.get();
Ethan Nicholas941e7e22016-12-12 15:33:30 -05003012 }
Ethan Nicholas5226b772018-05-03 16:20:41 -04003013 SpvId typeId;
John Stiles9485b552021-01-27 11:47:00 -05003014 const Modifiers& intfModifiers = intf.variable().modifiers();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04003015 if (intfModifiers.fLayout.fBuiltin == SK_IN_BUILTIN) {
Brian Osman133724c2020-10-28 14:14:39 -04003016 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04003017 if (e->is<ModifiersDeclaration>()) {
Ethan Nicholas077050b2020-10-13 10:30:20 -04003018 const Modifiers& m = e->as<ModifiersDeclaration>().modifiers();
Ethan Nicholas81d15112018-07-13 12:48:50 -04003019 update_sk_in_count(m, &fSkInCount);
Ethan Nicholas5226b772018-05-03 16:20:41 -04003020 }
3021 }
John Stilesad2d4942020-12-11 16:55:58 -05003022 typeId = this->getType(
3023 *Type::MakeArrayType("sk_in", intf.variable().type().componentType(), fSkInCount),
3024 memoryLayout);
Ethan Nicholas5226b772018-05-03 16:20:41 -04003025 } else {
3026 typeId = this->getType(*type, memoryLayout);
3027 }
Brian Osman58ee8982021-02-18 15:39:38 -05003028 if (intfModifiers.fLayout.fBuiltin == -1) {
Ethan Nicholas6ac8d362019-01-22 21:43:55 +00003029 this->writeInstruction(SpvOpDecorate, typeId, SpvDecorationBlock, fDecorationBuffer);
Ethan Nicholas0dd30d92017-05-01 16:57:07 -04003030 }
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04003031 SpvId ptrType = this->nextId(nullptr);
Ethan Nicholas941e7e22016-12-12 15:33:30 -05003032 this->writeInstruction(SpvOpTypePointer, ptrType, storageClass, typeId, fConstantBuffer);
ethannicholasb3058bd2016-07-01 08:22:01 -07003033 this->writeInstruction(SpvOpVariable, ptrType, result, storageClass, fConstantBuffer);
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04003034 Layout layout = intfModifiers.fLayout;
3035 if (intfModifiers.fFlags & Modifiers::kUniform_Flag && layout.fSet == -1) {
Ethan Nicholas8d2ba442018-03-16 16:40:36 -04003036 layout.fSet = 0;
3037 }
3038 this->writeLayout(layout, result);
Ethan Nicholaseaf47882020-10-15 10:10:08 -04003039 fVariableMap[&intf.variable()] = result;
ethannicholasb3058bd2016-07-01 08:22:01 -07003040 return result;
3041}
3042
John Stiles9485b552021-01-27 11:47:00 -05003043static bool is_dead(const Variable& var, const ProgramUsage* usage) {
Brian Osman010ce6a2020-10-19 16:34:10 -04003044 ProgramUsage::VariableCounts counts = usage->get(var);
3045 if (counts.fRead || counts.fWrite) {
Chris Dalton2284aab2019-11-15 11:02:24 -07003046 return false;
3047 }
Brian Osmand1f3b972021-03-22 17:03:42 -04003048 // It's not entirely clear what the rules are for eliding interface variables. Generally, it
3049 // causes problems to elide them, even when they're dead.
3050 return !(var.modifiers().fFlags &
3051 (Modifiers::kIn_Flag | Modifiers::kOut_Flag | Modifiers::kUniform_Flag));
Chris Dalton2284aab2019-11-15 11:02:24 -07003052}
3053
John Stilesdbd4e6f2021-02-16 13:29:15 -05003054void SPIRVCodeGenerator::writeGlobalVar(ProgramKind kind, const VarDeclaration& varDecl) {
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04003055 const Variable& var = varDecl.var();
John Stiles0ca2f592021-01-27 10:58:10 -05003056 // 9999 is a sentinel value used in our built-in modules that causes us to ignore these
3057 // declarations, beyond adding them to the symbol table.
3058 constexpr int kBuiltinIgnore = 9999;
3059 if (var.modifiers().fLayout.fBuiltin == kBuiltinIgnore) {
Brian Osmanc0213602020-10-06 14:43:32 -04003060 return;
3061 }
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04003062 if (var.modifiers().fLayout.fBuiltin == SK_FRAGCOLOR_BUILTIN &&
John Stilesdbd4e6f2021-02-16 13:29:15 -05003063 kind != ProgramKind::kFragment) {
John Stiles270cec22021-02-17 12:59:36 -05003064 SkASSERT(!fProgram.fConfig->fSettings.fFragColorIsInOut);
Brian Osmanc0213602020-10-06 14:43:32 -04003065 return;
3066 }
Brian Osman010ce6a2020-10-19 16:34:10 -04003067 if (is_dead(var, fProgram.fUsage.get())) {
Brian Osmanc0213602020-10-06 14:43:32 -04003068 return;
3069 }
John Stiles0de76f72021-01-29 09:19:39 -05003070 SpvStorageClass_ storageClass = get_storage_class(var, SpvStorageClassPrivate);
John Stilese40d1662021-01-29 10:08:50 -05003071 if (storageClass == SpvStorageClassUniform) {
3072 // Top-level uniforms are emitted in writeUniformBuffer.
3073 fTopLevelUniforms.push_back(&varDecl);
3074 return;
3075 }
3076 const Type& type = var.type();
John Stilesd8fc95d2021-01-26 16:22:53 -05003077 Layout layout = var.modifiers().fLayout;
John Stilese40d1662021-01-29 10:08:50 -05003078 if (layout.fSet < 0 && storageClass == SpvStorageClassUniformConstant) {
John Stiles270cec22021-02-17 12:59:36 -05003079 layout.fSet = fProgram.fConfig->fSettings.fDefaultUniformSet;
Brian Osmanc0213602020-10-06 14:43:32 -04003080 }
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04003081 SpvId id = this->nextId(&type);
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04003082 fVariableMap[&var] = id;
Brian Osmanc0213602020-10-06 14:43:32 -04003083 SpvId typeId;
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04003084 if (var.modifiers().fLayout.fBuiltin == SK_IN_BUILTIN) {
Brian Osmanc0213602020-10-06 14:43:32 -04003085 typeId = this->getPointerType(
John Stilesad2d4942020-12-11 16:55:58 -05003086 *Type::MakeArrayType("sk_in", type.componentType(), fSkInCount),
Brian Osmanc0213602020-10-06 14:43:32 -04003087 storageClass);
3088 } else {
3089 typeId = this->getPointerType(type, storageClass);
3090 }
3091 this->writeInstruction(SpvOpVariable, typeId, id, storageClass, fConstantBuffer);
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04003092 this->writeInstruction(SpvOpName, id, var.name(), fNameBuffer);
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04003093 if (varDecl.value()) {
Brian Osmanc0213602020-10-06 14:43:32 -04003094 SkASSERT(!fCurrentBlock);
3095 fCurrentBlock = -1;
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04003096 SpvId value = this->writeExpression(*varDecl.value(), fGlobalInitializersBuffer);
Brian Osmanc0213602020-10-06 14:43:32 -04003097 this->writeInstruction(SpvOpStore, id, value, fGlobalInitializersBuffer);
3098 fCurrentBlock = 0;
3099 }
John Stilesd8fc95d2021-01-26 16:22:53 -05003100 this->writeLayout(layout, id);
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04003101 if (var.modifiers().fFlags & Modifiers::kFlat_Flag) {
Brian Osmanc0213602020-10-06 14:43:32 -04003102 this->writeInstruction(SpvOpDecorate, id, SpvDecorationFlat, fDecorationBuffer);
3103 }
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04003104 if (var.modifiers().fFlags & Modifiers::kNoPerspective_Flag) {
Brian Osmanc0213602020-10-06 14:43:32 -04003105 this->writeInstruction(SpvOpDecorate, id, SpvDecorationNoPerspective,
3106 fDecorationBuffer);
ethannicholasb3058bd2016-07-01 08:22:01 -07003107 }
3108}
3109
Brian Osmanc0213602020-10-06 14:43:32 -04003110void SPIRVCodeGenerator::writeVarDeclaration(const VarDeclaration& varDecl, OutputStream& out) {
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04003111 const Variable& var = varDecl.var();
Ethan Nicholas7f015882021-03-23 14:16:52 -04003112 SpvId id = this->nextId(&var.type());
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04003113 fVariableMap[&var] = id;
3114 SpvId type = this->getPointerType(var.type(), SpvStorageClassFunction);
Brian Osmanc0213602020-10-06 14:43:32 -04003115 this->writeInstruction(SpvOpVariable, type, id, SpvStorageClassFunction, fVariableBuffer);
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04003116 this->writeInstruction(SpvOpName, id, var.name(), fNameBuffer);
3117 if (varDecl.value()) {
3118 SpvId value = this->writeExpression(*varDecl.value(), out);
Brian Osmanc0213602020-10-06 14:43:32 -04003119 this->writeInstruction(SpvOpStore, id, value, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003120 }
3121}
3122
Ethan Nicholas0df1b042017-03-31 13:56:23 -04003123void SPIRVCodeGenerator::writeStatement(const Statement& s, OutputStream& out) {
Ethan Nicholase6592142020-09-08 10:22:09 -04003124 switch (s.kind()) {
John Stiles98c1f822020-09-09 14:18:53 -04003125 case Statement::Kind::kInlineMarker:
Ethan Nicholase6592142020-09-08 10:22:09 -04003126 case Statement::Kind::kNop:
Ethan Nicholascb670962017-04-20 19:31:52 -04003127 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04003128 case Statement::Kind::kBlock:
John Stiles0693fb82021-01-22 18:27:52 -05003129 this->writeBlock(s.as<Block>(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003130 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04003131 case Statement::Kind::kExpression:
Ethan Nicholasd503a5a2020-09-30 09:29:55 -04003132 this->writeExpression(*s.as<ExpressionStatement>().expression(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003133 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04003134 case Statement::Kind::kReturn:
John Stiles26f98502020-08-18 09:30:51 -04003135 this->writeReturnStatement(s.as<ReturnStatement>(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003136 break;
Brian Osmanc0213602020-10-06 14:43:32 -04003137 case Statement::Kind::kVarDeclaration:
3138 this->writeVarDeclaration(s.as<VarDeclaration>(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003139 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04003140 case Statement::Kind::kIf:
John Stiles26f98502020-08-18 09:30:51 -04003141 this->writeIfStatement(s.as<IfStatement>(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003142 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04003143 case Statement::Kind::kFor:
John Stiles26f98502020-08-18 09:30:51 -04003144 this->writeForStatement(s.as<ForStatement>(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003145 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04003146 case Statement::Kind::kDo:
John Stiles26f98502020-08-18 09:30:51 -04003147 this->writeDoStatement(s.as<DoStatement>(), out);
Ethan Nicholasfd146aa2017-01-13 16:40:35 -05003148 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04003149 case Statement::Kind::kSwitch:
John Stiles26f98502020-08-18 09:30:51 -04003150 this->writeSwitchStatement(s.as<SwitchStatement>(), out);
Ethan Nicholase92b1b12017-11-13 16:13:21 -05003151 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04003152 case Statement::Kind::kBreak:
ethannicholasb3058bd2016-07-01 08:22:01 -07003153 this->writeInstruction(SpvOpBranch, fBreakTarget.top(), out);
3154 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04003155 case Statement::Kind::kContinue:
ethannicholasb3058bd2016-07-01 08:22:01 -07003156 this->writeInstruction(SpvOpBranch, fContinueTarget.top(), out);
3157 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04003158 case Statement::Kind::kDiscard:
ethannicholasb3058bd2016-07-01 08:22:01 -07003159 this->writeInstruction(SpvOpKill, out);
3160 break;
3161 default:
John Stileseada7bc2021-02-02 16:29:32 -05003162 SkDEBUGFAILF("unsupported statement: %s", s.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -05003163 break;
ethannicholasb3058bd2016-07-01 08:22:01 -07003164 }
3165}
3166
Ethan Nicholas0df1b042017-03-31 13:56:23 -04003167void SPIRVCodeGenerator::writeBlock(const Block& b, OutputStream& out) {
Ethan Nicholas7bd60432020-09-25 14:31:59 -04003168 for (const std::unique_ptr<Statement>& stmt : b.children()) {
3169 this->writeStatement(*stmt, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003170 }
3171}
3172
Ethan Nicholas0df1b042017-03-31 13:56:23 -04003173void SPIRVCodeGenerator::writeIfStatement(const IfStatement& stmt, OutputStream& out) {
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04003174 SpvId test = this->writeExpression(*stmt.test(), out);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04003175 SpvId ifTrue = this->nextId(nullptr);
3176 SpvId ifFalse = this->nextId(nullptr);
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04003177 if (stmt.ifFalse()) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04003178 SpvId end = this->nextId(nullptr);
ethannicholasb3058bd2016-07-01 08:22:01 -07003179 this->writeInstruction(SpvOpSelectionMerge, end, SpvSelectionControlMaskNone, out);
3180 this->writeInstruction(SpvOpBranchConditional, test, ifTrue, ifFalse, out);
3181 this->writeLabel(ifTrue, out);
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04003182 this->writeStatement(*stmt.ifTrue(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003183 if (fCurrentBlock) {
3184 this->writeInstruction(SpvOpBranch, end, out);
3185 }
3186 this->writeLabel(ifFalse, out);
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04003187 this->writeStatement(*stmt.ifFalse(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003188 if (fCurrentBlock) {
3189 this->writeInstruction(SpvOpBranch, end, out);
3190 }
3191 this->writeLabel(end, out);
3192 } else {
3193 this->writeInstruction(SpvOpSelectionMerge, ifFalse, SpvSelectionControlMaskNone, out);
3194 this->writeInstruction(SpvOpBranchConditional, test, ifTrue, ifFalse, out);
3195 this->writeLabel(ifTrue, out);
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04003196 this->writeStatement(*stmt.ifTrue(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003197 if (fCurrentBlock) {
3198 this->writeInstruction(SpvOpBranch, ifFalse, out);
3199 }
3200 this->writeLabel(ifFalse, out);
3201 }
3202}
3203
Ethan Nicholas0df1b042017-03-31 13:56:23 -04003204void SPIRVCodeGenerator::writeForStatement(const ForStatement& f, OutputStream& out) {
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04003205 if (f.initializer()) {
3206 this->writeStatement(*f.initializer(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003207 }
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04003208 SpvId header = this->nextId(nullptr);
3209 SpvId start = this->nextId(nullptr);
3210 SpvId body = this->nextId(nullptr);
3211 SpvId next = this->nextId(nullptr);
ethannicholasb3058bd2016-07-01 08:22:01 -07003212 fContinueTarget.push(next);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04003213 SpvId end = this->nextId(nullptr);
ethannicholasb3058bd2016-07-01 08:22:01 -07003214 fBreakTarget.push(end);
3215 this->writeInstruction(SpvOpBranch, header, out);
3216 this->writeLabel(header, out);
3217 this->writeInstruction(SpvOpLoopMerge, end, next, SpvLoopControlMaskNone, out);
ethannicholasf789b382016-08-03 12:43:36 -07003218 this->writeInstruction(SpvOpBranch, start, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003219 this->writeLabel(start, out);
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04003220 if (f.test()) {
3221 SpvId test = this->writeExpression(*f.test(), out);
ethannicholas22f939e2016-10-13 13:25:34 -07003222 this->writeInstruction(SpvOpBranchConditional, test, body, end, out);
Ethan Nicholas7fb39362020-12-16 15:25:19 -05003223 } else {
3224 this->writeInstruction(SpvOpBranch, body, out);
ethannicholas22f939e2016-10-13 13:25:34 -07003225 }
ethannicholasb3058bd2016-07-01 08:22:01 -07003226 this->writeLabel(body, out);
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04003227 this->writeStatement(*f.statement(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003228 if (fCurrentBlock) {
3229 this->writeInstruction(SpvOpBranch, next, out);
3230 }
3231 this->writeLabel(next, out);
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04003232 if (f.next()) {
3233 this->writeExpression(*f.next(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003234 }
3235 this->writeInstruction(SpvOpBranch, header, out);
3236 this->writeLabel(end, out);
3237 fBreakTarget.pop();
3238 fContinueTarget.pop();
3239}
3240
Ethan Nicholas0df1b042017-03-31 13:56:23 -04003241void SPIRVCodeGenerator::writeDoStatement(const DoStatement& d, OutputStream& out) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04003242 SpvId header = this->nextId(nullptr);
3243 SpvId start = this->nextId(nullptr);
3244 SpvId next = this->nextId(nullptr);
3245 SpvId continueTarget = this->nextId(nullptr);
Ethan Nicholas0d997662019-04-08 09:46:01 -04003246 fContinueTarget.push(continueTarget);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04003247 SpvId end = this->nextId(nullptr);
Ethan Nicholasfd146aa2017-01-13 16:40:35 -05003248 fBreakTarget.push(end);
3249 this->writeInstruction(SpvOpBranch, header, out);
3250 this->writeLabel(header, out);
Ethan Nicholas0d997662019-04-08 09:46:01 -04003251 this->writeInstruction(SpvOpLoopMerge, end, continueTarget, SpvLoopControlMaskNone, out);
Ethan Nicholasfd146aa2017-01-13 16:40:35 -05003252 this->writeInstruction(SpvOpBranch, start, out);
3253 this->writeLabel(start, out);
Ethan Nicholas1fd61162020-09-28 13:14:19 -04003254 this->writeStatement(*d.statement(), out);
Ethan Nicholasfd146aa2017-01-13 16:40:35 -05003255 if (fCurrentBlock) {
3256 this->writeInstruction(SpvOpBranch, next, out);
3257 }
3258 this->writeLabel(next, out);
John Stiles68072a42021-04-16 17:25:55 -04003259 this->writeInstruction(SpvOpBranch, continueTarget, out);
Ethan Nicholas0d997662019-04-08 09:46:01 -04003260 this->writeLabel(continueTarget, out);
John Stiles68072a42021-04-16 17:25:55 -04003261 SpvId test = this->writeExpression(*d.test(), out);
3262 this->writeInstruction(SpvOpBranchConditional, test, header, end, out);
Ethan Nicholasfd146aa2017-01-13 16:40:35 -05003263 this->writeLabel(end, out);
3264 fBreakTarget.pop();
3265 fContinueTarget.pop();
3266}
3267
Ethan Nicholase92b1b12017-11-13 16:13:21 -05003268void SPIRVCodeGenerator::writeSwitchStatement(const SwitchStatement& s, OutputStream& out) {
Ethan Nicholas01b05e52020-10-22 15:53:41 -04003269 SpvId value = this->writeExpression(*s.value(), out);
Ethan Nicholase92b1b12017-11-13 16:13:21 -05003270 std::vector<SpvId> labels;
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04003271 SpvId end = this->nextId(nullptr);
Ethan Nicholase92b1b12017-11-13 16:13:21 -05003272 SpvId defaultLabel = end;
3273 fBreakTarget.push(end);
3274 int size = 3;
John Stiles2d4f9592020-10-30 10:29:12 -04003275 auto& cases = s.cases();
John Stilesb23a64b2021-03-11 08:27:59 -05003276 for (const std::unique_ptr<Statement>& stmt : cases) {
3277 const SwitchCase& c = stmt->as<SwitchCase>();
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04003278 SpvId label = this->nextId(nullptr);
Ethan Nicholase92b1b12017-11-13 16:13:21 -05003279 labels.push_back(label);
John Stilesb23a64b2021-03-11 08:27:59 -05003280 if (c.value()) {
Ethan Nicholase92b1b12017-11-13 16:13:21 -05003281 size += 2;
3282 } else {
3283 defaultLabel = label;
3284 }
3285 }
3286 labels.push_back(end);
3287 this->writeInstruction(SpvOpSelectionMerge, end, SpvSelectionControlMaskNone, out);
3288 this->writeOpCode(SpvOpSwitch, size, out);
3289 this->writeWord(value, out);
3290 this->writeWord(defaultLabel, out);
John Stiles2d4f9592020-10-30 10:29:12 -04003291 for (size_t i = 0; i < cases.size(); ++i) {
John Stilesb23a64b2021-03-11 08:27:59 -05003292 const SwitchCase& c = cases[i]->as<SwitchCase>();
3293 if (!c.value()) {
Ethan Nicholase92b1b12017-11-13 16:13:21 -05003294 continue;
3295 }
John Stilesb23a64b2021-03-11 08:27:59 -05003296 this->writeWord(c.value()->as<IntLiteral>().value(), out);
Ethan Nicholase92b1b12017-11-13 16:13:21 -05003297 this->writeWord(labels[i], out);
3298 }
John Stiles2d4f9592020-10-30 10:29:12 -04003299 for (size_t i = 0; i < cases.size(); ++i) {
John Stilesb23a64b2021-03-11 08:27:59 -05003300 const SwitchCase& c = cases[i]->as<SwitchCase>();
Ethan Nicholase92b1b12017-11-13 16:13:21 -05003301 this->writeLabel(labels[i], out);
John Stilesb23a64b2021-03-11 08:27:59 -05003302 this->writeStatement(*c.statement(), out);
Ethan Nicholase92b1b12017-11-13 16:13:21 -05003303 if (fCurrentBlock) {
3304 this->writeInstruction(SpvOpBranch, labels[i + 1], out);
3305 }
3306 }
3307 this->writeLabel(end, out);
3308 fBreakTarget.pop();
3309}
3310
Ethan Nicholas0df1b042017-03-31 13:56:23 -04003311void SPIRVCodeGenerator::writeReturnStatement(const ReturnStatement& r, OutputStream& out) {
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04003312 if (r.expression()) {
3313 this->writeInstruction(SpvOpReturnValue, this->writeExpression(*r.expression(), out),
ethannicholasb3058bd2016-07-01 08:22:01 -07003314 out);
3315 } else {
3316 this->writeInstruction(SpvOpReturn, out);
3317 }
3318}
3319
Ethan Nicholasbb155e22017-07-24 10:05:09 -04003320void SPIRVCodeGenerator::writeGeometryShaderExecutionMode(SpvId entryPoint, OutputStream& out) {
John Stiles270cec22021-02-17 12:59:36 -05003321 SkASSERT(fProgram.fConfig->fKind == ProgramKind::kGeometry);
Ethan Nicholasbb155e22017-07-24 10:05:09 -04003322 int invocations = 1;
Brian Osman133724c2020-10-28 14:14:39 -04003323 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04003324 if (e->is<ModifiersDeclaration>()) {
Ethan Nicholas077050b2020-10-13 10:30:20 -04003325 const Modifiers& m = e->as<ModifiersDeclaration>().modifiers();
Ethan Nicholasbb155e22017-07-24 10:05:09 -04003326 if (m.fFlags & Modifiers::kIn_Flag) {
3327 if (m.fLayout.fInvocations != -1) {
3328 invocations = m.fLayout.fInvocations;
3329 }
3330 SpvId input;
3331 switch (m.fLayout.fPrimitive) {
3332 case Layout::kPoints_Primitive:
3333 input = SpvExecutionModeInputPoints;
3334 break;
3335 case Layout::kLines_Primitive:
3336 input = SpvExecutionModeInputLines;
3337 break;
3338 case Layout::kLinesAdjacency_Primitive:
3339 input = SpvExecutionModeInputLinesAdjacency;
3340 break;
3341 case Layout::kTriangles_Primitive:
3342 input = SpvExecutionModeTriangles;
3343 break;
3344 case Layout::kTrianglesAdjacency_Primitive:
3345 input = SpvExecutionModeInputTrianglesAdjacency;
3346 break;
3347 default:
3348 input = 0;
3349 break;
3350 }
Ethan Nicholas81d15112018-07-13 12:48:50 -04003351 update_sk_in_count(m, &fSkInCount);
Ethan Nicholasbb155e22017-07-24 10:05:09 -04003352 if (input) {
3353 this->writeInstruction(SpvOpExecutionMode, entryPoint, input, out);
3354 }
3355 } else if (m.fFlags & Modifiers::kOut_Flag) {
3356 SpvId output;
3357 switch (m.fLayout.fPrimitive) {
3358 case Layout::kPoints_Primitive:
3359 output = SpvExecutionModeOutputPoints;
3360 break;
3361 case Layout::kLineStrip_Primitive:
3362 output = SpvExecutionModeOutputLineStrip;
3363 break;
3364 case Layout::kTriangleStrip_Primitive:
3365 output = SpvExecutionModeOutputTriangleStrip;
3366 break;
3367 default:
3368 output = 0;
3369 break;
3370 }
3371 if (output) {
3372 this->writeInstruction(SpvOpExecutionMode, entryPoint, output, out);
3373 }
3374 if (m.fLayout.fMaxVertices != -1) {
3375 this->writeInstruction(SpvOpExecutionMode, entryPoint,
3376 SpvExecutionModeOutputVertices, m.fLayout.fMaxVertices,
3377 out);
3378 }
3379 }
3380 }
3381 }
3382 this->writeInstruction(SpvOpExecutionMode, entryPoint, SpvExecutionModeInvocations,
3383 invocations, out);
3384}
3385
John Stilese40d1662021-01-29 10:08:50 -05003386// Given any function, returns the top-level symbol table (OUTSIDE of the function's scope).
3387static std::shared_ptr<SymbolTable> get_top_level_symbol_table(const FunctionDeclaration& anyFunc) {
3388 return anyFunc.definition()->body()->as<Block>().symbolTable()->fParent;
3389}
3390
John Stiles4d6310a2021-01-26 19:58:22 -05003391SPIRVCodeGenerator::EntrypointAdapter SPIRVCodeGenerator::writeEntrypointAdapter(
3392 const FunctionDeclaration& main) {
3393 // Our goal is to synthesize a tiny helper function which looks like this:
3394 // void _entrypoint() { sk_FragColor = main(); }
3395
3396 // Fish a symbol table out of main().
John Stilese40d1662021-01-29 10:08:50 -05003397 std::shared_ptr<SymbolTable> symbolTable = get_top_level_symbol_table(main);
John Stiles4d6310a2021-01-26 19:58:22 -05003398
3399 // Get `sk_FragColor` as a writable reference.
3400 const Symbol* skFragColorSymbol = (*symbolTable)["sk_FragColor"];
3401 SkASSERT(skFragColorSymbol);
3402 const Variable& skFragColorVar = skFragColorSymbol->as<Variable>();
3403 auto skFragColorRef = std::make_unique<VariableReference>(/*offset=*/-1, &skFragColorVar,
3404 VariableReference::RefKind::kWrite);
3405 // Synthesize a call to the `main()` function.
3406 if (main.returnType() != skFragColorRef->type()) {
3407 fErrors.error(main.fOffset, "SPIR-V does not support returning '" +
3408 main.returnType().description() + "' from main()");
3409 return {};
3410 }
Brian Osman716aeb92021-04-21 13:20:00 -04003411 ExpressionArray args;
3412 if (main.parameters().size() == 1) {
3413 if (main.parameters()[0]->type() != *fContext.fTypes.fFloat2) {
3414 fErrors.error(main.fOffset,
3415 "SPIR-V does not support parameter of type '" +
3416 main.parameters()[0]->type().description() + "' to main()");
3417 return {};
3418 }
3419 auto zero = std::make_unique<FloatLiteral>(
3420 /*offset=*/-1, 0.0f, fContext.fTypes.fFloatLiteral.get());
3421 auto zeros = std::make_unique<ConstructorSplat>(
3422 /*offset=*/-1, *fContext.fTypes.fFloat2, std::move(zero));
3423 args.push_back(std::move(zeros));
3424 }
John Stiles4d6310a2021-01-26 19:58:22 -05003425 auto callMainFn = std::make_unique<FunctionCall>(/*offset=*/-1, &main.returnType(), &main,
Brian Osman716aeb92021-04-21 13:20:00 -04003426 std::move(args));
John Stiles4d6310a2021-01-26 19:58:22 -05003427
3428 // Synthesize `skFragColor = main()` as a BinaryExpression.
3429 auto assignmentStmt = std::make_unique<ExpressionStatement>(std::make_unique<BinaryExpression>(
3430 /*offset=*/-1,
3431 std::move(skFragColorRef),
3432 Token::Kind::TK_EQ,
3433 std::move(callMainFn),
3434 &main.returnType()));
3435
3436 // Function bodies are always wrapped in a Block.
3437 StatementArray entrypointStmts;
3438 entrypointStmts.push_back(std::move(assignmentStmt));
John Stilesbf16b6c2021-03-12 19:24:31 -05003439 auto entrypointBlock = Block::Make(/*offset=*/-1, std::move(entrypointStmts),
3440 symbolTable, /*isScope=*/true);
John Stiles4d6310a2021-01-26 19:58:22 -05003441 // Declare an entrypoint function.
3442 EntrypointAdapter adapter;
3443 adapter.fLayout = {};
3444 adapter.fModifiers = Modifiers{adapter.fLayout, Modifiers::kHasSideEffects_Flag};
3445 adapter.entrypointDecl =
3446 std::make_unique<FunctionDeclaration>(/*offset=*/-1,
3447 &adapter.fModifiers,
3448 "_entrypoint",
3449 /*parameters=*/std::vector<const Variable*>{},
3450 /*returnType=*/fContext.fTypes.fVoid.get(),
3451 /*builtin=*/false);
3452 // Define it.
3453 adapter.entrypointDef =
3454 std::make_unique<FunctionDefinition>(/*offset=*/-1, adapter.entrypointDecl.get(),
3455 /*builtin=*/false,
3456 /*body=*/std::move(entrypointBlock));
3457
3458 adapter.entrypointDecl->setDefinition(adapter.entrypointDef.get());
3459 return adapter;
3460}
3461
John Stilese40d1662021-01-29 10:08:50 -05003462void SPIRVCodeGenerator::writeUniformBuffer(std::shared_ptr<SymbolTable> topLevelSymbolTable) {
3463 SkASSERT(!fTopLevelUniforms.empty());
3464 static constexpr char kUniformBufferName[] = "_UniformBuffer";
3465
3466 // Convert the list of top-level uniforms into a matching struct named _UniformBuffer, and build
3467 // a lookup table of variables to UniformBuffer field indices.
3468 std::vector<Type::Field> fields;
3469 fields.reserve(fTopLevelUniforms.size());
3470 fTopLevelUniformMap.reserve(fTopLevelUniforms.size());
3471 for (const VarDeclaration* topLevelUniform : fTopLevelUniforms) {
3472 const Variable* var = &topLevelUniform->var();
3473 fTopLevelUniformMap[var] = (int)fields.size();
3474 fields.emplace_back(var->modifiers(), var->name(), &var->type());
3475 }
3476 fUniformBuffer.fStruct = Type::MakeStructType(/*offset=*/-1, kUniformBufferName,
3477 std::move(fields));
3478
3479 // Create a global variable to contain this struct.
3480 Layout layout;
John Stiles270cec22021-02-17 12:59:36 -05003481 layout.fBinding = fProgram.fConfig->fSettings.fDefaultUniformBinding;
3482 layout.fSet = fProgram.fConfig->fSettings.fDefaultUniformSet;
John Stilese40d1662021-01-29 10:08:50 -05003483 Modifiers modifiers{layout, Modifiers::kUniform_Flag};
3484
3485 fUniformBuffer.fInnerVariable = std::make_unique<Variable>(
John Stilesf2872e62021-05-04 11:38:43 -04003486 /*offset=*/-1, fProgram.fModifiers->add(modifiers), kUniformBufferName,
John Stilese40d1662021-01-29 10:08:50 -05003487 fUniformBuffer.fStruct.get(), /*builtin=*/false, Variable::Storage::kGlobal);
3488
3489 // Create an interface block object for this global variable.
3490 fUniformBuffer.fInterfaceBlock = std::make_unique<InterfaceBlock>(
3491 /*offset=*/-1, fUniformBuffer.fInnerVariable.get(), kUniformBufferName,
3492 kUniformBufferName, /*arraySize=*/0, topLevelSymbolTable);
3493
3494 // Generate an interface block and hold onto its ID.
3495 fUniformBufferId = this->writeInterfaceBlock(*fUniformBuffer.fInterfaceBlock);
3496}
3497
Ethan Nicholas0df1b042017-03-31 13:56:23 -04003498void SPIRVCodeGenerator::writeInstructions(const Program& program, OutputStream& out) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04003499 fGLSLExtendedInstructions = this->nextId(nullptr);
Ethan Nicholas0df1b042017-03-31 13:56:23 -04003500 StringStream body;
John Stiles4d6310a2021-01-26 19:58:22 -05003501 // Assign SpvIds to functions.
3502 const FunctionDeclaration* main = nullptr;
Brian Osman133724c2020-10-28 14:14:39 -04003503 for (const ProgramElement* e : program.elements()) {
John Stiles4d6310a2021-01-26 19:58:22 -05003504 if (e->is<FunctionDefinition>()) {
3505 const FunctionDefinition& funcDef = e->as<FunctionDefinition>();
3506 const FunctionDeclaration& funcDecl = funcDef.declaration();
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04003507 fFunctionMap[&funcDecl] = this->nextId(nullptr);
John Stilese8da4d22021-03-24 09:19:45 -04003508 if (funcDecl.isMain()) {
John Stiles4d6310a2021-01-26 19:58:22 -05003509 main = &funcDecl;
Ethan Nicholasb6ba82c2018-01-17 15:21:50 -05003510 }
ethannicholasb3058bd2016-07-01 08:22:01 -07003511 }
3512 }
John Stiles4d6310a2021-01-26 19:58:22 -05003513 // Make sure we have a main() function.
3514 if (!main) {
3515 fErrors.error(/*offset=*/0, "program does not contain a main() function");
3516 return;
3517 }
3518 // Emit interface blocks.
3519 std::set<SpvId> interfaceVars;
Brian Osman133724c2020-10-28 14:14:39 -04003520 for (const ProgramElement* e : program.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04003521 if (e->is<InterfaceBlock>()) {
Brian Osman1f8f5752020-10-28 14:46:21 -04003522 const InterfaceBlock& intf = e->as<InterfaceBlock>();
ethannicholasb3058bd2016-07-01 08:22:01 -07003523 SpvId id = this->writeInterfaceBlock(intf);
Brian Osman1f8f5752020-10-28 14:46:21 -04003524
3525 const Modifiers& modifiers = intf.variable().modifiers();
John Stiles8e2a84b2021-04-19 09:35:38 -04003526 if ((modifiers.fFlags & (Modifiers::kIn_Flag | Modifiers::kOut_Flag)) &&
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04003527 modifiers.fLayout.fBuiltin == -1 &&
Brian Osman010ce6a2020-10-19 16:34:10 -04003528 !is_dead(intf.variable(), fProgram.fUsage.get())) {
Ethan Nicholas8e48c1e2017-03-02 14:33:31 -05003529 interfaceVars.insert(id);
ethannicholasb3058bd2016-07-01 08:22:01 -07003530 }
3531 }
3532 }
John Stiles4d6310a2021-01-26 19:58:22 -05003533 // Emit global variable declarations.
Brian Osman133724c2020-10-28 14:14:39 -04003534 for (const ProgramElement* e : program.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04003535 if (e->is<GlobalVarDeclaration>()) {
John Stiles270cec22021-02-17 12:59:36 -05003536 this->writeGlobalVar(program.fConfig->fKind,
John Stilese40d1662021-01-29 10:08:50 -05003537 e->as<GlobalVarDeclaration>().declaration()->as<VarDeclaration>());
ethannicholasb3058bd2016-07-01 08:22:01 -07003538 }
3539 }
John Stilese40d1662021-01-29 10:08:50 -05003540 // Emit top-level uniforms into a dedicated uniform buffer.
3541 if (!fTopLevelUniforms.empty()) {
3542 this->writeUniformBuffer(get_top_level_symbol_table(*main));
3543 }
John Stiles4d6310a2021-01-26 19:58:22 -05003544 // If main() returns a half4, synthesize a tiny entrypoint function which invokes the real
3545 // main() and stores the result into sk_FragColor.
3546 EntrypointAdapter adapter;
3547 if (main->returnType() == *fContext.fTypes.fHalf4) {
3548 adapter = this->writeEntrypointAdapter(*main);
3549 if (adapter.entrypointDecl) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04003550 fFunctionMap[adapter.entrypointDecl.get()] = this->nextId(nullptr);
John Stiles4d6310a2021-01-26 19:58:22 -05003551 this->writeFunction(*adapter.entrypointDef, body);
3552 main = adapter.entrypointDecl.get();
3553 }
3554 }
3555 // Emit all the functions.
Brian Osman133724c2020-10-28 14:14:39 -04003556 for (const ProgramElement* e : program.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04003557 if (e->is<FunctionDefinition>()) {
3558 this->writeFunction(e->as<FunctionDefinition>(), body);
ethannicholasb3058bd2016-07-01 08:22:01 -07003559 }
3560 }
John Stiles4d6310a2021-01-26 19:58:22 -05003561 // Add global in/out variables to the list of interface variables.
ethannicholasb3058bd2016-07-01 08:22:01 -07003562 for (auto entry : fVariableMap) {
ethannicholasd598f792016-07-25 10:08:54 -07003563 const Variable* var = entry.first;
Ethan Nicholas453f67f2020-10-09 10:43:45 -04003564 if (var->storage() == Variable::Storage::kGlobal &&
John Stiles8e2a84b2021-04-19 09:35:38 -04003565 (var->modifiers().fFlags & (Modifiers::kIn_Flag | Modifiers::kOut_Flag)) &&
Brian Osman010ce6a2020-10-19 16:34:10 -04003566 !is_dead(*var, fProgram.fUsage.get())) {
Ethan Nicholas8e48c1e2017-03-02 14:33:31 -05003567 interfaceVars.insert(entry.second);
ethannicholasb3058bd2016-07-01 08:22:01 -07003568 }
3569 }
3570 this->writeCapabilities(out);
3571 this->writeInstruction(SpvOpExtInstImport, fGLSLExtendedInstructions, "GLSL.std.450", out);
3572 this->writeInstruction(SpvOpMemoryModel, SpvAddressingModelLogical, SpvMemoryModelGLSL450, out);
Ethan Nicholase2c49992020-10-05 11:49:11 -04003573 this->writeOpCode(SpvOpEntryPoint, (SpvId) (3 + (main->name().fLength + 4) / 4) +
ethannicholasb3058bd2016-07-01 08:22:01 -07003574 (int32_t) interfaceVars.size(), out);
John Stiles270cec22021-02-17 12:59:36 -05003575 switch (program.fConfig->fKind) {
John Stilesdbd4e6f2021-02-16 13:29:15 -05003576 case ProgramKind::kVertex:
ethannicholasb3058bd2016-07-01 08:22:01 -07003577 this->writeWord(SpvExecutionModelVertex, out);
3578 break;
John Stilesdbd4e6f2021-02-16 13:29:15 -05003579 case ProgramKind::kFragment:
ethannicholasb3058bd2016-07-01 08:22:01 -07003580 this->writeWord(SpvExecutionModelFragment, out);
3581 break;
John Stilesdbd4e6f2021-02-16 13:29:15 -05003582 case ProgramKind::kGeometry:
Ethan Nicholas52cad152017-02-16 16:37:32 -05003583 this->writeWord(SpvExecutionModelGeometry, out);
3584 break;
Ethan Nicholas762466e2017-06-29 10:03:38 -04003585 default:
John Stilesf57207b2021-02-02 17:50:34 -05003586 SK_ABORT("cannot write this kind of program to SPIR-V\n");
ethannicholasb3058bd2016-07-01 08:22:01 -07003587 }
Ethan Nicholasbb155e22017-07-24 10:05:09 -04003588 SpvId entryPoint = fFunctionMap[main];
3589 this->writeWord(entryPoint, out);
Ethan Nicholase2c49992020-10-05 11:49:11 -04003590 this->writeString(main->name().fChars, main->name().fLength, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003591 for (int var : interfaceVars) {
3592 this->writeWord(var, out);
3593 }
John Stiles270cec22021-02-17 12:59:36 -05003594 if (program.fConfig->fKind == ProgramKind::kGeometry) {
Ethan Nicholasbb155e22017-07-24 10:05:09 -04003595 this->writeGeometryShaderExecutionMode(entryPoint, out);
3596 }
John Stiles270cec22021-02-17 12:59:36 -05003597 if (program.fConfig->fKind == ProgramKind::kFragment) {
Greg Daniel64773e62016-11-22 09:44:03 -05003598 this->writeInstruction(SpvOpExecutionMode,
3599 fFunctionMap[main],
ethannicholasb3058bd2016-07-01 08:22:01 -07003600 SpvExecutionModeOriginUpperLeft,
3601 out);
3602 }
Brian Osman133724c2020-10-28 14:14:39 -04003603 for (const ProgramElement* e : program.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04003604 if (e->is<Extension>()) {
3605 this->writeInstruction(SpvOpSourceExtension, e->as<Extension>().name().c_str(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003606 }
3607 }
Greg Daniel64773e62016-11-22 09:44:03 -05003608
Ethan Nicholas0df1b042017-03-31 13:56:23 -04003609 write_stringstream(fExtraGlobalsBuffer, out);
3610 write_stringstream(fNameBuffer, out);
3611 write_stringstream(fDecorationBuffer, out);
3612 write_stringstream(fConstantBuffer, out);
3613 write_stringstream(fExternalFunctionsBuffer, out);
3614 write_stringstream(body, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003615}
3616
Ethan Nicholas941e7e22016-12-12 15:33:30 -05003617bool SPIRVCodeGenerator::generateCode() {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04003618 SkASSERT(!fErrors.errorCount());
Ethan Nicholas941e7e22016-12-12 15:33:30 -05003619 this->writeWord(SpvMagicNumber, *fOut);
3620 this->writeWord(SpvVersion, *fOut);
3621 this->writeWord(SKSL_MAGIC, *fOut);
Ethan Nicholas0df1b042017-03-31 13:56:23 -04003622 StringStream buffer;
Ethan Nicholas941e7e22016-12-12 15:33:30 -05003623 this->writeInstructions(fProgram, buffer);
3624 this->writeWord(fIdCount, *fOut);
3625 this->writeWord(0, *fOut); // reserved, always zero
Ethan Nicholas0df1b042017-03-31 13:56:23 -04003626 write_stringstream(buffer, *fOut);
Ethan Nicholas941e7e22016-12-12 15:33:30 -05003627 return 0 == fErrors.errorCount();
ethannicholasb3058bd2016-07-01 08:22:01 -07003628}
3629
John Stilesa6841be2020-08-06 14:11:56 -04003630} // namespace SkSL