blob: da206b4cc78438afcce505081f59121718bae7d4 [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
8#include "SkSLMetalCodeGenerator.h"
9
10#include "SkSLCompiler.h"
11#include "ir/SkSLExpressionStatement.h"
12#include "ir/SkSLExtension.h"
13#include "ir/SkSLIndexExpression.h"
14#include "ir/SkSLModifiersDeclaration.h"
15#include "ir/SkSLNop.h"
16#include "ir/SkSLVariableReference.h"
17
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) {
221 this->write("dfdy");
Ethan Nicholascc305772017-10-13 16:17:45 -0400222 } else {
Timothy Liang651286f2018-06-07 09:55:33 -0400223 this->writeName(c.fFunction.fName);
Ethan Nicholascc305772017-10-13 16:17:45 -0400224 }
225 this->write("(");
226 const char* separator = "";
227 if (this->requirements(c.fFunction) & kInputs_Requirement) {
228 this->write("_in");
229 separator = ", ";
230 }
231 if (this->requirements(c.fFunction) & kOutputs_Requirement) {
232 this->write(separator);
233 this->write("_out");
234 separator = ", ";
235 }
236 if (this->requirements(c.fFunction) & kUniforms_Requirement) {
237 this->write(separator);
238 this->write("_uniforms");
239 separator = ", ";
240 }
Timothy Liangee84fe12018-05-18 14:38:19 -0400241 if (this->requirements(c.fFunction) & kGlobals_Requirement) {
242 this->write(separator);
243 this->write("_globals");
244 separator = ", ";
245 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400246 for (size_t i = 0; i < c.fArguments.size(); ++i) {
247 const Expression& arg = *c.fArguments[i];
248 this->write(separator);
249 separator = ", ";
250 if (c.fFunction.fParameters[i]->fModifiers.fFlags & Modifiers::kOut_Flag) {
251 this->write("&");
252 }
253 this->writeExpression(arg, kSequence_Precedence);
254 }
255 this->write(")");
256}
257
Chris Daltondba7aab2018-11-15 10:57:49 -0500258void MetalCodeGenerator::writeInverseHack(const Expression& mat) {
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500259 String typeName = mat.fType.name();
260 String name = typeName + "_inverse";
261 if (mat.fType == *fContext.fFloat2x2_Type || mat.fType == *fContext.fHalf2x2_Type) {
Chris Daltondba7aab2018-11-15 10:57:49 -0500262 if (fWrittenIntrinsics.find(name) == fWrittenIntrinsics.end()) {
263 fWrittenIntrinsics.insert(name);
264 fExtraFunctions.writeText((
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500265 typeName + " " + name + "(" + typeName + " m) {"
Chris Daltondba7aab2018-11-15 10:57:49 -0500266 " return float2x2(m[1][1], -m[0][1], -m[1][0], m[0][0]) * (1/determinant(m));"
267 "}"
268 ).c_str());
269 }
270 }
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500271 else if (mat.fType == *fContext.fFloat3x3_Type || mat.fType == *fContext.fHalf3x3_Type) {
272 if (fWrittenIntrinsics.find(name) == fWrittenIntrinsics.end()) {
273 fWrittenIntrinsics.insert(name);
274 fExtraFunctions.writeText((
275 typeName + " " + name + "(" + typeName + " m) {"
276 " float a00 = m[0][0], a01 = m[0][1], a02 = m[0][2];"
277 " float a10 = m[1][0], a11 = m[1][1], a12 = m[1][2];"
278 " float a20 = m[2][0], a21 = m[2][1], a22 = m[2][2];"
279 " float b01 = a22 * a11 - a12 * a21;"
280 " float b11 = -a22 * a10 + a12 * a20;"
281 " float b21 = a21 * a10 - a11 * a20;"
282 " float det = a00 * b01 + a01 * b11 + a02 * b21;"
283 " return " + typeName +
284 " (b01, (-a22 * a01 + a02 * a21), (a12 * a01 - a02 * a11),"
285 " b11, (a22 * a00 - a02 * a20), (-a12 * a00 + a02 * a10),"
286 " b21, (-a21 * a00 + a01 * a20), (a11 * a00 - a01 * a10)) * "
287 " (1/det);"
288 "}"
289 ).c_str());
290 }
291 }
292 else if (mat.fType == *fContext.fFloat4x4_Type || mat.fType == *fContext.fHalf4x4_Type) {
293 if (fWrittenIntrinsics.find(name) == fWrittenIntrinsics.end()) {
294 fWrittenIntrinsics.insert(name);
295 fExtraFunctions.writeText((
296 typeName + " " + name + "(" + typeName + " m) {"
297 " float a00 = m[0][0], a01 = m[0][1], a02 = m[0][2], a03 = m[0][3];"
298 " float a10 = m[1][0], a11 = m[1][1], a12 = m[1][2], a13 = m[1][3];"
299 " float a20 = m[2][0], a21 = m[2][1], a22 = m[2][2], a23 = m[2][3];"
300 " float a30 = m[3][0], a31 = m[3][1], a32 = m[3][2], a33 = m[3][3];"
301 " float b00 = a00 * a11 - a01 * a10;"
302 " float b01 = a00 * a12 - a02 * a10;"
303 " float b02 = a00 * a13 - a03 * a10;"
304 " float b03 = a01 * a12 - a02 * a11;"
305 " float b04 = a01 * a13 - a03 * a11;"
306 " float b05 = a02 * a13 - a03 * a12;"
307 " float b06 = a20 * a31 - a21 * a30;"
308 " float b07 = a20 * a32 - a22 * a30;"
309 " float b08 = a20 * a33 - a23 * a30;"
310 " float b09 = a21 * a32 - a22 * a31;"
311 " float b10 = a21 * a33 - a23 * a31;"
312 " float b11 = a22 * a33 - a23 * a32;"
313 " float det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - "
314 " b04 * b07 + b05 * b06;"
315 " return " + typeName + "(a11 * b11 - a12 * b10 + a13 * b09,"
316 " a02 * b10 - a01 * b11 - a03 * b09,"
317 " a31 * b05 - a32 * b04 + a33 * b03,"
318 " a22 * b04 - a21 * b05 - a23 * b03,"
319 " a12 * b08 - a10 * b11 - a13 * b07,"
320 " a00 * b11 - a02 * b08 + a03 * b07,"
321 " a32 * b02 - a30 * b05 - a33 * b01,"
322 " a20 * b05 - a22 * b02 + a23 * b01,"
323 " a10 * b10 - a11 * b08 + a13 * b06,"
324 " a01 * b08 - a00 * b10 - a03 * b06,"
325 " a30 * b04 - a31 * b02 + a33 * b00,"
326 " a21 * b02 - a20 * b04 - a23 * b00,"
327 " a11 * b07 - a10 * b09 - a12 * b06,"
328 " a00 * b09 - a01 * b07 + a02 * b06,"
329 " a31 * b01 - a30 * b03 - a32 * b00,"
330 " a20 * b03 - a21 * b01 + a22 * b00) / det;"
331 "}"
332 ).c_str());
333 }
334 }
Chris Daltondba7aab2018-11-15 10:57:49 -0500335 this->write(name);
336}
337
Timothy Liang6403b0e2018-05-17 10:40:04 -0400338void MetalCodeGenerator::writeSpecialIntrinsic(const FunctionCall & c, SpecialIntrinsic kind) {
339 switch (kind) {
340 case kTexture_SpecialIntrinsic:
Timothy Liangee84fe12018-05-18 14:38:19 -0400341 this->writeExpression(*c.fArguments[0], kSequence_Precedence);
Timothy Lianga06f2152018-05-24 15:33:31 -0400342 this->write(".sample(");
343 this->writeExpression(*c.fArguments[0], kSequence_Precedence);
344 this->write(SAMPLER_SUFFIX);
345 this->write(", ");
Timothy Liang6403b0e2018-05-17 10:40:04 -0400346 this->writeExpression(*c.fArguments[1], kSequence_Precedence);
Timothy Liangee84fe12018-05-18 14:38:19 -0400347 if (c.fArguments[1]->fType == *fContext.fFloat3_Type) {
348 this->write(".xy)"); // FIXME - add projection functionality
349 } else {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400350 SkASSERT(c.fArguments[1]->fType == *fContext.fFloat2_Type);
Timothy Liangee84fe12018-05-18 14:38:19 -0400351 this->write(")");
352 }
Timothy Liang6403b0e2018-05-17 10:40:04 -0400353 break;
Timothy Liang651286f2018-06-07 09:55:33 -0400354 case kMod_SpecialIntrinsic:
355 // fmod(x, y) in metal calculates x - y * trunc(x / y) instead of x - y * floor(x / y)
356 this->write("((");
357 this->writeExpression(*c.fArguments[0], kSequence_Precedence);
358 this->write(") - (");
359 this->writeExpression(*c.fArguments[1], kSequence_Precedence);
360 this->write(") * floor((");
361 this->writeExpression(*c.fArguments[0], kSequence_Precedence);
362 this->write(") / (");
363 this->writeExpression(*c.fArguments[1], kSequence_Precedence);
364 this->write(")))");
365 break;
Timothy Liang6403b0e2018-05-17 10:40:04 -0400366 default:
367 ABORT("unsupported special intrinsic kind");
368 }
369}
370
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500371// If it hasn't already been written, writes a constructor for 'matrix' which takes a single value
372// of type 'arg'.
373String MetalCodeGenerator::getMatrixConstructHelper(const Type& matrix, const Type& arg) {
374 String key = matrix.name() + arg.name();
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500375 auto found = fHelpers.find(key);
376 if (found != fHelpers.end()) {
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500377 return found->second;
Ethan Nicholascc305772017-10-13 16:17:45 -0400378 }
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500379 String name;
380 int columns = matrix.columns();
381 int rows = matrix.rows();
382 if (arg.isNumber()) {
383 // creating a matrix from a single scalar value
384 name = "float" + to_string(columns) + "x" + to_string(rows) + "_from_float";
385 fExtraFunctions.printf("float%dx%d %s(float x) {\n",
386 columns, rows, name.c_str());
387 fExtraFunctions.printf(" return float%dx%d(", columns, rows);
388 for (int i = 0; i < columns; ++i) {
389 if (i > 0) {
390 fExtraFunctions.writeText(", ");
391 }
392 fExtraFunctions.printf("float%d(", rows);
393 for (int j = 0; j < rows; ++j) {
394 if (j > 0) {
395 fExtraFunctions.writeText(", ");
396 }
397 if (i == j) {
398 fExtraFunctions.writeText("x");
399 } else {
400 fExtraFunctions.writeText("0");
401 }
402 }
403 fExtraFunctions.writeText(")");
404 }
405 fExtraFunctions.writeText(");\n}\n");
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500406 } else if (arg.kind() == Type::kMatrix_Kind) {
407 // creating a matrix from another matrix
408 int argColumns = arg.columns();
409 int argRows = arg.rows();
410 name = "float" + to_string(columns) + "x" + to_string(rows) + "_from_float" +
411 to_string(argColumns) + "x" + to_string(argRows);
412 fExtraFunctions.printf("float%dx%d %s(float%dx%d m) {\n",
413 columns, rows, name.c_str(), argColumns, argRows);
414 fExtraFunctions.printf(" return float%dx%d(", columns, rows);
415 for (int i = 0; i < columns; ++i) {
416 if (i > 0) {
417 fExtraFunctions.writeText(", ");
418 }
419 fExtraFunctions.printf("float%d(", rows);
420 for (int j = 0; j < rows; ++j) {
421 if (j > 0) {
422 fExtraFunctions.writeText(", ");
423 }
424 if (i < argColumns && j < argRows) {
425 fExtraFunctions.printf("m[%d][%d]", i, j);
426 } else {
427 fExtraFunctions.writeText("0");
428 }
429 }
430 fExtraFunctions.writeText(")");
431 }
432 fExtraFunctions.writeText(");\n}\n");
433 } else if (matrix.rows() == 2 && matrix.columns() == 2 && arg == *fContext.fFloat4_Type) {
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500434 // float2x2(float4) doesn't work, need to split it into float2x2(float2, float2)
435 name = "float2x2_from_float4";
436 fExtraFunctions.printf(
437 "float2x2 %s(float4 v) {\n"
438 " return float2x2(float2(v[0], v[1]), float2(v[2], v[3]));\n"
439 "}\n",
440 name.c_str()
441 );
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500442 } else {
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500443 SkASSERT(false);
444 name = "<error>";
445 }
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500446 fHelpers[key] = name;
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500447 return name;
448}
449
450bool MetalCodeGenerator::canCoerce(const Type& t1, const Type& t2) {
451 if (t1.columns() != t2.columns() || t1.rows() != t2.rows()) {
452 return false;
453 }
454 if (t1.columns() > 1) {
455 return this->canCoerce(t1.componentType(), t2.componentType());
456 }
Ethan Nicholase1f55022019-02-05 17:17:40 -0500457 return t1.isFloat() && t2.isFloat();
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500458}
459
460void MetalCodeGenerator::writeConstructor(const Constructor& c, Precedence parentPrecedence) {
461 if (c.fArguments.size() == 1 && this->canCoerce(c.fType, c.fArguments[0]->fType)) {
462 this->writeExpression(*c.fArguments[0], parentPrecedence);
463 return;
464 }
465 if (c.fType.kind() == Type::kMatrix_Kind && c.fArguments.size() == 1) {
466 const Expression& arg = *c.fArguments[0];
467 String name = this->getMatrixConstructHelper(c.fType, arg.fType);
468 this->write(name);
469 this->write("(");
470 this->writeExpression(arg, kSequence_Precedence);
471 this->write(")");
472 } else {
473 this->writeType(c.fType);
474 this->write("(");
475 const char* separator = "";
476 int scalarCount = 0;
477 for (const auto& arg : c.fArguments) {
478 this->write(separator);
479 separator = ", ";
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500480 if (Type::kMatrix_Kind == c.fType.kind() && arg->fType.columns() != c.fType.rows()) {
481 // merge scalars and smaller vectors together
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500482 if (!scalarCount) {
483 this->writeType(c.fType.componentType());
484 this->write(to_string(c.fType.rows()));
485 this->write("(");
486 }
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500487 scalarCount += arg->fType.columns();
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500488 }
489 this->writeExpression(*arg, kSequence_Precedence);
490 if (scalarCount && scalarCount == c.fType.rows()) {
491 this->write(")");
492 scalarCount = 0;
493 }
494 }
495 this->write(")");
496 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400497}
498
499void MetalCodeGenerator::writeFragCoord() {
Jim Van Verth6bc650e2019-02-07 14:53:23 -0500500 if (fProgram.fInputs.fRTHeight) {
501 this->write("float4(_fragCoord.x, _anonInterface0.u_skRTHeight - _fragCoord.y, 0.0, "
502 "_fragCoord.w)");
503 } else {
504 this->write("float4(_fragCoord.x, _fragCoord.y, 0.0, _fragCoord.w)");
505 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400506}
507
508void MetalCodeGenerator::writeVariableReference(const VariableReference& ref) {
509 switch (ref.fVariable.fModifiers.fLayout.fBuiltin) {
510 case SK_FRAGCOLOR_BUILTIN:
Timothy Liang7d637782018-06-05 09:58:07 -0400511 this->write("_out->sk_FragColor");
Ethan Nicholascc305772017-10-13 16:17:45 -0400512 break;
Timothy Liang6403b0e2018-05-17 10:40:04 -0400513 case SK_FRAGCOORD_BUILTIN:
514 this->writeFragCoord();
515 break;
Timothy Liangdc89f192018-06-13 09:20:31 -0400516 case SK_VERTEXID_BUILTIN:
517 this->write("sk_VertexID");
518 break;
519 case SK_INSTANCEID_BUILTIN:
520 this->write("sk_InstanceID");
521 break;
Timothy Liang7b8875d2018-08-10 09:42:31 -0400522 case SK_CLOCKWISE_BUILTIN:
523 // We'd set the front facing winding in the MTLRenderCommandEncoder to be counter
524 // clockwise to match Skia convention. This is also the default in MoltenVK.
525 this->write(fProgram.fSettings.fFlipY ? "_frontFacing" : "(!_frontFacing)");
526 break;
Ethan Nicholascc305772017-10-13 16:17:45 -0400527 default:
528 if (Variable::kGlobal_Storage == ref.fVariable.fStorage) {
529 if (ref.fVariable.fModifiers.fFlags & Modifiers::kIn_Flag) {
530 this->write("_in.");
531 } else if (ref.fVariable.fModifiers.fFlags & Modifiers::kOut_Flag) {
Timothy Liangee84fe12018-05-18 14:38:19 -0400532 this->write("_out->");
Timothy Lianga06f2152018-05-24 15:33:31 -0400533 } else if (ref.fVariable.fModifiers.fFlags & Modifiers::kUniform_Flag &&
534 ref.fVariable.fType.kind() != Type::kSampler_Kind) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400535 this->write("_uniforms.");
536 } else {
Timothy Liangee84fe12018-05-18 14:38:19 -0400537 this->write("_globals->");
Ethan Nicholascc305772017-10-13 16:17:45 -0400538 }
539 }
Timothy Liang651286f2018-06-07 09:55:33 -0400540 this->writeName(ref.fVariable.fName);
Ethan Nicholascc305772017-10-13 16:17:45 -0400541 }
542}
543
544void MetalCodeGenerator::writeIndexExpression(const IndexExpression& expr) {
545 this->writeExpression(*expr.fBase, kPostfix_Precedence);
546 this->write("[");
547 this->writeExpression(*expr.fIndex, kTopLevel_Precedence);
548 this->write("]");
549}
550
551void MetalCodeGenerator::writeFieldAccess(const FieldAccess& f) {
Timothy Liang7d637782018-06-05 09:58:07 -0400552 const Type::Field* field = &f.fBase->fType.fields()[f.fFieldIndex];
Ethan Nicholascc305772017-10-13 16:17:45 -0400553 if (FieldAccess::kDefault_OwnerKind == f.fOwnerKind) {
554 this->writeExpression(*f.fBase, kPostfix_Precedence);
555 this->write(".");
556 }
Timothy Liang7d637782018-06-05 09:58:07 -0400557 switch (field->fModifiers.fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400558 case SK_CLIPDISTANCE_BUILTIN:
559 this->write("gl_ClipDistance");
560 break;
561 case SK_POSITION_BUILTIN:
Timothy Liangb8eeb802018-07-23 16:46:16 -0400562 this->write("_out->sk_Position");
Ethan Nicholascc305772017-10-13 16:17:45 -0400563 break;
564 default:
Timothy Liang7d637782018-06-05 09:58:07 -0400565 if (field->fName == "sk_PointSize") {
566 this->write("_out->sk_PointSize");
567 } else {
568 if (FieldAccess::kAnonymousInterfaceBlock_OwnerKind == f.fOwnerKind) {
569 this->write("_globals->");
570 this->write(fInterfaceBlockNameMap[fInterfaceBlockMap[field]]);
571 this->write("->");
572 }
Timothy Liang651286f2018-06-07 09:55:33 -0400573 this->writeName(field->fName);
Timothy Lianga06f2152018-05-24 15:33:31 -0400574 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400575 }
576}
577
578void MetalCodeGenerator::writeSwizzle(const Swizzle& swizzle) {
579 this->writeExpression(*swizzle.fBase, kPostfix_Precedence);
580 this->write(".");
581 for (int c : swizzle.fComponents) {
582 this->write(&("x\0y\0z\0w\0"[c * 2]));
583 }
584}
585
586MetalCodeGenerator::Precedence MetalCodeGenerator::GetBinaryPrecedence(Token::Kind op) {
587 switch (op) {
588 case Token::STAR: // fall through
589 case Token::SLASH: // fall through
590 case Token::PERCENT: return MetalCodeGenerator::kMultiplicative_Precedence;
591 case Token::PLUS: // fall through
592 case Token::MINUS: return MetalCodeGenerator::kAdditive_Precedence;
593 case Token::SHL: // fall through
594 case Token::SHR: return MetalCodeGenerator::kShift_Precedence;
595 case Token::LT: // fall through
596 case Token::GT: // fall through
597 case Token::LTEQ: // fall through
598 case Token::GTEQ: return MetalCodeGenerator::kRelational_Precedence;
599 case Token::EQEQ: // fall through
600 case Token::NEQ: return MetalCodeGenerator::kEquality_Precedence;
601 case Token::BITWISEAND: return MetalCodeGenerator::kBitwiseAnd_Precedence;
602 case Token::BITWISEXOR: return MetalCodeGenerator::kBitwiseXor_Precedence;
603 case Token::BITWISEOR: return MetalCodeGenerator::kBitwiseOr_Precedence;
604 case Token::LOGICALAND: return MetalCodeGenerator::kLogicalAnd_Precedence;
605 case Token::LOGICALXOR: return MetalCodeGenerator::kLogicalXor_Precedence;
606 case Token::LOGICALOR: return MetalCodeGenerator::kLogicalOr_Precedence;
607 case Token::EQ: // fall through
608 case Token::PLUSEQ: // fall through
609 case Token::MINUSEQ: // fall through
610 case Token::STAREQ: // fall through
611 case Token::SLASHEQ: // fall through
612 case Token::PERCENTEQ: // fall through
613 case Token::SHLEQ: // fall through
614 case Token::SHREQ: // fall through
615 case Token::LOGICALANDEQ: // fall through
616 case Token::LOGICALXOREQ: // fall through
617 case Token::LOGICALOREQ: // fall through
618 case Token::BITWISEANDEQ: // fall through
619 case Token::BITWISEXOREQ: // fall through
620 case Token::BITWISEOREQ: return MetalCodeGenerator::kAssignment_Precedence;
621 case Token::COMMA: return MetalCodeGenerator::kSequence_Precedence;
622 default: ABORT("unsupported binary operator");
623 }
624}
625
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500626void MetalCodeGenerator::writeMatrixTimesEqualHelper(const Type& left, const Type& right,
627 const Type& result) {
628 String key = "TimesEqual" + left.name() + right.name();
629 if (fHelpers.find(key) == fHelpers.end()) {
630 fExtraFunctions.printf("%s operator*=(thread %s& left, thread const %s& right) {\n"
631 " left = left * right;\n"
632 " return left;\n"
633 "}", result.name().c_str(), left.name().c_str(),
634 right.name().c_str());
635 }
636}
637
Ethan Nicholascc305772017-10-13 16:17:45 -0400638void MetalCodeGenerator::writeBinaryExpression(const BinaryExpression& b,
639 Precedence parentPrecedence) {
640 Precedence precedence = GetBinaryPrecedence(b.fOperator);
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500641 bool needParens = precedence >= parentPrecedence;
642 switch (b.fOperator) {
643 case Token::EQEQ:
644 if (b.fLeft->fType.kind() == Type::kVector_Kind) {
645 this->write("all");
646 needParens = true;
647 }
648 break;
649 case Token::NEQ:
650 if (b.fLeft->fType.kind() == Type::kVector_Kind) {
651 this->write("!all");
652 needParens = true;
653 }
654 break;
655 default:
656 break;
657 }
658 if (needParens) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400659 this->write("(");
660 }
661 if (Compiler::IsAssignment(b.fOperator) &&
662 Expression::kVariableReference_Kind == b.fLeft->fKind &&
663 Variable::kParameter_Storage == ((VariableReference&) *b.fLeft).fVariable.fStorage &&
664 (((VariableReference&) *b.fLeft).fVariable.fModifiers.fFlags & Modifiers::kOut_Flag)) {
665 // writing to an out parameter. Since we have to turn those into pointers, we have to
666 // dereference it here.
667 this->write("*");
668 }
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500669 if (b.fOperator == Token::STAREQ && b.fLeft->fType.kind() == Type::kMatrix_Kind &&
670 b.fRight->fType.kind() == Type::kMatrix_Kind) {
671 this->writeMatrixTimesEqualHelper(b.fLeft->fType, b.fRight->fType, b.fType);
672 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400673 this->writeExpression(*b.fLeft, precedence);
674 if (b.fOperator != Token::EQ && Compiler::IsAssignment(b.fOperator) &&
675 Expression::kSwizzle_Kind == b.fLeft->fKind && !b.fLeft->hasSideEffects()) {
676 // This doesn't compile in Metal:
677 // float4 x = float4(1);
678 // x.xy *= float2x2(...);
679 // with the error message "non-const reference cannot bind to vector element",
680 // but switching it to x.xy = x.xy * float2x2(...) fixes it. We perform this tranformation
681 // as long as the LHS has no side effects, and hope for the best otherwise.
682 this->write(" = ");
683 this->writeExpression(*b.fLeft, kAssignment_Precedence);
684 this->write(" ");
685 String op = Compiler::OperatorName(b.fOperator);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400686 SkASSERT(op.endsWith("="));
Ethan Nicholascc305772017-10-13 16:17:45 -0400687 this->write(op.substr(0, op.size() - 1).c_str());
688 this->write(" ");
689 } else {
690 this->write(String(" ") + Compiler::OperatorName(b.fOperator) + " ");
691 }
692 this->writeExpression(*b.fRight, precedence);
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500693 if (needParens) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400694 this->write(")");
695 }
696}
697
698void MetalCodeGenerator::writeTernaryExpression(const TernaryExpression& t,
699 Precedence parentPrecedence) {
700 if (kTernary_Precedence >= parentPrecedence) {
701 this->write("(");
702 }
703 this->writeExpression(*t.fTest, kTernary_Precedence);
704 this->write(" ? ");
705 this->writeExpression(*t.fIfTrue, kTernary_Precedence);
706 this->write(" : ");
707 this->writeExpression(*t.fIfFalse, kTernary_Precedence);
708 if (kTernary_Precedence >= parentPrecedence) {
709 this->write(")");
710 }
711}
712
713void MetalCodeGenerator::writePrefixExpression(const PrefixExpression& p,
714 Precedence parentPrecedence) {
715 if (kPrefix_Precedence >= parentPrecedence) {
716 this->write("(");
717 }
718 this->write(Compiler::OperatorName(p.fOperator));
719 this->writeExpression(*p.fOperand, kPrefix_Precedence);
720 if (kPrefix_Precedence >= parentPrecedence) {
721 this->write(")");
722 }
723}
724
725void MetalCodeGenerator::writePostfixExpression(const PostfixExpression& p,
726 Precedence parentPrecedence) {
727 if (kPostfix_Precedence >= parentPrecedence) {
728 this->write("(");
729 }
730 this->writeExpression(*p.fOperand, kPostfix_Precedence);
731 this->write(Compiler::OperatorName(p.fOperator));
732 if (kPostfix_Precedence >= parentPrecedence) {
733 this->write(")");
734 }
735}
736
737void MetalCodeGenerator::writeBoolLiteral(const BoolLiteral& b) {
738 this->write(b.fValue ? "true" : "false");
739}
740
741void MetalCodeGenerator::writeIntLiteral(const IntLiteral& i) {
742 if (i.fType == *fContext.fUInt_Type) {
743 this->write(to_string(i.fValue & 0xffffffff) + "u");
744 } else {
745 this->write(to_string((int32_t) i.fValue));
746 }
747}
748
749void MetalCodeGenerator::writeFloatLiteral(const FloatLiteral& f) {
750 this->write(to_string(f.fValue));
751}
752
753void MetalCodeGenerator::writeSetting(const Setting& s) {
754 ABORT("internal error; setting was not folded to a constant during compilation\n");
755}
756
757void MetalCodeGenerator::writeFunction(const FunctionDefinition& f) {
758 const char* separator = "";
759 if ("main" == f.fDeclaration.fName) {
760 switch (fProgram.fKind) {
761 case Program::kFragment_Kind:
Timothy Liangb8eeb802018-07-23 16:46:16 -0400762#ifdef SK_MOLTENVK
763 this->write("fragment Outputs main0");
764#else
765 this->write("fragment Outputs fragmentMain");
766#endif
Ethan Nicholascc305772017-10-13 16:17:45 -0400767 break;
768 case Program::kVertex_Kind:
Timothy Liangb8eeb802018-07-23 16:46:16 -0400769#ifdef SK_MOLTENVK
Timothy Lianga06f2152018-05-24 15:33:31 -0400770 this->write("vertex Outputs main0");
Timothy Liangb8eeb802018-07-23 16:46:16 -0400771#else
772 this->write("vertex Outputs vertexMain");
773#endif
Ethan Nicholascc305772017-10-13 16:17:45 -0400774 break;
775 default:
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400776 SkASSERT(false);
Ethan Nicholascc305772017-10-13 16:17:45 -0400777 }
778 this->write("(Inputs _in [[stage_in]]");
779 if (-1 != fUniformBuffer) {
780 this->write(", constant Uniforms& _uniforms [[buffer(" +
781 to_string(fUniformBuffer) + ")]]");
782 }
Timothy Liang6403b0e2018-05-17 10:40:04 -0400783 for (const auto& e : fProgram) {
784 if (ProgramElement::kVar_Kind == e.fKind) {
785 VarDeclarations& decls = (VarDeclarations&) e;
786 if (!decls.fVars.size()) {
787 continue;
788 }
Timothy Liangee84fe12018-05-18 14:38:19 -0400789 for (const auto& stmt: decls.fVars) {
Timothy Liang6403b0e2018-05-17 10:40:04 -0400790 VarDeclaration& var = (VarDeclaration&) *stmt;
Timothy Liangee84fe12018-05-18 14:38:19 -0400791 if (var.fVar->fType.kind() == Type::kSampler_Kind) {
Timothy Liang7d637782018-06-05 09:58:07 -0400792 this->write(", texture2d<float> "); // FIXME - support other texture types
Timothy Liang651286f2018-06-07 09:55:33 -0400793 this->writeName(var.fVar->fName);
Timothy Liangee84fe12018-05-18 14:38:19 -0400794 this->write("[[texture(");
Timothy Lianga06f2152018-05-24 15:33:31 -0400795 this->write(to_string(var.fVar->fModifiers.fLayout.fBinding));
796 this->write(")]]");
797 this->write(", sampler ");
Timothy Liang651286f2018-06-07 09:55:33 -0400798 this->writeName(var.fVar->fName);
Timothy Lianga06f2152018-05-24 15:33:31 -0400799 this->write(SAMPLER_SUFFIX);
800 this->write("[[sampler(");
801 this->write(to_string(var.fVar->fModifiers.fLayout.fBinding));
Timothy Liangee84fe12018-05-18 14:38:19 -0400802 this->write(")]]");
803 }
Timothy Liang6403b0e2018-05-17 10:40:04 -0400804 }
Timothy Lianga06f2152018-05-24 15:33:31 -0400805 } else if (ProgramElement::kInterfaceBlock_Kind == e.fKind) {
806 InterfaceBlock& intf = (InterfaceBlock&) e;
807 if ("sk_PerVertex" == intf.fTypeName) {
808 continue;
809 }
810 this->write(", constant ");
811 this->writeType(intf.fVariable.fType);
812 this->write("& " );
813 this->write(fInterfaceBlockNameMap[&intf]);
814 this->write(" [[buffer(");
Timothy Liang057c3902018-08-08 10:48:45 -0400815#ifdef SK_MOLTENVK
Timothy Liang7d637782018-06-05 09:58:07 -0400816 this->write(to_string(intf.fVariable.fModifiers.fLayout.fSet));
Timothy Liang057c3902018-08-08 10:48:45 -0400817#else
818 this->write(to_string(intf.fVariable.fModifiers.fLayout.fBinding));
819#endif
Timothy Lianga06f2152018-05-24 15:33:31 -0400820 this->write(")]]");
Timothy Liang6403b0e2018-05-17 10:40:04 -0400821 }
822 }
Jim Van Verth6bc650e2019-02-07 14:53:23 -0500823 if (fProgram.fKind == Program::kFragment_Kind) {
824 if (fProgram.fInputs.fRTHeight && fInterfaceBlockNameMap.empty()) {
Timothy Liang5422f9a2018-08-10 10:57:55 -0400825#ifdef SK_MOLTENVK
826 this->write(", constant sksl_synthetic_uniforms& _anonInterface0 [[buffer(0)]]");
827#else
828 this->write(", constant sksl_synthetic_uniforms& _anonInterface0 [[buffer(1)]]");
829#endif
830 }
Timothy Liang7b8875d2018-08-10 09:42:31 -0400831 this->write(", bool _frontFacing [[front_facing]]");
Timothy Liang7d637782018-06-05 09:58:07 -0400832 this->write(", float4 _fragCoord [[position]]");
Timothy Liangdc89f192018-06-13 09:20:31 -0400833 } else if (fProgram.fKind == Program::kVertex_Kind) {
834 this->write(", uint sk_VertexID [[vertex_id]], uint sk_InstanceID [[instance_id]]");
Timothy Liang7d637782018-06-05 09:58:07 -0400835 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400836 separator = ", ";
837 } else {
838 this->writeType(f.fDeclaration.fReturnType);
Timothy Liang651286f2018-06-07 09:55:33 -0400839 this->write(" ");
840 this->writeName(f.fDeclaration.fName);
841 this->write("(");
Ethan Nicholascc305772017-10-13 16:17:45 -0400842 if (this->requirements(f.fDeclaration) & kInputs_Requirement) {
843 this->write("Inputs _in");
844 separator = ", ";
845 }
846 if (this->requirements(f.fDeclaration) & kOutputs_Requirement) {
847 this->write(separator);
Timothy Liangee84fe12018-05-18 14:38:19 -0400848 this->write("thread Outputs* _out");
Ethan Nicholascc305772017-10-13 16:17:45 -0400849 separator = ", ";
850 }
851 if (this->requirements(f.fDeclaration) & kUniforms_Requirement) {
852 this->write(separator);
853 this->write("Uniforms _uniforms");
854 separator = ", ";
855 }
Timothy Liangee84fe12018-05-18 14:38:19 -0400856 if (this->requirements(f.fDeclaration) & kGlobals_Requirement) {
857 this->write(separator);
858 this->write("thread Globals* _globals");
859 separator = ", ";
860 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400861 }
862 for (const auto& param : f.fDeclaration.fParameters) {
863 this->write(separator);
864 separator = ", ";
865 this->writeModifiers(param->fModifiers, false);
866 std::vector<int> sizes;
867 const Type* type = &param->fType;
868 while (Type::kArray_Kind == type->kind()) {
869 sizes.push_back(type->columns());
870 type = &type->componentType();
871 }
872 this->writeType(*type);
873 if (param->fModifiers.fFlags & Modifiers::kOut_Flag) {
874 this->write("*");
875 }
Timothy Liang651286f2018-06-07 09:55:33 -0400876 this->write(" ");
877 this->writeName(param->fName);
Ethan Nicholascc305772017-10-13 16:17:45 -0400878 for (int s : sizes) {
879 if (s <= 0) {
880 this->write("[]");
881 } else {
882 this->write("[" + to_string(s) + "]");
883 }
884 }
885 }
886 this->writeLine(") {");
887
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400888 SkASSERT(!fProgram.fSettings.fFragColorIsInOut);
Brian Salomondc092132018-04-04 10:14:16 -0400889
Ethan Nicholascc305772017-10-13 16:17:45 -0400890 if ("main" == f.fDeclaration.fName) {
Timothy Liangee84fe12018-05-18 14:38:19 -0400891 if (fNeedsGlobalStructInit) {
892 this->writeLine(" Globals globalStruct;");
893 this->writeLine(" thread Globals* _globals = &globalStruct;");
Timothy Liang7d637782018-06-05 09:58:07 -0400894 for (const auto& intf: fInterfaceBlockNameMap) {
895 const auto& intfName = intf.second;
896 this->write(" _globals->");
Timothy Liang651286f2018-06-07 09:55:33 -0400897 this->writeName(intfName);
Timothy Liang7d637782018-06-05 09:58:07 -0400898 this->write(" = &");
Timothy Liang651286f2018-06-07 09:55:33 -0400899 this->writeName(intfName);
Timothy Liang7d637782018-06-05 09:58:07 -0400900 this->write(";\n");
901 }
Timothy Lianga06f2152018-05-24 15:33:31 -0400902 for (const auto& var: fInitNonConstGlobalVars) {
Timothy Liangee84fe12018-05-18 14:38:19 -0400903 this->write(" _globals->");
Timothy Liang651286f2018-06-07 09:55:33 -0400904 this->writeName(var->fVar->fName);
Timothy Liangee84fe12018-05-18 14:38:19 -0400905 this->write(" = ");
906 this->writeVarInitializer(*var->fVar, *var->fValue);
907 this->writeLine(";");
908 }
Timothy Lianga06f2152018-05-24 15:33:31 -0400909 for (const auto& texture: fTextures) {
Timothy Liangee84fe12018-05-18 14:38:19 -0400910 this->write(" _globals->");
Timothy Liang651286f2018-06-07 09:55:33 -0400911 this->writeName(texture->fName);
Timothy Liangee84fe12018-05-18 14:38:19 -0400912 this->write(" = ");
Timothy Liang651286f2018-06-07 09:55:33 -0400913 this->writeName(texture->fName);
Timothy Lianga06f2152018-05-24 15:33:31 -0400914 this->write(";\n");
915 this->write(" _globals->");
Timothy Liang651286f2018-06-07 09:55:33 -0400916 this->writeName(texture->fName);
Timothy Lianga06f2152018-05-24 15:33:31 -0400917 this->write(SAMPLER_SUFFIX);
918 this->write(" = ");
Timothy Liang651286f2018-06-07 09:55:33 -0400919 this->writeName(texture->fName);
Timothy Lianga06f2152018-05-24 15:33:31 -0400920 this->write(SAMPLER_SUFFIX);
Timothy Liangee84fe12018-05-18 14:38:19 -0400921 this->write(";\n");
922 }
Timothy Liang6403b0e2018-05-17 10:40:04 -0400923 }
Timothy Liang7d637782018-06-05 09:58:07 -0400924 this->writeLine(" Outputs _outputStruct;");
925 this->writeLine(" thread Outputs* _out = &_outputStruct;");
Ethan Nicholascc305772017-10-13 16:17:45 -0400926 }
927 fFunctionHeader = "";
928 OutputStream* oldOut = fOut;
929 StringStream buffer;
930 fOut = &buffer;
931 fIndentation++;
932 this->writeStatements(((Block&) *f.fBody).fStatements);
933 if ("main" == f.fDeclaration.fName) {
934 switch (fProgram.fKind) {
935 case Program::kFragment_Kind:
Timothy Liang7d637782018-06-05 09:58:07 -0400936 this->writeLine("return *_out;");
Ethan Nicholascc305772017-10-13 16:17:45 -0400937 break;
938 case Program::kVertex_Kind:
Timothy Liangb8eeb802018-07-23 16:46:16 -0400939 this->writeLine("_out->sk_Position.y = -_out->sk_Position.y;");
Timothy Lianga06f2152018-05-24 15:33:31 -0400940 this->writeLine("return *_out;"); // FIXME - detect if function already has return
Ethan Nicholascc305772017-10-13 16:17:45 -0400941 break;
942 default:
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400943 SkASSERT(false);
Ethan Nicholascc305772017-10-13 16:17:45 -0400944 }
945 }
946 fIndentation--;
947 this->writeLine("}");
948
949 fOut = oldOut;
950 this->write(fFunctionHeader);
951 this->write(buffer.str());
952}
953
954void MetalCodeGenerator::writeModifiers(const Modifiers& modifiers,
955 bool globalContext) {
956 if (modifiers.fFlags & Modifiers::kOut_Flag) {
957 this->write("thread ");
958 }
959 if (modifiers.fFlags & Modifiers::kConst_Flag) {
Timothy Liangee84fe12018-05-18 14:38:19 -0400960 this->write("constant ");
Ethan Nicholascc305772017-10-13 16:17:45 -0400961 }
962}
963
964void MetalCodeGenerator::writeInterfaceBlock(const InterfaceBlock& intf) {
965 if ("sk_PerVertex" == intf.fTypeName) {
966 return;
967 }
968 this->writeModifiers(intf.fVariable.fModifiers, true);
Timothy Liangdc89f192018-06-13 09:20:31 -0400969 this->write("struct ");
Ethan Nicholascc305772017-10-13 16:17:45 -0400970 this->writeLine(intf.fTypeName + " {");
Ethan Nicholascc305772017-10-13 16:17:45 -0400971 const Type* structType = &intf.fVariable.fType;
Timothy Lianga06f2152018-05-24 15:33:31 -0400972 fWrittenStructs.push_back(structType);
Ethan Nicholascc305772017-10-13 16:17:45 -0400973 while (Type::kArray_Kind == structType->kind()) {
974 structType = &structType->componentType();
975 }
Timothy Liangdc89f192018-06-13 09:20:31 -0400976 fIndentation++;
977 writeFields(structType->fields(), structType->fOffset, &intf);
Jim Van Verth3d482992019-02-07 10:48:05 -0500978 if (fProgram.fInputs.fRTHeight) {
Timothy Liang7d637782018-06-05 09:58:07 -0400979 this->writeLine("float u_skRTHeight;");
Ethan Nicholascc305772017-10-13 16:17:45 -0400980 }
981 fIndentation--;
982 this->write("}");
983 if (intf.fInstanceName.size()) {
984 this->write(" ");
985 this->write(intf.fInstanceName);
986 for (const auto& size : intf.fSizes) {
987 this->write("[");
988 if (size) {
989 this->writeExpression(*size, kTopLevel_Precedence);
990 }
991 this->write("]");
992 }
Timothy Lianga06f2152018-05-24 15:33:31 -0400993 fInterfaceBlockNameMap[&intf] = intf.fInstanceName;
994 } else {
Timothy Liang7d637782018-06-05 09:58:07 -0400995 fInterfaceBlockNameMap[&intf] = "_anonInterface" + to_string(fAnonInterfaceCount++);
Ethan Nicholascc305772017-10-13 16:17:45 -0400996 }
997 this->writeLine(";");
998}
999
Timothy Liangdc89f192018-06-13 09:20:31 -04001000void MetalCodeGenerator::writeFields(const std::vector<Type::Field>& fields, int parentOffset,
1001 const InterfaceBlock* parentIntf) {
Timothy Liang609fbe32018-08-10 16:40:49 -04001002#ifdef SK_MOLTENVK
Timothy Liangdc89f192018-06-13 09:20:31 -04001003 MemoryLayout memoryLayout(MemoryLayout::k140_Standard);
Timothy Liang609fbe32018-08-10 16:40:49 -04001004#else
1005 MemoryLayout memoryLayout(MemoryLayout::kMetal_Standard);
1006#endif
Timothy Liangdc89f192018-06-13 09:20:31 -04001007 int currentOffset = 0;
1008 for (const auto& field: fields) {
1009 int fieldOffset = field.fModifiers.fLayout.fOffset;
1010 const Type* fieldType = field.fType;
1011 if (fieldOffset != -1) {
1012 if (currentOffset > fieldOffset) {
1013 fErrors.error(parentOffset,
1014 "offset of field '" + field.fName + "' must be at least " +
1015 to_string((int) currentOffset));
1016 } else if (currentOffset < fieldOffset) {
1017 this->write("char pad");
1018 this->write(to_string(fPaddingCount++));
1019 this->write("[");
1020 this->write(to_string(fieldOffset - currentOffset));
1021 this->writeLine("];");
1022 currentOffset = fieldOffset;
1023 }
1024 int alignment = memoryLayout.alignment(*fieldType);
1025 if (fieldOffset % alignment) {
1026 fErrors.error(parentOffset,
1027 "offset of field '" + field.fName + "' must be a multiple of " +
1028 to_string((int) alignment));
1029 }
1030 }
Timothy Liang609fbe32018-08-10 16:40:49 -04001031#ifdef SK_MOLTENVK
Timothy Liangdc89f192018-06-13 09:20:31 -04001032 if (fieldType->kind() == Type::kVector_Kind &&
1033 fieldType->columns() == 3) {
Timothy Liang609fbe32018-08-10 16:40:49 -04001034 SkASSERT(memoryLayout.size(*fieldType) == 3);
Timothy Liangdc89f192018-06-13 09:20:31 -04001035 // Pack all vec3 types so that their size in bytes will match what was expected in the
1036 // original SkSL code since MSL has vec3 sizes equal to 4 * component type, while SkSL
1037 // has vec3 equal to 3 * component type.
Timothy Liang609fbe32018-08-10 16:40:49 -04001038
1039 // FIXME - Packed vectors can't be accessed by swizzles, but can be indexed into. A
1040 // combination of this being a problem which only occurs when using MoltenVK and the
1041 // fact that we haven't swizzled a vec3 yet means that this problem hasn't been
1042 // addressed.
Timothy Liangdc89f192018-06-13 09:20:31 -04001043 this->write(PACKED_PREFIX);
1044 }
Timothy Liang609fbe32018-08-10 16:40:49 -04001045#endif
Timothy Liangdc89f192018-06-13 09:20:31 -04001046 currentOffset += memoryLayout.size(*fieldType);
1047 std::vector<int> sizes;
1048 while (fieldType->kind() == Type::kArray_Kind) {
1049 sizes.push_back(fieldType->columns());
1050 fieldType = &fieldType->componentType();
1051 }
1052 this->writeModifiers(field.fModifiers, false);
1053 this->writeType(*fieldType);
1054 this->write(" ");
1055 this->writeName(field.fName);
1056 for (int s : sizes) {
1057 if (s <= 0) {
1058 this->write("[]");
1059 } else {
1060 this->write("[" + to_string(s) + "]");
1061 }
1062 }
1063 this->writeLine(";");
1064 if (parentIntf) {
1065 fInterfaceBlockMap[&field] = parentIntf;
1066 }
1067 }
1068}
1069
Ethan Nicholascc305772017-10-13 16:17:45 -04001070void MetalCodeGenerator::writeVarInitializer(const Variable& var, const Expression& value) {
1071 this->writeExpression(value, kTopLevel_Precedence);
1072}
1073
Timothy Liang651286f2018-06-07 09:55:33 -04001074void MetalCodeGenerator::writeName(const String& name) {
1075 if (fReservedWords.find(name) != fReservedWords.end()) {
1076 this->write("_"); // adding underscore before name to avoid conflict with reserved words
1077 }
1078 this->write(name);
1079}
1080
Ethan Nicholascc305772017-10-13 16:17:45 -04001081void MetalCodeGenerator::writeVarDeclarations(const VarDeclarations& decl, bool global) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001082 SkASSERT(decl.fVars.size() > 0);
Ethan Nicholascc305772017-10-13 16:17:45 -04001083 bool wroteType = false;
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001084 for (const auto& stmt : decl.fVars) {
1085 VarDeclaration& var = (VarDeclaration&) *stmt;
Timothy Liangee84fe12018-05-18 14:38:19 -04001086 if (global && !(var.fVar->fModifiers.fFlags & Modifiers::kConst_Flag)) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001087 continue;
1088 }
1089 if (wroteType) {
1090 this->write(", ");
1091 } else {
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001092 this->writeModifiers(var.fVar->fModifiers, global);
Ethan Nicholascc305772017-10-13 16:17:45 -04001093 this->writeType(decl.fBaseType);
1094 this->write(" ");
1095 wroteType = true;
1096 }
Timothy Liang651286f2018-06-07 09:55:33 -04001097 this->writeName(var.fVar->fName);
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001098 for (const auto& size : var.fSizes) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001099 this->write("[");
1100 if (size) {
1101 this->writeExpression(*size, kTopLevel_Precedence);
1102 }
1103 this->write("]");
1104 }
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001105 if (var.fValue) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001106 this->write(" = ");
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001107 this->writeVarInitializer(*var.fVar, *var.fValue);
Ethan Nicholascc305772017-10-13 16:17:45 -04001108 }
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001109 if (!fFoundImageDecl && var.fVar->fType == *fContext.fImage2D_Type) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001110 if (fProgram.fSettings.fCaps->imageLoadStoreExtensionString()) {
1111 fHeader.writeText("#extension ");
1112 fHeader.writeText(fProgram.fSettings.fCaps->imageLoadStoreExtensionString());
1113 fHeader.writeText(" : require\n");
1114 }
1115 fFoundImageDecl = true;
1116 }
1117 }
1118 if (wroteType) {
1119 this->write(";");
1120 }
1121}
1122
1123void MetalCodeGenerator::writeStatement(const Statement& s) {
1124 switch (s.fKind) {
1125 case Statement::kBlock_Kind:
1126 this->writeBlock((Block&) s);
1127 break;
1128 case Statement::kExpression_Kind:
1129 this->writeExpression(*((ExpressionStatement&) s).fExpression, kTopLevel_Precedence);
1130 this->write(";");
1131 break;
1132 case Statement::kReturn_Kind:
1133 this->writeReturnStatement((ReturnStatement&) s);
1134 break;
1135 case Statement::kVarDeclarations_Kind:
1136 this->writeVarDeclarations(*((VarDeclarationsStatement&) s).fDeclaration, false);
1137 break;
1138 case Statement::kIf_Kind:
1139 this->writeIfStatement((IfStatement&) s);
1140 break;
1141 case Statement::kFor_Kind:
1142 this->writeForStatement((ForStatement&) s);
1143 break;
1144 case Statement::kWhile_Kind:
1145 this->writeWhileStatement((WhileStatement&) s);
1146 break;
1147 case Statement::kDo_Kind:
1148 this->writeDoStatement((DoStatement&) s);
1149 break;
1150 case Statement::kSwitch_Kind:
1151 this->writeSwitchStatement((SwitchStatement&) s);
1152 break;
1153 case Statement::kBreak_Kind:
1154 this->write("break;");
1155 break;
1156 case Statement::kContinue_Kind:
1157 this->write("continue;");
1158 break;
1159 case Statement::kDiscard_Kind:
Timothy Lianga06f2152018-05-24 15:33:31 -04001160 this->write("discard_fragment();");
Ethan Nicholascc305772017-10-13 16:17:45 -04001161 break;
1162 case Statement::kNop_Kind:
1163 this->write(";");
1164 break;
1165 default:
1166 ABORT("unsupported statement: %s", s.description().c_str());
1167 }
1168}
1169
1170void MetalCodeGenerator::writeStatements(const std::vector<std::unique_ptr<Statement>>& statements) {
1171 for (const auto& s : statements) {
1172 if (!s->isEmpty()) {
1173 this->writeStatement(*s);
1174 this->writeLine();
1175 }
1176 }
1177}
1178
1179void MetalCodeGenerator::writeBlock(const Block& b) {
1180 this->writeLine("{");
1181 fIndentation++;
1182 this->writeStatements(b.fStatements);
1183 fIndentation--;
1184 this->write("}");
1185}
1186
1187void MetalCodeGenerator::writeIfStatement(const IfStatement& stmt) {
1188 this->write("if (");
1189 this->writeExpression(*stmt.fTest, kTopLevel_Precedence);
1190 this->write(") ");
1191 this->writeStatement(*stmt.fIfTrue);
1192 if (stmt.fIfFalse) {
1193 this->write(" else ");
1194 this->writeStatement(*stmt.fIfFalse);
1195 }
1196}
1197
1198void MetalCodeGenerator::writeForStatement(const ForStatement& f) {
1199 this->write("for (");
1200 if (f.fInitializer && !f.fInitializer->isEmpty()) {
1201 this->writeStatement(*f.fInitializer);
1202 } else {
1203 this->write("; ");
1204 }
1205 if (f.fTest) {
1206 this->writeExpression(*f.fTest, kTopLevel_Precedence);
1207 }
1208 this->write("; ");
1209 if (f.fNext) {
1210 this->writeExpression(*f.fNext, kTopLevel_Precedence);
1211 }
1212 this->write(") ");
1213 this->writeStatement(*f.fStatement);
1214}
1215
1216void MetalCodeGenerator::writeWhileStatement(const WhileStatement& w) {
1217 this->write("while (");
1218 this->writeExpression(*w.fTest, kTopLevel_Precedence);
1219 this->write(") ");
1220 this->writeStatement(*w.fStatement);
1221}
1222
1223void MetalCodeGenerator::writeDoStatement(const DoStatement& d) {
1224 this->write("do ");
1225 this->writeStatement(*d.fStatement);
1226 this->write(" while (");
1227 this->writeExpression(*d.fTest, kTopLevel_Precedence);
1228 this->write(");");
1229}
1230
1231void MetalCodeGenerator::writeSwitchStatement(const SwitchStatement& s) {
1232 this->write("switch (");
1233 this->writeExpression(*s.fValue, kTopLevel_Precedence);
1234 this->writeLine(") {");
1235 fIndentation++;
1236 for (const auto& c : s.fCases) {
1237 if (c->fValue) {
1238 this->write("case ");
1239 this->writeExpression(*c->fValue, kTopLevel_Precedence);
1240 this->writeLine(":");
1241 } else {
1242 this->writeLine("default:");
1243 }
1244 fIndentation++;
1245 for (const auto& stmt : c->fStatements) {
1246 this->writeStatement(*stmt);
1247 this->writeLine();
1248 }
1249 fIndentation--;
1250 }
1251 fIndentation--;
1252 this->write("}");
1253}
1254
1255void MetalCodeGenerator::writeReturnStatement(const ReturnStatement& r) {
1256 this->write("return");
1257 if (r.fExpression) {
1258 this->write(" ");
1259 this->writeExpression(*r.fExpression, kTopLevel_Precedence);
1260 }
1261 this->write(";");
1262}
1263
1264void MetalCodeGenerator::writeHeader() {
1265 this->write("#include <metal_stdlib>\n");
1266 this->write("#include <simd/simd.h>\n");
1267 this->write("using namespace metal;\n");
1268}
1269
1270void MetalCodeGenerator::writeUniformStruct() {
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001271 for (const auto& e : fProgram) {
1272 if (ProgramElement::kVar_Kind == e.fKind) {
1273 VarDeclarations& decls = (VarDeclarations&) e;
Ethan Nicholascc305772017-10-13 16:17:45 -04001274 if (!decls.fVars.size()) {
1275 continue;
1276 }
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001277 const Variable& first = *((VarDeclaration&) *decls.fVars[0]).fVar;
Timothy Lianga06f2152018-05-24 15:33:31 -04001278 if (first.fModifiers.fFlags & Modifiers::kUniform_Flag &&
1279 first.fType.kind() != Type::kSampler_Kind) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001280 if (-1 == fUniformBuffer) {
1281 this->write("struct Uniforms {\n");
1282 fUniformBuffer = first.fModifiers.fLayout.fSet;
1283 if (-1 == fUniformBuffer) {
1284 fErrors.error(decls.fOffset, "Metal uniforms must have 'layout(set=...)'");
1285 }
1286 } else if (first.fModifiers.fLayout.fSet != fUniformBuffer) {
1287 if (-1 == fUniformBuffer) {
1288 fErrors.error(decls.fOffset, "Metal backend requires all uniforms to have "
1289 "the same 'layout(set=...)'");
1290 }
1291 }
1292 this->write(" ");
1293 this->writeType(first.fType);
1294 this->write(" ");
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001295 for (const auto& stmt : decls.fVars) {
1296 VarDeclaration& var = (VarDeclaration&) *stmt;
Timothy Liang651286f2018-06-07 09:55:33 -04001297 this->writeName(var.fVar->fName);
Ethan Nicholascc305772017-10-13 16:17:45 -04001298 }
1299 this->write(";\n");
1300 }
1301 }
1302 }
1303 if (-1 != fUniformBuffer) {
1304 this->write("};\n");
1305 }
1306}
1307
1308void MetalCodeGenerator::writeInputStruct() {
1309 this->write("struct Inputs {\n");
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001310 for (const auto& e : fProgram) {
1311 if (ProgramElement::kVar_Kind == e.fKind) {
1312 VarDeclarations& decls = (VarDeclarations&) e;
Ethan Nicholascc305772017-10-13 16:17:45 -04001313 if (!decls.fVars.size()) {
1314 continue;
1315 }
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001316 const Variable& first = *((VarDeclaration&) *decls.fVars[0]).fVar;
Ethan Nicholascc305772017-10-13 16:17:45 -04001317 if (first.fModifiers.fFlags & Modifiers::kIn_Flag &&
1318 -1 == first.fModifiers.fLayout.fBuiltin) {
1319 this->write(" ");
1320 this->writeType(first.fType);
1321 this->write(" ");
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001322 for (const auto& stmt : decls.fVars) {
1323 VarDeclaration& var = (VarDeclaration&) *stmt;
Timothy Liang651286f2018-06-07 09:55:33 -04001324 this->writeName(var.fVar->fName);
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001325 if (-1 != var.fVar->fModifiers.fLayout.fLocation) {
Timothy Liang7d637782018-06-05 09:58:07 -04001326 if (fProgram.fKind == Program::kVertex_Kind) {
1327 this->write(" [[attribute(" +
1328 to_string(var.fVar->fModifiers.fLayout.fLocation) + ")]]");
1329 } else if (fProgram.fKind == Program::kFragment_Kind) {
1330 this->write(" [[user(locn" +
1331 to_string(var.fVar->fModifiers.fLayout.fLocation) + ")]]");
1332 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001333 }
1334 }
1335 this->write(";\n");
1336 }
1337 }
1338 }
1339 this->write("};\n");
1340}
1341
1342void MetalCodeGenerator::writeOutputStruct() {
1343 this->write("struct Outputs {\n");
Timothy Liang7d637782018-06-05 09:58:07 -04001344 if (fProgram.fKind == Program::kVertex_Kind) {
Timothy Liangb8eeb802018-07-23 16:46:16 -04001345 this->write(" float4 sk_Position [[position]];\n");
Timothy Liang7d637782018-06-05 09:58:07 -04001346 } else if (fProgram.fKind == Program::kFragment_Kind) {
Timothy Liangde0be802018-08-10 13:48:08 -04001347 this->write(" float4 sk_FragColor [[color(0)]];\n");
Timothy Liang7d637782018-06-05 09:58:07 -04001348 }
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001349 for (const auto& e : fProgram) {
1350 if (ProgramElement::kVar_Kind == e.fKind) {
1351 VarDeclarations& decls = (VarDeclarations&) e;
Ethan Nicholascc305772017-10-13 16:17:45 -04001352 if (!decls.fVars.size()) {
1353 continue;
1354 }
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001355 const Variable& first = *((VarDeclaration&) *decls.fVars[0]).fVar;
Ethan Nicholascc305772017-10-13 16:17:45 -04001356 if (first.fModifiers.fFlags & Modifiers::kOut_Flag &&
1357 -1 == first.fModifiers.fLayout.fBuiltin) {
1358 this->write(" ");
1359 this->writeType(first.fType);
1360 this->write(" ");
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001361 for (const auto& stmt : decls.fVars) {
1362 VarDeclaration& var = (VarDeclaration&) *stmt;
Timothy Liang651286f2018-06-07 09:55:33 -04001363 this->writeName(var.fVar->fName);
Timothy Liang7d637782018-06-05 09:58:07 -04001364 if (fProgram.fKind == Program::kVertex_Kind) {
1365 this->write(" [[user(locn" +
1366 to_string(var.fVar->fModifiers.fLayout.fLocation) + ")]]");
1367 } else if (fProgram.fKind == Program::kFragment_Kind) {
1368 this->write(" [[color(" +
Timothy Liangde0be802018-08-10 13:48:08 -04001369 to_string(var.fVar->fModifiers.fLayout.fLocation) +")");
1370 int colorIndex = var.fVar->fModifiers.fLayout.fIndex;
1371 if (colorIndex) {
1372 this->write(", index(" + to_string(colorIndex) + ")");
1373 }
1374 this->write("]]");
Timothy Liang7d637782018-06-05 09:58:07 -04001375 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001376 }
1377 this->write(";\n");
1378 }
1379 }
Timothy Liang7d637782018-06-05 09:58:07 -04001380 }
1381 if (fProgram.fKind == Program::kVertex_Kind) {
1382 this->write(" float sk_PointSize;\n");
1383 }
1384 this->write("};\n");
1385}
1386
1387void MetalCodeGenerator::writeInterfaceBlocks() {
1388 bool wroteInterfaceBlock = false;
1389 for (const auto& e : fProgram) {
1390 if (ProgramElement::kInterfaceBlock_Kind == e.fKind) {
1391 this->writeInterfaceBlock((InterfaceBlock&) e);
1392 wroteInterfaceBlock = true;
1393 }
1394 }
Jim Van Verth3d482992019-02-07 10:48:05 -05001395 if (!wroteInterfaceBlock && fProgram.fInputs.fRTHeight) {
Timothy Liang7d637782018-06-05 09:58:07 -04001396 this->writeLine("struct sksl_synthetic_uniforms {");
1397 this->writeLine(" float u_skRTHeight;");
1398 this->writeLine("};");
1399 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001400}
1401
Timothy Liangee84fe12018-05-18 14:38:19 -04001402void MetalCodeGenerator::writeGlobalStruct() {
1403 bool wroteStructDecl = false;
Timothy Liang7d637782018-06-05 09:58:07 -04001404 for (const auto& intf : fInterfaceBlockNameMap) {
1405 if (!wroteStructDecl) {
1406 this->write("struct Globals {\n");
1407 wroteStructDecl = true;
1408 }
1409 fNeedsGlobalStructInit = true;
1410 const auto& intfType = intf.first;
1411 const auto& intfName = intf.second;
1412 this->write(" constant ");
1413 this->write(intfType->fTypeName);
1414 this->write("* ");
Timothy Liang651286f2018-06-07 09:55:33 -04001415 this->writeName(intfName);
Timothy Liang7d637782018-06-05 09:58:07 -04001416 this->write(";\n");
1417 }
Timothy Liangee84fe12018-05-18 14:38:19 -04001418 for (const auto& e : fProgram) {
1419 if (ProgramElement::kVar_Kind == e.fKind) {
1420 VarDeclarations& decls = (VarDeclarations&) e;
1421 if (!decls.fVars.size()) {
1422 continue;
1423 }
1424 const Variable& first = *((VarDeclaration&) *decls.fVars[0]).fVar;
Timothy Lianga06f2152018-05-24 15:33:31 -04001425 if ((!first.fModifiers.fFlags && -1 == first.fModifiers.fLayout.fBuiltin) ||
1426 first.fType.kind() == Type::kSampler_Kind) {
Timothy Liangee84fe12018-05-18 14:38:19 -04001427 if (!wroteStructDecl) {
1428 this->write("struct Globals {\n");
1429 wroteStructDecl = true;
1430 }
1431 fNeedsGlobalStructInit = true;
1432 this->write(" ");
1433 this->writeType(first.fType);
1434 this->write(" ");
1435 for (const auto& stmt : decls.fVars) {
1436 VarDeclaration& var = (VarDeclaration&) *stmt;
Timothy Liang651286f2018-06-07 09:55:33 -04001437 this->writeName(var.fVar->fName);
Timothy Lianga06f2152018-05-24 15:33:31 -04001438 if (var.fVar->fType.kind() == Type::kSampler_Kind) {
1439 fTextures.push_back(var.fVar);
1440 this->write(";\n");
1441 this->write(" sampler ");
Timothy Liang651286f2018-06-07 09:55:33 -04001442 this->writeName(var.fVar->fName);
Timothy Lianga06f2152018-05-24 15:33:31 -04001443 this->write(SAMPLER_SUFFIX);
1444 }
Timothy Liangee84fe12018-05-18 14:38:19 -04001445 if (var.fValue) {
1446 fInitNonConstGlobalVars.push_back(&var);
1447 }
1448 }
1449 this->write(";\n");
1450 }
1451 }
1452 }
Timothy Liangee84fe12018-05-18 14:38:19 -04001453 if (wroteStructDecl) {
1454 this->write("};\n");
1455 }
1456}
1457
Ethan Nicholascc305772017-10-13 16:17:45 -04001458void MetalCodeGenerator::writeProgramElement(const ProgramElement& e) {
1459 switch (e.fKind) {
1460 case ProgramElement::kExtension_Kind:
1461 break;
1462 case ProgramElement::kVar_Kind: {
1463 VarDeclarations& decl = (VarDeclarations&) e;
1464 if (decl.fVars.size() > 0) {
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001465 int builtin = ((VarDeclaration&) *decl.fVars[0]).fVar->fModifiers.fLayout.fBuiltin;
Ethan Nicholascc305772017-10-13 16:17:45 -04001466 if (-1 == builtin) {
1467 // normal var
1468 this->writeVarDeclarations(decl, true);
1469 this->writeLine();
1470 } else if (SK_FRAGCOLOR_BUILTIN == builtin) {
1471 // ignore
1472 }
1473 }
1474 break;
1475 }
1476 case ProgramElement::kInterfaceBlock_Kind:
Timothy Liang7d637782018-06-05 09:58:07 -04001477 // handled in writeInterfaceBlocks, do nothing
Ethan Nicholascc305772017-10-13 16:17:45 -04001478 break;
1479 case ProgramElement::kFunction_Kind:
1480 this->writeFunction((FunctionDefinition&) e);
1481 break;
1482 case ProgramElement::kModifiers_Kind:
1483 this->writeModifiers(((ModifiersDeclaration&) e).fModifiers, true);
1484 this->writeLine(";");
1485 break;
1486 default:
1487 printf("%s\n", e.description().c_str());
1488 ABORT("unsupported program element");
1489 }
1490}
1491
1492MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const Expression& e) {
1493 switch (e.fKind) {
1494 case Expression::kFunctionCall_Kind: {
1495 const FunctionCall& f = (const FunctionCall&) e;
1496 Requirements result = this->requirements(f.fFunction);
1497 for (const auto& e : f.fArguments) {
1498 result |= this->requirements(*e);
1499 }
1500 return result;
1501 }
1502 case Expression::kConstructor_Kind: {
1503 const Constructor& c = (const Constructor&) e;
1504 Requirements result = kNo_Requirements;
1505 for (const auto& e : c.fArguments) {
1506 result |= this->requirements(*e);
1507 }
1508 return result;
1509 }
Timothy Liang7d637782018-06-05 09:58:07 -04001510 case Expression::kFieldAccess_Kind: {
1511 const FieldAccess& f = (const FieldAccess&) e;
1512 if (FieldAccess::kAnonymousInterfaceBlock_OwnerKind == f.fOwnerKind) {
1513 return kGlobals_Requirement;
1514 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001515 return this->requirements(*((const FieldAccess&) e).fBase);
Timothy Liang7d637782018-06-05 09:58:07 -04001516 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001517 case Expression::kSwizzle_Kind:
1518 return this->requirements(*((const Swizzle&) e).fBase);
1519 case Expression::kBinary_Kind: {
1520 const BinaryExpression& b = (const BinaryExpression&) e;
1521 return this->requirements(*b.fLeft) | this->requirements(*b.fRight);
1522 }
1523 case Expression::kIndex_Kind: {
1524 const IndexExpression& idx = (const IndexExpression&) e;
1525 return this->requirements(*idx.fBase) | this->requirements(*idx.fIndex);
1526 }
1527 case Expression::kPrefix_Kind:
1528 return this->requirements(*((const PrefixExpression&) e).fOperand);
1529 case Expression::kPostfix_Kind:
1530 return this->requirements(*((const PostfixExpression&) e).fOperand);
1531 case Expression::kTernary_Kind: {
1532 const TernaryExpression& t = (const TernaryExpression&) e;
1533 return this->requirements(*t.fTest) | this->requirements(*t.fIfTrue) |
1534 this->requirements(*t.fIfFalse);
1535 }
1536 case Expression::kVariableReference_Kind: {
1537 const VariableReference& v = (const VariableReference&) e;
1538 Requirements result = kNo_Requirements;
1539 if (v.fVariable.fModifiers.fLayout.fBuiltin == SK_FRAGCOORD_BUILTIN) {
1540 result = kInputs_Requirement;
1541 } else if (Variable::kGlobal_Storage == v.fVariable.fStorage) {
1542 if (v.fVariable.fModifiers.fFlags & Modifiers::kIn_Flag) {
1543 result = kInputs_Requirement;
1544 } else if (v.fVariable.fModifiers.fFlags & Modifiers::kOut_Flag) {
1545 result = kOutputs_Requirement;
Timothy Lianga06f2152018-05-24 15:33:31 -04001546 } else if (v.fVariable.fModifiers.fFlags & Modifiers::kUniform_Flag &&
1547 v.fVariable.fType.kind() != Type::kSampler_Kind) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001548 result = kUniforms_Requirement;
Timothy Liangee84fe12018-05-18 14:38:19 -04001549 } else {
1550 result = kGlobals_Requirement;
Ethan Nicholascc305772017-10-13 16:17:45 -04001551 }
1552 }
1553 return result;
1554 }
1555 default:
1556 return kNo_Requirements;
1557 }
1558}
1559
1560MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const Statement& s) {
1561 switch (s.fKind) {
1562 case Statement::kBlock_Kind: {
1563 Requirements result = kNo_Requirements;
1564 for (const auto& child : ((const Block&) s).fStatements) {
1565 result |= this->requirements(*child);
1566 }
1567 return result;
1568 }
Timothy Liang7d637782018-06-05 09:58:07 -04001569 case Statement::kVarDeclaration_Kind: {
1570 Requirements result = kNo_Requirements;
1571 const VarDeclaration& var = (const VarDeclaration&) s;
1572 if (var.fValue) {
1573 result = this->requirements(*var.fValue);
1574 }
1575 return result;
1576 }
1577 case Statement::kVarDeclarations_Kind: {
1578 Requirements result = kNo_Requirements;
1579 const VarDeclarations& decls = *((const VarDeclarationsStatement&) s).fDeclaration;
1580 for (const auto& stmt : decls.fVars) {
1581 result |= this->requirements(*stmt);
1582 }
1583 return result;
1584 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001585 case Statement::kExpression_Kind:
1586 return this->requirements(*((const ExpressionStatement&) s).fExpression);
1587 case Statement::kReturn_Kind: {
1588 const ReturnStatement& r = (const ReturnStatement&) s;
1589 if (r.fExpression) {
1590 return this->requirements(*r.fExpression);
1591 }
1592 return kNo_Requirements;
1593 }
1594 case Statement::kIf_Kind: {
1595 const IfStatement& i = (const IfStatement&) s;
1596 return this->requirements(*i.fTest) |
1597 this->requirements(*i.fIfTrue) |
1598 (i.fIfFalse && this->requirements(*i.fIfFalse));
1599 }
1600 case Statement::kFor_Kind: {
1601 const ForStatement& f = (const ForStatement&) s;
1602 return this->requirements(*f.fInitializer) |
1603 this->requirements(*f.fTest) |
1604 this->requirements(*f.fNext) |
1605 this->requirements(*f.fStatement);
1606 }
1607 case Statement::kWhile_Kind: {
1608 const WhileStatement& w = (const WhileStatement&) s;
1609 return this->requirements(*w.fTest) |
1610 this->requirements(*w.fStatement);
1611 }
1612 case Statement::kDo_Kind: {
1613 const DoStatement& d = (const DoStatement&) s;
1614 return this->requirements(*d.fTest) |
1615 this->requirements(*d.fStatement);
1616 }
1617 case Statement::kSwitch_Kind: {
1618 const SwitchStatement& sw = (const SwitchStatement&) s;
1619 Requirements result = this->requirements(*sw.fValue);
1620 for (const auto& c : sw.fCases) {
1621 for (const auto& st : c->fStatements) {
1622 result |= this->requirements(*st);
1623 }
1624 }
1625 return result;
1626 }
1627 default:
1628 return kNo_Requirements;
1629 }
1630}
1631
1632MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const FunctionDeclaration& f) {
1633 if (f.fBuiltin) {
1634 return kNo_Requirements;
1635 }
1636 auto found = fRequirements.find(&f);
1637 if (found == fRequirements.end()) {
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001638 for (const auto& e : fProgram) {
1639 if (ProgramElement::kFunction_Kind == e.fKind) {
1640 const FunctionDefinition& def = (const FunctionDefinition&) e;
Ethan Nicholascc305772017-10-13 16:17:45 -04001641 if (&def.fDeclaration == &f) {
1642 Requirements reqs = this->requirements(*def.fBody);
1643 fRequirements[&f] = reqs;
1644 return reqs;
1645 }
1646 }
1647 }
1648 }
1649 return found->second;
1650}
1651
Timothy Liangb8eeb802018-07-23 16:46:16 -04001652bool MetalCodeGenerator::generateCode() {
Ethan Nicholascc305772017-10-13 16:17:45 -04001653 OutputStream* rawOut = fOut;
1654 fOut = &fHeader;
Timothy Liangb8eeb802018-07-23 16:46:16 -04001655#ifdef SK_MOLTENVK
1656 fOut->write((const char*) &MVKMagicNum, sizeof(MVKMagicNum));
1657#endif
Ethan Nicholascc305772017-10-13 16:17:45 -04001658 fProgramKind = fProgram.fKind;
1659 this->writeHeader();
1660 this->writeUniformStruct();
1661 this->writeInputStruct();
Timothy Liang7d637782018-06-05 09:58:07 -04001662 this->writeOutputStruct();
1663 this->writeInterfaceBlocks();
Timothy Liangee84fe12018-05-18 14:38:19 -04001664 this->writeGlobalStruct();
Ethan Nicholascc305772017-10-13 16:17:45 -04001665 StringStream body;
1666 fOut = &body;
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001667 for (const auto& e : fProgram) {
1668 this->writeProgramElement(e);
Ethan Nicholascc305772017-10-13 16:17:45 -04001669 }
1670 fOut = rawOut;
1671
1672 write_stringstream(fHeader, *rawOut);
Chris Daltondba7aab2018-11-15 10:57:49 -05001673 write_stringstream(fExtraFunctions, *rawOut);
Ethan Nicholascc305772017-10-13 16:17:45 -04001674 write_stringstream(body, *rawOut);
Timothy Liangb8eeb802018-07-23 16:46:16 -04001675#ifdef SK_MOLTENVK
1676 this->write("\0");
1677#endif
Ethan Nicholascc305772017-10-13 16:17:45 -04001678 return true;
Ethan Nicholascc305772017-10-13 16:17:45 -04001679}
1680
1681}