blob: 43f8661522a1cc94fec3b5d3ca86f187bab68ce2 [file] [log] [blame]
ethannicholasb3058bd2016-07-01 08:22:01 -07001/*
2 * Copyright 2016 Google Inc.
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
Ethan Nicholasbcf35f82017-03-30 18:42:48 +00007
John Stiles3738ef52021-04-13 10:41:57 -04008#include "src/sksl/codegen/SkSLSPIRVCodeGenerator.h"
Ethan Nicholas9bd301d2017-03-31 16:04:34 +00009
Mike Kleinc0bd9f92019-04-23 12:05:21 -050010#include "src/sksl/GLSL.std.450.h"
ethannicholasb3058bd2016-07-01 08:22:01 -070011
Brian Salomond8d85b92021-07-07 09:41:17 -040012#include "include/sksl/DSLCore.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050013#include "src/sksl/SkSLCompiler.h"
Brian Osman00185012021-02-04 16:07:11 -050014#include "src/sksl/SkSLOperators.h"
Brian Salomond8d85b92021-07-07 09:41:17 -040015#include "src/sksl/dsl/priv/DSLWriter.h"
John Stiles4d6310a2021-01-26 19:58:22 -050016#include "src/sksl/ir/SkSLBlock.h"
John Stilese3ae9682021-08-05 10:35:01 -040017#include "src/sksl/ir/SkSLConstructorArrayCast.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050018#include "src/sksl/ir/SkSLExpressionStatement.h"
19#include "src/sksl/ir/SkSLExtension.h"
Brian Salomond8d85b92021-07-07 09:41:17 -040020#include "src/sksl/ir/SkSLField.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050021#include "src/sksl/ir/SkSLIndexExpression.h"
22#include "src/sksl/ir/SkSLVariableReference.h"
ethannicholasb3058bd2016-07-01 08:22:01 -070023
Ethan Nicholas0be34802019-08-15 12:36:58 -040024#ifdef SK_VULKAN
25#include "src/gpu/vk/GrVkCaps.h"
26#endif
27
John Stilescd806892021-01-06 13:33:31 -050028#define kLast_Capability SpvCapabilityMultiViewport
29
Brian Salomond8d85b92021-07-07 09:41:17 -040030constexpr int DEVICE_FRAGCOORDS_BUILTIN = -1000;
31constexpr int DEVICE_CLOCKWISE_BUILTIN = -1001;
32
ethannicholasb3058bd2016-07-01 08:22:01 -070033namespace SkSL {
34
ethannicholasb3058bd2016-07-01 08:22:01 -070035static const int32_t SKSL_MAGIC = 0x0; // FIXME: we should probably register a magic number
36
37void SPIRVCodeGenerator::setupIntrinsics() {
John Stilesaaac4e42021-05-06 14:08:28 -040038#define ALL_GLSL(x) std::make_tuple(kGLSL_STD_450_IntrinsicOpcodeKind, GLSLstd450 ## x, \
39 GLSLstd450 ## x, GLSLstd450 ## x, GLSLstd450 ## x)
40#define BY_TYPE_GLSL(ifFloat, ifInt, ifUInt) std::make_tuple(kGLSL_STD_450_IntrinsicOpcodeKind, \
41 GLSLstd450 ## ifFloat, \
42 GLSLstd450 ## ifInt, \
43 GLSLstd450 ## ifUInt, \
ethannicholasb3058bd2016-07-01 08:22:01 -070044 SpvOpUndef)
John Stilesaaac4e42021-05-06 14:08:28 -040045#define ALL_SPIRV(x) std::make_tuple(kSPIRV_IntrinsicOpcodeKind, \
46 SpvOp ## x, SpvOp ## x, SpvOp ## x, SpvOp ## x)
47#define SPECIAL(x) std::make_tuple(kSpecial_IntrinsicOpcodeKind, k ## x ## _SpecialIntrinsic, \
48 k ## x ## _SpecialIntrinsic, k ## x ## _SpecialIntrinsic, \
ethannicholasb3058bd2016-07-01 08:22:01 -070049 k ## x ## _SpecialIntrinsic)
John Stilesaaac4e42021-05-06 14:08:28 -040050 fIntrinsicMap[k_round_IntrinsicKind] = ALL_GLSL(Round);
51 fIntrinsicMap[k_roundEven_IntrinsicKind] = ALL_GLSL(RoundEven);
52 fIntrinsicMap[k_trunc_IntrinsicKind] = ALL_GLSL(Trunc);
53 fIntrinsicMap[k_abs_IntrinsicKind] = BY_TYPE_GLSL(FAbs, SAbs, SAbs);
54 fIntrinsicMap[k_sign_IntrinsicKind] = BY_TYPE_GLSL(FSign, SSign, SSign);
55 fIntrinsicMap[k_floor_IntrinsicKind] = ALL_GLSL(Floor);
56 fIntrinsicMap[k_ceil_IntrinsicKind] = ALL_GLSL(Ceil);
57 fIntrinsicMap[k_fract_IntrinsicKind] = ALL_GLSL(Fract);
58 fIntrinsicMap[k_radians_IntrinsicKind] = ALL_GLSL(Radians);
59 fIntrinsicMap[k_degrees_IntrinsicKind] = ALL_GLSL(Degrees);
60 fIntrinsicMap[k_sin_IntrinsicKind] = ALL_GLSL(Sin);
61 fIntrinsicMap[k_cos_IntrinsicKind] = ALL_GLSL(Cos);
62 fIntrinsicMap[k_tan_IntrinsicKind] = ALL_GLSL(Tan);
63 fIntrinsicMap[k_asin_IntrinsicKind] = ALL_GLSL(Asin);
64 fIntrinsicMap[k_acos_IntrinsicKind] = ALL_GLSL(Acos);
65 fIntrinsicMap[k_atan_IntrinsicKind] = SPECIAL(Atan);
66 fIntrinsicMap[k_sinh_IntrinsicKind] = ALL_GLSL(Sinh);
67 fIntrinsicMap[k_cosh_IntrinsicKind] = ALL_GLSL(Cosh);
68 fIntrinsicMap[k_tanh_IntrinsicKind] = ALL_GLSL(Tanh);
69 fIntrinsicMap[k_asinh_IntrinsicKind] = ALL_GLSL(Asinh);
70 fIntrinsicMap[k_acosh_IntrinsicKind] = ALL_GLSL(Acosh);
71 fIntrinsicMap[k_atanh_IntrinsicKind] = ALL_GLSL(Atanh);
72 fIntrinsicMap[k_pow_IntrinsicKind] = ALL_GLSL(Pow);
73 fIntrinsicMap[k_exp_IntrinsicKind] = ALL_GLSL(Exp);
74 fIntrinsicMap[k_log_IntrinsicKind] = ALL_GLSL(Log);
75 fIntrinsicMap[k_exp2_IntrinsicKind] = ALL_GLSL(Exp2);
76 fIntrinsicMap[k_log2_IntrinsicKind] = ALL_GLSL(Log2);
77 fIntrinsicMap[k_sqrt_IntrinsicKind] = ALL_GLSL(Sqrt);
78 fIntrinsicMap[k_inverse_IntrinsicKind] = ALL_GLSL(MatrixInverse);
79 fIntrinsicMap[k_outerProduct_IntrinsicKind] = ALL_SPIRV(OuterProduct);
80 fIntrinsicMap[k_transpose_IntrinsicKind] = ALL_SPIRV(Transpose);
81 fIntrinsicMap[k_isinf_IntrinsicKind] = ALL_SPIRV(IsInf);
82 fIntrinsicMap[k_isnan_IntrinsicKind] = ALL_SPIRV(IsNan);
83 fIntrinsicMap[k_inversesqrt_IntrinsicKind] = ALL_GLSL(InverseSqrt);
84 fIntrinsicMap[k_determinant_IntrinsicKind] = ALL_GLSL(Determinant);
85 fIntrinsicMap[k_matrixCompMult_IntrinsicKind] = SPECIAL(MatrixCompMult);
86 fIntrinsicMap[k_matrixInverse_IntrinsicKind] = ALL_GLSL(MatrixInverse);
87 fIntrinsicMap[k_mod_IntrinsicKind] = SPECIAL(Mod);
88 fIntrinsicMap[k_modf_IntrinsicKind] = ALL_GLSL(Modf);
89 fIntrinsicMap[k_min_IntrinsicKind] = SPECIAL(Min);
90 fIntrinsicMap[k_max_IntrinsicKind] = SPECIAL(Max);
91 fIntrinsicMap[k_clamp_IntrinsicKind] = SPECIAL(Clamp);
92 fIntrinsicMap[k_saturate_IntrinsicKind] = SPECIAL(Saturate);
93 fIntrinsicMap[k_dot_IntrinsicKind] = std::make_tuple(kSPIRV_IntrinsicOpcodeKind,
94 SpvOpDot, SpvOpUndef, SpvOpUndef, SpvOpUndef);
95 fIntrinsicMap[k_mix_IntrinsicKind] = SPECIAL(Mix);
96 fIntrinsicMap[k_step_IntrinsicKind] = SPECIAL(Step);
97 fIntrinsicMap[k_smoothstep_IntrinsicKind] = SPECIAL(SmoothStep);
98 fIntrinsicMap[k_fma_IntrinsicKind] = ALL_GLSL(Fma);
99 fIntrinsicMap[k_frexp_IntrinsicKind] = ALL_GLSL(Frexp);
100 fIntrinsicMap[k_ldexp_IntrinsicKind] = ALL_GLSL(Ldexp);
ethannicholasb3058bd2016-07-01 08:22:01 -0700101
John Stilesaaac4e42021-05-06 14:08:28 -0400102#define PACK(type) fIntrinsicMap[k_pack##type##_IntrinsicKind] = ALL_GLSL(Pack##type); \
103 fIntrinsicMap[k_unpack##type##_IntrinsicKind] = ALL_GLSL(Unpack##type)
ethannicholasb3058bd2016-07-01 08:22:01 -0700104 PACK(Snorm4x8);
105 PACK(Unorm4x8);
106 PACK(Snorm2x16);
107 PACK(Unorm2x16);
108 PACK(Half2x16);
109 PACK(Double2x32);
John Stilesaaac4e42021-05-06 14:08:28 -0400110#undef PACK
111 fIntrinsicMap[k_length_IntrinsicKind] = ALL_GLSL(Length);
112 fIntrinsicMap[k_distance_IntrinsicKind] = ALL_GLSL(Distance);
113 fIntrinsicMap[k_cross_IntrinsicKind] = ALL_GLSL(Cross);
114 fIntrinsicMap[k_normalize_IntrinsicKind] = ALL_GLSL(Normalize);
115 fIntrinsicMap[k_faceforward_IntrinsicKind] = ALL_GLSL(FaceForward);
116 fIntrinsicMap[k_reflect_IntrinsicKind] = ALL_GLSL(Reflect);
117 fIntrinsicMap[k_refract_IntrinsicKind] = ALL_GLSL(Refract);
118 fIntrinsicMap[k_bitCount_IntrinsicKind] = ALL_SPIRV(BitCount);
119 fIntrinsicMap[k_findLSB_IntrinsicKind] = ALL_GLSL(FindILsb);
120 fIntrinsicMap[k_findMSB_IntrinsicKind] = BY_TYPE_GLSL(FindSMsb, FindSMsb, FindUMsb);
121 fIntrinsicMap[k_dFdx_IntrinsicKind] = std::make_tuple(kSPIRV_IntrinsicOpcodeKind,
122 SpvOpDPdx, SpvOpUndef,
123 SpvOpUndef, SpvOpUndef);
124 fIntrinsicMap[k_dFdy_IntrinsicKind] = SPECIAL(DFdy);
125 fIntrinsicMap[k_fwidth_IntrinsicKind] = std::make_tuple(kSPIRV_IntrinsicOpcodeKind,
126 SpvOpFwidth, SpvOpUndef,
127 SpvOpUndef, SpvOpUndef);
128 fIntrinsicMap[k_makeSampler2D_IntrinsicKind] = SPECIAL(SampledImage);
Stephen Whiteff5d7a22019-07-26 17:42:06 -0400129
John Stilesaaac4e42021-05-06 14:08:28 -0400130 fIntrinsicMap[k_sample_IntrinsicKind] = SPECIAL(Texture);
131 fIntrinsicMap[k_subpassLoad_IntrinsicKind] = SPECIAL(SubpassLoad);
Greg Daniel64773e62016-11-22 09:44:03 -0500132
John Stilesaaac4e42021-05-06 14:08:28 -0400133 fIntrinsicMap[k_floatBitsToInt_IntrinsicKind] = ALL_SPIRV(Bitcast);
134 fIntrinsicMap[k_floatBitsToUint_IntrinsicKind] = ALL_SPIRV(Bitcast);
135 fIntrinsicMap[k_intBitsToFloat_IntrinsicKind] = ALL_SPIRV(Bitcast);
136 fIntrinsicMap[k_uintBitsToFloat_IntrinsicKind] = ALL_SPIRV(Bitcast);
John Stilescc9ff002020-12-09 18:39:41 -0500137
John Stilesaaac4e42021-05-06 14:08:28 -0400138 fIntrinsicMap[k_any_IntrinsicKind] = std::make_tuple(kSPIRV_IntrinsicOpcodeKind,
Brian Osman540c13a2020-11-24 16:55:34 -0500139 SpvOpUndef, SpvOpUndef,
John Stilesaaac4e42021-05-06 14:08:28 -0400140 SpvOpUndef, SpvOpAny);
141 fIntrinsicMap[k_all_IntrinsicKind] = std::make_tuple(kSPIRV_IntrinsicOpcodeKind,
142 SpvOpUndef, SpvOpUndef,
143 SpvOpUndef, SpvOpAll);
144 fIntrinsicMap[k_not_IntrinsicKind] = std::make_tuple(kSPIRV_IntrinsicOpcodeKind,
145 SpvOpUndef, SpvOpUndef, SpvOpUndef,
Brian Osman540c13a2020-11-24 16:55:34 -0500146 SpvOpLogicalNot);
John Stilesaaac4e42021-05-06 14:08:28 -0400147 fIntrinsicMap[k_equal_IntrinsicKind] = std::make_tuple(kSPIRV_IntrinsicOpcodeKind,
Ethan Nicholas0187ae62017-05-03 11:03:44 -0400148 SpvOpFOrdEqual, SpvOpIEqual,
149 SpvOpIEqual, SpvOpLogicalEqual);
John Stilesaaac4e42021-05-06 14:08:28 -0400150 fIntrinsicMap[k_notEqual_IntrinsicKind] = std::make_tuple(kSPIRV_IntrinsicOpcodeKind,
Ethan Nicholas0187ae62017-05-03 11:03:44 -0400151 SpvOpFOrdNotEqual, SpvOpINotEqual,
152 SpvOpINotEqual,
153 SpvOpLogicalNotEqual);
John Stilesaaac4e42021-05-06 14:08:28 -0400154 fIntrinsicMap[k_lessThan_IntrinsicKind] = std::make_tuple(kSPIRV_IntrinsicOpcodeKind,
155 SpvOpFOrdLessThan,
156 SpvOpSLessThan,
157 SpvOpULessThan,
158 SpvOpUndef);
159 fIntrinsicMap[k_lessThanEqual_IntrinsicKind] = std::make_tuple(kSPIRV_IntrinsicOpcodeKind,
160 SpvOpFOrdLessThanEqual,
161 SpvOpSLessThanEqual,
162 SpvOpULessThanEqual,
163 SpvOpUndef);
164 fIntrinsicMap[k_greaterThan_IntrinsicKind] = std::make_tuple(kSPIRV_IntrinsicOpcodeKind,
165 SpvOpFOrdGreaterThan,
166 SpvOpSGreaterThan,
167 SpvOpUGreaterThan,
168 SpvOpUndef);
169 fIntrinsicMap[k_greaterThanEqual_IntrinsicKind] = std::make_tuple(kSPIRV_IntrinsicOpcodeKind,
170 SpvOpFOrdGreaterThanEqual,
171 SpvOpSGreaterThanEqual,
172 SpvOpUGreaterThanEqual,
173 SpvOpUndef);
ethannicholasb3058bd2016-07-01 08:22:01 -0700174// interpolateAt* not yet supported...
175}
176
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400177void SPIRVCodeGenerator::writeWord(int32_t word, OutputStream& out) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700178 out.write((const char*) &word, sizeof(word));
ethannicholasb3058bd2016-07-01 08:22:01 -0700179}
180
ethannicholasd598f792016-07-25 10:08:54 -0700181static bool is_float(const Context& context, const Type& type) {
John Stiles4c151702021-02-09 18:31:34 -0500182 return (type.isScalar() || type.isVector() || type.isMatrix()) &&
183 type.componentType().isFloat();
ethannicholasb3058bd2016-07-01 08:22:01 -0700184}
185
ethannicholasd598f792016-07-25 10:08:54 -0700186static bool is_signed(const Context& context, const Type& type) {
Brian Osmanc9145f32021-07-08 13:40:10 -0400187 return (type.isScalar() || type.isVector()) && type.componentType().isSigned();
ethannicholasb3058bd2016-07-01 08:22:01 -0700188}
189
ethannicholasd598f792016-07-25 10:08:54 -0700190static bool is_unsigned(const Context& context, const Type& type) {
John Stiles4c151702021-02-09 18:31:34 -0500191 return (type.isScalar() || type.isVector()) && type.componentType().isUnsigned();
ethannicholasb3058bd2016-07-01 08:22:01 -0700192}
193
ethannicholasd598f792016-07-25 10:08:54 -0700194static bool is_bool(const Context& context, const Type& type) {
John Stiles4c151702021-02-09 18:31:34 -0500195 return (type.isScalar() || type.isVector()) && type.componentType().isBoolean();
ethannicholasb3058bd2016-07-01 08:22:01 -0700196}
197
ethannicholasd598f792016-07-25 10:08:54 -0700198static bool is_out(const Variable& var) {
Ethan Nicholas041fd0a2020-10-07 16:42:04 -0400199 return (var.modifiers().fFlags & Modifiers::kOut_Flag) != 0;
ethannicholasb3058bd2016-07-01 08:22:01 -0700200}
201
John Stiles6a51b202021-09-08 10:45:08 -0400202static bool is_in(const Variable& var) {
203 switch (var.modifiers().fFlags & (Modifiers::kOut_Flag | Modifiers::kIn_Flag)) {
204 case Modifiers::kOut_Flag: // out
205 return false;
206
207 case 0: // implicit in
208 case Modifiers::kIn_Flag: // explicit in
209 case Modifiers::kOut_Flag | Modifiers::kIn_Flag: // inout
210 return true;
211
212 default: SkUNREACHABLE;
213 }
214}
215
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400216void SPIRVCodeGenerator::writeOpCode(SpvOp_ opCode, int length, OutputStream& out) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400217 SkASSERT(opCode != SpvOpLoad || &out != &fConstantBuffer);
218 SkASSERT(opCode != SpvOpUndef);
ethannicholasb3058bd2016-07-01 08:22:01 -0700219 switch (opCode) {
220 case SpvOpReturn: // fall through
221 case SpvOpReturnValue: // fall through
ethannicholas552882f2016-07-07 06:30:48 -0700222 case SpvOpKill: // fall through
Ethan Nicholas7fb39362020-12-16 15:25:19 -0500223 case SpvOpSwitch: // fall through
ethannicholasb3058bd2016-07-01 08:22:01 -0700224 case SpvOpBranch: // fall through
225 case SpvOpBranchConditional:
John Stilesf2b08cc2021-05-17 14:46:05 -0400226 if (fCurrentBlock == 0) {
227 // We just encountered dead code--instructions that don't have an associated block.
228 // Synthesize a label if this happens; this is necessary to satisfy the validator.
229 this->writeLabel(this->nextId(nullptr), out);
230 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700231 fCurrentBlock = 0;
232 break;
233 case SpvOpConstant: // fall through
234 case SpvOpConstantTrue: // fall through
235 case SpvOpConstantFalse: // fall through
236 case SpvOpConstantComposite: // fall through
237 case SpvOpTypeVoid: // fall through
238 case SpvOpTypeInt: // fall through
239 case SpvOpTypeFloat: // fall through
240 case SpvOpTypeBool: // fall through
241 case SpvOpTypeVector: // fall through
242 case SpvOpTypeMatrix: // fall through
243 case SpvOpTypeArray: // fall through
244 case SpvOpTypePointer: // fall through
245 case SpvOpTypeFunction: // fall through
246 case SpvOpTypeRuntimeArray: // fall through
247 case SpvOpTypeStruct: // fall through
248 case SpvOpTypeImage: // fall through
249 case SpvOpTypeSampledImage: // fall through
Stephen Whiteff5d7a22019-07-26 17:42:06 -0400250 case SpvOpTypeSampler: // fall through
ethannicholasb3058bd2016-07-01 08:22:01 -0700251 case SpvOpVariable: // fall through
252 case SpvOpFunction: // fall through
253 case SpvOpFunctionParameter: // fall through
254 case SpvOpFunctionEnd: // fall through
255 case SpvOpExecutionMode: // fall through
256 case SpvOpMemoryModel: // fall through
257 case SpvOpCapability: // fall through
258 case SpvOpExtInstImport: // fall through
259 case SpvOpEntryPoint: // fall through
260 case SpvOpSource: // fall through
261 case SpvOpSourceExtension: // fall through
262 case SpvOpName: // fall through
263 case SpvOpMemberName: // fall through
264 case SpvOpDecorate: // fall through
265 case SpvOpMemberDecorate:
266 break;
267 default:
John Stilesf3a28db2021-03-10 23:00:47 -0500268 // We may find ourselves with dead code--instructions that don't have an associated
269 // block. This should be a rare event, but if it happens, synthesize a label; this is
270 // necessary to satisfy the validator.
271 if (fCurrentBlock == 0) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -0400272 this->writeLabel(this->nextId(nullptr), out);
John Stiles7142e402021-02-23 12:28:18 -0500273 }
John Stiles453f1432021-02-25 16:58:04 -0500274 break;
ethannicholasb3058bd2016-07-01 08:22:01 -0700275 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700276 this->writeWord((length << 16) | opCode, out);
ethannicholasb3058bd2016-07-01 08:22:01 -0700277}
278
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400279void SPIRVCodeGenerator::writeLabel(SpvId label, OutputStream& out) {
Ethan Nicholas7fb39362020-12-16 15:25:19 -0500280 SkASSERT(!fCurrentBlock);
ethannicholasb3058bd2016-07-01 08:22:01 -0700281 fCurrentBlock = label;
282 this->writeInstruction(SpvOpLabel, label, out);
283}
284
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400285void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, OutputStream& out) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700286 this->writeOpCode(opCode, 1, out);
287}
288
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400289void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, int32_t word1, OutputStream& out) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700290 this->writeOpCode(opCode, 2, out);
291 this->writeWord(word1, out);
292}
293
Ethan Nicholas962dec42021-06-10 13:06:39 -0400294void SPIRVCodeGenerator::writeString(skstd::string_view s, OutputStream& out) {
Ethan Nicholasd2e09602021-06-10 11:21:59 -0400295 out.write(s.data(), s.length());
296 switch (s.length() % 4) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700297 case 1:
Ethan Nicholas9e1138d2016-11-21 10:39:35 -0500298 out.write8(0);
John Stiles30212b72020-06-11 17:55:07 -0400299 [[fallthrough]];
ethannicholasb3058bd2016-07-01 08:22:01 -0700300 case 2:
Ethan Nicholas9e1138d2016-11-21 10:39:35 -0500301 out.write8(0);
John Stiles30212b72020-06-11 17:55:07 -0400302 [[fallthrough]];
ethannicholasb3058bd2016-07-01 08:22:01 -0700303 case 3:
Ethan Nicholas9e1138d2016-11-21 10:39:35 -0500304 out.write8(0);
ethannicholasb3058bd2016-07-01 08:22:01 -0700305 break;
306 default:
307 this->writeWord(0, out);
308 }
309}
310
Ethan Nicholas962dec42021-06-10 13:06:39 -0400311void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, skstd::string_view string,
312 OutputStream& out) {
Ethan Nicholasd2e09602021-06-10 11:21:59 -0400313 this->writeOpCode(opCode, 1 + (string.length() + 4) / 4, out);
314 this->writeString(string, out);
ethannicholasb3058bd2016-07-01 08:22:01 -0700315}
316
317
Ethan Nicholas962dec42021-06-10 13:06:39 -0400318void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, int32_t word1, skstd::string_view string,
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400319 OutputStream& out) {
Ethan Nicholasd2e09602021-06-10 11:21:59 -0400320 this->writeOpCode(opCode, 2 + (string.length() + 4) / 4, out);
ethannicholasb3058bd2016-07-01 08:22:01 -0700321 this->writeWord(word1, out);
Ethan Nicholasd2e09602021-06-10 11:21:59 -0400322 this->writeString(string, out);
ethannicholasb3058bd2016-07-01 08:22:01 -0700323}
324
Greg Daniel64773e62016-11-22 09:44:03 -0500325void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, int32_t word1, int32_t word2,
Ethan Nicholas962dec42021-06-10 13:06:39 -0400326 skstd::string_view string, OutputStream& out) {
Ethan Nicholasd2e09602021-06-10 11:21:59 -0400327 this->writeOpCode(opCode, 3 + (string.length() + 4) / 4, out);
ethannicholasb3058bd2016-07-01 08:22:01 -0700328 this->writeWord(word1, out);
329 this->writeWord(word2, out);
Ethan Nicholasd2e09602021-06-10 11:21:59 -0400330 this->writeString(string, out);
ethannicholasb3058bd2016-07-01 08:22:01 -0700331}
332
Greg Daniel64773e62016-11-22 09:44:03 -0500333void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, int32_t word1, int32_t word2,
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400334 OutputStream& out) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700335 this->writeOpCode(opCode, 3, out);
336 this->writeWord(word1, out);
337 this->writeWord(word2, out);
338}
339
Greg Daniel64773e62016-11-22 09:44:03 -0500340void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, int32_t word1, int32_t word2,
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400341 int32_t word3, OutputStream& out) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700342 this->writeOpCode(opCode, 4, out);
343 this->writeWord(word1, out);
344 this->writeWord(word2, out);
345 this->writeWord(word3, out);
346}
347
Greg Daniel64773e62016-11-22 09:44:03 -0500348void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, int32_t word1, int32_t word2,
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400349 int32_t word3, int32_t word4, OutputStream& out) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700350 this->writeOpCode(opCode, 5, out);
351 this->writeWord(word1, out);
352 this->writeWord(word2, out);
353 this->writeWord(word3, out);
354 this->writeWord(word4, out);
355}
356
Greg Daniel64773e62016-11-22 09:44:03 -0500357void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, int32_t word1, int32_t word2,
358 int32_t word3, int32_t word4, int32_t word5,
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400359 OutputStream& out) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700360 this->writeOpCode(opCode, 6, 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}
367
Greg Daniel64773e62016-11-22 09:44:03 -0500368void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, int32_t word1, int32_t word2,
ethannicholasb3058bd2016-07-01 08:22:01 -0700369 int32_t word3, int32_t word4, int32_t word5,
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400370 int32_t word6, OutputStream& out) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700371 this->writeOpCode(opCode, 7, out);
372 this->writeWord(word1, out);
373 this->writeWord(word2, out);
374 this->writeWord(word3, out);
375 this->writeWord(word4, out);
376 this->writeWord(word5, out);
377 this->writeWord(word6, out);
378}
379
Greg Daniel64773e62016-11-22 09:44:03 -0500380void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, int32_t word1, int32_t word2,
ethannicholasb3058bd2016-07-01 08:22:01 -0700381 int32_t word3, int32_t word4, int32_t word5,
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400382 int32_t word6, int32_t word7, OutputStream& out) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700383 this->writeOpCode(opCode, 8, out);
384 this->writeWord(word1, out);
385 this->writeWord(word2, out);
386 this->writeWord(word3, out);
387 this->writeWord(word4, out);
388 this->writeWord(word5, out);
389 this->writeWord(word6, out);
390 this->writeWord(word7, out);
391}
392
Greg Daniel64773e62016-11-22 09:44:03 -0500393void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, int32_t word1, int32_t word2,
ethannicholasb3058bd2016-07-01 08:22:01 -0700394 int32_t word3, int32_t word4, int32_t word5,
395 int32_t word6, int32_t word7, int32_t word8,
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400396 OutputStream& out) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700397 this->writeOpCode(opCode, 9, out);
398 this->writeWord(word1, out);
399 this->writeWord(word2, out);
400 this->writeWord(word3, out);
401 this->writeWord(word4, out);
402 this->writeWord(word5, out);
403 this->writeWord(word6, out);
404 this->writeWord(word7, out);
405 this->writeWord(word8, out);
406}
407
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400408void SPIRVCodeGenerator::writeCapabilities(OutputStream& out) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700409 for (uint64_t i = 0, bit = 1; i <= kLast_Capability; i++, bit <<= 1) {
410 if (fCapabilities & bit) {
411 this->writeInstruction(SpvOpCapability, (SpvId) i, out);
412 }
413 }
Brian Osman99ddd2a2021-08-27 11:21:12 -0400414 this->writeInstruction(SpvOpCapability, SpvCapabilityShader, out);
ethannicholasb3058bd2016-07-01 08:22:01 -0700415}
416
Ethan Nicholas8f352ce2021-03-17 14:12:20 -0400417SpvId SPIRVCodeGenerator::nextId(const Type* type) {
418 return this->nextId(type && type->hasPrecision() && !type->highPrecision()
419 ? Precision::kRelaxed
420 : Precision::kDefault);
421}
422
423SpvId SPIRVCodeGenerator::nextId(Precision precision) {
424 if (precision == Precision::kRelaxed && !fProgram.fConfig->fSettings.fForceHighPrecision) {
425 this->writeInstruction(SpvOpDecorate, fIdCount, SpvDecorationRelaxedPrecision,
426 fDecorationBuffer);
427 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700428 return fIdCount++;
429}
430
Ethan Nicholas19671772016-11-28 16:30:17 -0500431void SPIRVCodeGenerator::writeStruct(const Type& type, const MemoryLayout& memoryLayout,
432 SpvId resultId) {
Ethan Nicholase2c49992020-10-05 11:49:11 -0400433 this->writeInstruction(SpvOpName, resultId, String(type.name()).c_str(), fNameBuffer);
ethannicholasb3058bd2016-07-01 08:22:01 -0700434 // go ahead and write all of the field types, so we don't inadvertently write them while we're
435 // in the middle of writing the struct instruction
436 std::vector<SpvId> types;
437 for (const auto& f : type.fields()) {
Ethan Nicholas19671772016-11-28 16:30:17 -0500438 types.push_back(this->getType(*f.fType, memoryLayout));
ethannicholasb3058bd2016-07-01 08:22:01 -0700439 }
440 this->writeOpCode(SpvOpTypeStruct, 2 + (int32_t) types.size(), fConstantBuffer);
441 this->writeWord(resultId, fConstantBuffer);
442 for (SpvId id : types) {
443 this->writeWord(id, fConstantBuffer);
444 }
445 size_t offset = 0;
446 for (int32_t i = 0; i < (int32_t) type.fields().size(); i++) {
Ethan Nicholascc5d3e02019-04-19 09:50:56 -0400447 const Type::Field& field = type.fields()[i];
John Stiles21f5f452020-11-30 09:57:59 -0500448 if (!MemoryLayout::LayoutIsSupported(*field.fType)) {
Ethan Nicholas39f6da42021-08-23 13:10:07 -0400449 fContext.fErrors->error(type.fOffset, "type '" + field.fType->name() +
Ethan Nicholas3abc6c62021-08-13 11:20:09 -0400450 "' is not permitted here");
John Stiles0023c0c2020-11-16 13:32:18 -0500451 return;
452 }
Ethan Nicholascc5d3e02019-04-19 09:50:56 -0400453 size_t size = memoryLayout.size(*field.fType);
454 size_t alignment = memoryLayout.alignment(*field.fType);
455 const Layout& fieldLayout = field.fModifiers.fLayout;
Ethan Nicholas19671772016-11-28 16:30:17 -0500456 if (fieldLayout.fOffset >= 0) {
Greg Danieldbd44c72017-01-24 15:12:12 -0500457 if (fieldLayout.fOffset < (int) offset) {
Ethan Nicholas39f6da42021-08-23 13:10:07 -0400458 fContext.fErrors->error(type.fOffset,
Ethan Nicholas3abc6c62021-08-13 11:20:09 -0400459 "offset of field '" + field.fName + "' must be at "
460 "least " + to_string((int) offset));
Ethan Nicholas19671772016-11-28 16:30:17 -0500461 }
462 if (fieldLayout.fOffset % alignment) {
Ethan Nicholas39f6da42021-08-23 13:10:07 -0400463 fContext.fErrors->error(type.fOffset,
Ethan Nicholas3abc6c62021-08-13 11:20:09 -0400464 "offset of field '" + field.fName + "' must be a multiple"
465 " of " + to_string((int) alignment));
Ethan Nicholas19671772016-11-28 16:30:17 -0500466 }
467 offset = fieldLayout.fOffset;
468 } else {
469 size_t mod = offset % alignment;
470 if (mod) {
471 offset += alignment - mod;
472 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700473 }
Ethan Nicholascc5d3e02019-04-19 09:50:56 -0400474 this->writeInstruction(SpvOpMemberName, resultId, i, field.fName, fNameBuffer);
Ethan Nicholas19671772016-11-28 16:30:17 -0500475 this->writeLayout(fieldLayout, resultId, i);
Ethan Nicholascc5d3e02019-04-19 09:50:56 -0400476 if (field.fModifiers.fLayout.fBuiltin < 0) {
Greg Daniel64773e62016-11-22 09:44:03 -0500477 this->writeInstruction(SpvOpMemberDecorate, resultId, (SpvId) i, SpvDecorationOffset,
ethannicholasb3058bd2016-07-01 08:22:01 -0700478 (SpvId) offset, fDecorationBuffer);
479 }
John Stiles9aeed132020-11-24 17:36:06 -0500480 if (field.fType->isMatrix()) {
Greg Daniel64773e62016-11-22 09:44:03 -0500481 this->writeInstruction(SpvOpMemberDecorate, resultId, i, SpvDecorationColMajor,
ethannicholasb3058bd2016-07-01 08:22:01 -0700482 fDecorationBuffer);
Greg Daniel64773e62016-11-22 09:44:03 -0500483 this->writeInstruction(SpvOpMemberDecorate, resultId, i, SpvDecorationMatrixStride,
Ethan Nicholascc5d3e02019-04-19 09:50:56 -0400484 (SpvId) memoryLayout.stride(*field.fType),
ethannicholas8ac838d2016-11-22 08:39:36 -0800485 fDecorationBuffer);
ethannicholasb3058bd2016-07-01 08:22:01 -0700486 }
Ethan Nicholascc5d3e02019-04-19 09:50:56 -0400487 if (!field.fType->highPrecision()) {
488 this->writeInstruction(SpvOpMemberDecorate, resultId, (SpvId) i,
489 SpvDecorationRelaxedPrecision, fDecorationBuffer);
490 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700491 offset += size;
John Stilesc0c51062020-12-03 17:16:29 -0500492 if ((field.fType->isArray() || field.fType->isStruct()) && offset % alignment != 0) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700493 offset += alignment - offset % alignment;
494 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700495 }
496}
497
Ethan Nicholase2c49992020-10-05 11:49:11 -0400498const Type& SPIRVCodeGenerator::getActualType(const Type& type) {
Ethan Nicholase1f55022019-02-05 17:17:40 -0500499 if (type.isFloat()) {
John Stiles54e7c052021-01-11 14:22:36 -0500500 return *fContext.fTypes.fFloat;
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400501 }
Brian Osmanc9145f32021-07-08 13:40:10 -0400502 if (type.isSigned()) {
John Stiles54e7c052021-01-11 14:22:36 -0500503 return *fContext.fTypes.fInt;
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400504 }
Ethan Nicholase1f55022019-02-05 17:17:40 -0500505 if (type.isUnsigned()) {
John Stiles54e7c052021-01-11 14:22:36 -0500506 return *fContext.fTypes.fUInt;
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400507 }
John Stiles9aeed132020-11-24 17:36:06 -0500508 if (type.isMatrix() || type.isVector()) {
John Stiles54e7c052021-01-11 14:22:36 -0500509 if (type.componentType() == *fContext.fTypes.fHalf) {
510 return fContext.fTypes.fFloat->toCompound(fContext, type.columns(), type.rows());
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400511 }
Ethan Nicholas722c83e2021-05-04 11:39:30 -0400512 if (type.componentType() == *fContext.fTypes.fShort) {
John Stiles54e7c052021-01-11 14:22:36 -0500513 return fContext.fTypes.fInt->toCompound(fContext, type.columns(), type.rows());
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400514 }
Ethan Nicholas722c83e2021-05-04 11:39:30 -0400515 if (type.componentType() == *fContext.fTypes.fUShort) {
John Stiles54e7c052021-01-11 14:22:36 -0500516 return fContext.fTypes.fUInt->toCompound(fContext, type.columns(), type.rows());
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400517 }
518 }
519 return type;
520}
521
ethannicholasb3058bd2016-07-01 08:22:01 -0700522SpvId SPIRVCodeGenerator::getType(const Type& type) {
ethannicholas8ac838d2016-11-22 08:39:36 -0800523 return this->getType(type, fDefaultLayout);
524}
525
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400526SpvId SPIRVCodeGenerator::getType(const Type& rawType, const MemoryLayout& layout) {
John Stiles3c991fd2021-08-09 14:19:58 -0400527 const Type* type;
528 std::unique_ptr<Type> arrayType;
529 String arrayName;
530
531 if (rawType.isArray()) {
532 // For arrays, we need to synthesize a temporary Array type using the "actual" component
533 // type. That is, if `short[10]` is passed in, we need to synthesize a `int[10]` Type.
534 // Otherwise, we can end up with two different SpvIds for the same array type.
535 const Type& component = this->getActualType(rawType.componentType());
536 arrayName = component.getArrayName(rawType.columns());
537 arrayType = Type::MakeArrayType(arrayName, component, rawType.columns());
538 type = arrayType.get();
539 } else {
540 // For non-array types, we can simply look up the "actual" type and use it.
541 type = &this->getActualType(rawType);
542 }
543
544 String key(type->name());
545 if (type->isStruct() || type->isArray()) {
Jim Van Verthf3ec9832020-10-21 16:09:57 -0400546 key += to_string((int)layout.fStd);
Brian Osman2a4c0fb2021-01-22 13:41:40 -0500547#ifdef SK_DEBUG
548 SkASSERT(layout.fStd == MemoryLayout::Standard::k140_Standard ||
549 layout.fStd == MemoryLayout::Standard::k430_Standard);
550 MemoryLayout::Standard otherStd = layout.fStd == MemoryLayout::Standard::k140_Standard
551 ? MemoryLayout::Standard::k430_Standard
552 : MemoryLayout::Standard::k140_Standard;
John Stiles3c991fd2021-08-09 14:19:58 -0400553 String otherKey = type->name() + to_string((int)otherStd);
Brian Osman2a4c0fb2021-01-22 13:41:40 -0500554 SkASSERT(fTypeMap.find(otherKey) == fTypeMap.end());
555#endif
Jim Van Verthf3ec9832020-10-21 16:09:57 -0400556 }
ethannicholas8ac838d2016-11-22 08:39:36 -0800557 auto entry = fTypeMap.find(key);
ethannicholasb3058bd2016-07-01 08:22:01 -0700558 if (entry == fTypeMap.end()) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -0400559 SpvId result = this->nextId(nullptr);
John Stiles3c991fd2021-08-09 14:19:58 -0400560 switch (type->typeKind()) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400561 case Type::TypeKind::kScalar:
John Stiles3c991fd2021-08-09 14:19:58 -0400562 if (type->isBoolean()) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700563 this->writeInstruction(SpvOpTypeBool, result, fConstantBuffer);
John Stiles3c991fd2021-08-09 14:19:58 -0400564 } else if (type->isSigned()) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700565 this->writeInstruction(SpvOpTypeInt, result, 32, 1, fConstantBuffer);
John Stiles3c991fd2021-08-09 14:19:58 -0400566 } else if (type->isUnsigned()) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700567 this->writeInstruction(SpvOpTypeInt, result, 32, 0, fConstantBuffer);
John Stiles3c991fd2021-08-09 14:19:58 -0400568 } else if (type->isFloat()) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700569 this->writeInstruction(SpvOpTypeFloat, result, 32, fConstantBuffer);
ethannicholasb3058bd2016-07-01 08:22:01 -0700570 } else {
John Stiles3c991fd2021-08-09 14:19:58 -0400571 SkDEBUGFAILF("unrecognized scalar type '%s'", type->description().c_str());
ethannicholasb3058bd2016-07-01 08:22:01 -0700572 }
573 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400574 case Type::TypeKind::kVector:
Greg Daniel64773e62016-11-22 09:44:03 -0500575 this->writeInstruction(SpvOpTypeVector, result,
John Stiles3c991fd2021-08-09 14:19:58 -0400576 this->getType(type->componentType(), layout),
577 type->columns(), fConstantBuffer);
ethannicholasb3058bd2016-07-01 08:22:01 -0700578 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400579 case Type::TypeKind::kMatrix:
John Stiles51d33982021-03-08 09:18:07 -0500580 this->writeInstruction(
581 SpvOpTypeMatrix,
582 result,
John Stiles3c991fd2021-08-09 14:19:58 -0400583 this->getType(IndexExpression::IndexType(fContext, *type), layout),
584 type->columns(),
John Stiles51d33982021-03-08 09:18:07 -0500585 fConstantBuffer);
ethannicholasb3058bd2016-07-01 08:22:01 -0700586 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400587 case Type::TypeKind::kStruct:
John Stiles3c991fd2021-08-09 14:19:58 -0400588 this->writeStruct(*type, layout, result);
ethannicholasb3058bd2016-07-01 08:22:01 -0700589 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400590 case Type::TypeKind::kArray: {
John Stiles3c991fd2021-08-09 14:19:58 -0400591 if (!MemoryLayout::LayoutIsSupported(*type)) {
Ethan Nicholas39f6da42021-08-23 13:10:07 -0400592 fContext.fErrors->error(type->fOffset,
Ethan Nicholas3abc6c62021-08-13 11:20:09 -0400593 "type '" + type->name() + "' is not permitted here");
Ethan Nicholas8f352ce2021-03-17 14:12:20 -0400594 return this->nextId(nullptr);
John Stiles21f5f452020-11-30 09:57:59 -0500595 }
John Stiles3c991fd2021-08-09 14:19:58 -0400596 if (type->columns() > 0) {
597 SpvId typeId = this->getType(type->componentType(), layout);
598 IntLiteral countLiteral(/*offset=*/-1, type->columns(),
John Stiles9ce80f72021-03-11 22:35:19 -0500599 fContext.fTypes.fInt.get());
John Stilesb5db4822021-01-21 13:04:40 -0500600 SpvId countId = this->writeIntLiteral(countLiteral);
601 this->writeInstruction(SpvOpTypeArray, result, typeId, countId,
602 fConstantBuffer);
Greg Daniel64773e62016-11-22 09:44:03 -0500603 this->writeInstruction(SpvOpDecorate, result, SpvDecorationArrayStride,
John Stiles3c991fd2021-08-09 14:19:58 -0400604 (int32_t) layout.stride(*type),
ethannicholas8ac838d2016-11-22 08:39:36 -0800605 fDecorationBuffer);
ethannicholasb3058bd2016-07-01 08:22:01 -0700606 } else {
John Stiles5570c512020-11-19 17:58:07 -0500607 // We shouldn't have any runtime-sized arrays right now
Ethan Nicholas39f6da42021-08-23 13:10:07 -0400608 fContext.fErrors->error(type->fOffset,
Ethan Nicholas3abc6c62021-08-13 11:20:09 -0400609 "runtime-sized arrays are not supported in SPIR-V");
Greg Daniel64773e62016-11-22 09:44:03 -0500610 this->writeInstruction(SpvOpTypeRuntimeArray, result,
John Stiles3c991fd2021-08-09 14:19:58 -0400611 this->getType(type->componentType(), layout),
ethannicholas8ac838d2016-11-22 08:39:36 -0800612 fConstantBuffer);
Ethan Nicholas0dd30d92017-05-01 16:57:07 -0400613 this->writeInstruction(SpvOpDecorate, result, SpvDecorationArrayStride,
John Stiles3c991fd2021-08-09 14:19:58 -0400614 (int32_t) layout.stride(*type),
Ethan Nicholas0dd30d92017-05-01 16:57:07 -0400615 fDecorationBuffer);
ethannicholasb3058bd2016-07-01 08:22:01 -0700616 }
617 break;
618 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400619 case Type::TypeKind::kSampler: {
Greg Daniel64773e62016-11-22 09:44:03 -0500620 SpvId image = result;
John Stiles3c991fd2021-08-09 14:19:58 -0400621 if (SpvDimSubpassData != type->dimensions()) {
622 image = this->getType(type->textureType(), layout);
Greg Daniel64773e62016-11-22 09:44:03 -0500623 }
John Stiles3c991fd2021-08-09 14:19:58 -0400624 if (SpvDimBuffer == type->dimensions()) {
Ethan Nicholas0187ae62017-05-03 11:03:44 -0400625 fCapabilities |= (((uint64_t) 1) << SpvCapabilitySampledBuffer);
626 }
John Stiles3c991fd2021-08-09 14:19:58 -0400627 if (SpvDimSubpassData != type->dimensions()) {
Greg Daniel64773e62016-11-22 09:44:03 -0500628 this->writeInstruction(SpvOpTypeSampledImage, result, image, fConstantBuffer);
629 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700630 break;
631 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400632 case Type::TypeKind::kSeparateSampler: {
Stephen Whiteff5d7a22019-07-26 17:42:06 -0400633 this->writeInstruction(SpvOpTypeSampler, result, fConstantBuffer);
634 break;
635 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400636 case Type::TypeKind::kTexture: {
Stephen Whiteff5d7a22019-07-26 17:42:06 -0400637 this->writeInstruction(SpvOpTypeImage, result,
John Stiles54e7c052021-01-11 14:22:36 -0500638 this->getType(*fContext.fTypes.fFloat, layout),
John Stiles3c991fd2021-08-09 14:19:58 -0400639 type->dimensions(), type->isDepth(),
640 type->isArrayedTexture(), type->isMultisampled(),
641 type->isSampled() ? 1 : 2, SpvImageFormatUnknown,
642 fConstantBuffer);
Stephen Whiteff5d7a22019-07-26 17:42:06 -0400643 fImageTypeMap[key] = result;
644 break;
645 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700646 default:
John Stiles3c991fd2021-08-09 14:19:58 -0400647 if (type->isVoid()) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700648 this->writeInstruction(SpvOpTypeVoid, result, fConstantBuffer);
649 } else {
John Stiles3c991fd2021-08-09 14:19:58 -0400650 SkDEBUGFAILF("invalid type: %s", type->description().c_str());
ethannicholasb3058bd2016-07-01 08:22:01 -0700651 }
652 }
ethannicholas8ac838d2016-11-22 08:39:36 -0800653 fTypeMap[key] = result;
ethannicholasb3058bd2016-07-01 08:22:01 -0700654 return result;
655 }
656 return entry->second;
657}
658
Ethan Nicholas0187ae62017-05-03 11:03:44 -0400659SpvId SPIRVCodeGenerator::getImageType(const Type& type) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400660 SkASSERT(type.typeKind() == Type::TypeKind::kSampler);
Ethan Nicholas0187ae62017-05-03 11:03:44 -0400661 this->getType(type);
662 String key = type.name() + to_string((int) fDefaultLayout.fStd);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400663 SkASSERT(fImageTypeMap.find(key) != fImageTypeMap.end());
Ethan Nicholas0187ae62017-05-03 11:03:44 -0400664 return fImageTypeMap[key];
665}
666
ethannicholasd598f792016-07-25 10:08:54 -0700667SpvId SPIRVCodeGenerator::getFunctionType(const FunctionDeclaration& function) {
Ethan Nicholased84b732020-10-08 11:45:44 -0400668 String key = to_string(this->getType(function.returnType())) + "(";
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400669 String separator;
Brian Osman5bf3e202020-10-13 10:34:18 -0400670 const std::vector<const Variable*>& parameters = function.parameters();
Ethan Nicholased84b732020-10-08 11:45:44 -0400671 for (size_t i = 0; i < parameters.size(); i++) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700672 key += separator;
673 separator = ", ";
Ethan Nicholased84b732020-10-08 11:45:44 -0400674 key += to_string(this->getType(parameters[i]->type()));
ethannicholasb3058bd2016-07-01 08:22:01 -0700675 }
676 key += ")";
677 auto entry = fTypeMap.find(key);
678 if (entry == fTypeMap.end()) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -0400679 SpvId result = this->nextId(nullptr);
Ethan Nicholased84b732020-10-08 11:45:44 -0400680 int32_t length = 3 + (int32_t) parameters.size();
681 SpvId returnType = this->getType(function.returnType());
ethannicholasb3058bd2016-07-01 08:22:01 -0700682 std::vector<SpvId> parameterTypes;
Ethan Nicholased84b732020-10-08 11:45:44 -0400683 for (size_t i = 0; i < parameters.size(); i++) {
Greg Daniel64773e62016-11-22 09:44:03 -0500684 // glslang seems to treat all function arguments as pointers whether they need to be or
685 // not. I was initially puzzled by this until I ran bizarre failures with certain
686 // patterns of function calls and control constructs, as exemplified by this minimal
ethannicholasb3058bd2016-07-01 08:22:01 -0700687 // failure case:
688 //
689 // void sphere(float x) {
690 // }
Greg Daniel64773e62016-11-22 09:44:03 -0500691 //
ethannicholasb3058bd2016-07-01 08:22:01 -0700692 // void map() {
693 // sphere(1.0);
694 // }
Greg Daniel64773e62016-11-22 09:44:03 -0500695 //
ethannicholasb3058bd2016-07-01 08:22:01 -0700696 // void main() {
697 // for (int i = 0; i < 1; i++) {
698 // map();
699 // }
700 // }
701 //
Greg Daniel64773e62016-11-22 09:44:03 -0500702 // As of this writing, compiling this in the "obvious" way (with sphere taking a float)
703 // crashes. Making it take a float* and storing the argument in a temporary variable,
ethannicholasb3058bd2016-07-01 08:22:01 -0700704 // as glslang does, fixes it. It's entirely possible I simply missed whichever part of
705 // the spec makes this make sense.
706// if (is_out(function->fParameters[i])) {
Ethan Nicholased84b732020-10-08 11:45:44 -0400707 parameterTypes.push_back(this->getPointerType(parameters[i]->type(),
ethannicholasb3058bd2016-07-01 08:22:01 -0700708 SpvStorageClassFunction));
709// } else {
ethannicholasd598f792016-07-25 10:08:54 -0700710// parameterTypes.push_back(this->getType(function.fParameters[i]->fType));
ethannicholasb3058bd2016-07-01 08:22:01 -0700711// }
712 }
713 this->writeOpCode(SpvOpTypeFunction, length, fConstantBuffer);
714 this->writeWord(result, fConstantBuffer);
715 this->writeWord(returnType, fConstantBuffer);
716 for (SpvId id : parameterTypes) {
717 this->writeWord(id, fConstantBuffer);
718 }
719 fTypeMap[key] = result;
720 return result;
721 }
722 return entry->second;
723}
724
ethannicholas8ac838d2016-11-22 08:39:36 -0800725SpvId SPIRVCodeGenerator::getPointerType(const Type& type, SpvStorageClass_ storageClass) {
726 return this->getPointerType(type, fDefaultLayout, storageClass);
727}
728
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400729SpvId SPIRVCodeGenerator::getPointerType(const Type& rawType, const MemoryLayout& layout,
ethannicholasb3058bd2016-07-01 08:22:01 -0700730 SpvStorageClass_ storageClass) {
Ethan Nicholase2c49992020-10-05 11:49:11 -0400731 const Type& type = this->getActualType(rawType);
Ethan Nicholas2a099da2020-01-02 14:40:54 -0500732 String key = type.displayName() + "*" + to_string(layout.fStd) + to_string(storageClass);
ethannicholasb3058bd2016-07-01 08:22:01 -0700733 auto entry = fTypeMap.find(key);
734 if (entry == fTypeMap.end()) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -0400735 SpvId result = this->nextId(nullptr);
Greg Daniel64773e62016-11-22 09:44:03 -0500736 this->writeInstruction(SpvOpTypePointer, result, storageClass,
ethannicholasd598f792016-07-25 10:08:54 -0700737 this->getType(type), fConstantBuffer);
ethannicholasb3058bd2016-07-01 08:22:01 -0700738 fTypeMap[key] = result;
739 return result;
740 }
741 return entry->second;
742}
743
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400744SpvId SPIRVCodeGenerator::writeExpression(const Expression& expr, OutputStream& out) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400745 switch (expr.kind()) {
746 case Expression::Kind::kBinary:
John Stiles81365af2020-08-18 09:24:00 -0400747 return this->writeBinaryExpression(expr.as<BinaryExpression>(), out);
Ethan Nicholase6592142020-09-08 10:22:09 -0400748 case Expression::Kind::kBoolLiteral:
John Stiles81365af2020-08-18 09:24:00 -0400749 return this->writeBoolLiteral(expr.as<BoolLiteral>());
John Stilese3ae9682021-08-05 10:35:01 -0400750 case Expression::Kind::kConstructorArrayCast:
751 return this->writeExpression(*expr.as<ConstructorArrayCast>().argument(), out);
John Stiles7384b372021-04-01 13:48:15 -0400752 case Expression::Kind::kConstructorArray:
John Stilesd47330f2021-04-08 23:25:52 -0400753 case Expression::Kind::kConstructorStruct:
754 return this->writeCompositeConstructor(expr.asAnyConstructor(), out);
John Stilese1182782021-03-30 22:09:37 -0400755 case Expression::Kind::kConstructorDiagonalMatrix:
756 return this->writeConstructorDiagonalMatrix(expr.as<ConstructorDiagonalMatrix>(), out);
John Stiles5abb9e12021-04-06 13:47:19 -0400757 case Expression::Kind::kConstructorMatrixResize:
758 return this->writeConstructorMatrixResize(expr.as<ConstructorMatrixResize>(), out);
John Stilesfd7252f2021-04-04 22:24:40 -0400759 case Expression::Kind::kConstructorScalarCast:
760 return this->writeConstructorScalarCast(expr.as<ConstructorScalarCast>(), out);
John Stiles2938eea2021-04-01 18:58:25 -0400761 case Expression::Kind::kConstructorSplat:
762 return this->writeConstructorSplat(expr.as<ConstructorSplat>(), out);
John Stiles8cad6372021-04-07 12:31:13 -0400763 case Expression::Kind::kConstructorCompound:
764 return this->writeConstructorCompound(expr.as<ConstructorCompound>(), out);
765 case Expression::Kind::kConstructorCompoundCast:
766 return this->writeConstructorCompoundCast(expr.as<ConstructorCompoundCast>(), out);
Ethan Nicholase6592142020-09-08 10:22:09 -0400767 case Expression::Kind::kIntLiteral:
John Stiles81365af2020-08-18 09:24:00 -0400768 return this->writeIntLiteral(expr.as<IntLiteral>());
Ethan Nicholase6592142020-09-08 10:22:09 -0400769 case Expression::Kind::kFieldAccess:
John Stiles81365af2020-08-18 09:24:00 -0400770 return this->writeFieldAccess(expr.as<FieldAccess>(), out);
Ethan Nicholase6592142020-09-08 10:22:09 -0400771 case Expression::Kind::kFloatLiteral:
John Stiles81365af2020-08-18 09:24:00 -0400772 return this->writeFloatLiteral(expr.as<FloatLiteral>());
Ethan Nicholase6592142020-09-08 10:22:09 -0400773 case Expression::Kind::kFunctionCall:
John Stiles81365af2020-08-18 09:24:00 -0400774 return this->writeFunctionCall(expr.as<FunctionCall>(), out);
Ethan Nicholase6592142020-09-08 10:22:09 -0400775 case Expression::Kind::kPrefix:
John Stiles81365af2020-08-18 09:24:00 -0400776 return this->writePrefixExpression(expr.as<PrefixExpression>(), out);
Ethan Nicholase6592142020-09-08 10:22:09 -0400777 case Expression::Kind::kPostfix:
John Stiles81365af2020-08-18 09:24:00 -0400778 return this->writePostfixExpression(expr.as<PostfixExpression>(), out);
Ethan Nicholase6592142020-09-08 10:22:09 -0400779 case Expression::Kind::kSwizzle:
John Stiles81365af2020-08-18 09:24:00 -0400780 return this->writeSwizzle(expr.as<Swizzle>(), out);
Ethan Nicholase6592142020-09-08 10:22:09 -0400781 case Expression::Kind::kVariableReference:
John Stiles81365af2020-08-18 09:24:00 -0400782 return this->writeVariableReference(expr.as<VariableReference>(), out);
Ethan Nicholase6592142020-09-08 10:22:09 -0400783 case Expression::Kind::kTernary:
John Stiles81365af2020-08-18 09:24:00 -0400784 return this->writeTernaryExpression(expr.as<TernaryExpression>(), out);
Ethan Nicholase6592142020-09-08 10:22:09 -0400785 case Expression::Kind::kIndex:
John Stiles81365af2020-08-18 09:24:00 -0400786 return this->writeIndexExpression(expr.as<IndexExpression>(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -0700787 default:
John Stileseada7bc2021-02-02 16:29:32 -0500788 SkDEBUGFAILF("unsupported expression: %s", expr.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -0500789 break;
ethannicholasb3058bd2016-07-01 08:22:01 -0700790 }
791 return -1;
792}
793
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400794SpvId SPIRVCodeGenerator::writeIntrinsicCall(const FunctionCall& c, OutputStream& out) {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400795 const FunctionDeclaration& function = c.function();
John Stilesaaac4e42021-05-06 14:08:28 -0400796 auto intrinsic = fIntrinsicMap.find(function.intrinsicKind());
John Stiles93e661a2020-12-08 16:17:00 -0500797 if (intrinsic == fIntrinsicMap.end()) {
Ethan Nicholas39f6da42021-08-23 13:10:07 -0400798 fContext.fErrors->error(c.fOffset, "unsupported intrinsic '" + function.description() +
Ethan Nicholas3abc6c62021-08-13 11:20:09 -0400799 "'");
John Stiles93e661a2020-12-08 16:17:00 -0500800 return -1;
801 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700802 int32_t intrinsicId;
John Stiles89ac7c22020-12-30 17:47:31 -0500803 const ExpressionArray& arguments = c.arguments();
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400804 if (arguments.size() > 0) {
805 const Type& type = arguments[0]->type();
John Stilesaaac4e42021-05-06 14:08:28 -0400806 if (std::get<0>(intrinsic->second) == kSpecial_IntrinsicOpcodeKind ||
807 is_float(fContext, type)) {
Ethan Nicholasbb155e22017-07-24 10:05:09 -0400808 intrinsicId = std::get<1>(intrinsic->second);
809 } else if (is_signed(fContext, type)) {
810 intrinsicId = std::get<2>(intrinsic->second);
811 } else if (is_unsigned(fContext, type)) {
812 intrinsicId = std::get<3>(intrinsic->second);
813 } else if (is_bool(fContext, type)) {
814 intrinsicId = std::get<4>(intrinsic->second);
815 } else {
816 intrinsicId = std::get<1>(intrinsic->second);
817 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700818 } else {
Ethan Nicholasbb155e22017-07-24 10:05:09 -0400819 intrinsicId = std::get<1>(intrinsic->second);
ethannicholasb3058bd2016-07-01 08:22:01 -0700820 }
821 switch (std::get<0>(intrinsic->second)) {
John Stilesaaac4e42021-05-06 14:08:28 -0400822 case kGLSL_STD_450_IntrinsicOpcodeKind: {
Ethan Nicholas7f015882021-03-23 14:16:52 -0400823 SpvId result = this->nextId(&c.type());
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400824 std::vector<SpvId> argumentIds;
825 for (size_t i = 0; i < arguments.size(); i++) {
Ethan Nicholased84b732020-10-08 11:45:44 -0400826 if (function.parameters()[i]->modifiers().fFlags & Modifiers::kOut_Flag) {
John Stilesec241542021-02-11 17:50:09 -0500827 // TODO(skia:11052): swizzled lvalues won't work with getPointer()
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400828 argumentIds.push_back(this->getLValue(*arguments[i], out)->getPointer());
Ethan Nicholas8f7e28f2018-03-26 14:24:27 -0400829 } else {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400830 argumentIds.push_back(this->writeExpression(*arguments[i], out));
Ethan Nicholas8f7e28f2018-03-26 14:24:27 -0400831 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700832 }
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400833 this->writeOpCode(SpvOpExtInst, 5 + (int32_t) argumentIds.size(), out);
Ethan Nicholas30d30222020-09-11 12:27:26 -0400834 this->writeWord(this->getType(c.type()), out);
ethannicholasb3058bd2016-07-01 08:22:01 -0700835 this->writeWord(result, out);
836 this->writeWord(fGLSLExtendedInstructions, out);
837 this->writeWord(intrinsicId, out);
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400838 for (SpvId id : argumentIds) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700839 this->writeWord(id, out);
840 }
841 return result;
842 }
John Stilesaaac4e42021-05-06 14:08:28 -0400843 case kSPIRV_IntrinsicOpcodeKind: {
Brian Osman46787d52020-11-24 14:18:23 -0500844 // GLSL supports dot(float, float), but SPIR-V does not. Convert it to FMul
John Stiles9aeed132020-11-24 17:36:06 -0500845 if (intrinsicId == SpvOpDot && arguments[0]->type().isScalar()) {
Brian Osman46787d52020-11-24 14:18:23 -0500846 intrinsicId = SpvOpFMul;
847 }
Ethan Nicholas7f015882021-03-23 14:16:52 -0400848 SpvId result = this->nextId(&c.type());
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400849 std::vector<SpvId> argumentIds;
850 for (size_t i = 0; i < arguments.size(); i++) {
Ethan Nicholased84b732020-10-08 11:45:44 -0400851 if (function.parameters()[i]->modifiers().fFlags & Modifiers::kOut_Flag) {
John Stilesec241542021-02-11 17:50:09 -0500852 // TODO(skia:11052): swizzled lvalues won't work with getPointer()
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400853 argumentIds.push_back(this->getLValue(*arguments[i], out)->getPointer());
Ethan Nicholas8f7e28f2018-03-26 14:24:27 -0400854 } else {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400855 argumentIds.push_back(this->writeExpression(*arguments[i], out));
Ethan Nicholas8f7e28f2018-03-26 14:24:27 -0400856 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700857 }
John Stiles2558c462021-03-16 17:49:20 -0400858 if (!c.type().isVoid()) {
Ethan Nicholasbb155e22017-07-24 10:05:09 -0400859 this->writeOpCode((SpvOp_) intrinsicId, 3 + (int32_t) arguments.size(), out);
Ethan Nicholas30d30222020-09-11 12:27:26 -0400860 this->writeWord(this->getType(c.type()), out);
Ethan Nicholasbb155e22017-07-24 10:05:09 -0400861 this->writeWord(result, out);
862 } else {
863 this->writeOpCode((SpvOp_) intrinsicId, 1 + (int32_t) arguments.size(), out);
864 }
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400865 for (SpvId id : argumentIds) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700866 this->writeWord(id, out);
867 }
868 return result;
869 }
John Stilesaaac4e42021-05-06 14:08:28 -0400870 case kSpecial_IntrinsicOpcodeKind:
ethannicholasb3058bd2016-07-01 08:22:01 -0700871 return this->writeSpecialIntrinsic(c, (SpecialIntrinsic) intrinsicId, out);
872 default:
Ethan Nicholas39f6da42021-08-23 13:10:07 -0400873 fContext.fErrors->error(c.fOffset, "unsupported intrinsic '" + function.description() +
Ethan Nicholas3abc6c62021-08-13 11:20:09 -0400874 "'");
John Stiles93e661a2020-12-08 16:17:00 -0500875 return -1;
ethannicholasb3058bd2016-07-01 08:22:01 -0700876 }
877}
878
Brian Salomond8d85b92021-07-07 09:41:17 -0400879SpvId SPIRVCodeGenerator::vectorize(const Expression& arg, int vectorSize, OutputStream& out) {
880 SkASSERT(vectorSize >= 1 && vectorSize <= 4);
881 const Type& argType = arg.type();
882 SpvId raw = this->writeExpression(arg, out);
883 if (argType.isScalar()) {
884 if (vectorSize == 1) {
885 return raw;
886 }
887 SpvId vector = this->nextId(&argType);
888 this->writeOpCode(SpvOpCompositeConstruct, 3 + vectorSize, out);
889 this->writeWord(this->getType(argType.toCompound(fContext, vectorSize, 1)), out);
890 this->writeWord(vector, out);
891 for (int i = 0; i < vectorSize; i++) {
892 this->writeWord(raw, out);
893 }
894 return vector;
895 } else {
896 SkASSERT(vectorSize == argType.columns());
897 return raw;
898 }
899}
900
John Stiles8e3b6be2020-10-13 11:14:08 -0400901std::vector<SpvId> SPIRVCodeGenerator::vectorize(const ExpressionArray& args, OutputStream& out) {
Brian Salomond8d85b92021-07-07 09:41:17 -0400902 int vectorSize = 1;
Ethan Nicholas0fc07f92018-02-27 15:25:47 -0500903 for (const auto& a : args) {
John Stiles9aeed132020-11-24 17:36:06 -0500904 if (a->type().isVector()) {
Brian Salomond8d85b92021-07-07 09:41:17 -0400905 if (vectorSize > 1) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400906 SkASSERT(a->type().columns() == vectorSize);
Brian Salomond8d85b92021-07-07 09:41:17 -0400907 } else {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400908 vectorSize = a->type().columns();
Ethan Nicholas0fc07f92018-02-27 15:25:47 -0500909 }
910 }
911 }
912 std::vector<SpvId> result;
John Stiles8e3b6be2020-10-13 11:14:08 -0400913 result.reserve(args.size());
Ethan Nicholas30d30222020-09-11 12:27:26 -0400914 for (const auto& arg : args) {
Brian Salomond8d85b92021-07-07 09:41:17 -0400915 result.push_back(this->vectorize(*arg, vectorSize, out));
Ethan Nicholas0fc07f92018-02-27 15:25:47 -0500916 }
917 return result;
918}
919
920void SPIRVCodeGenerator::writeGLSLExtendedInstruction(const Type& type, SpvId id, SpvId floatInst,
921 SpvId signedInst, SpvId unsignedInst,
922 const std::vector<SpvId>& args,
923 OutputStream& out) {
924 this->writeOpCode(SpvOpExtInst, 5 + args.size(), out);
925 this->writeWord(this->getType(type), out);
926 this->writeWord(id, out);
927 this->writeWord(fGLSLExtendedInstructions, out);
928
929 if (is_float(fContext, type)) {
930 this->writeWord(floatInst, out);
931 } else if (is_signed(fContext, type)) {
932 this->writeWord(signedInst, out);
933 } else if (is_unsigned(fContext, type)) {
934 this->writeWord(unsignedInst, out);
935 } else {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400936 SkASSERT(false);
Ethan Nicholas0fc07f92018-02-27 15:25:47 -0500937 }
938 for (SpvId a : args) {
939 this->writeWord(a, out);
940 }
941}
942
Greg Daniel64773e62016-11-22 09:44:03 -0500943SpvId SPIRVCodeGenerator::writeSpecialIntrinsic(const FunctionCall& c, SpecialIntrinsic kind,
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400944 OutputStream& out) {
John Stiles8e3b6be2020-10-13 11:14:08 -0400945 const ExpressionArray& arguments = c.arguments();
Ethan Nicholas30d30222020-09-11 12:27:26 -0400946 const Type& callType = c.type();
Ethan Nicholas8f352ce2021-03-17 14:12:20 -0400947 SpvId result = this->nextId(nullptr);
ethannicholasb3058bd2016-07-01 08:22:01 -0700948 switch (kind) {
949 case kAtan_SpecialIntrinsic: {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400950 std::vector<SpvId> argumentIds;
951 for (const std::unique_ptr<Expression>& arg : arguments) {
952 argumentIds.push_back(this->writeExpression(*arg, out));
ethannicholasb3058bd2016-07-01 08:22:01 -0700953 }
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400954 this->writeOpCode(SpvOpExtInst, 5 + (int32_t) argumentIds.size(), out);
Ethan Nicholas30d30222020-09-11 12:27:26 -0400955 this->writeWord(this->getType(callType), out);
ethannicholasb3058bd2016-07-01 08:22:01 -0700956 this->writeWord(result, out);
957 this->writeWord(fGLSLExtendedInstructions, out);
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400958 this->writeWord(argumentIds.size() == 2 ? GLSLstd450Atan2 : GLSLstd450Atan, out);
959 for (SpvId id : argumentIds) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700960 this->writeWord(id, out);
961 }
Ethan Nicholas0187ae62017-05-03 11:03:44 -0400962 break;
963 }
Stephen Whiteff5d7a22019-07-26 17:42:06 -0400964 case kSampledImage_SpecialIntrinsic: {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400965 SkASSERT(arguments.size() == 2);
966 SpvId img = this->writeExpression(*arguments[0], out);
967 SpvId sampler = this->writeExpression(*arguments[1], out);
Stephen Whiteff5d7a22019-07-26 17:42:06 -0400968 this->writeInstruction(SpvOpSampledImage,
Ethan Nicholas30d30222020-09-11 12:27:26 -0400969 this->getType(callType),
Stephen Whiteff5d7a22019-07-26 17:42:06 -0400970 result,
971 img,
972 sampler,
973 out);
974 break;
975 }
Ethan Nicholas0187ae62017-05-03 11:03:44 -0400976 case kSubpassLoad_SpecialIntrinsic: {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400977 SpvId img = this->writeExpression(*arguments[0], out);
John Stiles8e3b6be2020-10-13 11:14:08 -0400978 ExpressionArray args;
John Stilesf4bda742020-10-14 16:57:41 -0400979 args.reserve_back(2);
John Stiles9ce80f72021-03-11 22:35:19 -0500980 args.push_back(IntLiteral::Make(fContext, /*offset=*/-1, /*value=*/0));
981 args.push_back(IntLiteral::Make(fContext, /*offset=*/-1, /*value=*/0));
John Stiles8cad6372021-04-07 12:31:13 -0400982 ConstructorCompound ctor(/*offset=*/-1, *fContext.fTypes.fInt2, std::move(args));
Ethan Nicholas0187ae62017-05-03 11:03:44 -0400983 SpvId coords = this->writeConstantVector(ctor);
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400984 if (arguments.size() == 1) {
Ethan Nicholas0187ae62017-05-03 11:03:44 -0400985 this->writeInstruction(SpvOpImageRead,
Ethan Nicholas30d30222020-09-11 12:27:26 -0400986 this->getType(callType),
Ethan Nicholas0187ae62017-05-03 11:03:44 -0400987 result,
988 img,
989 coords,
990 out);
991 } else {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400992 SkASSERT(arguments.size() == 2);
993 SpvId sample = this->writeExpression(*arguments[1], out);
Ethan Nicholas0187ae62017-05-03 11:03:44 -0400994 this->writeInstruction(SpvOpImageRead,
Ethan Nicholas30d30222020-09-11 12:27:26 -0400995 this->getType(callType),
Ethan Nicholas0187ae62017-05-03 11:03:44 -0400996 result,
997 img,
998 coords,
999 SpvImageOperandsSampleMask,
1000 sample,
1001 out);
1002 }
1003 break;
1004 }
ethannicholasb3058bd2016-07-01 08:22:01 -07001005 case kTexture_SpecialIntrinsic: {
Ethan Nicholas2b3dab62016-11-28 12:03:26 -05001006 SpvOp_ op = SpvOpImageSampleImplicitLod;
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001007 const Type& arg1Type = arguments[1]->type();
1008 switch (arguments[0]->type().dimensions()) {
Ethan Nicholas2b3dab62016-11-28 12:03:26 -05001009 case SpvDim1D:
John Stiles54e7c052021-01-11 14:22:36 -05001010 if (arg1Type == *fContext.fTypes.fFloat2) {
Ethan Nicholas2b3dab62016-11-28 12:03:26 -05001011 op = SpvOpImageSampleProjImplicitLod;
1012 } else {
John Stiles54e7c052021-01-11 14:22:36 -05001013 SkASSERT(arg1Type == *fContext.fTypes.fFloat);
Ethan Nicholas2b3dab62016-11-28 12:03:26 -05001014 }
1015 break;
1016 case SpvDim2D:
John Stiles54e7c052021-01-11 14:22:36 -05001017 if (arg1Type == *fContext.fTypes.fFloat3) {
Ethan Nicholas2b3dab62016-11-28 12:03:26 -05001018 op = SpvOpImageSampleProjImplicitLod;
1019 } else {
John Stiles54e7c052021-01-11 14:22:36 -05001020 SkASSERT(arg1Type == *fContext.fTypes.fFloat2);
Ethan Nicholas2b3dab62016-11-28 12:03:26 -05001021 }
1022 break;
1023 case SpvDim3D:
John Stiles54e7c052021-01-11 14:22:36 -05001024 if (arg1Type == *fContext.fTypes.fFloat4) {
Ethan Nicholas2b3dab62016-11-28 12:03:26 -05001025 op = SpvOpImageSampleProjImplicitLod;
1026 } else {
John Stiles54e7c052021-01-11 14:22:36 -05001027 SkASSERT(arg1Type == *fContext.fTypes.fFloat3);
Ethan Nicholas2b3dab62016-11-28 12:03:26 -05001028 }
1029 break;
1030 case SpvDimCube: // fall through
1031 case SpvDimRect: // fall through
1032 case SpvDimBuffer: // fall through
1033 case SpvDimSubpassData:
1034 break;
1035 }
Ethan Nicholas30d30222020-09-11 12:27:26 -04001036 SpvId type = this->getType(callType);
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001037 SpvId sampler = this->writeExpression(*arguments[0], out);
1038 SpvId uv = this->writeExpression(*arguments[1], out);
1039 if (arguments.size() == 3) {
Ethan Nicholas2b3dab62016-11-28 12:03:26 -05001040 this->writeInstruction(op, type, result, sampler, uv,
ethannicholasb3058bd2016-07-01 08:22:01 -07001041 SpvImageOperandsBiasMask,
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001042 this->writeExpression(*arguments[2], out),
ethannicholasb3058bd2016-07-01 08:22:01 -07001043 out);
1044 } else {
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001045 SkASSERT(arguments.size() == 2);
John Stiles270cec22021-02-17 12:59:36 -05001046 if (fProgram.fConfig->fSettings.fSharpenTextures) {
John Stiles9ce80f72021-03-11 22:35:19 -05001047 FloatLiteral lodBias(/*offset=*/-1, /*value=*/-0.5,
1048 fContext.fTypes.fFloat.get());
Brian Osman8a83ca42018-02-12 14:32:17 -05001049 this->writeInstruction(op, type, result, sampler, uv,
1050 SpvImageOperandsBiasMask,
1051 this->writeFloatLiteral(lodBias),
1052 out);
1053 } else {
1054 this->writeInstruction(op, type, result, sampler, uv,
1055 out);
1056 }
ethannicholasb3058bd2016-07-01 08:22:01 -07001057 }
1058 break;
1059 }
Ethan Nicholas70a44b22017-11-30 09:09:16 -05001060 case kMod_SpecialIntrinsic: {
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001061 std::vector<SpvId> args = this->vectorize(arguments, out);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001062 SkASSERT(args.size() == 2);
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001063 const Type& operandType = arguments[0]->type();
Ethan Nicholas70a44b22017-11-30 09:09:16 -05001064 SpvOp_ op;
1065 if (is_float(fContext, operandType)) {
1066 op = SpvOpFMod;
1067 } else if (is_signed(fContext, operandType)) {
1068 op = SpvOpSMod;
1069 } else if (is_unsigned(fContext, operandType)) {
1070 op = SpvOpUMod;
1071 } else {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001072 SkASSERT(false);
Ethan Nicholas70a44b22017-11-30 09:09:16 -05001073 return 0;
1074 }
1075 this->writeOpCode(op, 5, out);
1076 this->writeWord(this->getType(operandType), out);
1077 this->writeWord(result, out);
Ethan Nicholas0fc07f92018-02-27 15:25:47 -05001078 this->writeWord(args[0], out);
1079 this->writeWord(args[1], out);
1080 break;
1081 }
Chris Daltonb8af5ad2019-02-25 14:54:21 -07001082 case kDFdy_SpecialIntrinsic: {
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001083 SpvId fn = this->writeExpression(*arguments[0], out);
Chris Daltonb8af5ad2019-02-25 14:54:21 -07001084 this->writeOpCode(SpvOpDPdy, 4, out);
Ethan Nicholas30d30222020-09-11 12:27:26 -04001085 this->writeWord(this->getType(callType), out);
Chris Daltonb8af5ad2019-02-25 14:54:21 -07001086 this->writeWord(result, out);
1087 this->writeWord(fn, out);
Brian Salomond8d85b92021-07-07 09:41:17 -04001088 this->addRTFlipUniform(c.fOffset);
1089 using namespace dsl;
1090 DSLExpression rtFlip(DSLWriter::IRGenerator().convertIdentifier(/*offset=*/-1,
1091 SKSL_RTFLIP_NAME));
1092 SpvId rtFlipY = this->vectorize(*rtFlip.y().release(), callType.columns(), out);
1093 SpvId flipped = this->nextId(&callType);
1094 this->writeInstruction(SpvOpFMul, this->getType(callType), flipped, result, rtFlipY,
1095 out);
1096 result = flipped;
Chris Daltonb8af5ad2019-02-25 14:54:21 -07001097 break;
1098 }
Ethan Nicholas0fc07f92018-02-27 15:25:47 -05001099 case kClamp_SpecialIntrinsic: {
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001100 std::vector<SpvId> args = this->vectorize(arguments, out);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001101 SkASSERT(args.size() == 3);
Ethan Nicholas30d30222020-09-11 12:27:26 -04001102 this->writeGLSLExtendedInstruction(callType, result, GLSLstd450FClamp, GLSLstd450SClamp,
Ethan Nicholas0fc07f92018-02-27 15:25:47 -05001103 GLSLstd450UClamp, args, out);
1104 break;
1105 }
1106 case kMax_SpecialIntrinsic: {
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001107 std::vector<SpvId> args = this->vectorize(arguments, out);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001108 SkASSERT(args.size() == 2);
Ethan Nicholas30d30222020-09-11 12:27:26 -04001109 this->writeGLSLExtendedInstruction(callType, result, GLSLstd450FMax, GLSLstd450SMax,
Ethan Nicholas0fc07f92018-02-27 15:25:47 -05001110 GLSLstd450UMax, args, out);
1111 break;
1112 }
1113 case kMin_SpecialIntrinsic: {
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001114 std::vector<SpvId> args = this->vectorize(arguments, out);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001115 SkASSERT(args.size() == 2);
Ethan Nicholas30d30222020-09-11 12:27:26 -04001116 this->writeGLSLExtendedInstruction(callType, result, GLSLstd450FMin, GLSLstd450SMin,
Ethan Nicholas0fc07f92018-02-27 15:25:47 -05001117 GLSLstd450UMin, args, out);
1118 break;
1119 }
1120 case kMix_SpecialIntrinsic: {
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001121 std::vector<SpvId> args = this->vectorize(arguments, out);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001122 SkASSERT(args.size() == 3);
John Stilescc2d9cc2021-07-09 17:38:41 -04001123 if (arguments[2]->type().componentType().isBoolean()) {
1124 // Use OpSelect to implement Boolean mix().
1125 SpvId falseId = this->writeExpression(*arguments[0], out);
1126 SpvId trueId = this->writeExpression(*arguments[1], out);
1127 SpvId conditionId = this->writeExpression(*arguments[2], out);
1128 this->writeInstruction(SpvOpSelect, this->getType(arguments[0]->type()), result,
1129 conditionId, trueId, falseId, out);
1130 } else {
1131 this->writeGLSLExtendedInstruction(callType, result, GLSLstd450FMix, SpvOpUndef,
1132 SpvOpUndef, args, out);
1133 }
Ethan Nicholas0fc07f92018-02-27 15:25:47 -05001134 break;
Ethan Nicholas70a44b22017-11-30 09:09:16 -05001135 }
Ethan Nicholas12fb9cf2018-08-03 16:16:57 -04001136 case kSaturate_SpecialIntrinsic: {
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001137 SkASSERT(arguments.size() == 1);
John Stiles8e3b6be2020-10-13 11:14:08 -04001138 ExpressionArray finalArgs;
John Stilesf4bda742020-10-14 16:57:41 -04001139 finalArgs.reserve_back(3);
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001140 finalArgs.push_back(arguments[0]->clone());
John Stiles9ce80f72021-03-11 22:35:19 -05001141 finalArgs.push_back(FloatLiteral::Make(fContext, /*offset=*/-1, /*value=*/0));
1142 finalArgs.push_back(FloatLiteral::Make(fContext, /*offset=*/-1, /*value=*/1));
Ethan Nicholas12fb9cf2018-08-03 16:16:57 -04001143 std::vector<SpvId> spvArgs = this->vectorize(finalArgs, out);
Ethan Nicholas30d30222020-09-11 12:27:26 -04001144 this->writeGLSLExtendedInstruction(callType, result, GLSLstd450FClamp, GLSLstd450SClamp,
Ethan Nicholas12fb9cf2018-08-03 16:16:57 -04001145 GLSLstd450UClamp, spvArgs, out);
1146 break;
1147 }
Brian Osman6ba3be12020-11-13 16:32:52 -05001148 case kSmoothStep_SpecialIntrinsic: {
1149 std::vector<SpvId> args = this->vectorize(arguments, out);
1150 SkASSERT(args.size() == 3);
1151 this->writeGLSLExtendedInstruction(callType, result, GLSLstd450SmoothStep, SpvOpUndef,
1152 SpvOpUndef, args, out);
1153 break;
1154 }
1155 case kStep_SpecialIntrinsic: {
1156 std::vector<SpvId> args = this->vectorize(arguments, out);
1157 SkASSERT(args.size() == 2);
1158 this->writeGLSLExtendedInstruction(callType, result, GLSLstd450Step, SpvOpUndef,
1159 SpvOpUndef, args, out);
1160 break;
1161 }
Brian Osmand1b593f2020-12-28 13:00:46 -05001162 case kMatrixCompMult_SpecialIntrinsic: {
1163 SkASSERT(arguments.size() == 2);
1164 SpvId lhs = this->writeExpression(*arguments[0], out);
1165 SpvId rhs = this->writeExpression(*arguments[1], out);
John Stiles43b593c2021-05-13 22:03:27 -04001166 result = this->writeComponentwiseMatrixBinary(callType, lhs, rhs, SpvOpFMul, out);
Brian Osmand1b593f2020-12-28 13:00:46 -05001167 break;
1168 }
ethannicholasb3058bd2016-07-01 08:22:01 -07001169 }
1170 return result;
1171}
1172
John Stilesec241542021-02-11 17:50:09 -05001173namespace {
1174struct TempVar {
1175 SpvId spvId;
1176 const Type* type;
1177 std::unique_ptr<SPIRVCodeGenerator::LValue> lvalue;
1178};
1179}
1180
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001181SpvId SPIRVCodeGenerator::writeFunctionCall(const FunctionCall& c, OutputStream& out) {
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001182 const FunctionDeclaration& function = c.function();
John Stilesaaac4e42021-05-06 14:08:28 -04001183 if (function.isIntrinsic() && !function.definition()) {
John Stiles89ac7c22020-12-30 17:47:31 -05001184 return this->writeIntrinsicCall(c, out);
1185 }
John Stiles8e3b6be2020-10-13 11:14:08 -04001186 const ExpressionArray& arguments = c.arguments();
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001187 const auto& entry = fFunctionMap.find(&function);
ethannicholasb3058bd2016-07-01 08:22:01 -07001188 if (entry == fFunctionMap.end()) {
Ethan Nicholas39f6da42021-08-23 13:10:07 -04001189 fContext.fErrors->error(c.fOffset, "function '" + function.description() +
Ethan Nicholas3abc6c62021-08-13 11:20:09 -04001190 "' is not defined");
John Stiles89ac7c22020-12-30 17:47:31 -05001191 return -1;
ethannicholasb3058bd2016-07-01 08:22:01 -07001192 }
John Stilesec241542021-02-11 17:50:09 -05001193 // Temp variables are used to write back out-parameters after the function call is complete.
1194 std::vector<TempVar> tempVars;
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001195 std::vector<SpvId> argumentIds;
1196 for (size_t i = 0; i < arguments.size(); i++) {
Greg Daniel64773e62016-11-22 09:44:03 -05001197 // id of temporary variable that we will use to hold this argument, or 0 if it is being
ethannicholasb3058bd2016-07-01 08:22:01 -07001198 // passed directly
1199 SpvId tmpVar;
1200 // if we need a temporary var to store this argument, this is the value to store in the var
John Stiles6a51b202021-09-08 10:45:08 -04001201 SpvId tmpValueId = -1;
Ethan Nicholased84b732020-10-08 11:45:44 -04001202 if (is_out(*function.parameters()[i])) {
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001203 std::unique_ptr<LValue> lv = this->getLValue(*arguments[i], out);
ethannicholasb3058bd2016-07-01 08:22:01 -07001204 SpvId ptr = lv->getPointer();
Ethan Nicholase0707b72021-03-17 11:16:41 -04001205 if (ptr != (SpvId) -1 && lv->isMemoryObjectPointer()) {
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001206 argumentIds.push_back(ptr);
ethannicholasb3058bd2016-07-01 08:22:01 -07001207 continue;
1208 } else {
1209 // lvalue cannot simply be read and written via a pointer (e.g. a swizzle). Need to
1210 // copy it into a temp, call the function, read the value out of the temp, and then
1211 // update the lvalue.
John Stiles6a51b202021-09-08 10:45:08 -04001212 if (is_in(*function.parameters()[i])) {
1213 tmpValueId = lv->load(out);
1214 }
John Stiles30f86112021-09-08 08:48:26 -04001215 tmpVar = this->nextId(&arguments[i]->type());
John Stilesec241542021-02-11 17:50:09 -05001216 tempVars.push_back(TempVar{tmpVar, &arguments[i]->type(), std::move(lv)});
ethannicholasb3058bd2016-07-01 08:22:01 -07001217 }
1218 } else {
John Stilesec241542021-02-11 17:50:09 -05001219 // See getFunctionType for an explanation of why we're always using pointer parameters.
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001220 tmpValueId = this->writeExpression(*arguments[i], out);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001221 tmpVar = this->nextId(nullptr);
ethannicholasb3058bd2016-07-01 08:22:01 -07001222 }
Greg Daniel64773e62016-11-22 09:44:03 -05001223 this->writeInstruction(SpvOpVariable,
John Stilesec241542021-02-11 17:50:09 -05001224 this->getPointerType(arguments[i]->type(), SpvStorageClassFunction),
Greg Daniel64773e62016-11-22 09:44:03 -05001225 tmpVar,
ethannicholasb3058bd2016-07-01 08:22:01 -07001226 SpvStorageClassFunction,
ethannicholasd598f792016-07-25 10:08:54 -07001227 fVariableBuffer);
John Stiles6a51b202021-09-08 10:45:08 -04001228 if (tmpValueId != (SpvId)-1) {
1229 this->writeInstruction(SpvOpStore, tmpVar, tmpValueId, out);
1230 }
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001231 argumentIds.push_back(tmpVar);
ethannicholasb3058bd2016-07-01 08:22:01 -07001232 }
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001233 SpvId result = this->nextId(nullptr);
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001234 this->writeOpCode(SpvOpFunctionCall, 4 + (int32_t) arguments.size(), out);
Ethan Nicholas30d30222020-09-11 12:27:26 -04001235 this->writeWord(this->getType(c.type()), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07001236 this->writeWord(result, out);
1237 this->writeWord(entry->second, out);
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001238 for (SpvId id : argumentIds) {
ethannicholasb3058bd2016-07-01 08:22:01 -07001239 this->writeWord(id, out);
1240 }
John Stilesec241542021-02-11 17:50:09 -05001241 // Now that the call is complete, we copy temp out-variables back to their real lvalues.
1242 for (const TempVar& tempVar : tempVars) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001243 SpvId load = this->nextId(tempVar.type);
John Stilesec241542021-02-11 17:50:09 -05001244 this->writeInstruction(SpvOpLoad, getType(*tempVar.type), load, tempVar.spvId, out);
John Stilesec241542021-02-11 17:50:09 -05001245 tempVar.lvalue->store(load, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07001246 }
1247 return result;
1248}
1249
John Stiles2938eea2021-04-01 18:58:25 -04001250SpvId SPIRVCodeGenerator::writeConstantVector(const AnyConstructor& c) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001251 const Type& type = c.type();
John Stiles9aeed132020-11-24 17:36:06 -05001252 SkASSERT(type.isVector() && c.isCompileTimeConstant());
John Stilescd806892021-01-06 13:33:31 -05001253
John Stiles9cfaa4f2021-01-06 17:52:00 -05001254 // Get each of the constructor components as SPIR-V constants.
John Stilescd806892021-01-06 13:33:31 -05001255 SPIRVVectorConstant key{this->getType(type),
1256 /*fValueId=*/{SpvId(-1), SpvId(-1), SpvId(-1), SpvId(-1)}};
John Stiles9cfaa4f2021-01-06 17:52:00 -05001257
John Stiles21a50ec2021-04-06 14:49:36 -04001258 for (int n = 0; n < type.columns(); n++) {
1259 const Expression* expr = c.getConstantSubexpression(n);
1260 if (!expr) {
1261 SkDEBUGFAILF("writeConstantVector: %s not actually constant", c.description().c_str());
1262 return (SpvId)-1;
John Stiles9cfaa4f2021-01-06 17:52:00 -05001263 }
John Stiles21a50ec2021-04-06 14:49:36 -04001264 key.fValueId[n] = this->writeExpression(*expr, fConstantBuffer);
ethannicholasb3058bd2016-07-01 08:22:01 -07001265 }
John Stilescd806892021-01-06 13:33:31 -05001266
1267 // Check to see if we've already synthesized this vector constant.
1268 auto [iter, newlyCreated] = fVectorConstants.insert({key, (SpvId)-1});
1269 if (newlyCreated) {
1270 // Emit an OpConstantComposite instruction for this constant.
Ethan Nicholas7f015882021-03-23 14:16:52 -04001271 SpvId result = this->nextId(&type);
John Stiles9cfaa4f2021-01-06 17:52:00 -05001272 this->writeOpCode(SpvOpConstantComposite, 3 + type.columns(), fConstantBuffer);
John Stilescd806892021-01-06 13:33:31 -05001273 this->writeWord(key.fTypeId, fConstantBuffer);
1274 this->writeWord(result, fConstantBuffer);
John Stiles9cfaa4f2021-01-06 17:52:00 -05001275 for (int i = 0; i < type.columns(); i++) {
John Stilescd806892021-01-06 13:33:31 -05001276 this->writeWord(key.fValueId[i], fConstantBuffer);
1277 }
1278 iter->second = result;
1279 }
1280 return iter->second;
ethannicholasb3058bd2016-07-01 08:22:01 -07001281}
1282
John Stilesb14a8192021-04-05 11:40:46 -04001283SpvId SPIRVCodeGenerator::castScalarToType(SpvId inputExprId,
1284 const Type& inputType,
1285 const Type& outputType,
1286 OutputStream& out) {
1287 if (outputType.isFloat()) {
1288 return this->castScalarToFloat(inputExprId, inputType, outputType, out);
1289 }
1290 if (outputType.isSigned()) {
1291 return this->castScalarToSignedInt(inputExprId, inputType, outputType, out);
1292 }
1293 if (outputType.isUnsigned()) {
1294 return this->castScalarToUnsignedInt(inputExprId, inputType, outputType, out);
1295 }
1296 if (outputType.isBoolean()) {
1297 return this->castScalarToBoolean(inputExprId, inputType, outputType, out);
1298 }
1299
Ethan Nicholas39f6da42021-08-23 13:10:07 -04001300 fContext.fErrors->error(-1, "unsupported cast: " + inputType.description() +
Ethan Nicholas3abc6c62021-08-13 11:20:09 -04001301 " to " + outputType.description());
John Stilesb14a8192021-04-05 11:40:46 -04001302 return inputExprId;
1303}
1304
John Stilesfd7252f2021-04-04 22:24:40 -04001305SpvId SPIRVCodeGenerator::writeFloatConstructor(const AnyConstructor& c, OutputStream& out) {
1306 SkASSERT(c.argumentSpan().size() == 1);
John Stilesd9d52712021-01-13 17:15:02 -05001307 SkASSERT(c.type().isFloat());
John Stilesfd7252f2021-04-04 22:24:40 -04001308 const Expression& ctorExpr = *c.argumentSpan().front();
John Stilesd9d52712021-01-13 17:15:02 -05001309 SpvId expressionId = this->writeExpression(ctorExpr, out);
1310 return this->castScalarToFloat(expressionId, ctorExpr.type(), c.type(), out);
1311}
1312
1313SpvId SPIRVCodeGenerator::castScalarToFloat(SpvId inputId, const Type& inputType,
1314 const Type& outputType, OutputStream& out) {
1315 // Casting a float to float is a no-op.
1316 if (inputType.isFloat()) {
1317 return inputId;
1318 }
1319
1320 // Given the input type, generate the appropriate instruction to cast to float.
Ethan Nicholas7f015882021-03-23 14:16:52 -04001321 SpvId result = this->nextId(&outputType);
John Stilesd9d52712021-01-13 17:15:02 -05001322 if (inputType.isBoolean()) {
John Stilesba4b0e92021-01-05 13:55:39 -05001323 // Use OpSelect to convert the boolean argument to a literal 1.0 or 0.0.
John Stiles9ce80f72021-03-11 22:35:19 -05001324 FloatLiteral one(/*offset=*/-1, /*value=*/1, fContext.fTypes.fFloat.get());
John Stilesba4b0e92021-01-05 13:55:39 -05001325 SpvId oneID = this->writeFloatLiteral(one);
John Stiles9ce80f72021-03-11 22:35:19 -05001326 FloatLiteral zero(/*offset=*/-1, /*value=*/0, fContext.fTypes.fFloat.get());
John Stilesba4b0e92021-01-05 13:55:39 -05001327 SpvId zeroID = this->writeFloatLiteral(zero);
John Stilesd9d52712021-01-13 17:15:02 -05001328 this->writeInstruction(SpvOpSelect, this->getType(outputType), result,
1329 inputId, oneID, zeroID, out);
1330 } else if (inputType.isSigned()) {
1331 this->writeInstruction(SpvOpConvertSToF, this->getType(outputType), result, inputId, out);
1332 } else if (inputType.isUnsigned()) {
1333 this->writeInstruction(SpvOpConvertUToF, this->getType(outputType), result, inputId, out);
Ethan Nicholasf7b88202017-09-18 14:10:39 -04001334 } else {
John Stilesd9d52712021-01-13 17:15:02 -05001335 SkDEBUGFAILF("unsupported type for float typecast: %s", inputType.description().c_str());
1336 return (SpvId)-1;
ethannicholasb3058bd2016-07-01 08:22:01 -07001337 }
1338 return result;
1339}
1340
John Stilesfd7252f2021-04-04 22:24:40 -04001341SpvId SPIRVCodeGenerator::writeIntConstructor(const AnyConstructor& c, OutputStream& out) {
1342 SkASSERT(c.argumentSpan().size() == 1);
John Stilesd9d52712021-01-13 17:15:02 -05001343 SkASSERT(c.type().isSigned());
John Stilesfd7252f2021-04-04 22:24:40 -04001344 const Expression& ctorExpr = *c.argumentSpan().front();
John Stilesd9d52712021-01-13 17:15:02 -05001345 SpvId expressionId = this->writeExpression(ctorExpr, out);
1346 return this->castScalarToSignedInt(expressionId, ctorExpr.type(), c.type(), out);
1347}
1348
1349SpvId SPIRVCodeGenerator::castScalarToSignedInt(SpvId inputId, const Type& inputType,
1350 const Type& outputType, OutputStream& out) {
1351 // Casting a signed int to signed int is a no-op.
1352 if (inputType.isSigned()) {
1353 return inputId;
1354 }
1355
1356 // Given the input type, generate the appropriate instruction to cast to signed int.
Ethan Nicholas7f015882021-03-23 14:16:52 -04001357 SpvId result = this->nextId(&outputType);
John Stilesd9d52712021-01-13 17:15:02 -05001358 if (inputType.isBoolean()) {
John Stilesba4b0e92021-01-05 13:55:39 -05001359 // Use OpSelect to convert the boolean argument to a literal 1 or 0.
John Stiles54e7c052021-01-11 14:22:36 -05001360 IntLiteral one(/*offset=*/-1, /*value=*/1, fContext.fTypes.fInt.get());
John Stilesba4b0e92021-01-05 13:55:39 -05001361 SpvId oneID = this->writeIntLiteral(one);
John Stiles54e7c052021-01-11 14:22:36 -05001362 IntLiteral zero(/*offset=*/-1, /*value=*/0, fContext.fTypes.fInt.get());
John Stilesba4b0e92021-01-05 13:55:39 -05001363 SpvId zeroID = this->writeIntLiteral(zero);
John Stilesd9d52712021-01-13 17:15:02 -05001364 this->writeInstruction(SpvOpSelect, this->getType(outputType), result,
1365 inputId, oneID, zeroID, out);
1366 } else if (inputType.isFloat()) {
1367 this->writeInstruction(SpvOpConvertFToS, this->getType(outputType), result, inputId, out);
1368 } else if (inputType.isUnsigned()) {
1369 this->writeInstruction(SpvOpBitcast, this->getType(outputType), result, inputId, out);
1370 } else {
1371 SkDEBUGFAILF("unsupported type for signed int typecast: %s",
1372 inputType.description().c_str());
1373 return (SpvId)-1;
ethannicholasb3058bd2016-07-01 08:22:01 -07001374 }
1375 return result;
1376}
1377
John Stilesfd7252f2021-04-04 22:24:40 -04001378SpvId SPIRVCodeGenerator::writeUIntConstructor(const AnyConstructor& c, OutputStream& out) {
1379 SkASSERT(c.argumentSpan().size() == 1);
John Stilesd9d52712021-01-13 17:15:02 -05001380 SkASSERT(c.type().isUnsigned());
John Stilesfd7252f2021-04-04 22:24:40 -04001381 const Expression& ctorExpr = *c.argumentSpan().front();
John Stilesd9d52712021-01-13 17:15:02 -05001382 SpvId expressionId = this->writeExpression(ctorExpr, out);
1383 return this->castScalarToUnsignedInt(expressionId, ctorExpr.type(), c.type(), out);
1384}
1385
1386SpvId SPIRVCodeGenerator::castScalarToUnsignedInt(SpvId inputId, const Type& inputType,
1387 const Type& outputType, OutputStream& out) {
1388 // Casting an unsigned int to unsigned int is a no-op.
1389 if (inputType.isUnsigned()) {
1390 return inputId;
1391 }
1392
John Stiles48c28842021-01-14 11:05:03 -05001393 // Given the input type, generate the appropriate instruction to cast to unsigned int.
Ethan Nicholas7f015882021-03-23 14:16:52 -04001394 SpvId result = this->nextId(&outputType);
John Stilesd9d52712021-01-13 17:15:02 -05001395 if (inputType.isBoolean()) {
John Stilesba4b0e92021-01-05 13:55:39 -05001396 // Use OpSelect to convert the boolean argument to a literal 1u or 0u.
John Stiles54e7c052021-01-11 14:22:36 -05001397 IntLiteral one(/*offset=*/-1, /*value=*/1, fContext.fTypes.fUInt.get());
John Stilesba4b0e92021-01-05 13:55:39 -05001398 SpvId oneID = this->writeIntLiteral(one);
John Stiles54e7c052021-01-11 14:22:36 -05001399 IntLiteral zero(/*offset=*/-1, /*value=*/0, fContext.fTypes.fUInt.get());
John Stilesba4b0e92021-01-05 13:55:39 -05001400 SpvId zeroID = this->writeIntLiteral(zero);
John Stilesd9d52712021-01-13 17:15:02 -05001401 this->writeInstruction(SpvOpSelect, this->getType(outputType), result,
1402 inputId, oneID, zeroID, out);
1403 } else if (inputType.isFloat()) {
1404 this->writeInstruction(SpvOpConvertFToU, this->getType(outputType), result, inputId, out);
1405 } else if (inputType.isSigned()) {
1406 this->writeInstruction(SpvOpBitcast, this->getType(outputType), result, inputId, out);
Ethan Nicholasf7b88202017-09-18 14:10:39 -04001407 } else {
John Stilesd9d52712021-01-13 17:15:02 -05001408 SkDEBUGFAILF("unsupported type for unsigned int typecast: %s",
1409 inputType.description().c_str());
1410 return (SpvId)-1;
Ethan Nicholas925f52d2017-07-19 10:42:50 -04001411 }
1412 return result;
1413}
1414
John Stilesfd7252f2021-04-04 22:24:40 -04001415SpvId SPIRVCodeGenerator::writeBooleanConstructor(const AnyConstructor& c, OutputStream& out) {
1416 SkASSERT(c.argumentSpan().size() == 1);
John Stilesa60fb172021-01-14 11:06:20 -05001417 SkASSERT(c.type().isBoolean());
John Stilesfd7252f2021-04-04 22:24:40 -04001418 const Expression& ctorExpr = *c.argumentSpan().front();
John Stilesa60fb172021-01-14 11:06:20 -05001419 SpvId expressionId = this->writeExpression(ctorExpr, out);
1420 return this->castScalarToBoolean(expressionId, ctorExpr.type(), c.type(), out);
1421}
1422
John Stiles48c28842021-01-14 11:05:03 -05001423SpvId SPIRVCodeGenerator::castScalarToBoolean(SpvId inputId, const Type& inputType,
1424 const Type& outputType, OutputStream& out) {
1425 // Casting a bool to bool is a no-op.
1426 if (inputType.isBoolean()) {
1427 return inputId;
1428 }
1429
1430 // Given the input type, generate the appropriate instruction to cast to bool.
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001431 SpvId result = this->nextId(nullptr);
John Stiles48c28842021-01-14 11:05:03 -05001432 if (inputType.isSigned()) {
1433 // Synthesize a boolean result by comparing the input against a signed zero literal.
1434 IntLiteral zero(/*offset=*/-1, /*value=*/0, fContext.fTypes.fInt.get());
1435 SpvId zeroID = this->writeIntLiteral(zero);
1436 this->writeInstruction(SpvOpINotEqual, this->getType(outputType), result,
1437 inputId, zeroID, out);
1438 } else if (inputType.isUnsigned()) {
1439 // Synthesize a boolean result by comparing the input against an unsigned zero literal.
1440 IntLiteral zero(/*offset=*/-1, /*value=*/0, fContext.fTypes.fUInt.get());
1441 SpvId zeroID = this->writeIntLiteral(zero);
1442 this->writeInstruction(SpvOpINotEqual, this->getType(outputType), result,
1443 inputId, zeroID, out);
1444 } else if (inputType.isFloat()) {
1445 // Synthesize a boolean result by comparing the input against a floating-point zero literal.
1446 FloatLiteral zero(/*offset=*/-1, /*value=*/0, fContext.fTypes.fFloat.get());
1447 SpvId zeroID = this->writeFloatLiteral(zero);
1448 this->writeInstruction(SpvOpFUnordNotEqual, this->getType(outputType), result,
1449 inputId, zeroID, out);
1450 } else {
1451 SkDEBUGFAILF("unsupported type for boolean typecast: %s", inputType.description().c_str());
1452 return (SpvId)-1;
1453 }
1454 return result;
1455}
1456
Ethan Nicholas84645e32017-02-09 13:57:14 -05001457void SPIRVCodeGenerator::writeUniformScaleMatrix(SpvId id, SpvId diagonal, const Type& type,
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001458 OutputStream& out) {
John Stiles9ce80f72021-03-11 22:35:19 -05001459 FloatLiteral zero(/*offset=*/-1, /*value=*/0, fContext.fTypes.fFloat.get());
Ethan Nicholas84645e32017-02-09 13:57:14 -05001460 SpvId zeroId = this->writeFloatLiteral(zero);
1461 std::vector<SpvId> columnIds;
John Stiles392d8292021-04-09 12:14:03 -04001462 columnIds.reserve(type.columns());
Ethan Nicholas84645e32017-02-09 13:57:14 -05001463 for (int column = 0; column < type.columns(); column++) {
1464 this->writeOpCode(SpvOpCompositeConstruct, 3 + type.rows(),
1465 out);
John Stiles392d8292021-04-09 12:14:03 -04001466 this->writeWord(this->getType(type.componentType().toCompound(
1467 fContext, /*columns=*/type.rows(), /*rows=*/1)),
Ethan Nicholas84645e32017-02-09 13:57:14 -05001468 out);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001469 SpvId columnId = this->nextId(&type);
Ethan Nicholas84645e32017-02-09 13:57:14 -05001470 this->writeWord(columnId, out);
1471 columnIds.push_back(columnId);
John Stiles392d8292021-04-09 12:14:03 -04001472 for (int row = 0; row < type.rows(); row++) {
Ethan Nicholas84645e32017-02-09 13:57:14 -05001473 this->writeWord(row == column ? diagonal : zeroId, out);
1474 }
1475 }
1476 this->writeOpCode(SpvOpCompositeConstruct, 3 + type.columns(),
1477 out);
1478 this->writeWord(this->getType(type), out);
1479 this->writeWord(id, out);
John Stilesf621e232020-08-25 13:33:02 -04001480 for (SpvId columnId : columnIds) {
1481 this->writeWord(columnId, out);
Ethan Nicholas84645e32017-02-09 13:57:14 -05001482 }
1483}
1484
John Stiles268a73f2021-04-07 12:30:22 -04001485SpvId SPIRVCodeGenerator::writeMatrixCopy(SpvId src, const Type& srcType, const Type& dstType,
1486 OutputStream& out) {
John Stiles9aeed132020-11-24 17:36:06 -05001487 SkASSERT(srcType.isMatrix());
1488 SkASSERT(dstType.isMatrix());
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001489 SkASSERT(srcType.componentType() == dstType.componentType());
John Stiles268a73f2021-04-07 12:30:22 -04001490 SpvId id = this->nextId(&dstType);
Ethan Nicholasdc0e1c32017-07-21 13:23:34 -04001491 SpvId srcColumnType = this->getType(srcType.componentType().toCompound(fContext,
1492 srcType.rows(),
1493 1));
1494 SpvId dstColumnType = this->getType(dstType.componentType().toCompound(fContext,
1495 dstType.rows(),
1496 1));
John Stiles92671832021-04-06 09:24:55 -04001497 SkASSERT(dstType.componentType().isFloat());
1498 FloatLiteral zero(/*offset=*/-1, /*value=*/0.0, &dstType.componentType());
1499 const SpvId zeroId = this->writeFloatLiteral(zero);
1500 FloatLiteral one(/*offset=*/-1, /*value=*/1.0, &dstType.componentType());
1501 const SpvId oneId = this->writeFloatLiteral(one);
1502
Ethan Nicholasdc0e1c32017-07-21 13:23:34 -04001503 SpvId columns[4];
1504 for (int i = 0; i < dstType.columns(); i++) {
1505 if (i < srcType.columns()) {
1506 // we're still inside the src matrix, copy the column
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001507 SpvId srcColumn = this->nextId(&dstType);
Ethan Nicholasdc0e1c32017-07-21 13:23:34 -04001508 this->writeInstruction(SpvOpCompositeExtract, srcColumnType, srcColumn, src, i, out);
1509 SpvId dstColumn;
1510 if (srcType.rows() == dstType.rows()) {
1511 // columns are equal size, don't need to do anything
1512 dstColumn = srcColumn;
1513 }
1514 else if (dstType.rows() > srcType.rows()) {
1515 // dst column is bigger, need to zero-pad it
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001516 dstColumn = this->nextId(&dstType);
Ethan Nicholasdc0e1c32017-07-21 13:23:34 -04001517 int delta = dstType.rows() - srcType.rows();
1518 this->writeOpCode(SpvOpCompositeConstruct, 4 + delta, out);
1519 this->writeWord(dstColumnType, out);
1520 this->writeWord(dstColumn, out);
1521 this->writeWord(srcColumn, out);
John Stiles92671832021-04-06 09:24:55 -04001522 for (int j = srcType.rows(); j < dstType.rows(); ++j) {
1523 this->writeWord((i == j) ? oneId : zeroId, out);
Ethan Nicholasdc0e1c32017-07-21 13:23:34 -04001524 }
1525 }
1526 else {
1527 // dst column is smaller, need to swizzle the src column
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001528 dstColumn = this->nextId(&dstType);
John Stiles92671832021-04-06 09:24:55 -04001529 this->writeOpCode(SpvOpVectorShuffle, 5 + dstType.rows(), out);
Ethan Nicholasdc0e1c32017-07-21 13:23:34 -04001530 this->writeWord(dstColumnType, out);
1531 this->writeWord(dstColumn, out);
1532 this->writeWord(srcColumn, out);
1533 this->writeWord(srcColumn, out);
John Stiles92671832021-04-06 09:24:55 -04001534 for (int j = 0; j < dstType.rows(); j++) {
John Stilesf621e232020-08-25 13:33:02 -04001535 this->writeWord(j, out);
Ethan Nicholasdc0e1c32017-07-21 13:23:34 -04001536 }
1537 }
1538 columns[i] = dstColumn;
1539 } else {
John Stiles92671832021-04-06 09:24:55 -04001540 // we're past the end of the src matrix, need to synthesize an identity-matrix column
1541 SpvId identityColumn = this->nextId(&dstType);
1542 this->writeOpCode(SpvOpCompositeConstruct, 3 + dstType.rows(), out);
1543 this->writeWord(dstColumnType, out);
1544 this->writeWord(identityColumn, out);
1545 for (int j = 0; j < dstType.rows(); ++j) {
1546 this->writeWord((i == j) ? oneId : zeroId, out);
Ethan Nicholasdc0e1c32017-07-21 13:23:34 -04001547 }
John Stiles92671832021-04-06 09:24:55 -04001548 columns[i] = identityColumn;
Ethan Nicholasdc0e1c32017-07-21 13:23:34 -04001549 }
1550 }
1551 this->writeOpCode(SpvOpCompositeConstruct, 3 + dstType.columns(), out);
1552 this->writeWord(this->getType(dstType), out);
1553 this->writeWord(id, out);
1554 for (int i = 0; i < dstType.columns(); i++) {
1555 this->writeWord(columns[i], out);
1556 }
John Stiles268a73f2021-04-07 12:30:22 -04001557 return id;
Ethan Nicholas84645e32017-02-09 13:57:14 -05001558}
1559
John Stilesbeb2fbf2021-07-08 18:54:39 -04001560void SPIRVCodeGenerator::addColumnEntry(const Type& columnType,
Ethan Nicholascc5d3e02019-04-19 09:50:56 -04001561 std::vector<SpvId>* currentColumn,
Ethan Nicholas5c46b722019-03-22 14:32:37 -04001562 std::vector<SpvId>* columnIds,
John Stilesbeb2fbf2021-07-08 18:54:39 -04001563 int rows,
1564 SpvId entry,
Ethan Nicholas5c46b722019-03-22 14:32:37 -04001565 OutputStream& out) {
John Stilesbeb2fbf2021-07-08 18:54:39 -04001566 SkASSERT((int)currentColumn->size() < rows);
Ethan Nicholas5c46b722019-03-22 14:32:37 -04001567 currentColumn->push_back(entry);
John Stilesbeb2fbf2021-07-08 18:54:39 -04001568 if ((int)currentColumn->size() == rows) {
1569 // Synthesize this column into a vector.
1570 SpvId columnId = this->writeComposite(*currentColumn, columnType, out);
Ethan Nicholas5c46b722019-03-22 14:32:37 -04001571 columnIds->push_back(columnId);
Ethan Nicholas5c46b722019-03-22 14:32:37 -04001572 currentColumn->clear();
1573 }
1574}
1575
John Stiles8cad6372021-04-07 12:31:13 -04001576SpvId SPIRVCodeGenerator::writeMatrixConstructor(const ConstructorCompound& c, OutputStream& out) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001577 const Type& type = c.type();
John Stiles9aeed132020-11-24 17:36:06 -05001578 SkASSERT(type.isMatrix());
John Stiles2bec8ab2021-04-06 18:40:04 -04001579 SkASSERT(!c.arguments().empty());
Ethan Nicholasf70f0442020-09-29 12:41:35 -04001580 const Type& arg0Type = c.arguments()[0]->type();
ethannicholasb3058bd2016-07-01 08:22:01 -07001581 // go ahead and write the arguments so we don't try to write new instructions in the middle of
1582 // an instruction
1583 std::vector<SpvId> arguments;
John Stiles2bec8ab2021-04-06 18:40:04 -04001584 arguments.reserve(c.arguments().size());
1585 for (const std::unique_ptr<Expression>& arg : c.arguments()) {
1586 arguments.push_back(this->writeExpression(*arg, out));
ethannicholasb3058bd2016-07-01 08:22:01 -07001587 }
John Stilesbeb2fbf2021-07-08 18:54:39 -04001588
John Stiles268a73f2021-04-07 12:30:22 -04001589 if (arguments.size() == 1 && arg0Type.isVector()) {
1590 // Special-case handling of float4 -> mat2x2.
Ethan Nicholas30d30222020-09-11 12:27:26 -04001591 SkASSERT(type.rows() == 2 && type.columns() == 2);
1592 SkASSERT(arg0Type.columns() == 4);
1593 SpvId componentType = this->getType(type.componentType());
Ethan Nicholasdc0e1c32017-07-21 13:23:34 -04001594 SpvId v[4];
1595 for (int i = 0; i < 4; ++i) {
Ethan Nicholas7f015882021-03-23 14:16:52 -04001596 v[i] = this->nextId(&type);
Ethan Nicholas30d30222020-09-11 12:27:26 -04001597 this->writeInstruction(SpvOpCompositeExtract, componentType, v[i], arguments[0], i,
1598 out);
Ethan Nicholasdc0e1c32017-07-21 13:23:34 -04001599 }
John Stilesbeb2fbf2021-07-08 18:54:39 -04001600 const Type& vecType = type.componentType().toCompound(fContext, /*columns=*/2, /*rows=*/1);
1601 SpvId v0v1 = this->writeComposite({v[0], v[1]}, vecType, out);
1602 SpvId v2v3 = this->writeComposite({v[2], v[3]}, vecType, out);
1603 return this->writeComposite({v0v1, v2v3}, type, out);
1604 }
1605
1606 int rows = type.rows();
1607 const Type& columnType = type.componentType().toCompound(fContext,
1608 /*columns=*/rows, /*rows=*/1);
1609 // SpvIds of completed columns of the matrix.
1610 std::vector<SpvId> columnIds;
1611 // SpvIds of scalars we have written to the current column so far.
1612 std::vector<SpvId> currentColumn;
1613 for (size_t i = 0; i < arguments.size(); i++) {
1614 const Type& argType = c.arguments()[i]->type();
1615 if (currentColumn.empty() && argType.isVector() && argType.columns() == rows) {
1616 // This vector is a complete matrix column by itself and can be used as-is.
1617 columnIds.push_back(arguments[i]);
1618 } else if (argType.columns() == 1) {
1619 // This argument is a lone scalar and can be added to the current column as-is.
1620 this->addColumnEntry(columnType, &currentColumn, &columnIds, rows, arguments[i], out);
1621 } else {
1622 // This argument needs to be decomposed into its constituent scalars.
1623 SpvId componentType = this->getType(argType.componentType());
1624 for (int j = 0; j < argType.columns(); ++j) {
1625 SpvId swizzle = this->nextId(&argType);
1626 this->writeInstruction(SpvOpCompositeExtract, componentType, swizzle,
1627 arguments[i], j, out);
1628 this->addColumnEntry(columnType, &currentColumn, &columnIds, rows, swizzle, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07001629 }
1630 }
ethannicholasb3058bd2016-07-01 08:22:01 -07001631 }
John Stilesbeb2fbf2021-07-08 18:54:39 -04001632 SkASSERT(columnIds.size() == (size_t) type.columns());
1633 return this->writeComposite(columnIds, type, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07001634}
1635
John Stiles8cad6372021-04-07 12:31:13 -04001636SpvId SPIRVCodeGenerator::writeConstructorCompound(const ConstructorCompound& c,
1637 OutputStream& out) {
John Stiles2bec8ab2021-04-06 18:40:04 -04001638 return c.type().isMatrix() ? this->writeMatrixConstructor(c, out)
1639 : this->writeVectorConstructor(c, out);
1640}
1641
John Stiles8cad6372021-04-07 12:31:13 -04001642SpvId SPIRVCodeGenerator::writeVectorConstructor(const ConstructorCompound& c, OutputStream& out) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001643 const Type& type = c.type();
John Stilesd986f472021-04-06 15:54:43 -04001644 const Type& componentType = type.componentType();
John Stiles9aeed132020-11-24 17:36:06 -05001645 SkASSERT(type.isVector());
John Stilesd986f472021-04-06 15:54:43 -04001646
1647 if (c.isCompileTimeConstant()) {
ethannicholasb3058bd2016-07-01 08:22:01 -07001648 return this->writeConstantVector(c);
1649 }
John Stilesd986f472021-04-06 15:54:43 -04001650
ethannicholasb3058bd2016-07-01 08:22:01 -07001651 std::vector<SpvId> arguments;
John Stiles6de2e1d2021-07-09 12:41:55 -04001652 arguments.reserve(c.arguments().size());
Ethan Nicholasf70f0442020-09-29 12:41:35 -04001653 for (size_t i = 0; i < c.arguments().size(); i++) {
1654 const Type& argType = c.arguments()[i]->type();
John Stilesd986f472021-04-06 15:54:43 -04001655 SkASSERT(componentType == argType.componentType());
John Stiles48c28842021-01-14 11:05:03 -05001656
John Stiles6de2e1d2021-07-09 12:41:55 -04001657 SpvId arg = this->writeExpression(*c.arguments()[i], out);
1658 if (argType.isMatrix()) {
1659 // CompositeConstruct cannot take a 2x2 matrix as an input, so we need to extract out
1660 // each scalar separately.
1661 SkASSERT(argType.rows() == 2);
1662 SkASSERT(argType.columns() == 2);
1663 for (int j = 0; j < 4; ++j) {
1664 SpvId componentId = this->nextId(&componentType);
1665 this->writeInstruction(SpvOpCompositeExtract, this->getType(componentType),
1666 componentId, arg, j / 2, j % 2, out);
1667 arguments.push_back(componentId);
1668 }
1669 } else if (argType.isVector()) {
John Stilesd986f472021-04-06 15:54:43 -04001670 // There's a bug in the Intel Vulkan driver where OpCompositeConstruct doesn't handle
1671 // vector arguments at all, so we always extract each vector component and pass them
1672 // into OpCompositeConstruct individually.
Ethan Nicholas30d30222020-09-11 12:27:26 -04001673 for (int j = 0; j < argType.columns(); j++) {
John Stilesd986f472021-04-06 15:54:43 -04001674 SpvId componentId = this->nextId(&componentType);
1675 this->writeInstruction(SpvOpCompositeExtract, this->getType(componentType),
John Stiles6de2e1d2021-07-09 12:41:55 -04001676 componentId, arg, j, out);
John Stilesd986f472021-04-06 15:54:43 -04001677 arguments.push_back(componentId);
Ethan Nicholas26a8d902018-01-29 09:25:51 -05001678 }
Ethan Nicholas11e5bff2018-01-29 11:08:38 -05001679 } else {
John Stiles6de2e1d2021-07-09 12:41:55 -04001680 arguments.push_back(arg);
Ethan Nicholas26a8d902018-01-29 09:25:51 -05001681 }
ethannicholasb3058bd2016-07-01 08:22:01 -07001682 }
John Stilesb14a8192021-04-05 11:40:46 -04001683
1684 return this->writeComposite(arguments, type, out);
1685}
1686
1687SpvId SPIRVCodeGenerator::writeComposite(const std::vector<SpvId>& arguments,
1688 const Type& type,
1689 OutputStream& out) {
John Stilesd47330f2021-04-08 23:25:52 -04001690 SkASSERT(arguments.size() == (type.isStruct() ? type.fields().size() : (size_t)type.columns()));
John Stiles2938eea2021-04-01 18:58:25 -04001691
Ethan Nicholas7f015882021-03-23 14:16:52 -04001692 SpvId result = this->nextId(&type);
John Stiles2938eea2021-04-01 18:58:25 -04001693 this->writeOpCode(SpvOpCompositeConstruct, 3 + (int32_t) arguments.size(), out);
1694 this->writeWord(this->getType(type), out);
1695 this->writeWord(result, out);
1696 for (SpvId id : arguments) {
1697 this->writeWord(id, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07001698 }
1699 return result;
1700}
1701
John Stiles2938eea2021-04-01 18:58:25 -04001702SpvId SPIRVCodeGenerator::writeConstructorSplat(const ConstructorSplat& c, OutputStream& out) {
1703 // Use writeConstantVector to deduplicate constant splats.
1704 if (c.isCompileTimeConstant()) {
1705 return this->writeConstantVector(c);
1706 }
1707
1708 // Write the splat argument.
1709 SpvId argument = this->writeExpression(*c.argument(), out);
1710
1711 // Generate a OpCompositeConstruct which repeats the argument N times.
John Stilesb14a8192021-04-05 11:40:46 -04001712 std::vector<SpvId> arguments(/*count*/ c.type().columns(), /*value*/ argument);
1713 return this->writeComposite(arguments, c.type(), out);
John Stiles2938eea2021-04-01 18:58:25 -04001714}
1715
1716
John Stilesd47330f2021-04-08 23:25:52 -04001717SpvId SPIRVCodeGenerator::writeCompositeConstructor(const AnyConstructor& c, OutputStream& out) {
1718 SkASSERT(c.type().isArray() || c.type().isStruct());
1719 auto ctorArgs = c.argumentSpan();
1720
Ethan Nicholasbd553222017-07-18 15:54:59 -04001721 std::vector<SpvId> arguments;
John Stilesd47330f2021-04-08 23:25:52 -04001722 arguments.reserve(ctorArgs.size());
1723 for (const std::unique_ptr<Expression>& arg : ctorArgs) {
1724 arguments.push_back(this->writeExpression(*arg, out));
Ethan Nicholasbd553222017-07-18 15:54:59 -04001725 }
John Stilesd47330f2021-04-08 23:25:52 -04001726
1727 return this->writeComposite(arguments, c.type(), out);
Ethan Nicholasbd553222017-07-18 15:54:59 -04001728}
1729
John Stilesfd7252f2021-04-04 22:24:40 -04001730SpvId SPIRVCodeGenerator::writeConstructorScalarCast(const ConstructorScalarCast& c,
1731 OutputStream& out) {
1732 const Type& type = c.type();
1733 if (this->getActualType(type) == this->getActualType(c.argument()->type())) {
1734 return this->writeExpression(*c.argument(), out);
1735 }
John Stilesb14a8192021-04-05 11:40:46 -04001736
1737 const Expression& ctorExpr = *c.argument();
1738 SpvId expressionId = this->writeExpression(ctorExpr, out);
1739 return this->castScalarToType(expressionId, ctorExpr.type(), type, out);
1740}
1741
John Stiles8cad6372021-04-07 12:31:13 -04001742SpvId SPIRVCodeGenerator::writeConstructorCompoundCast(const ConstructorCompoundCast& c,
1743 OutputStream& out) {
John Stilesb14a8192021-04-05 11:40:46 -04001744 const Type& ctorType = c.type();
1745 const Type& argType = c.argument()->type();
John Stiles268a73f2021-04-07 12:30:22 -04001746 SkASSERT(ctorType.isVector() || ctorType.isMatrix());
John Stilesb14a8192021-04-05 11:40:46 -04001747
John Stiles268a73f2021-04-07 12:30:22 -04001748 // Write the composite that we are casting. If the actual type matches, we are done.
1749 SpvId compositeId = this->writeExpression(*c.argument(), out);
John Stilesb14a8192021-04-05 11:40:46 -04001750 if (this->getActualType(ctorType) == this->getActualType(argType)) {
John Stiles268a73f2021-04-07 12:30:22 -04001751 return compositeId;
1752 }
1753
1754 // writeMatrixCopy can cast matrices to a different type.
1755 if (ctorType.isMatrix()) {
1756 return this->writeMatrixCopy(compositeId, argType, ctorType, out);
John Stilesfd7252f2021-04-04 22:24:40 -04001757 }
John Stilesb14a8192021-04-05 11:40:46 -04001758
1759 // SPIR-V doesn't support vector(vector-of-different-type) directly, so we need to extract the
John Stilesd986f472021-04-06 15:54:43 -04001760 // components and convert each one manually.
John Stilesb14a8192021-04-05 11:40:46 -04001761 const Type& srcType = argType.componentType();
1762 const Type& dstType = ctorType.componentType();
1763
1764 std::vector<SpvId> arguments;
John Stiles268a73f2021-04-07 12:30:22 -04001765 arguments.reserve(argType.columns());
John Stilesb14a8192021-04-05 11:40:46 -04001766 for (int index = 0; index < argType.columns(); ++index) {
1767 SpvId componentId = this->nextId(&srcType);
1768 this->writeInstruction(SpvOpCompositeExtract, this->getType(srcType), componentId,
John Stiles268a73f2021-04-07 12:30:22 -04001769 compositeId, index, out);
John Stilesb14a8192021-04-05 11:40:46 -04001770 arguments.push_back(this->castScalarToType(componentId, srcType, dstType, out));
John Stilesfd7252f2021-04-04 22:24:40 -04001771 }
John Stilesb14a8192021-04-05 11:40:46 -04001772
1773 return this->writeComposite(arguments, ctorType, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07001774}
1775
John Stilese1182782021-03-30 22:09:37 -04001776SpvId SPIRVCodeGenerator::writeConstructorDiagonalMatrix(const ConstructorDiagonalMatrix& c,
1777 OutputStream& out) {
1778 const Type& type = c.type();
1779 SkASSERT(type.isMatrix());
1780 SkASSERT(c.argument()->type().isScalar());
1781
1782 // Write out the scalar argument.
1783 SpvId argument = this->writeExpression(*c.argument(), out);
1784
1785 // Build the diagonal matrix.
1786 SpvId result = this->nextId(&type);
1787 this->writeUniformScaleMatrix(result, argument, type, out);
1788 return result;
1789}
1790
John Stiles5abb9e12021-04-06 13:47:19 -04001791SpvId SPIRVCodeGenerator::writeConstructorMatrixResize(const ConstructorMatrixResize& c,
1792 OutputStream& out) {
1793 // Write the input matrix.
1794 SpvId argument = this->writeExpression(*c.argument(), out);
1795
1796 // Use matrix-copy to resize the input matrix to its new size.
John Stiles268a73f2021-04-07 12:30:22 -04001797 return this->writeMatrixCopy(argument, c.argument()->type(), c.type(), out);
John Stiles5abb9e12021-04-06 13:47:19 -04001798}
1799
John Stiles9485b552021-01-27 11:47:00 -05001800static SpvStorageClass_ get_storage_class(const Variable& var,
1801 SpvStorageClass_ fallbackStorageClass) {
1802 const Modifiers& modifiers = var.modifiers();
ethannicholasb3058bd2016-07-01 08:22:01 -07001803 if (modifiers.fFlags & Modifiers::kIn_Flag) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001804 SkASSERT(!(modifiers.fLayout.fFlags & Layout::kPushConstant_Flag));
ethannicholasb3058bd2016-07-01 08:22:01 -07001805 return SpvStorageClassInput;
John Stiles9485b552021-01-27 11:47:00 -05001806 }
1807 if (modifiers.fFlags & Modifiers::kOut_Flag) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001808 SkASSERT(!(modifiers.fLayout.fFlags & Layout::kPushConstant_Flag));
ethannicholasb3058bd2016-07-01 08:22:01 -07001809 return SpvStorageClassOutput;
John Stiles9485b552021-01-27 11:47:00 -05001810 }
1811 if (modifiers.fFlags & Modifiers::kUniform_Flag) {
Ethan Nicholas39204fd2017-11-27 13:12:30 -05001812 if (modifiers.fLayout.fFlags & Layout::kPushConstant_Flag) {
ethannicholas8ac838d2016-11-22 08:39:36 -08001813 return SpvStorageClassPushConstant;
1814 }
John Stiles9485b552021-01-27 11:47:00 -05001815 if (var.type().typeKind() == Type::TypeKind::kSampler ||
1816 var.type().typeKind() == Type::TypeKind::kSeparateSampler ||
1817 var.type().typeKind() == Type::TypeKind::kTexture) {
1818 return SpvStorageClassUniformConstant;
1819 }
ethannicholasb3058bd2016-07-01 08:22:01 -07001820 return SpvStorageClassUniform;
ethannicholasb3058bd2016-07-01 08:22:01 -07001821 }
John Stiles9485b552021-01-27 11:47:00 -05001822 return fallbackStorageClass;
ethannicholasb3058bd2016-07-01 08:22:01 -07001823}
1824
John Stiles9485b552021-01-27 11:47:00 -05001825static SpvStorageClass_ get_storage_class(const Expression& expr) {
Ethan Nicholase6592142020-09-08 10:22:09 -04001826 switch (expr.kind()) {
1827 case Expression::Kind::kVariableReference: {
Ethan Nicholas78686922020-10-08 06:46:27 -04001828 const Variable& var = *expr.as<VariableReference>().variable();
Ethan Nicholas453f67f2020-10-09 10:43:45 -04001829 if (var.storage() != Variable::Storage::kGlobal) {
Ethan Nicholasc6f5e102017-03-31 14:53:17 -04001830 return SpvStorageClassFunction;
1831 }
John Stiles9485b552021-01-27 11:47:00 -05001832 return get_storage_class(var, SpvStorageClassPrivate);
Ethan Nicholasc6f5e102017-03-31 14:53:17 -04001833 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001834 case Expression::Kind::kFieldAccess:
Ethan Nicholas7a95b202020-10-09 11:55:40 -04001835 return get_storage_class(*expr.as<FieldAccess>().base());
Ethan Nicholase6592142020-09-08 10:22:09 -04001836 case Expression::Kind::kIndex:
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04001837 return get_storage_class(*expr.as<IndexExpression>().base());
ethannicholasb3058bd2016-07-01 08:22:01 -07001838 default:
1839 return SpvStorageClassFunction;
1840 }
1841}
1842
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001843std::vector<SpvId> SPIRVCodeGenerator::getAccessChain(const Expression& expr, OutputStream& out) {
ethannicholasb3058bd2016-07-01 08:22:01 -07001844 std::vector<SpvId> chain;
Ethan Nicholase6592142020-09-08 10:22:09 -04001845 switch (expr.kind()) {
1846 case Expression::Kind::kIndex: {
John Stiles0693fb82021-01-22 18:27:52 -05001847 const IndexExpression& indexExpr = expr.as<IndexExpression>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04001848 chain = this->getAccessChain(*indexExpr.base(), out);
1849 chain.push_back(this->writeExpression(*indexExpr.index(), out));
ethannicholasb3058bd2016-07-01 08:22:01 -07001850 break;
1851 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001852 case Expression::Kind::kFieldAccess: {
John Stiles0693fb82021-01-22 18:27:52 -05001853 const FieldAccess& fieldExpr = expr.as<FieldAccess>();
Ethan Nicholas7a95b202020-10-09 11:55:40 -04001854 chain = this->getAccessChain(*fieldExpr.base(), out);
John Stiles9ce80f72021-03-11 22:35:19 -05001855 IntLiteral index(/*offset=*/-1, fieldExpr.fieldIndex(), fContext.fTypes.fInt.get());
ethannicholasb3058bd2016-07-01 08:22:01 -07001856 chain.push_back(this->writeIntLiteral(index));
1857 break;
1858 }
Ethan Nicholasa9a06902019-01-07 14:42:40 -05001859 default: {
1860 SpvId id = this->getLValue(expr, out)->getPointer();
John Stiles3f14d282021-02-05 09:31:04 -05001861 SkASSERT(id != (SpvId) -1);
Ethan Nicholasa9a06902019-01-07 14:42:40 -05001862 chain.push_back(id);
1863 }
ethannicholasb3058bd2016-07-01 08:22:01 -07001864 }
1865 return chain;
1866}
1867
1868class PointerLValue : public SPIRVCodeGenerator::LValue {
1869public:
Ethan Nicholase0707b72021-03-17 11:16:41 -04001870 PointerLValue(SPIRVCodeGenerator& gen, SpvId pointer, bool isMemoryObject, SpvId type,
Ethan Nicholas10e93b62019-03-20 10:46:14 -04001871 SPIRVCodeGenerator::Precision precision)
ethannicholasb3058bd2016-07-01 08:22:01 -07001872 : fGen(gen)
1873 , fPointer(pointer)
Ethan Nicholase0707b72021-03-17 11:16:41 -04001874 , fIsMemoryObject(isMemoryObject)
Ethan Nicholas10e93b62019-03-20 10:46:14 -04001875 , fType(type)
1876 , fPrecision(precision) {}
ethannicholasb3058bd2016-07-01 08:22:01 -07001877
John Stiles1cf2c8d2020-08-13 22:58:04 -04001878 SpvId getPointer() override {
ethannicholasb3058bd2016-07-01 08:22:01 -07001879 return fPointer;
1880 }
1881
Ethan Nicholase0707b72021-03-17 11:16:41 -04001882 bool isMemoryObjectPointer() const override {
1883 return fIsMemoryObject;
1884 }
1885
John Stiles1cf2c8d2020-08-13 22:58:04 -04001886 SpvId load(OutputStream& out) override {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001887 SpvId result = fGen.nextId(fPrecision);
ethannicholasb3058bd2016-07-01 08:22:01 -07001888 fGen.writeInstruction(SpvOpLoad, fType, result, fPointer, out);
1889 return result;
1890 }
1891
John Stiles1cf2c8d2020-08-13 22:58:04 -04001892 void store(SpvId value, OutputStream& out) override {
ethannicholasb3058bd2016-07-01 08:22:01 -07001893 fGen.writeInstruction(SpvOpStore, fPointer, value, out);
1894 }
1895
1896private:
1897 SPIRVCodeGenerator& fGen;
1898 const SpvId fPointer;
Ethan Nicholase0707b72021-03-17 11:16:41 -04001899 const bool fIsMemoryObject;
ethannicholasb3058bd2016-07-01 08:22:01 -07001900 const SpvId fType;
Ethan Nicholas10e93b62019-03-20 10:46:14 -04001901 const SPIRVCodeGenerator::Precision fPrecision;
ethannicholasb3058bd2016-07-01 08:22:01 -07001902};
1903
1904class SwizzleLValue : public SPIRVCodeGenerator::LValue {
1905public:
John Stiles750109b2020-10-30 13:45:46 -04001906 SwizzleLValue(SPIRVCodeGenerator& gen, SpvId vecPointer, const ComponentArray& components,
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001907 const Type& baseType, const Type& swizzleType)
ethannicholasb3058bd2016-07-01 08:22:01 -07001908 : fGen(gen)
1909 , fVecPointer(vecPointer)
1910 , fComponents(components)
John Stiles3f14d282021-02-05 09:31:04 -05001911 , fBaseType(&baseType)
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001912 , fSwizzleType(&swizzleType) {}
ethannicholasb3058bd2016-07-01 08:22:01 -07001913
John Stiles3f14d282021-02-05 09:31:04 -05001914 bool applySwizzle(const ComponentArray& components, const Type& newType) override {
1915 ComponentArray updatedSwizzle;
1916 for (int8_t component : components) {
1917 if (component < 0 || component >= fComponents.count()) {
1918 SkDEBUGFAILF("swizzle accessed nonexistent component %d", (int)component);
1919 return false;
1920 }
1921 updatedSwizzle.push_back(fComponents[component]);
1922 }
1923 fComponents = updatedSwizzle;
1924 fSwizzleType = &newType;
1925 return true;
ethannicholasb3058bd2016-07-01 08:22:01 -07001926 }
1927
John Stiles1cf2c8d2020-08-13 22:58:04 -04001928 SpvId load(OutputStream& out) override {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001929 SpvId base = fGen.nextId(fBaseType);
John Stiles3f14d282021-02-05 09:31:04 -05001930 fGen.writeInstruction(SpvOpLoad, fGen.getType(*fBaseType), base, fVecPointer, out);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001931 SpvId result = fGen.nextId(fBaseType);
ethannicholasb3058bd2016-07-01 08:22:01 -07001932 fGen.writeOpCode(SpvOpVectorShuffle, 5 + (int32_t) fComponents.size(), out);
John Stiles3f14d282021-02-05 09:31:04 -05001933 fGen.writeWord(fGen.getType(*fSwizzleType), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07001934 fGen.writeWord(result, out);
1935 fGen.writeWord(base, out);
1936 fGen.writeWord(base, out);
1937 for (int component : fComponents) {
1938 fGen.writeWord(component, out);
1939 }
1940 return result;
1941 }
1942
John Stiles1cf2c8d2020-08-13 22:58:04 -04001943 void store(SpvId value, OutputStream& out) override {
ethannicholasb3058bd2016-07-01 08:22:01 -07001944 // use OpVectorShuffle to mix and match the vector components. We effectively create
1945 // a virtual vector out of the concatenation of the left and right vectors, and then
Greg Daniel64773e62016-11-22 09:44:03 -05001946 // select components from this virtual vector to make the result vector. For
ethannicholasb3058bd2016-07-01 08:22:01 -07001947 // instance, given:
Ethan Nicholas5af9ea32017-07-28 15:19:46 -04001948 // float3L = ...;
1949 // float3R = ...;
ethannicholasb3058bd2016-07-01 08:22:01 -07001950 // L.xz = R.xy;
Greg Daniel64773e62016-11-22 09:44:03 -05001951 // 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 -07001952 // our result vector to look like (R.x, L.y, R.y), so we need to select indices
1953 // (3, 1, 4).
Ethan Nicholas7f015882021-03-23 14:16:52 -04001954 SpvId base = fGen.nextId(fBaseType);
John Stiles3f14d282021-02-05 09:31:04 -05001955 fGen.writeInstruction(SpvOpLoad, fGen.getType(*fBaseType), base, fVecPointer, out);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001956 SpvId shuffle = fGen.nextId(fBaseType);
John Stiles3f14d282021-02-05 09:31:04 -05001957 fGen.writeOpCode(SpvOpVectorShuffle, 5 + fBaseType->columns(), out);
1958 fGen.writeWord(fGen.getType(*fBaseType), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07001959 fGen.writeWord(shuffle, out);
1960 fGen.writeWord(base, out);
1961 fGen.writeWord(value, out);
John Stiles3f14d282021-02-05 09:31:04 -05001962 for (int i = 0; i < fBaseType->columns(); i++) {
ethannicholasb3058bd2016-07-01 08:22:01 -07001963 // current offset into the virtual vector, defaults to pulling the unmodified
1964 // value from the left side
1965 int offset = i;
1966 // check to see if we are writing this component
1967 for (size_t j = 0; j < fComponents.size(); j++) {
1968 if (fComponents[j] == i) {
Greg Daniel64773e62016-11-22 09:44:03 -05001969 // we're writing to this component, so adjust the offset to pull from
ethannicholasb3058bd2016-07-01 08:22:01 -07001970 // the correct component of the right side instead of preserving the
1971 // value from the left
John Stiles3f14d282021-02-05 09:31:04 -05001972 offset = (int) (j + fBaseType->columns());
ethannicholasb3058bd2016-07-01 08:22:01 -07001973 break;
1974 }
1975 }
1976 fGen.writeWord(offset, out);
1977 }
1978 fGen.writeInstruction(SpvOpStore, fVecPointer, shuffle, out);
1979 }
1980
1981private:
1982 SPIRVCodeGenerator& fGen;
1983 const SpvId fVecPointer;
John Stiles3f14d282021-02-05 09:31:04 -05001984 ComponentArray fComponents;
1985 const Type* fBaseType;
1986 const Type* fSwizzleType;
ethannicholasb3058bd2016-07-01 08:22:01 -07001987};
1988
John Stilese40d1662021-01-29 10:08:50 -05001989int SPIRVCodeGenerator::findUniformFieldIndex(const Variable& var) const {
1990 auto iter = fTopLevelUniformMap.find(&var);
1991 return (iter != fTopLevelUniformMap.end()) ? iter->second : -1;
1992}
1993
Greg Daniel64773e62016-11-22 09:44:03 -05001994std::unique_ptr<SPIRVCodeGenerator::LValue> SPIRVCodeGenerator::getLValue(const Expression& expr,
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001995 OutputStream& out) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001996 const Type& type = expr.type();
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001997 Precision precision = type.highPrecision() ? Precision::kDefault : Precision::kRelaxed;
Ethan Nicholase6592142020-09-08 10:22:09 -04001998 switch (expr.kind()) {
1999 case Expression::Kind::kVariableReference: {
John Stiles0de76f72021-01-29 09:19:39 -05002000 const Variable& var = *expr.as<VariableReference>().variable();
John Stilese40d1662021-01-29 10:08:50 -05002001 int uniformIdx = this->findUniformFieldIndex(var);
2002 if (uniformIdx >= 0) {
John Stiles9ce80f72021-03-11 22:35:19 -05002003 IntLiteral uniformIdxLiteral{/*offset=*/-1, uniformIdx, fContext.fTypes.fInt.get()};
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002004 SpvId memberId = this->nextId(nullptr);
John Stilese40d1662021-01-29 10:08:50 -05002005 SpvId typeId = this->getPointerType(type, SpvStorageClassUniform);
2006 SpvId uniformIdxId = this->writeIntLiteral(uniformIdxLiteral);
2007 this->writeInstruction(SpvOpAccessChain, typeId, memberId, fUniformBufferId,
2008 uniformIdxId, out);
Ethan Nicholase0707b72021-03-17 11:16:41 -04002009 return std::make_unique<PointerLValue>(*this, memberId,
2010 /*isMemoryObjectPointer=*/true,
2011 this->getType(type), precision);
John Stilese40d1662021-01-29 10:08:50 -05002012 }
Brian Osman99ddd2a2021-08-27 11:21:12 -04002013 SpvId typeId = this->getType(type, this->memoryLayoutForVariable(var));
ethannicholasd598f792016-07-25 10:08:54 -07002014 auto entry = fVariableMap.find(&var);
John Stiles9078a892021-08-18 15:03:17 -04002015 SkASSERTF(entry != fVariableMap.end(), "%s", expr.description().c_str());
Ethan Nicholase0707b72021-03-17 11:16:41 -04002016 return std::make_unique<PointerLValue>(*this, entry->second,
2017 /*isMemoryObjectPointer=*/true,
2018 typeId, precision);
ethannicholasb3058bd2016-07-01 08:22:01 -07002019 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002020 case Expression::Kind::kIndex: // fall through
2021 case Expression::Kind::kFieldAccess: {
ethannicholasb3058bd2016-07-01 08:22:01 -07002022 std::vector<SpvId> chain = this->getAccessChain(expr, out);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002023 SpvId member = this->nextId(nullptr);
ethannicholasb3058bd2016-07-01 08:22:01 -07002024 this->writeOpCode(SpvOpAccessChain, (SpvId) (3 + chain.size()), out);
Ethan Nicholas30d30222020-09-11 12:27:26 -04002025 this->writeWord(this->getPointerType(type, get_storage_class(expr)), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002026 this->writeWord(member, out);
2027 for (SpvId idx : chain) {
2028 this->writeWord(idx, out);
2029 }
Ethan Nicholase0707b72021-03-17 11:16:41 -04002030 return std::make_unique<PointerLValue>(*this, member, /*isMemoryObjectPointer=*/false,
2031 this->getType(type), precision);
ethannicholasb3058bd2016-07-01 08:22:01 -07002032 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002033 case Expression::Kind::kSwizzle: {
John Stiles0693fb82021-01-22 18:27:52 -05002034 const Swizzle& swizzle = expr.as<Swizzle>();
John Stiles3f14d282021-02-05 09:31:04 -05002035 std::unique_ptr<LValue> lvalue = this->getLValue(*swizzle.base(), out);
2036 if (lvalue->applySwizzle(swizzle.components(), type)) {
2037 return lvalue;
2038 }
2039 SpvId base = lvalue->getPointer();
2040 if (base == (SpvId) -1) {
Ethan Nicholas39f6da42021-08-23 13:10:07 -04002041 fContext.fErrors->error(swizzle.fOffset, "unable to retrieve lvalue from swizzle");
John Stiles5570c512020-11-19 17:58:07 -05002042 }
John Stiles3f14d282021-02-05 09:31:04 -05002043 if (swizzle.components().size() == 1) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002044 SpvId member = this->nextId(nullptr);
John Stilesb5db4822021-01-21 13:04:40 -05002045 SpvId typeId = this->getPointerType(type, get_storage_class(*swizzle.base()));
John Stiles9ce80f72021-03-11 22:35:19 -05002046 IntLiteral index(/*offset=*/-1, swizzle.components()[0],
2047 fContext.fTypes.fInt.get());
John Stilesb5db4822021-01-21 13:04:40 -05002048 SpvId indexId = this->writeIntLiteral(index);
2049 this->writeInstruction(SpvOpAccessChain, typeId, member, base, indexId, out);
Ethan Nicholase0707b72021-03-17 11:16:41 -04002050 return std::make_unique<PointerLValue>(*this,
2051 member,
2052 /*isMemoryObjectPointer=*/false,
2053 this->getType(type),
John Stiles5570c512020-11-19 17:58:07 -05002054 precision);
ethannicholasb3058bd2016-07-01 08:22:01 -07002055 } else {
John Stiles5570c512020-11-19 17:58:07 -05002056 return std::make_unique<SwizzleLValue>(*this, base, swizzle.components(),
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002057 swizzle.base()->type(), type);
ethannicholasb3058bd2016-07-01 08:22:01 -07002058 }
2059 }
Ethan Nicholas30d30222020-09-11 12:27:26 -04002060 default: {
Kevin Lubickbe03ef12021-06-16 15:28:00 -04002061 // expr isn't actually an lvalue, create a placeholder variable for it. This case
2062 // happens due to the need to store values in temporary variables during function
2063 // calls (see comments in getFunctionType); erroneous uses of rvalues as lvalues
2064 // should have been caught by IRGenerator
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002065 SpvId result = this->nextId(nullptr);
Ethan Nicholas30d30222020-09-11 12:27:26 -04002066 SpvId pointerType = this->getPointerType(type, SpvStorageClassFunction);
2067 this->writeInstruction(SpvOpVariable, pointerType, result, SpvStorageClassFunction,
ethannicholasd598f792016-07-25 10:08:54 -07002068 fVariableBuffer);
ethannicholasb3058bd2016-07-01 08:22:01 -07002069 this->writeInstruction(SpvOpStore, result, this->writeExpression(expr, out), out);
Ethan Nicholase0707b72021-03-17 11:16:41 -04002070 return std::make_unique<PointerLValue>(*this, result, /*isMemoryObjectPointer=*/true,
2071 this->getType(type), precision);
Ethan Nicholas30d30222020-09-11 12:27:26 -04002072 }
ethannicholasb3058bd2016-07-01 08:22:01 -07002073 }
2074}
2075
Ethan Nicholas0df1b042017-03-31 13:56:23 -04002076SpvId SPIRVCodeGenerator::writeVariableReference(const VariableReference& ref, OutputStream& out) {
John Stiles9078a892021-08-18 15:03:17 -04002077 const Variable* variable = ref.variable();
2078 if (variable->modifiers().fLayout.fBuiltin == DEVICE_FRAGCOORDS_BUILTIN) {
Brian Salomond8d85b92021-07-07 09:41:17 -04002079 // Down below, we rewrite raw references to sk_FragCoord with expressions that reference
2080 // DEVICE_FRAGCOORDS_BUILTIN. This is a fake variable that means we need to directly access
2081 // the fragcoord; do so now.
Ethan Nicholasa2d22b22021-07-15 10:35:54 -04002082 dsl::DSLGlobalVar fragCoord("sk_FragCoord");
Brian Salomond8d85b92021-07-07 09:41:17 -04002083 return this->getLValue(*dsl::DSLExpression(fragCoord).release(), out)->load(out);
2084 }
John Stiles9078a892021-08-18 15:03:17 -04002085 if (variable->modifiers().fLayout.fBuiltin == DEVICE_CLOCKWISE_BUILTIN) {
Brian Salomond8d85b92021-07-07 09:41:17 -04002086 // Down below, we rewrite raw references to sk_Clockwise with expressions that reference
2087 // DEVICE_CLOCKWISE_BUILTIN. This is a fake variable that means we need to directly
2088 // access front facing; do so now.
Ethan Nicholasa2d22b22021-07-15 10:35:54 -04002089 dsl::DSLGlobalVar clockwise("sk_Clockwise");
Brian Salomond8d85b92021-07-07 09:41:17 -04002090 return this->getLValue(*dsl::DSLExpression(clockwise).release(), out)->load(out);
2091 }
John Stilese40d1662021-01-29 10:08:50 -05002092
Brian Salomond8d85b92021-07-07 09:41:17 -04002093 // Handle inserting use of uniform to flip y when referencing sk_FragCoord.
Brian Salomond8d85b92021-07-07 09:41:17 -04002094 if (variable->modifiers().fLayout.fBuiltin == SK_FRAGCOORD_BUILTIN) {
2095 this->addRTFlipUniform(ref.fOffset);
2096 // Use sk_RTAdjust to compute the flipped coordinate
2097 using namespace dsl;
2098 const char* DEVICE_COORDS_NAME = "__device_FragCoords";
2099 SymbolTable& symbols = *dsl::DSLWriter::SymbolTable();
2100 // Use a uniform to flip the Y coordinate. The new expression will be written in
2101 // terms of __device_FragCoords, which is a fake variable that means "access the
2102 // underlying fragcoords directly without flipping it".
2103 DSLExpression rtFlip(DSLWriter::IRGenerator().convertIdentifier(/*offset=*/-1,
2104 SKSL_RTFLIP_NAME));
2105 if (!symbols[DEVICE_COORDS_NAME]) {
John Stiles0cac5ed2021-08-06 11:40:39 -04002106 AutoAttachPoolToThread attach(fProgram.fPool.get());
Brian Salomond8d85b92021-07-07 09:41:17 -04002107 Modifiers modifiers;
2108 modifiers.fLayout.fBuiltin = DEVICE_FRAGCOORDS_BUILTIN;
John Stilesd7437ee2021-08-02 11:56:16 -04002109 auto coordsVar = std::make_unique<Variable>(/*offset=*/-1,
2110 fContext.fModifiersPool->add(modifiers),
2111 DEVICE_COORDS_NAME,
2112 fContext.fTypes.fFloat4.get(),
2113 true,
2114 Variable::Storage::kGlobal);
2115 fSPIRVBonusVariables.insert(coordsVar.get());
2116 symbols.add(std::move(coordsVar));
Greg Daniela85e4bf2020-06-17 16:32:45 -04002117 }
Ethan Nicholasa2d22b22021-07-15 10:35:54 -04002118 DSLGlobalVar deviceCoord(DEVICE_COORDS_NAME);
Brian Salomond8d85b92021-07-07 09:41:17 -04002119 std::unique_ptr<Expression> rtFlipSkSLExpr = rtFlip.release();
2120 DSLExpression x = DSLExpression(rtFlipSkSLExpr->clone()).x();
2121 DSLExpression y = DSLExpression(std::move(rtFlipSkSLExpr)).y();
2122 return this->writeExpression(*dsl::Float4(deviceCoord.x(),
2123 std::move(x) + std::move(y) * deviceCoord.y(),
2124 deviceCoord.z(),
2125 deviceCoord.w()).release(),
2126 out);
Ethan Nicholas941e7e22016-12-12 15:33:30 -05002127 }
John Stiles1e1fe122021-01-29 12:18:46 -05002128
Brian Salomond8d85b92021-07-07 09:41:17 -04002129 // Handle flipping sk_Clockwise.
2130 if (variable->modifiers().fLayout.fBuiltin == SK_CLOCKWISE_BUILTIN) {
2131 this->addRTFlipUniform(ref.fOffset);
2132 using namespace dsl;
2133 const char* DEVICE_CLOCKWISE_NAME = "__device_Clockwise";
2134 SymbolTable& symbols = *dsl::DSLWriter::SymbolTable();
2135 // Use a uniform to flip the Y coordinate. The new expression will be written in
2136 // terms of __device_Clockwise, which is a fake variable that means "access the
2137 // underlying FrontFacing directly".
2138 DSLExpression rtFlip(DSLWriter::IRGenerator().convertIdentifier(/*offset=*/-1,
2139 SKSL_RTFLIP_NAME));
2140 if (!symbols[DEVICE_CLOCKWISE_NAME]) {
John Stiles0cac5ed2021-08-06 11:40:39 -04002141 AutoAttachPoolToThread attach(fProgram.fPool.get());
Brian Salomond8d85b92021-07-07 09:41:17 -04002142 Modifiers modifiers;
2143 modifiers.fLayout.fBuiltin = DEVICE_CLOCKWISE_BUILTIN;
John Stilesd7437ee2021-08-02 11:56:16 -04002144 auto clockwiseVar = std::make_unique<Variable>(/*offset=*/-1,
2145 fContext.fModifiersPool->add(modifiers),
2146 DEVICE_CLOCKWISE_NAME,
2147 fContext.fTypes.fBool.get(),
2148 true,
2149 Variable::Storage::kGlobal);
2150 fSPIRVBonusVariables.insert(clockwiseVar.get());
2151 symbols.add(std::move(clockwiseVar));
Brian Salomond8d85b92021-07-07 09:41:17 -04002152 }
Ethan Nicholasa2d22b22021-07-15 10:35:54 -04002153 DSLGlobalVar deviceClockwise(DEVICE_CLOCKWISE_NAME);
Brian Salomond8d85b92021-07-07 09:41:17 -04002154 // FrontFacing in Vulkan is defined in terms of a top-down render target. In skia,
2155 // we use the default convention of "counter-clockwise face is front".
2156 return this->writeExpression(*dsl::Bool(Select(rtFlip.y() > 0,
2157 !deviceClockwise,
2158 deviceClockwise)).release(),
2159 out);
Chris Daltonb91c4662018-08-01 10:46:22 -06002160 }
John Stiles1e1fe122021-01-29 12:18:46 -05002161
Brian Salomond8d85b92021-07-07 09:41:17 -04002162 return this->getLValue(ref, out)->load(out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002163}
2164
Ethan Nicholas0df1b042017-03-31 13:56:23 -04002165SpvId SPIRVCodeGenerator::writeIndexExpression(const IndexExpression& expr, OutputStream& out) {
John Stiles9aeed132020-11-24 17:36:06 -05002166 if (expr.base()->type().isVector()) {
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04002167 SpvId base = this->writeExpression(*expr.base(), out);
2168 SpvId index = this->writeExpression(*expr.index(), out);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002169 SpvId result = this->nextId(nullptr);
Ethan Nicholas30d30222020-09-11 12:27:26 -04002170 this->writeInstruction(SpvOpVectorExtractDynamic, this->getType(expr.type()), result, base,
Ethan Nicholasa9a06902019-01-07 14:42:40 -05002171 index, out);
2172 return result;
2173 }
ethannicholasb3058bd2016-07-01 08:22:01 -07002174 return getLValue(expr, out)->load(out);
2175}
2176
Ethan Nicholas0df1b042017-03-31 13:56:23 -04002177SpvId SPIRVCodeGenerator::writeFieldAccess(const FieldAccess& f, OutputStream& out) {
ethannicholasb3058bd2016-07-01 08:22:01 -07002178 return getLValue(f, out)->load(out);
2179}
2180
Ethan Nicholas0df1b042017-03-31 13:56:23 -04002181SpvId SPIRVCodeGenerator::writeSwizzle(const Swizzle& swizzle, OutputStream& out) {
Ethan Nicholas6b4d5812020-10-12 16:11:51 -04002182 SpvId base = this->writeExpression(*swizzle.base(), out);
Ethan Nicholas7f015882021-03-23 14:16:52 -04002183 SpvId result = this->nextId(&swizzle.type());
Ethan Nicholas6b4d5812020-10-12 16:11:51 -04002184 size_t count = swizzle.components().size();
ethannicholasb3058bd2016-07-01 08:22:01 -07002185 if (count == 1) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04002186 this->writeInstruction(SpvOpCompositeExtract, this->getType(swizzle.type()), result, base,
Ethan Nicholas6b4d5812020-10-12 16:11:51 -04002187 swizzle.components()[0], out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002188 } else {
2189 this->writeOpCode(SpvOpVectorShuffle, 5 + (int32_t) count, out);
Ethan Nicholas30d30222020-09-11 12:27:26 -04002190 this->writeWord(this->getType(swizzle.type()), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002191 this->writeWord(result, out);
2192 this->writeWord(base, out);
Brian Osman25647672020-09-15 15:16:56 -04002193 this->writeWord(base, out);
Ethan Nicholas6b4d5812020-10-12 16:11:51 -04002194 for (int component : swizzle.components()) {
Brian Osman25647672020-09-15 15:16:56 -04002195 this->writeWord(component, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002196 }
2197 }
2198 return result;
2199}
2200
Greg Daniel64773e62016-11-22 09:44:03 -05002201SpvId SPIRVCodeGenerator::writeBinaryOperation(const Type& resultType,
2202 const Type& operandType, SpvId lhs,
2203 SpvId rhs, SpvOp_ ifFloat, SpvOp_ ifInt,
Ethan Nicholas0df1b042017-03-31 13:56:23 -04002204 SpvOp_ ifUInt, SpvOp_ ifBool, OutputStream& out) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002205 SpvId result = this->nextId(&resultType);
ethannicholasd598f792016-07-25 10:08:54 -07002206 if (is_float(fContext, operandType)) {
ethannicholasb3058bd2016-07-01 08:22:01 -07002207 this->writeInstruction(ifFloat, this->getType(resultType), result, lhs, rhs, out);
ethannicholasd598f792016-07-25 10:08:54 -07002208 } else if (is_signed(fContext, operandType)) {
ethannicholasb3058bd2016-07-01 08:22:01 -07002209 this->writeInstruction(ifInt, this->getType(resultType), result, lhs, rhs, out);
ethannicholasd598f792016-07-25 10:08:54 -07002210 } else if (is_unsigned(fContext, operandType)) {
ethannicholasb3058bd2016-07-01 08:22:01 -07002211 this->writeInstruction(ifUInt, this->getType(resultType), result, lhs, rhs, out);
John Stiles123501f2020-12-09 10:08:13 -05002212 } else if (is_bool(fContext, operandType)) {
ethannicholasb3058bd2016-07-01 08:22:01 -07002213 this->writeInstruction(ifBool, this->getType(resultType), result, lhs, rhs, out);
2214 } else {
Ethan Nicholas39f6da42021-08-23 13:10:07 -04002215 fContext.fErrors->error(operandType.fOffset,
Ethan Nicholas3abc6c62021-08-13 11:20:09 -04002216 "unsupported operand for binary expression: " + operandType.description());
Ethan Nicholas2f4652f2021-03-12 18:48:48 +00002217 }
ethannicholasb3058bd2016-07-01 08:22:01 -07002218 return result;
2219}
2220
Ethan Nicholas48e24052018-03-14 13:51:39 -04002221SpvId SPIRVCodeGenerator::foldToBool(SpvId id, const Type& operandType, SpvOp op,
2222 OutputStream& out) {
John Stiles9aeed132020-11-24 17:36:06 -05002223 if (operandType.isVector()) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002224 SpvId result = this->nextId(nullptr);
John Stiles54e7c052021-01-11 14:22:36 -05002225 this->writeInstruction(op, this->getType(*fContext.fTypes.fBool), result, id, out);
Ethan Nicholasef653b82017-02-21 13:50:00 -05002226 return result;
2227 }
2228 return id;
2229}
2230
Ethan Nicholas68990be2017-07-13 09:36:52 -04002231SpvId SPIRVCodeGenerator::writeMatrixComparison(const Type& operandType, SpvId lhs, SpvId rhs,
2232 SpvOp_ floatOperator, SpvOp_ intOperator,
Ethan Nicholas0df21132018-07-10 09:37:51 -04002233 SpvOp_ vectorMergeOperator, SpvOp_ mergeOperator,
Ethan Nicholas68990be2017-07-13 09:36:52 -04002234 OutputStream& out) {
2235 SpvOp_ compareOp = is_float(fContext, operandType) ? floatOperator : intOperator;
John Stiles9aeed132020-11-24 17:36:06 -05002236 SkASSERT(operandType.isMatrix());
Ethan Nicholas0df21132018-07-10 09:37:51 -04002237 SpvId columnType = this->getType(operandType.componentType().toCompound(fContext,
2238 operandType.rows(),
2239 1));
John Stiles54e7c052021-01-11 14:22:36 -05002240 SpvId bvecType = this->getType(fContext.fTypes.fBool->toCompound(fContext,
Ethan Nicholas0df21132018-07-10 09:37:51 -04002241 operandType.rows(),
Ethan Nicholas68990be2017-07-13 09:36:52 -04002242 1));
John Stiles54e7c052021-01-11 14:22:36 -05002243 SpvId boolType = this->getType(*fContext.fTypes.fBool);
Ethan Nicholas68990be2017-07-13 09:36:52 -04002244 SpvId result = 0;
Ethan Nicholas0df21132018-07-10 09:37:51 -04002245 for (int i = 0; i < operandType.columns(); i++) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002246 SpvId columnL = this->nextId(&operandType);
Ethan Nicholas0df21132018-07-10 09:37:51 -04002247 this->writeInstruction(SpvOpCompositeExtract, columnType, columnL, lhs, i, out);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002248 SpvId columnR = this->nextId(&operandType);
Ethan Nicholas0df21132018-07-10 09:37:51 -04002249 this->writeInstruction(SpvOpCompositeExtract, columnType, columnR, rhs, i, out);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002250 SpvId compare = this->nextId(&operandType);
Ethan Nicholas0df21132018-07-10 09:37:51 -04002251 this->writeInstruction(compareOp, bvecType, compare, columnL, columnR, out);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002252 SpvId merge = this->nextId(nullptr);
Ethan Nicholas0df21132018-07-10 09:37:51 -04002253 this->writeInstruction(vectorMergeOperator, boolType, merge, compare, out);
Ethan Nicholas68990be2017-07-13 09:36:52 -04002254 if (result != 0) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002255 SpvId next = this->nextId(nullptr);
Ethan Nicholas0df21132018-07-10 09:37:51 -04002256 this->writeInstruction(mergeOperator, boolType, next, result, merge, out);
Ethan Nicholas68990be2017-07-13 09:36:52 -04002257 result = next;
2258 }
2259 else {
Ethan Nicholas0df21132018-07-10 09:37:51 -04002260 result = merge;
Ethan Nicholas68990be2017-07-13 09:36:52 -04002261 }
2262 }
2263 return result;
2264}
2265
Ethan Nicholas0df21132018-07-10 09:37:51 -04002266SpvId SPIRVCodeGenerator::writeComponentwiseMatrixBinary(const Type& operandType, SpvId lhs,
John Stiles43b593c2021-05-13 22:03:27 -04002267 SpvId rhs, SpvOp_ op, OutputStream& out) {
John Stiles9aeed132020-11-24 17:36:06 -05002268 SkASSERT(operandType.isMatrix());
Ethan Nicholas2f4652f2021-03-12 18:48:48 +00002269 SpvId columnType = this->getType(operandType.componentType().toCompound(fContext,
2270 operandType.rows(),
2271 1));
John Stiles43b593c2021-05-13 22:03:27 -04002272 std::vector<SpvId> columns;
2273 columns.reserve(operandType.columns());
Ethan Nicholas0df21132018-07-10 09:37:51 -04002274 for (int i = 0; i < operandType.columns(); i++) {
Ethan Nicholas7f015882021-03-23 14:16:52 -04002275 SpvId columnL = this->nextId(&operandType);
Ethan Nicholas2f4652f2021-03-12 18:48:48 +00002276 this->writeInstruction(SpvOpCompositeExtract, columnType, columnL, lhs, i, out);
Ethan Nicholas7f015882021-03-23 14:16:52 -04002277 SpvId columnR = this->nextId(&operandType);
Ethan Nicholas2f4652f2021-03-12 18:48:48 +00002278 this->writeInstruction(SpvOpCompositeExtract, columnType, columnR, rhs, i, out);
John Stiles43b593c2021-05-13 22:03:27 -04002279 columns.push_back(this->nextId(&operandType));
Ethan Nicholas2f4652f2021-03-12 18:48:48 +00002280 this->writeInstruction(op, columnType, columns[i], columnL, columnR, out);
Ethan Nicholas0df21132018-07-10 09:37:51 -04002281 }
John Stiles43b593c2021-05-13 22:03:27 -04002282 return this->writeComposite(columns, operandType, out);
Ethan Nicholas0df21132018-07-10 09:37:51 -04002283}
2284
John Stiles9485b552021-01-27 11:47:00 -05002285static std::unique_ptr<Expression> create_literal_1(const Context& context, const Type& type) {
Ethan Nicholas49465b42019-04-17 12:22:21 -04002286 if (type.isInteger()) {
John Stiles9ce80f72021-03-11 22:35:19 -05002287 return IntLiteral::Make(/*offset=*/-1, /*value=*/1, &type);
ethannicholasb3058bd2016-07-01 08:22:01 -07002288 }
Ethan Nicholas49465b42019-04-17 12:22:21 -04002289 else if (type.isFloat()) {
John Stiles9ce80f72021-03-11 22:35:19 -05002290 return FloatLiteral::Make(/*offset=*/-1, /*value=*/1.0, &type);
ethannicholasb3058bd2016-07-01 08:22:01 -07002291 } else {
John Stilesf57207b2021-02-02 17:50:34 -05002292 SK_ABORT("math is unsupported on type '%s'", String(type.name()).c_str());
ethannicholasb3058bd2016-07-01 08:22:01 -07002293 }
Ethan Nicholas49465b42019-04-17 12:22:21 -04002294}
2295
John Stilesd94bfdd2021-03-25 11:44:08 -04002296SpvId SPIRVCodeGenerator::writeReciprocal(const Type& type, SpvId value, OutputStream& out) {
2297 SkASSERT(type.isFloat());
2298 SpvId one = this->writeFloatLiteral({/*offset=*/-1, /*value=*/1, &type});
2299 SpvId reciprocal = this->nextId(&type);
2300 this->writeInstruction(SpvOpFDiv, this->getType(type), reciprocal, one, value, out);
2301 return reciprocal;
2302}
2303
John Stilesa91bf052021-05-17 09:34:03 -04002304SpvId SPIRVCodeGenerator::writeScalarToMatrixSplat(const Type& matrixType,
2305 SpvId scalarId,
2306 OutputStream& out) {
2307 // Splat the scalar into a vector.
2308 const Type& vectorType = matrixType.componentType().toCompound(fContext,
2309 /*columns=*/matrixType.rows(),
2310 /*rows=*/1);
2311 std::vector<SpvId> vecArguments(/*count*/ matrixType.rows(), /*value*/ scalarId);
2312 SpvId vectorId = this->writeComposite(vecArguments, vectorType, out);
2313
2314 // Splat the vector into a matrix.
2315 std::vector<SpvId> matArguments(/*count*/ matrixType.columns(), /*value*/ vectorId);
2316 return this->writeComposite(matArguments, matrixType, out);
2317}
2318
John Stiles45990502021-02-16 10:55:27 -05002319SpvId SPIRVCodeGenerator::writeBinaryExpression(const Type& leftType, SpvId lhs, Operator op,
Ethan Nicholas49465b42019-04-17 12:22:21 -04002320 const Type& rightType, SpvId rhs,
2321 const Type& resultType, OutputStream& out) {
John Stilesd0614f22020-12-09 11:11:41 -05002322 // The comma operator ignores the type of the left-hand side entirely.
John Stiles45990502021-02-16 10:55:27 -05002323 if (op.kind() == Token::Kind::TK_COMMA) {
John Stilesd0614f22020-12-09 11:11:41 -05002324 return rhs;
2325 }
Ethan Nicholas48e24052018-03-14 13:51:39 -04002326 // overall type we are operating on: float2, int, uint4...
ethannicholasb3058bd2016-07-01 08:22:01 -07002327 const Type* operandType;
Ethan Nicholas48e24052018-03-14 13:51:39 -04002328 // IR allows mismatched types in expressions (e.g. float2 * float), but they need special
2329 // handling in SPIR-V
Ethan Nicholas49465b42019-04-17 12:22:21 -04002330 if (this->getActualType(leftType) != this->getActualType(rightType)) {
John Stiles9aeed132020-11-24 17:36:06 -05002331 if (leftType.isVector() && rightType.isNumber()) {
John Stilesd94bfdd2021-03-25 11:44:08 -04002332 if (resultType.componentType().isFloat()) {
2333 switch (op.kind()) {
2334 case Token::Kind::TK_SLASH: {
2335 rhs = this->writeReciprocal(rightType, rhs, out);
2336 [[fallthrough]];
2337 }
2338 case Token::Kind::TK_STAR: {
2339 SpvId result = this->nextId(&resultType);
2340 this->writeInstruction(SpvOpVectorTimesScalar, this->getType(resultType),
2341 result, lhs, rhs, out);
2342 return result;
2343 }
2344 default:
2345 break;
2346 }
Ethan Nicholas49465b42019-04-17 12:22:21 -04002347 }
ethannicholasb3058bd2016-07-01 08:22:01 -07002348 // promote number to vector
Ethan Nicholas49465b42019-04-17 12:22:21 -04002349 const Type& vecType = leftType;
Ethan Nicholas7f015882021-03-23 14:16:52 -04002350 SpvId vec = this->nextId(&vecType);
Ethan Nicholas48e24052018-03-14 13:51:39 -04002351 this->writeOpCode(SpvOpCompositeConstruct, 3 + vecType.columns(), out);
2352 this->writeWord(this->getType(vecType), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002353 this->writeWord(vec, out);
Ethan Nicholas48e24052018-03-14 13:51:39 -04002354 for (int i = 0; i < vecType.columns(); i++) {
ethannicholasb3058bd2016-07-01 08:22:01 -07002355 this->writeWord(rhs, out);
2356 }
2357 rhs = vec;
Ethan Nicholas49465b42019-04-17 12:22:21 -04002358 operandType = &leftType;
John Stiles9aeed132020-11-24 17:36:06 -05002359 } else if (rightType.isVector() && leftType.isNumber()) {
John Stilesd94bfdd2021-03-25 11:44:08 -04002360 if (resultType.componentType().isFloat()) {
2361 if (op.kind() == Token::Kind::TK_STAR) {
2362 SpvId result = this->nextId(&resultType);
2363 this->writeInstruction(SpvOpVectorTimesScalar, this->getType(resultType),
2364 result, rhs, lhs, out);
2365 return result;
2366 }
Ethan Nicholas49465b42019-04-17 12:22:21 -04002367 }
ethannicholasb3058bd2016-07-01 08:22:01 -07002368 // promote number to vector
Ethan Nicholas49465b42019-04-17 12:22:21 -04002369 const Type& vecType = rightType;
Ethan Nicholas7f015882021-03-23 14:16:52 -04002370 SpvId vec = this->nextId(&vecType);
Ethan Nicholas48e24052018-03-14 13:51:39 -04002371 this->writeOpCode(SpvOpCompositeConstruct, 3 + vecType.columns(), out);
2372 this->writeWord(this->getType(vecType), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002373 this->writeWord(vec, out);
Ethan Nicholas48e24052018-03-14 13:51:39 -04002374 for (int i = 0; i < vecType.columns(); i++) {
ethannicholasb3058bd2016-07-01 08:22:01 -07002375 this->writeWord(lhs, out);
2376 }
2377 lhs = vec;
Ethan Nicholas49465b42019-04-17 12:22:21 -04002378 operandType = &rightType;
John Stiles9aeed132020-11-24 17:36:06 -05002379 } else if (leftType.isMatrix()) {
John Stilesa91bf052021-05-17 09:34:03 -04002380 if (op.kind() == Token::Kind::TK_STAR) {
2381 // Matrix-times-vector and matrix-times-scalar have dedicated ops in SPIR-V.
2382 SpvOp_ spvop;
2383 if (rightType.isMatrix()) {
2384 spvop = SpvOpMatrixTimesMatrix;
2385 } else if (rightType.isVector()) {
2386 spvop = SpvOpMatrixTimesVector;
2387 } else {
2388 SkASSERT(rightType.isScalar());
2389 spvop = SpvOpMatrixTimesScalar;
2390 }
2391 SpvId result = this->nextId(&resultType);
2392 this->writeInstruction(spvop, this->getType(resultType), result, lhs, rhs, out);
2393 return result;
ethannicholasb3058bd2016-07-01 08:22:01 -07002394 } else {
John Stilesa91bf052021-05-17 09:34:03 -04002395 // Matrix-op-vector is not supported in GLSL/SkSL for non-multiplication ops; we
2396 // expect to have a scalar here.
John Stiles9aeed132020-11-24 17:36:06 -05002397 SkASSERT(rightType.isScalar());
John Stilesa91bf052021-05-17 09:34:03 -04002398
2399 // Splat rhs across an entire matrix so we can reuse the matrix-op-matrix path.
2400 SpvId rhsMatrix = this->writeScalarToMatrixSplat(leftType, rhs, out);
2401
2402 // Perform this operation as matrix-op-matrix.
2403 return this->writeBinaryExpression(leftType, lhs, op, leftType, rhsMatrix,
2404 resultType, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002405 }
John Stiles9aeed132020-11-24 17:36:06 -05002406 } else if (rightType.isMatrix()) {
John Stilesa91bf052021-05-17 09:34:03 -04002407 if (op.kind() == Token::Kind::TK_STAR) {
2408 // Matrix-times-vector and matrix-times-scalar have dedicated ops in SPIR-V.
2409 SpvId result = this->nextId(&resultType);
2410 if (leftType.isVector()) {
2411 this->writeInstruction(SpvOpVectorTimesMatrix, this->getType(resultType),
2412 result, lhs, rhs, out);
2413 } else {
2414 SkASSERT(leftType.isScalar());
2415 this->writeInstruction(SpvOpMatrixTimesScalar, this->getType(resultType),
2416 result, rhs, lhs, out);
2417 }
2418 return result;
ethannicholasb3058bd2016-07-01 08:22:01 -07002419 } else {
John Stilesa91bf052021-05-17 09:34:03 -04002420 // Vector-op-matrix is not supported in GLSL/SkSL for non-multiplication ops; we
2421 // expect to have a scalar here.
John Stiles9aeed132020-11-24 17:36:06 -05002422 SkASSERT(leftType.isScalar());
John Stilesa91bf052021-05-17 09:34:03 -04002423
2424 // Splat lhs across an entire matrix so we can reuse the matrix-op-matrix path.
2425 SpvId lhsMatrix = this->writeScalarToMatrixSplat(rightType, lhs, out);
2426
2427 // Perform this operation as matrix-op-matrix.
2428 return this->writeBinaryExpression(rightType, lhsMatrix, op, rightType, rhs,
2429 resultType, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002430 }
ethannicholasb3058bd2016-07-01 08:22:01 -07002431 } else {
Ethan Nicholas39f6da42021-08-23 13:10:07 -04002432 fContext.fErrors->error(leftType.fOffset, "unsupported mixed-type expression");
Ethan Nicholas49465b42019-04-17 12:22:21 -04002433 return -1;
ethannicholasb3058bd2016-07-01 08:22:01 -07002434 }
2435 } else {
John Stiles2d4f9592020-10-30 10:29:12 -04002436 operandType = &this->getActualType(leftType);
Ethan Nicholas49465b42019-04-17 12:22:21 -04002437 SkASSERT(*operandType == this->getActualType(rightType));
ethannicholasb3058bd2016-07-01 08:22:01 -07002438 }
John Stiles45990502021-02-16 10:55:27 -05002439 switch (op.kind()) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002440 case Token::Kind::TK_EQEQ: {
John Stiles9aeed132020-11-24 17:36:06 -05002441 if (operandType->isMatrix()) {
Ethan Nicholas68990be2017-07-13 09:36:52 -04002442 return this->writeMatrixComparison(*operandType, lhs, rhs, SpvOpFOrdEqual,
Ethan Nicholas0df21132018-07-10 09:37:51 -04002443 SpvOpIEqual, SpvOpAll, SpvOpLogicalAnd, out);
Ethan Nicholas68990be2017-07-13 09:36:52 -04002444 }
John Stilesbc5c2a02021-04-08 11:44:53 -04002445 if (operandType->isStruct()) {
2446 return this->writeStructComparison(*operandType, lhs, op, rhs, out);
2447 }
John Stiles35092102021-04-08 23:30:51 -04002448 if (operandType->isArray()) {
2449 return this->writeArrayComparison(*operandType, lhs, op, rhs, out);
2450 }
John Stiles4a7dc462020-11-25 11:08:08 -05002451 SkASSERT(resultType.isBoolean());
Ethan Nicholas48e24052018-03-14 13:51:39 -04002452 const Type* tmpType;
John Stiles9aeed132020-11-24 17:36:06 -05002453 if (operandType->isVector()) {
John Stiles54e7c052021-01-11 14:22:36 -05002454 tmpType = &fContext.fTypes.fBool->toCompound(fContext,
2455 operandType->columns(),
2456 operandType->rows());
Ethan Nicholas48e24052018-03-14 13:51:39 -04002457 } else {
2458 tmpType = &resultType;
2459 }
2460 return this->foldToBool(this->writeBinaryOperation(*tmpType, *operandType, lhs, rhs,
Ethan Nicholasef653b82017-02-21 13:50:00 -05002461 SpvOpFOrdEqual, SpvOpIEqual,
2462 SpvOpIEqual, SpvOpLogicalEqual, out),
Ethan Nicholas48e24052018-03-14 13:51:39 -04002463 *operandType, SpvOpAll, out);
Ethan Nicholasef653b82017-02-21 13:50:00 -05002464 }
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002465 case Token::Kind::TK_NEQ:
John Stiles9aeed132020-11-24 17:36:06 -05002466 if (operandType->isMatrix()) {
Ethan Nicholas68990be2017-07-13 09:36:52 -04002467 return this->writeMatrixComparison(*operandType, lhs, rhs, SpvOpFOrdNotEqual,
Ethan Nicholas0df21132018-07-10 09:37:51 -04002468 SpvOpINotEqual, SpvOpAny, SpvOpLogicalOr, out);
Ethan Nicholas68990be2017-07-13 09:36:52 -04002469 }
John Stilesbc5c2a02021-04-08 11:44:53 -04002470 if (operandType->isStruct()) {
2471 return this->writeStructComparison(*operandType, lhs, op, rhs, out);
2472 }
John Stiles35092102021-04-08 23:30:51 -04002473 if (operandType->isArray()) {
2474 return this->writeArrayComparison(*operandType, lhs, op, rhs, out);
2475 }
John Stiles4a7dc462020-11-25 11:08:08 -05002476 [[fallthrough]];
2477 case Token::Kind::TK_LOGICALXOR:
2478 SkASSERT(resultType.isBoolean());
Ethan Nicholas48e24052018-03-14 13:51:39 -04002479 const Type* tmpType;
John Stiles9aeed132020-11-24 17:36:06 -05002480 if (operandType->isVector()) {
John Stiles54e7c052021-01-11 14:22:36 -05002481 tmpType = &fContext.fTypes.fBool->toCompound(fContext,
2482 operandType->columns(),
2483 operandType->rows());
Ethan Nicholas48e24052018-03-14 13:51:39 -04002484 } else {
2485 tmpType = &resultType;
2486 }
2487 return this->foldToBool(this->writeBinaryOperation(*tmpType, *operandType, lhs, rhs,
Ethan Nicholasef653b82017-02-21 13:50:00 -05002488 SpvOpFOrdNotEqual, SpvOpINotEqual,
2489 SpvOpINotEqual, SpvOpLogicalNotEqual,
2490 out),
Ethan Nicholas48e24052018-03-14 13:51:39 -04002491 *operandType, SpvOpAny, out);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002492 case Token::Kind::TK_GT:
John Stiles4a7dc462020-11-25 11:08:08 -05002493 SkASSERT(resultType.isBoolean());
Greg Daniel64773e62016-11-22 09:44:03 -05002494 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs,
2495 SpvOpFOrdGreaterThan, SpvOpSGreaterThan,
ethannicholasb3058bd2016-07-01 08:22:01 -07002496 SpvOpUGreaterThan, SpvOpUndef, out);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002497 case Token::Kind::TK_LT:
John Stiles4a7dc462020-11-25 11:08:08 -05002498 SkASSERT(resultType.isBoolean());
Greg Daniel64773e62016-11-22 09:44:03 -05002499 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs, SpvOpFOrdLessThan,
ethannicholasb3058bd2016-07-01 08:22:01 -07002500 SpvOpSLessThan, SpvOpULessThan, SpvOpUndef, out);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002501 case Token::Kind::TK_GTEQ:
John Stiles4a7dc462020-11-25 11:08:08 -05002502 SkASSERT(resultType.isBoolean());
Greg Daniel64773e62016-11-22 09:44:03 -05002503 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs,
2504 SpvOpFOrdGreaterThanEqual, SpvOpSGreaterThanEqual,
ethannicholasb3058bd2016-07-01 08:22:01 -07002505 SpvOpUGreaterThanEqual, SpvOpUndef, out);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002506 case Token::Kind::TK_LTEQ:
John Stiles4a7dc462020-11-25 11:08:08 -05002507 SkASSERT(resultType.isBoolean());
Greg Daniel64773e62016-11-22 09:44:03 -05002508 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs,
2509 SpvOpFOrdLessThanEqual, SpvOpSLessThanEqual,
ethannicholasb3058bd2016-07-01 08:22:01 -07002510 SpvOpULessThanEqual, SpvOpUndef, out);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002511 case Token::Kind::TK_PLUS:
John Stiles9aeed132020-11-24 17:36:06 -05002512 if (leftType.isMatrix() && rightType.isMatrix()) {
Ethan Nicholas49465b42019-04-17 12:22:21 -04002513 SkASSERT(leftType == rightType);
John Stiles43b593c2021-05-13 22:03:27 -04002514 return this->writeComponentwiseMatrixBinary(leftType, lhs, rhs, SpvOpFAdd, out);
Ethan Nicholas0df21132018-07-10 09:37:51 -04002515 }
Greg Daniel64773e62016-11-22 09:44:03 -05002516 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs, SpvOpFAdd,
ethannicholasb3058bd2016-07-01 08:22:01 -07002517 SpvOpIAdd, SpvOpIAdd, SpvOpUndef, out);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002518 case Token::Kind::TK_MINUS:
John Stiles9aeed132020-11-24 17:36:06 -05002519 if (leftType.isMatrix() && rightType.isMatrix()) {
Ethan Nicholas49465b42019-04-17 12:22:21 -04002520 SkASSERT(leftType == rightType);
John Stiles43b593c2021-05-13 22:03:27 -04002521 return this->writeComponentwiseMatrixBinary(leftType, lhs, rhs, SpvOpFSub, out);
Ethan Nicholas0df21132018-07-10 09:37:51 -04002522 }
Greg Daniel64773e62016-11-22 09:44:03 -05002523 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs, SpvOpFSub,
ethannicholasb3058bd2016-07-01 08:22:01 -07002524 SpvOpISub, SpvOpISub, SpvOpUndef, out);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002525 case Token::Kind::TK_STAR:
John Stiles9aeed132020-11-24 17:36:06 -05002526 if (leftType.isMatrix() && rightType.isMatrix()) {
ethannicholasb3058bd2016-07-01 08:22:01 -07002527 // matrix multiply
Ethan Nicholas7f015882021-03-23 14:16:52 -04002528 SpvId result = this->nextId(&resultType);
ethannicholasb3058bd2016-07-01 08:22:01 -07002529 this->writeInstruction(SpvOpMatrixTimesMatrix, this->getType(resultType), result,
2530 lhs, rhs, out);
2531 return result;
2532 }
Greg Daniel64773e62016-11-22 09:44:03 -05002533 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs, SpvOpFMul,
ethannicholasb3058bd2016-07-01 08:22:01 -07002534 SpvOpIMul, SpvOpIMul, SpvOpUndef, out);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002535 case Token::Kind::TK_SLASH:
John Stilesbdf3bb72021-05-17 09:34:23 -04002536 if (leftType.isMatrix() && rightType.isMatrix()) {
2537 SkASSERT(leftType == rightType);
2538 return this->writeComponentwiseMatrixBinary(leftType, lhs, rhs, SpvOpFDiv, out);
2539 }
Greg Daniel64773e62016-11-22 09:44:03 -05002540 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs, SpvOpFDiv,
ethannicholasb3058bd2016-07-01 08:22:01 -07002541 SpvOpSDiv, SpvOpUDiv, SpvOpUndef, out);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002542 case Token::Kind::TK_PERCENT:
Ethan Nicholasb3d0f7c2017-05-17 13:13:21 -04002543 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs, SpvOpFMod,
2544 SpvOpSMod, SpvOpUMod, SpvOpUndef, out);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002545 case Token::Kind::TK_SHL:
Ethan Nicholasfd444be2017-07-05 10:05:54 -04002546 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs, SpvOpUndef,
2547 SpvOpShiftLeftLogical, SpvOpShiftLeftLogical,
2548 SpvOpUndef, out);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002549 case Token::Kind::TK_SHR:
Ethan Nicholasfd444be2017-07-05 10:05:54 -04002550 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs, SpvOpUndef,
2551 SpvOpShiftRightArithmetic, SpvOpShiftRightLogical,
2552 SpvOpUndef, out);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002553 case Token::Kind::TK_BITWISEAND:
Ethan Nicholasfd444be2017-07-05 10:05:54 -04002554 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs, SpvOpUndef,
2555 SpvOpBitwiseAnd, SpvOpBitwiseAnd, SpvOpUndef, out);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002556 case Token::Kind::TK_BITWISEOR:
Ethan Nicholasfd444be2017-07-05 10:05:54 -04002557 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs, SpvOpUndef,
2558 SpvOpBitwiseOr, SpvOpBitwiseOr, SpvOpUndef, out);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002559 case Token::Kind::TK_BITWISEXOR:
Ethan Nicholasfd444be2017-07-05 10:05:54 -04002560 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs, SpvOpUndef,
2561 SpvOpBitwiseXor, SpvOpBitwiseXor, SpvOpUndef, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002562 default:
Ethan Nicholas39f6da42021-08-23 13:10:07 -04002563 fContext.fErrors->error(0, "unsupported token");
Ethan Nicholas49465b42019-04-17 12:22:21 -04002564 return -1;
ethannicholasb3058bd2016-07-01 08:22:01 -07002565 }
2566}
2567
John Stiles35092102021-04-08 23:30:51 -04002568SpvId SPIRVCodeGenerator::writeArrayComparison(const Type& arrayType, SpvId lhs, Operator op,
2569 SpvId rhs, OutputStream& out) {
2570 // The inputs must be arrays, and the op must be == or !=.
2571 SkASSERT(op.kind() == Token::Kind::TK_EQEQ || op.kind() == Token::Kind::TK_NEQ);
2572 SkASSERT(arrayType.isArray());
2573 const Type& componentType = arrayType.componentType();
2574 const SpvId componentTypeId = this->getType(componentType);
2575 const int arraySize = arrayType.columns();
2576 SkASSERT(arraySize > 0);
2577
2578 // Synthesize equality checks for each item in the array.
2579 const Type& boolType = *fContext.fTypes.fBool;
2580 SpvId allComparisons = (SpvId)-1;
2581 for (int index = 0; index < arraySize; ++index) {
2582 // Get the left and right item in the array.
2583 SpvId itemL = this->nextId(&componentType);
2584 this->writeInstruction(SpvOpCompositeExtract, componentTypeId, itemL, lhs, index, out);
2585 SpvId itemR = this->nextId(&componentType);
2586 this->writeInstruction(SpvOpCompositeExtract, componentTypeId, itemR, rhs, index, out);
2587 // Use `writeBinaryExpression` with the requested == or != operator on these items.
2588 SpvId comparison = this->writeBinaryExpression(componentType, itemL, op,
2589 componentType, itemR, boolType, out);
2590 // Merge this comparison result with all the other comparisons we've done.
2591 allComparisons = this->mergeComparisons(comparison, allComparisons, op, out);
2592 }
2593 return allComparisons;
2594}
2595
John Stilesbc5c2a02021-04-08 11:44:53 -04002596SpvId SPIRVCodeGenerator::writeStructComparison(const Type& structType, SpvId lhs, Operator op,
2597 SpvId rhs, OutputStream& out) {
2598 // The inputs must be structs containing fields, and the op must be == or !=.
John Stilesbc5c2a02021-04-08 11:44:53 -04002599 SkASSERT(op.kind() == Token::Kind::TK_EQEQ || op.kind() == Token::Kind::TK_NEQ);
John Stiles35092102021-04-08 23:30:51 -04002600 SkASSERT(structType.isStruct());
John Stilesbc5c2a02021-04-08 11:44:53 -04002601 const std::vector<Type::Field>& fields = structType.fields();
2602 SkASSERT(!fields.empty());
2603
2604 // Synthesize equality checks for each field in the struct.
2605 const Type& boolType = *fContext.fTypes.fBool;
John Stilesbc5c2a02021-04-08 11:44:53 -04002606 SpvId allComparisons = (SpvId)-1;
2607 for (int index = 0; index < (int)fields.size(); ++index) {
2608 // Get the left and right versions of this field.
2609 const Type& fieldType = *fields[index].fType;
John Stiles35092102021-04-08 23:30:51 -04002610 const SpvId fieldTypeId = this->getType(fieldType);
John Stilesbc5c2a02021-04-08 11:44:53 -04002611
2612 SpvId fieldL = this->nextId(&fieldType);
2613 this->writeInstruction(SpvOpCompositeExtract, fieldTypeId, fieldL, lhs, index, out);
2614 SpvId fieldR = this->nextId(&fieldType);
2615 this->writeInstruction(SpvOpCompositeExtract, fieldTypeId, fieldR, rhs, index, out);
2616 // Use `writeBinaryExpression` with the requested == or != operator on these fields.
2617 SpvId comparison = this->writeBinaryExpression(fieldType, fieldL, op, fieldType, fieldR,
2618 boolType, out);
John Stiles35092102021-04-08 23:30:51 -04002619 // Merge this comparison result with all the other comparisons we've done.
2620 allComparisons = this->mergeComparisons(comparison, allComparisons, op, out);
John Stilesbc5c2a02021-04-08 11:44:53 -04002621 }
2622 return allComparisons;
2623}
2624
John Stiles35092102021-04-08 23:30:51 -04002625SpvId SPIRVCodeGenerator::mergeComparisons(SpvId comparison, SpvId allComparisons, Operator op,
2626 OutputStream& out) {
2627 // If this is the first entry, we don't need to merge comparison results with anything.
2628 if (allComparisons == (SpvId)-1) {
2629 return comparison;
2630 }
2631 // Use LogicalAnd or LogicalOr to combine the comparison with all the other comparisons.
2632 const Type& boolType = *fContext.fTypes.fBool;
2633 SpvId boolTypeId = this->getType(boolType);
2634 SpvId logicalOp = this->nextId(&boolType);
2635 switch (op.kind()) {
2636 case Token::Kind::TK_EQEQ:
2637 this->writeInstruction(SpvOpLogicalAnd, boolTypeId, logicalOp,
2638 comparison, allComparisons, out);
2639 break;
2640 case Token::Kind::TK_NEQ:
2641 this->writeInstruction(SpvOpLogicalOr, boolTypeId, logicalOp,
2642 comparison, allComparisons, out);
2643 break;
2644 default:
2645 SkDEBUGFAILF("mergeComparisons only supports == and !=, not %s", op.operatorName());
2646 return (SpvId)-1;
2647 }
2648 return logicalOp;
2649}
2650
John Stilesbc5c2a02021-04-08 11:44:53 -04002651static float division_by_literal_value(Operator op, const Expression& right) {
2652 // If this is a division by a literal value, returns that literal value. Otherwise, returns 0.
2653 if (op.kind() == Token::Kind::TK_SLASH && right.is<FloatLiteral>()) {
2654 float rhsValue = right.as<FloatLiteral>().value();
2655 if (std::isfinite(rhsValue)) {
2656 return rhsValue;
2657 }
2658 }
2659 return 0.0f;
2660}
2661
Ethan Nicholas49465b42019-04-17 12:22:21 -04002662SpvId SPIRVCodeGenerator::writeBinaryExpression(const BinaryExpression& b, OutputStream& out) {
John Stiles2396fb82021-03-25 11:44:55 -04002663 const Expression* left = b.left().get();
2664 const Expression* right = b.right().get();
John Stiles45990502021-02-16 10:55:27 -05002665 Operator op = b.getOperator();
John Stilesbc5c2a02021-04-08 11:44:53 -04002666
John Stiles45990502021-02-16 10:55:27 -05002667 switch (op.kind()) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002668 case Token::Kind::TK_EQ: {
John Stilesbc5c2a02021-04-08 11:44:53 -04002669 // Handles assignment.
John Stiles2396fb82021-03-25 11:44:55 -04002670 SpvId rhs = this->writeExpression(*right, out);
2671 this->getLValue(*left, out)->store(rhs, out);
Ethan Nicholas49465b42019-04-17 12:22:21 -04002672 return rhs;
2673 }
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002674 case Token::Kind::TK_LOGICALAND:
John Stilesbc5c2a02021-04-08 11:44:53 -04002675 // Handles short-circuiting; we don't necessarily evaluate both LHS and RHS.
2676 return this->writeLogicalAnd(*b.left(), *b.right(), out);
2677
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002678 case Token::Kind::TK_LOGICALOR:
John Stilesbc5c2a02021-04-08 11:44:53 -04002679 // Handles short-circuiting; we don't necessarily evaluate both LHS and RHS.
2680 return this->writeLogicalOr(*b.left(), *b.right(), out);
2681
Ethan Nicholas49465b42019-04-17 12:22:21 -04002682 default:
2683 break;
2684 }
2685
2686 std::unique_ptr<LValue> lvalue;
2687 SpvId lhs;
John Stiles45990502021-02-16 10:55:27 -05002688 if (op.isAssignment()) {
John Stiles2396fb82021-03-25 11:44:55 -04002689 lvalue = this->getLValue(*left, out);
Ethan Nicholas49465b42019-04-17 12:22:21 -04002690 lhs = lvalue->load(out);
2691 } else {
2692 lvalue = nullptr;
John Stiles2396fb82021-03-25 11:44:55 -04002693 lhs = this->writeExpression(*left, out);
Ethan Nicholas49465b42019-04-17 12:22:21 -04002694 }
John Stiles2396fb82021-03-25 11:44:55 -04002695
John Stilesbc5c2a02021-04-08 11:44:53 -04002696 SpvId rhs;
2697 float rhsValue = division_by_literal_value(op, *right);
2698 if (rhsValue != 0.0f) {
2699 // Rewrite floating-point division by a literal into multiplication by the reciprocal.
2700 // This converts `expr / 2` into `expr * 0.5`
2701 // This improves codegen, especially for certain types of divides (e.g. vector/scalar).
2702 op = Operator(Token::Kind::TK_STAR);
2703 FloatLiteral reciprocal{right->fOffset, 1.0f / rhsValue, &right->type()};
2704 rhs = this->writeExpression(reciprocal, out);
2705 } else {
2706 // Write the right-hand side expression normally.
John Stiles2396fb82021-03-25 11:44:55 -04002707 rhs = this->writeExpression(*right, out);
2708 }
2709
2710 SpvId result = this->writeBinaryExpression(left->type(), lhs, op.removeAssignment(),
2711 right->type(), rhs, b.type(), out);
Ethan Nicholas49465b42019-04-17 12:22:21 -04002712 if (lvalue) {
2713 lvalue->store(result, out);
2714 }
2715 return result;
2716}
2717
John Stilesbc5c2a02021-04-08 11:44:53 -04002718SpvId SPIRVCodeGenerator::writeLogicalAnd(const Expression& left, const Expression& right,
2719 OutputStream& out) {
John Stiles9ce80f72021-03-11 22:35:19 -05002720 BoolLiteral falseLiteral(/*offset=*/-1, /*value=*/false, fContext.fTypes.fBool.get());
ethannicholasb3058bd2016-07-01 08:22:01 -07002721 SpvId falseConstant = this->writeBoolLiteral(falseLiteral);
John Stilesbc5c2a02021-04-08 11:44:53 -04002722 SpvId lhs = this->writeExpression(left, out);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002723 SpvId rhsLabel = this->nextId(nullptr);
2724 SpvId end = this->nextId(nullptr);
ethannicholasb3058bd2016-07-01 08:22:01 -07002725 SpvId lhsBlock = fCurrentBlock;
2726 this->writeInstruction(SpvOpSelectionMerge, end, SpvSelectionControlMaskNone, out);
2727 this->writeInstruction(SpvOpBranchConditional, lhs, rhsLabel, end, out);
2728 this->writeLabel(rhsLabel, out);
John Stilesbc5c2a02021-04-08 11:44:53 -04002729 SpvId rhs = this->writeExpression(right, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002730 SpvId rhsBlock = fCurrentBlock;
2731 this->writeInstruction(SpvOpBranch, end, out);
2732 this->writeLabel(end, out);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002733 SpvId result = this->nextId(nullptr);
John Stiles54e7c052021-01-11 14:22:36 -05002734 this->writeInstruction(SpvOpPhi, this->getType(*fContext.fTypes.fBool), result, falseConstant,
ethannicholasd598f792016-07-25 10:08:54 -07002735 lhsBlock, rhs, rhsBlock, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002736 return result;
2737}
2738
John Stilesbc5c2a02021-04-08 11:44:53 -04002739SpvId SPIRVCodeGenerator::writeLogicalOr(const Expression& left, const Expression& right,
2740 OutputStream& out) {
John Stiles9ce80f72021-03-11 22:35:19 -05002741 BoolLiteral trueLiteral(/*offset=*/-1, /*value=*/true, fContext.fTypes.fBool.get());
ethannicholasb3058bd2016-07-01 08:22:01 -07002742 SpvId trueConstant = this->writeBoolLiteral(trueLiteral);
John Stilesbc5c2a02021-04-08 11:44:53 -04002743 SpvId lhs = this->writeExpression(left, out);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002744 SpvId rhsLabel = this->nextId(nullptr);
2745 SpvId end = this->nextId(nullptr);
ethannicholasb3058bd2016-07-01 08:22:01 -07002746 SpvId lhsBlock = fCurrentBlock;
2747 this->writeInstruction(SpvOpSelectionMerge, end, SpvSelectionControlMaskNone, out);
2748 this->writeInstruction(SpvOpBranchConditional, lhs, end, rhsLabel, out);
2749 this->writeLabel(rhsLabel, out);
John Stilesbc5c2a02021-04-08 11:44:53 -04002750 SpvId rhs = this->writeExpression(right, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002751 SpvId rhsBlock = fCurrentBlock;
2752 this->writeInstruction(SpvOpBranch, end, out);
2753 this->writeLabel(end, out);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002754 SpvId result = this->nextId(nullptr);
John Stiles54e7c052021-01-11 14:22:36 -05002755 this->writeInstruction(SpvOpPhi, this->getType(*fContext.fTypes.fBool), result, trueConstant,
ethannicholasd598f792016-07-25 10:08:54 -07002756 lhsBlock, rhs, rhsBlock, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002757 return result;
2758}
2759
Ethan Nicholas0df1b042017-03-31 13:56:23 -04002760SpvId SPIRVCodeGenerator::writeTernaryExpression(const TernaryExpression& t, OutputStream& out) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04002761 const Type& type = t.type();
Ethan Nicholasdd218162020-10-08 05:48:01 -04002762 SpvId test = this->writeExpression(*t.test(), out);
2763 if (t.ifTrue()->type().columns() == 1 &&
2764 t.ifTrue()->isCompileTimeConstant() &&
2765 t.ifFalse()->isCompileTimeConstant()) {
ethannicholasb3058bd2016-07-01 08:22:01 -07002766 // both true and false are constants, can just use OpSelect
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002767 SpvId result = this->nextId(nullptr);
Ethan Nicholasdd218162020-10-08 05:48:01 -04002768 SpvId trueId = this->writeExpression(*t.ifTrue(), out);
2769 SpvId falseId = this->writeExpression(*t.ifFalse(), out);
Ethan Nicholas30d30222020-09-11 12:27:26 -04002770 this->writeInstruction(SpvOpSelect, this->getType(type), result, test, trueId, falseId,
ethannicholasb3058bd2016-07-01 08:22:01 -07002771 out);
2772 return result;
2773 }
Greg Daniel64773e62016-11-22 09:44:03 -05002774 // was originally using OpPhi to choose the result, but for some reason that is crashing on
ethannicholasb3058bd2016-07-01 08:22:01 -07002775 // Adreno. Switched to storing the result in a temp variable as glslang does.
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002776 SpvId var = this->nextId(nullptr);
Ethan Nicholas30d30222020-09-11 12:27:26 -04002777 this->writeInstruction(SpvOpVariable, this->getPointerType(type, SpvStorageClassFunction),
ethannicholasd598f792016-07-25 10:08:54 -07002778 var, SpvStorageClassFunction, fVariableBuffer);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002779 SpvId trueLabel = this->nextId(nullptr);
2780 SpvId falseLabel = this->nextId(nullptr);
2781 SpvId end = this->nextId(nullptr);
ethannicholasb3058bd2016-07-01 08:22:01 -07002782 this->writeInstruction(SpvOpSelectionMerge, end, SpvSelectionControlMaskNone, out);
2783 this->writeInstruction(SpvOpBranchConditional, test, trueLabel, falseLabel, out);
2784 this->writeLabel(trueLabel, out);
Ethan Nicholasdd218162020-10-08 05:48:01 -04002785 this->writeInstruction(SpvOpStore, var, this->writeExpression(*t.ifTrue(), out), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002786 this->writeInstruction(SpvOpBranch, end, out);
2787 this->writeLabel(falseLabel, out);
Ethan Nicholasdd218162020-10-08 05:48:01 -04002788 this->writeInstruction(SpvOpStore, var, this->writeExpression(*t.ifFalse(), out), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002789 this->writeInstruction(SpvOpBranch, end, out);
2790 this->writeLabel(end, out);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002791 SpvId result = this->nextId(&type);
Ethan Nicholas30d30222020-09-11 12:27:26 -04002792 this->writeInstruction(SpvOpLoad, this->getType(type), result, var, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002793 return result;
2794}
2795
Ethan Nicholas0df1b042017-03-31 13:56:23 -04002796SpvId SPIRVCodeGenerator::writePrefixExpression(const PrefixExpression& p, OutputStream& out) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04002797 const Type& type = p.type();
John Stiles45990502021-02-16 10:55:27 -05002798 if (p.getOperator().kind() == Token::Kind::TK_MINUS) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002799 SpvId result = this->nextId(&type);
Ethan Nicholas30d30222020-09-11 12:27:26 -04002800 SpvId typeId = this->getType(type);
Ethan Nicholas444ccc62020-10-09 10:16:22 -04002801 SpvId expr = this->writeExpression(*p.operand(), out);
Ethan Nicholas30d30222020-09-11 12:27:26 -04002802 if (is_float(fContext, type)) {
ethannicholasb3058bd2016-07-01 08:22:01 -07002803 this->writeInstruction(SpvOpFNegate, typeId, result, expr, out);
John Stiles43ac7e62021-08-25 12:43:22 -04002804 } else if (is_signed(fContext, type) || is_unsigned(fContext, type)) {
ethannicholasb3058bd2016-07-01 08:22:01 -07002805 this->writeInstruction(SpvOpSNegate, typeId, result, expr, out);
2806 } else {
John Stileseada7bc2021-02-02 16:29:32 -05002807 SkDEBUGFAILF("unsupported prefix expression %s", p.description().c_str());
Brian Salomon23356442018-11-30 15:33:19 -05002808 }
ethannicholasb3058bd2016-07-01 08:22:01 -07002809 return result;
2810 }
John Stiles45990502021-02-16 10:55:27 -05002811 switch (p.getOperator().kind()) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002812 case Token::Kind::TK_PLUS:
Ethan Nicholas444ccc62020-10-09 10:16:22 -04002813 return this->writeExpression(*p.operand(), out);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002814 case Token::Kind::TK_PLUSPLUS: {
Ethan Nicholas444ccc62020-10-09 10:16:22 -04002815 std::unique_ptr<LValue> lv = this->getLValue(*p.operand(), out);
Ethan Nicholas30d30222020-09-11 12:27:26 -04002816 SpvId one = this->writeExpression(*create_literal_1(fContext, type), out);
2817 SpvId result = this->writeBinaryOperation(type, type, lv->load(out), one,
Greg Daniel64773e62016-11-22 09:44:03 -05002818 SpvOpFAdd, SpvOpIAdd, SpvOpIAdd, SpvOpUndef,
ethannicholasb3058bd2016-07-01 08:22:01 -07002819 out);
2820 lv->store(result, out);
2821 return result;
2822 }
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002823 case Token::Kind::TK_MINUSMINUS: {
Ethan Nicholas444ccc62020-10-09 10:16:22 -04002824 std::unique_ptr<LValue> lv = this->getLValue(*p.operand(), out);
Ethan Nicholas30d30222020-09-11 12:27:26 -04002825 SpvId one = this->writeExpression(*create_literal_1(fContext, type), out);
2826 SpvId result = this->writeBinaryOperation(type, type, lv->load(out), one, SpvOpFSub,
2827 SpvOpISub, SpvOpISub, SpvOpUndef, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002828 lv->store(result, out);
2829 return result;
2830 }
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002831 case Token::Kind::TK_LOGICALNOT: {
John Stiles4a7dc462020-11-25 11:08:08 -05002832 SkASSERT(p.operand()->type().isBoolean());
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002833 SpvId result = this->nextId(nullptr);
Ethan Nicholas444ccc62020-10-09 10:16:22 -04002834 this->writeInstruction(SpvOpLogicalNot, this->getType(type), result,
2835 this->writeExpression(*p.operand(), out), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002836 return result;
2837 }
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002838 case Token::Kind::TK_BITWISENOT: {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002839 SpvId result = this->nextId(nullptr);
Ethan Nicholas444ccc62020-10-09 10:16:22 -04002840 this->writeInstruction(SpvOpNot, this->getType(type), result,
2841 this->writeExpression(*p.operand(), out), out);
ethannicholas5961bc92016-10-12 06:39:56 -07002842 return result;
2843 }
ethannicholasb3058bd2016-07-01 08:22:01 -07002844 default:
John Stileseada7bc2021-02-02 16:29:32 -05002845 SkDEBUGFAILF("unsupported prefix expression: %s", p.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -05002846 return -1;
ethannicholasb3058bd2016-07-01 08:22:01 -07002847 }
2848}
2849
Ethan Nicholas0df1b042017-03-31 13:56:23 -04002850SpvId SPIRVCodeGenerator::writePostfixExpression(const PostfixExpression& p, OutputStream& out) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04002851 const Type& type = p.type();
Ethan Nicholas444ccc62020-10-09 10:16:22 -04002852 std::unique_ptr<LValue> lv = this->getLValue(*p.operand(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002853 SpvId result = lv->load(out);
Ethan Nicholas30d30222020-09-11 12:27:26 -04002854 SpvId one = this->writeExpression(*create_literal_1(fContext, type), out);
John Stiles45990502021-02-16 10:55:27 -05002855 switch (p.getOperator().kind()) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002856 case Token::Kind::TK_PLUSPLUS: {
Ethan Nicholas30d30222020-09-11 12:27:26 -04002857 SpvId temp = this->writeBinaryOperation(type, type, result, one, SpvOpFAdd,
ethannicholasb3058bd2016-07-01 08:22:01 -07002858 SpvOpIAdd, SpvOpIAdd, SpvOpUndef, out);
2859 lv->store(temp, out);
2860 return result;
2861 }
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002862 case Token::Kind::TK_MINUSMINUS: {
Ethan Nicholas30d30222020-09-11 12:27:26 -04002863 SpvId temp = this->writeBinaryOperation(type, type, result, one, SpvOpFSub,
ethannicholasb3058bd2016-07-01 08:22:01 -07002864 SpvOpISub, SpvOpISub, SpvOpUndef, out);
2865 lv->store(temp, out);
2866 return result;
2867 }
2868 default:
John Stileseada7bc2021-02-02 16:29:32 -05002869 SkDEBUGFAILF("unsupported postfix expression %s", p.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -05002870 return -1;
ethannicholasb3058bd2016-07-01 08:22:01 -07002871 }
2872}
2873
ethannicholasf789b382016-08-03 12:43:36 -07002874SpvId SPIRVCodeGenerator::writeBoolLiteral(const BoolLiteral& b) {
Ethan Nicholas59d660c2020-09-28 09:18:15 -04002875 if (b.value()) {
ethannicholasb3058bd2016-07-01 08:22:01 -07002876 if (fBoolTrue == 0) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002877 fBoolTrue = this->nextId(nullptr);
Ethan Nicholas30d30222020-09-11 12:27:26 -04002878 this->writeInstruction(SpvOpConstantTrue, this->getType(b.type()), fBoolTrue,
ethannicholasb3058bd2016-07-01 08:22:01 -07002879 fConstantBuffer);
2880 }
2881 return fBoolTrue;
2882 } else {
2883 if (fBoolFalse == 0) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002884 fBoolFalse = this->nextId(nullptr);
Ethan Nicholas30d30222020-09-11 12:27:26 -04002885 this->writeInstruction(SpvOpConstantFalse, this->getType(b.type()), fBoolFalse,
ethannicholasb3058bd2016-07-01 08:22:01 -07002886 fConstantBuffer);
2887 }
2888 return fBoolFalse;
2889 }
2890}
2891
ethannicholasf789b382016-08-03 12:43:36 -07002892SpvId SPIRVCodeGenerator::writeIntLiteral(const IntLiteral& i) {
John Stilesbdc3d3c2021-01-06 18:41:40 -05002893 SPIRVNumberConstant key{i.value(), i.type().numberKind()};
John Stilesacb091f2021-01-06 11:57:58 -05002894 auto [iter, newlyCreated] = fNumberConstants.insert({key, (SpvId)-1});
2895 if (newlyCreated) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002896 SpvId result = this->nextId(nullptr);
John Stilesacb091f2021-01-06 11:57:58 -05002897 this->writeInstruction(SpvOpConstant, this->getType(i.type()), result, (SpvId) i.value(),
Ethan Nicholascc5d3e02019-04-19 09:50:56 -04002898 fConstantBuffer);
John Stilesacb091f2021-01-06 11:57:58 -05002899 iter->second = result;
Ethan Nicholascc5d3e02019-04-19 09:50:56 -04002900 }
John Stilesacb091f2021-01-06 11:57:58 -05002901 return iter->second;
ethannicholasb3058bd2016-07-01 08:22:01 -07002902}
2903
ethannicholasf789b382016-08-03 12:43:36 -07002904SpvId SPIRVCodeGenerator::writeFloatLiteral(const FloatLiteral& f) {
John Stilesbdc3d3c2021-01-06 18:41:40 -05002905 // Convert the float literal into its bit-representation.
2906 float value = f.value();
2907 uint32_t valueBits;
2908 static_assert(sizeof(valueBits) == sizeof(value));
2909 memcpy(&valueBits, &value, sizeof(value));
2910
2911 SPIRVNumberConstant key{valueBits, f.type().numberKind()};
John Stilesacb091f2021-01-06 11:57:58 -05002912 auto [iter, newlyCreated] = fNumberConstants.insert({key, (SpvId)-1});
2913 if (newlyCreated) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002914 SpvId result = this->nextId(nullptr);
John Stilesbdc3d3c2021-01-06 18:41:40 -05002915 this->writeInstruction(SpvOpConstant, this->getType(f.type()), result, (SpvId) valueBits,
John Stiles8c578662020-06-01 15:32:47 +00002916 fConstantBuffer);
John Stilesacb091f2021-01-06 11:57:58 -05002917 iter->second = result;
John Stiles8c578662020-06-01 15:32:47 +00002918 }
John Stilesacb091f2021-01-06 11:57:58 -05002919 return iter->second;
ethannicholasb3058bd2016-07-01 08:22:01 -07002920}
2921
Ethan Nicholas0df1b042017-03-31 13:56:23 -04002922SpvId SPIRVCodeGenerator::writeFunctionStart(const FunctionDeclaration& f, OutputStream& out) {
ethannicholasd598f792016-07-25 10:08:54 -07002923 SpvId result = fFunctionMap[&f];
John Stilesb5db4822021-01-21 13:04:40 -05002924 SpvId returnTypeId = this->getType(f.returnType());
2925 SpvId functionTypeId = this->getFunctionType(f);
2926 this->writeInstruction(SpvOpFunction, returnTypeId, result,
2927 SpvFunctionControlMaskNone, functionTypeId, out);
John Stilesf9e85512021-03-22 12:05:31 -04002928 String mangledName = f.mangledName();
2929 this->writeInstruction(SpvOpName,
2930 result,
Ethan Nicholas962dec42021-06-10 13:06:39 -04002931 skstd::string_view(mangledName.c_str(), mangledName.size()),
John Stilesf9e85512021-03-22 12:05:31 -04002932 fNameBuffer);
2933 for (const Variable* parameter : f.parameters()) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002934 SpvId id = this->nextId(nullptr);
John Stilesf9e85512021-03-22 12:05:31 -04002935 fVariableMap[parameter] = id;
2936 SpvId type = this->getPointerType(parameter->type(), SpvStorageClassFunction);
ethannicholasb3058bd2016-07-01 08:22:01 -07002937 this->writeInstruction(SpvOpFunctionParameter, type, id, out);
2938 }
2939 return result;
2940}
2941
Ethan Nicholas0df1b042017-03-31 13:56:23 -04002942SpvId SPIRVCodeGenerator::writeFunction(const FunctionDefinition& f, OutputStream& out) {
2943 fVariableBuffer.reset();
Ethan Nicholas0a5d0962020-10-14 13:33:18 -04002944 SpvId result = this->writeFunctionStart(f.declaration(), out);
Ethan Nicholas7fb39362020-12-16 15:25:19 -05002945 fCurrentBlock = 0;
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002946 this->writeLabel(this->nextId(nullptr), out);
Ethan Nicholas0df1b042017-03-31 13:56:23 -04002947 StringStream bodyBuffer;
John Stiles0693fb82021-01-22 18:27:52 -05002948 this->writeBlock(f.body()->as<Block>(), bodyBuffer);
Ethan Nicholas0df1b042017-03-31 13:56:23 -04002949 write_stringstream(fVariableBuffer, out);
John Stilese8da4d22021-03-24 09:19:45 -04002950 if (f.declaration().isMain()) {
Ethan Nicholas8eb64d32018-12-21 14:50:42 -05002951 write_stringstream(fGlobalInitializersBuffer, out);
2952 }
Ethan Nicholas0df1b042017-03-31 13:56:23 -04002953 write_stringstream(bodyBuffer, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002954 if (fCurrentBlock) {
John Stiles2558c462021-03-16 17:49:20 -04002955 if (f.declaration().returnType().isVoid()) {
Ethan Nicholas70a44b22017-11-30 09:09:16 -05002956 this->writeInstruction(SpvOpReturn, out);
2957 } else {
2958 this->writeInstruction(SpvOpUnreachable, out);
2959 }
ethannicholasb3058bd2016-07-01 08:22:01 -07002960 }
2961 this->writeInstruction(SpvOpFunctionEnd, out);
2962 return result;
2963}
2964
2965void SPIRVCodeGenerator::writeLayout(const Layout& layout, SpvId target) {
2966 if (layout.fLocation >= 0) {
Greg Daniel64773e62016-11-22 09:44:03 -05002967 this->writeInstruction(SpvOpDecorate, target, SpvDecorationLocation, layout.fLocation,
ethannicholasb3058bd2016-07-01 08:22:01 -07002968 fDecorationBuffer);
2969 }
2970 if (layout.fBinding >= 0) {
Greg Daniel64773e62016-11-22 09:44:03 -05002971 this->writeInstruction(SpvOpDecorate, target, SpvDecorationBinding, layout.fBinding,
ethannicholasb3058bd2016-07-01 08:22:01 -07002972 fDecorationBuffer);
2973 }
2974 if (layout.fIndex >= 0) {
Greg Daniel64773e62016-11-22 09:44:03 -05002975 this->writeInstruction(SpvOpDecorate, target, SpvDecorationIndex, layout.fIndex,
ethannicholasb3058bd2016-07-01 08:22:01 -07002976 fDecorationBuffer);
2977 }
2978 if (layout.fSet >= 0) {
Greg Daniel64773e62016-11-22 09:44:03 -05002979 this->writeInstruction(SpvOpDecorate, target, SpvDecorationDescriptorSet, layout.fSet,
ethannicholasb3058bd2016-07-01 08:22:01 -07002980 fDecorationBuffer);
2981 }
Greg Daniel64773e62016-11-22 09:44:03 -05002982 if (layout.fInputAttachmentIndex >= 0) {
2983 this->writeInstruction(SpvOpDecorate, target, SpvDecorationInputAttachmentIndex,
2984 layout.fInputAttachmentIndex, fDecorationBuffer);
Ethan Nicholasbe1099f2018-01-11 16:09:05 -05002985 fCapabilities |= (((uint64_t) 1) << SpvCapabilityInputAttachment);
Greg Daniel64773e62016-11-22 09:44:03 -05002986 }
Brian Osman99ddd2a2021-08-27 11:21:12 -04002987 if (layout.fBuiltin >= 0 && layout.fBuiltin != SK_FRAGCOLOR_BUILTIN) {
Greg Daniel64773e62016-11-22 09:44:03 -05002988 this->writeInstruction(SpvOpDecorate, target, SpvDecorationBuiltIn, layout.fBuiltin,
ethannicholasb3058bd2016-07-01 08:22:01 -07002989 fDecorationBuffer);
2990 }
2991}
2992
2993void SPIRVCodeGenerator::writeLayout(const Layout& layout, SpvId target, int member) {
2994 if (layout.fLocation >= 0) {
Greg Daniel64773e62016-11-22 09:44:03 -05002995 this->writeInstruction(SpvOpMemberDecorate, target, member, SpvDecorationLocation,
ethannicholasb3058bd2016-07-01 08:22:01 -07002996 layout.fLocation, fDecorationBuffer);
2997 }
2998 if (layout.fBinding >= 0) {
Greg Daniel64773e62016-11-22 09:44:03 -05002999 this->writeInstruction(SpvOpMemberDecorate, target, member, SpvDecorationBinding,
ethannicholasb3058bd2016-07-01 08:22:01 -07003000 layout.fBinding, fDecorationBuffer);
3001 }
3002 if (layout.fIndex >= 0) {
Greg Daniel64773e62016-11-22 09:44:03 -05003003 this->writeInstruction(SpvOpMemberDecorate, target, member, SpvDecorationIndex,
ethannicholasb3058bd2016-07-01 08:22:01 -07003004 layout.fIndex, fDecorationBuffer);
3005 }
3006 if (layout.fSet >= 0) {
Greg Daniel64773e62016-11-22 09:44:03 -05003007 this->writeInstruction(SpvOpMemberDecorate, target, member, SpvDecorationDescriptorSet,
ethannicholasb3058bd2016-07-01 08:22:01 -07003008 layout.fSet, fDecorationBuffer);
3009 }
Greg Daniel64773e62016-11-22 09:44:03 -05003010 if (layout.fInputAttachmentIndex >= 0) {
3011 this->writeInstruction(SpvOpDecorate, target, member, SpvDecorationInputAttachmentIndex,
3012 layout.fInputAttachmentIndex, fDecorationBuffer);
3013 }
ethannicholasb3058bd2016-07-01 08:22:01 -07003014 if (layout.fBuiltin >= 0) {
Greg Daniel64773e62016-11-22 09:44:03 -05003015 this->writeInstruction(SpvOpMemberDecorate, target, member, SpvDecorationBuiltIn,
ethannicholasb3058bd2016-07-01 08:22:01 -07003016 layout.fBuiltin, fDecorationBuffer);
3017 }
3018}
3019
Brian Osman2a4c0fb2021-01-22 13:41:40 -05003020MemoryLayout SPIRVCodeGenerator::memoryLayoutForVariable(const Variable& v) const {
Brian Osman2a4c0fb2021-01-22 13:41:40 -05003021 bool pushConstant = ((v.modifiers().fLayout.fFlags & Layout::kPushConstant_Flag) != 0);
Brian Osman58ee8982021-02-18 15:39:38 -05003022 return pushConstant ? MemoryLayout(MemoryLayout::k430_Standard) : fDefaultLayout;
Brian Osman2a4c0fb2021-01-22 13:41:40 -05003023}
3024
Brian Salomond8d85b92021-07-07 09:41:17 -04003025SpvId SPIRVCodeGenerator::writeInterfaceBlock(const InterfaceBlock& intf, bool appendRTFlip) {
Brian Osman2a4c0fb2021-01-22 13:41:40 -05003026 MemoryLayout memoryLayout = this->memoryLayoutForVariable(intf.variable());
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04003027 SpvId result = this->nextId(nullptr);
Brian Salomond8d85b92021-07-07 09:41:17 -04003028 const Variable& intfVar = intf.variable();
3029 const Type& type = intfVar.type();
3030 if (!MemoryLayout::LayoutIsSupported(type)) {
Ethan Nicholas39f6da42021-08-23 13:10:07 -04003031 fContext.fErrors->error(type.fOffset, "type '" + type.name() + "' is not permitted here");
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04003032 return this->nextId(nullptr);
John Stiles0023c0c2020-11-16 13:32:18 -05003033 }
John Stiles9485b552021-01-27 11:47:00 -05003034 SpvStorageClass_ storageClass = get_storage_class(intf.variable(), SpvStorageClassFunction);
John Stilesded41aa2021-08-05 12:19:35 -04003035 if (fProgram.fInputs.fUseFlipRTUniform && appendRTFlip && type.isStruct()) {
Brian Salomond8d85b92021-07-07 09:41:17 -04003036 // We can only have one interface block (because we use push_constant and that is limited
3037 // to one per program), so we need to append rtflip to this one rather than synthesize an
3038 // entirely new block when the variable is referenced. And we can't modify the existing
3039 // block, so we instead create a modified copy of it and write that.
3040 std::vector<Type::Field> fields = type.fields();
3041 fields.emplace_back(Modifiers(Layout(/*flags=*/0,
3042 /*location=*/-1,
3043 fProgram.fConfig->fSettings.fRTFlipOffset,
3044 /*binding=*/-1,
3045 /*index=*/-1,
3046 /*set=*/-1,
3047 /*builtin=*/-1,
Brian Osman99ddd2a2021-08-27 11:21:12 -04003048 /*inputAttachmentIndex=*/-1),
Brian Salomond8d85b92021-07-07 09:41:17 -04003049 /*flags=*/0),
3050 SKSL_RTFLIP_NAME,
3051 fContext.fTypes.fFloat2.get());
John Stiles0cac5ed2021-08-06 11:40:39 -04003052 {
3053 AutoAttachPoolToThread attach(fProgram.fPool.get());
3054 const Type* rtFlipStructType = fProgram.fSymbols->takeOwnershipOfSymbol(
3055 Type::MakeStructType(type.fOffset, type.name(), std::move(fields)));
3056 const Variable* modifiedVar = fProgram.fSymbols->takeOwnershipOfSymbol(
3057 std::make_unique<Variable>(intfVar.fOffset,
3058 &intfVar.modifiers(),
3059 intfVar.name(),
3060 rtFlipStructType,
3061 intfVar.isBuiltin(),
3062 intfVar.storage()));
3063 fSPIRVBonusVariables.insert(modifiedVar);
3064 InterfaceBlock modifiedCopy(intf.fOffset,
3065 modifiedVar,
3066 intf.typeName(),
3067 intf.instanceName(),
3068 intf.arraySize(),
3069 intf.typeOwner());
3070 result = this->writeInterfaceBlock(modifiedCopy, false);
3071 fProgram.fSymbols->add(std::make_unique<Field>(
3072 /*offset=*/-1, modifiedVar, rtFlipStructType->fields().size() - 1));
Brian Salomond8d85b92021-07-07 09:41:17 -04003073 }
3074 fVariableMap[&intfVar] = result;
3075 fWroteRTFlip = true;
3076 return result;
Ethan Nicholas941e7e22016-12-12 15:33:30 -05003077 }
Brian Salomond8d85b92021-07-07 09:41:17 -04003078 const Modifiers& intfModifiers = intfVar.modifiers();
Brian Osman99ddd2a2021-08-27 11:21:12 -04003079 SpvId typeId = this->getType(type, memoryLayout);
Brian Osman58ee8982021-02-18 15:39:38 -05003080 if (intfModifiers.fLayout.fBuiltin == -1) {
Ethan Nicholas6ac8d362019-01-22 21:43:55 +00003081 this->writeInstruction(SpvOpDecorate, typeId, SpvDecorationBlock, fDecorationBuffer);
Ethan Nicholas0dd30d92017-05-01 16:57:07 -04003082 }
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04003083 SpvId ptrType = this->nextId(nullptr);
Ethan Nicholas941e7e22016-12-12 15:33:30 -05003084 this->writeInstruction(SpvOpTypePointer, ptrType, storageClass, typeId, fConstantBuffer);
ethannicholasb3058bd2016-07-01 08:22:01 -07003085 this->writeInstruction(SpvOpVariable, ptrType, result, storageClass, fConstantBuffer);
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04003086 Layout layout = intfModifiers.fLayout;
3087 if (intfModifiers.fFlags & Modifiers::kUniform_Flag && layout.fSet == -1) {
Ethan Nicholas8d2ba442018-03-16 16:40:36 -04003088 layout.fSet = 0;
3089 }
3090 this->writeLayout(layout, result);
Brian Salomond8d85b92021-07-07 09:41:17 -04003091 fVariableMap[&intfVar] = result;
ethannicholasb3058bd2016-07-01 08:22:01 -07003092 return result;
3093}
3094
John Stilesd7437ee2021-08-02 11:56:16 -04003095bool SPIRVCodeGenerator::isDead(const Variable& var) const {
3096 // During SPIR-V code generation, we synthesize some extra bonus variables that don't actually
3097 // exist in the Program at all and aren't tracked by the ProgramUsage. They aren't dead, though.
3098 if (fSPIRVBonusVariables.count(&var)) {
3099 return false;
3100 }
3101 ProgramUsage::VariableCounts counts = fProgram.usage()->get(var);
Brian Osman010ce6a2020-10-19 16:34:10 -04003102 if (counts.fRead || counts.fWrite) {
Chris Dalton2284aab2019-11-15 11:02:24 -07003103 return false;
3104 }
Brian Osmand1f3b972021-03-22 17:03:42 -04003105 // It's not entirely clear what the rules are for eliding interface variables. Generally, it
3106 // causes problems to elide them, even when they're dead.
3107 return !(var.modifiers().fFlags &
3108 (Modifiers::kIn_Flag | Modifiers::kOut_Flag | Modifiers::kUniform_Flag));
Chris Dalton2284aab2019-11-15 11:02:24 -07003109}
3110
John Stilesdbd4e6f2021-02-16 13:29:15 -05003111void SPIRVCodeGenerator::writeGlobalVar(ProgramKind kind, const VarDeclaration& varDecl) {
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04003112 const Variable& var = varDecl.var();
John Stiles0ca2f592021-01-27 10:58:10 -05003113 // 9999 is a sentinel value used in our built-in modules that causes us to ignore these
3114 // declarations, beyond adding them to the symbol table.
3115 constexpr int kBuiltinIgnore = 9999;
3116 if (var.modifiers().fLayout.fBuiltin == kBuiltinIgnore) {
Brian Osmanc0213602020-10-06 14:43:32 -04003117 return;
3118 }
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04003119 if (var.modifiers().fLayout.fBuiltin == SK_FRAGCOLOR_BUILTIN &&
John Stilesdbd4e6f2021-02-16 13:29:15 -05003120 kind != ProgramKind::kFragment) {
John Stiles270cec22021-02-17 12:59:36 -05003121 SkASSERT(!fProgram.fConfig->fSettings.fFragColorIsInOut);
Brian Osmanc0213602020-10-06 14:43:32 -04003122 return;
3123 }
John Stilesd7437ee2021-08-02 11:56:16 -04003124 if (this->isDead(var)) {
Brian Osmanc0213602020-10-06 14:43:32 -04003125 return;
3126 }
John Stiles0de76f72021-01-29 09:19:39 -05003127 SpvStorageClass_ storageClass = get_storage_class(var, SpvStorageClassPrivate);
John Stilese40d1662021-01-29 10:08:50 -05003128 if (storageClass == SpvStorageClassUniform) {
3129 // Top-level uniforms are emitted in writeUniformBuffer.
3130 fTopLevelUniforms.push_back(&varDecl);
3131 return;
3132 }
3133 const Type& type = var.type();
John Stilesd8fc95d2021-01-26 16:22:53 -05003134 Layout layout = var.modifiers().fLayout;
John Stilese40d1662021-01-29 10:08:50 -05003135 if (layout.fSet < 0 && storageClass == SpvStorageClassUniformConstant) {
John Stiles270cec22021-02-17 12:59:36 -05003136 layout.fSet = fProgram.fConfig->fSettings.fDefaultUniformSet;
Brian Osmanc0213602020-10-06 14:43:32 -04003137 }
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04003138 SpvId id = this->nextId(&type);
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04003139 fVariableMap[&var] = id;
Brian Osman99ddd2a2021-08-27 11:21:12 -04003140 SpvId typeId = this->getPointerType(type, storageClass);
Brian Osmanc0213602020-10-06 14:43:32 -04003141 this->writeInstruction(SpvOpVariable, typeId, id, storageClass, fConstantBuffer);
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04003142 this->writeInstruction(SpvOpName, id, var.name(), fNameBuffer);
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04003143 if (varDecl.value()) {
Brian Osmanc0213602020-10-06 14:43:32 -04003144 SkASSERT(!fCurrentBlock);
3145 fCurrentBlock = -1;
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04003146 SpvId value = this->writeExpression(*varDecl.value(), fGlobalInitializersBuffer);
Brian Osmanc0213602020-10-06 14:43:32 -04003147 this->writeInstruction(SpvOpStore, id, value, fGlobalInitializersBuffer);
3148 fCurrentBlock = 0;
3149 }
John Stilesd8fc95d2021-01-26 16:22:53 -05003150 this->writeLayout(layout, id);
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04003151 if (var.modifiers().fFlags & Modifiers::kFlat_Flag) {
Brian Osmanc0213602020-10-06 14:43:32 -04003152 this->writeInstruction(SpvOpDecorate, id, SpvDecorationFlat, fDecorationBuffer);
3153 }
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04003154 if (var.modifiers().fFlags & Modifiers::kNoPerspective_Flag) {
Brian Osmanc0213602020-10-06 14:43:32 -04003155 this->writeInstruction(SpvOpDecorate, id, SpvDecorationNoPerspective,
3156 fDecorationBuffer);
ethannicholasb3058bd2016-07-01 08:22:01 -07003157 }
3158}
3159
Brian Osmanc0213602020-10-06 14:43:32 -04003160void SPIRVCodeGenerator::writeVarDeclaration(const VarDeclaration& varDecl, OutputStream& out) {
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04003161 const Variable& var = varDecl.var();
Ethan Nicholas7f015882021-03-23 14:16:52 -04003162 SpvId id = this->nextId(&var.type());
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04003163 fVariableMap[&var] = id;
3164 SpvId type = this->getPointerType(var.type(), SpvStorageClassFunction);
Brian Osmanc0213602020-10-06 14:43:32 -04003165 this->writeInstruction(SpvOpVariable, type, id, SpvStorageClassFunction, fVariableBuffer);
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04003166 this->writeInstruction(SpvOpName, id, var.name(), fNameBuffer);
3167 if (varDecl.value()) {
3168 SpvId value = this->writeExpression(*varDecl.value(), out);
Brian Osmanc0213602020-10-06 14:43:32 -04003169 this->writeInstruction(SpvOpStore, id, value, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003170 }
3171}
3172
Ethan Nicholas0df1b042017-03-31 13:56:23 -04003173void SPIRVCodeGenerator::writeStatement(const Statement& s, OutputStream& out) {
Ethan Nicholase6592142020-09-08 10:22:09 -04003174 switch (s.kind()) {
John Stiles98c1f822020-09-09 14:18:53 -04003175 case Statement::Kind::kInlineMarker:
Ethan Nicholase6592142020-09-08 10:22:09 -04003176 case Statement::Kind::kNop:
Ethan Nicholascb670962017-04-20 19:31:52 -04003177 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04003178 case Statement::Kind::kBlock:
John Stiles0693fb82021-01-22 18:27:52 -05003179 this->writeBlock(s.as<Block>(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003180 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04003181 case Statement::Kind::kExpression:
Ethan Nicholasd503a5a2020-09-30 09:29:55 -04003182 this->writeExpression(*s.as<ExpressionStatement>().expression(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003183 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04003184 case Statement::Kind::kReturn:
John Stiles26f98502020-08-18 09:30:51 -04003185 this->writeReturnStatement(s.as<ReturnStatement>(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003186 break;
Brian Osmanc0213602020-10-06 14:43:32 -04003187 case Statement::Kind::kVarDeclaration:
3188 this->writeVarDeclaration(s.as<VarDeclaration>(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003189 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04003190 case Statement::Kind::kIf:
John Stiles26f98502020-08-18 09:30:51 -04003191 this->writeIfStatement(s.as<IfStatement>(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003192 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04003193 case Statement::Kind::kFor:
John Stiles26f98502020-08-18 09:30:51 -04003194 this->writeForStatement(s.as<ForStatement>(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003195 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04003196 case Statement::Kind::kDo:
John Stiles26f98502020-08-18 09:30:51 -04003197 this->writeDoStatement(s.as<DoStatement>(), out);
Ethan Nicholasfd146aa2017-01-13 16:40:35 -05003198 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04003199 case Statement::Kind::kSwitch:
John Stiles26f98502020-08-18 09:30:51 -04003200 this->writeSwitchStatement(s.as<SwitchStatement>(), out);
Ethan Nicholase92b1b12017-11-13 16:13:21 -05003201 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04003202 case Statement::Kind::kBreak:
ethannicholasb3058bd2016-07-01 08:22:01 -07003203 this->writeInstruction(SpvOpBranch, fBreakTarget.top(), out);
3204 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04003205 case Statement::Kind::kContinue:
ethannicholasb3058bd2016-07-01 08:22:01 -07003206 this->writeInstruction(SpvOpBranch, fContinueTarget.top(), out);
3207 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04003208 case Statement::Kind::kDiscard:
ethannicholasb3058bd2016-07-01 08:22:01 -07003209 this->writeInstruction(SpvOpKill, out);
3210 break;
3211 default:
John Stileseada7bc2021-02-02 16:29:32 -05003212 SkDEBUGFAILF("unsupported statement: %s", s.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -05003213 break;
ethannicholasb3058bd2016-07-01 08:22:01 -07003214 }
3215}
3216
Ethan Nicholas0df1b042017-03-31 13:56:23 -04003217void SPIRVCodeGenerator::writeBlock(const Block& b, OutputStream& out) {
Ethan Nicholas7bd60432020-09-25 14:31:59 -04003218 for (const std::unique_ptr<Statement>& stmt : b.children()) {
3219 this->writeStatement(*stmt, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003220 }
3221}
3222
Ethan Nicholas0df1b042017-03-31 13:56:23 -04003223void SPIRVCodeGenerator::writeIfStatement(const IfStatement& stmt, OutputStream& out) {
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04003224 SpvId test = this->writeExpression(*stmt.test(), out);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04003225 SpvId ifTrue = this->nextId(nullptr);
3226 SpvId ifFalse = this->nextId(nullptr);
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04003227 if (stmt.ifFalse()) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04003228 SpvId end = this->nextId(nullptr);
ethannicholasb3058bd2016-07-01 08:22:01 -07003229 this->writeInstruction(SpvOpSelectionMerge, end, SpvSelectionControlMaskNone, out);
3230 this->writeInstruction(SpvOpBranchConditional, test, ifTrue, ifFalse, out);
3231 this->writeLabel(ifTrue, out);
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04003232 this->writeStatement(*stmt.ifTrue(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003233 if (fCurrentBlock) {
3234 this->writeInstruction(SpvOpBranch, end, out);
3235 }
3236 this->writeLabel(ifFalse, out);
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04003237 this->writeStatement(*stmt.ifFalse(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003238 if (fCurrentBlock) {
3239 this->writeInstruction(SpvOpBranch, end, out);
3240 }
3241 this->writeLabel(end, out);
3242 } else {
3243 this->writeInstruction(SpvOpSelectionMerge, ifFalse, SpvSelectionControlMaskNone, out);
3244 this->writeInstruction(SpvOpBranchConditional, test, ifTrue, ifFalse, out);
3245 this->writeLabel(ifTrue, out);
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04003246 this->writeStatement(*stmt.ifTrue(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003247 if (fCurrentBlock) {
3248 this->writeInstruction(SpvOpBranch, ifFalse, out);
3249 }
3250 this->writeLabel(ifFalse, out);
3251 }
3252}
3253
Ethan Nicholas0df1b042017-03-31 13:56:23 -04003254void SPIRVCodeGenerator::writeForStatement(const ForStatement& f, OutputStream& out) {
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04003255 if (f.initializer()) {
3256 this->writeStatement(*f.initializer(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003257 }
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04003258 SpvId header = this->nextId(nullptr);
3259 SpvId start = this->nextId(nullptr);
3260 SpvId body = this->nextId(nullptr);
3261 SpvId next = this->nextId(nullptr);
ethannicholasb3058bd2016-07-01 08:22:01 -07003262 fContinueTarget.push(next);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04003263 SpvId end = this->nextId(nullptr);
ethannicholasb3058bd2016-07-01 08:22:01 -07003264 fBreakTarget.push(end);
3265 this->writeInstruction(SpvOpBranch, header, out);
3266 this->writeLabel(header, out);
3267 this->writeInstruction(SpvOpLoopMerge, end, next, SpvLoopControlMaskNone, out);
ethannicholasf789b382016-08-03 12:43:36 -07003268 this->writeInstruction(SpvOpBranch, start, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003269 this->writeLabel(start, out);
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04003270 if (f.test()) {
3271 SpvId test = this->writeExpression(*f.test(), out);
ethannicholas22f939e2016-10-13 13:25:34 -07003272 this->writeInstruction(SpvOpBranchConditional, test, body, end, out);
Ethan Nicholas7fb39362020-12-16 15:25:19 -05003273 } else {
3274 this->writeInstruction(SpvOpBranch, body, out);
ethannicholas22f939e2016-10-13 13:25:34 -07003275 }
ethannicholasb3058bd2016-07-01 08:22:01 -07003276 this->writeLabel(body, out);
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04003277 this->writeStatement(*f.statement(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003278 if (fCurrentBlock) {
3279 this->writeInstruction(SpvOpBranch, next, out);
3280 }
3281 this->writeLabel(next, out);
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04003282 if (f.next()) {
3283 this->writeExpression(*f.next(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003284 }
3285 this->writeInstruction(SpvOpBranch, header, out);
3286 this->writeLabel(end, out);
3287 fBreakTarget.pop();
3288 fContinueTarget.pop();
3289}
3290
Ethan Nicholas0df1b042017-03-31 13:56:23 -04003291void SPIRVCodeGenerator::writeDoStatement(const DoStatement& d, OutputStream& out) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04003292 SpvId header = this->nextId(nullptr);
3293 SpvId start = this->nextId(nullptr);
3294 SpvId next = this->nextId(nullptr);
3295 SpvId continueTarget = this->nextId(nullptr);
Ethan Nicholas0d997662019-04-08 09:46:01 -04003296 fContinueTarget.push(continueTarget);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04003297 SpvId end = this->nextId(nullptr);
Ethan Nicholasfd146aa2017-01-13 16:40:35 -05003298 fBreakTarget.push(end);
3299 this->writeInstruction(SpvOpBranch, header, out);
3300 this->writeLabel(header, out);
Ethan Nicholas0d997662019-04-08 09:46:01 -04003301 this->writeInstruction(SpvOpLoopMerge, end, continueTarget, SpvLoopControlMaskNone, out);
Ethan Nicholasfd146aa2017-01-13 16:40:35 -05003302 this->writeInstruction(SpvOpBranch, start, out);
3303 this->writeLabel(start, out);
Ethan Nicholas1fd61162020-09-28 13:14:19 -04003304 this->writeStatement(*d.statement(), out);
Ethan Nicholasfd146aa2017-01-13 16:40:35 -05003305 if (fCurrentBlock) {
3306 this->writeInstruction(SpvOpBranch, next, out);
3307 }
3308 this->writeLabel(next, out);
John Stiles68072a42021-04-16 17:25:55 -04003309 this->writeInstruction(SpvOpBranch, continueTarget, out);
Ethan Nicholas0d997662019-04-08 09:46:01 -04003310 this->writeLabel(continueTarget, out);
John Stiles68072a42021-04-16 17:25:55 -04003311 SpvId test = this->writeExpression(*d.test(), out);
3312 this->writeInstruction(SpvOpBranchConditional, test, header, end, out);
Ethan Nicholasfd146aa2017-01-13 16:40:35 -05003313 this->writeLabel(end, out);
3314 fBreakTarget.pop();
3315 fContinueTarget.pop();
3316}
3317
Ethan Nicholase92b1b12017-11-13 16:13:21 -05003318void SPIRVCodeGenerator::writeSwitchStatement(const SwitchStatement& s, OutputStream& out) {
Ethan Nicholas01b05e52020-10-22 15:53:41 -04003319 SpvId value = this->writeExpression(*s.value(), out);
Ethan Nicholase92b1b12017-11-13 16:13:21 -05003320 std::vector<SpvId> labels;
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04003321 SpvId end = this->nextId(nullptr);
Ethan Nicholase92b1b12017-11-13 16:13:21 -05003322 SpvId defaultLabel = end;
3323 fBreakTarget.push(end);
3324 int size = 3;
John Stiles2d4f9592020-10-30 10:29:12 -04003325 auto& cases = s.cases();
John Stilesb23a64b2021-03-11 08:27:59 -05003326 for (const std::unique_ptr<Statement>& stmt : cases) {
3327 const SwitchCase& c = stmt->as<SwitchCase>();
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04003328 SpvId label = this->nextId(nullptr);
Ethan Nicholase92b1b12017-11-13 16:13:21 -05003329 labels.push_back(label);
John Stilesb23a64b2021-03-11 08:27:59 -05003330 if (c.value()) {
Ethan Nicholase92b1b12017-11-13 16:13:21 -05003331 size += 2;
3332 } else {
3333 defaultLabel = label;
3334 }
3335 }
3336 labels.push_back(end);
3337 this->writeInstruction(SpvOpSelectionMerge, end, SpvSelectionControlMaskNone, out);
3338 this->writeOpCode(SpvOpSwitch, size, out);
3339 this->writeWord(value, out);
3340 this->writeWord(defaultLabel, out);
John Stiles2d4f9592020-10-30 10:29:12 -04003341 for (size_t i = 0; i < cases.size(); ++i) {
John Stilesb23a64b2021-03-11 08:27:59 -05003342 const SwitchCase& c = cases[i]->as<SwitchCase>();
3343 if (!c.value()) {
Ethan Nicholase92b1b12017-11-13 16:13:21 -05003344 continue;
3345 }
John Stilesb23a64b2021-03-11 08:27:59 -05003346 this->writeWord(c.value()->as<IntLiteral>().value(), out);
Ethan Nicholase92b1b12017-11-13 16:13:21 -05003347 this->writeWord(labels[i], out);
3348 }
John Stiles2d4f9592020-10-30 10:29:12 -04003349 for (size_t i = 0; i < cases.size(); ++i) {
John Stilesb23a64b2021-03-11 08:27:59 -05003350 const SwitchCase& c = cases[i]->as<SwitchCase>();
Ethan Nicholase92b1b12017-11-13 16:13:21 -05003351 this->writeLabel(labels[i], out);
John Stilesb23a64b2021-03-11 08:27:59 -05003352 this->writeStatement(*c.statement(), out);
Ethan Nicholase92b1b12017-11-13 16:13:21 -05003353 if (fCurrentBlock) {
3354 this->writeInstruction(SpvOpBranch, labels[i + 1], out);
3355 }
3356 }
3357 this->writeLabel(end, out);
3358 fBreakTarget.pop();
3359}
3360
Ethan Nicholas0df1b042017-03-31 13:56:23 -04003361void SPIRVCodeGenerator::writeReturnStatement(const ReturnStatement& r, OutputStream& out) {
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04003362 if (r.expression()) {
3363 this->writeInstruction(SpvOpReturnValue, this->writeExpression(*r.expression(), out),
ethannicholasb3058bd2016-07-01 08:22:01 -07003364 out);
3365 } else {
3366 this->writeInstruction(SpvOpReturn, out);
3367 }
3368}
3369
John Stilese40d1662021-01-29 10:08:50 -05003370// Given any function, returns the top-level symbol table (OUTSIDE of the function's scope).
3371static std::shared_ptr<SymbolTable> get_top_level_symbol_table(const FunctionDeclaration& anyFunc) {
3372 return anyFunc.definition()->body()->as<Block>().symbolTable()->fParent;
3373}
3374
John Stiles4d6310a2021-01-26 19:58:22 -05003375SPIRVCodeGenerator::EntrypointAdapter SPIRVCodeGenerator::writeEntrypointAdapter(
3376 const FunctionDeclaration& main) {
3377 // Our goal is to synthesize a tiny helper function which looks like this:
3378 // void _entrypoint() { sk_FragColor = main(); }
3379
3380 // Fish a symbol table out of main().
John Stilese40d1662021-01-29 10:08:50 -05003381 std::shared_ptr<SymbolTable> symbolTable = get_top_level_symbol_table(main);
John Stiles4d6310a2021-01-26 19:58:22 -05003382
3383 // Get `sk_FragColor` as a writable reference.
3384 const Symbol* skFragColorSymbol = (*symbolTable)["sk_FragColor"];
3385 SkASSERT(skFragColorSymbol);
3386 const Variable& skFragColorVar = skFragColorSymbol->as<Variable>();
3387 auto skFragColorRef = std::make_unique<VariableReference>(/*offset=*/-1, &skFragColorVar,
3388 VariableReference::RefKind::kWrite);
3389 // Synthesize a call to the `main()` function.
3390 if (main.returnType() != skFragColorRef->type()) {
Ethan Nicholas39f6da42021-08-23 13:10:07 -04003391 fContext.fErrors->error(main.fOffset, "SPIR-V does not support returning '" +
Ethan Nicholas3abc6c62021-08-13 11:20:09 -04003392 main.returnType().description() + "' from main()");
John Stiles4d6310a2021-01-26 19:58:22 -05003393 return {};
3394 }
Brian Osman716aeb92021-04-21 13:20:00 -04003395 ExpressionArray args;
3396 if (main.parameters().size() == 1) {
3397 if (main.parameters()[0]->type() != *fContext.fTypes.fFloat2) {
Ethan Nicholas39f6da42021-08-23 13:10:07 -04003398 fContext.fErrors->error(main.fOffset,
Ethan Nicholas3abc6c62021-08-13 11:20:09 -04003399 "SPIR-V does not support parameter of type '" +
3400 main.parameters()[0]->type().description() + "' to main()");
Brian Osman716aeb92021-04-21 13:20:00 -04003401 return {};
3402 }
3403 auto zero = std::make_unique<FloatLiteral>(
3404 /*offset=*/-1, 0.0f, fContext.fTypes.fFloatLiteral.get());
3405 auto zeros = std::make_unique<ConstructorSplat>(
3406 /*offset=*/-1, *fContext.fTypes.fFloat2, std::move(zero));
3407 args.push_back(std::move(zeros));
3408 }
John Stiles4d6310a2021-01-26 19:58:22 -05003409 auto callMainFn = std::make_unique<FunctionCall>(/*offset=*/-1, &main.returnType(), &main,
Brian Osman716aeb92021-04-21 13:20:00 -04003410 std::move(args));
John Stiles4d6310a2021-01-26 19:58:22 -05003411
3412 // Synthesize `skFragColor = main()` as a BinaryExpression.
3413 auto assignmentStmt = std::make_unique<ExpressionStatement>(std::make_unique<BinaryExpression>(
3414 /*offset=*/-1,
3415 std::move(skFragColorRef),
3416 Token::Kind::TK_EQ,
3417 std::move(callMainFn),
3418 &main.returnType()));
3419
3420 // Function bodies are always wrapped in a Block.
3421 StatementArray entrypointStmts;
3422 entrypointStmts.push_back(std::move(assignmentStmt));
John Stilesbf16b6c2021-03-12 19:24:31 -05003423 auto entrypointBlock = Block::Make(/*offset=*/-1, std::move(entrypointStmts),
3424 symbolTable, /*isScope=*/true);
John Stiles4d6310a2021-01-26 19:58:22 -05003425 // Declare an entrypoint function.
3426 EntrypointAdapter adapter;
3427 adapter.fLayout = {};
3428 adapter.fModifiers = Modifiers{adapter.fLayout, Modifiers::kHasSideEffects_Flag};
3429 adapter.entrypointDecl =
3430 std::make_unique<FunctionDeclaration>(/*offset=*/-1,
3431 &adapter.fModifiers,
3432 "_entrypoint",
3433 /*parameters=*/std::vector<const Variable*>{},
3434 /*returnType=*/fContext.fTypes.fVoid.get(),
3435 /*builtin=*/false);
3436 // Define it.
John Stiles3b204892021-08-27 17:35:35 -04003437 adapter.entrypointDef = FunctionDefinition::Convert(fContext,
3438 /*offset=*/-1,
3439 *adapter.entrypointDecl,
3440 std::move(entrypointBlock),
3441 /*builtin=*/false);
John Stiles4d6310a2021-01-26 19:58:22 -05003442
3443 adapter.entrypointDecl->setDefinition(adapter.entrypointDef.get());
3444 return adapter;
3445}
3446
John Stilese40d1662021-01-29 10:08:50 -05003447void SPIRVCodeGenerator::writeUniformBuffer(std::shared_ptr<SymbolTable> topLevelSymbolTable) {
3448 SkASSERT(!fTopLevelUniforms.empty());
3449 static constexpr char kUniformBufferName[] = "_UniformBuffer";
3450
3451 // Convert the list of top-level uniforms into a matching struct named _UniformBuffer, and build
3452 // a lookup table of variables to UniformBuffer field indices.
3453 std::vector<Type::Field> fields;
3454 fields.reserve(fTopLevelUniforms.size());
3455 fTopLevelUniformMap.reserve(fTopLevelUniforms.size());
3456 for (const VarDeclaration* topLevelUniform : fTopLevelUniforms) {
3457 const Variable* var = &topLevelUniform->var();
3458 fTopLevelUniformMap[var] = (int)fields.size();
3459 fields.emplace_back(var->modifiers(), var->name(), &var->type());
3460 }
3461 fUniformBuffer.fStruct = Type::MakeStructType(/*offset=*/-1, kUniformBufferName,
3462 std::move(fields));
3463
3464 // Create a global variable to contain this struct.
3465 Layout layout;
John Stiles270cec22021-02-17 12:59:36 -05003466 layout.fBinding = fProgram.fConfig->fSettings.fDefaultUniformBinding;
3467 layout.fSet = fProgram.fConfig->fSettings.fDefaultUniformSet;
John Stilese40d1662021-01-29 10:08:50 -05003468 Modifiers modifiers{layout, Modifiers::kUniform_Flag};
3469
3470 fUniformBuffer.fInnerVariable = std::make_unique<Variable>(
John Stilesf2872e62021-05-04 11:38:43 -04003471 /*offset=*/-1, fProgram.fModifiers->add(modifiers), kUniformBufferName,
John Stilese40d1662021-01-29 10:08:50 -05003472 fUniformBuffer.fStruct.get(), /*builtin=*/false, Variable::Storage::kGlobal);
3473
3474 // Create an interface block object for this global variable.
3475 fUniformBuffer.fInterfaceBlock = std::make_unique<InterfaceBlock>(
3476 /*offset=*/-1, fUniformBuffer.fInnerVariable.get(), kUniformBufferName,
3477 kUniformBufferName, /*arraySize=*/0, topLevelSymbolTable);
3478
3479 // Generate an interface block and hold onto its ID.
3480 fUniformBufferId = this->writeInterfaceBlock(*fUniformBuffer.fInterfaceBlock);
3481}
3482
Brian Salomond8d85b92021-07-07 09:41:17 -04003483void SPIRVCodeGenerator::addRTFlipUniform(int offset) {
3484 if (fWroteRTFlip) {
3485 return;
3486 }
3487 // Flip variable hasn't been written yet. This means we don't have an existing
3488 // interface block, so we're free to just synthesize one.
3489 fWroteRTFlip = true;
3490 std::vector<Type::Field> fields;
3491 if (fProgram.fConfig->fSettings.fRTFlipOffset < 0) {
Ethan Nicholas39f6da42021-08-23 13:10:07 -04003492 fContext.fErrors->error(offset, "RTFlipOffset is negative");
Brian Salomond8d85b92021-07-07 09:41:17 -04003493 }
3494 fields.emplace_back(Modifiers(Layout(/*flags=*/0,
3495 /*location=*/-1,
3496 fProgram.fConfig->fSettings.fRTFlipOffset,
3497 /*binding=*/-1,
3498 /*index=*/-1,
3499 /*set=*/-1,
3500 /*builtin=*/-1,
Brian Osman99ddd2a2021-08-27 11:21:12 -04003501 /*inputAttachmentIndex=*/-1),
Brian Salomond8d85b92021-07-07 09:41:17 -04003502 /*flags=*/0),
3503 SKSL_RTFLIP_NAME,
3504 fContext.fTypes.fFloat2.get());
Ethan Nicholas27f06eb2021-07-26 16:39:40 -04003505 skstd::string_view name = "sksl_synthetic_uniforms";
Brian Salomond8d85b92021-07-07 09:41:17 -04003506 const Type* intfStruct =
3507 fSynthetics.takeOwnershipOfSymbol(Type::MakeStructType(/*offset=*/-1, name, fields));
3508 int binding = fProgram.fConfig->fSettings.fRTFlipBinding;
3509 if (binding == -1) {
Ethan Nicholas39f6da42021-08-23 13:10:07 -04003510 fContext.fErrors->error(offset, "layout(binding=...) is required in SPIR-V");
Brian Salomond8d85b92021-07-07 09:41:17 -04003511 }
3512 int set = fProgram.fConfig->fSettings.fRTFlipSet;
3513 if (set == -1) {
Ethan Nicholas39f6da42021-08-23 13:10:07 -04003514 fContext.fErrors->error(offset, "layout(set=...) is required in SPIR-V");
Brian Salomond8d85b92021-07-07 09:41:17 -04003515 }
3516 bool usePushConstants = fProgram.fConfig->fSettings.fUsePushConstants;
3517 int flags = usePushConstants ? Layout::Flag::kPushConstant_Flag : 0;
John Stiles0cac5ed2021-08-06 11:40:39 -04003518 const Modifiers* modsPtr;
3519 {
3520 AutoAttachPoolToThread attach(fProgram.fPool.get());
3521 Modifiers modifiers(Layout(flags,
3522 /*location=*/-1,
3523 /*offset=*/-1,
3524 binding,
3525 /*index=*/-1,
3526 set,
3527 /*builtin=*/-1,
Brian Osman99ddd2a2021-08-27 11:21:12 -04003528 /*inputAttachmentIndex=*/-1),
John Stiles0cac5ed2021-08-06 11:40:39 -04003529 Modifiers::kUniform_Flag);
3530 modsPtr = fProgram.fModifiers->add(modifiers);
Brian Salomond8d85b92021-07-07 09:41:17 -04003531 }
3532 const Variable* intfVar = fSynthetics.takeOwnershipOfSymbol(
3533 std::make_unique<Variable>(/*offset=*/-1,
3534 modsPtr,
3535 name,
3536 intfStruct,
3537 /*builtin=*/false,
3538 Variable::Storage::kGlobal));
John Stilesd7437ee2021-08-02 11:56:16 -04003539 fSPIRVBonusVariables.insert(intfVar);
John Stiles0cac5ed2021-08-06 11:40:39 -04003540 {
3541 AutoAttachPoolToThread attach(fProgram.fPool.get());
3542 fProgram.fSymbols->add(std::make_unique<Field>(/*offset=*/-1, intfVar, /*field=*/0));
Brian Salomond8d85b92021-07-07 09:41:17 -04003543 }
3544 InterfaceBlock intf(/*offset=*/-1,
3545 intfVar,
Ethan Nicholas3533ff12021-08-02 12:53:29 -04003546 name,
Brian Salomond8d85b92021-07-07 09:41:17 -04003547 /*instanceName=*/"",
3548 /*arraySize=*/0,
Ethan Nicholasc7774a72021-08-27 15:34:05 -04003549 std::make_shared<SymbolTable>(fContext, /*builtin=*/false));
Brian Salomond8d85b92021-07-07 09:41:17 -04003550
3551 this->writeInterfaceBlock(intf, false);
3552}
3553
Ethan Nicholas0df1b042017-03-31 13:56:23 -04003554void SPIRVCodeGenerator::writeInstructions(const Program& program, OutputStream& out) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04003555 fGLSLExtendedInstructions = this->nextId(nullptr);
Ethan Nicholas0df1b042017-03-31 13:56:23 -04003556 StringStream body;
John Stiles4d6310a2021-01-26 19:58:22 -05003557 // Assign SpvIds to functions.
3558 const FunctionDeclaration* main = nullptr;
Brian Osman133724c2020-10-28 14:14:39 -04003559 for (const ProgramElement* e : program.elements()) {
John Stiles4d6310a2021-01-26 19:58:22 -05003560 if (e->is<FunctionDefinition>()) {
3561 const FunctionDefinition& funcDef = e->as<FunctionDefinition>();
3562 const FunctionDeclaration& funcDecl = funcDef.declaration();
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04003563 fFunctionMap[&funcDecl] = this->nextId(nullptr);
John Stilese8da4d22021-03-24 09:19:45 -04003564 if (funcDecl.isMain()) {
John Stiles4d6310a2021-01-26 19:58:22 -05003565 main = &funcDecl;
Ethan Nicholasb6ba82c2018-01-17 15:21:50 -05003566 }
ethannicholasb3058bd2016-07-01 08:22:01 -07003567 }
3568 }
John Stiles4d6310a2021-01-26 19:58:22 -05003569 // Make sure we have a main() function.
3570 if (!main) {
Ethan Nicholas39f6da42021-08-23 13:10:07 -04003571 fContext.fErrors->error(/*offset=*/0, "program does not contain a main() function");
John Stiles4d6310a2021-01-26 19:58:22 -05003572 return;
3573 }
3574 // Emit interface blocks.
3575 std::set<SpvId> interfaceVars;
Brian Osman133724c2020-10-28 14:14:39 -04003576 for (const ProgramElement* e : program.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04003577 if (e->is<InterfaceBlock>()) {
Brian Osman1f8f5752020-10-28 14:46:21 -04003578 const InterfaceBlock& intf = e->as<InterfaceBlock>();
ethannicholasb3058bd2016-07-01 08:22:01 -07003579 SpvId id = this->writeInterfaceBlock(intf);
Brian Osman1f8f5752020-10-28 14:46:21 -04003580
3581 const Modifiers& modifiers = intf.variable().modifiers();
John Stiles8e2a84b2021-04-19 09:35:38 -04003582 if ((modifiers.fFlags & (Modifiers::kIn_Flag | Modifiers::kOut_Flag)) &&
John Stilesd7437ee2021-08-02 11:56:16 -04003583 modifiers.fLayout.fBuiltin == -1 && !this->isDead(intf.variable())) {
Ethan Nicholas8e48c1e2017-03-02 14:33:31 -05003584 interfaceVars.insert(id);
ethannicholasb3058bd2016-07-01 08:22:01 -07003585 }
3586 }
3587 }
John Stiles4d6310a2021-01-26 19:58:22 -05003588 // Emit global variable declarations.
Brian Osman133724c2020-10-28 14:14:39 -04003589 for (const ProgramElement* e : program.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04003590 if (e->is<GlobalVarDeclaration>()) {
John Stiles270cec22021-02-17 12:59:36 -05003591 this->writeGlobalVar(program.fConfig->fKind,
John Stilese40d1662021-01-29 10:08:50 -05003592 e->as<GlobalVarDeclaration>().declaration()->as<VarDeclaration>());
ethannicholasb3058bd2016-07-01 08:22:01 -07003593 }
3594 }
John Stilese40d1662021-01-29 10:08:50 -05003595 // Emit top-level uniforms into a dedicated uniform buffer.
3596 if (!fTopLevelUniforms.empty()) {
3597 this->writeUniformBuffer(get_top_level_symbol_table(*main));
3598 }
John Stiles4d6310a2021-01-26 19:58:22 -05003599 // If main() returns a half4, synthesize a tiny entrypoint function which invokes the real
3600 // main() and stores the result into sk_FragColor.
3601 EntrypointAdapter adapter;
3602 if (main->returnType() == *fContext.fTypes.fHalf4) {
3603 adapter = this->writeEntrypointAdapter(*main);
3604 if (adapter.entrypointDecl) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04003605 fFunctionMap[adapter.entrypointDecl.get()] = this->nextId(nullptr);
John Stiles4d6310a2021-01-26 19:58:22 -05003606 this->writeFunction(*adapter.entrypointDef, body);
3607 main = adapter.entrypointDecl.get();
3608 }
3609 }
3610 // Emit all the functions.
Brian Osman133724c2020-10-28 14:14:39 -04003611 for (const ProgramElement* e : program.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04003612 if (e->is<FunctionDefinition>()) {
3613 this->writeFunction(e->as<FunctionDefinition>(), body);
ethannicholasb3058bd2016-07-01 08:22:01 -07003614 }
3615 }
John Stiles4d6310a2021-01-26 19:58:22 -05003616 // Add global in/out variables to the list of interface variables.
ethannicholasb3058bd2016-07-01 08:22:01 -07003617 for (auto entry : fVariableMap) {
ethannicholasd598f792016-07-25 10:08:54 -07003618 const Variable* var = entry.first;
Ethan Nicholas453f67f2020-10-09 10:43:45 -04003619 if (var->storage() == Variable::Storage::kGlobal &&
John Stiles8e2a84b2021-04-19 09:35:38 -04003620 (var->modifiers().fFlags & (Modifiers::kIn_Flag | Modifiers::kOut_Flag)) &&
John Stilesd7437ee2021-08-02 11:56:16 -04003621 !this->isDead(*var)) {
Ethan Nicholas8e48c1e2017-03-02 14:33:31 -05003622 interfaceVars.insert(entry.second);
ethannicholasb3058bd2016-07-01 08:22:01 -07003623 }
3624 }
3625 this->writeCapabilities(out);
3626 this->writeInstruction(SpvOpExtInstImport, fGLSLExtendedInstructions, "GLSL.std.450", out);
3627 this->writeInstruction(SpvOpMemoryModel, SpvAddressingModelLogical, SpvMemoryModelGLSL450, out);
Ethan Nicholasd2e09602021-06-10 11:21:59 -04003628 this->writeOpCode(SpvOpEntryPoint, (SpvId) (3 + (main->name().length() + 4) / 4) +
ethannicholasb3058bd2016-07-01 08:22:01 -07003629 (int32_t) interfaceVars.size(), out);
John Stiles270cec22021-02-17 12:59:36 -05003630 switch (program.fConfig->fKind) {
John Stilesdbd4e6f2021-02-16 13:29:15 -05003631 case ProgramKind::kVertex:
ethannicholasb3058bd2016-07-01 08:22:01 -07003632 this->writeWord(SpvExecutionModelVertex, out);
3633 break;
John Stilesdbd4e6f2021-02-16 13:29:15 -05003634 case ProgramKind::kFragment:
ethannicholasb3058bd2016-07-01 08:22:01 -07003635 this->writeWord(SpvExecutionModelFragment, out);
3636 break;
Ethan Nicholas762466e2017-06-29 10:03:38 -04003637 default:
John Stilesf57207b2021-02-02 17:50:34 -05003638 SK_ABORT("cannot write this kind of program to SPIR-V\n");
ethannicholasb3058bd2016-07-01 08:22:01 -07003639 }
Ethan Nicholasbb155e22017-07-24 10:05:09 -04003640 SpvId entryPoint = fFunctionMap[main];
3641 this->writeWord(entryPoint, out);
Ethan Nicholasd2e09602021-06-10 11:21:59 -04003642 this->writeString(main->name(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003643 for (int var : interfaceVars) {
3644 this->writeWord(var, out);
3645 }
John Stiles270cec22021-02-17 12:59:36 -05003646 if (program.fConfig->fKind == ProgramKind::kFragment) {
Greg Daniel64773e62016-11-22 09:44:03 -05003647 this->writeInstruction(SpvOpExecutionMode,
3648 fFunctionMap[main],
ethannicholasb3058bd2016-07-01 08:22:01 -07003649 SpvExecutionModeOriginUpperLeft,
3650 out);
3651 }
Brian Osman133724c2020-10-28 14:14:39 -04003652 for (const ProgramElement* e : program.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04003653 if (e->is<Extension>()) {
Ethan Nicholasd2e09602021-06-10 11:21:59 -04003654 this->writeInstruction(SpvOpSourceExtension, e->as<Extension>().name(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003655 }
3656 }
Greg Daniel64773e62016-11-22 09:44:03 -05003657
Ethan Nicholas0df1b042017-03-31 13:56:23 -04003658 write_stringstream(fExtraGlobalsBuffer, out);
3659 write_stringstream(fNameBuffer, out);
3660 write_stringstream(fDecorationBuffer, out);
3661 write_stringstream(fConstantBuffer, out);
Ethan Nicholas0df1b042017-03-31 13:56:23 -04003662 write_stringstream(body, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003663}
3664
Ethan Nicholas941e7e22016-12-12 15:33:30 -05003665bool SPIRVCodeGenerator::generateCode() {
Ethan Nicholas39f6da42021-08-23 13:10:07 -04003666 SkASSERT(!fContext.fErrors->errorCount());
Ethan Nicholas941e7e22016-12-12 15:33:30 -05003667 this->writeWord(SpvMagicNumber, *fOut);
3668 this->writeWord(SpvVersion, *fOut);
3669 this->writeWord(SKSL_MAGIC, *fOut);
Ethan Nicholas0df1b042017-03-31 13:56:23 -04003670 StringStream buffer;
Ethan Nicholas941e7e22016-12-12 15:33:30 -05003671 this->writeInstructions(fProgram, buffer);
3672 this->writeWord(fIdCount, *fOut);
3673 this->writeWord(0, *fOut); // reserved, always zero
Ethan Nicholas0df1b042017-03-31 13:56:23 -04003674 write_stringstream(buffer, *fOut);
Ethan Nicholas553239b2021-08-23 15:40:20 -04003675 fContext.fErrors->reportPendingErrors(PositionInfo());
Ethan Nicholas39f6da42021-08-23 13:10:07 -04003676 return fContext.fErrors->errorCount() == 0;
ethannicholasb3058bd2016-07-01 08:22:01 -07003677}
3678
John Stilesa6841be2020-08-06 14:11:56 -04003679} // namespace SkSL