blob: 4b54a4f5d148a25b4bd0b8ef0c75a405e65403e8 [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"
John Stiles268a73f2021-04-07 12:30:22 -040014#include "src/sksl/ir/SkSLConstructorCompositeCast.h"
John Stiles7384b372021-04-01 13:48:15 -040015#include "src/sksl/ir/SkSLConstructorDiagonalMatrix.h"
John Stiles5abb9e12021-04-06 13:47:19 -040016#include "src/sksl/ir/SkSLConstructorMatrixResize.h"
John Stiles2938eea2021-04-01 18:58:25 -040017#include "src/sksl/ir/SkSLConstructorSplat.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050018#include "src/sksl/ir/SkSLExpressionStatement.h"
19#include "src/sksl/ir/SkSLExtension.h"
20#include "src/sksl/ir/SkSLIndexExpression.h"
21#include "src/sksl/ir/SkSLModifiersDeclaration.h"
22#include "src/sksl/ir/SkSLNop.h"
John Stilesdc75a972020-11-25 16:24:55 -050023#include "src/sksl/ir/SkSLStructDefinition.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050024#include "src/sksl/ir/SkSLVariableReference.h"
Ethan Nicholascc305772017-10-13 16:17:45 -040025
Brian Osmanc262a122020-08-06 16:34:34 -040026#include <algorithm>
27
Ethan Nicholascc305772017-10-13 16:17:45 -040028namespace SkSL {
29
John Stiles45990502021-02-16 10:55:27 -050030const char* MetalCodeGenerator::OperatorName(Operator op) {
31 switch (op.kind()) {
John Stilesd6449e92020-11-30 09:13:23 -050032 case Token::Kind::TK_LOGICALXOR: return "!=";
John Stiles45990502021-02-16 10:55:27 -050033 default: return op.operatorName();
John Stilesd6449e92020-11-30 09:13:23 -050034 }
35}
36
John Stilescdcdb042020-07-06 09:03:51 -040037class MetalCodeGenerator::GlobalStructVisitor {
38public:
39 virtual ~GlobalStructVisitor() = default;
John Stilesfdb8dbe2020-12-04 11:00:03 -050040 virtual void visitInterfaceBlock(const InterfaceBlock& block, const String& blockName) = 0;
41 virtual void visitTexture(const Type& type, const String& name) = 0;
42 virtual void visitSampler(const Type& type, const String& name) = 0;
43 virtual void visitVariable(const Variable& var, const Expression* value) = 0;
John Stilescdcdb042020-07-06 09:03:51 -040044};
45
Timothy Liangee84fe12018-05-18 14:38:19 -040046void MetalCodeGenerator::setupIntrinsics() {
John Stilesd7199b22020-12-30 16:22:58 -050047 fIntrinsicMap[String("atan")] = kAtan_IntrinsicKind;
48 fIntrinsicMap[String("floatBitsToInt")] = kBitcast_IntrinsicKind;
49 fIntrinsicMap[String("floatBitsToUint")] = kBitcast_IntrinsicKind;
50 fIntrinsicMap[String("intBitsToFloat")] = kBitcast_IntrinsicKind;
51 fIntrinsicMap[String("uintBitsToFloat")] = kBitcast_IntrinsicKind;
52 fIntrinsicMap[String("equal")] = kCompareEqual_IntrinsicKind;
53 fIntrinsicMap[String("notEqual")] = kCompareNotEqual_IntrinsicKind;
54 fIntrinsicMap[String("lessThan")] = kCompareLessThan_IntrinsicKind;
55 fIntrinsicMap[String("lessThanEqual")] = kCompareLessThanEqual_IntrinsicKind;
56 fIntrinsicMap[String("greaterThan")] = kCompareGreaterThan_IntrinsicKind;
57 fIntrinsicMap[String("greaterThanEqual")] = kCompareGreaterThanEqual_IntrinsicKind;
58 fIntrinsicMap[String("degrees")] = kDegrees_IntrinsicKind;
59 fIntrinsicMap[String("dFdx")] = kDFdx_IntrinsicKind;
60 fIntrinsicMap[String("dFdy")] = kDFdy_IntrinsicKind;
61 fIntrinsicMap[String("distance")] = kDistance_IntrinsicKind;
62 fIntrinsicMap[String("dot")] = kDot_IntrinsicKind;
63 fIntrinsicMap[String("faceforward")] = kFaceforward_IntrinsicKind;
64 fIntrinsicMap[String("bitCount")] = kBitCount_IntrinsicKind;
65 fIntrinsicMap[String("findLSB")] = kFindLSB_IntrinsicKind;
66 fIntrinsicMap[String("findMSB")] = kFindMSB_IntrinsicKind;
67 fIntrinsicMap[String("inverse")] = kInverse_IntrinsicKind;
68 fIntrinsicMap[String("inversesqrt")] = kInversesqrt_IntrinsicKind;
69 fIntrinsicMap[String("length")] = kLength_IntrinsicKind;
70 fIntrinsicMap[String("matrixCompMult")] = kMatrixCompMult_IntrinsicKind;
71 fIntrinsicMap[String("mod")] = kMod_IntrinsicKind;
72 fIntrinsicMap[String("normalize")] = kNormalize_IntrinsicKind;
73 fIntrinsicMap[String("radians")] = kRadians_IntrinsicKind;
74 fIntrinsicMap[String("reflect")] = kReflect_IntrinsicKind;
75 fIntrinsicMap[String("refract")] = kRefract_IntrinsicKind;
John Stiles23456532020-12-30 18:12:48 -050076 fIntrinsicMap[String("roundEven")] = kRoundEven_IntrinsicKind;
John Stilesd7199b22020-12-30 16:22:58 -050077 fIntrinsicMap[String("sample")] = kTexture_IntrinsicKind;
Timothy Liangee84fe12018-05-18 14:38:19 -040078}
79
Ethan Nicholascc305772017-10-13 16:17:45 -040080void MetalCodeGenerator::write(const char* s) {
81 if (!s[0]) {
82 return;
83 }
84 if (fAtLineStart) {
85 for (int i = 0; i < fIndentation; i++) {
86 fOut->writeText(" ");
87 }
88 }
89 fOut->writeText(s);
90 fAtLineStart = false;
91}
92
93void MetalCodeGenerator::writeLine(const char* s) {
94 this->write(s);
John Stilese8b5a732021-03-12 13:25:52 -050095 this->writeLine();
Ethan Nicholascc305772017-10-13 16:17:45 -040096}
97
98void MetalCodeGenerator::write(const String& s) {
99 this->write(s.c_str());
100}
101
102void MetalCodeGenerator::writeLine(const String& s) {
103 this->writeLine(s.c_str());
104}
105
106void MetalCodeGenerator::writeLine() {
John Stilese8b5a732021-03-12 13:25:52 -0500107 fOut->writeText(fLineEnding);
108 fAtLineStart = true;
109}
110
111void MetalCodeGenerator::finishLine() {
112 if (!fAtLineStart) {
113 this->writeLine();
114 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400115}
116
117void MetalCodeGenerator::writeExtension(const Extension& ext) {
Ethan Nicholasefb09e22020-09-30 10:17:00 -0400118 this->writeLine("#extension " + ext.name() + " : enable");
Ethan Nicholascc305772017-10-13 16:17:45 -0400119}
120
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500121String MetalCodeGenerator::typeName(const Type& type) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400122 switch (type.typeKind()) {
John Stilesb4418502021-02-04 10:57:08 -0500123 case Type::TypeKind::kArray:
124 SkASSERTF(type.columns() > 0, "invalid array size: %s", type.description().c_str());
125 return String::printf("array<%s, %d>",
126 this->typeName(type.componentType()).c_str(), type.columns());
127
Ethan Nicholase6592142020-09-08 10:22:09 -0400128 case Type::TypeKind::kVector:
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500129 return this->typeName(type.componentType()) + to_string(type.columns());
John Stilesb4418502021-02-04 10:57:08 -0500130
Ethan Nicholase6592142020-09-08 10:22:09 -0400131 case Type::TypeKind::kMatrix:
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500132 return this->typeName(type.componentType()) + to_string(type.columns()) + "x" +
133 to_string(type.rows());
John Stilesb4418502021-02-04 10:57:08 -0500134
Ethan Nicholase6592142020-09-08 10:22:09 -0400135 case Type::TypeKind::kSampler:
John Stiles368db7c2020-12-29 11:20:08 -0500136 return "texture2d<float>"; // FIXME - support other texture types
John Stilesb4418502021-02-04 10:57:08 -0500137
John Stilesfd41d872020-11-25 22:39:45 -0500138 case Type::TypeKind::kEnum:
139 return "int";
John Stilesb4418502021-02-04 10:57:08 -0500140
Ethan Nicholascc305772017-10-13 16:17:45 -0400141 default:
John Stiles54e7c052021-01-11 14:22:36 -0500142 if (type == *fContext.fTypes.fHalf) {
Timothy Liang43d225f2018-07-19 15:27:13 -0400143 // FIXME - Currently only supporting floats in MSL to avoid type coercion issues.
John Stiles54e7c052021-01-11 14:22:36 -0500144 return fContext.fTypes.fFloat->name();
145 } else if (type == *fContext.fTypes.fByte) {
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500146 return "char";
John Stiles54e7c052021-01-11 14:22:36 -0500147 } else if (type == *fContext.fTypes.fUByte) {
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500148 return "uchar";
Timothy Liang7d637782018-06-05 09:58:07 -0400149 } else {
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500150 return type.name();
Timothy Liang7d637782018-06-05 09:58:07 -0400151 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400152 }
153}
154
Brian Osman02bc5222021-01-28 11:00:20 -0500155void MetalCodeGenerator::writeStructDefinition(const StructDefinition& s) {
156 const Type& type = s.type();
John Stilesdc75a972020-11-25 16:24:55 -0500157 this->writeLine("struct " + type.name() + " {");
158 fIndentation++;
159 this->writeFields(type.fields(), type.fOffset);
160 fIndentation--;
Brian Osman02bc5222021-01-28 11:00:20 -0500161 this->writeLine("};");
John Stilesdc75a972020-11-25 16:24:55 -0500162}
163
John Stilesb4418502021-02-04 10:57:08 -0500164void MetalCodeGenerator::writeType(const Type& type) {
165 this->write(this->typeName(type));
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500166}
167
Ethan Nicholascc305772017-10-13 16:17:45 -0400168void MetalCodeGenerator::writeExpression(const Expression& expr, Precedence parentPrecedence) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400169 switch (expr.kind()) {
170 case Expression::Kind::kBinary:
John Stiles81365af2020-08-18 09:24:00 -0400171 this->writeBinaryExpression(expr.as<BinaryExpression>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400172 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400173 case Expression::Kind::kBoolLiteral:
John Stiles81365af2020-08-18 09:24:00 -0400174 this->writeBoolLiteral(expr.as<BoolLiteral>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400175 break;
John Stiles2bec8ab2021-04-06 18:40:04 -0400176 case Expression::Kind::kConstructorArray:
177 this->writeAnyConstructor(expr.asAnyConstructor(), "{", "}", parentPrecedence);
178 break;
179 case Expression::Kind::kConstructorComposite:
180 this->writeConstructorComposite(expr.as<ConstructorComposite>(), parentPrecedence);
181 break;
182 case Expression::Kind::kConstructorDiagonalMatrix:
183 case Expression::Kind::kConstructorSplat:
184 this->writeAnyConstructor(expr.asAnyConstructor(), "(", ")", parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400185 break;
John Stiles5abb9e12021-04-06 13:47:19 -0400186 case Expression::Kind::kConstructorMatrixResize:
187 this->writeConstructorMatrixResize(expr.as<ConstructorMatrixResize>(),
188 parentPrecedence);
189 break;
John Stilesfd7252f2021-04-04 22:24:40 -0400190 case Expression::Kind::kConstructorScalarCast:
John Stiles268a73f2021-04-07 12:30:22 -0400191 case Expression::Kind::kConstructorCompositeCast:
John Stilesb14a8192021-04-05 11:40:46 -0400192 this->writeCastConstructor(expr.asAnyConstructor(), "(", ")", parentPrecedence);
John Stiles2938eea2021-04-01 18:58:25 -0400193 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400194 case Expression::Kind::kIntLiteral:
John Stiles81365af2020-08-18 09:24:00 -0400195 this->writeIntLiteral(expr.as<IntLiteral>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400196 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400197 case Expression::Kind::kFieldAccess:
John Stiles81365af2020-08-18 09:24:00 -0400198 this->writeFieldAccess(expr.as<FieldAccess>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400199 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400200 case Expression::Kind::kFloatLiteral:
John Stiles81365af2020-08-18 09:24:00 -0400201 this->writeFloatLiteral(expr.as<FloatLiteral>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400202 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400203 case Expression::Kind::kFunctionCall:
John Stiles81365af2020-08-18 09:24:00 -0400204 this->writeFunctionCall(expr.as<FunctionCall>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400205 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400206 case Expression::Kind::kPrefix:
John Stiles81365af2020-08-18 09:24:00 -0400207 this->writePrefixExpression(expr.as<PrefixExpression>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400208 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400209 case Expression::Kind::kPostfix:
John Stiles81365af2020-08-18 09:24:00 -0400210 this->writePostfixExpression(expr.as<PostfixExpression>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400211 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400212 case Expression::Kind::kSetting:
John Stiles81365af2020-08-18 09:24:00 -0400213 this->writeSetting(expr.as<Setting>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400214 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400215 case Expression::Kind::kSwizzle:
John Stiles81365af2020-08-18 09:24:00 -0400216 this->writeSwizzle(expr.as<Swizzle>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400217 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400218 case Expression::Kind::kVariableReference:
John Stiles81365af2020-08-18 09:24:00 -0400219 this->writeVariableReference(expr.as<VariableReference>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400220 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400221 case Expression::Kind::kTernary:
John Stiles81365af2020-08-18 09:24:00 -0400222 this->writeTernaryExpression(expr.as<TernaryExpression>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400223 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400224 case Expression::Kind::kIndex:
John Stiles81365af2020-08-18 09:24:00 -0400225 this->writeIndexExpression(expr.as<IndexExpression>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400226 break;
227 default:
John Stileseada7bc2021-02-02 16:29:32 -0500228 SkDEBUGFAILF("unsupported expression: %s", expr.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -0500229 break;
Ethan Nicholascc305772017-10-13 16:17:45 -0400230 }
231}
232
John Stiles06b84ef2020-12-09 12:35:48 -0500233String MetalCodeGenerator::getOutParamHelper(const FunctionCall& call,
234 const ExpressionArray& arguments,
235 const SkTArray<VariableReference*>& outVars) {
236 AutoOutputStream outputToExtraFunctions(this, &fExtraFunctions, &fIndentation);
237 const FunctionDeclaration& function = call.function();
238
John Stilese1068342021-03-22 11:57:41 -0400239 String name = "_skOutParamHelper" + to_string(fSwizzleHelperCount++) +
240 "_" + function.mangledName();
John Stiles06b84ef2020-12-09 12:35:48 -0500241 const char* separator = "";
242
243 // Emit a prototype for the function we'll be calling through to in our helper.
244 if (!function.isBuiltin()) {
245 this->writeFunctionDeclaration(function);
246 this->writeLine(";");
247 }
248
249 // Synthesize a helper function that takes the same inputs as `function`, except in places where
250 // `outVars` is non-null; in those places, we take the type of the VariableReference.
251 //
252 // float _skOutParamHelper0_originalFuncName(float _var0, float _var1, float& outParam) {
John Stilesb4418502021-02-04 10:57:08 -0500253 this->writeType(call.type());
John Stiles06b84ef2020-12-09 12:35:48 -0500254 this->write(" ");
255 this->write(name);
256 this->write("(");
257 this->writeFunctionRequirementParams(function, separator);
258
259 SkASSERT(outVars.size() == arguments.size());
260 SkASSERT(outVars.size() == function.parameters().size());
261
John Stiles73e2c892021-02-13 13:58:01 -0500262 // We need to detect cases where the caller passes the same variable as an out-param more than
263 // once, and avoid reusing the variable name. (In those cases we can actually just ignore the
264 // redundant input parameter entirely, and not give it any name.)
265 std::unordered_set<const Variable*> writtenVars;
266
John Stiles06b84ef2020-12-09 12:35:48 -0500267 for (int index = 0; index < arguments.count(); ++index) {
268 this->write(separator);
269 separator = ", ";
270
271 const Variable* param = function.parameters()[index];
272 this->writeModifiers(param->modifiers(), /*globalContext=*/false);
273
274 const Type* type = outVars[index] ? &outVars[index]->type() : &arguments[index]->type();
John Stilesb4418502021-02-04 10:57:08 -0500275 this->writeType(*type);
John Stiles06b84ef2020-12-09 12:35:48 -0500276
277 if (param->modifiers().fFlags & Modifiers::kOut_Flag) {
278 this->write("&");
279 }
280 if (outVars[index]) {
John Stiles73e2c892021-02-13 13:58:01 -0500281 auto [iter, didInsert] = writtenVars.insert(outVars[index]->variable());
282 if (didInsert) {
283 this->write(" ");
284 fIgnoreVariableReferenceModifiers = true;
285 this->writeVariableReference(*outVars[index]);
286 fIgnoreVariableReferenceModifiers = false;
287 }
John Stiles06b84ef2020-12-09 12:35:48 -0500288 } else {
289 this->write(" _var");
290 this->write(to_string(index));
291 }
John Stiles06b84ef2020-12-09 12:35:48 -0500292 }
293 this->writeLine(") {");
294
295 ++fIndentation;
296 for (int index = 0; index < outVars.count(); ++index) {
297 if (!outVars[index]) {
298 continue;
299 }
300 // float3 _var2[ = outParam.zyx];
John Stilesb4418502021-02-04 10:57:08 -0500301 this->writeType(arguments[index]->type());
John Stiles06b84ef2020-12-09 12:35:48 -0500302 this->write(" _var");
303 this->write(to_string(index));
304
305 const Variable* param = function.parameters()[index];
306 if (param->modifiers().fFlags & Modifiers::kIn_Flag) {
307 this->write(" = ");
308 fIgnoreVariableReferenceModifiers = true;
Brian Osman00185012021-02-04 16:07:11 -0500309 this->writeExpression(*arguments[index], Precedence::kAssignment);
John Stiles06b84ef2020-12-09 12:35:48 -0500310 fIgnoreVariableReferenceModifiers = false;
311 }
312
313 this->writeLine(";");
314 }
315
John Stilesf7410bd2021-01-19 13:07:55 -0500316 // [int _skResult = ] myFunction(inputs, outputs, _globals, _var0, _var1, _var2, _var3);
John Stiles06b84ef2020-12-09 12:35:48 -0500317 bool hasResult = (call.type().name() != "void");
318 if (hasResult) {
John Stilesb4418502021-02-04 10:57:08 -0500319 this->writeType(call.type());
John Stiles06b84ef2020-12-09 12:35:48 -0500320 this->write(" _skResult = ");
321 }
322
John Stilese1068342021-03-22 11:57:41 -0400323 this->writeName(function.mangledName());
John Stiles06b84ef2020-12-09 12:35:48 -0500324 this->write("(");
325 separator = "";
326 this->writeFunctionRequirementArgs(function, separator);
327
328 for (int index = 0; index < arguments.count(); ++index) {
329 this->write(separator);
330 separator = ", ";
331
332 this->write("_var");
333 this->write(to_string(index));
334 }
335 this->writeLine(");");
336
337 for (int index = 0; index < outVars.count(); ++index) {
338 if (!outVars[index]) {
339 continue;
340 }
341 // outParam.zyx = _var2;
342 fIgnoreVariableReferenceModifiers = true;
Brian Osman00185012021-02-04 16:07:11 -0500343 this->writeExpression(*arguments[index], Precedence::kAssignment);
John Stiles06b84ef2020-12-09 12:35:48 -0500344 fIgnoreVariableReferenceModifiers = false;
345 this->write(" = _var");
346 this->write(to_string(index));
347 this->writeLine(";");
348 }
349
350 if (hasResult) {
351 this->writeLine("return _skResult;");
352 }
353
354 --fIndentation;
355 this->writeLine("}");
356
357 return name;
John Stilesb21fac22020-12-04 15:36:49 -0500358}
359
John Stilesf64e4072020-12-10 10:34:27 -0500360String MetalCodeGenerator::getBitcastIntrinsic(const Type& outType) {
361 return "as_type<" + outType.displayName() + ">";
362}
363
Ethan Nicholascc305772017-10-13 16:17:45 -0400364void MetalCodeGenerator::writeFunctionCall(const FunctionCall& c) {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400365 const FunctionDeclaration& function = c.function();
John Stiles89ac7c22020-12-30 17:47:31 -0500366 // If this function is a built-in with no declaration, it's probably an intrinsic and might need
367 // special handling.
368 if (function.isBuiltin() && !function.definition()) {
369 auto iter = fIntrinsicMap.find(function.name());
370 if (iter != fIntrinsicMap.end()) {
371 this->writeIntrinsicCall(c, iter->second);
372 return;
373 }
Timothy Liang6403b0e2018-05-17 10:40:04 -0400374 }
John Stilesb21fac22020-12-04 15:36:49 -0500375
John Stilesd7199b22020-12-30 16:22:58 -0500376 // Determine whether or not we need to emulate GLSL's out-param semantics for Metal using a
377 // helper function. (Specifically, out-parameters in GLSL are only written back to the original
378 // variable at the end of the function call; also, swizzles are supported, whereas Metal doesn't
379 // allow a swizzle to be passed to a `floatN&`.)
380 const ExpressionArray& arguments = c.arguments();
John Stilesb21fac22020-12-04 15:36:49 -0500381 const std::vector<const Variable*>& parameters = function.parameters();
382 SkASSERT(arguments.size() == parameters.size());
John Stiles06b84ef2020-12-09 12:35:48 -0500383
384 bool foundOutParam = false;
385 SkSTArray<16, VariableReference*> outVars;
John Stilesf64e4072020-12-10 10:34:27 -0500386 outVars.push_back_n(arguments.count(), (VariableReference*)nullptr);
John Stiles06b84ef2020-12-09 12:35:48 -0500387
388 for (int index = 0; index < arguments.count(); ++index) {
John Stilesb21fac22020-12-04 15:36:49 -0500389 // If this is an out parameter...
390 if (parameters[index]->modifiers().fFlags & Modifiers::kOut_Flag) {
John Stiles06b84ef2020-12-09 12:35:48 -0500391 // Find the expression's inner variable being written to.
John Stilesb21fac22020-12-04 15:36:49 -0500392 Analysis::AssignmentInfo info;
John Stiles06b84ef2020-12-09 12:35:48 -0500393 // Assignability was verified at IRGeneration time, so this should always succeed.
394 SkAssertResult(Analysis::IsAssignable(*arguments[index], &info));
395 outVars[index] = info.fAssignedVar;
396 foundOutParam = true;
John Stilesb21fac22020-12-04 15:36:49 -0500397 }
398 }
399
John Stiles06b84ef2020-12-09 12:35:48 -0500400 if (foundOutParam) {
401 // Out parameters need to be written back to at the end of the function. To do this, we
402 // synthesize a helper function which evaluates the out-param expression into a temporary
403 // variable, calls the original function, then writes the temp var back into the out param
404 // using the original out-param expression. (This lets us support things like swizzles and
405 // array indices.)
John Stilesd7199b22020-12-30 16:22:58 -0500406 this->write(getOutParamHelper(c, arguments, outVars));
407 } else {
John Stilese1068342021-03-22 11:57:41 -0400408 this->write(function.mangledName());
John Stiles06b84ef2020-12-09 12:35:48 -0500409 }
410
Ethan Nicholascc305772017-10-13 16:17:45 -0400411 this->write("(");
412 const char* separator = "";
John Stiles06b84ef2020-12-09 12:35:48 -0500413 this->writeFunctionRequirementArgs(function, separator);
414 for (int i = 0; i < arguments.count(); ++i) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400415 this->write(separator);
416 separator = ", ";
John Stiles06b84ef2020-12-09 12:35:48 -0500417
418 if (outVars[i]) {
Brian Osman00185012021-02-04 16:07:11 -0500419 this->writeExpression(*outVars[i], Precedence::kSequence);
John Stiles06b84ef2020-12-09 12:35:48 -0500420 } else {
Brian Osman00185012021-02-04 16:07:11 -0500421 this->writeExpression(*arguments[i], Precedence::kSequence);
John Stiles06b84ef2020-12-09 12:35:48 -0500422 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400423 }
424 this->write(")");
425}
426
Brian Osman964f0a02020-12-29 10:15:22 -0500427static constexpr char kInverse2x2[] = R"(
428float2x2 float2x2_inverse(float2x2 m) {
429 return float2x2(m[1][1], -m[0][1], -m[1][0], m[0][0]) * (1/determinant(m));
430}
431)";
432
433static constexpr char kInverse3x3[] = R"(
434float3x3 float3x3_inverse(float3x3 m) {
435 float a00 = m[0][0], a01 = m[0][1], a02 = m[0][2];
436 float a10 = m[1][0], a11 = m[1][1], a12 = m[1][2];
437 float a20 = m[2][0], a21 = m[2][1], a22 = m[2][2];
438 float b01 = a22*a11 - a12*a21;
439 float b11 = -a22*a10 + a12*a20;
440 float b21 = a21*a10 - a11*a20;
441 float det = a00*b01 + a01*b11 + a02*b21;
442 return float3x3(b01, (-a22*a01 + a02*a21), ( a12*a01 - a02*a11),
443 b11, ( a22*a00 - a02*a20), (-a12*a00 + a02*a10),
444 b21, (-a21*a00 + a01*a20), ( a11*a00 - a01*a10)) * (1/det);
445}
446)";
447
448static constexpr char kInverse4x4[] = R"(
449float4x4 float4x4_inverse(float4x4 m) {
450 float a00 = m[0][0], a01 = m[0][1], a02 = m[0][2], a03 = m[0][3];
451 float a10 = m[1][0], a11 = m[1][1], a12 = m[1][2], a13 = m[1][3];
452 float a20 = m[2][0], a21 = m[2][1], a22 = m[2][2], a23 = m[2][3];
453 float a30 = m[3][0], a31 = m[3][1], a32 = m[3][2], a33 = m[3][3];
454 float b00 = a00*a11 - a01*a10;
455 float b01 = a00*a12 - a02*a10;
456 float b02 = a00*a13 - a03*a10;
457 float b03 = a01*a12 - a02*a11;
458 float b04 = a01*a13 - a03*a11;
459 float b05 = a02*a13 - a03*a12;
460 float b06 = a20*a31 - a21*a30;
461 float b07 = a20*a32 - a22*a30;
462 float b08 = a20*a33 - a23*a30;
463 float b09 = a21*a32 - a22*a31;
464 float b10 = a21*a33 - a23*a31;
465 float b11 = a22*a33 - a23*a32;
466 float det = b00*b11 - b01*b10 + b02*b09 + b03*b08 - b04*b07 + b05*b06;
467 return float4x4(a11*b11 - a12*b10 + a13*b09,
468 a02*b10 - a01*b11 - a03*b09,
469 a31*b05 - a32*b04 + a33*b03,
470 a22*b04 - a21*b05 - a23*b03,
471 a12*b08 - a10*b11 - a13*b07,
472 a00*b11 - a02*b08 + a03*b07,
473 a32*b02 - a30*b05 - a33*b01,
474 a20*b05 - a22*b02 + a23*b01,
475 a10*b10 - a11*b08 + a13*b06,
476 a01*b08 - a00*b10 - a03*b06,
477 a30*b04 - a31*b02 + a33*b00,
478 a21*b02 - a20*b04 - a23*b00,
479 a11*b07 - a10*b09 - a12*b06,
480 a00*b09 - a01*b07 + a02*b06,
481 a31*b01 - a30*b03 - a32*b00,
482 a20*b03 - a21*b01 + a22*b00) * (1/det);
483}
484)";
485
John Stilesd7199b22020-12-30 16:22:58 -0500486String MetalCodeGenerator::getInversePolyfill(const ExpressionArray& arguments) {
487 // Only use polyfills for a function taking a single-argument square matrix.
488 if (arguments.size() == 1) {
489 const Type& type = arguments.front()->type();
490 if (type.isMatrix() && type.rows() == type.columns()) {
491 // Inject the correct polyfill based on the matrix size.
492 String name = this->typeName(type) + "_inverse";
493 auto [iter, didInsert] = fWrittenIntrinsics.insert(name);
494 if (didInsert) {
495 switch (type.rows()) {
496 case 2:
497 fExtraFunctions.writeText(kInverse2x2);
498 break;
499 case 3:
500 fExtraFunctions.writeText(kInverse3x3);
501 break;
502 case 4:
503 fExtraFunctions.writeText(kInverse4x4);
504 break;
505 }
506 }
507 return name;
Chris Daltondba7aab2018-11-15 10:57:49 -0500508 }
509 }
John Stilesd7199b22020-12-30 16:22:58 -0500510 // This isn't the built-in `inverse`. We don't want to polyfill it at all.
511 return "inverse";
Chris Daltondba7aab2018-11-15 10:57:49 -0500512}
513
Brian Osman93aed9a2020-12-28 15:18:46 -0500514static constexpr char kMatrixCompMult[] = R"(
515template <int C, int R>
516matrix<float, C, R> matrixCompMult(matrix<float, C, R> a, matrix<float, C, R> b) {
517 matrix<float, C, R> result;
518 for (int c = 0; c < C; ++c) {
519 result[c] = a[c] * b[c];
520 }
521 return result;
522}
523)";
524
525void MetalCodeGenerator::writeMatrixCompMult() {
526 String name = "matrixCompMult";
527 if (fWrittenIntrinsics.find(name) == fWrittenIntrinsics.end()) {
528 fWrittenIntrinsics.insert(name);
529 fExtraFunctions.writeText(kMatrixCompMult);
530 }
531}
532
John Stiles86424eb2020-12-11 11:17:14 -0500533String MetalCodeGenerator::getTempVariable(const Type& type) {
534 String tempVar = "_skTemp" + to_string(fVarCount++);
535 this->fFunctionHeader += " " + this->typeName(type) + " " + tempVar + ";\n";
536 return tempVar;
537}
538
John Stiles791c27d2020-12-30 14:56:57 -0500539void MetalCodeGenerator::writeSimpleIntrinsic(const FunctionCall& c) {
540 // Write out an intrinsic function call exactly as-is. No muss no fuss.
541 this->write(c.function().name());
John Stilesd7199b22020-12-30 16:22:58 -0500542 this->writeArgumentList(c.arguments());
543}
544
545void MetalCodeGenerator::writeArgumentList(const ExpressionArray& arguments) {
John Stiles791c27d2020-12-30 14:56:57 -0500546 this->write("(");
547 const char* separator = "";
John Stilesd7199b22020-12-30 16:22:58 -0500548 for (const std::unique_ptr<Expression>& arg : arguments) {
John Stiles791c27d2020-12-30 14:56:57 -0500549 this->write(separator);
550 separator = ", ";
Brian Osman00185012021-02-04 16:07:11 -0500551 this->writeExpression(*arg, Precedence::kSequence);
John Stiles791c27d2020-12-30 14:56:57 -0500552 }
553 this->write(")");
554}
555
John Stilesd7199b22020-12-30 16:22:58 -0500556void MetalCodeGenerator::writeIntrinsicCall(const FunctionCall& c, IntrinsicKind kind) {
John Stiles8e3b6be2020-10-13 11:14:08 -0400557 const ExpressionArray& arguments = c.arguments();
Timothy Liang6403b0e2018-05-17 10:40:04 -0400558 switch (kind) {
John Stilesd7199b22020-12-30 16:22:58 -0500559 case kTexture_IntrinsicKind: {
Brian Osman00185012021-02-04 16:07:11 -0500560 this->writeExpression(*arguments[0], Precedence::kSequence);
Timothy Lianga06f2152018-05-24 15:33:31 -0400561 this->write(".sample(");
Brian Osman00185012021-02-04 16:07:11 -0500562 this->writeExpression(*arguments[0], Precedence::kSequence);
Timothy Lianga06f2152018-05-24 15:33:31 -0400563 this->write(SAMPLER_SUFFIX);
564 this->write(", ");
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400565 const Type& arg1Type = arguments[1]->type();
John Stilesb14a8192021-04-05 11:40:46 -0400566 if (arg1Type.columns() == 3) {
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500567 // have to store the vector in a temp variable to avoid double evaluating it
John Stiles86424eb2020-12-11 11:17:14 -0500568 String tmpVar = this->getTempVariable(arg1Type);
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500569 this->write("(" + tmpVar + " = ");
Brian Osman00185012021-02-04 16:07:11 -0500570 this->writeExpression(*arguments[1], Precedence::kSequence);
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500571 this->write(", " + tmpVar + ".xy / " + tmpVar + ".z))");
Timothy Liangee84fe12018-05-18 14:38:19 -0400572 } else {
John Stilesb14a8192021-04-05 11:40:46 -0400573 SkASSERT(arg1Type.columns() == 2);
Brian Osman00185012021-02-04 16:07:11 -0500574 this->writeExpression(*arguments[1], Precedence::kSequence);
Timothy Liangee84fe12018-05-18 14:38:19 -0400575 this->write(")");
576 }
Timothy Liang6403b0e2018-05-17 10:40:04 -0400577 break;
Ethan Nicholas30d30222020-09-11 12:27:26 -0400578 }
John Stilesd7199b22020-12-30 16:22:58 -0500579 case kMod_IntrinsicKind: {
Timothy Liang651286f2018-06-07 09:55:33 -0400580 // 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 -0500581 String tmpX = this->getTempVariable(arguments[0]->type());
John Stiles61b2e812020-12-30 18:27:31 -0500582 String tmpY = this->getTempVariable(arguments[1]->type());
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500583 this->write("(" + tmpX + " = ");
Brian Osman00185012021-02-04 16:07:11 -0500584 this->writeExpression(*arguments[0], Precedence::kSequence);
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500585 this->write(", " + tmpY + " = ");
Brian Osman00185012021-02-04 16:07:11 -0500586 this->writeExpression(*arguments[1], Precedence::kSequence);
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500587 this->write(", " + tmpX + " - " + tmpY + " * floor(" + tmpX + " / " + tmpY + "))");
Timothy Liang651286f2018-06-07 09:55:33 -0400588 break;
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500589 }
Brian Osman46787d52020-11-24 14:18:23 -0500590 // GLSL declares scalar versions of most geometric intrinsics, but these don't exist in MSL
John Stilesd7199b22020-12-30 16:22:58 -0500591 case kDistance_IntrinsicKind: {
Brian Osman46787d52020-11-24 14:18:23 -0500592 if (arguments[0]->type().columns() == 1) {
593 this->write("abs(");
Brian Osman00185012021-02-04 16:07:11 -0500594 this->writeExpression(*arguments[0], Precedence::kAdditive);
Brian Osman46787d52020-11-24 14:18:23 -0500595 this->write(" - ");
Brian Osman00185012021-02-04 16:07:11 -0500596 this->writeExpression(*arguments[1], Precedence::kAdditive);
Brian Osman46787d52020-11-24 14:18:23 -0500597 this->write(")");
598 } else {
John Stiles791c27d2020-12-30 14:56:57 -0500599 this->writeSimpleIntrinsic(c);
Brian Osman46787d52020-11-24 14:18:23 -0500600 }
601 break;
602 }
John Stilesd7199b22020-12-30 16:22:58 -0500603 case kDot_IntrinsicKind: {
Brian Osman46787d52020-11-24 14:18:23 -0500604 if (arguments[0]->type().columns() == 1) {
605 this->write("(");
Brian Osman00185012021-02-04 16:07:11 -0500606 this->writeExpression(*arguments[0], Precedence::kMultiplicative);
Brian Osman46787d52020-11-24 14:18:23 -0500607 this->write(" * ");
Brian Osman00185012021-02-04 16:07:11 -0500608 this->writeExpression(*arguments[1], Precedence::kMultiplicative);
Brian Osman46787d52020-11-24 14:18:23 -0500609 this->write(")");
610 } else {
John Stiles791c27d2020-12-30 14:56:57 -0500611 this->writeSimpleIntrinsic(c);
Brian Osman46787d52020-11-24 14:18:23 -0500612 }
613 break;
614 }
John Stilesd7199b22020-12-30 16:22:58 -0500615 case kFaceforward_IntrinsicKind: {
John Stilesad0571f2020-12-10 18:03:10 -0500616 if (arguments[0]->type().columns() == 1) {
617 // ((((Nref) * (I) < 0) ? 1 : -1) * (N))
618 this->write("((((");
Brian Osman00185012021-02-04 16:07:11 -0500619 this->writeExpression(*arguments[2], Precedence::kSequence);
John Stilesad0571f2020-12-10 18:03:10 -0500620 this->write(") * (");
Brian Osman00185012021-02-04 16:07:11 -0500621 this->writeExpression(*arguments[1], Precedence::kSequence);
John Stilesad0571f2020-12-10 18:03:10 -0500622 this->write(") < 0) ? 1 : -1) * (");
Brian Osman00185012021-02-04 16:07:11 -0500623 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stilesad0571f2020-12-10 18:03:10 -0500624 this->write("))");
625 } else {
John Stiles791c27d2020-12-30 14:56:57 -0500626 this->writeSimpleIntrinsic(c);
John Stilesad0571f2020-12-10 18:03:10 -0500627 }
628 break;
629 }
John Stilesd7199b22020-12-30 16:22:58 -0500630 case kLength_IntrinsicKind: {
Brian Osman46787d52020-11-24 14:18:23 -0500631 this->write(arguments[0]->type().columns() == 1 ? "abs(" : "length(");
Brian Osman00185012021-02-04 16:07:11 -0500632 this->writeExpression(*arguments[0], Precedence::kSequence);
Brian Osman46787d52020-11-24 14:18:23 -0500633 this->write(")");
634 break;
635 }
John Stilesd7199b22020-12-30 16:22:58 -0500636 case kNormalize_IntrinsicKind: {
Brian Osman46787d52020-11-24 14:18:23 -0500637 this->write(arguments[0]->type().columns() == 1 ? "sign(" : "normalize(");
Brian Osman00185012021-02-04 16:07:11 -0500638 this->writeExpression(*arguments[0], Precedence::kSequence);
Brian Osman46787d52020-11-24 14:18:23 -0500639 this->write(")");
640 break;
641 }
John Stilesd7199b22020-12-30 16:22:58 -0500642 case kBitcast_IntrinsicKind: {
John Stiles0063a9f2020-12-10 18:01:45 -0500643 this->write(this->getBitcastIntrinsic(c.type()));
644 this->write("(");
Brian Osman00185012021-02-04 16:07:11 -0500645 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stiles0063a9f2020-12-10 18:01:45 -0500646 this->write(")");
647 break;
648 }
John Stilesd7199b22020-12-30 16:22:58 -0500649 case kDegrees_IntrinsicKind: {
John Stilese2d34f82020-12-10 18:02:02 -0500650 this->write("((");
Brian Osman00185012021-02-04 16:07:11 -0500651 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stilese2d34f82020-12-10 18:02:02 -0500652 this->write(") * 57.2957795)");
653 break;
654 }
John Stilesd7199b22020-12-30 16:22:58 -0500655 case kRadians_IntrinsicKind: {
John Stilese2d34f82020-12-10 18:02:02 -0500656 this->write("((");
Brian Osman00185012021-02-04 16:07:11 -0500657 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stilese2d34f82020-12-10 18:02:02 -0500658 this->write(") * 0.0174532925)");
659 break;
660 }
John Stilesd7199b22020-12-30 16:22:58 -0500661 case kDFdx_IntrinsicKind: {
662 this->write("dfdx");
663 this->writeArgumentList(c.arguments());
664 break;
665 }
666 case kDFdy_IntrinsicKind: {
667 // Flipping Y also negates the Y derivatives.
John Stiles270cec22021-02-17 12:59:36 -0500668 if (fProgram.fConfig->fSettings.fFlipY) {
John Stilesd7199b22020-12-30 16:22:58 -0500669 this->write("-");
670 }
671 this->write("dfdy");
672 this->writeArgumentList(c.arguments());
673 break;
674 }
675 case kInverse_IntrinsicKind: {
676 this->write(this->getInversePolyfill(arguments));
677 this->writeArgumentList(c.arguments());
678 break;
679 }
680 case kInversesqrt_IntrinsicKind: {
681 this->write("rsqrt");
682 this->writeArgumentList(c.arguments());
683 break;
684 }
685 case kAtan_IntrinsicKind: {
686 this->write(c.arguments().size() == 2 ? "atan2" : "atan");
687 this->writeArgumentList(c.arguments());
688 break;
689 }
690 case kReflect_IntrinsicKind: {
John Stiles791c27d2020-12-30 14:56:57 -0500691 if (arguments[0]->type().columns() == 1) {
692 // We need to synthesize `I - 2 * N * I * N`.
693 String tmpI = this->getTempVariable(arguments[0]->type());
694 String tmpN = this->getTempVariable(arguments[1]->type());
695
696 // (_skTempI = ...
697 this->write("(" + tmpI + " = ");
Brian Osman00185012021-02-04 16:07:11 -0500698 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stiles791c27d2020-12-30 14:56:57 -0500699
700 // , _skTempN = ...
701 this->write(", " + tmpN + " = ");
Brian Osman00185012021-02-04 16:07:11 -0500702 this->writeExpression(*arguments[1], Precedence::kSequence);
John Stiles791c27d2020-12-30 14:56:57 -0500703
704 // , _skTempI - 2 * _skTempN * _skTempI * _skTempN)
705 this->write(", " + tmpI + " - 2 * " + tmpN + " * " + tmpI + " * " + tmpN + ")");
706 } else {
707 this->writeSimpleIntrinsic(c);
708 }
709 break;
710 }
John Stilesd7199b22020-12-30 16:22:58 -0500711 case kRefract_IntrinsicKind: {
John Stiles4b783d62020-12-30 14:58:07 -0500712 if (arguments[0]->type().columns() == 1) {
713 // Metal does implement refract for vectors; rather than reimplementing refract from
714 // scratch, we can replace the call with `refract(float2(I,0), float2(N,0), eta).x`.
715 this->write("(refract(float2(");
Brian Osman00185012021-02-04 16:07:11 -0500716 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stiles4b783d62020-12-30 14:58:07 -0500717 this->write(", 0), float2(");
Brian Osman00185012021-02-04 16:07:11 -0500718 this->writeExpression(*arguments[1], Precedence::kSequence);
John Stiles4b783d62020-12-30 14:58:07 -0500719 this->write(", 0), ");
Brian Osman00185012021-02-04 16:07:11 -0500720 this->writeExpression(*arguments[2], Precedence::kSequence);
John Stiles4b783d62020-12-30 14:58:07 -0500721 this->write(").x)");
722 } else {
723 this->writeSimpleIntrinsic(c);
724 }
725 break;
726 }
John Stiles23456532020-12-30 18:12:48 -0500727 case kRoundEven_IntrinsicKind: {
728 this->write("rint");
729 this->writeArgumentList(c.arguments());
730 break;
731 }
John Stilesd7199b22020-12-30 16:22:58 -0500732 case kBitCount_IntrinsicKind: {
John Stilese7dc7cb2020-12-22 15:37:14 -0500733 this->write("popcount(");
Brian Osman00185012021-02-04 16:07:11 -0500734 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stilese7dc7cb2020-12-22 15:37:14 -0500735 this->write(")");
736 break;
737 }
John Stilesd7199b22020-12-30 16:22:58 -0500738 case kFindLSB_IntrinsicKind: {
John Stiles86424eb2020-12-11 11:17:14 -0500739 // Create a temp variable to store the expression, to avoid double-evaluating it.
740 String skTemp = this->getTempVariable(arguments[0]->type());
741 String exprType = this->typeName(arguments[0]->type());
742
743 // ctz returns numbits(type) on zero inputs; GLSL documents it as generating -1 instead.
744 // Use select to detect zero inputs and force a -1 result.
745
746 // (_skTemp1 = (.....), select(ctz(_skTemp1), int4(-1), _skTemp1 == int4(0)))
747 this->write("(");
748 this->write(skTemp);
749 this->write(" = (");
Brian Osman00185012021-02-04 16:07:11 -0500750 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stiles86424eb2020-12-11 11:17:14 -0500751 this->write("), select(ctz(");
752 this->write(skTemp);
753 this->write("), ");
754 this->write(exprType);
755 this->write("(-1), ");
756 this->write(skTemp);
757 this->write(" == ");
758 this->write(exprType);
759 this->write("(0)))");
760 break;
761 }
John Stilesd7199b22020-12-30 16:22:58 -0500762 case kFindMSB_IntrinsicKind: {
John Stiles9685e522020-12-14 11:52:14 -0500763 // Create a temp variable to store the expression, to avoid double-evaluating it.
764 String skTemp1 = this->getTempVariable(arguments[0]->type());
765 String exprType = this->typeName(arguments[0]->type());
766
767 // GLSL findMSB is actually quite different from Metal's clz:
768 // - For signed negative numbers, it returns the first zero bit, not the first one bit!
769 // - For an empty input (0/~0 depending on sign), findMSB gives -1; clz is numbits(type)
770
771 // (_skTemp1 = (.....),
772 this->write("(");
773 this->write(skTemp1);
774 this->write(" = (");
Brian Osman00185012021-02-04 16:07:11 -0500775 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stiles9685e522020-12-14 11:52:14 -0500776 this->write("), ");
777
778 // Signed input types might be negative; we need another helper variable to negate the
779 // input (since we can only find one bits, not zero bits).
780 String skTemp2;
781 if (arguments[0]->type().isSigned()) {
782 // ... _skTemp2 = (select(_skTemp1, ~_skTemp1, _skTemp1 < 0)),
783 skTemp2 = this->getTempVariable(arguments[0]->type());
784 this->write(skTemp2);
785 this->write(" = (select(");
786 this->write(skTemp1);
787 this->write(", ~");
788 this->write(skTemp1);
789 this->write(", ");
790 this->write(skTemp1);
791 this->write(" < 0)), ");
792 } else {
793 skTemp2 = skTemp1;
794 }
795
796 // ... select(int4(clz(_skTemp2)), int4(-1), _skTemp2 == int4(0)))
797 this->write("select(");
798 this->write(this->typeName(c.type()));
799 this->write("(clz(");
800 this->write(skTemp2);
801 this->write(")), ");
802 this->write(this->typeName(c.type()));
803 this->write("(-1), ");
804 this->write(skTemp2);
805 this->write(" == ");
806 this->write(exprType);
807 this->write("(0)))");
808 break;
809 }
John Stilesd7199b22020-12-30 16:22:58 -0500810 case kMatrixCompMult_IntrinsicKind: {
811 this->writeMatrixCompMult();
812 this->writeSimpleIntrinsic(c);
813 break;
814 }
815 case kCompareEqual_IntrinsicKind:
816 case kCompareGreaterThan_IntrinsicKind:
817 case kCompareGreaterThanEqual_IntrinsicKind:
818 case kCompareLessThan_IntrinsicKind:
819 case kCompareLessThanEqual_IntrinsicKind:
820 case kCompareNotEqual_IntrinsicKind: {
821 this->write("(");
Brian Osman00185012021-02-04 16:07:11 -0500822 this->writeExpression(*c.arguments()[0], Precedence::kRelational);
John Stilesd7199b22020-12-30 16:22:58 -0500823 switch (kind) {
824 case kCompareEqual_IntrinsicKind:
825 this->write(" == ");
826 break;
827 case kCompareNotEqual_IntrinsicKind:
828 this->write(" != ");
829 break;
830 case kCompareLessThan_IntrinsicKind:
831 this->write(" < ");
832 break;
833 case kCompareLessThanEqual_IntrinsicKind:
834 this->write(" <= ");
835 break;
836 case kCompareGreaterThan_IntrinsicKind:
837 this->write(" > ");
838 break;
839 case kCompareGreaterThanEqual_IntrinsicKind:
840 this->write(" >= ");
841 break;
842 default:
John Stilesf57207b2021-02-02 17:50:34 -0500843 SK_ABORT("unsupported comparison intrinsic kind");
John Stilesd7199b22020-12-30 16:22:58 -0500844 }
Brian Osman00185012021-02-04 16:07:11 -0500845 this->writeExpression(*c.arguments()[1], Precedence::kRelational);
John Stilesd7199b22020-12-30 16:22:58 -0500846 this->write(")");
847 break;
848 }
Timothy Liang6403b0e2018-05-17 10:40:04 -0400849 default:
John Stilesf57207b2021-02-02 17:50:34 -0500850 SK_ABORT("unsupported intrinsic kind");
Timothy Liang6403b0e2018-05-17 10:40:04 -0400851 }
852}
853
John Stilesfcf8cb22020-08-06 14:29:22 -0400854// Assembles a matrix of type floatRxC by resizing another matrix named `x0`.
855// Cells that don't exist in the source matrix will be populated with identity-matrix values.
856void MetalCodeGenerator::assembleMatrixFromMatrix(const Type& sourceMatrix, int rows, int columns) {
857 SkASSERT(rows <= 4);
858 SkASSERT(columns <= 4);
859
860 const char* columnSeparator = "";
861 for (int c = 0; c < columns; ++c) {
862 fExtraFunctions.printf("%sfloat%d(", columnSeparator, rows);
863 columnSeparator = "), ";
864
865 // Determine how many values to take from the source matrix for this row.
866 int swizzleLength = 0;
867 if (c < sourceMatrix.columns()) {
868 swizzleLength = std::min<>(rows, sourceMatrix.rows());
869 }
870
871 // Emit all the values from the source matrix row.
872 bool firstItem;
873 switch (swizzleLength) {
874 case 0: firstItem = true; break;
875 case 1: firstItem = false; fExtraFunctions.printf("x0[%d].x", c); break;
876 case 2: firstItem = false; fExtraFunctions.printf("x0[%d].xy", c); break;
877 case 3: firstItem = false; fExtraFunctions.printf("x0[%d].xyz", c); break;
878 case 4: firstItem = false; fExtraFunctions.printf("x0[%d].xyzw", c); break;
879 default: SkUNREACHABLE;
880 }
881
882 // Emit the placeholder identity-matrix cells.
883 for (int r = swizzleLength; r < rows; ++r) {
884 fExtraFunctions.printf("%s%s", firstItem ? "" : ", ", (r == c) ? "1.0" : "0.0");
885 firstItem = false;
886 }
887 }
888
889 fExtraFunctions.writeText(")");
890}
891
892// Assembles a matrix of type floatRxC by concatenating an arbitrary mix of values, named `x0`,
893// `x1`, etc. An error is written if the expression list don't contain exactly R*C scalars.
John Stiles5abb9e12021-04-06 13:47:19 -0400894void MetalCodeGenerator::assembleMatrixFromExpressions(const AnyConstructor& ctor,
John Stiles8e3b6be2020-10-13 11:14:08 -0400895 int rows, int columns) {
John Stilesfcf8cb22020-08-06 14:29:22 -0400896 size_t argIndex = 0;
897 int argPosition = 0;
John Stiles5abb9e12021-04-06 13:47:19 -0400898 auto args = ctor.argumentSpan();
John Stilesfcf8cb22020-08-06 14:29:22 -0400899
900 const char* columnSeparator = "";
901 for (int c = 0; c < columns; ++c) {
902 fExtraFunctions.printf("%sfloat%d(", columnSeparator, rows);
903 columnSeparator = "), ";
904
905 const char* rowSeparator = "";
906 for (int r = 0; r < rows; ++r) {
907 fExtraFunctions.writeText(rowSeparator);
908 rowSeparator = ", ";
909
910 if (argIndex < args.size()) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400911 const Type& argType = args[argIndex]->type();
Ethan Nicholase6592142020-09-08 10:22:09 -0400912 switch (argType.typeKind()) {
913 case Type::TypeKind::kScalar: {
John Stilesfcf8cb22020-08-06 14:29:22 -0400914 fExtraFunctions.printf("x%zu", argIndex);
915 break;
916 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400917 case Type::TypeKind::kVector: {
John Stilesfcf8cb22020-08-06 14:29:22 -0400918 fExtraFunctions.printf("x%zu[%d]", argIndex, argPosition);
919 break;
920 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400921 case Type::TypeKind::kMatrix: {
John Stilesfcf8cb22020-08-06 14:29:22 -0400922 fExtraFunctions.printf("x%zu[%d][%d]", argIndex,
923 argPosition / argType.rows(),
924 argPosition % argType.rows());
925 break;
926 }
927 default: {
928 SkDEBUGFAIL("incorrect type of argument for matrix constructor");
929 fExtraFunctions.writeText("<error>");
930 break;
931 }
932 }
933
934 ++argPosition;
935 if (argPosition >= argType.columns() * argType.rows()) {
936 ++argIndex;
937 argPosition = 0;
938 }
939 } else {
940 SkDEBUGFAIL("not enough arguments for matrix constructor");
941 fExtraFunctions.writeText("<error>");
942 }
943 }
944 }
945
946 if (argPosition != 0 || argIndex != args.size()) {
947 SkDEBUGFAIL("incorrect number of arguments for matrix constructor");
948 fExtraFunctions.writeText(", <error>");
949 }
950
951 fExtraFunctions.writeText(")");
952}
953
John Stiles1bdafbf2020-05-28 12:17:20 -0400954// Generates a constructor for 'matrix' which reorganizes the input arguments into the proper shape.
955// Keeps track of previously generated constructors so that we won't generate more than one
956// constructor for any given permutation of input argument types. Returns the name of the
957// generated constructor method.
John Stiles5abb9e12021-04-06 13:47:19 -0400958String MetalCodeGenerator::getMatrixConstructHelper(const AnyConstructor& c) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400959 const Type& matrix = c.type();
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500960 int columns = matrix.columns();
961 int rows = matrix.rows();
John Stiles5abb9e12021-04-06 13:47:19 -0400962 auto args = c.argumentSpan();
John Stiles1bdafbf2020-05-28 12:17:20 -0400963
964 // Create the helper-method name and use it as our lookup key.
965 String name;
966 name.appendf("float%dx%d_from", columns, rows);
967 for (const std::unique_ptr<Expression>& expr : args) {
John Stiles36129132020-12-29 12:28:04 -0500968 name.appendf("_%s", this->typeName(expr->type()).c_str());
John Stiles1bdafbf2020-05-28 12:17:20 -0400969 }
970
971 // If a helper-method has already been synthesized, we don't need to synthesize it again.
972 auto [iter, newlyCreated] = fHelpers.insert(name);
973 if (!newlyCreated) {
974 return name;
975 }
976
977 // Unlike GLSL, Metal requires that matrices are initialized with exactly R vectors of C
978 // components apiece. (In Metal 2.0, you can also supply R*C scalars, but you still cannot
979 // supply a mixture of scalars and vectors.)
980 fExtraFunctions.printf("float%dx%d %s(", columns, rows, name.c_str());
981
982 size_t argIndex = 0;
983 const char* argSeparator = "";
John Stilesfcf8cb22020-08-06 14:29:22 -0400984 for (const std::unique_ptr<Expression>& expr : args) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400985 fExtraFunctions.printf("%s%s x%zu", argSeparator,
John Stiles36129132020-12-29 12:28:04 -0500986 this->typeName(expr->type()).c_str(), argIndex++);
John Stiles1bdafbf2020-05-28 12:17:20 -0400987 argSeparator = ", ";
988 }
989
990 fExtraFunctions.printf(") {\n return float%dx%d(", columns, rows);
991
John Stiles9aeed132020-11-24 17:36:06 -0500992 if (args.size() == 1 && args.front()->type().isMatrix()) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400993 this->assembleMatrixFromMatrix(args.front()->type(), rows, columns);
John Stilesfcf8cb22020-08-06 14:29:22 -0400994 } else {
John Stiles5abb9e12021-04-06 13:47:19 -0400995 this->assembleMatrixFromExpressions(c, rows, columns);
John Stiles1bdafbf2020-05-28 12:17:20 -0400996 }
997
John Stilesfcf8cb22020-08-06 14:29:22 -0400998 fExtraFunctions.writeText(");\n}\n");
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500999 return name;
1000}
1001
1002bool MetalCodeGenerator::canCoerce(const Type& t1, const Type& t2) {
1003 if (t1.columns() != t2.columns() || t1.rows() != t2.rows()) {
1004 return false;
1005 }
1006 if (t1.columns() > 1) {
1007 return this->canCoerce(t1.componentType(), t2.componentType());
1008 }
Ethan Nicholase1f55022019-02-05 17:17:40 -05001009 return t1.isFloat() && t2.isFloat();
Ethan Nicholas842d31b2019-01-22 10:59:11 -05001010}
1011
John Stiles2bec8ab2021-04-06 18:40:04 -04001012bool MetalCodeGenerator::matrixConstructHelperIsNeeded(const ConstructorComposite& c) {
1013 SkASSERT(c.type().isMatrix());
John Stiles1bdafbf2020-05-28 12:17:20 -04001014
1015 // GLSL is fairly free-form about inputs to its matrix constructors, but Metal is not; it
1016 // expects exactly R vectors of C components apiece. (Metal 2.0 also allows a list of R*C
1017 // scalars.) Some cases are simple to translate and so we handle those inline--e.g. a list of
1018 // scalars can be constructed trivially. In more complex cases, we generate a helper function
1019 // that converts our inputs into a properly-shaped matrix.
1020 // A matrix construct helper method is always used if any input argument is a matrix.
1021 // Helper methods are also necessary when any argument would span multiple rows. For instance:
1022 //
1023 // float2 x = (1, 2);
1024 // float3x2(x, 3, 4, 5, 6) = | 1 3 5 | = no helper needed; conversion can be done inline
1025 // | 2 4 6 |
1026 //
1027 // float2 x = (2, 3);
1028 // float3x2(1, x, 4, 5, 6) = | 1 3 5 | = x spans multiple rows; a helper method will be used
1029 // | 2 4 6 |
1030 //
1031 // float4 x = (1, 2, 3, 4);
1032 // float2x2(x) = | 1 3 | = x spans multiple rows; a helper method will be used
1033 // | 2 4 |
1034 //
1035
1036 int position = 0;
Ethan Nicholasf70f0442020-09-29 12:41:35 -04001037 for (const std::unique_ptr<Expression>& expr : c.arguments()) {
John Stiles1bdafbf2020-05-28 12:17:20 -04001038 // If an input argument is a matrix, we need a helper function.
John Stiles9aeed132020-11-24 17:36:06 -05001039 if (expr->type().isMatrix()) {
John Stiles1bdafbf2020-05-28 12:17:20 -04001040 return true;
1041 }
Ethan Nicholas30d30222020-09-11 12:27:26 -04001042 position += expr->type().columns();
1043 if (position > c.type().rows()) {
John Stiles1bdafbf2020-05-28 12:17:20 -04001044 // An input argument would span multiple rows; a helper function is required.
1045 return true;
1046 }
Ethan Nicholas30d30222020-09-11 12:27:26 -04001047 if (position == c.type().rows()) {
John Stiles1bdafbf2020-05-28 12:17:20 -04001048 // We've advanced to the end of a row. Wrap to the start of the next row.
1049 position = 0;
1050 }
1051 }
1052
1053 return false;
1054}
1055
John Stiles5abb9e12021-04-06 13:47:19 -04001056void MetalCodeGenerator::writeConstructorMatrixResize(const ConstructorMatrixResize& c,
1057 Precedence parentPrecedence) {
1058 // Matrix-resize via casting doesn't natively exist in Metal at all, so we always need to use a
1059 // matrix-construct helper here.
1060 this->write(this->getMatrixConstructHelper(c));
1061 this->write("(");
1062 this->writeExpression(*c.argument(), Precedence::kSequence);
1063 this->write(")");
1064}
1065
John Stiles2bec8ab2021-04-06 18:40:04 -04001066void MetalCodeGenerator::writeConstructorComposite(const ConstructorComposite& c,
1067 Precedence parentPrecedence) {
1068 if (c.type().isMatrix()) {
1069 this->writeConstructorCompositeMatrix(c, parentPrecedence);
1070 } else {
1071 this->writeAnyConstructor(c, "(", ")", parentPrecedence);
1072 }
1073}
John Stiles7384b372021-04-01 13:48:15 -04001074
John Stiles2bec8ab2021-04-06 18:40:04 -04001075void MetalCodeGenerator::writeConstructorCompositeMatrix(const ConstructorComposite& c,
1076 Precedence parentPrecedence) {
John Stiles1bdafbf2020-05-28 12:17:20 -04001077 // Emit and invoke a matrix-constructor helper method if one is necessary.
1078 if (this->matrixConstructHelperIsNeeded(c)) {
1079 this->write(this->getMatrixConstructHelper(c));
John Stiles1fa15b12020-05-28 17:36:54 +00001080 this->write("(");
1081 const char* separator = "";
Ethan Nicholasf70f0442020-09-29 12:41:35 -04001082 for (const std::unique_ptr<Expression>& expr : c.arguments()) {
John Stiles1fa15b12020-05-28 17:36:54 +00001083 this->write(separator);
1084 separator = ", ";
Brian Osman00185012021-02-04 16:07:11 -05001085 this->writeExpression(*expr, Precedence::kSequence);
John Stilesdaa573e2020-05-28 12:17:20 -04001086 }
John Stiles1fa15b12020-05-28 17:36:54 +00001087 this->write(")");
John Stiles1bdafbf2020-05-28 12:17:20 -04001088 return;
John Stilesdaa573e2020-05-28 12:17:20 -04001089 }
John Stiles1bdafbf2020-05-28 12:17:20 -04001090
John Stiles2bec8ab2021-04-06 18:40:04 -04001091 // Metal doesn't allow creating matrices by passing in scalars and vectors in a jumble; it
1092 // requires your scalars to be grouped up into columns. Because `matrixConstructHelperIsNeeded`
1093 // returned false, we know that none of our scalars/vectors "wrap" across across a column, so we
1094 // can group our inputs up and synthesize a constructor for each column.
1095 const Type& matrixType = c.type();
1096 const Type& columnType = matrixType.componentType().toCompound(
1097 fContext, /*columns=*/matrixType.rows(), /*rows=*/1);
1098
1099 this->writeType(matrixType);
John Stiles7384b372021-04-01 13:48:15 -04001100 this->write("(");
John Stiles1bdafbf2020-05-28 12:17:20 -04001101 const char* separator = "";
1102 int scalarCount = 0;
Ethan Nicholasf70f0442020-09-29 12:41:35 -04001103 for (const std::unique_ptr<Expression>& arg : c.arguments()) {
John Stiles1bdafbf2020-05-28 12:17:20 -04001104 this->write(separator);
1105 separator = ", ";
John Stiles2bec8ab2021-04-06 18:40:04 -04001106 if (arg->type().columns() < matrixType.rows()) {
1107 // Write a `floatN(` constructor to group scalars and smaller vectors together.
John Stiles1bdafbf2020-05-28 12:17:20 -04001108 if (!scalarCount) {
John Stiles2bec8ab2021-04-06 18:40:04 -04001109 this->writeType(columnType);
John Stiles1bdafbf2020-05-28 12:17:20 -04001110 this->write("(");
1111 }
John Stiles2bec8ab2021-04-06 18:40:04 -04001112 scalarCount += arg->type().columns();
John Stiles1bdafbf2020-05-28 12:17:20 -04001113 }
Brian Osman00185012021-02-04 16:07:11 -05001114 this->writeExpression(*arg, Precedence::kSequence);
John Stiles2bec8ab2021-04-06 18:40:04 -04001115 if (scalarCount && scalarCount == matrixType.rows()) {
1116 // Close our `floatN(...` constructor block from above.
John Stiles1bdafbf2020-05-28 12:17:20 -04001117 this->write(")");
1118 scalarCount = 0;
1119 }
1120 }
John Stiles7384b372021-04-01 13:48:15 -04001121 this->write(")");
Ethan Nicholascc305772017-10-13 16:17:45 -04001122}
1123
John Stilesb14a8192021-04-05 11:40:46 -04001124void MetalCodeGenerator::writeAnyConstructor(const AnyConstructor& c,
1125 const char* leftBracket,
1126 const char* rightBracket,
1127 Precedence parentPrecedence) {
John Stilese1182782021-03-30 22:09:37 -04001128 this->writeType(c.type());
John Stilesb14a8192021-04-05 11:40:46 -04001129 this->write(leftBracket);
John Stiles7384b372021-04-01 13:48:15 -04001130 const char* separator = "";
John Stilesb14a8192021-04-05 11:40:46 -04001131 for (const std::unique_ptr<Expression>& arg : c.argumentSpan()) {
John Stiles7384b372021-04-01 13:48:15 -04001132 this->write(separator);
1133 separator = ", ";
1134 this->writeExpression(*arg, Precedence::kSequence);
1135 }
John Stilesb14a8192021-04-05 11:40:46 -04001136 this->write(rightBracket);
John Stiles7384b372021-04-01 13:48:15 -04001137}
1138
John Stilesb14a8192021-04-05 11:40:46 -04001139void MetalCodeGenerator::writeCastConstructor(const AnyConstructor& c,
1140 const char* leftBracket,
1141 const char* rightBracket,
1142 Precedence parentPrecedence) {
1143 // If the type is coercible, emit it directly without the cast.
1144 auto args = c.argumentSpan();
1145 if (args.size() == 1) {
1146 if (this->canCoerce(c.type(), args.front()->type())) {
1147 this->writeExpression(*args.front(), parentPrecedence);
1148 return;
1149 }
John Stilesfd7252f2021-04-04 22:24:40 -04001150 }
1151
John Stilesb14a8192021-04-05 11:40:46 -04001152 return this->writeAnyConstructor(c, leftBracket, rightBracket, parentPrecedence);
John Stilesfd7252f2021-04-04 22:24:40 -04001153}
1154
Ethan Nicholascc305772017-10-13 16:17:45 -04001155void MetalCodeGenerator::writeFragCoord() {
Ethan Nicholasf931e402019-07-26 15:40:33 -04001156 if (fRTHeightName.length()) {
1157 this->write("float4(_fragCoord.x, ");
1158 this->write(fRTHeightName.c_str());
1159 this->write(" - _fragCoord.y, 0.0, _fragCoord.w)");
Jim Van Verth6bc650e2019-02-07 14:53:23 -05001160 } else {
1161 this->write("float4(_fragCoord.x, _fragCoord.y, 0.0, _fragCoord.w)");
1162 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001163}
1164
1165void MetalCodeGenerator::writeVariableReference(const VariableReference& ref) {
John Stiles06b84ef2020-12-09 12:35:48 -05001166 // When assembling out-param helper functions, we copy variables into local clones with matching
John Stilesf7410bd2021-01-19 13:07:55 -05001167 // names. We never want to prepend "_in." or "_globals." when writing these variables since
John Stiles06b84ef2020-12-09 12:35:48 -05001168 // we're actually targeting the clones.
1169 if (fIgnoreVariableReferenceModifiers) {
1170 this->writeName(ref.variable()->name());
1171 return;
1172 }
1173
Ethan Nicholas78686922020-10-08 06:46:27 -04001174 switch (ref.variable()->modifiers().fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001175 case SK_FRAGCOLOR_BUILTIN:
John Stilesf7410bd2021-01-19 13:07:55 -05001176 this->write("_out.sk_FragColor");
Ethan Nicholascc305772017-10-13 16:17:45 -04001177 break;
Timothy Liang6403b0e2018-05-17 10:40:04 -04001178 case SK_FRAGCOORD_BUILTIN:
1179 this->writeFragCoord();
1180 break;
Timothy Liangdc89f192018-06-13 09:20:31 -04001181 case SK_VERTEXID_BUILTIN:
1182 this->write("sk_VertexID");
1183 break;
1184 case SK_INSTANCEID_BUILTIN:
1185 this->write("sk_InstanceID");
1186 break;
Timothy Liang7b8875d2018-08-10 09:42:31 -04001187 case SK_CLOCKWISE_BUILTIN:
1188 // We'd set the front facing winding in the MTLRenderCommandEncoder to be counter
Brian Salomonf4ba4ec2020-03-19 15:54:28 -04001189 // clockwise to match Skia convention.
John Stiles270cec22021-02-17 12:59:36 -05001190 this->write(fProgram.fConfig->fSettings.fFlipY ? "_frontFacing" : "(!_frontFacing)");
Timothy Liang7b8875d2018-08-10 09:42:31 -04001191 break;
Ethan Nicholascc305772017-10-13 16:17:45 -04001192 default:
Ethan Nicholas78686922020-10-08 06:46:27 -04001193 const Variable& var = *ref.variable();
Ethan Nicholas453f67f2020-10-09 10:43:45 -04001194 if (var.storage() == Variable::Storage::kGlobal) {
Ethan Nicholas78686922020-10-08 06:46:27 -04001195 if (var.modifiers().fFlags & Modifiers::kIn_Flag) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001196 this->write("_in.");
Ethan Nicholas78686922020-10-08 06:46:27 -04001197 } else if (var.modifiers().fFlags & Modifiers::kOut_Flag) {
John Stilesf7410bd2021-01-19 13:07:55 -05001198 this->write("_out.");
Ethan Nicholas78686922020-10-08 06:46:27 -04001199 } else if (var.modifiers().fFlags & Modifiers::kUniform_Flag &&
1200 var.type().typeKind() != Type::TypeKind::kSampler) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001201 this->write("_uniforms.");
1202 } else {
John Stilesf7410bd2021-01-19 13:07:55 -05001203 this->write("_globals.");
Ethan Nicholascc305772017-10-13 16:17:45 -04001204 }
1205 }
Ethan Nicholas78686922020-10-08 06:46:27 -04001206 this->writeName(var.name());
Ethan Nicholascc305772017-10-13 16:17:45 -04001207 }
1208}
1209
1210void MetalCodeGenerator::writeIndexExpression(const IndexExpression& expr) {
Brian Osman00185012021-02-04 16:07:11 -05001211 this->writeExpression(*expr.base(), Precedence::kPostfix);
Ethan Nicholascc305772017-10-13 16:17:45 -04001212 this->write("[");
Brian Osman00185012021-02-04 16:07:11 -05001213 this->writeExpression(*expr.index(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001214 this->write("]");
1215}
1216
1217void MetalCodeGenerator::writeFieldAccess(const FieldAccess& f) {
Ethan Nicholas7a95b202020-10-09 11:55:40 -04001218 const Type::Field* field = &f.base()->type().fields()[f.fieldIndex()];
1219 if (FieldAccess::OwnerKind::kDefault == f.ownerKind()) {
Brian Osman00185012021-02-04 16:07:11 -05001220 this->writeExpression(*f.base(), Precedence::kPostfix);
Ethan Nicholascc305772017-10-13 16:17:45 -04001221 this->write(".");
1222 }
Timothy Liang7d637782018-06-05 09:58:07 -04001223 switch (field->fModifiers.fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001224 case SK_POSITION_BUILTIN:
John Stilesf7410bd2021-01-19 13:07:55 -05001225 this->write("_out.sk_Position");
Ethan Nicholascc305772017-10-13 16:17:45 -04001226 break;
1227 default:
Timothy Liang7d637782018-06-05 09:58:07 -04001228 if (field->fName == "sk_PointSize") {
John Stilesf7410bd2021-01-19 13:07:55 -05001229 this->write("_out.sk_PointSize");
Timothy Liang7d637782018-06-05 09:58:07 -04001230 } else {
Ethan Nicholas7a95b202020-10-09 11:55:40 -04001231 if (FieldAccess::OwnerKind::kAnonymousInterfaceBlock == f.ownerKind()) {
John Stilesf7410bd2021-01-19 13:07:55 -05001232 this->write("_globals.");
Timothy Liang7d637782018-06-05 09:58:07 -04001233 this->write(fInterfaceBlockNameMap[fInterfaceBlockMap[field]]);
1234 this->write("->");
1235 }
Timothy Liang651286f2018-06-07 09:55:33 -04001236 this->writeName(field->fName);
Timothy Lianga06f2152018-05-24 15:33:31 -04001237 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001238 }
1239}
1240
1241void MetalCodeGenerator::writeSwizzle(const Swizzle& swizzle) {
Brian Osman00185012021-02-04 16:07:11 -05001242 this->writeExpression(*swizzle.base(), Precedence::kPostfix);
Ethan Nicholascc305772017-10-13 16:17:45 -04001243 this->write(".");
Ethan Nicholas6b4d5812020-10-12 16:11:51 -04001244 for (int c : swizzle.components()) {
Brian Osman25647672020-09-15 15:16:56 -04001245 SkASSERT(c >= 0 && c <= 3);
1246 this->write(&("x\0y\0z\0w\0"[c * 2]));
Ethan Nicholascc305772017-10-13 16:17:45 -04001247 }
1248}
1249
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001250void MetalCodeGenerator::writeMatrixTimesEqualHelper(const Type& left, const Type& right,
1251 const Type& result) {
John Stiles01cdf012021-02-10 09:53:41 -05001252 String key = "TimesEqual" + this->typeName(left) + ":" + this->typeName(right);
John Stiles56233d12021-02-03 13:03:29 -05001253
1254 auto [iter, wasInserted] = fHelpers.insert(key);
1255 if (wasInserted) {
John Stiles368db7c2020-12-29 11:20:08 -05001256 fExtraFunctions.printf("thread %s& operator*=(thread %s& left, thread const %s& right) {\n"
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001257 " left = left * right;\n"
1258 " return left;\n"
John Stiles368db7c2020-12-29 11:20:08 -05001259 "}\n",
1260 this->typeName(result).c_str(), this->typeName(left).c_str(),
1261 this->typeName(right).c_str());
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001262 }
1263}
1264
John Stiles01cdf012021-02-10 09:53:41 -05001265void MetalCodeGenerator::writeMatrixEqualityHelper(const Type& left, const Type& right) {
1266 SkASSERTF(left.rows() == right.rows() && left.columns() == right.columns(), "left=%s, right=%s",
1267 left.description().c_str(), right.description().c_str());
1268
1269 String key = "Equality" + this->typeName(left) + ":" + this->typeName(right);
1270
1271 auto [iter, wasInserted] = fHelpers.insert(key);
1272 if (wasInserted) {
1273 fExtraFunctions.printf(
1274 "thread bool operator==(const %s left, const %s right) {\n"
1275 " return",
1276 this->typeName(left).c_str(), this->typeName(right).c_str());
1277
1278 for (int index=0; index<left.columns(); ++index) {
1279 fExtraFunctions.printf("%s all(left[%d] == right[%d])",
1280 index == 0 ? "" : " &&", index, index);
1281 }
1282 fExtraFunctions.printf(";\n"
1283 "}\n");
1284 }
1285}
1286
1287void MetalCodeGenerator::writeMatrixInequalityHelper(const Type& left, const Type& right) {
1288 SkASSERTF(left.rows() == right.rows() && left.columns() == right.columns(), "left=%s, right=%s",
1289 left.description().c_str(), right.description().c_str());
1290
1291 String key = "Inequality" + this->typeName(left) + ":" + this->typeName(right);
1292
1293 auto [iter, wasInserted] = fHelpers.insert(key);
1294 if (wasInserted) {
1295 fExtraFunctions.printf(
1296 "thread bool operator!=(const %s left, const %s right) {\n"
1297 " return",
1298 this->typeName(left).c_str(), this->typeName(right).c_str());
1299
1300 for (int index=0; index<left.columns(); ++index) {
1301 fExtraFunctions.printf("%s any(left[%d] != right[%d])",
1302 index == 0 ? "" : " ||", index, index);
1303 }
1304 fExtraFunctions.printf(";\n"
1305 "}\n");
1306 }
1307}
1308
Ethan Nicholascc305772017-10-13 16:17:45 -04001309void MetalCodeGenerator::writeBinaryExpression(const BinaryExpression& b,
1310 Precedence parentPrecedence) {
John Stiles2d4f9592020-10-30 10:29:12 -04001311 const Expression& left = *b.left();
1312 const Expression& right = *b.right();
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001313 const Type& leftType = left.type();
1314 const Type& rightType = right.type();
John Stiles45990502021-02-16 10:55:27 -05001315 Operator op = b.getOperator();
1316 Precedence precedence = op.getBinaryPrecedence();
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001317 bool needParens = precedence >= parentPrecedence;
John Stiles45990502021-02-16 10:55:27 -05001318 switch (op.kind()) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001319 case Token::Kind::TK_EQEQ:
John Stiles9aeed132020-11-24 17:36:06 -05001320 if (leftType.isVector()) {
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001321 this->write("all");
1322 needParens = true;
1323 }
1324 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001325 case Token::Kind::TK_NEQ:
John Stiles9aeed132020-11-24 17:36:06 -05001326 if (leftType.isVector()) {
Jim Van Verth36477b42019-04-11 14:57:30 -04001327 this->write("any");
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001328 needParens = true;
1329 }
1330 break;
1331 default:
1332 break;
1333 }
1334 if (needParens) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001335 this->write("(");
1336 }
John Stiles01cdf012021-02-10 09:53:41 -05001337 if (leftType.isMatrix() && rightType.isMatrix()) {
John Stiles45990502021-02-16 10:55:27 -05001338 if (op.kind() == Token::Kind::TK_STAREQ) {
John Stiles01cdf012021-02-10 09:53:41 -05001339 this->writeMatrixTimesEqualHelper(leftType, rightType, b.type());
John Stiles45990502021-02-16 10:55:27 -05001340 } else if (op.kind() == Token::Kind::TK_EQEQ) {
John Stiles01cdf012021-02-10 09:53:41 -05001341 this->writeMatrixEqualityHelper(leftType, rightType);
John Stiles45990502021-02-16 10:55:27 -05001342 } else if (op.kind() == Token::Kind::TK_NEQ) {
John Stiles01cdf012021-02-10 09:53:41 -05001343 this->writeMatrixInequalityHelper(leftType, rightType);
1344 }
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001345 }
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001346 this->writeExpression(left, precedence);
John Stiles45990502021-02-16 10:55:27 -05001347 if (op.kind() != Token::Kind::TK_EQ && op.isAssignment() &&
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001348 left.kind() == Expression::Kind::kSwizzle && !left.hasSideEffects()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001349 // This doesn't compile in Metal:
1350 // float4 x = float4(1);
1351 // x.xy *= float2x2(...);
1352 // with the error message "non-const reference cannot bind to vector element",
1353 // but switching it to x.xy = x.xy * float2x2(...) fixes it. We perform this tranformation
1354 // as long as the LHS has no side effects, and hope for the best otherwise.
1355 this->write(" = ");
Brian Osman00185012021-02-04 16:07:11 -05001356 this->writeExpression(left, Precedence::kAssignment);
Ethan Nicholascc305772017-10-13 16:17:45 -04001357 this->write(" ");
John Stilesd6449e92020-11-30 09:13:23 -05001358 String opName = OperatorName(op);
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001359 SkASSERT(opName.endsWith("="));
1360 this->write(opName.substr(0, opName.size() - 1).c_str());
Ethan Nicholascc305772017-10-13 16:17:45 -04001361 this->write(" ");
1362 } else {
John Stilesd6449e92020-11-30 09:13:23 -05001363 this->write(String(" ") + OperatorName(op) + " ");
Ethan Nicholascc305772017-10-13 16:17:45 -04001364 }
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001365 this->writeExpression(right, precedence);
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001366 if (needParens) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001367 this->write(")");
1368 }
1369}
1370
1371void MetalCodeGenerator::writeTernaryExpression(const TernaryExpression& t,
1372 Precedence parentPrecedence) {
Brian Osman00185012021-02-04 16:07:11 -05001373 if (Precedence::kTernary >= parentPrecedence) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001374 this->write("(");
1375 }
Brian Osman00185012021-02-04 16:07:11 -05001376 this->writeExpression(*t.test(), Precedence::kTernary);
Ethan Nicholascc305772017-10-13 16:17:45 -04001377 this->write(" ? ");
Brian Osman00185012021-02-04 16:07:11 -05001378 this->writeExpression(*t.ifTrue(), Precedence::kTernary);
Ethan Nicholascc305772017-10-13 16:17:45 -04001379 this->write(" : ");
Brian Osman00185012021-02-04 16:07:11 -05001380 this->writeExpression(*t.ifFalse(), Precedence::kTernary);
1381 if (Precedence::kTernary >= parentPrecedence) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001382 this->write(")");
1383 }
1384}
1385
1386void MetalCodeGenerator::writePrefixExpression(const PrefixExpression& p,
1387 Precedence parentPrecedence) {
Brian Osman00185012021-02-04 16:07:11 -05001388 if (Precedence::kPrefix >= parentPrecedence) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001389 this->write("(");
1390 }
John Stilesd6449e92020-11-30 09:13:23 -05001391 this->write(OperatorName(p.getOperator()));
Brian Osman00185012021-02-04 16:07:11 -05001392 this->writeExpression(*p.operand(), Precedence::kPrefix);
1393 if (Precedence::kPrefix >= parentPrecedence) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001394 this->write(")");
1395 }
1396}
1397
1398void MetalCodeGenerator::writePostfixExpression(const PostfixExpression& p,
1399 Precedence parentPrecedence) {
Brian Osman00185012021-02-04 16:07:11 -05001400 if (Precedence::kPostfix >= parentPrecedence) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001401 this->write("(");
1402 }
Brian Osman00185012021-02-04 16:07:11 -05001403 this->writeExpression(*p.operand(), Precedence::kPostfix);
John Stilesd6449e92020-11-30 09:13:23 -05001404 this->write(OperatorName(p.getOperator()));
Brian Osman00185012021-02-04 16:07:11 -05001405 if (Precedence::kPostfix >= parentPrecedence) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001406 this->write(")");
1407 }
1408}
1409
1410void MetalCodeGenerator::writeBoolLiteral(const BoolLiteral& b) {
Ethan Nicholas59d660c2020-09-28 09:18:15 -04001411 this->write(b.value() ? "true" : "false");
Ethan Nicholascc305772017-10-13 16:17:45 -04001412}
1413
1414void MetalCodeGenerator::writeIntLiteral(const IntLiteral& i) {
John Stiles12739df2020-12-29 09:47:20 -05001415 const Type& type = i.type();
John Stiles54e7c052021-01-11 14:22:36 -05001416 if (type == *fContext.fTypes.fUInt) {
Ethan Nicholase96cdd12020-09-28 16:27:18 -04001417 this->write(to_string(i.value() & 0xffffffff) + "u");
John Stiles54e7c052021-01-11 14:22:36 -05001418 } else if (type == *fContext.fTypes.fUShort) {
John Stiles12739df2020-12-29 09:47:20 -05001419 this->write(to_string(i.value() & 0xffff) + "u");
John Stiles54e7c052021-01-11 14:22:36 -05001420 } else if (type == *fContext.fTypes.fUByte) {
John Stiles12739df2020-12-29 09:47:20 -05001421 this->write(to_string(i.value() & 0xff) + "u");
Ethan Nicholascc305772017-10-13 16:17:45 -04001422 } else {
John Stiles12739df2020-12-29 09:47:20 -05001423 this->write(to_string(i.value()));
Ethan Nicholascc305772017-10-13 16:17:45 -04001424 }
1425}
1426
1427void MetalCodeGenerator::writeFloatLiteral(const FloatLiteral& f) {
Ethan Nicholasa3f22f12020-10-01 12:13:17 -04001428 this->write(to_string(f.value()));
Ethan Nicholascc305772017-10-13 16:17:45 -04001429}
1430
1431void MetalCodeGenerator::writeSetting(const Setting& s) {
John Stilesf57207b2021-02-02 17:50:34 -05001432 SK_ABORT("internal error; setting was not folded to a constant during compilation\n");
Ethan Nicholascc305772017-10-13 16:17:45 -04001433}
1434
John Stiles06b84ef2020-12-09 12:35:48 -05001435void MetalCodeGenerator::writeFunctionRequirementArgs(const FunctionDeclaration& f,
1436 const char*& separator) {
1437 Requirements requirements = this->requirements(f);
1438 if (requirements & kInputs_Requirement) {
1439 this->write(separator);
1440 this->write("_in");
1441 separator = ", ";
1442 }
1443 if (requirements & kOutputs_Requirement) {
1444 this->write(separator);
1445 this->write("_out");
1446 separator = ", ";
1447 }
1448 if (requirements & kUniforms_Requirement) {
1449 this->write(separator);
1450 this->write("_uniforms");
1451 separator = ", ";
1452 }
1453 if (requirements & kGlobals_Requirement) {
1454 this->write(separator);
John Stilesf7410bd2021-01-19 13:07:55 -05001455 this->write("_globals");
John Stiles06b84ef2020-12-09 12:35:48 -05001456 separator = ", ";
1457 }
1458 if (requirements & kFragCoord_Requirement) {
1459 this->write(separator);
1460 this->write("_fragCoord");
1461 separator = ", ";
1462 }
1463}
1464
1465void MetalCodeGenerator::writeFunctionRequirementParams(const FunctionDeclaration& f,
1466 const char*& separator) {
1467 Requirements requirements = this->requirements(f);
1468 if (requirements & kInputs_Requirement) {
1469 this->write(separator);
1470 this->write("Inputs _in");
1471 separator = ", ";
1472 }
1473 if (requirements & kOutputs_Requirement) {
1474 this->write(separator);
John Stilesf7410bd2021-01-19 13:07:55 -05001475 this->write("thread Outputs& _out");
John Stiles06b84ef2020-12-09 12:35:48 -05001476 separator = ", ";
1477 }
1478 if (requirements & kUniforms_Requirement) {
1479 this->write(separator);
1480 this->write("Uniforms _uniforms");
1481 separator = ", ";
1482 }
1483 if (requirements & kGlobals_Requirement) {
1484 this->write(separator);
John Stilesf7410bd2021-01-19 13:07:55 -05001485 this->write("thread Globals& _globals");
John Stiles06b84ef2020-12-09 12:35:48 -05001486 separator = ", ";
1487 }
1488 if (requirements & kFragCoord_Requirement) {
1489 this->write(separator);
1490 this->write("float4 _fragCoord");
1491 separator = ", ";
1492 }
1493}
1494
John Stilesda5cdf62021-01-28 11:47:29 -05001495int MetalCodeGenerator::getUniformBinding(const Modifiers& m) {
1496 return (m.fLayout.fBinding >= 0) ? m.fLayout.fBinding
John Stiles270cec22021-02-17 12:59:36 -05001497 : fProgram.fConfig->fSettings.fDefaultUniformBinding;
John Stilesda5cdf62021-01-28 11:47:29 -05001498}
1499
1500int MetalCodeGenerator::getUniformSet(const Modifiers& m) {
1501 return (m.fLayout.fSet >= 0) ? m.fLayout.fSet
John Stiles270cec22021-02-17 12:59:36 -05001502 : fProgram.fConfig->fSettings.fDefaultUniformSet;
John Stilesda5cdf62021-01-28 11:47:29 -05001503}
1504
John Stiles569249b2020-11-03 12:18:22 -05001505bool MetalCodeGenerator::writeFunctionDeclaration(const FunctionDeclaration& f) {
John Stilesf7410bd2021-01-19 13:07:55 -05001506 fRTHeightName = fProgram.fInputs.fRTHeight ? "_globals._anonInterface0->u_skRTHeight" : "";
Ethan Nicholascc305772017-10-13 16:17:45 -04001507 const char* separator = "";
John Stilese8da4d22021-03-24 09:19:45 -04001508 if (f.isMain()) {
John Stiles270cec22021-02-17 12:59:36 -05001509 switch (fProgram.fConfig->fKind) {
John Stilesdbd4e6f2021-02-16 13:29:15 -05001510 case ProgramKind::kFragment:
Timothy Liangb8eeb802018-07-23 16:46:16 -04001511 this->write("fragment Outputs fragmentMain");
Ethan Nicholascc305772017-10-13 16:17:45 -04001512 break;
John Stilesdbd4e6f2021-02-16 13:29:15 -05001513 case ProgramKind::kVertex:
Timothy Liangb8eeb802018-07-23 16:46:16 -04001514 this->write("vertex Outputs vertexMain");
Ethan Nicholascc305772017-10-13 16:17:45 -04001515 break;
1516 default:
John Stiles3fabfc02020-09-25 15:51:28 -04001517 fErrors.error(-1, "unsupported kind of program");
John Stiles569249b2020-11-03 12:18:22 -05001518 return false;
Ethan Nicholascc305772017-10-13 16:17:45 -04001519 }
1520 this->write("(Inputs _in [[stage_in]]");
1521 if (-1 != fUniformBuffer) {
1522 this->write(", constant Uniforms& _uniforms [[buffer(" +
1523 to_string(fUniformBuffer) + ")]]");
1524 }
Brian Osman133724c2020-10-28 14:14:39 -04001525 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04001526 if (e->is<GlobalVarDeclaration>()) {
1527 const GlobalVarDeclaration& decls = e->as<GlobalVarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001528 const VarDeclaration& var = decls.declaration()->as<VarDeclaration>();
1529 if (var.var().type().typeKind() == Type::TypeKind::kSampler) {
1530 if (var.var().modifiers().fLayout.fBinding < 0) {
Brian Osmanc0213602020-10-06 14:43:32 -04001531 fErrors.error(decls.fOffset,
John Stilesb41d5bb2021-01-26 16:28:12 -05001532 "Metal samplers must have 'layout(binding=...)'");
John Stiles569249b2020-11-03 12:18:22 -05001533 return false;
Timothy Liangee84fe12018-05-18 14:38:19 -04001534 }
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001535 if (var.var().type().dimensions() != SpvDim2D) {
John Stiles569249b2020-11-03 12:18:22 -05001536 // Not yet implemented--Skia currently only uses 2D textures.
Brian Osmanc0213602020-10-06 14:43:32 -04001537 fErrors.error(decls.fOffset, "Unsupported texture dimensions");
John Stiles569249b2020-11-03 12:18:22 -05001538 return false;
Brian Osmanc0213602020-10-06 14:43:32 -04001539 }
1540 this->write(", texture2d<float> ");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001541 this->writeName(var.var().name());
Brian Osmanc0213602020-10-06 14:43:32 -04001542 this->write("[[texture(");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001543 this->write(to_string(var.var().modifiers().fLayout.fBinding));
Brian Osmanc0213602020-10-06 14:43:32 -04001544 this->write(")]]");
1545 this->write(", sampler ");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001546 this->writeName(var.var().name());
Brian Osmanc0213602020-10-06 14:43:32 -04001547 this->write(SAMPLER_SUFFIX);
1548 this->write("[[sampler(");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001549 this->write(to_string(var.var().modifiers().fLayout.fBinding));
Brian Osmanc0213602020-10-06 14:43:32 -04001550 this->write(")]]");
Timothy Liang6403b0e2018-05-17 10:40:04 -04001551 }
Brian Osman1179fcf2020-10-08 16:04:40 -04001552 } else if (e->is<InterfaceBlock>()) {
1553 const InterfaceBlock& intf = e->as<InterfaceBlock>();
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001554 if (intf.typeName() == "sk_PerVertex") {
Timothy Lianga06f2152018-05-24 15:33:31 -04001555 continue;
1556 }
1557 this->write(", constant ");
John Stilesb4418502021-02-04 10:57:08 -05001558 this->writeType(intf.variable().type());
Timothy Lianga06f2152018-05-24 15:33:31 -04001559 this->write("& " );
1560 this->write(fInterfaceBlockNameMap[&intf]);
1561 this->write(" [[buffer(");
John Stilesda5cdf62021-01-28 11:47:29 -05001562 this->write(to_string(this->getUniformBinding(intf.variable().modifiers())));
Timothy Lianga06f2152018-05-24 15:33:31 -04001563 this->write(")]]");
Timothy Liang6403b0e2018-05-17 10:40:04 -04001564 }
1565 }
John Stiles270cec22021-02-17 12:59:36 -05001566 if (fProgram.fConfig->fKind == ProgramKind::kFragment) {
Jim Van Verth6bc650e2019-02-07 14:53:23 -05001567 if (fProgram.fInputs.fRTHeight && fInterfaceBlockNameMap.empty()) {
Timothy Liang5422f9a2018-08-10 10:57:55 -04001568 this->write(", constant sksl_synthetic_uniforms& _anonInterface0 [[buffer(1)]]");
Ethan Nicholasf931e402019-07-26 15:40:33 -04001569 fRTHeightName = "_anonInterface0.u_skRTHeight";
Timothy Liang5422f9a2018-08-10 10:57:55 -04001570 }
Timothy Liang7b8875d2018-08-10 09:42:31 -04001571 this->write(", bool _frontFacing [[front_facing]]");
Timothy Liang7d637782018-06-05 09:58:07 -04001572 this->write(", float4 _fragCoord [[position]]");
John Stiles270cec22021-02-17 12:59:36 -05001573 } else if (fProgram.fConfig->fKind == ProgramKind::kVertex) {
Timothy Liangdc89f192018-06-13 09:20:31 -04001574 this->write(", uint sk_VertexID [[vertex_id]], uint sk_InstanceID [[instance_id]]");
Timothy Liang7d637782018-06-05 09:58:07 -04001575 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001576 separator = ", ";
1577 } else {
John Stilesb4418502021-02-04 10:57:08 -05001578 this->writeType(f.returnType());
Timothy Liang651286f2018-06-07 09:55:33 -04001579 this->write(" ");
John Stilese1068342021-03-22 11:57:41 -04001580 this->writeName(f.mangledName());
Timothy Liang651286f2018-06-07 09:55:33 -04001581 this->write("(");
John Stiles06b84ef2020-12-09 12:35:48 -05001582 this->writeFunctionRequirementParams(f, separator);
Ethan Nicholascc305772017-10-13 16:17:45 -04001583 }
John Stiles569249b2020-11-03 12:18:22 -05001584 for (const auto& param : f.parameters()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001585 this->write(separator);
1586 separator = ", ";
John Stiles06b84ef2020-12-09 12:35:48 -05001587 this->writeModifiers(param->modifiers(), /*globalContext=*/false);
Ethan Nicholas30d30222020-09-11 12:27:26 -04001588 const Type* type = &param->type();
John Stilesb4418502021-02-04 10:57:08 -05001589 this->writeType(*type);
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001590 if (param->modifiers().fFlags & Modifiers::kOut_Flag) {
John Stilesf2bd5012020-12-04 11:58:26 -05001591 this->write("&");
Ethan Nicholascc305772017-10-13 16:17:45 -04001592 }
Timothy Liang651286f2018-06-07 09:55:33 -04001593 this->write(" ");
Ethan Nicholase2c49992020-10-05 11:49:11 -04001594 this->writeName(param->name());
Ethan Nicholascc305772017-10-13 16:17:45 -04001595 }
John Stiles569249b2020-11-03 12:18:22 -05001596 this->write(")");
1597 return true;
1598}
Ethan Nicholascc305772017-10-13 16:17:45 -04001599
John Stiles569249b2020-11-03 12:18:22 -05001600void MetalCodeGenerator::writeFunctionPrototype(const FunctionPrototype& f) {
1601 this->writeFunctionDeclaration(f.declaration());
1602 this->writeLine(";");
1603}
1604
John Stiles986c7fb2020-12-01 14:44:56 -05001605static bool is_block_ending_with_return(const Statement* stmt) {
1606 // This function detects (potentially nested) blocks that end in a return statement.
1607 if (!stmt->is<Block>()) {
1608 return false;
1609 }
1610 const StatementArray& block = stmt->as<Block>().children();
1611 for (int index = block.count(); index--; ) {
1612 const Statement& stmt = *block[index];
1613 if (stmt.is<ReturnStatement>()) {
1614 return true;
1615 }
1616 if (stmt.is<Block>()) {
1617 return is_block_ending_with_return(&stmt);
1618 }
1619 if (!stmt.is<Nop>()) {
1620 break;
1621 }
1622 }
1623 return false;
1624}
1625
John Stiles569249b2020-11-03 12:18:22 -05001626void MetalCodeGenerator::writeFunction(const FunctionDefinition& f) {
John Stiles270cec22021-02-17 12:59:36 -05001627 SkASSERT(!fProgram.fConfig->fSettings.fFragColorIsInOut);
Brian Salomondc092132018-04-04 10:14:16 -04001628
John Stiles569249b2020-11-03 12:18:22 -05001629 if (!this->writeFunctionDeclaration(f.declaration())) {
1630 return;
1631 }
1632
John Stiles986c7fb2020-12-01 14:44:56 -05001633 fCurrentFunction = &f.declaration();
1634 SkScopeExit clearCurrentFunction([&] { fCurrentFunction = nullptr; });
1635
John Stiles569249b2020-11-03 12:18:22 -05001636 this->writeLine(" {");
1637
John Stilese8da4d22021-03-24 09:19:45 -04001638 if (f.declaration().isMain()) {
John Stilescdcdb042020-07-06 09:03:51 -04001639 this->writeGlobalInit();
John Stilesf7410bd2021-01-19 13:07:55 -05001640 this->writeLine(" Outputs _out;");
John Stiles37279172021-01-21 22:24:28 -05001641 this->writeLine(" (void)_out;");
Ethan Nicholascc305772017-10-13 16:17:45 -04001642 }
John Stilesc67b3622020-05-28 17:53:13 -04001643
Ethan Nicholascc305772017-10-13 16:17:45 -04001644 fFunctionHeader = "";
Ethan Nicholascc305772017-10-13 16:17:45 -04001645 StringStream buffer;
John Stiles44532372020-12-07 12:33:55 -05001646 {
1647 AutoOutputStream outputToBuffer(this, &buffer);
1648 fIndentation++;
1649 for (const std::unique_ptr<Statement>& stmt : f.body()->as<Block>().children()) {
1650 if (!stmt->isEmpty()) {
1651 this->writeStatement(*stmt);
John Stilese8b5a732021-03-12 13:25:52 -05001652 this->finishLine();
John Stiles44532372020-12-07 12:33:55 -05001653 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001654 }
John Stilese8da4d22021-03-24 09:19:45 -04001655 if (f.declaration().isMain()) {
John Stiles44532372020-12-07 12:33:55 -05001656 // If the main function doesn't end with a return, we need to synthesize one here.
1657 if (!is_block_ending_with_return(f.body().get())) {
1658 this->writeReturnStatementFromMain();
John Stilese8b5a732021-03-12 13:25:52 -05001659 this->finishLine();
John Stiles44532372020-12-07 12:33:55 -05001660 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001661 }
John Stiles44532372020-12-07 12:33:55 -05001662 fIndentation--;
1663 this->writeLine("}");
Ethan Nicholascc305772017-10-13 16:17:45 -04001664 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001665 this->write(fFunctionHeader);
1666 this->write(buffer.str());
1667}
1668
1669void MetalCodeGenerator::writeModifiers(const Modifiers& modifiers,
John Stiles06b84ef2020-12-09 12:35:48 -05001670 bool globalContext) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001671 if (modifiers.fFlags & Modifiers::kOut_Flag) {
1672 this->write("thread ");
1673 }
1674 if (modifiers.fFlags & Modifiers::kConst_Flag) {
John Stiles0bd55782021-02-09 18:29:40 -05001675 this->write("const ");
Ethan Nicholascc305772017-10-13 16:17:45 -04001676 }
1677}
1678
1679void MetalCodeGenerator::writeInterfaceBlock(const InterfaceBlock& intf) {
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001680 if ("sk_PerVertex" == intf.typeName()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001681 return;
1682 }
John Stiles06b84ef2020-12-09 12:35:48 -05001683 this->writeModifiers(intf.variable().modifiers(), /*globalContext=*/true);
Timothy Liangdc89f192018-06-13 09:20:31 -04001684 this->write("struct ");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001685 this->writeLine(intf.typeName() + " {");
1686 const Type* structType = &intf.variable().type();
John Stilesbb43b7e2020-12-03 17:36:32 -05001687 if (structType->isArray()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001688 structType = &structType->componentType();
1689 }
Timothy Liangdc89f192018-06-13 09:20:31 -04001690 fIndentation++;
John Stiles3dba3ee2020-12-02 23:35:49 -05001691 this->writeFields(structType->fields(), structType->fOffset, &intf);
Jim Van Verth3d482992019-02-07 10:48:05 -05001692 if (fProgram.fInputs.fRTHeight) {
Timothy Liang7d637782018-06-05 09:58:07 -04001693 this->writeLine("float u_skRTHeight;");
Ethan Nicholascc305772017-10-13 16:17:45 -04001694 }
1695 fIndentation--;
1696 this->write("}");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001697 if (intf.instanceName().size()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001698 this->write(" ");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001699 this->write(intf.instanceName());
John Stilesd39aec02020-12-03 10:42:26 -05001700 if (intf.arraySize() > 0) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001701 this->write("[");
John Stilesd39aec02020-12-03 10:42:26 -05001702 this->write(to_string(intf.arraySize()));
Ethan Nicholascc305772017-10-13 16:17:45 -04001703 this->write("]");
John Stilesd39aec02020-12-03 10:42:26 -05001704 } else if (intf.arraySize() == Type::kUnsizedArray){
1705 this->write("[]");
Ethan Nicholascc305772017-10-13 16:17:45 -04001706 }
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001707 fInterfaceBlockNameMap[&intf] = intf.instanceName();
Timothy Lianga06f2152018-05-24 15:33:31 -04001708 } else {
Timothy Liang7d637782018-06-05 09:58:07 -04001709 fInterfaceBlockNameMap[&intf] = "_anonInterface" + to_string(fAnonInterfaceCount++);
Ethan Nicholascc305772017-10-13 16:17:45 -04001710 }
1711 this->writeLine(";");
1712}
1713
Timothy Liangdc89f192018-06-13 09:20:31 -04001714void MetalCodeGenerator::writeFields(const std::vector<Type::Field>& fields, int parentOffset,
1715 const InterfaceBlock* parentIntf) {
Timothy Liang609fbe32018-08-10 16:40:49 -04001716 MemoryLayout memoryLayout(MemoryLayout::kMetal_Standard);
Timothy Liangdc89f192018-06-13 09:20:31 -04001717 int currentOffset = 0;
1718 for (const auto& field: fields) {
1719 int fieldOffset = field.fModifiers.fLayout.fOffset;
1720 const Type* fieldType = field.fType;
John Stiles21f5f452020-11-30 09:57:59 -05001721 if (!MemoryLayout::LayoutIsSupported(*fieldType)) {
John Stiles0023c0c2020-11-16 13:32:18 -05001722 fErrors.error(parentOffset, "type '" + fieldType->name() + "' is not permitted here");
1723 return;
1724 }
Timothy Liangdc89f192018-06-13 09:20:31 -04001725 if (fieldOffset != -1) {
1726 if (currentOffset > fieldOffset) {
1727 fErrors.error(parentOffset,
John Stilesd7199b22020-12-30 16:22:58 -05001728 "offset of field '" + field.fName + "' must be at least " +
1729 to_string((int) currentOffset));
Brian Osman8609a242020-09-08 14:01:49 -04001730 return;
Timothy Liangdc89f192018-06-13 09:20:31 -04001731 } else if (currentOffset < fieldOffset) {
1732 this->write("char pad");
1733 this->write(to_string(fPaddingCount++));
1734 this->write("[");
1735 this->write(to_string(fieldOffset - currentOffset));
1736 this->writeLine("];");
1737 currentOffset = fieldOffset;
1738 }
1739 int alignment = memoryLayout.alignment(*fieldType);
1740 if (fieldOffset % alignment) {
1741 fErrors.error(parentOffset,
1742 "offset of field '" + field.fName + "' must be a multiple of " +
1743 to_string((int) alignment));
Brian Osman8609a242020-09-08 14:01:49 -04001744 return;
Timothy Liangdc89f192018-06-13 09:20:31 -04001745 }
1746 }
Brian Osman8609a242020-09-08 14:01:49 -04001747 size_t fieldSize = memoryLayout.size(*fieldType);
1748 if (fieldSize > static_cast<size_t>(std::numeric_limits<int>::max() - currentOffset)) {
1749 fErrors.error(parentOffset, "field offset overflow");
1750 return;
1751 }
1752 currentOffset += fieldSize;
John Stiles06b84ef2020-12-09 12:35:48 -05001753 this->writeModifiers(field.fModifiers, /*globalContext=*/false);
John Stilesb4418502021-02-04 10:57:08 -05001754 this->writeType(*fieldType);
Timothy Liangdc89f192018-06-13 09:20:31 -04001755 this->write(" ");
1756 this->writeName(field.fName);
Timothy Liangdc89f192018-06-13 09:20:31 -04001757 this->writeLine(";");
1758 if (parentIntf) {
1759 fInterfaceBlockMap[&field] = parentIntf;
1760 }
1761 }
1762}
1763
Ethan Nicholascc305772017-10-13 16:17:45 -04001764void MetalCodeGenerator::writeVarInitializer(const Variable& var, const Expression& value) {
Brian Osman00185012021-02-04 16:07:11 -05001765 this->writeExpression(value, Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001766}
1767
Timothy Liang651286f2018-06-07 09:55:33 -04001768void MetalCodeGenerator::writeName(const String& name) {
1769 if (fReservedWords.find(name) != fReservedWords.end()) {
1770 this->write("_"); // adding underscore before name to avoid conflict with reserved words
1771 }
1772 this->write(name);
1773}
1774
John Stilesb4418502021-02-04 10:57:08 -05001775void MetalCodeGenerator::writeVarDeclaration(const VarDeclaration& varDecl, bool global) {
1776 if (global && !(varDecl.var().modifiers().fFlags & Modifiers::kConst_Flag)) {
Brian Osmanc0213602020-10-06 14:43:32 -04001777 return;
Ethan Nicholascc305772017-10-13 16:17:45 -04001778 }
John Stilesb4418502021-02-04 10:57:08 -05001779 this->writeModifiers(varDecl.var().modifiers(), global);
1780 this->writeType(varDecl.var().type());
Brian Osmanc0213602020-10-06 14:43:32 -04001781 this->write(" ");
John Stilesb4418502021-02-04 10:57:08 -05001782 this->writeName(varDecl.var().name());
1783 if (varDecl.value()) {
Brian Osmanc0213602020-10-06 14:43:32 -04001784 this->write(" = ");
John Stilesb4418502021-02-04 10:57:08 -05001785 this->writeVarInitializer(varDecl.var(), *varDecl.value());
Brian Osmanc0213602020-10-06 14:43:32 -04001786 }
1787 this->write(";");
Ethan Nicholascc305772017-10-13 16:17:45 -04001788}
1789
1790void MetalCodeGenerator::writeStatement(const Statement& s) {
Ethan Nicholase6592142020-09-08 10:22:09 -04001791 switch (s.kind()) {
1792 case Statement::Kind::kBlock:
John Stiles26f98502020-08-18 09:30:51 -04001793 this->writeBlock(s.as<Block>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001794 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001795 case Statement::Kind::kExpression:
Brian Osman00185012021-02-04 16:07:11 -05001796 this->writeExpression(*s.as<ExpressionStatement>().expression(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001797 this->write(";");
1798 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001799 case Statement::Kind::kReturn:
John Stiles26f98502020-08-18 09:30:51 -04001800 this->writeReturnStatement(s.as<ReturnStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001801 break;
Brian Osmanc0213602020-10-06 14:43:32 -04001802 case Statement::Kind::kVarDeclaration:
1803 this->writeVarDeclaration(s.as<VarDeclaration>(), false);
Ethan Nicholascc305772017-10-13 16:17:45 -04001804 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001805 case Statement::Kind::kIf:
John Stiles26f98502020-08-18 09:30:51 -04001806 this->writeIfStatement(s.as<IfStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001807 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001808 case Statement::Kind::kFor:
John Stiles26f98502020-08-18 09:30:51 -04001809 this->writeForStatement(s.as<ForStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001810 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001811 case Statement::Kind::kDo:
John Stiles26f98502020-08-18 09:30:51 -04001812 this->writeDoStatement(s.as<DoStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001813 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001814 case Statement::Kind::kSwitch:
John Stiles26f98502020-08-18 09:30:51 -04001815 this->writeSwitchStatement(s.as<SwitchStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001816 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001817 case Statement::Kind::kBreak:
Ethan Nicholascc305772017-10-13 16:17:45 -04001818 this->write("break;");
1819 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001820 case Statement::Kind::kContinue:
Ethan Nicholascc305772017-10-13 16:17:45 -04001821 this->write("continue;");
1822 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001823 case Statement::Kind::kDiscard:
Timothy Lianga06f2152018-05-24 15:33:31 -04001824 this->write("discard_fragment();");
Ethan Nicholascc305772017-10-13 16:17:45 -04001825 break;
John Stiles98c1f822020-09-09 14:18:53 -04001826 case Statement::Kind::kInlineMarker:
Ethan Nicholase6592142020-09-08 10:22:09 -04001827 case Statement::Kind::kNop:
Ethan Nicholascc305772017-10-13 16:17:45 -04001828 this->write(";");
1829 break;
1830 default:
John Stileseada7bc2021-02-02 16:29:32 -05001831 SkDEBUGFAILF("unsupported statement: %s", s.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -05001832 break;
Ethan Nicholascc305772017-10-13 16:17:45 -04001833 }
1834}
1835
Ethan Nicholascc305772017-10-13 16:17:45 -04001836void MetalCodeGenerator::writeBlock(const Block& b) {
John Stiles3744bd62021-01-26 13:49:43 -05001837 // Write scope markers if this block is a scope, or if the block is empty (since we need to emit
1838 // something here to make the code valid).
1839 bool isScope = b.isScope() || b.isEmpty();
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001840 if (isScope) {
Ethan Nicholas70728ef2020-05-28 07:09:00 -04001841 this->writeLine("{");
1842 fIndentation++;
1843 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001844 for (const std::unique_ptr<Statement>& stmt : b.children()) {
1845 if (!stmt->isEmpty()) {
1846 this->writeStatement(*stmt);
John Stilese8b5a732021-03-12 13:25:52 -05001847 this->finishLine();
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001848 }
1849 }
1850 if (isScope) {
Ethan Nicholas70728ef2020-05-28 07:09:00 -04001851 fIndentation--;
1852 this->write("}");
1853 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001854}
1855
1856void MetalCodeGenerator::writeIfStatement(const IfStatement& stmt) {
1857 this->write("if (");
Brian Osman00185012021-02-04 16:07:11 -05001858 this->writeExpression(*stmt.test(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001859 this->write(") ");
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04001860 this->writeStatement(*stmt.ifTrue());
1861 if (stmt.ifFalse()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001862 this->write(" else ");
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04001863 this->writeStatement(*stmt.ifFalse());
Ethan Nicholascc305772017-10-13 16:17:45 -04001864 }
1865}
1866
1867void MetalCodeGenerator::writeForStatement(const ForStatement& f) {
Brian Osmand6f23382020-12-15 17:08:59 -05001868 // Emit loops of the form 'for(;test;)' as 'while(test)', which is probably how they started
1869 if (!f.initializer() && f.test() && !f.next()) {
1870 this->write("while (");
Brian Osman00185012021-02-04 16:07:11 -05001871 this->writeExpression(*f.test(), Precedence::kTopLevel);
Brian Osmand6f23382020-12-15 17:08:59 -05001872 this->write(") ");
1873 this->writeStatement(*f.statement());
1874 return;
1875 }
1876
Ethan Nicholascc305772017-10-13 16:17:45 -04001877 this->write("for (");
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04001878 if (f.initializer() && !f.initializer()->isEmpty()) {
1879 this->writeStatement(*f.initializer());
Ethan Nicholascc305772017-10-13 16:17:45 -04001880 } else {
1881 this->write("; ");
1882 }
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04001883 if (f.test()) {
Brian Osman00185012021-02-04 16:07:11 -05001884 this->writeExpression(*f.test(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001885 }
1886 this->write("; ");
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04001887 if (f.next()) {
Brian Osman00185012021-02-04 16:07:11 -05001888 this->writeExpression(*f.next(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001889 }
1890 this->write(") ");
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04001891 this->writeStatement(*f.statement());
Ethan Nicholascc305772017-10-13 16:17:45 -04001892}
1893
Ethan Nicholascc305772017-10-13 16:17:45 -04001894void MetalCodeGenerator::writeDoStatement(const DoStatement& d) {
1895 this->write("do ");
Ethan Nicholas1fd61162020-09-28 13:14:19 -04001896 this->writeStatement(*d.statement());
Ethan Nicholascc305772017-10-13 16:17:45 -04001897 this->write(" while (");
Brian Osman00185012021-02-04 16:07:11 -05001898 this->writeExpression(*d.test(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001899 this->write(");");
1900}
1901
1902void MetalCodeGenerator::writeSwitchStatement(const SwitchStatement& s) {
1903 this->write("switch (");
Brian Osman00185012021-02-04 16:07:11 -05001904 this->writeExpression(*s.value(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001905 this->writeLine(") {");
1906 fIndentation++;
John Stilesb23a64b2021-03-11 08:27:59 -05001907 for (const std::unique_ptr<Statement>& stmt : s.cases()) {
1908 const SwitchCase& c = stmt->as<SwitchCase>();
1909 if (c.value()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001910 this->write("case ");
John Stilesb23a64b2021-03-11 08:27:59 -05001911 this->writeExpression(*c.value(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001912 this->writeLine(":");
1913 } else {
1914 this->writeLine("default:");
1915 }
John Stilesb23a64b2021-03-11 08:27:59 -05001916 if (!c.statement()->isEmpty()) {
John Stilesc3ce43b2021-03-09 15:37:01 -05001917 fIndentation++;
John Stilesb23a64b2021-03-11 08:27:59 -05001918 this->writeStatement(*c.statement());
John Stilese8b5a732021-03-12 13:25:52 -05001919 this->finishLine();
John Stilesc3ce43b2021-03-09 15:37:01 -05001920 fIndentation--;
Ethan Nicholascc305772017-10-13 16:17:45 -04001921 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001922 }
1923 fIndentation--;
1924 this->write("}");
1925}
1926
John Stiles986c7fb2020-12-01 14:44:56 -05001927void MetalCodeGenerator::writeReturnStatementFromMain() {
1928 // main functions in Metal return a magic _out parameter that doesn't exist in SkSL.
John Stiles270cec22021-02-17 12:59:36 -05001929 switch (fProgram.fConfig->fKind) {
John Stilesdbd4e6f2021-02-16 13:29:15 -05001930 case ProgramKind::kFragment:
John Stilesf7410bd2021-01-19 13:07:55 -05001931 this->write("return _out;");
John Stiles986c7fb2020-12-01 14:44:56 -05001932 break;
John Stilesdbd4e6f2021-02-16 13:29:15 -05001933 case ProgramKind::kVertex:
John Stilesf7410bd2021-01-19 13:07:55 -05001934 this->write("return (_out.sk_Position.y = -_out.sk_Position.y, _out);");
John Stiles986c7fb2020-12-01 14:44:56 -05001935 break;
1936 default:
1937 SkDEBUGFAIL("unsupported kind of program");
1938 }
1939}
1940
Ethan Nicholascc305772017-10-13 16:17:45 -04001941void MetalCodeGenerator::writeReturnStatement(const ReturnStatement& r) {
John Stilese8da4d22021-03-24 09:19:45 -04001942 if (fCurrentFunction && fCurrentFunction->isMain()) {
John Stiles986c7fb2020-12-01 14:44:56 -05001943 if (r.expression()) {
John Stiles97d18172021-01-22 16:47:42 -05001944 if (r.expression()->type() == *fContext.fTypes.fHalf4) {
1945 this->write("_out.sk_FragColor = ");
Brian Osman00185012021-02-04 16:07:11 -05001946 this->writeExpression(*r.expression(), Precedence::kTopLevel);
John Stiles97d18172021-01-22 16:47:42 -05001947 this->writeLine(";");
1948 } else {
1949 fErrors.error(r.fOffset, "Metal does not support returning '" +
1950 r.expression()->type().description() + "' from main()");
1951 }
John Stiles986c7fb2020-12-01 14:44:56 -05001952 }
1953 this->writeReturnStatementFromMain();
1954 return;
1955 }
1956
Ethan Nicholascc305772017-10-13 16:17:45 -04001957 this->write("return");
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04001958 if (r.expression()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001959 this->write(" ");
Brian Osman00185012021-02-04 16:07:11 -05001960 this->writeExpression(*r.expression(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001961 }
1962 this->write(";");
1963}
1964
Michael Ludwigbf58add2021-03-16 10:40:11 -04001965void MetalCodeGenerator::writeHeader() {
1966 this->write("#include <metal_stdlib>\n");
1967 this->write("#include <simd/simd.h>\n");
1968 this->write("using namespace metal;\n");
1969}
1970
Ethan Nicholascc305772017-10-13 16:17:45 -04001971void MetalCodeGenerator::writeUniformStruct() {
Brian Osman133724c2020-10-28 14:14:39 -04001972 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04001973 if (e->is<GlobalVarDeclaration>()) {
1974 const GlobalVarDeclaration& decls = e->as<GlobalVarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001975 const Variable& var = decls.declaration()->as<VarDeclaration>().var();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001976 if (var.modifiers().fFlags & Modifiers::kUniform_Flag &&
Brian Osmanc0213602020-10-06 14:43:32 -04001977 var.type().typeKind() != Type::TypeKind::kSampler) {
John Stilesda5cdf62021-01-28 11:47:29 -05001978 int uniformSet = this->getUniformSet(var.modifiers());
John Stilesd8fc95d2021-01-26 16:22:53 -05001979 // Make sure that the program's uniform-set value is consistent throughout.
Ethan Nicholascc305772017-10-13 16:17:45 -04001980 if (-1 == fUniformBuffer) {
1981 this->write("struct Uniforms {\n");
John Stilesd8fc95d2021-01-26 16:22:53 -05001982 fUniformBuffer = uniformSet;
1983 } else if (uniformSet != fUniformBuffer) {
1984 fErrors.error(decls.fOffset, "Metal backend requires all uniforms to have "
1985 "the same 'layout(set=...)'");
Ethan Nicholascc305772017-10-13 16:17:45 -04001986 }
1987 this->write(" ");
John Stilesb4418502021-02-04 10:57:08 -05001988 this->writeType(var.type());
Ethan Nicholascc305772017-10-13 16:17:45 -04001989 this->write(" ");
Brian Osmanc0213602020-10-06 14:43:32 -04001990 this->writeName(var.name());
Ethan Nicholascc305772017-10-13 16:17:45 -04001991 this->write(";\n");
1992 }
1993 }
1994 }
1995 if (-1 != fUniformBuffer) {
1996 this->write("};\n");
1997 }
1998}
1999
2000void MetalCodeGenerator::writeInputStruct() {
2001 this->write("struct Inputs {\n");
Brian Osman133724c2020-10-28 14:14:39 -04002002 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04002003 if (e->is<GlobalVarDeclaration>()) {
2004 const GlobalVarDeclaration& decls = e->as<GlobalVarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04002005 const Variable& var = decls.declaration()->as<VarDeclaration>().var();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002006 if (var.modifiers().fFlags & Modifiers::kIn_Flag &&
2007 -1 == var.modifiers().fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002008 this->write(" ");
John Stilesb4418502021-02-04 10:57:08 -05002009 this->writeType(var.type());
Ethan Nicholascc305772017-10-13 16:17:45 -04002010 this->write(" ");
Brian Osmanc0213602020-10-06 14:43:32 -04002011 this->writeName(var.name());
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002012 if (-1 != var.modifiers().fLayout.fLocation) {
John Stiles270cec22021-02-17 12:59:36 -05002013 if (fProgram.fConfig->fKind == ProgramKind::kVertex) {
Brian Osmanc0213602020-10-06 14:43:32 -04002014 this->write(" [[attribute(" +
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002015 to_string(var.modifiers().fLayout.fLocation) + ")]]");
John Stiles270cec22021-02-17 12:59:36 -05002016 } else if (fProgram.fConfig->fKind == ProgramKind::kFragment) {
Brian Osmanc0213602020-10-06 14:43:32 -04002017 this->write(" [[user(locn" +
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002018 to_string(var.modifiers().fLayout.fLocation) + ")]]");
Ethan Nicholascc305772017-10-13 16:17:45 -04002019 }
2020 }
2021 this->write(";\n");
2022 }
2023 }
2024 }
2025 this->write("};\n");
2026}
2027
2028void MetalCodeGenerator::writeOutputStruct() {
2029 this->write("struct Outputs {\n");
John Stiles270cec22021-02-17 12:59:36 -05002030 if (fProgram.fConfig->fKind == ProgramKind::kVertex) {
Timothy Liangb8eeb802018-07-23 16:46:16 -04002031 this->write(" float4 sk_Position [[position]];\n");
John Stiles270cec22021-02-17 12:59:36 -05002032 } else if (fProgram.fConfig->fKind == ProgramKind::kFragment) {
Timothy Liangde0be802018-08-10 13:48:08 -04002033 this->write(" float4 sk_FragColor [[color(0)]];\n");
Timothy Liang7d637782018-06-05 09:58:07 -04002034 }
Brian Osman133724c2020-10-28 14:14:39 -04002035 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04002036 if (e->is<GlobalVarDeclaration>()) {
2037 const GlobalVarDeclaration& decls = e->as<GlobalVarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04002038 const Variable& var = decls.declaration()->as<VarDeclaration>().var();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002039 if (var.modifiers().fFlags & Modifiers::kOut_Flag &&
2040 -1 == var.modifiers().fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002041 this->write(" ");
John Stilesb4418502021-02-04 10:57:08 -05002042 this->writeType(var.type());
Ethan Nicholascc305772017-10-13 16:17:45 -04002043 this->write(" ");
Brian Osmanc0213602020-10-06 14:43:32 -04002044 this->writeName(var.name());
John Stiles842b3592020-12-01 10:36:37 -05002045
2046 int location = var.modifiers().fLayout.fLocation;
2047 if (location < 0) {
2048 fErrors.error(var.fOffset,
2049 "Metal out variables must have 'layout(location=...)'");
John Stiles270cec22021-02-17 12:59:36 -05002050 } else if (fProgram.fConfig->fKind == ProgramKind::kVertex) {
John Stiles842b3592020-12-01 10:36:37 -05002051 this->write(" [[user(locn" + to_string(location) + ")]]");
John Stiles270cec22021-02-17 12:59:36 -05002052 } else if (fProgram.fConfig->fKind == ProgramKind::kFragment) {
John Stiles842b3592020-12-01 10:36:37 -05002053 this->write(" [[color(" + to_string(location) + ")");
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002054 int colorIndex = var.modifiers().fLayout.fIndex;
Brian Osmanc0213602020-10-06 14:43:32 -04002055 if (colorIndex) {
2056 this->write(", index(" + to_string(colorIndex) + ")");
Timothy Liang7d637782018-06-05 09:58:07 -04002057 }
Brian Osmanc0213602020-10-06 14:43:32 -04002058 this->write("]]");
Ethan Nicholascc305772017-10-13 16:17:45 -04002059 }
2060 this->write(";\n");
2061 }
2062 }
Timothy Liang7d637782018-06-05 09:58:07 -04002063 }
John Stiles270cec22021-02-17 12:59:36 -05002064 if (fProgram.fConfig->fKind == ProgramKind::kVertex) {
Jim Van Verth3913d3e2020-08-31 15:16:57 -04002065 this->write(" float sk_PointSize [[point_size]];\n");
Timothy Liang7d637782018-06-05 09:58:07 -04002066 }
2067 this->write("};\n");
2068}
2069
2070void MetalCodeGenerator::writeInterfaceBlocks() {
2071 bool wroteInterfaceBlock = false;
Brian Osman133724c2020-10-28 14:14:39 -04002072 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04002073 if (e->is<InterfaceBlock>()) {
2074 this->writeInterfaceBlock(e->as<InterfaceBlock>());
Timothy Liang7d637782018-06-05 09:58:07 -04002075 wroteInterfaceBlock = true;
2076 }
2077 }
Jim Van Verth3d482992019-02-07 10:48:05 -05002078 if (!wroteInterfaceBlock && fProgram.fInputs.fRTHeight) {
Timothy Liang7d637782018-06-05 09:58:07 -04002079 this->writeLine("struct sksl_synthetic_uniforms {");
2080 this->writeLine(" float u_skRTHeight;");
2081 this->writeLine("};");
2082 }
Ethan Nicholascc305772017-10-13 16:17:45 -04002083}
2084
John Stilesdc75a972020-11-25 16:24:55 -05002085void MetalCodeGenerator::writeStructDefinitions() {
2086 for (const ProgramElement* e : fProgram.elements()) {
2087 if (e->is<StructDefinition>()) {
Brian Osman02bc5222021-01-28 11:00:20 -05002088 this->writeStructDefinition(e->as<StructDefinition>());
John Stilesdc75a972020-11-25 16:24:55 -05002089 }
2090 }
2091}
2092
John Stilescdcdb042020-07-06 09:03:51 -04002093void MetalCodeGenerator::visitGlobalStruct(GlobalStructVisitor* visitor) {
2094 // Visit the interface blocks.
2095 for (const auto& [interfaceType, interfaceName] : fInterfaceBlockNameMap) {
John Stilesfdb8dbe2020-12-04 11:00:03 -05002096 visitor->visitInterfaceBlock(*interfaceType, interfaceName);
John Stilescdcdb042020-07-06 09:03:51 -04002097 }
Brian Osman133724c2020-10-28 14:14:39 -04002098 for (const ProgramElement* element : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04002099 if (!element->is<GlobalVarDeclaration>()) {
John Stilescdcdb042020-07-06 09:03:51 -04002100 continue;
Timothy Liang7d637782018-06-05 09:58:07 -04002101 }
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04002102 const GlobalVarDeclaration& global = element->as<GlobalVarDeclaration>();
2103 const VarDeclaration& decl = global.declaration()->as<VarDeclaration>();
2104 const Variable& var = decl.var();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002105 if ((!var.modifiers().fFlags && -1 == var.modifiers().fLayout.fBuiltin) ||
Brian Osmanc0213602020-10-06 14:43:32 -04002106 var.type().typeKind() == Type::TypeKind::kSampler) {
2107 if (var.type().typeKind() == Type::TypeKind::kSampler) {
2108 // Samplers are represented as a "texture/sampler" duo in the global struct.
John Stilesfdb8dbe2020-12-04 11:00:03 -05002109 visitor->visitTexture(var.type(), var.name());
2110 visitor->visitSampler(var.type(), String(var.name()) + SAMPLER_SUFFIX);
Brian Osmanc0213602020-10-06 14:43:32 -04002111 } else {
2112 // Visit a regular variable.
John Stilesfdb8dbe2020-12-04 11:00:03 -05002113 visitor->visitVariable(var, decl.value().get());
Timothy Liangee84fe12018-05-18 14:38:19 -04002114 }
2115 }
2116 }
John Stilescdcdb042020-07-06 09:03:51 -04002117}
2118
2119void MetalCodeGenerator::writeGlobalStruct() {
2120 class : public GlobalStructVisitor {
2121 public:
John Stilesfdb8dbe2020-12-04 11:00:03 -05002122 void visitInterfaceBlock(const InterfaceBlock& block, const String& blockName) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002123 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002124 fCodeGen->write(" constant ");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04002125 fCodeGen->write(block.typeName());
John Stilescdcdb042020-07-06 09:03:51 -04002126 fCodeGen->write("* ");
2127 fCodeGen->writeName(blockName);
2128 fCodeGen->write(";\n");
2129 }
John Stilesfdb8dbe2020-12-04 11:00:03 -05002130 void visitTexture(const Type& type, const String& name) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002131 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002132 fCodeGen->write(" ");
John Stilesb4418502021-02-04 10:57:08 -05002133 fCodeGen->writeType(type);
John Stilescdcdb042020-07-06 09:03:51 -04002134 fCodeGen->write(" ");
2135 fCodeGen->writeName(name);
2136 fCodeGen->write(";\n");
2137 }
John Stilesfdb8dbe2020-12-04 11:00:03 -05002138 void visitSampler(const Type&, const String& name) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002139 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002140 fCodeGen->write(" sampler ");
2141 fCodeGen->writeName(name);
2142 fCodeGen->write(";\n");
2143 }
John Stilesfdb8dbe2020-12-04 11:00:03 -05002144 void visitVariable(const Variable& var, const Expression* value) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002145 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002146 fCodeGen->write(" ");
John Stilesb4418502021-02-04 10:57:08 -05002147 fCodeGen->writeType(var.type());
John Stilescdcdb042020-07-06 09:03:51 -04002148 fCodeGen->write(" ");
Ethan Nicholase2c49992020-10-05 11:49:11 -04002149 fCodeGen->writeName(var.name());
John Stilescdcdb042020-07-06 09:03:51 -04002150 fCodeGen->write(";\n");
2151 }
John Stiles83f3b8d2020-12-07 17:52:25 -05002152 void addElement() {
John Stilescdcdb042020-07-06 09:03:51 -04002153 if (fFirst) {
2154 fCodeGen->write("struct Globals {\n");
2155 fFirst = false;
2156 }
2157 }
John Stiles83f3b8d2020-12-07 17:52:25 -05002158 void finish() {
John Stilescdcdb042020-07-06 09:03:51 -04002159 if (!fFirst) {
John Stiles83f3b8d2020-12-07 17:52:25 -05002160 fCodeGen->writeLine("};");
John Stilescdcdb042020-07-06 09:03:51 -04002161 fFirst = true;
2162 }
2163 }
2164
2165 MetalCodeGenerator* fCodeGen = nullptr;
2166 bool fFirst = true;
2167 } visitor;
2168
2169 visitor.fCodeGen = this;
2170 this->visitGlobalStruct(&visitor);
John Stiles83f3b8d2020-12-07 17:52:25 -05002171 visitor.finish();
John Stilescdcdb042020-07-06 09:03:51 -04002172}
2173
2174void MetalCodeGenerator::writeGlobalInit() {
2175 class : public GlobalStructVisitor {
2176 public:
John Stilesfdb8dbe2020-12-04 11:00:03 -05002177 void visitInterfaceBlock(const InterfaceBlock& blockType,
John Stilescdcdb042020-07-06 09:03:51 -04002178 const String& blockName) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002179 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002180 fCodeGen->write("&");
2181 fCodeGen->writeName(blockName);
2182 }
John Stilesfdb8dbe2020-12-04 11:00:03 -05002183 void visitTexture(const Type&, const String& name) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002184 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002185 fCodeGen->writeName(name);
2186 }
John Stilesfdb8dbe2020-12-04 11:00:03 -05002187 void visitSampler(const Type&, const String& name) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002188 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002189 fCodeGen->writeName(name);
2190 }
John Stilesfdb8dbe2020-12-04 11:00:03 -05002191 void visitVariable(const Variable& var, const Expression* value) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002192 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002193 if (value) {
2194 fCodeGen->writeVarInitializer(var, *value);
2195 } else {
2196 fCodeGen->write("{}");
2197 }
2198 }
John Stiles83f3b8d2020-12-07 17:52:25 -05002199 void addElement() {
John Stilescdcdb042020-07-06 09:03:51 -04002200 if (fFirst) {
John Stilesf7410bd2021-01-19 13:07:55 -05002201 fCodeGen->write(" Globals _globals{");
John Stilescdcdb042020-07-06 09:03:51 -04002202 fFirst = false;
2203 } else {
2204 fCodeGen->write(", ");
2205 }
2206 }
John Stiles83f3b8d2020-12-07 17:52:25 -05002207 void finish() {
John Stilescdcdb042020-07-06 09:03:51 -04002208 if (!fFirst) {
2209 fCodeGen->writeLine("};");
John Stiles37279172021-01-21 22:24:28 -05002210 fCodeGen->writeLine(" (void)_globals;");
John Stilescdcdb042020-07-06 09:03:51 -04002211 }
2212 }
2213 MetalCodeGenerator* fCodeGen = nullptr;
2214 bool fFirst = true;
2215 } visitor;
2216
2217 visitor.fCodeGen = this;
2218 this->visitGlobalStruct(&visitor);
John Stiles83f3b8d2020-12-07 17:52:25 -05002219 visitor.finish();
Timothy Liangee84fe12018-05-18 14:38:19 -04002220}
2221
Ethan Nicholascc305772017-10-13 16:17:45 -04002222void MetalCodeGenerator::writeProgramElement(const ProgramElement& e) {
Ethan Nicholase6592142020-09-08 10:22:09 -04002223 switch (e.kind()) {
2224 case ProgramElement::Kind::kExtension:
Ethan Nicholascc305772017-10-13 16:17:45 -04002225 break;
Brian Osmanc0213602020-10-06 14:43:32 -04002226 case ProgramElement::Kind::kGlobalVar: {
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04002227 const GlobalVarDeclaration& global = e.as<GlobalVarDeclaration>();
2228 const VarDeclaration& decl = global.declaration()->as<VarDeclaration>();
2229 int builtin = decl.var().modifiers().fLayout.fBuiltin;
Brian Osmanc0213602020-10-06 14:43:32 -04002230 if (-1 == builtin) {
2231 // normal var
2232 this->writeVarDeclaration(decl, true);
John Stilese8b5a732021-03-12 13:25:52 -05002233 this->finishLine();
Brian Osmanc0213602020-10-06 14:43:32 -04002234 } else if (SK_FRAGCOLOR_BUILTIN == builtin) {
2235 // ignore
Ethan Nicholascc305772017-10-13 16:17:45 -04002236 }
2237 break;
2238 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002239 case ProgramElement::Kind::kInterfaceBlock:
Timothy Liang7d637782018-06-05 09:58:07 -04002240 // handled in writeInterfaceBlocks, do nothing
Ethan Nicholascc305772017-10-13 16:17:45 -04002241 break;
John Stilesdc75a972020-11-25 16:24:55 -05002242 case ProgramElement::Kind::kStructDefinition:
2243 // Handled in writeStructDefinitions. Do nothing.
2244 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04002245 case ProgramElement::Kind::kFunction:
John Stiles3dc0da62020-08-19 17:48:31 -04002246 this->writeFunction(e.as<FunctionDefinition>());
Ethan Nicholascc305772017-10-13 16:17:45 -04002247 break;
John Stiles569249b2020-11-03 12:18:22 -05002248 case ProgramElement::Kind::kFunctionPrototype:
2249 this->writeFunctionPrototype(e.as<FunctionPrototype>());
2250 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04002251 case ProgramElement::Kind::kModifiers:
John Stiles06b84ef2020-12-09 12:35:48 -05002252 this->writeModifiers(e.as<ModifiersDeclaration>().modifiers(),
2253 /*globalContext=*/true);
Ethan Nicholascc305772017-10-13 16:17:45 -04002254 this->writeLine(";");
2255 break;
John Stiles712fd6b2020-11-25 22:25:43 -05002256 case ProgramElement::Kind::kEnum:
2257 break;
Ethan Nicholascc305772017-10-13 16:17:45 -04002258 default:
John Stileseada7bc2021-02-02 16:29:32 -05002259 SkDEBUGFAILF("unsupported program element: %s\n", e.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -05002260 break;
Ethan Nicholascc305772017-10-13 16:17:45 -04002261 }
2262}
2263
Ethan Nicholasff350cb2020-05-14 14:05:13 -04002264MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const Expression* e) {
2265 if (!e) {
2266 return kNo_Requirements;
2267 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002268 switch (e->kind()) {
2269 case Expression::Kind::kFunctionCall: {
John Stiles3dc0da62020-08-19 17:48:31 -04002270 const FunctionCall& f = e->as<FunctionCall>();
Ethan Nicholas0dec9922020-10-05 15:51:52 -04002271 Requirements result = this->requirements(f.function());
2272 for (const auto& arg : f.arguments()) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04002273 result |= this->requirements(arg.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002274 }
2275 return result;
2276 }
John Stiles2bec8ab2021-04-06 18:40:04 -04002277 case Expression::Kind::kConstructorComposite:
John Stiles268a73f2021-04-07 12:30:22 -04002278 case Expression::Kind::kConstructorCompositeCast:
John Stiles7384b372021-04-01 13:48:15 -04002279 case Expression::Kind::kConstructorArray:
John Stiles2938eea2021-04-01 18:58:25 -04002280 case Expression::Kind::kConstructorDiagonalMatrix:
John Stilesfd7252f2021-04-04 22:24:40 -04002281 case Expression::Kind::kConstructorScalarCast:
John Stiles268a73f2021-04-07 12:30:22 -04002282 case Expression::Kind::kConstructorSplat: {
John Stiles7384b372021-04-01 13:48:15 -04002283 const AnyConstructor& c = e->asAnyConstructor();
Ethan Nicholascc305772017-10-13 16:17:45 -04002284 Requirements result = kNo_Requirements;
John Stilesd8eb8752021-04-01 11:49:10 -04002285 for (const auto& arg : c.argumentSpan()) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04002286 result |= this->requirements(arg.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002287 }
2288 return result;
2289 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002290 case Expression::Kind::kFieldAccess: {
John Stiles3dc0da62020-08-19 17:48:31 -04002291 const FieldAccess& f = e->as<FieldAccess>();
Ethan Nicholas7a95b202020-10-09 11:55:40 -04002292 if (FieldAccess::OwnerKind::kAnonymousInterfaceBlock == f.ownerKind()) {
Timothy Liang7d637782018-06-05 09:58:07 -04002293 return kGlobals_Requirement;
2294 }
Ethan Nicholas7a95b202020-10-09 11:55:40 -04002295 return this->requirements(f.base().get());
Timothy Liang7d637782018-06-05 09:58:07 -04002296 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002297 case Expression::Kind::kSwizzle:
Ethan Nicholas6b4d5812020-10-12 16:11:51 -04002298 return this->requirements(e->as<Swizzle>().base().get());
Ethan Nicholase6592142020-09-08 10:22:09 -04002299 case Expression::Kind::kBinary: {
2300 const BinaryExpression& bin = e->as<BinaryExpression>();
John Stiles2d4f9592020-10-30 10:29:12 -04002301 return this->requirements(bin.left().get()) |
2302 this->requirements(bin.right().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002303 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002304 case Expression::Kind::kIndex: {
John Stiles3dc0da62020-08-19 17:48:31 -04002305 const IndexExpression& idx = e->as<IndexExpression>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04002306 return this->requirements(idx.base().get()) | this->requirements(idx.index().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002307 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002308 case Expression::Kind::kPrefix:
Ethan Nicholas444ccc62020-10-09 10:16:22 -04002309 return this->requirements(e->as<PrefixExpression>().operand().get());
Ethan Nicholase6592142020-09-08 10:22:09 -04002310 case Expression::Kind::kPostfix:
Ethan Nicholas444ccc62020-10-09 10:16:22 -04002311 return this->requirements(e->as<PostfixExpression>().operand().get());
Ethan Nicholase6592142020-09-08 10:22:09 -04002312 case Expression::Kind::kTernary: {
John Stiles3dc0da62020-08-19 17:48:31 -04002313 const TernaryExpression& t = e->as<TernaryExpression>();
Ethan Nicholasdd218162020-10-08 05:48:01 -04002314 return this->requirements(t.test().get()) | this->requirements(t.ifTrue().get()) |
2315 this->requirements(t.ifFalse().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002316 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002317 case Expression::Kind::kVariableReference: {
John Stiles3dc0da62020-08-19 17:48:31 -04002318 const VariableReference& v = e->as<VariableReference>();
Ethan Nicholas78686922020-10-08 06:46:27 -04002319 const Modifiers& modifiers = v.variable()->modifiers();
Ethan Nicholascc305772017-10-13 16:17:45 -04002320 Requirements result = kNo_Requirements;
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002321 if (modifiers.fLayout.fBuiltin == SK_FRAGCOORD_BUILTIN) {
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -04002322 result = kGlobals_Requirement | kFragCoord_Requirement;
Ethan Nicholas453f67f2020-10-09 10:43:45 -04002323 } else if (Variable::Storage::kGlobal == v.variable()->storage()) {
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002324 if (modifiers.fFlags & Modifiers::kIn_Flag) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002325 result = kInputs_Requirement;
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002326 } else if (modifiers.fFlags & Modifiers::kOut_Flag) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002327 result = kOutputs_Requirement;
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002328 } else if (modifiers.fFlags & Modifiers::kUniform_Flag &&
Ethan Nicholas78686922020-10-08 06:46:27 -04002329 v.variable()->type().typeKind() != Type::TypeKind::kSampler) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002330 result = kUniforms_Requirement;
Timothy Liangee84fe12018-05-18 14:38:19 -04002331 } else {
2332 result = kGlobals_Requirement;
Ethan Nicholascc305772017-10-13 16:17:45 -04002333 }
2334 }
2335 return result;
2336 }
2337 default:
2338 return kNo_Requirements;
2339 }
2340}
2341
Ethan Nicholasff350cb2020-05-14 14:05:13 -04002342MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const Statement* s) {
2343 if (!s) {
2344 return kNo_Requirements;
2345 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002346 switch (s->kind()) {
2347 case Statement::Kind::kBlock: {
Ethan Nicholascc305772017-10-13 16:17:45 -04002348 Requirements result = kNo_Requirements;
Ethan Nicholas7bd60432020-09-25 14:31:59 -04002349 for (const std::unique_ptr<Statement>& child : s->as<Block>().children()) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04002350 result |= this->requirements(child.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002351 }
2352 return result;
2353 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002354 case Statement::Kind::kVarDeclaration: {
John Stiles3dc0da62020-08-19 17:48:31 -04002355 const VarDeclaration& var = s->as<VarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04002356 return this->requirements(var.value().get());
Timothy Liang7d637782018-06-05 09:58:07 -04002357 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002358 case Statement::Kind::kExpression:
Ethan Nicholasd503a5a2020-09-30 09:29:55 -04002359 return this->requirements(s->as<ExpressionStatement>().expression().get());
Ethan Nicholase6592142020-09-08 10:22:09 -04002360 case Statement::Kind::kReturn: {
John Stiles3dc0da62020-08-19 17:48:31 -04002361 const ReturnStatement& r = s->as<ReturnStatement>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04002362 return this->requirements(r.expression().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002363 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002364 case Statement::Kind::kIf: {
John Stiles3dc0da62020-08-19 17:48:31 -04002365 const IfStatement& i = s->as<IfStatement>();
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04002366 return this->requirements(i.test().get()) |
2367 this->requirements(i.ifTrue().get()) |
2368 this->requirements(i.ifFalse().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002369 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002370 case Statement::Kind::kFor: {
John Stiles3dc0da62020-08-19 17:48:31 -04002371 const ForStatement& f = s->as<ForStatement>();
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04002372 return this->requirements(f.initializer().get()) |
2373 this->requirements(f.test().get()) |
2374 this->requirements(f.next().get()) |
2375 this->requirements(f.statement().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002376 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002377 case Statement::Kind::kDo: {
John Stiles3dc0da62020-08-19 17:48:31 -04002378 const DoStatement& d = s->as<DoStatement>();
Ethan Nicholas1fd61162020-09-28 13:14:19 -04002379 return this->requirements(d.test().get()) |
2380 this->requirements(d.statement().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002381 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002382 case Statement::Kind::kSwitch: {
John Stiles3dc0da62020-08-19 17:48:31 -04002383 const SwitchStatement& sw = s->as<SwitchStatement>();
Ethan Nicholas01b05e52020-10-22 15:53:41 -04002384 Requirements result = this->requirements(sw.value().get());
John Stilesb23a64b2021-03-11 08:27:59 -05002385 for (const std::unique_ptr<Statement>& sc : sw.cases()) {
2386 result |= this->requirements(sc->as<SwitchCase>().statement().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002387 }
2388 return result;
2389 }
2390 default:
2391 return kNo_Requirements;
2392 }
2393}
2394
2395MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const FunctionDeclaration& f) {
Ethan Nicholased84b732020-10-08 11:45:44 -04002396 if (f.isBuiltin()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002397 return kNo_Requirements;
2398 }
2399 auto found = fRequirements.find(&f);
2400 if (found == fRequirements.end()) {
Ethan Nicholas65a8f562019-04-19 14:00:26 -04002401 fRequirements[&f] = kNo_Requirements;
Brian Osman133724c2020-10-28 14:14:39 -04002402 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04002403 if (e->is<FunctionDefinition>()) {
2404 const FunctionDefinition& def = e->as<FunctionDefinition>();
Ethan Nicholas0a5d0962020-10-14 13:33:18 -04002405 if (&def.declaration() == &f) {
2406 Requirements reqs = this->requirements(def.body().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002407 fRequirements[&f] = reqs;
2408 return reqs;
2409 }
2410 }
2411 }
John Stiles569249b2020-11-03 12:18:22 -05002412 // We never found a definition for this declared function, but it's legal to prototype a
2413 // function without ever giving a definition, as long as you don't call it.
2414 return kNo_Requirements;
Ethan Nicholascc305772017-10-13 16:17:45 -04002415 }
2416 return found->second;
2417}
2418
Timothy Liangb8eeb802018-07-23 16:46:16 -04002419bool MetalCodeGenerator::generateCode() {
John Stiles44532372020-12-07 12:33:55 -05002420 StringStream header;
2421 {
2422 AutoOutputStream outputToHeader(this, &header, &fIndentation);
Michael Ludwigbf58add2021-03-16 10:40:11 -04002423 this->writeHeader();
John Stiles44532372020-12-07 12:33:55 -05002424 this->writeStructDefinitions();
2425 this->writeUniformStruct();
2426 this->writeInputStruct();
2427 this->writeOutputStruct();
2428 this->writeInterfaceBlocks();
2429 this->writeGlobalStruct();
2430 }
2431 StringStream body;
2432 {
2433 AutoOutputStream outputToBody(this, &body, &fIndentation);
2434 for (const ProgramElement* e : fProgram.elements()) {
2435 this->writeProgramElement(*e);
2436 }
2437 }
2438 write_stringstream(header, *fOut);
2439 write_stringstream(fExtraFunctions, *fOut);
2440 write_stringstream(body, *fOut);
Brian Osman8609a242020-09-08 14:01:49 -04002441 return 0 == fErrors.errorCount();
Ethan Nicholascc305772017-10-13 16:17:45 -04002442}
2443
John Stilesa6841be2020-08-06 14:11:56 -04002444} // namespace SkSL