blob: 31e55d320efc50c2e8972a8391367c01145c2203 [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
John Stiles3738ef52021-04-13 10:41:57 -04008#include "src/sksl/codegen/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"
John Stiles8cad6372021-04-07 12:31:13 -040014#include "src/sksl/ir/SkSLConstructorCompoundCast.h"
John Stiles7384b372021-04-01 13:48:15 -040015#include "src/sksl/ir/SkSLConstructorDiagonalMatrix.h"
John Stiles5abb9e12021-04-06 13:47:19 -040016#include "src/sksl/ir/SkSLConstructorMatrixResize.h"
John Stiles2938eea2021-04-01 18:58:25 -040017#include "src/sksl/ir/SkSLConstructorSplat.h"
John Stilesd47330f2021-04-08 23:25:52 -040018#include "src/sksl/ir/SkSLConstructorStruct.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050019#include "src/sksl/ir/SkSLExpressionStatement.h"
20#include "src/sksl/ir/SkSLExtension.h"
21#include "src/sksl/ir/SkSLIndexExpression.h"
22#include "src/sksl/ir/SkSLModifiersDeclaration.h"
23#include "src/sksl/ir/SkSLNop.h"
John Stilesdc75a972020-11-25 16:24:55 -050024#include "src/sksl/ir/SkSLStructDefinition.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050025#include "src/sksl/ir/SkSLVariableReference.h"
Ethan Nicholascc305772017-10-13 16:17:45 -040026
Brian Osmanc262a122020-08-06 16:34:34 -040027#include <algorithm>
28
Ethan Nicholascc305772017-10-13 16:17:45 -040029namespace SkSL {
30
John Stiles45990502021-02-16 10:55:27 -050031const char* MetalCodeGenerator::OperatorName(Operator op) {
32 switch (op.kind()) {
John Stilesd6449e92020-11-30 09:13:23 -050033 case Token::Kind::TK_LOGICALXOR: return "!=";
John Stiles45990502021-02-16 10:55:27 -050034 default: return op.operatorName();
John Stilesd6449e92020-11-30 09:13:23 -050035 }
36}
37
John Stilescdcdb042020-07-06 09:03:51 -040038class MetalCodeGenerator::GlobalStructVisitor {
39public:
40 virtual ~GlobalStructVisitor() = default;
John Stilesfdb8dbe2020-12-04 11:00:03 -050041 virtual void visitInterfaceBlock(const InterfaceBlock& block, const String& blockName) = 0;
42 virtual void visitTexture(const Type& type, const String& name) = 0;
43 virtual void visitSampler(const Type& type, const String& name) = 0;
44 virtual void visitVariable(const Variable& var, const Expression* value) = 0;
John Stilescdcdb042020-07-06 09:03:51 -040045};
46
Timothy Liangee84fe12018-05-18 14:38:19 -040047void MetalCodeGenerator::setupIntrinsics() {
John Stilesd7199b22020-12-30 16:22:58 -050048 fIntrinsicMap[String("atan")] = kAtan_IntrinsicKind;
49 fIntrinsicMap[String("floatBitsToInt")] = kBitcast_IntrinsicKind;
50 fIntrinsicMap[String("floatBitsToUint")] = kBitcast_IntrinsicKind;
51 fIntrinsicMap[String("intBitsToFloat")] = kBitcast_IntrinsicKind;
52 fIntrinsicMap[String("uintBitsToFloat")] = kBitcast_IntrinsicKind;
53 fIntrinsicMap[String("equal")] = kCompareEqual_IntrinsicKind;
54 fIntrinsicMap[String("notEqual")] = kCompareNotEqual_IntrinsicKind;
55 fIntrinsicMap[String("lessThan")] = kCompareLessThan_IntrinsicKind;
56 fIntrinsicMap[String("lessThanEqual")] = kCompareLessThanEqual_IntrinsicKind;
57 fIntrinsicMap[String("greaterThan")] = kCompareGreaterThan_IntrinsicKind;
58 fIntrinsicMap[String("greaterThanEqual")] = kCompareGreaterThanEqual_IntrinsicKind;
59 fIntrinsicMap[String("degrees")] = kDegrees_IntrinsicKind;
60 fIntrinsicMap[String("dFdx")] = kDFdx_IntrinsicKind;
61 fIntrinsicMap[String("dFdy")] = kDFdy_IntrinsicKind;
62 fIntrinsicMap[String("distance")] = kDistance_IntrinsicKind;
63 fIntrinsicMap[String("dot")] = kDot_IntrinsicKind;
64 fIntrinsicMap[String("faceforward")] = kFaceforward_IntrinsicKind;
65 fIntrinsicMap[String("bitCount")] = kBitCount_IntrinsicKind;
66 fIntrinsicMap[String("findLSB")] = kFindLSB_IntrinsicKind;
67 fIntrinsicMap[String("findMSB")] = kFindMSB_IntrinsicKind;
68 fIntrinsicMap[String("inverse")] = kInverse_IntrinsicKind;
69 fIntrinsicMap[String("inversesqrt")] = kInversesqrt_IntrinsicKind;
70 fIntrinsicMap[String("length")] = kLength_IntrinsicKind;
71 fIntrinsicMap[String("matrixCompMult")] = kMatrixCompMult_IntrinsicKind;
72 fIntrinsicMap[String("mod")] = kMod_IntrinsicKind;
73 fIntrinsicMap[String("normalize")] = kNormalize_IntrinsicKind;
74 fIntrinsicMap[String("radians")] = kRadians_IntrinsicKind;
75 fIntrinsicMap[String("reflect")] = kReflect_IntrinsicKind;
76 fIntrinsicMap[String("refract")] = kRefract_IntrinsicKind;
John Stiles23456532020-12-30 18:12:48 -050077 fIntrinsicMap[String("roundEven")] = kRoundEven_IntrinsicKind;
John Stilesd7199b22020-12-30 16:22:58 -050078 fIntrinsicMap[String("sample")] = kTexture_IntrinsicKind;
Timothy Liangee84fe12018-05-18 14:38:19 -040079}
80
Ethan Nicholascc305772017-10-13 16:17:45 -040081void MetalCodeGenerator::write(const char* s) {
82 if (!s[0]) {
83 return;
84 }
85 if (fAtLineStart) {
86 for (int i = 0; i < fIndentation; i++) {
87 fOut->writeText(" ");
88 }
89 }
90 fOut->writeText(s);
91 fAtLineStart = false;
92}
93
94void MetalCodeGenerator::writeLine(const char* s) {
95 this->write(s);
John Stilese8b5a732021-03-12 13:25:52 -050096 this->writeLine();
Ethan Nicholascc305772017-10-13 16:17:45 -040097}
98
99void MetalCodeGenerator::write(const String& s) {
100 this->write(s.c_str());
101}
102
103void MetalCodeGenerator::writeLine(const String& s) {
104 this->writeLine(s.c_str());
105}
106
107void MetalCodeGenerator::writeLine() {
John Stilese8b5a732021-03-12 13:25:52 -0500108 fOut->writeText(fLineEnding);
109 fAtLineStart = true;
110}
111
112void MetalCodeGenerator::finishLine() {
113 if (!fAtLineStart) {
114 this->writeLine();
115 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400116}
117
118void MetalCodeGenerator::writeExtension(const Extension& ext) {
Ethan Nicholasefb09e22020-09-30 10:17:00 -0400119 this->writeLine("#extension " + ext.name() + " : enable");
Ethan Nicholascc305772017-10-13 16:17:45 -0400120}
121
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500122String MetalCodeGenerator::typeName(const Type& type) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400123 switch (type.typeKind()) {
John Stilesb4418502021-02-04 10:57:08 -0500124 case Type::TypeKind::kArray:
125 SkASSERTF(type.columns() > 0, "invalid array size: %s", type.description().c_str());
126 return String::printf("array<%s, %d>",
127 this->typeName(type.componentType()).c_str(), type.columns());
128
Ethan Nicholase6592142020-09-08 10:22:09 -0400129 case Type::TypeKind::kVector:
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500130 return this->typeName(type.componentType()) + to_string(type.columns());
John Stilesb4418502021-02-04 10:57:08 -0500131
Ethan Nicholase6592142020-09-08 10:22:09 -0400132 case Type::TypeKind::kMatrix:
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500133 return this->typeName(type.componentType()) + to_string(type.columns()) + "x" +
134 to_string(type.rows());
John Stilesb4418502021-02-04 10:57:08 -0500135
Ethan Nicholase6592142020-09-08 10:22:09 -0400136 case Type::TypeKind::kSampler:
John Stiles368db7c2020-12-29 11:20:08 -0500137 return "texture2d<float>"; // FIXME - support other texture types
John Stilesb4418502021-02-04 10:57:08 -0500138
John Stilesfd41d872020-11-25 22:39:45 -0500139 case Type::TypeKind::kEnum:
140 return "int";
John Stilesb4418502021-02-04 10:57:08 -0500141
Ethan Nicholascc305772017-10-13 16:17:45 -0400142 default:
John Stiles54e7c052021-01-11 14:22:36 -0500143 if (type == *fContext.fTypes.fHalf) {
Timothy Liang43d225f2018-07-19 15:27:13 -0400144 // FIXME - Currently only supporting floats in MSL to avoid type coercion issues.
John Stiles54e7c052021-01-11 14:22:36 -0500145 return fContext.fTypes.fFloat->name();
146 } else if (type == *fContext.fTypes.fByte) {
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500147 return "char";
John Stiles54e7c052021-01-11 14:22:36 -0500148 } else if (type == *fContext.fTypes.fUByte) {
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500149 return "uchar";
Timothy Liang7d637782018-06-05 09:58:07 -0400150 } else {
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500151 return type.name();
Timothy Liang7d637782018-06-05 09:58:07 -0400152 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400153 }
154}
155
Brian Osman02bc5222021-01-28 11:00:20 -0500156void MetalCodeGenerator::writeStructDefinition(const StructDefinition& s) {
157 const Type& type = s.type();
John Stilesdc75a972020-11-25 16:24:55 -0500158 this->writeLine("struct " + type.name() + " {");
159 fIndentation++;
160 this->writeFields(type.fields(), type.fOffset);
161 fIndentation--;
Brian Osman02bc5222021-01-28 11:00:20 -0500162 this->writeLine("};");
John Stilesdc75a972020-11-25 16:24:55 -0500163}
164
John Stilesb4418502021-02-04 10:57:08 -0500165void MetalCodeGenerator::writeType(const Type& type) {
166 this->write(this->typeName(type));
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500167}
168
Ethan Nicholascc305772017-10-13 16:17:45 -0400169void MetalCodeGenerator::writeExpression(const Expression& expr, Precedence parentPrecedence) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400170 switch (expr.kind()) {
171 case Expression::Kind::kBinary:
John Stiles81365af2020-08-18 09:24:00 -0400172 this->writeBinaryExpression(expr.as<BinaryExpression>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400173 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400174 case Expression::Kind::kBoolLiteral:
John Stiles81365af2020-08-18 09:24:00 -0400175 this->writeBoolLiteral(expr.as<BoolLiteral>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400176 break;
John Stiles2bec8ab2021-04-06 18:40:04 -0400177 case Expression::Kind::kConstructorArray:
John Stilesd47330f2021-04-08 23:25:52 -0400178 case Expression::Kind::kConstructorStruct:
John Stiles2bec8ab2021-04-06 18:40:04 -0400179 this->writeAnyConstructor(expr.asAnyConstructor(), "{", "}", parentPrecedence);
180 break;
John Stiles8cad6372021-04-07 12:31:13 -0400181 case Expression::Kind::kConstructorCompound:
182 this->writeConstructorCompound(expr.as<ConstructorCompound>(), parentPrecedence);
John Stiles2bec8ab2021-04-06 18:40:04 -0400183 break;
184 case Expression::Kind::kConstructorDiagonalMatrix:
185 case Expression::Kind::kConstructorSplat:
186 this->writeAnyConstructor(expr.asAnyConstructor(), "(", ")", parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400187 break;
John Stiles5abb9e12021-04-06 13:47:19 -0400188 case Expression::Kind::kConstructorMatrixResize:
189 this->writeConstructorMatrixResize(expr.as<ConstructorMatrixResize>(),
190 parentPrecedence);
191 break;
John Stilesfd7252f2021-04-04 22:24:40 -0400192 case Expression::Kind::kConstructorScalarCast:
John Stiles8cad6372021-04-07 12:31:13 -0400193 case Expression::Kind::kConstructorCompoundCast:
John Stilesb14a8192021-04-05 11:40:46 -0400194 this->writeCastConstructor(expr.asAnyConstructor(), "(", ")", parentPrecedence);
John Stiles2938eea2021-04-01 18:58:25 -0400195 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400196 case Expression::Kind::kIntLiteral:
John Stiles81365af2020-08-18 09:24:00 -0400197 this->writeIntLiteral(expr.as<IntLiteral>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400198 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400199 case Expression::Kind::kFieldAccess:
John Stiles81365af2020-08-18 09:24:00 -0400200 this->writeFieldAccess(expr.as<FieldAccess>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400201 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400202 case Expression::Kind::kFloatLiteral:
John Stiles81365af2020-08-18 09:24:00 -0400203 this->writeFloatLiteral(expr.as<FloatLiteral>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400204 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400205 case Expression::Kind::kFunctionCall:
John Stiles81365af2020-08-18 09:24:00 -0400206 this->writeFunctionCall(expr.as<FunctionCall>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400207 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400208 case Expression::Kind::kPrefix:
John Stiles81365af2020-08-18 09:24:00 -0400209 this->writePrefixExpression(expr.as<PrefixExpression>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400210 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400211 case Expression::Kind::kPostfix:
John Stiles81365af2020-08-18 09:24:00 -0400212 this->writePostfixExpression(expr.as<PostfixExpression>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400213 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400214 case Expression::Kind::kSetting:
John Stiles81365af2020-08-18 09:24:00 -0400215 this->writeSetting(expr.as<Setting>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400216 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400217 case Expression::Kind::kSwizzle:
John Stiles81365af2020-08-18 09:24:00 -0400218 this->writeSwizzle(expr.as<Swizzle>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400219 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400220 case Expression::Kind::kVariableReference:
John Stiles81365af2020-08-18 09:24:00 -0400221 this->writeVariableReference(expr.as<VariableReference>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400222 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400223 case Expression::Kind::kTernary:
John Stiles81365af2020-08-18 09:24:00 -0400224 this->writeTernaryExpression(expr.as<TernaryExpression>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400225 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400226 case Expression::Kind::kIndex:
John Stiles81365af2020-08-18 09:24:00 -0400227 this->writeIndexExpression(expr.as<IndexExpression>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400228 break;
229 default:
John Stileseada7bc2021-02-02 16:29:32 -0500230 SkDEBUGFAILF("unsupported expression: %s", expr.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -0500231 break;
Ethan Nicholascc305772017-10-13 16:17:45 -0400232 }
233}
234
John Stiles06b84ef2020-12-09 12:35:48 -0500235String MetalCodeGenerator::getOutParamHelper(const FunctionCall& call,
236 const ExpressionArray& arguments,
237 const SkTArray<VariableReference*>& outVars) {
238 AutoOutputStream outputToExtraFunctions(this, &fExtraFunctions, &fIndentation);
239 const FunctionDeclaration& function = call.function();
240
John Stilese1068342021-03-22 11:57:41 -0400241 String name = "_skOutParamHelper" + to_string(fSwizzleHelperCount++) +
242 "_" + function.mangledName();
John Stiles06b84ef2020-12-09 12:35:48 -0500243 const char* separator = "";
244
245 // Emit a prototype for the function we'll be calling through to in our helper.
246 if (!function.isBuiltin()) {
247 this->writeFunctionDeclaration(function);
248 this->writeLine(";");
249 }
250
251 // Synthesize a helper function that takes the same inputs as `function`, except in places where
252 // `outVars` is non-null; in those places, we take the type of the VariableReference.
253 //
254 // float _skOutParamHelper0_originalFuncName(float _var0, float _var1, float& outParam) {
John Stilesb4418502021-02-04 10:57:08 -0500255 this->writeType(call.type());
John Stiles06b84ef2020-12-09 12:35:48 -0500256 this->write(" ");
257 this->write(name);
258 this->write("(");
259 this->writeFunctionRequirementParams(function, separator);
260
261 SkASSERT(outVars.size() == arguments.size());
262 SkASSERT(outVars.size() == function.parameters().size());
263
John Stiles73e2c892021-02-13 13:58:01 -0500264 // We need to detect cases where the caller passes the same variable as an out-param more than
265 // once, and avoid reusing the variable name. (In those cases we can actually just ignore the
266 // redundant input parameter entirely, and not give it any name.)
267 std::unordered_set<const Variable*> writtenVars;
268
John Stiles06b84ef2020-12-09 12:35:48 -0500269 for (int index = 0; index < arguments.count(); ++index) {
270 this->write(separator);
271 separator = ", ";
272
273 const Variable* param = function.parameters()[index];
274 this->writeModifiers(param->modifiers(), /*globalContext=*/false);
275
276 const Type* type = outVars[index] ? &outVars[index]->type() : &arguments[index]->type();
John Stilesb4418502021-02-04 10:57:08 -0500277 this->writeType(*type);
John Stiles06b84ef2020-12-09 12:35:48 -0500278
279 if (param->modifiers().fFlags & Modifiers::kOut_Flag) {
280 this->write("&");
281 }
282 if (outVars[index]) {
John Stiles73e2c892021-02-13 13:58:01 -0500283 auto [iter, didInsert] = writtenVars.insert(outVars[index]->variable());
284 if (didInsert) {
285 this->write(" ");
286 fIgnoreVariableReferenceModifiers = true;
287 this->writeVariableReference(*outVars[index]);
288 fIgnoreVariableReferenceModifiers = false;
289 }
John Stiles06b84ef2020-12-09 12:35:48 -0500290 } else {
291 this->write(" _var");
292 this->write(to_string(index));
293 }
John Stiles06b84ef2020-12-09 12:35:48 -0500294 }
295 this->writeLine(") {");
296
297 ++fIndentation;
298 for (int index = 0; index < outVars.count(); ++index) {
299 if (!outVars[index]) {
300 continue;
301 }
302 // float3 _var2[ = outParam.zyx];
John Stilesb4418502021-02-04 10:57:08 -0500303 this->writeType(arguments[index]->type());
John Stiles06b84ef2020-12-09 12:35:48 -0500304 this->write(" _var");
305 this->write(to_string(index));
306
307 const Variable* param = function.parameters()[index];
308 if (param->modifiers().fFlags & Modifiers::kIn_Flag) {
309 this->write(" = ");
310 fIgnoreVariableReferenceModifiers = true;
Brian Osman00185012021-02-04 16:07:11 -0500311 this->writeExpression(*arguments[index], Precedence::kAssignment);
John Stiles06b84ef2020-12-09 12:35:48 -0500312 fIgnoreVariableReferenceModifiers = false;
313 }
314
315 this->writeLine(";");
316 }
317
John Stilesf7410bd2021-01-19 13:07:55 -0500318 // [int _skResult = ] myFunction(inputs, outputs, _globals, _var0, _var1, _var2, _var3);
John Stiles06b84ef2020-12-09 12:35:48 -0500319 bool hasResult = (call.type().name() != "void");
320 if (hasResult) {
John Stilesb4418502021-02-04 10:57:08 -0500321 this->writeType(call.type());
John Stiles06b84ef2020-12-09 12:35:48 -0500322 this->write(" _skResult = ");
323 }
324
John Stilese1068342021-03-22 11:57:41 -0400325 this->writeName(function.mangledName());
John Stiles06b84ef2020-12-09 12:35:48 -0500326 this->write("(");
327 separator = "";
328 this->writeFunctionRequirementArgs(function, separator);
329
330 for (int index = 0; index < arguments.count(); ++index) {
331 this->write(separator);
332 separator = ", ";
333
334 this->write("_var");
335 this->write(to_string(index));
336 }
337 this->writeLine(");");
338
339 for (int index = 0; index < outVars.count(); ++index) {
340 if (!outVars[index]) {
341 continue;
342 }
343 // outParam.zyx = _var2;
344 fIgnoreVariableReferenceModifiers = true;
Brian Osman00185012021-02-04 16:07:11 -0500345 this->writeExpression(*arguments[index], Precedence::kAssignment);
John Stiles06b84ef2020-12-09 12:35:48 -0500346 fIgnoreVariableReferenceModifiers = false;
347 this->write(" = _var");
348 this->write(to_string(index));
349 this->writeLine(";");
350 }
351
352 if (hasResult) {
353 this->writeLine("return _skResult;");
354 }
355
356 --fIndentation;
357 this->writeLine("}");
358
359 return name;
John Stilesb21fac22020-12-04 15:36:49 -0500360}
361
John Stilesf64e4072020-12-10 10:34:27 -0500362String MetalCodeGenerator::getBitcastIntrinsic(const Type& outType) {
363 return "as_type<" + outType.displayName() + ">";
364}
365
Ethan Nicholascc305772017-10-13 16:17:45 -0400366void MetalCodeGenerator::writeFunctionCall(const FunctionCall& c) {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400367 const FunctionDeclaration& function = c.function();
John Stiles89ac7c22020-12-30 17:47:31 -0500368 // If this function is a built-in with no declaration, it's probably an intrinsic and might need
369 // special handling.
370 if (function.isBuiltin() && !function.definition()) {
371 auto iter = fIntrinsicMap.find(function.name());
372 if (iter != fIntrinsicMap.end()) {
373 this->writeIntrinsicCall(c, iter->second);
374 return;
375 }
Timothy Liang6403b0e2018-05-17 10:40:04 -0400376 }
John Stilesb21fac22020-12-04 15:36:49 -0500377
John Stilesd7199b22020-12-30 16:22:58 -0500378 // Determine whether or not we need to emulate GLSL's out-param semantics for Metal using a
379 // helper function. (Specifically, out-parameters in GLSL are only written back to the original
380 // variable at the end of the function call; also, swizzles are supported, whereas Metal doesn't
381 // allow a swizzle to be passed to a `floatN&`.)
382 const ExpressionArray& arguments = c.arguments();
John Stilesb21fac22020-12-04 15:36:49 -0500383 const std::vector<const Variable*>& parameters = function.parameters();
384 SkASSERT(arguments.size() == parameters.size());
John Stiles06b84ef2020-12-09 12:35:48 -0500385
386 bool foundOutParam = false;
387 SkSTArray<16, VariableReference*> outVars;
John Stilesf64e4072020-12-10 10:34:27 -0500388 outVars.push_back_n(arguments.count(), (VariableReference*)nullptr);
John Stiles06b84ef2020-12-09 12:35:48 -0500389
390 for (int index = 0; index < arguments.count(); ++index) {
John Stilesb21fac22020-12-04 15:36:49 -0500391 // If this is an out parameter...
392 if (parameters[index]->modifiers().fFlags & Modifiers::kOut_Flag) {
John Stiles06b84ef2020-12-09 12:35:48 -0500393 // Find the expression's inner variable being written to.
John Stilesb21fac22020-12-04 15:36:49 -0500394 Analysis::AssignmentInfo info;
John Stiles06b84ef2020-12-09 12:35:48 -0500395 // Assignability was verified at IRGeneration time, so this should always succeed.
396 SkAssertResult(Analysis::IsAssignable(*arguments[index], &info));
397 outVars[index] = info.fAssignedVar;
398 foundOutParam = true;
John Stilesb21fac22020-12-04 15:36:49 -0500399 }
400 }
401
John Stiles06b84ef2020-12-09 12:35:48 -0500402 if (foundOutParam) {
403 // Out parameters need to be written back to at the end of the function. To do this, we
404 // synthesize a helper function which evaluates the out-param expression into a temporary
405 // variable, calls the original function, then writes the temp var back into the out param
406 // using the original out-param expression. (This lets us support things like swizzles and
407 // array indices.)
John Stilesd7199b22020-12-30 16:22:58 -0500408 this->write(getOutParamHelper(c, arguments, outVars));
409 } else {
John Stilese1068342021-03-22 11:57:41 -0400410 this->write(function.mangledName());
John Stiles06b84ef2020-12-09 12:35:48 -0500411 }
412
Ethan Nicholascc305772017-10-13 16:17:45 -0400413 this->write("(");
414 const char* separator = "";
John Stiles06b84ef2020-12-09 12:35:48 -0500415 this->writeFunctionRequirementArgs(function, separator);
416 for (int i = 0; i < arguments.count(); ++i) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400417 this->write(separator);
418 separator = ", ";
John Stiles06b84ef2020-12-09 12:35:48 -0500419
420 if (outVars[i]) {
Brian Osman00185012021-02-04 16:07:11 -0500421 this->writeExpression(*outVars[i], Precedence::kSequence);
John Stiles06b84ef2020-12-09 12:35:48 -0500422 } else {
Brian Osman00185012021-02-04 16:07:11 -0500423 this->writeExpression(*arguments[i], Precedence::kSequence);
John Stiles06b84ef2020-12-09 12:35:48 -0500424 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400425 }
426 this->write(")");
427}
428
Brian Osman964f0a02020-12-29 10:15:22 -0500429static constexpr char kInverse2x2[] = R"(
430float2x2 float2x2_inverse(float2x2 m) {
431 return float2x2(m[1][1], -m[0][1], -m[1][0], m[0][0]) * (1/determinant(m));
432}
433)";
434
435static constexpr char kInverse3x3[] = R"(
436float3x3 float3x3_inverse(float3x3 m) {
437 float a00 = m[0][0], a01 = m[0][1], a02 = m[0][2];
438 float a10 = m[1][0], a11 = m[1][1], a12 = m[1][2];
439 float a20 = m[2][0], a21 = m[2][1], a22 = m[2][2];
440 float b01 = a22*a11 - a12*a21;
441 float b11 = -a22*a10 + a12*a20;
442 float b21 = a21*a10 - a11*a20;
443 float det = a00*b01 + a01*b11 + a02*b21;
444 return float3x3(b01, (-a22*a01 + a02*a21), ( a12*a01 - a02*a11),
445 b11, ( a22*a00 - a02*a20), (-a12*a00 + a02*a10),
446 b21, (-a21*a00 + a01*a20), ( a11*a00 - a01*a10)) * (1/det);
447}
448)";
449
450static constexpr char kInverse4x4[] = R"(
451float4x4 float4x4_inverse(float4x4 m) {
452 float a00 = m[0][0], a01 = m[0][1], a02 = m[0][2], a03 = m[0][3];
453 float a10 = m[1][0], a11 = m[1][1], a12 = m[1][2], a13 = m[1][3];
454 float a20 = m[2][0], a21 = m[2][1], a22 = m[2][2], a23 = m[2][3];
455 float a30 = m[3][0], a31 = m[3][1], a32 = m[3][2], a33 = m[3][3];
456 float b00 = a00*a11 - a01*a10;
457 float b01 = a00*a12 - a02*a10;
458 float b02 = a00*a13 - a03*a10;
459 float b03 = a01*a12 - a02*a11;
460 float b04 = a01*a13 - a03*a11;
461 float b05 = a02*a13 - a03*a12;
462 float b06 = a20*a31 - a21*a30;
463 float b07 = a20*a32 - a22*a30;
464 float b08 = a20*a33 - a23*a30;
465 float b09 = a21*a32 - a22*a31;
466 float b10 = a21*a33 - a23*a31;
467 float b11 = a22*a33 - a23*a32;
468 float det = b00*b11 - b01*b10 + b02*b09 + b03*b08 - b04*b07 + b05*b06;
469 return float4x4(a11*b11 - a12*b10 + a13*b09,
470 a02*b10 - a01*b11 - a03*b09,
471 a31*b05 - a32*b04 + a33*b03,
472 a22*b04 - a21*b05 - a23*b03,
473 a12*b08 - a10*b11 - a13*b07,
474 a00*b11 - a02*b08 + a03*b07,
475 a32*b02 - a30*b05 - a33*b01,
476 a20*b05 - a22*b02 + a23*b01,
477 a10*b10 - a11*b08 + a13*b06,
478 a01*b08 - a00*b10 - a03*b06,
479 a30*b04 - a31*b02 + a33*b00,
480 a21*b02 - a20*b04 - a23*b00,
481 a11*b07 - a10*b09 - a12*b06,
482 a00*b09 - a01*b07 + a02*b06,
483 a31*b01 - a30*b03 - a32*b00,
484 a20*b03 - a21*b01 + a22*b00) * (1/det);
485}
486)";
487
John Stilesd7199b22020-12-30 16:22:58 -0500488String MetalCodeGenerator::getInversePolyfill(const ExpressionArray& arguments) {
489 // Only use polyfills for a function taking a single-argument square matrix.
490 if (arguments.size() == 1) {
491 const Type& type = arguments.front()->type();
492 if (type.isMatrix() && type.rows() == type.columns()) {
493 // Inject the correct polyfill based on the matrix size.
494 String name = this->typeName(type) + "_inverse";
495 auto [iter, didInsert] = fWrittenIntrinsics.insert(name);
496 if (didInsert) {
497 switch (type.rows()) {
498 case 2:
499 fExtraFunctions.writeText(kInverse2x2);
500 break;
501 case 3:
502 fExtraFunctions.writeText(kInverse3x3);
503 break;
504 case 4:
505 fExtraFunctions.writeText(kInverse4x4);
506 break;
507 }
508 }
509 return name;
Chris Daltondba7aab2018-11-15 10:57:49 -0500510 }
511 }
John Stilesd7199b22020-12-30 16:22:58 -0500512 // This isn't the built-in `inverse`. We don't want to polyfill it at all.
513 return "inverse";
Chris Daltondba7aab2018-11-15 10:57:49 -0500514}
515
Brian Osman93aed9a2020-12-28 15:18:46 -0500516static constexpr char kMatrixCompMult[] = R"(
517template <int C, int R>
518matrix<float, C, R> matrixCompMult(matrix<float, C, R> a, matrix<float, C, R> b) {
519 matrix<float, C, R> result;
520 for (int c = 0; c < C; ++c) {
521 result[c] = a[c] * b[c];
522 }
523 return result;
524}
525)";
526
527void MetalCodeGenerator::writeMatrixCompMult() {
528 String name = "matrixCompMult";
529 if (fWrittenIntrinsics.find(name) == fWrittenIntrinsics.end()) {
530 fWrittenIntrinsics.insert(name);
531 fExtraFunctions.writeText(kMatrixCompMult);
532 }
533}
534
John Stiles86424eb2020-12-11 11:17:14 -0500535String MetalCodeGenerator::getTempVariable(const Type& type) {
536 String tempVar = "_skTemp" + to_string(fVarCount++);
537 this->fFunctionHeader += " " + this->typeName(type) + " " + tempVar + ";\n";
538 return tempVar;
539}
540
John Stiles791c27d2020-12-30 14:56:57 -0500541void MetalCodeGenerator::writeSimpleIntrinsic(const FunctionCall& c) {
542 // Write out an intrinsic function call exactly as-is. No muss no fuss.
543 this->write(c.function().name());
John Stilesd7199b22020-12-30 16:22:58 -0500544 this->writeArgumentList(c.arguments());
545}
546
547void MetalCodeGenerator::writeArgumentList(const ExpressionArray& arguments) {
John Stiles791c27d2020-12-30 14:56:57 -0500548 this->write("(");
549 const char* separator = "";
John Stilesd7199b22020-12-30 16:22:58 -0500550 for (const std::unique_ptr<Expression>& arg : arguments) {
John Stiles791c27d2020-12-30 14:56:57 -0500551 this->write(separator);
552 separator = ", ";
Brian Osman00185012021-02-04 16:07:11 -0500553 this->writeExpression(*arg, Precedence::kSequence);
John Stiles791c27d2020-12-30 14:56:57 -0500554 }
555 this->write(")");
556}
557
John Stilesd7199b22020-12-30 16:22:58 -0500558void MetalCodeGenerator::writeIntrinsicCall(const FunctionCall& c, IntrinsicKind kind) {
John Stiles8e3b6be2020-10-13 11:14:08 -0400559 const ExpressionArray& arguments = c.arguments();
Timothy Liang6403b0e2018-05-17 10:40:04 -0400560 switch (kind) {
John Stilesd7199b22020-12-30 16:22:58 -0500561 case kTexture_IntrinsicKind: {
Brian Osman00185012021-02-04 16:07:11 -0500562 this->writeExpression(*arguments[0], Precedence::kSequence);
Timothy Lianga06f2152018-05-24 15:33:31 -0400563 this->write(".sample(");
Brian Osman00185012021-02-04 16:07:11 -0500564 this->writeExpression(*arguments[0], Precedence::kSequence);
Timothy Lianga06f2152018-05-24 15:33:31 -0400565 this->write(SAMPLER_SUFFIX);
566 this->write(", ");
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400567 const Type& arg1Type = arguments[1]->type();
John Stilesb14a8192021-04-05 11:40:46 -0400568 if (arg1Type.columns() == 3) {
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500569 // have to store the vector in a temp variable to avoid double evaluating it
John Stiles86424eb2020-12-11 11:17:14 -0500570 String tmpVar = this->getTempVariable(arg1Type);
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500571 this->write("(" + tmpVar + " = ");
Brian Osman00185012021-02-04 16:07:11 -0500572 this->writeExpression(*arguments[1], Precedence::kSequence);
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500573 this->write(", " + tmpVar + ".xy / " + tmpVar + ".z))");
Timothy Liangee84fe12018-05-18 14:38:19 -0400574 } else {
John Stilesb14a8192021-04-05 11:40:46 -0400575 SkASSERT(arg1Type.columns() == 2);
Brian Osman00185012021-02-04 16:07:11 -0500576 this->writeExpression(*arguments[1], Precedence::kSequence);
Timothy Liangee84fe12018-05-18 14:38:19 -0400577 this->write(")");
578 }
Timothy Liang6403b0e2018-05-17 10:40:04 -0400579 break;
Ethan Nicholas30d30222020-09-11 12:27:26 -0400580 }
John Stilesd7199b22020-12-30 16:22:58 -0500581 case kMod_IntrinsicKind: {
Timothy Liang651286f2018-06-07 09:55:33 -0400582 // 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 -0500583 String tmpX = this->getTempVariable(arguments[0]->type());
John Stiles61b2e812020-12-30 18:27:31 -0500584 String tmpY = this->getTempVariable(arguments[1]->type());
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500585 this->write("(" + tmpX + " = ");
Brian Osman00185012021-02-04 16:07:11 -0500586 this->writeExpression(*arguments[0], Precedence::kSequence);
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500587 this->write(", " + tmpY + " = ");
Brian Osman00185012021-02-04 16:07:11 -0500588 this->writeExpression(*arguments[1], Precedence::kSequence);
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500589 this->write(", " + tmpX + " - " + tmpY + " * floor(" + tmpX + " / " + tmpY + "))");
Timothy Liang651286f2018-06-07 09:55:33 -0400590 break;
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500591 }
Brian Osman46787d52020-11-24 14:18:23 -0500592 // GLSL declares scalar versions of most geometric intrinsics, but these don't exist in MSL
John Stilesd7199b22020-12-30 16:22:58 -0500593 case kDistance_IntrinsicKind: {
Brian Osman46787d52020-11-24 14:18:23 -0500594 if (arguments[0]->type().columns() == 1) {
595 this->write("abs(");
Brian Osman00185012021-02-04 16:07:11 -0500596 this->writeExpression(*arguments[0], Precedence::kAdditive);
Brian Osman46787d52020-11-24 14:18:23 -0500597 this->write(" - ");
Brian Osman00185012021-02-04 16:07:11 -0500598 this->writeExpression(*arguments[1], Precedence::kAdditive);
Brian Osman46787d52020-11-24 14:18:23 -0500599 this->write(")");
600 } else {
John Stiles791c27d2020-12-30 14:56:57 -0500601 this->writeSimpleIntrinsic(c);
Brian Osman46787d52020-11-24 14:18:23 -0500602 }
603 break;
604 }
John Stilesd7199b22020-12-30 16:22:58 -0500605 case kDot_IntrinsicKind: {
Brian Osman46787d52020-11-24 14:18:23 -0500606 if (arguments[0]->type().columns() == 1) {
607 this->write("(");
Brian Osman00185012021-02-04 16:07:11 -0500608 this->writeExpression(*arguments[0], Precedence::kMultiplicative);
Brian Osman46787d52020-11-24 14:18:23 -0500609 this->write(" * ");
Brian Osman00185012021-02-04 16:07:11 -0500610 this->writeExpression(*arguments[1], Precedence::kMultiplicative);
Brian Osman46787d52020-11-24 14:18:23 -0500611 this->write(")");
612 } else {
John Stiles791c27d2020-12-30 14:56:57 -0500613 this->writeSimpleIntrinsic(c);
Brian Osman46787d52020-11-24 14:18:23 -0500614 }
615 break;
616 }
John Stilesd7199b22020-12-30 16:22:58 -0500617 case kFaceforward_IntrinsicKind: {
John Stilesad0571f2020-12-10 18:03:10 -0500618 if (arguments[0]->type().columns() == 1) {
619 // ((((Nref) * (I) < 0) ? 1 : -1) * (N))
620 this->write("((((");
Brian Osman00185012021-02-04 16:07:11 -0500621 this->writeExpression(*arguments[2], Precedence::kSequence);
John Stilesad0571f2020-12-10 18:03:10 -0500622 this->write(") * (");
Brian Osman00185012021-02-04 16:07:11 -0500623 this->writeExpression(*arguments[1], Precedence::kSequence);
John Stilesad0571f2020-12-10 18:03:10 -0500624 this->write(") < 0) ? 1 : -1) * (");
Brian Osman00185012021-02-04 16:07:11 -0500625 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stilesad0571f2020-12-10 18:03:10 -0500626 this->write("))");
627 } else {
John Stiles791c27d2020-12-30 14:56:57 -0500628 this->writeSimpleIntrinsic(c);
John Stilesad0571f2020-12-10 18:03:10 -0500629 }
630 break;
631 }
John Stilesd7199b22020-12-30 16:22:58 -0500632 case kLength_IntrinsicKind: {
Brian Osman46787d52020-11-24 14:18:23 -0500633 this->write(arguments[0]->type().columns() == 1 ? "abs(" : "length(");
Brian Osman00185012021-02-04 16:07:11 -0500634 this->writeExpression(*arguments[0], Precedence::kSequence);
Brian Osman46787d52020-11-24 14:18:23 -0500635 this->write(")");
636 break;
637 }
John Stilesd7199b22020-12-30 16:22:58 -0500638 case kNormalize_IntrinsicKind: {
Brian Osman46787d52020-11-24 14:18:23 -0500639 this->write(arguments[0]->type().columns() == 1 ? "sign(" : "normalize(");
Brian Osman00185012021-02-04 16:07:11 -0500640 this->writeExpression(*arguments[0], Precedence::kSequence);
Brian Osman46787d52020-11-24 14:18:23 -0500641 this->write(")");
642 break;
643 }
John Stilesd7199b22020-12-30 16:22:58 -0500644 case kBitcast_IntrinsicKind: {
John Stiles0063a9f2020-12-10 18:01:45 -0500645 this->write(this->getBitcastIntrinsic(c.type()));
646 this->write("(");
Brian Osman00185012021-02-04 16:07:11 -0500647 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stiles0063a9f2020-12-10 18:01:45 -0500648 this->write(")");
649 break;
650 }
John Stilesd7199b22020-12-30 16:22:58 -0500651 case kDegrees_IntrinsicKind: {
John Stilese2d34f82020-12-10 18:02:02 -0500652 this->write("((");
Brian Osman00185012021-02-04 16:07:11 -0500653 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stilese2d34f82020-12-10 18:02:02 -0500654 this->write(") * 57.2957795)");
655 break;
656 }
John Stilesd7199b22020-12-30 16:22:58 -0500657 case kRadians_IntrinsicKind: {
John Stilese2d34f82020-12-10 18:02:02 -0500658 this->write("((");
Brian Osman00185012021-02-04 16:07:11 -0500659 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stilese2d34f82020-12-10 18:02:02 -0500660 this->write(") * 0.0174532925)");
661 break;
662 }
John Stilesd7199b22020-12-30 16:22:58 -0500663 case kDFdx_IntrinsicKind: {
664 this->write("dfdx");
665 this->writeArgumentList(c.arguments());
666 break;
667 }
668 case kDFdy_IntrinsicKind: {
669 // Flipping Y also negates the Y derivatives.
John Stiles270cec22021-02-17 12:59:36 -0500670 if (fProgram.fConfig->fSettings.fFlipY) {
John Stilesd7199b22020-12-30 16:22:58 -0500671 this->write("-");
672 }
673 this->write("dfdy");
674 this->writeArgumentList(c.arguments());
675 break;
676 }
677 case kInverse_IntrinsicKind: {
678 this->write(this->getInversePolyfill(arguments));
679 this->writeArgumentList(c.arguments());
680 break;
681 }
682 case kInversesqrt_IntrinsicKind: {
683 this->write("rsqrt");
684 this->writeArgumentList(c.arguments());
685 break;
686 }
687 case kAtan_IntrinsicKind: {
688 this->write(c.arguments().size() == 2 ? "atan2" : "atan");
689 this->writeArgumentList(c.arguments());
690 break;
691 }
692 case kReflect_IntrinsicKind: {
John Stiles791c27d2020-12-30 14:56:57 -0500693 if (arguments[0]->type().columns() == 1) {
694 // We need to synthesize `I - 2 * N * I * N`.
695 String tmpI = this->getTempVariable(arguments[0]->type());
696 String tmpN = this->getTempVariable(arguments[1]->type());
697
698 // (_skTempI = ...
699 this->write("(" + tmpI + " = ");
Brian Osman00185012021-02-04 16:07:11 -0500700 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stiles791c27d2020-12-30 14:56:57 -0500701
702 // , _skTempN = ...
703 this->write(", " + tmpN + " = ");
Brian Osman00185012021-02-04 16:07:11 -0500704 this->writeExpression(*arguments[1], Precedence::kSequence);
John Stiles791c27d2020-12-30 14:56:57 -0500705
706 // , _skTempI - 2 * _skTempN * _skTempI * _skTempN)
707 this->write(", " + tmpI + " - 2 * " + tmpN + " * " + tmpI + " * " + tmpN + ")");
708 } else {
709 this->writeSimpleIntrinsic(c);
710 }
711 break;
712 }
John Stilesd7199b22020-12-30 16:22:58 -0500713 case kRefract_IntrinsicKind: {
John Stiles4b783d62020-12-30 14:58:07 -0500714 if (arguments[0]->type().columns() == 1) {
715 // Metal does implement refract for vectors; rather than reimplementing refract from
716 // scratch, we can replace the call with `refract(float2(I,0), float2(N,0), eta).x`.
717 this->write("(refract(float2(");
Brian Osman00185012021-02-04 16:07:11 -0500718 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stiles4b783d62020-12-30 14:58:07 -0500719 this->write(", 0), float2(");
Brian Osman00185012021-02-04 16:07:11 -0500720 this->writeExpression(*arguments[1], Precedence::kSequence);
John Stiles4b783d62020-12-30 14:58:07 -0500721 this->write(", 0), ");
Brian Osman00185012021-02-04 16:07:11 -0500722 this->writeExpression(*arguments[2], Precedence::kSequence);
John Stiles4b783d62020-12-30 14:58:07 -0500723 this->write(").x)");
724 } else {
725 this->writeSimpleIntrinsic(c);
726 }
727 break;
728 }
John Stiles23456532020-12-30 18:12:48 -0500729 case kRoundEven_IntrinsicKind: {
730 this->write("rint");
731 this->writeArgumentList(c.arguments());
732 break;
733 }
John Stilesd7199b22020-12-30 16:22:58 -0500734 case kBitCount_IntrinsicKind: {
John Stilese7dc7cb2020-12-22 15:37:14 -0500735 this->write("popcount(");
Brian Osman00185012021-02-04 16:07:11 -0500736 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stilese7dc7cb2020-12-22 15:37:14 -0500737 this->write(")");
738 break;
739 }
John Stilesd7199b22020-12-30 16:22:58 -0500740 case kFindLSB_IntrinsicKind: {
John Stiles86424eb2020-12-11 11:17:14 -0500741 // Create a temp variable to store the expression, to avoid double-evaluating it.
742 String skTemp = this->getTempVariable(arguments[0]->type());
743 String exprType = this->typeName(arguments[0]->type());
744
745 // ctz returns numbits(type) on zero inputs; GLSL documents it as generating -1 instead.
746 // Use select to detect zero inputs and force a -1 result.
747
748 // (_skTemp1 = (.....), select(ctz(_skTemp1), int4(-1), _skTemp1 == int4(0)))
749 this->write("(");
750 this->write(skTemp);
751 this->write(" = (");
Brian Osman00185012021-02-04 16:07:11 -0500752 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stiles86424eb2020-12-11 11:17:14 -0500753 this->write("), select(ctz(");
754 this->write(skTemp);
755 this->write("), ");
756 this->write(exprType);
757 this->write("(-1), ");
758 this->write(skTemp);
759 this->write(" == ");
760 this->write(exprType);
761 this->write("(0)))");
762 break;
763 }
John Stilesd7199b22020-12-30 16:22:58 -0500764 case kFindMSB_IntrinsicKind: {
John Stiles9685e522020-12-14 11:52:14 -0500765 // Create a temp variable to store the expression, to avoid double-evaluating it.
766 String skTemp1 = this->getTempVariable(arguments[0]->type());
767 String exprType = this->typeName(arguments[0]->type());
768
769 // GLSL findMSB is actually quite different from Metal's clz:
770 // - For signed negative numbers, it returns the first zero bit, not the first one bit!
771 // - For an empty input (0/~0 depending on sign), findMSB gives -1; clz is numbits(type)
772
773 // (_skTemp1 = (.....),
774 this->write("(");
775 this->write(skTemp1);
776 this->write(" = (");
Brian Osman00185012021-02-04 16:07:11 -0500777 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stiles9685e522020-12-14 11:52:14 -0500778 this->write("), ");
779
780 // Signed input types might be negative; we need another helper variable to negate the
781 // input (since we can only find one bits, not zero bits).
782 String skTemp2;
783 if (arguments[0]->type().isSigned()) {
784 // ... _skTemp2 = (select(_skTemp1, ~_skTemp1, _skTemp1 < 0)),
785 skTemp2 = this->getTempVariable(arguments[0]->type());
786 this->write(skTemp2);
787 this->write(" = (select(");
788 this->write(skTemp1);
789 this->write(", ~");
790 this->write(skTemp1);
791 this->write(", ");
792 this->write(skTemp1);
793 this->write(" < 0)), ");
794 } else {
795 skTemp2 = skTemp1;
796 }
797
798 // ... select(int4(clz(_skTemp2)), int4(-1), _skTemp2 == int4(0)))
799 this->write("select(");
800 this->write(this->typeName(c.type()));
801 this->write("(clz(");
802 this->write(skTemp2);
803 this->write(")), ");
804 this->write(this->typeName(c.type()));
805 this->write("(-1), ");
806 this->write(skTemp2);
807 this->write(" == ");
808 this->write(exprType);
809 this->write("(0)))");
810 break;
811 }
John Stilesd7199b22020-12-30 16:22:58 -0500812 case kMatrixCompMult_IntrinsicKind: {
813 this->writeMatrixCompMult();
814 this->writeSimpleIntrinsic(c);
815 break;
816 }
817 case kCompareEqual_IntrinsicKind:
818 case kCompareGreaterThan_IntrinsicKind:
819 case kCompareGreaterThanEqual_IntrinsicKind:
820 case kCompareLessThan_IntrinsicKind:
821 case kCompareLessThanEqual_IntrinsicKind:
822 case kCompareNotEqual_IntrinsicKind: {
823 this->write("(");
Brian Osman00185012021-02-04 16:07:11 -0500824 this->writeExpression(*c.arguments()[0], Precedence::kRelational);
John Stilesd7199b22020-12-30 16:22:58 -0500825 switch (kind) {
826 case kCompareEqual_IntrinsicKind:
827 this->write(" == ");
828 break;
829 case kCompareNotEqual_IntrinsicKind:
830 this->write(" != ");
831 break;
832 case kCompareLessThan_IntrinsicKind:
833 this->write(" < ");
834 break;
835 case kCompareLessThanEqual_IntrinsicKind:
836 this->write(" <= ");
837 break;
838 case kCompareGreaterThan_IntrinsicKind:
839 this->write(" > ");
840 break;
841 case kCompareGreaterThanEqual_IntrinsicKind:
842 this->write(" >= ");
843 break;
844 default:
John Stilesf57207b2021-02-02 17:50:34 -0500845 SK_ABORT("unsupported comparison intrinsic kind");
John Stilesd7199b22020-12-30 16:22:58 -0500846 }
Brian Osman00185012021-02-04 16:07:11 -0500847 this->writeExpression(*c.arguments()[1], Precedence::kRelational);
John Stilesd7199b22020-12-30 16:22:58 -0500848 this->write(")");
849 break;
850 }
Timothy Liang6403b0e2018-05-17 10:40:04 -0400851 default:
John Stilesf57207b2021-02-02 17:50:34 -0500852 SK_ABORT("unsupported intrinsic kind");
Timothy Liang6403b0e2018-05-17 10:40:04 -0400853 }
854}
855
John Stilesfcf8cb22020-08-06 14:29:22 -0400856// Assembles a matrix of type floatRxC by resizing another matrix named `x0`.
857// Cells that don't exist in the source matrix will be populated with identity-matrix values.
858void MetalCodeGenerator::assembleMatrixFromMatrix(const Type& sourceMatrix, int rows, int columns) {
859 SkASSERT(rows <= 4);
860 SkASSERT(columns <= 4);
861
862 const char* columnSeparator = "";
863 for (int c = 0; c < columns; ++c) {
864 fExtraFunctions.printf("%sfloat%d(", columnSeparator, rows);
865 columnSeparator = "), ";
866
867 // Determine how many values to take from the source matrix for this row.
868 int swizzleLength = 0;
869 if (c < sourceMatrix.columns()) {
870 swizzleLength = std::min<>(rows, sourceMatrix.rows());
871 }
872
873 // Emit all the values from the source matrix row.
874 bool firstItem;
875 switch (swizzleLength) {
876 case 0: firstItem = true; break;
877 case 1: firstItem = false; fExtraFunctions.printf("x0[%d].x", c); break;
878 case 2: firstItem = false; fExtraFunctions.printf("x0[%d].xy", c); break;
879 case 3: firstItem = false; fExtraFunctions.printf("x0[%d].xyz", c); break;
880 case 4: firstItem = false; fExtraFunctions.printf("x0[%d].xyzw", c); break;
881 default: SkUNREACHABLE;
882 }
883
884 // Emit the placeholder identity-matrix cells.
885 for (int r = swizzleLength; r < rows; ++r) {
886 fExtraFunctions.printf("%s%s", firstItem ? "" : ", ", (r == c) ? "1.0" : "0.0");
887 firstItem = false;
888 }
889 }
890
891 fExtraFunctions.writeText(")");
892}
893
894// Assembles a matrix of type floatRxC by concatenating an arbitrary mix of values, named `x0`,
895// `x1`, etc. An error is written if the expression list don't contain exactly R*C scalars.
John Stiles5abb9e12021-04-06 13:47:19 -0400896void MetalCodeGenerator::assembleMatrixFromExpressions(const AnyConstructor& ctor,
John Stiles8e3b6be2020-10-13 11:14:08 -0400897 int rows, int columns) {
John Stilesfcf8cb22020-08-06 14:29:22 -0400898 size_t argIndex = 0;
899 int argPosition = 0;
John Stiles5abb9e12021-04-06 13:47:19 -0400900 auto args = ctor.argumentSpan();
John Stilesfcf8cb22020-08-06 14:29:22 -0400901
902 const char* columnSeparator = "";
903 for (int c = 0; c < columns; ++c) {
904 fExtraFunctions.printf("%sfloat%d(", columnSeparator, rows);
905 columnSeparator = "), ";
906
907 const char* rowSeparator = "";
908 for (int r = 0; r < rows; ++r) {
909 fExtraFunctions.writeText(rowSeparator);
910 rowSeparator = ", ";
911
912 if (argIndex < args.size()) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400913 const Type& argType = args[argIndex]->type();
Ethan Nicholase6592142020-09-08 10:22:09 -0400914 switch (argType.typeKind()) {
915 case Type::TypeKind::kScalar: {
John Stilesfcf8cb22020-08-06 14:29:22 -0400916 fExtraFunctions.printf("x%zu", argIndex);
917 break;
918 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400919 case Type::TypeKind::kVector: {
John Stilesfcf8cb22020-08-06 14:29:22 -0400920 fExtraFunctions.printf("x%zu[%d]", argIndex, argPosition);
921 break;
922 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400923 case Type::TypeKind::kMatrix: {
John Stilesfcf8cb22020-08-06 14:29:22 -0400924 fExtraFunctions.printf("x%zu[%d][%d]", argIndex,
925 argPosition / argType.rows(),
926 argPosition % argType.rows());
927 break;
928 }
929 default: {
930 SkDEBUGFAIL("incorrect type of argument for matrix constructor");
931 fExtraFunctions.writeText("<error>");
932 break;
933 }
934 }
935
936 ++argPosition;
937 if (argPosition >= argType.columns() * argType.rows()) {
938 ++argIndex;
939 argPosition = 0;
940 }
941 } else {
942 SkDEBUGFAIL("not enough arguments for matrix constructor");
943 fExtraFunctions.writeText("<error>");
944 }
945 }
946 }
947
948 if (argPosition != 0 || argIndex != args.size()) {
949 SkDEBUGFAIL("incorrect number of arguments for matrix constructor");
950 fExtraFunctions.writeText(", <error>");
951 }
952
953 fExtraFunctions.writeText(")");
954}
955
John Stiles1bdafbf2020-05-28 12:17:20 -0400956// Generates a constructor for 'matrix' which reorganizes the input arguments into the proper shape.
957// Keeps track of previously generated constructors so that we won't generate more than one
958// constructor for any given permutation of input argument types. Returns the name of the
959// generated constructor method.
John Stiles5abb9e12021-04-06 13:47:19 -0400960String MetalCodeGenerator::getMatrixConstructHelper(const AnyConstructor& c) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400961 const Type& matrix = c.type();
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500962 int columns = matrix.columns();
963 int rows = matrix.rows();
John Stiles5abb9e12021-04-06 13:47:19 -0400964 auto args = c.argumentSpan();
John Stiles1bdafbf2020-05-28 12:17:20 -0400965
966 // Create the helper-method name and use it as our lookup key.
967 String name;
968 name.appendf("float%dx%d_from", columns, rows);
969 for (const std::unique_ptr<Expression>& expr : args) {
John Stiles36129132020-12-29 12:28:04 -0500970 name.appendf("_%s", this->typeName(expr->type()).c_str());
John Stiles1bdafbf2020-05-28 12:17:20 -0400971 }
972
973 // If a helper-method has already been synthesized, we don't need to synthesize it again.
974 auto [iter, newlyCreated] = fHelpers.insert(name);
975 if (!newlyCreated) {
976 return name;
977 }
978
979 // Unlike GLSL, Metal requires that matrices are initialized with exactly R vectors of C
980 // components apiece. (In Metal 2.0, you can also supply R*C scalars, but you still cannot
981 // supply a mixture of scalars and vectors.)
982 fExtraFunctions.printf("float%dx%d %s(", columns, rows, name.c_str());
983
984 size_t argIndex = 0;
985 const char* argSeparator = "";
John Stilesfcf8cb22020-08-06 14:29:22 -0400986 for (const std::unique_ptr<Expression>& expr : args) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400987 fExtraFunctions.printf("%s%s x%zu", argSeparator,
John Stiles36129132020-12-29 12:28:04 -0500988 this->typeName(expr->type()).c_str(), argIndex++);
John Stiles1bdafbf2020-05-28 12:17:20 -0400989 argSeparator = ", ";
990 }
991
992 fExtraFunctions.printf(") {\n return float%dx%d(", columns, rows);
993
John Stiles9aeed132020-11-24 17:36:06 -0500994 if (args.size() == 1 && args.front()->type().isMatrix()) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400995 this->assembleMatrixFromMatrix(args.front()->type(), rows, columns);
John Stilesfcf8cb22020-08-06 14:29:22 -0400996 } else {
John Stiles5abb9e12021-04-06 13:47:19 -0400997 this->assembleMatrixFromExpressions(c, rows, columns);
John Stiles1bdafbf2020-05-28 12:17:20 -0400998 }
999
John Stilesfcf8cb22020-08-06 14:29:22 -04001000 fExtraFunctions.writeText(");\n}\n");
Ethan Nicholas842d31b2019-01-22 10:59:11 -05001001 return name;
1002}
1003
1004bool MetalCodeGenerator::canCoerce(const Type& t1, const Type& t2) {
1005 if (t1.columns() != t2.columns() || t1.rows() != t2.rows()) {
1006 return false;
1007 }
1008 if (t1.columns() > 1) {
1009 return this->canCoerce(t1.componentType(), t2.componentType());
1010 }
Ethan Nicholase1f55022019-02-05 17:17:40 -05001011 return t1.isFloat() && t2.isFloat();
Ethan Nicholas842d31b2019-01-22 10:59:11 -05001012}
1013
John Stiles8cad6372021-04-07 12:31:13 -04001014bool MetalCodeGenerator::matrixConstructHelperIsNeeded(const ConstructorCompound& c) {
John Stiles2bec8ab2021-04-06 18:40:04 -04001015 SkASSERT(c.type().isMatrix());
John Stiles1bdafbf2020-05-28 12:17:20 -04001016
1017 // GLSL is fairly free-form about inputs to its matrix constructors, but Metal is not; it
1018 // expects exactly R vectors of C components apiece. (Metal 2.0 also allows a list of R*C
1019 // scalars.) Some cases are simple to translate and so we handle those inline--e.g. a list of
1020 // scalars can be constructed trivially. In more complex cases, we generate a helper function
1021 // that converts our inputs into a properly-shaped matrix.
1022 // A matrix construct helper method is always used if any input argument is a matrix.
1023 // Helper methods are also necessary when any argument would span multiple rows. For instance:
1024 //
1025 // float2 x = (1, 2);
1026 // float3x2(x, 3, 4, 5, 6) = | 1 3 5 | = no helper needed; conversion can be done inline
1027 // | 2 4 6 |
1028 //
1029 // float2 x = (2, 3);
1030 // float3x2(1, x, 4, 5, 6) = | 1 3 5 | = x spans multiple rows; a helper method will be used
1031 // | 2 4 6 |
1032 //
1033 // float4 x = (1, 2, 3, 4);
1034 // float2x2(x) = | 1 3 | = x spans multiple rows; a helper method will be used
1035 // | 2 4 |
1036 //
1037
1038 int position = 0;
Ethan Nicholasf70f0442020-09-29 12:41:35 -04001039 for (const std::unique_ptr<Expression>& expr : c.arguments()) {
John Stiles1bdafbf2020-05-28 12:17:20 -04001040 // If an input argument is a matrix, we need a helper function.
John Stiles9aeed132020-11-24 17:36:06 -05001041 if (expr->type().isMatrix()) {
John Stiles1bdafbf2020-05-28 12:17:20 -04001042 return true;
1043 }
Ethan Nicholas30d30222020-09-11 12:27:26 -04001044 position += expr->type().columns();
1045 if (position > c.type().rows()) {
John Stiles1bdafbf2020-05-28 12:17:20 -04001046 // An input argument would span multiple rows; a helper function is required.
1047 return true;
1048 }
Ethan Nicholas30d30222020-09-11 12:27:26 -04001049 if (position == c.type().rows()) {
John Stiles1bdafbf2020-05-28 12:17:20 -04001050 // We've advanced to the end of a row. Wrap to the start of the next row.
1051 position = 0;
1052 }
1053 }
1054
1055 return false;
1056}
1057
John Stiles5abb9e12021-04-06 13:47:19 -04001058void MetalCodeGenerator::writeConstructorMatrixResize(const ConstructorMatrixResize& c,
1059 Precedence parentPrecedence) {
1060 // Matrix-resize via casting doesn't natively exist in Metal at all, so we always need to use a
1061 // matrix-construct helper here.
1062 this->write(this->getMatrixConstructHelper(c));
1063 this->write("(");
1064 this->writeExpression(*c.argument(), Precedence::kSequence);
1065 this->write(")");
1066}
1067
John Stiles8cad6372021-04-07 12:31:13 -04001068void MetalCodeGenerator::writeConstructorCompound(const ConstructorCompound& c,
1069 Precedence parentPrecedence) {
John Stiles2bec8ab2021-04-06 18:40:04 -04001070 if (c.type().isMatrix()) {
John Stiles8cad6372021-04-07 12:31:13 -04001071 this->writeConstructorCompoundMatrix(c, parentPrecedence);
John Stiles2bec8ab2021-04-06 18:40:04 -04001072 } else {
1073 this->writeAnyConstructor(c, "(", ")", parentPrecedence);
1074 }
1075}
John Stiles7384b372021-04-01 13:48:15 -04001076
John Stiles8cad6372021-04-07 12:31:13 -04001077void MetalCodeGenerator::writeConstructorCompoundMatrix(const ConstructorCompound& c,
1078 Precedence parentPrecedence) {
John Stiles1bdafbf2020-05-28 12:17:20 -04001079 // Emit and invoke a matrix-constructor helper method if one is necessary.
1080 if (this->matrixConstructHelperIsNeeded(c)) {
1081 this->write(this->getMatrixConstructHelper(c));
John Stiles1fa15b12020-05-28 17:36:54 +00001082 this->write("(");
1083 const char* separator = "";
Ethan Nicholasf70f0442020-09-29 12:41:35 -04001084 for (const std::unique_ptr<Expression>& expr : c.arguments()) {
John Stiles1fa15b12020-05-28 17:36:54 +00001085 this->write(separator);
1086 separator = ", ";
Brian Osman00185012021-02-04 16:07:11 -05001087 this->writeExpression(*expr, Precedence::kSequence);
John Stilesdaa573e2020-05-28 12:17:20 -04001088 }
John Stiles1fa15b12020-05-28 17:36:54 +00001089 this->write(")");
John Stiles1bdafbf2020-05-28 12:17:20 -04001090 return;
John Stilesdaa573e2020-05-28 12:17:20 -04001091 }
John Stiles1bdafbf2020-05-28 12:17:20 -04001092
John Stiles2bec8ab2021-04-06 18:40:04 -04001093 // Metal doesn't allow creating matrices by passing in scalars and vectors in a jumble; it
1094 // requires your scalars to be grouped up into columns. Because `matrixConstructHelperIsNeeded`
1095 // returned false, we know that none of our scalars/vectors "wrap" across across a column, so we
1096 // can group our inputs up and synthesize a constructor for each column.
1097 const Type& matrixType = c.type();
1098 const Type& columnType = matrixType.componentType().toCompound(
1099 fContext, /*columns=*/matrixType.rows(), /*rows=*/1);
1100
1101 this->writeType(matrixType);
John Stiles7384b372021-04-01 13:48:15 -04001102 this->write("(");
John Stiles1bdafbf2020-05-28 12:17:20 -04001103 const char* separator = "";
1104 int scalarCount = 0;
Ethan Nicholasf70f0442020-09-29 12:41:35 -04001105 for (const std::unique_ptr<Expression>& arg : c.arguments()) {
John Stiles1bdafbf2020-05-28 12:17:20 -04001106 this->write(separator);
1107 separator = ", ";
John Stiles2bec8ab2021-04-06 18:40:04 -04001108 if (arg->type().columns() < matrixType.rows()) {
1109 // Write a `floatN(` constructor to group scalars and smaller vectors together.
John Stiles1bdafbf2020-05-28 12:17:20 -04001110 if (!scalarCount) {
John Stiles2bec8ab2021-04-06 18:40:04 -04001111 this->writeType(columnType);
John Stiles1bdafbf2020-05-28 12:17:20 -04001112 this->write("(");
1113 }
John Stiles2bec8ab2021-04-06 18:40:04 -04001114 scalarCount += arg->type().columns();
John Stiles1bdafbf2020-05-28 12:17:20 -04001115 }
Brian Osman00185012021-02-04 16:07:11 -05001116 this->writeExpression(*arg, Precedence::kSequence);
John Stiles2bec8ab2021-04-06 18:40:04 -04001117 if (scalarCount && scalarCount == matrixType.rows()) {
1118 // Close our `floatN(...` constructor block from above.
John Stiles1bdafbf2020-05-28 12:17:20 -04001119 this->write(")");
1120 scalarCount = 0;
1121 }
1122 }
John Stiles7384b372021-04-01 13:48:15 -04001123 this->write(")");
Ethan Nicholascc305772017-10-13 16:17:45 -04001124}
1125
John Stilesb14a8192021-04-05 11:40:46 -04001126void MetalCodeGenerator::writeAnyConstructor(const AnyConstructor& c,
1127 const char* leftBracket,
1128 const char* rightBracket,
1129 Precedence parentPrecedence) {
John Stilese1182782021-03-30 22:09:37 -04001130 this->writeType(c.type());
John Stilesb14a8192021-04-05 11:40:46 -04001131 this->write(leftBracket);
John Stiles7384b372021-04-01 13:48:15 -04001132 const char* separator = "";
John Stilesb14a8192021-04-05 11:40:46 -04001133 for (const std::unique_ptr<Expression>& arg : c.argumentSpan()) {
John Stiles7384b372021-04-01 13:48:15 -04001134 this->write(separator);
1135 separator = ", ";
1136 this->writeExpression(*arg, Precedence::kSequence);
1137 }
John Stilesb14a8192021-04-05 11:40:46 -04001138 this->write(rightBracket);
John Stiles7384b372021-04-01 13:48:15 -04001139}
1140
John Stilesb14a8192021-04-05 11:40:46 -04001141void MetalCodeGenerator::writeCastConstructor(const AnyConstructor& c,
1142 const char* leftBracket,
1143 const char* rightBracket,
1144 Precedence parentPrecedence) {
1145 // If the type is coercible, emit it directly without the cast.
1146 auto args = c.argumentSpan();
1147 if (args.size() == 1) {
1148 if (this->canCoerce(c.type(), args.front()->type())) {
1149 this->writeExpression(*args.front(), parentPrecedence);
1150 return;
1151 }
John Stilesfd7252f2021-04-04 22:24:40 -04001152 }
1153
John Stilesb14a8192021-04-05 11:40:46 -04001154 return this->writeAnyConstructor(c, leftBracket, rightBracket, parentPrecedence);
John Stilesfd7252f2021-04-04 22:24:40 -04001155}
1156
Ethan Nicholascc305772017-10-13 16:17:45 -04001157void MetalCodeGenerator::writeFragCoord() {
Ethan Nicholasf931e402019-07-26 15:40:33 -04001158 if (fRTHeightName.length()) {
1159 this->write("float4(_fragCoord.x, ");
1160 this->write(fRTHeightName.c_str());
1161 this->write(" - _fragCoord.y, 0.0, _fragCoord.w)");
Jim Van Verth6bc650e2019-02-07 14:53:23 -05001162 } else {
1163 this->write("float4(_fragCoord.x, _fragCoord.y, 0.0, _fragCoord.w)");
1164 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001165}
1166
1167void MetalCodeGenerator::writeVariableReference(const VariableReference& ref) {
John Stiles06b84ef2020-12-09 12:35:48 -05001168 // When assembling out-param helper functions, we copy variables into local clones with matching
John Stilesf7410bd2021-01-19 13:07:55 -05001169 // names. We never want to prepend "_in." or "_globals." when writing these variables since
John Stiles06b84ef2020-12-09 12:35:48 -05001170 // we're actually targeting the clones.
1171 if (fIgnoreVariableReferenceModifiers) {
1172 this->writeName(ref.variable()->name());
1173 return;
1174 }
1175
Ethan Nicholas78686922020-10-08 06:46:27 -04001176 switch (ref.variable()->modifiers().fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001177 case SK_FRAGCOLOR_BUILTIN:
John Stilesf7410bd2021-01-19 13:07:55 -05001178 this->write("_out.sk_FragColor");
Ethan Nicholascc305772017-10-13 16:17:45 -04001179 break;
Timothy Liang6403b0e2018-05-17 10:40:04 -04001180 case SK_FRAGCOORD_BUILTIN:
1181 this->writeFragCoord();
1182 break;
Timothy Liangdc89f192018-06-13 09:20:31 -04001183 case SK_VERTEXID_BUILTIN:
1184 this->write("sk_VertexID");
1185 break;
1186 case SK_INSTANCEID_BUILTIN:
1187 this->write("sk_InstanceID");
1188 break;
Timothy Liang7b8875d2018-08-10 09:42:31 -04001189 case SK_CLOCKWISE_BUILTIN:
1190 // We'd set the front facing winding in the MTLRenderCommandEncoder to be counter
Brian Salomonf4ba4ec2020-03-19 15:54:28 -04001191 // clockwise to match Skia convention.
John Stiles270cec22021-02-17 12:59:36 -05001192 this->write(fProgram.fConfig->fSettings.fFlipY ? "_frontFacing" : "(!_frontFacing)");
Timothy Liang7b8875d2018-08-10 09:42:31 -04001193 break;
Ethan Nicholascc305772017-10-13 16:17:45 -04001194 default:
Ethan Nicholas78686922020-10-08 06:46:27 -04001195 const Variable& var = *ref.variable();
Ethan Nicholas453f67f2020-10-09 10:43:45 -04001196 if (var.storage() == Variable::Storage::kGlobal) {
Ethan Nicholas78686922020-10-08 06:46:27 -04001197 if (var.modifiers().fFlags & Modifiers::kIn_Flag) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001198 this->write("_in.");
Ethan Nicholas78686922020-10-08 06:46:27 -04001199 } else if (var.modifiers().fFlags & Modifiers::kOut_Flag) {
John Stilesf7410bd2021-01-19 13:07:55 -05001200 this->write("_out.");
Ethan Nicholas78686922020-10-08 06:46:27 -04001201 } else if (var.modifiers().fFlags & Modifiers::kUniform_Flag &&
1202 var.type().typeKind() != Type::TypeKind::kSampler) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001203 this->write("_uniforms.");
1204 } else {
John Stilesf7410bd2021-01-19 13:07:55 -05001205 this->write("_globals.");
Ethan Nicholascc305772017-10-13 16:17:45 -04001206 }
1207 }
Ethan Nicholas78686922020-10-08 06:46:27 -04001208 this->writeName(var.name());
Ethan Nicholascc305772017-10-13 16:17:45 -04001209 }
1210}
1211
1212void MetalCodeGenerator::writeIndexExpression(const IndexExpression& expr) {
Brian Osman00185012021-02-04 16:07:11 -05001213 this->writeExpression(*expr.base(), Precedence::kPostfix);
Ethan Nicholascc305772017-10-13 16:17:45 -04001214 this->write("[");
Brian Osman00185012021-02-04 16:07:11 -05001215 this->writeExpression(*expr.index(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001216 this->write("]");
1217}
1218
1219void MetalCodeGenerator::writeFieldAccess(const FieldAccess& f) {
Ethan Nicholas7a95b202020-10-09 11:55:40 -04001220 const Type::Field* field = &f.base()->type().fields()[f.fieldIndex()];
1221 if (FieldAccess::OwnerKind::kDefault == f.ownerKind()) {
Brian Osman00185012021-02-04 16:07:11 -05001222 this->writeExpression(*f.base(), Precedence::kPostfix);
Ethan Nicholascc305772017-10-13 16:17:45 -04001223 this->write(".");
1224 }
Timothy Liang7d637782018-06-05 09:58:07 -04001225 switch (field->fModifiers.fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001226 case SK_POSITION_BUILTIN:
John Stilesf7410bd2021-01-19 13:07:55 -05001227 this->write("_out.sk_Position");
Ethan Nicholascc305772017-10-13 16:17:45 -04001228 break;
1229 default:
Timothy Liang7d637782018-06-05 09:58:07 -04001230 if (field->fName == "sk_PointSize") {
John Stilesf7410bd2021-01-19 13:07:55 -05001231 this->write("_out.sk_PointSize");
Timothy Liang7d637782018-06-05 09:58:07 -04001232 } else {
Ethan Nicholas7a95b202020-10-09 11:55:40 -04001233 if (FieldAccess::OwnerKind::kAnonymousInterfaceBlock == f.ownerKind()) {
John Stilesf7410bd2021-01-19 13:07:55 -05001234 this->write("_globals.");
Timothy Liang7d637782018-06-05 09:58:07 -04001235 this->write(fInterfaceBlockNameMap[fInterfaceBlockMap[field]]);
1236 this->write("->");
1237 }
Timothy Liang651286f2018-06-07 09:55:33 -04001238 this->writeName(field->fName);
Timothy Lianga06f2152018-05-24 15:33:31 -04001239 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001240 }
1241}
1242
1243void MetalCodeGenerator::writeSwizzle(const Swizzle& swizzle) {
Brian Osman00185012021-02-04 16:07:11 -05001244 this->writeExpression(*swizzle.base(), Precedence::kPostfix);
Ethan Nicholascc305772017-10-13 16:17:45 -04001245 this->write(".");
Ethan Nicholas6b4d5812020-10-12 16:11:51 -04001246 for (int c : swizzle.components()) {
Brian Osman25647672020-09-15 15:16:56 -04001247 SkASSERT(c >= 0 && c <= 3);
1248 this->write(&("x\0y\0z\0w\0"[c * 2]));
Ethan Nicholascc305772017-10-13 16:17:45 -04001249 }
1250}
1251
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001252void MetalCodeGenerator::writeMatrixTimesEqualHelper(const Type& left, const Type& right,
1253 const Type& result) {
John Stiles39346472021-04-29 14:39:35 -04001254 String key = "TimesEqual " + this->typeName(left) + ":" + this->typeName(right);
John Stiles56233d12021-02-03 13:03:29 -05001255
1256 auto [iter, wasInserted] = fHelpers.insert(key);
1257 if (wasInserted) {
John Stiles368db7c2020-12-29 11:20:08 -05001258 fExtraFunctions.printf("thread %s& operator*=(thread %s& left, thread const %s& right) {\n"
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001259 " left = left * right;\n"
1260 " return left;\n"
John Stiles368db7c2020-12-29 11:20:08 -05001261 "}\n",
1262 this->typeName(result).c_str(), this->typeName(left).c_str(),
1263 this->typeName(right).c_str());
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001264 }
1265}
1266
John Stiles39346472021-04-29 14:39:35 -04001267void MetalCodeGenerator::writeMatrixEqualityHelpers(const Type& left, const Type& right) {
1268 SkASSERT(left.isMatrix());
1269 SkASSERT(right.isMatrix());
1270 SkASSERT(left.rows() == right.rows());
1271 SkASSERT(left.columns() == right.columns());
John Stiles01cdf012021-02-10 09:53:41 -05001272
John Stiles39346472021-04-29 14:39:35 -04001273 String key = "MatrixEquality " + this->typeName(left) + ":" + this->typeName(right);
John Stiles01cdf012021-02-10 09:53:41 -05001274
1275 auto [iter, wasInserted] = fHelpers.insert(key);
1276 if (wasInserted) {
1277 fExtraFunctions.printf(
1278 "thread bool operator==(const %s left, const %s right) {\n"
John Stiles39346472021-04-29 14:39:35 -04001279 " return ",
John Stiles01cdf012021-02-10 09:53:41 -05001280 this->typeName(left).c_str(), this->typeName(right).c_str());
1281
John Stiles39346472021-04-29 14:39:35 -04001282 const char* separator = "";
John Stiles01cdf012021-02-10 09:53:41 -05001283 for (int index=0; index<left.columns(); ++index) {
John Stiles39346472021-04-29 14:39:35 -04001284 fExtraFunctions.printf("%sall(left[%d] == right[%d])", separator, index, index);
1285 separator = " &&\n ";
John Stiles01cdf012021-02-10 09:53:41 -05001286 }
John Stiles39346472021-04-29 14:39:35 -04001287
1288 fExtraFunctions.printf(
1289 ";\n"
1290 "}\n"
1291 "thread bool operator!=(const %s left, const %s right) {\n"
1292 " return !(left == right);\n"
1293 "}\n",
1294 this->typeName(left).c_str(), this->typeName(right).c_str());
John Stiles01cdf012021-02-10 09:53:41 -05001295 }
1296}
1297
John Stiles39346472021-04-29 14:39:35 -04001298void MetalCodeGenerator::writeArrayEqualityHelpers(const Type& type) {
1299 SkASSERT(type.isArray());
John Stiles01cdf012021-02-10 09:53:41 -05001300
John Stiles39346472021-04-29 14:39:35 -04001301 // If the array's component type needs a helper as well, we need to emit that one first.
1302 this->writeEqualityHelpers(type.componentType(), type.componentType());
1303
1304 auto [iter, wasInserted] = fHelpers.insert("ArrayEquality []");
1305 if (wasInserted) {
1306 fExtraFunctions.writeText(R"(
1307template <typename T, size_t N>
1308bool operator==(thread const array<T, N>& left, thread const array<T, N>& right) {
1309 for (size_t index = 0; index < N; ++index) {
1310 if (!(left[index] == right[index])) {
1311 return false;
1312 }
1313 }
1314 return true;
1315}
1316
1317template <typename T, size_t N>
1318bool operator!=(thread const array<T, N>& left, thread const array<T, N>& right) {
1319 return !(left == right);
1320}
1321)");
1322 }
1323}
1324
1325void MetalCodeGenerator::writeStructEqualityHelpers(const Type& type) {
1326 SkASSERT(type.isStruct());
1327 String key = "StructEquality " + this->typeName(type);
John Stiles01cdf012021-02-10 09:53:41 -05001328
1329 auto [iter, wasInserted] = fHelpers.insert(key);
1330 if (wasInserted) {
John Stiles39346472021-04-29 14:39:35 -04001331 // If one of the struct's fields needs a helper as well, we need to emit that one first.
1332 for (const Type::Field& field : type.fields()) {
1333 this->writeEqualityHelpers(*field.fType, *field.fType);
John Stiles830c69c2021-04-28 17:16:16 -04001334 }
John Stiles39346472021-04-29 14:39:35 -04001335
1336 // Write operator== and operator!= for this struct, since those are assumed to exist in SkSL
1337 // and GLSL but do not exist by default in Metal.
1338 fExtraFunctions.printf(
1339 "thread bool operator==(thread const %s& left, thread const %s& right) {\n"
1340 " return ",
1341 this->typeName(type).c_str(),
1342 this->typeName(type).c_str());
1343
1344 const char* separator = "";
1345 for (const Type::Field& field : type.fields()) {
1346 fExtraFunctions.printf("%s(left.%.*s == right.%.*s)",
1347 separator,
1348 (int)field.fName.size(), field.fName.data(),
1349 (int)field.fName.size(), field.fName.data());
1350 separator = " &&\n ";
1351 }
1352 fExtraFunctions.printf(
1353 ";\n"
1354 "}\n"
1355 "thread bool operator!=(thread const %s& left, thread const %s& right) {\n"
1356 " return !(left == right);\n"
1357 "}\n",
1358 this->typeName(type).c_str(),
1359 this->typeName(type).c_str());
1360 }
1361}
1362
1363void MetalCodeGenerator::writeEqualityHelpers(const Type& leftType, const Type& rightType) {
1364 if (leftType.isArray() && rightType.isArray()) {
1365 this->writeArrayEqualityHelpers(leftType);
1366 return;
1367 }
1368 if (leftType.isStruct() && rightType.isStruct()) {
1369 this->writeStructEqualityHelpers(leftType);
1370 return;
1371 }
1372 if (leftType.isMatrix() && rightType.isMatrix()) {
1373 this->writeMatrixEqualityHelpers(leftType, rightType);
1374 return;
John Stiles01cdf012021-02-10 09:53:41 -05001375 }
1376}
1377
Ethan Nicholascc305772017-10-13 16:17:45 -04001378void MetalCodeGenerator::writeBinaryExpression(const BinaryExpression& b,
1379 Precedence parentPrecedence) {
John Stiles2d4f9592020-10-30 10:29:12 -04001380 const Expression& left = *b.left();
1381 const Expression& right = *b.right();
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001382 const Type& leftType = left.type();
1383 const Type& rightType = right.type();
John Stiles45990502021-02-16 10:55:27 -05001384 Operator op = b.getOperator();
1385 Precedence precedence = op.getBinaryPrecedence();
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001386 bool needParens = precedence >= parentPrecedence;
John Stiles45990502021-02-16 10:55:27 -05001387 switch (op.kind()) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001388 case Token::Kind::TK_EQEQ:
John Stiles39346472021-04-29 14:39:35 -04001389 this->writeEqualityHelpers(leftType, rightType);
John Stiles9aeed132020-11-24 17:36:06 -05001390 if (leftType.isVector()) {
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001391 this->write("all");
1392 needParens = true;
1393 }
1394 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001395 case Token::Kind::TK_NEQ:
John Stiles39346472021-04-29 14:39:35 -04001396 this->writeEqualityHelpers(leftType, rightType);
John Stiles9aeed132020-11-24 17:36:06 -05001397 if (leftType.isVector()) {
Jim Van Verth36477b42019-04-11 14:57:30 -04001398 this->write("any");
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001399 needParens = true;
1400 }
1401 break;
1402 default:
1403 break;
1404 }
1405 if (needParens) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001406 this->write("(");
1407 }
John Stiles39346472021-04-29 14:39:35 -04001408 if (leftType.isMatrix() && rightType.isMatrix() && op.kind() == Token::Kind::TK_STAREQ) {
1409 this->writeMatrixTimesEqualHelper(leftType, rightType, b.type());
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001410 }
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001411 this->writeExpression(left, precedence);
John Stiles45990502021-02-16 10:55:27 -05001412 if (op.kind() != Token::Kind::TK_EQ && op.isAssignment() &&
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001413 left.kind() == Expression::Kind::kSwizzle && !left.hasSideEffects()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001414 // This doesn't compile in Metal:
1415 // float4 x = float4(1);
1416 // x.xy *= float2x2(...);
1417 // with the error message "non-const reference cannot bind to vector element",
1418 // but switching it to x.xy = x.xy * float2x2(...) fixes it. We perform this tranformation
1419 // as long as the LHS has no side effects, and hope for the best otherwise.
1420 this->write(" = ");
Brian Osman00185012021-02-04 16:07:11 -05001421 this->writeExpression(left, Precedence::kAssignment);
Ethan Nicholascc305772017-10-13 16:17:45 -04001422 this->write(" ");
John Stilesd6449e92020-11-30 09:13:23 -05001423 String opName = OperatorName(op);
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001424 SkASSERT(opName.endsWith("="));
1425 this->write(opName.substr(0, opName.size() - 1).c_str());
Ethan Nicholascc305772017-10-13 16:17:45 -04001426 this->write(" ");
1427 } else {
John Stilesd6449e92020-11-30 09:13:23 -05001428 this->write(String(" ") + OperatorName(op) + " ");
Ethan Nicholascc305772017-10-13 16:17:45 -04001429 }
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001430 this->writeExpression(right, precedence);
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001431 if (needParens) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001432 this->write(")");
1433 }
1434}
1435
1436void MetalCodeGenerator::writeTernaryExpression(const TernaryExpression& t,
1437 Precedence parentPrecedence) {
Brian Osman00185012021-02-04 16:07:11 -05001438 if (Precedence::kTernary >= parentPrecedence) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001439 this->write("(");
1440 }
Brian Osman00185012021-02-04 16:07:11 -05001441 this->writeExpression(*t.test(), Precedence::kTernary);
Ethan Nicholascc305772017-10-13 16:17:45 -04001442 this->write(" ? ");
Brian Osman00185012021-02-04 16:07:11 -05001443 this->writeExpression(*t.ifTrue(), Precedence::kTernary);
Ethan Nicholascc305772017-10-13 16:17:45 -04001444 this->write(" : ");
Brian Osman00185012021-02-04 16:07:11 -05001445 this->writeExpression(*t.ifFalse(), Precedence::kTernary);
1446 if (Precedence::kTernary >= parentPrecedence) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001447 this->write(")");
1448 }
1449}
1450
1451void MetalCodeGenerator::writePrefixExpression(const PrefixExpression& p,
1452 Precedence parentPrecedence) {
Brian Osman00185012021-02-04 16:07:11 -05001453 if (Precedence::kPrefix >= parentPrecedence) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001454 this->write("(");
1455 }
John Stilesd6449e92020-11-30 09:13:23 -05001456 this->write(OperatorName(p.getOperator()));
Brian Osman00185012021-02-04 16:07:11 -05001457 this->writeExpression(*p.operand(), Precedence::kPrefix);
1458 if (Precedence::kPrefix >= parentPrecedence) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001459 this->write(")");
1460 }
1461}
1462
1463void MetalCodeGenerator::writePostfixExpression(const PostfixExpression& p,
1464 Precedence parentPrecedence) {
Brian Osman00185012021-02-04 16:07:11 -05001465 if (Precedence::kPostfix >= parentPrecedence) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001466 this->write("(");
1467 }
Brian Osman00185012021-02-04 16:07:11 -05001468 this->writeExpression(*p.operand(), Precedence::kPostfix);
John Stilesd6449e92020-11-30 09:13:23 -05001469 this->write(OperatorName(p.getOperator()));
Brian Osman00185012021-02-04 16:07:11 -05001470 if (Precedence::kPostfix >= parentPrecedence) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001471 this->write(")");
1472 }
1473}
1474
1475void MetalCodeGenerator::writeBoolLiteral(const BoolLiteral& b) {
Ethan Nicholas59d660c2020-09-28 09:18:15 -04001476 this->write(b.value() ? "true" : "false");
Ethan Nicholascc305772017-10-13 16:17:45 -04001477}
1478
1479void MetalCodeGenerator::writeIntLiteral(const IntLiteral& i) {
John Stiles12739df2020-12-29 09:47:20 -05001480 const Type& type = i.type();
John Stiles54e7c052021-01-11 14:22:36 -05001481 if (type == *fContext.fTypes.fUInt) {
Ethan Nicholase96cdd12020-09-28 16:27:18 -04001482 this->write(to_string(i.value() & 0xffffffff) + "u");
John Stiles54e7c052021-01-11 14:22:36 -05001483 } else if (type == *fContext.fTypes.fUShort) {
John Stiles12739df2020-12-29 09:47:20 -05001484 this->write(to_string(i.value() & 0xffff) + "u");
John Stiles54e7c052021-01-11 14:22:36 -05001485 } else if (type == *fContext.fTypes.fUByte) {
John Stiles12739df2020-12-29 09:47:20 -05001486 this->write(to_string(i.value() & 0xff) + "u");
Ethan Nicholascc305772017-10-13 16:17:45 -04001487 } else {
John Stiles12739df2020-12-29 09:47:20 -05001488 this->write(to_string(i.value()));
Ethan Nicholascc305772017-10-13 16:17:45 -04001489 }
1490}
1491
1492void MetalCodeGenerator::writeFloatLiteral(const FloatLiteral& f) {
Ethan Nicholasa3f22f12020-10-01 12:13:17 -04001493 this->write(to_string(f.value()));
Ethan Nicholascc305772017-10-13 16:17:45 -04001494}
1495
1496void MetalCodeGenerator::writeSetting(const Setting& s) {
John Stilesf57207b2021-02-02 17:50:34 -05001497 SK_ABORT("internal error; setting was not folded to a constant during compilation\n");
Ethan Nicholascc305772017-10-13 16:17:45 -04001498}
1499
John Stiles06b84ef2020-12-09 12:35:48 -05001500void MetalCodeGenerator::writeFunctionRequirementArgs(const FunctionDeclaration& f,
1501 const char*& separator) {
1502 Requirements requirements = this->requirements(f);
1503 if (requirements & kInputs_Requirement) {
1504 this->write(separator);
1505 this->write("_in");
1506 separator = ", ";
1507 }
1508 if (requirements & kOutputs_Requirement) {
1509 this->write(separator);
1510 this->write("_out");
1511 separator = ", ";
1512 }
1513 if (requirements & kUniforms_Requirement) {
1514 this->write(separator);
1515 this->write("_uniforms");
1516 separator = ", ";
1517 }
1518 if (requirements & kGlobals_Requirement) {
1519 this->write(separator);
John Stilesf7410bd2021-01-19 13:07:55 -05001520 this->write("_globals");
John Stiles06b84ef2020-12-09 12:35:48 -05001521 separator = ", ";
1522 }
1523 if (requirements & kFragCoord_Requirement) {
1524 this->write(separator);
1525 this->write("_fragCoord");
1526 separator = ", ";
1527 }
1528}
1529
1530void MetalCodeGenerator::writeFunctionRequirementParams(const FunctionDeclaration& f,
1531 const char*& separator) {
1532 Requirements requirements = this->requirements(f);
1533 if (requirements & kInputs_Requirement) {
1534 this->write(separator);
1535 this->write("Inputs _in");
1536 separator = ", ";
1537 }
1538 if (requirements & kOutputs_Requirement) {
1539 this->write(separator);
John Stilesf7410bd2021-01-19 13:07:55 -05001540 this->write("thread Outputs& _out");
John Stiles06b84ef2020-12-09 12:35:48 -05001541 separator = ", ";
1542 }
1543 if (requirements & kUniforms_Requirement) {
1544 this->write(separator);
1545 this->write("Uniforms _uniforms");
1546 separator = ", ";
1547 }
1548 if (requirements & kGlobals_Requirement) {
1549 this->write(separator);
John Stilesf7410bd2021-01-19 13:07:55 -05001550 this->write("thread Globals& _globals");
John Stiles06b84ef2020-12-09 12:35:48 -05001551 separator = ", ";
1552 }
1553 if (requirements & kFragCoord_Requirement) {
1554 this->write(separator);
1555 this->write("float4 _fragCoord");
1556 separator = ", ";
1557 }
1558}
1559
John Stilesda5cdf62021-01-28 11:47:29 -05001560int MetalCodeGenerator::getUniformBinding(const Modifiers& m) {
1561 return (m.fLayout.fBinding >= 0) ? m.fLayout.fBinding
John Stiles270cec22021-02-17 12:59:36 -05001562 : fProgram.fConfig->fSettings.fDefaultUniformBinding;
John Stilesda5cdf62021-01-28 11:47:29 -05001563}
1564
1565int MetalCodeGenerator::getUniformSet(const Modifiers& m) {
1566 return (m.fLayout.fSet >= 0) ? m.fLayout.fSet
John Stiles270cec22021-02-17 12:59:36 -05001567 : fProgram.fConfig->fSettings.fDefaultUniformSet;
John Stilesda5cdf62021-01-28 11:47:29 -05001568}
1569
John Stiles569249b2020-11-03 12:18:22 -05001570bool MetalCodeGenerator::writeFunctionDeclaration(const FunctionDeclaration& f) {
John Stilesf7410bd2021-01-19 13:07:55 -05001571 fRTHeightName = fProgram.fInputs.fRTHeight ? "_globals._anonInterface0->u_skRTHeight" : "";
Ethan Nicholascc305772017-10-13 16:17:45 -04001572 const char* separator = "";
John Stilese8da4d22021-03-24 09:19:45 -04001573 if (f.isMain()) {
John Stiles270cec22021-02-17 12:59:36 -05001574 switch (fProgram.fConfig->fKind) {
John Stilesdbd4e6f2021-02-16 13:29:15 -05001575 case ProgramKind::kFragment:
Timothy Liangb8eeb802018-07-23 16:46:16 -04001576 this->write("fragment Outputs fragmentMain");
Ethan Nicholascc305772017-10-13 16:17:45 -04001577 break;
John Stilesdbd4e6f2021-02-16 13:29:15 -05001578 case ProgramKind::kVertex:
Timothy Liangb8eeb802018-07-23 16:46:16 -04001579 this->write("vertex Outputs vertexMain");
Ethan Nicholascc305772017-10-13 16:17:45 -04001580 break;
1581 default:
John Stiles3fabfc02020-09-25 15:51:28 -04001582 fErrors.error(-1, "unsupported kind of program");
John Stiles569249b2020-11-03 12:18:22 -05001583 return false;
Ethan Nicholascc305772017-10-13 16:17:45 -04001584 }
1585 this->write("(Inputs _in [[stage_in]]");
1586 if (-1 != fUniformBuffer) {
1587 this->write(", constant Uniforms& _uniforms [[buffer(" +
1588 to_string(fUniformBuffer) + ")]]");
1589 }
Brian Osman133724c2020-10-28 14:14:39 -04001590 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04001591 if (e->is<GlobalVarDeclaration>()) {
1592 const GlobalVarDeclaration& decls = e->as<GlobalVarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001593 const VarDeclaration& var = decls.declaration()->as<VarDeclaration>();
1594 if (var.var().type().typeKind() == Type::TypeKind::kSampler) {
1595 if (var.var().modifiers().fLayout.fBinding < 0) {
Brian Osmanc0213602020-10-06 14:43:32 -04001596 fErrors.error(decls.fOffset,
John Stilesb41d5bb2021-01-26 16:28:12 -05001597 "Metal samplers must have 'layout(binding=...)'");
John Stiles569249b2020-11-03 12:18:22 -05001598 return false;
Timothy Liangee84fe12018-05-18 14:38:19 -04001599 }
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001600 if (var.var().type().dimensions() != SpvDim2D) {
John Stiles569249b2020-11-03 12:18:22 -05001601 // Not yet implemented--Skia currently only uses 2D textures.
Brian Osmanc0213602020-10-06 14:43:32 -04001602 fErrors.error(decls.fOffset, "Unsupported texture dimensions");
John Stiles569249b2020-11-03 12:18:22 -05001603 return false;
Brian Osmanc0213602020-10-06 14:43:32 -04001604 }
1605 this->write(", texture2d<float> ");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001606 this->writeName(var.var().name());
Brian Osmanc0213602020-10-06 14:43:32 -04001607 this->write("[[texture(");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001608 this->write(to_string(var.var().modifiers().fLayout.fBinding));
Brian Osmanc0213602020-10-06 14:43:32 -04001609 this->write(")]]");
1610 this->write(", sampler ");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001611 this->writeName(var.var().name());
Brian Osmanc0213602020-10-06 14:43:32 -04001612 this->write(SAMPLER_SUFFIX);
1613 this->write("[[sampler(");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001614 this->write(to_string(var.var().modifiers().fLayout.fBinding));
Brian Osmanc0213602020-10-06 14:43:32 -04001615 this->write(")]]");
Timothy Liang6403b0e2018-05-17 10:40:04 -04001616 }
Brian Osman1179fcf2020-10-08 16:04:40 -04001617 } else if (e->is<InterfaceBlock>()) {
1618 const InterfaceBlock& intf = e->as<InterfaceBlock>();
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001619 if (intf.typeName() == "sk_PerVertex") {
Timothy Lianga06f2152018-05-24 15:33:31 -04001620 continue;
1621 }
1622 this->write(", constant ");
John Stilesb4418502021-02-04 10:57:08 -05001623 this->writeType(intf.variable().type());
Timothy Lianga06f2152018-05-24 15:33:31 -04001624 this->write("& " );
1625 this->write(fInterfaceBlockNameMap[&intf]);
1626 this->write(" [[buffer(");
John Stilesda5cdf62021-01-28 11:47:29 -05001627 this->write(to_string(this->getUniformBinding(intf.variable().modifiers())));
Timothy Lianga06f2152018-05-24 15:33:31 -04001628 this->write(")]]");
Timothy Liang6403b0e2018-05-17 10:40:04 -04001629 }
1630 }
John Stiles270cec22021-02-17 12:59:36 -05001631 if (fProgram.fConfig->fKind == ProgramKind::kFragment) {
Jim Van Verth6bc650e2019-02-07 14:53:23 -05001632 if (fProgram.fInputs.fRTHeight && fInterfaceBlockNameMap.empty()) {
Timothy Liang5422f9a2018-08-10 10:57:55 -04001633 this->write(", constant sksl_synthetic_uniforms& _anonInterface0 [[buffer(1)]]");
Ethan Nicholasf931e402019-07-26 15:40:33 -04001634 fRTHeightName = "_anonInterface0.u_skRTHeight";
Timothy Liang5422f9a2018-08-10 10:57:55 -04001635 }
Timothy Liang7b8875d2018-08-10 09:42:31 -04001636 this->write(", bool _frontFacing [[front_facing]]");
Timothy Liang7d637782018-06-05 09:58:07 -04001637 this->write(", float4 _fragCoord [[position]]");
John Stiles270cec22021-02-17 12:59:36 -05001638 } else if (fProgram.fConfig->fKind == ProgramKind::kVertex) {
Timothy Liangdc89f192018-06-13 09:20:31 -04001639 this->write(", uint sk_VertexID [[vertex_id]], uint sk_InstanceID [[instance_id]]");
Timothy Liang7d637782018-06-05 09:58:07 -04001640 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001641 separator = ", ";
1642 } else {
John Stilesb4418502021-02-04 10:57:08 -05001643 this->writeType(f.returnType());
Timothy Liang651286f2018-06-07 09:55:33 -04001644 this->write(" ");
John Stilese1068342021-03-22 11:57:41 -04001645 this->writeName(f.mangledName());
Timothy Liang651286f2018-06-07 09:55:33 -04001646 this->write("(");
John Stiles06b84ef2020-12-09 12:35:48 -05001647 this->writeFunctionRequirementParams(f, separator);
Ethan Nicholascc305772017-10-13 16:17:45 -04001648 }
John Stiles569249b2020-11-03 12:18:22 -05001649 for (const auto& param : f.parameters()) {
Brian Osman716aeb92021-04-21 13:20:00 -04001650 if (f.isMain() && param->modifiers().fLayout.fBuiltin != -1) {
1651 continue;
1652 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001653 this->write(separator);
1654 separator = ", ";
John Stiles06b84ef2020-12-09 12:35:48 -05001655 this->writeModifiers(param->modifiers(), /*globalContext=*/false);
Ethan Nicholas30d30222020-09-11 12:27:26 -04001656 const Type* type = &param->type();
John Stilesb4418502021-02-04 10:57:08 -05001657 this->writeType(*type);
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001658 if (param->modifiers().fFlags & Modifiers::kOut_Flag) {
John Stilesf2bd5012020-12-04 11:58:26 -05001659 this->write("&");
Ethan Nicholascc305772017-10-13 16:17:45 -04001660 }
Timothy Liang651286f2018-06-07 09:55:33 -04001661 this->write(" ");
Ethan Nicholase2c49992020-10-05 11:49:11 -04001662 this->writeName(param->name());
Ethan Nicholascc305772017-10-13 16:17:45 -04001663 }
John Stiles569249b2020-11-03 12:18:22 -05001664 this->write(")");
1665 return true;
1666}
Ethan Nicholascc305772017-10-13 16:17:45 -04001667
John Stiles569249b2020-11-03 12:18:22 -05001668void MetalCodeGenerator::writeFunctionPrototype(const FunctionPrototype& f) {
1669 this->writeFunctionDeclaration(f.declaration());
1670 this->writeLine(";");
1671}
1672
John Stiles986c7fb2020-12-01 14:44:56 -05001673static bool is_block_ending_with_return(const Statement* stmt) {
1674 // This function detects (potentially nested) blocks that end in a return statement.
1675 if (!stmt->is<Block>()) {
1676 return false;
1677 }
1678 const StatementArray& block = stmt->as<Block>().children();
1679 for (int index = block.count(); index--; ) {
1680 const Statement& stmt = *block[index];
1681 if (stmt.is<ReturnStatement>()) {
1682 return true;
1683 }
1684 if (stmt.is<Block>()) {
1685 return is_block_ending_with_return(&stmt);
1686 }
1687 if (!stmt.is<Nop>()) {
1688 break;
1689 }
1690 }
1691 return false;
1692}
1693
John Stiles569249b2020-11-03 12:18:22 -05001694void MetalCodeGenerator::writeFunction(const FunctionDefinition& f) {
John Stiles270cec22021-02-17 12:59:36 -05001695 SkASSERT(!fProgram.fConfig->fSettings.fFragColorIsInOut);
Brian Salomondc092132018-04-04 10:14:16 -04001696
John Stiles569249b2020-11-03 12:18:22 -05001697 if (!this->writeFunctionDeclaration(f.declaration())) {
1698 return;
1699 }
1700
John Stiles986c7fb2020-12-01 14:44:56 -05001701 fCurrentFunction = &f.declaration();
1702 SkScopeExit clearCurrentFunction([&] { fCurrentFunction = nullptr; });
1703
John Stiles569249b2020-11-03 12:18:22 -05001704 this->writeLine(" {");
1705
John Stilese8da4d22021-03-24 09:19:45 -04001706 if (f.declaration().isMain()) {
John Stilescdcdb042020-07-06 09:03:51 -04001707 this->writeGlobalInit();
John Stilesf7410bd2021-01-19 13:07:55 -05001708 this->writeLine(" Outputs _out;");
John Stiles37279172021-01-21 22:24:28 -05001709 this->writeLine(" (void)_out;");
Ethan Nicholascc305772017-10-13 16:17:45 -04001710 }
John Stilesc67b3622020-05-28 17:53:13 -04001711
John Stiles95680232021-04-22 15:05:20 -04001712 fFunctionHeader.clear();
Ethan Nicholascc305772017-10-13 16:17:45 -04001713 StringStream buffer;
John Stiles44532372020-12-07 12:33:55 -05001714 {
1715 AutoOutputStream outputToBuffer(this, &buffer);
1716 fIndentation++;
1717 for (const std::unique_ptr<Statement>& stmt : f.body()->as<Block>().children()) {
1718 if (!stmt->isEmpty()) {
1719 this->writeStatement(*stmt);
John Stilese8b5a732021-03-12 13:25:52 -05001720 this->finishLine();
John Stiles44532372020-12-07 12:33:55 -05001721 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001722 }
John Stilese8da4d22021-03-24 09:19:45 -04001723 if (f.declaration().isMain()) {
John Stiles44532372020-12-07 12:33:55 -05001724 // If the main function doesn't end with a return, we need to synthesize one here.
1725 if (!is_block_ending_with_return(f.body().get())) {
1726 this->writeReturnStatementFromMain();
John Stilese8b5a732021-03-12 13:25:52 -05001727 this->finishLine();
John Stiles44532372020-12-07 12:33:55 -05001728 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001729 }
John Stiles44532372020-12-07 12:33:55 -05001730 fIndentation--;
1731 this->writeLine("}");
Ethan Nicholascc305772017-10-13 16:17:45 -04001732 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001733 this->write(fFunctionHeader);
1734 this->write(buffer.str());
1735}
1736
1737void MetalCodeGenerator::writeModifiers(const Modifiers& modifiers,
John Stiles06b84ef2020-12-09 12:35:48 -05001738 bool globalContext) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001739 if (modifiers.fFlags & Modifiers::kOut_Flag) {
1740 this->write("thread ");
1741 }
1742 if (modifiers.fFlags & Modifiers::kConst_Flag) {
John Stiles0bd55782021-02-09 18:29:40 -05001743 this->write("const ");
Ethan Nicholascc305772017-10-13 16:17:45 -04001744 }
1745}
1746
1747void MetalCodeGenerator::writeInterfaceBlock(const InterfaceBlock& intf) {
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001748 if ("sk_PerVertex" == intf.typeName()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001749 return;
1750 }
John Stiles06b84ef2020-12-09 12:35:48 -05001751 this->writeModifiers(intf.variable().modifiers(), /*globalContext=*/true);
Timothy Liangdc89f192018-06-13 09:20:31 -04001752 this->write("struct ");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001753 this->writeLine(intf.typeName() + " {");
1754 const Type* structType = &intf.variable().type();
John Stilesbb43b7e2020-12-03 17:36:32 -05001755 if (structType->isArray()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001756 structType = &structType->componentType();
1757 }
Timothy Liangdc89f192018-06-13 09:20:31 -04001758 fIndentation++;
John Stiles3dba3ee2020-12-02 23:35:49 -05001759 this->writeFields(structType->fields(), structType->fOffset, &intf);
Jim Van Verth3d482992019-02-07 10:48:05 -05001760 if (fProgram.fInputs.fRTHeight) {
Timothy Liang7d637782018-06-05 09:58:07 -04001761 this->writeLine("float u_skRTHeight;");
Ethan Nicholascc305772017-10-13 16:17:45 -04001762 }
1763 fIndentation--;
1764 this->write("}");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001765 if (intf.instanceName().size()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001766 this->write(" ");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001767 this->write(intf.instanceName());
John Stilesd39aec02020-12-03 10:42:26 -05001768 if (intf.arraySize() > 0) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001769 this->write("[");
John Stilesd39aec02020-12-03 10:42:26 -05001770 this->write(to_string(intf.arraySize()));
Ethan Nicholascc305772017-10-13 16:17:45 -04001771 this->write("]");
John Stilesd39aec02020-12-03 10:42:26 -05001772 } else if (intf.arraySize() == Type::kUnsizedArray){
1773 this->write("[]");
Ethan Nicholascc305772017-10-13 16:17:45 -04001774 }
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001775 fInterfaceBlockNameMap[&intf] = intf.instanceName();
Timothy Lianga06f2152018-05-24 15:33:31 -04001776 } else {
Timothy Liang7d637782018-06-05 09:58:07 -04001777 fInterfaceBlockNameMap[&intf] = "_anonInterface" + to_string(fAnonInterfaceCount++);
Ethan Nicholascc305772017-10-13 16:17:45 -04001778 }
1779 this->writeLine(";");
1780}
1781
Timothy Liangdc89f192018-06-13 09:20:31 -04001782void MetalCodeGenerator::writeFields(const std::vector<Type::Field>& fields, int parentOffset,
1783 const InterfaceBlock* parentIntf) {
Timothy Liang609fbe32018-08-10 16:40:49 -04001784 MemoryLayout memoryLayout(MemoryLayout::kMetal_Standard);
Timothy Liangdc89f192018-06-13 09:20:31 -04001785 int currentOffset = 0;
John Stiles39346472021-04-29 14:39:35 -04001786 for (const Type::Field& field : fields) {
Timothy Liangdc89f192018-06-13 09:20:31 -04001787 int fieldOffset = field.fModifiers.fLayout.fOffset;
1788 const Type* fieldType = field.fType;
John Stiles21f5f452020-11-30 09:57:59 -05001789 if (!MemoryLayout::LayoutIsSupported(*fieldType)) {
John Stiles0023c0c2020-11-16 13:32:18 -05001790 fErrors.error(parentOffset, "type '" + fieldType->name() + "' is not permitted here");
1791 return;
1792 }
Timothy Liangdc89f192018-06-13 09:20:31 -04001793 if (fieldOffset != -1) {
1794 if (currentOffset > fieldOffset) {
1795 fErrors.error(parentOffset,
John Stilesd7199b22020-12-30 16:22:58 -05001796 "offset of field '" + field.fName + "' must be at least " +
1797 to_string((int) currentOffset));
Brian Osman8609a242020-09-08 14:01:49 -04001798 return;
Timothy Liangdc89f192018-06-13 09:20:31 -04001799 } else if (currentOffset < fieldOffset) {
1800 this->write("char pad");
1801 this->write(to_string(fPaddingCount++));
1802 this->write("[");
1803 this->write(to_string(fieldOffset - currentOffset));
1804 this->writeLine("];");
1805 currentOffset = fieldOffset;
1806 }
1807 int alignment = memoryLayout.alignment(*fieldType);
1808 if (fieldOffset % alignment) {
1809 fErrors.error(parentOffset,
1810 "offset of field '" + field.fName + "' must be a multiple of " +
1811 to_string((int) alignment));
Brian Osman8609a242020-09-08 14:01:49 -04001812 return;
Timothy Liangdc89f192018-06-13 09:20:31 -04001813 }
1814 }
Brian Osman8609a242020-09-08 14:01:49 -04001815 size_t fieldSize = memoryLayout.size(*fieldType);
1816 if (fieldSize > static_cast<size_t>(std::numeric_limits<int>::max() - currentOffset)) {
1817 fErrors.error(parentOffset, "field offset overflow");
1818 return;
1819 }
1820 currentOffset += fieldSize;
John Stiles06b84ef2020-12-09 12:35:48 -05001821 this->writeModifiers(field.fModifiers, /*globalContext=*/false);
John Stilesb4418502021-02-04 10:57:08 -05001822 this->writeType(*fieldType);
Timothy Liangdc89f192018-06-13 09:20:31 -04001823 this->write(" ");
1824 this->writeName(field.fName);
Timothy Liangdc89f192018-06-13 09:20:31 -04001825 this->writeLine(";");
1826 if (parentIntf) {
1827 fInterfaceBlockMap[&field] = parentIntf;
1828 }
1829 }
1830}
1831
Ethan Nicholascc305772017-10-13 16:17:45 -04001832void MetalCodeGenerator::writeVarInitializer(const Variable& var, const Expression& value) {
Brian Osman00185012021-02-04 16:07:11 -05001833 this->writeExpression(value, Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001834}
1835
Timothy Liang651286f2018-06-07 09:55:33 -04001836void MetalCodeGenerator::writeName(const String& name) {
1837 if (fReservedWords.find(name) != fReservedWords.end()) {
1838 this->write("_"); // adding underscore before name to avoid conflict with reserved words
1839 }
1840 this->write(name);
1841}
1842
John Stilesb4418502021-02-04 10:57:08 -05001843void MetalCodeGenerator::writeVarDeclaration(const VarDeclaration& varDecl, bool global) {
1844 if (global && !(varDecl.var().modifiers().fFlags & Modifiers::kConst_Flag)) {
Brian Osmanc0213602020-10-06 14:43:32 -04001845 return;
Ethan Nicholascc305772017-10-13 16:17:45 -04001846 }
John Stilesb4418502021-02-04 10:57:08 -05001847 this->writeModifiers(varDecl.var().modifiers(), global);
1848 this->writeType(varDecl.var().type());
Brian Osmanc0213602020-10-06 14:43:32 -04001849 this->write(" ");
John Stilesb4418502021-02-04 10:57:08 -05001850 this->writeName(varDecl.var().name());
1851 if (varDecl.value()) {
Brian Osmanc0213602020-10-06 14:43:32 -04001852 this->write(" = ");
John Stilesb4418502021-02-04 10:57:08 -05001853 this->writeVarInitializer(varDecl.var(), *varDecl.value());
Brian Osmanc0213602020-10-06 14:43:32 -04001854 }
1855 this->write(";");
Ethan Nicholascc305772017-10-13 16:17:45 -04001856}
1857
1858void MetalCodeGenerator::writeStatement(const Statement& s) {
Ethan Nicholase6592142020-09-08 10:22:09 -04001859 switch (s.kind()) {
1860 case Statement::Kind::kBlock:
John Stiles26f98502020-08-18 09:30:51 -04001861 this->writeBlock(s.as<Block>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001862 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001863 case Statement::Kind::kExpression:
Brian Osman00185012021-02-04 16:07:11 -05001864 this->writeExpression(*s.as<ExpressionStatement>().expression(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001865 this->write(";");
1866 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001867 case Statement::Kind::kReturn:
John Stiles26f98502020-08-18 09:30:51 -04001868 this->writeReturnStatement(s.as<ReturnStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001869 break;
Brian Osmanc0213602020-10-06 14:43:32 -04001870 case Statement::Kind::kVarDeclaration:
1871 this->writeVarDeclaration(s.as<VarDeclaration>(), false);
Ethan Nicholascc305772017-10-13 16:17:45 -04001872 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001873 case Statement::Kind::kIf:
John Stiles26f98502020-08-18 09:30:51 -04001874 this->writeIfStatement(s.as<IfStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001875 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001876 case Statement::Kind::kFor:
John Stiles26f98502020-08-18 09:30:51 -04001877 this->writeForStatement(s.as<ForStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001878 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001879 case Statement::Kind::kDo:
John Stiles26f98502020-08-18 09:30:51 -04001880 this->writeDoStatement(s.as<DoStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001881 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001882 case Statement::Kind::kSwitch:
John Stiles26f98502020-08-18 09:30:51 -04001883 this->writeSwitchStatement(s.as<SwitchStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001884 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001885 case Statement::Kind::kBreak:
Ethan Nicholascc305772017-10-13 16:17:45 -04001886 this->write("break;");
1887 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001888 case Statement::Kind::kContinue:
Ethan Nicholascc305772017-10-13 16:17:45 -04001889 this->write("continue;");
1890 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001891 case Statement::Kind::kDiscard:
Timothy Lianga06f2152018-05-24 15:33:31 -04001892 this->write("discard_fragment();");
Ethan Nicholascc305772017-10-13 16:17:45 -04001893 break;
John Stiles98c1f822020-09-09 14:18:53 -04001894 case Statement::Kind::kInlineMarker:
Ethan Nicholase6592142020-09-08 10:22:09 -04001895 case Statement::Kind::kNop:
Ethan Nicholascc305772017-10-13 16:17:45 -04001896 this->write(";");
1897 break;
1898 default:
John Stileseada7bc2021-02-02 16:29:32 -05001899 SkDEBUGFAILF("unsupported statement: %s", s.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -05001900 break;
Ethan Nicholascc305772017-10-13 16:17:45 -04001901 }
1902}
1903
Ethan Nicholascc305772017-10-13 16:17:45 -04001904void MetalCodeGenerator::writeBlock(const Block& b) {
John Stiles3744bd62021-01-26 13:49:43 -05001905 // Write scope markers if this block is a scope, or if the block is empty (since we need to emit
1906 // something here to make the code valid).
1907 bool isScope = b.isScope() || b.isEmpty();
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001908 if (isScope) {
Ethan Nicholas70728ef2020-05-28 07:09:00 -04001909 this->writeLine("{");
1910 fIndentation++;
1911 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001912 for (const std::unique_ptr<Statement>& stmt : b.children()) {
1913 if (!stmt->isEmpty()) {
1914 this->writeStatement(*stmt);
John Stilese8b5a732021-03-12 13:25:52 -05001915 this->finishLine();
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001916 }
1917 }
1918 if (isScope) {
Ethan Nicholas70728ef2020-05-28 07:09:00 -04001919 fIndentation--;
1920 this->write("}");
1921 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001922}
1923
1924void MetalCodeGenerator::writeIfStatement(const IfStatement& stmt) {
1925 this->write("if (");
Brian Osman00185012021-02-04 16:07:11 -05001926 this->writeExpression(*stmt.test(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001927 this->write(") ");
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04001928 this->writeStatement(*stmt.ifTrue());
1929 if (stmt.ifFalse()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001930 this->write(" else ");
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04001931 this->writeStatement(*stmt.ifFalse());
Ethan Nicholascc305772017-10-13 16:17:45 -04001932 }
1933}
1934
1935void MetalCodeGenerator::writeForStatement(const ForStatement& f) {
Brian Osmand6f23382020-12-15 17:08:59 -05001936 // Emit loops of the form 'for(;test;)' as 'while(test)', which is probably how they started
1937 if (!f.initializer() && f.test() && !f.next()) {
1938 this->write("while (");
Brian Osman00185012021-02-04 16:07:11 -05001939 this->writeExpression(*f.test(), Precedence::kTopLevel);
Brian Osmand6f23382020-12-15 17:08:59 -05001940 this->write(") ");
1941 this->writeStatement(*f.statement());
1942 return;
1943 }
1944
John Stiles1a15e572021-04-19 14:57:15 -04001945 this->write("for (");
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04001946 if (f.initializer() && !f.initializer()->isEmpty()) {
John Stiles1a15e572021-04-19 14:57:15 -04001947 this->writeStatement(*f.initializer());
Ethan Nicholascc305772017-10-13 16:17:45 -04001948 } else {
John Stiles1a15e572021-04-19 14:57:15 -04001949 this->write("; ");
Ethan Nicholascc305772017-10-13 16:17:45 -04001950 }
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04001951 if (f.test()) {
Brian Osman00185012021-02-04 16:07:11 -05001952 this->writeExpression(*f.test(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001953 }
1954 this->write("; ");
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04001955 if (f.next()) {
Brian Osman00185012021-02-04 16:07:11 -05001956 this->writeExpression(*f.next(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001957 }
1958 this->write(") ");
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04001959 this->writeStatement(*f.statement());
Ethan Nicholascc305772017-10-13 16:17:45 -04001960}
1961
Ethan Nicholascc305772017-10-13 16:17:45 -04001962void MetalCodeGenerator::writeDoStatement(const DoStatement& d) {
1963 this->write("do ");
Ethan Nicholas1fd61162020-09-28 13:14:19 -04001964 this->writeStatement(*d.statement());
Ethan Nicholascc305772017-10-13 16:17:45 -04001965 this->write(" while (");
Brian Osman00185012021-02-04 16:07:11 -05001966 this->writeExpression(*d.test(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001967 this->write(");");
1968}
1969
1970void MetalCodeGenerator::writeSwitchStatement(const SwitchStatement& s) {
1971 this->write("switch (");
Brian Osman00185012021-02-04 16:07:11 -05001972 this->writeExpression(*s.value(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001973 this->writeLine(") {");
1974 fIndentation++;
John Stilesb23a64b2021-03-11 08:27:59 -05001975 for (const std::unique_ptr<Statement>& stmt : s.cases()) {
1976 const SwitchCase& c = stmt->as<SwitchCase>();
1977 if (c.value()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001978 this->write("case ");
John Stilesb23a64b2021-03-11 08:27:59 -05001979 this->writeExpression(*c.value(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001980 this->writeLine(":");
1981 } else {
1982 this->writeLine("default:");
1983 }
John Stilesb23a64b2021-03-11 08:27:59 -05001984 if (!c.statement()->isEmpty()) {
John Stilesc3ce43b2021-03-09 15:37:01 -05001985 fIndentation++;
John Stilesb23a64b2021-03-11 08:27:59 -05001986 this->writeStatement(*c.statement());
John Stilese8b5a732021-03-12 13:25:52 -05001987 this->finishLine();
John Stilesc3ce43b2021-03-09 15:37:01 -05001988 fIndentation--;
Ethan Nicholascc305772017-10-13 16:17:45 -04001989 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001990 }
1991 fIndentation--;
1992 this->write("}");
1993}
1994
John Stiles986c7fb2020-12-01 14:44:56 -05001995void MetalCodeGenerator::writeReturnStatementFromMain() {
1996 // main functions in Metal return a magic _out parameter that doesn't exist in SkSL.
John Stiles270cec22021-02-17 12:59:36 -05001997 switch (fProgram.fConfig->fKind) {
John Stilesdbd4e6f2021-02-16 13:29:15 -05001998 case ProgramKind::kFragment:
John Stilesf7410bd2021-01-19 13:07:55 -05001999 this->write("return _out;");
John Stiles986c7fb2020-12-01 14:44:56 -05002000 break;
John Stilesdbd4e6f2021-02-16 13:29:15 -05002001 case ProgramKind::kVertex:
John Stilesf7410bd2021-01-19 13:07:55 -05002002 this->write("return (_out.sk_Position.y = -_out.sk_Position.y, _out);");
John Stiles986c7fb2020-12-01 14:44:56 -05002003 break;
2004 default:
2005 SkDEBUGFAIL("unsupported kind of program");
2006 }
2007}
2008
Ethan Nicholascc305772017-10-13 16:17:45 -04002009void MetalCodeGenerator::writeReturnStatement(const ReturnStatement& r) {
John Stilese8da4d22021-03-24 09:19:45 -04002010 if (fCurrentFunction && fCurrentFunction->isMain()) {
John Stiles986c7fb2020-12-01 14:44:56 -05002011 if (r.expression()) {
John Stiles97d18172021-01-22 16:47:42 -05002012 if (r.expression()->type() == *fContext.fTypes.fHalf4) {
2013 this->write("_out.sk_FragColor = ");
Brian Osman00185012021-02-04 16:07:11 -05002014 this->writeExpression(*r.expression(), Precedence::kTopLevel);
John Stiles97d18172021-01-22 16:47:42 -05002015 this->writeLine(";");
2016 } else {
2017 fErrors.error(r.fOffset, "Metal does not support returning '" +
2018 r.expression()->type().description() + "' from main()");
2019 }
John Stiles986c7fb2020-12-01 14:44:56 -05002020 }
2021 this->writeReturnStatementFromMain();
2022 return;
2023 }
2024
Ethan Nicholascc305772017-10-13 16:17:45 -04002025 this->write("return");
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04002026 if (r.expression()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002027 this->write(" ");
Brian Osman00185012021-02-04 16:07:11 -05002028 this->writeExpression(*r.expression(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04002029 }
2030 this->write(";");
2031}
2032
Michael Ludwigbf58add2021-03-16 10:40:11 -04002033void MetalCodeGenerator::writeHeader() {
2034 this->write("#include <metal_stdlib>\n");
2035 this->write("#include <simd/simd.h>\n");
2036 this->write("using namespace metal;\n");
2037}
2038
Ethan Nicholascc305772017-10-13 16:17:45 -04002039void MetalCodeGenerator::writeUniformStruct() {
Brian Osman133724c2020-10-28 14:14:39 -04002040 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04002041 if (e->is<GlobalVarDeclaration>()) {
2042 const GlobalVarDeclaration& decls = e->as<GlobalVarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04002043 const Variable& var = decls.declaration()->as<VarDeclaration>().var();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002044 if (var.modifiers().fFlags & Modifiers::kUniform_Flag &&
Brian Osmanc0213602020-10-06 14:43:32 -04002045 var.type().typeKind() != Type::TypeKind::kSampler) {
John Stilesda5cdf62021-01-28 11:47:29 -05002046 int uniformSet = this->getUniformSet(var.modifiers());
John Stilesd8fc95d2021-01-26 16:22:53 -05002047 // Make sure that the program's uniform-set value is consistent throughout.
Ethan Nicholascc305772017-10-13 16:17:45 -04002048 if (-1 == fUniformBuffer) {
2049 this->write("struct Uniforms {\n");
John Stilesd8fc95d2021-01-26 16:22:53 -05002050 fUniformBuffer = uniformSet;
2051 } else if (uniformSet != fUniformBuffer) {
2052 fErrors.error(decls.fOffset, "Metal backend requires all uniforms to have "
2053 "the same 'layout(set=...)'");
Ethan Nicholascc305772017-10-13 16:17:45 -04002054 }
2055 this->write(" ");
John Stilesb4418502021-02-04 10:57:08 -05002056 this->writeType(var.type());
Ethan Nicholascc305772017-10-13 16:17:45 -04002057 this->write(" ");
Brian Osmanc0213602020-10-06 14:43:32 -04002058 this->writeName(var.name());
Ethan Nicholascc305772017-10-13 16:17:45 -04002059 this->write(";\n");
2060 }
2061 }
2062 }
2063 if (-1 != fUniformBuffer) {
2064 this->write("};\n");
2065 }
2066}
2067
2068void MetalCodeGenerator::writeInputStruct() {
2069 this->write("struct Inputs {\n");
Brian Osman133724c2020-10-28 14:14:39 -04002070 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04002071 if (e->is<GlobalVarDeclaration>()) {
2072 const GlobalVarDeclaration& decls = e->as<GlobalVarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04002073 const Variable& var = decls.declaration()->as<VarDeclaration>().var();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002074 if (var.modifiers().fFlags & Modifiers::kIn_Flag &&
2075 -1 == var.modifiers().fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002076 this->write(" ");
John Stilesb4418502021-02-04 10:57:08 -05002077 this->writeType(var.type());
Ethan Nicholascc305772017-10-13 16:17:45 -04002078 this->write(" ");
Brian Osmanc0213602020-10-06 14:43:32 -04002079 this->writeName(var.name());
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002080 if (-1 != var.modifiers().fLayout.fLocation) {
John Stiles270cec22021-02-17 12:59:36 -05002081 if (fProgram.fConfig->fKind == ProgramKind::kVertex) {
Brian Osmanc0213602020-10-06 14:43:32 -04002082 this->write(" [[attribute(" +
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002083 to_string(var.modifiers().fLayout.fLocation) + ")]]");
John Stiles270cec22021-02-17 12:59:36 -05002084 } else if (fProgram.fConfig->fKind == ProgramKind::kFragment) {
Brian Osmanc0213602020-10-06 14:43:32 -04002085 this->write(" [[user(locn" +
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002086 to_string(var.modifiers().fLayout.fLocation) + ")]]");
Ethan Nicholascc305772017-10-13 16:17:45 -04002087 }
2088 }
2089 this->write(";\n");
2090 }
2091 }
2092 }
2093 this->write("};\n");
2094}
2095
2096void MetalCodeGenerator::writeOutputStruct() {
2097 this->write("struct Outputs {\n");
John Stiles270cec22021-02-17 12:59:36 -05002098 if (fProgram.fConfig->fKind == ProgramKind::kVertex) {
Timothy Liangb8eeb802018-07-23 16:46:16 -04002099 this->write(" float4 sk_Position [[position]];\n");
John Stiles270cec22021-02-17 12:59:36 -05002100 } else if (fProgram.fConfig->fKind == ProgramKind::kFragment) {
Timothy Liangde0be802018-08-10 13:48:08 -04002101 this->write(" float4 sk_FragColor [[color(0)]];\n");
Timothy Liang7d637782018-06-05 09:58:07 -04002102 }
Brian Osman133724c2020-10-28 14:14:39 -04002103 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04002104 if (e->is<GlobalVarDeclaration>()) {
2105 const GlobalVarDeclaration& decls = e->as<GlobalVarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04002106 const Variable& var = decls.declaration()->as<VarDeclaration>().var();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002107 if (var.modifiers().fFlags & Modifiers::kOut_Flag &&
2108 -1 == var.modifiers().fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002109 this->write(" ");
John Stilesb4418502021-02-04 10:57:08 -05002110 this->writeType(var.type());
Ethan Nicholascc305772017-10-13 16:17:45 -04002111 this->write(" ");
Brian Osmanc0213602020-10-06 14:43:32 -04002112 this->writeName(var.name());
John Stiles842b3592020-12-01 10:36:37 -05002113
2114 int location = var.modifiers().fLayout.fLocation;
2115 if (location < 0) {
2116 fErrors.error(var.fOffset,
2117 "Metal out variables must have 'layout(location=...)'");
John Stiles270cec22021-02-17 12:59:36 -05002118 } else if (fProgram.fConfig->fKind == ProgramKind::kVertex) {
John Stiles842b3592020-12-01 10:36:37 -05002119 this->write(" [[user(locn" + to_string(location) + ")]]");
John Stiles270cec22021-02-17 12:59:36 -05002120 } else if (fProgram.fConfig->fKind == ProgramKind::kFragment) {
John Stiles842b3592020-12-01 10:36:37 -05002121 this->write(" [[color(" + to_string(location) + ")");
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002122 int colorIndex = var.modifiers().fLayout.fIndex;
Brian Osmanc0213602020-10-06 14:43:32 -04002123 if (colorIndex) {
2124 this->write(", index(" + to_string(colorIndex) + ")");
Timothy Liang7d637782018-06-05 09:58:07 -04002125 }
Brian Osmanc0213602020-10-06 14:43:32 -04002126 this->write("]]");
Ethan Nicholascc305772017-10-13 16:17:45 -04002127 }
2128 this->write(";\n");
2129 }
2130 }
Timothy Liang7d637782018-06-05 09:58:07 -04002131 }
John Stiles270cec22021-02-17 12:59:36 -05002132 if (fProgram.fConfig->fKind == ProgramKind::kVertex) {
Jim Van Verth3913d3e2020-08-31 15:16:57 -04002133 this->write(" float sk_PointSize [[point_size]];\n");
Timothy Liang7d637782018-06-05 09:58:07 -04002134 }
2135 this->write("};\n");
2136}
2137
2138void MetalCodeGenerator::writeInterfaceBlocks() {
2139 bool wroteInterfaceBlock = false;
Brian Osman133724c2020-10-28 14:14:39 -04002140 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04002141 if (e->is<InterfaceBlock>()) {
2142 this->writeInterfaceBlock(e->as<InterfaceBlock>());
Timothy Liang7d637782018-06-05 09:58:07 -04002143 wroteInterfaceBlock = true;
2144 }
2145 }
Jim Van Verth3d482992019-02-07 10:48:05 -05002146 if (!wroteInterfaceBlock && fProgram.fInputs.fRTHeight) {
Timothy Liang7d637782018-06-05 09:58:07 -04002147 this->writeLine("struct sksl_synthetic_uniforms {");
2148 this->writeLine(" float u_skRTHeight;");
2149 this->writeLine("};");
2150 }
Ethan Nicholascc305772017-10-13 16:17:45 -04002151}
2152
John Stilesdc75a972020-11-25 16:24:55 -05002153void MetalCodeGenerator::writeStructDefinitions() {
2154 for (const ProgramElement* e : fProgram.elements()) {
2155 if (e->is<StructDefinition>()) {
Brian Osman02bc5222021-01-28 11:00:20 -05002156 this->writeStructDefinition(e->as<StructDefinition>());
John Stilesdc75a972020-11-25 16:24:55 -05002157 }
2158 }
2159}
2160
John Stilescdcdb042020-07-06 09:03:51 -04002161void MetalCodeGenerator::visitGlobalStruct(GlobalStructVisitor* visitor) {
2162 // Visit the interface blocks.
2163 for (const auto& [interfaceType, interfaceName] : fInterfaceBlockNameMap) {
John Stilesfdb8dbe2020-12-04 11:00:03 -05002164 visitor->visitInterfaceBlock(*interfaceType, interfaceName);
John Stilescdcdb042020-07-06 09:03:51 -04002165 }
Brian Osman133724c2020-10-28 14:14:39 -04002166 for (const ProgramElement* element : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04002167 if (!element->is<GlobalVarDeclaration>()) {
John Stilescdcdb042020-07-06 09:03:51 -04002168 continue;
Timothy Liang7d637782018-06-05 09:58:07 -04002169 }
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04002170 const GlobalVarDeclaration& global = element->as<GlobalVarDeclaration>();
2171 const VarDeclaration& decl = global.declaration()->as<VarDeclaration>();
2172 const Variable& var = decl.var();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002173 if ((!var.modifiers().fFlags && -1 == var.modifiers().fLayout.fBuiltin) ||
Brian Osmanc0213602020-10-06 14:43:32 -04002174 var.type().typeKind() == Type::TypeKind::kSampler) {
2175 if (var.type().typeKind() == Type::TypeKind::kSampler) {
2176 // Samplers are represented as a "texture/sampler" duo in the global struct.
John Stilesfdb8dbe2020-12-04 11:00:03 -05002177 visitor->visitTexture(var.type(), var.name());
2178 visitor->visitSampler(var.type(), String(var.name()) + SAMPLER_SUFFIX);
Brian Osmanc0213602020-10-06 14:43:32 -04002179 } else {
2180 // Visit a regular variable.
John Stilesfdb8dbe2020-12-04 11:00:03 -05002181 visitor->visitVariable(var, decl.value().get());
Timothy Liangee84fe12018-05-18 14:38:19 -04002182 }
2183 }
2184 }
John Stilescdcdb042020-07-06 09:03:51 -04002185}
2186
2187void MetalCodeGenerator::writeGlobalStruct() {
2188 class : public GlobalStructVisitor {
2189 public:
John Stilesfdb8dbe2020-12-04 11:00:03 -05002190 void visitInterfaceBlock(const InterfaceBlock& block, const String& blockName) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002191 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002192 fCodeGen->write(" constant ");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04002193 fCodeGen->write(block.typeName());
John Stilescdcdb042020-07-06 09:03:51 -04002194 fCodeGen->write("* ");
2195 fCodeGen->writeName(blockName);
2196 fCodeGen->write(";\n");
2197 }
John Stilesfdb8dbe2020-12-04 11:00:03 -05002198 void visitTexture(const Type& type, const String& name) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002199 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002200 fCodeGen->write(" ");
John Stilesb4418502021-02-04 10:57:08 -05002201 fCodeGen->writeType(type);
John Stilescdcdb042020-07-06 09:03:51 -04002202 fCodeGen->write(" ");
2203 fCodeGen->writeName(name);
2204 fCodeGen->write(";\n");
2205 }
John Stilesfdb8dbe2020-12-04 11:00:03 -05002206 void visitSampler(const Type&, const String& name) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002207 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002208 fCodeGen->write(" sampler ");
2209 fCodeGen->writeName(name);
2210 fCodeGen->write(";\n");
2211 }
John Stilesfdb8dbe2020-12-04 11:00:03 -05002212 void visitVariable(const Variable& var, const Expression* value) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002213 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002214 fCodeGen->write(" ");
John Stilesb4418502021-02-04 10:57:08 -05002215 fCodeGen->writeType(var.type());
John Stilescdcdb042020-07-06 09:03:51 -04002216 fCodeGen->write(" ");
Ethan Nicholase2c49992020-10-05 11:49:11 -04002217 fCodeGen->writeName(var.name());
John Stilescdcdb042020-07-06 09:03:51 -04002218 fCodeGen->write(";\n");
2219 }
John Stiles83f3b8d2020-12-07 17:52:25 -05002220 void addElement() {
John Stilescdcdb042020-07-06 09:03:51 -04002221 if (fFirst) {
2222 fCodeGen->write("struct Globals {\n");
2223 fFirst = false;
2224 }
2225 }
John Stiles83f3b8d2020-12-07 17:52:25 -05002226 void finish() {
John Stilescdcdb042020-07-06 09:03:51 -04002227 if (!fFirst) {
John Stiles83f3b8d2020-12-07 17:52:25 -05002228 fCodeGen->writeLine("};");
John Stilescdcdb042020-07-06 09:03:51 -04002229 fFirst = true;
2230 }
2231 }
2232
2233 MetalCodeGenerator* fCodeGen = nullptr;
2234 bool fFirst = true;
2235 } visitor;
2236
2237 visitor.fCodeGen = this;
2238 this->visitGlobalStruct(&visitor);
John Stiles83f3b8d2020-12-07 17:52:25 -05002239 visitor.finish();
John Stilescdcdb042020-07-06 09:03:51 -04002240}
2241
2242void MetalCodeGenerator::writeGlobalInit() {
2243 class : public GlobalStructVisitor {
2244 public:
John Stilesfdb8dbe2020-12-04 11:00:03 -05002245 void visitInterfaceBlock(const InterfaceBlock& blockType,
John Stilescdcdb042020-07-06 09:03:51 -04002246 const String& blockName) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002247 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002248 fCodeGen->write("&");
2249 fCodeGen->writeName(blockName);
2250 }
John Stilesfdb8dbe2020-12-04 11:00:03 -05002251 void visitTexture(const Type&, const String& name) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002252 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002253 fCodeGen->writeName(name);
2254 }
John Stilesfdb8dbe2020-12-04 11:00:03 -05002255 void visitSampler(const Type&, const String& name) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002256 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002257 fCodeGen->writeName(name);
2258 }
John Stilesfdb8dbe2020-12-04 11:00:03 -05002259 void visitVariable(const Variable& var, const Expression* value) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002260 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002261 if (value) {
2262 fCodeGen->writeVarInitializer(var, *value);
2263 } else {
2264 fCodeGen->write("{}");
2265 }
2266 }
John Stiles83f3b8d2020-12-07 17:52:25 -05002267 void addElement() {
John Stilescdcdb042020-07-06 09:03:51 -04002268 if (fFirst) {
John Stilesf7410bd2021-01-19 13:07:55 -05002269 fCodeGen->write(" Globals _globals{");
John Stilescdcdb042020-07-06 09:03:51 -04002270 fFirst = false;
2271 } else {
2272 fCodeGen->write(", ");
2273 }
2274 }
John Stiles83f3b8d2020-12-07 17:52:25 -05002275 void finish() {
John Stilescdcdb042020-07-06 09:03:51 -04002276 if (!fFirst) {
2277 fCodeGen->writeLine("};");
John Stiles37279172021-01-21 22:24:28 -05002278 fCodeGen->writeLine(" (void)_globals;");
John Stilescdcdb042020-07-06 09:03:51 -04002279 }
2280 }
2281 MetalCodeGenerator* fCodeGen = nullptr;
2282 bool fFirst = true;
2283 } visitor;
2284
2285 visitor.fCodeGen = this;
2286 this->visitGlobalStruct(&visitor);
John Stiles83f3b8d2020-12-07 17:52:25 -05002287 visitor.finish();
Timothy Liangee84fe12018-05-18 14:38:19 -04002288}
2289
Ethan Nicholascc305772017-10-13 16:17:45 -04002290void MetalCodeGenerator::writeProgramElement(const ProgramElement& e) {
Ethan Nicholase6592142020-09-08 10:22:09 -04002291 switch (e.kind()) {
2292 case ProgramElement::Kind::kExtension:
Ethan Nicholascc305772017-10-13 16:17:45 -04002293 break;
Brian Osmanc0213602020-10-06 14:43:32 -04002294 case ProgramElement::Kind::kGlobalVar: {
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04002295 const GlobalVarDeclaration& global = e.as<GlobalVarDeclaration>();
2296 const VarDeclaration& decl = global.declaration()->as<VarDeclaration>();
2297 int builtin = decl.var().modifiers().fLayout.fBuiltin;
Brian Osmanc0213602020-10-06 14:43:32 -04002298 if (-1 == builtin) {
2299 // normal var
2300 this->writeVarDeclaration(decl, true);
John Stilese8b5a732021-03-12 13:25:52 -05002301 this->finishLine();
Brian Osmanc0213602020-10-06 14:43:32 -04002302 } else if (SK_FRAGCOLOR_BUILTIN == builtin) {
2303 // ignore
Ethan Nicholascc305772017-10-13 16:17:45 -04002304 }
2305 break;
2306 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002307 case ProgramElement::Kind::kInterfaceBlock:
Timothy Liang7d637782018-06-05 09:58:07 -04002308 // handled in writeInterfaceBlocks, do nothing
Ethan Nicholascc305772017-10-13 16:17:45 -04002309 break;
John Stilesdc75a972020-11-25 16:24:55 -05002310 case ProgramElement::Kind::kStructDefinition:
2311 // Handled in writeStructDefinitions. Do nothing.
2312 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04002313 case ProgramElement::Kind::kFunction:
John Stiles3dc0da62020-08-19 17:48:31 -04002314 this->writeFunction(e.as<FunctionDefinition>());
Ethan Nicholascc305772017-10-13 16:17:45 -04002315 break;
John Stiles569249b2020-11-03 12:18:22 -05002316 case ProgramElement::Kind::kFunctionPrototype:
2317 this->writeFunctionPrototype(e.as<FunctionPrototype>());
2318 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04002319 case ProgramElement::Kind::kModifiers:
John Stiles06b84ef2020-12-09 12:35:48 -05002320 this->writeModifiers(e.as<ModifiersDeclaration>().modifiers(),
2321 /*globalContext=*/true);
Ethan Nicholascc305772017-10-13 16:17:45 -04002322 this->writeLine(";");
2323 break;
John Stiles712fd6b2020-11-25 22:25:43 -05002324 case ProgramElement::Kind::kEnum:
2325 break;
Ethan Nicholascc305772017-10-13 16:17:45 -04002326 default:
John Stileseada7bc2021-02-02 16:29:32 -05002327 SkDEBUGFAILF("unsupported program element: %s\n", e.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -05002328 break;
Ethan Nicholascc305772017-10-13 16:17:45 -04002329 }
2330}
2331
Ethan Nicholasff350cb2020-05-14 14:05:13 -04002332MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const Expression* e) {
2333 if (!e) {
2334 return kNo_Requirements;
2335 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002336 switch (e->kind()) {
2337 case Expression::Kind::kFunctionCall: {
John Stiles3dc0da62020-08-19 17:48:31 -04002338 const FunctionCall& f = e->as<FunctionCall>();
Ethan Nicholas0dec9922020-10-05 15:51:52 -04002339 Requirements result = this->requirements(f.function());
2340 for (const auto& arg : f.arguments()) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04002341 result |= this->requirements(arg.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002342 }
2343 return result;
2344 }
John Stiles8cad6372021-04-07 12:31:13 -04002345 case Expression::Kind::kConstructorCompound:
2346 case Expression::Kind::kConstructorCompoundCast:
John Stiles7384b372021-04-01 13:48:15 -04002347 case Expression::Kind::kConstructorArray:
John Stiles2938eea2021-04-01 18:58:25 -04002348 case Expression::Kind::kConstructorDiagonalMatrix:
John Stilesfd7252f2021-04-04 22:24:40 -04002349 case Expression::Kind::kConstructorScalarCast:
John Stilesd47330f2021-04-08 23:25:52 -04002350 case Expression::Kind::kConstructorSplat:
2351 case Expression::Kind::kConstructorStruct: {
John Stiles7384b372021-04-01 13:48:15 -04002352 const AnyConstructor& c = e->asAnyConstructor();
Ethan Nicholascc305772017-10-13 16:17:45 -04002353 Requirements result = kNo_Requirements;
John Stilesd8eb8752021-04-01 11:49:10 -04002354 for (const auto& arg : c.argumentSpan()) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04002355 result |= this->requirements(arg.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002356 }
2357 return result;
2358 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002359 case Expression::Kind::kFieldAccess: {
John Stiles3dc0da62020-08-19 17:48:31 -04002360 const FieldAccess& f = e->as<FieldAccess>();
Ethan Nicholas7a95b202020-10-09 11:55:40 -04002361 if (FieldAccess::OwnerKind::kAnonymousInterfaceBlock == f.ownerKind()) {
Timothy Liang7d637782018-06-05 09:58:07 -04002362 return kGlobals_Requirement;
2363 }
Ethan Nicholas7a95b202020-10-09 11:55:40 -04002364 return this->requirements(f.base().get());
Timothy Liang7d637782018-06-05 09:58:07 -04002365 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002366 case Expression::Kind::kSwizzle:
Ethan Nicholas6b4d5812020-10-12 16:11:51 -04002367 return this->requirements(e->as<Swizzle>().base().get());
Ethan Nicholase6592142020-09-08 10:22:09 -04002368 case Expression::Kind::kBinary: {
2369 const BinaryExpression& bin = e->as<BinaryExpression>();
John Stiles2d4f9592020-10-30 10:29:12 -04002370 return this->requirements(bin.left().get()) |
2371 this->requirements(bin.right().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002372 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002373 case Expression::Kind::kIndex: {
John Stiles3dc0da62020-08-19 17:48:31 -04002374 const IndexExpression& idx = e->as<IndexExpression>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04002375 return this->requirements(idx.base().get()) | this->requirements(idx.index().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002376 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002377 case Expression::Kind::kPrefix:
Ethan Nicholas444ccc62020-10-09 10:16:22 -04002378 return this->requirements(e->as<PrefixExpression>().operand().get());
Ethan Nicholase6592142020-09-08 10:22:09 -04002379 case Expression::Kind::kPostfix:
Ethan Nicholas444ccc62020-10-09 10:16:22 -04002380 return this->requirements(e->as<PostfixExpression>().operand().get());
Ethan Nicholase6592142020-09-08 10:22:09 -04002381 case Expression::Kind::kTernary: {
John Stiles3dc0da62020-08-19 17:48:31 -04002382 const TernaryExpression& t = e->as<TernaryExpression>();
Ethan Nicholasdd218162020-10-08 05:48:01 -04002383 return this->requirements(t.test().get()) | this->requirements(t.ifTrue().get()) |
2384 this->requirements(t.ifFalse().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002385 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002386 case Expression::Kind::kVariableReference: {
John Stiles3dc0da62020-08-19 17:48:31 -04002387 const VariableReference& v = e->as<VariableReference>();
Ethan Nicholas78686922020-10-08 06:46:27 -04002388 const Modifiers& modifiers = v.variable()->modifiers();
Ethan Nicholascc305772017-10-13 16:17:45 -04002389 Requirements result = kNo_Requirements;
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002390 if (modifiers.fLayout.fBuiltin == SK_FRAGCOORD_BUILTIN) {
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -04002391 result = kGlobals_Requirement | kFragCoord_Requirement;
Ethan Nicholas453f67f2020-10-09 10:43:45 -04002392 } else if (Variable::Storage::kGlobal == v.variable()->storage()) {
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002393 if (modifiers.fFlags & Modifiers::kIn_Flag) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002394 result = kInputs_Requirement;
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002395 } else if (modifiers.fFlags & Modifiers::kOut_Flag) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002396 result = kOutputs_Requirement;
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002397 } else if (modifiers.fFlags & Modifiers::kUniform_Flag &&
Ethan Nicholas78686922020-10-08 06:46:27 -04002398 v.variable()->type().typeKind() != Type::TypeKind::kSampler) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002399 result = kUniforms_Requirement;
Timothy Liangee84fe12018-05-18 14:38:19 -04002400 } else {
2401 result = kGlobals_Requirement;
Ethan Nicholascc305772017-10-13 16:17:45 -04002402 }
2403 }
2404 return result;
2405 }
2406 default:
2407 return kNo_Requirements;
2408 }
2409}
2410
Ethan Nicholasff350cb2020-05-14 14:05:13 -04002411MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const Statement* s) {
2412 if (!s) {
2413 return kNo_Requirements;
2414 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002415 switch (s->kind()) {
2416 case Statement::Kind::kBlock: {
Ethan Nicholascc305772017-10-13 16:17:45 -04002417 Requirements result = kNo_Requirements;
Ethan Nicholas7bd60432020-09-25 14:31:59 -04002418 for (const std::unique_ptr<Statement>& child : s->as<Block>().children()) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04002419 result |= this->requirements(child.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002420 }
2421 return result;
2422 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002423 case Statement::Kind::kVarDeclaration: {
John Stiles3dc0da62020-08-19 17:48:31 -04002424 const VarDeclaration& var = s->as<VarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04002425 return this->requirements(var.value().get());
Timothy Liang7d637782018-06-05 09:58:07 -04002426 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002427 case Statement::Kind::kExpression:
Ethan Nicholasd503a5a2020-09-30 09:29:55 -04002428 return this->requirements(s->as<ExpressionStatement>().expression().get());
Ethan Nicholase6592142020-09-08 10:22:09 -04002429 case Statement::Kind::kReturn: {
John Stiles3dc0da62020-08-19 17:48:31 -04002430 const ReturnStatement& r = s->as<ReturnStatement>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04002431 return this->requirements(r.expression().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002432 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002433 case Statement::Kind::kIf: {
John Stiles3dc0da62020-08-19 17:48:31 -04002434 const IfStatement& i = s->as<IfStatement>();
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04002435 return this->requirements(i.test().get()) |
2436 this->requirements(i.ifTrue().get()) |
2437 this->requirements(i.ifFalse().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002438 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002439 case Statement::Kind::kFor: {
John Stiles3dc0da62020-08-19 17:48:31 -04002440 const ForStatement& f = s->as<ForStatement>();
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04002441 return this->requirements(f.initializer().get()) |
2442 this->requirements(f.test().get()) |
2443 this->requirements(f.next().get()) |
2444 this->requirements(f.statement().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002445 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002446 case Statement::Kind::kDo: {
John Stiles3dc0da62020-08-19 17:48:31 -04002447 const DoStatement& d = s->as<DoStatement>();
Ethan Nicholas1fd61162020-09-28 13:14:19 -04002448 return this->requirements(d.test().get()) |
2449 this->requirements(d.statement().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002450 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002451 case Statement::Kind::kSwitch: {
John Stiles3dc0da62020-08-19 17:48:31 -04002452 const SwitchStatement& sw = s->as<SwitchStatement>();
Ethan Nicholas01b05e52020-10-22 15:53:41 -04002453 Requirements result = this->requirements(sw.value().get());
John Stilesb23a64b2021-03-11 08:27:59 -05002454 for (const std::unique_ptr<Statement>& sc : sw.cases()) {
2455 result |= this->requirements(sc->as<SwitchCase>().statement().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002456 }
2457 return result;
2458 }
2459 default:
2460 return kNo_Requirements;
2461 }
2462}
2463
2464MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const FunctionDeclaration& f) {
Ethan Nicholased84b732020-10-08 11:45:44 -04002465 if (f.isBuiltin()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002466 return kNo_Requirements;
2467 }
2468 auto found = fRequirements.find(&f);
2469 if (found == fRequirements.end()) {
Ethan Nicholas65a8f562019-04-19 14:00:26 -04002470 fRequirements[&f] = kNo_Requirements;
Brian Osman133724c2020-10-28 14:14:39 -04002471 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04002472 if (e->is<FunctionDefinition>()) {
2473 const FunctionDefinition& def = e->as<FunctionDefinition>();
Ethan Nicholas0a5d0962020-10-14 13:33:18 -04002474 if (&def.declaration() == &f) {
2475 Requirements reqs = this->requirements(def.body().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002476 fRequirements[&f] = reqs;
2477 return reqs;
2478 }
2479 }
2480 }
John Stiles569249b2020-11-03 12:18:22 -05002481 // We never found a definition for this declared function, but it's legal to prototype a
2482 // function without ever giving a definition, as long as you don't call it.
2483 return kNo_Requirements;
Ethan Nicholascc305772017-10-13 16:17:45 -04002484 }
2485 return found->second;
2486}
2487
Timothy Liangb8eeb802018-07-23 16:46:16 -04002488bool MetalCodeGenerator::generateCode() {
John Stiles44532372020-12-07 12:33:55 -05002489 StringStream header;
2490 {
2491 AutoOutputStream outputToHeader(this, &header, &fIndentation);
Michael Ludwigbf58add2021-03-16 10:40:11 -04002492 this->writeHeader();
John Stiles44532372020-12-07 12:33:55 -05002493 this->writeStructDefinitions();
2494 this->writeUniformStruct();
2495 this->writeInputStruct();
2496 this->writeOutputStruct();
2497 this->writeInterfaceBlocks();
2498 this->writeGlobalStruct();
2499 }
2500 StringStream body;
2501 {
2502 AutoOutputStream outputToBody(this, &body, &fIndentation);
2503 for (const ProgramElement* e : fProgram.elements()) {
2504 this->writeProgramElement(*e);
2505 }
2506 }
2507 write_stringstream(header, *fOut);
2508 write_stringstream(fExtraFunctions, *fOut);
2509 write_stringstream(body, *fOut);
Brian Osman8609a242020-09-08 14:01:49 -04002510 return 0 == fErrors.errorCount();
Ethan Nicholascc305772017-10-13 16:17:45 -04002511}
2512
John Stilesa6841be2020-08-06 14:11:56 -04002513} // namespace SkSL