blob: e24f35815d0890e31c4f9768057addf1fe8300e1 [file] [log] [blame]
Ethan Nicholascc305772017-10-13 16:17:45 -04001/*
2 * Copyright 2016 Google Inc.
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
7
Mike Kleinc0bd9f92019-04-23 12:05:21 -05008#include "src/sksl/SkSLMetalCodeGenerator.h"
Ethan Nicholascc305772017-10-13 16:17:45 -04009
John Stiles986c7fb2020-12-01 14:44:56 -050010#include "src/core/SkScopeExit.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050011#include "src/sksl/SkSLCompiler.h"
John Stiles0023c0c2020-11-16 13:32:18 -050012#include "src/sksl/SkSLMemoryLayout.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050013#include "src/sksl/ir/SkSLExpressionStatement.h"
14#include "src/sksl/ir/SkSLExtension.h"
15#include "src/sksl/ir/SkSLIndexExpression.h"
16#include "src/sksl/ir/SkSLModifiersDeclaration.h"
17#include "src/sksl/ir/SkSLNop.h"
John Stilesdc75a972020-11-25 16:24:55 -050018#include "src/sksl/ir/SkSLStructDefinition.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050019#include "src/sksl/ir/SkSLVariableReference.h"
Ethan Nicholascc305772017-10-13 16:17:45 -040020
Brian Osmanc262a122020-08-06 16:34:34 -040021#include <algorithm>
22
Ethan Nicholascc305772017-10-13 16:17:45 -040023namespace SkSL {
24
John Stilesd6449e92020-11-30 09:13:23 -050025const char* MetalCodeGenerator::OperatorName(Token::Kind op) {
26 switch (op) {
27 case Token::Kind::TK_LOGICALXOR: return "!=";
28 default: return Compiler::OperatorName(op);
29 }
30}
31
John Stilescdcdb042020-07-06 09:03:51 -040032class MetalCodeGenerator::GlobalStructVisitor {
33public:
34 virtual ~GlobalStructVisitor() = default;
John Stilesfdb8dbe2020-12-04 11:00:03 -050035 virtual void visitInterfaceBlock(const InterfaceBlock& block, const String& blockName) = 0;
36 virtual void visitTexture(const Type& type, const String& name) = 0;
37 virtual void visitSampler(const Type& type, const String& name) = 0;
38 virtual void visitVariable(const Variable& var, const Expression* value) = 0;
John Stilescdcdb042020-07-06 09:03:51 -040039};
40
Timothy Liangee84fe12018-05-18 14:38:19 -040041void MetalCodeGenerator::setupIntrinsics() {
Timothy Liang7d637782018-06-05 09:58:07 -040042#define METAL(x) std::make_pair(kMetal_IntrinsicKind, k ## x ## _MetalIntrinsic)
43#define SPECIAL(x) std::make_pair(kSpecial_IntrinsicKind, k ## x ## _SpecialIntrinsic)
John Stiles0063a9f2020-12-10 18:01:45 -050044 fIntrinsicMap[String("floatBitsToInt")] = SPECIAL(Bitcast);
45 fIntrinsicMap[String("floatBitsToUint")] = SPECIAL(Bitcast);
46 fIntrinsicMap[String("intBitsToFloat")] = SPECIAL(Bitcast);
47 fIntrinsicMap[String("uintBitsToFloat")] = SPECIAL(Bitcast);
John Stilese2d34f82020-12-10 18:02:02 -050048 fIntrinsicMap[String("degrees")] = SPECIAL(Degrees);
Brian Osman46787d52020-11-24 14:18:23 -050049 fIntrinsicMap[String("distance")] = SPECIAL(Distance);
50 fIntrinsicMap[String("dot")] = SPECIAL(Dot);
John Stilesad0571f2020-12-10 18:03:10 -050051 fIntrinsicMap[String("faceforward")] = SPECIAL(Faceforward);
John Stiles86424eb2020-12-11 11:17:14 -050052 fIntrinsicMap[String("findLSB")] = SPECIAL(FindLSB);
John Stiles9685e522020-12-14 11:52:14 -050053 fIntrinsicMap[String("findMSB")] = SPECIAL(FindMSB);
Brian Osman46787d52020-11-24 14:18:23 -050054 fIntrinsicMap[String("length")] = SPECIAL(Length);
Timothy Liang651286f2018-06-07 09:55:33 -040055 fIntrinsicMap[String("mod")] = SPECIAL(Mod);
Brian Osman46787d52020-11-24 14:18:23 -050056 fIntrinsicMap[String("normalize")] = SPECIAL(Normalize);
John Stilese2d34f82020-12-10 18:02:02 -050057 fIntrinsicMap[String("radians")] = SPECIAL(Radians);
Brian Osman46787d52020-11-24 14:18:23 -050058 fIntrinsicMap[String("sample")] = SPECIAL(Texture);
Ethan Nicholas0dc80872019-02-08 15:46:24 -050059 fIntrinsicMap[String("equal")] = METAL(Equal);
60 fIntrinsicMap[String("notEqual")] = METAL(NotEqual);
Timothy Lianga06f2152018-05-24 15:33:31 -040061 fIntrinsicMap[String("lessThan")] = METAL(LessThan);
62 fIntrinsicMap[String("lessThanEqual")] = METAL(LessThanEqual);
63 fIntrinsicMap[String("greaterThan")] = METAL(GreaterThan);
64 fIntrinsicMap[String("greaterThanEqual")] = METAL(GreaterThanEqual);
Timothy Liangee84fe12018-05-18 14:38:19 -040065}
66
Ethan Nicholascc305772017-10-13 16:17:45 -040067void MetalCodeGenerator::write(const char* s) {
68 if (!s[0]) {
69 return;
70 }
71 if (fAtLineStart) {
72 for (int i = 0; i < fIndentation; i++) {
73 fOut->writeText(" ");
74 }
75 }
76 fOut->writeText(s);
77 fAtLineStart = false;
78}
79
80void MetalCodeGenerator::writeLine(const char* s) {
81 this->write(s);
82 fOut->writeText(fLineEnding);
83 fAtLineStart = true;
84}
85
86void MetalCodeGenerator::write(const String& s) {
87 this->write(s.c_str());
88}
89
90void MetalCodeGenerator::writeLine(const String& s) {
91 this->writeLine(s.c_str());
92}
93
94void MetalCodeGenerator::writeLine() {
95 this->writeLine("");
96}
97
98void MetalCodeGenerator::writeExtension(const Extension& ext) {
Ethan Nicholasefb09e22020-09-30 10:17:00 -040099 this->writeLine("#extension " + ext.name() + " : enable");
Ethan Nicholascc305772017-10-13 16:17:45 -0400100}
101
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500102String MetalCodeGenerator::typeName(const Type& type) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400103 switch (type.typeKind()) {
104 case Type::TypeKind::kVector:
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500105 return this->typeName(type.componentType()) + to_string(type.columns());
Ethan Nicholase6592142020-09-08 10:22:09 -0400106 case Type::TypeKind::kMatrix:
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500107 return this->typeName(type.componentType()) + to_string(type.columns()) + "x" +
108 to_string(type.rows());
Ethan Nicholase6592142020-09-08 10:22:09 -0400109 case Type::TypeKind::kSampler:
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500110 return "texture2d<float>"; // FIXME - support other texture types;
John Stilesfd41d872020-11-25 22:39:45 -0500111 case Type::TypeKind::kEnum:
112 return "int";
Ethan Nicholascc305772017-10-13 16:17:45 -0400113 default:
Timothy Liang43d225f2018-07-19 15:27:13 -0400114 if (type == *fContext.fHalf_Type) {
115 // FIXME - Currently only supporting floats in MSL to avoid type coercion issues.
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500116 return fContext.fFloat_Type->name();
Timothy Liang43d225f2018-07-19 15:27:13 -0400117 } else if (type == *fContext.fByte_Type) {
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500118 return "char";
Timothy Liang43d225f2018-07-19 15:27:13 -0400119 } else if (type == *fContext.fUByte_Type) {
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500120 return "uchar";
Timothy Liang7d637782018-06-05 09:58:07 -0400121 } else {
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500122 return type.name();
Timothy Liang7d637782018-06-05 09:58:07 -0400123 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400124 }
125}
126
John Stilesdc75a972020-11-25 16:24:55 -0500127bool MetalCodeGenerator::writeStructDefinition(const Type& type) {
128 for (const Type* search : fWrittenStructs) {
129 if (*search == type) {
130 // already written
131 return false;
132 }
133 }
134 fWrittenStructs.push_back(&type);
135 this->writeLine("struct " + type.name() + " {");
136 fIndentation++;
137 this->writeFields(type.fields(), type.fOffset);
138 fIndentation--;
139 this->write("}");
140 return true;
141}
142
John Stiles3dba3ee2020-12-02 23:35:49 -0500143// Flags an error if an array type is found. Meant to be used in places where an array type might
144// appear in the SkSL/IR, but can't be represented by Metal.
John Stilesea166702020-12-11 17:30:47 -0500145void MetalCodeGenerator::disallowArrayTypes(const Type& type, int offset) {
John Stilesc0c51062020-12-03 17:16:29 -0500146 if (type.isArray()) {
John Stilesea166702020-12-11 17:30:47 -0500147 fErrors.error(offset, "Metal does not support array types in this context");
John Stiles3dba3ee2020-12-02 23:35:49 -0500148 }
149}
150
151// Writes the base type, stripping array suffixes. e.g. `float[2]` will output `float`.
152// Call `writeArrayDimensions` to write the type's accompanying array sizes.
153void MetalCodeGenerator::writeBaseType(const Type& type) {
154 switch (type.typeKind()) {
155 case Type::TypeKind::kStruct:
156 if (!this->writeStructDefinition(type)) {
157 this->write(type.name());
158 }
159 break;
160 case Type::TypeKind::kArray:
161 this->writeBaseType(type.componentType());
162 break;
163 default:
164 this->write(this->typeName(type));
165 break;
166 }
167}
168
169// Writes the array suffix of a type, if one exists. e.g. `float[2][4]` will output `[2][4]`.
170void MetalCodeGenerator::writeArrayDimensions(const Type& type) {
John Stilesc0c51062020-12-03 17:16:29 -0500171 if (type.isArray()) {
John Stiles3dba3ee2020-12-02 23:35:49 -0500172 this->write("[");
173 if (type.columns() != Type::kUnsizedArray) {
174 this->write(to_string(type.columns()));
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500175 }
John Stiles3dba3ee2020-12-02 23:35:49 -0500176 this->write("]");
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500177 }
178}
179
Ethan Nicholascc305772017-10-13 16:17:45 -0400180void MetalCodeGenerator::writeExpression(const Expression& expr, Precedence parentPrecedence) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400181 switch (expr.kind()) {
182 case Expression::Kind::kBinary:
John Stiles81365af2020-08-18 09:24:00 -0400183 this->writeBinaryExpression(expr.as<BinaryExpression>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400184 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400185 case Expression::Kind::kBoolLiteral:
John Stiles81365af2020-08-18 09:24:00 -0400186 this->writeBoolLiteral(expr.as<BoolLiteral>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400187 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400188 case Expression::Kind::kConstructor:
John Stiles81365af2020-08-18 09:24:00 -0400189 this->writeConstructor(expr.as<Constructor>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400190 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400191 case Expression::Kind::kIntLiteral:
John Stiles81365af2020-08-18 09:24:00 -0400192 this->writeIntLiteral(expr.as<IntLiteral>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400193 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400194 case Expression::Kind::kFieldAccess:
John Stiles81365af2020-08-18 09:24:00 -0400195 this->writeFieldAccess(expr.as<FieldAccess>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400196 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400197 case Expression::Kind::kFloatLiteral:
John Stiles81365af2020-08-18 09:24:00 -0400198 this->writeFloatLiteral(expr.as<FloatLiteral>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400199 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400200 case Expression::Kind::kFunctionCall:
John Stiles81365af2020-08-18 09:24:00 -0400201 this->writeFunctionCall(expr.as<FunctionCall>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400202 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400203 case Expression::Kind::kPrefix:
John Stiles81365af2020-08-18 09:24:00 -0400204 this->writePrefixExpression(expr.as<PrefixExpression>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400205 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400206 case Expression::Kind::kPostfix:
John Stiles81365af2020-08-18 09:24:00 -0400207 this->writePostfixExpression(expr.as<PostfixExpression>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400208 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400209 case Expression::Kind::kSetting:
John Stiles81365af2020-08-18 09:24:00 -0400210 this->writeSetting(expr.as<Setting>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400211 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400212 case Expression::Kind::kSwizzle:
John Stiles81365af2020-08-18 09:24:00 -0400213 this->writeSwizzle(expr.as<Swizzle>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400214 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400215 case Expression::Kind::kVariableReference:
John Stiles81365af2020-08-18 09:24:00 -0400216 this->writeVariableReference(expr.as<VariableReference>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400217 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400218 case Expression::Kind::kTernary:
John Stiles81365af2020-08-18 09:24:00 -0400219 this->writeTernaryExpression(expr.as<TernaryExpression>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400220 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400221 case Expression::Kind::kIndex:
John Stiles81365af2020-08-18 09:24:00 -0400222 this->writeIndexExpression(expr.as<IndexExpression>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400223 break;
224 default:
Ethan Nicholas2a099da2020-01-02 14:40:54 -0500225#ifdef SK_DEBUG
Ethan Nicholascc305772017-10-13 16:17:45 -0400226 ABORT("unsupported expression: %s", expr.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -0500227#endif
228 break;
Ethan Nicholascc305772017-10-13 16:17:45 -0400229 }
230}
231
Timothy Liang6403b0e2018-05-17 10:40:04 -0400232void MetalCodeGenerator::writeIntrinsicCall(const FunctionCall& c) {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400233 auto i = fIntrinsicMap.find(c.function().name());
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400234 SkASSERT(i != fIntrinsicMap.end());
Timothy Liang7d637782018-06-05 09:58:07 -0400235 Intrinsic intrinsic = i->second;
236 int32_t intrinsicId = intrinsic.second;
237 switch (intrinsic.first) {
Timothy Liang6403b0e2018-05-17 10:40:04 -0400238 case kSpecial_IntrinsicKind:
239 return this->writeSpecialIntrinsic(c, (SpecialIntrinsic) intrinsicId);
Timothy Lianga06f2152018-05-24 15:33:31 -0400240 break;
241 case kMetal_IntrinsicKind:
John Stiles47b4b192020-12-08 18:08:11 -0500242 this->write("(");
243 this->writeExpression(*c.arguments()[0], kRelational_Precedence);
Timothy Lianga06f2152018-05-24 15:33:31 -0400244 switch ((MetalIntrinsic) intrinsicId) {
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500245 case kEqual_MetalIntrinsic:
246 this->write(" == ");
247 break;
248 case kNotEqual_MetalIntrinsic:
249 this->write(" != ");
250 break;
Timothy Lianga06f2152018-05-24 15:33:31 -0400251 case kLessThan_MetalIntrinsic:
252 this->write(" < ");
253 break;
254 case kLessThanEqual_MetalIntrinsic:
255 this->write(" <= ");
256 break;
257 case kGreaterThan_MetalIntrinsic:
258 this->write(" > ");
259 break;
260 case kGreaterThanEqual_MetalIntrinsic:
261 this->write(" >= ");
262 break;
263 default:
John Stiles47b4b192020-12-08 18:08:11 -0500264 ABORT("unsupported Metal intrinsic kind");
Timothy Lianga06f2152018-05-24 15:33:31 -0400265 }
John Stiles47b4b192020-12-08 18:08:11 -0500266 this->writeExpression(*c.arguments()[1], kRelational_Precedence);
267 this->write(")");
Timothy Lianga06f2152018-05-24 15:33:31 -0400268 break;
Timothy Liang6403b0e2018-05-17 10:40:04 -0400269 default:
270 ABORT("unsupported intrinsic kind");
271 }
272}
273
John Stiles06b84ef2020-12-09 12:35:48 -0500274String MetalCodeGenerator::getOutParamHelper(const FunctionCall& call,
275 const ExpressionArray& arguments,
276 const SkTArray<VariableReference*>& outVars) {
277 AutoOutputStream outputToExtraFunctions(this, &fExtraFunctions, &fIndentation);
278 const FunctionDeclaration& function = call.function();
279
280 String name = "_skOutParamHelper" + to_string(fSwizzleHelperCount++) + "_" + function.name();
281 const char* separator = "";
282
283 // Emit a prototype for the function we'll be calling through to in our helper.
284 if (!function.isBuiltin()) {
285 this->writeFunctionDeclaration(function);
286 this->writeLine(";");
287 }
288
289 // Synthesize a helper function that takes the same inputs as `function`, except in places where
290 // `outVars` is non-null; in those places, we take the type of the VariableReference.
291 //
292 // float _skOutParamHelper0_originalFuncName(float _var0, float _var1, float& outParam) {
293 this->writeBaseType(call.type());
294 this->write(" ");
295 this->write(name);
296 this->write("(");
297 this->writeFunctionRequirementParams(function, separator);
298
299 SkASSERT(outVars.size() == arguments.size());
300 SkASSERT(outVars.size() == function.parameters().size());
301
302 for (int index = 0; index < arguments.count(); ++index) {
303 this->write(separator);
304 separator = ", ";
305
306 const Variable* param = function.parameters()[index];
307 this->writeModifiers(param->modifiers(), /*globalContext=*/false);
308
309 const Type* type = outVars[index] ? &outVars[index]->type() : &arguments[index]->type();
310 this->writeBaseType(*type);
311
312 if (param->modifiers().fFlags & Modifiers::kOut_Flag) {
313 this->write("&");
314 }
315 if (outVars[index]) {
316 this->write(" ");
317 fIgnoreVariableReferenceModifiers = true;
318 this->writeVariableReference(*outVars[index]);
319 fIgnoreVariableReferenceModifiers = false;
320 } else {
321 this->write(" _var");
322 this->write(to_string(index));
323 }
324 this->writeArrayDimensions(*type);
325 }
326 this->writeLine(") {");
327
328 ++fIndentation;
329 for (int index = 0; index < outVars.count(); ++index) {
330 if (!outVars[index]) {
331 continue;
332 }
333 // float3 _var2[ = outParam.zyx];
334 this->writeBaseType(arguments[index]->type());
335 this->write(" _var");
336 this->write(to_string(index));
337
338 const Variable* param = function.parameters()[index];
339 if (param->modifiers().fFlags & Modifiers::kIn_Flag) {
340 this->write(" = ");
341 fIgnoreVariableReferenceModifiers = true;
342 this->writeExpression(*arguments[index], kAssignment_Precedence);
343 fIgnoreVariableReferenceModifiers = false;
344 }
345
346 this->writeLine(";");
347 }
348
349 // [int _skResult = ] myFunction(inputs, outputs, globals, _var0, _var1, _var2, _var3);
350 bool hasResult = (call.type().name() != "void");
351 if (hasResult) {
352 this->writeBaseType(call.type());
353 this->write(" _skResult = ");
354 }
355
356 this->writeName(function.name());
357 this->write("(");
358 separator = "";
359 this->writeFunctionRequirementArgs(function, separator);
360
361 for (int index = 0; index < arguments.count(); ++index) {
362 this->write(separator);
363 separator = ", ";
364
365 this->write("_var");
366 this->write(to_string(index));
367 }
368 this->writeLine(");");
369
370 for (int index = 0; index < outVars.count(); ++index) {
371 if (!outVars[index]) {
372 continue;
373 }
374 // outParam.zyx = _var2;
375 fIgnoreVariableReferenceModifiers = true;
376 this->writeExpression(*arguments[index], kAssignment_Precedence);
377 fIgnoreVariableReferenceModifiers = false;
378 this->write(" = _var");
379 this->write(to_string(index));
380 this->writeLine(";");
381 }
382
383 if (hasResult) {
384 this->writeLine("return _skResult;");
385 }
386
387 --fIndentation;
388 this->writeLine("}");
389
390 return name;
John Stilesb21fac22020-12-04 15:36:49 -0500391}
392
John Stilesf64e4072020-12-10 10:34:27 -0500393String MetalCodeGenerator::getBitcastIntrinsic(const Type& outType) {
394 return "as_type<" + outType.displayName() + ">";
395}
396
Ethan Nicholascc305772017-10-13 16:17:45 -0400397void MetalCodeGenerator::writeFunctionCall(const FunctionCall& c) {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400398 const FunctionDeclaration& function = c.function();
John Stiles8e3b6be2020-10-13 11:14:08 -0400399 const ExpressionArray& arguments = c.arguments();
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400400 const auto& entry = fIntrinsicMap.find(function.name());
Timothy Liang6403b0e2018-05-17 10:40:04 -0400401 if (entry != fIntrinsicMap.end()) {
402 this->writeIntrinsicCall(c);
403 return;
404 }
John Stilesb21fac22020-12-04 15:36:49 -0500405 String name = function.name();
John Stilesb21fac22020-12-04 15:36:49 -0500406
John Stilesf64e4072020-12-10 10:34:27 -0500407 if (function.isBuiltin()) {
408 if (name == "atan" && arguments.size() == 2) {
409 name = "atan2";
410 } else if (name == "inversesqrt") {
411 name = "rsqrt";
412 } else if (name == "inverse") {
413 SkASSERT(arguments.size() == 1);
414 name = this->getInverseHack(*arguments[0]);
415 } else if (name == "dFdx") {
416 name = "dfdx";
417 } else if (name == "dFdy") {
418 // Flipping Y also negates the Y derivatives.
419 if (fProgram.fSettings.fFlipY) {
420 this->write("-");
421 }
422 name = "dfdy";
John Stilesb21fac22020-12-04 15:36:49 -0500423 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400424 }
John Stilesb21fac22020-12-04 15:36:49 -0500425
John Stilesf64e4072020-12-10 10:34:27 -0500426 // We emulate GLSL's out-param semantics for Metal using a helper function. (Specifically,
427 // results are only written back to the original variable at the end of the function call; also,
428 // swizzles are supported, whereas Metal doesn't allow a swizzle to be passed to a `floatN&`.)
John Stilesb21fac22020-12-04 15:36:49 -0500429 const std::vector<const Variable*>& parameters = function.parameters();
430 SkASSERT(arguments.size() == parameters.size());
John Stiles06b84ef2020-12-09 12:35:48 -0500431
432 bool foundOutParam = false;
433 SkSTArray<16, VariableReference*> outVars;
John Stilesf64e4072020-12-10 10:34:27 -0500434 outVars.push_back_n(arguments.count(), (VariableReference*)nullptr);
John Stiles06b84ef2020-12-09 12:35:48 -0500435
436 for (int index = 0; index < arguments.count(); ++index) {
John Stilesb21fac22020-12-04 15:36:49 -0500437 // If this is an out parameter...
438 if (parameters[index]->modifiers().fFlags & Modifiers::kOut_Flag) {
John Stiles06b84ef2020-12-09 12:35:48 -0500439 // Find the expression's inner variable being written to.
John Stilesb21fac22020-12-04 15:36:49 -0500440 Analysis::AssignmentInfo info;
John Stiles06b84ef2020-12-09 12:35:48 -0500441 // Assignability was verified at IRGeneration time, so this should always succeed.
442 SkAssertResult(Analysis::IsAssignable(*arguments[index], &info));
443 outVars[index] = info.fAssignedVar;
444 foundOutParam = true;
John Stilesb21fac22020-12-04 15:36:49 -0500445 }
446 }
447
John Stiles06b84ef2020-12-09 12:35:48 -0500448 if (foundOutParam) {
449 // Out parameters need to be written back to at the end of the function. To do this, we
450 // synthesize a helper function which evaluates the out-param expression into a temporary
451 // variable, calls the original function, then writes the temp var back into the out param
452 // using the original out-param expression. (This lets us support things like swizzles and
453 // array indices.)
454 name = getOutParamHelper(c, arguments, outVars);
455 }
456
John Stilesb21fac22020-12-04 15:36:49 -0500457 this->write(name);
Ethan Nicholascc305772017-10-13 16:17:45 -0400458 this->write("(");
459 const char* separator = "";
John Stiles06b84ef2020-12-09 12:35:48 -0500460 this->writeFunctionRequirementArgs(function, separator);
461 for (int i = 0; i < arguments.count(); ++i) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400462 this->write(separator);
463 separator = ", ";
John Stiles06b84ef2020-12-09 12:35:48 -0500464
465 if (outVars[i]) {
466 this->writeExpression(*outVars[i], kSequence_Precedence);
467 } else {
468 this->writeExpression(*arguments[i], kSequence_Precedence);
469 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400470 }
471 this->write(")");
472}
473
John Stilesb21fac22020-12-04 15:36:49 -0500474String MetalCodeGenerator::getInverseHack(const Expression& mat) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400475 const Type& type = mat.type();
476 const String& typeName = type.name();
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500477 String name = typeName + "_inverse";
Ethan Nicholas30d30222020-09-11 12:27:26 -0400478 if (type == *fContext.fFloat2x2_Type || type == *fContext.fHalf2x2_Type) {
Chris Daltondba7aab2018-11-15 10:57:49 -0500479 if (fWrittenIntrinsics.find(name) == fWrittenIntrinsics.end()) {
480 fWrittenIntrinsics.insert(name);
481 fExtraFunctions.writeText((
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500482 typeName + " " + name + "(" + typeName + " m) {"
Chris Daltondba7aab2018-11-15 10:57:49 -0500483 " return float2x2(m[1][1], -m[0][1], -m[1][0], m[0][0]) * (1/determinant(m));"
484 "}"
485 ).c_str());
486 }
487 }
Ethan Nicholas30d30222020-09-11 12:27:26 -0400488 else if (type == *fContext.fFloat3x3_Type || type == *fContext.fHalf3x3_Type) {
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500489 if (fWrittenIntrinsics.find(name) == fWrittenIntrinsics.end()) {
490 fWrittenIntrinsics.insert(name);
491 fExtraFunctions.writeText((
492 typeName + " " + name + "(" + typeName + " m) {"
493 " float a00 = m[0][0], a01 = m[0][1], a02 = m[0][2];"
494 " float a10 = m[1][0], a11 = m[1][1], a12 = m[1][2];"
495 " float a20 = m[2][0], a21 = m[2][1], a22 = m[2][2];"
496 " float b01 = a22 * a11 - a12 * a21;"
497 " float b11 = -a22 * a10 + a12 * a20;"
498 " float b21 = a21 * a10 - a11 * a20;"
499 " float det = a00 * b01 + a01 * b11 + a02 * b21;"
500 " return " + typeName +
501 " (b01, (-a22 * a01 + a02 * a21), (a12 * a01 - a02 * a11),"
502 " b11, (a22 * a00 - a02 * a20), (-a12 * a00 + a02 * a10),"
503 " b21, (-a21 * a00 + a01 * a20), (a11 * a00 - a01 * a10)) * "
504 " (1/det);"
505 "}"
506 ).c_str());
507 }
508 }
Ethan Nicholas30d30222020-09-11 12:27:26 -0400509 else if (type == *fContext.fFloat4x4_Type || type == *fContext.fHalf4x4_Type) {
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500510 if (fWrittenIntrinsics.find(name) == fWrittenIntrinsics.end()) {
511 fWrittenIntrinsics.insert(name);
512 fExtraFunctions.writeText((
513 typeName + " " + name + "(" + typeName + " m) {"
514 " float a00 = m[0][0], a01 = m[0][1], a02 = m[0][2], a03 = m[0][3];"
515 " float a10 = m[1][0], a11 = m[1][1], a12 = m[1][2], a13 = m[1][3];"
516 " float a20 = m[2][0], a21 = m[2][1], a22 = m[2][2], a23 = m[2][3];"
517 " float a30 = m[3][0], a31 = m[3][1], a32 = m[3][2], a33 = m[3][3];"
518 " float b00 = a00 * a11 - a01 * a10;"
519 " float b01 = a00 * a12 - a02 * a10;"
520 " float b02 = a00 * a13 - a03 * a10;"
521 " float b03 = a01 * a12 - a02 * a11;"
522 " float b04 = a01 * a13 - a03 * a11;"
523 " float b05 = a02 * a13 - a03 * a12;"
524 " float b06 = a20 * a31 - a21 * a30;"
525 " float b07 = a20 * a32 - a22 * a30;"
526 " float b08 = a20 * a33 - a23 * a30;"
527 " float b09 = a21 * a32 - a22 * a31;"
528 " float b10 = a21 * a33 - a23 * a31;"
529 " float b11 = a22 * a33 - a23 * a32;"
530 " float det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - "
531 " b04 * b07 + b05 * b06;"
532 " return " + typeName + "(a11 * b11 - a12 * b10 + a13 * b09,"
533 " a02 * b10 - a01 * b11 - a03 * b09,"
534 " a31 * b05 - a32 * b04 + a33 * b03,"
535 " a22 * b04 - a21 * b05 - a23 * b03,"
536 " a12 * b08 - a10 * b11 - a13 * b07,"
537 " a00 * b11 - a02 * b08 + a03 * b07,"
538 " a32 * b02 - a30 * b05 - a33 * b01,"
539 " a20 * b05 - a22 * b02 + a23 * b01,"
540 " a10 * b10 - a11 * b08 + a13 * b06,"
541 " a01 * b08 - a00 * b10 - a03 * b06,"
542 " a30 * b04 - a31 * b02 + a33 * b00,"
543 " a21 * b02 - a20 * b04 - a23 * b00,"
544 " a11 * b07 - a10 * b09 - a12 * b06,"
545 " a00 * b09 - a01 * b07 + a02 * b06,"
546 " a31 * b01 - a30 * b03 - a32 * b00,"
547 " a20 * b03 - a21 * b01 + a22 * b00) / det;"
548 "}"
549 ).c_str());
550 }
551 }
John Stilesb21fac22020-12-04 15:36:49 -0500552 return name;
Chris Daltondba7aab2018-11-15 10:57:49 -0500553}
554
John Stiles86424eb2020-12-11 11:17:14 -0500555String MetalCodeGenerator::getTempVariable(const Type& type) {
556 String tempVar = "_skTemp" + to_string(fVarCount++);
557 this->fFunctionHeader += " " + this->typeName(type) + " " + tempVar + ";\n";
558 return tempVar;
559}
560
Timothy Liang6403b0e2018-05-17 10:40:04 -0400561void MetalCodeGenerator::writeSpecialIntrinsic(const FunctionCall & c, SpecialIntrinsic kind) {
John Stiles8e3b6be2020-10-13 11:14:08 -0400562 const ExpressionArray& arguments = c.arguments();
Timothy Liang6403b0e2018-05-17 10:40:04 -0400563 switch (kind) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400564 case kTexture_SpecialIntrinsic: {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400565 this->writeExpression(*arguments[0], kSequence_Precedence);
Timothy Lianga06f2152018-05-24 15:33:31 -0400566 this->write(".sample(");
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400567 this->writeExpression(*arguments[0], kSequence_Precedence);
Timothy Lianga06f2152018-05-24 15:33:31 -0400568 this->write(SAMPLER_SUFFIX);
569 this->write(", ");
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400570 const Type& arg1Type = arguments[1]->type();
Ethan Nicholas30d30222020-09-11 12:27:26 -0400571 if (arg1Type == *fContext.fFloat3_Type) {
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500572 // have to store the vector in a temp variable to avoid double evaluating it
John Stiles86424eb2020-12-11 11:17:14 -0500573 String tmpVar = this->getTempVariable(arg1Type);
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500574 this->write("(" + tmpVar + " = ");
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400575 this->writeExpression(*arguments[1], kSequence_Precedence);
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500576 this->write(", " + tmpVar + ".xy / " + tmpVar + ".z))");
Timothy Liangee84fe12018-05-18 14:38:19 -0400577 } else {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400578 SkASSERT(arg1Type == *fContext.fFloat2_Type);
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400579 this->writeExpression(*arguments[1], kSequence_Precedence);
Timothy Liangee84fe12018-05-18 14:38:19 -0400580 this->write(")");
581 }
Timothy Liang6403b0e2018-05-17 10:40:04 -0400582 break;
Ethan Nicholas30d30222020-09-11 12:27:26 -0400583 }
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500584 case kMod_SpecialIntrinsic: {
Timothy Liang651286f2018-06-07 09:55:33 -0400585 // 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 -0500586 String tmpX = this->getTempVariable(arguments[0]->type());
587 String tmpY = this->getTempVariable(arguments[0]->type());
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500588 this->write("(" + tmpX + " = ");
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400589 this->writeExpression(*arguments[0], kSequence_Precedence);
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500590 this->write(", " + tmpY + " = ");
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400591 this->writeExpression(*arguments[1], kSequence_Precedence);
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500592 this->write(", " + tmpX + " - " + tmpY + " * floor(" + tmpX + " / " + tmpY + "))");
Timothy Liang651286f2018-06-07 09:55:33 -0400593 break;
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500594 }
Brian Osman46787d52020-11-24 14:18:23 -0500595 // GLSL declares scalar versions of most geometric intrinsics, but these don't exist in MSL
596 case kDistance_SpecialIntrinsic: {
597 if (arguments[0]->type().columns() == 1) {
598 this->write("abs(");
599 this->writeExpression(*arguments[0], kAdditive_Precedence);
600 this->write(" - ");
601 this->writeExpression(*arguments[1], kAdditive_Precedence);
602 this->write(")");
603 } else {
604 this->write("distance(");
605 this->writeExpression(*arguments[0], kSequence_Precedence);
606 this->write(", ");
607 this->writeExpression(*arguments[1], kSequence_Precedence);
608 this->write(")");
609 }
610 break;
611 }
612 case kDot_SpecialIntrinsic: {
613 if (arguments[0]->type().columns() == 1) {
614 this->write("(");
615 this->writeExpression(*arguments[0], kMultiplicative_Precedence);
616 this->write(" * ");
617 this->writeExpression(*arguments[1], kMultiplicative_Precedence);
618 this->write(")");
619 } else {
620 this->write("dot(");
621 this->writeExpression(*arguments[0], kSequence_Precedence);
622 this->write(", ");
623 this->writeExpression(*arguments[1], kSequence_Precedence);
624 this->write(")");
625 }
626 break;
627 }
John Stilesad0571f2020-12-10 18:03:10 -0500628 case kFaceforward_SpecialIntrinsic: {
629 if (arguments[0]->type().columns() == 1) {
630 // ((((Nref) * (I) < 0) ? 1 : -1) * (N))
631 this->write("((((");
632 this->writeExpression(*arguments[2], kSequence_Precedence);
633 this->write(") * (");
634 this->writeExpression(*arguments[1], kSequence_Precedence);
635 this->write(") < 0) ? 1 : -1) * (");
636 this->writeExpression(*arguments[0], kSequence_Precedence);
637 this->write("))");
638 } else {
639 this->write("faceforward(");
640 this->writeExpression(*arguments[0], kSequence_Precedence);
641 this->write(", ");
642 this->writeExpression(*arguments[1], kSequence_Precedence);
643 this->write(", ");
644 this->writeExpression(*arguments[2], kSequence_Precedence);
645 this->write(")");
646 }
647 break;
648 }
Brian Osman46787d52020-11-24 14:18:23 -0500649 case kLength_SpecialIntrinsic: {
650 this->write(arguments[0]->type().columns() == 1 ? "abs(" : "length(");
651 this->writeExpression(*arguments[0], kSequence_Precedence);
652 this->write(")");
653 break;
654 }
655 case kNormalize_SpecialIntrinsic: {
656 this->write(arguments[0]->type().columns() == 1 ? "sign(" : "normalize(");
657 this->writeExpression(*arguments[0], kSequence_Precedence);
658 this->write(")");
659 break;
660 }
John Stiles0063a9f2020-12-10 18:01:45 -0500661 case kBitcast_SpecialIntrinsic: {
662 this->write(this->getBitcastIntrinsic(c.type()));
663 this->write("(");
664 this->writeExpression(*arguments[0], kSequence_Precedence);
665 this->write(")");
666 break;
667 }
John Stilese2d34f82020-12-10 18:02:02 -0500668 case kDegrees_SpecialIntrinsic: {
669 this->write("((");
670 this->writeExpression(*arguments[0], kSequence_Precedence);
671 this->write(") * 57.2957795)");
672 break;
673 }
674 case kRadians_SpecialIntrinsic: {
675 this->write("((");
676 this->writeExpression(*arguments[0], kSequence_Precedence);
677 this->write(") * 0.0174532925)");
678 break;
679 }
John Stiles86424eb2020-12-11 11:17:14 -0500680 case kFindLSB_SpecialIntrinsic: {
681 // Create a temp variable to store the expression, to avoid double-evaluating it.
682 String skTemp = this->getTempVariable(arguments[0]->type());
683 String exprType = this->typeName(arguments[0]->type());
684
685 // ctz returns numbits(type) on zero inputs; GLSL documents it as generating -1 instead.
686 // Use select to detect zero inputs and force a -1 result.
687
688 // (_skTemp1 = (.....), select(ctz(_skTemp1), int4(-1), _skTemp1 == int4(0)))
689 this->write("(");
690 this->write(skTemp);
691 this->write(" = (");
692 this->writeExpression(*arguments[0], kSequence_Precedence);
693 this->write("), select(ctz(");
694 this->write(skTemp);
695 this->write("), ");
696 this->write(exprType);
697 this->write("(-1), ");
698 this->write(skTemp);
699 this->write(" == ");
700 this->write(exprType);
701 this->write("(0)))");
702 break;
703 }
John Stiles9685e522020-12-14 11:52:14 -0500704 case kFindMSB_SpecialIntrinsic: {
705 // Create a temp variable to store the expression, to avoid double-evaluating it.
706 String skTemp1 = this->getTempVariable(arguments[0]->type());
707 String exprType = this->typeName(arguments[0]->type());
708
709 // GLSL findMSB is actually quite different from Metal's clz:
710 // - For signed negative numbers, it returns the first zero bit, not the first one bit!
711 // - For an empty input (0/~0 depending on sign), findMSB gives -1; clz is numbits(type)
712
713 // (_skTemp1 = (.....),
714 this->write("(");
715 this->write(skTemp1);
716 this->write(" = (");
717 this->writeExpression(*arguments[0], kSequence_Precedence);
718 this->write("), ");
719
720 // Signed input types might be negative; we need another helper variable to negate the
721 // input (since we can only find one bits, not zero bits).
722 String skTemp2;
723 if (arguments[0]->type().isSigned()) {
724 // ... _skTemp2 = (select(_skTemp1, ~_skTemp1, _skTemp1 < 0)),
725 skTemp2 = this->getTempVariable(arguments[0]->type());
726 this->write(skTemp2);
727 this->write(" = (select(");
728 this->write(skTemp1);
729 this->write(", ~");
730 this->write(skTemp1);
731 this->write(", ");
732 this->write(skTemp1);
733 this->write(" < 0)), ");
734 } else {
735 skTemp2 = skTemp1;
736 }
737
738 // ... select(int4(clz(_skTemp2)), int4(-1), _skTemp2 == int4(0)))
739 this->write("select(");
740 this->write(this->typeName(c.type()));
741 this->write("(clz(");
742 this->write(skTemp2);
743 this->write(")), ");
744 this->write(this->typeName(c.type()));
745 this->write("(-1), ");
746 this->write(skTemp2);
747 this->write(" == ");
748 this->write(exprType);
749 this->write("(0)))");
750 break;
751 }
Timothy Liang6403b0e2018-05-17 10:40:04 -0400752 default:
753 ABORT("unsupported special intrinsic kind");
754 }
755}
756
John Stilesfcf8cb22020-08-06 14:29:22 -0400757// Assembles a matrix of type floatRxC by resizing another matrix named `x0`.
758// Cells that don't exist in the source matrix will be populated with identity-matrix values.
759void MetalCodeGenerator::assembleMatrixFromMatrix(const Type& sourceMatrix, int rows, int columns) {
760 SkASSERT(rows <= 4);
761 SkASSERT(columns <= 4);
762
763 const char* columnSeparator = "";
764 for (int c = 0; c < columns; ++c) {
765 fExtraFunctions.printf("%sfloat%d(", columnSeparator, rows);
766 columnSeparator = "), ";
767
768 // Determine how many values to take from the source matrix for this row.
769 int swizzleLength = 0;
770 if (c < sourceMatrix.columns()) {
771 swizzleLength = std::min<>(rows, sourceMatrix.rows());
772 }
773
774 // Emit all the values from the source matrix row.
775 bool firstItem;
776 switch (swizzleLength) {
777 case 0: firstItem = true; break;
778 case 1: firstItem = false; fExtraFunctions.printf("x0[%d].x", c); break;
779 case 2: firstItem = false; fExtraFunctions.printf("x0[%d].xy", c); break;
780 case 3: firstItem = false; fExtraFunctions.printf("x0[%d].xyz", c); break;
781 case 4: firstItem = false; fExtraFunctions.printf("x0[%d].xyzw", c); break;
782 default: SkUNREACHABLE;
783 }
784
785 // Emit the placeholder identity-matrix cells.
786 for (int r = swizzleLength; r < rows; ++r) {
787 fExtraFunctions.printf("%s%s", firstItem ? "" : ", ", (r == c) ? "1.0" : "0.0");
788 firstItem = false;
789 }
790 }
791
792 fExtraFunctions.writeText(")");
793}
794
795// Assembles a matrix of type floatRxC by concatenating an arbitrary mix of values, named `x0`,
796// `x1`, etc. An error is written if the expression list don't contain exactly R*C scalars.
John Stiles8e3b6be2020-10-13 11:14:08 -0400797void MetalCodeGenerator::assembleMatrixFromExpressions(const ExpressionArray& args,
798 int rows, int columns) {
John Stilesfcf8cb22020-08-06 14:29:22 -0400799 size_t argIndex = 0;
800 int argPosition = 0;
801
802 const char* columnSeparator = "";
803 for (int c = 0; c < columns; ++c) {
804 fExtraFunctions.printf("%sfloat%d(", columnSeparator, rows);
805 columnSeparator = "), ";
806
807 const char* rowSeparator = "";
808 for (int r = 0; r < rows; ++r) {
809 fExtraFunctions.writeText(rowSeparator);
810 rowSeparator = ", ";
811
812 if (argIndex < args.size()) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400813 const Type& argType = args[argIndex]->type();
Ethan Nicholase6592142020-09-08 10:22:09 -0400814 switch (argType.typeKind()) {
815 case Type::TypeKind::kScalar: {
John Stilesfcf8cb22020-08-06 14:29:22 -0400816 fExtraFunctions.printf("x%zu", argIndex);
817 break;
818 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400819 case Type::TypeKind::kVector: {
John Stilesfcf8cb22020-08-06 14:29:22 -0400820 fExtraFunctions.printf("x%zu[%d]", argIndex, argPosition);
821 break;
822 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400823 case Type::TypeKind::kMatrix: {
John Stilesfcf8cb22020-08-06 14:29:22 -0400824 fExtraFunctions.printf("x%zu[%d][%d]", argIndex,
825 argPosition / argType.rows(),
826 argPosition % argType.rows());
827 break;
828 }
829 default: {
830 SkDEBUGFAIL("incorrect type of argument for matrix constructor");
831 fExtraFunctions.writeText("<error>");
832 break;
833 }
834 }
835
836 ++argPosition;
837 if (argPosition >= argType.columns() * argType.rows()) {
838 ++argIndex;
839 argPosition = 0;
840 }
841 } else {
842 SkDEBUGFAIL("not enough arguments for matrix constructor");
843 fExtraFunctions.writeText("<error>");
844 }
845 }
846 }
847
848 if (argPosition != 0 || argIndex != args.size()) {
849 SkDEBUGFAIL("incorrect number of arguments for matrix constructor");
850 fExtraFunctions.writeText(", <error>");
851 }
852
853 fExtraFunctions.writeText(")");
854}
855
John Stiles1bdafbf2020-05-28 12:17:20 -0400856// Generates a constructor for 'matrix' which reorganizes the input arguments into the proper shape.
857// Keeps track of previously generated constructors so that we won't generate more than one
858// constructor for any given permutation of input argument types. Returns the name of the
859// generated constructor method.
860String MetalCodeGenerator::getMatrixConstructHelper(const Constructor& c) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400861 const Type& matrix = c.type();
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500862 int columns = matrix.columns();
863 int rows = matrix.rows();
John Stiles8e3b6be2020-10-13 11:14:08 -0400864 const ExpressionArray& args = c.arguments();
John Stiles1bdafbf2020-05-28 12:17:20 -0400865
866 // Create the helper-method name and use it as our lookup key.
867 String name;
868 name.appendf("float%dx%d_from", columns, rows);
869 for (const std::unique_ptr<Expression>& expr : args) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400870 name.appendf("_%s", expr->type().displayName().c_str());
John Stiles1bdafbf2020-05-28 12:17:20 -0400871 }
872
873 // If a helper-method has already been synthesized, we don't need to synthesize it again.
874 auto [iter, newlyCreated] = fHelpers.insert(name);
875 if (!newlyCreated) {
876 return name;
877 }
878
879 // Unlike GLSL, Metal requires that matrices are initialized with exactly R vectors of C
880 // components apiece. (In Metal 2.0, you can also supply R*C scalars, but you still cannot
881 // supply a mixture of scalars and vectors.)
882 fExtraFunctions.printf("float%dx%d %s(", columns, rows, name.c_str());
883
884 size_t argIndex = 0;
885 const char* argSeparator = "";
John Stilesfcf8cb22020-08-06 14:29:22 -0400886 for (const std::unique_ptr<Expression>& expr : args) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400887 fExtraFunctions.printf("%s%s x%zu", argSeparator,
Ethan Nicholas30d30222020-09-11 12:27:26 -0400888 expr->type().displayName().c_str(), argIndex++);
John Stiles1bdafbf2020-05-28 12:17:20 -0400889 argSeparator = ", ";
890 }
891
892 fExtraFunctions.printf(") {\n return float%dx%d(", columns, rows);
893
John Stiles9aeed132020-11-24 17:36:06 -0500894 if (args.size() == 1 && args.front()->type().isMatrix()) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400895 this->assembleMatrixFromMatrix(args.front()->type(), rows, columns);
John Stilesfcf8cb22020-08-06 14:29:22 -0400896 } else {
897 this->assembleMatrixFromExpressions(args, rows, columns);
John Stiles1bdafbf2020-05-28 12:17:20 -0400898 }
899
John Stilesfcf8cb22020-08-06 14:29:22 -0400900 fExtraFunctions.writeText(");\n}\n");
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500901 return name;
902}
903
904bool MetalCodeGenerator::canCoerce(const Type& t1, const Type& t2) {
905 if (t1.columns() != t2.columns() || t1.rows() != t2.rows()) {
906 return false;
907 }
908 if (t1.columns() > 1) {
909 return this->canCoerce(t1.componentType(), t2.componentType());
910 }
Ethan Nicholase1f55022019-02-05 17:17:40 -0500911 return t1.isFloat() && t2.isFloat();
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500912}
913
John Stiles1bdafbf2020-05-28 12:17:20 -0400914bool MetalCodeGenerator::matrixConstructHelperIsNeeded(const Constructor& c) {
915 // A matrix construct helper is only necessary if we are, in fact, constructing a matrix.
John Stiles9aeed132020-11-24 17:36:06 -0500916 if (!c.type().isMatrix()) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400917 return false;
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500918 }
John Stiles1bdafbf2020-05-28 12:17:20 -0400919
920 // GLSL is fairly free-form about inputs to its matrix constructors, but Metal is not; it
921 // expects exactly R vectors of C components apiece. (Metal 2.0 also allows a list of R*C
922 // scalars.) Some cases are simple to translate and so we handle those inline--e.g. a list of
923 // scalars can be constructed trivially. In more complex cases, we generate a helper function
924 // that converts our inputs into a properly-shaped matrix.
925 // A matrix construct helper method is always used if any input argument is a matrix.
926 // Helper methods are also necessary when any argument would span multiple rows. For instance:
927 //
928 // float2 x = (1, 2);
929 // float3x2(x, 3, 4, 5, 6) = | 1 3 5 | = no helper needed; conversion can be done inline
930 // | 2 4 6 |
931 //
932 // float2 x = (2, 3);
933 // float3x2(1, x, 4, 5, 6) = | 1 3 5 | = x spans multiple rows; a helper method will be used
934 // | 2 4 6 |
935 //
936 // float4 x = (1, 2, 3, 4);
937 // float2x2(x) = | 1 3 | = x spans multiple rows; a helper method will be used
938 // | 2 4 |
939 //
940
941 int position = 0;
Ethan Nicholasf70f0442020-09-29 12:41:35 -0400942 for (const std::unique_ptr<Expression>& expr : c.arguments()) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400943 // If an input argument is a matrix, we need a helper function.
John Stiles9aeed132020-11-24 17:36:06 -0500944 if (expr->type().isMatrix()) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400945 return true;
946 }
Ethan Nicholas30d30222020-09-11 12:27:26 -0400947 position += expr->type().columns();
948 if (position > c.type().rows()) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400949 // An input argument would span multiple rows; a helper function is required.
950 return true;
951 }
Ethan Nicholas30d30222020-09-11 12:27:26 -0400952 if (position == c.type().rows()) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400953 // We've advanced to the end of a row. Wrap to the start of the next row.
954 position = 0;
955 }
956 }
957
958 return false;
959}
960
961void MetalCodeGenerator::writeConstructor(const Constructor& c, Precedence parentPrecedence) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400962 const Type& constructorType = c.type();
John Stiles1bdafbf2020-05-28 12:17:20 -0400963 // Handle special cases for single-argument constructors.
Ethan Nicholasf70f0442020-09-29 12:41:35 -0400964 if (c.arguments().size() == 1) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400965 // If the type is coercible, emit it directly.
Ethan Nicholasf70f0442020-09-29 12:41:35 -0400966 const Expression& arg = *c.arguments().front();
Ethan Nicholas30d30222020-09-11 12:27:26 -0400967 const Type& argType = arg.type();
968 if (this->canCoerce(constructorType, argType)) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400969 this->writeExpression(arg, parentPrecedence);
970 return;
971 }
972
973 // Metal supports creating matrices with a scalar on the diagonal via the single-argument
974 // matrix constructor.
John Stiles9aeed132020-11-24 17:36:06 -0500975 if (constructorType.isMatrix() && argType.isNumber()) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400976 const Type& matrix = constructorType;
John Stiles1bdafbf2020-05-28 12:17:20 -0400977 this->write("float");
978 this->write(to_string(matrix.columns()));
979 this->write("x");
980 this->write(to_string(matrix.rows()));
981 this->write("(");
982 this->writeExpression(arg, parentPrecedence);
983 this->write(")");
984 return;
985 }
986 }
987
988 // Emit and invoke a matrix-constructor helper method if one is necessary.
989 if (this->matrixConstructHelperIsNeeded(c)) {
990 this->write(this->getMatrixConstructHelper(c));
John Stiles1fa15b12020-05-28 17:36:54 +0000991 this->write("(");
992 const char* separator = "";
Ethan Nicholasf70f0442020-09-29 12:41:35 -0400993 for (const std::unique_ptr<Expression>& expr : c.arguments()) {
John Stiles1fa15b12020-05-28 17:36:54 +0000994 this->write(separator);
995 separator = ", ";
John Stiles1bdafbf2020-05-28 12:17:20 -0400996 this->writeExpression(*expr, kSequence_Precedence);
John Stilesdaa573e2020-05-28 12:17:20 -0400997 }
John Stiles1fa15b12020-05-28 17:36:54 +0000998 this->write(")");
John Stiles1bdafbf2020-05-28 12:17:20 -0400999 return;
John Stilesdaa573e2020-05-28 12:17:20 -04001000 }
John Stiles1bdafbf2020-05-28 12:17:20 -04001001
1002 // Explicitly invoke the constructor, passing in the necessary arguments.
John Stiles3dba3ee2020-12-02 23:35:49 -05001003 this->writeBaseType(constructorType);
John Stilesea166702020-12-11 17:30:47 -05001004 this->disallowArrayTypes(constructorType, c.fOffset);
John Stiles1bdafbf2020-05-28 12:17:20 -04001005 this->write("(");
1006 const char* separator = "";
1007 int scalarCount = 0;
Ethan Nicholasf70f0442020-09-29 12:41:35 -04001008 for (const std::unique_ptr<Expression>& arg : c.arguments()) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001009 const Type& argType = arg->type();
John Stiles1bdafbf2020-05-28 12:17:20 -04001010 this->write(separator);
1011 separator = ", ";
John Stiles9aeed132020-11-24 17:36:06 -05001012 if (constructorType.isMatrix() &&
Ethan Nicholas30d30222020-09-11 12:27:26 -04001013 argType.columns() < constructorType.rows()) {
John Stiles1bdafbf2020-05-28 12:17:20 -04001014 // Merge scalars and smaller vectors together.
1015 if (!scalarCount) {
John Stiles3dba3ee2020-12-02 23:35:49 -05001016 this->writeBaseType(constructorType.componentType());
Ethan Nicholas30d30222020-09-11 12:27:26 -04001017 this->write(to_string(constructorType.rows()));
John Stiles1bdafbf2020-05-28 12:17:20 -04001018 this->write("(");
1019 }
Ethan Nicholas30d30222020-09-11 12:27:26 -04001020 scalarCount += argType.columns();
John Stiles1bdafbf2020-05-28 12:17:20 -04001021 }
1022 this->writeExpression(*arg, kSequence_Precedence);
Ethan Nicholas30d30222020-09-11 12:27:26 -04001023 if (scalarCount && scalarCount == constructorType.rows()) {
John Stiles1bdafbf2020-05-28 12:17:20 -04001024 this->write(")");
1025 scalarCount = 0;
1026 }
1027 }
1028 this->write(")");
Ethan Nicholascc305772017-10-13 16:17:45 -04001029}
1030
1031void MetalCodeGenerator::writeFragCoord() {
Ethan Nicholasf931e402019-07-26 15:40:33 -04001032 if (fRTHeightName.length()) {
1033 this->write("float4(_fragCoord.x, ");
1034 this->write(fRTHeightName.c_str());
1035 this->write(" - _fragCoord.y, 0.0, _fragCoord.w)");
Jim Van Verth6bc650e2019-02-07 14:53:23 -05001036 } else {
1037 this->write("float4(_fragCoord.x, _fragCoord.y, 0.0, _fragCoord.w)");
1038 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001039}
1040
1041void MetalCodeGenerator::writeVariableReference(const VariableReference& ref) {
John Stiles06b84ef2020-12-09 12:35:48 -05001042 // When assembling out-param helper functions, we copy variables into local clones with matching
1043 // names. We never want to prepend "_in." or "_globals->" when writing these variables since
1044 // we're actually targeting the clones.
1045 if (fIgnoreVariableReferenceModifiers) {
1046 this->writeName(ref.variable()->name());
1047 return;
1048 }
1049
Ethan Nicholas78686922020-10-08 06:46:27 -04001050 switch (ref.variable()->modifiers().fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001051 case SK_FRAGCOLOR_BUILTIN:
Timothy Liang7d637782018-06-05 09:58:07 -04001052 this->write("_out->sk_FragColor");
Ethan Nicholascc305772017-10-13 16:17:45 -04001053 break;
Timothy Liang6403b0e2018-05-17 10:40:04 -04001054 case SK_FRAGCOORD_BUILTIN:
1055 this->writeFragCoord();
1056 break;
Timothy Liangdc89f192018-06-13 09:20:31 -04001057 case SK_VERTEXID_BUILTIN:
1058 this->write("sk_VertexID");
1059 break;
1060 case SK_INSTANCEID_BUILTIN:
1061 this->write("sk_InstanceID");
1062 break;
Timothy Liang7b8875d2018-08-10 09:42:31 -04001063 case SK_CLOCKWISE_BUILTIN:
1064 // We'd set the front facing winding in the MTLRenderCommandEncoder to be counter
Brian Salomonf4ba4ec2020-03-19 15:54:28 -04001065 // clockwise to match Skia convention.
Timothy Liang7b8875d2018-08-10 09:42:31 -04001066 this->write(fProgram.fSettings.fFlipY ? "_frontFacing" : "(!_frontFacing)");
1067 break;
Ethan Nicholascc305772017-10-13 16:17:45 -04001068 default:
Ethan Nicholas78686922020-10-08 06:46:27 -04001069 const Variable& var = *ref.variable();
Ethan Nicholas453f67f2020-10-09 10:43:45 -04001070 if (var.storage() == Variable::Storage::kGlobal) {
Ethan Nicholas78686922020-10-08 06:46:27 -04001071 if (var.modifiers().fFlags & Modifiers::kIn_Flag) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001072 this->write("_in.");
Ethan Nicholas78686922020-10-08 06:46:27 -04001073 } else if (var.modifiers().fFlags & Modifiers::kOut_Flag) {
Timothy Liangee84fe12018-05-18 14:38:19 -04001074 this->write("_out->");
Ethan Nicholas78686922020-10-08 06:46:27 -04001075 } else if (var.modifiers().fFlags & Modifiers::kUniform_Flag &&
1076 var.type().typeKind() != Type::TypeKind::kSampler) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001077 this->write("_uniforms.");
1078 } else {
Timothy Liangee84fe12018-05-18 14:38:19 -04001079 this->write("_globals->");
Ethan Nicholascc305772017-10-13 16:17:45 -04001080 }
1081 }
Ethan Nicholas78686922020-10-08 06:46:27 -04001082 this->writeName(var.name());
Ethan Nicholascc305772017-10-13 16:17:45 -04001083 }
1084}
1085
1086void MetalCodeGenerator::writeIndexExpression(const IndexExpression& expr) {
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04001087 this->writeExpression(*expr.base(), kPostfix_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001088 this->write("[");
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04001089 this->writeExpression(*expr.index(), kTopLevel_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001090 this->write("]");
1091}
1092
1093void MetalCodeGenerator::writeFieldAccess(const FieldAccess& f) {
Ethan Nicholas7a95b202020-10-09 11:55:40 -04001094 const Type::Field* field = &f.base()->type().fields()[f.fieldIndex()];
1095 if (FieldAccess::OwnerKind::kDefault == f.ownerKind()) {
1096 this->writeExpression(*f.base(), kPostfix_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001097 this->write(".");
1098 }
Timothy Liang7d637782018-06-05 09:58:07 -04001099 switch (field->fModifiers.fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001100 case SK_POSITION_BUILTIN:
Timothy Liangb8eeb802018-07-23 16:46:16 -04001101 this->write("_out->sk_Position");
Ethan Nicholascc305772017-10-13 16:17:45 -04001102 break;
1103 default:
Timothy Liang7d637782018-06-05 09:58:07 -04001104 if (field->fName == "sk_PointSize") {
1105 this->write("_out->sk_PointSize");
1106 } else {
Ethan Nicholas7a95b202020-10-09 11:55:40 -04001107 if (FieldAccess::OwnerKind::kAnonymousInterfaceBlock == f.ownerKind()) {
Timothy Liang7d637782018-06-05 09:58:07 -04001108 this->write("_globals->");
1109 this->write(fInterfaceBlockNameMap[fInterfaceBlockMap[field]]);
1110 this->write("->");
1111 }
Timothy Liang651286f2018-06-07 09:55:33 -04001112 this->writeName(field->fName);
Timothy Lianga06f2152018-05-24 15:33:31 -04001113 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001114 }
1115}
1116
1117void MetalCodeGenerator::writeSwizzle(const Swizzle& swizzle) {
Ethan Nicholas6b4d5812020-10-12 16:11:51 -04001118 this->writeExpression(*swizzle.base(), kPostfix_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001119 this->write(".");
Ethan Nicholas6b4d5812020-10-12 16:11:51 -04001120 for (int c : swizzle.components()) {
Brian Osman25647672020-09-15 15:16:56 -04001121 SkASSERT(c >= 0 && c <= 3);
1122 this->write(&("x\0y\0z\0w\0"[c * 2]));
Ethan Nicholascc305772017-10-13 16:17:45 -04001123 }
1124}
1125
1126MetalCodeGenerator::Precedence MetalCodeGenerator::GetBinaryPrecedence(Token::Kind op) {
1127 switch (op) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001128 case Token::Kind::TK_STAR: // fall through
1129 case Token::Kind::TK_SLASH: // fall through
1130 case Token::Kind::TK_PERCENT: return MetalCodeGenerator::kMultiplicative_Precedence;
1131 case Token::Kind::TK_PLUS: // fall through
1132 case Token::Kind::TK_MINUS: return MetalCodeGenerator::kAdditive_Precedence;
1133 case Token::Kind::TK_SHL: // fall through
1134 case Token::Kind::TK_SHR: return MetalCodeGenerator::kShift_Precedence;
1135 case Token::Kind::TK_LT: // fall through
1136 case Token::Kind::TK_GT: // fall through
1137 case Token::Kind::TK_LTEQ: // fall through
1138 case Token::Kind::TK_GTEQ: return MetalCodeGenerator::kRelational_Precedence;
1139 case Token::Kind::TK_EQEQ: // fall through
1140 case Token::Kind::TK_NEQ: return MetalCodeGenerator::kEquality_Precedence;
1141 case Token::Kind::TK_BITWISEAND: return MetalCodeGenerator::kBitwiseAnd_Precedence;
1142 case Token::Kind::TK_BITWISEXOR: return MetalCodeGenerator::kBitwiseXor_Precedence;
1143 case Token::Kind::TK_BITWISEOR: return MetalCodeGenerator::kBitwiseOr_Precedence;
1144 case Token::Kind::TK_LOGICALAND: return MetalCodeGenerator::kLogicalAnd_Precedence;
1145 case Token::Kind::TK_LOGICALXOR: return MetalCodeGenerator::kLogicalXor_Precedence;
1146 case Token::Kind::TK_LOGICALOR: return MetalCodeGenerator::kLogicalOr_Precedence;
1147 case Token::Kind::TK_EQ: // fall through
1148 case Token::Kind::TK_PLUSEQ: // fall through
1149 case Token::Kind::TK_MINUSEQ: // fall through
1150 case Token::Kind::TK_STAREQ: // fall through
1151 case Token::Kind::TK_SLASHEQ: // fall through
1152 case Token::Kind::TK_PERCENTEQ: // fall through
1153 case Token::Kind::TK_SHLEQ: // fall through
1154 case Token::Kind::TK_SHREQ: // fall through
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001155 case Token::Kind::TK_BITWISEANDEQ: // fall through
1156 case Token::Kind::TK_BITWISEXOREQ: // fall through
1157 case Token::Kind::TK_BITWISEOREQ: return MetalCodeGenerator::kAssignment_Precedence;
1158 case Token::Kind::TK_COMMA: return MetalCodeGenerator::kSequence_Precedence;
Ethan Nicholascc305772017-10-13 16:17:45 -04001159 default: ABORT("unsupported binary operator");
1160 }
1161}
1162
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001163void MetalCodeGenerator::writeMatrixTimesEqualHelper(const Type& left, const Type& right,
1164 const Type& result) {
1165 String key = "TimesEqual" + left.name() + right.name();
1166 if (fHelpers.find(key) == fHelpers.end()) {
1167 fExtraFunctions.printf("%s operator*=(thread %s& left, thread const %s& right) {\n"
1168 " left = left * right;\n"
1169 " return left;\n"
Ethan Nicholase2c49992020-10-05 11:49:11 -04001170 "}", String(result.name()).c_str(), String(left.name()).c_str(),
1171 String(right.name()).c_str());
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001172 }
1173}
1174
Ethan Nicholascc305772017-10-13 16:17:45 -04001175void MetalCodeGenerator::writeBinaryExpression(const BinaryExpression& b,
1176 Precedence parentPrecedence) {
John Stiles2d4f9592020-10-30 10:29:12 -04001177 const Expression& left = *b.left();
1178 const Expression& right = *b.right();
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001179 const Type& leftType = left.type();
1180 const Type& rightType = right.type();
1181 Token::Kind op = b.getOperator();
1182 Precedence precedence = GetBinaryPrecedence(b.getOperator());
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001183 bool needParens = precedence >= parentPrecedence;
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001184 switch (op) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001185 case Token::Kind::TK_EQEQ:
John Stiles9aeed132020-11-24 17:36:06 -05001186 if (leftType.isVector()) {
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001187 this->write("all");
1188 needParens = true;
1189 }
1190 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001191 case Token::Kind::TK_NEQ:
John Stiles9aeed132020-11-24 17:36:06 -05001192 if (leftType.isVector()) {
Jim Van Verth36477b42019-04-11 14:57:30 -04001193 this->write("any");
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001194 needParens = true;
1195 }
1196 break;
1197 default:
1198 break;
1199 }
1200 if (needParens) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001201 this->write("(");
1202 }
John Stiles9aeed132020-11-24 17:36:06 -05001203 if (op == Token::Kind::TK_STAREQ && leftType.isMatrix() && rightType.isMatrix()) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001204 this->writeMatrixTimesEqualHelper(leftType, rightType, b.type());
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001205 }
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001206 this->writeExpression(left, precedence);
1207 if (op != Token::Kind::TK_EQ && Compiler::IsAssignment(op) &&
1208 left.kind() == Expression::Kind::kSwizzle && !left.hasSideEffects()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001209 // This doesn't compile in Metal:
1210 // float4 x = float4(1);
1211 // x.xy *= float2x2(...);
1212 // with the error message "non-const reference cannot bind to vector element",
1213 // but switching it to x.xy = x.xy * float2x2(...) fixes it. We perform this tranformation
1214 // as long as the LHS has no side effects, and hope for the best otherwise.
1215 this->write(" = ");
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001216 this->writeExpression(left, kAssignment_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001217 this->write(" ");
John Stilesd6449e92020-11-30 09:13:23 -05001218 String opName = OperatorName(op);
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001219 SkASSERT(opName.endsWith("="));
1220 this->write(opName.substr(0, opName.size() - 1).c_str());
Ethan Nicholascc305772017-10-13 16:17:45 -04001221 this->write(" ");
1222 } else {
John Stilesd6449e92020-11-30 09:13:23 -05001223 this->write(String(" ") + OperatorName(op) + " ");
Ethan Nicholascc305772017-10-13 16:17:45 -04001224 }
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001225 this->writeExpression(right, precedence);
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001226 if (needParens) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001227 this->write(")");
1228 }
1229}
1230
1231void MetalCodeGenerator::writeTernaryExpression(const TernaryExpression& t,
1232 Precedence parentPrecedence) {
1233 if (kTernary_Precedence >= parentPrecedence) {
1234 this->write("(");
1235 }
Ethan Nicholasdd218162020-10-08 05:48:01 -04001236 this->writeExpression(*t.test(), kTernary_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001237 this->write(" ? ");
Ethan Nicholasdd218162020-10-08 05:48:01 -04001238 this->writeExpression(*t.ifTrue(), kTernary_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001239 this->write(" : ");
Ethan Nicholasdd218162020-10-08 05:48:01 -04001240 this->writeExpression(*t.ifFalse(), kTernary_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001241 if (kTernary_Precedence >= parentPrecedence) {
1242 this->write(")");
1243 }
1244}
1245
1246void MetalCodeGenerator::writePrefixExpression(const PrefixExpression& p,
1247 Precedence parentPrecedence) {
1248 if (kPrefix_Precedence >= parentPrecedence) {
1249 this->write("(");
1250 }
John Stilesd6449e92020-11-30 09:13:23 -05001251 this->write(OperatorName(p.getOperator()));
Ethan Nicholas444ccc62020-10-09 10:16:22 -04001252 this->writeExpression(*p.operand(), kPrefix_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001253 if (kPrefix_Precedence >= parentPrecedence) {
1254 this->write(")");
1255 }
1256}
1257
1258void MetalCodeGenerator::writePostfixExpression(const PostfixExpression& p,
1259 Precedence parentPrecedence) {
1260 if (kPostfix_Precedence >= parentPrecedence) {
1261 this->write("(");
1262 }
Ethan Nicholas444ccc62020-10-09 10:16:22 -04001263 this->writeExpression(*p.operand(), kPostfix_Precedence);
John Stilesd6449e92020-11-30 09:13:23 -05001264 this->write(OperatorName(p.getOperator()));
Ethan Nicholascc305772017-10-13 16:17:45 -04001265 if (kPostfix_Precedence >= parentPrecedence) {
1266 this->write(")");
1267 }
1268}
1269
1270void MetalCodeGenerator::writeBoolLiteral(const BoolLiteral& b) {
Ethan Nicholas59d660c2020-09-28 09:18:15 -04001271 this->write(b.value() ? "true" : "false");
Ethan Nicholascc305772017-10-13 16:17:45 -04001272}
1273
1274void MetalCodeGenerator::writeIntLiteral(const IntLiteral& i) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001275 if (i.type() == *fContext.fUInt_Type) {
Ethan Nicholase96cdd12020-09-28 16:27:18 -04001276 this->write(to_string(i.value() & 0xffffffff) + "u");
Ethan Nicholascc305772017-10-13 16:17:45 -04001277 } else {
Ethan Nicholase96cdd12020-09-28 16:27:18 -04001278 this->write(to_string((int32_t) i.value()));
Ethan Nicholascc305772017-10-13 16:17:45 -04001279 }
1280}
1281
1282void MetalCodeGenerator::writeFloatLiteral(const FloatLiteral& f) {
Ethan Nicholasa3f22f12020-10-01 12:13:17 -04001283 this->write(to_string(f.value()));
Ethan Nicholascc305772017-10-13 16:17:45 -04001284}
1285
1286void MetalCodeGenerator::writeSetting(const Setting& s) {
1287 ABORT("internal error; setting was not folded to a constant during compilation\n");
1288}
1289
John Stiles06b84ef2020-12-09 12:35:48 -05001290void MetalCodeGenerator::writeFunctionRequirementArgs(const FunctionDeclaration& f,
1291 const char*& separator) {
1292 Requirements requirements = this->requirements(f);
1293 if (requirements & kInputs_Requirement) {
1294 this->write(separator);
1295 this->write("_in");
1296 separator = ", ";
1297 }
1298 if (requirements & kOutputs_Requirement) {
1299 this->write(separator);
1300 this->write("_out");
1301 separator = ", ";
1302 }
1303 if (requirements & kUniforms_Requirement) {
1304 this->write(separator);
1305 this->write("_uniforms");
1306 separator = ", ";
1307 }
1308 if (requirements & kGlobals_Requirement) {
1309 this->write(separator);
1310 this->write("_globals");
1311 separator = ", ";
1312 }
1313 if (requirements & kFragCoord_Requirement) {
1314 this->write(separator);
1315 this->write("_fragCoord");
1316 separator = ", ";
1317 }
1318}
1319
1320void MetalCodeGenerator::writeFunctionRequirementParams(const FunctionDeclaration& f,
1321 const char*& separator) {
1322 Requirements requirements = this->requirements(f);
1323 if (requirements & kInputs_Requirement) {
1324 this->write(separator);
1325 this->write("Inputs _in");
1326 separator = ", ";
1327 }
1328 if (requirements & kOutputs_Requirement) {
1329 this->write(separator);
1330 this->write("thread Outputs* _out");
1331 separator = ", ";
1332 }
1333 if (requirements & kUniforms_Requirement) {
1334 this->write(separator);
1335 this->write("Uniforms _uniforms");
1336 separator = ", ";
1337 }
1338 if (requirements & kGlobals_Requirement) {
1339 this->write(separator);
1340 this->write("thread Globals* _globals");
1341 separator = ", ";
1342 }
1343 if (requirements & kFragCoord_Requirement) {
1344 this->write(separator);
1345 this->write("float4 _fragCoord");
1346 separator = ", ";
1347 }
1348}
1349
John Stiles569249b2020-11-03 12:18:22 -05001350bool MetalCodeGenerator::writeFunctionDeclaration(const FunctionDeclaration& f) {
Ethan Nicholasf931e402019-07-26 15:40:33 -04001351 fRTHeightName = fProgram.fInputs.fRTHeight ? "_globals->_anonInterface0->u_skRTHeight" : "";
Ethan Nicholascc305772017-10-13 16:17:45 -04001352 const char* separator = "";
John Stiles569249b2020-11-03 12:18:22 -05001353 if ("main" == f.name()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001354 switch (fProgram.fKind) {
1355 case Program::kFragment_Kind:
Timothy Liangb8eeb802018-07-23 16:46:16 -04001356 this->write("fragment Outputs fragmentMain");
Ethan Nicholascc305772017-10-13 16:17:45 -04001357 break;
1358 case Program::kVertex_Kind:
Timothy Liangb8eeb802018-07-23 16:46:16 -04001359 this->write("vertex Outputs vertexMain");
Ethan Nicholascc305772017-10-13 16:17:45 -04001360 break;
1361 default:
John Stiles3fabfc02020-09-25 15:51:28 -04001362 fErrors.error(-1, "unsupported kind of program");
John Stiles569249b2020-11-03 12:18:22 -05001363 return false;
Ethan Nicholascc305772017-10-13 16:17:45 -04001364 }
1365 this->write("(Inputs _in [[stage_in]]");
1366 if (-1 != fUniformBuffer) {
1367 this->write(", constant Uniforms& _uniforms [[buffer(" +
1368 to_string(fUniformBuffer) + ")]]");
1369 }
Brian Osman133724c2020-10-28 14:14:39 -04001370 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04001371 if (e->is<GlobalVarDeclaration>()) {
1372 const GlobalVarDeclaration& decls = e->as<GlobalVarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001373 const VarDeclaration& var = decls.declaration()->as<VarDeclaration>();
1374 if (var.var().type().typeKind() == Type::TypeKind::kSampler) {
1375 if (var.var().modifiers().fLayout.fBinding < 0) {
Brian Osmanc0213602020-10-06 14:43:32 -04001376 fErrors.error(decls.fOffset,
1377 "Metal samplers must have 'layout(binding=...)'");
John Stiles569249b2020-11-03 12:18:22 -05001378 return false;
Timothy Liangee84fe12018-05-18 14:38:19 -04001379 }
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001380 if (var.var().type().dimensions() != SpvDim2D) {
John Stiles569249b2020-11-03 12:18:22 -05001381 // Not yet implemented--Skia currently only uses 2D textures.
Brian Osmanc0213602020-10-06 14:43:32 -04001382 fErrors.error(decls.fOffset, "Unsupported texture dimensions");
John Stiles569249b2020-11-03 12:18:22 -05001383 return false;
Brian Osmanc0213602020-10-06 14:43:32 -04001384 }
1385 this->write(", texture2d<float> ");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001386 this->writeName(var.var().name());
Brian Osmanc0213602020-10-06 14:43:32 -04001387 this->write("[[texture(");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001388 this->write(to_string(var.var().modifiers().fLayout.fBinding));
Brian Osmanc0213602020-10-06 14:43:32 -04001389 this->write(")]]");
1390 this->write(", sampler ");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001391 this->writeName(var.var().name());
Brian Osmanc0213602020-10-06 14:43:32 -04001392 this->write(SAMPLER_SUFFIX);
1393 this->write("[[sampler(");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001394 this->write(to_string(var.var().modifiers().fLayout.fBinding));
Brian Osmanc0213602020-10-06 14:43:32 -04001395 this->write(")]]");
Timothy Liang6403b0e2018-05-17 10:40:04 -04001396 }
Brian Osman1179fcf2020-10-08 16:04:40 -04001397 } else if (e->is<InterfaceBlock>()) {
1398 const InterfaceBlock& intf = e->as<InterfaceBlock>();
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001399 if (intf.typeName() == "sk_PerVertex") {
Timothy Lianga06f2152018-05-24 15:33:31 -04001400 continue;
1401 }
John Stilesbc3c41b2020-12-04 10:52:40 -05001402 if (intf.variable().modifiers().fLayout.fBinding < 0) {
1403 fErrors.error(intf.fOffset,
1404 "Metal interface blocks must have 'layout(binding=...)'");
1405 return false;
1406 }
Timothy Lianga06f2152018-05-24 15:33:31 -04001407 this->write(", constant ");
John Stiles3dba3ee2020-12-02 23:35:49 -05001408 this->writeBaseType(intf.variable().type());
Timothy Lianga06f2152018-05-24 15:33:31 -04001409 this->write("& " );
1410 this->write(fInterfaceBlockNameMap[&intf]);
1411 this->write(" [[buffer(");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001412 this->write(to_string(intf.variable().modifiers().fLayout.fBinding));
Timothy Lianga06f2152018-05-24 15:33:31 -04001413 this->write(")]]");
Timothy Liang6403b0e2018-05-17 10:40:04 -04001414 }
1415 }
Jim Van Verth6bc650e2019-02-07 14:53:23 -05001416 if (fProgram.fKind == Program::kFragment_Kind) {
1417 if (fProgram.fInputs.fRTHeight && fInterfaceBlockNameMap.empty()) {
Timothy Liang5422f9a2018-08-10 10:57:55 -04001418 this->write(", constant sksl_synthetic_uniforms& _anonInterface0 [[buffer(1)]]");
Ethan Nicholasf931e402019-07-26 15:40:33 -04001419 fRTHeightName = "_anonInterface0.u_skRTHeight";
Timothy Liang5422f9a2018-08-10 10:57:55 -04001420 }
Timothy Liang7b8875d2018-08-10 09:42:31 -04001421 this->write(", bool _frontFacing [[front_facing]]");
Timothy Liang7d637782018-06-05 09:58:07 -04001422 this->write(", float4 _fragCoord [[position]]");
Timothy Liangdc89f192018-06-13 09:20:31 -04001423 } else if (fProgram.fKind == Program::kVertex_Kind) {
1424 this->write(", uint sk_VertexID [[vertex_id]], uint sk_InstanceID [[instance_id]]");
Timothy Liang7d637782018-06-05 09:58:07 -04001425 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001426 separator = ", ";
1427 } else {
John Stiles3dba3ee2020-12-02 23:35:49 -05001428 this->writeBaseType(f.returnType());
John Stilesea166702020-12-11 17:30:47 -05001429 this->disallowArrayTypes(f.returnType(), f.fOffset);
Timothy Liang651286f2018-06-07 09:55:33 -04001430 this->write(" ");
John Stiles569249b2020-11-03 12:18:22 -05001431 this->writeName(f.name());
Timothy Liang651286f2018-06-07 09:55:33 -04001432 this->write("(");
John Stiles06b84ef2020-12-09 12:35:48 -05001433 this->writeFunctionRequirementParams(f, separator);
Ethan Nicholascc305772017-10-13 16:17:45 -04001434 }
John Stiles569249b2020-11-03 12:18:22 -05001435 for (const auto& param : f.parameters()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001436 this->write(separator);
1437 separator = ", ";
John Stiles06b84ef2020-12-09 12:35:48 -05001438 this->writeModifiers(param->modifiers(), /*globalContext=*/false);
Ethan Nicholas30d30222020-09-11 12:27:26 -04001439 const Type* type = &param->type();
John Stiles3dba3ee2020-12-02 23:35:49 -05001440 this->writeBaseType(*type);
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001441 if (param->modifiers().fFlags & Modifiers::kOut_Flag) {
John Stilesf2bd5012020-12-04 11:58:26 -05001442 this->write("&");
Ethan Nicholascc305772017-10-13 16:17:45 -04001443 }
Timothy Liang651286f2018-06-07 09:55:33 -04001444 this->write(" ");
Ethan Nicholase2c49992020-10-05 11:49:11 -04001445 this->writeName(param->name());
John Stiles3dba3ee2020-12-02 23:35:49 -05001446 this->writeArrayDimensions(*type);
Ethan Nicholascc305772017-10-13 16:17:45 -04001447 }
John Stiles569249b2020-11-03 12:18:22 -05001448 this->write(")");
1449 return true;
1450}
Ethan Nicholascc305772017-10-13 16:17:45 -04001451
John Stiles569249b2020-11-03 12:18:22 -05001452void MetalCodeGenerator::writeFunctionPrototype(const FunctionPrototype& f) {
1453 this->writeFunctionDeclaration(f.declaration());
1454 this->writeLine(";");
1455}
1456
John Stiles986c7fb2020-12-01 14:44:56 -05001457static bool is_block_ending_with_return(const Statement* stmt) {
1458 // This function detects (potentially nested) blocks that end in a return statement.
1459 if (!stmt->is<Block>()) {
1460 return false;
1461 }
1462 const StatementArray& block = stmt->as<Block>().children();
1463 for (int index = block.count(); index--; ) {
1464 const Statement& stmt = *block[index];
1465 if (stmt.is<ReturnStatement>()) {
1466 return true;
1467 }
1468 if (stmt.is<Block>()) {
1469 return is_block_ending_with_return(&stmt);
1470 }
1471 if (!stmt.is<Nop>()) {
1472 break;
1473 }
1474 }
1475 return false;
1476}
1477
John Stiles569249b2020-11-03 12:18:22 -05001478void MetalCodeGenerator::writeFunction(const FunctionDefinition& f) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001479 SkASSERT(!fProgram.fSettings.fFragColorIsInOut);
Brian Salomondc092132018-04-04 10:14:16 -04001480
John Stiles569249b2020-11-03 12:18:22 -05001481 if (!this->writeFunctionDeclaration(f.declaration())) {
1482 return;
1483 }
1484
John Stiles986c7fb2020-12-01 14:44:56 -05001485 fCurrentFunction = &f.declaration();
1486 SkScopeExit clearCurrentFunction([&] { fCurrentFunction = nullptr; });
1487
John Stiles569249b2020-11-03 12:18:22 -05001488 this->writeLine(" {");
1489
Ethan Nicholas0a5d0962020-10-14 13:33:18 -04001490 if (f.declaration().name() == "main") {
John Stilescdcdb042020-07-06 09:03:51 -04001491 this->writeGlobalInit();
Timothy Liang7d637782018-06-05 09:58:07 -04001492 this->writeLine(" Outputs _outputStruct;");
1493 this->writeLine(" thread Outputs* _out = &_outputStruct;");
Ethan Nicholascc305772017-10-13 16:17:45 -04001494 }
John Stilesc67b3622020-05-28 17:53:13 -04001495
Ethan Nicholascc305772017-10-13 16:17:45 -04001496 fFunctionHeader = "";
Ethan Nicholascc305772017-10-13 16:17:45 -04001497 StringStream buffer;
John Stiles44532372020-12-07 12:33:55 -05001498 {
1499 AutoOutputStream outputToBuffer(this, &buffer);
1500 fIndentation++;
1501 for (const std::unique_ptr<Statement>& stmt : f.body()->as<Block>().children()) {
1502 if (!stmt->isEmpty()) {
1503 this->writeStatement(*stmt);
1504 this->writeLine();
1505 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001506 }
John Stiles44532372020-12-07 12:33:55 -05001507 if (f.declaration().name() == "main") {
1508 // If the main function doesn't end with a return, we need to synthesize one here.
1509 if (!is_block_ending_with_return(f.body().get())) {
1510 this->writeReturnStatementFromMain();
1511 this->writeLine("");
1512 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001513 }
John Stiles44532372020-12-07 12:33:55 -05001514 fIndentation--;
1515 this->writeLine("}");
Ethan Nicholascc305772017-10-13 16:17:45 -04001516 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001517 this->write(fFunctionHeader);
1518 this->write(buffer.str());
1519}
1520
1521void MetalCodeGenerator::writeModifiers(const Modifiers& modifiers,
John Stiles06b84ef2020-12-09 12:35:48 -05001522 bool globalContext) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001523 if (modifiers.fFlags & Modifiers::kOut_Flag) {
1524 this->write("thread ");
1525 }
1526 if (modifiers.fFlags & Modifiers::kConst_Flag) {
Timothy Liangee84fe12018-05-18 14:38:19 -04001527 this->write("constant ");
Ethan Nicholascc305772017-10-13 16:17:45 -04001528 }
1529}
1530
1531void MetalCodeGenerator::writeInterfaceBlock(const InterfaceBlock& intf) {
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001532 if ("sk_PerVertex" == intf.typeName()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001533 return;
1534 }
John Stiles06b84ef2020-12-09 12:35:48 -05001535 this->writeModifiers(intf.variable().modifiers(), /*globalContext=*/true);
Timothy Liangdc89f192018-06-13 09:20:31 -04001536 this->write("struct ");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001537 this->writeLine(intf.typeName() + " {");
1538 const Type* structType = &intf.variable().type();
John Stilesbb43b7e2020-12-03 17:36:32 -05001539 if (structType->isArray()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001540 structType = &structType->componentType();
1541 }
John Stiles3dba3ee2020-12-02 23:35:49 -05001542 fWrittenStructs.push_back(structType);
Timothy Liangdc89f192018-06-13 09:20:31 -04001543 fIndentation++;
John Stiles3dba3ee2020-12-02 23:35:49 -05001544 this->writeFields(structType->fields(), structType->fOffset, &intf);
Jim Van Verth3d482992019-02-07 10:48:05 -05001545 if (fProgram.fInputs.fRTHeight) {
Timothy Liang7d637782018-06-05 09:58:07 -04001546 this->writeLine("float u_skRTHeight;");
Ethan Nicholascc305772017-10-13 16:17:45 -04001547 }
1548 fIndentation--;
1549 this->write("}");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001550 if (intf.instanceName().size()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001551 this->write(" ");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001552 this->write(intf.instanceName());
John Stilesd39aec02020-12-03 10:42:26 -05001553 if (intf.arraySize() > 0) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001554 this->write("[");
John Stilesd39aec02020-12-03 10:42:26 -05001555 this->write(to_string(intf.arraySize()));
Ethan Nicholascc305772017-10-13 16:17:45 -04001556 this->write("]");
John Stilesd39aec02020-12-03 10:42:26 -05001557 } else if (intf.arraySize() == Type::kUnsizedArray){
1558 this->write("[]");
Ethan Nicholascc305772017-10-13 16:17:45 -04001559 }
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001560 fInterfaceBlockNameMap[&intf] = intf.instanceName();
Timothy Lianga06f2152018-05-24 15:33:31 -04001561 } else {
Timothy Liang7d637782018-06-05 09:58:07 -04001562 fInterfaceBlockNameMap[&intf] = "_anonInterface" + to_string(fAnonInterfaceCount++);
Ethan Nicholascc305772017-10-13 16:17:45 -04001563 }
1564 this->writeLine(";");
1565}
1566
Timothy Liangdc89f192018-06-13 09:20:31 -04001567void MetalCodeGenerator::writeFields(const std::vector<Type::Field>& fields, int parentOffset,
1568 const InterfaceBlock* parentIntf) {
Timothy Liang609fbe32018-08-10 16:40:49 -04001569 MemoryLayout memoryLayout(MemoryLayout::kMetal_Standard);
Timothy Liangdc89f192018-06-13 09:20:31 -04001570 int currentOffset = 0;
1571 for (const auto& field: fields) {
1572 int fieldOffset = field.fModifiers.fLayout.fOffset;
1573 const Type* fieldType = field.fType;
John Stiles21f5f452020-11-30 09:57:59 -05001574 if (!MemoryLayout::LayoutIsSupported(*fieldType)) {
John Stiles0023c0c2020-11-16 13:32:18 -05001575 fErrors.error(parentOffset, "type '" + fieldType->name() + "' is not permitted here");
1576 return;
1577 }
Timothy Liangdc89f192018-06-13 09:20:31 -04001578 if (fieldOffset != -1) {
1579 if (currentOffset > fieldOffset) {
1580 fErrors.error(parentOffset,
1581 "offset of field '" + field.fName + "' must be at least " +
1582 to_string((int) currentOffset));
Brian Osman8609a242020-09-08 14:01:49 -04001583 return;
Timothy Liangdc89f192018-06-13 09:20:31 -04001584 } else if (currentOffset < fieldOffset) {
1585 this->write("char pad");
1586 this->write(to_string(fPaddingCount++));
1587 this->write("[");
1588 this->write(to_string(fieldOffset - currentOffset));
1589 this->writeLine("];");
1590 currentOffset = fieldOffset;
1591 }
1592 int alignment = memoryLayout.alignment(*fieldType);
1593 if (fieldOffset % alignment) {
1594 fErrors.error(parentOffset,
1595 "offset of field '" + field.fName + "' must be a multiple of " +
1596 to_string((int) alignment));
Brian Osman8609a242020-09-08 14:01:49 -04001597 return;
Timothy Liangdc89f192018-06-13 09:20:31 -04001598 }
1599 }
Brian Osman8609a242020-09-08 14:01:49 -04001600 size_t fieldSize = memoryLayout.size(*fieldType);
1601 if (fieldSize > static_cast<size_t>(std::numeric_limits<int>::max() - currentOffset)) {
1602 fErrors.error(parentOffset, "field offset overflow");
1603 return;
1604 }
1605 currentOffset += fieldSize;
John Stiles06b84ef2020-12-09 12:35:48 -05001606 this->writeModifiers(field.fModifiers, /*globalContext=*/false);
John Stiles3dba3ee2020-12-02 23:35:49 -05001607 this->writeBaseType(*fieldType);
Timothy Liangdc89f192018-06-13 09:20:31 -04001608 this->write(" ");
1609 this->writeName(field.fName);
John Stiles3dba3ee2020-12-02 23:35:49 -05001610 this->writeArrayDimensions(*fieldType);
Timothy Liangdc89f192018-06-13 09:20:31 -04001611 this->writeLine(";");
1612 if (parentIntf) {
1613 fInterfaceBlockMap[&field] = parentIntf;
1614 }
1615 }
1616}
1617
Ethan Nicholascc305772017-10-13 16:17:45 -04001618void MetalCodeGenerator::writeVarInitializer(const Variable& var, const Expression& value) {
1619 this->writeExpression(value, kTopLevel_Precedence);
1620}
1621
Timothy Liang651286f2018-06-07 09:55:33 -04001622void MetalCodeGenerator::writeName(const String& name) {
1623 if (fReservedWords.find(name) != fReservedWords.end()) {
1624 this->write("_"); // adding underscore before name to avoid conflict with reserved words
1625 }
1626 this->write(name);
1627}
1628
Brian Osmanc0213602020-10-06 14:43:32 -04001629void MetalCodeGenerator::writeVarDeclaration(const VarDeclaration& var, bool global) {
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001630 if (global && !(var.var().modifiers().fFlags & Modifiers::kConst_Flag)) {
Brian Osmanc0213602020-10-06 14:43:32 -04001631 return;
Ethan Nicholascc305772017-10-13 16:17:45 -04001632 }
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001633 this->writeModifiers(var.var().modifiers(), global);
John Stiles3dba3ee2020-12-02 23:35:49 -05001634 this->writeBaseType(var.baseType());
John Stilesea166702020-12-11 17:30:47 -05001635 this->disallowArrayTypes(var.baseType(), var.fOffset);
Brian Osmanc0213602020-10-06 14:43:32 -04001636 this->write(" ");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001637 this->writeName(var.var().name());
John Stiles62a56462020-12-03 10:41:58 -05001638 if (var.arraySize() > 0) {
Brian Osmanc0213602020-10-06 14:43:32 -04001639 this->write("[");
John Stiles62a56462020-12-03 10:41:58 -05001640 this->write(to_string(var.arraySize()));
Brian Osmanc0213602020-10-06 14:43:32 -04001641 this->write("]");
John Stiles62a56462020-12-03 10:41:58 -05001642 } else if (var.arraySize() == Type::kUnsizedArray){
1643 this->write("[]");
Ethan Nicholascc305772017-10-13 16:17:45 -04001644 }
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001645 if (var.value()) {
Brian Osmanc0213602020-10-06 14:43:32 -04001646 this->write(" = ");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001647 this->writeVarInitializer(var.var(), *var.value());
Brian Osmanc0213602020-10-06 14:43:32 -04001648 }
1649 this->write(";");
Ethan Nicholascc305772017-10-13 16:17:45 -04001650}
1651
1652void MetalCodeGenerator::writeStatement(const Statement& s) {
Ethan Nicholase6592142020-09-08 10:22:09 -04001653 switch (s.kind()) {
1654 case Statement::Kind::kBlock:
John Stiles26f98502020-08-18 09:30:51 -04001655 this->writeBlock(s.as<Block>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001656 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001657 case Statement::Kind::kExpression:
Ethan Nicholasd503a5a2020-09-30 09:29:55 -04001658 this->writeExpression(*s.as<ExpressionStatement>().expression(), kTopLevel_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001659 this->write(";");
1660 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001661 case Statement::Kind::kReturn:
John Stiles26f98502020-08-18 09:30:51 -04001662 this->writeReturnStatement(s.as<ReturnStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001663 break;
Brian Osmanc0213602020-10-06 14:43:32 -04001664 case Statement::Kind::kVarDeclaration:
1665 this->writeVarDeclaration(s.as<VarDeclaration>(), false);
Ethan Nicholascc305772017-10-13 16:17:45 -04001666 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001667 case Statement::Kind::kIf:
John Stiles26f98502020-08-18 09:30:51 -04001668 this->writeIfStatement(s.as<IfStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001669 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001670 case Statement::Kind::kFor:
John Stiles26f98502020-08-18 09:30:51 -04001671 this->writeForStatement(s.as<ForStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001672 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001673 case Statement::Kind::kDo:
John Stiles26f98502020-08-18 09:30:51 -04001674 this->writeDoStatement(s.as<DoStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001675 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001676 case Statement::Kind::kSwitch:
John Stiles26f98502020-08-18 09:30:51 -04001677 this->writeSwitchStatement(s.as<SwitchStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001678 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001679 case Statement::Kind::kBreak:
Ethan Nicholascc305772017-10-13 16:17:45 -04001680 this->write("break;");
1681 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001682 case Statement::Kind::kContinue:
Ethan Nicholascc305772017-10-13 16:17:45 -04001683 this->write("continue;");
1684 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001685 case Statement::Kind::kDiscard:
Timothy Lianga06f2152018-05-24 15:33:31 -04001686 this->write("discard_fragment();");
Ethan Nicholascc305772017-10-13 16:17:45 -04001687 break;
John Stiles98c1f822020-09-09 14:18:53 -04001688 case Statement::Kind::kInlineMarker:
Ethan Nicholase6592142020-09-08 10:22:09 -04001689 case Statement::Kind::kNop:
Ethan Nicholascc305772017-10-13 16:17:45 -04001690 this->write(";");
1691 break;
1692 default:
Ethan Nicholas2a099da2020-01-02 14:40:54 -05001693#ifdef SK_DEBUG
Ethan Nicholascc305772017-10-13 16:17:45 -04001694 ABORT("unsupported statement: %s", s.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -05001695#endif
1696 break;
Ethan Nicholascc305772017-10-13 16:17:45 -04001697 }
1698}
1699
Ethan Nicholascc305772017-10-13 16:17:45 -04001700void MetalCodeGenerator::writeBlock(const Block& b) {
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001701 bool isScope = b.isScope();
1702 if (isScope) {
Ethan Nicholas70728ef2020-05-28 07:09:00 -04001703 this->writeLine("{");
1704 fIndentation++;
1705 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001706 for (const std::unique_ptr<Statement>& stmt : b.children()) {
1707 if (!stmt->isEmpty()) {
1708 this->writeStatement(*stmt);
1709 this->writeLine();
1710 }
1711 }
1712 if (isScope) {
Ethan Nicholas70728ef2020-05-28 07:09:00 -04001713 fIndentation--;
1714 this->write("}");
1715 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001716}
1717
1718void MetalCodeGenerator::writeIfStatement(const IfStatement& stmt) {
1719 this->write("if (");
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04001720 this->writeExpression(*stmt.test(), kTopLevel_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001721 this->write(") ");
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04001722 this->writeStatement(*stmt.ifTrue());
1723 if (stmt.ifFalse()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001724 this->write(" else ");
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04001725 this->writeStatement(*stmt.ifFalse());
Ethan Nicholascc305772017-10-13 16:17:45 -04001726 }
1727}
1728
1729void MetalCodeGenerator::writeForStatement(const ForStatement& f) {
Brian Osmand6f23382020-12-15 17:08:59 -05001730 // Emit loops of the form 'for(;test;)' as 'while(test)', which is probably how they started
1731 if (!f.initializer() && f.test() && !f.next()) {
1732 this->write("while (");
1733 this->writeExpression(*f.test(), kTopLevel_Precedence);
1734 this->write(") ");
1735 this->writeStatement(*f.statement());
1736 return;
1737 }
1738
Ethan Nicholascc305772017-10-13 16:17:45 -04001739 this->write("for (");
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04001740 if (f.initializer() && !f.initializer()->isEmpty()) {
1741 this->writeStatement(*f.initializer());
Ethan Nicholascc305772017-10-13 16:17:45 -04001742 } else {
1743 this->write("; ");
1744 }
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04001745 if (f.test()) {
1746 this->writeExpression(*f.test(), kTopLevel_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001747 }
1748 this->write("; ");
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04001749 if (f.next()) {
1750 this->writeExpression(*f.next(), kTopLevel_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001751 }
1752 this->write(") ");
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04001753 this->writeStatement(*f.statement());
Ethan Nicholascc305772017-10-13 16:17:45 -04001754}
1755
Ethan Nicholascc305772017-10-13 16:17:45 -04001756void MetalCodeGenerator::writeDoStatement(const DoStatement& d) {
1757 this->write("do ");
Ethan Nicholas1fd61162020-09-28 13:14:19 -04001758 this->writeStatement(*d.statement());
Ethan Nicholascc305772017-10-13 16:17:45 -04001759 this->write(" while (");
Ethan Nicholas1fd61162020-09-28 13:14:19 -04001760 this->writeExpression(*d.test(), kTopLevel_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001761 this->write(");");
1762}
1763
1764void MetalCodeGenerator::writeSwitchStatement(const SwitchStatement& s) {
1765 this->write("switch (");
Ethan Nicholas01b05e52020-10-22 15:53:41 -04001766 this->writeExpression(*s.value(), kTopLevel_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001767 this->writeLine(") {");
1768 fIndentation++;
John Stiles2d4f9592020-10-30 10:29:12 -04001769 for (const std::unique_ptr<SwitchCase>& c : s.cases()) {
1770 if (c->value()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001771 this->write("case ");
John Stiles2d4f9592020-10-30 10:29:12 -04001772 this->writeExpression(*c->value(), kTopLevel_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001773 this->writeLine(":");
1774 } else {
1775 this->writeLine("default:");
1776 }
1777 fIndentation++;
John Stiles2d4f9592020-10-30 10:29:12 -04001778 for (const auto& stmt : c->statements()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001779 this->writeStatement(*stmt);
1780 this->writeLine();
1781 }
1782 fIndentation--;
1783 }
1784 fIndentation--;
1785 this->write("}");
1786}
1787
John Stiles986c7fb2020-12-01 14:44:56 -05001788void MetalCodeGenerator::writeReturnStatementFromMain() {
1789 // main functions in Metal return a magic _out parameter that doesn't exist in SkSL.
1790 switch (fProgram.fKind) {
1791 case Program::kFragment_Kind:
1792 this->write("return *_out;");
1793 break;
1794 case Program::kVertex_Kind:
1795 this->write("return (_out->sk_Position.y = -_out->sk_Position.y, *_out);");
1796 break;
1797 default:
1798 SkDEBUGFAIL("unsupported kind of program");
1799 }
1800}
1801
Ethan Nicholascc305772017-10-13 16:17:45 -04001802void MetalCodeGenerator::writeReturnStatement(const ReturnStatement& r) {
John Stiles986c7fb2020-12-01 14:44:56 -05001803 if (fCurrentFunction && fCurrentFunction->name() == "main") {
1804 if (r.expression()) {
1805 fErrors.error(r.fOffset, "Metal does not support returning values from main()");
1806 }
1807 this->writeReturnStatementFromMain();
1808 return;
1809 }
1810
Ethan Nicholascc305772017-10-13 16:17:45 -04001811 this->write("return");
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04001812 if (r.expression()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001813 this->write(" ");
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04001814 this->writeExpression(*r.expression(), kTopLevel_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001815 }
1816 this->write(";");
1817}
1818
1819void MetalCodeGenerator::writeHeader() {
1820 this->write("#include <metal_stdlib>\n");
1821 this->write("#include <simd/simd.h>\n");
1822 this->write("using namespace metal;\n");
1823}
1824
1825void MetalCodeGenerator::writeUniformStruct() {
Brian Osman133724c2020-10-28 14:14:39 -04001826 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04001827 if (e->is<GlobalVarDeclaration>()) {
1828 const GlobalVarDeclaration& decls = e->as<GlobalVarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001829 const Variable& var = decls.declaration()->as<VarDeclaration>().var();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001830 if (var.modifiers().fFlags & Modifiers::kUniform_Flag &&
Brian Osmanc0213602020-10-06 14:43:32 -04001831 var.type().typeKind() != Type::TypeKind::kSampler) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001832 if (-1 == fUniformBuffer) {
1833 this->write("struct Uniforms {\n");
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001834 fUniformBuffer = var.modifiers().fLayout.fSet;
Ethan Nicholascc305772017-10-13 16:17:45 -04001835 if (-1 == fUniformBuffer) {
1836 fErrors.error(decls.fOffset, "Metal uniforms must have 'layout(set=...)'");
1837 }
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001838 } else if (var.modifiers().fLayout.fSet != fUniformBuffer) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001839 if (-1 == fUniformBuffer) {
1840 fErrors.error(decls.fOffset, "Metal backend requires all uniforms to have "
1841 "the same 'layout(set=...)'");
1842 }
1843 }
1844 this->write(" ");
John Stiles3dba3ee2020-12-02 23:35:49 -05001845 this->writeBaseType(var.type());
Ethan Nicholascc305772017-10-13 16:17:45 -04001846 this->write(" ");
Brian Osmanc0213602020-10-06 14:43:32 -04001847 this->writeName(var.name());
John Stiles3dba3ee2020-12-02 23:35:49 -05001848 this->writeArrayDimensions(var.type());
Ethan Nicholascc305772017-10-13 16:17:45 -04001849 this->write(";\n");
1850 }
1851 }
1852 }
1853 if (-1 != fUniformBuffer) {
1854 this->write("};\n");
1855 }
1856}
1857
1858void MetalCodeGenerator::writeInputStruct() {
1859 this->write("struct Inputs {\n");
Brian Osman133724c2020-10-28 14:14:39 -04001860 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04001861 if (e->is<GlobalVarDeclaration>()) {
1862 const GlobalVarDeclaration& decls = e->as<GlobalVarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001863 const Variable& var = decls.declaration()->as<VarDeclaration>().var();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001864 if (var.modifiers().fFlags & Modifiers::kIn_Flag &&
1865 -1 == var.modifiers().fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001866 this->write(" ");
John Stiles3dba3ee2020-12-02 23:35:49 -05001867 this->writeBaseType(var.type());
Ethan Nicholascc305772017-10-13 16:17:45 -04001868 this->write(" ");
Brian Osmanc0213602020-10-06 14:43:32 -04001869 this->writeName(var.name());
John Stiles3dba3ee2020-12-02 23:35:49 -05001870 this->writeArrayDimensions(var.type());
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001871 if (-1 != var.modifiers().fLayout.fLocation) {
Brian Osmanc0213602020-10-06 14:43:32 -04001872 if (fProgram.fKind == Program::kVertex_Kind) {
1873 this->write(" [[attribute(" +
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001874 to_string(var.modifiers().fLayout.fLocation) + ")]]");
Brian Osmanc0213602020-10-06 14:43:32 -04001875 } else if (fProgram.fKind == Program::kFragment_Kind) {
1876 this->write(" [[user(locn" +
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001877 to_string(var.modifiers().fLayout.fLocation) + ")]]");
Ethan Nicholascc305772017-10-13 16:17:45 -04001878 }
1879 }
1880 this->write(";\n");
1881 }
1882 }
1883 }
1884 this->write("};\n");
1885}
1886
1887void MetalCodeGenerator::writeOutputStruct() {
1888 this->write("struct Outputs {\n");
Timothy Liang7d637782018-06-05 09:58:07 -04001889 if (fProgram.fKind == Program::kVertex_Kind) {
Timothy Liangb8eeb802018-07-23 16:46:16 -04001890 this->write(" float4 sk_Position [[position]];\n");
Timothy Liang7d637782018-06-05 09:58:07 -04001891 } else if (fProgram.fKind == Program::kFragment_Kind) {
Timothy Liangde0be802018-08-10 13:48:08 -04001892 this->write(" float4 sk_FragColor [[color(0)]];\n");
Timothy Liang7d637782018-06-05 09:58:07 -04001893 }
Brian Osman133724c2020-10-28 14:14:39 -04001894 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04001895 if (e->is<GlobalVarDeclaration>()) {
1896 const GlobalVarDeclaration& decls = e->as<GlobalVarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001897 const Variable& var = decls.declaration()->as<VarDeclaration>().var();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001898 if (var.modifiers().fFlags & Modifiers::kOut_Flag &&
1899 -1 == var.modifiers().fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001900 this->write(" ");
John Stiles3dba3ee2020-12-02 23:35:49 -05001901 this->writeBaseType(var.type());
Ethan Nicholascc305772017-10-13 16:17:45 -04001902 this->write(" ");
Brian Osmanc0213602020-10-06 14:43:32 -04001903 this->writeName(var.name());
John Stiles3dba3ee2020-12-02 23:35:49 -05001904 this->writeArrayDimensions(var.type());
John Stiles842b3592020-12-01 10:36:37 -05001905
1906 int location = var.modifiers().fLayout.fLocation;
1907 if (location < 0) {
1908 fErrors.error(var.fOffset,
1909 "Metal out variables must have 'layout(location=...)'");
1910 } else if (fProgram.fKind == Program::kVertex_Kind) {
1911 this->write(" [[user(locn" + to_string(location) + ")]]");
Brian Osmanc0213602020-10-06 14:43:32 -04001912 } else if (fProgram.fKind == Program::kFragment_Kind) {
John Stiles842b3592020-12-01 10:36:37 -05001913 this->write(" [[color(" + to_string(location) + ")");
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001914 int colorIndex = var.modifiers().fLayout.fIndex;
Brian Osmanc0213602020-10-06 14:43:32 -04001915 if (colorIndex) {
1916 this->write(", index(" + to_string(colorIndex) + ")");
Timothy Liang7d637782018-06-05 09:58:07 -04001917 }
Brian Osmanc0213602020-10-06 14:43:32 -04001918 this->write("]]");
Ethan Nicholascc305772017-10-13 16:17:45 -04001919 }
1920 this->write(";\n");
1921 }
1922 }
Timothy Liang7d637782018-06-05 09:58:07 -04001923 }
1924 if (fProgram.fKind == Program::kVertex_Kind) {
Jim Van Verth3913d3e2020-08-31 15:16:57 -04001925 this->write(" float sk_PointSize [[point_size]];\n");
Timothy Liang7d637782018-06-05 09:58:07 -04001926 }
1927 this->write("};\n");
1928}
1929
1930void MetalCodeGenerator::writeInterfaceBlocks() {
1931 bool wroteInterfaceBlock = false;
Brian Osman133724c2020-10-28 14:14:39 -04001932 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04001933 if (e->is<InterfaceBlock>()) {
1934 this->writeInterfaceBlock(e->as<InterfaceBlock>());
Timothy Liang7d637782018-06-05 09:58:07 -04001935 wroteInterfaceBlock = true;
1936 }
1937 }
Jim Van Verth3d482992019-02-07 10:48:05 -05001938 if (!wroteInterfaceBlock && fProgram.fInputs.fRTHeight) {
Timothy Liang7d637782018-06-05 09:58:07 -04001939 this->writeLine("struct sksl_synthetic_uniforms {");
1940 this->writeLine(" float u_skRTHeight;");
1941 this->writeLine("};");
1942 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001943}
1944
John Stilesdc75a972020-11-25 16:24:55 -05001945void MetalCodeGenerator::writeStructDefinitions() {
1946 for (const ProgramElement* e : fProgram.elements()) {
1947 if (e->is<StructDefinition>()) {
1948 if (this->writeStructDefinition(e->as<StructDefinition>().type())) {
1949 this->writeLine(";");
1950 }
1951 } else if (e->is<GlobalVarDeclaration>()) {
1952 // If a global var declaration introduces a struct type, we need to write that type
1953 // here, since globals are all embedded in a sub-struct.
1954 const Type* type = &e->as<GlobalVarDeclaration>().declaration()
1955 ->as<VarDeclaration>().baseType();
John Stilesc0c51062020-12-03 17:16:29 -05001956 if (type->isStruct()) {
John Stilesdc75a972020-11-25 16:24:55 -05001957 if (this->writeStructDefinition(*type)) {
1958 this->writeLine(";");
1959 }
1960 }
1961 }
1962 }
1963}
1964
John Stilescdcdb042020-07-06 09:03:51 -04001965void MetalCodeGenerator::visitGlobalStruct(GlobalStructVisitor* visitor) {
1966 // Visit the interface blocks.
1967 for (const auto& [interfaceType, interfaceName] : fInterfaceBlockNameMap) {
John Stilesfdb8dbe2020-12-04 11:00:03 -05001968 visitor->visitInterfaceBlock(*interfaceType, interfaceName);
John Stilescdcdb042020-07-06 09:03:51 -04001969 }
Brian Osman133724c2020-10-28 14:14:39 -04001970 for (const ProgramElement* element : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04001971 if (!element->is<GlobalVarDeclaration>()) {
John Stilescdcdb042020-07-06 09:03:51 -04001972 continue;
Timothy Liang7d637782018-06-05 09:58:07 -04001973 }
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001974 const GlobalVarDeclaration& global = element->as<GlobalVarDeclaration>();
1975 const VarDeclaration& decl = global.declaration()->as<VarDeclaration>();
1976 const Variable& var = decl.var();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001977 if ((!var.modifiers().fFlags && -1 == var.modifiers().fLayout.fBuiltin) ||
Brian Osmanc0213602020-10-06 14:43:32 -04001978 var.type().typeKind() == Type::TypeKind::kSampler) {
1979 if (var.type().typeKind() == Type::TypeKind::kSampler) {
1980 // Samplers are represented as a "texture/sampler" duo in the global struct.
John Stilesfdb8dbe2020-12-04 11:00:03 -05001981 visitor->visitTexture(var.type(), var.name());
1982 visitor->visitSampler(var.type(), String(var.name()) + SAMPLER_SUFFIX);
Brian Osmanc0213602020-10-06 14:43:32 -04001983 } else {
1984 // Visit a regular variable.
John Stilesfdb8dbe2020-12-04 11:00:03 -05001985 visitor->visitVariable(var, decl.value().get());
Timothy Liangee84fe12018-05-18 14:38:19 -04001986 }
1987 }
1988 }
John Stilescdcdb042020-07-06 09:03:51 -04001989}
1990
1991void MetalCodeGenerator::writeGlobalStruct() {
1992 class : public GlobalStructVisitor {
1993 public:
John Stilesfdb8dbe2020-12-04 11:00:03 -05001994 void visitInterfaceBlock(const InterfaceBlock& block, const String& blockName) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05001995 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04001996 fCodeGen->write(" constant ");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001997 fCodeGen->write(block.typeName());
John Stilescdcdb042020-07-06 09:03:51 -04001998 fCodeGen->write("* ");
1999 fCodeGen->writeName(blockName);
2000 fCodeGen->write(";\n");
2001 }
John Stilesfdb8dbe2020-12-04 11:00:03 -05002002 void visitTexture(const Type& type, const String& name) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002003 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002004 fCodeGen->write(" ");
John Stiles3dba3ee2020-12-02 23:35:49 -05002005 fCodeGen->writeBaseType(type);
John Stilescdcdb042020-07-06 09:03:51 -04002006 fCodeGen->write(" ");
2007 fCodeGen->writeName(name);
John Stiles3dba3ee2020-12-02 23:35:49 -05002008 fCodeGen->writeArrayDimensions(type);
John Stilescdcdb042020-07-06 09:03:51 -04002009 fCodeGen->write(";\n");
2010 }
John Stilesfdb8dbe2020-12-04 11:00:03 -05002011 void visitSampler(const Type&, const String& name) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002012 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002013 fCodeGen->write(" sampler ");
2014 fCodeGen->writeName(name);
2015 fCodeGen->write(";\n");
2016 }
John Stilesfdb8dbe2020-12-04 11:00:03 -05002017 void visitVariable(const Variable& var, const Expression* value) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002018 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002019 fCodeGen->write(" ");
John Stiles3dba3ee2020-12-02 23:35:49 -05002020 fCodeGen->writeBaseType(var.type());
John Stilescdcdb042020-07-06 09:03:51 -04002021 fCodeGen->write(" ");
Ethan Nicholase2c49992020-10-05 11:49:11 -04002022 fCodeGen->writeName(var.name());
John Stiles3dba3ee2020-12-02 23:35:49 -05002023 fCodeGen->writeArrayDimensions(var.type());
John Stilescdcdb042020-07-06 09:03:51 -04002024 fCodeGen->write(";\n");
2025 }
John Stiles83f3b8d2020-12-07 17:52:25 -05002026 void addElement() {
John Stilescdcdb042020-07-06 09:03:51 -04002027 if (fFirst) {
2028 fCodeGen->write("struct Globals {\n");
2029 fFirst = false;
2030 }
2031 }
John Stiles83f3b8d2020-12-07 17:52:25 -05002032 void finish() {
John Stilescdcdb042020-07-06 09:03:51 -04002033 if (!fFirst) {
John Stiles83f3b8d2020-12-07 17:52:25 -05002034 fCodeGen->writeLine("};");
John Stilescdcdb042020-07-06 09:03:51 -04002035 fFirst = true;
2036 }
2037 }
2038
2039 MetalCodeGenerator* fCodeGen = nullptr;
2040 bool fFirst = true;
2041 } visitor;
2042
2043 visitor.fCodeGen = this;
2044 this->visitGlobalStruct(&visitor);
John Stiles83f3b8d2020-12-07 17:52:25 -05002045 visitor.finish();
John Stilescdcdb042020-07-06 09:03:51 -04002046}
2047
2048void MetalCodeGenerator::writeGlobalInit() {
2049 class : public GlobalStructVisitor {
2050 public:
John Stilesfdb8dbe2020-12-04 11:00:03 -05002051 void visitInterfaceBlock(const InterfaceBlock& blockType,
John Stilescdcdb042020-07-06 09:03:51 -04002052 const String& blockName) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002053 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002054 fCodeGen->write("&");
2055 fCodeGen->writeName(blockName);
2056 }
John Stilesfdb8dbe2020-12-04 11:00:03 -05002057 void visitTexture(const Type&, const String& name) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002058 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002059 fCodeGen->writeName(name);
2060 }
John Stilesfdb8dbe2020-12-04 11:00:03 -05002061 void visitSampler(const Type&, const String& name) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002062 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002063 fCodeGen->writeName(name);
2064 }
John Stilesfdb8dbe2020-12-04 11:00:03 -05002065 void visitVariable(const Variable& var, const Expression* value) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002066 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002067 if (value) {
2068 fCodeGen->writeVarInitializer(var, *value);
2069 } else {
2070 fCodeGen->write("{}");
2071 }
2072 }
John Stiles83f3b8d2020-12-07 17:52:25 -05002073 void addElement() {
John Stilescdcdb042020-07-06 09:03:51 -04002074 if (fFirst) {
2075 fCodeGen->write(" Globals globalStruct{");
2076 fFirst = false;
2077 } else {
2078 fCodeGen->write(", ");
2079 }
2080 }
John Stiles83f3b8d2020-12-07 17:52:25 -05002081 void finish() {
John Stilescdcdb042020-07-06 09:03:51 -04002082 if (!fFirst) {
2083 fCodeGen->writeLine("};");
2084 fCodeGen->writeLine(" thread Globals* _globals = &globalStruct;");
2085 fCodeGen->writeLine(" (void)_globals;");
2086 }
2087 }
2088 MetalCodeGenerator* fCodeGen = nullptr;
2089 bool fFirst = true;
2090 } visitor;
2091
2092 visitor.fCodeGen = this;
2093 this->visitGlobalStruct(&visitor);
John Stiles83f3b8d2020-12-07 17:52:25 -05002094 visitor.finish();
Timothy Liangee84fe12018-05-18 14:38:19 -04002095}
2096
Ethan Nicholascc305772017-10-13 16:17:45 -04002097void MetalCodeGenerator::writeProgramElement(const ProgramElement& e) {
Ethan Nicholase6592142020-09-08 10:22:09 -04002098 switch (e.kind()) {
2099 case ProgramElement::Kind::kExtension:
Ethan Nicholascc305772017-10-13 16:17:45 -04002100 break;
Brian Osmanc0213602020-10-06 14:43:32 -04002101 case ProgramElement::Kind::kGlobalVar: {
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04002102 const GlobalVarDeclaration& global = e.as<GlobalVarDeclaration>();
2103 const VarDeclaration& decl = global.declaration()->as<VarDeclaration>();
2104 int builtin = decl.var().modifiers().fLayout.fBuiltin;
Brian Osmanc0213602020-10-06 14:43:32 -04002105 if (-1 == builtin) {
2106 // normal var
2107 this->writeVarDeclaration(decl, true);
2108 this->writeLine();
2109 } else if (SK_FRAGCOLOR_BUILTIN == builtin) {
2110 // ignore
Ethan Nicholascc305772017-10-13 16:17:45 -04002111 }
2112 break;
2113 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002114 case ProgramElement::Kind::kInterfaceBlock:
Timothy Liang7d637782018-06-05 09:58:07 -04002115 // handled in writeInterfaceBlocks, do nothing
Ethan Nicholascc305772017-10-13 16:17:45 -04002116 break;
John Stilesdc75a972020-11-25 16:24:55 -05002117 case ProgramElement::Kind::kStructDefinition:
2118 // Handled in writeStructDefinitions. Do nothing.
2119 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04002120 case ProgramElement::Kind::kFunction:
John Stiles3dc0da62020-08-19 17:48:31 -04002121 this->writeFunction(e.as<FunctionDefinition>());
Ethan Nicholascc305772017-10-13 16:17:45 -04002122 break;
John Stiles569249b2020-11-03 12:18:22 -05002123 case ProgramElement::Kind::kFunctionPrototype:
2124 this->writeFunctionPrototype(e.as<FunctionPrototype>());
2125 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04002126 case ProgramElement::Kind::kModifiers:
John Stiles06b84ef2020-12-09 12:35:48 -05002127 this->writeModifiers(e.as<ModifiersDeclaration>().modifiers(),
2128 /*globalContext=*/true);
Ethan Nicholascc305772017-10-13 16:17:45 -04002129 this->writeLine(";");
2130 break;
John Stiles712fd6b2020-11-25 22:25:43 -05002131 case ProgramElement::Kind::kEnum:
2132 break;
Ethan Nicholascc305772017-10-13 16:17:45 -04002133 default:
Ethan Nicholas2a099da2020-01-02 14:40:54 -05002134#ifdef SK_DEBUG
2135 ABORT("unsupported program element: %s\n", e.description().c_str());
2136#endif
2137 break;
Ethan Nicholascc305772017-10-13 16:17:45 -04002138 }
2139}
2140
Ethan Nicholasff350cb2020-05-14 14:05:13 -04002141MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const Expression* e) {
2142 if (!e) {
2143 return kNo_Requirements;
2144 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002145 switch (e->kind()) {
2146 case Expression::Kind::kFunctionCall: {
John Stiles3dc0da62020-08-19 17:48:31 -04002147 const FunctionCall& f = e->as<FunctionCall>();
Ethan Nicholas0dec9922020-10-05 15:51:52 -04002148 Requirements result = this->requirements(f.function());
2149 for (const auto& arg : f.arguments()) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04002150 result |= this->requirements(arg.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002151 }
2152 return result;
2153 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002154 case Expression::Kind::kConstructor: {
John Stiles3dc0da62020-08-19 17:48:31 -04002155 const Constructor& c = e->as<Constructor>();
Ethan Nicholascc305772017-10-13 16:17:45 -04002156 Requirements result = kNo_Requirements;
Ethan Nicholasf70f0442020-09-29 12:41:35 -04002157 for (const auto& arg : c.arguments()) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04002158 result |= this->requirements(arg.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002159 }
2160 return result;
2161 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002162 case Expression::Kind::kFieldAccess: {
John Stiles3dc0da62020-08-19 17:48:31 -04002163 const FieldAccess& f = e->as<FieldAccess>();
Ethan Nicholas7a95b202020-10-09 11:55:40 -04002164 if (FieldAccess::OwnerKind::kAnonymousInterfaceBlock == f.ownerKind()) {
Timothy Liang7d637782018-06-05 09:58:07 -04002165 return kGlobals_Requirement;
2166 }
Ethan Nicholas7a95b202020-10-09 11:55:40 -04002167 return this->requirements(f.base().get());
Timothy Liang7d637782018-06-05 09:58:07 -04002168 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002169 case Expression::Kind::kSwizzle:
Ethan Nicholas6b4d5812020-10-12 16:11:51 -04002170 return this->requirements(e->as<Swizzle>().base().get());
Ethan Nicholase6592142020-09-08 10:22:09 -04002171 case Expression::Kind::kBinary: {
2172 const BinaryExpression& bin = e->as<BinaryExpression>();
John Stiles2d4f9592020-10-30 10:29:12 -04002173 return this->requirements(bin.left().get()) |
2174 this->requirements(bin.right().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002175 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002176 case Expression::Kind::kIndex: {
John Stiles3dc0da62020-08-19 17:48:31 -04002177 const IndexExpression& idx = e->as<IndexExpression>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04002178 return this->requirements(idx.base().get()) | this->requirements(idx.index().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002179 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002180 case Expression::Kind::kPrefix:
Ethan Nicholas444ccc62020-10-09 10:16:22 -04002181 return this->requirements(e->as<PrefixExpression>().operand().get());
Ethan Nicholase6592142020-09-08 10:22:09 -04002182 case Expression::Kind::kPostfix:
Ethan Nicholas444ccc62020-10-09 10:16:22 -04002183 return this->requirements(e->as<PostfixExpression>().operand().get());
Ethan Nicholase6592142020-09-08 10:22:09 -04002184 case Expression::Kind::kTernary: {
John Stiles3dc0da62020-08-19 17:48:31 -04002185 const TernaryExpression& t = e->as<TernaryExpression>();
Ethan Nicholasdd218162020-10-08 05:48:01 -04002186 return this->requirements(t.test().get()) | this->requirements(t.ifTrue().get()) |
2187 this->requirements(t.ifFalse().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002188 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002189 case Expression::Kind::kVariableReference: {
John Stiles3dc0da62020-08-19 17:48:31 -04002190 const VariableReference& v = e->as<VariableReference>();
Ethan Nicholas78686922020-10-08 06:46:27 -04002191 const Modifiers& modifiers = v.variable()->modifiers();
Ethan Nicholascc305772017-10-13 16:17:45 -04002192 Requirements result = kNo_Requirements;
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002193 if (modifiers.fLayout.fBuiltin == SK_FRAGCOORD_BUILTIN) {
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -04002194 result = kGlobals_Requirement | kFragCoord_Requirement;
Ethan Nicholas453f67f2020-10-09 10:43:45 -04002195 } else if (Variable::Storage::kGlobal == v.variable()->storage()) {
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002196 if (modifiers.fFlags & Modifiers::kIn_Flag) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002197 result = kInputs_Requirement;
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002198 } else if (modifiers.fFlags & Modifiers::kOut_Flag) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002199 result = kOutputs_Requirement;
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002200 } else if (modifiers.fFlags & Modifiers::kUniform_Flag &&
Ethan Nicholas78686922020-10-08 06:46:27 -04002201 v.variable()->type().typeKind() != Type::TypeKind::kSampler) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002202 result = kUniforms_Requirement;
Timothy Liangee84fe12018-05-18 14:38:19 -04002203 } else {
2204 result = kGlobals_Requirement;
Ethan Nicholascc305772017-10-13 16:17:45 -04002205 }
2206 }
2207 return result;
2208 }
2209 default:
2210 return kNo_Requirements;
2211 }
2212}
2213
Ethan Nicholasff350cb2020-05-14 14:05:13 -04002214MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const Statement* s) {
2215 if (!s) {
2216 return kNo_Requirements;
2217 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002218 switch (s->kind()) {
2219 case Statement::Kind::kBlock: {
Ethan Nicholascc305772017-10-13 16:17:45 -04002220 Requirements result = kNo_Requirements;
Ethan Nicholas7bd60432020-09-25 14:31:59 -04002221 for (const std::unique_ptr<Statement>& child : s->as<Block>().children()) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04002222 result |= this->requirements(child.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002223 }
2224 return result;
2225 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002226 case Statement::Kind::kVarDeclaration: {
John Stiles3dc0da62020-08-19 17:48:31 -04002227 const VarDeclaration& var = s->as<VarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04002228 return this->requirements(var.value().get());
Timothy Liang7d637782018-06-05 09:58:07 -04002229 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002230 case Statement::Kind::kExpression:
Ethan Nicholasd503a5a2020-09-30 09:29:55 -04002231 return this->requirements(s->as<ExpressionStatement>().expression().get());
Ethan Nicholase6592142020-09-08 10:22:09 -04002232 case Statement::Kind::kReturn: {
John Stiles3dc0da62020-08-19 17:48:31 -04002233 const ReturnStatement& r = s->as<ReturnStatement>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04002234 return this->requirements(r.expression().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002235 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002236 case Statement::Kind::kIf: {
John Stiles3dc0da62020-08-19 17:48:31 -04002237 const IfStatement& i = s->as<IfStatement>();
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04002238 return this->requirements(i.test().get()) |
2239 this->requirements(i.ifTrue().get()) |
2240 this->requirements(i.ifFalse().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002241 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002242 case Statement::Kind::kFor: {
John Stiles3dc0da62020-08-19 17:48:31 -04002243 const ForStatement& f = s->as<ForStatement>();
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04002244 return this->requirements(f.initializer().get()) |
2245 this->requirements(f.test().get()) |
2246 this->requirements(f.next().get()) |
2247 this->requirements(f.statement().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002248 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002249 case Statement::Kind::kDo: {
John Stiles3dc0da62020-08-19 17:48:31 -04002250 const DoStatement& d = s->as<DoStatement>();
Ethan Nicholas1fd61162020-09-28 13:14:19 -04002251 return this->requirements(d.test().get()) |
2252 this->requirements(d.statement().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002253 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002254 case Statement::Kind::kSwitch: {
John Stiles3dc0da62020-08-19 17:48:31 -04002255 const SwitchStatement& sw = s->as<SwitchStatement>();
Ethan Nicholas01b05e52020-10-22 15:53:41 -04002256 Requirements result = this->requirements(sw.value().get());
John Stiles2d4f9592020-10-30 10:29:12 -04002257 for (const std::unique_ptr<SwitchCase>& sc : sw.cases()) {
2258 for (const auto& st : sc->statements()) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04002259 result |= this->requirements(st.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002260 }
2261 }
2262 return result;
2263 }
2264 default:
2265 return kNo_Requirements;
2266 }
2267}
2268
2269MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const FunctionDeclaration& f) {
Ethan Nicholased84b732020-10-08 11:45:44 -04002270 if (f.isBuiltin()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002271 return kNo_Requirements;
2272 }
2273 auto found = fRequirements.find(&f);
2274 if (found == fRequirements.end()) {
Ethan Nicholas65a8f562019-04-19 14:00:26 -04002275 fRequirements[&f] = kNo_Requirements;
Brian Osman133724c2020-10-28 14:14:39 -04002276 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04002277 if (e->is<FunctionDefinition>()) {
2278 const FunctionDefinition& def = e->as<FunctionDefinition>();
Ethan Nicholas0a5d0962020-10-14 13:33:18 -04002279 if (&def.declaration() == &f) {
2280 Requirements reqs = this->requirements(def.body().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002281 fRequirements[&f] = reqs;
2282 return reqs;
2283 }
2284 }
2285 }
John Stiles569249b2020-11-03 12:18:22 -05002286 // We never found a definition for this declared function, but it's legal to prototype a
2287 // function without ever giving a definition, as long as you don't call it.
2288 return kNo_Requirements;
Ethan Nicholascc305772017-10-13 16:17:45 -04002289 }
2290 return found->second;
2291}
2292
Timothy Liangb8eeb802018-07-23 16:46:16 -04002293bool MetalCodeGenerator::generateCode() {
Ethan Nicholascc305772017-10-13 16:17:45 -04002294 fProgramKind = fProgram.fKind;
Ethan Nicholascc305772017-10-13 16:17:45 -04002295
John Stiles44532372020-12-07 12:33:55 -05002296 StringStream header;
2297 {
2298 AutoOutputStream outputToHeader(this, &header, &fIndentation);
2299 this->writeHeader();
2300 this->writeStructDefinitions();
2301 this->writeUniformStruct();
2302 this->writeInputStruct();
2303 this->writeOutputStruct();
2304 this->writeInterfaceBlocks();
2305 this->writeGlobalStruct();
2306 }
2307 StringStream body;
2308 {
2309 AutoOutputStream outputToBody(this, &body, &fIndentation);
2310 for (const ProgramElement* e : fProgram.elements()) {
2311 this->writeProgramElement(*e);
2312 }
2313 }
2314 write_stringstream(header, *fOut);
2315 write_stringstream(fExtraFunctions, *fOut);
2316 write_stringstream(body, *fOut);
Brian Osman8609a242020-09-08 14:01:49 -04002317 return 0 == fErrors.errorCount();
Ethan Nicholascc305772017-10-13 16:17:45 -04002318}
2319
John Stilesa6841be2020-08-06 14:11:56 -04002320} // namespace SkSL