blob: 658445736e375cc6e315697a4734356cf7ea17a0 [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 Stiles54e7c052021-01-11 14:22:36 -050095 if (type == *fContext.fTypes.fHalf) {
Timothy Liang43d225f2018-07-19 15:27:13 -040096 // FIXME - Currently only supporting floats in MSL to avoid type coercion issues.
Ethan Nicholasd2e09602021-06-10 11:21:59 -040097 return String(fContext.fTypes.fFloat->name());
Timothy Liang7d637782018-06-05 09:58:07 -040098 } else {
Ethan Nicholasd2e09602021-06-10 11:21:59 -040099 return String(type.name());
Timothy Liang7d637782018-06-05 09:58:07 -0400100 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400101 }
102}
103
Brian Osman02bc5222021-01-28 11:00:20 -0500104void MetalCodeGenerator::writeStructDefinition(const StructDefinition& s) {
105 const Type& type = s.type();
John Stilesdc75a972020-11-25 16:24:55 -0500106 this->writeLine("struct " + type.name() + " {");
107 fIndentation++;
108 this->writeFields(type.fields(), type.fOffset);
109 fIndentation--;
Brian Osman02bc5222021-01-28 11:00:20 -0500110 this->writeLine("};");
John Stilesdc75a972020-11-25 16:24:55 -0500111}
112
John Stilesb4418502021-02-04 10:57:08 -0500113void MetalCodeGenerator::writeType(const Type& type) {
114 this->write(this->typeName(type));
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500115}
116
Ethan Nicholascc305772017-10-13 16:17:45 -0400117void MetalCodeGenerator::writeExpression(const Expression& expr, Precedence parentPrecedence) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400118 switch (expr.kind()) {
119 case Expression::Kind::kBinary:
John Stiles81365af2020-08-18 09:24:00 -0400120 this->writeBinaryExpression(expr.as<BinaryExpression>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400121 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400122 case Expression::Kind::kBoolLiteral:
John Stiles81365af2020-08-18 09:24:00 -0400123 this->writeBoolLiteral(expr.as<BoolLiteral>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400124 break;
John Stiles2bec8ab2021-04-06 18:40:04 -0400125 case Expression::Kind::kConstructorArray:
John Stilesd47330f2021-04-08 23:25:52 -0400126 case Expression::Kind::kConstructorStruct:
John Stiles2bec8ab2021-04-06 18:40:04 -0400127 this->writeAnyConstructor(expr.asAnyConstructor(), "{", "}", parentPrecedence);
128 break;
John Stilese3ae9682021-08-05 10:35:01 -0400129 case Expression::Kind::kConstructorArrayCast:
130 this->writeExpression(*expr.as<ConstructorArrayCast>().argument(), parentPrecedence);
131 break;
John Stiles8cad6372021-04-07 12:31:13 -0400132 case Expression::Kind::kConstructorCompound:
133 this->writeConstructorCompound(expr.as<ConstructorCompound>(), parentPrecedence);
John Stiles2bec8ab2021-04-06 18:40:04 -0400134 break;
135 case Expression::Kind::kConstructorDiagonalMatrix:
136 case Expression::Kind::kConstructorSplat:
137 this->writeAnyConstructor(expr.asAnyConstructor(), "(", ")", parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400138 break;
John Stiles5abb9e12021-04-06 13:47:19 -0400139 case Expression::Kind::kConstructorMatrixResize:
140 this->writeConstructorMatrixResize(expr.as<ConstructorMatrixResize>(),
141 parentPrecedence);
142 break;
John Stilesfd7252f2021-04-04 22:24:40 -0400143 case Expression::Kind::kConstructorScalarCast:
John Stiles8cad6372021-04-07 12:31:13 -0400144 case Expression::Kind::kConstructorCompoundCast:
John Stilesb14a8192021-04-05 11:40:46 -0400145 this->writeCastConstructor(expr.asAnyConstructor(), "(", ")", parentPrecedence);
John Stiles2938eea2021-04-01 18:58:25 -0400146 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400147 case Expression::Kind::kIntLiteral:
John Stiles81365af2020-08-18 09:24:00 -0400148 this->writeIntLiteral(expr.as<IntLiteral>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400149 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400150 case Expression::Kind::kFieldAccess:
John Stiles81365af2020-08-18 09:24:00 -0400151 this->writeFieldAccess(expr.as<FieldAccess>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400152 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400153 case Expression::Kind::kFloatLiteral:
John Stiles81365af2020-08-18 09:24:00 -0400154 this->writeFloatLiteral(expr.as<FloatLiteral>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400155 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400156 case Expression::Kind::kFunctionCall:
John Stiles81365af2020-08-18 09:24:00 -0400157 this->writeFunctionCall(expr.as<FunctionCall>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400158 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400159 case Expression::Kind::kPrefix:
John Stiles81365af2020-08-18 09:24:00 -0400160 this->writePrefixExpression(expr.as<PrefixExpression>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400161 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400162 case Expression::Kind::kPostfix:
John Stiles81365af2020-08-18 09:24:00 -0400163 this->writePostfixExpression(expr.as<PostfixExpression>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400164 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400165 case Expression::Kind::kSetting:
John Stiles81365af2020-08-18 09:24:00 -0400166 this->writeSetting(expr.as<Setting>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400167 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400168 case Expression::Kind::kSwizzle:
John Stiles81365af2020-08-18 09:24:00 -0400169 this->writeSwizzle(expr.as<Swizzle>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400170 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400171 case Expression::Kind::kVariableReference:
John Stiles81365af2020-08-18 09:24:00 -0400172 this->writeVariableReference(expr.as<VariableReference>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400173 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400174 case Expression::Kind::kTernary:
John Stiles81365af2020-08-18 09:24:00 -0400175 this->writeTernaryExpression(expr.as<TernaryExpression>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400176 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400177 case Expression::Kind::kIndex:
John Stiles81365af2020-08-18 09:24:00 -0400178 this->writeIndexExpression(expr.as<IndexExpression>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400179 break;
180 default:
John Stileseada7bc2021-02-02 16:29:32 -0500181 SkDEBUGFAILF("unsupported expression: %s", expr.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -0500182 break;
Ethan Nicholascc305772017-10-13 16:17:45 -0400183 }
184}
185
John Stiles06b84ef2020-12-09 12:35:48 -0500186String MetalCodeGenerator::getOutParamHelper(const FunctionCall& call,
187 const ExpressionArray& arguments,
188 const SkTArray<VariableReference*>& outVars) {
189 AutoOutputStream outputToExtraFunctions(this, &fExtraFunctions, &fIndentation);
190 const FunctionDeclaration& function = call.function();
191
John Stilese1068342021-03-22 11:57:41 -0400192 String name = "_skOutParamHelper" + to_string(fSwizzleHelperCount++) +
193 "_" + function.mangledName();
John Stiles06b84ef2020-12-09 12:35:48 -0500194 const char* separator = "";
195
196 // Emit a prototype for the function we'll be calling through to in our helper.
197 if (!function.isBuiltin()) {
198 this->writeFunctionDeclaration(function);
199 this->writeLine(";");
200 }
201
202 // Synthesize a helper function that takes the same inputs as `function`, except in places where
203 // `outVars` is non-null; in those places, we take the type of the VariableReference.
204 //
205 // float _skOutParamHelper0_originalFuncName(float _var0, float _var1, float& outParam) {
John Stilesb4418502021-02-04 10:57:08 -0500206 this->writeType(call.type());
John Stiles06b84ef2020-12-09 12:35:48 -0500207 this->write(" ");
208 this->write(name);
209 this->write("(");
210 this->writeFunctionRequirementParams(function, separator);
211
212 SkASSERT(outVars.size() == arguments.size());
213 SkASSERT(outVars.size() == function.parameters().size());
214
John Stiles73e2c892021-02-13 13:58:01 -0500215 // We need to detect cases where the caller passes the same variable as an out-param more than
216 // once, and avoid reusing the variable name. (In those cases we can actually just ignore the
217 // redundant input parameter entirely, and not give it any name.)
218 std::unordered_set<const Variable*> writtenVars;
219
John Stiles06b84ef2020-12-09 12:35:48 -0500220 for (int index = 0; index < arguments.count(); ++index) {
221 this->write(separator);
222 separator = ", ";
223
224 const Variable* param = function.parameters()[index];
Brian Osman58134e12021-05-13 14:51:07 -0400225 this->writeModifiers(param->modifiers());
John Stiles06b84ef2020-12-09 12:35:48 -0500226
227 const Type* type = outVars[index] ? &outVars[index]->type() : &arguments[index]->type();
John Stilesb4418502021-02-04 10:57:08 -0500228 this->writeType(*type);
John Stiles06b84ef2020-12-09 12:35:48 -0500229
230 if (param->modifiers().fFlags & Modifiers::kOut_Flag) {
231 this->write("&");
232 }
233 if (outVars[index]) {
John Stiles73e2c892021-02-13 13:58:01 -0500234 auto [iter, didInsert] = writtenVars.insert(outVars[index]->variable());
235 if (didInsert) {
236 this->write(" ");
237 fIgnoreVariableReferenceModifiers = true;
238 this->writeVariableReference(*outVars[index]);
239 fIgnoreVariableReferenceModifiers = false;
240 }
John Stiles06b84ef2020-12-09 12:35:48 -0500241 } else {
242 this->write(" _var");
243 this->write(to_string(index));
244 }
John Stiles06b84ef2020-12-09 12:35:48 -0500245 }
246 this->writeLine(") {");
247
248 ++fIndentation;
249 for (int index = 0; index < outVars.count(); ++index) {
250 if (!outVars[index]) {
251 continue;
252 }
253 // float3 _var2[ = outParam.zyx];
John Stilesb4418502021-02-04 10:57:08 -0500254 this->writeType(arguments[index]->type());
John Stiles06b84ef2020-12-09 12:35:48 -0500255 this->write(" _var");
256 this->write(to_string(index));
257
258 const Variable* param = function.parameters()[index];
259 if (param->modifiers().fFlags & Modifiers::kIn_Flag) {
260 this->write(" = ");
261 fIgnoreVariableReferenceModifiers = true;
Brian Osman00185012021-02-04 16:07:11 -0500262 this->writeExpression(*arguments[index], Precedence::kAssignment);
John Stiles06b84ef2020-12-09 12:35:48 -0500263 fIgnoreVariableReferenceModifiers = false;
264 }
265
266 this->writeLine(";");
267 }
268
John Stilesf7410bd2021-01-19 13:07:55 -0500269 // [int _skResult = ] myFunction(inputs, outputs, _globals, _var0, _var1, _var2, _var3);
John Stiles06b84ef2020-12-09 12:35:48 -0500270 bool hasResult = (call.type().name() != "void");
271 if (hasResult) {
John Stilesb4418502021-02-04 10:57:08 -0500272 this->writeType(call.type());
John Stiles06b84ef2020-12-09 12:35:48 -0500273 this->write(" _skResult = ");
274 }
275
John Stilese1068342021-03-22 11:57:41 -0400276 this->writeName(function.mangledName());
John Stiles06b84ef2020-12-09 12:35:48 -0500277 this->write("(");
278 separator = "";
279 this->writeFunctionRequirementArgs(function, separator);
280
281 for (int index = 0; index < arguments.count(); ++index) {
282 this->write(separator);
283 separator = ", ";
284
285 this->write("_var");
286 this->write(to_string(index));
287 }
288 this->writeLine(");");
289
290 for (int index = 0; index < outVars.count(); ++index) {
291 if (!outVars[index]) {
292 continue;
293 }
294 // outParam.zyx = _var2;
295 fIgnoreVariableReferenceModifiers = true;
Brian Osman00185012021-02-04 16:07:11 -0500296 this->writeExpression(*arguments[index], Precedence::kAssignment);
John Stiles06b84ef2020-12-09 12:35:48 -0500297 fIgnoreVariableReferenceModifiers = false;
298 this->write(" = _var");
299 this->write(to_string(index));
300 this->writeLine(";");
301 }
302
303 if (hasResult) {
304 this->writeLine("return _skResult;");
305 }
306
307 --fIndentation;
308 this->writeLine("}");
309
310 return name;
John Stilesb21fac22020-12-04 15:36:49 -0500311}
312
John Stilesf64e4072020-12-10 10:34:27 -0500313String MetalCodeGenerator::getBitcastIntrinsic(const Type& outType) {
314 return "as_type<" + outType.displayName() + ">";
315}
316
Ethan Nicholascc305772017-10-13 16:17:45 -0400317void MetalCodeGenerator::writeFunctionCall(const FunctionCall& c) {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400318 const FunctionDeclaration& function = c.function();
John Stiles496b7d12021-05-06 10:26:45 -0400319
320 // Many intrinsics need to be rewritten in Metal.
321 if (function.isIntrinsic()) {
322 if (this->writeIntrinsicCall(c, function.intrinsicKind())) {
John Stiles89ac7c22020-12-30 17:47:31 -0500323 return;
324 }
Timothy Liang6403b0e2018-05-17 10:40:04 -0400325 }
John Stilesb21fac22020-12-04 15:36:49 -0500326
John Stilesd7199b22020-12-30 16:22:58 -0500327 // Determine whether or not we need to emulate GLSL's out-param semantics for Metal using a
328 // helper function. (Specifically, out-parameters in GLSL are only written back to the original
329 // variable at the end of the function call; also, swizzles are supported, whereas Metal doesn't
330 // allow a swizzle to be passed to a `floatN&`.)
331 const ExpressionArray& arguments = c.arguments();
John Stilesb21fac22020-12-04 15:36:49 -0500332 const std::vector<const Variable*>& parameters = function.parameters();
333 SkASSERT(arguments.size() == parameters.size());
John Stiles06b84ef2020-12-09 12:35:48 -0500334
335 bool foundOutParam = false;
336 SkSTArray<16, VariableReference*> outVars;
John Stilesf64e4072020-12-10 10:34:27 -0500337 outVars.push_back_n(arguments.count(), (VariableReference*)nullptr);
John Stiles06b84ef2020-12-09 12:35:48 -0500338
339 for (int index = 0; index < arguments.count(); ++index) {
John Stilesb21fac22020-12-04 15:36:49 -0500340 // If this is an out parameter...
341 if (parameters[index]->modifiers().fFlags & Modifiers::kOut_Flag) {
John Stiles06b84ef2020-12-09 12:35:48 -0500342 // Find the expression's inner variable being written to.
John Stilesb21fac22020-12-04 15:36:49 -0500343 Analysis::AssignmentInfo info;
John Stiles06b84ef2020-12-09 12:35:48 -0500344 // Assignability was verified at IRGeneration time, so this should always succeed.
345 SkAssertResult(Analysis::IsAssignable(*arguments[index], &info));
346 outVars[index] = info.fAssignedVar;
347 foundOutParam = true;
John Stilesb21fac22020-12-04 15:36:49 -0500348 }
349 }
350
John Stiles06b84ef2020-12-09 12:35:48 -0500351 if (foundOutParam) {
352 // Out parameters need to be written back to at the end of the function. To do this, we
353 // synthesize a helper function which evaluates the out-param expression into a temporary
354 // variable, calls the original function, then writes the temp var back into the out param
355 // using the original out-param expression. (This lets us support things like swizzles and
356 // array indices.)
John Stilesd7199b22020-12-30 16:22:58 -0500357 this->write(getOutParamHelper(c, arguments, outVars));
358 } else {
John Stilese1068342021-03-22 11:57:41 -0400359 this->write(function.mangledName());
John Stiles06b84ef2020-12-09 12:35:48 -0500360 }
361
Ethan Nicholascc305772017-10-13 16:17:45 -0400362 this->write("(");
363 const char* separator = "";
John Stiles06b84ef2020-12-09 12:35:48 -0500364 this->writeFunctionRequirementArgs(function, separator);
365 for (int i = 0; i < arguments.count(); ++i) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400366 this->write(separator);
367 separator = ", ";
John Stiles06b84ef2020-12-09 12:35:48 -0500368
369 if (outVars[i]) {
Brian Osman00185012021-02-04 16:07:11 -0500370 this->writeExpression(*outVars[i], Precedence::kSequence);
John Stiles06b84ef2020-12-09 12:35:48 -0500371 } else {
Brian Osman00185012021-02-04 16:07:11 -0500372 this->writeExpression(*arguments[i], Precedence::kSequence);
John Stiles06b84ef2020-12-09 12:35:48 -0500373 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400374 }
375 this->write(")");
376}
377
Brian Osman964f0a02020-12-29 10:15:22 -0500378static constexpr char kInverse2x2[] = R"(
379float2x2 float2x2_inverse(float2x2 m) {
380 return float2x2(m[1][1], -m[0][1], -m[1][0], m[0][0]) * (1/determinant(m));
381}
382)";
383
384static constexpr char kInverse3x3[] = R"(
385float3x3 float3x3_inverse(float3x3 m) {
386 float a00 = m[0][0], a01 = m[0][1], a02 = m[0][2];
387 float a10 = m[1][0], a11 = m[1][1], a12 = m[1][2];
388 float a20 = m[2][0], a21 = m[2][1], a22 = m[2][2];
389 float b01 = a22*a11 - a12*a21;
390 float b11 = -a22*a10 + a12*a20;
391 float b21 = a21*a10 - a11*a20;
392 float det = a00*b01 + a01*b11 + a02*b21;
393 return float3x3(b01, (-a22*a01 + a02*a21), ( a12*a01 - a02*a11),
394 b11, ( a22*a00 - a02*a20), (-a12*a00 + a02*a10),
395 b21, (-a21*a00 + a01*a20), ( a11*a00 - a01*a10)) * (1/det);
396}
397)";
398
399static constexpr char kInverse4x4[] = R"(
400float4x4 float4x4_inverse(float4x4 m) {
401 float a00 = m[0][0], a01 = m[0][1], a02 = m[0][2], a03 = m[0][3];
402 float a10 = m[1][0], a11 = m[1][1], a12 = m[1][2], a13 = m[1][3];
403 float a20 = m[2][0], a21 = m[2][1], a22 = m[2][2], a23 = m[2][3];
404 float a30 = m[3][0], a31 = m[3][1], a32 = m[3][2], a33 = m[3][3];
405 float b00 = a00*a11 - a01*a10;
406 float b01 = a00*a12 - a02*a10;
407 float b02 = a00*a13 - a03*a10;
408 float b03 = a01*a12 - a02*a11;
409 float b04 = a01*a13 - a03*a11;
410 float b05 = a02*a13 - a03*a12;
411 float b06 = a20*a31 - a21*a30;
412 float b07 = a20*a32 - a22*a30;
413 float b08 = a20*a33 - a23*a30;
414 float b09 = a21*a32 - a22*a31;
415 float b10 = a21*a33 - a23*a31;
416 float b11 = a22*a33 - a23*a32;
417 float det = b00*b11 - b01*b10 + b02*b09 + b03*b08 - b04*b07 + b05*b06;
418 return float4x4(a11*b11 - a12*b10 + a13*b09,
419 a02*b10 - a01*b11 - a03*b09,
420 a31*b05 - a32*b04 + a33*b03,
421 a22*b04 - a21*b05 - a23*b03,
422 a12*b08 - a10*b11 - a13*b07,
423 a00*b11 - a02*b08 + a03*b07,
424 a32*b02 - a30*b05 - a33*b01,
425 a20*b05 - a22*b02 + a23*b01,
426 a10*b10 - a11*b08 + a13*b06,
427 a01*b08 - a00*b10 - a03*b06,
428 a30*b04 - a31*b02 + a33*b00,
429 a21*b02 - a20*b04 - a23*b00,
430 a11*b07 - a10*b09 - a12*b06,
431 a00*b09 - a01*b07 + a02*b06,
432 a31*b01 - a30*b03 - a32*b00,
433 a20*b03 - a21*b01 + a22*b00) * (1/det);
434}
435)";
436
John Stilesd7199b22020-12-30 16:22:58 -0500437String MetalCodeGenerator::getInversePolyfill(const ExpressionArray& arguments) {
438 // Only use polyfills for a function taking a single-argument square matrix.
439 if (arguments.size() == 1) {
440 const Type& type = arguments.front()->type();
441 if (type.isMatrix() && type.rows() == type.columns()) {
442 // Inject the correct polyfill based on the matrix size.
443 String name = this->typeName(type) + "_inverse";
444 auto [iter, didInsert] = fWrittenIntrinsics.insert(name);
445 if (didInsert) {
446 switch (type.rows()) {
447 case 2:
448 fExtraFunctions.writeText(kInverse2x2);
449 break;
450 case 3:
451 fExtraFunctions.writeText(kInverse3x3);
452 break;
453 case 4:
454 fExtraFunctions.writeText(kInverse4x4);
455 break;
456 }
457 }
458 return name;
Chris Daltondba7aab2018-11-15 10:57:49 -0500459 }
460 }
John Stilesd7199b22020-12-30 16:22:58 -0500461 // This isn't the built-in `inverse`. We don't want to polyfill it at all.
462 return "inverse";
Chris Daltondba7aab2018-11-15 10:57:49 -0500463}
464
Brian Osman93aed9a2020-12-28 15:18:46 -0500465static constexpr char kMatrixCompMult[] = R"(
466template <int C, int R>
467matrix<float, C, R> matrixCompMult(matrix<float, C, R> a, matrix<float, C, R> b) {
468 matrix<float, C, R> result;
469 for (int c = 0; c < C; ++c) {
470 result[c] = a[c] * b[c];
471 }
472 return result;
473}
474)";
475
476void MetalCodeGenerator::writeMatrixCompMult() {
477 String name = "matrixCompMult";
478 if (fWrittenIntrinsics.find(name) == fWrittenIntrinsics.end()) {
479 fWrittenIntrinsics.insert(name);
480 fExtraFunctions.writeText(kMatrixCompMult);
481 }
482}
483
John Stiles86424eb2020-12-11 11:17:14 -0500484String MetalCodeGenerator::getTempVariable(const Type& type) {
485 String tempVar = "_skTemp" + to_string(fVarCount++);
486 this->fFunctionHeader += " " + this->typeName(type) + " " + tempVar + ";\n";
487 return tempVar;
488}
489
John Stiles791c27d2020-12-30 14:56:57 -0500490void MetalCodeGenerator::writeSimpleIntrinsic(const FunctionCall& c) {
491 // Write out an intrinsic function call exactly as-is. No muss no fuss.
492 this->write(c.function().name());
John Stilesd7199b22020-12-30 16:22:58 -0500493 this->writeArgumentList(c.arguments());
494}
495
496void MetalCodeGenerator::writeArgumentList(const ExpressionArray& arguments) {
John Stiles791c27d2020-12-30 14:56:57 -0500497 this->write("(");
498 const char* separator = "";
John Stilesd7199b22020-12-30 16:22:58 -0500499 for (const std::unique_ptr<Expression>& arg : arguments) {
John Stiles791c27d2020-12-30 14:56:57 -0500500 this->write(separator);
501 separator = ", ";
Brian Osman00185012021-02-04 16:07:11 -0500502 this->writeExpression(*arg, Precedence::kSequence);
John Stiles791c27d2020-12-30 14:56:57 -0500503 }
504 this->write(")");
505}
506
John Stiles496b7d12021-05-06 10:26:45 -0400507bool MetalCodeGenerator::writeIntrinsicCall(const FunctionCall& c, IntrinsicKind kind) {
John Stiles8e3b6be2020-10-13 11:14:08 -0400508 const ExpressionArray& arguments = c.arguments();
Timothy Liang6403b0e2018-05-17 10:40:04 -0400509 switch (kind) {
John Stiles496b7d12021-05-06 10:26:45 -0400510 case k_sample_IntrinsicKind: {
Brian Osman00185012021-02-04 16:07:11 -0500511 this->writeExpression(*arguments[0], Precedence::kSequence);
Timothy Lianga06f2152018-05-24 15:33:31 -0400512 this->write(".sample(");
Brian Osman00185012021-02-04 16:07:11 -0500513 this->writeExpression(*arguments[0], Precedence::kSequence);
Timothy Lianga06f2152018-05-24 15:33:31 -0400514 this->write(SAMPLER_SUFFIX);
515 this->write(", ");
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400516 const Type& arg1Type = arguments[1]->type();
John Stilesb14a8192021-04-05 11:40:46 -0400517 if (arg1Type.columns() == 3) {
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500518 // have to store the vector in a temp variable to avoid double evaluating it
John Stiles86424eb2020-12-11 11:17:14 -0500519 String tmpVar = this->getTempVariable(arg1Type);
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500520 this->write("(" + tmpVar + " = ");
Brian Osman00185012021-02-04 16:07:11 -0500521 this->writeExpression(*arguments[1], Precedence::kSequence);
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500522 this->write(", " + tmpVar + ".xy / " + tmpVar + ".z))");
Timothy Liangee84fe12018-05-18 14:38:19 -0400523 } else {
John Stilesb14a8192021-04-05 11:40:46 -0400524 SkASSERT(arg1Type.columns() == 2);
Brian Osman00185012021-02-04 16:07:11 -0500525 this->writeExpression(*arguments[1], Precedence::kSequence);
Timothy Liangee84fe12018-05-18 14:38:19 -0400526 this->write(")");
527 }
John Stiles496b7d12021-05-06 10:26:45 -0400528 return true;
Ethan Nicholas30d30222020-09-11 12:27:26 -0400529 }
John Stiles496b7d12021-05-06 10:26:45 -0400530 case k_mod_IntrinsicKind: {
Timothy Liang651286f2018-06-07 09:55:33 -0400531 // 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 -0500532 String tmpX = this->getTempVariable(arguments[0]->type());
John Stiles61b2e812020-12-30 18:27:31 -0500533 String tmpY = this->getTempVariable(arguments[1]->type());
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500534 this->write("(" + tmpX + " = ");
Brian Osman00185012021-02-04 16:07:11 -0500535 this->writeExpression(*arguments[0], Precedence::kSequence);
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500536 this->write(", " + tmpY + " = ");
Brian Osman00185012021-02-04 16:07:11 -0500537 this->writeExpression(*arguments[1], Precedence::kSequence);
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500538 this->write(", " + tmpX + " - " + tmpY + " * floor(" + tmpX + " / " + tmpY + "))");
John Stiles496b7d12021-05-06 10:26:45 -0400539 return true;
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500540 }
Brian Osman46787d52020-11-24 14:18:23 -0500541 // GLSL declares scalar versions of most geometric intrinsics, but these don't exist in MSL
John Stiles496b7d12021-05-06 10:26:45 -0400542 case k_distance_IntrinsicKind: {
Brian Osman46787d52020-11-24 14:18:23 -0500543 if (arguments[0]->type().columns() == 1) {
544 this->write("abs(");
Brian Osman00185012021-02-04 16:07:11 -0500545 this->writeExpression(*arguments[0], Precedence::kAdditive);
Brian Osman46787d52020-11-24 14:18:23 -0500546 this->write(" - ");
Brian Osman00185012021-02-04 16:07:11 -0500547 this->writeExpression(*arguments[1], Precedence::kAdditive);
Brian Osman46787d52020-11-24 14:18:23 -0500548 this->write(")");
549 } else {
John Stiles791c27d2020-12-30 14:56:57 -0500550 this->writeSimpleIntrinsic(c);
Brian Osman46787d52020-11-24 14:18:23 -0500551 }
John Stiles496b7d12021-05-06 10:26:45 -0400552 return true;
Brian Osman46787d52020-11-24 14:18:23 -0500553 }
John Stiles496b7d12021-05-06 10:26:45 -0400554 case k_dot_IntrinsicKind: {
Brian Osman46787d52020-11-24 14:18:23 -0500555 if (arguments[0]->type().columns() == 1) {
556 this->write("(");
Brian Osman00185012021-02-04 16:07:11 -0500557 this->writeExpression(*arguments[0], Precedence::kMultiplicative);
Brian Osman46787d52020-11-24 14:18:23 -0500558 this->write(" * ");
Brian Osman00185012021-02-04 16:07:11 -0500559 this->writeExpression(*arguments[1], Precedence::kMultiplicative);
Brian Osman46787d52020-11-24 14:18:23 -0500560 this->write(")");
561 } else {
John Stiles791c27d2020-12-30 14:56:57 -0500562 this->writeSimpleIntrinsic(c);
Brian Osman46787d52020-11-24 14:18:23 -0500563 }
John Stiles496b7d12021-05-06 10:26:45 -0400564 return true;
Brian Osman46787d52020-11-24 14:18:23 -0500565 }
John Stiles496b7d12021-05-06 10:26:45 -0400566 case k_faceforward_IntrinsicKind: {
John Stilesad0571f2020-12-10 18:03:10 -0500567 if (arguments[0]->type().columns() == 1) {
568 // ((((Nref) * (I) < 0) ? 1 : -1) * (N))
569 this->write("((((");
Brian Osman00185012021-02-04 16:07:11 -0500570 this->writeExpression(*arguments[2], Precedence::kSequence);
John Stilesad0571f2020-12-10 18:03:10 -0500571 this->write(") * (");
Brian Osman00185012021-02-04 16:07:11 -0500572 this->writeExpression(*arguments[1], Precedence::kSequence);
John Stilesad0571f2020-12-10 18:03:10 -0500573 this->write(") < 0) ? 1 : -1) * (");
Brian Osman00185012021-02-04 16:07:11 -0500574 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stilesad0571f2020-12-10 18:03:10 -0500575 this->write("))");
576 } else {
John Stiles791c27d2020-12-30 14:56:57 -0500577 this->writeSimpleIntrinsic(c);
John Stilesad0571f2020-12-10 18:03:10 -0500578 }
John Stiles496b7d12021-05-06 10:26:45 -0400579 return true;
John Stilesad0571f2020-12-10 18:03:10 -0500580 }
John Stiles496b7d12021-05-06 10:26:45 -0400581 case k_length_IntrinsicKind: {
Brian Osman46787d52020-11-24 14:18:23 -0500582 this->write(arguments[0]->type().columns() == 1 ? "abs(" : "length(");
Brian Osman00185012021-02-04 16:07:11 -0500583 this->writeExpression(*arguments[0], Precedence::kSequence);
Brian Osman46787d52020-11-24 14:18:23 -0500584 this->write(")");
John Stiles496b7d12021-05-06 10:26:45 -0400585 return true;
Brian Osman46787d52020-11-24 14:18:23 -0500586 }
John Stiles496b7d12021-05-06 10:26:45 -0400587 case k_normalize_IntrinsicKind: {
Brian Osman46787d52020-11-24 14:18:23 -0500588 this->write(arguments[0]->type().columns() == 1 ? "sign(" : "normalize(");
Brian Osman00185012021-02-04 16:07:11 -0500589 this->writeExpression(*arguments[0], Precedence::kSequence);
Brian Osman46787d52020-11-24 14:18:23 -0500590 this->write(")");
John Stiles496b7d12021-05-06 10:26:45 -0400591 return true;
Brian Osman46787d52020-11-24 14:18:23 -0500592 }
John Stiles496b7d12021-05-06 10:26:45 -0400593
594 case k_floatBitsToInt_IntrinsicKind:
595 case k_floatBitsToUint_IntrinsicKind:
596 case k_intBitsToFloat_IntrinsicKind:
597 case k_uintBitsToFloat_IntrinsicKind: {
John Stiles0063a9f2020-12-10 18:01:45 -0500598 this->write(this->getBitcastIntrinsic(c.type()));
599 this->write("(");
Brian Osman00185012021-02-04 16:07:11 -0500600 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stiles0063a9f2020-12-10 18:01:45 -0500601 this->write(")");
John Stiles496b7d12021-05-06 10:26:45 -0400602 return true;
John Stiles0063a9f2020-12-10 18:01:45 -0500603 }
John Stiles496b7d12021-05-06 10:26:45 -0400604 case k_degrees_IntrinsicKind: {
John Stilese2d34f82020-12-10 18:02:02 -0500605 this->write("((");
Brian Osman00185012021-02-04 16:07:11 -0500606 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stilese2d34f82020-12-10 18:02:02 -0500607 this->write(") * 57.2957795)");
John Stiles496b7d12021-05-06 10:26:45 -0400608 return true;
John Stilese2d34f82020-12-10 18:02:02 -0500609 }
John Stiles496b7d12021-05-06 10:26:45 -0400610 case k_radians_IntrinsicKind: {
John Stilese2d34f82020-12-10 18:02:02 -0500611 this->write("((");
Brian Osman00185012021-02-04 16:07:11 -0500612 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stilese2d34f82020-12-10 18:02:02 -0500613 this->write(") * 0.0174532925)");
John Stiles496b7d12021-05-06 10:26:45 -0400614 return true;
John Stilese2d34f82020-12-10 18:02:02 -0500615 }
John Stiles496b7d12021-05-06 10:26:45 -0400616 case k_dFdx_IntrinsicKind: {
John Stilesd7199b22020-12-30 16:22:58 -0500617 this->write("dfdx");
618 this->writeArgumentList(c.arguments());
John Stiles496b7d12021-05-06 10:26:45 -0400619 return true;
John Stilesd7199b22020-12-30 16:22:58 -0500620 }
John Stiles496b7d12021-05-06 10:26:45 -0400621 case k_dFdy_IntrinsicKind: {
Brian Salomond8d85b92021-07-07 09:41:17 -0400622 this->write(fRTFlipName + ".y*dfdy");
John Stilesd7199b22020-12-30 16:22:58 -0500623 this->writeArgumentList(c.arguments());
John Stiles496b7d12021-05-06 10:26:45 -0400624 return true;
John Stilesd7199b22020-12-30 16:22:58 -0500625 }
John Stiles496b7d12021-05-06 10:26:45 -0400626 case k_inverse_IntrinsicKind: {
John Stilesd7199b22020-12-30 16:22:58 -0500627 this->write(this->getInversePolyfill(arguments));
628 this->writeArgumentList(c.arguments());
John Stiles496b7d12021-05-06 10:26:45 -0400629 return true;
John Stilesd7199b22020-12-30 16:22:58 -0500630 }
John Stiles496b7d12021-05-06 10:26:45 -0400631 case k_inversesqrt_IntrinsicKind: {
John Stilesd7199b22020-12-30 16:22:58 -0500632 this->write("rsqrt");
633 this->writeArgumentList(c.arguments());
John Stiles496b7d12021-05-06 10:26:45 -0400634 return true;
John Stilesd7199b22020-12-30 16:22:58 -0500635 }
John Stiles496b7d12021-05-06 10:26:45 -0400636 case k_atan_IntrinsicKind: {
John Stilesd7199b22020-12-30 16:22:58 -0500637 this->write(c.arguments().size() == 2 ? "atan2" : "atan");
638 this->writeArgumentList(c.arguments());
John Stiles496b7d12021-05-06 10:26:45 -0400639 return true;
John Stilesd7199b22020-12-30 16:22:58 -0500640 }
John Stiles496b7d12021-05-06 10:26:45 -0400641 case k_reflect_IntrinsicKind: {
John Stiles791c27d2020-12-30 14:56:57 -0500642 if (arguments[0]->type().columns() == 1) {
643 // We need to synthesize `I - 2 * N * I * N`.
644 String tmpI = this->getTempVariable(arguments[0]->type());
645 String tmpN = this->getTempVariable(arguments[1]->type());
646
647 // (_skTempI = ...
648 this->write("(" + tmpI + " = ");
Brian Osman00185012021-02-04 16:07:11 -0500649 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stiles791c27d2020-12-30 14:56:57 -0500650
651 // , _skTempN = ...
652 this->write(", " + tmpN + " = ");
Brian Osman00185012021-02-04 16:07:11 -0500653 this->writeExpression(*arguments[1], Precedence::kSequence);
John Stiles791c27d2020-12-30 14:56:57 -0500654
655 // , _skTempI - 2 * _skTempN * _skTempI * _skTempN)
656 this->write(", " + tmpI + " - 2 * " + tmpN + " * " + tmpI + " * " + tmpN + ")");
657 } else {
658 this->writeSimpleIntrinsic(c);
659 }
John Stiles496b7d12021-05-06 10:26:45 -0400660 return true;
John Stiles791c27d2020-12-30 14:56:57 -0500661 }
John Stiles496b7d12021-05-06 10:26:45 -0400662 case k_refract_IntrinsicKind: {
John Stiles4b783d62020-12-30 14:58:07 -0500663 if (arguments[0]->type().columns() == 1) {
664 // Metal does implement refract for vectors; rather than reimplementing refract from
665 // scratch, we can replace the call with `refract(float2(I,0), float2(N,0), eta).x`.
666 this->write("(refract(float2(");
Brian Osman00185012021-02-04 16:07:11 -0500667 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stiles4b783d62020-12-30 14:58:07 -0500668 this->write(", 0), float2(");
Brian Osman00185012021-02-04 16:07:11 -0500669 this->writeExpression(*arguments[1], Precedence::kSequence);
John Stiles4b783d62020-12-30 14:58:07 -0500670 this->write(", 0), ");
Brian Osman00185012021-02-04 16:07:11 -0500671 this->writeExpression(*arguments[2], Precedence::kSequence);
John Stiles4b783d62020-12-30 14:58:07 -0500672 this->write(").x)");
673 } else {
674 this->writeSimpleIntrinsic(c);
675 }
John Stiles496b7d12021-05-06 10:26:45 -0400676 return true;
John Stiles4b783d62020-12-30 14:58:07 -0500677 }
John Stiles496b7d12021-05-06 10:26:45 -0400678 case k_roundEven_IntrinsicKind: {
John Stiles23456532020-12-30 18:12:48 -0500679 this->write("rint");
680 this->writeArgumentList(c.arguments());
John Stiles496b7d12021-05-06 10:26:45 -0400681 return true;
John Stiles23456532020-12-30 18:12:48 -0500682 }
John Stiles496b7d12021-05-06 10:26:45 -0400683 case k_bitCount_IntrinsicKind: {
John Stilese7dc7cb2020-12-22 15:37:14 -0500684 this->write("popcount(");
Brian Osman00185012021-02-04 16:07:11 -0500685 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stilese7dc7cb2020-12-22 15:37:14 -0500686 this->write(")");
John Stiles496b7d12021-05-06 10:26:45 -0400687 return true;
John Stilese7dc7cb2020-12-22 15:37:14 -0500688 }
John Stiles496b7d12021-05-06 10:26:45 -0400689 case k_findLSB_IntrinsicKind: {
John Stiles86424eb2020-12-11 11:17:14 -0500690 // Create a temp variable to store the expression, to avoid double-evaluating it.
691 String skTemp = this->getTempVariable(arguments[0]->type());
692 String exprType = this->typeName(arguments[0]->type());
693
694 // ctz returns numbits(type) on zero inputs; GLSL documents it as generating -1 instead.
695 // Use select to detect zero inputs and force a -1 result.
696
697 // (_skTemp1 = (.....), select(ctz(_skTemp1), int4(-1), _skTemp1 == int4(0)))
698 this->write("(");
699 this->write(skTemp);
700 this->write(" = (");
Brian Osman00185012021-02-04 16:07:11 -0500701 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stiles86424eb2020-12-11 11:17:14 -0500702 this->write("), select(ctz(");
703 this->write(skTemp);
704 this->write("), ");
705 this->write(exprType);
706 this->write("(-1), ");
707 this->write(skTemp);
708 this->write(" == ");
709 this->write(exprType);
710 this->write("(0)))");
John Stiles496b7d12021-05-06 10:26:45 -0400711 return true;
John Stiles86424eb2020-12-11 11:17:14 -0500712 }
John Stiles496b7d12021-05-06 10:26:45 -0400713 case k_findMSB_IntrinsicKind: {
John Stiles9685e522020-12-14 11:52:14 -0500714 // Create a temp variable to store the expression, to avoid double-evaluating it.
715 String skTemp1 = this->getTempVariable(arguments[0]->type());
716 String exprType = this->typeName(arguments[0]->type());
717
718 // GLSL findMSB is actually quite different from Metal's clz:
719 // - For signed negative numbers, it returns the first zero bit, not the first one bit!
720 // - For an empty input (0/~0 depending on sign), findMSB gives -1; clz is numbits(type)
721
722 // (_skTemp1 = (.....),
723 this->write("(");
724 this->write(skTemp1);
725 this->write(" = (");
Brian Osman00185012021-02-04 16:07:11 -0500726 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stiles9685e522020-12-14 11:52:14 -0500727 this->write("), ");
728
729 // Signed input types might be negative; we need another helper variable to negate the
730 // input (since we can only find one bits, not zero bits).
731 String skTemp2;
732 if (arguments[0]->type().isSigned()) {
733 // ... _skTemp2 = (select(_skTemp1, ~_skTemp1, _skTemp1 < 0)),
734 skTemp2 = this->getTempVariable(arguments[0]->type());
735 this->write(skTemp2);
736 this->write(" = (select(");
737 this->write(skTemp1);
738 this->write(", ~");
739 this->write(skTemp1);
740 this->write(", ");
741 this->write(skTemp1);
742 this->write(" < 0)), ");
743 } else {
744 skTemp2 = skTemp1;
745 }
746
747 // ... select(int4(clz(_skTemp2)), int4(-1), _skTemp2 == int4(0)))
748 this->write("select(");
749 this->write(this->typeName(c.type()));
750 this->write("(clz(");
751 this->write(skTemp2);
752 this->write(")), ");
753 this->write(this->typeName(c.type()));
754 this->write("(-1), ");
755 this->write(skTemp2);
756 this->write(" == ");
757 this->write(exprType);
758 this->write("(0)))");
John Stiles496b7d12021-05-06 10:26:45 -0400759 return true;
John Stiles9685e522020-12-14 11:52:14 -0500760 }
John Stiles496b7d12021-05-06 10:26:45 -0400761 case k_matrixCompMult_IntrinsicKind: {
John Stilesd7199b22020-12-30 16:22:58 -0500762 this->writeMatrixCompMult();
763 this->writeSimpleIntrinsic(c);
John Stiles496b7d12021-05-06 10:26:45 -0400764 return true;
John Stilesd7199b22020-12-30 16:22:58 -0500765 }
John Stilescc2d9cc2021-07-09 17:38:41 -0400766 case k_mix_IntrinsicKind: {
767 SkASSERT(c.arguments().size() == 3);
768 if (arguments[2]->type().componentType().isBoolean()) {
769 // The Boolean forms of GLSL mix() use the select() intrinsic in Metal.
770 this->write("select");
771 this->writeArgumentList(c.arguments());
772 return true;
773 }
774 // The basic form of mix() is supported by Metal as-is.
775 this->writeSimpleIntrinsic(c);
776 return true;
777 }
John Stiles496b7d12021-05-06 10:26:45 -0400778 case k_equal_IntrinsicKind:
779 case k_greaterThan_IntrinsicKind:
780 case k_greaterThanEqual_IntrinsicKind:
781 case k_lessThan_IntrinsicKind:
782 case k_lessThanEqual_IntrinsicKind:
783 case k_notEqual_IntrinsicKind: {
John Stilesd7199b22020-12-30 16:22:58 -0500784 this->write("(");
Brian Osman00185012021-02-04 16:07:11 -0500785 this->writeExpression(*c.arguments()[0], Precedence::kRelational);
John Stilesd7199b22020-12-30 16:22:58 -0500786 switch (kind) {
John Stiles496b7d12021-05-06 10:26:45 -0400787 case k_equal_IntrinsicKind:
John Stilesd7199b22020-12-30 16:22:58 -0500788 this->write(" == ");
789 break;
John Stiles496b7d12021-05-06 10:26:45 -0400790 case k_notEqual_IntrinsicKind:
John Stilesd7199b22020-12-30 16:22:58 -0500791 this->write(" != ");
792 break;
John Stiles496b7d12021-05-06 10:26:45 -0400793 case k_lessThan_IntrinsicKind:
John Stilesd7199b22020-12-30 16:22:58 -0500794 this->write(" < ");
795 break;
John Stiles496b7d12021-05-06 10:26:45 -0400796 case k_lessThanEqual_IntrinsicKind:
John Stilesd7199b22020-12-30 16:22:58 -0500797 this->write(" <= ");
798 break;
John Stiles496b7d12021-05-06 10:26:45 -0400799 case k_greaterThan_IntrinsicKind:
John Stilesd7199b22020-12-30 16:22:58 -0500800 this->write(" > ");
801 break;
John Stiles496b7d12021-05-06 10:26:45 -0400802 case k_greaterThanEqual_IntrinsicKind:
John Stilesd7199b22020-12-30 16:22:58 -0500803 this->write(" >= ");
804 break;
805 default:
John Stilesf57207b2021-02-02 17:50:34 -0500806 SK_ABORT("unsupported comparison intrinsic kind");
John Stilesd7199b22020-12-30 16:22:58 -0500807 }
Brian Osman00185012021-02-04 16:07:11 -0500808 this->writeExpression(*c.arguments()[1], Precedence::kRelational);
John Stilesd7199b22020-12-30 16:22:58 -0500809 this->write(")");
John Stiles496b7d12021-05-06 10:26:45 -0400810 return true;
John Stilesd7199b22020-12-30 16:22:58 -0500811 }
Timothy Liang6403b0e2018-05-17 10:40:04 -0400812 default:
John Stiles496b7d12021-05-06 10:26:45 -0400813 return false;
Timothy Liang6403b0e2018-05-17 10:40:04 -0400814 }
815}
816
John Stilesfcf8cb22020-08-06 14:29:22 -0400817// Assembles a matrix of type floatRxC by resizing another matrix named `x0`.
818// Cells that don't exist in the source matrix will be populated with identity-matrix values.
819void MetalCodeGenerator::assembleMatrixFromMatrix(const Type& sourceMatrix, int rows, int columns) {
820 SkASSERT(rows <= 4);
821 SkASSERT(columns <= 4);
822
823 const char* columnSeparator = "";
824 for (int c = 0; c < columns; ++c) {
825 fExtraFunctions.printf("%sfloat%d(", columnSeparator, rows);
826 columnSeparator = "), ";
827
828 // Determine how many values to take from the source matrix for this row.
829 int swizzleLength = 0;
830 if (c < sourceMatrix.columns()) {
831 swizzleLength = std::min<>(rows, sourceMatrix.rows());
832 }
833
834 // Emit all the values from the source matrix row.
835 bool firstItem;
836 switch (swizzleLength) {
837 case 0: firstItem = true; break;
838 case 1: firstItem = false; fExtraFunctions.printf("x0[%d].x", c); break;
839 case 2: firstItem = false; fExtraFunctions.printf("x0[%d].xy", c); break;
840 case 3: firstItem = false; fExtraFunctions.printf("x0[%d].xyz", c); break;
841 case 4: firstItem = false; fExtraFunctions.printf("x0[%d].xyzw", c); break;
842 default: SkUNREACHABLE;
843 }
844
845 // Emit the placeholder identity-matrix cells.
846 for (int r = swizzleLength; r < rows; ++r) {
847 fExtraFunctions.printf("%s%s", firstItem ? "" : ", ", (r == c) ? "1.0" : "0.0");
848 firstItem = false;
849 }
850 }
851
852 fExtraFunctions.writeText(")");
853}
854
John Stiles1f7300b2021-07-08 15:40:38 -0400855// Assembles a matrix of type floatCxR by concatenating an arbitrary mix of values, named `x0`,
856// `x1`, etc. An error is written if the expression list don't contain exactly C*R scalars.
John Stiles5abb9e12021-04-06 13:47:19 -0400857void MetalCodeGenerator::assembleMatrixFromExpressions(const AnyConstructor& ctor,
John Stiles1f7300b2021-07-08 15:40:38 -0400858 int columns, int rows) {
John Stilesfcf8cb22020-08-06 14:29:22 -0400859 size_t argIndex = 0;
860 int argPosition = 0;
John Stiles5abb9e12021-04-06 13:47:19 -0400861 auto args = ctor.argumentSpan();
John Stilesfcf8cb22020-08-06 14:29:22 -0400862
John Stiles1f7300b2021-07-08 15:40:38 -0400863 const char* rowSeparator = "";
864 for (int r = 0; r < rows; ++r) {
865 fExtraFunctions.printf("%sfloat%d(", rowSeparator, rows);
866 rowSeparator = "), ";
John Stilesfcf8cb22020-08-06 14:29:22 -0400867
John Stiles1f7300b2021-07-08 15:40:38 -0400868 const char* columnSeparator = "";
869 for (int c = 0; c < columns; ++c) {
870 fExtraFunctions.writeText(columnSeparator);
871 columnSeparator = ", ";
John Stilesfcf8cb22020-08-06 14:29:22 -0400872
873 if (argIndex < args.size()) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400874 const Type& argType = args[argIndex]->type();
Ethan Nicholase6592142020-09-08 10:22:09 -0400875 switch (argType.typeKind()) {
876 case Type::TypeKind::kScalar: {
John Stilesfcf8cb22020-08-06 14:29:22 -0400877 fExtraFunctions.printf("x%zu", argIndex);
878 break;
879 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400880 case Type::TypeKind::kVector: {
John Stilesfcf8cb22020-08-06 14:29:22 -0400881 fExtraFunctions.printf("x%zu[%d]", argIndex, argPosition);
882 break;
883 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400884 case Type::TypeKind::kMatrix: {
John Stilesfcf8cb22020-08-06 14:29:22 -0400885 fExtraFunctions.printf("x%zu[%d][%d]", argIndex,
886 argPosition / argType.rows(),
887 argPosition % argType.rows());
888 break;
889 }
890 default: {
891 SkDEBUGFAIL("incorrect type of argument for matrix constructor");
892 fExtraFunctions.writeText("<error>");
893 break;
894 }
895 }
896
897 ++argPosition;
898 if (argPosition >= argType.columns() * argType.rows()) {
899 ++argIndex;
900 argPosition = 0;
901 }
902 } else {
903 SkDEBUGFAIL("not enough arguments for matrix constructor");
904 fExtraFunctions.writeText("<error>");
905 }
906 }
907 }
908
909 if (argPosition != 0 || argIndex != args.size()) {
910 SkDEBUGFAIL("incorrect number of arguments for matrix constructor");
911 fExtraFunctions.writeText(", <error>");
912 }
913
914 fExtraFunctions.writeText(")");
915}
916
John Stiles1bdafbf2020-05-28 12:17:20 -0400917// Generates a constructor for 'matrix' which reorganizes the input arguments into the proper shape.
918// Keeps track of previously generated constructors so that we won't generate more than one
919// constructor for any given permutation of input argument types. Returns the name of the
920// generated constructor method.
John Stiles5abb9e12021-04-06 13:47:19 -0400921String MetalCodeGenerator::getMatrixConstructHelper(const AnyConstructor& c) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400922 const Type& matrix = c.type();
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500923 int columns = matrix.columns();
924 int rows = matrix.rows();
John Stiles5abb9e12021-04-06 13:47:19 -0400925 auto args = c.argumentSpan();
John Stiles1bdafbf2020-05-28 12:17:20 -0400926
927 // Create the helper-method name and use it as our lookup key.
928 String name;
929 name.appendf("float%dx%d_from", columns, rows);
930 for (const std::unique_ptr<Expression>& expr : args) {
John Stiles36129132020-12-29 12:28:04 -0500931 name.appendf("_%s", this->typeName(expr->type()).c_str());
John Stiles1bdafbf2020-05-28 12:17:20 -0400932 }
933
934 // If a helper-method has already been synthesized, we don't need to synthesize it again.
935 auto [iter, newlyCreated] = fHelpers.insert(name);
936 if (!newlyCreated) {
937 return name;
938 }
939
940 // Unlike GLSL, Metal requires that matrices are initialized with exactly R vectors of C
941 // components apiece. (In Metal 2.0, you can also supply R*C scalars, but you still cannot
942 // supply a mixture of scalars and vectors.)
943 fExtraFunctions.printf("float%dx%d %s(", columns, rows, name.c_str());
944
945 size_t argIndex = 0;
946 const char* argSeparator = "";
John Stilesfcf8cb22020-08-06 14:29:22 -0400947 for (const std::unique_ptr<Expression>& expr : args) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400948 fExtraFunctions.printf("%s%s x%zu", argSeparator,
John Stiles36129132020-12-29 12:28:04 -0500949 this->typeName(expr->type()).c_str(), argIndex++);
John Stiles1bdafbf2020-05-28 12:17:20 -0400950 argSeparator = ", ";
951 }
952
953 fExtraFunctions.printf(") {\n return float%dx%d(", columns, rows);
954
John Stiles9aeed132020-11-24 17:36:06 -0500955 if (args.size() == 1 && args.front()->type().isMatrix()) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400956 this->assembleMatrixFromMatrix(args.front()->type(), rows, columns);
John Stilesfcf8cb22020-08-06 14:29:22 -0400957 } else {
John Stiles1f7300b2021-07-08 15:40:38 -0400958 this->assembleMatrixFromExpressions(c, columns, rows);
John Stiles1bdafbf2020-05-28 12:17:20 -0400959 }
960
John Stilesfcf8cb22020-08-06 14:29:22 -0400961 fExtraFunctions.writeText(");\n}\n");
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500962 return name;
963}
964
965bool MetalCodeGenerator::canCoerce(const Type& t1, const Type& t2) {
966 if (t1.columns() != t2.columns() || t1.rows() != t2.rows()) {
967 return false;
968 }
969 if (t1.columns() > 1) {
970 return this->canCoerce(t1.componentType(), t2.componentType());
971 }
Ethan Nicholase1f55022019-02-05 17:17:40 -0500972 return t1.isFloat() && t2.isFloat();
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500973}
974
John Stiles8cad6372021-04-07 12:31:13 -0400975bool MetalCodeGenerator::matrixConstructHelperIsNeeded(const ConstructorCompound& c) {
John Stiles2bec8ab2021-04-06 18:40:04 -0400976 SkASSERT(c.type().isMatrix());
John Stiles1bdafbf2020-05-28 12:17:20 -0400977
978 // GLSL is fairly free-form about inputs to its matrix constructors, but Metal is not; it
979 // expects exactly R vectors of C components apiece. (Metal 2.0 also allows a list of R*C
980 // scalars.) Some cases are simple to translate and so we handle those inline--e.g. a list of
981 // scalars can be constructed trivially. In more complex cases, we generate a helper function
982 // that converts our inputs into a properly-shaped matrix.
983 // A matrix construct helper method is always used if any input argument is a matrix.
984 // Helper methods are also necessary when any argument would span multiple rows. For instance:
985 //
986 // float2 x = (1, 2);
987 // float3x2(x, 3, 4, 5, 6) = | 1 3 5 | = no helper needed; conversion can be done inline
988 // | 2 4 6 |
989 //
990 // float2 x = (2, 3);
991 // float3x2(1, x, 4, 5, 6) = | 1 3 5 | = x spans multiple rows; a helper method will be used
992 // | 2 4 6 |
993 //
994 // float4 x = (1, 2, 3, 4);
995 // float2x2(x) = | 1 3 | = x spans multiple rows; a helper method will be used
996 // | 2 4 |
997 //
998
999 int position = 0;
Ethan Nicholasf70f0442020-09-29 12:41:35 -04001000 for (const std::unique_ptr<Expression>& expr : c.arguments()) {
John Stiles1bdafbf2020-05-28 12:17:20 -04001001 // If an input argument is a matrix, we need a helper function.
John Stiles9aeed132020-11-24 17:36:06 -05001002 if (expr->type().isMatrix()) {
John Stiles1bdafbf2020-05-28 12:17:20 -04001003 return true;
1004 }
Ethan Nicholas30d30222020-09-11 12:27:26 -04001005 position += expr->type().columns();
1006 if (position > c.type().rows()) {
John Stiles1bdafbf2020-05-28 12:17:20 -04001007 // An input argument would span multiple rows; a helper function is required.
1008 return true;
1009 }
Ethan Nicholas30d30222020-09-11 12:27:26 -04001010 if (position == c.type().rows()) {
John Stiles1bdafbf2020-05-28 12:17:20 -04001011 // We've advanced to the end of a row. Wrap to the start of the next row.
1012 position = 0;
1013 }
1014 }
1015
1016 return false;
1017}
1018
John Stiles5abb9e12021-04-06 13:47:19 -04001019void MetalCodeGenerator::writeConstructorMatrixResize(const ConstructorMatrixResize& c,
1020 Precedence parentPrecedence) {
1021 // Matrix-resize via casting doesn't natively exist in Metal at all, so we always need to use a
1022 // matrix-construct helper here.
1023 this->write(this->getMatrixConstructHelper(c));
1024 this->write("(");
1025 this->writeExpression(*c.argument(), Precedence::kSequence);
1026 this->write(")");
1027}
1028
John Stiles8cad6372021-04-07 12:31:13 -04001029void MetalCodeGenerator::writeConstructorCompound(const ConstructorCompound& c,
1030 Precedence parentPrecedence) {
John Stiles6de2e1d2021-07-09 12:41:55 -04001031 if (c.type().isVector()) {
1032 this->writeConstructorCompoundVector(c, parentPrecedence);
1033 } else if (c.type().isMatrix()) {
John Stiles8cad6372021-04-07 12:31:13 -04001034 this->writeConstructorCompoundMatrix(c, parentPrecedence);
John Stiles2bec8ab2021-04-06 18:40:04 -04001035 } else {
John Stiles6de2e1d2021-07-09 12:41:55 -04001036 fErrors.error(c.fOffset, "unsupported compound constructor");
John Stiles2bec8ab2021-04-06 18:40:04 -04001037 }
1038}
John Stiles7384b372021-04-01 13:48:15 -04001039
John Stiles6de2e1d2021-07-09 12:41:55 -04001040void MetalCodeGenerator::writeVectorFromMat2x2ConstructorHelper() {
1041 static constexpr char kCode[] =
1042R"(float4 float4_from_float2x2(float2x2 x) {
1043 return float4(x[0].xy, x[1].xy);
1044}
1045)";
1046
1047 String name = "matrixCompMult";
1048 if (fHelpers.find("float4_from_float2x2") == fHelpers.end()) {
1049 fHelpers.insert("float4_from_float2x2");
1050 fExtraFunctions.writeText(kCode);
1051 }
1052}
1053
1054void MetalCodeGenerator::writeConstructorCompoundVector(const ConstructorCompound& c,
1055 Precedence parentPrecedence) {
1056 SkASSERT(c.type().isVector());
1057
1058 // Metal supports constructing vectors from a mix of scalars and vectors, but not matrices.
1059 // GLSL supports vec4(mat2x2), so we detect that case here and emit a helper function.
1060 if (c.type().columns() == 4 && c.argumentSpan().size() == 1) {
1061 const Expression& expr = *c.argumentSpan().front();
1062 if (expr.type().isMatrix()) {
1063 SkASSERT(expr.type().rows() == 2);
1064 SkASSERT(expr.type().columns() == 2);
1065 this->writeVectorFromMat2x2ConstructorHelper();
1066 this->write("float4_from_float2x2(");
1067 this->writeExpression(expr, Precedence::kSequence);
1068 this->write(")");
1069 return;
1070 }
1071 }
1072
1073 this->writeAnyConstructor(c, "(", ")", parentPrecedence);
1074}
1075
John Stiles8cad6372021-04-07 12:31:13 -04001076void MetalCodeGenerator::writeConstructorCompoundMatrix(const ConstructorCompound& c,
1077 Precedence parentPrecedence) {
John Stiles6de2e1d2021-07-09 12:41:55 -04001078 SkASSERT(c.type().isMatrix());
1079
John Stiles1bdafbf2020-05-28 12:17:20 -04001080 // Emit and invoke a matrix-constructor helper method if one is necessary.
1081 if (this->matrixConstructHelperIsNeeded(c)) {
1082 this->write(this->getMatrixConstructHelper(c));
John Stiles1fa15b12020-05-28 17:36:54 +00001083 this->write("(");
1084 const char* separator = "";
Ethan Nicholasf70f0442020-09-29 12:41:35 -04001085 for (const std::unique_ptr<Expression>& expr : c.arguments()) {
John Stiles1fa15b12020-05-28 17:36:54 +00001086 this->write(separator);
1087 separator = ", ";
Brian Osman00185012021-02-04 16:07:11 -05001088 this->writeExpression(*expr, Precedence::kSequence);
John Stilesdaa573e2020-05-28 12:17:20 -04001089 }
John Stiles1fa15b12020-05-28 17:36:54 +00001090 this->write(")");
John Stiles1bdafbf2020-05-28 12:17:20 -04001091 return;
John Stilesdaa573e2020-05-28 12:17:20 -04001092 }
John Stiles1bdafbf2020-05-28 12:17:20 -04001093
John Stiles2bec8ab2021-04-06 18:40:04 -04001094 // Metal doesn't allow creating matrices by passing in scalars and vectors in a jumble; it
1095 // requires your scalars to be grouped up into columns. Because `matrixConstructHelperIsNeeded`
1096 // returned false, we know that none of our scalars/vectors "wrap" across across a column, so we
1097 // can group our inputs up and synthesize a constructor for each column.
1098 const Type& matrixType = c.type();
1099 const Type& columnType = matrixType.componentType().toCompound(
1100 fContext, /*columns=*/matrixType.rows(), /*rows=*/1);
1101
1102 this->writeType(matrixType);
John Stiles7384b372021-04-01 13:48:15 -04001103 this->write("(");
John Stiles1bdafbf2020-05-28 12:17:20 -04001104 const char* separator = "";
1105 int scalarCount = 0;
Ethan Nicholasf70f0442020-09-29 12:41:35 -04001106 for (const std::unique_ptr<Expression>& arg : c.arguments()) {
John Stiles1bdafbf2020-05-28 12:17:20 -04001107 this->write(separator);
1108 separator = ", ";
John Stiles2bec8ab2021-04-06 18:40:04 -04001109 if (arg->type().columns() < matrixType.rows()) {
1110 // Write a `floatN(` constructor to group scalars and smaller vectors together.
John Stiles1bdafbf2020-05-28 12:17:20 -04001111 if (!scalarCount) {
John Stiles2bec8ab2021-04-06 18:40:04 -04001112 this->writeType(columnType);
John Stiles1bdafbf2020-05-28 12:17:20 -04001113 this->write("(");
1114 }
John Stiles2bec8ab2021-04-06 18:40:04 -04001115 scalarCount += arg->type().columns();
John Stiles1bdafbf2020-05-28 12:17:20 -04001116 }
Brian Osman00185012021-02-04 16:07:11 -05001117 this->writeExpression(*arg, Precedence::kSequence);
John Stiles2bec8ab2021-04-06 18:40:04 -04001118 if (scalarCount && scalarCount == matrixType.rows()) {
1119 // Close our `floatN(...` constructor block from above.
John Stiles1bdafbf2020-05-28 12:17:20 -04001120 this->write(")");
1121 scalarCount = 0;
1122 }
1123 }
John Stiles7384b372021-04-01 13:48:15 -04001124 this->write(")");
Ethan Nicholascc305772017-10-13 16:17:45 -04001125}
1126
John Stilesb14a8192021-04-05 11:40:46 -04001127void MetalCodeGenerator::writeAnyConstructor(const AnyConstructor& c,
1128 const char* leftBracket,
1129 const char* rightBracket,
1130 Precedence parentPrecedence) {
John Stilese1182782021-03-30 22:09:37 -04001131 this->writeType(c.type());
John Stilesb14a8192021-04-05 11:40:46 -04001132 this->write(leftBracket);
John Stiles7384b372021-04-01 13:48:15 -04001133 const char* separator = "";
John Stilesb14a8192021-04-05 11:40:46 -04001134 for (const std::unique_ptr<Expression>& arg : c.argumentSpan()) {
John Stiles7384b372021-04-01 13:48:15 -04001135 this->write(separator);
1136 separator = ", ";
1137 this->writeExpression(*arg, Precedence::kSequence);
1138 }
John Stilesb14a8192021-04-05 11:40:46 -04001139 this->write(rightBracket);
John Stiles7384b372021-04-01 13:48:15 -04001140}
1141
John Stilesb14a8192021-04-05 11:40:46 -04001142void MetalCodeGenerator::writeCastConstructor(const AnyConstructor& c,
1143 const char* leftBracket,
1144 const char* rightBracket,
1145 Precedence parentPrecedence) {
1146 // If the type is coercible, emit it directly without the cast.
1147 auto args = c.argumentSpan();
1148 if (args.size() == 1) {
1149 if (this->canCoerce(c.type(), args.front()->type())) {
1150 this->writeExpression(*args.front(), parentPrecedence);
1151 return;
1152 }
John Stilesfd7252f2021-04-04 22:24:40 -04001153 }
1154
John Stilesb14a8192021-04-05 11:40:46 -04001155 return this->writeAnyConstructor(c, leftBracket, rightBracket, parentPrecedence);
John Stilesfd7252f2021-04-04 22:24:40 -04001156}
1157
Ethan Nicholascc305772017-10-13 16:17:45 -04001158void MetalCodeGenerator::writeFragCoord() {
Brian Salomond8d85b92021-07-07 09:41:17 -04001159 SkASSERT(fRTFlipName.length());
1160 this->write("float4(_fragCoord.x, ");
1161 this->write(fRTFlipName.c_str());
1162 this->write(".x + ");
1163 this->write(fRTFlipName.c_str());
1164 this->write(".y * _fragCoord.y, 0.0, _fragCoord.w)");
Ethan Nicholascc305772017-10-13 16:17:45 -04001165}
1166
1167void MetalCodeGenerator::writeVariableReference(const VariableReference& ref) {
John Stiles06b84ef2020-12-09 12:35:48 -05001168 // When assembling out-param helper functions, we copy variables into local clones with matching
John Stilesf7410bd2021-01-19 13:07:55 -05001169 // names. We never want to prepend "_in." or "_globals." when writing these variables since
John Stiles06b84ef2020-12-09 12:35:48 -05001170 // we're actually targeting the clones.
1171 if (fIgnoreVariableReferenceModifiers) {
1172 this->writeName(ref.variable()->name());
1173 return;
1174 }
1175
Ethan Nicholas78686922020-10-08 06:46:27 -04001176 switch (ref.variable()->modifiers().fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001177 case SK_FRAGCOLOR_BUILTIN:
John Stilesf7410bd2021-01-19 13:07:55 -05001178 this->write("_out.sk_FragColor");
Ethan Nicholascc305772017-10-13 16:17:45 -04001179 break;
Timothy Liang6403b0e2018-05-17 10:40:04 -04001180 case SK_FRAGCOORD_BUILTIN:
1181 this->writeFragCoord();
1182 break;
Timothy Liangdc89f192018-06-13 09:20:31 -04001183 case SK_VERTEXID_BUILTIN:
1184 this->write("sk_VertexID");
1185 break;
1186 case SK_INSTANCEID_BUILTIN:
1187 this->write("sk_InstanceID");
1188 break;
Timothy Liang7b8875d2018-08-10 09:42:31 -04001189 case SK_CLOCKWISE_BUILTIN:
1190 // We'd set the front facing winding in the MTLRenderCommandEncoder to be counter
Brian Salomonf4ba4ec2020-03-19 15:54:28 -04001191 // clockwise to match Skia convention.
Brian Salomond8d85b92021-07-07 09:41:17 -04001192 this->write("(" + fRTFlipName + ".y < 0 ? _frontFacing : !_frontFacing)");
Timothy Liang7b8875d2018-08-10 09:42:31 -04001193 break;
Ethan Nicholascc305772017-10-13 16:17:45 -04001194 default:
Ethan Nicholas78686922020-10-08 06:46:27 -04001195 const Variable& var = *ref.variable();
Ethan Nicholas453f67f2020-10-09 10:43:45 -04001196 if (var.storage() == Variable::Storage::kGlobal) {
Ethan Nicholas78686922020-10-08 06:46:27 -04001197 if (var.modifiers().fFlags & Modifiers::kIn_Flag) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001198 this->write("_in.");
Ethan Nicholas78686922020-10-08 06:46:27 -04001199 } else if (var.modifiers().fFlags & Modifiers::kOut_Flag) {
John Stilesf7410bd2021-01-19 13:07:55 -05001200 this->write("_out.");
Ethan Nicholas78686922020-10-08 06:46:27 -04001201 } else if (var.modifiers().fFlags & Modifiers::kUniform_Flag &&
1202 var.type().typeKind() != Type::TypeKind::kSampler) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001203 this->write("_uniforms.");
1204 } else {
John Stilesf7410bd2021-01-19 13:07:55 -05001205 this->write("_globals.");
Ethan Nicholascc305772017-10-13 16:17:45 -04001206 }
1207 }
Ethan Nicholas78686922020-10-08 06:46:27 -04001208 this->writeName(var.name());
Ethan Nicholascc305772017-10-13 16:17:45 -04001209 }
1210}
1211
1212void MetalCodeGenerator::writeIndexExpression(const IndexExpression& expr) {
Brian Osman00185012021-02-04 16:07:11 -05001213 this->writeExpression(*expr.base(), Precedence::kPostfix);
Ethan Nicholascc305772017-10-13 16:17:45 -04001214 this->write("[");
Brian Osman00185012021-02-04 16:07:11 -05001215 this->writeExpression(*expr.index(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001216 this->write("]");
1217}
1218
1219void MetalCodeGenerator::writeFieldAccess(const FieldAccess& f) {
Ethan Nicholas7a95b202020-10-09 11:55:40 -04001220 const Type::Field* field = &f.base()->type().fields()[f.fieldIndex()];
1221 if (FieldAccess::OwnerKind::kDefault == f.ownerKind()) {
Brian Osman00185012021-02-04 16:07:11 -05001222 this->writeExpression(*f.base(), Precedence::kPostfix);
Ethan Nicholascc305772017-10-13 16:17:45 -04001223 this->write(".");
1224 }
Timothy Liang7d637782018-06-05 09:58:07 -04001225 switch (field->fModifiers.fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001226 case SK_POSITION_BUILTIN:
John Stilesf7410bd2021-01-19 13:07:55 -05001227 this->write("_out.sk_Position");
Ethan Nicholascc305772017-10-13 16:17:45 -04001228 break;
1229 default:
Timothy Liang7d637782018-06-05 09:58:07 -04001230 if (field->fName == "sk_PointSize") {
John Stilesf7410bd2021-01-19 13:07:55 -05001231 this->write("_out.sk_PointSize");
Timothy Liang7d637782018-06-05 09:58:07 -04001232 } else {
Ethan Nicholas7a95b202020-10-09 11:55:40 -04001233 if (FieldAccess::OwnerKind::kAnonymousInterfaceBlock == f.ownerKind()) {
John Stilesf7410bd2021-01-19 13:07:55 -05001234 this->write("_globals.");
Timothy Liang7d637782018-06-05 09:58:07 -04001235 this->write(fInterfaceBlockNameMap[fInterfaceBlockMap[field]]);
1236 this->write("->");
1237 }
Timothy Liang651286f2018-06-07 09:55:33 -04001238 this->writeName(field->fName);
Timothy Lianga06f2152018-05-24 15:33:31 -04001239 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001240 }
1241}
1242
1243void MetalCodeGenerator::writeSwizzle(const Swizzle& swizzle) {
Brian Osman00185012021-02-04 16:07:11 -05001244 this->writeExpression(*swizzle.base(), Precedence::kPostfix);
Ethan Nicholascc305772017-10-13 16:17:45 -04001245 this->write(".");
Ethan Nicholas6b4d5812020-10-12 16:11:51 -04001246 for (int c : swizzle.components()) {
Brian Osman25647672020-09-15 15:16:56 -04001247 SkASSERT(c >= 0 && c <= 3);
1248 this->write(&("x\0y\0z\0w\0"[c * 2]));
Ethan Nicholascc305772017-10-13 16:17:45 -04001249 }
1250}
1251
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001252void MetalCodeGenerator::writeMatrixTimesEqualHelper(const Type& left, const Type& right,
1253 const Type& result) {
John Stilesc985e142021-05-13 14:01:48 -04001254 SkASSERT(left.isMatrix());
1255 SkASSERT(right.isMatrix());
1256 SkASSERT(result.isMatrix());
1257 SkASSERT(left.rows() == right.rows());
1258 SkASSERT(left.columns() == right.columns());
1259 SkASSERT(left.rows() == result.rows());
1260 SkASSERT(left.columns() == result.columns());
1261
1262 String key = "Matrix *= " + this->typeName(left) + ":" + this->typeName(right);
John Stiles56233d12021-02-03 13:03:29 -05001263
1264 auto [iter, wasInserted] = fHelpers.insert(key);
1265 if (wasInserted) {
John Stiles368db7c2020-12-29 11:20:08 -05001266 fExtraFunctions.printf("thread %s& operator*=(thread %s& left, thread const %s& right) {\n"
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001267 " left = left * right;\n"
1268 " return left;\n"
John Stiles368db7c2020-12-29 11:20:08 -05001269 "}\n",
1270 this->typeName(result).c_str(), this->typeName(left).c_str(),
1271 this->typeName(right).c_str());
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001272 }
1273}
1274
John Stiles39346472021-04-29 14:39:35 -04001275void MetalCodeGenerator::writeMatrixEqualityHelpers(const Type& left, const Type& right) {
1276 SkASSERT(left.isMatrix());
1277 SkASSERT(right.isMatrix());
1278 SkASSERT(left.rows() == right.rows());
1279 SkASSERT(left.columns() == right.columns());
John Stiles01cdf012021-02-10 09:53:41 -05001280
John Stilesc985e142021-05-13 14:01:48 -04001281 String key = "Matrix == " + this->typeName(left) + ":" + this->typeName(right);
John Stiles01cdf012021-02-10 09:53:41 -05001282
1283 auto [iter, wasInserted] = fHelpers.insert(key);
1284 if (wasInserted) {
1285 fExtraFunctions.printf(
1286 "thread bool operator==(const %s left, const %s right) {\n"
John Stiles39346472021-04-29 14:39:35 -04001287 " return ",
John Stiles01cdf012021-02-10 09:53:41 -05001288 this->typeName(left).c_str(), this->typeName(right).c_str());
1289
John Stiles39346472021-04-29 14:39:35 -04001290 const char* separator = "";
John Stiles01cdf012021-02-10 09:53:41 -05001291 for (int index=0; index<left.columns(); ++index) {
John Stiles39346472021-04-29 14:39:35 -04001292 fExtraFunctions.printf("%sall(left[%d] == right[%d])", separator, index, index);
1293 separator = " &&\n ";
John Stiles01cdf012021-02-10 09:53:41 -05001294 }
John Stiles39346472021-04-29 14:39:35 -04001295
1296 fExtraFunctions.printf(
1297 ";\n"
1298 "}\n"
1299 "thread bool operator!=(const %s left, const %s right) {\n"
1300 " return !(left == right);\n"
1301 "}\n",
1302 this->typeName(left).c_str(), this->typeName(right).c_str());
John Stiles01cdf012021-02-10 09:53:41 -05001303 }
1304}
1305
John Stilesc985e142021-05-13 14:01:48 -04001306void MetalCodeGenerator::writeMatrixDivisionHelpers(const Type& type) {
1307 SkASSERT(type.isMatrix());
1308
1309 String key = "Matrix / " + this->typeName(type);
1310
1311 auto [iter, wasInserted] = fHelpers.insert(key);
1312 if (wasInserted) {
1313 String typeName = this->typeName(type);
1314
1315 fExtraFunctions.printf(
1316 "thread %s operator/(const %s left, const %s right) {\n"
1317 " return %s(",
1318 typeName.c_str(), typeName.c_str(), typeName.c_str(), typeName.c_str());
1319
1320 const char* separator = "";
1321 for (int index=0; index<type.columns(); ++index) {
1322 fExtraFunctions.printf("%sleft[%d] / right[%d]", separator, index, index);
1323 separator = ", ";
1324 }
1325
1326 fExtraFunctions.printf(");\n"
1327 "}\n"
1328 "thread %s& operator/=(thread %s& left, thread const %s& right) {\n"
1329 " left = left / right;\n"
1330 " return left;\n"
1331 "}\n",
1332 typeName.c_str(), typeName.c_str(), typeName.c_str());
1333 }
1334}
1335
John Stiles39346472021-04-29 14:39:35 -04001336void MetalCodeGenerator::writeArrayEqualityHelpers(const Type& type) {
1337 SkASSERT(type.isArray());
John Stiles01cdf012021-02-10 09:53:41 -05001338
John Stiles39346472021-04-29 14:39:35 -04001339 // If the array's component type needs a helper as well, we need to emit that one first.
1340 this->writeEqualityHelpers(type.componentType(), type.componentType());
1341
1342 auto [iter, wasInserted] = fHelpers.insert("ArrayEquality []");
1343 if (wasInserted) {
1344 fExtraFunctions.writeText(R"(
John Stilese3ae9682021-08-05 10:35:01 -04001345template <typename T1, typename T2, size_t N>
1346bool operator==(thread const array<T1, N>& left, thread const array<T2, N>& right) {
John Stiles39346472021-04-29 14:39:35 -04001347 for (size_t index = 0; index < N; ++index) {
John Stilesef9a1b62021-08-10 14:31:12 +00001348 if (!(left[index] == right[index])) {
John Stiles39346472021-04-29 14:39:35 -04001349 return false;
1350 }
1351 }
1352 return true;
1353}
1354
John Stilese3ae9682021-08-05 10:35:01 -04001355template <typename T1, typename T2, size_t N>
1356bool operator!=(thread const array<T1, N>& left, thread const array<T2, N>& right) {
John Stiles39346472021-04-29 14:39:35 -04001357 return !(left == right);
1358}
1359)");
1360 }
1361}
1362
1363void MetalCodeGenerator::writeStructEqualityHelpers(const Type& type) {
1364 SkASSERT(type.isStruct());
1365 String key = "StructEquality " + this->typeName(type);
John Stiles01cdf012021-02-10 09:53:41 -05001366
1367 auto [iter, wasInserted] = fHelpers.insert(key);
1368 if (wasInserted) {
John Stiles39346472021-04-29 14:39:35 -04001369 // If one of the struct's fields needs a helper as well, we need to emit that one first.
1370 for (const Type::Field& field : type.fields()) {
1371 this->writeEqualityHelpers(*field.fType, *field.fType);
John Stiles830c69c2021-04-28 17:16:16 -04001372 }
John Stiles39346472021-04-29 14:39:35 -04001373
1374 // Write operator== and operator!= for this struct, since those are assumed to exist in SkSL
1375 // and GLSL but do not exist by default in Metal.
1376 fExtraFunctions.printf(
1377 "thread bool operator==(thread const %s& left, thread const %s& right) {\n"
1378 " return ",
1379 this->typeName(type).c_str(),
1380 this->typeName(type).c_str());
1381
1382 const char* separator = "";
1383 for (const Type::Field& field : type.fields()) {
1384 fExtraFunctions.printf("%s(left.%.*s == right.%.*s)",
1385 separator,
1386 (int)field.fName.size(), field.fName.data(),
1387 (int)field.fName.size(), field.fName.data());
1388 separator = " &&\n ";
1389 }
1390 fExtraFunctions.printf(
1391 ";\n"
1392 "}\n"
1393 "thread bool operator!=(thread const %s& left, thread const %s& right) {\n"
1394 " return !(left == right);\n"
1395 "}\n",
1396 this->typeName(type).c_str(),
1397 this->typeName(type).c_str());
1398 }
1399}
1400
1401void MetalCodeGenerator::writeEqualityHelpers(const Type& leftType, const Type& rightType) {
1402 if (leftType.isArray() && rightType.isArray()) {
1403 this->writeArrayEqualityHelpers(leftType);
1404 return;
1405 }
1406 if (leftType.isStruct() && rightType.isStruct()) {
1407 this->writeStructEqualityHelpers(leftType);
1408 return;
1409 }
1410 if (leftType.isMatrix() && rightType.isMatrix()) {
1411 this->writeMatrixEqualityHelpers(leftType, rightType);
1412 return;
John Stiles01cdf012021-02-10 09:53:41 -05001413 }
1414}
1415
John Stiles6b131292021-05-12 17:12:21 -04001416void MetalCodeGenerator::writeNumberAsMatrix(const Expression& expr, const Type& matrixType) {
1417 SkASSERT(expr.type().isNumber());
1418 SkASSERT(matrixType.isMatrix());
1419
1420 // Componentwise multiply the scalar against a matrix of the desired size which contains all 1s.
1421 this->write("(");
1422 this->writeType(matrixType);
1423 this->write("(");
1424
1425 const char* separator = "";
1426 for (int index = matrixType.slotCount(); index--;) {
1427 this->write(separator);
1428 this->write("1.0");
1429 separator = ", ";
1430 }
1431
1432 this->write(") * ");
1433 this->writeExpression(expr, Precedence::kMultiplicative);
1434 this->write(")");
1435}
1436
Ethan Nicholascc305772017-10-13 16:17:45 -04001437void MetalCodeGenerator::writeBinaryExpression(const BinaryExpression& b,
1438 Precedence parentPrecedence) {
John Stiles2d4f9592020-10-30 10:29:12 -04001439 const Expression& left = *b.left();
1440 const Expression& right = *b.right();
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001441 const Type& leftType = left.type();
1442 const Type& rightType = right.type();
John Stiles45990502021-02-16 10:55:27 -05001443 Operator op = b.getOperator();
1444 Precedence precedence = op.getBinaryPrecedence();
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001445 bool needParens = precedence >= parentPrecedence;
John Stiles45990502021-02-16 10:55:27 -05001446 switch (op.kind()) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001447 case Token::Kind::TK_EQEQ:
John Stiles39346472021-04-29 14:39:35 -04001448 this->writeEqualityHelpers(leftType, rightType);
John Stiles9aeed132020-11-24 17:36:06 -05001449 if (leftType.isVector()) {
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001450 this->write("all");
1451 needParens = true;
1452 }
1453 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001454 case Token::Kind::TK_NEQ:
John Stiles39346472021-04-29 14:39:35 -04001455 this->writeEqualityHelpers(leftType, rightType);
John Stiles9aeed132020-11-24 17:36:06 -05001456 if (leftType.isVector()) {
Jim Van Verth36477b42019-04-11 14:57:30 -04001457 this->write("any");
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001458 needParens = true;
1459 }
1460 break;
1461 default:
1462 break;
1463 }
John Stiles39346472021-04-29 14:39:35 -04001464 if (leftType.isMatrix() && rightType.isMatrix() && op.kind() == Token::Kind::TK_STAREQ) {
1465 this->writeMatrixTimesEqualHelper(leftType, rightType, b.type());
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001466 }
John Stilesc985e142021-05-13 14:01:48 -04001467 if (op.removeAssignment().kind() == Token::Kind::TK_SLASH &&
1468 ((leftType.isMatrix() && rightType.isMatrix()) ||
1469 (leftType.isScalar() && rightType.isMatrix()) ||
1470 (leftType.isMatrix() && rightType.isScalar()))) {
1471 this->writeMatrixDivisionHelpers(leftType.isMatrix() ? leftType : rightType);
1472 }
1473 if (needParens) {
1474 this->write("(");
1475 }
John Stiles6011bbc2021-05-19 22:56:18 -04001476 bool needMatrixSplatOnScalar = rightType.isMatrix() && leftType.isNumber() &&
1477 op.isValidForMatrixOrVector() &&
John Stiles6b131292021-05-12 17:12:21 -04001478 op.removeAssignment().kind() != Token::Kind::TK_STAR;
1479 if (needMatrixSplatOnScalar) {
1480 this->writeNumberAsMatrix(left, rightType);
1481 } else {
1482 this->writeExpression(left, precedence);
1483 }
John Stiles45990502021-02-16 10:55:27 -05001484 if (op.kind() != Token::Kind::TK_EQ && op.isAssignment() &&
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001485 left.kind() == Expression::Kind::kSwizzle && !left.hasSideEffects()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001486 // This doesn't compile in Metal:
1487 // float4 x = float4(1);
1488 // x.xy *= float2x2(...);
1489 // with the error message "non-const reference cannot bind to vector element",
1490 // but switching it to x.xy = x.xy * float2x2(...) fixes it. We perform this tranformation
1491 // as long as the LHS has no side effects, and hope for the best otherwise.
1492 this->write(" = ");
Brian Osman00185012021-02-04 16:07:11 -05001493 this->writeExpression(left, Precedence::kAssignment);
Ethan Nicholascc305772017-10-13 16:17:45 -04001494 this->write(" ");
John Stiles7cbe66b2021-05-12 17:01:23 -04001495 this->write(OperatorName(op.removeAssignment()));
Ethan Nicholascc305772017-10-13 16:17:45 -04001496 this->write(" ");
1497 } else {
John Stilesd6449e92020-11-30 09:13:23 -05001498 this->write(String(" ") + OperatorName(op) + " ");
Ethan Nicholascc305772017-10-13 16:17:45 -04001499 }
John Stiles6b131292021-05-12 17:12:21 -04001500
John Stiles6011bbc2021-05-19 22:56:18 -04001501 needMatrixSplatOnScalar = leftType.isMatrix() && rightType.isNumber() &&
1502 op.isValidForMatrixOrVector() &&
John Stiles6b131292021-05-12 17:12:21 -04001503 op.removeAssignment().kind() != Token::Kind::TK_STAR;
1504 if (needMatrixSplatOnScalar) {
1505 this->writeNumberAsMatrix(right, leftType);
1506 } else {
1507 this->writeExpression(right, precedence);
1508 }
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001509 if (needParens) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001510 this->write(")");
1511 }
1512}
1513
1514void MetalCodeGenerator::writeTernaryExpression(const TernaryExpression& t,
1515 Precedence parentPrecedence) {
Brian Osman00185012021-02-04 16:07:11 -05001516 if (Precedence::kTernary >= parentPrecedence) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001517 this->write("(");
1518 }
Brian Osman00185012021-02-04 16:07:11 -05001519 this->writeExpression(*t.test(), Precedence::kTernary);
Ethan Nicholascc305772017-10-13 16:17:45 -04001520 this->write(" ? ");
Brian Osman00185012021-02-04 16:07:11 -05001521 this->writeExpression(*t.ifTrue(), Precedence::kTernary);
Ethan Nicholascc305772017-10-13 16:17:45 -04001522 this->write(" : ");
Brian Osman00185012021-02-04 16:07:11 -05001523 this->writeExpression(*t.ifFalse(), Precedence::kTernary);
1524 if (Precedence::kTernary >= parentPrecedence) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001525 this->write(")");
1526 }
1527}
1528
1529void MetalCodeGenerator::writePrefixExpression(const PrefixExpression& p,
1530 Precedence parentPrecedence) {
Brian Osman00185012021-02-04 16:07:11 -05001531 if (Precedence::kPrefix >= parentPrecedence) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001532 this->write("(");
1533 }
John Stilesd6449e92020-11-30 09:13:23 -05001534 this->write(OperatorName(p.getOperator()));
Brian Osman00185012021-02-04 16:07:11 -05001535 this->writeExpression(*p.operand(), Precedence::kPrefix);
1536 if (Precedence::kPrefix >= parentPrecedence) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001537 this->write(")");
1538 }
1539}
1540
1541void MetalCodeGenerator::writePostfixExpression(const PostfixExpression& p,
1542 Precedence parentPrecedence) {
Brian Osman00185012021-02-04 16:07:11 -05001543 if (Precedence::kPostfix >= parentPrecedence) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001544 this->write("(");
1545 }
Brian Osman00185012021-02-04 16:07:11 -05001546 this->writeExpression(*p.operand(), Precedence::kPostfix);
John Stilesd6449e92020-11-30 09:13:23 -05001547 this->write(OperatorName(p.getOperator()));
Brian Osman00185012021-02-04 16:07:11 -05001548 if (Precedence::kPostfix >= parentPrecedence) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001549 this->write(")");
1550 }
1551}
1552
1553void MetalCodeGenerator::writeBoolLiteral(const BoolLiteral& b) {
Ethan Nicholas59d660c2020-09-28 09:18:15 -04001554 this->write(b.value() ? "true" : "false");
Ethan Nicholascc305772017-10-13 16:17:45 -04001555}
1556
1557void MetalCodeGenerator::writeIntLiteral(const IntLiteral& i) {
John Stiles12739df2020-12-29 09:47:20 -05001558 const Type& type = i.type();
John Stiles54e7c052021-01-11 14:22:36 -05001559 if (type == *fContext.fTypes.fUInt) {
Ethan Nicholase96cdd12020-09-28 16:27:18 -04001560 this->write(to_string(i.value() & 0xffffffff) + "u");
John Stiles54e7c052021-01-11 14:22:36 -05001561 } else if (type == *fContext.fTypes.fUShort) {
John Stiles12739df2020-12-29 09:47:20 -05001562 this->write(to_string(i.value() & 0xffff) + "u");
Ethan Nicholascc305772017-10-13 16:17:45 -04001563 } else {
John Stiles12739df2020-12-29 09:47:20 -05001564 this->write(to_string(i.value()));
Ethan Nicholascc305772017-10-13 16:17:45 -04001565 }
1566}
1567
1568void MetalCodeGenerator::writeFloatLiteral(const FloatLiteral& f) {
Ethan Nicholasa3f22f12020-10-01 12:13:17 -04001569 this->write(to_string(f.value()));
Ethan Nicholascc305772017-10-13 16:17:45 -04001570}
1571
1572void MetalCodeGenerator::writeSetting(const Setting& s) {
John Stilesf57207b2021-02-02 17:50:34 -05001573 SK_ABORT("internal error; setting was not folded to a constant during compilation\n");
Ethan Nicholascc305772017-10-13 16:17:45 -04001574}
1575
John Stiles06b84ef2020-12-09 12:35:48 -05001576void MetalCodeGenerator::writeFunctionRequirementArgs(const FunctionDeclaration& f,
1577 const char*& separator) {
1578 Requirements requirements = this->requirements(f);
1579 if (requirements & kInputs_Requirement) {
1580 this->write(separator);
1581 this->write("_in");
1582 separator = ", ";
1583 }
1584 if (requirements & kOutputs_Requirement) {
1585 this->write(separator);
1586 this->write("_out");
1587 separator = ", ";
1588 }
1589 if (requirements & kUniforms_Requirement) {
1590 this->write(separator);
1591 this->write("_uniforms");
1592 separator = ", ";
1593 }
1594 if (requirements & kGlobals_Requirement) {
1595 this->write(separator);
John Stilesf7410bd2021-01-19 13:07:55 -05001596 this->write("_globals");
John Stiles06b84ef2020-12-09 12:35:48 -05001597 separator = ", ";
1598 }
1599 if (requirements & kFragCoord_Requirement) {
1600 this->write(separator);
1601 this->write("_fragCoord");
1602 separator = ", ";
1603 }
1604}
1605
1606void MetalCodeGenerator::writeFunctionRequirementParams(const FunctionDeclaration& f,
1607 const char*& separator) {
1608 Requirements requirements = this->requirements(f);
1609 if (requirements & kInputs_Requirement) {
1610 this->write(separator);
1611 this->write("Inputs _in");
1612 separator = ", ";
1613 }
1614 if (requirements & kOutputs_Requirement) {
1615 this->write(separator);
John Stilesf7410bd2021-01-19 13:07:55 -05001616 this->write("thread Outputs& _out");
John Stiles06b84ef2020-12-09 12:35:48 -05001617 separator = ", ";
1618 }
1619 if (requirements & kUniforms_Requirement) {
1620 this->write(separator);
1621 this->write("Uniforms _uniforms");
1622 separator = ", ";
1623 }
1624 if (requirements & kGlobals_Requirement) {
1625 this->write(separator);
John Stilesf7410bd2021-01-19 13:07:55 -05001626 this->write("thread Globals& _globals");
John Stiles06b84ef2020-12-09 12:35:48 -05001627 separator = ", ";
1628 }
1629 if (requirements & kFragCoord_Requirement) {
1630 this->write(separator);
1631 this->write("float4 _fragCoord");
1632 separator = ", ";
1633 }
1634}
1635
John Stilesda5cdf62021-01-28 11:47:29 -05001636int MetalCodeGenerator::getUniformBinding(const Modifiers& m) {
1637 return (m.fLayout.fBinding >= 0) ? m.fLayout.fBinding
John Stiles270cec22021-02-17 12:59:36 -05001638 : fProgram.fConfig->fSettings.fDefaultUniformBinding;
John Stilesda5cdf62021-01-28 11:47:29 -05001639}
1640
1641int MetalCodeGenerator::getUniformSet(const Modifiers& m) {
1642 return (m.fLayout.fSet >= 0) ? m.fLayout.fSet
John Stiles270cec22021-02-17 12:59:36 -05001643 : fProgram.fConfig->fSettings.fDefaultUniformSet;
John Stilesda5cdf62021-01-28 11:47:29 -05001644}
1645
John Stiles569249b2020-11-03 12:18:22 -05001646bool MetalCodeGenerator::writeFunctionDeclaration(const FunctionDeclaration& f) {
Brian Salomond8d85b92021-07-07 09:41:17 -04001647 fRTFlipName = fProgram.fInputs.fUseFlipRTUniform
1648 ? "_globals._anonInterface0->" SKSL_RTFLIP_NAME
1649 : "";
Ethan Nicholascc305772017-10-13 16:17:45 -04001650 const char* separator = "";
John Stilese8da4d22021-03-24 09:19:45 -04001651 if (f.isMain()) {
John Stiles270cec22021-02-17 12:59:36 -05001652 switch (fProgram.fConfig->fKind) {
John Stilesdbd4e6f2021-02-16 13:29:15 -05001653 case ProgramKind::kFragment:
Timothy Liangb8eeb802018-07-23 16:46:16 -04001654 this->write("fragment Outputs fragmentMain");
Ethan Nicholascc305772017-10-13 16:17:45 -04001655 break;
John Stilesdbd4e6f2021-02-16 13:29:15 -05001656 case ProgramKind::kVertex:
Timothy Liangb8eeb802018-07-23 16:46:16 -04001657 this->write("vertex Outputs vertexMain");
Ethan Nicholascc305772017-10-13 16:17:45 -04001658 break;
1659 default:
John Stiles3fabfc02020-09-25 15:51:28 -04001660 fErrors.error(-1, "unsupported kind of program");
John Stiles569249b2020-11-03 12:18:22 -05001661 return false;
Ethan Nicholascc305772017-10-13 16:17:45 -04001662 }
1663 this->write("(Inputs _in [[stage_in]]");
1664 if (-1 != fUniformBuffer) {
1665 this->write(", constant Uniforms& _uniforms [[buffer(" +
1666 to_string(fUniformBuffer) + ")]]");
1667 }
Brian Osman133724c2020-10-28 14:14:39 -04001668 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04001669 if (e->is<GlobalVarDeclaration>()) {
1670 const GlobalVarDeclaration& decls = e->as<GlobalVarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001671 const VarDeclaration& var = decls.declaration()->as<VarDeclaration>();
1672 if (var.var().type().typeKind() == Type::TypeKind::kSampler) {
1673 if (var.var().modifiers().fLayout.fBinding < 0) {
Brian Osmanc0213602020-10-06 14:43:32 -04001674 fErrors.error(decls.fOffset,
John Stilesb41d5bb2021-01-26 16:28:12 -05001675 "Metal samplers must have 'layout(binding=...)'");
John Stiles569249b2020-11-03 12:18:22 -05001676 return false;
Timothy Liangee84fe12018-05-18 14:38:19 -04001677 }
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001678 if (var.var().type().dimensions() != SpvDim2D) {
John Stiles569249b2020-11-03 12:18:22 -05001679 // Not yet implemented--Skia currently only uses 2D textures.
Brian Osmanc0213602020-10-06 14:43:32 -04001680 fErrors.error(decls.fOffset, "Unsupported texture dimensions");
John Stiles569249b2020-11-03 12:18:22 -05001681 return false;
Brian Osmanc0213602020-10-06 14:43:32 -04001682 }
1683 this->write(", texture2d<float> ");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001684 this->writeName(var.var().name());
Brian Osmanc0213602020-10-06 14:43:32 -04001685 this->write("[[texture(");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001686 this->write(to_string(var.var().modifiers().fLayout.fBinding));
Brian Osmanc0213602020-10-06 14:43:32 -04001687 this->write(")]]");
1688 this->write(", sampler ");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001689 this->writeName(var.var().name());
Brian Osmanc0213602020-10-06 14:43:32 -04001690 this->write(SAMPLER_SUFFIX);
1691 this->write("[[sampler(");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001692 this->write(to_string(var.var().modifiers().fLayout.fBinding));
Brian Osmanc0213602020-10-06 14:43:32 -04001693 this->write(")]]");
Timothy Liang6403b0e2018-05-17 10:40:04 -04001694 }
Brian Osman1179fcf2020-10-08 16:04:40 -04001695 } else if (e->is<InterfaceBlock>()) {
1696 const InterfaceBlock& intf = e->as<InterfaceBlock>();
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001697 if (intf.typeName() == "sk_PerVertex") {
Timothy Lianga06f2152018-05-24 15:33:31 -04001698 continue;
1699 }
1700 this->write(", constant ");
John Stilesb4418502021-02-04 10:57:08 -05001701 this->writeType(intf.variable().type());
Timothy Lianga06f2152018-05-24 15:33:31 -04001702 this->write("& " );
1703 this->write(fInterfaceBlockNameMap[&intf]);
1704 this->write(" [[buffer(");
John Stilesda5cdf62021-01-28 11:47:29 -05001705 this->write(to_string(this->getUniformBinding(intf.variable().modifiers())));
Timothy Lianga06f2152018-05-24 15:33:31 -04001706 this->write(")]]");
Timothy Liang6403b0e2018-05-17 10:40:04 -04001707 }
1708 }
John Stiles270cec22021-02-17 12:59:36 -05001709 if (fProgram.fConfig->fKind == ProgramKind::kFragment) {
Brian Salomond8d85b92021-07-07 09:41:17 -04001710 if (fProgram.fInputs.fUseFlipRTUniform && fInterfaceBlockNameMap.empty()) {
Timothy Liang5422f9a2018-08-10 10:57:55 -04001711 this->write(", constant sksl_synthetic_uniforms& _anonInterface0 [[buffer(1)]]");
Brian Salomond8d85b92021-07-07 09:41:17 -04001712 fRTFlipName = "_anonInterface0." SKSL_RTFLIP_NAME;
Timothy Liang5422f9a2018-08-10 10:57:55 -04001713 }
Timothy Liang7b8875d2018-08-10 09:42:31 -04001714 this->write(", bool _frontFacing [[front_facing]]");
Timothy Liang7d637782018-06-05 09:58:07 -04001715 this->write(", float4 _fragCoord [[position]]");
John Stiles270cec22021-02-17 12:59:36 -05001716 } else if (fProgram.fConfig->fKind == ProgramKind::kVertex) {
Timothy Liangdc89f192018-06-13 09:20:31 -04001717 this->write(", uint sk_VertexID [[vertex_id]], uint sk_InstanceID [[instance_id]]");
Timothy Liang7d637782018-06-05 09:58:07 -04001718 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001719 separator = ", ";
1720 } else {
John Stilesb4418502021-02-04 10:57:08 -05001721 this->writeType(f.returnType());
Timothy Liang651286f2018-06-07 09:55:33 -04001722 this->write(" ");
John Stilese1068342021-03-22 11:57:41 -04001723 this->writeName(f.mangledName());
Timothy Liang651286f2018-06-07 09:55:33 -04001724 this->write("(");
John Stiles06b84ef2020-12-09 12:35:48 -05001725 this->writeFunctionRequirementParams(f, separator);
Ethan Nicholascc305772017-10-13 16:17:45 -04001726 }
John Stiles569249b2020-11-03 12:18:22 -05001727 for (const auto& param : f.parameters()) {
Brian Osman716aeb92021-04-21 13:20:00 -04001728 if (f.isMain() && param->modifiers().fLayout.fBuiltin != -1) {
1729 continue;
1730 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001731 this->write(separator);
1732 separator = ", ";
Brian Osman58134e12021-05-13 14:51:07 -04001733 this->writeModifiers(param->modifiers());
Ethan Nicholas30d30222020-09-11 12:27:26 -04001734 const Type* type = &param->type();
John Stilesb4418502021-02-04 10:57:08 -05001735 this->writeType(*type);
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001736 if (param->modifiers().fFlags & Modifiers::kOut_Flag) {
John Stilesf2bd5012020-12-04 11:58:26 -05001737 this->write("&");
Ethan Nicholascc305772017-10-13 16:17:45 -04001738 }
Timothy Liang651286f2018-06-07 09:55:33 -04001739 this->write(" ");
Ethan Nicholase2c49992020-10-05 11:49:11 -04001740 this->writeName(param->name());
Ethan Nicholascc305772017-10-13 16:17:45 -04001741 }
John Stiles569249b2020-11-03 12:18:22 -05001742 this->write(")");
1743 return true;
1744}
Ethan Nicholascc305772017-10-13 16:17:45 -04001745
John Stiles569249b2020-11-03 12:18:22 -05001746void MetalCodeGenerator::writeFunctionPrototype(const FunctionPrototype& f) {
1747 this->writeFunctionDeclaration(f.declaration());
1748 this->writeLine(";");
1749}
1750
John Stiles986c7fb2020-12-01 14:44:56 -05001751static bool is_block_ending_with_return(const Statement* stmt) {
1752 // This function detects (potentially nested) blocks that end in a return statement.
1753 if (!stmt->is<Block>()) {
1754 return false;
1755 }
1756 const StatementArray& block = stmt->as<Block>().children();
1757 for (int index = block.count(); index--; ) {
John Stiles628777c2021-08-04 22:07:41 -04001758 stmt = block[index].get();
1759 if (stmt->is<ReturnStatement>()) {
John Stiles986c7fb2020-12-01 14:44:56 -05001760 return true;
1761 }
John Stiles628777c2021-08-04 22:07:41 -04001762 if (stmt->is<Block>()) {
1763 return is_block_ending_with_return(stmt);
John Stiles986c7fb2020-12-01 14:44:56 -05001764 }
John Stiles628777c2021-08-04 22:07:41 -04001765 if (!stmt->is<Nop>()) {
John Stiles986c7fb2020-12-01 14:44:56 -05001766 break;
1767 }
1768 }
1769 return false;
1770}
1771
John Stiles569249b2020-11-03 12:18:22 -05001772void MetalCodeGenerator::writeFunction(const FunctionDefinition& f) {
John Stiles270cec22021-02-17 12:59:36 -05001773 SkASSERT(!fProgram.fConfig->fSettings.fFragColorIsInOut);
Brian Salomondc092132018-04-04 10:14:16 -04001774
John Stiles569249b2020-11-03 12:18:22 -05001775 if (!this->writeFunctionDeclaration(f.declaration())) {
1776 return;
1777 }
1778
John Stiles986c7fb2020-12-01 14:44:56 -05001779 fCurrentFunction = &f.declaration();
1780 SkScopeExit clearCurrentFunction([&] { fCurrentFunction = nullptr; });
1781
John Stiles569249b2020-11-03 12:18:22 -05001782 this->writeLine(" {");
1783
John Stilese8da4d22021-03-24 09:19:45 -04001784 if (f.declaration().isMain()) {
John Stilescdcdb042020-07-06 09:03:51 -04001785 this->writeGlobalInit();
John Stilesf7410bd2021-01-19 13:07:55 -05001786 this->writeLine(" Outputs _out;");
John Stiles37279172021-01-21 22:24:28 -05001787 this->writeLine(" (void)_out;");
Ethan Nicholascc305772017-10-13 16:17:45 -04001788 }
John Stilesc67b3622020-05-28 17:53:13 -04001789
John Stiles95680232021-04-22 15:05:20 -04001790 fFunctionHeader.clear();
Ethan Nicholascc305772017-10-13 16:17:45 -04001791 StringStream buffer;
John Stiles44532372020-12-07 12:33:55 -05001792 {
1793 AutoOutputStream outputToBuffer(this, &buffer);
1794 fIndentation++;
1795 for (const std::unique_ptr<Statement>& stmt : f.body()->as<Block>().children()) {
1796 if (!stmt->isEmpty()) {
1797 this->writeStatement(*stmt);
John Stilese8b5a732021-03-12 13:25:52 -05001798 this->finishLine();
John Stiles44532372020-12-07 12:33:55 -05001799 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001800 }
John Stilese8da4d22021-03-24 09:19:45 -04001801 if (f.declaration().isMain()) {
John Stiles44532372020-12-07 12:33:55 -05001802 // If the main function doesn't end with a return, we need to synthesize one here.
1803 if (!is_block_ending_with_return(f.body().get())) {
1804 this->writeReturnStatementFromMain();
John Stilese8b5a732021-03-12 13:25:52 -05001805 this->finishLine();
John Stiles44532372020-12-07 12:33:55 -05001806 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001807 }
John Stiles44532372020-12-07 12:33:55 -05001808 fIndentation--;
1809 this->writeLine("}");
Ethan Nicholascc305772017-10-13 16:17:45 -04001810 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001811 this->write(fFunctionHeader);
1812 this->write(buffer.str());
1813}
1814
Brian Osman58134e12021-05-13 14:51:07 -04001815void MetalCodeGenerator::writeModifiers(const Modifiers& modifiers) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001816 if (modifiers.fFlags & Modifiers::kOut_Flag) {
1817 this->write("thread ");
1818 }
1819 if (modifiers.fFlags & Modifiers::kConst_Flag) {
John Stiles0bd55782021-02-09 18:29:40 -05001820 this->write("const ");
Ethan Nicholascc305772017-10-13 16:17:45 -04001821 }
1822}
1823
1824void MetalCodeGenerator::writeInterfaceBlock(const InterfaceBlock& intf) {
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001825 if ("sk_PerVertex" == intf.typeName()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001826 return;
1827 }
Brian Osman58134e12021-05-13 14:51:07 -04001828 this->writeModifiers(intf.variable().modifiers());
Timothy Liangdc89f192018-06-13 09:20:31 -04001829 this->write("struct ");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001830 this->writeLine(intf.typeName() + " {");
1831 const Type* structType = &intf.variable().type();
John Stilesbb43b7e2020-12-03 17:36:32 -05001832 if (structType->isArray()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001833 structType = &structType->componentType();
1834 }
Timothy Liangdc89f192018-06-13 09:20:31 -04001835 fIndentation++;
John Stiles3dba3ee2020-12-02 23:35:49 -05001836 this->writeFields(structType->fields(), structType->fOffset, &intf);
Brian Salomond8d85b92021-07-07 09:41:17 -04001837 if (fProgram.fInputs.fUseFlipRTUniform) {
1838 this->writeLine("float2 " SKSL_RTFLIP_NAME ";");
Ethan Nicholascc305772017-10-13 16:17:45 -04001839 }
1840 fIndentation--;
1841 this->write("}");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001842 if (intf.instanceName().size()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001843 this->write(" ");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001844 this->write(intf.instanceName());
John Stilesd39aec02020-12-03 10:42:26 -05001845 if (intf.arraySize() > 0) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001846 this->write("[");
John Stilesd39aec02020-12-03 10:42:26 -05001847 this->write(to_string(intf.arraySize()));
Ethan Nicholascc305772017-10-13 16:17:45 -04001848 this->write("]");
John Stilesd39aec02020-12-03 10:42:26 -05001849 } else if (intf.arraySize() == Type::kUnsizedArray){
1850 this->write("[]");
Ethan Nicholascc305772017-10-13 16:17:45 -04001851 }
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001852 fInterfaceBlockNameMap[&intf] = intf.instanceName();
Timothy Lianga06f2152018-05-24 15:33:31 -04001853 } else {
Ethan Nicholas3533ff12021-08-02 12:53:29 -04001854 fInterfaceBlockNameMap[&intf] = *fProgram.fSymbols->takeOwnershipOfString("_anonInterface" +
1855 to_string(fAnonInterfaceCount++));
Ethan Nicholascc305772017-10-13 16:17:45 -04001856 }
1857 this->writeLine(";");
1858}
1859
Timothy Liangdc89f192018-06-13 09:20:31 -04001860void MetalCodeGenerator::writeFields(const std::vector<Type::Field>& fields, int parentOffset,
1861 const InterfaceBlock* parentIntf) {
Timothy Liang609fbe32018-08-10 16:40:49 -04001862 MemoryLayout memoryLayout(MemoryLayout::kMetal_Standard);
Timothy Liangdc89f192018-06-13 09:20:31 -04001863 int currentOffset = 0;
John Stiles39346472021-04-29 14:39:35 -04001864 for (const Type::Field& field : fields) {
Timothy Liangdc89f192018-06-13 09:20:31 -04001865 int fieldOffset = field.fModifiers.fLayout.fOffset;
1866 const Type* fieldType = field.fType;
John Stiles21f5f452020-11-30 09:57:59 -05001867 if (!MemoryLayout::LayoutIsSupported(*fieldType)) {
John Stiles0023c0c2020-11-16 13:32:18 -05001868 fErrors.error(parentOffset, "type '" + fieldType->name() + "' is not permitted here");
1869 return;
1870 }
Timothy Liangdc89f192018-06-13 09:20:31 -04001871 if (fieldOffset != -1) {
1872 if (currentOffset > fieldOffset) {
1873 fErrors.error(parentOffset,
John Stilesd7199b22020-12-30 16:22:58 -05001874 "offset of field '" + field.fName + "' must be at least " +
1875 to_string((int) currentOffset));
Brian Osman8609a242020-09-08 14:01:49 -04001876 return;
Timothy Liangdc89f192018-06-13 09:20:31 -04001877 } else if (currentOffset < fieldOffset) {
1878 this->write("char pad");
1879 this->write(to_string(fPaddingCount++));
1880 this->write("[");
1881 this->write(to_string(fieldOffset - currentOffset));
1882 this->writeLine("];");
1883 currentOffset = fieldOffset;
1884 }
1885 int alignment = memoryLayout.alignment(*fieldType);
1886 if (fieldOffset % alignment) {
1887 fErrors.error(parentOffset,
1888 "offset of field '" + field.fName + "' must be a multiple of " +
1889 to_string((int) alignment));
Brian Osman8609a242020-09-08 14:01:49 -04001890 return;
Timothy Liangdc89f192018-06-13 09:20:31 -04001891 }
1892 }
Brian Osman8609a242020-09-08 14:01:49 -04001893 size_t fieldSize = memoryLayout.size(*fieldType);
1894 if (fieldSize > static_cast<size_t>(std::numeric_limits<int>::max() - currentOffset)) {
1895 fErrors.error(parentOffset, "field offset overflow");
1896 return;
1897 }
1898 currentOffset += fieldSize;
Brian Osman58134e12021-05-13 14:51:07 -04001899 this->writeModifiers(field.fModifiers);
John Stilesb4418502021-02-04 10:57:08 -05001900 this->writeType(*fieldType);
Timothy Liangdc89f192018-06-13 09:20:31 -04001901 this->write(" ");
1902 this->writeName(field.fName);
Timothy Liangdc89f192018-06-13 09:20:31 -04001903 this->writeLine(";");
1904 if (parentIntf) {
1905 fInterfaceBlockMap[&field] = parentIntf;
1906 }
1907 }
1908}
1909
Ethan Nicholascc305772017-10-13 16:17:45 -04001910void MetalCodeGenerator::writeVarInitializer(const Variable& var, const Expression& value) {
Brian Osman00185012021-02-04 16:07:11 -05001911 this->writeExpression(value, Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001912}
1913
Ethan Nicholas962dec42021-06-10 13:06:39 -04001914void MetalCodeGenerator::writeName(skstd::string_view name) {
Timothy Liang651286f2018-06-07 09:55:33 -04001915 if (fReservedWords.find(name) != fReservedWords.end()) {
1916 this->write("_"); // adding underscore before name to avoid conflict with reserved words
1917 }
1918 this->write(name);
1919}
1920
Brian Osman58134e12021-05-13 14:51:07 -04001921void MetalCodeGenerator::writeVarDeclaration(const VarDeclaration& varDecl) {
1922 this->writeModifiers(varDecl.var().modifiers());
John Stilesb4418502021-02-04 10:57:08 -05001923 this->writeType(varDecl.var().type());
Brian Osmanc0213602020-10-06 14:43:32 -04001924 this->write(" ");
John Stilesb4418502021-02-04 10:57:08 -05001925 this->writeName(varDecl.var().name());
1926 if (varDecl.value()) {
Brian Osmanc0213602020-10-06 14:43:32 -04001927 this->write(" = ");
John Stilesb4418502021-02-04 10:57:08 -05001928 this->writeVarInitializer(varDecl.var(), *varDecl.value());
Brian Osmanc0213602020-10-06 14:43:32 -04001929 }
1930 this->write(";");
Ethan Nicholascc305772017-10-13 16:17:45 -04001931}
1932
1933void MetalCodeGenerator::writeStatement(const Statement& s) {
Ethan Nicholase6592142020-09-08 10:22:09 -04001934 switch (s.kind()) {
1935 case Statement::Kind::kBlock:
John Stiles26f98502020-08-18 09:30:51 -04001936 this->writeBlock(s.as<Block>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001937 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001938 case Statement::Kind::kExpression:
Brian Osman00185012021-02-04 16:07:11 -05001939 this->writeExpression(*s.as<ExpressionStatement>().expression(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001940 this->write(";");
1941 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001942 case Statement::Kind::kReturn:
John Stiles26f98502020-08-18 09:30:51 -04001943 this->writeReturnStatement(s.as<ReturnStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001944 break;
Brian Osmanc0213602020-10-06 14:43:32 -04001945 case Statement::Kind::kVarDeclaration:
Brian Osman58134e12021-05-13 14:51:07 -04001946 this->writeVarDeclaration(s.as<VarDeclaration>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001947 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001948 case Statement::Kind::kIf:
John Stiles26f98502020-08-18 09:30:51 -04001949 this->writeIfStatement(s.as<IfStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001950 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001951 case Statement::Kind::kFor:
John Stiles26f98502020-08-18 09:30:51 -04001952 this->writeForStatement(s.as<ForStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001953 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001954 case Statement::Kind::kDo:
John Stiles26f98502020-08-18 09:30:51 -04001955 this->writeDoStatement(s.as<DoStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001956 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001957 case Statement::Kind::kSwitch:
John Stiles26f98502020-08-18 09:30:51 -04001958 this->writeSwitchStatement(s.as<SwitchStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001959 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001960 case Statement::Kind::kBreak:
Ethan Nicholascc305772017-10-13 16:17:45 -04001961 this->write("break;");
1962 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001963 case Statement::Kind::kContinue:
Ethan Nicholascc305772017-10-13 16:17:45 -04001964 this->write("continue;");
1965 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001966 case Statement::Kind::kDiscard:
Timothy Lianga06f2152018-05-24 15:33:31 -04001967 this->write("discard_fragment();");
Ethan Nicholascc305772017-10-13 16:17:45 -04001968 break;
John Stiles98c1f822020-09-09 14:18:53 -04001969 case Statement::Kind::kInlineMarker:
Ethan Nicholase6592142020-09-08 10:22:09 -04001970 case Statement::Kind::kNop:
Ethan Nicholascc305772017-10-13 16:17:45 -04001971 this->write(";");
1972 break;
1973 default:
John Stileseada7bc2021-02-02 16:29:32 -05001974 SkDEBUGFAILF("unsupported statement: %s", s.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -05001975 break;
Ethan Nicholascc305772017-10-13 16:17:45 -04001976 }
1977}
1978
Ethan Nicholascc305772017-10-13 16:17:45 -04001979void MetalCodeGenerator::writeBlock(const Block& b) {
John Stiles3744bd62021-01-26 13:49:43 -05001980 // Write scope markers if this block is a scope, or if the block is empty (since we need to emit
1981 // something here to make the code valid).
1982 bool isScope = b.isScope() || b.isEmpty();
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001983 if (isScope) {
Ethan Nicholas70728ef2020-05-28 07:09:00 -04001984 this->writeLine("{");
1985 fIndentation++;
1986 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001987 for (const std::unique_ptr<Statement>& stmt : b.children()) {
1988 if (!stmt->isEmpty()) {
1989 this->writeStatement(*stmt);
John Stilese8b5a732021-03-12 13:25:52 -05001990 this->finishLine();
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001991 }
1992 }
1993 if (isScope) {
Ethan Nicholas70728ef2020-05-28 07:09:00 -04001994 fIndentation--;
1995 this->write("}");
1996 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001997}
1998
1999void MetalCodeGenerator::writeIfStatement(const IfStatement& stmt) {
2000 this->write("if (");
Brian Osman00185012021-02-04 16:07:11 -05002001 this->writeExpression(*stmt.test(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04002002 this->write(") ");
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04002003 this->writeStatement(*stmt.ifTrue());
2004 if (stmt.ifFalse()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002005 this->write(" else ");
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04002006 this->writeStatement(*stmt.ifFalse());
Ethan Nicholascc305772017-10-13 16:17:45 -04002007 }
2008}
2009
2010void MetalCodeGenerator::writeForStatement(const ForStatement& f) {
Brian Osmand6f23382020-12-15 17:08:59 -05002011 // Emit loops of the form 'for(;test;)' as 'while(test)', which is probably how they started
2012 if (!f.initializer() && f.test() && !f.next()) {
2013 this->write("while (");
Brian Osman00185012021-02-04 16:07:11 -05002014 this->writeExpression(*f.test(), Precedence::kTopLevel);
Brian Osmand6f23382020-12-15 17:08:59 -05002015 this->write(") ");
2016 this->writeStatement(*f.statement());
2017 return;
2018 }
2019
John Stiles1a15e572021-04-19 14:57:15 -04002020 this->write("for (");
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04002021 if (f.initializer() && !f.initializer()->isEmpty()) {
John Stiles1a15e572021-04-19 14:57:15 -04002022 this->writeStatement(*f.initializer());
Ethan Nicholascc305772017-10-13 16:17:45 -04002023 } else {
John Stiles1a15e572021-04-19 14:57:15 -04002024 this->write("; ");
Ethan Nicholascc305772017-10-13 16:17:45 -04002025 }
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04002026 if (f.test()) {
Brian Osman00185012021-02-04 16:07:11 -05002027 this->writeExpression(*f.test(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04002028 }
2029 this->write("; ");
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04002030 if (f.next()) {
Brian Osman00185012021-02-04 16:07:11 -05002031 this->writeExpression(*f.next(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04002032 }
2033 this->write(") ");
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04002034 this->writeStatement(*f.statement());
Ethan Nicholascc305772017-10-13 16:17:45 -04002035}
2036
Ethan Nicholascc305772017-10-13 16:17:45 -04002037void MetalCodeGenerator::writeDoStatement(const DoStatement& d) {
2038 this->write("do ");
Ethan Nicholas1fd61162020-09-28 13:14:19 -04002039 this->writeStatement(*d.statement());
Ethan Nicholascc305772017-10-13 16:17:45 -04002040 this->write(" while (");
Brian Osman00185012021-02-04 16:07:11 -05002041 this->writeExpression(*d.test(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04002042 this->write(");");
2043}
2044
2045void MetalCodeGenerator::writeSwitchStatement(const SwitchStatement& s) {
2046 this->write("switch (");
Brian Osman00185012021-02-04 16:07:11 -05002047 this->writeExpression(*s.value(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04002048 this->writeLine(") {");
2049 fIndentation++;
John Stilesb23a64b2021-03-11 08:27:59 -05002050 for (const std::unique_ptr<Statement>& stmt : s.cases()) {
2051 const SwitchCase& c = stmt->as<SwitchCase>();
2052 if (c.value()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002053 this->write("case ");
John Stilesb23a64b2021-03-11 08:27:59 -05002054 this->writeExpression(*c.value(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04002055 this->writeLine(":");
2056 } else {
2057 this->writeLine("default:");
2058 }
John Stilesb23a64b2021-03-11 08:27:59 -05002059 if (!c.statement()->isEmpty()) {
John Stilesc3ce43b2021-03-09 15:37:01 -05002060 fIndentation++;
John Stilesb23a64b2021-03-11 08:27:59 -05002061 this->writeStatement(*c.statement());
John Stilese8b5a732021-03-12 13:25:52 -05002062 this->finishLine();
John Stilesc3ce43b2021-03-09 15:37:01 -05002063 fIndentation--;
Ethan Nicholascc305772017-10-13 16:17:45 -04002064 }
Ethan Nicholascc305772017-10-13 16:17:45 -04002065 }
2066 fIndentation--;
2067 this->write("}");
2068}
2069
John Stiles986c7fb2020-12-01 14:44:56 -05002070void MetalCodeGenerator::writeReturnStatementFromMain() {
2071 // main functions in Metal return a magic _out parameter that doesn't exist in SkSL.
John Stiles270cec22021-02-17 12:59:36 -05002072 switch (fProgram.fConfig->fKind) {
Brian Salomon3e2fe2b2021-06-02 09:16:30 -04002073 case ProgramKind::kVertex:
John Stilesdbd4e6f2021-02-16 13:29:15 -05002074 case ProgramKind::kFragment:
John Stilesf7410bd2021-01-19 13:07:55 -05002075 this->write("return _out;");
John Stiles986c7fb2020-12-01 14:44:56 -05002076 break;
John Stiles986c7fb2020-12-01 14:44:56 -05002077 default:
2078 SkDEBUGFAIL("unsupported kind of program");
2079 }
2080}
2081
Ethan Nicholascc305772017-10-13 16:17:45 -04002082void MetalCodeGenerator::writeReturnStatement(const ReturnStatement& r) {
John Stilese8da4d22021-03-24 09:19:45 -04002083 if (fCurrentFunction && fCurrentFunction->isMain()) {
John Stiles986c7fb2020-12-01 14:44:56 -05002084 if (r.expression()) {
John Stiles97d18172021-01-22 16:47:42 -05002085 if (r.expression()->type() == *fContext.fTypes.fHalf4) {
2086 this->write("_out.sk_FragColor = ");
Brian Osman00185012021-02-04 16:07:11 -05002087 this->writeExpression(*r.expression(), Precedence::kTopLevel);
John Stiles97d18172021-01-22 16:47:42 -05002088 this->writeLine(";");
2089 } else {
2090 fErrors.error(r.fOffset, "Metal does not support returning '" +
2091 r.expression()->type().description() + "' from main()");
2092 }
John Stiles986c7fb2020-12-01 14:44:56 -05002093 }
2094 this->writeReturnStatementFromMain();
2095 return;
2096 }
2097
Ethan Nicholascc305772017-10-13 16:17:45 -04002098 this->write("return");
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04002099 if (r.expression()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002100 this->write(" ");
Brian Osman00185012021-02-04 16:07:11 -05002101 this->writeExpression(*r.expression(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04002102 }
2103 this->write(";");
2104}
2105
Michael Ludwigbf58add2021-03-16 10:40:11 -04002106void MetalCodeGenerator::writeHeader() {
2107 this->write("#include <metal_stdlib>\n");
2108 this->write("#include <simd/simd.h>\n");
2109 this->write("using namespace metal;\n");
2110}
2111
Ethan Nicholascc305772017-10-13 16:17:45 -04002112void MetalCodeGenerator::writeUniformStruct() {
Brian Osman133724c2020-10-28 14:14:39 -04002113 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04002114 if (e->is<GlobalVarDeclaration>()) {
2115 const GlobalVarDeclaration& decls = e->as<GlobalVarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04002116 const Variable& var = decls.declaration()->as<VarDeclaration>().var();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002117 if (var.modifiers().fFlags & Modifiers::kUniform_Flag &&
Brian Osmanc0213602020-10-06 14:43:32 -04002118 var.type().typeKind() != Type::TypeKind::kSampler) {
John Stilesda5cdf62021-01-28 11:47:29 -05002119 int uniformSet = this->getUniformSet(var.modifiers());
John Stilesd8fc95d2021-01-26 16:22:53 -05002120 // Make sure that the program's uniform-set value is consistent throughout.
Ethan Nicholascc305772017-10-13 16:17:45 -04002121 if (-1 == fUniformBuffer) {
2122 this->write("struct Uniforms {\n");
John Stilesd8fc95d2021-01-26 16:22:53 -05002123 fUniformBuffer = uniformSet;
2124 } else if (uniformSet != fUniformBuffer) {
2125 fErrors.error(decls.fOffset, "Metal backend requires all uniforms to have "
2126 "the same 'layout(set=...)'");
Ethan Nicholascc305772017-10-13 16:17:45 -04002127 }
2128 this->write(" ");
John Stilesb4418502021-02-04 10:57:08 -05002129 this->writeType(var.type());
Ethan Nicholascc305772017-10-13 16:17:45 -04002130 this->write(" ");
Brian Osmanc0213602020-10-06 14:43:32 -04002131 this->writeName(var.name());
Ethan Nicholascc305772017-10-13 16:17:45 -04002132 this->write(";\n");
2133 }
2134 }
2135 }
2136 if (-1 != fUniformBuffer) {
2137 this->write("};\n");
2138 }
2139}
2140
2141void MetalCodeGenerator::writeInputStruct() {
2142 this->write("struct Inputs {\n");
Brian Osman133724c2020-10-28 14:14:39 -04002143 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04002144 if (e->is<GlobalVarDeclaration>()) {
2145 const GlobalVarDeclaration& decls = e->as<GlobalVarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04002146 const Variable& var = decls.declaration()->as<VarDeclaration>().var();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002147 if (var.modifiers().fFlags & Modifiers::kIn_Flag &&
2148 -1 == var.modifiers().fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002149 this->write(" ");
John Stilesb4418502021-02-04 10:57:08 -05002150 this->writeType(var.type());
Ethan Nicholascc305772017-10-13 16:17:45 -04002151 this->write(" ");
Brian Osmanc0213602020-10-06 14:43:32 -04002152 this->writeName(var.name());
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002153 if (-1 != var.modifiers().fLayout.fLocation) {
John Stiles270cec22021-02-17 12:59:36 -05002154 if (fProgram.fConfig->fKind == ProgramKind::kVertex) {
Brian Osmanc0213602020-10-06 14:43:32 -04002155 this->write(" [[attribute(" +
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002156 to_string(var.modifiers().fLayout.fLocation) + ")]]");
John Stiles270cec22021-02-17 12:59:36 -05002157 } else if (fProgram.fConfig->fKind == ProgramKind::kFragment) {
Brian Osmanc0213602020-10-06 14:43:32 -04002158 this->write(" [[user(locn" +
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002159 to_string(var.modifiers().fLayout.fLocation) + ")]]");
Ethan Nicholascc305772017-10-13 16:17:45 -04002160 }
2161 }
2162 this->write(";\n");
2163 }
2164 }
2165 }
2166 this->write("};\n");
2167}
2168
2169void MetalCodeGenerator::writeOutputStruct() {
2170 this->write("struct Outputs {\n");
John Stiles270cec22021-02-17 12:59:36 -05002171 if (fProgram.fConfig->fKind == ProgramKind::kVertex) {
Timothy Liangb8eeb802018-07-23 16:46:16 -04002172 this->write(" float4 sk_Position [[position]];\n");
John Stiles270cec22021-02-17 12:59:36 -05002173 } else if (fProgram.fConfig->fKind == ProgramKind::kFragment) {
Timothy Liangde0be802018-08-10 13:48:08 -04002174 this->write(" float4 sk_FragColor [[color(0)]];\n");
Timothy Liang7d637782018-06-05 09:58:07 -04002175 }
Brian Osman133724c2020-10-28 14:14:39 -04002176 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04002177 if (e->is<GlobalVarDeclaration>()) {
2178 const GlobalVarDeclaration& decls = e->as<GlobalVarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04002179 const Variable& var = decls.declaration()->as<VarDeclaration>().var();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002180 if (var.modifiers().fFlags & Modifiers::kOut_Flag &&
2181 -1 == var.modifiers().fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002182 this->write(" ");
John Stilesb4418502021-02-04 10:57:08 -05002183 this->writeType(var.type());
Ethan Nicholascc305772017-10-13 16:17:45 -04002184 this->write(" ");
Brian Osmanc0213602020-10-06 14:43:32 -04002185 this->writeName(var.name());
John Stiles842b3592020-12-01 10:36:37 -05002186
2187 int location = var.modifiers().fLayout.fLocation;
2188 if (location < 0) {
2189 fErrors.error(var.fOffset,
2190 "Metal out variables must have 'layout(location=...)'");
John Stiles270cec22021-02-17 12:59:36 -05002191 } else if (fProgram.fConfig->fKind == ProgramKind::kVertex) {
John Stiles842b3592020-12-01 10:36:37 -05002192 this->write(" [[user(locn" + to_string(location) + ")]]");
John Stiles270cec22021-02-17 12:59:36 -05002193 } else if (fProgram.fConfig->fKind == ProgramKind::kFragment) {
John Stiles842b3592020-12-01 10:36:37 -05002194 this->write(" [[color(" + to_string(location) + ")");
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002195 int colorIndex = var.modifiers().fLayout.fIndex;
Brian Osmanc0213602020-10-06 14:43:32 -04002196 if (colorIndex) {
2197 this->write(", index(" + to_string(colorIndex) + ")");
Timothy Liang7d637782018-06-05 09:58:07 -04002198 }
Brian Osmanc0213602020-10-06 14:43:32 -04002199 this->write("]]");
Ethan Nicholascc305772017-10-13 16:17:45 -04002200 }
2201 this->write(";\n");
2202 }
2203 }
Timothy Liang7d637782018-06-05 09:58:07 -04002204 }
John Stiles270cec22021-02-17 12:59:36 -05002205 if (fProgram.fConfig->fKind == ProgramKind::kVertex) {
Jim Van Verth3913d3e2020-08-31 15:16:57 -04002206 this->write(" float sk_PointSize [[point_size]];\n");
Timothy Liang7d637782018-06-05 09:58:07 -04002207 }
2208 this->write("};\n");
2209}
2210
2211void MetalCodeGenerator::writeInterfaceBlocks() {
2212 bool wroteInterfaceBlock = false;
Brian Osman133724c2020-10-28 14:14:39 -04002213 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04002214 if (e->is<InterfaceBlock>()) {
2215 this->writeInterfaceBlock(e->as<InterfaceBlock>());
Timothy Liang7d637782018-06-05 09:58:07 -04002216 wroteInterfaceBlock = true;
2217 }
2218 }
Brian Salomond8d85b92021-07-07 09:41:17 -04002219 if (!wroteInterfaceBlock && fProgram.fInputs.fUseFlipRTUniform) {
Timothy Liang7d637782018-06-05 09:58:07 -04002220 this->writeLine("struct sksl_synthetic_uniforms {");
Brian Salomond8d85b92021-07-07 09:41:17 -04002221 this->writeLine(" float2 " SKSL_RTFLIP_NAME ";");
Timothy Liang7d637782018-06-05 09:58:07 -04002222 this->writeLine("};");
2223 }
Ethan Nicholascc305772017-10-13 16:17:45 -04002224}
2225
John Stilesdc75a972020-11-25 16:24:55 -05002226void MetalCodeGenerator::writeStructDefinitions() {
2227 for (const ProgramElement* e : fProgram.elements()) {
2228 if (e->is<StructDefinition>()) {
Brian Osman02bc5222021-01-28 11:00:20 -05002229 this->writeStructDefinition(e->as<StructDefinition>());
John Stilesdc75a972020-11-25 16:24:55 -05002230 }
2231 }
2232}
2233
John Stilescdcdb042020-07-06 09:03:51 -04002234void MetalCodeGenerator::visitGlobalStruct(GlobalStructVisitor* visitor) {
2235 // Visit the interface blocks.
2236 for (const auto& [interfaceType, interfaceName] : fInterfaceBlockNameMap) {
John Stilesfdb8dbe2020-12-04 11:00:03 -05002237 visitor->visitInterfaceBlock(*interfaceType, interfaceName);
John Stilescdcdb042020-07-06 09:03:51 -04002238 }
Brian Osman133724c2020-10-28 14:14:39 -04002239 for (const ProgramElement* element : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04002240 if (!element->is<GlobalVarDeclaration>()) {
John Stilescdcdb042020-07-06 09:03:51 -04002241 continue;
Timothy Liang7d637782018-06-05 09:58:07 -04002242 }
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04002243 const GlobalVarDeclaration& global = element->as<GlobalVarDeclaration>();
2244 const VarDeclaration& decl = global.declaration()->as<VarDeclaration>();
2245 const Variable& var = decl.var();
Brian Osman58134e12021-05-13 14:51:07 -04002246 if (var.type().typeKind() == Type::TypeKind::kSampler) {
2247 // Samplers are represented as a "texture/sampler" duo in the global struct.
2248 visitor->visitTexture(var.type(), var.name());
Ethan Nicholasd2e09602021-06-10 11:21:59 -04002249 visitor->visitSampler(var.type(), var.name() + SAMPLER_SUFFIX);
Brian Osman58134e12021-05-13 14:51:07 -04002250 continue;
2251 }
2252
2253 if (!(var.modifiers().fFlags & ~Modifiers::kConst_Flag) &&
2254 -1 == var.modifiers().fLayout.fBuiltin) {
2255 // Visit a regular variable.
2256 visitor->visitVariable(var, decl.value().get());
Timothy Liangee84fe12018-05-18 14:38:19 -04002257 }
2258 }
John Stilescdcdb042020-07-06 09:03:51 -04002259}
2260
2261void MetalCodeGenerator::writeGlobalStruct() {
2262 class : public GlobalStructVisitor {
2263 public:
Ethan Nicholas962dec42021-06-10 13:06:39 -04002264 void visitInterfaceBlock(const InterfaceBlock& block,
2265 skstd::string_view blockName) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002266 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002267 fCodeGen->write(" constant ");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04002268 fCodeGen->write(block.typeName());
John Stilescdcdb042020-07-06 09:03:51 -04002269 fCodeGen->write("* ");
2270 fCodeGen->writeName(blockName);
2271 fCodeGen->write(";\n");
2272 }
Ethan Nicholas962dec42021-06-10 13:06:39 -04002273 void visitTexture(const Type& type, skstd::string_view name) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002274 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002275 fCodeGen->write(" ");
John Stilesb4418502021-02-04 10:57:08 -05002276 fCodeGen->writeType(type);
John Stilescdcdb042020-07-06 09:03:51 -04002277 fCodeGen->write(" ");
2278 fCodeGen->writeName(name);
2279 fCodeGen->write(";\n");
2280 }
Ethan Nicholas962dec42021-06-10 13:06:39 -04002281 void visitSampler(const Type&, skstd::string_view name) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002282 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002283 fCodeGen->write(" sampler ");
2284 fCodeGen->writeName(name);
2285 fCodeGen->write(";\n");
2286 }
John Stilesfdb8dbe2020-12-04 11:00:03 -05002287 void visitVariable(const Variable& var, const Expression* value) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002288 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002289 fCodeGen->write(" ");
Brian Osman58134e12021-05-13 14:51:07 -04002290 fCodeGen->writeModifiers(var.modifiers());
John Stilesb4418502021-02-04 10:57:08 -05002291 fCodeGen->writeType(var.type());
John Stilescdcdb042020-07-06 09:03:51 -04002292 fCodeGen->write(" ");
Ethan Nicholase2c49992020-10-05 11:49:11 -04002293 fCodeGen->writeName(var.name());
John Stilescdcdb042020-07-06 09:03:51 -04002294 fCodeGen->write(";\n");
2295 }
John Stiles83f3b8d2020-12-07 17:52:25 -05002296 void addElement() {
John Stilescdcdb042020-07-06 09:03:51 -04002297 if (fFirst) {
2298 fCodeGen->write("struct Globals {\n");
2299 fFirst = false;
2300 }
2301 }
John Stiles83f3b8d2020-12-07 17:52:25 -05002302 void finish() {
John Stilescdcdb042020-07-06 09:03:51 -04002303 if (!fFirst) {
John Stiles83f3b8d2020-12-07 17:52:25 -05002304 fCodeGen->writeLine("};");
John Stilescdcdb042020-07-06 09:03:51 -04002305 fFirst = true;
2306 }
2307 }
2308
2309 MetalCodeGenerator* fCodeGen = nullptr;
2310 bool fFirst = true;
2311 } visitor;
2312
2313 visitor.fCodeGen = this;
2314 this->visitGlobalStruct(&visitor);
John Stiles83f3b8d2020-12-07 17:52:25 -05002315 visitor.finish();
John Stilescdcdb042020-07-06 09:03:51 -04002316}
2317
2318void MetalCodeGenerator::writeGlobalInit() {
2319 class : public GlobalStructVisitor {
2320 public:
John Stilesfdb8dbe2020-12-04 11:00:03 -05002321 void visitInterfaceBlock(const InterfaceBlock& blockType,
Ethan Nicholas962dec42021-06-10 13:06:39 -04002322 skstd::string_view blockName) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002323 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002324 fCodeGen->write("&");
2325 fCodeGen->writeName(blockName);
2326 }
Ethan Nicholas962dec42021-06-10 13:06:39 -04002327 void visitTexture(const Type&, skstd::string_view name) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002328 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002329 fCodeGen->writeName(name);
2330 }
Ethan Nicholas962dec42021-06-10 13:06:39 -04002331 void visitSampler(const Type&, skstd::string_view name) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002332 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002333 fCodeGen->writeName(name);
2334 }
John Stilesfdb8dbe2020-12-04 11:00:03 -05002335 void visitVariable(const Variable& var, const Expression* value) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002336 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002337 if (value) {
2338 fCodeGen->writeVarInitializer(var, *value);
2339 } else {
2340 fCodeGen->write("{}");
2341 }
2342 }
John Stiles83f3b8d2020-12-07 17:52:25 -05002343 void addElement() {
John Stilescdcdb042020-07-06 09:03:51 -04002344 if (fFirst) {
John Stilesf7410bd2021-01-19 13:07:55 -05002345 fCodeGen->write(" Globals _globals{");
John Stilescdcdb042020-07-06 09:03:51 -04002346 fFirst = false;
2347 } else {
2348 fCodeGen->write(", ");
2349 }
2350 }
John Stiles83f3b8d2020-12-07 17:52:25 -05002351 void finish() {
John Stilescdcdb042020-07-06 09:03:51 -04002352 if (!fFirst) {
2353 fCodeGen->writeLine("};");
John Stiles37279172021-01-21 22:24:28 -05002354 fCodeGen->writeLine(" (void)_globals;");
John Stilescdcdb042020-07-06 09:03:51 -04002355 }
2356 }
2357 MetalCodeGenerator* fCodeGen = nullptr;
2358 bool fFirst = true;
2359 } visitor;
2360
2361 visitor.fCodeGen = this;
2362 this->visitGlobalStruct(&visitor);
John Stiles83f3b8d2020-12-07 17:52:25 -05002363 visitor.finish();
Timothy Liangee84fe12018-05-18 14:38:19 -04002364}
2365
Ethan Nicholascc305772017-10-13 16:17:45 -04002366void MetalCodeGenerator::writeProgramElement(const ProgramElement& e) {
Ethan Nicholase6592142020-09-08 10:22:09 -04002367 switch (e.kind()) {
2368 case ProgramElement::Kind::kExtension:
Ethan Nicholascc305772017-10-13 16:17:45 -04002369 break;
Brian Osman58134e12021-05-13 14:51:07 -04002370 case ProgramElement::Kind::kGlobalVar:
Ethan Nicholascc305772017-10-13 16:17:45 -04002371 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04002372 case ProgramElement::Kind::kInterfaceBlock:
Timothy Liang7d637782018-06-05 09:58:07 -04002373 // handled in writeInterfaceBlocks, do nothing
Ethan Nicholascc305772017-10-13 16:17:45 -04002374 break;
John Stilesdc75a972020-11-25 16:24:55 -05002375 case ProgramElement::Kind::kStructDefinition:
2376 // Handled in writeStructDefinitions. Do nothing.
2377 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04002378 case ProgramElement::Kind::kFunction:
John Stiles3dc0da62020-08-19 17:48:31 -04002379 this->writeFunction(e.as<FunctionDefinition>());
Ethan Nicholascc305772017-10-13 16:17:45 -04002380 break;
John Stiles569249b2020-11-03 12:18:22 -05002381 case ProgramElement::Kind::kFunctionPrototype:
2382 this->writeFunctionPrototype(e.as<FunctionPrototype>());
2383 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04002384 case ProgramElement::Kind::kModifiers:
Brian Osman58134e12021-05-13 14:51:07 -04002385 this->writeModifiers(e.as<ModifiersDeclaration>().modifiers());
Ethan Nicholascc305772017-10-13 16:17:45 -04002386 this->writeLine(";");
2387 break;
2388 default:
John Stileseada7bc2021-02-02 16:29:32 -05002389 SkDEBUGFAILF("unsupported program element: %s\n", e.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -05002390 break;
Ethan Nicholascc305772017-10-13 16:17:45 -04002391 }
2392}
2393
Ethan Nicholasff350cb2020-05-14 14:05:13 -04002394MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const Expression* e) {
2395 if (!e) {
2396 return kNo_Requirements;
2397 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002398 switch (e->kind()) {
2399 case Expression::Kind::kFunctionCall: {
John Stiles3dc0da62020-08-19 17:48:31 -04002400 const FunctionCall& f = e->as<FunctionCall>();
Ethan Nicholas0dec9922020-10-05 15:51:52 -04002401 Requirements result = this->requirements(f.function());
2402 for (const auto& arg : f.arguments()) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04002403 result |= this->requirements(arg.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002404 }
2405 return result;
2406 }
John Stiles8cad6372021-04-07 12:31:13 -04002407 case Expression::Kind::kConstructorCompound:
2408 case Expression::Kind::kConstructorCompoundCast:
John Stiles7384b372021-04-01 13:48:15 -04002409 case Expression::Kind::kConstructorArray:
John Stilese3ae9682021-08-05 10:35:01 -04002410 case Expression::Kind::kConstructorArrayCast:
John Stiles2938eea2021-04-01 18:58:25 -04002411 case Expression::Kind::kConstructorDiagonalMatrix:
John Stilesfd7252f2021-04-04 22:24:40 -04002412 case Expression::Kind::kConstructorScalarCast:
John Stilesd47330f2021-04-08 23:25:52 -04002413 case Expression::Kind::kConstructorSplat:
2414 case Expression::Kind::kConstructorStruct: {
John Stiles7384b372021-04-01 13:48:15 -04002415 const AnyConstructor& c = e->asAnyConstructor();
Ethan Nicholascc305772017-10-13 16:17:45 -04002416 Requirements result = kNo_Requirements;
John Stilesd8eb8752021-04-01 11:49:10 -04002417 for (const auto& arg : c.argumentSpan()) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04002418 result |= this->requirements(arg.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002419 }
2420 return result;
2421 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002422 case Expression::Kind::kFieldAccess: {
John Stiles3dc0da62020-08-19 17:48:31 -04002423 const FieldAccess& f = e->as<FieldAccess>();
Ethan Nicholas7a95b202020-10-09 11:55:40 -04002424 if (FieldAccess::OwnerKind::kAnonymousInterfaceBlock == f.ownerKind()) {
Timothy Liang7d637782018-06-05 09:58:07 -04002425 return kGlobals_Requirement;
2426 }
Ethan Nicholas7a95b202020-10-09 11:55:40 -04002427 return this->requirements(f.base().get());
Timothy Liang7d637782018-06-05 09:58:07 -04002428 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002429 case Expression::Kind::kSwizzle:
Ethan Nicholas6b4d5812020-10-12 16:11:51 -04002430 return this->requirements(e->as<Swizzle>().base().get());
Ethan Nicholase6592142020-09-08 10:22:09 -04002431 case Expression::Kind::kBinary: {
2432 const BinaryExpression& bin = e->as<BinaryExpression>();
John Stiles2d4f9592020-10-30 10:29:12 -04002433 return this->requirements(bin.left().get()) |
2434 this->requirements(bin.right().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002435 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002436 case Expression::Kind::kIndex: {
John Stiles3dc0da62020-08-19 17:48:31 -04002437 const IndexExpression& idx = e->as<IndexExpression>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04002438 return this->requirements(idx.base().get()) | this->requirements(idx.index().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002439 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002440 case Expression::Kind::kPrefix:
Ethan Nicholas444ccc62020-10-09 10:16:22 -04002441 return this->requirements(e->as<PrefixExpression>().operand().get());
Ethan Nicholase6592142020-09-08 10:22:09 -04002442 case Expression::Kind::kPostfix:
Ethan Nicholas444ccc62020-10-09 10:16:22 -04002443 return this->requirements(e->as<PostfixExpression>().operand().get());
Ethan Nicholase6592142020-09-08 10:22:09 -04002444 case Expression::Kind::kTernary: {
John Stiles3dc0da62020-08-19 17:48:31 -04002445 const TernaryExpression& t = e->as<TernaryExpression>();
Ethan Nicholasdd218162020-10-08 05:48:01 -04002446 return this->requirements(t.test().get()) | this->requirements(t.ifTrue().get()) |
2447 this->requirements(t.ifFalse().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002448 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002449 case Expression::Kind::kVariableReference: {
John Stiles3dc0da62020-08-19 17:48:31 -04002450 const VariableReference& v = e->as<VariableReference>();
Ethan Nicholas78686922020-10-08 06:46:27 -04002451 const Modifiers& modifiers = v.variable()->modifiers();
Ethan Nicholascc305772017-10-13 16:17:45 -04002452 Requirements result = kNo_Requirements;
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002453 if (modifiers.fLayout.fBuiltin == SK_FRAGCOORD_BUILTIN) {
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -04002454 result = kGlobals_Requirement | kFragCoord_Requirement;
Ethan Nicholas453f67f2020-10-09 10:43:45 -04002455 } else if (Variable::Storage::kGlobal == v.variable()->storage()) {
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002456 if (modifiers.fFlags & Modifiers::kIn_Flag) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002457 result = kInputs_Requirement;
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002458 } else if (modifiers.fFlags & Modifiers::kOut_Flag) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002459 result = kOutputs_Requirement;
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002460 } else if (modifiers.fFlags & Modifiers::kUniform_Flag &&
Ethan Nicholas78686922020-10-08 06:46:27 -04002461 v.variable()->type().typeKind() != Type::TypeKind::kSampler) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002462 result = kUniforms_Requirement;
Timothy Liangee84fe12018-05-18 14:38:19 -04002463 } else {
2464 result = kGlobals_Requirement;
Ethan Nicholascc305772017-10-13 16:17:45 -04002465 }
2466 }
2467 return result;
2468 }
2469 default:
2470 return kNo_Requirements;
2471 }
2472}
2473
Ethan Nicholasff350cb2020-05-14 14:05:13 -04002474MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const Statement* s) {
2475 if (!s) {
2476 return kNo_Requirements;
2477 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002478 switch (s->kind()) {
2479 case Statement::Kind::kBlock: {
Ethan Nicholascc305772017-10-13 16:17:45 -04002480 Requirements result = kNo_Requirements;
Ethan Nicholas7bd60432020-09-25 14:31:59 -04002481 for (const std::unique_ptr<Statement>& child : s->as<Block>().children()) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04002482 result |= this->requirements(child.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002483 }
2484 return result;
2485 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002486 case Statement::Kind::kVarDeclaration: {
John Stiles3dc0da62020-08-19 17:48:31 -04002487 const VarDeclaration& var = s->as<VarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04002488 return this->requirements(var.value().get());
Timothy Liang7d637782018-06-05 09:58:07 -04002489 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002490 case Statement::Kind::kExpression:
Ethan Nicholasd503a5a2020-09-30 09:29:55 -04002491 return this->requirements(s->as<ExpressionStatement>().expression().get());
Ethan Nicholase6592142020-09-08 10:22:09 -04002492 case Statement::Kind::kReturn: {
John Stiles3dc0da62020-08-19 17:48:31 -04002493 const ReturnStatement& r = s->as<ReturnStatement>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04002494 return this->requirements(r.expression().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002495 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002496 case Statement::Kind::kIf: {
John Stiles3dc0da62020-08-19 17:48:31 -04002497 const IfStatement& i = s->as<IfStatement>();
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04002498 return this->requirements(i.test().get()) |
2499 this->requirements(i.ifTrue().get()) |
2500 this->requirements(i.ifFalse().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002501 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002502 case Statement::Kind::kFor: {
John Stiles3dc0da62020-08-19 17:48:31 -04002503 const ForStatement& f = s->as<ForStatement>();
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04002504 return this->requirements(f.initializer().get()) |
2505 this->requirements(f.test().get()) |
2506 this->requirements(f.next().get()) |
2507 this->requirements(f.statement().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002508 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002509 case Statement::Kind::kDo: {
John Stiles3dc0da62020-08-19 17:48:31 -04002510 const DoStatement& d = s->as<DoStatement>();
Ethan Nicholas1fd61162020-09-28 13:14:19 -04002511 return this->requirements(d.test().get()) |
2512 this->requirements(d.statement().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002513 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002514 case Statement::Kind::kSwitch: {
John Stiles3dc0da62020-08-19 17:48:31 -04002515 const SwitchStatement& sw = s->as<SwitchStatement>();
Ethan Nicholas01b05e52020-10-22 15:53:41 -04002516 Requirements result = this->requirements(sw.value().get());
John Stilesb23a64b2021-03-11 08:27:59 -05002517 for (const std::unique_ptr<Statement>& sc : sw.cases()) {
2518 result |= this->requirements(sc->as<SwitchCase>().statement().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002519 }
2520 return result;
2521 }
2522 default:
2523 return kNo_Requirements;
2524 }
2525}
2526
2527MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const FunctionDeclaration& f) {
Ethan Nicholased84b732020-10-08 11:45:44 -04002528 if (f.isBuiltin()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002529 return kNo_Requirements;
2530 }
2531 auto found = fRequirements.find(&f);
2532 if (found == fRequirements.end()) {
Ethan Nicholas65a8f562019-04-19 14:00:26 -04002533 fRequirements[&f] = kNo_Requirements;
Brian Osman133724c2020-10-28 14:14:39 -04002534 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04002535 if (e->is<FunctionDefinition>()) {
2536 const FunctionDefinition& def = e->as<FunctionDefinition>();
Ethan Nicholas0a5d0962020-10-14 13:33:18 -04002537 if (&def.declaration() == &f) {
2538 Requirements reqs = this->requirements(def.body().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002539 fRequirements[&f] = reqs;
2540 return reqs;
2541 }
2542 }
2543 }
John Stiles569249b2020-11-03 12:18:22 -05002544 // We never found a definition for this declared function, but it's legal to prototype a
2545 // function without ever giving a definition, as long as you don't call it.
2546 return kNo_Requirements;
Ethan Nicholascc305772017-10-13 16:17:45 -04002547 }
2548 return found->second;
2549}
2550
Timothy Liangb8eeb802018-07-23 16:46:16 -04002551bool MetalCodeGenerator::generateCode() {
John Stiles44532372020-12-07 12:33:55 -05002552 StringStream header;
2553 {
2554 AutoOutputStream outputToHeader(this, &header, &fIndentation);
Michael Ludwigbf58add2021-03-16 10:40:11 -04002555 this->writeHeader();
John Stiles44532372020-12-07 12:33:55 -05002556 this->writeStructDefinitions();
2557 this->writeUniformStruct();
2558 this->writeInputStruct();
2559 this->writeOutputStruct();
2560 this->writeInterfaceBlocks();
2561 this->writeGlobalStruct();
2562 }
2563 StringStream body;
2564 {
2565 AutoOutputStream outputToBody(this, &body, &fIndentation);
2566 for (const ProgramElement* e : fProgram.elements()) {
2567 this->writeProgramElement(*e);
2568 }
2569 }
2570 write_stringstream(header, *fOut);
2571 write_stringstream(fExtraFunctions, *fOut);
2572 write_stringstream(body, *fOut);
Brian Osman8609a242020-09-08 14:01:49 -04002573 return 0 == fErrors.errorCount();
Ethan Nicholascc305772017-10-13 16:17:45 -04002574}
2575
John Stilesa6841be2020-08-06 14:11:56 -04002576} // namespace SkSL