blob: 79bea71f59310eb33e4571eb15d6dce2d5f154e1 [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 Stiles7cbe66b2021-05-12 17:01:23 -04001415 this->write(OperatorName(op.removeAssignment()));
Ethan Nicholascc305772017-10-13 16:17:45 -04001416 this->write(" ");
1417 } else {
John Stilesd6449e92020-11-30 09:13:23 -05001418 this->write(String(" ") + OperatorName(op) + " ");
Ethan Nicholascc305772017-10-13 16:17:45 -04001419 }
John Stiles6b131292021-05-12 17:12:21 -04001420
1421 needMatrixSplatOnScalar = leftType.isMatrix() && rightType.isScalar() &&
1422 op.removeAssignment().kind() != Token::Kind::TK_STAR;
1423 if (needMatrixSplatOnScalar) {
1424 this->writeNumberAsMatrix(right, leftType);
1425 } else {
1426 this->writeExpression(right, precedence);
1427 }
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001428 if (needParens) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001429 this->write(")");
1430 }
1431}
1432
1433void MetalCodeGenerator::writeTernaryExpression(const TernaryExpression& t,
1434 Precedence parentPrecedence) {
Brian Osman00185012021-02-04 16:07:11 -05001435 if (Precedence::kTernary >= parentPrecedence) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001436 this->write("(");
1437 }
Brian Osman00185012021-02-04 16:07:11 -05001438 this->writeExpression(*t.test(), Precedence::kTernary);
Ethan Nicholascc305772017-10-13 16:17:45 -04001439 this->write(" ? ");
Brian Osman00185012021-02-04 16:07:11 -05001440 this->writeExpression(*t.ifTrue(), Precedence::kTernary);
Ethan Nicholascc305772017-10-13 16:17:45 -04001441 this->write(" : ");
Brian Osman00185012021-02-04 16:07:11 -05001442 this->writeExpression(*t.ifFalse(), Precedence::kTernary);
1443 if (Precedence::kTernary >= parentPrecedence) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001444 this->write(")");
1445 }
1446}
1447
1448void MetalCodeGenerator::writePrefixExpression(const PrefixExpression& p,
1449 Precedence parentPrecedence) {
Brian Osman00185012021-02-04 16:07:11 -05001450 if (Precedence::kPrefix >= parentPrecedence) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001451 this->write("(");
1452 }
John Stilesd6449e92020-11-30 09:13:23 -05001453 this->write(OperatorName(p.getOperator()));
Brian Osman00185012021-02-04 16:07:11 -05001454 this->writeExpression(*p.operand(), Precedence::kPrefix);
1455 if (Precedence::kPrefix >= parentPrecedence) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001456 this->write(")");
1457 }
1458}
1459
1460void MetalCodeGenerator::writePostfixExpression(const PostfixExpression& p,
1461 Precedence parentPrecedence) {
Brian Osman00185012021-02-04 16:07:11 -05001462 if (Precedence::kPostfix >= parentPrecedence) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001463 this->write("(");
1464 }
Brian Osman00185012021-02-04 16:07:11 -05001465 this->writeExpression(*p.operand(), Precedence::kPostfix);
John Stilesd6449e92020-11-30 09:13:23 -05001466 this->write(OperatorName(p.getOperator()));
Brian Osman00185012021-02-04 16:07:11 -05001467 if (Precedence::kPostfix >= parentPrecedence) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001468 this->write(")");
1469 }
1470}
1471
1472void MetalCodeGenerator::writeBoolLiteral(const BoolLiteral& b) {
Ethan Nicholas59d660c2020-09-28 09:18:15 -04001473 this->write(b.value() ? "true" : "false");
Ethan Nicholascc305772017-10-13 16:17:45 -04001474}
1475
1476void MetalCodeGenerator::writeIntLiteral(const IntLiteral& i) {
John Stiles12739df2020-12-29 09:47:20 -05001477 const Type& type = i.type();
John Stiles54e7c052021-01-11 14:22:36 -05001478 if (type == *fContext.fTypes.fUInt) {
Ethan Nicholase96cdd12020-09-28 16:27:18 -04001479 this->write(to_string(i.value() & 0xffffffff) + "u");
John Stiles54e7c052021-01-11 14:22:36 -05001480 } else if (type == *fContext.fTypes.fUShort) {
John Stiles12739df2020-12-29 09:47:20 -05001481 this->write(to_string(i.value() & 0xffff) + "u");
Ethan Nicholascc305772017-10-13 16:17:45 -04001482 } else {
John Stiles12739df2020-12-29 09:47:20 -05001483 this->write(to_string(i.value()));
Ethan Nicholascc305772017-10-13 16:17:45 -04001484 }
1485}
1486
1487void MetalCodeGenerator::writeFloatLiteral(const FloatLiteral& f) {
Ethan Nicholasa3f22f12020-10-01 12:13:17 -04001488 this->write(to_string(f.value()));
Ethan Nicholascc305772017-10-13 16:17:45 -04001489}
1490
1491void MetalCodeGenerator::writeSetting(const Setting& s) {
John Stilesf57207b2021-02-02 17:50:34 -05001492 SK_ABORT("internal error; setting was not folded to a constant during compilation\n");
Ethan Nicholascc305772017-10-13 16:17:45 -04001493}
1494
John Stiles06b84ef2020-12-09 12:35:48 -05001495void MetalCodeGenerator::writeFunctionRequirementArgs(const FunctionDeclaration& f,
1496 const char*& separator) {
1497 Requirements requirements = this->requirements(f);
1498 if (requirements & kInputs_Requirement) {
1499 this->write(separator);
1500 this->write("_in");
1501 separator = ", ";
1502 }
1503 if (requirements & kOutputs_Requirement) {
1504 this->write(separator);
1505 this->write("_out");
1506 separator = ", ";
1507 }
1508 if (requirements & kUniforms_Requirement) {
1509 this->write(separator);
1510 this->write("_uniforms");
1511 separator = ", ";
1512 }
1513 if (requirements & kGlobals_Requirement) {
1514 this->write(separator);
John Stilesf7410bd2021-01-19 13:07:55 -05001515 this->write("_globals");
John Stiles06b84ef2020-12-09 12:35:48 -05001516 separator = ", ";
1517 }
1518 if (requirements & kFragCoord_Requirement) {
1519 this->write(separator);
1520 this->write("_fragCoord");
1521 separator = ", ";
1522 }
1523}
1524
1525void MetalCodeGenerator::writeFunctionRequirementParams(const FunctionDeclaration& f,
1526 const char*& separator) {
1527 Requirements requirements = this->requirements(f);
1528 if (requirements & kInputs_Requirement) {
1529 this->write(separator);
1530 this->write("Inputs _in");
1531 separator = ", ";
1532 }
1533 if (requirements & kOutputs_Requirement) {
1534 this->write(separator);
John Stilesf7410bd2021-01-19 13:07:55 -05001535 this->write("thread Outputs& _out");
John Stiles06b84ef2020-12-09 12:35:48 -05001536 separator = ", ";
1537 }
1538 if (requirements & kUniforms_Requirement) {
1539 this->write(separator);
1540 this->write("Uniforms _uniforms");
1541 separator = ", ";
1542 }
1543 if (requirements & kGlobals_Requirement) {
1544 this->write(separator);
John Stilesf7410bd2021-01-19 13:07:55 -05001545 this->write("thread Globals& _globals");
John Stiles06b84ef2020-12-09 12:35:48 -05001546 separator = ", ";
1547 }
1548 if (requirements & kFragCoord_Requirement) {
1549 this->write(separator);
1550 this->write("float4 _fragCoord");
1551 separator = ", ";
1552 }
1553}
1554
John Stilesda5cdf62021-01-28 11:47:29 -05001555int MetalCodeGenerator::getUniformBinding(const Modifiers& m) {
1556 return (m.fLayout.fBinding >= 0) ? m.fLayout.fBinding
John Stiles270cec22021-02-17 12:59:36 -05001557 : fProgram.fConfig->fSettings.fDefaultUniformBinding;
John Stilesda5cdf62021-01-28 11:47:29 -05001558}
1559
1560int MetalCodeGenerator::getUniformSet(const Modifiers& m) {
1561 return (m.fLayout.fSet >= 0) ? m.fLayout.fSet
John Stiles270cec22021-02-17 12:59:36 -05001562 : fProgram.fConfig->fSettings.fDefaultUniformSet;
John Stilesda5cdf62021-01-28 11:47:29 -05001563}
1564
John Stiles569249b2020-11-03 12:18:22 -05001565bool MetalCodeGenerator::writeFunctionDeclaration(const FunctionDeclaration& f) {
John Stilesf7410bd2021-01-19 13:07:55 -05001566 fRTHeightName = fProgram.fInputs.fRTHeight ? "_globals._anonInterface0->u_skRTHeight" : "";
Ethan Nicholascc305772017-10-13 16:17:45 -04001567 const char* separator = "";
John Stilese8da4d22021-03-24 09:19:45 -04001568 if (f.isMain()) {
John Stiles270cec22021-02-17 12:59:36 -05001569 switch (fProgram.fConfig->fKind) {
John Stilesdbd4e6f2021-02-16 13:29:15 -05001570 case ProgramKind::kFragment:
Timothy Liangb8eeb802018-07-23 16:46:16 -04001571 this->write("fragment Outputs fragmentMain");
Ethan Nicholascc305772017-10-13 16:17:45 -04001572 break;
John Stilesdbd4e6f2021-02-16 13:29:15 -05001573 case ProgramKind::kVertex:
Timothy Liangb8eeb802018-07-23 16:46:16 -04001574 this->write("vertex Outputs vertexMain");
Ethan Nicholascc305772017-10-13 16:17:45 -04001575 break;
1576 default:
John Stiles3fabfc02020-09-25 15:51:28 -04001577 fErrors.error(-1, "unsupported kind of program");
John Stiles569249b2020-11-03 12:18:22 -05001578 return false;
Ethan Nicholascc305772017-10-13 16:17:45 -04001579 }
1580 this->write("(Inputs _in [[stage_in]]");
1581 if (-1 != fUniformBuffer) {
1582 this->write(", constant Uniforms& _uniforms [[buffer(" +
1583 to_string(fUniformBuffer) + ")]]");
1584 }
Brian Osman133724c2020-10-28 14:14:39 -04001585 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04001586 if (e->is<GlobalVarDeclaration>()) {
1587 const GlobalVarDeclaration& decls = e->as<GlobalVarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001588 const VarDeclaration& var = decls.declaration()->as<VarDeclaration>();
1589 if (var.var().type().typeKind() == Type::TypeKind::kSampler) {
1590 if (var.var().modifiers().fLayout.fBinding < 0) {
Brian Osmanc0213602020-10-06 14:43:32 -04001591 fErrors.error(decls.fOffset,
John Stilesb41d5bb2021-01-26 16:28:12 -05001592 "Metal samplers must have 'layout(binding=...)'");
John Stiles569249b2020-11-03 12:18:22 -05001593 return false;
Timothy Liangee84fe12018-05-18 14:38:19 -04001594 }
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001595 if (var.var().type().dimensions() != SpvDim2D) {
John Stiles569249b2020-11-03 12:18:22 -05001596 // Not yet implemented--Skia currently only uses 2D textures.
Brian Osmanc0213602020-10-06 14:43:32 -04001597 fErrors.error(decls.fOffset, "Unsupported texture dimensions");
John Stiles569249b2020-11-03 12:18:22 -05001598 return false;
Brian Osmanc0213602020-10-06 14:43:32 -04001599 }
1600 this->write(", texture2d<float> ");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001601 this->writeName(var.var().name());
Brian Osmanc0213602020-10-06 14:43:32 -04001602 this->write("[[texture(");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001603 this->write(to_string(var.var().modifiers().fLayout.fBinding));
Brian Osmanc0213602020-10-06 14:43:32 -04001604 this->write(")]]");
1605 this->write(", sampler ");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001606 this->writeName(var.var().name());
Brian Osmanc0213602020-10-06 14:43:32 -04001607 this->write(SAMPLER_SUFFIX);
1608 this->write("[[sampler(");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001609 this->write(to_string(var.var().modifiers().fLayout.fBinding));
Brian Osmanc0213602020-10-06 14:43:32 -04001610 this->write(")]]");
Timothy Liang6403b0e2018-05-17 10:40:04 -04001611 }
Brian Osman1179fcf2020-10-08 16:04:40 -04001612 } else if (e->is<InterfaceBlock>()) {
1613 const InterfaceBlock& intf = e->as<InterfaceBlock>();
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001614 if (intf.typeName() == "sk_PerVertex") {
Timothy Lianga06f2152018-05-24 15:33:31 -04001615 continue;
1616 }
1617 this->write(", constant ");
John Stilesb4418502021-02-04 10:57:08 -05001618 this->writeType(intf.variable().type());
Timothy Lianga06f2152018-05-24 15:33:31 -04001619 this->write("& " );
1620 this->write(fInterfaceBlockNameMap[&intf]);
1621 this->write(" [[buffer(");
John Stilesda5cdf62021-01-28 11:47:29 -05001622 this->write(to_string(this->getUniformBinding(intf.variable().modifiers())));
Timothy Lianga06f2152018-05-24 15:33:31 -04001623 this->write(")]]");
Timothy Liang6403b0e2018-05-17 10:40:04 -04001624 }
1625 }
John Stiles270cec22021-02-17 12:59:36 -05001626 if (fProgram.fConfig->fKind == ProgramKind::kFragment) {
Jim Van Verth6bc650e2019-02-07 14:53:23 -05001627 if (fProgram.fInputs.fRTHeight && fInterfaceBlockNameMap.empty()) {
Timothy Liang5422f9a2018-08-10 10:57:55 -04001628 this->write(", constant sksl_synthetic_uniforms& _anonInterface0 [[buffer(1)]]");
Ethan Nicholasf931e402019-07-26 15:40:33 -04001629 fRTHeightName = "_anonInterface0.u_skRTHeight";
Timothy Liang5422f9a2018-08-10 10:57:55 -04001630 }
Timothy Liang7b8875d2018-08-10 09:42:31 -04001631 this->write(", bool _frontFacing [[front_facing]]");
Timothy Liang7d637782018-06-05 09:58:07 -04001632 this->write(", float4 _fragCoord [[position]]");
John Stiles270cec22021-02-17 12:59:36 -05001633 } else if (fProgram.fConfig->fKind == ProgramKind::kVertex) {
Timothy Liangdc89f192018-06-13 09:20:31 -04001634 this->write(", uint sk_VertexID [[vertex_id]], uint sk_InstanceID [[instance_id]]");
Timothy Liang7d637782018-06-05 09:58:07 -04001635 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001636 separator = ", ";
1637 } else {
John Stilesb4418502021-02-04 10:57:08 -05001638 this->writeType(f.returnType());
Timothy Liang651286f2018-06-07 09:55:33 -04001639 this->write(" ");
John Stilese1068342021-03-22 11:57:41 -04001640 this->writeName(f.mangledName());
Timothy Liang651286f2018-06-07 09:55:33 -04001641 this->write("(");
John Stiles06b84ef2020-12-09 12:35:48 -05001642 this->writeFunctionRequirementParams(f, separator);
Ethan Nicholascc305772017-10-13 16:17:45 -04001643 }
John Stiles569249b2020-11-03 12:18:22 -05001644 for (const auto& param : f.parameters()) {
Brian Osman716aeb92021-04-21 13:20:00 -04001645 if (f.isMain() && param->modifiers().fLayout.fBuiltin != -1) {
1646 continue;
1647 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001648 this->write(separator);
1649 separator = ", ";
John Stiles06b84ef2020-12-09 12:35:48 -05001650 this->writeModifiers(param->modifiers(), /*globalContext=*/false);
Ethan Nicholas30d30222020-09-11 12:27:26 -04001651 const Type* type = &param->type();
John Stilesb4418502021-02-04 10:57:08 -05001652 this->writeType(*type);
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001653 if (param->modifiers().fFlags & Modifiers::kOut_Flag) {
John Stilesf2bd5012020-12-04 11:58:26 -05001654 this->write("&");
Ethan Nicholascc305772017-10-13 16:17:45 -04001655 }
Timothy Liang651286f2018-06-07 09:55:33 -04001656 this->write(" ");
Ethan Nicholase2c49992020-10-05 11:49:11 -04001657 this->writeName(param->name());
Ethan Nicholascc305772017-10-13 16:17:45 -04001658 }
John Stiles569249b2020-11-03 12:18:22 -05001659 this->write(")");
1660 return true;
1661}
Ethan Nicholascc305772017-10-13 16:17:45 -04001662
John Stiles569249b2020-11-03 12:18:22 -05001663void MetalCodeGenerator::writeFunctionPrototype(const FunctionPrototype& f) {
1664 this->writeFunctionDeclaration(f.declaration());
1665 this->writeLine(";");
1666}
1667
John Stiles986c7fb2020-12-01 14:44:56 -05001668static bool is_block_ending_with_return(const Statement* stmt) {
1669 // This function detects (potentially nested) blocks that end in a return statement.
1670 if (!stmt->is<Block>()) {
1671 return false;
1672 }
1673 const StatementArray& block = stmt->as<Block>().children();
1674 for (int index = block.count(); index--; ) {
1675 const Statement& stmt = *block[index];
1676 if (stmt.is<ReturnStatement>()) {
1677 return true;
1678 }
1679 if (stmt.is<Block>()) {
1680 return is_block_ending_with_return(&stmt);
1681 }
1682 if (!stmt.is<Nop>()) {
1683 break;
1684 }
1685 }
1686 return false;
1687}
1688
John Stiles569249b2020-11-03 12:18:22 -05001689void MetalCodeGenerator::writeFunction(const FunctionDefinition& f) {
John Stiles270cec22021-02-17 12:59:36 -05001690 SkASSERT(!fProgram.fConfig->fSettings.fFragColorIsInOut);
Brian Salomondc092132018-04-04 10:14:16 -04001691
John Stiles569249b2020-11-03 12:18:22 -05001692 if (!this->writeFunctionDeclaration(f.declaration())) {
1693 return;
1694 }
1695
John Stiles986c7fb2020-12-01 14:44:56 -05001696 fCurrentFunction = &f.declaration();
1697 SkScopeExit clearCurrentFunction([&] { fCurrentFunction = nullptr; });
1698
John Stiles569249b2020-11-03 12:18:22 -05001699 this->writeLine(" {");
1700
John Stilese8da4d22021-03-24 09:19:45 -04001701 if (f.declaration().isMain()) {
John Stilescdcdb042020-07-06 09:03:51 -04001702 this->writeGlobalInit();
John Stilesf7410bd2021-01-19 13:07:55 -05001703 this->writeLine(" Outputs _out;");
John Stiles37279172021-01-21 22:24:28 -05001704 this->writeLine(" (void)_out;");
Ethan Nicholascc305772017-10-13 16:17:45 -04001705 }
John Stilesc67b3622020-05-28 17:53:13 -04001706
John Stiles95680232021-04-22 15:05:20 -04001707 fFunctionHeader.clear();
Ethan Nicholascc305772017-10-13 16:17:45 -04001708 StringStream buffer;
John Stiles44532372020-12-07 12:33:55 -05001709 {
1710 AutoOutputStream outputToBuffer(this, &buffer);
1711 fIndentation++;
1712 for (const std::unique_ptr<Statement>& stmt : f.body()->as<Block>().children()) {
1713 if (!stmt->isEmpty()) {
1714 this->writeStatement(*stmt);
John Stilese8b5a732021-03-12 13:25:52 -05001715 this->finishLine();
John Stiles44532372020-12-07 12:33:55 -05001716 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001717 }
John Stilese8da4d22021-03-24 09:19:45 -04001718 if (f.declaration().isMain()) {
John Stiles44532372020-12-07 12:33:55 -05001719 // If the main function doesn't end with a return, we need to synthesize one here.
1720 if (!is_block_ending_with_return(f.body().get())) {
1721 this->writeReturnStatementFromMain();
John Stilese8b5a732021-03-12 13:25:52 -05001722 this->finishLine();
John Stiles44532372020-12-07 12:33:55 -05001723 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001724 }
John Stiles44532372020-12-07 12:33:55 -05001725 fIndentation--;
1726 this->writeLine("}");
Ethan Nicholascc305772017-10-13 16:17:45 -04001727 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001728 this->write(fFunctionHeader);
1729 this->write(buffer.str());
1730}
1731
1732void MetalCodeGenerator::writeModifiers(const Modifiers& modifiers,
John Stiles06b84ef2020-12-09 12:35:48 -05001733 bool globalContext) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001734 if (modifiers.fFlags & Modifiers::kOut_Flag) {
1735 this->write("thread ");
1736 }
1737 if (modifiers.fFlags & Modifiers::kConst_Flag) {
John Stiles0bd55782021-02-09 18:29:40 -05001738 this->write("const ");
Ethan Nicholascc305772017-10-13 16:17:45 -04001739 }
1740}
1741
1742void MetalCodeGenerator::writeInterfaceBlock(const InterfaceBlock& intf) {
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001743 if ("sk_PerVertex" == intf.typeName()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001744 return;
1745 }
John Stiles06b84ef2020-12-09 12:35:48 -05001746 this->writeModifiers(intf.variable().modifiers(), /*globalContext=*/true);
Timothy Liangdc89f192018-06-13 09:20:31 -04001747 this->write("struct ");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001748 this->writeLine(intf.typeName() + " {");
1749 const Type* structType = &intf.variable().type();
John Stilesbb43b7e2020-12-03 17:36:32 -05001750 if (structType->isArray()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001751 structType = &structType->componentType();
1752 }
Timothy Liangdc89f192018-06-13 09:20:31 -04001753 fIndentation++;
John Stiles3dba3ee2020-12-02 23:35:49 -05001754 this->writeFields(structType->fields(), structType->fOffset, &intf);
Jim Van Verth3d482992019-02-07 10:48:05 -05001755 if (fProgram.fInputs.fRTHeight) {
Timothy Liang7d637782018-06-05 09:58:07 -04001756 this->writeLine("float u_skRTHeight;");
Ethan Nicholascc305772017-10-13 16:17:45 -04001757 }
1758 fIndentation--;
1759 this->write("}");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001760 if (intf.instanceName().size()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001761 this->write(" ");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001762 this->write(intf.instanceName());
John Stilesd39aec02020-12-03 10:42:26 -05001763 if (intf.arraySize() > 0) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001764 this->write("[");
John Stilesd39aec02020-12-03 10:42:26 -05001765 this->write(to_string(intf.arraySize()));
Ethan Nicholascc305772017-10-13 16:17:45 -04001766 this->write("]");
John Stilesd39aec02020-12-03 10:42:26 -05001767 } else if (intf.arraySize() == Type::kUnsizedArray){
1768 this->write("[]");
Ethan Nicholascc305772017-10-13 16:17:45 -04001769 }
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001770 fInterfaceBlockNameMap[&intf] = intf.instanceName();
Timothy Lianga06f2152018-05-24 15:33:31 -04001771 } else {
Timothy Liang7d637782018-06-05 09:58:07 -04001772 fInterfaceBlockNameMap[&intf] = "_anonInterface" + to_string(fAnonInterfaceCount++);
Ethan Nicholascc305772017-10-13 16:17:45 -04001773 }
1774 this->writeLine(";");
1775}
1776
Timothy Liangdc89f192018-06-13 09:20:31 -04001777void MetalCodeGenerator::writeFields(const std::vector<Type::Field>& fields, int parentOffset,
1778 const InterfaceBlock* parentIntf) {
Timothy Liang609fbe32018-08-10 16:40:49 -04001779 MemoryLayout memoryLayout(MemoryLayout::kMetal_Standard);
Timothy Liangdc89f192018-06-13 09:20:31 -04001780 int currentOffset = 0;
John Stiles39346472021-04-29 14:39:35 -04001781 for (const Type::Field& field : fields) {
Timothy Liangdc89f192018-06-13 09:20:31 -04001782 int fieldOffset = field.fModifiers.fLayout.fOffset;
1783 const Type* fieldType = field.fType;
John Stiles21f5f452020-11-30 09:57:59 -05001784 if (!MemoryLayout::LayoutIsSupported(*fieldType)) {
John Stiles0023c0c2020-11-16 13:32:18 -05001785 fErrors.error(parentOffset, "type '" + fieldType->name() + "' is not permitted here");
1786 return;
1787 }
Timothy Liangdc89f192018-06-13 09:20:31 -04001788 if (fieldOffset != -1) {
1789 if (currentOffset > fieldOffset) {
1790 fErrors.error(parentOffset,
John Stilesd7199b22020-12-30 16:22:58 -05001791 "offset of field '" + field.fName + "' must be at least " +
1792 to_string((int) currentOffset));
Brian Osman8609a242020-09-08 14:01:49 -04001793 return;
Timothy Liangdc89f192018-06-13 09:20:31 -04001794 } else if (currentOffset < fieldOffset) {
1795 this->write("char pad");
1796 this->write(to_string(fPaddingCount++));
1797 this->write("[");
1798 this->write(to_string(fieldOffset - currentOffset));
1799 this->writeLine("];");
1800 currentOffset = fieldOffset;
1801 }
1802 int alignment = memoryLayout.alignment(*fieldType);
1803 if (fieldOffset % alignment) {
1804 fErrors.error(parentOffset,
1805 "offset of field '" + field.fName + "' must be a multiple of " +
1806 to_string((int) alignment));
Brian Osman8609a242020-09-08 14:01:49 -04001807 return;
Timothy Liangdc89f192018-06-13 09:20:31 -04001808 }
1809 }
Brian Osman8609a242020-09-08 14:01:49 -04001810 size_t fieldSize = memoryLayout.size(*fieldType);
1811 if (fieldSize > static_cast<size_t>(std::numeric_limits<int>::max() - currentOffset)) {
1812 fErrors.error(parentOffset, "field offset overflow");
1813 return;
1814 }
1815 currentOffset += fieldSize;
John Stiles06b84ef2020-12-09 12:35:48 -05001816 this->writeModifiers(field.fModifiers, /*globalContext=*/false);
John Stilesb4418502021-02-04 10:57:08 -05001817 this->writeType(*fieldType);
Timothy Liangdc89f192018-06-13 09:20:31 -04001818 this->write(" ");
1819 this->writeName(field.fName);
Timothy Liangdc89f192018-06-13 09:20:31 -04001820 this->writeLine(";");
1821 if (parentIntf) {
1822 fInterfaceBlockMap[&field] = parentIntf;
1823 }
1824 }
1825}
1826
Ethan Nicholascc305772017-10-13 16:17:45 -04001827void MetalCodeGenerator::writeVarInitializer(const Variable& var, const Expression& value) {
Brian Osman00185012021-02-04 16:07:11 -05001828 this->writeExpression(value, Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001829}
1830
Timothy Liang651286f2018-06-07 09:55:33 -04001831void MetalCodeGenerator::writeName(const String& name) {
1832 if (fReservedWords.find(name) != fReservedWords.end()) {
1833 this->write("_"); // adding underscore before name to avoid conflict with reserved words
1834 }
1835 this->write(name);
1836}
1837
John Stilesb4418502021-02-04 10:57:08 -05001838void MetalCodeGenerator::writeVarDeclaration(const VarDeclaration& varDecl, bool global) {
1839 if (global && !(varDecl.var().modifiers().fFlags & Modifiers::kConst_Flag)) {
Brian Osmanc0213602020-10-06 14:43:32 -04001840 return;
Ethan Nicholascc305772017-10-13 16:17:45 -04001841 }
John Stilesb4418502021-02-04 10:57:08 -05001842 this->writeModifiers(varDecl.var().modifiers(), global);
1843 this->writeType(varDecl.var().type());
Brian Osmanc0213602020-10-06 14:43:32 -04001844 this->write(" ");
John Stilesb4418502021-02-04 10:57:08 -05001845 this->writeName(varDecl.var().name());
1846 if (varDecl.value()) {
Brian Osmanc0213602020-10-06 14:43:32 -04001847 this->write(" = ");
John Stilesb4418502021-02-04 10:57:08 -05001848 this->writeVarInitializer(varDecl.var(), *varDecl.value());
Brian Osmanc0213602020-10-06 14:43:32 -04001849 }
1850 this->write(";");
Ethan Nicholascc305772017-10-13 16:17:45 -04001851}
1852
1853void MetalCodeGenerator::writeStatement(const Statement& s) {
Ethan Nicholase6592142020-09-08 10:22:09 -04001854 switch (s.kind()) {
1855 case Statement::Kind::kBlock:
John Stiles26f98502020-08-18 09:30:51 -04001856 this->writeBlock(s.as<Block>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001857 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001858 case Statement::Kind::kExpression:
Brian Osman00185012021-02-04 16:07:11 -05001859 this->writeExpression(*s.as<ExpressionStatement>().expression(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001860 this->write(";");
1861 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001862 case Statement::Kind::kReturn:
John Stiles26f98502020-08-18 09:30:51 -04001863 this->writeReturnStatement(s.as<ReturnStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001864 break;
Brian Osmanc0213602020-10-06 14:43:32 -04001865 case Statement::Kind::kVarDeclaration:
1866 this->writeVarDeclaration(s.as<VarDeclaration>(), false);
Ethan Nicholascc305772017-10-13 16:17:45 -04001867 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001868 case Statement::Kind::kIf:
John Stiles26f98502020-08-18 09:30:51 -04001869 this->writeIfStatement(s.as<IfStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001870 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001871 case Statement::Kind::kFor:
John Stiles26f98502020-08-18 09:30:51 -04001872 this->writeForStatement(s.as<ForStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001873 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001874 case Statement::Kind::kDo:
John Stiles26f98502020-08-18 09:30:51 -04001875 this->writeDoStatement(s.as<DoStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001876 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001877 case Statement::Kind::kSwitch:
John Stiles26f98502020-08-18 09:30:51 -04001878 this->writeSwitchStatement(s.as<SwitchStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001879 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001880 case Statement::Kind::kBreak:
Ethan Nicholascc305772017-10-13 16:17:45 -04001881 this->write("break;");
1882 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001883 case Statement::Kind::kContinue:
Ethan Nicholascc305772017-10-13 16:17:45 -04001884 this->write("continue;");
1885 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001886 case Statement::Kind::kDiscard:
Timothy Lianga06f2152018-05-24 15:33:31 -04001887 this->write("discard_fragment();");
Ethan Nicholascc305772017-10-13 16:17:45 -04001888 break;
John Stiles98c1f822020-09-09 14:18:53 -04001889 case Statement::Kind::kInlineMarker:
Ethan Nicholase6592142020-09-08 10:22:09 -04001890 case Statement::Kind::kNop:
Ethan Nicholascc305772017-10-13 16:17:45 -04001891 this->write(";");
1892 break;
1893 default:
John Stileseada7bc2021-02-02 16:29:32 -05001894 SkDEBUGFAILF("unsupported statement: %s", s.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -05001895 break;
Ethan Nicholascc305772017-10-13 16:17:45 -04001896 }
1897}
1898
Ethan Nicholascc305772017-10-13 16:17:45 -04001899void MetalCodeGenerator::writeBlock(const Block& b) {
John Stiles3744bd62021-01-26 13:49:43 -05001900 // Write scope markers if this block is a scope, or if the block is empty (since we need to emit
1901 // something here to make the code valid).
1902 bool isScope = b.isScope() || b.isEmpty();
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001903 if (isScope) {
Ethan Nicholas70728ef2020-05-28 07:09:00 -04001904 this->writeLine("{");
1905 fIndentation++;
1906 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001907 for (const std::unique_ptr<Statement>& stmt : b.children()) {
1908 if (!stmt->isEmpty()) {
1909 this->writeStatement(*stmt);
John Stilese8b5a732021-03-12 13:25:52 -05001910 this->finishLine();
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001911 }
1912 }
1913 if (isScope) {
Ethan Nicholas70728ef2020-05-28 07:09:00 -04001914 fIndentation--;
1915 this->write("}");
1916 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001917}
1918
1919void MetalCodeGenerator::writeIfStatement(const IfStatement& stmt) {
1920 this->write("if (");
Brian Osman00185012021-02-04 16:07:11 -05001921 this->writeExpression(*stmt.test(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001922 this->write(") ");
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04001923 this->writeStatement(*stmt.ifTrue());
1924 if (stmt.ifFalse()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001925 this->write(" else ");
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04001926 this->writeStatement(*stmt.ifFalse());
Ethan Nicholascc305772017-10-13 16:17:45 -04001927 }
1928}
1929
1930void MetalCodeGenerator::writeForStatement(const ForStatement& f) {
Brian Osmand6f23382020-12-15 17:08:59 -05001931 // Emit loops of the form 'for(;test;)' as 'while(test)', which is probably how they started
1932 if (!f.initializer() && f.test() && !f.next()) {
1933 this->write("while (");
Brian Osman00185012021-02-04 16:07:11 -05001934 this->writeExpression(*f.test(), Precedence::kTopLevel);
Brian Osmand6f23382020-12-15 17:08:59 -05001935 this->write(") ");
1936 this->writeStatement(*f.statement());
1937 return;
1938 }
1939
John Stiles1a15e572021-04-19 14:57:15 -04001940 this->write("for (");
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04001941 if (f.initializer() && !f.initializer()->isEmpty()) {
John Stiles1a15e572021-04-19 14:57:15 -04001942 this->writeStatement(*f.initializer());
Ethan Nicholascc305772017-10-13 16:17:45 -04001943 } else {
John Stiles1a15e572021-04-19 14:57:15 -04001944 this->write("; ");
Ethan Nicholascc305772017-10-13 16:17:45 -04001945 }
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04001946 if (f.test()) {
Brian Osman00185012021-02-04 16:07:11 -05001947 this->writeExpression(*f.test(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001948 }
1949 this->write("; ");
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04001950 if (f.next()) {
Brian Osman00185012021-02-04 16:07:11 -05001951 this->writeExpression(*f.next(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001952 }
1953 this->write(") ");
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04001954 this->writeStatement(*f.statement());
Ethan Nicholascc305772017-10-13 16:17:45 -04001955}
1956
Ethan Nicholascc305772017-10-13 16:17:45 -04001957void MetalCodeGenerator::writeDoStatement(const DoStatement& d) {
1958 this->write("do ");
Ethan Nicholas1fd61162020-09-28 13:14:19 -04001959 this->writeStatement(*d.statement());
Ethan Nicholascc305772017-10-13 16:17:45 -04001960 this->write(" while (");
Brian Osman00185012021-02-04 16:07:11 -05001961 this->writeExpression(*d.test(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001962 this->write(");");
1963}
1964
1965void MetalCodeGenerator::writeSwitchStatement(const SwitchStatement& s) {
1966 this->write("switch (");
Brian Osman00185012021-02-04 16:07:11 -05001967 this->writeExpression(*s.value(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001968 this->writeLine(") {");
1969 fIndentation++;
John Stilesb23a64b2021-03-11 08:27:59 -05001970 for (const std::unique_ptr<Statement>& stmt : s.cases()) {
1971 const SwitchCase& c = stmt->as<SwitchCase>();
1972 if (c.value()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001973 this->write("case ");
John Stilesb23a64b2021-03-11 08:27:59 -05001974 this->writeExpression(*c.value(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001975 this->writeLine(":");
1976 } else {
1977 this->writeLine("default:");
1978 }
John Stilesb23a64b2021-03-11 08:27:59 -05001979 if (!c.statement()->isEmpty()) {
John Stilesc3ce43b2021-03-09 15:37:01 -05001980 fIndentation++;
John Stilesb23a64b2021-03-11 08:27:59 -05001981 this->writeStatement(*c.statement());
John Stilese8b5a732021-03-12 13:25:52 -05001982 this->finishLine();
John Stilesc3ce43b2021-03-09 15:37:01 -05001983 fIndentation--;
Ethan Nicholascc305772017-10-13 16:17:45 -04001984 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001985 }
1986 fIndentation--;
1987 this->write("}");
1988}
1989
John Stiles986c7fb2020-12-01 14:44:56 -05001990void MetalCodeGenerator::writeReturnStatementFromMain() {
1991 // main functions in Metal return a magic _out parameter that doesn't exist in SkSL.
John Stiles270cec22021-02-17 12:59:36 -05001992 switch (fProgram.fConfig->fKind) {
John Stilesdbd4e6f2021-02-16 13:29:15 -05001993 case ProgramKind::kFragment:
John Stilesf7410bd2021-01-19 13:07:55 -05001994 this->write("return _out;");
John Stiles986c7fb2020-12-01 14:44:56 -05001995 break;
John Stilesdbd4e6f2021-02-16 13:29:15 -05001996 case ProgramKind::kVertex:
John Stilesf7410bd2021-01-19 13:07:55 -05001997 this->write("return (_out.sk_Position.y = -_out.sk_Position.y, _out);");
John Stiles986c7fb2020-12-01 14:44:56 -05001998 break;
1999 default:
2000 SkDEBUGFAIL("unsupported kind of program");
2001 }
2002}
2003
Ethan Nicholascc305772017-10-13 16:17:45 -04002004void MetalCodeGenerator::writeReturnStatement(const ReturnStatement& r) {
John Stilese8da4d22021-03-24 09:19:45 -04002005 if (fCurrentFunction && fCurrentFunction->isMain()) {
John Stiles986c7fb2020-12-01 14:44:56 -05002006 if (r.expression()) {
John Stiles97d18172021-01-22 16:47:42 -05002007 if (r.expression()->type() == *fContext.fTypes.fHalf4) {
2008 this->write("_out.sk_FragColor = ");
Brian Osman00185012021-02-04 16:07:11 -05002009 this->writeExpression(*r.expression(), Precedence::kTopLevel);
John Stiles97d18172021-01-22 16:47:42 -05002010 this->writeLine(";");
2011 } else {
2012 fErrors.error(r.fOffset, "Metal does not support returning '" +
2013 r.expression()->type().description() + "' from main()");
2014 }
John Stiles986c7fb2020-12-01 14:44:56 -05002015 }
2016 this->writeReturnStatementFromMain();
2017 return;
2018 }
2019
Ethan Nicholascc305772017-10-13 16:17:45 -04002020 this->write("return");
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04002021 if (r.expression()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002022 this->write(" ");
Brian Osman00185012021-02-04 16:07:11 -05002023 this->writeExpression(*r.expression(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04002024 }
2025 this->write(";");
2026}
2027
Michael Ludwigbf58add2021-03-16 10:40:11 -04002028void MetalCodeGenerator::writeHeader() {
2029 this->write("#include <metal_stdlib>\n");
2030 this->write("#include <simd/simd.h>\n");
2031 this->write("using namespace metal;\n");
2032}
2033
Ethan Nicholascc305772017-10-13 16:17:45 -04002034void MetalCodeGenerator::writeUniformStruct() {
Brian Osman133724c2020-10-28 14:14:39 -04002035 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04002036 if (e->is<GlobalVarDeclaration>()) {
2037 const GlobalVarDeclaration& decls = e->as<GlobalVarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04002038 const Variable& var = decls.declaration()->as<VarDeclaration>().var();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002039 if (var.modifiers().fFlags & Modifiers::kUniform_Flag &&
Brian Osmanc0213602020-10-06 14:43:32 -04002040 var.type().typeKind() != Type::TypeKind::kSampler) {
John Stilesda5cdf62021-01-28 11:47:29 -05002041 int uniformSet = this->getUniformSet(var.modifiers());
John Stilesd8fc95d2021-01-26 16:22:53 -05002042 // Make sure that the program's uniform-set value is consistent throughout.
Ethan Nicholascc305772017-10-13 16:17:45 -04002043 if (-1 == fUniformBuffer) {
2044 this->write("struct Uniforms {\n");
John Stilesd8fc95d2021-01-26 16:22:53 -05002045 fUniformBuffer = uniformSet;
2046 } else if (uniformSet != fUniformBuffer) {
2047 fErrors.error(decls.fOffset, "Metal backend requires all uniforms to have "
2048 "the same 'layout(set=...)'");
Ethan Nicholascc305772017-10-13 16:17:45 -04002049 }
2050 this->write(" ");
John Stilesb4418502021-02-04 10:57:08 -05002051 this->writeType(var.type());
Ethan Nicholascc305772017-10-13 16:17:45 -04002052 this->write(" ");
Brian Osmanc0213602020-10-06 14:43:32 -04002053 this->writeName(var.name());
Ethan Nicholascc305772017-10-13 16:17:45 -04002054 this->write(";\n");
2055 }
2056 }
2057 }
2058 if (-1 != fUniformBuffer) {
2059 this->write("};\n");
2060 }
2061}
2062
2063void MetalCodeGenerator::writeInputStruct() {
2064 this->write("struct Inputs {\n");
Brian Osman133724c2020-10-28 14:14:39 -04002065 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04002066 if (e->is<GlobalVarDeclaration>()) {
2067 const GlobalVarDeclaration& decls = e->as<GlobalVarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04002068 const Variable& var = decls.declaration()->as<VarDeclaration>().var();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002069 if (var.modifiers().fFlags & Modifiers::kIn_Flag &&
2070 -1 == var.modifiers().fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002071 this->write(" ");
John Stilesb4418502021-02-04 10:57:08 -05002072 this->writeType(var.type());
Ethan Nicholascc305772017-10-13 16:17:45 -04002073 this->write(" ");
Brian Osmanc0213602020-10-06 14:43:32 -04002074 this->writeName(var.name());
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002075 if (-1 != var.modifiers().fLayout.fLocation) {
John Stiles270cec22021-02-17 12:59:36 -05002076 if (fProgram.fConfig->fKind == ProgramKind::kVertex) {
Brian Osmanc0213602020-10-06 14:43:32 -04002077 this->write(" [[attribute(" +
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002078 to_string(var.modifiers().fLayout.fLocation) + ")]]");
John Stiles270cec22021-02-17 12:59:36 -05002079 } else if (fProgram.fConfig->fKind == ProgramKind::kFragment) {
Brian Osmanc0213602020-10-06 14:43:32 -04002080 this->write(" [[user(locn" +
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002081 to_string(var.modifiers().fLayout.fLocation) + ")]]");
Ethan Nicholascc305772017-10-13 16:17:45 -04002082 }
2083 }
2084 this->write(";\n");
2085 }
2086 }
2087 }
2088 this->write("};\n");
2089}
2090
2091void MetalCodeGenerator::writeOutputStruct() {
2092 this->write("struct Outputs {\n");
John Stiles270cec22021-02-17 12:59:36 -05002093 if (fProgram.fConfig->fKind == ProgramKind::kVertex) {
Timothy Liangb8eeb802018-07-23 16:46:16 -04002094 this->write(" float4 sk_Position [[position]];\n");
John Stiles270cec22021-02-17 12:59:36 -05002095 } else if (fProgram.fConfig->fKind == ProgramKind::kFragment) {
Timothy Liangde0be802018-08-10 13:48:08 -04002096 this->write(" float4 sk_FragColor [[color(0)]];\n");
Timothy Liang7d637782018-06-05 09:58:07 -04002097 }
Brian Osman133724c2020-10-28 14:14:39 -04002098 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04002099 if (e->is<GlobalVarDeclaration>()) {
2100 const GlobalVarDeclaration& decls = e->as<GlobalVarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04002101 const Variable& var = decls.declaration()->as<VarDeclaration>().var();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002102 if (var.modifiers().fFlags & Modifiers::kOut_Flag &&
2103 -1 == var.modifiers().fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002104 this->write(" ");
John Stilesb4418502021-02-04 10:57:08 -05002105 this->writeType(var.type());
Ethan Nicholascc305772017-10-13 16:17:45 -04002106 this->write(" ");
Brian Osmanc0213602020-10-06 14:43:32 -04002107 this->writeName(var.name());
John Stiles842b3592020-12-01 10:36:37 -05002108
2109 int location = var.modifiers().fLayout.fLocation;
2110 if (location < 0) {
2111 fErrors.error(var.fOffset,
2112 "Metal out variables must have 'layout(location=...)'");
John Stiles270cec22021-02-17 12:59:36 -05002113 } else if (fProgram.fConfig->fKind == ProgramKind::kVertex) {
John Stiles842b3592020-12-01 10:36:37 -05002114 this->write(" [[user(locn" + to_string(location) + ")]]");
John Stiles270cec22021-02-17 12:59:36 -05002115 } else if (fProgram.fConfig->fKind == ProgramKind::kFragment) {
John Stiles842b3592020-12-01 10:36:37 -05002116 this->write(" [[color(" + to_string(location) + ")");
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002117 int colorIndex = var.modifiers().fLayout.fIndex;
Brian Osmanc0213602020-10-06 14:43:32 -04002118 if (colorIndex) {
2119 this->write(", index(" + to_string(colorIndex) + ")");
Timothy Liang7d637782018-06-05 09:58:07 -04002120 }
Brian Osmanc0213602020-10-06 14:43:32 -04002121 this->write("]]");
Ethan Nicholascc305772017-10-13 16:17:45 -04002122 }
2123 this->write(";\n");
2124 }
2125 }
Timothy Liang7d637782018-06-05 09:58:07 -04002126 }
John Stiles270cec22021-02-17 12:59:36 -05002127 if (fProgram.fConfig->fKind == ProgramKind::kVertex) {
Jim Van Verth3913d3e2020-08-31 15:16:57 -04002128 this->write(" float sk_PointSize [[point_size]];\n");
Timothy Liang7d637782018-06-05 09:58:07 -04002129 }
2130 this->write("};\n");
2131}
2132
2133void MetalCodeGenerator::writeInterfaceBlocks() {
2134 bool wroteInterfaceBlock = false;
Brian Osman133724c2020-10-28 14:14:39 -04002135 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04002136 if (e->is<InterfaceBlock>()) {
2137 this->writeInterfaceBlock(e->as<InterfaceBlock>());
Timothy Liang7d637782018-06-05 09:58:07 -04002138 wroteInterfaceBlock = true;
2139 }
2140 }
Jim Van Verth3d482992019-02-07 10:48:05 -05002141 if (!wroteInterfaceBlock && fProgram.fInputs.fRTHeight) {
Timothy Liang7d637782018-06-05 09:58:07 -04002142 this->writeLine("struct sksl_synthetic_uniforms {");
2143 this->writeLine(" float u_skRTHeight;");
2144 this->writeLine("};");
2145 }
Ethan Nicholascc305772017-10-13 16:17:45 -04002146}
2147
John Stilesdc75a972020-11-25 16:24:55 -05002148void MetalCodeGenerator::writeStructDefinitions() {
2149 for (const ProgramElement* e : fProgram.elements()) {
2150 if (e->is<StructDefinition>()) {
Brian Osman02bc5222021-01-28 11:00:20 -05002151 this->writeStructDefinition(e->as<StructDefinition>());
John Stilesdc75a972020-11-25 16:24:55 -05002152 }
2153 }
2154}
2155
John Stilescdcdb042020-07-06 09:03:51 -04002156void MetalCodeGenerator::visitGlobalStruct(GlobalStructVisitor* visitor) {
2157 // Visit the interface blocks.
2158 for (const auto& [interfaceType, interfaceName] : fInterfaceBlockNameMap) {
John Stilesfdb8dbe2020-12-04 11:00:03 -05002159 visitor->visitInterfaceBlock(*interfaceType, interfaceName);
John Stilescdcdb042020-07-06 09:03:51 -04002160 }
Brian Osman133724c2020-10-28 14:14:39 -04002161 for (const ProgramElement* element : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04002162 if (!element->is<GlobalVarDeclaration>()) {
John Stilescdcdb042020-07-06 09:03:51 -04002163 continue;
Timothy Liang7d637782018-06-05 09:58:07 -04002164 }
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04002165 const GlobalVarDeclaration& global = element->as<GlobalVarDeclaration>();
2166 const VarDeclaration& decl = global.declaration()->as<VarDeclaration>();
2167 const Variable& var = decl.var();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002168 if ((!var.modifiers().fFlags && -1 == var.modifiers().fLayout.fBuiltin) ||
Brian Osmanc0213602020-10-06 14:43:32 -04002169 var.type().typeKind() == Type::TypeKind::kSampler) {
2170 if (var.type().typeKind() == Type::TypeKind::kSampler) {
2171 // Samplers are represented as a "texture/sampler" duo in the global struct.
John Stilesfdb8dbe2020-12-04 11:00:03 -05002172 visitor->visitTexture(var.type(), var.name());
2173 visitor->visitSampler(var.type(), String(var.name()) + SAMPLER_SUFFIX);
Brian Osmanc0213602020-10-06 14:43:32 -04002174 } else {
2175 // Visit a regular variable.
John Stilesfdb8dbe2020-12-04 11:00:03 -05002176 visitor->visitVariable(var, decl.value().get());
Timothy Liangee84fe12018-05-18 14:38:19 -04002177 }
2178 }
2179 }
John Stilescdcdb042020-07-06 09:03:51 -04002180}
2181
2182void MetalCodeGenerator::writeGlobalStruct() {
2183 class : public GlobalStructVisitor {
2184 public:
John Stilesfdb8dbe2020-12-04 11:00:03 -05002185 void visitInterfaceBlock(const InterfaceBlock& block, const String& blockName) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002186 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002187 fCodeGen->write(" constant ");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04002188 fCodeGen->write(block.typeName());
John Stilescdcdb042020-07-06 09:03:51 -04002189 fCodeGen->write("* ");
2190 fCodeGen->writeName(blockName);
2191 fCodeGen->write(";\n");
2192 }
John Stilesfdb8dbe2020-12-04 11:00:03 -05002193 void visitTexture(const Type& type, const String& name) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002194 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002195 fCodeGen->write(" ");
John Stilesb4418502021-02-04 10:57:08 -05002196 fCodeGen->writeType(type);
John Stilescdcdb042020-07-06 09:03:51 -04002197 fCodeGen->write(" ");
2198 fCodeGen->writeName(name);
2199 fCodeGen->write(";\n");
2200 }
John Stilesfdb8dbe2020-12-04 11:00:03 -05002201 void visitSampler(const Type&, const String& name) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002202 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002203 fCodeGen->write(" sampler ");
2204 fCodeGen->writeName(name);
2205 fCodeGen->write(";\n");
2206 }
John Stilesfdb8dbe2020-12-04 11:00:03 -05002207 void visitVariable(const Variable& var, const Expression* value) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002208 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002209 fCodeGen->write(" ");
John Stilesb4418502021-02-04 10:57:08 -05002210 fCodeGen->writeType(var.type());
John Stilescdcdb042020-07-06 09:03:51 -04002211 fCodeGen->write(" ");
Ethan Nicholase2c49992020-10-05 11:49:11 -04002212 fCodeGen->writeName(var.name());
John Stilescdcdb042020-07-06 09:03:51 -04002213 fCodeGen->write(";\n");
2214 }
John Stiles83f3b8d2020-12-07 17:52:25 -05002215 void addElement() {
John Stilescdcdb042020-07-06 09:03:51 -04002216 if (fFirst) {
2217 fCodeGen->write("struct Globals {\n");
2218 fFirst = false;
2219 }
2220 }
John Stiles83f3b8d2020-12-07 17:52:25 -05002221 void finish() {
John Stilescdcdb042020-07-06 09:03:51 -04002222 if (!fFirst) {
John Stiles83f3b8d2020-12-07 17:52:25 -05002223 fCodeGen->writeLine("};");
John Stilescdcdb042020-07-06 09:03:51 -04002224 fFirst = true;
2225 }
2226 }
2227
2228 MetalCodeGenerator* fCodeGen = nullptr;
2229 bool fFirst = true;
2230 } visitor;
2231
2232 visitor.fCodeGen = this;
2233 this->visitGlobalStruct(&visitor);
John Stiles83f3b8d2020-12-07 17:52:25 -05002234 visitor.finish();
John Stilescdcdb042020-07-06 09:03:51 -04002235}
2236
2237void MetalCodeGenerator::writeGlobalInit() {
2238 class : public GlobalStructVisitor {
2239 public:
John Stilesfdb8dbe2020-12-04 11:00:03 -05002240 void visitInterfaceBlock(const InterfaceBlock& blockType,
John Stilescdcdb042020-07-06 09:03:51 -04002241 const String& blockName) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002242 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002243 fCodeGen->write("&");
2244 fCodeGen->writeName(blockName);
2245 }
John Stilesfdb8dbe2020-12-04 11:00:03 -05002246 void visitTexture(const Type&, const String& name) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002247 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002248 fCodeGen->writeName(name);
2249 }
John Stilesfdb8dbe2020-12-04 11:00:03 -05002250 void visitSampler(const Type&, const String& name) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002251 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002252 fCodeGen->writeName(name);
2253 }
John Stilesfdb8dbe2020-12-04 11:00:03 -05002254 void visitVariable(const Variable& var, const Expression* value) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002255 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002256 if (value) {
2257 fCodeGen->writeVarInitializer(var, *value);
2258 } else {
2259 fCodeGen->write("{}");
2260 }
2261 }
John Stiles83f3b8d2020-12-07 17:52:25 -05002262 void addElement() {
John Stilescdcdb042020-07-06 09:03:51 -04002263 if (fFirst) {
John Stilesf7410bd2021-01-19 13:07:55 -05002264 fCodeGen->write(" Globals _globals{");
John Stilescdcdb042020-07-06 09:03:51 -04002265 fFirst = false;
2266 } else {
2267 fCodeGen->write(", ");
2268 }
2269 }
John Stiles83f3b8d2020-12-07 17:52:25 -05002270 void finish() {
John Stilescdcdb042020-07-06 09:03:51 -04002271 if (!fFirst) {
2272 fCodeGen->writeLine("};");
John Stiles37279172021-01-21 22:24:28 -05002273 fCodeGen->writeLine(" (void)_globals;");
John Stilescdcdb042020-07-06 09:03:51 -04002274 }
2275 }
2276 MetalCodeGenerator* fCodeGen = nullptr;
2277 bool fFirst = true;
2278 } visitor;
2279
2280 visitor.fCodeGen = this;
2281 this->visitGlobalStruct(&visitor);
John Stiles83f3b8d2020-12-07 17:52:25 -05002282 visitor.finish();
Timothy Liangee84fe12018-05-18 14:38:19 -04002283}
2284
Ethan Nicholascc305772017-10-13 16:17:45 -04002285void MetalCodeGenerator::writeProgramElement(const ProgramElement& e) {
Ethan Nicholase6592142020-09-08 10:22:09 -04002286 switch (e.kind()) {
2287 case ProgramElement::Kind::kExtension:
Ethan Nicholascc305772017-10-13 16:17:45 -04002288 break;
Brian Osmanc0213602020-10-06 14:43:32 -04002289 case ProgramElement::Kind::kGlobalVar: {
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04002290 const GlobalVarDeclaration& global = e.as<GlobalVarDeclaration>();
2291 const VarDeclaration& decl = global.declaration()->as<VarDeclaration>();
2292 int builtin = decl.var().modifiers().fLayout.fBuiltin;
Brian Osmanc0213602020-10-06 14:43:32 -04002293 if (-1 == builtin) {
2294 // normal var
2295 this->writeVarDeclaration(decl, true);
John Stilese8b5a732021-03-12 13:25:52 -05002296 this->finishLine();
Brian Osmanc0213602020-10-06 14:43:32 -04002297 } else if (SK_FRAGCOLOR_BUILTIN == builtin) {
2298 // ignore
Ethan Nicholascc305772017-10-13 16:17:45 -04002299 }
2300 break;
2301 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002302 case ProgramElement::Kind::kInterfaceBlock:
Timothy Liang7d637782018-06-05 09:58:07 -04002303 // handled in writeInterfaceBlocks, do nothing
Ethan Nicholascc305772017-10-13 16:17:45 -04002304 break;
John Stilesdc75a972020-11-25 16:24:55 -05002305 case ProgramElement::Kind::kStructDefinition:
2306 // Handled in writeStructDefinitions. Do nothing.
2307 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04002308 case ProgramElement::Kind::kFunction:
John Stiles3dc0da62020-08-19 17:48:31 -04002309 this->writeFunction(e.as<FunctionDefinition>());
Ethan Nicholascc305772017-10-13 16:17:45 -04002310 break;
John Stiles569249b2020-11-03 12:18:22 -05002311 case ProgramElement::Kind::kFunctionPrototype:
2312 this->writeFunctionPrototype(e.as<FunctionPrototype>());
2313 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04002314 case ProgramElement::Kind::kModifiers:
John Stiles06b84ef2020-12-09 12:35:48 -05002315 this->writeModifiers(e.as<ModifiersDeclaration>().modifiers(),
2316 /*globalContext=*/true);
Ethan Nicholascc305772017-10-13 16:17:45 -04002317 this->writeLine(";");
2318 break;
John Stiles712fd6b2020-11-25 22:25:43 -05002319 case ProgramElement::Kind::kEnum:
2320 break;
Ethan Nicholascc305772017-10-13 16:17:45 -04002321 default:
John Stileseada7bc2021-02-02 16:29:32 -05002322 SkDEBUGFAILF("unsupported program element: %s\n", e.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -05002323 break;
Ethan Nicholascc305772017-10-13 16:17:45 -04002324 }
2325}
2326
Ethan Nicholasff350cb2020-05-14 14:05:13 -04002327MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const Expression* e) {
2328 if (!e) {
2329 return kNo_Requirements;
2330 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002331 switch (e->kind()) {
2332 case Expression::Kind::kFunctionCall: {
John Stiles3dc0da62020-08-19 17:48:31 -04002333 const FunctionCall& f = e->as<FunctionCall>();
Ethan Nicholas0dec9922020-10-05 15:51:52 -04002334 Requirements result = this->requirements(f.function());
2335 for (const auto& arg : f.arguments()) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04002336 result |= this->requirements(arg.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002337 }
2338 return result;
2339 }
John Stiles8cad6372021-04-07 12:31:13 -04002340 case Expression::Kind::kConstructorCompound:
2341 case Expression::Kind::kConstructorCompoundCast:
John Stiles7384b372021-04-01 13:48:15 -04002342 case Expression::Kind::kConstructorArray:
John Stiles2938eea2021-04-01 18:58:25 -04002343 case Expression::Kind::kConstructorDiagonalMatrix:
John Stilesfd7252f2021-04-04 22:24:40 -04002344 case Expression::Kind::kConstructorScalarCast:
John Stilesd47330f2021-04-08 23:25:52 -04002345 case Expression::Kind::kConstructorSplat:
2346 case Expression::Kind::kConstructorStruct: {
John Stiles7384b372021-04-01 13:48:15 -04002347 const AnyConstructor& c = e->asAnyConstructor();
Ethan Nicholascc305772017-10-13 16:17:45 -04002348 Requirements result = kNo_Requirements;
John Stilesd8eb8752021-04-01 11:49:10 -04002349 for (const auto& arg : c.argumentSpan()) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04002350 result |= this->requirements(arg.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002351 }
2352 return result;
2353 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002354 case Expression::Kind::kFieldAccess: {
John Stiles3dc0da62020-08-19 17:48:31 -04002355 const FieldAccess& f = e->as<FieldAccess>();
Ethan Nicholas7a95b202020-10-09 11:55:40 -04002356 if (FieldAccess::OwnerKind::kAnonymousInterfaceBlock == f.ownerKind()) {
Timothy Liang7d637782018-06-05 09:58:07 -04002357 return kGlobals_Requirement;
2358 }
Ethan Nicholas7a95b202020-10-09 11:55:40 -04002359 return this->requirements(f.base().get());
Timothy Liang7d637782018-06-05 09:58:07 -04002360 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002361 case Expression::Kind::kSwizzle:
Ethan Nicholas6b4d5812020-10-12 16:11:51 -04002362 return this->requirements(e->as<Swizzle>().base().get());
Ethan Nicholase6592142020-09-08 10:22:09 -04002363 case Expression::Kind::kBinary: {
2364 const BinaryExpression& bin = e->as<BinaryExpression>();
John Stiles2d4f9592020-10-30 10:29:12 -04002365 return this->requirements(bin.left().get()) |
2366 this->requirements(bin.right().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002367 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002368 case Expression::Kind::kIndex: {
John Stiles3dc0da62020-08-19 17:48:31 -04002369 const IndexExpression& idx = e->as<IndexExpression>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04002370 return this->requirements(idx.base().get()) | this->requirements(idx.index().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002371 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002372 case Expression::Kind::kPrefix:
Ethan Nicholas444ccc62020-10-09 10:16:22 -04002373 return this->requirements(e->as<PrefixExpression>().operand().get());
Ethan Nicholase6592142020-09-08 10:22:09 -04002374 case Expression::Kind::kPostfix:
Ethan Nicholas444ccc62020-10-09 10:16:22 -04002375 return this->requirements(e->as<PostfixExpression>().operand().get());
Ethan Nicholase6592142020-09-08 10:22:09 -04002376 case Expression::Kind::kTernary: {
John Stiles3dc0da62020-08-19 17:48:31 -04002377 const TernaryExpression& t = e->as<TernaryExpression>();
Ethan Nicholasdd218162020-10-08 05:48:01 -04002378 return this->requirements(t.test().get()) | this->requirements(t.ifTrue().get()) |
2379 this->requirements(t.ifFalse().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002380 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002381 case Expression::Kind::kVariableReference: {
John Stiles3dc0da62020-08-19 17:48:31 -04002382 const VariableReference& v = e->as<VariableReference>();
Ethan Nicholas78686922020-10-08 06:46:27 -04002383 const Modifiers& modifiers = v.variable()->modifiers();
Ethan Nicholascc305772017-10-13 16:17:45 -04002384 Requirements result = kNo_Requirements;
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002385 if (modifiers.fLayout.fBuiltin == SK_FRAGCOORD_BUILTIN) {
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -04002386 result = kGlobals_Requirement | kFragCoord_Requirement;
Ethan Nicholas453f67f2020-10-09 10:43:45 -04002387 } else if (Variable::Storage::kGlobal == v.variable()->storage()) {
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002388 if (modifiers.fFlags & Modifiers::kIn_Flag) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002389 result = kInputs_Requirement;
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002390 } else if (modifiers.fFlags & Modifiers::kOut_Flag) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002391 result = kOutputs_Requirement;
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002392 } else if (modifiers.fFlags & Modifiers::kUniform_Flag &&
Ethan Nicholas78686922020-10-08 06:46:27 -04002393 v.variable()->type().typeKind() != Type::TypeKind::kSampler) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002394 result = kUniforms_Requirement;
Timothy Liangee84fe12018-05-18 14:38:19 -04002395 } else {
2396 result = kGlobals_Requirement;
Ethan Nicholascc305772017-10-13 16:17:45 -04002397 }
2398 }
2399 return result;
2400 }
2401 default:
2402 return kNo_Requirements;
2403 }
2404}
2405
Ethan Nicholasff350cb2020-05-14 14:05:13 -04002406MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const Statement* s) {
2407 if (!s) {
2408 return kNo_Requirements;
2409 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002410 switch (s->kind()) {
2411 case Statement::Kind::kBlock: {
Ethan Nicholascc305772017-10-13 16:17:45 -04002412 Requirements result = kNo_Requirements;
Ethan Nicholas7bd60432020-09-25 14:31:59 -04002413 for (const std::unique_ptr<Statement>& child : s->as<Block>().children()) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04002414 result |= this->requirements(child.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002415 }
2416 return result;
2417 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002418 case Statement::Kind::kVarDeclaration: {
John Stiles3dc0da62020-08-19 17:48:31 -04002419 const VarDeclaration& var = s->as<VarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04002420 return this->requirements(var.value().get());
Timothy Liang7d637782018-06-05 09:58:07 -04002421 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002422 case Statement::Kind::kExpression:
Ethan Nicholasd503a5a2020-09-30 09:29:55 -04002423 return this->requirements(s->as<ExpressionStatement>().expression().get());
Ethan Nicholase6592142020-09-08 10:22:09 -04002424 case Statement::Kind::kReturn: {
John Stiles3dc0da62020-08-19 17:48:31 -04002425 const ReturnStatement& r = s->as<ReturnStatement>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04002426 return this->requirements(r.expression().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002427 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002428 case Statement::Kind::kIf: {
John Stiles3dc0da62020-08-19 17:48:31 -04002429 const IfStatement& i = s->as<IfStatement>();
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04002430 return this->requirements(i.test().get()) |
2431 this->requirements(i.ifTrue().get()) |
2432 this->requirements(i.ifFalse().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002433 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002434 case Statement::Kind::kFor: {
John Stiles3dc0da62020-08-19 17:48:31 -04002435 const ForStatement& f = s->as<ForStatement>();
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04002436 return this->requirements(f.initializer().get()) |
2437 this->requirements(f.test().get()) |
2438 this->requirements(f.next().get()) |
2439 this->requirements(f.statement().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002440 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002441 case Statement::Kind::kDo: {
John Stiles3dc0da62020-08-19 17:48:31 -04002442 const DoStatement& d = s->as<DoStatement>();
Ethan Nicholas1fd61162020-09-28 13:14:19 -04002443 return this->requirements(d.test().get()) |
2444 this->requirements(d.statement().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002445 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002446 case Statement::Kind::kSwitch: {
John Stiles3dc0da62020-08-19 17:48:31 -04002447 const SwitchStatement& sw = s->as<SwitchStatement>();
Ethan Nicholas01b05e52020-10-22 15:53:41 -04002448 Requirements result = this->requirements(sw.value().get());
John Stilesb23a64b2021-03-11 08:27:59 -05002449 for (const std::unique_ptr<Statement>& sc : sw.cases()) {
2450 result |= this->requirements(sc->as<SwitchCase>().statement().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002451 }
2452 return result;
2453 }
2454 default:
2455 return kNo_Requirements;
2456 }
2457}
2458
2459MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const FunctionDeclaration& f) {
Ethan Nicholased84b732020-10-08 11:45:44 -04002460 if (f.isBuiltin()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002461 return kNo_Requirements;
2462 }
2463 auto found = fRequirements.find(&f);
2464 if (found == fRequirements.end()) {
Ethan Nicholas65a8f562019-04-19 14:00:26 -04002465 fRequirements[&f] = kNo_Requirements;
Brian Osman133724c2020-10-28 14:14:39 -04002466 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04002467 if (e->is<FunctionDefinition>()) {
2468 const FunctionDefinition& def = e->as<FunctionDefinition>();
Ethan Nicholas0a5d0962020-10-14 13:33:18 -04002469 if (&def.declaration() == &f) {
2470 Requirements reqs = this->requirements(def.body().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002471 fRequirements[&f] = reqs;
2472 return reqs;
2473 }
2474 }
2475 }
John Stiles569249b2020-11-03 12:18:22 -05002476 // We never found a definition for this declared function, but it's legal to prototype a
2477 // function without ever giving a definition, as long as you don't call it.
2478 return kNo_Requirements;
Ethan Nicholascc305772017-10-13 16:17:45 -04002479 }
2480 return found->second;
2481}
2482
Timothy Liangb8eeb802018-07-23 16:46:16 -04002483bool MetalCodeGenerator::generateCode() {
John Stiles44532372020-12-07 12:33:55 -05002484 StringStream header;
2485 {
2486 AutoOutputStream outputToHeader(this, &header, &fIndentation);
Michael Ludwigbf58add2021-03-16 10:40:11 -04002487 this->writeHeader();
John Stiles44532372020-12-07 12:33:55 -05002488 this->writeStructDefinitions();
2489 this->writeUniformStruct();
2490 this->writeInputStruct();
2491 this->writeOutputStruct();
2492 this->writeInterfaceBlocks();
2493 this->writeGlobalStruct();
2494 }
2495 StringStream body;
2496 {
2497 AutoOutputStream outputToBody(this, &body, &fIndentation);
2498 for (const ProgramElement* e : fProgram.elements()) {
2499 this->writeProgramElement(*e);
2500 }
2501 }
2502 write_stringstream(header, *fOut);
2503 write_stringstream(fExtraFunctions, *fOut);
2504 write_stringstream(body, *fOut);
Brian Osman8609a242020-09-08 14:01:49 -04002505 return 0 == fErrors.errorCount();
Ethan Nicholascc305772017-10-13 16:17:45 -04002506}
2507
John Stilesa6841be2020-08-06 14:11:56 -04002508} // namespace SkSL