blob: 50548c4449352df87b2f7fc32be5a6a47c79e757 [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"
John Stiles0023c0c2020-11-16 13:32:18 -050011#include "src/sksl/SkSLMemoryLayout.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050012#include "src/sksl/ir/SkSLExpressionStatement.h"
13#include "src/sksl/ir/SkSLExtension.h"
14#include "src/sksl/ir/SkSLIndexExpression.h"
15#include "src/sksl/ir/SkSLModifiersDeclaration.h"
16#include "src/sksl/ir/SkSLNop.h"
17#include "src/sksl/ir/SkSLVariableReference.h"
Ethan Nicholascc305772017-10-13 16:17:45 -040018
Brian Osmanc262a122020-08-06 16:34:34 -040019#include <algorithm>
20
Ethan Nicholascc305772017-10-13 16:17:45 -040021namespace SkSL {
22
John Stilescdcdb042020-07-06 09:03:51 -040023class MetalCodeGenerator::GlobalStructVisitor {
24public:
25 virtual ~GlobalStructVisitor() = default;
26 virtual void VisitInterfaceBlock(const InterfaceBlock& block, const String& blockName) = 0;
27 virtual void VisitTexture(const Type& type, const String& name) = 0;
28 virtual void VisitSampler(const Type& type, const String& name) = 0;
29 virtual void VisitVariable(const Variable& var, const Expression* value) = 0;
30};
31
Timothy Liangee84fe12018-05-18 14:38:19 -040032void MetalCodeGenerator::setupIntrinsics() {
Timothy Liang7d637782018-06-05 09:58:07 -040033#define METAL(x) std::make_pair(kMetal_IntrinsicKind, k ## x ## _MetalIntrinsic)
34#define SPECIAL(x) std::make_pair(kSpecial_IntrinsicKind, k ## x ## _SpecialIntrinsic)
Ethan Nicholas13863662019-07-29 13:05:15 -040035 fIntrinsicMap[String("sample")] = SPECIAL(Texture);
Timothy Liang651286f2018-06-07 09:55:33 -040036 fIntrinsicMap[String("mod")] = SPECIAL(Mod);
Ethan Nicholas0dc80872019-02-08 15:46:24 -050037 fIntrinsicMap[String("equal")] = METAL(Equal);
38 fIntrinsicMap[String("notEqual")] = METAL(NotEqual);
Timothy Lianga06f2152018-05-24 15:33:31 -040039 fIntrinsicMap[String("lessThan")] = METAL(LessThan);
40 fIntrinsicMap[String("lessThanEqual")] = METAL(LessThanEqual);
41 fIntrinsicMap[String("greaterThan")] = METAL(GreaterThan);
42 fIntrinsicMap[String("greaterThanEqual")] = METAL(GreaterThanEqual);
Timothy Liangee84fe12018-05-18 14:38:19 -040043}
44
Ethan Nicholascc305772017-10-13 16:17:45 -040045void MetalCodeGenerator::write(const char* s) {
46 if (!s[0]) {
47 return;
48 }
49 if (fAtLineStart) {
50 for (int i = 0; i < fIndentation; i++) {
51 fOut->writeText(" ");
52 }
53 }
54 fOut->writeText(s);
55 fAtLineStart = false;
56}
57
58void MetalCodeGenerator::writeLine(const char* s) {
59 this->write(s);
60 fOut->writeText(fLineEnding);
61 fAtLineStart = true;
62}
63
64void MetalCodeGenerator::write(const String& s) {
65 this->write(s.c_str());
66}
67
68void MetalCodeGenerator::writeLine(const String& s) {
69 this->writeLine(s.c_str());
70}
71
72void MetalCodeGenerator::writeLine() {
73 this->writeLine("");
74}
75
76void MetalCodeGenerator::writeExtension(const Extension& ext) {
Ethan Nicholasefb09e22020-09-30 10:17:00 -040077 this->writeLine("#extension " + ext.name() + " : enable");
Ethan Nicholascc305772017-10-13 16:17:45 -040078}
79
Ethan Nicholas45fa8102020-01-13 10:58:49 -050080String MetalCodeGenerator::typeName(const Type& type) {
Ethan Nicholase6592142020-09-08 10:22:09 -040081 switch (type.typeKind()) {
82 case Type::TypeKind::kVector:
Ethan Nicholas45fa8102020-01-13 10:58:49 -050083 return this->typeName(type.componentType()) + to_string(type.columns());
Ethan Nicholase6592142020-09-08 10:22:09 -040084 case Type::TypeKind::kMatrix:
Ethan Nicholas45fa8102020-01-13 10:58:49 -050085 return this->typeName(type.componentType()) + to_string(type.columns()) + "x" +
86 to_string(type.rows());
Ethan Nicholase6592142020-09-08 10:22:09 -040087 case Type::TypeKind::kSampler:
Ethan Nicholas45fa8102020-01-13 10:58:49 -050088 return "texture2d<float>"; // FIXME - support other texture types;
Ethan Nicholascc305772017-10-13 16:17:45 -040089 default:
Timothy Liang43d225f2018-07-19 15:27:13 -040090 if (type == *fContext.fHalf_Type) {
91 // FIXME - Currently only supporting floats in MSL to avoid type coercion issues.
Ethan Nicholas45fa8102020-01-13 10:58:49 -050092 return fContext.fFloat_Type->name();
Timothy Liang43d225f2018-07-19 15:27:13 -040093 } else if (type == *fContext.fByte_Type) {
Ethan Nicholas45fa8102020-01-13 10:58:49 -050094 return "char";
Timothy Liang43d225f2018-07-19 15:27:13 -040095 } else if (type == *fContext.fUByte_Type) {
Ethan Nicholas45fa8102020-01-13 10:58:49 -050096 return "uchar";
Timothy Liang7d637782018-06-05 09:58:07 -040097 } else {
Ethan Nicholas45fa8102020-01-13 10:58:49 -050098 return type.name();
Timothy Liang7d637782018-06-05 09:58:07 -040099 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400100 }
101}
102
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500103void MetalCodeGenerator::writeType(const Type& type) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400104 if (type.typeKind() == Type::TypeKind::kStruct) {
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500105 for (const Type* search : fWrittenStructs) {
106 if (*search == type) {
107 // already written
108 this->write(type.name());
109 return;
110 }
111 }
112 fWrittenStructs.push_back(&type);
113 this->writeLine("struct " + type.name() + " {");
114 fIndentation++;
115 this->writeFields(type.fields(), type.fOffset);
116 fIndentation--;
117 this->write("}");
118 } else {
119 this->write(this->typeName(type));
120 }
121}
122
Ethan Nicholascc305772017-10-13 16:17:45 -0400123void MetalCodeGenerator::writeExpression(const Expression& expr, Precedence parentPrecedence) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400124 switch (expr.kind()) {
125 case Expression::Kind::kBinary:
John Stiles81365af2020-08-18 09:24:00 -0400126 this->writeBinaryExpression(expr.as<BinaryExpression>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400127 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400128 case Expression::Kind::kBoolLiteral:
John Stiles81365af2020-08-18 09:24:00 -0400129 this->writeBoolLiteral(expr.as<BoolLiteral>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400130 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400131 case Expression::Kind::kConstructor:
John Stiles81365af2020-08-18 09:24:00 -0400132 this->writeConstructor(expr.as<Constructor>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400133 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400134 case Expression::Kind::kIntLiteral:
John Stiles81365af2020-08-18 09:24:00 -0400135 this->writeIntLiteral(expr.as<IntLiteral>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400136 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400137 case Expression::Kind::kFieldAccess:
John Stiles81365af2020-08-18 09:24:00 -0400138 this->writeFieldAccess(expr.as<FieldAccess>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400139 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400140 case Expression::Kind::kFloatLiteral:
John Stiles81365af2020-08-18 09:24:00 -0400141 this->writeFloatLiteral(expr.as<FloatLiteral>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400142 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400143 case Expression::Kind::kFunctionCall:
John Stiles81365af2020-08-18 09:24:00 -0400144 this->writeFunctionCall(expr.as<FunctionCall>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400145 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400146 case Expression::Kind::kPrefix:
John Stiles81365af2020-08-18 09:24:00 -0400147 this->writePrefixExpression(expr.as<PrefixExpression>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400148 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400149 case Expression::Kind::kPostfix:
John Stiles81365af2020-08-18 09:24:00 -0400150 this->writePostfixExpression(expr.as<PostfixExpression>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400151 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400152 case Expression::Kind::kSetting:
John Stiles81365af2020-08-18 09:24:00 -0400153 this->writeSetting(expr.as<Setting>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400154 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400155 case Expression::Kind::kSwizzle:
John Stiles81365af2020-08-18 09:24:00 -0400156 this->writeSwizzle(expr.as<Swizzle>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400157 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400158 case Expression::Kind::kVariableReference:
John Stiles81365af2020-08-18 09:24:00 -0400159 this->writeVariableReference(expr.as<VariableReference>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400160 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400161 case Expression::Kind::kTernary:
John Stiles81365af2020-08-18 09:24:00 -0400162 this->writeTernaryExpression(expr.as<TernaryExpression>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400163 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400164 case Expression::Kind::kIndex:
John Stiles81365af2020-08-18 09:24:00 -0400165 this->writeIndexExpression(expr.as<IndexExpression>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400166 break;
167 default:
Ethan Nicholas2a099da2020-01-02 14:40:54 -0500168#ifdef SK_DEBUG
Ethan Nicholascc305772017-10-13 16:17:45 -0400169 ABORT("unsupported expression: %s", expr.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -0500170#endif
171 break;
Ethan Nicholascc305772017-10-13 16:17:45 -0400172 }
173}
174
Timothy Liang6403b0e2018-05-17 10:40:04 -0400175void MetalCodeGenerator::writeIntrinsicCall(const FunctionCall& c) {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400176 auto i = fIntrinsicMap.find(c.function().name());
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400177 SkASSERT(i != fIntrinsicMap.end());
Timothy Liang7d637782018-06-05 09:58:07 -0400178 Intrinsic intrinsic = i->second;
179 int32_t intrinsicId = intrinsic.second;
180 switch (intrinsic.first) {
Timothy Liang6403b0e2018-05-17 10:40:04 -0400181 case kSpecial_IntrinsicKind:
182 return this->writeSpecialIntrinsic(c, (SpecialIntrinsic) intrinsicId);
Timothy Lianga06f2152018-05-24 15:33:31 -0400183 break;
184 case kMetal_IntrinsicKind:
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400185 this->writeExpression(*c.arguments()[0], kSequence_Precedence);
Timothy Lianga06f2152018-05-24 15:33:31 -0400186 switch ((MetalIntrinsic) intrinsicId) {
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500187 case kEqual_MetalIntrinsic:
188 this->write(" == ");
189 break;
190 case kNotEqual_MetalIntrinsic:
191 this->write(" != ");
192 break;
Timothy Lianga06f2152018-05-24 15:33:31 -0400193 case kLessThan_MetalIntrinsic:
194 this->write(" < ");
195 break;
196 case kLessThanEqual_MetalIntrinsic:
197 this->write(" <= ");
198 break;
199 case kGreaterThan_MetalIntrinsic:
200 this->write(" > ");
201 break;
202 case kGreaterThanEqual_MetalIntrinsic:
203 this->write(" >= ");
204 break;
205 default:
206 ABORT("unsupported metal intrinsic kind");
207 }
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400208 this->writeExpression(*c.arguments()[1], kSequence_Precedence);
Timothy Lianga06f2152018-05-24 15:33:31 -0400209 break;
Timothy Liang6403b0e2018-05-17 10:40:04 -0400210 default:
211 ABORT("unsupported intrinsic kind");
212 }
213}
214
Ethan Nicholascc305772017-10-13 16:17:45 -0400215void MetalCodeGenerator::writeFunctionCall(const FunctionCall& c) {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400216 const FunctionDeclaration& function = c.function();
John Stiles8e3b6be2020-10-13 11:14:08 -0400217 const ExpressionArray& arguments = c.arguments();
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400218 const auto& entry = fIntrinsicMap.find(function.name());
Timothy Liang6403b0e2018-05-17 10:40:04 -0400219 if (entry != fIntrinsicMap.end()) {
220 this->writeIntrinsicCall(c);
221 return;
222 }
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400223 const StringFragment& name = function.name();
Ethan Nicholased84b732020-10-08 11:45:44 -0400224 bool builtin = function.isBuiltin();
225 if (builtin && name == "atan" && arguments.size() == 2) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400226 this->write("atan2");
Ethan Nicholased84b732020-10-08 11:45:44 -0400227 } else if (builtin && name == "inversesqrt") {
Timothy Lianga06f2152018-05-24 15:33:31 -0400228 this->write("rsqrt");
Ethan Nicholased84b732020-10-08 11:45:44 -0400229 } else if (builtin && name == "inverse") {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400230 SkASSERT(arguments.size() == 1);
231 this->writeInverseHack(*arguments[0]);
John Stilesa80a3dc2020-10-20 10:24:56 -0400232 } else if (builtin && name == "frexp") {
233 // Our Metal codegen assumes that out params are pointers, but Metal's built-in frexp
234 // actually takes a reference for the exponent, not a pointer. We add in a helper function
235 // here to translate.
236 SkASSERT(arguments.size() == 2);
237 auto [iter, newlyCreated] = fHelpers.insert("frexp");
238 if (newlyCreated) {
239 fExtraFunctions.printf(
240 "float frexp(float arg, thread int* exp) { return frexp(arg, *exp); }\n");
241 }
242 this->write("frexp");
Ethan Nicholased84b732020-10-08 11:45:44 -0400243 } else if (builtin && name == "dFdx") {
Timothy Liang7d637782018-06-05 09:58:07 -0400244 this->write("dfdx");
Ethan Nicholased84b732020-10-08 11:45:44 -0400245 } else if (builtin && name == "dFdy") {
Chris Daltonb8af5ad2019-02-25 14:54:21 -0700246 // Flipping Y also negates the Y derivatives.
247 this->write((fProgram.fSettings.fFlipY) ? "-dfdy" : "dfdy");
Ethan Nicholascc305772017-10-13 16:17:45 -0400248 } else {
Ethan Nicholase2c49992020-10-05 11:49:11 -0400249 this->writeName(name);
Ethan Nicholascc305772017-10-13 16:17:45 -0400250 }
251 this->write("(");
252 const char* separator = "";
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400253 if (this->requirements(function) & kInputs_Requirement) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400254 this->write("_in");
255 separator = ", ";
256 }
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400257 if (this->requirements(function) & kOutputs_Requirement) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400258 this->write(separator);
259 this->write("_out");
260 separator = ", ";
261 }
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400262 if (this->requirements(function) & kUniforms_Requirement) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400263 this->write(separator);
264 this->write("_uniforms");
265 separator = ", ";
266 }
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400267 if (this->requirements(function) & kGlobals_Requirement) {
Timothy Liangee84fe12018-05-18 14:38:19 -0400268 this->write(separator);
269 this->write("_globals");
270 separator = ", ";
271 }
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400272 if (this->requirements(function) & kFragCoord_Requirement) {
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -0400273 this->write(separator);
274 this->write("_fragCoord");
275 separator = ", ";
276 }
Brian Osman5bf3e202020-10-13 10:34:18 -0400277 const std::vector<const Variable*>& parameters = function.parameters();
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400278 for (size_t i = 0; i < arguments.size(); ++i) {
279 const Expression& arg = *arguments[i];
Ethan Nicholascc305772017-10-13 16:17:45 -0400280 this->write(separator);
281 separator = ", ";
Ethan Nicholased84b732020-10-08 11:45:44 -0400282 if (parameters[i]->modifiers().fFlags & Modifiers::kOut_Flag) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400283 this->write("&");
284 }
285 this->writeExpression(arg, kSequence_Precedence);
286 }
287 this->write(")");
288}
289
Chris Daltondba7aab2018-11-15 10:57:49 -0500290void MetalCodeGenerator::writeInverseHack(const Expression& mat) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400291 const Type& type = mat.type();
292 const String& typeName = type.name();
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500293 String name = typeName + "_inverse";
Ethan Nicholas30d30222020-09-11 12:27:26 -0400294 if (type == *fContext.fFloat2x2_Type || type == *fContext.fHalf2x2_Type) {
Chris Daltondba7aab2018-11-15 10:57:49 -0500295 if (fWrittenIntrinsics.find(name) == fWrittenIntrinsics.end()) {
296 fWrittenIntrinsics.insert(name);
297 fExtraFunctions.writeText((
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500298 typeName + " " + name + "(" + typeName + " m) {"
Chris Daltondba7aab2018-11-15 10:57:49 -0500299 " return float2x2(m[1][1], -m[0][1], -m[1][0], m[0][0]) * (1/determinant(m));"
300 "}"
301 ).c_str());
302 }
303 }
Ethan Nicholas30d30222020-09-11 12:27:26 -0400304 else if (type == *fContext.fFloat3x3_Type || type == *fContext.fHalf3x3_Type) {
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500305 if (fWrittenIntrinsics.find(name) == fWrittenIntrinsics.end()) {
306 fWrittenIntrinsics.insert(name);
307 fExtraFunctions.writeText((
308 typeName + " " + name + "(" + typeName + " m) {"
309 " float a00 = m[0][0], a01 = m[0][1], a02 = m[0][2];"
310 " float a10 = m[1][0], a11 = m[1][1], a12 = m[1][2];"
311 " float a20 = m[2][0], a21 = m[2][1], a22 = m[2][2];"
312 " float b01 = a22 * a11 - a12 * a21;"
313 " float b11 = -a22 * a10 + a12 * a20;"
314 " float b21 = a21 * a10 - a11 * a20;"
315 " float det = a00 * b01 + a01 * b11 + a02 * b21;"
316 " return " + typeName +
317 " (b01, (-a22 * a01 + a02 * a21), (a12 * a01 - a02 * a11),"
318 " b11, (a22 * a00 - a02 * a20), (-a12 * a00 + a02 * a10),"
319 " b21, (-a21 * a00 + a01 * a20), (a11 * a00 - a01 * a10)) * "
320 " (1/det);"
321 "}"
322 ).c_str());
323 }
324 }
Ethan Nicholas30d30222020-09-11 12:27:26 -0400325 else if (type == *fContext.fFloat4x4_Type || type == *fContext.fHalf4x4_Type) {
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500326 if (fWrittenIntrinsics.find(name) == fWrittenIntrinsics.end()) {
327 fWrittenIntrinsics.insert(name);
328 fExtraFunctions.writeText((
329 typeName + " " + name + "(" + typeName + " m) {"
330 " float a00 = m[0][0], a01 = m[0][1], a02 = m[0][2], a03 = m[0][3];"
331 " float a10 = m[1][0], a11 = m[1][1], a12 = m[1][2], a13 = m[1][3];"
332 " float a20 = m[2][0], a21 = m[2][1], a22 = m[2][2], a23 = m[2][3];"
333 " float a30 = m[3][0], a31 = m[3][1], a32 = m[3][2], a33 = m[3][3];"
334 " float b00 = a00 * a11 - a01 * a10;"
335 " float b01 = a00 * a12 - a02 * a10;"
336 " float b02 = a00 * a13 - a03 * a10;"
337 " float b03 = a01 * a12 - a02 * a11;"
338 " float b04 = a01 * a13 - a03 * a11;"
339 " float b05 = a02 * a13 - a03 * a12;"
340 " float b06 = a20 * a31 - a21 * a30;"
341 " float b07 = a20 * a32 - a22 * a30;"
342 " float b08 = a20 * a33 - a23 * a30;"
343 " float b09 = a21 * a32 - a22 * a31;"
344 " float b10 = a21 * a33 - a23 * a31;"
345 " float b11 = a22 * a33 - a23 * a32;"
346 " float det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - "
347 " b04 * b07 + b05 * b06;"
348 " return " + typeName + "(a11 * b11 - a12 * b10 + a13 * b09,"
349 " a02 * b10 - a01 * b11 - a03 * b09,"
350 " a31 * b05 - a32 * b04 + a33 * b03,"
351 " a22 * b04 - a21 * b05 - a23 * b03,"
352 " a12 * b08 - a10 * b11 - a13 * b07,"
353 " a00 * b11 - a02 * b08 + a03 * b07,"
354 " a32 * b02 - a30 * b05 - a33 * b01,"
355 " a20 * b05 - a22 * b02 + a23 * b01,"
356 " a10 * b10 - a11 * b08 + a13 * b06,"
357 " a01 * b08 - a00 * b10 - a03 * b06,"
358 " a30 * b04 - a31 * b02 + a33 * b00,"
359 " a21 * b02 - a20 * b04 - a23 * b00,"
360 " a11 * b07 - a10 * b09 - a12 * b06,"
361 " a00 * b09 - a01 * b07 + a02 * b06,"
362 " a31 * b01 - a30 * b03 - a32 * b00,"
363 " a20 * b03 - a21 * b01 + a22 * b00) / det;"
364 "}"
365 ).c_str());
366 }
367 }
Chris Daltondba7aab2018-11-15 10:57:49 -0500368 this->write(name);
369}
370
Timothy Liang6403b0e2018-05-17 10:40:04 -0400371void MetalCodeGenerator::writeSpecialIntrinsic(const FunctionCall & c, SpecialIntrinsic kind) {
John Stiles8e3b6be2020-10-13 11:14:08 -0400372 const ExpressionArray& arguments = c.arguments();
Timothy Liang6403b0e2018-05-17 10:40:04 -0400373 switch (kind) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400374 case kTexture_SpecialIntrinsic: {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400375 this->writeExpression(*arguments[0], kSequence_Precedence);
Timothy Lianga06f2152018-05-24 15:33:31 -0400376 this->write(".sample(");
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400377 this->writeExpression(*arguments[0], kSequence_Precedence);
Timothy Lianga06f2152018-05-24 15:33:31 -0400378 this->write(SAMPLER_SUFFIX);
379 this->write(", ");
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400380 const Type& arg1Type = arguments[1]->type();
Ethan Nicholas30d30222020-09-11 12:27:26 -0400381 if (arg1Type == *fContext.fFloat3_Type) {
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500382 // have to store the vector in a temp variable to avoid double evaluating it
383 String tmpVar = "tmpCoord" + to_string(fVarCount++);
Ethan Nicholas30d30222020-09-11 12:27:26 -0400384 this->fFunctionHeader += " " + this->typeName(arg1Type) + " " + tmpVar + ";\n";
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500385 this->write("(" + tmpVar + " = ");
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400386 this->writeExpression(*arguments[1], kSequence_Precedence);
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500387 this->write(", " + tmpVar + ".xy / " + tmpVar + ".z))");
Timothy Liangee84fe12018-05-18 14:38:19 -0400388 } else {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400389 SkASSERT(arg1Type == *fContext.fFloat2_Type);
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400390 this->writeExpression(*arguments[1], kSequence_Precedence);
Timothy Liangee84fe12018-05-18 14:38:19 -0400391 this->write(")");
392 }
Timothy Liang6403b0e2018-05-17 10:40:04 -0400393 break;
Ethan Nicholas30d30222020-09-11 12:27:26 -0400394 }
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500395 case kMod_SpecialIntrinsic: {
Timothy Liang651286f2018-06-07 09:55:33 -0400396 // 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 -0500397 String tmpX = "tmpX" + to_string(fVarCount++);
398 String tmpY = "tmpY" + to_string(fVarCount++);
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400399 this->fFunctionHeader += " " + this->typeName(arguments[0]->type()) +
Ethan Nicholas30d30222020-09-11 12:27:26 -0400400 " " + tmpX + ", " + tmpY + ";\n";
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500401 this->write("(" + tmpX + " = ");
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400402 this->writeExpression(*arguments[0], kSequence_Precedence);
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500403 this->write(", " + tmpY + " = ");
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400404 this->writeExpression(*arguments[1], kSequence_Precedence);
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500405 this->write(", " + tmpX + " - " + tmpY + " * floor(" + tmpX + " / " + tmpY + "))");
Timothy Liang651286f2018-06-07 09:55:33 -0400406 break;
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500407 }
Timothy Liang6403b0e2018-05-17 10:40:04 -0400408 default:
409 ABORT("unsupported special intrinsic kind");
410 }
411}
412
John Stilesfcf8cb22020-08-06 14:29:22 -0400413// Assembles a matrix of type floatRxC by resizing another matrix named `x0`.
414// Cells that don't exist in the source matrix will be populated with identity-matrix values.
415void MetalCodeGenerator::assembleMatrixFromMatrix(const Type& sourceMatrix, int rows, int columns) {
416 SkASSERT(rows <= 4);
417 SkASSERT(columns <= 4);
418
419 const char* columnSeparator = "";
420 for (int c = 0; c < columns; ++c) {
421 fExtraFunctions.printf("%sfloat%d(", columnSeparator, rows);
422 columnSeparator = "), ";
423
424 // Determine how many values to take from the source matrix for this row.
425 int swizzleLength = 0;
426 if (c < sourceMatrix.columns()) {
427 swizzleLength = std::min<>(rows, sourceMatrix.rows());
428 }
429
430 // Emit all the values from the source matrix row.
431 bool firstItem;
432 switch (swizzleLength) {
433 case 0: firstItem = true; break;
434 case 1: firstItem = false; fExtraFunctions.printf("x0[%d].x", c); break;
435 case 2: firstItem = false; fExtraFunctions.printf("x0[%d].xy", c); break;
436 case 3: firstItem = false; fExtraFunctions.printf("x0[%d].xyz", c); break;
437 case 4: firstItem = false; fExtraFunctions.printf("x0[%d].xyzw", c); break;
438 default: SkUNREACHABLE;
439 }
440
441 // Emit the placeholder identity-matrix cells.
442 for (int r = swizzleLength; r < rows; ++r) {
443 fExtraFunctions.printf("%s%s", firstItem ? "" : ", ", (r == c) ? "1.0" : "0.0");
444 firstItem = false;
445 }
446 }
447
448 fExtraFunctions.writeText(")");
449}
450
451// Assembles a matrix of type floatRxC by concatenating an arbitrary mix of values, named `x0`,
452// `x1`, etc. An error is written if the expression list don't contain exactly R*C scalars.
John Stiles8e3b6be2020-10-13 11:14:08 -0400453void MetalCodeGenerator::assembleMatrixFromExpressions(const ExpressionArray& args,
454 int rows, int columns) {
John Stilesfcf8cb22020-08-06 14:29:22 -0400455 size_t argIndex = 0;
456 int argPosition = 0;
457
458 const char* columnSeparator = "";
459 for (int c = 0; c < columns; ++c) {
460 fExtraFunctions.printf("%sfloat%d(", columnSeparator, rows);
461 columnSeparator = "), ";
462
463 const char* rowSeparator = "";
464 for (int r = 0; r < rows; ++r) {
465 fExtraFunctions.writeText(rowSeparator);
466 rowSeparator = ", ";
467
468 if (argIndex < args.size()) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400469 const Type& argType = args[argIndex]->type();
Ethan Nicholase6592142020-09-08 10:22:09 -0400470 switch (argType.typeKind()) {
471 case Type::TypeKind::kScalar: {
John Stilesfcf8cb22020-08-06 14:29:22 -0400472 fExtraFunctions.printf("x%zu", argIndex);
473 break;
474 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400475 case Type::TypeKind::kVector: {
John Stilesfcf8cb22020-08-06 14:29:22 -0400476 fExtraFunctions.printf("x%zu[%d]", argIndex, argPosition);
477 break;
478 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400479 case Type::TypeKind::kMatrix: {
John Stilesfcf8cb22020-08-06 14:29:22 -0400480 fExtraFunctions.printf("x%zu[%d][%d]", argIndex,
481 argPosition / argType.rows(),
482 argPosition % argType.rows());
483 break;
484 }
485 default: {
486 SkDEBUGFAIL("incorrect type of argument for matrix constructor");
487 fExtraFunctions.writeText("<error>");
488 break;
489 }
490 }
491
492 ++argPosition;
493 if (argPosition >= argType.columns() * argType.rows()) {
494 ++argIndex;
495 argPosition = 0;
496 }
497 } else {
498 SkDEBUGFAIL("not enough arguments for matrix constructor");
499 fExtraFunctions.writeText("<error>");
500 }
501 }
502 }
503
504 if (argPosition != 0 || argIndex != args.size()) {
505 SkDEBUGFAIL("incorrect number of arguments for matrix constructor");
506 fExtraFunctions.writeText(", <error>");
507 }
508
509 fExtraFunctions.writeText(")");
510}
511
John Stiles1bdafbf2020-05-28 12:17:20 -0400512// Generates a constructor for 'matrix' which reorganizes the input arguments into the proper shape.
513// Keeps track of previously generated constructors so that we won't generate more than one
514// constructor for any given permutation of input argument types. Returns the name of the
515// generated constructor method.
516String MetalCodeGenerator::getMatrixConstructHelper(const Constructor& c) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400517 const Type& matrix = c.type();
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500518 int columns = matrix.columns();
519 int rows = matrix.rows();
John Stiles8e3b6be2020-10-13 11:14:08 -0400520 const ExpressionArray& args = c.arguments();
John Stiles1bdafbf2020-05-28 12:17:20 -0400521
522 // Create the helper-method name and use it as our lookup key.
523 String name;
524 name.appendf("float%dx%d_from", columns, rows);
525 for (const std::unique_ptr<Expression>& expr : args) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400526 name.appendf("_%s", expr->type().displayName().c_str());
John Stiles1bdafbf2020-05-28 12:17:20 -0400527 }
528
529 // If a helper-method has already been synthesized, we don't need to synthesize it again.
530 auto [iter, newlyCreated] = fHelpers.insert(name);
531 if (!newlyCreated) {
532 return name;
533 }
534
535 // Unlike GLSL, Metal requires that matrices are initialized with exactly R vectors of C
536 // components apiece. (In Metal 2.0, you can also supply R*C scalars, but you still cannot
537 // supply a mixture of scalars and vectors.)
538 fExtraFunctions.printf("float%dx%d %s(", columns, rows, name.c_str());
539
540 size_t argIndex = 0;
541 const char* argSeparator = "";
John Stilesfcf8cb22020-08-06 14:29:22 -0400542 for (const std::unique_ptr<Expression>& expr : args) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400543 fExtraFunctions.printf("%s%s x%zu", argSeparator,
Ethan Nicholas30d30222020-09-11 12:27:26 -0400544 expr->type().displayName().c_str(), argIndex++);
John Stiles1bdafbf2020-05-28 12:17:20 -0400545 argSeparator = ", ";
546 }
547
548 fExtraFunctions.printf(") {\n return float%dx%d(", columns, rows);
549
Ethan Nicholas30d30222020-09-11 12:27:26 -0400550 if (args.size() == 1 && args.front()->type().typeKind() == Type::TypeKind::kMatrix) {
551 this->assembleMatrixFromMatrix(args.front()->type(), rows, columns);
John Stilesfcf8cb22020-08-06 14:29:22 -0400552 } else {
553 this->assembleMatrixFromExpressions(args, rows, columns);
John Stiles1bdafbf2020-05-28 12:17:20 -0400554 }
555
John Stilesfcf8cb22020-08-06 14:29:22 -0400556 fExtraFunctions.writeText(");\n}\n");
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500557 return name;
558}
559
560bool MetalCodeGenerator::canCoerce(const Type& t1, const Type& t2) {
561 if (t1.columns() != t2.columns() || t1.rows() != t2.rows()) {
562 return false;
563 }
564 if (t1.columns() > 1) {
565 return this->canCoerce(t1.componentType(), t2.componentType());
566 }
Ethan Nicholase1f55022019-02-05 17:17:40 -0500567 return t1.isFloat() && t2.isFloat();
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500568}
569
John Stiles1bdafbf2020-05-28 12:17:20 -0400570bool MetalCodeGenerator::matrixConstructHelperIsNeeded(const Constructor& c) {
571 // A matrix construct helper is only necessary if we are, in fact, constructing a matrix.
Ethan Nicholas30d30222020-09-11 12:27:26 -0400572 if (c.type().typeKind() != Type::TypeKind::kMatrix) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400573 return false;
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500574 }
John Stiles1bdafbf2020-05-28 12:17:20 -0400575
576 // GLSL is fairly free-form about inputs to its matrix constructors, but Metal is not; it
577 // expects exactly R vectors of C components apiece. (Metal 2.0 also allows a list of R*C
578 // scalars.) Some cases are simple to translate and so we handle those inline--e.g. a list of
579 // scalars can be constructed trivially. In more complex cases, we generate a helper function
580 // that converts our inputs into a properly-shaped matrix.
581 // A matrix construct helper method is always used if any input argument is a matrix.
582 // Helper methods are also necessary when any argument would span multiple rows. For instance:
583 //
584 // float2 x = (1, 2);
585 // float3x2(x, 3, 4, 5, 6) = | 1 3 5 | = no helper needed; conversion can be done inline
586 // | 2 4 6 |
587 //
588 // float2 x = (2, 3);
589 // float3x2(1, x, 4, 5, 6) = | 1 3 5 | = x spans multiple rows; a helper method will be used
590 // | 2 4 6 |
591 //
592 // float4 x = (1, 2, 3, 4);
593 // float2x2(x) = | 1 3 | = x spans multiple rows; a helper method will be used
594 // | 2 4 |
595 //
596
597 int position = 0;
Ethan Nicholasf70f0442020-09-29 12:41:35 -0400598 for (const std::unique_ptr<Expression>& expr : c.arguments()) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400599 // If an input argument is a matrix, we need a helper function.
Ethan Nicholas30d30222020-09-11 12:27:26 -0400600 if (expr->type().typeKind() == Type::TypeKind::kMatrix) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400601 return true;
602 }
Ethan Nicholas30d30222020-09-11 12:27:26 -0400603 position += expr->type().columns();
604 if (position > c.type().rows()) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400605 // An input argument would span multiple rows; a helper function is required.
606 return true;
607 }
Ethan Nicholas30d30222020-09-11 12:27:26 -0400608 if (position == c.type().rows()) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400609 // We've advanced to the end of a row. Wrap to the start of the next row.
610 position = 0;
611 }
612 }
613
614 return false;
615}
616
617void MetalCodeGenerator::writeConstructor(const Constructor& c, Precedence parentPrecedence) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400618 const Type& constructorType = c.type();
John Stiles1bdafbf2020-05-28 12:17:20 -0400619 // Handle special cases for single-argument constructors.
Ethan Nicholasf70f0442020-09-29 12:41:35 -0400620 if (c.arguments().size() == 1) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400621 // If the type is coercible, emit it directly.
Ethan Nicholasf70f0442020-09-29 12:41:35 -0400622 const Expression& arg = *c.arguments().front();
Ethan Nicholas30d30222020-09-11 12:27:26 -0400623 const Type& argType = arg.type();
624 if (this->canCoerce(constructorType, argType)) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400625 this->writeExpression(arg, parentPrecedence);
626 return;
627 }
628
629 // Metal supports creating matrices with a scalar on the diagonal via the single-argument
630 // matrix constructor.
Ethan Nicholas30d30222020-09-11 12:27:26 -0400631 if (constructorType.typeKind() == Type::TypeKind::kMatrix && argType.isNumber()) {
632 const Type& matrix = constructorType;
John Stiles1bdafbf2020-05-28 12:17:20 -0400633 this->write("float");
634 this->write(to_string(matrix.columns()));
635 this->write("x");
636 this->write(to_string(matrix.rows()));
637 this->write("(");
638 this->writeExpression(arg, parentPrecedence);
639 this->write(")");
640 return;
641 }
642 }
643
644 // Emit and invoke a matrix-constructor helper method if one is necessary.
645 if (this->matrixConstructHelperIsNeeded(c)) {
646 this->write(this->getMatrixConstructHelper(c));
John Stiles1fa15b12020-05-28 17:36:54 +0000647 this->write("(");
648 const char* separator = "";
Ethan Nicholasf70f0442020-09-29 12:41:35 -0400649 for (const std::unique_ptr<Expression>& expr : c.arguments()) {
John Stiles1fa15b12020-05-28 17:36:54 +0000650 this->write(separator);
651 separator = ", ";
John Stiles1bdafbf2020-05-28 12:17:20 -0400652 this->writeExpression(*expr, kSequence_Precedence);
John Stilesdaa573e2020-05-28 12:17:20 -0400653 }
John Stiles1fa15b12020-05-28 17:36:54 +0000654 this->write(")");
John Stiles1bdafbf2020-05-28 12:17:20 -0400655 return;
John Stilesdaa573e2020-05-28 12:17:20 -0400656 }
John Stiles1bdafbf2020-05-28 12:17:20 -0400657
658 // Explicitly invoke the constructor, passing in the necessary arguments.
Ethan Nicholas30d30222020-09-11 12:27:26 -0400659 this->writeType(constructorType);
John Stiles1bdafbf2020-05-28 12:17:20 -0400660 this->write("(");
661 const char* separator = "";
662 int scalarCount = 0;
Ethan Nicholasf70f0442020-09-29 12:41:35 -0400663 for (const std::unique_ptr<Expression>& arg : c.arguments()) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400664 const Type& argType = arg->type();
John Stiles1bdafbf2020-05-28 12:17:20 -0400665 this->write(separator);
666 separator = ", ";
Ethan Nicholas30d30222020-09-11 12:27:26 -0400667 if (constructorType.typeKind() == Type::TypeKind::kMatrix &&
668 argType.columns() < constructorType.rows()) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400669 // Merge scalars and smaller vectors together.
670 if (!scalarCount) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400671 this->writeType(constructorType.componentType());
672 this->write(to_string(constructorType.rows()));
John Stiles1bdafbf2020-05-28 12:17:20 -0400673 this->write("(");
674 }
Ethan Nicholas30d30222020-09-11 12:27:26 -0400675 scalarCount += argType.columns();
John Stiles1bdafbf2020-05-28 12:17:20 -0400676 }
677 this->writeExpression(*arg, kSequence_Precedence);
Ethan Nicholas30d30222020-09-11 12:27:26 -0400678 if (scalarCount && scalarCount == constructorType.rows()) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400679 this->write(")");
680 scalarCount = 0;
681 }
682 }
683 this->write(")");
Ethan Nicholascc305772017-10-13 16:17:45 -0400684}
685
686void MetalCodeGenerator::writeFragCoord() {
Ethan Nicholasf931e402019-07-26 15:40:33 -0400687 if (fRTHeightName.length()) {
688 this->write("float4(_fragCoord.x, ");
689 this->write(fRTHeightName.c_str());
690 this->write(" - _fragCoord.y, 0.0, _fragCoord.w)");
Jim Van Verth6bc650e2019-02-07 14:53:23 -0500691 } else {
692 this->write("float4(_fragCoord.x, _fragCoord.y, 0.0, _fragCoord.w)");
693 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400694}
695
696void MetalCodeGenerator::writeVariableReference(const VariableReference& ref) {
Ethan Nicholas78686922020-10-08 06:46:27 -0400697 switch (ref.variable()->modifiers().fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400698 case SK_FRAGCOLOR_BUILTIN:
Timothy Liang7d637782018-06-05 09:58:07 -0400699 this->write("_out->sk_FragColor");
Ethan Nicholascc305772017-10-13 16:17:45 -0400700 break;
Timothy Liang6403b0e2018-05-17 10:40:04 -0400701 case SK_FRAGCOORD_BUILTIN:
702 this->writeFragCoord();
703 break;
Timothy Liangdc89f192018-06-13 09:20:31 -0400704 case SK_VERTEXID_BUILTIN:
705 this->write("sk_VertexID");
706 break;
707 case SK_INSTANCEID_BUILTIN:
708 this->write("sk_InstanceID");
709 break;
Timothy Liang7b8875d2018-08-10 09:42:31 -0400710 case SK_CLOCKWISE_BUILTIN:
711 // We'd set the front facing winding in the MTLRenderCommandEncoder to be counter
Brian Salomonf4ba4ec2020-03-19 15:54:28 -0400712 // clockwise to match Skia convention.
Timothy Liang7b8875d2018-08-10 09:42:31 -0400713 this->write(fProgram.fSettings.fFlipY ? "_frontFacing" : "(!_frontFacing)");
714 break;
Ethan Nicholascc305772017-10-13 16:17:45 -0400715 default:
Ethan Nicholas78686922020-10-08 06:46:27 -0400716 const Variable& var = *ref.variable();
Ethan Nicholas453f67f2020-10-09 10:43:45 -0400717 if (var.storage() == Variable::Storage::kGlobal) {
Ethan Nicholas78686922020-10-08 06:46:27 -0400718 if (var.modifiers().fFlags & Modifiers::kIn_Flag) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400719 this->write("_in.");
Ethan Nicholas78686922020-10-08 06:46:27 -0400720 } else if (var.modifiers().fFlags & Modifiers::kOut_Flag) {
Timothy Liangee84fe12018-05-18 14:38:19 -0400721 this->write("_out->");
Ethan Nicholas78686922020-10-08 06:46:27 -0400722 } else if (var.modifiers().fFlags & Modifiers::kUniform_Flag &&
723 var.type().typeKind() != Type::TypeKind::kSampler) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400724 this->write("_uniforms.");
725 } else {
Timothy Liangee84fe12018-05-18 14:38:19 -0400726 this->write("_globals->");
Ethan Nicholascc305772017-10-13 16:17:45 -0400727 }
728 }
Ethan Nicholas78686922020-10-08 06:46:27 -0400729 this->writeName(var.name());
Ethan Nicholascc305772017-10-13 16:17:45 -0400730 }
731}
732
733void MetalCodeGenerator::writeIndexExpression(const IndexExpression& expr) {
Ethan Nicholas2a4952d2020-10-08 15:35:56 -0400734 this->writeExpression(*expr.base(), kPostfix_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400735 this->write("[");
Ethan Nicholas2a4952d2020-10-08 15:35:56 -0400736 this->writeExpression(*expr.index(), kTopLevel_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400737 this->write("]");
738}
739
740void MetalCodeGenerator::writeFieldAccess(const FieldAccess& f) {
Ethan Nicholas7a95b202020-10-09 11:55:40 -0400741 const Type::Field* field = &f.base()->type().fields()[f.fieldIndex()];
742 if (FieldAccess::OwnerKind::kDefault == f.ownerKind()) {
743 this->writeExpression(*f.base(), kPostfix_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400744 this->write(".");
745 }
Timothy Liang7d637782018-06-05 09:58:07 -0400746 switch (field->fModifiers.fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400747 case SK_POSITION_BUILTIN:
Timothy Liangb8eeb802018-07-23 16:46:16 -0400748 this->write("_out->sk_Position");
Ethan Nicholascc305772017-10-13 16:17:45 -0400749 break;
750 default:
Timothy Liang7d637782018-06-05 09:58:07 -0400751 if (field->fName == "sk_PointSize") {
752 this->write("_out->sk_PointSize");
753 } else {
Ethan Nicholas7a95b202020-10-09 11:55:40 -0400754 if (FieldAccess::OwnerKind::kAnonymousInterfaceBlock == f.ownerKind()) {
Timothy Liang7d637782018-06-05 09:58:07 -0400755 this->write("_globals->");
756 this->write(fInterfaceBlockNameMap[fInterfaceBlockMap[field]]);
757 this->write("->");
758 }
Timothy Liang651286f2018-06-07 09:55:33 -0400759 this->writeName(field->fName);
Timothy Lianga06f2152018-05-24 15:33:31 -0400760 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400761 }
762}
763
764void MetalCodeGenerator::writeSwizzle(const Swizzle& swizzle) {
Ethan Nicholas6b4d5812020-10-12 16:11:51 -0400765 this->writeExpression(*swizzle.base(), kPostfix_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400766 this->write(".");
Ethan Nicholas6b4d5812020-10-12 16:11:51 -0400767 for (int c : swizzle.components()) {
Brian Osman25647672020-09-15 15:16:56 -0400768 SkASSERT(c >= 0 && c <= 3);
769 this->write(&("x\0y\0z\0w\0"[c * 2]));
Ethan Nicholascc305772017-10-13 16:17:45 -0400770 }
771}
772
773MetalCodeGenerator::Precedence MetalCodeGenerator::GetBinaryPrecedence(Token::Kind op) {
774 switch (op) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400775 case Token::Kind::TK_STAR: // fall through
776 case Token::Kind::TK_SLASH: // fall through
777 case Token::Kind::TK_PERCENT: return MetalCodeGenerator::kMultiplicative_Precedence;
778 case Token::Kind::TK_PLUS: // fall through
779 case Token::Kind::TK_MINUS: return MetalCodeGenerator::kAdditive_Precedence;
780 case Token::Kind::TK_SHL: // fall through
781 case Token::Kind::TK_SHR: return MetalCodeGenerator::kShift_Precedence;
782 case Token::Kind::TK_LT: // fall through
783 case Token::Kind::TK_GT: // fall through
784 case Token::Kind::TK_LTEQ: // fall through
785 case Token::Kind::TK_GTEQ: return MetalCodeGenerator::kRelational_Precedence;
786 case Token::Kind::TK_EQEQ: // fall through
787 case Token::Kind::TK_NEQ: return MetalCodeGenerator::kEquality_Precedence;
788 case Token::Kind::TK_BITWISEAND: return MetalCodeGenerator::kBitwiseAnd_Precedence;
789 case Token::Kind::TK_BITWISEXOR: return MetalCodeGenerator::kBitwiseXor_Precedence;
790 case Token::Kind::TK_BITWISEOR: return MetalCodeGenerator::kBitwiseOr_Precedence;
791 case Token::Kind::TK_LOGICALAND: return MetalCodeGenerator::kLogicalAnd_Precedence;
792 case Token::Kind::TK_LOGICALXOR: return MetalCodeGenerator::kLogicalXor_Precedence;
793 case Token::Kind::TK_LOGICALOR: return MetalCodeGenerator::kLogicalOr_Precedence;
794 case Token::Kind::TK_EQ: // fall through
795 case Token::Kind::TK_PLUSEQ: // fall through
796 case Token::Kind::TK_MINUSEQ: // fall through
797 case Token::Kind::TK_STAREQ: // fall through
798 case Token::Kind::TK_SLASHEQ: // fall through
799 case Token::Kind::TK_PERCENTEQ: // fall through
800 case Token::Kind::TK_SHLEQ: // fall through
801 case Token::Kind::TK_SHREQ: // fall through
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400802 case Token::Kind::TK_BITWISEANDEQ: // fall through
803 case Token::Kind::TK_BITWISEXOREQ: // fall through
804 case Token::Kind::TK_BITWISEOREQ: return MetalCodeGenerator::kAssignment_Precedence;
805 case Token::Kind::TK_COMMA: return MetalCodeGenerator::kSequence_Precedence;
Ethan Nicholascc305772017-10-13 16:17:45 -0400806 default: ABORT("unsupported binary operator");
807 }
808}
809
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500810void MetalCodeGenerator::writeMatrixTimesEqualHelper(const Type& left, const Type& right,
811 const Type& result) {
812 String key = "TimesEqual" + left.name() + right.name();
813 if (fHelpers.find(key) == fHelpers.end()) {
814 fExtraFunctions.printf("%s operator*=(thread %s& left, thread const %s& right) {\n"
815 " left = left * right;\n"
816 " return left;\n"
Ethan Nicholase2c49992020-10-05 11:49:11 -0400817 "}", String(result.name()).c_str(), String(left.name()).c_str(),
818 String(right.name()).c_str());
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500819 }
820}
821
Ethan Nicholascc305772017-10-13 16:17:45 -0400822void MetalCodeGenerator::writeBinaryExpression(const BinaryExpression& b,
823 Precedence parentPrecedence) {
John Stiles2d4f9592020-10-30 10:29:12 -0400824 const Expression& left = *b.left();
825 const Expression& right = *b.right();
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400826 const Type& leftType = left.type();
827 const Type& rightType = right.type();
828 Token::Kind op = b.getOperator();
829 Precedence precedence = GetBinaryPrecedence(b.getOperator());
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500830 bool needParens = precedence >= parentPrecedence;
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400831 switch (op) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400832 case Token::Kind::TK_EQEQ:
Ethan Nicholas30d30222020-09-11 12:27:26 -0400833 if (leftType.typeKind() == Type::TypeKind::kVector) {
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500834 this->write("all");
835 needParens = true;
836 }
837 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400838 case Token::Kind::TK_NEQ:
Ethan Nicholas30d30222020-09-11 12:27:26 -0400839 if (leftType.typeKind() == Type::TypeKind::kVector) {
Jim Van Verth36477b42019-04-11 14:57:30 -0400840 this->write("any");
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500841 needParens = true;
842 }
843 break;
844 default:
845 break;
846 }
847 if (needParens) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400848 this->write("(");
849 }
Brian Osman79457ef2020-09-24 15:01:27 -0400850 if (Compiler::IsAssignment(op) && left.is<VariableReference>() &&
Ethan Nicholas453f67f2020-10-09 10:43:45 -0400851 left.as<VariableReference>().variable()->storage() == Variable::Storage::kParameter &&
Ethan Nicholas78686922020-10-08 06:46:27 -0400852 left.as<VariableReference>().variable()->modifiers().fFlags & Modifiers::kOut_Flag) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400853 // writing to an out parameter. Since we have to turn those into pointers, we have to
854 // dereference it here.
855 this->write("*");
856 }
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400857 if (op == Token::Kind::TK_STAREQ && leftType.typeKind() == Type::TypeKind::kMatrix &&
Ethan Nicholas30d30222020-09-11 12:27:26 -0400858 rightType.typeKind() == Type::TypeKind::kMatrix) {
859 this->writeMatrixTimesEqualHelper(leftType, rightType, b.type());
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500860 }
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400861 this->writeExpression(left, precedence);
862 if (op != Token::Kind::TK_EQ && Compiler::IsAssignment(op) &&
863 left.kind() == Expression::Kind::kSwizzle && !left.hasSideEffects()) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400864 // This doesn't compile in Metal:
865 // float4 x = float4(1);
866 // x.xy *= float2x2(...);
867 // with the error message "non-const reference cannot bind to vector element",
868 // but switching it to x.xy = x.xy * float2x2(...) fixes it. We perform this tranformation
869 // as long as the LHS has no side effects, and hope for the best otherwise.
870 this->write(" = ");
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400871 this->writeExpression(left, kAssignment_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400872 this->write(" ");
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400873 String opName = Compiler::OperatorName(op);
874 SkASSERT(opName.endsWith("="));
875 this->write(opName.substr(0, opName.size() - 1).c_str());
Ethan Nicholascc305772017-10-13 16:17:45 -0400876 this->write(" ");
877 } else {
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400878 this->write(String(" ") + Compiler::OperatorName(op) + " ");
Ethan Nicholascc305772017-10-13 16:17:45 -0400879 }
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400880 this->writeExpression(right, precedence);
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500881 if (needParens) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400882 this->write(")");
883 }
884}
885
886void MetalCodeGenerator::writeTernaryExpression(const TernaryExpression& t,
887 Precedence parentPrecedence) {
888 if (kTernary_Precedence >= parentPrecedence) {
889 this->write("(");
890 }
Ethan Nicholasdd218162020-10-08 05:48:01 -0400891 this->writeExpression(*t.test(), kTernary_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400892 this->write(" ? ");
Ethan Nicholasdd218162020-10-08 05:48:01 -0400893 this->writeExpression(*t.ifTrue(), kTernary_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400894 this->write(" : ");
Ethan Nicholasdd218162020-10-08 05:48:01 -0400895 this->writeExpression(*t.ifFalse(), kTernary_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400896 if (kTernary_Precedence >= parentPrecedence) {
897 this->write(")");
898 }
899}
900
901void MetalCodeGenerator::writePrefixExpression(const PrefixExpression& p,
902 Precedence parentPrecedence) {
903 if (kPrefix_Precedence >= parentPrecedence) {
904 this->write("(");
905 }
Ethan Nicholas444ccc62020-10-09 10:16:22 -0400906 this->write(Compiler::OperatorName(p.getOperator()));
907 this->writeExpression(*p.operand(), kPrefix_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400908 if (kPrefix_Precedence >= parentPrecedence) {
909 this->write(")");
910 }
911}
912
913void MetalCodeGenerator::writePostfixExpression(const PostfixExpression& p,
914 Precedence parentPrecedence) {
915 if (kPostfix_Precedence >= parentPrecedence) {
916 this->write("(");
917 }
Ethan Nicholas444ccc62020-10-09 10:16:22 -0400918 this->writeExpression(*p.operand(), kPostfix_Precedence);
919 this->write(Compiler::OperatorName(p.getOperator()));
Ethan Nicholascc305772017-10-13 16:17:45 -0400920 if (kPostfix_Precedence >= parentPrecedence) {
921 this->write(")");
922 }
923}
924
925void MetalCodeGenerator::writeBoolLiteral(const BoolLiteral& b) {
Ethan Nicholas59d660c2020-09-28 09:18:15 -0400926 this->write(b.value() ? "true" : "false");
Ethan Nicholascc305772017-10-13 16:17:45 -0400927}
928
929void MetalCodeGenerator::writeIntLiteral(const IntLiteral& i) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400930 if (i.type() == *fContext.fUInt_Type) {
Ethan Nicholase96cdd12020-09-28 16:27:18 -0400931 this->write(to_string(i.value() & 0xffffffff) + "u");
Ethan Nicholascc305772017-10-13 16:17:45 -0400932 } else {
Ethan Nicholase96cdd12020-09-28 16:27:18 -0400933 this->write(to_string((int32_t) i.value()));
Ethan Nicholascc305772017-10-13 16:17:45 -0400934 }
935}
936
937void MetalCodeGenerator::writeFloatLiteral(const FloatLiteral& f) {
Ethan Nicholasa3f22f12020-10-01 12:13:17 -0400938 this->write(to_string(f.value()));
Ethan Nicholascc305772017-10-13 16:17:45 -0400939}
940
941void MetalCodeGenerator::writeSetting(const Setting& s) {
942 ABORT("internal error; setting was not folded to a constant during compilation\n");
943}
944
John Stiles569249b2020-11-03 12:18:22 -0500945bool MetalCodeGenerator::writeFunctionDeclaration(const FunctionDeclaration& f) {
Ethan Nicholasf931e402019-07-26 15:40:33 -0400946 fRTHeightName = fProgram.fInputs.fRTHeight ? "_globals->_anonInterface0->u_skRTHeight" : "";
Ethan Nicholascc305772017-10-13 16:17:45 -0400947 const char* separator = "";
John Stiles569249b2020-11-03 12:18:22 -0500948 if ("main" == f.name()) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400949 switch (fProgram.fKind) {
950 case Program::kFragment_Kind:
Timothy Liangb8eeb802018-07-23 16:46:16 -0400951 this->write("fragment Outputs fragmentMain");
Ethan Nicholascc305772017-10-13 16:17:45 -0400952 break;
953 case Program::kVertex_Kind:
Timothy Liangb8eeb802018-07-23 16:46:16 -0400954 this->write("vertex Outputs vertexMain");
Ethan Nicholascc305772017-10-13 16:17:45 -0400955 break;
956 default:
John Stiles3fabfc02020-09-25 15:51:28 -0400957 fErrors.error(-1, "unsupported kind of program");
John Stiles569249b2020-11-03 12:18:22 -0500958 return false;
Ethan Nicholascc305772017-10-13 16:17:45 -0400959 }
960 this->write("(Inputs _in [[stage_in]]");
961 if (-1 != fUniformBuffer) {
962 this->write(", constant Uniforms& _uniforms [[buffer(" +
963 to_string(fUniformBuffer) + ")]]");
964 }
Brian Osman133724c2020-10-28 14:14:39 -0400965 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -0400966 if (e->is<GlobalVarDeclaration>()) {
967 const GlobalVarDeclaration& decls = e->as<GlobalVarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -0400968 const VarDeclaration& var = decls.declaration()->as<VarDeclaration>();
969 if (var.var().type().typeKind() == Type::TypeKind::kSampler) {
970 if (var.var().modifiers().fLayout.fBinding < 0) {
Brian Osmanc0213602020-10-06 14:43:32 -0400971 fErrors.error(decls.fOffset,
972 "Metal samplers must have 'layout(binding=...)'");
John Stiles569249b2020-11-03 12:18:22 -0500973 return false;
Timothy Liangee84fe12018-05-18 14:38:19 -0400974 }
Ethan Nicholasc51f33e2020-10-13 13:49:44 -0400975 if (var.var().type().dimensions() != SpvDim2D) {
John Stiles569249b2020-11-03 12:18:22 -0500976 // Not yet implemented--Skia currently only uses 2D textures.
Brian Osmanc0213602020-10-06 14:43:32 -0400977 fErrors.error(decls.fOffset, "Unsupported texture dimensions");
John Stiles569249b2020-11-03 12:18:22 -0500978 return false;
Brian Osmanc0213602020-10-06 14:43:32 -0400979 }
980 this->write(", texture2d<float> ");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -0400981 this->writeName(var.var().name());
Brian Osmanc0213602020-10-06 14:43:32 -0400982 this->write("[[texture(");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -0400983 this->write(to_string(var.var().modifiers().fLayout.fBinding));
Brian Osmanc0213602020-10-06 14:43:32 -0400984 this->write(")]]");
985 this->write(", sampler ");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -0400986 this->writeName(var.var().name());
Brian Osmanc0213602020-10-06 14:43:32 -0400987 this->write(SAMPLER_SUFFIX);
988 this->write("[[sampler(");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -0400989 this->write(to_string(var.var().modifiers().fLayout.fBinding));
Brian Osmanc0213602020-10-06 14:43:32 -0400990 this->write(")]]");
Timothy Liang6403b0e2018-05-17 10:40:04 -0400991 }
Brian Osman1179fcf2020-10-08 16:04:40 -0400992 } else if (e->is<InterfaceBlock>()) {
993 const InterfaceBlock& intf = e->as<InterfaceBlock>();
Ethan Nicholaseaf47882020-10-15 10:10:08 -0400994 if (intf.typeName() == "sk_PerVertex") {
Timothy Lianga06f2152018-05-24 15:33:31 -0400995 continue;
996 }
997 this->write(", constant ");
Ethan Nicholaseaf47882020-10-15 10:10:08 -0400998 this->writeType(intf.variable().type());
Timothy Lianga06f2152018-05-24 15:33:31 -0400999 this->write("& " );
1000 this->write(fInterfaceBlockNameMap[&intf]);
1001 this->write(" [[buffer(");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001002 this->write(to_string(intf.variable().modifiers().fLayout.fBinding));
Timothy Lianga06f2152018-05-24 15:33:31 -04001003 this->write(")]]");
Timothy Liang6403b0e2018-05-17 10:40:04 -04001004 }
1005 }
Jim Van Verth6bc650e2019-02-07 14:53:23 -05001006 if (fProgram.fKind == Program::kFragment_Kind) {
1007 if (fProgram.fInputs.fRTHeight && fInterfaceBlockNameMap.empty()) {
Timothy Liang5422f9a2018-08-10 10:57:55 -04001008 this->write(", constant sksl_synthetic_uniforms& _anonInterface0 [[buffer(1)]]");
Ethan Nicholasf931e402019-07-26 15:40:33 -04001009 fRTHeightName = "_anonInterface0.u_skRTHeight";
Timothy Liang5422f9a2018-08-10 10:57:55 -04001010 }
Timothy Liang7b8875d2018-08-10 09:42:31 -04001011 this->write(", bool _frontFacing [[front_facing]]");
Timothy Liang7d637782018-06-05 09:58:07 -04001012 this->write(", float4 _fragCoord [[position]]");
Timothy Liangdc89f192018-06-13 09:20:31 -04001013 } else if (fProgram.fKind == Program::kVertex_Kind) {
1014 this->write(", uint sk_VertexID [[vertex_id]], uint sk_InstanceID [[instance_id]]");
Timothy Liang7d637782018-06-05 09:58:07 -04001015 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001016 separator = ", ";
1017 } else {
John Stiles569249b2020-11-03 12:18:22 -05001018 this->writeType(f.returnType());
Timothy Liang651286f2018-06-07 09:55:33 -04001019 this->write(" ");
John Stiles569249b2020-11-03 12:18:22 -05001020 this->writeName(f.name());
Timothy Liang651286f2018-06-07 09:55:33 -04001021 this->write("(");
John Stiles569249b2020-11-03 12:18:22 -05001022 Requirements requirements = this->requirements(f);
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -04001023 if (requirements & kInputs_Requirement) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001024 this->write("Inputs _in");
1025 separator = ", ";
1026 }
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -04001027 if (requirements & kOutputs_Requirement) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001028 this->write(separator);
Timothy Liangee84fe12018-05-18 14:38:19 -04001029 this->write("thread Outputs* _out");
Ethan Nicholascc305772017-10-13 16:17:45 -04001030 separator = ", ";
1031 }
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -04001032 if (requirements & kUniforms_Requirement) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001033 this->write(separator);
1034 this->write("Uniforms _uniforms");
1035 separator = ", ";
1036 }
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -04001037 if (requirements & kGlobals_Requirement) {
Timothy Liangee84fe12018-05-18 14:38:19 -04001038 this->write(separator);
1039 this->write("thread Globals* _globals");
1040 separator = ", ";
1041 }
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -04001042 if (requirements & kFragCoord_Requirement) {
1043 this->write(separator);
1044 this->write("float4 _fragCoord");
1045 separator = ", ";
1046 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001047 }
John Stiles569249b2020-11-03 12:18:22 -05001048 for (const auto& param : f.parameters()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001049 this->write(separator);
1050 separator = ", ";
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001051 this->writeModifiers(param->modifiers(), false);
Ethan Nicholascc305772017-10-13 16:17:45 -04001052 std::vector<int> sizes;
Ethan Nicholas30d30222020-09-11 12:27:26 -04001053 const Type* type = &param->type();
Ethan Nicholase6592142020-09-08 10:22:09 -04001054 while (type->typeKind() == Type::TypeKind::kArray) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001055 sizes.push_back(type->columns());
1056 type = &type->componentType();
1057 }
1058 this->writeType(*type);
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001059 if (param->modifiers().fFlags & Modifiers::kOut_Flag) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001060 this->write("*");
1061 }
Timothy Liang651286f2018-06-07 09:55:33 -04001062 this->write(" ");
Ethan Nicholase2c49992020-10-05 11:49:11 -04001063 this->writeName(param->name());
Ethan Nicholascc305772017-10-13 16:17:45 -04001064 for (int s : sizes) {
Brian Osmane8c26082020-10-01 17:22:45 -04001065 if (s == Type::kUnsizedArray) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001066 this->write("[]");
1067 } else {
1068 this->write("[" + to_string(s) + "]");
1069 }
1070 }
1071 }
John Stiles569249b2020-11-03 12:18:22 -05001072 this->write(")");
1073 return true;
1074}
Ethan Nicholascc305772017-10-13 16:17:45 -04001075
John Stiles569249b2020-11-03 12:18:22 -05001076void MetalCodeGenerator::writeFunctionPrototype(const FunctionPrototype& f) {
1077 this->writeFunctionDeclaration(f.declaration());
1078 this->writeLine(";");
1079}
1080
1081void MetalCodeGenerator::writeFunction(const FunctionDefinition& f) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001082 SkASSERT(!fProgram.fSettings.fFragColorIsInOut);
Brian Salomondc092132018-04-04 10:14:16 -04001083
John Stiles569249b2020-11-03 12:18:22 -05001084 if (!this->writeFunctionDeclaration(f.declaration())) {
1085 return;
1086 }
1087
1088 this->writeLine(" {");
1089
Ethan Nicholas0a5d0962020-10-14 13:33:18 -04001090 if (f.declaration().name() == "main") {
John Stilescdcdb042020-07-06 09:03:51 -04001091 this->writeGlobalInit();
Timothy Liang7d637782018-06-05 09:58:07 -04001092 this->writeLine(" Outputs _outputStruct;");
1093 this->writeLine(" thread Outputs* _out = &_outputStruct;");
Ethan Nicholascc305772017-10-13 16:17:45 -04001094 }
John Stilesc67b3622020-05-28 17:53:13 -04001095
Ethan Nicholascc305772017-10-13 16:17:45 -04001096 fFunctionHeader = "";
1097 OutputStream* oldOut = fOut;
1098 StringStream buffer;
1099 fOut = &buffer;
1100 fIndentation++;
Ethan Nicholas0a5d0962020-10-14 13:33:18 -04001101 for (const std::unique_ptr<Statement>& stmt : f.body()->as<Block>().children()) {
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001102 if (!stmt->isEmpty()) {
1103 this->writeStatement(*stmt);
1104 this->writeLine();
1105 }
1106 }
Ethan Nicholas0a5d0962020-10-14 13:33:18 -04001107 if (f.declaration().name() == "main") {
Ethan Nicholascc305772017-10-13 16:17:45 -04001108 switch (fProgram.fKind) {
1109 case Program::kFragment_Kind:
Timothy Liang7d637782018-06-05 09:58:07 -04001110 this->writeLine("return *_out;");
Ethan Nicholascc305772017-10-13 16:17:45 -04001111 break;
1112 case Program::kVertex_Kind:
Timothy Liangb8eeb802018-07-23 16:46:16 -04001113 this->writeLine("_out->sk_Position.y = -_out->sk_Position.y;");
Timothy Lianga06f2152018-05-24 15:33:31 -04001114 this->writeLine("return *_out;"); // FIXME - detect if function already has return
Ethan Nicholascc305772017-10-13 16:17:45 -04001115 break;
1116 default:
John Stilesf7d70432020-05-28 15:46:38 -04001117 SkDEBUGFAIL("unsupported kind of program");
Ethan Nicholascc305772017-10-13 16:17:45 -04001118 }
1119 }
1120 fIndentation--;
1121 this->writeLine("}");
1122
1123 fOut = oldOut;
1124 this->write(fFunctionHeader);
1125 this->write(buffer.str());
1126}
1127
1128void MetalCodeGenerator::writeModifiers(const Modifiers& modifiers,
1129 bool globalContext) {
1130 if (modifiers.fFlags & Modifiers::kOut_Flag) {
1131 this->write("thread ");
1132 }
1133 if (modifiers.fFlags & Modifiers::kConst_Flag) {
Timothy Liangee84fe12018-05-18 14:38:19 -04001134 this->write("constant ");
Ethan Nicholascc305772017-10-13 16:17:45 -04001135 }
1136}
1137
1138void MetalCodeGenerator::writeInterfaceBlock(const InterfaceBlock& intf) {
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001139 if ("sk_PerVertex" == intf.typeName()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001140 return;
1141 }
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001142 this->writeModifiers(intf.variable().modifiers(), true);
Timothy Liangdc89f192018-06-13 09:20:31 -04001143 this->write("struct ");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001144 this->writeLine(intf.typeName() + " {");
1145 const Type* structType = &intf.variable().type();
Timothy Lianga06f2152018-05-24 15:33:31 -04001146 fWrittenStructs.push_back(structType);
Ethan Nicholase6592142020-09-08 10:22:09 -04001147 while (structType->typeKind() == Type::TypeKind::kArray) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001148 structType = &structType->componentType();
1149 }
Timothy Liangdc89f192018-06-13 09:20:31 -04001150 fIndentation++;
1151 writeFields(structType->fields(), structType->fOffset, &intf);
Jim Van Verth3d482992019-02-07 10:48:05 -05001152 if (fProgram.fInputs.fRTHeight) {
Timothy Liang7d637782018-06-05 09:58:07 -04001153 this->writeLine("float u_skRTHeight;");
Ethan Nicholascc305772017-10-13 16:17:45 -04001154 }
1155 fIndentation--;
1156 this->write("}");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001157 if (intf.instanceName().size()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001158 this->write(" ");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001159 this->write(intf.instanceName());
1160 for (const auto& size : intf.sizes()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001161 this->write("[");
1162 if (size) {
1163 this->writeExpression(*size, kTopLevel_Precedence);
1164 }
1165 this->write("]");
1166 }
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001167 fInterfaceBlockNameMap[&intf] = intf.instanceName();
Timothy Lianga06f2152018-05-24 15:33:31 -04001168 } else {
Timothy Liang7d637782018-06-05 09:58:07 -04001169 fInterfaceBlockNameMap[&intf] = "_anonInterface" + to_string(fAnonInterfaceCount++);
Ethan Nicholascc305772017-10-13 16:17:45 -04001170 }
1171 this->writeLine(";");
1172}
1173
Timothy Liangdc89f192018-06-13 09:20:31 -04001174void MetalCodeGenerator::writeFields(const std::vector<Type::Field>& fields, int parentOffset,
1175 const InterfaceBlock* parentIntf) {
Timothy Liang609fbe32018-08-10 16:40:49 -04001176 MemoryLayout memoryLayout(MemoryLayout::kMetal_Standard);
Timothy Liangdc89f192018-06-13 09:20:31 -04001177 int currentOffset = 0;
1178 for (const auto& field: fields) {
1179 int fieldOffset = field.fModifiers.fLayout.fOffset;
1180 const Type* fieldType = field.fType;
John Stiles0023c0c2020-11-16 13:32:18 -05001181 if (!memoryLayout.layoutIsSupported(*fieldType)) {
1182 fErrors.error(parentOffset, "type '" + fieldType->name() + "' is not permitted here");
1183 return;
1184 }
Timothy Liangdc89f192018-06-13 09:20:31 -04001185 if (fieldOffset != -1) {
1186 if (currentOffset > fieldOffset) {
1187 fErrors.error(parentOffset,
1188 "offset of field '" + field.fName + "' must be at least " +
1189 to_string((int) currentOffset));
Brian Osman8609a242020-09-08 14:01:49 -04001190 return;
Timothy Liangdc89f192018-06-13 09:20:31 -04001191 } else if (currentOffset < fieldOffset) {
1192 this->write("char pad");
1193 this->write(to_string(fPaddingCount++));
1194 this->write("[");
1195 this->write(to_string(fieldOffset - currentOffset));
1196 this->writeLine("];");
1197 currentOffset = fieldOffset;
1198 }
1199 int alignment = memoryLayout.alignment(*fieldType);
1200 if (fieldOffset % alignment) {
1201 fErrors.error(parentOffset,
1202 "offset of field '" + field.fName + "' must be a multiple of " +
1203 to_string((int) alignment));
Brian Osman8609a242020-09-08 14:01:49 -04001204 return;
Timothy Liangdc89f192018-06-13 09:20:31 -04001205 }
1206 }
Brian Osman8609a242020-09-08 14:01:49 -04001207 size_t fieldSize = memoryLayout.size(*fieldType);
1208 if (fieldSize > static_cast<size_t>(std::numeric_limits<int>::max() - currentOffset)) {
1209 fErrors.error(parentOffset, "field offset overflow");
1210 return;
1211 }
1212 currentOffset += fieldSize;
Timothy Liangdc89f192018-06-13 09:20:31 -04001213 std::vector<int> sizes;
Ethan Nicholase6592142020-09-08 10:22:09 -04001214 while (fieldType->typeKind() == Type::TypeKind::kArray) {
Timothy Liangdc89f192018-06-13 09:20:31 -04001215 sizes.push_back(fieldType->columns());
1216 fieldType = &fieldType->componentType();
1217 }
1218 this->writeModifiers(field.fModifiers, false);
1219 this->writeType(*fieldType);
1220 this->write(" ");
1221 this->writeName(field.fName);
1222 for (int s : sizes) {
Brian Osmane8c26082020-10-01 17:22:45 -04001223 if (s == Type::kUnsizedArray) {
Timothy Liangdc89f192018-06-13 09:20:31 -04001224 this->write("[]");
1225 } else {
1226 this->write("[" + to_string(s) + "]");
1227 }
1228 }
1229 this->writeLine(";");
1230 if (parentIntf) {
1231 fInterfaceBlockMap[&field] = parentIntf;
1232 }
1233 }
1234}
1235
Ethan Nicholascc305772017-10-13 16:17:45 -04001236void MetalCodeGenerator::writeVarInitializer(const Variable& var, const Expression& value) {
1237 this->writeExpression(value, kTopLevel_Precedence);
1238}
1239
Timothy Liang651286f2018-06-07 09:55:33 -04001240void MetalCodeGenerator::writeName(const String& name) {
1241 if (fReservedWords.find(name) != fReservedWords.end()) {
1242 this->write("_"); // adding underscore before name to avoid conflict with reserved words
1243 }
1244 this->write(name);
1245}
1246
Brian Osmanc0213602020-10-06 14:43:32 -04001247void MetalCodeGenerator::writeVarDeclaration(const VarDeclaration& var, bool global) {
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001248 if (global && !(var.var().modifiers().fFlags & Modifiers::kConst_Flag)) {
Brian Osmanc0213602020-10-06 14:43:32 -04001249 return;
Ethan Nicholascc305772017-10-13 16:17:45 -04001250 }
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001251 this->writeModifiers(var.var().modifiers(), global);
1252 this->writeType(var.baseType());
Brian Osmanc0213602020-10-06 14:43:32 -04001253 this->write(" ");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001254 this->writeName(var.var().name());
John Stiles2d4f9592020-10-30 10:29:12 -04001255 for (const std::unique_ptr<Expression>& size : var.sizes()) {
Brian Osmanc0213602020-10-06 14:43:32 -04001256 this->write("[");
John Stiles2d4f9592020-10-30 10:29:12 -04001257 if (size) {
1258 this->writeExpression(*size, kTopLevel_Precedence);
Brian Osmanc0213602020-10-06 14:43:32 -04001259 }
1260 this->write("]");
Ethan Nicholascc305772017-10-13 16:17:45 -04001261 }
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001262 if (var.value()) {
Brian Osmanc0213602020-10-06 14:43:32 -04001263 this->write(" = ");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001264 this->writeVarInitializer(var.var(), *var.value());
Brian Osmanc0213602020-10-06 14:43:32 -04001265 }
1266 this->write(";");
Ethan Nicholascc305772017-10-13 16:17:45 -04001267}
1268
1269void MetalCodeGenerator::writeStatement(const Statement& s) {
Ethan Nicholase6592142020-09-08 10:22:09 -04001270 switch (s.kind()) {
1271 case Statement::Kind::kBlock:
John Stiles26f98502020-08-18 09:30:51 -04001272 this->writeBlock(s.as<Block>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001273 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001274 case Statement::Kind::kExpression:
Ethan Nicholasd503a5a2020-09-30 09:29:55 -04001275 this->writeExpression(*s.as<ExpressionStatement>().expression(), kTopLevel_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001276 this->write(";");
1277 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001278 case Statement::Kind::kReturn:
John Stiles26f98502020-08-18 09:30:51 -04001279 this->writeReturnStatement(s.as<ReturnStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001280 break;
Brian Osmanc0213602020-10-06 14:43:32 -04001281 case Statement::Kind::kVarDeclaration:
1282 this->writeVarDeclaration(s.as<VarDeclaration>(), false);
Ethan Nicholascc305772017-10-13 16:17:45 -04001283 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001284 case Statement::Kind::kIf:
John Stiles26f98502020-08-18 09:30:51 -04001285 this->writeIfStatement(s.as<IfStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001286 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001287 case Statement::Kind::kFor:
John Stiles26f98502020-08-18 09:30:51 -04001288 this->writeForStatement(s.as<ForStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001289 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001290 case Statement::Kind::kWhile:
John Stiles26f98502020-08-18 09:30:51 -04001291 this->writeWhileStatement(s.as<WhileStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001292 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001293 case Statement::Kind::kDo:
John Stiles26f98502020-08-18 09:30:51 -04001294 this->writeDoStatement(s.as<DoStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001295 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001296 case Statement::Kind::kSwitch:
John Stiles26f98502020-08-18 09:30:51 -04001297 this->writeSwitchStatement(s.as<SwitchStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001298 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001299 case Statement::Kind::kBreak:
Ethan Nicholascc305772017-10-13 16:17:45 -04001300 this->write("break;");
1301 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001302 case Statement::Kind::kContinue:
Ethan Nicholascc305772017-10-13 16:17:45 -04001303 this->write("continue;");
1304 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001305 case Statement::Kind::kDiscard:
Timothy Lianga06f2152018-05-24 15:33:31 -04001306 this->write("discard_fragment();");
Ethan Nicholascc305772017-10-13 16:17:45 -04001307 break;
John Stiles98c1f822020-09-09 14:18:53 -04001308 case Statement::Kind::kInlineMarker:
Ethan Nicholase6592142020-09-08 10:22:09 -04001309 case Statement::Kind::kNop:
Ethan Nicholascc305772017-10-13 16:17:45 -04001310 this->write(";");
1311 break;
1312 default:
Ethan Nicholas2a099da2020-01-02 14:40:54 -05001313#ifdef SK_DEBUG
Ethan Nicholascc305772017-10-13 16:17:45 -04001314 ABORT("unsupported statement: %s", s.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -05001315#endif
1316 break;
Ethan Nicholascc305772017-10-13 16:17:45 -04001317 }
1318}
1319
Ethan Nicholascc305772017-10-13 16:17:45 -04001320void MetalCodeGenerator::writeBlock(const Block& b) {
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001321 bool isScope = b.isScope();
1322 if (isScope) {
Ethan Nicholas70728ef2020-05-28 07:09:00 -04001323 this->writeLine("{");
1324 fIndentation++;
1325 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001326 for (const std::unique_ptr<Statement>& stmt : b.children()) {
1327 if (!stmt->isEmpty()) {
1328 this->writeStatement(*stmt);
1329 this->writeLine();
1330 }
1331 }
1332 if (isScope) {
Ethan Nicholas70728ef2020-05-28 07:09:00 -04001333 fIndentation--;
1334 this->write("}");
1335 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001336}
1337
1338void MetalCodeGenerator::writeIfStatement(const IfStatement& stmt) {
1339 this->write("if (");
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04001340 this->writeExpression(*stmt.test(), kTopLevel_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001341 this->write(") ");
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04001342 this->writeStatement(*stmt.ifTrue());
1343 if (stmt.ifFalse()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001344 this->write(" else ");
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04001345 this->writeStatement(*stmt.ifFalse());
Ethan Nicholascc305772017-10-13 16:17:45 -04001346 }
1347}
1348
1349void MetalCodeGenerator::writeForStatement(const ForStatement& f) {
1350 this->write("for (");
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04001351 if (f.initializer() && !f.initializer()->isEmpty()) {
1352 this->writeStatement(*f.initializer());
Ethan Nicholascc305772017-10-13 16:17:45 -04001353 } else {
1354 this->write("; ");
1355 }
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04001356 if (f.test()) {
1357 this->writeExpression(*f.test(), kTopLevel_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001358 }
1359 this->write("; ");
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04001360 if (f.next()) {
1361 this->writeExpression(*f.next(), kTopLevel_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001362 }
1363 this->write(") ");
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04001364 this->writeStatement(*f.statement());
Ethan Nicholascc305772017-10-13 16:17:45 -04001365}
1366
1367void MetalCodeGenerator::writeWhileStatement(const WhileStatement& w) {
1368 this->write("while (");
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04001369 this->writeExpression(*w.test(), kTopLevel_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001370 this->write(") ");
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04001371 this->writeStatement(*w.statement());
Ethan Nicholascc305772017-10-13 16:17:45 -04001372}
1373
1374void MetalCodeGenerator::writeDoStatement(const DoStatement& d) {
1375 this->write("do ");
Ethan Nicholas1fd61162020-09-28 13:14:19 -04001376 this->writeStatement(*d.statement());
Ethan Nicholascc305772017-10-13 16:17:45 -04001377 this->write(" while (");
Ethan Nicholas1fd61162020-09-28 13:14:19 -04001378 this->writeExpression(*d.test(), kTopLevel_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001379 this->write(");");
1380}
1381
1382void MetalCodeGenerator::writeSwitchStatement(const SwitchStatement& s) {
1383 this->write("switch (");
Ethan Nicholas01b05e52020-10-22 15:53:41 -04001384 this->writeExpression(*s.value(), kTopLevel_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001385 this->writeLine(") {");
1386 fIndentation++;
John Stiles2d4f9592020-10-30 10:29:12 -04001387 for (const std::unique_ptr<SwitchCase>& c : s.cases()) {
1388 if (c->value()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001389 this->write("case ");
John Stiles2d4f9592020-10-30 10:29:12 -04001390 this->writeExpression(*c->value(), kTopLevel_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001391 this->writeLine(":");
1392 } else {
1393 this->writeLine("default:");
1394 }
1395 fIndentation++;
John Stiles2d4f9592020-10-30 10:29:12 -04001396 for (const auto& stmt : c->statements()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001397 this->writeStatement(*stmt);
1398 this->writeLine();
1399 }
1400 fIndentation--;
1401 }
1402 fIndentation--;
1403 this->write("}");
1404}
1405
1406void MetalCodeGenerator::writeReturnStatement(const ReturnStatement& r) {
1407 this->write("return");
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04001408 if (r.expression()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001409 this->write(" ");
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04001410 this->writeExpression(*r.expression(), kTopLevel_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001411 }
1412 this->write(";");
1413}
1414
1415void MetalCodeGenerator::writeHeader() {
1416 this->write("#include <metal_stdlib>\n");
1417 this->write("#include <simd/simd.h>\n");
1418 this->write("using namespace metal;\n");
1419}
1420
1421void MetalCodeGenerator::writeUniformStruct() {
Brian Osman133724c2020-10-28 14:14:39 -04001422 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04001423 if (e->is<GlobalVarDeclaration>()) {
1424 const GlobalVarDeclaration& decls = e->as<GlobalVarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001425 const Variable& var = decls.declaration()->as<VarDeclaration>().var();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001426 if (var.modifiers().fFlags & Modifiers::kUniform_Flag &&
Brian Osmanc0213602020-10-06 14:43:32 -04001427 var.type().typeKind() != Type::TypeKind::kSampler) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001428 if (-1 == fUniformBuffer) {
1429 this->write("struct Uniforms {\n");
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001430 fUniformBuffer = var.modifiers().fLayout.fSet;
Ethan Nicholascc305772017-10-13 16:17:45 -04001431 if (-1 == fUniformBuffer) {
1432 fErrors.error(decls.fOffset, "Metal uniforms must have 'layout(set=...)'");
1433 }
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001434 } else if (var.modifiers().fLayout.fSet != fUniformBuffer) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001435 if (-1 == fUniformBuffer) {
1436 fErrors.error(decls.fOffset, "Metal backend requires all uniforms to have "
1437 "the same 'layout(set=...)'");
1438 }
1439 }
1440 this->write(" ");
Brian Osmanc0213602020-10-06 14:43:32 -04001441 this->writeType(var.type());
Ethan Nicholascc305772017-10-13 16:17:45 -04001442 this->write(" ");
Brian Osmanc0213602020-10-06 14:43:32 -04001443 this->writeName(var.name());
Ethan Nicholascc305772017-10-13 16:17:45 -04001444 this->write(";\n");
1445 }
1446 }
1447 }
1448 if (-1 != fUniformBuffer) {
1449 this->write("};\n");
1450 }
1451}
1452
1453void MetalCodeGenerator::writeInputStruct() {
1454 this->write("struct Inputs {\n");
Brian Osman133724c2020-10-28 14:14:39 -04001455 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04001456 if (e->is<GlobalVarDeclaration>()) {
1457 const GlobalVarDeclaration& decls = e->as<GlobalVarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001458 const Variable& var = decls.declaration()->as<VarDeclaration>().var();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001459 if (var.modifiers().fFlags & Modifiers::kIn_Flag &&
1460 -1 == var.modifiers().fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001461 this->write(" ");
Brian Osmanc0213602020-10-06 14:43:32 -04001462 this->writeType(var.type());
Ethan Nicholascc305772017-10-13 16:17:45 -04001463 this->write(" ");
Brian Osmanc0213602020-10-06 14:43:32 -04001464 this->writeName(var.name());
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001465 if (-1 != var.modifiers().fLayout.fLocation) {
Brian Osmanc0213602020-10-06 14:43:32 -04001466 if (fProgram.fKind == Program::kVertex_Kind) {
1467 this->write(" [[attribute(" +
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001468 to_string(var.modifiers().fLayout.fLocation) + ")]]");
Brian Osmanc0213602020-10-06 14:43:32 -04001469 } else if (fProgram.fKind == Program::kFragment_Kind) {
1470 this->write(" [[user(locn" +
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001471 to_string(var.modifiers().fLayout.fLocation) + ")]]");
Ethan Nicholascc305772017-10-13 16:17:45 -04001472 }
1473 }
1474 this->write(";\n");
1475 }
1476 }
1477 }
1478 this->write("};\n");
1479}
1480
1481void MetalCodeGenerator::writeOutputStruct() {
1482 this->write("struct Outputs {\n");
Timothy Liang7d637782018-06-05 09:58:07 -04001483 if (fProgram.fKind == Program::kVertex_Kind) {
Timothy Liangb8eeb802018-07-23 16:46:16 -04001484 this->write(" float4 sk_Position [[position]];\n");
Timothy Liang7d637782018-06-05 09:58:07 -04001485 } else if (fProgram.fKind == Program::kFragment_Kind) {
Timothy Liangde0be802018-08-10 13:48:08 -04001486 this->write(" float4 sk_FragColor [[color(0)]];\n");
Timothy Liang7d637782018-06-05 09:58:07 -04001487 }
Brian Osman133724c2020-10-28 14:14:39 -04001488 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04001489 if (e->is<GlobalVarDeclaration>()) {
1490 const GlobalVarDeclaration& decls = e->as<GlobalVarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001491 const Variable& var = decls.declaration()->as<VarDeclaration>().var();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001492 if (var.modifiers().fFlags & Modifiers::kOut_Flag &&
1493 -1 == var.modifiers().fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001494 this->write(" ");
Brian Osmanc0213602020-10-06 14:43:32 -04001495 this->writeType(var.type());
Ethan Nicholascc305772017-10-13 16:17:45 -04001496 this->write(" ");
Brian Osmanc0213602020-10-06 14:43:32 -04001497 this->writeName(var.name());
1498 if (fProgram.fKind == Program::kVertex_Kind) {
1499 this->write(" [[user(locn" +
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001500 to_string(var.modifiers().fLayout.fLocation) + ")]]");
Brian Osmanc0213602020-10-06 14:43:32 -04001501 } else if (fProgram.fKind == Program::kFragment_Kind) {
1502 this->write(" [[color(" +
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001503 to_string(var.modifiers().fLayout.fLocation) +")");
1504 int colorIndex = var.modifiers().fLayout.fIndex;
Brian Osmanc0213602020-10-06 14:43:32 -04001505 if (colorIndex) {
1506 this->write(", index(" + to_string(colorIndex) + ")");
Timothy Liang7d637782018-06-05 09:58:07 -04001507 }
Brian Osmanc0213602020-10-06 14:43:32 -04001508 this->write("]]");
Ethan Nicholascc305772017-10-13 16:17:45 -04001509 }
1510 this->write(";\n");
1511 }
1512 }
Timothy Liang7d637782018-06-05 09:58:07 -04001513 }
1514 if (fProgram.fKind == Program::kVertex_Kind) {
Jim Van Verth3913d3e2020-08-31 15:16:57 -04001515 this->write(" float sk_PointSize [[point_size]];\n");
Timothy Liang7d637782018-06-05 09:58:07 -04001516 }
1517 this->write("};\n");
1518}
1519
1520void MetalCodeGenerator::writeInterfaceBlocks() {
1521 bool wroteInterfaceBlock = false;
Brian Osman133724c2020-10-28 14:14:39 -04001522 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04001523 if (e->is<InterfaceBlock>()) {
1524 this->writeInterfaceBlock(e->as<InterfaceBlock>());
Timothy Liang7d637782018-06-05 09:58:07 -04001525 wroteInterfaceBlock = true;
1526 }
1527 }
Jim Van Verth3d482992019-02-07 10:48:05 -05001528 if (!wroteInterfaceBlock && fProgram.fInputs.fRTHeight) {
Timothy Liang7d637782018-06-05 09:58:07 -04001529 this->writeLine("struct sksl_synthetic_uniforms {");
1530 this->writeLine(" float u_skRTHeight;");
1531 this->writeLine("};");
1532 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001533}
1534
John Stilescdcdb042020-07-06 09:03:51 -04001535void MetalCodeGenerator::visitGlobalStruct(GlobalStructVisitor* visitor) {
1536 // Visit the interface blocks.
1537 for (const auto& [interfaceType, interfaceName] : fInterfaceBlockNameMap) {
1538 visitor->VisitInterfaceBlock(*interfaceType, interfaceName);
1539 }
Brian Osman133724c2020-10-28 14:14:39 -04001540 for (const ProgramElement* element : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04001541 if (!element->is<GlobalVarDeclaration>()) {
John Stilescdcdb042020-07-06 09:03:51 -04001542 continue;
Timothy Liang7d637782018-06-05 09:58:07 -04001543 }
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001544 const GlobalVarDeclaration& global = element->as<GlobalVarDeclaration>();
1545 const VarDeclaration& decl = global.declaration()->as<VarDeclaration>();
1546 const Variable& var = decl.var();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001547 if ((!var.modifiers().fFlags && -1 == var.modifiers().fLayout.fBuiltin) ||
Brian Osmanc0213602020-10-06 14:43:32 -04001548 var.type().typeKind() == Type::TypeKind::kSampler) {
1549 if (var.type().typeKind() == Type::TypeKind::kSampler) {
1550 // Samplers are represented as a "texture/sampler" duo in the global struct.
1551 visitor->VisitTexture(var.type(), var.name());
1552 visitor->VisitSampler(var.type(), String(var.name()) + SAMPLER_SUFFIX);
1553 } else {
1554 // Visit a regular variable.
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001555 visitor->VisitVariable(var, decl.value().get());
Timothy Liangee84fe12018-05-18 14:38:19 -04001556 }
1557 }
1558 }
John Stilescdcdb042020-07-06 09:03:51 -04001559}
1560
1561void MetalCodeGenerator::writeGlobalStruct() {
1562 class : public GlobalStructVisitor {
1563 public:
1564 void VisitInterfaceBlock(const InterfaceBlock& block, const String& blockName) override {
1565 this->AddElement();
1566 fCodeGen->write(" constant ");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001567 fCodeGen->write(block.typeName());
John Stilescdcdb042020-07-06 09:03:51 -04001568 fCodeGen->write("* ");
1569 fCodeGen->writeName(blockName);
1570 fCodeGen->write(";\n");
1571 }
1572 void VisitTexture(const Type& type, const String& name) override {
1573 this->AddElement();
1574 fCodeGen->write(" ");
1575 fCodeGen->writeType(type);
1576 fCodeGen->write(" ");
1577 fCodeGen->writeName(name);
1578 fCodeGen->write(";\n");
1579 }
1580 void VisitSampler(const Type&, const String& name) override {
1581 this->AddElement();
1582 fCodeGen->write(" sampler ");
1583 fCodeGen->writeName(name);
1584 fCodeGen->write(";\n");
1585 }
1586 void VisitVariable(const Variable& var, const Expression* value) override {
1587 this->AddElement();
1588 fCodeGen->write(" ");
Ethan Nicholas30d30222020-09-11 12:27:26 -04001589 fCodeGen->writeType(var.type());
John Stilescdcdb042020-07-06 09:03:51 -04001590 fCodeGen->write(" ");
Ethan Nicholase2c49992020-10-05 11:49:11 -04001591 fCodeGen->writeName(var.name());
John Stilescdcdb042020-07-06 09:03:51 -04001592 fCodeGen->write(";\n");
1593 }
1594 void AddElement() {
1595 if (fFirst) {
1596 fCodeGen->write("struct Globals {\n");
1597 fFirst = false;
1598 }
1599 }
1600 void Finish() {
1601 if (!fFirst) {
1602 fCodeGen->write("};");
1603 fFirst = true;
1604 }
1605 }
1606
1607 MetalCodeGenerator* fCodeGen = nullptr;
1608 bool fFirst = true;
1609 } visitor;
1610
1611 visitor.fCodeGen = this;
1612 this->visitGlobalStruct(&visitor);
1613 visitor.Finish();
1614}
1615
1616void MetalCodeGenerator::writeGlobalInit() {
1617 class : public GlobalStructVisitor {
1618 public:
1619 void VisitInterfaceBlock(const InterfaceBlock& blockType,
1620 const String& blockName) override {
1621 this->AddElement();
1622 fCodeGen->write("&");
1623 fCodeGen->writeName(blockName);
1624 }
1625 void VisitTexture(const Type&, const String& name) override {
1626 this->AddElement();
1627 fCodeGen->writeName(name);
1628 }
1629 void VisitSampler(const Type&, const String& name) override {
1630 this->AddElement();
1631 fCodeGen->writeName(name);
1632 }
1633 void VisitVariable(const Variable& var, const Expression* value) override {
1634 this->AddElement();
1635 if (value) {
1636 fCodeGen->writeVarInitializer(var, *value);
1637 } else {
1638 fCodeGen->write("{}");
1639 }
1640 }
1641 void AddElement() {
1642 if (fFirst) {
1643 fCodeGen->write(" Globals globalStruct{");
1644 fFirst = false;
1645 } else {
1646 fCodeGen->write(", ");
1647 }
1648 }
1649 void Finish() {
1650 if (!fFirst) {
1651 fCodeGen->writeLine("};");
1652 fCodeGen->writeLine(" thread Globals* _globals = &globalStruct;");
1653 fCodeGen->writeLine(" (void)_globals;");
1654 }
1655 }
1656 MetalCodeGenerator* fCodeGen = nullptr;
1657 bool fFirst = true;
1658 } visitor;
1659
1660 visitor.fCodeGen = this;
1661 this->visitGlobalStruct(&visitor);
1662 visitor.Finish();
Timothy Liangee84fe12018-05-18 14:38:19 -04001663}
1664
Ethan Nicholascc305772017-10-13 16:17:45 -04001665void MetalCodeGenerator::writeProgramElement(const ProgramElement& e) {
Ethan Nicholase6592142020-09-08 10:22:09 -04001666 switch (e.kind()) {
1667 case ProgramElement::Kind::kExtension:
Ethan Nicholascc305772017-10-13 16:17:45 -04001668 break;
Brian Osmanc0213602020-10-06 14:43:32 -04001669 case ProgramElement::Kind::kGlobalVar: {
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001670 const GlobalVarDeclaration& global = e.as<GlobalVarDeclaration>();
1671 const VarDeclaration& decl = global.declaration()->as<VarDeclaration>();
1672 int builtin = decl.var().modifiers().fLayout.fBuiltin;
Brian Osmanc0213602020-10-06 14:43:32 -04001673 if (-1 == builtin) {
1674 // normal var
1675 this->writeVarDeclaration(decl, true);
1676 this->writeLine();
1677 } else if (SK_FRAGCOLOR_BUILTIN == builtin) {
1678 // ignore
Ethan Nicholascc305772017-10-13 16:17:45 -04001679 }
1680 break;
1681 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001682 case ProgramElement::Kind::kInterfaceBlock:
Timothy Liang7d637782018-06-05 09:58:07 -04001683 // handled in writeInterfaceBlocks, do nothing
Ethan Nicholascc305772017-10-13 16:17:45 -04001684 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001685 case ProgramElement::Kind::kFunction:
John Stiles3dc0da62020-08-19 17:48:31 -04001686 this->writeFunction(e.as<FunctionDefinition>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001687 break;
John Stiles569249b2020-11-03 12:18:22 -05001688 case ProgramElement::Kind::kFunctionPrototype:
1689 this->writeFunctionPrototype(e.as<FunctionPrototype>());
1690 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001691 case ProgramElement::Kind::kModifiers:
Ethan Nicholas077050b2020-10-13 10:30:20 -04001692 this->writeModifiers(e.as<ModifiersDeclaration>().modifiers(), true);
Ethan Nicholascc305772017-10-13 16:17:45 -04001693 this->writeLine(";");
1694 break;
1695 default:
Ethan Nicholas2a099da2020-01-02 14:40:54 -05001696#ifdef SK_DEBUG
1697 ABORT("unsupported program element: %s\n", e.description().c_str());
1698#endif
1699 break;
Ethan Nicholascc305772017-10-13 16:17:45 -04001700 }
1701}
1702
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001703MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const Expression* e) {
1704 if (!e) {
1705 return kNo_Requirements;
1706 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001707 switch (e->kind()) {
1708 case Expression::Kind::kFunctionCall: {
John Stiles3dc0da62020-08-19 17:48:31 -04001709 const FunctionCall& f = e->as<FunctionCall>();
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001710 Requirements result = this->requirements(f.function());
1711 for (const auto& arg : f.arguments()) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001712 result |= this->requirements(arg.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001713 }
1714 return result;
1715 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001716 case Expression::Kind::kConstructor: {
John Stiles3dc0da62020-08-19 17:48:31 -04001717 const Constructor& c = e->as<Constructor>();
Ethan Nicholascc305772017-10-13 16:17:45 -04001718 Requirements result = kNo_Requirements;
Ethan Nicholasf70f0442020-09-29 12:41:35 -04001719 for (const auto& arg : c.arguments()) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001720 result |= this->requirements(arg.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001721 }
1722 return result;
1723 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001724 case Expression::Kind::kFieldAccess: {
John Stiles3dc0da62020-08-19 17:48:31 -04001725 const FieldAccess& f = e->as<FieldAccess>();
Ethan Nicholas7a95b202020-10-09 11:55:40 -04001726 if (FieldAccess::OwnerKind::kAnonymousInterfaceBlock == f.ownerKind()) {
Timothy Liang7d637782018-06-05 09:58:07 -04001727 return kGlobals_Requirement;
1728 }
Ethan Nicholas7a95b202020-10-09 11:55:40 -04001729 return this->requirements(f.base().get());
Timothy Liang7d637782018-06-05 09:58:07 -04001730 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001731 case Expression::Kind::kSwizzle:
Ethan Nicholas6b4d5812020-10-12 16:11:51 -04001732 return this->requirements(e->as<Swizzle>().base().get());
Ethan Nicholase6592142020-09-08 10:22:09 -04001733 case Expression::Kind::kBinary: {
1734 const BinaryExpression& bin = e->as<BinaryExpression>();
John Stiles2d4f9592020-10-30 10:29:12 -04001735 return this->requirements(bin.left().get()) |
1736 this->requirements(bin.right().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001737 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001738 case Expression::Kind::kIndex: {
John Stiles3dc0da62020-08-19 17:48:31 -04001739 const IndexExpression& idx = e->as<IndexExpression>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04001740 return this->requirements(idx.base().get()) | this->requirements(idx.index().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001741 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001742 case Expression::Kind::kPrefix:
Ethan Nicholas444ccc62020-10-09 10:16:22 -04001743 return this->requirements(e->as<PrefixExpression>().operand().get());
Ethan Nicholase6592142020-09-08 10:22:09 -04001744 case Expression::Kind::kPostfix:
Ethan Nicholas444ccc62020-10-09 10:16:22 -04001745 return this->requirements(e->as<PostfixExpression>().operand().get());
Ethan Nicholase6592142020-09-08 10:22:09 -04001746 case Expression::Kind::kTernary: {
John Stiles3dc0da62020-08-19 17:48:31 -04001747 const TernaryExpression& t = e->as<TernaryExpression>();
Ethan Nicholasdd218162020-10-08 05:48:01 -04001748 return this->requirements(t.test().get()) | this->requirements(t.ifTrue().get()) |
1749 this->requirements(t.ifFalse().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001750 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001751 case Expression::Kind::kVariableReference: {
John Stiles3dc0da62020-08-19 17:48:31 -04001752 const VariableReference& v = e->as<VariableReference>();
Ethan Nicholas78686922020-10-08 06:46:27 -04001753 const Modifiers& modifiers = v.variable()->modifiers();
Ethan Nicholascc305772017-10-13 16:17:45 -04001754 Requirements result = kNo_Requirements;
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001755 if (modifiers.fLayout.fBuiltin == SK_FRAGCOORD_BUILTIN) {
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -04001756 result = kGlobals_Requirement | kFragCoord_Requirement;
Ethan Nicholas453f67f2020-10-09 10:43:45 -04001757 } else if (Variable::Storage::kGlobal == v.variable()->storage()) {
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001758 if (modifiers.fFlags & Modifiers::kIn_Flag) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001759 result = kInputs_Requirement;
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001760 } else if (modifiers.fFlags & Modifiers::kOut_Flag) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001761 result = kOutputs_Requirement;
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001762 } else if (modifiers.fFlags & Modifiers::kUniform_Flag &&
Ethan Nicholas78686922020-10-08 06:46:27 -04001763 v.variable()->type().typeKind() != Type::TypeKind::kSampler) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001764 result = kUniforms_Requirement;
Timothy Liangee84fe12018-05-18 14:38:19 -04001765 } else {
1766 result = kGlobals_Requirement;
Ethan Nicholascc305772017-10-13 16:17:45 -04001767 }
1768 }
1769 return result;
1770 }
1771 default:
1772 return kNo_Requirements;
1773 }
1774}
1775
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001776MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const Statement* s) {
1777 if (!s) {
1778 return kNo_Requirements;
1779 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001780 switch (s->kind()) {
1781 case Statement::Kind::kBlock: {
Ethan Nicholascc305772017-10-13 16:17:45 -04001782 Requirements result = kNo_Requirements;
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001783 for (const std::unique_ptr<Statement>& child : s->as<Block>().children()) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001784 result |= this->requirements(child.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001785 }
1786 return result;
1787 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001788 case Statement::Kind::kVarDeclaration: {
John Stiles3dc0da62020-08-19 17:48:31 -04001789 const VarDeclaration& var = s->as<VarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001790 return this->requirements(var.value().get());
Timothy Liang7d637782018-06-05 09:58:07 -04001791 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001792 case Statement::Kind::kExpression:
Ethan Nicholasd503a5a2020-09-30 09:29:55 -04001793 return this->requirements(s->as<ExpressionStatement>().expression().get());
Ethan Nicholase6592142020-09-08 10:22:09 -04001794 case Statement::Kind::kReturn: {
John Stiles3dc0da62020-08-19 17:48:31 -04001795 const ReturnStatement& r = s->as<ReturnStatement>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04001796 return this->requirements(r.expression().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001797 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001798 case Statement::Kind::kIf: {
John Stiles3dc0da62020-08-19 17:48:31 -04001799 const IfStatement& i = s->as<IfStatement>();
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04001800 return this->requirements(i.test().get()) |
1801 this->requirements(i.ifTrue().get()) |
1802 this->requirements(i.ifFalse().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001803 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001804 case Statement::Kind::kFor: {
John Stiles3dc0da62020-08-19 17:48:31 -04001805 const ForStatement& f = s->as<ForStatement>();
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04001806 return this->requirements(f.initializer().get()) |
1807 this->requirements(f.test().get()) |
1808 this->requirements(f.next().get()) |
1809 this->requirements(f.statement().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001810 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001811 case Statement::Kind::kWhile: {
John Stiles3dc0da62020-08-19 17:48:31 -04001812 const WhileStatement& w = s->as<WhileStatement>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04001813 return this->requirements(w.test().get()) |
1814 this->requirements(w.statement().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001815 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001816 case Statement::Kind::kDo: {
John Stiles3dc0da62020-08-19 17:48:31 -04001817 const DoStatement& d = s->as<DoStatement>();
Ethan Nicholas1fd61162020-09-28 13:14:19 -04001818 return this->requirements(d.test().get()) |
1819 this->requirements(d.statement().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001820 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001821 case Statement::Kind::kSwitch: {
John Stiles3dc0da62020-08-19 17:48:31 -04001822 const SwitchStatement& sw = s->as<SwitchStatement>();
Ethan Nicholas01b05e52020-10-22 15:53:41 -04001823 Requirements result = this->requirements(sw.value().get());
John Stiles2d4f9592020-10-30 10:29:12 -04001824 for (const std::unique_ptr<SwitchCase>& sc : sw.cases()) {
1825 for (const auto& st : sc->statements()) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001826 result |= this->requirements(st.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001827 }
1828 }
1829 return result;
1830 }
1831 default:
1832 return kNo_Requirements;
1833 }
1834}
1835
1836MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const FunctionDeclaration& f) {
Ethan Nicholased84b732020-10-08 11:45:44 -04001837 if (f.isBuiltin()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001838 return kNo_Requirements;
1839 }
1840 auto found = fRequirements.find(&f);
1841 if (found == fRequirements.end()) {
Ethan Nicholas65a8f562019-04-19 14:00:26 -04001842 fRequirements[&f] = kNo_Requirements;
Brian Osman133724c2020-10-28 14:14:39 -04001843 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04001844 if (e->is<FunctionDefinition>()) {
1845 const FunctionDefinition& def = e->as<FunctionDefinition>();
Ethan Nicholas0a5d0962020-10-14 13:33:18 -04001846 if (&def.declaration() == &f) {
1847 Requirements reqs = this->requirements(def.body().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001848 fRequirements[&f] = reqs;
1849 return reqs;
1850 }
1851 }
1852 }
John Stiles569249b2020-11-03 12:18:22 -05001853 // We never found a definition for this declared function, but it's legal to prototype a
1854 // function without ever giving a definition, as long as you don't call it.
1855 return kNo_Requirements;
Ethan Nicholascc305772017-10-13 16:17:45 -04001856 }
1857 return found->second;
1858}
1859
Timothy Liangb8eeb802018-07-23 16:46:16 -04001860bool MetalCodeGenerator::generateCode() {
Ethan Nicholascc305772017-10-13 16:17:45 -04001861 OutputStream* rawOut = fOut;
1862 fOut = &fHeader;
1863 fProgramKind = fProgram.fKind;
1864 this->writeHeader();
1865 this->writeUniformStruct();
1866 this->writeInputStruct();
Timothy Liang7d637782018-06-05 09:58:07 -04001867 this->writeOutputStruct();
1868 this->writeInterfaceBlocks();
Timothy Liangee84fe12018-05-18 14:38:19 -04001869 this->writeGlobalStruct();
Ethan Nicholascc305772017-10-13 16:17:45 -04001870 StringStream body;
1871 fOut = &body;
Brian Osman133724c2020-10-28 14:14:39 -04001872 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04001873 this->writeProgramElement(*e);
Ethan Nicholascc305772017-10-13 16:17:45 -04001874 }
1875 fOut = rawOut;
1876
1877 write_stringstream(fHeader, *rawOut);
Chris Daltondba7aab2018-11-15 10:57:49 -05001878 write_stringstream(fExtraFunctions, *rawOut);
Ethan Nicholascc305772017-10-13 16:17:45 -04001879 write_stringstream(body, *rawOut);
Brian Osman8609a242020-09-08 14:01:49 -04001880 return 0 == fErrors.errorCount();
Ethan Nicholascc305772017-10-13 16:17:45 -04001881}
1882
John Stilesa6841be2020-08-06 14:11:56 -04001883} // namespace SkSL