blob: 96af1a0f6708e341b7e77a3ec88ee51031d0fdb8 [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
Brian Osmanc262a122020-08-06 16:34:34 -040018#include <algorithm>
19
Ethan Nicholascc305772017-10-13 16:17:45 -040020namespace SkSL {
21
John Stilescdcdb042020-07-06 09:03:51 -040022class MetalCodeGenerator::GlobalStructVisitor {
23public:
24 virtual ~GlobalStructVisitor() = default;
25 virtual void VisitInterfaceBlock(const InterfaceBlock& block, const String& blockName) = 0;
26 virtual void VisitTexture(const Type& type, const String& name) = 0;
27 virtual void VisitSampler(const Type& type, const String& name) = 0;
28 virtual void VisitVariable(const Variable& var, const Expression* value) = 0;
29};
30
Timothy Liangee84fe12018-05-18 14:38:19 -040031void MetalCodeGenerator::setupIntrinsics() {
Timothy Liang7d637782018-06-05 09:58:07 -040032#define METAL(x) std::make_pair(kMetal_IntrinsicKind, k ## x ## _MetalIntrinsic)
33#define SPECIAL(x) std::make_pair(kSpecial_IntrinsicKind, k ## x ## _SpecialIntrinsic)
Ethan Nicholas13863662019-07-29 13:05:15 -040034 fIntrinsicMap[String("sample")] = SPECIAL(Texture);
Timothy Liang651286f2018-06-07 09:55:33 -040035 fIntrinsicMap[String("mod")] = SPECIAL(Mod);
Ethan Nicholas0dc80872019-02-08 15:46:24 -050036 fIntrinsicMap[String("equal")] = METAL(Equal);
37 fIntrinsicMap[String("notEqual")] = METAL(NotEqual);
Timothy Lianga06f2152018-05-24 15:33:31 -040038 fIntrinsicMap[String("lessThan")] = METAL(LessThan);
39 fIntrinsicMap[String("lessThanEqual")] = METAL(LessThanEqual);
40 fIntrinsicMap[String("greaterThan")] = METAL(GreaterThan);
41 fIntrinsicMap[String("greaterThanEqual")] = METAL(GreaterThanEqual);
Timothy Liangee84fe12018-05-18 14:38:19 -040042}
43
Ethan Nicholascc305772017-10-13 16:17:45 -040044void MetalCodeGenerator::write(const char* s) {
45 if (!s[0]) {
46 return;
47 }
48 if (fAtLineStart) {
49 for (int i = 0; i < fIndentation; i++) {
50 fOut->writeText(" ");
51 }
52 }
53 fOut->writeText(s);
54 fAtLineStart = false;
55}
56
57void MetalCodeGenerator::writeLine(const char* s) {
58 this->write(s);
59 fOut->writeText(fLineEnding);
60 fAtLineStart = true;
61}
62
63void MetalCodeGenerator::write(const String& s) {
64 this->write(s.c_str());
65}
66
67void MetalCodeGenerator::writeLine(const String& s) {
68 this->writeLine(s.c_str());
69}
70
71void MetalCodeGenerator::writeLine() {
72 this->writeLine("");
73}
74
75void MetalCodeGenerator::writeExtension(const Extension& ext) {
76 this->writeLine("#extension " + ext.fName + " : enable");
77}
78
Ethan Nicholas45fa8102020-01-13 10:58:49 -050079String MetalCodeGenerator::typeName(const Type& type) {
Ethan Nicholase6592142020-09-08 10:22:09 -040080 switch (type.typeKind()) {
81 case Type::TypeKind::kVector:
Ethan Nicholas45fa8102020-01-13 10:58:49 -050082 return this->typeName(type.componentType()) + to_string(type.columns());
Ethan Nicholase6592142020-09-08 10:22:09 -040083 case Type::TypeKind::kMatrix:
Ethan Nicholas45fa8102020-01-13 10:58:49 -050084 return this->typeName(type.componentType()) + to_string(type.columns()) + "x" +
85 to_string(type.rows());
Ethan Nicholase6592142020-09-08 10:22:09 -040086 case Type::TypeKind::kSampler:
Ethan Nicholas45fa8102020-01-13 10:58:49 -050087 return "texture2d<float>"; // FIXME - support other texture types;
Ethan Nicholascc305772017-10-13 16:17:45 -040088 default:
Timothy Liang43d225f2018-07-19 15:27:13 -040089 if (type == *fContext.fHalf_Type) {
90 // FIXME - Currently only supporting floats in MSL to avoid type coercion issues.
Ethan Nicholas45fa8102020-01-13 10:58:49 -050091 return fContext.fFloat_Type->name();
Timothy Liang43d225f2018-07-19 15:27:13 -040092 } else if (type == *fContext.fByte_Type) {
Ethan Nicholas45fa8102020-01-13 10:58:49 -050093 return "char";
Timothy Liang43d225f2018-07-19 15:27:13 -040094 } else if (type == *fContext.fUByte_Type) {
Ethan Nicholas45fa8102020-01-13 10:58:49 -050095 return "uchar";
Timothy Liang7d637782018-06-05 09:58:07 -040096 } else {
Ethan Nicholas45fa8102020-01-13 10:58:49 -050097 return type.name();
Timothy Liang7d637782018-06-05 09:58:07 -040098 }
Ethan Nicholascc305772017-10-13 16:17:45 -040099 }
100}
101
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500102void MetalCodeGenerator::writeType(const Type& type) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400103 if (type.typeKind() == Type::TypeKind::kStruct) {
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500104 for (const Type* search : fWrittenStructs) {
105 if (*search == type) {
106 // already written
107 this->write(type.name());
108 return;
109 }
110 }
111 fWrittenStructs.push_back(&type);
112 this->writeLine("struct " + type.name() + " {");
113 fIndentation++;
114 this->writeFields(type.fields(), type.fOffset);
115 fIndentation--;
116 this->write("}");
117 } else {
118 this->write(this->typeName(type));
119 }
120}
121
Ethan Nicholascc305772017-10-13 16:17:45 -0400122void MetalCodeGenerator::writeExpression(const Expression& expr, Precedence parentPrecedence) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400123 switch (expr.kind()) {
124 case Expression::Kind::kBinary:
John Stiles81365af2020-08-18 09:24:00 -0400125 this->writeBinaryExpression(expr.as<BinaryExpression>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400126 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400127 case Expression::Kind::kBoolLiteral:
John Stiles81365af2020-08-18 09:24:00 -0400128 this->writeBoolLiteral(expr.as<BoolLiteral>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400129 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400130 case Expression::Kind::kConstructor:
John Stiles81365af2020-08-18 09:24:00 -0400131 this->writeConstructor(expr.as<Constructor>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400132 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400133 case Expression::Kind::kIntLiteral:
John Stiles81365af2020-08-18 09:24:00 -0400134 this->writeIntLiteral(expr.as<IntLiteral>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400135 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400136 case Expression::Kind::kFieldAccess:
John Stiles81365af2020-08-18 09:24:00 -0400137 this->writeFieldAccess(expr.as<FieldAccess>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400138 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400139 case Expression::Kind::kFloatLiteral:
John Stiles81365af2020-08-18 09:24:00 -0400140 this->writeFloatLiteral(expr.as<FloatLiteral>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400141 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400142 case Expression::Kind::kFunctionCall:
John Stiles81365af2020-08-18 09:24:00 -0400143 this->writeFunctionCall(expr.as<FunctionCall>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400144 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400145 case Expression::Kind::kPrefix:
John Stiles81365af2020-08-18 09:24:00 -0400146 this->writePrefixExpression(expr.as<PrefixExpression>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400147 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400148 case Expression::Kind::kPostfix:
John Stiles81365af2020-08-18 09:24:00 -0400149 this->writePostfixExpression(expr.as<PostfixExpression>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400150 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400151 case Expression::Kind::kSetting:
John Stiles81365af2020-08-18 09:24:00 -0400152 this->writeSetting(expr.as<Setting>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400153 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400154 case Expression::Kind::kSwizzle:
John Stiles81365af2020-08-18 09:24:00 -0400155 this->writeSwizzle(expr.as<Swizzle>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400156 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400157 case Expression::Kind::kVariableReference:
John Stiles81365af2020-08-18 09:24:00 -0400158 this->writeVariableReference(expr.as<VariableReference>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400159 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400160 case Expression::Kind::kTernary:
John Stiles81365af2020-08-18 09:24:00 -0400161 this->writeTernaryExpression(expr.as<TernaryExpression>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400162 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400163 case Expression::Kind::kIndex:
John Stiles81365af2020-08-18 09:24:00 -0400164 this->writeIndexExpression(expr.as<IndexExpression>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400165 break;
166 default:
Ethan Nicholas2a099da2020-01-02 14:40:54 -0500167#ifdef SK_DEBUG
Ethan Nicholascc305772017-10-13 16:17:45 -0400168 ABORT("unsupported expression: %s", expr.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -0500169#endif
170 break;
Ethan Nicholascc305772017-10-13 16:17:45 -0400171 }
172}
173
Timothy Liang6403b0e2018-05-17 10:40:04 -0400174void MetalCodeGenerator::writeIntrinsicCall(const FunctionCall& c) {
Timothy Liang7d637782018-06-05 09:58:07 -0400175 auto i = fIntrinsicMap.find(c.fFunction.fName);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400176 SkASSERT(i != fIntrinsicMap.end());
Timothy Liang7d637782018-06-05 09:58:07 -0400177 Intrinsic intrinsic = i->second;
178 int32_t intrinsicId = intrinsic.second;
179 switch (intrinsic.first) {
Timothy Liang6403b0e2018-05-17 10:40:04 -0400180 case kSpecial_IntrinsicKind:
181 return this->writeSpecialIntrinsic(c, (SpecialIntrinsic) intrinsicId);
Timothy Lianga06f2152018-05-24 15:33:31 -0400182 break;
183 case kMetal_IntrinsicKind:
184 this->writeExpression(*c.fArguments[0], kSequence_Precedence);
185 switch ((MetalIntrinsic) intrinsicId) {
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500186 case kEqual_MetalIntrinsic:
187 this->write(" == ");
188 break;
189 case kNotEqual_MetalIntrinsic:
190 this->write(" != ");
191 break;
Timothy Lianga06f2152018-05-24 15:33:31 -0400192 case kLessThan_MetalIntrinsic:
193 this->write(" < ");
194 break;
195 case kLessThanEqual_MetalIntrinsic:
196 this->write(" <= ");
197 break;
198 case kGreaterThan_MetalIntrinsic:
199 this->write(" > ");
200 break;
201 case kGreaterThanEqual_MetalIntrinsic:
202 this->write(" >= ");
203 break;
204 default:
205 ABORT("unsupported metal intrinsic kind");
206 }
207 this->writeExpression(*c.fArguments[1], kSequence_Precedence);
208 break;
Timothy Liang6403b0e2018-05-17 10:40:04 -0400209 default:
210 ABORT("unsupported intrinsic kind");
211 }
212}
213
Ethan Nicholascc305772017-10-13 16:17:45 -0400214void MetalCodeGenerator::writeFunctionCall(const FunctionCall& c) {
Timothy Liang6403b0e2018-05-17 10:40:04 -0400215 const auto& entry = fIntrinsicMap.find(c.fFunction.fName);
216 if (entry != fIntrinsicMap.end()) {
217 this->writeIntrinsicCall(c);
218 return;
219 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400220 if (c.fFunction.fBuiltin && "atan" == c.fFunction.fName && 2 == c.fArguments.size()) {
221 this->write("atan2");
Timothy Lianga06f2152018-05-24 15:33:31 -0400222 } else if (c.fFunction.fBuiltin && "inversesqrt" == c.fFunction.fName) {
223 this->write("rsqrt");
Chris Daltondba7aab2018-11-15 10:57:49 -0500224 } else if (c.fFunction.fBuiltin && "inverse" == c.fFunction.fName) {
225 SkASSERT(c.fArguments.size() == 1);
226 this->writeInverseHack(*c.fArguments[0]);
Timothy Liang7d637782018-06-05 09:58:07 -0400227 } else if (c.fFunction.fBuiltin && "dFdx" == c.fFunction.fName) {
228 this->write("dfdx");
229 } else if (c.fFunction.fBuiltin && "dFdy" == c.fFunction.fName) {
Chris Daltonb8af5ad2019-02-25 14:54:21 -0700230 // Flipping Y also negates the Y derivatives.
231 this->write((fProgram.fSettings.fFlipY) ? "-dfdy" : "dfdy");
Ethan Nicholascc305772017-10-13 16:17:45 -0400232 } else {
Timothy Liang651286f2018-06-07 09:55:33 -0400233 this->writeName(c.fFunction.fName);
Ethan Nicholascc305772017-10-13 16:17:45 -0400234 }
235 this->write("(");
236 const char* separator = "";
237 if (this->requirements(c.fFunction) & kInputs_Requirement) {
238 this->write("_in");
239 separator = ", ";
240 }
241 if (this->requirements(c.fFunction) & kOutputs_Requirement) {
242 this->write(separator);
243 this->write("_out");
244 separator = ", ";
245 }
246 if (this->requirements(c.fFunction) & kUniforms_Requirement) {
247 this->write(separator);
248 this->write("_uniforms");
249 separator = ", ";
250 }
Timothy Liangee84fe12018-05-18 14:38:19 -0400251 if (this->requirements(c.fFunction) & kGlobals_Requirement) {
252 this->write(separator);
253 this->write("_globals");
254 separator = ", ";
255 }
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -0400256 if (this->requirements(c.fFunction) & kFragCoord_Requirement) {
257 this->write(separator);
258 this->write("_fragCoord");
259 separator = ", ";
260 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400261 for (size_t i = 0; i < c.fArguments.size(); ++i) {
262 const Expression& arg = *c.fArguments[i];
263 this->write(separator);
264 separator = ", ";
265 if (c.fFunction.fParameters[i]->fModifiers.fFlags & Modifiers::kOut_Flag) {
266 this->write("&");
267 }
268 this->writeExpression(arg, kSequence_Precedence);
269 }
270 this->write(")");
271}
272
Chris Daltondba7aab2018-11-15 10:57:49 -0500273void MetalCodeGenerator::writeInverseHack(const Expression& mat) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400274 const Type& type = mat.type();
275 const String& typeName = type.name();
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500276 String name = typeName + "_inverse";
Ethan Nicholas30d30222020-09-11 12:27:26 -0400277 if (type == *fContext.fFloat2x2_Type || type == *fContext.fHalf2x2_Type) {
Chris Daltondba7aab2018-11-15 10:57:49 -0500278 if (fWrittenIntrinsics.find(name) == fWrittenIntrinsics.end()) {
279 fWrittenIntrinsics.insert(name);
280 fExtraFunctions.writeText((
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500281 typeName + " " + name + "(" + typeName + " m) {"
Chris Daltondba7aab2018-11-15 10:57:49 -0500282 " return float2x2(m[1][1], -m[0][1], -m[1][0], m[0][0]) * (1/determinant(m));"
283 "}"
284 ).c_str());
285 }
286 }
Ethan Nicholas30d30222020-09-11 12:27:26 -0400287 else if (type == *fContext.fFloat3x3_Type || type == *fContext.fHalf3x3_Type) {
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500288 if (fWrittenIntrinsics.find(name) == fWrittenIntrinsics.end()) {
289 fWrittenIntrinsics.insert(name);
290 fExtraFunctions.writeText((
291 typeName + " " + name + "(" + typeName + " m) {"
292 " float a00 = m[0][0], a01 = m[0][1], a02 = m[0][2];"
293 " float a10 = m[1][0], a11 = m[1][1], a12 = m[1][2];"
294 " float a20 = m[2][0], a21 = m[2][1], a22 = m[2][2];"
295 " float b01 = a22 * a11 - a12 * a21;"
296 " float b11 = -a22 * a10 + a12 * a20;"
297 " float b21 = a21 * a10 - a11 * a20;"
298 " float det = a00 * b01 + a01 * b11 + a02 * b21;"
299 " return " + typeName +
300 " (b01, (-a22 * a01 + a02 * a21), (a12 * a01 - a02 * a11),"
301 " b11, (a22 * a00 - a02 * a20), (-a12 * a00 + a02 * a10),"
302 " b21, (-a21 * a00 + a01 * a20), (a11 * a00 - a01 * a10)) * "
303 " (1/det);"
304 "}"
305 ).c_str());
306 }
307 }
Ethan Nicholas30d30222020-09-11 12:27:26 -0400308 else if (type == *fContext.fFloat4x4_Type || type == *fContext.fHalf4x4_Type) {
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500309 if (fWrittenIntrinsics.find(name) == fWrittenIntrinsics.end()) {
310 fWrittenIntrinsics.insert(name);
311 fExtraFunctions.writeText((
312 typeName + " " + name + "(" + typeName + " m) {"
313 " float a00 = m[0][0], a01 = m[0][1], a02 = m[0][2], a03 = m[0][3];"
314 " float a10 = m[1][0], a11 = m[1][1], a12 = m[1][2], a13 = m[1][3];"
315 " float a20 = m[2][0], a21 = m[2][1], a22 = m[2][2], a23 = m[2][3];"
316 " float a30 = m[3][0], a31 = m[3][1], a32 = m[3][2], a33 = m[3][3];"
317 " float b00 = a00 * a11 - a01 * a10;"
318 " float b01 = a00 * a12 - a02 * a10;"
319 " float b02 = a00 * a13 - a03 * a10;"
320 " float b03 = a01 * a12 - a02 * a11;"
321 " float b04 = a01 * a13 - a03 * a11;"
322 " float b05 = a02 * a13 - a03 * a12;"
323 " float b06 = a20 * a31 - a21 * a30;"
324 " float b07 = a20 * a32 - a22 * a30;"
325 " float b08 = a20 * a33 - a23 * a30;"
326 " float b09 = a21 * a32 - a22 * a31;"
327 " float b10 = a21 * a33 - a23 * a31;"
328 " float b11 = a22 * a33 - a23 * a32;"
329 " float det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - "
330 " b04 * b07 + b05 * b06;"
331 " return " + typeName + "(a11 * b11 - a12 * b10 + a13 * b09,"
332 " a02 * b10 - a01 * b11 - a03 * b09,"
333 " a31 * b05 - a32 * b04 + a33 * b03,"
334 " a22 * b04 - a21 * b05 - a23 * b03,"
335 " a12 * b08 - a10 * b11 - a13 * b07,"
336 " a00 * b11 - a02 * b08 + a03 * b07,"
337 " a32 * b02 - a30 * b05 - a33 * b01,"
338 " a20 * b05 - a22 * b02 + a23 * b01,"
339 " a10 * b10 - a11 * b08 + a13 * b06,"
340 " a01 * b08 - a00 * b10 - a03 * b06,"
341 " a30 * b04 - a31 * b02 + a33 * b00,"
342 " a21 * b02 - a20 * b04 - a23 * b00,"
343 " a11 * b07 - a10 * b09 - a12 * b06,"
344 " a00 * b09 - a01 * b07 + a02 * b06,"
345 " a31 * b01 - a30 * b03 - a32 * b00,"
346 " a20 * b03 - a21 * b01 + a22 * b00) / det;"
347 "}"
348 ).c_str());
349 }
350 }
Chris Daltondba7aab2018-11-15 10:57:49 -0500351 this->write(name);
352}
353
Timothy Liang6403b0e2018-05-17 10:40:04 -0400354void MetalCodeGenerator::writeSpecialIntrinsic(const FunctionCall & c, SpecialIntrinsic kind) {
355 switch (kind) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400356 case kTexture_SpecialIntrinsic: {
Timothy Liangee84fe12018-05-18 14:38:19 -0400357 this->writeExpression(*c.fArguments[0], kSequence_Precedence);
Timothy Lianga06f2152018-05-24 15:33:31 -0400358 this->write(".sample(");
359 this->writeExpression(*c.fArguments[0], kSequence_Precedence);
360 this->write(SAMPLER_SUFFIX);
361 this->write(", ");
Ethan Nicholas30d30222020-09-11 12:27:26 -0400362 const Type& arg1Type = c.fArguments[1]->type();
363 if (arg1Type == *fContext.fFloat3_Type) {
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500364 // have to store the vector in a temp variable to avoid double evaluating it
365 String tmpVar = "tmpCoord" + to_string(fVarCount++);
Ethan Nicholas30d30222020-09-11 12:27:26 -0400366 this->fFunctionHeader += " " + this->typeName(arg1Type) + " " + tmpVar + ";\n";
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500367 this->write("(" + tmpVar + " = ");
368 this->writeExpression(*c.fArguments[1], kSequence_Precedence);
369 this->write(", " + tmpVar + ".xy / " + tmpVar + ".z))");
Timothy Liangee84fe12018-05-18 14:38:19 -0400370 } else {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400371 SkASSERT(arg1Type == *fContext.fFloat2_Type);
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500372 this->writeExpression(*c.fArguments[1], kSequence_Precedence);
Timothy Liangee84fe12018-05-18 14:38:19 -0400373 this->write(")");
374 }
Timothy Liang6403b0e2018-05-17 10:40:04 -0400375 break;
Ethan Nicholas30d30222020-09-11 12:27:26 -0400376 }
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500377 case kMod_SpecialIntrinsic: {
Timothy Liang651286f2018-06-07 09:55:33 -0400378 // fmod(x, y) in metal calculates x - y * trunc(x / y) instead of x - y * floor(x / y)
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500379 String tmpX = "tmpX" + to_string(fVarCount++);
380 String tmpY = "tmpY" + to_string(fVarCount++);
Ethan Nicholas30d30222020-09-11 12:27:26 -0400381 this->fFunctionHeader += " " + this->typeName(c.fArguments[0]->type()) +
382 " " + tmpX + ", " + tmpY + ";\n";
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500383 this->write("(" + tmpX + " = ");
Timothy Liang651286f2018-06-07 09:55:33 -0400384 this->writeExpression(*c.fArguments[0], kSequence_Precedence);
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500385 this->write(", " + tmpY + " = ");
Timothy Liang651286f2018-06-07 09:55:33 -0400386 this->writeExpression(*c.fArguments[1], kSequence_Precedence);
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500387 this->write(", " + tmpX + " - " + tmpY + " * floor(" + tmpX + " / " + tmpY + "))");
Timothy Liang651286f2018-06-07 09:55:33 -0400388 break;
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500389 }
Timothy Liang6403b0e2018-05-17 10:40:04 -0400390 default:
391 ABORT("unsupported special intrinsic kind");
392 }
393}
394
John Stilesfcf8cb22020-08-06 14:29:22 -0400395// Assembles a matrix of type floatRxC by resizing another matrix named `x0`.
396// Cells that don't exist in the source matrix will be populated with identity-matrix values.
397void MetalCodeGenerator::assembleMatrixFromMatrix(const Type& sourceMatrix, int rows, int columns) {
398 SkASSERT(rows <= 4);
399 SkASSERT(columns <= 4);
400
401 const char* columnSeparator = "";
402 for (int c = 0; c < columns; ++c) {
403 fExtraFunctions.printf("%sfloat%d(", columnSeparator, rows);
404 columnSeparator = "), ";
405
406 // Determine how many values to take from the source matrix for this row.
407 int swizzleLength = 0;
408 if (c < sourceMatrix.columns()) {
409 swizzleLength = std::min<>(rows, sourceMatrix.rows());
410 }
411
412 // Emit all the values from the source matrix row.
413 bool firstItem;
414 switch (swizzleLength) {
415 case 0: firstItem = true; break;
416 case 1: firstItem = false; fExtraFunctions.printf("x0[%d].x", c); break;
417 case 2: firstItem = false; fExtraFunctions.printf("x0[%d].xy", c); break;
418 case 3: firstItem = false; fExtraFunctions.printf("x0[%d].xyz", c); break;
419 case 4: firstItem = false; fExtraFunctions.printf("x0[%d].xyzw", c); break;
420 default: SkUNREACHABLE;
421 }
422
423 // Emit the placeholder identity-matrix cells.
424 for (int r = swizzleLength; r < rows; ++r) {
425 fExtraFunctions.printf("%s%s", firstItem ? "" : ", ", (r == c) ? "1.0" : "0.0");
426 firstItem = false;
427 }
428 }
429
430 fExtraFunctions.writeText(")");
431}
432
433// Assembles a matrix of type floatRxC by concatenating an arbitrary mix of values, named `x0`,
434// `x1`, etc. An error is written if the expression list don't contain exactly R*C scalars.
435void MetalCodeGenerator::assembleMatrixFromExpressions(
436 const std::vector<std::unique_ptr<Expression>>& args, int rows, int columns) {
437 size_t argIndex = 0;
438 int argPosition = 0;
439
440 const char* columnSeparator = "";
441 for (int c = 0; c < columns; ++c) {
442 fExtraFunctions.printf("%sfloat%d(", columnSeparator, rows);
443 columnSeparator = "), ";
444
445 const char* rowSeparator = "";
446 for (int r = 0; r < rows; ++r) {
447 fExtraFunctions.writeText(rowSeparator);
448 rowSeparator = ", ";
449
450 if (argIndex < args.size()) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400451 const Type& argType = args[argIndex]->type();
Ethan Nicholase6592142020-09-08 10:22:09 -0400452 switch (argType.typeKind()) {
453 case Type::TypeKind::kScalar: {
John Stilesfcf8cb22020-08-06 14:29:22 -0400454 fExtraFunctions.printf("x%zu", argIndex);
455 break;
456 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400457 case Type::TypeKind::kVector: {
John Stilesfcf8cb22020-08-06 14:29:22 -0400458 fExtraFunctions.printf("x%zu[%d]", argIndex, argPosition);
459 break;
460 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400461 case Type::TypeKind::kMatrix: {
John Stilesfcf8cb22020-08-06 14:29:22 -0400462 fExtraFunctions.printf("x%zu[%d][%d]", argIndex,
463 argPosition / argType.rows(),
464 argPosition % argType.rows());
465 break;
466 }
467 default: {
468 SkDEBUGFAIL("incorrect type of argument for matrix constructor");
469 fExtraFunctions.writeText("<error>");
470 break;
471 }
472 }
473
474 ++argPosition;
475 if (argPosition >= argType.columns() * argType.rows()) {
476 ++argIndex;
477 argPosition = 0;
478 }
479 } else {
480 SkDEBUGFAIL("not enough arguments for matrix constructor");
481 fExtraFunctions.writeText("<error>");
482 }
483 }
484 }
485
486 if (argPosition != 0 || argIndex != args.size()) {
487 SkDEBUGFAIL("incorrect number of arguments for matrix constructor");
488 fExtraFunctions.writeText(", <error>");
489 }
490
491 fExtraFunctions.writeText(")");
492}
493
John Stiles1bdafbf2020-05-28 12:17:20 -0400494// Generates a constructor for 'matrix' which reorganizes the input arguments into the proper shape.
495// Keeps track of previously generated constructors so that we won't generate more than one
496// constructor for any given permutation of input argument types. Returns the name of the
497// generated constructor method.
498String MetalCodeGenerator::getMatrixConstructHelper(const Constructor& c) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400499 const Type& matrix = c.type();
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500500 int columns = matrix.columns();
501 int rows = matrix.rows();
John Stiles1bdafbf2020-05-28 12:17:20 -0400502 const std::vector<std::unique_ptr<Expression>>& args = c.fArguments;
503
504 // Create the helper-method name and use it as our lookup key.
505 String name;
506 name.appendf("float%dx%d_from", columns, rows);
507 for (const std::unique_ptr<Expression>& expr : args) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400508 name.appendf("_%s", expr->type().displayName().c_str());
John Stiles1bdafbf2020-05-28 12:17:20 -0400509 }
510
511 // If a helper-method has already been synthesized, we don't need to synthesize it again.
512 auto [iter, newlyCreated] = fHelpers.insert(name);
513 if (!newlyCreated) {
514 return name;
515 }
516
517 // Unlike GLSL, Metal requires that matrices are initialized with exactly R vectors of C
518 // components apiece. (In Metal 2.0, you can also supply R*C scalars, but you still cannot
519 // supply a mixture of scalars and vectors.)
520 fExtraFunctions.printf("float%dx%d %s(", columns, rows, name.c_str());
521
522 size_t argIndex = 0;
523 const char* argSeparator = "";
John Stilesfcf8cb22020-08-06 14:29:22 -0400524 for (const std::unique_ptr<Expression>& expr : args) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400525 fExtraFunctions.printf("%s%s x%zu", argSeparator,
Ethan Nicholas30d30222020-09-11 12:27:26 -0400526 expr->type().displayName().c_str(), argIndex++);
John Stiles1bdafbf2020-05-28 12:17:20 -0400527 argSeparator = ", ";
528 }
529
530 fExtraFunctions.printf(") {\n return float%dx%d(", columns, rows);
531
Ethan Nicholas30d30222020-09-11 12:27:26 -0400532 if (args.size() == 1 && args.front()->type().typeKind() == Type::TypeKind::kMatrix) {
533 this->assembleMatrixFromMatrix(args.front()->type(), rows, columns);
John Stilesfcf8cb22020-08-06 14:29:22 -0400534 } else {
535 this->assembleMatrixFromExpressions(args, rows, columns);
John Stiles1bdafbf2020-05-28 12:17:20 -0400536 }
537
John Stilesfcf8cb22020-08-06 14:29:22 -0400538 fExtraFunctions.writeText(");\n}\n");
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500539 return name;
540}
541
542bool MetalCodeGenerator::canCoerce(const Type& t1, const Type& t2) {
543 if (t1.columns() != t2.columns() || t1.rows() != t2.rows()) {
544 return false;
545 }
546 if (t1.columns() > 1) {
547 return this->canCoerce(t1.componentType(), t2.componentType());
548 }
Ethan Nicholase1f55022019-02-05 17:17:40 -0500549 return t1.isFloat() && t2.isFloat();
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500550}
551
John Stiles1bdafbf2020-05-28 12:17:20 -0400552bool MetalCodeGenerator::matrixConstructHelperIsNeeded(const Constructor& c) {
553 // A matrix construct helper is only necessary if we are, in fact, constructing a matrix.
Ethan Nicholas30d30222020-09-11 12:27:26 -0400554 if (c.type().typeKind() != Type::TypeKind::kMatrix) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400555 return false;
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500556 }
John Stiles1bdafbf2020-05-28 12:17:20 -0400557
558 // GLSL is fairly free-form about inputs to its matrix constructors, but Metal is not; it
559 // expects exactly R vectors of C components apiece. (Metal 2.0 also allows a list of R*C
560 // scalars.) Some cases are simple to translate and so we handle those inline--e.g. a list of
561 // scalars can be constructed trivially. In more complex cases, we generate a helper function
562 // that converts our inputs into a properly-shaped matrix.
563 // A matrix construct helper method is always used if any input argument is a matrix.
564 // Helper methods are also necessary when any argument would span multiple rows. For instance:
565 //
566 // float2 x = (1, 2);
567 // float3x2(x, 3, 4, 5, 6) = | 1 3 5 | = no helper needed; conversion can be done inline
568 // | 2 4 6 |
569 //
570 // float2 x = (2, 3);
571 // float3x2(1, x, 4, 5, 6) = | 1 3 5 | = x spans multiple rows; a helper method will be used
572 // | 2 4 6 |
573 //
574 // float4 x = (1, 2, 3, 4);
575 // float2x2(x) = | 1 3 | = x spans multiple rows; a helper method will be used
576 // | 2 4 |
577 //
578
579 int position = 0;
580 for (const std::unique_ptr<Expression>& expr : c.fArguments) {
581 // If an input argument is a matrix, we need a helper function.
Ethan Nicholas30d30222020-09-11 12:27:26 -0400582 if (expr->type().typeKind() == Type::TypeKind::kMatrix) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400583 return true;
584 }
Ethan Nicholas30d30222020-09-11 12:27:26 -0400585 position += expr->type().columns();
586 if (position > c.type().rows()) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400587 // An input argument would span multiple rows; a helper function is required.
588 return true;
589 }
Ethan Nicholas30d30222020-09-11 12:27:26 -0400590 if (position == c.type().rows()) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400591 // We've advanced to the end of a row. Wrap to the start of the next row.
592 position = 0;
593 }
594 }
595
596 return false;
597}
598
599void MetalCodeGenerator::writeConstructor(const Constructor& c, Precedence parentPrecedence) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400600 const Type& constructorType = c.type();
John Stiles1bdafbf2020-05-28 12:17:20 -0400601 // Handle special cases for single-argument constructors.
602 if (c.fArguments.size() == 1) {
603 // If the type is coercible, emit it directly.
604 const Expression& arg = *c.fArguments.front();
Ethan Nicholas30d30222020-09-11 12:27:26 -0400605 const Type& argType = arg.type();
606 if (this->canCoerce(constructorType, argType)) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400607 this->writeExpression(arg, parentPrecedence);
608 return;
609 }
610
611 // Metal supports creating matrices with a scalar on the diagonal via the single-argument
612 // matrix constructor.
Ethan Nicholas30d30222020-09-11 12:27:26 -0400613 if (constructorType.typeKind() == Type::TypeKind::kMatrix && argType.isNumber()) {
614 const Type& matrix = constructorType;
John Stiles1bdafbf2020-05-28 12:17:20 -0400615 this->write("float");
616 this->write(to_string(matrix.columns()));
617 this->write("x");
618 this->write(to_string(matrix.rows()));
619 this->write("(");
620 this->writeExpression(arg, parentPrecedence);
621 this->write(")");
622 return;
623 }
624 }
625
626 // Emit and invoke a matrix-constructor helper method if one is necessary.
627 if (this->matrixConstructHelperIsNeeded(c)) {
628 this->write(this->getMatrixConstructHelper(c));
John Stiles1fa15b12020-05-28 17:36:54 +0000629 this->write("(");
630 const char* separator = "";
John Stiles1bdafbf2020-05-28 12:17:20 -0400631 for (const std::unique_ptr<Expression>& expr : c.fArguments) {
John Stiles1fa15b12020-05-28 17:36:54 +0000632 this->write(separator);
633 separator = ", ";
John Stiles1bdafbf2020-05-28 12:17:20 -0400634 this->writeExpression(*expr, kSequence_Precedence);
John Stilesdaa573e2020-05-28 12:17:20 -0400635 }
John Stiles1fa15b12020-05-28 17:36:54 +0000636 this->write(")");
John Stiles1bdafbf2020-05-28 12:17:20 -0400637 return;
John Stilesdaa573e2020-05-28 12:17:20 -0400638 }
John Stiles1bdafbf2020-05-28 12:17:20 -0400639
640 // Explicitly invoke the constructor, passing in the necessary arguments.
Ethan Nicholas30d30222020-09-11 12:27:26 -0400641 this->writeType(constructorType);
John Stiles1bdafbf2020-05-28 12:17:20 -0400642 this->write("(");
643 const char* separator = "";
644 int scalarCount = 0;
645 for (const std::unique_ptr<Expression>& arg : c.fArguments) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400646 const Type& argType = arg->type();
John Stiles1bdafbf2020-05-28 12:17:20 -0400647 this->write(separator);
648 separator = ", ";
Ethan Nicholas30d30222020-09-11 12:27:26 -0400649 if (constructorType.typeKind() == Type::TypeKind::kMatrix &&
650 argType.columns() < constructorType.rows()) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400651 // Merge scalars and smaller vectors together.
652 if (!scalarCount) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400653 this->writeType(constructorType.componentType());
654 this->write(to_string(constructorType.rows()));
John Stiles1bdafbf2020-05-28 12:17:20 -0400655 this->write("(");
656 }
Ethan Nicholas30d30222020-09-11 12:27:26 -0400657 scalarCount += argType.columns();
John Stiles1bdafbf2020-05-28 12:17:20 -0400658 }
659 this->writeExpression(*arg, kSequence_Precedence);
Ethan Nicholas30d30222020-09-11 12:27:26 -0400660 if (scalarCount && scalarCount == constructorType.rows()) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400661 this->write(")");
662 scalarCount = 0;
663 }
664 }
665 this->write(")");
Ethan Nicholascc305772017-10-13 16:17:45 -0400666}
667
668void MetalCodeGenerator::writeFragCoord() {
Ethan Nicholasf931e402019-07-26 15:40:33 -0400669 if (fRTHeightName.length()) {
670 this->write("float4(_fragCoord.x, ");
671 this->write(fRTHeightName.c_str());
672 this->write(" - _fragCoord.y, 0.0, _fragCoord.w)");
Jim Van Verth6bc650e2019-02-07 14:53:23 -0500673 } else {
674 this->write("float4(_fragCoord.x, _fragCoord.y, 0.0, _fragCoord.w)");
675 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400676}
677
678void MetalCodeGenerator::writeVariableReference(const VariableReference& ref) {
679 switch (ref.fVariable.fModifiers.fLayout.fBuiltin) {
680 case SK_FRAGCOLOR_BUILTIN:
Timothy Liang7d637782018-06-05 09:58:07 -0400681 this->write("_out->sk_FragColor");
Ethan Nicholascc305772017-10-13 16:17:45 -0400682 break;
Timothy Liang6403b0e2018-05-17 10:40:04 -0400683 case SK_FRAGCOORD_BUILTIN:
684 this->writeFragCoord();
685 break;
Timothy Liangdc89f192018-06-13 09:20:31 -0400686 case SK_VERTEXID_BUILTIN:
687 this->write("sk_VertexID");
688 break;
689 case SK_INSTANCEID_BUILTIN:
690 this->write("sk_InstanceID");
691 break;
Timothy Liang7b8875d2018-08-10 09:42:31 -0400692 case SK_CLOCKWISE_BUILTIN:
693 // We'd set the front facing winding in the MTLRenderCommandEncoder to be counter
Brian Salomonf4ba4ec2020-03-19 15:54:28 -0400694 // clockwise to match Skia convention.
Timothy Liang7b8875d2018-08-10 09:42:31 -0400695 this->write(fProgram.fSettings.fFlipY ? "_frontFacing" : "(!_frontFacing)");
696 break;
Ethan Nicholascc305772017-10-13 16:17:45 -0400697 default:
698 if (Variable::kGlobal_Storage == ref.fVariable.fStorage) {
699 if (ref.fVariable.fModifiers.fFlags & Modifiers::kIn_Flag) {
700 this->write("_in.");
701 } else if (ref.fVariable.fModifiers.fFlags & Modifiers::kOut_Flag) {
Timothy Liangee84fe12018-05-18 14:38:19 -0400702 this->write("_out->");
Timothy Lianga06f2152018-05-24 15:33:31 -0400703 } else if (ref.fVariable.fModifiers.fFlags & Modifiers::kUniform_Flag &&
Ethan Nicholas30d30222020-09-11 12:27:26 -0400704 ref.fVariable.type().typeKind() != Type::TypeKind::kSampler) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400705 this->write("_uniforms.");
706 } else {
Timothy Liangee84fe12018-05-18 14:38:19 -0400707 this->write("_globals->");
Ethan Nicholascc305772017-10-13 16:17:45 -0400708 }
709 }
Timothy Liang651286f2018-06-07 09:55:33 -0400710 this->writeName(ref.fVariable.fName);
Ethan Nicholascc305772017-10-13 16:17:45 -0400711 }
712}
713
714void MetalCodeGenerator::writeIndexExpression(const IndexExpression& expr) {
715 this->writeExpression(*expr.fBase, kPostfix_Precedence);
716 this->write("[");
717 this->writeExpression(*expr.fIndex, kTopLevel_Precedence);
718 this->write("]");
719}
720
721void MetalCodeGenerator::writeFieldAccess(const FieldAccess& f) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400722 const Type::Field* field = &f.fBase->type().fields()[f.fFieldIndex];
Ethan Nicholascc305772017-10-13 16:17:45 -0400723 if (FieldAccess::kDefault_OwnerKind == f.fOwnerKind) {
724 this->writeExpression(*f.fBase, kPostfix_Precedence);
725 this->write(".");
726 }
Timothy Liang7d637782018-06-05 09:58:07 -0400727 switch (field->fModifiers.fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400728 case SK_CLIPDISTANCE_BUILTIN:
729 this->write("gl_ClipDistance");
730 break;
731 case SK_POSITION_BUILTIN:
Timothy Liangb8eeb802018-07-23 16:46:16 -0400732 this->write("_out->sk_Position");
Ethan Nicholascc305772017-10-13 16:17:45 -0400733 break;
734 default:
Timothy Liang7d637782018-06-05 09:58:07 -0400735 if (field->fName == "sk_PointSize") {
736 this->write("_out->sk_PointSize");
737 } else {
738 if (FieldAccess::kAnonymousInterfaceBlock_OwnerKind == f.fOwnerKind) {
739 this->write("_globals->");
740 this->write(fInterfaceBlockNameMap[fInterfaceBlockMap[field]]);
741 this->write("->");
742 }
Timothy Liang651286f2018-06-07 09:55:33 -0400743 this->writeName(field->fName);
Timothy Lianga06f2152018-05-24 15:33:31 -0400744 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400745 }
746}
747
748void MetalCodeGenerator::writeSwizzle(const Swizzle& swizzle) {
Ethan Nicholas5476f2e2019-03-07 15:11:31 -0500749 int last = swizzle.fComponents.back();
750 if (last == SKSL_SWIZZLE_0 || last == SKSL_SWIZZLE_1) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400751 this->writeType(swizzle.type());
Ethan Nicholas5476f2e2019-03-07 15:11:31 -0500752 this->write("(");
753 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400754 this->writeExpression(*swizzle.fBase, kPostfix_Precedence);
755 this->write(".");
756 for (int c : swizzle.fComponents) {
Ethan Nicholas5476f2e2019-03-07 15:11:31 -0500757 if (c >= 0) {
758 this->write(&("x\0y\0z\0w\0"[c * 2]));
759 }
760 }
761 if (last == SKSL_SWIZZLE_0) {
762 this->write(", 0)");
763 }
764 else if (last == SKSL_SWIZZLE_1) {
765 this->write(", 1)");
Ethan Nicholascc305772017-10-13 16:17:45 -0400766 }
767}
768
769MetalCodeGenerator::Precedence MetalCodeGenerator::GetBinaryPrecedence(Token::Kind op) {
770 switch (op) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400771 case Token::Kind::TK_STAR: // fall through
772 case Token::Kind::TK_SLASH: // fall through
773 case Token::Kind::TK_PERCENT: return MetalCodeGenerator::kMultiplicative_Precedence;
774 case Token::Kind::TK_PLUS: // fall through
775 case Token::Kind::TK_MINUS: return MetalCodeGenerator::kAdditive_Precedence;
776 case Token::Kind::TK_SHL: // fall through
777 case Token::Kind::TK_SHR: return MetalCodeGenerator::kShift_Precedence;
778 case Token::Kind::TK_LT: // fall through
779 case Token::Kind::TK_GT: // fall through
780 case Token::Kind::TK_LTEQ: // fall through
781 case Token::Kind::TK_GTEQ: return MetalCodeGenerator::kRelational_Precedence;
782 case Token::Kind::TK_EQEQ: // fall through
783 case Token::Kind::TK_NEQ: return MetalCodeGenerator::kEquality_Precedence;
784 case Token::Kind::TK_BITWISEAND: return MetalCodeGenerator::kBitwiseAnd_Precedence;
785 case Token::Kind::TK_BITWISEXOR: return MetalCodeGenerator::kBitwiseXor_Precedence;
786 case Token::Kind::TK_BITWISEOR: return MetalCodeGenerator::kBitwiseOr_Precedence;
787 case Token::Kind::TK_LOGICALAND: return MetalCodeGenerator::kLogicalAnd_Precedence;
788 case Token::Kind::TK_LOGICALXOR: return MetalCodeGenerator::kLogicalXor_Precedence;
789 case Token::Kind::TK_LOGICALOR: return MetalCodeGenerator::kLogicalOr_Precedence;
790 case Token::Kind::TK_EQ: // fall through
791 case Token::Kind::TK_PLUSEQ: // fall through
792 case Token::Kind::TK_MINUSEQ: // fall through
793 case Token::Kind::TK_STAREQ: // fall through
794 case Token::Kind::TK_SLASHEQ: // fall through
795 case Token::Kind::TK_PERCENTEQ: // fall through
796 case Token::Kind::TK_SHLEQ: // fall through
797 case Token::Kind::TK_SHREQ: // fall through
798 case Token::Kind::TK_LOGICALANDEQ: // fall through
799 case Token::Kind::TK_LOGICALXOREQ: // fall through
800 case Token::Kind::TK_LOGICALOREQ: // fall through
801 case Token::Kind::TK_BITWISEANDEQ: // fall through
802 case Token::Kind::TK_BITWISEXOREQ: // fall through
803 case Token::Kind::TK_BITWISEOREQ: return MetalCodeGenerator::kAssignment_Precedence;
804 case Token::Kind::TK_COMMA: return MetalCodeGenerator::kSequence_Precedence;
Ethan Nicholascc305772017-10-13 16:17:45 -0400805 default: ABORT("unsupported binary operator");
806 }
807}
808
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500809void MetalCodeGenerator::writeMatrixTimesEqualHelper(const Type& left, const Type& right,
810 const Type& result) {
811 String key = "TimesEqual" + left.name() + right.name();
812 if (fHelpers.find(key) == fHelpers.end()) {
813 fExtraFunctions.printf("%s operator*=(thread %s& left, thread const %s& right) {\n"
814 " left = left * right;\n"
815 " return left;\n"
816 "}", result.name().c_str(), left.name().c_str(),
817 right.name().c_str());
818 }
819}
820
Ethan Nicholascc305772017-10-13 16:17:45 -0400821void MetalCodeGenerator::writeBinaryExpression(const BinaryExpression& b,
822 Precedence parentPrecedence) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400823 const Type& leftType = b.fLeft->type();
824 const Type& rightType = b.fRight->type();
Ethan Nicholascc305772017-10-13 16:17:45 -0400825 Precedence precedence = GetBinaryPrecedence(b.fOperator);
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500826 bool needParens = precedence >= parentPrecedence;
827 switch (b.fOperator) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400828 case Token::Kind::TK_EQEQ:
Ethan Nicholas30d30222020-09-11 12:27:26 -0400829 if (leftType.typeKind() == Type::TypeKind::kVector) {
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500830 this->write("all");
831 needParens = true;
832 }
833 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400834 case Token::Kind::TK_NEQ:
Ethan Nicholas30d30222020-09-11 12:27:26 -0400835 if (leftType.typeKind() == Type::TypeKind::kVector) {
Jim Van Verth36477b42019-04-11 14:57:30 -0400836 this->write("any");
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500837 needParens = true;
838 }
839 break;
840 default:
841 break;
842 }
843 if (needParens) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400844 this->write("(");
845 }
846 if (Compiler::IsAssignment(b.fOperator) &&
Ethan Nicholase6592142020-09-08 10:22:09 -0400847 Expression::Kind::kVariableReference == b.fLeft->kind() &&
Ethan Nicholascc305772017-10-13 16:17:45 -0400848 Variable::kParameter_Storage == ((VariableReference&) *b.fLeft).fVariable.fStorage &&
849 (((VariableReference&) *b.fLeft).fVariable.fModifiers.fFlags & Modifiers::kOut_Flag)) {
850 // writing to an out parameter. Since we have to turn those into pointers, we have to
851 // dereference it here.
852 this->write("*");
853 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400854 if (b.fOperator == Token::Kind::TK_STAREQ &&
Ethan Nicholas30d30222020-09-11 12:27:26 -0400855 leftType.typeKind() == Type::TypeKind::kMatrix &&
856 rightType.typeKind() == Type::TypeKind::kMatrix) {
857 this->writeMatrixTimesEqualHelper(leftType, rightType, b.type());
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500858 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400859 this->writeExpression(*b.fLeft, precedence);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400860 if (b.fOperator != Token::Kind::TK_EQ && Compiler::IsAssignment(b.fOperator) &&
Ethan Nicholase6592142020-09-08 10:22:09 -0400861 b.fLeft->kind() == Expression::Kind::kSwizzle && !b.fLeft->hasSideEffects()) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400862 // This doesn't compile in Metal:
863 // float4 x = float4(1);
864 // x.xy *= float2x2(...);
865 // with the error message "non-const reference cannot bind to vector element",
866 // but switching it to x.xy = x.xy * float2x2(...) fixes it. We perform this tranformation
867 // as long as the LHS has no side effects, and hope for the best otherwise.
868 this->write(" = ");
869 this->writeExpression(*b.fLeft, kAssignment_Precedence);
870 this->write(" ");
871 String op = Compiler::OperatorName(b.fOperator);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400872 SkASSERT(op.endsWith("="));
Ethan Nicholascc305772017-10-13 16:17:45 -0400873 this->write(op.substr(0, op.size() - 1).c_str());
874 this->write(" ");
875 } else {
876 this->write(String(" ") + Compiler::OperatorName(b.fOperator) + " ");
877 }
878 this->writeExpression(*b.fRight, precedence);
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500879 if (needParens) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400880 this->write(")");
881 }
882}
883
884void MetalCodeGenerator::writeTernaryExpression(const TernaryExpression& t,
885 Precedence parentPrecedence) {
886 if (kTernary_Precedence >= parentPrecedence) {
887 this->write("(");
888 }
889 this->writeExpression(*t.fTest, kTernary_Precedence);
890 this->write(" ? ");
891 this->writeExpression(*t.fIfTrue, kTernary_Precedence);
892 this->write(" : ");
893 this->writeExpression(*t.fIfFalse, kTernary_Precedence);
894 if (kTernary_Precedence >= parentPrecedence) {
895 this->write(")");
896 }
897}
898
899void MetalCodeGenerator::writePrefixExpression(const PrefixExpression& p,
900 Precedence parentPrecedence) {
901 if (kPrefix_Precedence >= parentPrecedence) {
902 this->write("(");
903 }
904 this->write(Compiler::OperatorName(p.fOperator));
905 this->writeExpression(*p.fOperand, kPrefix_Precedence);
906 if (kPrefix_Precedence >= parentPrecedence) {
907 this->write(")");
908 }
909}
910
911void MetalCodeGenerator::writePostfixExpression(const PostfixExpression& p,
912 Precedence parentPrecedence) {
913 if (kPostfix_Precedence >= parentPrecedence) {
914 this->write("(");
915 }
916 this->writeExpression(*p.fOperand, kPostfix_Precedence);
917 this->write(Compiler::OperatorName(p.fOperator));
918 if (kPostfix_Precedence >= parentPrecedence) {
919 this->write(")");
920 }
921}
922
923void MetalCodeGenerator::writeBoolLiteral(const BoolLiteral& b) {
924 this->write(b.fValue ? "true" : "false");
925}
926
927void MetalCodeGenerator::writeIntLiteral(const IntLiteral& i) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400928 if (i.type() == *fContext.fUInt_Type) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400929 this->write(to_string(i.fValue & 0xffffffff) + "u");
930 } else {
931 this->write(to_string((int32_t) i.fValue));
932 }
933}
934
935void MetalCodeGenerator::writeFloatLiteral(const FloatLiteral& f) {
936 this->write(to_string(f.fValue));
937}
938
939void MetalCodeGenerator::writeSetting(const Setting& s) {
940 ABORT("internal error; setting was not folded to a constant during compilation\n");
941}
942
943void MetalCodeGenerator::writeFunction(const FunctionDefinition& f) {
Ethan Nicholasf931e402019-07-26 15:40:33 -0400944 fRTHeightName = fProgram.fInputs.fRTHeight ? "_globals->_anonInterface0->u_skRTHeight" : "";
Ethan Nicholascc305772017-10-13 16:17:45 -0400945 const char* separator = "";
946 if ("main" == f.fDeclaration.fName) {
947 switch (fProgram.fKind) {
948 case Program::kFragment_Kind:
Timothy Liangb8eeb802018-07-23 16:46:16 -0400949 this->write("fragment Outputs fragmentMain");
Ethan Nicholascc305772017-10-13 16:17:45 -0400950 break;
951 case Program::kVertex_Kind:
Timothy Liangb8eeb802018-07-23 16:46:16 -0400952 this->write("vertex Outputs vertexMain");
Ethan Nicholascc305772017-10-13 16:17:45 -0400953 break;
954 default:
John Stilesf7d70432020-05-28 15:46:38 -0400955 SkDEBUGFAIL("unsupported kind of program");
Ethan Nicholascc305772017-10-13 16:17:45 -0400956 }
957 this->write("(Inputs _in [[stage_in]]");
958 if (-1 != fUniformBuffer) {
959 this->write(", constant Uniforms& _uniforms [[buffer(" +
960 to_string(fUniformBuffer) + ")]]");
961 }
Timothy Liang6403b0e2018-05-17 10:40:04 -0400962 for (const auto& e : fProgram) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400963 if (e.kind() == ProgramElement::Kind::kVar) {
John Stiles3dc0da62020-08-19 17:48:31 -0400964 const VarDeclarations& decls = e.as<VarDeclarations>();
Timothy Liang6403b0e2018-05-17 10:40:04 -0400965 if (!decls.fVars.size()) {
966 continue;
967 }
Timothy Liangee84fe12018-05-18 14:38:19 -0400968 for (const auto& stmt: decls.fVars) {
John Stiles3dc0da62020-08-19 17:48:31 -0400969 VarDeclaration& var = stmt->as<VarDeclaration>();
Ethan Nicholas30d30222020-09-11 12:27:26 -0400970 if (var.fVar->type().typeKind() == Type::TypeKind::kSampler) {
John Stiles08cb2c12020-07-06 10:18:49 -0400971 if (var.fVar->fModifiers.fLayout.fBinding < 0) {
972 fErrors.error(decls.fOffset,
973 "Metal samplers must have 'layout(binding=...)'");
974 }
Timothy Liang7d637782018-06-05 09:58:07 -0400975 this->write(", texture2d<float> "); // FIXME - support other texture types
Timothy Liang651286f2018-06-07 09:55:33 -0400976 this->writeName(var.fVar->fName);
Timothy Liangee84fe12018-05-18 14:38:19 -0400977 this->write("[[texture(");
Timothy Lianga06f2152018-05-24 15:33:31 -0400978 this->write(to_string(var.fVar->fModifiers.fLayout.fBinding));
979 this->write(")]]");
980 this->write(", sampler ");
Timothy Liang651286f2018-06-07 09:55:33 -0400981 this->writeName(var.fVar->fName);
Timothy Lianga06f2152018-05-24 15:33:31 -0400982 this->write(SAMPLER_SUFFIX);
983 this->write("[[sampler(");
984 this->write(to_string(var.fVar->fModifiers.fLayout.fBinding));
Timothy Liangee84fe12018-05-18 14:38:19 -0400985 this->write(")]]");
986 }
Timothy Liang6403b0e2018-05-17 10:40:04 -0400987 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400988 } else if (e.kind() == ProgramElement::Kind::kInterfaceBlock) {
Timothy Lianga06f2152018-05-24 15:33:31 -0400989 InterfaceBlock& intf = (InterfaceBlock&) e;
990 if ("sk_PerVertex" == intf.fTypeName) {
991 continue;
992 }
993 this->write(", constant ");
Ethan Nicholas30d30222020-09-11 12:27:26 -0400994 this->writeType(intf.fVariable.type());
Timothy Lianga06f2152018-05-24 15:33:31 -0400995 this->write("& " );
996 this->write(fInterfaceBlockNameMap[&intf]);
997 this->write(" [[buffer(");
Timothy Liang057c3902018-08-08 10:48:45 -0400998 this->write(to_string(intf.fVariable.fModifiers.fLayout.fBinding));
Timothy Lianga06f2152018-05-24 15:33:31 -0400999 this->write(")]]");
Timothy Liang6403b0e2018-05-17 10:40:04 -04001000 }
1001 }
Jim Van Verth6bc650e2019-02-07 14:53:23 -05001002 if (fProgram.fKind == Program::kFragment_Kind) {
1003 if (fProgram.fInputs.fRTHeight && fInterfaceBlockNameMap.empty()) {
Timothy Liang5422f9a2018-08-10 10:57:55 -04001004 this->write(", constant sksl_synthetic_uniforms& _anonInterface0 [[buffer(1)]]");
Ethan Nicholasf931e402019-07-26 15:40:33 -04001005 fRTHeightName = "_anonInterface0.u_skRTHeight";
Timothy Liang5422f9a2018-08-10 10:57:55 -04001006 }
Timothy Liang7b8875d2018-08-10 09:42:31 -04001007 this->write(", bool _frontFacing [[front_facing]]");
Timothy Liang7d637782018-06-05 09:58:07 -04001008 this->write(", float4 _fragCoord [[position]]");
Timothy Liangdc89f192018-06-13 09:20:31 -04001009 } else if (fProgram.fKind == Program::kVertex_Kind) {
1010 this->write(", uint sk_VertexID [[vertex_id]], uint sk_InstanceID [[instance_id]]");
Timothy Liang7d637782018-06-05 09:58:07 -04001011 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001012 separator = ", ";
1013 } else {
1014 this->writeType(f.fDeclaration.fReturnType);
Timothy Liang651286f2018-06-07 09:55:33 -04001015 this->write(" ");
1016 this->writeName(f.fDeclaration.fName);
1017 this->write("(");
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -04001018 Requirements requirements = this->requirements(f.fDeclaration);
1019 if (requirements & kInputs_Requirement) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001020 this->write("Inputs _in");
1021 separator = ", ";
1022 }
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -04001023 if (requirements & kOutputs_Requirement) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001024 this->write(separator);
Timothy Liangee84fe12018-05-18 14:38:19 -04001025 this->write("thread Outputs* _out");
Ethan Nicholascc305772017-10-13 16:17:45 -04001026 separator = ", ";
1027 }
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -04001028 if (requirements & kUniforms_Requirement) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001029 this->write(separator);
1030 this->write("Uniforms _uniforms");
1031 separator = ", ";
1032 }
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -04001033 if (requirements & kGlobals_Requirement) {
Timothy Liangee84fe12018-05-18 14:38:19 -04001034 this->write(separator);
1035 this->write("thread Globals* _globals");
1036 separator = ", ";
1037 }
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -04001038 if (requirements & kFragCoord_Requirement) {
1039 this->write(separator);
1040 this->write("float4 _fragCoord");
1041 separator = ", ";
1042 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001043 }
1044 for (const auto& param : f.fDeclaration.fParameters) {
1045 this->write(separator);
1046 separator = ", ";
1047 this->writeModifiers(param->fModifiers, false);
1048 std::vector<int> sizes;
Ethan Nicholas30d30222020-09-11 12:27:26 -04001049 const Type* type = &param->type();
Ethan Nicholase6592142020-09-08 10:22:09 -04001050 while (type->typeKind() == Type::TypeKind::kArray) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001051 sizes.push_back(type->columns());
1052 type = &type->componentType();
1053 }
1054 this->writeType(*type);
1055 if (param->fModifiers.fFlags & Modifiers::kOut_Flag) {
1056 this->write("*");
1057 }
Timothy Liang651286f2018-06-07 09:55:33 -04001058 this->write(" ");
1059 this->writeName(param->fName);
Ethan Nicholascc305772017-10-13 16:17:45 -04001060 for (int s : sizes) {
1061 if (s <= 0) {
1062 this->write("[]");
1063 } else {
1064 this->write("[" + to_string(s) + "]");
1065 }
1066 }
1067 }
1068 this->writeLine(") {");
1069
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001070 SkASSERT(!fProgram.fSettings.fFragColorIsInOut);
Brian Salomondc092132018-04-04 10:14:16 -04001071
Ethan Nicholascc305772017-10-13 16:17:45 -04001072 if ("main" == f.fDeclaration.fName) {
John Stilescdcdb042020-07-06 09:03:51 -04001073 this->writeGlobalInit();
Timothy Liang7d637782018-06-05 09:58:07 -04001074 this->writeLine(" Outputs _outputStruct;");
1075 this->writeLine(" thread Outputs* _out = &_outputStruct;");
Ethan Nicholascc305772017-10-13 16:17:45 -04001076 }
John Stilesc67b3622020-05-28 17:53:13 -04001077
Ethan Nicholascc305772017-10-13 16:17:45 -04001078 fFunctionHeader = "";
1079 OutputStream* oldOut = fOut;
1080 StringStream buffer;
1081 fOut = &buffer;
1082 fIndentation++;
1083 this->writeStatements(((Block&) *f.fBody).fStatements);
1084 if ("main" == f.fDeclaration.fName) {
1085 switch (fProgram.fKind) {
1086 case Program::kFragment_Kind:
Timothy Liang7d637782018-06-05 09:58:07 -04001087 this->writeLine("return *_out;");
Ethan Nicholascc305772017-10-13 16:17:45 -04001088 break;
1089 case Program::kVertex_Kind:
Timothy Liangb8eeb802018-07-23 16:46:16 -04001090 this->writeLine("_out->sk_Position.y = -_out->sk_Position.y;");
Timothy Lianga06f2152018-05-24 15:33:31 -04001091 this->writeLine("return *_out;"); // FIXME - detect if function already has return
Ethan Nicholascc305772017-10-13 16:17:45 -04001092 break;
1093 default:
John Stilesf7d70432020-05-28 15:46:38 -04001094 SkDEBUGFAIL("unsupported kind of program");
Ethan Nicholascc305772017-10-13 16:17:45 -04001095 }
1096 }
1097 fIndentation--;
1098 this->writeLine("}");
1099
1100 fOut = oldOut;
1101 this->write(fFunctionHeader);
1102 this->write(buffer.str());
1103}
1104
1105void MetalCodeGenerator::writeModifiers(const Modifiers& modifiers,
1106 bool globalContext) {
1107 if (modifiers.fFlags & Modifiers::kOut_Flag) {
1108 this->write("thread ");
1109 }
1110 if (modifiers.fFlags & Modifiers::kConst_Flag) {
Timothy Liangee84fe12018-05-18 14:38:19 -04001111 this->write("constant ");
Ethan Nicholascc305772017-10-13 16:17:45 -04001112 }
1113}
1114
1115void MetalCodeGenerator::writeInterfaceBlock(const InterfaceBlock& intf) {
1116 if ("sk_PerVertex" == intf.fTypeName) {
1117 return;
1118 }
1119 this->writeModifiers(intf.fVariable.fModifiers, true);
Timothy Liangdc89f192018-06-13 09:20:31 -04001120 this->write("struct ");
Ethan Nicholascc305772017-10-13 16:17:45 -04001121 this->writeLine(intf.fTypeName + " {");
Ethan Nicholas30d30222020-09-11 12:27:26 -04001122 const Type* structType = &intf.fVariable.type();
Timothy Lianga06f2152018-05-24 15:33:31 -04001123 fWrittenStructs.push_back(structType);
Ethan Nicholase6592142020-09-08 10:22:09 -04001124 while (structType->typeKind() == Type::TypeKind::kArray) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001125 structType = &structType->componentType();
1126 }
Timothy Liangdc89f192018-06-13 09:20:31 -04001127 fIndentation++;
1128 writeFields(structType->fields(), structType->fOffset, &intf);
Jim Van Verth3d482992019-02-07 10:48:05 -05001129 if (fProgram.fInputs.fRTHeight) {
Timothy Liang7d637782018-06-05 09:58:07 -04001130 this->writeLine("float u_skRTHeight;");
Ethan Nicholascc305772017-10-13 16:17:45 -04001131 }
1132 fIndentation--;
1133 this->write("}");
1134 if (intf.fInstanceName.size()) {
1135 this->write(" ");
1136 this->write(intf.fInstanceName);
1137 for (const auto& size : intf.fSizes) {
1138 this->write("[");
1139 if (size) {
1140 this->writeExpression(*size, kTopLevel_Precedence);
1141 }
1142 this->write("]");
1143 }
Timothy Lianga06f2152018-05-24 15:33:31 -04001144 fInterfaceBlockNameMap[&intf] = intf.fInstanceName;
1145 } else {
Timothy Liang7d637782018-06-05 09:58:07 -04001146 fInterfaceBlockNameMap[&intf] = "_anonInterface" + to_string(fAnonInterfaceCount++);
Ethan Nicholascc305772017-10-13 16:17:45 -04001147 }
1148 this->writeLine(";");
1149}
1150
Timothy Liangdc89f192018-06-13 09:20:31 -04001151void MetalCodeGenerator::writeFields(const std::vector<Type::Field>& fields, int parentOffset,
1152 const InterfaceBlock* parentIntf) {
Timothy Liang609fbe32018-08-10 16:40:49 -04001153 MemoryLayout memoryLayout(MemoryLayout::kMetal_Standard);
Timothy Liangdc89f192018-06-13 09:20:31 -04001154 int currentOffset = 0;
1155 for (const auto& field: fields) {
1156 int fieldOffset = field.fModifiers.fLayout.fOffset;
1157 const Type* fieldType = field.fType;
1158 if (fieldOffset != -1) {
1159 if (currentOffset > fieldOffset) {
1160 fErrors.error(parentOffset,
1161 "offset of field '" + field.fName + "' must be at least " +
1162 to_string((int) currentOffset));
Brian Osman8609a242020-09-08 14:01:49 -04001163 return;
Timothy Liangdc89f192018-06-13 09:20:31 -04001164 } else if (currentOffset < fieldOffset) {
1165 this->write("char pad");
1166 this->write(to_string(fPaddingCount++));
1167 this->write("[");
1168 this->write(to_string(fieldOffset - currentOffset));
1169 this->writeLine("];");
1170 currentOffset = fieldOffset;
1171 }
1172 int alignment = memoryLayout.alignment(*fieldType);
1173 if (fieldOffset % alignment) {
1174 fErrors.error(parentOffset,
1175 "offset of field '" + field.fName + "' must be a multiple of " +
1176 to_string((int) alignment));
Brian Osman8609a242020-09-08 14:01:49 -04001177 return;
Timothy Liangdc89f192018-06-13 09:20:31 -04001178 }
1179 }
Brian Osman8609a242020-09-08 14:01:49 -04001180 size_t fieldSize = memoryLayout.size(*fieldType);
1181 if (fieldSize > static_cast<size_t>(std::numeric_limits<int>::max() - currentOffset)) {
1182 fErrors.error(parentOffset, "field offset overflow");
1183 return;
1184 }
1185 currentOffset += fieldSize;
Timothy Liangdc89f192018-06-13 09:20:31 -04001186 std::vector<int> sizes;
Ethan Nicholase6592142020-09-08 10:22:09 -04001187 while (fieldType->typeKind() == Type::TypeKind::kArray) {
Timothy Liangdc89f192018-06-13 09:20:31 -04001188 sizes.push_back(fieldType->columns());
1189 fieldType = &fieldType->componentType();
1190 }
1191 this->writeModifiers(field.fModifiers, false);
1192 this->writeType(*fieldType);
1193 this->write(" ");
1194 this->writeName(field.fName);
1195 for (int s : sizes) {
1196 if (s <= 0) {
1197 this->write("[]");
1198 } else {
1199 this->write("[" + to_string(s) + "]");
1200 }
1201 }
1202 this->writeLine(";");
1203 if (parentIntf) {
1204 fInterfaceBlockMap[&field] = parentIntf;
1205 }
1206 }
1207}
1208
Ethan Nicholascc305772017-10-13 16:17:45 -04001209void MetalCodeGenerator::writeVarInitializer(const Variable& var, const Expression& value) {
1210 this->writeExpression(value, kTopLevel_Precedence);
1211}
1212
Timothy Liang651286f2018-06-07 09:55:33 -04001213void MetalCodeGenerator::writeName(const String& name) {
1214 if (fReservedWords.find(name) != fReservedWords.end()) {
1215 this->write("_"); // adding underscore before name to avoid conflict with reserved words
1216 }
1217 this->write(name);
1218}
1219
Ethan Nicholascc305772017-10-13 16:17:45 -04001220void MetalCodeGenerator::writeVarDeclarations(const VarDeclarations& decl, bool global) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001221 SkASSERT(decl.fVars.size() > 0);
Ethan Nicholascc305772017-10-13 16:17:45 -04001222 bool wroteType = false;
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001223 for (const auto& stmt : decl.fVars) {
1224 VarDeclaration& var = (VarDeclaration&) *stmt;
Timothy Liangee84fe12018-05-18 14:38:19 -04001225 if (global && !(var.fVar->fModifiers.fFlags & Modifiers::kConst_Flag)) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001226 continue;
1227 }
1228 if (wroteType) {
1229 this->write(", ");
1230 } else {
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001231 this->writeModifiers(var.fVar->fModifiers, global);
Ethan Nicholascc305772017-10-13 16:17:45 -04001232 this->writeType(decl.fBaseType);
1233 this->write(" ");
1234 wroteType = true;
1235 }
Timothy Liang651286f2018-06-07 09:55:33 -04001236 this->writeName(var.fVar->fName);
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001237 for (const auto& size : var.fSizes) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001238 this->write("[");
1239 if (size) {
1240 this->writeExpression(*size, kTopLevel_Precedence);
1241 }
1242 this->write("]");
1243 }
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001244 if (var.fValue) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001245 this->write(" = ");
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001246 this->writeVarInitializer(*var.fVar, *var.fValue);
Ethan Nicholascc305772017-10-13 16:17:45 -04001247 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001248 }
1249 if (wroteType) {
1250 this->write(";");
1251 }
1252}
1253
1254void MetalCodeGenerator::writeStatement(const Statement& s) {
Ethan Nicholase6592142020-09-08 10:22:09 -04001255 switch (s.kind()) {
1256 case Statement::Kind::kBlock:
John Stiles26f98502020-08-18 09:30:51 -04001257 this->writeBlock(s.as<Block>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001258 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001259 case Statement::Kind::kExpression:
John Stiles26f98502020-08-18 09:30:51 -04001260 this->writeExpression(*s.as<ExpressionStatement>().fExpression, kTopLevel_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001261 this->write(";");
1262 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001263 case Statement::Kind::kReturn:
John Stiles26f98502020-08-18 09:30:51 -04001264 this->writeReturnStatement(s.as<ReturnStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001265 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001266 case Statement::Kind::kVarDeclarations:
John Stiles26f98502020-08-18 09:30:51 -04001267 this->writeVarDeclarations(*s.as<VarDeclarationsStatement>().fDeclaration, false);
Ethan Nicholascc305772017-10-13 16:17:45 -04001268 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001269 case Statement::Kind::kIf:
John Stiles26f98502020-08-18 09:30:51 -04001270 this->writeIfStatement(s.as<IfStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001271 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001272 case Statement::Kind::kFor:
John Stiles26f98502020-08-18 09:30:51 -04001273 this->writeForStatement(s.as<ForStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001274 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001275 case Statement::Kind::kWhile:
John Stiles26f98502020-08-18 09:30:51 -04001276 this->writeWhileStatement(s.as<WhileStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001277 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001278 case Statement::Kind::kDo:
John Stiles26f98502020-08-18 09:30:51 -04001279 this->writeDoStatement(s.as<DoStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001280 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001281 case Statement::Kind::kSwitch:
John Stiles26f98502020-08-18 09:30:51 -04001282 this->writeSwitchStatement(s.as<SwitchStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001283 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001284 case Statement::Kind::kBreak:
Ethan Nicholascc305772017-10-13 16:17:45 -04001285 this->write("break;");
1286 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001287 case Statement::Kind::kContinue:
Ethan Nicholascc305772017-10-13 16:17:45 -04001288 this->write("continue;");
1289 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001290 case Statement::Kind::kDiscard:
Timothy Lianga06f2152018-05-24 15:33:31 -04001291 this->write("discard_fragment();");
Ethan Nicholascc305772017-10-13 16:17:45 -04001292 break;
John Stiles98c1f822020-09-09 14:18:53 -04001293 case Statement::Kind::kInlineMarker:
Ethan Nicholase6592142020-09-08 10:22:09 -04001294 case Statement::Kind::kNop:
Ethan Nicholascc305772017-10-13 16:17:45 -04001295 this->write(";");
1296 break;
1297 default:
Ethan Nicholas2a099da2020-01-02 14:40:54 -05001298#ifdef SK_DEBUG
Ethan Nicholascc305772017-10-13 16:17:45 -04001299 ABORT("unsupported statement: %s", s.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -05001300#endif
1301 break;
Ethan Nicholascc305772017-10-13 16:17:45 -04001302 }
1303}
1304
1305void MetalCodeGenerator::writeStatements(const std::vector<std::unique_ptr<Statement>>& statements) {
1306 for (const auto& s : statements) {
1307 if (!s->isEmpty()) {
1308 this->writeStatement(*s);
1309 this->writeLine();
1310 }
1311 }
1312}
1313
1314void MetalCodeGenerator::writeBlock(const Block& b) {
Ethan Nicholas70728ef2020-05-28 07:09:00 -04001315 if (b.fIsScope) {
1316 this->writeLine("{");
1317 fIndentation++;
1318 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001319 this->writeStatements(b.fStatements);
Ethan Nicholas70728ef2020-05-28 07:09:00 -04001320 if (b.fIsScope) {
1321 fIndentation--;
1322 this->write("}");
1323 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001324}
1325
1326void MetalCodeGenerator::writeIfStatement(const IfStatement& stmt) {
1327 this->write("if (");
1328 this->writeExpression(*stmt.fTest, kTopLevel_Precedence);
1329 this->write(") ");
1330 this->writeStatement(*stmt.fIfTrue);
1331 if (stmt.fIfFalse) {
1332 this->write(" else ");
1333 this->writeStatement(*stmt.fIfFalse);
1334 }
1335}
1336
1337void MetalCodeGenerator::writeForStatement(const ForStatement& f) {
1338 this->write("for (");
1339 if (f.fInitializer && !f.fInitializer->isEmpty()) {
1340 this->writeStatement(*f.fInitializer);
1341 } else {
1342 this->write("; ");
1343 }
1344 if (f.fTest) {
1345 this->writeExpression(*f.fTest, kTopLevel_Precedence);
1346 }
1347 this->write("; ");
1348 if (f.fNext) {
1349 this->writeExpression(*f.fNext, kTopLevel_Precedence);
1350 }
1351 this->write(") ");
1352 this->writeStatement(*f.fStatement);
1353}
1354
1355void MetalCodeGenerator::writeWhileStatement(const WhileStatement& w) {
1356 this->write("while (");
1357 this->writeExpression(*w.fTest, kTopLevel_Precedence);
1358 this->write(") ");
1359 this->writeStatement(*w.fStatement);
1360}
1361
1362void MetalCodeGenerator::writeDoStatement(const DoStatement& d) {
1363 this->write("do ");
1364 this->writeStatement(*d.fStatement);
1365 this->write(" while (");
1366 this->writeExpression(*d.fTest, kTopLevel_Precedence);
1367 this->write(");");
1368}
1369
1370void MetalCodeGenerator::writeSwitchStatement(const SwitchStatement& s) {
1371 this->write("switch (");
1372 this->writeExpression(*s.fValue, kTopLevel_Precedence);
1373 this->writeLine(") {");
1374 fIndentation++;
1375 for (const auto& c : s.fCases) {
1376 if (c->fValue) {
1377 this->write("case ");
1378 this->writeExpression(*c->fValue, kTopLevel_Precedence);
1379 this->writeLine(":");
1380 } else {
1381 this->writeLine("default:");
1382 }
1383 fIndentation++;
1384 for (const auto& stmt : c->fStatements) {
1385 this->writeStatement(*stmt);
1386 this->writeLine();
1387 }
1388 fIndentation--;
1389 }
1390 fIndentation--;
1391 this->write("}");
1392}
1393
1394void MetalCodeGenerator::writeReturnStatement(const ReturnStatement& r) {
1395 this->write("return");
1396 if (r.fExpression) {
1397 this->write(" ");
1398 this->writeExpression(*r.fExpression, kTopLevel_Precedence);
1399 }
1400 this->write(";");
1401}
1402
1403void MetalCodeGenerator::writeHeader() {
1404 this->write("#include <metal_stdlib>\n");
1405 this->write("#include <simd/simd.h>\n");
1406 this->write("using namespace metal;\n");
1407}
1408
1409void MetalCodeGenerator::writeUniformStruct() {
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001410 for (const auto& e : fProgram) {
Ethan Nicholase6592142020-09-08 10:22:09 -04001411 if (e.kind() == ProgramElement::Kind::kVar) {
John Stiles3dc0da62020-08-19 17:48:31 -04001412 const VarDeclarations& decls = e.as<VarDeclarations>();
Ethan Nicholascc305772017-10-13 16:17:45 -04001413 if (!decls.fVars.size()) {
1414 continue;
1415 }
John Stiles3dc0da62020-08-19 17:48:31 -04001416 const Variable& first = *decls.fVars[0]->as<VarDeclaration>().fVar;
Timothy Lianga06f2152018-05-24 15:33:31 -04001417 if (first.fModifiers.fFlags & Modifiers::kUniform_Flag &&
Ethan Nicholas30d30222020-09-11 12:27:26 -04001418 first.type().typeKind() != Type::TypeKind::kSampler) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001419 if (-1 == fUniformBuffer) {
1420 this->write("struct Uniforms {\n");
1421 fUniformBuffer = first.fModifiers.fLayout.fSet;
1422 if (-1 == fUniformBuffer) {
1423 fErrors.error(decls.fOffset, "Metal uniforms must have 'layout(set=...)'");
1424 }
1425 } else if (first.fModifiers.fLayout.fSet != fUniformBuffer) {
1426 if (-1 == fUniformBuffer) {
1427 fErrors.error(decls.fOffset, "Metal backend requires all uniforms to have "
1428 "the same 'layout(set=...)'");
1429 }
1430 }
1431 this->write(" ");
Ethan Nicholas30d30222020-09-11 12:27:26 -04001432 this->writeType(first.type());
Ethan Nicholascc305772017-10-13 16:17:45 -04001433 this->write(" ");
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001434 for (const auto& stmt : decls.fVars) {
John Stiles3dc0da62020-08-19 17:48:31 -04001435 const VarDeclaration& var = stmt->as<VarDeclaration>();
Timothy Liang651286f2018-06-07 09:55:33 -04001436 this->writeName(var.fVar->fName);
Ethan Nicholascc305772017-10-13 16:17:45 -04001437 }
1438 this->write(";\n");
1439 }
1440 }
1441 }
1442 if (-1 != fUniformBuffer) {
1443 this->write("};\n");
1444 }
1445}
1446
1447void MetalCodeGenerator::writeInputStruct() {
1448 this->write("struct Inputs {\n");
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001449 for (const auto& e : fProgram) {
Ethan Nicholase6592142020-09-08 10:22:09 -04001450 if (e.kind() == ProgramElement::Kind::kVar) {
John Stiles3dc0da62020-08-19 17:48:31 -04001451 const VarDeclarations& decls = e.as<VarDeclarations>();
Ethan Nicholascc305772017-10-13 16:17:45 -04001452 if (!decls.fVars.size()) {
1453 continue;
1454 }
John Stiles3dc0da62020-08-19 17:48:31 -04001455 const Variable& first = *decls.fVars[0]->as<VarDeclaration>().fVar;
Ethan Nicholascc305772017-10-13 16:17:45 -04001456 if (first.fModifiers.fFlags & Modifiers::kIn_Flag &&
1457 -1 == first.fModifiers.fLayout.fBuiltin) {
1458 this->write(" ");
Ethan Nicholas30d30222020-09-11 12:27:26 -04001459 this->writeType(first.type());
Ethan Nicholascc305772017-10-13 16:17:45 -04001460 this->write(" ");
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001461 for (const auto& stmt : decls.fVars) {
John Stiles3dc0da62020-08-19 17:48:31 -04001462 const VarDeclaration& var = stmt->as<VarDeclaration>();
Timothy Liang651286f2018-06-07 09:55:33 -04001463 this->writeName(var.fVar->fName);
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001464 if (-1 != var.fVar->fModifiers.fLayout.fLocation) {
Timothy Liang7d637782018-06-05 09:58:07 -04001465 if (fProgram.fKind == Program::kVertex_Kind) {
1466 this->write(" [[attribute(" +
1467 to_string(var.fVar->fModifiers.fLayout.fLocation) + ")]]");
1468 } else if (fProgram.fKind == Program::kFragment_Kind) {
1469 this->write(" [[user(locn" +
1470 to_string(var.fVar->fModifiers.fLayout.fLocation) + ")]]");
1471 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001472 }
1473 }
1474 this->write(";\n");
1475 }
1476 }
1477 }
1478 this->write("};\n");
1479}
1480
1481void MetalCodeGenerator::writeOutputStruct() {
1482 this->write("struct Outputs {\n");
Timothy Liang7d637782018-06-05 09:58:07 -04001483 if (fProgram.fKind == Program::kVertex_Kind) {
Timothy Liangb8eeb802018-07-23 16:46:16 -04001484 this->write(" float4 sk_Position [[position]];\n");
Timothy Liang7d637782018-06-05 09:58:07 -04001485 } else if (fProgram.fKind == Program::kFragment_Kind) {
Timothy Liangde0be802018-08-10 13:48:08 -04001486 this->write(" float4 sk_FragColor [[color(0)]];\n");
Timothy Liang7d637782018-06-05 09:58:07 -04001487 }
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001488 for (const auto& e : fProgram) {
Ethan Nicholase6592142020-09-08 10:22:09 -04001489 if (e.kind() == ProgramElement::Kind::kVar) {
John Stiles3dc0da62020-08-19 17:48:31 -04001490 const VarDeclarations& decls = e.as<VarDeclarations>();
Ethan Nicholascc305772017-10-13 16:17:45 -04001491 if (!decls.fVars.size()) {
1492 continue;
1493 }
John Stiles3dc0da62020-08-19 17:48:31 -04001494 const Variable& first = *decls.fVars[0]->as<VarDeclaration>().fVar;
Ethan Nicholascc305772017-10-13 16:17:45 -04001495 if (first.fModifiers.fFlags & Modifiers::kOut_Flag &&
1496 -1 == first.fModifiers.fLayout.fBuiltin) {
1497 this->write(" ");
Ethan Nicholas30d30222020-09-11 12:27:26 -04001498 this->writeType(first.type());
Ethan Nicholascc305772017-10-13 16:17:45 -04001499 this->write(" ");
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001500 for (const auto& stmt : decls.fVars) {
John Stiles3dc0da62020-08-19 17:48:31 -04001501 const VarDeclaration& var = stmt->as<VarDeclaration>();
Timothy Liang651286f2018-06-07 09:55:33 -04001502 this->writeName(var.fVar->fName);
Timothy Liang7d637782018-06-05 09:58:07 -04001503 if (fProgram.fKind == Program::kVertex_Kind) {
1504 this->write(" [[user(locn" +
1505 to_string(var.fVar->fModifiers.fLayout.fLocation) + ")]]");
1506 } else if (fProgram.fKind == Program::kFragment_Kind) {
1507 this->write(" [[color(" +
Timothy Liangde0be802018-08-10 13:48:08 -04001508 to_string(var.fVar->fModifiers.fLayout.fLocation) +")");
1509 int colorIndex = var.fVar->fModifiers.fLayout.fIndex;
1510 if (colorIndex) {
1511 this->write(", index(" + to_string(colorIndex) + ")");
1512 }
1513 this->write("]]");
Timothy Liang7d637782018-06-05 09:58:07 -04001514 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001515 }
1516 this->write(";\n");
1517 }
1518 }
Timothy Liang7d637782018-06-05 09:58:07 -04001519 }
1520 if (fProgram.fKind == Program::kVertex_Kind) {
Jim Van Verth3913d3e2020-08-31 15:16:57 -04001521 this->write(" float sk_PointSize [[point_size]];\n");
Timothy Liang7d637782018-06-05 09:58:07 -04001522 }
1523 this->write("};\n");
1524}
1525
1526void MetalCodeGenerator::writeInterfaceBlocks() {
1527 bool wroteInterfaceBlock = false;
1528 for (const auto& e : fProgram) {
Ethan Nicholase6592142020-09-08 10:22:09 -04001529 if (e.kind() == ProgramElement::Kind::kInterfaceBlock) {
John Stiles3dc0da62020-08-19 17:48:31 -04001530 this->writeInterfaceBlock(e.as<InterfaceBlock>());
Timothy Liang7d637782018-06-05 09:58:07 -04001531 wroteInterfaceBlock = true;
1532 }
1533 }
Jim Van Verth3d482992019-02-07 10:48:05 -05001534 if (!wroteInterfaceBlock && fProgram.fInputs.fRTHeight) {
Timothy Liang7d637782018-06-05 09:58:07 -04001535 this->writeLine("struct sksl_synthetic_uniforms {");
1536 this->writeLine(" float u_skRTHeight;");
1537 this->writeLine("};");
1538 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001539}
1540
John Stilescdcdb042020-07-06 09:03:51 -04001541void MetalCodeGenerator::visitGlobalStruct(GlobalStructVisitor* visitor) {
1542 // Visit the interface blocks.
1543 for (const auto& [interfaceType, interfaceName] : fInterfaceBlockNameMap) {
1544 visitor->VisitInterfaceBlock(*interfaceType, interfaceName);
1545 }
1546 for (const ProgramElement& element : fProgram) {
Ethan Nicholase6592142020-09-08 10:22:09 -04001547 if (element.kind() != ProgramElement::Kind::kVar) {
John Stilescdcdb042020-07-06 09:03:51 -04001548 continue;
Timothy Liang7d637782018-06-05 09:58:07 -04001549 }
John Stilescdcdb042020-07-06 09:03:51 -04001550 const VarDeclarations& decls = static_cast<const VarDeclarations&>(element);
1551 if (decls.fVars.empty()) {
1552 continue;
1553 }
1554 const Variable& first = *((VarDeclaration&) *decls.fVars[0]).fVar;
1555 if ((!first.fModifiers.fFlags && -1 == first.fModifiers.fLayout.fBuiltin) ||
Ethan Nicholas30d30222020-09-11 12:27:26 -04001556 first.type().typeKind() == Type::TypeKind::kSampler) {
John Stilescdcdb042020-07-06 09:03:51 -04001557 for (const auto& stmt : decls.fVars) {
1558 VarDeclaration& var = static_cast<VarDeclaration&>(*stmt);
John Stilesc67b3622020-05-28 17:53:13 -04001559
Ethan Nicholas30d30222020-09-11 12:27:26 -04001560 if (var.fVar->type().typeKind() == Type::TypeKind::kSampler) {
John Stilescdcdb042020-07-06 09:03:51 -04001561 // Samplers are represented as a "texture/sampler" duo in the global struct.
Ethan Nicholas30d30222020-09-11 12:27:26 -04001562 visitor->VisitTexture(first.type(), var.fVar->fName);
1563 visitor->VisitSampler(first.type(), String(var.fVar->fName) + SAMPLER_SUFFIX);
John Stilescdcdb042020-07-06 09:03:51 -04001564 } else {
1565 // Visit a regular variable.
1566 visitor->VisitVariable(*var.fVar, var.fValue.get());
Timothy Liangee84fe12018-05-18 14:38:19 -04001567 }
Timothy Liangee84fe12018-05-18 14:38:19 -04001568 }
1569 }
1570 }
John Stilescdcdb042020-07-06 09:03:51 -04001571}
1572
1573void MetalCodeGenerator::writeGlobalStruct() {
1574 class : public GlobalStructVisitor {
1575 public:
1576 void VisitInterfaceBlock(const InterfaceBlock& block, const String& blockName) override {
1577 this->AddElement();
1578 fCodeGen->write(" constant ");
1579 fCodeGen->write(block.fTypeName);
1580 fCodeGen->write("* ");
1581 fCodeGen->writeName(blockName);
1582 fCodeGen->write(";\n");
1583 }
1584 void VisitTexture(const Type& type, const String& name) override {
1585 this->AddElement();
1586 fCodeGen->write(" ");
1587 fCodeGen->writeType(type);
1588 fCodeGen->write(" ");
1589 fCodeGen->writeName(name);
1590 fCodeGen->write(";\n");
1591 }
1592 void VisitSampler(const Type&, const String& name) override {
1593 this->AddElement();
1594 fCodeGen->write(" sampler ");
1595 fCodeGen->writeName(name);
1596 fCodeGen->write(";\n");
1597 }
1598 void VisitVariable(const Variable& var, const Expression* value) override {
1599 this->AddElement();
1600 fCodeGen->write(" ");
Ethan Nicholas30d30222020-09-11 12:27:26 -04001601 fCodeGen->writeType(var.type());
John Stilescdcdb042020-07-06 09:03:51 -04001602 fCodeGen->write(" ");
1603 fCodeGen->writeName(var.fName);
1604 fCodeGen->write(";\n");
1605 }
1606 void AddElement() {
1607 if (fFirst) {
1608 fCodeGen->write("struct Globals {\n");
1609 fFirst = false;
1610 }
1611 }
1612 void Finish() {
1613 if (!fFirst) {
1614 fCodeGen->write("};");
1615 fFirst = true;
1616 }
1617 }
1618
1619 MetalCodeGenerator* fCodeGen = nullptr;
1620 bool fFirst = true;
1621 } visitor;
1622
1623 visitor.fCodeGen = this;
1624 this->visitGlobalStruct(&visitor);
1625 visitor.Finish();
1626}
1627
1628void MetalCodeGenerator::writeGlobalInit() {
1629 class : public GlobalStructVisitor {
1630 public:
1631 void VisitInterfaceBlock(const InterfaceBlock& blockType,
1632 const String& blockName) override {
1633 this->AddElement();
1634 fCodeGen->write("&");
1635 fCodeGen->writeName(blockName);
1636 }
1637 void VisitTexture(const Type&, const String& name) override {
1638 this->AddElement();
1639 fCodeGen->writeName(name);
1640 }
1641 void VisitSampler(const Type&, const String& name) override {
1642 this->AddElement();
1643 fCodeGen->writeName(name);
1644 }
1645 void VisitVariable(const Variable& var, const Expression* value) override {
1646 this->AddElement();
1647 if (value) {
1648 fCodeGen->writeVarInitializer(var, *value);
1649 } else {
1650 fCodeGen->write("{}");
1651 }
1652 }
1653 void AddElement() {
1654 if (fFirst) {
1655 fCodeGen->write(" Globals globalStruct{");
1656 fFirst = false;
1657 } else {
1658 fCodeGen->write(", ");
1659 }
1660 }
1661 void Finish() {
1662 if (!fFirst) {
1663 fCodeGen->writeLine("};");
1664 fCodeGen->writeLine(" thread Globals* _globals = &globalStruct;");
1665 fCodeGen->writeLine(" (void)_globals;");
1666 }
1667 }
1668 MetalCodeGenerator* fCodeGen = nullptr;
1669 bool fFirst = true;
1670 } visitor;
1671
1672 visitor.fCodeGen = this;
1673 this->visitGlobalStruct(&visitor);
1674 visitor.Finish();
Timothy Liangee84fe12018-05-18 14:38:19 -04001675}
1676
Ethan Nicholascc305772017-10-13 16:17:45 -04001677void MetalCodeGenerator::writeProgramElement(const ProgramElement& e) {
Ethan Nicholase6592142020-09-08 10:22:09 -04001678 switch (e.kind()) {
1679 case ProgramElement::Kind::kExtension:
Ethan Nicholascc305772017-10-13 16:17:45 -04001680 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001681 case ProgramElement::Kind::kVar: {
John Stiles3dc0da62020-08-19 17:48:31 -04001682 const VarDeclarations& decl = e.as<VarDeclarations>();
Ethan Nicholascc305772017-10-13 16:17:45 -04001683 if (decl.fVars.size() > 0) {
John Stiles3dc0da62020-08-19 17:48:31 -04001684 int builtin = decl.fVars[0]->as<VarDeclaration>().fVar->fModifiers.fLayout.fBuiltin;
Ethan Nicholascc305772017-10-13 16:17:45 -04001685 if (-1 == builtin) {
1686 // normal var
1687 this->writeVarDeclarations(decl, true);
1688 this->writeLine();
1689 } else if (SK_FRAGCOLOR_BUILTIN == builtin) {
1690 // ignore
1691 }
1692 }
1693 break;
1694 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001695 case ProgramElement::Kind::kInterfaceBlock:
Timothy Liang7d637782018-06-05 09:58:07 -04001696 // handled in writeInterfaceBlocks, do nothing
Ethan Nicholascc305772017-10-13 16:17:45 -04001697 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001698 case ProgramElement::Kind::kFunction:
John Stiles3dc0da62020-08-19 17:48:31 -04001699 this->writeFunction(e.as<FunctionDefinition>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001700 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001701 case ProgramElement::Kind::kModifiers:
John Stiles3dc0da62020-08-19 17:48:31 -04001702 this->writeModifiers(e.as<ModifiersDeclaration>().fModifiers, true);
Ethan Nicholascc305772017-10-13 16:17:45 -04001703 this->writeLine(";");
1704 break;
1705 default:
Ethan Nicholas2a099da2020-01-02 14:40:54 -05001706#ifdef SK_DEBUG
1707 ABORT("unsupported program element: %s\n", e.description().c_str());
1708#endif
1709 break;
Ethan Nicholascc305772017-10-13 16:17:45 -04001710 }
1711}
1712
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001713MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const Expression* e) {
1714 if (!e) {
1715 return kNo_Requirements;
1716 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001717 switch (e->kind()) {
1718 case Expression::Kind::kFunctionCall: {
John Stiles3dc0da62020-08-19 17:48:31 -04001719 const FunctionCall& f = e->as<FunctionCall>();
Ethan Nicholascc305772017-10-13 16:17:45 -04001720 Requirements result = this->requirements(f.fFunction);
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001721 for (const auto& arg : f.fArguments) {
1722 result |= this->requirements(arg.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001723 }
1724 return result;
1725 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001726 case Expression::Kind::kConstructor: {
John Stiles3dc0da62020-08-19 17:48:31 -04001727 const Constructor& c = e->as<Constructor>();
Ethan Nicholascc305772017-10-13 16:17:45 -04001728 Requirements result = kNo_Requirements;
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001729 for (const auto& arg : c.fArguments) {
1730 result |= this->requirements(arg.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001731 }
1732 return result;
1733 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001734 case Expression::Kind::kFieldAccess: {
John Stiles3dc0da62020-08-19 17:48:31 -04001735 const FieldAccess& f = e->as<FieldAccess>();
Timothy Liang7d637782018-06-05 09:58:07 -04001736 if (FieldAccess::kAnonymousInterfaceBlock_OwnerKind == f.fOwnerKind) {
1737 return kGlobals_Requirement;
1738 }
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001739 return this->requirements(f.fBase.get());
Timothy Liang7d637782018-06-05 09:58:07 -04001740 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001741 case Expression::Kind::kSwizzle:
John Stiles3dc0da62020-08-19 17:48:31 -04001742 return this->requirements(e->as<Swizzle>().fBase.get());
Ethan Nicholase6592142020-09-08 10:22:09 -04001743 case Expression::Kind::kBinary: {
1744 const BinaryExpression& bin = e->as<BinaryExpression>();
1745 return this->requirements(bin.fLeft.get()) |
1746 this->requirements(bin.fRight.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001747 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001748 case Expression::Kind::kIndex: {
John Stiles3dc0da62020-08-19 17:48:31 -04001749 const IndexExpression& idx = e->as<IndexExpression>();
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001750 return this->requirements(idx.fBase.get()) | this->requirements(idx.fIndex.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001751 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001752 case Expression::Kind::kPrefix:
John Stiles3dc0da62020-08-19 17:48:31 -04001753 return this->requirements(e->as<PrefixExpression>().fOperand.get());
Ethan Nicholase6592142020-09-08 10:22:09 -04001754 case Expression::Kind::kPostfix:
John Stiles3dc0da62020-08-19 17:48:31 -04001755 return this->requirements(e->as<PostfixExpression>().fOperand.get());
Ethan Nicholase6592142020-09-08 10:22:09 -04001756 case Expression::Kind::kTernary: {
John Stiles3dc0da62020-08-19 17:48:31 -04001757 const TernaryExpression& t = e->as<TernaryExpression>();
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001758 return this->requirements(t.fTest.get()) | this->requirements(t.fIfTrue.get()) |
1759 this->requirements(t.fIfFalse.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001760 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001761 case Expression::Kind::kVariableReference: {
John Stiles3dc0da62020-08-19 17:48:31 -04001762 const VariableReference& v = e->as<VariableReference>();
Ethan Nicholascc305772017-10-13 16:17:45 -04001763 Requirements result = kNo_Requirements;
1764 if (v.fVariable.fModifiers.fLayout.fBuiltin == SK_FRAGCOORD_BUILTIN) {
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -04001765 result = kGlobals_Requirement | kFragCoord_Requirement;
Ethan Nicholascc305772017-10-13 16:17:45 -04001766 } else if (Variable::kGlobal_Storage == v.fVariable.fStorage) {
1767 if (v.fVariable.fModifiers.fFlags & Modifiers::kIn_Flag) {
1768 result = kInputs_Requirement;
1769 } else if (v.fVariable.fModifiers.fFlags & Modifiers::kOut_Flag) {
1770 result = kOutputs_Requirement;
Timothy Lianga06f2152018-05-24 15:33:31 -04001771 } else if (v.fVariable.fModifiers.fFlags & Modifiers::kUniform_Flag &&
Ethan Nicholas30d30222020-09-11 12:27:26 -04001772 v.fVariable.type().typeKind() != Type::TypeKind::kSampler) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001773 result = kUniforms_Requirement;
Timothy Liangee84fe12018-05-18 14:38:19 -04001774 } else {
1775 result = kGlobals_Requirement;
Ethan Nicholascc305772017-10-13 16:17:45 -04001776 }
1777 }
1778 return result;
1779 }
1780 default:
1781 return kNo_Requirements;
1782 }
1783}
1784
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001785MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const Statement* s) {
1786 if (!s) {
1787 return kNo_Requirements;
1788 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001789 switch (s->kind()) {
1790 case Statement::Kind::kBlock: {
Ethan Nicholascc305772017-10-13 16:17:45 -04001791 Requirements result = kNo_Requirements;
John Stiles3dc0da62020-08-19 17:48:31 -04001792 for (const auto& child : s->as<Block>().fStatements) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001793 result |= this->requirements(child.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001794 }
1795 return result;
1796 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001797 case Statement::Kind::kVarDeclaration: {
John Stiles3dc0da62020-08-19 17:48:31 -04001798 const VarDeclaration& var = s->as<VarDeclaration>();
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001799 return this->requirements(var.fValue.get());
Timothy Liang7d637782018-06-05 09:58:07 -04001800 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001801 case Statement::Kind::kVarDeclarations: {
Timothy Liang7d637782018-06-05 09:58:07 -04001802 Requirements result = kNo_Requirements;
John Stiles3dc0da62020-08-19 17:48:31 -04001803 const VarDeclarations& decls = *s->as<VarDeclarationsStatement>().fDeclaration;
Timothy Liang7d637782018-06-05 09:58:07 -04001804 for (const auto& stmt : decls.fVars) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001805 result |= this->requirements(stmt.get());
Timothy Liang7d637782018-06-05 09:58:07 -04001806 }
1807 return result;
1808 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001809 case Statement::Kind::kExpression:
John Stiles3dc0da62020-08-19 17:48:31 -04001810 return this->requirements(s->as<ExpressionStatement>().fExpression.get());
Ethan Nicholase6592142020-09-08 10:22:09 -04001811 case Statement::Kind::kReturn: {
John Stiles3dc0da62020-08-19 17:48:31 -04001812 const ReturnStatement& r = s->as<ReturnStatement>();
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001813 return this->requirements(r.fExpression.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001814 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001815 case Statement::Kind::kIf: {
John Stiles3dc0da62020-08-19 17:48:31 -04001816 const IfStatement& i = s->as<IfStatement>();
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001817 return this->requirements(i.fTest.get()) |
1818 this->requirements(i.fIfTrue.get()) |
1819 this->requirements(i.fIfFalse.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001820 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001821 case Statement::Kind::kFor: {
John Stiles3dc0da62020-08-19 17:48:31 -04001822 const ForStatement& f = s->as<ForStatement>();
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001823 return this->requirements(f.fInitializer.get()) |
1824 this->requirements(f.fTest.get()) |
1825 this->requirements(f.fNext.get()) |
1826 this->requirements(f.fStatement.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001827 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001828 case Statement::Kind::kWhile: {
John Stiles3dc0da62020-08-19 17:48:31 -04001829 const WhileStatement& w = s->as<WhileStatement>();
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001830 return this->requirements(w.fTest.get()) |
1831 this->requirements(w.fStatement.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001832 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001833 case Statement::Kind::kDo: {
John Stiles3dc0da62020-08-19 17:48:31 -04001834 const DoStatement& d = s->as<DoStatement>();
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001835 return this->requirements(d.fTest.get()) |
1836 this->requirements(d.fStatement.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001837 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001838 case Statement::Kind::kSwitch: {
John Stiles3dc0da62020-08-19 17:48:31 -04001839 const SwitchStatement& sw = s->as<SwitchStatement>();
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001840 Requirements result = this->requirements(sw.fValue.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001841 for (const auto& c : sw.fCases) {
1842 for (const auto& st : c->fStatements) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001843 result |= this->requirements(st.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001844 }
1845 }
1846 return result;
1847 }
1848 default:
1849 return kNo_Requirements;
1850 }
1851}
1852
1853MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const FunctionDeclaration& f) {
1854 if (f.fBuiltin) {
1855 return kNo_Requirements;
1856 }
1857 auto found = fRequirements.find(&f);
1858 if (found == fRequirements.end()) {
Ethan Nicholas65a8f562019-04-19 14:00:26 -04001859 fRequirements[&f] = kNo_Requirements;
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001860 for (const auto& e : fProgram) {
Ethan Nicholase6592142020-09-08 10:22:09 -04001861 if (e.kind() == ProgramElement::Kind::kFunction) {
John Stiles3dc0da62020-08-19 17:48:31 -04001862 const FunctionDefinition& def = e.as<FunctionDefinition>();
Ethan Nicholascc305772017-10-13 16:17:45 -04001863 if (&def.fDeclaration == &f) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001864 Requirements reqs = this->requirements(def.fBody.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001865 fRequirements[&f] = reqs;
1866 return reqs;
1867 }
1868 }
1869 }
1870 }
1871 return found->second;
1872}
1873
Timothy Liangb8eeb802018-07-23 16:46:16 -04001874bool MetalCodeGenerator::generateCode() {
Ethan Nicholascc305772017-10-13 16:17:45 -04001875 OutputStream* rawOut = fOut;
1876 fOut = &fHeader;
1877 fProgramKind = fProgram.fKind;
1878 this->writeHeader();
1879 this->writeUniformStruct();
1880 this->writeInputStruct();
Timothy Liang7d637782018-06-05 09:58:07 -04001881 this->writeOutputStruct();
1882 this->writeInterfaceBlocks();
Timothy Liangee84fe12018-05-18 14:38:19 -04001883 this->writeGlobalStruct();
Ethan Nicholascc305772017-10-13 16:17:45 -04001884 StringStream body;
1885 fOut = &body;
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001886 for (const auto& e : fProgram) {
1887 this->writeProgramElement(e);
Ethan Nicholascc305772017-10-13 16:17:45 -04001888 }
1889 fOut = rawOut;
1890
1891 write_stringstream(fHeader, *rawOut);
Chris Daltondba7aab2018-11-15 10:57:49 -05001892 write_stringstream(fExtraFunctions, *rawOut);
Ethan Nicholascc305772017-10-13 16:17:45 -04001893 write_stringstream(body, *rawOut);
Brian Osman8609a242020-09-08 14:01:49 -04001894 return 0 == fErrors.errorCount();
Ethan Nicholascc305772017-10-13 16:17:45 -04001895}
1896
John Stilesa6841be2020-08-06 14:11:56 -04001897} // namespace SkSL