blob: 6e513b7795d0844639c927bfec67eff9518a8822 [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 Stiles45990502021-02-16 10:55:27 -050025const char* MetalCodeGenerator::OperatorName(Operator op) {
26 switch (op.kind()) {
John Stilesd6449e92020-11-30 09:13:23 -050027 case Token::Kind::TK_LOGICALXOR: return "!=";
John Stiles45990502021-02-16 10:55:27 -050028 default: return op.operatorName();
John Stilesd6449e92020-11-30 09:13:23 -050029 }
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() {
John Stilesd7199b22020-12-30 16:22:58 -050042 fIntrinsicMap[String("atan")] = kAtan_IntrinsicKind;
43 fIntrinsicMap[String("floatBitsToInt")] = kBitcast_IntrinsicKind;
44 fIntrinsicMap[String("floatBitsToUint")] = kBitcast_IntrinsicKind;
45 fIntrinsicMap[String("intBitsToFloat")] = kBitcast_IntrinsicKind;
46 fIntrinsicMap[String("uintBitsToFloat")] = kBitcast_IntrinsicKind;
47 fIntrinsicMap[String("equal")] = kCompareEqual_IntrinsicKind;
48 fIntrinsicMap[String("notEqual")] = kCompareNotEqual_IntrinsicKind;
49 fIntrinsicMap[String("lessThan")] = kCompareLessThan_IntrinsicKind;
50 fIntrinsicMap[String("lessThanEqual")] = kCompareLessThanEqual_IntrinsicKind;
51 fIntrinsicMap[String("greaterThan")] = kCompareGreaterThan_IntrinsicKind;
52 fIntrinsicMap[String("greaterThanEqual")] = kCompareGreaterThanEqual_IntrinsicKind;
53 fIntrinsicMap[String("degrees")] = kDegrees_IntrinsicKind;
54 fIntrinsicMap[String("dFdx")] = kDFdx_IntrinsicKind;
55 fIntrinsicMap[String("dFdy")] = kDFdy_IntrinsicKind;
56 fIntrinsicMap[String("distance")] = kDistance_IntrinsicKind;
57 fIntrinsicMap[String("dot")] = kDot_IntrinsicKind;
58 fIntrinsicMap[String("faceforward")] = kFaceforward_IntrinsicKind;
59 fIntrinsicMap[String("bitCount")] = kBitCount_IntrinsicKind;
60 fIntrinsicMap[String("findLSB")] = kFindLSB_IntrinsicKind;
61 fIntrinsicMap[String("findMSB")] = kFindMSB_IntrinsicKind;
62 fIntrinsicMap[String("inverse")] = kInverse_IntrinsicKind;
63 fIntrinsicMap[String("inversesqrt")] = kInversesqrt_IntrinsicKind;
64 fIntrinsicMap[String("length")] = kLength_IntrinsicKind;
65 fIntrinsicMap[String("matrixCompMult")] = kMatrixCompMult_IntrinsicKind;
66 fIntrinsicMap[String("mod")] = kMod_IntrinsicKind;
67 fIntrinsicMap[String("normalize")] = kNormalize_IntrinsicKind;
68 fIntrinsicMap[String("radians")] = kRadians_IntrinsicKind;
69 fIntrinsicMap[String("reflect")] = kReflect_IntrinsicKind;
70 fIntrinsicMap[String("refract")] = kRefract_IntrinsicKind;
John Stiles23456532020-12-30 18:12:48 -050071 fIntrinsicMap[String("roundEven")] = kRoundEven_IntrinsicKind;
John Stilesd7199b22020-12-30 16:22:58 -050072 fIntrinsicMap[String("sample")] = kTexture_IntrinsicKind;
Timothy Liangee84fe12018-05-18 14:38:19 -040073}
74
Ethan Nicholascc305772017-10-13 16:17:45 -040075void MetalCodeGenerator::write(const char* s) {
76 if (!s[0]) {
77 return;
78 }
79 if (fAtLineStart) {
80 for (int i = 0; i < fIndentation; i++) {
81 fOut->writeText(" ");
82 }
83 }
84 fOut->writeText(s);
85 fAtLineStart = false;
86}
87
88void MetalCodeGenerator::writeLine(const char* s) {
89 this->write(s);
John Stilese8b5a732021-03-12 13:25:52 -050090 this->writeLine();
Ethan Nicholascc305772017-10-13 16:17:45 -040091}
92
93void MetalCodeGenerator::write(const String& s) {
94 this->write(s.c_str());
95}
96
97void MetalCodeGenerator::writeLine(const String& s) {
98 this->writeLine(s.c_str());
99}
100
101void MetalCodeGenerator::writeLine() {
John Stilese8b5a732021-03-12 13:25:52 -0500102 fOut->writeText(fLineEnding);
103 fAtLineStart = true;
104}
105
106void MetalCodeGenerator::finishLine() {
107 if (!fAtLineStart) {
108 this->writeLine();
109 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400110}
111
112void MetalCodeGenerator::writeExtension(const Extension& ext) {
Ethan Nicholasefb09e22020-09-30 10:17:00 -0400113 this->writeLine("#extension " + ext.name() + " : enable");
Ethan Nicholascc305772017-10-13 16:17:45 -0400114}
115
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500116String MetalCodeGenerator::typeName(const Type& type) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400117 switch (type.typeKind()) {
John Stilesb4418502021-02-04 10:57:08 -0500118 case Type::TypeKind::kArray:
119 SkASSERTF(type.columns() > 0, "invalid array size: %s", type.description().c_str());
120 return String::printf("array<%s, %d>",
121 this->typeName(type.componentType()).c_str(), type.columns());
122
Ethan Nicholase6592142020-09-08 10:22:09 -0400123 case Type::TypeKind::kVector:
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500124 return this->typeName(type.componentType()) + to_string(type.columns());
John Stilesb4418502021-02-04 10:57:08 -0500125
Ethan Nicholase6592142020-09-08 10:22:09 -0400126 case Type::TypeKind::kMatrix:
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500127 return this->typeName(type.componentType()) + to_string(type.columns()) + "x" +
128 to_string(type.rows());
John Stilesb4418502021-02-04 10:57:08 -0500129
Ethan Nicholase6592142020-09-08 10:22:09 -0400130 case Type::TypeKind::kSampler:
John Stiles368db7c2020-12-29 11:20:08 -0500131 return "texture2d<float>"; // FIXME - support other texture types
John Stilesb4418502021-02-04 10:57:08 -0500132
John Stilesfd41d872020-11-25 22:39:45 -0500133 case Type::TypeKind::kEnum:
134 return "int";
John Stilesb4418502021-02-04 10:57:08 -0500135
Ethan Nicholascc305772017-10-13 16:17:45 -0400136 default:
John Stiles54e7c052021-01-11 14:22:36 -0500137 if (type == *fContext.fTypes.fHalf) {
Timothy Liang43d225f2018-07-19 15:27:13 -0400138 // FIXME - Currently only supporting floats in MSL to avoid type coercion issues.
John Stiles54e7c052021-01-11 14:22:36 -0500139 return fContext.fTypes.fFloat->name();
140 } else if (type == *fContext.fTypes.fByte) {
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500141 return "char";
John Stiles54e7c052021-01-11 14:22:36 -0500142 } else if (type == *fContext.fTypes.fUByte) {
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500143 return "uchar";
Timothy Liang7d637782018-06-05 09:58:07 -0400144 } else {
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500145 return type.name();
Timothy Liang7d637782018-06-05 09:58:07 -0400146 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400147 }
148}
149
Brian Osman02bc5222021-01-28 11:00:20 -0500150void MetalCodeGenerator::writeStructDefinition(const StructDefinition& s) {
151 const Type& type = s.type();
John Stilesdc75a972020-11-25 16:24:55 -0500152 this->writeLine("struct " + type.name() + " {");
153 fIndentation++;
154 this->writeFields(type.fields(), type.fOffset);
155 fIndentation--;
Brian Osman02bc5222021-01-28 11:00:20 -0500156 this->writeLine("};");
John Stilesdc75a972020-11-25 16:24:55 -0500157}
158
John Stilesb4418502021-02-04 10:57:08 -0500159void MetalCodeGenerator::writeType(const Type& type) {
160 this->write(this->typeName(type));
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500161}
162
Ethan Nicholascc305772017-10-13 16:17:45 -0400163void MetalCodeGenerator::writeExpression(const Expression& expr, Precedence parentPrecedence) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400164 switch (expr.kind()) {
165 case Expression::Kind::kBinary:
John Stiles81365af2020-08-18 09:24:00 -0400166 this->writeBinaryExpression(expr.as<BinaryExpression>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400167 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400168 case Expression::Kind::kBoolLiteral:
John Stiles81365af2020-08-18 09:24:00 -0400169 this->writeBoolLiteral(expr.as<BoolLiteral>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400170 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400171 case Expression::Kind::kConstructor:
John Stiles81365af2020-08-18 09:24:00 -0400172 this->writeConstructor(expr.as<Constructor>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400173 break;
John Stilese1182782021-03-30 22:09:37 -0400174 case Expression::Kind::kConstructorDiagonalMatrix:
John Stiles933043b2021-03-31 15:23:16 -0400175 this->writeSingleArgumentConstructor(expr.as<ConstructorDiagonalMatrix>(),
John Stilese1182782021-03-30 22:09:37 -0400176 parentPrecedence);
177 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400178 case Expression::Kind::kIntLiteral:
John Stiles81365af2020-08-18 09:24:00 -0400179 this->writeIntLiteral(expr.as<IntLiteral>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400180 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400181 case Expression::Kind::kFieldAccess:
John Stiles81365af2020-08-18 09:24:00 -0400182 this->writeFieldAccess(expr.as<FieldAccess>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400183 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400184 case Expression::Kind::kFloatLiteral:
John Stiles81365af2020-08-18 09:24:00 -0400185 this->writeFloatLiteral(expr.as<FloatLiteral>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400186 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400187 case Expression::Kind::kFunctionCall:
John Stiles81365af2020-08-18 09:24:00 -0400188 this->writeFunctionCall(expr.as<FunctionCall>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400189 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400190 case Expression::Kind::kPrefix:
John Stiles81365af2020-08-18 09:24:00 -0400191 this->writePrefixExpression(expr.as<PrefixExpression>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400192 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400193 case Expression::Kind::kPostfix:
John Stiles81365af2020-08-18 09:24:00 -0400194 this->writePostfixExpression(expr.as<PostfixExpression>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400195 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400196 case Expression::Kind::kSetting:
John Stiles81365af2020-08-18 09:24:00 -0400197 this->writeSetting(expr.as<Setting>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400198 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400199 case Expression::Kind::kSwizzle:
John Stiles81365af2020-08-18 09:24:00 -0400200 this->writeSwizzle(expr.as<Swizzle>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400201 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400202 case Expression::Kind::kVariableReference:
John Stiles81365af2020-08-18 09:24:00 -0400203 this->writeVariableReference(expr.as<VariableReference>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400204 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400205 case Expression::Kind::kTernary:
John Stiles81365af2020-08-18 09:24:00 -0400206 this->writeTernaryExpression(expr.as<TernaryExpression>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400207 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400208 case Expression::Kind::kIndex:
John Stiles81365af2020-08-18 09:24:00 -0400209 this->writeIndexExpression(expr.as<IndexExpression>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400210 break;
211 default:
John Stileseada7bc2021-02-02 16:29:32 -0500212 SkDEBUGFAILF("unsupported expression: %s", expr.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -0500213 break;
Ethan Nicholascc305772017-10-13 16:17:45 -0400214 }
215}
216
John Stiles06b84ef2020-12-09 12:35:48 -0500217String MetalCodeGenerator::getOutParamHelper(const FunctionCall& call,
218 const ExpressionArray& arguments,
219 const SkTArray<VariableReference*>& outVars) {
220 AutoOutputStream outputToExtraFunctions(this, &fExtraFunctions, &fIndentation);
221 const FunctionDeclaration& function = call.function();
222
John Stilese1068342021-03-22 11:57:41 -0400223 String name = "_skOutParamHelper" + to_string(fSwizzleHelperCount++) +
224 "_" + function.mangledName();
John Stiles06b84ef2020-12-09 12:35:48 -0500225 const char* separator = "";
226
227 // Emit a prototype for the function we'll be calling through to in our helper.
228 if (!function.isBuiltin()) {
229 this->writeFunctionDeclaration(function);
230 this->writeLine(";");
231 }
232
233 // Synthesize a helper function that takes the same inputs as `function`, except in places where
234 // `outVars` is non-null; in those places, we take the type of the VariableReference.
235 //
236 // float _skOutParamHelper0_originalFuncName(float _var0, float _var1, float& outParam) {
John Stilesb4418502021-02-04 10:57:08 -0500237 this->writeType(call.type());
John Stiles06b84ef2020-12-09 12:35:48 -0500238 this->write(" ");
239 this->write(name);
240 this->write("(");
241 this->writeFunctionRequirementParams(function, separator);
242
243 SkASSERT(outVars.size() == arguments.size());
244 SkASSERT(outVars.size() == function.parameters().size());
245
John Stiles73e2c892021-02-13 13:58:01 -0500246 // We need to detect cases where the caller passes the same variable as an out-param more than
247 // once, and avoid reusing the variable name. (In those cases we can actually just ignore the
248 // redundant input parameter entirely, and not give it any name.)
249 std::unordered_set<const Variable*> writtenVars;
250
John Stiles06b84ef2020-12-09 12:35:48 -0500251 for (int index = 0; index < arguments.count(); ++index) {
252 this->write(separator);
253 separator = ", ";
254
255 const Variable* param = function.parameters()[index];
256 this->writeModifiers(param->modifiers(), /*globalContext=*/false);
257
258 const Type* type = outVars[index] ? &outVars[index]->type() : &arguments[index]->type();
John Stilesb4418502021-02-04 10:57:08 -0500259 this->writeType(*type);
John Stiles06b84ef2020-12-09 12:35:48 -0500260
261 if (param->modifiers().fFlags & Modifiers::kOut_Flag) {
262 this->write("&");
263 }
264 if (outVars[index]) {
John Stiles73e2c892021-02-13 13:58:01 -0500265 auto [iter, didInsert] = writtenVars.insert(outVars[index]->variable());
266 if (didInsert) {
267 this->write(" ");
268 fIgnoreVariableReferenceModifiers = true;
269 this->writeVariableReference(*outVars[index]);
270 fIgnoreVariableReferenceModifiers = false;
271 }
John Stiles06b84ef2020-12-09 12:35:48 -0500272 } else {
273 this->write(" _var");
274 this->write(to_string(index));
275 }
John Stiles06b84ef2020-12-09 12:35:48 -0500276 }
277 this->writeLine(") {");
278
279 ++fIndentation;
280 for (int index = 0; index < outVars.count(); ++index) {
281 if (!outVars[index]) {
282 continue;
283 }
284 // float3 _var2[ = outParam.zyx];
John Stilesb4418502021-02-04 10:57:08 -0500285 this->writeType(arguments[index]->type());
John Stiles06b84ef2020-12-09 12:35:48 -0500286 this->write(" _var");
287 this->write(to_string(index));
288
289 const Variable* param = function.parameters()[index];
290 if (param->modifiers().fFlags & Modifiers::kIn_Flag) {
291 this->write(" = ");
292 fIgnoreVariableReferenceModifiers = true;
Brian Osman00185012021-02-04 16:07:11 -0500293 this->writeExpression(*arguments[index], Precedence::kAssignment);
John Stiles06b84ef2020-12-09 12:35:48 -0500294 fIgnoreVariableReferenceModifiers = false;
295 }
296
297 this->writeLine(";");
298 }
299
John Stilesf7410bd2021-01-19 13:07:55 -0500300 // [int _skResult = ] myFunction(inputs, outputs, _globals, _var0, _var1, _var2, _var3);
John Stiles06b84ef2020-12-09 12:35:48 -0500301 bool hasResult = (call.type().name() != "void");
302 if (hasResult) {
John Stilesb4418502021-02-04 10:57:08 -0500303 this->writeType(call.type());
John Stiles06b84ef2020-12-09 12:35:48 -0500304 this->write(" _skResult = ");
305 }
306
John Stilese1068342021-03-22 11:57:41 -0400307 this->writeName(function.mangledName());
John Stiles06b84ef2020-12-09 12:35:48 -0500308 this->write("(");
309 separator = "";
310 this->writeFunctionRequirementArgs(function, separator);
311
312 for (int index = 0; index < arguments.count(); ++index) {
313 this->write(separator);
314 separator = ", ";
315
316 this->write("_var");
317 this->write(to_string(index));
318 }
319 this->writeLine(");");
320
321 for (int index = 0; index < outVars.count(); ++index) {
322 if (!outVars[index]) {
323 continue;
324 }
325 // outParam.zyx = _var2;
326 fIgnoreVariableReferenceModifiers = true;
Brian Osman00185012021-02-04 16:07:11 -0500327 this->writeExpression(*arguments[index], Precedence::kAssignment);
John Stiles06b84ef2020-12-09 12:35:48 -0500328 fIgnoreVariableReferenceModifiers = false;
329 this->write(" = _var");
330 this->write(to_string(index));
331 this->writeLine(";");
332 }
333
334 if (hasResult) {
335 this->writeLine("return _skResult;");
336 }
337
338 --fIndentation;
339 this->writeLine("}");
340
341 return name;
John Stilesb21fac22020-12-04 15:36:49 -0500342}
343
John Stilesf64e4072020-12-10 10:34:27 -0500344String MetalCodeGenerator::getBitcastIntrinsic(const Type& outType) {
345 return "as_type<" + outType.displayName() + ">";
346}
347
Ethan Nicholascc305772017-10-13 16:17:45 -0400348void MetalCodeGenerator::writeFunctionCall(const FunctionCall& c) {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400349 const FunctionDeclaration& function = c.function();
John Stiles89ac7c22020-12-30 17:47:31 -0500350 // If this function is a built-in with no declaration, it's probably an intrinsic and might need
351 // special handling.
352 if (function.isBuiltin() && !function.definition()) {
353 auto iter = fIntrinsicMap.find(function.name());
354 if (iter != fIntrinsicMap.end()) {
355 this->writeIntrinsicCall(c, iter->second);
356 return;
357 }
Timothy Liang6403b0e2018-05-17 10:40:04 -0400358 }
John Stilesb21fac22020-12-04 15:36:49 -0500359
John Stilesd7199b22020-12-30 16:22:58 -0500360 // Determine whether or not we need to emulate GLSL's out-param semantics for Metal using a
361 // helper function. (Specifically, out-parameters in GLSL are only written back to the original
362 // variable at the end of the function call; also, swizzles are supported, whereas Metal doesn't
363 // allow a swizzle to be passed to a `floatN&`.)
364 const ExpressionArray& arguments = c.arguments();
John Stilesb21fac22020-12-04 15:36:49 -0500365 const std::vector<const Variable*>& parameters = function.parameters();
366 SkASSERT(arguments.size() == parameters.size());
John Stiles06b84ef2020-12-09 12:35:48 -0500367
368 bool foundOutParam = false;
369 SkSTArray<16, VariableReference*> outVars;
John Stilesf64e4072020-12-10 10:34:27 -0500370 outVars.push_back_n(arguments.count(), (VariableReference*)nullptr);
John Stiles06b84ef2020-12-09 12:35:48 -0500371
372 for (int index = 0; index < arguments.count(); ++index) {
John Stilesb21fac22020-12-04 15:36:49 -0500373 // If this is an out parameter...
374 if (parameters[index]->modifiers().fFlags & Modifiers::kOut_Flag) {
John Stiles06b84ef2020-12-09 12:35:48 -0500375 // Find the expression's inner variable being written to.
John Stilesb21fac22020-12-04 15:36:49 -0500376 Analysis::AssignmentInfo info;
John Stiles06b84ef2020-12-09 12:35:48 -0500377 // Assignability was verified at IRGeneration time, so this should always succeed.
378 SkAssertResult(Analysis::IsAssignable(*arguments[index], &info));
379 outVars[index] = info.fAssignedVar;
380 foundOutParam = true;
John Stilesb21fac22020-12-04 15:36:49 -0500381 }
382 }
383
John Stiles06b84ef2020-12-09 12:35:48 -0500384 if (foundOutParam) {
385 // Out parameters need to be written back to at the end of the function. To do this, we
386 // synthesize a helper function which evaluates the out-param expression into a temporary
387 // variable, calls the original function, then writes the temp var back into the out param
388 // using the original out-param expression. (This lets us support things like swizzles and
389 // array indices.)
John Stilesd7199b22020-12-30 16:22:58 -0500390 this->write(getOutParamHelper(c, arguments, outVars));
391 } else {
John Stilese1068342021-03-22 11:57:41 -0400392 this->write(function.mangledName());
John Stiles06b84ef2020-12-09 12:35:48 -0500393 }
394
Ethan Nicholascc305772017-10-13 16:17:45 -0400395 this->write("(");
396 const char* separator = "";
John Stiles06b84ef2020-12-09 12:35:48 -0500397 this->writeFunctionRequirementArgs(function, separator);
398 for (int i = 0; i < arguments.count(); ++i) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400399 this->write(separator);
400 separator = ", ";
John Stiles06b84ef2020-12-09 12:35:48 -0500401
402 if (outVars[i]) {
Brian Osman00185012021-02-04 16:07:11 -0500403 this->writeExpression(*outVars[i], Precedence::kSequence);
John Stiles06b84ef2020-12-09 12:35:48 -0500404 } else {
Brian Osman00185012021-02-04 16:07:11 -0500405 this->writeExpression(*arguments[i], Precedence::kSequence);
John Stiles06b84ef2020-12-09 12:35:48 -0500406 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400407 }
408 this->write(")");
409}
410
Brian Osman964f0a02020-12-29 10:15:22 -0500411static constexpr char kInverse2x2[] = R"(
412float2x2 float2x2_inverse(float2x2 m) {
413 return float2x2(m[1][1], -m[0][1], -m[1][0], m[0][0]) * (1/determinant(m));
414}
415)";
416
417static constexpr char kInverse3x3[] = R"(
418float3x3 float3x3_inverse(float3x3 m) {
419 float a00 = m[0][0], a01 = m[0][1], a02 = m[0][2];
420 float a10 = m[1][0], a11 = m[1][1], a12 = m[1][2];
421 float a20 = m[2][0], a21 = m[2][1], a22 = m[2][2];
422 float b01 = a22*a11 - a12*a21;
423 float b11 = -a22*a10 + a12*a20;
424 float b21 = a21*a10 - a11*a20;
425 float det = a00*b01 + a01*b11 + a02*b21;
426 return float3x3(b01, (-a22*a01 + a02*a21), ( a12*a01 - a02*a11),
427 b11, ( a22*a00 - a02*a20), (-a12*a00 + a02*a10),
428 b21, (-a21*a00 + a01*a20), ( a11*a00 - a01*a10)) * (1/det);
429}
430)";
431
432static constexpr char kInverse4x4[] = R"(
433float4x4 float4x4_inverse(float4x4 m) {
434 float a00 = m[0][0], a01 = m[0][1], a02 = m[0][2], a03 = m[0][3];
435 float a10 = m[1][0], a11 = m[1][1], a12 = m[1][2], a13 = m[1][3];
436 float a20 = m[2][0], a21 = m[2][1], a22 = m[2][2], a23 = m[2][3];
437 float a30 = m[3][0], a31 = m[3][1], a32 = m[3][2], a33 = m[3][3];
438 float b00 = a00*a11 - a01*a10;
439 float b01 = a00*a12 - a02*a10;
440 float b02 = a00*a13 - a03*a10;
441 float b03 = a01*a12 - a02*a11;
442 float b04 = a01*a13 - a03*a11;
443 float b05 = a02*a13 - a03*a12;
444 float b06 = a20*a31 - a21*a30;
445 float b07 = a20*a32 - a22*a30;
446 float b08 = a20*a33 - a23*a30;
447 float b09 = a21*a32 - a22*a31;
448 float b10 = a21*a33 - a23*a31;
449 float b11 = a22*a33 - a23*a32;
450 float det = b00*b11 - b01*b10 + b02*b09 + b03*b08 - b04*b07 + b05*b06;
451 return float4x4(a11*b11 - a12*b10 + a13*b09,
452 a02*b10 - a01*b11 - a03*b09,
453 a31*b05 - a32*b04 + a33*b03,
454 a22*b04 - a21*b05 - a23*b03,
455 a12*b08 - a10*b11 - a13*b07,
456 a00*b11 - a02*b08 + a03*b07,
457 a32*b02 - a30*b05 - a33*b01,
458 a20*b05 - a22*b02 + a23*b01,
459 a10*b10 - a11*b08 + a13*b06,
460 a01*b08 - a00*b10 - a03*b06,
461 a30*b04 - a31*b02 + a33*b00,
462 a21*b02 - a20*b04 - a23*b00,
463 a11*b07 - a10*b09 - a12*b06,
464 a00*b09 - a01*b07 + a02*b06,
465 a31*b01 - a30*b03 - a32*b00,
466 a20*b03 - a21*b01 + a22*b00) * (1/det);
467}
468)";
469
John Stilesd7199b22020-12-30 16:22:58 -0500470String MetalCodeGenerator::getInversePolyfill(const ExpressionArray& arguments) {
471 // Only use polyfills for a function taking a single-argument square matrix.
472 if (arguments.size() == 1) {
473 const Type& type = arguments.front()->type();
474 if (type.isMatrix() && type.rows() == type.columns()) {
475 // Inject the correct polyfill based on the matrix size.
476 String name = this->typeName(type) + "_inverse";
477 auto [iter, didInsert] = fWrittenIntrinsics.insert(name);
478 if (didInsert) {
479 switch (type.rows()) {
480 case 2:
481 fExtraFunctions.writeText(kInverse2x2);
482 break;
483 case 3:
484 fExtraFunctions.writeText(kInverse3x3);
485 break;
486 case 4:
487 fExtraFunctions.writeText(kInverse4x4);
488 break;
489 }
490 }
491 return name;
Chris Daltondba7aab2018-11-15 10:57:49 -0500492 }
493 }
John Stilesd7199b22020-12-30 16:22:58 -0500494 // This isn't the built-in `inverse`. We don't want to polyfill it at all.
495 return "inverse";
Chris Daltondba7aab2018-11-15 10:57:49 -0500496}
497
Brian Osman93aed9a2020-12-28 15:18:46 -0500498static constexpr char kMatrixCompMult[] = R"(
499template <int C, int R>
500matrix<float, C, R> matrixCompMult(matrix<float, C, R> a, matrix<float, C, R> b) {
501 matrix<float, C, R> result;
502 for (int c = 0; c < C; ++c) {
503 result[c] = a[c] * b[c];
504 }
505 return result;
506}
507)";
508
509void MetalCodeGenerator::writeMatrixCompMult() {
510 String name = "matrixCompMult";
511 if (fWrittenIntrinsics.find(name) == fWrittenIntrinsics.end()) {
512 fWrittenIntrinsics.insert(name);
513 fExtraFunctions.writeText(kMatrixCompMult);
514 }
515}
516
John Stiles86424eb2020-12-11 11:17:14 -0500517String MetalCodeGenerator::getTempVariable(const Type& type) {
518 String tempVar = "_skTemp" + to_string(fVarCount++);
519 this->fFunctionHeader += " " + this->typeName(type) + " " + tempVar + ";\n";
520 return tempVar;
521}
522
John Stiles791c27d2020-12-30 14:56:57 -0500523void MetalCodeGenerator::writeSimpleIntrinsic(const FunctionCall& c) {
524 // Write out an intrinsic function call exactly as-is. No muss no fuss.
525 this->write(c.function().name());
John Stilesd7199b22020-12-30 16:22:58 -0500526 this->writeArgumentList(c.arguments());
527}
528
529void MetalCodeGenerator::writeArgumentList(const ExpressionArray& arguments) {
John Stiles791c27d2020-12-30 14:56:57 -0500530 this->write("(");
531 const char* separator = "";
John Stilesd7199b22020-12-30 16:22:58 -0500532 for (const std::unique_ptr<Expression>& arg : arguments) {
John Stiles791c27d2020-12-30 14:56:57 -0500533 this->write(separator);
534 separator = ", ";
Brian Osman00185012021-02-04 16:07:11 -0500535 this->writeExpression(*arg, Precedence::kSequence);
John Stiles791c27d2020-12-30 14:56:57 -0500536 }
537 this->write(")");
538}
539
John Stilesd7199b22020-12-30 16:22:58 -0500540void MetalCodeGenerator::writeIntrinsicCall(const FunctionCall& c, IntrinsicKind kind) {
John Stiles8e3b6be2020-10-13 11:14:08 -0400541 const ExpressionArray& arguments = c.arguments();
Timothy Liang6403b0e2018-05-17 10:40:04 -0400542 switch (kind) {
John Stilesd7199b22020-12-30 16:22:58 -0500543 case kTexture_IntrinsicKind: {
Brian Osman00185012021-02-04 16:07:11 -0500544 this->writeExpression(*arguments[0], Precedence::kSequence);
Timothy Lianga06f2152018-05-24 15:33:31 -0400545 this->write(".sample(");
Brian Osman00185012021-02-04 16:07:11 -0500546 this->writeExpression(*arguments[0], Precedence::kSequence);
Timothy Lianga06f2152018-05-24 15:33:31 -0400547 this->write(SAMPLER_SUFFIX);
548 this->write(", ");
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400549 const Type& arg1Type = arguments[1]->type();
John Stiles54e7c052021-01-11 14:22:36 -0500550 if (arg1Type == *fContext.fTypes.fFloat3) {
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500551 // have to store the vector in a temp variable to avoid double evaluating it
John Stiles86424eb2020-12-11 11:17:14 -0500552 String tmpVar = this->getTempVariable(arg1Type);
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500553 this->write("(" + tmpVar + " = ");
Brian Osman00185012021-02-04 16:07:11 -0500554 this->writeExpression(*arguments[1], Precedence::kSequence);
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500555 this->write(", " + tmpVar + ".xy / " + tmpVar + ".z))");
Timothy Liangee84fe12018-05-18 14:38:19 -0400556 } else {
John Stiles54e7c052021-01-11 14:22:36 -0500557 SkASSERT(arg1Type == *fContext.fTypes.fFloat2);
Brian Osman00185012021-02-04 16:07:11 -0500558 this->writeExpression(*arguments[1], Precedence::kSequence);
Timothy Liangee84fe12018-05-18 14:38:19 -0400559 this->write(")");
560 }
Timothy Liang6403b0e2018-05-17 10:40:04 -0400561 break;
Ethan Nicholas30d30222020-09-11 12:27:26 -0400562 }
John Stilesd7199b22020-12-30 16:22:58 -0500563 case kMod_IntrinsicKind: {
Timothy Liang651286f2018-06-07 09:55:33 -0400564 // fmod(x, y) in metal calculates x - y * trunc(x / y) instead of x - y * floor(x / y)
John Stiles86424eb2020-12-11 11:17:14 -0500565 String tmpX = this->getTempVariable(arguments[0]->type());
John Stiles61b2e812020-12-30 18:27:31 -0500566 String tmpY = this->getTempVariable(arguments[1]->type());
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500567 this->write("(" + tmpX + " = ");
Brian Osman00185012021-02-04 16:07:11 -0500568 this->writeExpression(*arguments[0], Precedence::kSequence);
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500569 this->write(", " + tmpY + " = ");
Brian Osman00185012021-02-04 16:07:11 -0500570 this->writeExpression(*arguments[1], Precedence::kSequence);
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500571 this->write(", " + tmpX + " - " + tmpY + " * floor(" + tmpX + " / " + tmpY + "))");
Timothy Liang651286f2018-06-07 09:55:33 -0400572 break;
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500573 }
Brian Osman46787d52020-11-24 14:18:23 -0500574 // GLSL declares scalar versions of most geometric intrinsics, but these don't exist in MSL
John Stilesd7199b22020-12-30 16:22:58 -0500575 case kDistance_IntrinsicKind: {
Brian Osman46787d52020-11-24 14:18:23 -0500576 if (arguments[0]->type().columns() == 1) {
577 this->write("abs(");
Brian Osman00185012021-02-04 16:07:11 -0500578 this->writeExpression(*arguments[0], Precedence::kAdditive);
Brian Osman46787d52020-11-24 14:18:23 -0500579 this->write(" - ");
Brian Osman00185012021-02-04 16:07:11 -0500580 this->writeExpression(*arguments[1], Precedence::kAdditive);
Brian Osman46787d52020-11-24 14:18:23 -0500581 this->write(")");
582 } else {
John Stiles791c27d2020-12-30 14:56:57 -0500583 this->writeSimpleIntrinsic(c);
Brian Osman46787d52020-11-24 14:18:23 -0500584 }
585 break;
586 }
John Stilesd7199b22020-12-30 16:22:58 -0500587 case kDot_IntrinsicKind: {
Brian Osman46787d52020-11-24 14:18:23 -0500588 if (arguments[0]->type().columns() == 1) {
589 this->write("(");
Brian Osman00185012021-02-04 16:07:11 -0500590 this->writeExpression(*arguments[0], Precedence::kMultiplicative);
Brian Osman46787d52020-11-24 14:18:23 -0500591 this->write(" * ");
Brian Osman00185012021-02-04 16:07:11 -0500592 this->writeExpression(*arguments[1], Precedence::kMultiplicative);
Brian Osman46787d52020-11-24 14:18:23 -0500593 this->write(")");
594 } else {
John Stiles791c27d2020-12-30 14:56:57 -0500595 this->writeSimpleIntrinsic(c);
Brian Osman46787d52020-11-24 14:18:23 -0500596 }
597 break;
598 }
John Stilesd7199b22020-12-30 16:22:58 -0500599 case kFaceforward_IntrinsicKind: {
John Stilesad0571f2020-12-10 18:03:10 -0500600 if (arguments[0]->type().columns() == 1) {
601 // ((((Nref) * (I) < 0) ? 1 : -1) * (N))
602 this->write("((((");
Brian Osman00185012021-02-04 16:07:11 -0500603 this->writeExpression(*arguments[2], Precedence::kSequence);
John Stilesad0571f2020-12-10 18:03:10 -0500604 this->write(") * (");
Brian Osman00185012021-02-04 16:07:11 -0500605 this->writeExpression(*arguments[1], Precedence::kSequence);
John Stilesad0571f2020-12-10 18:03:10 -0500606 this->write(") < 0) ? 1 : -1) * (");
Brian Osman00185012021-02-04 16:07:11 -0500607 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stilesad0571f2020-12-10 18:03:10 -0500608 this->write("))");
609 } else {
John Stiles791c27d2020-12-30 14:56:57 -0500610 this->writeSimpleIntrinsic(c);
John Stilesad0571f2020-12-10 18:03:10 -0500611 }
612 break;
613 }
John Stilesd7199b22020-12-30 16:22:58 -0500614 case kLength_IntrinsicKind: {
Brian Osman46787d52020-11-24 14:18:23 -0500615 this->write(arguments[0]->type().columns() == 1 ? "abs(" : "length(");
Brian Osman00185012021-02-04 16:07:11 -0500616 this->writeExpression(*arguments[0], Precedence::kSequence);
Brian Osman46787d52020-11-24 14:18:23 -0500617 this->write(")");
618 break;
619 }
John Stilesd7199b22020-12-30 16:22:58 -0500620 case kNormalize_IntrinsicKind: {
Brian Osman46787d52020-11-24 14:18:23 -0500621 this->write(arguments[0]->type().columns() == 1 ? "sign(" : "normalize(");
Brian Osman00185012021-02-04 16:07:11 -0500622 this->writeExpression(*arguments[0], Precedence::kSequence);
Brian Osman46787d52020-11-24 14:18:23 -0500623 this->write(")");
624 break;
625 }
John Stilesd7199b22020-12-30 16:22:58 -0500626 case kBitcast_IntrinsicKind: {
John Stiles0063a9f2020-12-10 18:01:45 -0500627 this->write(this->getBitcastIntrinsic(c.type()));
628 this->write("(");
Brian Osman00185012021-02-04 16:07:11 -0500629 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stiles0063a9f2020-12-10 18:01:45 -0500630 this->write(")");
631 break;
632 }
John Stilesd7199b22020-12-30 16:22:58 -0500633 case kDegrees_IntrinsicKind: {
John Stilese2d34f82020-12-10 18:02:02 -0500634 this->write("((");
Brian Osman00185012021-02-04 16:07:11 -0500635 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stilese2d34f82020-12-10 18:02:02 -0500636 this->write(") * 57.2957795)");
637 break;
638 }
John Stilesd7199b22020-12-30 16:22:58 -0500639 case kRadians_IntrinsicKind: {
John Stilese2d34f82020-12-10 18:02:02 -0500640 this->write("((");
Brian Osman00185012021-02-04 16:07:11 -0500641 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stilese2d34f82020-12-10 18:02:02 -0500642 this->write(") * 0.0174532925)");
643 break;
644 }
John Stilesd7199b22020-12-30 16:22:58 -0500645 case kDFdx_IntrinsicKind: {
646 this->write("dfdx");
647 this->writeArgumentList(c.arguments());
648 break;
649 }
650 case kDFdy_IntrinsicKind: {
651 // Flipping Y also negates the Y derivatives.
John Stiles270cec22021-02-17 12:59:36 -0500652 if (fProgram.fConfig->fSettings.fFlipY) {
John Stilesd7199b22020-12-30 16:22:58 -0500653 this->write("-");
654 }
655 this->write("dfdy");
656 this->writeArgumentList(c.arguments());
657 break;
658 }
659 case kInverse_IntrinsicKind: {
660 this->write(this->getInversePolyfill(arguments));
661 this->writeArgumentList(c.arguments());
662 break;
663 }
664 case kInversesqrt_IntrinsicKind: {
665 this->write("rsqrt");
666 this->writeArgumentList(c.arguments());
667 break;
668 }
669 case kAtan_IntrinsicKind: {
670 this->write(c.arguments().size() == 2 ? "atan2" : "atan");
671 this->writeArgumentList(c.arguments());
672 break;
673 }
674 case kReflect_IntrinsicKind: {
John Stiles791c27d2020-12-30 14:56:57 -0500675 if (arguments[0]->type().columns() == 1) {
676 // We need to synthesize `I - 2 * N * I * N`.
677 String tmpI = this->getTempVariable(arguments[0]->type());
678 String tmpN = this->getTempVariable(arguments[1]->type());
679
680 // (_skTempI = ...
681 this->write("(" + tmpI + " = ");
Brian Osman00185012021-02-04 16:07:11 -0500682 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stiles791c27d2020-12-30 14:56:57 -0500683
684 // , _skTempN = ...
685 this->write(", " + tmpN + " = ");
Brian Osman00185012021-02-04 16:07:11 -0500686 this->writeExpression(*arguments[1], Precedence::kSequence);
John Stiles791c27d2020-12-30 14:56:57 -0500687
688 // , _skTempI - 2 * _skTempN * _skTempI * _skTempN)
689 this->write(", " + tmpI + " - 2 * " + tmpN + " * " + tmpI + " * " + tmpN + ")");
690 } else {
691 this->writeSimpleIntrinsic(c);
692 }
693 break;
694 }
John Stilesd7199b22020-12-30 16:22:58 -0500695 case kRefract_IntrinsicKind: {
John Stiles4b783d62020-12-30 14:58:07 -0500696 if (arguments[0]->type().columns() == 1) {
697 // Metal does implement refract for vectors; rather than reimplementing refract from
698 // scratch, we can replace the call with `refract(float2(I,0), float2(N,0), eta).x`.
699 this->write("(refract(float2(");
Brian Osman00185012021-02-04 16:07:11 -0500700 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stiles4b783d62020-12-30 14:58:07 -0500701 this->write(", 0), float2(");
Brian Osman00185012021-02-04 16:07:11 -0500702 this->writeExpression(*arguments[1], Precedence::kSequence);
John Stiles4b783d62020-12-30 14:58:07 -0500703 this->write(", 0), ");
Brian Osman00185012021-02-04 16:07:11 -0500704 this->writeExpression(*arguments[2], Precedence::kSequence);
John Stiles4b783d62020-12-30 14:58:07 -0500705 this->write(").x)");
706 } else {
707 this->writeSimpleIntrinsic(c);
708 }
709 break;
710 }
John Stiles23456532020-12-30 18:12:48 -0500711 case kRoundEven_IntrinsicKind: {
712 this->write("rint");
713 this->writeArgumentList(c.arguments());
714 break;
715 }
John Stilesd7199b22020-12-30 16:22:58 -0500716 case kBitCount_IntrinsicKind: {
John Stilese7dc7cb2020-12-22 15:37:14 -0500717 this->write("popcount(");
Brian Osman00185012021-02-04 16:07:11 -0500718 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stilese7dc7cb2020-12-22 15:37:14 -0500719 this->write(")");
720 break;
721 }
John Stilesd7199b22020-12-30 16:22:58 -0500722 case kFindLSB_IntrinsicKind: {
John Stiles86424eb2020-12-11 11:17:14 -0500723 // Create a temp variable to store the expression, to avoid double-evaluating it.
724 String skTemp = this->getTempVariable(arguments[0]->type());
725 String exprType = this->typeName(arguments[0]->type());
726
727 // ctz returns numbits(type) on zero inputs; GLSL documents it as generating -1 instead.
728 // Use select to detect zero inputs and force a -1 result.
729
730 // (_skTemp1 = (.....), select(ctz(_skTemp1), int4(-1), _skTemp1 == int4(0)))
731 this->write("(");
732 this->write(skTemp);
733 this->write(" = (");
Brian Osman00185012021-02-04 16:07:11 -0500734 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stiles86424eb2020-12-11 11:17:14 -0500735 this->write("), select(ctz(");
736 this->write(skTemp);
737 this->write("), ");
738 this->write(exprType);
739 this->write("(-1), ");
740 this->write(skTemp);
741 this->write(" == ");
742 this->write(exprType);
743 this->write("(0)))");
744 break;
745 }
John Stilesd7199b22020-12-30 16:22:58 -0500746 case kFindMSB_IntrinsicKind: {
John Stiles9685e522020-12-14 11:52:14 -0500747 // Create a temp variable to store the expression, to avoid double-evaluating it.
748 String skTemp1 = this->getTempVariable(arguments[0]->type());
749 String exprType = this->typeName(arguments[0]->type());
750
751 // GLSL findMSB is actually quite different from Metal's clz:
752 // - For signed negative numbers, it returns the first zero bit, not the first one bit!
753 // - For an empty input (0/~0 depending on sign), findMSB gives -1; clz is numbits(type)
754
755 // (_skTemp1 = (.....),
756 this->write("(");
757 this->write(skTemp1);
758 this->write(" = (");
Brian Osman00185012021-02-04 16:07:11 -0500759 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stiles9685e522020-12-14 11:52:14 -0500760 this->write("), ");
761
762 // Signed input types might be negative; we need another helper variable to negate the
763 // input (since we can only find one bits, not zero bits).
764 String skTemp2;
765 if (arguments[0]->type().isSigned()) {
766 // ... _skTemp2 = (select(_skTemp1, ~_skTemp1, _skTemp1 < 0)),
767 skTemp2 = this->getTempVariable(arguments[0]->type());
768 this->write(skTemp2);
769 this->write(" = (select(");
770 this->write(skTemp1);
771 this->write(", ~");
772 this->write(skTemp1);
773 this->write(", ");
774 this->write(skTemp1);
775 this->write(" < 0)), ");
776 } else {
777 skTemp2 = skTemp1;
778 }
779
780 // ... select(int4(clz(_skTemp2)), int4(-1), _skTemp2 == int4(0)))
781 this->write("select(");
782 this->write(this->typeName(c.type()));
783 this->write("(clz(");
784 this->write(skTemp2);
785 this->write(")), ");
786 this->write(this->typeName(c.type()));
787 this->write("(-1), ");
788 this->write(skTemp2);
789 this->write(" == ");
790 this->write(exprType);
791 this->write("(0)))");
792 break;
793 }
John Stilesd7199b22020-12-30 16:22:58 -0500794 case kMatrixCompMult_IntrinsicKind: {
795 this->writeMatrixCompMult();
796 this->writeSimpleIntrinsic(c);
797 break;
798 }
799 case kCompareEqual_IntrinsicKind:
800 case kCompareGreaterThan_IntrinsicKind:
801 case kCompareGreaterThanEqual_IntrinsicKind:
802 case kCompareLessThan_IntrinsicKind:
803 case kCompareLessThanEqual_IntrinsicKind:
804 case kCompareNotEqual_IntrinsicKind: {
805 this->write("(");
Brian Osman00185012021-02-04 16:07:11 -0500806 this->writeExpression(*c.arguments()[0], Precedence::kRelational);
John Stilesd7199b22020-12-30 16:22:58 -0500807 switch (kind) {
808 case kCompareEqual_IntrinsicKind:
809 this->write(" == ");
810 break;
811 case kCompareNotEqual_IntrinsicKind:
812 this->write(" != ");
813 break;
814 case kCompareLessThan_IntrinsicKind:
815 this->write(" < ");
816 break;
817 case kCompareLessThanEqual_IntrinsicKind:
818 this->write(" <= ");
819 break;
820 case kCompareGreaterThan_IntrinsicKind:
821 this->write(" > ");
822 break;
823 case kCompareGreaterThanEqual_IntrinsicKind:
824 this->write(" >= ");
825 break;
826 default:
John Stilesf57207b2021-02-02 17:50:34 -0500827 SK_ABORT("unsupported comparison intrinsic kind");
John Stilesd7199b22020-12-30 16:22:58 -0500828 }
Brian Osman00185012021-02-04 16:07:11 -0500829 this->writeExpression(*c.arguments()[1], Precedence::kRelational);
John Stilesd7199b22020-12-30 16:22:58 -0500830 this->write(")");
831 break;
832 }
Timothy Liang6403b0e2018-05-17 10:40:04 -0400833 default:
John Stilesf57207b2021-02-02 17:50:34 -0500834 SK_ABORT("unsupported intrinsic kind");
Timothy Liang6403b0e2018-05-17 10:40:04 -0400835 }
836}
837
John Stilesfcf8cb22020-08-06 14:29:22 -0400838// Assembles a matrix of type floatRxC by resizing another matrix named `x0`.
839// Cells that don't exist in the source matrix will be populated with identity-matrix values.
840void MetalCodeGenerator::assembleMatrixFromMatrix(const Type& sourceMatrix, int rows, int columns) {
841 SkASSERT(rows <= 4);
842 SkASSERT(columns <= 4);
843
844 const char* columnSeparator = "";
845 for (int c = 0; c < columns; ++c) {
846 fExtraFunctions.printf("%sfloat%d(", columnSeparator, rows);
847 columnSeparator = "), ";
848
849 // Determine how many values to take from the source matrix for this row.
850 int swizzleLength = 0;
851 if (c < sourceMatrix.columns()) {
852 swizzleLength = std::min<>(rows, sourceMatrix.rows());
853 }
854
855 // Emit all the values from the source matrix row.
856 bool firstItem;
857 switch (swizzleLength) {
858 case 0: firstItem = true; break;
859 case 1: firstItem = false; fExtraFunctions.printf("x0[%d].x", c); break;
860 case 2: firstItem = false; fExtraFunctions.printf("x0[%d].xy", c); break;
861 case 3: firstItem = false; fExtraFunctions.printf("x0[%d].xyz", c); break;
862 case 4: firstItem = false; fExtraFunctions.printf("x0[%d].xyzw", c); break;
863 default: SkUNREACHABLE;
864 }
865
866 // Emit the placeholder identity-matrix cells.
867 for (int r = swizzleLength; r < rows; ++r) {
868 fExtraFunctions.printf("%s%s", firstItem ? "" : ", ", (r == c) ? "1.0" : "0.0");
869 firstItem = false;
870 }
871 }
872
873 fExtraFunctions.writeText(")");
874}
875
876// Assembles a matrix of type floatRxC by concatenating an arbitrary mix of values, named `x0`,
877// `x1`, etc. An error is written if the expression list don't contain exactly R*C scalars.
John Stiles8e3b6be2020-10-13 11:14:08 -0400878void MetalCodeGenerator::assembleMatrixFromExpressions(const ExpressionArray& args,
879 int rows, int columns) {
John Stilesfcf8cb22020-08-06 14:29:22 -0400880 size_t argIndex = 0;
881 int argPosition = 0;
882
883 const char* columnSeparator = "";
884 for (int c = 0; c < columns; ++c) {
885 fExtraFunctions.printf("%sfloat%d(", columnSeparator, rows);
886 columnSeparator = "), ";
887
888 const char* rowSeparator = "";
889 for (int r = 0; r < rows; ++r) {
890 fExtraFunctions.writeText(rowSeparator);
891 rowSeparator = ", ";
892
893 if (argIndex < args.size()) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400894 const Type& argType = args[argIndex]->type();
Ethan Nicholase6592142020-09-08 10:22:09 -0400895 switch (argType.typeKind()) {
896 case Type::TypeKind::kScalar: {
John Stilesfcf8cb22020-08-06 14:29:22 -0400897 fExtraFunctions.printf("x%zu", argIndex);
898 break;
899 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400900 case Type::TypeKind::kVector: {
John Stilesfcf8cb22020-08-06 14:29:22 -0400901 fExtraFunctions.printf("x%zu[%d]", argIndex, argPosition);
902 break;
903 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400904 case Type::TypeKind::kMatrix: {
John Stilesfcf8cb22020-08-06 14:29:22 -0400905 fExtraFunctions.printf("x%zu[%d][%d]", argIndex,
906 argPosition / argType.rows(),
907 argPosition % argType.rows());
908 break;
909 }
910 default: {
911 SkDEBUGFAIL("incorrect type of argument for matrix constructor");
912 fExtraFunctions.writeText("<error>");
913 break;
914 }
915 }
916
917 ++argPosition;
918 if (argPosition >= argType.columns() * argType.rows()) {
919 ++argIndex;
920 argPosition = 0;
921 }
922 } else {
923 SkDEBUGFAIL("not enough arguments for matrix constructor");
924 fExtraFunctions.writeText("<error>");
925 }
926 }
927 }
928
929 if (argPosition != 0 || argIndex != args.size()) {
930 SkDEBUGFAIL("incorrect number of arguments for matrix constructor");
931 fExtraFunctions.writeText(", <error>");
932 }
933
934 fExtraFunctions.writeText(")");
935}
936
John Stiles1bdafbf2020-05-28 12:17:20 -0400937// Generates a constructor for 'matrix' which reorganizes the input arguments into the proper shape.
938// Keeps track of previously generated constructors so that we won't generate more than one
939// constructor for any given permutation of input argument types. Returns the name of the
940// generated constructor method.
941String MetalCodeGenerator::getMatrixConstructHelper(const Constructor& c) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400942 const Type& matrix = c.type();
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500943 int columns = matrix.columns();
944 int rows = matrix.rows();
John Stiles8e3b6be2020-10-13 11:14:08 -0400945 const ExpressionArray& args = c.arguments();
John Stiles1bdafbf2020-05-28 12:17:20 -0400946
947 // Create the helper-method name and use it as our lookup key.
948 String name;
949 name.appendf("float%dx%d_from", columns, rows);
950 for (const std::unique_ptr<Expression>& expr : args) {
John Stiles36129132020-12-29 12:28:04 -0500951 name.appendf("_%s", this->typeName(expr->type()).c_str());
John Stiles1bdafbf2020-05-28 12:17:20 -0400952 }
953
954 // If a helper-method has already been synthesized, we don't need to synthesize it again.
955 auto [iter, newlyCreated] = fHelpers.insert(name);
956 if (!newlyCreated) {
957 return name;
958 }
959
960 // Unlike GLSL, Metal requires that matrices are initialized with exactly R vectors of C
961 // components apiece. (In Metal 2.0, you can also supply R*C scalars, but you still cannot
962 // supply a mixture of scalars and vectors.)
963 fExtraFunctions.printf("float%dx%d %s(", columns, rows, name.c_str());
964
965 size_t argIndex = 0;
966 const char* argSeparator = "";
John Stilesfcf8cb22020-08-06 14:29:22 -0400967 for (const std::unique_ptr<Expression>& expr : args) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400968 fExtraFunctions.printf("%s%s x%zu", argSeparator,
John Stiles36129132020-12-29 12:28:04 -0500969 this->typeName(expr->type()).c_str(), argIndex++);
John Stiles1bdafbf2020-05-28 12:17:20 -0400970 argSeparator = ", ";
971 }
972
973 fExtraFunctions.printf(") {\n return float%dx%d(", columns, rows);
974
John Stiles9aeed132020-11-24 17:36:06 -0500975 if (args.size() == 1 && args.front()->type().isMatrix()) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400976 this->assembleMatrixFromMatrix(args.front()->type(), rows, columns);
John Stilesfcf8cb22020-08-06 14:29:22 -0400977 } else {
978 this->assembleMatrixFromExpressions(args, rows, columns);
John Stiles1bdafbf2020-05-28 12:17:20 -0400979 }
980
John Stilesfcf8cb22020-08-06 14:29:22 -0400981 fExtraFunctions.writeText(");\n}\n");
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500982 return name;
983}
984
985bool MetalCodeGenerator::canCoerce(const Type& t1, const Type& t2) {
986 if (t1.columns() != t2.columns() || t1.rows() != t2.rows()) {
987 return false;
988 }
989 if (t1.columns() > 1) {
990 return this->canCoerce(t1.componentType(), t2.componentType());
991 }
Ethan Nicholase1f55022019-02-05 17:17:40 -0500992 return t1.isFloat() && t2.isFloat();
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500993}
994
John Stiles1bdafbf2020-05-28 12:17:20 -0400995bool MetalCodeGenerator::matrixConstructHelperIsNeeded(const Constructor& c) {
996 // A matrix construct helper is only necessary if we are, in fact, constructing a matrix.
John Stiles9aeed132020-11-24 17:36:06 -0500997 if (!c.type().isMatrix()) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400998 return false;
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500999 }
John Stiles1bdafbf2020-05-28 12:17:20 -04001000
1001 // GLSL is fairly free-form about inputs to its matrix constructors, but Metal is not; it
1002 // expects exactly R vectors of C components apiece. (Metal 2.0 also allows a list of R*C
1003 // scalars.) Some cases are simple to translate and so we handle those inline--e.g. a list of
1004 // scalars can be constructed trivially. In more complex cases, we generate a helper function
1005 // that converts our inputs into a properly-shaped matrix.
1006 // A matrix construct helper method is always used if any input argument is a matrix.
1007 // Helper methods are also necessary when any argument would span multiple rows. For instance:
1008 //
1009 // float2 x = (1, 2);
1010 // float3x2(x, 3, 4, 5, 6) = | 1 3 5 | = no helper needed; conversion can be done inline
1011 // | 2 4 6 |
1012 //
1013 // float2 x = (2, 3);
1014 // float3x2(1, x, 4, 5, 6) = | 1 3 5 | = x spans multiple rows; a helper method will be used
1015 // | 2 4 6 |
1016 //
1017 // float4 x = (1, 2, 3, 4);
1018 // float2x2(x) = | 1 3 | = x spans multiple rows; a helper method will be used
1019 // | 2 4 |
1020 //
1021
1022 int position = 0;
Ethan Nicholasf70f0442020-09-29 12:41:35 -04001023 for (const std::unique_ptr<Expression>& expr : c.arguments()) {
John Stiles1bdafbf2020-05-28 12:17:20 -04001024 // If an input argument is a matrix, we need a helper function.
John Stiles9aeed132020-11-24 17:36:06 -05001025 if (expr->type().isMatrix()) {
John Stiles1bdafbf2020-05-28 12:17:20 -04001026 return true;
1027 }
Ethan Nicholas30d30222020-09-11 12:27:26 -04001028 position += expr->type().columns();
1029 if (position > c.type().rows()) {
John Stiles1bdafbf2020-05-28 12:17:20 -04001030 // An input argument would span multiple rows; a helper function is required.
1031 return true;
1032 }
Ethan Nicholas30d30222020-09-11 12:27:26 -04001033 if (position == c.type().rows()) {
John Stiles1bdafbf2020-05-28 12:17:20 -04001034 // We've advanced to the end of a row. Wrap to the start of the next row.
1035 position = 0;
1036 }
1037 }
1038
1039 return false;
1040}
1041
1042void MetalCodeGenerator::writeConstructor(const Constructor& c, Precedence parentPrecedence) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001043 const Type& constructorType = c.type();
John Stiles1bdafbf2020-05-28 12:17:20 -04001044 // Handle special cases for single-argument constructors.
Ethan Nicholasf70f0442020-09-29 12:41:35 -04001045 if (c.arguments().size() == 1) {
John Stiles1bdafbf2020-05-28 12:17:20 -04001046 // If the type is coercible, emit it directly.
Ethan Nicholasf70f0442020-09-29 12:41:35 -04001047 const Expression& arg = *c.arguments().front();
Ethan Nicholas30d30222020-09-11 12:27:26 -04001048 const Type& argType = arg.type();
1049 if (this->canCoerce(constructorType, argType)) {
John Stiles1bdafbf2020-05-28 12:17:20 -04001050 this->writeExpression(arg, parentPrecedence);
1051 return;
1052 }
1053
1054 // Metal supports creating matrices with a scalar on the diagonal via the single-argument
1055 // matrix constructor.
John Stiles9aeed132020-11-24 17:36:06 -05001056 if (constructorType.isMatrix() && argType.isNumber()) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001057 const Type& matrix = constructorType;
John Stiles1bdafbf2020-05-28 12:17:20 -04001058 this->write("float");
1059 this->write(to_string(matrix.columns()));
1060 this->write("x");
1061 this->write(to_string(matrix.rows()));
1062 this->write("(");
1063 this->writeExpression(arg, parentPrecedence);
1064 this->write(")");
1065 return;
1066 }
1067 }
1068
1069 // Emit and invoke a matrix-constructor helper method if one is necessary.
1070 if (this->matrixConstructHelperIsNeeded(c)) {
1071 this->write(this->getMatrixConstructHelper(c));
John Stiles1fa15b12020-05-28 17:36:54 +00001072 this->write("(");
1073 const char* separator = "";
Ethan Nicholasf70f0442020-09-29 12:41:35 -04001074 for (const std::unique_ptr<Expression>& expr : c.arguments()) {
John Stiles1fa15b12020-05-28 17:36:54 +00001075 this->write(separator);
1076 separator = ", ";
Brian Osman00185012021-02-04 16:07:11 -05001077 this->writeExpression(*expr, Precedence::kSequence);
John Stilesdaa573e2020-05-28 12:17:20 -04001078 }
John Stiles1fa15b12020-05-28 17:36:54 +00001079 this->write(")");
John Stiles1bdafbf2020-05-28 12:17:20 -04001080 return;
John Stilesdaa573e2020-05-28 12:17:20 -04001081 }
John Stiles1bdafbf2020-05-28 12:17:20 -04001082
1083 // Explicitly invoke the constructor, passing in the necessary arguments.
John Stilesb4418502021-02-04 10:57:08 -05001084 this->writeType(constructorType);
1085 this->write(constructorType.isArray() ? "{" : "(");
John Stiles1bdafbf2020-05-28 12:17:20 -04001086 const char* separator = "";
1087 int scalarCount = 0;
Ethan Nicholasf70f0442020-09-29 12:41:35 -04001088 for (const std::unique_ptr<Expression>& arg : c.arguments()) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001089 const Type& argType = arg->type();
John Stiles1bdafbf2020-05-28 12:17:20 -04001090 this->write(separator);
1091 separator = ", ";
John Stiles9aeed132020-11-24 17:36:06 -05001092 if (constructorType.isMatrix() &&
Ethan Nicholas30d30222020-09-11 12:27:26 -04001093 argType.columns() < constructorType.rows()) {
John Stiles1bdafbf2020-05-28 12:17:20 -04001094 // Merge scalars and smaller vectors together.
1095 if (!scalarCount) {
John Stilesb4418502021-02-04 10:57:08 -05001096 this->writeType(constructorType.componentType());
Ethan Nicholas30d30222020-09-11 12:27:26 -04001097 this->write(to_string(constructorType.rows()));
John Stiles1bdafbf2020-05-28 12:17:20 -04001098 this->write("(");
1099 }
Ethan Nicholas30d30222020-09-11 12:27:26 -04001100 scalarCount += argType.columns();
John Stiles1bdafbf2020-05-28 12:17:20 -04001101 }
Brian Osman00185012021-02-04 16:07:11 -05001102 this->writeExpression(*arg, Precedence::kSequence);
Ethan Nicholas30d30222020-09-11 12:27:26 -04001103 if (scalarCount && scalarCount == constructorType.rows()) {
John Stiles1bdafbf2020-05-28 12:17:20 -04001104 this->write(")");
1105 scalarCount = 0;
1106 }
1107 }
John Stilesb4418502021-02-04 10:57:08 -05001108 this->write(constructorType.isArray() ? "}" : ")");
Ethan Nicholascc305772017-10-13 16:17:45 -04001109}
1110
John Stiles933043b2021-03-31 15:23:16 -04001111void MetalCodeGenerator::writeSingleArgumentConstructor(const SingleArgumentConstructor& c,
John Stilese1182782021-03-30 22:09:37 -04001112 Precedence parentPrecedence) {
1113 this->writeType(c.type());
1114 this->write("(");
1115 this->writeExpression(*c.argument(), Precedence::kSequence);
1116 this->write(")");
1117}
1118
Ethan Nicholascc305772017-10-13 16:17:45 -04001119void MetalCodeGenerator::writeFragCoord() {
Ethan Nicholasf931e402019-07-26 15:40:33 -04001120 if (fRTHeightName.length()) {
1121 this->write("float4(_fragCoord.x, ");
1122 this->write(fRTHeightName.c_str());
1123 this->write(" - _fragCoord.y, 0.0, _fragCoord.w)");
Jim Van Verth6bc650e2019-02-07 14:53:23 -05001124 } else {
1125 this->write("float4(_fragCoord.x, _fragCoord.y, 0.0, _fragCoord.w)");
1126 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001127}
1128
1129void MetalCodeGenerator::writeVariableReference(const VariableReference& ref) {
John Stiles06b84ef2020-12-09 12:35:48 -05001130 // When assembling out-param helper functions, we copy variables into local clones with matching
John Stilesf7410bd2021-01-19 13:07:55 -05001131 // names. We never want to prepend "_in." or "_globals." when writing these variables since
John Stiles06b84ef2020-12-09 12:35:48 -05001132 // we're actually targeting the clones.
1133 if (fIgnoreVariableReferenceModifiers) {
1134 this->writeName(ref.variable()->name());
1135 return;
1136 }
1137
Ethan Nicholas78686922020-10-08 06:46:27 -04001138 switch (ref.variable()->modifiers().fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001139 case SK_FRAGCOLOR_BUILTIN:
John Stilesf7410bd2021-01-19 13:07:55 -05001140 this->write("_out.sk_FragColor");
Ethan Nicholascc305772017-10-13 16:17:45 -04001141 break;
Timothy Liang6403b0e2018-05-17 10:40:04 -04001142 case SK_FRAGCOORD_BUILTIN:
1143 this->writeFragCoord();
1144 break;
Timothy Liangdc89f192018-06-13 09:20:31 -04001145 case SK_VERTEXID_BUILTIN:
1146 this->write("sk_VertexID");
1147 break;
1148 case SK_INSTANCEID_BUILTIN:
1149 this->write("sk_InstanceID");
1150 break;
Timothy Liang7b8875d2018-08-10 09:42:31 -04001151 case SK_CLOCKWISE_BUILTIN:
1152 // We'd set the front facing winding in the MTLRenderCommandEncoder to be counter
Brian Salomonf4ba4ec2020-03-19 15:54:28 -04001153 // clockwise to match Skia convention.
John Stiles270cec22021-02-17 12:59:36 -05001154 this->write(fProgram.fConfig->fSettings.fFlipY ? "_frontFacing" : "(!_frontFacing)");
Timothy Liang7b8875d2018-08-10 09:42:31 -04001155 break;
Ethan Nicholascc305772017-10-13 16:17:45 -04001156 default:
Ethan Nicholas78686922020-10-08 06:46:27 -04001157 const Variable& var = *ref.variable();
Ethan Nicholas453f67f2020-10-09 10:43:45 -04001158 if (var.storage() == Variable::Storage::kGlobal) {
Ethan Nicholas78686922020-10-08 06:46:27 -04001159 if (var.modifiers().fFlags & Modifiers::kIn_Flag) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001160 this->write("_in.");
Ethan Nicholas78686922020-10-08 06:46:27 -04001161 } else if (var.modifiers().fFlags & Modifiers::kOut_Flag) {
John Stilesf7410bd2021-01-19 13:07:55 -05001162 this->write("_out.");
Ethan Nicholas78686922020-10-08 06:46:27 -04001163 } else if (var.modifiers().fFlags & Modifiers::kUniform_Flag &&
1164 var.type().typeKind() != Type::TypeKind::kSampler) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001165 this->write("_uniforms.");
1166 } else {
John Stilesf7410bd2021-01-19 13:07:55 -05001167 this->write("_globals.");
Ethan Nicholascc305772017-10-13 16:17:45 -04001168 }
1169 }
Ethan Nicholas78686922020-10-08 06:46:27 -04001170 this->writeName(var.name());
Ethan Nicholascc305772017-10-13 16:17:45 -04001171 }
1172}
1173
1174void MetalCodeGenerator::writeIndexExpression(const IndexExpression& expr) {
Brian Osman00185012021-02-04 16:07:11 -05001175 this->writeExpression(*expr.base(), Precedence::kPostfix);
Ethan Nicholascc305772017-10-13 16:17:45 -04001176 this->write("[");
Brian Osman00185012021-02-04 16:07:11 -05001177 this->writeExpression(*expr.index(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001178 this->write("]");
1179}
1180
1181void MetalCodeGenerator::writeFieldAccess(const FieldAccess& f) {
Ethan Nicholas7a95b202020-10-09 11:55:40 -04001182 const Type::Field* field = &f.base()->type().fields()[f.fieldIndex()];
1183 if (FieldAccess::OwnerKind::kDefault == f.ownerKind()) {
Brian Osman00185012021-02-04 16:07:11 -05001184 this->writeExpression(*f.base(), Precedence::kPostfix);
Ethan Nicholascc305772017-10-13 16:17:45 -04001185 this->write(".");
1186 }
Timothy Liang7d637782018-06-05 09:58:07 -04001187 switch (field->fModifiers.fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001188 case SK_POSITION_BUILTIN:
John Stilesf7410bd2021-01-19 13:07:55 -05001189 this->write("_out.sk_Position");
Ethan Nicholascc305772017-10-13 16:17:45 -04001190 break;
1191 default:
Timothy Liang7d637782018-06-05 09:58:07 -04001192 if (field->fName == "sk_PointSize") {
John Stilesf7410bd2021-01-19 13:07:55 -05001193 this->write("_out.sk_PointSize");
Timothy Liang7d637782018-06-05 09:58:07 -04001194 } else {
Ethan Nicholas7a95b202020-10-09 11:55:40 -04001195 if (FieldAccess::OwnerKind::kAnonymousInterfaceBlock == f.ownerKind()) {
John Stilesf7410bd2021-01-19 13:07:55 -05001196 this->write("_globals.");
Timothy Liang7d637782018-06-05 09:58:07 -04001197 this->write(fInterfaceBlockNameMap[fInterfaceBlockMap[field]]);
1198 this->write("->");
1199 }
Timothy Liang651286f2018-06-07 09:55:33 -04001200 this->writeName(field->fName);
Timothy Lianga06f2152018-05-24 15:33:31 -04001201 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001202 }
1203}
1204
1205void MetalCodeGenerator::writeSwizzle(const Swizzle& swizzle) {
Brian Osman00185012021-02-04 16:07:11 -05001206 this->writeExpression(*swizzle.base(), Precedence::kPostfix);
Ethan Nicholascc305772017-10-13 16:17:45 -04001207 this->write(".");
Ethan Nicholas6b4d5812020-10-12 16:11:51 -04001208 for (int c : swizzle.components()) {
Brian Osman25647672020-09-15 15:16:56 -04001209 SkASSERT(c >= 0 && c <= 3);
1210 this->write(&("x\0y\0z\0w\0"[c * 2]));
Ethan Nicholascc305772017-10-13 16:17:45 -04001211 }
1212}
1213
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001214void MetalCodeGenerator::writeMatrixTimesEqualHelper(const Type& left, const Type& right,
1215 const Type& result) {
John Stiles01cdf012021-02-10 09:53:41 -05001216 String key = "TimesEqual" + this->typeName(left) + ":" + this->typeName(right);
John Stiles56233d12021-02-03 13:03:29 -05001217
1218 auto [iter, wasInserted] = fHelpers.insert(key);
1219 if (wasInserted) {
John Stiles368db7c2020-12-29 11:20:08 -05001220 fExtraFunctions.printf("thread %s& operator*=(thread %s& left, thread const %s& right) {\n"
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001221 " left = left * right;\n"
1222 " return left;\n"
John Stiles368db7c2020-12-29 11:20:08 -05001223 "}\n",
1224 this->typeName(result).c_str(), this->typeName(left).c_str(),
1225 this->typeName(right).c_str());
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001226 }
1227}
1228
John Stiles01cdf012021-02-10 09:53:41 -05001229void MetalCodeGenerator::writeMatrixEqualityHelper(const Type& left, const Type& right) {
1230 SkASSERTF(left.rows() == right.rows() && left.columns() == right.columns(), "left=%s, right=%s",
1231 left.description().c_str(), right.description().c_str());
1232
1233 String key = "Equality" + this->typeName(left) + ":" + this->typeName(right);
1234
1235 auto [iter, wasInserted] = fHelpers.insert(key);
1236 if (wasInserted) {
1237 fExtraFunctions.printf(
1238 "thread bool operator==(const %s left, const %s right) {\n"
1239 " return",
1240 this->typeName(left).c_str(), this->typeName(right).c_str());
1241
1242 for (int index=0; index<left.columns(); ++index) {
1243 fExtraFunctions.printf("%s all(left[%d] == right[%d])",
1244 index == 0 ? "" : " &&", index, index);
1245 }
1246 fExtraFunctions.printf(";\n"
1247 "}\n");
1248 }
1249}
1250
1251void MetalCodeGenerator::writeMatrixInequalityHelper(const Type& left, const Type& right) {
1252 SkASSERTF(left.rows() == right.rows() && left.columns() == right.columns(), "left=%s, right=%s",
1253 left.description().c_str(), right.description().c_str());
1254
1255 String key = "Inequality" + this->typeName(left) + ":" + this->typeName(right);
1256
1257 auto [iter, wasInserted] = fHelpers.insert(key);
1258 if (wasInserted) {
1259 fExtraFunctions.printf(
1260 "thread bool operator!=(const %s left, const %s right) {\n"
1261 " return",
1262 this->typeName(left).c_str(), this->typeName(right).c_str());
1263
1264 for (int index=0; index<left.columns(); ++index) {
1265 fExtraFunctions.printf("%s any(left[%d] != right[%d])",
1266 index == 0 ? "" : " ||", index, index);
1267 }
1268 fExtraFunctions.printf(";\n"
1269 "}\n");
1270 }
1271}
1272
Ethan Nicholascc305772017-10-13 16:17:45 -04001273void MetalCodeGenerator::writeBinaryExpression(const BinaryExpression& b,
1274 Precedence parentPrecedence) {
John Stiles2d4f9592020-10-30 10:29:12 -04001275 const Expression& left = *b.left();
1276 const Expression& right = *b.right();
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001277 const Type& leftType = left.type();
1278 const Type& rightType = right.type();
John Stiles45990502021-02-16 10:55:27 -05001279 Operator op = b.getOperator();
1280 Precedence precedence = op.getBinaryPrecedence();
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001281 bool needParens = precedence >= parentPrecedence;
John Stiles45990502021-02-16 10:55:27 -05001282 switch (op.kind()) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001283 case Token::Kind::TK_EQEQ:
John Stiles9aeed132020-11-24 17:36:06 -05001284 if (leftType.isVector()) {
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001285 this->write("all");
1286 needParens = true;
1287 }
1288 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001289 case Token::Kind::TK_NEQ:
John Stiles9aeed132020-11-24 17:36:06 -05001290 if (leftType.isVector()) {
Jim Van Verth36477b42019-04-11 14:57:30 -04001291 this->write("any");
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001292 needParens = true;
1293 }
1294 break;
1295 default:
1296 break;
1297 }
1298 if (needParens) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001299 this->write("(");
1300 }
John Stiles01cdf012021-02-10 09:53:41 -05001301 if (leftType.isMatrix() && rightType.isMatrix()) {
John Stiles45990502021-02-16 10:55:27 -05001302 if (op.kind() == Token::Kind::TK_STAREQ) {
John Stiles01cdf012021-02-10 09:53:41 -05001303 this->writeMatrixTimesEqualHelper(leftType, rightType, b.type());
John Stiles45990502021-02-16 10:55:27 -05001304 } else if (op.kind() == Token::Kind::TK_EQEQ) {
John Stiles01cdf012021-02-10 09:53:41 -05001305 this->writeMatrixEqualityHelper(leftType, rightType);
John Stiles45990502021-02-16 10:55:27 -05001306 } else if (op.kind() == Token::Kind::TK_NEQ) {
John Stiles01cdf012021-02-10 09:53:41 -05001307 this->writeMatrixInequalityHelper(leftType, rightType);
1308 }
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001309 }
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001310 this->writeExpression(left, precedence);
John Stiles45990502021-02-16 10:55:27 -05001311 if (op.kind() != Token::Kind::TK_EQ && op.isAssignment() &&
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001312 left.kind() == Expression::Kind::kSwizzle && !left.hasSideEffects()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001313 // This doesn't compile in Metal:
1314 // float4 x = float4(1);
1315 // x.xy *= float2x2(...);
1316 // with the error message "non-const reference cannot bind to vector element",
1317 // but switching it to x.xy = x.xy * float2x2(...) fixes it. We perform this tranformation
1318 // as long as the LHS has no side effects, and hope for the best otherwise.
1319 this->write(" = ");
Brian Osman00185012021-02-04 16:07:11 -05001320 this->writeExpression(left, Precedence::kAssignment);
Ethan Nicholascc305772017-10-13 16:17:45 -04001321 this->write(" ");
John Stilesd6449e92020-11-30 09:13:23 -05001322 String opName = OperatorName(op);
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001323 SkASSERT(opName.endsWith("="));
1324 this->write(opName.substr(0, opName.size() - 1).c_str());
Ethan Nicholascc305772017-10-13 16:17:45 -04001325 this->write(" ");
1326 } else {
John Stilesd6449e92020-11-30 09:13:23 -05001327 this->write(String(" ") + OperatorName(op) + " ");
Ethan Nicholascc305772017-10-13 16:17:45 -04001328 }
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001329 this->writeExpression(right, precedence);
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001330 if (needParens) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001331 this->write(")");
1332 }
1333}
1334
1335void MetalCodeGenerator::writeTernaryExpression(const TernaryExpression& t,
1336 Precedence parentPrecedence) {
Brian Osman00185012021-02-04 16:07:11 -05001337 if (Precedence::kTernary >= parentPrecedence) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001338 this->write("(");
1339 }
Brian Osman00185012021-02-04 16:07:11 -05001340 this->writeExpression(*t.test(), Precedence::kTernary);
Ethan Nicholascc305772017-10-13 16:17:45 -04001341 this->write(" ? ");
Brian Osman00185012021-02-04 16:07:11 -05001342 this->writeExpression(*t.ifTrue(), Precedence::kTernary);
Ethan Nicholascc305772017-10-13 16:17:45 -04001343 this->write(" : ");
Brian Osman00185012021-02-04 16:07:11 -05001344 this->writeExpression(*t.ifFalse(), Precedence::kTernary);
1345 if (Precedence::kTernary >= parentPrecedence) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001346 this->write(")");
1347 }
1348}
1349
1350void MetalCodeGenerator::writePrefixExpression(const PrefixExpression& p,
1351 Precedence parentPrecedence) {
Brian Osman00185012021-02-04 16:07:11 -05001352 if (Precedence::kPrefix >= parentPrecedence) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001353 this->write("(");
1354 }
John Stilesd6449e92020-11-30 09:13:23 -05001355 this->write(OperatorName(p.getOperator()));
Brian Osman00185012021-02-04 16:07:11 -05001356 this->writeExpression(*p.operand(), Precedence::kPrefix);
1357 if (Precedence::kPrefix >= parentPrecedence) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001358 this->write(")");
1359 }
1360}
1361
1362void MetalCodeGenerator::writePostfixExpression(const PostfixExpression& p,
1363 Precedence parentPrecedence) {
Brian Osman00185012021-02-04 16:07:11 -05001364 if (Precedence::kPostfix >= parentPrecedence) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001365 this->write("(");
1366 }
Brian Osman00185012021-02-04 16:07:11 -05001367 this->writeExpression(*p.operand(), Precedence::kPostfix);
John Stilesd6449e92020-11-30 09:13:23 -05001368 this->write(OperatorName(p.getOperator()));
Brian Osman00185012021-02-04 16:07:11 -05001369 if (Precedence::kPostfix >= parentPrecedence) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001370 this->write(")");
1371 }
1372}
1373
1374void MetalCodeGenerator::writeBoolLiteral(const BoolLiteral& b) {
Ethan Nicholas59d660c2020-09-28 09:18:15 -04001375 this->write(b.value() ? "true" : "false");
Ethan Nicholascc305772017-10-13 16:17:45 -04001376}
1377
1378void MetalCodeGenerator::writeIntLiteral(const IntLiteral& i) {
John Stiles12739df2020-12-29 09:47:20 -05001379 const Type& type = i.type();
John Stiles54e7c052021-01-11 14:22:36 -05001380 if (type == *fContext.fTypes.fUInt) {
Ethan Nicholase96cdd12020-09-28 16:27:18 -04001381 this->write(to_string(i.value() & 0xffffffff) + "u");
John Stiles54e7c052021-01-11 14:22:36 -05001382 } else if (type == *fContext.fTypes.fUShort) {
John Stiles12739df2020-12-29 09:47:20 -05001383 this->write(to_string(i.value() & 0xffff) + "u");
John Stiles54e7c052021-01-11 14:22:36 -05001384 } else if (type == *fContext.fTypes.fUByte) {
John Stiles12739df2020-12-29 09:47:20 -05001385 this->write(to_string(i.value() & 0xff) + "u");
Ethan Nicholascc305772017-10-13 16:17:45 -04001386 } else {
John Stiles12739df2020-12-29 09:47:20 -05001387 this->write(to_string(i.value()));
Ethan Nicholascc305772017-10-13 16:17:45 -04001388 }
1389}
1390
1391void MetalCodeGenerator::writeFloatLiteral(const FloatLiteral& f) {
Ethan Nicholasa3f22f12020-10-01 12:13:17 -04001392 this->write(to_string(f.value()));
Ethan Nicholascc305772017-10-13 16:17:45 -04001393}
1394
1395void MetalCodeGenerator::writeSetting(const Setting& s) {
John Stilesf57207b2021-02-02 17:50:34 -05001396 SK_ABORT("internal error; setting was not folded to a constant during compilation\n");
Ethan Nicholascc305772017-10-13 16:17:45 -04001397}
1398
John Stiles06b84ef2020-12-09 12:35:48 -05001399void MetalCodeGenerator::writeFunctionRequirementArgs(const FunctionDeclaration& f,
1400 const char*& separator) {
1401 Requirements requirements = this->requirements(f);
1402 if (requirements & kInputs_Requirement) {
1403 this->write(separator);
1404 this->write("_in");
1405 separator = ", ";
1406 }
1407 if (requirements & kOutputs_Requirement) {
1408 this->write(separator);
1409 this->write("_out");
1410 separator = ", ";
1411 }
1412 if (requirements & kUniforms_Requirement) {
1413 this->write(separator);
1414 this->write("_uniforms");
1415 separator = ", ";
1416 }
1417 if (requirements & kGlobals_Requirement) {
1418 this->write(separator);
John Stilesf7410bd2021-01-19 13:07:55 -05001419 this->write("_globals");
John Stiles06b84ef2020-12-09 12:35:48 -05001420 separator = ", ";
1421 }
1422 if (requirements & kFragCoord_Requirement) {
1423 this->write(separator);
1424 this->write("_fragCoord");
1425 separator = ", ";
1426 }
1427}
1428
1429void MetalCodeGenerator::writeFunctionRequirementParams(const FunctionDeclaration& f,
1430 const char*& separator) {
1431 Requirements requirements = this->requirements(f);
1432 if (requirements & kInputs_Requirement) {
1433 this->write(separator);
1434 this->write("Inputs _in");
1435 separator = ", ";
1436 }
1437 if (requirements & kOutputs_Requirement) {
1438 this->write(separator);
John Stilesf7410bd2021-01-19 13:07:55 -05001439 this->write("thread Outputs& _out");
John Stiles06b84ef2020-12-09 12:35:48 -05001440 separator = ", ";
1441 }
1442 if (requirements & kUniforms_Requirement) {
1443 this->write(separator);
1444 this->write("Uniforms _uniforms");
1445 separator = ", ";
1446 }
1447 if (requirements & kGlobals_Requirement) {
1448 this->write(separator);
John Stilesf7410bd2021-01-19 13:07:55 -05001449 this->write("thread Globals& _globals");
John Stiles06b84ef2020-12-09 12:35:48 -05001450 separator = ", ";
1451 }
1452 if (requirements & kFragCoord_Requirement) {
1453 this->write(separator);
1454 this->write("float4 _fragCoord");
1455 separator = ", ";
1456 }
1457}
1458
John Stilesda5cdf62021-01-28 11:47:29 -05001459int MetalCodeGenerator::getUniformBinding(const Modifiers& m) {
1460 return (m.fLayout.fBinding >= 0) ? m.fLayout.fBinding
John Stiles270cec22021-02-17 12:59:36 -05001461 : fProgram.fConfig->fSettings.fDefaultUniformBinding;
John Stilesda5cdf62021-01-28 11:47:29 -05001462}
1463
1464int MetalCodeGenerator::getUniformSet(const Modifiers& m) {
1465 return (m.fLayout.fSet >= 0) ? m.fLayout.fSet
John Stiles270cec22021-02-17 12:59:36 -05001466 : fProgram.fConfig->fSettings.fDefaultUniformSet;
John Stilesda5cdf62021-01-28 11:47:29 -05001467}
1468
John Stiles569249b2020-11-03 12:18:22 -05001469bool MetalCodeGenerator::writeFunctionDeclaration(const FunctionDeclaration& f) {
John Stilesf7410bd2021-01-19 13:07:55 -05001470 fRTHeightName = fProgram.fInputs.fRTHeight ? "_globals._anonInterface0->u_skRTHeight" : "";
Ethan Nicholascc305772017-10-13 16:17:45 -04001471 const char* separator = "";
John Stilese8da4d22021-03-24 09:19:45 -04001472 if (f.isMain()) {
John Stiles270cec22021-02-17 12:59:36 -05001473 switch (fProgram.fConfig->fKind) {
John Stilesdbd4e6f2021-02-16 13:29:15 -05001474 case ProgramKind::kFragment:
Timothy Liangb8eeb802018-07-23 16:46:16 -04001475 this->write("fragment Outputs fragmentMain");
Ethan Nicholascc305772017-10-13 16:17:45 -04001476 break;
John Stilesdbd4e6f2021-02-16 13:29:15 -05001477 case ProgramKind::kVertex:
Timothy Liangb8eeb802018-07-23 16:46:16 -04001478 this->write("vertex Outputs vertexMain");
Ethan Nicholascc305772017-10-13 16:17:45 -04001479 break;
1480 default:
John Stiles3fabfc02020-09-25 15:51:28 -04001481 fErrors.error(-1, "unsupported kind of program");
John Stiles569249b2020-11-03 12:18:22 -05001482 return false;
Ethan Nicholascc305772017-10-13 16:17:45 -04001483 }
1484 this->write("(Inputs _in [[stage_in]]");
1485 if (-1 != fUniformBuffer) {
1486 this->write(", constant Uniforms& _uniforms [[buffer(" +
1487 to_string(fUniformBuffer) + ")]]");
1488 }
Brian Osman133724c2020-10-28 14:14:39 -04001489 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04001490 if (e->is<GlobalVarDeclaration>()) {
1491 const GlobalVarDeclaration& decls = e->as<GlobalVarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001492 const VarDeclaration& var = decls.declaration()->as<VarDeclaration>();
1493 if (var.var().type().typeKind() == Type::TypeKind::kSampler) {
1494 if (var.var().modifiers().fLayout.fBinding < 0) {
Brian Osmanc0213602020-10-06 14:43:32 -04001495 fErrors.error(decls.fOffset,
John Stilesb41d5bb2021-01-26 16:28:12 -05001496 "Metal samplers must have 'layout(binding=...)'");
John Stiles569249b2020-11-03 12:18:22 -05001497 return false;
Timothy Liangee84fe12018-05-18 14:38:19 -04001498 }
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001499 if (var.var().type().dimensions() != SpvDim2D) {
John Stiles569249b2020-11-03 12:18:22 -05001500 // Not yet implemented--Skia currently only uses 2D textures.
Brian Osmanc0213602020-10-06 14:43:32 -04001501 fErrors.error(decls.fOffset, "Unsupported texture dimensions");
John Stiles569249b2020-11-03 12:18:22 -05001502 return false;
Brian Osmanc0213602020-10-06 14:43:32 -04001503 }
1504 this->write(", texture2d<float> ");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001505 this->writeName(var.var().name());
Brian Osmanc0213602020-10-06 14:43:32 -04001506 this->write("[[texture(");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001507 this->write(to_string(var.var().modifiers().fLayout.fBinding));
Brian Osmanc0213602020-10-06 14:43:32 -04001508 this->write(")]]");
1509 this->write(", sampler ");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001510 this->writeName(var.var().name());
Brian Osmanc0213602020-10-06 14:43:32 -04001511 this->write(SAMPLER_SUFFIX);
1512 this->write("[[sampler(");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001513 this->write(to_string(var.var().modifiers().fLayout.fBinding));
Brian Osmanc0213602020-10-06 14:43:32 -04001514 this->write(")]]");
Timothy Liang6403b0e2018-05-17 10:40:04 -04001515 }
Brian Osman1179fcf2020-10-08 16:04:40 -04001516 } else if (e->is<InterfaceBlock>()) {
1517 const InterfaceBlock& intf = e->as<InterfaceBlock>();
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001518 if (intf.typeName() == "sk_PerVertex") {
Timothy Lianga06f2152018-05-24 15:33:31 -04001519 continue;
1520 }
1521 this->write(", constant ");
John Stilesb4418502021-02-04 10:57:08 -05001522 this->writeType(intf.variable().type());
Timothy Lianga06f2152018-05-24 15:33:31 -04001523 this->write("& " );
1524 this->write(fInterfaceBlockNameMap[&intf]);
1525 this->write(" [[buffer(");
John Stilesda5cdf62021-01-28 11:47:29 -05001526 this->write(to_string(this->getUniformBinding(intf.variable().modifiers())));
Timothy Lianga06f2152018-05-24 15:33:31 -04001527 this->write(")]]");
Timothy Liang6403b0e2018-05-17 10:40:04 -04001528 }
1529 }
John Stiles270cec22021-02-17 12:59:36 -05001530 if (fProgram.fConfig->fKind == ProgramKind::kFragment) {
Jim Van Verth6bc650e2019-02-07 14:53:23 -05001531 if (fProgram.fInputs.fRTHeight && fInterfaceBlockNameMap.empty()) {
Timothy Liang5422f9a2018-08-10 10:57:55 -04001532 this->write(", constant sksl_synthetic_uniforms& _anonInterface0 [[buffer(1)]]");
Ethan Nicholasf931e402019-07-26 15:40:33 -04001533 fRTHeightName = "_anonInterface0.u_skRTHeight";
Timothy Liang5422f9a2018-08-10 10:57:55 -04001534 }
Timothy Liang7b8875d2018-08-10 09:42:31 -04001535 this->write(", bool _frontFacing [[front_facing]]");
Timothy Liang7d637782018-06-05 09:58:07 -04001536 this->write(", float4 _fragCoord [[position]]");
John Stiles270cec22021-02-17 12:59:36 -05001537 } else if (fProgram.fConfig->fKind == ProgramKind::kVertex) {
Timothy Liangdc89f192018-06-13 09:20:31 -04001538 this->write(", uint sk_VertexID [[vertex_id]], uint sk_InstanceID [[instance_id]]");
Timothy Liang7d637782018-06-05 09:58:07 -04001539 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001540 separator = ", ";
1541 } else {
John Stilesb4418502021-02-04 10:57:08 -05001542 this->writeType(f.returnType());
Timothy Liang651286f2018-06-07 09:55:33 -04001543 this->write(" ");
John Stilese1068342021-03-22 11:57:41 -04001544 this->writeName(f.mangledName());
Timothy Liang651286f2018-06-07 09:55:33 -04001545 this->write("(");
John Stiles06b84ef2020-12-09 12:35:48 -05001546 this->writeFunctionRequirementParams(f, separator);
Ethan Nicholascc305772017-10-13 16:17:45 -04001547 }
John Stiles569249b2020-11-03 12:18:22 -05001548 for (const auto& param : f.parameters()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001549 this->write(separator);
1550 separator = ", ";
John Stiles06b84ef2020-12-09 12:35:48 -05001551 this->writeModifiers(param->modifiers(), /*globalContext=*/false);
Ethan Nicholas30d30222020-09-11 12:27:26 -04001552 const Type* type = &param->type();
John Stilesb4418502021-02-04 10:57:08 -05001553 this->writeType(*type);
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001554 if (param->modifiers().fFlags & Modifiers::kOut_Flag) {
John Stilesf2bd5012020-12-04 11:58:26 -05001555 this->write("&");
Ethan Nicholascc305772017-10-13 16:17:45 -04001556 }
Timothy Liang651286f2018-06-07 09:55:33 -04001557 this->write(" ");
Ethan Nicholase2c49992020-10-05 11:49:11 -04001558 this->writeName(param->name());
Ethan Nicholascc305772017-10-13 16:17:45 -04001559 }
John Stiles569249b2020-11-03 12:18:22 -05001560 this->write(")");
1561 return true;
1562}
Ethan Nicholascc305772017-10-13 16:17:45 -04001563
John Stiles569249b2020-11-03 12:18:22 -05001564void MetalCodeGenerator::writeFunctionPrototype(const FunctionPrototype& f) {
1565 this->writeFunctionDeclaration(f.declaration());
1566 this->writeLine(";");
1567}
1568
John Stiles986c7fb2020-12-01 14:44:56 -05001569static bool is_block_ending_with_return(const Statement* stmt) {
1570 // This function detects (potentially nested) blocks that end in a return statement.
1571 if (!stmt->is<Block>()) {
1572 return false;
1573 }
1574 const StatementArray& block = stmt->as<Block>().children();
1575 for (int index = block.count(); index--; ) {
1576 const Statement& stmt = *block[index];
1577 if (stmt.is<ReturnStatement>()) {
1578 return true;
1579 }
1580 if (stmt.is<Block>()) {
1581 return is_block_ending_with_return(&stmt);
1582 }
1583 if (!stmt.is<Nop>()) {
1584 break;
1585 }
1586 }
1587 return false;
1588}
1589
John Stiles569249b2020-11-03 12:18:22 -05001590void MetalCodeGenerator::writeFunction(const FunctionDefinition& f) {
John Stiles270cec22021-02-17 12:59:36 -05001591 SkASSERT(!fProgram.fConfig->fSettings.fFragColorIsInOut);
Brian Salomondc092132018-04-04 10:14:16 -04001592
John Stiles569249b2020-11-03 12:18:22 -05001593 if (!this->writeFunctionDeclaration(f.declaration())) {
1594 return;
1595 }
1596
John Stiles986c7fb2020-12-01 14:44:56 -05001597 fCurrentFunction = &f.declaration();
1598 SkScopeExit clearCurrentFunction([&] { fCurrentFunction = nullptr; });
1599
John Stiles569249b2020-11-03 12:18:22 -05001600 this->writeLine(" {");
1601
John Stilese8da4d22021-03-24 09:19:45 -04001602 if (f.declaration().isMain()) {
John Stilescdcdb042020-07-06 09:03:51 -04001603 this->writeGlobalInit();
John Stilesf7410bd2021-01-19 13:07:55 -05001604 this->writeLine(" Outputs _out;");
John Stiles37279172021-01-21 22:24:28 -05001605 this->writeLine(" (void)_out;");
Ethan Nicholascc305772017-10-13 16:17:45 -04001606 }
John Stilesc67b3622020-05-28 17:53:13 -04001607
Ethan Nicholascc305772017-10-13 16:17:45 -04001608 fFunctionHeader = "";
Ethan Nicholascc305772017-10-13 16:17:45 -04001609 StringStream buffer;
John Stiles44532372020-12-07 12:33:55 -05001610 {
1611 AutoOutputStream outputToBuffer(this, &buffer);
1612 fIndentation++;
1613 for (const std::unique_ptr<Statement>& stmt : f.body()->as<Block>().children()) {
1614 if (!stmt->isEmpty()) {
1615 this->writeStatement(*stmt);
John Stilese8b5a732021-03-12 13:25:52 -05001616 this->finishLine();
John Stiles44532372020-12-07 12:33:55 -05001617 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001618 }
John Stilese8da4d22021-03-24 09:19:45 -04001619 if (f.declaration().isMain()) {
John Stiles44532372020-12-07 12:33:55 -05001620 // If the main function doesn't end with a return, we need to synthesize one here.
1621 if (!is_block_ending_with_return(f.body().get())) {
1622 this->writeReturnStatementFromMain();
John Stilese8b5a732021-03-12 13:25:52 -05001623 this->finishLine();
John Stiles44532372020-12-07 12:33:55 -05001624 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001625 }
John Stiles44532372020-12-07 12:33:55 -05001626 fIndentation--;
1627 this->writeLine("}");
Ethan Nicholascc305772017-10-13 16:17:45 -04001628 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001629 this->write(fFunctionHeader);
1630 this->write(buffer.str());
1631}
1632
1633void MetalCodeGenerator::writeModifiers(const Modifiers& modifiers,
John Stiles06b84ef2020-12-09 12:35:48 -05001634 bool globalContext) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001635 if (modifiers.fFlags & Modifiers::kOut_Flag) {
1636 this->write("thread ");
1637 }
1638 if (modifiers.fFlags & Modifiers::kConst_Flag) {
John Stiles0bd55782021-02-09 18:29:40 -05001639 this->write("const ");
Ethan Nicholascc305772017-10-13 16:17:45 -04001640 }
1641}
1642
1643void MetalCodeGenerator::writeInterfaceBlock(const InterfaceBlock& intf) {
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001644 if ("sk_PerVertex" == intf.typeName()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001645 return;
1646 }
John Stiles06b84ef2020-12-09 12:35:48 -05001647 this->writeModifiers(intf.variable().modifiers(), /*globalContext=*/true);
Timothy Liangdc89f192018-06-13 09:20:31 -04001648 this->write("struct ");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001649 this->writeLine(intf.typeName() + " {");
1650 const Type* structType = &intf.variable().type();
John Stilesbb43b7e2020-12-03 17:36:32 -05001651 if (structType->isArray()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001652 structType = &structType->componentType();
1653 }
Timothy Liangdc89f192018-06-13 09:20:31 -04001654 fIndentation++;
John Stiles3dba3ee2020-12-02 23:35:49 -05001655 this->writeFields(structType->fields(), structType->fOffset, &intf);
Jim Van Verth3d482992019-02-07 10:48:05 -05001656 if (fProgram.fInputs.fRTHeight) {
Timothy Liang7d637782018-06-05 09:58:07 -04001657 this->writeLine("float u_skRTHeight;");
Ethan Nicholascc305772017-10-13 16:17:45 -04001658 }
1659 fIndentation--;
1660 this->write("}");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001661 if (intf.instanceName().size()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001662 this->write(" ");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001663 this->write(intf.instanceName());
John Stilesd39aec02020-12-03 10:42:26 -05001664 if (intf.arraySize() > 0) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001665 this->write("[");
John Stilesd39aec02020-12-03 10:42:26 -05001666 this->write(to_string(intf.arraySize()));
Ethan Nicholascc305772017-10-13 16:17:45 -04001667 this->write("]");
John Stilesd39aec02020-12-03 10:42:26 -05001668 } else if (intf.arraySize() == Type::kUnsizedArray){
1669 this->write("[]");
Ethan Nicholascc305772017-10-13 16:17:45 -04001670 }
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001671 fInterfaceBlockNameMap[&intf] = intf.instanceName();
Timothy Lianga06f2152018-05-24 15:33:31 -04001672 } else {
Timothy Liang7d637782018-06-05 09:58:07 -04001673 fInterfaceBlockNameMap[&intf] = "_anonInterface" + to_string(fAnonInterfaceCount++);
Ethan Nicholascc305772017-10-13 16:17:45 -04001674 }
1675 this->writeLine(";");
1676}
1677
Timothy Liangdc89f192018-06-13 09:20:31 -04001678void MetalCodeGenerator::writeFields(const std::vector<Type::Field>& fields, int parentOffset,
1679 const InterfaceBlock* parentIntf) {
Timothy Liang609fbe32018-08-10 16:40:49 -04001680 MemoryLayout memoryLayout(MemoryLayout::kMetal_Standard);
Timothy Liangdc89f192018-06-13 09:20:31 -04001681 int currentOffset = 0;
1682 for (const auto& field: fields) {
1683 int fieldOffset = field.fModifiers.fLayout.fOffset;
1684 const Type* fieldType = field.fType;
John Stiles21f5f452020-11-30 09:57:59 -05001685 if (!MemoryLayout::LayoutIsSupported(*fieldType)) {
John Stiles0023c0c2020-11-16 13:32:18 -05001686 fErrors.error(parentOffset, "type '" + fieldType->name() + "' is not permitted here");
1687 return;
1688 }
Timothy Liangdc89f192018-06-13 09:20:31 -04001689 if (fieldOffset != -1) {
1690 if (currentOffset > fieldOffset) {
1691 fErrors.error(parentOffset,
John Stilesd7199b22020-12-30 16:22:58 -05001692 "offset of field '" + field.fName + "' must be at least " +
1693 to_string((int) currentOffset));
Brian Osman8609a242020-09-08 14:01:49 -04001694 return;
Timothy Liangdc89f192018-06-13 09:20:31 -04001695 } else if (currentOffset < fieldOffset) {
1696 this->write("char pad");
1697 this->write(to_string(fPaddingCount++));
1698 this->write("[");
1699 this->write(to_string(fieldOffset - currentOffset));
1700 this->writeLine("];");
1701 currentOffset = fieldOffset;
1702 }
1703 int alignment = memoryLayout.alignment(*fieldType);
1704 if (fieldOffset % alignment) {
1705 fErrors.error(parentOffset,
1706 "offset of field '" + field.fName + "' must be a multiple of " +
1707 to_string((int) alignment));
Brian Osman8609a242020-09-08 14:01:49 -04001708 return;
Timothy Liangdc89f192018-06-13 09:20:31 -04001709 }
1710 }
Brian Osman8609a242020-09-08 14:01:49 -04001711 size_t fieldSize = memoryLayout.size(*fieldType);
1712 if (fieldSize > static_cast<size_t>(std::numeric_limits<int>::max() - currentOffset)) {
1713 fErrors.error(parentOffset, "field offset overflow");
1714 return;
1715 }
1716 currentOffset += fieldSize;
John Stiles06b84ef2020-12-09 12:35:48 -05001717 this->writeModifiers(field.fModifiers, /*globalContext=*/false);
John Stilesb4418502021-02-04 10:57:08 -05001718 this->writeType(*fieldType);
Timothy Liangdc89f192018-06-13 09:20:31 -04001719 this->write(" ");
1720 this->writeName(field.fName);
Timothy Liangdc89f192018-06-13 09:20:31 -04001721 this->writeLine(";");
1722 if (parentIntf) {
1723 fInterfaceBlockMap[&field] = parentIntf;
1724 }
1725 }
1726}
1727
Ethan Nicholascc305772017-10-13 16:17:45 -04001728void MetalCodeGenerator::writeVarInitializer(const Variable& var, const Expression& value) {
Brian Osman00185012021-02-04 16:07:11 -05001729 this->writeExpression(value, Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001730}
1731
Timothy Liang651286f2018-06-07 09:55:33 -04001732void MetalCodeGenerator::writeName(const String& name) {
1733 if (fReservedWords.find(name) != fReservedWords.end()) {
1734 this->write("_"); // adding underscore before name to avoid conflict with reserved words
1735 }
1736 this->write(name);
1737}
1738
John Stilesb4418502021-02-04 10:57:08 -05001739void MetalCodeGenerator::writeVarDeclaration(const VarDeclaration& varDecl, bool global) {
1740 if (global && !(varDecl.var().modifiers().fFlags & Modifiers::kConst_Flag)) {
Brian Osmanc0213602020-10-06 14:43:32 -04001741 return;
Ethan Nicholascc305772017-10-13 16:17:45 -04001742 }
John Stilesb4418502021-02-04 10:57:08 -05001743 this->writeModifiers(varDecl.var().modifiers(), global);
1744 this->writeType(varDecl.var().type());
Brian Osmanc0213602020-10-06 14:43:32 -04001745 this->write(" ");
John Stilesb4418502021-02-04 10:57:08 -05001746 this->writeName(varDecl.var().name());
1747 if (varDecl.value()) {
Brian Osmanc0213602020-10-06 14:43:32 -04001748 this->write(" = ");
John Stilesb4418502021-02-04 10:57:08 -05001749 this->writeVarInitializer(varDecl.var(), *varDecl.value());
Brian Osmanc0213602020-10-06 14:43:32 -04001750 }
1751 this->write(";");
Ethan Nicholascc305772017-10-13 16:17:45 -04001752}
1753
1754void MetalCodeGenerator::writeStatement(const Statement& s) {
Ethan Nicholase6592142020-09-08 10:22:09 -04001755 switch (s.kind()) {
1756 case Statement::Kind::kBlock:
John Stiles26f98502020-08-18 09:30:51 -04001757 this->writeBlock(s.as<Block>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001758 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001759 case Statement::Kind::kExpression:
Brian Osman00185012021-02-04 16:07:11 -05001760 this->writeExpression(*s.as<ExpressionStatement>().expression(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001761 this->write(";");
1762 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001763 case Statement::Kind::kReturn:
John Stiles26f98502020-08-18 09:30:51 -04001764 this->writeReturnStatement(s.as<ReturnStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001765 break;
Brian Osmanc0213602020-10-06 14:43:32 -04001766 case Statement::Kind::kVarDeclaration:
1767 this->writeVarDeclaration(s.as<VarDeclaration>(), false);
Ethan Nicholascc305772017-10-13 16:17:45 -04001768 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001769 case Statement::Kind::kIf:
John Stiles26f98502020-08-18 09:30:51 -04001770 this->writeIfStatement(s.as<IfStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001771 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001772 case Statement::Kind::kFor:
John Stiles26f98502020-08-18 09:30:51 -04001773 this->writeForStatement(s.as<ForStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001774 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001775 case Statement::Kind::kDo:
John Stiles26f98502020-08-18 09:30:51 -04001776 this->writeDoStatement(s.as<DoStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001777 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001778 case Statement::Kind::kSwitch:
John Stiles26f98502020-08-18 09:30:51 -04001779 this->writeSwitchStatement(s.as<SwitchStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001780 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001781 case Statement::Kind::kBreak:
Ethan Nicholascc305772017-10-13 16:17:45 -04001782 this->write("break;");
1783 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001784 case Statement::Kind::kContinue:
Ethan Nicholascc305772017-10-13 16:17:45 -04001785 this->write("continue;");
1786 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001787 case Statement::Kind::kDiscard:
Timothy Lianga06f2152018-05-24 15:33:31 -04001788 this->write("discard_fragment();");
Ethan Nicholascc305772017-10-13 16:17:45 -04001789 break;
John Stiles98c1f822020-09-09 14:18:53 -04001790 case Statement::Kind::kInlineMarker:
Ethan Nicholase6592142020-09-08 10:22:09 -04001791 case Statement::Kind::kNop:
Ethan Nicholascc305772017-10-13 16:17:45 -04001792 this->write(";");
1793 break;
1794 default:
John Stileseada7bc2021-02-02 16:29:32 -05001795 SkDEBUGFAILF("unsupported statement: %s", s.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -05001796 break;
Ethan Nicholascc305772017-10-13 16:17:45 -04001797 }
1798}
1799
Ethan Nicholascc305772017-10-13 16:17:45 -04001800void MetalCodeGenerator::writeBlock(const Block& b) {
John Stiles3744bd62021-01-26 13:49:43 -05001801 // Write scope markers if this block is a scope, or if the block is empty (since we need to emit
1802 // something here to make the code valid).
1803 bool isScope = b.isScope() || b.isEmpty();
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001804 if (isScope) {
Ethan Nicholas70728ef2020-05-28 07:09:00 -04001805 this->writeLine("{");
1806 fIndentation++;
1807 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001808 for (const std::unique_ptr<Statement>& stmt : b.children()) {
1809 if (!stmt->isEmpty()) {
1810 this->writeStatement(*stmt);
John Stilese8b5a732021-03-12 13:25:52 -05001811 this->finishLine();
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001812 }
1813 }
1814 if (isScope) {
Ethan Nicholas70728ef2020-05-28 07:09:00 -04001815 fIndentation--;
1816 this->write("}");
1817 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001818}
1819
1820void MetalCodeGenerator::writeIfStatement(const IfStatement& stmt) {
1821 this->write("if (");
Brian Osman00185012021-02-04 16:07:11 -05001822 this->writeExpression(*stmt.test(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001823 this->write(") ");
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04001824 this->writeStatement(*stmt.ifTrue());
1825 if (stmt.ifFalse()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001826 this->write(" else ");
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04001827 this->writeStatement(*stmt.ifFalse());
Ethan Nicholascc305772017-10-13 16:17:45 -04001828 }
1829}
1830
1831void MetalCodeGenerator::writeForStatement(const ForStatement& f) {
Brian Osmand6f23382020-12-15 17:08:59 -05001832 // Emit loops of the form 'for(;test;)' as 'while(test)', which is probably how they started
1833 if (!f.initializer() && f.test() && !f.next()) {
1834 this->write("while (");
Brian Osman00185012021-02-04 16:07:11 -05001835 this->writeExpression(*f.test(), Precedence::kTopLevel);
Brian Osmand6f23382020-12-15 17:08:59 -05001836 this->write(") ");
1837 this->writeStatement(*f.statement());
1838 return;
1839 }
1840
Ethan Nicholascc305772017-10-13 16:17:45 -04001841 this->write("for (");
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04001842 if (f.initializer() && !f.initializer()->isEmpty()) {
1843 this->writeStatement(*f.initializer());
Ethan Nicholascc305772017-10-13 16:17:45 -04001844 } else {
1845 this->write("; ");
1846 }
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04001847 if (f.test()) {
Brian Osman00185012021-02-04 16:07:11 -05001848 this->writeExpression(*f.test(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001849 }
1850 this->write("; ");
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04001851 if (f.next()) {
Brian Osman00185012021-02-04 16:07:11 -05001852 this->writeExpression(*f.next(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001853 }
1854 this->write(") ");
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04001855 this->writeStatement(*f.statement());
Ethan Nicholascc305772017-10-13 16:17:45 -04001856}
1857
Ethan Nicholascc305772017-10-13 16:17:45 -04001858void MetalCodeGenerator::writeDoStatement(const DoStatement& d) {
1859 this->write("do ");
Ethan Nicholas1fd61162020-09-28 13:14:19 -04001860 this->writeStatement(*d.statement());
Ethan Nicholascc305772017-10-13 16:17:45 -04001861 this->write(" while (");
Brian Osman00185012021-02-04 16:07:11 -05001862 this->writeExpression(*d.test(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001863 this->write(");");
1864}
1865
1866void MetalCodeGenerator::writeSwitchStatement(const SwitchStatement& s) {
1867 this->write("switch (");
Brian Osman00185012021-02-04 16:07:11 -05001868 this->writeExpression(*s.value(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001869 this->writeLine(") {");
1870 fIndentation++;
John Stilesb23a64b2021-03-11 08:27:59 -05001871 for (const std::unique_ptr<Statement>& stmt : s.cases()) {
1872 const SwitchCase& c = stmt->as<SwitchCase>();
1873 if (c.value()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001874 this->write("case ");
John Stilesb23a64b2021-03-11 08:27:59 -05001875 this->writeExpression(*c.value(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001876 this->writeLine(":");
1877 } else {
1878 this->writeLine("default:");
1879 }
John Stilesb23a64b2021-03-11 08:27:59 -05001880 if (!c.statement()->isEmpty()) {
John Stilesc3ce43b2021-03-09 15:37:01 -05001881 fIndentation++;
John Stilesb23a64b2021-03-11 08:27:59 -05001882 this->writeStatement(*c.statement());
John Stilese8b5a732021-03-12 13:25:52 -05001883 this->finishLine();
John Stilesc3ce43b2021-03-09 15:37:01 -05001884 fIndentation--;
Ethan Nicholascc305772017-10-13 16:17:45 -04001885 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001886 }
1887 fIndentation--;
1888 this->write("}");
1889}
1890
John Stiles986c7fb2020-12-01 14:44:56 -05001891void MetalCodeGenerator::writeReturnStatementFromMain() {
1892 // main functions in Metal return a magic _out parameter that doesn't exist in SkSL.
John Stiles270cec22021-02-17 12:59:36 -05001893 switch (fProgram.fConfig->fKind) {
John Stilesdbd4e6f2021-02-16 13:29:15 -05001894 case ProgramKind::kFragment:
John Stilesf7410bd2021-01-19 13:07:55 -05001895 this->write("return _out;");
John Stiles986c7fb2020-12-01 14:44:56 -05001896 break;
John Stilesdbd4e6f2021-02-16 13:29:15 -05001897 case ProgramKind::kVertex:
John Stilesf7410bd2021-01-19 13:07:55 -05001898 this->write("return (_out.sk_Position.y = -_out.sk_Position.y, _out);");
John Stiles986c7fb2020-12-01 14:44:56 -05001899 break;
1900 default:
1901 SkDEBUGFAIL("unsupported kind of program");
1902 }
1903}
1904
Ethan Nicholascc305772017-10-13 16:17:45 -04001905void MetalCodeGenerator::writeReturnStatement(const ReturnStatement& r) {
John Stilese8da4d22021-03-24 09:19:45 -04001906 if (fCurrentFunction && fCurrentFunction->isMain()) {
John Stiles986c7fb2020-12-01 14:44:56 -05001907 if (r.expression()) {
John Stiles97d18172021-01-22 16:47:42 -05001908 if (r.expression()->type() == *fContext.fTypes.fHalf4) {
1909 this->write("_out.sk_FragColor = ");
Brian Osman00185012021-02-04 16:07:11 -05001910 this->writeExpression(*r.expression(), Precedence::kTopLevel);
John Stiles97d18172021-01-22 16:47:42 -05001911 this->writeLine(";");
1912 } else {
1913 fErrors.error(r.fOffset, "Metal does not support returning '" +
1914 r.expression()->type().description() + "' from main()");
1915 }
John Stiles986c7fb2020-12-01 14:44:56 -05001916 }
1917 this->writeReturnStatementFromMain();
1918 return;
1919 }
1920
Ethan Nicholascc305772017-10-13 16:17:45 -04001921 this->write("return");
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04001922 if (r.expression()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001923 this->write(" ");
Brian Osman00185012021-02-04 16:07:11 -05001924 this->writeExpression(*r.expression(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001925 }
1926 this->write(";");
1927}
1928
Michael Ludwigbf58add2021-03-16 10:40:11 -04001929void MetalCodeGenerator::writeHeader() {
1930 this->write("#include <metal_stdlib>\n");
1931 this->write("#include <simd/simd.h>\n");
1932 this->write("using namespace metal;\n");
1933}
1934
Ethan Nicholascc305772017-10-13 16:17:45 -04001935void MetalCodeGenerator::writeUniformStruct() {
Brian Osman133724c2020-10-28 14:14:39 -04001936 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04001937 if (e->is<GlobalVarDeclaration>()) {
1938 const GlobalVarDeclaration& decls = e->as<GlobalVarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001939 const Variable& var = decls.declaration()->as<VarDeclaration>().var();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001940 if (var.modifiers().fFlags & Modifiers::kUniform_Flag &&
Brian Osmanc0213602020-10-06 14:43:32 -04001941 var.type().typeKind() != Type::TypeKind::kSampler) {
John Stilesda5cdf62021-01-28 11:47:29 -05001942 int uniformSet = this->getUniformSet(var.modifiers());
John Stilesd8fc95d2021-01-26 16:22:53 -05001943 // Make sure that the program's uniform-set value is consistent throughout.
Ethan Nicholascc305772017-10-13 16:17:45 -04001944 if (-1 == fUniformBuffer) {
1945 this->write("struct Uniforms {\n");
John Stilesd8fc95d2021-01-26 16:22:53 -05001946 fUniformBuffer = uniformSet;
1947 } else if (uniformSet != fUniformBuffer) {
1948 fErrors.error(decls.fOffset, "Metal backend requires all uniforms to have "
1949 "the same 'layout(set=...)'");
Ethan Nicholascc305772017-10-13 16:17:45 -04001950 }
1951 this->write(" ");
John Stilesb4418502021-02-04 10:57:08 -05001952 this->writeType(var.type());
Ethan Nicholascc305772017-10-13 16:17:45 -04001953 this->write(" ");
Brian Osmanc0213602020-10-06 14:43:32 -04001954 this->writeName(var.name());
Ethan Nicholascc305772017-10-13 16:17:45 -04001955 this->write(";\n");
1956 }
1957 }
1958 }
1959 if (-1 != fUniformBuffer) {
1960 this->write("};\n");
1961 }
1962}
1963
1964void MetalCodeGenerator::writeInputStruct() {
1965 this->write("struct Inputs {\n");
Brian Osman133724c2020-10-28 14:14:39 -04001966 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04001967 if (e->is<GlobalVarDeclaration>()) {
1968 const GlobalVarDeclaration& decls = e->as<GlobalVarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001969 const Variable& var = decls.declaration()->as<VarDeclaration>().var();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001970 if (var.modifiers().fFlags & Modifiers::kIn_Flag &&
1971 -1 == var.modifiers().fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001972 this->write(" ");
John Stilesb4418502021-02-04 10:57:08 -05001973 this->writeType(var.type());
Ethan Nicholascc305772017-10-13 16:17:45 -04001974 this->write(" ");
Brian Osmanc0213602020-10-06 14:43:32 -04001975 this->writeName(var.name());
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001976 if (-1 != var.modifiers().fLayout.fLocation) {
John Stiles270cec22021-02-17 12:59:36 -05001977 if (fProgram.fConfig->fKind == ProgramKind::kVertex) {
Brian Osmanc0213602020-10-06 14:43:32 -04001978 this->write(" [[attribute(" +
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001979 to_string(var.modifiers().fLayout.fLocation) + ")]]");
John Stiles270cec22021-02-17 12:59:36 -05001980 } else if (fProgram.fConfig->fKind == ProgramKind::kFragment) {
Brian Osmanc0213602020-10-06 14:43:32 -04001981 this->write(" [[user(locn" +
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001982 to_string(var.modifiers().fLayout.fLocation) + ")]]");
Ethan Nicholascc305772017-10-13 16:17:45 -04001983 }
1984 }
1985 this->write(";\n");
1986 }
1987 }
1988 }
1989 this->write("};\n");
1990}
1991
1992void MetalCodeGenerator::writeOutputStruct() {
1993 this->write("struct Outputs {\n");
John Stiles270cec22021-02-17 12:59:36 -05001994 if (fProgram.fConfig->fKind == ProgramKind::kVertex) {
Timothy Liangb8eeb802018-07-23 16:46:16 -04001995 this->write(" float4 sk_Position [[position]];\n");
John Stiles270cec22021-02-17 12:59:36 -05001996 } else if (fProgram.fConfig->fKind == ProgramKind::kFragment) {
Timothy Liangde0be802018-08-10 13:48:08 -04001997 this->write(" float4 sk_FragColor [[color(0)]];\n");
Timothy Liang7d637782018-06-05 09:58:07 -04001998 }
Brian Osman133724c2020-10-28 14:14:39 -04001999 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04002000 if (e->is<GlobalVarDeclaration>()) {
2001 const GlobalVarDeclaration& decls = e->as<GlobalVarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04002002 const Variable& var = decls.declaration()->as<VarDeclaration>().var();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002003 if (var.modifiers().fFlags & Modifiers::kOut_Flag &&
2004 -1 == var.modifiers().fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002005 this->write(" ");
John Stilesb4418502021-02-04 10:57:08 -05002006 this->writeType(var.type());
Ethan Nicholascc305772017-10-13 16:17:45 -04002007 this->write(" ");
Brian Osmanc0213602020-10-06 14:43:32 -04002008 this->writeName(var.name());
John Stiles842b3592020-12-01 10:36:37 -05002009
2010 int location = var.modifiers().fLayout.fLocation;
2011 if (location < 0) {
2012 fErrors.error(var.fOffset,
2013 "Metal out variables must have 'layout(location=...)'");
John Stiles270cec22021-02-17 12:59:36 -05002014 } else if (fProgram.fConfig->fKind == ProgramKind::kVertex) {
John Stiles842b3592020-12-01 10:36:37 -05002015 this->write(" [[user(locn" + to_string(location) + ")]]");
John Stiles270cec22021-02-17 12:59:36 -05002016 } else if (fProgram.fConfig->fKind == ProgramKind::kFragment) {
John Stiles842b3592020-12-01 10:36:37 -05002017 this->write(" [[color(" + to_string(location) + ")");
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002018 int colorIndex = var.modifiers().fLayout.fIndex;
Brian Osmanc0213602020-10-06 14:43:32 -04002019 if (colorIndex) {
2020 this->write(", index(" + to_string(colorIndex) + ")");
Timothy Liang7d637782018-06-05 09:58:07 -04002021 }
Brian Osmanc0213602020-10-06 14:43:32 -04002022 this->write("]]");
Ethan Nicholascc305772017-10-13 16:17:45 -04002023 }
2024 this->write(";\n");
2025 }
2026 }
Timothy Liang7d637782018-06-05 09:58:07 -04002027 }
John Stiles270cec22021-02-17 12:59:36 -05002028 if (fProgram.fConfig->fKind == ProgramKind::kVertex) {
Jim Van Verth3913d3e2020-08-31 15:16:57 -04002029 this->write(" float sk_PointSize [[point_size]];\n");
Timothy Liang7d637782018-06-05 09:58:07 -04002030 }
2031 this->write("};\n");
2032}
2033
2034void MetalCodeGenerator::writeInterfaceBlocks() {
2035 bool wroteInterfaceBlock = false;
Brian Osman133724c2020-10-28 14:14:39 -04002036 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04002037 if (e->is<InterfaceBlock>()) {
2038 this->writeInterfaceBlock(e->as<InterfaceBlock>());
Timothy Liang7d637782018-06-05 09:58:07 -04002039 wroteInterfaceBlock = true;
2040 }
2041 }
Jim Van Verth3d482992019-02-07 10:48:05 -05002042 if (!wroteInterfaceBlock && fProgram.fInputs.fRTHeight) {
Timothy Liang7d637782018-06-05 09:58:07 -04002043 this->writeLine("struct sksl_synthetic_uniforms {");
2044 this->writeLine(" float u_skRTHeight;");
2045 this->writeLine("};");
2046 }
Ethan Nicholascc305772017-10-13 16:17:45 -04002047}
2048
John Stilesdc75a972020-11-25 16:24:55 -05002049void MetalCodeGenerator::writeStructDefinitions() {
2050 for (const ProgramElement* e : fProgram.elements()) {
2051 if (e->is<StructDefinition>()) {
Brian Osman02bc5222021-01-28 11:00:20 -05002052 this->writeStructDefinition(e->as<StructDefinition>());
John Stilesdc75a972020-11-25 16:24:55 -05002053 }
2054 }
2055}
2056
John Stilescdcdb042020-07-06 09:03:51 -04002057void MetalCodeGenerator::visitGlobalStruct(GlobalStructVisitor* visitor) {
2058 // Visit the interface blocks.
2059 for (const auto& [interfaceType, interfaceName] : fInterfaceBlockNameMap) {
John Stilesfdb8dbe2020-12-04 11:00:03 -05002060 visitor->visitInterfaceBlock(*interfaceType, interfaceName);
John Stilescdcdb042020-07-06 09:03:51 -04002061 }
Brian Osman133724c2020-10-28 14:14:39 -04002062 for (const ProgramElement* element : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04002063 if (!element->is<GlobalVarDeclaration>()) {
John Stilescdcdb042020-07-06 09:03:51 -04002064 continue;
Timothy Liang7d637782018-06-05 09:58:07 -04002065 }
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04002066 const GlobalVarDeclaration& global = element->as<GlobalVarDeclaration>();
2067 const VarDeclaration& decl = global.declaration()->as<VarDeclaration>();
2068 const Variable& var = decl.var();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002069 if ((!var.modifiers().fFlags && -1 == var.modifiers().fLayout.fBuiltin) ||
Brian Osmanc0213602020-10-06 14:43:32 -04002070 var.type().typeKind() == Type::TypeKind::kSampler) {
2071 if (var.type().typeKind() == Type::TypeKind::kSampler) {
2072 // Samplers are represented as a "texture/sampler" duo in the global struct.
John Stilesfdb8dbe2020-12-04 11:00:03 -05002073 visitor->visitTexture(var.type(), var.name());
2074 visitor->visitSampler(var.type(), String(var.name()) + SAMPLER_SUFFIX);
Brian Osmanc0213602020-10-06 14:43:32 -04002075 } else {
2076 // Visit a regular variable.
John Stilesfdb8dbe2020-12-04 11:00:03 -05002077 visitor->visitVariable(var, decl.value().get());
Timothy Liangee84fe12018-05-18 14:38:19 -04002078 }
2079 }
2080 }
John Stilescdcdb042020-07-06 09:03:51 -04002081}
2082
2083void MetalCodeGenerator::writeGlobalStruct() {
2084 class : public GlobalStructVisitor {
2085 public:
John Stilesfdb8dbe2020-12-04 11:00:03 -05002086 void visitInterfaceBlock(const InterfaceBlock& block, const String& blockName) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002087 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002088 fCodeGen->write(" constant ");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04002089 fCodeGen->write(block.typeName());
John Stilescdcdb042020-07-06 09:03:51 -04002090 fCodeGen->write("* ");
2091 fCodeGen->writeName(blockName);
2092 fCodeGen->write(";\n");
2093 }
John Stilesfdb8dbe2020-12-04 11:00:03 -05002094 void visitTexture(const Type& type, const String& name) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002095 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002096 fCodeGen->write(" ");
John Stilesb4418502021-02-04 10:57:08 -05002097 fCodeGen->writeType(type);
John Stilescdcdb042020-07-06 09:03:51 -04002098 fCodeGen->write(" ");
2099 fCodeGen->writeName(name);
2100 fCodeGen->write(";\n");
2101 }
John Stilesfdb8dbe2020-12-04 11:00:03 -05002102 void visitSampler(const Type&, const String& name) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002103 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002104 fCodeGen->write(" sampler ");
2105 fCodeGen->writeName(name);
2106 fCodeGen->write(";\n");
2107 }
John Stilesfdb8dbe2020-12-04 11:00:03 -05002108 void visitVariable(const Variable& var, const Expression* value) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002109 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002110 fCodeGen->write(" ");
John Stilesb4418502021-02-04 10:57:08 -05002111 fCodeGen->writeType(var.type());
John Stilescdcdb042020-07-06 09:03:51 -04002112 fCodeGen->write(" ");
Ethan Nicholase2c49992020-10-05 11:49:11 -04002113 fCodeGen->writeName(var.name());
John Stilescdcdb042020-07-06 09:03:51 -04002114 fCodeGen->write(";\n");
2115 }
John Stiles83f3b8d2020-12-07 17:52:25 -05002116 void addElement() {
John Stilescdcdb042020-07-06 09:03:51 -04002117 if (fFirst) {
2118 fCodeGen->write("struct Globals {\n");
2119 fFirst = false;
2120 }
2121 }
John Stiles83f3b8d2020-12-07 17:52:25 -05002122 void finish() {
John Stilescdcdb042020-07-06 09:03:51 -04002123 if (!fFirst) {
John Stiles83f3b8d2020-12-07 17:52:25 -05002124 fCodeGen->writeLine("};");
John Stilescdcdb042020-07-06 09:03:51 -04002125 fFirst = true;
2126 }
2127 }
2128
2129 MetalCodeGenerator* fCodeGen = nullptr;
2130 bool fFirst = true;
2131 } visitor;
2132
2133 visitor.fCodeGen = this;
2134 this->visitGlobalStruct(&visitor);
John Stiles83f3b8d2020-12-07 17:52:25 -05002135 visitor.finish();
John Stilescdcdb042020-07-06 09:03:51 -04002136}
2137
2138void MetalCodeGenerator::writeGlobalInit() {
2139 class : public GlobalStructVisitor {
2140 public:
John Stilesfdb8dbe2020-12-04 11:00:03 -05002141 void visitInterfaceBlock(const InterfaceBlock& blockType,
John Stilescdcdb042020-07-06 09:03:51 -04002142 const String& blockName) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002143 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002144 fCodeGen->write("&");
2145 fCodeGen->writeName(blockName);
2146 }
John Stilesfdb8dbe2020-12-04 11:00:03 -05002147 void visitTexture(const Type&, const String& name) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002148 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002149 fCodeGen->writeName(name);
2150 }
John Stilesfdb8dbe2020-12-04 11:00:03 -05002151 void visitSampler(const Type&, const String& name) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002152 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002153 fCodeGen->writeName(name);
2154 }
John Stilesfdb8dbe2020-12-04 11:00:03 -05002155 void visitVariable(const Variable& var, const Expression* value) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002156 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002157 if (value) {
2158 fCodeGen->writeVarInitializer(var, *value);
2159 } else {
2160 fCodeGen->write("{}");
2161 }
2162 }
John Stiles83f3b8d2020-12-07 17:52:25 -05002163 void addElement() {
John Stilescdcdb042020-07-06 09:03:51 -04002164 if (fFirst) {
John Stilesf7410bd2021-01-19 13:07:55 -05002165 fCodeGen->write(" Globals _globals{");
John Stilescdcdb042020-07-06 09:03:51 -04002166 fFirst = false;
2167 } else {
2168 fCodeGen->write(", ");
2169 }
2170 }
John Stiles83f3b8d2020-12-07 17:52:25 -05002171 void finish() {
John Stilescdcdb042020-07-06 09:03:51 -04002172 if (!fFirst) {
2173 fCodeGen->writeLine("};");
John Stiles37279172021-01-21 22:24:28 -05002174 fCodeGen->writeLine(" (void)_globals;");
John Stilescdcdb042020-07-06 09:03:51 -04002175 }
2176 }
2177 MetalCodeGenerator* fCodeGen = nullptr;
2178 bool fFirst = true;
2179 } visitor;
2180
2181 visitor.fCodeGen = this;
2182 this->visitGlobalStruct(&visitor);
John Stiles83f3b8d2020-12-07 17:52:25 -05002183 visitor.finish();
Timothy Liangee84fe12018-05-18 14:38:19 -04002184}
2185
Ethan Nicholascc305772017-10-13 16:17:45 -04002186void MetalCodeGenerator::writeProgramElement(const ProgramElement& e) {
Ethan Nicholase6592142020-09-08 10:22:09 -04002187 switch (e.kind()) {
2188 case ProgramElement::Kind::kExtension:
Ethan Nicholascc305772017-10-13 16:17:45 -04002189 break;
Brian Osmanc0213602020-10-06 14:43:32 -04002190 case ProgramElement::Kind::kGlobalVar: {
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04002191 const GlobalVarDeclaration& global = e.as<GlobalVarDeclaration>();
2192 const VarDeclaration& decl = global.declaration()->as<VarDeclaration>();
2193 int builtin = decl.var().modifiers().fLayout.fBuiltin;
Brian Osmanc0213602020-10-06 14:43:32 -04002194 if (-1 == builtin) {
2195 // normal var
2196 this->writeVarDeclaration(decl, true);
John Stilese8b5a732021-03-12 13:25:52 -05002197 this->finishLine();
Brian Osmanc0213602020-10-06 14:43:32 -04002198 } else if (SK_FRAGCOLOR_BUILTIN == builtin) {
2199 // ignore
Ethan Nicholascc305772017-10-13 16:17:45 -04002200 }
2201 break;
2202 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002203 case ProgramElement::Kind::kInterfaceBlock:
Timothy Liang7d637782018-06-05 09:58:07 -04002204 // handled in writeInterfaceBlocks, do nothing
Ethan Nicholascc305772017-10-13 16:17:45 -04002205 break;
John Stilesdc75a972020-11-25 16:24:55 -05002206 case ProgramElement::Kind::kStructDefinition:
2207 // Handled in writeStructDefinitions. Do nothing.
2208 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04002209 case ProgramElement::Kind::kFunction:
John Stiles3dc0da62020-08-19 17:48:31 -04002210 this->writeFunction(e.as<FunctionDefinition>());
Ethan Nicholascc305772017-10-13 16:17:45 -04002211 break;
John Stiles569249b2020-11-03 12:18:22 -05002212 case ProgramElement::Kind::kFunctionPrototype:
2213 this->writeFunctionPrototype(e.as<FunctionPrototype>());
2214 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04002215 case ProgramElement::Kind::kModifiers:
John Stiles06b84ef2020-12-09 12:35:48 -05002216 this->writeModifiers(e.as<ModifiersDeclaration>().modifiers(),
2217 /*globalContext=*/true);
Ethan Nicholascc305772017-10-13 16:17:45 -04002218 this->writeLine(";");
2219 break;
John Stiles712fd6b2020-11-25 22:25:43 -05002220 case ProgramElement::Kind::kEnum:
2221 break;
Ethan Nicholascc305772017-10-13 16:17:45 -04002222 default:
John Stileseada7bc2021-02-02 16:29:32 -05002223 SkDEBUGFAILF("unsupported program element: %s\n", e.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -05002224 break;
Ethan Nicholascc305772017-10-13 16:17:45 -04002225 }
2226}
2227
Ethan Nicholasff350cb2020-05-14 14:05:13 -04002228MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const Expression* e) {
2229 if (!e) {
2230 return kNo_Requirements;
2231 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002232 switch (e->kind()) {
2233 case Expression::Kind::kFunctionCall: {
John Stiles3dc0da62020-08-19 17:48:31 -04002234 const FunctionCall& f = e->as<FunctionCall>();
Ethan Nicholas0dec9922020-10-05 15:51:52 -04002235 Requirements result = this->requirements(f.function());
2236 for (const auto& arg : f.arguments()) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04002237 result |= this->requirements(arg.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002238 }
2239 return result;
2240 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002241 case Expression::Kind::kConstructor: {
John Stiles3dc0da62020-08-19 17:48:31 -04002242 const Constructor& c = e->as<Constructor>();
Ethan Nicholascc305772017-10-13 16:17:45 -04002243 Requirements result = kNo_Requirements;
John Stilesd8eb8752021-04-01 11:49:10 -04002244 for (const auto& arg : c.argumentSpan()) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04002245 result |= this->requirements(arg.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002246 }
2247 return result;
2248 }
John Stilese1182782021-03-30 22:09:37 -04002249 case Expression::Kind::kConstructorDiagonalMatrix: {
2250 return this->requirements(e->as<ConstructorDiagonalMatrix>().argument().get());
2251 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002252 case Expression::Kind::kFieldAccess: {
John Stiles3dc0da62020-08-19 17:48:31 -04002253 const FieldAccess& f = e->as<FieldAccess>();
Ethan Nicholas7a95b202020-10-09 11:55:40 -04002254 if (FieldAccess::OwnerKind::kAnonymousInterfaceBlock == f.ownerKind()) {
Timothy Liang7d637782018-06-05 09:58:07 -04002255 return kGlobals_Requirement;
2256 }
Ethan Nicholas7a95b202020-10-09 11:55:40 -04002257 return this->requirements(f.base().get());
Timothy Liang7d637782018-06-05 09:58:07 -04002258 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002259 case Expression::Kind::kSwizzle:
Ethan Nicholas6b4d5812020-10-12 16:11:51 -04002260 return this->requirements(e->as<Swizzle>().base().get());
Ethan Nicholase6592142020-09-08 10:22:09 -04002261 case Expression::Kind::kBinary: {
2262 const BinaryExpression& bin = e->as<BinaryExpression>();
John Stiles2d4f9592020-10-30 10:29:12 -04002263 return this->requirements(bin.left().get()) |
2264 this->requirements(bin.right().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002265 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002266 case Expression::Kind::kIndex: {
John Stiles3dc0da62020-08-19 17:48:31 -04002267 const IndexExpression& idx = e->as<IndexExpression>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04002268 return this->requirements(idx.base().get()) | this->requirements(idx.index().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002269 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002270 case Expression::Kind::kPrefix:
Ethan Nicholas444ccc62020-10-09 10:16:22 -04002271 return this->requirements(e->as<PrefixExpression>().operand().get());
Ethan Nicholase6592142020-09-08 10:22:09 -04002272 case Expression::Kind::kPostfix:
Ethan Nicholas444ccc62020-10-09 10:16:22 -04002273 return this->requirements(e->as<PostfixExpression>().operand().get());
Ethan Nicholase6592142020-09-08 10:22:09 -04002274 case Expression::Kind::kTernary: {
John Stiles3dc0da62020-08-19 17:48:31 -04002275 const TernaryExpression& t = e->as<TernaryExpression>();
Ethan Nicholasdd218162020-10-08 05:48:01 -04002276 return this->requirements(t.test().get()) | this->requirements(t.ifTrue().get()) |
2277 this->requirements(t.ifFalse().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002278 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002279 case Expression::Kind::kVariableReference: {
John Stiles3dc0da62020-08-19 17:48:31 -04002280 const VariableReference& v = e->as<VariableReference>();
Ethan Nicholas78686922020-10-08 06:46:27 -04002281 const Modifiers& modifiers = v.variable()->modifiers();
Ethan Nicholascc305772017-10-13 16:17:45 -04002282 Requirements result = kNo_Requirements;
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002283 if (modifiers.fLayout.fBuiltin == SK_FRAGCOORD_BUILTIN) {
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -04002284 result = kGlobals_Requirement | kFragCoord_Requirement;
Ethan Nicholas453f67f2020-10-09 10:43:45 -04002285 } else if (Variable::Storage::kGlobal == v.variable()->storage()) {
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002286 if (modifiers.fFlags & Modifiers::kIn_Flag) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002287 result = kInputs_Requirement;
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002288 } else if (modifiers.fFlags & Modifiers::kOut_Flag) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002289 result = kOutputs_Requirement;
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002290 } else if (modifiers.fFlags & Modifiers::kUniform_Flag &&
Ethan Nicholas78686922020-10-08 06:46:27 -04002291 v.variable()->type().typeKind() != Type::TypeKind::kSampler) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002292 result = kUniforms_Requirement;
Timothy Liangee84fe12018-05-18 14:38:19 -04002293 } else {
2294 result = kGlobals_Requirement;
Ethan Nicholascc305772017-10-13 16:17:45 -04002295 }
2296 }
2297 return result;
2298 }
2299 default:
2300 return kNo_Requirements;
2301 }
2302}
2303
Ethan Nicholasff350cb2020-05-14 14:05:13 -04002304MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const Statement* s) {
2305 if (!s) {
2306 return kNo_Requirements;
2307 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002308 switch (s->kind()) {
2309 case Statement::Kind::kBlock: {
Ethan Nicholascc305772017-10-13 16:17:45 -04002310 Requirements result = kNo_Requirements;
Ethan Nicholas7bd60432020-09-25 14:31:59 -04002311 for (const std::unique_ptr<Statement>& child : s->as<Block>().children()) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04002312 result |= this->requirements(child.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002313 }
2314 return result;
2315 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002316 case Statement::Kind::kVarDeclaration: {
John Stiles3dc0da62020-08-19 17:48:31 -04002317 const VarDeclaration& var = s->as<VarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04002318 return this->requirements(var.value().get());
Timothy Liang7d637782018-06-05 09:58:07 -04002319 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002320 case Statement::Kind::kExpression:
Ethan Nicholasd503a5a2020-09-30 09:29:55 -04002321 return this->requirements(s->as<ExpressionStatement>().expression().get());
Ethan Nicholase6592142020-09-08 10:22:09 -04002322 case Statement::Kind::kReturn: {
John Stiles3dc0da62020-08-19 17:48:31 -04002323 const ReturnStatement& r = s->as<ReturnStatement>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04002324 return this->requirements(r.expression().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002325 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002326 case Statement::Kind::kIf: {
John Stiles3dc0da62020-08-19 17:48:31 -04002327 const IfStatement& i = s->as<IfStatement>();
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04002328 return this->requirements(i.test().get()) |
2329 this->requirements(i.ifTrue().get()) |
2330 this->requirements(i.ifFalse().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002331 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002332 case Statement::Kind::kFor: {
John Stiles3dc0da62020-08-19 17:48:31 -04002333 const ForStatement& f = s->as<ForStatement>();
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04002334 return this->requirements(f.initializer().get()) |
2335 this->requirements(f.test().get()) |
2336 this->requirements(f.next().get()) |
2337 this->requirements(f.statement().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002338 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002339 case Statement::Kind::kDo: {
John Stiles3dc0da62020-08-19 17:48:31 -04002340 const DoStatement& d = s->as<DoStatement>();
Ethan Nicholas1fd61162020-09-28 13:14:19 -04002341 return this->requirements(d.test().get()) |
2342 this->requirements(d.statement().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002343 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002344 case Statement::Kind::kSwitch: {
John Stiles3dc0da62020-08-19 17:48:31 -04002345 const SwitchStatement& sw = s->as<SwitchStatement>();
Ethan Nicholas01b05e52020-10-22 15:53:41 -04002346 Requirements result = this->requirements(sw.value().get());
John Stilesb23a64b2021-03-11 08:27:59 -05002347 for (const std::unique_ptr<Statement>& sc : sw.cases()) {
2348 result |= this->requirements(sc->as<SwitchCase>().statement().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002349 }
2350 return result;
2351 }
2352 default:
2353 return kNo_Requirements;
2354 }
2355}
2356
2357MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const FunctionDeclaration& f) {
Ethan Nicholased84b732020-10-08 11:45:44 -04002358 if (f.isBuiltin()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002359 return kNo_Requirements;
2360 }
2361 auto found = fRequirements.find(&f);
2362 if (found == fRequirements.end()) {
Ethan Nicholas65a8f562019-04-19 14:00:26 -04002363 fRequirements[&f] = kNo_Requirements;
Brian Osman133724c2020-10-28 14:14:39 -04002364 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04002365 if (e->is<FunctionDefinition>()) {
2366 const FunctionDefinition& def = e->as<FunctionDefinition>();
Ethan Nicholas0a5d0962020-10-14 13:33:18 -04002367 if (&def.declaration() == &f) {
2368 Requirements reqs = this->requirements(def.body().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002369 fRequirements[&f] = reqs;
2370 return reqs;
2371 }
2372 }
2373 }
John Stiles569249b2020-11-03 12:18:22 -05002374 // We never found a definition for this declared function, but it's legal to prototype a
2375 // function without ever giving a definition, as long as you don't call it.
2376 return kNo_Requirements;
Ethan Nicholascc305772017-10-13 16:17:45 -04002377 }
2378 return found->second;
2379}
2380
Timothy Liangb8eeb802018-07-23 16:46:16 -04002381bool MetalCodeGenerator::generateCode() {
John Stiles44532372020-12-07 12:33:55 -05002382 StringStream header;
2383 {
2384 AutoOutputStream outputToHeader(this, &header, &fIndentation);
Michael Ludwigbf58add2021-03-16 10:40:11 -04002385 this->writeHeader();
John Stiles44532372020-12-07 12:33:55 -05002386 this->writeStructDefinitions();
2387 this->writeUniformStruct();
2388 this->writeInputStruct();
2389 this->writeOutputStruct();
2390 this->writeInterfaceBlocks();
2391 this->writeGlobalStruct();
2392 }
2393 StringStream body;
2394 {
2395 AutoOutputStream outputToBody(this, &body, &fIndentation);
2396 for (const ProgramElement* e : fProgram.elements()) {
2397 this->writeProgramElement(*e);
2398 }
2399 }
2400 write_stringstream(header, *fOut);
2401 write_stringstream(fExtraFunctions, *fOut);
2402 write_stringstream(body, *fOut);
Brian Osman8609a242020-09-08 14:01:49 -04002403 return 0 == fErrors.errorCount();
Ethan Nicholascc305772017-10-13 16:17:45 -04002404}
2405
John Stilesa6841be2020-08-06 14:11:56 -04002406} // namespace SkSL