blob: 038dd906c4e21818f356baa827176b988e81492e [file] [log] [blame]
Ethan Nicholascc305772017-10-13 16:17:45 -04001/*
2 * Copyright 2016 Google Inc.
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
7
Mike Kleinc0bd9f92019-04-23 12:05:21 -05008#include "src/sksl/SkSLMetalCodeGenerator.h"
Ethan Nicholascc305772017-10-13 16:17:45 -04009
John Stiles986c7fb2020-12-01 14:44:56 -050010#include "src/core/SkScopeExit.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050011#include "src/sksl/SkSLCompiler.h"
John Stiles0023c0c2020-11-16 13:32:18 -050012#include "src/sksl/SkSLMemoryLayout.h"
John Stiles7384b372021-04-01 13:48:15 -040013#include "src/sksl/ir/SkSLConstructorArray.h"
14#include "src/sksl/ir/SkSLConstructorDiagonalMatrix.h"
John Stiles2938eea2021-04-01 18:58:25 -040015#include "src/sksl/ir/SkSLConstructorSplat.h"
John Stilesb14a8192021-04-05 11:40:46 -040016#include "src/sksl/ir/SkSLConstructorVectorCast.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050017#include "src/sksl/ir/SkSLExpressionStatement.h"
18#include "src/sksl/ir/SkSLExtension.h"
19#include "src/sksl/ir/SkSLIndexExpression.h"
20#include "src/sksl/ir/SkSLModifiersDeclaration.h"
21#include "src/sksl/ir/SkSLNop.h"
John Stilesdc75a972020-11-25 16:24:55 -050022#include "src/sksl/ir/SkSLStructDefinition.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050023#include "src/sksl/ir/SkSLVariableReference.h"
Ethan Nicholascc305772017-10-13 16:17:45 -040024
Brian Osmanc262a122020-08-06 16:34:34 -040025#include <algorithm>
26
Ethan Nicholascc305772017-10-13 16:17:45 -040027namespace SkSL {
28
John Stiles45990502021-02-16 10:55:27 -050029const char* MetalCodeGenerator::OperatorName(Operator op) {
30 switch (op.kind()) {
John Stilesd6449e92020-11-30 09:13:23 -050031 case Token::Kind::TK_LOGICALXOR: return "!=";
John Stiles45990502021-02-16 10:55:27 -050032 default: return op.operatorName();
John Stilesd6449e92020-11-30 09:13:23 -050033 }
34}
35
John Stilescdcdb042020-07-06 09:03:51 -040036class MetalCodeGenerator::GlobalStructVisitor {
37public:
38 virtual ~GlobalStructVisitor() = default;
John Stilesfdb8dbe2020-12-04 11:00:03 -050039 virtual void visitInterfaceBlock(const InterfaceBlock& block, const String& blockName) = 0;
40 virtual void visitTexture(const Type& type, const String& name) = 0;
41 virtual void visitSampler(const Type& type, const String& name) = 0;
42 virtual void visitVariable(const Variable& var, const Expression* value) = 0;
John Stilescdcdb042020-07-06 09:03:51 -040043};
44
Timothy Liangee84fe12018-05-18 14:38:19 -040045void MetalCodeGenerator::setupIntrinsics() {
John Stilesd7199b22020-12-30 16:22:58 -050046 fIntrinsicMap[String("atan")] = kAtan_IntrinsicKind;
47 fIntrinsicMap[String("floatBitsToInt")] = kBitcast_IntrinsicKind;
48 fIntrinsicMap[String("floatBitsToUint")] = kBitcast_IntrinsicKind;
49 fIntrinsicMap[String("intBitsToFloat")] = kBitcast_IntrinsicKind;
50 fIntrinsicMap[String("uintBitsToFloat")] = kBitcast_IntrinsicKind;
51 fIntrinsicMap[String("equal")] = kCompareEqual_IntrinsicKind;
52 fIntrinsicMap[String("notEqual")] = kCompareNotEqual_IntrinsicKind;
53 fIntrinsicMap[String("lessThan")] = kCompareLessThan_IntrinsicKind;
54 fIntrinsicMap[String("lessThanEqual")] = kCompareLessThanEqual_IntrinsicKind;
55 fIntrinsicMap[String("greaterThan")] = kCompareGreaterThan_IntrinsicKind;
56 fIntrinsicMap[String("greaterThanEqual")] = kCompareGreaterThanEqual_IntrinsicKind;
57 fIntrinsicMap[String("degrees")] = kDegrees_IntrinsicKind;
58 fIntrinsicMap[String("dFdx")] = kDFdx_IntrinsicKind;
59 fIntrinsicMap[String("dFdy")] = kDFdy_IntrinsicKind;
60 fIntrinsicMap[String("distance")] = kDistance_IntrinsicKind;
61 fIntrinsicMap[String("dot")] = kDot_IntrinsicKind;
62 fIntrinsicMap[String("faceforward")] = kFaceforward_IntrinsicKind;
63 fIntrinsicMap[String("bitCount")] = kBitCount_IntrinsicKind;
64 fIntrinsicMap[String("findLSB")] = kFindLSB_IntrinsicKind;
65 fIntrinsicMap[String("findMSB")] = kFindMSB_IntrinsicKind;
66 fIntrinsicMap[String("inverse")] = kInverse_IntrinsicKind;
67 fIntrinsicMap[String("inversesqrt")] = kInversesqrt_IntrinsicKind;
68 fIntrinsicMap[String("length")] = kLength_IntrinsicKind;
69 fIntrinsicMap[String("matrixCompMult")] = kMatrixCompMult_IntrinsicKind;
70 fIntrinsicMap[String("mod")] = kMod_IntrinsicKind;
71 fIntrinsicMap[String("normalize")] = kNormalize_IntrinsicKind;
72 fIntrinsicMap[String("radians")] = kRadians_IntrinsicKind;
73 fIntrinsicMap[String("reflect")] = kReflect_IntrinsicKind;
74 fIntrinsicMap[String("refract")] = kRefract_IntrinsicKind;
John Stiles23456532020-12-30 18:12:48 -050075 fIntrinsicMap[String("roundEven")] = kRoundEven_IntrinsicKind;
John Stilesd7199b22020-12-30 16:22:58 -050076 fIntrinsicMap[String("sample")] = kTexture_IntrinsicKind;
Timothy Liangee84fe12018-05-18 14:38:19 -040077}
78
Ethan Nicholascc305772017-10-13 16:17:45 -040079void MetalCodeGenerator::write(const char* s) {
80 if (!s[0]) {
81 return;
82 }
83 if (fAtLineStart) {
84 for (int i = 0; i < fIndentation; i++) {
85 fOut->writeText(" ");
86 }
87 }
88 fOut->writeText(s);
89 fAtLineStart = false;
90}
91
92void MetalCodeGenerator::writeLine(const char* s) {
93 this->write(s);
John Stilese8b5a732021-03-12 13:25:52 -050094 this->writeLine();
Ethan Nicholascc305772017-10-13 16:17:45 -040095}
96
97void MetalCodeGenerator::write(const String& s) {
98 this->write(s.c_str());
99}
100
101void MetalCodeGenerator::writeLine(const String& s) {
102 this->writeLine(s.c_str());
103}
104
105void MetalCodeGenerator::writeLine() {
John Stilese8b5a732021-03-12 13:25:52 -0500106 fOut->writeText(fLineEnding);
107 fAtLineStart = true;
108}
109
110void MetalCodeGenerator::finishLine() {
111 if (!fAtLineStart) {
112 this->writeLine();
113 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400114}
115
116void MetalCodeGenerator::writeExtension(const Extension& ext) {
Ethan Nicholasefb09e22020-09-30 10:17:00 -0400117 this->writeLine("#extension " + ext.name() + " : enable");
Ethan Nicholascc305772017-10-13 16:17:45 -0400118}
119
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500120String MetalCodeGenerator::typeName(const Type& type) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400121 switch (type.typeKind()) {
John Stilesb4418502021-02-04 10:57:08 -0500122 case Type::TypeKind::kArray:
123 SkASSERTF(type.columns() > 0, "invalid array size: %s", type.description().c_str());
124 return String::printf("array<%s, %d>",
125 this->typeName(type.componentType()).c_str(), type.columns());
126
Ethan Nicholase6592142020-09-08 10:22:09 -0400127 case Type::TypeKind::kVector:
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500128 return this->typeName(type.componentType()) + to_string(type.columns());
John Stilesb4418502021-02-04 10:57:08 -0500129
Ethan Nicholase6592142020-09-08 10:22:09 -0400130 case Type::TypeKind::kMatrix:
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500131 return this->typeName(type.componentType()) + to_string(type.columns()) + "x" +
132 to_string(type.rows());
John Stilesb4418502021-02-04 10:57:08 -0500133
Ethan Nicholase6592142020-09-08 10:22:09 -0400134 case Type::TypeKind::kSampler:
John Stiles368db7c2020-12-29 11:20:08 -0500135 return "texture2d<float>"; // FIXME - support other texture types
John Stilesb4418502021-02-04 10:57:08 -0500136
John Stilesfd41d872020-11-25 22:39:45 -0500137 case Type::TypeKind::kEnum:
138 return "int";
John Stilesb4418502021-02-04 10:57:08 -0500139
Ethan Nicholascc305772017-10-13 16:17:45 -0400140 default:
John Stiles54e7c052021-01-11 14:22:36 -0500141 if (type == *fContext.fTypes.fHalf) {
Timothy Liang43d225f2018-07-19 15:27:13 -0400142 // FIXME - Currently only supporting floats in MSL to avoid type coercion issues.
John Stiles54e7c052021-01-11 14:22:36 -0500143 return fContext.fTypes.fFloat->name();
144 } else if (type == *fContext.fTypes.fByte) {
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500145 return "char";
John Stiles54e7c052021-01-11 14:22:36 -0500146 } else if (type == *fContext.fTypes.fUByte) {
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500147 return "uchar";
Timothy Liang7d637782018-06-05 09:58:07 -0400148 } else {
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500149 return type.name();
Timothy Liang7d637782018-06-05 09:58:07 -0400150 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400151 }
152}
153
Brian Osman02bc5222021-01-28 11:00:20 -0500154void MetalCodeGenerator::writeStructDefinition(const StructDefinition& s) {
155 const Type& type = s.type();
John Stilesdc75a972020-11-25 16:24:55 -0500156 this->writeLine("struct " + type.name() + " {");
157 fIndentation++;
158 this->writeFields(type.fields(), type.fOffset);
159 fIndentation--;
Brian Osman02bc5222021-01-28 11:00:20 -0500160 this->writeLine("};");
John Stilesdc75a972020-11-25 16:24:55 -0500161}
162
John Stilesb4418502021-02-04 10:57:08 -0500163void MetalCodeGenerator::writeType(const Type& type) {
164 this->write(this->typeName(type));
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500165}
166
Ethan Nicholascc305772017-10-13 16:17:45 -0400167void MetalCodeGenerator::writeExpression(const Expression& expr, Precedence parentPrecedence) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400168 switch (expr.kind()) {
169 case Expression::Kind::kBinary:
John Stiles81365af2020-08-18 09:24:00 -0400170 this->writeBinaryExpression(expr.as<BinaryExpression>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400171 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400172 case Expression::Kind::kBoolLiteral:
John Stiles81365af2020-08-18 09:24:00 -0400173 this->writeBoolLiteral(expr.as<BoolLiteral>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400174 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400175 case Expression::Kind::kConstructor:
John Stiles81365af2020-08-18 09:24:00 -0400176 this->writeConstructor(expr.as<Constructor>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400177 break;
John Stiles7384b372021-04-01 13:48:15 -0400178 case Expression::Kind::kConstructorArray:
John Stilesb14a8192021-04-05 11:40:46 -0400179 this->writeAnyConstructor(expr.asAnyConstructor(), "{", "}", parentPrecedence);
John Stiles7384b372021-04-01 13:48:15 -0400180 break;
John Stilese1182782021-03-30 22:09:37 -0400181 case Expression::Kind::kConstructorDiagonalMatrix:
John Stilesb14a8192021-04-05 11:40:46 -0400182 case Expression::Kind::kConstructorSplat:
183 this->writeAnyConstructor(expr.asAnyConstructor(), "(", ")", parentPrecedence);
John Stilese1182782021-03-30 22:09:37 -0400184 break;
John Stilesfd7252f2021-04-04 22:24:40 -0400185 case Expression::Kind::kConstructorScalarCast:
John Stilesb14a8192021-04-05 11:40:46 -0400186 case Expression::Kind::kConstructorVectorCast:
187 this->writeCastConstructor(expr.asAnyConstructor(), "(", ")", parentPrecedence);
John Stiles2938eea2021-04-01 18:58:25 -0400188 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400189 case Expression::Kind::kIntLiteral:
John Stiles81365af2020-08-18 09:24:00 -0400190 this->writeIntLiteral(expr.as<IntLiteral>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400191 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400192 case Expression::Kind::kFieldAccess:
John Stiles81365af2020-08-18 09:24:00 -0400193 this->writeFieldAccess(expr.as<FieldAccess>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400194 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400195 case Expression::Kind::kFloatLiteral:
John Stiles81365af2020-08-18 09:24:00 -0400196 this->writeFloatLiteral(expr.as<FloatLiteral>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400197 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400198 case Expression::Kind::kFunctionCall:
John Stiles81365af2020-08-18 09:24:00 -0400199 this->writeFunctionCall(expr.as<FunctionCall>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400200 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400201 case Expression::Kind::kPrefix:
John Stiles81365af2020-08-18 09:24:00 -0400202 this->writePrefixExpression(expr.as<PrefixExpression>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400203 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400204 case Expression::Kind::kPostfix:
John Stiles81365af2020-08-18 09:24:00 -0400205 this->writePostfixExpression(expr.as<PostfixExpression>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400206 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400207 case Expression::Kind::kSetting:
John Stiles81365af2020-08-18 09:24:00 -0400208 this->writeSetting(expr.as<Setting>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400209 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400210 case Expression::Kind::kSwizzle:
John Stiles81365af2020-08-18 09:24:00 -0400211 this->writeSwizzle(expr.as<Swizzle>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400212 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400213 case Expression::Kind::kVariableReference:
John Stiles81365af2020-08-18 09:24:00 -0400214 this->writeVariableReference(expr.as<VariableReference>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400215 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400216 case Expression::Kind::kTernary:
John Stiles81365af2020-08-18 09:24:00 -0400217 this->writeTernaryExpression(expr.as<TernaryExpression>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400218 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400219 case Expression::Kind::kIndex:
John Stiles81365af2020-08-18 09:24:00 -0400220 this->writeIndexExpression(expr.as<IndexExpression>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400221 break;
222 default:
John Stileseada7bc2021-02-02 16:29:32 -0500223 SkDEBUGFAILF("unsupported expression: %s", expr.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -0500224 break;
Ethan Nicholascc305772017-10-13 16:17:45 -0400225 }
226}
227
John Stiles06b84ef2020-12-09 12:35:48 -0500228String MetalCodeGenerator::getOutParamHelper(const FunctionCall& call,
229 const ExpressionArray& arguments,
230 const SkTArray<VariableReference*>& outVars) {
231 AutoOutputStream outputToExtraFunctions(this, &fExtraFunctions, &fIndentation);
232 const FunctionDeclaration& function = call.function();
233
John Stilese1068342021-03-22 11:57:41 -0400234 String name = "_skOutParamHelper" + to_string(fSwizzleHelperCount++) +
235 "_" + function.mangledName();
John Stiles06b84ef2020-12-09 12:35:48 -0500236 const char* separator = "";
237
238 // Emit a prototype for the function we'll be calling through to in our helper.
239 if (!function.isBuiltin()) {
240 this->writeFunctionDeclaration(function);
241 this->writeLine(";");
242 }
243
244 // Synthesize a helper function that takes the same inputs as `function`, except in places where
245 // `outVars` is non-null; in those places, we take the type of the VariableReference.
246 //
247 // float _skOutParamHelper0_originalFuncName(float _var0, float _var1, float& outParam) {
John Stilesb4418502021-02-04 10:57:08 -0500248 this->writeType(call.type());
John Stiles06b84ef2020-12-09 12:35:48 -0500249 this->write(" ");
250 this->write(name);
251 this->write("(");
252 this->writeFunctionRequirementParams(function, separator);
253
254 SkASSERT(outVars.size() == arguments.size());
255 SkASSERT(outVars.size() == function.parameters().size());
256
John Stiles73e2c892021-02-13 13:58:01 -0500257 // We need to detect cases where the caller passes the same variable as an out-param more than
258 // once, and avoid reusing the variable name. (In those cases we can actually just ignore the
259 // redundant input parameter entirely, and not give it any name.)
260 std::unordered_set<const Variable*> writtenVars;
261
John Stiles06b84ef2020-12-09 12:35:48 -0500262 for (int index = 0; index < arguments.count(); ++index) {
263 this->write(separator);
264 separator = ", ";
265
266 const Variable* param = function.parameters()[index];
267 this->writeModifiers(param->modifiers(), /*globalContext=*/false);
268
269 const Type* type = outVars[index] ? &outVars[index]->type() : &arguments[index]->type();
John Stilesb4418502021-02-04 10:57:08 -0500270 this->writeType(*type);
John Stiles06b84ef2020-12-09 12:35:48 -0500271
272 if (param->modifiers().fFlags & Modifiers::kOut_Flag) {
273 this->write("&");
274 }
275 if (outVars[index]) {
John Stiles73e2c892021-02-13 13:58:01 -0500276 auto [iter, didInsert] = writtenVars.insert(outVars[index]->variable());
277 if (didInsert) {
278 this->write(" ");
279 fIgnoreVariableReferenceModifiers = true;
280 this->writeVariableReference(*outVars[index]);
281 fIgnoreVariableReferenceModifiers = false;
282 }
John Stiles06b84ef2020-12-09 12:35:48 -0500283 } else {
284 this->write(" _var");
285 this->write(to_string(index));
286 }
John Stiles06b84ef2020-12-09 12:35:48 -0500287 }
288 this->writeLine(") {");
289
290 ++fIndentation;
291 for (int index = 0; index < outVars.count(); ++index) {
292 if (!outVars[index]) {
293 continue;
294 }
295 // float3 _var2[ = outParam.zyx];
John Stilesb4418502021-02-04 10:57:08 -0500296 this->writeType(arguments[index]->type());
John Stiles06b84ef2020-12-09 12:35:48 -0500297 this->write(" _var");
298 this->write(to_string(index));
299
300 const Variable* param = function.parameters()[index];
301 if (param->modifiers().fFlags & Modifiers::kIn_Flag) {
302 this->write(" = ");
303 fIgnoreVariableReferenceModifiers = true;
Brian Osman00185012021-02-04 16:07:11 -0500304 this->writeExpression(*arguments[index], Precedence::kAssignment);
John Stiles06b84ef2020-12-09 12:35:48 -0500305 fIgnoreVariableReferenceModifiers = false;
306 }
307
308 this->writeLine(";");
309 }
310
John Stilesf7410bd2021-01-19 13:07:55 -0500311 // [int _skResult = ] myFunction(inputs, outputs, _globals, _var0, _var1, _var2, _var3);
John Stiles06b84ef2020-12-09 12:35:48 -0500312 bool hasResult = (call.type().name() != "void");
313 if (hasResult) {
John Stilesb4418502021-02-04 10:57:08 -0500314 this->writeType(call.type());
John Stiles06b84ef2020-12-09 12:35:48 -0500315 this->write(" _skResult = ");
316 }
317
John Stilese1068342021-03-22 11:57:41 -0400318 this->writeName(function.mangledName());
John Stiles06b84ef2020-12-09 12:35:48 -0500319 this->write("(");
320 separator = "";
321 this->writeFunctionRequirementArgs(function, separator);
322
323 for (int index = 0; index < arguments.count(); ++index) {
324 this->write(separator);
325 separator = ", ";
326
327 this->write("_var");
328 this->write(to_string(index));
329 }
330 this->writeLine(");");
331
332 for (int index = 0; index < outVars.count(); ++index) {
333 if (!outVars[index]) {
334 continue;
335 }
336 // outParam.zyx = _var2;
337 fIgnoreVariableReferenceModifiers = true;
Brian Osman00185012021-02-04 16:07:11 -0500338 this->writeExpression(*arguments[index], Precedence::kAssignment);
John Stiles06b84ef2020-12-09 12:35:48 -0500339 fIgnoreVariableReferenceModifiers = false;
340 this->write(" = _var");
341 this->write(to_string(index));
342 this->writeLine(";");
343 }
344
345 if (hasResult) {
346 this->writeLine("return _skResult;");
347 }
348
349 --fIndentation;
350 this->writeLine("}");
351
352 return name;
John Stilesb21fac22020-12-04 15:36:49 -0500353}
354
John Stilesf64e4072020-12-10 10:34:27 -0500355String MetalCodeGenerator::getBitcastIntrinsic(const Type& outType) {
356 return "as_type<" + outType.displayName() + ">";
357}
358
Ethan Nicholascc305772017-10-13 16:17:45 -0400359void MetalCodeGenerator::writeFunctionCall(const FunctionCall& c) {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400360 const FunctionDeclaration& function = c.function();
John Stiles89ac7c22020-12-30 17:47:31 -0500361 // If this function is a built-in with no declaration, it's probably an intrinsic and might need
362 // special handling.
363 if (function.isBuiltin() && !function.definition()) {
364 auto iter = fIntrinsicMap.find(function.name());
365 if (iter != fIntrinsicMap.end()) {
366 this->writeIntrinsicCall(c, iter->second);
367 return;
368 }
Timothy Liang6403b0e2018-05-17 10:40:04 -0400369 }
John Stilesb21fac22020-12-04 15:36:49 -0500370
John Stilesd7199b22020-12-30 16:22:58 -0500371 // Determine whether or not we need to emulate GLSL's out-param semantics for Metal using a
372 // helper function. (Specifically, out-parameters in GLSL are only written back to the original
373 // variable at the end of the function call; also, swizzles are supported, whereas Metal doesn't
374 // allow a swizzle to be passed to a `floatN&`.)
375 const ExpressionArray& arguments = c.arguments();
John Stilesb21fac22020-12-04 15:36:49 -0500376 const std::vector<const Variable*>& parameters = function.parameters();
377 SkASSERT(arguments.size() == parameters.size());
John Stiles06b84ef2020-12-09 12:35:48 -0500378
379 bool foundOutParam = false;
380 SkSTArray<16, VariableReference*> outVars;
John Stilesf64e4072020-12-10 10:34:27 -0500381 outVars.push_back_n(arguments.count(), (VariableReference*)nullptr);
John Stiles06b84ef2020-12-09 12:35:48 -0500382
383 for (int index = 0; index < arguments.count(); ++index) {
John Stilesb21fac22020-12-04 15:36:49 -0500384 // If this is an out parameter...
385 if (parameters[index]->modifiers().fFlags & Modifiers::kOut_Flag) {
John Stiles06b84ef2020-12-09 12:35:48 -0500386 // Find the expression's inner variable being written to.
John Stilesb21fac22020-12-04 15:36:49 -0500387 Analysis::AssignmentInfo info;
John Stiles06b84ef2020-12-09 12:35:48 -0500388 // Assignability was verified at IRGeneration time, so this should always succeed.
389 SkAssertResult(Analysis::IsAssignable(*arguments[index], &info));
390 outVars[index] = info.fAssignedVar;
391 foundOutParam = true;
John Stilesb21fac22020-12-04 15:36:49 -0500392 }
393 }
394
John Stiles06b84ef2020-12-09 12:35:48 -0500395 if (foundOutParam) {
396 // Out parameters need to be written back to at the end of the function. To do this, we
397 // synthesize a helper function which evaluates the out-param expression into a temporary
398 // variable, calls the original function, then writes the temp var back into the out param
399 // using the original out-param expression. (This lets us support things like swizzles and
400 // array indices.)
John Stilesd7199b22020-12-30 16:22:58 -0500401 this->write(getOutParamHelper(c, arguments, outVars));
402 } else {
John Stilese1068342021-03-22 11:57:41 -0400403 this->write(function.mangledName());
John Stiles06b84ef2020-12-09 12:35:48 -0500404 }
405
Ethan Nicholascc305772017-10-13 16:17:45 -0400406 this->write("(");
407 const char* separator = "";
John Stiles06b84ef2020-12-09 12:35:48 -0500408 this->writeFunctionRequirementArgs(function, separator);
409 for (int i = 0; i < arguments.count(); ++i) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400410 this->write(separator);
411 separator = ", ";
John Stiles06b84ef2020-12-09 12:35:48 -0500412
413 if (outVars[i]) {
Brian Osman00185012021-02-04 16:07:11 -0500414 this->writeExpression(*outVars[i], Precedence::kSequence);
John Stiles06b84ef2020-12-09 12:35:48 -0500415 } else {
Brian Osman00185012021-02-04 16:07:11 -0500416 this->writeExpression(*arguments[i], Precedence::kSequence);
John Stiles06b84ef2020-12-09 12:35:48 -0500417 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400418 }
419 this->write(")");
420}
421
Brian Osman964f0a02020-12-29 10:15:22 -0500422static constexpr char kInverse2x2[] = R"(
423float2x2 float2x2_inverse(float2x2 m) {
424 return float2x2(m[1][1], -m[0][1], -m[1][0], m[0][0]) * (1/determinant(m));
425}
426)";
427
428static constexpr char kInverse3x3[] = R"(
429float3x3 float3x3_inverse(float3x3 m) {
430 float a00 = m[0][0], a01 = m[0][1], a02 = m[0][2];
431 float a10 = m[1][0], a11 = m[1][1], a12 = m[1][2];
432 float a20 = m[2][0], a21 = m[2][1], a22 = m[2][2];
433 float b01 = a22*a11 - a12*a21;
434 float b11 = -a22*a10 + a12*a20;
435 float b21 = a21*a10 - a11*a20;
436 float det = a00*b01 + a01*b11 + a02*b21;
437 return float3x3(b01, (-a22*a01 + a02*a21), ( a12*a01 - a02*a11),
438 b11, ( a22*a00 - a02*a20), (-a12*a00 + a02*a10),
439 b21, (-a21*a00 + a01*a20), ( a11*a00 - a01*a10)) * (1/det);
440}
441)";
442
443static constexpr char kInverse4x4[] = R"(
444float4x4 float4x4_inverse(float4x4 m) {
445 float a00 = m[0][0], a01 = m[0][1], a02 = m[0][2], a03 = m[0][3];
446 float a10 = m[1][0], a11 = m[1][1], a12 = m[1][2], a13 = m[1][3];
447 float a20 = m[2][0], a21 = m[2][1], a22 = m[2][2], a23 = m[2][3];
448 float a30 = m[3][0], a31 = m[3][1], a32 = m[3][2], a33 = m[3][3];
449 float b00 = a00*a11 - a01*a10;
450 float b01 = a00*a12 - a02*a10;
451 float b02 = a00*a13 - a03*a10;
452 float b03 = a01*a12 - a02*a11;
453 float b04 = a01*a13 - a03*a11;
454 float b05 = a02*a13 - a03*a12;
455 float b06 = a20*a31 - a21*a30;
456 float b07 = a20*a32 - a22*a30;
457 float b08 = a20*a33 - a23*a30;
458 float b09 = a21*a32 - a22*a31;
459 float b10 = a21*a33 - a23*a31;
460 float b11 = a22*a33 - a23*a32;
461 float det = b00*b11 - b01*b10 + b02*b09 + b03*b08 - b04*b07 + b05*b06;
462 return float4x4(a11*b11 - a12*b10 + a13*b09,
463 a02*b10 - a01*b11 - a03*b09,
464 a31*b05 - a32*b04 + a33*b03,
465 a22*b04 - a21*b05 - a23*b03,
466 a12*b08 - a10*b11 - a13*b07,
467 a00*b11 - a02*b08 + a03*b07,
468 a32*b02 - a30*b05 - a33*b01,
469 a20*b05 - a22*b02 + a23*b01,
470 a10*b10 - a11*b08 + a13*b06,
471 a01*b08 - a00*b10 - a03*b06,
472 a30*b04 - a31*b02 + a33*b00,
473 a21*b02 - a20*b04 - a23*b00,
474 a11*b07 - a10*b09 - a12*b06,
475 a00*b09 - a01*b07 + a02*b06,
476 a31*b01 - a30*b03 - a32*b00,
477 a20*b03 - a21*b01 + a22*b00) * (1/det);
478}
479)";
480
John Stilesd7199b22020-12-30 16:22:58 -0500481String MetalCodeGenerator::getInversePolyfill(const ExpressionArray& arguments) {
482 // Only use polyfills for a function taking a single-argument square matrix.
483 if (arguments.size() == 1) {
484 const Type& type = arguments.front()->type();
485 if (type.isMatrix() && type.rows() == type.columns()) {
486 // Inject the correct polyfill based on the matrix size.
487 String name = this->typeName(type) + "_inverse";
488 auto [iter, didInsert] = fWrittenIntrinsics.insert(name);
489 if (didInsert) {
490 switch (type.rows()) {
491 case 2:
492 fExtraFunctions.writeText(kInverse2x2);
493 break;
494 case 3:
495 fExtraFunctions.writeText(kInverse3x3);
496 break;
497 case 4:
498 fExtraFunctions.writeText(kInverse4x4);
499 break;
500 }
501 }
502 return name;
Chris Daltondba7aab2018-11-15 10:57:49 -0500503 }
504 }
John Stilesd7199b22020-12-30 16:22:58 -0500505 // This isn't the built-in `inverse`. We don't want to polyfill it at all.
506 return "inverse";
Chris Daltondba7aab2018-11-15 10:57:49 -0500507}
508
Brian Osman93aed9a2020-12-28 15:18:46 -0500509static constexpr char kMatrixCompMult[] = R"(
510template <int C, int R>
511matrix<float, C, R> matrixCompMult(matrix<float, C, R> a, matrix<float, C, R> b) {
512 matrix<float, C, R> result;
513 for (int c = 0; c < C; ++c) {
514 result[c] = a[c] * b[c];
515 }
516 return result;
517}
518)";
519
520void MetalCodeGenerator::writeMatrixCompMult() {
521 String name = "matrixCompMult";
522 if (fWrittenIntrinsics.find(name) == fWrittenIntrinsics.end()) {
523 fWrittenIntrinsics.insert(name);
524 fExtraFunctions.writeText(kMatrixCompMult);
525 }
526}
527
John Stiles86424eb2020-12-11 11:17:14 -0500528String MetalCodeGenerator::getTempVariable(const Type& type) {
529 String tempVar = "_skTemp" + to_string(fVarCount++);
530 this->fFunctionHeader += " " + this->typeName(type) + " " + tempVar + ";\n";
531 return tempVar;
532}
533
John Stiles791c27d2020-12-30 14:56:57 -0500534void MetalCodeGenerator::writeSimpleIntrinsic(const FunctionCall& c) {
535 // Write out an intrinsic function call exactly as-is. No muss no fuss.
536 this->write(c.function().name());
John Stilesd7199b22020-12-30 16:22:58 -0500537 this->writeArgumentList(c.arguments());
538}
539
540void MetalCodeGenerator::writeArgumentList(const ExpressionArray& arguments) {
John Stiles791c27d2020-12-30 14:56:57 -0500541 this->write("(");
542 const char* separator = "";
John Stilesd7199b22020-12-30 16:22:58 -0500543 for (const std::unique_ptr<Expression>& arg : arguments) {
John Stiles791c27d2020-12-30 14:56:57 -0500544 this->write(separator);
545 separator = ", ";
Brian Osman00185012021-02-04 16:07:11 -0500546 this->writeExpression(*arg, Precedence::kSequence);
John Stiles791c27d2020-12-30 14:56:57 -0500547 }
548 this->write(")");
549}
550
John Stilesd7199b22020-12-30 16:22:58 -0500551void MetalCodeGenerator::writeIntrinsicCall(const FunctionCall& c, IntrinsicKind kind) {
John Stiles8e3b6be2020-10-13 11:14:08 -0400552 const ExpressionArray& arguments = c.arguments();
Timothy Liang6403b0e2018-05-17 10:40:04 -0400553 switch (kind) {
John Stilesd7199b22020-12-30 16:22:58 -0500554 case kTexture_IntrinsicKind: {
Brian Osman00185012021-02-04 16:07:11 -0500555 this->writeExpression(*arguments[0], Precedence::kSequence);
Timothy Lianga06f2152018-05-24 15:33:31 -0400556 this->write(".sample(");
Brian Osman00185012021-02-04 16:07:11 -0500557 this->writeExpression(*arguments[0], Precedence::kSequence);
Timothy Lianga06f2152018-05-24 15:33:31 -0400558 this->write(SAMPLER_SUFFIX);
559 this->write(", ");
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400560 const Type& arg1Type = arguments[1]->type();
John Stilesb14a8192021-04-05 11:40:46 -0400561 if (arg1Type.columns() == 3) {
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500562 // have to store the vector in a temp variable to avoid double evaluating it
John Stiles86424eb2020-12-11 11:17:14 -0500563 String tmpVar = this->getTempVariable(arg1Type);
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500564 this->write("(" + tmpVar + " = ");
Brian Osman00185012021-02-04 16:07:11 -0500565 this->writeExpression(*arguments[1], Precedence::kSequence);
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500566 this->write(", " + tmpVar + ".xy / " + tmpVar + ".z))");
Timothy Liangee84fe12018-05-18 14:38:19 -0400567 } else {
John Stilesb14a8192021-04-05 11:40:46 -0400568 SkASSERT(arg1Type.columns() == 2);
Brian Osman00185012021-02-04 16:07:11 -0500569 this->writeExpression(*arguments[1], Precedence::kSequence);
Timothy Liangee84fe12018-05-18 14:38:19 -0400570 this->write(")");
571 }
Timothy Liang6403b0e2018-05-17 10:40:04 -0400572 break;
Ethan Nicholas30d30222020-09-11 12:27:26 -0400573 }
John Stilesd7199b22020-12-30 16:22:58 -0500574 case kMod_IntrinsicKind: {
Timothy Liang651286f2018-06-07 09:55:33 -0400575 // 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 -0500576 String tmpX = this->getTempVariable(arguments[0]->type());
John Stiles61b2e812020-12-30 18:27:31 -0500577 String tmpY = this->getTempVariable(arguments[1]->type());
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500578 this->write("(" + tmpX + " = ");
Brian Osman00185012021-02-04 16:07:11 -0500579 this->writeExpression(*arguments[0], Precedence::kSequence);
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500580 this->write(", " + tmpY + " = ");
Brian Osman00185012021-02-04 16:07:11 -0500581 this->writeExpression(*arguments[1], Precedence::kSequence);
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500582 this->write(", " + tmpX + " - " + tmpY + " * floor(" + tmpX + " / " + tmpY + "))");
Timothy Liang651286f2018-06-07 09:55:33 -0400583 break;
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500584 }
Brian Osman46787d52020-11-24 14:18:23 -0500585 // GLSL declares scalar versions of most geometric intrinsics, but these don't exist in MSL
John Stilesd7199b22020-12-30 16:22:58 -0500586 case kDistance_IntrinsicKind: {
Brian Osman46787d52020-11-24 14:18:23 -0500587 if (arguments[0]->type().columns() == 1) {
588 this->write("abs(");
Brian Osman00185012021-02-04 16:07:11 -0500589 this->writeExpression(*arguments[0], Precedence::kAdditive);
Brian Osman46787d52020-11-24 14:18:23 -0500590 this->write(" - ");
Brian Osman00185012021-02-04 16:07:11 -0500591 this->writeExpression(*arguments[1], Precedence::kAdditive);
Brian Osman46787d52020-11-24 14:18:23 -0500592 this->write(")");
593 } else {
John Stiles791c27d2020-12-30 14:56:57 -0500594 this->writeSimpleIntrinsic(c);
Brian Osman46787d52020-11-24 14:18:23 -0500595 }
596 break;
597 }
John Stilesd7199b22020-12-30 16:22:58 -0500598 case kDot_IntrinsicKind: {
Brian Osman46787d52020-11-24 14:18:23 -0500599 if (arguments[0]->type().columns() == 1) {
600 this->write("(");
Brian Osman00185012021-02-04 16:07:11 -0500601 this->writeExpression(*arguments[0], Precedence::kMultiplicative);
Brian Osman46787d52020-11-24 14:18:23 -0500602 this->write(" * ");
Brian Osman00185012021-02-04 16:07:11 -0500603 this->writeExpression(*arguments[1], Precedence::kMultiplicative);
Brian Osman46787d52020-11-24 14:18:23 -0500604 this->write(")");
605 } else {
John Stiles791c27d2020-12-30 14:56:57 -0500606 this->writeSimpleIntrinsic(c);
Brian Osman46787d52020-11-24 14:18:23 -0500607 }
608 break;
609 }
John Stilesd7199b22020-12-30 16:22:58 -0500610 case kFaceforward_IntrinsicKind: {
John Stilesad0571f2020-12-10 18:03:10 -0500611 if (arguments[0]->type().columns() == 1) {
612 // ((((Nref) * (I) < 0) ? 1 : -1) * (N))
613 this->write("((((");
Brian Osman00185012021-02-04 16:07:11 -0500614 this->writeExpression(*arguments[2], Precedence::kSequence);
John Stilesad0571f2020-12-10 18:03:10 -0500615 this->write(") * (");
Brian Osman00185012021-02-04 16:07:11 -0500616 this->writeExpression(*arguments[1], Precedence::kSequence);
John Stilesad0571f2020-12-10 18:03:10 -0500617 this->write(") < 0) ? 1 : -1) * (");
Brian Osman00185012021-02-04 16:07:11 -0500618 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stilesad0571f2020-12-10 18:03:10 -0500619 this->write("))");
620 } else {
John Stiles791c27d2020-12-30 14:56:57 -0500621 this->writeSimpleIntrinsic(c);
John Stilesad0571f2020-12-10 18:03:10 -0500622 }
623 break;
624 }
John Stilesd7199b22020-12-30 16:22:58 -0500625 case kLength_IntrinsicKind: {
Brian Osman46787d52020-11-24 14:18:23 -0500626 this->write(arguments[0]->type().columns() == 1 ? "abs(" : "length(");
Brian Osman00185012021-02-04 16:07:11 -0500627 this->writeExpression(*arguments[0], Precedence::kSequence);
Brian Osman46787d52020-11-24 14:18:23 -0500628 this->write(")");
629 break;
630 }
John Stilesd7199b22020-12-30 16:22:58 -0500631 case kNormalize_IntrinsicKind: {
Brian Osman46787d52020-11-24 14:18:23 -0500632 this->write(arguments[0]->type().columns() == 1 ? "sign(" : "normalize(");
Brian Osman00185012021-02-04 16:07:11 -0500633 this->writeExpression(*arguments[0], Precedence::kSequence);
Brian Osman46787d52020-11-24 14:18:23 -0500634 this->write(")");
635 break;
636 }
John Stilesd7199b22020-12-30 16:22:58 -0500637 case kBitcast_IntrinsicKind: {
John Stiles0063a9f2020-12-10 18:01:45 -0500638 this->write(this->getBitcastIntrinsic(c.type()));
639 this->write("(");
Brian Osman00185012021-02-04 16:07:11 -0500640 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stiles0063a9f2020-12-10 18:01:45 -0500641 this->write(")");
642 break;
643 }
John Stilesd7199b22020-12-30 16:22:58 -0500644 case kDegrees_IntrinsicKind: {
John Stilese2d34f82020-12-10 18:02:02 -0500645 this->write("((");
Brian Osman00185012021-02-04 16:07:11 -0500646 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stilese2d34f82020-12-10 18:02:02 -0500647 this->write(") * 57.2957795)");
648 break;
649 }
John Stilesd7199b22020-12-30 16:22:58 -0500650 case kRadians_IntrinsicKind: {
John Stilese2d34f82020-12-10 18:02:02 -0500651 this->write("((");
Brian Osman00185012021-02-04 16:07:11 -0500652 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stilese2d34f82020-12-10 18:02:02 -0500653 this->write(") * 0.0174532925)");
654 break;
655 }
John Stilesd7199b22020-12-30 16:22:58 -0500656 case kDFdx_IntrinsicKind: {
657 this->write("dfdx");
658 this->writeArgumentList(c.arguments());
659 break;
660 }
661 case kDFdy_IntrinsicKind: {
662 // Flipping Y also negates the Y derivatives.
John Stiles270cec22021-02-17 12:59:36 -0500663 if (fProgram.fConfig->fSettings.fFlipY) {
John Stilesd7199b22020-12-30 16:22:58 -0500664 this->write("-");
665 }
666 this->write("dfdy");
667 this->writeArgumentList(c.arguments());
668 break;
669 }
670 case kInverse_IntrinsicKind: {
671 this->write(this->getInversePolyfill(arguments));
672 this->writeArgumentList(c.arguments());
673 break;
674 }
675 case kInversesqrt_IntrinsicKind: {
676 this->write("rsqrt");
677 this->writeArgumentList(c.arguments());
678 break;
679 }
680 case kAtan_IntrinsicKind: {
681 this->write(c.arguments().size() == 2 ? "atan2" : "atan");
682 this->writeArgumentList(c.arguments());
683 break;
684 }
685 case kReflect_IntrinsicKind: {
John Stiles791c27d2020-12-30 14:56:57 -0500686 if (arguments[0]->type().columns() == 1) {
687 // We need to synthesize `I - 2 * N * I * N`.
688 String tmpI = this->getTempVariable(arguments[0]->type());
689 String tmpN = this->getTempVariable(arguments[1]->type());
690
691 // (_skTempI = ...
692 this->write("(" + tmpI + " = ");
Brian Osman00185012021-02-04 16:07:11 -0500693 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stiles791c27d2020-12-30 14:56:57 -0500694
695 // , _skTempN = ...
696 this->write(", " + tmpN + " = ");
Brian Osman00185012021-02-04 16:07:11 -0500697 this->writeExpression(*arguments[1], Precedence::kSequence);
John Stiles791c27d2020-12-30 14:56:57 -0500698
699 // , _skTempI - 2 * _skTempN * _skTempI * _skTempN)
700 this->write(", " + tmpI + " - 2 * " + tmpN + " * " + tmpI + " * " + tmpN + ")");
701 } else {
702 this->writeSimpleIntrinsic(c);
703 }
704 break;
705 }
John Stilesd7199b22020-12-30 16:22:58 -0500706 case kRefract_IntrinsicKind: {
John Stiles4b783d62020-12-30 14:58:07 -0500707 if (arguments[0]->type().columns() == 1) {
708 // Metal does implement refract for vectors; rather than reimplementing refract from
709 // scratch, we can replace the call with `refract(float2(I,0), float2(N,0), eta).x`.
710 this->write("(refract(float2(");
Brian Osman00185012021-02-04 16:07:11 -0500711 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stiles4b783d62020-12-30 14:58:07 -0500712 this->write(", 0), float2(");
Brian Osman00185012021-02-04 16:07:11 -0500713 this->writeExpression(*arguments[1], Precedence::kSequence);
John Stiles4b783d62020-12-30 14:58:07 -0500714 this->write(", 0), ");
Brian Osman00185012021-02-04 16:07:11 -0500715 this->writeExpression(*arguments[2], Precedence::kSequence);
John Stiles4b783d62020-12-30 14:58:07 -0500716 this->write(").x)");
717 } else {
718 this->writeSimpleIntrinsic(c);
719 }
720 break;
721 }
John Stiles23456532020-12-30 18:12:48 -0500722 case kRoundEven_IntrinsicKind: {
723 this->write("rint");
724 this->writeArgumentList(c.arguments());
725 break;
726 }
John Stilesd7199b22020-12-30 16:22:58 -0500727 case kBitCount_IntrinsicKind: {
John Stilese7dc7cb2020-12-22 15:37:14 -0500728 this->write("popcount(");
Brian Osman00185012021-02-04 16:07:11 -0500729 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stilese7dc7cb2020-12-22 15:37:14 -0500730 this->write(")");
731 break;
732 }
John Stilesd7199b22020-12-30 16:22:58 -0500733 case kFindLSB_IntrinsicKind: {
John Stiles86424eb2020-12-11 11:17:14 -0500734 // Create a temp variable to store the expression, to avoid double-evaluating it.
735 String skTemp = this->getTempVariable(arguments[0]->type());
736 String exprType = this->typeName(arguments[0]->type());
737
738 // ctz returns numbits(type) on zero inputs; GLSL documents it as generating -1 instead.
739 // Use select to detect zero inputs and force a -1 result.
740
741 // (_skTemp1 = (.....), select(ctz(_skTemp1), int4(-1), _skTemp1 == int4(0)))
742 this->write("(");
743 this->write(skTemp);
744 this->write(" = (");
Brian Osman00185012021-02-04 16:07:11 -0500745 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stiles86424eb2020-12-11 11:17:14 -0500746 this->write("), select(ctz(");
747 this->write(skTemp);
748 this->write("), ");
749 this->write(exprType);
750 this->write("(-1), ");
751 this->write(skTemp);
752 this->write(" == ");
753 this->write(exprType);
754 this->write("(0)))");
755 break;
756 }
John Stilesd7199b22020-12-30 16:22:58 -0500757 case kFindMSB_IntrinsicKind: {
John Stiles9685e522020-12-14 11:52:14 -0500758 // Create a temp variable to store the expression, to avoid double-evaluating it.
759 String skTemp1 = this->getTempVariable(arguments[0]->type());
760 String exprType = this->typeName(arguments[0]->type());
761
762 // GLSL findMSB is actually quite different from Metal's clz:
763 // - For signed negative numbers, it returns the first zero bit, not the first one bit!
764 // - For an empty input (0/~0 depending on sign), findMSB gives -1; clz is numbits(type)
765
766 // (_skTemp1 = (.....),
767 this->write("(");
768 this->write(skTemp1);
769 this->write(" = (");
Brian Osman00185012021-02-04 16:07:11 -0500770 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stiles9685e522020-12-14 11:52:14 -0500771 this->write("), ");
772
773 // Signed input types might be negative; we need another helper variable to negate the
774 // input (since we can only find one bits, not zero bits).
775 String skTemp2;
776 if (arguments[0]->type().isSigned()) {
777 // ... _skTemp2 = (select(_skTemp1, ~_skTemp1, _skTemp1 < 0)),
778 skTemp2 = this->getTempVariable(arguments[0]->type());
779 this->write(skTemp2);
780 this->write(" = (select(");
781 this->write(skTemp1);
782 this->write(", ~");
783 this->write(skTemp1);
784 this->write(", ");
785 this->write(skTemp1);
786 this->write(" < 0)), ");
787 } else {
788 skTemp2 = skTemp1;
789 }
790
791 // ... select(int4(clz(_skTemp2)), int4(-1), _skTemp2 == int4(0)))
792 this->write("select(");
793 this->write(this->typeName(c.type()));
794 this->write("(clz(");
795 this->write(skTemp2);
796 this->write(")), ");
797 this->write(this->typeName(c.type()));
798 this->write("(-1), ");
799 this->write(skTemp2);
800 this->write(" == ");
801 this->write(exprType);
802 this->write("(0)))");
803 break;
804 }
John Stilesd7199b22020-12-30 16:22:58 -0500805 case kMatrixCompMult_IntrinsicKind: {
806 this->writeMatrixCompMult();
807 this->writeSimpleIntrinsic(c);
808 break;
809 }
810 case kCompareEqual_IntrinsicKind:
811 case kCompareGreaterThan_IntrinsicKind:
812 case kCompareGreaterThanEqual_IntrinsicKind:
813 case kCompareLessThan_IntrinsicKind:
814 case kCompareLessThanEqual_IntrinsicKind:
815 case kCompareNotEqual_IntrinsicKind: {
816 this->write("(");
Brian Osman00185012021-02-04 16:07:11 -0500817 this->writeExpression(*c.arguments()[0], Precedence::kRelational);
John Stilesd7199b22020-12-30 16:22:58 -0500818 switch (kind) {
819 case kCompareEqual_IntrinsicKind:
820 this->write(" == ");
821 break;
822 case kCompareNotEqual_IntrinsicKind:
823 this->write(" != ");
824 break;
825 case kCompareLessThan_IntrinsicKind:
826 this->write(" < ");
827 break;
828 case kCompareLessThanEqual_IntrinsicKind:
829 this->write(" <= ");
830 break;
831 case kCompareGreaterThan_IntrinsicKind:
832 this->write(" > ");
833 break;
834 case kCompareGreaterThanEqual_IntrinsicKind:
835 this->write(" >= ");
836 break;
837 default:
John Stilesf57207b2021-02-02 17:50:34 -0500838 SK_ABORT("unsupported comparison intrinsic kind");
John Stilesd7199b22020-12-30 16:22:58 -0500839 }
Brian Osman00185012021-02-04 16:07:11 -0500840 this->writeExpression(*c.arguments()[1], Precedence::kRelational);
John Stilesd7199b22020-12-30 16:22:58 -0500841 this->write(")");
842 break;
843 }
Timothy Liang6403b0e2018-05-17 10:40:04 -0400844 default:
John Stilesf57207b2021-02-02 17:50:34 -0500845 SK_ABORT("unsupported intrinsic kind");
Timothy Liang6403b0e2018-05-17 10:40:04 -0400846 }
847}
848
John Stilesfcf8cb22020-08-06 14:29:22 -0400849// Assembles a matrix of type floatRxC by resizing another matrix named `x0`.
850// Cells that don't exist in the source matrix will be populated with identity-matrix values.
851void MetalCodeGenerator::assembleMatrixFromMatrix(const Type& sourceMatrix, int rows, int columns) {
852 SkASSERT(rows <= 4);
853 SkASSERT(columns <= 4);
854
855 const char* columnSeparator = "";
856 for (int c = 0; c < columns; ++c) {
857 fExtraFunctions.printf("%sfloat%d(", columnSeparator, rows);
858 columnSeparator = "), ";
859
860 // Determine how many values to take from the source matrix for this row.
861 int swizzleLength = 0;
862 if (c < sourceMatrix.columns()) {
863 swizzleLength = std::min<>(rows, sourceMatrix.rows());
864 }
865
866 // Emit all the values from the source matrix row.
867 bool firstItem;
868 switch (swizzleLength) {
869 case 0: firstItem = true; break;
870 case 1: firstItem = false; fExtraFunctions.printf("x0[%d].x", c); break;
871 case 2: firstItem = false; fExtraFunctions.printf("x0[%d].xy", c); break;
872 case 3: firstItem = false; fExtraFunctions.printf("x0[%d].xyz", c); break;
873 case 4: firstItem = false; fExtraFunctions.printf("x0[%d].xyzw", c); break;
874 default: SkUNREACHABLE;
875 }
876
877 // Emit the placeholder identity-matrix cells.
878 for (int r = swizzleLength; r < rows; ++r) {
879 fExtraFunctions.printf("%s%s", firstItem ? "" : ", ", (r == c) ? "1.0" : "0.0");
880 firstItem = false;
881 }
882 }
883
884 fExtraFunctions.writeText(")");
885}
886
887// Assembles a matrix of type floatRxC by concatenating an arbitrary mix of values, named `x0`,
888// `x1`, etc. An error is written if the expression list don't contain exactly R*C scalars.
John Stiles8e3b6be2020-10-13 11:14:08 -0400889void MetalCodeGenerator::assembleMatrixFromExpressions(const ExpressionArray& args,
890 int rows, int columns) {
John Stilesfcf8cb22020-08-06 14:29:22 -0400891 size_t argIndex = 0;
892 int argPosition = 0;
893
894 const char* columnSeparator = "";
895 for (int c = 0; c < columns; ++c) {
896 fExtraFunctions.printf("%sfloat%d(", columnSeparator, rows);
897 columnSeparator = "), ";
898
899 const char* rowSeparator = "";
900 for (int r = 0; r < rows; ++r) {
901 fExtraFunctions.writeText(rowSeparator);
902 rowSeparator = ", ";
903
904 if (argIndex < args.size()) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400905 const Type& argType = args[argIndex]->type();
Ethan Nicholase6592142020-09-08 10:22:09 -0400906 switch (argType.typeKind()) {
907 case Type::TypeKind::kScalar: {
John Stilesfcf8cb22020-08-06 14:29:22 -0400908 fExtraFunctions.printf("x%zu", argIndex);
909 break;
910 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400911 case Type::TypeKind::kVector: {
John Stilesfcf8cb22020-08-06 14:29:22 -0400912 fExtraFunctions.printf("x%zu[%d]", argIndex, argPosition);
913 break;
914 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400915 case Type::TypeKind::kMatrix: {
John Stilesfcf8cb22020-08-06 14:29:22 -0400916 fExtraFunctions.printf("x%zu[%d][%d]", argIndex,
917 argPosition / argType.rows(),
918 argPosition % argType.rows());
919 break;
920 }
921 default: {
922 SkDEBUGFAIL("incorrect type of argument for matrix constructor");
923 fExtraFunctions.writeText("<error>");
924 break;
925 }
926 }
927
928 ++argPosition;
929 if (argPosition >= argType.columns() * argType.rows()) {
930 ++argIndex;
931 argPosition = 0;
932 }
933 } else {
934 SkDEBUGFAIL("not enough arguments for matrix constructor");
935 fExtraFunctions.writeText("<error>");
936 }
937 }
938 }
939
940 if (argPosition != 0 || argIndex != args.size()) {
941 SkDEBUGFAIL("incorrect number of arguments for matrix constructor");
942 fExtraFunctions.writeText(", <error>");
943 }
944
945 fExtraFunctions.writeText(")");
946}
947
John Stiles1bdafbf2020-05-28 12:17:20 -0400948// Generates a constructor for 'matrix' which reorganizes the input arguments into the proper shape.
949// Keeps track of previously generated constructors so that we won't generate more than one
950// constructor for any given permutation of input argument types. Returns the name of the
951// generated constructor method.
952String MetalCodeGenerator::getMatrixConstructHelper(const Constructor& c) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400953 const Type& matrix = c.type();
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500954 int columns = matrix.columns();
955 int rows = matrix.rows();
John Stiles8e3b6be2020-10-13 11:14:08 -0400956 const ExpressionArray& args = c.arguments();
John Stiles1bdafbf2020-05-28 12:17:20 -0400957
958 // Create the helper-method name and use it as our lookup key.
959 String name;
960 name.appendf("float%dx%d_from", columns, rows);
961 for (const std::unique_ptr<Expression>& expr : args) {
John Stiles36129132020-12-29 12:28:04 -0500962 name.appendf("_%s", this->typeName(expr->type()).c_str());
John Stiles1bdafbf2020-05-28 12:17:20 -0400963 }
964
965 // If a helper-method has already been synthesized, we don't need to synthesize it again.
966 auto [iter, newlyCreated] = fHelpers.insert(name);
967 if (!newlyCreated) {
968 return name;
969 }
970
971 // Unlike GLSL, Metal requires that matrices are initialized with exactly R vectors of C
972 // components apiece. (In Metal 2.0, you can also supply R*C scalars, but you still cannot
973 // supply a mixture of scalars and vectors.)
974 fExtraFunctions.printf("float%dx%d %s(", columns, rows, name.c_str());
975
976 size_t argIndex = 0;
977 const char* argSeparator = "";
John Stilesfcf8cb22020-08-06 14:29:22 -0400978 for (const std::unique_ptr<Expression>& expr : args) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400979 fExtraFunctions.printf("%s%s x%zu", argSeparator,
John Stiles36129132020-12-29 12:28:04 -0500980 this->typeName(expr->type()).c_str(), argIndex++);
John Stiles1bdafbf2020-05-28 12:17:20 -0400981 argSeparator = ", ";
982 }
983
984 fExtraFunctions.printf(") {\n return float%dx%d(", columns, rows);
985
John Stiles9aeed132020-11-24 17:36:06 -0500986 if (args.size() == 1 && args.front()->type().isMatrix()) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400987 this->assembleMatrixFromMatrix(args.front()->type(), rows, columns);
John Stilesfcf8cb22020-08-06 14:29:22 -0400988 } else {
989 this->assembleMatrixFromExpressions(args, rows, columns);
John Stiles1bdafbf2020-05-28 12:17:20 -0400990 }
991
John Stilesfcf8cb22020-08-06 14:29:22 -0400992 fExtraFunctions.writeText(");\n}\n");
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500993 return name;
994}
995
996bool MetalCodeGenerator::canCoerce(const Type& t1, const Type& t2) {
997 if (t1.columns() != t2.columns() || t1.rows() != t2.rows()) {
998 return false;
999 }
1000 if (t1.columns() > 1) {
1001 return this->canCoerce(t1.componentType(), t2.componentType());
1002 }
Ethan Nicholase1f55022019-02-05 17:17:40 -05001003 return t1.isFloat() && t2.isFloat();
Ethan Nicholas842d31b2019-01-22 10:59:11 -05001004}
1005
John Stiles1bdafbf2020-05-28 12:17:20 -04001006bool MetalCodeGenerator::matrixConstructHelperIsNeeded(const Constructor& c) {
1007 // A matrix construct helper is only necessary if we are, in fact, constructing a matrix.
John Stiles9aeed132020-11-24 17:36:06 -05001008 if (!c.type().isMatrix()) {
John Stiles1bdafbf2020-05-28 12:17:20 -04001009 return false;
Ethan Nicholas842d31b2019-01-22 10:59:11 -05001010 }
John Stiles1bdafbf2020-05-28 12:17:20 -04001011
1012 // GLSL is fairly free-form about inputs to its matrix constructors, but Metal is not; it
1013 // expects exactly R vectors of C components apiece. (Metal 2.0 also allows a list of R*C
1014 // scalars.) Some cases are simple to translate and so we handle those inline--e.g. a list of
1015 // scalars can be constructed trivially. In more complex cases, we generate a helper function
1016 // that converts our inputs into a properly-shaped matrix.
1017 // A matrix construct helper method is always used if any input argument is a matrix.
1018 // Helper methods are also necessary when any argument would span multiple rows. For instance:
1019 //
1020 // float2 x = (1, 2);
1021 // float3x2(x, 3, 4, 5, 6) = | 1 3 5 | = no helper needed; conversion can be done inline
1022 // | 2 4 6 |
1023 //
1024 // float2 x = (2, 3);
1025 // float3x2(1, x, 4, 5, 6) = | 1 3 5 | = x spans multiple rows; a helper method will be used
1026 // | 2 4 6 |
1027 //
1028 // float4 x = (1, 2, 3, 4);
1029 // float2x2(x) = | 1 3 | = x spans multiple rows; a helper method will be used
1030 // | 2 4 |
1031 //
1032
1033 int position = 0;
Ethan Nicholasf70f0442020-09-29 12:41:35 -04001034 for (const std::unique_ptr<Expression>& expr : c.arguments()) {
John Stiles1bdafbf2020-05-28 12:17:20 -04001035 // If an input argument is a matrix, we need a helper function.
John Stiles9aeed132020-11-24 17:36:06 -05001036 if (expr->type().isMatrix()) {
John Stiles1bdafbf2020-05-28 12:17:20 -04001037 return true;
1038 }
Ethan Nicholas30d30222020-09-11 12:27:26 -04001039 position += expr->type().columns();
1040 if (position > c.type().rows()) {
John Stiles1bdafbf2020-05-28 12:17:20 -04001041 // An input argument would span multiple rows; a helper function is required.
1042 return true;
1043 }
Ethan Nicholas30d30222020-09-11 12:27:26 -04001044 if (position == c.type().rows()) {
John Stiles1bdafbf2020-05-28 12:17:20 -04001045 // We've advanced to the end of a row. Wrap to the start of the next row.
1046 position = 0;
1047 }
1048 }
1049
1050 return false;
1051}
1052
1053void MetalCodeGenerator::writeConstructor(const Constructor& c, Precedence parentPrecedence) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001054 const Type& constructorType = c.type();
John Stiles7384b372021-04-01 13:48:15 -04001055 SkASSERT(!constructorType.isArray());
1056
John Stiles1bdafbf2020-05-28 12:17:20 -04001057 // Emit and invoke a matrix-constructor helper method if one is necessary.
1058 if (this->matrixConstructHelperIsNeeded(c)) {
1059 this->write(this->getMatrixConstructHelper(c));
John Stiles1fa15b12020-05-28 17:36:54 +00001060 this->write("(");
1061 const char* separator = "";
Ethan Nicholasf70f0442020-09-29 12:41:35 -04001062 for (const std::unique_ptr<Expression>& expr : c.arguments()) {
John Stiles1fa15b12020-05-28 17:36:54 +00001063 this->write(separator);
1064 separator = ", ";
Brian Osman00185012021-02-04 16:07:11 -05001065 this->writeExpression(*expr, Precedence::kSequence);
John Stilesdaa573e2020-05-28 12:17:20 -04001066 }
John Stiles1fa15b12020-05-28 17:36:54 +00001067 this->write(")");
John Stiles1bdafbf2020-05-28 12:17:20 -04001068 return;
John Stilesdaa573e2020-05-28 12:17:20 -04001069 }
John Stiles1bdafbf2020-05-28 12:17:20 -04001070
1071 // Explicitly invoke the constructor, passing in the necessary arguments.
John Stilesb4418502021-02-04 10:57:08 -05001072 this->writeType(constructorType);
John Stiles7384b372021-04-01 13:48:15 -04001073 this->write("(");
John Stiles1bdafbf2020-05-28 12:17:20 -04001074 const char* separator = "";
1075 int scalarCount = 0;
Ethan Nicholasf70f0442020-09-29 12:41:35 -04001076 for (const std::unique_ptr<Expression>& arg : c.arguments()) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001077 const Type& argType = arg->type();
John Stiles1bdafbf2020-05-28 12:17:20 -04001078 this->write(separator);
1079 separator = ", ";
John Stiles9aeed132020-11-24 17:36:06 -05001080 if (constructorType.isMatrix() &&
Ethan Nicholas30d30222020-09-11 12:27:26 -04001081 argType.columns() < constructorType.rows()) {
John Stiles1bdafbf2020-05-28 12:17:20 -04001082 // Merge scalars and smaller vectors together.
1083 if (!scalarCount) {
John Stilesb4418502021-02-04 10:57:08 -05001084 this->writeType(constructorType.componentType());
Ethan Nicholas30d30222020-09-11 12:27:26 -04001085 this->write(to_string(constructorType.rows()));
John Stiles1bdafbf2020-05-28 12:17:20 -04001086 this->write("(");
1087 }
Ethan Nicholas30d30222020-09-11 12:27:26 -04001088 scalarCount += argType.columns();
John Stiles1bdafbf2020-05-28 12:17:20 -04001089 }
Brian Osman00185012021-02-04 16:07:11 -05001090 this->writeExpression(*arg, Precedence::kSequence);
Ethan Nicholas30d30222020-09-11 12:27:26 -04001091 if (scalarCount && scalarCount == constructorType.rows()) {
John Stiles1bdafbf2020-05-28 12:17:20 -04001092 this->write(")");
1093 scalarCount = 0;
1094 }
1095 }
John Stiles7384b372021-04-01 13:48:15 -04001096 this->write(")");
Ethan Nicholascc305772017-10-13 16:17:45 -04001097}
1098
John Stilesb14a8192021-04-05 11:40:46 -04001099void MetalCodeGenerator::writeAnyConstructor(const AnyConstructor& c,
1100 const char* leftBracket,
1101 const char* rightBracket,
1102 Precedence parentPrecedence) {
John Stilese1182782021-03-30 22:09:37 -04001103 this->writeType(c.type());
John Stilesb14a8192021-04-05 11:40:46 -04001104 this->write(leftBracket);
John Stiles7384b372021-04-01 13:48:15 -04001105 const char* separator = "";
John Stilesb14a8192021-04-05 11:40:46 -04001106 for (const std::unique_ptr<Expression>& arg : c.argumentSpan()) {
John Stiles7384b372021-04-01 13:48:15 -04001107 this->write(separator);
1108 separator = ", ";
1109 this->writeExpression(*arg, Precedence::kSequence);
1110 }
John Stilesb14a8192021-04-05 11:40:46 -04001111 this->write(rightBracket);
John Stiles7384b372021-04-01 13:48:15 -04001112}
1113
John Stilesb14a8192021-04-05 11:40:46 -04001114void MetalCodeGenerator::writeCastConstructor(const AnyConstructor& c,
1115 const char* leftBracket,
1116 const char* rightBracket,
1117 Precedence parentPrecedence) {
1118 // If the type is coercible, emit it directly without the cast.
1119 auto args = c.argumentSpan();
1120 if (args.size() == 1) {
1121 if (this->canCoerce(c.type(), args.front()->type())) {
1122 this->writeExpression(*args.front(), parentPrecedence);
1123 return;
1124 }
John Stilesfd7252f2021-04-04 22:24:40 -04001125 }
1126
John Stilesb14a8192021-04-05 11:40:46 -04001127 return this->writeAnyConstructor(c, leftBracket, rightBracket, parentPrecedence);
John Stilesfd7252f2021-04-04 22:24:40 -04001128}
1129
Ethan Nicholascc305772017-10-13 16:17:45 -04001130void MetalCodeGenerator::writeFragCoord() {
Ethan Nicholasf931e402019-07-26 15:40:33 -04001131 if (fRTHeightName.length()) {
1132 this->write("float4(_fragCoord.x, ");
1133 this->write(fRTHeightName.c_str());
1134 this->write(" - _fragCoord.y, 0.0, _fragCoord.w)");
Jim Van Verth6bc650e2019-02-07 14:53:23 -05001135 } else {
1136 this->write("float4(_fragCoord.x, _fragCoord.y, 0.0, _fragCoord.w)");
1137 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001138}
1139
1140void MetalCodeGenerator::writeVariableReference(const VariableReference& ref) {
John Stiles06b84ef2020-12-09 12:35:48 -05001141 // When assembling out-param helper functions, we copy variables into local clones with matching
John Stilesf7410bd2021-01-19 13:07:55 -05001142 // names. We never want to prepend "_in." or "_globals." when writing these variables since
John Stiles06b84ef2020-12-09 12:35:48 -05001143 // we're actually targeting the clones.
1144 if (fIgnoreVariableReferenceModifiers) {
1145 this->writeName(ref.variable()->name());
1146 return;
1147 }
1148
Ethan Nicholas78686922020-10-08 06:46:27 -04001149 switch (ref.variable()->modifiers().fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001150 case SK_FRAGCOLOR_BUILTIN:
John Stilesf7410bd2021-01-19 13:07:55 -05001151 this->write("_out.sk_FragColor");
Ethan Nicholascc305772017-10-13 16:17:45 -04001152 break;
Timothy Liang6403b0e2018-05-17 10:40:04 -04001153 case SK_FRAGCOORD_BUILTIN:
1154 this->writeFragCoord();
1155 break;
Timothy Liangdc89f192018-06-13 09:20:31 -04001156 case SK_VERTEXID_BUILTIN:
1157 this->write("sk_VertexID");
1158 break;
1159 case SK_INSTANCEID_BUILTIN:
1160 this->write("sk_InstanceID");
1161 break;
Timothy Liang7b8875d2018-08-10 09:42:31 -04001162 case SK_CLOCKWISE_BUILTIN:
1163 // We'd set the front facing winding in the MTLRenderCommandEncoder to be counter
Brian Salomonf4ba4ec2020-03-19 15:54:28 -04001164 // clockwise to match Skia convention.
John Stiles270cec22021-02-17 12:59:36 -05001165 this->write(fProgram.fConfig->fSettings.fFlipY ? "_frontFacing" : "(!_frontFacing)");
Timothy Liang7b8875d2018-08-10 09:42:31 -04001166 break;
Ethan Nicholascc305772017-10-13 16:17:45 -04001167 default:
Ethan Nicholas78686922020-10-08 06:46:27 -04001168 const Variable& var = *ref.variable();
Ethan Nicholas453f67f2020-10-09 10:43:45 -04001169 if (var.storage() == Variable::Storage::kGlobal) {
Ethan Nicholas78686922020-10-08 06:46:27 -04001170 if (var.modifiers().fFlags & Modifiers::kIn_Flag) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001171 this->write("_in.");
Ethan Nicholas78686922020-10-08 06:46:27 -04001172 } else if (var.modifiers().fFlags & Modifiers::kOut_Flag) {
John Stilesf7410bd2021-01-19 13:07:55 -05001173 this->write("_out.");
Ethan Nicholas78686922020-10-08 06:46:27 -04001174 } else if (var.modifiers().fFlags & Modifiers::kUniform_Flag &&
1175 var.type().typeKind() != Type::TypeKind::kSampler) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001176 this->write("_uniforms.");
1177 } else {
John Stilesf7410bd2021-01-19 13:07:55 -05001178 this->write("_globals.");
Ethan Nicholascc305772017-10-13 16:17:45 -04001179 }
1180 }
Ethan Nicholas78686922020-10-08 06:46:27 -04001181 this->writeName(var.name());
Ethan Nicholascc305772017-10-13 16:17:45 -04001182 }
1183}
1184
1185void MetalCodeGenerator::writeIndexExpression(const IndexExpression& expr) {
Brian Osman00185012021-02-04 16:07:11 -05001186 this->writeExpression(*expr.base(), Precedence::kPostfix);
Ethan Nicholascc305772017-10-13 16:17:45 -04001187 this->write("[");
Brian Osman00185012021-02-04 16:07:11 -05001188 this->writeExpression(*expr.index(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001189 this->write("]");
1190}
1191
1192void MetalCodeGenerator::writeFieldAccess(const FieldAccess& f) {
Ethan Nicholas7a95b202020-10-09 11:55:40 -04001193 const Type::Field* field = &f.base()->type().fields()[f.fieldIndex()];
1194 if (FieldAccess::OwnerKind::kDefault == f.ownerKind()) {
Brian Osman00185012021-02-04 16:07:11 -05001195 this->writeExpression(*f.base(), Precedence::kPostfix);
Ethan Nicholascc305772017-10-13 16:17:45 -04001196 this->write(".");
1197 }
Timothy Liang7d637782018-06-05 09:58:07 -04001198 switch (field->fModifiers.fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001199 case SK_POSITION_BUILTIN:
John Stilesf7410bd2021-01-19 13:07:55 -05001200 this->write("_out.sk_Position");
Ethan Nicholascc305772017-10-13 16:17:45 -04001201 break;
1202 default:
Timothy Liang7d637782018-06-05 09:58:07 -04001203 if (field->fName == "sk_PointSize") {
John Stilesf7410bd2021-01-19 13:07:55 -05001204 this->write("_out.sk_PointSize");
Timothy Liang7d637782018-06-05 09:58:07 -04001205 } else {
Ethan Nicholas7a95b202020-10-09 11:55:40 -04001206 if (FieldAccess::OwnerKind::kAnonymousInterfaceBlock == f.ownerKind()) {
John Stilesf7410bd2021-01-19 13:07:55 -05001207 this->write("_globals.");
Timothy Liang7d637782018-06-05 09:58:07 -04001208 this->write(fInterfaceBlockNameMap[fInterfaceBlockMap[field]]);
1209 this->write("->");
1210 }
Timothy Liang651286f2018-06-07 09:55:33 -04001211 this->writeName(field->fName);
Timothy Lianga06f2152018-05-24 15:33:31 -04001212 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001213 }
1214}
1215
1216void MetalCodeGenerator::writeSwizzle(const Swizzle& swizzle) {
Brian Osman00185012021-02-04 16:07:11 -05001217 this->writeExpression(*swizzle.base(), Precedence::kPostfix);
Ethan Nicholascc305772017-10-13 16:17:45 -04001218 this->write(".");
Ethan Nicholas6b4d5812020-10-12 16:11:51 -04001219 for (int c : swizzle.components()) {
Brian Osman25647672020-09-15 15:16:56 -04001220 SkASSERT(c >= 0 && c <= 3);
1221 this->write(&("x\0y\0z\0w\0"[c * 2]));
Ethan Nicholascc305772017-10-13 16:17:45 -04001222 }
1223}
1224
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001225void MetalCodeGenerator::writeMatrixTimesEqualHelper(const Type& left, const Type& right,
1226 const Type& result) {
John Stiles01cdf012021-02-10 09:53:41 -05001227 String key = "TimesEqual" + this->typeName(left) + ":" + this->typeName(right);
John Stiles56233d12021-02-03 13:03:29 -05001228
1229 auto [iter, wasInserted] = fHelpers.insert(key);
1230 if (wasInserted) {
John Stiles368db7c2020-12-29 11:20:08 -05001231 fExtraFunctions.printf("thread %s& operator*=(thread %s& left, thread const %s& right) {\n"
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001232 " left = left * right;\n"
1233 " return left;\n"
John Stiles368db7c2020-12-29 11:20:08 -05001234 "}\n",
1235 this->typeName(result).c_str(), this->typeName(left).c_str(),
1236 this->typeName(right).c_str());
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001237 }
1238}
1239
John Stiles01cdf012021-02-10 09:53:41 -05001240void MetalCodeGenerator::writeMatrixEqualityHelper(const Type& left, const Type& right) {
1241 SkASSERTF(left.rows() == right.rows() && left.columns() == right.columns(), "left=%s, right=%s",
1242 left.description().c_str(), right.description().c_str());
1243
1244 String key = "Equality" + this->typeName(left) + ":" + this->typeName(right);
1245
1246 auto [iter, wasInserted] = fHelpers.insert(key);
1247 if (wasInserted) {
1248 fExtraFunctions.printf(
1249 "thread bool operator==(const %s left, const %s right) {\n"
1250 " return",
1251 this->typeName(left).c_str(), this->typeName(right).c_str());
1252
1253 for (int index=0; index<left.columns(); ++index) {
1254 fExtraFunctions.printf("%s all(left[%d] == right[%d])",
1255 index == 0 ? "" : " &&", index, index);
1256 }
1257 fExtraFunctions.printf(";\n"
1258 "}\n");
1259 }
1260}
1261
1262void MetalCodeGenerator::writeMatrixInequalityHelper(const Type& left, const Type& right) {
1263 SkASSERTF(left.rows() == right.rows() && left.columns() == right.columns(), "left=%s, right=%s",
1264 left.description().c_str(), right.description().c_str());
1265
1266 String key = "Inequality" + this->typeName(left) + ":" + this->typeName(right);
1267
1268 auto [iter, wasInserted] = fHelpers.insert(key);
1269 if (wasInserted) {
1270 fExtraFunctions.printf(
1271 "thread bool operator!=(const %s left, const %s right) {\n"
1272 " return",
1273 this->typeName(left).c_str(), this->typeName(right).c_str());
1274
1275 for (int index=0; index<left.columns(); ++index) {
1276 fExtraFunctions.printf("%s any(left[%d] != right[%d])",
1277 index == 0 ? "" : " ||", index, index);
1278 }
1279 fExtraFunctions.printf(";\n"
1280 "}\n");
1281 }
1282}
1283
Ethan Nicholascc305772017-10-13 16:17:45 -04001284void MetalCodeGenerator::writeBinaryExpression(const BinaryExpression& b,
1285 Precedence parentPrecedence) {
John Stiles2d4f9592020-10-30 10:29:12 -04001286 const Expression& left = *b.left();
1287 const Expression& right = *b.right();
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001288 const Type& leftType = left.type();
1289 const Type& rightType = right.type();
John Stiles45990502021-02-16 10:55:27 -05001290 Operator op = b.getOperator();
1291 Precedence precedence = op.getBinaryPrecedence();
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001292 bool needParens = precedence >= parentPrecedence;
John Stiles45990502021-02-16 10:55:27 -05001293 switch (op.kind()) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001294 case Token::Kind::TK_EQEQ:
John Stiles9aeed132020-11-24 17:36:06 -05001295 if (leftType.isVector()) {
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001296 this->write("all");
1297 needParens = true;
1298 }
1299 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001300 case Token::Kind::TK_NEQ:
John Stiles9aeed132020-11-24 17:36:06 -05001301 if (leftType.isVector()) {
Jim Van Verth36477b42019-04-11 14:57:30 -04001302 this->write("any");
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001303 needParens = true;
1304 }
1305 break;
1306 default:
1307 break;
1308 }
1309 if (needParens) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001310 this->write("(");
1311 }
John Stiles01cdf012021-02-10 09:53:41 -05001312 if (leftType.isMatrix() && rightType.isMatrix()) {
John Stiles45990502021-02-16 10:55:27 -05001313 if (op.kind() == Token::Kind::TK_STAREQ) {
John Stiles01cdf012021-02-10 09:53:41 -05001314 this->writeMatrixTimesEqualHelper(leftType, rightType, b.type());
John Stiles45990502021-02-16 10:55:27 -05001315 } else if (op.kind() == Token::Kind::TK_EQEQ) {
John Stiles01cdf012021-02-10 09:53:41 -05001316 this->writeMatrixEqualityHelper(leftType, rightType);
John Stiles45990502021-02-16 10:55:27 -05001317 } else if (op.kind() == Token::Kind::TK_NEQ) {
John Stiles01cdf012021-02-10 09:53:41 -05001318 this->writeMatrixInequalityHelper(leftType, rightType);
1319 }
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001320 }
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001321 this->writeExpression(left, precedence);
John Stiles45990502021-02-16 10:55:27 -05001322 if (op.kind() != Token::Kind::TK_EQ && op.isAssignment() &&
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001323 left.kind() == Expression::Kind::kSwizzle && !left.hasSideEffects()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001324 // This doesn't compile in Metal:
1325 // float4 x = float4(1);
1326 // x.xy *= float2x2(...);
1327 // with the error message "non-const reference cannot bind to vector element",
1328 // but switching it to x.xy = x.xy * float2x2(...) fixes it. We perform this tranformation
1329 // as long as the LHS has no side effects, and hope for the best otherwise.
1330 this->write(" = ");
Brian Osman00185012021-02-04 16:07:11 -05001331 this->writeExpression(left, Precedence::kAssignment);
Ethan Nicholascc305772017-10-13 16:17:45 -04001332 this->write(" ");
John Stilesd6449e92020-11-30 09:13:23 -05001333 String opName = OperatorName(op);
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001334 SkASSERT(opName.endsWith("="));
1335 this->write(opName.substr(0, opName.size() - 1).c_str());
Ethan Nicholascc305772017-10-13 16:17:45 -04001336 this->write(" ");
1337 } else {
John Stilesd6449e92020-11-30 09:13:23 -05001338 this->write(String(" ") + OperatorName(op) + " ");
Ethan Nicholascc305772017-10-13 16:17:45 -04001339 }
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001340 this->writeExpression(right, precedence);
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001341 if (needParens) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001342 this->write(")");
1343 }
1344}
1345
1346void MetalCodeGenerator::writeTernaryExpression(const TernaryExpression& t,
1347 Precedence parentPrecedence) {
Brian Osman00185012021-02-04 16:07:11 -05001348 if (Precedence::kTernary >= parentPrecedence) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001349 this->write("(");
1350 }
Brian Osman00185012021-02-04 16:07:11 -05001351 this->writeExpression(*t.test(), Precedence::kTernary);
Ethan Nicholascc305772017-10-13 16:17:45 -04001352 this->write(" ? ");
Brian Osman00185012021-02-04 16:07:11 -05001353 this->writeExpression(*t.ifTrue(), Precedence::kTernary);
Ethan Nicholascc305772017-10-13 16:17:45 -04001354 this->write(" : ");
Brian Osman00185012021-02-04 16:07:11 -05001355 this->writeExpression(*t.ifFalse(), Precedence::kTernary);
1356 if (Precedence::kTernary >= parentPrecedence) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001357 this->write(")");
1358 }
1359}
1360
1361void MetalCodeGenerator::writePrefixExpression(const PrefixExpression& p,
1362 Precedence parentPrecedence) {
Brian Osman00185012021-02-04 16:07:11 -05001363 if (Precedence::kPrefix >= parentPrecedence) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001364 this->write("(");
1365 }
John Stilesd6449e92020-11-30 09:13:23 -05001366 this->write(OperatorName(p.getOperator()));
Brian Osman00185012021-02-04 16:07:11 -05001367 this->writeExpression(*p.operand(), Precedence::kPrefix);
1368 if (Precedence::kPrefix >= parentPrecedence) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001369 this->write(")");
1370 }
1371}
1372
1373void MetalCodeGenerator::writePostfixExpression(const PostfixExpression& p,
1374 Precedence parentPrecedence) {
Brian Osman00185012021-02-04 16:07:11 -05001375 if (Precedence::kPostfix >= parentPrecedence) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001376 this->write("(");
1377 }
Brian Osman00185012021-02-04 16:07:11 -05001378 this->writeExpression(*p.operand(), Precedence::kPostfix);
John Stilesd6449e92020-11-30 09:13:23 -05001379 this->write(OperatorName(p.getOperator()));
Brian Osman00185012021-02-04 16:07:11 -05001380 if (Precedence::kPostfix >= parentPrecedence) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001381 this->write(")");
1382 }
1383}
1384
1385void MetalCodeGenerator::writeBoolLiteral(const BoolLiteral& b) {
Ethan Nicholas59d660c2020-09-28 09:18:15 -04001386 this->write(b.value() ? "true" : "false");
Ethan Nicholascc305772017-10-13 16:17:45 -04001387}
1388
1389void MetalCodeGenerator::writeIntLiteral(const IntLiteral& i) {
John Stiles12739df2020-12-29 09:47:20 -05001390 const Type& type = i.type();
John Stiles54e7c052021-01-11 14:22:36 -05001391 if (type == *fContext.fTypes.fUInt) {
Ethan Nicholase96cdd12020-09-28 16:27:18 -04001392 this->write(to_string(i.value() & 0xffffffff) + "u");
John Stiles54e7c052021-01-11 14:22:36 -05001393 } else if (type == *fContext.fTypes.fUShort) {
John Stiles12739df2020-12-29 09:47:20 -05001394 this->write(to_string(i.value() & 0xffff) + "u");
John Stiles54e7c052021-01-11 14:22:36 -05001395 } else if (type == *fContext.fTypes.fUByte) {
John Stiles12739df2020-12-29 09:47:20 -05001396 this->write(to_string(i.value() & 0xff) + "u");
Ethan Nicholascc305772017-10-13 16:17:45 -04001397 } else {
John Stiles12739df2020-12-29 09:47:20 -05001398 this->write(to_string(i.value()));
Ethan Nicholascc305772017-10-13 16:17:45 -04001399 }
1400}
1401
1402void MetalCodeGenerator::writeFloatLiteral(const FloatLiteral& f) {
Ethan Nicholasa3f22f12020-10-01 12:13:17 -04001403 this->write(to_string(f.value()));
Ethan Nicholascc305772017-10-13 16:17:45 -04001404}
1405
1406void MetalCodeGenerator::writeSetting(const Setting& s) {
John Stilesf57207b2021-02-02 17:50:34 -05001407 SK_ABORT("internal error; setting was not folded to a constant during compilation\n");
Ethan Nicholascc305772017-10-13 16:17:45 -04001408}
1409
John Stiles06b84ef2020-12-09 12:35:48 -05001410void MetalCodeGenerator::writeFunctionRequirementArgs(const FunctionDeclaration& f,
1411 const char*& separator) {
1412 Requirements requirements = this->requirements(f);
1413 if (requirements & kInputs_Requirement) {
1414 this->write(separator);
1415 this->write("_in");
1416 separator = ", ";
1417 }
1418 if (requirements & kOutputs_Requirement) {
1419 this->write(separator);
1420 this->write("_out");
1421 separator = ", ";
1422 }
1423 if (requirements & kUniforms_Requirement) {
1424 this->write(separator);
1425 this->write("_uniforms");
1426 separator = ", ";
1427 }
1428 if (requirements & kGlobals_Requirement) {
1429 this->write(separator);
John Stilesf7410bd2021-01-19 13:07:55 -05001430 this->write("_globals");
John Stiles06b84ef2020-12-09 12:35:48 -05001431 separator = ", ";
1432 }
1433 if (requirements & kFragCoord_Requirement) {
1434 this->write(separator);
1435 this->write("_fragCoord");
1436 separator = ", ";
1437 }
1438}
1439
1440void MetalCodeGenerator::writeFunctionRequirementParams(const FunctionDeclaration& f,
1441 const char*& separator) {
1442 Requirements requirements = this->requirements(f);
1443 if (requirements & kInputs_Requirement) {
1444 this->write(separator);
1445 this->write("Inputs _in");
1446 separator = ", ";
1447 }
1448 if (requirements & kOutputs_Requirement) {
1449 this->write(separator);
John Stilesf7410bd2021-01-19 13:07:55 -05001450 this->write("thread Outputs& _out");
John Stiles06b84ef2020-12-09 12:35:48 -05001451 separator = ", ";
1452 }
1453 if (requirements & kUniforms_Requirement) {
1454 this->write(separator);
1455 this->write("Uniforms _uniforms");
1456 separator = ", ";
1457 }
1458 if (requirements & kGlobals_Requirement) {
1459 this->write(separator);
John Stilesf7410bd2021-01-19 13:07:55 -05001460 this->write("thread Globals& _globals");
John Stiles06b84ef2020-12-09 12:35:48 -05001461 separator = ", ";
1462 }
1463 if (requirements & kFragCoord_Requirement) {
1464 this->write(separator);
1465 this->write("float4 _fragCoord");
1466 separator = ", ";
1467 }
1468}
1469
John Stilesda5cdf62021-01-28 11:47:29 -05001470int MetalCodeGenerator::getUniformBinding(const Modifiers& m) {
1471 return (m.fLayout.fBinding >= 0) ? m.fLayout.fBinding
John Stiles270cec22021-02-17 12:59:36 -05001472 : fProgram.fConfig->fSettings.fDefaultUniformBinding;
John Stilesda5cdf62021-01-28 11:47:29 -05001473}
1474
1475int MetalCodeGenerator::getUniformSet(const Modifiers& m) {
1476 return (m.fLayout.fSet >= 0) ? m.fLayout.fSet
John Stiles270cec22021-02-17 12:59:36 -05001477 : fProgram.fConfig->fSettings.fDefaultUniformSet;
John Stilesda5cdf62021-01-28 11:47:29 -05001478}
1479
John Stiles569249b2020-11-03 12:18:22 -05001480bool MetalCodeGenerator::writeFunctionDeclaration(const FunctionDeclaration& f) {
John Stilesf7410bd2021-01-19 13:07:55 -05001481 fRTHeightName = fProgram.fInputs.fRTHeight ? "_globals._anonInterface0->u_skRTHeight" : "";
Ethan Nicholascc305772017-10-13 16:17:45 -04001482 const char* separator = "";
John Stilese8da4d22021-03-24 09:19:45 -04001483 if (f.isMain()) {
John Stiles270cec22021-02-17 12:59:36 -05001484 switch (fProgram.fConfig->fKind) {
John Stilesdbd4e6f2021-02-16 13:29:15 -05001485 case ProgramKind::kFragment:
Timothy Liangb8eeb802018-07-23 16:46:16 -04001486 this->write("fragment Outputs fragmentMain");
Ethan Nicholascc305772017-10-13 16:17:45 -04001487 break;
John Stilesdbd4e6f2021-02-16 13:29:15 -05001488 case ProgramKind::kVertex:
Timothy Liangb8eeb802018-07-23 16:46:16 -04001489 this->write("vertex Outputs vertexMain");
Ethan Nicholascc305772017-10-13 16:17:45 -04001490 break;
1491 default:
John Stiles3fabfc02020-09-25 15:51:28 -04001492 fErrors.error(-1, "unsupported kind of program");
John Stiles569249b2020-11-03 12:18:22 -05001493 return false;
Ethan Nicholascc305772017-10-13 16:17:45 -04001494 }
1495 this->write("(Inputs _in [[stage_in]]");
1496 if (-1 != fUniformBuffer) {
1497 this->write(", constant Uniforms& _uniforms [[buffer(" +
1498 to_string(fUniformBuffer) + ")]]");
1499 }
Brian Osman133724c2020-10-28 14:14:39 -04001500 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04001501 if (e->is<GlobalVarDeclaration>()) {
1502 const GlobalVarDeclaration& decls = e->as<GlobalVarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001503 const VarDeclaration& var = decls.declaration()->as<VarDeclaration>();
1504 if (var.var().type().typeKind() == Type::TypeKind::kSampler) {
1505 if (var.var().modifiers().fLayout.fBinding < 0) {
Brian Osmanc0213602020-10-06 14:43:32 -04001506 fErrors.error(decls.fOffset,
John Stilesb41d5bb2021-01-26 16:28:12 -05001507 "Metal samplers must have 'layout(binding=...)'");
John Stiles569249b2020-11-03 12:18:22 -05001508 return false;
Timothy Liangee84fe12018-05-18 14:38:19 -04001509 }
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001510 if (var.var().type().dimensions() != SpvDim2D) {
John Stiles569249b2020-11-03 12:18:22 -05001511 // Not yet implemented--Skia currently only uses 2D textures.
Brian Osmanc0213602020-10-06 14:43:32 -04001512 fErrors.error(decls.fOffset, "Unsupported texture dimensions");
John Stiles569249b2020-11-03 12:18:22 -05001513 return false;
Brian Osmanc0213602020-10-06 14:43:32 -04001514 }
1515 this->write(", texture2d<float> ");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001516 this->writeName(var.var().name());
Brian Osmanc0213602020-10-06 14:43:32 -04001517 this->write("[[texture(");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001518 this->write(to_string(var.var().modifiers().fLayout.fBinding));
Brian Osmanc0213602020-10-06 14:43:32 -04001519 this->write(")]]");
1520 this->write(", sampler ");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001521 this->writeName(var.var().name());
Brian Osmanc0213602020-10-06 14:43:32 -04001522 this->write(SAMPLER_SUFFIX);
1523 this->write("[[sampler(");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001524 this->write(to_string(var.var().modifiers().fLayout.fBinding));
Brian Osmanc0213602020-10-06 14:43:32 -04001525 this->write(")]]");
Timothy Liang6403b0e2018-05-17 10:40:04 -04001526 }
Brian Osman1179fcf2020-10-08 16:04:40 -04001527 } else if (e->is<InterfaceBlock>()) {
1528 const InterfaceBlock& intf = e->as<InterfaceBlock>();
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001529 if (intf.typeName() == "sk_PerVertex") {
Timothy Lianga06f2152018-05-24 15:33:31 -04001530 continue;
1531 }
1532 this->write(", constant ");
John Stilesb4418502021-02-04 10:57:08 -05001533 this->writeType(intf.variable().type());
Timothy Lianga06f2152018-05-24 15:33:31 -04001534 this->write("& " );
1535 this->write(fInterfaceBlockNameMap[&intf]);
1536 this->write(" [[buffer(");
John Stilesda5cdf62021-01-28 11:47:29 -05001537 this->write(to_string(this->getUniformBinding(intf.variable().modifiers())));
Timothy Lianga06f2152018-05-24 15:33:31 -04001538 this->write(")]]");
Timothy Liang6403b0e2018-05-17 10:40:04 -04001539 }
1540 }
John Stiles270cec22021-02-17 12:59:36 -05001541 if (fProgram.fConfig->fKind == ProgramKind::kFragment) {
Jim Van Verth6bc650e2019-02-07 14:53:23 -05001542 if (fProgram.fInputs.fRTHeight && fInterfaceBlockNameMap.empty()) {
Timothy Liang5422f9a2018-08-10 10:57:55 -04001543 this->write(", constant sksl_synthetic_uniforms& _anonInterface0 [[buffer(1)]]");
Ethan Nicholasf931e402019-07-26 15:40:33 -04001544 fRTHeightName = "_anonInterface0.u_skRTHeight";
Timothy Liang5422f9a2018-08-10 10:57:55 -04001545 }
Timothy Liang7b8875d2018-08-10 09:42:31 -04001546 this->write(", bool _frontFacing [[front_facing]]");
Timothy Liang7d637782018-06-05 09:58:07 -04001547 this->write(", float4 _fragCoord [[position]]");
John Stiles270cec22021-02-17 12:59:36 -05001548 } else if (fProgram.fConfig->fKind == ProgramKind::kVertex) {
Timothy Liangdc89f192018-06-13 09:20:31 -04001549 this->write(", uint sk_VertexID [[vertex_id]], uint sk_InstanceID [[instance_id]]");
Timothy Liang7d637782018-06-05 09:58:07 -04001550 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001551 separator = ", ";
1552 } else {
John Stilesb4418502021-02-04 10:57:08 -05001553 this->writeType(f.returnType());
Timothy Liang651286f2018-06-07 09:55:33 -04001554 this->write(" ");
John Stilese1068342021-03-22 11:57:41 -04001555 this->writeName(f.mangledName());
Timothy Liang651286f2018-06-07 09:55:33 -04001556 this->write("(");
John Stiles06b84ef2020-12-09 12:35:48 -05001557 this->writeFunctionRequirementParams(f, separator);
Ethan Nicholascc305772017-10-13 16:17:45 -04001558 }
John Stiles569249b2020-11-03 12:18:22 -05001559 for (const auto& param : f.parameters()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001560 this->write(separator);
1561 separator = ", ";
John Stiles06b84ef2020-12-09 12:35:48 -05001562 this->writeModifiers(param->modifiers(), /*globalContext=*/false);
Ethan Nicholas30d30222020-09-11 12:27:26 -04001563 const Type* type = &param->type();
John Stilesb4418502021-02-04 10:57:08 -05001564 this->writeType(*type);
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001565 if (param->modifiers().fFlags & Modifiers::kOut_Flag) {
John Stilesf2bd5012020-12-04 11:58:26 -05001566 this->write("&");
Ethan Nicholascc305772017-10-13 16:17:45 -04001567 }
Timothy Liang651286f2018-06-07 09:55:33 -04001568 this->write(" ");
Ethan Nicholase2c49992020-10-05 11:49:11 -04001569 this->writeName(param->name());
Ethan Nicholascc305772017-10-13 16:17:45 -04001570 }
John Stiles569249b2020-11-03 12:18:22 -05001571 this->write(")");
1572 return true;
1573}
Ethan Nicholascc305772017-10-13 16:17:45 -04001574
John Stiles569249b2020-11-03 12:18:22 -05001575void MetalCodeGenerator::writeFunctionPrototype(const FunctionPrototype& f) {
1576 this->writeFunctionDeclaration(f.declaration());
1577 this->writeLine(";");
1578}
1579
John Stiles986c7fb2020-12-01 14:44:56 -05001580static bool is_block_ending_with_return(const Statement* stmt) {
1581 // This function detects (potentially nested) blocks that end in a return statement.
1582 if (!stmt->is<Block>()) {
1583 return false;
1584 }
1585 const StatementArray& block = stmt->as<Block>().children();
1586 for (int index = block.count(); index--; ) {
1587 const Statement& stmt = *block[index];
1588 if (stmt.is<ReturnStatement>()) {
1589 return true;
1590 }
1591 if (stmt.is<Block>()) {
1592 return is_block_ending_with_return(&stmt);
1593 }
1594 if (!stmt.is<Nop>()) {
1595 break;
1596 }
1597 }
1598 return false;
1599}
1600
John Stiles569249b2020-11-03 12:18:22 -05001601void MetalCodeGenerator::writeFunction(const FunctionDefinition& f) {
John Stiles270cec22021-02-17 12:59:36 -05001602 SkASSERT(!fProgram.fConfig->fSettings.fFragColorIsInOut);
Brian Salomondc092132018-04-04 10:14:16 -04001603
John Stiles569249b2020-11-03 12:18:22 -05001604 if (!this->writeFunctionDeclaration(f.declaration())) {
1605 return;
1606 }
1607
John Stiles986c7fb2020-12-01 14:44:56 -05001608 fCurrentFunction = &f.declaration();
1609 SkScopeExit clearCurrentFunction([&] { fCurrentFunction = nullptr; });
1610
John Stiles569249b2020-11-03 12:18:22 -05001611 this->writeLine(" {");
1612
John Stilese8da4d22021-03-24 09:19:45 -04001613 if (f.declaration().isMain()) {
John Stilescdcdb042020-07-06 09:03:51 -04001614 this->writeGlobalInit();
John Stilesf7410bd2021-01-19 13:07:55 -05001615 this->writeLine(" Outputs _out;");
John Stiles37279172021-01-21 22:24:28 -05001616 this->writeLine(" (void)_out;");
Ethan Nicholascc305772017-10-13 16:17:45 -04001617 }
John Stilesc67b3622020-05-28 17:53:13 -04001618
Ethan Nicholascc305772017-10-13 16:17:45 -04001619 fFunctionHeader = "";
Ethan Nicholascc305772017-10-13 16:17:45 -04001620 StringStream buffer;
John Stiles44532372020-12-07 12:33:55 -05001621 {
1622 AutoOutputStream outputToBuffer(this, &buffer);
1623 fIndentation++;
1624 for (const std::unique_ptr<Statement>& stmt : f.body()->as<Block>().children()) {
1625 if (!stmt->isEmpty()) {
1626 this->writeStatement(*stmt);
John Stilese8b5a732021-03-12 13:25:52 -05001627 this->finishLine();
John Stiles44532372020-12-07 12:33:55 -05001628 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001629 }
John Stilese8da4d22021-03-24 09:19:45 -04001630 if (f.declaration().isMain()) {
John Stiles44532372020-12-07 12:33:55 -05001631 // If the main function doesn't end with a return, we need to synthesize one here.
1632 if (!is_block_ending_with_return(f.body().get())) {
1633 this->writeReturnStatementFromMain();
John Stilese8b5a732021-03-12 13:25:52 -05001634 this->finishLine();
John Stiles44532372020-12-07 12:33:55 -05001635 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001636 }
John Stiles44532372020-12-07 12:33:55 -05001637 fIndentation--;
1638 this->writeLine("}");
Ethan Nicholascc305772017-10-13 16:17:45 -04001639 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001640 this->write(fFunctionHeader);
1641 this->write(buffer.str());
1642}
1643
1644void MetalCodeGenerator::writeModifiers(const Modifiers& modifiers,
John Stiles06b84ef2020-12-09 12:35:48 -05001645 bool globalContext) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001646 if (modifiers.fFlags & Modifiers::kOut_Flag) {
1647 this->write("thread ");
1648 }
1649 if (modifiers.fFlags & Modifiers::kConst_Flag) {
John Stiles0bd55782021-02-09 18:29:40 -05001650 this->write("const ");
Ethan Nicholascc305772017-10-13 16:17:45 -04001651 }
1652}
1653
1654void MetalCodeGenerator::writeInterfaceBlock(const InterfaceBlock& intf) {
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001655 if ("sk_PerVertex" == intf.typeName()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001656 return;
1657 }
John Stiles06b84ef2020-12-09 12:35:48 -05001658 this->writeModifiers(intf.variable().modifiers(), /*globalContext=*/true);
Timothy Liangdc89f192018-06-13 09:20:31 -04001659 this->write("struct ");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001660 this->writeLine(intf.typeName() + " {");
1661 const Type* structType = &intf.variable().type();
John Stilesbb43b7e2020-12-03 17:36:32 -05001662 if (structType->isArray()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001663 structType = &structType->componentType();
1664 }
Timothy Liangdc89f192018-06-13 09:20:31 -04001665 fIndentation++;
John Stiles3dba3ee2020-12-02 23:35:49 -05001666 this->writeFields(structType->fields(), structType->fOffset, &intf);
Jim Van Verth3d482992019-02-07 10:48:05 -05001667 if (fProgram.fInputs.fRTHeight) {
Timothy Liang7d637782018-06-05 09:58:07 -04001668 this->writeLine("float u_skRTHeight;");
Ethan Nicholascc305772017-10-13 16:17:45 -04001669 }
1670 fIndentation--;
1671 this->write("}");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001672 if (intf.instanceName().size()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001673 this->write(" ");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001674 this->write(intf.instanceName());
John Stilesd39aec02020-12-03 10:42:26 -05001675 if (intf.arraySize() > 0) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001676 this->write("[");
John Stilesd39aec02020-12-03 10:42:26 -05001677 this->write(to_string(intf.arraySize()));
Ethan Nicholascc305772017-10-13 16:17:45 -04001678 this->write("]");
John Stilesd39aec02020-12-03 10:42:26 -05001679 } else if (intf.arraySize() == Type::kUnsizedArray){
1680 this->write("[]");
Ethan Nicholascc305772017-10-13 16:17:45 -04001681 }
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001682 fInterfaceBlockNameMap[&intf] = intf.instanceName();
Timothy Lianga06f2152018-05-24 15:33:31 -04001683 } else {
Timothy Liang7d637782018-06-05 09:58:07 -04001684 fInterfaceBlockNameMap[&intf] = "_anonInterface" + to_string(fAnonInterfaceCount++);
Ethan Nicholascc305772017-10-13 16:17:45 -04001685 }
1686 this->writeLine(";");
1687}
1688
Timothy Liangdc89f192018-06-13 09:20:31 -04001689void MetalCodeGenerator::writeFields(const std::vector<Type::Field>& fields, int parentOffset,
1690 const InterfaceBlock* parentIntf) {
Timothy Liang609fbe32018-08-10 16:40:49 -04001691 MemoryLayout memoryLayout(MemoryLayout::kMetal_Standard);
Timothy Liangdc89f192018-06-13 09:20:31 -04001692 int currentOffset = 0;
1693 for (const auto& field: fields) {
1694 int fieldOffset = field.fModifiers.fLayout.fOffset;
1695 const Type* fieldType = field.fType;
John Stiles21f5f452020-11-30 09:57:59 -05001696 if (!MemoryLayout::LayoutIsSupported(*fieldType)) {
John Stiles0023c0c2020-11-16 13:32:18 -05001697 fErrors.error(parentOffset, "type '" + fieldType->name() + "' is not permitted here");
1698 return;
1699 }
Timothy Liangdc89f192018-06-13 09:20:31 -04001700 if (fieldOffset != -1) {
1701 if (currentOffset > fieldOffset) {
1702 fErrors.error(parentOffset,
John Stilesd7199b22020-12-30 16:22:58 -05001703 "offset of field '" + field.fName + "' must be at least " +
1704 to_string((int) currentOffset));
Brian Osman8609a242020-09-08 14:01:49 -04001705 return;
Timothy Liangdc89f192018-06-13 09:20:31 -04001706 } else if (currentOffset < fieldOffset) {
1707 this->write("char pad");
1708 this->write(to_string(fPaddingCount++));
1709 this->write("[");
1710 this->write(to_string(fieldOffset - currentOffset));
1711 this->writeLine("];");
1712 currentOffset = fieldOffset;
1713 }
1714 int alignment = memoryLayout.alignment(*fieldType);
1715 if (fieldOffset % alignment) {
1716 fErrors.error(parentOffset,
1717 "offset of field '" + field.fName + "' must be a multiple of " +
1718 to_string((int) alignment));
Brian Osman8609a242020-09-08 14:01:49 -04001719 return;
Timothy Liangdc89f192018-06-13 09:20:31 -04001720 }
1721 }
Brian Osman8609a242020-09-08 14:01:49 -04001722 size_t fieldSize = memoryLayout.size(*fieldType);
1723 if (fieldSize > static_cast<size_t>(std::numeric_limits<int>::max() - currentOffset)) {
1724 fErrors.error(parentOffset, "field offset overflow");
1725 return;
1726 }
1727 currentOffset += fieldSize;
John Stiles06b84ef2020-12-09 12:35:48 -05001728 this->writeModifiers(field.fModifiers, /*globalContext=*/false);
John Stilesb4418502021-02-04 10:57:08 -05001729 this->writeType(*fieldType);
Timothy Liangdc89f192018-06-13 09:20:31 -04001730 this->write(" ");
1731 this->writeName(field.fName);
Timothy Liangdc89f192018-06-13 09:20:31 -04001732 this->writeLine(";");
1733 if (parentIntf) {
1734 fInterfaceBlockMap[&field] = parentIntf;
1735 }
1736 }
1737}
1738
Ethan Nicholascc305772017-10-13 16:17:45 -04001739void MetalCodeGenerator::writeVarInitializer(const Variable& var, const Expression& value) {
Brian Osman00185012021-02-04 16:07:11 -05001740 this->writeExpression(value, Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001741}
1742
Timothy Liang651286f2018-06-07 09:55:33 -04001743void MetalCodeGenerator::writeName(const String& name) {
1744 if (fReservedWords.find(name) != fReservedWords.end()) {
1745 this->write("_"); // adding underscore before name to avoid conflict with reserved words
1746 }
1747 this->write(name);
1748}
1749
John Stilesb4418502021-02-04 10:57:08 -05001750void MetalCodeGenerator::writeVarDeclaration(const VarDeclaration& varDecl, bool global) {
1751 if (global && !(varDecl.var().modifiers().fFlags & Modifiers::kConst_Flag)) {
Brian Osmanc0213602020-10-06 14:43:32 -04001752 return;
Ethan Nicholascc305772017-10-13 16:17:45 -04001753 }
John Stilesb4418502021-02-04 10:57:08 -05001754 this->writeModifiers(varDecl.var().modifiers(), global);
1755 this->writeType(varDecl.var().type());
Brian Osmanc0213602020-10-06 14:43:32 -04001756 this->write(" ");
John Stilesb4418502021-02-04 10:57:08 -05001757 this->writeName(varDecl.var().name());
1758 if (varDecl.value()) {
Brian Osmanc0213602020-10-06 14:43:32 -04001759 this->write(" = ");
John Stilesb4418502021-02-04 10:57:08 -05001760 this->writeVarInitializer(varDecl.var(), *varDecl.value());
Brian Osmanc0213602020-10-06 14:43:32 -04001761 }
1762 this->write(";");
Ethan Nicholascc305772017-10-13 16:17:45 -04001763}
1764
1765void MetalCodeGenerator::writeStatement(const Statement& s) {
Ethan Nicholase6592142020-09-08 10:22:09 -04001766 switch (s.kind()) {
1767 case Statement::Kind::kBlock:
John Stiles26f98502020-08-18 09:30:51 -04001768 this->writeBlock(s.as<Block>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001769 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001770 case Statement::Kind::kExpression:
Brian Osman00185012021-02-04 16:07:11 -05001771 this->writeExpression(*s.as<ExpressionStatement>().expression(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001772 this->write(";");
1773 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001774 case Statement::Kind::kReturn:
John Stiles26f98502020-08-18 09:30:51 -04001775 this->writeReturnStatement(s.as<ReturnStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001776 break;
Brian Osmanc0213602020-10-06 14:43:32 -04001777 case Statement::Kind::kVarDeclaration:
1778 this->writeVarDeclaration(s.as<VarDeclaration>(), false);
Ethan Nicholascc305772017-10-13 16:17:45 -04001779 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001780 case Statement::Kind::kIf:
John Stiles26f98502020-08-18 09:30:51 -04001781 this->writeIfStatement(s.as<IfStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001782 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001783 case Statement::Kind::kFor:
John Stiles26f98502020-08-18 09:30:51 -04001784 this->writeForStatement(s.as<ForStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001785 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001786 case Statement::Kind::kDo:
John Stiles26f98502020-08-18 09:30:51 -04001787 this->writeDoStatement(s.as<DoStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001788 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001789 case Statement::Kind::kSwitch:
John Stiles26f98502020-08-18 09:30:51 -04001790 this->writeSwitchStatement(s.as<SwitchStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001791 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001792 case Statement::Kind::kBreak:
Ethan Nicholascc305772017-10-13 16:17:45 -04001793 this->write("break;");
1794 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001795 case Statement::Kind::kContinue:
Ethan Nicholascc305772017-10-13 16:17:45 -04001796 this->write("continue;");
1797 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001798 case Statement::Kind::kDiscard:
Timothy Lianga06f2152018-05-24 15:33:31 -04001799 this->write("discard_fragment();");
Ethan Nicholascc305772017-10-13 16:17:45 -04001800 break;
John Stiles98c1f822020-09-09 14:18:53 -04001801 case Statement::Kind::kInlineMarker:
Ethan Nicholase6592142020-09-08 10:22:09 -04001802 case Statement::Kind::kNop:
Ethan Nicholascc305772017-10-13 16:17:45 -04001803 this->write(";");
1804 break;
1805 default:
John Stileseada7bc2021-02-02 16:29:32 -05001806 SkDEBUGFAILF("unsupported statement: %s", s.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -05001807 break;
Ethan Nicholascc305772017-10-13 16:17:45 -04001808 }
1809}
1810
Ethan Nicholascc305772017-10-13 16:17:45 -04001811void MetalCodeGenerator::writeBlock(const Block& b) {
John Stiles3744bd62021-01-26 13:49:43 -05001812 // Write scope markers if this block is a scope, or if the block is empty (since we need to emit
1813 // something here to make the code valid).
1814 bool isScope = b.isScope() || b.isEmpty();
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001815 if (isScope) {
Ethan Nicholas70728ef2020-05-28 07:09:00 -04001816 this->writeLine("{");
1817 fIndentation++;
1818 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001819 for (const std::unique_ptr<Statement>& stmt : b.children()) {
1820 if (!stmt->isEmpty()) {
1821 this->writeStatement(*stmt);
John Stilese8b5a732021-03-12 13:25:52 -05001822 this->finishLine();
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001823 }
1824 }
1825 if (isScope) {
Ethan Nicholas70728ef2020-05-28 07:09:00 -04001826 fIndentation--;
1827 this->write("}");
1828 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001829}
1830
1831void MetalCodeGenerator::writeIfStatement(const IfStatement& stmt) {
1832 this->write("if (");
Brian Osman00185012021-02-04 16:07:11 -05001833 this->writeExpression(*stmt.test(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001834 this->write(") ");
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04001835 this->writeStatement(*stmt.ifTrue());
1836 if (stmt.ifFalse()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001837 this->write(" else ");
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04001838 this->writeStatement(*stmt.ifFalse());
Ethan Nicholascc305772017-10-13 16:17:45 -04001839 }
1840}
1841
1842void MetalCodeGenerator::writeForStatement(const ForStatement& f) {
Brian Osmand6f23382020-12-15 17:08:59 -05001843 // Emit loops of the form 'for(;test;)' as 'while(test)', which is probably how they started
1844 if (!f.initializer() && f.test() && !f.next()) {
1845 this->write("while (");
Brian Osman00185012021-02-04 16:07:11 -05001846 this->writeExpression(*f.test(), Precedence::kTopLevel);
Brian Osmand6f23382020-12-15 17:08:59 -05001847 this->write(") ");
1848 this->writeStatement(*f.statement());
1849 return;
1850 }
1851
Ethan Nicholascc305772017-10-13 16:17:45 -04001852 this->write("for (");
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04001853 if (f.initializer() && !f.initializer()->isEmpty()) {
1854 this->writeStatement(*f.initializer());
Ethan Nicholascc305772017-10-13 16:17:45 -04001855 } else {
1856 this->write("; ");
1857 }
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04001858 if (f.test()) {
Brian Osman00185012021-02-04 16:07:11 -05001859 this->writeExpression(*f.test(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001860 }
1861 this->write("; ");
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04001862 if (f.next()) {
Brian Osman00185012021-02-04 16:07:11 -05001863 this->writeExpression(*f.next(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001864 }
1865 this->write(") ");
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04001866 this->writeStatement(*f.statement());
Ethan Nicholascc305772017-10-13 16:17:45 -04001867}
1868
Ethan Nicholascc305772017-10-13 16:17:45 -04001869void MetalCodeGenerator::writeDoStatement(const DoStatement& d) {
1870 this->write("do ");
Ethan Nicholas1fd61162020-09-28 13:14:19 -04001871 this->writeStatement(*d.statement());
Ethan Nicholascc305772017-10-13 16:17:45 -04001872 this->write(" while (");
Brian Osman00185012021-02-04 16:07:11 -05001873 this->writeExpression(*d.test(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001874 this->write(");");
1875}
1876
1877void MetalCodeGenerator::writeSwitchStatement(const SwitchStatement& s) {
1878 this->write("switch (");
Brian Osman00185012021-02-04 16:07:11 -05001879 this->writeExpression(*s.value(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001880 this->writeLine(") {");
1881 fIndentation++;
John Stilesb23a64b2021-03-11 08:27:59 -05001882 for (const std::unique_ptr<Statement>& stmt : s.cases()) {
1883 const SwitchCase& c = stmt->as<SwitchCase>();
1884 if (c.value()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001885 this->write("case ");
John Stilesb23a64b2021-03-11 08:27:59 -05001886 this->writeExpression(*c.value(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001887 this->writeLine(":");
1888 } else {
1889 this->writeLine("default:");
1890 }
John Stilesb23a64b2021-03-11 08:27:59 -05001891 if (!c.statement()->isEmpty()) {
John Stilesc3ce43b2021-03-09 15:37:01 -05001892 fIndentation++;
John Stilesb23a64b2021-03-11 08:27:59 -05001893 this->writeStatement(*c.statement());
John Stilese8b5a732021-03-12 13:25:52 -05001894 this->finishLine();
John Stilesc3ce43b2021-03-09 15:37:01 -05001895 fIndentation--;
Ethan Nicholascc305772017-10-13 16:17:45 -04001896 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001897 }
1898 fIndentation--;
1899 this->write("}");
1900}
1901
John Stiles986c7fb2020-12-01 14:44:56 -05001902void MetalCodeGenerator::writeReturnStatementFromMain() {
1903 // main functions in Metal return a magic _out parameter that doesn't exist in SkSL.
John Stiles270cec22021-02-17 12:59:36 -05001904 switch (fProgram.fConfig->fKind) {
John Stilesdbd4e6f2021-02-16 13:29:15 -05001905 case ProgramKind::kFragment:
John Stilesf7410bd2021-01-19 13:07:55 -05001906 this->write("return _out;");
John Stiles986c7fb2020-12-01 14:44:56 -05001907 break;
John Stilesdbd4e6f2021-02-16 13:29:15 -05001908 case ProgramKind::kVertex:
John Stilesf7410bd2021-01-19 13:07:55 -05001909 this->write("return (_out.sk_Position.y = -_out.sk_Position.y, _out);");
John Stiles986c7fb2020-12-01 14:44:56 -05001910 break;
1911 default:
1912 SkDEBUGFAIL("unsupported kind of program");
1913 }
1914}
1915
Ethan Nicholascc305772017-10-13 16:17:45 -04001916void MetalCodeGenerator::writeReturnStatement(const ReturnStatement& r) {
John Stilese8da4d22021-03-24 09:19:45 -04001917 if (fCurrentFunction && fCurrentFunction->isMain()) {
John Stiles986c7fb2020-12-01 14:44:56 -05001918 if (r.expression()) {
John Stiles97d18172021-01-22 16:47:42 -05001919 if (r.expression()->type() == *fContext.fTypes.fHalf4) {
1920 this->write("_out.sk_FragColor = ");
Brian Osman00185012021-02-04 16:07:11 -05001921 this->writeExpression(*r.expression(), Precedence::kTopLevel);
John Stiles97d18172021-01-22 16:47:42 -05001922 this->writeLine(";");
1923 } else {
1924 fErrors.error(r.fOffset, "Metal does not support returning '" +
1925 r.expression()->type().description() + "' from main()");
1926 }
John Stiles986c7fb2020-12-01 14:44:56 -05001927 }
1928 this->writeReturnStatementFromMain();
1929 return;
1930 }
1931
Ethan Nicholascc305772017-10-13 16:17:45 -04001932 this->write("return");
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04001933 if (r.expression()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001934 this->write(" ");
Brian Osman00185012021-02-04 16:07:11 -05001935 this->writeExpression(*r.expression(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001936 }
1937 this->write(";");
1938}
1939
Michael Ludwigbf58add2021-03-16 10:40:11 -04001940void MetalCodeGenerator::writeHeader() {
1941 this->write("#include <metal_stdlib>\n");
1942 this->write("#include <simd/simd.h>\n");
1943 this->write("using namespace metal;\n");
1944}
1945
Ethan Nicholascc305772017-10-13 16:17:45 -04001946void MetalCodeGenerator::writeUniformStruct() {
Brian Osman133724c2020-10-28 14:14:39 -04001947 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04001948 if (e->is<GlobalVarDeclaration>()) {
1949 const GlobalVarDeclaration& decls = e->as<GlobalVarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001950 const Variable& var = decls.declaration()->as<VarDeclaration>().var();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001951 if (var.modifiers().fFlags & Modifiers::kUniform_Flag &&
Brian Osmanc0213602020-10-06 14:43:32 -04001952 var.type().typeKind() != Type::TypeKind::kSampler) {
John Stilesda5cdf62021-01-28 11:47:29 -05001953 int uniformSet = this->getUniformSet(var.modifiers());
John Stilesd8fc95d2021-01-26 16:22:53 -05001954 // Make sure that the program's uniform-set value is consistent throughout.
Ethan Nicholascc305772017-10-13 16:17:45 -04001955 if (-1 == fUniformBuffer) {
1956 this->write("struct Uniforms {\n");
John Stilesd8fc95d2021-01-26 16:22:53 -05001957 fUniformBuffer = uniformSet;
1958 } else if (uniformSet != fUniformBuffer) {
1959 fErrors.error(decls.fOffset, "Metal backend requires all uniforms to have "
1960 "the same 'layout(set=...)'");
Ethan Nicholascc305772017-10-13 16:17:45 -04001961 }
1962 this->write(" ");
John Stilesb4418502021-02-04 10:57:08 -05001963 this->writeType(var.type());
Ethan Nicholascc305772017-10-13 16:17:45 -04001964 this->write(" ");
Brian Osmanc0213602020-10-06 14:43:32 -04001965 this->writeName(var.name());
Ethan Nicholascc305772017-10-13 16:17:45 -04001966 this->write(";\n");
1967 }
1968 }
1969 }
1970 if (-1 != fUniformBuffer) {
1971 this->write("};\n");
1972 }
1973}
1974
1975void MetalCodeGenerator::writeInputStruct() {
1976 this->write("struct Inputs {\n");
Brian Osman133724c2020-10-28 14:14:39 -04001977 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04001978 if (e->is<GlobalVarDeclaration>()) {
1979 const GlobalVarDeclaration& decls = e->as<GlobalVarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001980 const Variable& var = decls.declaration()->as<VarDeclaration>().var();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001981 if (var.modifiers().fFlags & Modifiers::kIn_Flag &&
1982 -1 == var.modifiers().fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001983 this->write(" ");
John Stilesb4418502021-02-04 10:57:08 -05001984 this->writeType(var.type());
Ethan Nicholascc305772017-10-13 16:17:45 -04001985 this->write(" ");
Brian Osmanc0213602020-10-06 14:43:32 -04001986 this->writeName(var.name());
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001987 if (-1 != var.modifiers().fLayout.fLocation) {
John Stiles270cec22021-02-17 12:59:36 -05001988 if (fProgram.fConfig->fKind == ProgramKind::kVertex) {
Brian Osmanc0213602020-10-06 14:43:32 -04001989 this->write(" [[attribute(" +
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001990 to_string(var.modifiers().fLayout.fLocation) + ")]]");
John Stiles270cec22021-02-17 12:59:36 -05001991 } else if (fProgram.fConfig->fKind == ProgramKind::kFragment) {
Brian Osmanc0213602020-10-06 14:43:32 -04001992 this->write(" [[user(locn" +
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001993 to_string(var.modifiers().fLayout.fLocation) + ")]]");
Ethan Nicholascc305772017-10-13 16:17:45 -04001994 }
1995 }
1996 this->write(";\n");
1997 }
1998 }
1999 }
2000 this->write("};\n");
2001}
2002
2003void MetalCodeGenerator::writeOutputStruct() {
2004 this->write("struct Outputs {\n");
John Stiles270cec22021-02-17 12:59:36 -05002005 if (fProgram.fConfig->fKind == ProgramKind::kVertex) {
Timothy Liangb8eeb802018-07-23 16:46:16 -04002006 this->write(" float4 sk_Position [[position]];\n");
John Stiles270cec22021-02-17 12:59:36 -05002007 } else if (fProgram.fConfig->fKind == ProgramKind::kFragment) {
Timothy Liangde0be802018-08-10 13:48:08 -04002008 this->write(" float4 sk_FragColor [[color(0)]];\n");
Timothy Liang7d637782018-06-05 09:58:07 -04002009 }
Brian Osman133724c2020-10-28 14:14:39 -04002010 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04002011 if (e->is<GlobalVarDeclaration>()) {
2012 const GlobalVarDeclaration& decls = e->as<GlobalVarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04002013 const Variable& var = decls.declaration()->as<VarDeclaration>().var();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002014 if (var.modifiers().fFlags & Modifiers::kOut_Flag &&
2015 -1 == var.modifiers().fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002016 this->write(" ");
John Stilesb4418502021-02-04 10:57:08 -05002017 this->writeType(var.type());
Ethan Nicholascc305772017-10-13 16:17:45 -04002018 this->write(" ");
Brian Osmanc0213602020-10-06 14:43:32 -04002019 this->writeName(var.name());
John Stiles842b3592020-12-01 10:36:37 -05002020
2021 int location = var.modifiers().fLayout.fLocation;
2022 if (location < 0) {
2023 fErrors.error(var.fOffset,
2024 "Metal out variables must have 'layout(location=...)'");
John Stiles270cec22021-02-17 12:59:36 -05002025 } else if (fProgram.fConfig->fKind == ProgramKind::kVertex) {
John Stiles842b3592020-12-01 10:36:37 -05002026 this->write(" [[user(locn" + to_string(location) + ")]]");
John Stiles270cec22021-02-17 12:59:36 -05002027 } else if (fProgram.fConfig->fKind == ProgramKind::kFragment) {
John Stiles842b3592020-12-01 10:36:37 -05002028 this->write(" [[color(" + to_string(location) + ")");
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002029 int colorIndex = var.modifiers().fLayout.fIndex;
Brian Osmanc0213602020-10-06 14:43:32 -04002030 if (colorIndex) {
2031 this->write(", index(" + to_string(colorIndex) + ")");
Timothy Liang7d637782018-06-05 09:58:07 -04002032 }
Brian Osmanc0213602020-10-06 14:43:32 -04002033 this->write("]]");
Ethan Nicholascc305772017-10-13 16:17:45 -04002034 }
2035 this->write(";\n");
2036 }
2037 }
Timothy Liang7d637782018-06-05 09:58:07 -04002038 }
John Stiles270cec22021-02-17 12:59:36 -05002039 if (fProgram.fConfig->fKind == ProgramKind::kVertex) {
Jim Van Verth3913d3e2020-08-31 15:16:57 -04002040 this->write(" float sk_PointSize [[point_size]];\n");
Timothy Liang7d637782018-06-05 09:58:07 -04002041 }
2042 this->write("};\n");
2043}
2044
2045void MetalCodeGenerator::writeInterfaceBlocks() {
2046 bool wroteInterfaceBlock = false;
Brian Osman133724c2020-10-28 14:14:39 -04002047 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04002048 if (e->is<InterfaceBlock>()) {
2049 this->writeInterfaceBlock(e->as<InterfaceBlock>());
Timothy Liang7d637782018-06-05 09:58:07 -04002050 wroteInterfaceBlock = true;
2051 }
2052 }
Jim Van Verth3d482992019-02-07 10:48:05 -05002053 if (!wroteInterfaceBlock && fProgram.fInputs.fRTHeight) {
Timothy Liang7d637782018-06-05 09:58:07 -04002054 this->writeLine("struct sksl_synthetic_uniforms {");
2055 this->writeLine(" float u_skRTHeight;");
2056 this->writeLine("};");
2057 }
Ethan Nicholascc305772017-10-13 16:17:45 -04002058}
2059
John Stilesdc75a972020-11-25 16:24:55 -05002060void MetalCodeGenerator::writeStructDefinitions() {
2061 for (const ProgramElement* e : fProgram.elements()) {
2062 if (e->is<StructDefinition>()) {
Brian Osman02bc5222021-01-28 11:00:20 -05002063 this->writeStructDefinition(e->as<StructDefinition>());
John Stilesdc75a972020-11-25 16:24:55 -05002064 }
2065 }
2066}
2067
John Stilescdcdb042020-07-06 09:03:51 -04002068void MetalCodeGenerator::visitGlobalStruct(GlobalStructVisitor* visitor) {
2069 // Visit the interface blocks.
2070 for (const auto& [interfaceType, interfaceName] : fInterfaceBlockNameMap) {
John Stilesfdb8dbe2020-12-04 11:00:03 -05002071 visitor->visitInterfaceBlock(*interfaceType, interfaceName);
John Stilescdcdb042020-07-06 09:03:51 -04002072 }
Brian Osman133724c2020-10-28 14:14:39 -04002073 for (const ProgramElement* element : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04002074 if (!element->is<GlobalVarDeclaration>()) {
John Stilescdcdb042020-07-06 09:03:51 -04002075 continue;
Timothy Liang7d637782018-06-05 09:58:07 -04002076 }
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04002077 const GlobalVarDeclaration& global = element->as<GlobalVarDeclaration>();
2078 const VarDeclaration& decl = global.declaration()->as<VarDeclaration>();
2079 const Variable& var = decl.var();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002080 if ((!var.modifiers().fFlags && -1 == var.modifiers().fLayout.fBuiltin) ||
Brian Osmanc0213602020-10-06 14:43:32 -04002081 var.type().typeKind() == Type::TypeKind::kSampler) {
2082 if (var.type().typeKind() == Type::TypeKind::kSampler) {
2083 // Samplers are represented as a "texture/sampler" duo in the global struct.
John Stilesfdb8dbe2020-12-04 11:00:03 -05002084 visitor->visitTexture(var.type(), var.name());
2085 visitor->visitSampler(var.type(), String(var.name()) + SAMPLER_SUFFIX);
Brian Osmanc0213602020-10-06 14:43:32 -04002086 } else {
2087 // Visit a regular variable.
John Stilesfdb8dbe2020-12-04 11:00:03 -05002088 visitor->visitVariable(var, decl.value().get());
Timothy Liangee84fe12018-05-18 14:38:19 -04002089 }
2090 }
2091 }
John Stilescdcdb042020-07-06 09:03:51 -04002092}
2093
2094void MetalCodeGenerator::writeGlobalStruct() {
2095 class : public GlobalStructVisitor {
2096 public:
John Stilesfdb8dbe2020-12-04 11:00:03 -05002097 void visitInterfaceBlock(const InterfaceBlock& block, const String& blockName) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002098 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002099 fCodeGen->write(" constant ");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04002100 fCodeGen->write(block.typeName());
John Stilescdcdb042020-07-06 09:03:51 -04002101 fCodeGen->write("* ");
2102 fCodeGen->writeName(blockName);
2103 fCodeGen->write(";\n");
2104 }
John Stilesfdb8dbe2020-12-04 11:00:03 -05002105 void visitTexture(const Type& type, const String& name) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002106 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002107 fCodeGen->write(" ");
John Stilesb4418502021-02-04 10:57:08 -05002108 fCodeGen->writeType(type);
John Stilescdcdb042020-07-06 09:03:51 -04002109 fCodeGen->write(" ");
2110 fCodeGen->writeName(name);
2111 fCodeGen->write(";\n");
2112 }
John Stilesfdb8dbe2020-12-04 11:00:03 -05002113 void visitSampler(const Type&, const String& name) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002114 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002115 fCodeGen->write(" sampler ");
2116 fCodeGen->writeName(name);
2117 fCodeGen->write(";\n");
2118 }
John Stilesfdb8dbe2020-12-04 11:00:03 -05002119 void visitVariable(const Variable& var, const Expression* value) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002120 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002121 fCodeGen->write(" ");
John Stilesb4418502021-02-04 10:57:08 -05002122 fCodeGen->writeType(var.type());
John Stilescdcdb042020-07-06 09:03:51 -04002123 fCodeGen->write(" ");
Ethan Nicholase2c49992020-10-05 11:49:11 -04002124 fCodeGen->writeName(var.name());
John Stilescdcdb042020-07-06 09:03:51 -04002125 fCodeGen->write(";\n");
2126 }
John Stiles83f3b8d2020-12-07 17:52:25 -05002127 void addElement() {
John Stilescdcdb042020-07-06 09:03:51 -04002128 if (fFirst) {
2129 fCodeGen->write("struct Globals {\n");
2130 fFirst = false;
2131 }
2132 }
John Stiles83f3b8d2020-12-07 17:52:25 -05002133 void finish() {
John Stilescdcdb042020-07-06 09:03:51 -04002134 if (!fFirst) {
John Stiles83f3b8d2020-12-07 17:52:25 -05002135 fCodeGen->writeLine("};");
John Stilescdcdb042020-07-06 09:03:51 -04002136 fFirst = true;
2137 }
2138 }
2139
2140 MetalCodeGenerator* fCodeGen = nullptr;
2141 bool fFirst = true;
2142 } visitor;
2143
2144 visitor.fCodeGen = this;
2145 this->visitGlobalStruct(&visitor);
John Stiles83f3b8d2020-12-07 17:52:25 -05002146 visitor.finish();
John Stilescdcdb042020-07-06 09:03:51 -04002147}
2148
2149void MetalCodeGenerator::writeGlobalInit() {
2150 class : public GlobalStructVisitor {
2151 public:
John Stilesfdb8dbe2020-12-04 11:00:03 -05002152 void visitInterfaceBlock(const InterfaceBlock& blockType,
John Stilescdcdb042020-07-06 09:03:51 -04002153 const String& blockName) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002154 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002155 fCodeGen->write("&");
2156 fCodeGen->writeName(blockName);
2157 }
John Stilesfdb8dbe2020-12-04 11:00:03 -05002158 void visitTexture(const Type&, const String& name) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002159 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002160 fCodeGen->writeName(name);
2161 }
John Stilesfdb8dbe2020-12-04 11:00:03 -05002162 void visitSampler(const Type&, const String& name) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002163 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002164 fCodeGen->writeName(name);
2165 }
John Stilesfdb8dbe2020-12-04 11:00:03 -05002166 void visitVariable(const Variable& var, const Expression* value) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002167 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002168 if (value) {
2169 fCodeGen->writeVarInitializer(var, *value);
2170 } else {
2171 fCodeGen->write("{}");
2172 }
2173 }
John Stiles83f3b8d2020-12-07 17:52:25 -05002174 void addElement() {
John Stilescdcdb042020-07-06 09:03:51 -04002175 if (fFirst) {
John Stilesf7410bd2021-01-19 13:07:55 -05002176 fCodeGen->write(" Globals _globals{");
John Stilescdcdb042020-07-06 09:03:51 -04002177 fFirst = false;
2178 } else {
2179 fCodeGen->write(", ");
2180 }
2181 }
John Stiles83f3b8d2020-12-07 17:52:25 -05002182 void finish() {
John Stilescdcdb042020-07-06 09:03:51 -04002183 if (!fFirst) {
2184 fCodeGen->writeLine("};");
John Stiles37279172021-01-21 22:24:28 -05002185 fCodeGen->writeLine(" (void)_globals;");
John Stilescdcdb042020-07-06 09:03:51 -04002186 }
2187 }
2188 MetalCodeGenerator* fCodeGen = nullptr;
2189 bool fFirst = true;
2190 } visitor;
2191
2192 visitor.fCodeGen = this;
2193 this->visitGlobalStruct(&visitor);
John Stiles83f3b8d2020-12-07 17:52:25 -05002194 visitor.finish();
Timothy Liangee84fe12018-05-18 14:38:19 -04002195}
2196
Ethan Nicholascc305772017-10-13 16:17:45 -04002197void MetalCodeGenerator::writeProgramElement(const ProgramElement& e) {
Ethan Nicholase6592142020-09-08 10:22:09 -04002198 switch (e.kind()) {
2199 case ProgramElement::Kind::kExtension:
Ethan Nicholascc305772017-10-13 16:17:45 -04002200 break;
Brian Osmanc0213602020-10-06 14:43:32 -04002201 case ProgramElement::Kind::kGlobalVar: {
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04002202 const GlobalVarDeclaration& global = e.as<GlobalVarDeclaration>();
2203 const VarDeclaration& decl = global.declaration()->as<VarDeclaration>();
2204 int builtin = decl.var().modifiers().fLayout.fBuiltin;
Brian Osmanc0213602020-10-06 14:43:32 -04002205 if (-1 == builtin) {
2206 // normal var
2207 this->writeVarDeclaration(decl, true);
John Stilese8b5a732021-03-12 13:25:52 -05002208 this->finishLine();
Brian Osmanc0213602020-10-06 14:43:32 -04002209 } else if (SK_FRAGCOLOR_BUILTIN == builtin) {
2210 // ignore
Ethan Nicholascc305772017-10-13 16:17:45 -04002211 }
2212 break;
2213 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002214 case ProgramElement::Kind::kInterfaceBlock:
Timothy Liang7d637782018-06-05 09:58:07 -04002215 // handled in writeInterfaceBlocks, do nothing
Ethan Nicholascc305772017-10-13 16:17:45 -04002216 break;
John Stilesdc75a972020-11-25 16:24:55 -05002217 case ProgramElement::Kind::kStructDefinition:
2218 // Handled in writeStructDefinitions. Do nothing.
2219 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04002220 case ProgramElement::Kind::kFunction:
John Stiles3dc0da62020-08-19 17:48:31 -04002221 this->writeFunction(e.as<FunctionDefinition>());
Ethan Nicholascc305772017-10-13 16:17:45 -04002222 break;
John Stiles569249b2020-11-03 12:18:22 -05002223 case ProgramElement::Kind::kFunctionPrototype:
2224 this->writeFunctionPrototype(e.as<FunctionPrototype>());
2225 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04002226 case ProgramElement::Kind::kModifiers:
John Stiles06b84ef2020-12-09 12:35:48 -05002227 this->writeModifiers(e.as<ModifiersDeclaration>().modifiers(),
2228 /*globalContext=*/true);
Ethan Nicholascc305772017-10-13 16:17:45 -04002229 this->writeLine(";");
2230 break;
John Stiles712fd6b2020-11-25 22:25:43 -05002231 case ProgramElement::Kind::kEnum:
2232 break;
Ethan Nicholascc305772017-10-13 16:17:45 -04002233 default:
John Stileseada7bc2021-02-02 16:29:32 -05002234 SkDEBUGFAILF("unsupported program element: %s\n", e.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -05002235 break;
Ethan Nicholascc305772017-10-13 16:17:45 -04002236 }
2237}
2238
Ethan Nicholasff350cb2020-05-14 14:05:13 -04002239MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const Expression* e) {
2240 if (!e) {
2241 return kNo_Requirements;
2242 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002243 switch (e->kind()) {
2244 case Expression::Kind::kFunctionCall: {
John Stiles3dc0da62020-08-19 17:48:31 -04002245 const FunctionCall& f = e->as<FunctionCall>();
Ethan Nicholas0dec9922020-10-05 15:51:52 -04002246 Requirements result = this->requirements(f.function());
2247 for (const auto& arg : f.arguments()) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04002248 result |= this->requirements(arg.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002249 }
2250 return result;
2251 }
John Stiles7384b372021-04-01 13:48:15 -04002252 case Expression::Kind::kConstructor:
2253 case Expression::Kind::kConstructorArray:
John Stiles2938eea2021-04-01 18:58:25 -04002254 case Expression::Kind::kConstructorDiagonalMatrix:
John Stilesfd7252f2021-04-04 22:24:40 -04002255 case Expression::Kind::kConstructorScalarCast:
John Stilesb14a8192021-04-05 11:40:46 -04002256 case Expression::Kind::kConstructorSplat:
2257 case Expression::Kind::kConstructorVectorCast: {
John Stiles7384b372021-04-01 13:48:15 -04002258 const AnyConstructor& c = e->asAnyConstructor();
Ethan Nicholascc305772017-10-13 16:17:45 -04002259 Requirements result = kNo_Requirements;
John Stilesd8eb8752021-04-01 11:49:10 -04002260 for (const auto& arg : c.argumentSpan()) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04002261 result |= this->requirements(arg.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002262 }
2263 return result;
2264 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002265 case Expression::Kind::kFieldAccess: {
John Stiles3dc0da62020-08-19 17:48:31 -04002266 const FieldAccess& f = e->as<FieldAccess>();
Ethan Nicholas7a95b202020-10-09 11:55:40 -04002267 if (FieldAccess::OwnerKind::kAnonymousInterfaceBlock == f.ownerKind()) {
Timothy Liang7d637782018-06-05 09:58:07 -04002268 return kGlobals_Requirement;
2269 }
Ethan Nicholas7a95b202020-10-09 11:55:40 -04002270 return this->requirements(f.base().get());
Timothy Liang7d637782018-06-05 09:58:07 -04002271 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002272 case Expression::Kind::kSwizzle:
Ethan Nicholas6b4d5812020-10-12 16:11:51 -04002273 return this->requirements(e->as<Swizzle>().base().get());
Ethan Nicholase6592142020-09-08 10:22:09 -04002274 case Expression::Kind::kBinary: {
2275 const BinaryExpression& bin = e->as<BinaryExpression>();
John Stiles2d4f9592020-10-30 10:29:12 -04002276 return this->requirements(bin.left().get()) |
2277 this->requirements(bin.right().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002278 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002279 case Expression::Kind::kIndex: {
John Stiles3dc0da62020-08-19 17:48:31 -04002280 const IndexExpression& idx = e->as<IndexExpression>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04002281 return this->requirements(idx.base().get()) | this->requirements(idx.index().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002282 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002283 case Expression::Kind::kPrefix:
Ethan Nicholas444ccc62020-10-09 10:16:22 -04002284 return this->requirements(e->as<PrefixExpression>().operand().get());
Ethan Nicholase6592142020-09-08 10:22:09 -04002285 case Expression::Kind::kPostfix:
Ethan Nicholas444ccc62020-10-09 10:16:22 -04002286 return this->requirements(e->as<PostfixExpression>().operand().get());
Ethan Nicholase6592142020-09-08 10:22:09 -04002287 case Expression::Kind::kTernary: {
John Stiles3dc0da62020-08-19 17:48:31 -04002288 const TernaryExpression& t = e->as<TernaryExpression>();
Ethan Nicholasdd218162020-10-08 05:48:01 -04002289 return this->requirements(t.test().get()) | this->requirements(t.ifTrue().get()) |
2290 this->requirements(t.ifFalse().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002291 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002292 case Expression::Kind::kVariableReference: {
John Stiles3dc0da62020-08-19 17:48:31 -04002293 const VariableReference& v = e->as<VariableReference>();
Ethan Nicholas78686922020-10-08 06:46:27 -04002294 const Modifiers& modifiers = v.variable()->modifiers();
Ethan Nicholascc305772017-10-13 16:17:45 -04002295 Requirements result = kNo_Requirements;
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002296 if (modifiers.fLayout.fBuiltin == SK_FRAGCOORD_BUILTIN) {
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -04002297 result = kGlobals_Requirement | kFragCoord_Requirement;
Ethan Nicholas453f67f2020-10-09 10:43:45 -04002298 } else if (Variable::Storage::kGlobal == v.variable()->storage()) {
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002299 if (modifiers.fFlags & Modifiers::kIn_Flag) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002300 result = kInputs_Requirement;
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002301 } else if (modifiers.fFlags & Modifiers::kOut_Flag) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002302 result = kOutputs_Requirement;
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002303 } else if (modifiers.fFlags & Modifiers::kUniform_Flag &&
Ethan Nicholas78686922020-10-08 06:46:27 -04002304 v.variable()->type().typeKind() != Type::TypeKind::kSampler) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002305 result = kUniforms_Requirement;
Timothy Liangee84fe12018-05-18 14:38:19 -04002306 } else {
2307 result = kGlobals_Requirement;
Ethan Nicholascc305772017-10-13 16:17:45 -04002308 }
2309 }
2310 return result;
2311 }
2312 default:
2313 return kNo_Requirements;
2314 }
2315}
2316
Ethan Nicholasff350cb2020-05-14 14:05:13 -04002317MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const Statement* s) {
2318 if (!s) {
2319 return kNo_Requirements;
2320 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002321 switch (s->kind()) {
2322 case Statement::Kind::kBlock: {
Ethan Nicholascc305772017-10-13 16:17:45 -04002323 Requirements result = kNo_Requirements;
Ethan Nicholas7bd60432020-09-25 14:31:59 -04002324 for (const std::unique_ptr<Statement>& child : s->as<Block>().children()) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04002325 result |= this->requirements(child.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002326 }
2327 return result;
2328 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002329 case Statement::Kind::kVarDeclaration: {
John Stiles3dc0da62020-08-19 17:48:31 -04002330 const VarDeclaration& var = s->as<VarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04002331 return this->requirements(var.value().get());
Timothy Liang7d637782018-06-05 09:58:07 -04002332 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002333 case Statement::Kind::kExpression:
Ethan Nicholasd503a5a2020-09-30 09:29:55 -04002334 return this->requirements(s->as<ExpressionStatement>().expression().get());
Ethan Nicholase6592142020-09-08 10:22:09 -04002335 case Statement::Kind::kReturn: {
John Stiles3dc0da62020-08-19 17:48:31 -04002336 const ReturnStatement& r = s->as<ReturnStatement>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04002337 return this->requirements(r.expression().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002338 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002339 case Statement::Kind::kIf: {
John Stiles3dc0da62020-08-19 17:48:31 -04002340 const IfStatement& i = s->as<IfStatement>();
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04002341 return this->requirements(i.test().get()) |
2342 this->requirements(i.ifTrue().get()) |
2343 this->requirements(i.ifFalse().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002344 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002345 case Statement::Kind::kFor: {
John Stiles3dc0da62020-08-19 17:48:31 -04002346 const ForStatement& f = s->as<ForStatement>();
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04002347 return this->requirements(f.initializer().get()) |
2348 this->requirements(f.test().get()) |
2349 this->requirements(f.next().get()) |
2350 this->requirements(f.statement().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002351 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002352 case Statement::Kind::kDo: {
John Stiles3dc0da62020-08-19 17:48:31 -04002353 const DoStatement& d = s->as<DoStatement>();
Ethan Nicholas1fd61162020-09-28 13:14:19 -04002354 return this->requirements(d.test().get()) |
2355 this->requirements(d.statement().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002356 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002357 case Statement::Kind::kSwitch: {
John Stiles3dc0da62020-08-19 17:48:31 -04002358 const SwitchStatement& sw = s->as<SwitchStatement>();
Ethan Nicholas01b05e52020-10-22 15:53:41 -04002359 Requirements result = this->requirements(sw.value().get());
John Stilesb23a64b2021-03-11 08:27:59 -05002360 for (const std::unique_ptr<Statement>& sc : sw.cases()) {
2361 result |= this->requirements(sc->as<SwitchCase>().statement().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002362 }
2363 return result;
2364 }
2365 default:
2366 return kNo_Requirements;
2367 }
2368}
2369
2370MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const FunctionDeclaration& f) {
Ethan Nicholased84b732020-10-08 11:45:44 -04002371 if (f.isBuiltin()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002372 return kNo_Requirements;
2373 }
2374 auto found = fRequirements.find(&f);
2375 if (found == fRequirements.end()) {
Ethan Nicholas65a8f562019-04-19 14:00:26 -04002376 fRequirements[&f] = kNo_Requirements;
Brian Osman133724c2020-10-28 14:14:39 -04002377 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04002378 if (e->is<FunctionDefinition>()) {
2379 const FunctionDefinition& def = e->as<FunctionDefinition>();
Ethan Nicholas0a5d0962020-10-14 13:33:18 -04002380 if (&def.declaration() == &f) {
2381 Requirements reqs = this->requirements(def.body().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002382 fRequirements[&f] = reqs;
2383 return reqs;
2384 }
2385 }
2386 }
John Stiles569249b2020-11-03 12:18:22 -05002387 // We never found a definition for this declared function, but it's legal to prototype a
2388 // function without ever giving a definition, as long as you don't call it.
2389 return kNo_Requirements;
Ethan Nicholascc305772017-10-13 16:17:45 -04002390 }
2391 return found->second;
2392}
2393
Timothy Liangb8eeb802018-07-23 16:46:16 -04002394bool MetalCodeGenerator::generateCode() {
John Stiles44532372020-12-07 12:33:55 -05002395 StringStream header;
2396 {
2397 AutoOutputStream outputToHeader(this, &header, &fIndentation);
Michael Ludwigbf58add2021-03-16 10:40:11 -04002398 this->writeHeader();
John Stiles44532372020-12-07 12:33:55 -05002399 this->writeStructDefinitions();
2400 this->writeUniformStruct();
2401 this->writeInputStruct();
2402 this->writeOutputStruct();
2403 this->writeInterfaceBlocks();
2404 this->writeGlobalStruct();
2405 }
2406 StringStream body;
2407 {
2408 AutoOutputStream outputToBody(this, &body, &fIndentation);
2409 for (const ProgramElement* e : fProgram.elements()) {
2410 this->writeProgramElement(*e);
2411 }
2412 }
2413 write_stringstream(header, *fOut);
2414 write_stringstream(fExtraFunctions, *fOut);
2415 write_stringstream(body, *fOut);
Brian Osman8609a242020-09-08 14:01:49 -04002416 return 0 == fErrors.errorCount();
Ethan Nicholascc305772017-10-13 16:17:45 -04002417}
2418
John Stilesa6841be2020-08-06 14:11:56 -04002419} // namespace SkSL