blob: 54bcae3f007ac017bf46bfcf6c1c2e0784baa681 [file] [log] [blame]
Ethan Nicholascc305772017-10-13 16:17:45 -04001/*
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 */
7
Mike Kleinc0bd9f92019-04-23 12:05:21 -05008#include "src/sksl/SkSLMetalCodeGenerator.h"
Ethan Nicholascc305772017-10-13 16:17:45 -04009
John Stiles986c7fb2020-12-01 14:44:56 -050010#include "src/core/SkScopeExit.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050011#include "src/sksl/SkSLCompiler.h"
John Stiles0023c0c2020-11-16 13:32:18 -050012#include "src/sksl/SkSLMemoryLayout.h"
John Stiles7384b372021-04-01 13:48:15 -040013#include "src/sksl/ir/SkSLConstructorArray.h"
14#include "src/sksl/ir/SkSLConstructorDiagonalMatrix.h"
John Stiles2938eea2021-04-01 18:58:25 -040015#include "src/sksl/ir/SkSLConstructorSplat.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050016#include "src/sksl/ir/SkSLExpressionStatement.h"
17#include "src/sksl/ir/SkSLExtension.h"
18#include "src/sksl/ir/SkSLIndexExpression.h"
19#include "src/sksl/ir/SkSLModifiersDeclaration.h"
20#include "src/sksl/ir/SkSLNop.h"
John Stilesdc75a972020-11-25 16:24:55 -050021#include "src/sksl/ir/SkSLStructDefinition.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050022#include "src/sksl/ir/SkSLVariableReference.h"
Ethan Nicholascc305772017-10-13 16:17:45 -040023
Brian Osmanc262a122020-08-06 16:34:34 -040024#include <algorithm>
25
Ethan Nicholascc305772017-10-13 16:17:45 -040026namespace SkSL {
27
John Stiles45990502021-02-16 10:55:27 -050028const char* MetalCodeGenerator::OperatorName(Operator op) {
29 switch (op.kind()) {
John Stilesd6449e92020-11-30 09:13:23 -050030 case Token::Kind::TK_LOGICALXOR: return "!=";
John Stiles45990502021-02-16 10:55:27 -050031 default: return op.operatorName();
John Stilesd6449e92020-11-30 09:13:23 -050032 }
33}
34
John Stilescdcdb042020-07-06 09:03:51 -040035class MetalCodeGenerator::GlobalStructVisitor {
36public:
37 virtual ~GlobalStructVisitor() = default;
John Stilesfdb8dbe2020-12-04 11:00:03 -050038 virtual void visitInterfaceBlock(const InterfaceBlock& block, const String& blockName) = 0;
39 virtual void visitTexture(const Type& type, const String& name) = 0;
40 virtual void visitSampler(const Type& type, const String& name) = 0;
41 virtual void visitVariable(const Variable& var, const Expression* value) = 0;
John Stilescdcdb042020-07-06 09:03:51 -040042};
43
Timothy Liangee84fe12018-05-18 14:38:19 -040044void MetalCodeGenerator::setupIntrinsics() {
John Stilesd7199b22020-12-30 16:22:58 -050045 fIntrinsicMap[String("atan")] = kAtan_IntrinsicKind;
46 fIntrinsicMap[String("floatBitsToInt")] = kBitcast_IntrinsicKind;
47 fIntrinsicMap[String("floatBitsToUint")] = kBitcast_IntrinsicKind;
48 fIntrinsicMap[String("intBitsToFloat")] = kBitcast_IntrinsicKind;
49 fIntrinsicMap[String("uintBitsToFloat")] = kBitcast_IntrinsicKind;
50 fIntrinsicMap[String("equal")] = kCompareEqual_IntrinsicKind;
51 fIntrinsicMap[String("notEqual")] = kCompareNotEqual_IntrinsicKind;
52 fIntrinsicMap[String("lessThan")] = kCompareLessThan_IntrinsicKind;
53 fIntrinsicMap[String("lessThanEqual")] = kCompareLessThanEqual_IntrinsicKind;
54 fIntrinsicMap[String("greaterThan")] = kCompareGreaterThan_IntrinsicKind;
55 fIntrinsicMap[String("greaterThanEqual")] = kCompareGreaterThanEqual_IntrinsicKind;
56 fIntrinsicMap[String("degrees")] = kDegrees_IntrinsicKind;
57 fIntrinsicMap[String("dFdx")] = kDFdx_IntrinsicKind;
58 fIntrinsicMap[String("dFdy")] = kDFdy_IntrinsicKind;
59 fIntrinsicMap[String("distance")] = kDistance_IntrinsicKind;
60 fIntrinsicMap[String("dot")] = kDot_IntrinsicKind;
61 fIntrinsicMap[String("faceforward")] = kFaceforward_IntrinsicKind;
62 fIntrinsicMap[String("bitCount")] = kBitCount_IntrinsicKind;
63 fIntrinsicMap[String("findLSB")] = kFindLSB_IntrinsicKind;
64 fIntrinsicMap[String("findMSB")] = kFindMSB_IntrinsicKind;
65 fIntrinsicMap[String("inverse")] = kInverse_IntrinsicKind;
66 fIntrinsicMap[String("inversesqrt")] = kInversesqrt_IntrinsicKind;
67 fIntrinsicMap[String("length")] = kLength_IntrinsicKind;
68 fIntrinsicMap[String("matrixCompMult")] = kMatrixCompMult_IntrinsicKind;
69 fIntrinsicMap[String("mod")] = kMod_IntrinsicKind;
70 fIntrinsicMap[String("normalize")] = kNormalize_IntrinsicKind;
71 fIntrinsicMap[String("radians")] = kRadians_IntrinsicKind;
72 fIntrinsicMap[String("reflect")] = kReflect_IntrinsicKind;
73 fIntrinsicMap[String("refract")] = kRefract_IntrinsicKind;
John Stiles23456532020-12-30 18:12:48 -050074 fIntrinsicMap[String("roundEven")] = kRoundEven_IntrinsicKind;
John Stilesd7199b22020-12-30 16:22:58 -050075 fIntrinsicMap[String("sample")] = kTexture_IntrinsicKind;
Timothy Liangee84fe12018-05-18 14:38:19 -040076}
77
Ethan Nicholascc305772017-10-13 16:17:45 -040078void MetalCodeGenerator::write(const char* s) {
79 if (!s[0]) {
80 return;
81 }
82 if (fAtLineStart) {
83 for (int i = 0; i < fIndentation; i++) {
84 fOut->writeText(" ");
85 }
86 }
87 fOut->writeText(s);
88 fAtLineStart = false;
89}
90
91void MetalCodeGenerator::writeLine(const char* s) {
92 this->write(s);
John Stilese8b5a732021-03-12 13:25:52 -050093 this->writeLine();
Ethan Nicholascc305772017-10-13 16:17:45 -040094}
95
96void MetalCodeGenerator::write(const String& s) {
97 this->write(s.c_str());
98}
99
100void MetalCodeGenerator::writeLine(const String& s) {
101 this->writeLine(s.c_str());
102}
103
104void MetalCodeGenerator::writeLine() {
John Stilese8b5a732021-03-12 13:25:52 -0500105 fOut->writeText(fLineEnding);
106 fAtLineStart = true;
107}
108
109void MetalCodeGenerator::finishLine() {
110 if (!fAtLineStart) {
111 this->writeLine();
112 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400113}
114
115void MetalCodeGenerator::writeExtension(const Extension& ext) {
Ethan Nicholasefb09e22020-09-30 10:17:00 -0400116 this->writeLine("#extension " + ext.name() + " : enable");
Ethan Nicholascc305772017-10-13 16:17:45 -0400117}
118
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500119String MetalCodeGenerator::typeName(const Type& type) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400120 switch (type.typeKind()) {
John Stilesb4418502021-02-04 10:57:08 -0500121 case Type::TypeKind::kArray:
122 SkASSERTF(type.columns() > 0, "invalid array size: %s", type.description().c_str());
123 return String::printf("array<%s, %d>",
124 this->typeName(type.componentType()).c_str(), type.columns());
125
Ethan Nicholase6592142020-09-08 10:22:09 -0400126 case Type::TypeKind::kVector:
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500127 return this->typeName(type.componentType()) + to_string(type.columns());
John Stilesb4418502021-02-04 10:57:08 -0500128
Ethan Nicholase6592142020-09-08 10:22:09 -0400129 case Type::TypeKind::kMatrix:
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500130 return this->typeName(type.componentType()) + to_string(type.columns()) + "x" +
131 to_string(type.rows());
John Stilesb4418502021-02-04 10:57:08 -0500132
Ethan Nicholase6592142020-09-08 10:22:09 -0400133 case Type::TypeKind::kSampler:
John Stiles368db7c2020-12-29 11:20:08 -0500134 return "texture2d<float>"; // FIXME - support other texture types
John Stilesb4418502021-02-04 10:57:08 -0500135
John Stilesfd41d872020-11-25 22:39:45 -0500136 case Type::TypeKind::kEnum:
137 return "int";
John Stilesb4418502021-02-04 10:57:08 -0500138
Ethan Nicholascc305772017-10-13 16:17:45 -0400139 default:
John Stiles54e7c052021-01-11 14:22:36 -0500140 if (type == *fContext.fTypes.fHalf) {
Timothy Liang43d225f2018-07-19 15:27:13 -0400141 // FIXME - Currently only supporting floats in MSL to avoid type coercion issues.
John Stiles54e7c052021-01-11 14:22:36 -0500142 return fContext.fTypes.fFloat->name();
143 } else if (type == *fContext.fTypes.fByte) {
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500144 return "char";
John Stiles54e7c052021-01-11 14:22:36 -0500145 } else if (type == *fContext.fTypes.fUByte) {
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500146 return "uchar";
Timothy Liang7d637782018-06-05 09:58:07 -0400147 } else {
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500148 return type.name();
Timothy Liang7d637782018-06-05 09:58:07 -0400149 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400150 }
151}
152
Brian Osman02bc5222021-01-28 11:00:20 -0500153void MetalCodeGenerator::writeStructDefinition(const StructDefinition& s) {
154 const Type& type = s.type();
John Stilesdc75a972020-11-25 16:24:55 -0500155 this->writeLine("struct " + type.name() + " {");
156 fIndentation++;
157 this->writeFields(type.fields(), type.fOffset);
158 fIndentation--;
Brian Osman02bc5222021-01-28 11:00:20 -0500159 this->writeLine("};");
John Stilesdc75a972020-11-25 16:24:55 -0500160}
161
John Stilesb4418502021-02-04 10:57:08 -0500162void MetalCodeGenerator::writeType(const Type& type) {
163 this->write(this->typeName(type));
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500164}
165
Ethan Nicholascc305772017-10-13 16:17:45 -0400166void MetalCodeGenerator::writeExpression(const Expression& expr, Precedence parentPrecedence) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400167 switch (expr.kind()) {
168 case Expression::Kind::kBinary:
John Stiles81365af2020-08-18 09:24:00 -0400169 this->writeBinaryExpression(expr.as<BinaryExpression>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400170 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400171 case Expression::Kind::kBoolLiteral:
John Stiles81365af2020-08-18 09:24:00 -0400172 this->writeBoolLiteral(expr.as<BoolLiteral>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400173 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400174 case Expression::Kind::kConstructor:
John Stiles81365af2020-08-18 09:24:00 -0400175 this->writeConstructor(expr.as<Constructor>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400176 break;
John Stiles7384b372021-04-01 13:48:15 -0400177 case Expression::Kind::kConstructorArray:
178 this->writeConstructorArray(expr.as<ConstructorArray>(), parentPrecedence);
179 break;
John Stilese1182782021-03-30 22:09:37 -0400180 case Expression::Kind::kConstructorDiagonalMatrix:
John Stiles933043b2021-03-31 15:23:16 -0400181 this->writeSingleArgumentConstructor(expr.as<ConstructorDiagonalMatrix>(),
John Stilese1182782021-03-30 22:09:37 -0400182 parentPrecedence);
183 break;
John Stiles2938eea2021-04-01 18:58:25 -0400184 case Expression::Kind::kConstructorSplat:
185 this->writeSingleArgumentConstructor(expr.as<ConstructorSplat>(), parentPrecedence);
186 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400187 case Expression::Kind::kIntLiteral:
John Stiles81365af2020-08-18 09:24:00 -0400188 this->writeIntLiteral(expr.as<IntLiteral>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400189 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400190 case Expression::Kind::kFieldAccess:
John Stiles81365af2020-08-18 09:24:00 -0400191 this->writeFieldAccess(expr.as<FieldAccess>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400192 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400193 case Expression::Kind::kFloatLiteral:
John Stiles81365af2020-08-18 09:24:00 -0400194 this->writeFloatLiteral(expr.as<FloatLiteral>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400195 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400196 case Expression::Kind::kFunctionCall:
John Stiles81365af2020-08-18 09:24:00 -0400197 this->writeFunctionCall(expr.as<FunctionCall>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400198 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400199 case Expression::Kind::kPrefix:
John Stiles81365af2020-08-18 09:24:00 -0400200 this->writePrefixExpression(expr.as<PrefixExpression>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400201 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400202 case Expression::Kind::kPostfix:
John Stiles81365af2020-08-18 09:24:00 -0400203 this->writePostfixExpression(expr.as<PostfixExpression>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400204 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400205 case Expression::Kind::kSetting:
John Stiles81365af2020-08-18 09:24:00 -0400206 this->writeSetting(expr.as<Setting>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400207 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400208 case Expression::Kind::kSwizzle:
John Stiles81365af2020-08-18 09:24:00 -0400209 this->writeSwizzle(expr.as<Swizzle>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400210 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400211 case Expression::Kind::kVariableReference:
John Stiles81365af2020-08-18 09:24:00 -0400212 this->writeVariableReference(expr.as<VariableReference>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400213 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400214 case Expression::Kind::kTernary:
John Stiles81365af2020-08-18 09:24:00 -0400215 this->writeTernaryExpression(expr.as<TernaryExpression>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400216 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400217 case Expression::Kind::kIndex:
John Stiles81365af2020-08-18 09:24:00 -0400218 this->writeIndexExpression(expr.as<IndexExpression>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400219 break;
220 default:
John Stileseada7bc2021-02-02 16:29:32 -0500221 SkDEBUGFAILF("unsupported expression: %s", expr.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -0500222 break;
Ethan Nicholascc305772017-10-13 16:17:45 -0400223 }
224}
225
John Stiles06b84ef2020-12-09 12:35:48 -0500226String MetalCodeGenerator::getOutParamHelper(const FunctionCall& call,
227 const ExpressionArray& arguments,
228 const SkTArray<VariableReference*>& outVars) {
229 AutoOutputStream outputToExtraFunctions(this, &fExtraFunctions, &fIndentation);
230 const FunctionDeclaration& function = call.function();
231
John Stilese1068342021-03-22 11:57:41 -0400232 String name = "_skOutParamHelper" + to_string(fSwizzleHelperCount++) +
233 "_" + function.mangledName();
John Stiles06b84ef2020-12-09 12:35:48 -0500234 const char* separator = "";
235
236 // Emit a prototype for the function we'll be calling through to in our helper.
237 if (!function.isBuiltin()) {
238 this->writeFunctionDeclaration(function);
239 this->writeLine(";");
240 }
241
242 // Synthesize a helper function that takes the same inputs as `function`, except in places where
243 // `outVars` is non-null; in those places, we take the type of the VariableReference.
244 //
245 // float _skOutParamHelper0_originalFuncName(float _var0, float _var1, float& outParam) {
John Stilesb4418502021-02-04 10:57:08 -0500246 this->writeType(call.type());
John Stiles06b84ef2020-12-09 12:35:48 -0500247 this->write(" ");
248 this->write(name);
249 this->write("(");
250 this->writeFunctionRequirementParams(function, separator);
251
252 SkASSERT(outVars.size() == arguments.size());
253 SkASSERT(outVars.size() == function.parameters().size());
254
John Stiles73e2c892021-02-13 13:58:01 -0500255 // We need to detect cases where the caller passes the same variable as an out-param more than
256 // once, and avoid reusing the variable name. (In those cases we can actually just ignore the
257 // redundant input parameter entirely, and not give it any name.)
258 std::unordered_set<const Variable*> writtenVars;
259
John Stiles06b84ef2020-12-09 12:35:48 -0500260 for (int index = 0; index < arguments.count(); ++index) {
261 this->write(separator);
262 separator = ", ";
263
264 const Variable* param = function.parameters()[index];
265 this->writeModifiers(param->modifiers(), /*globalContext=*/false);
266
267 const Type* type = outVars[index] ? &outVars[index]->type() : &arguments[index]->type();
John Stilesb4418502021-02-04 10:57:08 -0500268 this->writeType(*type);
John Stiles06b84ef2020-12-09 12:35:48 -0500269
270 if (param->modifiers().fFlags & Modifiers::kOut_Flag) {
271 this->write("&");
272 }
273 if (outVars[index]) {
John Stiles73e2c892021-02-13 13:58:01 -0500274 auto [iter, didInsert] = writtenVars.insert(outVars[index]->variable());
275 if (didInsert) {
276 this->write(" ");
277 fIgnoreVariableReferenceModifiers = true;
278 this->writeVariableReference(*outVars[index]);
279 fIgnoreVariableReferenceModifiers = false;
280 }
John Stiles06b84ef2020-12-09 12:35:48 -0500281 } else {
282 this->write(" _var");
283 this->write(to_string(index));
284 }
John Stiles06b84ef2020-12-09 12:35:48 -0500285 }
286 this->writeLine(") {");
287
288 ++fIndentation;
289 for (int index = 0; index < outVars.count(); ++index) {
290 if (!outVars[index]) {
291 continue;
292 }
293 // float3 _var2[ = outParam.zyx];
John Stilesb4418502021-02-04 10:57:08 -0500294 this->writeType(arguments[index]->type());
John Stiles06b84ef2020-12-09 12:35:48 -0500295 this->write(" _var");
296 this->write(to_string(index));
297
298 const Variable* param = function.parameters()[index];
299 if (param->modifiers().fFlags & Modifiers::kIn_Flag) {
300 this->write(" = ");
301 fIgnoreVariableReferenceModifiers = true;
Brian Osman00185012021-02-04 16:07:11 -0500302 this->writeExpression(*arguments[index], Precedence::kAssignment);
John Stiles06b84ef2020-12-09 12:35:48 -0500303 fIgnoreVariableReferenceModifiers = false;
304 }
305
306 this->writeLine(";");
307 }
308
John Stilesf7410bd2021-01-19 13:07:55 -0500309 // [int _skResult = ] myFunction(inputs, outputs, _globals, _var0, _var1, _var2, _var3);
John Stiles06b84ef2020-12-09 12:35:48 -0500310 bool hasResult = (call.type().name() != "void");
311 if (hasResult) {
John Stilesb4418502021-02-04 10:57:08 -0500312 this->writeType(call.type());
John Stiles06b84ef2020-12-09 12:35:48 -0500313 this->write(" _skResult = ");
314 }
315
John Stilese1068342021-03-22 11:57:41 -0400316 this->writeName(function.mangledName());
John Stiles06b84ef2020-12-09 12:35:48 -0500317 this->write("(");
318 separator = "";
319 this->writeFunctionRequirementArgs(function, separator);
320
321 for (int index = 0; index < arguments.count(); ++index) {
322 this->write(separator);
323 separator = ", ";
324
325 this->write("_var");
326 this->write(to_string(index));
327 }
328 this->writeLine(");");
329
330 for (int index = 0; index < outVars.count(); ++index) {
331 if (!outVars[index]) {
332 continue;
333 }
334 // outParam.zyx = _var2;
335 fIgnoreVariableReferenceModifiers = true;
Brian Osman00185012021-02-04 16:07:11 -0500336 this->writeExpression(*arguments[index], Precedence::kAssignment);
John Stiles06b84ef2020-12-09 12:35:48 -0500337 fIgnoreVariableReferenceModifiers = false;
338 this->write(" = _var");
339 this->write(to_string(index));
340 this->writeLine(";");
341 }
342
343 if (hasResult) {
344 this->writeLine("return _skResult;");
345 }
346
347 --fIndentation;
348 this->writeLine("}");
349
350 return name;
John Stilesb21fac22020-12-04 15:36:49 -0500351}
352
John Stilesf64e4072020-12-10 10:34:27 -0500353String MetalCodeGenerator::getBitcastIntrinsic(const Type& outType) {
354 return "as_type<" + outType.displayName() + ">";
355}
356
Ethan Nicholascc305772017-10-13 16:17:45 -0400357void MetalCodeGenerator::writeFunctionCall(const FunctionCall& c) {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400358 const FunctionDeclaration& function = c.function();
John Stiles89ac7c22020-12-30 17:47:31 -0500359 // If this function is a built-in with no declaration, it's probably an intrinsic and might need
360 // special handling.
361 if (function.isBuiltin() && !function.definition()) {
362 auto iter = fIntrinsicMap.find(function.name());
363 if (iter != fIntrinsicMap.end()) {
364 this->writeIntrinsicCall(c, iter->second);
365 return;
366 }
Timothy Liang6403b0e2018-05-17 10:40:04 -0400367 }
John Stilesb21fac22020-12-04 15:36:49 -0500368
John Stilesd7199b22020-12-30 16:22:58 -0500369 // Determine whether or not we need to emulate GLSL's out-param semantics for Metal using a
370 // helper function. (Specifically, out-parameters in GLSL are only written back to the original
371 // variable at the end of the function call; also, swizzles are supported, whereas Metal doesn't
372 // allow a swizzle to be passed to a `floatN&`.)
373 const ExpressionArray& arguments = c.arguments();
John Stilesb21fac22020-12-04 15:36:49 -0500374 const std::vector<const Variable*>& parameters = function.parameters();
375 SkASSERT(arguments.size() == parameters.size());
John Stiles06b84ef2020-12-09 12:35:48 -0500376
377 bool foundOutParam = false;
378 SkSTArray<16, VariableReference*> outVars;
John Stilesf64e4072020-12-10 10:34:27 -0500379 outVars.push_back_n(arguments.count(), (VariableReference*)nullptr);
John Stiles06b84ef2020-12-09 12:35:48 -0500380
381 for (int index = 0; index < arguments.count(); ++index) {
John Stilesb21fac22020-12-04 15:36:49 -0500382 // If this is an out parameter...
383 if (parameters[index]->modifiers().fFlags & Modifiers::kOut_Flag) {
John Stiles06b84ef2020-12-09 12:35:48 -0500384 // Find the expression's inner variable being written to.
John Stilesb21fac22020-12-04 15:36:49 -0500385 Analysis::AssignmentInfo info;
John Stiles06b84ef2020-12-09 12:35:48 -0500386 // Assignability was verified at IRGeneration time, so this should always succeed.
387 SkAssertResult(Analysis::IsAssignable(*arguments[index], &info));
388 outVars[index] = info.fAssignedVar;
389 foundOutParam = true;
John Stilesb21fac22020-12-04 15:36:49 -0500390 }
391 }
392
John Stiles06b84ef2020-12-09 12:35:48 -0500393 if (foundOutParam) {
394 // Out parameters need to be written back to at the end of the function. To do this, we
395 // synthesize a helper function which evaluates the out-param expression into a temporary
396 // variable, calls the original function, then writes the temp var back into the out param
397 // using the original out-param expression. (This lets us support things like swizzles and
398 // array indices.)
John Stilesd7199b22020-12-30 16:22:58 -0500399 this->write(getOutParamHelper(c, arguments, outVars));
400 } else {
John Stilese1068342021-03-22 11:57:41 -0400401 this->write(function.mangledName());
John Stiles06b84ef2020-12-09 12:35:48 -0500402 }
403
Ethan Nicholascc305772017-10-13 16:17:45 -0400404 this->write("(");
405 const char* separator = "";
John Stiles06b84ef2020-12-09 12:35:48 -0500406 this->writeFunctionRequirementArgs(function, separator);
407 for (int i = 0; i < arguments.count(); ++i) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400408 this->write(separator);
409 separator = ", ";
John Stiles06b84ef2020-12-09 12:35:48 -0500410
411 if (outVars[i]) {
Brian Osman00185012021-02-04 16:07:11 -0500412 this->writeExpression(*outVars[i], Precedence::kSequence);
John Stiles06b84ef2020-12-09 12:35:48 -0500413 } else {
Brian Osman00185012021-02-04 16:07:11 -0500414 this->writeExpression(*arguments[i], Precedence::kSequence);
John Stiles06b84ef2020-12-09 12:35:48 -0500415 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400416 }
417 this->write(")");
418}
419
Brian Osman964f0a02020-12-29 10:15:22 -0500420static constexpr char kInverse2x2[] = R"(
421float2x2 float2x2_inverse(float2x2 m) {
422 return float2x2(m[1][1], -m[0][1], -m[1][0], m[0][0]) * (1/determinant(m));
423}
424)";
425
426static constexpr char kInverse3x3[] = R"(
427float3x3 float3x3_inverse(float3x3 m) {
428 float a00 = m[0][0], a01 = m[0][1], a02 = m[0][2];
429 float a10 = m[1][0], a11 = m[1][1], a12 = m[1][2];
430 float a20 = m[2][0], a21 = m[2][1], a22 = m[2][2];
431 float b01 = a22*a11 - a12*a21;
432 float b11 = -a22*a10 + a12*a20;
433 float b21 = a21*a10 - a11*a20;
434 float det = a00*b01 + a01*b11 + a02*b21;
435 return float3x3(b01, (-a22*a01 + a02*a21), ( a12*a01 - a02*a11),
436 b11, ( a22*a00 - a02*a20), (-a12*a00 + a02*a10),
437 b21, (-a21*a00 + a01*a20), ( a11*a00 - a01*a10)) * (1/det);
438}
439)";
440
441static constexpr char kInverse4x4[] = R"(
442float4x4 float4x4_inverse(float4x4 m) {
443 float a00 = m[0][0], a01 = m[0][1], a02 = m[0][2], a03 = m[0][3];
444 float a10 = m[1][0], a11 = m[1][1], a12 = m[1][2], a13 = m[1][3];
445 float a20 = m[2][0], a21 = m[2][1], a22 = m[2][2], a23 = m[2][3];
446 float a30 = m[3][0], a31 = m[3][1], a32 = m[3][2], a33 = m[3][3];
447 float b00 = a00*a11 - a01*a10;
448 float b01 = a00*a12 - a02*a10;
449 float b02 = a00*a13 - a03*a10;
450 float b03 = a01*a12 - a02*a11;
451 float b04 = a01*a13 - a03*a11;
452 float b05 = a02*a13 - a03*a12;
453 float b06 = a20*a31 - a21*a30;
454 float b07 = a20*a32 - a22*a30;
455 float b08 = a20*a33 - a23*a30;
456 float b09 = a21*a32 - a22*a31;
457 float b10 = a21*a33 - a23*a31;
458 float b11 = a22*a33 - a23*a32;
459 float det = b00*b11 - b01*b10 + b02*b09 + b03*b08 - b04*b07 + b05*b06;
460 return float4x4(a11*b11 - a12*b10 + a13*b09,
461 a02*b10 - a01*b11 - a03*b09,
462 a31*b05 - a32*b04 + a33*b03,
463 a22*b04 - a21*b05 - a23*b03,
464 a12*b08 - a10*b11 - a13*b07,
465 a00*b11 - a02*b08 + a03*b07,
466 a32*b02 - a30*b05 - a33*b01,
467 a20*b05 - a22*b02 + a23*b01,
468 a10*b10 - a11*b08 + a13*b06,
469 a01*b08 - a00*b10 - a03*b06,
470 a30*b04 - a31*b02 + a33*b00,
471 a21*b02 - a20*b04 - a23*b00,
472 a11*b07 - a10*b09 - a12*b06,
473 a00*b09 - a01*b07 + a02*b06,
474 a31*b01 - a30*b03 - a32*b00,
475 a20*b03 - a21*b01 + a22*b00) * (1/det);
476}
477)";
478
John Stilesd7199b22020-12-30 16:22:58 -0500479String MetalCodeGenerator::getInversePolyfill(const ExpressionArray& arguments) {
480 // Only use polyfills for a function taking a single-argument square matrix.
481 if (arguments.size() == 1) {
482 const Type& type = arguments.front()->type();
483 if (type.isMatrix() && type.rows() == type.columns()) {
484 // Inject the correct polyfill based on the matrix size.
485 String name = this->typeName(type) + "_inverse";
486 auto [iter, didInsert] = fWrittenIntrinsics.insert(name);
487 if (didInsert) {
488 switch (type.rows()) {
489 case 2:
490 fExtraFunctions.writeText(kInverse2x2);
491 break;
492 case 3:
493 fExtraFunctions.writeText(kInverse3x3);
494 break;
495 case 4:
496 fExtraFunctions.writeText(kInverse4x4);
497 break;
498 }
499 }
500 return name;
Chris Daltondba7aab2018-11-15 10:57:49 -0500501 }
502 }
John Stilesd7199b22020-12-30 16:22:58 -0500503 // This isn't the built-in `inverse`. We don't want to polyfill it at all.
504 return "inverse";
Chris Daltondba7aab2018-11-15 10:57:49 -0500505}
506
Brian Osman93aed9a2020-12-28 15:18:46 -0500507static constexpr char kMatrixCompMult[] = R"(
508template <int C, int R>
509matrix<float, C, R> matrixCompMult(matrix<float, C, R> a, matrix<float, C, R> b) {
510 matrix<float, C, R> result;
511 for (int c = 0; c < C; ++c) {
512 result[c] = a[c] * b[c];
513 }
514 return result;
515}
516)";
517
518void MetalCodeGenerator::writeMatrixCompMult() {
519 String name = "matrixCompMult";
520 if (fWrittenIntrinsics.find(name) == fWrittenIntrinsics.end()) {
521 fWrittenIntrinsics.insert(name);
522 fExtraFunctions.writeText(kMatrixCompMult);
523 }
524}
525
John Stiles86424eb2020-12-11 11:17:14 -0500526String MetalCodeGenerator::getTempVariable(const Type& type) {
527 String tempVar = "_skTemp" + to_string(fVarCount++);
528 this->fFunctionHeader += " " + this->typeName(type) + " " + tempVar + ";\n";
529 return tempVar;
530}
531
John Stiles791c27d2020-12-30 14:56:57 -0500532void MetalCodeGenerator::writeSimpleIntrinsic(const FunctionCall& c) {
533 // Write out an intrinsic function call exactly as-is. No muss no fuss.
534 this->write(c.function().name());
John Stilesd7199b22020-12-30 16:22:58 -0500535 this->writeArgumentList(c.arguments());
536}
537
538void MetalCodeGenerator::writeArgumentList(const ExpressionArray& arguments) {
John Stiles791c27d2020-12-30 14:56:57 -0500539 this->write("(");
540 const char* separator = "";
John Stilesd7199b22020-12-30 16:22:58 -0500541 for (const std::unique_ptr<Expression>& arg : arguments) {
John Stiles791c27d2020-12-30 14:56:57 -0500542 this->write(separator);
543 separator = ", ";
Brian Osman00185012021-02-04 16:07:11 -0500544 this->writeExpression(*arg, Precedence::kSequence);
John Stiles791c27d2020-12-30 14:56:57 -0500545 }
546 this->write(")");
547}
548
John Stilesd7199b22020-12-30 16:22:58 -0500549void MetalCodeGenerator::writeIntrinsicCall(const FunctionCall& c, IntrinsicKind kind) {
John Stiles8e3b6be2020-10-13 11:14:08 -0400550 const ExpressionArray& arguments = c.arguments();
Timothy Liang6403b0e2018-05-17 10:40:04 -0400551 switch (kind) {
John Stilesd7199b22020-12-30 16:22:58 -0500552 case kTexture_IntrinsicKind: {
Brian Osman00185012021-02-04 16:07:11 -0500553 this->writeExpression(*arguments[0], Precedence::kSequence);
Timothy Lianga06f2152018-05-24 15:33:31 -0400554 this->write(".sample(");
Brian Osman00185012021-02-04 16:07:11 -0500555 this->writeExpression(*arguments[0], Precedence::kSequence);
Timothy Lianga06f2152018-05-24 15:33:31 -0400556 this->write(SAMPLER_SUFFIX);
557 this->write(", ");
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400558 const Type& arg1Type = arguments[1]->type();
John Stiles54e7c052021-01-11 14:22:36 -0500559 if (arg1Type == *fContext.fTypes.fFloat3) {
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500560 // have to store the vector in a temp variable to avoid double evaluating it
John Stiles86424eb2020-12-11 11:17:14 -0500561 String tmpVar = this->getTempVariable(arg1Type);
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500562 this->write("(" + tmpVar + " = ");
Brian Osman00185012021-02-04 16:07:11 -0500563 this->writeExpression(*arguments[1], Precedence::kSequence);
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500564 this->write(", " + tmpVar + ".xy / " + tmpVar + ".z))");
Timothy Liangee84fe12018-05-18 14:38:19 -0400565 } else {
John Stiles54e7c052021-01-11 14:22:36 -0500566 SkASSERT(arg1Type == *fContext.fTypes.fFloat2);
Brian Osman00185012021-02-04 16:07:11 -0500567 this->writeExpression(*arguments[1], Precedence::kSequence);
Timothy Liangee84fe12018-05-18 14:38:19 -0400568 this->write(")");
569 }
Timothy Liang6403b0e2018-05-17 10:40:04 -0400570 break;
Ethan Nicholas30d30222020-09-11 12:27:26 -0400571 }
John Stilesd7199b22020-12-30 16:22:58 -0500572 case kMod_IntrinsicKind: {
Timothy Liang651286f2018-06-07 09:55:33 -0400573 // fmod(x, y) in metal calculates x - y * trunc(x / y) instead of x - y * floor(x / y)
John Stiles86424eb2020-12-11 11:17:14 -0500574 String tmpX = this->getTempVariable(arguments[0]->type());
John Stiles61b2e812020-12-30 18:27:31 -0500575 String tmpY = this->getTempVariable(arguments[1]->type());
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500576 this->write("(" + tmpX + " = ");
Brian Osman00185012021-02-04 16:07:11 -0500577 this->writeExpression(*arguments[0], Precedence::kSequence);
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500578 this->write(", " + tmpY + " = ");
Brian Osman00185012021-02-04 16:07:11 -0500579 this->writeExpression(*arguments[1], Precedence::kSequence);
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500580 this->write(", " + tmpX + " - " + tmpY + " * floor(" + tmpX + " / " + tmpY + "))");
Timothy Liang651286f2018-06-07 09:55:33 -0400581 break;
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500582 }
Brian Osman46787d52020-11-24 14:18:23 -0500583 // GLSL declares scalar versions of most geometric intrinsics, but these don't exist in MSL
John Stilesd7199b22020-12-30 16:22:58 -0500584 case kDistance_IntrinsicKind: {
Brian Osman46787d52020-11-24 14:18:23 -0500585 if (arguments[0]->type().columns() == 1) {
586 this->write("abs(");
Brian Osman00185012021-02-04 16:07:11 -0500587 this->writeExpression(*arguments[0], Precedence::kAdditive);
Brian Osman46787d52020-11-24 14:18:23 -0500588 this->write(" - ");
Brian Osman00185012021-02-04 16:07:11 -0500589 this->writeExpression(*arguments[1], Precedence::kAdditive);
Brian Osman46787d52020-11-24 14:18:23 -0500590 this->write(")");
591 } else {
John Stiles791c27d2020-12-30 14:56:57 -0500592 this->writeSimpleIntrinsic(c);
Brian Osman46787d52020-11-24 14:18:23 -0500593 }
594 break;
595 }
John Stilesd7199b22020-12-30 16:22:58 -0500596 case kDot_IntrinsicKind: {
Brian Osman46787d52020-11-24 14:18:23 -0500597 if (arguments[0]->type().columns() == 1) {
598 this->write("(");
Brian Osman00185012021-02-04 16:07:11 -0500599 this->writeExpression(*arguments[0], Precedence::kMultiplicative);
Brian Osman46787d52020-11-24 14:18:23 -0500600 this->write(" * ");
Brian Osman00185012021-02-04 16:07:11 -0500601 this->writeExpression(*arguments[1], Precedence::kMultiplicative);
Brian Osman46787d52020-11-24 14:18:23 -0500602 this->write(")");
603 } else {
John Stiles791c27d2020-12-30 14:56:57 -0500604 this->writeSimpleIntrinsic(c);
Brian Osman46787d52020-11-24 14:18:23 -0500605 }
606 break;
607 }
John Stilesd7199b22020-12-30 16:22:58 -0500608 case kFaceforward_IntrinsicKind: {
John Stilesad0571f2020-12-10 18:03:10 -0500609 if (arguments[0]->type().columns() == 1) {
610 // ((((Nref) * (I) < 0) ? 1 : -1) * (N))
611 this->write("((((");
Brian Osman00185012021-02-04 16:07:11 -0500612 this->writeExpression(*arguments[2], Precedence::kSequence);
John Stilesad0571f2020-12-10 18:03:10 -0500613 this->write(") * (");
Brian Osman00185012021-02-04 16:07:11 -0500614 this->writeExpression(*arguments[1], Precedence::kSequence);
John Stilesad0571f2020-12-10 18:03:10 -0500615 this->write(") < 0) ? 1 : -1) * (");
Brian Osman00185012021-02-04 16:07:11 -0500616 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stilesad0571f2020-12-10 18:03:10 -0500617 this->write("))");
618 } else {
John Stiles791c27d2020-12-30 14:56:57 -0500619 this->writeSimpleIntrinsic(c);
John Stilesad0571f2020-12-10 18:03:10 -0500620 }
621 break;
622 }
John Stilesd7199b22020-12-30 16:22:58 -0500623 case kLength_IntrinsicKind: {
Brian Osman46787d52020-11-24 14:18:23 -0500624 this->write(arguments[0]->type().columns() == 1 ? "abs(" : "length(");
Brian Osman00185012021-02-04 16:07:11 -0500625 this->writeExpression(*arguments[0], Precedence::kSequence);
Brian Osman46787d52020-11-24 14:18:23 -0500626 this->write(")");
627 break;
628 }
John Stilesd7199b22020-12-30 16:22:58 -0500629 case kNormalize_IntrinsicKind: {
Brian Osman46787d52020-11-24 14:18:23 -0500630 this->write(arguments[0]->type().columns() == 1 ? "sign(" : "normalize(");
Brian Osman00185012021-02-04 16:07:11 -0500631 this->writeExpression(*arguments[0], Precedence::kSequence);
Brian Osman46787d52020-11-24 14:18:23 -0500632 this->write(")");
633 break;
634 }
John Stilesd7199b22020-12-30 16:22:58 -0500635 case kBitcast_IntrinsicKind: {
John Stiles0063a9f2020-12-10 18:01:45 -0500636 this->write(this->getBitcastIntrinsic(c.type()));
637 this->write("(");
Brian Osman00185012021-02-04 16:07:11 -0500638 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stiles0063a9f2020-12-10 18:01:45 -0500639 this->write(")");
640 break;
641 }
John Stilesd7199b22020-12-30 16:22:58 -0500642 case kDegrees_IntrinsicKind: {
John Stilese2d34f82020-12-10 18:02:02 -0500643 this->write("((");
Brian Osman00185012021-02-04 16:07:11 -0500644 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stilese2d34f82020-12-10 18:02:02 -0500645 this->write(") * 57.2957795)");
646 break;
647 }
John Stilesd7199b22020-12-30 16:22:58 -0500648 case kRadians_IntrinsicKind: {
John Stilese2d34f82020-12-10 18:02:02 -0500649 this->write("((");
Brian Osman00185012021-02-04 16:07:11 -0500650 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stilese2d34f82020-12-10 18:02:02 -0500651 this->write(") * 0.0174532925)");
652 break;
653 }
John Stilesd7199b22020-12-30 16:22:58 -0500654 case kDFdx_IntrinsicKind: {
655 this->write("dfdx");
656 this->writeArgumentList(c.arguments());
657 break;
658 }
659 case kDFdy_IntrinsicKind: {
660 // Flipping Y also negates the Y derivatives.
John Stiles270cec22021-02-17 12:59:36 -0500661 if (fProgram.fConfig->fSettings.fFlipY) {
John Stilesd7199b22020-12-30 16:22:58 -0500662 this->write("-");
663 }
664 this->write("dfdy");
665 this->writeArgumentList(c.arguments());
666 break;
667 }
668 case kInverse_IntrinsicKind: {
669 this->write(this->getInversePolyfill(arguments));
670 this->writeArgumentList(c.arguments());
671 break;
672 }
673 case kInversesqrt_IntrinsicKind: {
674 this->write("rsqrt");
675 this->writeArgumentList(c.arguments());
676 break;
677 }
678 case kAtan_IntrinsicKind: {
679 this->write(c.arguments().size() == 2 ? "atan2" : "atan");
680 this->writeArgumentList(c.arguments());
681 break;
682 }
683 case kReflect_IntrinsicKind: {
John Stiles791c27d2020-12-30 14:56:57 -0500684 if (arguments[0]->type().columns() == 1) {
685 // We need to synthesize `I - 2 * N * I * N`.
686 String tmpI = this->getTempVariable(arguments[0]->type());
687 String tmpN = this->getTempVariable(arguments[1]->type());
688
689 // (_skTempI = ...
690 this->write("(" + tmpI + " = ");
Brian Osman00185012021-02-04 16:07:11 -0500691 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stiles791c27d2020-12-30 14:56:57 -0500692
693 // , _skTempN = ...
694 this->write(", " + tmpN + " = ");
Brian Osman00185012021-02-04 16:07:11 -0500695 this->writeExpression(*arguments[1], Precedence::kSequence);
John Stiles791c27d2020-12-30 14:56:57 -0500696
697 // , _skTempI - 2 * _skTempN * _skTempI * _skTempN)
698 this->write(", " + tmpI + " - 2 * " + tmpN + " * " + tmpI + " * " + tmpN + ")");
699 } else {
700 this->writeSimpleIntrinsic(c);
701 }
702 break;
703 }
John Stilesd7199b22020-12-30 16:22:58 -0500704 case kRefract_IntrinsicKind: {
John Stiles4b783d62020-12-30 14:58:07 -0500705 if (arguments[0]->type().columns() == 1) {
706 // Metal does implement refract for vectors; rather than reimplementing refract from
707 // scratch, we can replace the call with `refract(float2(I,0), float2(N,0), eta).x`.
708 this->write("(refract(float2(");
Brian Osman00185012021-02-04 16:07:11 -0500709 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stiles4b783d62020-12-30 14:58:07 -0500710 this->write(", 0), float2(");
Brian Osman00185012021-02-04 16:07:11 -0500711 this->writeExpression(*arguments[1], Precedence::kSequence);
John Stiles4b783d62020-12-30 14:58:07 -0500712 this->write(", 0), ");
Brian Osman00185012021-02-04 16:07:11 -0500713 this->writeExpression(*arguments[2], Precedence::kSequence);
John Stiles4b783d62020-12-30 14:58:07 -0500714 this->write(").x)");
715 } else {
716 this->writeSimpleIntrinsic(c);
717 }
718 break;
719 }
John Stiles23456532020-12-30 18:12:48 -0500720 case kRoundEven_IntrinsicKind: {
721 this->write("rint");
722 this->writeArgumentList(c.arguments());
723 break;
724 }
John Stilesd7199b22020-12-30 16:22:58 -0500725 case kBitCount_IntrinsicKind: {
John Stilese7dc7cb2020-12-22 15:37:14 -0500726 this->write("popcount(");
Brian Osman00185012021-02-04 16:07:11 -0500727 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stilese7dc7cb2020-12-22 15:37:14 -0500728 this->write(")");
729 break;
730 }
John Stilesd7199b22020-12-30 16:22:58 -0500731 case kFindLSB_IntrinsicKind: {
John Stiles86424eb2020-12-11 11:17:14 -0500732 // Create a temp variable to store the expression, to avoid double-evaluating it.
733 String skTemp = this->getTempVariable(arguments[0]->type());
734 String exprType = this->typeName(arguments[0]->type());
735
736 // ctz returns numbits(type) on zero inputs; GLSL documents it as generating -1 instead.
737 // Use select to detect zero inputs and force a -1 result.
738
739 // (_skTemp1 = (.....), select(ctz(_skTemp1), int4(-1), _skTemp1 == int4(0)))
740 this->write("(");
741 this->write(skTemp);
742 this->write(" = (");
Brian Osman00185012021-02-04 16:07:11 -0500743 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stiles86424eb2020-12-11 11:17:14 -0500744 this->write("), select(ctz(");
745 this->write(skTemp);
746 this->write("), ");
747 this->write(exprType);
748 this->write("(-1), ");
749 this->write(skTemp);
750 this->write(" == ");
751 this->write(exprType);
752 this->write("(0)))");
753 break;
754 }
John Stilesd7199b22020-12-30 16:22:58 -0500755 case kFindMSB_IntrinsicKind: {
John Stiles9685e522020-12-14 11:52:14 -0500756 // Create a temp variable to store the expression, to avoid double-evaluating it.
757 String skTemp1 = this->getTempVariable(arguments[0]->type());
758 String exprType = this->typeName(arguments[0]->type());
759
760 // GLSL findMSB is actually quite different from Metal's clz:
761 // - For signed negative numbers, it returns the first zero bit, not the first one bit!
762 // - For an empty input (0/~0 depending on sign), findMSB gives -1; clz is numbits(type)
763
764 // (_skTemp1 = (.....),
765 this->write("(");
766 this->write(skTemp1);
767 this->write(" = (");
Brian Osman00185012021-02-04 16:07:11 -0500768 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stiles9685e522020-12-14 11:52:14 -0500769 this->write("), ");
770
771 // Signed input types might be negative; we need another helper variable to negate the
772 // input (since we can only find one bits, not zero bits).
773 String skTemp2;
774 if (arguments[0]->type().isSigned()) {
775 // ... _skTemp2 = (select(_skTemp1, ~_skTemp1, _skTemp1 < 0)),
776 skTemp2 = this->getTempVariable(arguments[0]->type());
777 this->write(skTemp2);
778 this->write(" = (select(");
779 this->write(skTemp1);
780 this->write(", ~");
781 this->write(skTemp1);
782 this->write(", ");
783 this->write(skTemp1);
784 this->write(" < 0)), ");
785 } else {
786 skTemp2 = skTemp1;
787 }
788
789 // ... select(int4(clz(_skTemp2)), int4(-1), _skTemp2 == int4(0)))
790 this->write("select(");
791 this->write(this->typeName(c.type()));
792 this->write("(clz(");
793 this->write(skTemp2);
794 this->write(")), ");
795 this->write(this->typeName(c.type()));
796 this->write("(-1), ");
797 this->write(skTemp2);
798 this->write(" == ");
799 this->write(exprType);
800 this->write("(0)))");
801 break;
802 }
John Stilesd7199b22020-12-30 16:22:58 -0500803 case kMatrixCompMult_IntrinsicKind: {
804 this->writeMatrixCompMult();
805 this->writeSimpleIntrinsic(c);
806 break;
807 }
808 case kCompareEqual_IntrinsicKind:
809 case kCompareGreaterThan_IntrinsicKind:
810 case kCompareGreaterThanEqual_IntrinsicKind:
811 case kCompareLessThan_IntrinsicKind:
812 case kCompareLessThanEqual_IntrinsicKind:
813 case kCompareNotEqual_IntrinsicKind: {
814 this->write("(");
Brian Osman00185012021-02-04 16:07:11 -0500815 this->writeExpression(*c.arguments()[0], Precedence::kRelational);
John Stilesd7199b22020-12-30 16:22:58 -0500816 switch (kind) {
817 case kCompareEqual_IntrinsicKind:
818 this->write(" == ");
819 break;
820 case kCompareNotEqual_IntrinsicKind:
821 this->write(" != ");
822 break;
823 case kCompareLessThan_IntrinsicKind:
824 this->write(" < ");
825 break;
826 case kCompareLessThanEqual_IntrinsicKind:
827 this->write(" <= ");
828 break;
829 case kCompareGreaterThan_IntrinsicKind:
830 this->write(" > ");
831 break;
832 case kCompareGreaterThanEqual_IntrinsicKind:
833 this->write(" >= ");
834 break;
835 default:
John Stilesf57207b2021-02-02 17:50:34 -0500836 SK_ABORT("unsupported comparison intrinsic kind");
John Stilesd7199b22020-12-30 16:22:58 -0500837 }
Brian Osman00185012021-02-04 16:07:11 -0500838 this->writeExpression(*c.arguments()[1], Precedence::kRelational);
John Stilesd7199b22020-12-30 16:22:58 -0500839 this->write(")");
840 break;
841 }
Timothy Liang6403b0e2018-05-17 10:40:04 -0400842 default:
John Stilesf57207b2021-02-02 17:50:34 -0500843 SK_ABORT("unsupported intrinsic kind");
Timothy Liang6403b0e2018-05-17 10:40:04 -0400844 }
845}
846
John Stilesfcf8cb22020-08-06 14:29:22 -0400847// Assembles a matrix of type floatRxC by resizing another matrix named `x0`.
848// Cells that don't exist in the source matrix will be populated with identity-matrix values.
849void MetalCodeGenerator::assembleMatrixFromMatrix(const Type& sourceMatrix, int rows, int columns) {
850 SkASSERT(rows <= 4);
851 SkASSERT(columns <= 4);
852
853 const char* columnSeparator = "";
854 for (int c = 0; c < columns; ++c) {
855 fExtraFunctions.printf("%sfloat%d(", columnSeparator, rows);
856 columnSeparator = "), ";
857
858 // Determine how many values to take from the source matrix for this row.
859 int swizzleLength = 0;
860 if (c < sourceMatrix.columns()) {
861 swizzleLength = std::min<>(rows, sourceMatrix.rows());
862 }
863
864 // Emit all the values from the source matrix row.
865 bool firstItem;
866 switch (swizzleLength) {
867 case 0: firstItem = true; break;
868 case 1: firstItem = false; fExtraFunctions.printf("x0[%d].x", c); break;
869 case 2: firstItem = false; fExtraFunctions.printf("x0[%d].xy", c); break;
870 case 3: firstItem = false; fExtraFunctions.printf("x0[%d].xyz", c); break;
871 case 4: firstItem = false; fExtraFunctions.printf("x0[%d].xyzw", c); break;
872 default: SkUNREACHABLE;
873 }
874
875 // Emit the placeholder identity-matrix cells.
876 for (int r = swizzleLength; r < rows; ++r) {
877 fExtraFunctions.printf("%s%s", firstItem ? "" : ", ", (r == c) ? "1.0" : "0.0");
878 firstItem = false;
879 }
880 }
881
882 fExtraFunctions.writeText(")");
883}
884
885// Assembles a matrix of type floatRxC by concatenating an arbitrary mix of values, named `x0`,
886// `x1`, etc. An error is written if the expression list don't contain exactly R*C scalars.
John Stiles8e3b6be2020-10-13 11:14:08 -0400887void MetalCodeGenerator::assembleMatrixFromExpressions(const ExpressionArray& args,
888 int rows, int columns) {
John Stilesfcf8cb22020-08-06 14:29:22 -0400889 size_t argIndex = 0;
890 int argPosition = 0;
891
892 const char* columnSeparator = "";
893 for (int c = 0; c < columns; ++c) {
894 fExtraFunctions.printf("%sfloat%d(", columnSeparator, rows);
895 columnSeparator = "), ";
896
897 const char* rowSeparator = "";
898 for (int r = 0; r < rows; ++r) {
899 fExtraFunctions.writeText(rowSeparator);
900 rowSeparator = ", ";
901
902 if (argIndex < args.size()) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400903 const Type& argType = args[argIndex]->type();
Ethan Nicholase6592142020-09-08 10:22:09 -0400904 switch (argType.typeKind()) {
905 case Type::TypeKind::kScalar: {
John Stilesfcf8cb22020-08-06 14:29:22 -0400906 fExtraFunctions.printf("x%zu", argIndex);
907 break;
908 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400909 case Type::TypeKind::kVector: {
John Stilesfcf8cb22020-08-06 14:29:22 -0400910 fExtraFunctions.printf("x%zu[%d]", argIndex, argPosition);
911 break;
912 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400913 case Type::TypeKind::kMatrix: {
John Stilesfcf8cb22020-08-06 14:29:22 -0400914 fExtraFunctions.printf("x%zu[%d][%d]", argIndex,
915 argPosition / argType.rows(),
916 argPosition % argType.rows());
917 break;
918 }
919 default: {
920 SkDEBUGFAIL("incorrect type of argument for matrix constructor");
921 fExtraFunctions.writeText("<error>");
922 break;
923 }
924 }
925
926 ++argPosition;
927 if (argPosition >= argType.columns() * argType.rows()) {
928 ++argIndex;
929 argPosition = 0;
930 }
931 } else {
932 SkDEBUGFAIL("not enough arguments for matrix constructor");
933 fExtraFunctions.writeText("<error>");
934 }
935 }
936 }
937
938 if (argPosition != 0 || argIndex != args.size()) {
939 SkDEBUGFAIL("incorrect number of arguments for matrix constructor");
940 fExtraFunctions.writeText(", <error>");
941 }
942
943 fExtraFunctions.writeText(")");
944}
945
John Stiles1bdafbf2020-05-28 12:17:20 -0400946// Generates a constructor for 'matrix' which reorganizes the input arguments into the proper shape.
947// Keeps track of previously generated constructors so that we won't generate more than one
948// constructor for any given permutation of input argument types. Returns the name of the
949// generated constructor method.
950String MetalCodeGenerator::getMatrixConstructHelper(const Constructor& c) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400951 const Type& matrix = c.type();
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500952 int columns = matrix.columns();
953 int rows = matrix.rows();
John Stiles8e3b6be2020-10-13 11:14:08 -0400954 const ExpressionArray& args = c.arguments();
John Stiles1bdafbf2020-05-28 12:17:20 -0400955
956 // Create the helper-method name and use it as our lookup key.
957 String name;
958 name.appendf("float%dx%d_from", columns, rows);
959 for (const std::unique_ptr<Expression>& expr : args) {
John Stiles36129132020-12-29 12:28:04 -0500960 name.appendf("_%s", this->typeName(expr->type()).c_str());
John Stiles1bdafbf2020-05-28 12:17:20 -0400961 }
962
963 // If a helper-method has already been synthesized, we don't need to synthesize it again.
964 auto [iter, newlyCreated] = fHelpers.insert(name);
965 if (!newlyCreated) {
966 return name;
967 }
968
969 // Unlike GLSL, Metal requires that matrices are initialized with exactly R vectors of C
970 // components apiece. (In Metal 2.0, you can also supply R*C scalars, but you still cannot
971 // supply a mixture of scalars and vectors.)
972 fExtraFunctions.printf("float%dx%d %s(", columns, rows, name.c_str());
973
974 size_t argIndex = 0;
975 const char* argSeparator = "";
John Stilesfcf8cb22020-08-06 14:29:22 -0400976 for (const std::unique_ptr<Expression>& expr : args) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400977 fExtraFunctions.printf("%s%s x%zu", argSeparator,
John Stiles36129132020-12-29 12:28:04 -0500978 this->typeName(expr->type()).c_str(), argIndex++);
John Stiles1bdafbf2020-05-28 12:17:20 -0400979 argSeparator = ", ";
980 }
981
982 fExtraFunctions.printf(") {\n return float%dx%d(", columns, rows);
983
John Stiles9aeed132020-11-24 17:36:06 -0500984 if (args.size() == 1 && args.front()->type().isMatrix()) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400985 this->assembleMatrixFromMatrix(args.front()->type(), rows, columns);
John Stilesfcf8cb22020-08-06 14:29:22 -0400986 } else {
987 this->assembleMatrixFromExpressions(args, rows, columns);
John Stiles1bdafbf2020-05-28 12:17:20 -0400988 }
989
John Stilesfcf8cb22020-08-06 14:29:22 -0400990 fExtraFunctions.writeText(");\n}\n");
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500991 return name;
992}
993
994bool MetalCodeGenerator::canCoerce(const Type& t1, const Type& t2) {
995 if (t1.columns() != t2.columns() || t1.rows() != t2.rows()) {
996 return false;
997 }
998 if (t1.columns() > 1) {
999 return this->canCoerce(t1.componentType(), t2.componentType());
1000 }
Ethan Nicholase1f55022019-02-05 17:17:40 -05001001 return t1.isFloat() && t2.isFloat();
Ethan Nicholas842d31b2019-01-22 10:59:11 -05001002}
1003
John Stiles1bdafbf2020-05-28 12:17:20 -04001004bool MetalCodeGenerator::matrixConstructHelperIsNeeded(const Constructor& c) {
1005 // A matrix construct helper is only necessary if we are, in fact, constructing a matrix.
John Stiles9aeed132020-11-24 17:36:06 -05001006 if (!c.type().isMatrix()) {
John Stiles1bdafbf2020-05-28 12:17:20 -04001007 return false;
Ethan Nicholas842d31b2019-01-22 10:59:11 -05001008 }
John Stiles1bdafbf2020-05-28 12:17:20 -04001009
1010 // GLSL is fairly free-form about inputs to its matrix constructors, but Metal is not; it
1011 // expects exactly R vectors of C components apiece. (Metal 2.0 also allows a list of R*C
1012 // scalars.) Some cases are simple to translate and so we handle those inline--e.g. a list of
1013 // scalars can be constructed trivially. In more complex cases, we generate a helper function
1014 // that converts our inputs into a properly-shaped matrix.
1015 // A matrix construct helper method is always used if any input argument is a matrix.
1016 // Helper methods are also necessary when any argument would span multiple rows. For instance:
1017 //
1018 // float2 x = (1, 2);
1019 // float3x2(x, 3, 4, 5, 6) = | 1 3 5 | = no helper needed; conversion can be done inline
1020 // | 2 4 6 |
1021 //
1022 // float2 x = (2, 3);
1023 // float3x2(1, x, 4, 5, 6) = | 1 3 5 | = x spans multiple rows; a helper method will be used
1024 // | 2 4 6 |
1025 //
1026 // float4 x = (1, 2, 3, 4);
1027 // float2x2(x) = | 1 3 | = x spans multiple rows; a helper method will be used
1028 // | 2 4 |
1029 //
1030
1031 int position = 0;
Ethan Nicholasf70f0442020-09-29 12:41:35 -04001032 for (const std::unique_ptr<Expression>& expr : c.arguments()) {
John Stiles1bdafbf2020-05-28 12:17:20 -04001033 // If an input argument is a matrix, we need a helper function.
John Stiles9aeed132020-11-24 17:36:06 -05001034 if (expr->type().isMatrix()) {
John Stiles1bdafbf2020-05-28 12:17:20 -04001035 return true;
1036 }
Ethan Nicholas30d30222020-09-11 12:27:26 -04001037 position += expr->type().columns();
1038 if (position > c.type().rows()) {
John Stiles1bdafbf2020-05-28 12:17:20 -04001039 // An input argument would span multiple rows; a helper function is required.
1040 return true;
1041 }
Ethan Nicholas30d30222020-09-11 12:27:26 -04001042 if (position == c.type().rows()) {
John Stiles1bdafbf2020-05-28 12:17:20 -04001043 // We've advanced to the end of a row. Wrap to the start of the next row.
1044 position = 0;
1045 }
1046 }
1047
1048 return false;
1049}
1050
1051void MetalCodeGenerator::writeConstructor(const Constructor& c, Precedence parentPrecedence) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001052 const Type& constructorType = c.type();
John Stiles7384b372021-04-01 13:48:15 -04001053 SkASSERT(!constructorType.isArray());
1054
John Stiles1bdafbf2020-05-28 12:17:20 -04001055 // Handle special cases for single-argument constructors.
Ethan Nicholasf70f0442020-09-29 12:41:35 -04001056 if (c.arguments().size() == 1) {
John Stiles1bdafbf2020-05-28 12:17:20 -04001057 // If the type is coercible, emit it directly.
Ethan Nicholasf70f0442020-09-29 12:41:35 -04001058 const Expression& arg = *c.arguments().front();
Ethan Nicholas30d30222020-09-11 12:27:26 -04001059 const Type& argType = arg.type();
1060 if (this->canCoerce(constructorType, argType)) {
John Stiles1bdafbf2020-05-28 12:17:20 -04001061 this->writeExpression(arg, parentPrecedence);
1062 return;
1063 }
1064
1065 // Metal supports creating matrices with a scalar on the diagonal via the single-argument
1066 // matrix constructor.
John Stiles9aeed132020-11-24 17:36:06 -05001067 if (constructorType.isMatrix() && argType.isNumber()) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001068 const Type& matrix = constructorType;
John Stiles1bdafbf2020-05-28 12:17:20 -04001069 this->write("float");
1070 this->write(to_string(matrix.columns()));
1071 this->write("x");
1072 this->write(to_string(matrix.rows()));
1073 this->write("(");
1074 this->writeExpression(arg, parentPrecedence);
1075 this->write(")");
1076 return;
1077 }
1078 }
1079
1080 // Emit and invoke a matrix-constructor helper method if one is necessary.
1081 if (this->matrixConstructHelperIsNeeded(c)) {
1082 this->write(this->getMatrixConstructHelper(c));
John Stiles1fa15b12020-05-28 17:36:54 +00001083 this->write("(");
1084 const char* separator = "";
Ethan Nicholasf70f0442020-09-29 12:41:35 -04001085 for (const std::unique_ptr<Expression>& expr : c.arguments()) {
John Stiles1fa15b12020-05-28 17:36:54 +00001086 this->write(separator);
1087 separator = ", ";
Brian Osman00185012021-02-04 16:07:11 -05001088 this->writeExpression(*expr, Precedence::kSequence);
John Stilesdaa573e2020-05-28 12:17:20 -04001089 }
John Stiles1fa15b12020-05-28 17:36:54 +00001090 this->write(")");
John Stiles1bdafbf2020-05-28 12:17:20 -04001091 return;
John Stilesdaa573e2020-05-28 12:17:20 -04001092 }
John Stiles1bdafbf2020-05-28 12:17:20 -04001093
1094 // Explicitly invoke the constructor, passing in the necessary arguments.
John Stilesb4418502021-02-04 10:57:08 -05001095 this->writeType(constructorType);
John Stiles7384b372021-04-01 13:48:15 -04001096 this->write("(");
John Stiles1bdafbf2020-05-28 12:17:20 -04001097 const char* separator = "";
1098 int scalarCount = 0;
Ethan Nicholasf70f0442020-09-29 12:41:35 -04001099 for (const std::unique_ptr<Expression>& arg : c.arguments()) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001100 const Type& argType = arg->type();
John Stiles1bdafbf2020-05-28 12:17:20 -04001101 this->write(separator);
1102 separator = ", ";
John Stiles9aeed132020-11-24 17:36:06 -05001103 if (constructorType.isMatrix() &&
Ethan Nicholas30d30222020-09-11 12:27:26 -04001104 argType.columns() < constructorType.rows()) {
John Stiles1bdafbf2020-05-28 12:17:20 -04001105 // Merge scalars and smaller vectors together.
1106 if (!scalarCount) {
John Stilesb4418502021-02-04 10:57:08 -05001107 this->writeType(constructorType.componentType());
Ethan Nicholas30d30222020-09-11 12:27:26 -04001108 this->write(to_string(constructorType.rows()));
John Stiles1bdafbf2020-05-28 12:17:20 -04001109 this->write("(");
1110 }
Ethan Nicholas30d30222020-09-11 12:27:26 -04001111 scalarCount += argType.columns();
John Stiles1bdafbf2020-05-28 12:17:20 -04001112 }
Brian Osman00185012021-02-04 16:07:11 -05001113 this->writeExpression(*arg, Precedence::kSequence);
Ethan Nicholas30d30222020-09-11 12:27:26 -04001114 if (scalarCount && scalarCount == constructorType.rows()) {
John Stiles1bdafbf2020-05-28 12:17:20 -04001115 this->write(")");
1116 scalarCount = 0;
1117 }
1118 }
John Stiles7384b372021-04-01 13:48:15 -04001119 this->write(")");
Ethan Nicholascc305772017-10-13 16:17:45 -04001120}
1121
John Stiles933043b2021-03-31 15:23:16 -04001122void MetalCodeGenerator::writeSingleArgumentConstructor(const SingleArgumentConstructor& c,
John Stilese1182782021-03-30 22:09:37 -04001123 Precedence parentPrecedence) {
1124 this->writeType(c.type());
1125 this->write("(");
1126 this->writeExpression(*c.argument(), Precedence::kSequence);
1127 this->write(")");
1128}
1129
John Stiles7384b372021-04-01 13:48:15 -04001130void MetalCodeGenerator::writeConstructorArray(const ConstructorArray& c,
1131 Precedence parentPrecedence) {
1132 this->writeType(c.type());
1133 this->write("{");
1134 const char* separator = "";
1135 for (const std::unique_ptr<Expression>& arg : c.arguments()) {
1136 this->write(separator);
1137 separator = ", ";
1138 this->writeExpression(*arg, Precedence::kSequence);
1139 }
1140 this->write("}");
1141}
1142
Ethan Nicholascc305772017-10-13 16:17:45 -04001143void MetalCodeGenerator::writeFragCoord() {
Ethan Nicholasf931e402019-07-26 15:40:33 -04001144 if (fRTHeightName.length()) {
1145 this->write("float4(_fragCoord.x, ");
1146 this->write(fRTHeightName.c_str());
1147 this->write(" - _fragCoord.y, 0.0, _fragCoord.w)");
Jim Van Verth6bc650e2019-02-07 14:53:23 -05001148 } else {
1149 this->write("float4(_fragCoord.x, _fragCoord.y, 0.0, _fragCoord.w)");
1150 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001151}
1152
1153void MetalCodeGenerator::writeVariableReference(const VariableReference& ref) {
John Stiles06b84ef2020-12-09 12:35:48 -05001154 // When assembling out-param helper functions, we copy variables into local clones with matching
John Stilesf7410bd2021-01-19 13:07:55 -05001155 // names. We never want to prepend "_in." or "_globals." when writing these variables since
John Stiles06b84ef2020-12-09 12:35:48 -05001156 // we're actually targeting the clones.
1157 if (fIgnoreVariableReferenceModifiers) {
1158 this->writeName(ref.variable()->name());
1159 return;
1160 }
1161
Ethan Nicholas78686922020-10-08 06:46:27 -04001162 switch (ref.variable()->modifiers().fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001163 case SK_FRAGCOLOR_BUILTIN:
John Stilesf7410bd2021-01-19 13:07:55 -05001164 this->write("_out.sk_FragColor");
Ethan Nicholascc305772017-10-13 16:17:45 -04001165 break;
Timothy Liang6403b0e2018-05-17 10:40:04 -04001166 case SK_FRAGCOORD_BUILTIN:
1167 this->writeFragCoord();
1168 break;
Timothy Liangdc89f192018-06-13 09:20:31 -04001169 case SK_VERTEXID_BUILTIN:
1170 this->write("sk_VertexID");
1171 break;
1172 case SK_INSTANCEID_BUILTIN:
1173 this->write("sk_InstanceID");
1174 break;
Timothy Liang7b8875d2018-08-10 09:42:31 -04001175 case SK_CLOCKWISE_BUILTIN:
1176 // We'd set the front facing winding in the MTLRenderCommandEncoder to be counter
Brian Salomonf4ba4ec2020-03-19 15:54:28 -04001177 // clockwise to match Skia convention.
John Stiles270cec22021-02-17 12:59:36 -05001178 this->write(fProgram.fConfig->fSettings.fFlipY ? "_frontFacing" : "(!_frontFacing)");
Timothy Liang7b8875d2018-08-10 09:42:31 -04001179 break;
Ethan Nicholascc305772017-10-13 16:17:45 -04001180 default:
Ethan Nicholas78686922020-10-08 06:46:27 -04001181 const Variable& var = *ref.variable();
Ethan Nicholas453f67f2020-10-09 10:43:45 -04001182 if (var.storage() == Variable::Storage::kGlobal) {
Ethan Nicholas78686922020-10-08 06:46:27 -04001183 if (var.modifiers().fFlags & Modifiers::kIn_Flag) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001184 this->write("_in.");
Ethan Nicholas78686922020-10-08 06:46:27 -04001185 } else if (var.modifiers().fFlags & Modifiers::kOut_Flag) {
John Stilesf7410bd2021-01-19 13:07:55 -05001186 this->write("_out.");
Ethan Nicholas78686922020-10-08 06:46:27 -04001187 } else if (var.modifiers().fFlags & Modifiers::kUniform_Flag &&
1188 var.type().typeKind() != Type::TypeKind::kSampler) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001189 this->write("_uniforms.");
1190 } else {
John Stilesf7410bd2021-01-19 13:07:55 -05001191 this->write("_globals.");
Ethan Nicholascc305772017-10-13 16:17:45 -04001192 }
1193 }
Ethan Nicholas78686922020-10-08 06:46:27 -04001194 this->writeName(var.name());
Ethan Nicholascc305772017-10-13 16:17:45 -04001195 }
1196}
1197
1198void MetalCodeGenerator::writeIndexExpression(const IndexExpression& expr) {
Brian Osman00185012021-02-04 16:07:11 -05001199 this->writeExpression(*expr.base(), Precedence::kPostfix);
Ethan Nicholascc305772017-10-13 16:17:45 -04001200 this->write("[");
Brian Osman00185012021-02-04 16:07:11 -05001201 this->writeExpression(*expr.index(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001202 this->write("]");
1203}
1204
1205void MetalCodeGenerator::writeFieldAccess(const FieldAccess& f) {
Ethan Nicholas7a95b202020-10-09 11:55:40 -04001206 const Type::Field* field = &f.base()->type().fields()[f.fieldIndex()];
1207 if (FieldAccess::OwnerKind::kDefault == f.ownerKind()) {
Brian Osman00185012021-02-04 16:07:11 -05001208 this->writeExpression(*f.base(), Precedence::kPostfix);
Ethan Nicholascc305772017-10-13 16:17:45 -04001209 this->write(".");
1210 }
Timothy Liang7d637782018-06-05 09:58:07 -04001211 switch (field->fModifiers.fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001212 case SK_POSITION_BUILTIN:
John Stilesf7410bd2021-01-19 13:07:55 -05001213 this->write("_out.sk_Position");
Ethan Nicholascc305772017-10-13 16:17:45 -04001214 break;
1215 default:
Timothy Liang7d637782018-06-05 09:58:07 -04001216 if (field->fName == "sk_PointSize") {
John Stilesf7410bd2021-01-19 13:07:55 -05001217 this->write("_out.sk_PointSize");
Timothy Liang7d637782018-06-05 09:58:07 -04001218 } else {
Ethan Nicholas7a95b202020-10-09 11:55:40 -04001219 if (FieldAccess::OwnerKind::kAnonymousInterfaceBlock == f.ownerKind()) {
John Stilesf7410bd2021-01-19 13:07:55 -05001220 this->write("_globals.");
Timothy Liang7d637782018-06-05 09:58:07 -04001221 this->write(fInterfaceBlockNameMap[fInterfaceBlockMap[field]]);
1222 this->write("->");
1223 }
Timothy Liang651286f2018-06-07 09:55:33 -04001224 this->writeName(field->fName);
Timothy Lianga06f2152018-05-24 15:33:31 -04001225 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001226 }
1227}
1228
1229void MetalCodeGenerator::writeSwizzle(const Swizzle& swizzle) {
Brian Osman00185012021-02-04 16:07:11 -05001230 this->writeExpression(*swizzle.base(), Precedence::kPostfix);
Ethan Nicholascc305772017-10-13 16:17:45 -04001231 this->write(".");
Ethan Nicholas6b4d5812020-10-12 16:11:51 -04001232 for (int c : swizzle.components()) {
Brian Osman25647672020-09-15 15:16:56 -04001233 SkASSERT(c >= 0 && c <= 3);
1234 this->write(&("x\0y\0z\0w\0"[c * 2]));
Ethan Nicholascc305772017-10-13 16:17:45 -04001235 }
1236}
1237
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001238void MetalCodeGenerator::writeMatrixTimesEqualHelper(const Type& left, const Type& right,
1239 const Type& result) {
John Stiles01cdf012021-02-10 09:53:41 -05001240 String key = "TimesEqual" + this->typeName(left) + ":" + this->typeName(right);
John Stiles56233d12021-02-03 13:03:29 -05001241
1242 auto [iter, wasInserted] = fHelpers.insert(key);
1243 if (wasInserted) {
John Stiles368db7c2020-12-29 11:20:08 -05001244 fExtraFunctions.printf("thread %s& operator*=(thread %s& left, thread const %s& right) {\n"
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001245 " left = left * right;\n"
1246 " return left;\n"
John Stiles368db7c2020-12-29 11:20:08 -05001247 "}\n",
1248 this->typeName(result).c_str(), this->typeName(left).c_str(),
1249 this->typeName(right).c_str());
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001250 }
1251}
1252
John Stiles01cdf012021-02-10 09:53:41 -05001253void MetalCodeGenerator::writeMatrixEqualityHelper(const Type& left, const Type& right) {
1254 SkASSERTF(left.rows() == right.rows() && left.columns() == right.columns(), "left=%s, right=%s",
1255 left.description().c_str(), right.description().c_str());
1256
1257 String key = "Equality" + this->typeName(left) + ":" + this->typeName(right);
1258
1259 auto [iter, wasInserted] = fHelpers.insert(key);
1260 if (wasInserted) {
1261 fExtraFunctions.printf(
1262 "thread bool operator==(const %s left, const %s right) {\n"
1263 " return",
1264 this->typeName(left).c_str(), this->typeName(right).c_str());
1265
1266 for (int index=0; index<left.columns(); ++index) {
1267 fExtraFunctions.printf("%s all(left[%d] == right[%d])",
1268 index == 0 ? "" : " &&", index, index);
1269 }
1270 fExtraFunctions.printf(";\n"
1271 "}\n");
1272 }
1273}
1274
1275void MetalCodeGenerator::writeMatrixInequalityHelper(const Type& left, const Type& right) {
1276 SkASSERTF(left.rows() == right.rows() && left.columns() == right.columns(), "left=%s, right=%s",
1277 left.description().c_str(), right.description().c_str());
1278
1279 String key = "Inequality" + this->typeName(left) + ":" + this->typeName(right);
1280
1281 auto [iter, wasInserted] = fHelpers.insert(key);
1282 if (wasInserted) {
1283 fExtraFunctions.printf(
1284 "thread bool operator!=(const %s left, const %s right) {\n"
1285 " return",
1286 this->typeName(left).c_str(), this->typeName(right).c_str());
1287
1288 for (int index=0; index<left.columns(); ++index) {
1289 fExtraFunctions.printf("%s any(left[%d] != right[%d])",
1290 index == 0 ? "" : " ||", index, index);
1291 }
1292 fExtraFunctions.printf(";\n"
1293 "}\n");
1294 }
1295}
1296
Ethan Nicholascc305772017-10-13 16:17:45 -04001297void MetalCodeGenerator::writeBinaryExpression(const BinaryExpression& b,
1298 Precedence parentPrecedence) {
John Stiles2d4f9592020-10-30 10:29:12 -04001299 const Expression& left = *b.left();
1300 const Expression& right = *b.right();
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001301 const Type& leftType = left.type();
1302 const Type& rightType = right.type();
John Stiles45990502021-02-16 10:55:27 -05001303 Operator op = b.getOperator();
1304 Precedence precedence = op.getBinaryPrecedence();
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001305 bool needParens = precedence >= parentPrecedence;
John Stiles45990502021-02-16 10:55:27 -05001306 switch (op.kind()) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001307 case Token::Kind::TK_EQEQ:
John Stiles9aeed132020-11-24 17:36:06 -05001308 if (leftType.isVector()) {
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001309 this->write("all");
1310 needParens = true;
1311 }
1312 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001313 case Token::Kind::TK_NEQ:
John Stiles9aeed132020-11-24 17:36:06 -05001314 if (leftType.isVector()) {
Jim Van Verth36477b42019-04-11 14:57:30 -04001315 this->write("any");
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001316 needParens = true;
1317 }
1318 break;
1319 default:
1320 break;
1321 }
1322 if (needParens) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001323 this->write("(");
1324 }
John Stiles01cdf012021-02-10 09:53:41 -05001325 if (leftType.isMatrix() && rightType.isMatrix()) {
John Stiles45990502021-02-16 10:55:27 -05001326 if (op.kind() == Token::Kind::TK_STAREQ) {
John Stiles01cdf012021-02-10 09:53:41 -05001327 this->writeMatrixTimesEqualHelper(leftType, rightType, b.type());
John Stiles45990502021-02-16 10:55:27 -05001328 } else if (op.kind() == Token::Kind::TK_EQEQ) {
John Stiles01cdf012021-02-10 09:53:41 -05001329 this->writeMatrixEqualityHelper(leftType, rightType);
John Stiles45990502021-02-16 10:55:27 -05001330 } else if (op.kind() == Token::Kind::TK_NEQ) {
John Stiles01cdf012021-02-10 09:53:41 -05001331 this->writeMatrixInequalityHelper(leftType, rightType);
1332 }
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001333 }
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001334 this->writeExpression(left, precedence);
John Stiles45990502021-02-16 10:55:27 -05001335 if (op.kind() != Token::Kind::TK_EQ && op.isAssignment() &&
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001336 left.kind() == Expression::Kind::kSwizzle && !left.hasSideEffects()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001337 // This doesn't compile in Metal:
1338 // float4 x = float4(1);
1339 // x.xy *= float2x2(...);
1340 // with the error message "non-const reference cannot bind to vector element",
1341 // but switching it to x.xy = x.xy * float2x2(...) fixes it. We perform this tranformation
1342 // as long as the LHS has no side effects, and hope for the best otherwise.
1343 this->write(" = ");
Brian Osman00185012021-02-04 16:07:11 -05001344 this->writeExpression(left, Precedence::kAssignment);
Ethan Nicholascc305772017-10-13 16:17:45 -04001345 this->write(" ");
John Stilesd6449e92020-11-30 09:13:23 -05001346 String opName = OperatorName(op);
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001347 SkASSERT(opName.endsWith("="));
1348 this->write(opName.substr(0, opName.size() - 1).c_str());
Ethan Nicholascc305772017-10-13 16:17:45 -04001349 this->write(" ");
1350 } else {
John Stilesd6449e92020-11-30 09:13:23 -05001351 this->write(String(" ") + OperatorName(op) + " ");
Ethan Nicholascc305772017-10-13 16:17:45 -04001352 }
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001353 this->writeExpression(right, precedence);
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001354 if (needParens) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001355 this->write(")");
1356 }
1357}
1358
1359void MetalCodeGenerator::writeTernaryExpression(const TernaryExpression& t,
1360 Precedence parentPrecedence) {
Brian Osman00185012021-02-04 16:07:11 -05001361 if (Precedence::kTernary >= parentPrecedence) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001362 this->write("(");
1363 }
Brian Osman00185012021-02-04 16:07:11 -05001364 this->writeExpression(*t.test(), Precedence::kTernary);
Ethan Nicholascc305772017-10-13 16:17:45 -04001365 this->write(" ? ");
Brian Osman00185012021-02-04 16:07:11 -05001366 this->writeExpression(*t.ifTrue(), Precedence::kTernary);
Ethan Nicholascc305772017-10-13 16:17:45 -04001367 this->write(" : ");
Brian Osman00185012021-02-04 16:07:11 -05001368 this->writeExpression(*t.ifFalse(), Precedence::kTernary);
1369 if (Precedence::kTernary >= parentPrecedence) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001370 this->write(")");
1371 }
1372}
1373
1374void MetalCodeGenerator::writePrefixExpression(const PrefixExpression& p,
1375 Precedence parentPrecedence) {
Brian Osman00185012021-02-04 16:07:11 -05001376 if (Precedence::kPrefix >= parentPrecedence) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001377 this->write("(");
1378 }
John Stilesd6449e92020-11-30 09:13:23 -05001379 this->write(OperatorName(p.getOperator()));
Brian Osman00185012021-02-04 16:07:11 -05001380 this->writeExpression(*p.operand(), Precedence::kPrefix);
1381 if (Precedence::kPrefix >= parentPrecedence) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001382 this->write(")");
1383 }
1384}
1385
1386void MetalCodeGenerator::writePostfixExpression(const PostfixExpression& p,
1387 Precedence parentPrecedence) {
Brian Osman00185012021-02-04 16:07:11 -05001388 if (Precedence::kPostfix >= parentPrecedence) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001389 this->write("(");
1390 }
Brian Osman00185012021-02-04 16:07:11 -05001391 this->writeExpression(*p.operand(), Precedence::kPostfix);
John Stilesd6449e92020-11-30 09:13:23 -05001392 this->write(OperatorName(p.getOperator()));
Brian Osman00185012021-02-04 16:07:11 -05001393 if (Precedence::kPostfix >= parentPrecedence) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001394 this->write(")");
1395 }
1396}
1397
1398void MetalCodeGenerator::writeBoolLiteral(const BoolLiteral& b) {
Ethan Nicholas59d660c2020-09-28 09:18:15 -04001399 this->write(b.value() ? "true" : "false");
Ethan Nicholascc305772017-10-13 16:17:45 -04001400}
1401
1402void MetalCodeGenerator::writeIntLiteral(const IntLiteral& i) {
John Stiles12739df2020-12-29 09:47:20 -05001403 const Type& type = i.type();
John Stiles54e7c052021-01-11 14:22:36 -05001404 if (type == *fContext.fTypes.fUInt) {
Ethan Nicholase96cdd12020-09-28 16:27:18 -04001405 this->write(to_string(i.value() & 0xffffffff) + "u");
John Stiles54e7c052021-01-11 14:22:36 -05001406 } else if (type == *fContext.fTypes.fUShort) {
John Stiles12739df2020-12-29 09:47:20 -05001407 this->write(to_string(i.value() & 0xffff) + "u");
John Stiles54e7c052021-01-11 14:22:36 -05001408 } else if (type == *fContext.fTypes.fUByte) {
John Stiles12739df2020-12-29 09:47:20 -05001409 this->write(to_string(i.value() & 0xff) + "u");
Ethan Nicholascc305772017-10-13 16:17:45 -04001410 } else {
John Stiles12739df2020-12-29 09:47:20 -05001411 this->write(to_string(i.value()));
Ethan Nicholascc305772017-10-13 16:17:45 -04001412 }
1413}
1414
1415void MetalCodeGenerator::writeFloatLiteral(const FloatLiteral& f) {
Ethan Nicholasa3f22f12020-10-01 12:13:17 -04001416 this->write(to_string(f.value()));
Ethan Nicholascc305772017-10-13 16:17:45 -04001417}
1418
1419void MetalCodeGenerator::writeSetting(const Setting& s) {
John Stilesf57207b2021-02-02 17:50:34 -05001420 SK_ABORT("internal error; setting was not folded to a constant during compilation\n");
Ethan Nicholascc305772017-10-13 16:17:45 -04001421}
1422
John Stiles06b84ef2020-12-09 12:35:48 -05001423void MetalCodeGenerator::writeFunctionRequirementArgs(const FunctionDeclaration& f,
1424 const char*& separator) {
1425 Requirements requirements = this->requirements(f);
1426 if (requirements & kInputs_Requirement) {
1427 this->write(separator);
1428 this->write("_in");
1429 separator = ", ";
1430 }
1431 if (requirements & kOutputs_Requirement) {
1432 this->write(separator);
1433 this->write("_out");
1434 separator = ", ";
1435 }
1436 if (requirements & kUniforms_Requirement) {
1437 this->write(separator);
1438 this->write("_uniforms");
1439 separator = ", ";
1440 }
1441 if (requirements & kGlobals_Requirement) {
1442 this->write(separator);
John Stilesf7410bd2021-01-19 13:07:55 -05001443 this->write("_globals");
John Stiles06b84ef2020-12-09 12:35:48 -05001444 separator = ", ";
1445 }
1446 if (requirements & kFragCoord_Requirement) {
1447 this->write(separator);
1448 this->write("_fragCoord");
1449 separator = ", ";
1450 }
1451}
1452
1453void MetalCodeGenerator::writeFunctionRequirementParams(const FunctionDeclaration& f,
1454 const char*& separator) {
1455 Requirements requirements = this->requirements(f);
1456 if (requirements & kInputs_Requirement) {
1457 this->write(separator);
1458 this->write("Inputs _in");
1459 separator = ", ";
1460 }
1461 if (requirements & kOutputs_Requirement) {
1462 this->write(separator);
John Stilesf7410bd2021-01-19 13:07:55 -05001463 this->write("thread Outputs& _out");
John Stiles06b84ef2020-12-09 12:35:48 -05001464 separator = ", ";
1465 }
1466 if (requirements & kUniforms_Requirement) {
1467 this->write(separator);
1468 this->write("Uniforms _uniforms");
1469 separator = ", ";
1470 }
1471 if (requirements & kGlobals_Requirement) {
1472 this->write(separator);
John Stilesf7410bd2021-01-19 13:07:55 -05001473 this->write("thread Globals& _globals");
John Stiles06b84ef2020-12-09 12:35:48 -05001474 separator = ", ";
1475 }
1476 if (requirements & kFragCoord_Requirement) {
1477 this->write(separator);
1478 this->write("float4 _fragCoord");
1479 separator = ", ";
1480 }
1481}
1482
John Stilesda5cdf62021-01-28 11:47:29 -05001483int MetalCodeGenerator::getUniformBinding(const Modifiers& m) {
1484 return (m.fLayout.fBinding >= 0) ? m.fLayout.fBinding
John Stiles270cec22021-02-17 12:59:36 -05001485 : fProgram.fConfig->fSettings.fDefaultUniformBinding;
John Stilesda5cdf62021-01-28 11:47:29 -05001486}
1487
1488int MetalCodeGenerator::getUniformSet(const Modifiers& m) {
1489 return (m.fLayout.fSet >= 0) ? m.fLayout.fSet
John Stiles270cec22021-02-17 12:59:36 -05001490 : fProgram.fConfig->fSettings.fDefaultUniformSet;
John Stilesda5cdf62021-01-28 11:47:29 -05001491}
1492
John Stiles569249b2020-11-03 12:18:22 -05001493bool MetalCodeGenerator::writeFunctionDeclaration(const FunctionDeclaration& f) {
John Stilesf7410bd2021-01-19 13:07:55 -05001494 fRTHeightName = fProgram.fInputs.fRTHeight ? "_globals._anonInterface0->u_skRTHeight" : "";
Ethan Nicholascc305772017-10-13 16:17:45 -04001495 const char* separator = "";
John Stilese8da4d22021-03-24 09:19:45 -04001496 if (f.isMain()) {
John Stiles270cec22021-02-17 12:59:36 -05001497 switch (fProgram.fConfig->fKind) {
John Stilesdbd4e6f2021-02-16 13:29:15 -05001498 case ProgramKind::kFragment:
Timothy Liangb8eeb802018-07-23 16:46:16 -04001499 this->write("fragment Outputs fragmentMain");
Ethan Nicholascc305772017-10-13 16:17:45 -04001500 break;
John Stilesdbd4e6f2021-02-16 13:29:15 -05001501 case ProgramKind::kVertex:
Timothy Liangb8eeb802018-07-23 16:46:16 -04001502 this->write("vertex Outputs vertexMain");
Ethan Nicholascc305772017-10-13 16:17:45 -04001503 break;
1504 default:
John Stiles3fabfc02020-09-25 15:51:28 -04001505 fErrors.error(-1, "unsupported kind of program");
John Stiles569249b2020-11-03 12:18:22 -05001506 return false;
Ethan Nicholascc305772017-10-13 16:17:45 -04001507 }
1508 this->write("(Inputs _in [[stage_in]]");
1509 if (-1 != fUniformBuffer) {
1510 this->write(", constant Uniforms& _uniforms [[buffer(" +
1511 to_string(fUniformBuffer) + ")]]");
1512 }
Brian Osman133724c2020-10-28 14:14:39 -04001513 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04001514 if (e->is<GlobalVarDeclaration>()) {
1515 const GlobalVarDeclaration& decls = e->as<GlobalVarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001516 const VarDeclaration& var = decls.declaration()->as<VarDeclaration>();
1517 if (var.var().type().typeKind() == Type::TypeKind::kSampler) {
1518 if (var.var().modifiers().fLayout.fBinding < 0) {
Brian Osmanc0213602020-10-06 14:43:32 -04001519 fErrors.error(decls.fOffset,
John Stilesb41d5bb2021-01-26 16:28:12 -05001520 "Metal samplers must have 'layout(binding=...)'");
John Stiles569249b2020-11-03 12:18:22 -05001521 return false;
Timothy Liangee84fe12018-05-18 14:38:19 -04001522 }
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001523 if (var.var().type().dimensions() != SpvDim2D) {
John Stiles569249b2020-11-03 12:18:22 -05001524 // Not yet implemented--Skia currently only uses 2D textures.
Brian Osmanc0213602020-10-06 14:43:32 -04001525 fErrors.error(decls.fOffset, "Unsupported texture dimensions");
John Stiles569249b2020-11-03 12:18:22 -05001526 return false;
Brian Osmanc0213602020-10-06 14:43:32 -04001527 }
1528 this->write(", texture2d<float> ");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001529 this->writeName(var.var().name());
Brian Osmanc0213602020-10-06 14:43:32 -04001530 this->write("[[texture(");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001531 this->write(to_string(var.var().modifiers().fLayout.fBinding));
Brian Osmanc0213602020-10-06 14:43:32 -04001532 this->write(")]]");
1533 this->write(", sampler ");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001534 this->writeName(var.var().name());
Brian Osmanc0213602020-10-06 14:43:32 -04001535 this->write(SAMPLER_SUFFIX);
1536 this->write("[[sampler(");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001537 this->write(to_string(var.var().modifiers().fLayout.fBinding));
Brian Osmanc0213602020-10-06 14:43:32 -04001538 this->write(")]]");
Timothy Liang6403b0e2018-05-17 10:40:04 -04001539 }
Brian Osman1179fcf2020-10-08 16:04:40 -04001540 } else if (e->is<InterfaceBlock>()) {
1541 const InterfaceBlock& intf = e->as<InterfaceBlock>();
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001542 if (intf.typeName() == "sk_PerVertex") {
Timothy Lianga06f2152018-05-24 15:33:31 -04001543 continue;
1544 }
1545 this->write(", constant ");
John Stilesb4418502021-02-04 10:57:08 -05001546 this->writeType(intf.variable().type());
Timothy Lianga06f2152018-05-24 15:33:31 -04001547 this->write("& " );
1548 this->write(fInterfaceBlockNameMap[&intf]);
1549 this->write(" [[buffer(");
John Stilesda5cdf62021-01-28 11:47:29 -05001550 this->write(to_string(this->getUniformBinding(intf.variable().modifiers())));
Timothy Lianga06f2152018-05-24 15:33:31 -04001551 this->write(")]]");
Timothy Liang6403b0e2018-05-17 10:40:04 -04001552 }
1553 }
John Stiles270cec22021-02-17 12:59:36 -05001554 if (fProgram.fConfig->fKind == ProgramKind::kFragment) {
Jim Van Verth6bc650e2019-02-07 14:53:23 -05001555 if (fProgram.fInputs.fRTHeight && fInterfaceBlockNameMap.empty()) {
Timothy Liang5422f9a2018-08-10 10:57:55 -04001556 this->write(", constant sksl_synthetic_uniforms& _anonInterface0 [[buffer(1)]]");
Ethan Nicholasf931e402019-07-26 15:40:33 -04001557 fRTHeightName = "_anonInterface0.u_skRTHeight";
Timothy Liang5422f9a2018-08-10 10:57:55 -04001558 }
Timothy Liang7b8875d2018-08-10 09:42:31 -04001559 this->write(", bool _frontFacing [[front_facing]]");
Timothy Liang7d637782018-06-05 09:58:07 -04001560 this->write(", float4 _fragCoord [[position]]");
John Stiles270cec22021-02-17 12:59:36 -05001561 } else if (fProgram.fConfig->fKind == ProgramKind::kVertex) {
Timothy Liangdc89f192018-06-13 09:20:31 -04001562 this->write(", uint sk_VertexID [[vertex_id]], uint sk_InstanceID [[instance_id]]");
Timothy Liang7d637782018-06-05 09:58:07 -04001563 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001564 separator = ", ";
1565 } else {
John Stilesb4418502021-02-04 10:57:08 -05001566 this->writeType(f.returnType());
Timothy Liang651286f2018-06-07 09:55:33 -04001567 this->write(" ");
John Stilese1068342021-03-22 11:57:41 -04001568 this->writeName(f.mangledName());
Timothy Liang651286f2018-06-07 09:55:33 -04001569 this->write("(");
John Stiles06b84ef2020-12-09 12:35:48 -05001570 this->writeFunctionRequirementParams(f, separator);
Ethan Nicholascc305772017-10-13 16:17:45 -04001571 }
John Stiles569249b2020-11-03 12:18:22 -05001572 for (const auto& param : f.parameters()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001573 this->write(separator);
1574 separator = ", ";
John Stiles06b84ef2020-12-09 12:35:48 -05001575 this->writeModifiers(param->modifiers(), /*globalContext=*/false);
Ethan Nicholas30d30222020-09-11 12:27:26 -04001576 const Type* type = &param->type();
John Stilesb4418502021-02-04 10:57:08 -05001577 this->writeType(*type);
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001578 if (param->modifiers().fFlags & Modifiers::kOut_Flag) {
John Stilesf2bd5012020-12-04 11:58:26 -05001579 this->write("&");
Ethan Nicholascc305772017-10-13 16:17:45 -04001580 }
Timothy Liang651286f2018-06-07 09:55:33 -04001581 this->write(" ");
Ethan Nicholase2c49992020-10-05 11:49:11 -04001582 this->writeName(param->name());
Ethan Nicholascc305772017-10-13 16:17:45 -04001583 }
John Stiles569249b2020-11-03 12:18:22 -05001584 this->write(")");
1585 return true;
1586}
Ethan Nicholascc305772017-10-13 16:17:45 -04001587
John Stiles569249b2020-11-03 12:18:22 -05001588void MetalCodeGenerator::writeFunctionPrototype(const FunctionPrototype& f) {
1589 this->writeFunctionDeclaration(f.declaration());
1590 this->writeLine(";");
1591}
1592
John Stiles986c7fb2020-12-01 14:44:56 -05001593static bool is_block_ending_with_return(const Statement* stmt) {
1594 // This function detects (potentially nested) blocks that end in a return statement.
1595 if (!stmt->is<Block>()) {
1596 return false;
1597 }
1598 const StatementArray& block = stmt->as<Block>().children();
1599 for (int index = block.count(); index--; ) {
1600 const Statement& stmt = *block[index];
1601 if (stmt.is<ReturnStatement>()) {
1602 return true;
1603 }
1604 if (stmt.is<Block>()) {
1605 return is_block_ending_with_return(&stmt);
1606 }
1607 if (!stmt.is<Nop>()) {
1608 break;
1609 }
1610 }
1611 return false;
1612}
1613
John Stiles569249b2020-11-03 12:18:22 -05001614void MetalCodeGenerator::writeFunction(const FunctionDefinition& f) {
John Stiles270cec22021-02-17 12:59:36 -05001615 SkASSERT(!fProgram.fConfig->fSettings.fFragColorIsInOut);
Brian Salomondc092132018-04-04 10:14:16 -04001616
John Stiles569249b2020-11-03 12:18:22 -05001617 if (!this->writeFunctionDeclaration(f.declaration())) {
1618 return;
1619 }
1620
John Stiles986c7fb2020-12-01 14:44:56 -05001621 fCurrentFunction = &f.declaration();
1622 SkScopeExit clearCurrentFunction([&] { fCurrentFunction = nullptr; });
1623
John Stiles569249b2020-11-03 12:18:22 -05001624 this->writeLine(" {");
1625
John Stilese8da4d22021-03-24 09:19:45 -04001626 if (f.declaration().isMain()) {
John Stilescdcdb042020-07-06 09:03:51 -04001627 this->writeGlobalInit();
John Stilesf7410bd2021-01-19 13:07:55 -05001628 this->writeLine(" Outputs _out;");
John Stiles37279172021-01-21 22:24:28 -05001629 this->writeLine(" (void)_out;");
Ethan Nicholascc305772017-10-13 16:17:45 -04001630 }
John Stilesc67b3622020-05-28 17:53:13 -04001631
Ethan Nicholascc305772017-10-13 16:17:45 -04001632 fFunctionHeader = "";
Ethan Nicholascc305772017-10-13 16:17:45 -04001633 StringStream buffer;
John Stiles44532372020-12-07 12:33:55 -05001634 {
1635 AutoOutputStream outputToBuffer(this, &buffer);
1636 fIndentation++;
1637 for (const std::unique_ptr<Statement>& stmt : f.body()->as<Block>().children()) {
1638 if (!stmt->isEmpty()) {
1639 this->writeStatement(*stmt);
John Stilese8b5a732021-03-12 13:25:52 -05001640 this->finishLine();
John Stiles44532372020-12-07 12:33:55 -05001641 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001642 }
John Stilese8da4d22021-03-24 09:19:45 -04001643 if (f.declaration().isMain()) {
John Stiles44532372020-12-07 12:33:55 -05001644 // If the main function doesn't end with a return, we need to synthesize one here.
1645 if (!is_block_ending_with_return(f.body().get())) {
1646 this->writeReturnStatementFromMain();
John Stilese8b5a732021-03-12 13:25:52 -05001647 this->finishLine();
John Stiles44532372020-12-07 12:33:55 -05001648 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001649 }
John Stiles44532372020-12-07 12:33:55 -05001650 fIndentation--;
1651 this->writeLine("}");
Ethan Nicholascc305772017-10-13 16:17:45 -04001652 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001653 this->write(fFunctionHeader);
1654 this->write(buffer.str());
1655}
1656
1657void MetalCodeGenerator::writeModifiers(const Modifiers& modifiers,
John Stiles06b84ef2020-12-09 12:35:48 -05001658 bool globalContext) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001659 if (modifiers.fFlags & Modifiers::kOut_Flag) {
1660 this->write("thread ");
1661 }
1662 if (modifiers.fFlags & Modifiers::kConst_Flag) {
John Stiles0bd55782021-02-09 18:29:40 -05001663 this->write("const ");
Ethan Nicholascc305772017-10-13 16:17:45 -04001664 }
1665}
1666
1667void MetalCodeGenerator::writeInterfaceBlock(const InterfaceBlock& intf) {
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001668 if ("sk_PerVertex" == intf.typeName()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001669 return;
1670 }
John Stiles06b84ef2020-12-09 12:35:48 -05001671 this->writeModifiers(intf.variable().modifiers(), /*globalContext=*/true);
Timothy Liangdc89f192018-06-13 09:20:31 -04001672 this->write("struct ");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001673 this->writeLine(intf.typeName() + " {");
1674 const Type* structType = &intf.variable().type();
John Stilesbb43b7e2020-12-03 17:36:32 -05001675 if (structType->isArray()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001676 structType = &structType->componentType();
1677 }
Timothy Liangdc89f192018-06-13 09:20:31 -04001678 fIndentation++;
John Stiles3dba3ee2020-12-02 23:35:49 -05001679 this->writeFields(structType->fields(), structType->fOffset, &intf);
Jim Van Verth3d482992019-02-07 10:48:05 -05001680 if (fProgram.fInputs.fRTHeight) {
Timothy Liang7d637782018-06-05 09:58:07 -04001681 this->writeLine("float u_skRTHeight;");
Ethan Nicholascc305772017-10-13 16:17:45 -04001682 }
1683 fIndentation--;
1684 this->write("}");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001685 if (intf.instanceName().size()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001686 this->write(" ");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001687 this->write(intf.instanceName());
John Stilesd39aec02020-12-03 10:42:26 -05001688 if (intf.arraySize() > 0) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001689 this->write("[");
John Stilesd39aec02020-12-03 10:42:26 -05001690 this->write(to_string(intf.arraySize()));
Ethan Nicholascc305772017-10-13 16:17:45 -04001691 this->write("]");
John Stilesd39aec02020-12-03 10:42:26 -05001692 } else if (intf.arraySize() == Type::kUnsizedArray){
1693 this->write("[]");
Ethan Nicholascc305772017-10-13 16:17:45 -04001694 }
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001695 fInterfaceBlockNameMap[&intf] = intf.instanceName();
Timothy Lianga06f2152018-05-24 15:33:31 -04001696 } else {
Timothy Liang7d637782018-06-05 09:58:07 -04001697 fInterfaceBlockNameMap[&intf] = "_anonInterface" + to_string(fAnonInterfaceCount++);
Ethan Nicholascc305772017-10-13 16:17:45 -04001698 }
1699 this->writeLine(";");
1700}
1701
Timothy Liangdc89f192018-06-13 09:20:31 -04001702void MetalCodeGenerator::writeFields(const std::vector<Type::Field>& fields, int parentOffset,
1703 const InterfaceBlock* parentIntf) {
Timothy Liang609fbe32018-08-10 16:40:49 -04001704 MemoryLayout memoryLayout(MemoryLayout::kMetal_Standard);
Timothy Liangdc89f192018-06-13 09:20:31 -04001705 int currentOffset = 0;
1706 for (const auto& field: fields) {
1707 int fieldOffset = field.fModifiers.fLayout.fOffset;
1708 const Type* fieldType = field.fType;
John Stiles21f5f452020-11-30 09:57:59 -05001709 if (!MemoryLayout::LayoutIsSupported(*fieldType)) {
John Stiles0023c0c2020-11-16 13:32:18 -05001710 fErrors.error(parentOffset, "type '" + fieldType->name() + "' is not permitted here");
1711 return;
1712 }
Timothy Liangdc89f192018-06-13 09:20:31 -04001713 if (fieldOffset != -1) {
1714 if (currentOffset > fieldOffset) {
1715 fErrors.error(parentOffset,
John Stilesd7199b22020-12-30 16:22:58 -05001716 "offset of field '" + field.fName + "' must be at least " +
1717 to_string((int) currentOffset));
Brian Osman8609a242020-09-08 14:01:49 -04001718 return;
Timothy Liangdc89f192018-06-13 09:20:31 -04001719 } else if (currentOffset < fieldOffset) {
1720 this->write("char pad");
1721 this->write(to_string(fPaddingCount++));
1722 this->write("[");
1723 this->write(to_string(fieldOffset - currentOffset));
1724 this->writeLine("];");
1725 currentOffset = fieldOffset;
1726 }
1727 int alignment = memoryLayout.alignment(*fieldType);
1728 if (fieldOffset % alignment) {
1729 fErrors.error(parentOffset,
1730 "offset of field '" + field.fName + "' must be a multiple of " +
1731 to_string((int) alignment));
Brian Osman8609a242020-09-08 14:01:49 -04001732 return;
Timothy Liangdc89f192018-06-13 09:20:31 -04001733 }
1734 }
Brian Osman8609a242020-09-08 14:01:49 -04001735 size_t fieldSize = memoryLayout.size(*fieldType);
1736 if (fieldSize > static_cast<size_t>(std::numeric_limits<int>::max() - currentOffset)) {
1737 fErrors.error(parentOffset, "field offset overflow");
1738 return;
1739 }
1740 currentOffset += fieldSize;
John Stiles06b84ef2020-12-09 12:35:48 -05001741 this->writeModifiers(field.fModifiers, /*globalContext=*/false);
John Stilesb4418502021-02-04 10:57:08 -05001742 this->writeType(*fieldType);
Timothy Liangdc89f192018-06-13 09:20:31 -04001743 this->write(" ");
1744 this->writeName(field.fName);
Timothy Liangdc89f192018-06-13 09:20:31 -04001745 this->writeLine(";");
1746 if (parentIntf) {
1747 fInterfaceBlockMap[&field] = parentIntf;
1748 }
1749 }
1750}
1751
Ethan Nicholascc305772017-10-13 16:17:45 -04001752void MetalCodeGenerator::writeVarInitializer(const Variable& var, const Expression& value) {
Brian Osman00185012021-02-04 16:07:11 -05001753 this->writeExpression(value, Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001754}
1755
Timothy Liang651286f2018-06-07 09:55:33 -04001756void MetalCodeGenerator::writeName(const String& name) {
1757 if (fReservedWords.find(name) != fReservedWords.end()) {
1758 this->write("_"); // adding underscore before name to avoid conflict with reserved words
1759 }
1760 this->write(name);
1761}
1762
John Stilesb4418502021-02-04 10:57:08 -05001763void MetalCodeGenerator::writeVarDeclaration(const VarDeclaration& varDecl, bool global) {
1764 if (global && !(varDecl.var().modifiers().fFlags & Modifiers::kConst_Flag)) {
Brian Osmanc0213602020-10-06 14:43:32 -04001765 return;
Ethan Nicholascc305772017-10-13 16:17:45 -04001766 }
John Stilesb4418502021-02-04 10:57:08 -05001767 this->writeModifiers(varDecl.var().modifiers(), global);
1768 this->writeType(varDecl.var().type());
Brian Osmanc0213602020-10-06 14:43:32 -04001769 this->write(" ");
John Stilesb4418502021-02-04 10:57:08 -05001770 this->writeName(varDecl.var().name());
1771 if (varDecl.value()) {
Brian Osmanc0213602020-10-06 14:43:32 -04001772 this->write(" = ");
John Stilesb4418502021-02-04 10:57:08 -05001773 this->writeVarInitializer(varDecl.var(), *varDecl.value());
Brian Osmanc0213602020-10-06 14:43:32 -04001774 }
1775 this->write(";");
Ethan Nicholascc305772017-10-13 16:17:45 -04001776}
1777
1778void MetalCodeGenerator::writeStatement(const Statement& s) {
Ethan Nicholase6592142020-09-08 10:22:09 -04001779 switch (s.kind()) {
1780 case Statement::Kind::kBlock:
John Stiles26f98502020-08-18 09:30:51 -04001781 this->writeBlock(s.as<Block>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001782 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001783 case Statement::Kind::kExpression:
Brian Osman00185012021-02-04 16:07:11 -05001784 this->writeExpression(*s.as<ExpressionStatement>().expression(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001785 this->write(";");
1786 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001787 case Statement::Kind::kReturn:
John Stiles26f98502020-08-18 09:30:51 -04001788 this->writeReturnStatement(s.as<ReturnStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001789 break;
Brian Osmanc0213602020-10-06 14:43:32 -04001790 case Statement::Kind::kVarDeclaration:
1791 this->writeVarDeclaration(s.as<VarDeclaration>(), false);
Ethan Nicholascc305772017-10-13 16:17:45 -04001792 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001793 case Statement::Kind::kIf:
John Stiles26f98502020-08-18 09:30:51 -04001794 this->writeIfStatement(s.as<IfStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001795 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001796 case Statement::Kind::kFor:
John Stiles26f98502020-08-18 09:30:51 -04001797 this->writeForStatement(s.as<ForStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001798 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001799 case Statement::Kind::kDo:
John Stiles26f98502020-08-18 09:30:51 -04001800 this->writeDoStatement(s.as<DoStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001801 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001802 case Statement::Kind::kSwitch:
John Stiles26f98502020-08-18 09:30:51 -04001803 this->writeSwitchStatement(s.as<SwitchStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001804 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001805 case Statement::Kind::kBreak:
Ethan Nicholascc305772017-10-13 16:17:45 -04001806 this->write("break;");
1807 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001808 case Statement::Kind::kContinue:
Ethan Nicholascc305772017-10-13 16:17:45 -04001809 this->write("continue;");
1810 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001811 case Statement::Kind::kDiscard:
Timothy Lianga06f2152018-05-24 15:33:31 -04001812 this->write("discard_fragment();");
Ethan Nicholascc305772017-10-13 16:17:45 -04001813 break;
John Stiles98c1f822020-09-09 14:18:53 -04001814 case Statement::Kind::kInlineMarker:
Ethan Nicholase6592142020-09-08 10:22:09 -04001815 case Statement::Kind::kNop:
Ethan Nicholascc305772017-10-13 16:17:45 -04001816 this->write(";");
1817 break;
1818 default:
John Stileseada7bc2021-02-02 16:29:32 -05001819 SkDEBUGFAILF("unsupported statement: %s", s.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -05001820 break;
Ethan Nicholascc305772017-10-13 16:17:45 -04001821 }
1822}
1823
Ethan Nicholascc305772017-10-13 16:17:45 -04001824void MetalCodeGenerator::writeBlock(const Block& b) {
John Stiles3744bd62021-01-26 13:49:43 -05001825 // Write scope markers if this block is a scope, or if the block is empty (since we need to emit
1826 // something here to make the code valid).
1827 bool isScope = b.isScope() || b.isEmpty();
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001828 if (isScope) {
Ethan Nicholas70728ef2020-05-28 07:09:00 -04001829 this->writeLine("{");
1830 fIndentation++;
1831 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001832 for (const std::unique_ptr<Statement>& stmt : b.children()) {
1833 if (!stmt->isEmpty()) {
1834 this->writeStatement(*stmt);
John Stilese8b5a732021-03-12 13:25:52 -05001835 this->finishLine();
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001836 }
1837 }
1838 if (isScope) {
Ethan Nicholas70728ef2020-05-28 07:09:00 -04001839 fIndentation--;
1840 this->write("}");
1841 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001842}
1843
1844void MetalCodeGenerator::writeIfStatement(const IfStatement& stmt) {
1845 this->write("if (");
Brian Osman00185012021-02-04 16:07:11 -05001846 this->writeExpression(*stmt.test(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001847 this->write(") ");
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04001848 this->writeStatement(*stmt.ifTrue());
1849 if (stmt.ifFalse()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001850 this->write(" else ");
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04001851 this->writeStatement(*stmt.ifFalse());
Ethan Nicholascc305772017-10-13 16:17:45 -04001852 }
1853}
1854
1855void MetalCodeGenerator::writeForStatement(const ForStatement& f) {
Brian Osmand6f23382020-12-15 17:08:59 -05001856 // Emit loops of the form 'for(;test;)' as 'while(test)', which is probably how they started
1857 if (!f.initializer() && f.test() && !f.next()) {
1858 this->write("while (");
Brian Osman00185012021-02-04 16:07:11 -05001859 this->writeExpression(*f.test(), Precedence::kTopLevel);
Brian Osmand6f23382020-12-15 17:08:59 -05001860 this->write(") ");
1861 this->writeStatement(*f.statement());
1862 return;
1863 }
1864
Ethan Nicholascc305772017-10-13 16:17:45 -04001865 this->write("for (");
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04001866 if (f.initializer() && !f.initializer()->isEmpty()) {
1867 this->writeStatement(*f.initializer());
Ethan Nicholascc305772017-10-13 16:17:45 -04001868 } else {
1869 this->write("; ");
1870 }
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04001871 if (f.test()) {
Brian Osman00185012021-02-04 16:07:11 -05001872 this->writeExpression(*f.test(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001873 }
1874 this->write("; ");
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04001875 if (f.next()) {
Brian Osman00185012021-02-04 16:07:11 -05001876 this->writeExpression(*f.next(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001877 }
1878 this->write(") ");
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04001879 this->writeStatement(*f.statement());
Ethan Nicholascc305772017-10-13 16:17:45 -04001880}
1881
Ethan Nicholascc305772017-10-13 16:17:45 -04001882void MetalCodeGenerator::writeDoStatement(const DoStatement& d) {
1883 this->write("do ");
Ethan Nicholas1fd61162020-09-28 13:14:19 -04001884 this->writeStatement(*d.statement());
Ethan Nicholascc305772017-10-13 16:17:45 -04001885 this->write(" while (");
Brian Osman00185012021-02-04 16:07:11 -05001886 this->writeExpression(*d.test(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001887 this->write(");");
1888}
1889
1890void MetalCodeGenerator::writeSwitchStatement(const SwitchStatement& s) {
1891 this->write("switch (");
Brian Osman00185012021-02-04 16:07:11 -05001892 this->writeExpression(*s.value(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001893 this->writeLine(") {");
1894 fIndentation++;
John Stilesb23a64b2021-03-11 08:27:59 -05001895 for (const std::unique_ptr<Statement>& stmt : s.cases()) {
1896 const SwitchCase& c = stmt->as<SwitchCase>();
1897 if (c.value()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001898 this->write("case ");
John Stilesb23a64b2021-03-11 08:27:59 -05001899 this->writeExpression(*c.value(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001900 this->writeLine(":");
1901 } else {
1902 this->writeLine("default:");
1903 }
John Stilesb23a64b2021-03-11 08:27:59 -05001904 if (!c.statement()->isEmpty()) {
John Stilesc3ce43b2021-03-09 15:37:01 -05001905 fIndentation++;
John Stilesb23a64b2021-03-11 08:27:59 -05001906 this->writeStatement(*c.statement());
John Stilese8b5a732021-03-12 13:25:52 -05001907 this->finishLine();
John Stilesc3ce43b2021-03-09 15:37:01 -05001908 fIndentation--;
Ethan Nicholascc305772017-10-13 16:17:45 -04001909 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001910 }
1911 fIndentation--;
1912 this->write("}");
1913}
1914
John Stiles986c7fb2020-12-01 14:44:56 -05001915void MetalCodeGenerator::writeReturnStatementFromMain() {
1916 // main functions in Metal return a magic _out parameter that doesn't exist in SkSL.
John Stiles270cec22021-02-17 12:59:36 -05001917 switch (fProgram.fConfig->fKind) {
John Stilesdbd4e6f2021-02-16 13:29:15 -05001918 case ProgramKind::kFragment:
John Stilesf7410bd2021-01-19 13:07:55 -05001919 this->write("return _out;");
John Stiles986c7fb2020-12-01 14:44:56 -05001920 break;
John Stilesdbd4e6f2021-02-16 13:29:15 -05001921 case ProgramKind::kVertex:
John Stilesf7410bd2021-01-19 13:07:55 -05001922 this->write("return (_out.sk_Position.y = -_out.sk_Position.y, _out);");
John Stiles986c7fb2020-12-01 14:44:56 -05001923 break;
1924 default:
1925 SkDEBUGFAIL("unsupported kind of program");
1926 }
1927}
1928
Ethan Nicholascc305772017-10-13 16:17:45 -04001929void MetalCodeGenerator::writeReturnStatement(const ReturnStatement& r) {
John Stilese8da4d22021-03-24 09:19:45 -04001930 if (fCurrentFunction && fCurrentFunction->isMain()) {
John Stiles986c7fb2020-12-01 14:44:56 -05001931 if (r.expression()) {
John Stiles97d18172021-01-22 16:47:42 -05001932 if (r.expression()->type() == *fContext.fTypes.fHalf4) {
1933 this->write("_out.sk_FragColor = ");
Brian Osman00185012021-02-04 16:07:11 -05001934 this->writeExpression(*r.expression(), Precedence::kTopLevel);
John Stiles97d18172021-01-22 16:47:42 -05001935 this->writeLine(";");
1936 } else {
1937 fErrors.error(r.fOffset, "Metal does not support returning '" +
1938 r.expression()->type().description() + "' from main()");
1939 }
John Stiles986c7fb2020-12-01 14:44:56 -05001940 }
1941 this->writeReturnStatementFromMain();
1942 return;
1943 }
1944
Ethan Nicholascc305772017-10-13 16:17:45 -04001945 this->write("return");
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04001946 if (r.expression()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001947 this->write(" ");
Brian Osman00185012021-02-04 16:07:11 -05001948 this->writeExpression(*r.expression(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001949 }
1950 this->write(";");
1951}
1952
Michael Ludwigbf58add2021-03-16 10:40:11 -04001953void MetalCodeGenerator::writeHeader() {
1954 this->write("#include <metal_stdlib>\n");
1955 this->write("#include <simd/simd.h>\n");
1956 this->write("using namespace metal;\n");
1957}
1958
Ethan Nicholascc305772017-10-13 16:17:45 -04001959void MetalCodeGenerator::writeUniformStruct() {
Brian Osman133724c2020-10-28 14:14:39 -04001960 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04001961 if (e->is<GlobalVarDeclaration>()) {
1962 const GlobalVarDeclaration& decls = e->as<GlobalVarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001963 const Variable& var = decls.declaration()->as<VarDeclaration>().var();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001964 if (var.modifiers().fFlags & Modifiers::kUniform_Flag &&
Brian Osmanc0213602020-10-06 14:43:32 -04001965 var.type().typeKind() != Type::TypeKind::kSampler) {
John Stilesda5cdf62021-01-28 11:47:29 -05001966 int uniformSet = this->getUniformSet(var.modifiers());
John Stilesd8fc95d2021-01-26 16:22:53 -05001967 // Make sure that the program's uniform-set value is consistent throughout.
Ethan Nicholascc305772017-10-13 16:17:45 -04001968 if (-1 == fUniformBuffer) {
1969 this->write("struct Uniforms {\n");
John Stilesd8fc95d2021-01-26 16:22:53 -05001970 fUniformBuffer = uniformSet;
1971 } else if (uniformSet != fUniformBuffer) {
1972 fErrors.error(decls.fOffset, "Metal backend requires all uniforms to have "
1973 "the same 'layout(set=...)'");
Ethan Nicholascc305772017-10-13 16:17:45 -04001974 }
1975 this->write(" ");
John Stilesb4418502021-02-04 10:57:08 -05001976 this->writeType(var.type());
Ethan Nicholascc305772017-10-13 16:17:45 -04001977 this->write(" ");
Brian Osmanc0213602020-10-06 14:43:32 -04001978 this->writeName(var.name());
Ethan Nicholascc305772017-10-13 16:17:45 -04001979 this->write(";\n");
1980 }
1981 }
1982 }
1983 if (-1 != fUniformBuffer) {
1984 this->write("};\n");
1985 }
1986}
1987
1988void MetalCodeGenerator::writeInputStruct() {
1989 this->write("struct Inputs {\n");
Brian Osman133724c2020-10-28 14:14:39 -04001990 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04001991 if (e->is<GlobalVarDeclaration>()) {
1992 const GlobalVarDeclaration& decls = e->as<GlobalVarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001993 const Variable& var = decls.declaration()->as<VarDeclaration>().var();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001994 if (var.modifiers().fFlags & Modifiers::kIn_Flag &&
1995 -1 == var.modifiers().fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001996 this->write(" ");
John Stilesb4418502021-02-04 10:57:08 -05001997 this->writeType(var.type());
Ethan Nicholascc305772017-10-13 16:17:45 -04001998 this->write(" ");
Brian Osmanc0213602020-10-06 14:43:32 -04001999 this->writeName(var.name());
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002000 if (-1 != var.modifiers().fLayout.fLocation) {
John Stiles270cec22021-02-17 12:59:36 -05002001 if (fProgram.fConfig->fKind == ProgramKind::kVertex) {
Brian Osmanc0213602020-10-06 14:43:32 -04002002 this->write(" [[attribute(" +
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002003 to_string(var.modifiers().fLayout.fLocation) + ")]]");
John Stiles270cec22021-02-17 12:59:36 -05002004 } else if (fProgram.fConfig->fKind == ProgramKind::kFragment) {
Brian Osmanc0213602020-10-06 14:43:32 -04002005 this->write(" [[user(locn" +
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002006 to_string(var.modifiers().fLayout.fLocation) + ")]]");
Ethan Nicholascc305772017-10-13 16:17:45 -04002007 }
2008 }
2009 this->write(";\n");
2010 }
2011 }
2012 }
2013 this->write("};\n");
2014}
2015
2016void MetalCodeGenerator::writeOutputStruct() {
2017 this->write("struct Outputs {\n");
John Stiles270cec22021-02-17 12:59:36 -05002018 if (fProgram.fConfig->fKind == ProgramKind::kVertex) {
Timothy Liangb8eeb802018-07-23 16:46:16 -04002019 this->write(" float4 sk_Position [[position]];\n");
John Stiles270cec22021-02-17 12:59:36 -05002020 } else if (fProgram.fConfig->fKind == ProgramKind::kFragment) {
Timothy Liangde0be802018-08-10 13:48:08 -04002021 this->write(" float4 sk_FragColor [[color(0)]];\n");
Timothy Liang7d637782018-06-05 09:58:07 -04002022 }
Brian Osman133724c2020-10-28 14:14:39 -04002023 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04002024 if (e->is<GlobalVarDeclaration>()) {
2025 const GlobalVarDeclaration& decls = e->as<GlobalVarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04002026 const Variable& var = decls.declaration()->as<VarDeclaration>().var();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002027 if (var.modifiers().fFlags & Modifiers::kOut_Flag &&
2028 -1 == var.modifiers().fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002029 this->write(" ");
John Stilesb4418502021-02-04 10:57:08 -05002030 this->writeType(var.type());
Ethan Nicholascc305772017-10-13 16:17:45 -04002031 this->write(" ");
Brian Osmanc0213602020-10-06 14:43:32 -04002032 this->writeName(var.name());
John Stiles842b3592020-12-01 10:36:37 -05002033
2034 int location = var.modifiers().fLayout.fLocation;
2035 if (location < 0) {
2036 fErrors.error(var.fOffset,
2037 "Metal out variables must have 'layout(location=...)'");
John Stiles270cec22021-02-17 12:59:36 -05002038 } else if (fProgram.fConfig->fKind == ProgramKind::kVertex) {
John Stiles842b3592020-12-01 10:36:37 -05002039 this->write(" [[user(locn" + to_string(location) + ")]]");
John Stiles270cec22021-02-17 12:59:36 -05002040 } else if (fProgram.fConfig->fKind == ProgramKind::kFragment) {
John Stiles842b3592020-12-01 10:36:37 -05002041 this->write(" [[color(" + to_string(location) + ")");
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002042 int colorIndex = var.modifiers().fLayout.fIndex;
Brian Osmanc0213602020-10-06 14:43:32 -04002043 if (colorIndex) {
2044 this->write(", index(" + to_string(colorIndex) + ")");
Timothy Liang7d637782018-06-05 09:58:07 -04002045 }
Brian Osmanc0213602020-10-06 14:43:32 -04002046 this->write("]]");
Ethan Nicholascc305772017-10-13 16:17:45 -04002047 }
2048 this->write(";\n");
2049 }
2050 }
Timothy Liang7d637782018-06-05 09:58:07 -04002051 }
John Stiles270cec22021-02-17 12:59:36 -05002052 if (fProgram.fConfig->fKind == ProgramKind::kVertex) {
Jim Van Verth3913d3e2020-08-31 15:16:57 -04002053 this->write(" float sk_PointSize [[point_size]];\n");
Timothy Liang7d637782018-06-05 09:58:07 -04002054 }
2055 this->write("};\n");
2056}
2057
2058void MetalCodeGenerator::writeInterfaceBlocks() {
2059 bool wroteInterfaceBlock = false;
Brian Osman133724c2020-10-28 14:14:39 -04002060 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04002061 if (e->is<InterfaceBlock>()) {
2062 this->writeInterfaceBlock(e->as<InterfaceBlock>());
Timothy Liang7d637782018-06-05 09:58:07 -04002063 wroteInterfaceBlock = true;
2064 }
2065 }
Jim Van Verth3d482992019-02-07 10:48:05 -05002066 if (!wroteInterfaceBlock && fProgram.fInputs.fRTHeight) {
Timothy Liang7d637782018-06-05 09:58:07 -04002067 this->writeLine("struct sksl_synthetic_uniforms {");
2068 this->writeLine(" float u_skRTHeight;");
2069 this->writeLine("};");
2070 }
Ethan Nicholascc305772017-10-13 16:17:45 -04002071}
2072
John Stilesdc75a972020-11-25 16:24:55 -05002073void MetalCodeGenerator::writeStructDefinitions() {
2074 for (const ProgramElement* e : fProgram.elements()) {
2075 if (e->is<StructDefinition>()) {
Brian Osman02bc5222021-01-28 11:00:20 -05002076 this->writeStructDefinition(e->as<StructDefinition>());
John Stilesdc75a972020-11-25 16:24:55 -05002077 }
2078 }
2079}
2080
John Stilescdcdb042020-07-06 09:03:51 -04002081void MetalCodeGenerator::visitGlobalStruct(GlobalStructVisitor* visitor) {
2082 // Visit the interface blocks.
2083 for (const auto& [interfaceType, interfaceName] : fInterfaceBlockNameMap) {
John Stilesfdb8dbe2020-12-04 11:00:03 -05002084 visitor->visitInterfaceBlock(*interfaceType, interfaceName);
John Stilescdcdb042020-07-06 09:03:51 -04002085 }
Brian Osman133724c2020-10-28 14:14:39 -04002086 for (const ProgramElement* element : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04002087 if (!element->is<GlobalVarDeclaration>()) {
John Stilescdcdb042020-07-06 09:03:51 -04002088 continue;
Timothy Liang7d637782018-06-05 09:58:07 -04002089 }
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04002090 const GlobalVarDeclaration& global = element->as<GlobalVarDeclaration>();
2091 const VarDeclaration& decl = global.declaration()->as<VarDeclaration>();
2092 const Variable& var = decl.var();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002093 if ((!var.modifiers().fFlags && -1 == var.modifiers().fLayout.fBuiltin) ||
Brian Osmanc0213602020-10-06 14:43:32 -04002094 var.type().typeKind() == Type::TypeKind::kSampler) {
2095 if (var.type().typeKind() == Type::TypeKind::kSampler) {
2096 // Samplers are represented as a "texture/sampler" duo in the global struct.
John Stilesfdb8dbe2020-12-04 11:00:03 -05002097 visitor->visitTexture(var.type(), var.name());
2098 visitor->visitSampler(var.type(), String(var.name()) + SAMPLER_SUFFIX);
Brian Osmanc0213602020-10-06 14:43:32 -04002099 } else {
2100 // Visit a regular variable.
John Stilesfdb8dbe2020-12-04 11:00:03 -05002101 visitor->visitVariable(var, decl.value().get());
Timothy Liangee84fe12018-05-18 14:38:19 -04002102 }
2103 }
2104 }
John Stilescdcdb042020-07-06 09:03:51 -04002105}
2106
2107void MetalCodeGenerator::writeGlobalStruct() {
2108 class : public GlobalStructVisitor {
2109 public:
John Stilesfdb8dbe2020-12-04 11:00:03 -05002110 void visitInterfaceBlock(const InterfaceBlock& block, const String& blockName) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002111 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002112 fCodeGen->write(" constant ");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04002113 fCodeGen->write(block.typeName());
John Stilescdcdb042020-07-06 09:03:51 -04002114 fCodeGen->write("* ");
2115 fCodeGen->writeName(blockName);
2116 fCodeGen->write(";\n");
2117 }
John Stilesfdb8dbe2020-12-04 11:00:03 -05002118 void visitTexture(const Type& type, const String& name) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002119 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002120 fCodeGen->write(" ");
John Stilesb4418502021-02-04 10:57:08 -05002121 fCodeGen->writeType(type);
John Stilescdcdb042020-07-06 09:03:51 -04002122 fCodeGen->write(" ");
2123 fCodeGen->writeName(name);
2124 fCodeGen->write(";\n");
2125 }
John Stilesfdb8dbe2020-12-04 11:00:03 -05002126 void visitSampler(const Type&, const String& name) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002127 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002128 fCodeGen->write(" sampler ");
2129 fCodeGen->writeName(name);
2130 fCodeGen->write(";\n");
2131 }
John Stilesfdb8dbe2020-12-04 11:00:03 -05002132 void visitVariable(const Variable& var, const Expression* value) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002133 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002134 fCodeGen->write(" ");
John Stilesb4418502021-02-04 10:57:08 -05002135 fCodeGen->writeType(var.type());
John Stilescdcdb042020-07-06 09:03:51 -04002136 fCodeGen->write(" ");
Ethan Nicholase2c49992020-10-05 11:49:11 -04002137 fCodeGen->writeName(var.name());
John Stilescdcdb042020-07-06 09:03:51 -04002138 fCodeGen->write(";\n");
2139 }
John Stiles83f3b8d2020-12-07 17:52:25 -05002140 void addElement() {
John Stilescdcdb042020-07-06 09:03:51 -04002141 if (fFirst) {
2142 fCodeGen->write("struct Globals {\n");
2143 fFirst = false;
2144 }
2145 }
John Stiles83f3b8d2020-12-07 17:52:25 -05002146 void finish() {
John Stilescdcdb042020-07-06 09:03:51 -04002147 if (!fFirst) {
John Stiles83f3b8d2020-12-07 17:52:25 -05002148 fCodeGen->writeLine("};");
John Stilescdcdb042020-07-06 09:03:51 -04002149 fFirst = true;
2150 }
2151 }
2152
2153 MetalCodeGenerator* fCodeGen = nullptr;
2154 bool fFirst = true;
2155 } visitor;
2156
2157 visitor.fCodeGen = this;
2158 this->visitGlobalStruct(&visitor);
John Stiles83f3b8d2020-12-07 17:52:25 -05002159 visitor.finish();
John Stilescdcdb042020-07-06 09:03:51 -04002160}
2161
2162void MetalCodeGenerator::writeGlobalInit() {
2163 class : public GlobalStructVisitor {
2164 public:
John Stilesfdb8dbe2020-12-04 11:00:03 -05002165 void visitInterfaceBlock(const InterfaceBlock& blockType,
John Stilescdcdb042020-07-06 09:03:51 -04002166 const String& blockName) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002167 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002168 fCodeGen->write("&");
2169 fCodeGen->writeName(blockName);
2170 }
John Stilesfdb8dbe2020-12-04 11:00:03 -05002171 void visitTexture(const Type&, const String& name) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002172 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002173 fCodeGen->writeName(name);
2174 }
John Stilesfdb8dbe2020-12-04 11:00:03 -05002175 void visitSampler(const Type&, const String& name) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002176 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002177 fCodeGen->writeName(name);
2178 }
John Stilesfdb8dbe2020-12-04 11:00:03 -05002179 void visitVariable(const Variable& var, const Expression* value) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002180 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002181 if (value) {
2182 fCodeGen->writeVarInitializer(var, *value);
2183 } else {
2184 fCodeGen->write("{}");
2185 }
2186 }
John Stiles83f3b8d2020-12-07 17:52:25 -05002187 void addElement() {
John Stilescdcdb042020-07-06 09:03:51 -04002188 if (fFirst) {
John Stilesf7410bd2021-01-19 13:07:55 -05002189 fCodeGen->write(" Globals _globals{");
John Stilescdcdb042020-07-06 09:03:51 -04002190 fFirst = false;
2191 } else {
2192 fCodeGen->write(", ");
2193 }
2194 }
John Stiles83f3b8d2020-12-07 17:52:25 -05002195 void finish() {
John Stilescdcdb042020-07-06 09:03:51 -04002196 if (!fFirst) {
2197 fCodeGen->writeLine("};");
John Stiles37279172021-01-21 22:24:28 -05002198 fCodeGen->writeLine(" (void)_globals;");
John Stilescdcdb042020-07-06 09:03:51 -04002199 }
2200 }
2201 MetalCodeGenerator* fCodeGen = nullptr;
2202 bool fFirst = true;
2203 } visitor;
2204
2205 visitor.fCodeGen = this;
2206 this->visitGlobalStruct(&visitor);
John Stiles83f3b8d2020-12-07 17:52:25 -05002207 visitor.finish();
Timothy Liangee84fe12018-05-18 14:38:19 -04002208}
2209
Ethan Nicholascc305772017-10-13 16:17:45 -04002210void MetalCodeGenerator::writeProgramElement(const ProgramElement& e) {
Ethan Nicholase6592142020-09-08 10:22:09 -04002211 switch (e.kind()) {
2212 case ProgramElement::Kind::kExtension:
Ethan Nicholascc305772017-10-13 16:17:45 -04002213 break;
Brian Osmanc0213602020-10-06 14:43:32 -04002214 case ProgramElement::Kind::kGlobalVar: {
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04002215 const GlobalVarDeclaration& global = e.as<GlobalVarDeclaration>();
2216 const VarDeclaration& decl = global.declaration()->as<VarDeclaration>();
2217 int builtin = decl.var().modifiers().fLayout.fBuiltin;
Brian Osmanc0213602020-10-06 14:43:32 -04002218 if (-1 == builtin) {
2219 // normal var
2220 this->writeVarDeclaration(decl, true);
John Stilese8b5a732021-03-12 13:25:52 -05002221 this->finishLine();
Brian Osmanc0213602020-10-06 14:43:32 -04002222 } else if (SK_FRAGCOLOR_BUILTIN == builtin) {
2223 // ignore
Ethan Nicholascc305772017-10-13 16:17:45 -04002224 }
2225 break;
2226 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002227 case ProgramElement::Kind::kInterfaceBlock:
Timothy Liang7d637782018-06-05 09:58:07 -04002228 // handled in writeInterfaceBlocks, do nothing
Ethan Nicholascc305772017-10-13 16:17:45 -04002229 break;
John Stilesdc75a972020-11-25 16:24:55 -05002230 case ProgramElement::Kind::kStructDefinition:
2231 // Handled in writeStructDefinitions. Do nothing.
2232 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04002233 case ProgramElement::Kind::kFunction:
John Stiles3dc0da62020-08-19 17:48:31 -04002234 this->writeFunction(e.as<FunctionDefinition>());
Ethan Nicholascc305772017-10-13 16:17:45 -04002235 break;
John Stiles569249b2020-11-03 12:18:22 -05002236 case ProgramElement::Kind::kFunctionPrototype:
2237 this->writeFunctionPrototype(e.as<FunctionPrototype>());
2238 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04002239 case ProgramElement::Kind::kModifiers:
John Stiles06b84ef2020-12-09 12:35:48 -05002240 this->writeModifiers(e.as<ModifiersDeclaration>().modifiers(),
2241 /*globalContext=*/true);
Ethan Nicholascc305772017-10-13 16:17:45 -04002242 this->writeLine(";");
2243 break;
John Stiles712fd6b2020-11-25 22:25:43 -05002244 case ProgramElement::Kind::kEnum:
2245 break;
Ethan Nicholascc305772017-10-13 16:17:45 -04002246 default:
John Stileseada7bc2021-02-02 16:29:32 -05002247 SkDEBUGFAILF("unsupported program element: %s\n", e.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -05002248 break;
Ethan Nicholascc305772017-10-13 16:17:45 -04002249 }
2250}
2251
Ethan Nicholasff350cb2020-05-14 14:05:13 -04002252MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const Expression* e) {
2253 if (!e) {
2254 return kNo_Requirements;
2255 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002256 switch (e->kind()) {
2257 case Expression::Kind::kFunctionCall: {
John Stiles3dc0da62020-08-19 17:48:31 -04002258 const FunctionCall& f = e->as<FunctionCall>();
Ethan Nicholas0dec9922020-10-05 15:51:52 -04002259 Requirements result = this->requirements(f.function());
2260 for (const auto& arg : f.arguments()) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04002261 result |= this->requirements(arg.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002262 }
2263 return result;
2264 }
John Stiles7384b372021-04-01 13:48:15 -04002265 case Expression::Kind::kConstructor:
2266 case Expression::Kind::kConstructorArray:
John Stiles2938eea2021-04-01 18:58:25 -04002267 case Expression::Kind::kConstructorDiagonalMatrix:
2268 case Expression::Kind::kConstructorSplat: {
John Stiles7384b372021-04-01 13:48:15 -04002269 const AnyConstructor& c = e->asAnyConstructor();
Ethan Nicholascc305772017-10-13 16:17:45 -04002270 Requirements result = kNo_Requirements;
John Stilesd8eb8752021-04-01 11:49:10 -04002271 for (const auto& arg : c.argumentSpan()) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04002272 result |= this->requirements(arg.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002273 }
2274 return result;
2275 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002276 case Expression::Kind::kFieldAccess: {
John Stiles3dc0da62020-08-19 17:48:31 -04002277 const FieldAccess& f = e->as<FieldAccess>();
Ethan Nicholas7a95b202020-10-09 11:55:40 -04002278 if (FieldAccess::OwnerKind::kAnonymousInterfaceBlock == f.ownerKind()) {
Timothy Liang7d637782018-06-05 09:58:07 -04002279 return kGlobals_Requirement;
2280 }
Ethan Nicholas7a95b202020-10-09 11:55:40 -04002281 return this->requirements(f.base().get());
Timothy Liang7d637782018-06-05 09:58:07 -04002282 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002283 case Expression::Kind::kSwizzle:
Ethan Nicholas6b4d5812020-10-12 16:11:51 -04002284 return this->requirements(e->as<Swizzle>().base().get());
Ethan Nicholase6592142020-09-08 10:22:09 -04002285 case Expression::Kind::kBinary: {
2286 const BinaryExpression& bin = e->as<BinaryExpression>();
John Stiles2d4f9592020-10-30 10:29:12 -04002287 return this->requirements(bin.left().get()) |
2288 this->requirements(bin.right().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002289 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002290 case Expression::Kind::kIndex: {
John Stiles3dc0da62020-08-19 17:48:31 -04002291 const IndexExpression& idx = e->as<IndexExpression>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04002292 return this->requirements(idx.base().get()) | this->requirements(idx.index().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002293 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002294 case Expression::Kind::kPrefix:
Ethan Nicholas444ccc62020-10-09 10:16:22 -04002295 return this->requirements(e->as<PrefixExpression>().operand().get());
Ethan Nicholase6592142020-09-08 10:22:09 -04002296 case Expression::Kind::kPostfix:
Ethan Nicholas444ccc62020-10-09 10:16:22 -04002297 return this->requirements(e->as<PostfixExpression>().operand().get());
Ethan Nicholase6592142020-09-08 10:22:09 -04002298 case Expression::Kind::kTernary: {
John Stiles3dc0da62020-08-19 17:48:31 -04002299 const TernaryExpression& t = e->as<TernaryExpression>();
Ethan Nicholasdd218162020-10-08 05:48:01 -04002300 return this->requirements(t.test().get()) | this->requirements(t.ifTrue().get()) |
2301 this->requirements(t.ifFalse().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002302 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002303 case Expression::Kind::kVariableReference: {
John Stiles3dc0da62020-08-19 17:48:31 -04002304 const VariableReference& v = e->as<VariableReference>();
Ethan Nicholas78686922020-10-08 06:46:27 -04002305 const Modifiers& modifiers = v.variable()->modifiers();
Ethan Nicholascc305772017-10-13 16:17:45 -04002306 Requirements result = kNo_Requirements;
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002307 if (modifiers.fLayout.fBuiltin == SK_FRAGCOORD_BUILTIN) {
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -04002308 result = kGlobals_Requirement | kFragCoord_Requirement;
Ethan Nicholas453f67f2020-10-09 10:43:45 -04002309 } else if (Variable::Storage::kGlobal == v.variable()->storage()) {
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002310 if (modifiers.fFlags & Modifiers::kIn_Flag) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002311 result = kInputs_Requirement;
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002312 } else if (modifiers.fFlags & Modifiers::kOut_Flag) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002313 result = kOutputs_Requirement;
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002314 } else if (modifiers.fFlags & Modifiers::kUniform_Flag &&
Ethan Nicholas78686922020-10-08 06:46:27 -04002315 v.variable()->type().typeKind() != Type::TypeKind::kSampler) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002316 result = kUniforms_Requirement;
Timothy Liangee84fe12018-05-18 14:38:19 -04002317 } else {
2318 result = kGlobals_Requirement;
Ethan Nicholascc305772017-10-13 16:17:45 -04002319 }
2320 }
2321 return result;
2322 }
2323 default:
2324 return kNo_Requirements;
2325 }
2326}
2327
Ethan Nicholasff350cb2020-05-14 14:05:13 -04002328MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const Statement* s) {
2329 if (!s) {
2330 return kNo_Requirements;
2331 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002332 switch (s->kind()) {
2333 case Statement::Kind::kBlock: {
Ethan Nicholascc305772017-10-13 16:17:45 -04002334 Requirements result = kNo_Requirements;
Ethan Nicholas7bd60432020-09-25 14:31:59 -04002335 for (const std::unique_ptr<Statement>& child : s->as<Block>().children()) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04002336 result |= this->requirements(child.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002337 }
2338 return result;
2339 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002340 case Statement::Kind::kVarDeclaration: {
John Stiles3dc0da62020-08-19 17:48:31 -04002341 const VarDeclaration& var = s->as<VarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04002342 return this->requirements(var.value().get());
Timothy Liang7d637782018-06-05 09:58:07 -04002343 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002344 case Statement::Kind::kExpression:
Ethan Nicholasd503a5a2020-09-30 09:29:55 -04002345 return this->requirements(s->as<ExpressionStatement>().expression().get());
Ethan Nicholase6592142020-09-08 10:22:09 -04002346 case Statement::Kind::kReturn: {
John Stiles3dc0da62020-08-19 17:48:31 -04002347 const ReturnStatement& r = s->as<ReturnStatement>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04002348 return this->requirements(r.expression().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002349 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002350 case Statement::Kind::kIf: {
John Stiles3dc0da62020-08-19 17:48:31 -04002351 const IfStatement& i = s->as<IfStatement>();
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04002352 return this->requirements(i.test().get()) |
2353 this->requirements(i.ifTrue().get()) |
2354 this->requirements(i.ifFalse().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002355 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002356 case Statement::Kind::kFor: {
John Stiles3dc0da62020-08-19 17:48:31 -04002357 const ForStatement& f = s->as<ForStatement>();
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04002358 return this->requirements(f.initializer().get()) |
2359 this->requirements(f.test().get()) |
2360 this->requirements(f.next().get()) |
2361 this->requirements(f.statement().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002362 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002363 case Statement::Kind::kDo: {
John Stiles3dc0da62020-08-19 17:48:31 -04002364 const DoStatement& d = s->as<DoStatement>();
Ethan Nicholas1fd61162020-09-28 13:14:19 -04002365 return this->requirements(d.test().get()) |
2366 this->requirements(d.statement().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002367 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002368 case Statement::Kind::kSwitch: {
John Stiles3dc0da62020-08-19 17:48:31 -04002369 const SwitchStatement& sw = s->as<SwitchStatement>();
Ethan Nicholas01b05e52020-10-22 15:53:41 -04002370 Requirements result = this->requirements(sw.value().get());
John Stilesb23a64b2021-03-11 08:27:59 -05002371 for (const std::unique_ptr<Statement>& sc : sw.cases()) {
2372 result |= this->requirements(sc->as<SwitchCase>().statement().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002373 }
2374 return result;
2375 }
2376 default:
2377 return kNo_Requirements;
2378 }
2379}
2380
2381MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const FunctionDeclaration& f) {
Ethan Nicholased84b732020-10-08 11:45:44 -04002382 if (f.isBuiltin()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002383 return kNo_Requirements;
2384 }
2385 auto found = fRequirements.find(&f);
2386 if (found == fRequirements.end()) {
Ethan Nicholas65a8f562019-04-19 14:00:26 -04002387 fRequirements[&f] = kNo_Requirements;
Brian Osman133724c2020-10-28 14:14:39 -04002388 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04002389 if (e->is<FunctionDefinition>()) {
2390 const FunctionDefinition& def = e->as<FunctionDefinition>();
Ethan Nicholas0a5d0962020-10-14 13:33:18 -04002391 if (&def.declaration() == &f) {
2392 Requirements reqs = this->requirements(def.body().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002393 fRequirements[&f] = reqs;
2394 return reqs;
2395 }
2396 }
2397 }
John Stiles569249b2020-11-03 12:18:22 -05002398 // We never found a definition for this declared function, but it's legal to prototype a
2399 // function without ever giving a definition, as long as you don't call it.
2400 return kNo_Requirements;
Ethan Nicholascc305772017-10-13 16:17:45 -04002401 }
2402 return found->second;
2403}
2404
Timothy Liangb8eeb802018-07-23 16:46:16 -04002405bool MetalCodeGenerator::generateCode() {
John Stiles44532372020-12-07 12:33:55 -05002406 StringStream header;
2407 {
2408 AutoOutputStream outputToHeader(this, &header, &fIndentation);
Michael Ludwigbf58add2021-03-16 10:40:11 -04002409 this->writeHeader();
John Stiles44532372020-12-07 12:33:55 -05002410 this->writeStructDefinitions();
2411 this->writeUniformStruct();
2412 this->writeInputStruct();
2413 this->writeOutputStruct();
2414 this->writeInterfaceBlocks();
2415 this->writeGlobalStruct();
2416 }
2417 StringStream body;
2418 {
2419 AutoOutputStream outputToBody(this, &body, &fIndentation);
2420 for (const ProgramElement* e : fProgram.elements()) {
2421 this->writeProgramElement(*e);
2422 }
2423 }
2424 write_stringstream(header, *fOut);
2425 write_stringstream(fExtraFunctions, *fOut);
2426 write_stringstream(body, *fOut);
Brian Osman8609a242020-09-08 14:01:49 -04002427 return 0 == fErrors.errorCount();
Ethan Nicholascc305772017-10-13 16:17:45 -04002428}
2429
John Stilesa6841be2020-08-06 14:11:56 -04002430} // namespace SkSL