blob: dc6e63242b89a86163fb602ae41d449d2c960f52 [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 Stiles5abb9e12021-04-06 13:47:19 -040015#include "src/sksl/ir/SkSLConstructorMatrixResize.h"
John Stiles2938eea2021-04-01 18:58:25 -040016#include "src/sksl/ir/SkSLConstructorSplat.h"
John Stilesb14a8192021-04-05 11:40:46 -040017#include "src/sksl/ir/SkSLConstructorVectorCast.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050018#include "src/sksl/ir/SkSLExpressionStatement.h"
19#include "src/sksl/ir/SkSLExtension.h"
20#include "src/sksl/ir/SkSLIndexExpression.h"
21#include "src/sksl/ir/SkSLModifiersDeclaration.h"
22#include "src/sksl/ir/SkSLNop.h"
John Stilesdc75a972020-11-25 16:24:55 -050023#include "src/sksl/ir/SkSLStructDefinition.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050024#include "src/sksl/ir/SkSLVariableReference.h"
Ethan Nicholascc305772017-10-13 16:17:45 -040025
Brian Osmanc262a122020-08-06 16:34:34 -040026#include <algorithm>
27
Ethan Nicholascc305772017-10-13 16:17:45 -040028namespace SkSL {
29
John Stiles45990502021-02-16 10:55:27 -050030const char* MetalCodeGenerator::OperatorName(Operator op) {
31 switch (op.kind()) {
John Stilesd6449e92020-11-30 09:13:23 -050032 case Token::Kind::TK_LOGICALXOR: return "!=";
John Stiles45990502021-02-16 10:55:27 -050033 default: return op.operatorName();
John Stilesd6449e92020-11-30 09:13:23 -050034 }
35}
36
John Stilescdcdb042020-07-06 09:03:51 -040037class MetalCodeGenerator::GlobalStructVisitor {
38public:
39 virtual ~GlobalStructVisitor() = default;
John Stilesfdb8dbe2020-12-04 11:00:03 -050040 virtual void visitInterfaceBlock(const InterfaceBlock& block, const String& blockName) = 0;
41 virtual void visitTexture(const Type& type, const String& name) = 0;
42 virtual void visitSampler(const Type& type, const String& name) = 0;
43 virtual void visitVariable(const Variable& var, const Expression* value) = 0;
John Stilescdcdb042020-07-06 09:03:51 -040044};
45
Timothy Liangee84fe12018-05-18 14:38:19 -040046void MetalCodeGenerator::setupIntrinsics() {
John Stilesd7199b22020-12-30 16:22:58 -050047 fIntrinsicMap[String("atan")] = kAtan_IntrinsicKind;
48 fIntrinsicMap[String("floatBitsToInt")] = kBitcast_IntrinsicKind;
49 fIntrinsicMap[String("floatBitsToUint")] = kBitcast_IntrinsicKind;
50 fIntrinsicMap[String("intBitsToFloat")] = kBitcast_IntrinsicKind;
51 fIntrinsicMap[String("uintBitsToFloat")] = kBitcast_IntrinsicKind;
52 fIntrinsicMap[String("equal")] = kCompareEqual_IntrinsicKind;
53 fIntrinsicMap[String("notEqual")] = kCompareNotEqual_IntrinsicKind;
54 fIntrinsicMap[String("lessThan")] = kCompareLessThan_IntrinsicKind;
55 fIntrinsicMap[String("lessThanEqual")] = kCompareLessThanEqual_IntrinsicKind;
56 fIntrinsicMap[String("greaterThan")] = kCompareGreaterThan_IntrinsicKind;
57 fIntrinsicMap[String("greaterThanEqual")] = kCompareGreaterThanEqual_IntrinsicKind;
58 fIntrinsicMap[String("degrees")] = kDegrees_IntrinsicKind;
59 fIntrinsicMap[String("dFdx")] = kDFdx_IntrinsicKind;
60 fIntrinsicMap[String("dFdy")] = kDFdy_IntrinsicKind;
61 fIntrinsicMap[String("distance")] = kDistance_IntrinsicKind;
62 fIntrinsicMap[String("dot")] = kDot_IntrinsicKind;
63 fIntrinsicMap[String("faceforward")] = kFaceforward_IntrinsicKind;
64 fIntrinsicMap[String("bitCount")] = kBitCount_IntrinsicKind;
65 fIntrinsicMap[String("findLSB")] = kFindLSB_IntrinsicKind;
66 fIntrinsicMap[String("findMSB")] = kFindMSB_IntrinsicKind;
67 fIntrinsicMap[String("inverse")] = kInverse_IntrinsicKind;
68 fIntrinsicMap[String("inversesqrt")] = kInversesqrt_IntrinsicKind;
69 fIntrinsicMap[String("length")] = kLength_IntrinsicKind;
70 fIntrinsicMap[String("matrixCompMult")] = kMatrixCompMult_IntrinsicKind;
71 fIntrinsicMap[String("mod")] = kMod_IntrinsicKind;
72 fIntrinsicMap[String("normalize")] = kNormalize_IntrinsicKind;
73 fIntrinsicMap[String("radians")] = kRadians_IntrinsicKind;
74 fIntrinsicMap[String("reflect")] = kReflect_IntrinsicKind;
75 fIntrinsicMap[String("refract")] = kRefract_IntrinsicKind;
John Stiles23456532020-12-30 18:12:48 -050076 fIntrinsicMap[String("roundEven")] = kRoundEven_IntrinsicKind;
John Stilesd7199b22020-12-30 16:22:58 -050077 fIntrinsicMap[String("sample")] = kTexture_IntrinsicKind;
Timothy Liangee84fe12018-05-18 14:38:19 -040078}
79
Ethan Nicholascc305772017-10-13 16:17:45 -040080void MetalCodeGenerator::write(const char* s) {
81 if (!s[0]) {
82 return;
83 }
84 if (fAtLineStart) {
85 for (int i = 0; i < fIndentation; i++) {
86 fOut->writeText(" ");
87 }
88 }
89 fOut->writeText(s);
90 fAtLineStart = false;
91}
92
93void MetalCodeGenerator::writeLine(const char* s) {
94 this->write(s);
John Stilese8b5a732021-03-12 13:25:52 -050095 this->writeLine();
Ethan Nicholascc305772017-10-13 16:17:45 -040096}
97
98void MetalCodeGenerator::write(const String& s) {
99 this->write(s.c_str());
100}
101
102void MetalCodeGenerator::writeLine(const String& s) {
103 this->writeLine(s.c_str());
104}
105
106void MetalCodeGenerator::writeLine() {
John Stilese8b5a732021-03-12 13:25:52 -0500107 fOut->writeText(fLineEnding);
108 fAtLineStart = true;
109}
110
111void MetalCodeGenerator::finishLine() {
112 if (!fAtLineStart) {
113 this->writeLine();
114 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400115}
116
117void MetalCodeGenerator::writeExtension(const Extension& ext) {
Ethan Nicholasefb09e22020-09-30 10:17:00 -0400118 this->writeLine("#extension " + ext.name() + " : enable");
Ethan Nicholascc305772017-10-13 16:17:45 -0400119}
120
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500121String MetalCodeGenerator::typeName(const Type& type) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400122 switch (type.typeKind()) {
John Stilesb4418502021-02-04 10:57:08 -0500123 case Type::TypeKind::kArray:
124 SkASSERTF(type.columns() > 0, "invalid array size: %s", type.description().c_str());
125 return String::printf("array<%s, %d>",
126 this->typeName(type.componentType()).c_str(), type.columns());
127
Ethan Nicholase6592142020-09-08 10:22:09 -0400128 case Type::TypeKind::kVector:
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500129 return this->typeName(type.componentType()) + to_string(type.columns());
John Stilesb4418502021-02-04 10:57:08 -0500130
Ethan Nicholase6592142020-09-08 10:22:09 -0400131 case Type::TypeKind::kMatrix:
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500132 return this->typeName(type.componentType()) + to_string(type.columns()) + "x" +
133 to_string(type.rows());
John Stilesb4418502021-02-04 10:57:08 -0500134
Ethan Nicholase6592142020-09-08 10:22:09 -0400135 case Type::TypeKind::kSampler:
John Stiles368db7c2020-12-29 11:20:08 -0500136 return "texture2d<float>"; // FIXME - support other texture types
John Stilesb4418502021-02-04 10:57:08 -0500137
John Stilesfd41d872020-11-25 22:39:45 -0500138 case Type::TypeKind::kEnum:
139 return "int";
John Stilesb4418502021-02-04 10:57:08 -0500140
Ethan Nicholascc305772017-10-13 16:17:45 -0400141 default:
John Stiles54e7c052021-01-11 14:22:36 -0500142 if (type == *fContext.fTypes.fHalf) {
Timothy Liang43d225f2018-07-19 15:27:13 -0400143 // FIXME - Currently only supporting floats in MSL to avoid type coercion issues.
John Stiles54e7c052021-01-11 14:22:36 -0500144 return fContext.fTypes.fFloat->name();
145 } else if (type == *fContext.fTypes.fByte) {
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500146 return "char";
John Stiles54e7c052021-01-11 14:22:36 -0500147 } else if (type == *fContext.fTypes.fUByte) {
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500148 return "uchar";
Timothy Liang7d637782018-06-05 09:58:07 -0400149 } else {
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500150 return type.name();
Timothy Liang7d637782018-06-05 09:58:07 -0400151 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400152 }
153}
154
Brian Osman02bc5222021-01-28 11:00:20 -0500155void MetalCodeGenerator::writeStructDefinition(const StructDefinition& s) {
156 const Type& type = s.type();
John Stilesdc75a972020-11-25 16:24:55 -0500157 this->writeLine("struct " + type.name() + " {");
158 fIndentation++;
159 this->writeFields(type.fields(), type.fOffset);
160 fIndentation--;
Brian Osman02bc5222021-01-28 11:00:20 -0500161 this->writeLine("};");
John Stilesdc75a972020-11-25 16:24:55 -0500162}
163
John Stilesb4418502021-02-04 10:57:08 -0500164void MetalCodeGenerator::writeType(const Type& type) {
165 this->write(this->typeName(type));
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500166}
167
Ethan Nicholascc305772017-10-13 16:17:45 -0400168void MetalCodeGenerator::writeExpression(const Expression& expr, Precedence parentPrecedence) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400169 switch (expr.kind()) {
170 case Expression::Kind::kBinary:
John Stiles81365af2020-08-18 09:24:00 -0400171 this->writeBinaryExpression(expr.as<BinaryExpression>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400172 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400173 case Expression::Kind::kBoolLiteral:
John Stiles81365af2020-08-18 09:24:00 -0400174 this->writeBoolLiteral(expr.as<BoolLiteral>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400175 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400176 case Expression::Kind::kConstructor:
John Stiles81365af2020-08-18 09:24:00 -0400177 this->writeConstructor(expr.as<Constructor>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400178 break;
John Stiles5abb9e12021-04-06 13:47:19 -0400179 case Expression::Kind::kConstructorMatrixResize:
180 this->writeConstructorMatrixResize(expr.as<ConstructorMatrixResize>(),
181 parentPrecedence);
182 break;
John Stiles7384b372021-04-01 13:48:15 -0400183 case Expression::Kind::kConstructorArray:
John Stilesb14a8192021-04-05 11:40:46 -0400184 this->writeAnyConstructor(expr.asAnyConstructor(), "{", "}", parentPrecedence);
John Stiles7384b372021-04-01 13:48:15 -0400185 break;
John Stilese1182782021-03-30 22:09:37 -0400186 case Expression::Kind::kConstructorDiagonalMatrix:
John Stilesb14a8192021-04-05 11:40:46 -0400187 case Expression::Kind::kConstructorSplat:
John Stilesd986f472021-04-06 15:54:43 -0400188 case Expression::Kind::kConstructorVector:
John Stilesb14a8192021-04-05 11:40:46 -0400189 this->writeAnyConstructor(expr.asAnyConstructor(), "(", ")", parentPrecedence);
John Stilese1182782021-03-30 22:09:37 -0400190 break;
John Stilesfd7252f2021-04-04 22:24:40 -0400191 case Expression::Kind::kConstructorScalarCast:
John Stilesb14a8192021-04-05 11:40:46 -0400192 case Expression::Kind::kConstructorVectorCast:
193 this->writeCastConstructor(expr.asAnyConstructor(), "(", ")", parentPrecedence);
John Stiles2938eea2021-04-01 18:58:25 -0400194 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400195 case Expression::Kind::kIntLiteral:
John Stiles81365af2020-08-18 09:24:00 -0400196 this->writeIntLiteral(expr.as<IntLiteral>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400197 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400198 case Expression::Kind::kFieldAccess:
John Stiles81365af2020-08-18 09:24:00 -0400199 this->writeFieldAccess(expr.as<FieldAccess>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400200 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400201 case Expression::Kind::kFloatLiteral:
John Stiles81365af2020-08-18 09:24:00 -0400202 this->writeFloatLiteral(expr.as<FloatLiteral>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400203 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400204 case Expression::Kind::kFunctionCall:
John Stiles81365af2020-08-18 09:24:00 -0400205 this->writeFunctionCall(expr.as<FunctionCall>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400206 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400207 case Expression::Kind::kPrefix:
John Stiles81365af2020-08-18 09:24:00 -0400208 this->writePrefixExpression(expr.as<PrefixExpression>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400209 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400210 case Expression::Kind::kPostfix:
John Stiles81365af2020-08-18 09:24:00 -0400211 this->writePostfixExpression(expr.as<PostfixExpression>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400212 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400213 case Expression::Kind::kSetting:
John Stiles81365af2020-08-18 09:24:00 -0400214 this->writeSetting(expr.as<Setting>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400215 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400216 case Expression::Kind::kSwizzle:
John Stiles81365af2020-08-18 09:24:00 -0400217 this->writeSwizzle(expr.as<Swizzle>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400218 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400219 case Expression::Kind::kVariableReference:
John Stiles81365af2020-08-18 09:24:00 -0400220 this->writeVariableReference(expr.as<VariableReference>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400221 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400222 case Expression::Kind::kTernary:
John Stiles81365af2020-08-18 09:24:00 -0400223 this->writeTernaryExpression(expr.as<TernaryExpression>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400224 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400225 case Expression::Kind::kIndex:
John Stiles81365af2020-08-18 09:24:00 -0400226 this->writeIndexExpression(expr.as<IndexExpression>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400227 break;
228 default:
John Stileseada7bc2021-02-02 16:29:32 -0500229 SkDEBUGFAILF("unsupported expression: %s", expr.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -0500230 break;
Ethan Nicholascc305772017-10-13 16:17:45 -0400231 }
232}
233
John Stiles06b84ef2020-12-09 12:35:48 -0500234String MetalCodeGenerator::getOutParamHelper(const FunctionCall& call,
235 const ExpressionArray& arguments,
236 const SkTArray<VariableReference*>& outVars) {
237 AutoOutputStream outputToExtraFunctions(this, &fExtraFunctions, &fIndentation);
238 const FunctionDeclaration& function = call.function();
239
John Stilese1068342021-03-22 11:57:41 -0400240 String name = "_skOutParamHelper" + to_string(fSwizzleHelperCount++) +
241 "_" + function.mangledName();
John Stiles06b84ef2020-12-09 12:35:48 -0500242 const char* separator = "";
243
244 // Emit a prototype for the function we'll be calling through to in our helper.
245 if (!function.isBuiltin()) {
246 this->writeFunctionDeclaration(function);
247 this->writeLine(";");
248 }
249
250 // Synthesize a helper function that takes the same inputs as `function`, except in places where
251 // `outVars` is non-null; in those places, we take the type of the VariableReference.
252 //
253 // float _skOutParamHelper0_originalFuncName(float _var0, float _var1, float& outParam) {
John Stilesb4418502021-02-04 10:57:08 -0500254 this->writeType(call.type());
John Stiles06b84ef2020-12-09 12:35:48 -0500255 this->write(" ");
256 this->write(name);
257 this->write("(");
258 this->writeFunctionRequirementParams(function, separator);
259
260 SkASSERT(outVars.size() == arguments.size());
261 SkASSERT(outVars.size() == function.parameters().size());
262
John Stiles73e2c892021-02-13 13:58:01 -0500263 // We need to detect cases where the caller passes the same variable as an out-param more than
264 // once, and avoid reusing the variable name. (In those cases we can actually just ignore the
265 // redundant input parameter entirely, and not give it any name.)
266 std::unordered_set<const Variable*> writtenVars;
267
John Stiles06b84ef2020-12-09 12:35:48 -0500268 for (int index = 0; index < arguments.count(); ++index) {
269 this->write(separator);
270 separator = ", ";
271
272 const Variable* param = function.parameters()[index];
273 this->writeModifiers(param->modifiers(), /*globalContext=*/false);
274
275 const Type* type = outVars[index] ? &outVars[index]->type() : &arguments[index]->type();
John Stilesb4418502021-02-04 10:57:08 -0500276 this->writeType(*type);
John Stiles06b84ef2020-12-09 12:35:48 -0500277
278 if (param->modifiers().fFlags & Modifiers::kOut_Flag) {
279 this->write("&");
280 }
281 if (outVars[index]) {
John Stiles73e2c892021-02-13 13:58:01 -0500282 auto [iter, didInsert] = writtenVars.insert(outVars[index]->variable());
283 if (didInsert) {
284 this->write(" ");
285 fIgnoreVariableReferenceModifiers = true;
286 this->writeVariableReference(*outVars[index]);
287 fIgnoreVariableReferenceModifiers = false;
288 }
John Stiles06b84ef2020-12-09 12:35:48 -0500289 } else {
290 this->write(" _var");
291 this->write(to_string(index));
292 }
John Stiles06b84ef2020-12-09 12:35:48 -0500293 }
294 this->writeLine(") {");
295
296 ++fIndentation;
297 for (int index = 0; index < outVars.count(); ++index) {
298 if (!outVars[index]) {
299 continue;
300 }
301 // float3 _var2[ = outParam.zyx];
John Stilesb4418502021-02-04 10:57:08 -0500302 this->writeType(arguments[index]->type());
John Stiles06b84ef2020-12-09 12:35:48 -0500303 this->write(" _var");
304 this->write(to_string(index));
305
306 const Variable* param = function.parameters()[index];
307 if (param->modifiers().fFlags & Modifiers::kIn_Flag) {
308 this->write(" = ");
309 fIgnoreVariableReferenceModifiers = true;
Brian Osman00185012021-02-04 16:07:11 -0500310 this->writeExpression(*arguments[index], Precedence::kAssignment);
John Stiles06b84ef2020-12-09 12:35:48 -0500311 fIgnoreVariableReferenceModifiers = false;
312 }
313
314 this->writeLine(";");
315 }
316
John Stilesf7410bd2021-01-19 13:07:55 -0500317 // [int _skResult = ] myFunction(inputs, outputs, _globals, _var0, _var1, _var2, _var3);
John Stiles06b84ef2020-12-09 12:35:48 -0500318 bool hasResult = (call.type().name() != "void");
319 if (hasResult) {
John Stilesb4418502021-02-04 10:57:08 -0500320 this->writeType(call.type());
John Stiles06b84ef2020-12-09 12:35:48 -0500321 this->write(" _skResult = ");
322 }
323
John Stilese1068342021-03-22 11:57:41 -0400324 this->writeName(function.mangledName());
John Stiles06b84ef2020-12-09 12:35:48 -0500325 this->write("(");
326 separator = "";
327 this->writeFunctionRequirementArgs(function, separator);
328
329 for (int index = 0; index < arguments.count(); ++index) {
330 this->write(separator);
331 separator = ", ";
332
333 this->write("_var");
334 this->write(to_string(index));
335 }
336 this->writeLine(");");
337
338 for (int index = 0; index < outVars.count(); ++index) {
339 if (!outVars[index]) {
340 continue;
341 }
342 // outParam.zyx = _var2;
343 fIgnoreVariableReferenceModifiers = true;
Brian Osman00185012021-02-04 16:07:11 -0500344 this->writeExpression(*arguments[index], Precedence::kAssignment);
John Stiles06b84ef2020-12-09 12:35:48 -0500345 fIgnoreVariableReferenceModifiers = false;
346 this->write(" = _var");
347 this->write(to_string(index));
348 this->writeLine(";");
349 }
350
351 if (hasResult) {
352 this->writeLine("return _skResult;");
353 }
354
355 --fIndentation;
356 this->writeLine("}");
357
358 return name;
John Stilesb21fac22020-12-04 15:36:49 -0500359}
360
John Stilesf64e4072020-12-10 10:34:27 -0500361String MetalCodeGenerator::getBitcastIntrinsic(const Type& outType) {
362 return "as_type<" + outType.displayName() + ">";
363}
364
Ethan Nicholascc305772017-10-13 16:17:45 -0400365void MetalCodeGenerator::writeFunctionCall(const FunctionCall& c) {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400366 const FunctionDeclaration& function = c.function();
John Stiles89ac7c22020-12-30 17:47:31 -0500367 // If this function is a built-in with no declaration, it's probably an intrinsic and might need
368 // special handling.
369 if (function.isBuiltin() && !function.definition()) {
370 auto iter = fIntrinsicMap.find(function.name());
371 if (iter != fIntrinsicMap.end()) {
372 this->writeIntrinsicCall(c, iter->second);
373 return;
374 }
Timothy Liang6403b0e2018-05-17 10:40:04 -0400375 }
John Stilesb21fac22020-12-04 15:36:49 -0500376
John Stilesd7199b22020-12-30 16:22:58 -0500377 // Determine whether or not we need to emulate GLSL's out-param semantics for Metal using a
378 // helper function. (Specifically, out-parameters in GLSL are only written back to the original
379 // variable at the end of the function call; also, swizzles are supported, whereas Metal doesn't
380 // allow a swizzle to be passed to a `floatN&`.)
381 const ExpressionArray& arguments = c.arguments();
John Stilesb21fac22020-12-04 15:36:49 -0500382 const std::vector<const Variable*>& parameters = function.parameters();
383 SkASSERT(arguments.size() == parameters.size());
John Stiles06b84ef2020-12-09 12:35:48 -0500384
385 bool foundOutParam = false;
386 SkSTArray<16, VariableReference*> outVars;
John Stilesf64e4072020-12-10 10:34:27 -0500387 outVars.push_back_n(arguments.count(), (VariableReference*)nullptr);
John Stiles06b84ef2020-12-09 12:35:48 -0500388
389 for (int index = 0; index < arguments.count(); ++index) {
John Stilesb21fac22020-12-04 15:36:49 -0500390 // If this is an out parameter...
391 if (parameters[index]->modifiers().fFlags & Modifiers::kOut_Flag) {
John Stiles06b84ef2020-12-09 12:35:48 -0500392 // Find the expression's inner variable being written to.
John Stilesb21fac22020-12-04 15:36:49 -0500393 Analysis::AssignmentInfo info;
John Stiles06b84ef2020-12-09 12:35:48 -0500394 // Assignability was verified at IRGeneration time, so this should always succeed.
395 SkAssertResult(Analysis::IsAssignable(*arguments[index], &info));
396 outVars[index] = info.fAssignedVar;
397 foundOutParam = true;
John Stilesb21fac22020-12-04 15:36:49 -0500398 }
399 }
400
John Stiles06b84ef2020-12-09 12:35:48 -0500401 if (foundOutParam) {
402 // Out parameters need to be written back to at the end of the function. To do this, we
403 // synthesize a helper function which evaluates the out-param expression into a temporary
404 // variable, calls the original function, then writes the temp var back into the out param
405 // using the original out-param expression. (This lets us support things like swizzles and
406 // array indices.)
John Stilesd7199b22020-12-30 16:22:58 -0500407 this->write(getOutParamHelper(c, arguments, outVars));
408 } else {
John Stilese1068342021-03-22 11:57:41 -0400409 this->write(function.mangledName());
John Stiles06b84ef2020-12-09 12:35:48 -0500410 }
411
Ethan Nicholascc305772017-10-13 16:17:45 -0400412 this->write("(");
413 const char* separator = "";
John Stiles06b84ef2020-12-09 12:35:48 -0500414 this->writeFunctionRequirementArgs(function, separator);
415 for (int i = 0; i < arguments.count(); ++i) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400416 this->write(separator);
417 separator = ", ";
John Stiles06b84ef2020-12-09 12:35:48 -0500418
419 if (outVars[i]) {
Brian Osman00185012021-02-04 16:07:11 -0500420 this->writeExpression(*outVars[i], Precedence::kSequence);
John Stiles06b84ef2020-12-09 12:35:48 -0500421 } else {
Brian Osman00185012021-02-04 16:07:11 -0500422 this->writeExpression(*arguments[i], Precedence::kSequence);
John Stiles06b84ef2020-12-09 12:35:48 -0500423 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400424 }
425 this->write(")");
426}
427
Brian Osman964f0a02020-12-29 10:15:22 -0500428static constexpr char kInverse2x2[] = R"(
429float2x2 float2x2_inverse(float2x2 m) {
430 return float2x2(m[1][1], -m[0][1], -m[1][0], m[0][0]) * (1/determinant(m));
431}
432)";
433
434static constexpr char kInverse3x3[] = R"(
435float3x3 float3x3_inverse(float3x3 m) {
436 float a00 = m[0][0], a01 = m[0][1], a02 = m[0][2];
437 float a10 = m[1][0], a11 = m[1][1], a12 = m[1][2];
438 float a20 = m[2][0], a21 = m[2][1], a22 = m[2][2];
439 float b01 = a22*a11 - a12*a21;
440 float b11 = -a22*a10 + a12*a20;
441 float b21 = a21*a10 - a11*a20;
442 float det = a00*b01 + a01*b11 + a02*b21;
443 return float3x3(b01, (-a22*a01 + a02*a21), ( a12*a01 - a02*a11),
444 b11, ( a22*a00 - a02*a20), (-a12*a00 + a02*a10),
445 b21, (-a21*a00 + a01*a20), ( a11*a00 - a01*a10)) * (1/det);
446}
447)";
448
449static constexpr char kInverse4x4[] = R"(
450float4x4 float4x4_inverse(float4x4 m) {
451 float a00 = m[0][0], a01 = m[0][1], a02 = m[0][2], a03 = m[0][3];
452 float a10 = m[1][0], a11 = m[1][1], a12 = m[1][2], a13 = m[1][3];
453 float a20 = m[2][0], a21 = m[2][1], a22 = m[2][2], a23 = m[2][3];
454 float a30 = m[3][0], a31 = m[3][1], a32 = m[3][2], a33 = m[3][3];
455 float b00 = a00*a11 - a01*a10;
456 float b01 = a00*a12 - a02*a10;
457 float b02 = a00*a13 - a03*a10;
458 float b03 = a01*a12 - a02*a11;
459 float b04 = a01*a13 - a03*a11;
460 float b05 = a02*a13 - a03*a12;
461 float b06 = a20*a31 - a21*a30;
462 float b07 = a20*a32 - a22*a30;
463 float b08 = a20*a33 - a23*a30;
464 float b09 = a21*a32 - a22*a31;
465 float b10 = a21*a33 - a23*a31;
466 float b11 = a22*a33 - a23*a32;
467 float det = b00*b11 - b01*b10 + b02*b09 + b03*b08 - b04*b07 + b05*b06;
468 return float4x4(a11*b11 - a12*b10 + a13*b09,
469 a02*b10 - a01*b11 - a03*b09,
470 a31*b05 - a32*b04 + a33*b03,
471 a22*b04 - a21*b05 - a23*b03,
472 a12*b08 - a10*b11 - a13*b07,
473 a00*b11 - a02*b08 + a03*b07,
474 a32*b02 - a30*b05 - a33*b01,
475 a20*b05 - a22*b02 + a23*b01,
476 a10*b10 - a11*b08 + a13*b06,
477 a01*b08 - a00*b10 - a03*b06,
478 a30*b04 - a31*b02 + a33*b00,
479 a21*b02 - a20*b04 - a23*b00,
480 a11*b07 - a10*b09 - a12*b06,
481 a00*b09 - a01*b07 + a02*b06,
482 a31*b01 - a30*b03 - a32*b00,
483 a20*b03 - a21*b01 + a22*b00) * (1/det);
484}
485)";
486
John Stilesd7199b22020-12-30 16:22:58 -0500487String MetalCodeGenerator::getInversePolyfill(const ExpressionArray& arguments) {
488 // Only use polyfills for a function taking a single-argument square matrix.
489 if (arguments.size() == 1) {
490 const Type& type = arguments.front()->type();
491 if (type.isMatrix() && type.rows() == type.columns()) {
492 // Inject the correct polyfill based on the matrix size.
493 String name = this->typeName(type) + "_inverse";
494 auto [iter, didInsert] = fWrittenIntrinsics.insert(name);
495 if (didInsert) {
496 switch (type.rows()) {
497 case 2:
498 fExtraFunctions.writeText(kInverse2x2);
499 break;
500 case 3:
501 fExtraFunctions.writeText(kInverse3x3);
502 break;
503 case 4:
504 fExtraFunctions.writeText(kInverse4x4);
505 break;
506 }
507 }
508 return name;
Chris Daltondba7aab2018-11-15 10:57:49 -0500509 }
510 }
John Stilesd7199b22020-12-30 16:22:58 -0500511 // This isn't the built-in `inverse`. We don't want to polyfill it at all.
512 return "inverse";
Chris Daltondba7aab2018-11-15 10:57:49 -0500513}
514
Brian Osman93aed9a2020-12-28 15:18:46 -0500515static constexpr char kMatrixCompMult[] = R"(
516template <int C, int R>
517matrix<float, C, R> matrixCompMult(matrix<float, C, R> a, matrix<float, C, R> b) {
518 matrix<float, C, R> result;
519 for (int c = 0; c < C; ++c) {
520 result[c] = a[c] * b[c];
521 }
522 return result;
523}
524)";
525
526void MetalCodeGenerator::writeMatrixCompMult() {
527 String name = "matrixCompMult";
528 if (fWrittenIntrinsics.find(name) == fWrittenIntrinsics.end()) {
529 fWrittenIntrinsics.insert(name);
530 fExtraFunctions.writeText(kMatrixCompMult);
531 }
532}
533
John Stiles86424eb2020-12-11 11:17:14 -0500534String MetalCodeGenerator::getTempVariable(const Type& type) {
535 String tempVar = "_skTemp" + to_string(fVarCount++);
536 this->fFunctionHeader += " " + this->typeName(type) + " " + tempVar + ";\n";
537 return tempVar;
538}
539
John Stiles791c27d2020-12-30 14:56:57 -0500540void MetalCodeGenerator::writeSimpleIntrinsic(const FunctionCall& c) {
541 // Write out an intrinsic function call exactly as-is. No muss no fuss.
542 this->write(c.function().name());
John Stilesd7199b22020-12-30 16:22:58 -0500543 this->writeArgumentList(c.arguments());
544}
545
546void MetalCodeGenerator::writeArgumentList(const ExpressionArray& arguments) {
John Stiles791c27d2020-12-30 14:56:57 -0500547 this->write("(");
548 const char* separator = "";
John Stilesd7199b22020-12-30 16:22:58 -0500549 for (const std::unique_ptr<Expression>& arg : arguments) {
John Stiles791c27d2020-12-30 14:56:57 -0500550 this->write(separator);
551 separator = ", ";
Brian Osman00185012021-02-04 16:07:11 -0500552 this->writeExpression(*arg, Precedence::kSequence);
John Stiles791c27d2020-12-30 14:56:57 -0500553 }
554 this->write(")");
555}
556
John Stilesd7199b22020-12-30 16:22:58 -0500557void MetalCodeGenerator::writeIntrinsicCall(const FunctionCall& c, IntrinsicKind kind) {
John Stiles8e3b6be2020-10-13 11:14:08 -0400558 const ExpressionArray& arguments = c.arguments();
Timothy Liang6403b0e2018-05-17 10:40:04 -0400559 switch (kind) {
John Stilesd7199b22020-12-30 16:22:58 -0500560 case kTexture_IntrinsicKind: {
Brian Osman00185012021-02-04 16:07:11 -0500561 this->writeExpression(*arguments[0], Precedence::kSequence);
Timothy Lianga06f2152018-05-24 15:33:31 -0400562 this->write(".sample(");
Brian Osman00185012021-02-04 16:07:11 -0500563 this->writeExpression(*arguments[0], Precedence::kSequence);
Timothy Lianga06f2152018-05-24 15:33:31 -0400564 this->write(SAMPLER_SUFFIX);
565 this->write(", ");
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400566 const Type& arg1Type = arguments[1]->type();
John Stilesb14a8192021-04-05 11:40:46 -0400567 if (arg1Type.columns() == 3) {
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500568 // have to store the vector in a temp variable to avoid double evaluating it
John Stiles86424eb2020-12-11 11:17:14 -0500569 String tmpVar = this->getTempVariable(arg1Type);
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500570 this->write("(" + tmpVar + " = ");
Brian Osman00185012021-02-04 16:07:11 -0500571 this->writeExpression(*arguments[1], Precedence::kSequence);
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500572 this->write(", " + tmpVar + ".xy / " + tmpVar + ".z))");
Timothy Liangee84fe12018-05-18 14:38:19 -0400573 } else {
John Stilesb14a8192021-04-05 11:40:46 -0400574 SkASSERT(arg1Type.columns() == 2);
Brian Osman00185012021-02-04 16:07:11 -0500575 this->writeExpression(*arguments[1], Precedence::kSequence);
Timothy Liangee84fe12018-05-18 14:38:19 -0400576 this->write(")");
577 }
Timothy Liang6403b0e2018-05-17 10:40:04 -0400578 break;
Ethan Nicholas30d30222020-09-11 12:27:26 -0400579 }
John Stilesd7199b22020-12-30 16:22:58 -0500580 case kMod_IntrinsicKind: {
Timothy Liang651286f2018-06-07 09:55:33 -0400581 // 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 -0500582 String tmpX = this->getTempVariable(arguments[0]->type());
John Stiles61b2e812020-12-30 18:27:31 -0500583 String tmpY = this->getTempVariable(arguments[1]->type());
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500584 this->write("(" + tmpX + " = ");
Brian Osman00185012021-02-04 16:07:11 -0500585 this->writeExpression(*arguments[0], Precedence::kSequence);
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500586 this->write(", " + tmpY + " = ");
Brian Osman00185012021-02-04 16:07:11 -0500587 this->writeExpression(*arguments[1], Precedence::kSequence);
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500588 this->write(", " + tmpX + " - " + tmpY + " * floor(" + tmpX + " / " + tmpY + "))");
Timothy Liang651286f2018-06-07 09:55:33 -0400589 break;
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500590 }
Brian Osman46787d52020-11-24 14:18:23 -0500591 // GLSL declares scalar versions of most geometric intrinsics, but these don't exist in MSL
John Stilesd7199b22020-12-30 16:22:58 -0500592 case kDistance_IntrinsicKind: {
Brian Osman46787d52020-11-24 14:18:23 -0500593 if (arguments[0]->type().columns() == 1) {
594 this->write("abs(");
Brian Osman00185012021-02-04 16:07:11 -0500595 this->writeExpression(*arguments[0], Precedence::kAdditive);
Brian Osman46787d52020-11-24 14:18:23 -0500596 this->write(" - ");
Brian Osman00185012021-02-04 16:07:11 -0500597 this->writeExpression(*arguments[1], Precedence::kAdditive);
Brian Osman46787d52020-11-24 14:18:23 -0500598 this->write(")");
599 } else {
John Stiles791c27d2020-12-30 14:56:57 -0500600 this->writeSimpleIntrinsic(c);
Brian Osman46787d52020-11-24 14:18:23 -0500601 }
602 break;
603 }
John Stilesd7199b22020-12-30 16:22:58 -0500604 case kDot_IntrinsicKind: {
Brian Osman46787d52020-11-24 14:18:23 -0500605 if (arguments[0]->type().columns() == 1) {
606 this->write("(");
Brian Osman00185012021-02-04 16:07:11 -0500607 this->writeExpression(*arguments[0], Precedence::kMultiplicative);
Brian Osman46787d52020-11-24 14:18:23 -0500608 this->write(" * ");
Brian Osman00185012021-02-04 16:07:11 -0500609 this->writeExpression(*arguments[1], Precedence::kMultiplicative);
Brian Osman46787d52020-11-24 14:18:23 -0500610 this->write(")");
611 } else {
John Stiles791c27d2020-12-30 14:56:57 -0500612 this->writeSimpleIntrinsic(c);
Brian Osman46787d52020-11-24 14:18:23 -0500613 }
614 break;
615 }
John Stilesd7199b22020-12-30 16:22:58 -0500616 case kFaceforward_IntrinsicKind: {
John Stilesad0571f2020-12-10 18:03:10 -0500617 if (arguments[0]->type().columns() == 1) {
618 // ((((Nref) * (I) < 0) ? 1 : -1) * (N))
619 this->write("((((");
Brian Osman00185012021-02-04 16:07:11 -0500620 this->writeExpression(*arguments[2], Precedence::kSequence);
John Stilesad0571f2020-12-10 18:03:10 -0500621 this->write(") * (");
Brian Osman00185012021-02-04 16:07:11 -0500622 this->writeExpression(*arguments[1], Precedence::kSequence);
John Stilesad0571f2020-12-10 18:03:10 -0500623 this->write(") < 0) ? 1 : -1) * (");
Brian Osman00185012021-02-04 16:07:11 -0500624 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stilesad0571f2020-12-10 18:03:10 -0500625 this->write("))");
626 } else {
John Stiles791c27d2020-12-30 14:56:57 -0500627 this->writeSimpleIntrinsic(c);
John Stilesad0571f2020-12-10 18:03:10 -0500628 }
629 break;
630 }
John Stilesd7199b22020-12-30 16:22:58 -0500631 case kLength_IntrinsicKind: {
Brian Osman46787d52020-11-24 14:18:23 -0500632 this->write(arguments[0]->type().columns() == 1 ? "abs(" : "length(");
Brian Osman00185012021-02-04 16:07:11 -0500633 this->writeExpression(*arguments[0], Precedence::kSequence);
Brian Osman46787d52020-11-24 14:18:23 -0500634 this->write(")");
635 break;
636 }
John Stilesd7199b22020-12-30 16:22:58 -0500637 case kNormalize_IntrinsicKind: {
Brian Osman46787d52020-11-24 14:18:23 -0500638 this->write(arguments[0]->type().columns() == 1 ? "sign(" : "normalize(");
Brian Osman00185012021-02-04 16:07:11 -0500639 this->writeExpression(*arguments[0], Precedence::kSequence);
Brian Osman46787d52020-11-24 14:18:23 -0500640 this->write(")");
641 break;
642 }
John Stilesd7199b22020-12-30 16:22:58 -0500643 case kBitcast_IntrinsicKind: {
John Stiles0063a9f2020-12-10 18:01:45 -0500644 this->write(this->getBitcastIntrinsic(c.type()));
645 this->write("(");
Brian Osman00185012021-02-04 16:07:11 -0500646 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stiles0063a9f2020-12-10 18:01:45 -0500647 this->write(")");
648 break;
649 }
John Stilesd7199b22020-12-30 16:22:58 -0500650 case kDegrees_IntrinsicKind: {
John Stilese2d34f82020-12-10 18:02:02 -0500651 this->write("((");
Brian Osman00185012021-02-04 16:07:11 -0500652 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stilese2d34f82020-12-10 18:02:02 -0500653 this->write(") * 57.2957795)");
654 break;
655 }
John Stilesd7199b22020-12-30 16:22:58 -0500656 case kRadians_IntrinsicKind: {
John Stilese2d34f82020-12-10 18:02:02 -0500657 this->write("((");
Brian Osman00185012021-02-04 16:07:11 -0500658 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stilese2d34f82020-12-10 18:02:02 -0500659 this->write(") * 0.0174532925)");
660 break;
661 }
John Stilesd7199b22020-12-30 16:22:58 -0500662 case kDFdx_IntrinsicKind: {
663 this->write("dfdx");
664 this->writeArgumentList(c.arguments());
665 break;
666 }
667 case kDFdy_IntrinsicKind: {
668 // Flipping Y also negates the Y derivatives.
John Stiles270cec22021-02-17 12:59:36 -0500669 if (fProgram.fConfig->fSettings.fFlipY) {
John Stilesd7199b22020-12-30 16:22:58 -0500670 this->write("-");
671 }
672 this->write("dfdy");
673 this->writeArgumentList(c.arguments());
674 break;
675 }
676 case kInverse_IntrinsicKind: {
677 this->write(this->getInversePolyfill(arguments));
678 this->writeArgumentList(c.arguments());
679 break;
680 }
681 case kInversesqrt_IntrinsicKind: {
682 this->write("rsqrt");
683 this->writeArgumentList(c.arguments());
684 break;
685 }
686 case kAtan_IntrinsicKind: {
687 this->write(c.arguments().size() == 2 ? "atan2" : "atan");
688 this->writeArgumentList(c.arguments());
689 break;
690 }
691 case kReflect_IntrinsicKind: {
John Stiles791c27d2020-12-30 14:56:57 -0500692 if (arguments[0]->type().columns() == 1) {
693 // We need to synthesize `I - 2 * N * I * N`.
694 String tmpI = this->getTempVariable(arguments[0]->type());
695 String tmpN = this->getTempVariable(arguments[1]->type());
696
697 // (_skTempI = ...
698 this->write("(" + tmpI + " = ");
Brian Osman00185012021-02-04 16:07:11 -0500699 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stiles791c27d2020-12-30 14:56:57 -0500700
701 // , _skTempN = ...
702 this->write(", " + tmpN + " = ");
Brian Osman00185012021-02-04 16:07:11 -0500703 this->writeExpression(*arguments[1], Precedence::kSequence);
John Stiles791c27d2020-12-30 14:56:57 -0500704
705 // , _skTempI - 2 * _skTempN * _skTempI * _skTempN)
706 this->write(", " + tmpI + " - 2 * " + tmpN + " * " + tmpI + " * " + tmpN + ")");
707 } else {
708 this->writeSimpleIntrinsic(c);
709 }
710 break;
711 }
John Stilesd7199b22020-12-30 16:22:58 -0500712 case kRefract_IntrinsicKind: {
John Stiles4b783d62020-12-30 14:58:07 -0500713 if (arguments[0]->type().columns() == 1) {
714 // Metal does implement refract for vectors; rather than reimplementing refract from
715 // scratch, we can replace the call with `refract(float2(I,0), float2(N,0), eta).x`.
716 this->write("(refract(float2(");
Brian Osman00185012021-02-04 16:07:11 -0500717 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stiles4b783d62020-12-30 14:58:07 -0500718 this->write(", 0), float2(");
Brian Osman00185012021-02-04 16:07:11 -0500719 this->writeExpression(*arguments[1], Precedence::kSequence);
John Stiles4b783d62020-12-30 14:58:07 -0500720 this->write(", 0), ");
Brian Osman00185012021-02-04 16:07:11 -0500721 this->writeExpression(*arguments[2], Precedence::kSequence);
John Stiles4b783d62020-12-30 14:58:07 -0500722 this->write(").x)");
723 } else {
724 this->writeSimpleIntrinsic(c);
725 }
726 break;
727 }
John Stiles23456532020-12-30 18:12:48 -0500728 case kRoundEven_IntrinsicKind: {
729 this->write("rint");
730 this->writeArgumentList(c.arguments());
731 break;
732 }
John Stilesd7199b22020-12-30 16:22:58 -0500733 case kBitCount_IntrinsicKind: {
John Stilese7dc7cb2020-12-22 15:37:14 -0500734 this->write("popcount(");
Brian Osman00185012021-02-04 16:07:11 -0500735 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stilese7dc7cb2020-12-22 15:37:14 -0500736 this->write(")");
737 break;
738 }
John Stilesd7199b22020-12-30 16:22:58 -0500739 case kFindLSB_IntrinsicKind: {
John Stiles86424eb2020-12-11 11:17:14 -0500740 // Create a temp variable to store the expression, to avoid double-evaluating it.
741 String skTemp = this->getTempVariable(arguments[0]->type());
742 String exprType = this->typeName(arguments[0]->type());
743
744 // ctz returns numbits(type) on zero inputs; GLSL documents it as generating -1 instead.
745 // Use select to detect zero inputs and force a -1 result.
746
747 // (_skTemp1 = (.....), select(ctz(_skTemp1), int4(-1), _skTemp1 == int4(0)))
748 this->write("(");
749 this->write(skTemp);
750 this->write(" = (");
Brian Osman00185012021-02-04 16:07:11 -0500751 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stiles86424eb2020-12-11 11:17:14 -0500752 this->write("), select(ctz(");
753 this->write(skTemp);
754 this->write("), ");
755 this->write(exprType);
756 this->write("(-1), ");
757 this->write(skTemp);
758 this->write(" == ");
759 this->write(exprType);
760 this->write("(0)))");
761 break;
762 }
John Stilesd7199b22020-12-30 16:22:58 -0500763 case kFindMSB_IntrinsicKind: {
John Stiles9685e522020-12-14 11:52:14 -0500764 // Create a temp variable to store the expression, to avoid double-evaluating it.
765 String skTemp1 = this->getTempVariable(arguments[0]->type());
766 String exprType = this->typeName(arguments[0]->type());
767
768 // GLSL findMSB is actually quite different from Metal's clz:
769 // - For signed negative numbers, it returns the first zero bit, not the first one bit!
770 // - For an empty input (0/~0 depending on sign), findMSB gives -1; clz is numbits(type)
771
772 // (_skTemp1 = (.....),
773 this->write("(");
774 this->write(skTemp1);
775 this->write(" = (");
Brian Osman00185012021-02-04 16:07:11 -0500776 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stiles9685e522020-12-14 11:52:14 -0500777 this->write("), ");
778
779 // Signed input types might be negative; we need another helper variable to negate the
780 // input (since we can only find one bits, not zero bits).
781 String skTemp2;
782 if (arguments[0]->type().isSigned()) {
783 // ... _skTemp2 = (select(_skTemp1, ~_skTemp1, _skTemp1 < 0)),
784 skTemp2 = this->getTempVariable(arguments[0]->type());
785 this->write(skTemp2);
786 this->write(" = (select(");
787 this->write(skTemp1);
788 this->write(", ~");
789 this->write(skTemp1);
790 this->write(", ");
791 this->write(skTemp1);
792 this->write(" < 0)), ");
793 } else {
794 skTemp2 = skTemp1;
795 }
796
797 // ... select(int4(clz(_skTemp2)), int4(-1), _skTemp2 == int4(0)))
798 this->write("select(");
799 this->write(this->typeName(c.type()));
800 this->write("(clz(");
801 this->write(skTemp2);
802 this->write(")), ");
803 this->write(this->typeName(c.type()));
804 this->write("(-1), ");
805 this->write(skTemp2);
806 this->write(" == ");
807 this->write(exprType);
808 this->write("(0)))");
809 break;
810 }
John Stilesd7199b22020-12-30 16:22:58 -0500811 case kMatrixCompMult_IntrinsicKind: {
812 this->writeMatrixCompMult();
813 this->writeSimpleIntrinsic(c);
814 break;
815 }
816 case kCompareEqual_IntrinsicKind:
817 case kCompareGreaterThan_IntrinsicKind:
818 case kCompareGreaterThanEqual_IntrinsicKind:
819 case kCompareLessThan_IntrinsicKind:
820 case kCompareLessThanEqual_IntrinsicKind:
821 case kCompareNotEqual_IntrinsicKind: {
822 this->write("(");
Brian Osman00185012021-02-04 16:07:11 -0500823 this->writeExpression(*c.arguments()[0], Precedence::kRelational);
John Stilesd7199b22020-12-30 16:22:58 -0500824 switch (kind) {
825 case kCompareEqual_IntrinsicKind:
826 this->write(" == ");
827 break;
828 case kCompareNotEqual_IntrinsicKind:
829 this->write(" != ");
830 break;
831 case kCompareLessThan_IntrinsicKind:
832 this->write(" < ");
833 break;
834 case kCompareLessThanEqual_IntrinsicKind:
835 this->write(" <= ");
836 break;
837 case kCompareGreaterThan_IntrinsicKind:
838 this->write(" > ");
839 break;
840 case kCompareGreaterThanEqual_IntrinsicKind:
841 this->write(" >= ");
842 break;
843 default:
John Stilesf57207b2021-02-02 17:50:34 -0500844 SK_ABORT("unsupported comparison intrinsic kind");
John Stilesd7199b22020-12-30 16:22:58 -0500845 }
Brian Osman00185012021-02-04 16:07:11 -0500846 this->writeExpression(*c.arguments()[1], Precedence::kRelational);
John Stilesd7199b22020-12-30 16:22:58 -0500847 this->write(")");
848 break;
849 }
Timothy Liang6403b0e2018-05-17 10:40:04 -0400850 default:
John Stilesf57207b2021-02-02 17:50:34 -0500851 SK_ABORT("unsupported intrinsic kind");
Timothy Liang6403b0e2018-05-17 10:40:04 -0400852 }
853}
854
John Stilesfcf8cb22020-08-06 14:29:22 -0400855// Assembles a matrix of type floatRxC by resizing another matrix named `x0`.
856// Cells that don't exist in the source matrix will be populated with identity-matrix values.
857void MetalCodeGenerator::assembleMatrixFromMatrix(const Type& sourceMatrix, int rows, int columns) {
858 SkASSERT(rows <= 4);
859 SkASSERT(columns <= 4);
860
861 const char* columnSeparator = "";
862 for (int c = 0; c < columns; ++c) {
863 fExtraFunctions.printf("%sfloat%d(", columnSeparator, rows);
864 columnSeparator = "), ";
865
866 // Determine how many values to take from the source matrix for this row.
867 int swizzleLength = 0;
868 if (c < sourceMatrix.columns()) {
869 swizzleLength = std::min<>(rows, sourceMatrix.rows());
870 }
871
872 // Emit all the values from the source matrix row.
873 bool firstItem;
874 switch (swizzleLength) {
875 case 0: firstItem = true; break;
876 case 1: firstItem = false; fExtraFunctions.printf("x0[%d].x", c); break;
877 case 2: firstItem = false; fExtraFunctions.printf("x0[%d].xy", c); break;
878 case 3: firstItem = false; fExtraFunctions.printf("x0[%d].xyz", c); break;
879 case 4: firstItem = false; fExtraFunctions.printf("x0[%d].xyzw", c); break;
880 default: SkUNREACHABLE;
881 }
882
883 // Emit the placeholder identity-matrix cells.
884 for (int r = swizzleLength; r < rows; ++r) {
885 fExtraFunctions.printf("%s%s", firstItem ? "" : ", ", (r == c) ? "1.0" : "0.0");
886 firstItem = false;
887 }
888 }
889
890 fExtraFunctions.writeText(")");
891}
892
893// Assembles a matrix of type floatRxC by concatenating an arbitrary mix of values, named `x0`,
894// `x1`, etc. An error is written if the expression list don't contain exactly R*C scalars.
John Stiles5abb9e12021-04-06 13:47:19 -0400895void MetalCodeGenerator::assembleMatrixFromExpressions(const AnyConstructor& ctor,
John Stiles8e3b6be2020-10-13 11:14:08 -0400896 int rows, int columns) {
John Stilesfcf8cb22020-08-06 14:29:22 -0400897 size_t argIndex = 0;
898 int argPosition = 0;
John Stiles5abb9e12021-04-06 13:47:19 -0400899 auto args = ctor.argumentSpan();
John Stilesfcf8cb22020-08-06 14:29:22 -0400900
901 const char* columnSeparator = "";
902 for (int c = 0; c < columns; ++c) {
903 fExtraFunctions.printf("%sfloat%d(", columnSeparator, rows);
904 columnSeparator = "), ";
905
906 const char* rowSeparator = "";
907 for (int r = 0; r < rows; ++r) {
908 fExtraFunctions.writeText(rowSeparator);
909 rowSeparator = ", ";
910
911 if (argIndex < args.size()) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400912 const Type& argType = args[argIndex]->type();
Ethan Nicholase6592142020-09-08 10:22:09 -0400913 switch (argType.typeKind()) {
914 case Type::TypeKind::kScalar: {
John Stilesfcf8cb22020-08-06 14:29:22 -0400915 fExtraFunctions.printf("x%zu", argIndex);
916 break;
917 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400918 case Type::TypeKind::kVector: {
John Stilesfcf8cb22020-08-06 14:29:22 -0400919 fExtraFunctions.printf("x%zu[%d]", argIndex, argPosition);
920 break;
921 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400922 case Type::TypeKind::kMatrix: {
John Stilesfcf8cb22020-08-06 14:29:22 -0400923 fExtraFunctions.printf("x%zu[%d][%d]", argIndex,
924 argPosition / argType.rows(),
925 argPosition % argType.rows());
926 break;
927 }
928 default: {
929 SkDEBUGFAIL("incorrect type of argument for matrix constructor");
930 fExtraFunctions.writeText("<error>");
931 break;
932 }
933 }
934
935 ++argPosition;
936 if (argPosition >= argType.columns() * argType.rows()) {
937 ++argIndex;
938 argPosition = 0;
939 }
940 } else {
941 SkDEBUGFAIL("not enough arguments for matrix constructor");
942 fExtraFunctions.writeText("<error>");
943 }
944 }
945 }
946
947 if (argPosition != 0 || argIndex != args.size()) {
948 SkDEBUGFAIL("incorrect number of arguments for matrix constructor");
949 fExtraFunctions.writeText(", <error>");
950 }
951
952 fExtraFunctions.writeText(")");
953}
954
John Stiles1bdafbf2020-05-28 12:17:20 -0400955// Generates a constructor for 'matrix' which reorganizes the input arguments into the proper shape.
956// Keeps track of previously generated constructors so that we won't generate more than one
957// constructor for any given permutation of input argument types. Returns the name of the
958// generated constructor method.
John Stiles5abb9e12021-04-06 13:47:19 -0400959String MetalCodeGenerator::getMatrixConstructHelper(const AnyConstructor& c) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400960 const Type& matrix = c.type();
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500961 int columns = matrix.columns();
962 int rows = matrix.rows();
John Stiles5abb9e12021-04-06 13:47:19 -0400963 auto args = c.argumentSpan();
John Stiles1bdafbf2020-05-28 12:17:20 -0400964
965 // Create the helper-method name and use it as our lookup key.
966 String name;
967 name.appendf("float%dx%d_from", columns, rows);
968 for (const std::unique_ptr<Expression>& expr : args) {
John Stiles36129132020-12-29 12:28:04 -0500969 name.appendf("_%s", this->typeName(expr->type()).c_str());
John Stiles1bdafbf2020-05-28 12:17:20 -0400970 }
971
972 // If a helper-method has already been synthesized, we don't need to synthesize it again.
973 auto [iter, newlyCreated] = fHelpers.insert(name);
974 if (!newlyCreated) {
975 return name;
976 }
977
978 // Unlike GLSL, Metal requires that matrices are initialized with exactly R vectors of C
979 // components apiece. (In Metal 2.0, you can also supply R*C scalars, but you still cannot
980 // supply a mixture of scalars and vectors.)
981 fExtraFunctions.printf("float%dx%d %s(", columns, rows, name.c_str());
982
983 size_t argIndex = 0;
984 const char* argSeparator = "";
John Stilesfcf8cb22020-08-06 14:29:22 -0400985 for (const std::unique_ptr<Expression>& expr : args) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400986 fExtraFunctions.printf("%s%s x%zu", argSeparator,
John Stiles36129132020-12-29 12:28:04 -0500987 this->typeName(expr->type()).c_str(), argIndex++);
John Stiles1bdafbf2020-05-28 12:17:20 -0400988 argSeparator = ", ";
989 }
990
991 fExtraFunctions.printf(") {\n return float%dx%d(", columns, rows);
992
John Stiles9aeed132020-11-24 17:36:06 -0500993 if (args.size() == 1 && args.front()->type().isMatrix()) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400994 this->assembleMatrixFromMatrix(args.front()->type(), rows, columns);
John Stilesfcf8cb22020-08-06 14:29:22 -0400995 } else {
John Stiles5abb9e12021-04-06 13:47:19 -0400996 this->assembleMatrixFromExpressions(c, rows, columns);
John Stiles1bdafbf2020-05-28 12:17:20 -0400997 }
998
John Stilesfcf8cb22020-08-06 14:29:22 -0400999 fExtraFunctions.writeText(");\n}\n");
Ethan Nicholas842d31b2019-01-22 10:59:11 -05001000 return name;
1001}
1002
1003bool MetalCodeGenerator::canCoerce(const Type& t1, const Type& t2) {
1004 if (t1.columns() != t2.columns() || t1.rows() != t2.rows()) {
1005 return false;
1006 }
1007 if (t1.columns() > 1) {
1008 return this->canCoerce(t1.componentType(), t2.componentType());
1009 }
Ethan Nicholase1f55022019-02-05 17:17:40 -05001010 return t1.isFloat() && t2.isFloat();
Ethan Nicholas842d31b2019-01-22 10:59:11 -05001011}
1012
John Stiles1bdafbf2020-05-28 12:17:20 -04001013bool MetalCodeGenerator::matrixConstructHelperIsNeeded(const Constructor& c) {
1014 // A matrix construct helper is only necessary if we are, in fact, constructing a matrix.
John Stiles9aeed132020-11-24 17:36:06 -05001015 if (!c.type().isMatrix()) {
John Stiles1bdafbf2020-05-28 12:17:20 -04001016 return false;
Ethan Nicholas842d31b2019-01-22 10:59:11 -05001017 }
John Stiles1bdafbf2020-05-28 12:17:20 -04001018
1019 // GLSL is fairly free-form about inputs to its matrix constructors, but Metal is not; it
1020 // expects exactly R vectors of C components apiece. (Metal 2.0 also allows a list of R*C
1021 // scalars.) Some cases are simple to translate and so we handle those inline--e.g. a list of
1022 // scalars can be constructed trivially. In more complex cases, we generate a helper function
1023 // that converts our inputs into a properly-shaped matrix.
1024 // A matrix construct helper method is always used if any input argument is a matrix.
1025 // Helper methods are also necessary when any argument would span multiple rows. For instance:
1026 //
1027 // float2 x = (1, 2);
1028 // float3x2(x, 3, 4, 5, 6) = | 1 3 5 | = no helper needed; conversion can be done inline
1029 // | 2 4 6 |
1030 //
1031 // float2 x = (2, 3);
1032 // float3x2(1, x, 4, 5, 6) = | 1 3 5 | = x spans multiple rows; a helper method will be used
1033 // | 2 4 6 |
1034 //
1035 // float4 x = (1, 2, 3, 4);
1036 // float2x2(x) = | 1 3 | = x spans multiple rows; a helper method will be used
1037 // | 2 4 |
1038 //
1039
1040 int position = 0;
Ethan Nicholasf70f0442020-09-29 12:41:35 -04001041 for (const std::unique_ptr<Expression>& expr : c.arguments()) {
John Stiles1bdafbf2020-05-28 12:17:20 -04001042 // If an input argument is a matrix, we need a helper function.
John Stiles9aeed132020-11-24 17:36:06 -05001043 if (expr->type().isMatrix()) {
John Stiles1bdafbf2020-05-28 12:17:20 -04001044 return true;
1045 }
Ethan Nicholas30d30222020-09-11 12:27:26 -04001046 position += expr->type().columns();
1047 if (position > c.type().rows()) {
John Stiles1bdafbf2020-05-28 12:17:20 -04001048 // An input argument would span multiple rows; a helper function is required.
1049 return true;
1050 }
Ethan Nicholas30d30222020-09-11 12:27:26 -04001051 if (position == c.type().rows()) {
John Stiles1bdafbf2020-05-28 12:17:20 -04001052 // We've advanced to the end of a row. Wrap to the start of the next row.
1053 position = 0;
1054 }
1055 }
1056
1057 return false;
1058}
1059
John Stiles5abb9e12021-04-06 13:47:19 -04001060void MetalCodeGenerator::writeConstructorMatrixResize(const ConstructorMatrixResize& c,
1061 Precedence parentPrecedence) {
1062 // Matrix-resize via casting doesn't natively exist in Metal at all, so we always need to use a
1063 // matrix-construct helper here.
1064 this->write(this->getMatrixConstructHelper(c));
1065 this->write("(");
1066 this->writeExpression(*c.argument(), Precedence::kSequence);
1067 this->write(")");
1068}
1069
John Stiles1bdafbf2020-05-28 12:17:20 -04001070void MetalCodeGenerator::writeConstructor(const Constructor& c, Precedence parentPrecedence) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001071 const Type& constructorType = c.type();
John Stiles7384b372021-04-01 13:48:15 -04001072 SkASSERT(!constructorType.isArray());
1073
John Stiles1bdafbf2020-05-28 12:17:20 -04001074 // Emit and invoke a matrix-constructor helper method if one is necessary.
1075 if (this->matrixConstructHelperIsNeeded(c)) {
1076 this->write(this->getMatrixConstructHelper(c));
John Stiles1fa15b12020-05-28 17:36:54 +00001077 this->write("(");
1078 const char* separator = "";
Ethan Nicholasf70f0442020-09-29 12:41:35 -04001079 for (const std::unique_ptr<Expression>& expr : c.arguments()) {
John Stiles1fa15b12020-05-28 17:36:54 +00001080 this->write(separator);
1081 separator = ", ";
Brian Osman00185012021-02-04 16:07:11 -05001082 this->writeExpression(*expr, Precedence::kSequence);
John Stilesdaa573e2020-05-28 12:17:20 -04001083 }
John Stiles1fa15b12020-05-28 17:36:54 +00001084 this->write(")");
John Stiles1bdafbf2020-05-28 12:17:20 -04001085 return;
John Stilesdaa573e2020-05-28 12:17:20 -04001086 }
John Stiles1bdafbf2020-05-28 12:17:20 -04001087
1088 // Explicitly invoke the constructor, passing in the necessary arguments.
John Stilesb4418502021-02-04 10:57:08 -05001089 this->writeType(constructorType);
John Stiles7384b372021-04-01 13:48:15 -04001090 this->write("(");
John Stiles1bdafbf2020-05-28 12:17:20 -04001091 const char* separator = "";
1092 int scalarCount = 0;
Ethan Nicholasf70f0442020-09-29 12:41:35 -04001093 for (const std::unique_ptr<Expression>& arg : c.arguments()) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001094 const Type& argType = arg->type();
John Stiles1bdafbf2020-05-28 12:17:20 -04001095 this->write(separator);
1096 separator = ", ";
John Stiles9aeed132020-11-24 17:36:06 -05001097 if (constructorType.isMatrix() &&
Ethan Nicholas30d30222020-09-11 12:27:26 -04001098 argType.columns() < constructorType.rows()) {
John Stiles1bdafbf2020-05-28 12:17:20 -04001099 // Merge scalars and smaller vectors together.
1100 if (!scalarCount) {
John Stilesb4418502021-02-04 10:57:08 -05001101 this->writeType(constructorType.componentType());
Ethan Nicholas30d30222020-09-11 12:27:26 -04001102 this->write(to_string(constructorType.rows()));
John Stiles1bdafbf2020-05-28 12:17:20 -04001103 this->write("(");
1104 }
Ethan Nicholas30d30222020-09-11 12:27:26 -04001105 scalarCount += argType.columns();
John Stiles1bdafbf2020-05-28 12:17:20 -04001106 }
Brian Osman00185012021-02-04 16:07:11 -05001107 this->writeExpression(*arg, Precedence::kSequence);
Ethan Nicholas30d30222020-09-11 12:27:26 -04001108 if (scalarCount && scalarCount == constructorType.rows()) {
John Stiles1bdafbf2020-05-28 12:17:20 -04001109 this->write(")");
1110 scalarCount = 0;
1111 }
1112 }
John Stiles7384b372021-04-01 13:48:15 -04001113 this->write(")");
Ethan Nicholascc305772017-10-13 16:17:45 -04001114}
1115
John Stilesb14a8192021-04-05 11:40:46 -04001116void MetalCodeGenerator::writeAnyConstructor(const AnyConstructor& c,
1117 const char* leftBracket,
1118 const char* rightBracket,
1119 Precedence parentPrecedence) {
John Stilese1182782021-03-30 22:09:37 -04001120 this->writeType(c.type());
John Stilesb14a8192021-04-05 11:40:46 -04001121 this->write(leftBracket);
John Stiles7384b372021-04-01 13:48:15 -04001122 const char* separator = "";
John Stilesb14a8192021-04-05 11:40:46 -04001123 for (const std::unique_ptr<Expression>& arg : c.argumentSpan()) {
John Stiles7384b372021-04-01 13:48:15 -04001124 this->write(separator);
1125 separator = ", ";
1126 this->writeExpression(*arg, Precedence::kSequence);
1127 }
John Stilesb14a8192021-04-05 11:40:46 -04001128 this->write(rightBracket);
John Stiles7384b372021-04-01 13:48:15 -04001129}
1130
John Stilesb14a8192021-04-05 11:40:46 -04001131void MetalCodeGenerator::writeCastConstructor(const AnyConstructor& c,
1132 const char* leftBracket,
1133 const char* rightBracket,
1134 Precedence parentPrecedence) {
1135 // If the type is coercible, emit it directly without the cast.
1136 auto args = c.argumentSpan();
1137 if (args.size() == 1) {
1138 if (this->canCoerce(c.type(), args.front()->type())) {
1139 this->writeExpression(*args.front(), parentPrecedence);
1140 return;
1141 }
John Stilesfd7252f2021-04-04 22:24:40 -04001142 }
1143
John Stilesb14a8192021-04-05 11:40:46 -04001144 return this->writeAnyConstructor(c, leftBracket, rightBracket, parentPrecedence);
John Stilesfd7252f2021-04-04 22:24:40 -04001145}
1146
Ethan Nicholascc305772017-10-13 16:17:45 -04001147void MetalCodeGenerator::writeFragCoord() {
Ethan Nicholasf931e402019-07-26 15:40:33 -04001148 if (fRTHeightName.length()) {
1149 this->write("float4(_fragCoord.x, ");
1150 this->write(fRTHeightName.c_str());
1151 this->write(" - _fragCoord.y, 0.0, _fragCoord.w)");
Jim Van Verth6bc650e2019-02-07 14:53:23 -05001152 } else {
1153 this->write("float4(_fragCoord.x, _fragCoord.y, 0.0, _fragCoord.w)");
1154 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001155}
1156
1157void MetalCodeGenerator::writeVariableReference(const VariableReference& ref) {
John Stiles06b84ef2020-12-09 12:35:48 -05001158 // When assembling out-param helper functions, we copy variables into local clones with matching
John Stilesf7410bd2021-01-19 13:07:55 -05001159 // names. We never want to prepend "_in." or "_globals." when writing these variables since
John Stiles06b84ef2020-12-09 12:35:48 -05001160 // we're actually targeting the clones.
1161 if (fIgnoreVariableReferenceModifiers) {
1162 this->writeName(ref.variable()->name());
1163 return;
1164 }
1165
Ethan Nicholas78686922020-10-08 06:46:27 -04001166 switch (ref.variable()->modifiers().fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001167 case SK_FRAGCOLOR_BUILTIN:
John Stilesf7410bd2021-01-19 13:07:55 -05001168 this->write("_out.sk_FragColor");
Ethan Nicholascc305772017-10-13 16:17:45 -04001169 break;
Timothy Liang6403b0e2018-05-17 10:40:04 -04001170 case SK_FRAGCOORD_BUILTIN:
1171 this->writeFragCoord();
1172 break;
Timothy Liangdc89f192018-06-13 09:20:31 -04001173 case SK_VERTEXID_BUILTIN:
1174 this->write("sk_VertexID");
1175 break;
1176 case SK_INSTANCEID_BUILTIN:
1177 this->write("sk_InstanceID");
1178 break;
Timothy Liang7b8875d2018-08-10 09:42:31 -04001179 case SK_CLOCKWISE_BUILTIN:
1180 // We'd set the front facing winding in the MTLRenderCommandEncoder to be counter
Brian Salomonf4ba4ec2020-03-19 15:54:28 -04001181 // clockwise to match Skia convention.
John Stiles270cec22021-02-17 12:59:36 -05001182 this->write(fProgram.fConfig->fSettings.fFlipY ? "_frontFacing" : "(!_frontFacing)");
Timothy Liang7b8875d2018-08-10 09:42:31 -04001183 break;
Ethan Nicholascc305772017-10-13 16:17:45 -04001184 default:
Ethan Nicholas78686922020-10-08 06:46:27 -04001185 const Variable& var = *ref.variable();
Ethan Nicholas453f67f2020-10-09 10:43:45 -04001186 if (var.storage() == Variable::Storage::kGlobal) {
Ethan Nicholas78686922020-10-08 06:46:27 -04001187 if (var.modifiers().fFlags & Modifiers::kIn_Flag) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001188 this->write("_in.");
Ethan Nicholas78686922020-10-08 06:46:27 -04001189 } else if (var.modifiers().fFlags & Modifiers::kOut_Flag) {
John Stilesf7410bd2021-01-19 13:07:55 -05001190 this->write("_out.");
Ethan Nicholas78686922020-10-08 06:46:27 -04001191 } else if (var.modifiers().fFlags & Modifiers::kUniform_Flag &&
1192 var.type().typeKind() != Type::TypeKind::kSampler) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001193 this->write("_uniforms.");
1194 } else {
John Stilesf7410bd2021-01-19 13:07:55 -05001195 this->write("_globals.");
Ethan Nicholascc305772017-10-13 16:17:45 -04001196 }
1197 }
Ethan Nicholas78686922020-10-08 06:46:27 -04001198 this->writeName(var.name());
Ethan Nicholascc305772017-10-13 16:17:45 -04001199 }
1200}
1201
1202void MetalCodeGenerator::writeIndexExpression(const IndexExpression& expr) {
Brian Osman00185012021-02-04 16:07:11 -05001203 this->writeExpression(*expr.base(), Precedence::kPostfix);
Ethan Nicholascc305772017-10-13 16:17:45 -04001204 this->write("[");
Brian Osman00185012021-02-04 16:07:11 -05001205 this->writeExpression(*expr.index(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001206 this->write("]");
1207}
1208
1209void MetalCodeGenerator::writeFieldAccess(const FieldAccess& f) {
Ethan Nicholas7a95b202020-10-09 11:55:40 -04001210 const Type::Field* field = &f.base()->type().fields()[f.fieldIndex()];
1211 if (FieldAccess::OwnerKind::kDefault == f.ownerKind()) {
Brian Osman00185012021-02-04 16:07:11 -05001212 this->writeExpression(*f.base(), Precedence::kPostfix);
Ethan Nicholascc305772017-10-13 16:17:45 -04001213 this->write(".");
1214 }
Timothy Liang7d637782018-06-05 09:58:07 -04001215 switch (field->fModifiers.fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001216 case SK_POSITION_BUILTIN:
John Stilesf7410bd2021-01-19 13:07:55 -05001217 this->write("_out.sk_Position");
Ethan Nicholascc305772017-10-13 16:17:45 -04001218 break;
1219 default:
Timothy Liang7d637782018-06-05 09:58:07 -04001220 if (field->fName == "sk_PointSize") {
John Stilesf7410bd2021-01-19 13:07:55 -05001221 this->write("_out.sk_PointSize");
Timothy Liang7d637782018-06-05 09:58:07 -04001222 } else {
Ethan Nicholas7a95b202020-10-09 11:55:40 -04001223 if (FieldAccess::OwnerKind::kAnonymousInterfaceBlock == f.ownerKind()) {
John Stilesf7410bd2021-01-19 13:07:55 -05001224 this->write("_globals.");
Timothy Liang7d637782018-06-05 09:58:07 -04001225 this->write(fInterfaceBlockNameMap[fInterfaceBlockMap[field]]);
1226 this->write("->");
1227 }
Timothy Liang651286f2018-06-07 09:55:33 -04001228 this->writeName(field->fName);
Timothy Lianga06f2152018-05-24 15:33:31 -04001229 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001230 }
1231}
1232
1233void MetalCodeGenerator::writeSwizzle(const Swizzle& swizzle) {
Brian Osman00185012021-02-04 16:07:11 -05001234 this->writeExpression(*swizzle.base(), Precedence::kPostfix);
Ethan Nicholascc305772017-10-13 16:17:45 -04001235 this->write(".");
Ethan Nicholas6b4d5812020-10-12 16:11:51 -04001236 for (int c : swizzle.components()) {
Brian Osman25647672020-09-15 15:16:56 -04001237 SkASSERT(c >= 0 && c <= 3);
1238 this->write(&("x\0y\0z\0w\0"[c * 2]));
Ethan Nicholascc305772017-10-13 16:17:45 -04001239 }
1240}
1241
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001242void MetalCodeGenerator::writeMatrixTimesEqualHelper(const Type& left, const Type& right,
1243 const Type& result) {
John Stiles01cdf012021-02-10 09:53:41 -05001244 String key = "TimesEqual" + this->typeName(left) + ":" + this->typeName(right);
John Stiles56233d12021-02-03 13:03:29 -05001245
1246 auto [iter, wasInserted] = fHelpers.insert(key);
1247 if (wasInserted) {
John Stiles368db7c2020-12-29 11:20:08 -05001248 fExtraFunctions.printf("thread %s& operator*=(thread %s& left, thread const %s& right) {\n"
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001249 " left = left * right;\n"
1250 " return left;\n"
John Stiles368db7c2020-12-29 11:20:08 -05001251 "}\n",
1252 this->typeName(result).c_str(), this->typeName(left).c_str(),
1253 this->typeName(right).c_str());
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001254 }
1255}
1256
John Stiles01cdf012021-02-10 09:53:41 -05001257void MetalCodeGenerator::writeMatrixEqualityHelper(const Type& left, const Type& right) {
1258 SkASSERTF(left.rows() == right.rows() && left.columns() == right.columns(), "left=%s, right=%s",
1259 left.description().c_str(), right.description().c_str());
1260
1261 String key = "Equality" + this->typeName(left) + ":" + this->typeName(right);
1262
1263 auto [iter, wasInserted] = fHelpers.insert(key);
1264 if (wasInserted) {
1265 fExtraFunctions.printf(
1266 "thread bool operator==(const %s left, const %s right) {\n"
1267 " return",
1268 this->typeName(left).c_str(), this->typeName(right).c_str());
1269
1270 for (int index=0; index<left.columns(); ++index) {
1271 fExtraFunctions.printf("%s all(left[%d] == right[%d])",
1272 index == 0 ? "" : " &&", index, index);
1273 }
1274 fExtraFunctions.printf(";\n"
1275 "}\n");
1276 }
1277}
1278
1279void MetalCodeGenerator::writeMatrixInequalityHelper(const Type& left, const Type& right) {
1280 SkASSERTF(left.rows() == right.rows() && left.columns() == right.columns(), "left=%s, right=%s",
1281 left.description().c_str(), right.description().c_str());
1282
1283 String key = "Inequality" + this->typeName(left) + ":" + this->typeName(right);
1284
1285 auto [iter, wasInserted] = fHelpers.insert(key);
1286 if (wasInserted) {
1287 fExtraFunctions.printf(
1288 "thread bool operator!=(const %s left, const %s right) {\n"
1289 " return",
1290 this->typeName(left).c_str(), this->typeName(right).c_str());
1291
1292 for (int index=0; index<left.columns(); ++index) {
1293 fExtraFunctions.printf("%s any(left[%d] != right[%d])",
1294 index == 0 ? "" : " ||", index, index);
1295 }
1296 fExtraFunctions.printf(";\n"
1297 "}\n");
1298 }
1299}
1300
Ethan Nicholascc305772017-10-13 16:17:45 -04001301void MetalCodeGenerator::writeBinaryExpression(const BinaryExpression& b,
1302 Precedence parentPrecedence) {
John Stiles2d4f9592020-10-30 10:29:12 -04001303 const Expression& left = *b.left();
1304 const Expression& right = *b.right();
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001305 const Type& leftType = left.type();
1306 const Type& rightType = right.type();
John Stiles45990502021-02-16 10:55:27 -05001307 Operator op = b.getOperator();
1308 Precedence precedence = op.getBinaryPrecedence();
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001309 bool needParens = precedence >= parentPrecedence;
John Stiles45990502021-02-16 10:55:27 -05001310 switch (op.kind()) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001311 case Token::Kind::TK_EQEQ:
John Stiles9aeed132020-11-24 17:36:06 -05001312 if (leftType.isVector()) {
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001313 this->write("all");
1314 needParens = true;
1315 }
1316 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001317 case Token::Kind::TK_NEQ:
John Stiles9aeed132020-11-24 17:36:06 -05001318 if (leftType.isVector()) {
Jim Van Verth36477b42019-04-11 14:57:30 -04001319 this->write("any");
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001320 needParens = true;
1321 }
1322 break;
1323 default:
1324 break;
1325 }
1326 if (needParens) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001327 this->write("(");
1328 }
John Stiles01cdf012021-02-10 09:53:41 -05001329 if (leftType.isMatrix() && rightType.isMatrix()) {
John Stiles45990502021-02-16 10:55:27 -05001330 if (op.kind() == Token::Kind::TK_STAREQ) {
John Stiles01cdf012021-02-10 09:53:41 -05001331 this->writeMatrixTimesEqualHelper(leftType, rightType, b.type());
John Stiles45990502021-02-16 10:55:27 -05001332 } else if (op.kind() == Token::Kind::TK_EQEQ) {
John Stiles01cdf012021-02-10 09:53:41 -05001333 this->writeMatrixEqualityHelper(leftType, rightType);
John Stiles45990502021-02-16 10:55:27 -05001334 } else if (op.kind() == Token::Kind::TK_NEQ) {
John Stiles01cdf012021-02-10 09:53:41 -05001335 this->writeMatrixInequalityHelper(leftType, rightType);
1336 }
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001337 }
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001338 this->writeExpression(left, precedence);
John Stiles45990502021-02-16 10:55:27 -05001339 if (op.kind() != Token::Kind::TK_EQ && op.isAssignment() &&
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001340 left.kind() == Expression::Kind::kSwizzle && !left.hasSideEffects()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001341 // This doesn't compile in Metal:
1342 // float4 x = float4(1);
1343 // x.xy *= float2x2(...);
1344 // with the error message "non-const reference cannot bind to vector element",
1345 // but switching it to x.xy = x.xy * float2x2(...) fixes it. We perform this tranformation
1346 // as long as the LHS has no side effects, and hope for the best otherwise.
1347 this->write(" = ");
Brian Osman00185012021-02-04 16:07:11 -05001348 this->writeExpression(left, Precedence::kAssignment);
Ethan Nicholascc305772017-10-13 16:17:45 -04001349 this->write(" ");
John Stilesd6449e92020-11-30 09:13:23 -05001350 String opName = OperatorName(op);
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001351 SkASSERT(opName.endsWith("="));
1352 this->write(opName.substr(0, opName.size() - 1).c_str());
Ethan Nicholascc305772017-10-13 16:17:45 -04001353 this->write(" ");
1354 } else {
John Stilesd6449e92020-11-30 09:13:23 -05001355 this->write(String(" ") + OperatorName(op) + " ");
Ethan Nicholascc305772017-10-13 16:17:45 -04001356 }
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001357 this->writeExpression(right, precedence);
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001358 if (needParens) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001359 this->write(")");
1360 }
1361}
1362
1363void MetalCodeGenerator::writeTernaryExpression(const TernaryExpression& t,
1364 Precedence parentPrecedence) {
Brian Osman00185012021-02-04 16:07:11 -05001365 if (Precedence::kTernary >= parentPrecedence) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001366 this->write("(");
1367 }
Brian Osman00185012021-02-04 16:07:11 -05001368 this->writeExpression(*t.test(), Precedence::kTernary);
Ethan Nicholascc305772017-10-13 16:17:45 -04001369 this->write(" ? ");
Brian Osman00185012021-02-04 16:07:11 -05001370 this->writeExpression(*t.ifTrue(), Precedence::kTernary);
Ethan Nicholascc305772017-10-13 16:17:45 -04001371 this->write(" : ");
Brian Osman00185012021-02-04 16:07:11 -05001372 this->writeExpression(*t.ifFalse(), Precedence::kTernary);
1373 if (Precedence::kTernary >= parentPrecedence) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001374 this->write(")");
1375 }
1376}
1377
1378void MetalCodeGenerator::writePrefixExpression(const PrefixExpression& p,
1379 Precedence parentPrecedence) {
Brian Osman00185012021-02-04 16:07:11 -05001380 if (Precedence::kPrefix >= parentPrecedence) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001381 this->write("(");
1382 }
John Stilesd6449e92020-11-30 09:13:23 -05001383 this->write(OperatorName(p.getOperator()));
Brian Osman00185012021-02-04 16:07:11 -05001384 this->writeExpression(*p.operand(), Precedence::kPrefix);
1385 if (Precedence::kPrefix >= parentPrecedence) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001386 this->write(")");
1387 }
1388}
1389
1390void MetalCodeGenerator::writePostfixExpression(const PostfixExpression& p,
1391 Precedence parentPrecedence) {
Brian Osman00185012021-02-04 16:07:11 -05001392 if (Precedence::kPostfix >= parentPrecedence) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001393 this->write("(");
1394 }
Brian Osman00185012021-02-04 16:07:11 -05001395 this->writeExpression(*p.operand(), Precedence::kPostfix);
John Stilesd6449e92020-11-30 09:13:23 -05001396 this->write(OperatorName(p.getOperator()));
Brian Osman00185012021-02-04 16:07:11 -05001397 if (Precedence::kPostfix >= parentPrecedence) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001398 this->write(")");
1399 }
1400}
1401
1402void MetalCodeGenerator::writeBoolLiteral(const BoolLiteral& b) {
Ethan Nicholas59d660c2020-09-28 09:18:15 -04001403 this->write(b.value() ? "true" : "false");
Ethan Nicholascc305772017-10-13 16:17:45 -04001404}
1405
1406void MetalCodeGenerator::writeIntLiteral(const IntLiteral& i) {
John Stiles12739df2020-12-29 09:47:20 -05001407 const Type& type = i.type();
John Stiles54e7c052021-01-11 14:22:36 -05001408 if (type == *fContext.fTypes.fUInt) {
Ethan Nicholase96cdd12020-09-28 16:27:18 -04001409 this->write(to_string(i.value() & 0xffffffff) + "u");
John Stiles54e7c052021-01-11 14:22:36 -05001410 } else if (type == *fContext.fTypes.fUShort) {
John Stiles12739df2020-12-29 09:47:20 -05001411 this->write(to_string(i.value() & 0xffff) + "u");
John Stiles54e7c052021-01-11 14:22:36 -05001412 } else if (type == *fContext.fTypes.fUByte) {
John Stiles12739df2020-12-29 09:47:20 -05001413 this->write(to_string(i.value() & 0xff) + "u");
Ethan Nicholascc305772017-10-13 16:17:45 -04001414 } else {
John Stiles12739df2020-12-29 09:47:20 -05001415 this->write(to_string(i.value()));
Ethan Nicholascc305772017-10-13 16:17:45 -04001416 }
1417}
1418
1419void MetalCodeGenerator::writeFloatLiteral(const FloatLiteral& f) {
Ethan Nicholasa3f22f12020-10-01 12:13:17 -04001420 this->write(to_string(f.value()));
Ethan Nicholascc305772017-10-13 16:17:45 -04001421}
1422
1423void MetalCodeGenerator::writeSetting(const Setting& s) {
John Stilesf57207b2021-02-02 17:50:34 -05001424 SK_ABORT("internal error; setting was not folded to a constant during compilation\n");
Ethan Nicholascc305772017-10-13 16:17:45 -04001425}
1426
John Stiles06b84ef2020-12-09 12:35:48 -05001427void MetalCodeGenerator::writeFunctionRequirementArgs(const FunctionDeclaration& f,
1428 const char*& separator) {
1429 Requirements requirements = this->requirements(f);
1430 if (requirements & kInputs_Requirement) {
1431 this->write(separator);
1432 this->write("_in");
1433 separator = ", ";
1434 }
1435 if (requirements & kOutputs_Requirement) {
1436 this->write(separator);
1437 this->write("_out");
1438 separator = ", ";
1439 }
1440 if (requirements & kUniforms_Requirement) {
1441 this->write(separator);
1442 this->write("_uniforms");
1443 separator = ", ";
1444 }
1445 if (requirements & kGlobals_Requirement) {
1446 this->write(separator);
John Stilesf7410bd2021-01-19 13:07:55 -05001447 this->write("_globals");
John Stiles06b84ef2020-12-09 12:35:48 -05001448 separator = ", ";
1449 }
1450 if (requirements & kFragCoord_Requirement) {
1451 this->write(separator);
1452 this->write("_fragCoord");
1453 separator = ", ";
1454 }
1455}
1456
1457void MetalCodeGenerator::writeFunctionRequirementParams(const FunctionDeclaration& f,
1458 const char*& separator) {
1459 Requirements requirements = this->requirements(f);
1460 if (requirements & kInputs_Requirement) {
1461 this->write(separator);
1462 this->write("Inputs _in");
1463 separator = ", ";
1464 }
1465 if (requirements & kOutputs_Requirement) {
1466 this->write(separator);
John Stilesf7410bd2021-01-19 13:07:55 -05001467 this->write("thread Outputs& _out");
John Stiles06b84ef2020-12-09 12:35:48 -05001468 separator = ", ";
1469 }
1470 if (requirements & kUniforms_Requirement) {
1471 this->write(separator);
1472 this->write("Uniforms _uniforms");
1473 separator = ", ";
1474 }
1475 if (requirements & kGlobals_Requirement) {
1476 this->write(separator);
John Stilesf7410bd2021-01-19 13:07:55 -05001477 this->write("thread Globals& _globals");
John Stiles06b84ef2020-12-09 12:35:48 -05001478 separator = ", ";
1479 }
1480 if (requirements & kFragCoord_Requirement) {
1481 this->write(separator);
1482 this->write("float4 _fragCoord");
1483 separator = ", ";
1484 }
1485}
1486
John Stilesda5cdf62021-01-28 11:47:29 -05001487int MetalCodeGenerator::getUniformBinding(const Modifiers& m) {
1488 return (m.fLayout.fBinding >= 0) ? m.fLayout.fBinding
John Stiles270cec22021-02-17 12:59:36 -05001489 : fProgram.fConfig->fSettings.fDefaultUniformBinding;
John Stilesda5cdf62021-01-28 11:47:29 -05001490}
1491
1492int MetalCodeGenerator::getUniformSet(const Modifiers& m) {
1493 return (m.fLayout.fSet >= 0) ? m.fLayout.fSet
John Stiles270cec22021-02-17 12:59:36 -05001494 : fProgram.fConfig->fSettings.fDefaultUniformSet;
John Stilesda5cdf62021-01-28 11:47:29 -05001495}
1496
John Stiles569249b2020-11-03 12:18:22 -05001497bool MetalCodeGenerator::writeFunctionDeclaration(const FunctionDeclaration& f) {
John Stilesf7410bd2021-01-19 13:07:55 -05001498 fRTHeightName = fProgram.fInputs.fRTHeight ? "_globals._anonInterface0->u_skRTHeight" : "";
Ethan Nicholascc305772017-10-13 16:17:45 -04001499 const char* separator = "";
John Stilese8da4d22021-03-24 09:19:45 -04001500 if (f.isMain()) {
John Stiles270cec22021-02-17 12:59:36 -05001501 switch (fProgram.fConfig->fKind) {
John Stilesdbd4e6f2021-02-16 13:29:15 -05001502 case ProgramKind::kFragment:
Timothy Liangb8eeb802018-07-23 16:46:16 -04001503 this->write("fragment Outputs fragmentMain");
Ethan Nicholascc305772017-10-13 16:17:45 -04001504 break;
John Stilesdbd4e6f2021-02-16 13:29:15 -05001505 case ProgramKind::kVertex:
Timothy Liangb8eeb802018-07-23 16:46:16 -04001506 this->write("vertex Outputs vertexMain");
Ethan Nicholascc305772017-10-13 16:17:45 -04001507 break;
1508 default:
John Stiles3fabfc02020-09-25 15:51:28 -04001509 fErrors.error(-1, "unsupported kind of program");
John Stiles569249b2020-11-03 12:18:22 -05001510 return false;
Ethan Nicholascc305772017-10-13 16:17:45 -04001511 }
1512 this->write("(Inputs _in [[stage_in]]");
1513 if (-1 != fUniformBuffer) {
1514 this->write(", constant Uniforms& _uniforms [[buffer(" +
1515 to_string(fUniformBuffer) + ")]]");
1516 }
Brian Osman133724c2020-10-28 14:14:39 -04001517 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04001518 if (e->is<GlobalVarDeclaration>()) {
1519 const GlobalVarDeclaration& decls = e->as<GlobalVarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001520 const VarDeclaration& var = decls.declaration()->as<VarDeclaration>();
1521 if (var.var().type().typeKind() == Type::TypeKind::kSampler) {
1522 if (var.var().modifiers().fLayout.fBinding < 0) {
Brian Osmanc0213602020-10-06 14:43:32 -04001523 fErrors.error(decls.fOffset,
John Stilesb41d5bb2021-01-26 16:28:12 -05001524 "Metal samplers must have 'layout(binding=...)'");
John Stiles569249b2020-11-03 12:18:22 -05001525 return false;
Timothy Liangee84fe12018-05-18 14:38:19 -04001526 }
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001527 if (var.var().type().dimensions() != SpvDim2D) {
John Stiles569249b2020-11-03 12:18:22 -05001528 // Not yet implemented--Skia currently only uses 2D textures.
Brian Osmanc0213602020-10-06 14:43:32 -04001529 fErrors.error(decls.fOffset, "Unsupported texture dimensions");
John Stiles569249b2020-11-03 12:18:22 -05001530 return false;
Brian Osmanc0213602020-10-06 14:43:32 -04001531 }
1532 this->write(", texture2d<float> ");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001533 this->writeName(var.var().name());
Brian Osmanc0213602020-10-06 14:43:32 -04001534 this->write("[[texture(");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001535 this->write(to_string(var.var().modifiers().fLayout.fBinding));
Brian Osmanc0213602020-10-06 14:43:32 -04001536 this->write(")]]");
1537 this->write(", sampler ");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001538 this->writeName(var.var().name());
Brian Osmanc0213602020-10-06 14:43:32 -04001539 this->write(SAMPLER_SUFFIX);
1540 this->write("[[sampler(");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001541 this->write(to_string(var.var().modifiers().fLayout.fBinding));
Brian Osmanc0213602020-10-06 14:43:32 -04001542 this->write(")]]");
Timothy Liang6403b0e2018-05-17 10:40:04 -04001543 }
Brian Osman1179fcf2020-10-08 16:04:40 -04001544 } else if (e->is<InterfaceBlock>()) {
1545 const InterfaceBlock& intf = e->as<InterfaceBlock>();
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001546 if (intf.typeName() == "sk_PerVertex") {
Timothy Lianga06f2152018-05-24 15:33:31 -04001547 continue;
1548 }
1549 this->write(", constant ");
John Stilesb4418502021-02-04 10:57:08 -05001550 this->writeType(intf.variable().type());
Timothy Lianga06f2152018-05-24 15:33:31 -04001551 this->write("& " );
1552 this->write(fInterfaceBlockNameMap[&intf]);
1553 this->write(" [[buffer(");
John Stilesda5cdf62021-01-28 11:47:29 -05001554 this->write(to_string(this->getUniformBinding(intf.variable().modifiers())));
Timothy Lianga06f2152018-05-24 15:33:31 -04001555 this->write(")]]");
Timothy Liang6403b0e2018-05-17 10:40:04 -04001556 }
1557 }
John Stiles270cec22021-02-17 12:59:36 -05001558 if (fProgram.fConfig->fKind == ProgramKind::kFragment) {
Jim Van Verth6bc650e2019-02-07 14:53:23 -05001559 if (fProgram.fInputs.fRTHeight && fInterfaceBlockNameMap.empty()) {
Timothy Liang5422f9a2018-08-10 10:57:55 -04001560 this->write(", constant sksl_synthetic_uniforms& _anonInterface0 [[buffer(1)]]");
Ethan Nicholasf931e402019-07-26 15:40:33 -04001561 fRTHeightName = "_anonInterface0.u_skRTHeight";
Timothy Liang5422f9a2018-08-10 10:57:55 -04001562 }
Timothy Liang7b8875d2018-08-10 09:42:31 -04001563 this->write(", bool _frontFacing [[front_facing]]");
Timothy Liang7d637782018-06-05 09:58:07 -04001564 this->write(", float4 _fragCoord [[position]]");
John Stiles270cec22021-02-17 12:59:36 -05001565 } else if (fProgram.fConfig->fKind == ProgramKind::kVertex) {
Timothy Liangdc89f192018-06-13 09:20:31 -04001566 this->write(", uint sk_VertexID [[vertex_id]], uint sk_InstanceID [[instance_id]]");
Timothy Liang7d637782018-06-05 09:58:07 -04001567 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001568 separator = ", ";
1569 } else {
John Stilesb4418502021-02-04 10:57:08 -05001570 this->writeType(f.returnType());
Timothy Liang651286f2018-06-07 09:55:33 -04001571 this->write(" ");
John Stilese1068342021-03-22 11:57:41 -04001572 this->writeName(f.mangledName());
Timothy Liang651286f2018-06-07 09:55:33 -04001573 this->write("(");
John Stiles06b84ef2020-12-09 12:35:48 -05001574 this->writeFunctionRequirementParams(f, separator);
Ethan Nicholascc305772017-10-13 16:17:45 -04001575 }
John Stiles569249b2020-11-03 12:18:22 -05001576 for (const auto& param : f.parameters()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001577 this->write(separator);
1578 separator = ", ";
John Stiles06b84ef2020-12-09 12:35:48 -05001579 this->writeModifiers(param->modifiers(), /*globalContext=*/false);
Ethan Nicholas30d30222020-09-11 12:27:26 -04001580 const Type* type = &param->type();
John Stilesb4418502021-02-04 10:57:08 -05001581 this->writeType(*type);
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001582 if (param->modifiers().fFlags & Modifiers::kOut_Flag) {
John Stilesf2bd5012020-12-04 11:58:26 -05001583 this->write("&");
Ethan Nicholascc305772017-10-13 16:17:45 -04001584 }
Timothy Liang651286f2018-06-07 09:55:33 -04001585 this->write(" ");
Ethan Nicholase2c49992020-10-05 11:49:11 -04001586 this->writeName(param->name());
Ethan Nicholascc305772017-10-13 16:17:45 -04001587 }
John Stiles569249b2020-11-03 12:18:22 -05001588 this->write(")");
1589 return true;
1590}
Ethan Nicholascc305772017-10-13 16:17:45 -04001591
John Stiles569249b2020-11-03 12:18:22 -05001592void MetalCodeGenerator::writeFunctionPrototype(const FunctionPrototype& f) {
1593 this->writeFunctionDeclaration(f.declaration());
1594 this->writeLine(";");
1595}
1596
John Stiles986c7fb2020-12-01 14:44:56 -05001597static bool is_block_ending_with_return(const Statement* stmt) {
1598 // This function detects (potentially nested) blocks that end in a return statement.
1599 if (!stmt->is<Block>()) {
1600 return false;
1601 }
1602 const StatementArray& block = stmt->as<Block>().children();
1603 for (int index = block.count(); index--; ) {
1604 const Statement& stmt = *block[index];
1605 if (stmt.is<ReturnStatement>()) {
1606 return true;
1607 }
1608 if (stmt.is<Block>()) {
1609 return is_block_ending_with_return(&stmt);
1610 }
1611 if (!stmt.is<Nop>()) {
1612 break;
1613 }
1614 }
1615 return false;
1616}
1617
John Stiles569249b2020-11-03 12:18:22 -05001618void MetalCodeGenerator::writeFunction(const FunctionDefinition& f) {
John Stiles270cec22021-02-17 12:59:36 -05001619 SkASSERT(!fProgram.fConfig->fSettings.fFragColorIsInOut);
Brian Salomondc092132018-04-04 10:14:16 -04001620
John Stiles569249b2020-11-03 12:18:22 -05001621 if (!this->writeFunctionDeclaration(f.declaration())) {
1622 return;
1623 }
1624
John Stiles986c7fb2020-12-01 14:44:56 -05001625 fCurrentFunction = &f.declaration();
1626 SkScopeExit clearCurrentFunction([&] { fCurrentFunction = nullptr; });
1627
John Stiles569249b2020-11-03 12:18:22 -05001628 this->writeLine(" {");
1629
John Stilese8da4d22021-03-24 09:19:45 -04001630 if (f.declaration().isMain()) {
John Stilescdcdb042020-07-06 09:03:51 -04001631 this->writeGlobalInit();
John Stilesf7410bd2021-01-19 13:07:55 -05001632 this->writeLine(" Outputs _out;");
John Stiles37279172021-01-21 22:24:28 -05001633 this->writeLine(" (void)_out;");
Ethan Nicholascc305772017-10-13 16:17:45 -04001634 }
John Stilesc67b3622020-05-28 17:53:13 -04001635
Ethan Nicholascc305772017-10-13 16:17:45 -04001636 fFunctionHeader = "";
Ethan Nicholascc305772017-10-13 16:17:45 -04001637 StringStream buffer;
John Stiles44532372020-12-07 12:33:55 -05001638 {
1639 AutoOutputStream outputToBuffer(this, &buffer);
1640 fIndentation++;
1641 for (const std::unique_ptr<Statement>& stmt : f.body()->as<Block>().children()) {
1642 if (!stmt->isEmpty()) {
1643 this->writeStatement(*stmt);
John Stilese8b5a732021-03-12 13:25:52 -05001644 this->finishLine();
John Stiles44532372020-12-07 12:33:55 -05001645 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001646 }
John Stilese8da4d22021-03-24 09:19:45 -04001647 if (f.declaration().isMain()) {
John Stiles44532372020-12-07 12:33:55 -05001648 // If the main function doesn't end with a return, we need to synthesize one here.
1649 if (!is_block_ending_with_return(f.body().get())) {
1650 this->writeReturnStatementFromMain();
John Stilese8b5a732021-03-12 13:25:52 -05001651 this->finishLine();
John Stiles44532372020-12-07 12:33:55 -05001652 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001653 }
John Stiles44532372020-12-07 12:33:55 -05001654 fIndentation--;
1655 this->writeLine("}");
Ethan Nicholascc305772017-10-13 16:17:45 -04001656 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001657 this->write(fFunctionHeader);
1658 this->write(buffer.str());
1659}
1660
1661void MetalCodeGenerator::writeModifiers(const Modifiers& modifiers,
John Stiles06b84ef2020-12-09 12:35:48 -05001662 bool globalContext) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001663 if (modifiers.fFlags & Modifiers::kOut_Flag) {
1664 this->write("thread ");
1665 }
1666 if (modifiers.fFlags & Modifiers::kConst_Flag) {
John Stiles0bd55782021-02-09 18:29:40 -05001667 this->write("const ");
Ethan Nicholascc305772017-10-13 16:17:45 -04001668 }
1669}
1670
1671void MetalCodeGenerator::writeInterfaceBlock(const InterfaceBlock& intf) {
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001672 if ("sk_PerVertex" == intf.typeName()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001673 return;
1674 }
John Stiles06b84ef2020-12-09 12:35:48 -05001675 this->writeModifiers(intf.variable().modifiers(), /*globalContext=*/true);
Timothy Liangdc89f192018-06-13 09:20:31 -04001676 this->write("struct ");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001677 this->writeLine(intf.typeName() + " {");
1678 const Type* structType = &intf.variable().type();
John Stilesbb43b7e2020-12-03 17:36:32 -05001679 if (structType->isArray()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001680 structType = &structType->componentType();
1681 }
Timothy Liangdc89f192018-06-13 09:20:31 -04001682 fIndentation++;
John Stiles3dba3ee2020-12-02 23:35:49 -05001683 this->writeFields(structType->fields(), structType->fOffset, &intf);
Jim Van Verth3d482992019-02-07 10:48:05 -05001684 if (fProgram.fInputs.fRTHeight) {
Timothy Liang7d637782018-06-05 09:58:07 -04001685 this->writeLine("float u_skRTHeight;");
Ethan Nicholascc305772017-10-13 16:17:45 -04001686 }
1687 fIndentation--;
1688 this->write("}");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001689 if (intf.instanceName().size()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001690 this->write(" ");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001691 this->write(intf.instanceName());
John Stilesd39aec02020-12-03 10:42:26 -05001692 if (intf.arraySize() > 0) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001693 this->write("[");
John Stilesd39aec02020-12-03 10:42:26 -05001694 this->write(to_string(intf.arraySize()));
Ethan Nicholascc305772017-10-13 16:17:45 -04001695 this->write("]");
John Stilesd39aec02020-12-03 10:42:26 -05001696 } else if (intf.arraySize() == Type::kUnsizedArray){
1697 this->write("[]");
Ethan Nicholascc305772017-10-13 16:17:45 -04001698 }
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001699 fInterfaceBlockNameMap[&intf] = intf.instanceName();
Timothy Lianga06f2152018-05-24 15:33:31 -04001700 } else {
Timothy Liang7d637782018-06-05 09:58:07 -04001701 fInterfaceBlockNameMap[&intf] = "_anonInterface" + to_string(fAnonInterfaceCount++);
Ethan Nicholascc305772017-10-13 16:17:45 -04001702 }
1703 this->writeLine(";");
1704}
1705
Timothy Liangdc89f192018-06-13 09:20:31 -04001706void MetalCodeGenerator::writeFields(const std::vector<Type::Field>& fields, int parentOffset,
1707 const InterfaceBlock* parentIntf) {
Timothy Liang609fbe32018-08-10 16:40:49 -04001708 MemoryLayout memoryLayout(MemoryLayout::kMetal_Standard);
Timothy Liangdc89f192018-06-13 09:20:31 -04001709 int currentOffset = 0;
1710 for (const auto& field: fields) {
1711 int fieldOffset = field.fModifiers.fLayout.fOffset;
1712 const Type* fieldType = field.fType;
John Stiles21f5f452020-11-30 09:57:59 -05001713 if (!MemoryLayout::LayoutIsSupported(*fieldType)) {
John Stiles0023c0c2020-11-16 13:32:18 -05001714 fErrors.error(parentOffset, "type '" + fieldType->name() + "' is not permitted here");
1715 return;
1716 }
Timothy Liangdc89f192018-06-13 09:20:31 -04001717 if (fieldOffset != -1) {
1718 if (currentOffset > fieldOffset) {
1719 fErrors.error(parentOffset,
John Stilesd7199b22020-12-30 16:22:58 -05001720 "offset of field '" + field.fName + "' must be at least " +
1721 to_string((int) currentOffset));
Brian Osman8609a242020-09-08 14:01:49 -04001722 return;
Timothy Liangdc89f192018-06-13 09:20:31 -04001723 } else if (currentOffset < fieldOffset) {
1724 this->write("char pad");
1725 this->write(to_string(fPaddingCount++));
1726 this->write("[");
1727 this->write(to_string(fieldOffset - currentOffset));
1728 this->writeLine("];");
1729 currentOffset = fieldOffset;
1730 }
1731 int alignment = memoryLayout.alignment(*fieldType);
1732 if (fieldOffset % alignment) {
1733 fErrors.error(parentOffset,
1734 "offset of field '" + field.fName + "' must be a multiple of " +
1735 to_string((int) alignment));
Brian Osman8609a242020-09-08 14:01:49 -04001736 return;
Timothy Liangdc89f192018-06-13 09:20:31 -04001737 }
1738 }
Brian Osman8609a242020-09-08 14:01:49 -04001739 size_t fieldSize = memoryLayout.size(*fieldType);
1740 if (fieldSize > static_cast<size_t>(std::numeric_limits<int>::max() - currentOffset)) {
1741 fErrors.error(parentOffset, "field offset overflow");
1742 return;
1743 }
1744 currentOffset += fieldSize;
John Stiles06b84ef2020-12-09 12:35:48 -05001745 this->writeModifiers(field.fModifiers, /*globalContext=*/false);
John Stilesb4418502021-02-04 10:57:08 -05001746 this->writeType(*fieldType);
Timothy Liangdc89f192018-06-13 09:20:31 -04001747 this->write(" ");
1748 this->writeName(field.fName);
Timothy Liangdc89f192018-06-13 09:20:31 -04001749 this->writeLine(";");
1750 if (parentIntf) {
1751 fInterfaceBlockMap[&field] = parentIntf;
1752 }
1753 }
1754}
1755
Ethan Nicholascc305772017-10-13 16:17:45 -04001756void MetalCodeGenerator::writeVarInitializer(const Variable& var, const Expression& value) {
Brian Osman00185012021-02-04 16:07:11 -05001757 this->writeExpression(value, Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001758}
1759
Timothy Liang651286f2018-06-07 09:55:33 -04001760void MetalCodeGenerator::writeName(const String& name) {
1761 if (fReservedWords.find(name) != fReservedWords.end()) {
1762 this->write("_"); // adding underscore before name to avoid conflict with reserved words
1763 }
1764 this->write(name);
1765}
1766
John Stilesb4418502021-02-04 10:57:08 -05001767void MetalCodeGenerator::writeVarDeclaration(const VarDeclaration& varDecl, bool global) {
1768 if (global && !(varDecl.var().modifiers().fFlags & Modifiers::kConst_Flag)) {
Brian Osmanc0213602020-10-06 14:43:32 -04001769 return;
Ethan Nicholascc305772017-10-13 16:17:45 -04001770 }
John Stilesb4418502021-02-04 10:57:08 -05001771 this->writeModifiers(varDecl.var().modifiers(), global);
1772 this->writeType(varDecl.var().type());
Brian Osmanc0213602020-10-06 14:43:32 -04001773 this->write(" ");
John Stilesb4418502021-02-04 10:57:08 -05001774 this->writeName(varDecl.var().name());
1775 if (varDecl.value()) {
Brian Osmanc0213602020-10-06 14:43:32 -04001776 this->write(" = ");
John Stilesb4418502021-02-04 10:57:08 -05001777 this->writeVarInitializer(varDecl.var(), *varDecl.value());
Brian Osmanc0213602020-10-06 14:43:32 -04001778 }
1779 this->write(";");
Ethan Nicholascc305772017-10-13 16:17:45 -04001780}
1781
1782void MetalCodeGenerator::writeStatement(const Statement& s) {
Ethan Nicholase6592142020-09-08 10:22:09 -04001783 switch (s.kind()) {
1784 case Statement::Kind::kBlock:
John Stiles26f98502020-08-18 09:30:51 -04001785 this->writeBlock(s.as<Block>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001786 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001787 case Statement::Kind::kExpression:
Brian Osman00185012021-02-04 16:07:11 -05001788 this->writeExpression(*s.as<ExpressionStatement>().expression(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001789 this->write(";");
1790 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001791 case Statement::Kind::kReturn:
John Stiles26f98502020-08-18 09:30:51 -04001792 this->writeReturnStatement(s.as<ReturnStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001793 break;
Brian Osmanc0213602020-10-06 14:43:32 -04001794 case Statement::Kind::kVarDeclaration:
1795 this->writeVarDeclaration(s.as<VarDeclaration>(), false);
Ethan Nicholascc305772017-10-13 16:17:45 -04001796 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001797 case Statement::Kind::kIf:
John Stiles26f98502020-08-18 09:30:51 -04001798 this->writeIfStatement(s.as<IfStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001799 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001800 case Statement::Kind::kFor:
John Stiles26f98502020-08-18 09:30:51 -04001801 this->writeForStatement(s.as<ForStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001802 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001803 case Statement::Kind::kDo:
John Stiles26f98502020-08-18 09:30:51 -04001804 this->writeDoStatement(s.as<DoStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001805 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001806 case Statement::Kind::kSwitch:
John Stiles26f98502020-08-18 09:30:51 -04001807 this->writeSwitchStatement(s.as<SwitchStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001808 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001809 case Statement::Kind::kBreak:
Ethan Nicholascc305772017-10-13 16:17:45 -04001810 this->write("break;");
1811 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001812 case Statement::Kind::kContinue:
Ethan Nicholascc305772017-10-13 16:17:45 -04001813 this->write("continue;");
1814 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001815 case Statement::Kind::kDiscard:
Timothy Lianga06f2152018-05-24 15:33:31 -04001816 this->write("discard_fragment();");
Ethan Nicholascc305772017-10-13 16:17:45 -04001817 break;
John Stiles98c1f822020-09-09 14:18:53 -04001818 case Statement::Kind::kInlineMarker:
Ethan Nicholase6592142020-09-08 10:22:09 -04001819 case Statement::Kind::kNop:
Ethan Nicholascc305772017-10-13 16:17:45 -04001820 this->write(";");
1821 break;
1822 default:
John Stileseada7bc2021-02-02 16:29:32 -05001823 SkDEBUGFAILF("unsupported statement: %s", s.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -05001824 break;
Ethan Nicholascc305772017-10-13 16:17:45 -04001825 }
1826}
1827
Ethan Nicholascc305772017-10-13 16:17:45 -04001828void MetalCodeGenerator::writeBlock(const Block& b) {
John Stiles3744bd62021-01-26 13:49:43 -05001829 // Write scope markers if this block is a scope, or if the block is empty (since we need to emit
1830 // something here to make the code valid).
1831 bool isScope = b.isScope() || b.isEmpty();
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001832 if (isScope) {
Ethan Nicholas70728ef2020-05-28 07:09:00 -04001833 this->writeLine("{");
1834 fIndentation++;
1835 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001836 for (const std::unique_ptr<Statement>& stmt : b.children()) {
1837 if (!stmt->isEmpty()) {
1838 this->writeStatement(*stmt);
John Stilese8b5a732021-03-12 13:25:52 -05001839 this->finishLine();
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001840 }
1841 }
1842 if (isScope) {
Ethan Nicholas70728ef2020-05-28 07:09:00 -04001843 fIndentation--;
1844 this->write("}");
1845 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001846}
1847
1848void MetalCodeGenerator::writeIfStatement(const IfStatement& stmt) {
1849 this->write("if (");
Brian Osman00185012021-02-04 16:07:11 -05001850 this->writeExpression(*stmt.test(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001851 this->write(") ");
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04001852 this->writeStatement(*stmt.ifTrue());
1853 if (stmt.ifFalse()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001854 this->write(" else ");
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04001855 this->writeStatement(*stmt.ifFalse());
Ethan Nicholascc305772017-10-13 16:17:45 -04001856 }
1857}
1858
1859void MetalCodeGenerator::writeForStatement(const ForStatement& f) {
Brian Osmand6f23382020-12-15 17:08:59 -05001860 // Emit loops of the form 'for(;test;)' as 'while(test)', which is probably how they started
1861 if (!f.initializer() && f.test() && !f.next()) {
1862 this->write("while (");
Brian Osman00185012021-02-04 16:07:11 -05001863 this->writeExpression(*f.test(), Precedence::kTopLevel);
Brian Osmand6f23382020-12-15 17:08:59 -05001864 this->write(") ");
1865 this->writeStatement(*f.statement());
1866 return;
1867 }
1868
Ethan Nicholascc305772017-10-13 16:17:45 -04001869 this->write("for (");
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04001870 if (f.initializer() && !f.initializer()->isEmpty()) {
1871 this->writeStatement(*f.initializer());
Ethan Nicholascc305772017-10-13 16:17:45 -04001872 } else {
1873 this->write("; ");
1874 }
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04001875 if (f.test()) {
Brian Osman00185012021-02-04 16:07:11 -05001876 this->writeExpression(*f.test(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001877 }
1878 this->write("; ");
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04001879 if (f.next()) {
Brian Osman00185012021-02-04 16:07:11 -05001880 this->writeExpression(*f.next(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001881 }
1882 this->write(") ");
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04001883 this->writeStatement(*f.statement());
Ethan Nicholascc305772017-10-13 16:17:45 -04001884}
1885
Ethan Nicholascc305772017-10-13 16:17:45 -04001886void MetalCodeGenerator::writeDoStatement(const DoStatement& d) {
1887 this->write("do ");
Ethan Nicholas1fd61162020-09-28 13:14:19 -04001888 this->writeStatement(*d.statement());
Ethan Nicholascc305772017-10-13 16:17:45 -04001889 this->write(" while (");
Brian Osman00185012021-02-04 16:07:11 -05001890 this->writeExpression(*d.test(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001891 this->write(");");
1892}
1893
1894void MetalCodeGenerator::writeSwitchStatement(const SwitchStatement& s) {
1895 this->write("switch (");
Brian Osman00185012021-02-04 16:07:11 -05001896 this->writeExpression(*s.value(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001897 this->writeLine(") {");
1898 fIndentation++;
John Stilesb23a64b2021-03-11 08:27:59 -05001899 for (const std::unique_ptr<Statement>& stmt : s.cases()) {
1900 const SwitchCase& c = stmt->as<SwitchCase>();
1901 if (c.value()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001902 this->write("case ");
John Stilesb23a64b2021-03-11 08:27:59 -05001903 this->writeExpression(*c.value(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001904 this->writeLine(":");
1905 } else {
1906 this->writeLine("default:");
1907 }
John Stilesb23a64b2021-03-11 08:27:59 -05001908 if (!c.statement()->isEmpty()) {
John Stilesc3ce43b2021-03-09 15:37:01 -05001909 fIndentation++;
John Stilesb23a64b2021-03-11 08:27:59 -05001910 this->writeStatement(*c.statement());
John Stilese8b5a732021-03-12 13:25:52 -05001911 this->finishLine();
John Stilesc3ce43b2021-03-09 15:37:01 -05001912 fIndentation--;
Ethan Nicholascc305772017-10-13 16:17:45 -04001913 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001914 }
1915 fIndentation--;
1916 this->write("}");
1917}
1918
John Stiles986c7fb2020-12-01 14:44:56 -05001919void MetalCodeGenerator::writeReturnStatementFromMain() {
1920 // main functions in Metal return a magic _out parameter that doesn't exist in SkSL.
John Stiles270cec22021-02-17 12:59:36 -05001921 switch (fProgram.fConfig->fKind) {
John Stilesdbd4e6f2021-02-16 13:29:15 -05001922 case ProgramKind::kFragment:
John Stilesf7410bd2021-01-19 13:07:55 -05001923 this->write("return _out;");
John Stiles986c7fb2020-12-01 14:44:56 -05001924 break;
John Stilesdbd4e6f2021-02-16 13:29:15 -05001925 case ProgramKind::kVertex:
John Stilesf7410bd2021-01-19 13:07:55 -05001926 this->write("return (_out.sk_Position.y = -_out.sk_Position.y, _out);");
John Stiles986c7fb2020-12-01 14:44:56 -05001927 break;
1928 default:
1929 SkDEBUGFAIL("unsupported kind of program");
1930 }
1931}
1932
Ethan Nicholascc305772017-10-13 16:17:45 -04001933void MetalCodeGenerator::writeReturnStatement(const ReturnStatement& r) {
John Stilese8da4d22021-03-24 09:19:45 -04001934 if (fCurrentFunction && fCurrentFunction->isMain()) {
John Stiles986c7fb2020-12-01 14:44:56 -05001935 if (r.expression()) {
John Stiles97d18172021-01-22 16:47:42 -05001936 if (r.expression()->type() == *fContext.fTypes.fHalf4) {
1937 this->write("_out.sk_FragColor = ");
Brian Osman00185012021-02-04 16:07:11 -05001938 this->writeExpression(*r.expression(), Precedence::kTopLevel);
John Stiles97d18172021-01-22 16:47:42 -05001939 this->writeLine(";");
1940 } else {
1941 fErrors.error(r.fOffset, "Metal does not support returning '" +
1942 r.expression()->type().description() + "' from main()");
1943 }
John Stiles986c7fb2020-12-01 14:44:56 -05001944 }
1945 this->writeReturnStatementFromMain();
1946 return;
1947 }
1948
Ethan Nicholascc305772017-10-13 16:17:45 -04001949 this->write("return");
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04001950 if (r.expression()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001951 this->write(" ");
Brian Osman00185012021-02-04 16:07:11 -05001952 this->writeExpression(*r.expression(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001953 }
1954 this->write(";");
1955}
1956
Michael Ludwigbf58add2021-03-16 10:40:11 -04001957void MetalCodeGenerator::writeHeader() {
1958 this->write("#include <metal_stdlib>\n");
1959 this->write("#include <simd/simd.h>\n");
1960 this->write("using namespace metal;\n");
1961}
1962
Ethan Nicholascc305772017-10-13 16:17:45 -04001963void MetalCodeGenerator::writeUniformStruct() {
Brian Osman133724c2020-10-28 14:14:39 -04001964 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04001965 if (e->is<GlobalVarDeclaration>()) {
1966 const GlobalVarDeclaration& decls = e->as<GlobalVarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001967 const Variable& var = decls.declaration()->as<VarDeclaration>().var();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001968 if (var.modifiers().fFlags & Modifiers::kUniform_Flag &&
Brian Osmanc0213602020-10-06 14:43:32 -04001969 var.type().typeKind() != Type::TypeKind::kSampler) {
John Stilesda5cdf62021-01-28 11:47:29 -05001970 int uniformSet = this->getUniformSet(var.modifiers());
John Stilesd8fc95d2021-01-26 16:22:53 -05001971 // Make sure that the program's uniform-set value is consistent throughout.
Ethan Nicholascc305772017-10-13 16:17:45 -04001972 if (-1 == fUniformBuffer) {
1973 this->write("struct Uniforms {\n");
John Stilesd8fc95d2021-01-26 16:22:53 -05001974 fUniformBuffer = uniformSet;
1975 } else if (uniformSet != fUniformBuffer) {
1976 fErrors.error(decls.fOffset, "Metal backend requires all uniforms to have "
1977 "the same 'layout(set=...)'");
Ethan Nicholascc305772017-10-13 16:17:45 -04001978 }
1979 this->write(" ");
John Stilesb4418502021-02-04 10:57:08 -05001980 this->writeType(var.type());
Ethan Nicholascc305772017-10-13 16:17:45 -04001981 this->write(" ");
Brian Osmanc0213602020-10-06 14:43:32 -04001982 this->writeName(var.name());
Ethan Nicholascc305772017-10-13 16:17:45 -04001983 this->write(";\n");
1984 }
1985 }
1986 }
1987 if (-1 != fUniformBuffer) {
1988 this->write("};\n");
1989 }
1990}
1991
1992void MetalCodeGenerator::writeInputStruct() {
1993 this->write("struct Inputs {\n");
Brian Osman133724c2020-10-28 14:14:39 -04001994 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04001995 if (e->is<GlobalVarDeclaration>()) {
1996 const GlobalVarDeclaration& decls = e->as<GlobalVarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001997 const Variable& var = decls.declaration()->as<VarDeclaration>().var();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001998 if (var.modifiers().fFlags & Modifiers::kIn_Flag &&
1999 -1 == var.modifiers().fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002000 this->write(" ");
John Stilesb4418502021-02-04 10:57:08 -05002001 this->writeType(var.type());
Ethan Nicholascc305772017-10-13 16:17:45 -04002002 this->write(" ");
Brian Osmanc0213602020-10-06 14:43:32 -04002003 this->writeName(var.name());
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002004 if (-1 != var.modifiers().fLayout.fLocation) {
John Stiles270cec22021-02-17 12:59:36 -05002005 if (fProgram.fConfig->fKind == ProgramKind::kVertex) {
Brian Osmanc0213602020-10-06 14:43:32 -04002006 this->write(" [[attribute(" +
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002007 to_string(var.modifiers().fLayout.fLocation) + ")]]");
John Stiles270cec22021-02-17 12:59:36 -05002008 } else if (fProgram.fConfig->fKind == ProgramKind::kFragment) {
Brian Osmanc0213602020-10-06 14:43:32 -04002009 this->write(" [[user(locn" +
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002010 to_string(var.modifiers().fLayout.fLocation) + ")]]");
Ethan Nicholascc305772017-10-13 16:17:45 -04002011 }
2012 }
2013 this->write(";\n");
2014 }
2015 }
2016 }
2017 this->write("};\n");
2018}
2019
2020void MetalCodeGenerator::writeOutputStruct() {
2021 this->write("struct Outputs {\n");
John Stiles270cec22021-02-17 12:59:36 -05002022 if (fProgram.fConfig->fKind == ProgramKind::kVertex) {
Timothy Liangb8eeb802018-07-23 16:46:16 -04002023 this->write(" float4 sk_Position [[position]];\n");
John Stiles270cec22021-02-17 12:59:36 -05002024 } else if (fProgram.fConfig->fKind == ProgramKind::kFragment) {
Timothy Liangde0be802018-08-10 13:48:08 -04002025 this->write(" float4 sk_FragColor [[color(0)]];\n");
Timothy Liang7d637782018-06-05 09:58:07 -04002026 }
Brian Osman133724c2020-10-28 14:14:39 -04002027 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04002028 if (e->is<GlobalVarDeclaration>()) {
2029 const GlobalVarDeclaration& decls = e->as<GlobalVarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04002030 const Variable& var = decls.declaration()->as<VarDeclaration>().var();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002031 if (var.modifiers().fFlags & Modifiers::kOut_Flag &&
2032 -1 == var.modifiers().fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002033 this->write(" ");
John Stilesb4418502021-02-04 10:57:08 -05002034 this->writeType(var.type());
Ethan Nicholascc305772017-10-13 16:17:45 -04002035 this->write(" ");
Brian Osmanc0213602020-10-06 14:43:32 -04002036 this->writeName(var.name());
John Stiles842b3592020-12-01 10:36:37 -05002037
2038 int location = var.modifiers().fLayout.fLocation;
2039 if (location < 0) {
2040 fErrors.error(var.fOffset,
2041 "Metal out variables must have 'layout(location=...)'");
John Stiles270cec22021-02-17 12:59:36 -05002042 } else if (fProgram.fConfig->fKind == ProgramKind::kVertex) {
John Stiles842b3592020-12-01 10:36:37 -05002043 this->write(" [[user(locn" + to_string(location) + ")]]");
John Stiles270cec22021-02-17 12:59:36 -05002044 } else if (fProgram.fConfig->fKind == ProgramKind::kFragment) {
John Stiles842b3592020-12-01 10:36:37 -05002045 this->write(" [[color(" + to_string(location) + ")");
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002046 int colorIndex = var.modifiers().fLayout.fIndex;
Brian Osmanc0213602020-10-06 14:43:32 -04002047 if (colorIndex) {
2048 this->write(", index(" + to_string(colorIndex) + ")");
Timothy Liang7d637782018-06-05 09:58:07 -04002049 }
Brian Osmanc0213602020-10-06 14:43:32 -04002050 this->write("]]");
Ethan Nicholascc305772017-10-13 16:17:45 -04002051 }
2052 this->write(";\n");
2053 }
2054 }
Timothy Liang7d637782018-06-05 09:58:07 -04002055 }
John Stiles270cec22021-02-17 12:59:36 -05002056 if (fProgram.fConfig->fKind == ProgramKind::kVertex) {
Jim Van Verth3913d3e2020-08-31 15:16:57 -04002057 this->write(" float sk_PointSize [[point_size]];\n");
Timothy Liang7d637782018-06-05 09:58:07 -04002058 }
2059 this->write("};\n");
2060}
2061
2062void MetalCodeGenerator::writeInterfaceBlocks() {
2063 bool wroteInterfaceBlock = false;
Brian Osman133724c2020-10-28 14:14:39 -04002064 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04002065 if (e->is<InterfaceBlock>()) {
2066 this->writeInterfaceBlock(e->as<InterfaceBlock>());
Timothy Liang7d637782018-06-05 09:58:07 -04002067 wroteInterfaceBlock = true;
2068 }
2069 }
Jim Van Verth3d482992019-02-07 10:48:05 -05002070 if (!wroteInterfaceBlock && fProgram.fInputs.fRTHeight) {
Timothy Liang7d637782018-06-05 09:58:07 -04002071 this->writeLine("struct sksl_synthetic_uniforms {");
2072 this->writeLine(" float u_skRTHeight;");
2073 this->writeLine("};");
2074 }
Ethan Nicholascc305772017-10-13 16:17:45 -04002075}
2076
John Stilesdc75a972020-11-25 16:24:55 -05002077void MetalCodeGenerator::writeStructDefinitions() {
2078 for (const ProgramElement* e : fProgram.elements()) {
2079 if (e->is<StructDefinition>()) {
Brian Osman02bc5222021-01-28 11:00:20 -05002080 this->writeStructDefinition(e->as<StructDefinition>());
John Stilesdc75a972020-11-25 16:24:55 -05002081 }
2082 }
2083}
2084
John Stilescdcdb042020-07-06 09:03:51 -04002085void MetalCodeGenerator::visitGlobalStruct(GlobalStructVisitor* visitor) {
2086 // Visit the interface blocks.
2087 for (const auto& [interfaceType, interfaceName] : fInterfaceBlockNameMap) {
John Stilesfdb8dbe2020-12-04 11:00:03 -05002088 visitor->visitInterfaceBlock(*interfaceType, interfaceName);
John Stilescdcdb042020-07-06 09:03:51 -04002089 }
Brian Osman133724c2020-10-28 14:14:39 -04002090 for (const ProgramElement* element : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04002091 if (!element->is<GlobalVarDeclaration>()) {
John Stilescdcdb042020-07-06 09:03:51 -04002092 continue;
Timothy Liang7d637782018-06-05 09:58:07 -04002093 }
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04002094 const GlobalVarDeclaration& global = element->as<GlobalVarDeclaration>();
2095 const VarDeclaration& decl = global.declaration()->as<VarDeclaration>();
2096 const Variable& var = decl.var();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002097 if ((!var.modifiers().fFlags && -1 == var.modifiers().fLayout.fBuiltin) ||
Brian Osmanc0213602020-10-06 14:43:32 -04002098 var.type().typeKind() == Type::TypeKind::kSampler) {
2099 if (var.type().typeKind() == Type::TypeKind::kSampler) {
2100 // Samplers are represented as a "texture/sampler" duo in the global struct.
John Stilesfdb8dbe2020-12-04 11:00:03 -05002101 visitor->visitTexture(var.type(), var.name());
2102 visitor->visitSampler(var.type(), String(var.name()) + SAMPLER_SUFFIX);
Brian Osmanc0213602020-10-06 14:43:32 -04002103 } else {
2104 // Visit a regular variable.
John Stilesfdb8dbe2020-12-04 11:00:03 -05002105 visitor->visitVariable(var, decl.value().get());
Timothy Liangee84fe12018-05-18 14:38:19 -04002106 }
2107 }
2108 }
John Stilescdcdb042020-07-06 09:03:51 -04002109}
2110
2111void MetalCodeGenerator::writeGlobalStruct() {
2112 class : public GlobalStructVisitor {
2113 public:
John Stilesfdb8dbe2020-12-04 11:00:03 -05002114 void visitInterfaceBlock(const InterfaceBlock& block, const String& blockName) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002115 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002116 fCodeGen->write(" constant ");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04002117 fCodeGen->write(block.typeName());
John Stilescdcdb042020-07-06 09:03:51 -04002118 fCodeGen->write("* ");
2119 fCodeGen->writeName(blockName);
2120 fCodeGen->write(";\n");
2121 }
John Stilesfdb8dbe2020-12-04 11:00:03 -05002122 void visitTexture(const Type& type, const String& name) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002123 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002124 fCodeGen->write(" ");
John Stilesb4418502021-02-04 10:57:08 -05002125 fCodeGen->writeType(type);
John Stilescdcdb042020-07-06 09:03:51 -04002126 fCodeGen->write(" ");
2127 fCodeGen->writeName(name);
2128 fCodeGen->write(";\n");
2129 }
John Stilesfdb8dbe2020-12-04 11:00:03 -05002130 void visitSampler(const Type&, const String& name) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002131 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002132 fCodeGen->write(" sampler ");
2133 fCodeGen->writeName(name);
2134 fCodeGen->write(";\n");
2135 }
John Stilesfdb8dbe2020-12-04 11:00:03 -05002136 void visitVariable(const Variable& var, const Expression* value) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002137 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002138 fCodeGen->write(" ");
John Stilesb4418502021-02-04 10:57:08 -05002139 fCodeGen->writeType(var.type());
John Stilescdcdb042020-07-06 09:03:51 -04002140 fCodeGen->write(" ");
Ethan Nicholase2c49992020-10-05 11:49:11 -04002141 fCodeGen->writeName(var.name());
John Stilescdcdb042020-07-06 09:03:51 -04002142 fCodeGen->write(";\n");
2143 }
John Stiles83f3b8d2020-12-07 17:52:25 -05002144 void addElement() {
John Stilescdcdb042020-07-06 09:03:51 -04002145 if (fFirst) {
2146 fCodeGen->write("struct Globals {\n");
2147 fFirst = false;
2148 }
2149 }
John Stiles83f3b8d2020-12-07 17:52:25 -05002150 void finish() {
John Stilescdcdb042020-07-06 09:03:51 -04002151 if (!fFirst) {
John Stiles83f3b8d2020-12-07 17:52:25 -05002152 fCodeGen->writeLine("};");
John Stilescdcdb042020-07-06 09:03:51 -04002153 fFirst = true;
2154 }
2155 }
2156
2157 MetalCodeGenerator* fCodeGen = nullptr;
2158 bool fFirst = true;
2159 } visitor;
2160
2161 visitor.fCodeGen = this;
2162 this->visitGlobalStruct(&visitor);
John Stiles83f3b8d2020-12-07 17:52:25 -05002163 visitor.finish();
John Stilescdcdb042020-07-06 09:03:51 -04002164}
2165
2166void MetalCodeGenerator::writeGlobalInit() {
2167 class : public GlobalStructVisitor {
2168 public:
John Stilesfdb8dbe2020-12-04 11:00:03 -05002169 void visitInterfaceBlock(const InterfaceBlock& blockType,
John Stilescdcdb042020-07-06 09:03:51 -04002170 const String& blockName) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002171 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002172 fCodeGen->write("&");
2173 fCodeGen->writeName(blockName);
2174 }
John Stilesfdb8dbe2020-12-04 11:00:03 -05002175 void visitTexture(const Type&, const String& name) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002176 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002177 fCodeGen->writeName(name);
2178 }
John Stilesfdb8dbe2020-12-04 11:00:03 -05002179 void visitSampler(const Type&, const String& name) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002180 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002181 fCodeGen->writeName(name);
2182 }
John Stilesfdb8dbe2020-12-04 11:00:03 -05002183 void visitVariable(const Variable& var, const Expression* value) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002184 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002185 if (value) {
2186 fCodeGen->writeVarInitializer(var, *value);
2187 } else {
2188 fCodeGen->write("{}");
2189 }
2190 }
John Stiles83f3b8d2020-12-07 17:52:25 -05002191 void addElement() {
John Stilescdcdb042020-07-06 09:03:51 -04002192 if (fFirst) {
John Stilesf7410bd2021-01-19 13:07:55 -05002193 fCodeGen->write(" Globals _globals{");
John Stilescdcdb042020-07-06 09:03:51 -04002194 fFirst = false;
2195 } else {
2196 fCodeGen->write(", ");
2197 }
2198 }
John Stiles83f3b8d2020-12-07 17:52:25 -05002199 void finish() {
John Stilescdcdb042020-07-06 09:03:51 -04002200 if (!fFirst) {
2201 fCodeGen->writeLine("};");
John Stiles37279172021-01-21 22:24:28 -05002202 fCodeGen->writeLine(" (void)_globals;");
John Stilescdcdb042020-07-06 09:03:51 -04002203 }
2204 }
2205 MetalCodeGenerator* fCodeGen = nullptr;
2206 bool fFirst = true;
2207 } visitor;
2208
2209 visitor.fCodeGen = this;
2210 this->visitGlobalStruct(&visitor);
John Stiles83f3b8d2020-12-07 17:52:25 -05002211 visitor.finish();
Timothy Liangee84fe12018-05-18 14:38:19 -04002212}
2213
Ethan Nicholascc305772017-10-13 16:17:45 -04002214void MetalCodeGenerator::writeProgramElement(const ProgramElement& e) {
Ethan Nicholase6592142020-09-08 10:22:09 -04002215 switch (e.kind()) {
2216 case ProgramElement::Kind::kExtension:
Ethan Nicholascc305772017-10-13 16:17:45 -04002217 break;
Brian Osmanc0213602020-10-06 14:43:32 -04002218 case ProgramElement::Kind::kGlobalVar: {
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04002219 const GlobalVarDeclaration& global = e.as<GlobalVarDeclaration>();
2220 const VarDeclaration& decl = global.declaration()->as<VarDeclaration>();
2221 int builtin = decl.var().modifiers().fLayout.fBuiltin;
Brian Osmanc0213602020-10-06 14:43:32 -04002222 if (-1 == builtin) {
2223 // normal var
2224 this->writeVarDeclaration(decl, true);
John Stilese8b5a732021-03-12 13:25:52 -05002225 this->finishLine();
Brian Osmanc0213602020-10-06 14:43:32 -04002226 } else if (SK_FRAGCOLOR_BUILTIN == builtin) {
2227 // ignore
Ethan Nicholascc305772017-10-13 16:17:45 -04002228 }
2229 break;
2230 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002231 case ProgramElement::Kind::kInterfaceBlock:
Timothy Liang7d637782018-06-05 09:58:07 -04002232 // handled in writeInterfaceBlocks, do nothing
Ethan Nicholascc305772017-10-13 16:17:45 -04002233 break;
John Stilesdc75a972020-11-25 16:24:55 -05002234 case ProgramElement::Kind::kStructDefinition:
2235 // Handled in writeStructDefinitions. Do nothing.
2236 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04002237 case ProgramElement::Kind::kFunction:
John Stiles3dc0da62020-08-19 17:48:31 -04002238 this->writeFunction(e.as<FunctionDefinition>());
Ethan Nicholascc305772017-10-13 16:17:45 -04002239 break;
John Stiles569249b2020-11-03 12:18:22 -05002240 case ProgramElement::Kind::kFunctionPrototype:
2241 this->writeFunctionPrototype(e.as<FunctionPrototype>());
2242 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04002243 case ProgramElement::Kind::kModifiers:
John Stiles06b84ef2020-12-09 12:35:48 -05002244 this->writeModifiers(e.as<ModifiersDeclaration>().modifiers(),
2245 /*globalContext=*/true);
Ethan Nicholascc305772017-10-13 16:17:45 -04002246 this->writeLine(";");
2247 break;
John Stiles712fd6b2020-11-25 22:25:43 -05002248 case ProgramElement::Kind::kEnum:
2249 break;
Ethan Nicholascc305772017-10-13 16:17:45 -04002250 default:
John Stileseada7bc2021-02-02 16:29:32 -05002251 SkDEBUGFAILF("unsupported program element: %s\n", e.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -05002252 break;
Ethan Nicholascc305772017-10-13 16:17:45 -04002253 }
2254}
2255
Ethan Nicholasff350cb2020-05-14 14:05:13 -04002256MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const Expression* e) {
2257 if (!e) {
2258 return kNo_Requirements;
2259 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002260 switch (e->kind()) {
2261 case Expression::Kind::kFunctionCall: {
John Stiles3dc0da62020-08-19 17:48:31 -04002262 const FunctionCall& f = e->as<FunctionCall>();
Ethan Nicholas0dec9922020-10-05 15:51:52 -04002263 Requirements result = this->requirements(f.function());
2264 for (const auto& arg : f.arguments()) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04002265 result |= this->requirements(arg.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002266 }
2267 return result;
2268 }
John Stiles7384b372021-04-01 13:48:15 -04002269 case Expression::Kind::kConstructor:
2270 case Expression::Kind::kConstructorArray:
John Stiles2938eea2021-04-01 18:58:25 -04002271 case Expression::Kind::kConstructorDiagonalMatrix:
John Stilesfd7252f2021-04-04 22:24:40 -04002272 case Expression::Kind::kConstructorScalarCast:
John Stilesb14a8192021-04-05 11:40:46 -04002273 case Expression::Kind::kConstructorSplat:
John Stilesd986f472021-04-06 15:54:43 -04002274 case Expression::Kind::kConstructorVector:
John Stilesb14a8192021-04-05 11:40:46 -04002275 case Expression::Kind::kConstructorVectorCast: {
John Stiles7384b372021-04-01 13:48:15 -04002276 const AnyConstructor& c = e->asAnyConstructor();
Ethan Nicholascc305772017-10-13 16:17:45 -04002277 Requirements result = kNo_Requirements;
John Stilesd8eb8752021-04-01 11:49:10 -04002278 for (const auto& arg : c.argumentSpan()) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04002279 result |= this->requirements(arg.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002280 }
2281 return result;
2282 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002283 case Expression::Kind::kFieldAccess: {
John Stiles3dc0da62020-08-19 17:48:31 -04002284 const FieldAccess& f = e->as<FieldAccess>();
Ethan Nicholas7a95b202020-10-09 11:55:40 -04002285 if (FieldAccess::OwnerKind::kAnonymousInterfaceBlock == f.ownerKind()) {
Timothy Liang7d637782018-06-05 09:58:07 -04002286 return kGlobals_Requirement;
2287 }
Ethan Nicholas7a95b202020-10-09 11:55:40 -04002288 return this->requirements(f.base().get());
Timothy Liang7d637782018-06-05 09:58:07 -04002289 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002290 case Expression::Kind::kSwizzle:
Ethan Nicholas6b4d5812020-10-12 16:11:51 -04002291 return this->requirements(e->as<Swizzle>().base().get());
Ethan Nicholase6592142020-09-08 10:22:09 -04002292 case Expression::Kind::kBinary: {
2293 const BinaryExpression& bin = e->as<BinaryExpression>();
John Stiles2d4f9592020-10-30 10:29:12 -04002294 return this->requirements(bin.left().get()) |
2295 this->requirements(bin.right().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002296 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002297 case Expression::Kind::kIndex: {
John Stiles3dc0da62020-08-19 17:48:31 -04002298 const IndexExpression& idx = e->as<IndexExpression>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04002299 return this->requirements(idx.base().get()) | this->requirements(idx.index().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002300 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002301 case Expression::Kind::kPrefix:
Ethan Nicholas444ccc62020-10-09 10:16:22 -04002302 return this->requirements(e->as<PrefixExpression>().operand().get());
Ethan Nicholase6592142020-09-08 10:22:09 -04002303 case Expression::Kind::kPostfix:
Ethan Nicholas444ccc62020-10-09 10:16:22 -04002304 return this->requirements(e->as<PostfixExpression>().operand().get());
Ethan Nicholase6592142020-09-08 10:22:09 -04002305 case Expression::Kind::kTernary: {
John Stiles3dc0da62020-08-19 17:48:31 -04002306 const TernaryExpression& t = e->as<TernaryExpression>();
Ethan Nicholasdd218162020-10-08 05:48:01 -04002307 return this->requirements(t.test().get()) | this->requirements(t.ifTrue().get()) |
2308 this->requirements(t.ifFalse().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002309 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002310 case Expression::Kind::kVariableReference: {
John Stiles3dc0da62020-08-19 17:48:31 -04002311 const VariableReference& v = e->as<VariableReference>();
Ethan Nicholas78686922020-10-08 06:46:27 -04002312 const Modifiers& modifiers = v.variable()->modifiers();
Ethan Nicholascc305772017-10-13 16:17:45 -04002313 Requirements result = kNo_Requirements;
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002314 if (modifiers.fLayout.fBuiltin == SK_FRAGCOORD_BUILTIN) {
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -04002315 result = kGlobals_Requirement | kFragCoord_Requirement;
Ethan Nicholas453f67f2020-10-09 10:43:45 -04002316 } else if (Variable::Storage::kGlobal == v.variable()->storage()) {
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002317 if (modifiers.fFlags & Modifiers::kIn_Flag) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002318 result = kInputs_Requirement;
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002319 } else if (modifiers.fFlags & Modifiers::kOut_Flag) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002320 result = kOutputs_Requirement;
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002321 } else if (modifiers.fFlags & Modifiers::kUniform_Flag &&
Ethan Nicholas78686922020-10-08 06:46:27 -04002322 v.variable()->type().typeKind() != Type::TypeKind::kSampler) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002323 result = kUniforms_Requirement;
Timothy Liangee84fe12018-05-18 14:38:19 -04002324 } else {
2325 result = kGlobals_Requirement;
Ethan Nicholascc305772017-10-13 16:17:45 -04002326 }
2327 }
2328 return result;
2329 }
2330 default:
2331 return kNo_Requirements;
2332 }
2333}
2334
Ethan Nicholasff350cb2020-05-14 14:05:13 -04002335MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const Statement* s) {
2336 if (!s) {
2337 return kNo_Requirements;
2338 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002339 switch (s->kind()) {
2340 case Statement::Kind::kBlock: {
Ethan Nicholascc305772017-10-13 16:17:45 -04002341 Requirements result = kNo_Requirements;
Ethan Nicholas7bd60432020-09-25 14:31:59 -04002342 for (const std::unique_ptr<Statement>& child : s->as<Block>().children()) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04002343 result |= this->requirements(child.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002344 }
2345 return result;
2346 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002347 case Statement::Kind::kVarDeclaration: {
John Stiles3dc0da62020-08-19 17:48:31 -04002348 const VarDeclaration& var = s->as<VarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04002349 return this->requirements(var.value().get());
Timothy Liang7d637782018-06-05 09:58:07 -04002350 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002351 case Statement::Kind::kExpression:
Ethan Nicholasd503a5a2020-09-30 09:29:55 -04002352 return this->requirements(s->as<ExpressionStatement>().expression().get());
Ethan Nicholase6592142020-09-08 10:22:09 -04002353 case Statement::Kind::kReturn: {
John Stiles3dc0da62020-08-19 17:48:31 -04002354 const ReturnStatement& r = s->as<ReturnStatement>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04002355 return this->requirements(r.expression().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002356 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002357 case Statement::Kind::kIf: {
John Stiles3dc0da62020-08-19 17:48:31 -04002358 const IfStatement& i = s->as<IfStatement>();
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04002359 return this->requirements(i.test().get()) |
2360 this->requirements(i.ifTrue().get()) |
2361 this->requirements(i.ifFalse().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002362 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002363 case Statement::Kind::kFor: {
John Stiles3dc0da62020-08-19 17:48:31 -04002364 const ForStatement& f = s->as<ForStatement>();
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04002365 return this->requirements(f.initializer().get()) |
2366 this->requirements(f.test().get()) |
2367 this->requirements(f.next().get()) |
2368 this->requirements(f.statement().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002369 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002370 case Statement::Kind::kDo: {
John Stiles3dc0da62020-08-19 17:48:31 -04002371 const DoStatement& d = s->as<DoStatement>();
Ethan Nicholas1fd61162020-09-28 13:14:19 -04002372 return this->requirements(d.test().get()) |
2373 this->requirements(d.statement().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002374 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002375 case Statement::Kind::kSwitch: {
John Stiles3dc0da62020-08-19 17:48:31 -04002376 const SwitchStatement& sw = s->as<SwitchStatement>();
Ethan Nicholas01b05e52020-10-22 15:53:41 -04002377 Requirements result = this->requirements(sw.value().get());
John Stilesb23a64b2021-03-11 08:27:59 -05002378 for (const std::unique_ptr<Statement>& sc : sw.cases()) {
2379 result |= this->requirements(sc->as<SwitchCase>().statement().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002380 }
2381 return result;
2382 }
2383 default:
2384 return kNo_Requirements;
2385 }
2386}
2387
2388MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const FunctionDeclaration& f) {
Ethan Nicholased84b732020-10-08 11:45:44 -04002389 if (f.isBuiltin()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002390 return kNo_Requirements;
2391 }
2392 auto found = fRequirements.find(&f);
2393 if (found == fRequirements.end()) {
Ethan Nicholas65a8f562019-04-19 14:00:26 -04002394 fRequirements[&f] = kNo_Requirements;
Brian Osman133724c2020-10-28 14:14:39 -04002395 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04002396 if (e->is<FunctionDefinition>()) {
2397 const FunctionDefinition& def = e->as<FunctionDefinition>();
Ethan Nicholas0a5d0962020-10-14 13:33:18 -04002398 if (&def.declaration() == &f) {
2399 Requirements reqs = this->requirements(def.body().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002400 fRequirements[&f] = reqs;
2401 return reqs;
2402 }
2403 }
2404 }
John Stiles569249b2020-11-03 12:18:22 -05002405 // We never found a definition for this declared function, but it's legal to prototype a
2406 // function without ever giving a definition, as long as you don't call it.
2407 return kNo_Requirements;
Ethan Nicholascc305772017-10-13 16:17:45 -04002408 }
2409 return found->second;
2410}
2411
Timothy Liangb8eeb802018-07-23 16:46:16 -04002412bool MetalCodeGenerator::generateCode() {
John Stiles44532372020-12-07 12:33:55 -05002413 StringStream header;
2414 {
2415 AutoOutputStream outputToHeader(this, &header, &fIndentation);
Michael Ludwigbf58add2021-03-16 10:40:11 -04002416 this->writeHeader();
John Stiles44532372020-12-07 12:33:55 -05002417 this->writeStructDefinitions();
2418 this->writeUniformStruct();
2419 this->writeInputStruct();
2420 this->writeOutputStruct();
2421 this->writeInterfaceBlocks();
2422 this->writeGlobalStruct();
2423 }
2424 StringStream body;
2425 {
2426 AutoOutputStream outputToBody(this, &body, &fIndentation);
2427 for (const ProgramElement* e : fProgram.elements()) {
2428 this->writeProgramElement(*e);
2429 }
2430 }
2431 write_stringstream(header, *fOut);
2432 write_stringstream(fExtraFunctions, *fOut);
2433 write_stringstream(body, *fOut);
Brian Osman8609a242020-09-08 14:01:49 -04002434 return 0 == fErrors.errorCount();
Ethan Nicholascc305772017-10-13 16:17:45 -04002435}
2436
John Stilesa6841be2020-08-06 14:11:56 -04002437} // namespace SkSL