blob: 70fe559ce0cb6d35308407c6ddc66643fb47d5cf [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 Stilesfd7252f2021-04-04 22:24:40 -0400184 case Expression::Kind::kConstructorScalarCast:
185 this->writeConstructorScalarCast(expr.as<ConstructorScalarCast>(), parentPrecedence);
186 break;
John Stiles2938eea2021-04-01 18:58:25 -0400187 case Expression::Kind::kConstructorSplat:
188 this->writeSingleArgumentConstructor(expr.as<ConstructorSplat>(), parentPrecedence);
189 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400190 case Expression::Kind::kIntLiteral:
John Stiles81365af2020-08-18 09:24:00 -0400191 this->writeIntLiteral(expr.as<IntLiteral>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400192 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400193 case Expression::Kind::kFieldAccess:
John Stiles81365af2020-08-18 09:24:00 -0400194 this->writeFieldAccess(expr.as<FieldAccess>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400195 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400196 case Expression::Kind::kFloatLiteral:
John Stiles81365af2020-08-18 09:24:00 -0400197 this->writeFloatLiteral(expr.as<FloatLiteral>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400198 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400199 case Expression::Kind::kFunctionCall:
John Stiles81365af2020-08-18 09:24:00 -0400200 this->writeFunctionCall(expr.as<FunctionCall>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400201 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400202 case Expression::Kind::kPrefix:
John Stiles81365af2020-08-18 09:24:00 -0400203 this->writePrefixExpression(expr.as<PrefixExpression>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400204 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400205 case Expression::Kind::kPostfix:
John Stiles81365af2020-08-18 09:24:00 -0400206 this->writePostfixExpression(expr.as<PostfixExpression>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400207 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400208 case Expression::Kind::kSetting:
John Stiles81365af2020-08-18 09:24:00 -0400209 this->writeSetting(expr.as<Setting>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400210 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400211 case Expression::Kind::kSwizzle:
John Stiles81365af2020-08-18 09:24:00 -0400212 this->writeSwizzle(expr.as<Swizzle>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400213 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400214 case Expression::Kind::kVariableReference:
John Stiles81365af2020-08-18 09:24:00 -0400215 this->writeVariableReference(expr.as<VariableReference>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400216 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400217 case Expression::Kind::kTernary:
John Stiles81365af2020-08-18 09:24:00 -0400218 this->writeTernaryExpression(expr.as<TernaryExpression>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400219 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400220 case Expression::Kind::kIndex:
John Stiles81365af2020-08-18 09:24:00 -0400221 this->writeIndexExpression(expr.as<IndexExpression>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400222 break;
223 default:
John Stileseada7bc2021-02-02 16:29:32 -0500224 SkDEBUGFAILF("unsupported expression: %s", expr.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -0500225 break;
Ethan Nicholascc305772017-10-13 16:17:45 -0400226 }
227}
228
John Stiles06b84ef2020-12-09 12:35:48 -0500229String MetalCodeGenerator::getOutParamHelper(const FunctionCall& call,
230 const ExpressionArray& arguments,
231 const SkTArray<VariableReference*>& outVars) {
232 AutoOutputStream outputToExtraFunctions(this, &fExtraFunctions, &fIndentation);
233 const FunctionDeclaration& function = call.function();
234
John Stilese1068342021-03-22 11:57:41 -0400235 String name = "_skOutParamHelper" + to_string(fSwizzleHelperCount++) +
236 "_" + function.mangledName();
John Stiles06b84ef2020-12-09 12:35:48 -0500237 const char* separator = "";
238
239 // Emit a prototype for the function we'll be calling through to in our helper.
240 if (!function.isBuiltin()) {
241 this->writeFunctionDeclaration(function);
242 this->writeLine(";");
243 }
244
245 // Synthesize a helper function that takes the same inputs as `function`, except in places where
246 // `outVars` is non-null; in those places, we take the type of the VariableReference.
247 //
248 // float _skOutParamHelper0_originalFuncName(float _var0, float _var1, float& outParam) {
John Stilesb4418502021-02-04 10:57:08 -0500249 this->writeType(call.type());
John Stiles06b84ef2020-12-09 12:35:48 -0500250 this->write(" ");
251 this->write(name);
252 this->write("(");
253 this->writeFunctionRequirementParams(function, separator);
254
255 SkASSERT(outVars.size() == arguments.size());
256 SkASSERT(outVars.size() == function.parameters().size());
257
John Stiles73e2c892021-02-13 13:58:01 -0500258 // We need to detect cases where the caller passes the same variable as an out-param more than
259 // once, and avoid reusing the variable name. (In those cases we can actually just ignore the
260 // redundant input parameter entirely, and not give it any name.)
261 std::unordered_set<const Variable*> writtenVars;
262
John Stiles06b84ef2020-12-09 12:35:48 -0500263 for (int index = 0; index < arguments.count(); ++index) {
264 this->write(separator);
265 separator = ", ";
266
267 const Variable* param = function.parameters()[index];
268 this->writeModifiers(param->modifiers(), /*globalContext=*/false);
269
270 const Type* type = outVars[index] ? &outVars[index]->type() : &arguments[index]->type();
John Stilesb4418502021-02-04 10:57:08 -0500271 this->writeType(*type);
John Stiles06b84ef2020-12-09 12:35:48 -0500272
273 if (param->modifiers().fFlags & Modifiers::kOut_Flag) {
274 this->write("&");
275 }
276 if (outVars[index]) {
John Stiles73e2c892021-02-13 13:58:01 -0500277 auto [iter, didInsert] = writtenVars.insert(outVars[index]->variable());
278 if (didInsert) {
279 this->write(" ");
280 fIgnoreVariableReferenceModifiers = true;
281 this->writeVariableReference(*outVars[index]);
282 fIgnoreVariableReferenceModifiers = false;
283 }
John Stiles06b84ef2020-12-09 12:35:48 -0500284 } else {
285 this->write(" _var");
286 this->write(to_string(index));
287 }
John Stiles06b84ef2020-12-09 12:35:48 -0500288 }
289 this->writeLine(") {");
290
291 ++fIndentation;
292 for (int index = 0; index < outVars.count(); ++index) {
293 if (!outVars[index]) {
294 continue;
295 }
296 // float3 _var2[ = outParam.zyx];
John Stilesb4418502021-02-04 10:57:08 -0500297 this->writeType(arguments[index]->type());
John Stiles06b84ef2020-12-09 12:35:48 -0500298 this->write(" _var");
299 this->write(to_string(index));
300
301 const Variable* param = function.parameters()[index];
302 if (param->modifiers().fFlags & Modifiers::kIn_Flag) {
303 this->write(" = ");
304 fIgnoreVariableReferenceModifiers = true;
Brian Osman00185012021-02-04 16:07:11 -0500305 this->writeExpression(*arguments[index], Precedence::kAssignment);
John Stiles06b84ef2020-12-09 12:35:48 -0500306 fIgnoreVariableReferenceModifiers = false;
307 }
308
309 this->writeLine(";");
310 }
311
John Stilesf7410bd2021-01-19 13:07:55 -0500312 // [int _skResult = ] myFunction(inputs, outputs, _globals, _var0, _var1, _var2, _var3);
John Stiles06b84ef2020-12-09 12:35:48 -0500313 bool hasResult = (call.type().name() != "void");
314 if (hasResult) {
John Stilesb4418502021-02-04 10:57:08 -0500315 this->writeType(call.type());
John Stiles06b84ef2020-12-09 12:35:48 -0500316 this->write(" _skResult = ");
317 }
318
John Stilese1068342021-03-22 11:57:41 -0400319 this->writeName(function.mangledName());
John Stiles06b84ef2020-12-09 12:35:48 -0500320 this->write("(");
321 separator = "";
322 this->writeFunctionRequirementArgs(function, separator);
323
324 for (int index = 0; index < arguments.count(); ++index) {
325 this->write(separator);
326 separator = ", ";
327
328 this->write("_var");
329 this->write(to_string(index));
330 }
331 this->writeLine(");");
332
333 for (int index = 0; index < outVars.count(); ++index) {
334 if (!outVars[index]) {
335 continue;
336 }
337 // outParam.zyx = _var2;
338 fIgnoreVariableReferenceModifiers = true;
Brian Osman00185012021-02-04 16:07:11 -0500339 this->writeExpression(*arguments[index], Precedence::kAssignment);
John Stiles06b84ef2020-12-09 12:35:48 -0500340 fIgnoreVariableReferenceModifiers = false;
341 this->write(" = _var");
342 this->write(to_string(index));
343 this->writeLine(";");
344 }
345
346 if (hasResult) {
347 this->writeLine("return _skResult;");
348 }
349
350 --fIndentation;
351 this->writeLine("}");
352
353 return name;
John Stilesb21fac22020-12-04 15:36:49 -0500354}
355
John Stilesf64e4072020-12-10 10:34:27 -0500356String MetalCodeGenerator::getBitcastIntrinsic(const Type& outType) {
357 return "as_type<" + outType.displayName() + ">";
358}
359
Ethan Nicholascc305772017-10-13 16:17:45 -0400360void MetalCodeGenerator::writeFunctionCall(const FunctionCall& c) {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400361 const FunctionDeclaration& function = c.function();
John Stiles89ac7c22020-12-30 17:47:31 -0500362 // If this function is a built-in with no declaration, it's probably an intrinsic and might need
363 // special handling.
364 if (function.isBuiltin() && !function.definition()) {
365 auto iter = fIntrinsicMap.find(function.name());
366 if (iter != fIntrinsicMap.end()) {
367 this->writeIntrinsicCall(c, iter->second);
368 return;
369 }
Timothy Liang6403b0e2018-05-17 10:40:04 -0400370 }
John Stilesb21fac22020-12-04 15:36:49 -0500371
John Stilesd7199b22020-12-30 16:22:58 -0500372 // Determine whether or not we need to emulate GLSL's out-param semantics for Metal using a
373 // helper function. (Specifically, out-parameters in GLSL are only written back to the original
374 // variable at the end of the function call; also, swizzles are supported, whereas Metal doesn't
375 // allow a swizzle to be passed to a `floatN&`.)
376 const ExpressionArray& arguments = c.arguments();
John Stilesb21fac22020-12-04 15:36:49 -0500377 const std::vector<const Variable*>& parameters = function.parameters();
378 SkASSERT(arguments.size() == parameters.size());
John Stiles06b84ef2020-12-09 12:35:48 -0500379
380 bool foundOutParam = false;
381 SkSTArray<16, VariableReference*> outVars;
John Stilesf64e4072020-12-10 10:34:27 -0500382 outVars.push_back_n(arguments.count(), (VariableReference*)nullptr);
John Stiles06b84ef2020-12-09 12:35:48 -0500383
384 for (int index = 0; index < arguments.count(); ++index) {
John Stilesb21fac22020-12-04 15:36:49 -0500385 // If this is an out parameter...
386 if (parameters[index]->modifiers().fFlags & Modifiers::kOut_Flag) {
John Stiles06b84ef2020-12-09 12:35:48 -0500387 // Find the expression's inner variable being written to.
John Stilesb21fac22020-12-04 15:36:49 -0500388 Analysis::AssignmentInfo info;
John Stiles06b84ef2020-12-09 12:35:48 -0500389 // Assignability was verified at IRGeneration time, so this should always succeed.
390 SkAssertResult(Analysis::IsAssignable(*arguments[index], &info));
391 outVars[index] = info.fAssignedVar;
392 foundOutParam = true;
John Stilesb21fac22020-12-04 15:36:49 -0500393 }
394 }
395
John Stiles06b84ef2020-12-09 12:35:48 -0500396 if (foundOutParam) {
397 // Out parameters need to be written back to at the end of the function. To do this, we
398 // synthesize a helper function which evaluates the out-param expression into a temporary
399 // variable, calls the original function, then writes the temp var back into the out param
400 // using the original out-param expression. (This lets us support things like swizzles and
401 // array indices.)
John Stilesd7199b22020-12-30 16:22:58 -0500402 this->write(getOutParamHelper(c, arguments, outVars));
403 } else {
John Stilese1068342021-03-22 11:57:41 -0400404 this->write(function.mangledName());
John Stiles06b84ef2020-12-09 12:35:48 -0500405 }
406
Ethan Nicholascc305772017-10-13 16:17:45 -0400407 this->write("(");
408 const char* separator = "";
John Stiles06b84ef2020-12-09 12:35:48 -0500409 this->writeFunctionRequirementArgs(function, separator);
410 for (int i = 0; i < arguments.count(); ++i) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400411 this->write(separator);
412 separator = ", ";
John Stiles06b84ef2020-12-09 12:35:48 -0500413
414 if (outVars[i]) {
Brian Osman00185012021-02-04 16:07:11 -0500415 this->writeExpression(*outVars[i], Precedence::kSequence);
John Stiles06b84ef2020-12-09 12:35:48 -0500416 } else {
Brian Osman00185012021-02-04 16:07:11 -0500417 this->writeExpression(*arguments[i], Precedence::kSequence);
John Stiles06b84ef2020-12-09 12:35:48 -0500418 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400419 }
420 this->write(")");
421}
422
Brian Osman964f0a02020-12-29 10:15:22 -0500423static constexpr char kInverse2x2[] = R"(
424float2x2 float2x2_inverse(float2x2 m) {
425 return float2x2(m[1][1], -m[0][1], -m[1][0], m[0][0]) * (1/determinant(m));
426}
427)";
428
429static constexpr char kInverse3x3[] = R"(
430float3x3 float3x3_inverse(float3x3 m) {
431 float a00 = m[0][0], a01 = m[0][1], a02 = m[0][2];
432 float a10 = m[1][0], a11 = m[1][1], a12 = m[1][2];
433 float a20 = m[2][0], a21 = m[2][1], a22 = m[2][2];
434 float b01 = a22*a11 - a12*a21;
435 float b11 = -a22*a10 + a12*a20;
436 float b21 = a21*a10 - a11*a20;
437 float det = a00*b01 + a01*b11 + a02*b21;
438 return float3x3(b01, (-a22*a01 + a02*a21), ( a12*a01 - a02*a11),
439 b11, ( a22*a00 - a02*a20), (-a12*a00 + a02*a10),
440 b21, (-a21*a00 + a01*a20), ( a11*a00 - a01*a10)) * (1/det);
441}
442)";
443
444static constexpr char kInverse4x4[] = R"(
445float4x4 float4x4_inverse(float4x4 m) {
446 float a00 = m[0][0], a01 = m[0][1], a02 = m[0][2], a03 = m[0][3];
447 float a10 = m[1][0], a11 = m[1][1], a12 = m[1][2], a13 = m[1][3];
448 float a20 = m[2][0], a21 = m[2][1], a22 = m[2][2], a23 = m[2][3];
449 float a30 = m[3][0], a31 = m[3][1], a32 = m[3][2], a33 = m[3][3];
450 float b00 = a00*a11 - a01*a10;
451 float b01 = a00*a12 - a02*a10;
452 float b02 = a00*a13 - a03*a10;
453 float b03 = a01*a12 - a02*a11;
454 float b04 = a01*a13 - a03*a11;
455 float b05 = a02*a13 - a03*a12;
456 float b06 = a20*a31 - a21*a30;
457 float b07 = a20*a32 - a22*a30;
458 float b08 = a20*a33 - a23*a30;
459 float b09 = a21*a32 - a22*a31;
460 float b10 = a21*a33 - a23*a31;
461 float b11 = a22*a33 - a23*a32;
462 float det = b00*b11 - b01*b10 + b02*b09 + b03*b08 - b04*b07 + b05*b06;
463 return float4x4(a11*b11 - a12*b10 + a13*b09,
464 a02*b10 - a01*b11 - a03*b09,
465 a31*b05 - a32*b04 + a33*b03,
466 a22*b04 - a21*b05 - a23*b03,
467 a12*b08 - a10*b11 - a13*b07,
468 a00*b11 - a02*b08 + a03*b07,
469 a32*b02 - a30*b05 - a33*b01,
470 a20*b05 - a22*b02 + a23*b01,
471 a10*b10 - a11*b08 + a13*b06,
472 a01*b08 - a00*b10 - a03*b06,
473 a30*b04 - a31*b02 + a33*b00,
474 a21*b02 - a20*b04 - a23*b00,
475 a11*b07 - a10*b09 - a12*b06,
476 a00*b09 - a01*b07 + a02*b06,
477 a31*b01 - a30*b03 - a32*b00,
478 a20*b03 - a21*b01 + a22*b00) * (1/det);
479}
480)";
481
John Stilesd7199b22020-12-30 16:22:58 -0500482String MetalCodeGenerator::getInversePolyfill(const ExpressionArray& arguments) {
483 // Only use polyfills for a function taking a single-argument square matrix.
484 if (arguments.size() == 1) {
485 const Type& type = arguments.front()->type();
486 if (type.isMatrix() && type.rows() == type.columns()) {
487 // Inject the correct polyfill based on the matrix size.
488 String name = this->typeName(type) + "_inverse";
489 auto [iter, didInsert] = fWrittenIntrinsics.insert(name);
490 if (didInsert) {
491 switch (type.rows()) {
492 case 2:
493 fExtraFunctions.writeText(kInverse2x2);
494 break;
495 case 3:
496 fExtraFunctions.writeText(kInverse3x3);
497 break;
498 case 4:
499 fExtraFunctions.writeText(kInverse4x4);
500 break;
501 }
502 }
503 return name;
Chris Daltondba7aab2018-11-15 10:57:49 -0500504 }
505 }
John Stilesd7199b22020-12-30 16:22:58 -0500506 // This isn't the built-in `inverse`. We don't want to polyfill it at all.
507 return "inverse";
Chris Daltondba7aab2018-11-15 10:57:49 -0500508}
509
Brian Osman93aed9a2020-12-28 15:18:46 -0500510static constexpr char kMatrixCompMult[] = R"(
511template <int C, int R>
512matrix<float, C, R> matrixCompMult(matrix<float, C, R> a, matrix<float, C, R> b) {
513 matrix<float, C, R> result;
514 for (int c = 0; c < C; ++c) {
515 result[c] = a[c] * b[c];
516 }
517 return result;
518}
519)";
520
521void MetalCodeGenerator::writeMatrixCompMult() {
522 String name = "matrixCompMult";
523 if (fWrittenIntrinsics.find(name) == fWrittenIntrinsics.end()) {
524 fWrittenIntrinsics.insert(name);
525 fExtraFunctions.writeText(kMatrixCompMult);
526 }
527}
528
John Stiles86424eb2020-12-11 11:17:14 -0500529String MetalCodeGenerator::getTempVariable(const Type& type) {
530 String tempVar = "_skTemp" + to_string(fVarCount++);
531 this->fFunctionHeader += " " + this->typeName(type) + " " + tempVar + ";\n";
532 return tempVar;
533}
534
John Stiles791c27d2020-12-30 14:56:57 -0500535void MetalCodeGenerator::writeSimpleIntrinsic(const FunctionCall& c) {
536 // Write out an intrinsic function call exactly as-is. No muss no fuss.
537 this->write(c.function().name());
John Stilesd7199b22020-12-30 16:22:58 -0500538 this->writeArgumentList(c.arguments());
539}
540
541void MetalCodeGenerator::writeArgumentList(const ExpressionArray& arguments) {
John Stiles791c27d2020-12-30 14:56:57 -0500542 this->write("(");
543 const char* separator = "";
John Stilesd7199b22020-12-30 16:22:58 -0500544 for (const std::unique_ptr<Expression>& arg : arguments) {
John Stiles791c27d2020-12-30 14:56:57 -0500545 this->write(separator);
546 separator = ", ";
Brian Osman00185012021-02-04 16:07:11 -0500547 this->writeExpression(*arg, Precedence::kSequence);
John Stiles791c27d2020-12-30 14:56:57 -0500548 }
549 this->write(")");
550}
551
John Stilesd7199b22020-12-30 16:22:58 -0500552void MetalCodeGenerator::writeIntrinsicCall(const FunctionCall& c, IntrinsicKind kind) {
John Stiles8e3b6be2020-10-13 11:14:08 -0400553 const ExpressionArray& arguments = c.arguments();
Timothy Liang6403b0e2018-05-17 10:40:04 -0400554 switch (kind) {
John Stilesd7199b22020-12-30 16:22:58 -0500555 case kTexture_IntrinsicKind: {
Brian Osman00185012021-02-04 16:07:11 -0500556 this->writeExpression(*arguments[0], Precedence::kSequence);
Timothy Lianga06f2152018-05-24 15:33:31 -0400557 this->write(".sample(");
Brian Osman00185012021-02-04 16:07:11 -0500558 this->writeExpression(*arguments[0], Precedence::kSequence);
Timothy Lianga06f2152018-05-24 15:33:31 -0400559 this->write(SAMPLER_SUFFIX);
560 this->write(", ");
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400561 const Type& arg1Type = arguments[1]->type();
John Stiles54e7c052021-01-11 14:22:36 -0500562 if (arg1Type == *fContext.fTypes.fFloat3) {
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500563 // have to store the vector in a temp variable to avoid double evaluating it
John Stiles86424eb2020-12-11 11:17:14 -0500564 String tmpVar = this->getTempVariable(arg1Type);
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500565 this->write("(" + tmpVar + " = ");
Brian Osman00185012021-02-04 16:07:11 -0500566 this->writeExpression(*arguments[1], Precedence::kSequence);
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500567 this->write(", " + tmpVar + ".xy / " + tmpVar + ".z))");
Timothy Liangee84fe12018-05-18 14:38:19 -0400568 } else {
John Stiles54e7c052021-01-11 14:22:36 -0500569 SkASSERT(arg1Type == *fContext.fTypes.fFloat2);
Brian Osman00185012021-02-04 16:07:11 -0500570 this->writeExpression(*arguments[1], Precedence::kSequence);
Timothy Liangee84fe12018-05-18 14:38:19 -0400571 this->write(")");
572 }
Timothy Liang6403b0e2018-05-17 10:40:04 -0400573 break;
Ethan Nicholas30d30222020-09-11 12:27:26 -0400574 }
John Stilesd7199b22020-12-30 16:22:58 -0500575 case kMod_IntrinsicKind: {
Timothy Liang651286f2018-06-07 09:55:33 -0400576 // 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 -0500577 String tmpX = this->getTempVariable(arguments[0]->type());
John Stiles61b2e812020-12-30 18:27:31 -0500578 String tmpY = this->getTempVariable(arguments[1]->type());
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500579 this->write("(" + tmpX + " = ");
Brian Osman00185012021-02-04 16:07:11 -0500580 this->writeExpression(*arguments[0], Precedence::kSequence);
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500581 this->write(", " + tmpY + " = ");
Brian Osman00185012021-02-04 16:07:11 -0500582 this->writeExpression(*arguments[1], Precedence::kSequence);
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500583 this->write(", " + tmpX + " - " + tmpY + " * floor(" + tmpX + " / " + tmpY + "))");
Timothy Liang651286f2018-06-07 09:55:33 -0400584 break;
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500585 }
Brian Osman46787d52020-11-24 14:18:23 -0500586 // GLSL declares scalar versions of most geometric intrinsics, but these don't exist in MSL
John Stilesd7199b22020-12-30 16:22:58 -0500587 case kDistance_IntrinsicKind: {
Brian Osman46787d52020-11-24 14:18:23 -0500588 if (arguments[0]->type().columns() == 1) {
589 this->write("abs(");
Brian Osman00185012021-02-04 16:07:11 -0500590 this->writeExpression(*arguments[0], Precedence::kAdditive);
Brian Osman46787d52020-11-24 14:18:23 -0500591 this->write(" - ");
Brian Osman00185012021-02-04 16:07:11 -0500592 this->writeExpression(*arguments[1], Precedence::kAdditive);
Brian Osman46787d52020-11-24 14:18:23 -0500593 this->write(")");
594 } else {
John Stiles791c27d2020-12-30 14:56:57 -0500595 this->writeSimpleIntrinsic(c);
Brian Osman46787d52020-11-24 14:18:23 -0500596 }
597 break;
598 }
John Stilesd7199b22020-12-30 16:22:58 -0500599 case kDot_IntrinsicKind: {
Brian Osman46787d52020-11-24 14:18:23 -0500600 if (arguments[0]->type().columns() == 1) {
601 this->write("(");
Brian Osman00185012021-02-04 16:07:11 -0500602 this->writeExpression(*arguments[0], Precedence::kMultiplicative);
Brian Osman46787d52020-11-24 14:18:23 -0500603 this->write(" * ");
Brian Osman00185012021-02-04 16:07:11 -0500604 this->writeExpression(*arguments[1], Precedence::kMultiplicative);
Brian Osman46787d52020-11-24 14:18:23 -0500605 this->write(")");
606 } else {
John Stiles791c27d2020-12-30 14:56:57 -0500607 this->writeSimpleIntrinsic(c);
Brian Osman46787d52020-11-24 14:18:23 -0500608 }
609 break;
610 }
John Stilesd7199b22020-12-30 16:22:58 -0500611 case kFaceforward_IntrinsicKind: {
John Stilesad0571f2020-12-10 18:03:10 -0500612 if (arguments[0]->type().columns() == 1) {
613 // ((((Nref) * (I) < 0) ? 1 : -1) * (N))
614 this->write("((((");
Brian Osman00185012021-02-04 16:07:11 -0500615 this->writeExpression(*arguments[2], Precedence::kSequence);
John Stilesad0571f2020-12-10 18:03:10 -0500616 this->write(") * (");
Brian Osman00185012021-02-04 16:07:11 -0500617 this->writeExpression(*arguments[1], Precedence::kSequence);
John Stilesad0571f2020-12-10 18:03:10 -0500618 this->write(") < 0) ? 1 : -1) * (");
Brian Osman00185012021-02-04 16:07:11 -0500619 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stilesad0571f2020-12-10 18:03:10 -0500620 this->write("))");
621 } else {
John Stiles791c27d2020-12-30 14:56:57 -0500622 this->writeSimpleIntrinsic(c);
John Stilesad0571f2020-12-10 18:03:10 -0500623 }
624 break;
625 }
John Stilesd7199b22020-12-30 16:22:58 -0500626 case kLength_IntrinsicKind: {
Brian Osman46787d52020-11-24 14:18:23 -0500627 this->write(arguments[0]->type().columns() == 1 ? "abs(" : "length(");
Brian Osman00185012021-02-04 16:07:11 -0500628 this->writeExpression(*arguments[0], Precedence::kSequence);
Brian Osman46787d52020-11-24 14:18:23 -0500629 this->write(")");
630 break;
631 }
John Stilesd7199b22020-12-30 16:22:58 -0500632 case kNormalize_IntrinsicKind: {
Brian Osman46787d52020-11-24 14:18:23 -0500633 this->write(arguments[0]->type().columns() == 1 ? "sign(" : "normalize(");
Brian Osman00185012021-02-04 16:07:11 -0500634 this->writeExpression(*arguments[0], Precedence::kSequence);
Brian Osman46787d52020-11-24 14:18:23 -0500635 this->write(")");
636 break;
637 }
John Stilesd7199b22020-12-30 16:22:58 -0500638 case kBitcast_IntrinsicKind: {
John Stiles0063a9f2020-12-10 18:01:45 -0500639 this->write(this->getBitcastIntrinsic(c.type()));
640 this->write("(");
Brian Osman00185012021-02-04 16:07:11 -0500641 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stiles0063a9f2020-12-10 18:01:45 -0500642 this->write(")");
643 break;
644 }
John Stilesd7199b22020-12-30 16:22:58 -0500645 case kDegrees_IntrinsicKind: {
John Stilese2d34f82020-12-10 18:02:02 -0500646 this->write("((");
Brian Osman00185012021-02-04 16:07:11 -0500647 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stilese2d34f82020-12-10 18:02:02 -0500648 this->write(") * 57.2957795)");
649 break;
650 }
John Stilesd7199b22020-12-30 16:22:58 -0500651 case kRadians_IntrinsicKind: {
John Stilese2d34f82020-12-10 18:02:02 -0500652 this->write("((");
Brian Osman00185012021-02-04 16:07:11 -0500653 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stilese2d34f82020-12-10 18:02:02 -0500654 this->write(") * 0.0174532925)");
655 break;
656 }
John Stilesd7199b22020-12-30 16:22:58 -0500657 case kDFdx_IntrinsicKind: {
658 this->write("dfdx");
659 this->writeArgumentList(c.arguments());
660 break;
661 }
662 case kDFdy_IntrinsicKind: {
663 // Flipping Y also negates the Y derivatives.
John Stiles270cec22021-02-17 12:59:36 -0500664 if (fProgram.fConfig->fSettings.fFlipY) {
John Stilesd7199b22020-12-30 16:22:58 -0500665 this->write("-");
666 }
667 this->write("dfdy");
668 this->writeArgumentList(c.arguments());
669 break;
670 }
671 case kInverse_IntrinsicKind: {
672 this->write(this->getInversePolyfill(arguments));
673 this->writeArgumentList(c.arguments());
674 break;
675 }
676 case kInversesqrt_IntrinsicKind: {
677 this->write("rsqrt");
678 this->writeArgumentList(c.arguments());
679 break;
680 }
681 case kAtan_IntrinsicKind: {
682 this->write(c.arguments().size() == 2 ? "atan2" : "atan");
683 this->writeArgumentList(c.arguments());
684 break;
685 }
686 case kReflect_IntrinsicKind: {
John Stiles791c27d2020-12-30 14:56:57 -0500687 if (arguments[0]->type().columns() == 1) {
688 // We need to synthesize `I - 2 * N * I * N`.
689 String tmpI = this->getTempVariable(arguments[0]->type());
690 String tmpN = this->getTempVariable(arguments[1]->type());
691
692 // (_skTempI = ...
693 this->write("(" + tmpI + " = ");
Brian Osman00185012021-02-04 16:07:11 -0500694 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stiles791c27d2020-12-30 14:56:57 -0500695
696 // , _skTempN = ...
697 this->write(", " + tmpN + " = ");
Brian Osman00185012021-02-04 16:07:11 -0500698 this->writeExpression(*arguments[1], Precedence::kSequence);
John Stiles791c27d2020-12-30 14:56:57 -0500699
700 // , _skTempI - 2 * _skTempN * _skTempI * _skTempN)
701 this->write(", " + tmpI + " - 2 * " + tmpN + " * " + tmpI + " * " + tmpN + ")");
702 } else {
703 this->writeSimpleIntrinsic(c);
704 }
705 break;
706 }
John Stilesd7199b22020-12-30 16:22:58 -0500707 case kRefract_IntrinsicKind: {
John Stiles4b783d62020-12-30 14:58:07 -0500708 if (arguments[0]->type().columns() == 1) {
709 // Metal does implement refract for vectors; rather than reimplementing refract from
710 // scratch, we can replace the call with `refract(float2(I,0), float2(N,0), eta).x`.
711 this->write("(refract(float2(");
Brian Osman00185012021-02-04 16:07:11 -0500712 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stiles4b783d62020-12-30 14:58:07 -0500713 this->write(", 0), float2(");
Brian Osman00185012021-02-04 16:07:11 -0500714 this->writeExpression(*arguments[1], Precedence::kSequence);
John Stiles4b783d62020-12-30 14:58:07 -0500715 this->write(", 0), ");
Brian Osman00185012021-02-04 16:07:11 -0500716 this->writeExpression(*arguments[2], Precedence::kSequence);
John Stiles4b783d62020-12-30 14:58:07 -0500717 this->write(").x)");
718 } else {
719 this->writeSimpleIntrinsic(c);
720 }
721 break;
722 }
John Stiles23456532020-12-30 18:12:48 -0500723 case kRoundEven_IntrinsicKind: {
724 this->write("rint");
725 this->writeArgumentList(c.arguments());
726 break;
727 }
John Stilesd7199b22020-12-30 16:22:58 -0500728 case kBitCount_IntrinsicKind: {
John Stilese7dc7cb2020-12-22 15:37:14 -0500729 this->write("popcount(");
Brian Osman00185012021-02-04 16:07:11 -0500730 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stilese7dc7cb2020-12-22 15:37:14 -0500731 this->write(")");
732 break;
733 }
John Stilesd7199b22020-12-30 16:22:58 -0500734 case kFindLSB_IntrinsicKind: {
John Stiles86424eb2020-12-11 11:17:14 -0500735 // Create a temp variable to store the expression, to avoid double-evaluating it.
736 String skTemp = this->getTempVariable(arguments[0]->type());
737 String exprType = this->typeName(arguments[0]->type());
738
739 // ctz returns numbits(type) on zero inputs; GLSL documents it as generating -1 instead.
740 // Use select to detect zero inputs and force a -1 result.
741
742 // (_skTemp1 = (.....), select(ctz(_skTemp1), int4(-1), _skTemp1 == int4(0)))
743 this->write("(");
744 this->write(skTemp);
745 this->write(" = (");
Brian Osman00185012021-02-04 16:07:11 -0500746 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stiles86424eb2020-12-11 11:17:14 -0500747 this->write("), select(ctz(");
748 this->write(skTemp);
749 this->write("), ");
750 this->write(exprType);
751 this->write("(-1), ");
752 this->write(skTemp);
753 this->write(" == ");
754 this->write(exprType);
755 this->write("(0)))");
756 break;
757 }
John Stilesd7199b22020-12-30 16:22:58 -0500758 case kFindMSB_IntrinsicKind: {
John Stiles9685e522020-12-14 11:52:14 -0500759 // Create a temp variable to store the expression, to avoid double-evaluating it.
760 String skTemp1 = this->getTempVariable(arguments[0]->type());
761 String exprType = this->typeName(arguments[0]->type());
762
763 // GLSL findMSB is actually quite different from Metal's clz:
764 // - For signed negative numbers, it returns the first zero bit, not the first one bit!
765 // - For an empty input (0/~0 depending on sign), findMSB gives -1; clz is numbits(type)
766
767 // (_skTemp1 = (.....),
768 this->write("(");
769 this->write(skTemp1);
770 this->write(" = (");
Brian Osman00185012021-02-04 16:07:11 -0500771 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stiles9685e522020-12-14 11:52:14 -0500772 this->write("), ");
773
774 // Signed input types might be negative; we need another helper variable to negate the
775 // input (since we can only find one bits, not zero bits).
776 String skTemp2;
777 if (arguments[0]->type().isSigned()) {
778 // ... _skTemp2 = (select(_skTemp1, ~_skTemp1, _skTemp1 < 0)),
779 skTemp2 = this->getTempVariable(arguments[0]->type());
780 this->write(skTemp2);
781 this->write(" = (select(");
782 this->write(skTemp1);
783 this->write(", ~");
784 this->write(skTemp1);
785 this->write(", ");
786 this->write(skTemp1);
787 this->write(" < 0)), ");
788 } else {
789 skTemp2 = skTemp1;
790 }
791
792 // ... select(int4(clz(_skTemp2)), int4(-1), _skTemp2 == int4(0)))
793 this->write("select(");
794 this->write(this->typeName(c.type()));
795 this->write("(clz(");
796 this->write(skTemp2);
797 this->write(")), ");
798 this->write(this->typeName(c.type()));
799 this->write("(-1), ");
800 this->write(skTemp2);
801 this->write(" == ");
802 this->write(exprType);
803 this->write("(0)))");
804 break;
805 }
John Stilesd7199b22020-12-30 16:22:58 -0500806 case kMatrixCompMult_IntrinsicKind: {
807 this->writeMatrixCompMult();
808 this->writeSimpleIntrinsic(c);
809 break;
810 }
811 case kCompareEqual_IntrinsicKind:
812 case kCompareGreaterThan_IntrinsicKind:
813 case kCompareGreaterThanEqual_IntrinsicKind:
814 case kCompareLessThan_IntrinsicKind:
815 case kCompareLessThanEqual_IntrinsicKind:
816 case kCompareNotEqual_IntrinsicKind: {
817 this->write("(");
Brian Osman00185012021-02-04 16:07:11 -0500818 this->writeExpression(*c.arguments()[0], Precedence::kRelational);
John Stilesd7199b22020-12-30 16:22:58 -0500819 switch (kind) {
820 case kCompareEqual_IntrinsicKind:
821 this->write(" == ");
822 break;
823 case kCompareNotEqual_IntrinsicKind:
824 this->write(" != ");
825 break;
826 case kCompareLessThan_IntrinsicKind:
827 this->write(" < ");
828 break;
829 case kCompareLessThanEqual_IntrinsicKind:
830 this->write(" <= ");
831 break;
832 case kCompareGreaterThan_IntrinsicKind:
833 this->write(" > ");
834 break;
835 case kCompareGreaterThanEqual_IntrinsicKind:
836 this->write(" >= ");
837 break;
838 default:
John Stilesf57207b2021-02-02 17:50:34 -0500839 SK_ABORT("unsupported comparison intrinsic kind");
John Stilesd7199b22020-12-30 16:22:58 -0500840 }
Brian Osman00185012021-02-04 16:07:11 -0500841 this->writeExpression(*c.arguments()[1], Precedence::kRelational);
John Stilesd7199b22020-12-30 16:22:58 -0500842 this->write(")");
843 break;
844 }
Timothy Liang6403b0e2018-05-17 10:40:04 -0400845 default:
John Stilesf57207b2021-02-02 17:50:34 -0500846 SK_ABORT("unsupported intrinsic kind");
Timothy Liang6403b0e2018-05-17 10:40:04 -0400847 }
848}
849
John Stilesfcf8cb22020-08-06 14:29:22 -0400850// Assembles a matrix of type floatRxC by resizing another matrix named `x0`.
851// Cells that don't exist in the source matrix will be populated with identity-matrix values.
852void MetalCodeGenerator::assembleMatrixFromMatrix(const Type& sourceMatrix, int rows, int columns) {
853 SkASSERT(rows <= 4);
854 SkASSERT(columns <= 4);
855
856 const char* columnSeparator = "";
857 for (int c = 0; c < columns; ++c) {
858 fExtraFunctions.printf("%sfloat%d(", columnSeparator, rows);
859 columnSeparator = "), ";
860
861 // Determine how many values to take from the source matrix for this row.
862 int swizzleLength = 0;
863 if (c < sourceMatrix.columns()) {
864 swizzleLength = std::min<>(rows, sourceMatrix.rows());
865 }
866
867 // Emit all the values from the source matrix row.
868 bool firstItem;
869 switch (swizzleLength) {
870 case 0: firstItem = true; break;
871 case 1: firstItem = false; fExtraFunctions.printf("x0[%d].x", c); break;
872 case 2: firstItem = false; fExtraFunctions.printf("x0[%d].xy", c); break;
873 case 3: firstItem = false; fExtraFunctions.printf("x0[%d].xyz", c); break;
874 case 4: firstItem = false; fExtraFunctions.printf("x0[%d].xyzw", c); break;
875 default: SkUNREACHABLE;
876 }
877
878 // Emit the placeholder identity-matrix cells.
879 for (int r = swizzleLength; r < rows; ++r) {
880 fExtraFunctions.printf("%s%s", firstItem ? "" : ", ", (r == c) ? "1.0" : "0.0");
881 firstItem = false;
882 }
883 }
884
885 fExtraFunctions.writeText(")");
886}
887
888// Assembles a matrix of type floatRxC by concatenating an arbitrary mix of values, named `x0`,
889// `x1`, etc. An error is written if the expression list don't contain exactly R*C scalars.
John Stiles8e3b6be2020-10-13 11:14:08 -0400890void MetalCodeGenerator::assembleMatrixFromExpressions(const ExpressionArray& args,
891 int rows, int columns) {
John Stilesfcf8cb22020-08-06 14:29:22 -0400892 size_t argIndex = 0;
893 int argPosition = 0;
894
895 const char* columnSeparator = "";
896 for (int c = 0; c < columns; ++c) {
897 fExtraFunctions.printf("%sfloat%d(", columnSeparator, rows);
898 columnSeparator = "), ";
899
900 const char* rowSeparator = "";
901 for (int r = 0; r < rows; ++r) {
902 fExtraFunctions.writeText(rowSeparator);
903 rowSeparator = ", ";
904
905 if (argIndex < args.size()) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400906 const Type& argType = args[argIndex]->type();
Ethan Nicholase6592142020-09-08 10:22:09 -0400907 switch (argType.typeKind()) {
908 case Type::TypeKind::kScalar: {
John Stilesfcf8cb22020-08-06 14:29:22 -0400909 fExtraFunctions.printf("x%zu", argIndex);
910 break;
911 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400912 case Type::TypeKind::kVector: {
John Stilesfcf8cb22020-08-06 14:29:22 -0400913 fExtraFunctions.printf("x%zu[%d]", argIndex, argPosition);
914 break;
915 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400916 case Type::TypeKind::kMatrix: {
John Stilesfcf8cb22020-08-06 14:29:22 -0400917 fExtraFunctions.printf("x%zu[%d][%d]", argIndex,
918 argPosition / argType.rows(),
919 argPosition % argType.rows());
920 break;
921 }
922 default: {
923 SkDEBUGFAIL("incorrect type of argument for matrix constructor");
924 fExtraFunctions.writeText("<error>");
925 break;
926 }
927 }
928
929 ++argPosition;
930 if (argPosition >= argType.columns() * argType.rows()) {
931 ++argIndex;
932 argPosition = 0;
933 }
934 } else {
935 SkDEBUGFAIL("not enough arguments for matrix constructor");
936 fExtraFunctions.writeText("<error>");
937 }
938 }
939 }
940
941 if (argPosition != 0 || argIndex != args.size()) {
942 SkDEBUGFAIL("incorrect number of arguments for matrix constructor");
943 fExtraFunctions.writeText(", <error>");
944 }
945
946 fExtraFunctions.writeText(")");
947}
948
John Stiles1bdafbf2020-05-28 12:17:20 -0400949// Generates a constructor for 'matrix' which reorganizes the input arguments into the proper shape.
950// Keeps track of previously generated constructors so that we won't generate more than one
951// constructor for any given permutation of input argument types. Returns the name of the
952// generated constructor method.
953String MetalCodeGenerator::getMatrixConstructHelper(const Constructor& c) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400954 const Type& matrix = c.type();
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500955 int columns = matrix.columns();
956 int rows = matrix.rows();
John Stiles8e3b6be2020-10-13 11:14:08 -0400957 const ExpressionArray& args = c.arguments();
John Stiles1bdafbf2020-05-28 12:17:20 -0400958
959 // Create the helper-method name and use it as our lookup key.
960 String name;
961 name.appendf("float%dx%d_from", columns, rows);
962 for (const std::unique_ptr<Expression>& expr : args) {
John Stiles36129132020-12-29 12:28:04 -0500963 name.appendf("_%s", this->typeName(expr->type()).c_str());
John Stiles1bdafbf2020-05-28 12:17:20 -0400964 }
965
966 // If a helper-method has already been synthesized, we don't need to synthesize it again.
967 auto [iter, newlyCreated] = fHelpers.insert(name);
968 if (!newlyCreated) {
969 return name;
970 }
971
972 // Unlike GLSL, Metal requires that matrices are initialized with exactly R vectors of C
973 // components apiece. (In Metal 2.0, you can also supply R*C scalars, but you still cannot
974 // supply a mixture of scalars and vectors.)
975 fExtraFunctions.printf("float%dx%d %s(", columns, rows, name.c_str());
976
977 size_t argIndex = 0;
978 const char* argSeparator = "";
John Stilesfcf8cb22020-08-06 14:29:22 -0400979 for (const std::unique_ptr<Expression>& expr : args) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400980 fExtraFunctions.printf("%s%s x%zu", argSeparator,
John Stiles36129132020-12-29 12:28:04 -0500981 this->typeName(expr->type()).c_str(), argIndex++);
John Stiles1bdafbf2020-05-28 12:17:20 -0400982 argSeparator = ", ";
983 }
984
985 fExtraFunctions.printf(") {\n return float%dx%d(", columns, rows);
986
John Stiles9aeed132020-11-24 17:36:06 -0500987 if (args.size() == 1 && args.front()->type().isMatrix()) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400988 this->assembleMatrixFromMatrix(args.front()->type(), rows, columns);
John Stilesfcf8cb22020-08-06 14:29:22 -0400989 } else {
990 this->assembleMatrixFromExpressions(args, rows, columns);
John Stiles1bdafbf2020-05-28 12:17:20 -0400991 }
992
John Stilesfcf8cb22020-08-06 14:29:22 -0400993 fExtraFunctions.writeText(");\n}\n");
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500994 return name;
995}
996
997bool MetalCodeGenerator::canCoerce(const Type& t1, const Type& t2) {
998 if (t1.columns() != t2.columns() || t1.rows() != t2.rows()) {
999 return false;
1000 }
1001 if (t1.columns() > 1) {
1002 return this->canCoerce(t1.componentType(), t2.componentType());
1003 }
Ethan Nicholase1f55022019-02-05 17:17:40 -05001004 return t1.isFloat() && t2.isFloat();
Ethan Nicholas842d31b2019-01-22 10:59:11 -05001005}
1006
John Stiles1bdafbf2020-05-28 12:17:20 -04001007bool MetalCodeGenerator::matrixConstructHelperIsNeeded(const Constructor& c) {
1008 // A matrix construct helper is only necessary if we are, in fact, constructing a matrix.
John Stiles9aeed132020-11-24 17:36:06 -05001009 if (!c.type().isMatrix()) {
John Stiles1bdafbf2020-05-28 12:17:20 -04001010 return false;
Ethan Nicholas842d31b2019-01-22 10:59:11 -05001011 }
John Stiles1bdafbf2020-05-28 12:17:20 -04001012
1013 // GLSL is fairly free-form about inputs to its matrix constructors, but Metal is not; it
1014 // expects exactly R vectors of C components apiece. (Metal 2.0 also allows a list of R*C
1015 // scalars.) Some cases are simple to translate and so we handle those inline--e.g. a list of
1016 // scalars can be constructed trivially. In more complex cases, we generate a helper function
1017 // that converts our inputs into a properly-shaped matrix.
1018 // A matrix construct helper method is always used if any input argument is a matrix.
1019 // Helper methods are also necessary when any argument would span multiple rows. For instance:
1020 //
1021 // float2 x = (1, 2);
1022 // float3x2(x, 3, 4, 5, 6) = | 1 3 5 | = no helper needed; conversion can be done inline
1023 // | 2 4 6 |
1024 //
1025 // float2 x = (2, 3);
1026 // float3x2(1, x, 4, 5, 6) = | 1 3 5 | = x spans multiple rows; a helper method will be used
1027 // | 2 4 6 |
1028 //
1029 // float4 x = (1, 2, 3, 4);
1030 // float2x2(x) = | 1 3 | = x spans multiple rows; a helper method will be used
1031 // | 2 4 |
1032 //
1033
1034 int position = 0;
Ethan Nicholasf70f0442020-09-29 12:41:35 -04001035 for (const std::unique_ptr<Expression>& expr : c.arguments()) {
John Stiles1bdafbf2020-05-28 12:17:20 -04001036 // If an input argument is a matrix, we need a helper function.
John Stiles9aeed132020-11-24 17:36:06 -05001037 if (expr->type().isMatrix()) {
John Stiles1bdafbf2020-05-28 12:17:20 -04001038 return true;
1039 }
Ethan Nicholas30d30222020-09-11 12:27:26 -04001040 position += expr->type().columns();
1041 if (position > c.type().rows()) {
John Stiles1bdafbf2020-05-28 12:17:20 -04001042 // An input argument would span multiple rows; a helper function is required.
1043 return true;
1044 }
Ethan Nicholas30d30222020-09-11 12:27:26 -04001045 if (position == c.type().rows()) {
John Stiles1bdafbf2020-05-28 12:17:20 -04001046 // We've advanced to the end of a row. Wrap to the start of the next row.
1047 position = 0;
1048 }
1049 }
1050
1051 return false;
1052}
1053
1054void MetalCodeGenerator::writeConstructor(const Constructor& c, Precedence parentPrecedence) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001055 const Type& constructorType = c.type();
John Stiles7384b372021-04-01 13:48:15 -04001056 SkASSERT(!constructorType.isArray());
1057
John Stiles1bdafbf2020-05-28 12:17:20 -04001058 // Handle special cases for single-argument constructors.
Ethan Nicholasf70f0442020-09-29 12:41:35 -04001059 if (c.arguments().size() == 1) {
John Stiles1bdafbf2020-05-28 12:17:20 -04001060 // If the type is coercible, emit it directly.
John Stilesfd7252f2021-04-04 22:24:40 -04001061 // (This will no longer be needed when VectorCast is added.)
Ethan Nicholasf70f0442020-09-29 12:41:35 -04001062 const Expression& arg = *c.arguments().front();
Ethan Nicholas30d30222020-09-11 12:27:26 -04001063 const Type& argType = arg.type();
1064 if (this->canCoerce(constructorType, argType)) {
John Stiles1bdafbf2020-05-28 12:17:20 -04001065 this->writeExpression(arg, parentPrecedence);
1066 return;
1067 }
John Stiles1bdafbf2020-05-28 12:17:20 -04001068 }
1069
1070 // Emit and invoke a matrix-constructor helper method if one is necessary.
1071 if (this->matrixConstructHelperIsNeeded(c)) {
1072 this->write(this->getMatrixConstructHelper(c));
John Stiles1fa15b12020-05-28 17:36:54 +00001073 this->write("(");
1074 const char* separator = "";
Ethan Nicholasf70f0442020-09-29 12:41:35 -04001075 for (const std::unique_ptr<Expression>& expr : c.arguments()) {
John Stiles1fa15b12020-05-28 17:36:54 +00001076 this->write(separator);
1077 separator = ", ";
Brian Osman00185012021-02-04 16:07:11 -05001078 this->writeExpression(*expr, Precedence::kSequence);
John Stilesdaa573e2020-05-28 12:17:20 -04001079 }
John Stiles1fa15b12020-05-28 17:36:54 +00001080 this->write(")");
John Stiles1bdafbf2020-05-28 12:17:20 -04001081 return;
John Stilesdaa573e2020-05-28 12:17:20 -04001082 }
John Stiles1bdafbf2020-05-28 12:17:20 -04001083
1084 // Explicitly invoke the constructor, passing in the necessary arguments.
John Stilesb4418502021-02-04 10:57:08 -05001085 this->writeType(constructorType);
John Stiles7384b372021-04-01 13:48:15 -04001086 this->write("(");
John Stiles1bdafbf2020-05-28 12:17:20 -04001087 const char* separator = "";
1088 int scalarCount = 0;
Ethan Nicholasf70f0442020-09-29 12:41:35 -04001089 for (const std::unique_ptr<Expression>& arg : c.arguments()) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001090 const Type& argType = arg->type();
John Stiles1bdafbf2020-05-28 12:17:20 -04001091 this->write(separator);
1092 separator = ", ";
John Stiles9aeed132020-11-24 17:36:06 -05001093 if (constructorType.isMatrix() &&
Ethan Nicholas30d30222020-09-11 12:27:26 -04001094 argType.columns() < constructorType.rows()) {
John Stiles1bdafbf2020-05-28 12:17:20 -04001095 // Merge scalars and smaller vectors together.
1096 if (!scalarCount) {
John Stilesb4418502021-02-04 10:57:08 -05001097 this->writeType(constructorType.componentType());
Ethan Nicholas30d30222020-09-11 12:27:26 -04001098 this->write(to_string(constructorType.rows()));
John Stiles1bdafbf2020-05-28 12:17:20 -04001099 this->write("(");
1100 }
Ethan Nicholas30d30222020-09-11 12:27:26 -04001101 scalarCount += argType.columns();
John Stiles1bdafbf2020-05-28 12:17:20 -04001102 }
Brian Osman00185012021-02-04 16:07:11 -05001103 this->writeExpression(*arg, Precedence::kSequence);
Ethan Nicholas30d30222020-09-11 12:27:26 -04001104 if (scalarCount && scalarCount == constructorType.rows()) {
John Stiles1bdafbf2020-05-28 12:17:20 -04001105 this->write(")");
1106 scalarCount = 0;
1107 }
1108 }
John Stiles7384b372021-04-01 13:48:15 -04001109 this->write(")");
Ethan Nicholascc305772017-10-13 16:17:45 -04001110}
1111
John Stiles933043b2021-03-31 15:23:16 -04001112void MetalCodeGenerator::writeSingleArgumentConstructor(const SingleArgumentConstructor& c,
John Stilese1182782021-03-30 22:09:37 -04001113 Precedence parentPrecedence) {
1114 this->writeType(c.type());
1115 this->write("(");
1116 this->writeExpression(*c.argument(), Precedence::kSequence);
1117 this->write(")");
1118}
1119
John Stiles7384b372021-04-01 13:48:15 -04001120void MetalCodeGenerator::writeConstructorArray(const ConstructorArray& c,
1121 Precedence parentPrecedence) {
1122 this->writeType(c.type());
1123 this->write("{");
1124 const char* separator = "";
1125 for (const std::unique_ptr<Expression>& arg : c.arguments()) {
1126 this->write(separator);
1127 separator = ", ";
1128 this->writeExpression(*arg, Precedence::kSequence);
1129 }
1130 this->write("}");
1131}
1132
John Stilesfd7252f2021-04-04 22:24:40 -04001133void MetalCodeGenerator::writeConstructorScalarCast(const ConstructorScalarCast& c,
1134 Precedence parentPrecedence) {
1135 // If the type is coercible, emit it directly.
1136 const Expression& arg = *c.argument();
1137 const Type& argType = arg.type();
1138 if (this->canCoerce(c.type(), argType)) {
1139 this->writeExpression(arg, parentPrecedence);
1140 return;
1141 }
1142
1143 return this->writeSingleArgumentConstructor(c, parentPrecedence);
1144}
1145
Ethan Nicholascc305772017-10-13 16:17:45 -04001146void MetalCodeGenerator::writeFragCoord() {
Ethan Nicholasf931e402019-07-26 15:40:33 -04001147 if (fRTHeightName.length()) {
1148 this->write("float4(_fragCoord.x, ");
1149 this->write(fRTHeightName.c_str());
1150 this->write(" - _fragCoord.y, 0.0, _fragCoord.w)");
Jim Van Verth6bc650e2019-02-07 14:53:23 -05001151 } else {
1152 this->write("float4(_fragCoord.x, _fragCoord.y, 0.0, _fragCoord.w)");
1153 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001154}
1155
1156void MetalCodeGenerator::writeVariableReference(const VariableReference& ref) {
John Stiles06b84ef2020-12-09 12:35:48 -05001157 // When assembling out-param helper functions, we copy variables into local clones with matching
John Stilesf7410bd2021-01-19 13:07:55 -05001158 // names. We never want to prepend "_in." or "_globals." when writing these variables since
John Stiles06b84ef2020-12-09 12:35:48 -05001159 // we're actually targeting the clones.
1160 if (fIgnoreVariableReferenceModifiers) {
1161 this->writeName(ref.variable()->name());
1162 return;
1163 }
1164
Ethan Nicholas78686922020-10-08 06:46:27 -04001165 switch (ref.variable()->modifiers().fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001166 case SK_FRAGCOLOR_BUILTIN:
John Stilesf7410bd2021-01-19 13:07:55 -05001167 this->write("_out.sk_FragColor");
Ethan Nicholascc305772017-10-13 16:17:45 -04001168 break;
Timothy Liang6403b0e2018-05-17 10:40:04 -04001169 case SK_FRAGCOORD_BUILTIN:
1170 this->writeFragCoord();
1171 break;
Timothy Liangdc89f192018-06-13 09:20:31 -04001172 case SK_VERTEXID_BUILTIN:
1173 this->write("sk_VertexID");
1174 break;
1175 case SK_INSTANCEID_BUILTIN:
1176 this->write("sk_InstanceID");
1177 break;
Timothy Liang7b8875d2018-08-10 09:42:31 -04001178 case SK_CLOCKWISE_BUILTIN:
1179 // We'd set the front facing winding in the MTLRenderCommandEncoder to be counter
Brian Salomonf4ba4ec2020-03-19 15:54:28 -04001180 // clockwise to match Skia convention.
John Stiles270cec22021-02-17 12:59:36 -05001181 this->write(fProgram.fConfig->fSettings.fFlipY ? "_frontFacing" : "(!_frontFacing)");
Timothy Liang7b8875d2018-08-10 09:42:31 -04001182 break;
Ethan Nicholascc305772017-10-13 16:17:45 -04001183 default:
Ethan Nicholas78686922020-10-08 06:46:27 -04001184 const Variable& var = *ref.variable();
Ethan Nicholas453f67f2020-10-09 10:43:45 -04001185 if (var.storage() == Variable::Storage::kGlobal) {
Ethan Nicholas78686922020-10-08 06:46:27 -04001186 if (var.modifiers().fFlags & Modifiers::kIn_Flag) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001187 this->write("_in.");
Ethan Nicholas78686922020-10-08 06:46:27 -04001188 } else if (var.modifiers().fFlags & Modifiers::kOut_Flag) {
John Stilesf7410bd2021-01-19 13:07:55 -05001189 this->write("_out.");
Ethan Nicholas78686922020-10-08 06:46:27 -04001190 } else if (var.modifiers().fFlags & Modifiers::kUniform_Flag &&
1191 var.type().typeKind() != Type::TypeKind::kSampler) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001192 this->write("_uniforms.");
1193 } else {
John Stilesf7410bd2021-01-19 13:07:55 -05001194 this->write("_globals.");
Ethan Nicholascc305772017-10-13 16:17:45 -04001195 }
1196 }
Ethan Nicholas78686922020-10-08 06:46:27 -04001197 this->writeName(var.name());
Ethan Nicholascc305772017-10-13 16:17:45 -04001198 }
1199}
1200
1201void MetalCodeGenerator::writeIndexExpression(const IndexExpression& expr) {
Brian Osman00185012021-02-04 16:07:11 -05001202 this->writeExpression(*expr.base(), Precedence::kPostfix);
Ethan Nicholascc305772017-10-13 16:17:45 -04001203 this->write("[");
Brian Osman00185012021-02-04 16:07:11 -05001204 this->writeExpression(*expr.index(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001205 this->write("]");
1206}
1207
1208void MetalCodeGenerator::writeFieldAccess(const FieldAccess& f) {
Ethan Nicholas7a95b202020-10-09 11:55:40 -04001209 const Type::Field* field = &f.base()->type().fields()[f.fieldIndex()];
1210 if (FieldAccess::OwnerKind::kDefault == f.ownerKind()) {
Brian Osman00185012021-02-04 16:07:11 -05001211 this->writeExpression(*f.base(), Precedence::kPostfix);
Ethan Nicholascc305772017-10-13 16:17:45 -04001212 this->write(".");
1213 }
Timothy Liang7d637782018-06-05 09:58:07 -04001214 switch (field->fModifiers.fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001215 case SK_POSITION_BUILTIN:
John Stilesf7410bd2021-01-19 13:07:55 -05001216 this->write("_out.sk_Position");
Ethan Nicholascc305772017-10-13 16:17:45 -04001217 break;
1218 default:
Timothy Liang7d637782018-06-05 09:58:07 -04001219 if (field->fName == "sk_PointSize") {
John Stilesf7410bd2021-01-19 13:07:55 -05001220 this->write("_out.sk_PointSize");
Timothy Liang7d637782018-06-05 09:58:07 -04001221 } else {
Ethan Nicholas7a95b202020-10-09 11:55:40 -04001222 if (FieldAccess::OwnerKind::kAnonymousInterfaceBlock == f.ownerKind()) {
John Stilesf7410bd2021-01-19 13:07:55 -05001223 this->write("_globals.");
Timothy Liang7d637782018-06-05 09:58:07 -04001224 this->write(fInterfaceBlockNameMap[fInterfaceBlockMap[field]]);
1225 this->write("->");
1226 }
Timothy Liang651286f2018-06-07 09:55:33 -04001227 this->writeName(field->fName);
Timothy Lianga06f2152018-05-24 15:33:31 -04001228 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001229 }
1230}
1231
1232void MetalCodeGenerator::writeSwizzle(const Swizzle& swizzle) {
Brian Osman00185012021-02-04 16:07:11 -05001233 this->writeExpression(*swizzle.base(), Precedence::kPostfix);
Ethan Nicholascc305772017-10-13 16:17:45 -04001234 this->write(".");
Ethan Nicholas6b4d5812020-10-12 16:11:51 -04001235 for (int c : swizzle.components()) {
Brian Osman25647672020-09-15 15:16:56 -04001236 SkASSERT(c >= 0 && c <= 3);
1237 this->write(&("x\0y\0z\0w\0"[c * 2]));
Ethan Nicholascc305772017-10-13 16:17:45 -04001238 }
1239}
1240
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001241void MetalCodeGenerator::writeMatrixTimesEqualHelper(const Type& left, const Type& right,
1242 const Type& result) {
John Stiles01cdf012021-02-10 09:53:41 -05001243 String key = "TimesEqual" + this->typeName(left) + ":" + this->typeName(right);
John Stiles56233d12021-02-03 13:03:29 -05001244
1245 auto [iter, wasInserted] = fHelpers.insert(key);
1246 if (wasInserted) {
John Stiles368db7c2020-12-29 11:20:08 -05001247 fExtraFunctions.printf("thread %s& operator*=(thread %s& left, thread const %s& right) {\n"
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001248 " left = left * right;\n"
1249 " return left;\n"
John Stiles368db7c2020-12-29 11:20:08 -05001250 "}\n",
1251 this->typeName(result).c_str(), this->typeName(left).c_str(),
1252 this->typeName(right).c_str());
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001253 }
1254}
1255
John Stiles01cdf012021-02-10 09:53:41 -05001256void MetalCodeGenerator::writeMatrixEqualityHelper(const Type& left, const Type& right) {
1257 SkASSERTF(left.rows() == right.rows() && left.columns() == right.columns(), "left=%s, right=%s",
1258 left.description().c_str(), right.description().c_str());
1259
1260 String key = "Equality" + this->typeName(left) + ":" + this->typeName(right);
1261
1262 auto [iter, wasInserted] = fHelpers.insert(key);
1263 if (wasInserted) {
1264 fExtraFunctions.printf(
1265 "thread bool operator==(const %s left, const %s right) {\n"
1266 " return",
1267 this->typeName(left).c_str(), this->typeName(right).c_str());
1268
1269 for (int index=0; index<left.columns(); ++index) {
1270 fExtraFunctions.printf("%s all(left[%d] == right[%d])",
1271 index == 0 ? "" : " &&", index, index);
1272 }
1273 fExtraFunctions.printf(";\n"
1274 "}\n");
1275 }
1276}
1277
1278void MetalCodeGenerator::writeMatrixInequalityHelper(const Type& left, const Type& right) {
1279 SkASSERTF(left.rows() == right.rows() && left.columns() == right.columns(), "left=%s, right=%s",
1280 left.description().c_str(), right.description().c_str());
1281
1282 String key = "Inequality" + this->typeName(left) + ":" + this->typeName(right);
1283
1284 auto [iter, wasInserted] = fHelpers.insert(key);
1285 if (wasInserted) {
1286 fExtraFunctions.printf(
1287 "thread bool operator!=(const %s left, const %s right) {\n"
1288 " return",
1289 this->typeName(left).c_str(), this->typeName(right).c_str());
1290
1291 for (int index=0; index<left.columns(); ++index) {
1292 fExtraFunctions.printf("%s any(left[%d] != right[%d])",
1293 index == 0 ? "" : " ||", index, index);
1294 }
1295 fExtraFunctions.printf(";\n"
1296 "}\n");
1297 }
1298}
1299
Ethan Nicholascc305772017-10-13 16:17:45 -04001300void MetalCodeGenerator::writeBinaryExpression(const BinaryExpression& b,
1301 Precedence parentPrecedence) {
John Stiles2d4f9592020-10-30 10:29:12 -04001302 const Expression& left = *b.left();
1303 const Expression& right = *b.right();
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001304 const Type& leftType = left.type();
1305 const Type& rightType = right.type();
John Stiles45990502021-02-16 10:55:27 -05001306 Operator op = b.getOperator();
1307 Precedence precedence = op.getBinaryPrecedence();
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001308 bool needParens = precedence >= parentPrecedence;
John Stiles45990502021-02-16 10:55:27 -05001309 switch (op.kind()) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001310 case Token::Kind::TK_EQEQ:
John Stiles9aeed132020-11-24 17:36:06 -05001311 if (leftType.isVector()) {
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001312 this->write("all");
1313 needParens = true;
1314 }
1315 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001316 case Token::Kind::TK_NEQ:
John Stiles9aeed132020-11-24 17:36:06 -05001317 if (leftType.isVector()) {
Jim Van Verth36477b42019-04-11 14:57:30 -04001318 this->write("any");
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001319 needParens = true;
1320 }
1321 break;
1322 default:
1323 break;
1324 }
1325 if (needParens) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001326 this->write("(");
1327 }
John Stiles01cdf012021-02-10 09:53:41 -05001328 if (leftType.isMatrix() && rightType.isMatrix()) {
John Stiles45990502021-02-16 10:55:27 -05001329 if (op.kind() == Token::Kind::TK_STAREQ) {
John Stiles01cdf012021-02-10 09:53:41 -05001330 this->writeMatrixTimesEqualHelper(leftType, rightType, b.type());
John Stiles45990502021-02-16 10:55:27 -05001331 } else if (op.kind() == Token::Kind::TK_EQEQ) {
John Stiles01cdf012021-02-10 09:53:41 -05001332 this->writeMatrixEqualityHelper(leftType, rightType);
John Stiles45990502021-02-16 10:55:27 -05001333 } else if (op.kind() == Token::Kind::TK_NEQ) {
John Stiles01cdf012021-02-10 09:53:41 -05001334 this->writeMatrixInequalityHelper(leftType, rightType);
1335 }
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001336 }
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001337 this->writeExpression(left, precedence);
John Stiles45990502021-02-16 10:55:27 -05001338 if (op.kind() != Token::Kind::TK_EQ && op.isAssignment() &&
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001339 left.kind() == Expression::Kind::kSwizzle && !left.hasSideEffects()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001340 // This doesn't compile in Metal:
1341 // float4 x = float4(1);
1342 // x.xy *= float2x2(...);
1343 // with the error message "non-const reference cannot bind to vector element",
1344 // but switching it to x.xy = x.xy * float2x2(...) fixes it. We perform this tranformation
1345 // as long as the LHS has no side effects, and hope for the best otherwise.
1346 this->write(" = ");
Brian Osman00185012021-02-04 16:07:11 -05001347 this->writeExpression(left, Precedence::kAssignment);
Ethan Nicholascc305772017-10-13 16:17:45 -04001348 this->write(" ");
John Stilesd6449e92020-11-30 09:13:23 -05001349 String opName = OperatorName(op);
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001350 SkASSERT(opName.endsWith("="));
1351 this->write(opName.substr(0, opName.size() - 1).c_str());
Ethan Nicholascc305772017-10-13 16:17:45 -04001352 this->write(" ");
1353 } else {
John Stilesd6449e92020-11-30 09:13:23 -05001354 this->write(String(" ") + OperatorName(op) + " ");
Ethan Nicholascc305772017-10-13 16:17:45 -04001355 }
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001356 this->writeExpression(right, precedence);
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001357 if (needParens) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001358 this->write(")");
1359 }
1360}
1361
1362void MetalCodeGenerator::writeTernaryExpression(const TernaryExpression& t,
1363 Precedence parentPrecedence) {
Brian Osman00185012021-02-04 16:07:11 -05001364 if (Precedence::kTernary >= parentPrecedence) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001365 this->write("(");
1366 }
Brian Osman00185012021-02-04 16:07:11 -05001367 this->writeExpression(*t.test(), Precedence::kTernary);
Ethan Nicholascc305772017-10-13 16:17:45 -04001368 this->write(" ? ");
Brian Osman00185012021-02-04 16:07:11 -05001369 this->writeExpression(*t.ifTrue(), Precedence::kTernary);
Ethan Nicholascc305772017-10-13 16:17:45 -04001370 this->write(" : ");
Brian Osman00185012021-02-04 16:07:11 -05001371 this->writeExpression(*t.ifFalse(), Precedence::kTernary);
1372 if (Precedence::kTernary >= parentPrecedence) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001373 this->write(")");
1374 }
1375}
1376
1377void MetalCodeGenerator::writePrefixExpression(const PrefixExpression& p,
1378 Precedence parentPrecedence) {
Brian Osman00185012021-02-04 16:07:11 -05001379 if (Precedence::kPrefix >= parentPrecedence) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001380 this->write("(");
1381 }
John Stilesd6449e92020-11-30 09:13:23 -05001382 this->write(OperatorName(p.getOperator()));
Brian Osman00185012021-02-04 16:07:11 -05001383 this->writeExpression(*p.operand(), Precedence::kPrefix);
1384 if (Precedence::kPrefix >= parentPrecedence) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001385 this->write(")");
1386 }
1387}
1388
1389void MetalCodeGenerator::writePostfixExpression(const PostfixExpression& p,
1390 Precedence parentPrecedence) {
Brian Osman00185012021-02-04 16:07:11 -05001391 if (Precedence::kPostfix >= parentPrecedence) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001392 this->write("(");
1393 }
Brian Osman00185012021-02-04 16:07:11 -05001394 this->writeExpression(*p.operand(), Precedence::kPostfix);
John Stilesd6449e92020-11-30 09:13:23 -05001395 this->write(OperatorName(p.getOperator()));
Brian Osman00185012021-02-04 16:07:11 -05001396 if (Precedence::kPostfix >= parentPrecedence) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001397 this->write(")");
1398 }
1399}
1400
1401void MetalCodeGenerator::writeBoolLiteral(const BoolLiteral& b) {
Ethan Nicholas59d660c2020-09-28 09:18:15 -04001402 this->write(b.value() ? "true" : "false");
Ethan Nicholascc305772017-10-13 16:17:45 -04001403}
1404
1405void MetalCodeGenerator::writeIntLiteral(const IntLiteral& i) {
John Stiles12739df2020-12-29 09:47:20 -05001406 const Type& type = i.type();
John Stiles54e7c052021-01-11 14:22:36 -05001407 if (type == *fContext.fTypes.fUInt) {
Ethan Nicholase96cdd12020-09-28 16:27:18 -04001408 this->write(to_string(i.value() & 0xffffffff) + "u");
John Stiles54e7c052021-01-11 14:22:36 -05001409 } else if (type == *fContext.fTypes.fUShort) {
John Stiles12739df2020-12-29 09:47:20 -05001410 this->write(to_string(i.value() & 0xffff) + "u");
John Stiles54e7c052021-01-11 14:22:36 -05001411 } else if (type == *fContext.fTypes.fUByte) {
John Stiles12739df2020-12-29 09:47:20 -05001412 this->write(to_string(i.value() & 0xff) + "u");
Ethan Nicholascc305772017-10-13 16:17:45 -04001413 } else {
John Stiles12739df2020-12-29 09:47:20 -05001414 this->write(to_string(i.value()));
Ethan Nicholascc305772017-10-13 16:17:45 -04001415 }
1416}
1417
1418void MetalCodeGenerator::writeFloatLiteral(const FloatLiteral& f) {
Ethan Nicholasa3f22f12020-10-01 12:13:17 -04001419 this->write(to_string(f.value()));
Ethan Nicholascc305772017-10-13 16:17:45 -04001420}
1421
1422void MetalCodeGenerator::writeSetting(const Setting& s) {
John Stilesf57207b2021-02-02 17:50:34 -05001423 SK_ABORT("internal error; setting was not folded to a constant during compilation\n");
Ethan Nicholascc305772017-10-13 16:17:45 -04001424}
1425
John Stiles06b84ef2020-12-09 12:35:48 -05001426void MetalCodeGenerator::writeFunctionRequirementArgs(const FunctionDeclaration& f,
1427 const char*& separator) {
1428 Requirements requirements = this->requirements(f);
1429 if (requirements & kInputs_Requirement) {
1430 this->write(separator);
1431 this->write("_in");
1432 separator = ", ";
1433 }
1434 if (requirements & kOutputs_Requirement) {
1435 this->write(separator);
1436 this->write("_out");
1437 separator = ", ";
1438 }
1439 if (requirements & kUniforms_Requirement) {
1440 this->write(separator);
1441 this->write("_uniforms");
1442 separator = ", ";
1443 }
1444 if (requirements & kGlobals_Requirement) {
1445 this->write(separator);
John Stilesf7410bd2021-01-19 13:07:55 -05001446 this->write("_globals");
John Stiles06b84ef2020-12-09 12:35:48 -05001447 separator = ", ";
1448 }
1449 if (requirements & kFragCoord_Requirement) {
1450 this->write(separator);
1451 this->write("_fragCoord");
1452 separator = ", ";
1453 }
1454}
1455
1456void MetalCodeGenerator::writeFunctionRequirementParams(const FunctionDeclaration& f,
1457 const char*& separator) {
1458 Requirements requirements = this->requirements(f);
1459 if (requirements & kInputs_Requirement) {
1460 this->write(separator);
1461 this->write("Inputs _in");
1462 separator = ", ";
1463 }
1464 if (requirements & kOutputs_Requirement) {
1465 this->write(separator);
John Stilesf7410bd2021-01-19 13:07:55 -05001466 this->write("thread Outputs& _out");
John Stiles06b84ef2020-12-09 12:35:48 -05001467 separator = ", ";
1468 }
1469 if (requirements & kUniforms_Requirement) {
1470 this->write(separator);
1471 this->write("Uniforms _uniforms");
1472 separator = ", ";
1473 }
1474 if (requirements & kGlobals_Requirement) {
1475 this->write(separator);
John Stilesf7410bd2021-01-19 13:07:55 -05001476 this->write("thread Globals& _globals");
John Stiles06b84ef2020-12-09 12:35:48 -05001477 separator = ", ";
1478 }
1479 if (requirements & kFragCoord_Requirement) {
1480 this->write(separator);
1481 this->write("float4 _fragCoord");
1482 separator = ", ";
1483 }
1484}
1485
John Stilesda5cdf62021-01-28 11:47:29 -05001486int MetalCodeGenerator::getUniformBinding(const Modifiers& m) {
1487 return (m.fLayout.fBinding >= 0) ? m.fLayout.fBinding
John Stiles270cec22021-02-17 12:59:36 -05001488 : fProgram.fConfig->fSettings.fDefaultUniformBinding;
John Stilesda5cdf62021-01-28 11:47:29 -05001489}
1490
1491int MetalCodeGenerator::getUniformSet(const Modifiers& m) {
1492 return (m.fLayout.fSet >= 0) ? m.fLayout.fSet
John Stiles270cec22021-02-17 12:59:36 -05001493 : fProgram.fConfig->fSettings.fDefaultUniformSet;
John Stilesda5cdf62021-01-28 11:47:29 -05001494}
1495
John Stiles569249b2020-11-03 12:18:22 -05001496bool MetalCodeGenerator::writeFunctionDeclaration(const FunctionDeclaration& f) {
John Stilesf7410bd2021-01-19 13:07:55 -05001497 fRTHeightName = fProgram.fInputs.fRTHeight ? "_globals._anonInterface0->u_skRTHeight" : "";
Ethan Nicholascc305772017-10-13 16:17:45 -04001498 const char* separator = "";
John Stilese8da4d22021-03-24 09:19:45 -04001499 if (f.isMain()) {
John Stiles270cec22021-02-17 12:59:36 -05001500 switch (fProgram.fConfig->fKind) {
John Stilesdbd4e6f2021-02-16 13:29:15 -05001501 case ProgramKind::kFragment:
Timothy Liangb8eeb802018-07-23 16:46:16 -04001502 this->write("fragment Outputs fragmentMain");
Ethan Nicholascc305772017-10-13 16:17:45 -04001503 break;
John Stilesdbd4e6f2021-02-16 13:29:15 -05001504 case ProgramKind::kVertex:
Timothy Liangb8eeb802018-07-23 16:46:16 -04001505 this->write("vertex Outputs vertexMain");
Ethan Nicholascc305772017-10-13 16:17:45 -04001506 break;
1507 default:
John Stiles3fabfc02020-09-25 15:51:28 -04001508 fErrors.error(-1, "unsupported kind of program");
John Stiles569249b2020-11-03 12:18:22 -05001509 return false;
Ethan Nicholascc305772017-10-13 16:17:45 -04001510 }
1511 this->write("(Inputs _in [[stage_in]]");
1512 if (-1 != fUniformBuffer) {
1513 this->write(", constant Uniforms& _uniforms [[buffer(" +
1514 to_string(fUniformBuffer) + ")]]");
1515 }
Brian Osman133724c2020-10-28 14:14:39 -04001516 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04001517 if (e->is<GlobalVarDeclaration>()) {
1518 const GlobalVarDeclaration& decls = e->as<GlobalVarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001519 const VarDeclaration& var = decls.declaration()->as<VarDeclaration>();
1520 if (var.var().type().typeKind() == Type::TypeKind::kSampler) {
1521 if (var.var().modifiers().fLayout.fBinding < 0) {
Brian Osmanc0213602020-10-06 14:43:32 -04001522 fErrors.error(decls.fOffset,
John Stilesb41d5bb2021-01-26 16:28:12 -05001523 "Metal samplers must have 'layout(binding=...)'");
John Stiles569249b2020-11-03 12:18:22 -05001524 return false;
Timothy Liangee84fe12018-05-18 14:38:19 -04001525 }
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001526 if (var.var().type().dimensions() != SpvDim2D) {
John Stiles569249b2020-11-03 12:18:22 -05001527 // Not yet implemented--Skia currently only uses 2D textures.
Brian Osmanc0213602020-10-06 14:43:32 -04001528 fErrors.error(decls.fOffset, "Unsupported texture dimensions");
John Stiles569249b2020-11-03 12:18:22 -05001529 return false;
Brian Osmanc0213602020-10-06 14:43:32 -04001530 }
1531 this->write(", texture2d<float> ");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001532 this->writeName(var.var().name());
Brian Osmanc0213602020-10-06 14:43:32 -04001533 this->write("[[texture(");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001534 this->write(to_string(var.var().modifiers().fLayout.fBinding));
Brian Osmanc0213602020-10-06 14:43:32 -04001535 this->write(")]]");
1536 this->write(", sampler ");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001537 this->writeName(var.var().name());
Brian Osmanc0213602020-10-06 14:43:32 -04001538 this->write(SAMPLER_SUFFIX);
1539 this->write("[[sampler(");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001540 this->write(to_string(var.var().modifiers().fLayout.fBinding));
Brian Osmanc0213602020-10-06 14:43:32 -04001541 this->write(")]]");
Timothy Liang6403b0e2018-05-17 10:40:04 -04001542 }
Brian Osman1179fcf2020-10-08 16:04:40 -04001543 } else if (e->is<InterfaceBlock>()) {
1544 const InterfaceBlock& intf = e->as<InterfaceBlock>();
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001545 if (intf.typeName() == "sk_PerVertex") {
Timothy Lianga06f2152018-05-24 15:33:31 -04001546 continue;
1547 }
1548 this->write(", constant ");
John Stilesb4418502021-02-04 10:57:08 -05001549 this->writeType(intf.variable().type());
Timothy Lianga06f2152018-05-24 15:33:31 -04001550 this->write("& " );
1551 this->write(fInterfaceBlockNameMap[&intf]);
1552 this->write(" [[buffer(");
John Stilesda5cdf62021-01-28 11:47:29 -05001553 this->write(to_string(this->getUniformBinding(intf.variable().modifiers())));
Timothy Lianga06f2152018-05-24 15:33:31 -04001554 this->write(")]]");
Timothy Liang6403b0e2018-05-17 10:40:04 -04001555 }
1556 }
John Stiles270cec22021-02-17 12:59:36 -05001557 if (fProgram.fConfig->fKind == ProgramKind::kFragment) {
Jim Van Verth6bc650e2019-02-07 14:53:23 -05001558 if (fProgram.fInputs.fRTHeight && fInterfaceBlockNameMap.empty()) {
Timothy Liang5422f9a2018-08-10 10:57:55 -04001559 this->write(", constant sksl_synthetic_uniforms& _anonInterface0 [[buffer(1)]]");
Ethan Nicholasf931e402019-07-26 15:40:33 -04001560 fRTHeightName = "_anonInterface0.u_skRTHeight";
Timothy Liang5422f9a2018-08-10 10:57:55 -04001561 }
Timothy Liang7b8875d2018-08-10 09:42:31 -04001562 this->write(", bool _frontFacing [[front_facing]]");
Timothy Liang7d637782018-06-05 09:58:07 -04001563 this->write(", float4 _fragCoord [[position]]");
John Stiles270cec22021-02-17 12:59:36 -05001564 } else if (fProgram.fConfig->fKind == ProgramKind::kVertex) {
Timothy Liangdc89f192018-06-13 09:20:31 -04001565 this->write(", uint sk_VertexID [[vertex_id]], uint sk_InstanceID [[instance_id]]");
Timothy Liang7d637782018-06-05 09:58:07 -04001566 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001567 separator = ", ";
1568 } else {
John Stilesb4418502021-02-04 10:57:08 -05001569 this->writeType(f.returnType());
Timothy Liang651286f2018-06-07 09:55:33 -04001570 this->write(" ");
John Stilese1068342021-03-22 11:57:41 -04001571 this->writeName(f.mangledName());
Timothy Liang651286f2018-06-07 09:55:33 -04001572 this->write("(");
John Stiles06b84ef2020-12-09 12:35:48 -05001573 this->writeFunctionRequirementParams(f, separator);
Ethan Nicholascc305772017-10-13 16:17:45 -04001574 }
John Stiles569249b2020-11-03 12:18:22 -05001575 for (const auto& param : f.parameters()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001576 this->write(separator);
1577 separator = ", ";
John Stiles06b84ef2020-12-09 12:35:48 -05001578 this->writeModifiers(param->modifiers(), /*globalContext=*/false);
Ethan Nicholas30d30222020-09-11 12:27:26 -04001579 const Type* type = &param->type();
John Stilesb4418502021-02-04 10:57:08 -05001580 this->writeType(*type);
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001581 if (param->modifiers().fFlags & Modifiers::kOut_Flag) {
John Stilesf2bd5012020-12-04 11:58:26 -05001582 this->write("&");
Ethan Nicholascc305772017-10-13 16:17:45 -04001583 }
Timothy Liang651286f2018-06-07 09:55:33 -04001584 this->write(" ");
Ethan Nicholase2c49992020-10-05 11:49:11 -04001585 this->writeName(param->name());
Ethan Nicholascc305772017-10-13 16:17:45 -04001586 }
John Stiles569249b2020-11-03 12:18:22 -05001587 this->write(")");
1588 return true;
1589}
Ethan Nicholascc305772017-10-13 16:17:45 -04001590
John Stiles569249b2020-11-03 12:18:22 -05001591void MetalCodeGenerator::writeFunctionPrototype(const FunctionPrototype& f) {
1592 this->writeFunctionDeclaration(f.declaration());
1593 this->writeLine(";");
1594}
1595
John Stiles986c7fb2020-12-01 14:44:56 -05001596static bool is_block_ending_with_return(const Statement* stmt) {
1597 // This function detects (potentially nested) blocks that end in a return statement.
1598 if (!stmt->is<Block>()) {
1599 return false;
1600 }
1601 const StatementArray& block = stmt->as<Block>().children();
1602 for (int index = block.count(); index--; ) {
1603 const Statement& stmt = *block[index];
1604 if (stmt.is<ReturnStatement>()) {
1605 return true;
1606 }
1607 if (stmt.is<Block>()) {
1608 return is_block_ending_with_return(&stmt);
1609 }
1610 if (!stmt.is<Nop>()) {
1611 break;
1612 }
1613 }
1614 return false;
1615}
1616
John Stiles569249b2020-11-03 12:18:22 -05001617void MetalCodeGenerator::writeFunction(const FunctionDefinition& f) {
John Stiles270cec22021-02-17 12:59:36 -05001618 SkASSERT(!fProgram.fConfig->fSettings.fFragColorIsInOut);
Brian Salomondc092132018-04-04 10:14:16 -04001619
John Stiles569249b2020-11-03 12:18:22 -05001620 if (!this->writeFunctionDeclaration(f.declaration())) {
1621 return;
1622 }
1623
John Stiles986c7fb2020-12-01 14:44:56 -05001624 fCurrentFunction = &f.declaration();
1625 SkScopeExit clearCurrentFunction([&] { fCurrentFunction = nullptr; });
1626
John Stiles569249b2020-11-03 12:18:22 -05001627 this->writeLine(" {");
1628
John Stilese8da4d22021-03-24 09:19:45 -04001629 if (f.declaration().isMain()) {
John Stilescdcdb042020-07-06 09:03:51 -04001630 this->writeGlobalInit();
John Stilesf7410bd2021-01-19 13:07:55 -05001631 this->writeLine(" Outputs _out;");
John Stiles37279172021-01-21 22:24:28 -05001632 this->writeLine(" (void)_out;");
Ethan Nicholascc305772017-10-13 16:17:45 -04001633 }
John Stilesc67b3622020-05-28 17:53:13 -04001634
Ethan Nicholascc305772017-10-13 16:17:45 -04001635 fFunctionHeader = "";
Ethan Nicholascc305772017-10-13 16:17:45 -04001636 StringStream buffer;
John Stiles44532372020-12-07 12:33:55 -05001637 {
1638 AutoOutputStream outputToBuffer(this, &buffer);
1639 fIndentation++;
1640 for (const std::unique_ptr<Statement>& stmt : f.body()->as<Block>().children()) {
1641 if (!stmt->isEmpty()) {
1642 this->writeStatement(*stmt);
John Stilese8b5a732021-03-12 13:25:52 -05001643 this->finishLine();
John Stiles44532372020-12-07 12:33:55 -05001644 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001645 }
John Stilese8da4d22021-03-24 09:19:45 -04001646 if (f.declaration().isMain()) {
John Stiles44532372020-12-07 12:33:55 -05001647 // If the main function doesn't end with a return, we need to synthesize one here.
1648 if (!is_block_ending_with_return(f.body().get())) {
1649 this->writeReturnStatementFromMain();
John Stilese8b5a732021-03-12 13:25:52 -05001650 this->finishLine();
John Stiles44532372020-12-07 12:33:55 -05001651 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001652 }
John Stiles44532372020-12-07 12:33:55 -05001653 fIndentation--;
1654 this->writeLine("}");
Ethan Nicholascc305772017-10-13 16:17:45 -04001655 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001656 this->write(fFunctionHeader);
1657 this->write(buffer.str());
1658}
1659
1660void MetalCodeGenerator::writeModifiers(const Modifiers& modifiers,
John Stiles06b84ef2020-12-09 12:35:48 -05001661 bool globalContext) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001662 if (modifiers.fFlags & Modifiers::kOut_Flag) {
1663 this->write("thread ");
1664 }
1665 if (modifiers.fFlags & Modifiers::kConst_Flag) {
John Stiles0bd55782021-02-09 18:29:40 -05001666 this->write("const ");
Ethan Nicholascc305772017-10-13 16:17:45 -04001667 }
1668}
1669
1670void MetalCodeGenerator::writeInterfaceBlock(const InterfaceBlock& intf) {
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001671 if ("sk_PerVertex" == intf.typeName()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001672 return;
1673 }
John Stiles06b84ef2020-12-09 12:35:48 -05001674 this->writeModifiers(intf.variable().modifiers(), /*globalContext=*/true);
Timothy Liangdc89f192018-06-13 09:20:31 -04001675 this->write("struct ");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001676 this->writeLine(intf.typeName() + " {");
1677 const Type* structType = &intf.variable().type();
John Stilesbb43b7e2020-12-03 17:36:32 -05001678 if (structType->isArray()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001679 structType = &structType->componentType();
1680 }
Timothy Liangdc89f192018-06-13 09:20:31 -04001681 fIndentation++;
John Stiles3dba3ee2020-12-02 23:35:49 -05001682 this->writeFields(structType->fields(), structType->fOffset, &intf);
Jim Van Verth3d482992019-02-07 10:48:05 -05001683 if (fProgram.fInputs.fRTHeight) {
Timothy Liang7d637782018-06-05 09:58:07 -04001684 this->writeLine("float u_skRTHeight;");
Ethan Nicholascc305772017-10-13 16:17:45 -04001685 }
1686 fIndentation--;
1687 this->write("}");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001688 if (intf.instanceName().size()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001689 this->write(" ");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001690 this->write(intf.instanceName());
John Stilesd39aec02020-12-03 10:42:26 -05001691 if (intf.arraySize() > 0) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001692 this->write("[");
John Stilesd39aec02020-12-03 10:42:26 -05001693 this->write(to_string(intf.arraySize()));
Ethan Nicholascc305772017-10-13 16:17:45 -04001694 this->write("]");
John Stilesd39aec02020-12-03 10:42:26 -05001695 } else if (intf.arraySize() == Type::kUnsizedArray){
1696 this->write("[]");
Ethan Nicholascc305772017-10-13 16:17:45 -04001697 }
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001698 fInterfaceBlockNameMap[&intf] = intf.instanceName();
Timothy Lianga06f2152018-05-24 15:33:31 -04001699 } else {
Timothy Liang7d637782018-06-05 09:58:07 -04001700 fInterfaceBlockNameMap[&intf] = "_anonInterface" + to_string(fAnonInterfaceCount++);
Ethan Nicholascc305772017-10-13 16:17:45 -04001701 }
1702 this->writeLine(";");
1703}
1704
Timothy Liangdc89f192018-06-13 09:20:31 -04001705void MetalCodeGenerator::writeFields(const std::vector<Type::Field>& fields, int parentOffset,
1706 const InterfaceBlock* parentIntf) {
Timothy Liang609fbe32018-08-10 16:40:49 -04001707 MemoryLayout memoryLayout(MemoryLayout::kMetal_Standard);
Timothy Liangdc89f192018-06-13 09:20:31 -04001708 int currentOffset = 0;
1709 for (const auto& field: fields) {
1710 int fieldOffset = field.fModifiers.fLayout.fOffset;
1711 const Type* fieldType = field.fType;
John Stiles21f5f452020-11-30 09:57:59 -05001712 if (!MemoryLayout::LayoutIsSupported(*fieldType)) {
John Stiles0023c0c2020-11-16 13:32:18 -05001713 fErrors.error(parentOffset, "type '" + fieldType->name() + "' is not permitted here");
1714 return;
1715 }
Timothy Liangdc89f192018-06-13 09:20:31 -04001716 if (fieldOffset != -1) {
1717 if (currentOffset > fieldOffset) {
1718 fErrors.error(parentOffset,
John Stilesd7199b22020-12-30 16:22:58 -05001719 "offset of field '" + field.fName + "' must be at least " +
1720 to_string((int) currentOffset));
Brian Osman8609a242020-09-08 14:01:49 -04001721 return;
Timothy Liangdc89f192018-06-13 09:20:31 -04001722 } else if (currentOffset < fieldOffset) {
1723 this->write("char pad");
1724 this->write(to_string(fPaddingCount++));
1725 this->write("[");
1726 this->write(to_string(fieldOffset - currentOffset));
1727 this->writeLine("];");
1728 currentOffset = fieldOffset;
1729 }
1730 int alignment = memoryLayout.alignment(*fieldType);
1731 if (fieldOffset % alignment) {
1732 fErrors.error(parentOffset,
1733 "offset of field '" + field.fName + "' must be a multiple of " +
1734 to_string((int) alignment));
Brian Osman8609a242020-09-08 14:01:49 -04001735 return;
Timothy Liangdc89f192018-06-13 09:20:31 -04001736 }
1737 }
Brian Osman8609a242020-09-08 14:01:49 -04001738 size_t fieldSize = memoryLayout.size(*fieldType);
1739 if (fieldSize > static_cast<size_t>(std::numeric_limits<int>::max() - currentOffset)) {
1740 fErrors.error(parentOffset, "field offset overflow");
1741 return;
1742 }
1743 currentOffset += fieldSize;
John Stiles06b84ef2020-12-09 12:35:48 -05001744 this->writeModifiers(field.fModifiers, /*globalContext=*/false);
John Stilesb4418502021-02-04 10:57:08 -05001745 this->writeType(*fieldType);
Timothy Liangdc89f192018-06-13 09:20:31 -04001746 this->write(" ");
1747 this->writeName(field.fName);
Timothy Liangdc89f192018-06-13 09:20:31 -04001748 this->writeLine(";");
1749 if (parentIntf) {
1750 fInterfaceBlockMap[&field] = parentIntf;
1751 }
1752 }
1753}
1754
Ethan Nicholascc305772017-10-13 16:17:45 -04001755void MetalCodeGenerator::writeVarInitializer(const Variable& var, const Expression& value) {
Brian Osman00185012021-02-04 16:07:11 -05001756 this->writeExpression(value, Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001757}
1758
Timothy Liang651286f2018-06-07 09:55:33 -04001759void MetalCodeGenerator::writeName(const String& name) {
1760 if (fReservedWords.find(name) != fReservedWords.end()) {
1761 this->write("_"); // adding underscore before name to avoid conflict with reserved words
1762 }
1763 this->write(name);
1764}
1765
John Stilesb4418502021-02-04 10:57:08 -05001766void MetalCodeGenerator::writeVarDeclaration(const VarDeclaration& varDecl, bool global) {
1767 if (global && !(varDecl.var().modifiers().fFlags & Modifiers::kConst_Flag)) {
Brian Osmanc0213602020-10-06 14:43:32 -04001768 return;
Ethan Nicholascc305772017-10-13 16:17:45 -04001769 }
John Stilesb4418502021-02-04 10:57:08 -05001770 this->writeModifiers(varDecl.var().modifiers(), global);
1771 this->writeType(varDecl.var().type());
Brian Osmanc0213602020-10-06 14:43:32 -04001772 this->write(" ");
John Stilesb4418502021-02-04 10:57:08 -05001773 this->writeName(varDecl.var().name());
1774 if (varDecl.value()) {
Brian Osmanc0213602020-10-06 14:43:32 -04001775 this->write(" = ");
John Stilesb4418502021-02-04 10:57:08 -05001776 this->writeVarInitializer(varDecl.var(), *varDecl.value());
Brian Osmanc0213602020-10-06 14:43:32 -04001777 }
1778 this->write(";");
Ethan Nicholascc305772017-10-13 16:17:45 -04001779}
1780
1781void MetalCodeGenerator::writeStatement(const Statement& s) {
Ethan Nicholase6592142020-09-08 10:22:09 -04001782 switch (s.kind()) {
1783 case Statement::Kind::kBlock:
John Stiles26f98502020-08-18 09:30:51 -04001784 this->writeBlock(s.as<Block>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001785 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001786 case Statement::Kind::kExpression:
Brian Osman00185012021-02-04 16:07:11 -05001787 this->writeExpression(*s.as<ExpressionStatement>().expression(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001788 this->write(";");
1789 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001790 case Statement::Kind::kReturn:
John Stiles26f98502020-08-18 09:30:51 -04001791 this->writeReturnStatement(s.as<ReturnStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001792 break;
Brian Osmanc0213602020-10-06 14:43:32 -04001793 case Statement::Kind::kVarDeclaration:
1794 this->writeVarDeclaration(s.as<VarDeclaration>(), false);
Ethan Nicholascc305772017-10-13 16:17:45 -04001795 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001796 case Statement::Kind::kIf:
John Stiles26f98502020-08-18 09:30:51 -04001797 this->writeIfStatement(s.as<IfStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001798 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001799 case Statement::Kind::kFor:
John Stiles26f98502020-08-18 09:30:51 -04001800 this->writeForStatement(s.as<ForStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001801 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001802 case Statement::Kind::kDo:
John Stiles26f98502020-08-18 09:30:51 -04001803 this->writeDoStatement(s.as<DoStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001804 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001805 case Statement::Kind::kSwitch:
John Stiles26f98502020-08-18 09:30:51 -04001806 this->writeSwitchStatement(s.as<SwitchStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001807 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001808 case Statement::Kind::kBreak:
Ethan Nicholascc305772017-10-13 16:17:45 -04001809 this->write("break;");
1810 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001811 case Statement::Kind::kContinue:
Ethan Nicholascc305772017-10-13 16:17:45 -04001812 this->write("continue;");
1813 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001814 case Statement::Kind::kDiscard:
Timothy Lianga06f2152018-05-24 15:33:31 -04001815 this->write("discard_fragment();");
Ethan Nicholascc305772017-10-13 16:17:45 -04001816 break;
John Stiles98c1f822020-09-09 14:18:53 -04001817 case Statement::Kind::kInlineMarker:
Ethan Nicholase6592142020-09-08 10:22:09 -04001818 case Statement::Kind::kNop:
Ethan Nicholascc305772017-10-13 16:17:45 -04001819 this->write(";");
1820 break;
1821 default:
John Stileseada7bc2021-02-02 16:29:32 -05001822 SkDEBUGFAILF("unsupported statement: %s", s.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -05001823 break;
Ethan Nicholascc305772017-10-13 16:17:45 -04001824 }
1825}
1826
Ethan Nicholascc305772017-10-13 16:17:45 -04001827void MetalCodeGenerator::writeBlock(const Block& b) {
John Stiles3744bd62021-01-26 13:49:43 -05001828 // Write scope markers if this block is a scope, or if the block is empty (since we need to emit
1829 // something here to make the code valid).
1830 bool isScope = b.isScope() || b.isEmpty();
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001831 if (isScope) {
Ethan Nicholas70728ef2020-05-28 07:09:00 -04001832 this->writeLine("{");
1833 fIndentation++;
1834 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001835 for (const std::unique_ptr<Statement>& stmt : b.children()) {
1836 if (!stmt->isEmpty()) {
1837 this->writeStatement(*stmt);
John Stilese8b5a732021-03-12 13:25:52 -05001838 this->finishLine();
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001839 }
1840 }
1841 if (isScope) {
Ethan Nicholas70728ef2020-05-28 07:09:00 -04001842 fIndentation--;
1843 this->write("}");
1844 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001845}
1846
1847void MetalCodeGenerator::writeIfStatement(const IfStatement& stmt) {
1848 this->write("if (");
Brian Osman00185012021-02-04 16:07:11 -05001849 this->writeExpression(*stmt.test(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001850 this->write(") ");
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04001851 this->writeStatement(*stmt.ifTrue());
1852 if (stmt.ifFalse()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001853 this->write(" else ");
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04001854 this->writeStatement(*stmt.ifFalse());
Ethan Nicholascc305772017-10-13 16:17:45 -04001855 }
1856}
1857
1858void MetalCodeGenerator::writeForStatement(const ForStatement& f) {
Brian Osmand6f23382020-12-15 17:08:59 -05001859 // Emit loops of the form 'for(;test;)' as 'while(test)', which is probably how they started
1860 if (!f.initializer() && f.test() && !f.next()) {
1861 this->write("while (");
Brian Osman00185012021-02-04 16:07:11 -05001862 this->writeExpression(*f.test(), Precedence::kTopLevel);
Brian Osmand6f23382020-12-15 17:08:59 -05001863 this->write(") ");
1864 this->writeStatement(*f.statement());
1865 return;
1866 }
1867
Ethan Nicholascc305772017-10-13 16:17:45 -04001868 this->write("for (");
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04001869 if (f.initializer() && !f.initializer()->isEmpty()) {
1870 this->writeStatement(*f.initializer());
Ethan Nicholascc305772017-10-13 16:17:45 -04001871 } else {
1872 this->write("; ");
1873 }
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04001874 if (f.test()) {
Brian Osman00185012021-02-04 16:07:11 -05001875 this->writeExpression(*f.test(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001876 }
1877 this->write("; ");
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04001878 if (f.next()) {
Brian Osman00185012021-02-04 16:07:11 -05001879 this->writeExpression(*f.next(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001880 }
1881 this->write(") ");
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04001882 this->writeStatement(*f.statement());
Ethan Nicholascc305772017-10-13 16:17:45 -04001883}
1884
Ethan Nicholascc305772017-10-13 16:17:45 -04001885void MetalCodeGenerator::writeDoStatement(const DoStatement& d) {
1886 this->write("do ");
Ethan Nicholas1fd61162020-09-28 13:14:19 -04001887 this->writeStatement(*d.statement());
Ethan Nicholascc305772017-10-13 16:17:45 -04001888 this->write(" while (");
Brian Osman00185012021-02-04 16:07:11 -05001889 this->writeExpression(*d.test(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001890 this->write(");");
1891}
1892
1893void MetalCodeGenerator::writeSwitchStatement(const SwitchStatement& s) {
1894 this->write("switch (");
Brian Osman00185012021-02-04 16:07:11 -05001895 this->writeExpression(*s.value(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001896 this->writeLine(") {");
1897 fIndentation++;
John Stilesb23a64b2021-03-11 08:27:59 -05001898 for (const std::unique_ptr<Statement>& stmt : s.cases()) {
1899 const SwitchCase& c = stmt->as<SwitchCase>();
1900 if (c.value()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001901 this->write("case ");
John Stilesb23a64b2021-03-11 08:27:59 -05001902 this->writeExpression(*c.value(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001903 this->writeLine(":");
1904 } else {
1905 this->writeLine("default:");
1906 }
John Stilesb23a64b2021-03-11 08:27:59 -05001907 if (!c.statement()->isEmpty()) {
John Stilesc3ce43b2021-03-09 15:37:01 -05001908 fIndentation++;
John Stilesb23a64b2021-03-11 08:27:59 -05001909 this->writeStatement(*c.statement());
John Stilese8b5a732021-03-12 13:25:52 -05001910 this->finishLine();
John Stilesc3ce43b2021-03-09 15:37:01 -05001911 fIndentation--;
Ethan Nicholascc305772017-10-13 16:17:45 -04001912 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001913 }
1914 fIndentation--;
1915 this->write("}");
1916}
1917
John Stiles986c7fb2020-12-01 14:44:56 -05001918void MetalCodeGenerator::writeReturnStatementFromMain() {
1919 // main functions in Metal return a magic _out parameter that doesn't exist in SkSL.
John Stiles270cec22021-02-17 12:59:36 -05001920 switch (fProgram.fConfig->fKind) {
John Stilesdbd4e6f2021-02-16 13:29:15 -05001921 case ProgramKind::kFragment:
John Stilesf7410bd2021-01-19 13:07:55 -05001922 this->write("return _out;");
John Stiles986c7fb2020-12-01 14:44:56 -05001923 break;
John Stilesdbd4e6f2021-02-16 13:29:15 -05001924 case ProgramKind::kVertex:
John Stilesf7410bd2021-01-19 13:07:55 -05001925 this->write("return (_out.sk_Position.y = -_out.sk_Position.y, _out);");
John Stiles986c7fb2020-12-01 14:44:56 -05001926 break;
1927 default:
1928 SkDEBUGFAIL("unsupported kind of program");
1929 }
1930}
1931
Ethan Nicholascc305772017-10-13 16:17:45 -04001932void MetalCodeGenerator::writeReturnStatement(const ReturnStatement& r) {
John Stilese8da4d22021-03-24 09:19:45 -04001933 if (fCurrentFunction && fCurrentFunction->isMain()) {
John Stiles986c7fb2020-12-01 14:44:56 -05001934 if (r.expression()) {
John Stiles97d18172021-01-22 16:47:42 -05001935 if (r.expression()->type() == *fContext.fTypes.fHalf4) {
1936 this->write("_out.sk_FragColor = ");
Brian Osman00185012021-02-04 16:07:11 -05001937 this->writeExpression(*r.expression(), Precedence::kTopLevel);
John Stiles97d18172021-01-22 16:47:42 -05001938 this->writeLine(";");
1939 } else {
1940 fErrors.error(r.fOffset, "Metal does not support returning '" +
1941 r.expression()->type().description() + "' from main()");
1942 }
John Stiles986c7fb2020-12-01 14:44:56 -05001943 }
1944 this->writeReturnStatementFromMain();
1945 return;
1946 }
1947
Ethan Nicholascc305772017-10-13 16:17:45 -04001948 this->write("return");
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04001949 if (r.expression()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001950 this->write(" ");
Brian Osman00185012021-02-04 16:07:11 -05001951 this->writeExpression(*r.expression(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001952 }
1953 this->write(";");
1954}
1955
Michael Ludwigbf58add2021-03-16 10:40:11 -04001956void MetalCodeGenerator::writeHeader() {
1957 this->write("#include <metal_stdlib>\n");
1958 this->write("#include <simd/simd.h>\n");
1959 this->write("using namespace metal;\n");
1960}
1961
Ethan Nicholascc305772017-10-13 16:17:45 -04001962void MetalCodeGenerator::writeUniformStruct() {
Brian Osman133724c2020-10-28 14:14:39 -04001963 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04001964 if (e->is<GlobalVarDeclaration>()) {
1965 const GlobalVarDeclaration& decls = e->as<GlobalVarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001966 const Variable& var = decls.declaration()->as<VarDeclaration>().var();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001967 if (var.modifiers().fFlags & Modifiers::kUniform_Flag &&
Brian Osmanc0213602020-10-06 14:43:32 -04001968 var.type().typeKind() != Type::TypeKind::kSampler) {
John Stilesda5cdf62021-01-28 11:47:29 -05001969 int uniformSet = this->getUniformSet(var.modifiers());
John Stilesd8fc95d2021-01-26 16:22:53 -05001970 // Make sure that the program's uniform-set value is consistent throughout.
Ethan Nicholascc305772017-10-13 16:17:45 -04001971 if (-1 == fUniformBuffer) {
1972 this->write("struct Uniforms {\n");
John Stilesd8fc95d2021-01-26 16:22:53 -05001973 fUniformBuffer = uniformSet;
1974 } else if (uniformSet != fUniformBuffer) {
1975 fErrors.error(decls.fOffset, "Metal backend requires all uniforms to have "
1976 "the same 'layout(set=...)'");
Ethan Nicholascc305772017-10-13 16:17:45 -04001977 }
1978 this->write(" ");
John Stilesb4418502021-02-04 10:57:08 -05001979 this->writeType(var.type());
Ethan Nicholascc305772017-10-13 16:17:45 -04001980 this->write(" ");
Brian Osmanc0213602020-10-06 14:43:32 -04001981 this->writeName(var.name());
Ethan Nicholascc305772017-10-13 16:17:45 -04001982 this->write(";\n");
1983 }
1984 }
1985 }
1986 if (-1 != fUniformBuffer) {
1987 this->write("};\n");
1988 }
1989}
1990
1991void MetalCodeGenerator::writeInputStruct() {
1992 this->write("struct Inputs {\n");
Brian Osman133724c2020-10-28 14:14:39 -04001993 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04001994 if (e->is<GlobalVarDeclaration>()) {
1995 const GlobalVarDeclaration& decls = e->as<GlobalVarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001996 const Variable& var = decls.declaration()->as<VarDeclaration>().var();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001997 if (var.modifiers().fFlags & Modifiers::kIn_Flag &&
1998 -1 == var.modifiers().fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001999 this->write(" ");
John Stilesb4418502021-02-04 10:57:08 -05002000 this->writeType(var.type());
Ethan Nicholascc305772017-10-13 16:17:45 -04002001 this->write(" ");
Brian Osmanc0213602020-10-06 14:43:32 -04002002 this->writeName(var.name());
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002003 if (-1 != var.modifiers().fLayout.fLocation) {
John Stiles270cec22021-02-17 12:59:36 -05002004 if (fProgram.fConfig->fKind == ProgramKind::kVertex) {
Brian Osmanc0213602020-10-06 14:43:32 -04002005 this->write(" [[attribute(" +
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002006 to_string(var.modifiers().fLayout.fLocation) + ")]]");
John Stiles270cec22021-02-17 12:59:36 -05002007 } else if (fProgram.fConfig->fKind == ProgramKind::kFragment) {
Brian Osmanc0213602020-10-06 14:43:32 -04002008 this->write(" [[user(locn" +
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002009 to_string(var.modifiers().fLayout.fLocation) + ")]]");
Ethan Nicholascc305772017-10-13 16:17:45 -04002010 }
2011 }
2012 this->write(";\n");
2013 }
2014 }
2015 }
2016 this->write("};\n");
2017}
2018
2019void MetalCodeGenerator::writeOutputStruct() {
2020 this->write("struct Outputs {\n");
John Stiles270cec22021-02-17 12:59:36 -05002021 if (fProgram.fConfig->fKind == ProgramKind::kVertex) {
Timothy Liangb8eeb802018-07-23 16:46:16 -04002022 this->write(" float4 sk_Position [[position]];\n");
John Stiles270cec22021-02-17 12:59:36 -05002023 } else if (fProgram.fConfig->fKind == ProgramKind::kFragment) {
Timothy Liangde0be802018-08-10 13:48:08 -04002024 this->write(" float4 sk_FragColor [[color(0)]];\n");
Timothy Liang7d637782018-06-05 09:58:07 -04002025 }
Brian Osman133724c2020-10-28 14:14:39 -04002026 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04002027 if (e->is<GlobalVarDeclaration>()) {
2028 const GlobalVarDeclaration& decls = e->as<GlobalVarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04002029 const Variable& var = decls.declaration()->as<VarDeclaration>().var();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002030 if (var.modifiers().fFlags & Modifiers::kOut_Flag &&
2031 -1 == var.modifiers().fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002032 this->write(" ");
John Stilesb4418502021-02-04 10:57:08 -05002033 this->writeType(var.type());
Ethan Nicholascc305772017-10-13 16:17:45 -04002034 this->write(" ");
Brian Osmanc0213602020-10-06 14:43:32 -04002035 this->writeName(var.name());
John Stiles842b3592020-12-01 10:36:37 -05002036
2037 int location = var.modifiers().fLayout.fLocation;
2038 if (location < 0) {
2039 fErrors.error(var.fOffset,
2040 "Metal out variables must have 'layout(location=...)'");
John Stiles270cec22021-02-17 12:59:36 -05002041 } else if (fProgram.fConfig->fKind == ProgramKind::kVertex) {
John Stiles842b3592020-12-01 10:36:37 -05002042 this->write(" [[user(locn" + to_string(location) + ")]]");
John Stiles270cec22021-02-17 12:59:36 -05002043 } else if (fProgram.fConfig->fKind == ProgramKind::kFragment) {
John Stiles842b3592020-12-01 10:36:37 -05002044 this->write(" [[color(" + to_string(location) + ")");
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002045 int colorIndex = var.modifiers().fLayout.fIndex;
Brian Osmanc0213602020-10-06 14:43:32 -04002046 if (colorIndex) {
2047 this->write(", index(" + to_string(colorIndex) + ")");
Timothy Liang7d637782018-06-05 09:58:07 -04002048 }
Brian Osmanc0213602020-10-06 14:43:32 -04002049 this->write("]]");
Ethan Nicholascc305772017-10-13 16:17:45 -04002050 }
2051 this->write(";\n");
2052 }
2053 }
Timothy Liang7d637782018-06-05 09:58:07 -04002054 }
John Stiles270cec22021-02-17 12:59:36 -05002055 if (fProgram.fConfig->fKind == ProgramKind::kVertex) {
Jim Van Verth3913d3e2020-08-31 15:16:57 -04002056 this->write(" float sk_PointSize [[point_size]];\n");
Timothy Liang7d637782018-06-05 09:58:07 -04002057 }
2058 this->write("};\n");
2059}
2060
2061void MetalCodeGenerator::writeInterfaceBlocks() {
2062 bool wroteInterfaceBlock = false;
Brian Osman133724c2020-10-28 14:14:39 -04002063 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04002064 if (e->is<InterfaceBlock>()) {
2065 this->writeInterfaceBlock(e->as<InterfaceBlock>());
Timothy Liang7d637782018-06-05 09:58:07 -04002066 wroteInterfaceBlock = true;
2067 }
2068 }
Jim Van Verth3d482992019-02-07 10:48:05 -05002069 if (!wroteInterfaceBlock && fProgram.fInputs.fRTHeight) {
Timothy Liang7d637782018-06-05 09:58:07 -04002070 this->writeLine("struct sksl_synthetic_uniforms {");
2071 this->writeLine(" float u_skRTHeight;");
2072 this->writeLine("};");
2073 }
Ethan Nicholascc305772017-10-13 16:17:45 -04002074}
2075
John Stilesdc75a972020-11-25 16:24:55 -05002076void MetalCodeGenerator::writeStructDefinitions() {
2077 for (const ProgramElement* e : fProgram.elements()) {
2078 if (e->is<StructDefinition>()) {
Brian Osman02bc5222021-01-28 11:00:20 -05002079 this->writeStructDefinition(e->as<StructDefinition>());
John Stilesdc75a972020-11-25 16:24:55 -05002080 }
2081 }
2082}
2083
John Stilescdcdb042020-07-06 09:03:51 -04002084void MetalCodeGenerator::visitGlobalStruct(GlobalStructVisitor* visitor) {
2085 // Visit the interface blocks.
2086 for (const auto& [interfaceType, interfaceName] : fInterfaceBlockNameMap) {
John Stilesfdb8dbe2020-12-04 11:00:03 -05002087 visitor->visitInterfaceBlock(*interfaceType, interfaceName);
John Stilescdcdb042020-07-06 09:03:51 -04002088 }
Brian Osman133724c2020-10-28 14:14:39 -04002089 for (const ProgramElement* element : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04002090 if (!element->is<GlobalVarDeclaration>()) {
John Stilescdcdb042020-07-06 09:03:51 -04002091 continue;
Timothy Liang7d637782018-06-05 09:58:07 -04002092 }
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04002093 const GlobalVarDeclaration& global = element->as<GlobalVarDeclaration>();
2094 const VarDeclaration& decl = global.declaration()->as<VarDeclaration>();
2095 const Variable& var = decl.var();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002096 if ((!var.modifiers().fFlags && -1 == var.modifiers().fLayout.fBuiltin) ||
Brian Osmanc0213602020-10-06 14:43:32 -04002097 var.type().typeKind() == Type::TypeKind::kSampler) {
2098 if (var.type().typeKind() == Type::TypeKind::kSampler) {
2099 // Samplers are represented as a "texture/sampler" duo in the global struct.
John Stilesfdb8dbe2020-12-04 11:00:03 -05002100 visitor->visitTexture(var.type(), var.name());
2101 visitor->visitSampler(var.type(), String(var.name()) + SAMPLER_SUFFIX);
Brian Osmanc0213602020-10-06 14:43:32 -04002102 } else {
2103 // Visit a regular variable.
John Stilesfdb8dbe2020-12-04 11:00:03 -05002104 visitor->visitVariable(var, decl.value().get());
Timothy Liangee84fe12018-05-18 14:38:19 -04002105 }
2106 }
2107 }
John Stilescdcdb042020-07-06 09:03:51 -04002108}
2109
2110void MetalCodeGenerator::writeGlobalStruct() {
2111 class : public GlobalStructVisitor {
2112 public:
John Stilesfdb8dbe2020-12-04 11:00:03 -05002113 void visitInterfaceBlock(const InterfaceBlock& block, const String& blockName) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002114 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002115 fCodeGen->write(" constant ");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04002116 fCodeGen->write(block.typeName());
John Stilescdcdb042020-07-06 09:03:51 -04002117 fCodeGen->write("* ");
2118 fCodeGen->writeName(blockName);
2119 fCodeGen->write(";\n");
2120 }
John Stilesfdb8dbe2020-12-04 11:00:03 -05002121 void visitTexture(const Type& type, const String& name) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002122 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002123 fCodeGen->write(" ");
John Stilesb4418502021-02-04 10:57:08 -05002124 fCodeGen->writeType(type);
John Stilescdcdb042020-07-06 09:03:51 -04002125 fCodeGen->write(" ");
2126 fCodeGen->writeName(name);
2127 fCodeGen->write(";\n");
2128 }
John Stilesfdb8dbe2020-12-04 11:00:03 -05002129 void visitSampler(const Type&, const String& name) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002130 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002131 fCodeGen->write(" sampler ");
2132 fCodeGen->writeName(name);
2133 fCodeGen->write(";\n");
2134 }
John Stilesfdb8dbe2020-12-04 11:00:03 -05002135 void visitVariable(const Variable& var, const Expression* value) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002136 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002137 fCodeGen->write(" ");
John Stilesb4418502021-02-04 10:57:08 -05002138 fCodeGen->writeType(var.type());
John Stilescdcdb042020-07-06 09:03:51 -04002139 fCodeGen->write(" ");
Ethan Nicholase2c49992020-10-05 11:49:11 -04002140 fCodeGen->writeName(var.name());
John Stilescdcdb042020-07-06 09:03:51 -04002141 fCodeGen->write(";\n");
2142 }
John Stiles83f3b8d2020-12-07 17:52:25 -05002143 void addElement() {
John Stilescdcdb042020-07-06 09:03:51 -04002144 if (fFirst) {
2145 fCodeGen->write("struct Globals {\n");
2146 fFirst = false;
2147 }
2148 }
John Stiles83f3b8d2020-12-07 17:52:25 -05002149 void finish() {
John Stilescdcdb042020-07-06 09:03:51 -04002150 if (!fFirst) {
John Stiles83f3b8d2020-12-07 17:52:25 -05002151 fCodeGen->writeLine("};");
John Stilescdcdb042020-07-06 09:03:51 -04002152 fFirst = true;
2153 }
2154 }
2155
2156 MetalCodeGenerator* fCodeGen = nullptr;
2157 bool fFirst = true;
2158 } visitor;
2159
2160 visitor.fCodeGen = this;
2161 this->visitGlobalStruct(&visitor);
John Stiles83f3b8d2020-12-07 17:52:25 -05002162 visitor.finish();
John Stilescdcdb042020-07-06 09:03:51 -04002163}
2164
2165void MetalCodeGenerator::writeGlobalInit() {
2166 class : public GlobalStructVisitor {
2167 public:
John Stilesfdb8dbe2020-12-04 11:00:03 -05002168 void visitInterfaceBlock(const InterfaceBlock& blockType,
John Stilescdcdb042020-07-06 09:03:51 -04002169 const String& blockName) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002170 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002171 fCodeGen->write("&");
2172 fCodeGen->writeName(blockName);
2173 }
John Stilesfdb8dbe2020-12-04 11:00:03 -05002174 void visitTexture(const Type&, const String& name) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002175 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002176 fCodeGen->writeName(name);
2177 }
John Stilesfdb8dbe2020-12-04 11:00:03 -05002178 void visitSampler(const Type&, const String& name) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002179 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002180 fCodeGen->writeName(name);
2181 }
John Stilesfdb8dbe2020-12-04 11:00:03 -05002182 void visitVariable(const Variable& var, const Expression* value) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002183 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002184 if (value) {
2185 fCodeGen->writeVarInitializer(var, *value);
2186 } else {
2187 fCodeGen->write("{}");
2188 }
2189 }
John Stiles83f3b8d2020-12-07 17:52:25 -05002190 void addElement() {
John Stilescdcdb042020-07-06 09:03:51 -04002191 if (fFirst) {
John Stilesf7410bd2021-01-19 13:07:55 -05002192 fCodeGen->write(" Globals _globals{");
John Stilescdcdb042020-07-06 09:03:51 -04002193 fFirst = false;
2194 } else {
2195 fCodeGen->write(", ");
2196 }
2197 }
John Stiles83f3b8d2020-12-07 17:52:25 -05002198 void finish() {
John Stilescdcdb042020-07-06 09:03:51 -04002199 if (!fFirst) {
2200 fCodeGen->writeLine("};");
John Stiles37279172021-01-21 22:24:28 -05002201 fCodeGen->writeLine(" (void)_globals;");
John Stilescdcdb042020-07-06 09:03:51 -04002202 }
2203 }
2204 MetalCodeGenerator* fCodeGen = nullptr;
2205 bool fFirst = true;
2206 } visitor;
2207
2208 visitor.fCodeGen = this;
2209 this->visitGlobalStruct(&visitor);
John Stiles83f3b8d2020-12-07 17:52:25 -05002210 visitor.finish();
Timothy Liangee84fe12018-05-18 14:38:19 -04002211}
2212
Ethan Nicholascc305772017-10-13 16:17:45 -04002213void MetalCodeGenerator::writeProgramElement(const ProgramElement& e) {
Ethan Nicholase6592142020-09-08 10:22:09 -04002214 switch (e.kind()) {
2215 case ProgramElement::Kind::kExtension:
Ethan Nicholascc305772017-10-13 16:17:45 -04002216 break;
Brian Osmanc0213602020-10-06 14:43:32 -04002217 case ProgramElement::Kind::kGlobalVar: {
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04002218 const GlobalVarDeclaration& global = e.as<GlobalVarDeclaration>();
2219 const VarDeclaration& decl = global.declaration()->as<VarDeclaration>();
2220 int builtin = decl.var().modifiers().fLayout.fBuiltin;
Brian Osmanc0213602020-10-06 14:43:32 -04002221 if (-1 == builtin) {
2222 // normal var
2223 this->writeVarDeclaration(decl, true);
John Stilese8b5a732021-03-12 13:25:52 -05002224 this->finishLine();
Brian Osmanc0213602020-10-06 14:43:32 -04002225 } else if (SK_FRAGCOLOR_BUILTIN == builtin) {
2226 // ignore
Ethan Nicholascc305772017-10-13 16:17:45 -04002227 }
2228 break;
2229 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002230 case ProgramElement::Kind::kInterfaceBlock:
Timothy Liang7d637782018-06-05 09:58:07 -04002231 // handled in writeInterfaceBlocks, do nothing
Ethan Nicholascc305772017-10-13 16:17:45 -04002232 break;
John Stilesdc75a972020-11-25 16:24:55 -05002233 case ProgramElement::Kind::kStructDefinition:
2234 // Handled in writeStructDefinitions. Do nothing.
2235 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04002236 case ProgramElement::Kind::kFunction:
John Stiles3dc0da62020-08-19 17:48:31 -04002237 this->writeFunction(e.as<FunctionDefinition>());
Ethan Nicholascc305772017-10-13 16:17:45 -04002238 break;
John Stiles569249b2020-11-03 12:18:22 -05002239 case ProgramElement::Kind::kFunctionPrototype:
2240 this->writeFunctionPrototype(e.as<FunctionPrototype>());
2241 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04002242 case ProgramElement::Kind::kModifiers:
John Stiles06b84ef2020-12-09 12:35:48 -05002243 this->writeModifiers(e.as<ModifiersDeclaration>().modifiers(),
2244 /*globalContext=*/true);
Ethan Nicholascc305772017-10-13 16:17:45 -04002245 this->writeLine(";");
2246 break;
John Stiles712fd6b2020-11-25 22:25:43 -05002247 case ProgramElement::Kind::kEnum:
2248 break;
Ethan Nicholascc305772017-10-13 16:17:45 -04002249 default:
John Stileseada7bc2021-02-02 16:29:32 -05002250 SkDEBUGFAILF("unsupported program element: %s\n", e.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -05002251 break;
Ethan Nicholascc305772017-10-13 16:17:45 -04002252 }
2253}
2254
Ethan Nicholasff350cb2020-05-14 14:05:13 -04002255MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const Expression* e) {
2256 if (!e) {
2257 return kNo_Requirements;
2258 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002259 switch (e->kind()) {
2260 case Expression::Kind::kFunctionCall: {
John Stiles3dc0da62020-08-19 17:48:31 -04002261 const FunctionCall& f = e->as<FunctionCall>();
Ethan Nicholas0dec9922020-10-05 15:51:52 -04002262 Requirements result = this->requirements(f.function());
2263 for (const auto& arg : f.arguments()) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04002264 result |= this->requirements(arg.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002265 }
2266 return result;
2267 }
John Stiles7384b372021-04-01 13:48:15 -04002268 case Expression::Kind::kConstructor:
2269 case Expression::Kind::kConstructorArray:
John Stiles2938eea2021-04-01 18:58:25 -04002270 case Expression::Kind::kConstructorDiagonalMatrix:
John Stilesfd7252f2021-04-04 22:24:40 -04002271 case Expression::Kind::kConstructorScalarCast:
John Stiles2938eea2021-04-01 18:58:25 -04002272 case Expression::Kind::kConstructorSplat: {
John Stiles7384b372021-04-01 13:48:15 -04002273 const AnyConstructor& c = e->asAnyConstructor();
Ethan Nicholascc305772017-10-13 16:17:45 -04002274 Requirements result = kNo_Requirements;
John Stilesd8eb8752021-04-01 11:49:10 -04002275 for (const auto& arg : c.argumentSpan()) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04002276 result |= this->requirements(arg.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002277 }
2278 return result;
2279 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002280 case Expression::Kind::kFieldAccess: {
John Stiles3dc0da62020-08-19 17:48:31 -04002281 const FieldAccess& f = e->as<FieldAccess>();
Ethan Nicholas7a95b202020-10-09 11:55:40 -04002282 if (FieldAccess::OwnerKind::kAnonymousInterfaceBlock == f.ownerKind()) {
Timothy Liang7d637782018-06-05 09:58:07 -04002283 return kGlobals_Requirement;
2284 }
Ethan Nicholas7a95b202020-10-09 11:55:40 -04002285 return this->requirements(f.base().get());
Timothy Liang7d637782018-06-05 09:58:07 -04002286 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002287 case Expression::Kind::kSwizzle:
Ethan Nicholas6b4d5812020-10-12 16:11:51 -04002288 return this->requirements(e->as<Swizzle>().base().get());
Ethan Nicholase6592142020-09-08 10:22:09 -04002289 case Expression::Kind::kBinary: {
2290 const BinaryExpression& bin = e->as<BinaryExpression>();
John Stiles2d4f9592020-10-30 10:29:12 -04002291 return this->requirements(bin.left().get()) |
2292 this->requirements(bin.right().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002293 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002294 case Expression::Kind::kIndex: {
John Stiles3dc0da62020-08-19 17:48:31 -04002295 const IndexExpression& idx = e->as<IndexExpression>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04002296 return this->requirements(idx.base().get()) | this->requirements(idx.index().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002297 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002298 case Expression::Kind::kPrefix:
Ethan Nicholas444ccc62020-10-09 10:16:22 -04002299 return this->requirements(e->as<PrefixExpression>().operand().get());
Ethan Nicholase6592142020-09-08 10:22:09 -04002300 case Expression::Kind::kPostfix:
Ethan Nicholas444ccc62020-10-09 10:16:22 -04002301 return this->requirements(e->as<PostfixExpression>().operand().get());
Ethan Nicholase6592142020-09-08 10:22:09 -04002302 case Expression::Kind::kTernary: {
John Stiles3dc0da62020-08-19 17:48:31 -04002303 const TernaryExpression& t = e->as<TernaryExpression>();
Ethan Nicholasdd218162020-10-08 05:48:01 -04002304 return this->requirements(t.test().get()) | this->requirements(t.ifTrue().get()) |
2305 this->requirements(t.ifFalse().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002306 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002307 case Expression::Kind::kVariableReference: {
John Stiles3dc0da62020-08-19 17:48:31 -04002308 const VariableReference& v = e->as<VariableReference>();
Ethan Nicholas78686922020-10-08 06:46:27 -04002309 const Modifiers& modifiers = v.variable()->modifiers();
Ethan Nicholascc305772017-10-13 16:17:45 -04002310 Requirements result = kNo_Requirements;
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002311 if (modifiers.fLayout.fBuiltin == SK_FRAGCOORD_BUILTIN) {
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -04002312 result = kGlobals_Requirement | kFragCoord_Requirement;
Ethan Nicholas453f67f2020-10-09 10:43:45 -04002313 } else if (Variable::Storage::kGlobal == v.variable()->storage()) {
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002314 if (modifiers.fFlags & Modifiers::kIn_Flag) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002315 result = kInputs_Requirement;
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002316 } else if (modifiers.fFlags & Modifiers::kOut_Flag) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002317 result = kOutputs_Requirement;
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002318 } else if (modifiers.fFlags & Modifiers::kUniform_Flag &&
Ethan Nicholas78686922020-10-08 06:46:27 -04002319 v.variable()->type().typeKind() != Type::TypeKind::kSampler) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002320 result = kUniforms_Requirement;
Timothy Liangee84fe12018-05-18 14:38:19 -04002321 } else {
2322 result = kGlobals_Requirement;
Ethan Nicholascc305772017-10-13 16:17:45 -04002323 }
2324 }
2325 return result;
2326 }
2327 default:
2328 return kNo_Requirements;
2329 }
2330}
2331
Ethan Nicholasff350cb2020-05-14 14:05:13 -04002332MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const Statement* s) {
2333 if (!s) {
2334 return kNo_Requirements;
2335 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002336 switch (s->kind()) {
2337 case Statement::Kind::kBlock: {
Ethan Nicholascc305772017-10-13 16:17:45 -04002338 Requirements result = kNo_Requirements;
Ethan Nicholas7bd60432020-09-25 14:31:59 -04002339 for (const std::unique_ptr<Statement>& child : s->as<Block>().children()) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04002340 result |= this->requirements(child.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002341 }
2342 return result;
2343 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002344 case Statement::Kind::kVarDeclaration: {
John Stiles3dc0da62020-08-19 17:48:31 -04002345 const VarDeclaration& var = s->as<VarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04002346 return this->requirements(var.value().get());
Timothy Liang7d637782018-06-05 09:58:07 -04002347 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002348 case Statement::Kind::kExpression:
Ethan Nicholasd503a5a2020-09-30 09:29:55 -04002349 return this->requirements(s->as<ExpressionStatement>().expression().get());
Ethan Nicholase6592142020-09-08 10:22:09 -04002350 case Statement::Kind::kReturn: {
John Stiles3dc0da62020-08-19 17:48:31 -04002351 const ReturnStatement& r = s->as<ReturnStatement>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04002352 return this->requirements(r.expression().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002353 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002354 case Statement::Kind::kIf: {
John Stiles3dc0da62020-08-19 17:48:31 -04002355 const IfStatement& i = s->as<IfStatement>();
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04002356 return this->requirements(i.test().get()) |
2357 this->requirements(i.ifTrue().get()) |
2358 this->requirements(i.ifFalse().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002359 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002360 case Statement::Kind::kFor: {
John Stiles3dc0da62020-08-19 17:48:31 -04002361 const ForStatement& f = s->as<ForStatement>();
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04002362 return this->requirements(f.initializer().get()) |
2363 this->requirements(f.test().get()) |
2364 this->requirements(f.next().get()) |
2365 this->requirements(f.statement().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002366 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002367 case Statement::Kind::kDo: {
John Stiles3dc0da62020-08-19 17:48:31 -04002368 const DoStatement& d = s->as<DoStatement>();
Ethan Nicholas1fd61162020-09-28 13:14:19 -04002369 return this->requirements(d.test().get()) |
2370 this->requirements(d.statement().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002371 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002372 case Statement::Kind::kSwitch: {
John Stiles3dc0da62020-08-19 17:48:31 -04002373 const SwitchStatement& sw = s->as<SwitchStatement>();
Ethan Nicholas01b05e52020-10-22 15:53:41 -04002374 Requirements result = this->requirements(sw.value().get());
John Stilesb23a64b2021-03-11 08:27:59 -05002375 for (const std::unique_ptr<Statement>& sc : sw.cases()) {
2376 result |= this->requirements(sc->as<SwitchCase>().statement().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002377 }
2378 return result;
2379 }
2380 default:
2381 return kNo_Requirements;
2382 }
2383}
2384
2385MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const FunctionDeclaration& f) {
Ethan Nicholased84b732020-10-08 11:45:44 -04002386 if (f.isBuiltin()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002387 return kNo_Requirements;
2388 }
2389 auto found = fRequirements.find(&f);
2390 if (found == fRequirements.end()) {
Ethan Nicholas65a8f562019-04-19 14:00:26 -04002391 fRequirements[&f] = kNo_Requirements;
Brian Osman133724c2020-10-28 14:14:39 -04002392 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04002393 if (e->is<FunctionDefinition>()) {
2394 const FunctionDefinition& def = e->as<FunctionDefinition>();
Ethan Nicholas0a5d0962020-10-14 13:33:18 -04002395 if (&def.declaration() == &f) {
2396 Requirements reqs = this->requirements(def.body().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002397 fRequirements[&f] = reqs;
2398 return reqs;
2399 }
2400 }
2401 }
John Stiles569249b2020-11-03 12:18:22 -05002402 // We never found a definition for this declared function, but it's legal to prototype a
2403 // function without ever giving a definition, as long as you don't call it.
2404 return kNo_Requirements;
Ethan Nicholascc305772017-10-13 16:17:45 -04002405 }
2406 return found->second;
2407}
2408
Timothy Liangb8eeb802018-07-23 16:46:16 -04002409bool MetalCodeGenerator::generateCode() {
John Stiles44532372020-12-07 12:33:55 -05002410 StringStream header;
2411 {
2412 AutoOutputStream outputToHeader(this, &header, &fIndentation);
Michael Ludwigbf58add2021-03-16 10:40:11 -04002413 this->writeHeader();
John Stiles44532372020-12-07 12:33:55 -05002414 this->writeStructDefinitions();
2415 this->writeUniformStruct();
2416 this->writeInputStruct();
2417 this->writeOutputStruct();
2418 this->writeInterfaceBlocks();
2419 this->writeGlobalStruct();
2420 }
2421 StringStream body;
2422 {
2423 AutoOutputStream outputToBody(this, &body, &fIndentation);
2424 for (const ProgramElement* e : fProgram.elements()) {
2425 this->writeProgramElement(*e);
2426 }
2427 }
2428 write_stringstream(header, *fOut);
2429 write_stringstream(fExtraFunctions, *fOut);
2430 write_stringstream(body, *fOut);
Brian Osman8609a242020-09-08 14:01:49 -04002431 return 0 == fErrors.errorCount();
Ethan Nicholascc305772017-10-13 16:17:45 -04002432}
2433
John Stilesa6841be2020-08-06 14:11:56 -04002434} // namespace SkSL