blob: a08133ea52c2bc42e6ea9e2facc12cb9b6fc21d2 [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
Ethan Nicholascc305772017-10-13 16:17:45 -040047void MetalCodeGenerator::write(const char* s) {
48 if (!s[0]) {
49 return;
50 }
51 if (fAtLineStart) {
52 for (int i = 0; i < fIndentation; i++) {
53 fOut->writeText(" ");
54 }
55 }
56 fOut->writeText(s);
57 fAtLineStart = false;
58}
59
60void MetalCodeGenerator::writeLine(const char* s) {
61 this->write(s);
John Stilese8b5a732021-03-12 13:25:52 -050062 this->writeLine();
Ethan Nicholascc305772017-10-13 16:17:45 -040063}
64
65void MetalCodeGenerator::write(const String& s) {
66 this->write(s.c_str());
67}
68
69void MetalCodeGenerator::writeLine(const String& s) {
70 this->writeLine(s.c_str());
71}
72
73void MetalCodeGenerator::writeLine() {
John Stilese8b5a732021-03-12 13:25:52 -050074 fOut->writeText(fLineEnding);
75 fAtLineStart = true;
76}
77
78void MetalCodeGenerator::finishLine() {
79 if (!fAtLineStart) {
80 this->writeLine();
81 }
Ethan Nicholascc305772017-10-13 16:17:45 -040082}
83
84void MetalCodeGenerator::writeExtension(const Extension& ext) {
Ethan Nicholasefb09e22020-09-30 10:17:00 -040085 this->writeLine("#extension " + ext.name() + " : enable");
Ethan Nicholascc305772017-10-13 16:17:45 -040086}
87
Ethan Nicholas45fa8102020-01-13 10:58:49 -050088String MetalCodeGenerator::typeName(const Type& type) {
Ethan Nicholase6592142020-09-08 10:22:09 -040089 switch (type.typeKind()) {
John Stilesb4418502021-02-04 10:57:08 -050090 case Type::TypeKind::kArray:
91 SkASSERTF(type.columns() > 0, "invalid array size: %s", type.description().c_str());
92 return String::printf("array<%s, %d>",
93 this->typeName(type.componentType()).c_str(), type.columns());
94
Ethan Nicholase6592142020-09-08 10:22:09 -040095 case Type::TypeKind::kVector:
Ethan Nicholas45fa8102020-01-13 10:58:49 -050096 return this->typeName(type.componentType()) + to_string(type.columns());
John Stilesb4418502021-02-04 10:57:08 -050097
Ethan Nicholase6592142020-09-08 10:22:09 -040098 case Type::TypeKind::kMatrix:
Ethan Nicholas45fa8102020-01-13 10:58:49 -050099 return this->typeName(type.componentType()) + to_string(type.columns()) + "x" +
100 to_string(type.rows());
John Stilesb4418502021-02-04 10:57:08 -0500101
Ethan Nicholase6592142020-09-08 10:22:09 -0400102 case Type::TypeKind::kSampler:
John Stiles368db7c2020-12-29 11:20:08 -0500103 return "texture2d<float>"; // FIXME - support other texture types
John Stilesb4418502021-02-04 10:57:08 -0500104
John Stilesfd41d872020-11-25 22:39:45 -0500105 case Type::TypeKind::kEnum:
106 return "int";
John Stilesb4418502021-02-04 10:57:08 -0500107
Ethan Nicholascc305772017-10-13 16:17:45 -0400108 default:
John Stiles54e7c052021-01-11 14:22:36 -0500109 if (type == *fContext.fTypes.fHalf) {
Timothy Liang43d225f2018-07-19 15:27:13 -0400110 // FIXME - Currently only supporting floats in MSL to avoid type coercion issues.
John Stiles54e7c052021-01-11 14:22:36 -0500111 return fContext.fTypes.fFloat->name();
Timothy Liang7d637782018-06-05 09:58:07 -0400112 } else {
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500113 return type.name();
Timothy Liang7d637782018-06-05 09:58:07 -0400114 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400115 }
116}
117
Brian Osman02bc5222021-01-28 11:00:20 -0500118void MetalCodeGenerator::writeStructDefinition(const StructDefinition& s) {
119 const Type& type = s.type();
John Stilesdc75a972020-11-25 16:24:55 -0500120 this->writeLine("struct " + type.name() + " {");
121 fIndentation++;
122 this->writeFields(type.fields(), type.fOffset);
123 fIndentation--;
Brian Osman02bc5222021-01-28 11:00:20 -0500124 this->writeLine("};");
John Stilesdc75a972020-11-25 16:24:55 -0500125}
126
John Stilesb4418502021-02-04 10:57:08 -0500127void MetalCodeGenerator::writeType(const Type& type) {
128 this->write(this->typeName(type));
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500129}
130
Ethan Nicholascc305772017-10-13 16:17:45 -0400131void MetalCodeGenerator::writeExpression(const Expression& expr, Precedence parentPrecedence) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400132 switch (expr.kind()) {
133 case Expression::Kind::kBinary:
John Stiles81365af2020-08-18 09:24:00 -0400134 this->writeBinaryExpression(expr.as<BinaryExpression>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400135 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400136 case Expression::Kind::kBoolLiteral:
John Stiles81365af2020-08-18 09:24:00 -0400137 this->writeBoolLiteral(expr.as<BoolLiteral>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400138 break;
John Stiles2bec8ab2021-04-06 18:40:04 -0400139 case Expression::Kind::kConstructorArray:
John Stilesd47330f2021-04-08 23:25:52 -0400140 case Expression::Kind::kConstructorStruct:
John Stiles2bec8ab2021-04-06 18:40:04 -0400141 this->writeAnyConstructor(expr.asAnyConstructor(), "{", "}", parentPrecedence);
142 break;
John Stiles8cad6372021-04-07 12:31:13 -0400143 case Expression::Kind::kConstructorCompound:
144 this->writeConstructorCompound(expr.as<ConstructorCompound>(), parentPrecedence);
John Stiles2bec8ab2021-04-06 18:40:04 -0400145 break;
146 case Expression::Kind::kConstructorDiagonalMatrix:
147 case Expression::Kind::kConstructorSplat:
148 this->writeAnyConstructor(expr.asAnyConstructor(), "(", ")", parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400149 break;
John Stiles5abb9e12021-04-06 13:47:19 -0400150 case Expression::Kind::kConstructorMatrixResize:
151 this->writeConstructorMatrixResize(expr.as<ConstructorMatrixResize>(),
152 parentPrecedence);
153 break;
John Stilesfd7252f2021-04-04 22:24:40 -0400154 case Expression::Kind::kConstructorScalarCast:
John Stiles8cad6372021-04-07 12:31:13 -0400155 case Expression::Kind::kConstructorCompoundCast:
John Stilesb14a8192021-04-05 11:40:46 -0400156 this->writeCastConstructor(expr.asAnyConstructor(), "(", ")", parentPrecedence);
John Stiles2938eea2021-04-01 18:58:25 -0400157 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400158 case Expression::Kind::kIntLiteral:
John Stiles81365af2020-08-18 09:24:00 -0400159 this->writeIntLiteral(expr.as<IntLiteral>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400160 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400161 case Expression::Kind::kFieldAccess:
John Stiles81365af2020-08-18 09:24:00 -0400162 this->writeFieldAccess(expr.as<FieldAccess>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400163 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400164 case Expression::Kind::kFloatLiteral:
John Stiles81365af2020-08-18 09:24:00 -0400165 this->writeFloatLiteral(expr.as<FloatLiteral>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400166 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400167 case Expression::Kind::kFunctionCall:
John Stiles81365af2020-08-18 09:24:00 -0400168 this->writeFunctionCall(expr.as<FunctionCall>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400169 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400170 case Expression::Kind::kPrefix:
John Stiles81365af2020-08-18 09:24:00 -0400171 this->writePrefixExpression(expr.as<PrefixExpression>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400172 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400173 case Expression::Kind::kPostfix:
John Stiles81365af2020-08-18 09:24:00 -0400174 this->writePostfixExpression(expr.as<PostfixExpression>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400175 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400176 case Expression::Kind::kSetting:
John Stiles81365af2020-08-18 09:24:00 -0400177 this->writeSetting(expr.as<Setting>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400178 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400179 case Expression::Kind::kSwizzle:
John Stiles81365af2020-08-18 09:24:00 -0400180 this->writeSwizzle(expr.as<Swizzle>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400181 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400182 case Expression::Kind::kVariableReference:
John Stiles81365af2020-08-18 09:24:00 -0400183 this->writeVariableReference(expr.as<VariableReference>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400184 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400185 case Expression::Kind::kTernary:
John Stiles81365af2020-08-18 09:24:00 -0400186 this->writeTernaryExpression(expr.as<TernaryExpression>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400187 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400188 case Expression::Kind::kIndex:
John Stiles81365af2020-08-18 09:24:00 -0400189 this->writeIndexExpression(expr.as<IndexExpression>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400190 break;
191 default:
John Stileseada7bc2021-02-02 16:29:32 -0500192 SkDEBUGFAILF("unsupported expression: %s", expr.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -0500193 break;
Ethan Nicholascc305772017-10-13 16:17:45 -0400194 }
195}
196
John Stiles06b84ef2020-12-09 12:35:48 -0500197String MetalCodeGenerator::getOutParamHelper(const FunctionCall& call,
198 const ExpressionArray& arguments,
199 const SkTArray<VariableReference*>& outVars) {
200 AutoOutputStream outputToExtraFunctions(this, &fExtraFunctions, &fIndentation);
201 const FunctionDeclaration& function = call.function();
202
John Stilese1068342021-03-22 11:57:41 -0400203 String name = "_skOutParamHelper" + to_string(fSwizzleHelperCount++) +
204 "_" + function.mangledName();
John Stiles06b84ef2020-12-09 12:35:48 -0500205 const char* separator = "";
206
207 // Emit a prototype for the function we'll be calling through to in our helper.
208 if (!function.isBuiltin()) {
209 this->writeFunctionDeclaration(function);
210 this->writeLine(";");
211 }
212
213 // Synthesize a helper function that takes the same inputs as `function`, except in places where
214 // `outVars` is non-null; in those places, we take the type of the VariableReference.
215 //
216 // float _skOutParamHelper0_originalFuncName(float _var0, float _var1, float& outParam) {
John Stilesb4418502021-02-04 10:57:08 -0500217 this->writeType(call.type());
John Stiles06b84ef2020-12-09 12:35:48 -0500218 this->write(" ");
219 this->write(name);
220 this->write("(");
221 this->writeFunctionRequirementParams(function, separator);
222
223 SkASSERT(outVars.size() == arguments.size());
224 SkASSERT(outVars.size() == function.parameters().size());
225
John Stiles73e2c892021-02-13 13:58:01 -0500226 // We need to detect cases where the caller passes the same variable as an out-param more than
227 // once, and avoid reusing the variable name. (In those cases we can actually just ignore the
228 // redundant input parameter entirely, and not give it any name.)
229 std::unordered_set<const Variable*> writtenVars;
230
John Stiles06b84ef2020-12-09 12:35:48 -0500231 for (int index = 0; index < arguments.count(); ++index) {
232 this->write(separator);
233 separator = ", ";
234
235 const Variable* param = function.parameters()[index];
236 this->writeModifiers(param->modifiers(), /*globalContext=*/false);
237
238 const Type* type = outVars[index] ? &outVars[index]->type() : &arguments[index]->type();
John Stilesb4418502021-02-04 10:57:08 -0500239 this->writeType(*type);
John Stiles06b84ef2020-12-09 12:35:48 -0500240
241 if (param->modifiers().fFlags & Modifiers::kOut_Flag) {
242 this->write("&");
243 }
244 if (outVars[index]) {
John Stiles73e2c892021-02-13 13:58:01 -0500245 auto [iter, didInsert] = writtenVars.insert(outVars[index]->variable());
246 if (didInsert) {
247 this->write(" ");
248 fIgnoreVariableReferenceModifiers = true;
249 this->writeVariableReference(*outVars[index]);
250 fIgnoreVariableReferenceModifiers = false;
251 }
John Stiles06b84ef2020-12-09 12:35:48 -0500252 } else {
253 this->write(" _var");
254 this->write(to_string(index));
255 }
John Stiles06b84ef2020-12-09 12:35:48 -0500256 }
257 this->writeLine(") {");
258
259 ++fIndentation;
260 for (int index = 0; index < outVars.count(); ++index) {
261 if (!outVars[index]) {
262 continue;
263 }
264 // float3 _var2[ = outParam.zyx];
John Stilesb4418502021-02-04 10:57:08 -0500265 this->writeType(arguments[index]->type());
John Stiles06b84ef2020-12-09 12:35:48 -0500266 this->write(" _var");
267 this->write(to_string(index));
268
269 const Variable* param = function.parameters()[index];
270 if (param->modifiers().fFlags & Modifiers::kIn_Flag) {
271 this->write(" = ");
272 fIgnoreVariableReferenceModifiers = true;
Brian Osman00185012021-02-04 16:07:11 -0500273 this->writeExpression(*arguments[index], Precedence::kAssignment);
John Stiles06b84ef2020-12-09 12:35:48 -0500274 fIgnoreVariableReferenceModifiers = false;
275 }
276
277 this->writeLine(";");
278 }
279
John Stilesf7410bd2021-01-19 13:07:55 -0500280 // [int _skResult = ] myFunction(inputs, outputs, _globals, _var0, _var1, _var2, _var3);
John Stiles06b84ef2020-12-09 12:35:48 -0500281 bool hasResult = (call.type().name() != "void");
282 if (hasResult) {
John Stilesb4418502021-02-04 10:57:08 -0500283 this->writeType(call.type());
John Stiles06b84ef2020-12-09 12:35:48 -0500284 this->write(" _skResult = ");
285 }
286
John Stilese1068342021-03-22 11:57:41 -0400287 this->writeName(function.mangledName());
John Stiles06b84ef2020-12-09 12:35:48 -0500288 this->write("(");
289 separator = "";
290 this->writeFunctionRequirementArgs(function, separator);
291
292 for (int index = 0; index < arguments.count(); ++index) {
293 this->write(separator);
294 separator = ", ";
295
296 this->write("_var");
297 this->write(to_string(index));
298 }
299 this->writeLine(");");
300
301 for (int index = 0; index < outVars.count(); ++index) {
302 if (!outVars[index]) {
303 continue;
304 }
305 // outParam.zyx = _var2;
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 this->write(" = _var");
310 this->write(to_string(index));
311 this->writeLine(";");
312 }
313
314 if (hasResult) {
315 this->writeLine("return _skResult;");
316 }
317
318 --fIndentation;
319 this->writeLine("}");
320
321 return name;
John Stilesb21fac22020-12-04 15:36:49 -0500322}
323
John Stilesf64e4072020-12-10 10:34:27 -0500324String MetalCodeGenerator::getBitcastIntrinsic(const Type& outType) {
325 return "as_type<" + outType.displayName() + ">";
326}
327
Ethan Nicholascc305772017-10-13 16:17:45 -0400328void MetalCodeGenerator::writeFunctionCall(const FunctionCall& c) {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400329 const FunctionDeclaration& function = c.function();
John Stiles496b7d12021-05-06 10:26:45 -0400330
331 // Many intrinsics need to be rewritten in Metal.
332 if (function.isIntrinsic()) {
333 if (this->writeIntrinsicCall(c, function.intrinsicKind())) {
John Stiles89ac7c22020-12-30 17:47:31 -0500334 return;
335 }
Timothy Liang6403b0e2018-05-17 10:40:04 -0400336 }
John Stilesb21fac22020-12-04 15:36:49 -0500337
John Stilesd7199b22020-12-30 16:22:58 -0500338 // Determine whether or not we need to emulate GLSL's out-param semantics for Metal using a
339 // helper function. (Specifically, out-parameters in GLSL are only written back to the original
340 // variable at the end of the function call; also, swizzles are supported, whereas Metal doesn't
341 // allow a swizzle to be passed to a `floatN&`.)
342 const ExpressionArray& arguments = c.arguments();
John Stilesb21fac22020-12-04 15:36:49 -0500343 const std::vector<const Variable*>& parameters = function.parameters();
344 SkASSERT(arguments.size() == parameters.size());
John Stiles06b84ef2020-12-09 12:35:48 -0500345
346 bool foundOutParam = false;
347 SkSTArray<16, VariableReference*> outVars;
John Stilesf64e4072020-12-10 10:34:27 -0500348 outVars.push_back_n(arguments.count(), (VariableReference*)nullptr);
John Stiles06b84ef2020-12-09 12:35:48 -0500349
350 for (int index = 0; index < arguments.count(); ++index) {
John Stilesb21fac22020-12-04 15:36:49 -0500351 // If this is an out parameter...
352 if (parameters[index]->modifiers().fFlags & Modifiers::kOut_Flag) {
John Stiles06b84ef2020-12-09 12:35:48 -0500353 // Find the expression's inner variable being written to.
John Stilesb21fac22020-12-04 15:36:49 -0500354 Analysis::AssignmentInfo info;
John Stiles06b84ef2020-12-09 12:35:48 -0500355 // Assignability was verified at IRGeneration time, so this should always succeed.
356 SkAssertResult(Analysis::IsAssignable(*arguments[index], &info));
357 outVars[index] = info.fAssignedVar;
358 foundOutParam = true;
John Stilesb21fac22020-12-04 15:36:49 -0500359 }
360 }
361
John Stiles06b84ef2020-12-09 12:35:48 -0500362 if (foundOutParam) {
363 // Out parameters need to be written back to at the end of the function. To do this, we
364 // synthesize a helper function which evaluates the out-param expression into a temporary
365 // variable, calls the original function, then writes the temp var back into the out param
366 // using the original out-param expression. (This lets us support things like swizzles and
367 // array indices.)
John Stilesd7199b22020-12-30 16:22:58 -0500368 this->write(getOutParamHelper(c, arguments, outVars));
369 } else {
John Stilese1068342021-03-22 11:57:41 -0400370 this->write(function.mangledName());
John Stiles06b84ef2020-12-09 12:35:48 -0500371 }
372
Ethan Nicholascc305772017-10-13 16:17:45 -0400373 this->write("(");
374 const char* separator = "";
John Stiles06b84ef2020-12-09 12:35:48 -0500375 this->writeFunctionRequirementArgs(function, separator);
376 for (int i = 0; i < arguments.count(); ++i) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400377 this->write(separator);
378 separator = ", ";
John Stiles06b84ef2020-12-09 12:35:48 -0500379
380 if (outVars[i]) {
Brian Osman00185012021-02-04 16:07:11 -0500381 this->writeExpression(*outVars[i], Precedence::kSequence);
John Stiles06b84ef2020-12-09 12:35:48 -0500382 } else {
Brian Osman00185012021-02-04 16:07:11 -0500383 this->writeExpression(*arguments[i], Precedence::kSequence);
John Stiles06b84ef2020-12-09 12:35:48 -0500384 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400385 }
386 this->write(")");
387}
388
Brian Osman964f0a02020-12-29 10:15:22 -0500389static constexpr char kInverse2x2[] = R"(
390float2x2 float2x2_inverse(float2x2 m) {
391 return float2x2(m[1][1], -m[0][1], -m[1][0], m[0][0]) * (1/determinant(m));
392}
393)";
394
395static constexpr char kInverse3x3[] = R"(
396float3x3 float3x3_inverse(float3x3 m) {
397 float a00 = m[0][0], a01 = m[0][1], a02 = m[0][2];
398 float a10 = m[1][0], a11 = m[1][1], a12 = m[1][2];
399 float a20 = m[2][0], a21 = m[2][1], a22 = m[2][2];
400 float b01 = a22*a11 - a12*a21;
401 float b11 = -a22*a10 + a12*a20;
402 float b21 = a21*a10 - a11*a20;
403 float det = a00*b01 + a01*b11 + a02*b21;
404 return float3x3(b01, (-a22*a01 + a02*a21), ( a12*a01 - a02*a11),
405 b11, ( a22*a00 - a02*a20), (-a12*a00 + a02*a10),
406 b21, (-a21*a00 + a01*a20), ( a11*a00 - a01*a10)) * (1/det);
407}
408)";
409
410static constexpr char kInverse4x4[] = R"(
411float4x4 float4x4_inverse(float4x4 m) {
412 float a00 = m[0][0], a01 = m[0][1], a02 = m[0][2], a03 = m[0][3];
413 float a10 = m[1][0], a11 = m[1][1], a12 = m[1][2], a13 = m[1][3];
414 float a20 = m[2][0], a21 = m[2][1], a22 = m[2][2], a23 = m[2][3];
415 float a30 = m[3][0], a31 = m[3][1], a32 = m[3][2], a33 = m[3][3];
416 float b00 = a00*a11 - a01*a10;
417 float b01 = a00*a12 - a02*a10;
418 float b02 = a00*a13 - a03*a10;
419 float b03 = a01*a12 - a02*a11;
420 float b04 = a01*a13 - a03*a11;
421 float b05 = a02*a13 - a03*a12;
422 float b06 = a20*a31 - a21*a30;
423 float b07 = a20*a32 - a22*a30;
424 float b08 = a20*a33 - a23*a30;
425 float b09 = a21*a32 - a22*a31;
426 float b10 = a21*a33 - a23*a31;
427 float b11 = a22*a33 - a23*a32;
428 float det = b00*b11 - b01*b10 + b02*b09 + b03*b08 - b04*b07 + b05*b06;
429 return float4x4(a11*b11 - a12*b10 + a13*b09,
430 a02*b10 - a01*b11 - a03*b09,
431 a31*b05 - a32*b04 + a33*b03,
432 a22*b04 - a21*b05 - a23*b03,
433 a12*b08 - a10*b11 - a13*b07,
434 a00*b11 - a02*b08 + a03*b07,
435 a32*b02 - a30*b05 - a33*b01,
436 a20*b05 - a22*b02 + a23*b01,
437 a10*b10 - a11*b08 + a13*b06,
438 a01*b08 - a00*b10 - a03*b06,
439 a30*b04 - a31*b02 + a33*b00,
440 a21*b02 - a20*b04 - a23*b00,
441 a11*b07 - a10*b09 - a12*b06,
442 a00*b09 - a01*b07 + a02*b06,
443 a31*b01 - a30*b03 - a32*b00,
444 a20*b03 - a21*b01 + a22*b00) * (1/det);
445}
446)";
447
John Stilesd7199b22020-12-30 16:22:58 -0500448String MetalCodeGenerator::getInversePolyfill(const ExpressionArray& arguments) {
449 // Only use polyfills for a function taking a single-argument square matrix.
450 if (arguments.size() == 1) {
451 const Type& type = arguments.front()->type();
452 if (type.isMatrix() && type.rows() == type.columns()) {
453 // Inject the correct polyfill based on the matrix size.
454 String name = this->typeName(type) + "_inverse";
455 auto [iter, didInsert] = fWrittenIntrinsics.insert(name);
456 if (didInsert) {
457 switch (type.rows()) {
458 case 2:
459 fExtraFunctions.writeText(kInverse2x2);
460 break;
461 case 3:
462 fExtraFunctions.writeText(kInverse3x3);
463 break;
464 case 4:
465 fExtraFunctions.writeText(kInverse4x4);
466 break;
467 }
468 }
469 return name;
Chris Daltondba7aab2018-11-15 10:57:49 -0500470 }
471 }
John Stilesd7199b22020-12-30 16:22:58 -0500472 // This isn't the built-in `inverse`. We don't want to polyfill it at all.
473 return "inverse";
Chris Daltondba7aab2018-11-15 10:57:49 -0500474}
475
Brian Osman93aed9a2020-12-28 15:18:46 -0500476static constexpr char kMatrixCompMult[] = R"(
477template <int C, int R>
478matrix<float, C, R> matrixCompMult(matrix<float, C, R> a, matrix<float, C, R> b) {
479 matrix<float, C, R> result;
480 for (int c = 0; c < C; ++c) {
481 result[c] = a[c] * b[c];
482 }
483 return result;
484}
485)";
486
487void MetalCodeGenerator::writeMatrixCompMult() {
488 String name = "matrixCompMult";
489 if (fWrittenIntrinsics.find(name) == fWrittenIntrinsics.end()) {
490 fWrittenIntrinsics.insert(name);
491 fExtraFunctions.writeText(kMatrixCompMult);
492 }
493}
494
John Stiles86424eb2020-12-11 11:17:14 -0500495String MetalCodeGenerator::getTempVariable(const Type& type) {
496 String tempVar = "_skTemp" + to_string(fVarCount++);
497 this->fFunctionHeader += " " + this->typeName(type) + " " + tempVar + ";\n";
498 return tempVar;
499}
500
John Stiles791c27d2020-12-30 14:56:57 -0500501void MetalCodeGenerator::writeSimpleIntrinsic(const FunctionCall& c) {
502 // Write out an intrinsic function call exactly as-is. No muss no fuss.
503 this->write(c.function().name());
John Stilesd7199b22020-12-30 16:22:58 -0500504 this->writeArgumentList(c.arguments());
505}
506
507void MetalCodeGenerator::writeArgumentList(const ExpressionArray& arguments) {
John Stiles791c27d2020-12-30 14:56:57 -0500508 this->write("(");
509 const char* separator = "";
John Stilesd7199b22020-12-30 16:22:58 -0500510 for (const std::unique_ptr<Expression>& arg : arguments) {
John Stiles791c27d2020-12-30 14:56:57 -0500511 this->write(separator);
512 separator = ", ";
Brian Osman00185012021-02-04 16:07:11 -0500513 this->writeExpression(*arg, Precedence::kSequence);
John Stiles791c27d2020-12-30 14:56:57 -0500514 }
515 this->write(")");
516}
517
John Stiles496b7d12021-05-06 10:26:45 -0400518bool MetalCodeGenerator::writeIntrinsicCall(const FunctionCall& c, IntrinsicKind kind) {
John Stiles8e3b6be2020-10-13 11:14:08 -0400519 const ExpressionArray& arguments = c.arguments();
Timothy Liang6403b0e2018-05-17 10:40:04 -0400520 switch (kind) {
John Stiles496b7d12021-05-06 10:26:45 -0400521 case k_sample_IntrinsicKind: {
Brian Osman00185012021-02-04 16:07:11 -0500522 this->writeExpression(*arguments[0], Precedence::kSequence);
Timothy Lianga06f2152018-05-24 15:33:31 -0400523 this->write(".sample(");
Brian Osman00185012021-02-04 16:07:11 -0500524 this->writeExpression(*arguments[0], Precedence::kSequence);
Timothy Lianga06f2152018-05-24 15:33:31 -0400525 this->write(SAMPLER_SUFFIX);
526 this->write(", ");
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400527 const Type& arg1Type = arguments[1]->type();
John Stilesb14a8192021-04-05 11:40:46 -0400528 if (arg1Type.columns() == 3) {
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500529 // have to store the vector in a temp variable to avoid double evaluating it
John Stiles86424eb2020-12-11 11:17:14 -0500530 String tmpVar = this->getTempVariable(arg1Type);
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500531 this->write("(" + tmpVar + " = ");
Brian Osman00185012021-02-04 16:07:11 -0500532 this->writeExpression(*arguments[1], Precedence::kSequence);
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500533 this->write(", " + tmpVar + ".xy / " + tmpVar + ".z))");
Timothy Liangee84fe12018-05-18 14:38:19 -0400534 } else {
John Stilesb14a8192021-04-05 11:40:46 -0400535 SkASSERT(arg1Type.columns() == 2);
Brian Osman00185012021-02-04 16:07:11 -0500536 this->writeExpression(*arguments[1], Precedence::kSequence);
Timothy Liangee84fe12018-05-18 14:38:19 -0400537 this->write(")");
538 }
John Stiles496b7d12021-05-06 10:26:45 -0400539 return true;
Ethan Nicholas30d30222020-09-11 12:27:26 -0400540 }
John Stiles496b7d12021-05-06 10:26:45 -0400541 case k_mod_IntrinsicKind: {
Timothy Liang651286f2018-06-07 09:55:33 -0400542 // 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 -0500543 String tmpX = this->getTempVariable(arguments[0]->type());
John Stiles61b2e812020-12-30 18:27:31 -0500544 String tmpY = this->getTempVariable(arguments[1]->type());
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500545 this->write("(" + tmpX + " = ");
Brian Osman00185012021-02-04 16:07:11 -0500546 this->writeExpression(*arguments[0], Precedence::kSequence);
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500547 this->write(", " + tmpY + " = ");
Brian Osman00185012021-02-04 16:07:11 -0500548 this->writeExpression(*arguments[1], Precedence::kSequence);
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500549 this->write(", " + tmpX + " - " + tmpY + " * floor(" + tmpX + " / " + tmpY + "))");
John Stiles496b7d12021-05-06 10:26:45 -0400550 return true;
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500551 }
Brian Osman46787d52020-11-24 14:18:23 -0500552 // GLSL declares scalar versions of most geometric intrinsics, but these don't exist in MSL
John Stiles496b7d12021-05-06 10:26:45 -0400553 case k_distance_IntrinsicKind: {
Brian Osman46787d52020-11-24 14:18:23 -0500554 if (arguments[0]->type().columns() == 1) {
555 this->write("abs(");
Brian Osman00185012021-02-04 16:07:11 -0500556 this->writeExpression(*arguments[0], Precedence::kAdditive);
Brian Osman46787d52020-11-24 14:18:23 -0500557 this->write(" - ");
Brian Osman00185012021-02-04 16:07:11 -0500558 this->writeExpression(*arguments[1], Precedence::kAdditive);
Brian Osman46787d52020-11-24 14:18:23 -0500559 this->write(")");
560 } else {
John Stiles791c27d2020-12-30 14:56:57 -0500561 this->writeSimpleIntrinsic(c);
Brian Osman46787d52020-11-24 14:18:23 -0500562 }
John Stiles496b7d12021-05-06 10:26:45 -0400563 return true;
Brian Osman46787d52020-11-24 14:18:23 -0500564 }
John Stiles496b7d12021-05-06 10:26:45 -0400565 case k_dot_IntrinsicKind: {
Brian Osman46787d52020-11-24 14:18:23 -0500566 if (arguments[0]->type().columns() == 1) {
567 this->write("(");
Brian Osman00185012021-02-04 16:07:11 -0500568 this->writeExpression(*arguments[0], Precedence::kMultiplicative);
Brian Osman46787d52020-11-24 14:18:23 -0500569 this->write(" * ");
Brian Osman00185012021-02-04 16:07:11 -0500570 this->writeExpression(*arguments[1], Precedence::kMultiplicative);
Brian Osman46787d52020-11-24 14:18:23 -0500571 this->write(")");
572 } else {
John Stiles791c27d2020-12-30 14:56:57 -0500573 this->writeSimpleIntrinsic(c);
Brian Osman46787d52020-11-24 14:18:23 -0500574 }
John Stiles496b7d12021-05-06 10:26:45 -0400575 return true;
Brian Osman46787d52020-11-24 14:18:23 -0500576 }
John Stiles496b7d12021-05-06 10:26:45 -0400577 case k_faceforward_IntrinsicKind: {
John Stilesad0571f2020-12-10 18:03:10 -0500578 if (arguments[0]->type().columns() == 1) {
579 // ((((Nref) * (I) < 0) ? 1 : -1) * (N))
580 this->write("((((");
Brian Osman00185012021-02-04 16:07:11 -0500581 this->writeExpression(*arguments[2], Precedence::kSequence);
John Stilesad0571f2020-12-10 18:03:10 -0500582 this->write(") * (");
Brian Osman00185012021-02-04 16:07:11 -0500583 this->writeExpression(*arguments[1], Precedence::kSequence);
John Stilesad0571f2020-12-10 18:03:10 -0500584 this->write(") < 0) ? 1 : -1) * (");
Brian Osman00185012021-02-04 16:07:11 -0500585 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stilesad0571f2020-12-10 18:03:10 -0500586 this->write("))");
587 } else {
John Stiles791c27d2020-12-30 14:56:57 -0500588 this->writeSimpleIntrinsic(c);
John Stilesad0571f2020-12-10 18:03:10 -0500589 }
John Stiles496b7d12021-05-06 10:26:45 -0400590 return true;
John Stilesad0571f2020-12-10 18:03:10 -0500591 }
John Stiles496b7d12021-05-06 10:26:45 -0400592 case k_length_IntrinsicKind: {
Brian Osman46787d52020-11-24 14:18:23 -0500593 this->write(arguments[0]->type().columns() == 1 ? "abs(" : "length(");
Brian Osman00185012021-02-04 16:07:11 -0500594 this->writeExpression(*arguments[0], Precedence::kSequence);
Brian Osman46787d52020-11-24 14:18:23 -0500595 this->write(")");
John Stiles496b7d12021-05-06 10:26:45 -0400596 return true;
Brian Osman46787d52020-11-24 14:18:23 -0500597 }
John Stiles496b7d12021-05-06 10:26:45 -0400598 case k_normalize_IntrinsicKind: {
Brian Osman46787d52020-11-24 14:18:23 -0500599 this->write(arguments[0]->type().columns() == 1 ? "sign(" : "normalize(");
Brian Osman00185012021-02-04 16:07:11 -0500600 this->writeExpression(*arguments[0], Precedence::kSequence);
Brian Osman46787d52020-11-24 14:18:23 -0500601 this->write(")");
John Stiles496b7d12021-05-06 10:26:45 -0400602 return true;
Brian Osman46787d52020-11-24 14:18:23 -0500603 }
John Stiles496b7d12021-05-06 10:26:45 -0400604
605 case k_floatBitsToInt_IntrinsicKind:
606 case k_floatBitsToUint_IntrinsicKind:
607 case k_intBitsToFloat_IntrinsicKind:
608 case k_uintBitsToFloat_IntrinsicKind: {
John Stiles0063a9f2020-12-10 18:01:45 -0500609 this->write(this->getBitcastIntrinsic(c.type()));
610 this->write("(");
Brian Osman00185012021-02-04 16:07:11 -0500611 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stiles0063a9f2020-12-10 18:01:45 -0500612 this->write(")");
John Stiles496b7d12021-05-06 10:26:45 -0400613 return true;
John Stiles0063a9f2020-12-10 18:01:45 -0500614 }
John Stiles496b7d12021-05-06 10:26:45 -0400615 case k_degrees_IntrinsicKind: {
John Stilese2d34f82020-12-10 18:02:02 -0500616 this->write("((");
Brian Osman00185012021-02-04 16:07:11 -0500617 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stilese2d34f82020-12-10 18:02:02 -0500618 this->write(") * 57.2957795)");
John Stiles496b7d12021-05-06 10:26:45 -0400619 return true;
John Stilese2d34f82020-12-10 18:02:02 -0500620 }
John Stiles496b7d12021-05-06 10:26:45 -0400621 case k_radians_IntrinsicKind: {
John Stilese2d34f82020-12-10 18:02:02 -0500622 this->write("((");
Brian Osman00185012021-02-04 16:07:11 -0500623 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stilese2d34f82020-12-10 18:02:02 -0500624 this->write(") * 0.0174532925)");
John Stiles496b7d12021-05-06 10:26:45 -0400625 return true;
John Stilese2d34f82020-12-10 18:02:02 -0500626 }
John Stiles496b7d12021-05-06 10:26:45 -0400627 case k_dFdx_IntrinsicKind: {
John Stilesd7199b22020-12-30 16:22:58 -0500628 this->write("dfdx");
629 this->writeArgumentList(c.arguments());
John Stiles496b7d12021-05-06 10:26:45 -0400630 return true;
John Stilesd7199b22020-12-30 16:22:58 -0500631 }
John Stiles496b7d12021-05-06 10:26:45 -0400632 case k_dFdy_IntrinsicKind: {
John Stilesd7199b22020-12-30 16:22:58 -0500633 // Flipping Y also negates the Y derivatives.
John Stiles270cec22021-02-17 12:59:36 -0500634 if (fProgram.fConfig->fSettings.fFlipY) {
John Stilesd7199b22020-12-30 16:22:58 -0500635 this->write("-");
636 }
637 this->write("dfdy");
638 this->writeArgumentList(c.arguments());
John Stiles496b7d12021-05-06 10:26:45 -0400639 return true;
John Stilesd7199b22020-12-30 16:22:58 -0500640 }
John Stiles496b7d12021-05-06 10:26:45 -0400641 case k_inverse_IntrinsicKind: {
John Stilesd7199b22020-12-30 16:22:58 -0500642 this->write(this->getInversePolyfill(arguments));
643 this->writeArgumentList(c.arguments());
John Stiles496b7d12021-05-06 10:26:45 -0400644 return true;
John Stilesd7199b22020-12-30 16:22:58 -0500645 }
John Stiles496b7d12021-05-06 10:26:45 -0400646 case k_inversesqrt_IntrinsicKind: {
John Stilesd7199b22020-12-30 16:22:58 -0500647 this->write("rsqrt");
648 this->writeArgumentList(c.arguments());
John Stiles496b7d12021-05-06 10:26:45 -0400649 return true;
John Stilesd7199b22020-12-30 16:22:58 -0500650 }
John Stiles496b7d12021-05-06 10:26:45 -0400651 case k_atan_IntrinsicKind: {
John Stilesd7199b22020-12-30 16:22:58 -0500652 this->write(c.arguments().size() == 2 ? "atan2" : "atan");
653 this->writeArgumentList(c.arguments());
John Stiles496b7d12021-05-06 10:26:45 -0400654 return true;
John Stilesd7199b22020-12-30 16:22:58 -0500655 }
John Stiles496b7d12021-05-06 10:26:45 -0400656 case k_reflect_IntrinsicKind: {
John Stiles791c27d2020-12-30 14:56:57 -0500657 if (arguments[0]->type().columns() == 1) {
658 // We need to synthesize `I - 2 * N * I * N`.
659 String tmpI = this->getTempVariable(arguments[0]->type());
660 String tmpN = this->getTempVariable(arguments[1]->type());
661
662 // (_skTempI = ...
663 this->write("(" + tmpI + " = ");
Brian Osman00185012021-02-04 16:07:11 -0500664 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stiles791c27d2020-12-30 14:56:57 -0500665
666 // , _skTempN = ...
667 this->write(", " + tmpN + " = ");
Brian Osman00185012021-02-04 16:07:11 -0500668 this->writeExpression(*arguments[1], Precedence::kSequence);
John Stiles791c27d2020-12-30 14:56:57 -0500669
670 // , _skTempI - 2 * _skTempN * _skTempI * _skTempN)
671 this->write(", " + tmpI + " - 2 * " + tmpN + " * " + tmpI + " * " + tmpN + ")");
672 } else {
673 this->writeSimpleIntrinsic(c);
674 }
John Stiles496b7d12021-05-06 10:26:45 -0400675 return true;
John Stiles791c27d2020-12-30 14:56:57 -0500676 }
John Stiles496b7d12021-05-06 10:26:45 -0400677 case k_refract_IntrinsicKind: {
John Stiles4b783d62020-12-30 14:58:07 -0500678 if (arguments[0]->type().columns() == 1) {
679 // Metal does implement refract for vectors; rather than reimplementing refract from
680 // scratch, we can replace the call with `refract(float2(I,0), float2(N,0), eta).x`.
681 this->write("(refract(float2(");
Brian Osman00185012021-02-04 16:07:11 -0500682 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stiles4b783d62020-12-30 14:58:07 -0500683 this->write(", 0), float2(");
Brian Osman00185012021-02-04 16:07:11 -0500684 this->writeExpression(*arguments[1], Precedence::kSequence);
John Stiles4b783d62020-12-30 14:58:07 -0500685 this->write(", 0), ");
Brian Osman00185012021-02-04 16:07:11 -0500686 this->writeExpression(*arguments[2], Precedence::kSequence);
John Stiles4b783d62020-12-30 14:58:07 -0500687 this->write(").x)");
688 } else {
689 this->writeSimpleIntrinsic(c);
690 }
John Stiles496b7d12021-05-06 10:26:45 -0400691 return true;
John Stiles4b783d62020-12-30 14:58:07 -0500692 }
John Stiles496b7d12021-05-06 10:26:45 -0400693 case k_roundEven_IntrinsicKind: {
John Stiles23456532020-12-30 18:12:48 -0500694 this->write("rint");
695 this->writeArgumentList(c.arguments());
John Stiles496b7d12021-05-06 10:26:45 -0400696 return true;
John Stiles23456532020-12-30 18:12:48 -0500697 }
John Stiles496b7d12021-05-06 10:26:45 -0400698 case k_bitCount_IntrinsicKind: {
John Stilese7dc7cb2020-12-22 15:37:14 -0500699 this->write("popcount(");
Brian Osman00185012021-02-04 16:07:11 -0500700 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stilese7dc7cb2020-12-22 15:37:14 -0500701 this->write(")");
John Stiles496b7d12021-05-06 10:26:45 -0400702 return true;
John Stilese7dc7cb2020-12-22 15:37:14 -0500703 }
John Stiles496b7d12021-05-06 10:26:45 -0400704 case k_findLSB_IntrinsicKind: {
John Stiles86424eb2020-12-11 11:17:14 -0500705 // Create a temp variable to store the expression, to avoid double-evaluating it.
706 String skTemp = this->getTempVariable(arguments[0]->type());
707 String exprType = this->typeName(arguments[0]->type());
708
709 // ctz returns numbits(type) on zero inputs; GLSL documents it as generating -1 instead.
710 // Use select to detect zero inputs and force a -1 result.
711
712 // (_skTemp1 = (.....), select(ctz(_skTemp1), int4(-1), _skTemp1 == int4(0)))
713 this->write("(");
714 this->write(skTemp);
715 this->write(" = (");
Brian Osman00185012021-02-04 16:07:11 -0500716 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stiles86424eb2020-12-11 11:17:14 -0500717 this->write("), select(ctz(");
718 this->write(skTemp);
719 this->write("), ");
720 this->write(exprType);
721 this->write("(-1), ");
722 this->write(skTemp);
723 this->write(" == ");
724 this->write(exprType);
725 this->write("(0)))");
John Stiles496b7d12021-05-06 10:26:45 -0400726 return true;
John Stiles86424eb2020-12-11 11:17:14 -0500727 }
John Stiles496b7d12021-05-06 10:26:45 -0400728 case k_findMSB_IntrinsicKind: {
John Stiles9685e522020-12-14 11:52:14 -0500729 // Create a temp variable to store the expression, to avoid double-evaluating it.
730 String skTemp1 = this->getTempVariable(arguments[0]->type());
731 String exprType = this->typeName(arguments[0]->type());
732
733 // GLSL findMSB is actually quite different from Metal's clz:
734 // - For signed negative numbers, it returns the first zero bit, not the first one bit!
735 // - For an empty input (0/~0 depending on sign), findMSB gives -1; clz is numbits(type)
736
737 // (_skTemp1 = (.....),
738 this->write("(");
739 this->write(skTemp1);
740 this->write(" = (");
Brian Osman00185012021-02-04 16:07:11 -0500741 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stiles9685e522020-12-14 11:52:14 -0500742 this->write("), ");
743
744 // Signed input types might be negative; we need another helper variable to negate the
745 // input (since we can only find one bits, not zero bits).
746 String skTemp2;
747 if (arguments[0]->type().isSigned()) {
748 // ... _skTemp2 = (select(_skTemp1, ~_skTemp1, _skTemp1 < 0)),
749 skTemp2 = this->getTempVariable(arguments[0]->type());
750 this->write(skTemp2);
751 this->write(" = (select(");
752 this->write(skTemp1);
753 this->write(", ~");
754 this->write(skTemp1);
755 this->write(", ");
756 this->write(skTemp1);
757 this->write(" < 0)), ");
758 } else {
759 skTemp2 = skTemp1;
760 }
761
762 // ... select(int4(clz(_skTemp2)), int4(-1), _skTemp2 == int4(0)))
763 this->write("select(");
764 this->write(this->typeName(c.type()));
765 this->write("(clz(");
766 this->write(skTemp2);
767 this->write(")), ");
768 this->write(this->typeName(c.type()));
769 this->write("(-1), ");
770 this->write(skTemp2);
771 this->write(" == ");
772 this->write(exprType);
773 this->write("(0)))");
John Stiles496b7d12021-05-06 10:26:45 -0400774 return true;
John Stiles9685e522020-12-14 11:52:14 -0500775 }
John Stiles496b7d12021-05-06 10:26:45 -0400776 case k_matrixCompMult_IntrinsicKind: {
John Stilesd7199b22020-12-30 16:22:58 -0500777 this->writeMatrixCompMult();
778 this->writeSimpleIntrinsic(c);
John Stiles496b7d12021-05-06 10:26:45 -0400779 return true;
John Stilesd7199b22020-12-30 16:22:58 -0500780 }
John Stiles496b7d12021-05-06 10:26:45 -0400781 case k_equal_IntrinsicKind:
782 case k_greaterThan_IntrinsicKind:
783 case k_greaterThanEqual_IntrinsicKind:
784 case k_lessThan_IntrinsicKind:
785 case k_lessThanEqual_IntrinsicKind:
786 case k_notEqual_IntrinsicKind: {
John Stilesd7199b22020-12-30 16:22:58 -0500787 this->write("(");
Brian Osman00185012021-02-04 16:07:11 -0500788 this->writeExpression(*c.arguments()[0], Precedence::kRelational);
John Stilesd7199b22020-12-30 16:22:58 -0500789 switch (kind) {
John Stiles496b7d12021-05-06 10:26:45 -0400790 case k_equal_IntrinsicKind:
John Stilesd7199b22020-12-30 16:22:58 -0500791 this->write(" == ");
792 break;
John Stiles496b7d12021-05-06 10:26:45 -0400793 case k_notEqual_IntrinsicKind:
John Stilesd7199b22020-12-30 16:22:58 -0500794 this->write(" != ");
795 break;
John Stiles496b7d12021-05-06 10:26:45 -0400796 case k_lessThan_IntrinsicKind:
John Stilesd7199b22020-12-30 16:22:58 -0500797 this->write(" < ");
798 break;
John Stiles496b7d12021-05-06 10:26:45 -0400799 case k_lessThanEqual_IntrinsicKind:
John Stilesd7199b22020-12-30 16:22:58 -0500800 this->write(" <= ");
801 break;
John Stiles496b7d12021-05-06 10:26:45 -0400802 case k_greaterThan_IntrinsicKind:
John Stilesd7199b22020-12-30 16:22:58 -0500803 this->write(" > ");
804 break;
John Stiles496b7d12021-05-06 10:26:45 -0400805 case k_greaterThanEqual_IntrinsicKind:
John Stilesd7199b22020-12-30 16:22:58 -0500806 this->write(" >= ");
807 break;
808 default:
John Stilesf57207b2021-02-02 17:50:34 -0500809 SK_ABORT("unsupported comparison intrinsic kind");
John Stilesd7199b22020-12-30 16:22:58 -0500810 }
Brian Osman00185012021-02-04 16:07:11 -0500811 this->writeExpression(*c.arguments()[1], Precedence::kRelational);
John Stilesd7199b22020-12-30 16:22:58 -0500812 this->write(")");
John Stiles496b7d12021-05-06 10:26:45 -0400813 return true;
John Stilesd7199b22020-12-30 16:22:58 -0500814 }
Timothy Liang6403b0e2018-05-17 10:40:04 -0400815 default:
John Stiles496b7d12021-05-06 10:26:45 -0400816 return false;
Timothy Liang6403b0e2018-05-17 10:40:04 -0400817 }
818}
819
John Stilesfcf8cb22020-08-06 14:29:22 -0400820// Assembles a matrix of type floatRxC by resizing another matrix named `x0`.
821// Cells that don't exist in the source matrix will be populated with identity-matrix values.
822void MetalCodeGenerator::assembleMatrixFromMatrix(const Type& sourceMatrix, int rows, int columns) {
823 SkASSERT(rows <= 4);
824 SkASSERT(columns <= 4);
825
826 const char* columnSeparator = "";
827 for (int c = 0; c < columns; ++c) {
828 fExtraFunctions.printf("%sfloat%d(", columnSeparator, rows);
829 columnSeparator = "), ";
830
831 // Determine how many values to take from the source matrix for this row.
832 int swizzleLength = 0;
833 if (c < sourceMatrix.columns()) {
834 swizzleLength = std::min<>(rows, sourceMatrix.rows());
835 }
836
837 // Emit all the values from the source matrix row.
838 bool firstItem;
839 switch (swizzleLength) {
840 case 0: firstItem = true; break;
841 case 1: firstItem = false; fExtraFunctions.printf("x0[%d].x", c); break;
842 case 2: firstItem = false; fExtraFunctions.printf("x0[%d].xy", c); break;
843 case 3: firstItem = false; fExtraFunctions.printf("x0[%d].xyz", c); break;
844 case 4: firstItem = false; fExtraFunctions.printf("x0[%d].xyzw", c); break;
845 default: SkUNREACHABLE;
846 }
847
848 // Emit the placeholder identity-matrix cells.
849 for (int r = swizzleLength; r < rows; ++r) {
850 fExtraFunctions.printf("%s%s", firstItem ? "" : ", ", (r == c) ? "1.0" : "0.0");
851 firstItem = false;
852 }
853 }
854
855 fExtraFunctions.writeText(")");
856}
857
858// Assembles a matrix of type floatRxC by concatenating an arbitrary mix of values, named `x0`,
859// `x1`, etc. An error is written if the expression list don't contain exactly R*C scalars.
John Stiles5abb9e12021-04-06 13:47:19 -0400860void MetalCodeGenerator::assembleMatrixFromExpressions(const AnyConstructor& ctor,
John Stiles8e3b6be2020-10-13 11:14:08 -0400861 int rows, int columns) {
John Stilesfcf8cb22020-08-06 14:29:22 -0400862 size_t argIndex = 0;
863 int argPosition = 0;
John Stiles5abb9e12021-04-06 13:47:19 -0400864 auto args = ctor.argumentSpan();
John Stilesfcf8cb22020-08-06 14:29:22 -0400865
866 const char* columnSeparator = "";
867 for (int c = 0; c < columns; ++c) {
868 fExtraFunctions.printf("%sfloat%d(", columnSeparator, rows);
869 columnSeparator = "), ";
870
871 const char* rowSeparator = "";
872 for (int r = 0; r < rows; ++r) {
873 fExtraFunctions.writeText(rowSeparator);
874 rowSeparator = ", ";
875
876 if (argIndex < args.size()) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400877 const Type& argType = args[argIndex]->type();
Ethan Nicholase6592142020-09-08 10:22:09 -0400878 switch (argType.typeKind()) {
879 case Type::TypeKind::kScalar: {
John Stilesfcf8cb22020-08-06 14:29:22 -0400880 fExtraFunctions.printf("x%zu", argIndex);
881 break;
882 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400883 case Type::TypeKind::kVector: {
John Stilesfcf8cb22020-08-06 14:29:22 -0400884 fExtraFunctions.printf("x%zu[%d]", argIndex, argPosition);
885 break;
886 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400887 case Type::TypeKind::kMatrix: {
John Stilesfcf8cb22020-08-06 14:29:22 -0400888 fExtraFunctions.printf("x%zu[%d][%d]", argIndex,
889 argPosition / argType.rows(),
890 argPosition % argType.rows());
891 break;
892 }
893 default: {
894 SkDEBUGFAIL("incorrect type of argument for matrix constructor");
895 fExtraFunctions.writeText("<error>");
896 break;
897 }
898 }
899
900 ++argPosition;
901 if (argPosition >= argType.columns() * argType.rows()) {
902 ++argIndex;
903 argPosition = 0;
904 }
905 } else {
906 SkDEBUGFAIL("not enough arguments for matrix constructor");
907 fExtraFunctions.writeText("<error>");
908 }
909 }
910 }
911
912 if (argPosition != 0 || argIndex != args.size()) {
913 SkDEBUGFAIL("incorrect number of arguments for matrix constructor");
914 fExtraFunctions.writeText(", <error>");
915 }
916
917 fExtraFunctions.writeText(")");
918}
919
John Stiles1bdafbf2020-05-28 12:17:20 -0400920// Generates a constructor for 'matrix' which reorganizes the input arguments into the proper shape.
921// Keeps track of previously generated constructors so that we won't generate more than one
922// constructor for any given permutation of input argument types. Returns the name of the
923// generated constructor method.
John Stiles5abb9e12021-04-06 13:47:19 -0400924String MetalCodeGenerator::getMatrixConstructHelper(const AnyConstructor& c) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400925 const Type& matrix = c.type();
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500926 int columns = matrix.columns();
927 int rows = matrix.rows();
John Stiles5abb9e12021-04-06 13:47:19 -0400928 auto args = c.argumentSpan();
John Stiles1bdafbf2020-05-28 12:17:20 -0400929
930 // Create the helper-method name and use it as our lookup key.
931 String name;
932 name.appendf("float%dx%d_from", columns, rows);
933 for (const std::unique_ptr<Expression>& expr : args) {
John Stiles36129132020-12-29 12:28:04 -0500934 name.appendf("_%s", this->typeName(expr->type()).c_str());
John Stiles1bdafbf2020-05-28 12:17:20 -0400935 }
936
937 // If a helper-method has already been synthesized, we don't need to synthesize it again.
938 auto [iter, newlyCreated] = fHelpers.insert(name);
939 if (!newlyCreated) {
940 return name;
941 }
942
943 // Unlike GLSL, Metal requires that matrices are initialized with exactly R vectors of C
944 // components apiece. (In Metal 2.0, you can also supply R*C scalars, but you still cannot
945 // supply a mixture of scalars and vectors.)
946 fExtraFunctions.printf("float%dx%d %s(", columns, rows, name.c_str());
947
948 size_t argIndex = 0;
949 const char* argSeparator = "";
John Stilesfcf8cb22020-08-06 14:29:22 -0400950 for (const std::unique_ptr<Expression>& expr : args) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400951 fExtraFunctions.printf("%s%s x%zu", argSeparator,
John Stiles36129132020-12-29 12:28:04 -0500952 this->typeName(expr->type()).c_str(), argIndex++);
John Stiles1bdafbf2020-05-28 12:17:20 -0400953 argSeparator = ", ";
954 }
955
956 fExtraFunctions.printf(") {\n return float%dx%d(", columns, rows);
957
John Stiles9aeed132020-11-24 17:36:06 -0500958 if (args.size() == 1 && args.front()->type().isMatrix()) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400959 this->assembleMatrixFromMatrix(args.front()->type(), rows, columns);
John Stilesfcf8cb22020-08-06 14:29:22 -0400960 } else {
John Stiles5abb9e12021-04-06 13:47:19 -0400961 this->assembleMatrixFromExpressions(c, rows, columns);
John Stiles1bdafbf2020-05-28 12:17:20 -0400962 }
963
John Stilesfcf8cb22020-08-06 14:29:22 -0400964 fExtraFunctions.writeText(");\n}\n");
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500965 return name;
966}
967
968bool MetalCodeGenerator::canCoerce(const Type& t1, const Type& t2) {
969 if (t1.columns() != t2.columns() || t1.rows() != t2.rows()) {
970 return false;
971 }
972 if (t1.columns() > 1) {
973 return this->canCoerce(t1.componentType(), t2.componentType());
974 }
Ethan Nicholase1f55022019-02-05 17:17:40 -0500975 return t1.isFloat() && t2.isFloat();
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500976}
977
John Stiles8cad6372021-04-07 12:31:13 -0400978bool MetalCodeGenerator::matrixConstructHelperIsNeeded(const ConstructorCompound& c) {
John Stiles2bec8ab2021-04-06 18:40:04 -0400979 SkASSERT(c.type().isMatrix());
John Stiles1bdafbf2020-05-28 12:17:20 -0400980
981 // GLSL is fairly free-form about inputs to its matrix constructors, but Metal is not; it
982 // expects exactly R vectors of C components apiece. (Metal 2.0 also allows a list of R*C
983 // scalars.) Some cases are simple to translate and so we handle those inline--e.g. a list of
984 // scalars can be constructed trivially. In more complex cases, we generate a helper function
985 // that converts our inputs into a properly-shaped matrix.
986 // A matrix construct helper method is always used if any input argument is a matrix.
987 // Helper methods are also necessary when any argument would span multiple rows. For instance:
988 //
989 // float2 x = (1, 2);
990 // float3x2(x, 3, 4, 5, 6) = | 1 3 5 | = no helper needed; conversion can be done inline
991 // | 2 4 6 |
992 //
993 // float2 x = (2, 3);
994 // float3x2(1, x, 4, 5, 6) = | 1 3 5 | = x spans multiple rows; a helper method will be used
995 // | 2 4 6 |
996 //
997 // float4 x = (1, 2, 3, 4);
998 // float2x2(x) = | 1 3 | = x spans multiple rows; a helper method will be used
999 // | 2 4 |
1000 //
1001
1002 int position = 0;
Ethan Nicholasf70f0442020-09-29 12:41:35 -04001003 for (const std::unique_ptr<Expression>& expr : c.arguments()) {
John Stiles1bdafbf2020-05-28 12:17:20 -04001004 // If an input argument is a matrix, we need a helper function.
John Stiles9aeed132020-11-24 17:36:06 -05001005 if (expr->type().isMatrix()) {
John Stiles1bdafbf2020-05-28 12:17:20 -04001006 return true;
1007 }
Ethan Nicholas30d30222020-09-11 12:27:26 -04001008 position += expr->type().columns();
1009 if (position > c.type().rows()) {
John Stiles1bdafbf2020-05-28 12:17:20 -04001010 // An input argument would span multiple rows; a helper function is required.
1011 return true;
1012 }
Ethan Nicholas30d30222020-09-11 12:27:26 -04001013 if (position == c.type().rows()) {
John Stiles1bdafbf2020-05-28 12:17:20 -04001014 // We've advanced to the end of a row. Wrap to the start of the next row.
1015 position = 0;
1016 }
1017 }
1018
1019 return false;
1020}
1021
John Stiles5abb9e12021-04-06 13:47:19 -04001022void MetalCodeGenerator::writeConstructorMatrixResize(const ConstructorMatrixResize& c,
1023 Precedence parentPrecedence) {
1024 // Matrix-resize via casting doesn't natively exist in Metal at all, so we always need to use a
1025 // matrix-construct helper here.
1026 this->write(this->getMatrixConstructHelper(c));
1027 this->write("(");
1028 this->writeExpression(*c.argument(), Precedence::kSequence);
1029 this->write(")");
1030}
1031
John Stiles8cad6372021-04-07 12:31:13 -04001032void MetalCodeGenerator::writeConstructorCompound(const ConstructorCompound& c,
1033 Precedence parentPrecedence) {
John Stiles2bec8ab2021-04-06 18:40:04 -04001034 if (c.type().isMatrix()) {
John Stiles8cad6372021-04-07 12:31:13 -04001035 this->writeConstructorCompoundMatrix(c, parentPrecedence);
John Stiles2bec8ab2021-04-06 18:40:04 -04001036 } else {
1037 this->writeAnyConstructor(c, "(", ")", parentPrecedence);
1038 }
1039}
John Stiles7384b372021-04-01 13:48:15 -04001040
John Stiles8cad6372021-04-07 12:31:13 -04001041void MetalCodeGenerator::writeConstructorCompoundMatrix(const ConstructorCompound& c,
1042 Precedence parentPrecedence) {
John Stiles1bdafbf2020-05-28 12:17:20 -04001043 // Emit and invoke a matrix-constructor helper method if one is necessary.
1044 if (this->matrixConstructHelperIsNeeded(c)) {
1045 this->write(this->getMatrixConstructHelper(c));
John Stiles1fa15b12020-05-28 17:36:54 +00001046 this->write("(");
1047 const char* separator = "";
Ethan Nicholasf70f0442020-09-29 12:41:35 -04001048 for (const std::unique_ptr<Expression>& expr : c.arguments()) {
John Stiles1fa15b12020-05-28 17:36:54 +00001049 this->write(separator);
1050 separator = ", ";
Brian Osman00185012021-02-04 16:07:11 -05001051 this->writeExpression(*expr, Precedence::kSequence);
John Stilesdaa573e2020-05-28 12:17:20 -04001052 }
John Stiles1fa15b12020-05-28 17:36:54 +00001053 this->write(")");
John Stiles1bdafbf2020-05-28 12:17:20 -04001054 return;
John Stilesdaa573e2020-05-28 12:17:20 -04001055 }
John Stiles1bdafbf2020-05-28 12:17:20 -04001056
John Stiles2bec8ab2021-04-06 18:40:04 -04001057 // Metal doesn't allow creating matrices by passing in scalars and vectors in a jumble; it
1058 // requires your scalars to be grouped up into columns. Because `matrixConstructHelperIsNeeded`
1059 // returned false, we know that none of our scalars/vectors "wrap" across across a column, so we
1060 // can group our inputs up and synthesize a constructor for each column.
1061 const Type& matrixType = c.type();
1062 const Type& columnType = matrixType.componentType().toCompound(
1063 fContext, /*columns=*/matrixType.rows(), /*rows=*/1);
1064
1065 this->writeType(matrixType);
John Stiles7384b372021-04-01 13:48:15 -04001066 this->write("(");
John Stiles1bdafbf2020-05-28 12:17:20 -04001067 const char* separator = "";
1068 int scalarCount = 0;
Ethan Nicholasf70f0442020-09-29 12:41:35 -04001069 for (const std::unique_ptr<Expression>& arg : c.arguments()) {
John Stiles1bdafbf2020-05-28 12:17:20 -04001070 this->write(separator);
1071 separator = ", ";
John Stiles2bec8ab2021-04-06 18:40:04 -04001072 if (arg->type().columns() < matrixType.rows()) {
1073 // Write a `floatN(` constructor to group scalars and smaller vectors together.
John Stiles1bdafbf2020-05-28 12:17:20 -04001074 if (!scalarCount) {
John Stiles2bec8ab2021-04-06 18:40:04 -04001075 this->writeType(columnType);
John Stiles1bdafbf2020-05-28 12:17:20 -04001076 this->write("(");
1077 }
John Stiles2bec8ab2021-04-06 18:40:04 -04001078 scalarCount += arg->type().columns();
John Stiles1bdafbf2020-05-28 12:17:20 -04001079 }
Brian Osman00185012021-02-04 16:07:11 -05001080 this->writeExpression(*arg, Precedence::kSequence);
John Stiles2bec8ab2021-04-06 18:40:04 -04001081 if (scalarCount && scalarCount == matrixType.rows()) {
1082 // Close our `floatN(...` constructor block from above.
John Stiles1bdafbf2020-05-28 12:17:20 -04001083 this->write(")");
1084 scalarCount = 0;
1085 }
1086 }
John Stiles7384b372021-04-01 13:48:15 -04001087 this->write(")");
Ethan Nicholascc305772017-10-13 16:17:45 -04001088}
1089
John Stilesb14a8192021-04-05 11:40:46 -04001090void MetalCodeGenerator::writeAnyConstructor(const AnyConstructor& c,
1091 const char* leftBracket,
1092 const char* rightBracket,
1093 Precedence parentPrecedence) {
John Stilese1182782021-03-30 22:09:37 -04001094 this->writeType(c.type());
John Stilesb14a8192021-04-05 11:40:46 -04001095 this->write(leftBracket);
John Stiles7384b372021-04-01 13:48:15 -04001096 const char* separator = "";
John Stilesb14a8192021-04-05 11:40:46 -04001097 for (const std::unique_ptr<Expression>& arg : c.argumentSpan()) {
John Stiles7384b372021-04-01 13:48:15 -04001098 this->write(separator);
1099 separator = ", ";
1100 this->writeExpression(*arg, Precedence::kSequence);
1101 }
John Stilesb14a8192021-04-05 11:40:46 -04001102 this->write(rightBracket);
John Stiles7384b372021-04-01 13:48:15 -04001103}
1104
John Stilesb14a8192021-04-05 11:40:46 -04001105void MetalCodeGenerator::writeCastConstructor(const AnyConstructor& c,
1106 const char* leftBracket,
1107 const char* rightBracket,
1108 Precedence parentPrecedence) {
1109 // If the type is coercible, emit it directly without the cast.
1110 auto args = c.argumentSpan();
1111 if (args.size() == 1) {
1112 if (this->canCoerce(c.type(), args.front()->type())) {
1113 this->writeExpression(*args.front(), parentPrecedence);
1114 return;
1115 }
John Stilesfd7252f2021-04-04 22:24:40 -04001116 }
1117
John Stilesb14a8192021-04-05 11:40:46 -04001118 return this->writeAnyConstructor(c, leftBracket, rightBracket, parentPrecedence);
John Stilesfd7252f2021-04-04 22:24:40 -04001119}
1120
Ethan Nicholascc305772017-10-13 16:17:45 -04001121void MetalCodeGenerator::writeFragCoord() {
Ethan Nicholasf931e402019-07-26 15:40:33 -04001122 if (fRTHeightName.length()) {
1123 this->write("float4(_fragCoord.x, ");
1124 this->write(fRTHeightName.c_str());
1125 this->write(" - _fragCoord.y, 0.0, _fragCoord.w)");
Jim Van Verth6bc650e2019-02-07 14:53:23 -05001126 } else {
1127 this->write("float4(_fragCoord.x, _fragCoord.y, 0.0, _fragCoord.w)");
1128 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001129}
1130
1131void MetalCodeGenerator::writeVariableReference(const VariableReference& ref) {
John Stiles06b84ef2020-12-09 12:35:48 -05001132 // When assembling out-param helper functions, we copy variables into local clones with matching
John Stilesf7410bd2021-01-19 13:07:55 -05001133 // names. We never want to prepend "_in." or "_globals." when writing these variables since
John Stiles06b84ef2020-12-09 12:35:48 -05001134 // we're actually targeting the clones.
1135 if (fIgnoreVariableReferenceModifiers) {
1136 this->writeName(ref.variable()->name());
1137 return;
1138 }
1139
Ethan Nicholas78686922020-10-08 06:46:27 -04001140 switch (ref.variable()->modifiers().fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001141 case SK_FRAGCOLOR_BUILTIN:
John Stilesf7410bd2021-01-19 13:07:55 -05001142 this->write("_out.sk_FragColor");
Ethan Nicholascc305772017-10-13 16:17:45 -04001143 break;
Timothy Liang6403b0e2018-05-17 10:40:04 -04001144 case SK_FRAGCOORD_BUILTIN:
1145 this->writeFragCoord();
1146 break;
Timothy Liangdc89f192018-06-13 09:20:31 -04001147 case SK_VERTEXID_BUILTIN:
1148 this->write("sk_VertexID");
1149 break;
1150 case SK_INSTANCEID_BUILTIN:
1151 this->write("sk_InstanceID");
1152 break;
Timothy Liang7b8875d2018-08-10 09:42:31 -04001153 case SK_CLOCKWISE_BUILTIN:
1154 // We'd set the front facing winding in the MTLRenderCommandEncoder to be counter
Brian Salomonf4ba4ec2020-03-19 15:54:28 -04001155 // clockwise to match Skia convention.
John Stiles270cec22021-02-17 12:59:36 -05001156 this->write(fProgram.fConfig->fSettings.fFlipY ? "_frontFacing" : "(!_frontFacing)");
Timothy Liang7b8875d2018-08-10 09:42:31 -04001157 break;
Ethan Nicholascc305772017-10-13 16:17:45 -04001158 default:
Ethan Nicholas78686922020-10-08 06:46:27 -04001159 const Variable& var = *ref.variable();
Ethan Nicholas453f67f2020-10-09 10:43:45 -04001160 if (var.storage() == Variable::Storage::kGlobal) {
Ethan Nicholas78686922020-10-08 06:46:27 -04001161 if (var.modifiers().fFlags & Modifiers::kIn_Flag) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001162 this->write("_in.");
Ethan Nicholas78686922020-10-08 06:46:27 -04001163 } else if (var.modifiers().fFlags & Modifiers::kOut_Flag) {
John Stilesf7410bd2021-01-19 13:07:55 -05001164 this->write("_out.");
Ethan Nicholas78686922020-10-08 06:46:27 -04001165 } else if (var.modifiers().fFlags & Modifiers::kUniform_Flag &&
1166 var.type().typeKind() != Type::TypeKind::kSampler) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001167 this->write("_uniforms.");
1168 } else {
John Stilesf7410bd2021-01-19 13:07:55 -05001169 this->write("_globals.");
Ethan Nicholascc305772017-10-13 16:17:45 -04001170 }
1171 }
Ethan Nicholas78686922020-10-08 06:46:27 -04001172 this->writeName(var.name());
Ethan Nicholascc305772017-10-13 16:17:45 -04001173 }
1174}
1175
1176void MetalCodeGenerator::writeIndexExpression(const IndexExpression& expr) {
Brian Osman00185012021-02-04 16:07:11 -05001177 this->writeExpression(*expr.base(), Precedence::kPostfix);
Ethan Nicholascc305772017-10-13 16:17:45 -04001178 this->write("[");
Brian Osman00185012021-02-04 16:07:11 -05001179 this->writeExpression(*expr.index(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001180 this->write("]");
1181}
1182
1183void MetalCodeGenerator::writeFieldAccess(const FieldAccess& f) {
Ethan Nicholas7a95b202020-10-09 11:55:40 -04001184 const Type::Field* field = &f.base()->type().fields()[f.fieldIndex()];
1185 if (FieldAccess::OwnerKind::kDefault == f.ownerKind()) {
Brian Osman00185012021-02-04 16:07:11 -05001186 this->writeExpression(*f.base(), Precedence::kPostfix);
Ethan Nicholascc305772017-10-13 16:17:45 -04001187 this->write(".");
1188 }
Timothy Liang7d637782018-06-05 09:58:07 -04001189 switch (field->fModifiers.fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001190 case SK_POSITION_BUILTIN:
John Stilesf7410bd2021-01-19 13:07:55 -05001191 this->write("_out.sk_Position");
Ethan Nicholascc305772017-10-13 16:17:45 -04001192 break;
1193 default:
Timothy Liang7d637782018-06-05 09:58:07 -04001194 if (field->fName == "sk_PointSize") {
John Stilesf7410bd2021-01-19 13:07:55 -05001195 this->write("_out.sk_PointSize");
Timothy Liang7d637782018-06-05 09:58:07 -04001196 } else {
Ethan Nicholas7a95b202020-10-09 11:55:40 -04001197 if (FieldAccess::OwnerKind::kAnonymousInterfaceBlock == f.ownerKind()) {
John Stilesf7410bd2021-01-19 13:07:55 -05001198 this->write("_globals.");
Timothy Liang7d637782018-06-05 09:58:07 -04001199 this->write(fInterfaceBlockNameMap[fInterfaceBlockMap[field]]);
1200 this->write("->");
1201 }
Timothy Liang651286f2018-06-07 09:55:33 -04001202 this->writeName(field->fName);
Timothy Lianga06f2152018-05-24 15:33:31 -04001203 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001204 }
1205}
1206
1207void MetalCodeGenerator::writeSwizzle(const Swizzle& swizzle) {
Brian Osman00185012021-02-04 16:07:11 -05001208 this->writeExpression(*swizzle.base(), Precedence::kPostfix);
Ethan Nicholascc305772017-10-13 16:17:45 -04001209 this->write(".");
Ethan Nicholas6b4d5812020-10-12 16:11:51 -04001210 for (int c : swizzle.components()) {
Brian Osman25647672020-09-15 15:16:56 -04001211 SkASSERT(c >= 0 && c <= 3);
1212 this->write(&("x\0y\0z\0w\0"[c * 2]));
Ethan Nicholascc305772017-10-13 16:17:45 -04001213 }
1214}
1215
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001216void MetalCodeGenerator::writeMatrixTimesEqualHelper(const Type& left, const Type& right,
1217 const Type& result) {
John Stiles39346472021-04-29 14:39:35 -04001218 String key = "TimesEqual " + this->typeName(left) + ":" + this->typeName(right);
John Stiles56233d12021-02-03 13:03:29 -05001219
1220 auto [iter, wasInserted] = fHelpers.insert(key);
1221 if (wasInserted) {
John Stiles368db7c2020-12-29 11:20:08 -05001222 fExtraFunctions.printf("thread %s& operator*=(thread %s& left, thread const %s& right) {\n"
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001223 " left = left * right;\n"
1224 " return left;\n"
John Stiles368db7c2020-12-29 11:20:08 -05001225 "}\n",
1226 this->typeName(result).c_str(), this->typeName(left).c_str(),
1227 this->typeName(right).c_str());
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001228 }
1229}
1230
John Stiles39346472021-04-29 14:39:35 -04001231void MetalCodeGenerator::writeMatrixEqualityHelpers(const Type& left, const Type& right) {
1232 SkASSERT(left.isMatrix());
1233 SkASSERT(right.isMatrix());
1234 SkASSERT(left.rows() == right.rows());
1235 SkASSERT(left.columns() == right.columns());
John Stiles01cdf012021-02-10 09:53:41 -05001236
John Stiles39346472021-04-29 14:39:35 -04001237 String key = "MatrixEquality " + this->typeName(left) + ":" + this->typeName(right);
John Stiles01cdf012021-02-10 09:53:41 -05001238
1239 auto [iter, wasInserted] = fHelpers.insert(key);
1240 if (wasInserted) {
1241 fExtraFunctions.printf(
1242 "thread bool operator==(const %s left, const %s right) {\n"
John Stiles39346472021-04-29 14:39:35 -04001243 " return ",
John Stiles01cdf012021-02-10 09:53:41 -05001244 this->typeName(left).c_str(), this->typeName(right).c_str());
1245
John Stiles39346472021-04-29 14:39:35 -04001246 const char* separator = "";
John Stiles01cdf012021-02-10 09:53:41 -05001247 for (int index=0; index<left.columns(); ++index) {
John Stiles39346472021-04-29 14:39:35 -04001248 fExtraFunctions.printf("%sall(left[%d] == right[%d])", separator, index, index);
1249 separator = " &&\n ";
John Stiles01cdf012021-02-10 09:53:41 -05001250 }
John Stiles39346472021-04-29 14:39:35 -04001251
1252 fExtraFunctions.printf(
1253 ";\n"
1254 "}\n"
1255 "thread bool operator!=(const %s left, const %s right) {\n"
1256 " return !(left == right);\n"
1257 "}\n",
1258 this->typeName(left).c_str(), this->typeName(right).c_str());
John Stiles01cdf012021-02-10 09:53:41 -05001259 }
1260}
1261
John Stiles39346472021-04-29 14:39:35 -04001262void MetalCodeGenerator::writeArrayEqualityHelpers(const Type& type) {
1263 SkASSERT(type.isArray());
John Stiles01cdf012021-02-10 09:53:41 -05001264
John Stiles39346472021-04-29 14:39:35 -04001265 // If the array's component type needs a helper as well, we need to emit that one first.
1266 this->writeEqualityHelpers(type.componentType(), type.componentType());
1267
1268 auto [iter, wasInserted] = fHelpers.insert("ArrayEquality []");
1269 if (wasInserted) {
1270 fExtraFunctions.writeText(R"(
1271template <typename T, size_t N>
1272bool operator==(thread const array<T, N>& left, thread const array<T, N>& right) {
1273 for (size_t index = 0; index < N; ++index) {
1274 if (!(left[index] == right[index])) {
1275 return false;
1276 }
1277 }
1278 return true;
1279}
1280
1281template <typename T, size_t N>
1282bool operator!=(thread const array<T, N>& left, thread const array<T, N>& right) {
1283 return !(left == right);
1284}
1285)");
1286 }
1287}
1288
1289void MetalCodeGenerator::writeStructEqualityHelpers(const Type& type) {
1290 SkASSERT(type.isStruct());
1291 String key = "StructEquality " + this->typeName(type);
John Stiles01cdf012021-02-10 09:53:41 -05001292
1293 auto [iter, wasInserted] = fHelpers.insert(key);
1294 if (wasInserted) {
John Stiles39346472021-04-29 14:39:35 -04001295 // If one of the struct's fields needs a helper as well, we need to emit that one first.
1296 for (const Type::Field& field : type.fields()) {
1297 this->writeEqualityHelpers(*field.fType, *field.fType);
John Stiles830c69c2021-04-28 17:16:16 -04001298 }
John Stiles39346472021-04-29 14:39:35 -04001299
1300 // Write operator== and operator!= for this struct, since those are assumed to exist in SkSL
1301 // and GLSL but do not exist by default in Metal.
1302 fExtraFunctions.printf(
1303 "thread bool operator==(thread const %s& left, thread const %s& right) {\n"
1304 " return ",
1305 this->typeName(type).c_str(),
1306 this->typeName(type).c_str());
1307
1308 const char* separator = "";
1309 for (const Type::Field& field : type.fields()) {
1310 fExtraFunctions.printf("%s(left.%.*s == right.%.*s)",
1311 separator,
1312 (int)field.fName.size(), field.fName.data(),
1313 (int)field.fName.size(), field.fName.data());
1314 separator = " &&\n ";
1315 }
1316 fExtraFunctions.printf(
1317 ";\n"
1318 "}\n"
1319 "thread bool operator!=(thread const %s& left, thread const %s& right) {\n"
1320 " return !(left == right);\n"
1321 "}\n",
1322 this->typeName(type).c_str(),
1323 this->typeName(type).c_str());
1324 }
1325}
1326
1327void MetalCodeGenerator::writeEqualityHelpers(const Type& leftType, const Type& rightType) {
1328 if (leftType.isArray() && rightType.isArray()) {
1329 this->writeArrayEqualityHelpers(leftType);
1330 return;
1331 }
1332 if (leftType.isStruct() && rightType.isStruct()) {
1333 this->writeStructEqualityHelpers(leftType);
1334 return;
1335 }
1336 if (leftType.isMatrix() && rightType.isMatrix()) {
1337 this->writeMatrixEqualityHelpers(leftType, rightType);
1338 return;
John Stiles01cdf012021-02-10 09:53:41 -05001339 }
1340}
1341
John Stiles6b131292021-05-12 17:12:21 -04001342void MetalCodeGenerator::writeNumberAsMatrix(const Expression& expr, const Type& matrixType) {
1343 SkASSERT(expr.type().isNumber());
1344 SkASSERT(matrixType.isMatrix());
1345
1346 // Componentwise multiply the scalar against a matrix of the desired size which contains all 1s.
1347 this->write("(");
1348 this->writeType(matrixType);
1349 this->write("(");
1350
1351 const char* separator = "";
1352 for (int index = matrixType.slotCount(); index--;) {
1353 this->write(separator);
1354 this->write("1.0");
1355 separator = ", ";
1356 }
1357
1358 this->write(") * ");
1359 this->writeExpression(expr, Precedence::kMultiplicative);
1360 this->write(")");
1361}
1362
Ethan Nicholascc305772017-10-13 16:17:45 -04001363void MetalCodeGenerator::writeBinaryExpression(const BinaryExpression& b,
1364 Precedence parentPrecedence) {
John Stiles2d4f9592020-10-30 10:29:12 -04001365 const Expression& left = *b.left();
1366 const Expression& right = *b.right();
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001367 const Type& leftType = left.type();
1368 const Type& rightType = right.type();
John Stiles45990502021-02-16 10:55:27 -05001369 Operator op = b.getOperator();
1370 Precedence precedence = op.getBinaryPrecedence();
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001371 bool needParens = precedence >= parentPrecedence;
John Stiles45990502021-02-16 10:55:27 -05001372 switch (op.kind()) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001373 case Token::Kind::TK_EQEQ:
John Stiles39346472021-04-29 14:39:35 -04001374 this->writeEqualityHelpers(leftType, rightType);
John Stiles9aeed132020-11-24 17:36:06 -05001375 if (leftType.isVector()) {
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001376 this->write("all");
1377 needParens = true;
1378 }
1379 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001380 case Token::Kind::TK_NEQ:
John Stiles39346472021-04-29 14:39:35 -04001381 this->writeEqualityHelpers(leftType, rightType);
John Stiles9aeed132020-11-24 17:36:06 -05001382 if (leftType.isVector()) {
Jim Van Verth36477b42019-04-11 14:57:30 -04001383 this->write("any");
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001384 needParens = true;
1385 }
1386 break;
1387 default:
1388 break;
1389 }
1390 if (needParens) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001391 this->write("(");
1392 }
John Stiles39346472021-04-29 14:39:35 -04001393 if (leftType.isMatrix() && rightType.isMatrix() && op.kind() == Token::Kind::TK_STAREQ) {
1394 this->writeMatrixTimesEqualHelper(leftType, rightType, b.type());
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001395 }
John Stiles6b131292021-05-12 17:12:21 -04001396
1397 bool needMatrixSplatOnScalar = rightType.isMatrix() && leftType.isScalar() &&
1398 op.removeAssignment().kind() != Token::Kind::TK_STAR;
1399 if (needMatrixSplatOnScalar) {
1400 this->writeNumberAsMatrix(left, rightType);
1401 } else {
1402 this->writeExpression(left, precedence);
1403 }
John Stiles45990502021-02-16 10:55:27 -05001404 if (op.kind() != Token::Kind::TK_EQ && op.isAssignment() &&
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001405 left.kind() == Expression::Kind::kSwizzle && !left.hasSideEffects()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001406 // This doesn't compile in Metal:
1407 // float4 x = float4(1);
1408 // x.xy *= float2x2(...);
1409 // with the error message "non-const reference cannot bind to vector element",
1410 // but switching it to x.xy = x.xy * float2x2(...) fixes it. We perform this tranformation
1411 // as long as the LHS has no side effects, and hope for the best otherwise.
1412 this->write(" = ");
Brian Osman00185012021-02-04 16:07:11 -05001413 this->writeExpression(left, Precedence::kAssignment);
Ethan Nicholascc305772017-10-13 16:17:45 -04001414 this->write(" ");
John Stilesd6449e92020-11-30 09:13:23 -05001415 String opName = OperatorName(op);
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001416 SkASSERT(opName.endsWith("="));
1417 this->write(opName.substr(0, opName.size() - 1).c_str());
Ethan Nicholascc305772017-10-13 16:17:45 -04001418 this->write(" ");
1419 } else {
John Stilesd6449e92020-11-30 09:13:23 -05001420 this->write(String(" ") + OperatorName(op) + " ");
Ethan Nicholascc305772017-10-13 16:17:45 -04001421 }
John Stiles6b131292021-05-12 17:12:21 -04001422
1423 needMatrixSplatOnScalar = leftType.isMatrix() && rightType.isScalar() &&
1424 op.removeAssignment().kind() != Token::Kind::TK_STAR;
1425 if (needMatrixSplatOnScalar) {
1426 this->writeNumberAsMatrix(right, leftType);
1427 } else {
1428 this->writeExpression(right, precedence);
1429 }
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001430 if (needParens) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001431 this->write(")");
1432 }
1433}
1434
1435void MetalCodeGenerator::writeTernaryExpression(const TernaryExpression& t,
1436 Precedence parentPrecedence) {
Brian Osman00185012021-02-04 16:07:11 -05001437 if (Precedence::kTernary >= parentPrecedence) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001438 this->write("(");
1439 }
Brian Osman00185012021-02-04 16:07:11 -05001440 this->writeExpression(*t.test(), Precedence::kTernary);
Ethan Nicholascc305772017-10-13 16:17:45 -04001441 this->write(" ? ");
Brian Osman00185012021-02-04 16:07:11 -05001442 this->writeExpression(*t.ifTrue(), Precedence::kTernary);
Ethan Nicholascc305772017-10-13 16:17:45 -04001443 this->write(" : ");
Brian Osman00185012021-02-04 16:07:11 -05001444 this->writeExpression(*t.ifFalse(), Precedence::kTernary);
1445 if (Precedence::kTernary >= parentPrecedence) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001446 this->write(")");
1447 }
1448}
1449
1450void MetalCodeGenerator::writePrefixExpression(const PrefixExpression& p,
1451 Precedence parentPrecedence) {
Brian Osman00185012021-02-04 16:07:11 -05001452 if (Precedence::kPrefix >= parentPrecedence) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001453 this->write("(");
1454 }
John Stilesd6449e92020-11-30 09:13:23 -05001455 this->write(OperatorName(p.getOperator()));
Brian Osman00185012021-02-04 16:07:11 -05001456 this->writeExpression(*p.operand(), Precedence::kPrefix);
1457 if (Precedence::kPrefix >= parentPrecedence) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001458 this->write(")");
1459 }
1460}
1461
1462void MetalCodeGenerator::writePostfixExpression(const PostfixExpression& p,
1463 Precedence parentPrecedence) {
Brian Osman00185012021-02-04 16:07:11 -05001464 if (Precedence::kPostfix >= parentPrecedence) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001465 this->write("(");
1466 }
Brian Osman00185012021-02-04 16:07:11 -05001467 this->writeExpression(*p.operand(), Precedence::kPostfix);
John Stilesd6449e92020-11-30 09:13:23 -05001468 this->write(OperatorName(p.getOperator()));
Brian Osman00185012021-02-04 16:07:11 -05001469 if (Precedence::kPostfix >= parentPrecedence) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001470 this->write(")");
1471 }
1472}
1473
1474void MetalCodeGenerator::writeBoolLiteral(const BoolLiteral& b) {
Ethan Nicholas59d660c2020-09-28 09:18:15 -04001475 this->write(b.value() ? "true" : "false");
Ethan Nicholascc305772017-10-13 16:17:45 -04001476}
1477
1478void MetalCodeGenerator::writeIntLiteral(const IntLiteral& i) {
John Stiles12739df2020-12-29 09:47:20 -05001479 const Type& type = i.type();
John Stiles54e7c052021-01-11 14:22:36 -05001480 if (type == *fContext.fTypes.fUInt) {
Ethan Nicholase96cdd12020-09-28 16:27:18 -04001481 this->write(to_string(i.value() & 0xffffffff) + "u");
John Stiles54e7c052021-01-11 14:22:36 -05001482 } else if (type == *fContext.fTypes.fUShort) {
John Stiles12739df2020-12-29 09:47:20 -05001483 this->write(to_string(i.value() & 0xffff) + "u");
Ethan Nicholascc305772017-10-13 16:17:45 -04001484 } else {
John Stiles12739df2020-12-29 09:47:20 -05001485 this->write(to_string(i.value()));
Ethan Nicholascc305772017-10-13 16:17:45 -04001486 }
1487}
1488
1489void MetalCodeGenerator::writeFloatLiteral(const FloatLiteral& f) {
Ethan Nicholasa3f22f12020-10-01 12:13:17 -04001490 this->write(to_string(f.value()));
Ethan Nicholascc305772017-10-13 16:17:45 -04001491}
1492
1493void MetalCodeGenerator::writeSetting(const Setting& s) {
John Stilesf57207b2021-02-02 17:50:34 -05001494 SK_ABORT("internal error; setting was not folded to a constant during compilation\n");
Ethan Nicholascc305772017-10-13 16:17:45 -04001495}
1496
John Stiles06b84ef2020-12-09 12:35:48 -05001497void MetalCodeGenerator::writeFunctionRequirementArgs(const FunctionDeclaration& f,
1498 const char*& separator) {
1499 Requirements requirements = this->requirements(f);
1500 if (requirements & kInputs_Requirement) {
1501 this->write(separator);
1502 this->write("_in");
1503 separator = ", ";
1504 }
1505 if (requirements & kOutputs_Requirement) {
1506 this->write(separator);
1507 this->write("_out");
1508 separator = ", ";
1509 }
1510 if (requirements & kUniforms_Requirement) {
1511 this->write(separator);
1512 this->write("_uniforms");
1513 separator = ", ";
1514 }
1515 if (requirements & kGlobals_Requirement) {
1516 this->write(separator);
John Stilesf7410bd2021-01-19 13:07:55 -05001517 this->write("_globals");
John Stiles06b84ef2020-12-09 12:35:48 -05001518 separator = ", ";
1519 }
1520 if (requirements & kFragCoord_Requirement) {
1521 this->write(separator);
1522 this->write("_fragCoord");
1523 separator = ", ";
1524 }
1525}
1526
1527void MetalCodeGenerator::writeFunctionRequirementParams(const FunctionDeclaration& f,
1528 const char*& separator) {
1529 Requirements requirements = this->requirements(f);
1530 if (requirements & kInputs_Requirement) {
1531 this->write(separator);
1532 this->write("Inputs _in");
1533 separator = ", ";
1534 }
1535 if (requirements & kOutputs_Requirement) {
1536 this->write(separator);
John Stilesf7410bd2021-01-19 13:07:55 -05001537 this->write("thread Outputs& _out");
John Stiles06b84ef2020-12-09 12:35:48 -05001538 separator = ", ";
1539 }
1540 if (requirements & kUniforms_Requirement) {
1541 this->write(separator);
1542 this->write("Uniforms _uniforms");
1543 separator = ", ";
1544 }
1545 if (requirements & kGlobals_Requirement) {
1546 this->write(separator);
John Stilesf7410bd2021-01-19 13:07:55 -05001547 this->write("thread Globals& _globals");
John Stiles06b84ef2020-12-09 12:35:48 -05001548 separator = ", ";
1549 }
1550 if (requirements & kFragCoord_Requirement) {
1551 this->write(separator);
1552 this->write("float4 _fragCoord");
1553 separator = ", ";
1554 }
1555}
1556
John Stilesda5cdf62021-01-28 11:47:29 -05001557int MetalCodeGenerator::getUniformBinding(const Modifiers& m) {
1558 return (m.fLayout.fBinding >= 0) ? m.fLayout.fBinding
John Stiles270cec22021-02-17 12:59:36 -05001559 : fProgram.fConfig->fSettings.fDefaultUniformBinding;
John Stilesda5cdf62021-01-28 11:47:29 -05001560}
1561
1562int MetalCodeGenerator::getUniformSet(const Modifiers& m) {
1563 return (m.fLayout.fSet >= 0) ? m.fLayout.fSet
John Stiles270cec22021-02-17 12:59:36 -05001564 : fProgram.fConfig->fSettings.fDefaultUniformSet;
John Stilesda5cdf62021-01-28 11:47:29 -05001565}
1566
John Stiles569249b2020-11-03 12:18:22 -05001567bool MetalCodeGenerator::writeFunctionDeclaration(const FunctionDeclaration& f) {
John Stilesf7410bd2021-01-19 13:07:55 -05001568 fRTHeightName = fProgram.fInputs.fRTHeight ? "_globals._anonInterface0->u_skRTHeight" : "";
Ethan Nicholascc305772017-10-13 16:17:45 -04001569 const char* separator = "";
John Stilese8da4d22021-03-24 09:19:45 -04001570 if (f.isMain()) {
John Stiles270cec22021-02-17 12:59:36 -05001571 switch (fProgram.fConfig->fKind) {
John Stilesdbd4e6f2021-02-16 13:29:15 -05001572 case ProgramKind::kFragment:
Timothy Liangb8eeb802018-07-23 16:46:16 -04001573 this->write("fragment Outputs fragmentMain");
Ethan Nicholascc305772017-10-13 16:17:45 -04001574 break;
John Stilesdbd4e6f2021-02-16 13:29:15 -05001575 case ProgramKind::kVertex:
Timothy Liangb8eeb802018-07-23 16:46:16 -04001576 this->write("vertex Outputs vertexMain");
Ethan Nicholascc305772017-10-13 16:17:45 -04001577 break;
1578 default:
John Stiles3fabfc02020-09-25 15:51:28 -04001579 fErrors.error(-1, "unsupported kind of program");
John Stiles569249b2020-11-03 12:18:22 -05001580 return false;
Ethan Nicholascc305772017-10-13 16:17:45 -04001581 }
1582 this->write("(Inputs _in [[stage_in]]");
1583 if (-1 != fUniformBuffer) {
1584 this->write(", constant Uniforms& _uniforms [[buffer(" +
1585 to_string(fUniformBuffer) + ")]]");
1586 }
Brian Osman133724c2020-10-28 14:14:39 -04001587 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04001588 if (e->is<GlobalVarDeclaration>()) {
1589 const GlobalVarDeclaration& decls = e->as<GlobalVarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001590 const VarDeclaration& var = decls.declaration()->as<VarDeclaration>();
1591 if (var.var().type().typeKind() == Type::TypeKind::kSampler) {
1592 if (var.var().modifiers().fLayout.fBinding < 0) {
Brian Osmanc0213602020-10-06 14:43:32 -04001593 fErrors.error(decls.fOffset,
John Stilesb41d5bb2021-01-26 16:28:12 -05001594 "Metal samplers must have 'layout(binding=...)'");
John Stiles569249b2020-11-03 12:18:22 -05001595 return false;
Timothy Liangee84fe12018-05-18 14:38:19 -04001596 }
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001597 if (var.var().type().dimensions() != SpvDim2D) {
John Stiles569249b2020-11-03 12:18:22 -05001598 // Not yet implemented--Skia currently only uses 2D textures.
Brian Osmanc0213602020-10-06 14:43:32 -04001599 fErrors.error(decls.fOffset, "Unsupported texture dimensions");
John Stiles569249b2020-11-03 12:18:22 -05001600 return false;
Brian Osmanc0213602020-10-06 14:43:32 -04001601 }
1602 this->write(", texture2d<float> ");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001603 this->writeName(var.var().name());
Brian Osmanc0213602020-10-06 14:43:32 -04001604 this->write("[[texture(");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001605 this->write(to_string(var.var().modifiers().fLayout.fBinding));
Brian Osmanc0213602020-10-06 14:43:32 -04001606 this->write(")]]");
1607 this->write(", sampler ");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001608 this->writeName(var.var().name());
Brian Osmanc0213602020-10-06 14:43:32 -04001609 this->write(SAMPLER_SUFFIX);
1610 this->write("[[sampler(");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001611 this->write(to_string(var.var().modifiers().fLayout.fBinding));
Brian Osmanc0213602020-10-06 14:43:32 -04001612 this->write(")]]");
Timothy Liang6403b0e2018-05-17 10:40:04 -04001613 }
Brian Osman1179fcf2020-10-08 16:04:40 -04001614 } else if (e->is<InterfaceBlock>()) {
1615 const InterfaceBlock& intf = e->as<InterfaceBlock>();
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001616 if (intf.typeName() == "sk_PerVertex") {
Timothy Lianga06f2152018-05-24 15:33:31 -04001617 continue;
1618 }
1619 this->write(", constant ");
John Stilesb4418502021-02-04 10:57:08 -05001620 this->writeType(intf.variable().type());
Timothy Lianga06f2152018-05-24 15:33:31 -04001621 this->write("& " );
1622 this->write(fInterfaceBlockNameMap[&intf]);
1623 this->write(" [[buffer(");
John Stilesda5cdf62021-01-28 11:47:29 -05001624 this->write(to_string(this->getUniformBinding(intf.variable().modifiers())));
Timothy Lianga06f2152018-05-24 15:33:31 -04001625 this->write(")]]");
Timothy Liang6403b0e2018-05-17 10:40:04 -04001626 }
1627 }
John Stiles270cec22021-02-17 12:59:36 -05001628 if (fProgram.fConfig->fKind == ProgramKind::kFragment) {
Jim Van Verth6bc650e2019-02-07 14:53:23 -05001629 if (fProgram.fInputs.fRTHeight && fInterfaceBlockNameMap.empty()) {
Timothy Liang5422f9a2018-08-10 10:57:55 -04001630 this->write(", constant sksl_synthetic_uniforms& _anonInterface0 [[buffer(1)]]");
Ethan Nicholasf931e402019-07-26 15:40:33 -04001631 fRTHeightName = "_anonInterface0.u_skRTHeight";
Timothy Liang5422f9a2018-08-10 10:57:55 -04001632 }
Timothy Liang7b8875d2018-08-10 09:42:31 -04001633 this->write(", bool _frontFacing [[front_facing]]");
Timothy Liang7d637782018-06-05 09:58:07 -04001634 this->write(", float4 _fragCoord [[position]]");
John Stiles270cec22021-02-17 12:59:36 -05001635 } else if (fProgram.fConfig->fKind == ProgramKind::kVertex) {
Timothy Liangdc89f192018-06-13 09:20:31 -04001636 this->write(", uint sk_VertexID [[vertex_id]], uint sk_InstanceID [[instance_id]]");
Timothy Liang7d637782018-06-05 09:58:07 -04001637 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001638 separator = ", ";
1639 } else {
John Stilesb4418502021-02-04 10:57:08 -05001640 this->writeType(f.returnType());
Timothy Liang651286f2018-06-07 09:55:33 -04001641 this->write(" ");
John Stilese1068342021-03-22 11:57:41 -04001642 this->writeName(f.mangledName());
Timothy Liang651286f2018-06-07 09:55:33 -04001643 this->write("(");
John Stiles06b84ef2020-12-09 12:35:48 -05001644 this->writeFunctionRequirementParams(f, separator);
Ethan Nicholascc305772017-10-13 16:17:45 -04001645 }
John Stiles569249b2020-11-03 12:18:22 -05001646 for (const auto& param : f.parameters()) {
Brian Osman716aeb92021-04-21 13:20:00 -04001647 if (f.isMain() && param->modifiers().fLayout.fBuiltin != -1) {
1648 continue;
1649 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001650 this->write(separator);
1651 separator = ", ";
John Stiles06b84ef2020-12-09 12:35:48 -05001652 this->writeModifiers(param->modifiers(), /*globalContext=*/false);
Ethan Nicholas30d30222020-09-11 12:27:26 -04001653 const Type* type = &param->type();
John Stilesb4418502021-02-04 10:57:08 -05001654 this->writeType(*type);
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001655 if (param->modifiers().fFlags & Modifiers::kOut_Flag) {
John Stilesf2bd5012020-12-04 11:58:26 -05001656 this->write("&");
Ethan Nicholascc305772017-10-13 16:17:45 -04001657 }
Timothy Liang651286f2018-06-07 09:55:33 -04001658 this->write(" ");
Ethan Nicholase2c49992020-10-05 11:49:11 -04001659 this->writeName(param->name());
Ethan Nicholascc305772017-10-13 16:17:45 -04001660 }
John Stiles569249b2020-11-03 12:18:22 -05001661 this->write(")");
1662 return true;
1663}
Ethan Nicholascc305772017-10-13 16:17:45 -04001664
John Stiles569249b2020-11-03 12:18:22 -05001665void MetalCodeGenerator::writeFunctionPrototype(const FunctionPrototype& f) {
1666 this->writeFunctionDeclaration(f.declaration());
1667 this->writeLine(";");
1668}
1669
John Stiles986c7fb2020-12-01 14:44:56 -05001670static bool is_block_ending_with_return(const Statement* stmt) {
1671 // This function detects (potentially nested) blocks that end in a return statement.
1672 if (!stmt->is<Block>()) {
1673 return false;
1674 }
1675 const StatementArray& block = stmt->as<Block>().children();
1676 for (int index = block.count(); index--; ) {
1677 const Statement& stmt = *block[index];
1678 if (stmt.is<ReturnStatement>()) {
1679 return true;
1680 }
1681 if (stmt.is<Block>()) {
1682 return is_block_ending_with_return(&stmt);
1683 }
1684 if (!stmt.is<Nop>()) {
1685 break;
1686 }
1687 }
1688 return false;
1689}
1690
John Stiles569249b2020-11-03 12:18:22 -05001691void MetalCodeGenerator::writeFunction(const FunctionDefinition& f) {
John Stiles270cec22021-02-17 12:59:36 -05001692 SkASSERT(!fProgram.fConfig->fSettings.fFragColorIsInOut);
Brian Salomondc092132018-04-04 10:14:16 -04001693
John Stiles569249b2020-11-03 12:18:22 -05001694 if (!this->writeFunctionDeclaration(f.declaration())) {
1695 return;
1696 }
1697
John Stiles986c7fb2020-12-01 14:44:56 -05001698 fCurrentFunction = &f.declaration();
1699 SkScopeExit clearCurrentFunction([&] { fCurrentFunction = nullptr; });
1700
John Stiles569249b2020-11-03 12:18:22 -05001701 this->writeLine(" {");
1702
John Stilese8da4d22021-03-24 09:19:45 -04001703 if (f.declaration().isMain()) {
John Stilescdcdb042020-07-06 09:03:51 -04001704 this->writeGlobalInit();
John Stilesf7410bd2021-01-19 13:07:55 -05001705 this->writeLine(" Outputs _out;");
John Stiles37279172021-01-21 22:24:28 -05001706 this->writeLine(" (void)_out;");
Ethan Nicholascc305772017-10-13 16:17:45 -04001707 }
John Stilesc67b3622020-05-28 17:53:13 -04001708
John Stiles95680232021-04-22 15:05:20 -04001709 fFunctionHeader.clear();
Ethan Nicholascc305772017-10-13 16:17:45 -04001710 StringStream buffer;
John Stiles44532372020-12-07 12:33:55 -05001711 {
1712 AutoOutputStream outputToBuffer(this, &buffer);
1713 fIndentation++;
1714 for (const std::unique_ptr<Statement>& stmt : f.body()->as<Block>().children()) {
1715 if (!stmt->isEmpty()) {
1716 this->writeStatement(*stmt);
John Stilese8b5a732021-03-12 13:25:52 -05001717 this->finishLine();
John Stiles44532372020-12-07 12:33:55 -05001718 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001719 }
John Stilese8da4d22021-03-24 09:19:45 -04001720 if (f.declaration().isMain()) {
John Stiles44532372020-12-07 12:33:55 -05001721 // If the main function doesn't end with a return, we need to synthesize one here.
1722 if (!is_block_ending_with_return(f.body().get())) {
1723 this->writeReturnStatementFromMain();
John Stilese8b5a732021-03-12 13:25:52 -05001724 this->finishLine();
John Stiles44532372020-12-07 12:33:55 -05001725 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001726 }
John Stiles44532372020-12-07 12:33:55 -05001727 fIndentation--;
1728 this->writeLine("}");
Ethan Nicholascc305772017-10-13 16:17:45 -04001729 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001730 this->write(fFunctionHeader);
1731 this->write(buffer.str());
1732}
1733
1734void MetalCodeGenerator::writeModifiers(const Modifiers& modifiers,
John Stiles06b84ef2020-12-09 12:35:48 -05001735 bool globalContext) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001736 if (modifiers.fFlags & Modifiers::kOut_Flag) {
1737 this->write("thread ");
1738 }
1739 if (modifiers.fFlags & Modifiers::kConst_Flag) {
John Stiles0bd55782021-02-09 18:29:40 -05001740 this->write("const ");
Ethan Nicholascc305772017-10-13 16:17:45 -04001741 }
1742}
1743
1744void MetalCodeGenerator::writeInterfaceBlock(const InterfaceBlock& intf) {
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001745 if ("sk_PerVertex" == intf.typeName()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001746 return;
1747 }
John Stiles06b84ef2020-12-09 12:35:48 -05001748 this->writeModifiers(intf.variable().modifiers(), /*globalContext=*/true);
Timothy Liangdc89f192018-06-13 09:20:31 -04001749 this->write("struct ");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001750 this->writeLine(intf.typeName() + " {");
1751 const Type* structType = &intf.variable().type();
John Stilesbb43b7e2020-12-03 17:36:32 -05001752 if (structType->isArray()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001753 structType = &structType->componentType();
1754 }
Timothy Liangdc89f192018-06-13 09:20:31 -04001755 fIndentation++;
John Stiles3dba3ee2020-12-02 23:35:49 -05001756 this->writeFields(structType->fields(), structType->fOffset, &intf);
Jim Van Verth3d482992019-02-07 10:48:05 -05001757 if (fProgram.fInputs.fRTHeight) {
Timothy Liang7d637782018-06-05 09:58:07 -04001758 this->writeLine("float u_skRTHeight;");
Ethan Nicholascc305772017-10-13 16:17:45 -04001759 }
1760 fIndentation--;
1761 this->write("}");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001762 if (intf.instanceName().size()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001763 this->write(" ");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001764 this->write(intf.instanceName());
John Stilesd39aec02020-12-03 10:42:26 -05001765 if (intf.arraySize() > 0) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001766 this->write("[");
John Stilesd39aec02020-12-03 10:42:26 -05001767 this->write(to_string(intf.arraySize()));
Ethan Nicholascc305772017-10-13 16:17:45 -04001768 this->write("]");
John Stilesd39aec02020-12-03 10:42:26 -05001769 } else if (intf.arraySize() == Type::kUnsizedArray){
1770 this->write("[]");
Ethan Nicholascc305772017-10-13 16:17:45 -04001771 }
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001772 fInterfaceBlockNameMap[&intf] = intf.instanceName();
Timothy Lianga06f2152018-05-24 15:33:31 -04001773 } else {
Timothy Liang7d637782018-06-05 09:58:07 -04001774 fInterfaceBlockNameMap[&intf] = "_anonInterface" + to_string(fAnonInterfaceCount++);
Ethan Nicholascc305772017-10-13 16:17:45 -04001775 }
1776 this->writeLine(";");
1777}
1778
Timothy Liangdc89f192018-06-13 09:20:31 -04001779void MetalCodeGenerator::writeFields(const std::vector<Type::Field>& fields, int parentOffset,
1780 const InterfaceBlock* parentIntf) {
Timothy Liang609fbe32018-08-10 16:40:49 -04001781 MemoryLayout memoryLayout(MemoryLayout::kMetal_Standard);
Timothy Liangdc89f192018-06-13 09:20:31 -04001782 int currentOffset = 0;
John Stiles39346472021-04-29 14:39:35 -04001783 for (const Type::Field& field : fields) {
Timothy Liangdc89f192018-06-13 09:20:31 -04001784 int fieldOffset = field.fModifiers.fLayout.fOffset;
1785 const Type* fieldType = field.fType;
John Stiles21f5f452020-11-30 09:57:59 -05001786 if (!MemoryLayout::LayoutIsSupported(*fieldType)) {
John Stiles0023c0c2020-11-16 13:32:18 -05001787 fErrors.error(parentOffset, "type '" + fieldType->name() + "' is not permitted here");
1788 return;
1789 }
Timothy Liangdc89f192018-06-13 09:20:31 -04001790 if (fieldOffset != -1) {
1791 if (currentOffset > fieldOffset) {
1792 fErrors.error(parentOffset,
John Stilesd7199b22020-12-30 16:22:58 -05001793 "offset of field '" + field.fName + "' must be at least " +
1794 to_string((int) currentOffset));
Brian Osman8609a242020-09-08 14:01:49 -04001795 return;
Timothy Liangdc89f192018-06-13 09:20:31 -04001796 } else if (currentOffset < fieldOffset) {
1797 this->write("char pad");
1798 this->write(to_string(fPaddingCount++));
1799 this->write("[");
1800 this->write(to_string(fieldOffset - currentOffset));
1801 this->writeLine("];");
1802 currentOffset = fieldOffset;
1803 }
1804 int alignment = memoryLayout.alignment(*fieldType);
1805 if (fieldOffset % alignment) {
1806 fErrors.error(parentOffset,
1807 "offset of field '" + field.fName + "' must be a multiple of " +
1808 to_string((int) alignment));
Brian Osman8609a242020-09-08 14:01:49 -04001809 return;
Timothy Liangdc89f192018-06-13 09:20:31 -04001810 }
1811 }
Brian Osman8609a242020-09-08 14:01:49 -04001812 size_t fieldSize = memoryLayout.size(*fieldType);
1813 if (fieldSize > static_cast<size_t>(std::numeric_limits<int>::max() - currentOffset)) {
1814 fErrors.error(parentOffset, "field offset overflow");
1815 return;
1816 }
1817 currentOffset += fieldSize;
John Stiles06b84ef2020-12-09 12:35:48 -05001818 this->writeModifiers(field.fModifiers, /*globalContext=*/false);
John Stilesb4418502021-02-04 10:57:08 -05001819 this->writeType(*fieldType);
Timothy Liangdc89f192018-06-13 09:20:31 -04001820 this->write(" ");
1821 this->writeName(field.fName);
Timothy Liangdc89f192018-06-13 09:20:31 -04001822 this->writeLine(";");
1823 if (parentIntf) {
1824 fInterfaceBlockMap[&field] = parentIntf;
1825 }
1826 }
1827}
1828
Ethan Nicholascc305772017-10-13 16:17:45 -04001829void MetalCodeGenerator::writeVarInitializer(const Variable& var, const Expression& value) {
Brian Osman00185012021-02-04 16:07:11 -05001830 this->writeExpression(value, Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001831}
1832
Timothy Liang651286f2018-06-07 09:55:33 -04001833void MetalCodeGenerator::writeName(const String& name) {
1834 if (fReservedWords.find(name) != fReservedWords.end()) {
1835 this->write("_"); // adding underscore before name to avoid conflict with reserved words
1836 }
1837 this->write(name);
1838}
1839
John Stilesb4418502021-02-04 10:57:08 -05001840void MetalCodeGenerator::writeVarDeclaration(const VarDeclaration& varDecl, bool global) {
1841 if (global && !(varDecl.var().modifiers().fFlags & Modifiers::kConst_Flag)) {
Brian Osmanc0213602020-10-06 14:43:32 -04001842 return;
Ethan Nicholascc305772017-10-13 16:17:45 -04001843 }
John Stilesb4418502021-02-04 10:57:08 -05001844 this->writeModifiers(varDecl.var().modifiers(), global);
1845 this->writeType(varDecl.var().type());
Brian Osmanc0213602020-10-06 14:43:32 -04001846 this->write(" ");
John Stilesb4418502021-02-04 10:57:08 -05001847 this->writeName(varDecl.var().name());
1848 if (varDecl.value()) {
Brian Osmanc0213602020-10-06 14:43:32 -04001849 this->write(" = ");
John Stilesb4418502021-02-04 10:57:08 -05001850 this->writeVarInitializer(varDecl.var(), *varDecl.value());
Brian Osmanc0213602020-10-06 14:43:32 -04001851 }
1852 this->write(";");
Ethan Nicholascc305772017-10-13 16:17:45 -04001853}
1854
1855void MetalCodeGenerator::writeStatement(const Statement& s) {
Ethan Nicholase6592142020-09-08 10:22:09 -04001856 switch (s.kind()) {
1857 case Statement::Kind::kBlock:
John Stiles26f98502020-08-18 09:30:51 -04001858 this->writeBlock(s.as<Block>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001859 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001860 case Statement::Kind::kExpression:
Brian Osman00185012021-02-04 16:07:11 -05001861 this->writeExpression(*s.as<ExpressionStatement>().expression(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001862 this->write(";");
1863 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001864 case Statement::Kind::kReturn:
John Stiles26f98502020-08-18 09:30:51 -04001865 this->writeReturnStatement(s.as<ReturnStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001866 break;
Brian Osmanc0213602020-10-06 14:43:32 -04001867 case Statement::Kind::kVarDeclaration:
1868 this->writeVarDeclaration(s.as<VarDeclaration>(), false);
Ethan Nicholascc305772017-10-13 16:17:45 -04001869 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001870 case Statement::Kind::kIf:
John Stiles26f98502020-08-18 09:30:51 -04001871 this->writeIfStatement(s.as<IfStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001872 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001873 case Statement::Kind::kFor:
John Stiles26f98502020-08-18 09:30:51 -04001874 this->writeForStatement(s.as<ForStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001875 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001876 case Statement::Kind::kDo:
John Stiles26f98502020-08-18 09:30:51 -04001877 this->writeDoStatement(s.as<DoStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001878 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001879 case Statement::Kind::kSwitch:
John Stiles26f98502020-08-18 09:30:51 -04001880 this->writeSwitchStatement(s.as<SwitchStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001881 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001882 case Statement::Kind::kBreak:
Ethan Nicholascc305772017-10-13 16:17:45 -04001883 this->write("break;");
1884 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001885 case Statement::Kind::kContinue:
Ethan Nicholascc305772017-10-13 16:17:45 -04001886 this->write("continue;");
1887 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001888 case Statement::Kind::kDiscard:
Timothy Lianga06f2152018-05-24 15:33:31 -04001889 this->write("discard_fragment();");
Ethan Nicholascc305772017-10-13 16:17:45 -04001890 break;
John Stiles98c1f822020-09-09 14:18:53 -04001891 case Statement::Kind::kInlineMarker:
Ethan Nicholase6592142020-09-08 10:22:09 -04001892 case Statement::Kind::kNop:
Ethan Nicholascc305772017-10-13 16:17:45 -04001893 this->write(";");
1894 break;
1895 default:
John Stileseada7bc2021-02-02 16:29:32 -05001896 SkDEBUGFAILF("unsupported statement: %s", s.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -05001897 break;
Ethan Nicholascc305772017-10-13 16:17:45 -04001898 }
1899}
1900
Ethan Nicholascc305772017-10-13 16:17:45 -04001901void MetalCodeGenerator::writeBlock(const Block& b) {
John Stiles3744bd62021-01-26 13:49:43 -05001902 // Write scope markers if this block is a scope, or if the block is empty (since we need to emit
1903 // something here to make the code valid).
1904 bool isScope = b.isScope() || b.isEmpty();
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001905 if (isScope) {
Ethan Nicholas70728ef2020-05-28 07:09:00 -04001906 this->writeLine("{");
1907 fIndentation++;
1908 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001909 for (const std::unique_ptr<Statement>& stmt : b.children()) {
1910 if (!stmt->isEmpty()) {
1911 this->writeStatement(*stmt);
John Stilese8b5a732021-03-12 13:25:52 -05001912 this->finishLine();
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001913 }
1914 }
1915 if (isScope) {
Ethan Nicholas70728ef2020-05-28 07:09:00 -04001916 fIndentation--;
1917 this->write("}");
1918 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001919}
1920
1921void MetalCodeGenerator::writeIfStatement(const IfStatement& stmt) {
1922 this->write("if (");
Brian Osman00185012021-02-04 16:07:11 -05001923 this->writeExpression(*stmt.test(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001924 this->write(") ");
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04001925 this->writeStatement(*stmt.ifTrue());
1926 if (stmt.ifFalse()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001927 this->write(" else ");
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04001928 this->writeStatement(*stmt.ifFalse());
Ethan Nicholascc305772017-10-13 16:17:45 -04001929 }
1930}
1931
1932void MetalCodeGenerator::writeForStatement(const ForStatement& f) {
Brian Osmand6f23382020-12-15 17:08:59 -05001933 // Emit loops of the form 'for(;test;)' as 'while(test)', which is probably how they started
1934 if (!f.initializer() && f.test() && !f.next()) {
1935 this->write("while (");
Brian Osman00185012021-02-04 16:07:11 -05001936 this->writeExpression(*f.test(), Precedence::kTopLevel);
Brian Osmand6f23382020-12-15 17:08:59 -05001937 this->write(") ");
1938 this->writeStatement(*f.statement());
1939 return;
1940 }
1941
John Stiles1a15e572021-04-19 14:57:15 -04001942 this->write("for (");
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04001943 if (f.initializer() && !f.initializer()->isEmpty()) {
John Stiles1a15e572021-04-19 14:57:15 -04001944 this->writeStatement(*f.initializer());
Ethan Nicholascc305772017-10-13 16:17:45 -04001945 } else {
John Stiles1a15e572021-04-19 14:57:15 -04001946 this->write("; ");
Ethan Nicholascc305772017-10-13 16:17:45 -04001947 }
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04001948 if (f.test()) {
Brian Osman00185012021-02-04 16:07:11 -05001949 this->writeExpression(*f.test(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001950 }
1951 this->write("; ");
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04001952 if (f.next()) {
Brian Osman00185012021-02-04 16:07:11 -05001953 this->writeExpression(*f.next(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001954 }
1955 this->write(") ");
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04001956 this->writeStatement(*f.statement());
Ethan Nicholascc305772017-10-13 16:17:45 -04001957}
1958
Ethan Nicholascc305772017-10-13 16:17:45 -04001959void MetalCodeGenerator::writeDoStatement(const DoStatement& d) {
1960 this->write("do ");
Ethan Nicholas1fd61162020-09-28 13:14:19 -04001961 this->writeStatement(*d.statement());
Ethan Nicholascc305772017-10-13 16:17:45 -04001962 this->write(" while (");
Brian Osman00185012021-02-04 16:07:11 -05001963 this->writeExpression(*d.test(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001964 this->write(");");
1965}
1966
1967void MetalCodeGenerator::writeSwitchStatement(const SwitchStatement& s) {
1968 this->write("switch (");
Brian Osman00185012021-02-04 16:07:11 -05001969 this->writeExpression(*s.value(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001970 this->writeLine(") {");
1971 fIndentation++;
John Stilesb23a64b2021-03-11 08:27:59 -05001972 for (const std::unique_ptr<Statement>& stmt : s.cases()) {
1973 const SwitchCase& c = stmt->as<SwitchCase>();
1974 if (c.value()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001975 this->write("case ");
John Stilesb23a64b2021-03-11 08:27:59 -05001976 this->writeExpression(*c.value(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001977 this->writeLine(":");
1978 } else {
1979 this->writeLine("default:");
1980 }
John Stilesb23a64b2021-03-11 08:27:59 -05001981 if (!c.statement()->isEmpty()) {
John Stilesc3ce43b2021-03-09 15:37:01 -05001982 fIndentation++;
John Stilesb23a64b2021-03-11 08:27:59 -05001983 this->writeStatement(*c.statement());
John Stilese8b5a732021-03-12 13:25:52 -05001984 this->finishLine();
John Stilesc3ce43b2021-03-09 15:37:01 -05001985 fIndentation--;
Ethan Nicholascc305772017-10-13 16:17:45 -04001986 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001987 }
1988 fIndentation--;
1989 this->write("}");
1990}
1991
John Stiles986c7fb2020-12-01 14:44:56 -05001992void MetalCodeGenerator::writeReturnStatementFromMain() {
1993 // main functions in Metal return a magic _out parameter that doesn't exist in SkSL.
John Stiles270cec22021-02-17 12:59:36 -05001994 switch (fProgram.fConfig->fKind) {
John Stilesdbd4e6f2021-02-16 13:29:15 -05001995 case ProgramKind::kFragment:
John Stilesf7410bd2021-01-19 13:07:55 -05001996 this->write("return _out;");
John Stiles986c7fb2020-12-01 14:44:56 -05001997 break;
John Stilesdbd4e6f2021-02-16 13:29:15 -05001998 case ProgramKind::kVertex:
John Stilesf7410bd2021-01-19 13:07:55 -05001999 this->write("return (_out.sk_Position.y = -_out.sk_Position.y, _out);");
John Stiles986c7fb2020-12-01 14:44:56 -05002000 break;
2001 default:
2002 SkDEBUGFAIL("unsupported kind of program");
2003 }
2004}
2005
Ethan Nicholascc305772017-10-13 16:17:45 -04002006void MetalCodeGenerator::writeReturnStatement(const ReturnStatement& r) {
John Stilese8da4d22021-03-24 09:19:45 -04002007 if (fCurrentFunction && fCurrentFunction->isMain()) {
John Stiles986c7fb2020-12-01 14:44:56 -05002008 if (r.expression()) {
John Stiles97d18172021-01-22 16:47:42 -05002009 if (r.expression()->type() == *fContext.fTypes.fHalf4) {
2010 this->write("_out.sk_FragColor = ");
Brian Osman00185012021-02-04 16:07:11 -05002011 this->writeExpression(*r.expression(), Precedence::kTopLevel);
John Stiles97d18172021-01-22 16:47:42 -05002012 this->writeLine(";");
2013 } else {
2014 fErrors.error(r.fOffset, "Metal does not support returning '" +
2015 r.expression()->type().description() + "' from main()");
2016 }
John Stiles986c7fb2020-12-01 14:44:56 -05002017 }
2018 this->writeReturnStatementFromMain();
2019 return;
2020 }
2021
Ethan Nicholascc305772017-10-13 16:17:45 -04002022 this->write("return");
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04002023 if (r.expression()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002024 this->write(" ");
Brian Osman00185012021-02-04 16:07:11 -05002025 this->writeExpression(*r.expression(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04002026 }
2027 this->write(";");
2028}
2029
Michael Ludwigbf58add2021-03-16 10:40:11 -04002030void MetalCodeGenerator::writeHeader() {
2031 this->write("#include <metal_stdlib>\n");
2032 this->write("#include <simd/simd.h>\n");
2033 this->write("using namespace metal;\n");
2034}
2035
Ethan Nicholascc305772017-10-13 16:17:45 -04002036void MetalCodeGenerator::writeUniformStruct() {
Brian Osman133724c2020-10-28 14:14:39 -04002037 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04002038 if (e->is<GlobalVarDeclaration>()) {
2039 const GlobalVarDeclaration& decls = e->as<GlobalVarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04002040 const Variable& var = decls.declaration()->as<VarDeclaration>().var();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002041 if (var.modifiers().fFlags & Modifiers::kUniform_Flag &&
Brian Osmanc0213602020-10-06 14:43:32 -04002042 var.type().typeKind() != Type::TypeKind::kSampler) {
John Stilesda5cdf62021-01-28 11:47:29 -05002043 int uniformSet = this->getUniformSet(var.modifiers());
John Stilesd8fc95d2021-01-26 16:22:53 -05002044 // Make sure that the program's uniform-set value is consistent throughout.
Ethan Nicholascc305772017-10-13 16:17:45 -04002045 if (-1 == fUniformBuffer) {
2046 this->write("struct Uniforms {\n");
John Stilesd8fc95d2021-01-26 16:22:53 -05002047 fUniformBuffer = uniformSet;
2048 } else if (uniformSet != fUniformBuffer) {
2049 fErrors.error(decls.fOffset, "Metal backend requires all uniforms to have "
2050 "the same 'layout(set=...)'");
Ethan Nicholascc305772017-10-13 16:17:45 -04002051 }
2052 this->write(" ");
John Stilesb4418502021-02-04 10:57:08 -05002053 this->writeType(var.type());
Ethan Nicholascc305772017-10-13 16:17:45 -04002054 this->write(" ");
Brian Osmanc0213602020-10-06 14:43:32 -04002055 this->writeName(var.name());
Ethan Nicholascc305772017-10-13 16:17:45 -04002056 this->write(";\n");
2057 }
2058 }
2059 }
2060 if (-1 != fUniformBuffer) {
2061 this->write("};\n");
2062 }
2063}
2064
2065void MetalCodeGenerator::writeInputStruct() {
2066 this->write("struct Inputs {\n");
Brian Osman133724c2020-10-28 14:14:39 -04002067 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04002068 if (e->is<GlobalVarDeclaration>()) {
2069 const GlobalVarDeclaration& decls = e->as<GlobalVarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04002070 const Variable& var = decls.declaration()->as<VarDeclaration>().var();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002071 if (var.modifiers().fFlags & Modifiers::kIn_Flag &&
2072 -1 == var.modifiers().fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002073 this->write(" ");
John Stilesb4418502021-02-04 10:57:08 -05002074 this->writeType(var.type());
Ethan Nicholascc305772017-10-13 16:17:45 -04002075 this->write(" ");
Brian Osmanc0213602020-10-06 14:43:32 -04002076 this->writeName(var.name());
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002077 if (-1 != var.modifiers().fLayout.fLocation) {
John Stiles270cec22021-02-17 12:59:36 -05002078 if (fProgram.fConfig->fKind == ProgramKind::kVertex) {
Brian Osmanc0213602020-10-06 14:43:32 -04002079 this->write(" [[attribute(" +
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002080 to_string(var.modifiers().fLayout.fLocation) + ")]]");
John Stiles270cec22021-02-17 12:59:36 -05002081 } else if (fProgram.fConfig->fKind == ProgramKind::kFragment) {
Brian Osmanc0213602020-10-06 14:43:32 -04002082 this->write(" [[user(locn" +
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002083 to_string(var.modifiers().fLayout.fLocation) + ")]]");
Ethan Nicholascc305772017-10-13 16:17:45 -04002084 }
2085 }
2086 this->write(";\n");
2087 }
2088 }
2089 }
2090 this->write("};\n");
2091}
2092
2093void MetalCodeGenerator::writeOutputStruct() {
2094 this->write("struct Outputs {\n");
John Stiles270cec22021-02-17 12:59:36 -05002095 if (fProgram.fConfig->fKind == ProgramKind::kVertex) {
Timothy Liangb8eeb802018-07-23 16:46:16 -04002096 this->write(" float4 sk_Position [[position]];\n");
John Stiles270cec22021-02-17 12:59:36 -05002097 } else if (fProgram.fConfig->fKind == ProgramKind::kFragment) {
Timothy Liangde0be802018-08-10 13:48:08 -04002098 this->write(" float4 sk_FragColor [[color(0)]];\n");
Timothy Liang7d637782018-06-05 09:58:07 -04002099 }
Brian Osman133724c2020-10-28 14:14:39 -04002100 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04002101 if (e->is<GlobalVarDeclaration>()) {
2102 const GlobalVarDeclaration& decls = e->as<GlobalVarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04002103 const Variable& var = decls.declaration()->as<VarDeclaration>().var();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002104 if (var.modifiers().fFlags & Modifiers::kOut_Flag &&
2105 -1 == var.modifiers().fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002106 this->write(" ");
John Stilesb4418502021-02-04 10:57:08 -05002107 this->writeType(var.type());
Ethan Nicholascc305772017-10-13 16:17:45 -04002108 this->write(" ");
Brian Osmanc0213602020-10-06 14:43:32 -04002109 this->writeName(var.name());
John Stiles842b3592020-12-01 10:36:37 -05002110
2111 int location = var.modifiers().fLayout.fLocation;
2112 if (location < 0) {
2113 fErrors.error(var.fOffset,
2114 "Metal out variables must have 'layout(location=...)'");
John Stiles270cec22021-02-17 12:59:36 -05002115 } else if (fProgram.fConfig->fKind == ProgramKind::kVertex) {
John Stiles842b3592020-12-01 10:36:37 -05002116 this->write(" [[user(locn" + to_string(location) + ")]]");
John Stiles270cec22021-02-17 12:59:36 -05002117 } else if (fProgram.fConfig->fKind == ProgramKind::kFragment) {
John Stiles842b3592020-12-01 10:36:37 -05002118 this->write(" [[color(" + to_string(location) + ")");
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002119 int colorIndex = var.modifiers().fLayout.fIndex;
Brian Osmanc0213602020-10-06 14:43:32 -04002120 if (colorIndex) {
2121 this->write(", index(" + to_string(colorIndex) + ")");
Timothy Liang7d637782018-06-05 09:58:07 -04002122 }
Brian Osmanc0213602020-10-06 14:43:32 -04002123 this->write("]]");
Ethan Nicholascc305772017-10-13 16:17:45 -04002124 }
2125 this->write(";\n");
2126 }
2127 }
Timothy Liang7d637782018-06-05 09:58:07 -04002128 }
John Stiles270cec22021-02-17 12:59:36 -05002129 if (fProgram.fConfig->fKind == ProgramKind::kVertex) {
Jim Van Verth3913d3e2020-08-31 15:16:57 -04002130 this->write(" float sk_PointSize [[point_size]];\n");
Timothy Liang7d637782018-06-05 09:58:07 -04002131 }
2132 this->write("};\n");
2133}
2134
2135void MetalCodeGenerator::writeInterfaceBlocks() {
2136 bool wroteInterfaceBlock = false;
Brian Osman133724c2020-10-28 14:14:39 -04002137 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04002138 if (e->is<InterfaceBlock>()) {
2139 this->writeInterfaceBlock(e->as<InterfaceBlock>());
Timothy Liang7d637782018-06-05 09:58:07 -04002140 wroteInterfaceBlock = true;
2141 }
2142 }
Jim Van Verth3d482992019-02-07 10:48:05 -05002143 if (!wroteInterfaceBlock && fProgram.fInputs.fRTHeight) {
Timothy Liang7d637782018-06-05 09:58:07 -04002144 this->writeLine("struct sksl_synthetic_uniforms {");
2145 this->writeLine(" float u_skRTHeight;");
2146 this->writeLine("};");
2147 }
Ethan Nicholascc305772017-10-13 16:17:45 -04002148}
2149
John Stilesdc75a972020-11-25 16:24:55 -05002150void MetalCodeGenerator::writeStructDefinitions() {
2151 for (const ProgramElement* e : fProgram.elements()) {
2152 if (e->is<StructDefinition>()) {
Brian Osman02bc5222021-01-28 11:00:20 -05002153 this->writeStructDefinition(e->as<StructDefinition>());
John Stilesdc75a972020-11-25 16:24:55 -05002154 }
2155 }
2156}
2157
John Stilescdcdb042020-07-06 09:03:51 -04002158void MetalCodeGenerator::visitGlobalStruct(GlobalStructVisitor* visitor) {
2159 // Visit the interface blocks.
2160 for (const auto& [interfaceType, interfaceName] : fInterfaceBlockNameMap) {
John Stilesfdb8dbe2020-12-04 11:00:03 -05002161 visitor->visitInterfaceBlock(*interfaceType, interfaceName);
John Stilescdcdb042020-07-06 09:03:51 -04002162 }
Brian Osman133724c2020-10-28 14:14:39 -04002163 for (const ProgramElement* element : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04002164 if (!element->is<GlobalVarDeclaration>()) {
John Stilescdcdb042020-07-06 09:03:51 -04002165 continue;
Timothy Liang7d637782018-06-05 09:58:07 -04002166 }
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04002167 const GlobalVarDeclaration& global = element->as<GlobalVarDeclaration>();
2168 const VarDeclaration& decl = global.declaration()->as<VarDeclaration>();
2169 const Variable& var = decl.var();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002170 if ((!var.modifiers().fFlags && -1 == var.modifiers().fLayout.fBuiltin) ||
Brian Osmanc0213602020-10-06 14:43:32 -04002171 var.type().typeKind() == Type::TypeKind::kSampler) {
2172 if (var.type().typeKind() == Type::TypeKind::kSampler) {
2173 // Samplers are represented as a "texture/sampler" duo in the global struct.
John Stilesfdb8dbe2020-12-04 11:00:03 -05002174 visitor->visitTexture(var.type(), var.name());
2175 visitor->visitSampler(var.type(), String(var.name()) + SAMPLER_SUFFIX);
Brian Osmanc0213602020-10-06 14:43:32 -04002176 } else {
2177 // Visit a regular variable.
John Stilesfdb8dbe2020-12-04 11:00:03 -05002178 visitor->visitVariable(var, decl.value().get());
Timothy Liangee84fe12018-05-18 14:38:19 -04002179 }
2180 }
2181 }
John Stilescdcdb042020-07-06 09:03:51 -04002182}
2183
2184void MetalCodeGenerator::writeGlobalStruct() {
2185 class : public GlobalStructVisitor {
2186 public:
John Stilesfdb8dbe2020-12-04 11:00:03 -05002187 void visitInterfaceBlock(const InterfaceBlock& block, const String& blockName) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002188 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002189 fCodeGen->write(" constant ");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04002190 fCodeGen->write(block.typeName());
John Stilescdcdb042020-07-06 09:03:51 -04002191 fCodeGen->write("* ");
2192 fCodeGen->writeName(blockName);
2193 fCodeGen->write(";\n");
2194 }
John Stilesfdb8dbe2020-12-04 11:00:03 -05002195 void visitTexture(const Type& type, const String& name) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002196 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002197 fCodeGen->write(" ");
John Stilesb4418502021-02-04 10:57:08 -05002198 fCodeGen->writeType(type);
John Stilescdcdb042020-07-06 09:03:51 -04002199 fCodeGen->write(" ");
2200 fCodeGen->writeName(name);
2201 fCodeGen->write(";\n");
2202 }
John Stilesfdb8dbe2020-12-04 11:00:03 -05002203 void visitSampler(const Type&, const String& name) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002204 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002205 fCodeGen->write(" sampler ");
2206 fCodeGen->writeName(name);
2207 fCodeGen->write(";\n");
2208 }
John Stilesfdb8dbe2020-12-04 11:00:03 -05002209 void visitVariable(const Variable& var, const Expression* value) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002210 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002211 fCodeGen->write(" ");
John Stilesb4418502021-02-04 10:57:08 -05002212 fCodeGen->writeType(var.type());
John Stilescdcdb042020-07-06 09:03:51 -04002213 fCodeGen->write(" ");
Ethan Nicholase2c49992020-10-05 11:49:11 -04002214 fCodeGen->writeName(var.name());
John Stilescdcdb042020-07-06 09:03:51 -04002215 fCodeGen->write(";\n");
2216 }
John Stiles83f3b8d2020-12-07 17:52:25 -05002217 void addElement() {
John Stilescdcdb042020-07-06 09:03:51 -04002218 if (fFirst) {
2219 fCodeGen->write("struct Globals {\n");
2220 fFirst = false;
2221 }
2222 }
John Stiles83f3b8d2020-12-07 17:52:25 -05002223 void finish() {
John Stilescdcdb042020-07-06 09:03:51 -04002224 if (!fFirst) {
John Stiles83f3b8d2020-12-07 17:52:25 -05002225 fCodeGen->writeLine("};");
John Stilescdcdb042020-07-06 09:03:51 -04002226 fFirst = true;
2227 }
2228 }
2229
2230 MetalCodeGenerator* fCodeGen = nullptr;
2231 bool fFirst = true;
2232 } visitor;
2233
2234 visitor.fCodeGen = this;
2235 this->visitGlobalStruct(&visitor);
John Stiles83f3b8d2020-12-07 17:52:25 -05002236 visitor.finish();
John Stilescdcdb042020-07-06 09:03:51 -04002237}
2238
2239void MetalCodeGenerator::writeGlobalInit() {
2240 class : public GlobalStructVisitor {
2241 public:
John Stilesfdb8dbe2020-12-04 11:00:03 -05002242 void visitInterfaceBlock(const InterfaceBlock& blockType,
John Stilescdcdb042020-07-06 09:03:51 -04002243 const String& blockName) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002244 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002245 fCodeGen->write("&");
2246 fCodeGen->writeName(blockName);
2247 }
John Stilesfdb8dbe2020-12-04 11:00:03 -05002248 void visitTexture(const Type&, const String& name) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002249 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002250 fCodeGen->writeName(name);
2251 }
John Stilesfdb8dbe2020-12-04 11:00:03 -05002252 void visitSampler(const Type&, const String& name) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002253 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002254 fCodeGen->writeName(name);
2255 }
John Stilesfdb8dbe2020-12-04 11:00:03 -05002256 void visitVariable(const Variable& var, const Expression* value) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002257 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002258 if (value) {
2259 fCodeGen->writeVarInitializer(var, *value);
2260 } else {
2261 fCodeGen->write("{}");
2262 }
2263 }
John Stiles83f3b8d2020-12-07 17:52:25 -05002264 void addElement() {
John Stilescdcdb042020-07-06 09:03:51 -04002265 if (fFirst) {
John Stilesf7410bd2021-01-19 13:07:55 -05002266 fCodeGen->write(" Globals _globals{");
John Stilescdcdb042020-07-06 09:03:51 -04002267 fFirst = false;
2268 } else {
2269 fCodeGen->write(", ");
2270 }
2271 }
John Stiles83f3b8d2020-12-07 17:52:25 -05002272 void finish() {
John Stilescdcdb042020-07-06 09:03:51 -04002273 if (!fFirst) {
2274 fCodeGen->writeLine("};");
John Stiles37279172021-01-21 22:24:28 -05002275 fCodeGen->writeLine(" (void)_globals;");
John Stilescdcdb042020-07-06 09:03:51 -04002276 }
2277 }
2278 MetalCodeGenerator* fCodeGen = nullptr;
2279 bool fFirst = true;
2280 } visitor;
2281
2282 visitor.fCodeGen = this;
2283 this->visitGlobalStruct(&visitor);
John Stiles83f3b8d2020-12-07 17:52:25 -05002284 visitor.finish();
Timothy Liangee84fe12018-05-18 14:38:19 -04002285}
2286
Ethan Nicholascc305772017-10-13 16:17:45 -04002287void MetalCodeGenerator::writeProgramElement(const ProgramElement& e) {
Ethan Nicholase6592142020-09-08 10:22:09 -04002288 switch (e.kind()) {
2289 case ProgramElement::Kind::kExtension:
Ethan Nicholascc305772017-10-13 16:17:45 -04002290 break;
Brian Osmanc0213602020-10-06 14:43:32 -04002291 case ProgramElement::Kind::kGlobalVar: {
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04002292 const GlobalVarDeclaration& global = e.as<GlobalVarDeclaration>();
2293 const VarDeclaration& decl = global.declaration()->as<VarDeclaration>();
2294 int builtin = decl.var().modifiers().fLayout.fBuiltin;
Brian Osmanc0213602020-10-06 14:43:32 -04002295 if (-1 == builtin) {
2296 // normal var
2297 this->writeVarDeclaration(decl, true);
John Stilese8b5a732021-03-12 13:25:52 -05002298 this->finishLine();
Brian Osmanc0213602020-10-06 14:43:32 -04002299 } else if (SK_FRAGCOLOR_BUILTIN == builtin) {
2300 // ignore
Ethan Nicholascc305772017-10-13 16:17:45 -04002301 }
2302 break;
2303 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002304 case ProgramElement::Kind::kInterfaceBlock:
Timothy Liang7d637782018-06-05 09:58:07 -04002305 // handled in writeInterfaceBlocks, do nothing
Ethan Nicholascc305772017-10-13 16:17:45 -04002306 break;
John Stilesdc75a972020-11-25 16:24:55 -05002307 case ProgramElement::Kind::kStructDefinition:
2308 // Handled in writeStructDefinitions. Do nothing.
2309 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04002310 case ProgramElement::Kind::kFunction:
John Stiles3dc0da62020-08-19 17:48:31 -04002311 this->writeFunction(e.as<FunctionDefinition>());
Ethan Nicholascc305772017-10-13 16:17:45 -04002312 break;
John Stiles569249b2020-11-03 12:18:22 -05002313 case ProgramElement::Kind::kFunctionPrototype:
2314 this->writeFunctionPrototype(e.as<FunctionPrototype>());
2315 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04002316 case ProgramElement::Kind::kModifiers:
John Stiles06b84ef2020-12-09 12:35:48 -05002317 this->writeModifiers(e.as<ModifiersDeclaration>().modifiers(),
2318 /*globalContext=*/true);
Ethan Nicholascc305772017-10-13 16:17:45 -04002319 this->writeLine(";");
2320 break;
John Stiles712fd6b2020-11-25 22:25:43 -05002321 case ProgramElement::Kind::kEnum:
2322 break;
Ethan Nicholascc305772017-10-13 16:17:45 -04002323 default:
John Stileseada7bc2021-02-02 16:29:32 -05002324 SkDEBUGFAILF("unsupported program element: %s\n", e.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -05002325 break;
Ethan Nicholascc305772017-10-13 16:17:45 -04002326 }
2327}
2328
Ethan Nicholasff350cb2020-05-14 14:05:13 -04002329MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const Expression* e) {
2330 if (!e) {
2331 return kNo_Requirements;
2332 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002333 switch (e->kind()) {
2334 case Expression::Kind::kFunctionCall: {
John Stiles3dc0da62020-08-19 17:48:31 -04002335 const FunctionCall& f = e->as<FunctionCall>();
Ethan Nicholas0dec9922020-10-05 15:51:52 -04002336 Requirements result = this->requirements(f.function());
2337 for (const auto& arg : f.arguments()) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04002338 result |= this->requirements(arg.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002339 }
2340 return result;
2341 }
John Stiles8cad6372021-04-07 12:31:13 -04002342 case Expression::Kind::kConstructorCompound:
2343 case Expression::Kind::kConstructorCompoundCast:
John Stiles7384b372021-04-01 13:48:15 -04002344 case Expression::Kind::kConstructorArray:
John Stiles2938eea2021-04-01 18:58:25 -04002345 case Expression::Kind::kConstructorDiagonalMatrix:
John Stilesfd7252f2021-04-04 22:24:40 -04002346 case Expression::Kind::kConstructorScalarCast:
John Stilesd47330f2021-04-08 23:25:52 -04002347 case Expression::Kind::kConstructorSplat:
2348 case Expression::Kind::kConstructorStruct: {
John Stiles7384b372021-04-01 13:48:15 -04002349 const AnyConstructor& c = e->asAnyConstructor();
Ethan Nicholascc305772017-10-13 16:17:45 -04002350 Requirements result = kNo_Requirements;
John Stilesd8eb8752021-04-01 11:49:10 -04002351 for (const auto& arg : c.argumentSpan()) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04002352 result |= this->requirements(arg.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002353 }
2354 return result;
2355 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002356 case Expression::Kind::kFieldAccess: {
John Stiles3dc0da62020-08-19 17:48:31 -04002357 const FieldAccess& f = e->as<FieldAccess>();
Ethan Nicholas7a95b202020-10-09 11:55:40 -04002358 if (FieldAccess::OwnerKind::kAnonymousInterfaceBlock == f.ownerKind()) {
Timothy Liang7d637782018-06-05 09:58:07 -04002359 return kGlobals_Requirement;
2360 }
Ethan Nicholas7a95b202020-10-09 11:55:40 -04002361 return this->requirements(f.base().get());
Timothy Liang7d637782018-06-05 09:58:07 -04002362 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002363 case Expression::Kind::kSwizzle:
Ethan Nicholas6b4d5812020-10-12 16:11:51 -04002364 return this->requirements(e->as<Swizzle>().base().get());
Ethan Nicholase6592142020-09-08 10:22:09 -04002365 case Expression::Kind::kBinary: {
2366 const BinaryExpression& bin = e->as<BinaryExpression>();
John Stiles2d4f9592020-10-30 10:29:12 -04002367 return this->requirements(bin.left().get()) |
2368 this->requirements(bin.right().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002369 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002370 case Expression::Kind::kIndex: {
John Stiles3dc0da62020-08-19 17:48:31 -04002371 const IndexExpression& idx = e->as<IndexExpression>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04002372 return this->requirements(idx.base().get()) | this->requirements(idx.index().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002373 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002374 case Expression::Kind::kPrefix:
Ethan Nicholas444ccc62020-10-09 10:16:22 -04002375 return this->requirements(e->as<PrefixExpression>().operand().get());
Ethan Nicholase6592142020-09-08 10:22:09 -04002376 case Expression::Kind::kPostfix:
Ethan Nicholas444ccc62020-10-09 10:16:22 -04002377 return this->requirements(e->as<PostfixExpression>().operand().get());
Ethan Nicholase6592142020-09-08 10:22:09 -04002378 case Expression::Kind::kTernary: {
John Stiles3dc0da62020-08-19 17:48:31 -04002379 const TernaryExpression& t = e->as<TernaryExpression>();
Ethan Nicholasdd218162020-10-08 05:48:01 -04002380 return this->requirements(t.test().get()) | this->requirements(t.ifTrue().get()) |
2381 this->requirements(t.ifFalse().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002382 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002383 case Expression::Kind::kVariableReference: {
John Stiles3dc0da62020-08-19 17:48:31 -04002384 const VariableReference& v = e->as<VariableReference>();
Ethan Nicholas78686922020-10-08 06:46:27 -04002385 const Modifiers& modifiers = v.variable()->modifiers();
Ethan Nicholascc305772017-10-13 16:17:45 -04002386 Requirements result = kNo_Requirements;
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002387 if (modifiers.fLayout.fBuiltin == SK_FRAGCOORD_BUILTIN) {
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -04002388 result = kGlobals_Requirement | kFragCoord_Requirement;
Ethan Nicholas453f67f2020-10-09 10:43:45 -04002389 } else if (Variable::Storage::kGlobal == v.variable()->storage()) {
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002390 if (modifiers.fFlags & Modifiers::kIn_Flag) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002391 result = kInputs_Requirement;
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002392 } else if (modifiers.fFlags & Modifiers::kOut_Flag) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002393 result = kOutputs_Requirement;
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002394 } else if (modifiers.fFlags & Modifiers::kUniform_Flag &&
Ethan Nicholas78686922020-10-08 06:46:27 -04002395 v.variable()->type().typeKind() != Type::TypeKind::kSampler) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002396 result = kUniforms_Requirement;
Timothy Liangee84fe12018-05-18 14:38:19 -04002397 } else {
2398 result = kGlobals_Requirement;
Ethan Nicholascc305772017-10-13 16:17:45 -04002399 }
2400 }
2401 return result;
2402 }
2403 default:
2404 return kNo_Requirements;
2405 }
2406}
2407
Ethan Nicholasff350cb2020-05-14 14:05:13 -04002408MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const Statement* s) {
2409 if (!s) {
2410 return kNo_Requirements;
2411 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002412 switch (s->kind()) {
2413 case Statement::Kind::kBlock: {
Ethan Nicholascc305772017-10-13 16:17:45 -04002414 Requirements result = kNo_Requirements;
Ethan Nicholas7bd60432020-09-25 14:31:59 -04002415 for (const std::unique_ptr<Statement>& child : s->as<Block>().children()) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04002416 result |= this->requirements(child.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002417 }
2418 return result;
2419 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002420 case Statement::Kind::kVarDeclaration: {
John Stiles3dc0da62020-08-19 17:48:31 -04002421 const VarDeclaration& var = s->as<VarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04002422 return this->requirements(var.value().get());
Timothy Liang7d637782018-06-05 09:58:07 -04002423 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002424 case Statement::Kind::kExpression:
Ethan Nicholasd503a5a2020-09-30 09:29:55 -04002425 return this->requirements(s->as<ExpressionStatement>().expression().get());
Ethan Nicholase6592142020-09-08 10:22:09 -04002426 case Statement::Kind::kReturn: {
John Stiles3dc0da62020-08-19 17:48:31 -04002427 const ReturnStatement& r = s->as<ReturnStatement>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04002428 return this->requirements(r.expression().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002429 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002430 case Statement::Kind::kIf: {
John Stiles3dc0da62020-08-19 17:48:31 -04002431 const IfStatement& i = s->as<IfStatement>();
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04002432 return this->requirements(i.test().get()) |
2433 this->requirements(i.ifTrue().get()) |
2434 this->requirements(i.ifFalse().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002435 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002436 case Statement::Kind::kFor: {
John Stiles3dc0da62020-08-19 17:48:31 -04002437 const ForStatement& f = s->as<ForStatement>();
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04002438 return this->requirements(f.initializer().get()) |
2439 this->requirements(f.test().get()) |
2440 this->requirements(f.next().get()) |
2441 this->requirements(f.statement().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002442 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002443 case Statement::Kind::kDo: {
John Stiles3dc0da62020-08-19 17:48:31 -04002444 const DoStatement& d = s->as<DoStatement>();
Ethan Nicholas1fd61162020-09-28 13:14:19 -04002445 return this->requirements(d.test().get()) |
2446 this->requirements(d.statement().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002447 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002448 case Statement::Kind::kSwitch: {
John Stiles3dc0da62020-08-19 17:48:31 -04002449 const SwitchStatement& sw = s->as<SwitchStatement>();
Ethan Nicholas01b05e52020-10-22 15:53:41 -04002450 Requirements result = this->requirements(sw.value().get());
John Stilesb23a64b2021-03-11 08:27:59 -05002451 for (const std::unique_ptr<Statement>& sc : sw.cases()) {
2452 result |= this->requirements(sc->as<SwitchCase>().statement().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002453 }
2454 return result;
2455 }
2456 default:
2457 return kNo_Requirements;
2458 }
2459}
2460
2461MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const FunctionDeclaration& f) {
Ethan Nicholased84b732020-10-08 11:45:44 -04002462 if (f.isBuiltin()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002463 return kNo_Requirements;
2464 }
2465 auto found = fRequirements.find(&f);
2466 if (found == fRequirements.end()) {
Ethan Nicholas65a8f562019-04-19 14:00:26 -04002467 fRequirements[&f] = kNo_Requirements;
Brian Osman133724c2020-10-28 14:14:39 -04002468 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04002469 if (e->is<FunctionDefinition>()) {
2470 const FunctionDefinition& def = e->as<FunctionDefinition>();
Ethan Nicholas0a5d0962020-10-14 13:33:18 -04002471 if (&def.declaration() == &f) {
2472 Requirements reqs = this->requirements(def.body().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002473 fRequirements[&f] = reqs;
2474 return reqs;
2475 }
2476 }
2477 }
John Stiles569249b2020-11-03 12:18:22 -05002478 // We never found a definition for this declared function, but it's legal to prototype a
2479 // function without ever giving a definition, as long as you don't call it.
2480 return kNo_Requirements;
Ethan Nicholascc305772017-10-13 16:17:45 -04002481 }
2482 return found->second;
2483}
2484
Timothy Liangb8eeb802018-07-23 16:46:16 -04002485bool MetalCodeGenerator::generateCode() {
John Stiles44532372020-12-07 12:33:55 -05002486 StringStream header;
2487 {
2488 AutoOutputStream outputToHeader(this, &header, &fIndentation);
Michael Ludwigbf58add2021-03-16 10:40:11 -04002489 this->writeHeader();
John Stiles44532372020-12-07 12:33:55 -05002490 this->writeStructDefinitions();
2491 this->writeUniformStruct();
2492 this->writeInputStruct();
2493 this->writeOutputStruct();
2494 this->writeInterfaceBlocks();
2495 this->writeGlobalStruct();
2496 }
2497 StringStream body;
2498 {
2499 AutoOutputStream outputToBody(this, &body, &fIndentation);
2500 for (const ProgramElement* e : fProgram.elements()) {
2501 this->writeProgramElement(*e);
2502 }
2503 }
2504 write_stringstream(header, *fOut);
2505 write_stringstream(fExtraFunctions, *fOut);
2506 write_stringstream(body, *fOut);
Brian Osman8609a242020-09-08 14:01:49 -04002507 return 0 == fErrors.errorCount();
Ethan Nicholascc305772017-10-13 16:17:45 -04002508}
2509
John Stilesa6841be2020-08-06 14:11:56 -04002510} // namespace SkSL