blob: 22f111c0144b0a1f0d0434a21c0053a2cce0b05e [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
Mike Kleinc0bd9f92019-04-23 12:05:21 -050010#include "src/sksl/SkSLCompiler.h"
11#include "src/sksl/ir/SkSLExpressionStatement.h"
12#include "src/sksl/ir/SkSLExtension.h"
13#include "src/sksl/ir/SkSLIndexExpression.h"
14#include "src/sksl/ir/SkSLModifiersDeclaration.h"
15#include "src/sksl/ir/SkSLNop.h"
16#include "src/sksl/ir/SkSLVariableReference.h"
Ethan Nicholascc305772017-10-13 16:17:45 -040017
Brian Osmanc262a122020-08-06 16:34:34 -040018#include <algorithm>
19
Ethan Nicholascc305772017-10-13 16:17:45 -040020namespace SkSL {
21
John Stilescdcdb042020-07-06 09:03:51 -040022class MetalCodeGenerator::GlobalStructVisitor {
23public:
24 virtual ~GlobalStructVisitor() = default;
25 virtual void VisitInterfaceBlock(const InterfaceBlock& block, const String& blockName) = 0;
26 virtual void VisitTexture(const Type& type, const String& name) = 0;
27 virtual void VisitSampler(const Type& type, const String& name) = 0;
28 virtual void VisitVariable(const Variable& var, const Expression* value) = 0;
29};
30
Timothy Liangee84fe12018-05-18 14:38:19 -040031void MetalCodeGenerator::setupIntrinsics() {
Timothy Liang7d637782018-06-05 09:58:07 -040032#define METAL(x) std::make_pair(kMetal_IntrinsicKind, k ## x ## _MetalIntrinsic)
33#define SPECIAL(x) std::make_pair(kSpecial_IntrinsicKind, k ## x ## _SpecialIntrinsic)
Ethan Nicholas13863662019-07-29 13:05:15 -040034 fIntrinsicMap[String("sample")] = SPECIAL(Texture);
Timothy Liang651286f2018-06-07 09:55:33 -040035 fIntrinsicMap[String("mod")] = SPECIAL(Mod);
Ethan Nicholas0dc80872019-02-08 15:46:24 -050036 fIntrinsicMap[String("equal")] = METAL(Equal);
37 fIntrinsicMap[String("notEqual")] = METAL(NotEqual);
Timothy Lianga06f2152018-05-24 15:33:31 -040038 fIntrinsicMap[String("lessThan")] = METAL(LessThan);
39 fIntrinsicMap[String("lessThanEqual")] = METAL(LessThanEqual);
40 fIntrinsicMap[String("greaterThan")] = METAL(GreaterThan);
41 fIntrinsicMap[String("greaterThanEqual")] = METAL(GreaterThanEqual);
Timothy Liangee84fe12018-05-18 14:38:19 -040042}
43
Ethan Nicholascc305772017-10-13 16:17:45 -040044void MetalCodeGenerator::write(const char* s) {
45 if (!s[0]) {
46 return;
47 }
48 if (fAtLineStart) {
49 for (int i = 0; i < fIndentation; i++) {
50 fOut->writeText(" ");
51 }
52 }
53 fOut->writeText(s);
54 fAtLineStart = false;
55}
56
57void MetalCodeGenerator::writeLine(const char* s) {
58 this->write(s);
59 fOut->writeText(fLineEnding);
60 fAtLineStart = true;
61}
62
63void MetalCodeGenerator::write(const String& s) {
64 this->write(s.c_str());
65}
66
67void MetalCodeGenerator::writeLine(const String& s) {
68 this->writeLine(s.c_str());
69}
70
71void MetalCodeGenerator::writeLine() {
72 this->writeLine("");
73}
74
75void MetalCodeGenerator::writeExtension(const Extension& ext) {
Ethan Nicholasefb09e22020-09-30 10:17:00 -040076 this->writeLine("#extension " + ext.name() + " : enable");
Ethan Nicholascc305772017-10-13 16:17:45 -040077}
78
Ethan Nicholas45fa8102020-01-13 10:58:49 -050079String MetalCodeGenerator::typeName(const Type& type) {
Ethan Nicholase6592142020-09-08 10:22:09 -040080 switch (type.typeKind()) {
81 case Type::TypeKind::kVector:
Ethan Nicholas45fa8102020-01-13 10:58:49 -050082 return this->typeName(type.componentType()) + to_string(type.columns());
Ethan Nicholase6592142020-09-08 10:22:09 -040083 case Type::TypeKind::kMatrix:
Ethan Nicholas45fa8102020-01-13 10:58:49 -050084 return this->typeName(type.componentType()) + to_string(type.columns()) + "x" +
85 to_string(type.rows());
Ethan Nicholase6592142020-09-08 10:22:09 -040086 case Type::TypeKind::kSampler:
Ethan Nicholas45fa8102020-01-13 10:58:49 -050087 return "texture2d<float>"; // FIXME - support other texture types;
Ethan Nicholascc305772017-10-13 16:17:45 -040088 default:
Timothy Liang43d225f2018-07-19 15:27:13 -040089 if (type == *fContext.fHalf_Type) {
90 // FIXME - Currently only supporting floats in MSL to avoid type coercion issues.
Ethan Nicholas45fa8102020-01-13 10:58:49 -050091 return fContext.fFloat_Type->name();
Timothy Liang43d225f2018-07-19 15:27:13 -040092 } else if (type == *fContext.fByte_Type) {
Ethan Nicholas45fa8102020-01-13 10:58:49 -050093 return "char";
Timothy Liang43d225f2018-07-19 15:27:13 -040094 } else if (type == *fContext.fUByte_Type) {
Ethan Nicholas45fa8102020-01-13 10:58:49 -050095 return "uchar";
Timothy Liang7d637782018-06-05 09:58:07 -040096 } else {
Ethan Nicholas45fa8102020-01-13 10:58:49 -050097 return type.name();
Timothy Liang7d637782018-06-05 09:58:07 -040098 }
Ethan Nicholascc305772017-10-13 16:17:45 -040099 }
100}
101
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500102void MetalCodeGenerator::writeType(const Type& type) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400103 if (type.typeKind() == Type::TypeKind::kStruct) {
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500104 for (const Type* search : fWrittenStructs) {
105 if (*search == type) {
106 // already written
107 this->write(type.name());
108 return;
109 }
110 }
111 fWrittenStructs.push_back(&type);
112 this->writeLine("struct " + type.name() + " {");
113 fIndentation++;
114 this->writeFields(type.fields(), type.fOffset);
115 fIndentation--;
116 this->write("}");
117 } else {
118 this->write(this->typeName(type));
119 }
120}
121
Ethan Nicholascc305772017-10-13 16:17:45 -0400122void MetalCodeGenerator::writeExpression(const Expression& expr, Precedence parentPrecedence) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400123 switch (expr.kind()) {
124 case Expression::Kind::kBinary:
John Stiles81365af2020-08-18 09:24:00 -0400125 this->writeBinaryExpression(expr.as<BinaryExpression>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400126 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400127 case Expression::Kind::kBoolLiteral:
John Stiles81365af2020-08-18 09:24:00 -0400128 this->writeBoolLiteral(expr.as<BoolLiteral>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400129 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400130 case Expression::Kind::kConstructor:
John Stiles81365af2020-08-18 09:24:00 -0400131 this->writeConstructor(expr.as<Constructor>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400132 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400133 case Expression::Kind::kIntLiteral:
John Stiles81365af2020-08-18 09:24:00 -0400134 this->writeIntLiteral(expr.as<IntLiteral>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400135 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400136 case Expression::Kind::kFieldAccess:
John Stiles81365af2020-08-18 09:24:00 -0400137 this->writeFieldAccess(expr.as<FieldAccess>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400138 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400139 case Expression::Kind::kFloatLiteral:
John Stiles81365af2020-08-18 09:24:00 -0400140 this->writeFloatLiteral(expr.as<FloatLiteral>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400141 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400142 case Expression::Kind::kFunctionCall:
John Stiles81365af2020-08-18 09:24:00 -0400143 this->writeFunctionCall(expr.as<FunctionCall>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400144 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400145 case Expression::Kind::kPrefix:
John Stiles81365af2020-08-18 09:24:00 -0400146 this->writePrefixExpression(expr.as<PrefixExpression>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400147 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400148 case Expression::Kind::kPostfix:
John Stiles81365af2020-08-18 09:24:00 -0400149 this->writePostfixExpression(expr.as<PostfixExpression>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400150 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400151 case Expression::Kind::kSetting:
John Stiles81365af2020-08-18 09:24:00 -0400152 this->writeSetting(expr.as<Setting>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400153 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400154 case Expression::Kind::kSwizzle:
John Stiles81365af2020-08-18 09:24:00 -0400155 this->writeSwizzle(expr.as<Swizzle>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400156 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400157 case Expression::Kind::kVariableReference:
John Stiles81365af2020-08-18 09:24:00 -0400158 this->writeVariableReference(expr.as<VariableReference>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400159 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400160 case Expression::Kind::kTernary:
John Stiles81365af2020-08-18 09:24:00 -0400161 this->writeTernaryExpression(expr.as<TernaryExpression>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400162 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400163 case Expression::Kind::kIndex:
John Stiles81365af2020-08-18 09:24:00 -0400164 this->writeIndexExpression(expr.as<IndexExpression>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400165 break;
166 default:
Ethan Nicholas2a099da2020-01-02 14:40:54 -0500167#ifdef SK_DEBUG
Ethan Nicholascc305772017-10-13 16:17:45 -0400168 ABORT("unsupported expression: %s", expr.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -0500169#endif
170 break;
Ethan Nicholascc305772017-10-13 16:17:45 -0400171 }
172}
173
Timothy Liang6403b0e2018-05-17 10:40:04 -0400174void MetalCodeGenerator::writeIntrinsicCall(const FunctionCall& c) {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400175 auto i = fIntrinsicMap.find(c.function().name());
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400176 SkASSERT(i != fIntrinsicMap.end());
Timothy Liang7d637782018-06-05 09:58:07 -0400177 Intrinsic intrinsic = i->second;
178 int32_t intrinsicId = intrinsic.second;
179 switch (intrinsic.first) {
Timothy Liang6403b0e2018-05-17 10:40:04 -0400180 case kSpecial_IntrinsicKind:
181 return this->writeSpecialIntrinsic(c, (SpecialIntrinsic) intrinsicId);
Timothy Lianga06f2152018-05-24 15:33:31 -0400182 break;
183 case kMetal_IntrinsicKind:
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400184 this->writeExpression(*c.arguments()[0], kSequence_Precedence);
Timothy Lianga06f2152018-05-24 15:33:31 -0400185 switch ((MetalIntrinsic) intrinsicId) {
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500186 case kEqual_MetalIntrinsic:
187 this->write(" == ");
188 break;
189 case kNotEqual_MetalIntrinsic:
190 this->write(" != ");
191 break;
Timothy Lianga06f2152018-05-24 15:33:31 -0400192 case kLessThan_MetalIntrinsic:
193 this->write(" < ");
194 break;
195 case kLessThanEqual_MetalIntrinsic:
196 this->write(" <= ");
197 break;
198 case kGreaterThan_MetalIntrinsic:
199 this->write(" > ");
200 break;
201 case kGreaterThanEqual_MetalIntrinsic:
202 this->write(" >= ");
203 break;
204 default:
205 ABORT("unsupported metal intrinsic kind");
206 }
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400207 this->writeExpression(*c.arguments()[1], kSequence_Precedence);
Timothy Lianga06f2152018-05-24 15:33:31 -0400208 break;
Timothy Liang6403b0e2018-05-17 10:40:04 -0400209 default:
210 ABORT("unsupported intrinsic kind");
211 }
212}
213
Ethan Nicholascc305772017-10-13 16:17:45 -0400214void MetalCodeGenerator::writeFunctionCall(const FunctionCall& c) {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400215 const FunctionDeclaration& function = c.function();
John Stiles8e3b6be2020-10-13 11:14:08 -0400216 const ExpressionArray& arguments = c.arguments();
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400217 const auto& entry = fIntrinsicMap.find(function.name());
Timothy Liang6403b0e2018-05-17 10:40:04 -0400218 if (entry != fIntrinsicMap.end()) {
219 this->writeIntrinsicCall(c);
220 return;
221 }
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400222 const StringFragment& name = function.name();
Ethan Nicholased84b732020-10-08 11:45:44 -0400223 bool builtin = function.isBuiltin();
224 if (builtin && name == "atan" && arguments.size() == 2) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400225 this->write("atan2");
Ethan Nicholased84b732020-10-08 11:45:44 -0400226 } else if (builtin && name == "inversesqrt") {
Timothy Lianga06f2152018-05-24 15:33:31 -0400227 this->write("rsqrt");
Ethan Nicholased84b732020-10-08 11:45:44 -0400228 } else if (builtin && name == "inverse") {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400229 SkASSERT(arguments.size() == 1);
230 this->writeInverseHack(*arguments[0]);
John Stilesa80a3dc2020-10-20 10:24:56 -0400231 } else if (builtin && name == "frexp") {
232 // Our Metal codegen assumes that out params are pointers, but Metal's built-in frexp
233 // actually takes a reference for the exponent, not a pointer. We add in a helper function
234 // here to translate.
235 SkASSERT(arguments.size() == 2);
236 auto [iter, newlyCreated] = fHelpers.insert("frexp");
237 if (newlyCreated) {
238 fExtraFunctions.printf(
239 "float frexp(float arg, thread int* exp) { return frexp(arg, *exp); }\n");
240 }
241 this->write("frexp");
Ethan Nicholased84b732020-10-08 11:45:44 -0400242 } else if (builtin && name == "dFdx") {
Timothy Liang7d637782018-06-05 09:58:07 -0400243 this->write("dfdx");
Ethan Nicholased84b732020-10-08 11:45:44 -0400244 } else if (builtin && name == "dFdy") {
Chris Daltonb8af5ad2019-02-25 14:54:21 -0700245 // Flipping Y also negates the Y derivatives.
246 this->write((fProgram.fSettings.fFlipY) ? "-dfdy" : "dfdy");
Ethan Nicholascc305772017-10-13 16:17:45 -0400247 } else {
Ethan Nicholase2c49992020-10-05 11:49:11 -0400248 this->writeName(name);
Ethan Nicholascc305772017-10-13 16:17:45 -0400249 }
250 this->write("(");
251 const char* separator = "";
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400252 if (this->requirements(function) & kInputs_Requirement) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400253 this->write("_in");
254 separator = ", ";
255 }
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400256 if (this->requirements(function) & kOutputs_Requirement) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400257 this->write(separator);
258 this->write("_out");
259 separator = ", ";
260 }
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400261 if (this->requirements(function) & kUniforms_Requirement) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400262 this->write(separator);
263 this->write("_uniforms");
264 separator = ", ";
265 }
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400266 if (this->requirements(function) & kGlobals_Requirement) {
Timothy Liangee84fe12018-05-18 14:38:19 -0400267 this->write(separator);
268 this->write("_globals");
269 separator = ", ";
270 }
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400271 if (this->requirements(function) & kFragCoord_Requirement) {
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -0400272 this->write(separator);
273 this->write("_fragCoord");
274 separator = ", ";
275 }
Brian Osman5bf3e202020-10-13 10:34:18 -0400276 const std::vector<const Variable*>& parameters = function.parameters();
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400277 for (size_t i = 0; i < arguments.size(); ++i) {
278 const Expression& arg = *arguments[i];
Ethan Nicholascc305772017-10-13 16:17:45 -0400279 this->write(separator);
280 separator = ", ";
Ethan Nicholased84b732020-10-08 11:45:44 -0400281 if (parameters[i]->modifiers().fFlags & Modifiers::kOut_Flag) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400282 this->write("&");
283 }
284 this->writeExpression(arg, kSequence_Precedence);
285 }
286 this->write(")");
287}
288
Chris Daltondba7aab2018-11-15 10:57:49 -0500289void MetalCodeGenerator::writeInverseHack(const Expression& mat) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400290 const Type& type = mat.type();
291 const String& typeName = type.name();
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500292 String name = typeName + "_inverse";
Ethan Nicholas30d30222020-09-11 12:27:26 -0400293 if (type == *fContext.fFloat2x2_Type || type == *fContext.fHalf2x2_Type) {
Chris Daltondba7aab2018-11-15 10:57:49 -0500294 if (fWrittenIntrinsics.find(name) == fWrittenIntrinsics.end()) {
295 fWrittenIntrinsics.insert(name);
296 fExtraFunctions.writeText((
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500297 typeName + " " + name + "(" + typeName + " m) {"
Chris Daltondba7aab2018-11-15 10:57:49 -0500298 " return float2x2(m[1][1], -m[0][1], -m[1][0], m[0][0]) * (1/determinant(m));"
299 "}"
300 ).c_str());
301 }
302 }
Ethan Nicholas30d30222020-09-11 12:27:26 -0400303 else if (type == *fContext.fFloat3x3_Type || type == *fContext.fHalf3x3_Type) {
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500304 if (fWrittenIntrinsics.find(name) == fWrittenIntrinsics.end()) {
305 fWrittenIntrinsics.insert(name);
306 fExtraFunctions.writeText((
307 typeName + " " + name + "(" + typeName + " m) {"
308 " float a00 = m[0][0], a01 = m[0][1], a02 = m[0][2];"
309 " float a10 = m[1][0], a11 = m[1][1], a12 = m[1][2];"
310 " float a20 = m[2][0], a21 = m[2][1], a22 = m[2][2];"
311 " float b01 = a22 * a11 - a12 * a21;"
312 " float b11 = -a22 * a10 + a12 * a20;"
313 " float b21 = a21 * a10 - a11 * a20;"
314 " float det = a00 * b01 + a01 * b11 + a02 * b21;"
315 " return " + typeName +
316 " (b01, (-a22 * a01 + a02 * a21), (a12 * a01 - a02 * a11),"
317 " b11, (a22 * a00 - a02 * a20), (-a12 * a00 + a02 * a10),"
318 " b21, (-a21 * a00 + a01 * a20), (a11 * a00 - a01 * a10)) * "
319 " (1/det);"
320 "}"
321 ).c_str());
322 }
323 }
Ethan Nicholas30d30222020-09-11 12:27:26 -0400324 else if (type == *fContext.fFloat4x4_Type || type == *fContext.fHalf4x4_Type) {
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500325 if (fWrittenIntrinsics.find(name) == fWrittenIntrinsics.end()) {
326 fWrittenIntrinsics.insert(name);
327 fExtraFunctions.writeText((
328 typeName + " " + name + "(" + typeName + " m) {"
329 " float a00 = m[0][0], a01 = m[0][1], a02 = m[0][2], a03 = m[0][3];"
330 " float a10 = m[1][0], a11 = m[1][1], a12 = m[1][2], a13 = m[1][3];"
331 " float a20 = m[2][0], a21 = m[2][1], a22 = m[2][2], a23 = m[2][3];"
332 " float a30 = m[3][0], a31 = m[3][1], a32 = m[3][2], a33 = m[3][3];"
333 " float b00 = a00 * a11 - a01 * a10;"
334 " float b01 = a00 * a12 - a02 * a10;"
335 " float b02 = a00 * a13 - a03 * a10;"
336 " float b03 = a01 * a12 - a02 * a11;"
337 " float b04 = a01 * a13 - a03 * a11;"
338 " float b05 = a02 * a13 - a03 * a12;"
339 " float b06 = a20 * a31 - a21 * a30;"
340 " float b07 = a20 * a32 - a22 * a30;"
341 " float b08 = a20 * a33 - a23 * a30;"
342 " float b09 = a21 * a32 - a22 * a31;"
343 " float b10 = a21 * a33 - a23 * a31;"
344 " float b11 = a22 * a33 - a23 * a32;"
345 " float det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - "
346 " b04 * b07 + b05 * b06;"
347 " return " + typeName + "(a11 * b11 - a12 * b10 + a13 * b09,"
348 " a02 * b10 - a01 * b11 - a03 * b09,"
349 " a31 * b05 - a32 * b04 + a33 * b03,"
350 " a22 * b04 - a21 * b05 - a23 * b03,"
351 " a12 * b08 - a10 * b11 - a13 * b07,"
352 " a00 * b11 - a02 * b08 + a03 * b07,"
353 " a32 * b02 - a30 * b05 - a33 * b01,"
354 " a20 * b05 - a22 * b02 + a23 * b01,"
355 " a10 * b10 - a11 * b08 + a13 * b06,"
356 " a01 * b08 - a00 * b10 - a03 * b06,"
357 " a30 * b04 - a31 * b02 + a33 * b00,"
358 " a21 * b02 - a20 * b04 - a23 * b00,"
359 " a11 * b07 - a10 * b09 - a12 * b06,"
360 " a00 * b09 - a01 * b07 + a02 * b06,"
361 " a31 * b01 - a30 * b03 - a32 * b00,"
362 " a20 * b03 - a21 * b01 + a22 * b00) / det;"
363 "}"
364 ).c_str());
365 }
366 }
Chris Daltondba7aab2018-11-15 10:57:49 -0500367 this->write(name);
368}
369
Timothy Liang6403b0e2018-05-17 10:40:04 -0400370void MetalCodeGenerator::writeSpecialIntrinsic(const FunctionCall & c, SpecialIntrinsic kind) {
John Stiles8e3b6be2020-10-13 11:14:08 -0400371 const ExpressionArray& arguments = c.arguments();
Timothy Liang6403b0e2018-05-17 10:40:04 -0400372 switch (kind) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400373 case kTexture_SpecialIntrinsic: {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400374 this->writeExpression(*arguments[0], kSequence_Precedence);
Timothy Lianga06f2152018-05-24 15:33:31 -0400375 this->write(".sample(");
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400376 this->writeExpression(*arguments[0], kSequence_Precedence);
Timothy Lianga06f2152018-05-24 15:33:31 -0400377 this->write(SAMPLER_SUFFIX);
378 this->write(", ");
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400379 const Type& arg1Type = arguments[1]->type();
Ethan Nicholas30d30222020-09-11 12:27:26 -0400380 if (arg1Type == *fContext.fFloat3_Type) {
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500381 // have to store the vector in a temp variable to avoid double evaluating it
382 String tmpVar = "tmpCoord" + to_string(fVarCount++);
Ethan Nicholas30d30222020-09-11 12:27:26 -0400383 this->fFunctionHeader += " " + this->typeName(arg1Type) + " " + tmpVar + ";\n";
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500384 this->write("(" + tmpVar + " = ");
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400385 this->writeExpression(*arguments[1], kSequence_Precedence);
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500386 this->write(", " + tmpVar + ".xy / " + tmpVar + ".z))");
Timothy Liangee84fe12018-05-18 14:38:19 -0400387 } else {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400388 SkASSERT(arg1Type == *fContext.fFloat2_Type);
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400389 this->writeExpression(*arguments[1], kSequence_Precedence);
Timothy Liangee84fe12018-05-18 14:38:19 -0400390 this->write(")");
391 }
Timothy Liang6403b0e2018-05-17 10:40:04 -0400392 break;
Ethan Nicholas30d30222020-09-11 12:27:26 -0400393 }
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500394 case kMod_SpecialIntrinsic: {
Timothy Liang651286f2018-06-07 09:55:33 -0400395 // fmod(x, y) in metal calculates x - y * trunc(x / y) instead of x - y * floor(x / y)
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500396 String tmpX = "tmpX" + to_string(fVarCount++);
397 String tmpY = "tmpY" + to_string(fVarCount++);
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400398 this->fFunctionHeader += " " + this->typeName(arguments[0]->type()) +
Ethan Nicholas30d30222020-09-11 12:27:26 -0400399 " " + tmpX + ", " + tmpY + ";\n";
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500400 this->write("(" + tmpX + " = ");
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400401 this->writeExpression(*arguments[0], kSequence_Precedence);
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500402 this->write(", " + tmpY + " = ");
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400403 this->writeExpression(*arguments[1], kSequence_Precedence);
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500404 this->write(", " + tmpX + " - " + tmpY + " * floor(" + tmpX + " / " + tmpY + "))");
Timothy Liang651286f2018-06-07 09:55:33 -0400405 break;
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500406 }
Timothy Liang6403b0e2018-05-17 10:40:04 -0400407 default:
408 ABORT("unsupported special intrinsic kind");
409 }
410}
411
John Stilesfcf8cb22020-08-06 14:29:22 -0400412// Assembles a matrix of type floatRxC by resizing another matrix named `x0`.
413// Cells that don't exist in the source matrix will be populated with identity-matrix values.
414void MetalCodeGenerator::assembleMatrixFromMatrix(const Type& sourceMatrix, int rows, int columns) {
415 SkASSERT(rows <= 4);
416 SkASSERT(columns <= 4);
417
418 const char* columnSeparator = "";
419 for (int c = 0; c < columns; ++c) {
420 fExtraFunctions.printf("%sfloat%d(", columnSeparator, rows);
421 columnSeparator = "), ";
422
423 // Determine how many values to take from the source matrix for this row.
424 int swizzleLength = 0;
425 if (c < sourceMatrix.columns()) {
426 swizzleLength = std::min<>(rows, sourceMatrix.rows());
427 }
428
429 // Emit all the values from the source matrix row.
430 bool firstItem;
431 switch (swizzleLength) {
432 case 0: firstItem = true; break;
433 case 1: firstItem = false; fExtraFunctions.printf("x0[%d].x", c); break;
434 case 2: firstItem = false; fExtraFunctions.printf("x0[%d].xy", c); break;
435 case 3: firstItem = false; fExtraFunctions.printf("x0[%d].xyz", c); break;
436 case 4: firstItem = false; fExtraFunctions.printf("x0[%d].xyzw", c); break;
437 default: SkUNREACHABLE;
438 }
439
440 // Emit the placeholder identity-matrix cells.
441 for (int r = swizzleLength; r < rows; ++r) {
442 fExtraFunctions.printf("%s%s", firstItem ? "" : ", ", (r == c) ? "1.0" : "0.0");
443 firstItem = false;
444 }
445 }
446
447 fExtraFunctions.writeText(")");
448}
449
450// Assembles a matrix of type floatRxC by concatenating an arbitrary mix of values, named `x0`,
451// `x1`, etc. An error is written if the expression list don't contain exactly R*C scalars.
John Stiles8e3b6be2020-10-13 11:14:08 -0400452void MetalCodeGenerator::assembleMatrixFromExpressions(const ExpressionArray& args,
453 int rows, int columns) {
John Stilesfcf8cb22020-08-06 14:29:22 -0400454 size_t argIndex = 0;
455 int argPosition = 0;
456
457 const char* columnSeparator = "";
458 for (int c = 0; c < columns; ++c) {
459 fExtraFunctions.printf("%sfloat%d(", columnSeparator, rows);
460 columnSeparator = "), ";
461
462 const char* rowSeparator = "";
463 for (int r = 0; r < rows; ++r) {
464 fExtraFunctions.writeText(rowSeparator);
465 rowSeparator = ", ";
466
467 if (argIndex < args.size()) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400468 const Type& argType = args[argIndex]->type();
Ethan Nicholase6592142020-09-08 10:22:09 -0400469 switch (argType.typeKind()) {
470 case Type::TypeKind::kScalar: {
John Stilesfcf8cb22020-08-06 14:29:22 -0400471 fExtraFunctions.printf("x%zu", argIndex);
472 break;
473 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400474 case Type::TypeKind::kVector: {
John Stilesfcf8cb22020-08-06 14:29:22 -0400475 fExtraFunctions.printf("x%zu[%d]", argIndex, argPosition);
476 break;
477 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400478 case Type::TypeKind::kMatrix: {
John Stilesfcf8cb22020-08-06 14:29:22 -0400479 fExtraFunctions.printf("x%zu[%d][%d]", argIndex,
480 argPosition / argType.rows(),
481 argPosition % argType.rows());
482 break;
483 }
484 default: {
485 SkDEBUGFAIL("incorrect type of argument for matrix constructor");
486 fExtraFunctions.writeText("<error>");
487 break;
488 }
489 }
490
491 ++argPosition;
492 if (argPosition >= argType.columns() * argType.rows()) {
493 ++argIndex;
494 argPosition = 0;
495 }
496 } else {
497 SkDEBUGFAIL("not enough arguments for matrix constructor");
498 fExtraFunctions.writeText("<error>");
499 }
500 }
501 }
502
503 if (argPosition != 0 || argIndex != args.size()) {
504 SkDEBUGFAIL("incorrect number of arguments for matrix constructor");
505 fExtraFunctions.writeText(", <error>");
506 }
507
508 fExtraFunctions.writeText(")");
509}
510
John Stiles1bdafbf2020-05-28 12:17:20 -0400511// Generates a constructor for 'matrix' which reorganizes the input arguments into the proper shape.
512// Keeps track of previously generated constructors so that we won't generate more than one
513// constructor for any given permutation of input argument types. Returns the name of the
514// generated constructor method.
515String MetalCodeGenerator::getMatrixConstructHelper(const Constructor& c) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400516 const Type& matrix = c.type();
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500517 int columns = matrix.columns();
518 int rows = matrix.rows();
John Stiles8e3b6be2020-10-13 11:14:08 -0400519 const ExpressionArray& args = c.arguments();
John Stiles1bdafbf2020-05-28 12:17:20 -0400520
521 // Create the helper-method name and use it as our lookup key.
522 String name;
523 name.appendf("float%dx%d_from", columns, rows);
524 for (const std::unique_ptr<Expression>& expr : args) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400525 name.appendf("_%s", expr->type().displayName().c_str());
John Stiles1bdafbf2020-05-28 12:17:20 -0400526 }
527
528 // If a helper-method has already been synthesized, we don't need to synthesize it again.
529 auto [iter, newlyCreated] = fHelpers.insert(name);
530 if (!newlyCreated) {
531 return name;
532 }
533
534 // Unlike GLSL, Metal requires that matrices are initialized with exactly R vectors of C
535 // components apiece. (In Metal 2.0, you can also supply R*C scalars, but you still cannot
536 // supply a mixture of scalars and vectors.)
537 fExtraFunctions.printf("float%dx%d %s(", columns, rows, name.c_str());
538
539 size_t argIndex = 0;
540 const char* argSeparator = "";
John Stilesfcf8cb22020-08-06 14:29:22 -0400541 for (const std::unique_ptr<Expression>& expr : args) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400542 fExtraFunctions.printf("%s%s x%zu", argSeparator,
Ethan Nicholas30d30222020-09-11 12:27:26 -0400543 expr->type().displayName().c_str(), argIndex++);
John Stiles1bdafbf2020-05-28 12:17:20 -0400544 argSeparator = ", ";
545 }
546
547 fExtraFunctions.printf(") {\n return float%dx%d(", columns, rows);
548
Ethan Nicholas30d30222020-09-11 12:27:26 -0400549 if (args.size() == 1 && args.front()->type().typeKind() == Type::TypeKind::kMatrix) {
550 this->assembleMatrixFromMatrix(args.front()->type(), rows, columns);
John Stilesfcf8cb22020-08-06 14:29:22 -0400551 } else {
552 this->assembleMatrixFromExpressions(args, rows, columns);
John Stiles1bdafbf2020-05-28 12:17:20 -0400553 }
554
John Stilesfcf8cb22020-08-06 14:29:22 -0400555 fExtraFunctions.writeText(");\n}\n");
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500556 return name;
557}
558
559bool MetalCodeGenerator::canCoerce(const Type& t1, const Type& t2) {
560 if (t1.columns() != t2.columns() || t1.rows() != t2.rows()) {
561 return false;
562 }
563 if (t1.columns() > 1) {
564 return this->canCoerce(t1.componentType(), t2.componentType());
565 }
Ethan Nicholase1f55022019-02-05 17:17:40 -0500566 return t1.isFloat() && t2.isFloat();
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500567}
568
John Stiles1bdafbf2020-05-28 12:17:20 -0400569bool MetalCodeGenerator::matrixConstructHelperIsNeeded(const Constructor& c) {
570 // A matrix construct helper is only necessary if we are, in fact, constructing a matrix.
Ethan Nicholas30d30222020-09-11 12:27:26 -0400571 if (c.type().typeKind() != Type::TypeKind::kMatrix) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400572 return false;
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500573 }
John Stiles1bdafbf2020-05-28 12:17:20 -0400574
575 // GLSL is fairly free-form about inputs to its matrix constructors, but Metal is not; it
576 // expects exactly R vectors of C components apiece. (Metal 2.0 also allows a list of R*C
577 // scalars.) Some cases are simple to translate and so we handle those inline--e.g. a list of
578 // scalars can be constructed trivially. In more complex cases, we generate a helper function
579 // that converts our inputs into a properly-shaped matrix.
580 // A matrix construct helper method is always used if any input argument is a matrix.
581 // Helper methods are also necessary when any argument would span multiple rows. For instance:
582 //
583 // float2 x = (1, 2);
584 // float3x2(x, 3, 4, 5, 6) = | 1 3 5 | = no helper needed; conversion can be done inline
585 // | 2 4 6 |
586 //
587 // float2 x = (2, 3);
588 // float3x2(1, x, 4, 5, 6) = | 1 3 5 | = x spans multiple rows; a helper method will be used
589 // | 2 4 6 |
590 //
591 // float4 x = (1, 2, 3, 4);
592 // float2x2(x) = | 1 3 | = x spans multiple rows; a helper method will be used
593 // | 2 4 |
594 //
595
596 int position = 0;
Ethan Nicholasf70f0442020-09-29 12:41:35 -0400597 for (const std::unique_ptr<Expression>& expr : c.arguments()) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400598 // If an input argument is a matrix, we need a helper function.
Ethan Nicholas30d30222020-09-11 12:27:26 -0400599 if (expr->type().typeKind() == Type::TypeKind::kMatrix) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400600 return true;
601 }
Ethan Nicholas30d30222020-09-11 12:27:26 -0400602 position += expr->type().columns();
603 if (position > c.type().rows()) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400604 // An input argument would span multiple rows; a helper function is required.
605 return true;
606 }
Ethan Nicholas30d30222020-09-11 12:27:26 -0400607 if (position == c.type().rows()) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400608 // We've advanced to the end of a row. Wrap to the start of the next row.
609 position = 0;
610 }
611 }
612
613 return false;
614}
615
616void MetalCodeGenerator::writeConstructor(const Constructor& c, Precedence parentPrecedence) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400617 const Type& constructorType = c.type();
John Stiles1bdafbf2020-05-28 12:17:20 -0400618 // Handle special cases for single-argument constructors.
Ethan Nicholasf70f0442020-09-29 12:41:35 -0400619 if (c.arguments().size() == 1) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400620 // If the type is coercible, emit it directly.
Ethan Nicholasf70f0442020-09-29 12:41:35 -0400621 const Expression& arg = *c.arguments().front();
Ethan Nicholas30d30222020-09-11 12:27:26 -0400622 const Type& argType = arg.type();
623 if (this->canCoerce(constructorType, argType)) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400624 this->writeExpression(arg, parentPrecedence);
625 return;
626 }
627
628 // Metal supports creating matrices with a scalar on the diagonal via the single-argument
629 // matrix constructor.
Ethan Nicholas30d30222020-09-11 12:27:26 -0400630 if (constructorType.typeKind() == Type::TypeKind::kMatrix && argType.isNumber()) {
631 const Type& matrix = constructorType;
John Stiles1bdafbf2020-05-28 12:17:20 -0400632 this->write("float");
633 this->write(to_string(matrix.columns()));
634 this->write("x");
635 this->write(to_string(matrix.rows()));
636 this->write("(");
637 this->writeExpression(arg, parentPrecedence);
638 this->write(")");
639 return;
640 }
641 }
642
643 // Emit and invoke a matrix-constructor helper method if one is necessary.
644 if (this->matrixConstructHelperIsNeeded(c)) {
645 this->write(this->getMatrixConstructHelper(c));
John Stiles1fa15b12020-05-28 17:36:54 +0000646 this->write("(");
647 const char* separator = "";
Ethan Nicholasf70f0442020-09-29 12:41:35 -0400648 for (const std::unique_ptr<Expression>& expr : c.arguments()) {
John Stiles1fa15b12020-05-28 17:36:54 +0000649 this->write(separator);
650 separator = ", ";
John Stiles1bdafbf2020-05-28 12:17:20 -0400651 this->writeExpression(*expr, kSequence_Precedence);
John Stilesdaa573e2020-05-28 12:17:20 -0400652 }
John Stiles1fa15b12020-05-28 17:36:54 +0000653 this->write(")");
John Stiles1bdafbf2020-05-28 12:17:20 -0400654 return;
John Stilesdaa573e2020-05-28 12:17:20 -0400655 }
John Stiles1bdafbf2020-05-28 12:17:20 -0400656
657 // Explicitly invoke the constructor, passing in the necessary arguments.
Ethan Nicholas30d30222020-09-11 12:27:26 -0400658 this->writeType(constructorType);
John Stiles1bdafbf2020-05-28 12:17:20 -0400659 this->write("(");
660 const char* separator = "";
661 int scalarCount = 0;
Ethan Nicholasf70f0442020-09-29 12:41:35 -0400662 for (const std::unique_ptr<Expression>& arg : c.arguments()) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400663 const Type& argType = arg->type();
John Stiles1bdafbf2020-05-28 12:17:20 -0400664 this->write(separator);
665 separator = ", ";
Ethan Nicholas30d30222020-09-11 12:27:26 -0400666 if (constructorType.typeKind() == Type::TypeKind::kMatrix &&
667 argType.columns() < constructorType.rows()) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400668 // Merge scalars and smaller vectors together.
669 if (!scalarCount) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400670 this->writeType(constructorType.componentType());
671 this->write(to_string(constructorType.rows()));
John Stiles1bdafbf2020-05-28 12:17:20 -0400672 this->write("(");
673 }
Ethan Nicholas30d30222020-09-11 12:27:26 -0400674 scalarCount += argType.columns();
John Stiles1bdafbf2020-05-28 12:17:20 -0400675 }
676 this->writeExpression(*arg, kSequence_Precedence);
Ethan Nicholas30d30222020-09-11 12:27:26 -0400677 if (scalarCount && scalarCount == constructorType.rows()) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400678 this->write(")");
679 scalarCount = 0;
680 }
681 }
682 this->write(")");
Ethan Nicholascc305772017-10-13 16:17:45 -0400683}
684
685void MetalCodeGenerator::writeFragCoord() {
Ethan Nicholasf931e402019-07-26 15:40:33 -0400686 if (fRTHeightName.length()) {
687 this->write("float4(_fragCoord.x, ");
688 this->write(fRTHeightName.c_str());
689 this->write(" - _fragCoord.y, 0.0, _fragCoord.w)");
Jim Van Verth6bc650e2019-02-07 14:53:23 -0500690 } else {
691 this->write("float4(_fragCoord.x, _fragCoord.y, 0.0, _fragCoord.w)");
692 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400693}
694
695void MetalCodeGenerator::writeVariableReference(const VariableReference& ref) {
Ethan Nicholas78686922020-10-08 06:46:27 -0400696 switch (ref.variable()->modifiers().fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400697 case SK_FRAGCOLOR_BUILTIN:
Timothy Liang7d637782018-06-05 09:58:07 -0400698 this->write("_out->sk_FragColor");
Ethan Nicholascc305772017-10-13 16:17:45 -0400699 break;
Timothy Liang6403b0e2018-05-17 10:40:04 -0400700 case SK_FRAGCOORD_BUILTIN:
701 this->writeFragCoord();
702 break;
Timothy Liangdc89f192018-06-13 09:20:31 -0400703 case SK_VERTEXID_BUILTIN:
704 this->write("sk_VertexID");
705 break;
706 case SK_INSTANCEID_BUILTIN:
707 this->write("sk_InstanceID");
708 break;
Timothy Liang7b8875d2018-08-10 09:42:31 -0400709 case SK_CLOCKWISE_BUILTIN:
710 // We'd set the front facing winding in the MTLRenderCommandEncoder to be counter
Brian Salomonf4ba4ec2020-03-19 15:54:28 -0400711 // clockwise to match Skia convention.
Timothy Liang7b8875d2018-08-10 09:42:31 -0400712 this->write(fProgram.fSettings.fFlipY ? "_frontFacing" : "(!_frontFacing)");
713 break;
Ethan Nicholascc305772017-10-13 16:17:45 -0400714 default:
Ethan Nicholas78686922020-10-08 06:46:27 -0400715 const Variable& var = *ref.variable();
Ethan Nicholas453f67f2020-10-09 10:43:45 -0400716 if (var.storage() == Variable::Storage::kGlobal) {
Ethan Nicholas78686922020-10-08 06:46:27 -0400717 if (var.modifiers().fFlags & Modifiers::kIn_Flag) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400718 this->write("_in.");
Ethan Nicholas78686922020-10-08 06:46:27 -0400719 } else if (var.modifiers().fFlags & Modifiers::kOut_Flag) {
Timothy Liangee84fe12018-05-18 14:38:19 -0400720 this->write("_out->");
Ethan Nicholas78686922020-10-08 06:46:27 -0400721 } else if (var.modifiers().fFlags & Modifiers::kUniform_Flag &&
722 var.type().typeKind() != Type::TypeKind::kSampler) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400723 this->write("_uniforms.");
724 } else {
Timothy Liangee84fe12018-05-18 14:38:19 -0400725 this->write("_globals->");
Ethan Nicholascc305772017-10-13 16:17:45 -0400726 }
727 }
Ethan Nicholas78686922020-10-08 06:46:27 -0400728 this->writeName(var.name());
Ethan Nicholascc305772017-10-13 16:17:45 -0400729 }
730}
731
732void MetalCodeGenerator::writeIndexExpression(const IndexExpression& expr) {
Ethan Nicholas2a4952d2020-10-08 15:35:56 -0400733 this->writeExpression(*expr.base(), kPostfix_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400734 this->write("[");
Ethan Nicholas2a4952d2020-10-08 15:35:56 -0400735 this->writeExpression(*expr.index(), kTopLevel_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400736 this->write("]");
737}
738
739void MetalCodeGenerator::writeFieldAccess(const FieldAccess& f) {
Ethan Nicholas7a95b202020-10-09 11:55:40 -0400740 const Type::Field* field = &f.base()->type().fields()[f.fieldIndex()];
741 if (FieldAccess::OwnerKind::kDefault == f.ownerKind()) {
742 this->writeExpression(*f.base(), kPostfix_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400743 this->write(".");
744 }
Timothy Liang7d637782018-06-05 09:58:07 -0400745 switch (field->fModifiers.fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400746 case SK_POSITION_BUILTIN:
Timothy Liangb8eeb802018-07-23 16:46:16 -0400747 this->write("_out->sk_Position");
Ethan Nicholascc305772017-10-13 16:17:45 -0400748 break;
749 default:
Timothy Liang7d637782018-06-05 09:58:07 -0400750 if (field->fName == "sk_PointSize") {
751 this->write("_out->sk_PointSize");
752 } else {
Ethan Nicholas7a95b202020-10-09 11:55:40 -0400753 if (FieldAccess::OwnerKind::kAnonymousInterfaceBlock == f.ownerKind()) {
Timothy Liang7d637782018-06-05 09:58:07 -0400754 this->write("_globals->");
755 this->write(fInterfaceBlockNameMap[fInterfaceBlockMap[field]]);
756 this->write("->");
757 }
Timothy Liang651286f2018-06-07 09:55:33 -0400758 this->writeName(field->fName);
Timothy Lianga06f2152018-05-24 15:33:31 -0400759 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400760 }
761}
762
763void MetalCodeGenerator::writeSwizzle(const Swizzle& swizzle) {
Ethan Nicholas6b4d5812020-10-12 16:11:51 -0400764 this->writeExpression(*swizzle.base(), kPostfix_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400765 this->write(".");
Ethan Nicholas6b4d5812020-10-12 16:11:51 -0400766 for (int c : swizzle.components()) {
Brian Osman25647672020-09-15 15:16:56 -0400767 SkASSERT(c >= 0 && c <= 3);
768 this->write(&("x\0y\0z\0w\0"[c * 2]));
Ethan Nicholascc305772017-10-13 16:17:45 -0400769 }
770}
771
772MetalCodeGenerator::Precedence MetalCodeGenerator::GetBinaryPrecedence(Token::Kind op) {
773 switch (op) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400774 case Token::Kind::TK_STAR: // fall through
775 case Token::Kind::TK_SLASH: // fall through
776 case Token::Kind::TK_PERCENT: return MetalCodeGenerator::kMultiplicative_Precedence;
777 case Token::Kind::TK_PLUS: // fall through
778 case Token::Kind::TK_MINUS: return MetalCodeGenerator::kAdditive_Precedence;
779 case Token::Kind::TK_SHL: // fall through
780 case Token::Kind::TK_SHR: return MetalCodeGenerator::kShift_Precedence;
781 case Token::Kind::TK_LT: // fall through
782 case Token::Kind::TK_GT: // fall through
783 case Token::Kind::TK_LTEQ: // fall through
784 case Token::Kind::TK_GTEQ: return MetalCodeGenerator::kRelational_Precedence;
785 case Token::Kind::TK_EQEQ: // fall through
786 case Token::Kind::TK_NEQ: return MetalCodeGenerator::kEquality_Precedence;
787 case Token::Kind::TK_BITWISEAND: return MetalCodeGenerator::kBitwiseAnd_Precedence;
788 case Token::Kind::TK_BITWISEXOR: return MetalCodeGenerator::kBitwiseXor_Precedence;
789 case Token::Kind::TK_BITWISEOR: return MetalCodeGenerator::kBitwiseOr_Precedence;
790 case Token::Kind::TK_LOGICALAND: return MetalCodeGenerator::kLogicalAnd_Precedence;
791 case Token::Kind::TK_LOGICALXOR: return MetalCodeGenerator::kLogicalXor_Precedence;
792 case Token::Kind::TK_LOGICALOR: return MetalCodeGenerator::kLogicalOr_Precedence;
793 case Token::Kind::TK_EQ: // fall through
794 case Token::Kind::TK_PLUSEQ: // fall through
795 case Token::Kind::TK_MINUSEQ: // fall through
796 case Token::Kind::TK_STAREQ: // fall through
797 case Token::Kind::TK_SLASHEQ: // fall through
798 case Token::Kind::TK_PERCENTEQ: // fall through
799 case Token::Kind::TK_SHLEQ: // fall through
800 case Token::Kind::TK_SHREQ: // fall through
801 case Token::Kind::TK_LOGICALANDEQ: // fall through
802 case Token::Kind::TK_LOGICALXOREQ: // fall through
803 case Token::Kind::TK_LOGICALOREQ: // fall through
804 case Token::Kind::TK_BITWISEANDEQ: // fall through
805 case Token::Kind::TK_BITWISEXOREQ: // fall through
806 case Token::Kind::TK_BITWISEOREQ: return MetalCodeGenerator::kAssignment_Precedence;
807 case Token::Kind::TK_COMMA: return MetalCodeGenerator::kSequence_Precedence;
Ethan Nicholascc305772017-10-13 16:17:45 -0400808 default: ABORT("unsupported binary operator");
809 }
810}
811
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500812void MetalCodeGenerator::writeMatrixTimesEqualHelper(const Type& left, const Type& right,
813 const Type& result) {
814 String key = "TimesEqual" + left.name() + right.name();
815 if (fHelpers.find(key) == fHelpers.end()) {
816 fExtraFunctions.printf("%s operator*=(thread %s& left, thread const %s& right) {\n"
817 " left = left * right;\n"
818 " return left;\n"
Ethan Nicholase2c49992020-10-05 11:49:11 -0400819 "}", String(result.name()).c_str(), String(left.name()).c_str(),
820 String(right.name()).c_str());
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500821 }
822}
823
Ethan Nicholascc305772017-10-13 16:17:45 -0400824void MetalCodeGenerator::writeBinaryExpression(const BinaryExpression& b,
825 Precedence parentPrecedence) {
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400826 const Expression& left = b.left();
827 const Expression& right = b.right();
828 const Type& leftType = left.type();
829 const Type& rightType = right.type();
830 Token::Kind op = b.getOperator();
831 Precedence precedence = GetBinaryPrecedence(b.getOperator());
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500832 bool needParens = precedence >= parentPrecedence;
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400833 switch (op) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400834 case Token::Kind::TK_EQEQ:
Ethan Nicholas30d30222020-09-11 12:27:26 -0400835 if (leftType.typeKind() == Type::TypeKind::kVector) {
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500836 this->write("all");
837 needParens = true;
838 }
839 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400840 case Token::Kind::TK_NEQ:
Ethan Nicholas30d30222020-09-11 12:27:26 -0400841 if (leftType.typeKind() == Type::TypeKind::kVector) {
Jim Van Verth36477b42019-04-11 14:57:30 -0400842 this->write("any");
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500843 needParens = true;
844 }
845 break;
846 default:
847 break;
848 }
849 if (needParens) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400850 this->write("(");
851 }
Brian Osman79457ef2020-09-24 15:01:27 -0400852 if (Compiler::IsAssignment(op) && left.is<VariableReference>() &&
Ethan Nicholas453f67f2020-10-09 10:43:45 -0400853 left.as<VariableReference>().variable()->storage() == Variable::Storage::kParameter &&
Ethan Nicholas78686922020-10-08 06:46:27 -0400854 left.as<VariableReference>().variable()->modifiers().fFlags & Modifiers::kOut_Flag) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400855 // writing to an out parameter. Since we have to turn those into pointers, we have to
856 // dereference it here.
857 this->write("*");
858 }
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400859 if (op == Token::Kind::TK_STAREQ && leftType.typeKind() == Type::TypeKind::kMatrix &&
Ethan Nicholas30d30222020-09-11 12:27:26 -0400860 rightType.typeKind() == Type::TypeKind::kMatrix) {
861 this->writeMatrixTimesEqualHelper(leftType, rightType, b.type());
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500862 }
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400863 this->writeExpression(left, precedence);
864 if (op != Token::Kind::TK_EQ && Compiler::IsAssignment(op) &&
865 left.kind() == Expression::Kind::kSwizzle && !left.hasSideEffects()) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400866 // This doesn't compile in Metal:
867 // float4 x = float4(1);
868 // x.xy *= float2x2(...);
869 // with the error message "non-const reference cannot bind to vector element",
870 // but switching it to x.xy = x.xy * float2x2(...) fixes it. We perform this tranformation
871 // as long as the LHS has no side effects, and hope for the best otherwise.
872 this->write(" = ");
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400873 this->writeExpression(left, kAssignment_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400874 this->write(" ");
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400875 String opName = Compiler::OperatorName(op);
876 SkASSERT(opName.endsWith("="));
877 this->write(opName.substr(0, opName.size() - 1).c_str());
Ethan Nicholascc305772017-10-13 16:17:45 -0400878 this->write(" ");
879 } else {
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400880 this->write(String(" ") + Compiler::OperatorName(op) + " ");
Ethan Nicholascc305772017-10-13 16:17:45 -0400881 }
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400882 this->writeExpression(right, precedence);
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500883 if (needParens) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400884 this->write(")");
885 }
886}
887
888void MetalCodeGenerator::writeTernaryExpression(const TernaryExpression& t,
889 Precedence parentPrecedence) {
890 if (kTernary_Precedence >= parentPrecedence) {
891 this->write("(");
892 }
Ethan Nicholasdd218162020-10-08 05:48:01 -0400893 this->writeExpression(*t.test(), kTernary_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400894 this->write(" ? ");
Ethan Nicholasdd218162020-10-08 05:48:01 -0400895 this->writeExpression(*t.ifTrue(), kTernary_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400896 this->write(" : ");
Ethan Nicholasdd218162020-10-08 05:48:01 -0400897 this->writeExpression(*t.ifFalse(), kTernary_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400898 if (kTernary_Precedence >= parentPrecedence) {
899 this->write(")");
900 }
901}
902
903void MetalCodeGenerator::writePrefixExpression(const PrefixExpression& p,
904 Precedence parentPrecedence) {
905 if (kPrefix_Precedence >= parentPrecedence) {
906 this->write("(");
907 }
Ethan Nicholas444ccc62020-10-09 10:16:22 -0400908 this->write(Compiler::OperatorName(p.getOperator()));
909 this->writeExpression(*p.operand(), kPrefix_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400910 if (kPrefix_Precedence >= parentPrecedence) {
911 this->write(")");
912 }
913}
914
915void MetalCodeGenerator::writePostfixExpression(const PostfixExpression& p,
916 Precedence parentPrecedence) {
917 if (kPostfix_Precedence >= parentPrecedence) {
918 this->write("(");
919 }
Ethan Nicholas444ccc62020-10-09 10:16:22 -0400920 this->writeExpression(*p.operand(), kPostfix_Precedence);
921 this->write(Compiler::OperatorName(p.getOperator()));
Ethan Nicholascc305772017-10-13 16:17:45 -0400922 if (kPostfix_Precedence >= parentPrecedence) {
923 this->write(")");
924 }
925}
926
927void MetalCodeGenerator::writeBoolLiteral(const BoolLiteral& b) {
Ethan Nicholas59d660c2020-09-28 09:18:15 -0400928 this->write(b.value() ? "true" : "false");
Ethan Nicholascc305772017-10-13 16:17:45 -0400929}
930
931void MetalCodeGenerator::writeIntLiteral(const IntLiteral& i) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400932 if (i.type() == *fContext.fUInt_Type) {
Ethan Nicholase96cdd12020-09-28 16:27:18 -0400933 this->write(to_string(i.value() & 0xffffffff) + "u");
Ethan Nicholascc305772017-10-13 16:17:45 -0400934 } else {
Ethan Nicholase96cdd12020-09-28 16:27:18 -0400935 this->write(to_string((int32_t) i.value()));
Ethan Nicholascc305772017-10-13 16:17:45 -0400936 }
937}
938
939void MetalCodeGenerator::writeFloatLiteral(const FloatLiteral& f) {
Ethan Nicholasa3f22f12020-10-01 12:13:17 -0400940 this->write(to_string(f.value()));
Ethan Nicholascc305772017-10-13 16:17:45 -0400941}
942
943void MetalCodeGenerator::writeSetting(const Setting& s) {
944 ABORT("internal error; setting was not folded to a constant during compilation\n");
945}
946
947void MetalCodeGenerator::writeFunction(const FunctionDefinition& f) {
Ethan Nicholasf931e402019-07-26 15:40:33 -0400948 fRTHeightName = fProgram.fInputs.fRTHeight ? "_globals->_anonInterface0->u_skRTHeight" : "";
Ethan Nicholascc305772017-10-13 16:17:45 -0400949 const char* separator = "";
Ethan Nicholas0a5d0962020-10-14 13:33:18 -0400950 if ("main" == f.declaration().name()) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400951 switch (fProgram.fKind) {
952 case Program::kFragment_Kind:
Timothy Liangb8eeb802018-07-23 16:46:16 -0400953 this->write("fragment Outputs fragmentMain");
Ethan Nicholascc305772017-10-13 16:17:45 -0400954 break;
955 case Program::kVertex_Kind:
Timothy Liangb8eeb802018-07-23 16:46:16 -0400956 this->write("vertex Outputs vertexMain");
Ethan Nicholascc305772017-10-13 16:17:45 -0400957 break;
958 default:
John Stiles3fabfc02020-09-25 15:51:28 -0400959 fErrors.error(-1, "unsupported kind of program");
960 return;
Ethan Nicholascc305772017-10-13 16:17:45 -0400961 }
962 this->write("(Inputs _in [[stage_in]]");
963 if (-1 != fUniformBuffer) {
964 this->write(", constant Uniforms& _uniforms [[buffer(" +
965 to_string(fUniformBuffer) + ")]]");
966 }
Brian Osman1179fcf2020-10-08 16:04:40 -0400967 for (const auto& e : fProgram.elements()) {
968 if (e->is<GlobalVarDeclaration>()) {
969 const GlobalVarDeclaration& decls = e->as<GlobalVarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -0400970 const VarDeclaration& var = decls.declaration()->as<VarDeclaration>();
971 if (var.var().type().typeKind() == Type::TypeKind::kSampler) {
972 if (var.var().modifiers().fLayout.fBinding < 0) {
Brian Osmanc0213602020-10-06 14:43:32 -0400973 fErrors.error(decls.fOffset,
974 "Metal samplers must have 'layout(binding=...)'");
975 return;
Timothy Liangee84fe12018-05-18 14:38:19 -0400976 }
Ethan Nicholasc51f33e2020-10-13 13:49:44 -0400977 if (var.var().type().dimensions() != SpvDim2D) {
Brian Osmanc0213602020-10-06 14:43:32 -0400978 // TODO: Support other texture types (skbug.com/10797)
979 fErrors.error(decls.fOffset, "Unsupported texture dimensions");
980 return;
981 }
982 this->write(", texture2d<float> ");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -0400983 this->writeName(var.var().name());
Brian Osmanc0213602020-10-06 14:43:32 -0400984 this->write("[[texture(");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -0400985 this->write(to_string(var.var().modifiers().fLayout.fBinding));
Brian Osmanc0213602020-10-06 14:43:32 -0400986 this->write(")]]");
987 this->write(", sampler ");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -0400988 this->writeName(var.var().name());
Brian Osmanc0213602020-10-06 14:43:32 -0400989 this->write(SAMPLER_SUFFIX);
990 this->write("[[sampler(");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -0400991 this->write(to_string(var.var().modifiers().fLayout.fBinding));
Brian Osmanc0213602020-10-06 14:43:32 -0400992 this->write(")]]");
Timothy Liang6403b0e2018-05-17 10:40:04 -0400993 }
Brian Osman1179fcf2020-10-08 16:04:40 -0400994 } else if (e->is<InterfaceBlock>()) {
995 const InterfaceBlock& intf = e->as<InterfaceBlock>();
Ethan Nicholaseaf47882020-10-15 10:10:08 -0400996 if (intf.typeName() == "sk_PerVertex") {
Timothy Lianga06f2152018-05-24 15:33:31 -0400997 continue;
998 }
999 this->write(", constant ");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001000 this->writeType(intf.variable().type());
Timothy Lianga06f2152018-05-24 15:33:31 -04001001 this->write("& " );
1002 this->write(fInterfaceBlockNameMap[&intf]);
1003 this->write(" [[buffer(");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001004 this->write(to_string(intf.variable().modifiers().fLayout.fBinding));
Timothy Lianga06f2152018-05-24 15:33:31 -04001005 this->write(")]]");
Timothy Liang6403b0e2018-05-17 10:40:04 -04001006 }
1007 }
Jim Van Verth6bc650e2019-02-07 14:53:23 -05001008 if (fProgram.fKind == Program::kFragment_Kind) {
1009 if (fProgram.fInputs.fRTHeight && fInterfaceBlockNameMap.empty()) {
Timothy Liang5422f9a2018-08-10 10:57:55 -04001010 this->write(", constant sksl_synthetic_uniforms& _anonInterface0 [[buffer(1)]]");
Ethan Nicholasf931e402019-07-26 15:40:33 -04001011 fRTHeightName = "_anonInterface0.u_skRTHeight";
Timothy Liang5422f9a2018-08-10 10:57:55 -04001012 }
Timothy Liang7b8875d2018-08-10 09:42:31 -04001013 this->write(", bool _frontFacing [[front_facing]]");
Timothy Liang7d637782018-06-05 09:58:07 -04001014 this->write(", float4 _fragCoord [[position]]");
Timothy Liangdc89f192018-06-13 09:20:31 -04001015 } else if (fProgram.fKind == Program::kVertex_Kind) {
1016 this->write(", uint sk_VertexID [[vertex_id]], uint sk_InstanceID [[instance_id]]");
Timothy Liang7d637782018-06-05 09:58:07 -04001017 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001018 separator = ", ";
1019 } else {
Ethan Nicholas0a5d0962020-10-14 13:33:18 -04001020 this->writeType(f.declaration().returnType());
Timothy Liang651286f2018-06-07 09:55:33 -04001021 this->write(" ");
Ethan Nicholas0a5d0962020-10-14 13:33:18 -04001022 this->writeName(f.declaration().name());
Timothy Liang651286f2018-06-07 09:55:33 -04001023 this->write("(");
Ethan Nicholas0a5d0962020-10-14 13:33:18 -04001024 Requirements requirements = this->requirements(f.declaration());
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -04001025 if (requirements & kInputs_Requirement) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001026 this->write("Inputs _in");
1027 separator = ", ";
1028 }
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -04001029 if (requirements & kOutputs_Requirement) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001030 this->write(separator);
Timothy Liangee84fe12018-05-18 14:38:19 -04001031 this->write("thread Outputs* _out");
Ethan Nicholascc305772017-10-13 16:17:45 -04001032 separator = ", ";
1033 }
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -04001034 if (requirements & kUniforms_Requirement) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001035 this->write(separator);
1036 this->write("Uniforms _uniforms");
1037 separator = ", ";
1038 }
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -04001039 if (requirements & kGlobals_Requirement) {
Timothy Liangee84fe12018-05-18 14:38:19 -04001040 this->write(separator);
1041 this->write("thread Globals* _globals");
1042 separator = ", ";
1043 }
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -04001044 if (requirements & kFragCoord_Requirement) {
1045 this->write(separator);
1046 this->write("float4 _fragCoord");
1047 separator = ", ";
1048 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001049 }
Ethan Nicholas0a5d0962020-10-14 13:33:18 -04001050 for (const auto& param : f.declaration().parameters()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001051 this->write(separator);
1052 separator = ", ";
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001053 this->writeModifiers(param->modifiers(), false);
Ethan Nicholascc305772017-10-13 16:17:45 -04001054 std::vector<int> sizes;
Ethan Nicholas30d30222020-09-11 12:27:26 -04001055 const Type* type = &param->type();
Ethan Nicholase6592142020-09-08 10:22:09 -04001056 while (type->typeKind() == Type::TypeKind::kArray) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001057 sizes.push_back(type->columns());
1058 type = &type->componentType();
1059 }
1060 this->writeType(*type);
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001061 if (param->modifiers().fFlags & Modifiers::kOut_Flag) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001062 this->write("*");
1063 }
Timothy Liang651286f2018-06-07 09:55:33 -04001064 this->write(" ");
Ethan Nicholase2c49992020-10-05 11:49:11 -04001065 this->writeName(param->name());
Ethan Nicholascc305772017-10-13 16:17:45 -04001066 for (int s : sizes) {
Brian Osmane8c26082020-10-01 17:22:45 -04001067 if (s == Type::kUnsizedArray) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001068 this->write("[]");
1069 } else {
1070 this->write("[" + to_string(s) + "]");
1071 }
1072 }
1073 }
1074 this->writeLine(") {");
1075
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001076 SkASSERT(!fProgram.fSettings.fFragColorIsInOut);
Brian Salomondc092132018-04-04 10:14:16 -04001077
Ethan Nicholas0a5d0962020-10-14 13:33:18 -04001078 if (f.declaration().name() == "main") {
John Stilescdcdb042020-07-06 09:03:51 -04001079 this->writeGlobalInit();
Timothy Liang7d637782018-06-05 09:58:07 -04001080 this->writeLine(" Outputs _outputStruct;");
1081 this->writeLine(" thread Outputs* _out = &_outputStruct;");
Ethan Nicholascc305772017-10-13 16:17:45 -04001082 }
John Stilesc67b3622020-05-28 17:53:13 -04001083
Ethan Nicholascc305772017-10-13 16:17:45 -04001084 fFunctionHeader = "";
1085 OutputStream* oldOut = fOut;
1086 StringStream buffer;
1087 fOut = &buffer;
1088 fIndentation++;
Ethan Nicholas0a5d0962020-10-14 13:33:18 -04001089 for (const std::unique_ptr<Statement>& stmt : f.body()->as<Block>().children()) {
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001090 if (!stmt->isEmpty()) {
1091 this->writeStatement(*stmt);
1092 this->writeLine();
1093 }
1094 }
Ethan Nicholas0a5d0962020-10-14 13:33:18 -04001095 if (f.declaration().name() == "main") {
Ethan Nicholascc305772017-10-13 16:17:45 -04001096 switch (fProgram.fKind) {
1097 case Program::kFragment_Kind:
Timothy Liang7d637782018-06-05 09:58:07 -04001098 this->writeLine("return *_out;");
Ethan Nicholascc305772017-10-13 16:17:45 -04001099 break;
1100 case Program::kVertex_Kind:
Timothy Liangb8eeb802018-07-23 16:46:16 -04001101 this->writeLine("_out->sk_Position.y = -_out->sk_Position.y;");
Timothy Lianga06f2152018-05-24 15:33:31 -04001102 this->writeLine("return *_out;"); // FIXME - detect if function already has return
Ethan Nicholascc305772017-10-13 16:17:45 -04001103 break;
1104 default:
John Stilesf7d70432020-05-28 15:46:38 -04001105 SkDEBUGFAIL("unsupported kind of program");
Ethan Nicholascc305772017-10-13 16:17:45 -04001106 }
1107 }
1108 fIndentation--;
1109 this->writeLine("}");
1110
1111 fOut = oldOut;
1112 this->write(fFunctionHeader);
1113 this->write(buffer.str());
1114}
1115
1116void MetalCodeGenerator::writeModifiers(const Modifiers& modifiers,
1117 bool globalContext) {
1118 if (modifiers.fFlags & Modifiers::kOut_Flag) {
1119 this->write("thread ");
1120 }
1121 if (modifiers.fFlags & Modifiers::kConst_Flag) {
Timothy Liangee84fe12018-05-18 14:38:19 -04001122 this->write("constant ");
Ethan Nicholascc305772017-10-13 16:17:45 -04001123 }
1124}
1125
1126void MetalCodeGenerator::writeInterfaceBlock(const InterfaceBlock& intf) {
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001127 if ("sk_PerVertex" == intf.typeName()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001128 return;
1129 }
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001130 this->writeModifiers(intf.variable().modifiers(), true);
Timothy Liangdc89f192018-06-13 09:20:31 -04001131 this->write("struct ");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001132 this->writeLine(intf.typeName() + " {");
1133 const Type* structType = &intf.variable().type();
Timothy Lianga06f2152018-05-24 15:33:31 -04001134 fWrittenStructs.push_back(structType);
Ethan Nicholase6592142020-09-08 10:22:09 -04001135 while (structType->typeKind() == Type::TypeKind::kArray) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001136 structType = &structType->componentType();
1137 }
Timothy Liangdc89f192018-06-13 09:20:31 -04001138 fIndentation++;
1139 writeFields(structType->fields(), structType->fOffset, &intf);
Jim Van Verth3d482992019-02-07 10:48:05 -05001140 if (fProgram.fInputs.fRTHeight) {
Timothy Liang7d637782018-06-05 09:58:07 -04001141 this->writeLine("float u_skRTHeight;");
Ethan Nicholascc305772017-10-13 16:17:45 -04001142 }
1143 fIndentation--;
1144 this->write("}");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001145 if (intf.instanceName().size()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001146 this->write(" ");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001147 this->write(intf.instanceName());
1148 for (const auto& size : intf.sizes()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001149 this->write("[");
1150 if (size) {
1151 this->writeExpression(*size, kTopLevel_Precedence);
1152 }
1153 this->write("]");
1154 }
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001155 fInterfaceBlockNameMap[&intf] = intf.instanceName();
Timothy Lianga06f2152018-05-24 15:33:31 -04001156 } else {
Timothy Liang7d637782018-06-05 09:58:07 -04001157 fInterfaceBlockNameMap[&intf] = "_anonInterface" + to_string(fAnonInterfaceCount++);
Ethan Nicholascc305772017-10-13 16:17:45 -04001158 }
1159 this->writeLine(";");
1160}
1161
Timothy Liangdc89f192018-06-13 09:20:31 -04001162void MetalCodeGenerator::writeFields(const std::vector<Type::Field>& fields, int parentOffset,
1163 const InterfaceBlock* parentIntf) {
Timothy Liang609fbe32018-08-10 16:40:49 -04001164 MemoryLayout memoryLayout(MemoryLayout::kMetal_Standard);
Timothy Liangdc89f192018-06-13 09:20:31 -04001165 int currentOffset = 0;
1166 for (const auto& field: fields) {
1167 int fieldOffset = field.fModifiers.fLayout.fOffset;
1168 const Type* fieldType = field.fType;
1169 if (fieldOffset != -1) {
1170 if (currentOffset > fieldOffset) {
1171 fErrors.error(parentOffset,
1172 "offset of field '" + field.fName + "' must be at least " +
1173 to_string((int) currentOffset));
Brian Osman8609a242020-09-08 14:01:49 -04001174 return;
Timothy Liangdc89f192018-06-13 09:20:31 -04001175 } else if (currentOffset < fieldOffset) {
1176 this->write("char pad");
1177 this->write(to_string(fPaddingCount++));
1178 this->write("[");
1179 this->write(to_string(fieldOffset - currentOffset));
1180 this->writeLine("];");
1181 currentOffset = fieldOffset;
1182 }
1183 int alignment = memoryLayout.alignment(*fieldType);
1184 if (fieldOffset % alignment) {
1185 fErrors.error(parentOffset,
1186 "offset of field '" + field.fName + "' must be a multiple of " +
1187 to_string((int) alignment));
Brian Osman8609a242020-09-08 14:01:49 -04001188 return;
Timothy Liangdc89f192018-06-13 09:20:31 -04001189 }
1190 }
Brian Osman8609a242020-09-08 14:01:49 -04001191 size_t fieldSize = memoryLayout.size(*fieldType);
1192 if (fieldSize > static_cast<size_t>(std::numeric_limits<int>::max() - currentOffset)) {
1193 fErrors.error(parentOffset, "field offset overflow");
1194 return;
1195 }
1196 currentOffset += fieldSize;
Timothy Liangdc89f192018-06-13 09:20:31 -04001197 std::vector<int> sizes;
Ethan Nicholase6592142020-09-08 10:22:09 -04001198 while (fieldType->typeKind() == Type::TypeKind::kArray) {
Timothy Liangdc89f192018-06-13 09:20:31 -04001199 sizes.push_back(fieldType->columns());
1200 fieldType = &fieldType->componentType();
1201 }
1202 this->writeModifiers(field.fModifiers, false);
1203 this->writeType(*fieldType);
1204 this->write(" ");
1205 this->writeName(field.fName);
1206 for (int s : sizes) {
Brian Osmane8c26082020-10-01 17:22:45 -04001207 if (s == Type::kUnsizedArray) {
Timothy Liangdc89f192018-06-13 09:20:31 -04001208 this->write("[]");
1209 } else {
1210 this->write("[" + to_string(s) + "]");
1211 }
1212 }
1213 this->writeLine(";");
1214 if (parentIntf) {
1215 fInterfaceBlockMap[&field] = parentIntf;
1216 }
1217 }
1218}
1219
Ethan Nicholascc305772017-10-13 16:17:45 -04001220void MetalCodeGenerator::writeVarInitializer(const Variable& var, const Expression& value) {
1221 this->writeExpression(value, kTopLevel_Precedence);
1222}
1223
Timothy Liang651286f2018-06-07 09:55:33 -04001224void MetalCodeGenerator::writeName(const String& name) {
1225 if (fReservedWords.find(name) != fReservedWords.end()) {
1226 this->write("_"); // adding underscore before name to avoid conflict with reserved words
1227 }
1228 this->write(name);
1229}
1230
Brian Osmanc0213602020-10-06 14:43:32 -04001231void MetalCodeGenerator::writeVarDeclaration(const VarDeclaration& var, bool global) {
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001232 if (global && !(var.var().modifiers().fFlags & Modifiers::kConst_Flag)) {
Brian Osmanc0213602020-10-06 14:43:32 -04001233 return;
Ethan Nicholascc305772017-10-13 16:17:45 -04001234 }
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001235 this->writeModifiers(var.var().modifiers(), global);
1236 this->writeType(var.baseType());
Brian Osmanc0213602020-10-06 14:43:32 -04001237 this->write(" ");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001238 this->writeName(var.var().name());
1239 for (int i = 0; i < var.sizeCount(); ++i) {
Brian Osmanc0213602020-10-06 14:43:32 -04001240 this->write("[");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001241 if (var.size(i)) {
1242 this->writeExpression(*var.size(i), kTopLevel_Precedence);
Brian Osmanc0213602020-10-06 14:43:32 -04001243 }
1244 this->write("]");
Ethan Nicholascc305772017-10-13 16:17:45 -04001245 }
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001246 if (var.value()) {
Brian Osmanc0213602020-10-06 14:43:32 -04001247 this->write(" = ");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001248 this->writeVarInitializer(var.var(), *var.value());
Brian Osmanc0213602020-10-06 14:43:32 -04001249 }
1250 this->write(";");
Ethan Nicholascc305772017-10-13 16:17:45 -04001251}
1252
1253void MetalCodeGenerator::writeStatement(const Statement& s) {
Ethan Nicholase6592142020-09-08 10:22:09 -04001254 switch (s.kind()) {
1255 case Statement::Kind::kBlock:
John Stiles26f98502020-08-18 09:30:51 -04001256 this->writeBlock(s.as<Block>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001257 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001258 case Statement::Kind::kExpression:
Ethan Nicholasd503a5a2020-09-30 09:29:55 -04001259 this->writeExpression(*s.as<ExpressionStatement>().expression(), kTopLevel_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001260 this->write(";");
1261 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001262 case Statement::Kind::kReturn:
John Stiles26f98502020-08-18 09:30:51 -04001263 this->writeReturnStatement(s.as<ReturnStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001264 break;
Brian Osmanc0213602020-10-06 14:43:32 -04001265 case Statement::Kind::kVarDeclaration:
1266 this->writeVarDeclaration(s.as<VarDeclaration>(), false);
Ethan Nicholascc305772017-10-13 16:17:45 -04001267 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001268 case Statement::Kind::kIf:
John Stiles26f98502020-08-18 09:30:51 -04001269 this->writeIfStatement(s.as<IfStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001270 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001271 case Statement::Kind::kFor:
John Stiles26f98502020-08-18 09:30:51 -04001272 this->writeForStatement(s.as<ForStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001273 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001274 case Statement::Kind::kWhile:
John Stiles26f98502020-08-18 09:30:51 -04001275 this->writeWhileStatement(s.as<WhileStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001276 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001277 case Statement::Kind::kDo:
John Stiles26f98502020-08-18 09:30:51 -04001278 this->writeDoStatement(s.as<DoStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001279 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001280 case Statement::Kind::kSwitch:
John Stiles26f98502020-08-18 09:30:51 -04001281 this->writeSwitchStatement(s.as<SwitchStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001282 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001283 case Statement::Kind::kBreak:
Ethan Nicholascc305772017-10-13 16:17:45 -04001284 this->write("break;");
1285 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001286 case Statement::Kind::kContinue:
Ethan Nicholascc305772017-10-13 16:17:45 -04001287 this->write("continue;");
1288 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001289 case Statement::Kind::kDiscard:
Timothy Lianga06f2152018-05-24 15:33:31 -04001290 this->write("discard_fragment();");
Ethan Nicholascc305772017-10-13 16:17:45 -04001291 break;
John Stiles98c1f822020-09-09 14:18:53 -04001292 case Statement::Kind::kInlineMarker:
Ethan Nicholase6592142020-09-08 10:22:09 -04001293 case Statement::Kind::kNop:
Ethan Nicholascc305772017-10-13 16:17:45 -04001294 this->write(";");
1295 break;
1296 default:
Ethan Nicholas2a099da2020-01-02 14:40:54 -05001297#ifdef SK_DEBUG
Ethan Nicholascc305772017-10-13 16:17:45 -04001298 ABORT("unsupported statement: %s", s.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -05001299#endif
1300 break;
Ethan Nicholascc305772017-10-13 16:17:45 -04001301 }
1302}
1303
Ethan Nicholascc305772017-10-13 16:17:45 -04001304void MetalCodeGenerator::writeBlock(const Block& b) {
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001305 bool isScope = b.isScope();
1306 if (isScope) {
Ethan Nicholas70728ef2020-05-28 07:09:00 -04001307 this->writeLine("{");
1308 fIndentation++;
1309 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001310 for (const std::unique_ptr<Statement>& stmt : b.children()) {
1311 if (!stmt->isEmpty()) {
1312 this->writeStatement(*stmt);
1313 this->writeLine();
1314 }
1315 }
1316 if (isScope) {
Ethan Nicholas70728ef2020-05-28 07:09:00 -04001317 fIndentation--;
1318 this->write("}");
1319 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001320}
1321
1322void MetalCodeGenerator::writeIfStatement(const IfStatement& stmt) {
1323 this->write("if (");
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04001324 this->writeExpression(*stmt.test(), kTopLevel_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001325 this->write(") ");
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04001326 this->writeStatement(*stmt.ifTrue());
1327 if (stmt.ifFalse()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001328 this->write(" else ");
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04001329 this->writeStatement(*stmt.ifFalse());
Ethan Nicholascc305772017-10-13 16:17:45 -04001330 }
1331}
1332
1333void MetalCodeGenerator::writeForStatement(const ForStatement& f) {
1334 this->write("for (");
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04001335 if (f.initializer() && !f.initializer()->isEmpty()) {
1336 this->writeStatement(*f.initializer());
Ethan Nicholascc305772017-10-13 16:17:45 -04001337 } else {
1338 this->write("; ");
1339 }
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04001340 if (f.test()) {
1341 this->writeExpression(*f.test(), kTopLevel_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001342 }
1343 this->write("; ");
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04001344 if (f.next()) {
1345 this->writeExpression(*f.next(), kTopLevel_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001346 }
1347 this->write(") ");
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04001348 this->writeStatement(*f.statement());
Ethan Nicholascc305772017-10-13 16:17:45 -04001349}
1350
1351void MetalCodeGenerator::writeWhileStatement(const WhileStatement& w) {
1352 this->write("while (");
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04001353 this->writeExpression(*w.test(), kTopLevel_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001354 this->write(") ");
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04001355 this->writeStatement(*w.statement());
Ethan Nicholascc305772017-10-13 16:17:45 -04001356}
1357
1358void MetalCodeGenerator::writeDoStatement(const DoStatement& d) {
1359 this->write("do ");
Ethan Nicholas1fd61162020-09-28 13:14:19 -04001360 this->writeStatement(*d.statement());
Ethan Nicholascc305772017-10-13 16:17:45 -04001361 this->write(" while (");
Ethan Nicholas1fd61162020-09-28 13:14:19 -04001362 this->writeExpression(*d.test(), kTopLevel_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001363 this->write(");");
1364}
1365
1366void MetalCodeGenerator::writeSwitchStatement(const SwitchStatement& s) {
1367 this->write("switch (");
1368 this->writeExpression(*s.fValue, kTopLevel_Precedence);
1369 this->writeLine(") {");
1370 fIndentation++;
1371 for (const auto& c : s.fCases) {
1372 if (c->fValue) {
1373 this->write("case ");
1374 this->writeExpression(*c->fValue, kTopLevel_Precedence);
1375 this->writeLine(":");
1376 } else {
1377 this->writeLine("default:");
1378 }
1379 fIndentation++;
1380 for (const auto& stmt : c->fStatements) {
1381 this->writeStatement(*stmt);
1382 this->writeLine();
1383 }
1384 fIndentation--;
1385 }
1386 fIndentation--;
1387 this->write("}");
1388}
1389
1390void MetalCodeGenerator::writeReturnStatement(const ReturnStatement& r) {
1391 this->write("return");
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04001392 if (r.expression()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001393 this->write(" ");
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04001394 this->writeExpression(*r.expression(), kTopLevel_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001395 }
1396 this->write(";");
1397}
1398
1399void MetalCodeGenerator::writeHeader() {
1400 this->write("#include <metal_stdlib>\n");
1401 this->write("#include <simd/simd.h>\n");
1402 this->write("using namespace metal;\n");
1403}
1404
1405void MetalCodeGenerator::writeUniformStruct() {
Brian Osman1179fcf2020-10-08 16:04:40 -04001406 for (const auto& e : fProgram.elements()) {
1407 if (e->is<GlobalVarDeclaration>()) {
1408 const GlobalVarDeclaration& decls = e->as<GlobalVarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001409 const Variable& var = decls.declaration()->as<VarDeclaration>().var();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001410 if (var.modifiers().fFlags & Modifiers::kUniform_Flag &&
Brian Osmanc0213602020-10-06 14:43:32 -04001411 var.type().typeKind() != Type::TypeKind::kSampler) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001412 if (-1 == fUniformBuffer) {
1413 this->write("struct Uniforms {\n");
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001414 fUniformBuffer = var.modifiers().fLayout.fSet;
Ethan Nicholascc305772017-10-13 16:17:45 -04001415 if (-1 == fUniformBuffer) {
1416 fErrors.error(decls.fOffset, "Metal uniforms must have 'layout(set=...)'");
1417 }
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001418 } else if (var.modifiers().fLayout.fSet != fUniformBuffer) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001419 if (-1 == fUniformBuffer) {
1420 fErrors.error(decls.fOffset, "Metal backend requires all uniforms to have "
1421 "the same 'layout(set=...)'");
1422 }
1423 }
1424 this->write(" ");
Brian Osmanc0213602020-10-06 14:43:32 -04001425 this->writeType(var.type());
Ethan Nicholascc305772017-10-13 16:17:45 -04001426 this->write(" ");
Brian Osmanc0213602020-10-06 14:43:32 -04001427 this->writeName(var.name());
Ethan Nicholascc305772017-10-13 16:17:45 -04001428 this->write(";\n");
1429 }
1430 }
1431 }
1432 if (-1 != fUniformBuffer) {
1433 this->write("};\n");
1434 }
1435}
1436
1437void MetalCodeGenerator::writeInputStruct() {
1438 this->write("struct Inputs {\n");
Brian Osman1179fcf2020-10-08 16:04:40 -04001439 for (const auto& e : fProgram.elements()) {
1440 if (e->is<GlobalVarDeclaration>()) {
1441 const GlobalVarDeclaration& decls = e->as<GlobalVarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001442 const Variable& var = decls.declaration()->as<VarDeclaration>().var();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001443 if (var.modifiers().fFlags & Modifiers::kIn_Flag &&
1444 -1 == var.modifiers().fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001445 this->write(" ");
Brian Osmanc0213602020-10-06 14:43:32 -04001446 this->writeType(var.type());
Ethan Nicholascc305772017-10-13 16:17:45 -04001447 this->write(" ");
Brian Osmanc0213602020-10-06 14:43:32 -04001448 this->writeName(var.name());
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001449 if (-1 != var.modifiers().fLayout.fLocation) {
Brian Osmanc0213602020-10-06 14:43:32 -04001450 if (fProgram.fKind == Program::kVertex_Kind) {
1451 this->write(" [[attribute(" +
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001452 to_string(var.modifiers().fLayout.fLocation) + ")]]");
Brian Osmanc0213602020-10-06 14:43:32 -04001453 } else if (fProgram.fKind == Program::kFragment_Kind) {
1454 this->write(" [[user(locn" +
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001455 to_string(var.modifiers().fLayout.fLocation) + ")]]");
Ethan Nicholascc305772017-10-13 16:17:45 -04001456 }
1457 }
1458 this->write(";\n");
1459 }
1460 }
1461 }
1462 this->write("};\n");
1463}
1464
1465void MetalCodeGenerator::writeOutputStruct() {
1466 this->write("struct Outputs {\n");
Timothy Liang7d637782018-06-05 09:58:07 -04001467 if (fProgram.fKind == Program::kVertex_Kind) {
Timothy Liangb8eeb802018-07-23 16:46:16 -04001468 this->write(" float4 sk_Position [[position]];\n");
Timothy Liang7d637782018-06-05 09:58:07 -04001469 } else if (fProgram.fKind == Program::kFragment_Kind) {
Timothy Liangde0be802018-08-10 13:48:08 -04001470 this->write(" float4 sk_FragColor [[color(0)]];\n");
Timothy Liang7d637782018-06-05 09:58:07 -04001471 }
Brian Osman1179fcf2020-10-08 16:04:40 -04001472 for (const auto& e : fProgram.elements()) {
1473 if (e->is<GlobalVarDeclaration>()) {
1474 const GlobalVarDeclaration& decls = e->as<GlobalVarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001475 const Variable& var = decls.declaration()->as<VarDeclaration>().var();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001476 if (var.modifiers().fFlags & Modifiers::kOut_Flag &&
1477 -1 == var.modifiers().fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001478 this->write(" ");
Brian Osmanc0213602020-10-06 14:43:32 -04001479 this->writeType(var.type());
Ethan Nicholascc305772017-10-13 16:17:45 -04001480 this->write(" ");
Brian Osmanc0213602020-10-06 14:43:32 -04001481 this->writeName(var.name());
1482 if (fProgram.fKind == Program::kVertex_Kind) {
1483 this->write(" [[user(locn" +
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001484 to_string(var.modifiers().fLayout.fLocation) + ")]]");
Brian Osmanc0213602020-10-06 14:43:32 -04001485 } else if (fProgram.fKind == Program::kFragment_Kind) {
1486 this->write(" [[color(" +
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001487 to_string(var.modifiers().fLayout.fLocation) +")");
1488 int colorIndex = var.modifiers().fLayout.fIndex;
Brian Osmanc0213602020-10-06 14:43:32 -04001489 if (colorIndex) {
1490 this->write(", index(" + to_string(colorIndex) + ")");
Timothy Liang7d637782018-06-05 09:58:07 -04001491 }
Brian Osmanc0213602020-10-06 14:43:32 -04001492 this->write("]]");
Ethan Nicholascc305772017-10-13 16:17:45 -04001493 }
1494 this->write(";\n");
1495 }
1496 }
Timothy Liang7d637782018-06-05 09:58:07 -04001497 }
1498 if (fProgram.fKind == Program::kVertex_Kind) {
Jim Van Verth3913d3e2020-08-31 15:16:57 -04001499 this->write(" float sk_PointSize [[point_size]];\n");
Timothy Liang7d637782018-06-05 09:58:07 -04001500 }
1501 this->write("};\n");
1502}
1503
1504void MetalCodeGenerator::writeInterfaceBlocks() {
1505 bool wroteInterfaceBlock = false;
Brian Osman1179fcf2020-10-08 16:04:40 -04001506 for (const auto& e : fProgram.elements()) {
1507 if (e->is<InterfaceBlock>()) {
1508 this->writeInterfaceBlock(e->as<InterfaceBlock>());
Timothy Liang7d637782018-06-05 09:58:07 -04001509 wroteInterfaceBlock = true;
1510 }
1511 }
Jim Van Verth3d482992019-02-07 10:48:05 -05001512 if (!wroteInterfaceBlock && fProgram.fInputs.fRTHeight) {
Timothy Liang7d637782018-06-05 09:58:07 -04001513 this->writeLine("struct sksl_synthetic_uniforms {");
1514 this->writeLine(" float u_skRTHeight;");
1515 this->writeLine("};");
1516 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001517}
1518
John Stilescdcdb042020-07-06 09:03:51 -04001519void MetalCodeGenerator::visitGlobalStruct(GlobalStructVisitor* visitor) {
1520 // Visit the interface blocks.
1521 for (const auto& [interfaceType, interfaceName] : fInterfaceBlockNameMap) {
1522 visitor->VisitInterfaceBlock(*interfaceType, interfaceName);
1523 }
Brian Osman1179fcf2020-10-08 16:04:40 -04001524 for (const auto& element : fProgram.elements()) {
1525 if (!element->is<GlobalVarDeclaration>()) {
John Stilescdcdb042020-07-06 09:03:51 -04001526 continue;
Timothy Liang7d637782018-06-05 09:58:07 -04001527 }
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001528 const GlobalVarDeclaration& global = element->as<GlobalVarDeclaration>();
1529 const VarDeclaration& decl = global.declaration()->as<VarDeclaration>();
1530 const Variable& var = decl.var();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001531 if ((!var.modifiers().fFlags && -1 == var.modifiers().fLayout.fBuiltin) ||
Brian Osmanc0213602020-10-06 14:43:32 -04001532 var.type().typeKind() == Type::TypeKind::kSampler) {
1533 if (var.type().typeKind() == Type::TypeKind::kSampler) {
1534 // Samplers are represented as a "texture/sampler" duo in the global struct.
1535 visitor->VisitTexture(var.type(), var.name());
1536 visitor->VisitSampler(var.type(), String(var.name()) + SAMPLER_SUFFIX);
1537 } else {
1538 // Visit a regular variable.
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001539 visitor->VisitVariable(var, decl.value().get());
Timothy Liangee84fe12018-05-18 14:38:19 -04001540 }
1541 }
1542 }
John Stilescdcdb042020-07-06 09:03:51 -04001543}
1544
1545void MetalCodeGenerator::writeGlobalStruct() {
1546 class : public GlobalStructVisitor {
1547 public:
1548 void VisitInterfaceBlock(const InterfaceBlock& block, const String& blockName) override {
1549 this->AddElement();
1550 fCodeGen->write(" constant ");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001551 fCodeGen->write(block.typeName());
John Stilescdcdb042020-07-06 09:03:51 -04001552 fCodeGen->write("* ");
1553 fCodeGen->writeName(blockName);
1554 fCodeGen->write(";\n");
1555 }
1556 void VisitTexture(const Type& type, const String& name) override {
1557 this->AddElement();
1558 fCodeGen->write(" ");
1559 fCodeGen->writeType(type);
1560 fCodeGen->write(" ");
1561 fCodeGen->writeName(name);
1562 fCodeGen->write(";\n");
1563 }
1564 void VisitSampler(const Type&, const String& name) override {
1565 this->AddElement();
1566 fCodeGen->write(" sampler ");
1567 fCodeGen->writeName(name);
1568 fCodeGen->write(";\n");
1569 }
1570 void VisitVariable(const Variable& var, const Expression* value) override {
1571 this->AddElement();
1572 fCodeGen->write(" ");
Ethan Nicholas30d30222020-09-11 12:27:26 -04001573 fCodeGen->writeType(var.type());
John Stilescdcdb042020-07-06 09:03:51 -04001574 fCodeGen->write(" ");
Ethan Nicholase2c49992020-10-05 11:49:11 -04001575 fCodeGen->writeName(var.name());
John Stilescdcdb042020-07-06 09:03:51 -04001576 fCodeGen->write(";\n");
1577 }
1578 void AddElement() {
1579 if (fFirst) {
1580 fCodeGen->write("struct Globals {\n");
1581 fFirst = false;
1582 }
1583 }
1584 void Finish() {
1585 if (!fFirst) {
1586 fCodeGen->write("};");
1587 fFirst = true;
1588 }
1589 }
1590
1591 MetalCodeGenerator* fCodeGen = nullptr;
1592 bool fFirst = true;
1593 } visitor;
1594
1595 visitor.fCodeGen = this;
1596 this->visitGlobalStruct(&visitor);
1597 visitor.Finish();
1598}
1599
1600void MetalCodeGenerator::writeGlobalInit() {
1601 class : public GlobalStructVisitor {
1602 public:
1603 void VisitInterfaceBlock(const InterfaceBlock& blockType,
1604 const String& blockName) override {
1605 this->AddElement();
1606 fCodeGen->write("&");
1607 fCodeGen->writeName(blockName);
1608 }
1609 void VisitTexture(const Type&, const String& name) override {
1610 this->AddElement();
1611 fCodeGen->writeName(name);
1612 }
1613 void VisitSampler(const Type&, const String& name) override {
1614 this->AddElement();
1615 fCodeGen->writeName(name);
1616 }
1617 void VisitVariable(const Variable& var, const Expression* value) override {
1618 this->AddElement();
1619 if (value) {
1620 fCodeGen->writeVarInitializer(var, *value);
1621 } else {
1622 fCodeGen->write("{}");
1623 }
1624 }
1625 void AddElement() {
1626 if (fFirst) {
1627 fCodeGen->write(" Globals globalStruct{");
1628 fFirst = false;
1629 } else {
1630 fCodeGen->write(", ");
1631 }
1632 }
1633 void Finish() {
1634 if (!fFirst) {
1635 fCodeGen->writeLine("};");
1636 fCodeGen->writeLine(" thread Globals* _globals = &globalStruct;");
1637 fCodeGen->writeLine(" (void)_globals;");
1638 }
1639 }
1640 MetalCodeGenerator* fCodeGen = nullptr;
1641 bool fFirst = true;
1642 } visitor;
1643
1644 visitor.fCodeGen = this;
1645 this->visitGlobalStruct(&visitor);
1646 visitor.Finish();
Timothy Liangee84fe12018-05-18 14:38:19 -04001647}
1648
Ethan Nicholascc305772017-10-13 16:17:45 -04001649void MetalCodeGenerator::writeProgramElement(const ProgramElement& e) {
Ethan Nicholase6592142020-09-08 10:22:09 -04001650 switch (e.kind()) {
1651 case ProgramElement::Kind::kExtension:
Ethan Nicholascc305772017-10-13 16:17:45 -04001652 break;
Brian Osmanc0213602020-10-06 14:43:32 -04001653 case ProgramElement::Kind::kGlobalVar: {
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001654 const GlobalVarDeclaration& global = e.as<GlobalVarDeclaration>();
1655 const VarDeclaration& decl = global.declaration()->as<VarDeclaration>();
1656 int builtin = decl.var().modifiers().fLayout.fBuiltin;
Brian Osmanc0213602020-10-06 14:43:32 -04001657 if (-1 == builtin) {
1658 // normal var
1659 this->writeVarDeclaration(decl, true);
1660 this->writeLine();
1661 } else if (SK_FRAGCOLOR_BUILTIN == builtin) {
1662 // ignore
Ethan Nicholascc305772017-10-13 16:17:45 -04001663 }
1664 break;
1665 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001666 case ProgramElement::Kind::kInterfaceBlock:
Timothy Liang7d637782018-06-05 09:58:07 -04001667 // handled in writeInterfaceBlocks, do nothing
Ethan Nicholascc305772017-10-13 16:17:45 -04001668 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001669 case ProgramElement::Kind::kFunction:
John Stiles3dc0da62020-08-19 17:48:31 -04001670 this->writeFunction(e.as<FunctionDefinition>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001671 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001672 case ProgramElement::Kind::kModifiers:
Ethan Nicholas077050b2020-10-13 10:30:20 -04001673 this->writeModifiers(e.as<ModifiersDeclaration>().modifiers(), true);
Ethan Nicholascc305772017-10-13 16:17:45 -04001674 this->writeLine(";");
1675 break;
1676 default:
Ethan Nicholas2a099da2020-01-02 14:40:54 -05001677#ifdef SK_DEBUG
1678 ABORT("unsupported program element: %s\n", e.description().c_str());
1679#endif
1680 break;
Ethan Nicholascc305772017-10-13 16:17:45 -04001681 }
1682}
1683
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001684MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const Expression* e) {
1685 if (!e) {
1686 return kNo_Requirements;
1687 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001688 switch (e->kind()) {
1689 case Expression::Kind::kFunctionCall: {
John Stiles3dc0da62020-08-19 17:48:31 -04001690 const FunctionCall& f = e->as<FunctionCall>();
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001691 Requirements result = this->requirements(f.function());
1692 for (const auto& arg : f.arguments()) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001693 result |= this->requirements(arg.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001694 }
1695 return result;
1696 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001697 case Expression::Kind::kConstructor: {
John Stiles3dc0da62020-08-19 17:48:31 -04001698 const Constructor& c = e->as<Constructor>();
Ethan Nicholascc305772017-10-13 16:17:45 -04001699 Requirements result = kNo_Requirements;
Ethan Nicholasf70f0442020-09-29 12:41:35 -04001700 for (const auto& arg : c.arguments()) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001701 result |= this->requirements(arg.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001702 }
1703 return result;
1704 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001705 case Expression::Kind::kFieldAccess: {
John Stiles3dc0da62020-08-19 17:48:31 -04001706 const FieldAccess& f = e->as<FieldAccess>();
Ethan Nicholas7a95b202020-10-09 11:55:40 -04001707 if (FieldAccess::OwnerKind::kAnonymousInterfaceBlock == f.ownerKind()) {
Timothy Liang7d637782018-06-05 09:58:07 -04001708 return kGlobals_Requirement;
1709 }
Ethan Nicholas7a95b202020-10-09 11:55:40 -04001710 return this->requirements(f.base().get());
Timothy Liang7d637782018-06-05 09:58:07 -04001711 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001712 case Expression::Kind::kSwizzle:
Ethan Nicholas6b4d5812020-10-12 16:11:51 -04001713 return this->requirements(e->as<Swizzle>().base().get());
Ethan Nicholase6592142020-09-08 10:22:09 -04001714 case Expression::Kind::kBinary: {
1715 const BinaryExpression& bin = e->as<BinaryExpression>();
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001716 return this->requirements(&bin.left()) |
1717 this->requirements(&bin.right());
Ethan Nicholascc305772017-10-13 16:17:45 -04001718 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001719 case Expression::Kind::kIndex: {
John Stiles3dc0da62020-08-19 17:48:31 -04001720 const IndexExpression& idx = e->as<IndexExpression>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04001721 return this->requirements(idx.base().get()) | this->requirements(idx.index().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001722 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001723 case Expression::Kind::kPrefix:
Ethan Nicholas444ccc62020-10-09 10:16:22 -04001724 return this->requirements(e->as<PrefixExpression>().operand().get());
Ethan Nicholase6592142020-09-08 10:22:09 -04001725 case Expression::Kind::kPostfix:
Ethan Nicholas444ccc62020-10-09 10:16:22 -04001726 return this->requirements(e->as<PostfixExpression>().operand().get());
Ethan Nicholase6592142020-09-08 10:22:09 -04001727 case Expression::Kind::kTernary: {
John Stiles3dc0da62020-08-19 17:48:31 -04001728 const TernaryExpression& t = e->as<TernaryExpression>();
Ethan Nicholasdd218162020-10-08 05:48:01 -04001729 return this->requirements(t.test().get()) | this->requirements(t.ifTrue().get()) |
1730 this->requirements(t.ifFalse().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001731 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001732 case Expression::Kind::kVariableReference: {
John Stiles3dc0da62020-08-19 17:48:31 -04001733 const VariableReference& v = e->as<VariableReference>();
Ethan Nicholas78686922020-10-08 06:46:27 -04001734 const Modifiers& modifiers = v.variable()->modifiers();
Ethan Nicholascc305772017-10-13 16:17:45 -04001735 Requirements result = kNo_Requirements;
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001736 if (modifiers.fLayout.fBuiltin == SK_FRAGCOORD_BUILTIN) {
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -04001737 result = kGlobals_Requirement | kFragCoord_Requirement;
Ethan Nicholas453f67f2020-10-09 10:43:45 -04001738 } else if (Variable::Storage::kGlobal == v.variable()->storage()) {
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001739 if (modifiers.fFlags & Modifiers::kIn_Flag) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001740 result = kInputs_Requirement;
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001741 } else if (modifiers.fFlags & Modifiers::kOut_Flag) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001742 result = kOutputs_Requirement;
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001743 } else if (modifiers.fFlags & Modifiers::kUniform_Flag &&
Ethan Nicholas78686922020-10-08 06:46:27 -04001744 v.variable()->type().typeKind() != Type::TypeKind::kSampler) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001745 result = kUniforms_Requirement;
Timothy Liangee84fe12018-05-18 14:38:19 -04001746 } else {
1747 result = kGlobals_Requirement;
Ethan Nicholascc305772017-10-13 16:17:45 -04001748 }
1749 }
1750 return result;
1751 }
1752 default:
1753 return kNo_Requirements;
1754 }
1755}
1756
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001757MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const Statement* s) {
1758 if (!s) {
1759 return kNo_Requirements;
1760 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001761 switch (s->kind()) {
1762 case Statement::Kind::kBlock: {
Ethan Nicholascc305772017-10-13 16:17:45 -04001763 Requirements result = kNo_Requirements;
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001764 for (const std::unique_ptr<Statement>& child : s->as<Block>().children()) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001765 result |= this->requirements(child.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001766 }
1767 return result;
1768 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001769 case Statement::Kind::kVarDeclaration: {
John Stiles3dc0da62020-08-19 17:48:31 -04001770 const VarDeclaration& var = s->as<VarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001771 return this->requirements(var.value().get());
Timothy Liang7d637782018-06-05 09:58:07 -04001772 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001773 case Statement::Kind::kExpression:
Ethan Nicholasd503a5a2020-09-30 09:29:55 -04001774 return this->requirements(s->as<ExpressionStatement>().expression().get());
Ethan Nicholase6592142020-09-08 10:22:09 -04001775 case Statement::Kind::kReturn: {
John Stiles3dc0da62020-08-19 17:48:31 -04001776 const ReturnStatement& r = s->as<ReturnStatement>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04001777 return this->requirements(r.expression().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001778 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001779 case Statement::Kind::kIf: {
John Stiles3dc0da62020-08-19 17:48:31 -04001780 const IfStatement& i = s->as<IfStatement>();
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04001781 return this->requirements(i.test().get()) |
1782 this->requirements(i.ifTrue().get()) |
1783 this->requirements(i.ifFalse().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001784 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001785 case Statement::Kind::kFor: {
John Stiles3dc0da62020-08-19 17:48:31 -04001786 const ForStatement& f = s->as<ForStatement>();
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04001787 return this->requirements(f.initializer().get()) |
1788 this->requirements(f.test().get()) |
1789 this->requirements(f.next().get()) |
1790 this->requirements(f.statement().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001791 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001792 case Statement::Kind::kWhile: {
John Stiles3dc0da62020-08-19 17:48:31 -04001793 const WhileStatement& w = s->as<WhileStatement>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04001794 return this->requirements(w.test().get()) |
1795 this->requirements(w.statement().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001796 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001797 case Statement::Kind::kDo: {
John Stiles3dc0da62020-08-19 17:48:31 -04001798 const DoStatement& d = s->as<DoStatement>();
Ethan Nicholas1fd61162020-09-28 13:14:19 -04001799 return this->requirements(d.test().get()) |
1800 this->requirements(d.statement().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001801 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001802 case Statement::Kind::kSwitch: {
John Stiles3dc0da62020-08-19 17:48:31 -04001803 const SwitchStatement& sw = s->as<SwitchStatement>();
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001804 Requirements result = this->requirements(sw.fValue.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001805 for (const auto& c : sw.fCases) {
1806 for (const auto& st : c->fStatements) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001807 result |= this->requirements(st.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001808 }
1809 }
1810 return result;
1811 }
1812 default:
1813 return kNo_Requirements;
1814 }
1815}
1816
1817MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const FunctionDeclaration& f) {
Ethan Nicholased84b732020-10-08 11:45:44 -04001818 if (f.isBuiltin()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001819 return kNo_Requirements;
1820 }
1821 auto found = fRequirements.find(&f);
1822 if (found == fRequirements.end()) {
Ethan Nicholas65a8f562019-04-19 14:00:26 -04001823 fRequirements[&f] = kNo_Requirements;
Brian Osman1179fcf2020-10-08 16:04:40 -04001824 for (const auto& e : fProgram.elements()) {
1825 if (e->is<FunctionDefinition>()) {
1826 const FunctionDefinition& def = e->as<FunctionDefinition>();
Ethan Nicholas0a5d0962020-10-14 13:33:18 -04001827 if (&def.declaration() == &f) {
1828 Requirements reqs = this->requirements(def.body().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001829 fRequirements[&f] = reqs;
1830 return reqs;
1831 }
1832 }
1833 }
1834 }
1835 return found->second;
1836}
1837
Timothy Liangb8eeb802018-07-23 16:46:16 -04001838bool MetalCodeGenerator::generateCode() {
Ethan Nicholascc305772017-10-13 16:17:45 -04001839 OutputStream* rawOut = fOut;
1840 fOut = &fHeader;
1841 fProgramKind = fProgram.fKind;
1842 this->writeHeader();
1843 this->writeUniformStruct();
1844 this->writeInputStruct();
Timothy Liang7d637782018-06-05 09:58:07 -04001845 this->writeOutputStruct();
1846 this->writeInterfaceBlocks();
Timothy Liangee84fe12018-05-18 14:38:19 -04001847 this->writeGlobalStruct();
Ethan Nicholascc305772017-10-13 16:17:45 -04001848 StringStream body;
1849 fOut = &body;
Brian Osman1179fcf2020-10-08 16:04:40 -04001850 for (const auto& e : fProgram.elements()) {
1851 this->writeProgramElement(*e);
Ethan Nicholascc305772017-10-13 16:17:45 -04001852 }
1853 fOut = rawOut;
1854
1855 write_stringstream(fHeader, *rawOut);
Chris Daltondba7aab2018-11-15 10:57:49 -05001856 write_stringstream(fExtraFunctions, *rawOut);
Ethan Nicholascc305772017-10-13 16:17:45 -04001857 write_stringstream(body, *rawOut);
Brian Osman8609a242020-09-08 14:01:49 -04001858 return 0 == fErrors.errorCount();
Ethan Nicholascc305772017-10-13 16:17:45 -04001859}
1860
John Stilesa6841be2020-08-06 14:11:56 -04001861} // namespace SkSL