blob: 301d095c8e949551c8a6e2b2f8df9ebe05e72ea4 [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)
Brian Osman46787d52020-11-24 14:18:23 -050035 fIntrinsicMap[String("distance")] = SPECIAL(Distance);
36 fIntrinsicMap[String("dot")] = SPECIAL(Dot);
37 fIntrinsicMap[String("length")] = SPECIAL(Length);
Timothy Liang651286f2018-06-07 09:55:33 -040038 fIntrinsicMap[String("mod")] = SPECIAL(Mod);
Brian Osman46787d52020-11-24 14:18:23 -050039 fIntrinsicMap[String("normalize")] = SPECIAL(Normalize);
40 fIntrinsicMap[String("sample")] = SPECIAL(Texture);
Ethan Nicholas0dc80872019-02-08 15:46:24 -050041 fIntrinsicMap[String("equal")] = METAL(Equal);
42 fIntrinsicMap[String("notEqual")] = METAL(NotEqual);
Timothy Lianga06f2152018-05-24 15:33:31 -040043 fIntrinsicMap[String("lessThan")] = METAL(LessThan);
44 fIntrinsicMap[String("lessThanEqual")] = METAL(LessThanEqual);
45 fIntrinsicMap[String("greaterThan")] = METAL(GreaterThan);
46 fIntrinsicMap[String("greaterThanEqual")] = METAL(GreaterThanEqual);
Timothy Liangee84fe12018-05-18 14:38:19 -040047}
48
Ethan Nicholascc305772017-10-13 16:17:45 -040049void MetalCodeGenerator::write(const char* s) {
50 if (!s[0]) {
51 return;
52 }
53 if (fAtLineStart) {
54 for (int i = 0; i < fIndentation; i++) {
55 fOut->writeText(" ");
56 }
57 }
58 fOut->writeText(s);
59 fAtLineStart = false;
60}
61
62void MetalCodeGenerator::writeLine(const char* s) {
63 this->write(s);
64 fOut->writeText(fLineEnding);
65 fAtLineStart = true;
66}
67
68void MetalCodeGenerator::write(const String& s) {
69 this->write(s.c_str());
70}
71
72void MetalCodeGenerator::writeLine(const String& s) {
73 this->writeLine(s.c_str());
74}
75
76void MetalCodeGenerator::writeLine() {
77 this->writeLine("");
78}
79
80void MetalCodeGenerator::writeExtension(const Extension& ext) {
Ethan Nicholasefb09e22020-09-30 10:17:00 -040081 this->writeLine("#extension " + ext.name() + " : enable");
Ethan Nicholascc305772017-10-13 16:17:45 -040082}
83
Ethan Nicholas45fa8102020-01-13 10:58:49 -050084String MetalCodeGenerator::typeName(const Type& type) {
Ethan Nicholase6592142020-09-08 10:22:09 -040085 switch (type.typeKind()) {
86 case Type::TypeKind::kVector:
Ethan Nicholas45fa8102020-01-13 10:58:49 -050087 return this->typeName(type.componentType()) + to_string(type.columns());
Ethan Nicholase6592142020-09-08 10:22:09 -040088 case Type::TypeKind::kMatrix:
Ethan Nicholas45fa8102020-01-13 10:58:49 -050089 return this->typeName(type.componentType()) + to_string(type.columns()) + "x" +
90 to_string(type.rows());
Ethan Nicholase6592142020-09-08 10:22:09 -040091 case Type::TypeKind::kSampler:
Ethan Nicholas45fa8102020-01-13 10:58:49 -050092 return "texture2d<float>"; // FIXME - support other texture types;
Ethan Nicholascc305772017-10-13 16:17:45 -040093 default:
Timothy Liang43d225f2018-07-19 15:27:13 -040094 if (type == *fContext.fHalf_Type) {
95 // FIXME - Currently only supporting floats in MSL to avoid type coercion issues.
Ethan Nicholas45fa8102020-01-13 10:58:49 -050096 return fContext.fFloat_Type->name();
Timothy Liang43d225f2018-07-19 15:27:13 -040097 } else if (type == *fContext.fByte_Type) {
Ethan Nicholas45fa8102020-01-13 10:58:49 -050098 return "char";
Timothy Liang43d225f2018-07-19 15:27:13 -040099 } else if (type == *fContext.fUByte_Type) {
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500100 return "uchar";
Timothy Liang7d637782018-06-05 09:58:07 -0400101 } else {
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500102 return type.name();
Timothy Liang7d637782018-06-05 09:58:07 -0400103 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400104 }
105}
106
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500107void MetalCodeGenerator::writeType(const Type& type) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400108 if (type.typeKind() == Type::TypeKind::kStruct) {
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500109 for (const Type* search : fWrittenStructs) {
110 if (*search == type) {
111 // already written
112 this->write(type.name());
113 return;
114 }
115 }
116 fWrittenStructs.push_back(&type);
117 this->writeLine("struct " + type.name() + " {");
118 fIndentation++;
119 this->writeFields(type.fields(), type.fOffset);
120 fIndentation--;
121 this->write("}");
122 } else {
123 this->write(this->typeName(type));
124 }
125}
126
Ethan Nicholascc305772017-10-13 16:17:45 -0400127void MetalCodeGenerator::writeExpression(const Expression& expr, Precedence parentPrecedence) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400128 switch (expr.kind()) {
129 case Expression::Kind::kBinary:
John Stiles81365af2020-08-18 09:24:00 -0400130 this->writeBinaryExpression(expr.as<BinaryExpression>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400131 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400132 case Expression::Kind::kBoolLiteral:
John Stiles81365af2020-08-18 09:24:00 -0400133 this->writeBoolLiteral(expr.as<BoolLiteral>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400134 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400135 case Expression::Kind::kConstructor:
John Stiles81365af2020-08-18 09:24:00 -0400136 this->writeConstructor(expr.as<Constructor>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400137 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400138 case Expression::Kind::kIntLiteral:
John Stiles81365af2020-08-18 09:24:00 -0400139 this->writeIntLiteral(expr.as<IntLiteral>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400140 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400141 case Expression::Kind::kFieldAccess:
John Stiles81365af2020-08-18 09:24:00 -0400142 this->writeFieldAccess(expr.as<FieldAccess>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400143 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400144 case Expression::Kind::kFloatLiteral:
John Stiles81365af2020-08-18 09:24:00 -0400145 this->writeFloatLiteral(expr.as<FloatLiteral>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400146 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400147 case Expression::Kind::kFunctionCall:
John Stiles81365af2020-08-18 09:24:00 -0400148 this->writeFunctionCall(expr.as<FunctionCall>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400149 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400150 case Expression::Kind::kPrefix:
John Stiles81365af2020-08-18 09:24:00 -0400151 this->writePrefixExpression(expr.as<PrefixExpression>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400152 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400153 case Expression::Kind::kPostfix:
John Stiles81365af2020-08-18 09:24:00 -0400154 this->writePostfixExpression(expr.as<PostfixExpression>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400155 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400156 case Expression::Kind::kSetting:
John Stiles81365af2020-08-18 09:24:00 -0400157 this->writeSetting(expr.as<Setting>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400158 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400159 case Expression::Kind::kSwizzle:
John Stiles81365af2020-08-18 09:24:00 -0400160 this->writeSwizzle(expr.as<Swizzle>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400161 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400162 case Expression::Kind::kVariableReference:
John Stiles81365af2020-08-18 09:24:00 -0400163 this->writeVariableReference(expr.as<VariableReference>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400164 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400165 case Expression::Kind::kTernary:
John Stiles81365af2020-08-18 09:24:00 -0400166 this->writeTernaryExpression(expr.as<TernaryExpression>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400167 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400168 case Expression::Kind::kIndex:
John Stiles81365af2020-08-18 09:24:00 -0400169 this->writeIndexExpression(expr.as<IndexExpression>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400170 break;
171 default:
Ethan Nicholas2a099da2020-01-02 14:40:54 -0500172#ifdef SK_DEBUG
Ethan Nicholascc305772017-10-13 16:17:45 -0400173 ABORT("unsupported expression: %s", expr.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -0500174#endif
175 break;
Ethan Nicholascc305772017-10-13 16:17:45 -0400176 }
177}
178
Timothy Liang6403b0e2018-05-17 10:40:04 -0400179void MetalCodeGenerator::writeIntrinsicCall(const FunctionCall& c) {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400180 auto i = fIntrinsicMap.find(c.function().name());
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400181 SkASSERT(i != fIntrinsicMap.end());
Timothy Liang7d637782018-06-05 09:58:07 -0400182 Intrinsic intrinsic = i->second;
183 int32_t intrinsicId = intrinsic.second;
184 switch (intrinsic.first) {
Timothy Liang6403b0e2018-05-17 10:40:04 -0400185 case kSpecial_IntrinsicKind:
186 return this->writeSpecialIntrinsic(c, (SpecialIntrinsic) intrinsicId);
Timothy Lianga06f2152018-05-24 15:33:31 -0400187 break;
188 case kMetal_IntrinsicKind:
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400189 this->writeExpression(*c.arguments()[0], kSequence_Precedence);
Timothy Lianga06f2152018-05-24 15:33:31 -0400190 switch ((MetalIntrinsic) intrinsicId) {
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500191 case kEqual_MetalIntrinsic:
192 this->write(" == ");
193 break;
194 case kNotEqual_MetalIntrinsic:
195 this->write(" != ");
196 break;
Timothy Lianga06f2152018-05-24 15:33:31 -0400197 case kLessThan_MetalIntrinsic:
198 this->write(" < ");
199 break;
200 case kLessThanEqual_MetalIntrinsic:
201 this->write(" <= ");
202 break;
203 case kGreaterThan_MetalIntrinsic:
204 this->write(" > ");
205 break;
206 case kGreaterThanEqual_MetalIntrinsic:
207 this->write(" >= ");
208 break;
209 default:
210 ABORT("unsupported metal intrinsic kind");
211 }
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400212 this->writeExpression(*c.arguments()[1], kSequence_Precedence);
Timothy Lianga06f2152018-05-24 15:33:31 -0400213 break;
Timothy Liang6403b0e2018-05-17 10:40:04 -0400214 default:
215 ABORT("unsupported intrinsic kind");
216 }
217}
218
Ethan Nicholascc305772017-10-13 16:17:45 -0400219void MetalCodeGenerator::writeFunctionCall(const FunctionCall& c) {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400220 const FunctionDeclaration& function = c.function();
John Stiles8e3b6be2020-10-13 11:14:08 -0400221 const ExpressionArray& arguments = c.arguments();
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400222 const auto& entry = fIntrinsicMap.find(function.name());
Timothy Liang6403b0e2018-05-17 10:40:04 -0400223 if (entry != fIntrinsicMap.end()) {
224 this->writeIntrinsicCall(c);
225 return;
226 }
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400227 const StringFragment& name = function.name();
Ethan Nicholased84b732020-10-08 11:45:44 -0400228 bool builtin = function.isBuiltin();
229 if (builtin && name == "atan" && arguments.size() == 2) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400230 this->write("atan2");
Ethan Nicholased84b732020-10-08 11:45:44 -0400231 } else if (builtin && name == "inversesqrt") {
Timothy Lianga06f2152018-05-24 15:33:31 -0400232 this->write("rsqrt");
Ethan Nicholased84b732020-10-08 11:45:44 -0400233 } else if (builtin && name == "inverse") {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400234 SkASSERT(arguments.size() == 1);
235 this->writeInverseHack(*arguments[0]);
John Stilesa80a3dc2020-10-20 10:24:56 -0400236 } else if (builtin && name == "frexp") {
237 // Our Metal codegen assumes that out params are pointers, but Metal's built-in frexp
238 // actually takes a reference for the exponent, not a pointer. We add in a helper function
239 // here to translate.
240 SkASSERT(arguments.size() == 2);
241 auto [iter, newlyCreated] = fHelpers.insert("frexp");
242 if (newlyCreated) {
243 fExtraFunctions.printf(
244 "float frexp(float arg, thread int* exp) { return frexp(arg, *exp); }\n");
245 }
246 this->write("frexp");
Ethan Nicholased84b732020-10-08 11:45:44 -0400247 } else if (builtin && name == "dFdx") {
Timothy Liang7d637782018-06-05 09:58:07 -0400248 this->write("dfdx");
Ethan Nicholased84b732020-10-08 11:45:44 -0400249 } else if (builtin && name == "dFdy") {
Chris Daltonb8af5ad2019-02-25 14:54:21 -0700250 // Flipping Y also negates the Y derivatives.
251 this->write((fProgram.fSettings.fFlipY) ? "-dfdy" : "dfdy");
Ethan Nicholascc305772017-10-13 16:17:45 -0400252 } else {
Ethan Nicholase2c49992020-10-05 11:49:11 -0400253 this->writeName(name);
Ethan Nicholascc305772017-10-13 16:17:45 -0400254 }
255 this->write("(");
256 const char* separator = "";
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400257 if (this->requirements(function) & kInputs_Requirement) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400258 this->write("_in");
259 separator = ", ";
260 }
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400261 if (this->requirements(function) & kOutputs_Requirement) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400262 this->write(separator);
263 this->write("_out");
264 separator = ", ";
265 }
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400266 if (this->requirements(function) & kUniforms_Requirement) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400267 this->write(separator);
268 this->write("_uniforms");
269 separator = ", ";
270 }
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400271 if (this->requirements(function) & kGlobals_Requirement) {
Timothy Liangee84fe12018-05-18 14:38:19 -0400272 this->write(separator);
273 this->write("_globals");
274 separator = ", ";
275 }
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400276 if (this->requirements(function) & kFragCoord_Requirement) {
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -0400277 this->write(separator);
278 this->write("_fragCoord");
279 separator = ", ";
280 }
Brian Osman5bf3e202020-10-13 10:34:18 -0400281 const std::vector<const Variable*>& parameters = function.parameters();
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400282 for (size_t i = 0; i < arguments.size(); ++i) {
283 const Expression& arg = *arguments[i];
Ethan Nicholascc305772017-10-13 16:17:45 -0400284 this->write(separator);
285 separator = ", ";
Ethan Nicholased84b732020-10-08 11:45:44 -0400286 if (parameters[i]->modifiers().fFlags & Modifiers::kOut_Flag) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400287 this->write("&");
288 }
289 this->writeExpression(arg, kSequence_Precedence);
290 }
291 this->write(")");
292}
293
Chris Daltondba7aab2018-11-15 10:57:49 -0500294void MetalCodeGenerator::writeInverseHack(const Expression& mat) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400295 const Type& type = mat.type();
296 const String& typeName = type.name();
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500297 String name = typeName + "_inverse";
Ethan Nicholas30d30222020-09-11 12:27:26 -0400298 if (type == *fContext.fFloat2x2_Type || type == *fContext.fHalf2x2_Type) {
Chris Daltondba7aab2018-11-15 10:57:49 -0500299 if (fWrittenIntrinsics.find(name) == fWrittenIntrinsics.end()) {
300 fWrittenIntrinsics.insert(name);
301 fExtraFunctions.writeText((
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500302 typeName + " " + name + "(" + typeName + " m) {"
Chris Daltondba7aab2018-11-15 10:57:49 -0500303 " return float2x2(m[1][1], -m[0][1], -m[1][0], m[0][0]) * (1/determinant(m));"
304 "}"
305 ).c_str());
306 }
307 }
Ethan Nicholas30d30222020-09-11 12:27:26 -0400308 else if (type == *fContext.fFloat3x3_Type || type == *fContext.fHalf3x3_Type) {
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500309 if (fWrittenIntrinsics.find(name) == fWrittenIntrinsics.end()) {
310 fWrittenIntrinsics.insert(name);
311 fExtraFunctions.writeText((
312 typeName + " " + name + "(" + typeName + " m) {"
313 " float a00 = m[0][0], a01 = m[0][1], a02 = m[0][2];"
314 " float a10 = m[1][0], a11 = m[1][1], a12 = m[1][2];"
315 " float a20 = m[2][0], a21 = m[2][1], a22 = m[2][2];"
316 " float b01 = a22 * a11 - a12 * a21;"
317 " float b11 = -a22 * a10 + a12 * a20;"
318 " float b21 = a21 * a10 - a11 * a20;"
319 " float det = a00 * b01 + a01 * b11 + a02 * b21;"
320 " return " + typeName +
321 " (b01, (-a22 * a01 + a02 * a21), (a12 * a01 - a02 * a11),"
322 " b11, (a22 * a00 - a02 * a20), (-a12 * a00 + a02 * a10),"
323 " b21, (-a21 * a00 + a01 * a20), (a11 * a00 - a01 * a10)) * "
324 " (1/det);"
325 "}"
326 ).c_str());
327 }
328 }
Ethan Nicholas30d30222020-09-11 12:27:26 -0400329 else if (type == *fContext.fFloat4x4_Type || type == *fContext.fHalf4x4_Type) {
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500330 if (fWrittenIntrinsics.find(name) == fWrittenIntrinsics.end()) {
331 fWrittenIntrinsics.insert(name);
332 fExtraFunctions.writeText((
333 typeName + " " + name + "(" + typeName + " m) {"
334 " float a00 = m[0][0], a01 = m[0][1], a02 = m[0][2], a03 = m[0][3];"
335 " float a10 = m[1][0], a11 = m[1][1], a12 = m[1][2], a13 = m[1][3];"
336 " float a20 = m[2][0], a21 = m[2][1], a22 = m[2][2], a23 = m[2][3];"
337 " float a30 = m[3][0], a31 = m[3][1], a32 = m[3][2], a33 = m[3][3];"
338 " float b00 = a00 * a11 - a01 * a10;"
339 " float b01 = a00 * a12 - a02 * a10;"
340 " float b02 = a00 * a13 - a03 * a10;"
341 " float b03 = a01 * a12 - a02 * a11;"
342 " float b04 = a01 * a13 - a03 * a11;"
343 " float b05 = a02 * a13 - a03 * a12;"
344 " float b06 = a20 * a31 - a21 * a30;"
345 " float b07 = a20 * a32 - a22 * a30;"
346 " float b08 = a20 * a33 - a23 * a30;"
347 " float b09 = a21 * a32 - a22 * a31;"
348 " float b10 = a21 * a33 - a23 * a31;"
349 " float b11 = a22 * a33 - a23 * a32;"
350 " float det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - "
351 " b04 * b07 + b05 * b06;"
352 " return " + typeName + "(a11 * b11 - a12 * b10 + a13 * b09,"
353 " a02 * b10 - a01 * b11 - a03 * b09,"
354 " a31 * b05 - a32 * b04 + a33 * b03,"
355 " a22 * b04 - a21 * b05 - a23 * b03,"
356 " a12 * b08 - a10 * b11 - a13 * b07,"
357 " a00 * b11 - a02 * b08 + a03 * b07,"
358 " a32 * b02 - a30 * b05 - a33 * b01,"
359 " a20 * b05 - a22 * b02 + a23 * b01,"
360 " a10 * b10 - a11 * b08 + a13 * b06,"
361 " a01 * b08 - a00 * b10 - a03 * b06,"
362 " a30 * b04 - a31 * b02 + a33 * b00,"
363 " a21 * b02 - a20 * b04 - a23 * b00,"
364 " a11 * b07 - a10 * b09 - a12 * b06,"
365 " a00 * b09 - a01 * b07 + a02 * b06,"
366 " a31 * b01 - a30 * b03 - a32 * b00,"
367 " a20 * b03 - a21 * b01 + a22 * b00) / det;"
368 "}"
369 ).c_str());
370 }
371 }
Chris Daltondba7aab2018-11-15 10:57:49 -0500372 this->write(name);
373}
374
Timothy Liang6403b0e2018-05-17 10:40:04 -0400375void MetalCodeGenerator::writeSpecialIntrinsic(const FunctionCall & c, SpecialIntrinsic kind) {
John Stiles8e3b6be2020-10-13 11:14:08 -0400376 const ExpressionArray& arguments = c.arguments();
Timothy Liang6403b0e2018-05-17 10:40:04 -0400377 switch (kind) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400378 case kTexture_SpecialIntrinsic: {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400379 this->writeExpression(*arguments[0], kSequence_Precedence);
Timothy Lianga06f2152018-05-24 15:33:31 -0400380 this->write(".sample(");
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400381 this->writeExpression(*arguments[0], kSequence_Precedence);
Timothy Lianga06f2152018-05-24 15:33:31 -0400382 this->write(SAMPLER_SUFFIX);
383 this->write(", ");
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400384 const Type& arg1Type = arguments[1]->type();
Ethan Nicholas30d30222020-09-11 12:27:26 -0400385 if (arg1Type == *fContext.fFloat3_Type) {
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500386 // have to store the vector in a temp variable to avoid double evaluating it
387 String tmpVar = "tmpCoord" + to_string(fVarCount++);
Ethan Nicholas30d30222020-09-11 12:27:26 -0400388 this->fFunctionHeader += " " + this->typeName(arg1Type) + " " + tmpVar + ";\n";
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500389 this->write("(" + tmpVar + " = ");
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400390 this->writeExpression(*arguments[1], kSequence_Precedence);
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500391 this->write(", " + tmpVar + ".xy / " + tmpVar + ".z))");
Timothy Liangee84fe12018-05-18 14:38:19 -0400392 } else {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400393 SkASSERT(arg1Type == *fContext.fFloat2_Type);
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400394 this->writeExpression(*arguments[1], kSequence_Precedence);
Timothy Liangee84fe12018-05-18 14:38:19 -0400395 this->write(")");
396 }
Timothy Liang6403b0e2018-05-17 10:40:04 -0400397 break;
Ethan Nicholas30d30222020-09-11 12:27:26 -0400398 }
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500399 case kMod_SpecialIntrinsic: {
Timothy Liang651286f2018-06-07 09:55:33 -0400400 // 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 -0500401 String tmpX = "tmpX" + to_string(fVarCount++);
402 String tmpY = "tmpY" + to_string(fVarCount++);
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400403 this->fFunctionHeader += " " + this->typeName(arguments[0]->type()) +
Ethan Nicholas30d30222020-09-11 12:27:26 -0400404 " " + tmpX + ", " + tmpY + ";\n";
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500405 this->write("(" + tmpX + " = ");
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400406 this->writeExpression(*arguments[0], kSequence_Precedence);
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500407 this->write(", " + tmpY + " = ");
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400408 this->writeExpression(*arguments[1], kSequence_Precedence);
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500409 this->write(", " + tmpX + " - " + tmpY + " * floor(" + tmpX + " / " + tmpY + "))");
Timothy Liang651286f2018-06-07 09:55:33 -0400410 break;
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500411 }
Brian Osman46787d52020-11-24 14:18:23 -0500412 // GLSL declares scalar versions of most geometric intrinsics, but these don't exist in MSL
413 case kDistance_SpecialIntrinsic: {
414 if (arguments[0]->type().columns() == 1) {
415 this->write("abs(");
416 this->writeExpression(*arguments[0], kAdditive_Precedence);
417 this->write(" - ");
418 this->writeExpression(*arguments[1], kAdditive_Precedence);
419 this->write(")");
420 } else {
421 this->write("distance(");
422 this->writeExpression(*arguments[0], kSequence_Precedence);
423 this->write(", ");
424 this->writeExpression(*arguments[1], kSequence_Precedence);
425 this->write(")");
426 }
427 break;
428 }
429 case kDot_SpecialIntrinsic: {
430 if (arguments[0]->type().columns() == 1) {
431 this->write("(");
432 this->writeExpression(*arguments[0], kMultiplicative_Precedence);
433 this->write(" * ");
434 this->writeExpression(*arguments[1], kMultiplicative_Precedence);
435 this->write(")");
436 } else {
437 this->write("dot(");
438 this->writeExpression(*arguments[0], kSequence_Precedence);
439 this->write(", ");
440 this->writeExpression(*arguments[1], kSequence_Precedence);
441 this->write(")");
442 }
443 break;
444 }
445 case kLength_SpecialIntrinsic: {
446 this->write(arguments[0]->type().columns() == 1 ? "abs(" : "length(");
447 this->writeExpression(*arguments[0], kSequence_Precedence);
448 this->write(")");
449 break;
450 }
451 case kNormalize_SpecialIntrinsic: {
452 this->write(arguments[0]->type().columns() == 1 ? "sign(" : "normalize(");
453 this->writeExpression(*arguments[0], kSequence_Precedence);
454 this->write(")");
455 break;
456 }
Timothy Liang6403b0e2018-05-17 10:40:04 -0400457 default:
458 ABORT("unsupported special intrinsic kind");
459 }
460}
461
John Stilesfcf8cb22020-08-06 14:29:22 -0400462// Assembles a matrix of type floatRxC by resizing another matrix named `x0`.
463// Cells that don't exist in the source matrix will be populated with identity-matrix values.
464void MetalCodeGenerator::assembleMatrixFromMatrix(const Type& sourceMatrix, int rows, int columns) {
465 SkASSERT(rows <= 4);
466 SkASSERT(columns <= 4);
467
468 const char* columnSeparator = "";
469 for (int c = 0; c < columns; ++c) {
470 fExtraFunctions.printf("%sfloat%d(", columnSeparator, rows);
471 columnSeparator = "), ";
472
473 // Determine how many values to take from the source matrix for this row.
474 int swizzleLength = 0;
475 if (c < sourceMatrix.columns()) {
476 swizzleLength = std::min<>(rows, sourceMatrix.rows());
477 }
478
479 // Emit all the values from the source matrix row.
480 bool firstItem;
481 switch (swizzleLength) {
482 case 0: firstItem = true; break;
483 case 1: firstItem = false; fExtraFunctions.printf("x0[%d].x", c); break;
484 case 2: firstItem = false; fExtraFunctions.printf("x0[%d].xy", c); break;
485 case 3: firstItem = false; fExtraFunctions.printf("x0[%d].xyz", c); break;
486 case 4: firstItem = false; fExtraFunctions.printf("x0[%d].xyzw", c); break;
487 default: SkUNREACHABLE;
488 }
489
490 // Emit the placeholder identity-matrix cells.
491 for (int r = swizzleLength; r < rows; ++r) {
492 fExtraFunctions.printf("%s%s", firstItem ? "" : ", ", (r == c) ? "1.0" : "0.0");
493 firstItem = false;
494 }
495 }
496
497 fExtraFunctions.writeText(")");
498}
499
500// Assembles a matrix of type floatRxC by concatenating an arbitrary mix of values, named `x0`,
501// `x1`, etc. An error is written if the expression list don't contain exactly R*C scalars.
John Stiles8e3b6be2020-10-13 11:14:08 -0400502void MetalCodeGenerator::assembleMatrixFromExpressions(const ExpressionArray& args,
503 int rows, int columns) {
John Stilesfcf8cb22020-08-06 14:29:22 -0400504 size_t argIndex = 0;
505 int argPosition = 0;
506
507 const char* columnSeparator = "";
508 for (int c = 0; c < columns; ++c) {
509 fExtraFunctions.printf("%sfloat%d(", columnSeparator, rows);
510 columnSeparator = "), ";
511
512 const char* rowSeparator = "";
513 for (int r = 0; r < rows; ++r) {
514 fExtraFunctions.writeText(rowSeparator);
515 rowSeparator = ", ";
516
517 if (argIndex < args.size()) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400518 const Type& argType = args[argIndex]->type();
Ethan Nicholase6592142020-09-08 10:22:09 -0400519 switch (argType.typeKind()) {
520 case Type::TypeKind::kScalar: {
John Stilesfcf8cb22020-08-06 14:29:22 -0400521 fExtraFunctions.printf("x%zu", argIndex);
522 break;
523 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400524 case Type::TypeKind::kVector: {
John Stilesfcf8cb22020-08-06 14:29:22 -0400525 fExtraFunctions.printf("x%zu[%d]", argIndex, argPosition);
526 break;
527 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400528 case Type::TypeKind::kMatrix: {
John Stilesfcf8cb22020-08-06 14:29:22 -0400529 fExtraFunctions.printf("x%zu[%d][%d]", argIndex,
530 argPosition / argType.rows(),
531 argPosition % argType.rows());
532 break;
533 }
534 default: {
535 SkDEBUGFAIL("incorrect type of argument for matrix constructor");
536 fExtraFunctions.writeText("<error>");
537 break;
538 }
539 }
540
541 ++argPosition;
542 if (argPosition >= argType.columns() * argType.rows()) {
543 ++argIndex;
544 argPosition = 0;
545 }
546 } else {
547 SkDEBUGFAIL("not enough arguments for matrix constructor");
548 fExtraFunctions.writeText("<error>");
549 }
550 }
551 }
552
553 if (argPosition != 0 || argIndex != args.size()) {
554 SkDEBUGFAIL("incorrect number of arguments for matrix constructor");
555 fExtraFunctions.writeText(", <error>");
556 }
557
558 fExtraFunctions.writeText(")");
559}
560
John Stiles1bdafbf2020-05-28 12:17:20 -0400561// Generates a constructor for 'matrix' which reorganizes the input arguments into the proper shape.
562// Keeps track of previously generated constructors so that we won't generate more than one
563// constructor for any given permutation of input argument types. Returns the name of the
564// generated constructor method.
565String MetalCodeGenerator::getMatrixConstructHelper(const Constructor& c) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400566 const Type& matrix = c.type();
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500567 int columns = matrix.columns();
568 int rows = matrix.rows();
John Stiles8e3b6be2020-10-13 11:14:08 -0400569 const ExpressionArray& args = c.arguments();
John Stiles1bdafbf2020-05-28 12:17:20 -0400570
571 // Create the helper-method name and use it as our lookup key.
572 String name;
573 name.appendf("float%dx%d_from", columns, rows);
574 for (const std::unique_ptr<Expression>& expr : args) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400575 name.appendf("_%s", expr->type().displayName().c_str());
John Stiles1bdafbf2020-05-28 12:17:20 -0400576 }
577
578 // If a helper-method has already been synthesized, we don't need to synthesize it again.
579 auto [iter, newlyCreated] = fHelpers.insert(name);
580 if (!newlyCreated) {
581 return name;
582 }
583
584 // Unlike GLSL, Metal requires that matrices are initialized with exactly R vectors of C
585 // components apiece. (In Metal 2.0, you can also supply R*C scalars, but you still cannot
586 // supply a mixture of scalars and vectors.)
587 fExtraFunctions.printf("float%dx%d %s(", columns, rows, name.c_str());
588
589 size_t argIndex = 0;
590 const char* argSeparator = "";
John Stilesfcf8cb22020-08-06 14:29:22 -0400591 for (const std::unique_ptr<Expression>& expr : args) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400592 fExtraFunctions.printf("%s%s x%zu", argSeparator,
Ethan Nicholas30d30222020-09-11 12:27:26 -0400593 expr->type().displayName().c_str(), argIndex++);
John Stiles1bdafbf2020-05-28 12:17:20 -0400594 argSeparator = ", ";
595 }
596
597 fExtraFunctions.printf(") {\n return float%dx%d(", columns, rows);
598
John Stiles9aeed132020-11-24 17:36:06 -0500599 if (args.size() == 1 && args.front()->type().isMatrix()) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400600 this->assembleMatrixFromMatrix(args.front()->type(), rows, columns);
John Stilesfcf8cb22020-08-06 14:29:22 -0400601 } else {
602 this->assembleMatrixFromExpressions(args, rows, columns);
John Stiles1bdafbf2020-05-28 12:17:20 -0400603 }
604
John Stilesfcf8cb22020-08-06 14:29:22 -0400605 fExtraFunctions.writeText(");\n}\n");
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500606 return name;
607}
608
609bool MetalCodeGenerator::canCoerce(const Type& t1, const Type& t2) {
610 if (t1.columns() != t2.columns() || t1.rows() != t2.rows()) {
611 return false;
612 }
613 if (t1.columns() > 1) {
614 return this->canCoerce(t1.componentType(), t2.componentType());
615 }
Ethan Nicholase1f55022019-02-05 17:17:40 -0500616 return t1.isFloat() && t2.isFloat();
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500617}
618
John Stiles1bdafbf2020-05-28 12:17:20 -0400619bool MetalCodeGenerator::matrixConstructHelperIsNeeded(const Constructor& c) {
620 // A matrix construct helper is only necessary if we are, in fact, constructing a matrix.
John Stiles9aeed132020-11-24 17:36:06 -0500621 if (!c.type().isMatrix()) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400622 return false;
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500623 }
John Stiles1bdafbf2020-05-28 12:17:20 -0400624
625 // GLSL is fairly free-form about inputs to its matrix constructors, but Metal is not; it
626 // expects exactly R vectors of C components apiece. (Metal 2.0 also allows a list of R*C
627 // scalars.) Some cases are simple to translate and so we handle those inline--e.g. a list of
628 // scalars can be constructed trivially. In more complex cases, we generate a helper function
629 // that converts our inputs into a properly-shaped matrix.
630 // A matrix construct helper method is always used if any input argument is a matrix.
631 // Helper methods are also necessary when any argument would span multiple rows. For instance:
632 //
633 // float2 x = (1, 2);
634 // float3x2(x, 3, 4, 5, 6) = | 1 3 5 | = no helper needed; conversion can be done inline
635 // | 2 4 6 |
636 //
637 // float2 x = (2, 3);
638 // float3x2(1, x, 4, 5, 6) = | 1 3 5 | = x spans multiple rows; a helper method will be used
639 // | 2 4 6 |
640 //
641 // float4 x = (1, 2, 3, 4);
642 // float2x2(x) = | 1 3 | = x spans multiple rows; a helper method will be used
643 // | 2 4 |
644 //
645
646 int position = 0;
Ethan Nicholasf70f0442020-09-29 12:41:35 -0400647 for (const std::unique_ptr<Expression>& expr : c.arguments()) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400648 // If an input argument is a matrix, we need a helper function.
John Stiles9aeed132020-11-24 17:36:06 -0500649 if (expr->type().isMatrix()) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400650 return true;
651 }
Ethan Nicholas30d30222020-09-11 12:27:26 -0400652 position += expr->type().columns();
653 if (position > c.type().rows()) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400654 // An input argument would span multiple rows; a helper function is required.
655 return true;
656 }
Ethan Nicholas30d30222020-09-11 12:27:26 -0400657 if (position == c.type().rows()) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400658 // We've advanced to the end of a row. Wrap to the start of the next row.
659 position = 0;
660 }
661 }
662
663 return false;
664}
665
666void MetalCodeGenerator::writeConstructor(const Constructor& c, Precedence parentPrecedence) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400667 const Type& constructorType = c.type();
John Stiles1bdafbf2020-05-28 12:17:20 -0400668 // Handle special cases for single-argument constructors.
Ethan Nicholasf70f0442020-09-29 12:41:35 -0400669 if (c.arguments().size() == 1) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400670 // If the type is coercible, emit it directly.
Ethan Nicholasf70f0442020-09-29 12:41:35 -0400671 const Expression& arg = *c.arguments().front();
Ethan Nicholas30d30222020-09-11 12:27:26 -0400672 const Type& argType = arg.type();
673 if (this->canCoerce(constructorType, argType)) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400674 this->writeExpression(arg, parentPrecedence);
675 return;
676 }
677
678 // Metal supports creating matrices with a scalar on the diagonal via the single-argument
679 // matrix constructor.
John Stiles9aeed132020-11-24 17:36:06 -0500680 if (constructorType.isMatrix() && argType.isNumber()) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400681 const Type& matrix = constructorType;
John Stiles1bdafbf2020-05-28 12:17:20 -0400682 this->write("float");
683 this->write(to_string(matrix.columns()));
684 this->write("x");
685 this->write(to_string(matrix.rows()));
686 this->write("(");
687 this->writeExpression(arg, parentPrecedence);
688 this->write(")");
689 return;
690 }
691 }
692
693 // Emit and invoke a matrix-constructor helper method if one is necessary.
694 if (this->matrixConstructHelperIsNeeded(c)) {
695 this->write(this->getMatrixConstructHelper(c));
John Stiles1fa15b12020-05-28 17:36:54 +0000696 this->write("(");
697 const char* separator = "";
Ethan Nicholasf70f0442020-09-29 12:41:35 -0400698 for (const std::unique_ptr<Expression>& expr : c.arguments()) {
John Stiles1fa15b12020-05-28 17:36:54 +0000699 this->write(separator);
700 separator = ", ";
John Stiles1bdafbf2020-05-28 12:17:20 -0400701 this->writeExpression(*expr, kSequence_Precedence);
John Stilesdaa573e2020-05-28 12:17:20 -0400702 }
John Stiles1fa15b12020-05-28 17:36:54 +0000703 this->write(")");
John Stiles1bdafbf2020-05-28 12:17:20 -0400704 return;
John Stilesdaa573e2020-05-28 12:17:20 -0400705 }
John Stiles1bdafbf2020-05-28 12:17:20 -0400706
707 // Explicitly invoke the constructor, passing in the necessary arguments.
Ethan Nicholas30d30222020-09-11 12:27:26 -0400708 this->writeType(constructorType);
John Stiles1bdafbf2020-05-28 12:17:20 -0400709 this->write("(");
710 const char* separator = "";
711 int scalarCount = 0;
Ethan Nicholasf70f0442020-09-29 12:41:35 -0400712 for (const std::unique_ptr<Expression>& arg : c.arguments()) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400713 const Type& argType = arg->type();
John Stiles1bdafbf2020-05-28 12:17:20 -0400714 this->write(separator);
715 separator = ", ";
John Stiles9aeed132020-11-24 17:36:06 -0500716 if (constructorType.isMatrix() &&
Ethan Nicholas30d30222020-09-11 12:27:26 -0400717 argType.columns() < constructorType.rows()) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400718 // Merge scalars and smaller vectors together.
719 if (!scalarCount) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400720 this->writeType(constructorType.componentType());
721 this->write(to_string(constructorType.rows()));
John Stiles1bdafbf2020-05-28 12:17:20 -0400722 this->write("(");
723 }
Ethan Nicholas30d30222020-09-11 12:27:26 -0400724 scalarCount += argType.columns();
John Stiles1bdafbf2020-05-28 12:17:20 -0400725 }
726 this->writeExpression(*arg, kSequence_Precedence);
Ethan Nicholas30d30222020-09-11 12:27:26 -0400727 if (scalarCount && scalarCount == constructorType.rows()) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400728 this->write(")");
729 scalarCount = 0;
730 }
731 }
732 this->write(")");
Ethan Nicholascc305772017-10-13 16:17:45 -0400733}
734
735void MetalCodeGenerator::writeFragCoord() {
Ethan Nicholasf931e402019-07-26 15:40:33 -0400736 if (fRTHeightName.length()) {
737 this->write("float4(_fragCoord.x, ");
738 this->write(fRTHeightName.c_str());
739 this->write(" - _fragCoord.y, 0.0, _fragCoord.w)");
Jim Van Verth6bc650e2019-02-07 14:53:23 -0500740 } else {
741 this->write("float4(_fragCoord.x, _fragCoord.y, 0.0, _fragCoord.w)");
742 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400743}
744
745void MetalCodeGenerator::writeVariableReference(const VariableReference& ref) {
Ethan Nicholas78686922020-10-08 06:46:27 -0400746 switch (ref.variable()->modifiers().fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400747 case SK_FRAGCOLOR_BUILTIN:
Timothy Liang7d637782018-06-05 09:58:07 -0400748 this->write("_out->sk_FragColor");
Ethan Nicholascc305772017-10-13 16:17:45 -0400749 break;
Timothy Liang6403b0e2018-05-17 10:40:04 -0400750 case SK_FRAGCOORD_BUILTIN:
751 this->writeFragCoord();
752 break;
Timothy Liangdc89f192018-06-13 09:20:31 -0400753 case SK_VERTEXID_BUILTIN:
754 this->write("sk_VertexID");
755 break;
756 case SK_INSTANCEID_BUILTIN:
757 this->write("sk_InstanceID");
758 break;
Timothy Liang7b8875d2018-08-10 09:42:31 -0400759 case SK_CLOCKWISE_BUILTIN:
760 // We'd set the front facing winding in the MTLRenderCommandEncoder to be counter
Brian Salomonf4ba4ec2020-03-19 15:54:28 -0400761 // clockwise to match Skia convention.
Timothy Liang7b8875d2018-08-10 09:42:31 -0400762 this->write(fProgram.fSettings.fFlipY ? "_frontFacing" : "(!_frontFacing)");
763 break;
Ethan Nicholascc305772017-10-13 16:17:45 -0400764 default:
Ethan Nicholas78686922020-10-08 06:46:27 -0400765 const Variable& var = *ref.variable();
Ethan Nicholas453f67f2020-10-09 10:43:45 -0400766 if (var.storage() == Variable::Storage::kGlobal) {
Ethan Nicholas78686922020-10-08 06:46:27 -0400767 if (var.modifiers().fFlags & Modifiers::kIn_Flag) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400768 this->write("_in.");
Ethan Nicholas78686922020-10-08 06:46:27 -0400769 } else if (var.modifiers().fFlags & Modifiers::kOut_Flag) {
Timothy Liangee84fe12018-05-18 14:38:19 -0400770 this->write("_out->");
Ethan Nicholas78686922020-10-08 06:46:27 -0400771 } else if (var.modifiers().fFlags & Modifiers::kUniform_Flag &&
772 var.type().typeKind() != Type::TypeKind::kSampler) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400773 this->write("_uniforms.");
774 } else {
Timothy Liangee84fe12018-05-18 14:38:19 -0400775 this->write("_globals->");
Ethan Nicholascc305772017-10-13 16:17:45 -0400776 }
777 }
Ethan Nicholas78686922020-10-08 06:46:27 -0400778 this->writeName(var.name());
Ethan Nicholascc305772017-10-13 16:17:45 -0400779 }
780}
781
782void MetalCodeGenerator::writeIndexExpression(const IndexExpression& expr) {
Ethan Nicholas2a4952d2020-10-08 15:35:56 -0400783 this->writeExpression(*expr.base(), kPostfix_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400784 this->write("[");
Ethan Nicholas2a4952d2020-10-08 15:35:56 -0400785 this->writeExpression(*expr.index(), kTopLevel_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400786 this->write("]");
787}
788
789void MetalCodeGenerator::writeFieldAccess(const FieldAccess& f) {
Ethan Nicholas7a95b202020-10-09 11:55:40 -0400790 const Type::Field* field = &f.base()->type().fields()[f.fieldIndex()];
791 if (FieldAccess::OwnerKind::kDefault == f.ownerKind()) {
792 this->writeExpression(*f.base(), kPostfix_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400793 this->write(".");
794 }
Timothy Liang7d637782018-06-05 09:58:07 -0400795 switch (field->fModifiers.fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400796 case SK_POSITION_BUILTIN:
Timothy Liangb8eeb802018-07-23 16:46:16 -0400797 this->write("_out->sk_Position");
Ethan Nicholascc305772017-10-13 16:17:45 -0400798 break;
799 default:
Timothy Liang7d637782018-06-05 09:58:07 -0400800 if (field->fName == "sk_PointSize") {
801 this->write("_out->sk_PointSize");
802 } else {
Ethan Nicholas7a95b202020-10-09 11:55:40 -0400803 if (FieldAccess::OwnerKind::kAnonymousInterfaceBlock == f.ownerKind()) {
Timothy Liang7d637782018-06-05 09:58:07 -0400804 this->write("_globals->");
805 this->write(fInterfaceBlockNameMap[fInterfaceBlockMap[field]]);
806 this->write("->");
807 }
Timothy Liang651286f2018-06-07 09:55:33 -0400808 this->writeName(field->fName);
Timothy Lianga06f2152018-05-24 15:33:31 -0400809 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400810 }
811}
812
813void MetalCodeGenerator::writeSwizzle(const Swizzle& swizzle) {
Ethan Nicholas6b4d5812020-10-12 16:11:51 -0400814 this->writeExpression(*swizzle.base(), kPostfix_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400815 this->write(".");
Ethan Nicholas6b4d5812020-10-12 16:11:51 -0400816 for (int c : swizzle.components()) {
Brian Osman25647672020-09-15 15:16:56 -0400817 SkASSERT(c >= 0 && c <= 3);
818 this->write(&("x\0y\0z\0w\0"[c * 2]));
Ethan Nicholascc305772017-10-13 16:17:45 -0400819 }
820}
821
822MetalCodeGenerator::Precedence MetalCodeGenerator::GetBinaryPrecedence(Token::Kind op) {
823 switch (op) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400824 case Token::Kind::TK_STAR: // fall through
825 case Token::Kind::TK_SLASH: // fall through
826 case Token::Kind::TK_PERCENT: return MetalCodeGenerator::kMultiplicative_Precedence;
827 case Token::Kind::TK_PLUS: // fall through
828 case Token::Kind::TK_MINUS: return MetalCodeGenerator::kAdditive_Precedence;
829 case Token::Kind::TK_SHL: // fall through
830 case Token::Kind::TK_SHR: return MetalCodeGenerator::kShift_Precedence;
831 case Token::Kind::TK_LT: // fall through
832 case Token::Kind::TK_GT: // fall through
833 case Token::Kind::TK_LTEQ: // fall through
834 case Token::Kind::TK_GTEQ: return MetalCodeGenerator::kRelational_Precedence;
835 case Token::Kind::TK_EQEQ: // fall through
836 case Token::Kind::TK_NEQ: return MetalCodeGenerator::kEquality_Precedence;
837 case Token::Kind::TK_BITWISEAND: return MetalCodeGenerator::kBitwiseAnd_Precedence;
838 case Token::Kind::TK_BITWISEXOR: return MetalCodeGenerator::kBitwiseXor_Precedence;
839 case Token::Kind::TK_BITWISEOR: return MetalCodeGenerator::kBitwiseOr_Precedence;
840 case Token::Kind::TK_LOGICALAND: return MetalCodeGenerator::kLogicalAnd_Precedence;
841 case Token::Kind::TK_LOGICALXOR: return MetalCodeGenerator::kLogicalXor_Precedence;
842 case Token::Kind::TK_LOGICALOR: return MetalCodeGenerator::kLogicalOr_Precedence;
843 case Token::Kind::TK_EQ: // fall through
844 case Token::Kind::TK_PLUSEQ: // fall through
845 case Token::Kind::TK_MINUSEQ: // fall through
846 case Token::Kind::TK_STAREQ: // fall through
847 case Token::Kind::TK_SLASHEQ: // fall through
848 case Token::Kind::TK_PERCENTEQ: // fall through
849 case Token::Kind::TK_SHLEQ: // fall through
850 case Token::Kind::TK_SHREQ: // fall through
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400851 case Token::Kind::TK_BITWISEANDEQ: // fall through
852 case Token::Kind::TK_BITWISEXOREQ: // fall through
853 case Token::Kind::TK_BITWISEOREQ: return MetalCodeGenerator::kAssignment_Precedence;
854 case Token::Kind::TK_COMMA: return MetalCodeGenerator::kSequence_Precedence;
Ethan Nicholascc305772017-10-13 16:17:45 -0400855 default: ABORT("unsupported binary operator");
856 }
857}
858
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500859void MetalCodeGenerator::writeMatrixTimesEqualHelper(const Type& left, const Type& right,
860 const Type& result) {
861 String key = "TimesEqual" + left.name() + right.name();
862 if (fHelpers.find(key) == fHelpers.end()) {
863 fExtraFunctions.printf("%s operator*=(thread %s& left, thread const %s& right) {\n"
864 " left = left * right;\n"
865 " return left;\n"
Ethan Nicholase2c49992020-10-05 11:49:11 -0400866 "}", String(result.name()).c_str(), String(left.name()).c_str(),
867 String(right.name()).c_str());
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500868 }
869}
870
Ethan Nicholascc305772017-10-13 16:17:45 -0400871void MetalCodeGenerator::writeBinaryExpression(const BinaryExpression& b,
872 Precedence parentPrecedence) {
John Stiles2d4f9592020-10-30 10:29:12 -0400873 const Expression& left = *b.left();
874 const Expression& right = *b.right();
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400875 const Type& leftType = left.type();
876 const Type& rightType = right.type();
877 Token::Kind op = b.getOperator();
878 Precedence precedence = GetBinaryPrecedence(b.getOperator());
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500879 bool needParens = precedence >= parentPrecedence;
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400880 switch (op) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400881 case Token::Kind::TK_EQEQ:
John Stiles9aeed132020-11-24 17:36:06 -0500882 if (leftType.isVector()) {
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500883 this->write("all");
884 needParens = true;
885 }
886 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400887 case Token::Kind::TK_NEQ:
John Stiles9aeed132020-11-24 17:36:06 -0500888 if (leftType.isVector()) {
Jim Van Verth36477b42019-04-11 14:57:30 -0400889 this->write("any");
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500890 needParens = true;
891 }
892 break;
893 default:
894 break;
895 }
896 if (needParens) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400897 this->write("(");
898 }
Brian Osman79457ef2020-09-24 15:01:27 -0400899 if (Compiler::IsAssignment(op) && left.is<VariableReference>() &&
Ethan Nicholas453f67f2020-10-09 10:43:45 -0400900 left.as<VariableReference>().variable()->storage() == Variable::Storage::kParameter &&
Ethan Nicholas78686922020-10-08 06:46:27 -0400901 left.as<VariableReference>().variable()->modifiers().fFlags & Modifiers::kOut_Flag) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400902 // writing to an out parameter. Since we have to turn those into pointers, we have to
903 // dereference it here.
904 this->write("*");
905 }
John Stiles9aeed132020-11-24 17:36:06 -0500906 if (op == Token::Kind::TK_STAREQ && leftType.isMatrix() && rightType.isMatrix()) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400907 this->writeMatrixTimesEqualHelper(leftType, rightType, b.type());
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500908 }
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400909 this->writeExpression(left, precedence);
910 if (op != Token::Kind::TK_EQ && Compiler::IsAssignment(op) &&
911 left.kind() == Expression::Kind::kSwizzle && !left.hasSideEffects()) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400912 // This doesn't compile in Metal:
913 // float4 x = float4(1);
914 // x.xy *= float2x2(...);
915 // with the error message "non-const reference cannot bind to vector element",
916 // but switching it to x.xy = x.xy * float2x2(...) fixes it. We perform this tranformation
917 // as long as the LHS has no side effects, and hope for the best otherwise.
918 this->write(" = ");
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400919 this->writeExpression(left, kAssignment_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400920 this->write(" ");
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400921 String opName = Compiler::OperatorName(op);
922 SkASSERT(opName.endsWith("="));
923 this->write(opName.substr(0, opName.size() - 1).c_str());
Ethan Nicholascc305772017-10-13 16:17:45 -0400924 this->write(" ");
925 } else {
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400926 this->write(String(" ") + Compiler::OperatorName(op) + " ");
Ethan Nicholascc305772017-10-13 16:17:45 -0400927 }
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400928 this->writeExpression(right, precedence);
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500929 if (needParens) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400930 this->write(")");
931 }
932}
933
934void MetalCodeGenerator::writeTernaryExpression(const TernaryExpression& t,
935 Precedence parentPrecedence) {
936 if (kTernary_Precedence >= parentPrecedence) {
937 this->write("(");
938 }
Ethan Nicholasdd218162020-10-08 05:48:01 -0400939 this->writeExpression(*t.test(), kTernary_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400940 this->write(" ? ");
Ethan Nicholasdd218162020-10-08 05:48:01 -0400941 this->writeExpression(*t.ifTrue(), kTernary_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400942 this->write(" : ");
Ethan Nicholasdd218162020-10-08 05:48:01 -0400943 this->writeExpression(*t.ifFalse(), kTernary_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400944 if (kTernary_Precedence >= parentPrecedence) {
945 this->write(")");
946 }
947}
948
949void MetalCodeGenerator::writePrefixExpression(const PrefixExpression& p,
950 Precedence parentPrecedence) {
951 if (kPrefix_Precedence >= parentPrecedence) {
952 this->write("(");
953 }
Ethan Nicholas444ccc62020-10-09 10:16:22 -0400954 this->write(Compiler::OperatorName(p.getOperator()));
955 this->writeExpression(*p.operand(), kPrefix_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400956 if (kPrefix_Precedence >= parentPrecedence) {
957 this->write(")");
958 }
959}
960
961void MetalCodeGenerator::writePostfixExpression(const PostfixExpression& p,
962 Precedence parentPrecedence) {
963 if (kPostfix_Precedence >= parentPrecedence) {
964 this->write("(");
965 }
Ethan Nicholas444ccc62020-10-09 10:16:22 -0400966 this->writeExpression(*p.operand(), kPostfix_Precedence);
967 this->write(Compiler::OperatorName(p.getOperator()));
Ethan Nicholascc305772017-10-13 16:17:45 -0400968 if (kPostfix_Precedence >= parentPrecedence) {
969 this->write(")");
970 }
971}
972
973void MetalCodeGenerator::writeBoolLiteral(const BoolLiteral& b) {
Ethan Nicholas59d660c2020-09-28 09:18:15 -0400974 this->write(b.value() ? "true" : "false");
Ethan Nicholascc305772017-10-13 16:17:45 -0400975}
976
977void MetalCodeGenerator::writeIntLiteral(const IntLiteral& i) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400978 if (i.type() == *fContext.fUInt_Type) {
Ethan Nicholase96cdd12020-09-28 16:27:18 -0400979 this->write(to_string(i.value() & 0xffffffff) + "u");
Ethan Nicholascc305772017-10-13 16:17:45 -0400980 } else {
Ethan Nicholase96cdd12020-09-28 16:27:18 -0400981 this->write(to_string((int32_t) i.value()));
Ethan Nicholascc305772017-10-13 16:17:45 -0400982 }
983}
984
985void MetalCodeGenerator::writeFloatLiteral(const FloatLiteral& f) {
Ethan Nicholasa3f22f12020-10-01 12:13:17 -0400986 this->write(to_string(f.value()));
Ethan Nicholascc305772017-10-13 16:17:45 -0400987}
988
989void MetalCodeGenerator::writeSetting(const Setting& s) {
990 ABORT("internal error; setting was not folded to a constant during compilation\n");
991}
992
John Stiles569249b2020-11-03 12:18:22 -0500993bool MetalCodeGenerator::writeFunctionDeclaration(const FunctionDeclaration& f) {
Ethan Nicholasf931e402019-07-26 15:40:33 -0400994 fRTHeightName = fProgram.fInputs.fRTHeight ? "_globals->_anonInterface0->u_skRTHeight" : "";
Ethan Nicholascc305772017-10-13 16:17:45 -0400995 const char* separator = "";
John Stiles569249b2020-11-03 12:18:22 -0500996 if ("main" == f.name()) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400997 switch (fProgram.fKind) {
998 case Program::kFragment_Kind:
Timothy Liangb8eeb802018-07-23 16:46:16 -0400999 this->write("fragment Outputs fragmentMain");
Ethan Nicholascc305772017-10-13 16:17:45 -04001000 break;
1001 case Program::kVertex_Kind:
Timothy Liangb8eeb802018-07-23 16:46:16 -04001002 this->write("vertex Outputs vertexMain");
Ethan Nicholascc305772017-10-13 16:17:45 -04001003 break;
1004 default:
John Stiles3fabfc02020-09-25 15:51:28 -04001005 fErrors.error(-1, "unsupported kind of program");
John Stiles569249b2020-11-03 12:18:22 -05001006 return false;
Ethan Nicholascc305772017-10-13 16:17:45 -04001007 }
1008 this->write("(Inputs _in [[stage_in]]");
1009 if (-1 != fUniformBuffer) {
1010 this->write(", constant Uniforms& _uniforms [[buffer(" +
1011 to_string(fUniformBuffer) + ")]]");
1012 }
Brian Osman133724c2020-10-28 14:14:39 -04001013 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04001014 if (e->is<GlobalVarDeclaration>()) {
1015 const GlobalVarDeclaration& decls = e->as<GlobalVarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001016 const VarDeclaration& var = decls.declaration()->as<VarDeclaration>();
1017 if (var.var().type().typeKind() == Type::TypeKind::kSampler) {
1018 if (var.var().modifiers().fLayout.fBinding < 0) {
Brian Osmanc0213602020-10-06 14:43:32 -04001019 fErrors.error(decls.fOffset,
1020 "Metal samplers must have 'layout(binding=...)'");
John Stiles569249b2020-11-03 12:18:22 -05001021 return false;
Timothy Liangee84fe12018-05-18 14:38:19 -04001022 }
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001023 if (var.var().type().dimensions() != SpvDim2D) {
John Stiles569249b2020-11-03 12:18:22 -05001024 // Not yet implemented--Skia currently only uses 2D textures.
Brian Osmanc0213602020-10-06 14:43:32 -04001025 fErrors.error(decls.fOffset, "Unsupported texture dimensions");
John Stiles569249b2020-11-03 12:18:22 -05001026 return false;
Brian Osmanc0213602020-10-06 14:43:32 -04001027 }
1028 this->write(", texture2d<float> ");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001029 this->writeName(var.var().name());
Brian Osmanc0213602020-10-06 14:43:32 -04001030 this->write("[[texture(");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001031 this->write(to_string(var.var().modifiers().fLayout.fBinding));
Brian Osmanc0213602020-10-06 14:43:32 -04001032 this->write(")]]");
1033 this->write(", sampler ");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001034 this->writeName(var.var().name());
Brian Osmanc0213602020-10-06 14:43:32 -04001035 this->write(SAMPLER_SUFFIX);
1036 this->write("[[sampler(");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001037 this->write(to_string(var.var().modifiers().fLayout.fBinding));
Brian Osmanc0213602020-10-06 14:43:32 -04001038 this->write(")]]");
Timothy Liang6403b0e2018-05-17 10:40:04 -04001039 }
Brian Osman1179fcf2020-10-08 16:04:40 -04001040 } else if (e->is<InterfaceBlock>()) {
1041 const InterfaceBlock& intf = e->as<InterfaceBlock>();
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001042 if (intf.typeName() == "sk_PerVertex") {
Timothy Lianga06f2152018-05-24 15:33:31 -04001043 continue;
1044 }
1045 this->write(", constant ");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001046 this->writeType(intf.variable().type());
Timothy Lianga06f2152018-05-24 15:33:31 -04001047 this->write("& " );
1048 this->write(fInterfaceBlockNameMap[&intf]);
1049 this->write(" [[buffer(");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001050 this->write(to_string(intf.variable().modifiers().fLayout.fBinding));
Timothy Lianga06f2152018-05-24 15:33:31 -04001051 this->write(")]]");
Timothy Liang6403b0e2018-05-17 10:40:04 -04001052 }
1053 }
Jim Van Verth6bc650e2019-02-07 14:53:23 -05001054 if (fProgram.fKind == Program::kFragment_Kind) {
1055 if (fProgram.fInputs.fRTHeight && fInterfaceBlockNameMap.empty()) {
Timothy Liang5422f9a2018-08-10 10:57:55 -04001056 this->write(", constant sksl_synthetic_uniforms& _anonInterface0 [[buffer(1)]]");
Ethan Nicholasf931e402019-07-26 15:40:33 -04001057 fRTHeightName = "_anonInterface0.u_skRTHeight";
Timothy Liang5422f9a2018-08-10 10:57:55 -04001058 }
Timothy Liang7b8875d2018-08-10 09:42:31 -04001059 this->write(", bool _frontFacing [[front_facing]]");
Timothy Liang7d637782018-06-05 09:58:07 -04001060 this->write(", float4 _fragCoord [[position]]");
Timothy Liangdc89f192018-06-13 09:20:31 -04001061 } else if (fProgram.fKind == Program::kVertex_Kind) {
1062 this->write(", uint sk_VertexID [[vertex_id]], uint sk_InstanceID [[instance_id]]");
Timothy Liang7d637782018-06-05 09:58:07 -04001063 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001064 separator = ", ";
1065 } else {
John Stiles569249b2020-11-03 12:18:22 -05001066 this->writeType(f.returnType());
Timothy Liang651286f2018-06-07 09:55:33 -04001067 this->write(" ");
John Stiles569249b2020-11-03 12:18:22 -05001068 this->writeName(f.name());
Timothy Liang651286f2018-06-07 09:55:33 -04001069 this->write("(");
John Stiles569249b2020-11-03 12:18:22 -05001070 Requirements requirements = this->requirements(f);
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -04001071 if (requirements & kInputs_Requirement) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001072 this->write("Inputs _in");
1073 separator = ", ";
1074 }
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -04001075 if (requirements & kOutputs_Requirement) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001076 this->write(separator);
Timothy Liangee84fe12018-05-18 14:38:19 -04001077 this->write("thread Outputs* _out");
Ethan Nicholascc305772017-10-13 16:17:45 -04001078 separator = ", ";
1079 }
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -04001080 if (requirements & kUniforms_Requirement) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001081 this->write(separator);
1082 this->write("Uniforms _uniforms");
1083 separator = ", ";
1084 }
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -04001085 if (requirements & kGlobals_Requirement) {
Timothy Liangee84fe12018-05-18 14:38:19 -04001086 this->write(separator);
1087 this->write("thread Globals* _globals");
1088 separator = ", ";
1089 }
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -04001090 if (requirements & kFragCoord_Requirement) {
1091 this->write(separator);
1092 this->write("float4 _fragCoord");
1093 separator = ", ";
1094 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001095 }
John Stiles569249b2020-11-03 12:18:22 -05001096 for (const auto& param : f.parameters()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001097 this->write(separator);
1098 separator = ", ";
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001099 this->writeModifiers(param->modifiers(), false);
Ethan Nicholascc305772017-10-13 16:17:45 -04001100 std::vector<int> sizes;
Ethan Nicholas30d30222020-09-11 12:27:26 -04001101 const Type* type = &param->type();
Ethan Nicholase6592142020-09-08 10:22:09 -04001102 while (type->typeKind() == Type::TypeKind::kArray) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001103 sizes.push_back(type->columns());
1104 type = &type->componentType();
1105 }
1106 this->writeType(*type);
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001107 if (param->modifiers().fFlags & Modifiers::kOut_Flag) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001108 this->write("*");
1109 }
Timothy Liang651286f2018-06-07 09:55:33 -04001110 this->write(" ");
Ethan Nicholase2c49992020-10-05 11:49:11 -04001111 this->writeName(param->name());
Ethan Nicholascc305772017-10-13 16:17:45 -04001112 for (int s : sizes) {
Brian Osmane8c26082020-10-01 17:22:45 -04001113 if (s == Type::kUnsizedArray) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001114 this->write("[]");
1115 } else {
1116 this->write("[" + to_string(s) + "]");
1117 }
1118 }
1119 }
John Stiles569249b2020-11-03 12:18:22 -05001120 this->write(")");
1121 return true;
1122}
Ethan Nicholascc305772017-10-13 16:17:45 -04001123
John Stiles569249b2020-11-03 12:18:22 -05001124void MetalCodeGenerator::writeFunctionPrototype(const FunctionPrototype& f) {
1125 this->writeFunctionDeclaration(f.declaration());
1126 this->writeLine(";");
1127}
1128
1129void MetalCodeGenerator::writeFunction(const FunctionDefinition& f) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001130 SkASSERT(!fProgram.fSettings.fFragColorIsInOut);
Brian Salomondc092132018-04-04 10:14:16 -04001131
John Stiles569249b2020-11-03 12:18:22 -05001132 if (!this->writeFunctionDeclaration(f.declaration())) {
1133 return;
1134 }
1135
1136 this->writeLine(" {");
1137
Ethan Nicholas0a5d0962020-10-14 13:33:18 -04001138 if (f.declaration().name() == "main") {
John Stilescdcdb042020-07-06 09:03:51 -04001139 this->writeGlobalInit();
Timothy Liang7d637782018-06-05 09:58:07 -04001140 this->writeLine(" Outputs _outputStruct;");
1141 this->writeLine(" thread Outputs* _out = &_outputStruct;");
Ethan Nicholascc305772017-10-13 16:17:45 -04001142 }
John Stilesc67b3622020-05-28 17:53:13 -04001143
Ethan Nicholascc305772017-10-13 16:17:45 -04001144 fFunctionHeader = "";
1145 OutputStream* oldOut = fOut;
1146 StringStream buffer;
1147 fOut = &buffer;
1148 fIndentation++;
Ethan Nicholas0a5d0962020-10-14 13:33:18 -04001149 for (const std::unique_ptr<Statement>& stmt : f.body()->as<Block>().children()) {
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001150 if (!stmt->isEmpty()) {
1151 this->writeStatement(*stmt);
1152 this->writeLine();
1153 }
1154 }
Ethan Nicholas0a5d0962020-10-14 13:33:18 -04001155 if (f.declaration().name() == "main") {
Ethan Nicholascc305772017-10-13 16:17:45 -04001156 switch (fProgram.fKind) {
1157 case Program::kFragment_Kind:
Timothy Liang7d637782018-06-05 09:58:07 -04001158 this->writeLine("return *_out;");
Ethan Nicholascc305772017-10-13 16:17:45 -04001159 break;
1160 case Program::kVertex_Kind:
Timothy Liangb8eeb802018-07-23 16:46:16 -04001161 this->writeLine("_out->sk_Position.y = -_out->sk_Position.y;");
Timothy Lianga06f2152018-05-24 15:33:31 -04001162 this->writeLine("return *_out;"); // FIXME - detect if function already has return
Ethan Nicholascc305772017-10-13 16:17:45 -04001163 break;
1164 default:
John Stilesf7d70432020-05-28 15:46:38 -04001165 SkDEBUGFAIL("unsupported kind of program");
Ethan Nicholascc305772017-10-13 16:17:45 -04001166 }
1167 }
1168 fIndentation--;
1169 this->writeLine("}");
1170
1171 fOut = oldOut;
1172 this->write(fFunctionHeader);
1173 this->write(buffer.str());
1174}
1175
1176void MetalCodeGenerator::writeModifiers(const Modifiers& modifiers,
1177 bool globalContext) {
1178 if (modifiers.fFlags & Modifiers::kOut_Flag) {
1179 this->write("thread ");
1180 }
1181 if (modifiers.fFlags & Modifiers::kConst_Flag) {
Timothy Liangee84fe12018-05-18 14:38:19 -04001182 this->write("constant ");
Ethan Nicholascc305772017-10-13 16:17:45 -04001183 }
1184}
1185
1186void MetalCodeGenerator::writeInterfaceBlock(const InterfaceBlock& intf) {
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001187 if ("sk_PerVertex" == intf.typeName()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001188 return;
1189 }
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001190 this->writeModifiers(intf.variable().modifiers(), true);
Timothy Liangdc89f192018-06-13 09:20:31 -04001191 this->write("struct ");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001192 this->writeLine(intf.typeName() + " {");
1193 const Type* structType = &intf.variable().type();
Timothy Lianga06f2152018-05-24 15:33:31 -04001194 fWrittenStructs.push_back(structType);
Ethan Nicholase6592142020-09-08 10:22:09 -04001195 while (structType->typeKind() == Type::TypeKind::kArray) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001196 structType = &structType->componentType();
1197 }
Timothy Liangdc89f192018-06-13 09:20:31 -04001198 fIndentation++;
1199 writeFields(structType->fields(), structType->fOffset, &intf);
Jim Van Verth3d482992019-02-07 10:48:05 -05001200 if (fProgram.fInputs.fRTHeight) {
Timothy Liang7d637782018-06-05 09:58:07 -04001201 this->writeLine("float u_skRTHeight;");
Ethan Nicholascc305772017-10-13 16:17:45 -04001202 }
1203 fIndentation--;
1204 this->write("}");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001205 if (intf.instanceName().size()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001206 this->write(" ");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001207 this->write(intf.instanceName());
1208 for (const auto& size : intf.sizes()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001209 this->write("[");
1210 if (size) {
1211 this->writeExpression(*size, kTopLevel_Precedence);
1212 }
1213 this->write("]");
1214 }
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001215 fInterfaceBlockNameMap[&intf] = intf.instanceName();
Timothy Lianga06f2152018-05-24 15:33:31 -04001216 } else {
Timothy Liang7d637782018-06-05 09:58:07 -04001217 fInterfaceBlockNameMap[&intf] = "_anonInterface" + to_string(fAnonInterfaceCount++);
Ethan Nicholascc305772017-10-13 16:17:45 -04001218 }
1219 this->writeLine(";");
1220}
1221
Timothy Liangdc89f192018-06-13 09:20:31 -04001222void MetalCodeGenerator::writeFields(const std::vector<Type::Field>& fields, int parentOffset,
1223 const InterfaceBlock* parentIntf) {
Timothy Liang609fbe32018-08-10 16:40:49 -04001224 MemoryLayout memoryLayout(MemoryLayout::kMetal_Standard);
Timothy Liangdc89f192018-06-13 09:20:31 -04001225 int currentOffset = 0;
1226 for (const auto& field: fields) {
1227 int fieldOffset = field.fModifiers.fLayout.fOffset;
1228 const Type* fieldType = field.fType;
John Stiles0023c0c2020-11-16 13:32:18 -05001229 if (!memoryLayout.layoutIsSupported(*fieldType)) {
1230 fErrors.error(parentOffset, "type '" + fieldType->name() + "' is not permitted here");
1231 return;
1232 }
Timothy Liangdc89f192018-06-13 09:20:31 -04001233 if (fieldOffset != -1) {
1234 if (currentOffset > fieldOffset) {
1235 fErrors.error(parentOffset,
1236 "offset of field '" + field.fName + "' must be at least " +
1237 to_string((int) currentOffset));
Brian Osman8609a242020-09-08 14:01:49 -04001238 return;
Timothy Liangdc89f192018-06-13 09:20:31 -04001239 } else if (currentOffset < fieldOffset) {
1240 this->write("char pad");
1241 this->write(to_string(fPaddingCount++));
1242 this->write("[");
1243 this->write(to_string(fieldOffset - currentOffset));
1244 this->writeLine("];");
1245 currentOffset = fieldOffset;
1246 }
1247 int alignment = memoryLayout.alignment(*fieldType);
1248 if (fieldOffset % alignment) {
1249 fErrors.error(parentOffset,
1250 "offset of field '" + field.fName + "' must be a multiple of " +
1251 to_string((int) alignment));
Brian Osman8609a242020-09-08 14:01:49 -04001252 return;
Timothy Liangdc89f192018-06-13 09:20:31 -04001253 }
1254 }
Brian Osman8609a242020-09-08 14:01:49 -04001255 size_t fieldSize = memoryLayout.size(*fieldType);
1256 if (fieldSize > static_cast<size_t>(std::numeric_limits<int>::max() - currentOffset)) {
1257 fErrors.error(parentOffset, "field offset overflow");
1258 return;
1259 }
1260 currentOffset += fieldSize;
Timothy Liangdc89f192018-06-13 09:20:31 -04001261 std::vector<int> sizes;
Ethan Nicholase6592142020-09-08 10:22:09 -04001262 while (fieldType->typeKind() == Type::TypeKind::kArray) {
Timothy Liangdc89f192018-06-13 09:20:31 -04001263 sizes.push_back(fieldType->columns());
1264 fieldType = &fieldType->componentType();
1265 }
1266 this->writeModifiers(field.fModifiers, false);
1267 this->writeType(*fieldType);
1268 this->write(" ");
1269 this->writeName(field.fName);
1270 for (int s : sizes) {
Brian Osmane8c26082020-10-01 17:22:45 -04001271 if (s == Type::kUnsizedArray) {
Timothy Liangdc89f192018-06-13 09:20:31 -04001272 this->write("[]");
1273 } else {
1274 this->write("[" + to_string(s) + "]");
1275 }
1276 }
1277 this->writeLine(";");
1278 if (parentIntf) {
1279 fInterfaceBlockMap[&field] = parentIntf;
1280 }
1281 }
1282}
1283
Ethan Nicholascc305772017-10-13 16:17:45 -04001284void MetalCodeGenerator::writeVarInitializer(const Variable& var, const Expression& value) {
1285 this->writeExpression(value, kTopLevel_Precedence);
1286}
1287
Timothy Liang651286f2018-06-07 09:55:33 -04001288void MetalCodeGenerator::writeName(const String& name) {
1289 if (fReservedWords.find(name) != fReservedWords.end()) {
1290 this->write("_"); // adding underscore before name to avoid conflict with reserved words
1291 }
1292 this->write(name);
1293}
1294
Brian Osmanc0213602020-10-06 14:43:32 -04001295void MetalCodeGenerator::writeVarDeclaration(const VarDeclaration& var, bool global) {
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001296 if (global && !(var.var().modifiers().fFlags & Modifiers::kConst_Flag)) {
Brian Osmanc0213602020-10-06 14:43:32 -04001297 return;
Ethan Nicholascc305772017-10-13 16:17:45 -04001298 }
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001299 this->writeModifiers(var.var().modifiers(), global);
1300 this->writeType(var.baseType());
Brian Osmanc0213602020-10-06 14:43:32 -04001301 this->write(" ");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001302 this->writeName(var.var().name());
John Stiles2d4f9592020-10-30 10:29:12 -04001303 for (const std::unique_ptr<Expression>& size : var.sizes()) {
Brian Osmanc0213602020-10-06 14:43:32 -04001304 this->write("[");
John Stiles2d4f9592020-10-30 10:29:12 -04001305 if (size) {
1306 this->writeExpression(*size, kTopLevel_Precedence);
Brian Osmanc0213602020-10-06 14:43:32 -04001307 }
1308 this->write("]");
Ethan Nicholascc305772017-10-13 16:17:45 -04001309 }
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001310 if (var.value()) {
Brian Osmanc0213602020-10-06 14:43:32 -04001311 this->write(" = ");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001312 this->writeVarInitializer(var.var(), *var.value());
Brian Osmanc0213602020-10-06 14:43:32 -04001313 }
1314 this->write(";");
Ethan Nicholascc305772017-10-13 16:17:45 -04001315}
1316
1317void MetalCodeGenerator::writeStatement(const Statement& s) {
Ethan Nicholase6592142020-09-08 10:22:09 -04001318 switch (s.kind()) {
1319 case Statement::Kind::kBlock:
John Stiles26f98502020-08-18 09:30:51 -04001320 this->writeBlock(s.as<Block>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001321 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001322 case Statement::Kind::kExpression:
Ethan Nicholasd503a5a2020-09-30 09:29:55 -04001323 this->writeExpression(*s.as<ExpressionStatement>().expression(), kTopLevel_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001324 this->write(";");
1325 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001326 case Statement::Kind::kReturn:
John Stiles26f98502020-08-18 09:30:51 -04001327 this->writeReturnStatement(s.as<ReturnStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001328 break;
Brian Osmanc0213602020-10-06 14:43:32 -04001329 case Statement::Kind::kVarDeclaration:
1330 this->writeVarDeclaration(s.as<VarDeclaration>(), false);
Ethan Nicholascc305772017-10-13 16:17:45 -04001331 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001332 case Statement::Kind::kIf:
John Stiles26f98502020-08-18 09:30:51 -04001333 this->writeIfStatement(s.as<IfStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001334 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001335 case Statement::Kind::kFor:
John Stiles26f98502020-08-18 09:30:51 -04001336 this->writeForStatement(s.as<ForStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001337 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001338 case Statement::Kind::kWhile:
John Stiles26f98502020-08-18 09:30:51 -04001339 this->writeWhileStatement(s.as<WhileStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001340 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001341 case Statement::Kind::kDo:
John Stiles26f98502020-08-18 09:30:51 -04001342 this->writeDoStatement(s.as<DoStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001343 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001344 case Statement::Kind::kSwitch:
John Stiles26f98502020-08-18 09:30:51 -04001345 this->writeSwitchStatement(s.as<SwitchStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001346 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001347 case Statement::Kind::kBreak:
Ethan Nicholascc305772017-10-13 16:17:45 -04001348 this->write("break;");
1349 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001350 case Statement::Kind::kContinue:
Ethan Nicholascc305772017-10-13 16:17:45 -04001351 this->write("continue;");
1352 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001353 case Statement::Kind::kDiscard:
Timothy Lianga06f2152018-05-24 15:33:31 -04001354 this->write("discard_fragment();");
Ethan Nicholascc305772017-10-13 16:17:45 -04001355 break;
John Stiles98c1f822020-09-09 14:18:53 -04001356 case Statement::Kind::kInlineMarker:
Ethan Nicholase6592142020-09-08 10:22:09 -04001357 case Statement::Kind::kNop:
Ethan Nicholascc305772017-10-13 16:17:45 -04001358 this->write(";");
1359 break;
1360 default:
Ethan Nicholas2a099da2020-01-02 14:40:54 -05001361#ifdef SK_DEBUG
Ethan Nicholascc305772017-10-13 16:17:45 -04001362 ABORT("unsupported statement: %s", s.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -05001363#endif
1364 break;
Ethan Nicholascc305772017-10-13 16:17:45 -04001365 }
1366}
1367
Ethan Nicholascc305772017-10-13 16:17:45 -04001368void MetalCodeGenerator::writeBlock(const Block& b) {
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001369 bool isScope = b.isScope();
1370 if (isScope) {
Ethan Nicholas70728ef2020-05-28 07:09:00 -04001371 this->writeLine("{");
1372 fIndentation++;
1373 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001374 for (const std::unique_ptr<Statement>& stmt : b.children()) {
1375 if (!stmt->isEmpty()) {
1376 this->writeStatement(*stmt);
1377 this->writeLine();
1378 }
1379 }
1380 if (isScope) {
Ethan Nicholas70728ef2020-05-28 07:09:00 -04001381 fIndentation--;
1382 this->write("}");
1383 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001384}
1385
1386void MetalCodeGenerator::writeIfStatement(const IfStatement& stmt) {
1387 this->write("if (");
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04001388 this->writeExpression(*stmt.test(), kTopLevel_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001389 this->write(") ");
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04001390 this->writeStatement(*stmt.ifTrue());
1391 if (stmt.ifFalse()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001392 this->write(" else ");
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04001393 this->writeStatement(*stmt.ifFalse());
Ethan Nicholascc305772017-10-13 16:17:45 -04001394 }
1395}
1396
1397void MetalCodeGenerator::writeForStatement(const ForStatement& f) {
1398 this->write("for (");
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04001399 if (f.initializer() && !f.initializer()->isEmpty()) {
1400 this->writeStatement(*f.initializer());
Ethan Nicholascc305772017-10-13 16:17:45 -04001401 } else {
1402 this->write("; ");
1403 }
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04001404 if (f.test()) {
1405 this->writeExpression(*f.test(), kTopLevel_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001406 }
1407 this->write("; ");
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04001408 if (f.next()) {
1409 this->writeExpression(*f.next(), kTopLevel_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001410 }
1411 this->write(") ");
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04001412 this->writeStatement(*f.statement());
Ethan Nicholascc305772017-10-13 16:17:45 -04001413}
1414
1415void MetalCodeGenerator::writeWhileStatement(const WhileStatement& w) {
1416 this->write("while (");
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04001417 this->writeExpression(*w.test(), kTopLevel_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001418 this->write(") ");
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04001419 this->writeStatement(*w.statement());
Ethan Nicholascc305772017-10-13 16:17:45 -04001420}
1421
1422void MetalCodeGenerator::writeDoStatement(const DoStatement& d) {
1423 this->write("do ");
Ethan Nicholas1fd61162020-09-28 13:14:19 -04001424 this->writeStatement(*d.statement());
Ethan Nicholascc305772017-10-13 16:17:45 -04001425 this->write(" while (");
Ethan Nicholas1fd61162020-09-28 13:14:19 -04001426 this->writeExpression(*d.test(), kTopLevel_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001427 this->write(");");
1428}
1429
1430void MetalCodeGenerator::writeSwitchStatement(const SwitchStatement& s) {
1431 this->write("switch (");
Ethan Nicholas01b05e52020-10-22 15:53:41 -04001432 this->writeExpression(*s.value(), kTopLevel_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001433 this->writeLine(") {");
1434 fIndentation++;
John Stiles2d4f9592020-10-30 10:29:12 -04001435 for (const std::unique_ptr<SwitchCase>& c : s.cases()) {
1436 if (c->value()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001437 this->write("case ");
John Stiles2d4f9592020-10-30 10:29:12 -04001438 this->writeExpression(*c->value(), kTopLevel_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001439 this->writeLine(":");
1440 } else {
1441 this->writeLine("default:");
1442 }
1443 fIndentation++;
John Stiles2d4f9592020-10-30 10:29:12 -04001444 for (const auto& stmt : c->statements()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001445 this->writeStatement(*stmt);
1446 this->writeLine();
1447 }
1448 fIndentation--;
1449 }
1450 fIndentation--;
1451 this->write("}");
1452}
1453
1454void MetalCodeGenerator::writeReturnStatement(const ReturnStatement& r) {
1455 this->write("return");
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04001456 if (r.expression()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001457 this->write(" ");
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04001458 this->writeExpression(*r.expression(), kTopLevel_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001459 }
1460 this->write(";");
1461}
1462
1463void MetalCodeGenerator::writeHeader() {
1464 this->write("#include <metal_stdlib>\n");
1465 this->write("#include <simd/simd.h>\n");
1466 this->write("using namespace metal;\n");
1467}
1468
1469void MetalCodeGenerator::writeUniformStruct() {
Brian Osman133724c2020-10-28 14:14:39 -04001470 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04001471 if (e->is<GlobalVarDeclaration>()) {
1472 const GlobalVarDeclaration& decls = e->as<GlobalVarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001473 const Variable& var = decls.declaration()->as<VarDeclaration>().var();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001474 if (var.modifiers().fFlags & Modifiers::kUniform_Flag &&
Brian Osmanc0213602020-10-06 14:43:32 -04001475 var.type().typeKind() != Type::TypeKind::kSampler) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001476 if (-1 == fUniformBuffer) {
1477 this->write("struct Uniforms {\n");
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001478 fUniformBuffer = var.modifiers().fLayout.fSet;
Ethan Nicholascc305772017-10-13 16:17:45 -04001479 if (-1 == fUniformBuffer) {
1480 fErrors.error(decls.fOffset, "Metal uniforms must have 'layout(set=...)'");
1481 }
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001482 } else if (var.modifiers().fLayout.fSet != fUniformBuffer) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001483 if (-1 == fUniformBuffer) {
1484 fErrors.error(decls.fOffset, "Metal backend requires all uniforms to have "
1485 "the same 'layout(set=...)'");
1486 }
1487 }
1488 this->write(" ");
Brian Osmanc0213602020-10-06 14:43:32 -04001489 this->writeType(var.type());
Ethan Nicholascc305772017-10-13 16:17:45 -04001490 this->write(" ");
Brian Osmanc0213602020-10-06 14:43:32 -04001491 this->writeName(var.name());
Ethan Nicholascc305772017-10-13 16:17:45 -04001492 this->write(";\n");
1493 }
1494 }
1495 }
1496 if (-1 != fUniformBuffer) {
1497 this->write("};\n");
1498 }
1499}
1500
1501void MetalCodeGenerator::writeInputStruct() {
1502 this->write("struct Inputs {\n");
Brian Osman133724c2020-10-28 14:14:39 -04001503 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04001504 if (e->is<GlobalVarDeclaration>()) {
1505 const GlobalVarDeclaration& decls = e->as<GlobalVarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001506 const Variable& var = decls.declaration()->as<VarDeclaration>().var();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001507 if (var.modifiers().fFlags & Modifiers::kIn_Flag &&
1508 -1 == var.modifiers().fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001509 this->write(" ");
Brian Osmanc0213602020-10-06 14:43:32 -04001510 this->writeType(var.type());
Ethan Nicholascc305772017-10-13 16:17:45 -04001511 this->write(" ");
Brian Osmanc0213602020-10-06 14:43:32 -04001512 this->writeName(var.name());
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001513 if (-1 != var.modifiers().fLayout.fLocation) {
Brian Osmanc0213602020-10-06 14:43:32 -04001514 if (fProgram.fKind == Program::kVertex_Kind) {
1515 this->write(" [[attribute(" +
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001516 to_string(var.modifiers().fLayout.fLocation) + ")]]");
Brian Osmanc0213602020-10-06 14:43:32 -04001517 } else if (fProgram.fKind == Program::kFragment_Kind) {
1518 this->write(" [[user(locn" +
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001519 to_string(var.modifiers().fLayout.fLocation) + ")]]");
Ethan Nicholascc305772017-10-13 16:17:45 -04001520 }
1521 }
1522 this->write(";\n");
1523 }
1524 }
1525 }
1526 this->write("};\n");
1527}
1528
1529void MetalCodeGenerator::writeOutputStruct() {
1530 this->write("struct Outputs {\n");
Timothy Liang7d637782018-06-05 09:58:07 -04001531 if (fProgram.fKind == Program::kVertex_Kind) {
Timothy Liangb8eeb802018-07-23 16:46:16 -04001532 this->write(" float4 sk_Position [[position]];\n");
Timothy Liang7d637782018-06-05 09:58:07 -04001533 } else if (fProgram.fKind == Program::kFragment_Kind) {
Timothy Liangde0be802018-08-10 13:48:08 -04001534 this->write(" float4 sk_FragColor [[color(0)]];\n");
Timothy Liang7d637782018-06-05 09:58:07 -04001535 }
Brian Osman133724c2020-10-28 14:14:39 -04001536 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04001537 if (e->is<GlobalVarDeclaration>()) {
1538 const GlobalVarDeclaration& decls = e->as<GlobalVarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001539 const Variable& var = decls.declaration()->as<VarDeclaration>().var();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001540 if (var.modifiers().fFlags & Modifiers::kOut_Flag &&
1541 -1 == var.modifiers().fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001542 this->write(" ");
Brian Osmanc0213602020-10-06 14:43:32 -04001543 this->writeType(var.type());
Ethan Nicholascc305772017-10-13 16:17:45 -04001544 this->write(" ");
Brian Osmanc0213602020-10-06 14:43:32 -04001545 this->writeName(var.name());
1546 if (fProgram.fKind == Program::kVertex_Kind) {
1547 this->write(" [[user(locn" +
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001548 to_string(var.modifiers().fLayout.fLocation) + ")]]");
Brian Osmanc0213602020-10-06 14:43:32 -04001549 } else if (fProgram.fKind == Program::kFragment_Kind) {
1550 this->write(" [[color(" +
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001551 to_string(var.modifiers().fLayout.fLocation) +")");
1552 int colorIndex = var.modifiers().fLayout.fIndex;
Brian Osmanc0213602020-10-06 14:43:32 -04001553 if (colorIndex) {
1554 this->write(", index(" + to_string(colorIndex) + ")");
Timothy Liang7d637782018-06-05 09:58:07 -04001555 }
Brian Osmanc0213602020-10-06 14:43:32 -04001556 this->write("]]");
Ethan Nicholascc305772017-10-13 16:17:45 -04001557 }
1558 this->write(";\n");
1559 }
1560 }
Timothy Liang7d637782018-06-05 09:58:07 -04001561 }
1562 if (fProgram.fKind == Program::kVertex_Kind) {
Jim Van Verth3913d3e2020-08-31 15:16:57 -04001563 this->write(" float sk_PointSize [[point_size]];\n");
Timothy Liang7d637782018-06-05 09:58:07 -04001564 }
1565 this->write("};\n");
1566}
1567
1568void MetalCodeGenerator::writeInterfaceBlocks() {
1569 bool wroteInterfaceBlock = false;
Brian Osman133724c2020-10-28 14:14:39 -04001570 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04001571 if (e->is<InterfaceBlock>()) {
1572 this->writeInterfaceBlock(e->as<InterfaceBlock>());
Timothy Liang7d637782018-06-05 09:58:07 -04001573 wroteInterfaceBlock = true;
1574 }
1575 }
Jim Van Verth3d482992019-02-07 10:48:05 -05001576 if (!wroteInterfaceBlock && fProgram.fInputs.fRTHeight) {
Timothy Liang7d637782018-06-05 09:58:07 -04001577 this->writeLine("struct sksl_synthetic_uniforms {");
1578 this->writeLine(" float u_skRTHeight;");
1579 this->writeLine("};");
1580 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001581}
1582
John Stilescdcdb042020-07-06 09:03:51 -04001583void MetalCodeGenerator::visitGlobalStruct(GlobalStructVisitor* visitor) {
1584 // Visit the interface blocks.
1585 for (const auto& [interfaceType, interfaceName] : fInterfaceBlockNameMap) {
1586 visitor->VisitInterfaceBlock(*interfaceType, interfaceName);
1587 }
Brian Osman133724c2020-10-28 14:14:39 -04001588 for (const ProgramElement* element : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04001589 if (!element->is<GlobalVarDeclaration>()) {
John Stilescdcdb042020-07-06 09:03:51 -04001590 continue;
Timothy Liang7d637782018-06-05 09:58:07 -04001591 }
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001592 const GlobalVarDeclaration& global = element->as<GlobalVarDeclaration>();
1593 const VarDeclaration& decl = global.declaration()->as<VarDeclaration>();
1594 const Variable& var = decl.var();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001595 if ((!var.modifiers().fFlags && -1 == var.modifiers().fLayout.fBuiltin) ||
Brian Osmanc0213602020-10-06 14:43:32 -04001596 var.type().typeKind() == Type::TypeKind::kSampler) {
1597 if (var.type().typeKind() == Type::TypeKind::kSampler) {
1598 // Samplers are represented as a "texture/sampler" duo in the global struct.
1599 visitor->VisitTexture(var.type(), var.name());
1600 visitor->VisitSampler(var.type(), String(var.name()) + SAMPLER_SUFFIX);
1601 } else {
1602 // Visit a regular variable.
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001603 visitor->VisitVariable(var, decl.value().get());
Timothy Liangee84fe12018-05-18 14:38:19 -04001604 }
1605 }
1606 }
John Stilescdcdb042020-07-06 09:03:51 -04001607}
1608
1609void MetalCodeGenerator::writeGlobalStruct() {
1610 class : public GlobalStructVisitor {
1611 public:
1612 void VisitInterfaceBlock(const InterfaceBlock& block, const String& blockName) override {
1613 this->AddElement();
1614 fCodeGen->write(" constant ");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001615 fCodeGen->write(block.typeName());
John Stilescdcdb042020-07-06 09:03:51 -04001616 fCodeGen->write("* ");
1617 fCodeGen->writeName(blockName);
1618 fCodeGen->write(";\n");
1619 }
1620 void VisitTexture(const Type& type, const String& name) override {
1621 this->AddElement();
1622 fCodeGen->write(" ");
1623 fCodeGen->writeType(type);
1624 fCodeGen->write(" ");
1625 fCodeGen->writeName(name);
1626 fCodeGen->write(";\n");
1627 }
1628 void VisitSampler(const Type&, const String& name) override {
1629 this->AddElement();
1630 fCodeGen->write(" sampler ");
1631 fCodeGen->writeName(name);
1632 fCodeGen->write(";\n");
1633 }
1634 void VisitVariable(const Variable& var, const Expression* value) override {
1635 this->AddElement();
1636 fCodeGen->write(" ");
Ethan Nicholas30d30222020-09-11 12:27:26 -04001637 fCodeGen->writeType(var.type());
John Stilescdcdb042020-07-06 09:03:51 -04001638 fCodeGen->write(" ");
Ethan Nicholase2c49992020-10-05 11:49:11 -04001639 fCodeGen->writeName(var.name());
John Stilescdcdb042020-07-06 09:03:51 -04001640 fCodeGen->write(";\n");
1641 }
1642 void AddElement() {
1643 if (fFirst) {
1644 fCodeGen->write("struct Globals {\n");
1645 fFirst = false;
1646 }
1647 }
1648 void Finish() {
1649 if (!fFirst) {
1650 fCodeGen->write("};");
1651 fFirst = true;
1652 }
1653 }
1654
1655 MetalCodeGenerator* fCodeGen = nullptr;
1656 bool fFirst = true;
1657 } visitor;
1658
1659 visitor.fCodeGen = this;
1660 this->visitGlobalStruct(&visitor);
1661 visitor.Finish();
1662}
1663
1664void MetalCodeGenerator::writeGlobalInit() {
1665 class : public GlobalStructVisitor {
1666 public:
1667 void VisitInterfaceBlock(const InterfaceBlock& blockType,
1668 const String& blockName) override {
1669 this->AddElement();
1670 fCodeGen->write("&");
1671 fCodeGen->writeName(blockName);
1672 }
1673 void VisitTexture(const Type&, const String& name) override {
1674 this->AddElement();
1675 fCodeGen->writeName(name);
1676 }
1677 void VisitSampler(const Type&, const String& name) override {
1678 this->AddElement();
1679 fCodeGen->writeName(name);
1680 }
1681 void VisitVariable(const Variable& var, const Expression* value) override {
1682 this->AddElement();
1683 if (value) {
1684 fCodeGen->writeVarInitializer(var, *value);
1685 } else {
1686 fCodeGen->write("{}");
1687 }
1688 }
1689 void AddElement() {
1690 if (fFirst) {
1691 fCodeGen->write(" Globals globalStruct{");
1692 fFirst = false;
1693 } else {
1694 fCodeGen->write(", ");
1695 }
1696 }
1697 void Finish() {
1698 if (!fFirst) {
1699 fCodeGen->writeLine("};");
1700 fCodeGen->writeLine(" thread Globals* _globals = &globalStruct;");
1701 fCodeGen->writeLine(" (void)_globals;");
1702 }
1703 }
1704 MetalCodeGenerator* fCodeGen = nullptr;
1705 bool fFirst = true;
1706 } visitor;
1707
1708 visitor.fCodeGen = this;
1709 this->visitGlobalStruct(&visitor);
1710 visitor.Finish();
Timothy Liangee84fe12018-05-18 14:38:19 -04001711}
1712
Ethan Nicholascc305772017-10-13 16:17:45 -04001713void MetalCodeGenerator::writeProgramElement(const ProgramElement& e) {
Ethan Nicholase6592142020-09-08 10:22:09 -04001714 switch (e.kind()) {
1715 case ProgramElement::Kind::kExtension:
Ethan Nicholascc305772017-10-13 16:17:45 -04001716 break;
Brian Osmanc0213602020-10-06 14:43:32 -04001717 case ProgramElement::Kind::kGlobalVar: {
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001718 const GlobalVarDeclaration& global = e.as<GlobalVarDeclaration>();
1719 const VarDeclaration& decl = global.declaration()->as<VarDeclaration>();
1720 int builtin = decl.var().modifiers().fLayout.fBuiltin;
Brian Osmanc0213602020-10-06 14:43:32 -04001721 if (-1 == builtin) {
1722 // normal var
1723 this->writeVarDeclaration(decl, true);
1724 this->writeLine();
1725 } else if (SK_FRAGCOLOR_BUILTIN == builtin) {
1726 // ignore
Ethan Nicholascc305772017-10-13 16:17:45 -04001727 }
1728 break;
1729 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001730 case ProgramElement::Kind::kInterfaceBlock:
Timothy Liang7d637782018-06-05 09:58:07 -04001731 // handled in writeInterfaceBlocks, do nothing
Ethan Nicholascc305772017-10-13 16:17:45 -04001732 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001733 case ProgramElement::Kind::kFunction:
John Stiles3dc0da62020-08-19 17:48:31 -04001734 this->writeFunction(e.as<FunctionDefinition>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001735 break;
John Stiles569249b2020-11-03 12:18:22 -05001736 case ProgramElement::Kind::kFunctionPrototype:
1737 this->writeFunctionPrototype(e.as<FunctionPrototype>());
1738 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001739 case ProgramElement::Kind::kModifiers:
Ethan Nicholas077050b2020-10-13 10:30:20 -04001740 this->writeModifiers(e.as<ModifiersDeclaration>().modifiers(), true);
Ethan Nicholascc305772017-10-13 16:17:45 -04001741 this->writeLine(";");
1742 break;
1743 default:
Ethan Nicholas2a099da2020-01-02 14:40:54 -05001744#ifdef SK_DEBUG
1745 ABORT("unsupported program element: %s\n", e.description().c_str());
1746#endif
1747 break;
Ethan Nicholascc305772017-10-13 16:17:45 -04001748 }
1749}
1750
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001751MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const Expression* e) {
1752 if (!e) {
1753 return kNo_Requirements;
1754 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001755 switch (e->kind()) {
1756 case Expression::Kind::kFunctionCall: {
John Stiles3dc0da62020-08-19 17:48:31 -04001757 const FunctionCall& f = e->as<FunctionCall>();
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001758 Requirements result = this->requirements(f.function());
1759 for (const auto& arg : f.arguments()) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001760 result |= this->requirements(arg.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001761 }
1762 return result;
1763 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001764 case Expression::Kind::kConstructor: {
John Stiles3dc0da62020-08-19 17:48:31 -04001765 const Constructor& c = e->as<Constructor>();
Ethan Nicholascc305772017-10-13 16:17:45 -04001766 Requirements result = kNo_Requirements;
Ethan Nicholasf70f0442020-09-29 12:41:35 -04001767 for (const auto& arg : c.arguments()) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001768 result |= this->requirements(arg.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001769 }
1770 return result;
1771 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001772 case Expression::Kind::kFieldAccess: {
John Stiles3dc0da62020-08-19 17:48:31 -04001773 const FieldAccess& f = e->as<FieldAccess>();
Ethan Nicholas7a95b202020-10-09 11:55:40 -04001774 if (FieldAccess::OwnerKind::kAnonymousInterfaceBlock == f.ownerKind()) {
Timothy Liang7d637782018-06-05 09:58:07 -04001775 return kGlobals_Requirement;
1776 }
Ethan Nicholas7a95b202020-10-09 11:55:40 -04001777 return this->requirements(f.base().get());
Timothy Liang7d637782018-06-05 09:58:07 -04001778 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001779 case Expression::Kind::kSwizzle:
Ethan Nicholas6b4d5812020-10-12 16:11:51 -04001780 return this->requirements(e->as<Swizzle>().base().get());
Ethan Nicholase6592142020-09-08 10:22:09 -04001781 case Expression::Kind::kBinary: {
1782 const BinaryExpression& bin = e->as<BinaryExpression>();
John Stiles2d4f9592020-10-30 10:29:12 -04001783 return this->requirements(bin.left().get()) |
1784 this->requirements(bin.right().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001785 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001786 case Expression::Kind::kIndex: {
John Stiles3dc0da62020-08-19 17:48:31 -04001787 const IndexExpression& idx = e->as<IndexExpression>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04001788 return this->requirements(idx.base().get()) | this->requirements(idx.index().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001789 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001790 case Expression::Kind::kPrefix:
Ethan Nicholas444ccc62020-10-09 10:16:22 -04001791 return this->requirements(e->as<PrefixExpression>().operand().get());
Ethan Nicholase6592142020-09-08 10:22:09 -04001792 case Expression::Kind::kPostfix:
Ethan Nicholas444ccc62020-10-09 10:16:22 -04001793 return this->requirements(e->as<PostfixExpression>().operand().get());
Ethan Nicholase6592142020-09-08 10:22:09 -04001794 case Expression::Kind::kTernary: {
John Stiles3dc0da62020-08-19 17:48:31 -04001795 const TernaryExpression& t = e->as<TernaryExpression>();
Ethan Nicholasdd218162020-10-08 05:48:01 -04001796 return this->requirements(t.test().get()) | this->requirements(t.ifTrue().get()) |
1797 this->requirements(t.ifFalse().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001798 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001799 case Expression::Kind::kVariableReference: {
John Stiles3dc0da62020-08-19 17:48:31 -04001800 const VariableReference& v = e->as<VariableReference>();
Ethan Nicholas78686922020-10-08 06:46:27 -04001801 const Modifiers& modifiers = v.variable()->modifiers();
Ethan Nicholascc305772017-10-13 16:17:45 -04001802 Requirements result = kNo_Requirements;
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001803 if (modifiers.fLayout.fBuiltin == SK_FRAGCOORD_BUILTIN) {
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -04001804 result = kGlobals_Requirement | kFragCoord_Requirement;
Ethan Nicholas453f67f2020-10-09 10:43:45 -04001805 } else if (Variable::Storage::kGlobal == v.variable()->storage()) {
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001806 if (modifiers.fFlags & Modifiers::kIn_Flag) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001807 result = kInputs_Requirement;
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001808 } else if (modifiers.fFlags & Modifiers::kOut_Flag) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001809 result = kOutputs_Requirement;
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001810 } else if (modifiers.fFlags & Modifiers::kUniform_Flag &&
Ethan Nicholas78686922020-10-08 06:46:27 -04001811 v.variable()->type().typeKind() != Type::TypeKind::kSampler) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001812 result = kUniforms_Requirement;
Timothy Liangee84fe12018-05-18 14:38:19 -04001813 } else {
1814 result = kGlobals_Requirement;
Ethan Nicholascc305772017-10-13 16:17:45 -04001815 }
1816 }
1817 return result;
1818 }
1819 default:
1820 return kNo_Requirements;
1821 }
1822}
1823
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001824MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const Statement* s) {
1825 if (!s) {
1826 return kNo_Requirements;
1827 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001828 switch (s->kind()) {
1829 case Statement::Kind::kBlock: {
Ethan Nicholascc305772017-10-13 16:17:45 -04001830 Requirements result = kNo_Requirements;
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001831 for (const std::unique_ptr<Statement>& child : s->as<Block>().children()) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001832 result |= this->requirements(child.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001833 }
1834 return result;
1835 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001836 case Statement::Kind::kVarDeclaration: {
John Stiles3dc0da62020-08-19 17:48:31 -04001837 const VarDeclaration& var = s->as<VarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001838 return this->requirements(var.value().get());
Timothy Liang7d637782018-06-05 09:58:07 -04001839 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001840 case Statement::Kind::kExpression:
Ethan Nicholasd503a5a2020-09-30 09:29:55 -04001841 return this->requirements(s->as<ExpressionStatement>().expression().get());
Ethan Nicholase6592142020-09-08 10:22:09 -04001842 case Statement::Kind::kReturn: {
John Stiles3dc0da62020-08-19 17:48:31 -04001843 const ReturnStatement& r = s->as<ReturnStatement>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04001844 return this->requirements(r.expression().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001845 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001846 case Statement::Kind::kIf: {
John Stiles3dc0da62020-08-19 17:48:31 -04001847 const IfStatement& i = s->as<IfStatement>();
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04001848 return this->requirements(i.test().get()) |
1849 this->requirements(i.ifTrue().get()) |
1850 this->requirements(i.ifFalse().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001851 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001852 case Statement::Kind::kFor: {
John Stiles3dc0da62020-08-19 17:48:31 -04001853 const ForStatement& f = s->as<ForStatement>();
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04001854 return this->requirements(f.initializer().get()) |
1855 this->requirements(f.test().get()) |
1856 this->requirements(f.next().get()) |
1857 this->requirements(f.statement().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001858 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001859 case Statement::Kind::kWhile: {
John Stiles3dc0da62020-08-19 17:48:31 -04001860 const WhileStatement& w = s->as<WhileStatement>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04001861 return this->requirements(w.test().get()) |
1862 this->requirements(w.statement().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001863 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001864 case Statement::Kind::kDo: {
John Stiles3dc0da62020-08-19 17:48:31 -04001865 const DoStatement& d = s->as<DoStatement>();
Ethan Nicholas1fd61162020-09-28 13:14:19 -04001866 return this->requirements(d.test().get()) |
1867 this->requirements(d.statement().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001868 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001869 case Statement::Kind::kSwitch: {
John Stiles3dc0da62020-08-19 17:48:31 -04001870 const SwitchStatement& sw = s->as<SwitchStatement>();
Ethan Nicholas01b05e52020-10-22 15:53:41 -04001871 Requirements result = this->requirements(sw.value().get());
John Stiles2d4f9592020-10-30 10:29:12 -04001872 for (const std::unique_ptr<SwitchCase>& sc : sw.cases()) {
1873 for (const auto& st : sc->statements()) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001874 result |= this->requirements(st.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001875 }
1876 }
1877 return result;
1878 }
1879 default:
1880 return kNo_Requirements;
1881 }
1882}
1883
1884MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const FunctionDeclaration& f) {
Ethan Nicholased84b732020-10-08 11:45:44 -04001885 if (f.isBuiltin()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001886 return kNo_Requirements;
1887 }
1888 auto found = fRequirements.find(&f);
1889 if (found == fRequirements.end()) {
Ethan Nicholas65a8f562019-04-19 14:00:26 -04001890 fRequirements[&f] = kNo_Requirements;
Brian Osman133724c2020-10-28 14:14:39 -04001891 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04001892 if (e->is<FunctionDefinition>()) {
1893 const FunctionDefinition& def = e->as<FunctionDefinition>();
Ethan Nicholas0a5d0962020-10-14 13:33:18 -04001894 if (&def.declaration() == &f) {
1895 Requirements reqs = this->requirements(def.body().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001896 fRequirements[&f] = reqs;
1897 return reqs;
1898 }
1899 }
1900 }
John Stiles569249b2020-11-03 12:18:22 -05001901 // We never found a definition for this declared function, but it's legal to prototype a
1902 // function without ever giving a definition, as long as you don't call it.
1903 return kNo_Requirements;
Ethan Nicholascc305772017-10-13 16:17:45 -04001904 }
1905 return found->second;
1906}
1907
Timothy Liangb8eeb802018-07-23 16:46:16 -04001908bool MetalCodeGenerator::generateCode() {
Ethan Nicholascc305772017-10-13 16:17:45 -04001909 OutputStream* rawOut = fOut;
1910 fOut = &fHeader;
1911 fProgramKind = fProgram.fKind;
1912 this->writeHeader();
1913 this->writeUniformStruct();
1914 this->writeInputStruct();
Timothy Liang7d637782018-06-05 09:58:07 -04001915 this->writeOutputStruct();
1916 this->writeInterfaceBlocks();
Timothy Liangee84fe12018-05-18 14:38:19 -04001917 this->writeGlobalStruct();
Ethan Nicholascc305772017-10-13 16:17:45 -04001918 StringStream body;
1919 fOut = &body;
Brian Osman133724c2020-10-28 14:14:39 -04001920 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04001921 this->writeProgramElement(*e);
Ethan Nicholascc305772017-10-13 16:17:45 -04001922 }
1923 fOut = rawOut;
1924
1925 write_stringstream(fHeader, *rawOut);
Chris Daltondba7aab2018-11-15 10:57:49 -05001926 write_stringstream(fExtraFunctions, *rawOut);
Ethan Nicholascc305772017-10-13 16:17:45 -04001927 write_stringstream(body, *rawOut);
Brian Osman8609a242020-09-08 14:01:49 -04001928 return 0 == fErrors.errorCount();
Ethan Nicholascc305772017-10-13 16:17:45 -04001929}
1930
John Stilesa6841be2020-08-06 14:11:56 -04001931} // namespace SkSL