blob: 02e8b14f8a99a3230983dad4e519c6ffa5b22120 [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 Stilese3ae9682021-08-05 10:35:01 -040014#include "src/sksl/ir/SkSLConstructorArrayCast.h"
John Stiles8cad6372021-04-07 12:31:13 -040015#include "src/sksl/ir/SkSLConstructorCompoundCast.h"
John Stiles7384b372021-04-01 13:48:15 -040016#include "src/sksl/ir/SkSLConstructorDiagonalMatrix.h"
John Stiles5abb9e12021-04-06 13:47:19 -040017#include "src/sksl/ir/SkSLConstructorMatrixResize.h"
John Stiles2938eea2021-04-01 18:58:25 -040018#include "src/sksl/ir/SkSLConstructorSplat.h"
John Stilesd47330f2021-04-08 23:25:52 -040019#include "src/sksl/ir/SkSLConstructorStruct.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050020#include "src/sksl/ir/SkSLExpressionStatement.h"
21#include "src/sksl/ir/SkSLExtension.h"
22#include "src/sksl/ir/SkSLIndexExpression.h"
23#include "src/sksl/ir/SkSLModifiersDeclaration.h"
24#include "src/sksl/ir/SkSLNop.h"
John Stilesdc75a972020-11-25 16:24:55 -050025#include "src/sksl/ir/SkSLStructDefinition.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050026#include "src/sksl/ir/SkSLVariableReference.h"
Ethan Nicholascc305772017-10-13 16:17:45 -040027
Brian Osmanc262a122020-08-06 16:34:34 -040028#include <algorithm>
29
Ethan Nicholascc305772017-10-13 16:17:45 -040030namespace SkSL {
31
John Stiles45990502021-02-16 10:55:27 -050032const char* MetalCodeGenerator::OperatorName(Operator op) {
33 switch (op.kind()) {
John Stilesd6449e92020-11-30 09:13:23 -050034 case Token::Kind::TK_LOGICALXOR: return "!=";
John Stiles45990502021-02-16 10:55:27 -050035 default: return op.operatorName();
John Stilesd6449e92020-11-30 09:13:23 -050036 }
37}
38
John Stilescdcdb042020-07-06 09:03:51 -040039class MetalCodeGenerator::GlobalStructVisitor {
40public:
41 virtual ~GlobalStructVisitor() = default;
Ethan Nicholas962dec42021-06-10 13:06:39 -040042 virtual void visitInterfaceBlock(const InterfaceBlock& block, skstd::string_view blockName) = 0;
43 virtual void visitTexture(const Type& type, skstd::string_view name) = 0;
44 virtual void visitSampler(const Type& type, skstd::string_view name) = 0;
John Stilesfdb8dbe2020-12-04 11:00:03 -050045 virtual void visitVariable(const Variable& var, const Expression* value) = 0;
John Stilescdcdb042020-07-06 09:03:51 -040046};
47
Ethan Nicholas962dec42021-06-10 13:06:39 -040048void MetalCodeGenerator::write(skstd::string_view s) {
Ethan Nicholasd2e09602021-06-10 11:21:59 -040049 if (s.empty()) {
Ethan Nicholascc305772017-10-13 16:17:45 -040050 return;
51 }
52 if (fAtLineStart) {
53 for (int i = 0; i < fIndentation; i++) {
54 fOut->writeText(" ");
55 }
56 }
Ethan Nicholasd2e09602021-06-10 11:21:59 -040057 fOut->writeText(String(s).c_str());
Ethan Nicholascc305772017-10-13 16:17:45 -040058 fAtLineStart = false;
59}
60
Ethan Nicholas962dec42021-06-10 13:06:39 -040061void MetalCodeGenerator::writeLine(skstd::string_view s) {
Ethan Nicholascc305772017-10-13 16:17:45 -040062 this->write(s);
John Stilese8b5a732021-03-12 13:25:52 -050063 fOut->writeText(fLineEnding);
64 fAtLineStart = true;
65}
66
67void MetalCodeGenerator::finishLine() {
68 if (!fAtLineStart) {
69 this->writeLine();
70 }
Ethan Nicholascc305772017-10-13 16:17:45 -040071}
72
73void MetalCodeGenerator::writeExtension(const Extension& ext) {
Ethan Nicholasefb09e22020-09-30 10:17:00 -040074 this->writeLine("#extension " + ext.name() + " : enable");
Ethan Nicholascc305772017-10-13 16:17:45 -040075}
76
Ethan Nicholas45fa8102020-01-13 10:58:49 -050077String MetalCodeGenerator::typeName(const Type& type) {
Ethan Nicholase6592142020-09-08 10:22:09 -040078 switch (type.typeKind()) {
John Stilesb4418502021-02-04 10:57:08 -050079 case Type::TypeKind::kArray:
80 SkASSERTF(type.columns() > 0, "invalid array size: %s", type.description().c_str());
81 return String::printf("array<%s, %d>",
82 this->typeName(type.componentType()).c_str(), type.columns());
83
Ethan Nicholase6592142020-09-08 10:22:09 -040084 case Type::TypeKind::kVector:
Ethan Nicholas45fa8102020-01-13 10:58:49 -050085 return this->typeName(type.componentType()) + to_string(type.columns());
John Stilesb4418502021-02-04 10:57:08 -050086
Ethan Nicholase6592142020-09-08 10:22:09 -040087 case Type::TypeKind::kMatrix:
Ethan Nicholas45fa8102020-01-13 10:58:49 -050088 return this->typeName(type.componentType()) + to_string(type.columns()) + "x" +
89 to_string(type.rows());
John Stilesb4418502021-02-04 10:57:08 -050090
Ethan Nicholase6592142020-09-08 10:22:09 -040091 case Type::TypeKind::kSampler:
John Stiles368db7c2020-12-29 11:20:08 -050092 return "texture2d<float>"; // FIXME - support other texture types
John Stilesb4418502021-02-04 10:57:08 -050093
Ethan Nicholascc305772017-10-13 16:17:45 -040094 default:
John Stiles7b2b8582021-08-09 14:20:54 -040095 // We currently only support full-precision types in MSL to avoid type coercion issues.
John Stiles54e7c052021-01-11 14:22:36 -050096 if (type == *fContext.fTypes.fHalf) {
John Stiles7b2b8582021-08-09 14:20:54 -040097 return "float";
Timothy Liang7d637782018-06-05 09:58:07 -040098 }
John Stiles7b2b8582021-08-09 14:20:54 -040099 if (type == *fContext.fTypes.fShort) {
100 return "int";
101 }
102 if (type == *fContext.fTypes.fUShort) {
103 return "uint";
104 }
105 return String(type.name());
Ethan Nicholascc305772017-10-13 16:17:45 -0400106 }
107}
108
Brian Osman02bc5222021-01-28 11:00:20 -0500109void MetalCodeGenerator::writeStructDefinition(const StructDefinition& s) {
110 const Type& type = s.type();
John Stilesdc75a972020-11-25 16:24:55 -0500111 this->writeLine("struct " + type.name() + " {");
112 fIndentation++;
113 this->writeFields(type.fields(), type.fOffset);
114 fIndentation--;
Brian Osman02bc5222021-01-28 11:00:20 -0500115 this->writeLine("};");
John Stilesdc75a972020-11-25 16:24:55 -0500116}
117
John Stilesb4418502021-02-04 10:57:08 -0500118void MetalCodeGenerator::writeType(const Type& type) {
119 this->write(this->typeName(type));
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500120}
121
Ethan Nicholascc305772017-10-13 16:17:45 -0400122void MetalCodeGenerator::writeExpression(const Expression& expr, Precedence parentPrecedence) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400123 switch (expr.kind()) {
124 case Expression::Kind::kBinary:
John Stiles81365af2020-08-18 09:24:00 -0400125 this->writeBinaryExpression(expr.as<BinaryExpression>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400126 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400127 case Expression::Kind::kBoolLiteral:
John Stiles81365af2020-08-18 09:24:00 -0400128 this->writeBoolLiteral(expr.as<BoolLiteral>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400129 break;
John Stiles2bec8ab2021-04-06 18:40:04 -0400130 case Expression::Kind::kConstructorArray:
John Stilesd47330f2021-04-08 23:25:52 -0400131 case Expression::Kind::kConstructorStruct:
John Stiles2bec8ab2021-04-06 18:40:04 -0400132 this->writeAnyConstructor(expr.asAnyConstructor(), "{", "}", parentPrecedence);
133 break;
John Stilese3ae9682021-08-05 10:35:01 -0400134 case Expression::Kind::kConstructorArrayCast:
135 this->writeExpression(*expr.as<ConstructorArrayCast>().argument(), parentPrecedence);
136 break;
John Stiles8cad6372021-04-07 12:31:13 -0400137 case Expression::Kind::kConstructorCompound:
138 this->writeConstructorCompound(expr.as<ConstructorCompound>(), parentPrecedence);
John Stiles2bec8ab2021-04-06 18:40:04 -0400139 break;
140 case Expression::Kind::kConstructorDiagonalMatrix:
141 case Expression::Kind::kConstructorSplat:
142 this->writeAnyConstructor(expr.asAnyConstructor(), "(", ")", parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400143 break;
John Stiles5abb9e12021-04-06 13:47:19 -0400144 case Expression::Kind::kConstructorMatrixResize:
145 this->writeConstructorMatrixResize(expr.as<ConstructorMatrixResize>(),
146 parentPrecedence);
147 break;
John Stilesfd7252f2021-04-04 22:24:40 -0400148 case Expression::Kind::kConstructorScalarCast:
John Stiles8cad6372021-04-07 12:31:13 -0400149 case Expression::Kind::kConstructorCompoundCast:
John Stilesb14a8192021-04-05 11:40:46 -0400150 this->writeCastConstructor(expr.asAnyConstructor(), "(", ")", parentPrecedence);
John Stiles2938eea2021-04-01 18:58:25 -0400151 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400152 case Expression::Kind::kIntLiteral:
John Stiles81365af2020-08-18 09:24:00 -0400153 this->writeIntLiteral(expr.as<IntLiteral>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400154 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400155 case Expression::Kind::kFieldAccess:
John Stiles81365af2020-08-18 09:24:00 -0400156 this->writeFieldAccess(expr.as<FieldAccess>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400157 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400158 case Expression::Kind::kFloatLiteral:
John Stiles81365af2020-08-18 09:24:00 -0400159 this->writeFloatLiteral(expr.as<FloatLiteral>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400160 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400161 case Expression::Kind::kFunctionCall:
John Stiles81365af2020-08-18 09:24:00 -0400162 this->writeFunctionCall(expr.as<FunctionCall>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400163 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400164 case Expression::Kind::kPrefix:
John Stiles81365af2020-08-18 09:24:00 -0400165 this->writePrefixExpression(expr.as<PrefixExpression>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400166 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400167 case Expression::Kind::kPostfix:
John Stiles81365af2020-08-18 09:24:00 -0400168 this->writePostfixExpression(expr.as<PostfixExpression>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400169 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400170 case Expression::Kind::kSetting:
John Stiles81365af2020-08-18 09:24:00 -0400171 this->writeSetting(expr.as<Setting>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400172 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400173 case Expression::Kind::kSwizzle:
John Stiles81365af2020-08-18 09:24:00 -0400174 this->writeSwizzle(expr.as<Swizzle>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400175 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400176 case Expression::Kind::kVariableReference:
John Stiles81365af2020-08-18 09:24:00 -0400177 this->writeVariableReference(expr.as<VariableReference>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400178 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400179 case Expression::Kind::kTernary:
John Stiles81365af2020-08-18 09:24:00 -0400180 this->writeTernaryExpression(expr.as<TernaryExpression>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400181 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400182 case Expression::Kind::kIndex:
John Stiles81365af2020-08-18 09:24:00 -0400183 this->writeIndexExpression(expr.as<IndexExpression>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400184 break;
185 default:
John Stileseada7bc2021-02-02 16:29:32 -0500186 SkDEBUGFAILF("unsupported expression: %s", expr.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -0500187 break;
Ethan Nicholascc305772017-10-13 16:17:45 -0400188 }
189}
190
John Stiles06b84ef2020-12-09 12:35:48 -0500191String MetalCodeGenerator::getOutParamHelper(const FunctionCall& call,
192 const ExpressionArray& arguments,
193 const SkTArray<VariableReference*>& outVars) {
194 AutoOutputStream outputToExtraFunctions(this, &fExtraFunctions, &fIndentation);
195 const FunctionDeclaration& function = call.function();
196
John Stilese1068342021-03-22 11:57:41 -0400197 String name = "_skOutParamHelper" + to_string(fSwizzleHelperCount++) +
198 "_" + function.mangledName();
John Stiles06b84ef2020-12-09 12:35:48 -0500199 const char* separator = "";
200
201 // Emit a prototype for the function we'll be calling through to in our helper.
202 if (!function.isBuiltin()) {
203 this->writeFunctionDeclaration(function);
204 this->writeLine(";");
205 }
206
207 // Synthesize a helper function that takes the same inputs as `function`, except in places where
208 // `outVars` is non-null; in those places, we take the type of the VariableReference.
209 //
210 // float _skOutParamHelper0_originalFuncName(float _var0, float _var1, float& outParam) {
John Stilesb4418502021-02-04 10:57:08 -0500211 this->writeType(call.type());
John Stiles06b84ef2020-12-09 12:35:48 -0500212 this->write(" ");
213 this->write(name);
214 this->write("(");
215 this->writeFunctionRequirementParams(function, separator);
216
217 SkASSERT(outVars.size() == arguments.size());
218 SkASSERT(outVars.size() == function.parameters().size());
219
John Stiles73e2c892021-02-13 13:58:01 -0500220 // We need to detect cases where the caller passes the same variable as an out-param more than
221 // once, and avoid reusing the variable name. (In those cases we can actually just ignore the
222 // redundant input parameter entirely, and not give it any name.)
223 std::unordered_set<const Variable*> writtenVars;
224
John Stiles06b84ef2020-12-09 12:35:48 -0500225 for (int index = 0; index < arguments.count(); ++index) {
226 this->write(separator);
227 separator = ", ";
228
229 const Variable* param = function.parameters()[index];
Brian Osman58134e12021-05-13 14:51:07 -0400230 this->writeModifiers(param->modifiers());
John Stiles06b84ef2020-12-09 12:35:48 -0500231
232 const Type* type = outVars[index] ? &outVars[index]->type() : &arguments[index]->type();
John Stilesb4418502021-02-04 10:57:08 -0500233 this->writeType(*type);
John Stiles06b84ef2020-12-09 12:35:48 -0500234
235 if (param->modifiers().fFlags & Modifiers::kOut_Flag) {
236 this->write("&");
237 }
238 if (outVars[index]) {
John Stiles73e2c892021-02-13 13:58:01 -0500239 auto [iter, didInsert] = writtenVars.insert(outVars[index]->variable());
240 if (didInsert) {
241 this->write(" ");
242 fIgnoreVariableReferenceModifiers = true;
243 this->writeVariableReference(*outVars[index]);
244 fIgnoreVariableReferenceModifiers = false;
245 }
John Stiles06b84ef2020-12-09 12:35:48 -0500246 } else {
247 this->write(" _var");
248 this->write(to_string(index));
249 }
John Stiles06b84ef2020-12-09 12:35:48 -0500250 }
251 this->writeLine(") {");
252
253 ++fIndentation;
254 for (int index = 0; index < outVars.count(); ++index) {
255 if (!outVars[index]) {
256 continue;
257 }
258 // float3 _var2[ = outParam.zyx];
John Stilesb4418502021-02-04 10:57:08 -0500259 this->writeType(arguments[index]->type());
John Stiles06b84ef2020-12-09 12:35:48 -0500260 this->write(" _var");
261 this->write(to_string(index));
262
263 const Variable* param = function.parameters()[index];
264 if (param->modifiers().fFlags & Modifiers::kIn_Flag) {
265 this->write(" = ");
266 fIgnoreVariableReferenceModifiers = true;
Brian Osman00185012021-02-04 16:07:11 -0500267 this->writeExpression(*arguments[index], Precedence::kAssignment);
John Stiles06b84ef2020-12-09 12:35:48 -0500268 fIgnoreVariableReferenceModifiers = false;
269 }
270
271 this->writeLine(";");
272 }
273
John Stilesf7410bd2021-01-19 13:07:55 -0500274 // [int _skResult = ] myFunction(inputs, outputs, _globals, _var0, _var1, _var2, _var3);
John Stiles06b84ef2020-12-09 12:35:48 -0500275 bool hasResult = (call.type().name() != "void");
276 if (hasResult) {
John Stilesb4418502021-02-04 10:57:08 -0500277 this->writeType(call.type());
John Stiles06b84ef2020-12-09 12:35:48 -0500278 this->write(" _skResult = ");
279 }
280
John Stilese1068342021-03-22 11:57:41 -0400281 this->writeName(function.mangledName());
John Stiles06b84ef2020-12-09 12:35:48 -0500282 this->write("(");
283 separator = "";
284 this->writeFunctionRequirementArgs(function, separator);
285
286 for (int index = 0; index < arguments.count(); ++index) {
287 this->write(separator);
288 separator = ", ";
289
290 this->write("_var");
291 this->write(to_string(index));
292 }
293 this->writeLine(");");
294
295 for (int index = 0; index < outVars.count(); ++index) {
296 if (!outVars[index]) {
297 continue;
298 }
299 // outParam.zyx = _var2;
300 fIgnoreVariableReferenceModifiers = true;
Brian Osman00185012021-02-04 16:07:11 -0500301 this->writeExpression(*arguments[index], Precedence::kAssignment);
John Stiles06b84ef2020-12-09 12:35:48 -0500302 fIgnoreVariableReferenceModifiers = false;
303 this->write(" = _var");
304 this->write(to_string(index));
305 this->writeLine(";");
306 }
307
308 if (hasResult) {
309 this->writeLine("return _skResult;");
310 }
311
312 --fIndentation;
313 this->writeLine("}");
314
315 return name;
John Stilesb21fac22020-12-04 15:36:49 -0500316}
317
John Stilesf64e4072020-12-10 10:34:27 -0500318String MetalCodeGenerator::getBitcastIntrinsic(const Type& outType) {
319 return "as_type<" + outType.displayName() + ">";
320}
321
Ethan Nicholascc305772017-10-13 16:17:45 -0400322void MetalCodeGenerator::writeFunctionCall(const FunctionCall& c) {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400323 const FunctionDeclaration& function = c.function();
John Stiles496b7d12021-05-06 10:26:45 -0400324
325 // Many intrinsics need to be rewritten in Metal.
326 if (function.isIntrinsic()) {
327 if (this->writeIntrinsicCall(c, function.intrinsicKind())) {
John Stiles89ac7c22020-12-30 17:47:31 -0500328 return;
329 }
Timothy Liang6403b0e2018-05-17 10:40:04 -0400330 }
John Stilesb21fac22020-12-04 15:36:49 -0500331
John Stilesd7199b22020-12-30 16:22:58 -0500332 // Determine whether or not we need to emulate GLSL's out-param semantics for Metal using a
333 // helper function. (Specifically, out-parameters in GLSL are only written back to the original
334 // variable at the end of the function call; also, swizzles are supported, whereas Metal doesn't
335 // allow a swizzle to be passed to a `floatN&`.)
336 const ExpressionArray& arguments = c.arguments();
John Stilesb21fac22020-12-04 15:36:49 -0500337 const std::vector<const Variable*>& parameters = function.parameters();
338 SkASSERT(arguments.size() == parameters.size());
John Stiles06b84ef2020-12-09 12:35:48 -0500339
340 bool foundOutParam = false;
341 SkSTArray<16, VariableReference*> outVars;
John Stilesf64e4072020-12-10 10:34:27 -0500342 outVars.push_back_n(arguments.count(), (VariableReference*)nullptr);
John Stiles06b84ef2020-12-09 12:35:48 -0500343
344 for (int index = 0; index < arguments.count(); ++index) {
John Stilesb21fac22020-12-04 15:36:49 -0500345 // If this is an out parameter...
346 if (parameters[index]->modifiers().fFlags & Modifiers::kOut_Flag) {
John Stiles06b84ef2020-12-09 12:35:48 -0500347 // Find the expression's inner variable being written to.
John Stilesb21fac22020-12-04 15:36:49 -0500348 Analysis::AssignmentInfo info;
John Stiles06b84ef2020-12-09 12:35:48 -0500349 // Assignability was verified at IRGeneration time, so this should always succeed.
350 SkAssertResult(Analysis::IsAssignable(*arguments[index], &info));
351 outVars[index] = info.fAssignedVar;
352 foundOutParam = true;
John Stilesb21fac22020-12-04 15:36:49 -0500353 }
354 }
355
John Stiles06b84ef2020-12-09 12:35:48 -0500356 if (foundOutParam) {
357 // Out parameters need to be written back to at the end of the function. To do this, we
358 // synthesize a helper function which evaluates the out-param expression into a temporary
359 // variable, calls the original function, then writes the temp var back into the out param
360 // using the original out-param expression. (This lets us support things like swizzles and
361 // array indices.)
John Stilesd7199b22020-12-30 16:22:58 -0500362 this->write(getOutParamHelper(c, arguments, outVars));
363 } else {
John Stilese1068342021-03-22 11:57:41 -0400364 this->write(function.mangledName());
John Stiles06b84ef2020-12-09 12:35:48 -0500365 }
366
Ethan Nicholascc305772017-10-13 16:17:45 -0400367 this->write("(");
368 const char* separator = "";
John Stiles06b84ef2020-12-09 12:35:48 -0500369 this->writeFunctionRequirementArgs(function, separator);
370 for (int i = 0; i < arguments.count(); ++i) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400371 this->write(separator);
372 separator = ", ";
John Stiles06b84ef2020-12-09 12:35:48 -0500373
374 if (outVars[i]) {
Brian Osman00185012021-02-04 16:07:11 -0500375 this->writeExpression(*outVars[i], Precedence::kSequence);
John Stiles06b84ef2020-12-09 12:35:48 -0500376 } else {
Brian Osman00185012021-02-04 16:07:11 -0500377 this->writeExpression(*arguments[i], Precedence::kSequence);
John Stiles06b84ef2020-12-09 12:35:48 -0500378 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400379 }
380 this->write(")");
381}
382
Brian Osman964f0a02020-12-29 10:15:22 -0500383static constexpr char kInverse2x2[] = R"(
384float2x2 float2x2_inverse(float2x2 m) {
385 return float2x2(m[1][1], -m[0][1], -m[1][0], m[0][0]) * (1/determinant(m));
386}
387)";
388
389static constexpr char kInverse3x3[] = R"(
390float3x3 float3x3_inverse(float3x3 m) {
391 float a00 = m[0][0], a01 = m[0][1], a02 = m[0][2];
392 float a10 = m[1][0], a11 = m[1][1], a12 = m[1][2];
393 float a20 = m[2][0], a21 = m[2][1], a22 = m[2][2];
394 float b01 = a22*a11 - a12*a21;
395 float b11 = -a22*a10 + a12*a20;
396 float b21 = a21*a10 - a11*a20;
397 float det = a00*b01 + a01*b11 + a02*b21;
398 return float3x3(b01, (-a22*a01 + a02*a21), ( a12*a01 - a02*a11),
399 b11, ( a22*a00 - a02*a20), (-a12*a00 + a02*a10),
400 b21, (-a21*a00 + a01*a20), ( a11*a00 - a01*a10)) * (1/det);
401}
402)";
403
404static constexpr char kInverse4x4[] = R"(
405float4x4 float4x4_inverse(float4x4 m) {
406 float a00 = m[0][0], a01 = m[0][1], a02 = m[0][2], a03 = m[0][3];
407 float a10 = m[1][0], a11 = m[1][1], a12 = m[1][2], a13 = m[1][3];
408 float a20 = m[2][0], a21 = m[2][1], a22 = m[2][2], a23 = m[2][3];
409 float a30 = m[3][0], a31 = m[3][1], a32 = m[3][2], a33 = m[3][3];
410 float b00 = a00*a11 - a01*a10;
411 float b01 = a00*a12 - a02*a10;
412 float b02 = a00*a13 - a03*a10;
413 float b03 = a01*a12 - a02*a11;
414 float b04 = a01*a13 - a03*a11;
415 float b05 = a02*a13 - a03*a12;
416 float b06 = a20*a31 - a21*a30;
417 float b07 = a20*a32 - a22*a30;
418 float b08 = a20*a33 - a23*a30;
419 float b09 = a21*a32 - a22*a31;
420 float b10 = a21*a33 - a23*a31;
421 float b11 = a22*a33 - a23*a32;
422 float det = b00*b11 - b01*b10 + b02*b09 + b03*b08 - b04*b07 + b05*b06;
423 return float4x4(a11*b11 - a12*b10 + a13*b09,
424 a02*b10 - a01*b11 - a03*b09,
425 a31*b05 - a32*b04 + a33*b03,
426 a22*b04 - a21*b05 - a23*b03,
427 a12*b08 - a10*b11 - a13*b07,
428 a00*b11 - a02*b08 + a03*b07,
429 a32*b02 - a30*b05 - a33*b01,
430 a20*b05 - a22*b02 + a23*b01,
431 a10*b10 - a11*b08 + a13*b06,
432 a01*b08 - a00*b10 - a03*b06,
433 a30*b04 - a31*b02 + a33*b00,
434 a21*b02 - a20*b04 - a23*b00,
435 a11*b07 - a10*b09 - a12*b06,
436 a00*b09 - a01*b07 + a02*b06,
437 a31*b01 - a30*b03 - a32*b00,
438 a20*b03 - a21*b01 + a22*b00) * (1/det);
439}
440)";
441
John Stilesd7199b22020-12-30 16:22:58 -0500442String MetalCodeGenerator::getInversePolyfill(const ExpressionArray& arguments) {
443 // Only use polyfills for a function taking a single-argument square matrix.
444 if (arguments.size() == 1) {
445 const Type& type = arguments.front()->type();
446 if (type.isMatrix() && type.rows() == type.columns()) {
447 // Inject the correct polyfill based on the matrix size.
448 String name = this->typeName(type) + "_inverse";
449 auto [iter, didInsert] = fWrittenIntrinsics.insert(name);
450 if (didInsert) {
451 switch (type.rows()) {
452 case 2:
453 fExtraFunctions.writeText(kInverse2x2);
454 break;
455 case 3:
456 fExtraFunctions.writeText(kInverse3x3);
457 break;
458 case 4:
459 fExtraFunctions.writeText(kInverse4x4);
460 break;
461 }
462 }
463 return name;
Chris Daltondba7aab2018-11-15 10:57:49 -0500464 }
465 }
John Stilesd7199b22020-12-30 16:22:58 -0500466 // This isn't the built-in `inverse`. We don't want to polyfill it at all.
467 return "inverse";
Chris Daltondba7aab2018-11-15 10:57:49 -0500468}
469
John Stilesfeb1e122021-09-09 14:27:28 -0400470void MetalCodeGenerator::writeMatrixCompMult() {
471 static constexpr char kMatrixCompMult[] = R"(
Brian Osman93aed9a2020-12-28 15:18:46 -0500472template <int C, int R>
473matrix<float, C, R> matrixCompMult(matrix<float, C, R> a, matrix<float, C, R> b) {
474 matrix<float, C, R> result;
475 for (int c = 0; c < C; ++c) {
476 result[c] = a[c] * b[c];
477 }
478 return result;
479}
480)";
481
Brian Osman93aed9a2020-12-28 15:18:46 -0500482 String name = "matrixCompMult";
483 if (fWrittenIntrinsics.find(name) == fWrittenIntrinsics.end()) {
484 fWrittenIntrinsics.insert(name);
485 fExtraFunctions.writeText(kMatrixCompMult);
486 }
487}
488
John Stilesfeb1e122021-09-09 14:27:28 -0400489void MetalCodeGenerator::writeOuterProduct() {
490 static constexpr char kOuterProduct[] = R"(
491template <int C, int R>
492matrix<float, C, R> outerProduct(const vec<float, R> a, const vec<float, C> b) {
493 matrix<float, C, R> result;
494 for (int c = 0; c < C; ++c) {
495 result[c] = a * b[c];
496 }
497 return result;
498}
499)";
500
501 String name = "outerProduct";
502 if (fWrittenIntrinsics.find(name) == fWrittenIntrinsics.end()) {
503 fWrittenIntrinsics.insert(name);
504 fExtraFunctions.writeText(kOuterProduct);
505 }
506}
507
John Stiles86424eb2020-12-11 11:17:14 -0500508String MetalCodeGenerator::getTempVariable(const Type& type) {
509 String tempVar = "_skTemp" + to_string(fVarCount++);
510 this->fFunctionHeader += " " + this->typeName(type) + " " + tempVar + ";\n";
511 return tempVar;
512}
513
John Stiles791c27d2020-12-30 14:56:57 -0500514void MetalCodeGenerator::writeSimpleIntrinsic(const FunctionCall& c) {
515 // Write out an intrinsic function call exactly as-is. No muss no fuss.
516 this->write(c.function().name());
John Stilesd7199b22020-12-30 16:22:58 -0500517 this->writeArgumentList(c.arguments());
518}
519
520void MetalCodeGenerator::writeArgumentList(const ExpressionArray& arguments) {
John Stiles791c27d2020-12-30 14:56:57 -0500521 this->write("(");
522 const char* separator = "";
John Stilesd7199b22020-12-30 16:22:58 -0500523 for (const std::unique_ptr<Expression>& arg : arguments) {
John Stiles791c27d2020-12-30 14:56:57 -0500524 this->write(separator);
525 separator = ", ";
Brian Osman00185012021-02-04 16:07:11 -0500526 this->writeExpression(*arg, Precedence::kSequence);
John Stiles791c27d2020-12-30 14:56:57 -0500527 }
528 this->write(")");
529}
530
John Stiles496b7d12021-05-06 10:26:45 -0400531bool MetalCodeGenerator::writeIntrinsicCall(const FunctionCall& c, IntrinsicKind kind) {
John Stiles8e3b6be2020-10-13 11:14:08 -0400532 const ExpressionArray& arguments = c.arguments();
Timothy Liang6403b0e2018-05-17 10:40:04 -0400533 switch (kind) {
John Stiles496b7d12021-05-06 10:26:45 -0400534 case k_sample_IntrinsicKind: {
Brian Osman00185012021-02-04 16:07:11 -0500535 this->writeExpression(*arguments[0], Precedence::kSequence);
Timothy Lianga06f2152018-05-24 15:33:31 -0400536 this->write(".sample(");
Brian Osman00185012021-02-04 16:07:11 -0500537 this->writeExpression(*arguments[0], Precedence::kSequence);
Timothy Lianga06f2152018-05-24 15:33:31 -0400538 this->write(SAMPLER_SUFFIX);
539 this->write(", ");
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400540 const Type& arg1Type = arguments[1]->type();
John Stilesb14a8192021-04-05 11:40:46 -0400541 if (arg1Type.columns() == 3) {
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500542 // have to store the vector in a temp variable to avoid double evaluating it
John Stiles86424eb2020-12-11 11:17:14 -0500543 String tmpVar = this->getTempVariable(arg1Type);
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500544 this->write("(" + tmpVar + " = ");
Brian Osman00185012021-02-04 16:07:11 -0500545 this->writeExpression(*arguments[1], Precedence::kSequence);
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500546 this->write(", " + tmpVar + ".xy / " + tmpVar + ".z))");
Timothy Liangee84fe12018-05-18 14:38:19 -0400547 } else {
John Stilesb14a8192021-04-05 11:40:46 -0400548 SkASSERT(arg1Type.columns() == 2);
Brian Osman00185012021-02-04 16:07:11 -0500549 this->writeExpression(*arguments[1], Precedence::kSequence);
Timothy Liangee84fe12018-05-18 14:38:19 -0400550 this->write(")");
551 }
John Stiles496b7d12021-05-06 10:26:45 -0400552 return true;
Ethan Nicholas30d30222020-09-11 12:27:26 -0400553 }
John Stiles496b7d12021-05-06 10:26:45 -0400554 case k_mod_IntrinsicKind: {
Timothy Liang651286f2018-06-07 09:55:33 -0400555 // 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 -0500556 String tmpX = this->getTempVariable(arguments[0]->type());
John Stiles61b2e812020-12-30 18:27:31 -0500557 String tmpY = this->getTempVariable(arguments[1]->type());
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500558 this->write("(" + tmpX + " = ");
Brian Osman00185012021-02-04 16:07:11 -0500559 this->writeExpression(*arguments[0], Precedence::kSequence);
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500560 this->write(", " + tmpY + " = ");
Brian Osman00185012021-02-04 16:07:11 -0500561 this->writeExpression(*arguments[1], Precedence::kSequence);
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500562 this->write(", " + tmpX + " - " + tmpY + " * floor(" + tmpX + " / " + tmpY + "))");
John Stiles496b7d12021-05-06 10:26:45 -0400563 return true;
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500564 }
Brian Osman46787d52020-11-24 14:18:23 -0500565 // GLSL declares scalar versions of most geometric intrinsics, but these don't exist in MSL
John Stiles496b7d12021-05-06 10:26:45 -0400566 case k_distance_IntrinsicKind: {
Brian Osman46787d52020-11-24 14:18:23 -0500567 if (arguments[0]->type().columns() == 1) {
568 this->write("abs(");
Brian Osman00185012021-02-04 16:07:11 -0500569 this->writeExpression(*arguments[0], Precedence::kAdditive);
Brian Osman46787d52020-11-24 14:18:23 -0500570 this->write(" - ");
Brian Osman00185012021-02-04 16:07:11 -0500571 this->writeExpression(*arguments[1], Precedence::kAdditive);
Brian Osman46787d52020-11-24 14:18:23 -0500572 this->write(")");
573 } else {
John Stiles791c27d2020-12-30 14:56:57 -0500574 this->writeSimpleIntrinsic(c);
Brian Osman46787d52020-11-24 14:18:23 -0500575 }
John Stiles496b7d12021-05-06 10:26:45 -0400576 return true;
Brian Osman46787d52020-11-24 14:18:23 -0500577 }
John Stiles496b7d12021-05-06 10:26:45 -0400578 case k_dot_IntrinsicKind: {
Brian Osman46787d52020-11-24 14:18:23 -0500579 if (arguments[0]->type().columns() == 1) {
580 this->write("(");
Brian Osman00185012021-02-04 16:07:11 -0500581 this->writeExpression(*arguments[0], Precedence::kMultiplicative);
Brian Osman46787d52020-11-24 14:18:23 -0500582 this->write(" * ");
Brian Osman00185012021-02-04 16:07:11 -0500583 this->writeExpression(*arguments[1], Precedence::kMultiplicative);
Brian Osman46787d52020-11-24 14:18:23 -0500584 this->write(")");
585 } else {
John Stiles791c27d2020-12-30 14:56:57 -0500586 this->writeSimpleIntrinsic(c);
Brian Osman46787d52020-11-24 14:18:23 -0500587 }
John Stiles496b7d12021-05-06 10:26:45 -0400588 return true;
Brian Osman46787d52020-11-24 14:18:23 -0500589 }
John Stiles496b7d12021-05-06 10:26:45 -0400590 case k_faceforward_IntrinsicKind: {
John Stilesad0571f2020-12-10 18:03:10 -0500591 if (arguments[0]->type().columns() == 1) {
592 // ((((Nref) * (I) < 0) ? 1 : -1) * (N))
593 this->write("((((");
Brian Osman00185012021-02-04 16:07:11 -0500594 this->writeExpression(*arguments[2], Precedence::kSequence);
John Stilesad0571f2020-12-10 18:03:10 -0500595 this->write(") * (");
Brian Osman00185012021-02-04 16:07:11 -0500596 this->writeExpression(*arguments[1], Precedence::kSequence);
John Stilesad0571f2020-12-10 18:03:10 -0500597 this->write(") < 0) ? 1 : -1) * (");
Brian Osman00185012021-02-04 16:07:11 -0500598 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stilesad0571f2020-12-10 18:03:10 -0500599 this->write("))");
600 } else {
John Stiles791c27d2020-12-30 14:56:57 -0500601 this->writeSimpleIntrinsic(c);
John Stilesad0571f2020-12-10 18:03:10 -0500602 }
John Stiles496b7d12021-05-06 10:26:45 -0400603 return true;
John Stilesad0571f2020-12-10 18:03:10 -0500604 }
John Stiles496b7d12021-05-06 10:26:45 -0400605 case k_length_IntrinsicKind: {
Brian Osman46787d52020-11-24 14:18:23 -0500606 this->write(arguments[0]->type().columns() == 1 ? "abs(" : "length(");
Brian Osman00185012021-02-04 16:07:11 -0500607 this->writeExpression(*arguments[0], Precedence::kSequence);
Brian Osman46787d52020-11-24 14:18:23 -0500608 this->write(")");
John Stiles496b7d12021-05-06 10:26:45 -0400609 return true;
Brian Osman46787d52020-11-24 14:18:23 -0500610 }
John Stiles496b7d12021-05-06 10:26:45 -0400611 case k_normalize_IntrinsicKind: {
Brian Osman46787d52020-11-24 14:18:23 -0500612 this->write(arguments[0]->type().columns() == 1 ? "sign(" : "normalize(");
Brian Osman00185012021-02-04 16:07:11 -0500613 this->writeExpression(*arguments[0], Precedence::kSequence);
Brian Osman46787d52020-11-24 14:18:23 -0500614 this->write(")");
John Stiles496b7d12021-05-06 10:26:45 -0400615 return true;
Brian Osman46787d52020-11-24 14:18:23 -0500616 }
John Stilesb6981fb2021-09-08 15:11:27 -0400617 case k_packUnorm2x16_IntrinsicKind: {
618 this->write("pack_float_to_unorm2x16(");
619 this->writeExpression(*arguments[0], Precedence::kSequence);
620 this->write(")");
621 return true;
622 }
623 case k_unpackUnorm2x16_IntrinsicKind: {
624 this->write("unpack_unorm2x16_to_float(");
625 this->writeExpression(*arguments[0], Precedence::kSequence);
626 this->write(")");
627 return true;
628 }
629 case k_packSnorm2x16_IntrinsicKind: {
630 this->write("pack_float_to_snorm2x16(");
631 this->writeExpression(*arguments[0], Precedence::kSequence);
632 this->write(")");
633 return true;
634 }
635 case k_unpackSnorm2x16_IntrinsicKind: {
636 this->write("unpack_snorm2x16_to_float(");
637 this->writeExpression(*arguments[0], Precedence::kSequence);
638 this->write(")");
639 return true;
640 }
641 case k_packUnorm4x8_IntrinsicKind: {
642 this->write("pack_float_to_unorm4x8(");
643 this->writeExpression(*arguments[0], Precedence::kSequence);
644 this->write(")");
645 return true;
646 }
647 case k_unpackUnorm4x8_IntrinsicKind: {
648 this->write("unpack_unorm4x8_to_float(");
649 this->writeExpression(*arguments[0], Precedence::kSequence);
650 this->write(")");
651 return true;
652 }
653 case k_packSnorm4x8_IntrinsicKind: {
654 this->write("pack_float_to_snorm4x8(");
655 this->writeExpression(*arguments[0], Precedence::kSequence);
656 this->write(")");
657 return true;
658 }
659 case k_unpackSnorm4x8_IntrinsicKind: {
660 this->write("unpack_snorm4x8_to_float(");
661 this->writeExpression(*arguments[0], Precedence::kSequence);
662 this->write(")");
663 return true;
664 }
665 case k_packHalf2x16_IntrinsicKind: {
666 this->write("as_type<uint>(half2(");
667 this->writeExpression(*arguments[0], Precedence::kSequence);
668 this->write("))");
669 return true;
670 }
671 case k_unpackHalf2x16_IntrinsicKind: {
672 this->write("float2(as_type<half2>(");
673 this->writeExpression(*arguments[0], Precedence::kSequence);
674 this->write("))");
675 return true;
676 }
John Stiles496b7d12021-05-06 10:26:45 -0400677 case k_floatBitsToInt_IntrinsicKind:
678 case k_floatBitsToUint_IntrinsicKind:
679 case k_intBitsToFloat_IntrinsicKind:
680 case k_uintBitsToFloat_IntrinsicKind: {
John Stiles0063a9f2020-12-10 18:01:45 -0500681 this->write(this->getBitcastIntrinsic(c.type()));
682 this->write("(");
Brian Osman00185012021-02-04 16:07:11 -0500683 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stiles0063a9f2020-12-10 18:01:45 -0500684 this->write(")");
John Stiles496b7d12021-05-06 10:26:45 -0400685 return true;
John Stiles0063a9f2020-12-10 18:01:45 -0500686 }
John Stiles496b7d12021-05-06 10:26:45 -0400687 case k_degrees_IntrinsicKind: {
John Stilese2d34f82020-12-10 18:02:02 -0500688 this->write("((");
Brian Osman00185012021-02-04 16:07:11 -0500689 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stilese2d34f82020-12-10 18:02:02 -0500690 this->write(") * 57.2957795)");
John Stiles496b7d12021-05-06 10:26:45 -0400691 return true;
John Stilese2d34f82020-12-10 18:02:02 -0500692 }
John Stiles496b7d12021-05-06 10:26:45 -0400693 case k_radians_IntrinsicKind: {
John Stilese2d34f82020-12-10 18:02:02 -0500694 this->write("((");
Brian Osman00185012021-02-04 16:07:11 -0500695 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stilese2d34f82020-12-10 18:02:02 -0500696 this->write(") * 0.0174532925)");
John Stiles496b7d12021-05-06 10:26:45 -0400697 return true;
John Stilese2d34f82020-12-10 18:02:02 -0500698 }
John Stiles496b7d12021-05-06 10:26:45 -0400699 case k_dFdx_IntrinsicKind: {
John Stilesd7199b22020-12-30 16:22:58 -0500700 this->write("dfdx");
701 this->writeArgumentList(c.arguments());
John Stiles496b7d12021-05-06 10:26:45 -0400702 return true;
John Stilesd7199b22020-12-30 16:22:58 -0500703 }
John Stiles496b7d12021-05-06 10:26:45 -0400704 case k_dFdy_IntrinsicKind: {
Brian Salomond8d85b92021-07-07 09:41:17 -0400705 this->write(fRTFlipName + ".y*dfdy");
John Stilesd7199b22020-12-30 16:22:58 -0500706 this->writeArgumentList(c.arguments());
John Stiles496b7d12021-05-06 10:26:45 -0400707 return true;
John Stilesd7199b22020-12-30 16:22:58 -0500708 }
John Stiles496b7d12021-05-06 10:26:45 -0400709 case k_inverse_IntrinsicKind: {
John Stilesd7199b22020-12-30 16:22:58 -0500710 this->write(this->getInversePolyfill(arguments));
711 this->writeArgumentList(c.arguments());
John Stiles496b7d12021-05-06 10:26:45 -0400712 return true;
John Stilesd7199b22020-12-30 16:22:58 -0500713 }
John Stiles496b7d12021-05-06 10:26:45 -0400714 case k_inversesqrt_IntrinsicKind: {
John Stilesd7199b22020-12-30 16:22:58 -0500715 this->write("rsqrt");
716 this->writeArgumentList(c.arguments());
John Stiles496b7d12021-05-06 10:26:45 -0400717 return true;
John Stilesd7199b22020-12-30 16:22:58 -0500718 }
John Stiles496b7d12021-05-06 10:26:45 -0400719 case k_atan_IntrinsicKind: {
John Stilesd7199b22020-12-30 16:22:58 -0500720 this->write(c.arguments().size() == 2 ? "atan2" : "atan");
721 this->writeArgumentList(c.arguments());
John Stiles496b7d12021-05-06 10:26:45 -0400722 return true;
John Stilesd7199b22020-12-30 16:22:58 -0500723 }
John Stiles496b7d12021-05-06 10:26:45 -0400724 case k_reflect_IntrinsicKind: {
John Stiles791c27d2020-12-30 14:56:57 -0500725 if (arguments[0]->type().columns() == 1) {
726 // We need to synthesize `I - 2 * N * I * N`.
727 String tmpI = this->getTempVariable(arguments[0]->type());
728 String tmpN = this->getTempVariable(arguments[1]->type());
729
730 // (_skTempI = ...
731 this->write("(" + tmpI + " = ");
Brian Osman00185012021-02-04 16:07:11 -0500732 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stiles791c27d2020-12-30 14:56:57 -0500733
734 // , _skTempN = ...
735 this->write(", " + tmpN + " = ");
Brian Osman00185012021-02-04 16:07:11 -0500736 this->writeExpression(*arguments[1], Precedence::kSequence);
John Stiles791c27d2020-12-30 14:56:57 -0500737
738 // , _skTempI - 2 * _skTempN * _skTempI * _skTempN)
739 this->write(", " + tmpI + " - 2 * " + tmpN + " * " + tmpI + " * " + tmpN + ")");
740 } else {
741 this->writeSimpleIntrinsic(c);
742 }
John Stiles496b7d12021-05-06 10:26:45 -0400743 return true;
John Stiles791c27d2020-12-30 14:56:57 -0500744 }
John Stiles496b7d12021-05-06 10:26:45 -0400745 case k_refract_IntrinsicKind: {
John Stiles4b783d62020-12-30 14:58:07 -0500746 if (arguments[0]->type().columns() == 1) {
747 // Metal does implement refract for vectors; rather than reimplementing refract from
748 // scratch, we can replace the call with `refract(float2(I,0), float2(N,0), eta).x`.
749 this->write("(refract(float2(");
Brian Osman00185012021-02-04 16:07:11 -0500750 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stiles4b783d62020-12-30 14:58:07 -0500751 this->write(", 0), float2(");
Brian Osman00185012021-02-04 16:07:11 -0500752 this->writeExpression(*arguments[1], Precedence::kSequence);
John Stiles4b783d62020-12-30 14:58:07 -0500753 this->write(", 0), ");
Brian Osman00185012021-02-04 16:07:11 -0500754 this->writeExpression(*arguments[2], Precedence::kSequence);
John Stiles4b783d62020-12-30 14:58:07 -0500755 this->write(").x)");
756 } else {
757 this->writeSimpleIntrinsic(c);
758 }
John Stiles496b7d12021-05-06 10:26:45 -0400759 return true;
John Stiles4b783d62020-12-30 14:58:07 -0500760 }
John Stiles496b7d12021-05-06 10:26:45 -0400761 case k_roundEven_IntrinsicKind: {
John Stiles23456532020-12-30 18:12:48 -0500762 this->write("rint");
763 this->writeArgumentList(c.arguments());
John Stiles496b7d12021-05-06 10:26:45 -0400764 return true;
John Stiles23456532020-12-30 18:12:48 -0500765 }
John Stiles496b7d12021-05-06 10:26:45 -0400766 case k_bitCount_IntrinsicKind: {
John Stilese7dc7cb2020-12-22 15:37:14 -0500767 this->write("popcount(");
Brian Osman00185012021-02-04 16:07:11 -0500768 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stilese7dc7cb2020-12-22 15:37:14 -0500769 this->write(")");
John Stiles496b7d12021-05-06 10:26:45 -0400770 return true;
John Stilese7dc7cb2020-12-22 15:37:14 -0500771 }
John Stiles496b7d12021-05-06 10:26:45 -0400772 case k_findLSB_IntrinsicKind: {
John Stiles86424eb2020-12-11 11:17:14 -0500773 // Create a temp variable to store the expression, to avoid double-evaluating it.
774 String skTemp = this->getTempVariable(arguments[0]->type());
775 String exprType = this->typeName(arguments[0]->type());
776
777 // ctz returns numbits(type) on zero inputs; GLSL documents it as generating -1 instead.
778 // Use select to detect zero inputs and force a -1 result.
779
780 // (_skTemp1 = (.....), select(ctz(_skTemp1), int4(-1), _skTemp1 == int4(0)))
781 this->write("(");
782 this->write(skTemp);
783 this->write(" = (");
Brian Osman00185012021-02-04 16:07:11 -0500784 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stiles86424eb2020-12-11 11:17:14 -0500785 this->write("), select(ctz(");
786 this->write(skTemp);
787 this->write("), ");
788 this->write(exprType);
789 this->write("(-1), ");
790 this->write(skTemp);
791 this->write(" == ");
792 this->write(exprType);
793 this->write("(0)))");
John Stiles496b7d12021-05-06 10:26:45 -0400794 return true;
John Stiles86424eb2020-12-11 11:17:14 -0500795 }
John Stiles496b7d12021-05-06 10:26:45 -0400796 case k_findMSB_IntrinsicKind: {
John Stiles9685e522020-12-14 11:52:14 -0500797 // Create a temp variable to store the expression, to avoid double-evaluating it.
798 String skTemp1 = this->getTempVariable(arguments[0]->type());
799 String exprType = this->typeName(arguments[0]->type());
800
801 // GLSL findMSB is actually quite different from Metal's clz:
802 // - For signed negative numbers, it returns the first zero bit, not the first one bit!
803 // - For an empty input (0/~0 depending on sign), findMSB gives -1; clz is numbits(type)
804
805 // (_skTemp1 = (.....),
806 this->write("(");
807 this->write(skTemp1);
808 this->write(" = (");
Brian Osman00185012021-02-04 16:07:11 -0500809 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stiles9685e522020-12-14 11:52:14 -0500810 this->write("), ");
811
812 // Signed input types might be negative; we need another helper variable to negate the
813 // input (since we can only find one bits, not zero bits).
814 String skTemp2;
815 if (arguments[0]->type().isSigned()) {
816 // ... _skTemp2 = (select(_skTemp1, ~_skTemp1, _skTemp1 < 0)),
817 skTemp2 = this->getTempVariable(arguments[0]->type());
818 this->write(skTemp2);
819 this->write(" = (select(");
820 this->write(skTemp1);
821 this->write(", ~");
822 this->write(skTemp1);
823 this->write(", ");
824 this->write(skTemp1);
825 this->write(" < 0)), ");
826 } else {
827 skTemp2 = skTemp1;
828 }
829
830 // ... select(int4(clz(_skTemp2)), int4(-1), _skTemp2 == int4(0)))
831 this->write("select(");
832 this->write(this->typeName(c.type()));
833 this->write("(clz(");
834 this->write(skTemp2);
835 this->write(")), ");
836 this->write(this->typeName(c.type()));
837 this->write("(-1), ");
838 this->write(skTemp2);
839 this->write(" == ");
840 this->write(exprType);
841 this->write("(0)))");
John Stiles496b7d12021-05-06 10:26:45 -0400842 return true;
John Stiles9685e522020-12-14 11:52:14 -0500843 }
John Stiles496b7d12021-05-06 10:26:45 -0400844 case k_matrixCompMult_IntrinsicKind: {
John Stilesd7199b22020-12-30 16:22:58 -0500845 this->writeMatrixCompMult();
846 this->writeSimpleIntrinsic(c);
John Stiles496b7d12021-05-06 10:26:45 -0400847 return true;
John Stilesd7199b22020-12-30 16:22:58 -0500848 }
John Stilesfeb1e122021-09-09 14:27:28 -0400849 case k_outerProduct_IntrinsicKind: {
850 this->writeOuterProduct();
851 this->writeSimpleIntrinsic(c);
852 return true;
853 }
John Stilescc2d9cc2021-07-09 17:38:41 -0400854 case k_mix_IntrinsicKind: {
855 SkASSERT(c.arguments().size() == 3);
856 if (arguments[2]->type().componentType().isBoolean()) {
857 // The Boolean forms of GLSL mix() use the select() intrinsic in Metal.
858 this->write("select");
859 this->writeArgumentList(c.arguments());
860 return true;
861 }
862 // The basic form of mix() is supported by Metal as-is.
863 this->writeSimpleIntrinsic(c);
864 return true;
865 }
John Stiles496b7d12021-05-06 10:26:45 -0400866 case k_equal_IntrinsicKind:
867 case k_greaterThan_IntrinsicKind:
868 case k_greaterThanEqual_IntrinsicKind:
869 case k_lessThan_IntrinsicKind:
870 case k_lessThanEqual_IntrinsicKind:
871 case k_notEqual_IntrinsicKind: {
John Stilesd7199b22020-12-30 16:22:58 -0500872 this->write("(");
Brian Osman00185012021-02-04 16:07:11 -0500873 this->writeExpression(*c.arguments()[0], Precedence::kRelational);
John Stilesd7199b22020-12-30 16:22:58 -0500874 switch (kind) {
John Stiles496b7d12021-05-06 10:26:45 -0400875 case k_equal_IntrinsicKind:
John Stilesd7199b22020-12-30 16:22:58 -0500876 this->write(" == ");
877 break;
John Stiles496b7d12021-05-06 10:26:45 -0400878 case k_notEqual_IntrinsicKind:
John Stilesd7199b22020-12-30 16:22:58 -0500879 this->write(" != ");
880 break;
John Stiles496b7d12021-05-06 10:26:45 -0400881 case k_lessThan_IntrinsicKind:
John Stilesd7199b22020-12-30 16:22:58 -0500882 this->write(" < ");
883 break;
John Stiles496b7d12021-05-06 10:26:45 -0400884 case k_lessThanEqual_IntrinsicKind:
John Stilesd7199b22020-12-30 16:22:58 -0500885 this->write(" <= ");
886 break;
John Stiles496b7d12021-05-06 10:26:45 -0400887 case k_greaterThan_IntrinsicKind:
John Stilesd7199b22020-12-30 16:22:58 -0500888 this->write(" > ");
889 break;
John Stiles496b7d12021-05-06 10:26:45 -0400890 case k_greaterThanEqual_IntrinsicKind:
John Stilesd7199b22020-12-30 16:22:58 -0500891 this->write(" >= ");
892 break;
893 default:
John Stilesf57207b2021-02-02 17:50:34 -0500894 SK_ABORT("unsupported comparison intrinsic kind");
John Stilesd7199b22020-12-30 16:22:58 -0500895 }
Brian Osman00185012021-02-04 16:07:11 -0500896 this->writeExpression(*c.arguments()[1], Precedence::kRelational);
John Stilesd7199b22020-12-30 16:22:58 -0500897 this->write(")");
John Stiles496b7d12021-05-06 10:26:45 -0400898 return true;
John Stilesd7199b22020-12-30 16:22:58 -0500899 }
Timothy Liang6403b0e2018-05-17 10:40:04 -0400900 default:
John Stiles496b7d12021-05-06 10:26:45 -0400901 return false;
Timothy Liang6403b0e2018-05-17 10:40:04 -0400902 }
903}
904
John Stilesfcf8cb22020-08-06 14:29:22 -0400905// Assembles a matrix of type floatRxC by resizing another matrix named `x0`.
906// Cells that don't exist in the source matrix will be populated with identity-matrix values.
907void MetalCodeGenerator::assembleMatrixFromMatrix(const Type& sourceMatrix, int rows, int columns) {
908 SkASSERT(rows <= 4);
909 SkASSERT(columns <= 4);
910
John Stilesc18ee4e2021-08-13 17:53:49 -0400911 std::string matrixType = this->typeName(sourceMatrix.componentType());
912
913 const char* separator = "";
John Stilesfcf8cb22020-08-06 14:29:22 -0400914 for (int c = 0; c < columns; ++c) {
John Stilesc18ee4e2021-08-13 17:53:49 -0400915 fExtraFunctions.printf("%s%s%d(", separator, matrixType.c_str(), rows);
916 separator = "), ";
John Stilesfcf8cb22020-08-06 14:29:22 -0400917
918 // Determine how many values to take from the source matrix for this row.
919 int swizzleLength = 0;
920 if (c < sourceMatrix.columns()) {
921 swizzleLength = std::min<>(rows, sourceMatrix.rows());
922 }
923
924 // Emit all the values from the source matrix row.
925 bool firstItem;
926 switch (swizzleLength) {
927 case 0: firstItem = true; break;
928 case 1: firstItem = false; fExtraFunctions.printf("x0[%d].x", c); break;
929 case 2: firstItem = false; fExtraFunctions.printf("x0[%d].xy", c); break;
930 case 3: firstItem = false; fExtraFunctions.printf("x0[%d].xyz", c); break;
931 case 4: firstItem = false; fExtraFunctions.printf("x0[%d].xyzw", c); break;
932 default: SkUNREACHABLE;
933 }
934
935 // Emit the placeholder identity-matrix cells.
936 for (int r = swizzleLength; r < rows; ++r) {
937 fExtraFunctions.printf("%s%s", firstItem ? "" : ", ", (r == c) ? "1.0" : "0.0");
938 firstItem = false;
939 }
940 }
941
942 fExtraFunctions.writeText(")");
943}
944
John Stiles1f7300b2021-07-08 15:40:38 -0400945// Assembles a matrix of type floatCxR by concatenating an arbitrary mix of values, named `x0`,
946// `x1`, etc. An error is written if the expression list don't contain exactly C*R scalars.
John Stiles5abb9e12021-04-06 13:47:19 -0400947void MetalCodeGenerator::assembleMatrixFromExpressions(const AnyConstructor& ctor,
John Stiles1f7300b2021-07-08 15:40:38 -0400948 int columns, int rows) {
John Stilesc18ee4e2021-08-13 17:53:49 -0400949 SkASSERT(rows <= 4);
950 SkASSERT(columns <= 4);
951
952 std::string matrixType = this->typeName(ctor.type().componentType());
John Stilesfcf8cb22020-08-06 14:29:22 -0400953 size_t argIndex = 0;
954 int argPosition = 0;
John Stiles5abb9e12021-04-06 13:47:19 -0400955 auto args = ctor.argumentSpan();
John Stilesfcf8cb22020-08-06 14:29:22 -0400956
John Stilesc18ee4e2021-08-13 17:53:49 -0400957 const char* separator = "";
John Stiles1f7300b2021-07-08 15:40:38 -0400958 for (int r = 0; r < rows; ++r) {
John Stilesc18ee4e2021-08-13 17:53:49 -0400959 fExtraFunctions.printf("%s%s%d(", separator, matrixType.c_str(), rows);
960 separator = "), ";
John Stilesfcf8cb22020-08-06 14:29:22 -0400961
John Stiles1f7300b2021-07-08 15:40:38 -0400962 const char* columnSeparator = "";
963 for (int c = 0; c < columns; ++c) {
964 fExtraFunctions.writeText(columnSeparator);
965 columnSeparator = ", ";
John Stilesfcf8cb22020-08-06 14:29:22 -0400966
967 if (argIndex < args.size()) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400968 const Type& argType = args[argIndex]->type();
Ethan Nicholase6592142020-09-08 10:22:09 -0400969 switch (argType.typeKind()) {
970 case Type::TypeKind::kScalar: {
John Stilesfcf8cb22020-08-06 14:29:22 -0400971 fExtraFunctions.printf("x%zu", argIndex);
972 break;
973 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400974 case Type::TypeKind::kVector: {
John Stilesfcf8cb22020-08-06 14:29:22 -0400975 fExtraFunctions.printf("x%zu[%d]", argIndex, argPosition);
976 break;
977 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400978 case Type::TypeKind::kMatrix: {
John Stilesfcf8cb22020-08-06 14:29:22 -0400979 fExtraFunctions.printf("x%zu[%d][%d]", argIndex,
980 argPosition / argType.rows(),
981 argPosition % argType.rows());
982 break;
983 }
984 default: {
985 SkDEBUGFAIL("incorrect type of argument for matrix constructor");
986 fExtraFunctions.writeText("<error>");
987 break;
988 }
989 }
990
991 ++argPosition;
992 if (argPosition >= argType.columns() * argType.rows()) {
993 ++argIndex;
994 argPosition = 0;
995 }
996 } else {
997 SkDEBUGFAIL("not enough arguments for matrix constructor");
998 fExtraFunctions.writeText("<error>");
999 }
1000 }
1001 }
1002
1003 if (argPosition != 0 || argIndex != args.size()) {
1004 SkDEBUGFAIL("incorrect number of arguments for matrix constructor");
1005 fExtraFunctions.writeText(", <error>");
1006 }
1007
1008 fExtraFunctions.writeText(")");
1009}
1010
John Stiles1bdafbf2020-05-28 12:17:20 -04001011// Generates a constructor for 'matrix' which reorganizes the input arguments into the proper shape.
1012// Keeps track of previously generated constructors so that we won't generate more than one
1013// constructor for any given permutation of input argument types. Returns the name of the
1014// generated constructor method.
John Stiles5abb9e12021-04-06 13:47:19 -04001015String MetalCodeGenerator::getMatrixConstructHelper(const AnyConstructor& c) {
John Stilesc18ee4e2021-08-13 17:53:49 -04001016 const Type& type = c.type();
1017 int columns = type.columns();
1018 int rows = type.rows();
John Stiles5abb9e12021-04-06 13:47:19 -04001019 auto args = c.argumentSpan();
John Stilesc18ee4e2021-08-13 17:53:49 -04001020 String typeName = this->typeName(type);
John Stiles1bdafbf2020-05-28 12:17:20 -04001021
1022 // Create the helper-method name and use it as our lookup key.
1023 String name;
John Stilesc18ee4e2021-08-13 17:53:49 -04001024 name.appendf("%s_from", typeName.c_str());
John Stiles1bdafbf2020-05-28 12:17:20 -04001025 for (const std::unique_ptr<Expression>& expr : args) {
John Stiles36129132020-12-29 12:28:04 -05001026 name.appendf("_%s", this->typeName(expr->type()).c_str());
John Stiles1bdafbf2020-05-28 12:17:20 -04001027 }
1028
1029 // If a helper-method has already been synthesized, we don't need to synthesize it again.
1030 auto [iter, newlyCreated] = fHelpers.insert(name);
1031 if (!newlyCreated) {
1032 return name;
1033 }
1034
1035 // Unlike GLSL, Metal requires that matrices are initialized with exactly R vectors of C
1036 // components apiece. (In Metal 2.0, you can also supply R*C scalars, but you still cannot
1037 // supply a mixture of scalars and vectors.)
John Stilesc18ee4e2021-08-13 17:53:49 -04001038 fExtraFunctions.printf("%s %s(", typeName.c_str(), name.c_str());
John Stiles1bdafbf2020-05-28 12:17:20 -04001039
1040 size_t argIndex = 0;
1041 const char* argSeparator = "";
John Stilesfcf8cb22020-08-06 14:29:22 -04001042 for (const std::unique_ptr<Expression>& expr : args) {
John Stiles1bdafbf2020-05-28 12:17:20 -04001043 fExtraFunctions.printf("%s%s x%zu", argSeparator,
John Stiles36129132020-12-29 12:28:04 -05001044 this->typeName(expr->type()).c_str(), argIndex++);
John Stiles1bdafbf2020-05-28 12:17:20 -04001045 argSeparator = ", ";
1046 }
1047
John Stilesc18ee4e2021-08-13 17:53:49 -04001048 fExtraFunctions.printf(") {\n return %s(", typeName.c_str());
John Stiles1bdafbf2020-05-28 12:17:20 -04001049
John Stiles9aeed132020-11-24 17:36:06 -05001050 if (args.size() == 1 && args.front()->type().isMatrix()) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001051 this->assembleMatrixFromMatrix(args.front()->type(), rows, columns);
John Stilesfcf8cb22020-08-06 14:29:22 -04001052 } else {
John Stiles1f7300b2021-07-08 15:40:38 -04001053 this->assembleMatrixFromExpressions(c, columns, rows);
John Stiles1bdafbf2020-05-28 12:17:20 -04001054 }
1055
John Stilesfcf8cb22020-08-06 14:29:22 -04001056 fExtraFunctions.writeText(");\n}\n");
Ethan Nicholas842d31b2019-01-22 10:59:11 -05001057 return name;
1058}
1059
1060bool MetalCodeGenerator::canCoerce(const Type& t1, const Type& t2) {
1061 if (t1.columns() != t2.columns() || t1.rows() != t2.rows()) {
1062 return false;
1063 }
1064 if (t1.columns() > 1) {
1065 return this->canCoerce(t1.componentType(), t2.componentType());
1066 }
Ethan Nicholase1f55022019-02-05 17:17:40 -05001067 return t1.isFloat() && t2.isFloat();
Ethan Nicholas842d31b2019-01-22 10:59:11 -05001068}
1069
John Stiles8cad6372021-04-07 12:31:13 -04001070bool MetalCodeGenerator::matrixConstructHelperIsNeeded(const ConstructorCompound& c) {
John Stiles2bec8ab2021-04-06 18:40:04 -04001071 SkASSERT(c.type().isMatrix());
John Stiles1bdafbf2020-05-28 12:17:20 -04001072
1073 // GLSL is fairly free-form about inputs to its matrix constructors, but Metal is not; it
1074 // expects exactly R vectors of C components apiece. (Metal 2.0 also allows a list of R*C
1075 // scalars.) Some cases are simple to translate and so we handle those inline--e.g. a list of
1076 // scalars can be constructed trivially. In more complex cases, we generate a helper function
1077 // that converts our inputs into a properly-shaped matrix.
1078 // A matrix construct helper method is always used if any input argument is a matrix.
1079 // Helper methods are also necessary when any argument would span multiple rows. For instance:
1080 //
1081 // float2 x = (1, 2);
1082 // float3x2(x, 3, 4, 5, 6) = | 1 3 5 | = no helper needed; conversion can be done inline
1083 // | 2 4 6 |
1084 //
1085 // float2 x = (2, 3);
1086 // float3x2(1, x, 4, 5, 6) = | 1 3 5 | = x spans multiple rows; a helper method will be used
1087 // | 2 4 6 |
1088 //
1089 // float4 x = (1, 2, 3, 4);
1090 // float2x2(x) = | 1 3 | = x spans multiple rows; a helper method will be used
1091 // | 2 4 |
1092 //
1093
1094 int position = 0;
Ethan Nicholasf70f0442020-09-29 12:41:35 -04001095 for (const std::unique_ptr<Expression>& expr : c.arguments()) {
John Stiles1bdafbf2020-05-28 12:17:20 -04001096 // If an input argument is a matrix, we need a helper function.
John Stiles9aeed132020-11-24 17:36:06 -05001097 if (expr->type().isMatrix()) {
John Stiles1bdafbf2020-05-28 12:17:20 -04001098 return true;
1099 }
Ethan Nicholas30d30222020-09-11 12:27:26 -04001100 position += expr->type().columns();
1101 if (position > c.type().rows()) {
John Stiles1bdafbf2020-05-28 12:17:20 -04001102 // An input argument would span multiple rows; a helper function is required.
1103 return true;
1104 }
Ethan Nicholas30d30222020-09-11 12:27:26 -04001105 if (position == c.type().rows()) {
John Stiles1bdafbf2020-05-28 12:17:20 -04001106 // We've advanced to the end of a row. Wrap to the start of the next row.
1107 position = 0;
1108 }
1109 }
1110
1111 return false;
1112}
1113
John Stiles5abb9e12021-04-06 13:47:19 -04001114void MetalCodeGenerator::writeConstructorMatrixResize(const ConstructorMatrixResize& c,
1115 Precedence parentPrecedence) {
1116 // Matrix-resize via casting doesn't natively exist in Metal at all, so we always need to use a
1117 // matrix-construct helper here.
1118 this->write(this->getMatrixConstructHelper(c));
1119 this->write("(");
1120 this->writeExpression(*c.argument(), Precedence::kSequence);
1121 this->write(")");
1122}
1123
John Stiles8cad6372021-04-07 12:31:13 -04001124void MetalCodeGenerator::writeConstructorCompound(const ConstructorCompound& c,
1125 Precedence parentPrecedence) {
John Stiles6de2e1d2021-07-09 12:41:55 -04001126 if (c.type().isVector()) {
1127 this->writeConstructorCompoundVector(c, parentPrecedence);
1128 } else if (c.type().isMatrix()) {
John Stiles8cad6372021-04-07 12:31:13 -04001129 this->writeConstructorCompoundMatrix(c, parentPrecedence);
John Stiles2bec8ab2021-04-06 18:40:04 -04001130 } else {
Ethan Nicholas39f6da42021-08-23 13:10:07 -04001131 fContext.fErrors->error(c.fOffset, "unsupported compound constructor");
John Stiles2bec8ab2021-04-06 18:40:04 -04001132 }
1133}
John Stiles7384b372021-04-01 13:48:15 -04001134
John Stilesc18ee4e2021-08-13 17:53:49 -04001135String MetalCodeGenerator::getVectorFromMat2x2ConstructorHelper(const Type& matrixType) {
1136 SkASSERT(matrixType.isMatrix());
1137 SkASSERT(matrixType.rows() == 2);
1138 SkASSERT(matrixType.columns() == 2);
John Stiles6de2e1d2021-07-09 12:41:55 -04001139
John Stilesc18ee4e2021-08-13 17:53:49 -04001140 String baseType = this->typeName(matrixType.componentType());
1141 String name = String::printf("%s4_from_%s2x2", baseType.c_str(), baseType.c_str());
1142 if (fHelpers.find(name) == fHelpers.end()) {
1143 fHelpers.insert(name);
1144
1145 fExtraFunctions.printf(R"(
1146%s4 %s(%s2x2 x) {
1147 return %s4(x[0].xy, x[1].xy);
1148}
1149)", baseType.c_str(), name.c_str(), baseType.c_str(), baseType.c_str());
John Stiles6de2e1d2021-07-09 12:41:55 -04001150 }
John Stilesc18ee4e2021-08-13 17:53:49 -04001151
1152 return name;
John Stiles6de2e1d2021-07-09 12:41:55 -04001153}
1154
1155void MetalCodeGenerator::writeConstructorCompoundVector(const ConstructorCompound& c,
1156 Precedence parentPrecedence) {
1157 SkASSERT(c.type().isVector());
1158
1159 // Metal supports constructing vectors from a mix of scalars and vectors, but not matrices.
1160 // GLSL supports vec4(mat2x2), so we detect that case here and emit a helper function.
1161 if (c.type().columns() == 4 && c.argumentSpan().size() == 1) {
1162 const Expression& expr = *c.argumentSpan().front();
1163 if (expr.type().isMatrix()) {
John Stilesc18ee4e2021-08-13 17:53:49 -04001164 this->write(this->getVectorFromMat2x2ConstructorHelper(expr.type()));
1165 this->write("(");
John Stiles6de2e1d2021-07-09 12:41:55 -04001166 this->writeExpression(expr, Precedence::kSequence);
1167 this->write(")");
1168 return;
1169 }
1170 }
1171
1172 this->writeAnyConstructor(c, "(", ")", parentPrecedence);
1173}
1174
John Stiles8cad6372021-04-07 12:31:13 -04001175void MetalCodeGenerator::writeConstructorCompoundMatrix(const ConstructorCompound& c,
1176 Precedence parentPrecedence) {
John Stiles6de2e1d2021-07-09 12:41:55 -04001177 SkASSERT(c.type().isMatrix());
1178
John Stiles1bdafbf2020-05-28 12:17:20 -04001179 // Emit and invoke a matrix-constructor helper method if one is necessary.
1180 if (this->matrixConstructHelperIsNeeded(c)) {
1181 this->write(this->getMatrixConstructHelper(c));
John Stiles1fa15b12020-05-28 17:36:54 +00001182 this->write("(");
1183 const char* separator = "";
Ethan Nicholasf70f0442020-09-29 12:41:35 -04001184 for (const std::unique_ptr<Expression>& expr : c.arguments()) {
John Stiles1fa15b12020-05-28 17:36:54 +00001185 this->write(separator);
1186 separator = ", ";
Brian Osman00185012021-02-04 16:07:11 -05001187 this->writeExpression(*expr, Precedence::kSequence);
John Stilesdaa573e2020-05-28 12:17:20 -04001188 }
John Stiles1fa15b12020-05-28 17:36:54 +00001189 this->write(")");
John Stiles1bdafbf2020-05-28 12:17:20 -04001190 return;
John Stilesdaa573e2020-05-28 12:17:20 -04001191 }
John Stiles1bdafbf2020-05-28 12:17:20 -04001192
John Stiles2bec8ab2021-04-06 18:40:04 -04001193 // Metal doesn't allow creating matrices by passing in scalars and vectors in a jumble; it
1194 // requires your scalars to be grouped up into columns. Because `matrixConstructHelperIsNeeded`
1195 // returned false, we know that none of our scalars/vectors "wrap" across across a column, so we
1196 // can group our inputs up and synthesize a constructor for each column.
1197 const Type& matrixType = c.type();
1198 const Type& columnType = matrixType.componentType().toCompound(
1199 fContext, /*columns=*/matrixType.rows(), /*rows=*/1);
1200
1201 this->writeType(matrixType);
John Stiles7384b372021-04-01 13:48:15 -04001202 this->write("(");
John Stiles1bdafbf2020-05-28 12:17:20 -04001203 const char* separator = "";
1204 int scalarCount = 0;
Ethan Nicholasf70f0442020-09-29 12:41:35 -04001205 for (const std::unique_ptr<Expression>& arg : c.arguments()) {
John Stiles1bdafbf2020-05-28 12:17:20 -04001206 this->write(separator);
1207 separator = ", ";
John Stiles2bec8ab2021-04-06 18:40:04 -04001208 if (arg->type().columns() < matrixType.rows()) {
1209 // Write a `floatN(` constructor to group scalars and smaller vectors together.
John Stiles1bdafbf2020-05-28 12:17:20 -04001210 if (!scalarCount) {
John Stiles2bec8ab2021-04-06 18:40:04 -04001211 this->writeType(columnType);
John Stiles1bdafbf2020-05-28 12:17:20 -04001212 this->write("(");
1213 }
John Stiles2bec8ab2021-04-06 18:40:04 -04001214 scalarCount += arg->type().columns();
John Stiles1bdafbf2020-05-28 12:17:20 -04001215 }
Brian Osman00185012021-02-04 16:07:11 -05001216 this->writeExpression(*arg, Precedence::kSequence);
John Stiles2bec8ab2021-04-06 18:40:04 -04001217 if (scalarCount && scalarCount == matrixType.rows()) {
1218 // Close our `floatN(...` constructor block from above.
John Stiles1bdafbf2020-05-28 12:17:20 -04001219 this->write(")");
1220 scalarCount = 0;
1221 }
1222 }
John Stiles7384b372021-04-01 13:48:15 -04001223 this->write(")");
Ethan Nicholascc305772017-10-13 16:17:45 -04001224}
1225
John Stilesb14a8192021-04-05 11:40:46 -04001226void MetalCodeGenerator::writeAnyConstructor(const AnyConstructor& c,
1227 const char* leftBracket,
1228 const char* rightBracket,
1229 Precedence parentPrecedence) {
John Stilese1182782021-03-30 22:09:37 -04001230 this->writeType(c.type());
John Stilesb14a8192021-04-05 11:40:46 -04001231 this->write(leftBracket);
John Stiles7384b372021-04-01 13:48:15 -04001232 const char* separator = "";
John Stilesb14a8192021-04-05 11:40:46 -04001233 for (const std::unique_ptr<Expression>& arg : c.argumentSpan()) {
John Stiles7384b372021-04-01 13:48:15 -04001234 this->write(separator);
1235 separator = ", ";
1236 this->writeExpression(*arg, Precedence::kSequence);
1237 }
John Stilesb14a8192021-04-05 11:40:46 -04001238 this->write(rightBracket);
John Stiles7384b372021-04-01 13:48:15 -04001239}
1240
John Stilesb14a8192021-04-05 11:40:46 -04001241void MetalCodeGenerator::writeCastConstructor(const AnyConstructor& c,
1242 const char* leftBracket,
1243 const char* rightBracket,
1244 Precedence parentPrecedence) {
1245 // If the type is coercible, emit it directly without the cast.
1246 auto args = c.argumentSpan();
1247 if (args.size() == 1) {
1248 if (this->canCoerce(c.type(), args.front()->type())) {
1249 this->writeExpression(*args.front(), parentPrecedence);
1250 return;
1251 }
John Stilesfd7252f2021-04-04 22:24:40 -04001252 }
1253
John Stilesb14a8192021-04-05 11:40:46 -04001254 return this->writeAnyConstructor(c, leftBracket, rightBracket, parentPrecedence);
John Stilesfd7252f2021-04-04 22:24:40 -04001255}
1256
Ethan Nicholascc305772017-10-13 16:17:45 -04001257void MetalCodeGenerator::writeFragCoord() {
Brian Salomond8d85b92021-07-07 09:41:17 -04001258 SkASSERT(fRTFlipName.length());
1259 this->write("float4(_fragCoord.x, ");
1260 this->write(fRTFlipName.c_str());
1261 this->write(".x + ");
1262 this->write(fRTFlipName.c_str());
1263 this->write(".y * _fragCoord.y, 0.0, _fragCoord.w)");
Ethan Nicholascc305772017-10-13 16:17:45 -04001264}
1265
1266void MetalCodeGenerator::writeVariableReference(const VariableReference& ref) {
John Stiles06b84ef2020-12-09 12:35:48 -05001267 // When assembling out-param helper functions, we copy variables into local clones with matching
John Stilesf7410bd2021-01-19 13:07:55 -05001268 // names. We never want to prepend "_in." or "_globals." when writing these variables since
John Stiles06b84ef2020-12-09 12:35:48 -05001269 // we're actually targeting the clones.
1270 if (fIgnoreVariableReferenceModifiers) {
1271 this->writeName(ref.variable()->name());
1272 return;
1273 }
1274
Ethan Nicholas78686922020-10-08 06:46:27 -04001275 switch (ref.variable()->modifiers().fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001276 case SK_FRAGCOLOR_BUILTIN:
John Stilesf7410bd2021-01-19 13:07:55 -05001277 this->write("_out.sk_FragColor");
Ethan Nicholascc305772017-10-13 16:17:45 -04001278 break;
Timothy Liang6403b0e2018-05-17 10:40:04 -04001279 case SK_FRAGCOORD_BUILTIN:
1280 this->writeFragCoord();
1281 break;
Timothy Liangdc89f192018-06-13 09:20:31 -04001282 case SK_VERTEXID_BUILTIN:
1283 this->write("sk_VertexID");
1284 break;
1285 case SK_INSTANCEID_BUILTIN:
1286 this->write("sk_InstanceID");
1287 break;
Timothy Liang7b8875d2018-08-10 09:42:31 -04001288 case SK_CLOCKWISE_BUILTIN:
1289 // We'd set the front facing winding in the MTLRenderCommandEncoder to be counter
Brian Salomonf4ba4ec2020-03-19 15:54:28 -04001290 // clockwise to match Skia convention.
Brian Salomond8d85b92021-07-07 09:41:17 -04001291 this->write("(" + fRTFlipName + ".y < 0 ? _frontFacing : !_frontFacing)");
Timothy Liang7b8875d2018-08-10 09:42:31 -04001292 break;
Ethan Nicholascc305772017-10-13 16:17:45 -04001293 default:
Ethan Nicholas78686922020-10-08 06:46:27 -04001294 const Variable& var = *ref.variable();
Ethan Nicholas453f67f2020-10-09 10:43:45 -04001295 if (var.storage() == Variable::Storage::kGlobal) {
Ethan Nicholas78686922020-10-08 06:46:27 -04001296 if (var.modifiers().fFlags & Modifiers::kIn_Flag) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001297 this->write("_in.");
Ethan Nicholas78686922020-10-08 06:46:27 -04001298 } else if (var.modifiers().fFlags & Modifiers::kOut_Flag) {
John Stilesf7410bd2021-01-19 13:07:55 -05001299 this->write("_out.");
Ethan Nicholas78686922020-10-08 06:46:27 -04001300 } else if (var.modifiers().fFlags & Modifiers::kUniform_Flag &&
1301 var.type().typeKind() != Type::TypeKind::kSampler) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001302 this->write("_uniforms.");
1303 } else {
John Stilesf7410bd2021-01-19 13:07:55 -05001304 this->write("_globals.");
Ethan Nicholascc305772017-10-13 16:17:45 -04001305 }
1306 }
Ethan Nicholas78686922020-10-08 06:46:27 -04001307 this->writeName(var.name());
Ethan Nicholascc305772017-10-13 16:17:45 -04001308 }
1309}
1310
1311void MetalCodeGenerator::writeIndexExpression(const IndexExpression& expr) {
Brian Osman00185012021-02-04 16:07:11 -05001312 this->writeExpression(*expr.base(), Precedence::kPostfix);
Ethan Nicholascc305772017-10-13 16:17:45 -04001313 this->write("[");
Brian Osman00185012021-02-04 16:07:11 -05001314 this->writeExpression(*expr.index(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001315 this->write("]");
1316}
1317
1318void MetalCodeGenerator::writeFieldAccess(const FieldAccess& f) {
Ethan Nicholas7a95b202020-10-09 11:55:40 -04001319 const Type::Field* field = &f.base()->type().fields()[f.fieldIndex()];
1320 if (FieldAccess::OwnerKind::kDefault == f.ownerKind()) {
Brian Osman00185012021-02-04 16:07:11 -05001321 this->writeExpression(*f.base(), Precedence::kPostfix);
Ethan Nicholascc305772017-10-13 16:17:45 -04001322 this->write(".");
1323 }
Timothy Liang7d637782018-06-05 09:58:07 -04001324 switch (field->fModifiers.fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001325 case SK_POSITION_BUILTIN:
John Stilesf7410bd2021-01-19 13:07:55 -05001326 this->write("_out.sk_Position");
Ethan Nicholascc305772017-10-13 16:17:45 -04001327 break;
1328 default:
Timothy Liang7d637782018-06-05 09:58:07 -04001329 if (field->fName == "sk_PointSize") {
John Stilesf7410bd2021-01-19 13:07:55 -05001330 this->write("_out.sk_PointSize");
Timothy Liang7d637782018-06-05 09:58:07 -04001331 } else {
Ethan Nicholas7a95b202020-10-09 11:55:40 -04001332 if (FieldAccess::OwnerKind::kAnonymousInterfaceBlock == f.ownerKind()) {
John Stilesf7410bd2021-01-19 13:07:55 -05001333 this->write("_globals.");
Timothy Liang7d637782018-06-05 09:58:07 -04001334 this->write(fInterfaceBlockNameMap[fInterfaceBlockMap[field]]);
1335 this->write("->");
1336 }
Timothy Liang651286f2018-06-07 09:55:33 -04001337 this->writeName(field->fName);
Timothy Lianga06f2152018-05-24 15:33:31 -04001338 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001339 }
1340}
1341
1342void MetalCodeGenerator::writeSwizzle(const Swizzle& swizzle) {
Brian Osman00185012021-02-04 16:07:11 -05001343 this->writeExpression(*swizzle.base(), Precedence::kPostfix);
Ethan Nicholascc305772017-10-13 16:17:45 -04001344 this->write(".");
Ethan Nicholas6b4d5812020-10-12 16:11:51 -04001345 for (int c : swizzle.components()) {
Brian Osman25647672020-09-15 15:16:56 -04001346 SkASSERT(c >= 0 && c <= 3);
1347 this->write(&("x\0y\0z\0w\0"[c * 2]));
Ethan Nicholascc305772017-10-13 16:17:45 -04001348 }
1349}
1350
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001351void MetalCodeGenerator::writeMatrixTimesEqualHelper(const Type& left, const Type& right,
1352 const Type& result) {
John Stilesc985e142021-05-13 14:01:48 -04001353 SkASSERT(left.isMatrix());
1354 SkASSERT(right.isMatrix());
1355 SkASSERT(result.isMatrix());
1356 SkASSERT(left.rows() == right.rows());
1357 SkASSERT(left.columns() == right.columns());
1358 SkASSERT(left.rows() == result.rows());
1359 SkASSERT(left.columns() == result.columns());
1360
1361 String key = "Matrix *= " + this->typeName(left) + ":" + this->typeName(right);
John Stiles56233d12021-02-03 13:03:29 -05001362
1363 auto [iter, wasInserted] = fHelpers.insert(key);
1364 if (wasInserted) {
John Stiles368db7c2020-12-29 11:20:08 -05001365 fExtraFunctions.printf("thread %s& operator*=(thread %s& left, thread const %s& right) {\n"
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001366 " left = left * right;\n"
1367 " return left;\n"
John Stiles368db7c2020-12-29 11:20:08 -05001368 "}\n",
1369 this->typeName(result).c_str(), this->typeName(left).c_str(),
1370 this->typeName(right).c_str());
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001371 }
1372}
1373
John Stiles39346472021-04-29 14:39:35 -04001374void MetalCodeGenerator::writeMatrixEqualityHelpers(const Type& left, const Type& right) {
1375 SkASSERT(left.isMatrix());
1376 SkASSERT(right.isMatrix());
1377 SkASSERT(left.rows() == right.rows());
1378 SkASSERT(left.columns() == right.columns());
John Stiles01cdf012021-02-10 09:53:41 -05001379
John Stilesc985e142021-05-13 14:01:48 -04001380 String key = "Matrix == " + this->typeName(left) + ":" + this->typeName(right);
John Stiles01cdf012021-02-10 09:53:41 -05001381
1382 auto [iter, wasInserted] = fHelpers.insert(key);
1383 if (wasInserted) {
John Stiles82d4c122021-08-10 16:03:23 -04001384 fExtraFunctionPrototypes.printf(R"(
1385thread bool operator==(const %s left, const %s right);
1386thread bool operator!=(const %s left, const %s right);
1387)",
1388 this->typeName(left).c_str(),
1389 this->typeName(right).c_str(),
1390 this->typeName(left).c_str(),
1391 this->typeName(right).c_str());
1392
John Stiles01cdf012021-02-10 09:53:41 -05001393 fExtraFunctions.printf(
1394 "thread bool operator==(const %s left, const %s right) {\n"
John Stiles39346472021-04-29 14:39:35 -04001395 " return ",
John Stiles01cdf012021-02-10 09:53:41 -05001396 this->typeName(left).c_str(), this->typeName(right).c_str());
1397
John Stiles39346472021-04-29 14:39:35 -04001398 const char* separator = "";
John Stiles01cdf012021-02-10 09:53:41 -05001399 for (int index=0; index<left.columns(); ++index) {
John Stiles39346472021-04-29 14:39:35 -04001400 fExtraFunctions.printf("%sall(left[%d] == right[%d])", separator, index, index);
1401 separator = " &&\n ";
John Stiles01cdf012021-02-10 09:53:41 -05001402 }
John Stiles39346472021-04-29 14:39:35 -04001403
1404 fExtraFunctions.printf(
1405 ";\n"
1406 "}\n"
1407 "thread bool operator!=(const %s left, const %s right) {\n"
1408 " return !(left == right);\n"
1409 "}\n",
1410 this->typeName(left).c_str(), this->typeName(right).c_str());
John Stiles01cdf012021-02-10 09:53:41 -05001411 }
1412}
1413
John Stilesc985e142021-05-13 14:01:48 -04001414void MetalCodeGenerator::writeMatrixDivisionHelpers(const Type& type) {
1415 SkASSERT(type.isMatrix());
1416
1417 String key = "Matrix / " + this->typeName(type);
1418
1419 auto [iter, wasInserted] = fHelpers.insert(key);
1420 if (wasInserted) {
1421 String typeName = this->typeName(type);
1422
1423 fExtraFunctions.printf(
1424 "thread %s operator/(const %s left, const %s right) {\n"
1425 " return %s(",
1426 typeName.c_str(), typeName.c_str(), typeName.c_str(), typeName.c_str());
1427
1428 const char* separator = "";
1429 for (int index=0; index<type.columns(); ++index) {
1430 fExtraFunctions.printf("%sleft[%d] / right[%d]", separator, index, index);
1431 separator = ", ";
1432 }
1433
1434 fExtraFunctions.printf(");\n"
1435 "}\n"
1436 "thread %s& operator/=(thread %s& left, thread const %s& right) {\n"
1437 " left = left / right;\n"
1438 " return left;\n"
1439 "}\n",
1440 typeName.c_str(), typeName.c_str(), typeName.c_str());
1441 }
1442}
1443
John Stiles39346472021-04-29 14:39:35 -04001444void MetalCodeGenerator::writeArrayEqualityHelpers(const Type& type) {
1445 SkASSERT(type.isArray());
John Stiles01cdf012021-02-10 09:53:41 -05001446
John Stiles39346472021-04-29 14:39:35 -04001447 // If the array's component type needs a helper as well, we need to emit that one first.
1448 this->writeEqualityHelpers(type.componentType(), type.componentType());
1449
1450 auto [iter, wasInserted] = fHelpers.insert("ArrayEquality []");
1451 if (wasInserted) {
John Stiles82d4c122021-08-10 16:03:23 -04001452 fExtraFunctionPrototypes.writeText(R"(
1453template <typename T1, typename T2, size_t N>
1454bool operator==(thread const array<T1, N>& left, thread const array<T2, N>& right);
1455template <typename T1, typename T2, size_t N>
1456bool operator!=(thread const array<T1, N>& left, thread const array<T2, N>& right);
1457)");
John Stiles39346472021-04-29 14:39:35 -04001458 fExtraFunctions.writeText(R"(
John Stilese3ae9682021-08-05 10:35:01 -04001459template <typename T1, typename T2, size_t N>
1460bool operator==(thread const array<T1, N>& left, thread const array<T2, N>& right) {
John Stiles39346472021-04-29 14:39:35 -04001461 for (size_t index = 0; index < N; ++index) {
John Stilese076c382021-08-10 16:56:23 +00001462 if (!all(left[index] == right[index])) {
John Stiles39346472021-04-29 14:39:35 -04001463 return false;
1464 }
1465 }
1466 return true;
1467}
1468
John Stilese3ae9682021-08-05 10:35:01 -04001469template <typename T1, typename T2, size_t N>
1470bool operator!=(thread const array<T1, N>& left, thread const array<T2, N>& right) {
John Stiles39346472021-04-29 14:39:35 -04001471 return !(left == right);
1472}
1473)");
1474 }
1475}
1476
1477void MetalCodeGenerator::writeStructEqualityHelpers(const Type& type) {
1478 SkASSERT(type.isStruct());
1479 String key = "StructEquality " + this->typeName(type);
John Stiles01cdf012021-02-10 09:53:41 -05001480
1481 auto [iter, wasInserted] = fHelpers.insert(key);
1482 if (wasInserted) {
John Stiles39346472021-04-29 14:39:35 -04001483 // If one of the struct's fields needs a helper as well, we need to emit that one first.
1484 for (const Type::Field& field : type.fields()) {
1485 this->writeEqualityHelpers(*field.fType, *field.fType);
John Stiles830c69c2021-04-28 17:16:16 -04001486 }
John Stiles39346472021-04-29 14:39:35 -04001487
1488 // Write operator== and operator!= for this struct, since those are assumed to exist in SkSL
1489 // and GLSL but do not exist by default in Metal.
John Stiles82d4c122021-08-10 16:03:23 -04001490 fExtraFunctionPrototypes.printf(R"(
1491thread bool operator==(thread const %s& left, thread const %s& right);
1492thread bool operator!=(thread const %s& left, thread const %s& right);
1493)",
1494 this->typeName(type).c_str(),
1495 this->typeName(type).c_str(),
1496 this->typeName(type).c_str(),
1497 this->typeName(type).c_str());
1498
John Stiles39346472021-04-29 14:39:35 -04001499 fExtraFunctions.printf(
1500 "thread bool operator==(thread const %s& left, thread const %s& right) {\n"
1501 " return ",
1502 this->typeName(type).c_str(),
1503 this->typeName(type).c_str());
1504
1505 const char* separator = "";
1506 for (const Type::Field& field : type.fields()) {
1507 fExtraFunctions.printf("%s(left.%.*s == right.%.*s)",
1508 separator,
1509 (int)field.fName.size(), field.fName.data(),
1510 (int)field.fName.size(), field.fName.data());
1511 separator = " &&\n ";
1512 }
1513 fExtraFunctions.printf(
1514 ";\n"
1515 "}\n"
1516 "thread bool operator!=(thread const %s& left, thread const %s& right) {\n"
1517 " return !(left == right);\n"
1518 "}\n",
1519 this->typeName(type).c_str(),
1520 this->typeName(type).c_str());
1521 }
1522}
1523
1524void MetalCodeGenerator::writeEqualityHelpers(const Type& leftType, const Type& rightType) {
1525 if (leftType.isArray() && rightType.isArray()) {
1526 this->writeArrayEqualityHelpers(leftType);
1527 return;
1528 }
1529 if (leftType.isStruct() && rightType.isStruct()) {
1530 this->writeStructEqualityHelpers(leftType);
1531 return;
1532 }
1533 if (leftType.isMatrix() && rightType.isMatrix()) {
1534 this->writeMatrixEqualityHelpers(leftType, rightType);
1535 return;
John Stiles01cdf012021-02-10 09:53:41 -05001536 }
1537}
1538
John Stiles6b131292021-05-12 17:12:21 -04001539void MetalCodeGenerator::writeNumberAsMatrix(const Expression& expr, const Type& matrixType) {
1540 SkASSERT(expr.type().isNumber());
1541 SkASSERT(matrixType.isMatrix());
1542
1543 // Componentwise multiply the scalar against a matrix of the desired size which contains all 1s.
1544 this->write("(");
1545 this->writeType(matrixType);
1546 this->write("(");
1547
1548 const char* separator = "";
1549 for (int index = matrixType.slotCount(); index--;) {
1550 this->write(separator);
1551 this->write("1.0");
1552 separator = ", ";
1553 }
1554
1555 this->write(") * ");
1556 this->writeExpression(expr, Precedence::kMultiplicative);
1557 this->write(")");
1558}
1559
Ethan Nicholascc305772017-10-13 16:17:45 -04001560void MetalCodeGenerator::writeBinaryExpression(const BinaryExpression& b,
1561 Precedence parentPrecedence) {
John Stiles2d4f9592020-10-30 10:29:12 -04001562 const Expression& left = *b.left();
1563 const Expression& right = *b.right();
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001564 const Type& leftType = left.type();
1565 const Type& rightType = right.type();
John Stiles45990502021-02-16 10:55:27 -05001566 Operator op = b.getOperator();
1567 Precedence precedence = op.getBinaryPrecedence();
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001568 bool needParens = precedence >= parentPrecedence;
John Stiles45990502021-02-16 10:55:27 -05001569 switch (op.kind()) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001570 case Token::Kind::TK_EQEQ:
John Stiles39346472021-04-29 14:39:35 -04001571 this->writeEqualityHelpers(leftType, rightType);
John Stiles9aeed132020-11-24 17:36:06 -05001572 if (leftType.isVector()) {
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001573 this->write("all");
1574 needParens = true;
1575 }
1576 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001577 case Token::Kind::TK_NEQ:
John Stiles39346472021-04-29 14:39:35 -04001578 this->writeEqualityHelpers(leftType, rightType);
John Stiles9aeed132020-11-24 17:36:06 -05001579 if (leftType.isVector()) {
Jim Van Verth36477b42019-04-11 14:57:30 -04001580 this->write("any");
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001581 needParens = true;
1582 }
1583 break;
1584 default:
1585 break;
1586 }
John Stiles39346472021-04-29 14:39:35 -04001587 if (leftType.isMatrix() && rightType.isMatrix() && op.kind() == Token::Kind::TK_STAREQ) {
1588 this->writeMatrixTimesEqualHelper(leftType, rightType, b.type());
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001589 }
John Stilesc985e142021-05-13 14:01:48 -04001590 if (op.removeAssignment().kind() == Token::Kind::TK_SLASH &&
1591 ((leftType.isMatrix() && rightType.isMatrix()) ||
1592 (leftType.isScalar() && rightType.isMatrix()) ||
1593 (leftType.isMatrix() && rightType.isScalar()))) {
1594 this->writeMatrixDivisionHelpers(leftType.isMatrix() ? leftType : rightType);
1595 }
1596 if (needParens) {
1597 this->write("(");
1598 }
John Stiles6011bbc2021-05-19 22:56:18 -04001599 bool needMatrixSplatOnScalar = rightType.isMatrix() && leftType.isNumber() &&
1600 op.isValidForMatrixOrVector() &&
John Stiles6b131292021-05-12 17:12:21 -04001601 op.removeAssignment().kind() != Token::Kind::TK_STAR;
1602 if (needMatrixSplatOnScalar) {
1603 this->writeNumberAsMatrix(left, rightType);
1604 } else {
1605 this->writeExpression(left, precedence);
1606 }
John Stiles45990502021-02-16 10:55:27 -05001607 if (op.kind() != Token::Kind::TK_EQ && op.isAssignment() &&
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001608 left.kind() == Expression::Kind::kSwizzle && !left.hasSideEffects()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001609 // This doesn't compile in Metal:
1610 // float4 x = float4(1);
1611 // x.xy *= float2x2(...);
1612 // with the error message "non-const reference cannot bind to vector element",
1613 // but switching it to x.xy = x.xy * float2x2(...) fixes it. We perform this tranformation
1614 // as long as the LHS has no side effects, and hope for the best otherwise.
1615 this->write(" = ");
Brian Osman00185012021-02-04 16:07:11 -05001616 this->writeExpression(left, Precedence::kAssignment);
Ethan Nicholascc305772017-10-13 16:17:45 -04001617 this->write(" ");
John Stiles7cbe66b2021-05-12 17:01:23 -04001618 this->write(OperatorName(op.removeAssignment()));
Ethan Nicholascc305772017-10-13 16:17:45 -04001619 this->write(" ");
1620 } else {
John Stilesd6449e92020-11-30 09:13:23 -05001621 this->write(String(" ") + OperatorName(op) + " ");
Ethan Nicholascc305772017-10-13 16:17:45 -04001622 }
John Stiles6b131292021-05-12 17:12:21 -04001623
John Stiles6011bbc2021-05-19 22:56:18 -04001624 needMatrixSplatOnScalar = leftType.isMatrix() && rightType.isNumber() &&
1625 op.isValidForMatrixOrVector() &&
John Stiles6b131292021-05-12 17:12:21 -04001626 op.removeAssignment().kind() != Token::Kind::TK_STAR;
1627 if (needMatrixSplatOnScalar) {
1628 this->writeNumberAsMatrix(right, leftType);
1629 } else {
1630 this->writeExpression(right, precedence);
1631 }
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001632 if (needParens) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001633 this->write(")");
1634 }
1635}
1636
1637void MetalCodeGenerator::writeTernaryExpression(const TernaryExpression& t,
1638 Precedence parentPrecedence) {
Brian Osman00185012021-02-04 16:07:11 -05001639 if (Precedence::kTernary >= parentPrecedence) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001640 this->write("(");
1641 }
Brian Osman00185012021-02-04 16:07:11 -05001642 this->writeExpression(*t.test(), Precedence::kTernary);
Ethan Nicholascc305772017-10-13 16:17:45 -04001643 this->write(" ? ");
Brian Osman00185012021-02-04 16:07:11 -05001644 this->writeExpression(*t.ifTrue(), Precedence::kTernary);
Ethan Nicholascc305772017-10-13 16:17:45 -04001645 this->write(" : ");
Brian Osman00185012021-02-04 16:07:11 -05001646 this->writeExpression(*t.ifFalse(), Precedence::kTernary);
1647 if (Precedence::kTernary >= parentPrecedence) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001648 this->write(")");
1649 }
1650}
1651
1652void MetalCodeGenerator::writePrefixExpression(const PrefixExpression& p,
1653 Precedence parentPrecedence) {
Brian Osman00185012021-02-04 16:07:11 -05001654 if (Precedence::kPrefix >= parentPrecedence) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001655 this->write("(");
1656 }
John Stilesd6449e92020-11-30 09:13:23 -05001657 this->write(OperatorName(p.getOperator()));
Brian Osman00185012021-02-04 16:07:11 -05001658 this->writeExpression(*p.operand(), Precedence::kPrefix);
1659 if (Precedence::kPrefix >= parentPrecedence) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001660 this->write(")");
1661 }
1662}
1663
1664void MetalCodeGenerator::writePostfixExpression(const PostfixExpression& p,
1665 Precedence parentPrecedence) {
Brian Osman00185012021-02-04 16:07:11 -05001666 if (Precedence::kPostfix >= parentPrecedence) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001667 this->write("(");
1668 }
Brian Osman00185012021-02-04 16:07:11 -05001669 this->writeExpression(*p.operand(), Precedence::kPostfix);
John Stilesd6449e92020-11-30 09:13:23 -05001670 this->write(OperatorName(p.getOperator()));
Brian Osman00185012021-02-04 16:07:11 -05001671 if (Precedence::kPostfix >= parentPrecedence) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001672 this->write(")");
1673 }
1674}
1675
1676void MetalCodeGenerator::writeBoolLiteral(const BoolLiteral& b) {
Ethan Nicholas59d660c2020-09-28 09:18:15 -04001677 this->write(b.value() ? "true" : "false");
Ethan Nicholascc305772017-10-13 16:17:45 -04001678}
1679
1680void MetalCodeGenerator::writeIntLiteral(const IntLiteral& i) {
John Stiles12739df2020-12-29 09:47:20 -05001681 const Type& type = i.type();
John Stiles54e7c052021-01-11 14:22:36 -05001682 if (type == *fContext.fTypes.fUInt) {
Ethan Nicholase96cdd12020-09-28 16:27:18 -04001683 this->write(to_string(i.value() & 0xffffffff) + "u");
John Stiles54e7c052021-01-11 14:22:36 -05001684 } else if (type == *fContext.fTypes.fUShort) {
John Stiles12739df2020-12-29 09:47:20 -05001685 this->write(to_string(i.value() & 0xffff) + "u");
Ethan Nicholascc305772017-10-13 16:17:45 -04001686 } else {
John Stiles12739df2020-12-29 09:47:20 -05001687 this->write(to_string(i.value()));
Ethan Nicholascc305772017-10-13 16:17:45 -04001688 }
1689}
1690
1691void MetalCodeGenerator::writeFloatLiteral(const FloatLiteral& f) {
Ethan Nicholasa3f22f12020-10-01 12:13:17 -04001692 this->write(to_string(f.value()));
Ethan Nicholascc305772017-10-13 16:17:45 -04001693}
1694
1695void MetalCodeGenerator::writeSetting(const Setting& s) {
John Stilesf57207b2021-02-02 17:50:34 -05001696 SK_ABORT("internal error; setting was not folded to a constant during compilation\n");
Ethan Nicholascc305772017-10-13 16:17:45 -04001697}
1698
John Stiles06b84ef2020-12-09 12:35:48 -05001699void MetalCodeGenerator::writeFunctionRequirementArgs(const FunctionDeclaration& f,
1700 const char*& separator) {
1701 Requirements requirements = this->requirements(f);
1702 if (requirements & kInputs_Requirement) {
1703 this->write(separator);
1704 this->write("_in");
1705 separator = ", ";
1706 }
1707 if (requirements & kOutputs_Requirement) {
1708 this->write(separator);
1709 this->write("_out");
1710 separator = ", ";
1711 }
1712 if (requirements & kUniforms_Requirement) {
1713 this->write(separator);
1714 this->write("_uniforms");
1715 separator = ", ";
1716 }
1717 if (requirements & kGlobals_Requirement) {
1718 this->write(separator);
John Stilesf7410bd2021-01-19 13:07:55 -05001719 this->write("_globals");
John Stiles06b84ef2020-12-09 12:35:48 -05001720 separator = ", ";
1721 }
1722 if (requirements & kFragCoord_Requirement) {
1723 this->write(separator);
1724 this->write("_fragCoord");
1725 separator = ", ";
1726 }
1727}
1728
1729void MetalCodeGenerator::writeFunctionRequirementParams(const FunctionDeclaration& f,
1730 const char*& separator) {
1731 Requirements requirements = this->requirements(f);
1732 if (requirements & kInputs_Requirement) {
1733 this->write(separator);
1734 this->write("Inputs _in");
1735 separator = ", ";
1736 }
1737 if (requirements & kOutputs_Requirement) {
1738 this->write(separator);
John Stilesf7410bd2021-01-19 13:07:55 -05001739 this->write("thread Outputs& _out");
John Stiles06b84ef2020-12-09 12:35:48 -05001740 separator = ", ";
1741 }
1742 if (requirements & kUniforms_Requirement) {
1743 this->write(separator);
1744 this->write("Uniforms _uniforms");
1745 separator = ", ";
1746 }
1747 if (requirements & kGlobals_Requirement) {
1748 this->write(separator);
John Stilesf7410bd2021-01-19 13:07:55 -05001749 this->write("thread Globals& _globals");
John Stiles06b84ef2020-12-09 12:35:48 -05001750 separator = ", ";
1751 }
1752 if (requirements & kFragCoord_Requirement) {
1753 this->write(separator);
1754 this->write("float4 _fragCoord");
1755 separator = ", ";
1756 }
1757}
1758
John Stilesda5cdf62021-01-28 11:47:29 -05001759int MetalCodeGenerator::getUniformBinding(const Modifiers& m) {
1760 return (m.fLayout.fBinding >= 0) ? m.fLayout.fBinding
John Stiles270cec22021-02-17 12:59:36 -05001761 : fProgram.fConfig->fSettings.fDefaultUniformBinding;
John Stilesda5cdf62021-01-28 11:47:29 -05001762}
1763
1764int MetalCodeGenerator::getUniformSet(const Modifiers& m) {
1765 return (m.fLayout.fSet >= 0) ? m.fLayout.fSet
John Stiles270cec22021-02-17 12:59:36 -05001766 : fProgram.fConfig->fSettings.fDefaultUniformSet;
John Stilesda5cdf62021-01-28 11:47:29 -05001767}
1768
John Stiles569249b2020-11-03 12:18:22 -05001769bool MetalCodeGenerator::writeFunctionDeclaration(const FunctionDeclaration& f) {
Brian Salomond8d85b92021-07-07 09:41:17 -04001770 fRTFlipName = fProgram.fInputs.fUseFlipRTUniform
1771 ? "_globals._anonInterface0->" SKSL_RTFLIP_NAME
1772 : "";
Ethan Nicholascc305772017-10-13 16:17:45 -04001773 const char* separator = "";
John Stilese8da4d22021-03-24 09:19:45 -04001774 if (f.isMain()) {
John Stiles270cec22021-02-17 12:59:36 -05001775 switch (fProgram.fConfig->fKind) {
John Stilesdbd4e6f2021-02-16 13:29:15 -05001776 case ProgramKind::kFragment:
Timothy Liangb8eeb802018-07-23 16:46:16 -04001777 this->write("fragment Outputs fragmentMain");
Ethan Nicholascc305772017-10-13 16:17:45 -04001778 break;
John Stilesdbd4e6f2021-02-16 13:29:15 -05001779 case ProgramKind::kVertex:
Timothy Liangb8eeb802018-07-23 16:46:16 -04001780 this->write("vertex Outputs vertexMain");
Ethan Nicholascc305772017-10-13 16:17:45 -04001781 break;
1782 default:
Ethan Nicholas39f6da42021-08-23 13:10:07 -04001783 fContext.fErrors->error(-1, "unsupported kind of program");
John Stiles569249b2020-11-03 12:18:22 -05001784 return false;
Ethan Nicholascc305772017-10-13 16:17:45 -04001785 }
1786 this->write("(Inputs _in [[stage_in]]");
1787 if (-1 != fUniformBuffer) {
1788 this->write(", constant Uniforms& _uniforms [[buffer(" +
1789 to_string(fUniformBuffer) + ")]]");
1790 }
Brian Osman133724c2020-10-28 14:14:39 -04001791 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04001792 if (e->is<GlobalVarDeclaration>()) {
1793 const GlobalVarDeclaration& decls = e->as<GlobalVarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001794 const VarDeclaration& var = decls.declaration()->as<VarDeclaration>();
1795 if (var.var().type().typeKind() == Type::TypeKind::kSampler) {
1796 if (var.var().modifiers().fLayout.fBinding < 0) {
Ethan Nicholas39f6da42021-08-23 13:10:07 -04001797 fContext.fErrors->error(decls.fOffset,
Ethan Nicholas3abc6c62021-08-13 11:20:09 -04001798 "Metal samplers must have 'layout(binding=...)'");
John Stiles569249b2020-11-03 12:18:22 -05001799 return false;
Timothy Liangee84fe12018-05-18 14:38:19 -04001800 }
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001801 if (var.var().type().dimensions() != SpvDim2D) {
John Stiles569249b2020-11-03 12:18:22 -05001802 // Not yet implemented--Skia currently only uses 2D textures.
Ethan Nicholas39f6da42021-08-23 13:10:07 -04001803 fContext.fErrors->error(decls.fOffset, "Unsupported texture dimensions");
John Stiles569249b2020-11-03 12:18:22 -05001804 return false;
Brian Osmanc0213602020-10-06 14:43:32 -04001805 }
1806 this->write(", texture2d<float> ");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001807 this->writeName(var.var().name());
Brian Osmanc0213602020-10-06 14:43:32 -04001808 this->write("[[texture(");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001809 this->write(to_string(var.var().modifiers().fLayout.fBinding));
Brian Osmanc0213602020-10-06 14:43:32 -04001810 this->write(")]]");
1811 this->write(", sampler ");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001812 this->writeName(var.var().name());
Brian Osmanc0213602020-10-06 14:43:32 -04001813 this->write(SAMPLER_SUFFIX);
1814 this->write("[[sampler(");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001815 this->write(to_string(var.var().modifiers().fLayout.fBinding));
Brian Osmanc0213602020-10-06 14:43:32 -04001816 this->write(")]]");
Timothy Liang6403b0e2018-05-17 10:40:04 -04001817 }
Brian Osman1179fcf2020-10-08 16:04:40 -04001818 } else if (e->is<InterfaceBlock>()) {
1819 const InterfaceBlock& intf = e->as<InterfaceBlock>();
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001820 if (intf.typeName() == "sk_PerVertex") {
Timothy Lianga06f2152018-05-24 15:33:31 -04001821 continue;
1822 }
1823 this->write(", constant ");
John Stilesb4418502021-02-04 10:57:08 -05001824 this->writeType(intf.variable().type());
Timothy Lianga06f2152018-05-24 15:33:31 -04001825 this->write("& " );
1826 this->write(fInterfaceBlockNameMap[&intf]);
1827 this->write(" [[buffer(");
John Stilesda5cdf62021-01-28 11:47:29 -05001828 this->write(to_string(this->getUniformBinding(intf.variable().modifiers())));
Timothy Lianga06f2152018-05-24 15:33:31 -04001829 this->write(")]]");
Timothy Liang6403b0e2018-05-17 10:40:04 -04001830 }
1831 }
John Stiles270cec22021-02-17 12:59:36 -05001832 if (fProgram.fConfig->fKind == ProgramKind::kFragment) {
Brian Salomond8d85b92021-07-07 09:41:17 -04001833 if (fProgram.fInputs.fUseFlipRTUniform && fInterfaceBlockNameMap.empty()) {
Timothy Liang5422f9a2018-08-10 10:57:55 -04001834 this->write(", constant sksl_synthetic_uniforms& _anonInterface0 [[buffer(1)]]");
Brian Salomond8d85b92021-07-07 09:41:17 -04001835 fRTFlipName = "_anonInterface0." SKSL_RTFLIP_NAME;
Timothy Liang5422f9a2018-08-10 10:57:55 -04001836 }
Timothy Liang7b8875d2018-08-10 09:42:31 -04001837 this->write(", bool _frontFacing [[front_facing]]");
Timothy Liang7d637782018-06-05 09:58:07 -04001838 this->write(", float4 _fragCoord [[position]]");
John Stiles270cec22021-02-17 12:59:36 -05001839 } else if (fProgram.fConfig->fKind == ProgramKind::kVertex) {
Timothy Liangdc89f192018-06-13 09:20:31 -04001840 this->write(", uint sk_VertexID [[vertex_id]], uint sk_InstanceID [[instance_id]]");
Timothy Liang7d637782018-06-05 09:58:07 -04001841 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001842 separator = ", ";
1843 } else {
John Stilesb4418502021-02-04 10:57:08 -05001844 this->writeType(f.returnType());
Timothy Liang651286f2018-06-07 09:55:33 -04001845 this->write(" ");
John Stilese1068342021-03-22 11:57:41 -04001846 this->writeName(f.mangledName());
Timothy Liang651286f2018-06-07 09:55:33 -04001847 this->write("(");
John Stiles06b84ef2020-12-09 12:35:48 -05001848 this->writeFunctionRequirementParams(f, separator);
Ethan Nicholascc305772017-10-13 16:17:45 -04001849 }
John Stiles569249b2020-11-03 12:18:22 -05001850 for (const auto& param : f.parameters()) {
Brian Osman716aeb92021-04-21 13:20:00 -04001851 if (f.isMain() && param->modifiers().fLayout.fBuiltin != -1) {
1852 continue;
1853 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001854 this->write(separator);
1855 separator = ", ";
Brian Osman58134e12021-05-13 14:51:07 -04001856 this->writeModifiers(param->modifiers());
Ethan Nicholas30d30222020-09-11 12:27:26 -04001857 const Type* type = &param->type();
John Stilesb4418502021-02-04 10:57:08 -05001858 this->writeType(*type);
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001859 if (param->modifiers().fFlags & Modifiers::kOut_Flag) {
John Stilesf2bd5012020-12-04 11:58:26 -05001860 this->write("&");
Ethan Nicholascc305772017-10-13 16:17:45 -04001861 }
Timothy Liang651286f2018-06-07 09:55:33 -04001862 this->write(" ");
Ethan Nicholase2c49992020-10-05 11:49:11 -04001863 this->writeName(param->name());
Ethan Nicholascc305772017-10-13 16:17:45 -04001864 }
John Stiles569249b2020-11-03 12:18:22 -05001865 this->write(")");
1866 return true;
1867}
Ethan Nicholascc305772017-10-13 16:17:45 -04001868
John Stiles569249b2020-11-03 12:18:22 -05001869void MetalCodeGenerator::writeFunctionPrototype(const FunctionPrototype& f) {
1870 this->writeFunctionDeclaration(f.declaration());
1871 this->writeLine(";");
1872}
1873
John Stiles986c7fb2020-12-01 14:44:56 -05001874static bool is_block_ending_with_return(const Statement* stmt) {
1875 // This function detects (potentially nested) blocks that end in a return statement.
1876 if (!stmt->is<Block>()) {
1877 return false;
1878 }
1879 const StatementArray& block = stmt->as<Block>().children();
1880 for (int index = block.count(); index--; ) {
John Stiles628777c2021-08-04 22:07:41 -04001881 stmt = block[index].get();
1882 if (stmt->is<ReturnStatement>()) {
John Stiles986c7fb2020-12-01 14:44:56 -05001883 return true;
1884 }
John Stiles628777c2021-08-04 22:07:41 -04001885 if (stmt->is<Block>()) {
1886 return is_block_ending_with_return(stmt);
John Stiles986c7fb2020-12-01 14:44:56 -05001887 }
John Stiles628777c2021-08-04 22:07:41 -04001888 if (!stmt->is<Nop>()) {
John Stiles986c7fb2020-12-01 14:44:56 -05001889 break;
1890 }
1891 }
1892 return false;
1893}
1894
John Stiles569249b2020-11-03 12:18:22 -05001895void MetalCodeGenerator::writeFunction(const FunctionDefinition& f) {
John Stiles270cec22021-02-17 12:59:36 -05001896 SkASSERT(!fProgram.fConfig->fSettings.fFragColorIsInOut);
Brian Salomondc092132018-04-04 10:14:16 -04001897
John Stiles569249b2020-11-03 12:18:22 -05001898 if (!this->writeFunctionDeclaration(f.declaration())) {
1899 return;
1900 }
1901
John Stiles986c7fb2020-12-01 14:44:56 -05001902 fCurrentFunction = &f.declaration();
1903 SkScopeExit clearCurrentFunction([&] { fCurrentFunction = nullptr; });
1904
John Stiles569249b2020-11-03 12:18:22 -05001905 this->writeLine(" {");
1906
John Stilese8da4d22021-03-24 09:19:45 -04001907 if (f.declaration().isMain()) {
John Stilescdcdb042020-07-06 09:03:51 -04001908 this->writeGlobalInit();
John Stilesf7410bd2021-01-19 13:07:55 -05001909 this->writeLine(" Outputs _out;");
John Stiles37279172021-01-21 22:24:28 -05001910 this->writeLine(" (void)_out;");
Ethan Nicholascc305772017-10-13 16:17:45 -04001911 }
John Stilesc67b3622020-05-28 17:53:13 -04001912
John Stiles95680232021-04-22 15:05:20 -04001913 fFunctionHeader.clear();
Ethan Nicholascc305772017-10-13 16:17:45 -04001914 StringStream buffer;
John Stiles44532372020-12-07 12:33:55 -05001915 {
1916 AutoOutputStream outputToBuffer(this, &buffer);
1917 fIndentation++;
1918 for (const std::unique_ptr<Statement>& stmt : f.body()->as<Block>().children()) {
1919 if (!stmt->isEmpty()) {
1920 this->writeStatement(*stmt);
John Stilese8b5a732021-03-12 13:25:52 -05001921 this->finishLine();
John Stiles44532372020-12-07 12:33:55 -05001922 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001923 }
John Stilese8da4d22021-03-24 09:19:45 -04001924 if (f.declaration().isMain()) {
John Stiles44532372020-12-07 12:33:55 -05001925 // If the main function doesn't end with a return, we need to synthesize one here.
1926 if (!is_block_ending_with_return(f.body().get())) {
1927 this->writeReturnStatementFromMain();
John Stilese8b5a732021-03-12 13:25:52 -05001928 this->finishLine();
John Stiles44532372020-12-07 12:33:55 -05001929 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001930 }
John Stiles44532372020-12-07 12:33:55 -05001931 fIndentation--;
1932 this->writeLine("}");
Ethan Nicholascc305772017-10-13 16:17:45 -04001933 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001934 this->write(fFunctionHeader);
1935 this->write(buffer.str());
1936}
1937
Brian Osman58134e12021-05-13 14:51:07 -04001938void MetalCodeGenerator::writeModifiers(const Modifiers& modifiers) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001939 if (modifiers.fFlags & Modifiers::kOut_Flag) {
1940 this->write("thread ");
1941 }
1942 if (modifiers.fFlags & Modifiers::kConst_Flag) {
John Stiles0bd55782021-02-09 18:29:40 -05001943 this->write("const ");
Ethan Nicholascc305772017-10-13 16:17:45 -04001944 }
1945}
1946
1947void MetalCodeGenerator::writeInterfaceBlock(const InterfaceBlock& intf) {
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001948 if ("sk_PerVertex" == intf.typeName()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001949 return;
1950 }
Brian Osman58134e12021-05-13 14:51:07 -04001951 this->writeModifiers(intf.variable().modifiers());
Timothy Liangdc89f192018-06-13 09:20:31 -04001952 this->write("struct ");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001953 this->writeLine(intf.typeName() + " {");
1954 const Type* structType = &intf.variable().type();
John Stilesbb43b7e2020-12-03 17:36:32 -05001955 if (structType->isArray()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001956 structType = &structType->componentType();
1957 }
Timothy Liangdc89f192018-06-13 09:20:31 -04001958 fIndentation++;
John Stiles3dba3ee2020-12-02 23:35:49 -05001959 this->writeFields(structType->fields(), structType->fOffset, &intf);
Brian Salomond8d85b92021-07-07 09:41:17 -04001960 if (fProgram.fInputs.fUseFlipRTUniform) {
1961 this->writeLine("float2 " SKSL_RTFLIP_NAME ";");
Ethan Nicholascc305772017-10-13 16:17:45 -04001962 }
1963 fIndentation--;
1964 this->write("}");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001965 if (intf.instanceName().size()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001966 this->write(" ");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001967 this->write(intf.instanceName());
John Stilesd39aec02020-12-03 10:42:26 -05001968 if (intf.arraySize() > 0) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001969 this->write("[");
John Stilesd39aec02020-12-03 10:42:26 -05001970 this->write(to_string(intf.arraySize()));
Ethan Nicholascc305772017-10-13 16:17:45 -04001971 this->write("]");
1972 }
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001973 fInterfaceBlockNameMap[&intf] = intf.instanceName();
Timothy Lianga06f2152018-05-24 15:33:31 -04001974 } else {
Ethan Nicholas3533ff12021-08-02 12:53:29 -04001975 fInterfaceBlockNameMap[&intf] = *fProgram.fSymbols->takeOwnershipOfString("_anonInterface" +
1976 to_string(fAnonInterfaceCount++));
Ethan Nicholascc305772017-10-13 16:17:45 -04001977 }
1978 this->writeLine(";");
1979}
1980
Timothy Liangdc89f192018-06-13 09:20:31 -04001981void MetalCodeGenerator::writeFields(const std::vector<Type::Field>& fields, int parentOffset,
1982 const InterfaceBlock* parentIntf) {
Timothy Liang609fbe32018-08-10 16:40:49 -04001983 MemoryLayout memoryLayout(MemoryLayout::kMetal_Standard);
Timothy Liangdc89f192018-06-13 09:20:31 -04001984 int currentOffset = 0;
John Stiles39346472021-04-29 14:39:35 -04001985 for (const Type::Field& field : fields) {
Timothy Liangdc89f192018-06-13 09:20:31 -04001986 int fieldOffset = field.fModifiers.fLayout.fOffset;
1987 const Type* fieldType = field.fType;
John Stiles21f5f452020-11-30 09:57:59 -05001988 if (!MemoryLayout::LayoutIsSupported(*fieldType)) {
Ethan Nicholas39f6da42021-08-23 13:10:07 -04001989 fContext.fErrors->error(parentOffset, "type '" + fieldType->name() +
Ethan Nicholas3abc6c62021-08-13 11:20:09 -04001990 "' is not permitted here");
John Stiles0023c0c2020-11-16 13:32:18 -05001991 return;
1992 }
Timothy Liangdc89f192018-06-13 09:20:31 -04001993 if (fieldOffset != -1) {
1994 if (currentOffset > fieldOffset) {
Ethan Nicholas39f6da42021-08-23 13:10:07 -04001995 fContext.fErrors->error(parentOffset,
Ethan Nicholas3abc6c62021-08-13 11:20:09 -04001996 "offset of field '" + field.fName + "' must be at least " +
1997 to_string((int) currentOffset));
Brian Osman8609a242020-09-08 14:01:49 -04001998 return;
Timothy Liangdc89f192018-06-13 09:20:31 -04001999 } else if (currentOffset < fieldOffset) {
2000 this->write("char pad");
2001 this->write(to_string(fPaddingCount++));
2002 this->write("[");
2003 this->write(to_string(fieldOffset - currentOffset));
2004 this->writeLine("];");
2005 currentOffset = fieldOffset;
2006 }
2007 int alignment = memoryLayout.alignment(*fieldType);
2008 if (fieldOffset % alignment) {
Ethan Nicholas39f6da42021-08-23 13:10:07 -04002009 fContext.fErrors->error(parentOffset,
Ethan Nicholas3abc6c62021-08-13 11:20:09 -04002010 "offset of field '" + field.fName + "' must be a multiple of " +
2011 to_string((int) alignment));
Brian Osman8609a242020-09-08 14:01:49 -04002012 return;
Timothy Liangdc89f192018-06-13 09:20:31 -04002013 }
2014 }
Brian Osman8609a242020-09-08 14:01:49 -04002015 size_t fieldSize = memoryLayout.size(*fieldType);
2016 if (fieldSize > static_cast<size_t>(std::numeric_limits<int>::max() - currentOffset)) {
Ethan Nicholas39f6da42021-08-23 13:10:07 -04002017 fContext.fErrors->error(parentOffset, "field offset overflow");
Brian Osman8609a242020-09-08 14:01:49 -04002018 return;
2019 }
2020 currentOffset += fieldSize;
Brian Osman58134e12021-05-13 14:51:07 -04002021 this->writeModifiers(field.fModifiers);
John Stilesb4418502021-02-04 10:57:08 -05002022 this->writeType(*fieldType);
Timothy Liangdc89f192018-06-13 09:20:31 -04002023 this->write(" ");
2024 this->writeName(field.fName);
Timothy Liangdc89f192018-06-13 09:20:31 -04002025 this->writeLine(";");
2026 if (parentIntf) {
2027 fInterfaceBlockMap[&field] = parentIntf;
2028 }
2029 }
2030}
2031
Ethan Nicholascc305772017-10-13 16:17:45 -04002032void MetalCodeGenerator::writeVarInitializer(const Variable& var, const Expression& value) {
Brian Osman00185012021-02-04 16:07:11 -05002033 this->writeExpression(value, Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04002034}
2035
Ethan Nicholas962dec42021-06-10 13:06:39 -04002036void MetalCodeGenerator::writeName(skstd::string_view name) {
Timothy Liang651286f2018-06-07 09:55:33 -04002037 if (fReservedWords.find(name) != fReservedWords.end()) {
2038 this->write("_"); // adding underscore before name to avoid conflict with reserved words
2039 }
2040 this->write(name);
2041}
2042
Brian Osman58134e12021-05-13 14:51:07 -04002043void MetalCodeGenerator::writeVarDeclaration(const VarDeclaration& varDecl) {
2044 this->writeModifiers(varDecl.var().modifiers());
John Stilesb4418502021-02-04 10:57:08 -05002045 this->writeType(varDecl.var().type());
Brian Osmanc0213602020-10-06 14:43:32 -04002046 this->write(" ");
John Stilesb4418502021-02-04 10:57:08 -05002047 this->writeName(varDecl.var().name());
2048 if (varDecl.value()) {
Brian Osmanc0213602020-10-06 14:43:32 -04002049 this->write(" = ");
John Stilesb4418502021-02-04 10:57:08 -05002050 this->writeVarInitializer(varDecl.var(), *varDecl.value());
Brian Osmanc0213602020-10-06 14:43:32 -04002051 }
2052 this->write(";");
Ethan Nicholascc305772017-10-13 16:17:45 -04002053}
2054
2055void MetalCodeGenerator::writeStatement(const Statement& s) {
Ethan Nicholase6592142020-09-08 10:22:09 -04002056 switch (s.kind()) {
2057 case Statement::Kind::kBlock:
John Stiles26f98502020-08-18 09:30:51 -04002058 this->writeBlock(s.as<Block>());
Ethan Nicholascc305772017-10-13 16:17:45 -04002059 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04002060 case Statement::Kind::kExpression:
Brian Osman00185012021-02-04 16:07:11 -05002061 this->writeExpression(*s.as<ExpressionStatement>().expression(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04002062 this->write(";");
2063 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04002064 case Statement::Kind::kReturn:
John Stiles26f98502020-08-18 09:30:51 -04002065 this->writeReturnStatement(s.as<ReturnStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04002066 break;
Brian Osmanc0213602020-10-06 14:43:32 -04002067 case Statement::Kind::kVarDeclaration:
Brian Osman58134e12021-05-13 14:51:07 -04002068 this->writeVarDeclaration(s.as<VarDeclaration>());
Ethan Nicholascc305772017-10-13 16:17:45 -04002069 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04002070 case Statement::Kind::kIf:
John Stiles26f98502020-08-18 09:30:51 -04002071 this->writeIfStatement(s.as<IfStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04002072 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04002073 case Statement::Kind::kFor:
John Stiles26f98502020-08-18 09:30:51 -04002074 this->writeForStatement(s.as<ForStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04002075 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04002076 case Statement::Kind::kDo:
John Stiles26f98502020-08-18 09:30:51 -04002077 this->writeDoStatement(s.as<DoStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04002078 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04002079 case Statement::Kind::kSwitch:
John Stiles26f98502020-08-18 09:30:51 -04002080 this->writeSwitchStatement(s.as<SwitchStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04002081 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04002082 case Statement::Kind::kBreak:
Ethan Nicholascc305772017-10-13 16:17:45 -04002083 this->write("break;");
2084 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04002085 case Statement::Kind::kContinue:
Ethan Nicholascc305772017-10-13 16:17:45 -04002086 this->write("continue;");
2087 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04002088 case Statement::Kind::kDiscard:
Timothy Lianga06f2152018-05-24 15:33:31 -04002089 this->write("discard_fragment();");
Ethan Nicholascc305772017-10-13 16:17:45 -04002090 break;
John Stiles98c1f822020-09-09 14:18:53 -04002091 case Statement::Kind::kInlineMarker:
Ethan Nicholase6592142020-09-08 10:22:09 -04002092 case Statement::Kind::kNop:
Ethan Nicholascc305772017-10-13 16:17:45 -04002093 this->write(";");
2094 break;
2095 default:
John Stileseada7bc2021-02-02 16:29:32 -05002096 SkDEBUGFAILF("unsupported statement: %s", s.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -05002097 break;
Ethan Nicholascc305772017-10-13 16:17:45 -04002098 }
2099}
2100
Ethan Nicholascc305772017-10-13 16:17:45 -04002101void MetalCodeGenerator::writeBlock(const Block& b) {
John Stiles3744bd62021-01-26 13:49:43 -05002102 // Write scope markers if this block is a scope, or if the block is empty (since we need to emit
2103 // something here to make the code valid).
2104 bool isScope = b.isScope() || b.isEmpty();
Ethan Nicholas7bd60432020-09-25 14:31:59 -04002105 if (isScope) {
Ethan Nicholas70728ef2020-05-28 07:09:00 -04002106 this->writeLine("{");
2107 fIndentation++;
2108 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -04002109 for (const std::unique_ptr<Statement>& stmt : b.children()) {
2110 if (!stmt->isEmpty()) {
2111 this->writeStatement(*stmt);
John Stilese8b5a732021-03-12 13:25:52 -05002112 this->finishLine();
Ethan Nicholas7bd60432020-09-25 14:31:59 -04002113 }
2114 }
2115 if (isScope) {
Ethan Nicholas70728ef2020-05-28 07:09:00 -04002116 fIndentation--;
2117 this->write("}");
2118 }
Ethan Nicholascc305772017-10-13 16:17:45 -04002119}
2120
2121void MetalCodeGenerator::writeIfStatement(const IfStatement& stmt) {
2122 this->write("if (");
Brian Osman00185012021-02-04 16:07:11 -05002123 this->writeExpression(*stmt.test(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04002124 this->write(") ");
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04002125 this->writeStatement(*stmt.ifTrue());
2126 if (stmt.ifFalse()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002127 this->write(" else ");
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04002128 this->writeStatement(*stmt.ifFalse());
Ethan Nicholascc305772017-10-13 16:17:45 -04002129 }
2130}
2131
2132void MetalCodeGenerator::writeForStatement(const ForStatement& f) {
Brian Osmand6f23382020-12-15 17:08:59 -05002133 // Emit loops of the form 'for(;test;)' as 'while(test)', which is probably how they started
2134 if (!f.initializer() && f.test() && !f.next()) {
2135 this->write("while (");
Brian Osman00185012021-02-04 16:07:11 -05002136 this->writeExpression(*f.test(), Precedence::kTopLevel);
Brian Osmand6f23382020-12-15 17:08:59 -05002137 this->write(") ");
2138 this->writeStatement(*f.statement());
2139 return;
2140 }
2141
John Stiles1a15e572021-04-19 14:57:15 -04002142 this->write("for (");
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04002143 if (f.initializer() && !f.initializer()->isEmpty()) {
John Stiles1a15e572021-04-19 14:57:15 -04002144 this->writeStatement(*f.initializer());
Ethan Nicholascc305772017-10-13 16:17:45 -04002145 } else {
John Stiles1a15e572021-04-19 14:57:15 -04002146 this->write("; ");
Ethan Nicholascc305772017-10-13 16:17:45 -04002147 }
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04002148 if (f.test()) {
Brian Osman00185012021-02-04 16:07:11 -05002149 this->writeExpression(*f.test(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04002150 }
2151 this->write("; ");
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04002152 if (f.next()) {
Brian Osman00185012021-02-04 16:07:11 -05002153 this->writeExpression(*f.next(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04002154 }
2155 this->write(") ");
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04002156 this->writeStatement(*f.statement());
Ethan Nicholascc305772017-10-13 16:17:45 -04002157}
2158
Ethan Nicholascc305772017-10-13 16:17:45 -04002159void MetalCodeGenerator::writeDoStatement(const DoStatement& d) {
2160 this->write("do ");
Ethan Nicholas1fd61162020-09-28 13:14:19 -04002161 this->writeStatement(*d.statement());
Ethan Nicholascc305772017-10-13 16:17:45 -04002162 this->write(" while (");
Brian Osman00185012021-02-04 16:07:11 -05002163 this->writeExpression(*d.test(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04002164 this->write(");");
2165}
2166
2167void MetalCodeGenerator::writeSwitchStatement(const SwitchStatement& s) {
2168 this->write("switch (");
Brian Osman00185012021-02-04 16:07:11 -05002169 this->writeExpression(*s.value(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04002170 this->writeLine(") {");
2171 fIndentation++;
John Stilesb23a64b2021-03-11 08:27:59 -05002172 for (const std::unique_ptr<Statement>& stmt : s.cases()) {
2173 const SwitchCase& c = stmt->as<SwitchCase>();
2174 if (c.value()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002175 this->write("case ");
John Stilesb23a64b2021-03-11 08:27:59 -05002176 this->writeExpression(*c.value(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04002177 this->writeLine(":");
2178 } else {
2179 this->writeLine("default:");
2180 }
John Stilesb23a64b2021-03-11 08:27:59 -05002181 if (!c.statement()->isEmpty()) {
John Stilesc3ce43b2021-03-09 15:37:01 -05002182 fIndentation++;
John Stilesb23a64b2021-03-11 08:27:59 -05002183 this->writeStatement(*c.statement());
John Stilese8b5a732021-03-12 13:25:52 -05002184 this->finishLine();
John Stilesc3ce43b2021-03-09 15:37:01 -05002185 fIndentation--;
Ethan Nicholascc305772017-10-13 16:17:45 -04002186 }
Ethan Nicholascc305772017-10-13 16:17:45 -04002187 }
2188 fIndentation--;
2189 this->write("}");
2190}
2191
John Stiles986c7fb2020-12-01 14:44:56 -05002192void MetalCodeGenerator::writeReturnStatementFromMain() {
2193 // main functions in Metal return a magic _out parameter that doesn't exist in SkSL.
John Stiles270cec22021-02-17 12:59:36 -05002194 switch (fProgram.fConfig->fKind) {
Brian Salomon3e2fe2b2021-06-02 09:16:30 -04002195 case ProgramKind::kVertex:
John Stilesdbd4e6f2021-02-16 13:29:15 -05002196 case ProgramKind::kFragment:
John Stilesf7410bd2021-01-19 13:07:55 -05002197 this->write("return _out;");
John Stiles986c7fb2020-12-01 14:44:56 -05002198 break;
John Stiles986c7fb2020-12-01 14:44:56 -05002199 default:
2200 SkDEBUGFAIL("unsupported kind of program");
2201 }
2202}
2203
Ethan Nicholascc305772017-10-13 16:17:45 -04002204void MetalCodeGenerator::writeReturnStatement(const ReturnStatement& r) {
John Stilese8da4d22021-03-24 09:19:45 -04002205 if (fCurrentFunction && fCurrentFunction->isMain()) {
John Stiles986c7fb2020-12-01 14:44:56 -05002206 if (r.expression()) {
John Stiles97d18172021-01-22 16:47:42 -05002207 if (r.expression()->type() == *fContext.fTypes.fHalf4) {
2208 this->write("_out.sk_FragColor = ");
Brian Osman00185012021-02-04 16:07:11 -05002209 this->writeExpression(*r.expression(), Precedence::kTopLevel);
John Stiles97d18172021-01-22 16:47:42 -05002210 this->writeLine(";");
2211 } else {
Ethan Nicholas39f6da42021-08-23 13:10:07 -04002212 fContext.fErrors->error(r.fOffset,
Ethan Nicholas3abc6c62021-08-13 11:20:09 -04002213 "Metal does not support returning '" +
2214 r.expression()->type().description() + "' from main()");
John Stiles97d18172021-01-22 16:47:42 -05002215 }
John Stiles986c7fb2020-12-01 14:44:56 -05002216 }
2217 this->writeReturnStatementFromMain();
2218 return;
2219 }
2220
Ethan Nicholascc305772017-10-13 16:17:45 -04002221 this->write("return");
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04002222 if (r.expression()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002223 this->write(" ");
Brian Osman00185012021-02-04 16:07:11 -05002224 this->writeExpression(*r.expression(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04002225 }
2226 this->write(";");
2227}
2228
Michael Ludwigbf58add2021-03-16 10:40:11 -04002229void MetalCodeGenerator::writeHeader() {
2230 this->write("#include <metal_stdlib>\n");
2231 this->write("#include <simd/simd.h>\n");
2232 this->write("using namespace metal;\n");
2233}
2234
Ethan Nicholascc305772017-10-13 16:17:45 -04002235void MetalCodeGenerator::writeUniformStruct() {
Brian Osman133724c2020-10-28 14:14:39 -04002236 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04002237 if (e->is<GlobalVarDeclaration>()) {
2238 const GlobalVarDeclaration& decls = e->as<GlobalVarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04002239 const Variable& var = decls.declaration()->as<VarDeclaration>().var();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002240 if (var.modifiers().fFlags & Modifiers::kUniform_Flag &&
Brian Osmanc0213602020-10-06 14:43:32 -04002241 var.type().typeKind() != Type::TypeKind::kSampler) {
John Stilesda5cdf62021-01-28 11:47:29 -05002242 int uniformSet = this->getUniformSet(var.modifiers());
John Stilesd8fc95d2021-01-26 16:22:53 -05002243 // Make sure that the program's uniform-set value is consistent throughout.
Ethan Nicholascc305772017-10-13 16:17:45 -04002244 if (-1 == fUniformBuffer) {
2245 this->write("struct Uniforms {\n");
John Stilesd8fc95d2021-01-26 16:22:53 -05002246 fUniformBuffer = uniformSet;
2247 } else if (uniformSet != fUniformBuffer) {
Ethan Nicholas39f6da42021-08-23 13:10:07 -04002248 fContext.fErrors->error(decls.fOffset,
Ethan Nicholas3abc6c62021-08-13 11:20:09 -04002249 "Metal backend requires all uniforms to have the same "
2250 "'layout(set=...)'");
Ethan Nicholascc305772017-10-13 16:17:45 -04002251 }
2252 this->write(" ");
John Stilesb4418502021-02-04 10:57:08 -05002253 this->writeType(var.type());
Ethan Nicholascc305772017-10-13 16:17:45 -04002254 this->write(" ");
Brian Osmanc0213602020-10-06 14:43:32 -04002255 this->writeName(var.name());
Ethan Nicholascc305772017-10-13 16:17:45 -04002256 this->write(";\n");
2257 }
2258 }
2259 }
2260 if (-1 != fUniformBuffer) {
2261 this->write("};\n");
2262 }
2263}
2264
2265void MetalCodeGenerator::writeInputStruct() {
2266 this->write("struct Inputs {\n");
Brian Osman133724c2020-10-28 14:14:39 -04002267 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04002268 if (e->is<GlobalVarDeclaration>()) {
2269 const GlobalVarDeclaration& decls = e->as<GlobalVarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04002270 const Variable& var = decls.declaration()->as<VarDeclaration>().var();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002271 if (var.modifiers().fFlags & Modifiers::kIn_Flag &&
2272 -1 == var.modifiers().fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002273 this->write(" ");
John Stilesb4418502021-02-04 10:57:08 -05002274 this->writeType(var.type());
Ethan Nicholascc305772017-10-13 16:17:45 -04002275 this->write(" ");
Brian Osmanc0213602020-10-06 14:43:32 -04002276 this->writeName(var.name());
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002277 if (-1 != var.modifiers().fLayout.fLocation) {
John Stiles270cec22021-02-17 12:59:36 -05002278 if (fProgram.fConfig->fKind == ProgramKind::kVertex) {
Brian Osmanc0213602020-10-06 14:43:32 -04002279 this->write(" [[attribute(" +
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002280 to_string(var.modifiers().fLayout.fLocation) + ")]]");
John Stiles270cec22021-02-17 12:59:36 -05002281 } else if (fProgram.fConfig->fKind == ProgramKind::kFragment) {
Brian Osmanc0213602020-10-06 14:43:32 -04002282 this->write(" [[user(locn" +
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002283 to_string(var.modifiers().fLayout.fLocation) + ")]]");
Ethan Nicholascc305772017-10-13 16:17:45 -04002284 }
2285 }
2286 this->write(";\n");
2287 }
2288 }
2289 }
2290 this->write("};\n");
2291}
2292
2293void MetalCodeGenerator::writeOutputStruct() {
2294 this->write("struct Outputs {\n");
John Stiles270cec22021-02-17 12:59:36 -05002295 if (fProgram.fConfig->fKind == ProgramKind::kVertex) {
Timothy Liangb8eeb802018-07-23 16:46:16 -04002296 this->write(" float4 sk_Position [[position]];\n");
John Stiles270cec22021-02-17 12:59:36 -05002297 } else if (fProgram.fConfig->fKind == ProgramKind::kFragment) {
Timothy Liangde0be802018-08-10 13:48:08 -04002298 this->write(" float4 sk_FragColor [[color(0)]];\n");
Timothy Liang7d637782018-06-05 09:58:07 -04002299 }
Brian Osman133724c2020-10-28 14:14:39 -04002300 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04002301 if (e->is<GlobalVarDeclaration>()) {
2302 const GlobalVarDeclaration& decls = e->as<GlobalVarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04002303 const Variable& var = decls.declaration()->as<VarDeclaration>().var();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002304 if (var.modifiers().fFlags & Modifiers::kOut_Flag &&
2305 -1 == var.modifiers().fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002306 this->write(" ");
John Stilesb4418502021-02-04 10:57:08 -05002307 this->writeType(var.type());
Ethan Nicholascc305772017-10-13 16:17:45 -04002308 this->write(" ");
Brian Osmanc0213602020-10-06 14:43:32 -04002309 this->writeName(var.name());
John Stiles842b3592020-12-01 10:36:37 -05002310
2311 int location = var.modifiers().fLayout.fLocation;
2312 if (location < 0) {
Ethan Nicholas39f6da42021-08-23 13:10:07 -04002313 fContext.fErrors->error(var.fOffset,
Ethan Nicholas3abc6c62021-08-13 11:20:09 -04002314 "Metal out variables must have 'layout(location=...)'");
John Stiles270cec22021-02-17 12:59:36 -05002315 } else if (fProgram.fConfig->fKind == ProgramKind::kVertex) {
John Stiles842b3592020-12-01 10:36:37 -05002316 this->write(" [[user(locn" + to_string(location) + ")]]");
John Stiles270cec22021-02-17 12:59:36 -05002317 } else if (fProgram.fConfig->fKind == ProgramKind::kFragment) {
John Stiles842b3592020-12-01 10:36:37 -05002318 this->write(" [[color(" + to_string(location) + ")");
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002319 int colorIndex = var.modifiers().fLayout.fIndex;
Brian Osmanc0213602020-10-06 14:43:32 -04002320 if (colorIndex) {
2321 this->write(", index(" + to_string(colorIndex) + ")");
Timothy Liang7d637782018-06-05 09:58:07 -04002322 }
Brian Osmanc0213602020-10-06 14:43:32 -04002323 this->write("]]");
Ethan Nicholascc305772017-10-13 16:17:45 -04002324 }
2325 this->write(";\n");
2326 }
2327 }
Timothy Liang7d637782018-06-05 09:58:07 -04002328 }
John Stiles270cec22021-02-17 12:59:36 -05002329 if (fProgram.fConfig->fKind == ProgramKind::kVertex) {
Jim Van Verth3913d3e2020-08-31 15:16:57 -04002330 this->write(" float sk_PointSize [[point_size]];\n");
Timothy Liang7d637782018-06-05 09:58:07 -04002331 }
2332 this->write("};\n");
2333}
2334
2335void MetalCodeGenerator::writeInterfaceBlocks() {
2336 bool wroteInterfaceBlock = false;
Brian Osman133724c2020-10-28 14:14:39 -04002337 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04002338 if (e->is<InterfaceBlock>()) {
2339 this->writeInterfaceBlock(e->as<InterfaceBlock>());
Timothy Liang7d637782018-06-05 09:58:07 -04002340 wroteInterfaceBlock = true;
2341 }
2342 }
Brian Salomond8d85b92021-07-07 09:41:17 -04002343 if (!wroteInterfaceBlock && fProgram.fInputs.fUseFlipRTUniform) {
Timothy Liang7d637782018-06-05 09:58:07 -04002344 this->writeLine("struct sksl_synthetic_uniforms {");
Brian Salomond8d85b92021-07-07 09:41:17 -04002345 this->writeLine(" float2 " SKSL_RTFLIP_NAME ";");
Timothy Liang7d637782018-06-05 09:58:07 -04002346 this->writeLine("};");
2347 }
Ethan Nicholascc305772017-10-13 16:17:45 -04002348}
2349
John Stilesdc75a972020-11-25 16:24:55 -05002350void MetalCodeGenerator::writeStructDefinitions() {
2351 for (const ProgramElement* e : fProgram.elements()) {
2352 if (e->is<StructDefinition>()) {
Brian Osman02bc5222021-01-28 11:00:20 -05002353 this->writeStructDefinition(e->as<StructDefinition>());
John Stilesdc75a972020-11-25 16:24:55 -05002354 }
2355 }
2356}
2357
John Stilescdcdb042020-07-06 09:03:51 -04002358void MetalCodeGenerator::visitGlobalStruct(GlobalStructVisitor* visitor) {
2359 // Visit the interface blocks.
2360 for (const auto& [interfaceType, interfaceName] : fInterfaceBlockNameMap) {
John Stilesfdb8dbe2020-12-04 11:00:03 -05002361 visitor->visitInterfaceBlock(*interfaceType, interfaceName);
John Stilescdcdb042020-07-06 09:03:51 -04002362 }
Brian Osman133724c2020-10-28 14:14:39 -04002363 for (const ProgramElement* element : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04002364 if (!element->is<GlobalVarDeclaration>()) {
John Stilescdcdb042020-07-06 09:03:51 -04002365 continue;
Timothy Liang7d637782018-06-05 09:58:07 -04002366 }
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04002367 const GlobalVarDeclaration& global = element->as<GlobalVarDeclaration>();
2368 const VarDeclaration& decl = global.declaration()->as<VarDeclaration>();
2369 const Variable& var = decl.var();
Brian Osman58134e12021-05-13 14:51:07 -04002370 if (var.type().typeKind() == Type::TypeKind::kSampler) {
2371 // Samplers are represented as a "texture/sampler" duo in the global struct.
2372 visitor->visitTexture(var.type(), var.name());
Ethan Nicholasd2e09602021-06-10 11:21:59 -04002373 visitor->visitSampler(var.type(), var.name() + SAMPLER_SUFFIX);
Brian Osman58134e12021-05-13 14:51:07 -04002374 continue;
2375 }
2376
2377 if (!(var.modifiers().fFlags & ~Modifiers::kConst_Flag) &&
2378 -1 == var.modifiers().fLayout.fBuiltin) {
2379 // Visit a regular variable.
2380 visitor->visitVariable(var, decl.value().get());
Timothy Liangee84fe12018-05-18 14:38:19 -04002381 }
2382 }
John Stilescdcdb042020-07-06 09:03:51 -04002383}
2384
2385void MetalCodeGenerator::writeGlobalStruct() {
2386 class : public GlobalStructVisitor {
2387 public:
Ethan Nicholas962dec42021-06-10 13:06:39 -04002388 void visitInterfaceBlock(const InterfaceBlock& block,
2389 skstd::string_view blockName) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002390 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002391 fCodeGen->write(" constant ");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04002392 fCodeGen->write(block.typeName());
John Stilescdcdb042020-07-06 09:03:51 -04002393 fCodeGen->write("* ");
2394 fCodeGen->writeName(blockName);
2395 fCodeGen->write(";\n");
2396 }
Ethan Nicholas962dec42021-06-10 13:06:39 -04002397 void visitTexture(const Type& type, skstd::string_view name) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002398 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002399 fCodeGen->write(" ");
John Stilesb4418502021-02-04 10:57:08 -05002400 fCodeGen->writeType(type);
John Stilescdcdb042020-07-06 09:03:51 -04002401 fCodeGen->write(" ");
2402 fCodeGen->writeName(name);
2403 fCodeGen->write(";\n");
2404 }
Ethan Nicholas962dec42021-06-10 13:06:39 -04002405 void visitSampler(const Type&, skstd::string_view name) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002406 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002407 fCodeGen->write(" sampler ");
2408 fCodeGen->writeName(name);
2409 fCodeGen->write(";\n");
2410 }
John Stilesfdb8dbe2020-12-04 11:00:03 -05002411 void visitVariable(const Variable& var, const Expression* value) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002412 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002413 fCodeGen->write(" ");
Brian Osman58134e12021-05-13 14:51:07 -04002414 fCodeGen->writeModifiers(var.modifiers());
John Stilesb4418502021-02-04 10:57:08 -05002415 fCodeGen->writeType(var.type());
John Stilescdcdb042020-07-06 09:03:51 -04002416 fCodeGen->write(" ");
Ethan Nicholase2c49992020-10-05 11:49:11 -04002417 fCodeGen->writeName(var.name());
John Stilescdcdb042020-07-06 09:03:51 -04002418 fCodeGen->write(";\n");
2419 }
John Stiles83f3b8d2020-12-07 17:52:25 -05002420 void addElement() {
John Stilescdcdb042020-07-06 09:03:51 -04002421 if (fFirst) {
2422 fCodeGen->write("struct Globals {\n");
2423 fFirst = false;
2424 }
2425 }
John Stiles83f3b8d2020-12-07 17:52:25 -05002426 void finish() {
John Stilescdcdb042020-07-06 09:03:51 -04002427 if (!fFirst) {
John Stiles83f3b8d2020-12-07 17:52:25 -05002428 fCodeGen->writeLine("};");
John Stilescdcdb042020-07-06 09:03:51 -04002429 fFirst = true;
2430 }
2431 }
2432
2433 MetalCodeGenerator* fCodeGen = nullptr;
2434 bool fFirst = true;
2435 } visitor;
2436
2437 visitor.fCodeGen = this;
2438 this->visitGlobalStruct(&visitor);
John Stiles83f3b8d2020-12-07 17:52:25 -05002439 visitor.finish();
John Stilescdcdb042020-07-06 09:03:51 -04002440}
2441
2442void MetalCodeGenerator::writeGlobalInit() {
2443 class : public GlobalStructVisitor {
2444 public:
John Stilesfdb8dbe2020-12-04 11:00:03 -05002445 void visitInterfaceBlock(const InterfaceBlock& blockType,
Ethan Nicholas962dec42021-06-10 13:06:39 -04002446 skstd::string_view blockName) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002447 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002448 fCodeGen->write("&");
2449 fCodeGen->writeName(blockName);
2450 }
Ethan Nicholas962dec42021-06-10 13:06:39 -04002451 void visitTexture(const Type&, skstd::string_view name) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002452 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002453 fCodeGen->writeName(name);
2454 }
Ethan Nicholas962dec42021-06-10 13:06:39 -04002455 void visitSampler(const Type&, skstd::string_view name) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002456 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002457 fCodeGen->writeName(name);
2458 }
John Stilesfdb8dbe2020-12-04 11:00:03 -05002459 void visitVariable(const Variable& var, const Expression* value) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002460 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002461 if (value) {
2462 fCodeGen->writeVarInitializer(var, *value);
2463 } else {
2464 fCodeGen->write("{}");
2465 }
2466 }
John Stiles83f3b8d2020-12-07 17:52:25 -05002467 void addElement() {
John Stilescdcdb042020-07-06 09:03:51 -04002468 if (fFirst) {
John Stilesf7410bd2021-01-19 13:07:55 -05002469 fCodeGen->write(" Globals _globals{");
John Stilescdcdb042020-07-06 09:03:51 -04002470 fFirst = false;
2471 } else {
2472 fCodeGen->write(", ");
2473 }
2474 }
John Stiles83f3b8d2020-12-07 17:52:25 -05002475 void finish() {
John Stilescdcdb042020-07-06 09:03:51 -04002476 if (!fFirst) {
2477 fCodeGen->writeLine("};");
John Stiles37279172021-01-21 22:24:28 -05002478 fCodeGen->writeLine(" (void)_globals;");
John Stilescdcdb042020-07-06 09:03:51 -04002479 }
2480 }
2481 MetalCodeGenerator* fCodeGen = nullptr;
2482 bool fFirst = true;
2483 } visitor;
2484
2485 visitor.fCodeGen = this;
2486 this->visitGlobalStruct(&visitor);
John Stiles83f3b8d2020-12-07 17:52:25 -05002487 visitor.finish();
Timothy Liangee84fe12018-05-18 14:38:19 -04002488}
2489
Ethan Nicholascc305772017-10-13 16:17:45 -04002490void MetalCodeGenerator::writeProgramElement(const ProgramElement& e) {
Ethan Nicholase6592142020-09-08 10:22:09 -04002491 switch (e.kind()) {
2492 case ProgramElement::Kind::kExtension:
Ethan Nicholascc305772017-10-13 16:17:45 -04002493 break;
Brian Osman58134e12021-05-13 14:51:07 -04002494 case ProgramElement::Kind::kGlobalVar:
Ethan Nicholascc305772017-10-13 16:17:45 -04002495 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04002496 case ProgramElement::Kind::kInterfaceBlock:
Timothy Liang7d637782018-06-05 09:58:07 -04002497 // handled in writeInterfaceBlocks, do nothing
Ethan Nicholascc305772017-10-13 16:17:45 -04002498 break;
John Stilesdc75a972020-11-25 16:24:55 -05002499 case ProgramElement::Kind::kStructDefinition:
2500 // Handled in writeStructDefinitions. Do nothing.
2501 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04002502 case ProgramElement::Kind::kFunction:
John Stiles3dc0da62020-08-19 17:48:31 -04002503 this->writeFunction(e.as<FunctionDefinition>());
Ethan Nicholascc305772017-10-13 16:17:45 -04002504 break;
John Stiles569249b2020-11-03 12:18:22 -05002505 case ProgramElement::Kind::kFunctionPrototype:
2506 this->writeFunctionPrototype(e.as<FunctionPrototype>());
2507 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04002508 case ProgramElement::Kind::kModifiers:
Brian Osman58134e12021-05-13 14:51:07 -04002509 this->writeModifiers(e.as<ModifiersDeclaration>().modifiers());
Ethan Nicholascc305772017-10-13 16:17:45 -04002510 this->writeLine(";");
2511 break;
2512 default:
John Stileseada7bc2021-02-02 16:29:32 -05002513 SkDEBUGFAILF("unsupported program element: %s\n", e.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -05002514 break;
Ethan Nicholascc305772017-10-13 16:17:45 -04002515 }
2516}
2517
Ethan Nicholasff350cb2020-05-14 14:05:13 -04002518MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const Expression* e) {
2519 if (!e) {
2520 return kNo_Requirements;
2521 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002522 switch (e->kind()) {
2523 case Expression::Kind::kFunctionCall: {
John Stiles3dc0da62020-08-19 17:48:31 -04002524 const FunctionCall& f = e->as<FunctionCall>();
Ethan Nicholas0dec9922020-10-05 15:51:52 -04002525 Requirements result = this->requirements(f.function());
2526 for (const auto& arg : f.arguments()) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04002527 result |= this->requirements(arg.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002528 }
2529 return result;
2530 }
John Stiles8cad6372021-04-07 12:31:13 -04002531 case Expression::Kind::kConstructorCompound:
2532 case Expression::Kind::kConstructorCompoundCast:
John Stiles7384b372021-04-01 13:48:15 -04002533 case Expression::Kind::kConstructorArray:
John Stilese3ae9682021-08-05 10:35:01 -04002534 case Expression::Kind::kConstructorArrayCast:
John Stiles2938eea2021-04-01 18:58:25 -04002535 case Expression::Kind::kConstructorDiagonalMatrix:
John Stilesfd7252f2021-04-04 22:24:40 -04002536 case Expression::Kind::kConstructorScalarCast:
John Stilesd47330f2021-04-08 23:25:52 -04002537 case Expression::Kind::kConstructorSplat:
2538 case Expression::Kind::kConstructorStruct: {
John Stiles7384b372021-04-01 13:48:15 -04002539 const AnyConstructor& c = e->asAnyConstructor();
Ethan Nicholascc305772017-10-13 16:17:45 -04002540 Requirements result = kNo_Requirements;
John Stilesd8eb8752021-04-01 11:49:10 -04002541 for (const auto& arg : c.argumentSpan()) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04002542 result |= this->requirements(arg.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002543 }
2544 return result;
2545 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002546 case Expression::Kind::kFieldAccess: {
John Stiles3dc0da62020-08-19 17:48:31 -04002547 const FieldAccess& f = e->as<FieldAccess>();
Ethan Nicholas7a95b202020-10-09 11:55:40 -04002548 if (FieldAccess::OwnerKind::kAnonymousInterfaceBlock == f.ownerKind()) {
Timothy Liang7d637782018-06-05 09:58:07 -04002549 return kGlobals_Requirement;
2550 }
Ethan Nicholas7a95b202020-10-09 11:55:40 -04002551 return this->requirements(f.base().get());
Timothy Liang7d637782018-06-05 09:58:07 -04002552 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002553 case Expression::Kind::kSwizzle:
Ethan Nicholas6b4d5812020-10-12 16:11:51 -04002554 return this->requirements(e->as<Swizzle>().base().get());
Ethan Nicholase6592142020-09-08 10:22:09 -04002555 case Expression::Kind::kBinary: {
2556 const BinaryExpression& bin = e->as<BinaryExpression>();
John Stiles2d4f9592020-10-30 10:29:12 -04002557 return this->requirements(bin.left().get()) |
2558 this->requirements(bin.right().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002559 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002560 case Expression::Kind::kIndex: {
John Stiles3dc0da62020-08-19 17:48:31 -04002561 const IndexExpression& idx = e->as<IndexExpression>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04002562 return this->requirements(idx.base().get()) | this->requirements(idx.index().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002563 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002564 case Expression::Kind::kPrefix:
Ethan Nicholas444ccc62020-10-09 10:16:22 -04002565 return this->requirements(e->as<PrefixExpression>().operand().get());
Ethan Nicholase6592142020-09-08 10:22:09 -04002566 case Expression::Kind::kPostfix:
Ethan Nicholas444ccc62020-10-09 10:16:22 -04002567 return this->requirements(e->as<PostfixExpression>().operand().get());
Ethan Nicholase6592142020-09-08 10:22:09 -04002568 case Expression::Kind::kTernary: {
John Stiles3dc0da62020-08-19 17:48:31 -04002569 const TernaryExpression& t = e->as<TernaryExpression>();
Ethan Nicholasdd218162020-10-08 05:48:01 -04002570 return this->requirements(t.test().get()) | this->requirements(t.ifTrue().get()) |
2571 this->requirements(t.ifFalse().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002572 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002573 case Expression::Kind::kVariableReference: {
John Stiles3dc0da62020-08-19 17:48:31 -04002574 const VariableReference& v = e->as<VariableReference>();
Ethan Nicholas78686922020-10-08 06:46:27 -04002575 const Modifiers& modifiers = v.variable()->modifiers();
Ethan Nicholascc305772017-10-13 16:17:45 -04002576 Requirements result = kNo_Requirements;
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002577 if (modifiers.fLayout.fBuiltin == SK_FRAGCOORD_BUILTIN) {
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -04002578 result = kGlobals_Requirement | kFragCoord_Requirement;
Ethan Nicholas453f67f2020-10-09 10:43:45 -04002579 } else if (Variable::Storage::kGlobal == v.variable()->storage()) {
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002580 if (modifiers.fFlags & Modifiers::kIn_Flag) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002581 result = kInputs_Requirement;
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002582 } else if (modifiers.fFlags & Modifiers::kOut_Flag) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002583 result = kOutputs_Requirement;
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002584 } else if (modifiers.fFlags & Modifiers::kUniform_Flag &&
Ethan Nicholas78686922020-10-08 06:46:27 -04002585 v.variable()->type().typeKind() != Type::TypeKind::kSampler) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002586 result = kUniforms_Requirement;
Timothy Liangee84fe12018-05-18 14:38:19 -04002587 } else {
2588 result = kGlobals_Requirement;
Ethan Nicholascc305772017-10-13 16:17:45 -04002589 }
2590 }
2591 return result;
2592 }
2593 default:
2594 return kNo_Requirements;
2595 }
2596}
2597
Ethan Nicholasff350cb2020-05-14 14:05:13 -04002598MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const Statement* s) {
2599 if (!s) {
2600 return kNo_Requirements;
2601 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002602 switch (s->kind()) {
2603 case Statement::Kind::kBlock: {
Ethan Nicholascc305772017-10-13 16:17:45 -04002604 Requirements result = kNo_Requirements;
Ethan Nicholas7bd60432020-09-25 14:31:59 -04002605 for (const std::unique_ptr<Statement>& child : s->as<Block>().children()) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04002606 result |= this->requirements(child.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002607 }
2608 return result;
2609 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002610 case Statement::Kind::kVarDeclaration: {
John Stiles3dc0da62020-08-19 17:48:31 -04002611 const VarDeclaration& var = s->as<VarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04002612 return this->requirements(var.value().get());
Timothy Liang7d637782018-06-05 09:58:07 -04002613 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002614 case Statement::Kind::kExpression:
Ethan Nicholasd503a5a2020-09-30 09:29:55 -04002615 return this->requirements(s->as<ExpressionStatement>().expression().get());
Ethan Nicholase6592142020-09-08 10:22:09 -04002616 case Statement::Kind::kReturn: {
John Stiles3dc0da62020-08-19 17:48:31 -04002617 const ReturnStatement& r = s->as<ReturnStatement>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04002618 return this->requirements(r.expression().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002619 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002620 case Statement::Kind::kIf: {
John Stiles3dc0da62020-08-19 17:48:31 -04002621 const IfStatement& i = s->as<IfStatement>();
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04002622 return this->requirements(i.test().get()) |
2623 this->requirements(i.ifTrue().get()) |
2624 this->requirements(i.ifFalse().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002625 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002626 case Statement::Kind::kFor: {
John Stiles3dc0da62020-08-19 17:48:31 -04002627 const ForStatement& f = s->as<ForStatement>();
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04002628 return this->requirements(f.initializer().get()) |
2629 this->requirements(f.test().get()) |
2630 this->requirements(f.next().get()) |
2631 this->requirements(f.statement().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002632 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002633 case Statement::Kind::kDo: {
John Stiles3dc0da62020-08-19 17:48:31 -04002634 const DoStatement& d = s->as<DoStatement>();
Ethan Nicholas1fd61162020-09-28 13:14:19 -04002635 return this->requirements(d.test().get()) |
2636 this->requirements(d.statement().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002637 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002638 case Statement::Kind::kSwitch: {
John Stiles3dc0da62020-08-19 17:48:31 -04002639 const SwitchStatement& sw = s->as<SwitchStatement>();
Ethan Nicholas01b05e52020-10-22 15:53:41 -04002640 Requirements result = this->requirements(sw.value().get());
John Stilesb23a64b2021-03-11 08:27:59 -05002641 for (const std::unique_ptr<Statement>& sc : sw.cases()) {
2642 result |= this->requirements(sc->as<SwitchCase>().statement().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002643 }
2644 return result;
2645 }
2646 default:
2647 return kNo_Requirements;
2648 }
2649}
2650
2651MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const FunctionDeclaration& f) {
Ethan Nicholased84b732020-10-08 11:45:44 -04002652 if (f.isBuiltin()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002653 return kNo_Requirements;
2654 }
2655 auto found = fRequirements.find(&f);
2656 if (found == fRequirements.end()) {
Ethan Nicholas65a8f562019-04-19 14:00:26 -04002657 fRequirements[&f] = kNo_Requirements;
Brian Osman133724c2020-10-28 14:14:39 -04002658 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04002659 if (e->is<FunctionDefinition>()) {
2660 const FunctionDefinition& def = e->as<FunctionDefinition>();
Ethan Nicholas0a5d0962020-10-14 13:33:18 -04002661 if (&def.declaration() == &f) {
2662 Requirements reqs = this->requirements(def.body().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002663 fRequirements[&f] = reqs;
2664 return reqs;
2665 }
2666 }
2667 }
John Stiles569249b2020-11-03 12:18:22 -05002668 // We never found a definition for this declared function, but it's legal to prototype a
2669 // function without ever giving a definition, as long as you don't call it.
2670 return kNo_Requirements;
Ethan Nicholascc305772017-10-13 16:17:45 -04002671 }
2672 return found->second;
2673}
2674
Timothy Liangb8eeb802018-07-23 16:46:16 -04002675bool MetalCodeGenerator::generateCode() {
John Stiles44532372020-12-07 12:33:55 -05002676 StringStream header;
2677 {
2678 AutoOutputStream outputToHeader(this, &header, &fIndentation);
Michael Ludwigbf58add2021-03-16 10:40:11 -04002679 this->writeHeader();
John Stiles44532372020-12-07 12:33:55 -05002680 this->writeStructDefinitions();
2681 this->writeUniformStruct();
2682 this->writeInputStruct();
2683 this->writeOutputStruct();
2684 this->writeInterfaceBlocks();
2685 this->writeGlobalStruct();
2686 }
2687 StringStream body;
2688 {
2689 AutoOutputStream outputToBody(this, &body, &fIndentation);
2690 for (const ProgramElement* e : fProgram.elements()) {
2691 this->writeProgramElement(*e);
2692 }
2693 }
2694 write_stringstream(header, *fOut);
John Stiles82d4c122021-08-10 16:03:23 -04002695 write_stringstream(fExtraFunctionPrototypes, *fOut);
John Stiles44532372020-12-07 12:33:55 -05002696 write_stringstream(fExtraFunctions, *fOut);
2697 write_stringstream(body, *fOut);
Ethan Nicholas0f36d112021-08-23 15:27:36 -04002698 fContext.fErrors->reportPendingErrors(PositionInfo());
Ethan Nicholas39f6da42021-08-23 13:10:07 -04002699 return fContext.fErrors->errorCount() == 0;
Ethan Nicholascc305772017-10-13 16:17:45 -04002700}
2701
John Stilesa6841be2020-08-06 14:11:56 -04002702} // namespace SkSL