blob: 772baa4359606fe53df795c83a5e02eb5d6fbc8a [file] [log] [blame]
Mike Reed8520e762020-04-30 12:06:23 -04001/*
Ethan Nicholas0e9401d2019-03-21 11:05:37 -04002 * Copyright 2019 Google LLC
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
7
Mike Kleinc0bd9f92019-04-23 12:05:21 -05008#include "src/sksl/SkSLByteCodeGenerator.h"
Ethan Nicholas0e9401d2019-03-21 11:05:37 -04009
Brian Osmanb08cc022020-04-02 11:38:40 -040010#include <algorithm>
11
Ethan Nicholas0e9401d2019-03-21 11:05:37 -040012namespace SkSL {
13
Brian Osmanb08cc022020-04-02 11:38:40 -040014static TypeCategory type_category(const Type& type) {
Ethan Nicholase6592142020-09-08 10:22:09 -040015 switch (type.typeKind()) {
16 case Type::TypeKind::kVector:
17 case Type::TypeKind::kMatrix:
Brian Osmanb08cc022020-04-02 11:38:40 -040018 return type_category(type.componentType());
19 default:
20 if (type.fName == "bool") {
21 return TypeCategory::kBool;
22 } else if (type.fName == "int" ||
23 type.fName == "short" ||
24 type.fName == "$intLiteral") {
25 return TypeCategory::kSigned;
26 } else if (type.fName == "uint" ||
27 type.fName == "ushort") {
28 return TypeCategory::kUnsigned;
29 } else {
30 SkASSERT(type.fName == "float" ||
31 type.fName == "half" ||
32 type.fName == "$floatLiteral");
33 return TypeCategory::kFloat;
34 }
35 ABORT("unsupported type: %s\n", type.displayName().c_str());
36 }
37}
38
39
40ByteCodeGenerator::ByteCodeGenerator(const Context* context, const Program* program, ErrorReporter* errors,
41 ByteCode* output)
Ethan Nicholas82162ee2019-05-21 16:05:08 -040042 : INHERITED(program, errors, nullptr)
Brian Osmanb08cc022020-04-02 11:38:40 -040043 , fContext(*context)
Ethan Nicholasae9633b2019-05-24 12:46:34 -040044 , fOutput(output)
Brian Osman3479a952020-05-04 10:22:53 -040045 // If you're adding new intrinsics here, ensure that they're declared in sksl_interp.inc, so
46 // they're available to "generic" interpreter programs (eg particles).
47 // You can probably copy the declarations from sksl_gpu.inc.
Ethan Nicholasae9633b2019-05-24 12:46:34 -040048 , fIntrinsics {
Brian Osman2a4871b2020-06-19 11:29:58 -040049 { "atan", ByteCodeInstruction::kATan },
50 { "ceil", ByteCodeInstruction::kCeil },
51 { "clamp", SpecialIntrinsic::kClamp },
52 { "cos", ByteCodeInstruction::kCos },
53 { "dot", SpecialIntrinsic::kDot },
54 { "floor", ByteCodeInstruction::kFloor },
55 { "fract", ByteCodeInstruction::kFract },
56 { "inverse", ByteCodeInstruction::kInverse2x2 },
57 { "length", SpecialIntrinsic::kLength },
58 { "max", SpecialIntrinsic::kMax },
59 { "min", SpecialIntrinsic::kMin },
60 { "mix", SpecialIntrinsic::kMix },
61 { "normalize", SpecialIntrinsic::kNormalize },
62 { "pow", ByteCodeInstruction::kPow },
63 { "sample", SpecialIntrinsic::kSample },
64 { "saturate", SpecialIntrinsic::kSaturate },
65 { "sin", ByteCodeInstruction::kSin },
66 { "sqrt", ByteCodeInstruction::kSqrt },
67 { "tan", ByteCodeInstruction::kTan },
Brian Osman8842b372020-05-01 15:07:49 -040068
69 { "lessThan", { ByteCodeInstruction::kCompareFLT,
70 ByteCodeInstruction::kCompareSLT,
71 ByteCodeInstruction::kCompareULT } },
72 { "lessThanEqual", { ByteCodeInstruction::kCompareFLTEQ,
73 ByteCodeInstruction::kCompareSLTEQ,
74 ByteCodeInstruction::kCompareULTEQ } },
75 { "greaterThan", { ByteCodeInstruction::kCompareFGT,
76 ByteCodeInstruction::kCompareSGT,
77 ByteCodeInstruction::kCompareUGT } },
78 { "greaterThanEqual", { ByteCodeInstruction::kCompareFGTEQ,
79 ByteCodeInstruction::kCompareSGTEQ,
80 ByteCodeInstruction::kCompareUGTEQ } },
81 { "equal", { ByteCodeInstruction::kCompareFEQ,
82 ByteCodeInstruction::kCompareIEQ,
83 ByteCodeInstruction::kCompareIEQ } },
84 { "notEqual", { ByteCodeInstruction::kCompareFNEQ,
85 ByteCodeInstruction::kCompareINEQ,
86 ByteCodeInstruction::kCompareINEQ } },
87
88 { "any", SpecialIntrinsic::kAny },
89 { "all", SpecialIntrinsic::kAll },
90 { "not", ByteCodeInstruction::kNotB },
91 } {}
Brian Osmanb08cc022020-04-02 11:38:40 -040092
Ethan Nicholas82162ee2019-05-21 16:05:08 -040093
Brian Osman07c117b2019-05-23 12:51:06 -070094int ByteCodeGenerator::SlotCount(const Type& type) {
Ethan Nicholase6592142020-09-08 10:22:09 -040095 switch (type.typeKind()) {
96 case Type::TypeKind::kOther:
97 return 0;
98 case Type::TypeKind::kStruct: {
99 int slots = 0;
100 for (const auto& f : type.fields()) {
101 slots += SlotCount(*f.fType);
102 }
103 SkASSERT(slots <= 255);
104 return slots;
Brian Osman07c117b2019-05-23 12:51:06 -0700105 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400106 case Type::TypeKind::kArray: {
107 int columns = type.columns();
108 SkASSERT(columns >= 0);
109 int slots = columns * SlotCount(type.componentType());
110 SkASSERT(slots <= 255);
111 return slots;
112 }
113 default:
114 return type.columns() * type.rows();
Brian Osman07c117b2019-05-23 12:51:06 -0700115 }
Ethan Nicholas0e9401d2019-03-21 11:05:37 -0400116}
117
Brian Osman1c110a02019-10-01 14:53:32 -0400118static inline bool is_uniform(const SkSL::Variable& var) {
119 return var.fModifiers.fFlags & Modifiers::kUniform_Flag;
120}
121
Brian Osmaneadfeb92020-01-09 12:43:03 -0500122static inline bool is_in(const SkSL::Variable& var) {
123 return var.fModifiers.fFlags & Modifiers::kIn_Flag;
124}
Brian Osmanb08cc022020-04-02 11:38:40 -0400125
126void ByteCodeGenerator::gatherUniforms(const Type& type, const String& name) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400127 switch (type.typeKind()) {
128 case Type::TypeKind::kOther:
129 break;
130 case Type::TypeKind::kStruct:
131 for (const auto& f : type.fields()) {
132 this->gatherUniforms(*f.fType, name + "." + f.fName);
133 }
134 break;
135 case Type::TypeKind::kArray:
136 for (int i = 0; i < type.columns(); ++i) {
137 this->gatherUniforms(type.componentType(), String::printf("%s[%d]", name.c_str(),
138 i));
139 }
140 break;
141 default:
142 fOutput->fUniforms.push_back({ name, type_category(type), type.rows(), type.columns(),
143 fOutput->fUniformSlotCount });
144 fOutput->fUniformSlotCount += type.columns() * type.rows();
Brian Osmanb08cc022020-04-02 11:38:40 -0400145 }
146}
147
148bool ByteCodeGenerator::generateCode() {
149 for (const auto& e : fProgram) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400150 switch (e.kind()) {
151 case ProgramElement::Kind::kFunction: {
John Stiles3dc0da62020-08-19 17:48:31 -0400152 std::unique_ptr<ByteCodeFunction> f =
153 this->writeFunction(e.as<FunctionDefinition>());
Brian Osmanb08cc022020-04-02 11:38:40 -0400154 if (!f) {
155 return false;
156 }
157 fOutput->fFunctions.push_back(std::move(f));
John Stiles3dc0da62020-08-19 17:48:31 -0400158 fFunctions.push_back(&e.as<FunctionDefinition>());
Brian Osmanb08cc022020-04-02 11:38:40 -0400159 break;
Ethan Nicholasb962eff2020-01-23 16:49:41 -0500160 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400161 case ProgramElement::Kind::kVar: {
John Stiles3dc0da62020-08-19 17:48:31 -0400162 const VarDeclarations& decl = e.as<VarDeclarations>();
Brian Osmanb08cc022020-04-02 11:38:40 -0400163 for (const auto& v : decl.fVars) {
John Stiles3dc0da62020-08-19 17:48:31 -0400164 const Variable* declVar = v->as<VarDeclaration>().fVar;
Brian Osmana43d8202020-06-17 16:50:39 -0400165 if (declVar->fType == *fContext.fFragmentProcessor_Type) {
166 fOutput->fChildFPCount++;
167 }
Brian Osmanb08cc022020-04-02 11:38:40 -0400168 if (declVar->fModifiers.fLayout.fBuiltin >= 0 || is_in(*declVar)) {
169 continue;
170 }
171 if (is_uniform(*declVar)) {
172 this->gatherUniforms(declVar->fType, declVar->fName);
173 } else {
174 fOutput->fGlobalSlotCount += SlotCount(declVar->fType);
Ethan Nicholas0e9401d2019-03-21 11:05:37 -0400175 }
176 }
Brian Osmanb08cc022020-04-02 11:38:40 -0400177 break;
Ethan Nicholas0e9401d2019-03-21 11:05:37 -0400178 }
Brian Osmanb08cc022020-04-02 11:38:40 -0400179 default:
180 ; // ignore
Ethan Nicholas0e9401d2019-03-21 11:05:37 -0400181 }
182 }
Brian Osmanb08cc022020-04-02 11:38:40 -0400183 return 0 == fErrors.errorCount();
184}
185
186std::unique_ptr<ByteCodeFunction> ByteCodeGenerator::writeFunction(const FunctionDefinition& f) {
187 fFunction = &f;
188 std::unique_ptr<ByteCodeFunction> result(new ByteCodeFunction(&f.fDeclaration));
189 fParameterCount = result->fParameterCount;
190 fLoopCount = fMaxLoopCount = 0;
191 fConditionCount = fMaxConditionCount = 0;
192 fStackCount = fMaxStackCount = 0;
193 fCode = &result->fCode;
194
195 this->writeStatement(*f.fBody);
196 if (0 == fErrors.errorCount()) {
197 SkASSERT(fLoopCount == 0);
198 SkASSERT(fConditionCount == 0);
199 SkASSERT(fStackCount == 0);
200 }
201 this->write(ByteCodeInstruction::kReturn, 0);
Brian Osmanb08cc022020-04-02 11:38:40 -0400202
203 result->fLocalCount = fLocals.size();
204 result->fConditionCount = fMaxConditionCount;
205 result->fLoopCount = fMaxLoopCount;
206 result->fStackCount = fMaxStackCount;
207
208 const Type& returnType = f.fDeclaration.fReturnType;
209 if (returnType != *fContext.fVoid_Type) {
210 result->fReturnCount = SlotCount(returnType);
211 }
212 fLocals.clear();
213 fFunction = nullptr;
214 return result;
Ethan Nicholas0e9401d2019-03-21 11:05:37 -0400215}
216
Brian Osman5aaaeea2020-06-22 14:26:03 -0400217// If the expression is a reference to a builtin global variable, return the builtin ID.
218// Otherwise, return -1.
219static int expression_as_builtin(const Expression& e) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400220 if (e.kind() == Expression::Kind::kVariableReference) {
John Stiles403a3632020-08-20 12:11:48 -0400221 const Variable& var(e.as<VariableReference>().fVariable);
Brian Osman5aaaeea2020-06-22 14:26:03 -0400222 if (var.fStorage == Variable::kGlobal_Storage) {
223 return var.fModifiers.fLayout.fBuiltin;
224 }
225 }
226 return -1;
227}
228
Brian Osman0785db02019-05-24 14:19:11 -0400229// A "simple" Swizzle is based on a variable (or a compound variable like a struct or array), and
230// that references consecutive values, such that it can be implemented using normal load/store ops
231// with an offset. Note that all single-component swizzles (of suitable base types) are simple.
232static bool swizzle_is_simple(const Swizzle& s) {
Brian Osman5aaaeea2020-06-22 14:26:03 -0400233 // Builtin variables use dedicated instructions that don't allow subset loads
234 if (expression_as_builtin(*s.fBase) >= 0) {
235 return false;
236 }
237
Ethan Nicholase6592142020-09-08 10:22:09 -0400238 switch (s.fBase->kind()) {
239 case Expression::Kind::kFieldAccess:
240 case Expression::Kind::kIndex:
241 case Expression::Kind::kVariableReference:
Brian Osman0785db02019-05-24 14:19:11 -0400242 break;
243 default:
244 return false;
245 }
246
247 for (size_t i = 1; i < s.fComponents.size(); ++i) {
248 if (s.fComponents[i] != s.fComponents[i - 1] + 1) {
249 return false;
250 }
251 }
252 return true;
253}
254
Brian Osmanb08cc022020-04-02 11:38:40 -0400255int ByteCodeGenerator::StackUsage(ByteCodeInstruction inst, int count_) {
256 // Ensures that we use count iff we're passed a non-default value. Most instructions have an
257 // implicit count, so the caller shouldn't need to worry about it (or count makes no sense).
258 // The asserts avoids callers thinking they're supplying useful information in that scenario,
259 // or failing to supply necessary information for the ops that need a count.
260 struct CountValue {
261 operator int() {
262 SkASSERT(val != ByteCodeGenerator::kUnusedStackCount);
263 SkDEBUGCODE(used = true);
264 return val;
265 }
266 ~CountValue() {
267 SkASSERT(used || val == ByteCodeGenerator::kUnusedStackCount);
268 }
269 int val;
270 SkDEBUGCODE(bool used = false;)
271 } count = { count_ };
272
273 switch (inst) {
274 // Unary functions/operators that don't change stack depth at all:
Brian Osmanb08cc022020-04-02 11:38:40 -0400275
Brian Osman49b30f42020-06-26 17:22:27 -0400276#define VEC_UNARY(inst) case ByteCodeInstruction::inst: return count - count;
Brian Osmanb08cc022020-04-02 11:38:40 -0400277
Brian Osman49b30f42020-06-26 17:22:27 -0400278 VEC_UNARY(kConvertFtoI)
279 VEC_UNARY(kConvertStoF)
280 VEC_UNARY(kConvertUtoF)
Brian Osmanb08cc022020-04-02 11:38:40 -0400281
Brian Osman49b30f42020-06-26 17:22:27 -0400282 VEC_UNARY(kATan)
283 VEC_UNARY(kCeil)
284 VEC_UNARY(kCos)
285 VEC_UNARY(kFloor)
286 VEC_UNARY(kFract)
287 VEC_UNARY(kSin)
288 VEC_UNARY(kSqrt)
289 VEC_UNARY(kTan)
290
291 VEC_UNARY(kNegateF)
292 VEC_UNARY(kNegateI)
293 VEC_UNARY(kNotB)
294
295#undef VEC_UNARY
Brian Osmanb08cc022020-04-02 11:38:40 -0400296
297 case ByteCodeInstruction::kInverse2x2:
298 case ByteCodeInstruction::kInverse3x3:
299 case ByteCodeInstruction::kInverse4x4: return 0;
300
Brian Osman49b30f42020-06-26 17:22:27 -0400301 case ByteCodeInstruction::kClampIndex: return 0;
302 case ByteCodeInstruction::kShiftLeft: return 0;
Brian Osmanb08cc022020-04-02 11:38:40 -0400303 case ByteCodeInstruction::kShiftRightS: return 0;
304 case ByteCodeInstruction::kShiftRightU: return 0;
305
Brian Osman49b30f42020-06-26 17:22:27 -0400306 // Binary functions/operators that do a 2 -> 1 reduction, N times
307 case ByteCodeInstruction::kAndB: return -count;
308 case ByteCodeInstruction::kOrB: return -count;
309 case ByteCodeInstruction::kXorB: return -count;
Brian Osmanb08cc022020-04-02 11:38:40 -0400310
Brian Osman49b30f42020-06-26 17:22:27 -0400311 case ByteCodeInstruction::kAddI: return -count;
312 case ByteCodeInstruction::kAddF: return -count;
Brian Osmanb08cc022020-04-02 11:38:40 -0400313
Brian Osman49b30f42020-06-26 17:22:27 -0400314 case ByteCodeInstruction::kCompareIEQ: return -count;
315 case ByteCodeInstruction::kCompareFEQ: return -count;
316 case ByteCodeInstruction::kCompareINEQ: return -count;
317 case ByteCodeInstruction::kCompareFNEQ: return -count;
318 case ByteCodeInstruction::kCompareSGT: return -count;
319 case ByteCodeInstruction::kCompareUGT: return -count;
320 case ByteCodeInstruction::kCompareFGT: return -count;
321 case ByteCodeInstruction::kCompareSGTEQ: return -count;
322 case ByteCodeInstruction::kCompareUGTEQ: return -count;
323 case ByteCodeInstruction::kCompareFGTEQ: return -count;
324 case ByteCodeInstruction::kCompareSLT: return -count;
325 case ByteCodeInstruction::kCompareULT: return -count;
326 case ByteCodeInstruction::kCompareFLT: return -count;
327 case ByteCodeInstruction::kCompareSLTEQ: return -count;
328 case ByteCodeInstruction::kCompareULTEQ: return -count;
329 case ByteCodeInstruction::kCompareFLTEQ: return -count;
Brian Osmanb08cc022020-04-02 11:38:40 -0400330
Brian Osman49b30f42020-06-26 17:22:27 -0400331 case ByteCodeInstruction::kDivideS: return -count;
332 case ByteCodeInstruction::kDivideU: return -count;
333 case ByteCodeInstruction::kDivideF: return -count;
334 case ByteCodeInstruction::kMaxF: return -count;
335 case ByteCodeInstruction::kMaxS: return -count;
336 case ByteCodeInstruction::kMinF: return -count;
337 case ByteCodeInstruction::kMinS: return -count;
338 case ByteCodeInstruction::kMultiplyI: return -count;
339 case ByteCodeInstruction::kMultiplyF: return -count;
340 case ByteCodeInstruction::kPow: return -count;
341 case ByteCodeInstruction::kRemainderF: return -count;
342 case ByteCodeInstruction::kRemainderS: return -count;
343 case ByteCodeInstruction::kRemainderU: return -count;
344 case ByteCodeInstruction::kSubtractI: return -count;
345 case ByteCodeInstruction::kSubtractF: return -count;
Brian Osmanb08cc022020-04-02 11:38:40 -0400346
347 // Ops that push or load data to grow the stack:
Brian Osman49b30f42020-06-26 17:22:27 -0400348 case ByteCodeInstruction::kPushImmediate:
349 return 1;
350 case ByteCodeInstruction::kLoadFragCoord:
351 return 4;
352
Brian Osmanb08cc022020-04-02 11:38:40 -0400353 case ByteCodeInstruction::kDup:
354 case ByteCodeInstruction::kLoad:
355 case ByteCodeInstruction::kLoadGlobal:
356 case ByteCodeInstruction::kLoadUniform:
357 case ByteCodeInstruction::kReadExternal:
Brian Osman49b30f42020-06-26 17:22:27 -0400358 case ByteCodeInstruction::kReserve:
Brian Osmanb08cc022020-04-02 11:38:40 -0400359 return count;
360
361 // Pushes 'count' values, minus one for the 'address' that's consumed first
362 case ByteCodeInstruction::kLoadExtended:
363 case ByteCodeInstruction::kLoadExtendedGlobal:
364 case ByteCodeInstruction::kLoadExtendedUniform:
365 return count - 1;
366
367 // Ops that pop or store data to shrink the stack:
368 case ByteCodeInstruction::kPop:
Brian Osman49b30f42020-06-26 17:22:27 -0400369 case ByteCodeInstruction::kReturn:
Brian Osmanb08cc022020-04-02 11:38:40 -0400370 case ByteCodeInstruction::kStore:
371 case ByteCodeInstruction::kStoreGlobal:
372 case ByteCodeInstruction::kWriteExternal:
Brian Osmanb08cc022020-04-02 11:38:40 -0400373 return -count;
374
375 // Consumes 'count' values, plus one for the 'address'
376 case ByteCodeInstruction::kStoreExtended:
377 case ByteCodeInstruction::kStoreExtendedGlobal:
Brian Osmanb08cc022020-04-02 11:38:40 -0400378 return -count - 1;
379
380 // Strange ops where the caller computes the delta for us:
381 case ByteCodeInstruction::kCallExternal:
382 case ByteCodeInstruction::kMatrixToMatrix:
383 case ByteCodeInstruction::kMatrixMultiply:
Brian Osmanb08cc022020-04-02 11:38:40 -0400384 case ByteCodeInstruction::kScalarToMatrix:
385 case ByteCodeInstruction::kSwizzle:
386 return count;
387
388 // Miscellaneous
389
Brian Osman795efd22020-07-01 13:18:36 -0400390 // () -> (R, G, B, A)
391 case ByteCodeInstruction::kSample: return 4;
Brian Osmana43d8202020-06-17 16:50:39 -0400392 // (X, Y) -> (R, G, B, A)
393 case ByteCodeInstruction::kSampleExplicit: return 4 - 2;
394 // (float3x3) -> (R, G, B, A)
395 case ByteCodeInstruction::kSampleMatrix: return 4 - 9;
396
Brian Osman8842b372020-05-01 15:07:49 -0400397 // kMix does a 3 -> 1 reduction (A, B, M -> A -or- B) for each component
Brian Osman49b30f42020-06-26 17:22:27 -0400398 case ByteCodeInstruction::kMix: return -(2 * count);
Brian Osman8842b372020-05-01 15:07:49 -0400399
400 // kLerp works the same way (producing lerp(A, B, T) for each component)
Brian Osman49b30f42020-06-26 17:22:27 -0400401 case ByteCodeInstruction::kLerp: return -(2 * count);
Brian Osman8842b372020-05-01 15:07:49 -0400402
Brian Osmanb08cc022020-04-02 11:38:40 -0400403 // kCall is net-zero. Max stack depth is adjusted in writeFunctionCall.
404 case ByteCodeInstruction::kCall: return 0;
405 case ByteCodeInstruction::kBranch: return 0;
406 case ByteCodeInstruction::kBranchIfAllFalse: return 0;
407
408 case ByteCodeInstruction::kMaskPush: return -1;
409 case ByteCodeInstruction::kMaskPop: return 0;
410 case ByteCodeInstruction::kMaskNegate: return 0;
411 case ByteCodeInstruction::kMaskBlend: return -count;
412
413 case ByteCodeInstruction::kLoopBegin: return 0;
414 case ByteCodeInstruction::kLoopNext: return 0;
415 case ByteCodeInstruction::kLoopMask: return -1;
416 case ByteCodeInstruction::kLoopEnd: return 0;
417 case ByteCodeInstruction::kLoopBreak: return 0;
418 case ByteCodeInstruction::kLoopContinue: return 0;
Brian Osmanb08cc022020-04-02 11:38:40 -0400419 }
Brian Osmand5f937b2020-05-04 12:07:29 -0400420
421 SkUNREACHABLE;
Brian Osmanb08cc022020-04-02 11:38:40 -0400422}
423
424ByteCodeGenerator::Location ByteCodeGenerator::getLocation(const Variable& var) {
425 // given that we seldom have more than a couple of variables, linear search is probably the most
426 // efficient way to handle lookups
427 switch (var.fStorage) {
428 case Variable::kLocal_Storage: {
429 for (int i = fLocals.size() - 1; i >= 0; --i) {
430 if (fLocals[i] == &var) {
431 SkASSERT(fParameterCount + i <= 255);
432 return { fParameterCount + i, Storage::kLocal };
433 }
434 }
435 int result = fParameterCount + fLocals.size();
436 fLocals.push_back(&var);
437 for (int i = 0; i < SlotCount(var.fType) - 1; ++i) {
438 fLocals.push_back(nullptr);
439 }
440 SkASSERT(result <= 255);
441 return { result, Storage::kLocal };
442 }
443 case Variable::kParameter_Storage: {
444 int offset = 0;
445 for (const auto& p : fFunction->fDeclaration.fParameters) {
446 if (p == &var) {
447 SkASSERT(offset <= 255);
448 return { offset, Storage::kLocal };
449 }
450 offset += SlotCount(p->fType);
451 }
452 SkASSERT(false);
453 return Location::MakeInvalid();
454 }
455 case Variable::kGlobal_Storage: {
Brian Osmana43d8202020-06-17 16:50:39 -0400456 if (var.fType == *fContext.fFragmentProcessor_Type) {
457 int offset = 0;
458 for (const auto& e : fProgram) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400459 if (e.kind() == ProgramElement::Kind::kVar) {
John Stiles403a3632020-08-20 12:11:48 -0400460 const VarDeclarations& decl = e.as<VarDeclarations>();
Brian Osmana43d8202020-06-17 16:50:39 -0400461 for (const auto& v : decl.fVars) {
John Stiles403a3632020-08-20 12:11:48 -0400462 const Variable* declVar = v->as<VarDeclaration>().fVar;
Brian Osmana43d8202020-06-17 16:50:39 -0400463 if (declVar->fType != *fContext.fFragmentProcessor_Type) {
464 continue;
465 }
466 if (declVar == &var) {
467 SkASSERT(offset <= 255);
468 return { offset, Storage::kChildFP };
469 }
470 offset++;
471 }
472 }
473 }
474 SkASSERT(false);
475 return Location::MakeInvalid();
476 }
Brian Osmanb08cc022020-04-02 11:38:40 -0400477 if (is_in(var)) {
478 // If you see this error, it means the program is using raw 'in' variables. You
479 // should either specialize the program (Compiler::specialize) to bake in the final
480 // values of the 'in' variables, or not use 'in' variables (maybe you meant to use
481 // 'uniform' instead?).
482 fErrors.error(var.fOffset,
483 "'in' variable is not specialized or has unsupported type");
484 return Location::MakeInvalid();
485 }
486 int offset = 0;
487 bool isUniform = is_uniform(var);
488 for (const auto& e : fProgram) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400489 if (e.kind() == ProgramElement::Kind::kVar) {
John Stiles403a3632020-08-20 12:11:48 -0400490 const VarDeclarations& decl = e.as<VarDeclarations>();
Brian Osmanb08cc022020-04-02 11:38:40 -0400491 for (const auto& v : decl.fVars) {
John Stiles403a3632020-08-20 12:11:48 -0400492 const Variable* declVar = v->as<VarDeclaration>().fVar;
Brian Osmanb08cc022020-04-02 11:38:40 -0400493 if (declVar->fModifiers.fLayout.fBuiltin >= 0 || is_in(*declVar)) {
494 continue;
495 }
496 if (isUniform != is_uniform(*declVar)) {
497 continue;
498 }
499 if (declVar == &var) {
500 SkASSERT(offset <= 255);
501 return { offset, isUniform ? Storage::kUniform : Storage::kGlobal };
502 }
503 offset += SlotCount(declVar->fType);
504 }
505 }
506 }
507 SkASSERT(false);
508 return Location::MakeInvalid();
509 }
510 default:
511 SkASSERT(false);
512 return Location::MakeInvalid();
513 }
514}
515
Brian Osman1c110a02019-10-01 14:53:32 -0400516ByteCodeGenerator::Location ByteCodeGenerator::getLocation(const Expression& expr) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400517 switch (expr.kind()) {
518 case Expression::Kind::kFieldAccess: {
John Stiles403a3632020-08-20 12:11:48 -0400519 const FieldAccess& f = expr.as<FieldAccess>();
Brian Osmanb08cc022020-04-02 11:38:40 -0400520 Location baseLoc = this->getLocation(*f.fBase);
Brian Osman07c117b2019-05-23 12:51:06 -0700521 int offset = 0;
522 for (int i = 0; i < f.fFieldIndex; ++i) {
523 offset += SlotCount(*f.fBase->fType.fields()[i].fType);
524 }
Brian Osmanb08cc022020-04-02 11:38:40 -0400525 if (baseLoc.isOnStack()) {
526 if (offset != 0) {
527 this->write(ByteCodeInstruction::kPushImmediate);
528 this->write32(offset);
Brian Osman49b30f42020-06-26 17:22:27 -0400529 this->write(ByteCodeInstruction::kAddI, 1);
Ben Wagner470e0ac2020-01-22 16:59:21 -0500530 }
Brian Osmanb08cc022020-04-02 11:38:40 -0400531 return baseLoc;
Ben Wagner470e0ac2020-01-22 16:59:21 -0500532 } else {
Brian Osmanb08cc022020-04-02 11:38:40 -0400533 return baseLoc + offset;
Ben Wagner470e0ac2020-01-22 16:59:21 -0500534 }
Ben Wagner470e0ac2020-01-22 16:59:21 -0500535 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400536 case Expression::Kind::kIndex: {
John Stiles403a3632020-08-20 12:11:48 -0400537 const IndexExpression& i = expr.as<IndexExpression>();
Brian Osmanb08cc022020-04-02 11:38:40 -0400538 int stride = SlotCount(i.fType);
539 int length = i.fBase->fType.columns();
540 SkASSERT(length <= 255);
541 int offset = -1;
Brian Osmanb6b95732020-06-30 11:44:27 -0400542 if (i.fIndex->isCompileTimeConstant()) {
Brian Osmanb08cc022020-04-02 11:38:40 -0400543 int64_t index = i.fIndex->getConstantInt();
544 if (index < 0 || index >= length) {
545 fErrors.error(i.fIndex->fOffset, "Array index out of bounds.");
546 return Location::MakeInvalid();
547 }
548 offset = index * stride;
549 } else {
550 if (i.fIndex->hasSideEffects()) {
551 // Having a side-effect in an indexer is technically safe for an rvalue,
552 // but with lvalues we have to evaluate the indexer twice, so make it an error.
553 fErrors.error(i.fIndex->fOffset,
554 "Index expressions with side-effects not supported in byte code.");
555 return Location::MakeInvalid();
556 }
557 this->writeExpression(*i.fIndex);
558 this->write(ByteCodeInstruction::kClampIndex);
559 this->write8(length);
560 if (stride != 1) {
561 this->write(ByteCodeInstruction::kPushImmediate);
562 this->write32(stride);
Brian Osman49b30f42020-06-26 17:22:27 -0400563 this->write(ByteCodeInstruction::kMultiplyI, 1);
Brian Osmanb08cc022020-04-02 11:38:40 -0400564 }
565 }
566 Location baseLoc = this->getLocation(*i.fBase);
567
568 // Are both components known statically?
569 if (!baseLoc.isOnStack() && offset >= 0) {
570 return baseLoc + offset;
571 }
572
573 // At least one component is dynamic (and on the stack).
574
575 // If the other component is zero, we're done
576 if (baseLoc.fSlot == 0 || offset == 0) {
577 return baseLoc.makeOnStack();
578 }
579
580 // Push the non-dynamic component (if any) to the stack, then add the two
581 if (!baseLoc.isOnStack()) {
582 this->write(ByteCodeInstruction::kPushImmediate);
583 this->write32(baseLoc.fSlot);
584 }
585 if (offset >= 0) {
586 this->write(ByteCodeInstruction::kPushImmediate);
587 this->write32(offset);
588 }
Brian Osman49b30f42020-06-26 17:22:27 -0400589 this->write(ByteCodeInstruction::kAddI, 1);
Brian Osmanb08cc022020-04-02 11:38:40 -0400590 return baseLoc.makeOnStack();
591 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400592 case Expression::Kind::kSwizzle: {
John Stiles403a3632020-08-20 12:11:48 -0400593 const Swizzle& s = expr.as<Swizzle>();
Brian Osman0785db02019-05-24 14:19:11 -0400594 SkASSERT(swizzle_is_simple(s));
Brian Osmanb08cc022020-04-02 11:38:40 -0400595 Location baseLoc = this->getLocation(*s.fBase);
596 int offset = s.fComponents[0];
597 if (baseLoc.isOnStack()) {
598 if (offset != 0) {
599 this->write(ByteCodeInstruction::kPushImmediate);
600 this->write32(offset);
Brian Osman49b30f42020-06-26 17:22:27 -0400601 this->write(ByteCodeInstruction::kAddI, 1);
Brian Osmanb08cc022020-04-02 11:38:40 -0400602 }
603 return baseLoc;
604 } else {
605 return baseLoc + offset;
606 }
Brian Osman0785db02019-05-24 14:19:11 -0400607 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400608 case Expression::Kind::kVariableReference: {
John Stiles403a3632020-08-20 12:11:48 -0400609 const Variable& var = expr.as<VariableReference>().fVariable;
Brian Osman07c117b2019-05-23 12:51:06 -0700610 return this->getLocation(var);
611 }
612 default:
613 SkASSERT(false);
Brian Osmanb08cc022020-04-02 11:38:40 -0400614 return Location::MakeInvalid();
Brian Osman07c117b2019-05-23 12:51:06 -0700615 }
616}
617
Brian Osmanb08cc022020-04-02 11:38:40 -0400618void ByteCodeGenerator::write8(uint8_t b) {
619 fCode->push_back(b);
Ethan Nicholas2cde3a12020-01-21 09:23:13 -0500620}
621
Brian Osmanb08cc022020-04-02 11:38:40 -0400622void ByteCodeGenerator::write16(uint16_t i) {
623 size_t n = fCode->size();
624 fCode->resize(n+2);
625 memcpy(fCode->data() + n, &i, 2);
Ethan Nicholasb962eff2020-01-23 16:49:41 -0500626}
Ben Wagner470e0ac2020-01-22 16:59:21 -0500627
Brian Osmanb08cc022020-04-02 11:38:40 -0400628void ByteCodeGenerator::write32(uint32_t i) {
629 size_t n = fCode->size();
630 fCode->resize(n+4);
631 memcpy(fCode->data() + n, &i, 4);
Ethan Nicholasb962eff2020-01-23 16:49:41 -0500632}
633
Brian Osmanb08cc022020-04-02 11:38:40 -0400634void ByteCodeGenerator::write(ByteCodeInstruction i, int count) {
635 switch (i) {
636 case ByteCodeInstruction::kLoopBegin: this->enterLoop(); break;
637 case ByteCodeInstruction::kLoopEnd: this->exitLoop(); break;
Ethan Nicholas2329da02020-01-24 15:49:33 -0500638
Brian Osmanb08cc022020-04-02 11:38:40 -0400639 case ByteCodeInstruction::kMaskPush: this->enterCondition(); break;
640 case ByteCodeInstruction::kMaskPop:
641 case ByteCodeInstruction::kMaskBlend: this->exitCondition(); break;
642 default: /* Do nothing */ break;
Ben Wagner470e0ac2020-01-22 16:59:21 -0500643 }
Mike Klein01d01612020-08-14 10:52:11 -0500644 this->write8((uint8_t)i);
Brian Osmanb08cc022020-04-02 11:38:40 -0400645 fStackCount += StackUsage(i, count);
646 fMaxStackCount = std::max(fMaxStackCount, fStackCount);
Brian Osman49b30f42020-06-26 17:22:27 -0400647
648 // Most ops have an explicit count byte after them (passed here as 'count')
649 // Ops that don't have a count byte pass the default (kUnusedStackCount)
650 // There are a handful of strange ops that pass in a computed stack delta as count, but where
651 // that value should *not* be written as a count byte (it may even be negative!)
652 if (count != kUnusedStackCount) {
653 switch (i) {
654 // Odd instructions that have a non-default count, but we shouldn't write it
655 case ByteCodeInstruction::kCallExternal:
656 case ByteCodeInstruction::kMatrixToMatrix:
657 case ByteCodeInstruction::kMatrixMultiply:
658 case ByteCodeInstruction::kScalarToMatrix:
659 case ByteCodeInstruction::kSwizzle:
660 break;
661 default:
662 this->write8(count);
663 break;
664 }
665 }
Ethan Nicholasb962eff2020-01-23 16:49:41 -0500666}
667
Brian Osman49b30f42020-06-26 17:22:27 -0400668void ByteCodeGenerator::writeTypedInstruction(const Type& type,
669 ByteCodeInstruction s,
670 ByteCodeInstruction u,
671 ByteCodeInstruction f,
Brian Osmanab8f3842020-04-07 09:30:44 -0400672 int count) {
Ethan Nicholasb962eff2020-01-23 16:49:41 -0500673 switch (type_category(type)) {
Brian Osman8842b372020-05-01 15:07:49 -0400674 case TypeCategory::kBool:
Brian Osman49b30f42020-06-26 17:22:27 -0400675 case TypeCategory::kSigned: this->write(s, count); break;
676 case TypeCategory::kUnsigned: this->write(u, count); break;
677 case TypeCategory::kFloat: this->write(f, count); break;
Ethan Nicholasb962eff2020-01-23 16:49:41 -0500678 default:
679 SkASSERT(false);
680 }
Ethan Nicholasb962eff2020-01-23 16:49:41 -0500681}
682
Brian Osmanb08cc022020-04-02 11:38:40 -0400683bool ByteCodeGenerator::writeBinaryExpression(const BinaryExpression& b, bool discard) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400684 if (b.fOperator == Token::Kind::TK_EQ) {
Ethan Nicholasb962eff2020-01-23 16:49:41 -0500685 std::unique_ptr<LValue> lvalue = this->getLValue(*b.fLeft);
Brian Osmanb08cc022020-04-02 11:38:40 -0400686 this->writeExpression(*b.fRight);
687 lvalue->store(discard);
688 discard = false;
689 return discard;
Ethan Nicholasb962eff2020-01-23 16:49:41 -0500690 }
691 const Type& lType = b.fLeft->fType;
692 const Type& rType = b.fRight->fType;
Ethan Nicholase6592142020-09-08 10:22:09 -0400693 bool lVecOrMtx = (lType.typeKind() == Type::TypeKind::kVector ||
694 lType.typeKind() == Type::TypeKind::kMatrix);
695 bool rVecOrMtx = (rType.typeKind() == Type::TypeKind::kVector ||
696 rType.typeKind() == Type::TypeKind::kMatrix);
Ethan Nicholasb962eff2020-01-23 16:49:41 -0500697 Token::Kind op;
698 std::unique_ptr<LValue> lvalue;
Ethan Nicholasb962eff2020-01-23 16:49:41 -0500699 if (is_assignment(b.fOperator)) {
700 lvalue = this->getLValue(*b.fLeft);
Brian Osmanb08cc022020-04-02 11:38:40 -0400701 lvalue->load();
Ethan Nicholasb962eff2020-01-23 16:49:41 -0500702 op = remove_assignment(b.fOperator);
703 } else {
Brian Osmanb08cc022020-04-02 11:38:40 -0400704 this->writeExpression(*b.fLeft);
Ethan Nicholasb962eff2020-01-23 16:49:41 -0500705 op = b.fOperator;
706 if (!lVecOrMtx && rVecOrMtx) {
Brian Osmanb08cc022020-04-02 11:38:40 -0400707 for (int i = SlotCount(rType); i > 1; --i) {
Brian Osman49b30f42020-06-26 17:22:27 -0400708 this->write(ByteCodeInstruction::kDup, 1);
Brian Osmanb08cc022020-04-02 11:38:40 -0400709 }
Ethan Nicholasb962eff2020-01-23 16:49:41 -0500710 }
711 }
Ethan Nicholasb962eff2020-01-23 16:49:41 -0500712 int count = std::max(SlotCount(lType), SlotCount(rType));
Brian Osmanb08cc022020-04-02 11:38:40 -0400713 SkDEBUGCODE(TypeCategory tc = type_category(lType));
Ethan Nicholasb962eff2020-01-23 16:49:41 -0500714 switch (op) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400715 case Token::Kind::TK_LOGICALAND: {
Brian Osmanb08cc022020-04-02 11:38:40 -0400716 SkASSERT(tc == SkSL::TypeCategory::kBool && count == 1);
Brian Osman49b30f42020-06-26 17:22:27 -0400717 this->write(ByteCodeInstruction::kDup, 1);
Brian Osmanb08cc022020-04-02 11:38:40 -0400718 this->write(ByteCodeInstruction::kMaskPush);
719 this->write(ByteCodeInstruction::kBranchIfAllFalse);
Ethan Nicholasb962eff2020-01-23 16:49:41 -0500720 DeferredLocation falseLocation(this);
Brian Osmanb08cc022020-04-02 11:38:40 -0400721 this->writeExpression(*b.fRight);
Brian Osman49b30f42020-06-26 17:22:27 -0400722 this->write(ByteCodeInstruction::kAndB, 1);
Ethan Nicholasb962eff2020-01-23 16:49:41 -0500723 falseLocation.set();
Brian Osmanb08cc022020-04-02 11:38:40 -0400724 this->write(ByteCodeInstruction::kMaskPop);
725 return false;
Ethan Nicholasb962eff2020-01-23 16:49:41 -0500726 }
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400727 case Token::Kind::TK_LOGICALOR: {
Brian Osmanb08cc022020-04-02 11:38:40 -0400728 SkASSERT(tc == SkSL::TypeCategory::kBool && count == 1);
Brian Osman49b30f42020-06-26 17:22:27 -0400729 this->write(ByteCodeInstruction::kDup, 1);
730 this->write(ByteCodeInstruction::kNotB, 1);
Brian Osmanb08cc022020-04-02 11:38:40 -0400731 this->write(ByteCodeInstruction::kMaskPush);
732 this->write(ByteCodeInstruction::kBranchIfAllFalse);
Ethan Nicholasb962eff2020-01-23 16:49:41 -0500733 DeferredLocation falseLocation(this);
Brian Osmanb08cc022020-04-02 11:38:40 -0400734 this->writeExpression(*b.fRight);
Brian Osman49b30f42020-06-26 17:22:27 -0400735 this->write(ByteCodeInstruction::kOrB, 1);
Ethan Nicholasb962eff2020-01-23 16:49:41 -0500736 falseLocation.set();
Brian Osmanb08cc022020-04-02 11:38:40 -0400737 this->write(ByteCodeInstruction::kMaskPop);
738 return false;
Ethan Nicholasb962eff2020-01-23 16:49:41 -0500739 }
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400740 case Token::Kind::TK_SHL:
741 case Token::Kind::TK_SHR: {
Ethan Nicholasb962eff2020-01-23 16:49:41 -0500742 SkASSERT(count == 1 && (tc == SkSL::TypeCategory::kSigned ||
743 tc == SkSL::TypeCategory::kUnsigned));
Brian Osmanb6b95732020-06-30 11:44:27 -0400744 if (!b.fRight->isCompileTimeConstant()) {
Ethan Nicholasb962eff2020-01-23 16:49:41 -0500745 fErrors.error(b.fRight->fOffset, "Shift amounts must be constant");
Brian Osmanb08cc022020-04-02 11:38:40 -0400746 return false;
Ethan Nicholasb962eff2020-01-23 16:49:41 -0500747 }
748 int64_t shift = b.fRight->getConstantInt();
749 if (shift < 0 || shift > 31) {
750 fErrors.error(b.fRight->fOffset, "Shift amount out of range");
Brian Osmanb08cc022020-04-02 11:38:40 -0400751 return false;
Ethan Nicholasb962eff2020-01-23 16:49:41 -0500752 }
753
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400754 if (op == Token::Kind::TK_SHL) {
Brian Osmanb08cc022020-04-02 11:38:40 -0400755 this->write(ByteCodeInstruction::kShiftLeft);
Ethan Nicholasb962eff2020-01-23 16:49:41 -0500756 } else {
757 this->write(type_category(lType) == TypeCategory::kSigned
Brian Osmanb08cc022020-04-02 11:38:40 -0400758 ? ByteCodeInstruction::kShiftRightS
759 : ByteCodeInstruction::kShiftRightU);
Ethan Nicholasb962eff2020-01-23 16:49:41 -0500760 }
Brian Osmanb08cc022020-04-02 11:38:40 -0400761 this->write8(shift);
762 return false;
Ethan Nicholasb962eff2020-01-23 16:49:41 -0500763 }
Ethan Nicholasb962eff2020-01-23 16:49:41 -0500764
765 default:
766 break;
767 }
Brian Osmanb08cc022020-04-02 11:38:40 -0400768 this->writeExpression(*b.fRight);
Ethan Nicholasb962eff2020-01-23 16:49:41 -0500769 if (lVecOrMtx && !rVecOrMtx) {
Brian Osmanb08cc022020-04-02 11:38:40 -0400770 for (int i = SlotCount(lType); i > 1; --i) {
Brian Osman49b30f42020-06-26 17:22:27 -0400771 this->write(ByteCodeInstruction::kDup, 1);
Brian Osmanb08cc022020-04-02 11:38:40 -0400772 }
Ethan Nicholasb962eff2020-01-23 16:49:41 -0500773 }
Brian Osmanb08cc022020-04-02 11:38:40 -0400774 // Special case for M*V, V*M, M*M (but not V*V!)
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400775 if (op == Token::Kind::TK_STAR && lVecOrMtx && rVecOrMtx &&
Ethan Nicholase6592142020-09-08 10:22:09 -0400776 !(lType.typeKind() == Type::TypeKind::kVector &&
777 rType.typeKind() == Type::TypeKind::kVector)) {
Brian Osmanb08cc022020-04-02 11:38:40 -0400778 this->write(ByteCodeInstruction::kMatrixMultiply,
779 SlotCount(b.fType) - (SlotCount(lType) + SlotCount(rType)));
780 int rCols = rType.columns(),
781 rRows = rType.rows(),
782 lCols = lType.columns(),
783 lRows = lType.rows();
784 // M*V treats the vector as a column
Ethan Nicholase6592142020-09-08 10:22:09 -0400785 if (rType.typeKind() == Type::TypeKind::kVector) {
Brian Osmanb08cc022020-04-02 11:38:40 -0400786 std::swap(rCols, rRows);
Ethan Nicholasb962eff2020-01-23 16:49:41 -0500787 }
Brian Osmanb08cc022020-04-02 11:38:40 -0400788 SkASSERT(lCols == rRows);
789 SkASSERT(SlotCount(b.fType) == lRows * rCols);
790 this->write8(lCols);
791 this->write8(lRows);
792 this->write8(rCols);
793 } else {
794 switch (op) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400795 case Token::Kind::TK_EQEQ:
Brian Osmanb08cc022020-04-02 11:38:40 -0400796 this->writeTypedInstruction(lType, ByteCodeInstruction::kCompareIEQ,
797 ByteCodeInstruction::kCompareIEQ,
798 ByteCodeInstruction::kCompareFEQ,
799 count);
800 // Collapse to a single bool
801 for (int i = count; i > 1; --i) {
Brian Osman49b30f42020-06-26 17:22:27 -0400802 this->write(ByteCodeInstruction::kAndB, 1);
Brian Osmanb08cc022020-04-02 11:38:40 -0400803 }
804 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400805 case Token::Kind::TK_GT:
Brian Osmanb08cc022020-04-02 11:38:40 -0400806 this->writeTypedInstruction(lType, ByteCodeInstruction::kCompareSGT,
807 ByteCodeInstruction::kCompareUGT,
808 ByteCodeInstruction::kCompareFGT,
809 count);
810 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400811 case Token::Kind::TK_GTEQ:
Brian Osmanb08cc022020-04-02 11:38:40 -0400812 this->writeTypedInstruction(lType, ByteCodeInstruction::kCompareSGTEQ,
813 ByteCodeInstruction::kCompareUGTEQ,
814 ByteCodeInstruction::kCompareFGTEQ,
815 count);
816 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400817 case Token::Kind::TK_LT:
Brian Osmanb08cc022020-04-02 11:38:40 -0400818 this->writeTypedInstruction(lType, ByteCodeInstruction::kCompareSLT,
819 ByteCodeInstruction::kCompareULT,
820 ByteCodeInstruction::kCompareFLT,
821 count);
822 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400823 case Token::Kind::TK_LTEQ:
Brian Osmanb08cc022020-04-02 11:38:40 -0400824 this->writeTypedInstruction(lType, ByteCodeInstruction::kCompareSLTEQ,
825 ByteCodeInstruction::kCompareULTEQ,
826 ByteCodeInstruction::kCompareFLTEQ,
827 count);
828 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400829 case Token::Kind::TK_MINUS:
Brian Osmanb08cc022020-04-02 11:38:40 -0400830 this->writeTypedInstruction(lType, ByteCodeInstruction::kSubtractI,
831 ByteCodeInstruction::kSubtractI,
832 ByteCodeInstruction::kSubtractF,
833 count);
834 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400835 case Token::Kind::TK_NEQ:
Brian Osmanb08cc022020-04-02 11:38:40 -0400836 this->writeTypedInstruction(lType, ByteCodeInstruction::kCompareINEQ,
837 ByteCodeInstruction::kCompareINEQ,
838 ByteCodeInstruction::kCompareFNEQ,
839 count);
840 // Collapse to a single bool
841 for (int i = count; i > 1; --i) {
Brian Osman49b30f42020-06-26 17:22:27 -0400842 this->write(ByteCodeInstruction::kOrB, 1);
Brian Osmanb08cc022020-04-02 11:38:40 -0400843 }
844 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400845 case Token::Kind::TK_PERCENT:
Brian Osmanb08cc022020-04-02 11:38:40 -0400846 this->writeTypedInstruction(lType, ByteCodeInstruction::kRemainderS,
847 ByteCodeInstruction::kRemainderU,
848 ByteCodeInstruction::kRemainderF,
849 count);
850 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400851 case Token::Kind::TK_PLUS:
Brian Osmanb08cc022020-04-02 11:38:40 -0400852 this->writeTypedInstruction(lType, ByteCodeInstruction::kAddI,
853 ByteCodeInstruction::kAddI,
854 ByteCodeInstruction::kAddF,
855 count);
856 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400857 case Token::Kind::TK_SLASH:
Brian Osmanb08cc022020-04-02 11:38:40 -0400858 this->writeTypedInstruction(lType, ByteCodeInstruction::kDivideS,
859 ByteCodeInstruction::kDivideU,
860 ByteCodeInstruction::kDivideF,
861 count);
862 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400863 case Token::Kind::TK_STAR:
Brian Osmanb08cc022020-04-02 11:38:40 -0400864 this->writeTypedInstruction(lType, ByteCodeInstruction::kMultiplyI,
865 ByteCodeInstruction::kMultiplyI,
866 ByteCodeInstruction::kMultiplyF,
867 count);
868 break;
869
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400870 case Token::Kind::TK_LOGICALXOR:
Brian Osman49b30f42020-06-26 17:22:27 -0400871 SkASSERT(tc == SkSL::TypeCategory::kBool);
872 this->write(ByteCodeInstruction::kXorB, count);
Brian Osmanb08cc022020-04-02 11:38:40 -0400873 break;
874
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400875 case Token::Kind::TK_BITWISEAND:
Brian Osman49b30f42020-06-26 17:22:27 -0400876 SkASSERT(tc == SkSL::TypeCategory::kSigned || tc == SkSL::TypeCategory::kUnsigned);
877 this->write(ByteCodeInstruction::kAndB, count);
Brian Osmanb08cc022020-04-02 11:38:40 -0400878 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400879 case Token::Kind::TK_BITWISEOR:
Brian Osman49b30f42020-06-26 17:22:27 -0400880 SkASSERT(tc == SkSL::TypeCategory::kSigned || tc == SkSL::TypeCategory::kUnsigned);
881 this->write(ByteCodeInstruction::kOrB, count);
Brian Osmanb08cc022020-04-02 11:38:40 -0400882 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400883 case Token::Kind::TK_BITWISEXOR:
Brian Osman49b30f42020-06-26 17:22:27 -0400884 SkASSERT(tc == SkSL::TypeCategory::kSigned || tc == SkSL::TypeCategory::kUnsigned);
885 this->write(ByteCodeInstruction::kXorB, count);
Brian Osmanb08cc022020-04-02 11:38:40 -0400886 break;
887
888 default:
889 fErrors.error(b.fOffset, SkSL::String::printf("Unsupported binary operator '%s'",
890 Compiler::OperatorName(op)));
891 break;
Ethan Nicholasb962eff2020-01-23 16:49:41 -0500892 }
Ethan Nicholasb962eff2020-01-23 16:49:41 -0500893 }
894 if (lvalue) {
Brian Osmanb08cc022020-04-02 11:38:40 -0400895 lvalue->store(discard);
896 discard = false;
Ethan Nicholasb962eff2020-01-23 16:49:41 -0500897 }
Brian Osmanb08cc022020-04-02 11:38:40 -0400898 return discard;
Ethan Nicholasb962eff2020-01-23 16:49:41 -0500899}
900
Brian Osmanb08cc022020-04-02 11:38:40 -0400901void ByteCodeGenerator::writeBoolLiteral(const BoolLiteral& b) {
902 this->write(ByteCodeInstruction::kPushImmediate);
903 this->write32(b.fValue ? ~0 : 0);
904}
905
906void ByteCodeGenerator::writeConstructor(const Constructor& c) {
907 for (const auto& arg : c.fArguments) {
908 this->writeExpression(*arg);
909 }
910 if (c.fArguments.size() == 1) {
911 const Type& inType = c.fArguments[0]->fType;
912 const Type& outType = c.fType;
913 TypeCategory inCategory = type_category(inType);
914 TypeCategory outCategory = type_category(outType);
915 int inCount = SlotCount(inType);
916 int outCount = SlotCount(outType);
917 if (inCategory != outCategory) {
918 SkASSERT(inCount == outCount);
919 if (inCategory == TypeCategory::kFloat) {
920 SkASSERT(outCategory == TypeCategory::kSigned ||
921 outCategory == TypeCategory::kUnsigned);
Brian Osman49b30f42020-06-26 17:22:27 -0400922 this->write(ByteCodeInstruction::kConvertFtoI, outCount);
Brian Osmanb08cc022020-04-02 11:38:40 -0400923 } else if (outCategory == TypeCategory::kFloat) {
924 if (inCategory == TypeCategory::kSigned) {
Brian Osman49b30f42020-06-26 17:22:27 -0400925 this->write(ByteCodeInstruction::kConvertStoF, outCount);
Brian Osmanb08cc022020-04-02 11:38:40 -0400926 } else {
927 SkASSERT(inCategory == TypeCategory::kUnsigned);
Brian Osman49b30f42020-06-26 17:22:27 -0400928 this->write(ByteCodeInstruction::kConvertUtoF, outCount);
Brian Osmanb08cc022020-04-02 11:38:40 -0400929 }
930 } else {
931 SkASSERT(false);
Ethan Nicholasb962eff2020-01-23 16:49:41 -0500932 }
933 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400934 if (inType.typeKind() == Type::TypeKind::kMatrix &&
935 outType.typeKind() == Type::TypeKind::kMatrix) {
Brian Osmanb08cc022020-04-02 11:38:40 -0400936 this->write(ByteCodeInstruction::kMatrixToMatrix,
937 SlotCount(outType) - SlotCount(inType));
938 this->write8(inType.columns());
939 this->write8(inType.rows());
940 this->write8(outType.columns());
941 this->write8(outType.rows());
942 } else if (inCount != outCount) {
943 SkASSERT(inCount == 1);
Ethan Nicholase6592142020-09-08 10:22:09 -0400944 if (outType.typeKind() == Type::TypeKind::kMatrix) {
Brian Osmanb08cc022020-04-02 11:38:40 -0400945 this->write(ByteCodeInstruction::kScalarToMatrix, SlotCount(outType) - 1);
946 this->write8(outType.columns());
947 this->write8(outType.rows());
Ethan Nicholasb962eff2020-01-23 16:49:41 -0500948 } else {
Ethan Nicholase6592142020-09-08 10:22:09 -0400949 SkASSERT(outType.typeKind() == Type::TypeKind::kVector);
Brian Osmanb08cc022020-04-02 11:38:40 -0400950 for (; inCount != outCount; ++inCount) {
Brian Osman49b30f42020-06-26 17:22:27 -0400951 this->write(ByteCodeInstruction::kDup, 1);
Brian Osmanb08cc022020-04-02 11:38:40 -0400952 }
Ethan Nicholasb962eff2020-01-23 16:49:41 -0500953 }
954 }
955 }
956}
957
Brian Osmanb08cc022020-04-02 11:38:40 -0400958void ByteCodeGenerator::writeExternalFunctionCall(const ExternalFunctionCall& f) {
Ethan Nicholasb962eff2020-01-23 16:49:41 -0500959 int argumentCount = 0;
960 for (const auto& arg : f.fArguments) {
Brian Osmanb08cc022020-04-02 11:38:40 -0400961 this->writeExpression(*arg);
Ethan Nicholasb962eff2020-01-23 16:49:41 -0500962 argumentCount += SlotCount(arg->fType);
963 }
Brian Osmanb08cc022020-04-02 11:38:40 -0400964 this->write(ByteCodeInstruction::kCallExternal, SlotCount(f.fType) - argumentCount);
965 SkASSERT(argumentCount <= 255);
966 this->write8(argumentCount);
967 this->write8(SlotCount(f.fType));
Ethan Nicholasb962eff2020-01-23 16:49:41 -0500968 int index = fOutput->fExternalValues.size();
969 fOutput->fExternalValues.push_back(f.fFunction);
970 SkASSERT(index <= 255);
Brian Osmanb08cc022020-04-02 11:38:40 -0400971 this->write8(index);
Ethan Nicholasb962eff2020-01-23 16:49:41 -0500972}
973
Brian Osmanb08cc022020-04-02 11:38:40 -0400974void ByteCodeGenerator::writeExternalValue(const ExternalValueReference& e) {
975 int count = SlotCount(e.fValue->type());
Brian Osman49b30f42020-06-26 17:22:27 -0400976 this->write(ByteCodeInstruction::kReadExternal, count);
Ethan Nicholasb962eff2020-01-23 16:49:41 -0500977 int index = fOutput->fExternalValues.size();
978 fOutput->fExternalValues.push_back(e.fValue);
979 SkASSERT(index <= 255);
Brian Osmanb08cc022020-04-02 11:38:40 -0400980 this->write8(index);
Ethan Nicholasb962eff2020-01-23 16:49:41 -0500981}
982
Brian Osmanb08cc022020-04-02 11:38:40 -0400983void ByteCodeGenerator::writeVariableExpression(const Expression& expr) {
Brian Osman5aaaeea2020-06-22 14:26:03 -0400984 if (int builtin = expression_as_builtin(expr); builtin >= 0) {
985 switch (builtin) {
986 case SK_FRAGCOORD_BUILTIN:
987 this->write(ByteCodeInstruction::kLoadFragCoord);
988 fOutput->fUsesFragCoord = true;
989 break;
990 default:
991 fErrors.error(expr.fOffset, "Unsupported builtin");
992 break;
993 }
994 return;
995 }
996
Brian Osmanb08cc022020-04-02 11:38:40 -0400997 Location location = this->getLocation(expr);
998 int count = SlotCount(expr.fType);
Brian Osmanefb08402020-04-13 16:30:44 -0400999 if (count == 0) {
1000 return;
1001 }
Brian Osman02f8b072020-06-19 14:04:48 -04001002 if (location.isOnStack()) {
Brian Osmanb08cc022020-04-02 11:38:40 -04001003 this->write(location.selectLoad(ByteCodeInstruction::kLoadExtended,
1004 ByteCodeInstruction::kLoadExtendedGlobal,
1005 ByteCodeInstruction::kLoadExtendedUniform),
1006 count);
Brian Osmanb08cc022020-04-02 11:38:40 -04001007 } else {
Brian Osman49b30f42020-06-26 17:22:27 -04001008 this->write(location.selectLoad(ByteCodeInstruction::kLoad,
1009 ByteCodeInstruction::kLoadGlobal,
1010 ByteCodeInstruction::kLoadUniform),
1011 count);
1012 this->write8(location.fSlot);
Brian Osmanb08cc022020-04-02 11:38:40 -04001013 }
1014}
1015
1016static inline uint32_t float_to_bits(float x) {
1017 uint32_t u;
1018 memcpy(&u, &x, sizeof(uint32_t));
1019 return u;
1020}
1021
1022void ByteCodeGenerator::writeFloatLiteral(const FloatLiteral& f) {
1023 this->write(ByteCodeInstruction::kPushImmediate);
1024 this->write32(float_to_bits(f.fValue));
1025}
1026
Brian Osman8842b372020-05-01 15:07:49 -04001027static bool is_generic_type(const Type* type, const Type* generic) {
1028 const std::vector<const Type*>& concrete(generic->coercibleTypes());
1029 return std::find(concrete.begin(), concrete.end(), type) != concrete.end();
1030}
1031
Brian Osmanb08cc022020-04-02 11:38:40 -04001032void ByteCodeGenerator::writeIntrinsicCall(const FunctionCall& c) {
1033 auto found = fIntrinsics.find(c.fFunction.fName);
1034 if (found == fIntrinsics.end()) {
1035 fErrors.error(c.fOffset, String::printf("Unsupported intrinsic: '%s'",
1036 String(c.fFunction.fName).c_str()));
1037 return;
1038 }
Mike Klein45be0772020-05-01 09:13:18 -05001039 Intrinsic intrin = found->second;
Brian Osman795efd22020-07-01 13:18:36 -04001040
1041 const auto& args = c.fArguments;
1042 const size_t nargs = args.size();
1043 SkASSERT(nargs >= 1);
1044
1045 int count = SlotCount(args[0]->fType);
Brian Osmand5f937b2020-05-04 12:07:29 -04001046
1047 // Several intrinsics have variants where one argument is either scalar, or the same size as
1048 // the first argument. Call dupSmallerType(SlotCount(argType)) to ensure equal component count.
1049 auto dupSmallerType = [count, this](int smallCount) {
1050 SkASSERT(smallCount == 1 || smallCount == count);
1051 for (int i = smallCount; i < count; ++i) {
Brian Osman49b30f42020-06-26 17:22:27 -04001052 this->write(ByteCodeInstruction::kDup, 1);
Brian Osmand5f937b2020-05-04 12:07:29 -04001053 }
1054 };
1055
Brian Osmana43d8202020-06-17 16:50:39 -04001056 if (intrin.is_special && intrin.special == SpecialIntrinsic::kSample) {
Brian Osman795efd22020-07-01 13:18:36 -04001057 // Sample is very special, the first argument is an FP, which can't be pushed to the stack.
1058 if (nargs > 2 || args[0]->fType != *fContext.fFragmentProcessor_Type ||
1059 (nargs == 2 && (args[1]->fType != *fContext.fFloat2_Type &&
1060 args[1]->fType != *fContext.fFloat3x3_Type))) {
Brian Osmana43d8202020-06-17 16:50:39 -04001061 fErrors.error(c.fOffset, "Unsupported form of sample");
1062 return;
1063 }
1064
Brian Osman795efd22020-07-01 13:18:36 -04001065 if (nargs == 2) {
1066 // Write our coords or matrix
1067 this->writeExpression(*args[1]);
1068 this->write(args[1]->fType == *fContext.fFloat3x3_Type
1069 ? ByteCodeInstruction::kSampleMatrix
1070 : ByteCodeInstruction::kSampleExplicit);
1071 } else {
1072 this->write(ByteCodeInstruction::kSample);
1073 }
Brian Osmana43d8202020-06-17 16:50:39 -04001074
Brian Osman795efd22020-07-01 13:18:36 -04001075 Location childLoc = this->getLocation(*args[0]);
Brian Osmana43d8202020-06-17 16:50:39 -04001076 SkASSERT(childLoc.fStorage == Storage::kChildFP);
1077 this->write8(childLoc.fSlot);
1078 return;
1079 }
1080
Brian Osmand5f937b2020-05-04 12:07:29 -04001081 if (intrin.is_special && (intrin.special == SpecialIntrinsic::kClamp ||
1082 intrin.special == SpecialIntrinsic::kSaturate)) {
1083 // These intrinsics are extra-special, we need instructions interleaved with arguments
1084 bool saturate = (intrin.special == SpecialIntrinsic::kSaturate);
Brian Osman795efd22020-07-01 13:18:36 -04001085 SkASSERT(nargs == (saturate ? 1 : 3));
1086 int limitCount = saturate ? 1 : SlotCount(args[1]->fType);
Brian Osmand5f937b2020-05-04 12:07:29 -04001087
1088 // 'x'
Brian Osman795efd22020-07-01 13:18:36 -04001089 this->writeExpression(*args[0]);
Brian Osmand5f937b2020-05-04 12:07:29 -04001090
1091 // 'minVal'
1092 if (saturate) {
1093 this->write(ByteCodeInstruction::kPushImmediate);
1094 this->write32(float_to_bits(0.0f));
1095 } else {
Brian Osman795efd22020-07-01 13:18:36 -04001096 this->writeExpression(*args[1]);
Brian Osmand5f937b2020-05-04 12:07:29 -04001097 }
1098 dupSmallerType(limitCount);
Brian Osman795efd22020-07-01 13:18:36 -04001099 this->writeTypedInstruction(args[0]->fType,
Brian Osmand5f937b2020-05-04 12:07:29 -04001100 ByteCodeInstruction::kMaxS,
1101 ByteCodeInstruction::kMaxS,
1102 ByteCodeInstruction::kMaxF,
1103 count);
1104
1105 // 'maxVal'
1106 if (saturate) {
1107 this->write(ByteCodeInstruction::kPushImmediate);
1108 this->write32(float_to_bits(1.0f));
1109 } else {
Brian Osman795efd22020-07-01 13:18:36 -04001110 SkASSERT(limitCount == SlotCount(args[2]->fType));
1111 this->writeExpression(*args[2]);
Brian Osmand5f937b2020-05-04 12:07:29 -04001112 }
1113 dupSmallerType(limitCount);
Brian Osman795efd22020-07-01 13:18:36 -04001114 this->writeTypedInstruction(args[0]->fType,
Brian Osmand5f937b2020-05-04 12:07:29 -04001115 ByteCodeInstruction::kMinS,
1116 ByteCodeInstruction::kMinS,
1117 ByteCodeInstruction::kMinF,
1118 count);
1119 return;
1120 }
1121
1122 // All other intrinsics can handle their arguments being on the stack in order
Brian Osman795efd22020-07-01 13:18:36 -04001123 for (const auto& arg : args) {
Brian Osmand5f937b2020-05-04 12:07:29 -04001124 this->writeExpression(*arg);
1125 }
1126
Mike Klein45be0772020-05-01 09:13:18 -05001127 if (intrin.is_special) {
1128 switch (intrin.special) {
Brian Osman8842b372020-05-01 15:07:49 -04001129 case SpecialIntrinsic::kAll: {
1130 for (int i = count-1; i --> 0;) {
Brian Osman49b30f42020-06-26 17:22:27 -04001131 this->write(ByteCodeInstruction::kAndB, 1);
Brian Osman8842b372020-05-01 15:07:49 -04001132 }
1133 } break;
1134
1135 case SpecialIntrinsic::kAny: {
1136 for (int i = count-1; i --> 0;) {
Brian Osman49b30f42020-06-26 17:22:27 -04001137 this->write(ByteCodeInstruction::kOrB, 1);
Brian Osman8842b372020-05-01 15:07:49 -04001138 }
1139 } break;
1140
Brian Osman15c98cb2020-02-27 18:36:57 +00001141 case SpecialIntrinsic::kDot: {
Brian Osman795efd22020-07-01 13:18:36 -04001142 SkASSERT(nargs == 2);
1143 SkASSERT(count == SlotCount(args[1]->fType));
Brian Osman49b30f42020-06-26 17:22:27 -04001144 this->write(ByteCodeInstruction::kMultiplyF, count);
Mike Klein45be0772020-05-01 09:13:18 -05001145 for (int i = count-1; i --> 0;) {
Brian Osman49b30f42020-06-26 17:22:27 -04001146 this->write(ByteCodeInstruction::kAddF, 1);
Ethan Nicholasb962eff2020-01-23 16:49:41 -05001147 }
Mike Klein45be0772020-05-01 09:13:18 -05001148 } break;
1149
1150 case SpecialIntrinsic::kLength: {
Brian Osman795efd22020-07-01 13:18:36 -04001151 SkASSERT(nargs == 1);
Brian Osman49b30f42020-06-26 17:22:27 -04001152 this->write(ByteCodeInstruction::kDup, count);
1153 this->write(ByteCodeInstruction::kMultiplyF, count);
Mike Klein45be0772020-05-01 09:13:18 -05001154 for (int i = count-1; i --> 0;) {
Brian Osman49b30f42020-06-26 17:22:27 -04001155 this->write(ByteCodeInstruction::kAddF, 1);
Mike Klein45be0772020-05-01 09:13:18 -05001156 }
Brian Osman49b30f42020-06-26 17:22:27 -04001157 this->write(ByteCodeInstruction::kSqrt, 1);
Mike Klein45be0772020-05-01 09:13:18 -05001158 } break;
1159
Brian Osmand5f937b2020-05-04 12:07:29 -04001160 case SpecialIntrinsic::kMax:
1161 case SpecialIntrinsic::kMin: {
Brian Osman795efd22020-07-01 13:18:36 -04001162 SkASSERT(nargs == 2);
Brian Osmand5f937b2020-05-04 12:07:29 -04001163 // There are variants where the second argument is scalar
Brian Osman795efd22020-07-01 13:18:36 -04001164 dupSmallerType(SlotCount(args[1]->fType));
Brian Osmand5f937b2020-05-04 12:07:29 -04001165 if (intrin.special == SpecialIntrinsic::kMax) {
Brian Osman795efd22020-07-01 13:18:36 -04001166 this->writeTypedInstruction(args[0]->fType,
Brian Osmand5f937b2020-05-04 12:07:29 -04001167 ByteCodeInstruction::kMaxS,
1168 ByteCodeInstruction::kMaxS,
1169 ByteCodeInstruction::kMaxF,
1170 count);
1171 } else {
Brian Osman795efd22020-07-01 13:18:36 -04001172 this->writeTypedInstruction(args[0]->fType,
Brian Osmand5f937b2020-05-04 12:07:29 -04001173 ByteCodeInstruction::kMinS,
1174 ByteCodeInstruction::kMinS,
1175 ByteCodeInstruction::kMinF,
1176 count);
1177 }
1178 } break;
1179
Brian Osman8842b372020-05-01 15:07:49 -04001180 case SpecialIntrinsic::kMix: {
1181 // Two main variants of mix to handle
Brian Osman795efd22020-07-01 13:18:36 -04001182 SkASSERT(nargs == 3);
1183 SkASSERT(count == SlotCount(args[1]->fType));
1184 int selectorCount = SlotCount(args[2]->fType);
Brian Osman8842b372020-05-01 15:07:49 -04001185
Brian Osman795efd22020-07-01 13:18:36 -04001186 if (is_generic_type(&args[2]->fType, fContext.fGenBType_Type.get())) {
Brian Osman8842b372020-05-01 15:07:49 -04001187 // mix(genType, genType, genBoolType)
1188 SkASSERT(selectorCount == count);
Brian Osman49b30f42020-06-26 17:22:27 -04001189 this->write(ByteCodeInstruction::kMix, count);
Brian Osman8842b372020-05-01 15:07:49 -04001190 } else {
1191 // mix(genType, genType, genType) or mix(genType, genType, float)
Brian Osmand5f937b2020-05-04 12:07:29 -04001192 dupSmallerType(selectorCount);
Brian Osman49b30f42020-06-26 17:22:27 -04001193 this->write(ByteCodeInstruction::kLerp, count);
Brian Osman8842b372020-05-01 15:07:49 -04001194 }
1195 } break;
1196
Brian Osman2a4871b2020-06-19 11:29:58 -04001197 case SpecialIntrinsic::kNormalize: {
Brian Osman795efd22020-07-01 13:18:36 -04001198 SkASSERT(nargs == 1);
Brian Osman49b30f42020-06-26 17:22:27 -04001199 this->write(ByteCodeInstruction::kDup, count);
1200 this->write(ByteCodeInstruction::kDup, count);
1201 this->write(ByteCodeInstruction::kMultiplyF, count);
Brian Osman2a4871b2020-06-19 11:29:58 -04001202 for (int i = count-1; i --> 0;) {
Brian Osman49b30f42020-06-26 17:22:27 -04001203 this->write(ByteCodeInstruction::kAddF, 1);
Brian Osman2a4871b2020-06-19 11:29:58 -04001204 }
Brian Osman49b30f42020-06-26 17:22:27 -04001205 this->write(ByteCodeInstruction::kSqrt, 1);
Brian Osman2a4871b2020-06-19 11:29:58 -04001206 dupSmallerType(1);
Brian Osman49b30f42020-06-26 17:22:27 -04001207 this->write(ByteCodeInstruction::kDivideF, count);
Brian Osman2a4871b2020-06-19 11:29:58 -04001208 } break;
1209
Brian Osmanb08cc022020-04-02 11:38:40 -04001210 default:
1211 SkASSERT(false);
Ethan Nicholasb962eff2020-01-23 16:49:41 -05001212 }
1213 } else {
Brian Osman8842b372020-05-01 15:07:49 -04001214 switch (intrin.inst_f) {
Brian Osmanb08cc022020-04-02 11:38:40 -04001215 case ByteCodeInstruction::kInverse2x2: {
Brian Osmanb08cc022020-04-02 11:38:40 -04001216 auto op = ByteCodeInstruction::kInverse2x2;
1217 switch (count) {
1218 case 4: break; // float2x2
1219 case 9: op = ByteCodeInstruction::kInverse3x3; break;
1220 case 16: op = ByteCodeInstruction::kInverse4x4; break;
1221 default: SkASSERT(false);
1222 }
1223 this->write(op);
1224 break;
Brian Osman15c98cb2020-02-27 18:36:57 +00001225 }
Mike Klein45be0772020-05-01 09:13:18 -05001226
Brian Osmanb08cc022020-04-02 11:38:40 -04001227 default:
Brian Osman795efd22020-07-01 13:18:36 -04001228 this->writeTypedInstruction(args[0]->fType,
Brian Osman49b30f42020-06-26 17:22:27 -04001229 intrin.inst_s,
1230 intrin.inst_u,
1231 intrin.inst_f,
1232 count);
Brian Osman8842b372020-05-01 15:07:49 -04001233 break;
Ethan Nicholasb962eff2020-01-23 16:49:41 -05001234 }
1235 }
1236}
1237
Brian Osmanb08cc022020-04-02 11:38:40 -04001238void ByteCodeGenerator::writeFunctionCall(const FunctionCall& f) {
Ethan Nicholasb962eff2020-01-23 16:49:41 -05001239 // Find the index of the function we're calling. We explicitly do not allow calls to functions
1240 // before they're defined. This is an easy-to-understand rule that prevents recursion.
Brian Osmanb08cc022020-04-02 11:38:40 -04001241 int idx = -1;
1242 for (size_t i = 0; i < fFunctions.size(); ++i) {
1243 if (f.fFunction.matches(fFunctions[i]->fDeclaration)) {
1244 idx = i;
Ethan Nicholasb962eff2020-01-23 16:49:41 -05001245 break;
1246 }
1247 }
Brian Osmanb08cc022020-04-02 11:38:40 -04001248 if (idx == -1) {
Brian Osmanb08cc022020-04-02 11:38:40 -04001249 this->writeIntrinsicCall(f);
1250 return;
Ethan Nicholasb962eff2020-01-23 16:49:41 -05001251 }
Brian Osmanb08cc022020-04-02 11:38:40 -04001252
1253
1254 if (idx > 255) {
1255 fErrors.error(f.fOffset, "Function count limit exceeded");
1256 return;
1257 } else if (idx >= (int) fFunctions.size()) {
1258 fErrors.error(f.fOffset, "Call to undefined function");
1259 return;
1260 }
1261
1262 // We may need to deal with out parameters, so the sequence is tricky
1263 if (int returnCount = SlotCount(f.fType)) {
1264 this->write(ByteCodeInstruction::kReserve, returnCount);
Brian Osmanb08cc022020-04-02 11:38:40 -04001265 }
1266
1267 int argCount = f.fArguments.size();
1268 std::vector<std::unique_ptr<LValue>> lvalues;
1269 for (int i = 0; i < argCount; ++i) {
1270 const auto& param = f.fFunction.fParameters[i];
1271 const auto& arg = f.fArguments[i];
1272 if (param->fModifiers.fFlags & Modifiers::kOut_Flag) {
1273 lvalues.emplace_back(this->getLValue(*arg));
1274 lvalues.back()->load();
1275 } else {
1276 this->writeExpression(*arg);
1277 }
1278 }
1279
1280 // The space used by the call is based on the callee, but it also unwinds all of that before
1281 // we continue execution. We adjust our max stack depths below.
1282 this->write(ByteCodeInstruction::kCall);
1283 this->write8(idx);
1284
1285 const ByteCodeFunction* callee = fOutput->fFunctions[idx].get();
1286 fMaxLoopCount = std::max(fMaxLoopCount, fLoopCount + callee->fLoopCount);
1287 fMaxConditionCount = std::max(fMaxConditionCount, fConditionCount + callee->fConditionCount);
1288 fMaxStackCount = std::max(fMaxStackCount, fStackCount + callee->fLocalCount
1289 + callee->fStackCount);
1290
1291 // After the called function returns, the stack will still contain our arguments. We have to
1292 // pop them (storing any out parameters back to their lvalues as we go). We glob together slot
1293 // counts for all parameters that aren't out-params, so we can pop them in one big chunk.
1294 int popCount = 0;
1295 auto pop = [&]() {
Brian Osman49b30f42020-06-26 17:22:27 -04001296 if (popCount > 0) {
1297 this->write(ByteCodeInstruction::kPop, popCount);
Brian Osmanb08cc022020-04-02 11:38:40 -04001298 }
1299 popCount = 0;
1300 };
1301
1302 for (int i = argCount - 1; i >= 0; --i) {
1303 const auto& param = f.fFunction.fParameters[i];
1304 const auto& arg = f.fArguments[i];
1305 if (param->fModifiers.fFlags & Modifiers::kOut_Flag) {
1306 pop();
1307 lvalues.back()->store(true);
1308 lvalues.pop_back();
1309 } else {
1310 popCount += SlotCount(arg->fType);
1311 }
1312 }
1313 pop();
Ethan Nicholasb962eff2020-01-23 16:49:41 -05001314}
1315
Brian Osmanb08cc022020-04-02 11:38:40 -04001316void ByteCodeGenerator::writeIntLiteral(const IntLiteral& i) {
1317 this->write(ByteCodeInstruction::kPushImmediate);
1318 this->write32(i.fValue);
Ethan Nicholasb962eff2020-01-23 16:49:41 -05001319}
1320
Brian Osmanb08cc022020-04-02 11:38:40 -04001321void ByteCodeGenerator::writeNullLiteral(const NullLiteral& n) {
1322 // not yet implemented
1323 abort();
Ethan Nicholasb962eff2020-01-23 16:49:41 -05001324}
1325
Brian Osmanb08cc022020-04-02 11:38:40 -04001326bool ByteCodeGenerator::writePrefixExpression(const PrefixExpression& p, bool discard) {
Ethan Nicholasb962eff2020-01-23 16:49:41 -05001327 switch (p.fOperator) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001328 case Token::Kind::TK_PLUSPLUS: // fall through
1329 case Token::Kind::TK_MINUSMINUS: {
Brian Osmanb08cc022020-04-02 11:38:40 -04001330 SkASSERT(SlotCount(p.fOperand->fType) == 1);
1331 std::unique_ptr<LValue> lvalue = this->getLValue(*p.fOperand);
1332 lvalue->load();
1333 this->write(ByteCodeInstruction::kPushImmediate);
1334 this->write32(type_category(p.fType) == TypeCategory::kFloat ? float_to_bits(1.0f) : 1);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001335 if (p.fOperator == Token::Kind::TK_PLUSPLUS) {
Brian Osmanb08cc022020-04-02 11:38:40 -04001336 this->writeTypedInstruction(p.fType,
1337 ByteCodeInstruction::kAddI,
1338 ByteCodeInstruction::kAddI,
1339 ByteCodeInstruction::kAddF,
1340 1);
1341 } else {
1342 this->writeTypedInstruction(p.fType,
1343 ByteCodeInstruction::kSubtractI,
1344 ByteCodeInstruction::kSubtractI,
1345 ByteCodeInstruction::kSubtractF,
1346 1);
1347 }
1348 lvalue->store(discard);
1349 discard = false;
1350 break;
Ethan Nicholasb962eff2020-01-23 16:49:41 -05001351 }
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001352 case Token::Kind::TK_MINUS: {
Brian Osmanb08cc022020-04-02 11:38:40 -04001353 this->writeExpression(*p.fOperand);
1354 this->writeTypedInstruction(p.fType,
1355 ByteCodeInstruction::kNegateI,
1356 ByteCodeInstruction::kNegateI,
1357 ByteCodeInstruction::kNegateF,
Brian Osmanab8f3842020-04-07 09:30:44 -04001358 SlotCount(p.fOperand->fType));
Ethan Nicholasb962eff2020-01-23 16:49:41 -05001359 break;
1360 }
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001361 case Token::Kind::TK_LOGICALNOT:
1362 case Token::Kind::TK_BITWISENOT: {
Brian Osmanb08cc022020-04-02 11:38:40 -04001363 SkASSERT(SlotCount(p.fOperand->fType) == 1);
1364 SkDEBUGCODE(TypeCategory tc = type_category(p.fOperand->fType));
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001365 SkASSERT((p.fOperator == Token::Kind::TK_LOGICALNOT && tc == TypeCategory::kBool) ||
1366 (p.fOperator == Token::Kind::TK_BITWISENOT && (tc == TypeCategory::kSigned ||
Brian Osmanb08cc022020-04-02 11:38:40 -04001367 tc == TypeCategory::kUnsigned)));
1368 this->writeExpression(*p.fOperand);
Brian Osman49b30f42020-06-26 17:22:27 -04001369 this->write(ByteCodeInstruction::kNotB, 1);
Ethan Nicholasb962eff2020-01-23 16:49:41 -05001370 break;
1371 }
1372 default:
1373 SkASSERT(false);
1374 }
Brian Osmanb08cc022020-04-02 11:38:40 -04001375 return discard;
Ethan Nicholasb962eff2020-01-23 16:49:41 -05001376}
1377
Brian Osmanb08cc022020-04-02 11:38:40 -04001378bool ByteCodeGenerator::writePostfixExpression(const PostfixExpression& p, bool discard) {
1379 switch (p.fOperator) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001380 case Token::Kind::TK_PLUSPLUS: // fall through
1381 case Token::Kind::TK_MINUSMINUS: {
Brian Osmanb08cc022020-04-02 11:38:40 -04001382 SkASSERT(SlotCount(p.fOperand->fType) == 1);
1383 std::unique_ptr<LValue> lvalue = this->getLValue(*p.fOperand);
1384 lvalue->load();
1385 // If we're not supposed to discard the result, then make a copy *before* the +/-
1386 if (!discard) {
Brian Osman49b30f42020-06-26 17:22:27 -04001387 this->write(ByteCodeInstruction::kDup, 1);
Brian Osmanb08cc022020-04-02 11:38:40 -04001388 }
1389 this->write(ByteCodeInstruction::kPushImmediate);
1390 this->write32(type_category(p.fType) == TypeCategory::kFloat ? float_to_bits(1.0f) : 1);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001391 if (p.fOperator == Token::Kind::TK_PLUSPLUS) {
Brian Osmanb08cc022020-04-02 11:38:40 -04001392 this->writeTypedInstruction(p.fType,
1393 ByteCodeInstruction::kAddI,
1394 ByteCodeInstruction::kAddI,
1395 ByteCodeInstruction::kAddF,
1396 1);
1397 } else {
1398 this->writeTypedInstruction(p.fType,
1399 ByteCodeInstruction::kSubtractI,
1400 ByteCodeInstruction::kSubtractI,
1401 ByteCodeInstruction::kSubtractF,
1402 1);
1403 }
1404 // Always consume the result as part of the store
1405 lvalue->store(true);
1406 discard = false;
1407 break;
1408 }
1409 default:
1410 SkASSERT(false);
1411 }
1412 return discard;
1413}
1414
1415void ByteCodeGenerator::writeSwizzle(const Swizzle& s) {
Ethan Nicholasb962eff2020-01-23 16:49:41 -05001416 if (swizzle_is_simple(s)) {
Brian Osmanb08cc022020-04-02 11:38:40 -04001417 this->writeVariableExpression(s);
Ethan Nicholasb962eff2020-01-23 16:49:41 -05001418 return;
1419 }
Brian Osmanb08cc022020-04-02 11:38:40 -04001420
Brian Osman3711c662020-06-18 14:42:21 -04001421 this->writeExpression(*s.fBase);
1422 this->write(ByteCodeInstruction::kSwizzle, s.fComponents.size() - s.fBase->fType.columns());
1423 this->write8(s.fBase->fType.columns());
1424 this->write8(s.fComponents.size());
1425 for (int c : s.fComponents) {
1426 this->write8(c);
Ethan Nicholasb962eff2020-01-23 16:49:41 -05001427 }
1428}
1429
Brian Osmanb08cc022020-04-02 11:38:40 -04001430void ByteCodeGenerator::writeTernaryExpression(const TernaryExpression& t) {
Ethan Nicholasb962eff2020-01-23 16:49:41 -05001431 int count = SlotCount(t.fType);
1432 SkASSERT(count == SlotCount(t.fIfTrue->fType));
1433 SkASSERT(count == SlotCount(t.fIfFalse->fType));
1434
Brian Osmanb08cc022020-04-02 11:38:40 -04001435 this->writeExpression(*t.fTest);
1436 this->write(ByteCodeInstruction::kMaskPush);
1437 this->writeExpression(*t.fIfTrue);
1438 this->write(ByteCodeInstruction::kMaskNegate);
1439 this->writeExpression(*t.fIfFalse);
1440 this->write(ByteCodeInstruction::kMaskBlend, count);
Ethan Nicholasb962eff2020-01-23 16:49:41 -05001441}
1442
Brian Osmanb08cc022020-04-02 11:38:40 -04001443void ByteCodeGenerator::writeExpression(const Expression& e, bool discard) {
Ethan Nicholase6592142020-09-08 10:22:09 -04001444 switch (e.kind()) {
1445 case Expression::Kind::kBinary:
John Stiles81365af2020-08-18 09:24:00 -04001446 discard = this->writeBinaryExpression(e.as<BinaryExpression>(), discard);
Ethan Nicholasb962eff2020-01-23 16:49:41 -05001447 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001448 case Expression::Kind::kBoolLiteral:
John Stiles81365af2020-08-18 09:24:00 -04001449 this->writeBoolLiteral(e.as<BoolLiteral>());
Ethan Nicholasb962eff2020-01-23 16:49:41 -05001450 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001451 case Expression::Kind::kConstructor:
John Stiles81365af2020-08-18 09:24:00 -04001452 this->writeConstructor(e.as<Constructor>());
Ethan Nicholasb962eff2020-01-23 16:49:41 -05001453 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001454 case Expression::Kind::kExternalFunctionCall:
John Stiles81365af2020-08-18 09:24:00 -04001455 this->writeExternalFunctionCall(e.as<ExternalFunctionCall>());
Ethan Nicholasb962eff2020-01-23 16:49:41 -05001456 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001457 case Expression::Kind::kExternalValue:
John Stiles81365af2020-08-18 09:24:00 -04001458 this->writeExternalValue(e.as<ExternalValueReference>());
Ethan Nicholasb962eff2020-01-23 16:49:41 -05001459 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001460 case Expression::Kind::kFieldAccess:
1461 case Expression::Kind::kIndex:
1462 case Expression::Kind::kVariableReference:
Brian Osmanb08cc022020-04-02 11:38:40 -04001463 this->writeVariableExpression(e);
1464 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001465 case Expression::Kind::kFloatLiteral:
John Stiles81365af2020-08-18 09:24:00 -04001466 this->writeFloatLiteral(e.as<FloatLiteral>());
Brian Osmanb08cc022020-04-02 11:38:40 -04001467 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001468 case Expression::Kind::kFunctionCall:
John Stiles81365af2020-08-18 09:24:00 -04001469 this->writeFunctionCall(e.as<FunctionCall>());
Brian Osmanb08cc022020-04-02 11:38:40 -04001470 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001471 case Expression::Kind::kIntLiteral:
John Stiles81365af2020-08-18 09:24:00 -04001472 this->writeIntLiteral(e.as<IntLiteral>());
Brian Osmanb08cc022020-04-02 11:38:40 -04001473 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001474 case Expression::Kind::kNullLiteral:
John Stiles81365af2020-08-18 09:24:00 -04001475 this->writeNullLiteral(e.as<NullLiteral>());
Brian Osmanb08cc022020-04-02 11:38:40 -04001476 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001477 case Expression::Kind::kPrefix:
John Stiles81365af2020-08-18 09:24:00 -04001478 discard = this->writePrefixExpression(e.as<PrefixExpression>(), discard);
Brian Osmanb08cc022020-04-02 11:38:40 -04001479 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001480 case Expression::Kind::kPostfix:
John Stiles81365af2020-08-18 09:24:00 -04001481 discard = this->writePostfixExpression(e.as<PostfixExpression>(), discard);
Brian Osmanb08cc022020-04-02 11:38:40 -04001482 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001483 case Expression::Kind::kSwizzle:
John Stiles81365af2020-08-18 09:24:00 -04001484 this->writeSwizzle(e.as<Swizzle>());
Brian Osmanb08cc022020-04-02 11:38:40 -04001485 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001486 case Expression::Kind::kTernary:
John Stiles81365af2020-08-18 09:24:00 -04001487 this->writeTernaryExpression(e.as<TernaryExpression>());
Ethan Nicholasb962eff2020-01-23 16:49:41 -05001488 break;
Ben Wagner470e0ac2020-01-22 16:59:21 -05001489 default:
1490#ifdef SK_DEBUG
Brian Osmanb08cc022020-04-02 11:38:40 -04001491 printf("unsupported expression %s\n", e.description().c_str());
Ben Wagner470e0ac2020-01-22 16:59:21 -05001492#endif
Brian Osmanb08cc022020-04-02 11:38:40 -04001493 SkASSERT(false);
1494 }
1495 if (discard) {
1496 int count = SlotCount(e.fType);
Brian Osman49b30f42020-06-26 17:22:27 -04001497 if (count > 0) {
1498 this->write(ByteCodeInstruction::kPop, count);
Brian Osmanb08cc022020-04-02 11:38:40 -04001499 }
1500 discard = false;
Ben Wagner470e0ac2020-01-22 16:59:21 -05001501 }
Ethan Nicholas7deb1c22020-01-22 10:31:55 -05001502}
1503
Brian Osmanb08cc022020-04-02 11:38:40 -04001504class ByteCodeExternalValueLValue : public ByteCodeGenerator::LValue {
1505public:
John Stiles534d7992020-08-18 00:06:01 -04001506 ByteCodeExternalValueLValue(ByteCodeGenerator* generator, const ExternalValue& value, int index)
Brian Osmanb08cc022020-04-02 11:38:40 -04001507 : INHERITED(*generator)
1508 , fCount(ByteCodeGenerator::SlotCount(value.type()))
1509 , fIndex(index) {}
1510
1511 void load() override {
Brian Osman49b30f42020-06-26 17:22:27 -04001512 fGenerator.write(ByteCodeInstruction::kReadExternal, fCount);
Brian Osmanb08cc022020-04-02 11:38:40 -04001513 fGenerator.write8(fIndex);
1514 }
1515
1516 void store(bool discard) override {
1517 if (!discard) {
Brian Osman49b30f42020-06-26 17:22:27 -04001518 fGenerator.write(ByteCodeInstruction::kDup, fCount);
Brian Osmanb08cc022020-04-02 11:38:40 -04001519 }
Brian Osman49b30f42020-06-26 17:22:27 -04001520 fGenerator.write(ByteCodeInstruction::kWriteExternal, fCount);
Brian Osmanb08cc022020-04-02 11:38:40 -04001521 fGenerator.write8(fIndex);
1522 }
1523
1524private:
John Stiles7571f9e2020-09-02 22:42:33 -04001525 using INHERITED = LValue;
Brian Osmanb08cc022020-04-02 11:38:40 -04001526
1527 int fCount;
Brian Osmanb08cc022020-04-02 11:38:40 -04001528 int fIndex;
1529};
1530
1531class ByteCodeSwizzleLValue : public ByteCodeGenerator::LValue {
1532public:
1533 ByteCodeSwizzleLValue(ByteCodeGenerator* generator, const Swizzle& swizzle)
1534 : INHERITED(*generator)
1535 , fSwizzle(swizzle) {}
1536
1537 void load() override {
1538 fGenerator.writeSwizzle(fSwizzle);
1539 }
1540
1541 void store(bool discard) override {
1542 int count = fSwizzle.fComponents.size();
1543 if (!discard) {
Brian Osman49b30f42020-06-26 17:22:27 -04001544 fGenerator.write(ByteCodeInstruction::kDup, count);
Brian Osmanb08cc022020-04-02 11:38:40 -04001545 }
Brian Osman304dfa32020-06-18 15:53:51 -04001546 // We already have the correct number of values on the stack, thanks to type checking.
1547 // The algorithm: Walk down the values on the stack, doing 'count' single-element stores.
1548 // For each value, use the corresponding swizzle component to offset the store location.
1549 //
1550 // Static locations: We (wastefully) call getLocation every time, but get good byte code.
1551 // Note that we could (but don't) store adjacent/sequential values with fewer instructions.
1552 //
1553 // Dynamic locations: ... are bad. We have to recompute the base address on each iteration,
1554 // because the stack doesn't let us retain that address between stores. Dynamic locations
1555 // are rare though, and swizzled writes to those are even rarer, so we just live with this.
1556 for (int i = count; i-- > 0;) {
1557 ByteCodeGenerator::Location location = fGenerator.getLocation(*fSwizzle.fBase);
1558 if (!location.isOnStack()) {
1559 fGenerator.write(location.selectStore(ByteCodeInstruction::kStore,
Brian Osman49b30f42020-06-26 17:22:27 -04001560 ByteCodeInstruction::kStoreGlobal),
1561 1);
Brian Osman304dfa32020-06-18 15:53:51 -04001562 fGenerator.write8(location.fSlot + fSwizzle.fComponents[i]);
1563 } else {
1564 fGenerator.write(ByteCodeInstruction::kPushImmediate);
1565 fGenerator.write32(fSwizzle.fComponents[i]);
Brian Osman49b30f42020-06-26 17:22:27 -04001566 fGenerator.write(ByteCodeInstruction::kAddI, 1);
Brian Osman304dfa32020-06-18 15:53:51 -04001567 fGenerator.write(location.selectStore(ByteCodeInstruction::kStoreExtended,
1568 ByteCodeInstruction::kStoreExtendedGlobal),
1569 1);
Brian Osman304dfa32020-06-18 15:53:51 -04001570 }
Brian Osmanb08cc022020-04-02 11:38:40 -04001571 }
1572 }
1573
1574private:
1575 const Swizzle& fSwizzle;
1576
John Stiles7571f9e2020-09-02 22:42:33 -04001577 using INHERITED = LValue;
Brian Osmanb08cc022020-04-02 11:38:40 -04001578};
1579
1580class ByteCodeExpressionLValue : public ByteCodeGenerator::LValue {
1581public:
1582 ByteCodeExpressionLValue(ByteCodeGenerator* generator, const Expression& expr)
1583 : INHERITED(*generator)
1584 , fExpression(expr) {}
1585
1586 void load() override {
1587 fGenerator.writeVariableExpression(fExpression);
1588 }
1589
1590 void store(bool discard) override {
1591 int count = ByteCodeGenerator::SlotCount(fExpression.fType);
1592 if (!discard) {
Brian Osman49b30f42020-06-26 17:22:27 -04001593 fGenerator.write(ByteCodeInstruction::kDup, count);
Brian Osmanb08cc022020-04-02 11:38:40 -04001594 }
1595 ByteCodeGenerator::Location location = fGenerator.getLocation(fExpression);
Brian Osman49b30f42020-06-26 17:22:27 -04001596 if (location.isOnStack()) {
Brian Osmanb08cc022020-04-02 11:38:40 -04001597 fGenerator.write(location.selectStore(ByteCodeInstruction::kStoreExtended,
1598 ByteCodeInstruction::kStoreExtendedGlobal),
1599 count);
Brian Osmanb08cc022020-04-02 11:38:40 -04001600 } else {
Brian Osman49b30f42020-06-26 17:22:27 -04001601 fGenerator.write(location.selectStore(ByteCodeInstruction::kStore,
1602 ByteCodeInstruction::kStoreGlobal),
1603 count);
Brian Osmanb08cc022020-04-02 11:38:40 -04001604 fGenerator.write8(location.fSlot);
1605 }
1606 }
1607
1608private:
John Stiles7571f9e2020-09-02 22:42:33 -04001609 using INHERITED = LValue;
Brian Osmanb08cc022020-04-02 11:38:40 -04001610
1611 const Expression& fExpression;
1612};
1613
1614std::unique_ptr<ByteCodeGenerator::LValue> ByteCodeGenerator::getLValue(const Expression& e) {
Ethan Nicholase6592142020-09-08 10:22:09 -04001615 switch (e.kind()) {
1616 case Expression::Kind::kExternalValue: {
John Stiles17c5b702020-08-18 10:40:03 -04001617 const ExternalValue* value = e.as<ExternalValueReference>().fValue;
Brian Osmanb08cc022020-04-02 11:38:40 -04001618 int index = fOutput->fExternalValues.size();
1619 fOutput->fExternalValues.push_back(value);
1620 SkASSERT(index <= 255);
1621 return std::unique_ptr<LValue>(new ByteCodeExternalValueLValue(this, *value, index));
1622 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001623 case Expression::Kind::kFieldAccess:
1624 case Expression::Kind::kIndex:
1625 case Expression::Kind::kVariableReference:
Brian Osmanb08cc022020-04-02 11:38:40 -04001626 return std::unique_ptr<LValue>(new ByteCodeExpressionLValue(this, e));
Ethan Nicholase6592142020-09-08 10:22:09 -04001627 case Expression::Kind::kSwizzle: {
John Stiles17c5b702020-08-18 10:40:03 -04001628 const Swizzle& s = e.as<Swizzle>();
Brian Osmanb08cc022020-04-02 11:38:40 -04001629 return swizzle_is_simple(s)
1630 ? std::unique_ptr<LValue>(new ByteCodeExpressionLValue(this, e))
1631 : std::unique_ptr<LValue>(new ByteCodeSwizzleLValue(this, s));
1632 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001633 case Expression::Kind::kTernary:
Brian Osmanb08cc022020-04-02 11:38:40 -04001634 default:
1635#ifdef SK_DEBUG
1636 ABORT("unsupported lvalue %s\n", e.description().c_str());
1637#endif
1638 return nullptr;
1639 }
Ethan Nicholasb962eff2020-01-23 16:49:41 -05001640}
1641
Ethan Nicholas0e9401d2019-03-21 11:05:37 -04001642void ByteCodeGenerator::writeBlock(const Block& b) {
1643 for (const auto& s : b.fStatements) {
1644 this->writeStatement(*s);
1645 }
1646}
1647
Brian Osmanb08cc022020-04-02 11:38:40 -04001648void ByteCodeGenerator::setBreakTargets() {
1649 std::vector<DeferredLocation>& breaks = fBreakTargets.top();
1650 for (DeferredLocation& b : breaks) {
1651 b.set();
1652 }
1653 fBreakTargets.pop();
1654}
1655
1656void ByteCodeGenerator::setContinueTargets() {
1657 std::vector<DeferredLocation>& continues = fContinueTargets.top();
1658 for (DeferredLocation& c : continues) {
1659 c.set();
1660 }
1661 fContinueTargets.pop();
1662}
1663
1664void ByteCodeGenerator::writeBreakStatement(const BreakStatement& b) {
1665 // TODO: Include BranchIfAllFalse to top-most LoopNext
1666 this->write(ByteCodeInstruction::kLoopBreak);
1667}
1668
1669void ByteCodeGenerator::writeContinueStatement(const ContinueStatement& c) {
1670 // TODO: Include BranchIfAllFalse to top-most LoopNext
1671 this->write(ByteCodeInstruction::kLoopContinue);
1672}
1673
Ethan Nicholas0e9401d2019-03-21 11:05:37 -04001674void ByteCodeGenerator::writeDoStatement(const DoStatement& d) {
Brian Osmanb08cc022020-04-02 11:38:40 -04001675 this->write(ByteCodeInstruction::kLoopBegin);
1676 size_t start = fCode->size();
Ethan Nicholas0e9401d2019-03-21 11:05:37 -04001677 this->writeStatement(*d.fStatement);
Brian Osmanb08cc022020-04-02 11:38:40 -04001678 this->write(ByteCodeInstruction::kLoopNext);
1679 this->writeExpression(*d.fTest);
1680 this->write(ByteCodeInstruction::kLoopMask);
1681 // TODO: Could shorten this with kBranchIfAnyTrue
1682 this->write(ByteCodeInstruction::kBranchIfAllFalse);
Brian Osman569f12f2019-06-13 11:23:57 -04001683 DeferredLocation endLocation(this);
Brian Osmanb08cc022020-04-02 11:38:40 -04001684 this->write(ByteCodeInstruction::kBranch);
1685 this->write16(start);
Brian Osman569f12f2019-06-13 11:23:57 -04001686 endLocation.set();
Brian Osmanb08cc022020-04-02 11:38:40 -04001687 this->write(ByteCodeInstruction::kLoopEnd);
Ethan Nicholas0e9401d2019-03-21 11:05:37 -04001688}
1689
1690void ByteCodeGenerator::writeForStatement(const ForStatement& f) {
Brian Osmanb08cc022020-04-02 11:38:40 -04001691 fContinueTargets.emplace();
1692 fBreakTargets.emplace();
Ethan Nicholas0e9401d2019-03-21 11:05:37 -04001693 if (f.fInitializer) {
1694 this->writeStatement(*f.fInitializer);
1695 }
Brian Osmanb08cc022020-04-02 11:38:40 -04001696 this->write(ByteCodeInstruction::kLoopBegin);
1697 size_t start = fCode->size();
Ethan Nicholas0e9401d2019-03-21 11:05:37 -04001698 if (f.fTest) {
Brian Osmanb08cc022020-04-02 11:38:40 -04001699 this->writeExpression(*f.fTest);
1700 this->write(ByteCodeInstruction::kLoopMask);
Ethan Nicholas0e9401d2019-03-21 11:05:37 -04001701 }
Brian Osmanb08cc022020-04-02 11:38:40 -04001702 this->write(ByteCodeInstruction::kBranchIfAllFalse);
Brian Osman569f12f2019-06-13 11:23:57 -04001703 DeferredLocation endLocation(this);
1704 this->writeStatement(*f.fStatement);
Brian Osmanb08cc022020-04-02 11:38:40 -04001705 this->write(ByteCodeInstruction::kLoopNext);
Brian Osman569f12f2019-06-13 11:23:57 -04001706 if (f.fNext) {
Brian Osmanb08cc022020-04-02 11:38:40 -04001707 this->writeExpression(*f.fNext, true);
Brian Osman569f12f2019-06-13 11:23:57 -04001708 }
Brian Osmanb08cc022020-04-02 11:38:40 -04001709 this->write(ByteCodeInstruction::kBranch);
1710 this->write16(start);
Brian Osman569f12f2019-06-13 11:23:57 -04001711 endLocation.set();
Brian Osmanb08cc022020-04-02 11:38:40 -04001712 this->write(ByteCodeInstruction::kLoopEnd);
Ethan Nicholas0e9401d2019-03-21 11:05:37 -04001713}
1714
1715void ByteCodeGenerator::writeIfStatement(const IfStatement& i) {
Brian Osmanb08cc022020-04-02 11:38:40 -04001716 this->writeExpression(*i.fTest);
1717 this->write(ByteCodeInstruction::kMaskPush);
1718 this->write(ByteCodeInstruction::kBranchIfAllFalse);
Brian Osman569f12f2019-06-13 11:23:57 -04001719 DeferredLocation falseLocation(this);
1720 this->writeStatement(*i.fIfTrue);
1721 falseLocation.set();
Ethan Nicholas0e9401d2019-03-21 11:05:37 -04001722 if (i.fIfFalse) {
Brian Osmanb08cc022020-04-02 11:38:40 -04001723 this->write(ByteCodeInstruction::kMaskNegate);
1724 this->write(ByteCodeInstruction::kBranchIfAllFalse);
Brian Osman569f12f2019-06-13 11:23:57 -04001725 DeferredLocation endLocation(this);
Ethan Nicholas0e9401d2019-03-21 11:05:37 -04001726 this->writeStatement(*i.fIfFalse);
Mike Kleinb45ee832019-05-17 11:11:11 -05001727 endLocation.set();
Ethan Nicholas0e9401d2019-03-21 11:05:37 -04001728 }
Brian Osmanb08cc022020-04-02 11:38:40 -04001729 this->write(ByteCodeInstruction::kMaskPop);
Ethan Nicholas0e9401d2019-03-21 11:05:37 -04001730}
1731
Brian Osmanb08cc022020-04-02 11:38:40 -04001732void ByteCodeGenerator::writeReturnStatement(const ReturnStatement& r) {
1733 if (fLoopCount || fConditionCount) {
Brian Osman4a47da72019-07-12 11:30:32 -04001734 fErrors.error(r.fOffset, "return not allowed inside conditional or loop");
1735 return;
1736 }
Brian Osmanb08cc022020-04-02 11:38:40 -04001737 int count = SlotCount(r.fExpression->fType);
1738 this->writeExpression(*r.fExpression);
1739
1740 // Technically, the kReturn also pops fOutput->fLocalCount values from the stack, too, but we
1741 // haven't counted pushing those (they're outside the scope of our stack tracking). Instead,
1742 // we account for those in writeFunction().
1743
1744 // This is all fine because we don't allow conditional returns, so we only return once anyway.
Brian Osman49b30f42020-06-26 17:22:27 -04001745 this->write(ByteCodeInstruction::kReturn, count);
Brian Osmanb08cc022020-04-02 11:38:40 -04001746}
1747
1748void ByteCodeGenerator::writeSwitchStatement(const SwitchStatement& r) {
1749 // not yet implemented
1750 abort();
Ethan Nicholas0e9401d2019-03-21 11:05:37 -04001751}
1752
1753void ByteCodeGenerator::writeVarDeclarations(const VarDeclarations& v) {
1754 for (const auto& declStatement : v.fVars) {
John Stiles403a3632020-08-20 12:11:48 -04001755 const VarDeclaration& decl = declStatement->as<VarDeclaration>();
Brian Osmanb08cc022020-04-02 11:38:40 -04001756 // we need to grab the location even if we don't use it, to ensure it has been allocated
1757 Location location = this->getLocation(*decl.fVar);
Ethan Nicholas0e9401d2019-03-21 11:05:37 -04001758 if (decl.fValue) {
Brian Osmanb08cc022020-04-02 11:38:40 -04001759 this->writeExpression(*decl.fValue);
1760 int count = SlotCount(decl.fValue->fType);
Brian Osman49b30f42020-06-26 17:22:27 -04001761 this->write(ByteCodeInstruction::kStore, count);
1762 this->write8(location.fSlot);
Ethan Nicholas0e9401d2019-03-21 11:05:37 -04001763 }
1764 }
1765}
1766
1767void ByteCodeGenerator::writeWhileStatement(const WhileStatement& w) {
Brian Osmanb08cc022020-04-02 11:38:40 -04001768 this->write(ByteCodeInstruction::kLoopBegin);
1769 size_t cond = fCode->size();
1770 this->writeExpression(*w.fTest);
1771 this->write(ByteCodeInstruction::kLoopMask);
1772 this->write(ByteCodeInstruction::kBranchIfAllFalse);
Ethan Nicholas0e9401d2019-03-21 11:05:37 -04001773 DeferredLocation endLocation(this);
1774 this->writeStatement(*w.fStatement);
Brian Osmanb08cc022020-04-02 11:38:40 -04001775 this->write(ByteCodeInstruction::kLoopNext);
1776 this->write(ByteCodeInstruction::kBranch);
1777 this->write16(cond);
Ethan Nicholas0e9401d2019-03-21 11:05:37 -04001778 endLocation.set();
Brian Osmanb08cc022020-04-02 11:38:40 -04001779 this->write(ByteCodeInstruction::kLoopEnd);
Ethan Nicholas0e9401d2019-03-21 11:05:37 -04001780}
1781
1782void ByteCodeGenerator::writeStatement(const Statement& s) {
Ethan Nicholase6592142020-09-08 10:22:09 -04001783 switch (s.kind()) {
1784 case Statement::Kind::kBlock:
John Stiles26f98502020-08-18 09:30:51 -04001785 this->writeBlock(s.as<Block>());
Ethan Nicholas0e9401d2019-03-21 11:05:37 -04001786 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001787 case Statement::Kind::kBreak:
John Stiles26f98502020-08-18 09:30:51 -04001788 this->writeBreakStatement(s.as<BreakStatement>());
Ethan Nicholas0e9401d2019-03-21 11:05:37 -04001789 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001790 case Statement::Kind::kContinue:
John Stiles26f98502020-08-18 09:30:51 -04001791 this->writeContinueStatement(s.as<ContinueStatement>());
Ethan Nicholas0e9401d2019-03-21 11:05:37 -04001792 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001793 case Statement::Kind::kDiscard:
Brian Osmanb08cc022020-04-02 11:38:40 -04001794 // not yet implemented
1795 abort();
Ethan Nicholase6592142020-09-08 10:22:09 -04001796 case Statement::Kind::kDo:
John Stiles26f98502020-08-18 09:30:51 -04001797 this->writeDoStatement(s.as<DoStatement>());
Ethan Nicholas0e9401d2019-03-21 11:05:37 -04001798 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001799 case Statement::Kind::kExpression:
John Stiles26f98502020-08-18 09:30:51 -04001800 this->writeExpression(*s.as<ExpressionStatement>().fExpression, true);
Ethan Nicholas0e9401d2019-03-21 11:05:37 -04001801 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001802 case Statement::Kind::kFor:
John Stiles26f98502020-08-18 09:30:51 -04001803 this->writeForStatement(s.as<ForStatement>());
Ethan Nicholas0e9401d2019-03-21 11:05:37 -04001804 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001805 case Statement::Kind::kIf:
John Stiles26f98502020-08-18 09:30:51 -04001806 this->writeIfStatement(s.as<IfStatement>());
Ethan Nicholas0e9401d2019-03-21 11:05:37 -04001807 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001808 case Statement::Kind::kNop:
Ethan Nicholas0e9401d2019-03-21 11:05:37 -04001809 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001810 case Statement::Kind::kReturn:
John Stiles26f98502020-08-18 09:30:51 -04001811 this->writeReturnStatement(s.as<ReturnStatement>());
Brian Osmanb08cc022020-04-02 11:38:40 -04001812 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001813 case Statement::Kind::kSwitch:
John Stiles26f98502020-08-18 09:30:51 -04001814 this->writeSwitchStatement(s.as<SwitchStatement>());
Ethan Nicholas0e9401d2019-03-21 11:05:37 -04001815 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001816 case Statement::Kind::kVarDeclarations:
John Stiles26f98502020-08-18 09:30:51 -04001817 this->writeVarDeclarations(*s.as<VarDeclarationsStatement>().fDeclaration);
Ethan Nicholas0e9401d2019-03-21 11:05:37 -04001818 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001819 case Statement::Kind::kWhile:
John Stiles26f98502020-08-18 09:30:51 -04001820 this->writeWhileStatement(s.as<WhileStatement>());
Ethan Nicholas0e9401d2019-03-21 11:05:37 -04001821 break;
1822 default:
Brian Osmanb08cc022020-04-02 11:38:40 -04001823 SkASSERT(false);
Ethan Nicholas0e9401d2019-03-21 11:05:37 -04001824 }
1825}
1826
Brian Osmanb08cc022020-04-02 11:38:40 -04001827ByteCodeFunction::ByteCodeFunction(const FunctionDeclaration* declaration)
1828 : fName(declaration->fName) {
Brian Osman80164412019-06-07 13:00:23 -04001829 fParameterCount = 0;
Brian Osmanb08cc022020-04-02 11:38:40 -04001830 for (const auto& p : declaration->fParameters) {
1831 int slots = ByteCodeGenerator::SlotCount(p->fType);
1832 fParameters.push_back({ slots, (bool)(p->fModifiers.fFlags & Modifiers::kOut_Flag) });
1833 fParameterCount += slots;
Brian Osman80164412019-06-07 13:00:23 -04001834 }
1835}
1836
John Stilesa6841be2020-08-06 14:11:56 -04001837} // namespace SkSL