blob: fc2c7590af17c4086a828c11f1e067e7b3159075 [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
Mike Kleinc0bd9f92019-04-23 12:05:21 -05008#include "src/sksl/SkSLSPIRVCodeGenerator.h"
Ethan Nicholas9bd301d2017-03-31 16:04:34 +00009
Mike Kleinc0bd9f92019-04-23 12:05:21 -050010#include "src/sksl/GLSL.std.450.h"
ethannicholasb3058bd2016-07-01 08:22:01 -070011
Mike Kleinc0bd9f92019-04-23 12:05:21 -050012#include "src/sksl/SkSLCompiler.h"
13#include "src/sksl/ir/SkSLExpressionStatement.h"
14#include "src/sksl/ir/SkSLExtension.h"
15#include "src/sksl/ir/SkSLIndexExpression.h"
16#include "src/sksl/ir/SkSLVariableReference.h"
ethannicholasb3058bd2016-07-01 08:22:01 -070017
Ethan Nicholas0be34802019-08-15 12:36:58 -040018#ifdef SK_VULKAN
19#include "src/gpu/vk/GrVkCaps.h"
20#endif
21
John Stilescd806892021-01-06 13:33:31 -050022#define kLast_Capability SpvCapabilityMultiViewport
23
ethannicholasb3058bd2016-07-01 08:22:01 -070024namespace SkSL {
25
ethannicholasb3058bd2016-07-01 08:22:01 -070026static const int32_t SKSL_MAGIC = 0x0; // FIXME: we should probably register a magic number
27
28void SPIRVCodeGenerator::setupIntrinsics() {
29#define ALL_GLSL(x) std::make_tuple(kGLSL_STD_450_IntrinsicKind, GLSLstd450 ## x, GLSLstd450 ## x, \
30 GLSLstd450 ## x, GLSLstd450 ## x)
31#define BY_TYPE_GLSL(ifFloat, ifInt, ifUInt) std::make_tuple(kGLSL_STD_450_IntrinsicKind, \
32 GLSLstd450 ## ifFloat, \
33 GLSLstd450 ## ifInt, \
34 GLSLstd450 ## ifUInt, \
35 SpvOpUndef)
Ethan Nicholasdc0e1c32017-07-21 13:23:34 -040036#define ALL_SPIRV(x) std::make_tuple(kSPIRV_IntrinsicKind, SpvOp ## x, SpvOp ## x, SpvOp ## x, \
37 SpvOp ## x)
ethannicholasb3058bd2016-07-01 08:22:01 -070038#define SPECIAL(x) std::make_tuple(kSpecial_IntrinsicKind, k ## x ## _SpecialIntrinsic, \
39 k ## x ## _SpecialIntrinsic, k ## x ## _SpecialIntrinsic, \
40 k ## x ## _SpecialIntrinsic)
Ethan Nicholas0df1b042017-03-31 13:56:23 -040041 fIntrinsicMap[String("round")] = ALL_GLSL(Round);
42 fIntrinsicMap[String("roundEven")] = ALL_GLSL(RoundEven);
43 fIntrinsicMap[String("trunc")] = ALL_GLSL(Trunc);
44 fIntrinsicMap[String("abs")] = BY_TYPE_GLSL(FAbs, SAbs, SAbs);
45 fIntrinsicMap[String("sign")] = BY_TYPE_GLSL(FSign, SSign, SSign);
46 fIntrinsicMap[String("floor")] = ALL_GLSL(Floor);
47 fIntrinsicMap[String("ceil")] = ALL_GLSL(Ceil);
48 fIntrinsicMap[String("fract")] = ALL_GLSL(Fract);
49 fIntrinsicMap[String("radians")] = ALL_GLSL(Radians);
50 fIntrinsicMap[String("degrees")] = ALL_GLSL(Degrees);
51 fIntrinsicMap[String("sin")] = ALL_GLSL(Sin);
52 fIntrinsicMap[String("cos")] = ALL_GLSL(Cos);
53 fIntrinsicMap[String("tan")] = ALL_GLSL(Tan);
54 fIntrinsicMap[String("asin")] = ALL_GLSL(Asin);
55 fIntrinsicMap[String("acos")] = ALL_GLSL(Acos);
56 fIntrinsicMap[String("atan")] = SPECIAL(Atan);
57 fIntrinsicMap[String("sinh")] = ALL_GLSL(Sinh);
58 fIntrinsicMap[String("cosh")] = ALL_GLSL(Cosh);
59 fIntrinsicMap[String("tanh")] = ALL_GLSL(Tanh);
60 fIntrinsicMap[String("asinh")] = ALL_GLSL(Asinh);
61 fIntrinsicMap[String("acosh")] = ALL_GLSL(Acosh);
62 fIntrinsicMap[String("atanh")] = ALL_GLSL(Atanh);
63 fIntrinsicMap[String("pow")] = ALL_GLSL(Pow);
64 fIntrinsicMap[String("exp")] = ALL_GLSL(Exp);
65 fIntrinsicMap[String("log")] = ALL_GLSL(Log);
66 fIntrinsicMap[String("exp2")] = ALL_GLSL(Exp2);
67 fIntrinsicMap[String("log2")] = ALL_GLSL(Log2);
68 fIntrinsicMap[String("sqrt")] = ALL_GLSL(Sqrt);
Ethan Nicholasdc0e1c32017-07-21 13:23:34 -040069 fIntrinsicMap[String("inverse")] = ALL_GLSL(MatrixInverse);
John Stilesa07338f2020-12-17 12:39:08 -050070 fIntrinsicMap[String("outerProduct")] = ALL_SPIRV(OuterProduct);
Ethan Nicholasdc0e1c32017-07-21 13:23:34 -040071 fIntrinsicMap[String("transpose")] = ALL_SPIRV(Transpose);
John Stiles3679cd12020-12-09 16:22:12 -050072 fIntrinsicMap[String("isinf")] = ALL_SPIRV(IsInf);
73 fIntrinsicMap[String("isnan")] = ALL_SPIRV(IsNan);
Ethan Nicholas0df1b042017-03-31 13:56:23 -040074 fIntrinsicMap[String("inversesqrt")] = ALL_GLSL(InverseSqrt);
75 fIntrinsicMap[String("determinant")] = ALL_GLSL(Determinant);
Brian Osmand1b593f2020-12-28 13:00:46 -050076 fIntrinsicMap[String("matrixCompMult")] = SPECIAL(MatrixCompMult);
Ethan Nicholas0df1b042017-03-31 13:56:23 -040077 fIntrinsicMap[String("matrixInverse")] = ALL_GLSL(MatrixInverse);
Ethan Nicholas70a44b22017-11-30 09:09:16 -050078 fIntrinsicMap[String("mod")] = SPECIAL(Mod);
John Stiles01957272020-12-09 17:14:47 -050079 fIntrinsicMap[String("modf")] = ALL_GLSL(Modf);
Ethan Nicholas0fc07f92018-02-27 15:25:47 -050080 fIntrinsicMap[String("min")] = SPECIAL(Min);
81 fIntrinsicMap[String("max")] = SPECIAL(Max);
82 fIntrinsicMap[String("clamp")] = SPECIAL(Clamp);
Ethan Nicholas12fb9cf2018-08-03 16:16:57 -040083 fIntrinsicMap[String("saturate")] = SPECIAL(Saturate);
Ethan Nicholas0df1b042017-03-31 13:56:23 -040084 fIntrinsicMap[String("dot")] = std::make_tuple(kSPIRV_IntrinsicKind, SpvOpDot,
Ethan Nicholas0187ae62017-05-03 11:03:44 -040085 SpvOpUndef, SpvOpUndef, SpvOpUndef);
Ethan Nicholas0fc07f92018-02-27 15:25:47 -050086 fIntrinsicMap[String("mix")] = SPECIAL(Mix);
Brian Osman6ba3be12020-11-13 16:32:52 -050087 fIntrinsicMap[String("step")] = SPECIAL(Step);
88 fIntrinsicMap[String("smoothstep")] = SPECIAL(SmoothStep);
Ethan Nicholas0df1b042017-03-31 13:56:23 -040089 fIntrinsicMap[String("fma")] = ALL_GLSL(Fma);
90 fIntrinsicMap[String("frexp")] = ALL_GLSL(Frexp);
91 fIntrinsicMap[String("ldexp")] = ALL_GLSL(Ldexp);
ethannicholasb3058bd2016-07-01 08:22:01 -070092
Ethan Nicholas0df1b042017-03-31 13:56:23 -040093#define PACK(type) fIntrinsicMap[String("pack" #type)] = ALL_GLSL(Pack ## type); \
94 fIntrinsicMap[String("unpack" #type)] = ALL_GLSL(Unpack ## type)
ethannicholasb3058bd2016-07-01 08:22:01 -070095 PACK(Snorm4x8);
96 PACK(Unorm4x8);
97 PACK(Snorm2x16);
98 PACK(Unorm2x16);
99 PACK(Half2x16);
100 PACK(Double2x32);
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400101 fIntrinsicMap[String("length")] = ALL_GLSL(Length);
102 fIntrinsicMap[String("distance")] = ALL_GLSL(Distance);
103 fIntrinsicMap[String("cross")] = ALL_GLSL(Cross);
104 fIntrinsicMap[String("normalize")] = ALL_GLSL(Normalize);
John Stiles0d19fb42020-12-10 17:04:37 -0500105 fIntrinsicMap[String("faceforward")] = ALL_GLSL(FaceForward);
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400106 fIntrinsicMap[String("reflect")] = ALL_GLSL(Reflect);
107 fIntrinsicMap[String("refract")] = ALL_GLSL(Refract);
John Stilese7dc7cb2020-12-22 15:37:14 -0500108 fIntrinsicMap[String("bitCount")] = ALL_SPIRV(BitCount);
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400109 fIntrinsicMap[String("findLSB")] = ALL_GLSL(FindILsb);
110 fIntrinsicMap[String("findMSB")] = BY_TYPE_GLSL(FindSMsb, FindSMsb, FindUMsb);
111 fIntrinsicMap[String("dFdx")] = std::make_tuple(kSPIRV_IntrinsicKind, SpvOpDPdx,
Ethan Nicholas0187ae62017-05-03 11:03:44 -0400112 SpvOpUndef, SpvOpUndef, SpvOpUndef);
Chris Daltonb8af5ad2019-02-25 14:54:21 -0700113 fIntrinsicMap[String("dFdy")] = SPECIAL(DFdy);
Chris Dalton09212192018-11-13 15:07:24 -0500114 fIntrinsicMap[String("fwidth")] = std::make_tuple(kSPIRV_IntrinsicKind, SpvOpFwidth,
Ethan Nicholas0187ae62017-05-03 11:03:44 -0400115 SpvOpUndef, SpvOpUndef, SpvOpUndef);
Stephen Whiteff5d7a22019-07-26 17:42:06 -0400116 fIntrinsicMap[String("makeSampler2D")] = SPECIAL(SampledImage);
117
Ethan Nicholas13863662019-07-29 13:05:15 -0400118 fIntrinsicMap[String("sample")] = SPECIAL(Texture);
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400119 fIntrinsicMap[String("subpassLoad")] = SPECIAL(SubpassLoad);
Greg Daniel64773e62016-11-22 09:44:03 -0500120
John Stilescc9ff002020-12-09 18:39:41 -0500121 fIntrinsicMap[String("floatBitsToInt")] = ALL_SPIRV(Bitcast);
122 fIntrinsicMap[String("floatBitsToUint")] = ALL_SPIRV(Bitcast);
123 fIntrinsicMap[String("intBitsToFloat")] = ALL_SPIRV(Bitcast);
124 fIntrinsicMap[String("uintBitsToFloat")] = ALL_SPIRV(Bitcast);
125
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400126 fIntrinsicMap[String("any")] = std::make_tuple(kSPIRV_IntrinsicKind, SpvOpUndef,
Ethan Nicholas0187ae62017-05-03 11:03:44 -0400127 SpvOpUndef, SpvOpUndef, SpvOpAny);
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400128 fIntrinsicMap[String("all")] = std::make_tuple(kSPIRV_IntrinsicKind, SpvOpUndef,
Ethan Nicholas0187ae62017-05-03 11:03:44 -0400129 SpvOpUndef, SpvOpUndef, SpvOpAll);
Brian Osman540c13a2020-11-24 16:55:34 -0500130 fIntrinsicMap[String("not")] = std::make_tuple(kSPIRV_IntrinsicKind, SpvOpUndef,
131 SpvOpUndef, SpvOpUndef,
132 SpvOpLogicalNot);
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400133 fIntrinsicMap[String("equal")] = std::make_tuple(kSPIRV_IntrinsicKind,
Ethan Nicholas0187ae62017-05-03 11:03:44 -0400134 SpvOpFOrdEqual, SpvOpIEqual,
135 SpvOpIEqual, SpvOpLogicalEqual);
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400136 fIntrinsicMap[String("notEqual")] = std::make_tuple(kSPIRV_IntrinsicKind,
Ethan Nicholas0187ae62017-05-03 11:03:44 -0400137 SpvOpFOrdNotEqual, SpvOpINotEqual,
138 SpvOpINotEqual,
139 SpvOpLogicalNotEqual);
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400140 fIntrinsicMap[String("lessThan")] = std::make_tuple(kSPIRV_IntrinsicKind,
Ethan Nicholas70a44b22017-11-30 09:09:16 -0500141 SpvOpFOrdLessThan, SpvOpSLessThan,
142 SpvOpULessThan, SpvOpUndef);
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400143 fIntrinsicMap[String("lessThanEqual")] = std::make_tuple(kSPIRV_IntrinsicKind,
Ethan Nicholas70a44b22017-11-30 09:09:16 -0500144 SpvOpFOrdLessThanEqual,
Ethan Nicholas0187ae62017-05-03 11:03:44 -0400145 SpvOpSLessThanEqual,
146 SpvOpULessThanEqual,
Ethan Nicholas0187ae62017-05-03 11:03:44 -0400147 SpvOpUndef);
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400148 fIntrinsicMap[String("greaterThan")] = std::make_tuple(kSPIRV_IntrinsicKind,
Ethan Nicholas70a44b22017-11-30 09:09:16 -0500149 SpvOpFOrdGreaterThan,
Ethan Nicholas0187ae62017-05-03 11:03:44 -0400150 SpvOpSGreaterThan,
151 SpvOpUGreaterThan,
Ethan Nicholas0187ae62017-05-03 11:03:44 -0400152 SpvOpUndef);
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400153 fIntrinsicMap[String("greaterThanEqual")] = std::make_tuple(kSPIRV_IntrinsicKind,
Ethan Nicholas70a44b22017-11-30 09:09:16 -0500154 SpvOpFOrdGreaterThanEqual,
Ethan Nicholas0187ae62017-05-03 11:03:44 -0400155 SpvOpSGreaterThanEqual,
156 SpvOpUGreaterThanEqual,
Ethan Nicholas0187ae62017-05-03 11:03:44 -0400157 SpvOpUndef);
Ethan Nicholasbb155e22017-07-24 10:05:09 -0400158 fIntrinsicMap[String("EmitVertex")] = ALL_SPIRV(EmitVertex);
159 fIntrinsicMap[String("EndPrimitive")] = ALL_SPIRV(EndPrimitive);
ethannicholasb3058bd2016-07-01 08:22:01 -0700160// interpolateAt* not yet supported...
161}
162
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400163void SPIRVCodeGenerator::writeWord(int32_t word, OutputStream& out) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700164 out.write((const char*) &word, sizeof(word));
ethannicholasb3058bd2016-07-01 08:22:01 -0700165}
166
ethannicholasd598f792016-07-25 10:08:54 -0700167static bool is_float(const Context& context, const Type& type) {
Ethan Nicholas0df21132018-07-10 09:37:51 -0400168 if (type.columns() > 1) {
ethannicholasd598f792016-07-25 10:08:54 -0700169 return is_float(context, type.componentType());
ethannicholasb3058bd2016-07-01 08:22:01 -0700170 }
John Stiles123501f2020-12-09 10:08:13 -0500171 return type.isFloat();
ethannicholasb3058bd2016-07-01 08:22:01 -0700172}
173
ethannicholasd598f792016-07-25 10:08:54 -0700174static bool is_signed(const Context& context, const Type& type) {
John Stiles9aeed132020-11-24 17:36:06 -0500175 if (type.isVector()) {
ethannicholasd598f792016-07-25 10:08:54 -0700176 return is_signed(context, type.componentType());
ethannicholasb3058bd2016-07-01 08:22:01 -0700177 }
John Stiles123501f2020-12-09 10:08:13 -0500178 return type.isSigned();
ethannicholasb3058bd2016-07-01 08:22:01 -0700179}
180
ethannicholasd598f792016-07-25 10:08:54 -0700181static bool is_unsigned(const Context& context, const Type& type) {
John Stiles9aeed132020-11-24 17:36:06 -0500182 if (type.isVector()) {
ethannicholasd598f792016-07-25 10:08:54 -0700183 return is_unsigned(context, type.componentType());
ethannicholasb3058bd2016-07-01 08:22:01 -0700184 }
John Stiles123501f2020-12-09 10:08:13 -0500185 return type.isUnsigned();
ethannicholasb3058bd2016-07-01 08:22:01 -0700186}
187
ethannicholasd598f792016-07-25 10:08:54 -0700188static bool is_bool(const Context& context, const Type& type) {
John Stiles9aeed132020-11-24 17:36:06 -0500189 if (type.isVector()) {
ethannicholasd598f792016-07-25 10:08:54 -0700190 return is_bool(context, type.componentType());
ethannicholasb3058bd2016-07-01 08:22:01 -0700191 }
John Stiles123501f2020-12-09 10:08:13 -0500192 return type.isBoolean();
ethannicholasb3058bd2016-07-01 08:22:01 -0700193}
194
ethannicholasd598f792016-07-25 10:08:54 -0700195static bool is_out(const Variable& var) {
Ethan Nicholas041fd0a2020-10-07 16:42:04 -0400196 return (var.modifiers().fFlags & Modifiers::kOut_Flag) != 0;
ethannicholasb3058bd2016-07-01 08:22:01 -0700197}
198
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400199void SPIRVCodeGenerator::writeOpCode(SpvOp_ opCode, int length, OutputStream& out) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400200 SkASSERT(opCode != SpvOpLoad || &out != &fConstantBuffer);
201 SkASSERT(opCode != SpvOpUndef);
ethannicholasb3058bd2016-07-01 08:22:01 -0700202 switch (opCode) {
203 case SpvOpReturn: // fall through
204 case SpvOpReturnValue: // fall through
ethannicholas552882f2016-07-07 06:30:48 -0700205 case SpvOpKill: // fall through
Ethan Nicholas7fb39362020-12-16 15:25:19 -0500206 case SpvOpSwitch: // fall through
ethannicholasb3058bd2016-07-01 08:22:01 -0700207 case SpvOpBranch: // fall through
208 case SpvOpBranchConditional:
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400209 SkASSERT(fCurrentBlock);
ethannicholasb3058bd2016-07-01 08:22:01 -0700210 fCurrentBlock = 0;
211 break;
212 case SpvOpConstant: // fall through
213 case SpvOpConstantTrue: // fall through
214 case SpvOpConstantFalse: // fall through
215 case SpvOpConstantComposite: // fall through
216 case SpvOpTypeVoid: // fall through
217 case SpvOpTypeInt: // fall through
218 case SpvOpTypeFloat: // fall through
219 case SpvOpTypeBool: // fall through
220 case SpvOpTypeVector: // fall through
221 case SpvOpTypeMatrix: // fall through
222 case SpvOpTypeArray: // fall through
223 case SpvOpTypePointer: // fall through
224 case SpvOpTypeFunction: // fall through
225 case SpvOpTypeRuntimeArray: // fall through
226 case SpvOpTypeStruct: // fall through
227 case SpvOpTypeImage: // fall through
228 case SpvOpTypeSampledImage: // fall through
Stephen Whiteff5d7a22019-07-26 17:42:06 -0400229 case SpvOpTypeSampler: // fall through
ethannicholasb3058bd2016-07-01 08:22:01 -0700230 case SpvOpVariable: // fall through
231 case SpvOpFunction: // fall through
232 case SpvOpFunctionParameter: // fall through
233 case SpvOpFunctionEnd: // fall through
234 case SpvOpExecutionMode: // fall through
235 case SpvOpMemoryModel: // fall through
236 case SpvOpCapability: // fall through
237 case SpvOpExtInstImport: // fall through
238 case SpvOpEntryPoint: // fall through
239 case SpvOpSource: // fall through
240 case SpvOpSourceExtension: // fall through
241 case SpvOpName: // fall through
242 case SpvOpMemberName: // fall through
243 case SpvOpDecorate: // fall through
244 case SpvOpMemberDecorate:
245 break;
246 default:
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400247 SkASSERT(fCurrentBlock);
ethannicholasb3058bd2016-07-01 08:22:01 -0700248 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700249 this->writeWord((length << 16) | opCode, out);
ethannicholasb3058bd2016-07-01 08:22:01 -0700250}
251
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400252void SPIRVCodeGenerator::writeLabel(SpvId label, OutputStream& out) {
Ethan Nicholas7fb39362020-12-16 15:25:19 -0500253 SkASSERT(!fCurrentBlock);
ethannicholasb3058bd2016-07-01 08:22:01 -0700254 fCurrentBlock = label;
255 this->writeInstruction(SpvOpLabel, label, out);
256}
257
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400258void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, OutputStream& out) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700259 this->writeOpCode(opCode, 1, out);
260}
261
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400262void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, int32_t word1, OutputStream& out) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700263 this->writeOpCode(opCode, 2, out);
264 this->writeWord(word1, out);
265}
266
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700267void SPIRVCodeGenerator::writeString(const char* string, size_t length, OutputStream& out) {
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400268 out.write(string, length);
ethannicholasb3058bd2016-07-01 08:22:01 -0700269 switch (length % 4) {
270 case 1:
Ethan Nicholas9e1138d2016-11-21 10:39:35 -0500271 out.write8(0);
John Stiles30212b72020-06-11 17:55:07 -0400272 [[fallthrough]];
ethannicholasb3058bd2016-07-01 08:22:01 -0700273 case 2:
Ethan Nicholas9e1138d2016-11-21 10:39:35 -0500274 out.write8(0);
John Stiles30212b72020-06-11 17:55:07 -0400275 [[fallthrough]];
ethannicholasb3058bd2016-07-01 08:22:01 -0700276 case 3:
Ethan Nicholas9e1138d2016-11-21 10:39:35 -0500277 out.write8(0);
ethannicholasb3058bd2016-07-01 08:22:01 -0700278 break;
279 default:
280 this->writeWord(0, out);
281 }
282}
283
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700284void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, StringFragment string, OutputStream& out) {
285 this->writeOpCode(opCode, 1 + (string.fLength + 4) / 4, out);
286 this->writeString(string.fChars, string.fLength, out);
ethannicholasb3058bd2016-07-01 08:22:01 -0700287}
288
289
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700290void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, int32_t word1, StringFragment string,
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400291 OutputStream& out) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700292 this->writeOpCode(opCode, 2 + (string.fLength + 4) / 4, out);
ethannicholasb3058bd2016-07-01 08:22:01 -0700293 this->writeWord(word1, out);
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700294 this->writeString(string.fChars, string.fLength, out);
ethannicholasb3058bd2016-07-01 08:22:01 -0700295}
296
Greg Daniel64773e62016-11-22 09:44:03 -0500297void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, int32_t word1, int32_t word2,
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700298 StringFragment string, OutputStream& out) {
299 this->writeOpCode(opCode, 3 + (string.fLength + 4) / 4, out);
ethannicholasb3058bd2016-07-01 08:22:01 -0700300 this->writeWord(word1, out);
301 this->writeWord(word2, out);
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700302 this->writeString(string.fChars, string.fLength, out);
ethannicholasb3058bd2016-07-01 08:22:01 -0700303}
304
Greg Daniel64773e62016-11-22 09:44:03 -0500305void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, int32_t word1, int32_t word2,
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400306 OutputStream& out) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700307 this->writeOpCode(opCode, 3, out);
308 this->writeWord(word1, out);
309 this->writeWord(word2, out);
310}
311
Greg Daniel64773e62016-11-22 09:44:03 -0500312void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, int32_t word1, int32_t word2,
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400313 int32_t word3, OutputStream& out) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700314 this->writeOpCode(opCode, 4, out);
315 this->writeWord(word1, out);
316 this->writeWord(word2, out);
317 this->writeWord(word3, out);
318}
319
Greg Daniel64773e62016-11-22 09:44:03 -0500320void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, int32_t word1, int32_t word2,
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400321 int32_t word3, int32_t word4, OutputStream& out) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700322 this->writeOpCode(opCode, 5, out);
323 this->writeWord(word1, out);
324 this->writeWord(word2, out);
325 this->writeWord(word3, out);
326 this->writeWord(word4, out);
327}
328
Greg Daniel64773e62016-11-22 09:44:03 -0500329void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, int32_t word1, int32_t word2,
330 int32_t word3, int32_t word4, int32_t word5,
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400331 OutputStream& out) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700332 this->writeOpCode(opCode, 6, out);
333 this->writeWord(word1, out);
334 this->writeWord(word2, out);
335 this->writeWord(word3, out);
336 this->writeWord(word4, out);
337 this->writeWord(word5, out);
338}
339
Greg Daniel64773e62016-11-22 09:44:03 -0500340void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, int32_t word1, int32_t word2,
ethannicholasb3058bd2016-07-01 08:22:01 -0700341 int32_t word3, int32_t word4, int32_t word5,
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400342 int32_t word6, OutputStream& out) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700343 this->writeOpCode(opCode, 7, out);
344 this->writeWord(word1, out);
345 this->writeWord(word2, out);
346 this->writeWord(word3, out);
347 this->writeWord(word4, out);
348 this->writeWord(word5, out);
349 this->writeWord(word6, out);
350}
351
Greg Daniel64773e62016-11-22 09:44:03 -0500352void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, int32_t word1, int32_t word2,
ethannicholasb3058bd2016-07-01 08:22:01 -0700353 int32_t word3, int32_t word4, int32_t word5,
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400354 int32_t word6, int32_t word7, OutputStream& out) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700355 this->writeOpCode(opCode, 8, out);
356 this->writeWord(word1, out);
357 this->writeWord(word2, out);
358 this->writeWord(word3, out);
359 this->writeWord(word4, out);
360 this->writeWord(word5, out);
361 this->writeWord(word6, out);
362 this->writeWord(word7, out);
363}
364
Greg Daniel64773e62016-11-22 09:44:03 -0500365void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, int32_t word1, int32_t word2,
ethannicholasb3058bd2016-07-01 08:22:01 -0700366 int32_t word3, int32_t word4, int32_t word5,
367 int32_t word6, int32_t word7, int32_t word8,
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400368 OutputStream& out) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700369 this->writeOpCode(opCode, 9, out);
370 this->writeWord(word1, out);
371 this->writeWord(word2, out);
372 this->writeWord(word3, out);
373 this->writeWord(word4, out);
374 this->writeWord(word5, out);
375 this->writeWord(word6, out);
376 this->writeWord(word7, out);
377 this->writeWord(word8, out);
378}
379
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400380void SPIRVCodeGenerator::writeCapabilities(OutputStream& out) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700381 for (uint64_t i = 0, bit = 1; i <= kLast_Capability; i++, bit <<= 1) {
382 if (fCapabilities & bit) {
383 this->writeInstruction(SpvOpCapability, (SpvId) i, out);
384 }
385 }
Ethan Nicholasbb155e22017-07-24 10:05:09 -0400386 if (fProgram.fKind == Program::kGeometry_Kind) {
387 this->writeInstruction(SpvOpCapability, SpvCapabilityGeometry, out);
388 }
Ethan Nicholas81d15112018-07-13 12:48:50 -0400389 else {
390 this->writeInstruction(SpvOpCapability, SpvCapabilityShader, out);
391 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700392}
393
394SpvId SPIRVCodeGenerator::nextId() {
395 return fIdCount++;
396}
397
Ethan Nicholas19671772016-11-28 16:30:17 -0500398void SPIRVCodeGenerator::writeStruct(const Type& type, const MemoryLayout& memoryLayout,
399 SpvId resultId) {
Ethan Nicholase2c49992020-10-05 11:49:11 -0400400 this->writeInstruction(SpvOpName, resultId, String(type.name()).c_str(), fNameBuffer);
ethannicholasb3058bd2016-07-01 08:22:01 -0700401 // go ahead and write all of the field types, so we don't inadvertently write them while we're
402 // in the middle of writing the struct instruction
403 std::vector<SpvId> types;
404 for (const auto& f : type.fields()) {
Ethan Nicholas19671772016-11-28 16:30:17 -0500405 types.push_back(this->getType(*f.fType, memoryLayout));
ethannicholasb3058bd2016-07-01 08:22:01 -0700406 }
407 this->writeOpCode(SpvOpTypeStruct, 2 + (int32_t) types.size(), fConstantBuffer);
408 this->writeWord(resultId, fConstantBuffer);
409 for (SpvId id : types) {
410 this->writeWord(id, fConstantBuffer);
411 }
412 size_t offset = 0;
413 for (int32_t i = 0; i < (int32_t) type.fields().size(); i++) {
Ethan Nicholascc5d3e02019-04-19 09:50:56 -0400414 const Type::Field& field = type.fields()[i];
John Stiles21f5f452020-11-30 09:57:59 -0500415 if (!MemoryLayout::LayoutIsSupported(*field.fType)) {
John Stiles0023c0c2020-11-16 13:32:18 -0500416 fErrors.error(type.fOffset, "type '" + field.fType->name() + "' is not permitted here");
417 return;
418 }
Ethan Nicholascc5d3e02019-04-19 09:50:56 -0400419 size_t size = memoryLayout.size(*field.fType);
420 size_t alignment = memoryLayout.alignment(*field.fType);
421 const Layout& fieldLayout = field.fModifiers.fLayout;
Ethan Nicholas19671772016-11-28 16:30:17 -0500422 if (fieldLayout.fOffset >= 0) {
Greg Danieldbd44c72017-01-24 15:12:12 -0500423 if (fieldLayout.fOffset < (int) offset) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700424 fErrors.error(type.fOffset,
Ethan Nicholascc5d3e02019-04-19 09:50:56 -0400425 "offset of field '" + field.fName + "' must be at "
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500426 "least " + to_string((int) offset));
Ethan Nicholas19671772016-11-28 16:30:17 -0500427 }
428 if (fieldLayout.fOffset % alignment) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700429 fErrors.error(type.fOffset,
Ethan Nicholascc5d3e02019-04-19 09:50:56 -0400430 "offset of field '" + field.fName + "' must be a multiple"
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500431 " of " + to_string((int) alignment));
Ethan Nicholas19671772016-11-28 16:30:17 -0500432 }
433 offset = fieldLayout.fOffset;
434 } else {
435 size_t mod = offset % alignment;
436 if (mod) {
437 offset += alignment - mod;
438 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700439 }
Ethan Nicholascc5d3e02019-04-19 09:50:56 -0400440 this->writeInstruction(SpvOpMemberName, resultId, i, field.fName, fNameBuffer);
Ethan Nicholas19671772016-11-28 16:30:17 -0500441 this->writeLayout(fieldLayout, resultId, i);
Ethan Nicholascc5d3e02019-04-19 09:50:56 -0400442 if (field.fModifiers.fLayout.fBuiltin < 0) {
Greg Daniel64773e62016-11-22 09:44:03 -0500443 this->writeInstruction(SpvOpMemberDecorate, resultId, (SpvId) i, SpvDecorationOffset,
ethannicholasb3058bd2016-07-01 08:22:01 -0700444 (SpvId) offset, fDecorationBuffer);
445 }
John Stiles9aeed132020-11-24 17:36:06 -0500446 if (field.fType->isMatrix()) {
Greg Daniel64773e62016-11-22 09:44:03 -0500447 this->writeInstruction(SpvOpMemberDecorate, resultId, i, SpvDecorationColMajor,
ethannicholasb3058bd2016-07-01 08:22:01 -0700448 fDecorationBuffer);
Greg Daniel64773e62016-11-22 09:44:03 -0500449 this->writeInstruction(SpvOpMemberDecorate, resultId, i, SpvDecorationMatrixStride,
Ethan Nicholascc5d3e02019-04-19 09:50:56 -0400450 (SpvId) memoryLayout.stride(*field.fType),
ethannicholas8ac838d2016-11-22 08:39:36 -0800451 fDecorationBuffer);
ethannicholasb3058bd2016-07-01 08:22:01 -0700452 }
Ethan Nicholascc5d3e02019-04-19 09:50:56 -0400453 if (!field.fType->highPrecision()) {
454 this->writeInstruction(SpvOpMemberDecorate, resultId, (SpvId) i,
455 SpvDecorationRelaxedPrecision, fDecorationBuffer);
456 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700457 offset += size;
John Stilesc0c51062020-12-03 17:16:29 -0500458 if ((field.fType->isArray() || field.fType->isStruct()) && offset % alignment != 0) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700459 offset += alignment - offset % alignment;
460 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700461 }
462}
463
Ethan Nicholase2c49992020-10-05 11:49:11 -0400464const Type& SPIRVCodeGenerator::getActualType(const Type& type) {
Ethan Nicholase1f55022019-02-05 17:17:40 -0500465 if (type.isFloat()) {
John Stiles54e7c052021-01-11 14:22:36 -0500466 return *fContext.fTypes.fFloat;
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400467 }
Ethan Nicholase1f55022019-02-05 17:17:40 -0500468 if (type.isSigned()) {
John Stiles54e7c052021-01-11 14:22:36 -0500469 return *fContext.fTypes.fInt;
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400470 }
Ethan Nicholase1f55022019-02-05 17:17:40 -0500471 if (type.isUnsigned()) {
John Stiles54e7c052021-01-11 14:22:36 -0500472 return *fContext.fTypes.fUInt;
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400473 }
John Stiles9aeed132020-11-24 17:36:06 -0500474 if (type.isMatrix() || type.isVector()) {
John Stiles54e7c052021-01-11 14:22:36 -0500475 if (type.componentType() == *fContext.fTypes.fHalf) {
476 return fContext.fTypes.fFloat->toCompound(fContext, type.columns(), type.rows());
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400477 }
John Stiles54e7c052021-01-11 14:22:36 -0500478 if (type.componentType() == *fContext.fTypes.fShort ||
479 type.componentType() == *fContext.fTypes.fByte) {
480 return fContext.fTypes.fInt->toCompound(fContext, type.columns(), type.rows());
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400481 }
John Stiles54e7c052021-01-11 14:22:36 -0500482 if (type.componentType() == *fContext.fTypes.fUShort ||
483 type.componentType() == *fContext.fTypes.fUByte) {
484 return fContext.fTypes.fUInt->toCompound(fContext, type.columns(), type.rows());
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400485 }
486 }
487 return type;
488}
489
ethannicholasb3058bd2016-07-01 08:22:01 -0700490SpvId SPIRVCodeGenerator::getType(const Type& type) {
ethannicholas8ac838d2016-11-22 08:39:36 -0800491 return this->getType(type, fDefaultLayout);
492}
493
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400494SpvId SPIRVCodeGenerator::getType(const Type& rawType, const MemoryLayout& layout) {
Ethan Nicholase2c49992020-10-05 11:49:11 -0400495 const Type& type = this->getActualType(rawType);
Jim Van Verthf3ec9832020-10-21 16:09:57 -0400496 String key = type.name();
John Stilesc0c51062020-12-03 17:16:29 -0500497 if (type.isStruct() || type.isArray()) {
Jim Van Verthf3ec9832020-10-21 16:09:57 -0400498 key += to_string((int)layout.fStd);
499 }
ethannicholas8ac838d2016-11-22 08:39:36 -0800500 auto entry = fTypeMap.find(key);
ethannicholasb3058bd2016-07-01 08:22:01 -0700501 if (entry == fTypeMap.end()) {
502 SpvId result = this->nextId();
Ethan Nicholase6592142020-09-08 10:22:09 -0400503 switch (type.typeKind()) {
504 case Type::TypeKind::kScalar:
John Stiles4a7dc462020-11-25 11:08:08 -0500505 if (type.isBoolean()) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700506 this->writeInstruction(SpvOpTypeBool, result, fConstantBuffer);
John Stiles54e7c052021-01-11 14:22:36 -0500507 } else if (type == *fContext.fTypes.fInt || type == *fContext.fTypes.fShort ||
508 type == *fContext.fTypes.fIntLiteral) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700509 this->writeInstruction(SpvOpTypeInt, result, 32, 1, fConstantBuffer);
John Stiles54e7c052021-01-11 14:22:36 -0500510 } else if (type == *fContext.fTypes.fUInt || type == *fContext.fTypes.fUShort) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700511 this->writeInstruction(SpvOpTypeInt, result, 32, 0, fConstantBuffer);
John Stiles54e7c052021-01-11 14:22:36 -0500512 } else if (type == *fContext.fTypes.fFloat || type == *fContext.fTypes.fHalf ||
513 type == *fContext.fTypes.fFloatLiteral) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700514 this->writeInstruction(SpvOpTypeFloat, result, 32, fConstantBuffer);
ethannicholasb3058bd2016-07-01 08:22:01 -0700515 } else {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400516 SkASSERT(false);
ethannicholasb3058bd2016-07-01 08:22:01 -0700517 }
518 break;
John Stilesfd41d872020-11-25 22:39:45 -0500519 case Type::TypeKind::kEnum:
520 this->writeInstruction(SpvOpTypeInt, result, 32, 1, fConstantBuffer);
521 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400522 case Type::TypeKind::kVector:
Greg Daniel64773e62016-11-22 09:44:03 -0500523 this->writeInstruction(SpvOpTypeVector, result,
ethannicholas8ac838d2016-11-22 08:39:36 -0800524 this->getType(type.componentType(), layout),
ethannicholasb3058bd2016-07-01 08:22:01 -0700525 type.columns(), fConstantBuffer);
526 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400527 case Type::TypeKind::kMatrix:
Greg Daniel64773e62016-11-22 09:44:03 -0500528 this->writeInstruction(SpvOpTypeMatrix, result,
ethannicholas8ac838d2016-11-22 08:39:36 -0800529 this->getType(index_type(fContext, type), layout),
ethannicholasb3058bd2016-07-01 08:22:01 -0700530 type.columns(), fConstantBuffer);
531 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400532 case Type::TypeKind::kStruct:
ethannicholas8ac838d2016-11-22 08:39:36 -0800533 this->writeStruct(type, layout, result);
ethannicholasb3058bd2016-07-01 08:22:01 -0700534 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400535 case Type::TypeKind::kArray: {
John Stiles21f5f452020-11-30 09:57:59 -0500536 if (!MemoryLayout::LayoutIsSupported(type)) {
537 fErrors.error(type.fOffset, "type '" + type.name() + "' is not permitted here");
538 return this->nextId();
539 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700540 if (type.columns() > 0) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700541 IntLiteral count(fContext, -1, type.columns());
Greg Daniel64773e62016-11-22 09:44:03 -0500542 this->writeInstruction(SpvOpTypeArray, result,
ethannicholas8ac838d2016-11-22 08:39:36 -0800543 this->getType(type.componentType(), layout),
ethannicholasb3058bd2016-07-01 08:22:01 -0700544 this->writeIntLiteral(count), fConstantBuffer);
Greg Daniel64773e62016-11-22 09:44:03 -0500545 this->writeInstruction(SpvOpDecorate, result, SpvDecorationArrayStride,
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400546 (int32_t) layout.stride(type),
ethannicholas8ac838d2016-11-22 08:39:36 -0800547 fDecorationBuffer);
ethannicholasb3058bd2016-07-01 08:22:01 -0700548 } else {
John Stiles5570c512020-11-19 17:58:07 -0500549 // We shouldn't have any runtime-sized arrays right now
550 fErrors.error(type.fOffset, "runtime-sized arrays are not supported in SPIR-V");
Greg Daniel64773e62016-11-22 09:44:03 -0500551 this->writeInstruction(SpvOpTypeRuntimeArray, result,
ethannicholas8ac838d2016-11-22 08:39:36 -0800552 this->getType(type.componentType(), layout),
553 fConstantBuffer);
Ethan Nicholas0dd30d92017-05-01 16:57:07 -0400554 this->writeInstruction(SpvOpDecorate, result, SpvDecorationArrayStride,
555 (int32_t) layout.stride(type),
556 fDecorationBuffer);
ethannicholasb3058bd2016-07-01 08:22:01 -0700557 }
558 break;
559 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400560 case Type::TypeKind::kSampler: {
Greg Daniel64773e62016-11-22 09:44:03 -0500561 SpvId image = result;
562 if (SpvDimSubpassData != type.dimensions()) {
Stephen White792e2302019-08-09 13:33:51 -0400563 image = this->getType(type.textureType(), layout);
Greg Daniel64773e62016-11-22 09:44:03 -0500564 }
Ethan Nicholas0187ae62017-05-03 11:03:44 -0400565 if (SpvDimBuffer == type.dimensions()) {
566 fCapabilities |= (((uint64_t) 1) << SpvCapabilitySampledBuffer);
567 }
Greg Daniel64773e62016-11-22 09:44:03 -0500568 if (SpvDimSubpassData != type.dimensions()) {
569 this->writeInstruction(SpvOpTypeSampledImage, result, image, fConstantBuffer);
570 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700571 break;
572 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400573 case Type::TypeKind::kSeparateSampler: {
Stephen Whiteff5d7a22019-07-26 17:42:06 -0400574 this->writeInstruction(SpvOpTypeSampler, result, fConstantBuffer);
575 break;
576 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400577 case Type::TypeKind::kTexture: {
Stephen Whiteff5d7a22019-07-26 17:42:06 -0400578 this->writeInstruction(SpvOpTypeImage, result,
John Stiles54e7c052021-01-11 14:22:36 -0500579 this->getType(*fContext.fTypes.fFloat, layout),
John Stilesc0c51062020-12-03 17:16:29 -0500580 type.dimensions(), type.isDepth(), type.isArrayedTexture(),
Stephen White792e2302019-08-09 13:33:51 -0400581 type.isMultisampled(), type.isSampled() ? 1 : 2,
Stephen Whiteff5d7a22019-07-26 17:42:06 -0400582 SpvImageFormatUnknown, fConstantBuffer);
583 fImageTypeMap[key] = result;
584 break;
585 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700586 default:
John Stiles54e7c052021-01-11 14:22:36 -0500587 if (type == *fContext.fTypes.fVoid) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700588 this->writeInstruction(SpvOpTypeVoid, result, fConstantBuffer);
589 } else {
Ethan Nicholas2a099da2020-01-02 14:40:54 -0500590#ifdef SK_DEBUG
ethannicholasb3058bd2016-07-01 08:22:01 -0700591 ABORT("invalid type: %s", type.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -0500592#endif
ethannicholasb3058bd2016-07-01 08:22:01 -0700593 }
594 }
ethannicholas8ac838d2016-11-22 08:39:36 -0800595 fTypeMap[key] = result;
ethannicholasb3058bd2016-07-01 08:22:01 -0700596 return result;
597 }
598 return entry->second;
599}
600
Ethan Nicholas0187ae62017-05-03 11:03:44 -0400601SpvId SPIRVCodeGenerator::getImageType(const Type& type) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400602 SkASSERT(type.typeKind() == Type::TypeKind::kSampler);
Ethan Nicholas0187ae62017-05-03 11:03:44 -0400603 this->getType(type);
604 String key = type.name() + to_string((int) fDefaultLayout.fStd);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400605 SkASSERT(fImageTypeMap.find(key) != fImageTypeMap.end());
Ethan Nicholas0187ae62017-05-03 11:03:44 -0400606 return fImageTypeMap[key];
607}
608
ethannicholasd598f792016-07-25 10:08:54 -0700609SpvId SPIRVCodeGenerator::getFunctionType(const FunctionDeclaration& function) {
Ethan Nicholased84b732020-10-08 11:45:44 -0400610 String key = to_string(this->getType(function.returnType())) + "(";
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400611 String separator;
Brian Osman5bf3e202020-10-13 10:34:18 -0400612 const std::vector<const Variable*>& parameters = function.parameters();
Ethan Nicholased84b732020-10-08 11:45:44 -0400613 for (size_t i = 0; i < parameters.size(); i++) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700614 key += separator;
615 separator = ", ";
Ethan Nicholased84b732020-10-08 11:45:44 -0400616 key += to_string(this->getType(parameters[i]->type()));
ethannicholasb3058bd2016-07-01 08:22:01 -0700617 }
618 key += ")";
619 auto entry = fTypeMap.find(key);
620 if (entry == fTypeMap.end()) {
621 SpvId result = this->nextId();
Ethan Nicholased84b732020-10-08 11:45:44 -0400622 int32_t length = 3 + (int32_t) parameters.size();
623 SpvId returnType = this->getType(function.returnType());
ethannicholasb3058bd2016-07-01 08:22:01 -0700624 std::vector<SpvId> parameterTypes;
Ethan Nicholased84b732020-10-08 11:45:44 -0400625 for (size_t i = 0; i < parameters.size(); i++) {
Greg Daniel64773e62016-11-22 09:44:03 -0500626 // glslang seems to treat all function arguments as pointers whether they need to be or
627 // not. I was initially puzzled by this until I ran bizarre failures with certain
628 // patterns of function calls and control constructs, as exemplified by this minimal
ethannicholasb3058bd2016-07-01 08:22:01 -0700629 // failure case:
630 //
631 // void sphere(float x) {
632 // }
Greg Daniel64773e62016-11-22 09:44:03 -0500633 //
ethannicholasb3058bd2016-07-01 08:22:01 -0700634 // void map() {
635 // sphere(1.0);
636 // }
Greg Daniel64773e62016-11-22 09:44:03 -0500637 //
ethannicholasb3058bd2016-07-01 08:22:01 -0700638 // void main() {
639 // for (int i = 0; i < 1; i++) {
640 // map();
641 // }
642 // }
643 //
Greg Daniel64773e62016-11-22 09:44:03 -0500644 // As of this writing, compiling this in the "obvious" way (with sphere taking a float)
645 // crashes. Making it take a float* and storing the argument in a temporary variable,
ethannicholasb3058bd2016-07-01 08:22:01 -0700646 // as glslang does, fixes it. It's entirely possible I simply missed whichever part of
647 // the spec makes this make sense.
648// if (is_out(function->fParameters[i])) {
Ethan Nicholased84b732020-10-08 11:45:44 -0400649 parameterTypes.push_back(this->getPointerType(parameters[i]->type(),
ethannicholasb3058bd2016-07-01 08:22:01 -0700650 SpvStorageClassFunction));
651// } else {
ethannicholasd598f792016-07-25 10:08:54 -0700652// parameterTypes.push_back(this->getType(function.fParameters[i]->fType));
ethannicholasb3058bd2016-07-01 08:22:01 -0700653// }
654 }
655 this->writeOpCode(SpvOpTypeFunction, length, fConstantBuffer);
656 this->writeWord(result, fConstantBuffer);
657 this->writeWord(returnType, fConstantBuffer);
658 for (SpvId id : parameterTypes) {
659 this->writeWord(id, fConstantBuffer);
660 }
661 fTypeMap[key] = result;
662 return result;
663 }
664 return entry->second;
665}
666
ethannicholas8ac838d2016-11-22 08:39:36 -0800667SpvId SPIRVCodeGenerator::getPointerType(const Type& type, SpvStorageClass_ storageClass) {
668 return this->getPointerType(type, fDefaultLayout, storageClass);
669}
670
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400671SpvId SPIRVCodeGenerator::getPointerType(const Type& rawType, const MemoryLayout& layout,
ethannicholasb3058bd2016-07-01 08:22:01 -0700672 SpvStorageClass_ storageClass) {
Ethan Nicholase2c49992020-10-05 11:49:11 -0400673 const Type& type = this->getActualType(rawType);
Ethan Nicholas2a099da2020-01-02 14:40:54 -0500674 String key = type.displayName() + "*" + to_string(layout.fStd) + to_string(storageClass);
ethannicholasb3058bd2016-07-01 08:22:01 -0700675 auto entry = fTypeMap.find(key);
676 if (entry == fTypeMap.end()) {
677 SpvId result = this->nextId();
Greg Daniel64773e62016-11-22 09:44:03 -0500678 this->writeInstruction(SpvOpTypePointer, result, storageClass,
ethannicholasd598f792016-07-25 10:08:54 -0700679 this->getType(type), fConstantBuffer);
ethannicholasb3058bd2016-07-01 08:22:01 -0700680 fTypeMap[key] = result;
681 return result;
682 }
683 return entry->second;
684}
685
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400686SpvId SPIRVCodeGenerator::writeExpression(const Expression& expr, OutputStream& out) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400687 switch (expr.kind()) {
688 case Expression::Kind::kBinary:
John Stiles81365af2020-08-18 09:24:00 -0400689 return this->writeBinaryExpression(expr.as<BinaryExpression>(), out);
Ethan Nicholase6592142020-09-08 10:22:09 -0400690 case Expression::Kind::kBoolLiteral:
John Stiles81365af2020-08-18 09:24:00 -0400691 return this->writeBoolLiteral(expr.as<BoolLiteral>());
Ethan Nicholase6592142020-09-08 10:22:09 -0400692 case Expression::Kind::kConstructor:
John Stiles81365af2020-08-18 09:24:00 -0400693 return this->writeConstructor(expr.as<Constructor>(), out);
Ethan Nicholase6592142020-09-08 10:22:09 -0400694 case Expression::Kind::kIntLiteral:
John Stiles81365af2020-08-18 09:24:00 -0400695 return this->writeIntLiteral(expr.as<IntLiteral>());
Ethan Nicholase6592142020-09-08 10:22:09 -0400696 case Expression::Kind::kFieldAccess:
John Stiles81365af2020-08-18 09:24:00 -0400697 return this->writeFieldAccess(expr.as<FieldAccess>(), out);
Ethan Nicholase6592142020-09-08 10:22:09 -0400698 case Expression::Kind::kFloatLiteral:
John Stiles81365af2020-08-18 09:24:00 -0400699 return this->writeFloatLiteral(expr.as<FloatLiteral>());
Ethan Nicholase6592142020-09-08 10:22:09 -0400700 case Expression::Kind::kFunctionCall:
John Stiles81365af2020-08-18 09:24:00 -0400701 return this->writeFunctionCall(expr.as<FunctionCall>(), out);
Ethan Nicholase6592142020-09-08 10:22:09 -0400702 case Expression::Kind::kPrefix:
John Stiles81365af2020-08-18 09:24:00 -0400703 return this->writePrefixExpression(expr.as<PrefixExpression>(), out);
Ethan Nicholase6592142020-09-08 10:22:09 -0400704 case Expression::Kind::kPostfix:
John Stiles81365af2020-08-18 09:24:00 -0400705 return this->writePostfixExpression(expr.as<PostfixExpression>(), out);
Ethan Nicholase6592142020-09-08 10:22:09 -0400706 case Expression::Kind::kSwizzle:
John Stiles81365af2020-08-18 09:24:00 -0400707 return this->writeSwizzle(expr.as<Swizzle>(), out);
Ethan Nicholase6592142020-09-08 10:22:09 -0400708 case Expression::Kind::kVariableReference:
John Stiles81365af2020-08-18 09:24:00 -0400709 return this->writeVariableReference(expr.as<VariableReference>(), out);
Ethan Nicholase6592142020-09-08 10:22:09 -0400710 case Expression::Kind::kTernary:
John Stiles81365af2020-08-18 09:24:00 -0400711 return this->writeTernaryExpression(expr.as<TernaryExpression>(), out);
Ethan Nicholase6592142020-09-08 10:22:09 -0400712 case Expression::Kind::kIndex:
John Stiles81365af2020-08-18 09:24:00 -0400713 return this->writeIndexExpression(expr.as<IndexExpression>(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -0700714 default:
Ethan Nicholas2a099da2020-01-02 14:40:54 -0500715#ifdef SK_DEBUG
ethannicholasb3058bd2016-07-01 08:22:01 -0700716 ABORT("unsupported expression: %s", expr.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -0500717#endif
718 break;
ethannicholasb3058bd2016-07-01 08:22:01 -0700719 }
720 return -1;
721}
722
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400723SpvId SPIRVCodeGenerator::writeIntrinsicCall(const FunctionCall& c, OutputStream& out) {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400724 const FunctionDeclaration& function = c.function();
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400725 auto intrinsic = fIntrinsicMap.find(function.name());
John Stiles93e661a2020-12-08 16:17:00 -0500726 if (intrinsic == fIntrinsicMap.end()) {
727 fErrors.error(c.fOffset, "unsupported intrinsic '" + function.description() + "'");
728 return -1;
729 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700730 int32_t intrinsicId;
John Stiles89ac7c22020-12-30 17:47:31 -0500731 const ExpressionArray& arguments = c.arguments();
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400732 if (arguments.size() > 0) {
733 const Type& type = arguments[0]->type();
Ethan Nicholasbb155e22017-07-24 10:05:09 -0400734 if (std::get<0>(intrinsic->second) == kSpecial_IntrinsicKind || is_float(fContext, type)) {
735 intrinsicId = std::get<1>(intrinsic->second);
736 } else if (is_signed(fContext, type)) {
737 intrinsicId = std::get<2>(intrinsic->second);
738 } else if (is_unsigned(fContext, type)) {
739 intrinsicId = std::get<3>(intrinsic->second);
740 } else if (is_bool(fContext, type)) {
741 intrinsicId = std::get<4>(intrinsic->second);
742 } else {
743 intrinsicId = std::get<1>(intrinsic->second);
744 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700745 } else {
Ethan Nicholasbb155e22017-07-24 10:05:09 -0400746 intrinsicId = std::get<1>(intrinsic->second);
ethannicholasb3058bd2016-07-01 08:22:01 -0700747 }
748 switch (std::get<0>(intrinsic->second)) {
749 case kGLSL_STD_450_IntrinsicKind: {
750 SpvId result = this->nextId();
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400751 std::vector<SpvId> argumentIds;
752 for (size_t i = 0; i < arguments.size(); i++) {
Ethan Nicholased84b732020-10-08 11:45:44 -0400753 if (function.parameters()[i]->modifiers().fFlags & Modifiers::kOut_Flag) {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400754 argumentIds.push_back(this->getLValue(*arguments[i], out)->getPointer());
Ethan Nicholas8f7e28f2018-03-26 14:24:27 -0400755 } else {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400756 argumentIds.push_back(this->writeExpression(*arguments[i], out));
Ethan Nicholas8f7e28f2018-03-26 14:24:27 -0400757 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700758 }
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400759 this->writeOpCode(SpvOpExtInst, 5 + (int32_t) argumentIds.size(), out);
Ethan Nicholas30d30222020-09-11 12:27:26 -0400760 this->writeWord(this->getType(c.type()), out);
ethannicholasb3058bd2016-07-01 08:22:01 -0700761 this->writeWord(result, out);
762 this->writeWord(fGLSLExtendedInstructions, out);
763 this->writeWord(intrinsicId, out);
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400764 for (SpvId id : argumentIds) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700765 this->writeWord(id, out);
766 }
767 return result;
768 }
769 case kSPIRV_IntrinsicKind: {
Brian Osman46787d52020-11-24 14:18:23 -0500770 // GLSL supports dot(float, float), but SPIR-V does not. Convert it to FMul
John Stiles9aeed132020-11-24 17:36:06 -0500771 if (intrinsicId == SpvOpDot && arguments[0]->type().isScalar()) {
Brian Osman46787d52020-11-24 14:18:23 -0500772 intrinsicId = SpvOpFMul;
773 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700774 SpvId result = this->nextId();
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400775 std::vector<SpvId> argumentIds;
776 for (size_t i = 0; i < arguments.size(); i++) {
Ethan Nicholased84b732020-10-08 11:45:44 -0400777 if (function.parameters()[i]->modifiers().fFlags & Modifiers::kOut_Flag) {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400778 argumentIds.push_back(this->getLValue(*arguments[i], out)->getPointer());
Ethan Nicholas8f7e28f2018-03-26 14:24:27 -0400779 } else {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400780 argumentIds.push_back(this->writeExpression(*arguments[i], out));
Ethan Nicholas8f7e28f2018-03-26 14:24:27 -0400781 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700782 }
John Stiles54e7c052021-01-11 14:22:36 -0500783 if (c.type() != *fContext.fTypes.fVoid) {
Ethan Nicholasbb155e22017-07-24 10:05:09 -0400784 this->writeOpCode((SpvOp_) intrinsicId, 3 + (int32_t) arguments.size(), out);
Ethan Nicholas30d30222020-09-11 12:27:26 -0400785 this->writeWord(this->getType(c.type()), out);
Ethan Nicholasbb155e22017-07-24 10:05:09 -0400786 this->writeWord(result, out);
787 } else {
788 this->writeOpCode((SpvOp_) intrinsicId, 1 + (int32_t) arguments.size(), out);
789 }
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400790 for (SpvId id : argumentIds) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700791 this->writeWord(id, out);
792 }
793 return result;
794 }
795 case kSpecial_IntrinsicKind:
796 return this->writeSpecialIntrinsic(c, (SpecialIntrinsic) intrinsicId, out);
797 default:
John Stiles93e661a2020-12-08 16:17:00 -0500798 fErrors.error(c.fOffset, "unsupported intrinsic '" + function.description() + "'");
799 return -1;
ethannicholasb3058bd2016-07-01 08:22:01 -0700800 }
801}
802
John Stiles8e3b6be2020-10-13 11:14:08 -0400803std::vector<SpvId> SPIRVCodeGenerator::vectorize(const ExpressionArray& args, OutputStream& out) {
Ethan Nicholas0fc07f92018-02-27 15:25:47 -0500804 int vectorSize = 0;
805 for (const auto& a : args) {
John Stiles9aeed132020-11-24 17:36:06 -0500806 if (a->type().isVector()) {
Ethan Nicholas0fc07f92018-02-27 15:25:47 -0500807 if (vectorSize) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400808 SkASSERT(a->type().columns() == vectorSize);
Ethan Nicholas0fc07f92018-02-27 15:25:47 -0500809 }
810 else {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400811 vectorSize = a->type().columns();
Ethan Nicholas0fc07f92018-02-27 15:25:47 -0500812 }
813 }
814 }
815 std::vector<SpvId> result;
John Stiles8e3b6be2020-10-13 11:14:08 -0400816 result.reserve(args.size());
Ethan Nicholas30d30222020-09-11 12:27:26 -0400817 for (const auto& arg : args) {
818 const Type& argType = arg->type();
819 SpvId raw = this->writeExpression(*arg, out);
John Stiles9aeed132020-11-24 17:36:06 -0500820 if (vectorSize && argType.isScalar()) {
Ethan Nicholas0fc07f92018-02-27 15:25:47 -0500821 SpvId vector = this->nextId();
822 this->writeOpCode(SpvOpCompositeConstruct, 3 + vectorSize, out);
Ethan Nicholas30d30222020-09-11 12:27:26 -0400823 this->writeWord(this->getType(argType.toCompound(fContext, vectorSize, 1)), out);
Ethan Nicholas0fc07f92018-02-27 15:25:47 -0500824 this->writeWord(vector, out);
825 for (int i = 0; i < vectorSize; i++) {
826 this->writeWord(raw, out);
827 }
Ethan Nicholas30d30222020-09-11 12:27:26 -0400828 this->writePrecisionModifier(argType, vector);
Ethan Nicholas0fc07f92018-02-27 15:25:47 -0500829 result.push_back(vector);
830 } else {
831 result.push_back(raw);
832 }
833 }
834 return result;
835}
836
837void SPIRVCodeGenerator::writeGLSLExtendedInstruction(const Type& type, SpvId id, SpvId floatInst,
838 SpvId signedInst, SpvId unsignedInst,
839 const std::vector<SpvId>& args,
840 OutputStream& out) {
841 this->writeOpCode(SpvOpExtInst, 5 + args.size(), out);
842 this->writeWord(this->getType(type), out);
843 this->writeWord(id, out);
844 this->writeWord(fGLSLExtendedInstructions, out);
845
846 if (is_float(fContext, type)) {
847 this->writeWord(floatInst, out);
848 } else if (is_signed(fContext, type)) {
849 this->writeWord(signedInst, out);
850 } else if (is_unsigned(fContext, type)) {
851 this->writeWord(unsignedInst, out);
852 } else {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400853 SkASSERT(false);
Ethan Nicholas0fc07f92018-02-27 15:25:47 -0500854 }
855 for (SpvId a : args) {
856 this->writeWord(a, out);
857 }
858}
859
Greg Daniel64773e62016-11-22 09:44:03 -0500860SpvId SPIRVCodeGenerator::writeSpecialIntrinsic(const FunctionCall& c, SpecialIntrinsic kind,
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400861 OutputStream& out) {
John Stiles8e3b6be2020-10-13 11:14:08 -0400862 const ExpressionArray& arguments = c.arguments();
ethannicholasb3058bd2016-07-01 08:22:01 -0700863 SpvId result = this->nextId();
Ethan Nicholas30d30222020-09-11 12:27:26 -0400864 const Type& callType = c.type();
ethannicholasb3058bd2016-07-01 08:22:01 -0700865 switch (kind) {
866 case kAtan_SpecialIntrinsic: {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400867 std::vector<SpvId> argumentIds;
868 for (const std::unique_ptr<Expression>& arg : arguments) {
869 argumentIds.push_back(this->writeExpression(*arg, out));
ethannicholasb3058bd2016-07-01 08:22:01 -0700870 }
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400871 this->writeOpCode(SpvOpExtInst, 5 + (int32_t) argumentIds.size(), out);
Ethan Nicholas30d30222020-09-11 12:27:26 -0400872 this->writeWord(this->getType(callType), out);
ethannicholasb3058bd2016-07-01 08:22:01 -0700873 this->writeWord(result, out);
874 this->writeWord(fGLSLExtendedInstructions, out);
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400875 this->writeWord(argumentIds.size() == 2 ? GLSLstd450Atan2 : GLSLstd450Atan, out);
876 for (SpvId id : argumentIds) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700877 this->writeWord(id, out);
878 }
Ethan Nicholas0187ae62017-05-03 11:03:44 -0400879 break;
880 }
Stephen Whiteff5d7a22019-07-26 17:42:06 -0400881 case kSampledImage_SpecialIntrinsic: {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400882 SkASSERT(arguments.size() == 2);
883 SpvId img = this->writeExpression(*arguments[0], out);
884 SpvId sampler = this->writeExpression(*arguments[1], out);
Stephen Whiteff5d7a22019-07-26 17:42:06 -0400885 this->writeInstruction(SpvOpSampledImage,
Ethan Nicholas30d30222020-09-11 12:27:26 -0400886 this->getType(callType),
Stephen Whiteff5d7a22019-07-26 17:42:06 -0400887 result,
888 img,
889 sampler,
890 out);
891 break;
892 }
Ethan Nicholas0187ae62017-05-03 11:03:44 -0400893 case kSubpassLoad_SpecialIntrinsic: {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400894 SpvId img = this->writeExpression(*arguments[0], out);
John Stiles8e3b6be2020-10-13 11:14:08 -0400895 ExpressionArray args;
John Stilesf4bda742020-10-14 16:57:41 -0400896 args.reserve_back(2);
John Stiles8e3b6be2020-10-13 11:14:08 -0400897 args.push_back(std::make_unique<IntLiteral>(fContext, /*offset=*/-1, /*value=*/0));
898 args.push_back(std::make_unique<IntLiteral>(fContext, /*offset=*/-1, /*value=*/0));
John Stiles54e7c052021-01-11 14:22:36 -0500899 Constructor ctor(-1, fContext.fTypes.fInt2.get(), std::move(args));
Ethan Nicholas0187ae62017-05-03 11:03:44 -0400900 SpvId coords = this->writeConstantVector(ctor);
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400901 if (arguments.size() == 1) {
Ethan Nicholas0187ae62017-05-03 11:03:44 -0400902 this->writeInstruction(SpvOpImageRead,
Ethan Nicholas30d30222020-09-11 12:27:26 -0400903 this->getType(callType),
Ethan Nicholas0187ae62017-05-03 11:03:44 -0400904 result,
905 img,
906 coords,
907 out);
908 } else {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400909 SkASSERT(arguments.size() == 2);
910 SpvId sample = this->writeExpression(*arguments[1], out);
Ethan Nicholas0187ae62017-05-03 11:03:44 -0400911 this->writeInstruction(SpvOpImageRead,
Ethan Nicholas30d30222020-09-11 12:27:26 -0400912 this->getType(callType),
Ethan Nicholas0187ae62017-05-03 11:03:44 -0400913 result,
914 img,
915 coords,
916 SpvImageOperandsSampleMask,
917 sample,
918 out);
919 }
920 break;
921 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700922 case kTexture_SpecialIntrinsic: {
Ethan Nicholas2b3dab62016-11-28 12:03:26 -0500923 SpvOp_ op = SpvOpImageSampleImplicitLod;
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400924 const Type& arg1Type = arguments[1]->type();
925 switch (arguments[0]->type().dimensions()) {
Ethan Nicholas2b3dab62016-11-28 12:03:26 -0500926 case SpvDim1D:
John Stiles54e7c052021-01-11 14:22:36 -0500927 if (arg1Type == *fContext.fTypes.fFloat2) {
Ethan Nicholas2b3dab62016-11-28 12:03:26 -0500928 op = SpvOpImageSampleProjImplicitLod;
929 } else {
John Stiles54e7c052021-01-11 14:22:36 -0500930 SkASSERT(arg1Type == *fContext.fTypes.fFloat);
Ethan Nicholas2b3dab62016-11-28 12:03:26 -0500931 }
932 break;
933 case SpvDim2D:
John Stiles54e7c052021-01-11 14:22:36 -0500934 if (arg1Type == *fContext.fTypes.fFloat3) {
Ethan Nicholas2b3dab62016-11-28 12:03:26 -0500935 op = SpvOpImageSampleProjImplicitLod;
936 } else {
John Stiles54e7c052021-01-11 14:22:36 -0500937 SkASSERT(arg1Type == *fContext.fTypes.fFloat2);
Ethan Nicholas2b3dab62016-11-28 12:03:26 -0500938 }
939 break;
940 case SpvDim3D:
John Stiles54e7c052021-01-11 14:22:36 -0500941 if (arg1Type == *fContext.fTypes.fFloat4) {
Ethan Nicholas2b3dab62016-11-28 12:03:26 -0500942 op = SpvOpImageSampleProjImplicitLod;
943 } else {
John Stiles54e7c052021-01-11 14:22:36 -0500944 SkASSERT(arg1Type == *fContext.fTypes.fFloat3);
Ethan Nicholas2b3dab62016-11-28 12:03:26 -0500945 }
946 break;
947 case SpvDimCube: // fall through
948 case SpvDimRect: // fall through
949 case SpvDimBuffer: // fall through
950 case SpvDimSubpassData:
951 break;
952 }
Ethan Nicholas30d30222020-09-11 12:27:26 -0400953 SpvId type = this->getType(callType);
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400954 SpvId sampler = this->writeExpression(*arguments[0], out);
955 SpvId uv = this->writeExpression(*arguments[1], out);
956 if (arguments.size() == 3) {
Ethan Nicholas2b3dab62016-11-28 12:03:26 -0500957 this->writeInstruction(op, type, result, sampler, uv,
ethannicholasb3058bd2016-07-01 08:22:01 -0700958 SpvImageOperandsBiasMask,
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400959 this->writeExpression(*arguments[2], out),
ethannicholasb3058bd2016-07-01 08:22:01 -0700960 out);
961 } else {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400962 SkASSERT(arguments.size() == 2);
Brian Osman8a83ca42018-02-12 14:32:17 -0500963 if (fProgram.fSettings.fSharpenTextures) {
964 FloatLiteral lodBias(fContext, -1, -0.5);
965 this->writeInstruction(op, type, result, sampler, uv,
966 SpvImageOperandsBiasMask,
967 this->writeFloatLiteral(lodBias),
968 out);
969 } else {
970 this->writeInstruction(op, type, result, sampler, uv,
971 out);
972 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700973 }
974 break;
975 }
Ethan Nicholas70a44b22017-11-30 09:09:16 -0500976 case kMod_SpecialIntrinsic: {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400977 std::vector<SpvId> args = this->vectorize(arguments, out);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400978 SkASSERT(args.size() == 2);
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400979 const Type& operandType = arguments[0]->type();
Ethan Nicholas70a44b22017-11-30 09:09:16 -0500980 SpvOp_ op;
981 if (is_float(fContext, operandType)) {
982 op = SpvOpFMod;
983 } else if (is_signed(fContext, operandType)) {
984 op = SpvOpSMod;
985 } else if (is_unsigned(fContext, operandType)) {
986 op = SpvOpUMod;
987 } else {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400988 SkASSERT(false);
Ethan Nicholas70a44b22017-11-30 09:09:16 -0500989 return 0;
990 }
991 this->writeOpCode(op, 5, out);
992 this->writeWord(this->getType(operandType), out);
993 this->writeWord(result, out);
Ethan Nicholas0fc07f92018-02-27 15:25:47 -0500994 this->writeWord(args[0], out);
995 this->writeWord(args[1], out);
996 break;
997 }
Chris Daltonb8af5ad2019-02-25 14:54:21 -0700998 case kDFdy_SpecialIntrinsic: {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400999 SpvId fn = this->writeExpression(*arguments[0], out);
Chris Daltonb8af5ad2019-02-25 14:54:21 -07001000 this->writeOpCode(SpvOpDPdy, 4, out);
Ethan Nicholas30d30222020-09-11 12:27:26 -04001001 this->writeWord(this->getType(callType), out);
Chris Daltonb8af5ad2019-02-25 14:54:21 -07001002 this->writeWord(result, out);
1003 this->writeWord(fn, out);
1004 if (fProgram.fSettings.fFlipY) {
1005 // Flipping Y also negates the Y derivatives.
1006 SpvId flipped = this->nextId();
Ethan Nicholas30d30222020-09-11 12:27:26 -04001007 this->writeInstruction(SpvOpFNegate, this->getType(callType), flipped, result,
1008 out);
1009 this->writePrecisionModifier(callType, flipped);
Chris Daltonb8af5ad2019-02-25 14:54:21 -07001010 return flipped;
1011 }
1012 break;
1013 }
Ethan Nicholas0fc07f92018-02-27 15:25:47 -05001014 case kClamp_SpecialIntrinsic: {
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001015 std::vector<SpvId> args = this->vectorize(arguments, out);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001016 SkASSERT(args.size() == 3);
Ethan Nicholas30d30222020-09-11 12:27:26 -04001017 this->writeGLSLExtendedInstruction(callType, result, GLSLstd450FClamp, GLSLstd450SClamp,
Ethan Nicholas0fc07f92018-02-27 15:25:47 -05001018 GLSLstd450UClamp, args, out);
1019 break;
1020 }
1021 case kMax_SpecialIntrinsic: {
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001022 std::vector<SpvId> args = this->vectorize(arguments, out);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001023 SkASSERT(args.size() == 2);
Ethan Nicholas30d30222020-09-11 12:27:26 -04001024 this->writeGLSLExtendedInstruction(callType, result, GLSLstd450FMax, GLSLstd450SMax,
Ethan Nicholas0fc07f92018-02-27 15:25:47 -05001025 GLSLstd450UMax, args, out);
1026 break;
1027 }
1028 case kMin_SpecialIntrinsic: {
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001029 std::vector<SpvId> args = this->vectorize(arguments, out);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001030 SkASSERT(args.size() == 2);
Ethan Nicholas30d30222020-09-11 12:27:26 -04001031 this->writeGLSLExtendedInstruction(callType, result, GLSLstd450FMin, GLSLstd450SMin,
Ethan Nicholas0fc07f92018-02-27 15:25:47 -05001032 GLSLstd450UMin, args, out);
1033 break;
1034 }
1035 case kMix_SpecialIntrinsic: {
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001036 std::vector<SpvId> args = this->vectorize(arguments, out);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001037 SkASSERT(args.size() == 3);
Ethan Nicholas30d30222020-09-11 12:27:26 -04001038 this->writeGLSLExtendedInstruction(callType, result, GLSLstd450FMix, SpvOpUndef,
Ethan Nicholas0fc07f92018-02-27 15:25:47 -05001039 SpvOpUndef, args, out);
1040 break;
Ethan Nicholas70a44b22017-11-30 09:09:16 -05001041 }
Ethan Nicholas12fb9cf2018-08-03 16:16:57 -04001042 case kSaturate_SpecialIntrinsic: {
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001043 SkASSERT(arguments.size() == 1);
John Stiles8e3b6be2020-10-13 11:14:08 -04001044 ExpressionArray finalArgs;
John Stilesf4bda742020-10-14 16:57:41 -04001045 finalArgs.reserve_back(3);
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001046 finalArgs.push_back(arguments[0]->clone());
John Stiles8e3b6be2020-10-13 11:14:08 -04001047 finalArgs.push_back(std::make_unique<FloatLiteral>(fContext, /*offset=*/-1,
1048 /*value=*/0));
1049 finalArgs.push_back(std::make_unique<FloatLiteral>(fContext, /*offset=*/-1,
1050 /*value=*/1));
Ethan Nicholas12fb9cf2018-08-03 16:16:57 -04001051 std::vector<SpvId> spvArgs = this->vectorize(finalArgs, out);
Ethan Nicholas30d30222020-09-11 12:27:26 -04001052 this->writeGLSLExtendedInstruction(callType, result, GLSLstd450FClamp, GLSLstd450SClamp,
Ethan Nicholas12fb9cf2018-08-03 16:16:57 -04001053 GLSLstd450UClamp, spvArgs, out);
1054 break;
1055 }
Brian Osman6ba3be12020-11-13 16:32:52 -05001056 case kSmoothStep_SpecialIntrinsic: {
1057 std::vector<SpvId> args = this->vectorize(arguments, out);
1058 SkASSERT(args.size() == 3);
1059 this->writeGLSLExtendedInstruction(callType, result, GLSLstd450SmoothStep, SpvOpUndef,
1060 SpvOpUndef, args, out);
1061 break;
1062 }
1063 case kStep_SpecialIntrinsic: {
1064 std::vector<SpvId> args = this->vectorize(arguments, out);
1065 SkASSERT(args.size() == 2);
1066 this->writeGLSLExtendedInstruction(callType, result, GLSLstd450Step, SpvOpUndef,
1067 SpvOpUndef, args, out);
1068 break;
1069 }
Brian Osmand1b593f2020-12-28 13:00:46 -05001070 case kMatrixCompMult_SpecialIntrinsic: {
1071 SkASSERT(arguments.size() == 2);
1072 SpvId lhs = this->writeExpression(*arguments[0], out);
1073 SpvId rhs = this->writeExpression(*arguments[1], out);
1074 result = this->writeComponentwiseMatrixBinary(callType, lhs, rhs, SpvOpFMul, SpvOpUndef,
1075 out);
1076 break;
1077 }
ethannicholasb3058bd2016-07-01 08:22:01 -07001078 }
1079 return result;
1080}
1081
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001082SpvId SPIRVCodeGenerator::writeFunctionCall(const FunctionCall& c, OutputStream& out) {
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001083 const FunctionDeclaration& function = c.function();
John Stiles89ac7c22020-12-30 17:47:31 -05001084 if (function.isBuiltin() && !function.definition()) {
1085 return this->writeIntrinsicCall(c, out);
1086 }
John Stiles8e3b6be2020-10-13 11:14:08 -04001087 const ExpressionArray& arguments = c.arguments();
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001088 const auto& entry = fFunctionMap.find(&function);
ethannicholasb3058bd2016-07-01 08:22:01 -07001089 if (entry == fFunctionMap.end()) {
John Stiles89ac7c22020-12-30 17:47:31 -05001090 fErrors.error(c.fOffset, "function '" + function.description() + "' is not defined");
1091 return -1;
ethannicholasb3058bd2016-07-01 08:22:01 -07001092 }
1093 // stores (variable, type, lvalue) pairs to extract and save after the function call is complete
Ethan Nicholas10e93b62019-03-20 10:46:14 -04001094 std::vector<std::tuple<SpvId, const Type*, std::unique_ptr<LValue>>> lvalues;
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001095 std::vector<SpvId> argumentIds;
1096 for (size_t i = 0; i < arguments.size(); i++) {
Greg Daniel64773e62016-11-22 09:44:03 -05001097 // id of temporary variable that we will use to hold this argument, or 0 if it is being
ethannicholasb3058bd2016-07-01 08:22:01 -07001098 // passed directly
1099 SpvId tmpVar;
1100 // if we need a temporary var to store this argument, this is the value to store in the var
1101 SpvId tmpValueId;
Ethan Nicholased84b732020-10-08 11:45:44 -04001102 if (is_out(*function.parameters()[i])) {
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001103 std::unique_ptr<LValue> lv = this->getLValue(*arguments[i], out);
ethannicholasb3058bd2016-07-01 08:22:01 -07001104 SpvId ptr = lv->getPointer();
1105 if (ptr) {
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001106 argumentIds.push_back(ptr);
ethannicholasb3058bd2016-07-01 08:22:01 -07001107 continue;
1108 } else {
1109 // lvalue cannot simply be read and written via a pointer (e.g. a swizzle). Need to
1110 // copy it into a temp, call the function, read the value out of the temp, and then
1111 // update the lvalue.
1112 tmpValueId = lv->load(out);
1113 tmpVar = this->nextId();
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001114 lvalues.push_back(std::make_tuple(tmpVar, &arguments[i]->type(), std::move(lv)));
ethannicholasb3058bd2016-07-01 08:22:01 -07001115 }
1116 } else {
1117 // see getFunctionType for an explanation of why we're always using pointer parameters
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001118 tmpValueId = this->writeExpression(*arguments[i], out);
ethannicholasb3058bd2016-07-01 08:22:01 -07001119 tmpVar = this->nextId();
1120 }
Greg Daniel64773e62016-11-22 09:44:03 -05001121 this->writeInstruction(SpvOpVariable,
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001122 this->getPointerType(arguments[i]->type(),
ethannicholasb3058bd2016-07-01 08:22:01 -07001123 SpvStorageClassFunction),
Greg Daniel64773e62016-11-22 09:44:03 -05001124 tmpVar,
ethannicholasb3058bd2016-07-01 08:22:01 -07001125 SpvStorageClassFunction,
ethannicholasd598f792016-07-25 10:08:54 -07001126 fVariableBuffer);
ethannicholasb3058bd2016-07-01 08:22:01 -07001127 this->writeInstruction(SpvOpStore, tmpVar, tmpValueId, out);
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001128 argumentIds.push_back(tmpVar);
ethannicholasb3058bd2016-07-01 08:22:01 -07001129 }
1130 SpvId result = this->nextId();
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001131 this->writeOpCode(SpvOpFunctionCall, 4 + (int32_t) arguments.size(), out);
Ethan Nicholas30d30222020-09-11 12:27:26 -04001132 this->writeWord(this->getType(c.type()), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07001133 this->writeWord(result, out);
1134 this->writeWord(entry->second, out);
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001135 for (SpvId id : argumentIds) {
ethannicholasb3058bd2016-07-01 08:22:01 -07001136 this->writeWord(id, out);
1137 }
1138 // now that the call is complete, we may need to update some lvalues with the new values of out
1139 // arguments
1140 for (const auto& tuple : lvalues) {
1141 SpvId load = this->nextId();
Ethan Nicholas10e93b62019-03-20 10:46:14 -04001142 this->writeInstruction(SpvOpLoad, getType(*std::get<1>(tuple)), load, std::get<0>(tuple),
1143 out);
1144 this->writePrecisionModifier(*std::get<1>(tuple), load);
ethannicholasb3058bd2016-07-01 08:22:01 -07001145 std::get<2>(tuple)->store(load, out);
1146 }
1147 return result;
1148}
1149
ethannicholasf789b382016-08-03 12:43:36 -07001150SpvId SPIRVCodeGenerator::writeConstantVector(const Constructor& c) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001151 const Type& type = c.type();
John Stiles9aeed132020-11-24 17:36:06 -05001152 SkASSERT(type.isVector() && c.isCompileTimeConstant());
John Stilescd806892021-01-06 13:33:31 -05001153
John Stiles9cfaa4f2021-01-06 17:52:00 -05001154 // Get each of the constructor components as SPIR-V constants.
John Stilescd806892021-01-06 13:33:31 -05001155 SPIRVVectorConstant key{this->getType(type),
1156 /*fValueId=*/{SpvId(-1), SpvId(-1), SpvId(-1), SpvId(-1)}};
John Stiles9cfaa4f2021-01-06 17:52:00 -05001157
1158 if (c.componentType().isFloat()) {
1159 for (int i = 0; i < type.columns(); i++) {
1160 FloatLiteral literal(c.fOffset, c.getFVecComponent(i), &c.componentType());
1161 key.fValueId[i] = this->writeFloatLiteral(literal);
1162 }
1163 } else if (c.componentType().isInteger()) {
1164 for (int i = 0; i < type.columns(); i++) {
1165 IntLiteral literal(c.fOffset, c.getIVecComponent(i), &c.componentType());
1166 key.fValueId[i] = this->writeIntLiteral(literal);
1167 }
1168 } else if (c.componentType().isBoolean()) {
1169 for (int i = 0; i < type.columns(); i++) {
1170 BoolLiteral literal(c.fOffset, c.getBVecComponent(i), &c.componentType());
1171 key.fValueId[i] = this->writeBoolLiteral(literal);
ethannicholasb3058bd2016-07-01 08:22:01 -07001172 }
1173 } else {
John Stiles9cfaa4f2021-01-06 17:52:00 -05001174 SkDEBUGFAILF("unexpected vector component type: %s",
1175 c.componentType().displayName().c_str());
1176 return SpvId(-1);
ethannicholasb3058bd2016-07-01 08:22:01 -07001177 }
John Stilescd806892021-01-06 13:33:31 -05001178
1179 // Check to see if we've already synthesized this vector constant.
1180 auto [iter, newlyCreated] = fVectorConstants.insert({key, (SpvId)-1});
1181 if (newlyCreated) {
1182 // Emit an OpConstantComposite instruction for this constant.
1183 SpvId result = this->nextId();
John Stiles9cfaa4f2021-01-06 17:52:00 -05001184 this->writeOpCode(SpvOpConstantComposite, 3 + type.columns(), fConstantBuffer);
John Stilescd806892021-01-06 13:33:31 -05001185 this->writeWord(key.fTypeId, fConstantBuffer);
1186 this->writeWord(result, fConstantBuffer);
John Stiles9cfaa4f2021-01-06 17:52:00 -05001187 for (int i = 0; i < type.columns(); i++) {
John Stilescd806892021-01-06 13:33:31 -05001188 this->writeWord(key.fValueId[i], fConstantBuffer);
1189 }
1190 iter->second = result;
1191 }
1192 return iter->second;
ethannicholasb3058bd2016-07-01 08:22:01 -07001193}
1194
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001195SpvId SPIRVCodeGenerator::writeFloatConstructor(const Constructor& c, OutputStream& out) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001196 const Type& constructorType = c.type();
Ethan Nicholasf70f0442020-09-29 12:41:35 -04001197 SkASSERT(c.arguments().size() == 1);
1198 const Type& argType = c.arguments()[0]->type();
Ethan Nicholas30d30222020-09-11 12:27:26 -04001199 SkASSERT(constructorType.isFloat());
John Stilesba4b0e92021-01-05 13:55:39 -05001200 SkASSERT(argType.isNumber() || argType.isBoolean());
ethannicholasb3058bd2016-07-01 08:22:01 -07001201 SpvId result = this->nextId();
Ethan Nicholasf70f0442020-09-29 12:41:35 -04001202 SpvId parameter = this->writeExpression(*c.arguments()[0], out);
John Stilesba4b0e92021-01-05 13:55:39 -05001203 if (argType.isBoolean()) {
1204 // Use OpSelect to convert the boolean argument to a literal 1.0 or 0.0.
1205 FloatLiteral one(fContext, /*offset=*/-1, /*value=*/1);
1206 SpvId oneID = this->writeFloatLiteral(one);
1207 FloatLiteral zero(fContext, /*offset=*/-1, /*value=*/0);
1208 SpvId zeroID = this->writeFloatLiteral(zero);
1209 this->writeInstruction(SpvOpSelect, this->getType(constructorType), result, parameter,
1210 oneID, zeroID, out);
1211 } else if (argType.isSigned()) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001212 this->writeInstruction(SpvOpConvertSToF, this->getType(constructorType), result, parameter,
ethannicholasb3058bd2016-07-01 08:22:01 -07001213 out);
Ethan Nicholasf7b88202017-09-18 14:10:39 -04001214 } else {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001215 SkASSERT(argType.isUnsigned());
1216 this->writeInstruction(SpvOpConvertUToF, this->getType(constructorType), result, parameter,
ethannicholasb3058bd2016-07-01 08:22:01 -07001217 out);
ethannicholasb3058bd2016-07-01 08:22:01 -07001218 }
1219 return result;
1220}
1221
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001222SpvId SPIRVCodeGenerator::writeIntConstructor(const Constructor& c, OutputStream& out) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001223 const Type& constructorType = c.type();
Ethan Nicholasf70f0442020-09-29 12:41:35 -04001224 SkASSERT(c.arguments().size() == 1);
1225 const Type& argType = c.arguments()[0]->type();
Ethan Nicholas30d30222020-09-11 12:27:26 -04001226 SkASSERT(constructorType.isSigned());
John Stilesba4b0e92021-01-05 13:55:39 -05001227 SkASSERT(argType.isNumber() || argType.isBoolean());
ethannicholasb3058bd2016-07-01 08:22:01 -07001228 SpvId result = this->nextId();
Ethan Nicholasf70f0442020-09-29 12:41:35 -04001229 SpvId parameter = this->writeExpression(*c.arguments()[0], out);
John Stilesba4b0e92021-01-05 13:55:39 -05001230 if (argType.isBoolean()) {
1231 // Use OpSelect to convert the boolean argument to a literal 1 or 0.
John Stiles54e7c052021-01-11 14:22:36 -05001232 IntLiteral one(/*offset=*/-1, /*value=*/1, fContext.fTypes.fInt.get());
John Stilesba4b0e92021-01-05 13:55:39 -05001233 SpvId oneID = this->writeIntLiteral(one);
John Stiles54e7c052021-01-11 14:22:36 -05001234 IntLiteral zero(/*offset=*/-1, /*value=*/0, fContext.fTypes.fInt.get());
John Stilesba4b0e92021-01-05 13:55:39 -05001235 SpvId zeroID = this->writeIntLiteral(zero);
1236 this->writeInstruction(SpvOpSelect, this->getType(constructorType), result, parameter,
1237 oneID, zeroID, out);
1238 } else if (argType.isFloat()) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001239 this->writeInstruction(SpvOpConvertFToS, this->getType(constructorType), result, parameter,
ethannicholasb3058bd2016-07-01 08:22:01 -07001240 out);
Ethan Nicholasf7b88202017-09-18 14:10:39 -04001241 }
1242 else {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001243 SkASSERT(argType.isUnsigned());
1244 this->writeInstruction(SpvOpBitcast, this->getType(constructorType), result, parameter,
ethannicholasb3058bd2016-07-01 08:22:01 -07001245 out);
ethannicholasb3058bd2016-07-01 08:22:01 -07001246 }
1247 return result;
1248}
1249
Ethan Nicholas925f52d2017-07-19 10:42:50 -04001250SpvId SPIRVCodeGenerator::writeUIntConstructor(const Constructor& c, OutputStream& out) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001251 const Type& constructorType = c.type();
Ethan Nicholasf70f0442020-09-29 12:41:35 -04001252 SkASSERT(c.arguments().size() == 1);
1253 const Type& argType = c.arguments()[0]->type();
Ethan Nicholas30d30222020-09-11 12:27:26 -04001254 SkASSERT(constructorType.isUnsigned());
John Stilesba4b0e92021-01-05 13:55:39 -05001255 SkASSERT(argType.isNumber() || argType.isBoolean());
Ethan Nicholas925f52d2017-07-19 10:42:50 -04001256 SpvId result = this->nextId();
Ethan Nicholasf70f0442020-09-29 12:41:35 -04001257 SpvId parameter = this->writeExpression(*c.arguments()[0], out);
John Stilesba4b0e92021-01-05 13:55:39 -05001258 if (argType.isBoolean()) {
1259 // Use OpSelect to convert the boolean argument to a literal 1u or 0u.
John Stiles54e7c052021-01-11 14:22:36 -05001260 IntLiteral one(/*offset=*/-1, /*value=*/1, fContext.fTypes.fUInt.get());
John Stilesba4b0e92021-01-05 13:55:39 -05001261 SpvId oneID = this->writeIntLiteral(one);
John Stiles54e7c052021-01-11 14:22:36 -05001262 IntLiteral zero(/*offset=*/-1, /*value=*/0, fContext.fTypes.fUInt.get());
John Stilesba4b0e92021-01-05 13:55:39 -05001263 SpvId zeroID = this->writeIntLiteral(zero);
1264 this->writeInstruction(SpvOpSelect, this->getType(constructorType), result, parameter,
1265 oneID, zeroID, out);
1266 } else if (argType.isFloat()) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001267 this->writeInstruction(SpvOpConvertFToU, this->getType(constructorType), result, parameter,
Ethan Nicholas925f52d2017-07-19 10:42:50 -04001268 out);
Ethan Nicholasf7b88202017-09-18 14:10:39 -04001269 } else {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001270 SkASSERT(argType.isSigned());
1271 this->writeInstruction(SpvOpBitcast, this->getType(constructorType), result, parameter,
Ethan Nicholas925f52d2017-07-19 10:42:50 -04001272 out);
Ethan Nicholas925f52d2017-07-19 10:42:50 -04001273 }
1274 return result;
1275}
1276
Ethan Nicholas84645e32017-02-09 13:57:14 -05001277void SPIRVCodeGenerator::writeUniformScaleMatrix(SpvId id, SpvId diagonal, const Type& type,
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001278 OutputStream& out) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001279 FloatLiteral zero(fContext, -1, 0);
Ethan Nicholas84645e32017-02-09 13:57:14 -05001280 SpvId zeroId = this->writeFloatLiteral(zero);
1281 std::vector<SpvId> columnIds;
1282 for (int column = 0; column < type.columns(); column++) {
1283 this->writeOpCode(SpvOpCompositeConstruct, 3 + type.rows(),
1284 out);
1285 this->writeWord(this->getType(type.componentType().toCompound(fContext, type.rows(), 1)),
1286 out);
1287 SpvId columnId = this->nextId();
1288 this->writeWord(columnId, out);
1289 columnIds.push_back(columnId);
1290 for (int row = 0; row < type.columns(); row++) {
1291 this->writeWord(row == column ? diagonal : zeroId, out);
1292 }
Ethan Nicholascc5d3e02019-04-19 09:50:56 -04001293 this->writePrecisionModifier(type, columnId);
Ethan Nicholas84645e32017-02-09 13:57:14 -05001294 }
1295 this->writeOpCode(SpvOpCompositeConstruct, 3 + type.columns(),
1296 out);
1297 this->writeWord(this->getType(type), out);
1298 this->writeWord(id, out);
John Stilesf621e232020-08-25 13:33:02 -04001299 for (SpvId columnId : columnIds) {
1300 this->writeWord(columnId, out);
Ethan Nicholas84645e32017-02-09 13:57:14 -05001301 }
Ethan Nicholascc5d3e02019-04-19 09:50:56 -04001302 this->writePrecisionModifier(type, id);
Ethan Nicholas84645e32017-02-09 13:57:14 -05001303}
1304
1305void SPIRVCodeGenerator::writeMatrixCopy(SpvId id, SpvId src, const Type& srcType,
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001306 const Type& dstType, OutputStream& out) {
John Stiles9aeed132020-11-24 17:36:06 -05001307 SkASSERT(srcType.isMatrix());
1308 SkASSERT(dstType.isMatrix());
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001309 SkASSERT(srcType.componentType() == dstType.componentType());
Ethan Nicholasdc0e1c32017-07-21 13:23:34 -04001310 SpvId srcColumnType = this->getType(srcType.componentType().toCompound(fContext,
1311 srcType.rows(),
1312 1));
1313 SpvId dstColumnType = this->getType(dstType.componentType().toCompound(fContext,
1314 dstType.rows(),
1315 1));
1316 SpvId zeroId;
John Stiles54e7c052021-01-11 14:22:36 -05001317 if (dstType.componentType() == *fContext.fTypes.fFloat) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001318 FloatLiteral zero(fContext, -1, 0.0);
Ethan Nicholasdc0e1c32017-07-21 13:23:34 -04001319 zeroId = this->writeFloatLiteral(zero);
John Stiles54e7c052021-01-11 14:22:36 -05001320 } else if (dstType.componentType() == *fContext.fTypes.fInt) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001321 IntLiteral zero(fContext, -1, 0);
Ethan Nicholasdc0e1c32017-07-21 13:23:34 -04001322 zeroId = this->writeIntLiteral(zero);
1323 } else {
1324 ABORT("unsupported matrix component type");
1325 }
1326 SpvId zeroColumn = 0;
1327 SpvId columns[4];
1328 for (int i = 0; i < dstType.columns(); i++) {
1329 if (i < srcType.columns()) {
1330 // we're still inside the src matrix, copy the column
1331 SpvId srcColumn = this->nextId();
1332 this->writeInstruction(SpvOpCompositeExtract, srcColumnType, srcColumn, src, i, out);
Ethan Nicholascc5d3e02019-04-19 09:50:56 -04001333 this->writePrecisionModifier(dstType, srcColumn);
Ethan Nicholasdc0e1c32017-07-21 13:23:34 -04001334 SpvId dstColumn;
1335 if (srcType.rows() == dstType.rows()) {
1336 // columns are equal size, don't need to do anything
1337 dstColumn = srcColumn;
1338 }
1339 else if (dstType.rows() > srcType.rows()) {
1340 // dst column is bigger, need to zero-pad it
1341 dstColumn = this->nextId();
1342 int delta = dstType.rows() - srcType.rows();
1343 this->writeOpCode(SpvOpCompositeConstruct, 4 + delta, out);
1344 this->writeWord(dstColumnType, out);
1345 this->writeWord(dstColumn, out);
1346 this->writeWord(srcColumn, out);
John Stilesf621e232020-08-25 13:33:02 -04001347 for (int j = 0; j < delta; ++j) {
Ethan Nicholasdc0e1c32017-07-21 13:23:34 -04001348 this->writeWord(zeroId, out);
1349 }
Ethan Nicholascc5d3e02019-04-19 09:50:56 -04001350 this->writePrecisionModifier(dstType, dstColumn);
Ethan Nicholasdc0e1c32017-07-21 13:23:34 -04001351 }
1352 else {
1353 // dst column is smaller, need to swizzle the src column
1354 dstColumn = this->nextId();
1355 int count = dstType.rows();
1356 this->writeOpCode(SpvOpVectorShuffle, 5 + count, out);
1357 this->writeWord(dstColumnType, out);
1358 this->writeWord(dstColumn, out);
1359 this->writeWord(srcColumn, out);
1360 this->writeWord(srcColumn, out);
John Stilesf621e232020-08-25 13:33:02 -04001361 for (int j = 0; j < count; j++) {
1362 this->writeWord(j, out);
Ethan Nicholasdc0e1c32017-07-21 13:23:34 -04001363 }
Ethan Nicholascc5d3e02019-04-19 09:50:56 -04001364 this->writePrecisionModifier(dstType, dstColumn);
Ethan Nicholasdc0e1c32017-07-21 13:23:34 -04001365 }
1366 columns[i] = dstColumn;
1367 } else {
1368 // we're past the end of the src matrix, need a vector of zeroes
1369 if (!zeroColumn) {
1370 zeroColumn = this->nextId();
1371 this->writeOpCode(SpvOpCompositeConstruct, 3 + dstType.rows(), out);
1372 this->writeWord(dstColumnType, out);
1373 this->writeWord(zeroColumn, out);
John Stilesf621e232020-08-25 13:33:02 -04001374 for (int j = 0; j < dstType.rows(); ++j) {
Ethan Nicholasdc0e1c32017-07-21 13:23:34 -04001375 this->writeWord(zeroId, out);
1376 }
Ethan Nicholascc5d3e02019-04-19 09:50:56 -04001377 this->writePrecisionModifier(dstType, zeroColumn);
Ethan Nicholasdc0e1c32017-07-21 13:23:34 -04001378 }
1379 columns[i] = zeroColumn;
1380 }
1381 }
1382 this->writeOpCode(SpvOpCompositeConstruct, 3 + dstType.columns(), out);
1383 this->writeWord(this->getType(dstType), out);
1384 this->writeWord(id, out);
1385 for (int i = 0; i < dstType.columns(); i++) {
1386 this->writeWord(columns[i], out);
1387 }
Ethan Nicholascc5d3e02019-04-19 09:50:56 -04001388 this->writePrecisionModifier(dstType, id);
Ethan Nicholas84645e32017-02-09 13:57:14 -05001389}
1390
Ethan Nicholascc5d3e02019-04-19 09:50:56 -04001391void SPIRVCodeGenerator::addColumnEntry(SpvId columnType, Precision precision,
1392 std::vector<SpvId>* currentColumn,
Ethan Nicholas5c46b722019-03-22 14:32:37 -04001393 std::vector<SpvId>* columnIds,
1394 int* currentCount, int rows, SpvId entry,
1395 OutputStream& out) {
1396 SkASSERT(*currentCount < rows);
1397 ++(*currentCount);
1398 currentColumn->push_back(entry);
1399 if (*currentCount == rows) {
1400 *currentCount = 0;
1401 this->writeOpCode(SpvOpCompositeConstruct, 3 + currentColumn->size(), out);
1402 this->writeWord(columnType, out);
1403 SpvId columnId = this->nextId();
1404 this->writeWord(columnId, out);
1405 columnIds->push_back(columnId);
1406 for (SpvId id : *currentColumn) {
1407 this->writeWord(id, out);
1408 }
1409 currentColumn->clear();
Ethan Nicholascc5d3e02019-04-19 09:50:56 -04001410 this->writePrecisionModifier(precision, columnId);
Ethan Nicholas5c46b722019-03-22 14:32:37 -04001411 }
1412}
1413
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001414SpvId SPIRVCodeGenerator::writeMatrixConstructor(const Constructor& c, OutputStream& out) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001415 const Type& type = c.type();
John Stiles9aeed132020-11-24 17:36:06 -05001416 SkASSERT(type.isMatrix());
Ethan Nicholasf70f0442020-09-29 12:41:35 -04001417 SkASSERT(c.arguments().size() > 0);
1418 const Type& arg0Type = c.arguments()[0]->type();
ethannicholasb3058bd2016-07-01 08:22:01 -07001419 // go ahead and write the arguments so we don't try to write new instructions in the middle of
1420 // an instruction
1421 std::vector<SpvId> arguments;
Ethan Nicholasf70f0442020-09-29 12:41:35 -04001422 for (size_t i = 0; i < c.arguments().size(); i++) {
1423 arguments.push_back(this->writeExpression(*c.arguments()[i], out));
ethannicholasb3058bd2016-07-01 08:22:01 -07001424 }
1425 SpvId result = this->nextId();
Ethan Nicholas30d30222020-09-11 12:27:26 -04001426 int rows = type.rows();
1427 int columns = type.columns();
John Stiles9aeed132020-11-24 17:36:06 -05001428 if (arguments.size() == 1 && arg0Type.isScalar()) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001429 this->writeUniformScaleMatrix(result, arguments[0], type, out);
John Stiles9aeed132020-11-24 17:36:06 -05001430 } else if (arguments.size() == 1 && arg0Type.isMatrix()) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001431 this->writeMatrixCopy(result, arguments[0], arg0Type, type, out);
Ethan Nicholase6592142020-09-08 10:22:09 -04001432 } else if (arguments.size() == 1 &&
John Stiles9aeed132020-11-24 17:36:06 -05001433 arg0Type.isVector()) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001434 SkASSERT(type.rows() == 2 && type.columns() == 2);
1435 SkASSERT(arg0Type.columns() == 4);
1436 SpvId componentType = this->getType(type.componentType());
Ethan Nicholasdc0e1c32017-07-21 13:23:34 -04001437 SpvId v[4];
1438 for (int i = 0; i < 4; ++i) {
1439 v[i] = this->nextId();
Ethan Nicholas30d30222020-09-11 12:27:26 -04001440 this->writeInstruction(SpvOpCompositeExtract, componentType, v[i], arguments[0], i,
1441 out);
Ethan Nicholasdc0e1c32017-07-21 13:23:34 -04001442 }
Ethan Nicholas30d30222020-09-11 12:27:26 -04001443 SpvId columnType = this->getType(type.componentType().toCompound(fContext, 2, 1));
Ethan Nicholasdc0e1c32017-07-21 13:23:34 -04001444 SpvId column1 = this->nextId();
1445 this->writeInstruction(SpvOpCompositeConstruct, columnType, column1, v[0], v[1], out);
1446 SpvId column2 = this->nextId();
1447 this->writeInstruction(SpvOpCompositeConstruct, columnType, column2, v[2], v[3], out);
Ethan Nicholas30d30222020-09-11 12:27:26 -04001448 this->writeInstruction(SpvOpCompositeConstruct, this->getType(type), result, column1,
Ethan Nicholasdc0e1c32017-07-21 13:23:34 -04001449 column2, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07001450 } else {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001451 SpvId columnType = this->getType(type.componentType().toCompound(fContext, rows, 1));
ethannicholasb3058bd2016-07-01 08:22:01 -07001452 std::vector<SpvId> columnIds;
Ethan Nicholasdc0e1c32017-07-21 13:23:34 -04001453 // ids of vectors and scalars we have written to the current column so far
1454 std::vector<SpvId> currentColumn;
1455 // the total number of scalars represented by currentColumn's entries
ethannicholasb3058bd2016-07-01 08:22:01 -07001456 int currentCount = 0;
Ethan Nicholas30d30222020-09-11 12:27:26 -04001457 Precision precision = type.highPrecision() ? Precision::kHigh : Precision::kLow;
ethannicholasb3058bd2016-07-01 08:22:01 -07001458 for (size_t i = 0; i < arguments.size(); i++) {
Ethan Nicholasf70f0442020-09-29 12:41:35 -04001459 const Type& argType = c.arguments()[i]->type();
John Stiles9aeed132020-11-24 17:36:06 -05001460 if (currentCount == 0 && argType.isVector() &&
Ethan Nicholas30d30222020-09-11 12:27:26 -04001461 argType.columns() == type.rows()) {
Ethan Nicholasdc0e1c32017-07-21 13:23:34 -04001462 // this is a complete column by itself
ethannicholasb3058bd2016-07-01 08:22:01 -07001463 columnIds.push_back(arguments[i]);
ethannicholasb3058bd2016-07-01 08:22:01 -07001464 } else {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001465 if (argType.columns() == 1) {
Ethan Nicholascc5d3e02019-04-19 09:50:56 -04001466 this->addColumnEntry(columnType, precision, &currentColumn, &columnIds,
1467 &currentCount, rows, arguments[i], out);
Ethan Nicholasbe850ad2018-04-27 10:36:31 -04001468 } else {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001469 SpvId componentType = this->getType(argType.componentType());
1470 for (int j = 0; j < argType.columns(); ++j) {
Ethan Nicholasbe850ad2018-04-27 10:36:31 -04001471 SpvId swizzle = this->nextId();
1472 this->writeInstruction(SpvOpCompositeExtract, componentType, swizzle,
1473 arguments[i], j, out);
Ethan Nicholascc5d3e02019-04-19 09:50:56 -04001474 this->addColumnEntry(columnType, precision, &currentColumn, &columnIds,
1475 &currentCount, rows, swizzle, out);
Ethan Nicholasbe850ad2018-04-27 10:36:31 -04001476 }
1477 }
ethannicholasb3058bd2016-07-01 08:22:01 -07001478 }
1479 }
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001480 SkASSERT(columnIds.size() == (size_t) columns);
ethannicholasb3058bd2016-07-01 08:22:01 -07001481 this->writeOpCode(SpvOpCompositeConstruct, 3 + columns, out);
Ethan Nicholas30d30222020-09-11 12:27:26 -04001482 this->writeWord(this->getType(type), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07001483 this->writeWord(result, out);
1484 for (SpvId id : columnIds) {
1485 this->writeWord(id, out);
1486 }
1487 }
Ethan Nicholas30d30222020-09-11 12:27:26 -04001488 this->writePrecisionModifier(type, result);
ethannicholasb3058bd2016-07-01 08:22:01 -07001489 return result;
1490}
1491
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001492SpvId SPIRVCodeGenerator::writeVectorConstructor(const Constructor& c, OutputStream& out) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001493 const Type& type = c.type();
John Stiles9aeed132020-11-24 17:36:06 -05001494 SkASSERT(type.isVector());
Brian Osman0247e9e2020-12-23 15:07:11 -05001495 // Constructing a vector from another vector (even if it's constant) requires our general
1496 // case code, to deal with (possible) per-element type conversion.
1497 bool vectorToVector = c.arguments().size() == 1 && c.arguments()[0]->type().isVector();
1498 if (c.isCompileTimeConstant() && !vectorToVector) {
ethannicholasb3058bd2016-07-01 08:22:01 -07001499 return this->writeConstantVector(c);
1500 }
1501 // go ahead and write the arguments so we don't try to write new instructions in the middle of
1502 // an instruction
1503 std::vector<SpvId> arguments;
Ethan Nicholasf70f0442020-09-29 12:41:35 -04001504 for (size_t i = 0; i < c.arguments().size(); i++) {
1505 const Type& argType = c.arguments()[i]->type();
John Stiles9aeed132020-11-24 17:36:06 -05001506 if (argType.isVector()) {
Ethan Nicholas11e5bff2018-01-29 11:08:38 -05001507 // SPIR-V doesn't support vector(vector-of-different-type) directly, so we need to
1508 // extract the components and convert them in that case manually. On top of that,
John Stilesd5e59b62021-01-13 13:09:26 -05001509 // as of this writing there's a bug in the Intel Vulkan driver where
1510 // OpCompositeConstruct doesn't handle vector arguments at all, so we always extract
1511 // vector components and pass them into OpCompositeConstruct individually.
Ethan Nicholasf70f0442020-09-29 12:41:35 -04001512 SpvId vec = this->writeExpression(*c.arguments()[i], out);
Ethan Nicholas11e5bff2018-01-29 11:08:38 -05001513 SpvOp_ op = SpvOpUndef;
Ethan Nicholas30d30222020-09-11 12:27:26 -04001514 const Type& src = argType.componentType();
1515 const Type& dst = type.componentType();
John Stiles54e7c052021-01-11 14:22:36 -05001516 if (dst == *fContext.fTypes.fFloat || dst == *fContext.fTypes.fHalf) {
1517 if (src == *fContext.fTypes.fFloat || src == *fContext.fTypes.fHalf) {
Ethan Nicholasf70f0442020-09-29 12:41:35 -04001518 if (c.arguments().size() == 1) {
Ethan Nicholas11e5bff2018-01-29 11:08:38 -05001519 return vec;
1520 }
John Stiles54e7c052021-01-11 14:22:36 -05001521 } else if (src == *fContext.fTypes.fInt ||
1522 src == *fContext.fTypes.fShort ||
1523 src == *fContext.fTypes.fByte) {
Ethan Nicholas11e5bff2018-01-29 11:08:38 -05001524 op = SpvOpConvertSToF;
John Stiles54e7c052021-01-11 14:22:36 -05001525 } else if (src == *fContext.fTypes.fUInt ||
1526 src == *fContext.fTypes.fUShort ||
1527 src == *fContext.fTypes.fUByte) {
Ethan Nicholas11e5bff2018-01-29 11:08:38 -05001528 op = SpvOpConvertUToF;
1529 } else {
John Stilesd5e59b62021-01-13 13:09:26 -05001530 fErrors.error(c.arguments()[i]->fOffset, "unsupported cast in SPIR-V: vector " +
1531 src.description() + " to " +
1532 dst.description());
Ethan Nicholas11e5bff2018-01-29 11:08:38 -05001533 }
John Stiles54e7c052021-01-11 14:22:36 -05001534 } else if (dst == *fContext.fTypes.fInt ||
1535 dst == *fContext.fTypes.fShort ||
1536 dst == *fContext.fTypes.fByte) {
1537 if (src == *fContext.fTypes.fFloat || src == *fContext.fTypes.fHalf) {
Ethan Nicholas11e5bff2018-01-29 11:08:38 -05001538 op = SpvOpConvertFToS;
John Stiles54e7c052021-01-11 14:22:36 -05001539 } else if (src == *fContext.fTypes.fInt ||
1540 src == *fContext.fTypes.fShort ||
1541 src == *fContext.fTypes.fByte) {
Ethan Nicholasf70f0442020-09-29 12:41:35 -04001542 if (c.arguments().size() == 1) {
Ethan Nicholas11e5bff2018-01-29 11:08:38 -05001543 return vec;
1544 }
John Stiles54e7c052021-01-11 14:22:36 -05001545 } else if (src == *fContext.fTypes.fUInt ||
1546 src == *fContext.fTypes.fUShort ||
1547 src == *fContext.fTypes.fUByte) {
Ethan Nicholas11e5bff2018-01-29 11:08:38 -05001548 op = SpvOpBitcast;
1549 } else {
John Stilesd5e59b62021-01-13 13:09:26 -05001550 fErrors.error(c.arguments()[i]->fOffset, "unsupported cast in SPIR-V: vector " +
1551 src.description() + " to " +
1552 dst.description());
Ethan Nicholas11e5bff2018-01-29 11:08:38 -05001553 }
John Stiles54e7c052021-01-11 14:22:36 -05001554 } else if (dst == *fContext.fTypes.fUInt ||
1555 dst == *fContext.fTypes.fUShort ||
1556 dst == *fContext.fTypes.fUByte) {
1557 if (src == *fContext.fTypes.fFloat || src == *fContext.fTypes.fHalf) {
Ethan Nicholas11e5bff2018-01-29 11:08:38 -05001558 op = SpvOpConvertFToS;
John Stiles54e7c052021-01-11 14:22:36 -05001559 } else if (src == *fContext.fTypes.fInt ||
1560 src == *fContext.fTypes.fShort ||
1561 src == *fContext.fTypes.fByte) {
Ethan Nicholas11e5bff2018-01-29 11:08:38 -05001562 op = SpvOpBitcast;
John Stiles54e7c052021-01-11 14:22:36 -05001563 } else if (src == *fContext.fTypes.fUInt ||
1564 src == *fContext.fTypes.fUShort ||
1565 src == *fContext.fTypes.fUByte) {
Ethan Nicholasf70f0442020-09-29 12:41:35 -04001566 if (c.arguments().size() == 1) {
Ethan Nicholas11e5bff2018-01-29 11:08:38 -05001567 return vec;
1568 }
1569 } else {
John Stilesd5e59b62021-01-13 13:09:26 -05001570 fErrors.error(c.arguments()[i]->fOffset, "unsupported cast in SPIR-V: vector " +
1571 src.description() + " to " +
1572 dst.description());
Ethan Nicholas11e5bff2018-01-29 11:08:38 -05001573 }
Ethan Nicholas26a8d902018-01-29 09:25:51 -05001574 }
Ethan Nicholas30d30222020-09-11 12:27:26 -04001575 for (int j = 0; j < argType.columns(); j++) {
Ethan Nicholas11e5bff2018-01-29 11:08:38 -05001576 SpvId swizzle = this->nextId();
1577 this->writeInstruction(SpvOpCompositeExtract, this->getType(src), swizzle, vec, j,
1578 out);
1579 if (op != SpvOpUndef) {
1580 SpvId cast = this->nextId();
1581 this->writeInstruction(op, this->getType(dst), cast, swizzle, out);
1582 arguments.push_back(cast);
1583 } else {
1584 arguments.push_back(swizzle);
1585 }
Ethan Nicholas26a8d902018-01-29 09:25:51 -05001586 }
Ethan Nicholas11e5bff2018-01-29 11:08:38 -05001587 } else {
Ethan Nicholasf70f0442020-09-29 12:41:35 -04001588 arguments.push_back(this->writeExpression(*c.arguments()[i], out));
Ethan Nicholas26a8d902018-01-29 09:25:51 -05001589 }
ethannicholasb3058bd2016-07-01 08:22:01 -07001590 }
1591 SpvId result = this->nextId();
John Stiles9aeed132020-11-24 17:36:06 -05001592 if (arguments.size() == 1 && c.arguments()[0]->type().isScalar()) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001593 this->writeOpCode(SpvOpCompositeConstruct, 3 + type.columns(), out);
1594 this->writeWord(this->getType(type), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07001595 this->writeWord(result, out);
Ethan Nicholas30d30222020-09-11 12:27:26 -04001596 for (int i = 0; i < type.columns(); i++) {
ethannicholasb3058bd2016-07-01 08:22:01 -07001597 this->writeWord(arguments[0], out);
1598 }
1599 } else {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001600 SkASSERT(arguments.size() > 1);
Ethan Nicholas26a8d902018-01-29 09:25:51 -05001601 this->writeOpCode(SpvOpCompositeConstruct, 3 + (int32_t) arguments.size(), out);
Ethan Nicholas30d30222020-09-11 12:27:26 -04001602 this->writeWord(this->getType(type), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07001603 this->writeWord(result, out);
1604 for (SpvId id : arguments) {
1605 this->writeWord(id, out);
1606 }
1607 }
1608 return result;
1609}
1610
Ethan Nicholasbd553222017-07-18 15:54:59 -04001611SpvId SPIRVCodeGenerator::writeArrayConstructor(const Constructor& c, OutputStream& out) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001612 const Type& type = c.type();
John Stilesc0c51062020-12-03 17:16:29 -05001613 SkASSERT(type.isArray());
Ethan Nicholasbd553222017-07-18 15:54:59 -04001614 // go ahead and write the arguments so we don't try to write new instructions in the middle of
1615 // an instruction
1616 std::vector<SpvId> arguments;
Ethan Nicholasf70f0442020-09-29 12:41:35 -04001617 for (size_t i = 0; i < c.arguments().size(); i++) {
1618 arguments.push_back(this->writeExpression(*c.arguments()[i], out));
Ethan Nicholasbd553222017-07-18 15:54:59 -04001619 }
1620 SpvId result = this->nextId();
Ethan Nicholasf70f0442020-09-29 12:41:35 -04001621 this->writeOpCode(SpvOpCompositeConstruct, 3 + (int32_t) c.arguments().size(), out);
Ethan Nicholas30d30222020-09-11 12:27:26 -04001622 this->writeWord(this->getType(type), out);
Ethan Nicholasbd553222017-07-18 15:54:59 -04001623 this->writeWord(result, out);
1624 for (SpvId id : arguments) {
1625 this->writeWord(id, out);
1626 }
1627 return result;
1628}
1629
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001630SpvId SPIRVCodeGenerator::writeConstructor(const Constructor& c, OutputStream& out) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001631 const Type& type = c.type();
Ethan Nicholasf70f0442020-09-29 12:41:35 -04001632 if (c.arguments().size() == 1 &&
1633 this->getActualType(type) == this->getActualType(c.arguments()[0]->type())) {
1634 return this->writeExpression(*c.arguments()[0], out);
Ethan Nicholasf7b88202017-09-18 14:10:39 -04001635 }
John Stiles54e7c052021-01-11 14:22:36 -05001636 if (type == *fContext.fTypes.fFloat || type == *fContext.fTypes.fHalf) {
ethannicholasb3058bd2016-07-01 08:22:01 -07001637 return this->writeFloatConstructor(c, out);
John Stiles54e7c052021-01-11 14:22:36 -05001638 } else if (type == *fContext.fTypes.fInt ||
1639 type == *fContext.fTypes.fShort ||
1640 type == *fContext.fTypes.fByte) {
ethannicholasb3058bd2016-07-01 08:22:01 -07001641 return this->writeIntConstructor(c, out);
John Stiles54e7c052021-01-11 14:22:36 -05001642 } else if (type == *fContext.fTypes.fUInt ||
1643 type == *fContext.fTypes.fUShort ||
1644 type == *fContext.fTypes.fUByte) {
Ethan Nicholas925f52d2017-07-19 10:42:50 -04001645 return this->writeUIntConstructor(c, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07001646 }
Ethan Nicholas30d30222020-09-11 12:27:26 -04001647 switch (type.typeKind()) {
Ethan Nicholase6592142020-09-08 10:22:09 -04001648 case Type::TypeKind::kVector:
ethannicholasb3058bd2016-07-01 08:22:01 -07001649 return this->writeVectorConstructor(c, out);
Ethan Nicholase6592142020-09-08 10:22:09 -04001650 case Type::TypeKind::kMatrix:
ethannicholasb3058bd2016-07-01 08:22:01 -07001651 return this->writeMatrixConstructor(c, out);
Ethan Nicholase6592142020-09-08 10:22:09 -04001652 case Type::TypeKind::kArray:
Ethan Nicholasbd553222017-07-18 15:54:59 -04001653 return this->writeArrayConstructor(c, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07001654 default:
Ethan Nicholas2a099da2020-01-02 14:40:54 -05001655#ifdef SK_DEBUG
ethannicholasb3058bd2016-07-01 08:22:01 -07001656 ABORT("unsupported constructor: %s", c.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -05001657#endif
1658 return -1;
ethannicholasb3058bd2016-07-01 08:22:01 -07001659 }
1660}
1661
1662SpvStorageClass_ get_storage_class(const Modifiers& modifiers) {
1663 if (modifiers.fFlags & Modifiers::kIn_Flag) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001664 SkASSERT(!(modifiers.fLayout.fFlags & Layout::kPushConstant_Flag));
ethannicholasb3058bd2016-07-01 08:22:01 -07001665 return SpvStorageClassInput;
1666 } else if (modifiers.fFlags & Modifiers::kOut_Flag) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001667 SkASSERT(!(modifiers.fLayout.fFlags & Layout::kPushConstant_Flag));
ethannicholasb3058bd2016-07-01 08:22:01 -07001668 return SpvStorageClassOutput;
1669 } else if (modifiers.fFlags & Modifiers::kUniform_Flag) {
Ethan Nicholas39204fd2017-11-27 13:12:30 -05001670 if (modifiers.fLayout.fFlags & Layout::kPushConstant_Flag) {
ethannicholas8ac838d2016-11-22 08:39:36 -08001671 return SpvStorageClassPushConstant;
1672 }
ethannicholasb3058bd2016-07-01 08:22:01 -07001673 return SpvStorageClassUniform;
1674 } else {
1675 return SpvStorageClassFunction;
1676 }
1677}
1678
ethannicholasf789b382016-08-03 12:43:36 -07001679SpvStorageClass_ get_storage_class(const Expression& expr) {
Ethan Nicholase6592142020-09-08 10:22:09 -04001680 switch (expr.kind()) {
1681 case Expression::Kind::kVariableReference: {
Ethan Nicholas78686922020-10-08 06:46:27 -04001682 const Variable& var = *expr.as<VariableReference>().variable();
Ethan Nicholas453f67f2020-10-09 10:43:45 -04001683 if (var.storage() != Variable::Storage::kGlobal) {
Ethan Nicholasc6f5e102017-03-31 14:53:17 -04001684 return SpvStorageClassFunction;
1685 }
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001686 SpvStorageClass_ result = get_storage_class(var.modifiers());
Ethan Nicholasdc0e1c32017-07-21 13:23:34 -04001687 if (result == SpvStorageClassFunction) {
1688 result = SpvStorageClassPrivate;
1689 }
1690 return result;
Ethan Nicholasc6f5e102017-03-31 14:53:17 -04001691 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001692 case Expression::Kind::kFieldAccess:
Ethan Nicholas7a95b202020-10-09 11:55:40 -04001693 return get_storage_class(*expr.as<FieldAccess>().base());
Ethan Nicholase6592142020-09-08 10:22:09 -04001694 case Expression::Kind::kIndex:
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04001695 return get_storage_class(*expr.as<IndexExpression>().base());
ethannicholasb3058bd2016-07-01 08:22:01 -07001696 default:
1697 return SpvStorageClassFunction;
1698 }
1699}
1700
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001701std::vector<SpvId> SPIRVCodeGenerator::getAccessChain(const Expression& expr, OutputStream& out) {
ethannicholasb3058bd2016-07-01 08:22:01 -07001702 std::vector<SpvId> chain;
Ethan Nicholase6592142020-09-08 10:22:09 -04001703 switch (expr.kind()) {
1704 case Expression::Kind::kIndex: {
ethannicholasb3058bd2016-07-01 08:22:01 -07001705 IndexExpression& indexExpr = (IndexExpression&) expr;
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04001706 chain = this->getAccessChain(*indexExpr.base(), out);
1707 chain.push_back(this->writeExpression(*indexExpr.index(), out));
ethannicholasb3058bd2016-07-01 08:22:01 -07001708 break;
1709 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001710 case Expression::Kind::kFieldAccess: {
ethannicholasb3058bd2016-07-01 08:22:01 -07001711 FieldAccess& fieldExpr = (FieldAccess&) expr;
Ethan Nicholas7a95b202020-10-09 11:55:40 -04001712 chain = this->getAccessChain(*fieldExpr.base(), out);
1713 IntLiteral index(fContext, -1, fieldExpr.fieldIndex());
ethannicholasb3058bd2016-07-01 08:22:01 -07001714 chain.push_back(this->writeIntLiteral(index));
1715 break;
1716 }
Ethan Nicholasa9a06902019-01-07 14:42:40 -05001717 default: {
1718 SpvId id = this->getLValue(expr, out)->getPointer();
1719 SkASSERT(id != 0);
1720 chain.push_back(id);
1721 }
ethannicholasb3058bd2016-07-01 08:22:01 -07001722 }
1723 return chain;
1724}
1725
1726class PointerLValue : public SPIRVCodeGenerator::LValue {
1727public:
Ethan Nicholas10e93b62019-03-20 10:46:14 -04001728 PointerLValue(SPIRVCodeGenerator& gen, SpvId pointer, SpvId type,
1729 SPIRVCodeGenerator::Precision precision)
ethannicholasb3058bd2016-07-01 08:22:01 -07001730 : fGen(gen)
1731 , fPointer(pointer)
Ethan Nicholas10e93b62019-03-20 10:46:14 -04001732 , fType(type)
1733 , fPrecision(precision) {}
ethannicholasb3058bd2016-07-01 08:22:01 -07001734
John Stiles1cf2c8d2020-08-13 22:58:04 -04001735 SpvId getPointer() override {
ethannicholasb3058bd2016-07-01 08:22:01 -07001736 return fPointer;
1737 }
1738
John Stiles1cf2c8d2020-08-13 22:58:04 -04001739 SpvId load(OutputStream& out) override {
ethannicholasb3058bd2016-07-01 08:22:01 -07001740 SpvId result = fGen.nextId();
1741 fGen.writeInstruction(SpvOpLoad, fType, result, fPointer, out);
Ethan Nicholas10e93b62019-03-20 10:46:14 -04001742 fGen.writePrecisionModifier(fPrecision, result);
ethannicholasb3058bd2016-07-01 08:22:01 -07001743 return result;
1744 }
1745
John Stiles1cf2c8d2020-08-13 22:58:04 -04001746 void store(SpvId value, OutputStream& out) override {
ethannicholasb3058bd2016-07-01 08:22:01 -07001747 fGen.writeInstruction(SpvOpStore, fPointer, value, out);
1748 }
1749
1750private:
1751 SPIRVCodeGenerator& fGen;
1752 const SpvId fPointer;
1753 const SpvId fType;
Ethan Nicholas10e93b62019-03-20 10:46:14 -04001754 const SPIRVCodeGenerator::Precision fPrecision;
ethannicholasb3058bd2016-07-01 08:22:01 -07001755};
1756
1757class SwizzleLValue : public SPIRVCodeGenerator::LValue {
1758public:
John Stiles750109b2020-10-30 13:45:46 -04001759 SwizzleLValue(SPIRVCodeGenerator& gen, SpvId vecPointer, const ComponentArray& components,
Ethan Nicholas10e93b62019-03-20 10:46:14 -04001760 const Type& baseType, const Type& swizzleType,
1761 SPIRVCodeGenerator::Precision precision)
ethannicholasb3058bd2016-07-01 08:22:01 -07001762 : fGen(gen)
1763 , fVecPointer(vecPointer)
1764 , fComponents(components)
1765 , fBaseType(baseType)
Ethan Nicholas10e93b62019-03-20 10:46:14 -04001766 , fSwizzleType(swizzleType)
1767 , fPrecision(precision) {}
ethannicholasb3058bd2016-07-01 08:22:01 -07001768
John Stiles1cf2c8d2020-08-13 22:58:04 -04001769 SpvId getPointer() override {
ethannicholasb3058bd2016-07-01 08:22:01 -07001770 return 0;
1771 }
1772
John Stiles1cf2c8d2020-08-13 22:58:04 -04001773 SpvId load(OutputStream& out) override {
ethannicholasb3058bd2016-07-01 08:22:01 -07001774 SpvId base = fGen.nextId();
1775 fGen.writeInstruction(SpvOpLoad, fGen.getType(fBaseType), base, fVecPointer, out);
Ethan Nicholas10e93b62019-03-20 10:46:14 -04001776 fGen.writePrecisionModifier(fPrecision, base);
ethannicholasb3058bd2016-07-01 08:22:01 -07001777 SpvId result = fGen.nextId();
1778 fGen.writeOpCode(SpvOpVectorShuffle, 5 + (int32_t) fComponents.size(), out);
1779 fGen.writeWord(fGen.getType(fSwizzleType), out);
1780 fGen.writeWord(result, out);
1781 fGen.writeWord(base, out);
1782 fGen.writeWord(base, out);
1783 for (int component : fComponents) {
1784 fGen.writeWord(component, out);
1785 }
Ethan Nicholas10e93b62019-03-20 10:46:14 -04001786 fGen.writePrecisionModifier(fPrecision, result);
ethannicholasb3058bd2016-07-01 08:22:01 -07001787 return result;
1788 }
1789
John Stiles1cf2c8d2020-08-13 22:58:04 -04001790 void store(SpvId value, OutputStream& out) override {
ethannicholasb3058bd2016-07-01 08:22:01 -07001791 // use OpVectorShuffle to mix and match the vector components. We effectively create
1792 // a virtual vector out of the concatenation of the left and right vectors, and then
Greg Daniel64773e62016-11-22 09:44:03 -05001793 // select components from this virtual vector to make the result vector. For
ethannicholasb3058bd2016-07-01 08:22:01 -07001794 // instance, given:
Ethan Nicholas5af9ea32017-07-28 15:19:46 -04001795 // float3L = ...;
1796 // float3R = ...;
ethannicholasb3058bd2016-07-01 08:22:01 -07001797 // L.xz = R.xy;
Greg Daniel64773e62016-11-22 09:44:03 -05001798 // 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 -07001799 // our result vector to look like (R.x, L.y, R.y), so we need to select indices
1800 // (3, 1, 4).
1801 SpvId base = fGen.nextId();
1802 fGen.writeInstruction(SpvOpLoad, fGen.getType(fBaseType), base, fVecPointer, out);
1803 SpvId shuffle = fGen.nextId();
1804 fGen.writeOpCode(SpvOpVectorShuffle, 5 + fBaseType.columns(), out);
1805 fGen.writeWord(fGen.getType(fBaseType), out);
1806 fGen.writeWord(shuffle, out);
1807 fGen.writeWord(base, out);
1808 fGen.writeWord(value, out);
1809 for (int i = 0; i < fBaseType.columns(); i++) {
1810 // current offset into the virtual vector, defaults to pulling the unmodified
1811 // value from the left side
1812 int offset = i;
1813 // check to see if we are writing this component
1814 for (size_t j = 0; j < fComponents.size(); j++) {
1815 if (fComponents[j] == i) {
Greg Daniel64773e62016-11-22 09:44:03 -05001816 // we're writing to this component, so adjust the offset to pull from
ethannicholasb3058bd2016-07-01 08:22:01 -07001817 // the correct component of the right side instead of preserving the
1818 // value from the left
1819 offset = (int) (j + fBaseType.columns());
1820 break;
1821 }
1822 }
1823 fGen.writeWord(offset, out);
1824 }
Ethan Nicholas10e93b62019-03-20 10:46:14 -04001825 fGen.writePrecisionModifier(fPrecision, shuffle);
ethannicholasb3058bd2016-07-01 08:22:01 -07001826 fGen.writeInstruction(SpvOpStore, fVecPointer, shuffle, out);
1827 }
1828
1829private:
1830 SPIRVCodeGenerator& fGen;
1831 const SpvId fVecPointer;
John Stiles750109b2020-10-30 13:45:46 -04001832 const ComponentArray& fComponents;
ethannicholasb3058bd2016-07-01 08:22:01 -07001833 const Type& fBaseType;
1834 const Type& fSwizzleType;
Ethan Nicholas10e93b62019-03-20 10:46:14 -04001835 const SPIRVCodeGenerator::Precision fPrecision;
ethannicholasb3058bd2016-07-01 08:22:01 -07001836};
1837
Greg Daniel64773e62016-11-22 09:44:03 -05001838std::unique_ptr<SPIRVCodeGenerator::LValue> SPIRVCodeGenerator::getLValue(const Expression& expr,
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001839 OutputStream& out) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001840 const Type& type = expr.type();
1841 Precision precision = type.highPrecision() ? Precision::kHigh : Precision::kLow;
Ethan Nicholase6592142020-09-08 10:22:09 -04001842 switch (expr.kind()) {
1843 case Expression::Kind::kVariableReference: {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001844 SpvId typeId;
Ethan Nicholas78686922020-10-08 06:46:27 -04001845 const Variable& var = *expr.as<VariableReference>().variable();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001846 if (var.modifiers().fLayout.fBuiltin == SK_IN_BUILTIN) {
John Stilesad2d4942020-12-11 16:55:58 -05001847 typeId = this->getType(*Type::MakeArrayType("sk_in", var.type().componentType(),
1848 fSkInCount));
Ethan Nicholas5226b772018-05-03 16:20:41 -04001849 } else {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001850 typeId = this->getType(type);
Ethan Nicholas5226b772018-05-03 16:20:41 -04001851 }
ethannicholasd598f792016-07-25 10:08:54 -07001852 auto entry = fVariableMap.find(&var);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001853 SkASSERT(entry != fVariableMap.end());
John Stiles5570c512020-11-19 17:58:07 -05001854 return std::make_unique<PointerLValue>(*this, entry->second, typeId, precision);
ethannicholasb3058bd2016-07-01 08:22:01 -07001855 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001856 case Expression::Kind::kIndex: // fall through
1857 case Expression::Kind::kFieldAccess: {
ethannicholasb3058bd2016-07-01 08:22:01 -07001858 std::vector<SpvId> chain = this->getAccessChain(expr, out);
1859 SpvId member = this->nextId();
1860 this->writeOpCode(SpvOpAccessChain, (SpvId) (3 + chain.size()), out);
Ethan Nicholas30d30222020-09-11 12:27:26 -04001861 this->writeWord(this->getPointerType(type, get_storage_class(expr)), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07001862 this->writeWord(member, out);
1863 for (SpvId idx : chain) {
1864 this->writeWord(idx, out);
1865 }
John Stiles5570c512020-11-19 17:58:07 -05001866 return std::make_unique<PointerLValue>(*this, member, this->getType(type), precision);
ethannicholasb3058bd2016-07-01 08:22:01 -07001867 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001868 case Expression::Kind::kSwizzle: {
ethannicholasb3058bd2016-07-01 08:22:01 -07001869 Swizzle& swizzle = (Swizzle&) expr;
Ethan Nicholas6b4d5812020-10-12 16:11:51 -04001870 size_t count = swizzle.components().size();
1871 SpvId base = this->getLValue(*swizzle.base(), out)->getPointer();
John Stiles5570c512020-11-19 17:58:07 -05001872 if (!base) {
1873 fErrors.error(swizzle.fOffset, "unable to retrieve lvalue from swizzle");
1874 }
ethannicholasb3058bd2016-07-01 08:22:01 -07001875 if (count == 1) {
Ethan Nicholas6b4d5812020-10-12 16:11:51 -04001876 IntLiteral index(fContext, -1, swizzle.components()[0]);
ethannicholasb3058bd2016-07-01 08:22:01 -07001877 SpvId member = this->nextId();
1878 this->writeInstruction(SpvOpAccessChain,
Ethan Nicholas30d30222020-09-11 12:27:26 -04001879 this->getPointerType(type,
Ethan Nicholas6b4d5812020-10-12 16:11:51 -04001880 get_storage_class(*swizzle.base())),
Greg Daniel64773e62016-11-22 09:44:03 -05001881 member,
1882 base,
1883 this->writeIntLiteral(index),
ethannicholasb3058bd2016-07-01 08:22:01 -07001884 out);
John Stiles5570c512020-11-19 17:58:07 -05001885 return std::make_unique<PointerLValue>(*this, member, this->getType(type),
1886 precision);
ethannicholasb3058bd2016-07-01 08:22:01 -07001887 } else {
John Stiles5570c512020-11-19 17:58:07 -05001888 return std::make_unique<SwizzleLValue>(*this, base, swizzle.components(),
1889 swizzle.base()->type(), type, precision);
ethannicholasb3058bd2016-07-01 08:22:01 -07001890 }
1891 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001892 case Expression::Kind::kTernary: {
Ethan Nicholasa583b812018-01-18 13:32:11 -05001893 TernaryExpression& t = (TernaryExpression&) expr;
Ethan Nicholasdd218162020-10-08 05:48:01 -04001894 SpvId test = this->writeExpression(*t.test(), out);
Ethan Nicholasa583b812018-01-18 13:32:11 -05001895 SpvId end = this->nextId();
1896 SpvId ifTrueLabel = this->nextId();
1897 SpvId ifFalseLabel = this->nextId();
1898 this->writeInstruction(SpvOpSelectionMerge, end, SpvSelectionControlMaskNone, out);
1899 this->writeInstruction(SpvOpBranchConditional, test, ifTrueLabel, ifFalseLabel, out);
1900 this->writeLabel(ifTrueLabel, out);
Ethan Nicholasdd218162020-10-08 05:48:01 -04001901 SpvId ifTrue = this->getLValue(*t.ifTrue(), out)->getPointer();
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001902 SkASSERT(ifTrue);
Ethan Nicholasa583b812018-01-18 13:32:11 -05001903 this->writeInstruction(SpvOpBranch, end, out);
1904 ifTrueLabel = fCurrentBlock;
Ethan Nicholasdd218162020-10-08 05:48:01 -04001905 SpvId ifFalse = this->getLValue(*t.ifFalse(), out)->getPointer();
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001906 SkASSERT(ifFalse);
Ethan Nicholasa583b812018-01-18 13:32:11 -05001907 ifFalseLabel = fCurrentBlock;
1908 this->writeInstruction(SpvOpBranch, end, out);
1909 SpvId result = this->nextId();
John Stiles54e7c052021-01-11 14:22:36 -05001910 this->writeInstruction(SpvOpPhi, this->getType(*fContext.fTypes.fBool), result, ifTrue,
Ethan Nicholasa583b812018-01-18 13:32:11 -05001911 ifTrueLabel, ifFalse, ifFalseLabel, out);
John Stiles5570c512020-11-19 17:58:07 -05001912 return std::make_unique<PointerLValue>(*this, result, this->getType(type), precision);
Ethan Nicholasa583b812018-01-18 13:32:11 -05001913 }
Ethan Nicholas30d30222020-09-11 12:27:26 -04001914 default: {
ethannicholasb3058bd2016-07-01 08:22:01 -07001915 // expr isn't actually an lvalue, create a dummy variable for it. This case happens due
Greg Daniel64773e62016-11-22 09:44:03 -05001916 // to the need to store values in temporary variables during function calls (see
ethannicholasb3058bd2016-07-01 08:22:01 -07001917 // comments in getFunctionType); erroneous uses of rvalues as lvalues should have been
1918 // caught by IRGenerator
1919 SpvId result = this->nextId();
Ethan Nicholas30d30222020-09-11 12:27:26 -04001920 SpvId pointerType = this->getPointerType(type, SpvStorageClassFunction);
1921 this->writeInstruction(SpvOpVariable, pointerType, result, SpvStorageClassFunction,
ethannicholasd598f792016-07-25 10:08:54 -07001922 fVariableBuffer);
ethannicholasb3058bd2016-07-01 08:22:01 -07001923 this->writeInstruction(SpvOpStore, result, this->writeExpression(expr, out), out);
John Stiles5570c512020-11-19 17:58:07 -05001924 return std::make_unique<PointerLValue>(*this, result, this->getType(type), precision);
Ethan Nicholas30d30222020-09-11 12:27:26 -04001925 }
ethannicholasb3058bd2016-07-01 08:22:01 -07001926 }
1927}
1928
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001929SpvId SPIRVCodeGenerator::writeVariableReference(const VariableReference& ref, OutputStream& out) {
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001930 SpvId result = this->nextId();
Ethan Nicholas78686922020-10-08 06:46:27 -04001931 auto entry = fVariableMap.find(ref.variable());
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001932 SkASSERT(entry != fVariableMap.end());
ethannicholasb3058bd2016-07-01 08:22:01 -07001933 SpvId var = entry->second;
Ethan Nicholas78686922020-10-08 06:46:27 -04001934 this->writeInstruction(SpvOpLoad, this->getType(ref.variable()->type()), result, var, out);
1935 this->writePrecisionModifier(ref.variable()->type(), result);
1936 if (ref.variable()->modifiers().fLayout.fBuiltin == SK_FRAGCOORD_BUILTIN &&
Brian Osmane38bedd2020-12-21 11:51:54 -05001937 fProgram.fSettings.fFlipY) {
Greg Daniela85e4bf2020-06-17 16:32:45 -04001938 // The x component never changes, so just grab it
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001939 SpvId xId = this->nextId();
John Stiles54e7c052021-01-11 14:22:36 -05001940 this->writeInstruction(SpvOpCompositeExtract, this->getType(*fContext.fTypes.fFloat), xId,
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001941 result, 0, out);
Greg Daniela85e4bf2020-06-17 16:32:45 -04001942
1943 // Calculate the y component which may need to be flipped
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001944 SpvId rawYId = this->nextId();
John Stiles54e7c052021-01-11 14:22:36 -05001945 this->writeInstruction(SpvOpCompositeExtract, this->getType(*fContext.fTypes.fFloat),
1946 rawYId, result, 1, out);
Greg Daniela85e4bf2020-06-17 16:32:45 -04001947 SpvId flippedYId = 0;
1948 if (fProgram.fSettings.fFlipY) {
1949 // need to remap to a top-left coordinate system
1950 if (fRTHeightStructId == (SpvId)-1) {
1951 // height variable hasn't been written yet
Greg Daniela85e4bf2020-06-17 16:32:45 -04001952 SkASSERT(fRTHeightFieldIndex == (SpvId)-1);
1953 std::vector<Type::Field> fields;
John Stiles5570c512020-11-19 17:58:07 -05001954 if (fProgram.fSettings.fRTHeightOffset < 0) {
1955 fErrors.error(ref.fOffset, "RTHeightOffset is negative");
1956 }
Greg Daniela85e4bf2020-06-17 16:32:45 -04001957 fields.emplace_back(
1958 Modifiers(Layout(0, -1, fProgram.fSettings.fRTHeightOffset, -1, -1, -1, -1,
1959 -1, Layout::Format::kUnspecified,
1960 Layout::kUnspecified_Primitive, 1, -1, "", "",
1961 Layout::kNo_Key, Layout::CType::kDefault),
1962 0),
John Stiles54e7c052021-01-11 14:22:36 -05001963 SKSL_RTHEIGHT_NAME, fContext.fTypes.fFloat.get());
Greg Daniela85e4bf2020-06-17 16:32:45 -04001964 StringFragment name("sksl_synthetic_uniforms");
John Stilesad2d4942020-12-11 16:55:58 -05001965 std::unique_ptr<Type> intfStruct = Type::MakeStructType(/*offset=*/-1, name,
1966 fields);
Greg Daniela85e4bf2020-06-17 16:32:45 -04001967 int binding = fProgram.fSettings.fRTHeightBinding;
John Stiles5570c512020-11-19 17:58:07 -05001968 if (binding == -1) {
1969 fErrors.error(ref.fOffset, "layout(binding=...) is required in SPIR-V");
1970 }
Greg Daniela85e4bf2020-06-17 16:32:45 -04001971 int set = fProgram.fSettings.fRTHeightSet;
John Stiles5570c512020-11-19 17:58:07 -05001972 if (set == -1) {
1973 fErrors.error(ref.fOffset, "layout(set=...) is required in SPIR-V");
1974 }
Greg Daniela85e4bf2020-06-17 16:32:45 -04001975 Layout layout(0, -1, -1, binding, -1, set, -1, -1, Layout::Format::kUnspecified,
1976 Layout::kUnspecified_Primitive, -1, -1, "", "", Layout::kNo_Key,
1977 Layout::CType::kDefault);
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001978 Modifiers modifiers(layout, Modifiers::kUniform_Flag);
John Stiles3ae071e2020-08-05 15:29:29 -04001979 const Variable* intfVar = fSynthetics.takeOwnershipOfSymbol(
1980 std::make_unique<Variable>(/*offset=*/-1,
John Stiles586df952020-11-12 18:27:13 -05001981 fProgram.fModifiers->addToPool(modifiers),
John Stiles3ae071e2020-08-05 15:29:29 -04001982 name,
John Stilesad2d4942020-12-11 16:55:58 -05001983 intfStruct.get(),
Brian Osman3887a012020-09-30 13:22:27 -04001984 /*builtin=*/false,
Ethan Nicholas453f67f2020-10-09 10:43:45 -04001985 Variable::Storage::kGlobal));
John Stilesd39aec02020-12-03 10:42:26 -05001986 InterfaceBlock intf(/*offset=*/-1, intfVar, name,
1987 /*instanceName=*/"", /*arraySize=*/0,
John Stiles7c3515b2020-10-16 18:38:39 -04001988 std::make_shared<SymbolTable>(&fErrors, /*builtin=*/false));
Stephen White88574972020-06-23 19:09:29 -04001989
1990 fRTHeightStructId = this->writeInterfaceBlock(intf, false);
Greg Daniela85e4bf2020-06-17 16:32:45 -04001991 fRTHeightFieldIndex = 0;
Jim Van Verthf3ec9832020-10-21 16:09:57 -04001992 fRTHeightStorageClass = SpvStorageClassUniform;
Greg Daniela85e4bf2020-06-17 16:32:45 -04001993 }
1994 SkASSERT(fRTHeightFieldIndex != (SpvId)-1);
1995
1996 IntLiteral fieldIndex(fContext, -1, fRTHeightFieldIndex);
1997 SpvId fieldIndexId = this->writeIntLiteral(fieldIndex);
1998 SpvId heightPtr = this->nextId();
1999 this->writeOpCode(SpvOpAccessChain, 5, out);
John Stiles54e7c052021-01-11 14:22:36 -05002000 this->writeWord(this->getPointerType(*fContext.fTypes.fFloat, fRTHeightStorageClass),
Greg Daniela85e4bf2020-06-17 16:32:45 -04002001 out);
2002 this->writeWord(heightPtr, out);
2003 this->writeWord(fRTHeightStructId, out);
2004 this->writeWord(fieldIndexId, out);
2005 SpvId heightRead = this->nextId();
John Stiles54e7c052021-01-11 14:22:36 -05002006 this->writeInstruction(SpvOpLoad, this->getType(*fContext.fTypes.fFloat), heightRead,
Greg Daniela85e4bf2020-06-17 16:32:45 -04002007 heightPtr, out);
2008
2009 flippedYId = this->nextId();
John Stiles54e7c052021-01-11 14:22:36 -05002010 this->writeInstruction(SpvOpFSub, this->getType(*fContext.fTypes.fFloat), flippedYId,
Greg Daniela85e4bf2020-06-17 16:32:45 -04002011 heightRead, rawYId, out);
2012 }
2013
2014 // The z component will always be zero so we just get an id to the 0 literal
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002015 FloatLiteral zero(fContext, -1, 0.0);
Ethan Nicholas941e7e22016-12-12 15:33:30 -05002016 SpvId zeroId = writeFloatLiteral(zero);
Greg Daniela85e4bf2020-06-17 16:32:45 -04002017
Brian Osmane38bedd2020-12-21 11:51:54 -05002018 // Calculate the w component
Greg Daniela85e4bf2020-06-17 16:32:45 -04002019 SpvId rawWId = this->nextId();
John Stiles54e7c052021-01-11 14:22:36 -05002020 this->writeInstruction(SpvOpCompositeExtract, this->getType(*fContext.fTypes.fFloat),
2021 rawWId, result, 3, out);
Greg Daniela85e4bf2020-06-17 16:32:45 -04002022
2023 // Fill in the new fragcoord with the components from above
2024 SpvId adjusted = this->nextId();
Ethan Nicholas941e7e22016-12-12 15:33:30 -05002025 this->writeOpCode(SpvOpCompositeConstruct, 7, out);
John Stiles54e7c052021-01-11 14:22:36 -05002026 this->writeWord(this->getType(*fContext.fTypes.fFloat4), out);
Greg Daniela85e4bf2020-06-17 16:32:45 -04002027 this->writeWord(adjusted, out);
Ethan Nicholas941e7e22016-12-12 15:33:30 -05002028 this->writeWord(xId, out);
Greg Daniela85e4bf2020-06-17 16:32:45 -04002029 if (fProgram.fSettings.fFlipY) {
2030 this->writeWord(flippedYId, out);
2031 } else {
2032 this->writeWord(rawYId, out);
2033 }
Ethan Nicholas941e7e22016-12-12 15:33:30 -05002034 this->writeWord(zeroId, out);
Brian Osmane38bedd2020-12-21 11:51:54 -05002035 this->writeWord(rawWId, out);
Greg Daniela85e4bf2020-06-17 16:32:45 -04002036
2037 return adjusted;
Ethan Nicholas941e7e22016-12-12 15:33:30 -05002038 }
Ethan Nicholas78686922020-10-08 06:46:27 -04002039 if (ref.variable()->modifiers().fLayout.fBuiltin == SK_CLOCKWISE_BUILTIN &&
Chris Daltonb91c4662018-08-01 10:46:22 -06002040 !fProgram.fSettings.fFlipY) {
2041 // FrontFacing in Vulkan is defined in terms of a top-down render target. In skia, we use
2042 // the default convention of "counter-clockwise face is front".
2043 SpvId inverse = this->nextId();
John Stiles54e7c052021-01-11 14:22:36 -05002044 this->writeInstruction(SpvOpLogicalNot, this->getType(*fContext.fTypes.fBool), inverse,
Chris Daltonb91c4662018-08-01 10:46:22 -06002045 result, out);
2046 return inverse;
2047 }
ethannicholasb3058bd2016-07-01 08:22:01 -07002048 return result;
2049}
2050
Ethan Nicholas0df1b042017-03-31 13:56:23 -04002051SpvId SPIRVCodeGenerator::writeIndexExpression(const IndexExpression& expr, OutputStream& out) {
John Stiles9aeed132020-11-24 17:36:06 -05002052 if (expr.base()->type().isVector()) {
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04002053 SpvId base = this->writeExpression(*expr.base(), out);
2054 SpvId index = this->writeExpression(*expr.index(), out);
Ethan Nicholasa9a06902019-01-07 14:42:40 -05002055 SpvId result = this->nextId();
Ethan Nicholas30d30222020-09-11 12:27:26 -04002056 this->writeInstruction(SpvOpVectorExtractDynamic, this->getType(expr.type()), result, base,
Ethan Nicholasa9a06902019-01-07 14:42:40 -05002057 index, out);
2058 return result;
2059 }
ethannicholasb3058bd2016-07-01 08:22:01 -07002060 return getLValue(expr, out)->load(out);
2061}
2062
Ethan Nicholas0df1b042017-03-31 13:56:23 -04002063SpvId SPIRVCodeGenerator::writeFieldAccess(const FieldAccess& f, OutputStream& out) {
ethannicholasb3058bd2016-07-01 08:22:01 -07002064 return getLValue(f, out)->load(out);
2065}
2066
Ethan Nicholas0df1b042017-03-31 13:56:23 -04002067SpvId SPIRVCodeGenerator::writeSwizzle(const Swizzle& swizzle, OutputStream& out) {
Ethan Nicholas6b4d5812020-10-12 16:11:51 -04002068 SpvId base = this->writeExpression(*swizzle.base(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002069 SpvId result = this->nextId();
Ethan Nicholas6b4d5812020-10-12 16:11:51 -04002070 size_t count = swizzle.components().size();
ethannicholasb3058bd2016-07-01 08:22:01 -07002071 if (count == 1) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04002072 this->writeInstruction(SpvOpCompositeExtract, this->getType(swizzle.type()), result, base,
Ethan Nicholas6b4d5812020-10-12 16:11:51 -04002073 swizzle.components()[0], out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002074 } else {
2075 this->writeOpCode(SpvOpVectorShuffle, 5 + (int32_t) count, out);
Ethan Nicholas30d30222020-09-11 12:27:26 -04002076 this->writeWord(this->getType(swizzle.type()), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002077 this->writeWord(result, out);
2078 this->writeWord(base, out);
Brian Osman25647672020-09-15 15:16:56 -04002079 this->writeWord(base, out);
Ethan Nicholas6b4d5812020-10-12 16:11:51 -04002080 for (int component : swizzle.components()) {
Brian Osman25647672020-09-15 15:16:56 -04002081 this->writeWord(component, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002082 }
2083 }
2084 return result;
2085}
2086
Greg Daniel64773e62016-11-22 09:44:03 -05002087SpvId SPIRVCodeGenerator::writeBinaryOperation(const Type& resultType,
2088 const Type& operandType, SpvId lhs,
2089 SpvId rhs, SpvOp_ ifFloat, SpvOp_ ifInt,
Ethan Nicholas0df1b042017-03-31 13:56:23 -04002090 SpvOp_ ifUInt, SpvOp_ ifBool, OutputStream& out) {
ethannicholasb3058bd2016-07-01 08:22:01 -07002091 SpvId result = this->nextId();
ethannicholasd598f792016-07-25 10:08:54 -07002092 if (is_float(fContext, operandType)) {
ethannicholasb3058bd2016-07-01 08:22:01 -07002093 this->writeInstruction(ifFloat, this->getType(resultType), result, lhs, rhs, out);
ethannicholasd598f792016-07-25 10:08:54 -07002094 } else if (is_signed(fContext, operandType)) {
ethannicholasb3058bd2016-07-01 08:22:01 -07002095 this->writeInstruction(ifInt, this->getType(resultType), result, lhs, rhs, out);
ethannicholasd598f792016-07-25 10:08:54 -07002096 } else if (is_unsigned(fContext, operandType)) {
ethannicholasb3058bd2016-07-01 08:22:01 -07002097 this->writeInstruction(ifUInt, this->getType(resultType), result, lhs, rhs, out);
John Stiles123501f2020-12-09 10:08:13 -05002098 } else if (is_bool(fContext, operandType)) {
ethannicholasb3058bd2016-07-01 08:22:01 -07002099 this->writeInstruction(ifBool, this->getType(resultType), result, lhs, rhs, out);
Ethan Nicholas858fecc2019-03-07 13:19:18 -05002100 return result; // skip RelaxedPrecision check
ethannicholasb3058bd2016-07-01 08:22:01 -07002101 } else {
John Stiles123501f2020-12-09 10:08:13 -05002102 fErrors.error(operandType.fOffset,
2103 "unsupported operand for binary expression: " + operandType.description());
2104 return result;
ethannicholasb3058bd2016-07-01 08:22:01 -07002105 }
Ethan Nicholase77739e2019-03-14 14:04:43 -04002106 if (getActualType(resultType) == operandType && !resultType.highPrecision()) {
Ethan Nicholas858fecc2019-03-07 13:19:18 -05002107 this->writeInstruction(SpvOpDecorate, result, SpvDecorationRelaxedPrecision,
2108 fDecorationBuffer);
2109 }
ethannicholasb3058bd2016-07-01 08:22:01 -07002110 return result;
2111}
2112
Ethan Nicholas48e24052018-03-14 13:51:39 -04002113SpvId SPIRVCodeGenerator::foldToBool(SpvId id, const Type& operandType, SpvOp op,
2114 OutputStream& out) {
John Stiles9aeed132020-11-24 17:36:06 -05002115 if (operandType.isVector()) {
Ethan Nicholasef653b82017-02-21 13:50:00 -05002116 SpvId result = this->nextId();
John Stiles54e7c052021-01-11 14:22:36 -05002117 this->writeInstruction(op, this->getType(*fContext.fTypes.fBool), result, id, out);
Ethan Nicholasef653b82017-02-21 13:50:00 -05002118 return result;
2119 }
2120 return id;
2121}
2122
Ethan Nicholas68990be2017-07-13 09:36:52 -04002123SpvId SPIRVCodeGenerator::writeMatrixComparison(const Type& operandType, SpvId lhs, SpvId rhs,
2124 SpvOp_ floatOperator, SpvOp_ intOperator,
Ethan Nicholas0df21132018-07-10 09:37:51 -04002125 SpvOp_ vectorMergeOperator, SpvOp_ mergeOperator,
Ethan Nicholas68990be2017-07-13 09:36:52 -04002126 OutputStream& out) {
2127 SpvOp_ compareOp = is_float(fContext, operandType) ? floatOperator : intOperator;
John Stiles9aeed132020-11-24 17:36:06 -05002128 SkASSERT(operandType.isMatrix());
Ethan Nicholas0df21132018-07-10 09:37:51 -04002129 SpvId columnType = this->getType(operandType.componentType().toCompound(fContext,
2130 operandType.rows(),
2131 1));
John Stiles54e7c052021-01-11 14:22:36 -05002132 SpvId bvecType = this->getType(fContext.fTypes.fBool->toCompound(fContext,
Ethan Nicholas0df21132018-07-10 09:37:51 -04002133 operandType.rows(),
Ethan Nicholas68990be2017-07-13 09:36:52 -04002134 1));
John Stiles54e7c052021-01-11 14:22:36 -05002135 SpvId boolType = this->getType(*fContext.fTypes.fBool);
Ethan Nicholas68990be2017-07-13 09:36:52 -04002136 SpvId result = 0;
Ethan Nicholas0df21132018-07-10 09:37:51 -04002137 for (int i = 0; i < operandType.columns(); i++) {
2138 SpvId columnL = this->nextId();
2139 this->writeInstruction(SpvOpCompositeExtract, columnType, columnL, lhs, i, out);
2140 SpvId columnR = this->nextId();
2141 this->writeInstruction(SpvOpCompositeExtract, columnType, columnR, rhs, i, out);
Ethan Nicholas68990be2017-07-13 09:36:52 -04002142 SpvId compare = this->nextId();
Ethan Nicholas0df21132018-07-10 09:37:51 -04002143 this->writeInstruction(compareOp, bvecType, compare, columnL, columnR, out);
2144 SpvId merge = this->nextId();
2145 this->writeInstruction(vectorMergeOperator, boolType, merge, compare, out);
Ethan Nicholas68990be2017-07-13 09:36:52 -04002146 if (result != 0) {
2147 SpvId next = this->nextId();
Ethan Nicholas0df21132018-07-10 09:37:51 -04002148 this->writeInstruction(mergeOperator, boolType, next, result, merge, out);
Ethan Nicholas68990be2017-07-13 09:36:52 -04002149 result = next;
2150 }
2151 else {
Ethan Nicholas0df21132018-07-10 09:37:51 -04002152 result = merge;
Ethan Nicholas68990be2017-07-13 09:36:52 -04002153 }
2154 }
2155 return result;
2156}
2157
Ethan Nicholas0df21132018-07-10 09:37:51 -04002158SpvId SPIRVCodeGenerator::writeComponentwiseMatrixBinary(const Type& operandType, SpvId lhs,
2159 SpvId rhs, SpvOp_ floatOperator,
2160 SpvOp_ intOperator,
2161 OutputStream& out) {
2162 SpvOp_ op = is_float(fContext, operandType) ? floatOperator : intOperator;
John Stiles9aeed132020-11-24 17:36:06 -05002163 SkASSERT(operandType.isMatrix());
Ethan Nicholas0df21132018-07-10 09:37:51 -04002164 SpvId columnType = this->getType(operandType.componentType().toCompound(fContext,
2165 operandType.rows(),
2166 1));
2167 SpvId columns[4];
2168 for (int i = 0; i < operandType.columns(); i++) {
2169 SpvId columnL = this->nextId();
2170 this->writeInstruction(SpvOpCompositeExtract, columnType, columnL, lhs, i, out);
2171 SpvId columnR = this->nextId();
2172 this->writeInstruction(SpvOpCompositeExtract, columnType, columnR, rhs, i, out);
2173 columns[i] = this->nextId();
2174 this->writeInstruction(op, columnType, columns[i], columnL, columnR, out);
2175 }
2176 SpvId result = this->nextId();
2177 this->writeOpCode(SpvOpCompositeConstruct, 3 + operandType.columns(), out);
2178 this->writeWord(this->getType(operandType), out);
2179 this->writeWord(result, out);
2180 for (int i = 0; i < operandType.columns(); i++) {
2181 this->writeWord(columns[i], out);
2182 }
2183 return result;
2184}
2185
Ethan Nicholas49465b42019-04-17 12:22:21 -04002186std::unique_ptr<Expression> create_literal_1(const Context& context, const Type& type) {
2187 if (type.isInteger()) {
2188 return std::unique_ptr<Expression>(new IntLiteral(-1, 1, &type));
ethannicholasb3058bd2016-07-01 08:22:01 -07002189 }
Ethan Nicholas49465b42019-04-17 12:22:21 -04002190 else if (type.isFloat()) {
2191 return std::unique_ptr<Expression>(new FloatLiteral(-1, 1.0, &type));
ethannicholasb3058bd2016-07-01 08:22:01 -07002192 } else {
Ethan Nicholase2c49992020-10-05 11:49:11 -04002193 ABORT("math is unsupported on type '%s'", String(type.name()).c_str());
ethannicholasb3058bd2016-07-01 08:22:01 -07002194 }
Ethan Nicholas49465b42019-04-17 12:22:21 -04002195}
2196
2197SpvId SPIRVCodeGenerator::writeBinaryExpression(const Type& leftType, SpvId lhs, Token::Kind op,
2198 const Type& rightType, SpvId rhs,
2199 const Type& resultType, OutputStream& out) {
John Stilesd0614f22020-12-09 11:11:41 -05002200 // The comma operator ignores the type of the left-hand side entirely.
2201 if (op == Token::Kind::TK_COMMA) {
2202 return rhs;
2203 }
Ethan Nicholas48e24052018-03-14 13:51:39 -04002204 // overall type we are operating on: float2, int, uint4...
ethannicholasb3058bd2016-07-01 08:22:01 -07002205 const Type* operandType;
Ethan Nicholas48e24052018-03-14 13:51:39 -04002206 // IR allows mismatched types in expressions (e.g. float2 * float), but they need special
2207 // handling in SPIR-V
Ethan Nicholas49465b42019-04-17 12:22:21 -04002208 if (this->getActualType(leftType) != this->getActualType(rightType)) {
John Stiles9aeed132020-11-24 17:36:06 -05002209 if (leftType.isVector() && rightType.isNumber()) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002210 if (op == Token::Kind::TK_SLASH) {
Ethan Nicholas49465b42019-04-17 12:22:21 -04002211 SpvId one = this->writeExpression(*create_literal_1(fContext, rightType), out);
2212 SpvId inverse = this->nextId();
2213 this->writeInstruction(SpvOpFDiv, this->getType(rightType), inverse, one, rhs, out);
2214 rhs = inverse;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002215 op = Token::Kind::TK_STAR;
Ethan Nicholas49465b42019-04-17 12:22:21 -04002216 }
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002217 if (op == Token::Kind::TK_STAR) {
Ethan Nicholas49465b42019-04-17 12:22:21 -04002218 SpvId result = this->nextId();
2219 this->writeInstruction(SpvOpVectorTimesScalar, this->getType(resultType),
2220 result, lhs, rhs, out);
2221 return result;
2222 }
ethannicholasb3058bd2016-07-01 08:22:01 -07002223 // promote number to vector
2224 SpvId vec = this->nextId();
Ethan Nicholas49465b42019-04-17 12:22:21 -04002225 const Type& vecType = leftType;
Ethan Nicholas48e24052018-03-14 13:51:39 -04002226 this->writeOpCode(SpvOpCompositeConstruct, 3 + vecType.columns(), out);
2227 this->writeWord(this->getType(vecType), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002228 this->writeWord(vec, out);
Ethan Nicholas48e24052018-03-14 13:51:39 -04002229 for (int i = 0; i < vecType.columns(); i++) {
ethannicholasb3058bd2016-07-01 08:22:01 -07002230 this->writeWord(rhs, out);
2231 }
2232 rhs = vec;
Ethan Nicholas49465b42019-04-17 12:22:21 -04002233 operandType = &leftType;
John Stiles9aeed132020-11-24 17:36:06 -05002234 } else if (rightType.isVector() && leftType.isNumber()) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002235 if (op == Token::Kind::TK_STAR) {
Ethan Nicholas49465b42019-04-17 12:22:21 -04002236 SpvId result = this->nextId();
2237 this->writeInstruction(SpvOpVectorTimesScalar, this->getType(resultType),
2238 result, rhs, lhs, out);
2239 return result;
2240 }
ethannicholasb3058bd2016-07-01 08:22:01 -07002241 // promote number to vector
2242 SpvId vec = this->nextId();
Ethan Nicholas49465b42019-04-17 12:22:21 -04002243 const Type& vecType = rightType;
Ethan Nicholas48e24052018-03-14 13:51:39 -04002244 this->writeOpCode(SpvOpCompositeConstruct, 3 + vecType.columns(), out);
2245 this->writeWord(this->getType(vecType), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002246 this->writeWord(vec, out);
Ethan Nicholas48e24052018-03-14 13:51:39 -04002247 for (int i = 0; i < vecType.columns(); i++) {
ethannicholasb3058bd2016-07-01 08:22:01 -07002248 this->writeWord(lhs, out);
2249 }
2250 lhs = vec;
Ethan Nicholas49465b42019-04-17 12:22:21 -04002251 operandType = &rightType;
John Stiles9aeed132020-11-24 17:36:06 -05002252 } else if (leftType.isMatrix()) {
Ethan Nicholas49465b42019-04-17 12:22:21 -04002253 SpvOp_ spvop;
John Stiles9aeed132020-11-24 17:36:06 -05002254 if (rightType.isMatrix()) {
Ethan Nicholas49465b42019-04-17 12:22:21 -04002255 spvop = SpvOpMatrixTimesMatrix;
John Stiles9aeed132020-11-24 17:36:06 -05002256 } else if (rightType.isVector()) {
Ethan Nicholas49465b42019-04-17 12:22:21 -04002257 spvop = SpvOpMatrixTimesVector;
ethannicholasb3058bd2016-07-01 08:22:01 -07002258 } else {
John Stiles9aeed132020-11-24 17:36:06 -05002259 SkASSERT(rightType.isScalar());
Ethan Nicholas49465b42019-04-17 12:22:21 -04002260 spvop = SpvOpMatrixTimesScalar;
ethannicholasb3058bd2016-07-01 08:22:01 -07002261 }
2262 SpvId result = this->nextId();
Ethan Nicholas49465b42019-04-17 12:22:21 -04002263 this->writeInstruction(spvop, this->getType(resultType), result, lhs, rhs, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002264 return result;
John Stiles9aeed132020-11-24 17:36:06 -05002265 } else if (rightType.isMatrix()) {
ethannicholasb3058bd2016-07-01 08:22:01 -07002266 SpvId result = this->nextId();
John Stiles9aeed132020-11-24 17:36:06 -05002267 if (leftType.isVector()) {
Ethan Nicholas49465b42019-04-17 12:22:21 -04002268 this->writeInstruction(SpvOpVectorTimesMatrix, this->getType(resultType), result,
ethannicholasb3058bd2016-07-01 08:22:01 -07002269 lhs, rhs, out);
2270 } else {
John Stiles9aeed132020-11-24 17:36:06 -05002271 SkASSERT(leftType.isScalar());
Ethan Nicholas49465b42019-04-17 12:22:21 -04002272 this->writeInstruction(SpvOpMatrixTimesScalar, this->getType(resultType), result,
2273 rhs, lhs, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002274 }
2275 return result;
2276 } else {
John Stilesd8ca6b62020-11-23 14:28:36 -05002277 fErrors.error(leftType.fOffset, "unsupported mixed-type expression");
Ethan Nicholas49465b42019-04-17 12:22:21 -04002278 return -1;
ethannicholasb3058bd2016-07-01 08:22:01 -07002279 }
2280 } else {
John Stiles2d4f9592020-10-30 10:29:12 -04002281 operandType = &this->getActualType(leftType);
Ethan Nicholas49465b42019-04-17 12:22:21 -04002282 SkASSERT(*operandType == this->getActualType(rightType));
ethannicholasb3058bd2016-07-01 08:22:01 -07002283 }
Ethan Nicholas49465b42019-04-17 12:22:21 -04002284 switch (op) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002285 case Token::Kind::TK_EQEQ: {
John Stiles9aeed132020-11-24 17:36:06 -05002286 if (operandType->isMatrix()) {
Ethan Nicholas68990be2017-07-13 09:36:52 -04002287 return this->writeMatrixComparison(*operandType, lhs, rhs, SpvOpFOrdEqual,
Ethan Nicholas0df21132018-07-10 09:37:51 -04002288 SpvOpIEqual, SpvOpAll, SpvOpLogicalAnd, out);
Ethan Nicholas68990be2017-07-13 09:36:52 -04002289 }
John Stiles4a7dc462020-11-25 11:08:08 -05002290 SkASSERT(resultType.isBoolean());
Ethan Nicholas48e24052018-03-14 13:51:39 -04002291 const Type* tmpType;
John Stiles9aeed132020-11-24 17:36:06 -05002292 if (operandType->isVector()) {
John Stiles54e7c052021-01-11 14:22:36 -05002293 tmpType = &fContext.fTypes.fBool->toCompound(fContext,
2294 operandType->columns(),
2295 operandType->rows());
Ethan Nicholas48e24052018-03-14 13:51:39 -04002296 } else {
2297 tmpType = &resultType;
2298 }
2299 return this->foldToBool(this->writeBinaryOperation(*tmpType, *operandType, lhs, rhs,
Ethan Nicholasef653b82017-02-21 13:50:00 -05002300 SpvOpFOrdEqual, SpvOpIEqual,
2301 SpvOpIEqual, SpvOpLogicalEqual, out),
Ethan Nicholas48e24052018-03-14 13:51:39 -04002302 *operandType, SpvOpAll, out);
Ethan Nicholasef653b82017-02-21 13:50:00 -05002303 }
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002304 case Token::Kind::TK_NEQ:
John Stiles9aeed132020-11-24 17:36:06 -05002305 if (operandType->isMatrix()) {
Ethan Nicholas68990be2017-07-13 09:36:52 -04002306 return this->writeMatrixComparison(*operandType, lhs, rhs, SpvOpFOrdNotEqual,
Ethan Nicholas0df21132018-07-10 09:37:51 -04002307 SpvOpINotEqual, SpvOpAny, SpvOpLogicalOr, out);
Ethan Nicholas68990be2017-07-13 09:36:52 -04002308 }
John Stiles4a7dc462020-11-25 11:08:08 -05002309 [[fallthrough]];
2310 case Token::Kind::TK_LOGICALXOR:
2311 SkASSERT(resultType.isBoolean());
Ethan Nicholas48e24052018-03-14 13:51:39 -04002312 const Type* tmpType;
John Stiles9aeed132020-11-24 17:36:06 -05002313 if (operandType->isVector()) {
John Stiles54e7c052021-01-11 14:22:36 -05002314 tmpType = &fContext.fTypes.fBool->toCompound(fContext,
2315 operandType->columns(),
2316 operandType->rows());
Ethan Nicholas48e24052018-03-14 13:51:39 -04002317 } else {
2318 tmpType = &resultType;
2319 }
2320 return this->foldToBool(this->writeBinaryOperation(*tmpType, *operandType, lhs, rhs,
Ethan Nicholasef653b82017-02-21 13:50:00 -05002321 SpvOpFOrdNotEqual, SpvOpINotEqual,
2322 SpvOpINotEqual, SpvOpLogicalNotEqual,
2323 out),
Ethan Nicholas48e24052018-03-14 13:51:39 -04002324 *operandType, SpvOpAny, out);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002325 case Token::Kind::TK_GT:
John Stiles4a7dc462020-11-25 11:08:08 -05002326 SkASSERT(resultType.isBoolean());
Greg Daniel64773e62016-11-22 09:44:03 -05002327 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs,
2328 SpvOpFOrdGreaterThan, SpvOpSGreaterThan,
ethannicholasb3058bd2016-07-01 08:22:01 -07002329 SpvOpUGreaterThan, SpvOpUndef, out);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002330 case Token::Kind::TK_LT:
John Stiles4a7dc462020-11-25 11:08:08 -05002331 SkASSERT(resultType.isBoolean());
Greg Daniel64773e62016-11-22 09:44:03 -05002332 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs, SpvOpFOrdLessThan,
ethannicholasb3058bd2016-07-01 08:22:01 -07002333 SpvOpSLessThan, SpvOpULessThan, SpvOpUndef, out);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002334 case Token::Kind::TK_GTEQ:
John Stiles4a7dc462020-11-25 11:08:08 -05002335 SkASSERT(resultType.isBoolean());
Greg Daniel64773e62016-11-22 09:44:03 -05002336 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs,
2337 SpvOpFOrdGreaterThanEqual, SpvOpSGreaterThanEqual,
ethannicholasb3058bd2016-07-01 08:22:01 -07002338 SpvOpUGreaterThanEqual, SpvOpUndef, out);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002339 case Token::Kind::TK_LTEQ:
John Stiles4a7dc462020-11-25 11:08:08 -05002340 SkASSERT(resultType.isBoolean());
Greg Daniel64773e62016-11-22 09:44:03 -05002341 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs,
2342 SpvOpFOrdLessThanEqual, SpvOpSLessThanEqual,
ethannicholasb3058bd2016-07-01 08:22:01 -07002343 SpvOpULessThanEqual, SpvOpUndef, out);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002344 case Token::Kind::TK_PLUS:
John Stiles9aeed132020-11-24 17:36:06 -05002345 if (leftType.isMatrix() && rightType.isMatrix()) {
Ethan Nicholas49465b42019-04-17 12:22:21 -04002346 SkASSERT(leftType == rightType);
2347 return this->writeComponentwiseMatrixBinary(leftType, lhs, rhs,
Ethan Nicholas0df21132018-07-10 09:37:51 -04002348 SpvOpFAdd, SpvOpIAdd, out);
2349 }
Greg Daniel64773e62016-11-22 09:44:03 -05002350 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs, SpvOpFAdd,
ethannicholasb3058bd2016-07-01 08:22:01 -07002351 SpvOpIAdd, SpvOpIAdd, SpvOpUndef, out);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002352 case Token::Kind::TK_MINUS:
John Stiles9aeed132020-11-24 17:36:06 -05002353 if (leftType.isMatrix() && rightType.isMatrix()) {
Ethan Nicholas49465b42019-04-17 12:22:21 -04002354 SkASSERT(leftType == rightType);
2355 return this->writeComponentwiseMatrixBinary(leftType, lhs, rhs,
Ethan Nicholas0df21132018-07-10 09:37:51 -04002356 SpvOpFSub, SpvOpISub, out);
2357 }
Greg Daniel64773e62016-11-22 09:44:03 -05002358 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs, SpvOpFSub,
ethannicholasb3058bd2016-07-01 08:22:01 -07002359 SpvOpISub, SpvOpISub, SpvOpUndef, out);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002360 case Token::Kind::TK_STAR:
John Stiles9aeed132020-11-24 17:36:06 -05002361 if (leftType.isMatrix() && rightType.isMatrix()) {
ethannicholasb3058bd2016-07-01 08:22:01 -07002362 // matrix multiply
2363 SpvId result = this->nextId();
2364 this->writeInstruction(SpvOpMatrixTimesMatrix, this->getType(resultType), result,
2365 lhs, rhs, out);
2366 return result;
2367 }
Greg Daniel64773e62016-11-22 09:44:03 -05002368 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs, SpvOpFMul,
ethannicholasb3058bd2016-07-01 08:22:01 -07002369 SpvOpIMul, SpvOpIMul, SpvOpUndef, out);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002370 case Token::Kind::TK_SLASH:
Greg Daniel64773e62016-11-22 09:44:03 -05002371 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs, SpvOpFDiv,
ethannicholasb3058bd2016-07-01 08:22:01 -07002372 SpvOpSDiv, SpvOpUDiv, SpvOpUndef, out);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002373 case Token::Kind::TK_PERCENT:
Ethan Nicholasb3d0f7c2017-05-17 13:13:21 -04002374 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs, SpvOpFMod,
2375 SpvOpSMod, SpvOpUMod, SpvOpUndef, out);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002376 case Token::Kind::TK_SHL:
Ethan Nicholasfd444be2017-07-05 10:05:54 -04002377 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs, SpvOpUndef,
2378 SpvOpShiftLeftLogical, SpvOpShiftLeftLogical,
2379 SpvOpUndef, out);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002380 case Token::Kind::TK_SHR:
Ethan Nicholasfd444be2017-07-05 10:05:54 -04002381 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs, SpvOpUndef,
2382 SpvOpShiftRightArithmetic, SpvOpShiftRightLogical,
2383 SpvOpUndef, out);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002384 case Token::Kind::TK_BITWISEAND:
Ethan Nicholasfd444be2017-07-05 10:05:54 -04002385 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs, SpvOpUndef,
2386 SpvOpBitwiseAnd, SpvOpBitwiseAnd, SpvOpUndef, out);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002387 case Token::Kind::TK_BITWISEOR:
Ethan Nicholasfd444be2017-07-05 10:05:54 -04002388 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs, SpvOpUndef,
2389 SpvOpBitwiseOr, SpvOpBitwiseOr, SpvOpUndef, out);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002390 case Token::Kind::TK_BITWISEXOR:
Ethan Nicholasfd444be2017-07-05 10:05:54 -04002391 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs, SpvOpUndef,
2392 SpvOpBitwiseXor, SpvOpBitwiseXor, SpvOpUndef, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002393 default:
John Stiles5570c512020-11-19 17:58:07 -05002394 fErrors.error(0, "unsupported token");
Ethan Nicholas49465b42019-04-17 12:22:21 -04002395 return -1;
ethannicholasb3058bd2016-07-01 08:22:01 -07002396 }
2397}
2398
Ethan Nicholas49465b42019-04-17 12:22:21 -04002399SpvId SPIRVCodeGenerator::writeBinaryExpression(const BinaryExpression& b, OutputStream& out) {
John Stiles2d4f9592020-10-30 10:29:12 -04002400 const Expression& left = *b.left();
2401 const Expression& right = *b.right();
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04002402 Token::Kind op = b.getOperator();
Ethan Nicholas49465b42019-04-17 12:22:21 -04002403 // handle cases where we don't necessarily evaluate both LHS and RHS
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04002404 switch (op) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002405 case Token::Kind::TK_EQ: {
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04002406 SpvId rhs = this->writeExpression(right, out);
2407 this->getLValue(left, out)->store(rhs, out);
Ethan Nicholas49465b42019-04-17 12:22:21 -04002408 return rhs;
2409 }
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002410 case Token::Kind::TK_LOGICALAND:
Ethan Nicholas49465b42019-04-17 12:22:21 -04002411 return this->writeLogicalAnd(b, out);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002412 case Token::Kind::TK_LOGICALOR:
Ethan Nicholas49465b42019-04-17 12:22:21 -04002413 return this->writeLogicalOr(b, out);
2414 default:
2415 break;
2416 }
2417
2418 std::unique_ptr<LValue> lvalue;
2419 SpvId lhs;
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04002420 if (Compiler::IsAssignment(op)) {
2421 lvalue = this->getLValue(left, out);
Ethan Nicholas49465b42019-04-17 12:22:21 -04002422 lhs = lvalue->load(out);
2423 } else {
2424 lvalue = nullptr;
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04002425 lhs = this->writeExpression(left, out);
Ethan Nicholas49465b42019-04-17 12:22:21 -04002426 }
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04002427 SpvId rhs = this->writeExpression(right, out);
2428 SpvId result = this->writeBinaryExpression(left.type(), lhs, Compiler::RemoveAssignment(op),
2429 right.type(), rhs, b.type(), out);
Ethan Nicholas49465b42019-04-17 12:22:21 -04002430 if (lvalue) {
2431 lvalue->store(result, out);
2432 }
2433 return result;
2434}
2435
Ethan Nicholas0df1b042017-03-31 13:56:23 -04002436SpvId SPIRVCodeGenerator::writeLogicalAnd(const BinaryExpression& a, OutputStream& out) {
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04002437 SkASSERT(a.getOperator() == Token::Kind::TK_LOGICALAND);
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002438 BoolLiteral falseLiteral(fContext, -1, false);
ethannicholasb3058bd2016-07-01 08:22:01 -07002439 SpvId falseConstant = this->writeBoolLiteral(falseLiteral);
John Stiles2d4f9592020-10-30 10:29:12 -04002440 SpvId lhs = this->writeExpression(*a.left(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002441 SpvId rhsLabel = this->nextId();
2442 SpvId end = this->nextId();
2443 SpvId lhsBlock = fCurrentBlock;
2444 this->writeInstruction(SpvOpSelectionMerge, end, SpvSelectionControlMaskNone, out);
2445 this->writeInstruction(SpvOpBranchConditional, lhs, rhsLabel, end, out);
2446 this->writeLabel(rhsLabel, out);
John Stiles2d4f9592020-10-30 10:29:12 -04002447 SpvId rhs = this->writeExpression(*a.right(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002448 SpvId rhsBlock = fCurrentBlock;
2449 this->writeInstruction(SpvOpBranch, end, out);
2450 this->writeLabel(end, out);
2451 SpvId result = this->nextId();
John Stiles54e7c052021-01-11 14:22:36 -05002452 this->writeInstruction(SpvOpPhi, this->getType(*fContext.fTypes.fBool), result, falseConstant,
ethannicholasd598f792016-07-25 10:08:54 -07002453 lhsBlock, rhs, rhsBlock, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002454 return result;
2455}
2456
Ethan Nicholas0df1b042017-03-31 13:56:23 -04002457SpvId SPIRVCodeGenerator::writeLogicalOr(const BinaryExpression& o, OutputStream& out) {
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04002458 SkASSERT(o.getOperator() == Token::Kind::TK_LOGICALOR);
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002459 BoolLiteral trueLiteral(fContext, -1, true);
ethannicholasb3058bd2016-07-01 08:22:01 -07002460 SpvId trueConstant = this->writeBoolLiteral(trueLiteral);
John Stiles2d4f9592020-10-30 10:29:12 -04002461 SpvId lhs = this->writeExpression(*o.left(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002462 SpvId rhsLabel = this->nextId();
2463 SpvId end = this->nextId();
2464 SpvId lhsBlock = fCurrentBlock;
2465 this->writeInstruction(SpvOpSelectionMerge, end, SpvSelectionControlMaskNone, out);
2466 this->writeInstruction(SpvOpBranchConditional, lhs, end, rhsLabel, out);
2467 this->writeLabel(rhsLabel, out);
John Stiles2d4f9592020-10-30 10:29:12 -04002468 SpvId rhs = this->writeExpression(*o.right(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002469 SpvId rhsBlock = fCurrentBlock;
2470 this->writeInstruction(SpvOpBranch, end, out);
2471 this->writeLabel(end, out);
2472 SpvId result = this->nextId();
John Stiles54e7c052021-01-11 14:22:36 -05002473 this->writeInstruction(SpvOpPhi, this->getType(*fContext.fTypes.fBool), result, trueConstant,
ethannicholasd598f792016-07-25 10:08:54 -07002474 lhsBlock, rhs, rhsBlock, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002475 return result;
2476}
2477
Ethan Nicholas0df1b042017-03-31 13:56:23 -04002478SpvId SPIRVCodeGenerator::writeTernaryExpression(const TernaryExpression& t, OutputStream& out) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04002479 const Type& type = t.type();
Ethan Nicholasdd218162020-10-08 05:48:01 -04002480 SpvId test = this->writeExpression(*t.test(), out);
2481 if (t.ifTrue()->type().columns() == 1 &&
2482 t.ifTrue()->isCompileTimeConstant() &&
2483 t.ifFalse()->isCompileTimeConstant()) {
ethannicholasb3058bd2016-07-01 08:22:01 -07002484 // both true and false are constants, can just use OpSelect
2485 SpvId result = this->nextId();
Ethan Nicholasdd218162020-10-08 05:48:01 -04002486 SpvId trueId = this->writeExpression(*t.ifTrue(), out);
2487 SpvId falseId = this->writeExpression(*t.ifFalse(), out);
Ethan Nicholas30d30222020-09-11 12:27:26 -04002488 this->writeInstruction(SpvOpSelect, this->getType(type), result, test, trueId, falseId,
ethannicholasb3058bd2016-07-01 08:22:01 -07002489 out);
2490 return result;
2491 }
Greg Daniel64773e62016-11-22 09:44:03 -05002492 // was originally using OpPhi to choose the result, but for some reason that is crashing on
ethannicholasb3058bd2016-07-01 08:22:01 -07002493 // Adreno. Switched to storing the result in a temp variable as glslang does.
2494 SpvId var = this->nextId();
Ethan Nicholas30d30222020-09-11 12:27:26 -04002495 this->writeInstruction(SpvOpVariable, this->getPointerType(type, SpvStorageClassFunction),
ethannicholasd598f792016-07-25 10:08:54 -07002496 var, SpvStorageClassFunction, fVariableBuffer);
ethannicholasb3058bd2016-07-01 08:22:01 -07002497 SpvId trueLabel = this->nextId();
2498 SpvId falseLabel = this->nextId();
2499 SpvId end = this->nextId();
2500 this->writeInstruction(SpvOpSelectionMerge, end, SpvSelectionControlMaskNone, out);
2501 this->writeInstruction(SpvOpBranchConditional, test, trueLabel, falseLabel, out);
2502 this->writeLabel(trueLabel, out);
Ethan Nicholasdd218162020-10-08 05:48:01 -04002503 this->writeInstruction(SpvOpStore, var, this->writeExpression(*t.ifTrue(), out), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002504 this->writeInstruction(SpvOpBranch, end, out);
2505 this->writeLabel(falseLabel, out);
Ethan Nicholasdd218162020-10-08 05:48:01 -04002506 this->writeInstruction(SpvOpStore, var, this->writeExpression(*t.ifFalse(), out), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002507 this->writeInstruction(SpvOpBranch, end, out);
2508 this->writeLabel(end, out);
2509 SpvId result = this->nextId();
Ethan Nicholas30d30222020-09-11 12:27:26 -04002510 this->writeInstruction(SpvOpLoad, this->getType(type), result, var, out);
2511 this->writePrecisionModifier(type, result);
ethannicholasb3058bd2016-07-01 08:22:01 -07002512 return result;
2513}
2514
Ethan Nicholas0df1b042017-03-31 13:56:23 -04002515SpvId SPIRVCodeGenerator::writePrefixExpression(const PrefixExpression& p, OutputStream& out) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04002516 const Type& type = p.type();
Ethan Nicholas444ccc62020-10-09 10:16:22 -04002517 if (p.getOperator() == Token::Kind::TK_MINUS) {
ethannicholasb3058bd2016-07-01 08:22:01 -07002518 SpvId result = this->nextId();
Ethan Nicholas30d30222020-09-11 12:27:26 -04002519 SpvId typeId = this->getType(type);
Ethan Nicholas444ccc62020-10-09 10:16:22 -04002520 SpvId expr = this->writeExpression(*p.operand(), out);
Ethan Nicholas30d30222020-09-11 12:27:26 -04002521 if (is_float(fContext, type)) {
ethannicholasb3058bd2016-07-01 08:22:01 -07002522 this->writeInstruction(SpvOpFNegate, typeId, result, expr, out);
Ethan Nicholas30d30222020-09-11 12:27:26 -04002523 } else if (is_signed(fContext, type)) {
ethannicholasb3058bd2016-07-01 08:22:01 -07002524 this->writeInstruction(SpvOpSNegate, typeId, result, expr, out);
2525 } else {
Ethan Nicholas2a099da2020-01-02 14:40:54 -05002526#ifdef SK_DEBUG
ethannicholasb3058bd2016-07-01 08:22:01 -07002527 ABORT("unsupported prefix expression %s", p.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -05002528#endif
Brian Salomon23356442018-11-30 15:33:19 -05002529 }
Ethan Nicholas30d30222020-09-11 12:27:26 -04002530 this->writePrecisionModifier(type, result);
ethannicholasb3058bd2016-07-01 08:22:01 -07002531 return result;
2532 }
Ethan Nicholas444ccc62020-10-09 10:16:22 -04002533 switch (p.getOperator()) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002534 case Token::Kind::TK_PLUS:
Ethan Nicholas444ccc62020-10-09 10:16:22 -04002535 return this->writeExpression(*p.operand(), out);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002536 case Token::Kind::TK_PLUSPLUS: {
Ethan Nicholas444ccc62020-10-09 10:16:22 -04002537 std::unique_ptr<LValue> lv = this->getLValue(*p.operand(), out);
Ethan Nicholas30d30222020-09-11 12:27:26 -04002538 SpvId one = this->writeExpression(*create_literal_1(fContext, type), out);
2539 SpvId result = this->writeBinaryOperation(type, type, lv->load(out), one,
Greg Daniel64773e62016-11-22 09:44:03 -05002540 SpvOpFAdd, SpvOpIAdd, SpvOpIAdd, SpvOpUndef,
ethannicholasb3058bd2016-07-01 08:22:01 -07002541 out);
2542 lv->store(result, out);
2543 return result;
2544 }
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002545 case Token::Kind::TK_MINUSMINUS: {
Ethan Nicholas444ccc62020-10-09 10:16:22 -04002546 std::unique_ptr<LValue> lv = this->getLValue(*p.operand(), out);
Ethan Nicholas30d30222020-09-11 12:27:26 -04002547 SpvId one = this->writeExpression(*create_literal_1(fContext, type), out);
2548 SpvId result = this->writeBinaryOperation(type, type, lv->load(out), one, SpvOpFSub,
2549 SpvOpISub, SpvOpISub, SpvOpUndef, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002550 lv->store(result, out);
2551 return result;
2552 }
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002553 case Token::Kind::TK_LOGICALNOT: {
John Stiles4a7dc462020-11-25 11:08:08 -05002554 SkASSERT(p.operand()->type().isBoolean());
ethannicholasb3058bd2016-07-01 08:22:01 -07002555 SpvId result = this->nextId();
Ethan Nicholas444ccc62020-10-09 10:16:22 -04002556 this->writeInstruction(SpvOpLogicalNot, this->getType(type), result,
2557 this->writeExpression(*p.operand(), out), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002558 return result;
2559 }
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002560 case Token::Kind::TK_BITWISENOT: {
ethannicholas5961bc92016-10-12 06:39:56 -07002561 SpvId result = this->nextId();
Ethan Nicholas444ccc62020-10-09 10:16:22 -04002562 this->writeInstruction(SpvOpNot, this->getType(type), result,
2563 this->writeExpression(*p.operand(), out), out);
ethannicholas5961bc92016-10-12 06:39:56 -07002564 return result;
2565 }
ethannicholasb3058bd2016-07-01 08:22:01 -07002566 default:
Ethan Nicholas2a099da2020-01-02 14:40:54 -05002567#ifdef SK_DEBUG
ethannicholasb3058bd2016-07-01 08:22:01 -07002568 ABORT("unsupported prefix expression: %s", p.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -05002569#endif
2570 return -1;
ethannicholasb3058bd2016-07-01 08:22:01 -07002571 }
2572}
2573
Ethan Nicholas0df1b042017-03-31 13:56:23 -04002574SpvId SPIRVCodeGenerator::writePostfixExpression(const PostfixExpression& p, OutputStream& out) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04002575 const Type& type = p.type();
Ethan Nicholas444ccc62020-10-09 10:16:22 -04002576 std::unique_ptr<LValue> lv = this->getLValue(*p.operand(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002577 SpvId result = lv->load(out);
Ethan Nicholas30d30222020-09-11 12:27:26 -04002578 SpvId one = this->writeExpression(*create_literal_1(fContext, type), out);
Ethan Nicholas444ccc62020-10-09 10:16:22 -04002579 switch (p.getOperator()) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002580 case Token::Kind::TK_PLUSPLUS: {
Ethan Nicholas30d30222020-09-11 12:27:26 -04002581 SpvId temp = this->writeBinaryOperation(type, type, result, one, SpvOpFAdd,
ethannicholasb3058bd2016-07-01 08:22:01 -07002582 SpvOpIAdd, SpvOpIAdd, SpvOpUndef, out);
2583 lv->store(temp, out);
2584 return result;
2585 }
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002586 case Token::Kind::TK_MINUSMINUS: {
Ethan Nicholas30d30222020-09-11 12:27:26 -04002587 SpvId temp = this->writeBinaryOperation(type, type, result, one, SpvOpFSub,
ethannicholasb3058bd2016-07-01 08:22:01 -07002588 SpvOpISub, SpvOpISub, SpvOpUndef, out);
2589 lv->store(temp, out);
2590 return result;
2591 }
2592 default:
Ethan Nicholas2a099da2020-01-02 14:40:54 -05002593#ifdef SK_DEBUG
ethannicholasb3058bd2016-07-01 08:22:01 -07002594 ABORT("unsupported postfix expression %s", p.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -05002595#endif
2596 return -1;
ethannicholasb3058bd2016-07-01 08:22:01 -07002597 }
2598}
2599
ethannicholasf789b382016-08-03 12:43:36 -07002600SpvId SPIRVCodeGenerator::writeBoolLiteral(const BoolLiteral& b) {
Ethan Nicholas59d660c2020-09-28 09:18:15 -04002601 if (b.value()) {
ethannicholasb3058bd2016-07-01 08:22:01 -07002602 if (fBoolTrue == 0) {
2603 fBoolTrue = this->nextId();
Ethan Nicholas30d30222020-09-11 12:27:26 -04002604 this->writeInstruction(SpvOpConstantTrue, this->getType(b.type()), fBoolTrue,
ethannicholasb3058bd2016-07-01 08:22:01 -07002605 fConstantBuffer);
2606 }
2607 return fBoolTrue;
2608 } else {
2609 if (fBoolFalse == 0) {
2610 fBoolFalse = this->nextId();
Ethan Nicholas30d30222020-09-11 12:27:26 -04002611 this->writeInstruction(SpvOpConstantFalse, this->getType(b.type()), fBoolFalse,
ethannicholasb3058bd2016-07-01 08:22:01 -07002612 fConstantBuffer);
2613 }
2614 return fBoolFalse;
2615 }
2616}
2617
ethannicholasf789b382016-08-03 12:43:36 -07002618SpvId SPIRVCodeGenerator::writeIntLiteral(const IntLiteral& i) {
John Stilesbdc3d3c2021-01-06 18:41:40 -05002619 SPIRVNumberConstant key{i.value(), i.type().numberKind()};
John Stilesacb091f2021-01-06 11:57:58 -05002620 auto [iter, newlyCreated] = fNumberConstants.insert({key, (SpvId)-1});
2621 if (newlyCreated) {
Ethan Nicholascc5d3e02019-04-19 09:50:56 -04002622 SpvId result = this->nextId();
John Stilesacb091f2021-01-06 11:57:58 -05002623 this->writeInstruction(SpvOpConstant, this->getType(i.type()), result, (SpvId) i.value(),
Ethan Nicholascc5d3e02019-04-19 09:50:56 -04002624 fConstantBuffer);
John Stilesacb091f2021-01-06 11:57:58 -05002625 iter->second = result;
Ethan Nicholascc5d3e02019-04-19 09:50:56 -04002626 }
John Stilesacb091f2021-01-06 11:57:58 -05002627 return iter->second;
ethannicholasb3058bd2016-07-01 08:22:01 -07002628}
2629
ethannicholasf789b382016-08-03 12:43:36 -07002630SpvId SPIRVCodeGenerator::writeFloatLiteral(const FloatLiteral& f) {
John Stilesbdc3d3c2021-01-06 18:41:40 -05002631 // Convert the float literal into its bit-representation.
2632 float value = f.value();
2633 uint32_t valueBits;
2634 static_assert(sizeof(valueBits) == sizeof(value));
2635 memcpy(&valueBits, &value, sizeof(value));
2636
2637 SPIRVNumberConstant key{valueBits, f.type().numberKind()};
John Stilesacb091f2021-01-06 11:57:58 -05002638 auto [iter, newlyCreated] = fNumberConstants.insert({key, (SpvId)-1});
2639 if (newlyCreated) {
John Stiles8c578662020-06-01 15:32:47 +00002640 SpvId result = this->nextId();
John Stilesbdc3d3c2021-01-06 18:41:40 -05002641 this->writeInstruction(SpvOpConstant, this->getType(f.type()), result, (SpvId) valueBits,
John Stiles8c578662020-06-01 15:32:47 +00002642 fConstantBuffer);
John Stilesacb091f2021-01-06 11:57:58 -05002643 iter->second = result;
John Stiles8c578662020-06-01 15:32:47 +00002644 }
John Stilesacb091f2021-01-06 11:57:58 -05002645 return iter->second;
ethannicholasb3058bd2016-07-01 08:22:01 -07002646}
2647
Ethan Nicholas0df1b042017-03-31 13:56:23 -04002648SpvId SPIRVCodeGenerator::writeFunctionStart(const FunctionDeclaration& f, OutputStream& out) {
ethannicholasd598f792016-07-25 10:08:54 -07002649 SpvId result = fFunctionMap[&f];
Ethan Nicholased84b732020-10-08 11:45:44 -04002650 this->writeInstruction(SpvOpFunction, this->getType(f.returnType()), result,
ethannicholasb3058bd2016-07-01 08:22:01 -07002651 SpvFunctionControlMaskNone, this->getFunctionType(f), out);
Ethan Nicholase2c49992020-10-05 11:49:11 -04002652 this->writeInstruction(SpvOpName, result, f.name(), fNameBuffer);
Brian Osman5bf3e202020-10-13 10:34:18 -04002653 const std::vector<const Variable*>& parameters = f.parameters();
Ethan Nicholased84b732020-10-08 11:45:44 -04002654 for (size_t i = 0; i < parameters.size(); i++) {
ethannicholasb3058bd2016-07-01 08:22:01 -07002655 SpvId id = this->nextId();
Ethan Nicholased84b732020-10-08 11:45:44 -04002656 fVariableMap[parameters[i]] = id;
ethannicholasb3058bd2016-07-01 08:22:01 -07002657 SpvId type;
Ethan Nicholased84b732020-10-08 11:45:44 -04002658 type = this->getPointerType(parameters[i]->type(), SpvStorageClassFunction);
ethannicholasb3058bd2016-07-01 08:22:01 -07002659 this->writeInstruction(SpvOpFunctionParameter, type, id, out);
2660 }
2661 return result;
2662}
2663
Ethan Nicholas0df1b042017-03-31 13:56:23 -04002664SpvId SPIRVCodeGenerator::writeFunction(const FunctionDefinition& f, OutputStream& out) {
2665 fVariableBuffer.reset();
Ethan Nicholas0a5d0962020-10-14 13:33:18 -04002666 SpvId result = this->writeFunctionStart(f.declaration(), out);
Ethan Nicholas7fb39362020-12-16 15:25:19 -05002667 fCurrentBlock = 0;
ethannicholasb3058bd2016-07-01 08:22:01 -07002668 this->writeLabel(this->nextId(), out);
Ethan Nicholas0df1b042017-03-31 13:56:23 -04002669 StringStream bodyBuffer;
Ethan Nicholas0a5d0962020-10-14 13:33:18 -04002670 this->writeBlock((Block&) *f.body(), bodyBuffer);
Ethan Nicholas0df1b042017-03-31 13:56:23 -04002671 write_stringstream(fVariableBuffer, out);
Ethan Nicholas0a5d0962020-10-14 13:33:18 -04002672 if (f.declaration().name() == "main") {
Ethan Nicholas8eb64d32018-12-21 14:50:42 -05002673 write_stringstream(fGlobalInitializersBuffer, out);
2674 }
Ethan Nicholas0df1b042017-03-31 13:56:23 -04002675 write_stringstream(bodyBuffer, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002676 if (fCurrentBlock) {
John Stiles54e7c052021-01-11 14:22:36 -05002677 if (f.declaration().returnType() == *fContext.fTypes.fVoid) {
Ethan Nicholas70a44b22017-11-30 09:09:16 -05002678 this->writeInstruction(SpvOpReturn, out);
2679 } else {
2680 this->writeInstruction(SpvOpUnreachable, out);
2681 }
ethannicholasb3058bd2016-07-01 08:22:01 -07002682 }
2683 this->writeInstruction(SpvOpFunctionEnd, out);
2684 return result;
2685}
2686
2687void SPIRVCodeGenerator::writeLayout(const Layout& layout, SpvId target) {
2688 if (layout.fLocation >= 0) {
Greg Daniel64773e62016-11-22 09:44:03 -05002689 this->writeInstruction(SpvOpDecorate, target, SpvDecorationLocation, layout.fLocation,
ethannicholasb3058bd2016-07-01 08:22:01 -07002690 fDecorationBuffer);
2691 }
2692 if (layout.fBinding >= 0) {
Greg Daniel64773e62016-11-22 09:44:03 -05002693 this->writeInstruction(SpvOpDecorate, target, SpvDecorationBinding, layout.fBinding,
ethannicholasb3058bd2016-07-01 08:22:01 -07002694 fDecorationBuffer);
2695 }
2696 if (layout.fIndex >= 0) {
Greg Daniel64773e62016-11-22 09:44:03 -05002697 this->writeInstruction(SpvOpDecorate, target, SpvDecorationIndex, layout.fIndex,
ethannicholasb3058bd2016-07-01 08:22:01 -07002698 fDecorationBuffer);
2699 }
2700 if (layout.fSet >= 0) {
Greg Daniel64773e62016-11-22 09:44:03 -05002701 this->writeInstruction(SpvOpDecorate, target, SpvDecorationDescriptorSet, layout.fSet,
ethannicholasb3058bd2016-07-01 08:22:01 -07002702 fDecorationBuffer);
2703 }
Greg Daniel64773e62016-11-22 09:44:03 -05002704 if (layout.fInputAttachmentIndex >= 0) {
2705 this->writeInstruction(SpvOpDecorate, target, SpvDecorationInputAttachmentIndex,
2706 layout.fInputAttachmentIndex, fDecorationBuffer);
Ethan Nicholasbe1099f2018-01-11 16:09:05 -05002707 fCapabilities |= (((uint64_t) 1) << SpvCapabilityInputAttachment);
Greg Daniel64773e62016-11-22 09:44:03 -05002708 }
Ethan Nicholasbb155e22017-07-24 10:05:09 -04002709 if (layout.fBuiltin >= 0 && layout.fBuiltin != SK_FRAGCOLOR_BUILTIN &&
Greg Daniele6ab9982018-08-22 13:56:32 +00002710 layout.fBuiltin != SK_IN_BUILTIN && layout.fBuiltin != SK_OUT_BUILTIN) {
Greg Daniel64773e62016-11-22 09:44:03 -05002711 this->writeInstruction(SpvOpDecorate, target, SpvDecorationBuiltIn, layout.fBuiltin,
ethannicholasb3058bd2016-07-01 08:22:01 -07002712 fDecorationBuffer);
2713 }
2714}
2715
2716void SPIRVCodeGenerator::writeLayout(const Layout& layout, SpvId target, int member) {
2717 if (layout.fLocation >= 0) {
Greg Daniel64773e62016-11-22 09:44:03 -05002718 this->writeInstruction(SpvOpMemberDecorate, target, member, SpvDecorationLocation,
ethannicholasb3058bd2016-07-01 08:22:01 -07002719 layout.fLocation, fDecorationBuffer);
2720 }
2721 if (layout.fBinding >= 0) {
Greg Daniel64773e62016-11-22 09:44:03 -05002722 this->writeInstruction(SpvOpMemberDecorate, target, member, SpvDecorationBinding,
ethannicholasb3058bd2016-07-01 08:22:01 -07002723 layout.fBinding, fDecorationBuffer);
2724 }
2725 if (layout.fIndex >= 0) {
Greg Daniel64773e62016-11-22 09:44:03 -05002726 this->writeInstruction(SpvOpMemberDecorate, target, member, SpvDecorationIndex,
ethannicholasb3058bd2016-07-01 08:22:01 -07002727 layout.fIndex, fDecorationBuffer);
2728 }
2729 if (layout.fSet >= 0) {
Greg Daniel64773e62016-11-22 09:44:03 -05002730 this->writeInstruction(SpvOpMemberDecorate, target, member, SpvDecorationDescriptorSet,
ethannicholasb3058bd2016-07-01 08:22:01 -07002731 layout.fSet, fDecorationBuffer);
2732 }
Greg Daniel64773e62016-11-22 09:44:03 -05002733 if (layout.fInputAttachmentIndex >= 0) {
2734 this->writeInstruction(SpvOpDecorate, target, member, SpvDecorationInputAttachmentIndex,
2735 layout.fInputAttachmentIndex, fDecorationBuffer);
2736 }
ethannicholasb3058bd2016-07-01 08:22:01 -07002737 if (layout.fBuiltin >= 0) {
Greg Daniel64773e62016-11-22 09:44:03 -05002738 this->writeInstruction(SpvOpMemberDecorate, target, member, SpvDecorationBuiltIn,
ethannicholasb3058bd2016-07-01 08:22:01 -07002739 layout.fBuiltin, fDecorationBuffer);
2740 }
2741}
2742
Ethan Nicholas81d15112018-07-13 12:48:50 -04002743static void update_sk_in_count(const Modifiers& m, int* outSkInCount) {
2744 switch (m.fLayout.fPrimitive) {
2745 case Layout::kPoints_Primitive:
2746 *outSkInCount = 1;
2747 break;
2748 case Layout::kLines_Primitive:
2749 *outSkInCount = 2;
2750 break;
2751 case Layout::kLinesAdjacency_Primitive:
2752 *outSkInCount = 4;
2753 break;
2754 case Layout::kTriangles_Primitive:
2755 *outSkInCount = 3;
2756 break;
2757 case Layout::kTrianglesAdjacency_Primitive:
2758 *outSkInCount = 6;
2759 break;
2760 default:
2761 return;
2762 }
2763}
2764
Stephen White88574972020-06-23 19:09:29 -04002765SpvId SPIRVCodeGenerator::writeInterfaceBlock(const InterfaceBlock& intf, bool appendRTHeight) {
Ethan Nicholaseaf47882020-10-15 10:10:08 -04002766 bool isBuffer = ((intf.variable().modifiers().fFlags & Modifiers::kBuffer_Flag) != 0);
2767 bool pushConstant = ((intf.variable().modifiers().fLayout.fFlags &
2768 Layout::kPushConstant_Flag) != 0);
Ethan Nicholas8d2ba442018-03-16 16:40:36 -04002769 MemoryLayout memoryLayout = (pushConstant || isBuffer) ?
2770 MemoryLayout(MemoryLayout::k430_Standard) :
2771 fDefaultLayout;
ethannicholasb3058bd2016-07-01 08:22:01 -07002772 SpvId result = this->nextId();
John Stilesad2d4942020-12-11 16:55:58 -05002773 std::unique_ptr<Type> rtHeightStructType;
Ethan Nicholaseaf47882020-10-15 10:10:08 -04002774 const Type* type = &intf.variable().type();
John Stiles21f5f452020-11-30 09:57:59 -05002775 if (!MemoryLayout::LayoutIsSupported(*type)) {
John Stiles0023c0c2020-11-16 13:32:18 -05002776 fErrors.error(type->fOffset, "type '" + type->name() + "' is not permitted here");
2777 return this->nextId();
2778 }
Jim Van Verthf3ec9832020-10-21 16:09:57 -04002779 Modifiers intfModifiers = intf.variable().modifiers();
2780 SpvStorageClass_ storageClass = get_storage_class(intfModifiers);
Stephen White88574972020-06-23 19:09:29 -04002781 if (fProgram.fInputs.fRTHeight && appendRTHeight) {
Greg Daniele6ab9982018-08-22 13:56:32 +00002782 SkASSERT(fRTHeightStructId == (SpvId) -1);
2783 SkASSERT(fRTHeightFieldIndex == (SpvId) -1);
Ethan Nicholas941e7e22016-12-12 15:33:30 -05002784 std::vector<Type::Field> fields = type->fields();
Greg Daniele6ab9982018-08-22 13:56:32 +00002785 fRTHeightStructId = result;
2786 fRTHeightFieldIndex = fields.size();
Jim Van Verthf3ec9832020-10-21 16:09:57 -04002787 fRTHeightStorageClass = storageClass;
John Stilesad2d4942020-12-11 16:55:58 -05002788 fields.emplace_back(Modifiers(), StringFragment(SKSL_RTHEIGHT_NAME),
John Stiles54e7c052021-01-11 14:22:36 -05002789 fContext.fTypes.fFloat.get());
John Stilesad2d4942020-12-11 16:55:58 -05002790 rtHeightStructType = Type::MakeStructType(type->fOffset, type->name(), std::move(fields));
2791 type = rtHeightStructType.get();
Ethan Nicholas941e7e22016-12-12 15:33:30 -05002792 }
Ethan Nicholas5226b772018-05-03 16:20:41 -04002793 SpvId typeId;
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002794 if (intfModifiers.fLayout.fBuiltin == SK_IN_BUILTIN) {
Brian Osman133724c2020-10-28 14:14:39 -04002795 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04002796 if (e->is<ModifiersDeclaration>()) {
Ethan Nicholas077050b2020-10-13 10:30:20 -04002797 const Modifiers& m = e->as<ModifiersDeclaration>().modifiers();
Ethan Nicholas81d15112018-07-13 12:48:50 -04002798 update_sk_in_count(m, &fSkInCount);
Ethan Nicholas5226b772018-05-03 16:20:41 -04002799 }
2800 }
John Stilesad2d4942020-12-11 16:55:58 -05002801 typeId = this->getType(
2802 *Type::MakeArrayType("sk_in", intf.variable().type().componentType(), fSkInCount),
2803 memoryLayout);
Ethan Nicholas5226b772018-05-03 16:20:41 -04002804 } else {
2805 typeId = this->getType(*type, memoryLayout);
2806 }
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002807 if (intfModifiers.fFlags & Modifiers::kBuffer_Flag) {
Ethan Nicholas0dd30d92017-05-01 16:57:07 -04002808 this->writeInstruction(SpvOpDecorate, typeId, SpvDecorationBufferBlock, fDecorationBuffer);
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002809 } else if (intfModifiers.fLayout.fBuiltin == -1) {
Ethan Nicholas6ac8d362019-01-22 21:43:55 +00002810 this->writeInstruction(SpvOpDecorate, typeId, SpvDecorationBlock, fDecorationBuffer);
Ethan Nicholas0dd30d92017-05-01 16:57:07 -04002811 }
ethannicholasb3058bd2016-07-01 08:22:01 -07002812 SpvId ptrType = this->nextId();
Ethan Nicholas941e7e22016-12-12 15:33:30 -05002813 this->writeInstruction(SpvOpTypePointer, ptrType, storageClass, typeId, fConstantBuffer);
ethannicholasb3058bd2016-07-01 08:22:01 -07002814 this->writeInstruction(SpvOpVariable, ptrType, result, storageClass, fConstantBuffer);
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002815 Layout layout = intfModifiers.fLayout;
2816 if (intfModifiers.fFlags & Modifiers::kUniform_Flag && layout.fSet == -1) {
Ethan Nicholas8d2ba442018-03-16 16:40:36 -04002817 layout.fSet = 0;
2818 }
2819 this->writeLayout(layout, result);
Ethan Nicholaseaf47882020-10-15 10:10:08 -04002820 fVariableMap[&intf.variable()] = result;
ethannicholasb3058bd2016-07-01 08:22:01 -07002821 return result;
2822}
2823
Ethan Nicholas858fecc2019-03-07 13:19:18 -05002824void SPIRVCodeGenerator::writePrecisionModifier(const Type& type, SpvId id) {
Ethan Nicholas10e93b62019-03-20 10:46:14 -04002825 this->writePrecisionModifier(type.highPrecision() ? Precision::kHigh : Precision::kLow, id);
2826}
2827
2828void SPIRVCodeGenerator::writePrecisionModifier(Precision precision, SpvId id) {
2829 if (precision == Precision::kLow) {
Ethan Nicholasa51d7132017-06-09 10:47:31 -04002830 this->writeInstruction(SpvOpDecorate, id, SpvDecorationRelaxedPrecision, fDecorationBuffer);
2831 }
2832}
2833
Brian Osman010ce6a2020-10-19 16:34:10 -04002834bool is_dead(const Variable& var, const ProgramUsage* usage) {
2835 ProgramUsage::VariableCounts counts = usage->get(var);
2836 if (counts.fRead || counts.fWrite) {
Chris Dalton2284aab2019-11-15 11:02:24 -07002837 return false;
2838 }
2839 // not entirely sure what the rules are for when it's safe to elide interface variables, but it
2840 // causes various problems to elide some of them even when dead. But it also causes problems
2841 // *not* to elide sk_SampleMask when it's not being used.
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002842 if (!(var.modifiers().fFlags & (Modifiers::kIn_Flag |
2843 Modifiers::kOut_Flag |
2844 Modifiers::kUniform_Flag |
2845 Modifiers::kBuffer_Flag))) {
Chris Dalton2284aab2019-11-15 11:02:24 -07002846 return true;
2847 }
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002848 return var.modifiers().fLayout.fBuiltin == SK_SAMPLEMASK_BUILTIN;
Chris Dalton2284aab2019-11-15 11:02:24 -07002849}
2850
ethannicholas5961bc92016-10-12 06:39:56 -07002851#define BUILTIN_IGNORE 9999
Brian Osmanc0213602020-10-06 14:43:32 -04002852void SPIRVCodeGenerator::writeGlobalVar(Program::Kind kind, const VarDeclaration& varDecl,
2853 OutputStream& out) {
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04002854 const Variable& var = varDecl.var();
Brian Osmanc0213602020-10-06 14:43:32 -04002855 // These haven't been implemented in our SPIR-V generator yet and we only currently use them
2856 // in the OpenGL backend.
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04002857 SkASSERT(!(var.modifiers().fFlags & (Modifiers::kReadOnly_Flag |
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002858 Modifiers::kWriteOnly_Flag |
2859 Modifiers::kCoherent_Flag |
2860 Modifiers::kVolatile_Flag |
2861 Modifiers::kRestrict_Flag)));
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04002862 if (var.modifiers().fLayout.fBuiltin == BUILTIN_IGNORE) {
Brian Osmanc0213602020-10-06 14:43:32 -04002863 return;
2864 }
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04002865 if (var.modifiers().fLayout.fBuiltin == SK_FRAGCOLOR_BUILTIN &&
Brian Osmanc0213602020-10-06 14:43:32 -04002866 kind != Program::kFragment_Kind) {
2867 SkASSERT(!fProgram.fSettings.fFragColorIsInOut);
2868 return;
2869 }
Brian Osman010ce6a2020-10-19 16:34:10 -04002870 if (is_dead(var, fProgram.fUsage.get())) {
Brian Osmanc0213602020-10-06 14:43:32 -04002871 return;
2872 }
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04002873 const Type& type = var.type();
Brian Osmanc0213602020-10-06 14:43:32 -04002874 SpvStorageClass_ storageClass;
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04002875 if (var.modifiers().fFlags & Modifiers::kIn_Flag) {
Brian Osmanc0213602020-10-06 14:43:32 -04002876 storageClass = SpvStorageClassInput;
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04002877 } else if (var.modifiers().fFlags & Modifiers::kOut_Flag) {
Brian Osmanc0213602020-10-06 14:43:32 -04002878 storageClass = SpvStorageClassOutput;
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04002879 } else if (var.modifiers().fFlags & Modifiers::kUniform_Flag) {
Brian Osmanc0213602020-10-06 14:43:32 -04002880 if (type.typeKind() == Type::TypeKind::kSampler ||
2881 type.typeKind() == Type::TypeKind::kSeparateSampler ||
2882 type.typeKind() == Type::TypeKind::kTexture) {
2883 storageClass = SpvStorageClassUniformConstant;
ethannicholasb3058bd2016-07-01 08:22:01 -07002884 } else {
Brian Osmanc0213602020-10-06 14:43:32 -04002885 storageClass = SpvStorageClassUniform;
ethannicholasb3058bd2016-07-01 08:22:01 -07002886 }
Brian Osmanc0213602020-10-06 14:43:32 -04002887 } else {
2888 storageClass = SpvStorageClassPrivate;
2889 }
2890 SpvId id = this->nextId();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04002891 fVariableMap[&var] = id;
Brian Osmanc0213602020-10-06 14:43:32 -04002892 SpvId typeId;
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04002893 if (var.modifiers().fLayout.fBuiltin == SK_IN_BUILTIN) {
Brian Osmanc0213602020-10-06 14:43:32 -04002894 typeId = this->getPointerType(
John Stilesad2d4942020-12-11 16:55:58 -05002895 *Type::MakeArrayType("sk_in", type.componentType(), fSkInCount),
Brian Osmanc0213602020-10-06 14:43:32 -04002896 storageClass);
2897 } else {
2898 typeId = this->getPointerType(type, storageClass);
2899 }
2900 this->writeInstruction(SpvOpVariable, typeId, id, storageClass, fConstantBuffer);
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04002901 this->writeInstruction(SpvOpName, id, var.name(), fNameBuffer);
Brian Osmanc0213602020-10-06 14:43:32 -04002902 this->writePrecisionModifier(type, id);
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04002903 if (varDecl.value()) {
Brian Osmanc0213602020-10-06 14:43:32 -04002904 SkASSERT(!fCurrentBlock);
2905 fCurrentBlock = -1;
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04002906 SpvId value = this->writeExpression(*varDecl.value(), fGlobalInitializersBuffer);
Brian Osmanc0213602020-10-06 14:43:32 -04002907 this->writeInstruction(SpvOpStore, id, value, fGlobalInitializersBuffer);
2908 fCurrentBlock = 0;
2909 }
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04002910 this->writeLayout(var.modifiers().fLayout, id);
2911 if (var.modifiers().fFlags & Modifiers::kFlat_Flag) {
Brian Osmanc0213602020-10-06 14:43:32 -04002912 this->writeInstruction(SpvOpDecorate, id, SpvDecorationFlat, fDecorationBuffer);
2913 }
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04002914 if (var.modifiers().fFlags & Modifiers::kNoPerspective_Flag) {
Brian Osmanc0213602020-10-06 14:43:32 -04002915 this->writeInstruction(SpvOpDecorate, id, SpvDecorationNoPerspective,
2916 fDecorationBuffer);
ethannicholasb3058bd2016-07-01 08:22:01 -07002917 }
2918}
2919
Brian Osmanc0213602020-10-06 14:43:32 -04002920void SPIRVCodeGenerator::writeVarDeclaration(const VarDeclaration& varDecl, OutputStream& out) {
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04002921 const Variable& var = varDecl.var();
Brian Osmanc0213602020-10-06 14:43:32 -04002922 // These haven't been implemented in our SPIR-V generator yet and we only currently use them
2923 // in the OpenGL backend.
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04002924 SkASSERT(!(var.modifiers().fFlags & (Modifiers::kReadOnly_Flag |
2925 Modifiers::kWriteOnly_Flag |
2926 Modifiers::kCoherent_Flag |
2927 Modifiers::kVolatile_Flag |
2928 Modifiers::kRestrict_Flag)));
Brian Osmanc0213602020-10-06 14:43:32 -04002929 SpvId id = this->nextId();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04002930 fVariableMap[&var] = id;
2931 SpvId type = this->getPointerType(var.type(), SpvStorageClassFunction);
Brian Osmanc0213602020-10-06 14:43:32 -04002932 this->writeInstruction(SpvOpVariable, type, id, SpvStorageClassFunction, fVariableBuffer);
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04002933 this->writeInstruction(SpvOpName, id, var.name(), fNameBuffer);
2934 if (varDecl.value()) {
2935 SpvId value = this->writeExpression(*varDecl.value(), out);
Brian Osmanc0213602020-10-06 14:43:32 -04002936 this->writeInstruction(SpvOpStore, id, value, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002937 }
2938}
2939
Ethan Nicholas0df1b042017-03-31 13:56:23 -04002940void SPIRVCodeGenerator::writeStatement(const Statement& s, OutputStream& out) {
Ethan Nicholase6592142020-09-08 10:22:09 -04002941 switch (s.kind()) {
John Stiles98c1f822020-09-09 14:18:53 -04002942 case Statement::Kind::kInlineMarker:
Ethan Nicholase6592142020-09-08 10:22:09 -04002943 case Statement::Kind::kNop:
Ethan Nicholascb670962017-04-20 19:31:52 -04002944 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04002945 case Statement::Kind::kBlock:
ethannicholasb3058bd2016-07-01 08:22:01 -07002946 this->writeBlock((Block&) s, out);
2947 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04002948 case Statement::Kind::kExpression:
Ethan Nicholasd503a5a2020-09-30 09:29:55 -04002949 this->writeExpression(*s.as<ExpressionStatement>().expression(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002950 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04002951 case Statement::Kind::kReturn:
John Stiles26f98502020-08-18 09:30:51 -04002952 this->writeReturnStatement(s.as<ReturnStatement>(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002953 break;
Brian Osmanc0213602020-10-06 14:43:32 -04002954 case Statement::Kind::kVarDeclaration:
2955 this->writeVarDeclaration(s.as<VarDeclaration>(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002956 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04002957 case Statement::Kind::kIf:
John Stiles26f98502020-08-18 09:30:51 -04002958 this->writeIfStatement(s.as<IfStatement>(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002959 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04002960 case Statement::Kind::kFor:
John Stiles26f98502020-08-18 09:30:51 -04002961 this->writeForStatement(s.as<ForStatement>(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002962 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04002963 case Statement::Kind::kDo:
John Stiles26f98502020-08-18 09:30:51 -04002964 this->writeDoStatement(s.as<DoStatement>(), out);
Ethan Nicholasfd146aa2017-01-13 16:40:35 -05002965 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04002966 case Statement::Kind::kSwitch:
John Stiles26f98502020-08-18 09:30:51 -04002967 this->writeSwitchStatement(s.as<SwitchStatement>(), out);
Ethan Nicholase92b1b12017-11-13 16:13:21 -05002968 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04002969 case Statement::Kind::kBreak:
ethannicholasb3058bd2016-07-01 08:22:01 -07002970 this->writeInstruction(SpvOpBranch, fBreakTarget.top(), out);
2971 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04002972 case Statement::Kind::kContinue:
ethannicholasb3058bd2016-07-01 08:22:01 -07002973 this->writeInstruction(SpvOpBranch, fContinueTarget.top(), out);
2974 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04002975 case Statement::Kind::kDiscard:
ethannicholasb3058bd2016-07-01 08:22:01 -07002976 this->writeInstruction(SpvOpKill, out);
2977 break;
2978 default:
Ethan Nicholas2a099da2020-01-02 14:40:54 -05002979#ifdef SK_DEBUG
ethannicholasb3058bd2016-07-01 08:22:01 -07002980 ABORT("unsupported statement: %s", s.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -05002981#endif
2982 break;
ethannicholasb3058bd2016-07-01 08:22:01 -07002983 }
2984}
2985
Ethan Nicholas0df1b042017-03-31 13:56:23 -04002986void SPIRVCodeGenerator::writeBlock(const Block& b, OutputStream& out) {
Ethan Nicholas7bd60432020-09-25 14:31:59 -04002987 for (const std::unique_ptr<Statement>& stmt : b.children()) {
2988 this->writeStatement(*stmt, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002989 }
2990}
2991
Ethan Nicholas0df1b042017-03-31 13:56:23 -04002992void SPIRVCodeGenerator::writeIfStatement(const IfStatement& stmt, OutputStream& out) {
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04002993 SpvId test = this->writeExpression(*stmt.test(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002994 SpvId ifTrue = this->nextId();
2995 SpvId ifFalse = this->nextId();
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04002996 if (stmt.ifFalse()) {
ethannicholasb3058bd2016-07-01 08:22:01 -07002997 SpvId end = this->nextId();
2998 this->writeInstruction(SpvOpSelectionMerge, end, SpvSelectionControlMaskNone, out);
2999 this->writeInstruction(SpvOpBranchConditional, test, ifTrue, ifFalse, out);
3000 this->writeLabel(ifTrue, out);
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04003001 this->writeStatement(*stmt.ifTrue(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003002 if (fCurrentBlock) {
3003 this->writeInstruction(SpvOpBranch, end, out);
3004 }
3005 this->writeLabel(ifFalse, out);
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04003006 this->writeStatement(*stmt.ifFalse(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003007 if (fCurrentBlock) {
3008 this->writeInstruction(SpvOpBranch, end, out);
3009 }
3010 this->writeLabel(end, out);
3011 } else {
3012 this->writeInstruction(SpvOpSelectionMerge, ifFalse, SpvSelectionControlMaskNone, out);
3013 this->writeInstruction(SpvOpBranchConditional, test, ifTrue, ifFalse, out);
3014 this->writeLabel(ifTrue, out);
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04003015 this->writeStatement(*stmt.ifTrue(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003016 if (fCurrentBlock) {
3017 this->writeInstruction(SpvOpBranch, ifFalse, out);
3018 }
3019 this->writeLabel(ifFalse, out);
3020 }
3021}
3022
Ethan Nicholas0df1b042017-03-31 13:56:23 -04003023void SPIRVCodeGenerator::writeForStatement(const ForStatement& f, OutputStream& out) {
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04003024 if (f.initializer()) {
3025 this->writeStatement(*f.initializer(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003026 }
3027 SpvId header = this->nextId();
3028 SpvId start = this->nextId();
3029 SpvId body = this->nextId();
3030 SpvId next = this->nextId();
3031 fContinueTarget.push(next);
3032 SpvId end = this->nextId();
3033 fBreakTarget.push(end);
3034 this->writeInstruction(SpvOpBranch, header, out);
3035 this->writeLabel(header, out);
3036 this->writeInstruction(SpvOpLoopMerge, end, next, SpvLoopControlMaskNone, out);
ethannicholasf789b382016-08-03 12:43:36 -07003037 this->writeInstruction(SpvOpBranch, start, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003038 this->writeLabel(start, out);
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04003039 if (f.test()) {
3040 SpvId test = this->writeExpression(*f.test(), out);
ethannicholas22f939e2016-10-13 13:25:34 -07003041 this->writeInstruction(SpvOpBranchConditional, test, body, end, out);
Ethan Nicholas7fb39362020-12-16 15:25:19 -05003042 } else {
3043 this->writeInstruction(SpvOpBranch, body, out);
ethannicholas22f939e2016-10-13 13:25:34 -07003044 }
ethannicholasb3058bd2016-07-01 08:22:01 -07003045 this->writeLabel(body, out);
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04003046 this->writeStatement(*f.statement(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003047 if (fCurrentBlock) {
3048 this->writeInstruction(SpvOpBranch, next, out);
3049 }
3050 this->writeLabel(next, out);
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04003051 if (f.next()) {
3052 this->writeExpression(*f.next(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003053 }
3054 this->writeInstruction(SpvOpBranch, header, out);
3055 this->writeLabel(end, out);
3056 fBreakTarget.pop();
3057 fContinueTarget.pop();
3058}
3059
Ethan Nicholas0df1b042017-03-31 13:56:23 -04003060void SPIRVCodeGenerator::writeDoStatement(const DoStatement& d, OutputStream& out) {
Ethan Nicholasfd146aa2017-01-13 16:40:35 -05003061 SpvId header = this->nextId();
3062 SpvId start = this->nextId();
3063 SpvId next = this->nextId();
Ethan Nicholas0d997662019-04-08 09:46:01 -04003064 SpvId continueTarget = this->nextId();
3065 fContinueTarget.push(continueTarget);
Ethan Nicholasfd146aa2017-01-13 16:40:35 -05003066 SpvId end = this->nextId();
3067 fBreakTarget.push(end);
3068 this->writeInstruction(SpvOpBranch, header, out);
3069 this->writeLabel(header, out);
Ethan Nicholas0d997662019-04-08 09:46:01 -04003070 this->writeInstruction(SpvOpLoopMerge, end, continueTarget, SpvLoopControlMaskNone, out);
Ethan Nicholasfd146aa2017-01-13 16:40:35 -05003071 this->writeInstruction(SpvOpBranch, start, out);
3072 this->writeLabel(start, out);
Ethan Nicholas1fd61162020-09-28 13:14:19 -04003073 this->writeStatement(*d.statement(), out);
Ethan Nicholasfd146aa2017-01-13 16:40:35 -05003074 if (fCurrentBlock) {
3075 this->writeInstruction(SpvOpBranch, next, out);
3076 }
3077 this->writeLabel(next, out);
Ethan Nicholas1fd61162020-09-28 13:14:19 -04003078 SpvId test = this->writeExpression(*d.test(), out);
Ethan Nicholas0d997662019-04-08 09:46:01 -04003079 this->writeInstruction(SpvOpBranchConditional, test, continueTarget, end, out);
3080 this->writeLabel(continueTarget, out);
3081 this->writeInstruction(SpvOpBranch, header, out);
Ethan Nicholasfd146aa2017-01-13 16:40:35 -05003082 this->writeLabel(end, out);
3083 fBreakTarget.pop();
3084 fContinueTarget.pop();
3085}
3086
Ethan Nicholase92b1b12017-11-13 16:13:21 -05003087void SPIRVCodeGenerator::writeSwitchStatement(const SwitchStatement& s, OutputStream& out) {
Ethan Nicholas01b05e52020-10-22 15:53:41 -04003088 SpvId value = this->writeExpression(*s.value(), out);
Ethan Nicholase92b1b12017-11-13 16:13:21 -05003089 std::vector<SpvId> labels;
3090 SpvId end = this->nextId();
3091 SpvId defaultLabel = end;
3092 fBreakTarget.push(end);
3093 int size = 3;
John Stiles2d4f9592020-10-30 10:29:12 -04003094 auto& cases = s.cases();
3095 for (const std::unique_ptr<SwitchCase>& c : cases) {
Ethan Nicholase92b1b12017-11-13 16:13:21 -05003096 SpvId label = this->nextId();
3097 labels.push_back(label);
John Stiles2d4f9592020-10-30 10:29:12 -04003098 if (c->value()) {
Ethan Nicholase92b1b12017-11-13 16:13:21 -05003099 size += 2;
3100 } else {
3101 defaultLabel = label;
3102 }
3103 }
3104 labels.push_back(end);
3105 this->writeInstruction(SpvOpSelectionMerge, end, SpvSelectionControlMaskNone, out);
3106 this->writeOpCode(SpvOpSwitch, size, out);
3107 this->writeWord(value, out);
3108 this->writeWord(defaultLabel, out);
John Stiles2d4f9592020-10-30 10:29:12 -04003109 for (size_t i = 0; i < cases.size(); ++i) {
3110 if (!cases[i]->value()) {
Ethan Nicholase92b1b12017-11-13 16:13:21 -05003111 continue;
3112 }
John Stiles2d4f9592020-10-30 10:29:12 -04003113 this->writeWord(cases[i]->value()->as<IntLiteral>().value(), out);
Ethan Nicholase92b1b12017-11-13 16:13:21 -05003114 this->writeWord(labels[i], out);
3115 }
John Stiles2d4f9592020-10-30 10:29:12 -04003116 for (size_t i = 0; i < cases.size(); ++i) {
Ethan Nicholase92b1b12017-11-13 16:13:21 -05003117 this->writeLabel(labels[i], out);
John Stiles2d4f9592020-10-30 10:29:12 -04003118 for (const auto& stmt : cases[i]->statements()) {
Ethan Nicholase92b1b12017-11-13 16:13:21 -05003119 this->writeStatement(*stmt, out);
3120 }
3121 if (fCurrentBlock) {
3122 this->writeInstruction(SpvOpBranch, labels[i + 1], out);
3123 }
3124 }
3125 this->writeLabel(end, out);
3126 fBreakTarget.pop();
3127}
3128
Ethan Nicholas0df1b042017-03-31 13:56:23 -04003129void SPIRVCodeGenerator::writeReturnStatement(const ReturnStatement& r, OutputStream& out) {
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04003130 if (r.expression()) {
3131 this->writeInstruction(SpvOpReturnValue, this->writeExpression(*r.expression(), out),
ethannicholasb3058bd2016-07-01 08:22:01 -07003132 out);
3133 } else {
3134 this->writeInstruction(SpvOpReturn, out);
3135 }
3136}
3137
Ethan Nicholasbb155e22017-07-24 10:05:09 -04003138void SPIRVCodeGenerator::writeGeometryShaderExecutionMode(SpvId entryPoint, OutputStream& out) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04003139 SkASSERT(fProgram.fKind == Program::kGeometry_Kind);
Ethan Nicholasbb155e22017-07-24 10:05:09 -04003140 int invocations = 1;
Brian Osman133724c2020-10-28 14:14:39 -04003141 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04003142 if (e->is<ModifiersDeclaration>()) {
Ethan Nicholas077050b2020-10-13 10:30:20 -04003143 const Modifiers& m = e->as<ModifiersDeclaration>().modifiers();
Ethan Nicholasbb155e22017-07-24 10:05:09 -04003144 if (m.fFlags & Modifiers::kIn_Flag) {
3145 if (m.fLayout.fInvocations != -1) {
3146 invocations = m.fLayout.fInvocations;
3147 }
3148 SpvId input;
3149 switch (m.fLayout.fPrimitive) {
3150 case Layout::kPoints_Primitive:
3151 input = SpvExecutionModeInputPoints;
3152 break;
3153 case Layout::kLines_Primitive:
3154 input = SpvExecutionModeInputLines;
3155 break;
3156 case Layout::kLinesAdjacency_Primitive:
3157 input = SpvExecutionModeInputLinesAdjacency;
3158 break;
3159 case Layout::kTriangles_Primitive:
3160 input = SpvExecutionModeTriangles;
3161 break;
3162 case Layout::kTrianglesAdjacency_Primitive:
3163 input = SpvExecutionModeInputTrianglesAdjacency;
3164 break;
3165 default:
3166 input = 0;
3167 break;
3168 }
Ethan Nicholas81d15112018-07-13 12:48:50 -04003169 update_sk_in_count(m, &fSkInCount);
Ethan Nicholasbb155e22017-07-24 10:05:09 -04003170 if (input) {
3171 this->writeInstruction(SpvOpExecutionMode, entryPoint, input, out);
3172 }
3173 } else if (m.fFlags & Modifiers::kOut_Flag) {
3174 SpvId output;
3175 switch (m.fLayout.fPrimitive) {
3176 case Layout::kPoints_Primitive:
3177 output = SpvExecutionModeOutputPoints;
3178 break;
3179 case Layout::kLineStrip_Primitive:
3180 output = SpvExecutionModeOutputLineStrip;
3181 break;
3182 case Layout::kTriangleStrip_Primitive:
3183 output = SpvExecutionModeOutputTriangleStrip;
3184 break;
3185 default:
3186 output = 0;
3187 break;
3188 }
3189 if (output) {
3190 this->writeInstruction(SpvOpExecutionMode, entryPoint, output, out);
3191 }
3192 if (m.fLayout.fMaxVertices != -1) {
3193 this->writeInstruction(SpvOpExecutionMode, entryPoint,
3194 SpvExecutionModeOutputVertices, m.fLayout.fMaxVertices,
3195 out);
3196 }
3197 }
3198 }
3199 }
3200 this->writeInstruction(SpvOpExecutionMode, entryPoint, SpvExecutionModeInvocations,
3201 invocations, out);
3202}
3203
Ethan Nicholas0df1b042017-03-31 13:56:23 -04003204void SPIRVCodeGenerator::writeInstructions(const Program& program, OutputStream& out) {
ethannicholasb3058bd2016-07-01 08:22:01 -07003205 fGLSLExtendedInstructions = this->nextId();
Ethan Nicholas0df1b042017-03-31 13:56:23 -04003206 StringStream body;
Ethan Nicholas8e48c1e2017-03-02 14:33:31 -05003207 std::set<SpvId> interfaceVars;
Brian Osman1f8f5752020-10-28 14:46:21 -04003208 // assign IDs to functions
Brian Osman133724c2020-10-28 14:14:39 -04003209 for (const ProgramElement* e : program.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04003210 switch (e->kind()) {
Ethan Nicholase6592142020-09-08 10:22:09 -04003211 case ProgramElement::Kind::kFunction: {
Brian Osman1179fcf2020-10-08 16:04:40 -04003212 const FunctionDefinition& f = e->as<FunctionDefinition>();
Ethan Nicholas0a5d0962020-10-14 13:33:18 -04003213 fFunctionMap[&f.declaration()] = this->nextId();
Ethan Nicholasb6ba82c2018-01-17 15:21:50 -05003214 break;
3215 }
Ethan Nicholasb6ba82c2018-01-17 15:21:50 -05003216 default:
3217 break;
ethannicholasb3058bd2016-07-01 08:22:01 -07003218 }
3219 }
Brian Osman133724c2020-10-28 14:14:39 -04003220 for (const ProgramElement* e : program.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04003221 if (e->is<InterfaceBlock>()) {
Brian Osman1f8f5752020-10-28 14:46:21 -04003222 const InterfaceBlock& intf = e->as<InterfaceBlock>();
ethannicholasb3058bd2016-07-01 08:22:01 -07003223 SpvId id = this->writeInterfaceBlock(intf);
Brian Osman1f8f5752020-10-28 14:46:21 -04003224
3225 const Modifiers& modifiers = intf.variable().modifiers();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04003226 if (((modifiers.fFlags & Modifiers::kIn_Flag) ||
3227 (modifiers.fFlags & Modifiers::kOut_Flag)) &&
3228 modifiers.fLayout.fBuiltin == -1 &&
Brian Osman010ce6a2020-10-19 16:34:10 -04003229 !is_dead(intf.variable(), fProgram.fUsage.get())) {
Ethan Nicholas8e48c1e2017-03-02 14:33:31 -05003230 interfaceVars.insert(id);
ethannicholasb3058bd2016-07-01 08:22:01 -07003231 }
3232 }
3233 }
Brian Osman133724c2020-10-28 14:14:39 -04003234 for (const ProgramElement* e : program.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04003235 if (e->is<GlobalVarDeclaration>()) {
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04003236 this->writeGlobalVar(program.fKind,
3237 e->as<GlobalVarDeclaration>().declaration()->as<VarDeclaration>(),
3238 body);
ethannicholasb3058bd2016-07-01 08:22:01 -07003239 }
3240 }
Brian Osman133724c2020-10-28 14:14:39 -04003241 for (const ProgramElement* e : program.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04003242 if (e->is<FunctionDefinition>()) {
3243 this->writeFunction(e->as<FunctionDefinition>(), body);
ethannicholasb3058bd2016-07-01 08:22:01 -07003244 }
3245 }
ethannicholasd598f792016-07-25 10:08:54 -07003246 const FunctionDeclaration* main = nullptr;
ethannicholasb3058bd2016-07-01 08:22:01 -07003247 for (auto entry : fFunctionMap) {
Ethan Nicholase2c49992020-10-05 11:49:11 -04003248 if (entry.first->name() == "main") {
ethannicholasb3058bd2016-07-01 08:22:01 -07003249 main = entry.first;
3250 }
3251 }
Ethan Nicholas1a668d22019-04-18 10:37:40 -04003252 if (!main) {
3253 fErrors.error(0, "program does not contain a main() function");
3254 return;
3255 }
ethannicholasb3058bd2016-07-01 08:22:01 -07003256 for (auto entry : fVariableMap) {
ethannicholasd598f792016-07-25 10:08:54 -07003257 const Variable* var = entry.first;
Ethan Nicholas453f67f2020-10-09 10:43:45 -04003258 if (var->storage() == Variable::Storage::kGlobal &&
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04003259 ((var->modifiers().fFlags & Modifiers::kIn_Flag) ||
Brian Osman010ce6a2020-10-19 16:34:10 -04003260 (var->modifiers().fFlags & Modifiers::kOut_Flag)) &&
3261 !is_dead(*var, fProgram.fUsage.get())) {
Ethan Nicholas8e48c1e2017-03-02 14:33:31 -05003262 interfaceVars.insert(entry.second);
ethannicholasb3058bd2016-07-01 08:22:01 -07003263 }
3264 }
3265 this->writeCapabilities(out);
3266 this->writeInstruction(SpvOpExtInstImport, fGLSLExtendedInstructions, "GLSL.std.450", out);
3267 this->writeInstruction(SpvOpMemoryModel, SpvAddressingModelLogical, SpvMemoryModelGLSL450, out);
Ethan Nicholase2c49992020-10-05 11:49:11 -04003268 this->writeOpCode(SpvOpEntryPoint, (SpvId) (3 + (main->name().fLength + 4) / 4) +
ethannicholasb3058bd2016-07-01 08:22:01 -07003269 (int32_t) interfaceVars.size(), out);
3270 switch (program.fKind) {
3271 case Program::kVertex_Kind:
3272 this->writeWord(SpvExecutionModelVertex, out);
3273 break;
3274 case Program::kFragment_Kind:
3275 this->writeWord(SpvExecutionModelFragment, out);
3276 break;
Ethan Nicholas52cad152017-02-16 16:37:32 -05003277 case Program::kGeometry_Kind:
3278 this->writeWord(SpvExecutionModelGeometry, out);
3279 break;
Ethan Nicholas762466e2017-06-29 10:03:38 -04003280 default:
3281 ABORT("cannot write this kind of program to SPIR-V\n");
ethannicholasb3058bd2016-07-01 08:22:01 -07003282 }
Ethan Nicholasbb155e22017-07-24 10:05:09 -04003283 SpvId entryPoint = fFunctionMap[main];
3284 this->writeWord(entryPoint, out);
Ethan Nicholase2c49992020-10-05 11:49:11 -04003285 this->writeString(main->name().fChars, main->name().fLength, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003286 for (int var : interfaceVars) {
3287 this->writeWord(var, out);
3288 }
Ethan Nicholasbb155e22017-07-24 10:05:09 -04003289 if (program.fKind == Program::kGeometry_Kind) {
3290 this->writeGeometryShaderExecutionMode(entryPoint, out);
3291 }
ethannicholasb3058bd2016-07-01 08:22:01 -07003292 if (program.fKind == Program::kFragment_Kind) {
Greg Daniel64773e62016-11-22 09:44:03 -05003293 this->writeInstruction(SpvOpExecutionMode,
3294 fFunctionMap[main],
ethannicholasb3058bd2016-07-01 08:22:01 -07003295 SpvExecutionModeOriginUpperLeft,
3296 out);
3297 }
Brian Osman133724c2020-10-28 14:14:39 -04003298 for (const ProgramElement* e : program.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04003299 if (e->is<Extension>()) {
3300 this->writeInstruction(SpvOpSourceExtension, e->as<Extension>().name().c_str(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003301 }
3302 }
Greg Daniel64773e62016-11-22 09:44:03 -05003303
Ethan Nicholas0df1b042017-03-31 13:56:23 -04003304 write_stringstream(fExtraGlobalsBuffer, out);
3305 write_stringstream(fNameBuffer, out);
3306 write_stringstream(fDecorationBuffer, out);
3307 write_stringstream(fConstantBuffer, out);
3308 write_stringstream(fExternalFunctionsBuffer, out);
3309 write_stringstream(body, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003310}
3311
Ethan Nicholas941e7e22016-12-12 15:33:30 -05003312bool SPIRVCodeGenerator::generateCode() {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04003313 SkASSERT(!fErrors.errorCount());
Ethan Nicholas941e7e22016-12-12 15:33:30 -05003314 this->writeWord(SpvMagicNumber, *fOut);
3315 this->writeWord(SpvVersion, *fOut);
3316 this->writeWord(SKSL_MAGIC, *fOut);
Ethan Nicholas0df1b042017-03-31 13:56:23 -04003317 StringStream buffer;
Ethan Nicholas941e7e22016-12-12 15:33:30 -05003318 this->writeInstructions(fProgram, buffer);
3319 this->writeWord(fIdCount, *fOut);
3320 this->writeWord(0, *fOut); // reserved, always zero
Ethan Nicholas0df1b042017-03-31 13:56:23 -04003321 write_stringstream(buffer, *fOut);
Ethan Nicholas941e7e22016-12-12 15:33:30 -05003322 return 0 == fErrors.errorCount();
ethannicholasb3058bd2016-07-01 08:22:01 -07003323}
3324
John Stilesa6841be2020-08-06 14:11:56 -04003325} // namespace SkSL