blob: 980b8d4761fb585c37c2db542941a3997af5d73e [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"
Ethan Nicholasc8452722021-10-07 10:47:32 -040015#include "src/sksl/SkSLThreadContext.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
Greg Danielcb0d81b2021-10-06 14:50:52 -040035// Skia's magic number is 31 and goes in the top 16 bits. We can use the lower bits to version the
36// sksl generator if we want.
37// https://github.com/KhronosGroup/SPIRV-Headers/blob/master/include/spirv/spir-v.xml#L84
38static const int32_t SKSL_MAGIC = 0x001F0000;
ethannicholasb3058bd2016-07-01 08:22:01 -070039
40void SPIRVCodeGenerator::setupIntrinsics() {
John Stilesaaac4e42021-05-06 14:08:28 -040041#define ALL_GLSL(x) std::make_tuple(kGLSL_STD_450_IntrinsicOpcodeKind, GLSLstd450 ## x, \
42 GLSLstd450 ## x, GLSLstd450 ## x, GLSLstd450 ## x)
43#define BY_TYPE_GLSL(ifFloat, ifInt, ifUInt) std::make_tuple(kGLSL_STD_450_IntrinsicOpcodeKind, \
44 GLSLstd450 ## ifFloat, \
45 GLSLstd450 ## ifInt, \
46 GLSLstd450 ## ifUInt, \
ethannicholasb3058bd2016-07-01 08:22:01 -070047 SpvOpUndef)
John Stilesaaac4e42021-05-06 14:08:28 -040048#define ALL_SPIRV(x) std::make_tuple(kSPIRV_IntrinsicOpcodeKind, \
49 SpvOp ## x, SpvOp ## x, SpvOp ## x, SpvOp ## x)
50#define SPECIAL(x) std::make_tuple(kSpecial_IntrinsicOpcodeKind, k ## x ## _SpecialIntrinsic, \
51 k ## x ## _SpecialIntrinsic, k ## x ## _SpecialIntrinsic, \
ethannicholasb3058bd2016-07-01 08:22:01 -070052 k ## x ## _SpecialIntrinsic)
John Stilesaaac4e42021-05-06 14:08:28 -040053 fIntrinsicMap[k_round_IntrinsicKind] = ALL_GLSL(Round);
54 fIntrinsicMap[k_roundEven_IntrinsicKind] = ALL_GLSL(RoundEven);
55 fIntrinsicMap[k_trunc_IntrinsicKind] = ALL_GLSL(Trunc);
56 fIntrinsicMap[k_abs_IntrinsicKind] = BY_TYPE_GLSL(FAbs, SAbs, SAbs);
57 fIntrinsicMap[k_sign_IntrinsicKind] = BY_TYPE_GLSL(FSign, SSign, SSign);
58 fIntrinsicMap[k_floor_IntrinsicKind] = ALL_GLSL(Floor);
59 fIntrinsicMap[k_ceil_IntrinsicKind] = ALL_GLSL(Ceil);
60 fIntrinsicMap[k_fract_IntrinsicKind] = ALL_GLSL(Fract);
61 fIntrinsicMap[k_radians_IntrinsicKind] = ALL_GLSL(Radians);
62 fIntrinsicMap[k_degrees_IntrinsicKind] = ALL_GLSL(Degrees);
63 fIntrinsicMap[k_sin_IntrinsicKind] = ALL_GLSL(Sin);
64 fIntrinsicMap[k_cos_IntrinsicKind] = ALL_GLSL(Cos);
65 fIntrinsicMap[k_tan_IntrinsicKind] = ALL_GLSL(Tan);
66 fIntrinsicMap[k_asin_IntrinsicKind] = ALL_GLSL(Asin);
67 fIntrinsicMap[k_acos_IntrinsicKind] = ALL_GLSL(Acos);
68 fIntrinsicMap[k_atan_IntrinsicKind] = SPECIAL(Atan);
69 fIntrinsicMap[k_sinh_IntrinsicKind] = ALL_GLSL(Sinh);
70 fIntrinsicMap[k_cosh_IntrinsicKind] = ALL_GLSL(Cosh);
71 fIntrinsicMap[k_tanh_IntrinsicKind] = ALL_GLSL(Tanh);
72 fIntrinsicMap[k_asinh_IntrinsicKind] = ALL_GLSL(Asinh);
73 fIntrinsicMap[k_acosh_IntrinsicKind] = ALL_GLSL(Acosh);
74 fIntrinsicMap[k_atanh_IntrinsicKind] = ALL_GLSL(Atanh);
75 fIntrinsicMap[k_pow_IntrinsicKind] = ALL_GLSL(Pow);
76 fIntrinsicMap[k_exp_IntrinsicKind] = ALL_GLSL(Exp);
77 fIntrinsicMap[k_log_IntrinsicKind] = ALL_GLSL(Log);
78 fIntrinsicMap[k_exp2_IntrinsicKind] = ALL_GLSL(Exp2);
79 fIntrinsicMap[k_log2_IntrinsicKind] = ALL_GLSL(Log2);
80 fIntrinsicMap[k_sqrt_IntrinsicKind] = ALL_GLSL(Sqrt);
81 fIntrinsicMap[k_inverse_IntrinsicKind] = ALL_GLSL(MatrixInverse);
82 fIntrinsicMap[k_outerProduct_IntrinsicKind] = ALL_SPIRV(OuterProduct);
83 fIntrinsicMap[k_transpose_IntrinsicKind] = ALL_SPIRV(Transpose);
84 fIntrinsicMap[k_isinf_IntrinsicKind] = ALL_SPIRV(IsInf);
85 fIntrinsicMap[k_isnan_IntrinsicKind] = ALL_SPIRV(IsNan);
86 fIntrinsicMap[k_inversesqrt_IntrinsicKind] = ALL_GLSL(InverseSqrt);
87 fIntrinsicMap[k_determinant_IntrinsicKind] = ALL_GLSL(Determinant);
88 fIntrinsicMap[k_matrixCompMult_IntrinsicKind] = SPECIAL(MatrixCompMult);
89 fIntrinsicMap[k_matrixInverse_IntrinsicKind] = ALL_GLSL(MatrixInverse);
90 fIntrinsicMap[k_mod_IntrinsicKind] = SPECIAL(Mod);
91 fIntrinsicMap[k_modf_IntrinsicKind] = ALL_GLSL(Modf);
92 fIntrinsicMap[k_min_IntrinsicKind] = SPECIAL(Min);
93 fIntrinsicMap[k_max_IntrinsicKind] = SPECIAL(Max);
94 fIntrinsicMap[k_clamp_IntrinsicKind] = SPECIAL(Clamp);
95 fIntrinsicMap[k_saturate_IntrinsicKind] = SPECIAL(Saturate);
96 fIntrinsicMap[k_dot_IntrinsicKind] = std::make_tuple(kSPIRV_IntrinsicOpcodeKind,
97 SpvOpDot, SpvOpUndef, SpvOpUndef, SpvOpUndef);
98 fIntrinsicMap[k_mix_IntrinsicKind] = SPECIAL(Mix);
99 fIntrinsicMap[k_step_IntrinsicKind] = SPECIAL(Step);
100 fIntrinsicMap[k_smoothstep_IntrinsicKind] = SPECIAL(SmoothStep);
101 fIntrinsicMap[k_fma_IntrinsicKind] = ALL_GLSL(Fma);
102 fIntrinsicMap[k_frexp_IntrinsicKind] = ALL_GLSL(Frexp);
103 fIntrinsicMap[k_ldexp_IntrinsicKind] = ALL_GLSL(Ldexp);
ethannicholasb3058bd2016-07-01 08:22:01 -0700104
John Stilesaaac4e42021-05-06 14:08:28 -0400105#define PACK(type) fIntrinsicMap[k_pack##type##_IntrinsicKind] = ALL_GLSL(Pack##type); \
106 fIntrinsicMap[k_unpack##type##_IntrinsicKind] = ALL_GLSL(Unpack##type)
ethannicholasb3058bd2016-07-01 08:22:01 -0700107 PACK(Snorm4x8);
108 PACK(Unorm4x8);
109 PACK(Snorm2x16);
110 PACK(Unorm2x16);
111 PACK(Half2x16);
112 PACK(Double2x32);
John Stilesaaac4e42021-05-06 14:08:28 -0400113#undef PACK
114 fIntrinsicMap[k_length_IntrinsicKind] = ALL_GLSL(Length);
115 fIntrinsicMap[k_distance_IntrinsicKind] = ALL_GLSL(Distance);
116 fIntrinsicMap[k_cross_IntrinsicKind] = ALL_GLSL(Cross);
117 fIntrinsicMap[k_normalize_IntrinsicKind] = ALL_GLSL(Normalize);
118 fIntrinsicMap[k_faceforward_IntrinsicKind] = ALL_GLSL(FaceForward);
119 fIntrinsicMap[k_reflect_IntrinsicKind] = ALL_GLSL(Reflect);
120 fIntrinsicMap[k_refract_IntrinsicKind] = ALL_GLSL(Refract);
121 fIntrinsicMap[k_bitCount_IntrinsicKind] = ALL_SPIRV(BitCount);
122 fIntrinsicMap[k_findLSB_IntrinsicKind] = ALL_GLSL(FindILsb);
123 fIntrinsicMap[k_findMSB_IntrinsicKind] = BY_TYPE_GLSL(FindSMsb, FindSMsb, FindUMsb);
124 fIntrinsicMap[k_dFdx_IntrinsicKind] = std::make_tuple(kSPIRV_IntrinsicOpcodeKind,
125 SpvOpDPdx, SpvOpUndef,
126 SpvOpUndef, SpvOpUndef);
127 fIntrinsicMap[k_dFdy_IntrinsicKind] = SPECIAL(DFdy);
128 fIntrinsicMap[k_fwidth_IntrinsicKind] = std::make_tuple(kSPIRV_IntrinsicOpcodeKind,
129 SpvOpFwidth, SpvOpUndef,
130 SpvOpUndef, SpvOpUndef);
131 fIntrinsicMap[k_makeSampler2D_IntrinsicKind] = SPECIAL(SampledImage);
Stephen Whiteff5d7a22019-07-26 17:42:06 -0400132
John Stilesaaac4e42021-05-06 14:08:28 -0400133 fIntrinsicMap[k_sample_IntrinsicKind] = SPECIAL(Texture);
134 fIntrinsicMap[k_subpassLoad_IntrinsicKind] = SPECIAL(SubpassLoad);
Greg Daniel64773e62016-11-22 09:44:03 -0500135
John Stilesaaac4e42021-05-06 14:08:28 -0400136 fIntrinsicMap[k_floatBitsToInt_IntrinsicKind] = ALL_SPIRV(Bitcast);
137 fIntrinsicMap[k_floatBitsToUint_IntrinsicKind] = ALL_SPIRV(Bitcast);
138 fIntrinsicMap[k_intBitsToFloat_IntrinsicKind] = ALL_SPIRV(Bitcast);
139 fIntrinsicMap[k_uintBitsToFloat_IntrinsicKind] = ALL_SPIRV(Bitcast);
John Stilescc9ff002020-12-09 18:39:41 -0500140
John Stilesaaac4e42021-05-06 14:08:28 -0400141 fIntrinsicMap[k_any_IntrinsicKind] = std::make_tuple(kSPIRV_IntrinsicOpcodeKind,
Brian Osman540c13a2020-11-24 16:55:34 -0500142 SpvOpUndef, SpvOpUndef,
John Stilesaaac4e42021-05-06 14:08:28 -0400143 SpvOpUndef, SpvOpAny);
144 fIntrinsicMap[k_all_IntrinsicKind] = std::make_tuple(kSPIRV_IntrinsicOpcodeKind,
145 SpvOpUndef, SpvOpUndef,
146 SpvOpUndef, SpvOpAll);
147 fIntrinsicMap[k_not_IntrinsicKind] = std::make_tuple(kSPIRV_IntrinsicOpcodeKind,
148 SpvOpUndef, SpvOpUndef, SpvOpUndef,
Brian Osman540c13a2020-11-24 16:55:34 -0500149 SpvOpLogicalNot);
John Stilesaaac4e42021-05-06 14:08:28 -0400150 fIntrinsicMap[k_equal_IntrinsicKind] = std::make_tuple(kSPIRV_IntrinsicOpcodeKind,
Ethan Nicholas0187ae62017-05-03 11:03:44 -0400151 SpvOpFOrdEqual, SpvOpIEqual,
152 SpvOpIEqual, SpvOpLogicalEqual);
John Stilesaaac4e42021-05-06 14:08:28 -0400153 fIntrinsicMap[k_notEqual_IntrinsicKind] = std::make_tuple(kSPIRV_IntrinsicOpcodeKind,
Ethan Nicholas0187ae62017-05-03 11:03:44 -0400154 SpvOpFOrdNotEqual, SpvOpINotEqual,
155 SpvOpINotEqual,
156 SpvOpLogicalNotEqual);
John Stilesaaac4e42021-05-06 14:08:28 -0400157 fIntrinsicMap[k_lessThan_IntrinsicKind] = std::make_tuple(kSPIRV_IntrinsicOpcodeKind,
158 SpvOpFOrdLessThan,
159 SpvOpSLessThan,
160 SpvOpULessThan,
161 SpvOpUndef);
162 fIntrinsicMap[k_lessThanEqual_IntrinsicKind] = std::make_tuple(kSPIRV_IntrinsicOpcodeKind,
163 SpvOpFOrdLessThanEqual,
164 SpvOpSLessThanEqual,
165 SpvOpULessThanEqual,
166 SpvOpUndef);
167 fIntrinsicMap[k_greaterThan_IntrinsicKind] = std::make_tuple(kSPIRV_IntrinsicOpcodeKind,
168 SpvOpFOrdGreaterThan,
169 SpvOpSGreaterThan,
170 SpvOpUGreaterThan,
171 SpvOpUndef);
172 fIntrinsicMap[k_greaterThanEqual_IntrinsicKind] = std::make_tuple(kSPIRV_IntrinsicOpcodeKind,
173 SpvOpFOrdGreaterThanEqual,
174 SpvOpSGreaterThanEqual,
175 SpvOpUGreaterThanEqual,
176 SpvOpUndef);
ethannicholasb3058bd2016-07-01 08:22:01 -0700177// interpolateAt* not yet supported...
178}
179
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400180void SPIRVCodeGenerator::writeWord(int32_t word, OutputStream& out) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700181 out.write((const char*) &word, sizeof(word));
ethannicholasb3058bd2016-07-01 08:22:01 -0700182}
183
ethannicholasd598f792016-07-25 10:08:54 -0700184static bool is_float(const Context& context, const Type& type) {
John Stiles4c151702021-02-09 18:31:34 -0500185 return (type.isScalar() || type.isVector() || type.isMatrix()) &&
186 type.componentType().isFloat();
ethannicholasb3058bd2016-07-01 08:22:01 -0700187}
188
ethannicholasd598f792016-07-25 10:08:54 -0700189static bool is_signed(const Context& context, const Type& type) {
Brian Osmanc9145f32021-07-08 13:40:10 -0400190 return (type.isScalar() || type.isVector()) && type.componentType().isSigned();
ethannicholasb3058bd2016-07-01 08:22:01 -0700191}
192
ethannicholasd598f792016-07-25 10:08:54 -0700193static bool is_unsigned(const Context& context, const Type& type) {
John Stiles4c151702021-02-09 18:31:34 -0500194 return (type.isScalar() || type.isVector()) && type.componentType().isUnsigned();
ethannicholasb3058bd2016-07-01 08:22:01 -0700195}
196
ethannicholasd598f792016-07-25 10:08:54 -0700197static bool is_bool(const Context& context, const Type& type) {
John Stiles4c151702021-02-09 18:31:34 -0500198 return (type.isScalar() || type.isVector()) && type.componentType().isBoolean();
ethannicholasb3058bd2016-07-01 08:22:01 -0700199}
200
John Stiles07367122021-09-08 13:12:26 -0400201static bool is_out(const Modifiers& m) {
202 return (m.fFlags & Modifiers::kOut_Flag) != 0;
ethannicholasb3058bd2016-07-01 08:22:01 -0700203}
204
John Stiles07367122021-09-08 13:12:26 -0400205static bool is_in(const Modifiers& m) {
206 switch (m.fFlags & (Modifiers::kOut_Flag | Modifiers::kIn_Flag)) {
John Stiles6a51b202021-09-08 10:45:08 -0400207 case Modifiers::kOut_Flag: // out
208 return false;
209
210 case 0: // implicit in
211 case Modifiers::kIn_Flag: // explicit in
212 case Modifiers::kOut_Flag | Modifiers::kIn_Flag: // inout
213 return true;
214
215 default: SkUNREACHABLE;
216 }
217}
218
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400219void SPIRVCodeGenerator::writeOpCode(SpvOp_ opCode, int length, OutputStream& out) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400220 SkASSERT(opCode != SpvOpLoad || &out != &fConstantBuffer);
221 SkASSERT(opCode != SpvOpUndef);
ethannicholasb3058bd2016-07-01 08:22:01 -0700222 switch (opCode) {
223 case SpvOpReturn: // fall through
224 case SpvOpReturnValue: // fall through
ethannicholas552882f2016-07-07 06:30:48 -0700225 case SpvOpKill: // fall through
Ethan Nicholas7fb39362020-12-16 15:25:19 -0500226 case SpvOpSwitch: // fall through
ethannicholasb3058bd2016-07-01 08:22:01 -0700227 case SpvOpBranch: // fall through
228 case SpvOpBranchConditional:
John Stilesf2b08cc2021-05-17 14:46:05 -0400229 if (fCurrentBlock == 0) {
230 // We just encountered dead code--instructions that don't have an associated block.
231 // Synthesize a label if this happens; this is necessary to satisfy the validator.
232 this->writeLabel(this->nextId(nullptr), out);
233 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700234 fCurrentBlock = 0;
235 break;
236 case SpvOpConstant: // fall through
237 case SpvOpConstantTrue: // fall through
238 case SpvOpConstantFalse: // fall through
239 case SpvOpConstantComposite: // fall through
240 case SpvOpTypeVoid: // fall through
241 case SpvOpTypeInt: // fall through
242 case SpvOpTypeFloat: // fall through
243 case SpvOpTypeBool: // fall through
244 case SpvOpTypeVector: // fall through
245 case SpvOpTypeMatrix: // fall through
246 case SpvOpTypeArray: // fall through
247 case SpvOpTypePointer: // fall through
248 case SpvOpTypeFunction: // fall through
249 case SpvOpTypeRuntimeArray: // fall through
250 case SpvOpTypeStruct: // fall through
251 case SpvOpTypeImage: // fall through
252 case SpvOpTypeSampledImage: // fall through
Stephen Whiteff5d7a22019-07-26 17:42:06 -0400253 case SpvOpTypeSampler: // fall through
ethannicholasb3058bd2016-07-01 08:22:01 -0700254 case SpvOpVariable: // fall through
255 case SpvOpFunction: // fall through
256 case SpvOpFunctionParameter: // fall through
257 case SpvOpFunctionEnd: // fall through
258 case SpvOpExecutionMode: // fall through
259 case SpvOpMemoryModel: // fall through
260 case SpvOpCapability: // fall through
261 case SpvOpExtInstImport: // fall through
262 case SpvOpEntryPoint: // fall through
263 case SpvOpSource: // fall through
264 case SpvOpSourceExtension: // fall through
265 case SpvOpName: // fall through
266 case SpvOpMemberName: // fall through
267 case SpvOpDecorate: // fall through
268 case SpvOpMemberDecorate:
269 break;
270 default:
John Stilesf3a28db2021-03-10 23:00:47 -0500271 // We may find ourselves with dead code--instructions that don't have an associated
272 // block. This should be a rare event, but if it happens, synthesize a label; this is
273 // necessary to satisfy the validator.
274 if (fCurrentBlock == 0) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -0400275 this->writeLabel(this->nextId(nullptr), out);
John Stiles7142e402021-02-23 12:28:18 -0500276 }
John Stiles453f1432021-02-25 16:58:04 -0500277 break;
ethannicholasb3058bd2016-07-01 08:22:01 -0700278 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700279 this->writeWord((length << 16) | opCode, out);
ethannicholasb3058bd2016-07-01 08:22:01 -0700280}
281
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400282void SPIRVCodeGenerator::writeLabel(SpvId label, OutputStream& out) {
Ethan Nicholas7fb39362020-12-16 15:25:19 -0500283 SkASSERT(!fCurrentBlock);
ethannicholasb3058bd2016-07-01 08:22:01 -0700284 fCurrentBlock = label;
285 this->writeInstruction(SpvOpLabel, label, out);
286}
287
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400288void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, OutputStream& out) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700289 this->writeOpCode(opCode, 1, out);
290}
291
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400292void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, int32_t word1, OutputStream& out) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700293 this->writeOpCode(opCode, 2, out);
294 this->writeWord(word1, out);
295}
296
Ethan Nicholas962dec42021-06-10 13:06:39 -0400297void SPIRVCodeGenerator::writeString(skstd::string_view s, OutputStream& out) {
Ethan Nicholasd2e09602021-06-10 11:21:59 -0400298 out.write(s.data(), s.length());
299 switch (s.length() % 4) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700300 case 1:
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 2:
Ethan Nicholas9e1138d2016-11-21 10:39:35 -0500304 out.write8(0);
John Stiles30212b72020-06-11 17:55:07 -0400305 [[fallthrough]];
ethannicholasb3058bd2016-07-01 08:22:01 -0700306 case 3:
Ethan Nicholas9e1138d2016-11-21 10:39:35 -0500307 out.write8(0);
ethannicholasb3058bd2016-07-01 08:22:01 -0700308 break;
309 default:
310 this->writeWord(0, out);
Ethan Nicholasb13f3692021-09-10 16:49:42 -0400311 break;
ethannicholasb3058bd2016-07-01 08:22:01 -0700312 }
313}
314
Ethan Nicholas962dec42021-06-10 13:06:39 -0400315void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, skstd::string_view string,
316 OutputStream& out) {
Ethan Nicholasd2e09602021-06-10 11:21:59 -0400317 this->writeOpCode(opCode, 1 + (string.length() + 4) / 4, out);
318 this->writeString(string, out);
ethannicholasb3058bd2016-07-01 08:22:01 -0700319}
320
321
Ethan Nicholas962dec42021-06-10 13:06:39 -0400322void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, int32_t word1, skstd::string_view string,
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400323 OutputStream& out) {
Ethan Nicholasd2e09602021-06-10 11:21:59 -0400324 this->writeOpCode(opCode, 2 + (string.length() + 4) / 4, out);
ethannicholasb3058bd2016-07-01 08:22:01 -0700325 this->writeWord(word1, out);
Ethan Nicholasd2e09602021-06-10 11:21:59 -0400326 this->writeString(string, out);
ethannicholasb3058bd2016-07-01 08:22:01 -0700327}
328
Greg Daniel64773e62016-11-22 09:44:03 -0500329void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, int32_t word1, int32_t word2,
Ethan Nicholas962dec42021-06-10 13:06:39 -0400330 skstd::string_view string, OutputStream& out) {
Ethan Nicholasd2e09602021-06-10 11:21:59 -0400331 this->writeOpCode(opCode, 3 + (string.length() + 4) / 4, out);
ethannicholasb3058bd2016-07-01 08:22:01 -0700332 this->writeWord(word1, out);
333 this->writeWord(word2, out);
Ethan Nicholasd2e09602021-06-10 11:21:59 -0400334 this->writeString(string, out);
ethannicholasb3058bd2016-07-01 08:22:01 -0700335}
336
Greg Daniel64773e62016-11-22 09:44:03 -0500337void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, int32_t word1, int32_t word2,
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400338 OutputStream& out) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700339 this->writeOpCode(opCode, 3, out);
340 this->writeWord(word1, out);
341 this->writeWord(word2, out);
342}
343
Greg Daniel64773e62016-11-22 09:44:03 -0500344void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, int32_t word1, int32_t word2,
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400345 int32_t word3, OutputStream& out) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700346 this->writeOpCode(opCode, 4, out);
347 this->writeWord(word1, out);
348 this->writeWord(word2, out);
349 this->writeWord(word3, out);
350}
351
Greg Daniel64773e62016-11-22 09:44:03 -0500352void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, int32_t word1, int32_t word2,
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400353 int32_t word3, int32_t word4, OutputStream& out) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700354 this->writeOpCode(opCode, 5, out);
355 this->writeWord(word1, out);
356 this->writeWord(word2, out);
357 this->writeWord(word3, out);
358 this->writeWord(word4, out);
359}
360
Greg Daniel64773e62016-11-22 09:44:03 -0500361void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, int32_t word1, int32_t word2,
362 int32_t word3, int32_t word4, int32_t word5,
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400363 OutputStream& out) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700364 this->writeOpCode(opCode, 6, out);
365 this->writeWord(word1, out);
366 this->writeWord(word2, out);
367 this->writeWord(word3, out);
368 this->writeWord(word4, out);
369 this->writeWord(word5, out);
370}
371
Greg Daniel64773e62016-11-22 09:44:03 -0500372void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, int32_t word1, int32_t word2,
ethannicholasb3058bd2016-07-01 08:22:01 -0700373 int32_t word3, int32_t word4, int32_t word5,
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400374 int32_t word6, OutputStream& out) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700375 this->writeOpCode(opCode, 7, out);
376 this->writeWord(word1, out);
377 this->writeWord(word2, out);
378 this->writeWord(word3, out);
379 this->writeWord(word4, out);
380 this->writeWord(word5, out);
381 this->writeWord(word6, out);
382}
383
Greg Daniel64773e62016-11-22 09:44:03 -0500384void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, int32_t word1, int32_t word2,
ethannicholasb3058bd2016-07-01 08:22:01 -0700385 int32_t word3, int32_t word4, int32_t word5,
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400386 int32_t word6, int32_t word7, OutputStream& out) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700387 this->writeOpCode(opCode, 8, out);
388 this->writeWord(word1, out);
389 this->writeWord(word2, out);
390 this->writeWord(word3, out);
391 this->writeWord(word4, out);
392 this->writeWord(word5, out);
393 this->writeWord(word6, out);
394 this->writeWord(word7, out);
395}
396
Greg Daniel64773e62016-11-22 09:44:03 -0500397void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, int32_t word1, int32_t word2,
ethannicholasb3058bd2016-07-01 08:22:01 -0700398 int32_t word3, int32_t word4, int32_t word5,
399 int32_t word6, int32_t word7, int32_t word8,
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400400 OutputStream& out) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700401 this->writeOpCode(opCode, 9, out);
402 this->writeWord(word1, out);
403 this->writeWord(word2, out);
404 this->writeWord(word3, out);
405 this->writeWord(word4, out);
406 this->writeWord(word5, out);
407 this->writeWord(word6, out);
408 this->writeWord(word7, out);
409 this->writeWord(word8, out);
410}
411
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400412void SPIRVCodeGenerator::writeCapabilities(OutputStream& out) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700413 for (uint64_t i = 0, bit = 1; i <= kLast_Capability; i++, bit <<= 1) {
414 if (fCapabilities & bit) {
415 this->writeInstruction(SpvOpCapability, (SpvId) i, out);
416 }
417 }
Brian Osman99ddd2a2021-08-27 11:21:12 -0400418 this->writeInstruction(SpvOpCapability, SpvCapabilityShader, out);
ethannicholasb3058bd2016-07-01 08:22:01 -0700419}
420
Ethan Nicholas8f352ce2021-03-17 14:12:20 -0400421SpvId SPIRVCodeGenerator::nextId(const Type* type) {
422 return this->nextId(type && type->hasPrecision() && !type->highPrecision()
423 ? Precision::kRelaxed
424 : Precision::kDefault);
425}
426
427SpvId SPIRVCodeGenerator::nextId(Precision precision) {
428 if (precision == Precision::kRelaxed && !fProgram.fConfig->fSettings.fForceHighPrecision) {
429 this->writeInstruction(SpvOpDecorate, fIdCount, SpvDecorationRelaxedPrecision,
430 fDecorationBuffer);
431 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700432 return fIdCount++;
433}
434
Ethan Nicholas19671772016-11-28 16:30:17 -0500435void SPIRVCodeGenerator::writeStruct(const Type& type, const MemoryLayout& memoryLayout,
436 SpvId resultId) {
Ethan Nicholase2c49992020-10-05 11:49:11 -0400437 this->writeInstruction(SpvOpName, resultId, String(type.name()).c_str(), fNameBuffer);
ethannicholasb3058bd2016-07-01 08:22:01 -0700438 // go ahead and write all of the field types, so we don't inadvertently write them while we're
439 // in the middle of writing the struct instruction
440 std::vector<SpvId> types;
441 for (const auto& f : type.fields()) {
Ethan Nicholas19671772016-11-28 16:30:17 -0500442 types.push_back(this->getType(*f.fType, memoryLayout));
ethannicholasb3058bd2016-07-01 08:22:01 -0700443 }
444 this->writeOpCode(SpvOpTypeStruct, 2 + (int32_t) types.size(), fConstantBuffer);
445 this->writeWord(resultId, fConstantBuffer);
446 for (SpvId id : types) {
447 this->writeWord(id, fConstantBuffer);
448 }
449 size_t offset = 0;
450 for (int32_t i = 0; i < (int32_t) type.fields().size(); i++) {
Ethan Nicholascc5d3e02019-04-19 09:50:56 -0400451 const Type::Field& field = type.fields()[i];
John Stiles21f5f452020-11-30 09:57:59 -0500452 if (!MemoryLayout::LayoutIsSupported(*field.fType)) {
Ethan Nicholas89cfde12021-09-27 11:20:34 -0400453 fContext.fErrors->error(type.fLine, "type '" + field.fType->name() +
Ethan Nicholas3abc6c62021-08-13 11:20:09 -0400454 "' is not permitted here");
John Stiles0023c0c2020-11-16 13:32:18 -0500455 return;
456 }
Ethan Nicholascc5d3e02019-04-19 09:50:56 -0400457 size_t size = memoryLayout.size(*field.fType);
458 size_t alignment = memoryLayout.alignment(*field.fType);
459 const Layout& fieldLayout = field.fModifiers.fLayout;
Ethan Nicholas19671772016-11-28 16:30:17 -0500460 if (fieldLayout.fOffset >= 0) {
Greg Danieldbd44c72017-01-24 15:12:12 -0500461 if (fieldLayout.fOffset < (int) offset) {
Ethan Nicholas89cfde12021-09-27 11:20:34 -0400462 fContext.fErrors->error(type.fLine,
Ethan Nicholas3abc6c62021-08-13 11:20:09 -0400463 "offset of field '" + field.fName + "' must be at "
464 "least " + to_string((int) offset));
Ethan Nicholas19671772016-11-28 16:30:17 -0500465 }
466 if (fieldLayout.fOffset % alignment) {
Ethan Nicholas89cfde12021-09-27 11:20:34 -0400467 fContext.fErrors->error(type.fLine,
Ethan Nicholas3abc6c62021-08-13 11:20:09 -0400468 "offset of field '" + field.fName + "' must be a multiple"
469 " of " + to_string((int) alignment));
Ethan Nicholas19671772016-11-28 16:30:17 -0500470 }
471 offset = fieldLayout.fOffset;
472 } else {
473 size_t mod = offset % alignment;
474 if (mod) {
475 offset += alignment - mod;
476 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700477 }
Ethan Nicholascc5d3e02019-04-19 09:50:56 -0400478 this->writeInstruction(SpvOpMemberName, resultId, i, field.fName, fNameBuffer);
Ethan Nicholas19671772016-11-28 16:30:17 -0500479 this->writeLayout(fieldLayout, resultId, i);
Ethan Nicholascc5d3e02019-04-19 09:50:56 -0400480 if (field.fModifiers.fLayout.fBuiltin < 0) {
Greg Daniel64773e62016-11-22 09:44:03 -0500481 this->writeInstruction(SpvOpMemberDecorate, resultId, (SpvId) i, SpvDecorationOffset,
ethannicholasb3058bd2016-07-01 08:22:01 -0700482 (SpvId) offset, fDecorationBuffer);
483 }
John Stiles9aeed132020-11-24 17:36:06 -0500484 if (field.fType->isMatrix()) {
Greg Daniel64773e62016-11-22 09:44:03 -0500485 this->writeInstruction(SpvOpMemberDecorate, resultId, i, SpvDecorationColMajor,
ethannicholasb3058bd2016-07-01 08:22:01 -0700486 fDecorationBuffer);
Greg Daniel64773e62016-11-22 09:44:03 -0500487 this->writeInstruction(SpvOpMemberDecorate, resultId, i, SpvDecorationMatrixStride,
Ethan Nicholascc5d3e02019-04-19 09:50:56 -0400488 (SpvId) memoryLayout.stride(*field.fType),
ethannicholas8ac838d2016-11-22 08:39:36 -0800489 fDecorationBuffer);
ethannicholasb3058bd2016-07-01 08:22:01 -0700490 }
Ethan Nicholascc5d3e02019-04-19 09:50:56 -0400491 if (!field.fType->highPrecision()) {
492 this->writeInstruction(SpvOpMemberDecorate, resultId, (SpvId) i,
493 SpvDecorationRelaxedPrecision, fDecorationBuffer);
494 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700495 offset += size;
John Stilesc0c51062020-12-03 17:16:29 -0500496 if ((field.fType->isArray() || field.fType->isStruct()) && offset % alignment != 0) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700497 offset += alignment - offset % alignment;
498 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700499 }
500}
501
Ethan Nicholase2c49992020-10-05 11:49:11 -0400502const Type& SPIRVCodeGenerator::getActualType(const Type& type) {
Ethan Nicholase1f55022019-02-05 17:17:40 -0500503 if (type.isFloat()) {
John Stiles54e7c052021-01-11 14:22:36 -0500504 return *fContext.fTypes.fFloat;
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400505 }
Brian Osmanc9145f32021-07-08 13:40:10 -0400506 if (type.isSigned()) {
John Stiles54e7c052021-01-11 14:22:36 -0500507 return *fContext.fTypes.fInt;
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400508 }
Ethan Nicholase1f55022019-02-05 17:17:40 -0500509 if (type.isUnsigned()) {
John Stiles54e7c052021-01-11 14:22:36 -0500510 return *fContext.fTypes.fUInt;
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400511 }
John Stiles9aeed132020-11-24 17:36:06 -0500512 if (type.isMatrix() || type.isVector()) {
John Stiles54e7c052021-01-11 14:22:36 -0500513 if (type.componentType() == *fContext.fTypes.fHalf) {
514 return fContext.fTypes.fFloat->toCompound(fContext, type.columns(), type.rows());
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400515 }
Ethan Nicholas722c83e2021-05-04 11:39:30 -0400516 if (type.componentType() == *fContext.fTypes.fShort) {
John Stiles54e7c052021-01-11 14:22:36 -0500517 return fContext.fTypes.fInt->toCompound(fContext, type.columns(), type.rows());
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400518 }
Ethan Nicholas722c83e2021-05-04 11:39:30 -0400519 if (type.componentType() == *fContext.fTypes.fUShort) {
John Stiles54e7c052021-01-11 14:22:36 -0500520 return fContext.fTypes.fUInt->toCompound(fContext, type.columns(), type.rows());
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400521 }
522 }
523 return type;
524}
525
ethannicholasb3058bd2016-07-01 08:22:01 -0700526SpvId SPIRVCodeGenerator::getType(const Type& type) {
ethannicholas8ac838d2016-11-22 08:39:36 -0800527 return this->getType(type, fDefaultLayout);
528}
529
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400530SpvId SPIRVCodeGenerator::getType(const Type& rawType, const MemoryLayout& layout) {
John Stiles3c991fd2021-08-09 14:19:58 -0400531 const Type* type;
532 std::unique_ptr<Type> arrayType;
533 String arrayName;
534
535 if (rawType.isArray()) {
536 // For arrays, we need to synthesize a temporary Array type using the "actual" component
537 // type. That is, if `short[10]` is passed in, we need to synthesize a `int[10]` Type.
538 // Otherwise, we can end up with two different SpvIds for the same array type.
539 const Type& component = this->getActualType(rawType.componentType());
540 arrayName = component.getArrayName(rawType.columns());
541 arrayType = Type::MakeArrayType(arrayName, component, rawType.columns());
542 type = arrayType.get();
543 } else {
544 // For non-array types, we can simply look up the "actual" type and use it.
545 type = &this->getActualType(rawType);
546 }
547
548 String key(type->name());
549 if (type->isStruct() || type->isArray()) {
Jim Van Verthf3ec9832020-10-21 16:09:57 -0400550 key += to_string((int)layout.fStd);
Brian Osman2a4c0fb2021-01-22 13:41:40 -0500551#ifdef SK_DEBUG
552 SkASSERT(layout.fStd == MemoryLayout::Standard::k140_Standard ||
553 layout.fStd == MemoryLayout::Standard::k430_Standard);
554 MemoryLayout::Standard otherStd = layout.fStd == MemoryLayout::Standard::k140_Standard
555 ? MemoryLayout::Standard::k430_Standard
556 : MemoryLayout::Standard::k140_Standard;
John Stiles3c991fd2021-08-09 14:19:58 -0400557 String otherKey = type->name() + to_string((int)otherStd);
Brian Osman2a4c0fb2021-01-22 13:41:40 -0500558 SkASSERT(fTypeMap.find(otherKey) == fTypeMap.end());
559#endif
Jim Van Verthf3ec9832020-10-21 16:09:57 -0400560 }
ethannicholas8ac838d2016-11-22 08:39:36 -0800561 auto entry = fTypeMap.find(key);
ethannicholasb3058bd2016-07-01 08:22:01 -0700562 if (entry == fTypeMap.end()) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -0400563 SpvId result = this->nextId(nullptr);
John Stiles3c991fd2021-08-09 14:19:58 -0400564 switch (type->typeKind()) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400565 case Type::TypeKind::kScalar:
John Stiles3c991fd2021-08-09 14:19:58 -0400566 if (type->isBoolean()) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700567 this->writeInstruction(SpvOpTypeBool, result, fConstantBuffer);
John Stiles3c991fd2021-08-09 14:19:58 -0400568 } else if (type->isSigned()) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700569 this->writeInstruction(SpvOpTypeInt, result, 32, 1, fConstantBuffer);
John Stiles3c991fd2021-08-09 14:19:58 -0400570 } else if (type->isUnsigned()) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700571 this->writeInstruction(SpvOpTypeInt, result, 32, 0, fConstantBuffer);
John Stiles3c991fd2021-08-09 14:19:58 -0400572 } else if (type->isFloat()) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700573 this->writeInstruction(SpvOpTypeFloat, result, 32, fConstantBuffer);
ethannicholasb3058bd2016-07-01 08:22:01 -0700574 } else {
John Stiles3c991fd2021-08-09 14:19:58 -0400575 SkDEBUGFAILF("unrecognized scalar type '%s'", type->description().c_str());
ethannicholasb3058bd2016-07-01 08:22:01 -0700576 }
577 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400578 case Type::TypeKind::kVector:
Greg Daniel64773e62016-11-22 09:44:03 -0500579 this->writeInstruction(SpvOpTypeVector, result,
John Stiles3c991fd2021-08-09 14:19:58 -0400580 this->getType(type->componentType(), layout),
581 type->columns(), fConstantBuffer);
ethannicholasb3058bd2016-07-01 08:22:01 -0700582 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400583 case Type::TypeKind::kMatrix:
John Stiles51d33982021-03-08 09:18:07 -0500584 this->writeInstruction(
585 SpvOpTypeMatrix,
586 result,
John Stiles3c991fd2021-08-09 14:19:58 -0400587 this->getType(IndexExpression::IndexType(fContext, *type), layout),
588 type->columns(),
John Stiles51d33982021-03-08 09:18:07 -0500589 fConstantBuffer);
ethannicholasb3058bd2016-07-01 08:22:01 -0700590 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400591 case Type::TypeKind::kStruct:
John Stiles3c991fd2021-08-09 14:19:58 -0400592 this->writeStruct(*type, layout, result);
ethannicholasb3058bd2016-07-01 08:22:01 -0700593 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400594 case Type::TypeKind::kArray: {
John Stiles3c991fd2021-08-09 14:19:58 -0400595 if (!MemoryLayout::LayoutIsSupported(*type)) {
Ethan Nicholas89cfde12021-09-27 11:20:34 -0400596 fContext.fErrors->error(type->fLine,
Ethan Nicholas3abc6c62021-08-13 11:20:09 -0400597 "type '" + type->name() + "' is not permitted here");
Ethan Nicholas8f352ce2021-03-17 14:12:20 -0400598 return this->nextId(nullptr);
John Stiles21f5f452020-11-30 09:57:59 -0500599 }
John Stiles3c991fd2021-08-09 14:19:58 -0400600 if (type->columns() > 0) {
601 SpvId typeId = this->getType(type->componentType(), layout);
Ethan Nicholas89cfde12021-09-27 11:20:34 -0400602 Literal countLiteral(/*line=*/-1, type->columns(),
John Stiles7591d4b2021-09-13 13:32:06 -0400603 fContext.fTypes.fInt.get());
604 SpvId countId = this->writeLiteral(countLiteral);
John Stilesb5db4822021-01-21 13:04:40 -0500605 this->writeInstruction(SpvOpTypeArray, result, typeId, countId,
606 fConstantBuffer);
Greg Daniel64773e62016-11-22 09:44:03 -0500607 this->writeInstruction(SpvOpDecorate, result, SpvDecorationArrayStride,
John Stiles3c991fd2021-08-09 14:19:58 -0400608 (int32_t) layout.stride(*type),
ethannicholas8ac838d2016-11-22 08:39:36 -0800609 fDecorationBuffer);
ethannicholasb3058bd2016-07-01 08:22:01 -0700610 } else {
John Stiles5570c512020-11-19 17:58:07 -0500611 // We shouldn't have any runtime-sized arrays right now
Ethan Nicholas89cfde12021-09-27 11:20:34 -0400612 fContext.fErrors->error(type->fLine,
Ethan Nicholas3abc6c62021-08-13 11:20:09 -0400613 "runtime-sized arrays are not supported in SPIR-V");
Greg Daniel64773e62016-11-22 09:44:03 -0500614 this->writeInstruction(SpvOpTypeRuntimeArray, result,
John Stiles3c991fd2021-08-09 14:19:58 -0400615 this->getType(type->componentType(), layout),
ethannicholas8ac838d2016-11-22 08:39:36 -0800616 fConstantBuffer);
Ethan Nicholas0dd30d92017-05-01 16:57:07 -0400617 this->writeInstruction(SpvOpDecorate, result, SpvDecorationArrayStride,
John Stiles3c991fd2021-08-09 14:19:58 -0400618 (int32_t) layout.stride(*type),
Ethan Nicholas0dd30d92017-05-01 16:57:07 -0400619 fDecorationBuffer);
ethannicholasb3058bd2016-07-01 08:22:01 -0700620 }
621 break;
622 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400623 case Type::TypeKind::kSampler: {
Greg Daniel64773e62016-11-22 09:44:03 -0500624 SpvId image = result;
John Stiles3c991fd2021-08-09 14:19:58 -0400625 if (SpvDimSubpassData != type->dimensions()) {
626 image = this->getType(type->textureType(), layout);
Greg Daniel64773e62016-11-22 09:44:03 -0500627 }
John Stiles3c991fd2021-08-09 14:19:58 -0400628 if (SpvDimBuffer == type->dimensions()) {
Ethan Nicholas0187ae62017-05-03 11:03:44 -0400629 fCapabilities |= (((uint64_t) 1) << SpvCapabilitySampledBuffer);
630 }
John Stiles3c991fd2021-08-09 14:19:58 -0400631 if (SpvDimSubpassData != type->dimensions()) {
Greg Daniel64773e62016-11-22 09:44:03 -0500632 this->writeInstruction(SpvOpTypeSampledImage, result, image, fConstantBuffer);
633 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700634 break;
635 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400636 case Type::TypeKind::kSeparateSampler: {
Stephen Whiteff5d7a22019-07-26 17:42:06 -0400637 this->writeInstruction(SpvOpTypeSampler, result, fConstantBuffer);
638 break;
639 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400640 case Type::TypeKind::kTexture: {
Stephen Whiteff5d7a22019-07-26 17:42:06 -0400641 this->writeInstruction(SpvOpTypeImage, result,
John Stiles54e7c052021-01-11 14:22:36 -0500642 this->getType(*fContext.fTypes.fFloat, layout),
John Stiles3c991fd2021-08-09 14:19:58 -0400643 type->dimensions(), type->isDepth(),
644 type->isArrayedTexture(), type->isMultisampled(),
645 type->isSampled() ? 1 : 2, SpvImageFormatUnknown,
646 fConstantBuffer);
Stephen Whiteff5d7a22019-07-26 17:42:06 -0400647 fImageTypeMap[key] = result;
648 break;
649 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700650 default:
John Stiles3c991fd2021-08-09 14:19:58 -0400651 if (type->isVoid()) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700652 this->writeInstruction(SpvOpTypeVoid, result, fConstantBuffer);
653 } else {
John Stiles3c991fd2021-08-09 14:19:58 -0400654 SkDEBUGFAILF("invalid type: %s", type->description().c_str());
ethannicholasb3058bd2016-07-01 08:22:01 -0700655 }
Ethan Nicholasb13f3692021-09-10 16:49:42 -0400656 break;
ethannicholasb3058bd2016-07-01 08:22:01 -0700657 }
ethannicholas8ac838d2016-11-22 08:39:36 -0800658 fTypeMap[key] = result;
ethannicholasb3058bd2016-07-01 08:22:01 -0700659 return result;
660 }
661 return entry->second;
662}
663
Ethan Nicholas0187ae62017-05-03 11:03:44 -0400664SpvId SPIRVCodeGenerator::getImageType(const Type& type) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400665 SkASSERT(type.typeKind() == Type::TypeKind::kSampler);
Ethan Nicholas0187ae62017-05-03 11:03:44 -0400666 this->getType(type);
667 String key = type.name() + to_string((int) fDefaultLayout.fStd);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400668 SkASSERT(fImageTypeMap.find(key) != fImageTypeMap.end());
Ethan Nicholas0187ae62017-05-03 11:03:44 -0400669 return fImageTypeMap[key];
670}
671
ethannicholasd598f792016-07-25 10:08:54 -0700672SpvId SPIRVCodeGenerator::getFunctionType(const FunctionDeclaration& function) {
Ethan Nicholased84b732020-10-08 11:45:44 -0400673 String key = to_string(this->getType(function.returnType())) + "(";
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400674 String separator;
Brian Osman5bf3e202020-10-13 10:34:18 -0400675 const std::vector<const Variable*>& parameters = function.parameters();
Ethan Nicholased84b732020-10-08 11:45:44 -0400676 for (size_t i = 0; i < parameters.size(); i++) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700677 key += separator;
678 separator = ", ";
Ethan Nicholased84b732020-10-08 11:45:44 -0400679 key += to_string(this->getType(parameters[i]->type()));
ethannicholasb3058bd2016-07-01 08:22:01 -0700680 }
681 key += ")";
682 auto entry = fTypeMap.find(key);
683 if (entry == fTypeMap.end()) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -0400684 SpvId result = this->nextId(nullptr);
Ethan Nicholased84b732020-10-08 11:45:44 -0400685 int32_t length = 3 + (int32_t) parameters.size();
686 SpvId returnType = this->getType(function.returnType());
ethannicholasb3058bd2016-07-01 08:22:01 -0700687 std::vector<SpvId> parameterTypes;
Ethan Nicholased84b732020-10-08 11:45:44 -0400688 for (size_t i = 0; i < parameters.size(); i++) {
Greg Daniel64773e62016-11-22 09:44:03 -0500689 // glslang seems to treat all function arguments as pointers whether they need to be or
690 // not. I was initially puzzled by this until I ran bizarre failures with certain
691 // patterns of function calls and control constructs, as exemplified by this minimal
ethannicholasb3058bd2016-07-01 08:22:01 -0700692 // failure case:
693 //
694 // void sphere(float x) {
695 // }
Greg Daniel64773e62016-11-22 09:44:03 -0500696 //
ethannicholasb3058bd2016-07-01 08:22:01 -0700697 // void map() {
698 // sphere(1.0);
699 // }
Greg Daniel64773e62016-11-22 09:44:03 -0500700 //
ethannicholasb3058bd2016-07-01 08:22:01 -0700701 // void main() {
702 // for (int i = 0; i < 1; i++) {
703 // map();
704 // }
705 // }
706 //
Greg Daniel64773e62016-11-22 09:44:03 -0500707 // As of this writing, compiling this in the "obvious" way (with sphere taking a float)
708 // crashes. Making it take a float* and storing the argument in a temporary variable,
ethannicholasb3058bd2016-07-01 08:22:01 -0700709 // as glslang does, fixes it. It's entirely possible I simply missed whichever part of
710 // the spec makes this make sense.
John Stiles07367122021-09-08 13:12:26 -0400711 parameterTypes.push_back(this->getPointerType(parameters[i]->type(),
712 SpvStorageClassFunction));
ethannicholasb3058bd2016-07-01 08:22:01 -0700713 }
714 this->writeOpCode(SpvOpTypeFunction, length, fConstantBuffer);
715 this->writeWord(result, fConstantBuffer);
716 this->writeWord(returnType, fConstantBuffer);
717 for (SpvId id : parameterTypes) {
718 this->writeWord(id, fConstantBuffer);
719 }
720 fTypeMap[key] = result;
721 return result;
722 }
723 return entry->second;
724}
725
ethannicholas8ac838d2016-11-22 08:39:36 -0800726SpvId SPIRVCodeGenerator::getPointerType(const Type& type, SpvStorageClass_ storageClass) {
727 return this->getPointerType(type, fDefaultLayout, storageClass);
728}
729
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400730SpvId SPIRVCodeGenerator::getPointerType(const Type& rawType, const MemoryLayout& layout,
ethannicholasb3058bd2016-07-01 08:22:01 -0700731 SpvStorageClass_ storageClass) {
Ethan Nicholase2c49992020-10-05 11:49:11 -0400732 const Type& type = this->getActualType(rawType);
Ethan Nicholas2a099da2020-01-02 14:40:54 -0500733 String key = type.displayName() + "*" + to_string(layout.fStd) + to_string(storageClass);
ethannicholasb3058bd2016-07-01 08:22:01 -0700734 auto entry = fTypeMap.find(key);
735 if (entry == fTypeMap.end()) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -0400736 SpvId result = this->nextId(nullptr);
Greg Daniel64773e62016-11-22 09:44:03 -0500737 this->writeInstruction(SpvOpTypePointer, result, storageClass,
ethannicholasd598f792016-07-25 10:08:54 -0700738 this->getType(type), fConstantBuffer);
ethannicholasb3058bd2016-07-01 08:22:01 -0700739 fTypeMap[key] = result;
740 return result;
741 }
742 return entry->second;
743}
744
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400745SpvId SPIRVCodeGenerator::writeExpression(const Expression& expr, OutputStream& out) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400746 switch (expr.kind()) {
747 case Expression::Kind::kBinary:
John Stiles81365af2020-08-18 09:24:00 -0400748 return this->writeBinaryExpression(expr.as<BinaryExpression>(), out);
John Stilese3ae9682021-08-05 10:35:01 -0400749 case Expression::Kind::kConstructorArrayCast:
750 return this->writeExpression(*expr.as<ConstructorArrayCast>().argument(), out);
John Stiles7384b372021-04-01 13:48:15 -0400751 case Expression::Kind::kConstructorArray:
John Stilesd47330f2021-04-08 23:25:52 -0400752 case Expression::Kind::kConstructorStruct:
753 return this->writeCompositeConstructor(expr.asAnyConstructor(), out);
John Stilese1182782021-03-30 22:09:37 -0400754 case Expression::Kind::kConstructorDiagonalMatrix:
755 return this->writeConstructorDiagonalMatrix(expr.as<ConstructorDiagonalMatrix>(), out);
John Stiles5abb9e12021-04-06 13:47:19 -0400756 case Expression::Kind::kConstructorMatrixResize:
757 return this->writeConstructorMatrixResize(expr.as<ConstructorMatrixResize>(), out);
John Stilesfd7252f2021-04-04 22:24:40 -0400758 case Expression::Kind::kConstructorScalarCast:
759 return this->writeConstructorScalarCast(expr.as<ConstructorScalarCast>(), out);
John Stiles2938eea2021-04-01 18:58:25 -0400760 case Expression::Kind::kConstructorSplat:
761 return this->writeConstructorSplat(expr.as<ConstructorSplat>(), out);
John Stiles8cad6372021-04-07 12:31:13 -0400762 case Expression::Kind::kConstructorCompound:
763 return this->writeConstructorCompound(expr.as<ConstructorCompound>(), out);
764 case Expression::Kind::kConstructorCompoundCast:
765 return this->writeConstructorCompoundCast(expr.as<ConstructorCompoundCast>(), out);
Ethan Nicholase6592142020-09-08 10:22:09 -0400766 case Expression::Kind::kFieldAccess:
John Stiles81365af2020-08-18 09:24:00 -0400767 return this->writeFieldAccess(expr.as<FieldAccess>(), out);
Ethan Nicholase6592142020-09-08 10:22:09 -0400768 case Expression::Kind::kFunctionCall:
John Stiles81365af2020-08-18 09:24:00 -0400769 return this->writeFunctionCall(expr.as<FunctionCall>(), out);
John Stiles7591d4b2021-09-13 13:32:06 -0400770 case Expression::Kind::kLiteral:
771 return this->writeLiteral(expr.as<Literal>());
Ethan Nicholase6592142020-09-08 10:22:09 -0400772 case Expression::Kind::kPrefix:
John Stiles81365af2020-08-18 09:24:00 -0400773 return this->writePrefixExpression(expr.as<PrefixExpression>(), out);
Ethan Nicholase6592142020-09-08 10:22:09 -0400774 case Expression::Kind::kPostfix:
John Stiles81365af2020-08-18 09:24:00 -0400775 return this->writePostfixExpression(expr.as<PostfixExpression>(), out);
Ethan Nicholase6592142020-09-08 10:22:09 -0400776 case Expression::Kind::kSwizzle:
John Stiles81365af2020-08-18 09:24:00 -0400777 return this->writeSwizzle(expr.as<Swizzle>(), out);
Ethan Nicholase6592142020-09-08 10:22:09 -0400778 case Expression::Kind::kVariableReference:
John Stiles81365af2020-08-18 09:24:00 -0400779 return this->writeVariableReference(expr.as<VariableReference>(), out);
Ethan Nicholase6592142020-09-08 10:22:09 -0400780 case Expression::Kind::kTernary:
John Stiles81365af2020-08-18 09:24:00 -0400781 return this->writeTernaryExpression(expr.as<TernaryExpression>(), out);
Ethan Nicholase6592142020-09-08 10:22:09 -0400782 case Expression::Kind::kIndex:
John Stiles81365af2020-08-18 09:24:00 -0400783 return this->writeIndexExpression(expr.as<IndexExpression>(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -0700784 default:
John Stileseada7bc2021-02-02 16:29:32 -0500785 SkDEBUGFAILF("unsupported expression: %s", expr.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -0500786 break;
ethannicholasb3058bd2016-07-01 08:22:01 -0700787 }
788 return -1;
789}
790
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400791SpvId SPIRVCodeGenerator::writeIntrinsicCall(const FunctionCall& c, OutputStream& out) {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400792 const FunctionDeclaration& function = c.function();
John Stilesaaac4e42021-05-06 14:08:28 -0400793 auto intrinsic = fIntrinsicMap.find(function.intrinsicKind());
John Stiles93e661a2020-12-08 16:17:00 -0500794 if (intrinsic == fIntrinsicMap.end()) {
Ethan Nicholas89cfde12021-09-27 11:20:34 -0400795 fContext.fErrors->error(c.fLine, "unsupported intrinsic '" + function.description() + "'");
John Stiles93e661a2020-12-08 16:17:00 -0500796 return -1;
797 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700798 int32_t intrinsicId;
John Stiles89ac7c22020-12-30 17:47:31 -0500799 const ExpressionArray& arguments = c.arguments();
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400800 if (arguments.size() > 0) {
801 const Type& type = arguments[0]->type();
John Stilesaaac4e42021-05-06 14:08:28 -0400802 if (std::get<0>(intrinsic->second) == kSpecial_IntrinsicOpcodeKind ||
803 is_float(fContext, type)) {
Ethan Nicholasbb155e22017-07-24 10:05:09 -0400804 intrinsicId = std::get<1>(intrinsic->second);
805 } else if (is_signed(fContext, type)) {
806 intrinsicId = std::get<2>(intrinsic->second);
807 } else if (is_unsigned(fContext, type)) {
808 intrinsicId = std::get<3>(intrinsic->second);
809 } else if (is_bool(fContext, type)) {
810 intrinsicId = std::get<4>(intrinsic->second);
811 } else {
812 intrinsicId = std::get<1>(intrinsic->second);
813 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700814 } else {
Ethan Nicholasbb155e22017-07-24 10:05:09 -0400815 intrinsicId = std::get<1>(intrinsic->second);
ethannicholasb3058bd2016-07-01 08:22:01 -0700816 }
817 switch (std::get<0>(intrinsic->second)) {
John Stilesaaac4e42021-05-06 14:08:28 -0400818 case kGLSL_STD_450_IntrinsicOpcodeKind: {
Ethan Nicholas7f015882021-03-23 14:16:52 -0400819 SpvId result = this->nextId(&c.type());
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400820 std::vector<SpvId> argumentIds;
John Stiles07367122021-09-08 13:12:26 -0400821 std::vector<TempVar> tempVars;
822 argumentIds.reserve(arguments.size());
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400823 for (size_t i = 0; i < arguments.size(); i++) {
John Stiles07367122021-09-08 13:12:26 -0400824 if (is_out(function.parameters()[i]->modifiers())) {
825 argumentIds.push_back(
826 this->writeFunctionCallArgument(*arguments[i],
827 function.parameters()[i]->modifiers(),
828 &tempVars,
829 out));
Ethan Nicholas8f7e28f2018-03-26 14:24:27 -0400830 } else {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400831 argumentIds.push_back(this->writeExpression(*arguments[i], out));
Ethan Nicholas8f7e28f2018-03-26 14:24:27 -0400832 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700833 }
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400834 this->writeOpCode(SpvOpExtInst, 5 + (int32_t) argumentIds.size(), out);
Ethan Nicholas30d30222020-09-11 12:27:26 -0400835 this->writeWord(this->getType(c.type()), out);
ethannicholasb3058bd2016-07-01 08:22:01 -0700836 this->writeWord(result, out);
837 this->writeWord(fGLSLExtendedInstructions, out);
838 this->writeWord(intrinsicId, out);
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400839 for (SpvId id : argumentIds) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700840 this->writeWord(id, out);
841 }
John Stiles07367122021-09-08 13:12:26 -0400842 this->copyBackTempVars(tempVars, out);
ethannicholasb3058bd2016-07-01 08:22:01 -0700843 return result;
844 }
John Stilesaaac4e42021-05-06 14:08:28 -0400845 case kSPIRV_IntrinsicOpcodeKind: {
Brian Osman46787d52020-11-24 14:18:23 -0500846 // GLSL supports dot(float, float), but SPIR-V does not. Convert it to FMul
John Stiles9aeed132020-11-24 17:36:06 -0500847 if (intrinsicId == SpvOpDot && arguments[0]->type().isScalar()) {
Brian Osman46787d52020-11-24 14:18:23 -0500848 intrinsicId = SpvOpFMul;
849 }
Ethan Nicholas7f015882021-03-23 14:16:52 -0400850 SpvId result = this->nextId(&c.type());
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400851 std::vector<SpvId> argumentIds;
John Stiles07367122021-09-08 13:12:26 -0400852 std::vector<TempVar> tempVars;
853 argumentIds.reserve(arguments.size());
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400854 for (size_t i = 0; i < arguments.size(); i++) {
John Stiles07367122021-09-08 13:12:26 -0400855 if (is_out(function.parameters()[i]->modifiers())) {
856 argumentIds.push_back(
857 this->writeFunctionCallArgument(*arguments[i],
858 function.parameters()[i]->modifiers(),
859 &tempVars,
860 out));
Ethan Nicholas8f7e28f2018-03-26 14:24:27 -0400861 } else {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400862 argumentIds.push_back(this->writeExpression(*arguments[i], out));
Ethan Nicholas8f7e28f2018-03-26 14:24:27 -0400863 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700864 }
John Stiles2558c462021-03-16 17:49:20 -0400865 if (!c.type().isVoid()) {
Ethan Nicholasbb155e22017-07-24 10:05:09 -0400866 this->writeOpCode((SpvOp_) intrinsicId, 3 + (int32_t) arguments.size(), out);
Ethan Nicholas30d30222020-09-11 12:27:26 -0400867 this->writeWord(this->getType(c.type()), out);
Ethan Nicholasbb155e22017-07-24 10:05:09 -0400868 this->writeWord(result, out);
869 } else {
870 this->writeOpCode((SpvOp_) intrinsicId, 1 + (int32_t) arguments.size(), out);
871 }
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400872 for (SpvId id : argumentIds) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700873 this->writeWord(id, out);
874 }
John Stiles07367122021-09-08 13:12:26 -0400875 this->copyBackTempVars(tempVars, out);
ethannicholasb3058bd2016-07-01 08:22:01 -0700876 return result;
877 }
John Stilesaaac4e42021-05-06 14:08:28 -0400878 case kSpecial_IntrinsicOpcodeKind:
ethannicholasb3058bd2016-07-01 08:22:01 -0700879 return this->writeSpecialIntrinsic(c, (SpecialIntrinsic) intrinsicId, out);
880 default:
Ethan Nicholas89cfde12021-09-27 11:20:34 -0400881 fContext.fErrors->error(c.fLine, "unsupported intrinsic '" + function.description() +
882 "'");
John Stiles93e661a2020-12-08 16:17:00 -0500883 return -1;
ethannicholasb3058bd2016-07-01 08:22:01 -0700884 }
885}
886
Brian Salomond8d85b92021-07-07 09:41:17 -0400887SpvId SPIRVCodeGenerator::vectorize(const Expression& arg, int vectorSize, OutputStream& out) {
888 SkASSERT(vectorSize >= 1 && vectorSize <= 4);
889 const Type& argType = arg.type();
890 SpvId raw = this->writeExpression(arg, out);
891 if (argType.isScalar()) {
892 if (vectorSize == 1) {
893 return raw;
894 }
895 SpvId vector = this->nextId(&argType);
896 this->writeOpCode(SpvOpCompositeConstruct, 3 + vectorSize, out);
897 this->writeWord(this->getType(argType.toCompound(fContext, vectorSize, 1)), out);
898 this->writeWord(vector, out);
899 for (int i = 0; i < vectorSize; i++) {
900 this->writeWord(raw, out);
901 }
902 return vector;
903 } else {
904 SkASSERT(vectorSize == argType.columns());
905 return raw;
906 }
907}
908
John Stiles8e3b6be2020-10-13 11:14:08 -0400909std::vector<SpvId> SPIRVCodeGenerator::vectorize(const ExpressionArray& args, OutputStream& out) {
Brian Salomond8d85b92021-07-07 09:41:17 -0400910 int vectorSize = 1;
Ethan Nicholas0fc07f92018-02-27 15:25:47 -0500911 for (const auto& a : args) {
John Stiles9aeed132020-11-24 17:36:06 -0500912 if (a->type().isVector()) {
Brian Salomond8d85b92021-07-07 09:41:17 -0400913 if (vectorSize > 1) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400914 SkASSERT(a->type().columns() == vectorSize);
Brian Salomond8d85b92021-07-07 09:41:17 -0400915 } else {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400916 vectorSize = a->type().columns();
Ethan Nicholas0fc07f92018-02-27 15:25:47 -0500917 }
918 }
919 }
920 std::vector<SpvId> result;
John Stiles8e3b6be2020-10-13 11:14:08 -0400921 result.reserve(args.size());
Ethan Nicholas30d30222020-09-11 12:27:26 -0400922 for (const auto& arg : args) {
Brian Salomond8d85b92021-07-07 09:41:17 -0400923 result.push_back(this->vectorize(*arg, vectorSize, out));
Ethan Nicholas0fc07f92018-02-27 15:25:47 -0500924 }
925 return result;
926}
927
928void SPIRVCodeGenerator::writeGLSLExtendedInstruction(const Type& type, SpvId id, SpvId floatInst,
929 SpvId signedInst, SpvId unsignedInst,
930 const std::vector<SpvId>& args,
931 OutputStream& out) {
932 this->writeOpCode(SpvOpExtInst, 5 + args.size(), out);
933 this->writeWord(this->getType(type), out);
934 this->writeWord(id, out);
935 this->writeWord(fGLSLExtendedInstructions, out);
936
937 if (is_float(fContext, type)) {
938 this->writeWord(floatInst, out);
939 } else if (is_signed(fContext, type)) {
940 this->writeWord(signedInst, out);
941 } else if (is_unsigned(fContext, type)) {
942 this->writeWord(unsignedInst, out);
943 } else {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400944 SkASSERT(false);
Ethan Nicholas0fc07f92018-02-27 15:25:47 -0500945 }
946 for (SpvId a : args) {
947 this->writeWord(a, out);
948 }
949}
950
Greg Daniel64773e62016-11-22 09:44:03 -0500951SpvId SPIRVCodeGenerator::writeSpecialIntrinsic(const FunctionCall& c, SpecialIntrinsic kind,
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400952 OutputStream& out) {
John Stiles8e3b6be2020-10-13 11:14:08 -0400953 const ExpressionArray& arguments = c.arguments();
Ethan Nicholas30d30222020-09-11 12:27:26 -0400954 const Type& callType = c.type();
Ethan Nicholas8f352ce2021-03-17 14:12:20 -0400955 SpvId result = this->nextId(nullptr);
ethannicholasb3058bd2016-07-01 08:22:01 -0700956 switch (kind) {
957 case kAtan_SpecialIntrinsic: {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400958 std::vector<SpvId> argumentIds;
John Stiles07367122021-09-08 13:12:26 -0400959 argumentIds.reserve(arguments.size());
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400960 for (const std::unique_ptr<Expression>& arg : arguments) {
961 argumentIds.push_back(this->writeExpression(*arg, out));
ethannicholasb3058bd2016-07-01 08:22:01 -0700962 }
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400963 this->writeOpCode(SpvOpExtInst, 5 + (int32_t) argumentIds.size(), out);
Ethan Nicholas30d30222020-09-11 12:27:26 -0400964 this->writeWord(this->getType(callType), out);
ethannicholasb3058bd2016-07-01 08:22:01 -0700965 this->writeWord(result, out);
966 this->writeWord(fGLSLExtendedInstructions, out);
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400967 this->writeWord(argumentIds.size() == 2 ? GLSLstd450Atan2 : GLSLstd450Atan, out);
968 for (SpvId id : argumentIds) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700969 this->writeWord(id, out);
970 }
Ethan Nicholas0187ae62017-05-03 11:03:44 -0400971 break;
972 }
Stephen Whiteff5d7a22019-07-26 17:42:06 -0400973 case kSampledImage_SpecialIntrinsic: {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400974 SkASSERT(arguments.size() == 2);
975 SpvId img = this->writeExpression(*arguments[0], out);
976 SpvId sampler = this->writeExpression(*arguments[1], out);
Stephen Whiteff5d7a22019-07-26 17:42:06 -0400977 this->writeInstruction(SpvOpSampledImage,
Ethan Nicholas30d30222020-09-11 12:27:26 -0400978 this->getType(callType),
Stephen Whiteff5d7a22019-07-26 17:42:06 -0400979 result,
980 img,
981 sampler,
982 out);
983 break;
984 }
Ethan Nicholas0187ae62017-05-03 11:03:44 -0400985 case kSubpassLoad_SpecialIntrinsic: {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400986 SpvId img = this->writeExpression(*arguments[0], out);
John Stiles8e3b6be2020-10-13 11:14:08 -0400987 ExpressionArray args;
John Stilesf4bda742020-10-14 16:57:41 -0400988 args.reserve_back(2);
Ethan Nicholas89cfde12021-09-27 11:20:34 -0400989 args.push_back(Literal::MakeInt(fContext, /*line=*/-1, /*value=*/0));
990 args.push_back(Literal::MakeInt(fContext, /*line=*/-1, /*value=*/0));
991 ConstructorCompound ctor(/*line=*/-1, *fContext.fTypes.fInt2, std::move(args));
Ethan Nicholas0187ae62017-05-03 11:03:44 -0400992 SpvId coords = this->writeConstantVector(ctor);
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400993 if (arguments.size() == 1) {
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 out);
1000 } else {
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001001 SkASSERT(arguments.size() == 2);
1002 SpvId sample = this->writeExpression(*arguments[1], out);
Ethan Nicholas0187ae62017-05-03 11:03:44 -04001003 this->writeInstruction(SpvOpImageRead,
Ethan Nicholas30d30222020-09-11 12:27:26 -04001004 this->getType(callType),
Ethan Nicholas0187ae62017-05-03 11:03:44 -04001005 result,
1006 img,
1007 coords,
1008 SpvImageOperandsSampleMask,
1009 sample,
1010 out);
1011 }
1012 break;
1013 }
ethannicholasb3058bd2016-07-01 08:22:01 -07001014 case kTexture_SpecialIntrinsic: {
Ethan Nicholas2b3dab62016-11-28 12:03:26 -05001015 SpvOp_ op = SpvOpImageSampleImplicitLod;
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001016 const Type& arg1Type = arguments[1]->type();
1017 switch (arguments[0]->type().dimensions()) {
Ethan Nicholas2b3dab62016-11-28 12:03:26 -05001018 case SpvDim1D:
John Stiles54e7c052021-01-11 14:22:36 -05001019 if (arg1Type == *fContext.fTypes.fFloat2) {
Ethan Nicholas2b3dab62016-11-28 12:03:26 -05001020 op = SpvOpImageSampleProjImplicitLod;
1021 } else {
John Stiles54e7c052021-01-11 14:22:36 -05001022 SkASSERT(arg1Type == *fContext.fTypes.fFloat);
Ethan Nicholas2b3dab62016-11-28 12:03:26 -05001023 }
1024 break;
1025 case SpvDim2D:
John Stiles54e7c052021-01-11 14:22:36 -05001026 if (arg1Type == *fContext.fTypes.fFloat3) {
Ethan Nicholas2b3dab62016-11-28 12:03:26 -05001027 op = SpvOpImageSampleProjImplicitLod;
1028 } else {
John Stiles54e7c052021-01-11 14:22:36 -05001029 SkASSERT(arg1Type == *fContext.fTypes.fFloat2);
Ethan Nicholas2b3dab62016-11-28 12:03:26 -05001030 }
1031 break;
1032 case SpvDim3D:
John Stiles54e7c052021-01-11 14:22:36 -05001033 if (arg1Type == *fContext.fTypes.fFloat4) {
Ethan Nicholas2b3dab62016-11-28 12:03:26 -05001034 op = SpvOpImageSampleProjImplicitLod;
1035 } else {
John Stiles54e7c052021-01-11 14:22:36 -05001036 SkASSERT(arg1Type == *fContext.fTypes.fFloat3);
Ethan Nicholas2b3dab62016-11-28 12:03:26 -05001037 }
1038 break;
1039 case SpvDimCube: // fall through
1040 case SpvDimRect: // fall through
1041 case SpvDimBuffer: // fall through
1042 case SpvDimSubpassData:
1043 break;
1044 }
Ethan Nicholas30d30222020-09-11 12:27:26 -04001045 SpvId type = this->getType(callType);
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001046 SpvId sampler = this->writeExpression(*arguments[0], out);
1047 SpvId uv = this->writeExpression(*arguments[1], out);
1048 if (arguments.size() == 3) {
Ethan Nicholas2b3dab62016-11-28 12:03:26 -05001049 this->writeInstruction(op, type, result, sampler, uv,
ethannicholasb3058bd2016-07-01 08:22:01 -07001050 SpvImageOperandsBiasMask,
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001051 this->writeExpression(*arguments[2], out),
ethannicholasb3058bd2016-07-01 08:22:01 -07001052 out);
1053 } else {
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001054 SkASSERT(arguments.size() == 2);
John Stiles270cec22021-02-17 12:59:36 -05001055 if (fProgram.fConfig->fSettings.fSharpenTextures) {
Ethan Nicholas89cfde12021-09-27 11:20:34 -04001056 Literal lodBias(/*line=*/-1, /*value=*/-0.5, fContext.fTypes.fFloat.get());
Brian Osman8a83ca42018-02-12 14:32:17 -05001057 this->writeInstruction(op, type, result, sampler, uv,
1058 SpvImageOperandsBiasMask,
John Stiles7591d4b2021-09-13 13:32:06 -04001059 this->writeLiteral(lodBias),
Brian Osman8a83ca42018-02-12 14:32:17 -05001060 out);
1061 } else {
1062 this->writeInstruction(op, type, result, sampler, uv,
1063 out);
1064 }
ethannicholasb3058bd2016-07-01 08:22:01 -07001065 }
1066 break;
1067 }
Ethan Nicholas70a44b22017-11-30 09:09:16 -05001068 case kMod_SpecialIntrinsic: {
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001069 std::vector<SpvId> args = this->vectorize(arguments, out);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001070 SkASSERT(args.size() == 2);
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001071 const Type& operandType = arguments[0]->type();
Ethan Nicholas70a44b22017-11-30 09:09:16 -05001072 SpvOp_ op;
1073 if (is_float(fContext, operandType)) {
1074 op = SpvOpFMod;
1075 } else if (is_signed(fContext, operandType)) {
1076 op = SpvOpSMod;
1077 } else if (is_unsigned(fContext, operandType)) {
1078 op = SpvOpUMod;
1079 } else {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001080 SkASSERT(false);
Ethan Nicholas70a44b22017-11-30 09:09:16 -05001081 return 0;
1082 }
1083 this->writeOpCode(op, 5, out);
1084 this->writeWord(this->getType(operandType), out);
1085 this->writeWord(result, out);
Ethan Nicholas0fc07f92018-02-27 15:25:47 -05001086 this->writeWord(args[0], out);
1087 this->writeWord(args[1], out);
1088 break;
1089 }
Chris Daltonb8af5ad2019-02-25 14:54:21 -07001090 case kDFdy_SpecialIntrinsic: {
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001091 SpvId fn = this->writeExpression(*arguments[0], out);
Chris Daltonb8af5ad2019-02-25 14:54:21 -07001092 this->writeOpCode(SpvOpDPdy, 4, out);
Ethan Nicholas30d30222020-09-11 12:27:26 -04001093 this->writeWord(this->getType(callType), out);
Chris Daltonb8af5ad2019-02-25 14:54:21 -07001094 this->writeWord(result, out);
1095 this->writeWord(fn, out);
Ethan Nicholas89cfde12021-09-27 11:20:34 -04001096 this->addRTFlipUniform(c.fLine);
Brian Salomond8d85b92021-07-07 09:41:17 -04001097 using namespace dsl;
Ethan Nicholasc8452722021-10-07 10:47:32 -04001098 DSLExpression rtFlip(ThreadContext::IRGenerator().convertIdentifier(/*line=*/-1,
1099 SKSL_RTFLIP_NAME));
Brian Salomond8d85b92021-07-07 09:41:17 -04001100 SpvId rtFlipY = this->vectorize(*rtFlip.y().release(), callType.columns(), out);
1101 SpvId flipped = this->nextId(&callType);
1102 this->writeInstruction(SpvOpFMul, this->getType(callType), flipped, result, rtFlipY,
1103 out);
1104 result = flipped;
Chris Daltonb8af5ad2019-02-25 14:54:21 -07001105 break;
1106 }
Ethan Nicholas0fc07f92018-02-27 15:25:47 -05001107 case kClamp_SpecialIntrinsic: {
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001108 std::vector<SpvId> args = this->vectorize(arguments, out);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001109 SkASSERT(args.size() == 3);
Ethan Nicholas30d30222020-09-11 12:27:26 -04001110 this->writeGLSLExtendedInstruction(callType, result, GLSLstd450FClamp, GLSLstd450SClamp,
Ethan Nicholas0fc07f92018-02-27 15:25:47 -05001111 GLSLstd450UClamp, args, out);
1112 break;
1113 }
1114 case kMax_SpecialIntrinsic: {
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001115 std::vector<SpvId> args = this->vectorize(arguments, out);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001116 SkASSERT(args.size() == 2);
Ethan Nicholas30d30222020-09-11 12:27:26 -04001117 this->writeGLSLExtendedInstruction(callType, result, GLSLstd450FMax, GLSLstd450SMax,
Ethan Nicholas0fc07f92018-02-27 15:25:47 -05001118 GLSLstd450UMax, args, out);
1119 break;
1120 }
1121 case kMin_SpecialIntrinsic: {
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001122 std::vector<SpvId> args = this->vectorize(arguments, out);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001123 SkASSERT(args.size() == 2);
Ethan Nicholas30d30222020-09-11 12:27:26 -04001124 this->writeGLSLExtendedInstruction(callType, result, GLSLstd450FMin, GLSLstd450SMin,
Ethan Nicholas0fc07f92018-02-27 15:25:47 -05001125 GLSLstd450UMin, args, out);
1126 break;
1127 }
1128 case kMix_SpecialIntrinsic: {
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001129 std::vector<SpvId> args = this->vectorize(arguments, out);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001130 SkASSERT(args.size() == 3);
John Stilescc2d9cc2021-07-09 17:38:41 -04001131 if (arguments[2]->type().componentType().isBoolean()) {
1132 // Use OpSelect to implement Boolean mix().
1133 SpvId falseId = this->writeExpression(*arguments[0], out);
1134 SpvId trueId = this->writeExpression(*arguments[1], out);
1135 SpvId conditionId = this->writeExpression(*arguments[2], out);
1136 this->writeInstruction(SpvOpSelect, this->getType(arguments[0]->type()), result,
1137 conditionId, trueId, falseId, out);
1138 } else {
1139 this->writeGLSLExtendedInstruction(callType, result, GLSLstd450FMix, SpvOpUndef,
1140 SpvOpUndef, args, out);
1141 }
Ethan Nicholas0fc07f92018-02-27 15:25:47 -05001142 break;
Ethan Nicholas70a44b22017-11-30 09:09:16 -05001143 }
Ethan Nicholas12fb9cf2018-08-03 16:16:57 -04001144 case kSaturate_SpecialIntrinsic: {
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001145 SkASSERT(arguments.size() == 1);
John Stiles8e3b6be2020-10-13 11:14:08 -04001146 ExpressionArray finalArgs;
John Stilesf4bda742020-10-14 16:57:41 -04001147 finalArgs.reserve_back(3);
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001148 finalArgs.push_back(arguments[0]->clone());
Ethan Nicholas89cfde12021-09-27 11:20:34 -04001149 finalArgs.push_back(Literal::MakeFloat(fContext, /*line=*/-1, /*value=*/0));
1150 finalArgs.push_back(Literal::MakeFloat(fContext, /*line=*/-1, /*value=*/1));
Ethan Nicholas12fb9cf2018-08-03 16:16:57 -04001151 std::vector<SpvId> spvArgs = this->vectorize(finalArgs, out);
Ethan Nicholas30d30222020-09-11 12:27:26 -04001152 this->writeGLSLExtendedInstruction(callType, result, GLSLstd450FClamp, GLSLstd450SClamp,
Ethan Nicholas12fb9cf2018-08-03 16:16:57 -04001153 GLSLstd450UClamp, spvArgs, out);
1154 break;
1155 }
Brian Osman6ba3be12020-11-13 16:32:52 -05001156 case kSmoothStep_SpecialIntrinsic: {
1157 std::vector<SpvId> args = this->vectorize(arguments, out);
1158 SkASSERT(args.size() == 3);
1159 this->writeGLSLExtendedInstruction(callType, result, GLSLstd450SmoothStep, SpvOpUndef,
1160 SpvOpUndef, args, out);
1161 break;
1162 }
1163 case kStep_SpecialIntrinsic: {
1164 std::vector<SpvId> args = this->vectorize(arguments, out);
1165 SkASSERT(args.size() == 2);
1166 this->writeGLSLExtendedInstruction(callType, result, GLSLstd450Step, SpvOpUndef,
1167 SpvOpUndef, args, out);
1168 break;
1169 }
Brian Osmand1b593f2020-12-28 13:00:46 -05001170 case kMatrixCompMult_SpecialIntrinsic: {
1171 SkASSERT(arguments.size() == 2);
1172 SpvId lhs = this->writeExpression(*arguments[0], out);
1173 SpvId rhs = this->writeExpression(*arguments[1], out);
John Stiles43b593c2021-05-13 22:03:27 -04001174 result = this->writeComponentwiseMatrixBinary(callType, lhs, rhs, SpvOpFMul, out);
Brian Osmand1b593f2020-12-28 13:00:46 -05001175 break;
1176 }
ethannicholasb3058bd2016-07-01 08:22:01 -07001177 }
1178 return result;
1179}
1180
John Stiles07367122021-09-08 13:12:26 -04001181SpvId SPIRVCodeGenerator::writeFunctionCallArgument(const Expression& arg,
1182 const Modifiers& paramModifiers,
1183 std::vector<TempVar>* tempVars,
1184 OutputStream& out) {
1185 // ID of temporary variable that we will use to hold this argument, or 0 if it is being
1186 // passed directly
1187 SpvId tmpVar;
1188 // if we need a temporary var to store this argument, this is the value to store in the var
1189 SpvId tmpValueId = -1;
1190
1191 if (is_out(paramModifiers)) {
1192 std::unique_ptr<LValue> lv = this->getLValue(arg, out);
1193 SpvId ptr = lv->getPointer();
1194 if (ptr != (SpvId) -1 && lv->isMemoryObjectPointer()) {
1195 return ptr;
1196 }
1197
1198 // lvalue cannot simply be read and written via a pointer (e.g. it's a swizzle). We need to
1199 // to use a temp variable.
1200 if (is_in(paramModifiers)) {
1201 tmpValueId = lv->load(out);
1202 }
1203 tmpVar = this->nextId(&arg.type());
1204 tempVars->push_back(TempVar{tmpVar, &arg.type(), std::move(lv)});
1205 } else {
1206 // See getFunctionType for an explanation of why we're always using pointer parameters.
1207 tmpValueId = this->writeExpression(arg, out);
1208 tmpVar = this->nextId(nullptr);
1209 }
1210 this->writeInstruction(SpvOpVariable,
1211 this->getPointerType(arg.type(), SpvStorageClassFunction),
1212 tmpVar,
1213 SpvStorageClassFunction,
1214 fVariableBuffer);
1215 if (tmpValueId != (SpvId)-1) {
1216 this->writeInstruction(SpvOpStore, tmpVar, tmpValueId, out);
1217 }
1218 return tmpVar;
1219}
1220
1221void SPIRVCodeGenerator::copyBackTempVars(const std::vector<TempVar>& tempVars, OutputStream& out) {
1222 for (const TempVar& tempVar : tempVars) {
1223 SpvId load = this->nextId(tempVar.type);
1224 this->writeInstruction(SpvOpLoad, this->getType(*tempVar.type), load, tempVar.spvId, out);
1225 tempVar.lvalue->store(load, out);
1226 }
John Stilesec241542021-02-11 17:50:09 -05001227}
1228
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001229SpvId SPIRVCodeGenerator::writeFunctionCall(const FunctionCall& c, OutputStream& out) {
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001230 const FunctionDeclaration& function = c.function();
John Stilesaaac4e42021-05-06 14:08:28 -04001231 if (function.isIntrinsic() && !function.definition()) {
John Stiles89ac7c22020-12-30 17:47:31 -05001232 return this->writeIntrinsicCall(c, out);
1233 }
John Stiles8e3b6be2020-10-13 11:14:08 -04001234 const ExpressionArray& arguments = c.arguments();
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001235 const auto& entry = fFunctionMap.find(&function);
ethannicholasb3058bd2016-07-01 08:22:01 -07001236 if (entry == fFunctionMap.end()) {
Ethan Nicholas89cfde12021-09-27 11:20:34 -04001237 fContext.fErrors->error(c.fLine, "function '" + function.description() +
1238 "' is not defined");
John Stiles89ac7c22020-12-30 17:47:31 -05001239 return -1;
ethannicholasb3058bd2016-07-01 08:22:01 -07001240 }
John Stilesec241542021-02-11 17:50:09 -05001241 // Temp variables are used to write back out-parameters after the function call is complete.
1242 std::vector<TempVar> tempVars;
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001243 std::vector<SpvId> argumentIds;
John Stiles07367122021-09-08 13:12:26 -04001244 argumentIds.reserve(arguments.size());
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001245 for (size_t i = 0; i < arguments.size(); i++) {
John Stiles07367122021-09-08 13:12:26 -04001246 argumentIds.push_back(this->writeFunctionCallArgument(*arguments[i],
1247 function.parameters()[i]->modifiers(),
1248 &tempVars,
1249 out));
ethannicholasb3058bd2016-07-01 08:22:01 -07001250 }
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001251 SpvId result = this->nextId(nullptr);
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001252 this->writeOpCode(SpvOpFunctionCall, 4 + (int32_t) arguments.size(), out);
Ethan Nicholas30d30222020-09-11 12:27:26 -04001253 this->writeWord(this->getType(c.type()), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07001254 this->writeWord(result, out);
1255 this->writeWord(entry->second, out);
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001256 for (SpvId id : argumentIds) {
ethannicholasb3058bd2016-07-01 08:22:01 -07001257 this->writeWord(id, out);
1258 }
John Stilesec241542021-02-11 17:50:09 -05001259 // Now that the call is complete, we copy temp out-variables back to their real lvalues.
John Stiles07367122021-09-08 13:12:26 -04001260 this->copyBackTempVars(tempVars, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07001261 return result;
1262}
1263
John Stiles2938eea2021-04-01 18:58:25 -04001264SpvId SPIRVCodeGenerator::writeConstantVector(const AnyConstructor& c) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001265 const Type& type = c.type();
John Stiles9aeed132020-11-24 17:36:06 -05001266 SkASSERT(type.isVector() && c.isCompileTimeConstant());
John Stilescd806892021-01-06 13:33:31 -05001267
John Stiles9cfaa4f2021-01-06 17:52:00 -05001268 // Get each of the constructor components as SPIR-V constants.
John Stilescd806892021-01-06 13:33:31 -05001269 SPIRVVectorConstant key{this->getType(type),
1270 /*fValueId=*/{SpvId(-1), SpvId(-1), SpvId(-1), SpvId(-1)}};
John Stiles9cfaa4f2021-01-06 17:52:00 -05001271
John Stiles21a50ec2021-04-06 14:49:36 -04001272 for (int n = 0; n < type.columns(); n++) {
1273 const Expression* expr = c.getConstantSubexpression(n);
1274 if (!expr) {
1275 SkDEBUGFAILF("writeConstantVector: %s not actually constant", c.description().c_str());
1276 return (SpvId)-1;
John Stiles9cfaa4f2021-01-06 17:52:00 -05001277 }
John Stiles21a50ec2021-04-06 14:49:36 -04001278 key.fValueId[n] = this->writeExpression(*expr, fConstantBuffer);
ethannicholasb3058bd2016-07-01 08:22:01 -07001279 }
John Stilescd806892021-01-06 13:33:31 -05001280
1281 // Check to see if we've already synthesized this vector constant.
1282 auto [iter, newlyCreated] = fVectorConstants.insert({key, (SpvId)-1});
1283 if (newlyCreated) {
1284 // Emit an OpConstantComposite instruction for this constant.
Ethan Nicholas7f015882021-03-23 14:16:52 -04001285 SpvId result = this->nextId(&type);
John Stiles9cfaa4f2021-01-06 17:52:00 -05001286 this->writeOpCode(SpvOpConstantComposite, 3 + type.columns(), fConstantBuffer);
John Stilescd806892021-01-06 13:33:31 -05001287 this->writeWord(key.fTypeId, fConstantBuffer);
1288 this->writeWord(result, fConstantBuffer);
John Stiles9cfaa4f2021-01-06 17:52:00 -05001289 for (int i = 0; i < type.columns(); i++) {
John Stilescd806892021-01-06 13:33:31 -05001290 this->writeWord(key.fValueId[i], fConstantBuffer);
1291 }
1292 iter->second = result;
1293 }
1294 return iter->second;
ethannicholasb3058bd2016-07-01 08:22:01 -07001295}
1296
John Stilesb14a8192021-04-05 11:40:46 -04001297SpvId SPIRVCodeGenerator::castScalarToType(SpvId inputExprId,
1298 const Type& inputType,
1299 const Type& outputType,
1300 OutputStream& out) {
1301 if (outputType.isFloat()) {
1302 return this->castScalarToFloat(inputExprId, inputType, outputType, out);
1303 }
1304 if (outputType.isSigned()) {
1305 return this->castScalarToSignedInt(inputExprId, inputType, outputType, out);
1306 }
1307 if (outputType.isUnsigned()) {
1308 return this->castScalarToUnsignedInt(inputExprId, inputType, outputType, out);
1309 }
1310 if (outputType.isBoolean()) {
1311 return this->castScalarToBoolean(inputExprId, inputType, outputType, out);
1312 }
1313
Ethan Nicholas39f6da42021-08-23 13:10:07 -04001314 fContext.fErrors->error(-1, "unsupported cast: " + inputType.description() +
Ethan Nicholas3abc6c62021-08-13 11:20:09 -04001315 " to " + outputType.description());
John Stilesb14a8192021-04-05 11:40:46 -04001316 return inputExprId;
1317}
1318
John Stilesfd7252f2021-04-04 22:24:40 -04001319SpvId SPIRVCodeGenerator::writeFloatConstructor(const AnyConstructor& c, OutputStream& out) {
1320 SkASSERT(c.argumentSpan().size() == 1);
John Stilesd9d52712021-01-13 17:15:02 -05001321 SkASSERT(c.type().isFloat());
John Stilesfd7252f2021-04-04 22:24:40 -04001322 const Expression& ctorExpr = *c.argumentSpan().front();
John Stilesd9d52712021-01-13 17:15:02 -05001323 SpvId expressionId = this->writeExpression(ctorExpr, out);
1324 return this->castScalarToFloat(expressionId, ctorExpr.type(), c.type(), out);
1325}
1326
1327SpvId SPIRVCodeGenerator::castScalarToFloat(SpvId inputId, const Type& inputType,
1328 const Type& outputType, OutputStream& out) {
1329 // Casting a float to float is a no-op.
1330 if (inputType.isFloat()) {
1331 return inputId;
1332 }
1333
1334 // Given the input type, generate the appropriate instruction to cast to float.
Ethan Nicholas7f015882021-03-23 14:16:52 -04001335 SpvId result = this->nextId(&outputType);
John Stilesd9d52712021-01-13 17:15:02 -05001336 if (inputType.isBoolean()) {
John Stilesba4b0e92021-01-05 13:55:39 -05001337 // Use OpSelect to convert the boolean argument to a literal 1.0 or 0.0.
Ethan Nicholas89cfde12021-09-27 11:20:34 -04001338 Literal one(/*line=*/-1, /*value=*/1, fContext.fTypes.fFloat.get());
John Stiles7591d4b2021-09-13 13:32:06 -04001339 const SpvId oneID = this->writeLiteral(one);
Ethan Nicholas89cfde12021-09-27 11:20:34 -04001340 Literal zero(/*line=*/-1, /*value=*/0, fContext.fTypes.fFloat.get());
John Stiles7591d4b2021-09-13 13:32:06 -04001341 const SpvId zeroID = this->writeLiteral(zero);
John Stilesd9d52712021-01-13 17:15:02 -05001342 this->writeInstruction(SpvOpSelect, this->getType(outputType), result,
1343 inputId, oneID, zeroID, out);
1344 } else if (inputType.isSigned()) {
1345 this->writeInstruction(SpvOpConvertSToF, this->getType(outputType), result, inputId, out);
1346 } else if (inputType.isUnsigned()) {
1347 this->writeInstruction(SpvOpConvertUToF, this->getType(outputType), result, inputId, out);
Ethan Nicholasf7b88202017-09-18 14:10:39 -04001348 } else {
John Stilesd9d52712021-01-13 17:15:02 -05001349 SkDEBUGFAILF("unsupported type for float typecast: %s", inputType.description().c_str());
1350 return (SpvId)-1;
ethannicholasb3058bd2016-07-01 08:22:01 -07001351 }
1352 return result;
1353}
1354
John Stilesfd7252f2021-04-04 22:24:40 -04001355SpvId SPIRVCodeGenerator::writeIntConstructor(const AnyConstructor& c, OutputStream& out) {
1356 SkASSERT(c.argumentSpan().size() == 1);
John Stilesd9d52712021-01-13 17:15:02 -05001357 SkASSERT(c.type().isSigned());
John Stilesfd7252f2021-04-04 22:24:40 -04001358 const Expression& ctorExpr = *c.argumentSpan().front();
John Stilesd9d52712021-01-13 17:15:02 -05001359 SpvId expressionId = this->writeExpression(ctorExpr, out);
1360 return this->castScalarToSignedInt(expressionId, ctorExpr.type(), c.type(), out);
1361}
1362
1363SpvId SPIRVCodeGenerator::castScalarToSignedInt(SpvId inputId, const Type& inputType,
1364 const Type& outputType, OutputStream& out) {
1365 // Casting a signed int to signed int is a no-op.
1366 if (inputType.isSigned()) {
1367 return inputId;
1368 }
1369
1370 // Given the input type, generate the appropriate instruction to cast to signed int.
Ethan Nicholas7f015882021-03-23 14:16:52 -04001371 SpvId result = this->nextId(&outputType);
John Stilesd9d52712021-01-13 17:15:02 -05001372 if (inputType.isBoolean()) {
John Stilesba4b0e92021-01-05 13:55:39 -05001373 // Use OpSelect to convert the boolean argument to a literal 1 or 0.
Ethan Nicholas89cfde12021-09-27 11:20:34 -04001374 Literal one(/*line=*/-1, /*value=*/1, fContext.fTypes.fInt.get());
John Stiles7591d4b2021-09-13 13:32:06 -04001375 const SpvId oneID = this->writeLiteral(one);
Ethan Nicholas89cfde12021-09-27 11:20:34 -04001376 Literal zero(/*line=*/-1, /*value=*/0, fContext.fTypes.fInt.get());
John Stiles7591d4b2021-09-13 13:32:06 -04001377 const SpvId zeroID = this->writeLiteral(zero);
John Stilesd9d52712021-01-13 17:15:02 -05001378 this->writeInstruction(SpvOpSelect, this->getType(outputType), result,
1379 inputId, oneID, zeroID, out);
1380 } else if (inputType.isFloat()) {
1381 this->writeInstruction(SpvOpConvertFToS, this->getType(outputType), result, inputId, out);
1382 } else if (inputType.isUnsigned()) {
1383 this->writeInstruction(SpvOpBitcast, this->getType(outputType), result, inputId, out);
1384 } else {
1385 SkDEBUGFAILF("unsupported type for signed int typecast: %s",
1386 inputType.description().c_str());
1387 return (SpvId)-1;
ethannicholasb3058bd2016-07-01 08:22:01 -07001388 }
1389 return result;
1390}
1391
John Stilesfd7252f2021-04-04 22:24:40 -04001392SpvId SPIRVCodeGenerator::writeUIntConstructor(const AnyConstructor& c, OutputStream& out) {
1393 SkASSERT(c.argumentSpan().size() == 1);
John Stilesd9d52712021-01-13 17:15:02 -05001394 SkASSERT(c.type().isUnsigned());
John Stilesfd7252f2021-04-04 22:24:40 -04001395 const Expression& ctorExpr = *c.argumentSpan().front();
John Stilesd9d52712021-01-13 17:15:02 -05001396 SpvId expressionId = this->writeExpression(ctorExpr, out);
1397 return this->castScalarToUnsignedInt(expressionId, ctorExpr.type(), c.type(), out);
1398}
1399
1400SpvId SPIRVCodeGenerator::castScalarToUnsignedInt(SpvId inputId, const Type& inputType,
1401 const Type& outputType, OutputStream& out) {
1402 // Casting an unsigned int to unsigned int is a no-op.
1403 if (inputType.isUnsigned()) {
1404 return inputId;
1405 }
1406
John Stiles48c28842021-01-14 11:05:03 -05001407 // Given the input type, generate the appropriate instruction to cast to unsigned int.
Ethan Nicholas7f015882021-03-23 14:16:52 -04001408 SpvId result = this->nextId(&outputType);
John Stilesd9d52712021-01-13 17:15:02 -05001409 if (inputType.isBoolean()) {
John Stilesba4b0e92021-01-05 13:55:39 -05001410 // Use OpSelect to convert the boolean argument to a literal 1u or 0u.
Ethan Nicholas89cfde12021-09-27 11:20:34 -04001411 Literal one(/*line=*/-1, /*value=*/1, fContext.fTypes.fUInt.get());
John Stiles7591d4b2021-09-13 13:32:06 -04001412 const SpvId oneID = this->writeLiteral(one);
Ethan Nicholas89cfde12021-09-27 11:20:34 -04001413 Literal zero(/*line=*/-1, /*value=*/0, fContext.fTypes.fUInt.get());
John Stiles7591d4b2021-09-13 13:32:06 -04001414 const SpvId zeroID = this->writeLiteral(zero);
John Stilesd9d52712021-01-13 17:15:02 -05001415 this->writeInstruction(SpvOpSelect, this->getType(outputType), result,
1416 inputId, oneID, zeroID, out);
1417 } else if (inputType.isFloat()) {
1418 this->writeInstruction(SpvOpConvertFToU, this->getType(outputType), result, inputId, out);
1419 } else if (inputType.isSigned()) {
1420 this->writeInstruction(SpvOpBitcast, this->getType(outputType), result, inputId, out);
Ethan Nicholasf7b88202017-09-18 14:10:39 -04001421 } else {
John Stilesd9d52712021-01-13 17:15:02 -05001422 SkDEBUGFAILF("unsupported type for unsigned int typecast: %s",
1423 inputType.description().c_str());
1424 return (SpvId)-1;
Ethan Nicholas925f52d2017-07-19 10:42:50 -04001425 }
1426 return result;
1427}
1428
John Stilesfd7252f2021-04-04 22:24:40 -04001429SpvId SPIRVCodeGenerator::writeBooleanConstructor(const AnyConstructor& c, OutputStream& out) {
1430 SkASSERT(c.argumentSpan().size() == 1);
John Stilesa60fb172021-01-14 11:06:20 -05001431 SkASSERT(c.type().isBoolean());
John Stilesfd7252f2021-04-04 22:24:40 -04001432 const Expression& ctorExpr = *c.argumentSpan().front();
John Stilesa60fb172021-01-14 11:06:20 -05001433 SpvId expressionId = this->writeExpression(ctorExpr, out);
1434 return this->castScalarToBoolean(expressionId, ctorExpr.type(), c.type(), out);
1435}
1436
John Stiles48c28842021-01-14 11:05:03 -05001437SpvId SPIRVCodeGenerator::castScalarToBoolean(SpvId inputId, const Type& inputType,
1438 const Type& outputType, OutputStream& out) {
1439 // Casting a bool to bool is a no-op.
1440 if (inputType.isBoolean()) {
1441 return inputId;
1442 }
1443
1444 // Given the input type, generate the appropriate instruction to cast to bool.
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001445 SpvId result = this->nextId(nullptr);
John Stiles48c28842021-01-14 11:05:03 -05001446 if (inputType.isSigned()) {
1447 // Synthesize a boolean result by comparing the input against a signed zero literal.
Ethan Nicholas89cfde12021-09-27 11:20:34 -04001448 Literal zero(/*line=*/-1, /*value=*/0, fContext.fTypes.fInt.get());
John Stiles7591d4b2021-09-13 13:32:06 -04001449 const SpvId zeroID = this->writeLiteral(zero);
John Stiles48c28842021-01-14 11:05:03 -05001450 this->writeInstruction(SpvOpINotEqual, this->getType(outputType), result,
1451 inputId, zeroID, out);
1452 } else if (inputType.isUnsigned()) {
1453 // Synthesize a boolean result by comparing the input against an unsigned zero literal.
Ethan Nicholas89cfde12021-09-27 11:20:34 -04001454 Literal zero(/*line=*/-1, /*value=*/0, fContext.fTypes.fUInt.get());
John Stiles7591d4b2021-09-13 13:32:06 -04001455 const SpvId zeroID = this->writeLiteral(zero);
John Stiles48c28842021-01-14 11:05:03 -05001456 this->writeInstruction(SpvOpINotEqual, this->getType(outputType), result,
1457 inputId, zeroID, out);
1458 } else if (inputType.isFloat()) {
1459 // Synthesize a boolean result by comparing the input against a floating-point zero literal.
Ethan Nicholas89cfde12021-09-27 11:20:34 -04001460 Literal zero(/*line=*/-1, /*value=*/0, fContext.fTypes.fFloat.get());
John Stiles7591d4b2021-09-13 13:32:06 -04001461 const SpvId zeroID = this->writeLiteral(zero);
John Stiles48c28842021-01-14 11:05:03 -05001462 this->writeInstruction(SpvOpFUnordNotEqual, this->getType(outputType), result,
1463 inputId, zeroID, out);
1464 } else {
1465 SkDEBUGFAILF("unsupported type for boolean typecast: %s", inputType.description().c_str());
1466 return (SpvId)-1;
1467 }
1468 return result;
1469}
1470
Ethan Nicholas84645e32017-02-09 13:57:14 -05001471void SPIRVCodeGenerator::writeUniformScaleMatrix(SpvId id, SpvId diagonal, const Type& type,
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001472 OutputStream& out) {
Ethan Nicholas89cfde12021-09-27 11:20:34 -04001473 Literal zero(/*line=*/-1, /*value=*/0, fContext.fTypes.fFloat.get());
John Stiles7591d4b2021-09-13 13:32:06 -04001474 SpvId zeroId = this->writeLiteral(zero);
Ethan Nicholas84645e32017-02-09 13:57:14 -05001475 std::vector<SpvId> columnIds;
John Stiles392d8292021-04-09 12:14:03 -04001476 columnIds.reserve(type.columns());
Ethan Nicholas84645e32017-02-09 13:57:14 -05001477 for (int column = 0; column < type.columns(); column++) {
1478 this->writeOpCode(SpvOpCompositeConstruct, 3 + type.rows(),
1479 out);
John Stiles392d8292021-04-09 12:14:03 -04001480 this->writeWord(this->getType(type.componentType().toCompound(
1481 fContext, /*columns=*/type.rows(), /*rows=*/1)),
Ethan Nicholas84645e32017-02-09 13:57:14 -05001482 out);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001483 SpvId columnId = this->nextId(&type);
Ethan Nicholas84645e32017-02-09 13:57:14 -05001484 this->writeWord(columnId, out);
1485 columnIds.push_back(columnId);
John Stiles392d8292021-04-09 12:14:03 -04001486 for (int row = 0; row < type.rows(); row++) {
Ethan Nicholas84645e32017-02-09 13:57:14 -05001487 this->writeWord(row == column ? diagonal : zeroId, out);
1488 }
1489 }
1490 this->writeOpCode(SpvOpCompositeConstruct, 3 + type.columns(),
1491 out);
1492 this->writeWord(this->getType(type), out);
1493 this->writeWord(id, out);
John Stilesf621e232020-08-25 13:33:02 -04001494 for (SpvId columnId : columnIds) {
1495 this->writeWord(columnId, out);
Ethan Nicholas84645e32017-02-09 13:57:14 -05001496 }
1497}
1498
John Stiles268a73f2021-04-07 12:30:22 -04001499SpvId SPIRVCodeGenerator::writeMatrixCopy(SpvId src, const Type& srcType, const Type& dstType,
1500 OutputStream& out) {
John Stiles9aeed132020-11-24 17:36:06 -05001501 SkASSERT(srcType.isMatrix());
1502 SkASSERT(dstType.isMatrix());
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001503 SkASSERT(srcType.componentType() == dstType.componentType());
John Stiles268a73f2021-04-07 12:30:22 -04001504 SpvId id = this->nextId(&dstType);
Ethan Nicholasdc0e1c32017-07-21 13:23:34 -04001505 SpvId srcColumnType = this->getType(srcType.componentType().toCompound(fContext,
1506 srcType.rows(),
1507 1));
1508 SpvId dstColumnType = this->getType(dstType.componentType().toCompound(fContext,
1509 dstType.rows(),
1510 1));
John Stiles92671832021-04-06 09:24:55 -04001511 SkASSERT(dstType.componentType().isFloat());
Ethan Nicholas89cfde12021-09-27 11:20:34 -04001512 Literal zero(/*line=*/-1, /*value=*/0.0, &dstType.componentType());
John Stiles7591d4b2021-09-13 13:32:06 -04001513 const SpvId zeroId = this->writeLiteral(zero);
Ethan Nicholas89cfde12021-09-27 11:20:34 -04001514 Literal one(/*line=*/-1, /*value=*/1.0, &dstType.componentType());
John Stiles7591d4b2021-09-13 13:32:06 -04001515 const SpvId oneId = this->writeLiteral(one);
John Stiles92671832021-04-06 09:24:55 -04001516
Ethan Nicholasdc0e1c32017-07-21 13:23:34 -04001517 SpvId columns[4];
1518 for (int i = 0; i < dstType.columns(); i++) {
1519 if (i < srcType.columns()) {
1520 // we're still inside the src matrix, copy the column
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001521 SpvId srcColumn = this->nextId(&dstType);
Ethan Nicholasdc0e1c32017-07-21 13:23:34 -04001522 this->writeInstruction(SpvOpCompositeExtract, srcColumnType, srcColumn, src, i, out);
1523 SpvId dstColumn;
1524 if (srcType.rows() == dstType.rows()) {
1525 // columns are equal size, don't need to do anything
1526 dstColumn = srcColumn;
1527 }
1528 else if (dstType.rows() > srcType.rows()) {
1529 // dst column is bigger, need to zero-pad it
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001530 dstColumn = this->nextId(&dstType);
Ethan Nicholasdc0e1c32017-07-21 13:23:34 -04001531 int delta = dstType.rows() - srcType.rows();
1532 this->writeOpCode(SpvOpCompositeConstruct, 4 + delta, out);
1533 this->writeWord(dstColumnType, out);
1534 this->writeWord(dstColumn, out);
1535 this->writeWord(srcColumn, out);
John Stiles92671832021-04-06 09:24:55 -04001536 for (int j = srcType.rows(); j < dstType.rows(); ++j) {
1537 this->writeWord((i == j) ? oneId : zeroId, out);
Ethan Nicholasdc0e1c32017-07-21 13:23:34 -04001538 }
1539 }
1540 else {
1541 // dst column is smaller, need to swizzle the src column
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001542 dstColumn = this->nextId(&dstType);
John Stiles92671832021-04-06 09:24:55 -04001543 this->writeOpCode(SpvOpVectorShuffle, 5 + dstType.rows(), out);
Ethan Nicholasdc0e1c32017-07-21 13:23:34 -04001544 this->writeWord(dstColumnType, out);
1545 this->writeWord(dstColumn, out);
1546 this->writeWord(srcColumn, out);
1547 this->writeWord(srcColumn, out);
John Stiles92671832021-04-06 09:24:55 -04001548 for (int j = 0; j < dstType.rows(); j++) {
John Stilesf621e232020-08-25 13:33:02 -04001549 this->writeWord(j, out);
Ethan Nicholasdc0e1c32017-07-21 13:23:34 -04001550 }
1551 }
1552 columns[i] = dstColumn;
1553 } else {
John Stiles92671832021-04-06 09:24:55 -04001554 // we're past the end of the src matrix, need to synthesize an identity-matrix column
1555 SpvId identityColumn = this->nextId(&dstType);
1556 this->writeOpCode(SpvOpCompositeConstruct, 3 + dstType.rows(), out);
1557 this->writeWord(dstColumnType, out);
1558 this->writeWord(identityColumn, out);
1559 for (int j = 0; j < dstType.rows(); ++j) {
1560 this->writeWord((i == j) ? oneId : zeroId, out);
Ethan Nicholasdc0e1c32017-07-21 13:23:34 -04001561 }
John Stiles92671832021-04-06 09:24:55 -04001562 columns[i] = identityColumn;
Ethan Nicholasdc0e1c32017-07-21 13:23:34 -04001563 }
1564 }
1565 this->writeOpCode(SpvOpCompositeConstruct, 3 + dstType.columns(), out);
1566 this->writeWord(this->getType(dstType), out);
1567 this->writeWord(id, out);
1568 for (int i = 0; i < dstType.columns(); i++) {
1569 this->writeWord(columns[i], out);
1570 }
John Stiles268a73f2021-04-07 12:30:22 -04001571 return id;
Ethan Nicholas84645e32017-02-09 13:57:14 -05001572}
1573
John Stilesbeb2fbf2021-07-08 18:54:39 -04001574void SPIRVCodeGenerator::addColumnEntry(const Type& columnType,
Ethan Nicholascc5d3e02019-04-19 09:50:56 -04001575 std::vector<SpvId>* currentColumn,
Ethan Nicholas5c46b722019-03-22 14:32:37 -04001576 std::vector<SpvId>* columnIds,
John Stilesbeb2fbf2021-07-08 18:54:39 -04001577 int rows,
1578 SpvId entry,
Ethan Nicholas5c46b722019-03-22 14:32:37 -04001579 OutputStream& out) {
John Stilesbeb2fbf2021-07-08 18:54:39 -04001580 SkASSERT((int)currentColumn->size() < rows);
Ethan Nicholas5c46b722019-03-22 14:32:37 -04001581 currentColumn->push_back(entry);
John Stilesbeb2fbf2021-07-08 18:54:39 -04001582 if ((int)currentColumn->size() == rows) {
1583 // Synthesize this column into a vector.
1584 SpvId columnId = this->writeComposite(*currentColumn, columnType, out);
Ethan Nicholas5c46b722019-03-22 14:32:37 -04001585 columnIds->push_back(columnId);
Ethan Nicholas5c46b722019-03-22 14:32:37 -04001586 currentColumn->clear();
1587 }
1588}
1589
John Stiles8cad6372021-04-07 12:31:13 -04001590SpvId SPIRVCodeGenerator::writeMatrixConstructor(const ConstructorCompound& c, OutputStream& out) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001591 const Type& type = c.type();
John Stiles9aeed132020-11-24 17:36:06 -05001592 SkASSERT(type.isMatrix());
John Stiles2bec8ab2021-04-06 18:40:04 -04001593 SkASSERT(!c.arguments().empty());
Ethan Nicholasf70f0442020-09-29 12:41:35 -04001594 const Type& arg0Type = c.arguments()[0]->type();
ethannicholasb3058bd2016-07-01 08:22:01 -07001595 // go ahead and write the arguments so we don't try to write new instructions in the middle of
1596 // an instruction
1597 std::vector<SpvId> arguments;
John Stiles2bec8ab2021-04-06 18:40:04 -04001598 arguments.reserve(c.arguments().size());
1599 for (const std::unique_ptr<Expression>& arg : c.arguments()) {
1600 arguments.push_back(this->writeExpression(*arg, out));
ethannicholasb3058bd2016-07-01 08:22:01 -07001601 }
John Stilesbeb2fbf2021-07-08 18:54:39 -04001602
John Stiles268a73f2021-04-07 12:30:22 -04001603 if (arguments.size() == 1 && arg0Type.isVector()) {
1604 // Special-case handling of float4 -> mat2x2.
Ethan Nicholas30d30222020-09-11 12:27:26 -04001605 SkASSERT(type.rows() == 2 && type.columns() == 2);
1606 SkASSERT(arg0Type.columns() == 4);
1607 SpvId componentType = this->getType(type.componentType());
Ethan Nicholasdc0e1c32017-07-21 13:23:34 -04001608 SpvId v[4];
1609 for (int i = 0; i < 4; ++i) {
Ethan Nicholas7f015882021-03-23 14:16:52 -04001610 v[i] = this->nextId(&type);
Ethan Nicholas30d30222020-09-11 12:27:26 -04001611 this->writeInstruction(SpvOpCompositeExtract, componentType, v[i], arguments[0], i,
1612 out);
Ethan Nicholasdc0e1c32017-07-21 13:23:34 -04001613 }
John Stilesbeb2fbf2021-07-08 18:54:39 -04001614 const Type& vecType = type.componentType().toCompound(fContext, /*columns=*/2, /*rows=*/1);
1615 SpvId v0v1 = this->writeComposite({v[0], v[1]}, vecType, out);
1616 SpvId v2v3 = this->writeComposite({v[2], v[3]}, vecType, out);
1617 return this->writeComposite({v0v1, v2v3}, type, out);
1618 }
1619
1620 int rows = type.rows();
1621 const Type& columnType = type.componentType().toCompound(fContext,
1622 /*columns=*/rows, /*rows=*/1);
1623 // SpvIds of completed columns of the matrix.
1624 std::vector<SpvId> columnIds;
1625 // SpvIds of scalars we have written to the current column so far.
1626 std::vector<SpvId> currentColumn;
1627 for (size_t i = 0; i < arguments.size(); i++) {
1628 const Type& argType = c.arguments()[i]->type();
1629 if (currentColumn.empty() && argType.isVector() && argType.columns() == rows) {
1630 // This vector is a complete matrix column by itself and can be used as-is.
1631 columnIds.push_back(arguments[i]);
1632 } else if (argType.columns() == 1) {
1633 // This argument is a lone scalar and can be added to the current column as-is.
1634 this->addColumnEntry(columnType, &currentColumn, &columnIds, rows, arguments[i], out);
1635 } else {
1636 // This argument needs to be decomposed into its constituent scalars.
1637 SpvId componentType = this->getType(argType.componentType());
1638 for (int j = 0; j < argType.columns(); ++j) {
1639 SpvId swizzle = this->nextId(&argType);
1640 this->writeInstruction(SpvOpCompositeExtract, componentType, swizzle,
1641 arguments[i], j, out);
1642 this->addColumnEntry(columnType, &currentColumn, &columnIds, rows, swizzle, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07001643 }
1644 }
ethannicholasb3058bd2016-07-01 08:22:01 -07001645 }
John Stilesbeb2fbf2021-07-08 18:54:39 -04001646 SkASSERT(columnIds.size() == (size_t) type.columns());
1647 return this->writeComposite(columnIds, type, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07001648}
1649
John Stiles8cad6372021-04-07 12:31:13 -04001650SpvId SPIRVCodeGenerator::writeConstructorCompound(const ConstructorCompound& c,
1651 OutputStream& out) {
John Stiles2bec8ab2021-04-06 18:40:04 -04001652 return c.type().isMatrix() ? this->writeMatrixConstructor(c, out)
1653 : this->writeVectorConstructor(c, out);
1654}
1655
John Stiles8cad6372021-04-07 12:31:13 -04001656SpvId SPIRVCodeGenerator::writeVectorConstructor(const ConstructorCompound& c, OutputStream& out) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001657 const Type& type = c.type();
John Stilesd986f472021-04-06 15:54:43 -04001658 const Type& componentType = type.componentType();
John Stiles9aeed132020-11-24 17:36:06 -05001659 SkASSERT(type.isVector());
John Stilesd986f472021-04-06 15:54:43 -04001660
1661 if (c.isCompileTimeConstant()) {
ethannicholasb3058bd2016-07-01 08:22:01 -07001662 return this->writeConstantVector(c);
1663 }
John Stilesd986f472021-04-06 15:54:43 -04001664
ethannicholasb3058bd2016-07-01 08:22:01 -07001665 std::vector<SpvId> arguments;
John Stiles6de2e1d2021-07-09 12:41:55 -04001666 arguments.reserve(c.arguments().size());
Ethan Nicholasf70f0442020-09-29 12:41:35 -04001667 for (size_t i = 0; i < c.arguments().size(); i++) {
1668 const Type& argType = c.arguments()[i]->type();
John Stilesd986f472021-04-06 15:54:43 -04001669 SkASSERT(componentType == argType.componentType());
John Stiles48c28842021-01-14 11:05:03 -05001670
John Stiles6de2e1d2021-07-09 12:41:55 -04001671 SpvId arg = this->writeExpression(*c.arguments()[i], out);
1672 if (argType.isMatrix()) {
1673 // CompositeConstruct cannot take a 2x2 matrix as an input, so we need to extract out
1674 // each scalar separately.
1675 SkASSERT(argType.rows() == 2);
1676 SkASSERT(argType.columns() == 2);
1677 for (int j = 0; j < 4; ++j) {
1678 SpvId componentId = this->nextId(&componentType);
1679 this->writeInstruction(SpvOpCompositeExtract, this->getType(componentType),
1680 componentId, arg, j / 2, j % 2, out);
1681 arguments.push_back(componentId);
1682 }
1683 } else if (argType.isVector()) {
John Stilesd986f472021-04-06 15:54:43 -04001684 // There's a bug in the Intel Vulkan driver where OpCompositeConstruct doesn't handle
1685 // vector arguments at all, so we always extract each vector component and pass them
1686 // into OpCompositeConstruct individually.
Ethan Nicholas30d30222020-09-11 12:27:26 -04001687 for (int j = 0; j < argType.columns(); j++) {
John Stilesd986f472021-04-06 15:54:43 -04001688 SpvId componentId = this->nextId(&componentType);
1689 this->writeInstruction(SpvOpCompositeExtract, this->getType(componentType),
John Stiles6de2e1d2021-07-09 12:41:55 -04001690 componentId, arg, j, out);
John Stilesd986f472021-04-06 15:54:43 -04001691 arguments.push_back(componentId);
Ethan Nicholas26a8d902018-01-29 09:25:51 -05001692 }
Ethan Nicholas11e5bff2018-01-29 11:08:38 -05001693 } else {
John Stiles6de2e1d2021-07-09 12:41:55 -04001694 arguments.push_back(arg);
Ethan Nicholas26a8d902018-01-29 09:25:51 -05001695 }
ethannicholasb3058bd2016-07-01 08:22:01 -07001696 }
John Stilesb14a8192021-04-05 11:40:46 -04001697
1698 return this->writeComposite(arguments, type, out);
1699}
1700
1701SpvId SPIRVCodeGenerator::writeComposite(const std::vector<SpvId>& arguments,
1702 const Type& type,
1703 OutputStream& out) {
John Stilesd47330f2021-04-08 23:25:52 -04001704 SkASSERT(arguments.size() == (type.isStruct() ? type.fields().size() : (size_t)type.columns()));
John Stiles2938eea2021-04-01 18:58:25 -04001705
Ethan Nicholas7f015882021-03-23 14:16:52 -04001706 SpvId result = this->nextId(&type);
John Stiles2938eea2021-04-01 18:58:25 -04001707 this->writeOpCode(SpvOpCompositeConstruct, 3 + (int32_t) arguments.size(), out);
1708 this->writeWord(this->getType(type), out);
1709 this->writeWord(result, out);
1710 for (SpvId id : arguments) {
1711 this->writeWord(id, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07001712 }
1713 return result;
1714}
1715
John Stiles2938eea2021-04-01 18:58:25 -04001716SpvId SPIRVCodeGenerator::writeConstructorSplat(const ConstructorSplat& c, OutputStream& out) {
1717 // Use writeConstantVector to deduplicate constant splats.
1718 if (c.isCompileTimeConstant()) {
1719 return this->writeConstantVector(c);
1720 }
1721
1722 // Write the splat argument.
1723 SpvId argument = this->writeExpression(*c.argument(), out);
1724
1725 // Generate a OpCompositeConstruct which repeats the argument N times.
John Stilesb14a8192021-04-05 11:40:46 -04001726 std::vector<SpvId> arguments(/*count*/ c.type().columns(), /*value*/ argument);
1727 return this->writeComposite(arguments, c.type(), out);
John Stiles2938eea2021-04-01 18:58:25 -04001728}
1729
1730
John Stilesd47330f2021-04-08 23:25:52 -04001731SpvId SPIRVCodeGenerator::writeCompositeConstructor(const AnyConstructor& c, OutputStream& out) {
1732 SkASSERT(c.type().isArray() || c.type().isStruct());
1733 auto ctorArgs = c.argumentSpan();
1734
Ethan Nicholasbd553222017-07-18 15:54:59 -04001735 std::vector<SpvId> arguments;
John Stilesd47330f2021-04-08 23:25:52 -04001736 arguments.reserve(ctorArgs.size());
1737 for (const std::unique_ptr<Expression>& arg : ctorArgs) {
1738 arguments.push_back(this->writeExpression(*arg, out));
Ethan Nicholasbd553222017-07-18 15:54:59 -04001739 }
John Stilesd47330f2021-04-08 23:25:52 -04001740
1741 return this->writeComposite(arguments, c.type(), out);
Ethan Nicholasbd553222017-07-18 15:54:59 -04001742}
1743
John Stilesfd7252f2021-04-04 22:24:40 -04001744SpvId SPIRVCodeGenerator::writeConstructorScalarCast(const ConstructorScalarCast& c,
1745 OutputStream& out) {
1746 const Type& type = c.type();
1747 if (this->getActualType(type) == this->getActualType(c.argument()->type())) {
1748 return this->writeExpression(*c.argument(), out);
1749 }
John Stilesb14a8192021-04-05 11:40:46 -04001750
1751 const Expression& ctorExpr = *c.argument();
1752 SpvId expressionId = this->writeExpression(ctorExpr, out);
1753 return this->castScalarToType(expressionId, ctorExpr.type(), type, out);
1754}
1755
John Stiles8cad6372021-04-07 12:31:13 -04001756SpvId SPIRVCodeGenerator::writeConstructorCompoundCast(const ConstructorCompoundCast& c,
1757 OutputStream& out) {
John Stilesb14a8192021-04-05 11:40:46 -04001758 const Type& ctorType = c.type();
1759 const Type& argType = c.argument()->type();
John Stiles268a73f2021-04-07 12:30:22 -04001760 SkASSERT(ctorType.isVector() || ctorType.isMatrix());
John Stilesb14a8192021-04-05 11:40:46 -04001761
John Stiles268a73f2021-04-07 12:30:22 -04001762 // Write the composite that we are casting. If the actual type matches, we are done.
1763 SpvId compositeId = this->writeExpression(*c.argument(), out);
John Stilesb14a8192021-04-05 11:40:46 -04001764 if (this->getActualType(ctorType) == this->getActualType(argType)) {
John Stiles268a73f2021-04-07 12:30:22 -04001765 return compositeId;
1766 }
1767
1768 // writeMatrixCopy can cast matrices to a different type.
1769 if (ctorType.isMatrix()) {
1770 return this->writeMatrixCopy(compositeId, argType, ctorType, out);
John Stilesfd7252f2021-04-04 22:24:40 -04001771 }
John Stilesb14a8192021-04-05 11:40:46 -04001772
1773 // SPIR-V doesn't support vector(vector-of-different-type) directly, so we need to extract the
John Stilesd986f472021-04-06 15:54:43 -04001774 // components and convert each one manually.
John Stilesb14a8192021-04-05 11:40:46 -04001775 const Type& srcType = argType.componentType();
1776 const Type& dstType = ctorType.componentType();
1777
1778 std::vector<SpvId> arguments;
John Stiles268a73f2021-04-07 12:30:22 -04001779 arguments.reserve(argType.columns());
John Stilesb14a8192021-04-05 11:40:46 -04001780 for (int index = 0; index < argType.columns(); ++index) {
1781 SpvId componentId = this->nextId(&srcType);
1782 this->writeInstruction(SpvOpCompositeExtract, this->getType(srcType), componentId,
John Stiles268a73f2021-04-07 12:30:22 -04001783 compositeId, index, out);
John Stilesb14a8192021-04-05 11:40:46 -04001784 arguments.push_back(this->castScalarToType(componentId, srcType, dstType, out));
John Stilesfd7252f2021-04-04 22:24:40 -04001785 }
John Stilesb14a8192021-04-05 11:40:46 -04001786
1787 return this->writeComposite(arguments, ctorType, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07001788}
1789
John Stilese1182782021-03-30 22:09:37 -04001790SpvId SPIRVCodeGenerator::writeConstructorDiagonalMatrix(const ConstructorDiagonalMatrix& c,
1791 OutputStream& out) {
1792 const Type& type = c.type();
1793 SkASSERT(type.isMatrix());
1794 SkASSERT(c.argument()->type().isScalar());
1795
1796 // Write out the scalar argument.
1797 SpvId argument = this->writeExpression(*c.argument(), out);
1798
1799 // Build the diagonal matrix.
1800 SpvId result = this->nextId(&type);
1801 this->writeUniformScaleMatrix(result, argument, type, out);
1802 return result;
1803}
1804
John Stiles5abb9e12021-04-06 13:47:19 -04001805SpvId SPIRVCodeGenerator::writeConstructorMatrixResize(const ConstructorMatrixResize& c,
1806 OutputStream& out) {
1807 // Write the input matrix.
1808 SpvId argument = this->writeExpression(*c.argument(), out);
1809
1810 // Use matrix-copy to resize the input matrix to its new size.
John Stiles268a73f2021-04-07 12:30:22 -04001811 return this->writeMatrixCopy(argument, c.argument()->type(), c.type(), out);
John Stiles5abb9e12021-04-06 13:47:19 -04001812}
1813
John Stiles9485b552021-01-27 11:47:00 -05001814static SpvStorageClass_ get_storage_class(const Variable& var,
1815 SpvStorageClass_ fallbackStorageClass) {
1816 const Modifiers& modifiers = var.modifiers();
ethannicholasb3058bd2016-07-01 08:22:01 -07001817 if (modifiers.fFlags & Modifiers::kIn_Flag) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001818 SkASSERT(!(modifiers.fLayout.fFlags & Layout::kPushConstant_Flag));
ethannicholasb3058bd2016-07-01 08:22:01 -07001819 return SpvStorageClassInput;
John Stiles9485b552021-01-27 11:47:00 -05001820 }
1821 if (modifiers.fFlags & Modifiers::kOut_Flag) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001822 SkASSERT(!(modifiers.fLayout.fFlags & Layout::kPushConstant_Flag));
ethannicholasb3058bd2016-07-01 08:22:01 -07001823 return SpvStorageClassOutput;
John Stiles9485b552021-01-27 11:47:00 -05001824 }
1825 if (modifiers.fFlags & Modifiers::kUniform_Flag) {
Ethan Nicholas39204fd2017-11-27 13:12:30 -05001826 if (modifiers.fLayout.fFlags & Layout::kPushConstant_Flag) {
ethannicholas8ac838d2016-11-22 08:39:36 -08001827 return SpvStorageClassPushConstant;
1828 }
John Stiles9485b552021-01-27 11:47:00 -05001829 if (var.type().typeKind() == Type::TypeKind::kSampler ||
1830 var.type().typeKind() == Type::TypeKind::kSeparateSampler ||
1831 var.type().typeKind() == Type::TypeKind::kTexture) {
1832 return SpvStorageClassUniformConstant;
1833 }
ethannicholasb3058bd2016-07-01 08:22:01 -07001834 return SpvStorageClassUniform;
ethannicholasb3058bd2016-07-01 08:22:01 -07001835 }
John Stiles9485b552021-01-27 11:47:00 -05001836 return fallbackStorageClass;
ethannicholasb3058bd2016-07-01 08:22:01 -07001837}
1838
John Stiles9485b552021-01-27 11:47:00 -05001839static SpvStorageClass_ get_storage_class(const Expression& expr) {
Ethan Nicholase6592142020-09-08 10:22:09 -04001840 switch (expr.kind()) {
1841 case Expression::Kind::kVariableReference: {
Ethan Nicholas78686922020-10-08 06:46:27 -04001842 const Variable& var = *expr.as<VariableReference>().variable();
Ethan Nicholas453f67f2020-10-09 10:43:45 -04001843 if (var.storage() != Variable::Storage::kGlobal) {
Ethan Nicholasc6f5e102017-03-31 14:53:17 -04001844 return SpvStorageClassFunction;
1845 }
John Stiles9485b552021-01-27 11:47:00 -05001846 return get_storage_class(var, SpvStorageClassPrivate);
Ethan Nicholasc6f5e102017-03-31 14:53:17 -04001847 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001848 case Expression::Kind::kFieldAccess:
Ethan Nicholas7a95b202020-10-09 11:55:40 -04001849 return get_storage_class(*expr.as<FieldAccess>().base());
Ethan Nicholase6592142020-09-08 10:22:09 -04001850 case Expression::Kind::kIndex:
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04001851 return get_storage_class(*expr.as<IndexExpression>().base());
ethannicholasb3058bd2016-07-01 08:22:01 -07001852 default:
1853 return SpvStorageClassFunction;
1854 }
1855}
1856
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001857std::vector<SpvId> SPIRVCodeGenerator::getAccessChain(const Expression& expr, OutputStream& out) {
ethannicholasb3058bd2016-07-01 08:22:01 -07001858 std::vector<SpvId> chain;
Ethan Nicholase6592142020-09-08 10:22:09 -04001859 switch (expr.kind()) {
1860 case Expression::Kind::kIndex: {
John Stiles0693fb82021-01-22 18:27:52 -05001861 const IndexExpression& indexExpr = expr.as<IndexExpression>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04001862 chain = this->getAccessChain(*indexExpr.base(), out);
1863 chain.push_back(this->writeExpression(*indexExpr.index(), out));
ethannicholasb3058bd2016-07-01 08:22:01 -07001864 break;
1865 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001866 case Expression::Kind::kFieldAccess: {
John Stiles0693fb82021-01-22 18:27:52 -05001867 const FieldAccess& fieldExpr = expr.as<FieldAccess>();
Ethan Nicholas7a95b202020-10-09 11:55:40 -04001868 chain = this->getAccessChain(*fieldExpr.base(), out);
Ethan Nicholas89cfde12021-09-27 11:20:34 -04001869 Literal index(/*line=*/-1, fieldExpr.fieldIndex(), fContext.fTypes.fInt.get());
John Stiles7591d4b2021-09-13 13:32:06 -04001870 chain.push_back(this->writeLiteral(index));
ethannicholasb3058bd2016-07-01 08:22:01 -07001871 break;
1872 }
Ethan Nicholasa9a06902019-01-07 14:42:40 -05001873 default: {
1874 SpvId id = this->getLValue(expr, out)->getPointer();
John Stiles3f14d282021-02-05 09:31:04 -05001875 SkASSERT(id != (SpvId) -1);
Ethan Nicholasa9a06902019-01-07 14:42:40 -05001876 chain.push_back(id);
Ethan Nicholasb13f3692021-09-10 16:49:42 -04001877 break;
Ethan Nicholasa9a06902019-01-07 14:42:40 -05001878 }
ethannicholasb3058bd2016-07-01 08:22:01 -07001879 }
1880 return chain;
1881}
1882
1883class PointerLValue : public SPIRVCodeGenerator::LValue {
1884public:
Ethan Nicholase0707b72021-03-17 11:16:41 -04001885 PointerLValue(SPIRVCodeGenerator& gen, SpvId pointer, bool isMemoryObject, SpvId type,
Ethan Nicholas10e93b62019-03-20 10:46:14 -04001886 SPIRVCodeGenerator::Precision precision)
ethannicholasb3058bd2016-07-01 08:22:01 -07001887 : fGen(gen)
1888 , fPointer(pointer)
Ethan Nicholase0707b72021-03-17 11:16:41 -04001889 , fIsMemoryObject(isMemoryObject)
Ethan Nicholas10e93b62019-03-20 10:46:14 -04001890 , fType(type)
1891 , fPrecision(precision) {}
ethannicholasb3058bd2016-07-01 08:22:01 -07001892
John Stiles1cf2c8d2020-08-13 22:58:04 -04001893 SpvId getPointer() override {
ethannicholasb3058bd2016-07-01 08:22:01 -07001894 return fPointer;
1895 }
1896
Ethan Nicholase0707b72021-03-17 11:16:41 -04001897 bool isMemoryObjectPointer() const override {
1898 return fIsMemoryObject;
1899 }
1900
John Stiles1cf2c8d2020-08-13 22:58:04 -04001901 SpvId load(OutputStream& out) override {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001902 SpvId result = fGen.nextId(fPrecision);
ethannicholasb3058bd2016-07-01 08:22:01 -07001903 fGen.writeInstruction(SpvOpLoad, fType, result, fPointer, out);
1904 return result;
1905 }
1906
John Stiles1cf2c8d2020-08-13 22:58:04 -04001907 void store(SpvId value, OutputStream& out) override {
ethannicholasb3058bd2016-07-01 08:22:01 -07001908 fGen.writeInstruction(SpvOpStore, fPointer, value, out);
1909 }
1910
1911private:
1912 SPIRVCodeGenerator& fGen;
1913 const SpvId fPointer;
Ethan Nicholase0707b72021-03-17 11:16:41 -04001914 const bool fIsMemoryObject;
ethannicholasb3058bd2016-07-01 08:22:01 -07001915 const SpvId fType;
Ethan Nicholas10e93b62019-03-20 10:46:14 -04001916 const SPIRVCodeGenerator::Precision fPrecision;
ethannicholasb3058bd2016-07-01 08:22:01 -07001917};
1918
1919class SwizzleLValue : public SPIRVCodeGenerator::LValue {
1920public:
John Stiles750109b2020-10-30 13:45:46 -04001921 SwizzleLValue(SPIRVCodeGenerator& gen, SpvId vecPointer, const ComponentArray& components,
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001922 const Type& baseType, const Type& swizzleType)
ethannicholasb3058bd2016-07-01 08:22:01 -07001923 : fGen(gen)
1924 , fVecPointer(vecPointer)
1925 , fComponents(components)
John Stiles3f14d282021-02-05 09:31:04 -05001926 , fBaseType(&baseType)
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001927 , fSwizzleType(&swizzleType) {}
ethannicholasb3058bd2016-07-01 08:22:01 -07001928
John Stiles3f14d282021-02-05 09:31:04 -05001929 bool applySwizzle(const ComponentArray& components, const Type& newType) override {
1930 ComponentArray updatedSwizzle;
1931 for (int8_t component : components) {
1932 if (component < 0 || component >= fComponents.count()) {
1933 SkDEBUGFAILF("swizzle accessed nonexistent component %d", (int)component);
1934 return false;
1935 }
1936 updatedSwizzle.push_back(fComponents[component]);
1937 }
1938 fComponents = updatedSwizzle;
1939 fSwizzleType = &newType;
1940 return true;
ethannicholasb3058bd2016-07-01 08:22:01 -07001941 }
1942
John Stiles1cf2c8d2020-08-13 22:58:04 -04001943 SpvId load(OutputStream& out) override {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001944 SpvId base = fGen.nextId(fBaseType);
John Stiles3f14d282021-02-05 09:31:04 -05001945 fGen.writeInstruction(SpvOpLoad, fGen.getType(*fBaseType), base, fVecPointer, out);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001946 SpvId result = fGen.nextId(fBaseType);
ethannicholasb3058bd2016-07-01 08:22:01 -07001947 fGen.writeOpCode(SpvOpVectorShuffle, 5 + (int32_t) fComponents.size(), out);
John Stiles3f14d282021-02-05 09:31:04 -05001948 fGen.writeWord(fGen.getType(*fSwizzleType), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07001949 fGen.writeWord(result, out);
1950 fGen.writeWord(base, out);
1951 fGen.writeWord(base, out);
1952 for (int component : fComponents) {
1953 fGen.writeWord(component, out);
1954 }
1955 return result;
1956 }
1957
John Stiles1cf2c8d2020-08-13 22:58:04 -04001958 void store(SpvId value, OutputStream& out) override {
ethannicholasb3058bd2016-07-01 08:22:01 -07001959 // use OpVectorShuffle to mix and match the vector components. We effectively create
1960 // a virtual vector out of the concatenation of the left and right vectors, and then
Greg Daniel64773e62016-11-22 09:44:03 -05001961 // select components from this virtual vector to make the result vector. For
ethannicholasb3058bd2016-07-01 08:22:01 -07001962 // instance, given:
Ethan Nicholas5af9ea32017-07-28 15:19:46 -04001963 // float3L = ...;
1964 // float3R = ...;
ethannicholasb3058bd2016-07-01 08:22:01 -07001965 // L.xz = R.xy;
Greg Daniel64773e62016-11-22 09:44:03 -05001966 // 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 -07001967 // our result vector to look like (R.x, L.y, R.y), so we need to select indices
1968 // (3, 1, 4).
Ethan Nicholas7f015882021-03-23 14:16:52 -04001969 SpvId base = fGen.nextId(fBaseType);
John Stiles3f14d282021-02-05 09:31:04 -05001970 fGen.writeInstruction(SpvOpLoad, fGen.getType(*fBaseType), base, fVecPointer, out);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001971 SpvId shuffle = fGen.nextId(fBaseType);
John Stiles3f14d282021-02-05 09:31:04 -05001972 fGen.writeOpCode(SpvOpVectorShuffle, 5 + fBaseType->columns(), out);
1973 fGen.writeWord(fGen.getType(*fBaseType), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07001974 fGen.writeWord(shuffle, out);
1975 fGen.writeWord(base, out);
1976 fGen.writeWord(value, out);
John Stiles3f14d282021-02-05 09:31:04 -05001977 for (int i = 0; i < fBaseType->columns(); i++) {
ethannicholasb3058bd2016-07-01 08:22:01 -07001978 // current offset into the virtual vector, defaults to pulling the unmodified
1979 // value from the left side
1980 int offset = i;
1981 // check to see if we are writing this component
1982 for (size_t j = 0; j < fComponents.size(); j++) {
1983 if (fComponents[j] == i) {
Greg Daniel64773e62016-11-22 09:44:03 -05001984 // we're writing to this component, so adjust the offset to pull from
ethannicholasb3058bd2016-07-01 08:22:01 -07001985 // the correct component of the right side instead of preserving the
1986 // value from the left
John Stiles3f14d282021-02-05 09:31:04 -05001987 offset = (int) (j + fBaseType->columns());
ethannicholasb3058bd2016-07-01 08:22:01 -07001988 break;
1989 }
1990 }
1991 fGen.writeWord(offset, out);
1992 }
1993 fGen.writeInstruction(SpvOpStore, fVecPointer, shuffle, out);
1994 }
1995
1996private:
1997 SPIRVCodeGenerator& fGen;
1998 const SpvId fVecPointer;
John Stiles3f14d282021-02-05 09:31:04 -05001999 ComponentArray fComponents;
2000 const Type* fBaseType;
2001 const Type* fSwizzleType;
ethannicholasb3058bd2016-07-01 08:22:01 -07002002};
2003
John Stilese40d1662021-01-29 10:08:50 -05002004int SPIRVCodeGenerator::findUniformFieldIndex(const Variable& var) const {
2005 auto iter = fTopLevelUniformMap.find(&var);
2006 return (iter != fTopLevelUniformMap.end()) ? iter->second : -1;
2007}
2008
Greg Daniel64773e62016-11-22 09:44:03 -05002009std::unique_ptr<SPIRVCodeGenerator::LValue> SPIRVCodeGenerator::getLValue(const Expression& expr,
Ethan Nicholas0df1b042017-03-31 13:56:23 -04002010 OutputStream& out) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04002011 const Type& type = expr.type();
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002012 Precision precision = type.highPrecision() ? Precision::kDefault : Precision::kRelaxed;
Ethan Nicholase6592142020-09-08 10:22:09 -04002013 switch (expr.kind()) {
2014 case Expression::Kind::kVariableReference: {
John Stiles0de76f72021-01-29 09:19:39 -05002015 const Variable& var = *expr.as<VariableReference>().variable();
John Stilese40d1662021-01-29 10:08:50 -05002016 int uniformIdx = this->findUniformFieldIndex(var);
2017 if (uniformIdx >= 0) {
Ethan Nicholas89cfde12021-09-27 11:20:34 -04002018 Literal uniformIdxLiteral{/*line=*/-1, (double)uniformIdx,
John Stiles7591d4b2021-09-13 13:32:06 -04002019 fContext.fTypes.fInt.get()};
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002020 SpvId memberId = this->nextId(nullptr);
John Stilese40d1662021-01-29 10:08:50 -05002021 SpvId typeId = this->getPointerType(type, SpvStorageClassUniform);
John Stiles7591d4b2021-09-13 13:32:06 -04002022 SpvId uniformIdxId = this->writeLiteral(uniformIdxLiteral);
John Stilese40d1662021-01-29 10:08:50 -05002023 this->writeInstruction(SpvOpAccessChain, typeId, memberId, fUniformBufferId,
2024 uniformIdxId, out);
Ethan Nicholase0707b72021-03-17 11:16:41 -04002025 return std::make_unique<PointerLValue>(*this, memberId,
2026 /*isMemoryObjectPointer=*/true,
2027 this->getType(type), precision);
John Stilese40d1662021-01-29 10:08:50 -05002028 }
Brian Osman99ddd2a2021-08-27 11:21:12 -04002029 SpvId typeId = this->getType(type, this->memoryLayoutForVariable(var));
ethannicholasd598f792016-07-25 10:08:54 -07002030 auto entry = fVariableMap.find(&var);
John Stiles9078a892021-08-18 15:03:17 -04002031 SkASSERTF(entry != fVariableMap.end(), "%s", expr.description().c_str());
Ethan Nicholase0707b72021-03-17 11:16:41 -04002032 return std::make_unique<PointerLValue>(*this, entry->second,
2033 /*isMemoryObjectPointer=*/true,
2034 typeId, precision);
ethannicholasb3058bd2016-07-01 08:22:01 -07002035 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002036 case Expression::Kind::kIndex: // fall through
2037 case Expression::Kind::kFieldAccess: {
ethannicholasb3058bd2016-07-01 08:22:01 -07002038 std::vector<SpvId> chain = this->getAccessChain(expr, out);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002039 SpvId member = this->nextId(nullptr);
ethannicholasb3058bd2016-07-01 08:22:01 -07002040 this->writeOpCode(SpvOpAccessChain, (SpvId) (3 + chain.size()), out);
Ethan Nicholas30d30222020-09-11 12:27:26 -04002041 this->writeWord(this->getPointerType(type, get_storage_class(expr)), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002042 this->writeWord(member, out);
2043 for (SpvId idx : chain) {
2044 this->writeWord(idx, out);
2045 }
Ethan Nicholase0707b72021-03-17 11:16:41 -04002046 return std::make_unique<PointerLValue>(*this, member, /*isMemoryObjectPointer=*/false,
2047 this->getType(type), precision);
ethannicholasb3058bd2016-07-01 08:22:01 -07002048 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002049 case Expression::Kind::kSwizzle: {
John Stiles0693fb82021-01-22 18:27:52 -05002050 const Swizzle& swizzle = expr.as<Swizzle>();
John Stiles3f14d282021-02-05 09:31:04 -05002051 std::unique_ptr<LValue> lvalue = this->getLValue(*swizzle.base(), out);
2052 if (lvalue->applySwizzle(swizzle.components(), type)) {
2053 return lvalue;
2054 }
2055 SpvId base = lvalue->getPointer();
2056 if (base == (SpvId) -1) {
Ethan Nicholas89cfde12021-09-27 11:20:34 -04002057 fContext.fErrors->error(swizzle.fLine, "unable to retrieve lvalue from swizzle");
John Stiles5570c512020-11-19 17:58:07 -05002058 }
John Stiles3f14d282021-02-05 09:31:04 -05002059 if (swizzle.components().size() == 1) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002060 SpvId member = this->nextId(nullptr);
John Stilesb5db4822021-01-21 13:04:40 -05002061 SpvId typeId = this->getPointerType(type, get_storage_class(*swizzle.base()));
Ethan Nicholas89cfde12021-09-27 11:20:34 -04002062 Literal index(/*line=*/-1, swizzle.components()[0], fContext.fTypes.fInt.get());
John Stiles7591d4b2021-09-13 13:32:06 -04002063 SpvId indexId = this->writeLiteral(index);
John Stilesb5db4822021-01-21 13:04:40 -05002064 this->writeInstruction(SpvOpAccessChain, typeId, member, base, indexId, out);
Ethan Nicholase0707b72021-03-17 11:16:41 -04002065 return std::make_unique<PointerLValue>(*this,
2066 member,
2067 /*isMemoryObjectPointer=*/false,
2068 this->getType(type),
John Stiles5570c512020-11-19 17:58:07 -05002069 precision);
ethannicholasb3058bd2016-07-01 08:22:01 -07002070 } else {
John Stiles5570c512020-11-19 17:58:07 -05002071 return std::make_unique<SwizzleLValue>(*this, base, swizzle.components(),
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002072 swizzle.base()->type(), type);
ethannicholasb3058bd2016-07-01 08:22:01 -07002073 }
2074 }
Ethan Nicholas30d30222020-09-11 12:27:26 -04002075 default: {
Kevin Lubickbe03ef12021-06-16 15:28:00 -04002076 // expr isn't actually an lvalue, create a placeholder variable for it. This case
2077 // happens due to the need to store values in temporary variables during function
2078 // calls (see comments in getFunctionType); erroneous uses of rvalues as lvalues
2079 // should have been caught by IRGenerator
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002080 SpvId result = this->nextId(nullptr);
Ethan Nicholas30d30222020-09-11 12:27:26 -04002081 SpvId pointerType = this->getPointerType(type, SpvStorageClassFunction);
2082 this->writeInstruction(SpvOpVariable, pointerType, result, SpvStorageClassFunction,
ethannicholasd598f792016-07-25 10:08:54 -07002083 fVariableBuffer);
ethannicholasb3058bd2016-07-01 08:22:01 -07002084 this->writeInstruction(SpvOpStore, result, this->writeExpression(expr, out), out);
Ethan Nicholase0707b72021-03-17 11:16:41 -04002085 return std::make_unique<PointerLValue>(*this, result, /*isMemoryObjectPointer=*/true,
2086 this->getType(type), precision);
Ethan Nicholas30d30222020-09-11 12:27:26 -04002087 }
ethannicholasb3058bd2016-07-01 08:22:01 -07002088 }
2089}
2090
Ethan Nicholas0df1b042017-03-31 13:56:23 -04002091SpvId SPIRVCodeGenerator::writeVariableReference(const VariableReference& ref, OutputStream& out) {
John Stiles9078a892021-08-18 15:03:17 -04002092 const Variable* variable = ref.variable();
2093 if (variable->modifiers().fLayout.fBuiltin == DEVICE_FRAGCOORDS_BUILTIN) {
Brian Salomond8d85b92021-07-07 09:41:17 -04002094 // Down below, we rewrite raw references to sk_FragCoord with expressions that reference
2095 // DEVICE_FRAGCOORDS_BUILTIN. This is a fake variable that means we need to directly access
2096 // the fragcoord; do so now.
Ethan Nicholasa2d22b22021-07-15 10:35:54 -04002097 dsl::DSLGlobalVar fragCoord("sk_FragCoord");
Brian Salomond8d85b92021-07-07 09:41:17 -04002098 return this->getLValue(*dsl::DSLExpression(fragCoord).release(), out)->load(out);
2099 }
John Stiles9078a892021-08-18 15:03:17 -04002100 if (variable->modifiers().fLayout.fBuiltin == DEVICE_CLOCKWISE_BUILTIN) {
Brian Salomond8d85b92021-07-07 09:41:17 -04002101 // Down below, we rewrite raw references to sk_Clockwise with expressions that reference
2102 // DEVICE_CLOCKWISE_BUILTIN. This is a fake variable that means we need to directly
2103 // access front facing; do so now.
Ethan Nicholasa2d22b22021-07-15 10:35:54 -04002104 dsl::DSLGlobalVar clockwise("sk_Clockwise");
Brian Salomond8d85b92021-07-07 09:41:17 -04002105 return this->getLValue(*dsl::DSLExpression(clockwise).release(), out)->load(out);
2106 }
John Stilese40d1662021-01-29 10:08:50 -05002107
Brian Salomond8d85b92021-07-07 09:41:17 -04002108 // Handle inserting use of uniform to flip y when referencing sk_FragCoord.
Brian Salomond8d85b92021-07-07 09:41:17 -04002109 if (variable->modifiers().fLayout.fBuiltin == SK_FRAGCOORD_BUILTIN) {
Ethan Nicholas89cfde12021-09-27 11:20:34 -04002110 this->addRTFlipUniform(ref.fLine);
Brian Salomond8d85b92021-07-07 09:41:17 -04002111 // Use sk_RTAdjust to compute the flipped coordinate
2112 using namespace dsl;
2113 const char* DEVICE_COORDS_NAME = "__device_FragCoords";
Ethan Nicholasc8452722021-10-07 10:47:32 -04002114 SymbolTable& symbols = *ThreadContext::SymbolTable();
Brian Salomond8d85b92021-07-07 09:41:17 -04002115 // Use a uniform to flip the Y coordinate. The new expression will be written in
2116 // terms of __device_FragCoords, which is a fake variable that means "access the
2117 // underlying fragcoords directly without flipping it".
Ethan Nicholasc8452722021-10-07 10:47:32 -04002118 DSLExpression rtFlip(ThreadContext::IRGenerator().convertIdentifier(/*line=*/-1,
2119 SKSL_RTFLIP_NAME));
Brian Salomond8d85b92021-07-07 09:41:17 -04002120 if (!symbols[DEVICE_COORDS_NAME]) {
John Stiles0cac5ed2021-08-06 11:40:39 -04002121 AutoAttachPoolToThread attach(fProgram.fPool.get());
Brian Salomond8d85b92021-07-07 09:41:17 -04002122 Modifiers modifiers;
2123 modifiers.fLayout.fBuiltin = DEVICE_FRAGCOORDS_BUILTIN;
Ethan Nicholas89cfde12021-09-27 11:20:34 -04002124 auto coordsVar = std::make_unique<Variable>(/*line=*/-1,
John Stilesd7437ee2021-08-02 11:56:16 -04002125 fContext.fModifiersPool->add(modifiers),
2126 DEVICE_COORDS_NAME,
2127 fContext.fTypes.fFloat4.get(),
2128 true,
2129 Variable::Storage::kGlobal);
2130 fSPIRVBonusVariables.insert(coordsVar.get());
2131 symbols.add(std::move(coordsVar));
Greg Daniela85e4bf2020-06-17 16:32:45 -04002132 }
Ethan Nicholasa2d22b22021-07-15 10:35:54 -04002133 DSLGlobalVar deviceCoord(DEVICE_COORDS_NAME);
Brian Salomond8d85b92021-07-07 09:41:17 -04002134 std::unique_ptr<Expression> rtFlipSkSLExpr = rtFlip.release();
2135 DSLExpression x = DSLExpression(rtFlipSkSLExpr->clone()).x();
2136 DSLExpression y = DSLExpression(std::move(rtFlipSkSLExpr)).y();
2137 return this->writeExpression(*dsl::Float4(deviceCoord.x(),
2138 std::move(x) + std::move(y) * deviceCoord.y(),
2139 deviceCoord.z(),
2140 deviceCoord.w()).release(),
2141 out);
Ethan Nicholas941e7e22016-12-12 15:33:30 -05002142 }
John Stiles1e1fe122021-01-29 12:18:46 -05002143
Brian Salomond8d85b92021-07-07 09:41:17 -04002144 // Handle flipping sk_Clockwise.
2145 if (variable->modifiers().fLayout.fBuiltin == SK_CLOCKWISE_BUILTIN) {
Ethan Nicholas89cfde12021-09-27 11:20:34 -04002146 this->addRTFlipUniform(ref.fLine);
Brian Salomond8d85b92021-07-07 09:41:17 -04002147 using namespace dsl;
2148 const char* DEVICE_CLOCKWISE_NAME = "__device_Clockwise";
Ethan Nicholasc8452722021-10-07 10:47:32 -04002149 SymbolTable& symbols = *ThreadContext::SymbolTable();
Brian Salomond8d85b92021-07-07 09:41:17 -04002150 // Use a uniform to flip the Y coordinate. The new expression will be written in
2151 // terms of __device_Clockwise, which is a fake variable that means "access the
2152 // underlying FrontFacing directly".
Ethan Nicholasc8452722021-10-07 10:47:32 -04002153 DSLExpression rtFlip(ThreadContext::IRGenerator().convertIdentifier(/*line=*/-1,
2154 SKSL_RTFLIP_NAME));
Brian Salomond8d85b92021-07-07 09:41:17 -04002155 if (!symbols[DEVICE_CLOCKWISE_NAME]) {
John Stiles0cac5ed2021-08-06 11:40:39 -04002156 AutoAttachPoolToThread attach(fProgram.fPool.get());
Brian Salomond8d85b92021-07-07 09:41:17 -04002157 Modifiers modifiers;
2158 modifiers.fLayout.fBuiltin = DEVICE_CLOCKWISE_BUILTIN;
Ethan Nicholas89cfde12021-09-27 11:20:34 -04002159 auto clockwiseVar = std::make_unique<Variable>(/*line=*/-1,
John Stilesd7437ee2021-08-02 11:56:16 -04002160 fContext.fModifiersPool->add(modifiers),
2161 DEVICE_CLOCKWISE_NAME,
2162 fContext.fTypes.fBool.get(),
2163 true,
2164 Variable::Storage::kGlobal);
2165 fSPIRVBonusVariables.insert(clockwiseVar.get());
2166 symbols.add(std::move(clockwiseVar));
Brian Salomond8d85b92021-07-07 09:41:17 -04002167 }
Ethan Nicholasa2d22b22021-07-15 10:35:54 -04002168 DSLGlobalVar deviceClockwise(DEVICE_CLOCKWISE_NAME);
Brian Salomond8d85b92021-07-07 09:41:17 -04002169 // FrontFacing in Vulkan is defined in terms of a top-down render target. In skia,
2170 // we use the default convention of "counter-clockwise face is front".
2171 return this->writeExpression(*dsl::Bool(Select(rtFlip.y() > 0,
2172 !deviceClockwise,
2173 deviceClockwise)).release(),
2174 out);
Chris Daltonb91c4662018-08-01 10:46:22 -06002175 }
John Stiles1e1fe122021-01-29 12:18:46 -05002176
Brian Salomond8d85b92021-07-07 09:41:17 -04002177 return this->getLValue(ref, out)->load(out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002178}
2179
Ethan Nicholas0df1b042017-03-31 13:56:23 -04002180SpvId SPIRVCodeGenerator::writeIndexExpression(const IndexExpression& expr, OutputStream& out) {
John Stiles9aeed132020-11-24 17:36:06 -05002181 if (expr.base()->type().isVector()) {
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04002182 SpvId base = this->writeExpression(*expr.base(), out);
2183 SpvId index = this->writeExpression(*expr.index(), out);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002184 SpvId result = this->nextId(nullptr);
Ethan Nicholas30d30222020-09-11 12:27:26 -04002185 this->writeInstruction(SpvOpVectorExtractDynamic, this->getType(expr.type()), result, base,
Ethan Nicholasa9a06902019-01-07 14:42:40 -05002186 index, out);
2187 return result;
2188 }
ethannicholasb3058bd2016-07-01 08:22:01 -07002189 return getLValue(expr, out)->load(out);
2190}
2191
Ethan Nicholas0df1b042017-03-31 13:56:23 -04002192SpvId SPIRVCodeGenerator::writeFieldAccess(const FieldAccess& f, OutputStream& out) {
ethannicholasb3058bd2016-07-01 08:22:01 -07002193 return getLValue(f, out)->load(out);
2194}
2195
Ethan Nicholas0df1b042017-03-31 13:56:23 -04002196SpvId SPIRVCodeGenerator::writeSwizzle(const Swizzle& swizzle, OutputStream& out) {
Ethan Nicholas6b4d5812020-10-12 16:11:51 -04002197 SpvId base = this->writeExpression(*swizzle.base(), out);
Ethan Nicholas7f015882021-03-23 14:16:52 -04002198 SpvId result = this->nextId(&swizzle.type());
Ethan Nicholas6b4d5812020-10-12 16:11:51 -04002199 size_t count = swizzle.components().size();
ethannicholasb3058bd2016-07-01 08:22:01 -07002200 if (count == 1) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04002201 this->writeInstruction(SpvOpCompositeExtract, this->getType(swizzle.type()), result, base,
Ethan Nicholas6b4d5812020-10-12 16:11:51 -04002202 swizzle.components()[0], out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002203 } else {
2204 this->writeOpCode(SpvOpVectorShuffle, 5 + (int32_t) count, out);
Ethan Nicholas30d30222020-09-11 12:27:26 -04002205 this->writeWord(this->getType(swizzle.type()), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002206 this->writeWord(result, out);
2207 this->writeWord(base, out);
Brian Osman25647672020-09-15 15:16:56 -04002208 this->writeWord(base, out);
Ethan Nicholas6b4d5812020-10-12 16:11:51 -04002209 for (int component : swizzle.components()) {
Brian Osman25647672020-09-15 15:16:56 -04002210 this->writeWord(component, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002211 }
2212 }
2213 return result;
2214}
2215
Greg Daniel64773e62016-11-22 09:44:03 -05002216SpvId SPIRVCodeGenerator::writeBinaryOperation(const Type& resultType,
2217 const Type& operandType, SpvId lhs,
2218 SpvId rhs, SpvOp_ ifFloat, SpvOp_ ifInt,
Ethan Nicholas0df1b042017-03-31 13:56:23 -04002219 SpvOp_ ifUInt, SpvOp_ ifBool, OutputStream& out) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002220 SpvId result = this->nextId(&resultType);
ethannicholasd598f792016-07-25 10:08:54 -07002221 if (is_float(fContext, operandType)) {
ethannicholasb3058bd2016-07-01 08:22:01 -07002222 this->writeInstruction(ifFloat, this->getType(resultType), result, lhs, rhs, out);
ethannicholasd598f792016-07-25 10:08:54 -07002223 } else if (is_signed(fContext, operandType)) {
ethannicholasb3058bd2016-07-01 08:22:01 -07002224 this->writeInstruction(ifInt, this->getType(resultType), result, lhs, rhs, out);
ethannicholasd598f792016-07-25 10:08:54 -07002225 } else if (is_unsigned(fContext, operandType)) {
ethannicholasb3058bd2016-07-01 08:22:01 -07002226 this->writeInstruction(ifUInt, this->getType(resultType), result, lhs, rhs, out);
John Stiles123501f2020-12-09 10:08:13 -05002227 } else if (is_bool(fContext, operandType)) {
ethannicholasb3058bd2016-07-01 08:22:01 -07002228 this->writeInstruction(ifBool, this->getType(resultType), result, lhs, rhs, out);
2229 } else {
Ethan Nicholas89cfde12021-09-27 11:20:34 -04002230 fContext.fErrors->error(operandType.fLine,
Ethan Nicholas3abc6c62021-08-13 11:20:09 -04002231 "unsupported operand for binary expression: " + operandType.description());
Ethan Nicholas2f4652f2021-03-12 18:48:48 +00002232 }
ethannicholasb3058bd2016-07-01 08:22:01 -07002233 return result;
2234}
2235
Ethan Nicholas48e24052018-03-14 13:51:39 -04002236SpvId SPIRVCodeGenerator::foldToBool(SpvId id, const Type& operandType, SpvOp op,
2237 OutputStream& out) {
John Stiles9aeed132020-11-24 17:36:06 -05002238 if (operandType.isVector()) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002239 SpvId result = this->nextId(nullptr);
John Stiles54e7c052021-01-11 14:22:36 -05002240 this->writeInstruction(op, this->getType(*fContext.fTypes.fBool), result, id, out);
Ethan Nicholasef653b82017-02-21 13:50:00 -05002241 return result;
2242 }
2243 return id;
2244}
2245
Ethan Nicholas68990be2017-07-13 09:36:52 -04002246SpvId SPIRVCodeGenerator::writeMatrixComparison(const Type& operandType, SpvId lhs, SpvId rhs,
2247 SpvOp_ floatOperator, SpvOp_ intOperator,
Ethan Nicholas0df21132018-07-10 09:37:51 -04002248 SpvOp_ vectorMergeOperator, SpvOp_ mergeOperator,
Ethan Nicholas68990be2017-07-13 09:36:52 -04002249 OutputStream& out) {
2250 SpvOp_ compareOp = is_float(fContext, operandType) ? floatOperator : intOperator;
John Stiles9aeed132020-11-24 17:36:06 -05002251 SkASSERT(operandType.isMatrix());
Ethan Nicholas0df21132018-07-10 09:37:51 -04002252 SpvId columnType = this->getType(operandType.componentType().toCompound(fContext,
2253 operandType.rows(),
2254 1));
John Stiles54e7c052021-01-11 14:22:36 -05002255 SpvId bvecType = this->getType(fContext.fTypes.fBool->toCompound(fContext,
Ethan Nicholas0df21132018-07-10 09:37:51 -04002256 operandType.rows(),
Ethan Nicholas68990be2017-07-13 09:36:52 -04002257 1));
John Stiles54e7c052021-01-11 14:22:36 -05002258 SpvId boolType = this->getType(*fContext.fTypes.fBool);
Ethan Nicholas68990be2017-07-13 09:36:52 -04002259 SpvId result = 0;
Ethan Nicholas0df21132018-07-10 09:37:51 -04002260 for (int i = 0; i < operandType.columns(); i++) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002261 SpvId columnL = this->nextId(&operandType);
Ethan Nicholas0df21132018-07-10 09:37:51 -04002262 this->writeInstruction(SpvOpCompositeExtract, columnType, columnL, lhs, i, out);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002263 SpvId columnR = this->nextId(&operandType);
Ethan Nicholas0df21132018-07-10 09:37:51 -04002264 this->writeInstruction(SpvOpCompositeExtract, columnType, columnR, rhs, i, out);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002265 SpvId compare = this->nextId(&operandType);
Ethan Nicholas0df21132018-07-10 09:37:51 -04002266 this->writeInstruction(compareOp, bvecType, compare, columnL, columnR, out);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002267 SpvId merge = this->nextId(nullptr);
Ethan Nicholas0df21132018-07-10 09:37:51 -04002268 this->writeInstruction(vectorMergeOperator, boolType, merge, compare, out);
Ethan Nicholas68990be2017-07-13 09:36:52 -04002269 if (result != 0) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002270 SpvId next = this->nextId(nullptr);
Ethan Nicholas0df21132018-07-10 09:37:51 -04002271 this->writeInstruction(mergeOperator, boolType, next, result, merge, out);
Ethan Nicholas68990be2017-07-13 09:36:52 -04002272 result = next;
2273 }
2274 else {
Ethan Nicholas0df21132018-07-10 09:37:51 -04002275 result = merge;
Ethan Nicholas68990be2017-07-13 09:36:52 -04002276 }
2277 }
2278 return result;
2279}
2280
Ethan Nicholas0df21132018-07-10 09:37:51 -04002281SpvId SPIRVCodeGenerator::writeComponentwiseMatrixBinary(const Type& operandType, SpvId lhs,
John Stiles43b593c2021-05-13 22:03:27 -04002282 SpvId rhs, SpvOp_ op, OutputStream& out) {
John Stiles9aeed132020-11-24 17:36:06 -05002283 SkASSERT(operandType.isMatrix());
Ethan Nicholas2f4652f2021-03-12 18:48:48 +00002284 SpvId columnType = this->getType(operandType.componentType().toCompound(fContext,
2285 operandType.rows(),
2286 1));
John Stiles43b593c2021-05-13 22:03:27 -04002287 std::vector<SpvId> columns;
2288 columns.reserve(operandType.columns());
Ethan Nicholas0df21132018-07-10 09:37:51 -04002289 for (int i = 0; i < operandType.columns(); i++) {
Ethan Nicholas7f015882021-03-23 14:16:52 -04002290 SpvId columnL = this->nextId(&operandType);
Ethan Nicholas2f4652f2021-03-12 18:48:48 +00002291 this->writeInstruction(SpvOpCompositeExtract, columnType, columnL, lhs, i, out);
Ethan Nicholas7f015882021-03-23 14:16:52 -04002292 SpvId columnR = this->nextId(&operandType);
Ethan Nicholas2f4652f2021-03-12 18:48:48 +00002293 this->writeInstruction(SpvOpCompositeExtract, columnType, columnR, rhs, i, out);
John Stiles43b593c2021-05-13 22:03:27 -04002294 columns.push_back(this->nextId(&operandType));
Ethan Nicholas2f4652f2021-03-12 18:48:48 +00002295 this->writeInstruction(op, columnType, columns[i], columnL, columnR, out);
Ethan Nicholas0df21132018-07-10 09:37:51 -04002296 }
John Stiles43b593c2021-05-13 22:03:27 -04002297 return this->writeComposite(columns, operandType, out);
Ethan Nicholas0df21132018-07-10 09:37:51 -04002298}
2299
John Stiles9485b552021-01-27 11:47:00 -05002300static std::unique_ptr<Expression> create_literal_1(const Context& context, const Type& type) {
John Stiles7591d4b2021-09-13 13:32:06 -04002301 SkASSERT(type.isInteger() || type.isFloat());
Ethan Nicholas89cfde12021-09-27 11:20:34 -04002302 return Literal::Make(/*line=*/-1, /*value=*/1.0, &type);
Ethan Nicholas49465b42019-04-17 12:22:21 -04002303}
2304
John Stilesd94bfdd2021-03-25 11:44:08 -04002305SpvId SPIRVCodeGenerator::writeReciprocal(const Type& type, SpvId value, OutputStream& out) {
2306 SkASSERT(type.isFloat());
Ethan Nicholas89cfde12021-09-27 11:20:34 -04002307 SpvId one = this->writeLiteral({/*line=*/-1, /*value=*/1, &type});
John Stilesd94bfdd2021-03-25 11:44:08 -04002308 SpvId reciprocal = this->nextId(&type);
2309 this->writeInstruction(SpvOpFDiv, this->getType(type), reciprocal, one, value, out);
2310 return reciprocal;
2311}
2312
John Stilesa91bf052021-05-17 09:34:03 -04002313SpvId SPIRVCodeGenerator::writeScalarToMatrixSplat(const Type& matrixType,
2314 SpvId scalarId,
2315 OutputStream& out) {
2316 // Splat the scalar into a vector.
2317 const Type& vectorType = matrixType.componentType().toCompound(fContext,
2318 /*columns=*/matrixType.rows(),
2319 /*rows=*/1);
2320 std::vector<SpvId> vecArguments(/*count*/ matrixType.rows(), /*value*/ scalarId);
2321 SpvId vectorId = this->writeComposite(vecArguments, vectorType, out);
2322
2323 // Splat the vector into a matrix.
2324 std::vector<SpvId> matArguments(/*count*/ matrixType.columns(), /*value*/ vectorId);
2325 return this->writeComposite(matArguments, matrixType, out);
2326}
2327
John Stiles45990502021-02-16 10:55:27 -05002328SpvId SPIRVCodeGenerator::writeBinaryExpression(const Type& leftType, SpvId lhs, Operator op,
Ethan Nicholas49465b42019-04-17 12:22:21 -04002329 const Type& rightType, SpvId rhs,
2330 const Type& resultType, OutputStream& out) {
John Stilesd0614f22020-12-09 11:11:41 -05002331 // The comma operator ignores the type of the left-hand side entirely.
John Stiles45990502021-02-16 10:55:27 -05002332 if (op.kind() == Token::Kind::TK_COMMA) {
John Stilesd0614f22020-12-09 11:11:41 -05002333 return rhs;
2334 }
Ethan Nicholas48e24052018-03-14 13:51:39 -04002335 // overall type we are operating on: float2, int, uint4...
ethannicholasb3058bd2016-07-01 08:22:01 -07002336 const Type* operandType;
Ethan Nicholas48e24052018-03-14 13:51:39 -04002337 // IR allows mismatched types in expressions (e.g. float2 * float), but they need special
2338 // handling in SPIR-V
Ethan Nicholas49465b42019-04-17 12:22:21 -04002339 if (this->getActualType(leftType) != this->getActualType(rightType)) {
John Stiles9aeed132020-11-24 17:36:06 -05002340 if (leftType.isVector() && rightType.isNumber()) {
John Stilesd94bfdd2021-03-25 11:44:08 -04002341 if (resultType.componentType().isFloat()) {
2342 switch (op.kind()) {
2343 case Token::Kind::TK_SLASH: {
2344 rhs = this->writeReciprocal(rightType, rhs, out);
2345 [[fallthrough]];
2346 }
2347 case Token::Kind::TK_STAR: {
2348 SpvId result = this->nextId(&resultType);
2349 this->writeInstruction(SpvOpVectorTimesScalar, this->getType(resultType),
2350 result, lhs, rhs, out);
2351 return result;
2352 }
2353 default:
2354 break;
2355 }
Ethan Nicholas49465b42019-04-17 12:22:21 -04002356 }
ethannicholasb3058bd2016-07-01 08:22:01 -07002357 // promote number to vector
Ethan Nicholas49465b42019-04-17 12:22:21 -04002358 const Type& vecType = leftType;
Ethan Nicholas7f015882021-03-23 14:16:52 -04002359 SpvId vec = this->nextId(&vecType);
Ethan Nicholas48e24052018-03-14 13:51:39 -04002360 this->writeOpCode(SpvOpCompositeConstruct, 3 + vecType.columns(), out);
2361 this->writeWord(this->getType(vecType), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002362 this->writeWord(vec, out);
Ethan Nicholas48e24052018-03-14 13:51:39 -04002363 for (int i = 0; i < vecType.columns(); i++) {
ethannicholasb3058bd2016-07-01 08:22:01 -07002364 this->writeWord(rhs, out);
2365 }
2366 rhs = vec;
Ethan Nicholas49465b42019-04-17 12:22:21 -04002367 operandType = &leftType;
John Stiles9aeed132020-11-24 17:36:06 -05002368 } else if (rightType.isVector() && leftType.isNumber()) {
John Stilesd94bfdd2021-03-25 11:44:08 -04002369 if (resultType.componentType().isFloat()) {
2370 if (op.kind() == Token::Kind::TK_STAR) {
2371 SpvId result = this->nextId(&resultType);
2372 this->writeInstruction(SpvOpVectorTimesScalar, this->getType(resultType),
2373 result, rhs, lhs, out);
2374 return result;
2375 }
Ethan Nicholas49465b42019-04-17 12:22:21 -04002376 }
ethannicholasb3058bd2016-07-01 08:22:01 -07002377 // promote number to vector
Ethan Nicholas49465b42019-04-17 12:22:21 -04002378 const Type& vecType = rightType;
Ethan Nicholas7f015882021-03-23 14:16:52 -04002379 SpvId vec = this->nextId(&vecType);
Ethan Nicholas48e24052018-03-14 13:51:39 -04002380 this->writeOpCode(SpvOpCompositeConstruct, 3 + vecType.columns(), out);
2381 this->writeWord(this->getType(vecType), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002382 this->writeWord(vec, out);
Ethan Nicholas48e24052018-03-14 13:51:39 -04002383 for (int i = 0; i < vecType.columns(); i++) {
ethannicholasb3058bd2016-07-01 08:22:01 -07002384 this->writeWord(lhs, out);
2385 }
2386 lhs = vec;
Ethan Nicholas49465b42019-04-17 12:22:21 -04002387 operandType = &rightType;
John Stiles9aeed132020-11-24 17:36:06 -05002388 } else if (leftType.isMatrix()) {
John Stilesa91bf052021-05-17 09:34:03 -04002389 if (op.kind() == Token::Kind::TK_STAR) {
2390 // Matrix-times-vector and matrix-times-scalar have dedicated ops in SPIR-V.
2391 SpvOp_ spvop;
2392 if (rightType.isMatrix()) {
2393 spvop = SpvOpMatrixTimesMatrix;
2394 } else if (rightType.isVector()) {
2395 spvop = SpvOpMatrixTimesVector;
2396 } else {
2397 SkASSERT(rightType.isScalar());
2398 spvop = SpvOpMatrixTimesScalar;
2399 }
2400 SpvId result = this->nextId(&resultType);
2401 this->writeInstruction(spvop, this->getType(resultType), result, lhs, rhs, out);
2402 return result;
ethannicholasb3058bd2016-07-01 08:22:01 -07002403 } else {
John Stilesa91bf052021-05-17 09:34:03 -04002404 // Matrix-op-vector is not supported in GLSL/SkSL for non-multiplication ops; we
2405 // expect to have a scalar here.
John Stiles9aeed132020-11-24 17:36:06 -05002406 SkASSERT(rightType.isScalar());
John Stilesa91bf052021-05-17 09:34:03 -04002407
2408 // Splat rhs across an entire matrix so we can reuse the matrix-op-matrix path.
2409 SpvId rhsMatrix = this->writeScalarToMatrixSplat(leftType, rhs, out);
2410
2411 // Perform this operation as matrix-op-matrix.
2412 return this->writeBinaryExpression(leftType, lhs, op, leftType, rhsMatrix,
2413 resultType, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002414 }
John Stiles9aeed132020-11-24 17:36:06 -05002415 } else if (rightType.isMatrix()) {
John Stilesa91bf052021-05-17 09:34:03 -04002416 if (op.kind() == Token::Kind::TK_STAR) {
2417 // Matrix-times-vector and matrix-times-scalar have dedicated ops in SPIR-V.
2418 SpvId result = this->nextId(&resultType);
2419 if (leftType.isVector()) {
2420 this->writeInstruction(SpvOpVectorTimesMatrix, this->getType(resultType),
2421 result, lhs, rhs, out);
2422 } else {
2423 SkASSERT(leftType.isScalar());
2424 this->writeInstruction(SpvOpMatrixTimesScalar, this->getType(resultType),
2425 result, rhs, lhs, out);
2426 }
2427 return result;
ethannicholasb3058bd2016-07-01 08:22:01 -07002428 } else {
John Stilesa91bf052021-05-17 09:34:03 -04002429 // Vector-op-matrix is not supported in GLSL/SkSL for non-multiplication ops; we
2430 // expect to have a scalar here.
John Stiles9aeed132020-11-24 17:36:06 -05002431 SkASSERT(leftType.isScalar());
John Stilesa91bf052021-05-17 09:34:03 -04002432
2433 // Splat lhs across an entire matrix so we can reuse the matrix-op-matrix path.
2434 SpvId lhsMatrix = this->writeScalarToMatrixSplat(rightType, lhs, out);
2435
2436 // Perform this operation as matrix-op-matrix.
2437 return this->writeBinaryExpression(rightType, lhsMatrix, op, rightType, rhs,
2438 resultType, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002439 }
ethannicholasb3058bd2016-07-01 08:22:01 -07002440 } else {
Ethan Nicholas89cfde12021-09-27 11:20:34 -04002441 fContext.fErrors->error(leftType.fLine, "unsupported mixed-type expression");
Ethan Nicholas49465b42019-04-17 12:22:21 -04002442 return -1;
ethannicholasb3058bd2016-07-01 08:22:01 -07002443 }
2444 } else {
John Stiles2d4f9592020-10-30 10:29:12 -04002445 operandType = &this->getActualType(leftType);
Ethan Nicholas49465b42019-04-17 12:22:21 -04002446 SkASSERT(*operandType == this->getActualType(rightType));
ethannicholasb3058bd2016-07-01 08:22:01 -07002447 }
John Stiles45990502021-02-16 10:55:27 -05002448 switch (op.kind()) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002449 case Token::Kind::TK_EQEQ: {
John Stiles9aeed132020-11-24 17:36:06 -05002450 if (operandType->isMatrix()) {
Ethan Nicholas68990be2017-07-13 09:36:52 -04002451 return this->writeMatrixComparison(*operandType, lhs, rhs, SpvOpFOrdEqual,
Ethan Nicholas0df21132018-07-10 09:37:51 -04002452 SpvOpIEqual, SpvOpAll, SpvOpLogicalAnd, out);
Ethan Nicholas68990be2017-07-13 09:36:52 -04002453 }
John Stilesbc5c2a02021-04-08 11:44:53 -04002454 if (operandType->isStruct()) {
2455 return this->writeStructComparison(*operandType, lhs, op, rhs, out);
2456 }
John Stiles35092102021-04-08 23:30:51 -04002457 if (operandType->isArray()) {
2458 return this->writeArrayComparison(*operandType, lhs, op, rhs, out);
2459 }
John Stiles4a7dc462020-11-25 11:08:08 -05002460 SkASSERT(resultType.isBoolean());
Ethan Nicholas48e24052018-03-14 13:51:39 -04002461 const Type* tmpType;
John Stiles9aeed132020-11-24 17:36:06 -05002462 if (operandType->isVector()) {
John Stiles54e7c052021-01-11 14:22:36 -05002463 tmpType = &fContext.fTypes.fBool->toCompound(fContext,
2464 operandType->columns(),
2465 operandType->rows());
Ethan Nicholas48e24052018-03-14 13:51:39 -04002466 } else {
2467 tmpType = &resultType;
2468 }
2469 return this->foldToBool(this->writeBinaryOperation(*tmpType, *operandType, lhs, rhs,
Ethan Nicholasef653b82017-02-21 13:50:00 -05002470 SpvOpFOrdEqual, SpvOpIEqual,
2471 SpvOpIEqual, SpvOpLogicalEqual, out),
Ethan Nicholas48e24052018-03-14 13:51:39 -04002472 *operandType, SpvOpAll, out);
Ethan Nicholasef653b82017-02-21 13:50:00 -05002473 }
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002474 case Token::Kind::TK_NEQ:
John Stiles9aeed132020-11-24 17:36:06 -05002475 if (operandType->isMatrix()) {
Ethan Nicholas68990be2017-07-13 09:36:52 -04002476 return this->writeMatrixComparison(*operandType, lhs, rhs, SpvOpFOrdNotEqual,
Ethan Nicholas0df21132018-07-10 09:37:51 -04002477 SpvOpINotEqual, SpvOpAny, SpvOpLogicalOr, out);
Ethan Nicholas68990be2017-07-13 09:36:52 -04002478 }
John Stilesbc5c2a02021-04-08 11:44:53 -04002479 if (operandType->isStruct()) {
2480 return this->writeStructComparison(*operandType, lhs, op, rhs, out);
2481 }
John Stiles35092102021-04-08 23:30:51 -04002482 if (operandType->isArray()) {
2483 return this->writeArrayComparison(*operandType, lhs, op, rhs, out);
2484 }
John Stiles4a7dc462020-11-25 11:08:08 -05002485 [[fallthrough]];
2486 case Token::Kind::TK_LOGICALXOR:
2487 SkASSERT(resultType.isBoolean());
Ethan Nicholas48e24052018-03-14 13:51:39 -04002488 const Type* tmpType;
John Stiles9aeed132020-11-24 17:36:06 -05002489 if (operandType->isVector()) {
John Stiles54e7c052021-01-11 14:22:36 -05002490 tmpType = &fContext.fTypes.fBool->toCompound(fContext,
2491 operandType->columns(),
2492 operandType->rows());
Ethan Nicholas48e24052018-03-14 13:51:39 -04002493 } else {
2494 tmpType = &resultType;
2495 }
2496 return this->foldToBool(this->writeBinaryOperation(*tmpType, *operandType, lhs, rhs,
Ethan Nicholasef653b82017-02-21 13:50:00 -05002497 SpvOpFOrdNotEqual, SpvOpINotEqual,
2498 SpvOpINotEqual, SpvOpLogicalNotEqual,
2499 out),
Ethan Nicholas48e24052018-03-14 13:51:39 -04002500 *operandType, SpvOpAny, out);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002501 case Token::Kind::TK_GT:
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 SpvOpFOrdGreaterThan, SpvOpSGreaterThan,
ethannicholasb3058bd2016-07-01 08:22:01 -07002505 SpvOpUGreaterThan, SpvOpUndef, out);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002506 case Token::Kind::TK_LT:
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, SpvOpFOrdLessThan,
ethannicholasb3058bd2016-07-01 08:22:01 -07002509 SpvOpSLessThan, SpvOpULessThan, SpvOpUndef, out);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002510 case Token::Kind::TK_GTEQ:
John Stiles4a7dc462020-11-25 11:08:08 -05002511 SkASSERT(resultType.isBoolean());
Greg Daniel64773e62016-11-22 09:44:03 -05002512 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs,
2513 SpvOpFOrdGreaterThanEqual, SpvOpSGreaterThanEqual,
ethannicholasb3058bd2016-07-01 08:22:01 -07002514 SpvOpUGreaterThanEqual, SpvOpUndef, out);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002515 case Token::Kind::TK_LTEQ:
John Stiles4a7dc462020-11-25 11:08:08 -05002516 SkASSERT(resultType.isBoolean());
Greg Daniel64773e62016-11-22 09:44:03 -05002517 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs,
2518 SpvOpFOrdLessThanEqual, SpvOpSLessThanEqual,
ethannicholasb3058bd2016-07-01 08:22:01 -07002519 SpvOpULessThanEqual, SpvOpUndef, out);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002520 case Token::Kind::TK_PLUS:
John Stiles9aeed132020-11-24 17:36:06 -05002521 if (leftType.isMatrix() && rightType.isMatrix()) {
Ethan Nicholas49465b42019-04-17 12:22:21 -04002522 SkASSERT(leftType == rightType);
John Stiles43b593c2021-05-13 22:03:27 -04002523 return this->writeComponentwiseMatrixBinary(leftType, lhs, rhs, SpvOpFAdd, out);
Ethan Nicholas0df21132018-07-10 09:37:51 -04002524 }
Greg Daniel64773e62016-11-22 09:44:03 -05002525 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs, SpvOpFAdd,
ethannicholasb3058bd2016-07-01 08:22:01 -07002526 SpvOpIAdd, SpvOpIAdd, SpvOpUndef, out);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002527 case Token::Kind::TK_MINUS:
John Stiles9aeed132020-11-24 17:36:06 -05002528 if (leftType.isMatrix() && rightType.isMatrix()) {
Ethan Nicholas49465b42019-04-17 12:22:21 -04002529 SkASSERT(leftType == rightType);
John Stiles43b593c2021-05-13 22:03:27 -04002530 return this->writeComponentwiseMatrixBinary(leftType, lhs, rhs, SpvOpFSub, out);
Ethan Nicholas0df21132018-07-10 09:37:51 -04002531 }
Greg Daniel64773e62016-11-22 09:44:03 -05002532 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs, SpvOpFSub,
ethannicholasb3058bd2016-07-01 08:22:01 -07002533 SpvOpISub, SpvOpISub, SpvOpUndef, out);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002534 case Token::Kind::TK_STAR:
John Stiles9aeed132020-11-24 17:36:06 -05002535 if (leftType.isMatrix() && rightType.isMatrix()) {
ethannicholasb3058bd2016-07-01 08:22:01 -07002536 // matrix multiply
Ethan Nicholas7f015882021-03-23 14:16:52 -04002537 SpvId result = this->nextId(&resultType);
ethannicholasb3058bd2016-07-01 08:22:01 -07002538 this->writeInstruction(SpvOpMatrixTimesMatrix, this->getType(resultType), result,
2539 lhs, rhs, out);
2540 return result;
2541 }
Greg Daniel64773e62016-11-22 09:44:03 -05002542 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs, SpvOpFMul,
ethannicholasb3058bd2016-07-01 08:22:01 -07002543 SpvOpIMul, SpvOpIMul, SpvOpUndef, out);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002544 case Token::Kind::TK_SLASH:
John Stilesbdf3bb72021-05-17 09:34:23 -04002545 if (leftType.isMatrix() && rightType.isMatrix()) {
2546 SkASSERT(leftType == rightType);
2547 return this->writeComponentwiseMatrixBinary(leftType, lhs, rhs, SpvOpFDiv, out);
2548 }
Greg Daniel64773e62016-11-22 09:44:03 -05002549 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs, SpvOpFDiv,
ethannicholasb3058bd2016-07-01 08:22:01 -07002550 SpvOpSDiv, SpvOpUDiv, SpvOpUndef, out);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002551 case Token::Kind::TK_PERCENT:
Ethan Nicholasb3d0f7c2017-05-17 13:13:21 -04002552 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs, SpvOpFMod,
2553 SpvOpSMod, SpvOpUMod, SpvOpUndef, out);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002554 case Token::Kind::TK_SHL:
Ethan Nicholasfd444be2017-07-05 10:05:54 -04002555 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs, SpvOpUndef,
2556 SpvOpShiftLeftLogical, SpvOpShiftLeftLogical,
2557 SpvOpUndef, out);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002558 case Token::Kind::TK_SHR:
Ethan Nicholasfd444be2017-07-05 10:05:54 -04002559 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs, SpvOpUndef,
2560 SpvOpShiftRightArithmetic, SpvOpShiftRightLogical,
2561 SpvOpUndef, out);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002562 case Token::Kind::TK_BITWISEAND:
Ethan Nicholasfd444be2017-07-05 10:05:54 -04002563 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs, SpvOpUndef,
2564 SpvOpBitwiseAnd, SpvOpBitwiseAnd, SpvOpUndef, out);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002565 case Token::Kind::TK_BITWISEOR:
Ethan Nicholasfd444be2017-07-05 10:05:54 -04002566 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs, SpvOpUndef,
2567 SpvOpBitwiseOr, SpvOpBitwiseOr, SpvOpUndef, out);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002568 case Token::Kind::TK_BITWISEXOR:
Ethan Nicholasfd444be2017-07-05 10:05:54 -04002569 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs, SpvOpUndef,
2570 SpvOpBitwiseXor, SpvOpBitwiseXor, SpvOpUndef, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002571 default:
Ethan Nicholas39f6da42021-08-23 13:10:07 -04002572 fContext.fErrors->error(0, "unsupported token");
Ethan Nicholas49465b42019-04-17 12:22:21 -04002573 return -1;
ethannicholasb3058bd2016-07-01 08:22:01 -07002574 }
2575}
2576
John Stiles35092102021-04-08 23:30:51 -04002577SpvId SPIRVCodeGenerator::writeArrayComparison(const Type& arrayType, SpvId lhs, Operator op,
2578 SpvId rhs, OutputStream& out) {
2579 // The inputs must be arrays, and the op must be == or !=.
2580 SkASSERT(op.kind() == Token::Kind::TK_EQEQ || op.kind() == Token::Kind::TK_NEQ);
2581 SkASSERT(arrayType.isArray());
2582 const Type& componentType = arrayType.componentType();
2583 const SpvId componentTypeId = this->getType(componentType);
2584 const int arraySize = arrayType.columns();
2585 SkASSERT(arraySize > 0);
2586
2587 // Synthesize equality checks for each item in the array.
2588 const Type& boolType = *fContext.fTypes.fBool;
2589 SpvId allComparisons = (SpvId)-1;
2590 for (int index = 0; index < arraySize; ++index) {
2591 // Get the left and right item in the array.
2592 SpvId itemL = this->nextId(&componentType);
2593 this->writeInstruction(SpvOpCompositeExtract, componentTypeId, itemL, lhs, index, out);
2594 SpvId itemR = this->nextId(&componentType);
2595 this->writeInstruction(SpvOpCompositeExtract, componentTypeId, itemR, rhs, index, out);
2596 // Use `writeBinaryExpression` with the requested == or != operator on these items.
2597 SpvId comparison = this->writeBinaryExpression(componentType, itemL, op,
2598 componentType, itemR, boolType, out);
2599 // Merge this comparison result with all the other comparisons we've done.
2600 allComparisons = this->mergeComparisons(comparison, allComparisons, op, out);
2601 }
2602 return allComparisons;
2603}
2604
John Stilesbc5c2a02021-04-08 11:44:53 -04002605SpvId SPIRVCodeGenerator::writeStructComparison(const Type& structType, SpvId lhs, Operator op,
2606 SpvId rhs, OutputStream& out) {
2607 // The inputs must be structs containing fields, and the op must be == or !=.
John Stilesbc5c2a02021-04-08 11:44:53 -04002608 SkASSERT(op.kind() == Token::Kind::TK_EQEQ || op.kind() == Token::Kind::TK_NEQ);
John Stiles35092102021-04-08 23:30:51 -04002609 SkASSERT(structType.isStruct());
John Stilesbc5c2a02021-04-08 11:44:53 -04002610 const std::vector<Type::Field>& fields = structType.fields();
2611 SkASSERT(!fields.empty());
2612
2613 // Synthesize equality checks for each field in the struct.
2614 const Type& boolType = *fContext.fTypes.fBool;
John Stilesbc5c2a02021-04-08 11:44:53 -04002615 SpvId allComparisons = (SpvId)-1;
2616 for (int index = 0; index < (int)fields.size(); ++index) {
2617 // Get the left and right versions of this field.
2618 const Type& fieldType = *fields[index].fType;
John Stiles35092102021-04-08 23:30:51 -04002619 const SpvId fieldTypeId = this->getType(fieldType);
John Stilesbc5c2a02021-04-08 11:44:53 -04002620
2621 SpvId fieldL = this->nextId(&fieldType);
2622 this->writeInstruction(SpvOpCompositeExtract, fieldTypeId, fieldL, lhs, index, out);
2623 SpvId fieldR = this->nextId(&fieldType);
2624 this->writeInstruction(SpvOpCompositeExtract, fieldTypeId, fieldR, rhs, index, out);
2625 // Use `writeBinaryExpression` with the requested == or != operator on these fields.
2626 SpvId comparison = this->writeBinaryExpression(fieldType, fieldL, op, fieldType, fieldR,
2627 boolType, out);
John Stiles35092102021-04-08 23:30:51 -04002628 // Merge this comparison result with all the other comparisons we've done.
2629 allComparisons = this->mergeComparisons(comparison, allComparisons, op, out);
John Stilesbc5c2a02021-04-08 11:44:53 -04002630 }
2631 return allComparisons;
2632}
2633
John Stiles35092102021-04-08 23:30:51 -04002634SpvId SPIRVCodeGenerator::mergeComparisons(SpvId comparison, SpvId allComparisons, Operator op,
2635 OutputStream& out) {
2636 // If this is the first entry, we don't need to merge comparison results with anything.
2637 if (allComparisons == (SpvId)-1) {
2638 return comparison;
2639 }
2640 // Use LogicalAnd or LogicalOr to combine the comparison with all the other comparisons.
2641 const Type& boolType = *fContext.fTypes.fBool;
2642 SpvId boolTypeId = this->getType(boolType);
2643 SpvId logicalOp = this->nextId(&boolType);
2644 switch (op.kind()) {
2645 case Token::Kind::TK_EQEQ:
2646 this->writeInstruction(SpvOpLogicalAnd, boolTypeId, logicalOp,
2647 comparison, allComparisons, out);
2648 break;
2649 case Token::Kind::TK_NEQ:
2650 this->writeInstruction(SpvOpLogicalOr, boolTypeId, logicalOp,
2651 comparison, allComparisons, out);
2652 break;
2653 default:
2654 SkDEBUGFAILF("mergeComparisons only supports == and !=, not %s", op.operatorName());
2655 return (SpvId)-1;
2656 }
2657 return logicalOp;
2658}
2659
John Stilesbc5c2a02021-04-08 11:44:53 -04002660static float division_by_literal_value(Operator op, const Expression& right) {
2661 // If this is a division by a literal value, returns that literal value. Otherwise, returns 0.
John Stiles7591d4b2021-09-13 13:32:06 -04002662 if (op.kind() == Token::Kind::TK_SLASH && right.isFloatLiteral()) {
2663 float rhsValue = right.as<Literal>().floatValue();
John Stilesbc5c2a02021-04-08 11:44:53 -04002664 if (std::isfinite(rhsValue)) {
2665 return rhsValue;
2666 }
2667 }
2668 return 0.0f;
2669}
2670
Ethan Nicholas49465b42019-04-17 12:22:21 -04002671SpvId SPIRVCodeGenerator::writeBinaryExpression(const BinaryExpression& b, OutputStream& out) {
John Stiles2396fb82021-03-25 11:44:55 -04002672 const Expression* left = b.left().get();
2673 const Expression* right = b.right().get();
John Stiles45990502021-02-16 10:55:27 -05002674 Operator op = b.getOperator();
John Stilesbc5c2a02021-04-08 11:44:53 -04002675
John Stiles45990502021-02-16 10:55:27 -05002676 switch (op.kind()) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002677 case Token::Kind::TK_EQ: {
John Stilesbc5c2a02021-04-08 11:44:53 -04002678 // Handles assignment.
John Stiles2396fb82021-03-25 11:44:55 -04002679 SpvId rhs = this->writeExpression(*right, out);
2680 this->getLValue(*left, out)->store(rhs, out);
Ethan Nicholas49465b42019-04-17 12:22:21 -04002681 return rhs;
2682 }
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002683 case Token::Kind::TK_LOGICALAND:
John Stilesbc5c2a02021-04-08 11:44:53 -04002684 // Handles short-circuiting; we don't necessarily evaluate both LHS and RHS.
2685 return this->writeLogicalAnd(*b.left(), *b.right(), out);
2686
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002687 case Token::Kind::TK_LOGICALOR:
John Stilesbc5c2a02021-04-08 11:44:53 -04002688 // Handles short-circuiting; we don't necessarily evaluate both LHS and RHS.
2689 return this->writeLogicalOr(*b.left(), *b.right(), out);
2690
Ethan Nicholas49465b42019-04-17 12:22:21 -04002691 default:
2692 break;
2693 }
2694
2695 std::unique_ptr<LValue> lvalue;
2696 SpvId lhs;
John Stiles45990502021-02-16 10:55:27 -05002697 if (op.isAssignment()) {
John Stiles2396fb82021-03-25 11:44:55 -04002698 lvalue = this->getLValue(*left, out);
Ethan Nicholas49465b42019-04-17 12:22:21 -04002699 lhs = lvalue->load(out);
2700 } else {
2701 lvalue = nullptr;
John Stiles2396fb82021-03-25 11:44:55 -04002702 lhs = this->writeExpression(*left, out);
Ethan Nicholas49465b42019-04-17 12:22:21 -04002703 }
John Stiles2396fb82021-03-25 11:44:55 -04002704
John Stilesbc5c2a02021-04-08 11:44:53 -04002705 SpvId rhs;
2706 float rhsValue = division_by_literal_value(op, *right);
2707 if (rhsValue != 0.0f) {
2708 // Rewrite floating-point division by a literal into multiplication by the reciprocal.
2709 // This converts `expr / 2` into `expr * 0.5`
2710 // This improves codegen, especially for certain types of divides (e.g. vector/scalar).
2711 op = Operator(Token::Kind::TK_STAR);
Ethan Nicholas89cfde12021-09-27 11:20:34 -04002712 Literal reciprocal{right->fLine, 1.0f / rhsValue, &right->type()};
John Stilesbc5c2a02021-04-08 11:44:53 -04002713 rhs = this->writeExpression(reciprocal, out);
2714 } else {
2715 // Write the right-hand side expression normally.
John Stiles2396fb82021-03-25 11:44:55 -04002716 rhs = this->writeExpression(*right, out);
2717 }
2718
2719 SpvId result = this->writeBinaryExpression(left->type(), lhs, op.removeAssignment(),
2720 right->type(), rhs, b.type(), out);
Ethan Nicholas49465b42019-04-17 12:22:21 -04002721 if (lvalue) {
2722 lvalue->store(result, out);
2723 }
2724 return result;
2725}
2726
John Stilesbc5c2a02021-04-08 11:44:53 -04002727SpvId SPIRVCodeGenerator::writeLogicalAnd(const Expression& left, const Expression& right,
2728 OutputStream& out) {
Ethan Nicholas89cfde12021-09-27 11:20:34 -04002729 Literal falseLiteral(/*line=*/-1, /*value=*/false, fContext.fTypes.fBool.get());
John Stiles7591d4b2021-09-13 13:32:06 -04002730 SpvId falseConstant = this->writeLiteral(falseLiteral);
John Stilesbc5c2a02021-04-08 11:44:53 -04002731 SpvId lhs = this->writeExpression(left, out);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002732 SpvId rhsLabel = this->nextId(nullptr);
2733 SpvId end = this->nextId(nullptr);
ethannicholasb3058bd2016-07-01 08:22:01 -07002734 SpvId lhsBlock = fCurrentBlock;
2735 this->writeInstruction(SpvOpSelectionMerge, end, SpvSelectionControlMaskNone, out);
2736 this->writeInstruction(SpvOpBranchConditional, lhs, rhsLabel, end, out);
2737 this->writeLabel(rhsLabel, out);
John Stilesbc5c2a02021-04-08 11:44:53 -04002738 SpvId rhs = this->writeExpression(right, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002739 SpvId rhsBlock = fCurrentBlock;
2740 this->writeInstruction(SpvOpBranch, end, out);
2741 this->writeLabel(end, out);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002742 SpvId result = this->nextId(nullptr);
John Stiles54e7c052021-01-11 14:22:36 -05002743 this->writeInstruction(SpvOpPhi, this->getType(*fContext.fTypes.fBool), result, falseConstant,
ethannicholasd598f792016-07-25 10:08:54 -07002744 lhsBlock, rhs, rhsBlock, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002745 return result;
2746}
2747
John Stilesbc5c2a02021-04-08 11:44:53 -04002748SpvId SPIRVCodeGenerator::writeLogicalOr(const Expression& left, const Expression& right,
2749 OutputStream& out) {
Ethan Nicholas89cfde12021-09-27 11:20:34 -04002750 Literal trueLiteral(/*line=*/-1, /*value=*/true, fContext.fTypes.fBool.get());
John Stiles7591d4b2021-09-13 13:32:06 -04002751 SpvId trueConstant = this->writeLiteral(trueLiteral);
John Stilesbc5c2a02021-04-08 11:44:53 -04002752 SpvId lhs = this->writeExpression(left, out);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002753 SpvId rhsLabel = this->nextId(nullptr);
2754 SpvId end = this->nextId(nullptr);
ethannicholasb3058bd2016-07-01 08:22:01 -07002755 SpvId lhsBlock = fCurrentBlock;
2756 this->writeInstruction(SpvOpSelectionMerge, end, SpvSelectionControlMaskNone, out);
2757 this->writeInstruction(SpvOpBranchConditional, lhs, end, rhsLabel, out);
2758 this->writeLabel(rhsLabel, out);
John Stilesbc5c2a02021-04-08 11:44:53 -04002759 SpvId rhs = this->writeExpression(right, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002760 SpvId rhsBlock = fCurrentBlock;
2761 this->writeInstruction(SpvOpBranch, end, out);
2762 this->writeLabel(end, out);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002763 SpvId result = this->nextId(nullptr);
John Stiles54e7c052021-01-11 14:22:36 -05002764 this->writeInstruction(SpvOpPhi, this->getType(*fContext.fTypes.fBool), result, trueConstant,
ethannicholasd598f792016-07-25 10:08:54 -07002765 lhsBlock, rhs, rhsBlock, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002766 return result;
2767}
2768
Ethan Nicholas0df1b042017-03-31 13:56:23 -04002769SpvId SPIRVCodeGenerator::writeTernaryExpression(const TernaryExpression& t, OutputStream& out) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04002770 const Type& type = t.type();
Ethan Nicholasdd218162020-10-08 05:48:01 -04002771 SpvId test = this->writeExpression(*t.test(), out);
2772 if (t.ifTrue()->type().columns() == 1 &&
2773 t.ifTrue()->isCompileTimeConstant() &&
2774 t.ifFalse()->isCompileTimeConstant()) {
ethannicholasb3058bd2016-07-01 08:22:01 -07002775 // both true and false are constants, can just use OpSelect
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002776 SpvId result = this->nextId(nullptr);
Ethan Nicholasdd218162020-10-08 05:48:01 -04002777 SpvId trueId = this->writeExpression(*t.ifTrue(), out);
2778 SpvId falseId = this->writeExpression(*t.ifFalse(), out);
Ethan Nicholas30d30222020-09-11 12:27:26 -04002779 this->writeInstruction(SpvOpSelect, this->getType(type), result, test, trueId, falseId,
ethannicholasb3058bd2016-07-01 08:22:01 -07002780 out);
2781 return result;
2782 }
Greg Daniel64773e62016-11-22 09:44:03 -05002783 // was originally using OpPhi to choose the result, but for some reason that is crashing on
ethannicholasb3058bd2016-07-01 08:22:01 -07002784 // Adreno. Switched to storing the result in a temp variable as glslang does.
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002785 SpvId var = this->nextId(nullptr);
Ethan Nicholas30d30222020-09-11 12:27:26 -04002786 this->writeInstruction(SpvOpVariable, this->getPointerType(type, SpvStorageClassFunction),
ethannicholasd598f792016-07-25 10:08:54 -07002787 var, SpvStorageClassFunction, fVariableBuffer);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002788 SpvId trueLabel = this->nextId(nullptr);
2789 SpvId falseLabel = this->nextId(nullptr);
2790 SpvId end = this->nextId(nullptr);
ethannicholasb3058bd2016-07-01 08:22:01 -07002791 this->writeInstruction(SpvOpSelectionMerge, end, SpvSelectionControlMaskNone, out);
2792 this->writeInstruction(SpvOpBranchConditional, test, trueLabel, falseLabel, out);
2793 this->writeLabel(trueLabel, out);
Ethan Nicholasdd218162020-10-08 05:48:01 -04002794 this->writeInstruction(SpvOpStore, var, this->writeExpression(*t.ifTrue(), out), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002795 this->writeInstruction(SpvOpBranch, end, out);
2796 this->writeLabel(falseLabel, out);
Ethan Nicholasdd218162020-10-08 05:48:01 -04002797 this->writeInstruction(SpvOpStore, var, this->writeExpression(*t.ifFalse(), out), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002798 this->writeInstruction(SpvOpBranch, end, out);
2799 this->writeLabel(end, out);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002800 SpvId result = this->nextId(&type);
Ethan Nicholas30d30222020-09-11 12:27:26 -04002801 this->writeInstruction(SpvOpLoad, this->getType(type), result, var, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002802 return result;
2803}
2804
Ethan Nicholas0df1b042017-03-31 13:56:23 -04002805SpvId SPIRVCodeGenerator::writePrefixExpression(const PrefixExpression& p, OutputStream& out) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04002806 const Type& type = p.type();
John Stiles45990502021-02-16 10:55:27 -05002807 if (p.getOperator().kind() == Token::Kind::TK_MINUS) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002808 SpvId result = this->nextId(&type);
Ethan Nicholas30d30222020-09-11 12:27:26 -04002809 SpvId typeId = this->getType(type);
Ethan Nicholas444ccc62020-10-09 10:16:22 -04002810 SpvId expr = this->writeExpression(*p.operand(), out);
Ethan Nicholas30d30222020-09-11 12:27:26 -04002811 if (is_float(fContext, type)) {
ethannicholasb3058bd2016-07-01 08:22:01 -07002812 this->writeInstruction(SpvOpFNegate, typeId, result, expr, out);
John Stiles43ac7e62021-08-25 12:43:22 -04002813 } else if (is_signed(fContext, type) || is_unsigned(fContext, type)) {
ethannicholasb3058bd2016-07-01 08:22:01 -07002814 this->writeInstruction(SpvOpSNegate, typeId, result, expr, out);
2815 } else {
John Stileseada7bc2021-02-02 16:29:32 -05002816 SkDEBUGFAILF("unsupported prefix expression %s", p.description().c_str());
Brian Salomon23356442018-11-30 15:33:19 -05002817 }
ethannicholasb3058bd2016-07-01 08:22:01 -07002818 return result;
2819 }
John Stiles45990502021-02-16 10:55:27 -05002820 switch (p.getOperator().kind()) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002821 case Token::Kind::TK_PLUS:
Ethan Nicholas444ccc62020-10-09 10:16:22 -04002822 return this->writeExpression(*p.operand(), out);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002823 case Token::Kind::TK_PLUSPLUS: {
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,
Greg Daniel64773e62016-11-22 09:44:03 -05002827 SpvOpFAdd, SpvOpIAdd, SpvOpIAdd, SpvOpUndef,
ethannicholasb3058bd2016-07-01 08:22:01 -07002828 out);
2829 lv->store(result, out);
2830 return result;
2831 }
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002832 case Token::Kind::TK_MINUSMINUS: {
Ethan Nicholas444ccc62020-10-09 10:16:22 -04002833 std::unique_ptr<LValue> lv = this->getLValue(*p.operand(), out);
Ethan Nicholas30d30222020-09-11 12:27:26 -04002834 SpvId one = this->writeExpression(*create_literal_1(fContext, type), out);
2835 SpvId result = this->writeBinaryOperation(type, type, lv->load(out), one, SpvOpFSub,
2836 SpvOpISub, SpvOpISub, SpvOpUndef, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002837 lv->store(result, out);
2838 return result;
2839 }
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002840 case Token::Kind::TK_LOGICALNOT: {
John Stiles4a7dc462020-11-25 11:08:08 -05002841 SkASSERT(p.operand()->type().isBoolean());
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002842 SpvId result = this->nextId(nullptr);
Ethan Nicholas444ccc62020-10-09 10:16:22 -04002843 this->writeInstruction(SpvOpLogicalNot, this->getType(type), result,
2844 this->writeExpression(*p.operand(), out), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002845 return result;
2846 }
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002847 case Token::Kind::TK_BITWISENOT: {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002848 SpvId result = this->nextId(nullptr);
Ethan Nicholas444ccc62020-10-09 10:16:22 -04002849 this->writeInstruction(SpvOpNot, this->getType(type), result,
2850 this->writeExpression(*p.operand(), out), out);
ethannicholas5961bc92016-10-12 06:39:56 -07002851 return result;
2852 }
ethannicholasb3058bd2016-07-01 08:22:01 -07002853 default:
John Stileseada7bc2021-02-02 16:29:32 -05002854 SkDEBUGFAILF("unsupported prefix expression: %s", p.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -05002855 return -1;
ethannicholasb3058bd2016-07-01 08:22:01 -07002856 }
2857}
2858
Ethan Nicholas0df1b042017-03-31 13:56:23 -04002859SpvId SPIRVCodeGenerator::writePostfixExpression(const PostfixExpression& p, OutputStream& out) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04002860 const Type& type = p.type();
Ethan Nicholas444ccc62020-10-09 10:16:22 -04002861 std::unique_ptr<LValue> lv = this->getLValue(*p.operand(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002862 SpvId result = lv->load(out);
Ethan Nicholas30d30222020-09-11 12:27:26 -04002863 SpvId one = this->writeExpression(*create_literal_1(fContext, type), out);
John Stiles45990502021-02-16 10:55:27 -05002864 switch (p.getOperator().kind()) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002865 case Token::Kind::TK_PLUSPLUS: {
Ethan Nicholas30d30222020-09-11 12:27:26 -04002866 SpvId temp = this->writeBinaryOperation(type, type, result, one, SpvOpFAdd,
ethannicholasb3058bd2016-07-01 08:22:01 -07002867 SpvOpIAdd, SpvOpIAdd, SpvOpUndef, out);
2868 lv->store(temp, out);
2869 return result;
2870 }
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002871 case Token::Kind::TK_MINUSMINUS: {
Ethan Nicholas30d30222020-09-11 12:27:26 -04002872 SpvId temp = this->writeBinaryOperation(type, type, result, one, SpvOpFSub,
ethannicholasb3058bd2016-07-01 08:22:01 -07002873 SpvOpISub, SpvOpISub, SpvOpUndef, out);
2874 lv->store(temp, out);
2875 return result;
2876 }
2877 default:
John Stileseada7bc2021-02-02 16:29:32 -05002878 SkDEBUGFAILF("unsupported postfix expression %s", p.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -05002879 return -1;
ethannicholasb3058bd2016-07-01 08:22:01 -07002880 }
2881}
2882
John Stiles7591d4b2021-09-13 13:32:06 -04002883SpvId SPIRVCodeGenerator::writeLiteral(const Literal& l) {
2884 int32_t valueBits;
2885 if (l.isFloatLiteral()) {
2886 float value = l.floatValue();
2887 memcpy(&valueBits, &value, sizeof(valueBits));
2888 } else if (l.isIntLiteral()) {
2889 // intValue() returns a 64-bit signed value, which will be truncated here.
2890 // The hash key also contains the numberKind, so -1 won't overlap with 0xFFFFFFFFu.
2891 valueBits = l.intValue();
ethannicholasb3058bd2016-07-01 08:22:01 -07002892 } else {
John Stiles7591d4b2021-09-13 13:32:06 -04002893 valueBits = l.boolValue();
2894 }
2895
2896 SPIRVNumberConstant key{valueBits, l.type().numberKind()};
2897 auto [iter, newlyCreated] = fNumberConstants.insert({key, (SpvId)-1});
2898 if (newlyCreated) {
2899 SpvId result = this->nextId(nullptr);
2900 iter->second = result;
2901
2902 if (l.isBoolLiteral()) {
2903 this->writeInstruction(l.boolValue() ? SpvOpConstantTrue : SpvOpConstantFalse,
2904 this->getType(l.type()), result, fConstantBuffer);
2905 } else {
2906 this->writeInstruction(SpvOpConstant, this->getType(l.type()), result,
2907 (SpvId)valueBits, fConstantBuffer);
ethannicholasb3058bd2016-07-01 08:22:01 -07002908 }
ethannicholasb3058bd2016-07-01 08:22:01 -07002909 }
ethannicholasb3058bd2016-07-01 08:22:01 -07002910
John Stilesacb091f2021-01-06 11:57:58 -05002911 return iter->second;
ethannicholasb3058bd2016-07-01 08:22:01 -07002912}
2913
Ethan Nicholas0df1b042017-03-31 13:56:23 -04002914SpvId SPIRVCodeGenerator::writeFunctionStart(const FunctionDeclaration& f, OutputStream& out) {
ethannicholasd598f792016-07-25 10:08:54 -07002915 SpvId result = fFunctionMap[&f];
John Stilesb5db4822021-01-21 13:04:40 -05002916 SpvId returnTypeId = this->getType(f.returnType());
2917 SpvId functionTypeId = this->getFunctionType(f);
2918 this->writeInstruction(SpvOpFunction, returnTypeId, result,
2919 SpvFunctionControlMaskNone, functionTypeId, out);
John Stilesf9e85512021-03-22 12:05:31 -04002920 String mangledName = f.mangledName();
2921 this->writeInstruction(SpvOpName,
2922 result,
Ethan Nicholas962dec42021-06-10 13:06:39 -04002923 skstd::string_view(mangledName.c_str(), mangledName.size()),
John Stilesf9e85512021-03-22 12:05:31 -04002924 fNameBuffer);
2925 for (const Variable* parameter : f.parameters()) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002926 SpvId id = this->nextId(nullptr);
John Stilesf9e85512021-03-22 12:05:31 -04002927 fVariableMap[parameter] = id;
2928 SpvId type = this->getPointerType(parameter->type(), SpvStorageClassFunction);
ethannicholasb3058bd2016-07-01 08:22:01 -07002929 this->writeInstruction(SpvOpFunctionParameter, type, id, out);
2930 }
2931 return result;
2932}
2933
Ethan Nicholas0df1b042017-03-31 13:56:23 -04002934SpvId SPIRVCodeGenerator::writeFunction(const FunctionDefinition& f, OutputStream& out) {
2935 fVariableBuffer.reset();
Ethan Nicholas0a5d0962020-10-14 13:33:18 -04002936 SpvId result = this->writeFunctionStart(f.declaration(), out);
Ethan Nicholas7fb39362020-12-16 15:25:19 -05002937 fCurrentBlock = 0;
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002938 this->writeLabel(this->nextId(nullptr), out);
Ethan Nicholas0df1b042017-03-31 13:56:23 -04002939 StringStream bodyBuffer;
John Stiles0693fb82021-01-22 18:27:52 -05002940 this->writeBlock(f.body()->as<Block>(), bodyBuffer);
Ethan Nicholas0df1b042017-03-31 13:56:23 -04002941 write_stringstream(fVariableBuffer, out);
John Stilese8da4d22021-03-24 09:19:45 -04002942 if (f.declaration().isMain()) {
Ethan Nicholas8eb64d32018-12-21 14:50:42 -05002943 write_stringstream(fGlobalInitializersBuffer, out);
2944 }
Ethan Nicholas0df1b042017-03-31 13:56:23 -04002945 write_stringstream(bodyBuffer, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002946 if (fCurrentBlock) {
John Stiles2558c462021-03-16 17:49:20 -04002947 if (f.declaration().returnType().isVoid()) {
Ethan Nicholas70a44b22017-11-30 09:09:16 -05002948 this->writeInstruction(SpvOpReturn, out);
2949 } else {
2950 this->writeInstruction(SpvOpUnreachable, out);
2951 }
ethannicholasb3058bd2016-07-01 08:22:01 -07002952 }
2953 this->writeInstruction(SpvOpFunctionEnd, out);
2954 return result;
2955}
2956
2957void SPIRVCodeGenerator::writeLayout(const Layout& layout, SpvId target) {
2958 if (layout.fLocation >= 0) {
Greg Daniel64773e62016-11-22 09:44:03 -05002959 this->writeInstruction(SpvOpDecorate, target, SpvDecorationLocation, layout.fLocation,
ethannicholasb3058bd2016-07-01 08:22:01 -07002960 fDecorationBuffer);
2961 }
2962 if (layout.fBinding >= 0) {
Greg Daniel64773e62016-11-22 09:44:03 -05002963 this->writeInstruction(SpvOpDecorate, target, SpvDecorationBinding, layout.fBinding,
ethannicholasb3058bd2016-07-01 08:22:01 -07002964 fDecorationBuffer);
2965 }
2966 if (layout.fIndex >= 0) {
Greg Daniel64773e62016-11-22 09:44:03 -05002967 this->writeInstruction(SpvOpDecorate, target, SpvDecorationIndex, layout.fIndex,
ethannicholasb3058bd2016-07-01 08:22:01 -07002968 fDecorationBuffer);
2969 }
2970 if (layout.fSet >= 0) {
Greg Daniel64773e62016-11-22 09:44:03 -05002971 this->writeInstruction(SpvOpDecorate, target, SpvDecorationDescriptorSet, layout.fSet,
ethannicholasb3058bd2016-07-01 08:22:01 -07002972 fDecorationBuffer);
2973 }
Greg Daniel64773e62016-11-22 09:44:03 -05002974 if (layout.fInputAttachmentIndex >= 0) {
2975 this->writeInstruction(SpvOpDecorate, target, SpvDecorationInputAttachmentIndex,
2976 layout.fInputAttachmentIndex, fDecorationBuffer);
Ethan Nicholasbe1099f2018-01-11 16:09:05 -05002977 fCapabilities |= (((uint64_t) 1) << SpvCapabilityInputAttachment);
Greg Daniel64773e62016-11-22 09:44:03 -05002978 }
Brian Osman99ddd2a2021-08-27 11:21:12 -04002979 if (layout.fBuiltin >= 0 && layout.fBuiltin != SK_FRAGCOLOR_BUILTIN) {
Greg Daniel64773e62016-11-22 09:44:03 -05002980 this->writeInstruction(SpvOpDecorate, target, SpvDecorationBuiltIn, layout.fBuiltin,
ethannicholasb3058bd2016-07-01 08:22:01 -07002981 fDecorationBuffer);
2982 }
2983}
2984
2985void SPIRVCodeGenerator::writeLayout(const Layout& layout, SpvId target, int member) {
2986 if (layout.fLocation >= 0) {
Greg Daniel64773e62016-11-22 09:44:03 -05002987 this->writeInstruction(SpvOpMemberDecorate, target, member, SpvDecorationLocation,
ethannicholasb3058bd2016-07-01 08:22:01 -07002988 layout.fLocation, fDecorationBuffer);
2989 }
2990 if (layout.fBinding >= 0) {
Greg Daniel64773e62016-11-22 09:44:03 -05002991 this->writeInstruction(SpvOpMemberDecorate, target, member, SpvDecorationBinding,
ethannicholasb3058bd2016-07-01 08:22:01 -07002992 layout.fBinding, fDecorationBuffer);
2993 }
2994 if (layout.fIndex >= 0) {
Greg Daniel64773e62016-11-22 09:44:03 -05002995 this->writeInstruction(SpvOpMemberDecorate, target, member, SpvDecorationIndex,
ethannicholasb3058bd2016-07-01 08:22:01 -07002996 layout.fIndex, fDecorationBuffer);
2997 }
2998 if (layout.fSet >= 0) {
Greg Daniel64773e62016-11-22 09:44:03 -05002999 this->writeInstruction(SpvOpMemberDecorate, target, member, SpvDecorationDescriptorSet,
ethannicholasb3058bd2016-07-01 08:22:01 -07003000 layout.fSet, fDecorationBuffer);
3001 }
Greg Daniel64773e62016-11-22 09:44:03 -05003002 if (layout.fInputAttachmentIndex >= 0) {
3003 this->writeInstruction(SpvOpDecorate, target, member, SpvDecorationInputAttachmentIndex,
3004 layout.fInputAttachmentIndex, fDecorationBuffer);
3005 }
ethannicholasb3058bd2016-07-01 08:22:01 -07003006 if (layout.fBuiltin >= 0) {
Greg Daniel64773e62016-11-22 09:44:03 -05003007 this->writeInstruction(SpvOpMemberDecorate, target, member, SpvDecorationBuiltIn,
ethannicholasb3058bd2016-07-01 08:22:01 -07003008 layout.fBuiltin, fDecorationBuffer);
3009 }
3010}
3011
Brian Osman2a4c0fb2021-01-22 13:41:40 -05003012MemoryLayout SPIRVCodeGenerator::memoryLayoutForVariable(const Variable& v) const {
Brian Osman2a4c0fb2021-01-22 13:41:40 -05003013 bool pushConstant = ((v.modifiers().fLayout.fFlags & Layout::kPushConstant_Flag) != 0);
Brian Osman58ee8982021-02-18 15:39:38 -05003014 return pushConstant ? MemoryLayout(MemoryLayout::k430_Standard) : fDefaultLayout;
Brian Osman2a4c0fb2021-01-22 13:41:40 -05003015}
3016
Brian Salomond8d85b92021-07-07 09:41:17 -04003017SpvId SPIRVCodeGenerator::writeInterfaceBlock(const InterfaceBlock& intf, bool appendRTFlip) {
Brian Osman2a4c0fb2021-01-22 13:41:40 -05003018 MemoryLayout memoryLayout = this->memoryLayoutForVariable(intf.variable());
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04003019 SpvId result = this->nextId(nullptr);
Brian Salomond8d85b92021-07-07 09:41:17 -04003020 const Variable& intfVar = intf.variable();
3021 const Type& type = intfVar.type();
3022 if (!MemoryLayout::LayoutIsSupported(type)) {
Ethan Nicholas89cfde12021-09-27 11:20:34 -04003023 fContext.fErrors->error(type.fLine, "type '" + type.name() + "' is not permitted here");
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04003024 return this->nextId(nullptr);
John Stiles0023c0c2020-11-16 13:32:18 -05003025 }
John Stiles9485b552021-01-27 11:47:00 -05003026 SpvStorageClass_ storageClass = get_storage_class(intf.variable(), SpvStorageClassFunction);
John Stilesded41aa2021-08-05 12:19:35 -04003027 if (fProgram.fInputs.fUseFlipRTUniform && appendRTFlip && type.isStruct()) {
Brian Salomond8d85b92021-07-07 09:41:17 -04003028 // We can only have one interface block (because we use push_constant and that is limited
3029 // to one per program), so we need to append rtflip to this one rather than synthesize an
3030 // entirely new block when the variable is referenced. And we can't modify the existing
3031 // block, so we instead create a modified copy of it and write that.
3032 std::vector<Type::Field> fields = type.fields();
3033 fields.emplace_back(Modifiers(Layout(/*flags=*/0,
3034 /*location=*/-1,
3035 fProgram.fConfig->fSettings.fRTFlipOffset,
3036 /*binding=*/-1,
3037 /*index=*/-1,
3038 /*set=*/-1,
3039 /*builtin=*/-1,
Brian Osman99ddd2a2021-08-27 11:21:12 -04003040 /*inputAttachmentIndex=*/-1),
Brian Salomond8d85b92021-07-07 09:41:17 -04003041 /*flags=*/0),
3042 SKSL_RTFLIP_NAME,
3043 fContext.fTypes.fFloat2.get());
John Stiles0cac5ed2021-08-06 11:40:39 -04003044 {
3045 AutoAttachPoolToThread attach(fProgram.fPool.get());
3046 const Type* rtFlipStructType = fProgram.fSymbols->takeOwnershipOfSymbol(
Ethan Nicholas89cfde12021-09-27 11:20:34 -04003047 Type::MakeStructType(type.fLine, type.name(), std::move(fields)));
John Stiles0cac5ed2021-08-06 11:40:39 -04003048 const Variable* modifiedVar = fProgram.fSymbols->takeOwnershipOfSymbol(
Ethan Nicholas89cfde12021-09-27 11:20:34 -04003049 std::make_unique<Variable>(intfVar.fLine,
John Stiles0cac5ed2021-08-06 11:40:39 -04003050 &intfVar.modifiers(),
3051 intfVar.name(),
3052 rtFlipStructType,
3053 intfVar.isBuiltin(),
3054 intfVar.storage()));
3055 fSPIRVBonusVariables.insert(modifiedVar);
Ethan Nicholas89cfde12021-09-27 11:20:34 -04003056 InterfaceBlock modifiedCopy(intf.fLine,
Ethan Nicholas2816dcf2021-09-21 09:18:47 -04003057 *modifiedVar,
John Stiles0cac5ed2021-08-06 11:40:39 -04003058 intf.typeName(),
3059 intf.instanceName(),
3060 intf.arraySize(),
3061 intf.typeOwner());
3062 result = this->writeInterfaceBlock(modifiedCopy, false);
3063 fProgram.fSymbols->add(std::make_unique<Field>(
Ethan Nicholas89cfde12021-09-27 11:20:34 -04003064 /*line=*/-1, modifiedVar, rtFlipStructType->fields().size() - 1));
Brian Salomond8d85b92021-07-07 09:41:17 -04003065 }
3066 fVariableMap[&intfVar] = result;
3067 fWroteRTFlip = true;
3068 return result;
Ethan Nicholas941e7e22016-12-12 15:33:30 -05003069 }
Brian Salomond8d85b92021-07-07 09:41:17 -04003070 const Modifiers& intfModifiers = intfVar.modifiers();
Brian Osman99ddd2a2021-08-27 11:21:12 -04003071 SpvId typeId = this->getType(type, memoryLayout);
Brian Osman58ee8982021-02-18 15:39:38 -05003072 if (intfModifiers.fLayout.fBuiltin == -1) {
Ethan Nicholas6ac8d362019-01-22 21:43:55 +00003073 this->writeInstruction(SpvOpDecorate, typeId, SpvDecorationBlock, fDecorationBuffer);
Ethan Nicholas0dd30d92017-05-01 16:57:07 -04003074 }
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04003075 SpvId ptrType = this->nextId(nullptr);
Ethan Nicholas941e7e22016-12-12 15:33:30 -05003076 this->writeInstruction(SpvOpTypePointer, ptrType, storageClass, typeId, fConstantBuffer);
ethannicholasb3058bd2016-07-01 08:22:01 -07003077 this->writeInstruction(SpvOpVariable, ptrType, result, storageClass, fConstantBuffer);
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04003078 Layout layout = intfModifiers.fLayout;
3079 if (intfModifiers.fFlags & Modifiers::kUniform_Flag && layout.fSet == -1) {
Ethan Nicholas8d2ba442018-03-16 16:40:36 -04003080 layout.fSet = 0;
3081 }
3082 this->writeLayout(layout, result);
Brian Salomond8d85b92021-07-07 09:41:17 -04003083 fVariableMap[&intfVar] = result;
ethannicholasb3058bd2016-07-01 08:22:01 -07003084 return result;
3085}
3086
John Stilesd7437ee2021-08-02 11:56:16 -04003087bool SPIRVCodeGenerator::isDead(const Variable& var) const {
3088 // During SPIR-V code generation, we synthesize some extra bonus variables that don't actually
3089 // exist in the Program at all and aren't tracked by the ProgramUsage. They aren't dead, though.
3090 if (fSPIRVBonusVariables.count(&var)) {
3091 return false;
3092 }
3093 ProgramUsage::VariableCounts counts = fProgram.usage()->get(var);
Brian Osman010ce6a2020-10-19 16:34:10 -04003094 if (counts.fRead || counts.fWrite) {
Chris Dalton2284aab2019-11-15 11:02:24 -07003095 return false;
3096 }
Brian Osmand1f3b972021-03-22 17:03:42 -04003097 // It's not entirely clear what the rules are for eliding interface variables. Generally, it
3098 // causes problems to elide them, even when they're dead.
3099 return !(var.modifiers().fFlags &
3100 (Modifiers::kIn_Flag | Modifiers::kOut_Flag | Modifiers::kUniform_Flag));
Chris Dalton2284aab2019-11-15 11:02:24 -07003101}
3102
John Stilesdbd4e6f2021-02-16 13:29:15 -05003103void SPIRVCodeGenerator::writeGlobalVar(ProgramKind kind, const VarDeclaration& varDecl) {
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04003104 const Variable& var = varDecl.var();
John Stiles0ca2f592021-01-27 10:58:10 -05003105 // 9999 is a sentinel value used in our built-in modules that causes us to ignore these
3106 // declarations, beyond adding them to the symbol table.
3107 constexpr int kBuiltinIgnore = 9999;
3108 if (var.modifiers().fLayout.fBuiltin == kBuiltinIgnore) {
Brian Osmanc0213602020-10-06 14:43:32 -04003109 return;
3110 }
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04003111 if (var.modifiers().fLayout.fBuiltin == SK_FRAGCOLOR_BUILTIN &&
John Stilesdbd4e6f2021-02-16 13:29:15 -05003112 kind != ProgramKind::kFragment) {
John Stiles270cec22021-02-17 12:59:36 -05003113 SkASSERT(!fProgram.fConfig->fSettings.fFragColorIsInOut);
Brian Osmanc0213602020-10-06 14:43:32 -04003114 return;
3115 }
John Stilesd7437ee2021-08-02 11:56:16 -04003116 if (this->isDead(var)) {
Brian Osmanc0213602020-10-06 14:43:32 -04003117 return;
3118 }
John Stiles0de76f72021-01-29 09:19:39 -05003119 SpvStorageClass_ storageClass = get_storage_class(var, SpvStorageClassPrivate);
John Stilese40d1662021-01-29 10:08:50 -05003120 if (storageClass == SpvStorageClassUniform) {
3121 // Top-level uniforms are emitted in writeUniformBuffer.
3122 fTopLevelUniforms.push_back(&varDecl);
3123 return;
3124 }
3125 const Type& type = var.type();
John Stilesd8fc95d2021-01-26 16:22:53 -05003126 Layout layout = var.modifiers().fLayout;
John Stilese40d1662021-01-29 10:08:50 -05003127 if (layout.fSet < 0 && storageClass == SpvStorageClassUniformConstant) {
John Stiles270cec22021-02-17 12:59:36 -05003128 layout.fSet = fProgram.fConfig->fSettings.fDefaultUniformSet;
Brian Osmanc0213602020-10-06 14:43:32 -04003129 }
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04003130 SpvId id = this->nextId(&type);
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04003131 fVariableMap[&var] = id;
Brian Osman99ddd2a2021-08-27 11:21:12 -04003132 SpvId typeId = this->getPointerType(type, storageClass);
Brian Osmanc0213602020-10-06 14:43:32 -04003133 this->writeInstruction(SpvOpVariable, typeId, id, storageClass, fConstantBuffer);
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04003134 this->writeInstruction(SpvOpName, id, var.name(), fNameBuffer);
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04003135 if (varDecl.value()) {
Brian Osmanc0213602020-10-06 14:43:32 -04003136 SkASSERT(!fCurrentBlock);
3137 fCurrentBlock = -1;
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04003138 SpvId value = this->writeExpression(*varDecl.value(), fGlobalInitializersBuffer);
Brian Osmanc0213602020-10-06 14:43:32 -04003139 this->writeInstruction(SpvOpStore, id, value, fGlobalInitializersBuffer);
3140 fCurrentBlock = 0;
3141 }
John Stilesd8fc95d2021-01-26 16:22:53 -05003142 this->writeLayout(layout, id);
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04003143 if (var.modifiers().fFlags & Modifiers::kFlat_Flag) {
Brian Osmanc0213602020-10-06 14:43:32 -04003144 this->writeInstruction(SpvOpDecorate, id, SpvDecorationFlat, fDecorationBuffer);
3145 }
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04003146 if (var.modifiers().fFlags & Modifiers::kNoPerspective_Flag) {
Brian Osmanc0213602020-10-06 14:43:32 -04003147 this->writeInstruction(SpvOpDecorate, id, SpvDecorationNoPerspective,
3148 fDecorationBuffer);
ethannicholasb3058bd2016-07-01 08:22:01 -07003149 }
3150}
3151
Brian Osmanc0213602020-10-06 14:43:32 -04003152void SPIRVCodeGenerator::writeVarDeclaration(const VarDeclaration& varDecl, OutputStream& out) {
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04003153 const Variable& var = varDecl.var();
Ethan Nicholas7f015882021-03-23 14:16:52 -04003154 SpvId id = this->nextId(&var.type());
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04003155 fVariableMap[&var] = id;
3156 SpvId type = this->getPointerType(var.type(), SpvStorageClassFunction);
Brian Osmanc0213602020-10-06 14:43:32 -04003157 this->writeInstruction(SpvOpVariable, type, id, SpvStorageClassFunction, fVariableBuffer);
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04003158 this->writeInstruction(SpvOpName, id, var.name(), fNameBuffer);
3159 if (varDecl.value()) {
3160 SpvId value = this->writeExpression(*varDecl.value(), out);
Brian Osmanc0213602020-10-06 14:43:32 -04003161 this->writeInstruction(SpvOpStore, id, value, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003162 }
3163}
3164
Ethan Nicholas0df1b042017-03-31 13:56:23 -04003165void SPIRVCodeGenerator::writeStatement(const Statement& s, OutputStream& out) {
Ethan Nicholase6592142020-09-08 10:22:09 -04003166 switch (s.kind()) {
John Stiles98c1f822020-09-09 14:18:53 -04003167 case Statement::Kind::kInlineMarker:
Ethan Nicholase6592142020-09-08 10:22:09 -04003168 case Statement::Kind::kNop:
Ethan Nicholascb670962017-04-20 19:31:52 -04003169 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04003170 case Statement::Kind::kBlock:
John Stiles0693fb82021-01-22 18:27:52 -05003171 this->writeBlock(s.as<Block>(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003172 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04003173 case Statement::Kind::kExpression:
Ethan Nicholasd503a5a2020-09-30 09:29:55 -04003174 this->writeExpression(*s.as<ExpressionStatement>().expression(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003175 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04003176 case Statement::Kind::kReturn:
John Stiles26f98502020-08-18 09:30:51 -04003177 this->writeReturnStatement(s.as<ReturnStatement>(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003178 break;
Brian Osmanc0213602020-10-06 14:43:32 -04003179 case Statement::Kind::kVarDeclaration:
3180 this->writeVarDeclaration(s.as<VarDeclaration>(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003181 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04003182 case Statement::Kind::kIf:
John Stiles26f98502020-08-18 09:30:51 -04003183 this->writeIfStatement(s.as<IfStatement>(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003184 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04003185 case Statement::Kind::kFor:
John Stiles26f98502020-08-18 09:30:51 -04003186 this->writeForStatement(s.as<ForStatement>(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003187 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04003188 case Statement::Kind::kDo:
John Stiles26f98502020-08-18 09:30:51 -04003189 this->writeDoStatement(s.as<DoStatement>(), out);
Ethan Nicholasfd146aa2017-01-13 16:40:35 -05003190 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04003191 case Statement::Kind::kSwitch:
John Stiles26f98502020-08-18 09:30:51 -04003192 this->writeSwitchStatement(s.as<SwitchStatement>(), out);
Ethan Nicholase92b1b12017-11-13 16:13:21 -05003193 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04003194 case Statement::Kind::kBreak:
ethannicholasb3058bd2016-07-01 08:22:01 -07003195 this->writeInstruction(SpvOpBranch, fBreakTarget.top(), out);
3196 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04003197 case Statement::Kind::kContinue:
ethannicholasb3058bd2016-07-01 08:22:01 -07003198 this->writeInstruction(SpvOpBranch, fContinueTarget.top(), out);
3199 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04003200 case Statement::Kind::kDiscard:
ethannicholasb3058bd2016-07-01 08:22:01 -07003201 this->writeInstruction(SpvOpKill, out);
3202 break;
3203 default:
John Stileseada7bc2021-02-02 16:29:32 -05003204 SkDEBUGFAILF("unsupported statement: %s", s.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -05003205 break;
ethannicholasb3058bd2016-07-01 08:22:01 -07003206 }
3207}
3208
Ethan Nicholas0df1b042017-03-31 13:56:23 -04003209void SPIRVCodeGenerator::writeBlock(const Block& b, OutputStream& out) {
Ethan Nicholas7bd60432020-09-25 14:31:59 -04003210 for (const std::unique_ptr<Statement>& stmt : b.children()) {
3211 this->writeStatement(*stmt, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003212 }
3213}
3214
Ethan Nicholas0df1b042017-03-31 13:56:23 -04003215void SPIRVCodeGenerator::writeIfStatement(const IfStatement& stmt, OutputStream& out) {
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04003216 SpvId test = this->writeExpression(*stmt.test(), out);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04003217 SpvId ifTrue = this->nextId(nullptr);
3218 SpvId ifFalse = this->nextId(nullptr);
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04003219 if (stmt.ifFalse()) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04003220 SpvId end = this->nextId(nullptr);
ethannicholasb3058bd2016-07-01 08:22:01 -07003221 this->writeInstruction(SpvOpSelectionMerge, end, SpvSelectionControlMaskNone, out);
3222 this->writeInstruction(SpvOpBranchConditional, test, ifTrue, ifFalse, out);
3223 this->writeLabel(ifTrue, out);
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04003224 this->writeStatement(*stmt.ifTrue(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003225 if (fCurrentBlock) {
3226 this->writeInstruction(SpvOpBranch, end, out);
3227 }
3228 this->writeLabel(ifFalse, out);
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04003229 this->writeStatement(*stmt.ifFalse(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003230 if (fCurrentBlock) {
3231 this->writeInstruction(SpvOpBranch, end, out);
3232 }
3233 this->writeLabel(end, out);
3234 } else {
3235 this->writeInstruction(SpvOpSelectionMerge, ifFalse, SpvSelectionControlMaskNone, out);
3236 this->writeInstruction(SpvOpBranchConditional, test, ifTrue, ifFalse, out);
3237 this->writeLabel(ifTrue, out);
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04003238 this->writeStatement(*stmt.ifTrue(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003239 if (fCurrentBlock) {
3240 this->writeInstruction(SpvOpBranch, ifFalse, out);
3241 }
3242 this->writeLabel(ifFalse, out);
3243 }
3244}
3245
Ethan Nicholas0df1b042017-03-31 13:56:23 -04003246void SPIRVCodeGenerator::writeForStatement(const ForStatement& f, OutputStream& out) {
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04003247 if (f.initializer()) {
3248 this->writeStatement(*f.initializer(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003249 }
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04003250 SpvId header = this->nextId(nullptr);
3251 SpvId start = this->nextId(nullptr);
3252 SpvId body = this->nextId(nullptr);
3253 SpvId next = this->nextId(nullptr);
ethannicholasb3058bd2016-07-01 08:22:01 -07003254 fContinueTarget.push(next);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04003255 SpvId end = this->nextId(nullptr);
ethannicholasb3058bd2016-07-01 08:22:01 -07003256 fBreakTarget.push(end);
3257 this->writeInstruction(SpvOpBranch, header, out);
3258 this->writeLabel(header, out);
3259 this->writeInstruction(SpvOpLoopMerge, end, next, SpvLoopControlMaskNone, out);
ethannicholasf789b382016-08-03 12:43:36 -07003260 this->writeInstruction(SpvOpBranch, start, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003261 this->writeLabel(start, out);
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04003262 if (f.test()) {
3263 SpvId test = this->writeExpression(*f.test(), out);
ethannicholas22f939e2016-10-13 13:25:34 -07003264 this->writeInstruction(SpvOpBranchConditional, test, body, end, out);
Ethan Nicholas7fb39362020-12-16 15:25:19 -05003265 } else {
3266 this->writeInstruction(SpvOpBranch, body, out);
ethannicholas22f939e2016-10-13 13:25:34 -07003267 }
ethannicholasb3058bd2016-07-01 08:22:01 -07003268 this->writeLabel(body, out);
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04003269 this->writeStatement(*f.statement(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003270 if (fCurrentBlock) {
3271 this->writeInstruction(SpvOpBranch, next, out);
3272 }
3273 this->writeLabel(next, out);
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04003274 if (f.next()) {
3275 this->writeExpression(*f.next(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003276 }
3277 this->writeInstruction(SpvOpBranch, header, out);
3278 this->writeLabel(end, out);
3279 fBreakTarget.pop();
3280 fContinueTarget.pop();
3281}
3282
Ethan Nicholas0df1b042017-03-31 13:56:23 -04003283void SPIRVCodeGenerator::writeDoStatement(const DoStatement& d, OutputStream& out) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04003284 SpvId header = this->nextId(nullptr);
3285 SpvId start = this->nextId(nullptr);
3286 SpvId next = this->nextId(nullptr);
3287 SpvId continueTarget = this->nextId(nullptr);
Ethan Nicholas0d997662019-04-08 09:46:01 -04003288 fContinueTarget.push(continueTarget);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04003289 SpvId end = this->nextId(nullptr);
Ethan Nicholasfd146aa2017-01-13 16:40:35 -05003290 fBreakTarget.push(end);
3291 this->writeInstruction(SpvOpBranch, header, out);
3292 this->writeLabel(header, out);
Ethan Nicholas0d997662019-04-08 09:46:01 -04003293 this->writeInstruction(SpvOpLoopMerge, end, continueTarget, SpvLoopControlMaskNone, out);
Ethan Nicholasfd146aa2017-01-13 16:40:35 -05003294 this->writeInstruction(SpvOpBranch, start, out);
3295 this->writeLabel(start, out);
Ethan Nicholas1fd61162020-09-28 13:14:19 -04003296 this->writeStatement(*d.statement(), out);
Ethan Nicholasfd146aa2017-01-13 16:40:35 -05003297 if (fCurrentBlock) {
3298 this->writeInstruction(SpvOpBranch, next, out);
3299 }
3300 this->writeLabel(next, out);
John Stiles68072a42021-04-16 17:25:55 -04003301 this->writeInstruction(SpvOpBranch, continueTarget, out);
Ethan Nicholas0d997662019-04-08 09:46:01 -04003302 this->writeLabel(continueTarget, out);
John Stiles68072a42021-04-16 17:25:55 -04003303 SpvId test = this->writeExpression(*d.test(), out);
3304 this->writeInstruction(SpvOpBranchConditional, test, header, end, out);
Ethan Nicholasfd146aa2017-01-13 16:40:35 -05003305 this->writeLabel(end, out);
3306 fBreakTarget.pop();
3307 fContinueTarget.pop();
3308}
3309
Ethan Nicholase92b1b12017-11-13 16:13:21 -05003310void SPIRVCodeGenerator::writeSwitchStatement(const SwitchStatement& s, OutputStream& out) {
Ethan Nicholas01b05e52020-10-22 15:53:41 -04003311 SpvId value = this->writeExpression(*s.value(), out);
Ethan Nicholase92b1b12017-11-13 16:13:21 -05003312 std::vector<SpvId> labels;
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04003313 SpvId end = this->nextId(nullptr);
Ethan Nicholase92b1b12017-11-13 16:13:21 -05003314 SpvId defaultLabel = end;
3315 fBreakTarget.push(end);
3316 int size = 3;
John Stiles2d4f9592020-10-30 10:29:12 -04003317 auto& cases = s.cases();
John Stilesb23a64b2021-03-11 08:27:59 -05003318 for (const std::unique_ptr<Statement>& stmt : cases) {
3319 const SwitchCase& c = stmt->as<SwitchCase>();
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04003320 SpvId label = this->nextId(nullptr);
Ethan Nicholase92b1b12017-11-13 16:13:21 -05003321 labels.push_back(label);
John Stilesb23a64b2021-03-11 08:27:59 -05003322 if (c.value()) {
Ethan Nicholase92b1b12017-11-13 16:13:21 -05003323 size += 2;
3324 } else {
3325 defaultLabel = label;
3326 }
3327 }
3328 labels.push_back(end);
3329 this->writeInstruction(SpvOpSelectionMerge, end, SpvSelectionControlMaskNone, out);
3330 this->writeOpCode(SpvOpSwitch, size, out);
3331 this->writeWord(value, out);
3332 this->writeWord(defaultLabel, out);
John Stiles2d4f9592020-10-30 10:29:12 -04003333 for (size_t i = 0; i < cases.size(); ++i) {
John Stilesb23a64b2021-03-11 08:27:59 -05003334 const SwitchCase& c = cases[i]->as<SwitchCase>();
3335 if (!c.value()) {
Ethan Nicholase92b1b12017-11-13 16:13:21 -05003336 continue;
3337 }
John Stiles7591d4b2021-09-13 13:32:06 -04003338 this->writeWord(c.value()->as<Literal>().intValue(), out);
Ethan Nicholase92b1b12017-11-13 16:13:21 -05003339 this->writeWord(labels[i], out);
3340 }
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>();
Ethan Nicholase92b1b12017-11-13 16:13:21 -05003343 this->writeLabel(labels[i], out);
John Stilesb23a64b2021-03-11 08:27:59 -05003344 this->writeStatement(*c.statement(), out);
Ethan Nicholase92b1b12017-11-13 16:13:21 -05003345 if (fCurrentBlock) {
3346 this->writeInstruction(SpvOpBranch, labels[i + 1], out);
3347 }
3348 }
3349 this->writeLabel(end, out);
3350 fBreakTarget.pop();
3351}
3352
Ethan Nicholas0df1b042017-03-31 13:56:23 -04003353void SPIRVCodeGenerator::writeReturnStatement(const ReturnStatement& r, OutputStream& out) {
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04003354 if (r.expression()) {
3355 this->writeInstruction(SpvOpReturnValue, this->writeExpression(*r.expression(), out),
ethannicholasb3058bd2016-07-01 08:22:01 -07003356 out);
3357 } else {
3358 this->writeInstruction(SpvOpReturn, out);
3359 }
3360}
3361
John Stilese40d1662021-01-29 10:08:50 -05003362// Given any function, returns the top-level symbol table (OUTSIDE of the function's scope).
3363static std::shared_ptr<SymbolTable> get_top_level_symbol_table(const FunctionDeclaration& anyFunc) {
3364 return anyFunc.definition()->body()->as<Block>().symbolTable()->fParent;
3365}
3366
John Stiles4d6310a2021-01-26 19:58:22 -05003367SPIRVCodeGenerator::EntrypointAdapter SPIRVCodeGenerator::writeEntrypointAdapter(
3368 const FunctionDeclaration& main) {
3369 // Our goal is to synthesize a tiny helper function which looks like this:
3370 // void _entrypoint() { sk_FragColor = main(); }
3371
3372 // Fish a symbol table out of main().
John Stilese40d1662021-01-29 10:08:50 -05003373 std::shared_ptr<SymbolTable> symbolTable = get_top_level_symbol_table(main);
John Stiles4d6310a2021-01-26 19:58:22 -05003374
3375 // Get `sk_FragColor` as a writable reference.
3376 const Symbol* skFragColorSymbol = (*symbolTable)["sk_FragColor"];
3377 SkASSERT(skFragColorSymbol);
3378 const Variable& skFragColorVar = skFragColorSymbol->as<Variable>();
Ethan Nicholas89cfde12021-09-27 11:20:34 -04003379 auto skFragColorRef = std::make_unique<VariableReference>(/*line=*/-1, &skFragColorVar,
John Stiles4d6310a2021-01-26 19:58:22 -05003380 VariableReference::RefKind::kWrite);
3381 // Synthesize a call to the `main()` function.
3382 if (main.returnType() != skFragColorRef->type()) {
Ethan Nicholas89cfde12021-09-27 11:20:34 -04003383 fContext.fErrors->error(main.fLine, "SPIR-V does not support returning '" +
3384 main.returnType().description() + "' from main()");
John Stiles4d6310a2021-01-26 19:58:22 -05003385 return {};
3386 }
Brian Osman716aeb92021-04-21 13:20:00 -04003387 ExpressionArray args;
3388 if (main.parameters().size() == 1) {
3389 if (main.parameters()[0]->type() != *fContext.fTypes.fFloat2) {
Ethan Nicholas89cfde12021-09-27 11:20:34 -04003390 fContext.fErrors->error(main.fLine,
Ethan Nicholas3abc6c62021-08-13 11:20:09 -04003391 "SPIR-V does not support parameter of type '" +
3392 main.parameters()[0]->type().description() + "' to main()");
Brian Osman716aeb92021-04-21 13:20:00 -04003393 return {};
3394 }
John Stiles7591d4b2021-09-13 13:32:06 -04003395 args.push_back(dsl::Float2(0).release());
Brian Osman716aeb92021-04-21 13:20:00 -04003396 }
Ethan Nicholas89cfde12021-09-27 11:20:34 -04003397 auto callMainFn = std::make_unique<FunctionCall>(/*line=*/-1, &main.returnType(), &main,
Brian Osman716aeb92021-04-21 13:20:00 -04003398 std::move(args));
John Stiles4d6310a2021-01-26 19:58:22 -05003399
3400 // Synthesize `skFragColor = main()` as a BinaryExpression.
3401 auto assignmentStmt = std::make_unique<ExpressionStatement>(std::make_unique<BinaryExpression>(
Ethan Nicholas89cfde12021-09-27 11:20:34 -04003402 /*line=*/-1,
John Stiles4d6310a2021-01-26 19:58:22 -05003403 std::move(skFragColorRef),
3404 Token::Kind::TK_EQ,
3405 std::move(callMainFn),
3406 &main.returnType()));
3407
3408 // Function bodies are always wrapped in a Block.
3409 StatementArray entrypointStmts;
3410 entrypointStmts.push_back(std::move(assignmentStmt));
Ethan Nicholas89cfde12021-09-27 11:20:34 -04003411 auto entrypointBlock = Block::Make(/*line=*/-1, std::move(entrypointStmts),
John Stilesbf16b6c2021-03-12 19:24:31 -05003412 symbolTable, /*isScope=*/true);
John Stiles4d6310a2021-01-26 19:58:22 -05003413 // Declare an entrypoint function.
3414 EntrypointAdapter adapter;
3415 adapter.fLayout = {};
3416 adapter.fModifiers = Modifiers{adapter.fLayout, Modifiers::kHasSideEffects_Flag};
3417 adapter.entrypointDecl =
Ethan Nicholas89cfde12021-09-27 11:20:34 -04003418 std::make_unique<FunctionDeclaration>(/*line=*/-1,
John Stiles4d6310a2021-01-26 19:58:22 -05003419 &adapter.fModifiers,
3420 "_entrypoint",
3421 /*parameters=*/std::vector<const Variable*>{},
3422 /*returnType=*/fContext.fTypes.fVoid.get(),
3423 /*builtin=*/false);
3424 // Define it.
John Stiles3b204892021-08-27 17:35:35 -04003425 adapter.entrypointDef = FunctionDefinition::Convert(fContext,
Ethan Nicholas89cfde12021-09-27 11:20:34 -04003426 /*line=*/-1,
John Stiles3b204892021-08-27 17:35:35 -04003427 *adapter.entrypointDecl,
3428 std::move(entrypointBlock),
3429 /*builtin=*/false);
John Stiles4d6310a2021-01-26 19:58:22 -05003430
3431 adapter.entrypointDecl->setDefinition(adapter.entrypointDef.get());
3432 return adapter;
3433}
3434
John Stilese40d1662021-01-29 10:08:50 -05003435void SPIRVCodeGenerator::writeUniformBuffer(std::shared_ptr<SymbolTable> topLevelSymbolTable) {
3436 SkASSERT(!fTopLevelUniforms.empty());
3437 static constexpr char kUniformBufferName[] = "_UniformBuffer";
3438
3439 // Convert the list of top-level uniforms into a matching struct named _UniformBuffer, and build
3440 // a lookup table of variables to UniformBuffer field indices.
3441 std::vector<Type::Field> fields;
3442 fields.reserve(fTopLevelUniforms.size());
3443 fTopLevelUniformMap.reserve(fTopLevelUniforms.size());
3444 for (const VarDeclaration* topLevelUniform : fTopLevelUniforms) {
3445 const Variable* var = &topLevelUniform->var();
3446 fTopLevelUniformMap[var] = (int)fields.size();
3447 fields.emplace_back(var->modifiers(), var->name(), &var->type());
3448 }
Ethan Nicholas89cfde12021-09-27 11:20:34 -04003449 fUniformBuffer.fStruct = Type::MakeStructType(/*line=*/-1, kUniformBufferName,
John Stilese40d1662021-01-29 10:08:50 -05003450 std::move(fields));
3451
3452 // Create a global variable to contain this struct.
3453 Layout layout;
John Stiles270cec22021-02-17 12:59:36 -05003454 layout.fBinding = fProgram.fConfig->fSettings.fDefaultUniformBinding;
3455 layout.fSet = fProgram.fConfig->fSettings.fDefaultUniformSet;
John Stilese40d1662021-01-29 10:08:50 -05003456 Modifiers modifiers{layout, Modifiers::kUniform_Flag};
3457
3458 fUniformBuffer.fInnerVariable = std::make_unique<Variable>(
Ethan Nicholas89cfde12021-09-27 11:20:34 -04003459 /*line=*/-1, fProgram.fModifiers->add(modifiers), kUniformBufferName,
John Stilese40d1662021-01-29 10:08:50 -05003460 fUniformBuffer.fStruct.get(), /*builtin=*/false, Variable::Storage::kGlobal);
3461
3462 // Create an interface block object for this global variable.
3463 fUniformBuffer.fInterfaceBlock = std::make_unique<InterfaceBlock>(
Ethan Nicholas2816dcf2021-09-21 09:18:47 -04003464 /*offset=*/-1, *fUniformBuffer.fInnerVariable, kUniformBufferName,
John Stilese40d1662021-01-29 10:08:50 -05003465 kUniformBufferName, /*arraySize=*/0, topLevelSymbolTable);
3466
3467 // Generate an interface block and hold onto its ID.
3468 fUniformBufferId = this->writeInterfaceBlock(*fUniformBuffer.fInterfaceBlock);
3469}
3470
Ethan Nicholas89cfde12021-09-27 11:20:34 -04003471void SPIRVCodeGenerator::addRTFlipUniform(int line) {
Brian Salomond8d85b92021-07-07 09:41:17 -04003472 if (fWroteRTFlip) {
3473 return;
3474 }
3475 // Flip variable hasn't been written yet. This means we don't have an existing
3476 // interface block, so we're free to just synthesize one.
3477 fWroteRTFlip = true;
3478 std::vector<Type::Field> fields;
3479 if (fProgram.fConfig->fSettings.fRTFlipOffset < 0) {
Ethan Nicholas89cfde12021-09-27 11:20:34 -04003480 fContext.fErrors->error(line, "RTFlipOffset is negative");
Brian Salomond8d85b92021-07-07 09:41:17 -04003481 }
3482 fields.emplace_back(Modifiers(Layout(/*flags=*/0,
3483 /*location=*/-1,
3484 fProgram.fConfig->fSettings.fRTFlipOffset,
3485 /*binding=*/-1,
3486 /*index=*/-1,
3487 /*set=*/-1,
3488 /*builtin=*/-1,
Brian Osman99ddd2a2021-08-27 11:21:12 -04003489 /*inputAttachmentIndex=*/-1),
Brian Salomond8d85b92021-07-07 09:41:17 -04003490 /*flags=*/0),
3491 SKSL_RTFLIP_NAME,
3492 fContext.fTypes.fFloat2.get());
Ethan Nicholas27f06eb2021-07-26 16:39:40 -04003493 skstd::string_view name = "sksl_synthetic_uniforms";
Brian Salomond8d85b92021-07-07 09:41:17 -04003494 const Type* intfStruct =
Ethan Nicholas89cfde12021-09-27 11:20:34 -04003495 fSynthetics.takeOwnershipOfSymbol(Type::MakeStructType(/*line=*/-1, name, fields));
Brian Salomond8d85b92021-07-07 09:41:17 -04003496 int binding = fProgram.fConfig->fSettings.fRTFlipBinding;
3497 if (binding == -1) {
Ethan Nicholas89cfde12021-09-27 11:20:34 -04003498 fContext.fErrors->error(line, "layout(binding=...) is required in SPIR-V");
Brian Salomond8d85b92021-07-07 09:41:17 -04003499 }
3500 int set = fProgram.fConfig->fSettings.fRTFlipSet;
3501 if (set == -1) {
Ethan Nicholas89cfde12021-09-27 11:20:34 -04003502 fContext.fErrors->error(line, "layout(set=...) is required in SPIR-V");
Brian Salomond8d85b92021-07-07 09:41:17 -04003503 }
3504 bool usePushConstants = fProgram.fConfig->fSettings.fUsePushConstants;
3505 int flags = usePushConstants ? Layout::Flag::kPushConstant_Flag : 0;
John Stiles0cac5ed2021-08-06 11:40:39 -04003506 const Modifiers* modsPtr;
3507 {
3508 AutoAttachPoolToThread attach(fProgram.fPool.get());
3509 Modifiers modifiers(Layout(flags,
3510 /*location=*/-1,
3511 /*offset=*/-1,
3512 binding,
3513 /*index=*/-1,
3514 set,
3515 /*builtin=*/-1,
Brian Osman99ddd2a2021-08-27 11:21:12 -04003516 /*inputAttachmentIndex=*/-1),
John Stiles0cac5ed2021-08-06 11:40:39 -04003517 Modifiers::kUniform_Flag);
3518 modsPtr = fProgram.fModifiers->add(modifiers);
Brian Salomond8d85b92021-07-07 09:41:17 -04003519 }
3520 const Variable* intfVar = fSynthetics.takeOwnershipOfSymbol(
Ethan Nicholas89cfde12021-09-27 11:20:34 -04003521 std::make_unique<Variable>(/*line=*/-1,
Brian Salomond8d85b92021-07-07 09:41:17 -04003522 modsPtr,
3523 name,
3524 intfStruct,
3525 /*builtin=*/false,
3526 Variable::Storage::kGlobal));
John Stilesd7437ee2021-08-02 11:56:16 -04003527 fSPIRVBonusVariables.insert(intfVar);
John Stiles0cac5ed2021-08-06 11:40:39 -04003528 {
3529 AutoAttachPoolToThread attach(fProgram.fPool.get());
Ethan Nicholas89cfde12021-09-27 11:20:34 -04003530 fProgram.fSymbols->add(std::make_unique<Field>(/*line=*/-1, intfVar, /*field=*/0));
Brian Salomond8d85b92021-07-07 09:41:17 -04003531 }
Ethan Nicholas89cfde12021-09-27 11:20:34 -04003532 InterfaceBlock intf(/*line=*/-1,
Ethan Nicholas2816dcf2021-09-21 09:18:47 -04003533 *intfVar,
Ethan Nicholas3533ff12021-08-02 12:53:29 -04003534 name,
Brian Salomond8d85b92021-07-07 09:41:17 -04003535 /*instanceName=*/"",
3536 /*arraySize=*/0,
Ethan Nicholasc7774a72021-08-27 15:34:05 -04003537 std::make_shared<SymbolTable>(fContext, /*builtin=*/false));
Brian Salomond8d85b92021-07-07 09:41:17 -04003538
3539 this->writeInterfaceBlock(intf, false);
3540}
3541
Ethan Nicholas0df1b042017-03-31 13:56:23 -04003542void SPIRVCodeGenerator::writeInstructions(const Program& program, OutputStream& out) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04003543 fGLSLExtendedInstructions = this->nextId(nullptr);
Ethan Nicholas0df1b042017-03-31 13:56:23 -04003544 StringStream body;
John Stiles4d6310a2021-01-26 19:58:22 -05003545 // Assign SpvIds to functions.
3546 const FunctionDeclaration* main = nullptr;
Brian Osman133724c2020-10-28 14:14:39 -04003547 for (const ProgramElement* e : program.elements()) {
John Stiles4d6310a2021-01-26 19:58:22 -05003548 if (e->is<FunctionDefinition>()) {
3549 const FunctionDefinition& funcDef = e->as<FunctionDefinition>();
3550 const FunctionDeclaration& funcDecl = funcDef.declaration();
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04003551 fFunctionMap[&funcDecl] = this->nextId(nullptr);
John Stilese8da4d22021-03-24 09:19:45 -04003552 if (funcDecl.isMain()) {
John Stiles4d6310a2021-01-26 19:58:22 -05003553 main = &funcDecl;
Ethan Nicholasb6ba82c2018-01-17 15:21:50 -05003554 }
ethannicholasb3058bd2016-07-01 08:22:01 -07003555 }
3556 }
John Stiles4d6310a2021-01-26 19:58:22 -05003557 // Make sure we have a main() function.
3558 if (!main) {
Ethan Nicholas89cfde12021-09-27 11:20:34 -04003559 fContext.fErrors->error(/*line=*/-1, "program does not contain a main() function");
John Stiles4d6310a2021-01-26 19:58:22 -05003560 return;
3561 }
3562 // Emit interface blocks.
3563 std::set<SpvId> interfaceVars;
Brian Osman133724c2020-10-28 14:14:39 -04003564 for (const ProgramElement* e : program.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04003565 if (e->is<InterfaceBlock>()) {
Brian Osman1f8f5752020-10-28 14:46:21 -04003566 const InterfaceBlock& intf = e->as<InterfaceBlock>();
ethannicholasb3058bd2016-07-01 08:22:01 -07003567 SpvId id = this->writeInterfaceBlock(intf);
Brian Osman1f8f5752020-10-28 14:46:21 -04003568
3569 const Modifiers& modifiers = intf.variable().modifiers();
John Stiles8e2a84b2021-04-19 09:35:38 -04003570 if ((modifiers.fFlags & (Modifiers::kIn_Flag | Modifiers::kOut_Flag)) &&
John Stilesd7437ee2021-08-02 11:56:16 -04003571 modifiers.fLayout.fBuiltin == -1 && !this->isDead(intf.variable())) {
Ethan Nicholas8e48c1e2017-03-02 14:33:31 -05003572 interfaceVars.insert(id);
ethannicholasb3058bd2016-07-01 08:22:01 -07003573 }
3574 }
3575 }
John Stiles4d6310a2021-01-26 19:58:22 -05003576 // Emit global variable declarations.
Brian Osman133724c2020-10-28 14:14:39 -04003577 for (const ProgramElement* e : program.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04003578 if (e->is<GlobalVarDeclaration>()) {
John Stiles270cec22021-02-17 12:59:36 -05003579 this->writeGlobalVar(program.fConfig->fKind,
John Stilese40d1662021-01-29 10:08:50 -05003580 e->as<GlobalVarDeclaration>().declaration()->as<VarDeclaration>());
ethannicholasb3058bd2016-07-01 08:22:01 -07003581 }
3582 }
John Stilese40d1662021-01-29 10:08:50 -05003583 // Emit top-level uniforms into a dedicated uniform buffer.
3584 if (!fTopLevelUniforms.empty()) {
3585 this->writeUniformBuffer(get_top_level_symbol_table(*main));
3586 }
John Stiles4d6310a2021-01-26 19:58:22 -05003587 // If main() returns a half4, synthesize a tiny entrypoint function which invokes the real
3588 // main() and stores the result into sk_FragColor.
3589 EntrypointAdapter adapter;
3590 if (main->returnType() == *fContext.fTypes.fHalf4) {
3591 adapter = this->writeEntrypointAdapter(*main);
3592 if (adapter.entrypointDecl) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04003593 fFunctionMap[adapter.entrypointDecl.get()] = this->nextId(nullptr);
John Stiles4d6310a2021-01-26 19:58:22 -05003594 this->writeFunction(*adapter.entrypointDef, body);
3595 main = adapter.entrypointDecl.get();
3596 }
3597 }
3598 // Emit all the functions.
Brian Osman133724c2020-10-28 14:14:39 -04003599 for (const ProgramElement* e : program.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04003600 if (e->is<FunctionDefinition>()) {
3601 this->writeFunction(e->as<FunctionDefinition>(), body);
ethannicholasb3058bd2016-07-01 08:22:01 -07003602 }
3603 }
John Stiles4d6310a2021-01-26 19:58:22 -05003604 // Add global in/out variables to the list of interface variables.
ethannicholasb3058bd2016-07-01 08:22:01 -07003605 for (auto entry : fVariableMap) {
ethannicholasd598f792016-07-25 10:08:54 -07003606 const Variable* var = entry.first;
Ethan Nicholas453f67f2020-10-09 10:43:45 -04003607 if (var->storage() == Variable::Storage::kGlobal &&
John Stiles8e2a84b2021-04-19 09:35:38 -04003608 (var->modifiers().fFlags & (Modifiers::kIn_Flag | Modifiers::kOut_Flag)) &&
John Stilesd7437ee2021-08-02 11:56:16 -04003609 !this->isDead(*var)) {
Ethan Nicholas8e48c1e2017-03-02 14:33:31 -05003610 interfaceVars.insert(entry.second);
ethannicholasb3058bd2016-07-01 08:22:01 -07003611 }
3612 }
3613 this->writeCapabilities(out);
3614 this->writeInstruction(SpvOpExtInstImport, fGLSLExtendedInstructions, "GLSL.std.450", out);
3615 this->writeInstruction(SpvOpMemoryModel, SpvAddressingModelLogical, SpvMemoryModelGLSL450, out);
Ethan Nicholasd2e09602021-06-10 11:21:59 -04003616 this->writeOpCode(SpvOpEntryPoint, (SpvId) (3 + (main->name().length() + 4) / 4) +
ethannicholasb3058bd2016-07-01 08:22:01 -07003617 (int32_t) interfaceVars.size(), out);
John Stiles270cec22021-02-17 12:59:36 -05003618 switch (program.fConfig->fKind) {
John Stilesdbd4e6f2021-02-16 13:29:15 -05003619 case ProgramKind::kVertex:
ethannicholasb3058bd2016-07-01 08:22:01 -07003620 this->writeWord(SpvExecutionModelVertex, out);
3621 break;
John Stilesdbd4e6f2021-02-16 13:29:15 -05003622 case ProgramKind::kFragment:
ethannicholasb3058bd2016-07-01 08:22:01 -07003623 this->writeWord(SpvExecutionModelFragment, out);
3624 break;
Ethan Nicholas762466e2017-06-29 10:03:38 -04003625 default:
John Stilesf57207b2021-02-02 17:50:34 -05003626 SK_ABORT("cannot write this kind of program to SPIR-V\n");
ethannicholasb3058bd2016-07-01 08:22:01 -07003627 }
Ethan Nicholasbb155e22017-07-24 10:05:09 -04003628 SpvId entryPoint = fFunctionMap[main];
3629 this->writeWord(entryPoint, out);
Ethan Nicholasd2e09602021-06-10 11:21:59 -04003630 this->writeString(main->name(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003631 for (int var : interfaceVars) {
3632 this->writeWord(var, out);
3633 }
John Stiles270cec22021-02-17 12:59:36 -05003634 if (program.fConfig->fKind == ProgramKind::kFragment) {
Greg Daniel64773e62016-11-22 09:44:03 -05003635 this->writeInstruction(SpvOpExecutionMode,
3636 fFunctionMap[main],
ethannicholasb3058bd2016-07-01 08:22:01 -07003637 SpvExecutionModeOriginUpperLeft,
3638 out);
3639 }
Brian Osman133724c2020-10-28 14:14:39 -04003640 for (const ProgramElement* e : program.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04003641 if (e->is<Extension>()) {
Ethan Nicholasd2e09602021-06-10 11:21:59 -04003642 this->writeInstruction(SpvOpSourceExtension, e->as<Extension>().name(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003643 }
3644 }
Greg Daniel64773e62016-11-22 09:44:03 -05003645
Ethan Nicholas0df1b042017-03-31 13:56:23 -04003646 write_stringstream(fExtraGlobalsBuffer, out);
3647 write_stringstream(fNameBuffer, out);
3648 write_stringstream(fDecorationBuffer, out);
3649 write_stringstream(fConstantBuffer, out);
Ethan Nicholas0df1b042017-03-31 13:56:23 -04003650 write_stringstream(body, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003651}
3652
Ethan Nicholas941e7e22016-12-12 15:33:30 -05003653bool SPIRVCodeGenerator::generateCode() {
Ethan Nicholas39f6da42021-08-23 13:10:07 -04003654 SkASSERT(!fContext.fErrors->errorCount());
Ethan Nicholas941e7e22016-12-12 15:33:30 -05003655 this->writeWord(SpvMagicNumber, *fOut);
3656 this->writeWord(SpvVersion, *fOut);
3657 this->writeWord(SKSL_MAGIC, *fOut);
Ethan Nicholas0df1b042017-03-31 13:56:23 -04003658 StringStream buffer;
Ethan Nicholas941e7e22016-12-12 15:33:30 -05003659 this->writeInstructions(fProgram, buffer);
3660 this->writeWord(fIdCount, *fOut);
3661 this->writeWord(0, *fOut); // reserved, always zero
Ethan Nicholas0df1b042017-03-31 13:56:23 -04003662 write_stringstream(buffer, *fOut);
Ethan Nicholas553239b2021-08-23 15:40:20 -04003663 fContext.fErrors->reportPendingErrors(PositionInfo());
Ethan Nicholas39f6da42021-08-23 13:10:07 -04003664 return fContext.fErrors->errorCount() == 0;
ethannicholasb3058bd2016-07-01 08:22:01 -07003665}
3666
John Stilesa6841be2020-08-06 14:11:56 -04003667} // namespace SkSL