blob: b090962cde47f625886ada92397c149e4fd7df22 [file] [log] [blame]
Ethan Nicholascc305772017-10-13 16:17:45 -04001/*
2 * Copyright 2016 Google Inc.
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
7
Mike Kleinc0bd9f92019-04-23 12:05:21 -05008#include "src/sksl/SkSLMetalCodeGenerator.h"
Ethan Nicholascc305772017-10-13 16:17:45 -04009
Mike Kleinc0bd9f92019-04-23 12:05:21 -050010#include "src/sksl/SkSLCompiler.h"
11#include "src/sksl/ir/SkSLExpressionStatement.h"
12#include "src/sksl/ir/SkSLExtension.h"
13#include "src/sksl/ir/SkSLIndexExpression.h"
14#include "src/sksl/ir/SkSLModifiersDeclaration.h"
15#include "src/sksl/ir/SkSLNop.h"
16#include "src/sksl/ir/SkSLVariableReference.h"
Ethan Nicholascc305772017-10-13 16:17:45 -040017
18namespace SkSL {
19
John Stilescdcdb042020-07-06 09:03:51 -040020class MetalCodeGenerator::GlobalStructVisitor {
21public:
22 virtual ~GlobalStructVisitor() = default;
23 virtual void VisitInterfaceBlock(const InterfaceBlock& block, const String& blockName) = 0;
24 virtual void VisitTexture(const Type& type, const String& name) = 0;
25 virtual void VisitSampler(const Type& type, const String& name) = 0;
26 virtual void VisitVariable(const Variable& var, const Expression* value) = 0;
27};
28
Timothy Liangee84fe12018-05-18 14:38:19 -040029void MetalCodeGenerator::setupIntrinsics() {
Timothy Liang7d637782018-06-05 09:58:07 -040030#define METAL(x) std::make_pair(kMetal_IntrinsicKind, k ## x ## _MetalIntrinsic)
31#define SPECIAL(x) std::make_pair(kSpecial_IntrinsicKind, k ## x ## _SpecialIntrinsic)
Ethan Nicholas13863662019-07-29 13:05:15 -040032 fIntrinsicMap[String("sample")] = SPECIAL(Texture);
Timothy Liang651286f2018-06-07 09:55:33 -040033 fIntrinsicMap[String("mod")] = SPECIAL(Mod);
Ethan Nicholas0dc80872019-02-08 15:46:24 -050034 fIntrinsicMap[String("equal")] = METAL(Equal);
35 fIntrinsicMap[String("notEqual")] = METAL(NotEqual);
Timothy Lianga06f2152018-05-24 15:33:31 -040036 fIntrinsicMap[String("lessThan")] = METAL(LessThan);
37 fIntrinsicMap[String("lessThanEqual")] = METAL(LessThanEqual);
38 fIntrinsicMap[String("greaterThan")] = METAL(GreaterThan);
39 fIntrinsicMap[String("greaterThanEqual")] = METAL(GreaterThanEqual);
Timothy Liangee84fe12018-05-18 14:38:19 -040040}
41
Ethan Nicholascc305772017-10-13 16:17:45 -040042void MetalCodeGenerator::write(const char* s) {
43 if (!s[0]) {
44 return;
45 }
46 if (fAtLineStart) {
47 for (int i = 0; i < fIndentation; i++) {
48 fOut->writeText(" ");
49 }
50 }
51 fOut->writeText(s);
52 fAtLineStart = false;
53}
54
55void MetalCodeGenerator::writeLine(const char* s) {
56 this->write(s);
57 fOut->writeText(fLineEnding);
58 fAtLineStart = true;
59}
60
61void MetalCodeGenerator::write(const String& s) {
62 this->write(s.c_str());
63}
64
65void MetalCodeGenerator::writeLine(const String& s) {
66 this->writeLine(s.c_str());
67}
68
69void MetalCodeGenerator::writeLine() {
70 this->writeLine("");
71}
72
73void MetalCodeGenerator::writeExtension(const Extension& ext) {
74 this->writeLine("#extension " + ext.fName + " : enable");
75}
76
Ethan Nicholas45fa8102020-01-13 10:58:49 -050077String MetalCodeGenerator::typeName(const Type& type) {
Ethan Nicholascc305772017-10-13 16:17:45 -040078 switch (type.kind()) {
Ethan Nicholascc305772017-10-13 16:17:45 -040079 case Type::kVector_Kind:
Ethan Nicholas45fa8102020-01-13 10:58:49 -050080 return this->typeName(type.componentType()) + to_string(type.columns());
Timothy Liang43d225f2018-07-19 15:27:13 -040081 case Type::kMatrix_Kind:
Ethan Nicholas45fa8102020-01-13 10:58:49 -050082 return this->typeName(type.componentType()) + to_string(type.columns()) + "x" +
83 to_string(type.rows());
Timothy Liangee84fe12018-05-18 14:38:19 -040084 case Type::kSampler_Kind:
Ethan Nicholas45fa8102020-01-13 10:58:49 -050085 return "texture2d<float>"; // FIXME - support other texture types;
Ethan Nicholascc305772017-10-13 16:17:45 -040086 default:
Timothy Liang43d225f2018-07-19 15:27:13 -040087 if (type == *fContext.fHalf_Type) {
88 // FIXME - Currently only supporting floats in MSL to avoid type coercion issues.
Ethan Nicholas45fa8102020-01-13 10:58:49 -050089 return fContext.fFloat_Type->name();
Timothy Liang43d225f2018-07-19 15:27:13 -040090 } else if (type == *fContext.fByte_Type) {
Ethan Nicholas45fa8102020-01-13 10:58:49 -050091 return "char";
Timothy Liang43d225f2018-07-19 15:27:13 -040092 } else if (type == *fContext.fUByte_Type) {
Ethan Nicholas45fa8102020-01-13 10:58:49 -050093 return "uchar";
Timothy Liang7d637782018-06-05 09:58:07 -040094 } else {
Ethan Nicholas45fa8102020-01-13 10:58:49 -050095 return type.name();
Timothy Liang7d637782018-06-05 09:58:07 -040096 }
Ethan Nicholascc305772017-10-13 16:17:45 -040097 }
98}
99
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500100void MetalCodeGenerator::writeType(const Type& type) {
101 if (type.kind() == Type::kStruct_Kind) {
102 for (const Type* search : fWrittenStructs) {
103 if (*search == type) {
104 // already written
105 this->write(type.name());
106 return;
107 }
108 }
109 fWrittenStructs.push_back(&type);
110 this->writeLine("struct " + type.name() + " {");
111 fIndentation++;
112 this->writeFields(type.fields(), type.fOffset);
113 fIndentation--;
114 this->write("}");
115 } else {
116 this->write(this->typeName(type));
117 }
118}
119
Ethan Nicholascc305772017-10-13 16:17:45 -0400120void MetalCodeGenerator::writeExpression(const Expression& expr, Precedence parentPrecedence) {
121 switch (expr.fKind) {
122 case Expression::kBinary_Kind:
123 this->writeBinaryExpression((BinaryExpression&) expr, parentPrecedence);
124 break;
125 case Expression::kBoolLiteral_Kind:
126 this->writeBoolLiteral((BoolLiteral&) expr);
127 break;
128 case Expression::kConstructor_Kind:
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500129 this->writeConstructor((Constructor&) expr, parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400130 break;
131 case Expression::kIntLiteral_Kind:
132 this->writeIntLiteral((IntLiteral&) expr);
133 break;
134 case Expression::kFieldAccess_Kind:
135 this->writeFieldAccess(((FieldAccess&) expr));
136 break;
137 case Expression::kFloatLiteral_Kind:
138 this->writeFloatLiteral(((FloatLiteral&) expr));
139 break;
140 case Expression::kFunctionCall_Kind:
141 this->writeFunctionCall((FunctionCall&) expr);
142 break;
143 case Expression::kPrefix_Kind:
144 this->writePrefixExpression((PrefixExpression&) expr, parentPrecedence);
145 break;
146 case Expression::kPostfix_Kind:
147 this->writePostfixExpression((PostfixExpression&) expr, parentPrecedence);
148 break;
149 case Expression::kSetting_Kind:
150 this->writeSetting((Setting&) expr);
151 break;
152 case Expression::kSwizzle_Kind:
153 this->writeSwizzle((Swizzle&) expr);
154 break;
155 case Expression::kVariableReference_Kind:
156 this->writeVariableReference((VariableReference&) expr);
157 break;
158 case Expression::kTernary_Kind:
159 this->writeTernaryExpression((TernaryExpression&) expr, parentPrecedence);
160 break;
161 case Expression::kIndex_Kind:
162 this->writeIndexExpression((IndexExpression&) expr);
163 break;
164 default:
Ethan Nicholas2a099da2020-01-02 14:40:54 -0500165#ifdef SK_DEBUG
Ethan Nicholascc305772017-10-13 16:17:45 -0400166 ABORT("unsupported expression: %s", expr.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -0500167#endif
168 break;
Ethan Nicholascc305772017-10-13 16:17:45 -0400169 }
170}
171
Timothy Liang6403b0e2018-05-17 10:40:04 -0400172void MetalCodeGenerator::writeIntrinsicCall(const FunctionCall& c) {
Timothy Liang7d637782018-06-05 09:58:07 -0400173 auto i = fIntrinsicMap.find(c.fFunction.fName);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400174 SkASSERT(i != fIntrinsicMap.end());
Timothy Liang7d637782018-06-05 09:58:07 -0400175 Intrinsic intrinsic = i->second;
176 int32_t intrinsicId = intrinsic.second;
177 switch (intrinsic.first) {
Timothy Liang6403b0e2018-05-17 10:40:04 -0400178 case kSpecial_IntrinsicKind:
179 return this->writeSpecialIntrinsic(c, (SpecialIntrinsic) intrinsicId);
Timothy Lianga06f2152018-05-24 15:33:31 -0400180 break;
181 case kMetal_IntrinsicKind:
182 this->writeExpression(*c.fArguments[0], kSequence_Precedence);
183 switch ((MetalIntrinsic) intrinsicId) {
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500184 case kEqual_MetalIntrinsic:
185 this->write(" == ");
186 break;
187 case kNotEqual_MetalIntrinsic:
188 this->write(" != ");
189 break;
Timothy Lianga06f2152018-05-24 15:33:31 -0400190 case kLessThan_MetalIntrinsic:
191 this->write(" < ");
192 break;
193 case kLessThanEqual_MetalIntrinsic:
194 this->write(" <= ");
195 break;
196 case kGreaterThan_MetalIntrinsic:
197 this->write(" > ");
198 break;
199 case kGreaterThanEqual_MetalIntrinsic:
200 this->write(" >= ");
201 break;
202 default:
203 ABORT("unsupported metal intrinsic kind");
204 }
205 this->writeExpression(*c.fArguments[1], kSequence_Precedence);
206 break;
Timothy Liang6403b0e2018-05-17 10:40:04 -0400207 default:
208 ABORT("unsupported intrinsic kind");
209 }
210}
211
Ethan Nicholascc305772017-10-13 16:17:45 -0400212void MetalCodeGenerator::writeFunctionCall(const FunctionCall& c) {
Timothy Liang6403b0e2018-05-17 10:40:04 -0400213 const auto& entry = fIntrinsicMap.find(c.fFunction.fName);
214 if (entry != fIntrinsicMap.end()) {
215 this->writeIntrinsicCall(c);
216 return;
217 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400218 if (c.fFunction.fBuiltin && "atan" == c.fFunction.fName && 2 == c.fArguments.size()) {
219 this->write("atan2");
Timothy Lianga06f2152018-05-24 15:33:31 -0400220 } else if (c.fFunction.fBuiltin && "inversesqrt" == c.fFunction.fName) {
221 this->write("rsqrt");
Chris Daltondba7aab2018-11-15 10:57:49 -0500222 } else if (c.fFunction.fBuiltin && "inverse" == c.fFunction.fName) {
223 SkASSERT(c.fArguments.size() == 1);
224 this->writeInverseHack(*c.fArguments[0]);
Timothy Liang7d637782018-06-05 09:58:07 -0400225 } else if (c.fFunction.fBuiltin && "dFdx" == c.fFunction.fName) {
226 this->write("dfdx");
227 } else if (c.fFunction.fBuiltin && "dFdy" == c.fFunction.fName) {
Chris Daltonb8af5ad2019-02-25 14:54:21 -0700228 // Flipping Y also negates the Y derivatives.
229 this->write((fProgram.fSettings.fFlipY) ? "-dfdy" : "dfdy");
Ethan Nicholascc305772017-10-13 16:17:45 -0400230 } else {
Timothy Liang651286f2018-06-07 09:55:33 -0400231 this->writeName(c.fFunction.fName);
Ethan Nicholascc305772017-10-13 16:17:45 -0400232 }
233 this->write("(");
234 const char* separator = "";
235 if (this->requirements(c.fFunction) & kInputs_Requirement) {
236 this->write("_in");
237 separator = ", ";
238 }
239 if (this->requirements(c.fFunction) & kOutputs_Requirement) {
240 this->write(separator);
241 this->write("_out");
242 separator = ", ";
243 }
244 if (this->requirements(c.fFunction) & kUniforms_Requirement) {
245 this->write(separator);
246 this->write("_uniforms");
247 separator = ", ";
248 }
Timothy Liangee84fe12018-05-18 14:38:19 -0400249 if (this->requirements(c.fFunction) & kGlobals_Requirement) {
250 this->write(separator);
251 this->write("_globals");
252 separator = ", ";
253 }
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -0400254 if (this->requirements(c.fFunction) & kFragCoord_Requirement) {
255 this->write(separator);
256 this->write("_fragCoord");
257 separator = ", ";
258 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400259 for (size_t i = 0; i < c.fArguments.size(); ++i) {
260 const Expression& arg = *c.fArguments[i];
261 this->write(separator);
262 separator = ", ";
263 if (c.fFunction.fParameters[i]->fModifiers.fFlags & Modifiers::kOut_Flag) {
264 this->write("&");
265 }
266 this->writeExpression(arg, kSequence_Precedence);
267 }
268 this->write(")");
269}
270
Chris Daltondba7aab2018-11-15 10:57:49 -0500271void MetalCodeGenerator::writeInverseHack(const Expression& mat) {
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500272 String typeName = mat.fType.name();
273 String name = typeName + "_inverse";
274 if (mat.fType == *fContext.fFloat2x2_Type || mat.fType == *fContext.fHalf2x2_Type) {
Chris Daltondba7aab2018-11-15 10:57:49 -0500275 if (fWrittenIntrinsics.find(name) == fWrittenIntrinsics.end()) {
276 fWrittenIntrinsics.insert(name);
277 fExtraFunctions.writeText((
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500278 typeName + " " + name + "(" + typeName + " m) {"
Chris Daltondba7aab2018-11-15 10:57:49 -0500279 " return float2x2(m[1][1], -m[0][1], -m[1][0], m[0][0]) * (1/determinant(m));"
280 "}"
281 ).c_str());
282 }
283 }
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500284 else if (mat.fType == *fContext.fFloat3x3_Type || mat.fType == *fContext.fHalf3x3_Type) {
285 if (fWrittenIntrinsics.find(name) == fWrittenIntrinsics.end()) {
286 fWrittenIntrinsics.insert(name);
287 fExtraFunctions.writeText((
288 typeName + " " + name + "(" + typeName + " m) {"
289 " float a00 = m[0][0], a01 = m[0][1], a02 = m[0][2];"
290 " float a10 = m[1][0], a11 = m[1][1], a12 = m[1][2];"
291 " float a20 = m[2][0], a21 = m[2][1], a22 = m[2][2];"
292 " float b01 = a22 * a11 - a12 * a21;"
293 " float b11 = -a22 * a10 + a12 * a20;"
294 " float b21 = a21 * a10 - a11 * a20;"
295 " float det = a00 * b01 + a01 * b11 + a02 * b21;"
296 " return " + typeName +
297 " (b01, (-a22 * a01 + a02 * a21), (a12 * a01 - a02 * a11),"
298 " b11, (a22 * a00 - a02 * a20), (-a12 * a00 + a02 * a10),"
299 " b21, (-a21 * a00 + a01 * a20), (a11 * a00 - a01 * a10)) * "
300 " (1/det);"
301 "}"
302 ).c_str());
303 }
304 }
305 else if (mat.fType == *fContext.fFloat4x4_Type || mat.fType == *fContext.fHalf4x4_Type) {
306 if (fWrittenIntrinsics.find(name) == fWrittenIntrinsics.end()) {
307 fWrittenIntrinsics.insert(name);
308 fExtraFunctions.writeText((
309 typeName + " " + name + "(" + typeName + " m) {"
310 " float a00 = m[0][0], a01 = m[0][1], a02 = m[0][2], a03 = m[0][3];"
311 " float a10 = m[1][0], a11 = m[1][1], a12 = m[1][2], a13 = m[1][3];"
312 " float a20 = m[2][0], a21 = m[2][1], a22 = m[2][2], a23 = m[2][3];"
313 " float a30 = m[3][0], a31 = m[3][1], a32 = m[3][2], a33 = m[3][3];"
314 " float b00 = a00 * a11 - a01 * a10;"
315 " float b01 = a00 * a12 - a02 * a10;"
316 " float b02 = a00 * a13 - a03 * a10;"
317 " float b03 = a01 * a12 - a02 * a11;"
318 " float b04 = a01 * a13 - a03 * a11;"
319 " float b05 = a02 * a13 - a03 * a12;"
320 " float b06 = a20 * a31 - a21 * a30;"
321 " float b07 = a20 * a32 - a22 * a30;"
322 " float b08 = a20 * a33 - a23 * a30;"
323 " float b09 = a21 * a32 - a22 * a31;"
324 " float b10 = a21 * a33 - a23 * a31;"
325 " float b11 = a22 * a33 - a23 * a32;"
326 " float det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - "
327 " b04 * b07 + b05 * b06;"
328 " return " + typeName + "(a11 * b11 - a12 * b10 + a13 * b09,"
329 " a02 * b10 - a01 * b11 - a03 * b09,"
330 " a31 * b05 - a32 * b04 + a33 * b03,"
331 " a22 * b04 - a21 * b05 - a23 * b03,"
332 " a12 * b08 - a10 * b11 - a13 * b07,"
333 " a00 * b11 - a02 * b08 + a03 * b07,"
334 " a32 * b02 - a30 * b05 - a33 * b01,"
335 " a20 * b05 - a22 * b02 + a23 * b01,"
336 " a10 * b10 - a11 * b08 + a13 * b06,"
337 " a01 * b08 - a00 * b10 - a03 * b06,"
338 " a30 * b04 - a31 * b02 + a33 * b00,"
339 " a21 * b02 - a20 * b04 - a23 * b00,"
340 " a11 * b07 - a10 * b09 - a12 * b06,"
341 " a00 * b09 - a01 * b07 + a02 * b06,"
342 " a31 * b01 - a30 * b03 - a32 * b00,"
343 " a20 * b03 - a21 * b01 + a22 * b00) / det;"
344 "}"
345 ).c_str());
346 }
347 }
Chris Daltondba7aab2018-11-15 10:57:49 -0500348 this->write(name);
349}
350
Timothy Liang6403b0e2018-05-17 10:40:04 -0400351void MetalCodeGenerator::writeSpecialIntrinsic(const FunctionCall & c, SpecialIntrinsic kind) {
352 switch (kind) {
353 case kTexture_SpecialIntrinsic:
Timothy Liangee84fe12018-05-18 14:38:19 -0400354 this->writeExpression(*c.fArguments[0], kSequence_Precedence);
Timothy Lianga06f2152018-05-24 15:33:31 -0400355 this->write(".sample(");
356 this->writeExpression(*c.fArguments[0], kSequence_Precedence);
357 this->write(SAMPLER_SUFFIX);
358 this->write(", ");
Timothy Liangee84fe12018-05-18 14:38:19 -0400359 if (c.fArguments[1]->fType == *fContext.fFloat3_Type) {
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500360 // have to store the vector in a temp variable to avoid double evaluating it
361 String tmpVar = "tmpCoord" + to_string(fVarCount++);
362 this->fFunctionHeader += " " + this->typeName(c.fArguments[1]->fType) + " " +
363 tmpVar + ";\n";
364 this->write("(" + tmpVar + " = ");
365 this->writeExpression(*c.fArguments[1], kSequence_Precedence);
366 this->write(", " + tmpVar + ".xy / " + tmpVar + ".z))");
Timothy Liangee84fe12018-05-18 14:38:19 -0400367 } else {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400368 SkASSERT(c.fArguments[1]->fType == *fContext.fFloat2_Type);
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500369 this->writeExpression(*c.fArguments[1], kSequence_Precedence);
Timothy Liangee84fe12018-05-18 14:38:19 -0400370 this->write(")");
371 }
Timothy Liang6403b0e2018-05-17 10:40:04 -0400372 break;
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500373 case kMod_SpecialIntrinsic: {
Timothy Liang651286f2018-06-07 09:55:33 -0400374 // 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 -0500375 String tmpX = "tmpX" + to_string(fVarCount++);
376 String tmpY = "tmpY" + to_string(fVarCount++);
377 this->fFunctionHeader += " " + this->typeName(c.fArguments[0]->fType) + " " + tmpX +
378 ", " + tmpY + ";\n";
379 this->write("(" + tmpX + " = ");
Timothy Liang651286f2018-06-07 09:55:33 -0400380 this->writeExpression(*c.fArguments[0], kSequence_Precedence);
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500381 this->write(", " + tmpY + " = ");
Timothy Liang651286f2018-06-07 09:55:33 -0400382 this->writeExpression(*c.fArguments[1], kSequence_Precedence);
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500383 this->write(", " + tmpX + " - " + tmpY + " * floor(" + tmpX + " / " + tmpY + "))");
Timothy Liang651286f2018-06-07 09:55:33 -0400384 break;
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500385 }
Timothy Liang6403b0e2018-05-17 10:40:04 -0400386 default:
387 ABORT("unsupported special intrinsic kind");
388 }
389}
390
John Stiles1bdafbf2020-05-28 12:17:20 -0400391// Generates a constructor for 'matrix' which reorganizes the input arguments into the proper shape.
392// Keeps track of previously generated constructors so that we won't generate more than one
393// constructor for any given permutation of input argument types. Returns the name of the
394// generated constructor method.
395String MetalCodeGenerator::getMatrixConstructHelper(const Constructor& c) {
396 const Type& matrix = c.fType;
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500397 int columns = matrix.columns();
398 int rows = matrix.rows();
John Stiles1bdafbf2020-05-28 12:17:20 -0400399 const std::vector<std::unique_ptr<Expression>>& args = c.fArguments;
400
401 // Create the helper-method name and use it as our lookup key.
402 String name;
403 name.appendf("float%dx%d_from", columns, rows);
404 for (const std::unique_ptr<Expression>& expr : args) {
405 name.appendf("_%s", expr->fType.displayName().c_str());
406 }
407
408 // If a helper-method has already been synthesized, we don't need to synthesize it again.
409 auto [iter, newlyCreated] = fHelpers.insert(name);
410 if (!newlyCreated) {
411 return name;
412 }
413
414 // Unlike GLSL, Metal requires that matrices are initialized with exactly R vectors of C
415 // components apiece. (In Metal 2.0, you can also supply R*C scalars, but you still cannot
416 // supply a mixture of scalars and vectors.)
417 fExtraFunctions.printf("float%dx%d %s(", columns, rows, name.c_str());
418
419 size_t argIndex = 0;
420 const char* argSeparator = "";
421 for (const std::unique_ptr<Expression>& expr : c.fArguments) {
422 fExtraFunctions.printf("%s%s x%zu", argSeparator,
423 expr->fType.displayName().c_str(), argIndex++);
424 argSeparator = ", ";
425 }
426
427 fExtraFunctions.printf(") {\n return float%dx%d(", columns, rows);
428
429 argIndex = 0;
430 int argPosition = 0;
431
432 const char* columnSeparator = "";
433 for (int c = 0; c < columns; ++c) {
434 fExtraFunctions.printf("%sfloat%d(", columnSeparator, rows);
435 columnSeparator = "), ";
436
437 const char* rowSeparator = "";
438 for (int r = 0; r < rows; ++r) {
439 fExtraFunctions.printf("%s", rowSeparator);
440 rowSeparator = ", ";
441
John Stiles0e041ba2020-08-05 11:14:33 -0400442 if (argIndex < args.size()) {
443 const Type& argType = args[argIndex]->fType;
444 switch (argType.kind()) {
445 case Type::kScalar_Kind: {
446 fExtraFunctions.printf("x%zu", argIndex);
447 break;
448 }
449 case Type::kVector_Kind: {
450 fExtraFunctions.printf("x%zu[%d]", argIndex, argPosition);
451 break;
452 }
453 case Type::kMatrix_Kind: {
454 fExtraFunctions.printf("x%zu[%d][%d]", argIndex,
455 argPosition / argType.rows(),
456 argPosition % argType.rows());
457 break;
458 }
459 default: {
460 SkDEBUGFAIL("incorrect type of argument for matrix constructor");
461 fExtraFunctions.printf("<error>");
462 break;
463 }
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500464 }
John Stiles1bdafbf2020-05-28 12:17:20 -0400465
John Stiles0e041ba2020-08-05 11:14:33 -0400466 ++argPosition;
467 if (argPosition >= argType.columns() * argType.rows()) {
468 ++argIndex;
469 argPosition = 0;
470 }
471 } else {
472 SkDEBUGFAIL("not enough arguments for matrix constructor");
473 fExtraFunctions.printf("<error>");
John Stiles1bdafbf2020-05-28 12:17:20 -0400474 }
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500475 }
John Stiles1bdafbf2020-05-28 12:17:20 -0400476 }
477
478 if (argPosition != 0 || argIndex != args.size()) {
479 SkDEBUGFAIL("incorrect number of arguments for matrix constructor");
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500480 name = "<error>";
481 }
John Stiles1bdafbf2020-05-28 12:17:20 -0400482
483 fExtraFunctions.printf("));\n}\n");
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500484 return name;
485}
486
487bool MetalCodeGenerator::canCoerce(const Type& t1, const Type& t2) {
488 if (t1.columns() != t2.columns() || t1.rows() != t2.rows()) {
489 return false;
490 }
491 if (t1.columns() > 1) {
492 return this->canCoerce(t1.componentType(), t2.componentType());
493 }
Ethan Nicholase1f55022019-02-05 17:17:40 -0500494 return t1.isFloat() && t2.isFloat();
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500495}
496
John Stiles1bdafbf2020-05-28 12:17:20 -0400497bool MetalCodeGenerator::matrixConstructHelperIsNeeded(const Constructor& c) {
498 // A matrix construct helper is only necessary if we are, in fact, constructing a matrix.
499 if (c.fType.kind() != Type::kMatrix_Kind) {
500 return false;
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500501 }
John Stiles1bdafbf2020-05-28 12:17:20 -0400502
503 // GLSL is fairly free-form about inputs to its matrix constructors, but Metal is not; it
504 // expects exactly R vectors of C components apiece. (Metal 2.0 also allows a list of R*C
505 // scalars.) Some cases are simple to translate and so we handle those inline--e.g. a list of
506 // scalars can be constructed trivially. In more complex cases, we generate a helper function
507 // that converts our inputs into a properly-shaped matrix.
508 // A matrix construct helper method is always used if any input argument is a matrix.
509 // Helper methods are also necessary when any argument would span multiple rows. For instance:
510 //
511 // float2 x = (1, 2);
512 // float3x2(x, 3, 4, 5, 6) = | 1 3 5 | = no helper needed; conversion can be done inline
513 // | 2 4 6 |
514 //
515 // float2 x = (2, 3);
516 // float3x2(1, x, 4, 5, 6) = | 1 3 5 | = x spans multiple rows; a helper method will be used
517 // | 2 4 6 |
518 //
519 // float4 x = (1, 2, 3, 4);
520 // float2x2(x) = | 1 3 | = x spans multiple rows; a helper method will be used
521 // | 2 4 |
522 //
523
524 int position = 0;
525 for (const std::unique_ptr<Expression>& expr : c.fArguments) {
526 // If an input argument is a matrix, we need a helper function.
527 if (expr->fType.kind() == Type::kMatrix_Kind) {
528 return true;
529 }
530 position += expr->fType.columns();
531 if (position > c.fType.rows()) {
532 // An input argument would span multiple rows; a helper function is required.
533 return true;
534 }
535 if (position == c.fType.rows()) {
536 // We've advanced to the end of a row. Wrap to the start of the next row.
537 position = 0;
538 }
539 }
540
541 return false;
542}
543
544void MetalCodeGenerator::writeConstructor(const Constructor& c, Precedence parentPrecedence) {
545 // Handle special cases for single-argument constructors.
546 if (c.fArguments.size() == 1) {
547 // If the type is coercible, emit it directly.
548 const Expression& arg = *c.fArguments.front();
549 if (this->canCoerce(c.fType, arg.fType)) {
550 this->writeExpression(arg, parentPrecedence);
551 return;
552 }
553
554 // Metal supports creating matrices with a scalar on the diagonal via the single-argument
555 // matrix constructor.
556 if (c.fType.kind() == Type::kMatrix_Kind && arg.fType.isNumber()) {
557 const Type& matrix = c.fType;
558 this->write("float");
559 this->write(to_string(matrix.columns()));
560 this->write("x");
561 this->write(to_string(matrix.rows()));
562 this->write("(");
563 this->writeExpression(arg, parentPrecedence);
564 this->write(")");
565 return;
566 }
567 }
568
569 // Emit and invoke a matrix-constructor helper method if one is necessary.
570 if (this->matrixConstructHelperIsNeeded(c)) {
571 this->write(this->getMatrixConstructHelper(c));
John Stiles1fa15b12020-05-28 17:36:54 +0000572 this->write("(");
573 const char* separator = "";
John Stiles1bdafbf2020-05-28 12:17:20 -0400574 for (const std::unique_ptr<Expression>& expr : c.fArguments) {
John Stiles1fa15b12020-05-28 17:36:54 +0000575 this->write(separator);
576 separator = ", ";
John Stiles1bdafbf2020-05-28 12:17:20 -0400577 this->writeExpression(*expr, kSequence_Precedence);
John Stilesdaa573e2020-05-28 12:17:20 -0400578 }
John Stiles1fa15b12020-05-28 17:36:54 +0000579 this->write(")");
John Stiles1bdafbf2020-05-28 12:17:20 -0400580 return;
John Stilesdaa573e2020-05-28 12:17:20 -0400581 }
John Stiles1bdafbf2020-05-28 12:17:20 -0400582
583 // Explicitly invoke the constructor, passing in the necessary arguments.
584 this->writeType(c.fType);
585 this->write("(");
586 const char* separator = "";
587 int scalarCount = 0;
588 for (const std::unique_ptr<Expression>& arg : c.fArguments) {
589 this->write(separator);
590 separator = ", ";
591 if (Type::kMatrix_Kind == c.fType.kind() && arg->fType.columns() < c.fType.rows()) {
592 // Merge scalars and smaller vectors together.
593 if (!scalarCount) {
594 this->writeType(c.fType.componentType());
595 this->write(to_string(c.fType.rows()));
596 this->write("(");
597 }
598 scalarCount += arg->fType.columns();
599 }
600 this->writeExpression(*arg, kSequence_Precedence);
601 if (scalarCount && scalarCount == c.fType.rows()) {
602 this->write(")");
603 scalarCount = 0;
604 }
605 }
606 this->write(")");
Ethan Nicholascc305772017-10-13 16:17:45 -0400607}
608
609void MetalCodeGenerator::writeFragCoord() {
Ethan Nicholasf931e402019-07-26 15:40:33 -0400610 if (fRTHeightName.length()) {
611 this->write("float4(_fragCoord.x, ");
612 this->write(fRTHeightName.c_str());
613 this->write(" - _fragCoord.y, 0.0, _fragCoord.w)");
Jim Van Verth6bc650e2019-02-07 14:53:23 -0500614 } else {
615 this->write("float4(_fragCoord.x, _fragCoord.y, 0.0, _fragCoord.w)");
616 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400617}
618
619void MetalCodeGenerator::writeVariableReference(const VariableReference& ref) {
620 switch (ref.fVariable.fModifiers.fLayout.fBuiltin) {
621 case SK_FRAGCOLOR_BUILTIN:
Timothy Liang7d637782018-06-05 09:58:07 -0400622 this->write("_out->sk_FragColor");
Ethan Nicholascc305772017-10-13 16:17:45 -0400623 break;
Timothy Liang6403b0e2018-05-17 10:40:04 -0400624 case SK_FRAGCOORD_BUILTIN:
625 this->writeFragCoord();
626 break;
Timothy Liangdc89f192018-06-13 09:20:31 -0400627 case SK_VERTEXID_BUILTIN:
628 this->write("sk_VertexID");
629 break;
630 case SK_INSTANCEID_BUILTIN:
631 this->write("sk_InstanceID");
632 break;
Timothy Liang7b8875d2018-08-10 09:42:31 -0400633 case SK_CLOCKWISE_BUILTIN:
634 // We'd set the front facing winding in the MTLRenderCommandEncoder to be counter
Brian Salomonf4ba4ec2020-03-19 15:54:28 -0400635 // clockwise to match Skia convention.
Timothy Liang7b8875d2018-08-10 09:42:31 -0400636 this->write(fProgram.fSettings.fFlipY ? "_frontFacing" : "(!_frontFacing)");
637 break;
Ethan Nicholascc305772017-10-13 16:17:45 -0400638 default:
639 if (Variable::kGlobal_Storage == ref.fVariable.fStorage) {
640 if (ref.fVariable.fModifiers.fFlags & Modifiers::kIn_Flag) {
641 this->write("_in.");
642 } else if (ref.fVariable.fModifiers.fFlags & Modifiers::kOut_Flag) {
Timothy Liangee84fe12018-05-18 14:38:19 -0400643 this->write("_out->");
Timothy Lianga06f2152018-05-24 15:33:31 -0400644 } else if (ref.fVariable.fModifiers.fFlags & Modifiers::kUniform_Flag &&
645 ref.fVariable.fType.kind() != Type::kSampler_Kind) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400646 this->write("_uniforms.");
647 } else {
Timothy Liangee84fe12018-05-18 14:38:19 -0400648 this->write("_globals->");
Ethan Nicholascc305772017-10-13 16:17:45 -0400649 }
650 }
Timothy Liang651286f2018-06-07 09:55:33 -0400651 this->writeName(ref.fVariable.fName);
Ethan Nicholascc305772017-10-13 16:17:45 -0400652 }
653}
654
655void MetalCodeGenerator::writeIndexExpression(const IndexExpression& expr) {
656 this->writeExpression(*expr.fBase, kPostfix_Precedence);
657 this->write("[");
658 this->writeExpression(*expr.fIndex, kTopLevel_Precedence);
659 this->write("]");
660}
661
662void MetalCodeGenerator::writeFieldAccess(const FieldAccess& f) {
Timothy Liang7d637782018-06-05 09:58:07 -0400663 const Type::Field* field = &f.fBase->fType.fields()[f.fFieldIndex];
Ethan Nicholascc305772017-10-13 16:17:45 -0400664 if (FieldAccess::kDefault_OwnerKind == f.fOwnerKind) {
665 this->writeExpression(*f.fBase, kPostfix_Precedence);
666 this->write(".");
667 }
Timothy Liang7d637782018-06-05 09:58:07 -0400668 switch (field->fModifiers.fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400669 case SK_CLIPDISTANCE_BUILTIN:
670 this->write("gl_ClipDistance");
671 break;
672 case SK_POSITION_BUILTIN:
Timothy Liangb8eeb802018-07-23 16:46:16 -0400673 this->write("_out->sk_Position");
Ethan Nicholascc305772017-10-13 16:17:45 -0400674 break;
675 default:
Timothy Liang7d637782018-06-05 09:58:07 -0400676 if (field->fName == "sk_PointSize") {
677 this->write("_out->sk_PointSize");
678 } else {
679 if (FieldAccess::kAnonymousInterfaceBlock_OwnerKind == f.fOwnerKind) {
680 this->write("_globals->");
681 this->write(fInterfaceBlockNameMap[fInterfaceBlockMap[field]]);
682 this->write("->");
683 }
Timothy Liang651286f2018-06-07 09:55:33 -0400684 this->writeName(field->fName);
Timothy Lianga06f2152018-05-24 15:33:31 -0400685 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400686 }
687}
688
689void MetalCodeGenerator::writeSwizzle(const Swizzle& swizzle) {
Ethan Nicholas5476f2e2019-03-07 15:11:31 -0500690 int last = swizzle.fComponents.back();
691 if (last == SKSL_SWIZZLE_0 || last == SKSL_SWIZZLE_1) {
692 this->writeType(swizzle.fType);
693 this->write("(");
694 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400695 this->writeExpression(*swizzle.fBase, kPostfix_Precedence);
696 this->write(".");
697 for (int c : swizzle.fComponents) {
Ethan Nicholas5476f2e2019-03-07 15:11:31 -0500698 if (c >= 0) {
699 this->write(&("x\0y\0z\0w\0"[c * 2]));
700 }
701 }
702 if (last == SKSL_SWIZZLE_0) {
703 this->write(", 0)");
704 }
705 else if (last == SKSL_SWIZZLE_1) {
706 this->write(", 1)");
Ethan Nicholascc305772017-10-13 16:17:45 -0400707 }
708}
709
710MetalCodeGenerator::Precedence MetalCodeGenerator::GetBinaryPrecedence(Token::Kind op) {
711 switch (op) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400712 case Token::Kind::TK_STAR: // fall through
713 case Token::Kind::TK_SLASH: // fall through
714 case Token::Kind::TK_PERCENT: return MetalCodeGenerator::kMultiplicative_Precedence;
715 case Token::Kind::TK_PLUS: // fall through
716 case Token::Kind::TK_MINUS: return MetalCodeGenerator::kAdditive_Precedence;
717 case Token::Kind::TK_SHL: // fall through
718 case Token::Kind::TK_SHR: return MetalCodeGenerator::kShift_Precedence;
719 case Token::Kind::TK_LT: // fall through
720 case Token::Kind::TK_GT: // fall through
721 case Token::Kind::TK_LTEQ: // fall through
722 case Token::Kind::TK_GTEQ: return MetalCodeGenerator::kRelational_Precedence;
723 case Token::Kind::TK_EQEQ: // fall through
724 case Token::Kind::TK_NEQ: return MetalCodeGenerator::kEquality_Precedence;
725 case Token::Kind::TK_BITWISEAND: return MetalCodeGenerator::kBitwiseAnd_Precedence;
726 case Token::Kind::TK_BITWISEXOR: return MetalCodeGenerator::kBitwiseXor_Precedence;
727 case Token::Kind::TK_BITWISEOR: return MetalCodeGenerator::kBitwiseOr_Precedence;
728 case Token::Kind::TK_LOGICALAND: return MetalCodeGenerator::kLogicalAnd_Precedence;
729 case Token::Kind::TK_LOGICALXOR: return MetalCodeGenerator::kLogicalXor_Precedence;
730 case Token::Kind::TK_LOGICALOR: return MetalCodeGenerator::kLogicalOr_Precedence;
731 case Token::Kind::TK_EQ: // fall through
732 case Token::Kind::TK_PLUSEQ: // fall through
733 case Token::Kind::TK_MINUSEQ: // fall through
734 case Token::Kind::TK_STAREQ: // fall through
735 case Token::Kind::TK_SLASHEQ: // fall through
736 case Token::Kind::TK_PERCENTEQ: // fall through
737 case Token::Kind::TK_SHLEQ: // fall through
738 case Token::Kind::TK_SHREQ: // fall through
739 case Token::Kind::TK_LOGICALANDEQ: // fall through
740 case Token::Kind::TK_LOGICALXOREQ: // fall through
741 case Token::Kind::TK_LOGICALOREQ: // fall through
742 case Token::Kind::TK_BITWISEANDEQ: // fall through
743 case Token::Kind::TK_BITWISEXOREQ: // fall through
744 case Token::Kind::TK_BITWISEOREQ: return MetalCodeGenerator::kAssignment_Precedence;
745 case Token::Kind::TK_COMMA: return MetalCodeGenerator::kSequence_Precedence;
Ethan Nicholascc305772017-10-13 16:17:45 -0400746 default: ABORT("unsupported binary operator");
747 }
748}
749
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500750void MetalCodeGenerator::writeMatrixTimesEqualHelper(const Type& left, const Type& right,
751 const Type& result) {
752 String key = "TimesEqual" + left.name() + right.name();
753 if (fHelpers.find(key) == fHelpers.end()) {
754 fExtraFunctions.printf("%s operator*=(thread %s& left, thread const %s& right) {\n"
755 " left = left * right;\n"
756 " return left;\n"
757 "}", result.name().c_str(), left.name().c_str(),
758 right.name().c_str());
759 }
760}
761
Ethan Nicholascc305772017-10-13 16:17:45 -0400762void MetalCodeGenerator::writeBinaryExpression(const BinaryExpression& b,
763 Precedence parentPrecedence) {
764 Precedence precedence = GetBinaryPrecedence(b.fOperator);
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500765 bool needParens = precedence >= parentPrecedence;
766 switch (b.fOperator) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400767 case Token::Kind::TK_EQEQ:
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500768 if (b.fLeft->fType.kind() == Type::kVector_Kind) {
769 this->write("all");
770 needParens = true;
771 }
772 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400773 case Token::Kind::TK_NEQ:
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500774 if (b.fLeft->fType.kind() == Type::kVector_Kind) {
Jim Van Verth36477b42019-04-11 14:57:30 -0400775 this->write("any");
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500776 needParens = true;
777 }
778 break;
779 default:
780 break;
781 }
782 if (needParens) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400783 this->write("(");
784 }
785 if (Compiler::IsAssignment(b.fOperator) &&
786 Expression::kVariableReference_Kind == b.fLeft->fKind &&
787 Variable::kParameter_Storage == ((VariableReference&) *b.fLeft).fVariable.fStorage &&
788 (((VariableReference&) *b.fLeft).fVariable.fModifiers.fFlags & Modifiers::kOut_Flag)) {
789 // writing to an out parameter. Since we have to turn those into pointers, we have to
790 // dereference it here.
791 this->write("*");
792 }
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400793 if (b.fOperator == Token::Kind::TK_STAREQ && b.fLeft->fType.kind() == Type::kMatrix_Kind &&
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500794 b.fRight->fType.kind() == Type::kMatrix_Kind) {
795 this->writeMatrixTimesEqualHelper(b.fLeft->fType, b.fRight->fType, b.fType);
796 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400797 this->writeExpression(*b.fLeft, precedence);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400798 if (b.fOperator != Token::Kind::TK_EQ && Compiler::IsAssignment(b.fOperator) &&
Ethan Nicholascc305772017-10-13 16:17:45 -0400799 Expression::kSwizzle_Kind == b.fLeft->fKind && !b.fLeft->hasSideEffects()) {
800 // This doesn't compile in Metal:
801 // float4 x = float4(1);
802 // x.xy *= float2x2(...);
803 // with the error message "non-const reference cannot bind to vector element",
804 // but switching it to x.xy = x.xy * float2x2(...) fixes it. We perform this tranformation
805 // as long as the LHS has no side effects, and hope for the best otherwise.
806 this->write(" = ");
807 this->writeExpression(*b.fLeft, kAssignment_Precedence);
808 this->write(" ");
809 String op = Compiler::OperatorName(b.fOperator);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400810 SkASSERT(op.endsWith("="));
Ethan Nicholascc305772017-10-13 16:17:45 -0400811 this->write(op.substr(0, op.size() - 1).c_str());
812 this->write(" ");
813 } else {
814 this->write(String(" ") + Compiler::OperatorName(b.fOperator) + " ");
815 }
816 this->writeExpression(*b.fRight, precedence);
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500817 if (needParens) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400818 this->write(")");
819 }
820}
821
822void MetalCodeGenerator::writeTernaryExpression(const TernaryExpression& t,
823 Precedence parentPrecedence) {
824 if (kTernary_Precedence >= parentPrecedence) {
825 this->write("(");
826 }
827 this->writeExpression(*t.fTest, kTernary_Precedence);
828 this->write(" ? ");
829 this->writeExpression(*t.fIfTrue, kTernary_Precedence);
830 this->write(" : ");
831 this->writeExpression(*t.fIfFalse, kTernary_Precedence);
832 if (kTernary_Precedence >= parentPrecedence) {
833 this->write(")");
834 }
835}
836
837void MetalCodeGenerator::writePrefixExpression(const PrefixExpression& p,
838 Precedence parentPrecedence) {
839 if (kPrefix_Precedence >= parentPrecedence) {
840 this->write("(");
841 }
842 this->write(Compiler::OperatorName(p.fOperator));
843 this->writeExpression(*p.fOperand, kPrefix_Precedence);
844 if (kPrefix_Precedence >= parentPrecedence) {
845 this->write(")");
846 }
847}
848
849void MetalCodeGenerator::writePostfixExpression(const PostfixExpression& p,
850 Precedence parentPrecedence) {
851 if (kPostfix_Precedence >= parentPrecedence) {
852 this->write("(");
853 }
854 this->writeExpression(*p.fOperand, kPostfix_Precedence);
855 this->write(Compiler::OperatorName(p.fOperator));
856 if (kPostfix_Precedence >= parentPrecedence) {
857 this->write(")");
858 }
859}
860
861void MetalCodeGenerator::writeBoolLiteral(const BoolLiteral& b) {
862 this->write(b.fValue ? "true" : "false");
863}
864
865void MetalCodeGenerator::writeIntLiteral(const IntLiteral& i) {
866 if (i.fType == *fContext.fUInt_Type) {
867 this->write(to_string(i.fValue & 0xffffffff) + "u");
868 } else {
869 this->write(to_string((int32_t) i.fValue));
870 }
871}
872
873void MetalCodeGenerator::writeFloatLiteral(const FloatLiteral& f) {
874 this->write(to_string(f.fValue));
875}
876
877void MetalCodeGenerator::writeSetting(const Setting& s) {
878 ABORT("internal error; setting was not folded to a constant during compilation\n");
879}
880
881void MetalCodeGenerator::writeFunction(const FunctionDefinition& f) {
Ethan Nicholasf931e402019-07-26 15:40:33 -0400882 fRTHeightName = fProgram.fInputs.fRTHeight ? "_globals->_anonInterface0->u_skRTHeight" : "";
Ethan Nicholascc305772017-10-13 16:17:45 -0400883 const char* separator = "";
884 if ("main" == f.fDeclaration.fName) {
885 switch (fProgram.fKind) {
886 case Program::kFragment_Kind:
Timothy Liangb8eeb802018-07-23 16:46:16 -0400887 this->write("fragment Outputs fragmentMain");
Ethan Nicholascc305772017-10-13 16:17:45 -0400888 break;
889 case Program::kVertex_Kind:
Timothy Liangb8eeb802018-07-23 16:46:16 -0400890 this->write("vertex Outputs vertexMain");
Ethan Nicholascc305772017-10-13 16:17:45 -0400891 break;
892 default:
John Stilesf7d70432020-05-28 15:46:38 -0400893 SkDEBUGFAIL("unsupported kind of program");
Ethan Nicholascc305772017-10-13 16:17:45 -0400894 }
895 this->write("(Inputs _in [[stage_in]]");
896 if (-1 != fUniformBuffer) {
897 this->write(", constant Uniforms& _uniforms [[buffer(" +
898 to_string(fUniformBuffer) + ")]]");
899 }
Timothy Liang6403b0e2018-05-17 10:40:04 -0400900 for (const auto& e : fProgram) {
901 if (ProgramElement::kVar_Kind == e.fKind) {
902 VarDeclarations& decls = (VarDeclarations&) e;
903 if (!decls.fVars.size()) {
904 continue;
905 }
Timothy Liangee84fe12018-05-18 14:38:19 -0400906 for (const auto& stmt: decls.fVars) {
Timothy Liang6403b0e2018-05-17 10:40:04 -0400907 VarDeclaration& var = (VarDeclaration&) *stmt;
Timothy Liangee84fe12018-05-18 14:38:19 -0400908 if (var.fVar->fType.kind() == Type::kSampler_Kind) {
John Stiles08cb2c12020-07-06 10:18:49 -0400909 if (var.fVar->fModifiers.fLayout.fBinding < 0) {
910 fErrors.error(decls.fOffset,
911 "Metal samplers must have 'layout(binding=...)'");
912 }
Timothy Liang7d637782018-06-05 09:58:07 -0400913 this->write(", texture2d<float> "); // FIXME - support other texture types
Timothy Liang651286f2018-06-07 09:55:33 -0400914 this->writeName(var.fVar->fName);
Timothy Liangee84fe12018-05-18 14:38:19 -0400915 this->write("[[texture(");
Timothy Lianga06f2152018-05-24 15:33:31 -0400916 this->write(to_string(var.fVar->fModifiers.fLayout.fBinding));
917 this->write(")]]");
918 this->write(", sampler ");
Timothy Liang651286f2018-06-07 09:55:33 -0400919 this->writeName(var.fVar->fName);
Timothy Lianga06f2152018-05-24 15:33:31 -0400920 this->write(SAMPLER_SUFFIX);
921 this->write("[[sampler(");
922 this->write(to_string(var.fVar->fModifiers.fLayout.fBinding));
Timothy Liangee84fe12018-05-18 14:38:19 -0400923 this->write(")]]");
924 }
Timothy Liang6403b0e2018-05-17 10:40:04 -0400925 }
Timothy Lianga06f2152018-05-24 15:33:31 -0400926 } else if (ProgramElement::kInterfaceBlock_Kind == e.fKind) {
927 InterfaceBlock& intf = (InterfaceBlock&) e;
928 if ("sk_PerVertex" == intf.fTypeName) {
929 continue;
930 }
931 this->write(", constant ");
932 this->writeType(intf.fVariable.fType);
933 this->write("& " );
934 this->write(fInterfaceBlockNameMap[&intf]);
935 this->write(" [[buffer(");
Timothy Liang057c3902018-08-08 10:48:45 -0400936 this->write(to_string(intf.fVariable.fModifiers.fLayout.fBinding));
Timothy Lianga06f2152018-05-24 15:33:31 -0400937 this->write(")]]");
Timothy Liang6403b0e2018-05-17 10:40:04 -0400938 }
939 }
Jim Van Verth6bc650e2019-02-07 14:53:23 -0500940 if (fProgram.fKind == Program::kFragment_Kind) {
941 if (fProgram.fInputs.fRTHeight && fInterfaceBlockNameMap.empty()) {
Timothy Liang5422f9a2018-08-10 10:57:55 -0400942 this->write(", constant sksl_synthetic_uniforms& _anonInterface0 [[buffer(1)]]");
Ethan Nicholasf931e402019-07-26 15:40:33 -0400943 fRTHeightName = "_anonInterface0.u_skRTHeight";
Timothy Liang5422f9a2018-08-10 10:57:55 -0400944 }
Timothy Liang7b8875d2018-08-10 09:42:31 -0400945 this->write(", bool _frontFacing [[front_facing]]");
Timothy Liang7d637782018-06-05 09:58:07 -0400946 this->write(", float4 _fragCoord [[position]]");
Timothy Liangdc89f192018-06-13 09:20:31 -0400947 } else if (fProgram.fKind == Program::kVertex_Kind) {
948 this->write(", uint sk_VertexID [[vertex_id]], uint sk_InstanceID [[instance_id]]");
Timothy Liang7d637782018-06-05 09:58:07 -0400949 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400950 separator = ", ";
951 } else {
952 this->writeType(f.fDeclaration.fReturnType);
Timothy Liang651286f2018-06-07 09:55:33 -0400953 this->write(" ");
954 this->writeName(f.fDeclaration.fName);
955 this->write("(");
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -0400956 Requirements requirements = this->requirements(f.fDeclaration);
957 if (requirements & kInputs_Requirement) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400958 this->write("Inputs _in");
959 separator = ", ";
960 }
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -0400961 if (requirements & kOutputs_Requirement) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400962 this->write(separator);
Timothy Liangee84fe12018-05-18 14:38:19 -0400963 this->write("thread Outputs* _out");
Ethan Nicholascc305772017-10-13 16:17:45 -0400964 separator = ", ";
965 }
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -0400966 if (requirements & kUniforms_Requirement) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400967 this->write(separator);
968 this->write("Uniforms _uniforms");
969 separator = ", ";
970 }
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -0400971 if (requirements & kGlobals_Requirement) {
Timothy Liangee84fe12018-05-18 14:38:19 -0400972 this->write(separator);
973 this->write("thread Globals* _globals");
974 separator = ", ";
975 }
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -0400976 if (requirements & kFragCoord_Requirement) {
977 this->write(separator);
978 this->write("float4 _fragCoord");
979 separator = ", ";
980 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400981 }
982 for (const auto& param : f.fDeclaration.fParameters) {
983 this->write(separator);
984 separator = ", ";
985 this->writeModifiers(param->fModifiers, false);
986 std::vector<int> sizes;
987 const Type* type = &param->fType;
988 while (Type::kArray_Kind == type->kind()) {
989 sizes.push_back(type->columns());
990 type = &type->componentType();
991 }
992 this->writeType(*type);
993 if (param->fModifiers.fFlags & Modifiers::kOut_Flag) {
994 this->write("*");
995 }
Timothy Liang651286f2018-06-07 09:55:33 -0400996 this->write(" ");
997 this->writeName(param->fName);
Ethan Nicholascc305772017-10-13 16:17:45 -0400998 for (int s : sizes) {
999 if (s <= 0) {
1000 this->write("[]");
1001 } else {
1002 this->write("[" + to_string(s) + "]");
1003 }
1004 }
1005 }
1006 this->writeLine(") {");
1007
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001008 SkASSERT(!fProgram.fSettings.fFragColorIsInOut);
Brian Salomondc092132018-04-04 10:14:16 -04001009
Ethan Nicholascc305772017-10-13 16:17:45 -04001010 if ("main" == f.fDeclaration.fName) {
John Stilescdcdb042020-07-06 09:03:51 -04001011 this->writeGlobalInit();
Timothy Liang7d637782018-06-05 09:58:07 -04001012 this->writeLine(" Outputs _outputStruct;");
1013 this->writeLine(" thread Outputs* _out = &_outputStruct;");
Ethan Nicholascc305772017-10-13 16:17:45 -04001014 }
John Stilesc67b3622020-05-28 17:53:13 -04001015
Ethan Nicholascc305772017-10-13 16:17:45 -04001016 fFunctionHeader = "";
1017 OutputStream* oldOut = fOut;
1018 StringStream buffer;
1019 fOut = &buffer;
1020 fIndentation++;
1021 this->writeStatements(((Block&) *f.fBody).fStatements);
1022 if ("main" == f.fDeclaration.fName) {
1023 switch (fProgram.fKind) {
1024 case Program::kFragment_Kind:
Timothy Liang7d637782018-06-05 09:58:07 -04001025 this->writeLine("return *_out;");
Ethan Nicholascc305772017-10-13 16:17:45 -04001026 break;
1027 case Program::kVertex_Kind:
Timothy Liangb8eeb802018-07-23 16:46:16 -04001028 this->writeLine("_out->sk_Position.y = -_out->sk_Position.y;");
Timothy Lianga06f2152018-05-24 15:33:31 -04001029 this->writeLine("return *_out;"); // FIXME - detect if function already has return
Ethan Nicholascc305772017-10-13 16:17:45 -04001030 break;
1031 default:
John Stilesf7d70432020-05-28 15:46:38 -04001032 SkDEBUGFAIL("unsupported kind of program");
Ethan Nicholascc305772017-10-13 16:17:45 -04001033 }
1034 }
1035 fIndentation--;
1036 this->writeLine("}");
1037
1038 fOut = oldOut;
1039 this->write(fFunctionHeader);
1040 this->write(buffer.str());
1041}
1042
1043void MetalCodeGenerator::writeModifiers(const Modifiers& modifiers,
1044 bool globalContext) {
1045 if (modifiers.fFlags & Modifiers::kOut_Flag) {
1046 this->write("thread ");
1047 }
1048 if (modifiers.fFlags & Modifiers::kConst_Flag) {
Timothy Liangee84fe12018-05-18 14:38:19 -04001049 this->write("constant ");
Ethan Nicholascc305772017-10-13 16:17:45 -04001050 }
1051}
1052
1053void MetalCodeGenerator::writeInterfaceBlock(const InterfaceBlock& intf) {
1054 if ("sk_PerVertex" == intf.fTypeName) {
1055 return;
1056 }
1057 this->writeModifiers(intf.fVariable.fModifiers, true);
Timothy Liangdc89f192018-06-13 09:20:31 -04001058 this->write("struct ");
Ethan Nicholascc305772017-10-13 16:17:45 -04001059 this->writeLine(intf.fTypeName + " {");
Ethan Nicholascc305772017-10-13 16:17:45 -04001060 const Type* structType = &intf.fVariable.fType;
Timothy Lianga06f2152018-05-24 15:33:31 -04001061 fWrittenStructs.push_back(structType);
Ethan Nicholascc305772017-10-13 16:17:45 -04001062 while (Type::kArray_Kind == structType->kind()) {
1063 structType = &structType->componentType();
1064 }
Timothy Liangdc89f192018-06-13 09:20:31 -04001065 fIndentation++;
1066 writeFields(structType->fields(), structType->fOffset, &intf);
Jim Van Verth3d482992019-02-07 10:48:05 -05001067 if (fProgram.fInputs.fRTHeight) {
Timothy Liang7d637782018-06-05 09:58:07 -04001068 this->writeLine("float u_skRTHeight;");
Ethan Nicholascc305772017-10-13 16:17:45 -04001069 }
1070 fIndentation--;
1071 this->write("}");
1072 if (intf.fInstanceName.size()) {
1073 this->write(" ");
1074 this->write(intf.fInstanceName);
1075 for (const auto& size : intf.fSizes) {
1076 this->write("[");
1077 if (size) {
1078 this->writeExpression(*size, kTopLevel_Precedence);
1079 }
1080 this->write("]");
1081 }
Timothy Lianga06f2152018-05-24 15:33:31 -04001082 fInterfaceBlockNameMap[&intf] = intf.fInstanceName;
1083 } else {
Timothy Liang7d637782018-06-05 09:58:07 -04001084 fInterfaceBlockNameMap[&intf] = "_anonInterface" + to_string(fAnonInterfaceCount++);
Ethan Nicholascc305772017-10-13 16:17:45 -04001085 }
1086 this->writeLine(";");
1087}
1088
Timothy Liangdc89f192018-06-13 09:20:31 -04001089void MetalCodeGenerator::writeFields(const std::vector<Type::Field>& fields, int parentOffset,
1090 const InterfaceBlock* parentIntf) {
Timothy Liang609fbe32018-08-10 16:40:49 -04001091 MemoryLayout memoryLayout(MemoryLayout::kMetal_Standard);
Timothy Liangdc89f192018-06-13 09:20:31 -04001092 int currentOffset = 0;
1093 for (const auto& field: fields) {
1094 int fieldOffset = field.fModifiers.fLayout.fOffset;
1095 const Type* fieldType = field.fType;
1096 if (fieldOffset != -1) {
1097 if (currentOffset > fieldOffset) {
1098 fErrors.error(parentOffset,
1099 "offset of field '" + field.fName + "' must be at least " +
1100 to_string((int) currentOffset));
1101 } else if (currentOffset < fieldOffset) {
1102 this->write("char pad");
1103 this->write(to_string(fPaddingCount++));
1104 this->write("[");
1105 this->write(to_string(fieldOffset - currentOffset));
1106 this->writeLine("];");
1107 currentOffset = fieldOffset;
1108 }
1109 int alignment = memoryLayout.alignment(*fieldType);
1110 if (fieldOffset % alignment) {
1111 fErrors.error(parentOffset,
1112 "offset of field '" + field.fName + "' must be a multiple of " +
1113 to_string((int) alignment));
1114 }
1115 }
Timothy Liangdc89f192018-06-13 09:20:31 -04001116 currentOffset += memoryLayout.size(*fieldType);
1117 std::vector<int> sizes;
1118 while (fieldType->kind() == Type::kArray_Kind) {
1119 sizes.push_back(fieldType->columns());
1120 fieldType = &fieldType->componentType();
1121 }
1122 this->writeModifiers(field.fModifiers, false);
1123 this->writeType(*fieldType);
1124 this->write(" ");
1125 this->writeName(field.fName);
1126 for (int s : sizes) {
1127 if (s <= 0) {
1128 this->write("[]");
1129 } else {
1130 this->write("[" + to_string(s) + "]");
1131 }
1132 }
1133 this->writeLine(";");
1134 if (parentIntf) {
1135 fInterfaceBlockMap[&field] = parentIntf;
1136 }
1137 }
1138}
1139
Ethan Nicholascc305772017-10-13 16:17:45 -04001140void MetalCodeGenerator::writeVarInitializer(const Variable& var, const Expression& value) {
1141 this->writeExpression(value, kTopLevel_Precedence);
1142}
1143
Timothy Liang651286f2018-06-07 09:55:33 -04001144void MetalCodeGenerator::writeName(const String& name) {
1145 if (fReservedWords.find(name) != fReservedWords.end()) {
1146 this->write("_"); // adding underscore before name to avoid conflict with reserved words
1147 }
1148 this->write(name);
1149}
1150
Ethan Nicholascc305772017-10-13 16:17:45 -04001151void MetalCodeGenerator::writeVarDeclarations(const VarDeclarations& decl, bool global) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001152 SkASSERT(decl.fVars.size() > 0);
Ethan Nicholascc305772017-10-13 16:17:45 -04001153 bool wroteType = false;
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001154 for (const auto& stmt : decl.fVars) {
1155 VarDeclaration& var = (VarDeclaration&) *stmt;
Timothy Liangee84fe12018-05-18 14:38:19 -04001156 if (global && !(var.fVar->fModifiers.fFlags & Modifiers::kConst_Flag)) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001157 continue;
1158 }
1159 if (wroteType) {
1160 this->write(", ");
1161 } else {
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001162 this->writeModifiers(var.fVar->fModifiers, global);
Ethan Nicholascc305772017-10-13 16:17:45 -04001163 this->writeType(decl.fBaseType);
1164 this->write(" ");
1165 wroteType = true;
1166 }
Timothy Liang651286f2018-06-07 09:55:33 -04001167 this->writeName(var.fVar->fName);
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001168 for (const auto& size : var.fSizes) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001169 this->write("[");
1170 if (size) {
1171 this->writeExpression(*size, kTopLevel_Precedence);
1172 }
1173 this->write("]");
1174 }
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001175 if (var.fValue) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001176 this->write(" = ");
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001177 this->writeVarInitializer(*var.fVar, *var.fValue);
Ethan Nicholascc305772017-10-13 16:17:45 -04001178 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001179 }
1180 if (wroteType) {
1181 this->write(";");
1182 }
1183}
1184
1185void MetalCodeGenerator::writeStatement(const Statement& s) {
1186 switch (s.fKind) {
1187 case Statement::kBlock_Kind:
1188 this->writeBlock((Block&) s);
1189 break;
1190 case Statement::kExpression_Kind:
1191 this->writeExpression(*((ExpressionStatement&) s).fExpression, kTopLevel_Precedence);
1192 this->write(";");
1193 break;
1194 case Statement::kReturn_Kind:
1195 this->writeReturnStatement((ReturnStatement&) s);
1196 break;
1197 case Statement::kVarDeclarations_Kind:
1198 this->writeVarDeclarations(*((VarDeclarationsStatement&) s).fDeclaration, false);
1199 break;
1200 case Statement::kIf_Kind:
1201 this->writeIfStatement((IfStatement&) s);
1202 break;
1203 case Statement::kFor_Kind:
1204 this->writeForStatement((ForStatement&) s);
1205 break;
1206 case Statement::kWhile_Kind:
1207 this->writeWhileStatement((WhileStatement&) s);
1208 break;
1209 case Statement::kDo_Kind:
1210 this->writeDoStatement((DoStatement&) s);
1211 break;
1212 case Statement::kSwitch_Kind:
1213 this->writeSwitchStatement((SwitchStatement&) s);
1214 break;
1215 case Statement::kBreak_Kind:
1216 this->write("break;");
1217 break;
1218 case Statement::kContinue_Kind:
1219 this->write("continue;");
1220 break;
1221 case Statement::kDiscard_Kind:
Timothy Lianga06f2152018-05-24 15:33:31 -04001222 this->write("discard_fragment();");
Ethan Nicholascc305772017-10-13 16:17:45 -04001223 break;
1224 case Statement::kNop_Kind:
1225 this->write(";");
1226 break;
1227 default:
Ethan Nicholas2a099da2020-01-02 14:40:54 -05001228#ifdef SK_DEBUG
Ethan Nicholascc305772017-10-13 16:17:45 -04001229 ABORT("unsupported statement: %s", s.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -05001230#endif
1231 break;
Ethan Nicholascc305772017-10-13 16:17:45 -04001232 }
1233}
1234
1235void MetalCodeGenerator::writeStatements(const std::vector<std::unique_ptr<Statement>>& statements) {
1236 for (const auto& s : statements) {
1237 if (!s->isEmpty()) {
1238 this->writeStatement(*s);
1239 this->writeLine();
1240 }
1241 }
1242}
1243
1244void MetalCodeGenerator::writeBlock(const Block& b) {
Ethan Nicholas70728ef2020-05-28 07:09:00 -04001245 if (b.fIsScope) {
1246 this->writeLine("{");
1247 fIndentation++;
1248 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001249 this->writeStatements(b.fStatements);
Ethan Nicholas70728ef2020-05-28 07:09:00 -04001250 if (b.fIsScope) {
1251 fIndentation--;
1252 this->write("}");
1253 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001254}
1255
1256void MetalCodeGenerator::writeIfStatement(const IfStatement& stmt) {
1257 this->write("if (");
1258 this->writeExpression(*stmt.fTest, kTopLevel_Precedence);
1259 this->write(") ");
1260 this->writeStatement(*stmt.fIfTrue);
1261 if (stmt.fIfFalse) {
1262 this->write(" else ");
1263 this->writeStatement(*stmt.fIfFalse);
1264 }
1265}
1266
1267void MetalCodeGenerator::writeForStatement(const ForStatement& f) {
1268 this->write("for (");
1269 if (f.fInitializer && !f.fInitializer->isEmpty()) {
1270 this->writeStatement(*f.fInitializer);
1271 } else {
1272 this->write("; ");
1273 }
1274 if (f.fTest) {
1275 this->writeExpression(*f.fTest, kTopLevel_Precedence);
1276 }
1277 this->write("; ");
1278 if (f.fNext) {
1279 this->writeExpression(*f.fNext, kTopLevel_Precedence);
1280 }
1281 this->write(") ");
1282 this->writeStatement(*f.fStatement);
1283}
1284
1285void MetalCodeGenerator::writeWhileStatement(const WhileStatement& w) {
1286 this->write("while (");
1287 this->writeExpression(*w.fTest, kTopLevel_Precedence);
1288 this->write(") ");
1289 this->writeStatement(*w.fStatement);
1290}
1291
1292void MetalCodeGenerator::writeDoStatement(const DoStatement& d) {
1293 this->write("do ");
1294 this->writeStatement(*d.fStatement);
1295 this->write(" while (");
1296 this->writeExpression(*d.fTest, kTopLevel_Precedence);
1297 this->write(");");
1298}
1299
1300void MetalCodeGenerator::writeSwitchStatement(const SwitchStatement& s) {
1301 this->write("switch (");
1302 this->writeExpression(*s.fValue, kTopLevel_Precedence);
1303 this->writeLine(") {");
1304 fIndentation++;
1305 for (const auto& c : s.fCases) {
1306 if (c->fValue) {
1307 this->write("case ");
1308 this->writeExpression(*c->fValue, kTopLevel_Precedence);
1309 this->writeLine(":");
1310 } else {
1311 this->writeLine("default:");
1312 }
1313 fIndentation++;
1314 for (const auto& stmt : c->fStatements) {
1315 this->writeStatement(*stmt);
1316 this->writeLine();
1317 }
1318 fIndentation--;
1319 }
1320 fIndentation--;
1321 this->write("}");
1322}
1323
1324void MetalCodeGenerator::writeReturnStatement(const ReturnStatement& r) {
1325 this->write("return");
1326 if (r.fExpression) {
1327 this->write(" ");
1328 this->writeExpression(*r.fExpression, kTopLevel_Precedence);
1329 }
1330 this->write(";");
1331}
1332
1333void MetalCodeGenerator::writeHeader() {
1334 this->write("#include <metal_stdlib>\n");
1335 this->write("#include <simd/simd.h>\n");
1336 this->write("using namespace metal;\n");
1337}
1338
1339void MetalCodeGenerator::writeUniformStruct() {
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001340 for (const auto& e : fProgram) {
1341 if (ProgramElement::kVar_Kind == e.fKind) {
1342 VarDeclarations& decls = (VarDeclarations&) e;
Ethan Nicholascc305772017-10-13 16:17:45 -04001343 if (!decls.fVars.size()) {
1344 continue;
1345 }
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001346 const Variable& first = *((VarDeclaration&) *decls.fVars[0]).fVar;
Timothy Lianga06f2152018-05-24 15:33:31 -04001347 if (first.fModifiers.fFlags & Modifiers::kUniform_Flag &&
1348 first.fType.kind() != Type::kSampler_Kind) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001349 if (-1 == fUniformBuffer) {
1350 this->write("struct Uniforms {\n");
1351 fUniformBuffer = first.fModifiers.fLayout.fSet;
1352 if (-1 == fUniformBuffer) {
1353 fErrors.error(decls.fOffset, "Metal uniforms must have 'layout(set=...)'");
1354 }
1355 } else if (first.fModifiers.fLayout.fSet != fUniformBuffer) {
1356 if (-1 == fUniformBuffer) {
1357 fErrors.error(decls.fOffset, "Metal backend requires all uniforms to have "
1358 "the same 'layout(set=...)'");
1359 }
1360 }
1361 this->write(" ");
1362 this->writeType(first.fType);
1363 this->write(" ");
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001364 for (const auto& stmt : decls.fVars) {
1365 VarDeclaration& var = (VarDeclaration&) *stmt;
Timothy Liang651286f2018-06-07 09:55:33 -04001366 this->writeName(var.fVar->fName);
Ethan Nicholascc305772017-10-13 16:17:45 -04001367 }
1368 this->write(";\n");
1369 }
1370 }
1371 }
1372 if (-1 != fUniformBuffer) {
1373 this->write("};\n");
1374 }
1375}
1376
1377void MetalCodeGenerator::writeInputStruct() {
1378 this->write("struct Inputs {\n");
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001379 for (const auto& e : fProgram) {
1380 if (ProgramElement::kVar_Kind == e.fKind) {
1381 VarDeclarations& decls = (VarDeclarations&) e;
Ethan Nicholascc305772017-10-13 16:17:45 -04001382 if (!decls.fVars.size()) {
1383 continue;
1384 }
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001385 const Variable& first = *((VarDeclaration&) *decls.fVars[0]).fVar;
Ethan Nicholascc305772017-10-13 16:17:45 -04001386 if (first.fModifiers.fFlags & Modifiers::kIn_Flag &&
1387 -1 == first.fModifiers.fLayout.fBuiltin) {
1388 this->write(" ");
1389 this->writeType(first.fType);
1390 this->write(" ");
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001391 for (const auto& stmt : decls.fVars) {
1392 VarDeclaration& var = (VarDeclaration&) *stmt;
Timothy Liang651286f2018-06-07 09:55:33 -04001393 this->writeName(var.fVar->fName);
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001394 if (-1 != var.fVar->fModifiers.fLayout.fLocation) {
Timothy Liang7d637782018-06-05 09:58:07 -04001395 if (fProgram.fKind == Program::kVertex_Kind) {
1396 this->write(" [[attribute(" +
1397 to_string(var.fVar->fModifiers.fLayout.fLocation) + ")]]");
1398 } else if (fProgram.fKind == Program::kFragment_Kind) {
1399 this->write(" [[user(locn" +
1400 to_string(var.fVar->fModifiers.fLayout.fLocation) + ")]]");
1401 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001402 }
1403 }
1404 this->write(";\n");
1405 }
1406 }
1407 }
1408 this->write("};\n");
1409}
1410
1411void MetalCodeGenerator::writeOutputStruct() {
1412 this->write("struct Outputs {\n");
Timothy Liang7d637782018-06-05 09:58:07 -04001413 if (fProgram.fKind == Program::kVertex_Kind) {
Timothy Liangb8eeb802018-07-23 16:46:16 -04001414 this->write(" float4 sk_Position [[position]];\n");
Timothy Liang7d637782018-06-05 09:58:07 -04001415 } else if (fProgram.fKind == Program::kFragment_Kind) {
Timothy Liangde0be802018-08-10 13:48:08 -04001416 this->write(" float4 sk_FragColor [[color(0)]];\n");
Timothy Liang7d637782018-06-05 09:58:07 -04001417 }
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001418 for (const auto& e : fProgram) {
1419 if (ProgramElement::kVar_Kind == e.fKind) {
1420 VarDeclarations& decls = (VarDeclarations&) e;
Ethan Nicholascc305772017-10-13 16:17:45 -04001421 if (!decls.fVars.size()) {
1422 continue;
1423 }
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001424 const Variable& first = *((VarDeclaration&) *decls.fVars[0]).fVar;
Ethan Nicholascc305772017-10-13 16:17:45 -04001425 if (first.fModifiers.fFlags & Modifiers::kOut_Flag &&
1426 -1 == first.fModifiers.fLayout.fBuiltin) {
1427 this->write(" ");
1428 this->writeType(first.fType);
1429 this->write(" ");
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001430 for (const auto& stmt : decls.fVars) {
1431 VarDeclaration& var = (VarDeclaration&) *stmt;
Timothy Liang651286f2018-06-07 09:55:33 -04001432 this->writeName(var.fVar->fName);
Timothy Liang7d637782018-06-05 09:58:07 -04001433 if (fProgram.fKind == Program::kVertex_Kind) {
1434 this->write(" [[user(locn" +
1435 to_string(var.fVar->fModifiers.fLayout.fLocation) + ")]]");
1436 } else if (fProgram.fKind == Program::kFragment_Kind) {
1437 this->write(" [[color(" +
Timothy Liangde0be802018-08-10 13:48:08 -04001438 to_string(var.fVar->fModifiers.fLayout.fLocation) +")");
1439 int colorIndex = var.fVar->fModifiers.fLayout.fIndex;
1440 if (colorIndex) {
1441 this->write(", index(" + to_string(colorIndex) + ")");
1442 }
1443 this->write("]]");
Timothy Liang7d637782018-06-05 09:58:07 -04001444 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001445 }
1446 this->write(";\n");
1447 }
1448 }
Timothy Liang7d637782018-06-05 09:58:07 -04001449 }
1450 if (fProgram.fKind == Program::kVertex_Kind) {
1451 this->write(" float sk_PointSize;\n");
1452 }
1453 this->write("};\n");
1454}
1455
1456void MetalCodeGenerator::writeInterfaceBlocks() {
1457 bool wroteInterfaceBlock = false;
1458 for (const auto& e : fProgram) {
1459 if (ProgramElement::kInterfaceBlock_Kind == e.fKind) {
1460 this->writeInterfaceBlock((InterfaceBlock&) e);
1461 wroteInterfaceBlock = true;
1462 }
1463 }
Jim Van Verth3d482992019-02-07 10:48:05 -05001464 if (!wroteInterfaceBlock && fProgram.fInputs.fRTHeight) {
Timothy Liang7d637782018-06-05 09:58:07 -04001465 this->writeLine("struct sksl_synthetic_uniforms {");
1466 this->writeLine(" float u_skRTHeight;");
1467 this->writeLine("};");
1468 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001469}
1470
John Stilescdcdb042020-07-06 09:03:51 -04001471void MetalCodeGenerator::visitGlobalStruct(GlobalStructVisitor* visitor) {
1472 // Visit the interface blocks.
1473 for (const auto& [interfaceType, interfaceName] : fInterfaceBlockNameMap) {
1474 visitor->VisitInterfaceBlock(*interfaceType, interfaceName);
1475 }
1476 for (const ProgramElement& element : fProgram) {
1477 if (element.fKind != ProgramElement::kVar_Kind) {
1478 continue;
Timothy Liang7d637782018-06-05 09:58:07 -04001479 }
John Stilescdcdb042020-07-06 09:03:51 -04001480 const VarDeclarations& decls = static_cast<const VarDeclarations&>(element);
1481 if (decls.fVars.empty()) {
1482 continue;
1483 }
1484 const Variable& first = *((VarDeclaration&) *decls.fVars[0]).fVar;
1485 if ((!first.fModifiers.fFlags && -1 == first.fModifiers.fLayout.fBuiltin) ||
1486 first.fType.kind() == Type::kSampler_Kind) {
1487 for (const auto& stmt : decls.fVars) {
1488 VarDeclaration& var = static_cast<VarDeclaration&>(*stmt);
John Stilesc67b3622020-05-28 17:53:13 -04001489
John Stilescdcdb042020-07-06 09:03:51 -04001490 if (var.fVar->fType.kind() == Type::kSampler_Kind) {
1491 // Samplers are represented as a "texture/sampler" duo in the global struct.
1492 visitor->VisitTexture(first.fType, var.fVar->fName);
1493 visitor->VisitSampler(first.fType, String(var.fVar->fName) + SAMPLER_SUFFIX);
1494 } else {
1495 // Visit a regular variable.
1496 visitor->VisitVariable(*var.fVar, var.fValue.get());
Timothy Liangee84fe12018-05-18 14:38:19 -04001497 }
Timothy Liangee84fe12018-05-18 14:38:19 -04001498 }
1499 }
1500 }
John Stilescdcdb042020-07-06 09:03:51 -04001501}
1502
1503void MetalCodeGenerator::writeGlobalStruct() {
1504 class : public GlobalStructVisitor {
1505 public:
1506 void VisitInterfaceBlock(const InterfaceBlock& block, const String& blockName) override {
1507 this->AddElement();
1508 fCodeGen->write(" constant ");
1509 fCodeGen->write(block.fTypeName);
1510 fCodeGen->write("* ");
1511 fCodeGen->writeName(blockName);
1512 fCodeGen->write(";\n");
1513 }
1514 void VisitTexture(const Type& type, const String& name) override {
1515 this->AddElement();
1516 fCodeGen->write(" ");
1517 fCodeGen->writeType(type);
1518 fCodeGen->write(" ");
1519 fCodeGen->writeName(name);
1520 fCodeGen->write(";\n");
1521 }
1522 void VisitSampler(const Type&, const String& name) override {
1523 this->AddElement();
1524 fCodeGen->write(" sampler ");
1525 fCodeGen->writeName(name);
1526 fCodeGen->write(";\n");
1527 }
1528 void VisitVariable(const Variable& var, const Expression* value) override {
1529 this->AddElement();
1530 fCodeGen->write(" ");
1531 fCodeGen->writeType(var.fType);
1532 fCodeGen->write(" ");
1533 fCodeGen->writeName(var.fName);
1534 fCodeGen->write(";\n");
1535 }
1536 void AddElement() {
1537 if (fFirst) {
1538 fCodeGen->write("struct Globals {\n");
1539 fFirst = false;
1540 }
1541 }
1542 void Finish() {
1543 if (!fFirst) {
1544 fCodeGen->write("};");
1545 fFirst = true;
1546 }
1547 }
1548
1549 MetalCodeGenerator* fCodeGen = nullptr;
1550 bool fFirst = true;
1551 } visitor;
1552
1553 visitor.fCodeGen = this;
1554 this->visitGlobalStruct(&visitor);
1555 visitor.Finish();
1556}
1557
1558void MetalCodeGenerator::writeGlobalInit() {
1559 class : public GlobalStructVisitor {
1560 public:
1561 void VisitInterfaceBlock(const InterfaceBlock& blockType,
1562 const String& blockName) override {
1563 this->AddElement();
1564 fCodeGen->write("&");
1565 fCodeGen->writeName(blockName);
1566 }
1567 void VisitTexture(const Type&, const String& name) override {
1568 this->AddElement();
1569 fCodeGen->writeName(name);
1570 }
1571 void VisitSampler(const Type&, const String& name) override {
1572 this->AddElement();
1573 fCodeGen->writeName(name);
1574 }
1575 void VisitVariable(const Variable& var, const Expression* value) override {
1576 this->AddElement();
1577 if (value) {
1578 fCodeGen->writeVarInitializer(var, *value);
1579 } else {
1580 fCodeGen->write("{}");
1581 }
1582 }
1583 void AddElement() {
1584 if (fFirst) {
1585 fCodeGen->write(" Globals globalStruct{");
1586 fFirst = false;
1587 } else {
1588 fCodeGen->write(", ");
1589 }
1590 }
1591 void Finish() {
1592 if (!fFirst) {
1593 fCodeGen->writeLine("};");
1594 fCodeGen->writeLine(" thread Globals* _globals = &globalStruct;");
1595 fCodeGen->writeLine(" (void)_globals;");
1596 }
1597 }
1598 MetalCodeGenerator* fCodeGen = nullptr;
1599 bool fFirst = true;
1600 } visitor;
1601
1602 visitor.fCodeGen = this;
1603 this->visitGlobalStruct(&visitor);
1604 visitor.Finish();
Timothy Liangee84fe12018-05-18 14:38:19 -04001605}
1606
Ethan Nicholascc305772017-10-13 16:17:45 -04001607void MetalCodeGenerator::writeProgramElement(const ProgramElement& e) {
1608 switch (e.fKind) {
1609 case ProgramElement::kExtension_Kind:
1610 break;
1611 case ProgramElement::kVar_Kind: {
1612 VarDeclarations& decl = (VarDeclarations&) e;
1613 if (decl.fVars.size() > 0) {
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001614 int builtin = ((VarDeclaration&) *decl.fVars[0]).fVar->fModifiers.fLayout.fBuiltin;
Ethan Nicholascc305772017-10-13 16:17:45 -04001615 if (-1 == builtin) {
1616 // normal var
1617 this->writeVarDeclarations(decl, true);
1618 this->writeLine();
1619 } else if (SK_FRAGCOLOR_BUILTIN == builtin) {
1620 // ignore
1621 }
1622 }
1623 break;
1624 }
1625 case ProgramElement::kInterfaceBlock_Kind:
Timothy Liang7d637782018-06-05 09:58:07 -04001626 // handled in writeInterfaceBlocks, do nothing
Ethan Nicholascc305772017-10-13 16:17:45 -04001627 break;
1628 case ProgramElement::kFunction_Kind:
1629 this->writeFunction((FunctionDefinition&) e);
1630 break;
1631 case ProgramElement::kModifiers_Kind:
1632 this->writeModifiers(((ModifiersDeclaration&) e).fModifiers, true);
1633 this->writeLine(";");
1634 break;
1635 default:
Ethan Nicholas2a099da2020-01-02 14:40:54 -05001636#ifdef SK_DEBUG
1637 ABORT("unsupported program element: %s\n", e.description().c_str());
1638#endif
1639 break;
Ethan Nicholascc305772017-10-13 16:17:45 -04001640 }
1641}
1642
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001643MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const Expression* e) {
1644 if (!e) {
1645 return kNo_Requirements;
1646 }
1647 switch (e->fKind) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001648 case Expression::kFunctionCall_Kind: {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001649 const FunctionCall& f = (const FunctionCall&) *e;
Ethan Nicholascc305772017-10-13 16:17:45 -04001650 Requirements result = this->requirements(f.fFunction);
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001651 for (const auto& arg : f.fArguments) {
1652 result |= this->requirements(arg.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001653 }
1654 return result;
1655 }
1656 case Expression::kConstructor_Kind: {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001657 const Constructor& c = (const Constructor&) *e;
Ethan Nicholascc305772017-10-13 16:17:45 -04001658 Requirements result = kNo_Requirements;
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001659 for (const auto& arg : c.fArguments) {
1660 result |= this->requirements(arg.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001661 }
1662 return result;
1663 }
Timothy Liang7d637782018-06-05 09:58:07 -04001664 case Expression::kFieldAccess_Kind: {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001665 const FieldAccess& f = (const FieldAccess&) *e;
Timothy Liang7d637782018-06-05 09:58:07 -04001666 if (FieldAccess::kAnonymousInterfaceBlock_OwnerKind == f.fOwnerKind) {
1667 return kGlobals_Requirement;
1668 }
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001669 return this->requirements(f.fBase.get());
Timothy Liang7d637782018-06-05 09:58:07 -04001670 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001671 case Expression::kSwizzle_Kind:
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001672 return this->requirements(((const Swizzle&) *e).fBase.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001673 case Expression::kBinary_Kind: {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001674 const BinaryExpression& b = (const BinaryExpression&) *e;
1675 return this->requirements(b.fLeft.get()) | this->requirements(b.fRight.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001676 }
1677 case Expression::kIndex_Kind: {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001678 const IndexExpression& idx = (const IndexExpression&) *e;
1679 return this->requirements(idx.fBase.get()) | this->requirements(idx.fIndex.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001680 }
1681 case Expression::kPrefix_Kind:
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001682 return this->requirements(((const PrefixExpression&) *e).fOperand.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001683 case Expression::kPostfix_Kind:
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001684 return this->requirements(((const PostfixExpression&) *e).fOperand.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001685 case Expression::kTernary_Kind: {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001686 const TernaryExpression& t = (const TernaryExpression&) *e;
1687 return this->requirements(t.fTest.get()) | this->requirements(t.fIfTrue.get()) |
1688 this->requirements(t.fIfFalse.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001689 }
1690 case Expression::kVariableReference_Kind: {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001691 const VariableReference& v = (const VariableReference&) *e;
Ethan Nicholascc305772017-10-13 16:17:45 -04001692 Requirements result = kNo_Requirements;
1693 if (v.fVariable.fModifiers.fLayout.fBuiltin == SK_FRAGCOORD_BUILTIN) {
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -04001694 result = kGlobals_Requirement | kFragCoord_Requirement;
Ethan Nicholascc305772017-10-13 16:17:45 -04001695 } else if (Variable::kGlobal_Storage == v.fVariable.fStorage) {
1696 if (v.fVariable.fModifiers.fFlags & Modifiers::kIn_Flag) {
1697 result = kInputs_Requirement;
1698 } else if (v.fVariable.fModifiers.fFlags & Modifiers::kOut_Flag) {
1699 result = kOutputs_Requirement;
Timothy Lianga06f2152018-05-24 15:33:31 -04001700 } else if (v.fVariable.fModifiers.fFlags & Modifiers::kUniform_Flag &&
1701 v.fVariable.fType.kind() != Type::kSampler_Kind) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001702 result = kUniforms_Requirement;
Timothy Liangee84fe12018-05-18 14:38:19 -04001703 } else {
1704 result = kGlobals_Requirement;
Ethan Nicholascc305772017-10-13 16:17:45 -04001705 }
1706 }
1707 return result;
1708 }
1709 default:
1710 return kNo_Requirements;
1711 }
1712}
1713
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001714MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const Statement* s) {
1715 if (!s) {
1716 return kNo_Requirements;
1717 }
1718 switch (s->fKind) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001719 case Statement::kBlock_Kind: {
1720 Requirements result = kNo_Requirements;
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001721 for (const auto& child : ((const Block*) s)->fStatements) {
1722 result |= this->requirements(child.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001723 }
1724 return result;
1725 }
Timothy Liang7d637782018-06-05 09:58:07 -04001726 case Statement::kVarDeclaration_Kind: {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001727 const VarDeclaration& var = (const VarDeclaration&) *s;
1728 return this->requirements(var.fValue.get());
Timothy Liang7d637782018-06-05 09:58:07 -04001729 }
1730 case Statement::kVarDeclarations_Kind: {
1731 Requirements result = kNo_Requirements;
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001732 const VarDeclarations& decls = *((const VarDeclarationsStatement&) *s).fDeclaration;
Timothy Liang7d637782018-06-05 09:58:07 -04001733 for (const auto& stmt : decls.fVars) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001734 result |= this->requirements(stmt.get());
Timothy Liang7d637782018-06-05 09:58:07 -04001735 }
1736 return result;
1737 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001738 case Statement::kExpression_Kind:
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001739 return this->requirements(((const ExpressionStatement&) *s).fExpression.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001740 case Statement::kReturn_Kind: {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001741 const ReturnStatement& r = (const ReturnStatement&) *s;
1742 return this->requirements(r.fExpression.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001743 }
1744 case Statement::kIf_Kind: {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001745 const IfStatement& i = (const IfStatement&) *s;
1746 return this->requirements(i.fTest.get()) |
1747 this->requirements(i.fIfTrue.get()) |
1748 this->requirements(i.fIfFalse.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001749 }
1750 case Statement::kFor_Kind: {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001751 const ForStatement& f = (const ForStatement&) *s;
1752 return this->requirements(f.fInitializer.get()) |
1753 this->requirements(f.fTest.get()) |
1754 this->requirements(f.fNext.get()) |
1755 this->requirements(f.fStatement.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001756 }
1757 case Statement::kWhile_Kind: {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001758 const WhileStatement& w = (const WhileStatement&) *s;
1759 return this->requirements(w.fTest.get()) |
1760 this->requirements(w.fStatement.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001761 }
1762 case Statement::kDo_Kind: {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001763 const DoStatement& d = (const DoStatement&) *s;
1764 return this->requirements(d.fTest.get()) |
1765 this->requirements(d.fStatement.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001766 }
1767 case Statement::kSwitch_Kind: {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001768 const SwitchStatement& sw = (const SwitchStatement&) *s;
1769 Requirements result = this->requirements(sw.fValue.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001770 for (const auto& c : sw.fCases) {
1771 for (const auto& st : c->fStatements) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001772 result |= this->requirements(st.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001773 }
1774 }
1775 return result;
1776 }
1777 default:
1778 return kNo_Requirements;
1779 }
1780}
1781
1782MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const FunctionDeclaration& f) {
1783 if (f.fBuiltin) {
1784 return kNo_Requirements;
1785 }
1786 auto found = fRequirements.find(&f);
1787 if (found == fRequirements.end()) {
Ethan Nicholas65a8f562019-04-19 14:00:26 -04001788 fRequirements[&f] = kNo_Requirements;
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001789 for (const auto& e : fProgram) {
1790 if (ProgramElement::kFunction_Kind == e.fKind) {
1791 const FunctionDefinition& def = (const FunctionDefinition&) e;
Ethan Nicholascc305772017-10-13 16:17:45 -04001792 if (&def.fDeclaration == &f) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001793 Requirements reqs = this->requirements(def.fBody.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001794 fRequirements[&f] = reqs;
1795 return reqs;
1796 }
1797 }
1798 }
1799 }
1800 return found->second;
1801}
1802
Timothy Liangb8eeb802018-07-23 16:46:16 -04001803bool MetalCodeGenerator::generateCode() {
Ethan Nicholascc305772017-10-13 16:17:45 -04001804 OutputStream* rawOut = fOut;
1805 fOut = &fHeader;
1806 fProgramKind = fProgram.fKind;
1807 this->writeHeader();
1808 this->writeUniformStruct();
1809 this->writeInputStruct();
Timothy Liang7d637782018-06-05 09:58:07 -04001810 this->writeOutputStruct();
1811 this->writeInterfaceBlocks();
Timothy Liangee84fe12018-05-18 14:38:19 -04001812 this->writeGlobalStruct();
Ethan Nicholascc305772017-10-13 16:17:45 -04001813 StringStream body;
1814 fOut = &body;
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001815 for (const auto& e : fProgram) {
1816 this->writeProgramElement(e);
Ethan Nicholascc305772017-10-13 16:17:45 -04001817 }
1818 fOut = rawOut;
1819
1820 write_stringstream(fHeader, *rawOut);
Chris Daltondba7aab2018-11-15 10:57:49 -05001821 write_stringstream(fExtraFunctions, *rawOut);
Ethan Nicholascc305772017-10-13 16:17:45 -04001822 write_stringstream(body, *rawOut);
Ethan Nicholascc305772017-10-13 16:17:45 -04001823 return true;
Ethan Nicholascc305772017-10-13 16:17:45 -04001824}
1825
John Stilesa6841be2020-08-06 14:11:56 -04001826} // namespace SkSL