blob: 4b625a310fd155cb9dbfbc466d61798eb32a9c2f [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
Timothy Liangb8eeb802018-07-23 16:46:16 -040018#ifdef SK_MOLTENVK
19 static const uint32_t MVKMagicNum = 0x19960412;
20#endif
Timothy Lianga06f2152018-05-24 15:33:31 -040021
Ethan Nicholascc305772017-10-13 16:17:45 -040022namespace SkSL {
23
Timothy Liangee84fe12018-05-18 14:38:19 -040024void MetalCodeGenerator::setupIntrinsics() {
Timothy Liang7d637782018-06-05 09:58:07 -040025#define METAL(x) std::make_pair(kMetal_IntrinsicKind, k ## x ## _MetalIntrinsic)
26#define SPECIAL(x) std::make_pair(kSpecial_IntrinsicKind, k ## x ## _SpecialIntrinsic)
Timothy Lianga06f2152018-05-24 15:33:31 -040027 fIntrinsicMap[String("texture")] = SPECIAL(Texture);
Timothy Liang651286f2018-06-07 09:55:33 -040028 fIntrinsicMap[String("mod")] = SPECIAL(Mod);
Ethan Nicholas0dc80872019-02-08 15:46:24 -050029 fIntrinsicMap[String("equal")] = METAL(Equal);
30 fIntrinsicMap[String("notEqual")] = METAL(NotEqual);
Timothy Lianga06f2152018-05-24 15:33:31 -040031 fIntrinsicMap[String("lessThan")] = METAL(LessThan);
32 fIntrinsicMap[String("lessThanEqual")] = METAL(LessThanEqual);
33 fIntrinsicMap[String("greaterThan")] = METAL(GreaterThan);
34 fIntrinsicMap[String("greaterThanEqual")] = METAL(GreaterThanEqual);
Timothy Liangee84fe12018-05-18 14:38:19 -040035}
36
Ethan Nicholascc305772017-10-13 16:17:45 -040037void MetalCodeGenerator::write(const char* s) {
38 if (!s[0]) {
39 return;
40 }
41 if (fAtLineStart) {
42 for (int i = 0; i < fIndentation; i++) {
43 fOut->writeText(" ");
44 }
45 }
46 fOut->writeText(s);
47 fAtLineStart = false;
48}
49
50void MetalCodeGenerator::writeLine(const char* s) {
51 this->write(s);
52 fOut->writeText(fLineEnding);
53 fAtLineStart = true;
54}
55
56void MetalCodeGenerator::write(const String& s) {
57 this->write(s.c_str());
58}
59
60void MetalCodeGenerator::writeLine(const String& s) {
61 this->writeLine(s.c_str());
62}
63
64void MetalCodeGenerator::writeLine() {
65 this->writeLine("");
66}
67
68void MetalCodeGenerator::writeExtension(const Extension& ext) {
69 this->writeLine("#extension " + ext.fName + " : enable");
70}
71
72void MetalCodeGenerator::writeType(const Type& type) {
73 switch (type.kind()) {
74 case Type::kStruct_Kind:
75 for (const Type* search : fWrittenStructs) {
76 if (*search == type) {
77 // already written
78 this->write(type.name());
79 return;
80 }
81 }
82 fWrittenStructs.push_back(&type);
83 this->writeLine("struct " + type.name() + " {");
84 fIndentation++;
Timothy Liangdc89f192018-06-13 09:20:31 -040085 this->writeFields(type.fields(), type.fOffset);
Ethan Nicholascc305772017-10-13 16:17:45 -040086 fIndentation--;
87 this->write("}");
88 break;
89 case Type::kVector_Kind:
90 this->writeType(type.componentType());
91 this->write(to_string(type.columns()));
92 break;
Timothy Liang43d225f2018-07-19 15:27:13 -040093 case Type::kMatrix_Kind:
94 this->writeType(type.componentType());
95 this->write(to_string(type.columns()));
96 this->write("x");
97 this->write(to_string(type.rows()));
98 break;
Timothy Liangee84fe12018-05-18 14:38:19 -040099 case Type::kSampler_Kind:
Timothy Liang43d225f2018-07-19 15:27:13 -0400100 this->write("texture2d<float> "); // FIXME - support other texture types;
Timothy Liangee84fe12018-05-18 14:38:19 -0400101 break;
Ethan Nicholascc305772017-10-13 16:17:45 -0400102 default:
Timothy Liang43d225f2018-07-19 15:27:13 -0400103 if (type == *fContext.fHalf_Type) {
104 // FIXME - Currently only supporting floats in MSL to avoid type coercion issues.
105 this->write(fContext.fFloat_Type->name());
106 } else if (type == *fContext.fByte_Type) {
107 this->write("char");
108 } else if (type == *fContext.fUByte_Type) {
109 this->write("uchar");
Timothy Liang7d637782018-06-05 09:58:07 -0400110 } else {
111 this->write(type.name());
112 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400113 }
114}
115
116void MetalCodeGenerator::writeExpression(const Expression& expr, Precedence parentPrecedence) {
117 switch (expr.fKind) {
118 case Expression::kBinary_Kind:
119 this->writeBinaryExpression((BinaryExpression&) expr, parentPrecedence);
120 break;
121 case Expression::kBoolLiteral_Kind:
122 this->writeBoolLiteral((BoolLiteral&) expr);
123 break;
124 case Expression::kConstructor_Kind:
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500125 this->writeConstructor((Constructor&) expr, parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400126 break;
127 case Expression::kIntLiteral_Kind:
128 this->writeIntLiteral((IntLiteral&) expr);
129 break;
130 case Expression::kFieldAccess_Kind:
131 this->writeFieldAccess(((FieldAccess&) expr));
132 break;
133 case Expression::kFloatLiteral_Kind:
134 this->writeFloatLiteral(((FloatLiteral&) expr));
135 break;
136 case Expression::kFunctionCall_Kind:
137 this->writeFunctionCall((FunctionCall&) expr);
138 break;
139 case Expression::kPrefix_Kind:
140 this->writePrefixExpression((PrefixExpression&) expr, parentPrecedence);
141 break;
142 case Expression::kPostfix_Kind:
143 this->writePostfixExpression((PostfixExpression&) expr, parentPrecedence);
144 break;
145 case Expression::kSetting_Kind:
146 this->writeSetting((Setting&) expr);
147 break;
148 case Expression::kSwizzle_Kind:
149 this->writeSwizzle((Swizzle&) expr);
150 break;
151 case Expression::kVariableReference_Kind:
152 this->writeVariableReference((VariableReference&) expr);
153 break;
154 case Expression::kTernary_Kind:
155 this->writeTernaryExpression((TernaryExpression&) expr, parentPrecedence);
156 break;
157 case Expression::kIndex_Kind:
158 this->writeIndexExpression((IndexExpression&) expr);
159 break;
160 default:
161 ABORT("unsupported expression: %s", expr.description().c_str());
162 }
163}
164
Timothy Liang6403b0e2018-05-17 10:40:04 -0400165void MetalCodeGenerator::writeIntrinsicCall(const FunctionCall& c) {
Timothy Liang7d637782018-06-05 09:58:07 -0400166 auto i = fIntrinsicMap.find(c.fFunction.fName);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400167 SkASSERT(i != fIntrinsicMap.end());
Timothy Liang7d637782018-06-05 09:58:07 -0400168 Intrinsic intrinsic = i->second;
169 int32_t intrinsicId = intrinsic.second;
170 switch (intrinsic.first) {
Timothy Liang6403b0e2018-05-17 10:40:04 -0400171 case kSpecial_IntrinsicKind:
172 return this->writeSpecialIntrinsic(c, (SpecialIntrinsic) intrinsicId);
Timothy Lianga06f2152018-05-24 15:33:31 -0400173 break;
174 case kMetal_IntrinsicKind:
175 this->writeExpression(*c.fArguments[0], kSequence_Precedence);
176 switch ((MetalIntrinsic) intrinsicId) {
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500177 case kEqual_MetalIntrinsic:
178 this->write(" == ");
179 break;
180 case kNotEqual_MetalIntrinsic:
181 this->write(" != ");
182 break;
Timothy Lianga06f2152018-05-24 15:33:31 -0400183 case kLessThan_MetalIntrinsic:
184 this->write(" < ");
185 break;
186 case kLessThanEqual_MetalIntrinsic:
187 this->write(" <= ");
188 break;
189 case kGreaterThan_MetalIntrinsic:
190 this->write(" > ");
191 break;
192 case kGreaterThanEqual_MetalIntrinsic:
193 this->write(" >= ");
194 break;
195 default:
196 ABORT("unsupported metal intrinsic kind");
197 }
198 this->writeExpression(*c.fArguments[1], kSequence_Precedence);
199 break;
Timothy Liang6403b0e2018-05-17 10:40:04 -0400200 default:
201 ABORT("unsupported intrinsic kind");
202 }
203}
204
Ethan Nicholascc305772017-10-13 16:17:45 -0400205void MetalCodeGenerator::writeFunctionCall(const FunctionCall& c) {
Timothy Liang6403b0e2018-05-17 10:40:04 -0400206 const auto& entry = fIntrinsicMap.find(c.fFunction.fName);
207 if (entry != fIntrinsicMap.end()) {
208 this->writeIntrinsicCall(c);
209 return;
210 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400211 if (c.fFunction.fBuiltin && "atan" == c.fFunction.fName && 2 == c.fArguments.size()) {
212 this->write("atan2");
Timothy Lianga06f2152018-05-24 15:33:31 -0400213 } else if (c.fFunction.fBuiltin && "inversesqrt" == c.fFunction.fName) {
214 this->write("rsqrt");
Chris Daltondba7aab2018-11-15 10:57:49 -0500215 } else if (c.fFunction.fBuiltin && "inverse" == c.fFunction.fName) {
216 SkASSERT(c.fArguments.size() == 1);
217 this->writeInverseHack(*c.fArguments[0]);
Timothy Liang7d637782018-06-05 09:58:07 -0400218 } else if (c.fFunction.fBuiltin && "dFdx" == c.fFunction.fName) {
219 this->write("dfdx");
220 } else if (c.fFunction.fBuiltin && "dFdy" == c.fFunction.fName) {
Chris Daltonb8af5ad2019-02-25 14:54:21 -0700221 // Flipping Y also negates the Y derivatives.
222 this->write((fProgram.fSettings.fFlipY) ? "-dfdy" : "dfdy");
Ethan Nicholascc305772017-10-13 16:17:45 -0400223 } else {
Timothy Liang651286f2018-06-07 09:55:33 -0400224 this->writeName(c.fFunction.fName);
Ethan Nicholascc305772017-10-13 16:17:45 -0400225 }
226 this->write("(");
227 const char* separator = "";
228 if (this->requirements(c.fFunction) & kInputs_Requirement) {
229 this->write("_in");
230 separator = ", ";
231 }
232 if (this->requirements(c.fFunction) & kOutputs_Requirement) {
233 this->write(separator);
234 this->write("_out");
235 separator = ", ";
236 }
237 if (this->requirements(c.fFunction) & kUniforms_Requirement) {
238 this->write(separator);
239 this->write("_uniforms");
240 separator = ", ";
241 }
Timothy Liangee84fe12018-05-18 14:38:19 -0400242 if (this->requirements(c.fFunction) & kGlobals_Requirement) {
243 this->write(separator);
244 this->write("_globals");
245 separator = ", ";
246 }
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -0400247 if (this->requirements(c.fFunction) & kFragCoord_Requirement) {
248 this->write(separator);
249 this->write("_fragCoord");
250 separator = ", ";
251 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400252 for (size_t i = 0; i < c.fArguments.size(); ++i) {
253 const Expression& arg = *c.fArguments[i];
254 this->write(separator);
255 separator = ", ";
256 if (c.fFunction.fParameters[i]->fModifiers.fFlags & Modifiers::kOut_Flag) {
257 this->write("&");
258 }
259 this->writeExpression(arg, kSequence_Precedence);
260 }
261 this->write(")");
262}
263
Chris Daltondba7aab2018-11-15 10:57:49 -0500264void MetalCodeGenerator::writeInverseHack(const Expression& mat) {
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500265 String typeName = mat.fType.name();
266 String name = typeName + "_inverse";
267 if (mat.fType == *fContext.fFloat2x2_Type || mat.fType == *fContext.fHalf2x2_Type) {
Chris Daltondba7aab2018-11-15 10:57:49 -0500268 if (fWrittenIntrinsics.find(name) == fWrittenIntrinsics.end()) {
269 fWrittenIntrinsics.insert(name);
270 fExtraFunctions.writeText((
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500271 typeName + " " + name + "(" + typeName + " m) {"
Chris Daltondba7aab2018-11-15 10:57:49 -0500272 " return float2x2(m[1][1], -m[0][1], -m[1][0], m[0][0]) * (1/determinant(m));"
273 "}"
274 ).c_str());
275 }
276 }
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500277 else if (mat.fType == *fContext.fFloat3x3_Type || mat.fType == *fContext.fHalf3x3_Type) {
278 if (fWrittenIntrinsics.find(name) == fWrittenIntrinsics.end()) {
279 fWrittenIntrinsics.insert(name);
280 fExtraFunctions.writeText((
281 typeName + " " + name + "(" + typeName + " m) {"
282 " float a00 = m[0][0], a01 = m[0][1], a02 = m[0][2];"
283 " float a10 = m[1][0], a11 = m[1][1], a12 = m[1][2];"
284 " float a20 = m[2][0], a21 = m[2][1], a22 = m[2][2];"
285 " float b01 = a22 * a11 - a12 * a21;"
286 " float b11 = -a22 * a10 + a12 * a20;"
287 " float b21 = a21 * a10 - a11 * a20;"
288 " float det = a00 * b01 + a01 * b11 + a02 * b21;"
289 " return " + typeName +
290 " (b01, (-a22 * a01 + a02 * a21), (a12 * a01 - a02 * a11),"
291 " b11, (a22 * a00 - a02 * a20), (-a12 * a00 + a02 * a10),"
292 " b21, (-a21 * a00 + a01 * a20), (a11 * a00 - a01 * a10)) * "
293 " (1/det);"
294 "}"
295 ).c_str());
296 }
297 }
298 else if (mat.fType == *fContext.fFloat4x4_Type || mat.fType == *fContext.fHalf4x4_Type) {
299 if (fWrittenIntrinsics.find(name) == fWrittenIntrinsics.end()) {
300 fWrittenIntrinsics.insert(name);
301 fExtraFunctions.writeText((
302 typeName + " " + name + "(" + typeName + " m) {"
303 " float a00 = m[0][0], a01 = m[0][1], a02 = m[0][2], a03 = m[0][3];"
304 " float a10 = m[1][0], a11 = m[1][1], a12 = m[1][2], a13 = m[1][3];"
305 " float a20 = m[2][0], a21 = m[2][1], a22 = m[2][2], a23 = m[2][3];"
306 " float a30 = m[3][0], a31 = m[3][1], a32 = m[3][2], a33 = m[3][3];"
307 " float b00 = a00 * a11 - a01 * a10;"
308 " float b01 = a00 * a12 - a02 * a10;"
309 " float b02 = a00 * a13 - a03 * a10;"
310 " float b03 = a01 * a12 - a02 * a11;"
311 " float b04 = a01 * a13 - a03 * a11;"
312 " float b05 = a02 * a13 - a03 * a12;"
313 " float b06 = a20 * a31 - a21 * a30;"
314 " float b07 = a20 * a32 - a22 * a30;"
315 " float b08 = a20 * a33 - a23 * a30;"
316 " float b09 = a21 * a32 - a22 * a31;"
317 " float b10 = a21 * a33 - a23 * a31;"
318 " float b11 = a22 * a33 - a23 * a32;"
319 " float det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - "
320 " b04 * b07 + b05 * b06;"
321 " return " + typeName + "(a11 * b11 - a12 * b10 + a13 * b09,"
322 " a02 * b10 - a01 * b11 - a03 * b09,"
323 " a31 * b05 - a32 * b04 + a33 * b03,"
324 " a22 * b04 - a21 * b05 - a23 * b03,"
325 " a12 * b08 - a10 * b11 - a13 * b07,"
326 " a00 * b11 - a02 * b08 + a03 * b07,"
327 " a32 * b02 - a30 * b05 - a33 * b01,"
328 " a20 * b05 - a22 * b02 + a23 * b01,"
329 " a10 * b10 - a11 * b08 + a13 * b06,"
330 " a01 * b08 - a00 * b10 - a03 * b06,"
331 " a30 * b04 - a31 * b02 + a33 * b00,"
332 " a21 * b02 - a20 * b04 - a23 * b00,"
333 " a11 * b07 - a10 * b09 - a12 * b06,"
334 " a00 * b09 - a01 * b07 + a02 * b06,"
335 " a31 * b01 - a30 * b03 - a32 * b00,"
336 " a20 * b03 - a21 * b01 + a22 * b00) / det;"
337 "}"
338 ).c_str());
339 }
340 }
Chris Daltondba7aab2018-11-15 10:57:49 -0500341 this->write(name);
342}
343
Timothy Liang6403b0e2018-05-17 10:40:04 -0400344void MetalCodeGenerator::writeSpecialIntrinsic(const FunctionCall & c, SpecialIntrinsic kind) {
345 switch (kind) {
346 case kTexture_SpecialIntrinsic:
Timothy Liangee84fe12018-05-18 14:38:19 -0400347 this->writeExpression(*c.fArguments[0], kSequence_Precedence);
Timothy Lianga06f2152018-05-24 15:33:31 -0400348 this->write(".sample(");
349 this->writeExpression(*c.fArguments[0], kSequence_Precedence);
350 this->write(SAMPLER_SUFFIX);
351 this->write(", ");
Timothy Liang6403b0e2018-05-17 10:40:04 -0400352 this->writeExpression(*c.fArguments[1], kSequence_Precedence);
Timothy Liangee84fe12018-05-18 14:38:19 -0400353 if (c.fArguments[1]->fType == *fContext.fFloat3_Type) {
354 this->write(".xy)"); // FIXME - add projection functionality
355 } else {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400356 SkASSERT(c.fArguments[1]->fType == *fContext.fFloat2_Type);
Timothy Liangee84fe12018-05-18 14:38:19 -0400357 this->write(")");
358 }
Timothy Liang6403b0e2018-05-17 10:40:04 -0400359 break;
Timothy Liang651286f2018-06-07 09:55:33 -0400360 case kMod_SpecialIntrinsic:
361 // fmod(x, y) in metal calculates x - y * trunc(x / y) instead of x - y * floor(x / y)
362 this->write("((");
363 this->writeExpression(*c.fArguments[0], kSequence_Precedence);
364 this->write(") - (");
365 this->writeExpression(*c.fArguments[1], kSequence_Precedence);
366 this->write(") * floor((");
367 this->writeExpression(*c.fArguments[0], kSequence_Precedence);
368 this->write(") / (");
369 this->writeExpression(*c.fArguments[1], kSequence_Precedence);
370 this->write(")))");
371 break;
Timothy Liang6403b0e2018-05-17 10:40:04 -0400372 default:
373 ABORT("unsupported special intrinsic kind");
374 }
375}
376
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500377// If it hasn't already been written, writes a constructor for 'matrix' which takes a single value
378// of type 'arg'.
379String MetalCodeGenerator::getMatrixConstructHelper(const Type& matrix, const Type& arg) {
380 String key = matrix.name() + arg.name();
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500381 auto found = fHelpers.find(key);
382 if (found != fHelpers.end()) {
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500383 return found->second;
Ethan Nicholascc305772017-10-13 16:17:45 -0400384 }
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500385 String name;
386 int columns = matrix.columns();
387 int rows = matrix.rows();
388 if (arg.isNumber()) {
389 // creating a matrix from a single scalar value
390 name = "float" + to_string(columns) + "x" + to_string(rows) + "_from_float";
391 fExtraFunctions.printf("float%dx%d %s(float x) {\n",
392 columns, rows, name.c_str());
393 fExtraFunctions.printf(" return float%dx%d(", columns, rows);
394 for (int i = 0; i < columns; ++i) {
395 if (i > 0) {
396 fExtraFunctions.writeText(", ");
397 }
398 fExtraFunctions.printf("float%d(", rows);
399 for (int j = 0; j < rows; ++j) {
400 if (j > 0) {
401 fExtraFunctions.writeText(", ");
402 }
403 if (i == j) {
404 fExtraFunctions.writeText("x");
405 } else {
406 fExtraFunctions.writeText("0");
407 }
408 }
409 fExtraFunctions.writeText(")");
410 }
411 fExtraFunctions.writeText(");\n}\n");
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500412 } else if (arg.kind() == Type::kMatrix_Kind) {
413 // creating a matrix from another matrix
414 int argColumns = arg.columns();
415 int argRows = arg.rows();
416 name = "float" + to_string(columns) + "x" + to_string(rows) + "_from_float" +
417 to_string(argColumns) + "x" + to_string(argRows);
418 fExtraFunctions.printf("float%dx%d %s(float%dx%d m) {\n",
419 columns, rows, name.c_str(), argColumns, argRows);
420 fExtraFunctions.printf(" return float%dx%d(", columns, rows);
421 for (int i = 0; i < columns; ++i) {
422 if (i > 0) {
423 fExtraFunctions.writeText(", ");
424 }
425 fExtraFunctions.printf("float%d(", rows);
426 for (int j = 0; j < rows; ++j) {
427 if (j > 0) {
428 fExtraFunctions.writeText(", ");
429 }
430 if (i < argColumns && j < argRows) {
431 fExtraFunctions.printf("m[%d][%d]", i, j);
432 } else {
433 fExtraFunctions.writeText("0");
434 }
435 }
436 fExtraFunctions.writeText(")");
437 }
438 fExtraFunctions.writeText(");\n}\n");
439 } else if (matrix.rows() == 2 && matrix.columns() == 2 && arg == *fContext.fFloat4_Type) {
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500440 // float2x2(float4) doesn't work, need to split it into float2x2(float2, float2)
441 name = "float2x2_from_float4";
442 fExtraFunctions.printf(
443 "float2x2 %s(float4 v) {\n"
444 " return float2x2(float2(v[0], v[1]), float2(v[2], v[3]));\n"
445 "}\n",
446 name.c_str()
447 );
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500448 } else {
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500449 SkASSERT(false);
450 name = "<error>";
451 }
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500452 fHelpers[key] = name;
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500453 return name;
454}
455
456bool MetalCodeGenerator::canCoerce(const Type& t1, const Type& t2) {
457 if (t1.columns() != t2.columns() || t1.rows() != t2.rows()) {
458 return false;
459 }
460 if (t1.columns() > 1) {
461 return this->canCoerce(t1.componentType(), t2.componentType());
462 }
Ethan Nicholase1f55022019-02-05 17:17:40 -0500463 return t1.isFloat() && t2.isFloat();
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500464}
465
466void MetalCodeGenerator::writeConstructor(const Constructor& c, Precedence parentPrecedence) {
467 if (c.fArguments.size() == 1 && this->canCoerce(c.fType, c.fArguments[0]->fType)) {
468 this->writeExpression(*c.fArguments[0], parentPrecedence);
469 return;
470 }
471 if (c.fType.kind() == Type::kMatrix_Kind && c.fArguments.size() == 1) {
472 const Expression& arg = *c.fArguments[0];
473 String name = this->getMatrixConstructHelper(c.fType, arg.fType);
474 this->write(name);
475 this->write("(");
476 this->writeExpression(arg, kSequence_Precedence);
477 this->write(")");
478 } else {
479 this->writeType(c.fType);
480 this->write("(");
481 const char* separator = "";
482 int scalarCount = 0;
483 for (const auto& arg : c.fArguments) {
484 this->write(separator);
485 separator = ", ";
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500486 if (Type::kMatrix_Kind == c.fType.kind() && arg->fType.columns() != c.fType.rows()) {
487 // merge scalars and smaller vectors together
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500488 if (!scalarCount) {
489 this->writeType(c.fType.componentType());
490 this->write(to_string(c.fType.rows()));
491 this->write("(");
492 }
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500493 scalarCount += arg->fType.columns();
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500494 }
495 this->writeExpression(*arg, kSequence_Precedence);
496 if (scalarCount && scalarCount == c.fType.rows()) {
497 this->write(")");
498 scalarCount = 0;
499 }
500 }
501 this->write(")");
502 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400503}
504
505void MetalCodeGenerator::writeFragCoord() {
Jim Van Verth6bc650e2019-02-07 14:53:23 -0500506 if (fProgram.fInputs.fRTHeight) {
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -0400507 this->write("float4(_fragCoord.x, _globals->_anonInterface0->u_skRTHeight - "
508 "_fragCoord.y, 0.0, _fragCoord.w)");
Jim Van Verth6bc650e2019-02-07 14:53:23 -0500509 } else {
510 this->write("float4(_fragCoord.x, _fragCoord.y, 0.0, _fragCoord.w)");
511 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400512}
513
514void MetalCodeGenerator::writeVariableReference(const VariableReference& ref) {
515 switch (ref.fVariable.fModifiers.fLayout.fBuiltin) {
516 case SK_FRAGCOLOR_BUILTIN:
Timothy Liang7d637782018-06-05 09:58:07 -0400517 this->write("_out->sk_FragColor");
Ethan Nicholascc305772017-10-13 16:17:45 -0400518 break;
Timothy Liang6403b0e2018-05-17 10:40:04 -0400519 case SK_FRAGCOORD_BUILTIN:
520 this->writeFragCoord();
521 break;
Timothy Liangdc89f192018-06-13 09:20:31 -0400522 case SK_VERTEXID_BUILTIN:
523 this->write("sk_VertexID");
524 break;
525 case SK_INSTANCEID_BUILTIN:
526 this->write("sk_InstanceID");
527 break;
Timothy Liang7b8875d2018-08-10 09:42:31 -0400528 case SK_CLOCKWISE_BUILTIN:
529 // We'd set the front facing winding in the MTLRenderCommandEncoder to be counter
530 // clockwise to match Skia convention. This is also the default in MoltenVK.
531 this->write(fProgram.fSettings.fFlipY ? "_frontFacing" : "(!_frontFacing)");
532 break;
Ethan Nicholascc305772017-10-13 16:17:45 -0400533 default:
534 if (Variable::kGlobal_Storage == ref.fVariable.fStorage) {
535 if (ref.fVariable.fModifiers.fFlags & Modifiers::kIn_Flag) {
536 this->write("_in.");
537 } else if (ref.fVariable.fModifiers.fFlags & Modifiers::kOut_Flag) {
Timothy Liangee84fe12018-05-18 14:38:19 -0400538 this->write("_out->");
Timothy Lianga06f2152018-05-24 15:33:31 -0400539 } else if (ref.fVariable.fModifiers.fFlags & Modifiers::kUniform_Flag &&
540 ref.fVariable.fType.kind() != Type::kSampler_Kind) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400541 this->write("_uniforms.");
542 } else {
Timothy Liangee84fe12018-05-18 14:38:19 -0400543 this->write("_globals->");
Ethan Nicholascc305772017-10-13 16:17:45 -0400544 }
545 }
Timothy Liang651286f2018-06-07 09:55:33 -0400546 this->writeName(ref.fVariable.fName);
Ethan Nicholascc305772017-10-13 16:17:45 -0400547 }
548}
549
550void MetalCodeGenerator::writeIndexExpression(const IndexExpression& expr) {
551 this->writeExpression(*expr.fBase, kPostfix_Precedence);
552 this->write("[");
553 this->writeExpression(*expr.fIndex, kTopLevel_Precedence);
554 this->write("]");
555}
556
557void MetalCodeGenerator::writeFieldAccess(const FieldAccess& f) {
Timothy Liang7d637782018-06-05 09:58:07 -0400558 const Type::Field* field = &f.fBase->fType.fields()[f.fFieldIndex];
Ethan Nicholascc305772017-10-13 16:17:45 -0400559 if (FieldAccess::kDefault_OwnerKind == f.fOwnerKind) {
560 this->writeExpression(*f.fBase, kPostfix_Precedence);
561 this->write(".");
562 }
Timothy Liang7d637782018-06-05 09:58:07 -0400563 switch (field->fModifiers.fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400564 case SK_CLIPDISTANCE_BUILTIN:
565 this->write("gl_ClipDistance");
566 break;
567 case SK_POSITION_BUILTIN:
Timothy Liangb8eeb802018-07-23 16:46:16 -0400568 this->write("_out->sk_Position");
Ethan Nicholascc305772017-10-13 16:17:45 -0400569 break;
570 default:
Timothy Liang7d637782018-06-05 09:58:07 -0400571 if (field->fName == "sk_PointSize") {
572 this->write("_out->sk_PointSize");
573 } else {
574 if (FieldAccess::kAnonymousInterfaceBlock_OwnerKind == f.fOwnerKind) {
575 this->write("_globals->");
576 this->write(fInterfaceBlockNameMap[fInterfaceBlockMap[field]]);
577 this->write("->");
578 }
Timothy Liang651286f2018-06-07 09:55:33 -0400579 this->writeName(field->fName);
Timothy Lianga06f2152018-05-24 15:33:31 -0400580 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400581 }
582}
583
584void MetalCodeGenerator::writeSwizzle(const Swizzle& swizzle) {
Ethan Nicholas5476f2e2019-03-07 15:11:31 -0500585 int last = swizzle.fComponents.back();
586 if (last == SKSL_SWIZZLE_0 || last == SKSL_SWIZZLE_1) {
587 this->writeType(swizzle.fType);
588 this->write("(");
589 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400590 this->writeExpression(*swizzle.fBase, kPostfix_Precedence);
591 this->write(".");
592 for (int c : swizzle.fComponents) {
Ethan Nicholas5476f2e2019-03-07 15:11:31 -0500593 if (c >= 0) {
594 this->write(&("x\0y\0z\0w\0"[c * 2]));
595 }
596 }
597 if (last == SKSL_SWIZZLE_0) {
598 this->write(", 0)");
599 }
600 else if (last == SKSL_SWIZZLE_1) {
601 this->write(", 1)");
Ethan Nicholascc305772017-10-13 16:17:45 -0400602 }
603}
604
605MetalCodeGenerator::Precedence MetalCodeGenerator::GetBinaryPrecedence(Token::Kind op) {
606 switch (op) {
607 case Token::STAR: // fall through
608 case Token::SLASH: // fall through
609 case Token::PERCENT: return MetalCodeGenerator::kMultiplicative_Precedence;
610 case Token::PLUS: // fall through
611 case Token::MINUS: return MetalCodeGenerator::kAdditive_Precedence;
612 case Token::SHL: // fall through
613 case Token::SHR: return MetalCodeGenerator::kShift_Precedence;
614 case Token::LT: // fall through
615 case Token::GT: // fall through
616 case Token::LTEQ: // fall through
617 case Token::GTEQ: return MetalCodeGenerator::kRelational_Precedence;
618 case Token::EQEQ: // fall through
619 case Token::NEQ: return MetalCodeGenerator::kEquality_Precedence;
620 case Token::BITWISEAND: return MetalCodeGenerator::kBitwiseAnd_Precedence;
621 case Token::BITWISEXOR: return MetalCodeGenerator::kBitwiseXor_Precedence;
622 case Token::BITWISEOR: return MetalCodeGenerator::kBitwiseOr_Precedence;
623 case Token::LOGICALAND: return MetalCodeGenerator::kLogicalAnd_Precedence;
624 case Token::LOGICALXOR: return MetalCodeGenerator::kLogicalXor_Precedence;
625 case Token::LOGICALOR: return MetalCodeGenerator::kLogicalOr_Precedence;
626 case Token::EQ: // fall through
627 case Token::PLUSEQ: // fall through
628 case Token::MINUSEQ: // fall through
629 case Token::STAREQ: // fall through
630 case Token::SLASHEQ: // fall through
631 case Token::PERCENTEQ: // fall through
632 case Token::SHLEQ: // fall through
633 case Token::SHREQ: // fall through
634 case Token::LOGICALANDEQ: // fall through
635 case Token::LOGICALXOREQ: // fall through
636 case Token::LOGICALOREQ: // fall through
637 case Token::BITWISEANDEQ: // fall through
638 case Token::BITWISEXOREQ: // fall through
639 case Token::BITWISEOREQ: return MetalCodeGenerator::kAssignment_Precedence;
640 case Token::COMMA: return MetalCodeGenerator::kSequence_Precedence;
641 default: ABORT("unsupported binary operator");
642 }
643}
644
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500645void MetalCodeGenerator::writeMatrixTimesEqualHelper(const Type& left, const Type& right,
646 const Type& result) {
647 String key = "TimesEqual" + left.name() + right.name();
648 if (fHelpers.find(key) == fHelpers.end()) {
649 fExtraFunctions.printf("%s operator*=(thread %s& left, thread const %s& right) {\n"
650 " left = left * right;\n"
651 " return left;\n"
652 "}", result.name().c_str(), left.name().c_str(),
653 right.name().c_str());
654 }
655}
656
Ethan Nicholascc305772017-10-13 16:17:45 -0400657void MetalCodeGenerator::writeBinaryExpression(const BinaryExpression& b,
658 Precedence parentPrecedence) {
659 Precedence precedence = GetBinaryPrecedence(b.fOperator);
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500660 bool needParens = precedence >= parentPrecedence;
661 switch (b.fOperator) {
662 case Token::EQEQ:
663 if (b.fLeft->fType.kind() == Type::kVector_Kind) {
664 this->write("all");
665 needParens = true;
666 }
667 break;
668 case Token::NEQ:
669 if (b.fLeft->fType.kind() == Type::kVector_Kind) {
Jim Van Verth36477b42019-04-11 14:57:30 -0400670 this->write("any");
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500671 needParens = true;
672 }
673 break;
674 default:
675 break;
676 }
677 if (needParens) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400678 this->write("(");
679 }
680 if (Compiler::IsAssignment(b.fOperator) &&
681 Expression::kVariableReference_Kind == b.fLeft->fKind &&
682 Variable::kParameter_Storage == ((VariableReference&) *b.fLeft).fVariable.fStorage &&
683 (((VariableReference&) *b.fLeft).fVariable.fModifiers.fFlags & Modifiers::kOut_Flag)) {
684 // writing to an out parameter. Since we have to turn those into pointers, we have to
685 // dereference it here.
686 this->write("*");
687 }
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500688 if (b.fOperator == Token::STAREQ && b.fLeft->fType.kind() == Type::kMatrix_Kind &&
689 b.fRight->fType.kind() == Type::kMatrix_Kind) {
690 this->writeMatrixTimesEqualHelper(b.fLeft->fType, b.fRight->fType, b.fType);
691 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400692 this->writeExpression(*b.fLeft, precedence);
693 if (b.fOperator != Token::EQ && Compiler::IsAssignment(b.fOperator) &&
694 Expression::kSwizzle_Kind == b.fLeft->fKind && !b.fLeft->hasSideEffects()) {
695 // This doesn't compile in Metal:
696 // float4 x = float4(1);
697 // x.xy *= float2x2(...);
698 // with the error message "non-const reference cannot bind to vector element",
699 // but switching it to x.xy = x.xy * float2x2(...) fixes it. We perform this tranformation
700 // as long as the LHS has no side effects, and hope for the best otherwise.
701 this->write(" = ");
702 this->writeExpression(*b.fLeft, kAssignment_Precedence);
703 this->write(" ");
704 String op = Compiler::OperatorName(b.fOperator);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400705 SkASSERT(op.endsWith("="));
Ethan Nicholascc305772017-10-13 16:17:45 -0400706 this->write(op.substr(0, op.size() - 1).c_str());
707 this->write(" ");
708 } else {
709 this->write(String(" ") + Compiler::OperatorName(b.fOperator) + " ");
710 }
711 this->writeExpression(*b.fRight, precedence);
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500712 if (needParens) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400713 this->write(")");
714 }
715}
716
717void MetalCodeGenerator::writeTernaryExpression(const TernaryExpression& t,
718 Precedence parentPrecedence) {
719 if (kTernary_Precedence >= parentPrecedence) {
720 this->write("(");
721 }
722 this->writeExpression(*t.fTest, kTernary_Precedence);
723 this->write(" ? ");
724 this->writeExpression(*t.fIfTrue, kTernary_Precedence);
725 this->write(" : ");
726 this->writeExpression(*t.fIfFalse, kTernary_Precedence);
727 if (kTernary_Precedence >= parentPrecedence) {
728 this->write(")");
729 }
730}
731
732void MetalCodeGenerator::writePrefixExpression(const PrefixExpression& p,
733 Precedence parentPrecedence) {
734 if (kPrefix_Precedence >= parentPrecedence) {
735 this->write("(");
736 }
737 this->write(Compiler::OperatorName(p.fOperator));
738 this->writeExpression(*p.fOperand, kPrefix_Precedence);
739 if (kPrefix_Precedence >= parentPrecedence) {
740 this->write(")");
741 }
742}
743
744void MetalCodeGenerator::writePostfixExpression(const PostfixExpression& p,
745 Precedence parentPrecedence) {
746 if (kPostfix_Precedence >= parentPrecedence) {
747 this->write("(");
748 }
749 this->writeExpression(*p.fOperand, kPostfix_Precedence);
750 this->write(Compiler::OperatorName(p.fOperator));
751 if (kPostfix_Precedence >= parentPrecedence) {
752 this->write(")");
753 }
754}
755
756void MetalCodeGenerator::writeBoolLiteral(const BoolLiteral& b) {
757 this->write(b.fValue ? "true" : "false");
758}
759
760void MetalCodeGenerator::writeIntLiteral(const IntLiteral& i) {
761 if (i.fType == *fContext.fUInt_Type) {
762 this->write(to_string(i.fValue & 0xffffffff) + "u");
763 } else {
764 this->write(to_string((int32_t) i.fValue));
765 }
766}
767
768void MetalCodeGenerator::writeFloatLiteral(const FloatLiteral& f) {
769 this->write(to_string(f.fValue));
770}
771
772void MetalCodeGenerator::writeSetting(const Setting& s) {
773 ABORT("internal error; setting was not folded to a constant during compilation\n");
774}
775
776void MetalCodeGenerator::writeFunction(const FunctionDefinition& f) {
777 const char* separator = "";
778 if ("main" == f.fDeclaration.fName) {
779 switch (fProgram.fKind) {
780 case Program::kFragment_Kind:
Timothy Liangb8eeb802018-07-23 16:46:16 -0400781#ifdef SK_MOLTENVK
782 this->write("fragment Outputs main0");
783#else
784 this->write("fragment Outputs fragmentMain");
785#endif
Ethan Nicholascc305772017-10-13 16:17:45 -0400786 break;
787 case Program::kVertex_Kind:
Timothy Liangb8eeb802018-07-23 16:46:16 -0400788#ifdef SK_MOLTENVK
Timothy Lianga06f2152018-05-24 15:33:31 -0400789 this->write("vertex Outputs main0");
Timothy Liangb8eeb802018-07-23 16:46:16 -0400790#else
791 this->write("vertex Outputs vertexMain");
792#endif
Ethan Nicholascc305772017-10-13 16:17:45 -0400793 break;
794 default:
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400795 SkASSERT(false);
Ethan Nicholascc305772017-10-13 16:17:45 -0400796 }
797 this->write("(Inputs _in [[stage_in]]");
798 if (-1 != fUniformBuffer) {
799 this->write(", constant Uniforms& _uniforms [[buffer(" +
800 to_string(fUniformBuffer) + ")]]");
801 }
Timothy Liang6403b0e2018-05-17 10:40:04 -0400802 for (const auto& e : fProgram) {
803 if (ProgramElement::kVar_Kind == e.fKind) {
804 VarDeclarations& decls = (VarDeclarations&) e;
805 if (!decls.fVars.size()) {
806 continue;
807 }
Timothy Liangee84fe12018-05-18 14:38:19 -0400808 for (const auto& stmt: decls.fVars) {
Timothy Liang6403b0e2018-05-17 10:40:04 -0400809 VarDeclaration& var = (VarDeclaration&) *stmt;
Timothy Liangee84fe12018-05-18 14:38:19 -0400810 if (var.fVar->fType.kind() == Type::kSampler_Kind) {
Timothy Liang7d637782018-06-05 09:58:07 -0400811 this->write(", texture2d<float> "); // FIXME - support other texture types
Timothy Liang651286f2018-06-07 09:55:33 -0400812 this->writeName(var.fVar->fName);
Timothy Liangee84fe12018-05-18 14:38:19 -0400813 this->write("[[texture(");
Timothy Lianga06f2152018-05-24 15:33:31 -0400814 this->write(to_string(var.fVar->fModifiers.fLayout.fBinding));
815 this->write(")]]");
816 this->write(", sampler ");
Timothy Liang651286f2018-06-07 09:55:33 -0400817 this->writeName(var.fVar->fName);
Timothy Lianga06f2152018-05-24 15:33:31 -0400818 this->write(SAMPLER_SUFFIX);
819 this->write("[[sampler(");
820 this->write(to_string(var.fVar->fModifiers.fLayout.fBinding));
Timothy Liangee84fe12018-05-18 14:38:19 -0400821 this->write(")]]");
822 }
Timothy Liang6403b0e2018-05-17 10:40:04 -0400823 }
Timothy Lianga06f2152018-05-24 15:33:31 -0400824 } else if (ProgramElement::kInterfaceBlock_Kind == e.fKind) {
825 InterfaceBlock& intf = (InterfaceBlock&) e;
826 if ("sk_PerVertex" == intf.fTypeName) {
827 continue;
828 }
829 this->write(", constant ");
830 this->writeType(intf.fVariable.fType);
831 this->write("& " );
832 this->write(fInterfaceBlockNameMap[&intf]);
833 this->write(" [[buffer(");
Timothy Liang057c3902018-08-08 10:48:45 -0400834#ifdef SK_MOLTENVK
Timothy Liang7d637782018-06-05 09:58:07 -0400835 this->write(to_string(intf.fVariable.fModifiers.fLayout.fSet));
Timothy Liang057c3902018-08-08 10:48:45 -0400836#else
837 this->write(to_string(intf.fVariable.fModifiers.fLayout.fBinding));
838#endif
Timothy Lianga06f2152018-05-24 15:33:31 -0400839 this->write(")]]");
Timothy Liang6403b0e2018-05-17 10:40:04 -0400840 }
841 }
Jim Van Verth6bc650e2019-02-07 14:53:23 -0500842 if (fProgram.fKind == Program::kFragment_Kind) {
843 if (fProgram.fInputs.fRTHeight && fInterfaceBlockNameMap.empty()) {
Timothy Liang5422f9a2018-08-10 10:57:55 -0400844#ifdef SK_MOLTENVK
845 this->write(", constant sksl_synthetic_uniforms& _anonInterface0 [[buffer(0)]]");
846#else
847 this->write(", constant sksl_synthetic_uniforms& _anonInterface0 [[buffer(1)]]");
848#endif
849 }
Timothy Liang7b8875d2018-08-10 09:42:31 -0400850 this->write(", bool _frontFacing [[front_facing]]");
Timothy Liang7d637782018-06-05 09:58:07 -0400851 this->write(", float4 _fragCoord [[position]]");
Timothy Liangdc89f192018-06-13 09:20:31 -0400852 } else if (fProgram.fKind == Program::kVertex_Kind) {
853 this->write(", uint sk_VertexID [[vertex_id]], uint sk_InstanceID [[instance_id]]");
Timothy Liang7d637782018-06-05 09:58:07 -0400854 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400855 separator = ", ";
856 } else {
857 this->writeType(f.fDeclaration.fReturnType);
Timothy Liang651286f2018-06-07 09:55:33 -0400858 this->write(" ");
859 this->writeName(f.fDeclaration.fName);
860 this->write("(");
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -0400861 Requirements requirements = this->requirements(f.fDeclaration);
862 if (requirements & kInputs_Requirement) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400863 this->write("Inputs _in");
864 separator = ", ";
865 }
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -0400866 if (requirements & kOutputs_Requirement) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400867 this->write(separator);
Timothy Liangee84fe12018-05-18 14:38:19 -0400868 this->write("thread Outputs* _out");
Ethan Nicholascc305772017-10-13 16:17:45 -0400869 separator = ", ";
870 }
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -0400871 if (requirements & kUniforms_Requirement) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400872 this->write(separator);
873 this->write("Uniforms _uniforms");
874 separator = ", ";
875 }
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -0400876 if (requirements & kGlobals_Requirement) {
Timothy Liangee84fe12018-05-18 14:38:19 -0400877 this->write(separator);
878 this->write("thread Globals* _globals");
879 separator = ", ";
880 }
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -0400881 if (requirements & kFragCoord_Requirement) {
882 this->write(separator);
883 this->write("float4 _fragCoord");
884 separator = ", ";
885 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400886 }
887 for (const auto& param : f.fDeclaration.fParameters) {
888 this->write(separator);
889 separator = ", ";
890 this->writeModifiers(param->fModifiers, false);
891 std::vector<int> sizes;
892 const Type* type = &param->fType;
893 while (Type::kArray_Kind == type->kind()) {
894 sizes.push_back(type->columns());
895 type = &type->componentType();
896 }
897 this->writeType(*type);
898 if (param->fModifiers.fFlags & Modifiers::kOut_Flag) {
899 this->write("*");
900 }
Timothy Liang651286f2018-06-07 09:55:33 -0400901 this->write(" ");
902 this->writeName(param->fName);
Ethan Nicholascc305772017-10-13 16:17:45 -0400903 for (int s : sizes) {
904 if (s <= 0) {
905 this->write("[]");
906 } else {
907 this->write("[" + to_string(s) + "]");
908 }
909 }
910 }
911 this->writeLine(") {");
912
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400913 SkASSERT(!fProgram.fSettings.fFragColorIsInOut);
Brian Salomondc092132018-04-04 10:14:16 -0400914
Ethan Nicholascc305772017-10-13 16:17:45 -0400915 if ("main" == f.fDeclaration.fName) {
Timothy Liangee84fe12018-05-18 14:38:19 -0400916 if (fNeedsGlobalStructInit) {
917 this->writeLine(" Globals globalStruct;");
918 this->writeLine(" thread Globals* _globals = &globalStruct;");
Timothy Liang7d637782018-06-05 09:58:07 -0400919 for (const auto& intf: fInterfaceBlockNameMap) {
920 const auto& intfName = intf.second;
921 this->write(" _globals->");
Timothy Liang651286f2018-06-07 09:55:33 -0400922 this->writeName(intfName);
Timothy Liang7d637782018-06-05 09:58:07 -0400923 this->write(" = &");
Timothy Liang651286f2018-06-07 09:55:33 -0400924 this->writeName(intfName);
Timothy Liang7d637782018-06-05 09:58:07 -0400925 this->write(";\n");
926 }
Timothy Lianga06f2152018-05-24 15:33:31 -0400927 for (const auto& var: fInitNonConstGlobalVars) {
Timothy Liangee84fe12018-05-18 14:38:19 -0400928 this->write(" _globals->");
Timothy Liang651286f2018-06-07 09:55:33 -0400929 this->writeName(var->fVar->fName);
Timothy Liangee84fe12018-05-18 14:38:19 -0400930 this->write(" = ");
931 this->writeVarInitializer(*var->fVar, *var->fValue);
932 this->writeLine(";");
933 }
Timothy Lianga06f2152018-05-24 15:33:31 -0400934 for (const auto& texture: fTextures) {
Timothy Liangee84fe12018-05-18 14:38:19 -0400935 this->write(" _globals->");
Timothy Liang651286f2018-06-07 09:55:33 -0400936 this->writeName(texture->fName);
Timothy Liangee84fe12018-05-18 14:38:19 -0400937 this->write(" = ");
Timothy Liang651286f2018-06-07 09:55:33 -0400938 this->writeName(texture->fName);
Timothy Lianga06f2152018-05-24 15:33:31 -0400939 this->write(";\n");
940 this->write(" _globals->");
Timothy Liang651286f2018-06-07 09:55:33 -0400941 this->writeName(texture->fName);
Timothy Lianga06f2152018-05-24 15:33:31 -0400942 this->write(SAMPLER_SUFFIX);
943 this->write(" = ");
Timothy Liang651286f2018-06-07 09:55:33 -0400944 this->writeName(texture->fName);
Timothy Lianga06f2152018-05-24 15:33:31 -0400945 this->write(SAMPLER_SUFFIX);
Timothy Liangee84fe12018-05-18 14:38:19 -0400946 this->write(";\n");
947 }
Timothy Liang6403b0e2018-05-17 10:40:04 -0400948 }
Timothy Liang7d637782018-06-05 09:58:07 -0400949 this->writeLine(" Outputs _outputStruct;");
950 this->writeLine(" thread Outputs* _out = &_outputStruct;");
Ethan Nicholascc305772017-10-13 16:17:45 -0400951 }
952 fFunctionHeader = "";
953 OutputStream* oldOut = fOut;
954 StringStream buffer;
955 fOut = &buffer;
956 fIndentation++;
957 this->writeStatements(((Block&) *f.fBody).fStatements);
958 if ("main" == f.fDeclaration.fName) {
959 switch (fProgram.fKind) {
960 case Program::kFragment_Kind:
Timothy Liang7d637782018-06-05 09:58:07 -0400961 this->writeLine("return *_out;");
Ethan Nicholascc305772017-10-13 16:17:45 -0400962 break;
963 case Program::kVertex_Kind:
Timothy Liangb8eeb802018-07-23 16:46:16 -0400964 this->writeLine("_out->sk_Position.y = -_out->sk_Position.y;");
Timothy Lianga06f2152018-05-24 15:33:31 -0400965 this->writeLine("return *_out;"); // FIXME - detect if function already has return
Ethan Nicholascc305772017-10-13 16:17:45 -0400966 break;
967 default:
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400968 SkASSERT(false);
Ethan Nicholascc305772017-10-13 16:17:45 -0400969 }
970 }
971 fIndentation--;
972 this->writeLine("}");
973
974 fOut = oldOut;
975 this->write(fFunctionHeader);
976 this->write(buffer.str());
977}
978
979void MetalCodeGenerator::writeModifiers(const Modifiers& modifiers,
980 bool globalContext) {
981 if (modifiers.fFlags & Modifiers::kOut_Flag) {
982 this->write("thread ");
983 }
984 if (modifiers.fFlags & Modifiers::kConst_Flag) {
Timothy Liangee84fe12018-05-18 14:38:19 -0400985 this->write("constant ");
Ethan Nicholascc305772017-10-13 16:17:45 -0400986 }
987}
988
989void MetalCodeGenerator::writeInterfaceBlock(const InterfaceBlock& intf) {
990 if ("sk_PerVertex" == intf.fTypeName) {
991 return;
992 }
993 this->writeModifiers(intf.fVariable.fModifiers, true);
Timothy Liangdc89f192018-06-13 09:20:31 -0400994 this->write("struct ");
Ethan Nicholascc305772017-10-13 16:17:45 -0400995 this->writeLine(intf.fTypeName + " {");
Ethan Nicholascc305772017-10-13 16:17:45 -0400996 const Type* structType = &intf.fVariable.fType;
Timothy Lianga06f2152018-05-24 15:33:31 -0400997 fWrittenStructs.push_back(structType);
Ethan Nicholascc305772017-10-13 16:17:45 -0400998 while (Type::kArray_Kind == structType->kind()) {
999 structType = &structType->componentType();
1000 }
Timothy Liangdc89f192018-06-13 09:20:31 -04001001 fIndentation++;
1002 writeFields(structType->fields(), structType->fOffset, &intf);
Jim Van Verth3d482992019-02-07 10:48:05 -05001003 if (fProgram.fInputs.fRTHeight) {
Timothy Liang7d637782018-06-05 09:58:07 -04001004 this->writeLine("float u_skRTHeight;");
Ethan Nicholascc305772017-10-13 16:17:45 -04001005 }
1006 fIndentation--;
1007 this->write("}");
1008 if (intf.fInstanceName.size()) {
1009 this->write(" ");
1010 this->write(intf.fInstanceName);
1011 for (const auto& size : intf.fSizes) {
1012 this->write("[");
1013 if (size) {
1014 this->writeExpression(*size, kTopLevel_Precedence);
1015 }
1016 this->write("]");
1017 }
Timothy Lianga06f2152018-05-24 15:33:31 -04001018 fInterfaceBlockNameMap[&intf] = intf.fInstanceName;
1019 } else {
Timothy Liang7d637782018-06-05 09:58:07 -04001020 fInterfaceBlockNameMap[&intf] = "_anonInterface" + to_string(fAnonInterfaceCount++);
Ethan Nicholascc305772017-10-13 16:17:45 -04001021 }
1022 this->writeLine(";");
1023}
1024
Timothy Liangdc89f192018-06-13 09:20:31 -04001025void MetalCodeGenerator::writeFields(const std::vector<Type::Field>& fields, int parentOffset,
1026 const InterfaceBlock* parentIntf) {
Timothy Liang609fbe32018-08-10 16:40:49 -04001027#ifdef SK_MOLTENVK
Timothy Liangdc89f192018-06-13 09:20:31 -04001028 MemoryLayout memoryLayout(MemoryLayout::k140_Standard);
Timothy Liang609fbe32018-08-10 16:40:49 -04001029#else
1030 MemoryLayout memoryLayout(MemoryLayout::kMetal_Standard);
1031#endif
Timothy Liangdc89f192018-06-13 09:20:31 -04001032 int currentOffset = 0;
1033 for (const auto& field: fields) {
1034 int fieldOffset = field.fModifiers.fLayout.fOffset;
1035 const Type* fieldType = field.fType;
1036 if (fieldOffset != -1) {
1037 if (currentOffset > fieldOffset) {
1038 fErrors.error(parentOffset,
1039 "offset of field '" + field.fName + "' must be at least " +
1040 to_string((int) currentOffset));
1041 } else if (currentOffset < fieldOffset) {
1042 this->write("char pad");
1043 this->write(to_string(fPaddingCount++));
1044 this->write("[");
1045 this->write(to_string(fieldOffset - currentOffset));
1046 this->writeLine("];");
1047 currentOffset = fieldOffset;
1048 }
1049 int alignment = memoryLayout.alignment(*fieldType);
1050 if (fieldOffset % alignment) {
1051 fErrors.error(parentOffset,
1052 "offset of field '" + field.fName + "' must be a multiple of " +
1053 to_string((int) alignment));
1054 }
1055 }
Timothy Liang609fbe32018-08-10 16:40:49 -04001056#ifdef SK_MOLTENVK
Timothy Liangdc89f192018-06-13 09:20:31 -04001057 if (fieldType->kind() == Type::kVector_Kind &&
1058 fieldType->columns() == 3) {
Timothy Liang609fbe32018-08-10 16:40:49 -04001059 SkASSERT(memoryLayout.size(*fieldType) == 3);
Timothy Liangdc89f192018-06-13 09:20:31 -04001060 // Pack all vec3 types so that their size in bytes will match what was expected in the
1061 // original SkSL code since MSL has vec3 sizes equal to 4 * component type, while SkSL
1062 // has vec3 equal to 3 * component type.
Timothy Liang609fbe32018-08-10 16:40:49 -04001063
1064 // FIXME - Packed vectors can't be accessed by swizzles, but can be indexed into. A
1065 // combination of this being a problem which only occurs when using MoltenVK and the
1066 // fact that we haven't swizzled a vec3 yet means that this problem hasn't been
1067 // addressed.
Timothy Liangdc89f192018-06-13 09:20:31 -04001068 this->write(PACKED_PREFIX);
1069 }
Timothy Liang609fbe32018-08-10 16:40:49 -04001070#endif
Timothy Liangdc89f192018-06-13 09:20:31 -04001071 currentOffset += memoryLayout.size(*fieldType);
1072 std::vector<int> sizes;
1073 while (fieldType->kind() == Type::kArray_Kind) {
1074 sizes.push_back(fieldType->columns());
1075 fieldType = &fieldType->componentType();
1076 }
1077 this->writeModifiers(field.fModifiers, false);
1078 this->writeType(*fieldType);
1079 this->write(" ");
1080 this->writeName(field.fName);
1081 for (int s : sizes) {
1082 if (s <= 0) {
1083 this->write("[]");
1084 } else {
1085 this->write("[" + to_string(s) + "]");
1086 }
1087 }
1088 this->writeLine(";");
1089 if (parentIntf) {
1090 fInterfaceBlockMap[&field] = parentIntf;
1091 }
1092 }
1093}
1094
Ethan Nicholascc305772017-10-13 16:17:45 -04001095void MetalCodeGenerator::writeVarInitializer(const Variable& var, const Expression& value) {
1096 this->writeExpression(value, kTopLevel_Precedence);
1097}
1098
Timothy Liang651286f2018-06-07 09:55:33 -04001099void MetalCodeGenerator::writeName(const String& name) {
1100 if (fReservedWords.find(name) != fReservedWords.end()) {
1101 this->write("_"); // adding underscore before name to avoid conflict with reserved words
1102 }
1103 this->write(name);
1104}
1105
Ethan Nicholascc305772017-10-13 16:17:45 -04001106void MetalCodeGenerator::writeVarDeclarations(const VarDeclarations& decl, bool global) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001107 SkASSERT(decl.fVars.size() > 0);
Ethan Nicholascc305772017-10-13 16:17:45 -04001108 bool wroteType = false;
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001109 for (const auto& stmt : decl.fVars) {
1110 VarDeclaration& var = (VarDeclaration&) *stmt;
Timothy Liangee84fe12018-05-18 14:38:19 -04001111 if (global && !(var.fVar->fModifiers.fFlags & Modifiers::kConst_Flag)) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001112 continue;
1113 }
1114 if (wroteType) {
1115 this->write(", ");
1116 } else {
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001117 this->writeModifiers(var.fVar->fModifiers, global);
Ethan Nicholascc305772017-10-13 16:17:45 -04001118 this->writeType(decl.fBaseType);
1119 this->write(" ");
1120 wroteType = true;
1121 }
Timothy Liang651286f2018-06-07 09:55:33 -04001122 this->writeName(var.fVar->fName);
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001123 for (const auto& size : var.fSizes) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001124 this->write("[");
1125 if (size) {
1126 this->writeExpression(*size, kTopLevel_Precedence);
1127 }
1128 this->write("]");
1129 }
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001130 if (var.fValue) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001131 this->write(" = ");
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001132 this->writeVarInitializer(*var.fVar, *var.fValue);
Ethan Nicholascc305772017-10-13 16:17:45 -04001133 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001134 }
1135 if (wroteType) {
1136 this->write(";");
1137 }
1138}
1139
1140void MetalCodeGenerator::writeStatement(const Statement& s) {
1141 switch (s.fKind) {
1142 case Statement::kBlock_Kind:
1143 this->writeBlock((Block&) s);
1144 break;
1145 case Statement::kExpression_Kind:
1146 this->writeExpression(*((ExpressionStatement&) s).fExpression, kTopLevel_Precedence);
1147 this->write(";");
1148 break;
1149 case Statement::kReturn_Kind:
1150 this->writeReturnStatement((ReturnStatement&) s);
1151 break;
1152 case Statement::kVarDeclarations_Kind:
1153 this->writeVarDeclarations(*((VarDeclarationsStatement&) s).fDeclaration, false);
1154 break;
1155 case Statement::kIf_Kind:
1156 this->writeIfStatement((IfStatement&) s);
1157 break;
1158 case Statement::kFor_Kind:
1159 this->writeForStatement((ForStatement&) s);
1160 break;
1161 case Statement::kWhile_Kind:
1162 this->writeWhileStatement((WhileStatement&) s);
1163 break;
1164 case Statement::kDo_Kind:
1165 this->writeDoStatement((DoStatement&) s);
1166 break;
1167 case Statement::kSwitch_Kind:
1168 this->writeSwitchStatement((SwitchStatement&) s);
1169 break;
1170 case Statement::kBreak_Kind:
1171 this->write("break;");
1172 break;
1173 case Statement::kContinue_Kind:
1174 this->write("continue;");
1175 break;
1176 case Statement::kDiscard_Kind:
Timothy Lianga06f2152018-05-24 15:33:31 -04001177 this->write("discard_fragment();");
Ethan Nicholascc305772017-10-13 16:17:45 -04001178 break;
1179 case Statement::kNop_Kind:
1180 this->write(";");
1181 break;
1182 default:
1183 ABORT("unsupported statement: %s", s.description().c_str());
1184 }
1185}
1186
1187void MetalCodeGenerator::writeStatements(const std::vector<std::unique_ptr<Statement>>& statements) {
1188 for (const auto& s : statements) {
1189 if (!s->isEmpty()) {
1190 this->writeStatement(*s);
1191 this->writeLine();
1192 }
1193 }
1194}
1195
1196void MetalCodeGenerator::writeBlock(const Block& b) {
1197 this->writeLine("{");
1198 fIndentation++;
1199 this->writeStatements(b.fStatements);
1200 fIndentation--;
1201 this->write("}");
1202}
1203
1204void MetalCodeGenerator::writeIfStatement(const IfStatement& stmt) {
1205 this->write("if (");
1206 this->writeExpression(*stmt.fTest, kTopLevel_Precedence);
1207 this->write(") ");
1208 this->writeStatement(*stmt.fIfTrue);
1209 if (stmt.fIfFalse) {
1210 this->write(" else ");
1211 this->writeStatement(*stmt.fIfFalse);
1212 }
1213}
1214
1215void MetalCodeGenerator::writeForStatement(const ForStatement& f) {
1216 this->write("for (");
1217 if (f.fInitializer && !f.fInitializer->isEmpty()) {
1218 this->writeStatement(*f.fInitializer);
1219 } else {
1220 this->write("; ");
1221 }
1222 if (f.fTest) {
1223 this->writeExpression(*f.fTest, kTopLevel_Precedence);
1224 }
1225 this->write("; ");
1226 if (f.fNext) {
1227 this->writeExpression(*f.fNext, kTopLevel_Precedence);
1228 }
1229 this->write(") ");
1230 this->writeStatement(*f.fStatement);
1231}
1232
1233void MetalCodeGenerator::writeWhileStatement(const WhileStatement& w) {
1234 this->write("while (");
1235 this->writeExpression(*w.fTest, kTopLevel_Precedence);
1236 this->write(") ");
1237 this->writeStatement(*w.fStatement);
1238}
1239
1240void MetalCodeGenerator::writeDoStatement(const DoStatement& d) {
1241 this->write("do ");
1242 this->writeStatement(*d.fStatement);
1243 this->write(" while (");
1244 this->writeExpression(*d.fTest, kTopLevel_Precedence);
1245 this->write(");");
1246}
1247
1248void MetalCodeGenerator::writeSwitchStatement(const SwitchStatement& s) {
1249 this->write("switch (");
1250 this->writeExpression(*s.fValue, kTopLevel_Precedence);
1251 this->writeLine(") {");
1252 fIndentation++;
1253 for (const auto& c : s.fCases) {
1254 if (c->fValue) {
1255 this->write("case ");
1256 this->writeExpression(*c->fValue, kTopLevel_Precedence);
1257 this->writeLine(":");
1258 } else {
1259 this->writeLine("default:");
1260 }
1261 fIndentation++;
1262 for (const auto& stmt : c->fStatements) {
1263 this->writeStatement(*stmt);
1264 this->writeLine();
1265 }
1266 fIndentation--;
1267 }
1268 fIndentation--;
1269 this->write("}");
1270}
1271
1272void MetalCodeGenerator::writeReturnStatement(const ReturnStatement& r) {
1273 this->write("return");
1274 if (r.fExpression) {
1275 this->write(" ");
1276 this->writeExpression(*r.fExpression, kTopLevel_Precedence);
1277 }
1278 this->write(";");
1279}
1280
1281void MetalCodeGenerator::writeHeader() {
1282 this->write("#include <metal_stdlib>\n");
1283 this->write("#include <simd/simd.h>\n");
1284 this->write("using namespace metal;\n");
1285}
1286
1287void MetalCodeGenerator::writeUniformStruct() {
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001288 for (const auto& e : fProgram) {
1289 if (ProgramElement::kVar_Kind == e.fKind) {
1290 VarDeclarations& decls = (VarDeclarations&) e;
Ethan Nicholascc305772017-10-13 16:17:45 -04001291 if (!decls.fVars.size()) {
1292 continue;
1293 }
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001294 const Variable& first = *((VarDeclaration&) *decls.fVars[0]).fVar;
Timothy Lianga06f2152018-05-24 15:33:31 -04001295 if (first.fModifiers.fFlags & Modifiers::kUniform_Flag &&
1296 first.fType.kind() != Type::kSampler_Kind) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001297 if (-1 == fUniformBuffer) {
1298 this->write("struct Uniforms {\n");
1299 fUniformBuffer = first.fModifiers.fLayout.fSet;
1300 if (-1 == fUniformBuffer) {
1301 fErrors.error(decls.fOffset, "Metal uniforms must have 'layout(set=...)'");
1302 }
1303 } else if (first.fModifiers.fLayout.fSet != fUniformBuffer) {
1304 if (-1 == fUniformBuffer) {
1305 fErrors.error(decls.fOffset, "Metal backend requires all uniforms to have "
1306 "the same 'layout(set=...)'");
1307 }
1308 }
1309 this->write(" ");
1310 this->writeType(first.fType);
1311 this->write(" ");
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001312 for (const auto& stmt : decls.fVars) {
1313 VarDeclaration& var = (VarDeclaration&) *stmt;
Timothy Liang651286f2018-06-07 09:55:33 -04001314 this->writeName(var.fVar->fName);
Ethan Nicholascc305772017-10-13 16:17:45 -04001315 }
1316 this->write(";\n");
1317 }
1318 }
1319 }
1320 if (-1 != fUniformBuffer) {
1321 this->write("};\n");
1322 }
1323}
1324
1325void MetalCodeGenerator::writeInputStruct() {
1326 this->write("struct Inputs {\n");
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001327 for (const auto& e : fProgram) {
1328 if (ProgramElement::kVar_Kind == e.fKind) {
1329 VarDeclarations& decls = (VarDeclarations&) e;
Ethan Nicholascc305772017-10-13 16:17:45 -04001330 if (!decls.fVars.size()) {
1331 continue;
1332 }
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001333 const Variable& first = *((VarDeclaration&) *decls.fVars[0]).fVar;
Ethan Nicholascc305772017-10-13 16:17:45 -04001334 if (first.fModifiers.fFlags & Modifiers::kIn_Flag &&
1335 -1 == first.fModifiers.fLayout.fBuiltin) {
1336 this->write(" ");
1337 this->writeType(first.fType);
1338 this->write(" ");
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001339 for (const auto& stmt : decls.fVars) {
1340 VarDeclaration& var = (VarDeclaration&) *stmt;
Timothy Liang651286f2018-06-07 09:55:33 -04001341 this->writeName(var.fVar->fName);
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001342 if (-1 != var.fVar->fModifiers.fLayout.fLocation) {
Timothy Liang7d637782018-06-05 09:58:07 -04001343 if (fProgram.fKind == Program::kVertex_Kind) {
1344 this->write(" [[attribute(" +
1345 to_string(var.fVar->fModifiers.fLayout.fLocation) + ")]]");
1346 } else if (fProgram.fKind == Program::kFragment_Kind) {
1347 this->write(" [[user(locn" +
1348 to_string(var.fVar->fModifiers.fLayout.fLocation) + ")]]");
1349 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001350 }
1351 }
1352 this->write(";\n");
1353 }
1354 }
1355 }
1356 this->write("};\n");
1357}
1358
1359void MetalCodeGenerator::writeOutputStruct() {
1360 this->write("struct Outputs {\n");
Timothy Liang7d637782018-06-05 09:58:07 -04001361 if (fProgram.fKind == Program::kVertex_Kind) {
Timothy Liangb8eeb802018-07-23 16:46:16 -04001362 this->write(" float4 sk_Position [[position]];\n");
Timothy Liang7d637782018-06-05 09:58:07 -04001363 } else if (fProgram.fKind == Program::kFragment_Kind) {
Timothy Liangde0be802018-08-10 13:48:08 -04001364 this->write(" float4 sk_FragColor [[color(0)]];\n");
Timothy Liang7d637782018-06-05 09:58:07 -04001365 }
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001366 for (const auto& e : fProgram) {
1367 if (ProgramElement::kVar_Kind == e.fKind) {
1368 VarDeclarations& decls = (VarDeclarations&) e;
Ethan Nicholascc305772017-10-13 16:17:45 -04001369 if (!decls.fVars.size()) {
1370 continue;
1371 }
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001372 const Variable& first = *((VarDeclaration&) *decls.fVars[0]).fVar;
Ethan Nicholascc305772017-10-13 16:17:45 -04001373 if (first.fModifiers.fFlags & Modifiers::kOut_Flag &&
1374 -1 == first.fModifiers.fLayout.fBuiltin) {
1375 this->write(" ");
1376 this->writeType(first.fType);
1377 this->write(" ");
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001378 for (const auto& stmt : decls.fVars) {
1379 VarDeclaration& var = (VarDeclaration&) *stmt;
Timothy Liang651286f2018-06-07 09:55:33 -04001380 this->writeName(var.fVar->fName);
Timothy Liang7d637782018-06-05 09:58:07 -04001381 if (fProgram.fKind == Program::kVertex_Kind) {
1382 this->write(" [[user(locn" +
1383 to_string(var.fVar->fModifiers.fLayout.fLocation) + ")]]");
1384 } else if (fProgram.fKind == Program::kFragment_Kind) {
1385 this->write(" [[color(" +
Timothy Liangde0be802018-08-10 13:48:08 -04001386 to_string(var.fVar->fModifiers.fLayout.fLocation) +")");
1387 int colorIndex = var.fVar->fModifiers.fLayout.fIndex;
1388 if (colorIndex) {
1389 this->write(", index(" + to_string(colorIndex) + ")");
1390 }
1391 this->write("]]");
Timothy Liang7d637782018-06-05 09:58:07 -04001392 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001393 }
1394 this->write(";\n");
1395 }
1396 }
Timothy Liang7d637782018-06-05 09:58:07 -04001397 }
1398 if (fProgram.fKind == Program::kVertex_Kind) {
1399 this->write(" float sk_PointSize;\n");
1400 }
1401 this->write("};\n");
1402}
1403
1404void MetalCodeGenerator::writeInterfaceBlocks() {
1405 bool wroteInterfaceBlock = false;
1406 for (const auto& e : fProgram) {
1407 if (ProgramElement::kInterfaceBlock_Kind == e.fKind) {
1408 this->writeInterfaceBlock((InterfaceBlock&) e);
1409 wroteInterfaceBlock = true;
1410 }
1411 }
Jim Van Verth3d482992019-02-07 10:48:05 -05001412 if (!wroteInterfaceBlock && fProgram.fInputs.fRTHeight) {
Timothy Liang7d637782018-06-05 09:58:07 -04001413 this->writeLine("struct sksl_synthetic_uniforms {");
1414 this->writeLine(" float u_skRTHeight;");
1415 this->writeLine("};");
1416 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001417}
1418
Timothy Liangee84fe12018-05-18 14:38:19 -04001419void MetalCodeGenerator::writeGlobalStruct() {
1420 bool wroteStructDecl = false;
Timothy Liang7d637782018-06-05 09:58:07 -04001421 for (const auto& intf : fInterfaceBlockNameMap) {
1422 if (!wroteStructDecl) {
1423 this->write("struct Globals {\n");
1424 wroteStructDecl = true;
1425 }
1426 fNeedsGlobalStructInit = true;
1427 const auto& intfType = intf.first;
1428 const auto& intfName = intf.second;
1429 this->write(" constant ");
1430 this->write(intfType->fTypeName);
1431 this->write("* ");
Timothy Liang651286f2018-06-07 09:55:33 -04001432 this->writeName(intfName);
Timothy Liang7d637782018-06-05 09:58:07 -04001433 this->write(";\n");
1434 }
Timothy Liangee84fe12018-05-18 14:38:19 -04001435 for (const auto& e : fProgram) {
1436 if (ProgramElement::kVar_Kind == e.fKind) {
1437 VarDeclarations& decls = (VarDeclarations&) e;
1438 if (!decls.fVars.size()) {
1439 continue;
1440 }
1441 const Variable& first = *((VarDeclaration&) *decls.fVars[0]).fVar;
Timothy Lianga06f2152018-05-24 15:33:31 -04001442 if ((!first.fModifiers.fFlags && -1 == first.fModifiers.fLayout.fBuiltin) ||
1443 first.fType.kind() == Type::kSampler_Kind) {
Timothy Liangee84fe12018-05-18 14:38:19 -04001444 if (!wroteStructDecl) {
1445 this->write("struct Globals {\n");
1446 wroteStructDecl = true;
1447 }
1448 fNeedsGlobalStructInit = true;
1449 this->write(" ");
1450 this->writeType(first.fType);
1451 this->write(" ");
1452 for (const auto& stmt : decls.fVars) {
1453 VarDeclaration& var = (VarDeclaration&) *stmt;
Timothy Liang651286f2018-06-07 09:55:33 -04001454 this->writeName(var.fVar->fName);
Timothy Lianga06f2152018-05-24 15:33:31 -04001455 if (var.fVar->fType.kind() == Type::kSampler_Kind) {
1456 fTextures.push_back(var.fVar);
1457 this->write(";\n");
1458 this->write(" sampler ");
Timothy Liang651286f2018-06-07 09:55:33 -04001459 this->writeName(var.fVar->fName);
Timothy Lianga06f2152018-05-24 15:33:31 -04001460 this->write(SAMPLER_SUFFIX);
1461 }
Timothy Liangee84fe12018-05-18 14:38:19 -04001462 if (var.fValue) {
1463 fInitNonConstGlobalVars.push_back(&var);
1464 }
1465 }
1466 this->write(";\n");
1467 }
1468 }
1469 }
Timothy Liangee84fe12018-05-18 14:38:19 -04001470 if (wroteStructDecl) {
1471 this->write("};\n");
1472 }
1473}
1474
Ethan Nicholascc305772017-10-13 16:17:45 -04001475void MetalCodeGenerator::writeProgramElement(const ProgramElement& e) {
1476 switch (e.fKind) {
1477 case ProgramElement::kExtension_Kind:
1478 break;
1479 case ProgramElement::kVar_Kind: {
1480 VarDeclarations& decl = (VarDeclarations&) e;
1481 if (decl.fVars.size() > 0) {
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001482 int builtin = ((VarDeclaration&) *decl.fVars[0]).fVar->fModifiers.fLayout.fBuiltin;
Ethan Nicholascc305772017-10-13 16:17:45 -04001483 if (-1 == builtin) {
1484 // normal var
1485 this->writeVarDeclarations(decl, true);
1486 this->writeLine();
1487 } else if (SK_FRAGCOLOR_BUILTIN == builtin) {
1488 // ignore
1489 }
1490 }
1491 break;
1492 }
1493 case ProgramElement::kInterfaceBlock_Kind:
Timothy Liang7d637782018-06-05 09:58:07 -04001494 // handled in writeInterfaceBlocks, do nothing
Ethan Nicholascc305772017-10-13 16:17:45 -04001495 break;
1496 case ProgramElement::kFunction_Kind:
1497 this->writeFunction((FunctionDefinition&) e);
1498 break;
1499 case ProgramElement::kModifiers_Kind:
1500 this->writeModifiers(((ModifiersDeclaration&) e).fModifiers, true);
1501 this->writeLine(";");
1502 break;
1503 default:
1504 printf("%s\n", e.description().c_str());
1505 ABORT("unsupported program element");
1506 }
1507}
1508
1509MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const Expression& e) {
1510 switch (e.fKind) {
1511 case Expression::kFunctionCall_Kind: {
1512 const FunctionCall& f = (const FunctionCall&) e;
1513 Requirements result = this->requirements(f.fFunction);
1514 for (const auto& e : f.fArguments) {
1515 result |= this->requirements(*e);
1516 }
1517 return result;
1518 }
1519 case Expression::kConstructor_Kind: {
1520 const Constructor& c = (const Constructor&) e;
1521 Requirements result = kNo_Requirements;
1522 for (const auto& e : c.fArguments) {
1523 result |= this->requirements(*e);
1524 }
1525 return result;
1526 }
Timothy Liang7d637782018-06-05 09:58:07 -04001527 case Expression::kFieldAccess_Kind: {
1528 const FieldAccess& f = (const FieldAccess&) e;
1529 if (FieldAccess::kAnonymousInterfaceBlock_OwnerKind == f.fOwnerKind) {
1530 return kGlobals_Requirement;
1531 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001532 return this->requirements(*((const FieldAccess&) e).fBase);
Timothy Liang7d637782018-06-05 09:58:07 -04001533 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001534 case Expression::kSwizzle_Kind:
1535 return this->requirements(*((const Swizzle&) e).fBase);
1536 case Expression::kBinary_Kind: {
1537 const BinaryExpression& b = (const BinaryExpression&) e;
1538 return this->requirements(*b.fLeft) | this->requirements(*b.fRight);
1539 }
1540 case Expression::kIndex_Kind: {
1541 const IndexExpression& idx = (const IndexExpression&) e;
1542 return this->requirements(*idx.fBase) | this->requirements(*idx.fIndex);
1543 }
1544 case Expression::kPrefix_Kind:
1545 return this->requirements(*((const PrefixExpression&) e).fOperand);
1546 case Expression::kPostfix_Kind:
1547 return this->requirements(*((const PostfixExpression&) e).fOperand);
1548 case Expression::kTernary_Kind: {
1549 const TernaryExpression& t = (const TernaryExpression&) e;
1550 return this->requirements(*t.fTest) | this->requirements(*t.fIfTrue) |
1551 this->requirements(*t.fIfFalse);
1552 }
1553 case Expression::kVariableReference_Kind: {
1554 const VariableReference& v = (const VariableReference&) e;
1555 Requirements result = kNo_Requirements;
1556 if (v.fVariable.fModifiers.fLayout.fBuiltin == SK_FRAGCOORD_BUILTIN) {
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -04001557 result = kGlobals_Requirement | kFragCoord_Requirement;
Ethan Nicholascc305772017-10-13 16:17:45 -04001558 } else if (Variable::kGlobal_Storage == v.fVariable.fStorage) {
1559 if (v.fVariable.fModifiers.fFlags & Modifiers::kIn_Flag) {
1560 result = kInputs_Requirement;
1561 } else if (v.fVariable.fModifiers.fFlags & Modifiers::kOut_Flag) {
1562 result = kOutputs_Requirement;
Timothy Lianga06f2152018-05-24 15:33:31 -04001563 } else if (v.fVariable.fModifiers.fFlags & Modifiers::kUniform_Flag &&
1564 v.fVariable.fType.kind() != Type::kSampler_Kind) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001565 result = kUniforms_Requirement;
Timothy Liangee84fe12018-05-18 14:38:19 -04001566 } else {
1567 result = kGlobals_Requirement;
Ethan Nicholascc305772017-10-13 16:17:45 -04001568 }
1569 }
1570 return result;
1571 }
1572 default:
1573 return kNo_Requirements;
1574 }
1575}
1576
1577MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const Statement& s) {
1578 switch (s.fKind) {
1579 case Statement::kBlock_Kind: {
1580 Requirements result = kNo_Requirements;
1581 for (const auto& child : ((const Block&) s).fStatements) {
1582 result |= this->requirements(*child);
1583 }
1584 return result;
1585 }
Timothy Liang7d637782018-06-05 09:58:07 -04001586 case Statement::kVarDeclaration_Kind: {
1587 Requirements result = kNo_Requirements;
1588 const VarDeclaration& var = (const VarDeclaration&) s;
1589 if (var.fValue) {
1590 result = this->requirements(*var.fValue);
1591 }
1592 return result;
1593 }
1594 case Statement::kVarDeclarations_Kind: {
1595 Requirements result = kNo_Requirements;
1596 const VarDeclarations& decls = *((const VarDeclarationsStatement&) s).fDeclaration;
1597 for (const auto& stmt : decls.fVars) {
1598 result |= this->requirements(*stmt);
1599 }
1600 return result;
1601 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001602 case Statement::kExpression_Kind:
1603 return this->requirements(*((const ExpressionStatement&) s).fExpression);
1604 case Statement::kReturn_Kind: {
1605 const ReturnStatement& r = (const ReturnStatement&) s;
1606 if (r.fExpression) {
1607 return this->requirements(*r.fExpression);
1608 }
1609 return kNo_Requirements;
1610 }
1611 case Statement::kIf_Kind: {
1612 const IfStatement& i = (const IfStatement&) s;
1613 return this->requirements(*i.fTest) |
1614 this->requirements(*i.fIfTrue) |
1615 (i.fIfFalse && this->requirements(*i.fIfFalse));
1616 }
1617 case Statement::kFor_Kind: {
1618 const ForStatement& f = (const ForStatement&) s;
1619 return this->requirements(*f.fInitializer) |
1620 this->requirements(*f.fTest) |
1621 this->requirements(*f.fNext) |
1622 this->requirements(*f.fStatement);
1623 }
1624 case Statement::kWhile_Kind: {
1625 const WhileStatement& w = (const WhileStatement&) s;
1626 return this->requirements(*w.fTest) |
1627 this->requirements(*w.fStatement);
1628 }
1629 case Statement::kDo_Kind: {
1630 const DoStatement& d = (const DoStatement&) s;
1631 return this->requirements(*d.fTest) |
1632 this->requirements(*d.fStatement);
1633 }
1634 case Statement::kSwitch_Kind: {
1635 const SwitchStatement& sw = (const SwitchStatement&) s;
1636 Requirements result = this->requirements(*sw.fValue);
1637 for (const auto& c : sw.fCases) {
1638 for (const auto& st : c->fStatements) {
1639 result |= this->requirements(*st);
1640 }
1641 }
1642 return result;
1643 }
1644 default:
1645 return kNo_Requirements;
1646 }
1647}
1648
1649MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const FunctionDeclaration& f) {
1650 if (f.fBuiltin) {
1651 return kNo_Requirements;
1652 }
1653 auto found = fRequirements.find(&f);
1654 if (found == fRequirements.end()) {
Ethan Nicholas65a8f562019-04-19 14:00:26 -04001655 fRequirements[&f] = kNo_Requirements;
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001656 for (const auto& e : fProgram) {
1657 if (ProgramElement::kFunction_Kind == e.fKind) {
1658 const FunctionDefinition& def = (const FunctionDefinition&) e;
Ethan Nicholascc305772017-10-13 16:17:45 -04001659 if (&def.fDeclaration == &f) {
1660 Requirements reqs = this->requirements(*def.fBody);
1661 fRequirements[&f] = reqs;
1662 return reqs;
1663 }
1664 }
1665 }
1666 }
1667 return found->second;
1668}
1669
Timothy Liangb8eeb802018-07-23 16:46:16 -04001670bool MetalCodeGenerator::generateCode() {
Ethan Nicholascc305772017-10-13 16:17:45 -04001671 OutputStream* rawOut = fOut;
1672 fOut = &fHeader;
Timothy Liangb8eeb802018-07-23 16:46:16 -04001673#ifdef SK_MOLTENVK
1674 fOut->write((const char*) &MVKMagicNum, sizeof(MVKMagicNum));
1675#endif
Ethan Nicholascc305772017-10-13 16:17:45 -04001676 fProgramKind = fProgram.fKind;
1677 this->writeHeader();
1678 this->writeUniformStruct();
1679 this->writeInputStruct();
Timothy Liang7d637782018-06-05 09:58:07 -04001680 this->writeOutputStruct();
1681 this->writeInterfaceBlocks();
Timothy Liangee84fe12018-05-18 14:38:19 -04001682 this->writeGlobalStruct();
Ethan Nicholascc305772017-10-13 16:17:45 -04001683 StringStream body;
1684 fOut = &body;
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001685 for (const auto& e : fProgram) {
1686 this->writeProgramElement(e);
Ethan Nicholascc305772017-10-13 16:17:45 -04001687 }
1688 fOut = rawOut;
1689
1690 write_stringstream(fHeader, *rawOut);
Chris Daltondba7aab2018-11-15 10:57:49 -05001691 write_stringstream(fExtraFunctions, *rawOut);
Ethan Nicholascc305772017-10-13 16:17:45 -04001692 write_stringstream(body, *rawOut);
Timothy Liangb8eeb802018-07-23 16:46:16 -04001693#ifdef SK_MOLTENVK
1694 this->write("\0");
1695#endif
Ethan Nicholascc305772017-10-13 16:17:45 -04001696 return true;
Ethan Nicholascc305772017-10-13 16:17:45 -04001697}
1698
1699}