blob: fe85ce7567c945687b88bd38c7710b10c5c1b8b7 [file] [log] [blame]
Ethan Nicholascc305772017-10-13 16:17:45 -04001/*
2 * Copyright 2016 Google Inc.
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
7
John Stiles3738ef52021-04-13 10:41:57 -04008#include "src/sksl/codegen/SkSLMetalCodeGenerator.h"
Ethan Nicholascc305772017-10-13 16:17:45 -04009
John Stiles986c7fb2020-12-01 14:44:56 -050010#include "src/core/SkScopeExit.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050011#include "src/sksl/SkSLCompiler.h"
John Stiles0023c0c2020-11-16 13:32:18 -050012#include "src/sksl/SkSLMemoryLayout.h"
John Stiles7384b372021-04-01 13:48:15 -040013#include "src/sksl/ir/SkSLConstructorArray.h"
John Stiles8cad6372021-04-07 12:31:13 -040014#include "src/sksl/ir/SkSLConstructorCompoundCast.h"
John Stiles7384b372021-04-01 13:48:15 -040015#include "src/sksl/ir/SkSLConstructorDiagonalMatrix.h"
John Stiles5abb9e12021-04-06 13:47:19 -040016#include "src/sksl/ir/SkSLConstructorMatrixResize.h"
John Stiles2938eea2021-04-01 18:58:25 -040017#include "src/sksl/ir/SkSLConstructorSplat.h"
John Stilesd47330f2021-04-08 23:25:52 -040018#include "src/sksl/ir/SkSLConstructorStruct.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050019#include "src/sksl/ir/SkSLExpressionStatement.h"
20#include "src/sksl/ir/SkSLExtension.h"
21#include "src/sksl/ir/SkSLIndexExpression.h"
22#include "src/sksl/ir/SkSLModifiersDeclaration.h"
23#include "src/sksl/ir/SkSLNop.h"
John Stilesdc75a972020-11-25 16:24:55 -050024#include "src/sksl/ir/SkSLStructDefinition.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050025#include "src/sksl/ir/SkSLVariableReference.h"
Ethan Nicholascc305772017-10-13 16:17:45 -040026
Brian Osmanc262a122020-08-06 16:34:34 -040027#include <algorithm>
28
Ethan Nicholascc305772017-10-13 16:17:45 -040029namespace SkSL {
30
John Stiles45990502021-02-16 10:55:27 -050031const char* MetalCodeGenerator::OperatorName(Operator op) {
32 switch (op.kind()) {
John Stilesd6449e92020-11-30 09:13:23 -050033 case Token::Kind::TK_LOGICALXOR: return "!=";
John Stiles45990502021-02-16 10:55:27 -050034 default: return op.operatorName();
John Stilesd6449e92020-11-30 09:13:23 -050035 }
36}
37
John Stilescdcdb042020-07-06 09:03:51 -040038class MetalCodeGenerator::GlobalStructVisitor {
39public:
40 virtual ~GlobalStructVisitor() = default;
John Stilesfdb8dbe2020-12-04 11:00:03 -050041 virtual void visitInterfaceBlock(const InterfaceBlock& block, const String& blockName) = 0;
42 virtual void visitTexture(const Type& type, const String& name) = 0;
43 virtual void visitSampler(const Type& type, const String& name) = 0;
44 virtual void visitVariable(const Variable& var, const Expression* value) = 0;
John Stilescdcdb042020-07-06 09:03:51 -040045};
46
Timothy Liangee84fe12018-05-18 14:38:19 -040047void MetalCodeGenerator::setupIntrinsics() {
John Stilesd7199b22020-12-30 16:22:58 -050048 fIntrinsicMap[String("atan")] = kAtan_IntrinsicKind;
49 fIntrinsicMap[String("floatBitsToInt")] = kBitcast_IntrinsicKind;
50 fIntrinsicMap[String("floatBitsToUint")] = kBitcast_IntrinsicKind;
51 fIntrinsicMap[String("intBitsToFloat")] = kBitcast_IntrinsicKind;
52 fIntrinsicMap[String("uintBitsToFloat")] = kBitcast_IntrinsicKind;
53 fIntrinsicMap[String("equal")] = kCompareEqual_IntrinsicKind;
54 fIntrinsicMap[String("notEqual")] = kCompareNotEqual_IntrinsicKind;
55 fIntrinsicMap[String("lessThan")] = kCompareLessThan_IntrinsicKind;
56 fIntrinsicMap[String("lessThanEqual")] = kCompareLessThanEqual_IntrinsicKind;
57 fIntrinsicMap[String("greaterThan")] = kCompareGreaterThan_IntrinsicKind;
58 fIntrinsicMap[String("greaterThanEqual")] = kCompareGreaterThanEqual_IntrinsicKind;
59 fIntrinsicMap[String("degrees")] = kDegrees_IntrinsicKind;
60 fIntrinsicMap[String("dFdx")] = kDFdx_IntrinsicKind;
61 fIntrinsicMap[String("dFdy")] = kDFdy_IntrinsicKind;
62 fIntrinsicMap[String("distance")] = kDistance_IntrinsicKind;
63 fIntrinsicMap[String("dot")] = kDot_IntrinsicKind;
64 fIntrinsicMap[String("faceforward")] = kFaceforward_IntrinsicKind;
65 fIntrinsicMap[String("bitCount")] = kBitCount_IntrinsicKind;
66 fIntrinsicMap[String("findLSB")] = kFindLSB_IntrinsicKind;
67 fIntrinsicMap[String("findMSB")] = kFindMSB_IntrinsicKind;
68 fIntrinsicMap[String("inverse")] = kInverse_IntrinsicKind;
69 fIntrinsicMap[String("inversesqrt")] = kInversesqrt_IntrinsicKind;
70 fIntrinsicMap[String("length")] = kLength_IntrinsicKind;
71 fIntrinsicMap[String("matrixCompMult")] = kMatrixCompMult_IntrinsicKind;
72 fIntrinsicMap[String("mod")] = kMod_IntrinsicKind;
73 fIntrinsicMap[String("normalize")] = kNormalize_IntrinsicKind;
74 fIntrinsicMap[String("radians")] = kRadians_IntrinsicKind;
75 fIntrinsicMap[String("reflect")] = kReflect_IntrinsicKind;
76 fIntrinsicMap[String("refract")] = kRefract_IntrinsicKind;
John Stiles23456532020-12-30 18:12:48 -050077 fIntrinsicMap[String("roundEven")] = kRoundEven_IntrinsicKind;
John Stilesd7199b22020-12-30 16:22:58 -050078 fIntrinsicMap[String("sample")] = kTexture_IntrinsicKind;
Timothy Liangee84fe12018-05-18 14:38:19 -040079}
80
Ethan Nicholascc305772017-10-13 16:17:45 -040081void MetalCodeGenerator::write(const char* s) {
82 if (!s[0]) {
83 return;
84 }
85 if (fAtLineStart) {
86 for (int i = 0; i < fIndentation; i++) {
87 fOut->writeText(" ");
88 }
89 }
90 fOut->writeText(s);
91 fAtLineStart = false;
92}
93
94void MetalCodeGenerator::writeLine(const char* s) {
95 this->write(s);
John Stilese8b5a732021-03-12 13:25:52 -050096 this->writeLine();
Ethan Nicholascc305772017-10-13 16:17:45 -040097}
98
99void MetalCodeGenerator::write(const String& s) {
100 this->write(s.c_str());
101}
102
103void MetalCodeGenerator::writeLine(const String& s) {
104 this->writeLine(s.c_str());
105}
106
107void MetalCodeGenerator::writeLine() {
John Stilese8b5a732021-03-12 13:25:52 -0500108 fOut->writeText(fLineEnding);
109 fAtLineStart = true;
110}
111
112void MetalCodeGenerator::finishLine() {
113 if (!fAtLineStart) {
114 this->writeLine();
115 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400116}
117
118void MetalCodeGenerator::writeExtension(const Extension& ext) {
Ethan Nicholasefb09e22020-09-30 10:17:00 -0400119 this->writeLine("#extension " + ext.name() + " : enable");
Ethan Nicholascc305772017-10-13 16:17:45 -0400120}
121
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500122String MetalCodeGenerator::typeName(const Type& type) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400123 switch (type.typeKind()) {
John Stilesb4418502021-02-04 10:57:08 -0500124 case Type::TypeKind::kArray:
125 SkASSERTF(type.columns() > 0, "invalid array size: %s", type.description().c_str());
126 return String::printf("array<%s, %d>",
127 this->typeName(type.componentType()).c_str(), type.columns());
128
Ethan Nicholase6592142020-09-08 10:22:09 -0400129 case Type::TypeKind::kVector:
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500130 return this->typeName(type.componentType()) + to_string(type.columns());
John Stilesb4418502021-02-04 10:57:08 -0500131
Ethan Nicholase6592142020-09-08 10:22:09 -0400132 case Type::TypeKind::kMatrix:
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500133 return this->typeName(type.componentType()) + to_string(type.columns()) + "x" +
134 to_string(type.rows());
John Stilesb4418502021-02-04 10:57:08 -0500135
Ethan Nicholase6592142020-09-08 10:22:09 -0400136 case Type::TypeKind::kSampler:
John Stiles368db7c2020-12-29 11:20:08 -0500137 return "texture2d<float>"; // FIXME - support other texture types
John Stilesb4418502021-02-04 10:57:08 -0500138
John Stilesfd41d872020-11-25 22:39:45 -0500139 case Type::TypeKind::kEnum:
140 return "int";
John Stilesb4418502021-02-04 10:57:08 -0500141
Ethan Nicholascc305772017-10-13 16:17:45 -0400142 default:
John Stiles54e7c052021-01-11 14:22:36 -0500143 if (type == *fContext.fTypes.fHalf) {
Timothy Liang43d225f2018-07-19 15:27:13 -0400144 // FIXME - Currently only supporting floats in MSL to avoid type coercion issues.
John Stiles54e7c052021-01-11 14:22:36 -0500145 return fContext.fTypes.fFloat->name();
Timothy Liang7d637782018-06-05 09:58:07 -0400146 } else {
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500147 return type.name();
Timothy Liang7d637782018-06-05 09:58:07 -0400148 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400149 }
150}
151
Brian Osman02bc5222021-01-28 11:00:20 -0500152void MetalCodeGenerator::writeStructDefinition(const StructDefinition& s) {
153 const Type& type = s.type();
John Stilesdc75a972020-11-25 16:24:55 -0500154 this->writeLine("struct " + type.name() + " {");
155 fIndentation++;
156 this->writeFields(type.fields(), type.fOffset);
157 fIndentation--;
Brian Osman02bc5222021-01-28 11:00:20 -0500158 this->writeLine("};");
John Stilesdc75a972020-11-25 16:24:55 -0500159}
160
John Stilesb4418502021-02-04 10:57:08 -0500161void MetalCodeGenerator::writeType(const Type& type) {
162 this->write(this->typeName(type));
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500163}
164
Ethan Nicholascc305772017-10-13 16:17:45 -0400165void MetalCodeGenerator::writeExpression(const Expression& expr, Precedence parentPrecedence) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400166 switch (expr.kind()) {
167 case Expression::Kind::kBinary:
John Stiles81365af2020-08-18 09:24:00 -0400168 this->writeBinaryExpression(expr.as<BinaryExpression>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400169 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400170 case Expression::Kind::kBoolLiteral:
John Stiles81365af2020-08-18 09:24:00 -0400171 this->writeBoolLiteral(expr.as<BoolLiteral>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400172 break;
John Stiles2bec8ab2021-04-06 18:40:04 -0400173 case Expression::Kind::kConstructorArray:
John Stilesd47330f2021-04-08 23:25:52 -0400174 case Expression::Kind::kConstructorStruct:
John Stiles2bec8ab2021-04-06 18:40:04 -0400175 this->writeAnyConstructor(expr.asAnyConstructor(), "{", "}", parentPrecedence);
176 break;
John Stiles8cad6372021-04-07 12:31:13 -0400177 case Expression::Kind::kConstructorCompound:
178 this->writeConstructorCompound(expr.as<ConstructorCompound>(), parentPrecedence);
John Stiles2bec8ab2021-04-06 18:40:04 -0400179 break;
180 case Expression::Kind::kConstructorDiagonalMatrix:
181 case Expression::Kind::kConstructorSplat:
182 this->writeAnyConstructor(expr.asAnyConstructor(), "(", ")", parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400183 break;
John Stiles5abb9e12021-04-06 13:47:19 -0400184 case Expression::Kind::kConstructorMatrixResize:
185 this->writeConstructorMatrixResize(expr.as<ConstructorMatrixResize>(),
186 parentPrecedence);
187 break;
John Stilesfd7252f2021-04-04 22:24:40 -0400188 case Expression::Kind::kConstructorScalarCast:
John Stiles8cad6372021-04-07 12:31:13 -0400189 case Expression::Kind::kConstructorCompoundCast:
John Stilesb14a8192021-04-05 11:40:46 -0400190 this->writeCastConstructor(expr.asAnyConstructor(), "(", ")", parentPrecedence);
John Stiles2938eea2021-04-01 18:58:25 -0400191 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400192 case Expression::Kind::kIntLiteral:
John Stiles81365af2020-08-18 09:24:00 -0400193 this->writeIntLiteral(expr.as<IntLiteral>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400194 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400195 case Expression::Kind::kFieldAccess:
John Stiles81365af2020-08-18 09:24:00 -0400196 this->writeFieldAccess(expr.as<FieldAccess>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400197 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400198 case Expression::Kind::kFloatLiteral:
John Stiles81365af2020-08-18 09:24:00 -0400199 this->writeFloatLiteral(expr.as<FloatLiteral>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400200 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400201 case Expression::Kind::kFunctionCall:
John Stiles81365af2020-08-18 09:24:00 -0400202 this->writeFunctionCall(expr.as<FunctionCall>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400203 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400204 case Expression::Kind::kPrefix:
John Stiles81365af2020-08-18 09:24:00 -0400205 this->writePrefixExpression(expr.as<PrefixExpression>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400206 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400207 case Expression::Kind::kPostfix:
John Stiles81365af2020-08-18 09:24:00 -0400208 this->writePostfixExpression(expr.as<PostfixExpression>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400209 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400210 case Expression::Kind::kSetting:
John Stiles81365af2020-08-18 09:24:00 -0400211 this->writeSetting(expr.as<Setting>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400212 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400213 case Expression::Kind::kSwizzle:
John Stiles81365af2020-08-18 09:24:00 -0400214 this->writeSwizzle(expr.as<Swizzle>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400215 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400216 case Expression::Kind::kVariableReference:
John Stiles81365af2020-08-18 09:24:00 -0400217 this->writeVariableReference(expr.as<VariableReference>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400218 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400219 case Expression::Kind::kTernary:
John Stiles81365af2020-08-18 09:24:00 -0400220 this->writeTernaryExpression(expr.as<TernaryExpression>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400221 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400222 case Expression::Kind::kIndex:
John Stiles81365af2020-08-18 09:24:00 -0400223 this->writeIndexExpression(expr.as<IndexExpression>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400224 break;
225 default:
John Stileseada7bc2021-02-02 16:29:32 -0500226 SkDEBUGFAILF("unsupported expression: %s", expr.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -0500227 break;
Ethan Nicholascc305772017-10-13 16:17:45 -0400228 }
229}
230
John Stiles06b84ef2020-12-09 12:35:48 -0500231String MetalCodeGenerator::getOutParamHelper(const FunctionCall& call,
232 const ExpressionArray& arguments,
233 const SkTArray<VariableReference*>& outVars) {
234 AutoOutputStream outputToExtraFunctions(this, &fExtraFunctions, &fIndentation);
235 const FunctionDeclaration& function = call.function();
236
John Stilese1068342021-03-22 11:57:41 -0400237 String name = "_skOutParamHelper" + to_string(fSwizzleHelperCount++) +
238 "_" + function.mangledName();
John Stiles06b84ef2020-12-09 12:35:48 -0500239 const char* separator = "";
240
241 // Emit a prototype for the function we'll be calling through to in our helper.
242 if (!function.isBuiltin()) {
243 this->writeFunctionDeclaration(function);
244 this->writeLine(";");
245 }
246
247 // Synthesize a helper function that takes the same inputs as `function`, except in places where
248 // `outVars` is non-null; in those places, we take the type of the VariableReference.
249 //
250 // float _skOutParamHelper0_originalFuncName(float _var0, float _var1, float& outParam) {
John Stilesb4418502021-02-04 10:57:08 -0500251 this->writeType(call.type());
John Stiles06b84ef2020-12-09 12:35:48 -0500252 this->write(" ");
253 this->write(name);
254 this->write("(");
255 this->writeFunctionRequirementParams(function, separator);
256
257 SkASSERT(outVars.size() == arguments.size());
258 SkASSERT(outVars.size() == function.parameters().size());
259
John Stiles73e2c892021-02-13 13:58:01 -0500260 // We need to detect cases where the caller passes the same variable as an out-param more than
261 // once, and avoid reusing the variable name. (In those cases we can actually just ignore the
262 // redundant input parameter entirely, and not give it any name.)
263 std::unordered_set<const Variable*> writtenVars;
264
John Stiles06b84ef2020-12-09 12:35:48 -0500265 for (int index = 0; index < arguments.count(); ++index) {
266 this->write(separator);
267 separator = ", ";
268
269 const Variable* param = function.parameters()[index];
270 this->writeModifiers(param->modifiers(), /*globalContext=*/false);
271
272 const Type* type = outVars[index] ? &outVars[index]->type() : &arguments[index]->type();
John Stilesb4418502021-02-04 10:57:08 -0500273 this->writeType(*type);
John Stiles06b84ef2020-12-09 12:35:48 -0500274
275 if (param->modifiers().fFlags & Modifiers::kOut_Flag) {
276 this->write("&");
277 }
278 if (outVars[index]) {
John Stiles73e2c892021-02-13 13:58:01 -0500279 auto [iter, didInsert] = writtenVars.insert(outVars[index]->variable());
280 if (didInsert) {
281 this->write(" ");
282 fIgnoreVariableReferenceModifiers = true;
283 this->writeVariableReference(*outVars[index]);
284 fIgnoreVariableReferenceModifiers = false;
285 }
John Stiles06b84ef2020-12-09 12:35:48 -0500286 } else {
287 this->write(" _var");
288 this->write(to_string(index));
289 }
John Stiles06b84ef2020-12-09 12:35:48 -0500290 }
291 this->writeLine(") {");
292
293 ++fIndentation;
294 for (int index = 0; index < outVars.count(); ++index) {
295 if (!outVars[index]) {
296 continue;
297 }
298 // float3 _var2[ = outParam.zyx];
John Stilesb4418502021-02-04 10:57:08 -0500299 this->writeType(arguments[index]->type());
John Stiles06b84ef2020-12-09 12:35:48 -0500300 this->write(" _var");
301 this->write(to_string(index));
302
303 const Variable* param = function.parameters()[index];
304 if (param->modifiers().fFlags & Modifiers::kIn_Flag) {
305 this->write(" = ");
306 fIgnoreVariableReferenceModifiers = true;
Brian Osman00185012021-02-04 16:07:11 -0500307 this->writeExpression(*arguments[index], Precedence::kAssignment);
John Stiles06b84ef2020-12-09 12:35:48 -0500308 fIgnoreVariableReferenceModifiers = false;
309 }
310
311 this->writeLine(";");
312 }
313
John Stilesf7410bd2021-01-19 13:07:55 -0500314 // [int _skResult = ] myFunction(inputs, outputs, _globals, _var0, _var1, _var2, _var3);
John Stiles06b84ef2020-12-09 12:35:48 -0500315 bool hasResult = (call.type().name() != "void");
316 if (hasResult) {
John Stilesb4418502021-02-04 10:57:08 -0500317 this->writeType(call.type());
John Stiles06b84ef2020-12-09 12:35:48 -0500318 this->write(" _skResult = ");
319 }
320
John Stilese1068342021-03-22 11:57:41 -0400321 this->writeName(function.mangledName());
John Stiles06b84ef2020-12-09 12:35:48 -0500322 this->write("(");
323 separator = "";
324 this->writeFunctionRequirementArgs(function, separator);
325
326 for (int index = 0; index < arguments.count(); ++index) {
327 this->write(separator);
328 separator = ", ";
329
330 this->write("_var");
331 this->write(to_string(index));
332 }
333 this->writeLine(");");
334
335 for (int index = 0; index < outVars.count(); ++index) {
336 if (!outVars[index]) {
337 continue;
338 }
339 // outParam.zyx = _var2;
340 fIgnoreVariableReferenceModifiers = true;
Brian Osman00185012021-02-04 16:07:11 -0500341 this->writeExpression(*arguments[index], Precedence::kAssignment);
John Stiles06b84ef2020-12-09 12:35:48 -0500342 fIgnoreVariableReferenceModifiers = false;
343 this->write(" = _var");
344 this->write(to_string(index));
345 this->writeLine(";");
346 }
347
348 if (hasResult) {
349 this->writeLine("return _skResult;");
350 }
351
352 --fIndentation;
353 this->writeLine("}");
354
355 return name;
John Stilesb21fac22020-12-04 15:36:49 -0500356}
357
John Stilesf64e4072020-12-10 10:34:27 -0500358String MetalCodeGenerator::getBitcastIntrinsic(const Type& outType) {
359 return "as_type<" + outType.displayName() + ">";
360}
361
Ethan Nicholascc305772017-10-13 16:17:45 -0400362void MetalCodeGenerator::writeFunctionCall(const FunctionCall& c) {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400363 const FunctionDeclaration& function = c.function();
John Stiles89ac7c22020-12-30 17:47:31 -0500364 // If this function is a built-in with no declaration, it's probably an intrinsic and might need
365 // special handling.
366 if (function.isBuiltin() && !function.definition()) {
367 auto iter = fIntrinsicMap.find(function.name());
368 if (iter != fIntrinsicMap.end()) {
369 this->writeIntrinsicCall(c, iter->second);
370 return;
371 }
Timothy Liang6403b0e2018-05-17 10:40:04 -0400372 }
John Stilesb21fac22020-12-04 15:36:49 -0500373
John Stilesd7199b22020-12-30 16:22:58 -0500374 // Determine whether or not we need to emulate GLSL's out-param semantics for Metal using a
375 // helper function. (Specifically, out-parameters in GLSL are only written back to the original
376 // variable at the end of the function call; also, swizzles are supported, whereas Metal doesn't
377 // allow a swizzle to be passed to a `floatN&`.)
378 const ExpressionArray& arguments = c.arguments();
John Stilesb21fac22020-12-04 15:36:49 -0500379 const std::vector<const Variable*>& parameters = function.parameters();
380 SkASSERT(arguments.size() == parameters.size());
John Stiles06b84ef2020-12-09 12:35:48 -0500381
382 bool foundOutParam = false;
383 SkSTArray<16, VariableReference*> outVars;
John Stilesf64e4072020-12-10 10:34:27 -0500384 outVars.push_back_n(arguments.count(), (VariableReference*)nullptr);
John Stiles06b84ef2020-12-09 12:35:48 -0500385
386 for (int index = 0; index < arguments.count(); ++index) {
John Stilesb21fac22020-12-04 15:36:49 -0500387 // If this is an out parameter...
388 if (parameters[index]->modifiers().fFlags & Modifiers::kOut_Flag) {
John Stiles06b84ef2020-12-09 12:35:48 -0500389 // Find the expression's inner variable being written to.
John Stilesb21fac22020-12-04 15:36:49 -0500390 Analysis::AssignmentInfo info;
John Stiles06b84ef2020-12-09 12:35:48 -0500391 // Assignability was verified at IRGeneration time, so this should always succeed.
392 SkAssertResult(Analysis::IsAssignable(*arguments[index], &info));
393 outVars[index] = info.fAssignedVar;
394 foundOutParam = true;
John Stilesb21fac22020-12-04 15:36:49 -0500395 }
396 }
397
John Stiles06b84ef2020-12-09 12:35:48 -0500398 if (foundOutParam) {
399 // Out parameters need to be written back to at the end of the function. To do this, we
400 // synthesize a helper function which evaluates the out-param expression into a temporary
401 // variable, calls the original function, then writes the temp var back into the out param
402 // using the original out-param expression. (This lets us support things like swizzles and
403 // array indices.)
John Stilesd7199b22020-12-30 16:22:58 -0500404 this->write(getOutParamHelper(c, arguments, outVars));
405 } else {
John Stilese1068342021-03-22 11:57:41 -0400406 this->write(function.mangledName());
John Stiles06b84ef2020-12-09 12:35:48 -0500407 }
408
Ethan Nicholascc305772017-10-13 16:17:45 -0400409 this->write("(");
410 const char* separator = "";
John Stiles06b84ef2020-12-09 12:35:48 -0500411 this->writeFunctionRequirementArgs(function, separator);
412 for (int i = 0; i < arguments.count(); ++i) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400413 this->write(separator);
414 separator = ", ";
John Stiles06b84ef2020-12-09 12:35:48 -0500415
416 if (outVars[i]) {
Brian Osman00185012021-02-04 16:07:11 -0500417 this->writeExpression(*outVars[i], Precedence::kSequence);
John Stiles06b84ef2020-12-09 12:35:48 -0500418 } else {
Brian Osman00185012021-02-04 16:07:11 -0500419 this->writeExpression(*arguments[i], Precedence::kSequence);
John Stiles06b84ef2020-12-09 12:35:48 -0500420 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400421 }
422 this->write(")");
423}
424
Brian Osman964f0a02020-12-29 10:15:22 -0500425static constexpr char kInverse2x2[] = R"(
426float2x2 float2x2_inverse(float2x2 m) {
427 return float2x2(m[1][1], -m[0][1], -m[1][0], m[0][0]) * (1/determinant(m));
428}
429)";
430
431static constexpr char kInverse3x3[] = R"(
432float3x3 float3x3_inverse(float3x3 m) {
433 float a00 = m[0][0], a01 = m[0][1], a02 = m[0][2];
434 float a10 = m[1][0], a11 = m[1][1], a12 = m[1][2];
435 float a20 = m[2][0], a21 = m[2][1], a22 = m[2][2];
436 float b01 = a22*a11 - a12*a21;
437 float b11 = -a22*a10 + a12*a20;
438 float b21 = a21*a10 - a11*a20;
439 float det = a00*b01 + a01*b11 + a02*b21;
440 return float3x3(b01, (-a22*a01 + a02*a21), ( a12*a01 - a02*a11),
441 b11, ( a22*a00 - a02*a20), (-a12*a00 + a02*a10),
442 b21, (-a21*a00 + a01*a20), ( a11*a00 - a01*a10)) * (1/det);
443}
444)";
445
446static constexpr char kInverse4x4[] = R"(
447float4x4 float4x4_inverse(float4x4 m) {
448 float a00 = m[0][0], a01 = m[0][1], a02 = m[0][2], a03 = m[0][3];
449 float a10 = m[1][0], a11 = m[1][1], a12 = m[1][2], a13 = m[1][3];
450 float a20 = m[2][0], a21 = m[2][1], a22 = m[2][2], a23 = m[2][3];
451 float a30 = m[3][0], a31 = m[3][1], a32 = m[3][2], a33 = m[3][3];
452 float b00 = a00*a11 - a01*a10;
453 float b01 = a00*a12 - a02*a10;
454 float b02 = a00*a13 - a03*a10;
455 float b03 = a01*a12 - a02*a11;
456 float b04 = a01*a13 - a03*a11;
457 float b05 = a02*a13 - a03*a12;
458 float b06 = a20*a31 - a21*a30;
459 float b07 = a20*a32 - a22*a30;
460 float b08 = a20*a33 - a23*a30;
461 float b09 = a21*a32 - a22*a31;
462 float b10 = a21*a33 - a23*a31;
463 float b11 = a22*a33 - a23*a32;
464 float det = b00*b11 - b01*b10 + b02*b09 + b03*b08 - b04*b07 + b05*b06;
465 return float4x4(a11*b11 - a12*b10 + a13*b09,
466 a02*b10 - a01*b11 - a03*b09,
467 a31*b05 - a32*b04 + a33*b03,
468 a22*b04 - a21*b05 - a23*b03,
469 a12*b08 - a10*b11 - a13*b07,
470 a00*b11 - a02*b08 + a03*b07,
471 a32*b02 - a30*b05 - a33*b01,
472 a20*b05 - a22*b02 + a23*b01,
473 a10*b10 - a11*b08 + a13*b06,
474 a01*b08 - a00*b10 - a03*b06,
475 a30*b04 - a31*b02 + a33*b00,
476 a21*b02 - a20*b04 - a23*b00,
477 a11*b07 - a10*b09 - a12*b06,
478 a00*b09 - a01*b07 + a02*b06,
479 a31*b01 - a30*b03 - a32*b00,
480 a20*b03 - a21*b01 + a22*b00) * (1/det);
481}
482)";
483
John Stilesd7199b22020-12-30 16:22:58 -0500484String MetalCodeGenerator::getInversePolyfill(const ExpressionArray& arguments) {
485 // Only use polyfills for a function taking a single-argument square matrix.
486 if (arguments.size() == 1) {
487 const Type& type = arguments.front()->type();
488 if (type.isMatrix() && type.rows() == type.columns()) {
489 // Inject the correct polyfill based on the matrix size.
490 String name = this->typeName(type) + "_inverse";
491 auto [iter, didInsert] = fWrittenIntrinsics.insert(name);
492 if (didInsert) {
493 switch (type.rows()) {
494 case 2:
495 fExtraFunctions.writeText(kInverse2x2);
496 break;
497 case 3:
498 fExtraFunctions.writeText(kInverse3x3);
499 break;
500 case 4:
501 fExtraFunctions.writeText(kInverse4x4);
502 break;
503 }
504 }
505 return name;
Chris Daltondba7aab2018-11-15 10:57:49 -0500506 }
507 }
John Stilesd7199b22020-12-30 16:22:58 -0500508 // This isn't the built-in `inverse`. We don't want to polyfill it at all.
509 return "inverse";
Chris Daltondba7aab2018-11-15 10:57:49 -0500510}
511
Brian Osman93aed9a2020-12-28 15:18:46 -0500512static constexpr char kMatrixCompMult[] = R"(
513template <int C, int R>
514matrix<float, C, R> matrixCompMult(matrix<float, C, R> a, matrix<float, C, R> b) {
515 matrix<float, C, R> result;
516 for (int c = 0; c < C; ++c) {
517 result[c] = a[c] * b[c];
518 }
519 return result;
520}
521)";
522
523void MetalCodeGenerator::writeMatrixCompMult() {
524 String name = "matrixCompMult";
525 if (fWrittenIntrinsics.find(name) == fWrittenIntrinsics.end()) {
526 fWrittenIntrinsics.insert(name);
527 fExtraFunctions.writeText(kMatrixCompMult);
528 }
529}
530
John Stiles86424eb2020-12-11 11:17:14 -0500531String MetalCodeGenerator::getTempVariable(const Type& type) {
532 String tempVar = "_skTemp" + to_string(fVarCount++);
533 this->fFunctionHeader += " " + this->typeName(type) + " " + tempVar + ";\n";
534 return tempVar;
535}
536
John Stiles791c27d2020-12-30 14:56:57 -0500537void MetalCodeGenerator::writeSimpleIntrinsic(const FunctionCall& c) {
538 // Write out an intrinsic function call exactly as-is. No muss no fuss.
539 this->write(c.function().name());
John Stilesd7199b22020-12-30 16:22:58 -0500540 this->writeArgumentList(c.arguments());
541}
542
543void MetalCodeGenerator::writeArgumentList(const ExpressionArray& arguments) {
John Stiles791c27d2020-12-30 14:56:57 -0500544 this->write("(");
545 const char* separator = "";
John Stilesd7199b22020-12-30 16:22:58 -0500546 for (const std::unique_ptr<Expression>& arg : arguments) {
John Stiles791c27d2020-12-30 14:56:57 -0500547 this->write(separator);
548 separator = ", ";
Brian Osman00185012021-02-04 16:07:11 -0500549 this->writeExpression(*arg, Precedence::kSequence);
John Stiles791c27d2020-12-30 14:56:57 -0500550 }
551 this->write(")");
552}
553
John Stilesd7199b22020-12-30 16:22:58 -0500554void MetalCodeGenerator::writeIntrinsicCall(const FunctionCall& c, IntrinsicKind kind) {
John Stiles8e3b6be2020-10-13 11:14:08 -0400555 const ExpressionArray& arguments = c.arguments();
Timothy Liang6403b0e2018-05-17 10:40:04 -0400556 switch (kind) {
John Stilesd7199b22020-12-30 16:22:58 -0500557 case kTexture_IntrinsicKind: {
Brian Osman00185012021-02-04 16:07:11 -0500558 this->writeExpression(*arguments[0], Precedence::kSequence);
Timothy Lianga06f2152018-05-24 15:33:31 -0400559 this->write(".sample(");
Brian Osman00185012021-02-04 16:07:11 -0500560 this->writeExpression(*arguments[0], Precedence::kSequence);
Timothy Lianga06f2152018-05-24 15:33:31 -0400561 this->write(SAMPLER_SUFFIX);
562 this->write(", ");
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400563 const Type& arg1Type = arguments[1]->type();
John Stilesb14a8192021-04-05 11:40:46 -0400564 if (arg1Type.columns() == 3) {
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500565 // have to store the vector in a temp variable to avoid double evaluating it
John Stiles86424eb2020-12-11 11:17:14 -0500566 String tmpVar = this->getTempVariable(arg1Type);
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500567 this->write("(" + tmpVar + " = ");
Brian Osman00185012021-02-04 16:07:11 -0500568 this->writeExpression(*arguments[1], Precedence::kSequence);
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500569 this->write(", " + tmpVar + ".xy / " + tmpVar + ".z))");
Timothy Liangee84fe12018-05-18 14:38:19 -0400570 } else {
John Stilesb14a8192021-04-05 11:40:46 -0400571 SkASSERT(arg1Type.columns() == 2);
Brian Osman00185012021-02-04 16:07:11 -0500572 this->writeExpression(*arguments[1], Precedence::kSequence);
Timothy Liangee84fe12018-05-18 14:38:19 -0400573 this->write(")");
574 }
Timothy Liang6403b0e2018-05-17 10:40:04 -0400575 break;
Ethan Nicholas30d30222020-09-11 12:27:26 -0400576 }
John Stilesd7199b22020-12-30 16:22:58 -0500577 case kMod_IntrinsicKind: {
Timothy Liang651286f2018-06-07 09:55:33 -0400578 // 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 -0500579 String tmpX = this->getTempVariable(arguments[0]->type());
John Stiles61b2e812020-12-30 18:27:31 -0500580 String tmpY = this->getTempVariable(arguments[1]->type());
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500581 this->write("(" + tmpX + " = ");
Brian Osman00185012021-02-04 16:07:11 -0500582 this->writeExpression(*arguments[0], Precedence::kSequence);
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500583 this->write(", " + tmpY + " = ");
Brian Osman00185012021-02-04 16:07:11 -0500584 this->writeExpression(*arguments[1], Precedence::kSequence);
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500585 this->write(", " + tmpX + " - " + tmpY + " * floor(" + tmpX + " / " + tmpY + "))");
Timothy Liang651286f2018-06-07 09:55:33 -0400586 break;
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500587 }
Brian Osman46787d52020-11-24 14:18:23 -0500588 // GLSL declares scalar versions of most geometric intrinsics, but these don't exist in MSL
John Stilesd7199b22020-12-30 16:22:58 -0500589 case kDistance_IntrinsicKind: {
Brian Osman46787d52020-11-24 14:18:23 -0500590 if (arguments[0]->type().columns() == 1) {
591 this->write("abs(");
Brian Osman00185012021-02-04 16:07:11 -0500592 this->writeExpression(*arguments[0], Precedence::kAdditive);
Brian Osman46787d52020-11-24 14:18:23 -0500593 this->write(" - ");
Brian Osman00185012021-02-04 16:07:11 -0500594 this->writeExpression(*arguments[1], Precedence::kAdditive);
Brian Osman46787d52020-11-24 14:18:23 -0500595 this->write(")");
596 } else {
John Stiles791c27d2020-12-30 14:56:57 -0500597 this->writeSimpleIntrinsic(c);
Brian Osman46787d52020-11-24 14:18:23 -0500598 }
599 break;
600 }
John Stilesd7199b22020-12-30 16:22:58 -0500601 case kDot_IntrinsicKind: {
Brian Osman46787d52020-11-24 14:18:23 -0500602 if (arguments[0]->type().columns() == 1) {
603 this->write("(");
Brian Osman00185012021-02-04 16:07:11 -0500604 this->writeExpression(*arguments[0], Precedence::kMultiplicative);
Brian Osman46787d52020-11-24 14:18:23 -0500605 this->write(" * ");
Brian Osman00185012021-02-04 16:07:11 -0500606 this->writeExpression(*arguments[1], Precedence::kMultiplicative);
Brian Osman46787d52020-11-24 14:18:23 -0500607 this->write(")");
608 } else {
John Stiles791c27d2020-12-30 14:56:57 -0500609 this->writeSimpleIntrinsic(c);
Brian Osman46787d52020-11-24 14:18:23 -0500610 }
611 break;
612 }
John Stilesd7199b22020-12-30 16:22:58 -0500613 case kFaceforward_IntrinsicKind: {
John Stilesad0571f2020-12-10 18:03:10 -0500614 if (arguments[0]->type().columns() == 1) {
615 // ((((Nref) * (I) < 0) ? 1 : -1) * (N))
616 this->write("((((");
Brian Osman00185012021-02-04 16:07:11 -0500617 this->writeExpression(*arguments[2], Precedence::kSequence);
John Stilesad0571f2020-12-10 18:03:10 -0500618 this->write(") * (");
Brian Osman00185012021-02-04 16:07:11 -0500619 this->writeExpression(*arguments[1], Precedence::kSequence);
John Stilesad0571f2020-12-10 18:03:10 -0500620 this->write(") < 0) ? 1 : -1) * (");
Brian Osman00185012021-02-04 16:07:11 -0500621 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stilesad0571f2020-12-10 18:03:10 -0500622 this->write("))");
623 } else {
John Stiles791c27d2020-12-30 14:56:57 -0500624 this->writeSimpleIntrinsic(c);
John Stilesad0571f2020-12-10 18:03:10 -0500625 }
626 break;
627 }
John Stilesd7199b22020-12-30 16:22:58 -0500628 case kLength_IntrinsicKind: {
Brian Osman46787d52020-11-24 14:18:23 -0500629 this->write(arguments[0]->type().columns() == 1 ? "abs(" : "length(");
Brian Osman00185012021-02-04 16:07:11 -0500630 this->writeExpression(*arguments[0], Precedence::kSequence);
Brian Osman46787d52020-11-24 14:18:23 -0500631 this->write(")");
632 break;
633 }
John Stilesd7199b22020-12-30 16:22:58 -0500634 case kNormalize_IntrinsicKind: {
Brian Osman46787d52020-11-24 14:18:23 -0500635 this->write(arguments[0]->type().columns() == 1 ? "sign(" : "normalize(");
Brian Osman00185012021-02-04 16:07:11 -0500636 this->writeExpression(*arguments[0], Precedence::kSequence);
Brian Osman46787d52020-11-24 14:18:23 -0500637 this->write(")");
638 break;
639 }
John Stilesd7199b22020-12-30 16:22:58 -0500640 case kBitcast_IntrinsicKind: {
John Stiles0063a9f2020-12-10 18:01:45 -0500641 this->write(this->getBitcastIntrinsic(c.type()));
642 this->write("(");
Brian Osman00185012021-02-04 16:07:11 -0500643 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stiles0063a9f2020-12-10 18:01:45 -0500644 this->write(")");
645 break;
646 }
John Stilesd7199b22020-12-30 16:22:58 -0500647 case kDegrees_IntrinsicKind: {
John Stilese2d34f82020-12-10 18:02:02 -0500648 this->write("((");
Brian Osman00185012021-02-04 16:07:11 -0500649 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stilese2d34f82020-12-10 18:02:02 -0500650 this->write(") * 57.2957795)");
651 break;
652 }
John Stilesd7199b22020-12-30 16:22:58 -0500653 case kRadians_IntrinsicKind: {
John Stilese2d34f82020-12-10 18:02:02 -0500654 this->write("((");
Brian Osman00185012021-02-04 16:07:11 -0500655 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stilese2d34f82020-12-10 18:02:02 -0500656 this->write(") * 0.0174532925)");
657 break;
658 }
John Stilesd7199b22020-12-30 16:22:58 -0500659 case kDFdx_IntrinsicKind: {
660 this->write("dfdx");
661 this->writeArgumentList(c.arguments());
662 break;
663 }
664 case kDFdy_IntrinsicKind: {
665 // Flipping Y also negates the Y derivatives.
John Stiles270cec22021-02-17 12:59:36 -0500666 if (fProgram.fConfig->fSettings.fFlipY) {
John Stilesd7199b22020-12-30 16:22:58 -0500667 this->write("-");
668 }
669 this->write("dfdy");
670 this->writeArgumentList(c.arguments());
671 break;
672 }
673 case kInverse_IntrinsicKind: {
674 this->write(this->getInversePolyfill(arguments));
675 this->writeArgumentList(c.arguments());
676 break;
677 }
678 case kInversesqrt_IntrinsicKind: {
679 this->write("rsqrt");
680 this->writeArgumentList(c.arguments());
681 break;
682 }
683 case kAtan_IntrinsicKind: {
684 this->write(c.arguments().size() == 2 ? "atan2" : "atan");
685 this->writeArgumentList(c.arguments());
686 break;
687 }
688 case kReflect_IntrinsicKind: {
John Stiles791c27d2020-12-30 14:56:57 -0500689 if (arguments[0]->type().columns() == 1) {
690 // We need to synthesize `I - 2 * N * I * N`.
691 String tmpI = this->getTempVariable(arguments[0]->type());
692 String tmpN = this->getTempVariable(arguments[1]->type());
693
694 // (_skTempI = ...
695 this->write("(" + tmpI + " = ");
Brian Osman00185012021-02-04 16:07:11 -0500696 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stiles791c27d2020-12-30 14:56:57 -0500697
698 // , _skTempN = ...
699 this->write(", " + tmpN + " = ");
Brian Osman00185012021-02-04 16:07:11 -0500700 this->writeExpression(*arguments[1], Precedence::kSequence);
John Stiles791c27d2020-12-30 14:56:57 -0500701
702 // , _skTempI - 2 * _skTempN * _skTempI * _skTempN)
703 this->write(", " + tmpI + " - 2 * " + tmpN + " * " + tmpI + " * " + tmpN + ")");
704 } else {
705 this->writeSimpleIntrinsic(c);
706 }
707 break;
708 }
John Stilesd7199b22020-12-30 16:22:58 -0500709 case kRefract_IntrinsicKind: {
John Stiles4b783d62020-12-30 14:58:07 -0500710 if (arguments[0]->type().columns() == 1) {
711 // Metal does implement refract for vectors; rather than reimplementing refract from
712 // scratch, we can replace the call with `refract(float2(I,0), float2(N,0), eta).x`.
713 this->write("(refract(float2(");
Brian Osman00185012021-02-04 16:07:11 -0500714 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stiles4b783d62020-12-30 14:58:07 -0500715 this->write(", 0), float2(");
Brian Osman00185012021-02-04 16:07:11 -0500716 this->writeExpression(*arguments[1], Precedence::kSequence);
John Stiles4b783d62020-12-30 14:58:07 -0500717 this->write(", 0), ");
Brian Osman00185012021-02-04 16:07:11 -0500718 this->writeExpression(*arguments[2], Precedence::kSequence);
John Stiles4b783d62020-12-30 14:58:07 -0500719 this->write(").x)");
720 } else {
721 this->writeSimpleIntrinsic(c);
722 }
723 break;
724 }
John Stiles23456532020-12-30 18:12:48 -0500725 case kRoundEven_IntrinsicKind: {
726 this->write("rint");
727 this->writeArgumentList(c.arguments());
728 break;
729 }
John Stilesd7199b22020-12-30 16:22:58 -0500730 case kBitCount_IntrinsicKind: {
John Stilese7dc7cb2020-12-22 15:37:14 -0500731 this->write("popcount(");
Brian Osman00185012021-02-04 16:07:11 -0500732 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stilese7dc7cb2020-12-22 15:37:14 -0500733 this->write(")");
734 break;
735 }
John Stilesd7199b22020-12-30 16:22:58 -0500736 case kFindLSB_IntrinsicKind: {
John Stiles86424eb2020-12-11 11:17:14 -0500737 // Create a temp variable to store the expression, to avoid double-evaluating it.
738 String skTemp = this->getTempVariable(arguments[0]->type());
739 String exprType = this->typeName(arguments[0]->type());
740
741 // ctz returns numbits(type) on zero inputs; GLSL documents it as generating -1 instead.
742 // Use select to detect zero inputs and force a -1 result.
743
744 // (_skTemp1 = (.....), select(ctz(_skTemp1), int4(-1), _skTemp1 == int4(0)))
745 this->write("(");
746 this->write(skTemp);
747 this->write(" = (");
Brian Osman00185012021-02-04 16:07:11 -0500748 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stiles86424eb2020-12-11 11:17:14 -0500749 this->write("), select(ctz(");
750 this->write(skTemp);
751 this->write("), ");
752 this->write(exprType);
753 this->write("(-1), ");
754 this->write(skTemp);
755 this->write(" == ");
756 this->write(exprType);
757 this->write("(0)))");
758 break;
759 }
John Stilesd7199b22020-12-30 16:22:58 -0500760 case kFindMSB_IntrinsicKind: {
John Stiles9685e522020-12-14 11:52:14 -0500761 // Create a temp variable to store the expression, to avoid double-evaluating it.
762 String skTemp1 = this->getTempVariable(arguments[0]->type());
763 String exprType = this->typeName(arguments[0]->type());
764
765 // GLSL findMSB is actually quite different from Metal's clz:
766 // - For signed negative numbers, it returns the first zero bit, not the first one bit!
767 // - For an empty input (0/~0 depending on sign), findMSB gives -1; clz is numbits(type)
768
769 // (_skTemp1 = (.....),
770 this->write("(");
771 this->write(skTemp1);
772 this->write(" = (");
Brian Osman00185012021-02-04 16:07:11 -0500773 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stiles9685e522020-12-14 11:52:14 -0500774 this->write("), ");
775
776 // Signed input types might be negative; we need another helper variable to negate the
777 // input (since we can only find one bits, not zero bits).
778 String skTemp2;
779 if (arguments[0]->type().isSigned()) {
780 // ... _skTemp2 = (select(_skTemp1, ~_skTemp1, _skTemp1 < 0)),
781 skTemp2 = this->getTempVariable(arguments[0]->type());
782 this->write(skTemp2);
783 this->write(" = (select(");
784 this->write(skTemp1);
785 this->write(", ~");
786 this->write(skTemp1);
787 this->write(", ");
788 this->write(skTemp1);
789 this->write(" < 0)), ");
790 } else {
791 skTemp2 = skTemp1;
792 }
793
794 // ... select(int4(clz(_skTemp2)), int4(-1), _skTemp2 == int4(0)))
795 this->write("select(");
796 this->write(this->typeName(c.type()));
797 this->write("(clz(");
798 this->write(skTemp2);
799 this->write(")), ");
800 this->write(this->typeName(c.type()));
801 this->write("(-1), ");
802 this->write(skTemp2);
803 this->write(" == ");
804 this->write(exprType);
805 this->write("(0)))");
806 break;
807 }
John Stilesd7199b22020-12-30 16:22:58 -0500808 case kMatrixCompMult_IntrinsicKind: {
809 this->writeMatrixCompMult();
810 this->writeSimpleIntrinsic(c);
811 break;
812 }
813 case kCompareEqual_IntrinsicKind:
814 case kCompareGreaterThan_IntrinsicKind:
815 case kCompareGreaterThanEqual_IntrinsicKind:
816 case kCompareLessThan_IntrinsicKind:
817 case kCompareLessThanEqual_IntrinsicKind:
818 case kCompareNotEqual_IntrinsicKind: {
819 this->write("(");
Brian Osman00185012021-02-04 16:07:11 -0500820 this->writeExpression(*c.arguments()[0], Precedence::kRelational);
John Stilesd7199b22020-12-30 16:22:58 -0500821 switch (kind) {
822 case kCompareEqual_IntrinsicKind:
823 this->write(" == ");
824 break;
825 case kCompareNotEqual_IntrinsicKind:
826 this->write(" != ");
827 break;
828 case kCompareLessThan_IntrinsicKind:
829 this->write(" < ");
830 break;
831 case kCompareLessThanEqual_IntrinsicKind:
832 this->write(" <= ");
833 break;
834 case kCompareGreaterThan_IntrinsicKind:
835 this->write(" > ");
836 break;
837 case kCompareGreaterThanEqual_IntrinsicKind:
838 this->write(" >= ");
839 break;
840 default:
John Stilesf57207b2021-02-02 17:50:34 -0500841 SK_ABORT("unsupported comparison intrinsic kind");
John Stilesd7199b22020-12-30 16:22:58 -0500842 }
Brian Osman00185012021-02-04 16:07:11 -0500843 this->writeExpression(*c.arguments()[1], Precedence::kRelational);
John Stilesd7199b22020-12-30 16:22:58 -0500844 this->write(")");
845 break;
846 }
Timothy Liang6403b0e2018-05-17 10:40:04 -0400847 default:
John Stilesf57207b2021-02-02 17:50:34 -0500848 SK_ABORT("unsupported intrinsic kind");
Timothy Liang6403b0e2018-05-17 10:40:04 -0400849 }
850}
851
John Stilesfcf8cb22020-08-06 14:29:22 -0400852// Assembles a matrix of type floatRxC by resizing another matrix named `x0`.
853// Cells that don't exist in the source matrix will be populated with identity-matrix values.
854void MetalCodeGenerator::assembleMatrixFromMatrix(const Type& sourceMatrix, int rows, int columns) {
855 SkASSERT(rows <= 4);
856 SkASSERT(columns <= 4);
857
858 const char* columnSeparator = "";
859 for (int c = 0; c < columns; ++c) {
860 fExtraFunctions.printf("%sfloat%d(", columnSeparator, rows);
861 columnSeparator = "), ";
862
863 // Determine how many values to take from the source matrix for this row.
864 int swizzleLength = 0;
865 if (c < sourceMatrix.columns()) {
866 swizzleLength = std::min<>(rows, sourceMatrix.rows());
867 }
868
869 // Emit all the values from the source matrix row.
870 bool firstItem;
871 switch (swizzleLength) {
872 case 0: firstItem = true; break;
873 case 1: firstItem = false; fExtraFunctions.printf("x0[%d].x", c); break;
874 case 2: firstItem = false; fExtraFunctions.printf("x0[%d].xy", c); break;
875 case 3: firstItem = false; fExtraFunctions.printf("x0[%d].xyz", c); break;
876 case 4: firstItem = false; fExtraFunctions.printf("x0[%d].xyzw", c); break;
877 default: SkUNREACHABLE;
878 }
879
880 // Emit the placeholder identity-matrix cells.
881 for (int r = swizzleLength; r < rows; ++r) {
882 fExtraFunctions.printf("%s%s", firstItem ? "" : ", ", (r == c) ? "1.0" : "0.0");
883 firstItem = false;
884 }
885 }
886
887 fExtraFunctions.writeText(")");
888}
889
890// Assembles a matrix of type floatRxC by concatenating an arbitrary mix of values, named `x0`,
891// `x1`, etc. An error is written if the expression list don't contain exactly R*C scalars.
John Stiles5abb9e12021-04-06 13:47:19 -0400892void MetalCodeGenerator::assembleMatrixFromExpressions(const AnyConstructor& ctor,
John Stiles8e3b6be2020-10-13 11:14:08 -0400893 int rows, int columns) {
John Stilesfcf8cb22020-08-06 14:29:22 -0400894 size_t argIndex = 0;
895 int argPosition = 0;
John Stiles5abb9e12021-04-06 13:47:19 -0400896 auto args = ctor.argumentSpan();
John Stilesfcf8cb22020-08-06 14:29:22 -0400897
898 const char* columnSeparator = "";
899 for (int c = 0; c < columns; ++c) {
900 fExtraFunctions.printf("%sfloat%d(", columnSeparator, rows);
901 columnSeparator = "), ";
902
903 const char* rowSeparator = "";
904 for (int r = 0; r < rows; ++r) {
905 fExtraFunctions.writeText(rowSeparator);
906 rowSeparator = ", ";
907
908 if (argIndex < args.size()) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400909 const Type& argType = args[argIndex]->type();
Ethan Nicholase6592142020-09-08 10:22:09 -0400910 switch (argType.typeKind()) {
911 case Type::TypeKind::kScalar: {
John Stilesfcf8cb22020-08-06 14:29:22 -0400912 fExtraFunctions.printf("x%zu", argIndex);
913 break;
914 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400915 case Type::TypeKind::kVector: {
John Stilesfcf8cb22020-08-06 14:29:22 -0400916 fExtraFunctions.printf("x%zu[%d]", argIndex, argPosition);
917 break;
918 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400919 case Type::TypeKind::kMatrix: {
John Stilesfcf8cb22020-08-06 14:29:22 -0400920 fExtraFunctions.printf("x%zu[%d][%d]", argIndex,
921 argPosition / argType.rows(),
922 argPosition % argType.rows());
923 break;
924 }
925 default: {
926 SkDEBUGFAIL("incorrect type of argument for matrix constructor");
927 fExtraFunctions.writeText("<error>");
928 break;
929 }
930 }
931
932 ++argPosition;
933 if (argPosition >= argType.columns() * argType.rows()) {
934 ++argIndex;
935 argPosition = 0;
936 }
937 } else {
938 SkDEBUGFAIL("not enough arguments for matrix constructor");
939 fExtraFunctions.writeText("<error>");
940 }
941 }
942 }
943
944 if (argPosition != 0 || argIndex != args.size()) {
945 SkDEBUGFAIL("incorrect number of arguments for matrix constructor");
946 fExtraFunctions.writeText(", <error>");
947 }
948
949 fExtraFunctions.writeText(")");
950}
951
John Stiles1bdafbf2020-05-28 12:17:20 -0400952// Generates a constructor for 'matrix' which reorganizes the input arguments into the proper shape.
953// Keeps track of previously generated constructors so that we won't generate more than one
954// constructor for any given permutation of input argument types. Returns the name of the
955// generated constructor method.
John Stiles5abb9e12021-04-06 13:47:19 -0400956String MetalCodeGenerator::getMatrixConstructHelper(const AnyConstructor& c) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400957 const Type& matrix = c.type();
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500958 int columns = matrix.columns();
959 int rows = matrix.rows();
John Stiles5abb9e12021-04-06 13:47:19 -0400960 auto args = c.argumentSpan();
John Stiles1bdafbf2020-05-28 12:17:20 -0400961
962 // Create the helper-method name and use it as our lookup key.
963 String name;
964 name.appendf("float%dx%d_from", columns, rows);
965 for (const std::unique_ptr<Expression>& expr : args) {
John Stiles36129132020-12-29 12:28:04 -0500966 name.appendf("_%s", this->typeName(expr->type()).c_str());
John Stiles1bdafbf2020-05-28 12:17:20 -0400967 }
968
969 // If a helper-method has already been synthesized, we don't need to synthesize it again.
970 auto [iter, newlyCreated] = fHelpers.insert(name);
971 if (!newlyCreated) {
972 return name;
973 }
974
975 // Unlike GLSL, Metal requires that matrices are initialized with exactly R vectors of C
976 // components apiece. (In Metal 2.0, you can also supply R*C scalars, but you still cannot
977 // supply a mixture of scalars and vectors.)
978 fExtraFunctions.printf("float%dx%d %s(", columns, rows, name.c_str());
979
980 size_t argIndex = 0;
981 const char* argSeparator = "";
John Stilesfcf8cb22020-08-06 14:29:22 -0400982 for (const std::unique_ptr<Expression>& expr : args) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400983 fExtraFunctions.printf("%s%s x%zu", argSeparator,
John Stiles36129132020-12-29 12:28:04 -0500984 this->typeName(expr->type()).c_str(), argIndex++);
John Stiles1bdafbf2020-05-28 12:17:20 -0400985 argSeparator = ", ";
986 }
987
988 fExtraFunctions.printf(") {\n return float%dx%d(", columns, rows);
989
John Stiles9aeed132020-11-24 17:36:06 -0500990 if (args.size() == 1 && args.front()->type().isMatrix()) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400991 this->assembleMatrixFromMatrix(args.front()->type(), rows, columns);
John Stilesfcf8cb22020-08-06 14:29:22 -0400992 } else {
John Stiles5abb9e12021-04-06 13:47:19 -0400993 this->assembleMatrixFromExpressions(c, rows, columns);
John Stiles1bdafbf2020-05-28 12:17:20 -0400994 }
995
John Stilesfcf8cb22020-08-06 14:29:22 -0400996 fExtraFunctions.writeText(");\n}\n");
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500997 return name;
998}
999
1000bool MetalCodeGenerator::canCoerce(const Type& t1, const Type& t2) {
1001 if (t1.columns() != t2.columns() || t1.rows() != t2.rows()) {
1002 return false;
1003 }
1004 if (t1.columns() > 1) {
1005 return this->canCoerce(t1.componentType(), t2.componentType());
1006 }
Ethan Nicholase1f55022019-02-05 17:17:40 -05001007 return t1.isFloat() && t2.isFloat();
Ethan Nicholas842d31b2019-01-22 10:59:11 -05001008}
1009
John Stiles8cad6372021-04-07 12:31:13 -04001010bool MetalCodeGenerator::matrixConstructHelperIsNeeded(const ConstructorCompound& c) {
John Stiles2bec8ab2021-04-06 18:40:04 -04001011 SkASSERT(c.type().isMatrix());
John Stiles1bdafbf2020-05-28 12:17:20 -04001012
1013 // GLSL is fairly free-form about inputs to its matrix constructors, but Metal is not; it
1014 // expects exactly R vectors of C components apiece. (Metal 2.0 also allows a list of R*C
1015 // scalars.) Some cases are simple to translate and so we handle those inline--e.g. a list of
1016 // scalars can be constructed trivially. In more complex cases, we generate a helper function
1017 // that converts our inputs into a properly-shaped matrix.
1018 // A matrix construct helper method is always used if any input argument is a matrix.
1019 // Helper methods are also necessary when any argument would span multiple rows. For instance:
1020 //
1021 // float2 x = (1, 2);
1022 // float3x2(x, 3, 4, 5, 6) = | 1 3 5 | = no helper needed; conversion can be done inline
1023 // | 2 4 6 |
1024 //
1025 // float2 x = (2, 3);
1026 // float3x2(1, x, 4, 5, 6) = | 1 3 5 | = x spans multiple rows; a helper method will be used
1027 // | 2 4 6 |
1028 //
1029 // float4 x = (1, 2, 3, 4);
1030 // float2x2(x) = | 1 3 | = x spans multiple rows; a helper method will be used
1031 // | 2 4 |
1032 //
1033
1034 int position = 0;
Ethan Nicholasf70f0442020-09-29 12:41:35 -04001035 for (const std::unique_ptr<Expression>& expr : c.arguments()) {
John Stiles1bdafbf2020-05-28 12:17:20 -04001036 // If an input argument is a matrix, we need a helper function.
John Stiles9aeed132020-11-24 17:36:06 -05001037 if (expr->type().isMatrix()) {
John Stiles1bdafbf2020-05-28 12:17:20 -04001038 return true;
1039 }
Ethan Nicholas30d30222020-09-11 12:27:26 -04001040 position += expr->type().columns();
1041 if (position > c.type().rows()) {
John Stiles1bdafbf2020-05-28 12:17:20 -04001042 // An input argument would span multiple rows; a helper function is required.
1043 return true;
1044 }
Ethan Nicholas30d30222020-09-11 12:27:26 -04001045 if (position == c.type().rows()) {
John Stiles1bdafbf2020-05-28 12:17:20 -04001046 // We've advanced to the end of a row. Wrap to the start of the next row.
1047 position = 0;
1048 }
1049 }
1050
1051 return false;
1052}
1053
John Stiles5abb9e12021-04-06 13:47:19 -04001054void MetalCodeGenerator::writeConstructorMatrixResize(const ConstructorMatrixResize& c,
1055 Precedence parentPrecedence) {
1056 // Matrix-resize via casting doesn't natively exist in Metal at all, so we always need to use a
1057 // matrix-construct helper here.
1058 this->write(this->getMatrixConstructHelper(c));
1059 this->write("(");
1060 this->writeExpression(*c.argument(), Precedence::kSequence);
1061 this->write(")");
1062}
1063
John Stiles8cad6372021-04-07 12:31:13 -04001064void MetalCodeGenerator::writeConstructorCompound(const ConstructorCompound& c,
1065 Precedence parentPrecedence) {
John Stiles2bec8ab2021-04-06 18:40:04 -04001066 if (c.type().isMatrix()) {
John Stiles8cad6372021-04-07 12:31:13 -04001067 this->writeConstructorCompoundMatrix(c, parentPrecedence);
John Stiles2bec8ab2021-04-06 18:40:04 -04001068 } else {
1069 this->writeAnyConstructor(c, "(", ")", parentPrecedence);
1070 }
1071}
John Stiles7384b372021-04-01 13:48:15 -04001072
John Stiles8cad6372021-04-07 12:31:13 -04001073void MetalCodeGenerator::writeConstructorCompoundMatrix(const ConstructorCompound& c,
1074 Precedence parentPrecedence) {
John Stiles1bdafbf2020-05-28 12:17:20 -04001075 // Emit and invoke a matrix-constructor helper method if one is necessary.
1076 if (this->matrixConstructHelperIsNeeded(c)) {
1077 this->write(this->getMatrixConstructHelper(c));
John Stiles1fa15b12020-05-28 17:36:54 +00001078 this->write("(");
1079 const char* separator = "";
Ethan Nicholasf70f0442020-09-29 12:41:35 -04001080 for (const std::unique_ptr<Expression>& expr : c.arguments()) {
John Stiles1fa15b12020-05-28 17:36:54 +00001081 this->write(separator);
1082 separator = ", ";
Brian Osman00185012021-02-04 16:07:11 -05001083 this->writeExpression(*expr, Precedence::kSequence);
John Stilesdaa573e2020-05-28 12:17:20 -04001084 }
John Stiles1fa15b12020-05-28 17:36:54 +00001085 this->write(")");
John Stiles1bdafbf2020-05-28 12:17:20 -04001086 return;
John Stilesdaa573e2020-05-28 12:17:20 -04001087 }
John Stiles1bdafbf2020-05-28 12:17:20 -04001088
John Stiles2bec8ab2021-04-06 18:40:04 -04001089 // Metal doesn't allow creating matrices by passing in scalars and vectors in a jumble; it
1090 // requires your scalars to be grouped up into columns. Because `matrixConstructHelperIsNeeded`
1091 // returned false, we know that none of our scalars/vectors "wrap" across across a column, so we
1092 // can group our inputs up and synthesize a constructor for each column.
1093 const Type& matrixType = c.type();
1094 const Type& columnType = matrixType.componentType().toCompound(
1095 fContext, /*columns=*/matrixType.rows(), /*rows=*/1);
1096
1097 this->writeType(matrixType);
John Stiles7384b372021-04-01 13:48:15 -04001098 this->write("(");
John Stiles1bdafbf2020-05-28 12:17:20 -04001099 const char* separator = "";
1100 int scalarCount = 0;
Ethan Nicholasf70f0442020-09-29 12:41:35 -04001101 for (const std::unique_ptr<Expression>& arg : c.arguments()) {
John Stiles1bdafbf2020-05-28 12:17:20 -04001102 this->write(separator);
1103 separator = ", ";
John Stiles2bec8ab2021-04-06 18:40:04 -04001104 if (arg->type().columns() < matrixType.rows()) {
1105 // Write a `floatN(` constructor to group scalars and smaller vectors together.
John Stiles1bdafbf2020-05-28 12:17:20 -04001106 if (!scalarCount) {
John Stiles2bec8ab2021-04-06 18:40:04 -04001107 this->writeType(columnType);
John Stiles1bdafbf2020-05-28 12:17:20 -04001108 this->write("(");
1109 }
John Stiles2bec8ab2021-04-06 18:40:04 -04001110 scalarCount += arg->type().columns();
John Stiles1bdafbf2020-05-28 12:17:20 -04001111 }
Brian Osman00185012021-02-04 16:07:11 -05001112 this->writeExpression(*arg, Precedence::kSequence);
John Stiles2bec8ab2021-04-06 18:40:04 -04001113 if (scalarCount && scalarCount == matrixType.rows()) {
1114 // Close our `floatN(...` constructor block from above.
John Stiles1bdafbf2020-05-28 12:17:20 -04001115 this->write(")");
1116 scalarCount = 0;
1117 }
1118 }
John Stiles7384b372021-04-01 13:48:15 -04001119 this->write(")");
Ethan Nicholascc305772017-10-13 16:17:45 -04001120}
1121
John Stilesb14a8192021-04-05 11:40:46 -04001122void MetalCodeGenerator::writeAnyConstructor(const AnyConstructor& c,
1123 const char* leftBracket,
1124 const char* rightBracket,
1125 Precedence parentPrecedence) {
John Stilese1182782021-03-30 22:09:37 -04001126 this->writeType(c.type());
John Stilesb14a8192021-04-05 11:40:46 -04001127 this->write(leftBracket);
John Stiles7384b372021-04-01 13:48:15 -04001128 const char* separator = "";
John Stilesb14a8192021-04-05 11:40:46 -04001129 for (const std::unique_ptr<Expression>& arg : c.argumentSpan()) {
John Stiles7384b372021-04-01 13:48:15 -04001130 this->write(separator);
1131 separator = ", ";
1132 this->writeExpression(*arg, Precedence::kSequence);
1133 }
John Stilesb14a8192021-04-05 11:40:46 -04001134 this->write(rightBracket);
John Stiles7384b372021-04-01 13:48:15 -04001135}
1136
John Stilesb14a8192021-04-05 11:40:46 -04001137void MetalCodeGenerator::writeCastConstructor(const AnyConstructor& c,
1138 const char* leftBracket,
1139 const char* rightBracket,
1140 Precedence parentPrecedence) {
1141 // If the type is coercible, emit it directly without the cast.
1142 auto args = c.argumentSpan();
1143 if (args.size() == 1) {
1144 if (this->canCoerce(c.type(), args.front()->type())) {
1145 this->writeExpression(*args.front(), parentPrecedence);
1146 return;
1147 }
John Stilesfd7252f2021-04-04 22:24:40 -04001148 }
1149
John Stilesb14a8192021-04-05 11:40:46 -04001150 return this->writeAnyConstructor(c, leftBracket, rightBracket, parentPrecedence);
John Stilesfd7252f2021-04-04 22:24:40 -04001151}
1152
Ethan Nicholascc305772017-10-13 16:17:45 -04001153void MetalCodeGenerator::writeFragCoord() {
Ethan Nicholasf931e402019-07-26 15:40:33 -04001154 if (fRTHeightName.length()) {
1155 this->write("float4(_fragCoord.x, ");
1156 this->write(fRTHeightName.c_str());
1157 this->write(" - _fragCoord.y, 0.0, _fragCoord.w)");
Jim Van Verth6bc650e2019-02-07 14:53:23 -05001158 } else {
1159 this->write("float4(_fragCoord.x, _fragCoord.y, 0.0, _fragCoord.w)");
1160 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001161}
1162
1163void MetalCodeGenerator::writeVariableReference(const VariableReference& ref) {
John Stiles06b84ef2020-12-09 12:35:48 -05001164 // When assembling out-param helper functions, we copy variables into local clones with matching
John Stilesf7410bd2021-01-19 13:07:55 -05001165 // names. We never want to prepend "_in." or "_globals." when writing these variables since
John Stiles06b84ef2020-12-09 12:35:48 -05001166 // we're actually targeting the clones.
1167 if (fIgnoreVariableReferenceModifiers) {
1168 this->writeName(ref.variable()->name());
1169 return;
1170 }
1171
Ethan Nicholas78686922020-10-08 06:46:27 -04001172 switch (ref.variable()->modifiers().fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001173 case SK_FRAGCOLOR_BUILTIN:
John Stilesf7410bd2021-01-19 13:07:55 -05001174 this->write("_out.sk_FragColor");
Ethan Nicholascc305772017-10-13 16:17:45 -04001175 break;
Timothy Liang6403b0e2018-05-17 10:40:04 -04001176 case SK_FRAGCOORD_BUILTIN:
1177 this->writeFragCoord();
1178 break;
Timothy Liangdc89f192018-06-13 09:20:31 -04001179 case SK_VERTEXID_BUILTIN:
1180 this->write("sk_VertexID");
1181 break;
1182 case SK_INSTANCEID_BUILTIN:
1183 this->write("sk_InstanceID");
1184 break;
Timothy Liang7b8875d2018-08-10 09:42:31 -04001185 case SK_CLOCKWISE_BUILTIN:
1186 // We'd set the front facing winding in the MTLRenderCommandEncoder to be counter
Brian Salomonf4ba4ec2020-03-19 15:54:28 -04001187 // clockwise to match Skia convention.
John Stiles270cec22021-02-17 12:59:36 -05001188 this->write(fProgram.fConfig->fSettings.fFlipY ? "_frontFacing" : "(!_frontFacing)");
Timothy Liang7b8875d2018-08-10 09:42:31 -04001189 break;
Ethan Nicholascc305772017-10-13 16:17:45 -04001190 default:
Ethan Nicholas78686922020-10-08 06:46:27 -04001191 const Variable& var = *ref.variable();
Ethan Nicholas453f67f2020-10-09 10:43:45 -04001192 if (var.storage() == Variable::Storage::kGlobal) {
Ethan Nicholas78686922020-10-08 06:46:27 -04001193 if (var.modifiers().fFlags & Modifiers::kIn_Flag) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001194 this->write("_in.");
Ethan Nicholas78686922020-10-08 06:46:27 -04001195 } else if (var.modifiers().fFlags & Modifiers::kOut_Flag) {
John Stilesf7410bd2021-01-19 13:07:55 -05001196 this->write("_out.");
Ethan Nicholas78686922020-10-08 06:46:27 -04001197 } else if (var.modifiers().fFlags & Modifiers::kUniform_Flag &&
1198 var.type().typeKind() != Type::TypeKind::kSampler) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001199 this->write("_uniforms.");
1200 } else {
John Stilesf7410bd2021-01-19 13:07:55 -05001201 this->write("_globals.");
Ethan Nicholascc305772017-10-13 16:17:45 -04001202 }
1203 }
Ethan Nicholas78686922020-10-08 06:46:27 -04001204 this->writeName(var.name());
Ethan Nicholascc305772017-10-13 16:17:45 -04001205 }
1206}
1207
1208void MetalCodeGenerator::writeIndexExpression(const IndexExpression& expr) {
Brian Osman00185012021-02-04 16:07:11 -05001209 this->writeExpression(*expr.base(), Precedence::kPostfix);
Ethan Nicholascc305772017-10-13 16:17:45 -04001210 this->write("[");
Brian Osman00185012021-02-04 16:07:11 -05001211 this->writeExpression(*expr.index(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001212 this->write("]");
1213}
1214
1215void MetalCodeGenerator::writeFieldAccess(const FieldAccess& f) {
Ethan Nicholas7a95b202020-10-09 11:55:40 -04001216 const Type::Field* field = &f.base()->type().fields()[f.fieldIndex()];
1217 if (FieldAccess::OwnerKind::kDefault == f.ownerKind()) {
Brian Osman00185012021-02-04 16:07:11 -05001218 this->writeExpression(*f.base(), Precedence::kPostfix);
Ethan Nicholascc305772017-10-13 16:17:45 -04001219 this->write(".");
1220 }
Timothy Liang7d637782018-06-05 09:58:07 -04001221 switch (field->fModifiers.fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001222 case SK_POSITION_BUILTIN:
John Stilesf7410bd2021-01-19 13:07:55 -05001223 this->write("_out.sk_Position");
Ethan Nicholascc305772017-10-13 16:17:45 -04001224 break;
1225 default:
Timothy Liang7d637782018-06-05 09:58:07 -04001226 if (field->fName == "sk_PointSize") {
John Stilesf7410bd2021-01-19 13:07:55 -05001227 this->write("_out.sk_PointSize");
Timothy Liang7d637782018-06-05 09:58:07 -04001228 } else {
Ethan Nicholas7a95b202020-10-09 11:55:40 -04001229 if (FieldAccess::OwnerKind::kAnonymousInterfaceBlock == f.ownerKind()) {
John Stilesf7410bd2021-01-19 13:07:55 -05001230 this->write("_globals.");
Timothy Liang7d637782018-06-05 09:58:07 -04001231 this->write(fInterfaceBlockNameMap[fInterfaceBlockMap[field]]);
1232 this->write("->");
1233 }
Timothy Liang651286f2018-06-07 09:55:33 -04001234 this->writeName(field->fName);
Timothy Lianga06f2152018-05-24 15:33:31 -04001235 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001236 }
1237}
1238
1239void MetalCodeGenerator::writeSwizzle(const Swizzle& swizzle) {
Brian Osman00185012021-02-04 16:07:11 -05001240 this->writeExpression(*swizzle.base(), Precedence::kPostfix);
Ethan Nicholascc305772017-10-13 16:17:45 -04001241 this->write(".");
Ethan Nicholas6b4d5812020-10-12 16:11:51 -04001242 for (int c : swizzle.components()) {
Brian Osman25647672020-09-15 15:16:56 -04001243 SkASSERT(c >= 0 && c <= 3);
1244 this->write(&("x\0y\0z\0w\0"[c * 2]));
Ethan Nicholascc305772017-10-13 16:17:45 -04001245 }
1246}
1247
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001248void MetalCodeGenerator::writeMatrixTimesEqualHelper(const Type& left, const Type& right,
1249 const Type& result) {
John Stiles39346472021-04-29 14:39:35 -04001250 String key = "TimesEqual " + this->typeName(left) + ":" + this->typeName(right);
John Stiles56233d12021-02-03 13:03:29 -05001251
1252 auto [iter, wasInserted] = fHelpers.insert(key);
1253 if (wasInserted) {
John Stiles368db7c2020-12-29 11:20:08 -05001254 fExtraFunctions.printf("thread %s& operator*=(thread %s& left, thread const %s& right) {\n"
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001255 " left = left * right;\n"
1256 " return left;\n"
John Stiles368db7c2020-12-29 11:20:08 -05001257 "}\n",
1258 this->typeName(result).c_str(), this->typeName(left).c_str(),
1259 this->typeName(right).c_str());
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001260 }
1261}
1262
John Stiles39346472021-04-29 14:39:35 -04001263void MetalCodeGenerator::writeMatrixEqualityHelpers(const Type& left, const Type& right) {
1264 SkASSERT(left.isMatrix());
1265 SkASSERT(right.isMatrix());
1266 SkASSERT(left.rows() == right.rows());
1267 SkASSERT(left.columns() == right.columns());
John Stiles01cdf012021-02-10 09:53:41 -05001268
John Stiles39346472021-04-29 14:39:35 -04001269 String key = "MatrixEquality " + this->typeName(left) + ":" + this->typeName(right);
John Stiles01cdf012021-02-10 09:53:41 -05001270
1271 auto [iter, wasInserted] = fHelpers.insert(key);
1272 if (wasInserted) {
1273 fExtraFunctions.printf(
1274 "thread bool operator==(const %s left, const %s right) {\n"
John Stiles39346472021-04-29 14:39:35 -04001275 " return ",
John Stiles01cdf012021-02-10 09:53:41 -05001276 this->typeName(left).c_str(), this->typeName(right).c_str());
1277
John Stiles39346472021-04-29 14:39:35 -04001278 const char* separator = "";
John Stiles01cdf012021-02-10 09:53:41 -05001279 for (int index=0; index<left.columns(); ++index) {
John Stiles39346472021-04-29 14:39:35 -04001280 fExtraFunctions.printf("%sall(left[%d] == right[%d])", separator, index, index);
1281 separator = " &&\n ";
John Stiles01cdf012021-02-10 09:53:41 -05001282 }
John Stiles39346472021-04-29 14:39:35 -04001283
1284 fExtraFunctions.printf(
1285 ";\n"
1286 "}\n"
1287 "thread bool operator!=(const %s left, const %s right) {\n"
1288 " return !(left == right);\n"
1289 "}\n",
1290 this->typeName(left).c_str(), this->typeName(right).c_str());
John Stiles01cdf012021-02-10 09:53:41 -05001291 }
1292}
1293
John Stiles39346472021-04-29 14:39:35 -04001294void MetalCodeGenerator::writeArrayEqualityHelpers(const Type& type) {
1295 SkASSERT(type.isArray());
John Stiles01cdf012021-02-10 09:53:41 -05001296
John Stiles39346472021-04-29 14:39:35 -04001297 // If the array's component type needs a helper as well, we need to emit that one first.
1298 this->writeEqualityHelpers(type.componentType(), type.componentType());
1299
1300 auto [iter, wasInserted] = fHelpers.insert("ArrayEquality []");
1301 if (wasInserted) {
1302 fExtraFunctions.writeText(R"(
1303template <typename T, size_t N>
1304bool operator==(thread const array<T, N>& left, thread const array<T, N>& right) {
1305 for (size_t index = 0; index < N; ++index) {
1306 if (!(left[index] == right[index])) {
1307 return false;
1308 }
1309 }
1310 return true;
1311}
1312
1313template <typename T, size_t N>
1314bool operator!=(thread const array<T, N>& left, thread const array<T, N>& right) {
1315 return !(left == right);
1316}
1317)");
1318 }
1319}
1320
1321void MetalCodeGenerator::writeStructEqualityHelpers(const Type& type) {
1322 SkASSERT(type.isStruct());
1323 String key = "StructEquality " + this->typeName(type);
John Stiles01cdf012021-02-10 09:53:41 -05001324
1325 auto [iter, wasInserted] = fHelpers.insert(key);
1326 if (wasInserted) {
John Stiles39346472021-04-29 14:39:35 -04001327 // If one of the struct's fields needs a helper as well, we need to emit that one first.
1328 for (const Type::Field& field : type.fields()) {
1329 this->writeEqualityHelpers(*field.fType, *field.fType);
John Stiles830c69c2021-04-28 17:16:16 -04001330 }
John Stiles39346472021-04-29 14:39:35 -04001331
1332 // Write operator== and operator!= for this struct, since those are assumed to exist in SkSL
1333 // and GLSL but do not exist by default in Metal.
1334 fExtraFunctions.printf(
1335 "thread bool operator==(thread const %s& left, thread const %s& right) {\n"
1336 " return ",
1337 this->typeName(type).c_str(),
1338 this->typeName(type).c_str());
1339
1340 const char* separator = "";
1341 for (const Type::Field& field : type.fields()) {
1342 fExtraFunctions.printf("%s(left.%.*s == right.%.*s)",
1343 separator,
1344 (int)field.fName.size(), field.fName.data(),
1345 (int)field.fName.size(), field.fName.data());
1346 separator = " &&\n ";
1347 }
1348 fExtraFunctions.printf(
1349 ";\n"
1350 "}\n"
1351 "thread bool operator!=(thread const %s& left, thread const %s& right) {\n"
1352 " return !(left == right);\n"
1353 "}\n",
1354 this->typeName(type).c_str(),
1355 this->typeName(type).c_str());
1356 }
1357}
1358
1359void MetalCodeGenerator::writeEqualityHelpers(const Type& leftType, const Type& rightType) {
1360 if (leftType.isArray() && rightType.isArray()) {
1361 this->writeArrayEqualityHelpers(leftType);
1362 return;
1363 }
1364 if (leftType.isStruct() && rightType.isStruct()) {
1365 this->writeStructEqualityHelpers(leftType);
1366 return;
1367 }
1368 if (leftType.isMatrix() && rightType.isMatrix()) {
1369 this->writeMatrixEqualityHelpers(leftType, rightType);
1370 return;
John Stiles01cdf012021-02-10 09:53:41 -05001371 }
1372}
1373
Ethan Nicholascc305772017-10-13 16:17:45 -04001374void MetalCodeGenerator::writeBinaryExpression(const BinaryExpression& b,
1375 Precedence parentPrecedence) {
John Stiles2d4f9592020-10-30 10:29:12 -04001376 const Expression& left = *b.left();
1377 const Expression& right = *b.right();
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001378 const Type& leftType = left.type();
1379 const Type& rightType = right.type();
John Stiles45990502021-02-16 10:55:27 -05001380 Operator op = b.getOperator();
1381 Precedence precedence = op.getBinaryPrecedence();
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001382 bool needParens = precedence >= parentPrecedence;
John Stiles45990502021-02-16 10:55:27 -05001383 switch (op.kind()) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001384 case Token::Kind::TK_EQEQ:
John Stiles39346472021-04-29 14:39:35 -04001385 this->writeEqualityHelpers(leftType, rightType);
John Stiles9aeed132020-11-24 17:36:06 -05001386 if (leftType.isVector()) {
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001387 this->write("all");
1388 needParens = true;
1389 }
1390 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001391 case Token::Kind::TK_NEQ:
John Stiles39346472021-04-29 14:39:35 -04001392 this->writeEqualityHelpers(leftType, rightType);
John Stiles9aeed132020-11-24 17:36:06 -05001393 if (leftType.isVector()) {
Jim Van Verth36477b42019-04-11 14:57:30 -04001394 this->write("any");
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001395 needParens = true;
1396 }
1397 break;
1398 default:
1399 break;
1400 }
1401 if (needParens) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001402 this->write("(");
1403 }
John Stiles39346472021-04-29 14:39:35 -04001404 if (leftType.isMatrix() && rightType.isMatrix() && op.kind() == Token::Kind::TK_STAREQ) {
1405 this->writeMatrixTimesEqualHelper(leftType, rightType, b.type());
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001406 }
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001407 this->writeExpression(left, precedence);
John Stiles45990502021-02-16 10:55:27 -05001408 if (op.kind() != Token::Kind::TK_EQ && op.isAssignment() &&
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001409 left.kind() == Expression::Kind::kSwizzle && !left.hasSideEffects()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001410 // This doesn't compile in Metal:
1411 // float4 x = float4(1);
1412 // x.xy *= float2x2(...);
1413 // with the error message "non-const reference cannot bind to vector element",
1414 // but switching it to x.xy = x.xy * float2x2(...) fixes it. We perform this tranformation
1415 // as long as the LHS has no side effects, and hope for the best otherwise.
1416 this->write(" = ");
Brian Osman00185012021-02-04 16:07:11 -05001417 this->writeExpression(left, Precedence::kAssignment);
Ethan Nicholascc305772017-10-13 16:17:45 -04001418 this->write(" ");
John Stilesd6449e92020-11-30 09:13:23 -05001419 String opName = OperatorName(op);
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001420 SkASSERT(opName.endsWith("="));
1421 this->write(opName.substr(0, opName.size() - 1).c_str());
Ethan Nicholascc305772017-10-13 16:17:45 -04001422 this->write(" ");
1423 } else {
John Stilesd6449e92020-11-30 09:13:23 -05001424 this->write(String(" ") + OperatorName(op) + " ");
Ethan Nicholascc305772017-10-13 16:17:45 -04001425 }
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001426 this->writeExpression(right, precedence);
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001427 if (needParens) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001428 this->write(")");
1429 }
1430}
1431
1432void MetalCodeGenerator::writeTernaryExpression(const TernaryExpression& t,
1433 Precedence parentPrecedence) {
Brian Osman00185012021-02-04 16:07:11 -05001434 if (Precedence::kTernary >= parentPrecedence) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001435 this->write("(");
1436 }
Brian Osman00185012021-02-04 16:07:11 -05001437 this->writeExpression(*t.test(), Precedence::kTernary);
Ethan Nicholascc305772017-10-13 16:17:45 -04001438 this->write(" ? ");
Brian Osman00185012021-02-04 16:07:11 -05001439 this->writeExpression(*t.ifTrue(), Precedence::kTernary);
Ethan Nicholascc305772017-10-13 16:17:45 -04001440 this->write(" : ");
Brian Osman00185012021-02-04 16:07:11 -05001441 this->writeExpression(*t.ifFalse(), Precedence::kTernary);
1442 if (Precedence::kTernary >= parentPrecedence) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001443 this->write(")");
1444 }
1445}
1446
1447void MetalCodeGenerator::writePrefixExpression(const PrefixExpression& p,
1448 Precedence parentPrecedence) {
Brian Osman00185012021-02-04 16:07:11 -05001449 if (Precedence::kPrefix >= parentPrecedence) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001450 this->write("(");
1451 }
John Stilesd6449e92020-11-30 09:13:23 -05001452 this->write(OperatorName(p.getOperator()));
Brian Osman00185012021-02-04 16:07:11 -05001453 this->writeExpression(*p.operand(), Precedence::kPrefix);
1454 if (Precedence::kPrefix >= parentPrecedence) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001455 this->write(")");
1456 }
1457}
1458
1459void MetalCodeGenerator::writePostfixExpression(const PostfixExpression& p,
1460 Precedence parentPrecedence) {
Brian Osman00185012021-02-04 16:07:11 -05001461 if (Precedence::kPostfix >= parentPrecedence) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001462 this->write("(");
1463 }
Brian Osman00185012021-02-04 16:07:11 -05001464 this->writeExpression(*p.operand(), Precedence::kPostfix);
John Stilesd6449e92020-11-30 09:13:23 -05001465 this->write(OperatorName(p.getOperator()));
Brian Osman00185012021-02-04 16:07:11 -05001466 if (Precedence::kPostfix >= parentPrecedence) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001467 this->write(")");
1468 }
1469}
1470
1471void MetalCodeGenerator::writeBoolLiteral(const BoolLiteral& b) {
Ethan Nicholas59d660c2020-09-28 09:18:15 -04001472 this->write(b.value() ? "true" : "false");
Ethan Nicholascc305772017-10-13 16:17:45 -04001473}
1474
1475void MetalCodeGenerator::writeIntLiteral(const IntLiteral& i) {
John Stiles12739df2020-12-29 09:47:20 -05001476 const Type& type = i.type();
John Stiles54e7c052021-01-11 14:22:36 -05001477 if (type == *fContext.fTypes.fUInt) {
Ethan Nicholase96cdd12020-09-28 16:27:18 -04001478 this->write(to_string(i.value() & 0xffffffff) + "u");
John Stiles54e7c052021-01-11 14:22:36 -05001479 } else if (type == *fContext.fTypes.fUShort) {
John Stiles12739df2020-12-29 09:47:20 -05001480 this->write(to_string(i.value() & 0xffff) + "u");
Ethan Nicholascc305772017-10-13 16:17:45 -04001481 } else {
John Stiles12739df2020-12-29 09:47:20 -05001482 this->write(to_string(i.value()));
Ethan Nicholascc305772017-10-13 16:17:45 -04001483 }
1484}
1485
1486void MetalCodeGenerator::writeFloatLiteral(const FloatLiteral& f) {
Ethan Nicholasa3f22f12020-10-01 12:13:17 -04001487 this->write(to_string(f.value()));
Ethan Nicholascc305772017-10-13 16:17:45 -04001488}
1489
1490void MetalCodeGenerator::writeSetting(const Setting& s) {
John Stilesf57207b2021-02-02 17:50:34 -05001491 SK_ABORT("internal error; setting was not folded to a constant during compilation\n");
Ethan Nicholascc305772017-10-13 16:17:45 -04001492}
1493
John Stiles06b84ef2020-12-09 12:35:48 -05001494void MetalCodeGenerator::writeFunctionRequirementArgs(const FunctionDeclaration& f,
1495 const char*& separator) {
1496 Requirements requirements = this->requirements(f);
1497 if (requirements & kInputs_Requirement) {
1498 this->write(separator);
1499 this->write("_in");
1500 separator = ", ";
1501 }
1502 if (requirements & kOutputs_Requirement) {
1503 this->write(separator);
1504 this->write("_out");
1505 separator = ", ";
1506 }
1507 if (requirements & kUniforms_Requirement) {
1508 this->write(separator);
1509 this->write("_uniforms");
1510 separator = ", ";
1511 }
1512 if (requirements & kGlobals_Requirement) {
1513 this->write(separator);
John Stilesf7410bd2021-01-19 13:07:55 -05001514 this->write("_globals");
John Stiles06b84ef2020-12-09 12:35:48 -05001515 separator = ", ";
1516 }
1517 if (requirements & kFragCoord_Requirement) {
1518 this->write(separator);
1519 this->write("_fragCoord");
1520 separator = ", ";
1521 }
1522}
1523
1524void MetalCodeGenerator::writeFunctionRequirementParams(const FunctionDeclaration& f,
1525 const char*& separator) {
1526 Requirements requirements = this->requirements(f);
1527 if (requirements & kInputs_Requirement) {
1528 this->write(separator);
1529 this->write("Inputs _in");
1530 separator = ", ";
1531 }
1532 if (requirements & kOutputs_Requirement) {
1533 this->write(separator);
John Stilesf7410bd2021-01-19 13:07:55 -05001534 this->write("thread Outputs& _out");
John Stiles06b84ef2020-12-09 12:35:48 -05001535 separator = ", ";
1536 }
1537 if (requirements & kUniforms_Requirement) {
1538 this->write(separator);
1539 this->write("Uniforms _uniforms");
1540 separator = ", ";
1541 }
1542 if (requirements & kGlobals_Requirement) {
1543 this->write(separator);
John Stilesf7410bd2021-01-19 13:07:55 -05001544 this->write("thread Globals& _globals");
John Stiles06b84ef2020-12-09 12:35:48 -05001545 separator = ", ";
1546 }
1547 if (requirements & kFragCoord_Requirement) {
1548 this->write(separator);
1549 this->write("float4 _fragCoord");
1550 separator = ", ";
1551 }
1552}
1553
John Stilesda5cdf62021-01-28 11:47:29 -05001554int MetalCodeGenerator::getUniformBinding(const Modifiers& m) {
1555 return (m.fLayout.fBinding >= 0) ? m.fLayout.fBinding
John Stiles270cec22021-02-17 12:59:36 -05001556 : fProgram.fConfig->fSettings.fDefaultUniformBinding;
John Stilesda5cdf62021-01-28 11:47:29 -05001557}
1558
1559int MetalCodeGenerator::getUniformSet(const Modifiers& m) {
1560 return (m.fLayout.fSet >= 0) ? m.fLayout.fSet
John Stiles270cec22021-02-17 12:59:36 -05001561 : fProgram.fConfig->fSettings.fDefaultUniformSet;
John Stilesda5cdf62021-01-28 11:47:29 -05001562}
1563
John Stiles569249b2020-11-03 12:18:22 -05001564bool MetalCodeGenerator::writeFunctionDeclaration(const FunctionDeclaration& f) {
John Stilesf7410bd2021-01-19 13:07:55 -05001565 fRTHeightName = fProgram.fInputs.fRTHeight ? "_globals._anonInterface0->u_skRTHeight" : "";
Ethan Nicholascc305772017-10-13 16:17:45 -04001566 const char* separator = "";
John Stilese8da4d22021-03-24 09:19:45 -04001567 if (f.isMain()) {
John Stiles270cec22021-02-17 12:59:36 -05001568 switch (fProgram.fConfig->fKind) {
John Stilesdbd4e6f2021-02-16 13:29:15 -05001569 case ProgramKind::kFragment:
Timothy Liangb8eeb802018-07-23 16:46:16 -04001570 this->write("fragment Outputs fragmentMain");
Ethan Nicholascc305772017-10-13 16:17:45 -04001571 break;
John Stilesdbd4e6f2021-02-16 13:29:15 -05001572 case ProgramKind::kVertex:
Timothy Liangb8eeb802018-07-23 16:46:16 -04001573 this->write("vertex Outputs vertexMain");
Ethan Nicholascc305772017-10-13 16:17:45 -04001574 break;
1575 default:
John Stiles3fabfc02020-09-25 15:51:28 -04001576 fErrors.error(-1, "unsupported kind of program");
John Stiles569249b2020-11-03 12:18:22 -05001577 return false;
Ethan Nicholascc305772017-10-13 16:17:45 -04001578 }
1579 this->write("(Inputs _in [[stage_in]]");
1580 if (-1 != fUniformBuffer) {
1581 this->write(", constant Uniforms& _uniforms [[buffer(" +
1582 to_string(fUniformBuffer) + ")]]");
1583 }
Brian Osman133724c2020-10-28 14:14:39 -04001584 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04001585 if (e->is<GlobalVarDeclaration>()) {
1586 const GlobalVarDeclaration& decls = e->as<GlobalVarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001587 const VarDeclaration& var = decls.declaration()->as<VarDeclaration>();
1588 if (var.var().type().typeKind() == Type::TypeKind::kSampler) {
1589 if (var.var().modifiers().fLayout.fBinding < 0) {
Brian Osmanc0213602020-10-06 14:43:32 -04001590 fErrors.error(decls.fOffset,
John Stilesb41d5bb2021-01-26 16:28:12 -05001591 "Metal samplers must have 'layout(binding=...)'");
John Stiles569249b2020-11-03 12:18:22 -05001592 return false;
Timothy Liangee84fe12018-05-18 14:38:19 -04001593 }
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001594 if (var.var().type().dimensions() != SpvDim2D) {
John Stiles569249b2020-11-03 12:18:22 -05001595 // Not yet implemented--Skia currently only uses 2D textures.
Brian Osmanc0213602020-10-06 14:43:32 -04001596 fErrors.error(decls.fOffset, "Unsupported texture dimensions");
John Stiles569249b2020-11-03 12:18:22 -05001597 return false;
Brian Osmanc0213602020-10-06 14:43:32 -04001598 }
1599 this->write(", texture2d<float> ");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001600 this->writeName(var.var().name());
Brian Osmanc0213602020-10-06 14:43:32 -04001601 this->write("[[texture(");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001602 this->write(to_string(var.var().modifiers().fLayout.fBinding));
Brian Osmanc0213602020-10-06 14:43:32 -04001603 this->write(")]]");
1604 this->write(", sampler ");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001605 this->writeName(var.var().name());
Brian Osmanc0213602020-10-06 14:43:32 -04001606 this->write(SAMPLER_SUFFIX);
1607 this->write("[[sampler(");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001608 this->write(to_string(var.var().modifiers().fLayout.fBinding));
Brian Osmanc0213602020-10-06 14:43:32 -04001609 this->write(")]]");
Timothy Liang6403b0e2018-05-17 10:40:04 -04001610 }
Brian Osman1179fcf2020-10-08 16:04:40 -04001611 } else if (e->is<InterfaceBlock>()) {
1612 const InterfaceBlock& intf = e->as<InterfaceBlock>();
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001613 if (intf.typeName() == "sk_PerVertex") {
Timothy Lianga06f2152018-05-24 15:33:31 -04001614 continue;
1615 }
1616 this->write(", constant ");
John Stilesb4418502021-02-04 10:57:08 -05001617 this->writeType(intf.variable().type());
Timothy Lianga06f2152018-05-24 15:33:31 -04001618 this->write("& " );
1619 this->write(fInterfaceBlockNameMap[&intf]);
1620 this->write(" [[buffer(");
John Stilesda5cdf62021-01-28 11:47:29 -05001621 this->write(to_string(this->getUniformBinding(intf.variable().modifiers())));
Timothy Lianga06f2152018-05-24 15:33:31 -04001622 this->write(")]]");
Timothy Liang6403b0e2018-05-17 10:40:04 -04001623 }
1624 }
John Stiles270cec22021-02-17 12:59:36 -05001625 if (fProgram.fConfig->fKind == ProgramKind::kFragment) {
Jim Van Verth6bc650e2019-02-07 14:53:23 -05001626 if (fProgram.fInputs.fRTHeight && fInterfaceBlockNameMap.empty()) {
Timothy Liang5422f9a2018-08-10 10:57:55 -04001627 this->write(", constant sksl_synthetic_uniforms& _anonInterface0 [[buffer(1)]]");
Ethan Nicholasf931e402019-07-26 15:40:33 -04001628 fRTHeightName = "_anonInterface0.u_skRTHeight";
Timothy Liang5422f9a2018-08-10 10:57:55 -04001629 }
Timothy Liang7b8875d2018-08-10 09:42:31 -04001630 this->write(", bool _frontFacing [[front_facing]]");
Timothy Liang7d637782018-06-05 09:58:07 -04001631 this->write(", float4 _fragCoord [[position]]");
John Stiles270cec22021-02-17 12:59:36 -05001632 } else if (fProgram.fConfig->fKind == ProgramKind::kVertex) {
Timothy Liangdc89f192018-06-13 09:20:31 -04001633 this->write(", uint sk_VertexID [[vertex_id]], uint sk_InstanceID [[instance_id]]");
Timothy Liang7d637782018-06-05 09:58:07 -04001634 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001635 separator = ", ";
1636 } else {
John Stilesb4418502021-02-04 10:57:08 -05001637 this->writeType(f.returnType());
Timothy Liang651286f2018-06-07 09:55:33 -04001638 this->write(" ");
John Stilese1068342021-03-22 11:57:41 -04001639 this->writeName(f.mangledName());
Timothy Liang651286f2018-06-07 09:55:33 -04001640 this->write("(");
John Stiles06b84ef2020-12-09 12:35:48 -05001641 this->writeFunctionRequirementParams(f, separator);
Ethan Nicholascc305772017-10-13 16:17:45 -04001642 }
John Stiles569249b2020-11-03 12:18:22 -05001643 for (const auto& param : f.parameters()) {
Brian Osman716aeb92021-04-21 13:20:00 -04001644 if (f.isMain() && param->modifiers().fLayout.fBuiltin != -1) {
1645 continue;
1646 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001647 this->write(separator);
1648 separator = ", ";
John Stiles06b84ef2020-12-09 12:35:48 -05001649 this->writeModifiers(param->modifiers(), /*globalContext=*/false);
Ethan Nicholas30d30222020-09-11 12:27:26 -04001650 const Type* type = &param->type();
John Stilesb4418502021-02-04 10:57:08 -05001651 this->writeType(*type);
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001652 if (param->modifiers().fFlags & Modifiers::kOut_Flag) {
John Stilesf2bd5012020-12-04 11:58:26 -05001653 this->write("&");
Ethan Nicholascc305772017-10-13 16:17:45 -04001654 }
Timothy Liang651286f2018-06-07 09:55:33 -04001655 this->write(" ");
Ethan Nicholase2c49992020-10-05 11:49:11 -04001656 this->writeName(param->name());
Ethan Nicholascc305772017-10-13 16:17:45 -04001657 }
John Stiles569249b2020-11-03 12:18:22 -05001658 this->write(")");
1659 return true;
1660}
Ethan Nicholascc305772017-10-13 16:17:45 -04001661
John Stiles569249b2020-11-03 12:18:22 -05001662void MetalCodeGenerator::writeFunctionPrototype(const FunctionPrototype& f) {
1663 this->writeFunctionDeclaration(f.declaration());
1664 this->writeLine(";");
1665}
1666
John Stiles986c7fb2020-12-01 14:44:56 -05001667static bool is_block_ending_with_return(const Statement* stmt) {
1668 // This function detects (potentially nested) blocks that end in a return statement.
1669 if (!stmt->is<Block>()) {
1670 return false;
1671 }
1672 const StatementArray& block = stmt->as<Block>().children();
1673 for (int index = block.count(); index--; ) {
1674 const Statement& stmt = *block[index];
1675 if (stmt.is<ReturnStatement>()) {
1676 return true;
1677 }
1678 if (stmt.is<Block>()) {
1679 return is_block_ending_with_return(&stmt);
1680 }
1681 if (!stmt.is<Nop>()) {
1682 break;
1683 }
1684 }
1685 return false;
1686}
1687
John Stiles569249b2020-11-03 12:18:22 -05001688void MetalCodeGenerator::writeFunction(const FunctionDefinition& f) {
John Stiles270cec22021-02-17 12:59:36 -05001689 SkASSERT(!fProgram.fConfig->fSettings.fFragColorIsInOut);
Brian Salomondc092132018-04-04 10:14:16 -04001690
John Stiles569249b2020-11-03 12:18:22 -05001691 if (!this->writeFunctionDeclaration(f.declaration())) {
1692 return;
1693 }
1694
John Stiles986c7fb2020-12-01 14:44:56 -05001695 fCurrentFunction = &f.declaration();
1696 SkScopeExit clearCurrentFunction([&] { fCurrentFunction = nullptr; });
1697
John Stiles569249b2020-11-03 12:18:22 -05001698 this->writeLine(" {");
1699
John Stilese8da4d22021-03-24 09:19:45 -04001700 if (f.declaration().isMain()) {
John Stilescdcdb042020-07-06 09:03:51 -04001701 this->writeGlobalInit();
John Stilesf7410bd2021-01-19 13:07:55 -05001702 this->writeLine(" Outputs _out;");
John Stiles37279172021-01-21 22:24:28 -05001703 this->writeLine(" (void)_out;");
Ethan Nicholascc305772017-10-13 16:17:45 -04001704 }
John Stilesc67b3622020-05-28 17:53:13 -04001705
John Stiles95680232021-04-22 15:05:20 -04001706 fFunctionHeader.clear();
Ethan Nicholascc305772017-10-13 16:17:45 -04001707 StringStream buffer;
John Stiles44532372020-12-07 12:33:55 -05001708 {
1709 AutoOutputStream outputToBuffer(this, &buffer);
1710 fIndentation++;
1711 for (const std::unique_ptr<Statement>& stmt : f.body()->as<Block>().children()) {
1712 if (!stmt->isEmpty()) {
1713 this->writeStatement(*stmt);
John Stilese8b5a732021-03-12 13:25:52 -05001714 this->finishLine();
John Stiles44532372020-12-07 12:33:55 -05001715 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001716 }
John Stilese8da4d22021-03-24 09:19:45 -04001717 if (f.declaration().isMain()) {
John Stiles44532372020-12-07 12:33:55 -05001718 // If the main function doesn't end with a return, we need to synthesize one here.
1719 if (!is_block_ending_with_return(f.body().get())) {
1720 this->writeReturnStatementFromMain();
John Stilese8b5a732021-03-12 13:25:52 -05001721 this->finishLine();
John Stiles44532372020-12-07 12:33:55 -05001722 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001723 }
John Stiles44532372020-12-07 12:33:55 -05001724 fIndentation--;
1725 this->writeLine("}");
Ethan Nicholascc305772017-10-13 16:17:45 -04001726 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001727 this->write(fFunctionHeader);
1728 this->write(buffer.str());
1729}
1730
1731void MetalCodeGenerator::writeModifiers(const Modifiers& modifiers,
John Stiles06b84ef2020-12-09 12:35:48 -05001732 bool globalContext) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001733 if (modifiers.fFlags & Modifiers::kOut_Flag) {
1734 this->write("thread ");
1735 }
1736 if (modifiers.fFlags & Modifiers::kConst_Flag) {
John Stiles0bd55782021-02-09 18:29:40 -05001737 this->write("const ");
Ethan Nicholascc305772017-10-13 16:17:45 -04001738 }
1739}
1740
1741void MetalCodeGenerator::writeInterfaceBlock(const InterfaceBlock& intf) {
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001742 if ("sk_PerVertex" == intf.typeName()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001743 return;
1744 }
John Stiles06b84ef2020-12-09 12:35:48 -05001745 this->writeModifiers(intf.variable().modifiers(), /*globalContext=*/true);
Timothy Liangdc89f192018-06-13 09:20:31 -04001746 this->write("struct ");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001747 this->writeLine(intf.typeName() + " {");
1748 const Type* structType = &intf.variable().type();
John Stilesbb43b7e2020-12-03 17:36:32 -05001749 if (structType->isArray()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001750 structType = &structType->componentType();
1751 }
Timothy Liangdc89f192018-06-13 09:20:31 -04001752 fIndentation++;
John Stiles3dba3ee2020-12-02 23:35:49 -05001753 this->writeFields(structType->fields(), structType->fOffset, &intf);
Jim Van Verth3d482992019-02-07 10:48:05 -05001754 if (fProgram.fInputs.fRTHeight) {
Timothy Liang7d637782018-06-05 09:58:07 -04001755 this->writeLine("float u_skRTHeight;");
Ethan Nicholascc305772017-10-13 16:17:45 -04001756 }
1757 fIndentation--;
1758 this->write("}");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001759 if (intf.instanceName().size()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001760 this->write(" ");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001761 this->write(intf.instanceName());
John Stilesd39aec02020-12-03 10:42:26 -05001762 if (intf.arraySize() > 0) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001763 this->write("[");
John Stilesd39aec02020-12-03 10:42:26 -05001764 this->write(to_string(intf.arraySize()));
Ethan Nicholascc305772017-10-13 16:17:45 -04001765 this->write("]");
John Stilesd39aec02020-12-03 10:42:26 -05001766 } else if (intf.arraySize() == Type::kUnsizedArray){
1767 this->write("[]");
Ethan Nicholascc305772017-10-13 16:17:45 -04001768 }
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001769 fInterfaceBlockNameMap[&intf] = intf.instanceName();
Timothy Lianga06f2152018-05-24 15:33:31 -04001770 } else {
Timothy Liang7d637782018-06-05 09:58:07 -04001771 fInterfaceBlockNameMap[&intf] = "_anonInterface" + to_string(fAnonInterfaceCount++);
Ethan Nicholascc305772017-10-13 16:17:45 -04001772 }
1773 this->writeLine(";");
1774}
1775
Timothy Liangdc89f192018-06-13 09:20:31 -04001776void MetalCodeGenerator::writeFields(const std::vector<Type::Field>& fields, int parentOffset,
1777 const InterfaceBlock* parentIntf) {
Timothy Liang609fbe32018-08-10 16:40:49 -04001778 MemoryLayout memoryLayout(MemoryLayout::kMetal_Standard);
Timothy Liangdc89f192018-06-13 09:20:31 -04001779 int currentOffset = 0;
John Stiles39346472021-04-29 14:39:35 -04001780 for (const Type::Field& field : fields) {
Timothy Liangdc89f192018-06-13 09:20:31 -04001781 int fieldOffset = field.fModifiers.fLayout.fOffset;
1782 const Type* fieldType = field.fType;
John Stiles21f5f452020-11-30 09:57:59 -05001783 if (!MemoryLayout::LayoutIsSupported(*fieldType)) {
John Stiles0023c0c2020-11-16 13:32:18 -05001784 fErrors.error(parentOffset, "type '" + fieldType->name() + "' is not permitted here");
1785 return;
1786 }
Timothy Liangdc89f192018-06-13 09:20:31 -04001787 if (fieldOffset != -1) {
1788 if (currentOffset > fieldOffset) {
1789 fErrors.error(parentOffset,
John Stilesd7199b22020-12-30 16:22:58 -05001790 "offset of field '" + field.fName + "' must be at least " +
1791 to_string((int) currentOffset));
Brian Osman8609a242020-09-08 14:01:49 -04001792 return;
Timothy Liangdc89f192018-06-13 09:20:31 -04001793 } else if (currentOffset < fieldOffset) {
1794 this->write("char pad");
1795 this->write(to_string(fPaddingCount++));
1796 this->write("[");
1797 this->write(to_string(fieldOffset - currentOffset));
1798 this->writeLine("];");
1799 currentOffset = fieldOffset;
1800 }
1801 int alignment = memoryLayout.alignment(*fieldType);
1802 if (fieldOffset % alignment) {
1803 fErrors.error(parentOffset,
1804 "offset of field '" + field.fName + "' must be a multiple of " +
1805 to_string((int) alignment));
Brian Osman8609a242020-09-08 14:01:49 -04001806 return;
Timothy Liangdc89f192018-06-13 09:20:31 -04001807 }
1808 }
Brian Osman8609a242020-09-08 14:01:49 -04001809 size_t fieldSize = memoryLayout.size(*fieldType);
1810 if (fieldSize > static_cast<size_t>(std::numeric_limits<int>::max() - currentOffset)) {
1811 fErrors.error(parentOffset, "field offset overflow");
1812 return;
1813 }
1814 currentOffset += fieldSize;
John Stiles06b84ef2020-12-09 12:35:48 -05001815 this->writeModifiers(field.fModifiers, /*globalContext=*/false);
John Stilesb4418502021-02-04 10:57:08 -05001816 this->writeType(*fieldType);
Timothy Liangdc89f192018-06-13 09:20:31 -04001817 this->write(" ");
1818 this->writeName(field.fName);
Timothy Liangdc89f192018-06-13 09:20:31 -04001819 this->writeLine(";");
1820 if (parentIntf) {
1821 fInterfaceBlockMap[&field] = parentIntf;
1822 }
1823 }
1824}
1825
Ethan Nicholascc305772017-10-13 16:17:45 -04001826void MetalCodeGenerator::writeVarInitializer(const Variable& var, const Expression& value) {
Brian Osman00185012021-02-04 16:07:11 -05001827 this->writeExpression(value, Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001828}
1829
Timothy Liang651286f2018-06-07 09:55:33 -04001830void MetalCodeGenerator::writeName(const String& name) {
1831 if (fReservedWords.find(name) != fReservedWords.end()) {
1832 this->write("_"); // adding underscore before name to avoid conflict with reserved words
1833 }
1834 this->write(name);
1835}
1836
John Stilesb4418502021-02-04 10:57:08 -05001837void MetalCodeGenerator::writeVarDeclaration(const VarDeclaration& varDecl, bool global) {
1838 if (global && !(varDecl.var().modifiers().fFlags & Modifiers::kConst_Flag)) {
Brian Osmanc0213602020-10-06 14:43:32 -04001839 return;
Ethan Nicholascc305772017-10-13 16:17:45 -04001840 }
John Stilesb4418502021-02-04 10:57:08 -05001841 this->writeModifiers(varDecl.var().modifiers(), global);
1842 this->writeType(varDecl.var().type());
Brian Osmanc0213602020-10-06 14:43:32 -04001843 this->write(" ");
John Stilesb4418502021-02-04 10:57:08 -05001844 this->writeName(varDecl.var().name());
1845 if (varDecl.value()) {
Brian Osmanc0213602020-10-06 14:43:32 -04001846 this->write(" = ");
John Stilesb4418502021-02-04 10:57:08 -05001847 this->writeVarInitializer(varDecl.var(), *varDecl.value());
Brian Osmanc0213602020-10-06 14:43:32 -04001848 }
1849 this->write(";");
Ethan Nicholascc305772017-10-13 16:17:45 -04001850}
1851
1852void MetalCodeGenerator::writeStatement(const Statement& s) {
Ethan Nicholase6592142020-09-08 10:22:09 -04001853 switch (s.kind()) {
1854 case Statement::Kind::kBlock:
John Stiles26f98502020-08-18 09:30:51 -04001855 this->writeBlock(s.as<Block>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001856 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001857 case Statement::Kind::kExpression:
Brian Osman00185012021-02-04 16:07:11 -05001858 this->writeExpression(*s.as<ExpressionStatement>().expression(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001859 this->write(";");
1860 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001861 case Statement::Kind::kReturn:
John Stiles26f98502020-08-18 09:30:51 -04001862 this->writeReturnStatement(s.as<ReturnStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001863 break;
Brian Osmanc0213602020-10-06 14:43:32 -04001864 case Statement::Kind::kVarDeclaration:
1865 this->writeVarDeclaration(s.as<VarDeclaration>(), false);
Ethan Nicholascc305772017-10-13 16:17:45 -04001866 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001867 case Statement::Kind::kIf:
John Stiles26f98502020-08-18 09:30:51 -04001868 this->writeIfStatement(s.as<IfStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001869 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001870 case Statement::Kind::kFor:
John Stiles26f98502020-08-18 09:30:51 -04001871 this->writeForStatement(s.as<ForStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001872 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001873 case Statement::Kind::kDo:
John Stiles26f98502020-08-18 09:30:51 -04001874 this->writeDoStatement(s.as<DoStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001875 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001876 case Statement::Kind::kSwitch:
John Stiles26f98502020-08-18 09:30:51 -04001877 this->writeSwitchStatement(s.as<SwitchStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001878 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001879 case Statement::Kind::kBreak:
Ethan Nicholascc305772017-10-13 16:17:45 -04001880 this->write("break;");
1881 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001882 case Statement::Kind::kContinue:
Ethan Nicholascc305772017-10-13 16:17:45 -04001883 this->write("continue;");
1884 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001885 case Statement::Kind::kDiscard:
Timothy Lianga06f2152018-05-24 15:33:31 -04001886 this->write("discard_fragment();");
Ethan Nicholascc305772017-10-13 16:17:45 -04001887 break;
John Stiles98c1f822020-09-09 14:18:53 -04001888 case Statement::Kind::kInlineMarker:
Ethan Nicholase6592142020-09-08 10:22:09 -04001889 case Statement::Kind::kNop:
Ethan Nicholascc305772017-10-13 16:17:45 -04001890 this->write(";");
1891 break;
1892 default:
John Stileseada7bc2021-02-02 16:29:32 -05001893 SkDEBUGFAILF("unsupported statement: %s", s.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -05001894 break;
Ethan Nicholascc305772017-10-13 16:17:45 -04001895 }
1896}
1897
Ethan Nicholascc305772017-10-13 16:17:45 -04001898void MetalCodeGenerator::writeBlock(const Block& b) {
John Stiles3744bd62021-01-26 13:49:43 -05001899 // Write scope markers if this block is a scope, or if the block is empty (since we need to emit
1900 // something here to make the code valid).
1901 bool isScope = b.isScope() || b.isEmpty();
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001902 if (isScope) {
Ethan Nicholas70728ef2020-05-28 07:09:00 -04001903 this->writeLine("{");
1904 fIndentation++;
1905 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001906 for (const std::unique_ptr<Statement>& stmt : b.children()) {
1907 if (!stmt->isEmpty()) {
1908 this->writeStatement(*stmt);
John Stilese8b5a732021-03-12 13:25:52 -05001909 this->finishLine();
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001910 }
1911 }
1912 if (isScope) {
Ethan Nicholas70728ef2020-05-28 07:09:00 -04001913 fIndentation--;
1914 this->write("}");
1915 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001916}
1917
1918void MetalCodeGenerator::writeIfStatement(const IfStatement& stmt) {
1919 this->write("if (");
Brian Osman00185012021-02-04 16:07:11 -05001920 this->writeExpression(*stmt.test(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001921 this->write(") ");
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04001922 this->writeStatement(*stmt.ifTrue());
1923 if (stmt.ifFalse()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001924 this->write(" else ");
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04001925 this->writeStatement(*stmt.ifFalse());
Ethan Nicholascc305772017-10-13 16:17:45 -04001926 }
1927}
1928
1929void MetalCodeGenerator::writeForStatement(const ForStatement& f) {
Brian Osmand6f23382020-12-15 17:08:59 -05001930 // Emit loops of the form 'for(;test;)' as 'while(test)', which is probably how they started
1931 if (!f.initializer() && f.test() && !f.next()) {
1932 this->write("while (");
Brian Osman00185012021-02-04 16:07:11 -05001933 this->writeExpression(*f.test(), Precedence::kTopLevel);
Brian Osmand6f23382020-12-15 17:08:59 -05001934 this->write(") ");
1935 this->writeStatement(*f.statement());
1936 return;
1937 }
1938
John Stiles1a15e572021-04-19 14:57:15 -04001939 this->write("for (");
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04001940 if (f.initializer() && !f.initializer()->isEmpty()) {
John Stiles1a15e572021-04-19 14:57:15 -04001941 this->writeStatement(*f.initializer());
Ethan Nicholascc305772017-10-13 16:17:45 -04001942 } else {
John Stiles1a15e572021-04-19 14:57:15 -04001943 this->write("; ");
Ethan Nicholascc305772017-10-13 16:17:45 -04001944 }
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04001945 if (f.test()) {
Brian Osman00185012021-02-04 16:07:11 -05001946 this->writeExpression(*f.test(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001947 }
1948 this->write("; ");
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04001949 if (f.next()) {
Brian Osman00185012021-02-04 16:07:11 -05001950 this->writeExpression(*f.next(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001951 }
1952 this->write(") ");
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04001953 this->writeStatement(*f.statement());
Ethan Nicholascc305772017-10-13 16:17:45 -04001954}
1955
Ethan Nicholascc305772017-10-13 16:17:45 -04001956void MetalCodeGenerator::writeDoStatement(const DoStatement& d) {
1957 this->write("do ");
Ethan Nicholas1fd61162020-09-28 13:14:19 -04001958 this->writeStatement(*d.statement());
Ethan Nicholascc305772017-10-13 16:17:45 -04001959 this->write(" while (");
Brian Osman00185012021-02-04 16:07:11 -05001960 this->writeExpression(*d.test(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001961 this->write(");");
1962}
1963
1964void MetalCodeGenerator::writeSwitchStatement(const SwitchStatement& s) {
1965 this->write("switch (");
Brian Osman00185012021-02-04 16:07:11 -05001966 this->writeExpression(*s.value(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001967 this->writeLine(") {");
1968 fIndentation++;
John Stilesb23a64b2021-03-11 08:27:59 -05001969 for (const std::unique_ptr<Statement>& stmt : s.cases()) {
1970 const SwitchCase& c = stmt->as<SwitchCase>();
1971 if (c.value()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001972 this->write("case ");
John Stilesb23a64b2021-03-11 08:27:59 -05001973 this->writeExpression(*c.value(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001974 this->writeLine(":");
1975 } else {
1976 this->writeLine("default:");
1977 }
John Stilesb23a64b2021-03-11 08:27:59 -05001978 if (!c.statement()->isEmpty()) {
John Stilesc3ce43b2021-03-09 15:37:01 -05001979 fIndentation++;
John Stilesb23a64b2021-03-11 08:27:59 -05001980 this->writeStatement(*c.statement());
John Stilese8b5a732021-03-12 13:25:52 -05001981 this->finishLine();
John Stilesc3ce43b2021-03-09 15:37:01 -05001982 fIndentation--;
Ethan Nicholascc305772017-10-13 16:17:45 -04001983 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001984 }
1985 fIndentation--;
1986 this->write("}");
1987}
1988
John Stiles986c7fb2020-12-01 14:44:56 -05001989void MetalCodeGenerator::writeReturnStatementFromMain() {
1990 // main functions in Metal return a magic _out parameter that doesn't exist in SkSL.
John Stiles270cec22021-02-17 12:59:36 -05001991 switch (fProgram.fConfig->fKind) {
John Stilesdbd4e6f2021-02-16 13:29:15 -05001992 case ProgramKind::kFragment:
John Stilesf7410bd2021-01-19 13:07:55 -05001993 this->write("return _out;");
John Stiles986c7fb2020-12-01 14:44:56 -05001994 break;
John Stilesdbd4e6f2021-02-16 13:29:15 -05001995 case ProgramKind::kVertex:
John Stilesf7410bd2021-01-19 13:07:55 -05001996 this->write("return (_out.sk_Position.y = -_out.sk_Position.y, _out);");
John Stiles986c7fb2020-12-01 14:44:56 -05001997 break;
1998 default:
1999 SkDEBUGFAIL("unsupported kind of program");
2000 }
2001}
2002
Ethan Nicholascc305772017-10-13 16:17:45 -04002003void MetalCodeGenerator::writeReturnStatement(const ReturnStatement& r) {
John Stilese8da4d22021-03-24 09:19:45 -04002004 if (fCurrentFunction && fCurrentFunction->isMain()) {
John Stiles986c7fb2020-12-01 14:44:56 -05002005 if (r.expression()) {
John Stiles97d18172021-01-22 16:47:42 -05002006 if (r.expression()->type() == *fContext.fTypes.fHalf4) {
2007 this->write("_out.sk_FragColor = ");
Brian Osman00185012021-02-04 16:07:11 -05002008 this->writeExpression(*r.expression(), Precedence::kTopLevel);
John Stiles97d18172021-01-22 16:47:42 -05002009 this->writeLine(";");
2010 } else {
2011 fErrors.error(r.fOffset, "Metal does not support returning '" +
2012 r.expression()->type().description() + "' from main()");
2013 }
John Stiles986c7fb2020-12-01 14:44:56 -05002014 }
2015 this->writeReturnStatementFromMain();
2016 return;
2017 }
2018
Ethan Nicholascc305772017-10-13 16:17:45 -04002019 this->write("return");
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04002020 if (r.expression()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002021 this->write(" ");
Brian Osman00185012021-02-04 16:07:11 -05002022 this->writeExpression(*r.expression(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04002023 }
2024 this->write(";");
2025}
2026
Michael Ludwigbf58add2021-03-16 10:40:11 -04002027void MetalCodeGenerator::writeHeader() {
2028 this->write("#include <metal_stdlib>\n");
2029 this->write("#include <simd/simd.h>\n");
2030 this->write("using namespace metal;\n");
2031}
2032
Ethan Nicholascc305772017-10-13 16:17:45 -04002033void MetalCodeGenerator::writeUniformStruct() {
Brian Osman133724c2020-10-28 14:14:39 -04002034 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04002035 if (e->is<GlobalVarDeclaration>()) {
2036 const GlobalVarDeclaration& decls = e->as<GlobalVarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04002037 const Variable& var = decls.declaration()->as<VarDeclaration>().var();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002038 if (var.modifiers().fFlags & Modifiers::kUniform_Flag &&
Brian Osmanc0213602020-10-06 14:43:32 -04002039 var.type().typeKind() != Type::TypeKind::kSampler) {
John Stilesda5cdf62021-01-28 11:47:29 -05002040 int uniformSet = this->getUniformSet(var.modifiers());
John Stilesd8fc95d2021-01-26 16:22:53 -05002041 // Make sure that the program's uniform-set value is consistent throughout.
Ethan Nicholascc305772017-10-13 16:17:45 -04002042 if (-1 == fUniformBuffer) {
2043 this->write("struct Uniforms {\n");
John Stilesd8fc95d2021-01-26 16:22:53 -05002044 fUniformBuffer = uniformSet;
2045 } else if (uniformSet != fUniformBuffer) {
2046 fErrors.error(decls.fOffset, "Metal backend requires all uniforms to have "
2047 "the same 'layout(set=...)'");
Ethan Nicholascc305772017-10-13 16:17:45 -04002048 }
2049 this->write(" ");
John Stilesb4418502021-02-04 10:57:08 -05002050 this->writeType(var.type());
Ethan Nicholascc305772017-10-13 16:17:45 -04002051 this->write(" ");
Brian Osmanc0213602020-10-06 14:43:32 -04002052 this->writeName(var.name());
Ethan Nicholascc305772017-10-13 16:17:45 -04002053 this->write(";\n");
2054 }
2055 }
2056 }
2057 if (-1 != fUniformBuffer) {
2058 this->write("};\n");
2059 }
2060}
2061
2062void MetalCodeGenerator::writeInputStruct() {
2063 this->write("struct Inputs {\n");
Brian Osman133724c2020-10-28 14:14:39 -04002064 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04002065 if (e->is<GlobalVarDeclaration>()) {
2066 const GlobalVarDeclaration& decls = e->as<GlobalVarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04002067 const Variable& var = decls.declaration()->as<VarDeclaration>().var();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002068 if (var.modifiers().fFlags & Modifiers::kIn_Flag &&
2069 -1 == var.modifiers().fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002070 this->write(" ");
John Stilesb4418502021-02-04 10:57:08 -05002071 this->writeType(var.type());
Ethan Nicholascc305772017-10-13 16:17:45 -04002072 this->write(" ");
Brian Osmanc0213602020-10-06 14:43:32 -04002073 this->writeName(var.name());
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002074 if (-1 != var.modifiers().fLayout.fLocation) {
John Stiles270cec22021-02-17 12:59:36 -05002075 if (fProgram.fConfig->fKind == ProgramKind::kVertex) {
Brian Osmanc0213602020-10-06 14:43:32 -04002076 this->write(" [[attribute(" +
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002077 to_string(var.modifiers().fLayout.fLocation) + ")]]");
John Stiles270cec22021-02-17 12:59:36 -05002078 } else if (fProgram.fConfig->fKind == ProgramKind::kFragment) {
Brian Osmanc0213602020-10-06 14:43:32 -04002079 this->write(" [[user(locn" +
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002080 to_string(var.modifiers().fLayout.fLocation) + ")]]");
Ethan Nicholascc305772017-10-13 16:17:45 -04002081 }
2082 }
2083 this->write(";\n");
2084 }
2085 }
2086 }
2087 this->write("};\n");
2088}
2089
2090void MetalCodeGenerator::writeOutputStruct() {
2091 this->write("struct Outputs {\n");
John Stiles270cec22021-02-17 12:59:36 -05002092 if (fProgram.fConfig->fKind == ProgramKind::kVertex) {
Timothy Liangb8eeb802018-07-23 16:46:16 -04002093 this->write(" float4 sk_Position [[position]];\n");
John Stiles270cec22021-02-17 12:59:36 -05002094 } else if (fProgram.fConfig->fKind == ProgramKind::kFragment) {
Timothy Liangde0be802018-08-10 13:48:08 -04002095 this->write(" float4 sk_FragColor [[color(0)]];\n");
Timothy Liang7d637782018-06-05 09:58:07 -04002096 }
Brian Osman133724c2020-10-28 14:14:39 -04002097 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04002098 if (e->is<GlobalVarDeclaration>()) {
2099 const GlobalVarDeclaration& decls = e->as<GlobalVarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04002100 const Variable& var = decls.declaration()->as<VarDeclaration>().var();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002101 if (var.modifiers().fFlags & Modifiers::kOut_Flag &&
2102 -1 == var.modifiers().fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002103 this->write(" ");
John Stilesb4418502021-02-04 10:57:08 -05002104 this->writeType(var.type());
Ethan Nicholascc305772017-10-13 16:17:45 -04002105 this->write(" ");
Brian Osmanc0213602020-10-06 14:43:32 -04002106 this->writeName(var.name());
John Stiles842b3592020-12-01 10:36:37 -05002107
2108 int location = var.modifiers().fLayout.fLocation;
2109 if (location < 0) {
2110 fErrors.error(var.fOffset,
2111 "Metal out variables must have 'layout(location=...)'");
John Stiles270cec22021-02-17 12:59:36 -05002112 } else if (fProgram.fConfig->fKind == ProgramKind::kVertex) {
John Stiles842b3592020-12-01 10:36:37 -05002113 this->write(" [[user(locn" + to_string(location) + ")]]");
John Stiles270cec22021-02-17 12:59:36 -05002114 } else if (fProgram.fConfig->fKind == ProgramKind::kFragment) {
John Stiles842b3592020-12-01 10:36:37 -05002115 this->write(" [[color(" + to_string(location) + ")");
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002116 int colorIndex = var.modifiers().fLayout.fIndex;
Brian Osmanc0213602020-10-06 14:43:32 -04002117 if (colorIndex) {
2118 this->write(", index(" + to_string(colorIndex) + ")");
Timothy Liang7d637782018-06-05 09:58:07 -04002119 }
Brian Osmanc0213602020-10-06 14:43:32 -04002120 this->write("]]");
Ethan Nicholascc305772017-10-13 16:17:45 -04002121 }
2122 this->write(";\n");
2123 }
2124 }
Timothy Liang7d637782018-06-05 09:58:07 -04002125 }
John Stiles270cec22021-02-17 12:59:36 -05002126 if (fProgram.fConfig->fKind == ProgramKind::kVertex) {
Jim Van Verth3913d3e2020-08-31 15:16:57 -04002127 this->write(" float sk_PointSize [[point_size]];\n");
Timothy Liang7d637782018-06-05 09:58:07 -04002128 }
2129 this->write("};\n");
2130}
2131
2132void MetalCodeGenerator::writeInterfaceBlocks() {
2133 bool wroteInterfaceBlock = false;
Brian Osman133724c2020-10-28 14:14:39 -04002134 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04002135 if (e->is<InterfaceBlock>()) {
2136 this->writeInterfaceBlock(e->as<InterfaceBlock>());
Timothy Liang7d637782018-06-05 09:58:07 -04002137 wroteInterfaceBlock = true;
2138 }
2139 }
Jim Van Verth3d482992019-02-07 10:48:05 -05002140 if (!wroteInterfaceBlock && fProgram.fInputs.fRTHeight) {
Timothy Liang7d637782018-06-05 09:58:07 -04002141 this->writeLine("struct sksl_synthetic_uniforms {");
2142 this->writeLine(" float u_skRTHeight;");
2143 this->writeLine("};");
2144 }
Ethan Nicholascc305772017-10-13 16:17:45 -04002145}
2146
John Stilesdc75a972020-11-25 16:24:55 -05002147void MetalCodeGenerator::writeStructDefinitions() {
2148 for (const ProgramElement* e : fProgram.elements()) {
2149 if (e->is<StructDefinition>()) {
Brian Osman02bc5222021-01-28 11:00:20 -05002150 this->writeStructDefinition(e->as<StructDefinition>());
John Stilesdc75a972020-11-25 16:24:55 -05002151 }
2152 }
2153}
2154
John Stilescdcdb042020-07-06 09:03:51 -04002155void MetalCodeGenerator::visitGlobalStruct(GlobalStructVisitor* visitor) {
2156 // Visit the interface blocks.
2157 for (const auto& [interfaceType, interfaceName] : fInterfaceBlockNameMap) {
John Stilesfdb8dbe2020-12-04 11:00:03 -05002158 visitor->visitInterfaceBlock(*interfaceType, interfaceName);
John Stilescdcdb042020-07-06 09:03:51 -04002159 }
Brian Osman133724c2020-10-28 14:14:39 -04002160 for (const ProgramElement* element : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04002161 if (!element->is<GlobalVarDeclaration>()) {
John Stilescdcdb042020-07-06 09:03:51 -04002162 continue;
Timothy Liang7d637782018-06-05 09:58:07 -04002163 }
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04002164 const GlobalVarDeclaration& global = element->as<GlobalVarDeclaration>();
2165 const VarDeclaration& decl = global.declaration()->as<VarDeclaration>();
2166 const Variable& var = decl.var();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002167 if ((!var.modifiers().fFlags && -1 == var.modifiers().fLayout.fBuiltin) ||
Brian Osmanc0213602020-10-06 14:43:32 -04002168 var.type().typeKind() == Type::TypeKind::kSampler) {
2169 if (var.type().typeKind() == Type::TypeKind::kSampler) {
2170 // Samplers are represented as a "texture/sampler" duo in the global struct.
John Stilesfdb8dbe2020-12-04 11:00:03 -05002171 visitor->visitTexture(var.type(), var.name());
2172 visitor->visitSampler(var.type(), String(var.name()) + SAMPLER_SUFFIX);
Brian Osmanc0213602020-10-06 14:43:32 -04002173 } else {
2174 // Visit a regular variable.
John Stilesfdb8dbe2020-12-04 11:00:03 -05002175 visitor->visitVariable(var, decl.value().get());
Timothy Liangee84fe12018-05-18 14:38:19 -04002176 }
2177 }
2178 }
John Stilescdcdb042020-07-06 09:03:51 -04002179}
2180
2181void MetalCodeGenerator::writeGlobalStruct() {
2182 class : public GlobalStructVisitor {
2183 public:
John Stilesfdb8dbe2020-12-04 11:00:03 -05002184 void visitInterfaceBlock(const InterfaceBlock& block, const String& blockName) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002185 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002186 fCodeGen->write(" constant ");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04002187 fCodeGen->write(block.typeName());
John Stilescdcdb042020-07-06 09:03:51 -04002188 fCodeGen->write("* ");
2189 fCodeGen->writeName(blockName);
2190 fCodeGen->write(";\n");
2191 }
John Stilesfdb8dbe2020-12-04 11:00:03 -05002192 void visitTexture(const Type& type, const String& name) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002193 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002194 fCodeGen->write(" ");
John Stilesb4418502021-02-04 10:57:08 -05002195 fCodeGen->writeType(type);
John Stilescdcdb042020-07-06 09:03:51 -04002196 fCodeGen->write(" ");
2197 fCodeGen->writeName(name);
2198 fCodeGen->write(";\n");
2199 }
John Stilesfdb8dbe2020-12-04 11:00:03 -05002200 void visitSampler(const Type&, const String& name) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002201 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002202 fCodeGen->write(" sampler ");
2203 fCodeGen->writeName(name);
2204 fCodeGen->write(";\n");
2205 }
John Stilesfdb8dbe2020-12-04 11:00:03 -05002206 void visitVariable(const Variable& var, const Expression* value) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002207 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002208 fCodeGen->write(" ");
John Stilesb4418502021-02-04 10:57:08 -05002209 fCodeGen->writeType(var.type());
John Stilescdcdb042020-07-06 09:03:51 -04002210 fCodeGen->write(" ");
Ethan Nicholase2c49992020-10-05 11:49:11 -04002211 fCodeGen->writeName(var.name());
John Stilescdcdb042020-07-06 09:03:51 -04002212 fCodeGen->write(";\n");
2213 }
John Stiles83f3b8d2020-12-07 17:52:25 -05002214 void addElement() {
John Stilescdcdb042020-07-06 09:03:51 -04002215 if (fFirst) {
2216 fCodeGen->write("struct Globals {\n");
2217 fFirst = false;
2218 }
2219 }
John Stiles83f3b8d2020-12-07 17:52:25 -05002220 void finish() {
John Stilescdcdb042020-07-06 09:03:51 -04002221 if (!fFirst) {
John Stiles83f3b8d2020-12-07 17:52:25 -05002222 fCodeGen->writeLine("};");
John Stilescdcdb042020-07-06 09:03:51 -04002223 fFirst = true;
2224 }
2225 }
2226
2227 MetalCodeGenerator* fCodeGen = nullptr;
2228 bool fFirst = true;
2229 } visitor;
2230
2231 visitor.fCodeGen = this;
2232 this->visitGlobalStruct(&visitor);
John Stiles83f3b8d2020-12-07 17:52:25 -05002233 visitor.finish();
John Stilescdcdb042020-07-06 09:03:51 -04002234}
2235
2236void MetalCodeGenerator::writeGlobalInit() {
2237 class : public GlobalStructVisitor {
2238 public:
John Stilesfdb8dbe2020-12-04 11:00:03 -05002239 void visitInterfaceBlock(const InterfaceBlock& blockType,
John Stilescdcdb042020-07-06 09:03:51 -04002240 const String& blockName) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002241 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002242 fCodeGen->write("&");
2243 fCodeGen->writeName(blockName);
2244 }
John Stilesfdb8dbe2020-12-04 11:00:03 -05002245 void visitTexture(const Type&, const String& name) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002246 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002247 fCodeGen->writeName(name);
2248 }
John Stilesfdb8dbe2020-12-04 11:00:03 -05002249 void visitSampler(const Type&, const String& name) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002250 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002251 fCodeGen->writeName(name);
2252 }
John Stilesfdb8dbe2020-12-04 11:00:03 -05002253 void visitVariable(const Variable& var, const Expression* value) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002254 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002255 if (value) {
2256 fCodeGen->writeVarInitializer(var, *value);
2257 } else {
2258 fCodeGen->write("{}");
2259 }
2260 }
John Stiles83f3b8d2020-12-07 17:52:25 -05002261 void addElement() {
John Stilescdcdb042020-07-06 09:03:51 -04002262 if (fFirst) {
John Stilesf7410bd2021-01-19 13:07:55 -05002263 fCodeGen->write(" Globals _globals{");
John Stilescdcdb042020-07-06 09:03:51 -04002264 fFirst = false;
2265 } else {
2266 fCodeGen->write(", ");
2267 }
2268 }
John Stiles83f3b8d2020-12-07 17:52:25 -05002269 void finish() {
John Stilescdcdb042020-07-06 09:03:51 -04002270 if (!fFirst) {
2271 fCodeGen->writeLine("};");
John Stiles37279172021-01-21 22:24:28 -05002272 fCodeGen->writeLine(" (void)_globals;");
John Stilescdcdb042020-07-06 09:03:51 -04002273 }
2274 }
2275 MetalCodeGenerator* fCodeGen = nullptr;
2276 bool fFirst = true;
2277 } visitor;
2278
2279 visitor.fCodeGen = this;
2280 this->visitGlobalStruct(&visitor);
John Stiles83f3b8d2020-12-07 17:52:25 -05002281 visitor.finish();
Timothy Liangee84fe12018-05-18 14:38:19 -04002282}
2283
Ethan Nicholascc305772017-10-13 16:17:45 -04002284void MetalCodeGenerator::writeProgramElement(const ProgramElement& e) {
Ethan Nicholase6592142020-09-08 10:22:09 -04002285 switch (e.kind()) {
2286 case ProgramElement::Kind::kExtension:
Ethan Nicholascc305772017-10-13 16:17:45 -04002287 break;
Brian Osmanc0213602020-10-06 14:43:32 -04002288 case ProgramElement::Kind::kGlobalVar: {
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04002289 const GlobalVarDeclaration& global = e.as<GlobalVarDeclaration>();
2290 const VarDeclaration& decl = global.declaration()->as<VarDeclaration>();
2291 int builtin = decl.var().modifiers().fLayout.fBuiltin;
Brian Osmanc0213602020-10-06 14:43:32 -04002292 if (-1 == builtin) {
2293 // normal var
2294 this->writeVarDeclaration(decl, true);
John Stilese8b5a732021-03-12 13:25:52 -05002295 this->finishLine();
Brian Osmanc0213602020-10-06 14:43:32 -04002296 } else if (SK_FRAGCOLOR_BUILTIN == builtin) {
2297 // ignore
Ethan Nicholascc305772017-10-13 16:17:45 -04002298 }
2299 break;
2300 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002301 case ProgramElement::Kind::kInterfaceBlock:
Timothy Liang7d637782018-06-05 09:58:07 -04002302 // handled in writeInterfaceBlocks, do nothing
Ethan Nicholascc305772017-10-13 16:17:45 -04002303 break;
John Stilesdc75a972020-11-25 16:24:55 -05002304 case ProgramElement::Kind::kStructDefinition:
2305 // Handled in writeStructDefinitions. Do nothing.
2306 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04002307 case ProgramElement::Kind::kFunction:
John Stiles3dc0da62020-08-19 17:48:31 -04002308 this->writeFunction(e.as<FunctionDefinition>());
Ethan Nicholascc305772017-10-13 16:17:45 -04002309 break;
John Stiles569249b2020-11-03 12:18:22 -05002310 case ProgramElement::Kind::kFunctionPrototype:
2311 this->writeFunctionPrototype(e.as<FunctionPrototype>());
2312 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04002313 case ProgramElement::Kind::kModifiers:
John Stiles06b84ef2020-12-09 12:35:48 -05002314 this->writeModifiers(e.as<ModifiersDeclaration>().modifiers(),
2315 /*globalContext=*/true);
Ethan Nicholascc305772017-10-13 16:17:45 -04002316 this->writeLine(";");
2317 break;
John Stiles712fd6b2020-11-25 22:25:43 -05002318 case ProgramElement::Kind::kEnum:
2319 break;
Ethan Nicholascc305772017-10-13 16:17:45 -04002320 default:
John Stileseada7bc2021-02-02 16:29:32 -05002321 SkDEBUGFAILF("unsupported program element: %s\n", e.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -05002322 break;
Ethan Nicholascc305772017-10-13 16:17:45 -04002323 }
2324}
2325
Ethan Nicholasff350cb2020-05-14 14:05:13 -04002326MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const Expression* e) {
2327 if (!e) {
2328 return kNo_Requirements;
2329 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002330 switch (e->kind()) {
2331 case Expression::Kind::kFunctionCall: {
John Stiles3dc0da62020-08-19 17:48:31 -04002332 const FunctionCall& f = e->as<FunctionCall>();
Ethan Nicholas0dec9922020-10-05 15:51:52 -04002333 Requirements result = this->requirements(f.function());
2334 for (const auto& arg : f.arguments()) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04002335 result |= this->requirements(arg.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002336 }
2337 return result;
2338 }
John Stiles8cad6372021-04-07 12:31:13 -04002339 case Expression::Kind::kConstructorCompound:
2340 case Expression::Kind::kConstructorCompoundCast:
John Stiles7384b372021-04-01 13:48:15 -04002341 case Expression::Kind::kConstructorArray:
John Stiles2938eea2021-04-01 18:58:25 -04002342 case Expression::Kind::kConstructorDiagonalMatrix:
John Stilesfd7252f2021-04-04 22:24:40 -04002343 case Expression::Kind::kConstructorScalarCast:
John Stilesd47330f2021-04-08 23:25:52 -04002344 case Expression::Kind::kConstructorSplat:
2345 case Expression::Kind::kConstructorStruct: {
John Stiles7384b372021-04-01 13:48:15 -04002346 const AnyConstructor& c = e->asAnyConstructor();
Ethan Nicholascc305772017-10-13 16:17:45 -04002347 Requirements result = kNo_Requirements;
John Stilesd8eb8752021-04-01 11:49:10 -04002348 for (const auto& arg : c.argumentSpan()) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04002349 result |= this->requirements(arg.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002350 }
2351 return result;
2352 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002353 case Expression::Kind::kFieldAccess: {
John Stiles3dc0da62020-08-19 17:48:31 -04002354 const FieldAccess& f = e->as<FieldAccess>();
Ethan Nicholas7a95b202020-10-09 11:55:40 -04002355 if (FieldAccess::OwnerKind::kAnonymousInterfaceBlock == f.ownerKind()) {
Timothy Liang7d637782018-06-05 09:58:07 -04002356 return kGlobals_Requirement;
2357 }
Ethan Nicholas7a95b202020-10-09 11:55:40 -04002358 return this->requirements(f.base().get());
Timothy Liang7d637782018-06-05 09:58:07 -04002359 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002360 case Expression::Kind::kSwizzle:
Ethan Nicholas6b4d5812020-10-12 16:11:51 -04002361 return this->requirements(e->as<Swizzle>().base().get());
Ethan Nicholase6592142020-09-08 10:22:09 -04002362 case Expression::Kind::kBinary: {
2363 const BinaryExpression& bin = e->as<BinaryExpression>();
John Stiles2d4f9592020-10-30 10:29:12 -04002364 return this->requirements(bin.left().get()) |
2365 this->requirements(bin.right().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002366 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002367 case Expression::Kind::kIndex: {
John Stiles3dc0da62020-08-19 17:48:31 -04002368 const IndexExpression& idx = e->as<IndexExpression>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04002369 return this->requirements(idx.base().get()) | this->requirements(idx.index().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002370 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002371 case Expression::Kind::kPrefix:
Ethan Nicholas444ccc62020-10-09 10:16:22 -04002372 return this->requirements(e->as<PrefixExpression>().operand().get());
Ethan Nicholase6592142020-09-08 10:22:09 -04002373 case Expression::Kind::kPostfix:
Ethan Nicholas444ccc62020-10-09 10:16:22 -04002374 return this->requirements(e->as<PostfixExpression>().operand().get());
Ethan Nicholase6592142020-09-08 10:22:09 -04002375 case Expression::Kind::kTernary: {
John Stiles3dc0da62020-08-19 17:48:31 -04002376 const TernaryExpression& t = e->as<TernaryExpression>();
Ethan Nicholasdd218162020-10-08 05:48:01 -04002377 return this->requirements(t.test().get()) | this->requirements(t.ifTrue().get()) |
2378 this->requirements(t.ifFalse().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002379 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002380 case Expression::Kind::kVariableReference: {
John Stiles3dc0da62020-08-19 17:48:31 -04002381 const VariableReference& v = e->as<VariableReference>();
Ethan Nicholas78686922020-10-08 06:46:27 -04002382 const Modifiers& modifiers = v.variable()->modifiers();
Ethan Nicholascc305772017-10-13 16:17:45 -04002383 Requirements result = kNo_Requirements;
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002384 if (modifiers.fLayout.fBuiltin == SK_FRAGCOORD_BUILTIN) {
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -04002385 result = kGlobals_Requirement | kFragCoord_Requirement;
Ethan Nicholas453f67f2020-10-09 10:43:45 -04002386 } else if (Variable::Storage::kGlobal == v.variable()->storage()) {
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002387 if (modifiers.fFlags & Modifiers::kIn_Flag) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002388 result = kInputs_Requirement;
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002389 } else if (modifiers.fFlags & Modifiers::kOut_Flag) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002390 result = kOutputs_Requirement;
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002391 } else if (modifiers.fFlags & Modifiers::kUniform_Flag &&
Ethan Nicholas78686922020-10-08 06:46:27 -04002392 v.variable()->type().typeKind() != Type::TypeKind::kSampler) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002393 result = kUniforms_Requirement;
Timothy Liangee84fe12018-05-18 14:38:19 -04002394 } else {
2395 result = kGlobals_Requirement;
Ethan Nicholascc305772017-10-13 16:17:45 -04002396 }
2397 }
2398 return result;
2399 }
2400 default:
2401 return kNo_Requirements;
2402 }
2403}
2404
Ethan Nicholasff350cb2020-05-14 14:05:13 -04002405MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const Statement* s) {
2406 if (!s) {
2407 return kNo_Requirements;
2408 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002409 switch (s->kind()) {
2410 case Statement::Kind::kBlock: {
Ethan Nicholascc305772017-10-13 16:17:45 -04002411 Requirements result = kNo_Requirements;
Ethan Nicholas7bd60432020-09-25 14:31:59 -04002412 for (const std::unique_ptr<Statement>& child : s->as<Block>().children()) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04002413 result |= this->requirements(child.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002414 }
2415 return result;
2416 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002417 case Statement::Kind::kVarDeclaration: {
John Stiles3dc0da62020-08-19 17:48:31 -04002418 const VarDeclaration& var = s->as<VarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04002419 return this->requirements(var.value().get());
Timothy Liang7d637782018-06-05 09:58:07 -04002420 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002421 case Statement::Kind::kExpression:
Ethan Nicholasd503a5a2020-09-30 09:29:55 -04002422 return this->requirements(s->as<ExpressionStatement>().expression().get());
Ethan Nicholase6592142020-09-08 10:22:09 -04002423 case Statement::Kind::kReturn: {
John Stiles3dc0da62020-08-19 17:48:31 -04002424 const ReturnStatement& r = s->as<ReturnStatement>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04002425 return this->requirements(r.expression().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002426 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002427 case Statement::Kind::kIf: {
John Stiles3dc0da62020-08-19 17:48:31 -04002428 const IfStatement& i = s->as<IfStatement>();
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04002429 return this->requirements(i.test().get()) |
2430 this->requirements(i.ifTrue().get()) |
2431 this->requirements(i.ifFalse().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002432 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002433 case Statement::Kind::kFor: {
John Stiles3dc0da62020-08-19 17:48:31 -04002434 const ForStatement& f = s->as<ForStatement>();
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04002435 return this->requirements(f.initializer().get()) |
2436 this->requirements(f.test().get()) |
2437 this->requirements(f.next().get()) |
2438 this->requirements(f.statement().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002439 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002440 case Statement::Kind::kDo: {
John Stiles3dc0da62020-08-19 17:48:31 -04002441 const DoStatement& d = s->as<DoStatement>();
Ethan Nicholas1fd61162020-09-28 13:14:19 -04002442 return this->requirements(d.test().get()) |
2443 this->requirements(d.statement().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002444 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002445 case Statement::Kind::kSwitch: {
John Stiles3dc0da62020-08-19 17:48:31 -04002446 const SwitchStatement& sw = s->as<SwitchStatement>();
Ethan Nicholas01b05e52020-10-22 15:53:41 -04002447 Requirements result = this->requirements(sw.value().get());
John Stilesb23a64b2021-03-11 08:27:59 -05002448 for (const std::unique_ptr<Statement>& sc : sw.cases()) {
2449 result |= this->requirements(sc->as<SwitchCase>().statement().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002450 }
2451 return result;
2452 }
2453 default:
2454 return kNo_Requirements;
2455 }
2456}
2457
2458MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const FunctionDeclaration& f) {
Ethan Nicholased84b732020-10-08 11:45:44 -04002459 if (f.isBuiltin()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002460 return kNo_Requirements;
2461 }
2462 auto found = fRequirements.find(&f);
2463 if (found == fRequirements.end()) {
Ethan Nicholas65a8f562019-04-19 14:00:26 -04002464 fRequirements[&f] = kNo_Requirements;
Brian Osman133724c2020-10-28 14:14:39 -04002465 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04002466 if (e->is<FunctionDefinition>()) {
2467 const FunctionDefinition& def = e->as<FunctionDefinition>();
Ethan Nicholas0a5d0962020-10-14 13:33:18 -04002468 if (&def.declaration() == &f) {
2469 Requirements reqs = this->requirements(def.body().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002470 fRequirements[&f] = reqs;
2471 return reqs;
2472 }
2473 }
2474 }
John Stiles569249b2020-11-03 12:18:22 -05002475 // We never found a definition for this declared function, but it's legal to prototype a
2476 // function without ever giving a definition, as long as you don't call it.
2477 return kNo_Requirements;
Ethan Nicholascc305772017-10-13 16:17:45 -04002478 }
2479 return found->second;
2480}
2481
Timothy Liangb8eeb802018-07-23 16:46:16 -04002482bool MetalCodeGenerator::generateCode() {
John Stiles44532372020-12-07 12:33:55 -05002483 StringStream header;
2484 {
2485 AutoOutputStream outputToHeader(this, &header, &fIndentation);
Michael Ludwigbf58add2021-03-16 10:40:11 -04002486 this->writeHeader();
John Stiles44532372020-12-07 12:33:55 -05002487 this->writeStructDefinitions();
2488 this->writeUniformStruct();
2489 this->writeInputStruct();
2490 this->writeOutputStruct();
2491 this->writeInterfaceBlocks();
2492 this->writeGlobalStruct();
2493 }
2494 StringStream body;
2495 {
2496 AutoOutputStream outputToBody(this, &body, &fIndentation);
2497 for (const ProgramElement* e : fProgram.elements()) {
2498 this->writeProgramElement(*e);
2499 }
2500 }
2501 write_stringstream(header, *fOut);
2502 write_stringstream(fExtraFunctions, *fOut);
2503 write_stringstream(body, *fOut);
Brian Osman8609a242020-09-08 14:01:49 -04002504 return 0 == fErrors.errorCount();
Ethan Nicholascc305772017-10-13 16:17:45 -04002505}
2506
John Stilesa6841be2020-08-06 14:11:56 -04002507} // namespace SkSL