blob: 41184bf43f6c2ab71012be623df35524ca215755 [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
Mike Kleinc0bd9f92019-04-23 12:05:21 -05008#include "src/sksl/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"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050013#include "src/sksl/ir/SkSLExpressionStatement.h"
14#include "src/sksl/ir/SkSLExtension.h"
15#include "src/sksl/ir/SkSLIndexExpression.h"
16#include "src/sksl/ir/SkSLModifiersDeclaration.h"
17#include "src/sksl/ir/SkSLNop.h"
John Stilesdc75a972020-11-25 16:24:55 -050018#include "src/sksl/ir/SkSLStructDefinition.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050019#include "src/sksl/ir/SkSLVariableReference.h"
Ethan Nicholascc305772017-10-13 16:17:45 -040020
Brian Osmanc262a122020-08-06 16:34:34 -040021#include <algorithm>
22
Ethan Nicholascc305772017-10-13 16:17:45 -040023namespace SkSL {
24
John Stilesd6449e92020-11-30 09:13:23 -050025const char* MetalCodeGenerator::OperatorName(Token::Kind op) {
26 switch (op) {
27 case Token::Kind::TK_LOGICALXOR: return "!=";
28 default: return Compiler::OperatorName(op);
29 }
30}
31
John Stilescdcdb042020-07-06 09:03:51 -040032class MetalCodeGenerator::GlobalStructVisitor {
33public:
34 virtual ~GlobalStructVisitor() = default;
John Stilesfdb8dbe2020-12-04 11:00:03 -050035 virtual void visitInterfaceBlock(const InterfaceBlock& block, const String& blockName) = 0;
36 virtual void visitTexture(const Type& type, const String& name) = 0;
37 virtual void visitSampler(const Type& type, const String& name) = 0;
38 virtual void visitVariable(const Variable& var, const Expression* value) = 0;
John Stilescdcdb042020-07-06 09:03:51 -040039};
40
Timothy Liangee84fe12018-05-18 14:38:19 -040041void MetalCodeGenerator::setupIntrinsics() {
Timothy Liang7d637782018-06-05 09:58:07 -040042#define METAL(x) std::make_pair(kMetal_IntrinsicKind, k ## x ## _MetalIntrinsic)
43#define SPECIAL(x) std::make_pair(kSpecial_IntrinsicKind, k ## x ## _SpecialIntrinsic)
Brian Osman46787d52020-11-24 14:18:23 -050044 fIntrinsicMap[String("distance")] = SPECIAL(Distance);
45 fIntrinsicMap[String("dot")] = SPECIAL(Dot);
46 fIntrinsicMap[String("length")] = SPECIAL(Length);
Timothy Liang651286f2018-06-07 09:55:33 -040047 fIntrinsicMap[String("mod")] = SPECIAL(Mod);
Brian Osman46787d52020-11-24 14:18:23 -050048 fIntrinsicMap[String("normalize")] = SPECIAL(Normalize);
49 fIntrinsicMap[String("sample")] = SPECIAL(Texture);
Ethan Nicholas0dc80872019-02-08 15:46:24 -050050 fIntrinsicMap[String("equal")] = METAL(Equal);
51 fIntrinsicMap[String("notEqual")] = METAL(NotEqual);
Timothy Lianga06f2152018-05-24 15:33:31 -040052 fIntrinsicMap[String("lessThan")] = METAL(LessThan);
53 fIntrinsicMap[String("lessThanEqual")] = METAL(LessThanEqual);
54 fIntrinsicMap[String("greaterThan")] = METAL(GreaterThan);
55 fIntrinsicMap[String("greaterThanEqual")] = METAL(GreaterThanEqual);
Timothy Liangee84fe12018-05-18 14:38:19 -040056}
57
Ethan Nicholascc305772017-10-13 16:17:45 -040058void MetalCodeGenerator::write(const char* s) {
59 if (!s[0]) {
60 return;
61 }
62 if (fAtLineStart) {
63 for (int i = 0; i < fIndentation; i++) {
64 fOut->writeText(" ");
65 }
66 }
67 fOut->writeText(s);
68 fAtLineStart = false;
69}
70
71void MetalCodeGenerator::writeLine(const char* s) {
72 this->write(s);
73 fOut->writeText(fLineEnding);
74 fAtLineStart = true;
75}
76
77void MetalCodeGenerator::write(const String& s) {
78 this->write(s.c_str());
79}
80
81void MetalCodeGenerator::writeLine(const String& s) {
82 this->writeLine(s.c_str());
83}
84
85void MetalCodeGenerator::writeLine() {
86 this->writeLine("");
87}
88
89void MetalCodeGenerator::writeExtension(const Extension& ext) {
Ethan Nicholasefb09e22020-09-30 10:17:00 -040090 this->writeLine("#extension " + ext.name() + " : enable");
Ethan Nicholascc305772017-10-13 16:17:45 -040091}
92
Ethan Nicholas45fa8102020-01-13 10:58:49 -050093String MetalCodeGenerator::typeName(const Type& type) {
Ethan Nicholase6592142020-09-08 10:22:09 -040094 switch (type.typeKind()) {
95 case Type::TypeKind::kVector:
Ethan Nicholas45fa8102020-01-13 10:58:49 -050096 return this->typeName(type.componentType()) + to_string(type.columns());
Ethan Nicholase6592142020-09-08 10:22:09 -040097 case Type::TypeKind::kMatrix:
Ethan Nicholas45fa8102020-01-13 10:58:49 -050098 return this->typeName(type.componentType()) + to_string(type.columns()) + "x" +
99 to_string(type.rows());
Ethan Nicholase6592142020-09-08 10:22:09 -0400100 case Type::TypeKind::kSampler:
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500101 return "texture2d<float>"; // FIXME - support other texture types;
John Stilesfd41d872020-11-25 22:39:45 -0500102 case Type::TypeKind::kEnum:
103 return "int";
Ethan Nicholascc305772017-10-13 16:17:45 -0400104 default:
Timothy Liang43d225f2018-07-19 15:27:13 -0400105 if (type == *fContext.fHalf_Type) {
106 // FIXME - Currently only supporting floats in MSL to avoid type coercion issues.
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500107 return fContext.fFloat_Type->name();
Timothy Liang43d225f2018-07-19 15:27:13 -0400108 } else if (type == *fContext.fByte_Type) {
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500109 return "char";
Timothy Liang43d225f2018-07-19 15:27:13 -0400110 } else if (type == *fContext.fUByte_Type) {
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500111 return "uchar";
Timothy Liang7d637782018-06-05 09:58:07 -0400112 } else {
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500113 return type.name();
Timothy Liang7d637782018-06-05 09:58:07 -0400114 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400115 }
116}
117
John Stilesdc75a972020-11-25 16:24:55 -0500118bool MetalCodeGenerator::writeStructDefinition(const Type& type) {
119 for (const Type* search : fWrittenStructs) {
120 if (*search == type) {
121 // already written
122 return false;
123 }
124 }
125 fWrittenStructs.push_back(&type);
126 this->writeLine("struct " + type.name() + " {");
127 fIndentation++;
128 this->writeFields(type.fields(), type.fOffset);
129 fIndentation--;
130 this->write("}");
131 return true;
132}
133
John Stiles3dba3ee2020-12-02 23:35:49 -0500134// Flags an error if an array type is found. Meant to be used in places where an array type might
135// appear in the SkSL/IR, but can't be represented by Metal.
136void MetalCodeGenerator::disallowArrayTypes(const Type& type) {
John Stilesc0c51062020-12-03 17:16:29 -0500137 if (type.isArray()) {
John Stiles3dba3ee2020-12-02 23:35:49 -0500138 fErrors.error(type.fOffset, "Metal does not support array types in this context");
139 }
140}
141
142// Writes the base type, stripping array suffixes. e.g. `float[2]` will output `float`.
143// Call `writeArrayDimensions` to write the type's accompanying array sizes.
144void MetalCodeGenerator::writeBaseType(const Type& type) {
145 switch (type.typeKind()) {
146 case Type::TypeKind::kStruct:
147 if (!this->writeStructDefinition(type)) {
148 this->write(type.name());
149 }
150 break;
151 case Type::TypeKind::kArray:
152 this->writeBaseType(type.componentType());
153 break;
154 default:
155 this->write(this->typeName(type));
156 break;
157 }
158}
159
160// Writes the array suffix of a type, if one exists. e.g. `float[2][4]` will output `[2][4]`.
161void MetalCodeGenerator::writeArrayDimensions(const Type& type) {
John Stilesc0c51062020-12-03 17:16:29 -0500162 if (type.isArray()) {
John Stiles3dba3ee2020-12-02 23:35:49 -0500163 this->write("[");
164 if (type.columns() != Type::kUnsizedArray) {
165 this->write(to_string(type.columns()));
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500166 }
John Stiles3dba3ee2020-12-02 23:35:49 -0500167 this->write("]");
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500168 }
169}
170
Ethan Nicholascc305772017-10-13 16:17:45 -0400171void MetalCodeGenerator::writeExpression(const Expression& expr, Precedence parentPrecedence) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400172 switch (expr.kind()) {
173 case Expression::Kind::kBinary:
John Stiles81365af2020-08-18 09:24:00 -0400174 this->writeBinaryExpression(expr.as<BinaryExpression>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400175 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400176 case Expression::Kind::kBoolLiteral:
John Stiles81365af2020-08-18 09:24:00 -0400177 this->writeBoolLiteral(expr.as<BoolLiteral>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400178 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400179 case Expression::Kind::kConstructor:
John Stiles81365af2020-08-18 09:24:00 -0400180 this->writeConstructor(expr.as<Constructor>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400181 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400182 case Expression::Kind::kIntLiteral:
John Stiles81365af2020-08-18 09:24:00 -0400183 this->writeIntLiteral(expr.as<IntLiteral>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400184 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400185 case Expression::Kind::kFieldAccess:
John Stiles81365af2020-08-18 09:24:00 -0400186 this->writeFieldAccess(expr.as<FieldAccess>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400187 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400188 case Expression::Kind::kFloatLiteral:
John Stiles81365af2020-08-18 09:24:00 -0400189 this->writeFloatLiteral(expr.as<FloatLiteral>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400190 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400191 case Expression::Kind::kFunctionCall:
John Stiles81365af2020-08-18 09:24:00 -0400192 this->writeFunctionCall(expr.as<FunctionCall>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400193 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400194 case Expression::Kind::kPrefix:
John Stiles81365af2020-08-18 09:24:00 -0400195 this->writePrefixExpression(expr.as<PrefixExpression>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400196 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400197 case Expression::Kind::kPostfix:
John Stiles81365af2020-08-18 09:24:00 -0400198 this->writePostfixExpression(expr.as<PostfixExpression>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400199 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400200 case Expression::Kind::kSetting:
John Stiles81365af2020-08-18 09:24:00 -0400201 this->writeSetting(expr.as<Setting>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400202 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400203 case Expression::Kind::kSwizzle:
John Stiles81365af2020-08-18 09:24:00 -0400204 this->writeSwizzle(expr.as<Swizzle>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400205 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400206 case Expression::Kind::kVariableReference:
John Stiles81365af2020-08-18 09:24:00 -0400207 this->writeVariableReference(expr.as<VariableReference>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400208 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400209 case Expression::Kind::kTernary:
John Stiles81365af2020-08-18 09:24:00 -0400210 this->writeTernaryExpression(expr.as<TernaryExpression>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400211 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400212 case Expression::Kind::kIndex:
John Stiles81365af2020-08-18 09:24:00 -0400213 this->writeIndexExpression(expr.as<IndexExpression>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400214 break;
215 default:
Ethan Nicholas2a099da2020-01-02 14:40:54 -0500216#ifdef SK_DEBUG
Ethan Nicholascc305772017-10-13 16:17:45 -0400217 ABORT("unsupported expression: %s", expr.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -0500218#endif
219 break;
Ethan Nicholascc305772017-10-13 16:17:45 -0400220 }
221}
222
Timothy Liang6403b0e2018-05-17 10:40:04 -0400223void MetalCodeGenerator::writeIntrinsicCall(const FunctionCall& c) {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400224 auto i = fIntrinsicMap.find(c.function().name());
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400225 SkASSERT(i != fIntrinsicMap.end());
Timothy Liang7d637782018-06-05 09:58:07 -0400226 Intrinsic intrinsic = i->second;
227 int32_t intrinsicId = intrinsic.second;
228 switch (intrinsic.first) {
Timothy Liang6403b0e2018-05-17 10:40:04 -0400229 case kSpecial_IntrinsicKind:
230 return this->writeSpecialIntrinsic(c, (SpecialIntrinsic) intrinsicId);
Timothy Lianga06f2152018-05-24 15:33:31 -0400231 break;
232 case kMetal_IntrinsicKind:
John Stiles47b4b192020-12-08 18:08:11 -0500233 this->write("(");
234 this->writeExpression(*c.arguments()[0], kRelational_Precedence);
Timothy Lianga06f2152018-05-24 15:33:31 -0400235 switch ((MetalIntrinsic) intrinsicId) {
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500236 case kEqual_MetalIntrinsic:
237 this->write(" == ");
238 break;
239 case kNotEqual_MetalIntrinsic:
240 this->write(" != ");
241 break;
Timothy Lianga06f2152018-05-24 15:33:31 -0400242 case kLessThan_MetalIntrinsic:
243 this->write(" < ");
244 break;
245 case kLessThanEqual_MetalIntrinsic:
246 this->write(" <= ");
247 break;
248 case kGreaterThan_MetalIntrinsic:
249 this->write(" > ");
250 break;
251 case kGreaterThanEqual_MetalIntrinsic:
252 this->write(" >= ");
253 break;
254 default:
John Stiles47b4b192020-12-08 18:08:11 -0500255 ABORT("unsupported Metal intrinsic kind");
Timothy Lianga06f2152018-05-24 15:33:31 -0400256 }
John Stiles47b4b192020-12-08 18:08:11 -0500257 this->writeExpression(*c.arguments()[1], kRelational_Precedence);
258 this->write(")");
Timothy Lianga06f2152018-05-24 15:33:31 -0400259 break;
Timothy Liang6403b0e2018-05-17 10:40:04 -0400260 default:
261 ABORT("unsupported intrinsic kind");
262 }
263}
264
John Stiles06b84ef2020-12-09 12:35:48 -0500265String MetalCodeGenerator::getOutParamHelper(const FunctionCall& call,
266 const ExpressionArray& arguments,
267 const SkTArray<VariableReference*>& outVars) {
268 AutoOutputStream outputToExtraFunctions(this, &fExtraFunctions, &fIndentation);
269 const FunctionDeclaration& function = call.function();
270
271 String name = "_skOutParamHelper" + to_string(fSwizzleHelperCount++) + "_" + function.name();
272 const char* separator = "";
273
274 // Emit a prototype for the function we'll be calling through to in our helper.
275 if (!function.isBuiltin()) {
276 this->writeFunctionDeclaration(function);
277 this->writeLine(";");
278 }
279
280 // Synthesize a helper function that takes the same inputs as `function`, except in places where
281 // `outVars` is non-null; in those places, we take the type of the VariableReference.
282 //
283 // float _skOutParamHelper0_originalFuncName(float _var0, float _var1, float& outParam) {
284 this->writeBaseType(call.type());
285 this->write(" ");
286 this->write(name);
287 this->write("(");
288 this->writeFunctionRequirementParams(function, separator);
289
290 SkASSERT(outVars.size() == arguments.size());
291 SkASSERT(outVars.size() == function.parameters().size());
292
293 for (int index = 0; index < arguments.count(); ++index) {
294 this->write(separator);
295 separator = ", ";
296
297 const Variable* param = function.parameters()[index];
298 this->writeModifiers(param->modifiers(), /*globalContext=*/false);
299
300 const Type* type = outVars[index] ? &outVars[index]->type() : &arguments[index]->type();
301 this->writeBaseType(*type);
302
303 if (param->modifiers().fFlags & Modifiers::kOut_Flag) {
304 this->write("&");
305 }
306 if (outVars[index]) {
307 this->write(" ");
308 fIgnoreVariableReferenceModifiers = true;
309 this->writeVariableReference(*outVars[index]);
310 fIgnoreVariableReferenceModifiers = false;
311 } else {
312 this->write(" _var");
313 this->write(to_string(index));
314 }
315 this->writeArrayDimensions(*type);
316 }
317 this->writeLine(") {");
318
319 ++fIndentation;
320 for (int index = 0; index < outVars.count(); ++index) {
321 if (!outVars[index]) {
322 continue;
323 }
324 // float3 _var2[ = outParam.zyx];
325 this->writeBaseType(arguments[index]->type());
326 this->write(" _var");
327 this->write(to_string(index));
328
329 const Variable* param = function.parameters()[index];
330 if (param->modifiers().fFlags & Modifiers::kIn_Flag) {
331 this->write(" = ");
332 fIgnoreVariableReferenceModifiers = true;
333 this->writeExpression(*arguments[index], kAssignment_Precedence);
334 fIgnoreVariableReferenceModifiers = false;
335 }
336
337 this->writeLine(";");
338 }
339
340 // [int _skResult = ] myFunction(inputs, outputs, globals, _var0, _var1, _var2, _var3);
341 bool hasResult = (call.type().name() != "void");
342 if (hasResult) {
343 this->writeBaseType(call.type());
344 this->write(" _skResult = ");
345 }
346
347 this->writeName(function.name());
348 this->write("(");
349 separator = "";
350 this->writeFunctionRequirementArgs(function, separator);
351
352 for (int index = 0; index < arguments.count(); ++index) {
353 this->write(separator);
354 separator = ", ";
355
356 this->write("_var");
357 this->write(to_string(index));
358 }
359 this->writeLine(");");
360
361 for (int index = 0; index < outVars.count(); ++index) {
362 if (!outVars[index]) {
363 continue;
364 }
365 // outParam.zyx = _var2;
366 fIgnoreVariableReferenceModifiers = true;
367 this->writeExpression(*arguments[index], kAssignment_Precedence);
368 fIgnoreVariableReferenceModifiers = false;
369 this->write(" = _var");
370 this->write(to_string(index));
371 this->writeLine(";");
372 }
373
374 if (hasResult) {
375 this->writeLine("return _skResult;");
376 }
377
378 --fIndentation;
379 this->writeLine("}");
380
381 return name;
John Stilesb21fac22020-12-04 15:36:49 -0500382}
383
John Stilesf64e4072020-12-10 10:34:27 -0500384String MetalCodeGenerator::getBitcastIntrinsic(const Type& outType) {
385 return "as_type<" + outType.displayName() + ">";
386}
387
Ethan Nicholascc305772017-10-13 16:17:45 -0400388void MetalCodeGenerator::writeFunctionCall(const FunctionCall& c) {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400389 const FunctionDeclaration& function = c.function();
John Stiles8e3b6be2020-10-13 11:14:08 -0400390 const ExpressionArray& arguments = c.arguments();
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400391 const auto& entry = fIntrinsicMap.find(function.name());
Timothy Liang6403b0e2018-05-17 10:40:04 -0400392 if (entry != fIntrinsicMap.end()) {
393 this->writeIntrinsicCall(c);
394 return;
395 }
John Stilesb21fac22020-12-04 15:36:49 -0500396 String name = function.name();
John Stilesb21fac22020-12-04 15:36:49 -0500397
John Stilesf64e4072020-12-10 10:34:27 -0500398 if (function.isBuiltin()) {
399 if (name == "atan" && arguments.size() == 2) {
400 name = "atan2";
401 } else if (name == "inversesqrt") {
402 name = "rsqrt";
403 } else if (name == "inverse") {
404 SkASSERT(arguments.size() == 1);
405 name = this->getInverseHack(*arguments[0]);
406 } else if (name == "dFdx") {
407 name = "dfdx";
408 } else if (name == "dFdy") {
409 // Flipping Y also negates the Y derivatives.
410 if (fProgram.fSettings.fFlipY) {
411 this->write("-");
412 }
413 name = "dfdy";
414 } else if (name == "floatBitsToInt" || name == "floatBitsToUint" ||
415 name == "intBitsToFloat" || name == "uintBitsToFloat") {
416 name = this->getBitcastIntrinsic(c.type());
John Stilesb21fac22020-12-04 15:36:49 -0500417 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400418 }
John Stilesb21fac22020-12-04 15:36:49 -0500419
John Stilesf64e4072020-12-10 10:34:27 -0500420 // We emulate GLSL's out-param semantics for Metal using a helper function. (Specifically,
421 // results are only written back to the original variable at the end of the function call; also,
422 // swizzles are supported, whereas Metal doesn't allow a swizzle to be passed to a `floatN&`.)
John Stilesb21fac22020-12-04 15:36:49 -0500423 const std::vector<const Variable*>& parameters = function.parameters();
424 SkASSERT(arguments.size() == parameters.size());
John Stiles06b84ef2020-12-09 12:35:48 -0500425
426 bool foundOutParam = false;
427 SkSTArray<16, VariableReference*> outVars;
John Stilesf64e4072020-12-10 10:34:27 -0500428 outVars.push_back_n(arguments.count(), (VariableReference*)nullptr);
John Stiles06b84ef2020-12-09 12:35:48 -0500429
430 for (int index = 0; index < arguments.count(); ++index) {
John Stilesb21fac22020-12-04 15:36:49 -0500431 // If this is an out parameter...
432 if (parameters[index]->modifiers().fFlags & Modifiers::kOut_Flag) {
John Stiles06b84ef2020-12-09 12:35:48 -0500433 // Find the expression's inner variable being written to.
John Stilesb21fac22020-12-04 15:36:49 -0500434 Analysis::AssignmentInfo info;
John Stiles06b84ef2020-12-09 12:35:48 -0500435 // Assignability was verified at IRGeneration time, so this should always succeed.
436 SkAssertResult(Analysis::IsAssignable(*arguments[index], &info));
437 outVars[index] = info.fAssignedVar;
438 foundOutParam = true;
John Stilesb21fac22020-12-04 15:36:49 -0500439 }
440 }
441
John Stiles06b84ef2020-12-09 12:35:48 -0500442 if (foundOutParam) {
443 // Out parameters need to be written back to at the end of the function. To do this, we
444 // synthesize a helper function which evaluates the out-param expression into a temporary
445 // variable, calls the original function, then writes the temp var back into the out param
446 // using the original out-param expression. (This lets us support things like swizzles and
447 // array indices.)
448 name = getOutParamHelper(c, arguments, outVars);
449 }
450
John Stilesb21fac22020-12-04 15:36:49 -0500451 this->write(name);
Ethan Nicholascc305772017-10-13 16:17:45 -0400452 this->write("(");
453 const char* separator = "";
John Stiles06b84ef2020-12-09 12:35:48 -0500454 this->writeFunctionRequirementArgs(function, separator);
455 for (int i = 0; i < arguments.count(); ++i) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400456 this->write(separator);
457 separator = ", ";
John Stiles06b84ef2020-12-09 12:35:48 -0500458
459 if (outVars[i]) {
460 this->writeExpression(*outVars[i], kSequence_Precedence);
461 } else {
462 this->writeExpression(*arguments[i], kSequence_Precedence);
463 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400464 }
465 this->write(")");
466}
467
John Stilesb21fac22020-12-04 15:36:49 -0500468String MetalCodeGenerator::getInverseHack(const Expression& mat) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400469 const Type& type = mat.type();
470 const String& typeName = type.name();
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500471 String name = typeName + "_inverse";
Ethan Nicholas30d30222020-09-11 12:27:26 -0400472 if (type == *fContext.fFloat2x2_Type || type == *fContext.fHalf2x2_Type) {
Chris Daltondba7aab2018-11-15 10:57:49 -0500473 if (fWrittenIntrinsics.find(name) == fWrittenIntrinsics.end()) {
474 fWrittenIntrinsics.insert(name);
475 fExtraFunctions.writeText((
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500476 typeName + " " + name + "(" + typeName + " m) {"
Chris Daltondba7aab2018-11-15 10:57:49 -0500477 " return float2x2(m[1][1], -m[0][1], -m[1][0], m[0][0]) * (1/determinant(m));"
478 "}"
479 ).c_str());
480 }
481 }
Ethan Nicholas30d30222020-09-11 12:27:26 -0400482 else if (type == *fContext.fFloat3x3_Type || type == *fContext.fHalf3x3_Type) {
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500483 if (fWrittenIntrinsics.find(name) == fWrittenIntrinsics.end()) {
484 fWrittenIntrinsics.insert(name);
485 fExtraFunctions.writeText((
486 typeName + " " + name + "(" + typeName + " m) {"
487 " float a00 = m[0][0], a01 = m[0][1], a02 = m[0][2];"
488 " float a10 = m[1][0], a11 = m[1][1], a12 = m[1][2];"
489 " float a20 = m[2][0], a21 = m[2][1], a22 = m[2][2];"
490 " float b01 = a22 * a11 - a12 * a21;"
491 " float b11 = -a22 * a10 + a12 * a20;"
492 " float b21 = a21 * a10 - a11 * a20;"
493 " float det = a00 * b01 + a01 * b11 + a02 * b21;"
494 " return " + typeName +
495 " (b01, (-a22 * a01 + a02 * a21), (a12 * a01 - a02 * a11),"
496 " b11, (a22 * a00 - a02 * a20), (-a12 * a00 + a02 * a10),"
497 " b21, (-a21 * a00 + a01 * a20), (a11 * a00 - a01 * a10)) * "
498 " (1/det);"
499 "}"
500 ).c_str());
501 }
502 }
Ethan Nicholas30d30222020-09-11 12:27:26 -0400503 else if (type == *fContext.fFloat4x4_Type || type == *fContext.fHalf4x4_Type) {
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500504 if (fWrittenIntrinsics.find(name) == fWrittenIntrinsics.end()) {
505 fWrittenIntrinsics.insert(name);
506 fExtraFunctions.writeText((
507 typeName + " " + name + "(" + typeName + " m) {"
508 " float a00 = m[0][0], a01 = m[0][1], a02 = m[0][2], a03 = m[0][3];"
509 " float a10 = m[1][0], a11 = m[1][1], a12 = m[1][2], a13 = m[1][3];"
510 " float a20 = m[2][0], a21 = m[2][1], a22 = m[2][2], a23 = m[2][3];"
511 " float a30 = m[3][0], a31 = m[3][1], a32 = m[3][2], a33 = m[3][3];"
512 " float b00 = a00 * a11 - a01 * a10;"
513 " float b01 = a00 * a12 - a02 * a10;"
514 " float b02 = a00 * a13 - a03 * a10;"
515 " float b03 = a01 * a12 - a02 * a11;"
516 " float b04 = a01 * a13 - a03 * a11;"
517 " float b05 = a02 * a13 - a03 * a12;"
518 " float b06 = a20 * a31 - a21 * a30;"
519 " float b07 = a20 * a32 - a22 * a30;"
520 " float b08 = a20 * a33 - a23 * a30;"
521 " float b09 = a21 * a32 - a22 * a31;"
522 " float b10 = a21 * a33 - a23 * a31;"
523 " float b11 = a22 * a33 - a23 * a32;"
524 " float det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - "
525 " b04 * b07 + b05 * b06;"
526 " return " + typeName + "(a11 * b11 - a12 * b10 + a13 * b09,"
527 " a02 * b10 - a01 * b11 - a03 * b09,"
528 " a31 * b05 - a32 * b04 + a33 * b03,"
529 " a22 * b04 - a21 * b05 - a23 * b03,"
530 " a12 * b08 - a10 * b11 - a13 * b07,"
531 " a00 * b11 - a02 * b08 + a03 * b07,"
532 " a32 * b02 - a30 * b05 - a33 * b01,"
533 " a20 * b05 - a22 * b02 + a23 * b01,"
534 " a10 * b10 - a11 * b08 + a13 * b06,"
535 " a01 * b08 - a00 * b10 - a03 * b06,"
536 " a30 * b04 - a31 * b02 + a33 * b00,"
537 " a21 * b02 - a20 * b04 - a23 * b00,"
538 " a11 * b07 - a10 * b09 - a12 * b06,"
539 " a00 * b09 - a01 * b07 + a02 * b06,"
540 " a31 * b01 - a30 * b03 - a32 * b00,"
541 " a20 * b03 - a21 * b01 + a22 * b00) / det;"
542 "}"
543 ).c_str());
544 }
545 }
John Stilesb21fac22020-12-04 15:36:49 -0500546 return name;
Chris Daltondba7aab2018-11-15 10:57:49 -0500547}
548
Timothy Liang6403b0e2018-05-17 10:40:04 -0400549void MetalCodeGenerator::writeSpecialIntrinsic(const FunctionCall & c, SpecialIntrinsic kind) {
John Stiles8e3b6be2020-10-13 11:14:08 -0400550 const ExpressionArray& arguments = c.arguments();
Timothy Liang6403b0e2018-05-17 10:40:04 -0400551 switch (kind) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400552 case kTexture_SpecialIntrinsic: {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400553 this->writeExpression(*arguments[0], kSequence_Precedence);
Timothy Lianga06f2152018-05-24 15:33:31 -0400554 this->write(".sample(");
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400555 this->writeExpression(*arguments[0], kSequence_Precedence);
Timothy Lianga06f2152018-05-24 15:33:31 -0400556 this->write(SAMPLER_SUFFIX);
557 this->write(", ");
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400558 const Type& arg1Type = arguments[1]->type();
Ethan Nicholas30d30222020-09-11 12:27:26 -0400559 if (arg1Type == *fContext.fFloat3_Type) {
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500560 // have to store the vector in a temp variable to avoid double evaluating it
561 String tmpVar = "tmpCoord" + to_string(fVarCount++);
Ethan Nicholas30d30222020-09-11 12:27:26 -0400562 this->fFunctionHeader += " " + this->typeName(arg1Type) + " " + tmpVar + ";\n";
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500563 this->write("(" + tmpVar + " = ");
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400564 this->writeExpression(*arguments[1], kSequence_Precedence);
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500565 this->write(", " + tmpVar + ".xy / " + tmpVar + ".z))");
Timothy Liangee84fe12018-05-18 14:38:19 -0400566 } else {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400567 SkASSERT(arg1Type == *fContext.fFloat2_Type);
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400568 this->writeExpression(*arguments[1], kSequence_Precedence);
Timothy Liangee84fe12018-05-18 14:38:19 -0400569 this->write(")");
570 }
Timothy Liang6403b0e2018-05-17 10:40:04 -0400571 break;
Ethan Nicholas30d30222020-09-11 12:27:26 -0400572 }
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500573 case kMod_SpecialIntrinsic: {
Timothy Liang651286f2018-06-07 09:55:33 -0400574 // fmod(x, y) in metal calculates x - y * trunc(x / y) instead of x - y * floor(x / y)
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500575 String tmpX = "tmpX" + to_string(fVarCount++);
576 String tmpY = "tmpY" + to_string(fVarCount++);
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400577 this->fFunctionHeader += " " + this->typeName(arguments[0]->type()) +
Ethan Nicholas30d30222020-09-11 12:27:26 -0400578 " " + tmpX + ", " + tmpY + ";\n";
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500579 this->write("(" + tmpX + " = ");
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400580 this->writeExpression(*arguments[0], kSequence_Precedence);
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500581 this->write(", " + tmpY + " = ");
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400582 this->writeExpression(*arguments[1], kSequence_Precedence);
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500583 this->write(", " + tmpX + " - " + tmpY + " * floor(" + tmpX + " / " + tmpY + "))");
Timothy Liang651286f2018-06-07 09:55:33 -0400584 break;
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500585 }
Brian Osman46787d52020-11-24 14:18:23 -0500586 // GLSL declares scalar versions of most geometric intrinsics, but these don't exist in MSL
587 case kDistance_SpecialIntrinsic: {
588 if (arguments[0]->type().columns() == 1) {
589 this->write("abs(");
590 this->writeExpression(*arguments[0], kAdditive_Precedence);
591 this->write(" - ");
592 this->writeExpression(*arguments[1], kAdditive_Precedence);
593 this->write(")");
594 } else {
595 this->write("distance(");
596 this->writeExpression(*arguments[0], kSequence_Precedence);
597 this->write(", ");
598 this->writeExpression(*arguments[1], kSequence_Precedence);
599 this->write(")");
600 }
601 break;
602 }
603 case kDot_SpecialIntrinsic: {
604 if (arguments[0]->type().columns() == 1) {
605 this->write("(");
606 this->writeExpression(*arguments[0], kMultiplicative_Precedence);
607 this->write(" * ");
608 this->writeExpression(*arguments[1], kMultiplicative_Precedence);
609 this->write(")");
610 } else {
611 this->write("dot(");
612 this->writeExpression(*arguments[0], kSequence_Precedence);
613 this->write(", ");
614 this->writeExpression(*arguments[1], kSequence_Precedence);
615 this->write(")");
616 }
617 break;
618 }
619 case kLength_SpecialIntrinsic: {
620 this->write(arguments[0]->type().columns() == 1 ? "abs(" : "length(");
621 this->writeExpression(*arguments[0], kSequence_Precedence);
622 this->write(")");
623 break;
624 }
625 case kNormalize_SpecialIntrinsic: {
626 this->write(arguments[0]->type().columns() == 1 ? "sign(" : "normalize(");
627 this->writeExpression(*arguments[0], kSequence_Precedence);
628 this->write(")");
629 break;
630 }
Timothy Liang6403b0e2018-05-17 10:40:04 -0400631 default:
632 ABORT("unsupported special intrinsic kind");
633 }
634}
635
John Stilesfcf8cb22020-08-06 14:29:22 -0400636// Assembles a matrix of type floatRxC by resizing another matrix named `x0`.
637// Cells that don't exist in the source matrix will be populated with identity-matrix values.
638void MetalCodeGenerator::assembleMatrixFromMatrix(const Type& sourceMatrix, int rows, int columns) {
639 SkASSERT(rows <= 4);
640 SkASSERT(columns <= 4);
641
642 const char* columnSeparator = "";
643 for (int c = 0; c < columns; ++c) {
644 fExtraFunctions.printf("%sfloat%d(", columnSeparator, rows);
645 columnSeparator = "), ";
646
647 // Determine how many values to take from the source matrix for this row.
648 int swizzleLength = 0;
649 if (c < sourceMatrix.columns()) {
650 swizzleLength = std::min<>(rows, sourceMatrix.rows());
651 }
652
653 // Emit all the values from the source matrix row.
654 bool firstItem;
655 switch (swizzleLength) {
656 case 0: firstItem = true; break;
657 case 1: firstItem = false; fExtraFunctions.printf("x0[%d].x", c); break;
658 case 2: firstItem = false; fExtraFunctions.printf("x0[%d].xy", c); break;
659 case 3: firstItem = false; fExtraFunctions.printf("x0[%d].xyz", c); break;
660 case 4: firstItem = false; fExtraFunctions.printf("x0[%d].xyzw", c); break;
661 default: SkUNREACHABLE;
662 }
663
664 // Emit the placeholder identity-matrix cells.
665 for (int r = swizzleLength; r < rows; ++r) {
666 fExtraFunctions.printf("%s%s", firstItem ? "" : ", ", (r == c) ? "1.0" : "0.0");
667 firstItem = false;
668 }
669 }
670
671 fExtraFunctions.writeText(")");
672}
673
674// Assembles a matrix of type floatRxC by concatenating an arbitrary mix of values, named `x0`,
675// `x1`, etc. An error is written if the expression list don't contain exactly R*C scalars.
John Stiles8e3b6be2020-10-13 11:14:08 -0400676void MetalCodeGenerator::assembleMatrixFromExpressions(const ExpressionArray& args,
677 int rows, int columns) {
John Stilesfcf8cb22020-08-06 14:29:22 -0400678 size_t argIndex = 0;
679 int argPosition = 0;
680
681 const char* columnSeparator = "";
682 for (int c = 0; c < columns; ++c) {
683 fExtraFunctions.printf("%sfloat%d(", columnSeparator, rows);
684 columnSeparator = "), ";
685
686 const char* rowSeparator = "";
687 for (int r = 0; r < rows; ++r) {
688 fExtraFunctions.writeText(rowSeparator);
689 rowSeparator = ", ";
690
691 if (argIndex < args.size()) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400692 const Type& argType = args[argIndex]->type();
Ethan Nicholase6592142020-09-08 10:22:09 -0400693 switch (argType.typeKind()) {
694 case Type::TypeKind::kScalar: {
John Stilesfcf8cb22020-08-06 14:29:22 -0400695 fExtraFunctions.printf("x%zu", argIndex);
696 break;
697 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400698 case Type::TypeKind::kVector: {
John Stilesfcf8cb22020-08-06 14:29:22 -0400699 fExtraFunctions.printf("x%zu[%d]", argIndex, argPosition);
700 break;
701 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400702 case Type::TypeKind::kMatrix: {
John Stilesfcf8cb22020-08-06 14:29:22 -0400703 fExtraFunctions.printf("x%zu[%d][%d]", argIndex,
704 argPosition / argType.rows(),
705 argPosition % argType.rows());
706 break;
707 }
708 default: {
709 SkDEBUGFAIL("incorrect type of argument for matrix constructor");
710 fExtraFunctions.writeText("<error>");
711 break;
712 }
713 }
714
715 ++argPosition;
716 if (argPosition >= argType.columns() * argType.rows()) {
717 ++argIndex;
718 argPosition = 0;
719 }
720 } else {
721 SkDEBUGFAIL("not enough arguments for matrix constructor");
722 fExtraFunctions.writeText("<error>");
723 }
724 }
725 }
726
727 if (argPosition != 0 || argIndex != args.size()) {
728 SkDEBUGFAIL("incorrect number of arguments for matrix constructor");
729 fExtraFunctions.writeText(", <error>");
730 }
731
732 fExtraFunctions.writeText(")");
733}
734
John Stiles1bdafbf2020-05-28 12:17:20 -0400735// Generates a constructor for 'matrix' which reorganizes the input arguments into the proper shape.
736// Keeps track of previously generated constructors so that we won't generate more than one
737// constructor for any given permutation of input argument types. Returns the name of the
738// generated constructor method.
739String MetalCodeGenerator::getMatrixConstructHelper(const Constructor& c) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400740 const Type& matrix = c.type();
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500741 int columns = matrix.columns();
742 int rows = matrix.rows();
John Stiles8e3b6be2020-10-13 11:14:08 -0400743 const ExpressionArray& args = c.arguments();
John Stiles1bdafbf2020-05-28 12:17:20 -0400744
745 // Create the helper-method name and use it as our lookup key.
746 String name;
747 name.appendf("float%dx%d_from", columns, rows);
748 for (const std::unique_ptr<Expression>& expr : args) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400749 name.appendf("_%s", expr->type().displayName().c_str());
John Stiles1bdafbf2020-05-28 12:17:20 -0400750 }
751
752 // If a helper-method has already been synthesized, we don't need to synthesize it again.
753 auto [iter, newlyCreated] = fHelpers.insert(name);
754 if (!newlyCreated) {
755 return name;
756 }
757
758 // Unlike GLSL, Metal requires that matrices are initialized with exactly R vectors of C
759 // components apiece. (In Metal 2.0, you can also supply R*C scalars, but you still cannot
760 // supply a mixture of scalars and vectors.)
761 fExtraFunctions.printf("float%dx%d %s(", columns, rows, name.c_str());
762
763 size_t argIndex = 0;
764 const char* argSeparator = "";
John Stilesfcf8cb22020-08-06 14:29:22 -0400765 for (const std::unique_ptr<Expression>& expr : args) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400766 fExtraFunctions.printf("%s%s x%zu", argSeparator,
Ethan Nicholas30d30222020-09-11 12:27:26 -0400767 expr->type().displayName().c_str(), argIndex++);
John Stiles1bdafbf2020-05-28 12:17:20 -0400768 argSeparator = ", ";
769 }
770
771 fExtraFunctions.printf(") {\n return float%dx%d(", columns, rows);
772
John Stiles9aeed132020-11-24 17:36:06 -0500773 if (args.size() == 1 && args.front()->type().isMatrix()) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400774 this->assembleMatrixFromMatrix(args.front()->type(), rows, columns);
John Stilesfcf8cb22020-08-06 14:29:22 -0400775 } else {
776 this->assembleMatrixFromExpressions(args, rows, columns);
John Stiles1bdafbf2020-05-28 12:17:20 -0400777 }
778
John Stilesfcf8cb22020-08-06 14:29:22 -0400779 fExtraFunctions.writeText(");\n}\n");
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500780 return name;
781}
782
783bool MetalCodeGenerator::canCoerce(const Type& t1, const Type& t2) {
784 if (t1.columns() != t2.columns() || t1.rows() != t2.rows()) {
785 return false;
786 }
787 if (t1.columns() > 1) {
788 return this->canCoerce(t1.componentType(), t2.componentType());
789 }
Ethan Nicholase1f55022019-02-05 17:17:40 -0500790 return t1.isFloat() && t2.isFloat();
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500791}
792
John Stiles1bdafbf2020-05-28 12:17:20 -0400793bool MetalCodeGenerator::matrixConstructHelperIsNeeded(const Constructor& c) {
794 // A matrix construct helper is only necessary if we are, in fact, constructing a matrix.
John Stiles9aeed132020-11-24 17:36:06 -0500795 if (!c.type().isMatrix()) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400796 return false;
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500797 }
John Stiles1bdafbf2020-05-28 12:17:20 -0400798
799 // GLSL is fairly free-form about inputs to its matrix constructors, but Metal is not; it
800 // expects exactly R vectors of C components apiece. (Metal 2.0 also allows a list of R*C
801 // scalars.) Some cases are simple to translate and so we handle those inline--e.g. a list of
802 // scalars can be constructed trivially. In more complex cases, we generate a helper function
803 // that converts our inputs into a properly-shaped matrix.
804 // A matrix construct helper method is always used if any input argument is a matrix.
805 // Helper methods are also necessary when any argument would span multiple rows. For instance:
806 //
807 // float2 x = (1, 2);
808 // float3x2(x, 3, 4, 5, 6) = | 1 3 5 | = no helper needed; conversion can be done inline
809 // | 2 4 6 |
810 //
811 // float2 x = (2, 3);
812 // float3x2(1, x, 4, 5, 6) = | 1 3 5 | = x spans multiple rows; a helper method will be used
813 // | 2 4 6 |
814 //
815 // float4 x = (1, 2, 3, 4);
816 // float2x2(x) = | 1 3 | = x spans multiple rows; a helper method will be used
817 // | 2 4 |
818 //
819
820 int position = 0;
Ethan Nicholasf70f0442020-09-29 12:41:35 -0400821 for (const std::unique_ptr<Expression>& expr : c.arguments()) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400822 // If an input argument is a matrix, we need a helper function.
John Stiles9aeed132020-11-24 17:36:06 -0500823 if (expr->type().isMatrix()) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400824 return true;
825 }
Ethan Nicholas30d30222020-09-11 12:27:26 -0400826 position += expr->type().columns();
827 if (position > c.type().rows()) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400828 // An input argument would span multiple rows; a helper function is required.
829 return true;
830 }
Ethan Nicholas30d30222020-09-11 12:27:26 -0400831 if (position == c.type().rows()) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400832 // We've advanced to the end of a row. Wrap to the start of the next row.
833 position = 0;
834 }
835 }
836
837 return false;
838}
839
840void MetalCodeGenerator::writeConstructor(const Constructor& c, Precedence parentPrecedence) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400841 const Type& constructorType = c.type();
John Stiles1bdafbf2020-05-28 12:17:20 -0400842 // Handle special cases for single-argument constructors.
Ethan Nicholasf70f0442020-09-29 12:41:35 -0400843 if (c.arguments().size() == 1) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400844 // If the type is coercible, emit it directly.
Ethan Nicholasf70f0442020-09-29 12:41:35 -0400845 const Expression& arg = *c.arguments().front();
Ethan Nicholas30d30222020-09-11 12:27:26 -0400846 const Type& argType = arg.type();
847 if (this->canCoerce(constructorType, argType)) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400848 this->writeExpression(arg, parentPrecedence);
849 return;
850 }
851
852 // Metal supports creating matrices with a scalar on the diagonal via the single-argument
853 // matrix constructor.
John Stiles9aeed132020-11-24 17:36:06 -0500854 if (constructorType.isMatrix() && argType.isNumber()) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400855 const Type& matrix = constructorType;
John Stiles1bdafbf2020-05-28 12:17:20 -0400856 this->write("float");
857 this->write(to_string(matrix.columns()));
858 this->write("x");
859 this->write(to_string(matrix.rows()));
860 this->write("(");
861 this->writeExpression(arg, parentPrecedence);
862 this->write(")");
863 return;
864 }
865 }
866
867 // Emit and invoke a matrix-constructor helper method if one is necessary.
868 if (this->matrixConstructHelperIsNeeded(c)) {
869 this->write(this->getMatrixConstructHelper(c));
John Stiles1fa15b12020-05-28 17:36:54 +0000870 this->write("(");
871 const char* separator = "";
Ethan Nicholasf70f0442020-09-29 12:41:35 -0400872 for (const std::unique_ptr<Expression>& expr : c.arguments()) {
John Stiles1fa15b12020-05-28 17:36:54 +0000873 this->write(separator);
874 separator = ", ";
John Stiles1bdafbf2020-05-28 12:17:20 -0400875 this->writeExpression(*expr, kSequence_Precedence);
John Stilesdaa573e2020-05-28 12:17:20 -0400876 }
John Stiles1fa15b12020-05-28 17:36:54 +0000877 this->write(")");
John Stiles1bdafbf2020-05-28 12:17:20 -0400878 return;
John Stilesdaa573e2020-05-28 12:17:20 -0400879 }
John Stiles1bdafbf2020-05-28 12:17:20 -0400880
881 // Explicitly invoke the constructor, passing in the necessary arguments.
John Stiles3dba3ee2020-12-02 23:35:49 -0500882 this->writeBaseType(constructorType);
883 this->disallowArrayTypes(constructorType); // constructors of array types aren't valid exprs
John Stiles1bdafbf2020-05-28 12:17:20 -0400884 this->write("(");
885 const char* separator = "";
886 int scalarCount = 0;
Ethan Nicholasf70f0442020-09-29 12:41:35 -0400887 for (const std::unique_ptr<Expression>& arg : c.arguments()) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400888 const Type& argType = arg->type();
John Stiles1bdafbf2020-05-28 12:17:20 -0400889 this->write(separator);
890 separator = ", ";
John Stiles9aeed132020-11-24 17:36:06 -0500891 if (constructorType.isMatrix() &&
Ethan Nicholas30d30222020-09-11 12:27:26 -0400892 argType.columns() < constructorType.rows()) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400893 // Merge scalars and smaller vectors together.
894 if (!scalarCount) {
John Stiles3dba3ee2020-12-02 23:35:49 -0500895 this->writeBaseType(constructorType.componentType());
Ethan Nicholas30d30222020-09-11 12:27:26 -0400896 this->write(to_string(constructorType.rows()));
John Stiles1bdafbf2020-05-28 12:17:20 -0400897 this->write("(");
898 }
Ethan Nicholas30d30222020-09-11 12:27:26 -0400899 scalarCount += argType.columns();
John Stiles1bdafbf2020-05-28 12:17:20 -0400900 }
901 this->writeExpression(*arg, kSequence_Precedence);
Ethan Nicholas30d30222020-09-11 12:27:26 -0400902 if (scalarCount && scalarCount == constructorType.rows()) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400903 this->write(")");
904 scalarCount = 0;
905 }
906 }
907 this->write(")");
Ethan Nicholascc305772017-10-13 16:17:45 -0400908}
909
910void MetalCodeGenerator::writeFragCoord() {
Ethan Nicholasf931e402019-07-26 15:40:33 -0400911 if (fRTHeightName.length()) {
912 this->write("float4(_fragCoord.x, ");
913 this->write(fRTHeightName.c_str());
914 this->write(" - _fragCoord.y, 0.0, _fragCoord.w)");
Jim Van Verth6bc650e2019-02-07 14:53:23 -0500915 } else {
916 this->write("float4(_fragCoord.x, _fragCoord.y, 0.0, _fragCoord.w)");
917 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400918}
919
920void MetalCodeGenerator::writeVariableReference(const VariableReference& ref) {
John Stiles06b84ef2020-12-09 12:35:48 -0500921 // When assembling out-param helper functions, we copy variables into local clones with matching
922 // names. We never want to prepend "_in." or "_globals->" when writing these variables since
923 // we're actually targeting the clones.
924 if (fIgnoreVariableReferenceModifiers) {
925 this->writeName(ref.variable()->name());
926 return;
927 }
928
Ethan Nicholas78686922020-10-08 06:46:27 -0400929 switch (ref.variable()->modifiers().fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400930 case SK_FRAGCOLOR_BUILTIN:
Timothy Liang7d637782018-06-05 09:58:07 -0400931 this->write("_out->sk_FragColor");
Ethan Nicholascc305772017-10-13 16:17:45 -0400932 break;
Timothy Liang6403b0e2018-05-17 10:40:04 -0400933 case SK_FRAGCOORD_BUILTIN:
934 this->writeFragCoord();
935 break;
Timothy Liangdc89f192018-06-13 09:20:31 -0400936 case SK_VERTEXID_BUILTIN:
937 this->write("sk_VertexID");
938 break;
939 case SK_INSTANCEID_BUILTIN:
940 this->write("sk_InstanceID");
941 break;
Timothy Liang7b8875d2018-08-10 09:42:31 -0400942 case SK_CLOCKWISE_BUILTIN:
943 // We'd set the front facing winding in the MTLRenderCommandEncoder to be counter
Brian Salomonf4ba4ec2020-03-19 15:54:28 -0400944 // clockwise to match Skia convention.
Timothy Liang7b8875d2018-08-10 09:42:31 -0400945 this->write(fProgram.fSettings.fFlipY ? "_frontFacing" : "(!_frontFacing)");
946 break;
Ethan Nicholascc305772017-10-13 16:17:45 -0400947 default:
Ethan Nicholas78686922020-10-08 06:46:27 -0400948 const Variable& var = *ref.variable();
Ethan Nicholas453f67f2020-10-09 10:43:45 -0400949 if (var.storage() == Variable::Storage::kGlobal) {
Ethan Nicholas78686922020-10-08 06:46:27 -0400950 if (var.modifiers().fFlags & Modifiers::kIn_Flag) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400951 this->write("_in.");
Ethan Nicholas78686922020-10-08 06:46:27 -0400952 } else if (var.modifiers().fFlags & Modifiers::kOut_Flag) {
Timothy Liangee84fe12018-05-18 14:38:19 -0400953 this->write("_out->");
Ethan Nicholas78686922020-10-08 06:46:27 -0400954 } else if (var.modifiers().fFlags & Modifiers::kUniform_Flag &&
955 var.type().typeKind() != Type::TypeKind::kSampler) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400956 this->write("_uniforms.");
957 } else {
Timothy Liangee84fe12018-05-18 14:38:19 -0400958 this->write("_globals->");
Ethan Nicholascc305772017-10-13 16:17:45 -0400959 }
960 }
Ethan Nicholas78686922020-10-08 06:46:27 -0400961 this->writeName(var.name());
Ethan Nicholascc305772017-10-13 16:17:45 -0400962 }
963}
964
965void MetalCodeGenerator::writeIndexExpression(const IndexExpression& expr) {
Ethan Nicholas2a4952d2020-10-08 15:35:56 -0400966 this->writeExpression(*expr.base(), kPostfix_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400967 this->write("[");
Ethan Nicholas2a4952d2020-10-08 15:35:56 -0400968 this->writeExpression(*expr.index(), kTopLevel_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400969 this->write("]");
970}
971
972void MetalCodeGenerator::writeFieldAccess(const FieldAccess& f) {
Ethan Nicholas7a95b202020-10-09 11:55:40 -0400973 const Type::Field* field = &f.base()->type().fields()[f.fieldIndex()];
974 if (FieldAccess::OwnerKind::kDefault == f.ownerKind()) {
975 this->writeExpression(*f.base(), kPostfix_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400976 this->write(".");
977 }
Timothy Liang7d637782018-06-05 09:58:07 -0400978 switch (field->fModifiers.fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400979 case SK_POSITION_BUILTIN:
Timothy Liangb8eeb802018-07-23 16:46:16 -0400980 this->write("_out->sk_Position");
Ethan Nicholascc305772017-10-13 16:17:45 -0400981 break;
982 default:
Timothy Liang7d637782018-06-05 09:58:07 -0400983 if (field->fName == "sk_PointSize") {
984 this->write("_out->sk_PointSize");
985 } else {
Ethan Nicholas7a95b202020-10-09 11:55:40 -0400986 if (FieldAccess::OwnerKind::kAnonymousInterfaceBlock == f.ownerKind()) {
Timothy Liang7d637782018-06-05 09:58:07 -0400987 this->write("_globals->");
988 this->write(fInterfaceBlockNameMap[fInterfaceBlockMap[field]]);
989 this->write("->");
990 }
Timothy Liang651286f2018-06-07 09:55:33 -0400991 this->writeName(field->fName);
Timothy Lianga06f2152018-05-24 15:33:31 -0400992 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400993 }
994}
995
996void MetalCodeGenerator::writeSwizzle(const Swizzle& swizzle) {
Ethan Nicholas6b4d5812020-10-12 16:11:51 -0400997 this->writeExpression(*swizzle.base(), kPostfix_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400998 this->write(".");
Ethan Nicholas6b4d5812020-10-12 16:11:51 -0400999 for (int c : swizzle.components()) {
Brian Osman25647672020-09-15 15:16:56 -04001000 SkASSERT(c >= 0 && c <= 3);
1001 this->write(&("x\0y\0z\0w\0"[c * 2]));
Ethan Nicholascc305772017-10-13 16:17:45 -04001002 }
1003}
1004
1005MetalCodeGenerator::Precedence MetalCodeGenerator::GetBinaryPrecedence(Token::Kind op) {
1006 switch (op) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001007 case Token::Kind::TK_STAR: // fall through
1008 case Token::Kind::TK_SLASH: // fall through
1009 case Token::Kind::TK_PERCENT: return MetalCodeGenerator::kMultiplicative_Precedence;
1010 case Token::Kind::TK_PLUS: // fall through
1011 case Token::Kind::TK_MINUS: return MetalCodeGenerator::kAdditive_Precedence;
1012 case Token::Kind::TK_SHL: // fall through
1013 case Token::Kind::TK_SHR: return MetalCodeGenerator::kShift_Precedence;
1014 case Token::Kind::TK_LT: // fall through
1015 case Token::Kind::TK_GT: // fall through
1016 case Token::Kind::TK_LTEQ: // fall through
1017 case Token::Kind::TK_GTEQ: return MetalCodeGenerator::kRelational_Precedence;
1018 case Token::Kind::TK_EQEQ: // fall through
1019 case Token::Kind::TK_NEQ: return MetalCodeGenerator::kEquality_Precedence;
1020 case Token::Kind::TK_BITWISEAND: return MetalCodeGenerator::kBitwiseAnd_Precedence;
1021 case Token::Kind::TK_BITWISEXOR: return MetalCodeGenerator::kBitwiseXor_Precedence;
1022 case Token::Kind::TK_BITWISEOR: return MetalCodeGenerator::kBitwiseOr_Precedence;
1023 case Token::Kind::TK_LOGICALAND: return MetalCodeGenerator::kLogicalAnd_Precedence;
1024 case Token::Kind::TK_LOGICALXOR: return MetalCodeGenerator::kLogicalXor_Precedence;
1025 case Token::Kind::TK_LOGICALOR: return MetalCodeGenerator::kLogicalOr_Precedence;
1026 case Token::Kind::TK_EQ: // fall through
1027 case Token::Kind::TK_PLUSEQ: // fall through
1028 case Token::Kind::TK_MINUSEQ: // fall through
1029 case Token::Kind::TK_STAREQ: // fall through
1030 case Token::Kind::TK_SLASHEQ: // fall through
1031 case Token::Kind::TK_PERCENTEQ: // fall through
1032 case Token::Kind::TK_SHLEQ: // fall through
1033 case Token::Kind::TK_SHREQ: // fall through
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001034 case Token::Kind::TK_BITWISEANDEQ: // fall through
1035 case Token::Kind::TK_BITWISEXOREQ: // fall through
1036 case Token::Kind::TK_BITWISEOREQ: return MetalCodeGenerator::kAssignment_Precedence;
1037 case Token::Kind::TK_COMMA: return MetalCodeGenerator::kSequence_Precedence;
Ethan Nicholascc305772017-10-13 16:17:45 -04001038 default: ABORT("unsupported binary operator");
1039 }
1040}
1041
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001042void MetalCodeGenerator::writeMatrixTimesEqualHelper(const Type& left, const Type& right,
1043 const Type& result) {
1044 String key = "TimesEqual" + left.name() + right.name();
1045 if (fHelpers.find(key) == fHelpers.end()) {
1046 fExtraFunctions.printf("%s operator*=(thread %s& left, thread const %s& right) {\n"
1047 " left = left * right;\n"
1048 " return left;\n"
Ethan Nicholase2c49992020-10-05 11:49:11 -04001049 "}", String(result.name()).c_str(), String(left.name()).c_str(),
1050 String(right.name()).c_str());
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001051 }
1052}
1053
Ethan Nicholascc305772017-10-13 16:17:45 -04001054void MetalCodeGenerator::writeBinaryExpression(const BinaryExpression& b,
1055 Precedence parentPrecedence) {
John Stiles2d4f9592020-10-30 10:29:12 -04001056 const Expression& left = *b.left();
1057 const Expression& right = *b.right();
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001058 const Type& leftType = left.type();
1059 const Type& rightType = right.type();
1060 Token::Kind op = b.getOperator();
1061 Precedence precedence = GetBinaryPrecedence(b.getOperator());
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001062 bool needParens = precedence >= parentPrecedence;
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001063 switch (op) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001064 case Token::Kind::TK_EQEQ:
John Stiles9aeed132020-11-24 17:36:06 -05001065 if (leftType.isVector()) {
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001066 this->write("all");
1067 needParens = true;
1068 }
1069 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001070 case Token::Kind::TK_NEQ:
John Stiles9aeed132020-11-24 17:36:06 -05001071 if (leftType.isVector()) {
Jim Van Verth36477b42019-04-11 14:57:30 -04001072 this->write("any");
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001073 needParens = true;
1074 }
1075 break;
1076 default:
1077 break;
1078 }
1079 if (needParens) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001080 this->write("(");
1081 }
John Stiles9aeed132020-11-24 17:36:06 -05001082 if (op == Token::Kind::TK_STAREQ && leftType.isMatrix() && rightType.isMatrix()) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001083 this->writeMatrixTimesEqualHelper(leftType, rightType, b.type());
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001084 }
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001085 this->writeExpression(left, precedence);
1086 if (op != Token::Kind::TK_EQ && Compiler::IsAssignment(op) &&
1087 left.kind() == Expression::Kind::kSwizzle && !left.hasSideEffects()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001088 // This doesn't compile in Metal:
1089 // float4 x = float4(1);
1090 // x.xy *= float2x2(...);
1091 // with the error message "non-const reference cannot bind to vector element",
1092 // but switching it to x.xy = x.xy * float2x2(...) fixes it. We perform this tranformation
1093 // as long as the LHS has no side effects, and hope for the best otherwise.
1094 this->write(" = ");
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001095 this->writeExpression(left, kAssignment_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001096 this->write(" ");
John Stilesd6449e92020-11-30 09:13:23 -05001097 String opName = OperatorName(op);
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001098 SkASSERT(opName.endsWith("="));
1099 this->write(opName.substr(0, opName.size() - 1).c_str());
Ethan Nicholascc305772017-10-13 16:17:45 -04001100 this->write(" ");
1101 } else {
John Stilesd6449e92020-11-30 09:13:23 -05001102 this->write(String(" ") + OperatorName(op) + " ");
Ethan Nicholascc305772017-10-13 16:17:45 -04001103 }
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001104 this->writeExpression(right, precedence);
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001105 if (needParens) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001106 this->write(")");
1107 }
1108}
1109
1110void MetalCodeGenerator::writeTernaryExpression(const TernaryExpression& t,
1111 Precedence parentPrecedence) {
1112 if (kTernary_Precedence >= parentPrecedence) {
1113 this->write("(");
1114 }
Ethan Nicholasdd218162020-10-08 05:48:01 -04001115 this->writeExpression(*t.test(), kTernary_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001116 this->write(" ? ");
Ethan Nicholasdd218162020-10-08 05:48:01 -04001117 this->writeExpression(*t.ifTrue(), kTernary_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001118 this->write(" : ");
Ethan Nicholasdd218162020-10-08 05:48:01 -04001119 this->writeExpression(*t.ifFalse(), kTernary_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001120 if (kTernary_Precedence >= parentPrecedence) {
1121 this->write(")");
1122 }
1123}
1124
1125void MetalCodeGenerator::writePrefixExpression(const PrefixExpression& p,
1126 Precedence parentPrecedence) {
1127 if (kPrefix_Precedence >= parentPrecedence) {
1128 this->write("(");
1129 }
John Stilesd6449e92020-11-30 09:13:23 -05001130 this->write(OperatorName(p.getOperator()));
Ethan Nicholas444ccc62020-10-09 10:16:22 -04001131 this->writeExpression(*p.operand(), kPrefix_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001132 if (kPrefix_Precedence >= parentPrecedence) {
1133 this->write(")");
1134 }
1135}
1136
1137void MetalCodeGenerator::writePostfixExpression(const PostfixExpression& p,
1138 Precedence parentPrecedence) {
1139 if (kPostfix_Precedence >= parentPrecedence) {
1140 this->write("(");
1141 }
Ethan Nicholas444ccc62020-10-09 10:16:22 -04001142 this->writeExpression(*p.operand(), kPostfix_Precedence);
John Stilesd6449e92020-11-30 09:13:23 -05001143 this->write(OperatorName(p.getOperator()));
Ethan Nicholascc305772017-10-13 16:17:45 -04001144 if (kPostfix_Precedence >= parentPrecedence) {
1145 this->write(")");
1146 }
1147}
1148
1149void MetalCodeGenerator::writeBoolLiteral(const BoolLiteral& b) {
Ethan Nicholas59d660c2020-09-28 09:18:15 -04001150 this->write(b.value() ? "true" : "false");
Ethan Nicholascc305772017-10-13 16:17:45 -04001151}
1152
1153void MetalCodeGenerator::writeIntLiteral(const IntLiteral& i) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001154 if (i.type() == *fContext.fUInt_Type) {
Ethan Nicholase96cdd12020-09-28 16:27:18 -04001155 this->write(to_string(i.value() & 0xffffffff) + "u");
Ethan Nicholascc305772017-10-13 16:17:45 -04001156 } else {
Ethan Nicholase96cdd12020-09-28 16:27:18 -04001157 this->write(to_string((int32_t) i.value()));
Ethan Nicholascc305772017-10-13 16:17:45 -04001158 }
1159}
1160
1161void MetalCodeGenerator::writeFloatLiteral(const FloatLiteral& f) {
Ethan Nicholasa3f22f12020-10-01 12:13:17 -04001162 this->write(to_string(f.value()));
Ethan Nicholascc305772017-10-13 16:17:45 -04001163}
1164
1165void MetalCodeGenerator::writeSetting(const Setting& s) {
1166 ABORT("internal error; setting was not folded to a constant during compilation\n");
1167}
1168
John Stiles06b84ef2020-12-09 12:35:48 -05001169void MetalCodeGenerator::writeFunctionRequirementArgs(const FunctionDeclaration& f,
1170 const char*& separator) {
1171 Requirements requirements = this->requirements(f);
1172 if (requirements & kInputs_Requirement) {
1173 this->write(separator);
1174 this->write("_in");
1175 separator = ", ";
1176 }
1177 if (requirements & kOutputs_Requirement) {
1178 this->write(separator);
1179 this->write("_out");
1180 separator = ", ";
1181 }
1182 if (requirements & kUniforms_Requirement) {
1183 this->write(separator);
1184 this->write("_uniforms");
1185 separator = ", ";
1186 }
1187 if (requirements & kGlobals_Requirement) {
1188 this->write(separator);
1189 this->write("_globals");
1190 separator = ", ";
1191 }
1192 if (requirements & kFragCoord_Requirement) {
1193 this->write(separator);
1194 this->write("_fragCoord");
1195 separator = ", ";
1196 }
1197}
1198
1199void MetalCodeGenerator::writeFunctionRequirementParams(const FunctionDeclaration& f,
1200 const char*& separator) {
1201 Requirements requirements = this->requirements(f);
1202 if (requirements & kInputs_Requirement) {
1203 this->write(separator);
1204 this->write("Inputs _in");
1205 separator = ", ";
1206 }
1207 if (requirements & kOutputs_Requirement) {
1208 this->write(separator);
1209 this->write("thread Outputs* _out");
1210 separator = ", ";
1211 }
1212 if (requirements & kUniforms_Requirement) {
1213 this->write(separator);
1214 this->write("Uniforms _uniforms");
1215 separator = ", ";
1216 }
1217 if (requirements & kGlobals_Requirement) {
1218 this->write(separator);
1219 this->write("thread Globals* _globals");
1220 separator = ", ";
1221 }
1222 if (requirements & kFragCoord_Requirement) {
1223 this->write(separator);
1224 this->write("float4 _fragCoord");
1225 separator = ", ";
1226 }
1227}
1228
John Stiles569249b2020-11-03 12:18:22 -05001229bool MetalCodeGenerator::writeFunctionDeclaration(const FunctionDeclaration& f) {
Ethan Nicholasf931e402019-07-26 15:40:33 -04001230 fRTHeightName = fProgram.fInputs.fRTHeight ? "_globals->_anonInterface0->u_skRTHeight" : "";
Ethan Nicholascc305772017-10-13 16:17:45 -04001231 const char* separator = "";
John Stiles569249b2020-11-03 12:18:22 -05001232 if ("main" == f.name()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001233 switch (fProgram.fKind) {
1234 case Program::kFragment_Kind:
Timothy Liangb8eeb802018-07-23 16:46:16 -04001235 this->write("fragment Outputs fragmentMain");
Ethan Nicholascc305772017-10-13 16:17:45 -04001236 break;
1237 case Program::kVertex_Kind:
Timothy Liangb8eeb802018-07-23 16:46:16 -04001238 this->write("vertex Outputs vertexMain");
Ethan Nicholascc305772017-10-13 16:17:45 -04001239 break;
1240 default:
John Stiles3fabfc02020-09-25 15:51:28 -04001241 fErrors.error(-1, "unsupported kind of program");
John Stiles569249b2020-11-03 12:18:22 -05001242 return false;
Ethan Nicholascc305772017-10-13 16:17:45 -04001243 }
1244 this->write("(Inputs _in [[stage_in]]");
1245 if (-1 != fUniformBuffer) {
1246 this->write(", constant Uniforms& _uniforms [[buffer(" +
1247 to_string(fUniformBuffer) + ")]]");
1248 }
Brian Osman133724c2020-10-28 14:14:39 -04001249 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04001250 if (e->is<GlobalVarDeclaration>()) {
1251 const GlobalVarDeclaration& decls = e->as<GlobalVarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001252 const VarDeclaration& var = decls.declaration()->as<VarDeclaration>();
1253 if (var.var().type().typeKind() == Type::TypeKind::kSampler) {
1254 if (var.var().modifiers().fLayout.fBinding < 0) {
Brian Osmanc0213602020-10-06 14:43:32 -04001255 fErrors.error(decls.fOffset,
1256 "Metal samplers must have 'layout(binding=...)'");
John Stiles569249b2020-11-03 12:18:22 -05001257 return false;
Timothy Liangee84fe12018-05-18 14:38:19 -04001258 }
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001259 if (var.var().type().dimensions() != SpvDim2D) {
John Stiles569249b2020-11-03 12:18:22 -05001260 // Not yet implemented--Skia currently only uses 2D textures.
Brian Osmanc0213602020-10-06 14:43:32 -04001261 fErrors.error(decls.fOffset, "Unsupported texture dimensions");
John Stiles569249b2020-11-03 12:18:22 -05001262 return false;
Brian Osmanc0213602020-10-06 14:43:32 -04001263 }
1264 this->write(", texture2d<float> ");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001265 this->writeName(var.var().name());
Brian Osmanc0213602020-10-06 14:43:32 -04001266 this->write("[[texture(");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001267 this->write(to_string(var.var().modifiers().fLayout.fBinding));
Brian Osmanc0213602020-10-06 14:43:32 -04001268 this->write(")]]");
1269 this->write(", sampler ");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001270 this->writeName(var.var().name());
Brian Osmanc0213602020-10-06 14:43:32 -04001271 this->write(SAMPLER_SUFFIX);
1272 this->write("[[sampler(");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001273 this->write(to_string(var.var().modifiers().fLayout.fBinding));
Brian Osmanc0213602020-10-06 14:43:32 -04001274 this->write(")]]");
Timothy Liang6403b0e2018-05-17 10:40:04 -04001275 }
Brian Osman1179fcf2020-10-08 16:04:40 -04001276 } else if (e->is<InterfaceBlock>()) {
1277 const InterfaceBlock& intf = e->as<InterfaceBlock>();
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001278 if (intf.typeName() == "sk_PerVertex") {
Timothy Lianga06f2152018-05-24 15:33:31 -04001279 continue;
1280 }
John Stilesbc3c41b2020-12-04 10:52:40 -05001281 if (intf.variable().modifiers().fLayout.fBinding < 0) {
1282 fErrors.error(intf.fOffset,
1283 "Metal interface blocks must have 'layout(binding=...)'");
1284 return false;
1285 }
Timothy Lianga06f2152018-05-24 15:33:31 -04001286 this->write(", constant ");
John Stiles3dba3ee2020-12-02 23:35:49 -05001287 this->writeBaseType(intf.variable().type());
Timothy Lianga06f2152018-05-24 15:33:31 -04001288 this->write("& " );
1289 this->write(fInterfaceBlockNameMap[&intf]);
1290 this->write(" [[buffer(");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001291 this->write(to_string(intf.variable().modifiers().fLayout.fBinding));
Timothy Lianga06f2152018-05-24 15:33:31 -04001292 this->write(")]]");
Timothy Liang6403b0e2018-05-17 10:40:04 -04001293 }
1294 }
Jim Van Verth6bc650e2019-02-07 14:53:23 -05001295 if (fProgram.fKind == Program::kFragment_Kind) {
1296 if (fProgram.fInputs.fRTHeight && fInterfaceBlockNameMap.empty()) {
Timothy Liang5422f9a2018-08-10 10:57:55 -04001297 this->write(", constant sksl_synthetic_uniforms& _anonInterface0 [[buffer(1)]]");
Ethan Nicholasf931e402019-07-26 15:40:33 -04001298 fRTHeightName = "_anonInterface0.u_skRTHeight";
Timothy Liang5422f9a2018-08-10 10:57:55 -04001299 }
Timothy Liang7b8875d2018-08-10 09:42:31 -04001300 this->write(", bool _frontFacing [[front_facing]]");
Timothy Liang7d637782018-06-05 09:58:07 -04001301 this->write(", float4 _fragCoord [[position]]");
Timothy Liangdc89f192018-06-13 09:20:31 -04001302 } else if (fProgram.fKind == Program::kVertex_Kind) {
1303 this->write(", uint sk_VertexID [[vertex_id]], uint sk_InstanceID [[instance_id]]");
Timothy Liang7d637782018-06-05 09:58:07 -04001304 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001305 separator = ", ";
1306 } else {
John Stiles3dba3ee2020-12-02 23:35:49 -05001307 this->writeBaseType(f.returnType());
1308 this->disallowArrayTypes(f.returnType()); // return types can't be arrays in SkSL/GLSL
Timothy Liang651286f2018-06-07 09:55:33 -04001309 this->write(" ");
John Stiles569249b2020-11-03 12:18:22 -05001310 this->writeName(f.name());
Timothy Liang651286f2018-06-07 09:55:33 -04001311 this->write("(");
John Stiles06b84ef2020-12-09 12:35:48 -05001312 this->writeFunctionRequirementParams(f, separator);
Ethan Nicholascc305772017-10-13 16:17:45 -04001313 }
John Stiles569249b2020-11-03 12:18:22 -05001314 for (const auto& param : f.parameters()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001315 this->write(separator);
1316 separator = ", ";
John Stiles06b84ef2020-12-09 12:35:48 -05001317 this->writeModifiers(param->modifiers(), /*globalContext=*/false);
Ethan Nicholas30d30222020-09-11 12:27:26 -04001318 const Type* type = &param->type();
John Stiles3dba3ee2020-12-02 23:35:49 -05001319 this->writeBaseType(*type);
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001320 if (param->modifiers().fFlags & Modifiers::kOut_Flag) {
John Stilesf2bd5012020-12-04 11:58:26 -05001321 this->write("&");
Ethan Nicholascc305772017-10-13 16:17:45 -04001322 }
Timothy Liang651286f2018-06-07 09:55:33 -04001323 this->write(" ");
Ethan Nicholase2c49992020-10-05 11:49:11 -04001324 this->writeName(param->name());
John Stiles3dba3ee2020-12-02 23:35:49 -05001325 this->writeArrayDimensions(*type);
Ethan Nicholascc305772017-10-13 16:17:45 -04001326 }
John Stiles569249b2020-11-03 12:18:22 -05001327 this->write(")");
1328 return true;
1329}
Ethan Nicholascc305772017-10-13 16:17:45 -04001330
John Stiles569249b2020-11-03 12:18:22 -05001331void MetalCodeGenerator::writeFunctionPrototype(const FunctionPrototype& f) {
1332 this->writeFunctionDeclaration(f.declaration());
1333 this->writeLine(";");
1334}
1335
John Stiles986c7fb2020-12-01 14:44:56 -05001336static bool is_block_ending_with_return(const Statement* stmt) {
1337 // This function detects (potentially nested) blocks that end in a return statement.
1338 if (!stmt->is<Block>()) {
1339 return false;
1340 }
1341 const StatementArray& block = stmt->as<Block>().children();
1342 for (int index = block.count(); index--; ) {
1343 const Statement& stmt = *block[index];
1344 if (stmt.is<ReturnStatement>()) {
1345 return true;
1346 }
1347 if (stmt.is<Block>()) {
1348 return is_block_ending_with_return(&stmt);
1349 }
1350 if (!stmt.is<Nop>()) {
1351 break;
1352 }
1353 }
1354 return false;
1355}
1356
John Stiles569249b2020-11-03 12:18:22 -05001357void MetalCodeGenerator::writeFunction(const FunctionDefinition& f) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001358 SkASSERT(!fProgram.fSettings.fFragColorIsInOut);
Brian Salomondc092132018-04-04 10:14:16 -04001359
John Stiles569249b2020-11-03 12:18:22 -05001360 if (!this->writeFunctionDeclaration(f.declaration())) {
1361 return;
1362 }
1363
John Stiles986c7fb2020-12-01 14:44:56 -05001364 fCurrentFunction = &f.declaration();
1365 SkScopeExit clearCurrentFunction([&] { fCurrentFunction = nullptr; });
1366
John Stiles569249b2020-11-03 12:18:22 -05001367 this->writeLine(" {");
1368
Ethan Nicholas0a5d0962020-10-14 13:33:18 -04001369 if (f.declaration().name() == "main") {
John Stilescdcdb042020-07-06 09:03:51 -04001370 this->writeGlobalInit();
Timothy Liang7d637782018-06-05 09:58:07 -04001371 this->writeLine(" Outputs _outputStruct;");
1372 this->writeLine(" thread Outputs* _out = &_outputStruct;");
Ethan Nicholascc305772017-10-13 16:17:45 -04001373 }
John Stilesc67b3622020-05-28 17:53:13 -04001374
Ethan Nicholascc305772017-10-13 16:17:45 -04001375 fFunctionHeader = "";
Ethan Nicholascc305772017-10-13 16:17:45 -04001376 StringStream buffer;
John Stiles44532372020-12-07 12:33:55 -05001377 {
1378 AutoOutputStream outputToBuffer(this, &buffer);
1379 fIndentation++;
1380 for (const std::unique_ptr<Statement>& stmt : f.body()->as<Block>().children()) {
1381 if (!stmt->isEmpty()) {
1382 this->writeStatement(*stmt);
1383 this->writeLine();
1384 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001385 }
John Stiles44532372020-12-07 12:33:55 -05001386 if (f.declaration().name() == "main") {
1387 // If the main function doesn't end with a return, we need to synthesize one here.
1388 if (!is_block_ending_with_return(f.body().get())) {
1389 this->writeReturnStatementFromMain();
1390 this->writeLine("");
1391 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001392 }
John Stiles44532372020-12-07 12:33:55 -05001393 fIndentation--;
1394 this->writeLine("}");
Ethan Nicholascc305772017-10-13 16:17:45 -04001395 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001396 this->write(fFunctionHeader);
1397 this->write(buffer.str());
1398}
1399
1400void MetalCodeGenerator::writeModifiers(const Modifiers& modifiers,
John Stiles06b84ef2020-12-09 12:35:48 -05001401 bool globalContext) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001402 if (modifiers.fFlags & Modifiers::kOut_Flag) {
1403 this->write("thread ");
1404 }
1405 if (modifiers.fFlags & Modifiers::kConst_Flag) {
Timothy Liangee84fe12018-05-18 14:38:19 -04001406 this->write("constant ");
Ethan Nicholascc305772017-10-13 16:17:45 -04001407 }
1408}
1409
1410void MetalCodeGenerator::writeInterfaceBlock(const InterfaceBlock& intf) {
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001411 if ("sk_PerVertex" == intf.typeName()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001412 return;
1413 }
John Stiles06b84ef2020-12-09 12:35:48 -05001414 this->writeModifiers(intf.variable().modifiers(), /*globalContext=*/true);
Timothy Liangdc89f192018-06-13 09:20:31 -04001415 this->write("struct ");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001416 this->writeLine(intf.typeName() + " {");
1417 const Type* structType = &intf.variable().type();
John Stilesbb43b7e2020-12-03 17:36:32 -05001418 if (structType->isArray()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001419 structType = &structType->componentType();
1420 }
John Stiles3dba3ee2020-12-02 23:35:49 -05001421 fWrittenStructs.push_back(structType);
Timothy Liangdc89f192018-06-13 09:20:31 -04001422 fIndentation++;
John Stiles3dba3ee2020-12-02 23:35:49 -05001423 this->writeFields(structType->fields(), structType->fOffset, &intf);
Jim Van Verth3d482992019-02-07 10:48:05 -05001424 if (fProgram.fInputs.fRTHeight) {
Timothy Liang7d637782018-06-05 09:58:07 -04001425 this->writeLine("float u_skRTHeight;");
Ethan Nicholascc305772017-10-13 16:17:45 -04001426 }
1427 fIndentation--;
1428 this->write("}");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001429 if (intf.instanceName().size()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001430 this->write(" ");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001431 this->write(intf.instanceName());
John Stilesd39aec02020-12-03 10:42:26 -05001432 if (intf.arraySize() > 0) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001433 this->write("[");
John Stilesd39aec02020-12-03 10:42:26 -05001434 this->write(to_string(intf.arraySize()));
Ethan Nicholascc305772017-10-13 16:17:45 -04001435 this->write("]");
John Stilesd39aec02020-12-03 10:42:26 -05001436 } else if (intf.arraySize() == Type::kUnsizedArray){
1437 this->write("[]");
Ethan Nicholascc305772017-10-13 16:17:45 -04001438 }
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001439 fInterfaceBlockNameMap[&intf] = intf.instanceName();
Timothy Lianga06f2152018-05-24 15:33:31 -04001440 } else {
Timothy Liang7d637782018-06-05 09:58:07 -04001441 fInterfaceBlockNameMap[&intf] = "_anonInterface" + to_string(fAnonInterfaceCount++);
Ethan Nicholascc305772017-10-13 16:17:45 -04001442 }
1443 this->writeLine(";");
1444}
1445
Timothy Liangdc89f192018-06-13 09:20:31 -04001446void MetalCodeGenerator::writeFields(const std::vector<Type::Field>& fields, int parentOffset,
1447 const InterfaceBlock* parentIntf) {
Timothy Liang609fbe32018-08-10 16:40:49 -04001448 MemoryLayout memoryLayout(MemoryLayout::kMetal_Standard);
Timothy Liangdc89f192018-06-13 09:20:31 -04001449 int currentOffset = 0;
1450 for (const auto& field: fields) {
1451 int fieldOffset = field.fModifiers.fLayout.fOffset;
1452 const Type* fieldType = field.fType;
John Stiles21f5f452020-11-30 09:57:59 -05001453 if (!MemoryLayout::LayoutIsSupported(*fieldType)) {
John Stiles0023c0c2020-11-16 13:32:18 -05001454 fErrors.error(parentOffset, "type '" + fieldType->name() + "' is not permitted here");
1455 return;
1456 }
Timothy Liangdc89f192018-06-13 09:20:31 -04001457 if (fieldOffset != -1) {
1458 if (currentOffset > fieldOffset) {
1459 fErrors.error(parentOffset,
1460 "offset of field '" + field.fName + "' must be at least " +
1461 to_string((int) currentOffset));
Brian Osman8609a242020-09-08 14:01:49 -04001462 return;
Timothy Liangdc89f192018-06-13 09:20:31 -04001463 } else if (currentOffset < fieldOffset) {
1464 this->write("char pad");
1465 this->write(to_string(fPaddingCount++));
1466 this->write("[");
1467 this->write(to_string(fieldOffset - currentOffset));
1468 this->writeLine("];");
1469 currentOffset = fieldOffset;
1470 }
1471 int alignment = memoryLayout.alignment(*fieldType);
1472 if (fieldOffset % alignment) {
1473 fErrors.error(parentOffset,
1474 "offset of field '" + field.fName + "' must be a multiple of " +
1475 to_string((int) alignment));
Brian Osman8609a242020-09-08 14:01:49 -04001476 return;
Timothy Liangdc89f192018-06-13 09:20:31 -04001477 }
1478 }
Brian Osman8609a242020-09-08 14:01:49 -04001479 size_t fieldSize = memoryLayout.size(*fieldType);
1480 if (fieldSize > static_cast<size_t>(std::numeric_limits<int>::max() - currentOffset)) {
1481 fErrors.error(parentOffset, "field offset overflow");
1482 return;
1483 }
1484 currentOffset += fieldSize;
John Stiles06b84ef2020-12-09 12:35:48 -05001485 this->writeModifiers(field.fModifiers, /*globalContext=*/false);
John Stiles3dba3ee2020-12-02 23:35:49 -05001486 this->writeBaseType(*fieldType);
Timothy Liangdc89f192018-06-13 09:20:31 -04001487 this->write(" ");
1488 this->writeName(field.fName);
John Stiles3dba3ee2020-12-02 23:35:49 -05001489 this->writeArrayDimensions(*fieldType);
Timothy Liangdc89f192018-06-13 09:20:31 -04001490 this->writeLine(";");
1491 if (parentIntf) {
1492 fInterfaceBlockMap[&field] = parentIntf;
1493 }
1494 }
1495}
1496
Ethan Nicholascc305772017-10-13 16:17:45 -04001497void MetalCodeGenerator::writeVarInitializer(const Variable& var, const Expression& value) {
1498 this->writeExpression(value, kTopLevel_Precedence);
1499}
1500
Timothy Liang651286f2018-06-07 09:55:33 -04001501void MetalCodeGenerator::writeName(const String& name) {
1502 if (fReservedWords.find(name) != fReservedWords.end()) {
1503 this->write("_"); // adding underscore before name to avoid conflict with reserved words
1504 }
1505 this->write(name);
1506}
1507
Brian Osmanc0213602020-10-06 14:43:32 -04001508void MetalCodeGenerator::writeVarDeclaration(const VarDeclaration& var, bool global) {
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001509 if (global && !(var.var().modifiers().fFlags & Modifiers::kConst_Flag)) {
Brian Osmanc0213602020-10-06 14:43:32 -04001510 return;
Ethan Nicholascc305772017-10-13 16:17:45 -04001511 }
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001512 this->writeModifiers(var.var().modifiers(), global);
John Stiles3dba3ee2020-12-02 23:35:49 -05001513 this->writeBaseType(var.baseType());
1514 this->disallowArrayTypes(var.baseType()); // `float[2] x` shouldn't be possible (invalid SkSL)
Brian Osmanc0213602020-10-06 14:43:32 -04001515 this->write(" ");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001516 this->writeName(var.var().name());
John Stiles62a56462020-12-03 10:41:58 -05001517 if (var.arraySize() > 0) {
Brian Osmanc0213602020-10-06 14:43:32 -04001518 this->write("[");
John Stiles62a56462020-12-03 10:41:58 -05001519 this->write(to_string(var.arraySize()));
Brian Osmanc0213602020-10-06 14:43:32 -04001520 this->write("]");
John Stiles62a56462020-12-03 10:41:58 -05001521 } else if (var.arraySize() == Type::kUnsizedArray){
1522 this->write("[]");
Ethan Nicholascc305772017-10-13 16:17:45 -04001523 }
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001524 if (var.value()) {
Brian Osmanc0213602020-10-06 14:43:32 -04001525 this->write(" = ");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001526 this->writeVarInitializer(var.var(), *var.value());
Brian Osmanc0213602020-10-06 14:43:32 -04001527 }
1528 this->write(";");
Ethan Nicholascc305772017-10-13 16:17:45 -04001529}
1530
1531void MetalCodeGenerator::writeStatement(const Statement& s) {
Ethan Nicholase6592142020-09-08 10:22:09 -04001532 switch (s.kind()) {
1533 case Statement::Kind::kBlock:
John Stiles26f98502020-08-18 09:30:51 -04001534 this->writeBlock(s.as<Block>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001535 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001536 case Statement::Kind::kExpression:
Ethan Nicholasd503a5a2020-09-30 09:29:55 -04001537 this->writeExpression(*s.as<ExpressionStatement>().expression(), kTopLevel_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001538 this->write(";");
1539 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001540 case Statement::Kind::kReturn:
John Stiles26f98502020-08-18 09:30:51 -04001541 this->writeReturnStatement(s.as<ReturnStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001542 break;
Brian Osmanc0213602020-10-06 14:43:32 -04001543 case Statement::Kind::kVarDeclaration:
1544 this->writeVarDeclaration(s.as<VarDeclaration>(), false);
Ethan Nicholascc305772017-10-13 16:17:45 -04001545 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001546 case Statement::Kind::kIf:
John Stiles26f98502020-08-18 09:30:51 -04001547 this->writeIfStatement(s.as<IfStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001548 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001549 case Statement::Kind::kFor:
John Stiles26f98502020-08-18 09:30:51 -04001550 this->writeForStatement(s.as<ForStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001551 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001552 case Statement::Kind::kWhile:
John Stiles26f98502020-08-18 09:30:51 -04001553 this->writeWhileStatement(s.as<WhileStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001554 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001555 case Statement::Kind::kDo:
John Stiles26f98502020-08-18 09:30:51 -04001556 this->writeDoStatement(s.as<DoStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001557 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001558 case Statement::Kind::kSwitch:
John Stiles26f98502020-08-18 09:30:51 -04001559 this->writeSwitchStatement(s.as<SwitchStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001560 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001561 case Statement::Kind::kBreak:
Ethan Nicholascc305772017-10-13 16:17:45 -04001562 this->write("break;");
1563 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001564 case Statement::Kind::kContinue:
Ethan Nicholascc305772017-10-13 16:17:45 -04001565 this->write("continue;");
1566 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001567 case Statement::Kind::kDiscard:
Timothy Lianga06f2152018-05-24 15:33:31 -04001568 this->write("discard_fragment();");
Ethan Nicholascc305772017-10-13 16:17:45 -04001569 break;
John Stiles98c1f822020-09-09 14:18:53 -04001570 case Statement::Kind::kInlineMarker:
Ethan Nicholase6592142020-09-08 10:22:09 -04001571 case Statement::Kind::kNop:
Ethan Nicholascc305772017-10-13 16:17:45 -04001572 this->write(";");
1573 break;
1574 default:
Ethan Nicholas2a099da2020-01-02 14:40:54 -05001575#ifdef SK_DEBUG
Ethan Nicholascc305772017-10-13 16:17:45 -04001576 ABORT("unsupported statement: %s", s.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -05001577#endif
1578 break;
Ethan Nicholascc305772017-10-13 16:17:45 -04001579 }
1580}
1581
Ethan Nicholascc305772017-10-13 16:17:45 -04001582void MetalCodeGenerator::writeBlock(const Block& b) {
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001583 bool isScope = b.isScope();
1584 if (isScope) {
Ethan Nicholas70728ef2020-05-28 07:09:00 -04001585 this->writeLine("{");
1586 fIndentation++;
1587 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001588 for (const std::unique_ptr<Statement>& stmt : b.children()) {
1589 if (!stmt->isEmpty()) {
1590 this->writeStatement(*stmt);
1591 this->writeLine();
1592 }
1593 }
1594 if (isScope) {
Ethan Nicholas70728ef2020-05-28 07:09:00 -04001595 fIndentation--;
1596 this->write("}");
1597 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001598}
1599
1600void MetalCodeGenerator::writeIfStatement(const IfStatement& stmt) {
1601 this->write("if (");
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04001602 this->writeExpression(*stmt.test(), kTopLevel_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001603 this->write(") ");
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04001604 this->writeStatement(*stmt.ifTrue());
1605 if (stmt.ifFalse()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001606 this->write(" else ");
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04001607 this->writeStatement(*stmt.ifFalse());
Ethan Nicholascc305772017-10-13 16:17:45 -04001608 }
1609}
1610
1611void MetalCodeGenerator::writeForStatement(const ForStatement& f) {
1612 this->write("for (");
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04001613 if (f.initializer() && !f.initializer()->isEmpty()) {
1614 this->writeStatement(*f.initializer());
Ethan Nicholascc305772017-10-13 16:17:45 -04001615 } else {
1616 this->write("; ");
1617 }
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04001618 if (f.test()) {
1619 this->writeExpression(*f.test(), kTopLevel_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001620 }
1621 this->write("; ");
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04001622 if (f.next()) {
1623 this->writeExpression(*f.next(), kTopLevel_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001624 }
1625 this->write(") ");
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04001626 this->writeStatement(*f.statement());
Ethan Nicholascc305772017-10-13 16:17:45 -04001627}
1628
1629void MetalCodeGenerator::writeWhileStatement(const WhileStatement& w) {
1630 this->write("while (");
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04001631 this->writeExpression(*w.test(), kTopLevel_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001632 this->write(") ");
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04001633 this->writeStatement(*w.statement());
Ethan Nicholascc305772017-10-13 16:17:45 -04001634}
1635
1636void MetalCodeGenerator::writeDoStatement(const DoStatement& d) {
1637 this->write("do ");
Ethan Nicholas1fd61162020-09-28 13:14:19 -04001638 this->writeStatement(*d.statement());
Ethan Nicholascc305772017-10-13 16:17:45 -04001639 this->write(" while (");
Ethan Nicholas1fd61162020-09-28 13:14:19 -04001640 this->writeExpression(*d.test(), kTopLevel_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001641 this->write(");");
1642}
1643
1644void MetalCodeGenerator::writeSwitchStatement(const SwitchStatement& s) {
1645 this->write("switch (");
Ethan Nicholas01b05e52020-10-22 15:53:41 -04001646 this->writeExpression(*s.value(), kTopLevel_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001647 this->writeLine(") {");
1648 fIndentation++;
John Stiles2d4f9592020-10-30 10:29:12 -04001649 for (const std::unique_ptr<SwitchCase>& c : s.cases()) {
1650 if (c->value()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001651 this->write("case ");
John Stiles2d4f9592020-10-30 10:29:12 -04001652 this->writeExpression(*c->value(), kTopLevel_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001653 this->writeLine(":");
1654 } else {
1655 this->writeLine("default:");
1656 }
1657 fIndentation++;
John Stiles2d4f9592020-10-30 10:29:12 -04001658 for (const auto& stmt : c->statements()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001659 this->writeStatement(*stmt);
1660 this->writeLine();
1661 }
1662 fIndentation--;
1663 }
1664 fIndentation--;
1665 this->write("}");
1666}
1667
John Stiles986c7fb2020-12-01 14:44:56 -05001668void MetalCodeGenerator::writeReturnStatementFromMain() {
1669 // main functions in Metal return a magic _out parameter that doesn't exist in SkSL.
1670 switch (fProgram.fKind) {
1671 case Program::kFragment_Kind:
1672 this->write("return *_out;");
1673 break;
1674 case Program::kVertex_Kind:
1675 this->write("return (_out->sk_Position.y = -_out->sk_Position.y, *_out);");
1676 break;
1677 default:
1678 SkDEBUGFAIL("unsupported kind of program");
1679 }
1680}
1681
Ethan Nicholascc305772017-10-13 16:17:45 -04001682void MetalCodeGenerator::writeReturnStatement(const ReturnStatement& r) {
John Stiles986c7fb2020-12-01 14:44:56 -05001683 if (fCurrentFunction && fCurrentFunction->name() == "main") {
1684 if (r.expression()) {
1685 fErrors.error(r.fOffset, "Metal does not support returning values from main()");
1686 }
1687 this->writeReturnStatementFromMain();
1688 return;
1689 }
1690
Ethan Nicholascc305772017-10-13 16:17:45 -04001691 this->write("return");
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04001692 if (r.expression()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001693 this->write(" ");
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04001694 this->writeExpression(*r.expression(), kTopLevel_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001695 }
1696 this->write(";");
1697}
1698
1699void MetalCodeGenerator::writeHeader() {
1700 this->write("#include <metal_stdlib>\n");
1701 this->write("#include <simd/simd.h>\n");
1702 this->write("using namespace metal;\n");
1703}
1704
1705void MetalCodeGenerator::writeUniformStruct() {
Brian Osman133724c2020-10-28 14:14:39 -04001706 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04001707 if (e->is<GlobalVarDeclaration>()) {
1708 const GlobalVarDeclaration& decls = e->as<GlobalVarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001709 const Variable& var = decls.declaration()->as<VarDeclaration>().var();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001710 if (var.modifiers().fFlags & Modifiers::kUniform_Flag &&
Brian Osmanc0213602020-10-06 14:43:32 -04001711 var.type().typeKind() != Type::TypeKind::kSampler) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001712 if (-1 == fUniformBuffer) {
1713 this->write("struct Uniforms {\n");
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001714 fUniformBuffer = var.modifiers().fLayout.fSet;
Ethan Nicholascc305772017-10-13 16:17:45 -04001715 if (-1 == fUniformBuffer) {
1716 fErrors.error(decls.fOffset, "Metal uniforms must have 'layout(set=...)'");
1717 }
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001718 } else if (var.modifiers().fLayout.fSet != fUniformBuffer) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001719 if (-1 == fUniformBuffer) {
1720 fErrors.error(decls.fOffset, "Metal backend requires all uniforms to have "
1721 "the same 'layout(set=...)'");
1722 }
1723 }
1724 this->write(" ");
John Stiles3dba3ee2020-12-02 23:35:49 -05001725 this->writeBaseType(var.type());
Ethan Nicholascc305772017-10-13 16:17:45 -04001726 this->write(" ");
Brian Osmanc0213602020-10-06 14:43:32 -04001727 this->writeName(var.name());
John Stiles3dba3ee2020-12-02 23:35:49 -05001728 this->writeArrayDimensions(var.type());
Ethan Nicholascc305772017-10-13 16:17:45 -04001729 this->write(";\n");
1730 }
1731 }
1732 }
1733 if (-1 != fUniformBuffer) {
1734 this->write("};\n");
1735 }
1736}
1737
1738void MetalCodeGenerator::writeInputStruct() {
1739 this->write("struct Inputs {\n");
Brian Osman133724c2020-10-28 14:14:39 -04001740 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04001741 if (e->is<GlobalVarDeclaration>()) {
1742 const GlobalVarDeclaration& decls = e->as<GlobalVarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001743 const Variable& var = decls.declaration()->as<VarDeclaration>().var();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001744 if (var.modifiers().fFlags & Modifiers::kIn_Flag &&
1745 -1 == var.modifiers().fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001746 this->write(" ");
John Stiles3dba3ee2020-12-02 23:35:49 -05001747 this->writeBaseType(var.type());
Ethan Nicholascc305772017-10-13 16:17:45 -04001748 this->write(" ");
Brian Osmanc0213602020-10-06 14:43:32 -04001749 this->writeName(var.name());
John Stiles3dba3ee2020-12-02 23:35:49 -05001750 this->writeArrayDimensions(var.type());
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001751 if (-1 != var.modifiers().fLayout.fLocation) {
Brian Osmanc0213602020-10-06 14:43:32 -04001752 if (fProgram.fKind == Program::kVertex_Kind) {
1753 this->write(" [[attribute(" +
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001754 to_string(var.modifiers().fLayout.fLocation) + ")]]");
Brian Osmanc0213602020-10-06 14:43:32 -04001755 } else if (fProgram.fKind == Program::kFragment_Kind) {
1756 this->write(" [[user(locn" +
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001757 to_string(var.modifiers().fLayout.fLocation) + ")]]");
Ethan Nicholascc305772017-10-13 16:17:45 -04001758 }
1759 }
1760 this->write(";\n");
1761 }
1762 }
1763 }
1764 this->write("};\n");
1765}
1766
1767void MetalCodeGenerator::writeOutputStruct() {
1768 this->write("struct Outputs {\n");
Timothy Liang7d637782018-06-05 09:58:07 -04001769 if (fProgram.fKind == Program::kVertex_Kind) {
Timothy Liangb8eeb802018-07-23 16:46:16 -04001770 this->write(" float4 sk_Position [[position]];\n");
Timothy Liang7d637782018-06-05 09:58:07 -04001771 } else if (fProgram.fKind == Program::kFragment_Kind) {
Timothy Liangde0be802018-08-10 13:48:08 -04001772 this->write(" float4 sk_FragColor [[color(0)]];\n");
Timothy Liang7d637782018-06-05 09:58:07 -04001773 }
Brian Osman133724c2020-10-28 14:14:39 -04001774 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04001775 if (e->is<GlobalVarDeclaration>()) {
1776 const GlobalVarDeclaration& decls = e->as<GlobalVarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001777 const Variable& var = decls.declaration()->as<VarDeclaration>().var();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001778 if (var.modifiers().fFlags & Modifiers::kOut_Flag &&
1779 -1 == var.modifiers().fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001780 this->write(" ");
John Stiles3dba3ee2020-12-02 23:35:49 -05001781 this->writeBaseType(var.type());
Ethan Nicholascc305772017-10-13 16:17:45 -04001782 this->write(" ");
Brian Osmanc0213602020-10-06 14:43:32 -04001783 this->writeName(var.name());
John Stiles3dba3ee2020-12-02 23:35:49 -05001784 this->writeArrayDimensions(var.type());
John Stiles842b3592020-12-01 10:36:37 -05001785
1786 int location = var.modifiers().fLayout.fLocation;
1787 if (location < 0) {
1788 fErrors.error(var.fOffset,
1789 "Metal out variables must have 'layout(location=...)'");
1790 } else if (fProgram.fKind == Program::kVertex_Kind) {
1791 this->write(" [[user(locn" + to_string(location) + ")]]");
Brian Osmanc0213602020-10-06 14:43:32 -04001792 } else if (fProgram.fKind == Program::kFragment_Kind) {
John Stiles842b3592020-12-01 10:36:37 -05001793 this->write(" [[color(" + to_string(location) + ")");
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001794 int colorIndex = var.modifiers().fLayout.fIndex;
Brian Osmanc0213602020-10-06 14:43:32 -04001795 if (colorIndex) {
1796 this->write(", index(" + to_string(colorIndex) + ")");
Timothy Liang7d637782018-06-05 09:58:07 -04001797 }
Brian Osmanc0213602020-10-06 14:43:32 -04001798 this->write("]]");
Ethan Nicholascc305772017-10-13 16:17:45 -04001799 }
1800 this->write(";\n");
1801 }
1802 }
Timothy Liang7d637782018-06-05 09:58:07 -04001803 }
1804 if (fProgram.fKind == Program::kVertex_Kind) {
Jim Van Verth3913d3e2020-08-31 15:16:57 -04001805 this->write(" float sk_PointSize [[point_size]];\n");
Timothy Liang7d637782018-06-05 09:58:07 -04001806 }
1807 this->write("};\n");
1808}
1809
1810void MetalCodeGenerator::writeInterfaceBlocks() {
1811 bool wroteInterfaceBlock = false;
Brian Osman133724c2020-10-28 14:14:39 -04001812 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04001813 if (e->is<InterfaceBlock>()) {
1814 this->writeInterfaceBlock(e->as<InterfaceBlock>());
Timothy Liang7d637782018-06-05 09:58:07 -04001815 wroteInterfaceBlock = true;
1816 }
1817 }
Jim Van Verth3d482992019-02-07 10:48:05 -05001818 if (!wroteInterfaceBlock && fProgram.fInputs.fRTHeight) {
Timothy Liang7d637782018-06-05 09:58:07 -04001819 this->writeLine("struct sksl_synthetic_uniforms {");
1820 this->writeLine(" float u_skRTHeight;");
1821 this->writeLine("};");
1822 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001823}
1824
John Stilesdc75a972020-11-25 16:24:55 -05001825void MetalCodeGenerator::writeStructDefinitions() {
1826 for (const ProgramElement* e : fProgram.elements()) {
1827 if (e->is<StructDefinition>()) {
1828 if (this->writeStructDefinition(e->as<StructDefinition>().type())) {
1829 this->writeLine(";");
1830 }
1831 } else if (e->is<GlobalVarDeclaration>()) {
1832 // If a global var declaration introduces a struct type, we need to write that type
1833 // here, since globals are all embedded in a sub-struct.
1834 const Type* type = &e->as<GlobalVarDeclaration>().declaration()
1835 ->as<VarDeclaration>().baseType();
John Stilesc0c51062020-12-03 17:16:29 -05001836 if (type->isStruct()) {
John Stilesdc75a972020-11-25 16:24:55 -05001837 if (this->writeStructDefinition(*type)) {
1838 this->writeLine(";");
1839 }
1840 }
1841 }
1842 }
1843}
1844
John Stilescdcdb042020-07-06 09:03:51 -04001845void MetalCodeGenerator::visitGlobalStruct(GlobalStructVisitor* visitor) {
1846 // Visit the interface blocks.
1847 for (const auto& [interfaceType, interfaceName] : fInterfaceBlockNameMap) {
John Stilesfdb8dbe2020-12-04 11:00:03 -05001848 visitor->visitInterfaceBlock(*interfaceType, interfaceName);
John Stilescdcdb042020-07-06 09:03:51 -04001849 }
Brian Osman133724c2020-10-28 14:14:39 -04001850 for (const ProgramElement* element : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04001851 if (!element->is<GlobalVarDeclaration>()) {
John Stilescdcdb042020-07-06 09:03:51 -04001852 continue;
Timothy Liang7d637782018-06-05 09:58:07 -04001853 }
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001854 const GlobalVarDeclaration& global = element->as<GlobalVarDeclaration>();
1855 const VarDeclaration& decl = global.declaration()->as<VarDeclaration>();
1856 const Variable& var = decl.var();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001857 if ((!var.modifiers().fFlags && -1 == var.modifiers().fLayout.fBuiltin) ||
Brian Osmanc0213602020-10-06 14:43:32 -04001858 var.type().typeKind() == Type::TypeKind::kSampler) {
1859 if (var.type().typeKind() == Type::TypeKind::kSampler) {
1860 // Samplers are represented as a "texture/sampler" duo in the global struct.
John Stilesfdb8dbe2020-12-04 11:00:03 -05001861 visitor->visitTexture(var.type(), var.name());
1862 visitor->visitSampler(var.type(), String(var.name()) + SAMPLER_SUFFIX);
Brian Osmanc0213602020-10-06 14:43:32 -04001863 } else {
1864 // Visit a regular variable.
John Stilesfdb8dbe2020-12-04 11:00:03 -05001865 visitor->visitVariable(var, decl.value().get());
Timothy Liangee84fe12018-05-18 14:38:19 -04001866 }
1867 }
1868 }
John Stilescdcdb042020-07-06 09:03:51 -04001869}
1870
1871void MetalCodeGenerator::writeGlobalStruct() {
1872 class : public GlobalStructVisitor {
1873 public:
John Stilesfdb8dbe2020-12-04 11:00:03 -05001874 void visitInterfaceBlock(const InterfaceBlock& block, const String& blockName) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05001875 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04001876 fCodeGen->write(" constant ");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001877 fCodeGen->write(block.typeName());
John Stilescdcdb042020-07-06 09:03:51 -04001878 fCodeGen->write("* ");
1879 fCodeGen->writeName(blockName);
1880 fCodeGen->write(";\n");
1881 }
John Stilesfdb8dbe2020-12-04 11:00:03 -05001882 void visitTexture(const Type& type, const String& name) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05001883 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04001884 fCodeGen->write(" ");
John Stiles3dba3ee2020-12-02 23:35:49 -05001885 fCodeGen->writeBaseType(type);
John Stilescdcdb042020-07-06 09:03:51 -04001886 fCodeGen->write(" ");
1887 fCodeGen->writeName(name);
John Stiles3dba3ee2020-12-02 23:35:49 -05001888 fCodeGen->writeArrayDimensions(type);
John Stilescdcdb042020-07-06 09:03:51 -04001889 fCodeGen->write(";\n");
1890 }
John Stilesfdb8dbe2020-12-04 11:00:03 -05001891 void visitSampler(const Type&, const String& name) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05001892 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04001893 fCodeGen->write(" sampler ");
1894 fCodeGen->writeName(name);
1895 fCodeGen->write(";\n");
1896 }
John Stilesfdb8dbe2020-12-04 11:00:03 -05001897 void visitVariable(const Variable& var, const Expression* value) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05001898 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04001899 fCodeGen->write(" ");
John Stiles3dba3ee2020-12-02 23:35:49 -05001900 fCodeGen->writeBaseType(var.type());
John Stilescdcdb042020-07-06 09:03:51 -04001901 fCodeGen->write(" ");
Ethan Nicholase2c49992020-10-05 11:49:11 -04001902 fCodeGen->writeName(var.name());
John Stiles3dba3ee2020-12-02 23:35:49 -05001903 fCodeGen->writeArrayDimensions(var.type());
John Stilescdcdb042020-07-06 09:03:51 -04001904 fCodeGen->write(";\n");
1905 }
John Stiles83f3b8d2020-12-07 17:52:25 -05001906 void addElement() {
John Stilescdcdb042020-07-06 09:03:51 -04001907 if (fFirst) {
1908 fCodeGen->write("struct Globals {\n");
1909 fFirst = false;
1910 }
1911 }
John Stiles83f3b8d2020-12-07 17:52:25 -05001912 void finish() {
John Stilescdcdb042020-07-06 09:03:51 -04001913 if (!fFirst) {
John Stiles83f3b8d2020-12-07 17:52:25 -05001914 fCodeGen->writeLine("};");
John Stilescdcdb042020-07-06 09:03:51 -04001915 fFirst = true;
1916 }
1917 }
1918
1919 MetalCodeGenerator* fCodeGen = nullptr;
1920 bool fFirst = true;
1921 } visitor;
1922
1923 visitor.fCodeGen = this;
1924 this->visitGlobalStruct(&visitor);
John Stiles83f3b8d2020-12-07 17:52:25 -05001925 visitor.finish();
John Stilescdcdb042020-07-06 09:03:51 -04001926}
1927
1928void MetalCodeGenerator::writeGlobalInit() {
1929 class : public GlobalStructVisitor {
1930 public:
John Stilesfdb8dbe2020-12-04 11:00:03 -05001931 void visitInterfaceBlock(const InterfaceBlock& blockType,
John Stilescdcdb042020-07-06 09:03:51 -04001932 const String& blockName) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05001933 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04001934 fCodeGen->write("&");
1935 fCodeGen->writeName(blockName);
1936 }
John Stilesfdb8dbe2020-12-04 11:00:03 -05001937 void visitTexture(const Type&, const String& name) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05001938 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04001939 fCodeGen->writeName(name);
1940 }
John Stilesfdb8dbe2020-12-04 11:00:03 -05001941 void visitSampler(const Type&, const String& name) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05001942 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04001943 fCodeGen->writeName(name);
1944 }
John Stilesfdb8dbe2020-12-04 11:00:03 -05001945 void visitVariable(const Variable& var, const Expression* value) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05001946 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04001947 if (value) {
1948 fCodeGen->writeVarInitializer(var, *value);
1949 } else {
1950 fCodeGen->write("{}");
1951 }
1952 }
John Stiles83f3b8d2020-12-07 17:52:25 -05001953 void addElement() {
John Stilescdcdb042020-07-06 09:03:51 -04001954 if (fFirst) {
1955 fCodeGen->write(" Globals globalStruct{");
1956 fFirst = false;
1957 } else {
1958 fCodeGen->write(", ");
1959 }
1960 }
John Stiles83f3b8d2020-12-07 17:52:25 -05001961 void finish() {
John Stilescdcdb042020-07-06 09:03:51 -04001962 if (!fFirst) {
1963 fCodeGen->writeLine("};");
1964 fCodeGen->writeLine(" thread Globals* _globals = &globalStruct;");
1965 fCodeGen->writeLine(" (void)_globals;");
1966 }
1967 }
1968 MetalCodeGenerator* fCodeGen = nullptr;
1969 bool fFirst = true;
1970 } visitor;
1971
1972 visitor.fCodeGen = this;
1973 this->visitGlobalStruct(&visitor);
John Stiles83f3b8d2020-12-07 17:52:25 -05001974 visitor.finish();
Timothy Liangee84fe12018-05-18 14:38:19 -04001975}
1976
Ethan Nicholascc305772017-10-13 16:17:45 -04001977void MetalCodeGenerator::writeProgramElement(const ProgramElement& e) {
Ethan Nicholase6592142020-09-08 10:22:09 -04001978 switch (e.kind()) {
1979 case ProgramElement::Kind::kExtension:
Ethan Nicholascc305772017-10-13 16:17:45 -04001980 break;
Brian Osmanc0213602020-10-06 14:43:32 -04001981 case ProgramElement::Kind::kGlobalVar: {
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001982 const GlobalVarDeclaration& global = e.as<GlobalVarDeclaration>();
1983 const VarDeclaration& decl = global.declaration()->as<VarDeclaration>();
1984 int builtin = decl.var().modifiers().fLayout.fBuiltin;
Brian Osmanc0213602020-10-06 14:43:32 -04001985 if (-1 == builtin) {
1986 // normal var
1987 this->writeVarDeclaration(decl, true);
1988 this->writeLine();
1989 } else if (SK_FRAGCOLOR_BUILTIN == builtin) {
1990 // ignore
Ethan Nicholascc305772017-10-13 16:17:45 -04001991 }
1992 break;
1993 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001994 case ProgramElement::Kind::kInterfaceBlock:
Timothy Liang7d637782018-06-05 09:58:07 -04001995 // handled in writeInterfaceBlocks, do nothing
Ethan Nicholascc305772017-10-13 16:17:45 -04001996 break;
John Stilesdc75a972020-11-25 16:24:55 -05001997 case ProgramElement::Kind::kStructDefinition:
1998 // Handled in writeStructDefinitions. Do nothing.
1999 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04002000 case ProgramElement::Kind::kFunction:
John Stiles3dc0da62020-08-19 17:48:31 -04002001 this->writeFunction(e.as<FunctionDefinition>());
Ethan Nicholascc305772017-10-13 16:17:45 -04002002 break;
John Stiles569249b2020-11-03 12:18:22 -05002003 case ProgramElement::Kind::kFunctionPrototype:
2004 this->writeFunctionPrototype(e.as<FunctionPrototype>());
2005 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04002006 case ProgramElement::Kind::kModifiers:
John Stiles06b84ef2020-12-09 12:35:48 -05002007 this->writeModifiers(e.as<ModifiersDeclaration>().modifiers(),
2008 /*globalContext=*/true);
Ethan Nicholascc305772017-10-13 16:17:45 -04002009 this->writeLine(";");
2010 break;
John Stiles712fd6b2020-11-25 22:25:43 -05002011 case ProgramElement::Kind::kEnum:
2012 break;
Ethan Nicholascc305772017-10-13 16:17:45 -04002013 default:
Ethan Nicholas2a099da2020-01-02 14:40:54 -05002014#ifdef SK_DEBUG
2015 ABORT("unsupported program element: %s\n", e.description().c_str());
2016#endif
2017 break;
Ethan Nicholascc305772017-10-13 16:17:45 -04002018 }
2019}
2020
Ethan Nicholasff350cb2020-05-14 14:05:13 -04002021MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const Expression* e) {
2022 if (!e) {
2023 return kNo_Requirements;
2024 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002025 switch (e->kind()) {
2026 case Expression::Kind::kFunctionCall: {
John Stiles3dc0da62020-08-19 17:48:31 -04002027 const FunctionCall& f = e->as<FunctionCall>();
Ethan Nicholas0dec9922020-10-05 15:51:52 -04002028 Requirements result = this->requirements(f.function());
2029 for (const auto& arg : f.arguments()) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04002030 result |= this->requirements(arg.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002031 }
2032 return result;
2033 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002034 case Expression::Kind::kConstructor: {
John Stiles3dc0da62020-08-19 17:48:31 -04002035 const Constructor& c = e->as<Constructor>();
Ethan Nicholascc305772017-10-13 16:17:45 -04002036 Requirements result = kNo_Requirements;
Ethan Nicholasf70f0442020-09-29 12:41:35 -04002037 for (const auto& arg : c.arguments()) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04002038 result |= this->requirements(arg.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002039 }
2040 return result;
2041 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002042 case Expression::Kind::kFieldAccess: {
John Stiles3dc0da62020-08-19 17:48:31 -04002043 const FieldAccess& f = e->as<FieldAccess>();
Ethan Nicholas7a95b202020-10-09 11:55:40 -04002044 if (FieldAccess::OwnerKind::kAnonymousInterfaceBlock == f.ownerKind()) {
Timothy Liang7d637782018-06-05 09:58:07 -04002045 return kGlobals_Requirement;
2046 }
Ethan Nicholas7a95b202020-10-09 11:55:40 -04002047 return this->requirements(f.base().get());
Timothy Liang7d637782018-06-05 09:58:07 -04002048 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002049 case Expression::Kind::kSwizzle:
Ethan Nicholas6b4d5812020-10-12 16:11:51 -04002050 return this->requirements(e->as<Swizzle>().base().get());
Ethan Nicholase6592142020-09-08 10:22:09 -04002051 case Expression::Kind::kBinary: {
2052 const BinaryExpression& bin = e->as<BinaryExpression>();
John Stiles2d4f9592020-10-30 10:29:12 -04002053 return this->requirements(bin.left().get()) |
2054 this->requirements(bin.right().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002055 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002056 case Expression::Kind::kIndex: {
John Stiles3dc0da62020-08-19 17:48:31 -04002057 const IndexExpression& idx = e->as<IndexExpression>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04002058 return this->requirements(idx.base().get()) | this->requirements(idx.index().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002059 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002060 case Expression::Kind::kPrefix:
Ethan Nicholas444ccc62020-10-09 10:16:22 -04002061 return this->requirements(e->as<PrefixExpression>().operand().get());
Ethan Nicholase6592142020-09-08 10:22:09 -04002062 case Expression::Kind::kPostfix:
Ethan Nicholas444ccc62020-10-09 10:16:22 -04002063 return this->requirements(e->as<PostfixExpression>().operand().get());
Ethan Nicholase6592142020-09-08 10:22:09 -04002064 case Expression::Kind::kTernary: {
John Stiles3dc0da62020-08-19 17:48:31 -04002065 const TernaryExpression& t = e->as<TernaryExpression>();
Ethan Nicholasdd218162020-10-08 05:48:01 -04002066 return this->requirements(t.test().get()) | this->requirements(t.ifTrue().get()) |
2067 this->requirements(t.ifFalse().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002068 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002069 case Expression::Kind::kVariableReference: {
John Stiles3dc0da62020-08-19 17:48:31 -04002070 const VariableReference& v = e->as<VariableReference>();
Ethan Nicholas78686922020-10-08 06:46:27 -04002071 const Modifiers& modifiers = v.variable()->modifiers();
Ethan Nicholascc305772017-10-13 16:17:45 -04002072 Requirements result = kNo_Requirements;
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002073 if (modifiers.fLayout.fBuiltin == SK_FRAGCOORD_BUILTIN) {
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -04002074 result = kGlobals_Requirement | kFragCoord_Requirement;
Ethan Nicholas453f67f2020-10-09 10:43:45 -04002075 } else if (Variable::Storage::kGlobal == v.variable()->storage()) {
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002076 if (modifiers.fFlags & Modifiers::kIn_Flag) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002077 result = kInputs_Requirement;
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002078 } else if (modifiers.fFlags & Modifiers::kOut_Flag) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002079 result = kOutputs_Requirement;
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002080 } else if (modifiers.fFlags & Modifiers::kUniform_Flag &&
Ethan Nicholas78686922020-10-08 06:46:27 -04002081 v.variable()->type().typeKind() != Type::TypeKind::kSampler) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002082 result = kUniforms_Requirement;
Timothy Liangee84fe12018-05-18 14:38:19 -04002083 } else {
2084 result = kGlobals_Requirement;
Ethan Nicholascc305772017-10-13 16:17:45 -04002085 }
2086 }
2087 return result;
2088 }
2089 default:
2090 return kNo_Requirements;
2091 }
2092}
2093
Ethan Nicholasff350cb2020-05-14 14:05:13 -04002094MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const Statement* s) {
2095 if (!s) {
2096 return kNo_Requirements;
2097 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002098 switch (s->kind()) {
2099 case Statement::Kind::kBlock: {
Ethan Nicholascc305772017-10-13 16:17:45 -04002100 Requirements result = kNo_Requirements;
Ethan Nicholas7bd60432020-09-25 14:31:59 -04002101 for (const std::unique_ptr<Statement>& child : s->as<Block>().children()) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04002102 result |= this->requirements(child.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002103 }
2104 return result;
2105 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002106 case Statement::Kind::kVarDeclaration: {
John Stiles3dc0da62020-08-19 17:48:31 -04002107 const VarDeclaration& var = s->as<VarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04002108 return this->requirements(var.value().get());
Timothy Liang7d637782018-06-05 09:58:07 -04002109 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002110 case Statement::Kind::kExpression:
Ethan Nicholasd503a5a2020-09-30 09:29:55 -04002111 return this->requirements(s->as<ExpressionStatement>().expression().get());
Ethan Nicholase6592142020-09-08 10:22:09 -04002112 case Statement::Kind::kReturn: {
John Stiles3dc0da62020-08-19 17:48:31 -04002113 const ReturnStatement& r = s->as<ReturnStatement>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04002114 return this->requirements(r.expression().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002115 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002116 case Statement::Kind::kIf: {
John Stiles3dc0da62020-08-19 17:48:31 -04002117 const IfStatement& i = s->as<IfStatement>();
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04002118 return this->requirements(i.test().get()) |
2119 this->requirements(i.ifTrue().get()) |
2120 this->requirements(i.ifFalse().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002121 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002122 case Statement::Kind::kFor: {
John Stiles3dc0da62020-08-19 17:48:31 -04002123 const ForStatement& f = s->as<ForStatement>();
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04002124 return this->requirements(f.initializer().get()) |
2125 this->requirements(f.test().get()) |
2126 this->requirements(f.next().get()) |
2127 this->requirements(f.statement().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002128 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002129 case Statement::Kind::kWhile: {
John Stiles3dc0da62020-08-19 17:48:31 -04002130 const WhileStatement& w = s->as<WhileStatement>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04002131 return this->requirements(w.test().get()) |
2132 this->requirements(w.statement().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002133 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002134 case Statement::Kind::kDo: {
John Stiles3dc0da62020-08-19 17:48:31 -04002135 const DoStatement& d = s->as<DoStatement>();
Ethan Nicholas1fd61162020-09-28 13:14:19 -04002136 return this->requirements(d.test().get()) |
2137 this->requirements(d.statement().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002138 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002139 case Statement::Kind::kSwitch: {
John Stiles3dc0da62020-08-19 17:48:31 -04002140 const SwitchStatement& sw = s->as<SwitchStatement>();
Ethan Nicholas01b05e52020-10-22 15:53:41 -04002141 Requirements result = this->requirements(sw.value().get());
John Stiles2d4f9592020-10-30 10:29:12 -04002142 for (const std::unique_ptr<SwitchCase>& sc : sw.cases()) {
2143 for (const auto& st : sc->statements()) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04002144 result |= this->requirements(st.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002145 }
2146 }
2147 return result;
2148 }
2149 default:
2150 return kNo_Requirements;
2151 }
2152}
2153
2154MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const FunctionDeclaration& f) {
Ethan Nicholased84b732020-10-08 11:45:44 -04002155 if (f.isBuiltin()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002156 return kNo_Requirements;
2157 }
2158 auto found = fRequirements.find(&f);
2159 if (found == fRequirements.end()) {
Ethan Nicholas65a8f562019-04-19 14:00:26 -04002160 fRequirements[&f] = kNo_Requirements;
Brian Osman133724c2020-10-28 14:14:39 -04002161 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04002162 if (e->is<FunctionDefinition>()) {
2163 const FunctionDefinition& def = e->as<FunctionDefinition>();
Ethan Nicholas0a5d0962020-10-14 13:33:18 -04002164 if (&def.declaration() == &f) {
2165 Requirements reqs = this->requirements(def.body().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002166 fRequirements[&f] = reqs;
2167 return reqs;
2168 }
2169 }
2170 }
John Stiles569249b2020-11-03 12:18:22 -05002171 // We never found a definition for this declared function, but it's legal to prototype a
2172 // function without ever giving a definition, as long as you don't call it.
2173 return kNo_Requirements;
Ethan Nicholascc305772017-10-13 16:17:45 -04002174 }
2175 return found->second;
2176}
2177
Timothy Liangb8eeb802018-07-23 16:46:16 -04002178bool MetalCodeGenerator::generateCode() {
Ethan Nicholascc305772017-10-13 16:17:45 -04002179 fProgramKind = fProgram.fKind;
Ethan Nicholascc305772017-10-13 16:17:45 -04002180
John Stiles44532372020-12-07 12:33:55 -05002181 StringStream header;
2182 {
2183 AutoOutputStream outputToHeader(this, &header, &fIndentation);
2184 this->writeHeader();
2185 this->writeStructDefinitions();
2186 this->writeUniformStruct();
2187 this->writeInputStruct();
2188 this->writeOutputStruct();
2189 this->writeInterfaceBlocks();
2190 this->writeGlobalStruct();
2191 }
2192 StringStream body;
2193 {
2194 AutoOutputStream outputToBody(this, &body, &fIndentation);
2195 for (const ProgramElement* e : fProgram.elements()) {
2196 this->writeProgramElement(*e);
2197 }
2198 }
2199 write_stringstream(header, *fOut);
2200 write_stringstream(fExtraFunctions, *fOut);
2201 write_stringstream(body, *fOut);
Brian Osman8609a242020-09-08 14:01:49 -04002202 return 0 == fErrors.errorCount();
Ethan Nicholascc305772017-10-13 16:17:45 -04002203}
2204
John Stilesa6841be2020-08-06 14:11:56 -04002205} // namespace SkSL