blob: 5f4160a57c461ebe52ea683f8fb88d1f85591995 [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) {
Ethan Nicholasefb09e22020-09-30 10:17:00 -040076 this->writeLine("#extension " + ext.name() + " : enable");
Ethan Nicholascc305772017-10-13 16:17:45 -040077}
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) {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400175 auto i = fIntrinsicMap.find(c.function().name());
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:
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400184 this->writeExpression(*c.arguments()[0], kSequence_Precedence);
Timothy Lianga06f2152018-05-24 15:33:31 -0400185 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 }
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400207 this->writeExpression(*c.arguments()[1], kSequence_Precedence);
Timothy Lianga06f2152018-05-24 15:33:31 -0400208 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) {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400215 const FunctionDeclaration& function = c.function();
216 const std::vector<std::unique_ptr<Expression>>& arguments = c.arguments();
217 const auto& entry = fIntrinsicMap.find(function.name());
Timothy Liang6403b0e2018-05-17 10:40:04 -0400218 if (entry != fIntrinsicMap.end()) {
219 this->writeIntrinsicCall(c);
220 return;
221 }
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400222 const StringFragment& name = function.name();
223 if (function.fBuiltin && name == "atan" && arguments.size() == 2) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400224 this->write("atan2");
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400225 } else if (function.fBuiltin && name == "inversesqrt") {
Timothy Lianga06f2152018-05-24 15:33:31 -0400226 this->write("rsqrt");
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400227 } else if (function.fBuiltin && name == "inverse") {
228 SkASSERT(arguments.size() == 1);
229 this->writeInverseHack(*arguments[0]);
230 } else if (function.fBuiltin && name == "dFdx") {
Timothy Liang7d637782018-06-05 09:58:07 -0400231 this->write("dfdx");
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400232 } else if (function.fBuiltin && name == "dFdy") {
Chris Daltonb8af5ad2019-02-25 14:54:21 -0700233 // Flipping Y also negates the Y derivatives.
234 this->write((fProgram.fSettings.fFlipY) ? "-dfdy" : "dfdy");
Ethan Nicholascc305772017-10-13 16:17:45 -0400235 } else {
Ethan Nicholase2c49992020-10-05 11:49:11 -0400236 this->writeName(name);
Ethan Nicholascc305772017-10-13 16:17:45 -0400237 }
238 this->write("(");
239 const char* separator = "";
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400240 if (this->requirements(function) & kInputs_Requirement) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400241 this->write("_in");
242 separator = ", ";
243 }
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400244 if (this->requirements(function) & kOutputs_Requirement) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400245 this->write(separator);
246 this->write("_out");
247 separator = ", ";
248 }
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400249 if (this->requirements(function) & kUniforms_Requirement) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400250 this->write(separator);
251 this->write("_uniforms");
252 separator = ", ";
253 }
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400254 if (this->requirements(function) & kGlobals_Requirement) {
Timothy Liangee84fe12018-05-18 14:38:19 -0400255 this->write(separator);
256 this->write("_globals");
257 separator = ", ";
258 }
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400259 if (this->requirements(function) & kFragCoord_Requirement) {
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -0400260 this->write(separator);
261 this->write("_fragCoord");
262 separator = ", ";
263 }
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400264 for (size_t i = 0; i < arguments.size(); ++i) {
265 const Expression& arg = *arguments[i];
Ethan Nicholascc305772017-10-13 16:17:45 -0400266 this->write(separator);
267 separator = ", ";
Ethan Nicholas041fd0a2020-10-07 16:42:04 -0400268 if (function.fParameters[i]->modifiers().fFlags & Modifiers::kOut_Flag) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400269 this->write("&");
270 }
271 this->writeExpression(arg, kSequence_Precedence);
272 }
273 this->write(")");
274}
275
Chris Daltondba7aab2018-11-15 10:57:49 -0500276void MetalCodeGenerator::writeInverseHack(const Expression& mat) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400277 const Type& type = mat.type();
278 const String& typeName = type.name();
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500279 String name = typeName + "_inverse";
Ethan Nicholas30d30222020-09-11 12:27:26 -0400280 if (type == *fContext.fFloat2x2_Type || type == *fContext.fHalf2x2_Type) {
Chris Daltondba7aab2018-11-15 10:57:49 -0500281 if (fWrittenIntrinsics.find(name) == fWrittenIntrinsics.end()) {
282 fWrittenIntrinsics.insert(name);
283 fExtraFunctions.writeText((
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500284 typeName + " " + name + "(" + typeName + " m) {"
Chris Daltondba7aab2018-11-15 10:57:49 -0500285 " return float2x2(m[1][1], -m[0][1], -m[1][0], m[0][0]) * (1/determinant(m));"
286 "}"
287 ).c_str());
288 }
289 }
Ethan Nicholas30d30222020-09-11 12:27:26 -0400290 else if (type == *fContext.fFloat3x3_Type || type == *fContext.fHalf3x3_Type) {
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500291 if (fWrittenIntrinsics.find(name) == fWrittenIntrinsics.end()) {
292 fWrittenIntrinsics.insert(name);
293 fExtraFunctions.writeText((
294 typeName + " " + name + "(" + typeName + " m) {"
295 " float a00 = m[0][0], a01 = m[0][1], a02 = m[0][2];"
296 " float a10 = m[1][0], a11 = m[1][1], a12 = m[1][2];"
297 " float a20 = m[2][0], a21 = m[2][1], a22 = m[2][2];"
298 " float b01 = a22 * a11 - a12 * a21;"
299 " float b11 = -a22 * a10 + a12 * a20;"
300 " float b21 = a21 * a10 - a11 * a20;"
301 " float det = a00 * b01 + a01 * b11 + a02 * b21;"
302 " return " + typeName +
303 " (b01, (-a22 * a01 + a02 * a21), (a12 * a01 - a02 * a11),"
304 " b11, (a22 * a00 - a02 * a20), (-a12 * a00 + a02 * a10),"
305 " b21, (-a21 * a00 + a01 * a20), (a11 * a00 - a01 * a10)) * "
306 " (1/det);"
307 "}"
308 ).c_str());
309 }
310 }
Ethan Nicholas30d30222020-09-11 12:27:26 -0400311 else if (type == *fContext.fFloat4x4_Type || type == *fContext.fHalf4x4_Type) {
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500312 if (fWrittenIntrinsics.find(name) == fWrittenIntrinsics.end()) {
313 fWrittenIntrinsics.insert(name);
314 fExtraFunctions.writeText((
315 typeName + " " + name + "(" + typeName + " m) {"
316 " float a00 = m[0][0], a01 = m[0][1], a02 = m[0][2], a03 = m[0][3];"
317 " float a10 = m[1][0], a11 = m[1][1], a12 = m[1][2], a13 = m[1][3];"
318 " float a20 = m[2][0], a21 = m[2][1], a22 = m[2][2], a23 = m[2][3];"
319 " float a30 = m[3][0], a31 = m[3][1], a32 = m[3][2], a33 = m[3][3];"
320 " float b00 = a00 * a11 - a01 * a10;"
321 " float b01 = a00 * a12 - a02 * a10;"
322 " float b02 = a00 * a13 - a03 * a10;"
323 " float b03 = a01 * a12 - a02 * a11;"
324 " float b04 = a01 * a13 - a03 * a11;"
325 " float b05 = a02 * a13 - a03 * a12;"
326 " float b06 = a20 * a31 - a21 * a30;"
327 " float b07 = a20 * a32 - a22 * a30;"
328 " float b08 = a20 * a33 - a23 * a30;"
329 " float b09 = a21 * a32 - a22 * a31;"
330 " float b10 = a21 * a33 - a23 * a31;"
331 " float b11 = a22 * a33 - a23 * a32;"
332 " float det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - "
333 " b04 * b07 + b05 * b06;"
334 " return " + typeName + "(a11 * b11 - a12 * b10 + a13 * b09,"
335 " a02 * b10 - a01 * b11 - a03 * b09,"
336 " a31 * b05 - a32 * b04 + a33 * b03,"
337 " a22 * b04 - a21 * b05 - a23 * b03,"
338 " a12 * b08 - a10 * b11 - a13 * b07,"
339 " a00 * b11 - a02 * b08 + a03 * b07,"
340 " a32 * b02 - a30 * b05 - a33 * b01,"
341 " a20 * b05 - a22 * b02 + a23 * b01,"
342 " a10 * b10 - a11 * b08 + a13 * b06,"
343 " a01 * b08 - a00 * b10 - a03 * b06,"
344 " a30 * b04 - a31 * b02 + a33 * b00,"
345 " a21 * b02 - a20 * b04 - a23 * b00,"
346 " a11 * b07 - a10 * b09 - a12 * b06,"
347 " a00 * b09 - a01 * b07 + a02 * b06,"
348 " a31 * b01 - a30 * b03 - a32 * b00,"
349 " a20 * b03 - a21 * b01 + a22 * b00) / det;"
350 "}"
351 ).c_str());
352 }
353 }
Chris Daltondba7aab2018-11-15 10:57:49 -0500354 this->write(name);
355}
356
Timothy Liang6403b0e2018-05-17 10:40:04 -0400357void MetalCodeGenerator::writeSpecialIntrinsic(const FunctionCall & c, SpecialIntrinsic kind) {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400358 const std::vector<std::unique_ptr<Expression>>& arguments = c.arguments();
Timothy Liang6403b0e2018-05-17 10:40:04 -0400359 switch (kind) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400360 case kTexture_SpecialIntrinsic: {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400361 this->writeExpression(*arguments[0], kSequence_Precedence);
Timothy Lianga06f2152018-05-24 15:33:31 -0400362 this->write(".sample(");
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400363 this->writeExpression(*arguments[0], kSequence_Precedence);
Timothy Lianga06f2152018-05-24 15:33:31 -0400364 this->write(SAMPLER_SUFFIX);
365 this->write(", ");
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400366 const Type& arg1Type = arguments[1]->type();
Ethan Nicholas30d30222020-09-11 12:27:26 -0400367 if (arg1Type == *fContext.fFloat3_Type) {
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500368 // have to store the vector in a temp variable to avoid double evaluating it
369 String tmpVar = "tmpCoord" + to_string(fVarCount++);
Ethan Nicholas30d30222020-09-11 12:27:26 -0400370 this->fFunctionHeader += " " + this->typeName(arg1Type) + " " + tmpVar + ";\n";
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500371 this->write("(" + tmpVar + " = ");
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400372 this->writeExpression(*arguments[1], kSequence_Precedence);
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500373 this->write(", " + tmpVar + ".xy / " + tmpVar + ".z))");
Timothy Liangee84fe12018-05-18 14:38:19 -0400374 } else {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400375 SkASSERT(arg1Type == *fContext.fFloat2_Type);
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400376 this->writeExpression(*arguments[1], kSequence_Precedence);
Timothy Liangee84fe12018-05-18 14:38:19 -0400377 this->write(")");
378 }
Timothy Liang6403b0e2018-05-17 10:40:04 -0400379 break;
Ethan Nicholas30d30222020-09-11 12:27:26 -0400380 }
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500381 case kMod_SpecialIntrinsic: {
Timothy Liang651286f2018-06-07 09:55:33 -0400382 // 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 -0500383 String tmpX = "tmpX" + to_string(fVarCount++);
384 String tmpY = "tmpY" + to_string(fVarCount++);
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400385 this->fFunctionHeader += " " + this->typeName(arguments[0]->type()) +
Ethan Nicholas30d30222020-09-11 12:27:26 -0400386 " " + tmpX + ", " + tmpY + ";\n";
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500387 this->write("(" + tmpX + " = ");
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400388 this->writeExpression(*arguments[0], kSequence_Precedence);
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500389 this->write(", " + tmpY + " = ");
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400390 this->writeExpression(*arguments[1], kSequence_Precedence);
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500391 this->write(", " + tmpX + " - " + tmpY + " * floor(" + tmpX + " / " + tmpY + "))");
Timothy Liang651286f2018-06-07 09:55:33 -0400392 break;
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500393 }
Timothy Liang6403b0e2018-05-17 10:40:04 -0400394 default:
395 ABORT("unsupported special intrinsic kind");
396 }
397}
398
John Stilesfcf8cb22020-08-06 14:29:22 -0400399// Assembles a matrix of type floatRxC by resizing another matrix named `x0`.
400// Cells that don't exist in the source matrix will be populated with identity-matrix values.
401void MetalCodeGenerator::assembleMatrixFromMatrix(const Type& sourceMatrix, int rows, int columns) {
402 SkASSERT(rows <= 4);
403 SkASSERT(columns <= 4);
404
405 const char* columnSeparator = "";
406 for (int c = 0; c < columns; ++c) {
407 fExtraFunctions.printf("%sfloat%d(", columnSeparator, rows);
408 columnSeparator = "), ";
409
410 // Determine how many values to take from the source matrix for this row.
411 int swizzleLength = 0;
412 if (c < sourceMatrix.columns()) {
413 swizzleLength = std::min<>(rows, sourceMatrix.rows());
414 }
415
416 // Emit all the values from the source matrix row.
417 bool firstItem;
418 switch (swizzleLength) {
419 case 0: firstItem = true; break;
420 case 1: firstItem = false; fExtraFunctions.printf("x0[%d].x", c); break;
421 case 2: firstItem = false; fExtraFunctions.printf("x0[%d].xy", c); break;
422 case 3: firstItem = false; fExtraFunctions.printf("x0[%d].xyz", c); break;
423 case 4: firstItem = false; fExtraFunctions.printf("x0[%d].xyzw", c); break;
424 default: SkUNREACHABLE;
425 }
426
427 // Emit the placeholder identity-matrix cells.
428 for (int r = swizzleLength; r < rows; ++r) {
429 fExtraFunctions.printf("%s%s", firstItem ? "" : ", ", (r == c) ? "1.0" : "0.0");
430 firstItem = false;
431 }
432 }
433
434 fExtraFunctions.writeText(")");
435}
436
437// Assembles a matrix of type floatRxC by concatenating an arbitrary mix of values, named `x0`,
438// `x1`, etc. An error is written if the expression list don't contain exactly R*C scalars.
439void MetalCodeGenerator::assembleMatrixFromExpressions(
440 const std::vector<std::unique_ptr<Expression>>& args, int rows, int columns) {
441 size_t argIndex = 0;
442 int argPosition = 0;
443
444 const char* columnSeparator = "";
445 for (int c = 0; c < columns; ++c) {
446 fExtraFunctions.printf("%sfloat%d(", columnSeparator, rows);
447 columnSeparator = "), ";
448
449 const char* rowSeparator = "";
450 for (int r = 0; r < rows; ++r) {
451 fExtraFunctions.writeText(rowSeparator);
452 rowSeparator = ", ";
453
454 if (argIndex < args.size()) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400455 const Type& argType = args[argIndex]->type();
Ethan Nicholase6592142020-09-08 10:22:09 -0400456 switch (argType.typeKind()) {
457 case Type::TypeKind::kScalar: {
John Stilesfcf8cb22020-08-06 14:29:22 -0400458 fExtraFunctions.printf("x%zu", argIndex);
459 break;
460 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400461 case Type::TypeKind::kVector: {
John Stilesfcf8cb22020-08-06 14:29:22 -0400462 fExtraFunctions.printf("x%zu[%d]", argIndex, argPosition);
463 break;
464 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400465 case Type::TypeKind::kMatrix: {
John Stilesfcf8cb22020-08-06 14:29:22 -0400466 fExtraFunctions.printf("x%zu[%d][%d]", argIndex,
467 argPosition / argType.rows(),
468 argPosition % argType.rows());
469 break;
470 }
471 default: {
472 SkDEBUGFAIL("incorrect type of argument for matrix constructor");
473 fExtraFunctions.writeText("<error>");
474 break;
475 }
476 }
477
478 ++argPosition;
479 if (argPosition >= argType.columns() * argType.rows()) {
480 ++argIndex;
481 argPosition = 0;
482 }
483 } else {
484 SkDEBUGFAIL("not enough arguments for matrix constructor");
485 fExtraFunctions.writeText("<error>");
486 }
487 }
488 }
489
490 if (argPosition != 0 || argIndex != args.size()) {
491 SkDEBUGFAIL("incorrect number of arguments for matrix constructor");
492 fExtraFunctions.writeText(", <error>");
493 }
494
495 fExtraFunctions.writeText(")");
496}
497
John Stiles1bdafbf2020-05-28 12:17:20 -0400498// Generates a constructor for 'matrix' which reorganizes the input arguments into the proper shape.
499// Keeps track of previously generated constructors so that we won't generate more than one
500// constructor for any given permutation of input argument types. Returns the name of the
501// generated constructor method.
502String MetalCodeGenerator::getMatrixConstructHelper(const Constructor& c) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400503 const Type& matrix = c.type();
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500504 int columns = matrix.columns();
505 int rows = matrix.rows();
Ethan Nicholasf70f0442020-09-29 12:41:35 -0400506 const std::vector<std::unique_ptr<Expression>>& args = c.arguments();
John Stiles1bdafbf2020-05-28 12:17:20 -0400507
508 // Create the helper-method name and use it as our lookup key.
509 String name;
510 name.appendf("float%dx%d_from", columns, rows);
511 for (const std::unique_ptr<Expression>& expr : args) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400512 name.appendf("_%s", expr->type().displayName().c_str());
John Stiles1bdafbf2020-05-28 12:17:20 -0400513 }
514
515 // If a helper-method has already been synthesized, we don't need to synthesize it again.
516 auto [iter, newlyCreated] = fHelpers.insert(name);
517 if (!newlyCreated) {
518 return name;
519 }
520
521 // Unlike GLSL, Metal requires that matrices are initialized with exactly R vectors of C
522 // components apiece. (In Metal 2.0, you can also supply R*C scalars, but you still cannot
523 // supply a mixture of scalars and vectors.)
524 fExtraFunctions.printf("float%dx%d %s(", columns, rows, name.c_str());
525
526 size_t argIndex = 0;
527 const char* argSeparator = "";
John Stilesfcf8cb22020-08-06 14:29:22 -0400528 for (const std::unique_ptr<Expression>& expr : args) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400529 fExtraFunctions.printf("%s%s x%zu", argSeparator,
Ethan Nicholas30d30222020-09-11 12:27:26 -0400530 expr->type().displayName().c_str(), argIndex++);
John Stiles1bdafbf2020-05-28 12:17:20 -0400531 argSeparator = ", ";
532 }
533
534 fExtraFunctions.printf(") {\n return float%dx%d(", columns, rows);
535
Ethan Nicholas30d30222020-09-11 12:27:26 -0400536 if (args.size() == 1 && args.front()->type().typeKind() == Type::TypeKind::kMatrix) {
537 this->assembleMatrixFromMatrix(args.front()->type(), rows, columns);
John Stilesfcf8cb22020-08-06 14:29:22 -0400538 } else {
539 this->assembleMatrixFromExpressions(args, rows, columns);
John Stiles1bdafbf2020-05-28 12:17:20 -0400540 }
541
John Stilesfcf8cb22020-08-06 14:29:22 -0400542 fExtraFunctions.writeText(");\n}\n");
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500543 return name;
544}
545
546bool MetalCodeGenerator::canCoerce(const Type& t1, const Type& t2) {
547 if (t1.columns() != t2.columns() || t1.rows() != t2.rows()) {
548 return false;
549 }
550 if (t1.columns() > 1) {
551 return this->canCoerce(t1.componentType(), t2.componentType());
552 }
Ethan Nicholase1f55022019-02-05 17:17:40 -0500553 return t1.isFloat() && t2.isFloat();
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500554}
555
John Stiles1bdafbf2020-05-28 12:17:20 -0400556bool MetalCodeGenerator::matrixConstructHelperIsNeeded(const Constructor& c) {
557 // A matrix construct helper is only necessary if we are, in fact, constructing a matrix.
Ethan Nicholas30d30222020-09-11 12:27:26 -0400558 if (c.type().typeKind() != Type::TypeKind::kMatrix) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400559 return false;
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500560 }
John Stiles1bdafbf2020-05-28 12:17:20 -0400561
562 // GLSL is fairly free-form about inputs to its matrix constructors, but Metal is not; it
563 // expects exactly R vectors of C components apiece. (Metal 2.0 also allows a list of R*C
564 // scalars.) Some cases are simple to translate and so we handle those inline--e.g. a list of
565 // scalars can be constructed trivially. In more complex cases, we generate a helper function
566 // that converts our inputs into a properly-shaped matrix.
567 // A matrix construct helper method is always used if any input argument is a matrix.
568 // Helper methods are also necessary when any argument would span multiple rows. For instance:
569 //
570 // float2 x = (1, 2);
571 // float3x2(x, 3, 4, 5, 6) = | 1 3 5 | = no helper needed; conversion can be done inline
572 // | 2 4 6 |
573 //
574 // float2 x = (2, 3);
575 // float3x2(1, x, 4, 5, 6) = | 1 3 5 | = x spans multiple rows; a helper method will be used
576 // | 2 4 6 |
577 //
578 // float4 x = (1, 2, 3, 4);
579 // float2x2(x) = | 1 3 | = x spans multiple rows; a helper method will be used
580 // | 2 4 |
581 //
582
583 int position = 0;
Ethan Nicholasf70f0442020-09-29 12:41:35 -0400584 for (const std::unique_ptr<Expression>& expr : c.arguments()) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400585 // If an input argument is a matrix, we need a helper function.
Ethan Nicholas30d30222020-09-11 12:27:26 -0400586 if (expr->type().typeKind() == Type::TypeKind::kMatrix) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400587 return true;
588 }
Ethan Nicholas30d30222020-09-11 12:27:26 -0400589 position += expr->type().columns();
590 if (position > c.type().rows()) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400591 // An input argument would span multiple rows; a helper function is required.
592 return true;
593 }
Ethan Nicholas30d30222020-09-11 12:27:26 -0400594 if (position == c.type().rows()) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400595 // We've advanced to the end of a row. Wrap to the start of the next row.
596 position = 0;
597 }
598 }
599
600 return false;
601}
602
603void MetalCodeGenerator::writeConstructor(const Constructor& c, Precedence parentPrecedence) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400604 const Type& constructorType = c.type();
John Stiles1bdafbf2020-05-28 12:17:20 -0400605 // Handle special cases for single-argument constructors.
Ethan Nicholasf70f0442020-09-29 12:41:35 -0400606 if (c.arguments().size() == 1) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400607 // If the type is coercible, emit it directly.
Ethan Nicholasf70f0442020-09-29 12:41:35 -0400608 const Expression& arg = *c.arguments().front();
Ethan Nicholas30d30222020-09-11 12:27:26 -0400609 const Type& argType = arg.type();
610 if (this->canCoerce(constructorType, argType)) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400611 this->writeExpression(arg, parentPrecedence);
612 return;
613 }
614
615 // Metal supports creating matrices with a scalar on the diagonal via the single-argument
616 // matrix constructor.
Ethan Nicholas30d30222020-09-11 12:27:26 -0400617 if (constructorType.typeKind() == Type::TypeKind::kMatrix && argType.isNumber()) {
618 const Type& matrix = constructorType;
John Stiles1bdafbf2020-05-28 12:17:20 -0400619 this->write("float");
620 this->write(to_string(matrix.columns()));
621 this->write("x");
622 this->write(to_string(matrix.rows()));
623 this->write("(");
624 this->writeExpression(arg, parentPrecedence);
625 this->write(")");
626 return;
627 }
628 }
629
630 // Emit and invoke a matrix-constructor helper method if one is necessary.
631 if (this->matrixConstructHelperIsNeeded(c)) {
632 this->write(this->getMatrixConstructHelper(c));
John Stiles1fa15b12020-05-28 17:36:54 +0000633 this->write("(");
634 const char* separator = "";
Ethan Nicholasf70f0442020-09-29 12:41:35 -0400635 for (const std::unique_ptr<Expression>& expr : c.arguments()) {
John Stiles1fa15b12020-05-28 17:36:54 +0000636 this->write(separator);
637 separator = ", ";
John Stiles1bdafbf2020-05-28 12:17:20 -0400638 this->writeExpression(*expr, kSequence_Precedence);
John Stilesdaa573e2020-05-28 12:17:20 -0400639 }
John Stiles1fa15b12020-05-28 17:36:54 +0000640 this->write(")");
John Stiles1bdafbf2020-05-28 12:17:20 -0400641 return;
John Stilesdaa573e2020-05-28 12:17:20 -0400642 }
John Stiles1bdafbf2020-05-28 12:17:20 -0400643
644 // Explicitly invoke the constructor, passing in the necessary arguments.
Ethan Nicholas30d30222020-09-11 12:27:26 -0400645 this->writeType(constructorType);
John Stiles1bdafbf2020-05-28 12:17:20 -0400646 this->write("(");
647 const char* separator = "";
648 int scalarCount = 0;
Ethan Nicholasf70f0442020-09-29 12:41:35 -0400649 for (const std::unique_ptr<Expression>& arg : c.arguments()) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400650 const Type& argType = arg->type();
John Stiles1bdafbf2020-05-28 12:17:20 -0400651 this->write(separator);
652 separator = ", ";
Ethan Nicholas30d30222020-09-11 12:27:26 -0400653 if (constructorType.typeKind() == Type::TypeKind::kMatrix &&
654 argType.columns() < constructorType.rows()) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400655 // Merge scalars and smaller vectors together.
656 if (!scalarCount) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400657 this->writeType(constructorType.componentType());
658 this->write(to_string(constructorType.rows()));
John Stiles1bdafbf2020-05-28 12:17:20 -0400659 this->write("(");
660 }
Ethan Nicholas30d30222020-09-11 12:27:26 -0400661 scalarCount += argType.columns();
John Stiles1bdafbf2020-05-28 12:17:20 -0400662 }
663 this->writeExpression(*arg, kSequence_Precedence);
Ethan Nicholas30d30222020-09-11 12:27:26 -0400664 if (scalarCount && scalarCount == constructorType.rows()) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400665 this->write(")");
666 scalarCount = 0;
667 }
668 }
669 this->write(")");
Ethan Nicholascc305772017-10-13 16:17:45 -0400670}
671
672void MetalCodeGenerator::writeFragCoord() {
Ethan Nicholasf931e402019-07-26 15:40:33 -0400673 if (fRTHeightName.length()) {
674 this->write("float4(_fragCoord.x, ");
675 this->write(fRTHeightName.c_str());
676 this->write(" - _fragCoord.y, 0.0, _fragCoord.w)");
Jim Van Verth6bc650e2019-02-07 14:53:23 -0500677 } else {
678 this->write("float4(_fragCoord.x, _fragCoord.y, 0.0, _fragCoord.w)");
679 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400680}
681
682void MetalCodeGenerator::writeVariableReference(const VariableReference& ref) {
Ethan Nicholas78686922020-10-08 06:46:27 -0400683 switch (ref.variable()->modifiers().fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400684 case SK_FRAGCOLOR_BUILTIN:
Timothy Liang7d637782018-06-05 09:58:07 -0400685 this->write("_out->sk_FragColor");
Ethan Nicholascc305772017-10-13 16:17:45 -0400686 break;
Timothy Liang6403b0e2018-05-17 10:40:04 -0400687 case SK_FRAGCOORD_BUILTIN:
688 this->writeFragCoord();
689 break;
Timothy Liangdc89f192018-06-13 09:20:31 -0400690 case SK_VERTEXID_BUILTIN:
691 this->write("sk_VertexID");
692 break;
693 case SK_INSTANCEID_BUILTIN:
694 this->write("sk_InstanceID");
695 break;
Timothy Liang7b8875d2018-08-10 09:42:31 -0400696 case SK_CLOCKWISE_BUILTIN:
697 // We'd set the front facing winding in the MTLRenderCommandEncoder to be counter
Brian Salomonf4ba4ec2020-03-19 15:54:28 -0400698 // clockwise to match Skia convention.
Timothy Liang7b8875d2018-08-10 09:42:31 -0400699 this->write(fProgram.fSettings.fFlipY ? "_frontFacing" : "(!_frontFacing)");
700 break;
Ethan Nicholascc305772017-10-13 16:17:45 -0400701 default:
Ethan Nicholas78686922020-10-08 06:46:27 -0400702 const Variable& var = *ref.variable();
703 if (var.storage() == Variable::kGlobal_Storage) {
704 if (var.modifiers().fFlags & Modifiers::kIn_Flag) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400705 this->write("_in.");
Ethan Nicholas78686922020-10-08 06:46:27 -0400706 } else if (var.modifiers().fFlags & Modifiers::kOut_Flag) {
Timothy Liangee84fe12018-05-18 14:38:19 -0400707 this->write("_out->");
Ethan Nicholas78686922020-10-08 06:46:27 -0400708 } else if (var.modifiers().fFlags & Modifiers::kUniform_Flag &&
709 var.type().typeKind() != Type::TypeKind::kSampler) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400710 this->write("_uniforms.");
711 } else {
Timothy Liangee84fe12018-05-18 14:38:19 -0400712 this->write("_globals->");
Ethan Nicholascc305772017-10-13 16:17:45 -0400713 }
714 }
Ethan Nicholas78686922020-10-08 06:46:27 -0400715 this->writeName(var.name());
Ethan Nicholascc305772017-10-13 16:17:45 -0400716 }
717}
718
719void MetalCodeGenerator::writeIndexExpression(const IndexExpression& expr) {
720 this->writeExpression(*expr.fBase, kPostfix_Precedence);
721 this->write("[");
722 this->writeExpression(*expr.fIndex, kTopLevel_Precedence);
723 this->write("]");
724}
725
726void MetalCodeGenerator::writeFieldAccess(const FieldAccess& f) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400727 const Type::Field* field = &f.fBase->type().fields()[f.fFieldIndex];
Ethan Nicholascc305772017-10-13 16:17:45 -0400728 if (FieldAccess::kDefault_OwnerKind == f.fOwnerKind) {
729 this->writeExpression(*f.fBase, kPostfix_Precedence);
730 this->write(".");
731 }
Timothy Liang7d637782018-06-05 09:58:07 -0400732 switch (field->fModifiers.fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400733 case SK_POSITION_BUILTIN:
Timothy Liangb8eeb802018-07-23 16:46:16 -0400734 this->write("_out->sk_Position");
Ethan Nicholascc305772017-10-13 16:17:45 -0400735 break;
736 default:
Timothy Liang7d637782018-06-05 09:58:07 -0400737 if (field->fName == "sk_PointSize") {
738 this->write("_out->sk_PointSize");
739 } else {
740 if (FieldAccess::kAnonymousInterfaceBlock_OwnerKind == f.fOwnerKind) {
741 this->write("_globals->");
742 this->write(fInterfaceBlockNameMap[fInterfaceBlockMap[field]]);
743 this->write("->");
744 }
Timothy Liang651286f2018-06-07 09:55:33 -0400745 this->writeName(field->fName);
Timothy Lianga06f2152018-05-24 15:33:31 -0400746 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400747 }
748}
749
750void MetalCodeGenerator::writeSwizzle(const Swizzle& swizzle) {
751 this->writeExpression(*swizzle.fBase, kPostfix_Precedence);
752 this->write(".");
753 for (int c : swizzle.fComponents) {
Brian Osman25647672020-09-15 15:16:56 -0400754 SkASSERT(c >= 0 && c <= 3);
755 this->write(&("x\0y\0z\0w\0"[c * 2]));
Ethan Nicholascc305772017-10-13 16:17:45 -0400756 }
757}
758
759MetalCodeGenerator::Precedence MetalCodeGenerator::GetBinaryPrecedence(Token::Kind op) {
760 switch (op) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400761 case Token::Kind::TK_STAR: // fall through
762 case Token::Kind::TK_SLASH: // fall through
763 case Token::Kind::TK_PERCENT: return MetalCodeGenerator::kMultiplicative_Precedence;
764 case Token::Kind::TK_PLUS: // fall through
765 case Token::Kind::TK_MINUS: return MetalCodeGenerator::kAdditive_Precedence;
766 case Token::Kind::TK_SHL: // fall through
767 case Token::Kind::TK_SHR: return MetalCodeGenerator::kShift_Precedence;
768 case Token::Kind::TK_LT: // fall through
769 case Token::Kind::TK_GT: // fall through
770 case Token::Kind::TK_LTEQ: // fall through
771 case Token::Kind::TK_GTEQ: return MetalCodeGenerator::kRelational_Precedence;
772 case Token::Kind::TK_EQEQ: // fall through
773 case Token::Kind::TK_NEQ: return MetalCodeGenerator::kEquality_Precedence;
774 case Token::Kind::TK_BITWISEAND: return MetalCodeGenerator::kBitwiseAnd_Precedence;
775 case Token::Kind::TK_BITWISEXOR: return MetalCodeGenerator::kBitwiseXor_Precedence;
776 case Token::Kind::TK_BITWISEOR: return MetalCodeGenerator::kBitwiseOr_Precedence;
777 case Token::Kind::TK_LOGICALAND: return MetalCodeGenerator::kLogicalAnd_Precedence;
778 case Token::Kind::TK_LOGICALXOR: return MetalCodeGenerator::kLogicalXor_Precedence;
779 case Token::Kind::TK_LOGICALOR: return MetalCodeGenerator::kLogicalOr_Precedence;
780 case Token::Kind::TK_EQ: // fall through
781 case Token::Kind::TK_PLUSEQ: // fall through
782 case Token::Kind::TK_MINUSEQ: // fall through
783 case Token::Kind::TK_STAREQ: // fall through
784 case Token::Kind::TK_SLASHEQ: // fall through
785 case Token::Kind::TK_PERCENTEQ: // fall through
786 case Token::Kind::TK_SHLEQ: // fall through
787 case Token::Kind::TK_SHREQ: // fall through
788 case Token::Kind::TK_LOGICALANDEQ: // fall through
789 case Token::Kind::TK_LOGICALXOREQ: // fall through
790 case Token::Kind::TK_LOGICALOREQ: // fall through
791 case Token::Kind::TK_BITWISEANDEQ: // fall through
792 case Token::Kind::TK_BITWISEXOREQ: // fall through
793 case Token::Kind::TK_BITWISEOREQ: return MetalCodeGenerator::kAssignment_Precedence;
794 case Token::Kind::TK_COMMA: return MetalCodeGenerator::kSequence_Precedence;
Ethan Nicholascc305772017-10-13 16:17:45 -0400795 default: ABORT("unsupported binary operator");
796 }
797}
798
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500799void MetalCodeGenerator::writeMatrixTimesEqualHelper(const Type& left, const Type& right,
800 const Type& result) {
801 String key = "TimesEqual" + left.name() + right.name();
802 if (fHelpers.find(key) == fHelpers.end()) {
803 fExtraFunctions.printf("%s operator*=(thread %s& left, thread const %s& right) {\n"
804 " left = left * right;\n"
805 " return left;\n"
Ethan Nicholase2c49992020-10-05 11:49:11 -0400806 "}", String(result.name()).c_str(), String(left.name()).c_str(),
807 String(right.name()).c_str());
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500808 }
809}
810
Ethan Nicholascc305772017-10-13 16:17:45 -0400811void MetalCodeGenerator::writeBinaryExpression(const BinaryExpression& b,
812 Precedence parentPrecedence) {
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400813 const Expression& left = b.left();
814 const Expression& right = b.right();
815 const Type& leftType = left.type();
816 const Type& rightType = right.type();
817 Token::Kind op = b.getOperator();
818 Precedence precedence = GetBinaryPrecedence(b.getOperator());
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500819 bool needParens = precedence >= parentPrecedence;
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400820 switch (op) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400821 case Token::Kind::TK_EQEQ:
Ethan Nicholas30d30222020-09-11 12:27:26 -0400822 if (leftType.typeKind() == Type::TypeKind::kVector) {
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500823 this->write("all");
824 needParens = true;
825 }
826 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400827 case Token::Kind::TK_NEQ:
Ethan Nicholas30d30222020-09-11 12:27:26 -0400828 if (leftType.typeKind() == Type::TypeKind::kVector) {
Jim Van Verth36477b42019-04-11 14:57:30 -0400829 this->write("any");
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500830 needParens = true;
831 }
832 break;
833 default:
834 break;
835 }
836 if (needParens) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400837 this->write("(");
838 }
Brian Osman79457ef2020-09-24 15:01:27 -0400839 if (Compiler::IsAssignment(op) && left.is<VariableReference>() &&
Ethan Nicholas78686922020-10-08 06:46:27 -0400840 left.as<VariableReference>().variable()->storage() == Variable::kParameter_Storage &&
841 left.as<VariableReference>().variable()->modifiers().fFlags & Modifiers::kOut_Flag) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400842 // writing to an out parameter. Since we have to turn those into pointers, we have to
843 // dereference it here.
844 this->write("*");
845 }
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400846 if (op == Token::Kind::TK_STAREQ && leftType.typeKind() == Type::TypeKind::kMatrix &&
Ethan Nicholas30d30222020-09-11 12:27:26 -0400847 rightType.typeKind() == Type::TypeKind::kMatrix) {
848 this->writeMatrixTimesEqualHelper(leftType, rightType, b.type());
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500849 }
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400850 this->writeExpression(left, precedence);
851 if (op != Token::Kind::TK_EQ && Compiler::IsAssignment(op) &&
852 left.kind() == Expression::Kind::kSwizzle && !left.hasSideEffects()) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400853 // This doesn't compile in Metal:
854 // float4 x = float4(1);
855 // x.xy *= float2x2(...);
856 // with the error message "non-const reference cannot bind to vector element",
857 // but switching it to x.xy = x.xy * float2x2(...) fixes it. We perform this tranformation
858 // as long as the LHS has no side effects, and hope for the best otherwise.
859 this->write(" = ");
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400860 this->writeExpression(left, kAssignment_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400861 this->write(" ");
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400862 String opName = Compiler::OperatorName(op);
863 SkASSERT(opName.endsWith("="));
864 this->write(opName.substr(0, opName.size() - 1).c_str());
Ethan Nicholascc305772017-10-13 16:17:45 -0400865 this->write(" ");
866 } else {
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400867 this->write(String(" ") + Compiler::OperatorName(op) + " ");
Ethan Nicholascc305772017-10-13 16:17:45 -0400868 }
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400869 this->writeExpression(right, precedence);
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500870 if (needParens) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400871 this->write(")");
872 }
873}
874
875void MetalCodeGenerator::writeTernaryExpression(const TernaryExpression& t,
876 Precedence parentPrecedence) {
877 if (kTernary_Precedence >= parentPrecedence) {
878 this->write("(");
879 }
Ethan Nicholasdd218162020-10-08 05:48:01 -0400880 this->writeExpression(*t.test(), kTernary_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400881 this->write(" ? ");
Ethan Nicholasdd218162020-10-08 05:48:01 -0400882 this->writeExpression(*t.ifTrue(), kTernary_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400883 this->write(" : ");
Ethan Nicholasdd218162020-10-08 05:48:01 -0400884 this->writeExpression(*t.ifFalse(), kTernary_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400885 if (kTernary_Precedence >= parentPrecedence) {
886 this->write(")");
887 }
888}
889
890void MetalCodeGenerator::writePrefixExpression(const PrefixExpression& p,
891 Precedence parentPrecedence) {
892 if (kPrefix_Precedence >= parentPrecedence) {
893 this->write("(");
894 }
895 this->write(Compiler::OperatorName(p.fOperator));
896 this->writeExpression(*p.fOperand, kPrefix_Precedence);
897 if (kPrefix_Precedence >= parentPrecedence) {
898 this->write(")");
899 }
900}
901
902void MetalCodeGenerator::writePostfixExpression(const PostfixExpression& p,
903 Precedence parentPrecedence) {
904 if (kPostfix_Precedence >= parentPrecedence) {
905 this->write("(");
906 }
907 this->writeExpression(*p.fOperand, kPostfix_Precedence);
908 this->write(Compiler::OperatorName(p.fOperator));
909 if (kPostfix_Precedence >= parentPrecedence) {
910 this->write(")");
911 }
912}
913
914void MetalCodeGenerator::writeBoolLiteral(const BoolLiteral& b) {
Ethan Nicholas59d660c2020-09-28 09:18:15 -0400915 this->write(b.value() ? "true" : "false");
Ethan Nicholascc305772017-10-13 16:17:45 -0400916}
917
918void MetalCodeGenerator::writeIntLiteral(const IntLiteral& i) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400919 if (i.type() == *fContext.fUInt_Type) {
Ethan Nicholase96cdd12020-09-28 16:27:18 -0400920 this->write(to_string(i.value() & 0xffffffff) + "u");
Ethan Nicholascc305772017-10-13 16:17:45 -0400921 } else {
Ethan Nicholase96cdd12020-09-28 16:27:18 -0400922 this->write(to_string((int32_t) i.value()));
Ethan Nicholascc305772017-10-13 16:17:45 -0400923 }
924}
925
926void MetalCodeGenerator::writeFloatLiteral(const FloatLiteral& f) {
Ethan Nicholasa3f22f12020-10-01 12:13:17 -0400927 this->write(to_string(f.value()));
Ethan Nicholascc305772017-10-13 16:17:45 -0400928}
929
930void MetalCodeGenerator::writeSetting(const Setting& s) {
931 ABORT("internal error; setting was not folded to a constant during compilation\n");
932}
933
934void MetalCodeGenerator::writeFunction(const FunctionDefinition& f) {
Ethan Nicholasf931e402019-07-26 15:40:33 -0400935 fRTHeightName = fProgram.fInputs.fRTHeight ? "_globals->_anonInterface0->u_skRTHeight" : "";
Ethan Nicholascc305772017-10-13 16:17:45 -0400936 const char* separator = "";
Ethan Nicholase2c49992020-10-05 11:49:11 -0400937 if ("main" == f.fDeclaration.name()) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400938 switch (fProgram.fKind) {
939 case Program::kFragment_Kind:
Timothy Liangb8eeb802018-07-23 16:46:16 -0400940 this->write("fragment Outputs fragmentMain");
Ethan Nicholascc305772017-10-13 16:17:45 -0400941 break;
942 case Program::kVertex_Kind:
Timothy Liangb8eeb802018-07-23 16:46:16 -0400943 this->write("vertex Outputs vertexMain");
Ethan Nicholascc305772017-10-13 16:17:45 -0400944 break;
945 default:
John Stiles3fabfc02020-09-25 15:51:28 -0400946 fErrors.error(-1, "unsupported kind of program");
947 return;
Ethan Nicholascc305772017-10-13 16:17:45 -0400948 }
949 this->write("(Inputs _in [[stage_in]]");
950 if (-1 != fUniformBuffer) {
951 this->write(", constant Uniforms& _uniforms [[buffer(" +
952 to_string(fUniformBuffer) + ")]]");
953 }
Timothy Liang6403b0e2018-05-17 10:40:04 -0400954 for (const auto& e : fProgram) {
Brian Osmanc0213602020-10-06 14:43:32 -0400955 if (e.is<GlobalVarDeclaration>()) {
956 const GlobalVarDeclaration& decls = e.as<GlobalVarDeclaration>();
957 const VarDeclaration& var = *decls.fDecl;
958 if (var.fVar->type().typeKind() == Type::TypeKind::kSampler) {
Ethan Nicholas041fd0a2020-10-07 16:42:04 -0400959 if (var.fVar->modifiers().fLayout.fBinding < 0) {
Brian Osmanc0213602020-10-06 14:43:32 -0400960 fErrors.error(decls.fOffset,
961 "Metal samplers must have 'layout(binding=...)'");
962 return;
Timothy Liangee84fe12018-05-18 14:38:19 -0400963 }
Brian Osmanc0213602020-10-06 14:43:32 -0400964 if (var.fVar->type().dimensions() != SpvDim2D) {
965 // TODO: Support other texture types (skbug.com/10797)
966 fErrors.error(decls.fOffset, "Unsupported texture dimensions");
967 return;
968 }
969 this->write(", texture2d<float> ");
970 this->writeName(var.fVar->name());
971 this->write("[[texture(");
Ethan Nicholas041fd0a2020-10-07 16:42:04 -0400972 this->write(to_string(var.fVar->modifiers().fLayout.fBinding));
Brian Osmanc0213602020-10-06 14:43:32 -0400973 this->write(")]]");
974 this->write(", sampler ");
975 this->writeName(var.fVar->name());
976 this->write(SAMPLER_SUFFIX);
977 this->write("[[sampler(");
Ethan Nicholas041fd0a2020-10-07 16:42:04 -0400978 this->write(to_string(var.fVar->modifiers().fLayout.fBinding));
Brian Osmanc0213602020-10-06 14:43:32 -0400979 this->write(")]]");
Timothy Liang6403b0e2018-05-17 10:40:04 -0400980 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400981 } else if (e.kind() == ProgramElement::Kind::kInterfaceBlock) {
Timothy Lianga06f2152018-05-24 15:33:31 -0400982 InterfaceBlock& intf = (InterfaceBlock&) e;
983 if ("sk_PerVertex" == intf.fTypeName) {
984 continue;
985 }
986 this->write(", constant ");
Brian Osman6a204db2020-10-08 09:29:02 -0400987 this->writeType(intf.fVariable->type());
Timothy Lianga06f2152018-05-24 15:33:31 -0400988 this->write("& " );
989 this->write(fInterfaceBlockNameMap[&intf]);
990 this->write(" [[buffer(");
Brian Osman6a204db2020-10-08 09:29:02 -0400991 this->write(to_string(intf.fVariable->modifiers().fLayout.fBinding));
Timothy Lianga06f2152018-05-24 15:33:31 -0400992 this->write(")]]");
Timothy Liang6403b0e2018-05-17 10:40:04 -0400993 }
994 }
Jim Van Verth6bc650e2019-02-07 14:53:23 -0500995 if (fProgram.fKind == Program::kFragment_Kind) {
996 if (fProgram.fInputs.fRTHeight && fInterfaceBlockNameMap.empty()) {
Timothy Liang5422f9a2018-08-10 10:57:55 -0400997 this->write(", constant sksl_synthetic_uniforms& _anonInterface0 [[buffer(1)]]");
Ethan Nicholasf931e402019-07-26 15:40:33 -0400998 fRTHeightName = "_anonInterface0.u_skRTHeight";
Timothy Liang5422f9a2018-08-10 10:57:55 -0400999 }
Timothy Liang7b8875d2018-08-10 09:42:31 -04001000 this->write(", bool _frontFacing [[front_facing]]");
Timothy Liang7d637782018-06-05 09:58:07 -04001001 this->write(", float4 _fragCoord [[position]]");
Timothy Liangdc89f192018-06-13 09:20:31 -04001002 } else if (fProgram.fKind == Program::kVertex_Kind) {
1003 this->write(", uint sk_VertexID [[vertex_id]], uint sk_InstanceID [[instance_id]]");
Timothy Liang7d637782018-06-05 09:58:07 -04001004 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001005 separator = ", ";
1006 } else {
1007 this->writeType(f.fDeclaration.fReturnType);
Timothy Liang651286f2018-06-07 09:55:33 -04001008 this->write(" ");
Ethan Nicholase2c49992020-10-05 11:49:11 -04001009 this->writeName(f.fDeclaration.name());
Timothy Liang651286f2018-06-07 09:55:33 -04001010 this->write("(");
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -04001011 Requirements requirements = this->requirements(f.fDeclaration);
1012 if (requirements & kInputs_Requirement) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001013 this->write("Inputs _in");
1014 separator = ", ";
1015 }
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -04001016 if (requirements & kOutputs_Requirement) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001017 this->write(separator);
Timothy Liangee84fe12018-05-18 14:38:19 -04001018 this->write("thread Outputs* _out");
Ethan Nicholascc305772017-10-13 16:17:45 -04001019 separator = ", ";
1020 }
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -04001021 if (requirements & kUniforms_Requirement) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001022 this->write(separator);
1023 this->write("Uniforms _uniforms");
1024 separator = ", ";
1025 }
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -04001026 if (requirements & kGlobals_Requirement) {
Timothy Liangee84fe12018-05-18 14:38:19 -04001027 this->write(separator);
1028 this->write("thread Globals* _globals");
1029 separator = ", ";
1030 }
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -04001031 if (requirements & kFragCoord_Requirement) {
1032 this->write(separator);
1033 this->write("float4 _fragCoord");
1034 separator = ", ";
1035 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001036 }
1037 for (const auto& param : f.fDeclaration.fParameters) {
1038 this->write(separator);
1039 separator = ", ";
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001040 this->writeModifiers(param->modifiers(), false);
Ethan Nicholascc305772017-10-13 16:17:45 -04001041 std::vector<int> sizes;
Ethan Nicholas30d30222020-09-11 12:27:26 -04001042 const Type* type = &param->type();
Ethan Nicholase6592142020-09-08 10:22:09 -04001043 while (type->typeKind() == Type::TypeKind::kArray) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001044 sizes.push_back(type->columns());
1045 type = &type->componentType();
1046 }
1047 this->writeType(*type);
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001048 if (param->modifiers().fFlags & Modifiers::kOut_Flag) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001049 this->write("*");
1050 }
Timothy Liang651286f2018-06-07 09:55:33 -04001051 this->write(" ");
Ethan Nicholase2c49992020-10-05 11:49:11 -04001052 this->writeName(param->name());
Ethan Nicholascc305772017-10-13 16:17:45 -04001053 for (int s : sizes) {
Brian Osmane8c26082020-10-01 17:22:45 -04001054 if (s == Type::kUnsizedArray) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001055 this->write("[]");
1056 } else {
1057 this->write("[" + to_string(s) + "]");
1058 }
1059 }
1060 }
1061 this->writeLine(") {");
1062
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001063 SkASSERT(!fProgram.fSettings.fFragColorIsInOut);
Brian Salomondc092132018-04-04 10:14:16 -04001064
Ethan Nicholase2c49992020-10-05 11:49:11 -04001065 if (f.fDeclaration.name() == "main") {
John Stilescdcdb042020-07-06 09:03:51 -04001066 this->writeGlobalInit();
Timothy Liang7d637782018-06-05 09:58:07 -04001067 this->writeLine(" Outputs _outputStruct;");
1068 this->writeLine(" thread Outputs* _out = &_outputStruct;");
Ethan Nicholascc305772017-10-13 16:17:45 -04001069 }
John Stilesc67b3622020-05-28 17:53:13 -04001070
Ethan Nicholascc305772017-10-13 16:17:45 -04001071 fFunctionHeader = "";
1072 OutputStream* oldOut = fOut;
1073 StringStream buffer;
1074 fOut = &buffer;
1075 fIndentation++;
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001076 for (const std::unique_ptr<Statement>& stmt : f.fBody->as<Block>().children()) {
1077 if (!stmt->isEmpty()) {
1078 this->writeStatement(*stmt);
1079 this->writeLine();
1080 }
1081 }
Ethan Nicholase2c49992020-10-05 11:49:11 -04001082 if (f.fDeclaration.name() == "main") {
Ethan Nicholascc305772017-10-13 16:17:45 -04001083 switch (fProgram.fKind) {
1084 case Program::kFragment_Kind:
Timothy Liang7d637782018-06-05 09:58:07 -04001085 this->writeLine("return *_out;");
Ethan Nicholascc305772017-10-13 16:17:45 -04001086 break;
1087 case Program::kVertex_Kind:
Timothy Liangb8eeb802018-07-23 16:46:16 -04001088 this->writeLine("_out->sk_Position.y = -_out->sk_Position.y;");
Timothy Lianga06f2152018-05-24 15:33:31 -04001089 this->writeLine("return *_out;"); // FIXME - detect if function already has return
Ethan Nicholascc305772017-10-13 16:17:45 -04001090 break;
1091 default:
John Stilesf7d70432020-05-28 15:46:38 -04001092 SkDEBUGFAIL("unsupported kind of program");
Ethan Nicholascc305772017-10-13 16:17:45 -04001093 }
1094 }
1095 fIndentation--;
1096 this->writeLine("}");
1097
1098 fOut = oldOut;
1099 this->write(fFunctionHeader);
1100 this->write(buffer.str());
1101}
1102
1103void MetalCodeGenerator::writeModifiers(const Modifiers& modifiers,
1104 bool globalContext) {
1105 if (modifiers.fFlags & Modifiers::kOut_Flag) {
1106 this->write("thread ");
1107 }
1108 if (modifiers.fFlags & Modifiers::kConst_Flag) {
Timothy Liangee84fe12018-05-18 14:38:19 -04001109 this->write("constant ");
Ethan Nicholascc305772017-10-13 16:17:45 -04001110 }
1111}
1112
1113void MetalCodeGenerator::writeInterfaceBlock(const InterfaceBlock& intf) {
1114 if ("sk_PerVertex" == intf.fTypeName) {
1115 return;
1116 }
Brian Osman6a204db2020-10-08 09:29:02 -04001117 this->writeModifiers(intf.fVariable->modifiers(), true);
Timothy Liangdc89f192018-06-13 09:20:31 -04001118 this->write("struct ");
Ethan Nicholascc305772017-10-13 16:17:45 -04001119 this->writeLine(intf.fTypeName + " {");
Brian Osman6a204db2020-10-08 09:29:02 -04001120 const Type* structType = &intf.fVariable->type();
Timothy Lianga06f2152018-05-24 15:33:31 -04001121 fWrittenStructs.push_back(structType);
Ethan Nicholase6592142020-09-08 10:22:09 -04001122 while (structType->typeKind() == Type::TypeKind::kArray) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001123 structType = &structType->componentType();
1124 }
Timothy Liangdc89f192018-06-13 09:20:31 -04001125 fIndentation++;
1126 writeFields(structType->fields(), structType->fOffset, &intf);
Jim Van Verth3d482992019-02-07 10:48:05 -05001127 if (fProgram.fInputs.fRTHeight) {
Timothy Liang7d637782018-06-05 09:58:07 -04001128 this->writeLine("float u_skRTHeight;");
Ethan Nicholascc305772017-10-13 16:17:45 -04001129 }
1130 fIndentation--;
1131 this->write("}");
1132 if (intf.fInstanceName.size()) {
1133 this->write(" ");
1134 this->write(intf.fInstanceName);
1135 for (const auto& size : intf.fSizes) {
1136 this->write("[");
1137 if (size) {
1138 this->writeExpression(*size, kTopLevel_Precedence);
1139 }
1140 this->write("]");
1141 }
Timothy Lianga06f2152018-05-24 15:33:31 -04001142 fInterfaceBlockNameMap[&intf] = intf.fInstanceName;
1143 } else {
Timothy Liang7d637782018-06-05 09:58:07 -04001144 fInterfaceBlockNameMap[&intf] = "_anonInterface" + to_string(fAnonInterfaceCount++);
Ethan Nicholascc305772017-10-13 16:17:45 -04001145 }
1146 this->writeLine(";");
1147}
1148
Timothy Liangdc89f192018-06-13 09:20:31 -04001149void MetalCodeGenerator::writeFields(const std::vector<Type::Field>& fields, int parentOffset,
1150 const InterfaceBlock* parentIntf) {
Timothy Liang609fbe32018-08-10 16:40:49 -04001151 MemoryLayout memoryLayout(MemoryLayout::kMetal_Standard);
Timothy Liangdc89f192018-06-13 09:20:31 -04001152 int currentOffset = 0;
1153 for (const auto& field: fields) {
1154 int fieldOffset = field.fModifiers.fLayout.fOffset;
1155 const Type* fieldType = field.fType;
1156 if (fieldOffset != -1) {
1157 if (currentOffset > fieldOffset) {
1158 fErrors.error(parentOffset,
1159 "offset of field '" + field.fName + "' must be at least " +
1160 to_string((int) currentOffset));
Brian Osman8609a242020-09-08 14:01:49 -04001161 return;
Timothy Liangdc89f192018-06-13 09:20:31 -04001162 } else if (currentOffset < fieldOffset) {
1163 this->write("char pad");
1164 this->write(to_string(fPaddingCount++));
1165 this->write("[");
1166 this->write(to_string(fieldOffset - currentOffset));
1167 this->writeLine("];");
1168 currentOffset = fieldOffset;
1169 }
1170 int alignment = memoryLayout.alignment(*fieldType);
1171 if (fieldOffset % alignment) {
1172 fErrors.error(parentOffset,
1173 "offset of field '" + field.fName + "' must be a multiple of " +
1174 to_string((int) alignment));
Brian Osman8609a242020-09-08 14:01:49 -04001175 return;
Timothy Liangdc89f192018-06-13 09:20:31 -04001176 }
1177 }
Brian Osman8609a242020-09-08 14:01:49 -04001178 size_t fieldSize = memoryLayout.size(*fieldType);
1179 if (fieldSize > static_cast<size_t>(std::numeric_limits<int>::max() - currentOffset)) {
1180 fErrors.error(parentOffset, "field offset overflow");
1181 return;
1182 }
1183 currentOffset += fieldSize;
Timothy Liangdc89f192018-06-13 09:20:31 -04001184 std::vector<int> sizes;
Ethan Nicholase6592142020-09-08 10:22:09 -04001185 while (fieldType->typeKind() == Type::TypeKind::kArray) {
Timothy Liangdc89f192018-06-13 09:20:31 -04001186 sizes.push_back(fieldType->columns());
1187 fieldType = &fieldType->componentType();
1188 }
1189 this->writeModifiers(field.fModifiers, false);
1190 this->writeType(*fieldType);
1191 this->write(" ");
1192 this->writeName(field.fName);
1193 for (int s : sizes) {
Brian Osmane8c26082020-10-01 17:22:45 -04001194 if (s == Type::kUnsizedArray) {
Timothy Liangdc89f192018-06-13 09:20:31 -04001195 this->write("[]");
1196 } else {
1197 this->write("[" + to_string(s) + "]");
1198 }
1199 }
1200 this->writeLine(";");
1201 if (parentIntf) {
1202 fInterfaceBlockMap[&field] = parentIntf;
1203 }
1204 }
1205}
1206
Ethan Nicholascc305772017-10-13 16:17:45 -04001207void MetalCodeGenerator::writeVarInitializer(const Variable& var, const Expression& value) {
1208 this->writeExpression(value, kTopLevel_Precedence);
1209}
1210
Timothy Liang651286f2018-06-07 09:55:33 -04001211void MetalCodeGenerator::writeName(const String& name) {
1212 if (fReservedWords.find(name) != fReservedWords.end()) {
1213 this->write("_"); // adding underscore before name to avoid conflict with reserved words
1214 }
1215 this->write(name);
1216}
1217
Brian Osmanc0213602020-10-06 14:43:32 -04001218void MetalCodeGenerator::writeVarDeclaration(const VarDeclaration& var, bool global) {
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001219 if (global && !(var.fVar->modifiers().fFlags & Modifiers::kConst_Flag)) {
Brian Osmanc0213602020-10-06 14:43:32 -04001220 return;
Ethan Nicholascc305772017-10-13 16:17:45 -04001221 }
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001222 this->writeModifiers(var.fVar->modifiers(), global);
Brian Osmanc0213602020-10-06 14:43:32 -04001223 this->writeType(var.fBaseType);
1224 this->write(" ");
1225 this->writeName(var.fVar->name());
1226 for (const auto& size : var.fSizes) {
1227 this->write("[");
1228 if (size) {
1229 this->writeExpression(*size, kTopLevel_Precedence);
1230 }
1231 this->write("]");
Ethan Nicholascc305772017-10-13 16:17:45 -04001232 }
Brian Osmanc0213602020-10-06 14:43:32 -04001233 if (var.fValue) {
1234 this->write(" = ");
1235 this->writeVarInitializer(*var.fVar, *var.fValue);
1236 }
1237 this->write(";");
Ethan Nicholascc305772017-10-13 16:17:45 -04001238}
1239
1240void MetalCodeGenerator::writeStatement(const Statement& s) {
Ethan Nicholase6592142020-09-08 10:22:09 -04001241 switch (s.kind()) {
1242 case Statement::Kind::kBlock:
John Stiles26f98502020-08-18 09:30:51 -04001243 this->writeBlock(s.as<Block>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001244 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001245 case Statement::Kind::kExpression:
Ethan Nicholasd503a5a2020-09-30 09:29:55 -04001246 this->writeExpression(*s.as<ExpressionStatement>().expression(), kTopLevel_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001247 this->write(";");
1248 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001249 case Statement::Kind::kReturn:
John Stiles26f98502020-08-18 09:30:51 -04001250 this->writeReturnStatement(s.as<ReturnStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001251 break;
Brian Osmanc0213602020-10-06 14:43:32 -04001252 case Statement::Kind::kVarDeclaration:
1253 this->writeVarDeclaration(s.as<VarDeclaration>(), false);
Ethan Nicholascc305772017-10-13 16:17:45 -04001254 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001255 case Statement::Kind::kIf:
John Stiles26f98502020-08-18 09:30:51 -04001256 this->writeIfStatement(s.as<IfStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001257 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001258 case Statement::Kind::kFor:
John Stiles26f98502020-08-18 09:30:51 -04001259 this->writeForStatement(s.as<ForStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001260 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001261 case Statement::Kind::kWhile:
John Stiles26f98502020-08-18 09:30:51 -04001262 this->writeWhileStatement(s.as<WhileStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001263 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001264 case Statement::Kind::kDo:
John Stiles26f98502020-08-18 09:30:51 -04001265 this->writeDoStatement(s.as<DoStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001266 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001267 case Statement::Kind::kSwitch:
John Stiles26f98502020-08-18 09:30:51 -04001268 this->writeSwitchStatement(s.as<SwitchStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001269 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001270 case Statement::Kind::kBreak:
Ethan Nicholascc305772017-10-13 16:17:45 -04001271 this->write("break;");
1272 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001273 case Statement::Kind::kContinue:
Ethan Nicholascc305772017-10-13 16:17:45 -04001274 this->write("continue;");
1275 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001276 case Statement::Kind::kDiscard:
Timothy Lianga06f2152018-05-24 15:33:31 -04001277 this->write("discard_fragment();");
Ethan Nicholascc305772017-10-13 16:17:45 -04001278 break;
John Stiles98c1f822020-09-09 14:18:53 -04001279 case Statement::Kind::kInlineMarker:
Ethan Nicholase6592142020-09-08 10:22:09 -04001280 case Statement::Kind::kNop:
Ethan Nicholascc305772017-10-13 16:17:45 -04001281 this->write(";");
1282 break;
1283 default:
Ethan Nicholas2a099da2020-01-02 14:40:54 -05001284#ifdef SK_DEBUG
Ethan Nicholascc305772017-10-13 16:17:45 -04001285 ABORT("unsupported statement: %s", s.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -05001286#endif
1287 break;
Ethan Nicholascc305772017-10-13 16:17:45 -04001288 }
1289}
1290
Ethan Nicholascc305772017-10-13 16:17:45 -04001291void MetalCodeGenerator::writeBlock(const Block& b) {
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001292 bool isScope = b.isScope();
1293 if (isScope) {
Ethan Nicholas70728ef2020-05-28 07:09:00 -04001294 this->writeLine("{");
1295 fIndentation++;
1296 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001297 for (const std::unique_ptr<Statement>& stmt : b.children()) {
1298 if (!stmt->isEmpty()) {
1299 this->writeStatement(*stmt);
1300 this->writeLine();
1301 }
1302 }
1303 if (isScope) {
Ethan Nicholas70728ef2020-05-28 07:09:00 -04001304 fIndentation--;
1305 this->write("}");
1306 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001307}
1308
1309void MetalCodeGenerator::writeIfStatement(const IfStatement& stmt) {
1310 this->write("if (");
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04001311 this->writeExpression(*stmt.test(), kTopLevel_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001312 this->write(") ");
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04001313 this->writeStatement(*stmt.ifTrue());
1314 if (stmt.ifFalse()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001315 this->write(" else ");
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04001316 this->writeStatement(*stmt.ifFalse());
Ethan Nicholascc305772017-10-13 16:17:45 -04001317 }
1318}
1319
1320void MetalCodeGenerator::writeForStatement(const ForStatement& f) {
1321 this->write("for (");
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04001322 if (f.initializer() && !f.initializer()->isEmpty()) {
1323 this->writeStatement(*f.initializer());
Ethan Nicholascc305772017-10-13 16:17:45 -04001324 } else {
1325 this->write("; ");
1326 }
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04001327 if (f.test()) {
1328 this->writeExpression(*f.test(), kTopLevel_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001329 }
1330 this->write("; ");
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04001331 if (f.next()) {
1332 this->writeExpression(*f.next(), kTopLevel_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001333 }
1334 this->write(") ");
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04001335 this->writeStatement(*f.statement());
Ethan Nicholascc305772017-10-13 16:17:45 -04001336}
1337
1338void MetalCodeGenerator::writeWhileStatement(const WhileStatement& w) {
1339 this->write("while (");
1340 this->writeExpression(*w.fTest, kTopLevel_Precedence);
1341 this->write(") ");
1342 this->writeStatement(*w.fStatement);
1343}
1344
1345void MetalCodeGenerator::writeDoStatement(const DoStatement& d) {
1346 this->write("do ");
Ethan Nicholas1fd61162020-09-28 13:14:19 -04001347 this->writeStatement(*d.statement());
Ethan Nicholascc305772017-10-13 16:17:45 -04001348 this->write(" while (");
Ethan Nicholas1fd61162020-09-28 13:14:19 -04001349 this->writeExpression(*d.test(), kTopLevel_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001350 this->write(");");
1351}
1352
1353void MetalCodeGenerator::writeSwitchStatement(const SwitchStatement& s) {
1354 this->write("switch (");
1355 this->writeExpression(*s.fValue, kTopLevel_Precedence);
1356 this->writeLine(") {");
1357 fIndentation++;
1358 for (const auto& c : s.fCases) {
1359 if (c->fValue) {
1360 this->write("case ");
1361 this->writeExpression(*c->fValue, kTopLevel_Precedence);
1362 this->writeLine(":");
1363 } else {
1364 this->writeLine("default:");
1365 }
1366 fIndentation++;
1367 for (const auto& stmt : c->fStatements) {
1368 this->writeStatement(*stmt);
1369 this->writeLine();
1370 }
1371 fIndentation--;
1372 }
1373 fIndentation--;
1374 this->write("}");
1375}
1376
1377void MetalCodeGenerator::writeReturnStatement(const ReturnStatement& r) {
1378 this->write("return");
1379 if (r.fExpression) {
1380 this->write(" ");
1381 this->writeExpression(*r.fExpression, kTopLevel_Precedence);
1382 }
1383 this->write(";");
1384}
1385
1386void MetalCodeGenerator::writeHeader() {
1387 this->write("#include <metal_stdlib>\n");
1388 this->write("#include <simd/simd.h>\n");
1389 this->write("using namespace metal;\n");
1390}
1391
1392void MetalCodeGenerator::writeUniformStruct() {
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001393 for (const auto& e : fProgram) {
Brian Osmanc0213602020-10-06 14:43:32 -04001394 if (e.is<GlobalVarDeclaration>()) {
1395 const GlobalVarDeclaration& decls = e.as<GlobalVarDeclaration>();
1396 const Variable& var = *decls.fDecl->fVar;
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001397 if (var.modifiers().fFlags & Modifiers::kUniform_Flag &&
Brian Osmanc0213602020-10-06 14:43:32 -04001398 var.type().typeKind() != Type::TypeKind::kSampler) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001399 if (-1 == fUniformBuffer) {
1400 this->write("struct Uniforms {\n");
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001401 fUniformBuffer = var.modifiers().fLayout.fSet;
Ethan Nicholascc305772017-10-13 16:17:45 -04001402 if (-1 == fUniformBuffer) {
1403 fErrors.error(decls.fOffset, "Metal uniforms must have 'layout(set=...)'");
1404 }
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001405 } else if (var.modifiers().fLayout.fSet != fUniformBuffer) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001406 if (-1 == fUniformBuffer) {
1407 fErrors.error(decls.fOffset, "Metal backend requires all uniforms to have "
1408 "the same 'layout(set=...)'");
1409 }
1410 }
1411 this->write(" ");
Brian Osmanc0213602020-10-06 14:43:32 -04001412 this->writeType(var.type());
Ethan Nicholascc305772017-10-13 16:17:45 -04001413 this->write(" ");
Brian Osmanc0213602020-10-06 14:43:32 -04001414 this->writeName(var.name());
Ethan Nicholascc305772017-10-13 16:17:45 -04001415 this->write(";\n");
1416 }
1417 }
1418 }
1419 if (-1 != fUniformBuffer) {
1420 this->write("};\n");
1421 }
1422}
1423
1424void MetalCodeGenerator::writeInputStruct() {
1425 this->write("struct Inputs {\n");
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001426 for (const auto& e : fProgram) {
Brian Osmanc0213602020-10-06 14:43:32 -04001427 if (e.is<GlobalVarDeclaration>()) {
1428 const GlobalVarDeclaration& decls = e.as<GlobalVarDeclaration>();
1429 const Variable& var = *decls.fDecl->fVar;
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001430 if (var.modifiers().fFlags & Modifiers::kIn_Flag &&
1431 -1 == var.modifiers().fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001432 this->write(" ");
Brian Osmanc0213602020-10-06 14:43:32 -04001433 this->writeType(var.type());
Ethan Nicholascc305772017-10-13 16:17:45 -04001434 this->write(" ");
Brian Osmanc0213602020-10-06 14:43:32 -04001435 this->writeName(var.name());
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001436 if (-1 != var.modifiers().fLayout.fLocation) {
Brian Osmanc0213602020-10-06 14:43:32 -04001437 if (fProgram.fKind == Program::kVertex_Kind) {
1438 this->write(" [[attribute(" +
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001439 to_string(var.modifiers().fLayout.fLocation) + ")]]");
Brian Osmanc0213602020-10-06 14:43:32 -04001440 } else if (fProgram.fKind == Program::kFragment_Kind) {
1441 this->write(" [[user(locn" +
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001442 to_string(var.modifiers().fLayout.fLocation) + ")]]");
Ethan Nicholascc305772017-10-13 16:17:45 -04001443 }
1444 }
1445 this->write(";\n");
1446 }
1447 }
1448 }
1449 this->write("};\n");
1450}
1451
1452void MetalCodeGenerator::writeOutputStruct() {
1453 this->write("struct Outputs {\n");
Timothy Liang7d637782018-06-05 09:58:07 -04001454 if (fProgram.fKind == Program::kVertex_Kind) {
Timothy Liangb8eeb802018-07-23 16:46:16 -04001455 this->write(" float4 sk_Position [[position]];\n");
Timothy Liang7d637782018-06-05 09:58:07 -04001456 } else if (fProgram.fKind == Program::kFragment_Kind) {
Timothy Liangde0be802018-08-10 13:48:08 -04001457 this->write(" float4 sk_FragColor [[color(0)]];\n");
Timothy Liang7d637782018-06-05 09:58:07 -04001458 }
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001459 for (const auto& e : fProgram) {
Brian Osmanc0213602020-10-06 14:43:32 -04001460 if (e.is<GlobalVarDeclaration>()) {
1461 const GlobalVarDeclaration& decls = e.as<GlobalVarDeclaration>();
1462 const Variable& var = *decls.fDecl->fVar;
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001463 if (var.modifiers().fFlags & Modifiers::kOut_Flag &&
1464 -1 == var.modifiers().fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001465 this->write(" ");
Brian Osmanc0213602020-10-06 14:43:32 -04001466 this->writeType(var.type());
Ethan Nicholascc305772017-10-13 16:17:45 -04001467 this->write(" ");
Brian Osmanc0213602020-10-06 14:43:32 -04001468 this->writeName(var.name());
1469 if (fProgram.fKind == Program::kVertex_Kind) {
1470 this->write(" [[user(locn" +
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001471 to_string(var.modifiers().fLayout.fLocation) + ")]]");
Brian Osmanc0213602020-10-06 14:43:32 -04001472 } else if (fProgram.fKind == Program::kFragment_Kind) {
1473 this->write(" [[color(" +
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001474 to_string(var.modifiers().fLayout.fLocation) +")");
1475 int colorIndex = var.modifiers().fLayout.fIndex;
Brian Osmanc0213602020-10-06 14:43:32 -04001476 if (colorIndex) {
1477 this->write(", index(" + to_string(colorIndex) + ")");
Timothy Liang7d637782018-06-05 09:58:07 -04001478 }
Brian Osmanc0213602020-10-06 14:43:32 -04001479 this->write("]]");
Ethan Nicholascc305772017-10-13 16:17:45 -04001480 }
1481 this->write(";\n");
1482 }
1483 }
Timothy Liang7d637782018-06-05 09:58:07 -04001484 }
1485 if (fProgram.fKind == Program::kVertex_Kind) {
Jim Van Verth3913d3e2020-08-31 15:16:57 -04001486 this->write(" float sk_PointSize [[point_size]];\n");
Timothy Liang7d637782018-06-05 09:58:07 -04001487 }
1488 this->write("};\n");
1489}
1490
1491void MetalCodeGenerator::writeInterfaceBlocks() {
1492 bool wroteInterfaceBlock = false;
1493 for (const auto& e : fProgram) {
Ethan Nicholase6592142020-09-08 10:22:09 -04001494 if (e.kind() == ProgramElement::Kind::kInterfaceBlock) {
John Stiles3dc0da62020-08-19 17:48:31 -04001495 this->writeInterfaceBlock(e.as<InterfaceBlock>());
Timothy Liang7d637782018-06-05 09:58:07 -04001496 wroteInterfaceBlock = true;
1497 }
1498 }
Jim Van Verth3d482992019-02-07 10:48:05 -05001499 if (!wroteInterfaceBlock && fProgram.fInputs.fRTHeight) {
Timothy Liang7d637782018-06-05 09:58:07 -04001500 this->writeLine("struct sksl_synthetic_uniforms {");
1501 this->writeLine(" float u_skRTHeight;");
1502 this->writeLine("};");
1503 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001504}
1505
John Stilescdcdb042020-07-06 09:03:51 -04001506void MetalCodeGenerator::visitGlobalStruct(GlobalStructVisitor* visitor) {
1507 // Visit the interface blocks.
1508 for (const auto& [interfaceType, interfaceName] : fInterfaceBlockNameMap) {
1509 visitor->VisitInterfaceBlock(*interfaceType, interfaceName);
1510 }
1511 for (const ProgramElement& element : fProgram) {
Brian Osmanc0213602020-10-06 14:43:32 -04001512 if (!element.is<GlobalVarDeclaration>()) {
John Stilescdcdb042020-07-06 09:03:51 -04001513 continue;
Timothy Liang7d637782018-06-05 09:58:07 -04001514 }
Brian Osmanc0213602020-10-06 14:43:32 -04001515 const GlobalVarDeclaration& decls = element.as<GlobalVarDeclaration>();
1516 const VarDeclaration& decl = *decls.fDecl;
1517 const Variable& var = *decl.fVar;
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001518 if ((!var.modifiers().fFlags && -1 == var.modifiers().fLayout.fBuiltin) ||
Brian Osmanc0213602020-10-06 14:43:32 -04001519 var.type().typeKind() == Type::TypeKind::kSampler) {
1520 if (var.type().typeKind() == Type::TypeKind::kSampler) {
1521 // Samplers are represented as a "texture/sampler" duo in the global struct.
1522 visitor->VisitTexture(var.type(), var.name());
1523 visitor->VisitSampler(var.type(), String(var.name()) + SAMPLER_SUFFIX);
1524 } else {
1525 // Visit a regular variable.
1526 visitor->VisitVariable(var, decl.fValue.get());
Timothy Liangee84fe12018-05-18 14:38:19 -04001527 }
1528 }
1529 }
John Stilescdcdb042020-07-06 09:03:51 -04001530}
1531
1532void MetalCodeGenerator::writeGlobalStruct() {
1533 class : public GlobalStructVisitor {
1534 public:
1535 void VisitInterfaceBlock(const InterfaceBlock& block, const String& blockName) override {
1536 this->AddElement();
1537 fCodeGen->write(" constant ");
1538 fCodeGen->write(block.fTypeName);
1539 fCodeGen->write("* ");
1540 fCodeGen->writeName(blockName);
1541 fCodeGen->write(";\n");
1542 }
1543 void VisitTexture(const Type& type, const String& name) override {
1544 this->AddElement();
1545 fCodeGen->write(" ");
1546 fCodeGen->writeType(type);
1547 fCodeGen->write(" ");
1548 fCodeGen->writeName(name);
1549 fCodeGen->write(";\n");
1550 }
1551 void VisitSampler(const Type&, const String& name) override {
1552 this->AddElement();
1553 fCodeGen->write(" sampler ");
1554 fCodeGen->writeName(name);
1555 fCodeGen->write(";\n");
1556 }
1557 void VisitVariable(const Variable& var, const Expression* value) override {
1558 this->AddElement();
1559 fCodeGen->write(" ");
Ethan Nicholas30d30222020-09-11 12:27:26 -04001560 fCodeGen->writeType(var.type());
John Stilescdcdb042020-07-06 09:03:51 -04001561 fCodeGen->write(" ");
Ethan Nicholase2c49992020-10-05 11:49:11 -04001562 fCodeGen->writeName(var.name());
John Stilescdcdb042020-07-06 09:03:51 -04001563 fCodeGen->write(";\n");
1564 }
1565 void AddElement() {
1566 if (fFirst) {
1567 fCodeGen->write("struct Globals {\n");
1568 fFirst = false;
1569 }
1570 }
1571 void Finish() {
1572 if (!fFirst) {
1573 fCodeGen->write("};");
1574 fFirst = true;
1575 }
1576 }
1577
1578 MetalCodeGenerator* fCodeGen = nullptr;
1579 bool fFirst = true;
1580 } visitor;
1581
1582 visitor.fCodeGen = this;
1583 this->visitGlobalStruct(&visitor);
1584 visitor.Finish();
1585}
1586
1587void MetalCodeGenerator::writeGlobalInit() {
1588 class : public GlobalStructVisitor {
1589 public:
1590 void VisitInterfaceBlock(const InterfaceBlock& blockType,
1591 const String& blockName) override {
1592 this->AddElement();
1593 fCodeGen->write("&");
1594 fCodeGen->writeName(blockName);
1595 }
1596 void VisitTexture(const Type&, const String& name) override {
1597 this->AddElement();
1598 fCodeGen->writeName(name);
1599 }
1600 void VisitSampler(const Type&, const String& name) override {
1601 this->AddElement();
1602 fCodeGen->writeName(name);
1603 }
1604 void VisitVariable(const Variable& var, const Expression* value) override {
1605 this->AddElement();
1606 if (value) {
1607 fCodeGen->writeVarInitializer(var, *value);
1608 } else {
1609 fCodeGen->write("{}");
1610 }
1611 }
1612 void AddElement() {
1613 if (fFirst) {
1614 fCodeGen->write(" Globals globalStruct{");
1615 fFirst = false;
1616 } else {
1617 fCodeGen->write(", ");
1618 }
1619 }
1620 void Finish() {
1621 if (!fFirst) {
1622 fCodeGen->writeLine("};");
1623 fCodeGen->writeLine(" thread Globals* _globals = &globalStruct;");
1624 fCodeGen->writeLine(" (void)_globals;");
1625 }
1626 }
1627 MetalCodeGenerator* fCodeGen = nullptr;
1628 bool fFirst = true;
1629 } visitor;
1630
1631 visitor.fCodeGen = this;
1632 this->visitGlobalStruct(&visitor);
1633 visitor.Finish();
Timothy Liangee84fe12018-05-18 14:38:19 -04001634}
1635
Ethan Nicholascc305772017-10-13 16:17:45 -04001636void MetalCodeGenerator::writeProgramElement(const ProgramElement& e) {
Ethan Nicholase6592142020-09-08 10:22:09 -04001637 switch (e.kind()) {
1638 case ProgramElement::Kind::kExtension:
Ethan Nicholascc305772017-10-13 16:17:45 -04001639 break;
Brian Osmanc0213602020-10-06 14:43:32 -04001640 case ProgramElement::Kind::kGlobalVar: {
1641 const VarDeclaration& decl = *e.as<GlobalVarDeclaration>().fDecl;
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001642 int builtin = decl.fVar->modifiers().fLayout.fBuiltin;
Brian Osmanc0213602020-10-06 14:43:32 -04001643 if (-1 == builtin) {
1644 // normal var
1645 this->writeVarDeclaration(decl, true);
1646 this->writeLine();
1647 } else if (SK_FRAGCOLOR_BUILTIN == builtin) {
1648 // ignore
Ethan Nicholascc305772017-10-13 16:17:45 -04001649 }
1650 break;
1651 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001652 case ProgramElement::Kind::kInterfaceBlock:
Timothy Liang7d637782018-06-05 09:58:07 -04001653 // handled in writeInterfaceBlocks, do nothing
Ethan Nicholascc305772017-10-13 16:17:45 -04001654 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001655 case ProgramElement::Kind::kFunction:
John Stiles3dc0da62020-08-19 17:48:31 -04001656 this->writeFunction(e.as<FunctionDefinition>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001657 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001658 case ProgramElement::Kind::kModifiers:
John Stiles3dc0da62020-08-19 17:48:31 -04001659 this->writeModifiers(e.as<ModifiersDeclaration>().fModifiers, true);
Ethan Nicholascc305772017-10-13 16:17:45 -04001660 this->writeLine(";");
1661 break;
1662 default:
Ethan Nicholas2a099da2020-01-02 14:40:54 -05001663#ifdef SK_DEBUG
1664 ABORT("unsupported program element: %s\n", e.description().c_str());
1665#endif
1666 break;
Ethan Nicholascc305772017-10-13 16:17:45 -04001667 }
1668}
1669
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001670MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const Expression* e) {
1671 if (!e) {
1672 return kNo_Requirements;
1673 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001674 switch (e->kind()) {
1675 case Expression::Kind::kFunctionCall: {
John Stiles3dc0da62020-08-19 17:48:31 -04001676 const FunctionCall& f = e->as<FunctionCall>();
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001677 Requirements result = this->requirements(f.function());
1678 for (const auto& arg : f.arguments()) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001679 result |= this->requirements(arg.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001680 }
1681 return result;
1682 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001683 case Expression::Kind::kConstructor: {
John Stiles3dc0da62020-08-19 17:48:31 -04001684 const Constructor& c = e->as<Constructor>();
Ethan Nicholascc305772017-10-13 16:17:45 -04001685 Requirements result = kNo_Requirements;
Ethan Nicholasf70f0442020-09-29 12:41:35 -04001686 for (const auto& arg : c.arguments()) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001687 result |= this->requirements(arg.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001688 }
1689 return result;
1690 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001691 case Expression::Kind::kFieldAccess: {
John Stiles3dc0da62020-08-19 17:48:31 -04001692 const FieldAccess& f = e->as<FieldAccess>();
Timothy Liang7d637782018-06-05 09:58:07 -04001693 if (FieldAccess::kAnonymousInterfaceBlock_OwnerKind == f.fOwnerKind) {
1694 return kGlobals_Requirement;
1695 }
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001696 return this->requirements(f.fBase.get());
Timothy Liang7d637782018-06-05 09:58:07 -04001697 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001698 case Expression::Kind::kSwizzle:
John Stiles3dc0da62020-08-19 17:48:31 -04001699 return this->requirements(e->as<Swizzle>().fBase.get());
Ethan Nicholase6592142020-09-08 10:22:09 -04001700 case Expression::Kind::kBinary: {
1701 const BinaryExpression& bin = e->as<BinaryExpression>();
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001702 return this->requirements(&bin.left()) |
1703 this->requirements(&bin.right());
Ethan Nicholascc305772017-10-13 16:17:45 -04001704 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001705 case Expression::Kind::kIndex: {
John Stiles3dc0da62020-08-19 17:48:31 -04001706 const IndexExpression& idx = e->as<IndexExpression>();
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001707 return this->requirements(idx.fBase.get()) | this->requirements(idx.fIndex.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001708 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001709 case Expression::Kind::kPrefix:
John Stiles3dc0da62020-08-19 17:48:31 -04001710 return this->requirements(e->as<PrefixExpression>().fOperand.get());
Ethan Nicholase6592142020-09-08 10:22:09 -04001711 case Expression::Kind::kPostfix:
John Stiles3dc0da62020-08-19 17:48:31 -04001712 return this->requirements(e->as<PostfixExpression>().fOperand.get());
Ethan Nicholase6592142020-09-08 10:22:09 -04001713 case Expression::Kind::kTernary: {
John Stiles3dc0da62020-08-19 17:48:31 -04001714 const TernaryExpression& t = e->as<TernaryExpression>();
Ethan Nicholasdd218162020-10-08 05:48:01 -04001715 return this->requirements(t.test().get()) | this->requirements(t.ifTrue().get()) |
1716 this->requirements(t.ifFalse().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001717 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001718 case Expression::Kind::kVariableReference: {
John Stiles3dc0da62020-08-19 17:48:31 -04001719 const VariableReference& v = e->as<VariableReference>();
Ethan Nicholas78686922020-10-08 06:46:27 -04001720 const Modifiers& modifiers = v.variable()->modifiers();
Ethan Nicholascc305772017-10-13 16:17:45 -04001721 Requirements result = kNo_Requirements;
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001722 if (modifiers.fLayout.fBuiltin == SK_FRAGCOORD_BUILTIN) {
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -04001723 result = kGlobals_Requirement | kFragCoord_Requirement;
Ethan Nicholas78686922020-10-08 06:46:27 -04001724 } else if (Variable::kGlobal_Storage == v.variable()->storage()) {
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001725 if (modifiers.fFlags & Modifiers::kIn_Flag) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001726 result = kInputs_Requirement;
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001727 } else if (modifiers.fFlags & Modifiers::kOut_Flag) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001728 result = kOutputs_Requirement;
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001729 } else if (modifiers.fFlags & Modifiers::kUniform_Flag &&
Ethan Nicholas78686922020-10-08 06:46:27 -04001730 v.variable()->type().typeKind() != Type::TypeKind::kSampler) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001731 result = kUniforms_Requirement;
Timothy Liangee84fe12018-05-18 14:38:19 -04001732 } else {
1733 result = kGlobals_Requirement;
Ethan Nicholascc305772017-10-13 16:17:45 -04001734 }
1735 }
1736 return result;
1737 }
1738 default:
1739 return kNo_Requirements;
1740 }
1741}
1742
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001743MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const Statement* s) {
1744 if (!s) {
1745 return kNo_Requirements;
1746 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001747 switch (s->kind()) {
1748 case Statement::Kind::kBlock: {
Ethan Nicholascc305772017-10-13 16:17:45 -04001749 Requirements result = kNo_Requirements;
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001750 for (const std::unique_ptr<Statement>& child : s->as<Block>().children()) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001751 result |= this->requirements(child.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001752 }
1753 return result;
1754 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001755 case Statement::Kind::kVarDeclaration: {
John Stiles3dc0da62020-08-19 17:48:31 -04001756 const VarDeclaration& var = s->as<VarDeclaration>();
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001757 return this->requirements(var.fValue.get());
Timothy Liang7d637782018-06-05 09:58:07 -04001758 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001759 case Statement::Kind::kExpression:
Ethan Nicholasd503a5a2020-09-30 09:29:55 -04001760 return this->requirements(s->as<ExpressionStatement>().expression().get());
Ethan Nicholase6592142020-09-08 10:22:09 -04001761 case Statement::Kind::kReturn: {
John Stiles3dc0da62020-08-19 17:48:31 -04001762 const ReturnStatement& r = s->as<ReturnStatement>();
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001763 return this->requirements(r.fExpression.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001764 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001765 case Statement::Kind::kIf: {
John Stiles3dc0da62020-08-19 17:48:31 -04001766 const IfStatement& i = s->as<IfStatement>();
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04001767 return this->requirements(i.test().get()) |
1768 this->requirements(i.ifTrue().get()) |
1769 this->requirements(i.ifFalse().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001770 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001771 case Statement::Kind::kFor: {
John Stiles3dc0da62020-08-19 17:48:31 -04001772 const ForStatement& f = s->as<ForStatement>();
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04001773 return this->requirements(f.initializer().get()) |
1774 this->requirements(f.test().get()) |
1775 this->requirements(f.next().get()) |
1776 this->requirements(f.statement().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001777 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001778 case Statement::Kind::kWhile: {
John Stiles3dc0da62020-08-19 17:48:31 -04001779 const WhileStatement& w = s->as<WhileStatement>();
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001780 return this->requirements(w.fTest.get()) |
1781 this->requirements(w.fStatement.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001782 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001783 case Statement::Kind::kDo: {
John Stiles3dc0da62020-08-19 17:48:31 -04001784 const DoStatement& d = s->as<DoStatement>();
Ethan Nicholas1fd61162020-09-28 13:14:19 -04001785 return this->requirements(d.test().get()) |
1786 this->requirements(d.statement().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001787 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001788 case Statement::Kind::kSwitch: {
John Stiles3dc0da62020-08-19 17:48:31 -04001789 const SwitchStatement& sw = s->as<SwitchStatement>();
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001790 Requirements result = this->requirements(sw.fValue.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001791 for (const auto& c : sw.fCases) {
1792 for (const auto& st : c->fStatements) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001793 result |= this->requirements(st.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001794 }
1795 }
1796 return result;
1797 }
1798 default:
1799 return kNo_Requirements;
1800 }
1801}
1802
1803MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const FunctionDeclaration& f) {
1804 if (f.fBuiltin) {
1805 return kNo_Requirements;
1806 }
1807 auto found = fRequirements.find(&f);
1808 if (found == fRequirements.end()) {
Ethan Nicholas65a8f562019-04-19 14:00:26 -04001809 fRequirements[&f] = kNo_Requirements;
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001810 for (const auto& e : fProgram) {
Ethan Nicholase6592142020-09-08 10:22:09 -04001811 if (e.kind() == ProgramElement::Kind::kFunction) {
John Stiles3dc0da62020-08-19 17:48:31 -04001812 const FunctionDefinition& def = e.as<FunctionDefinition>();
Ethan Nicholascc305772017-10-13 16:17:45 -04001813 if (&def.fDeclaration == &f) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001814 Requirements reqs = this->requirements(def.fBody.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001815 fRequirements[&f] = reqs;
1816 return reqs;
1817 }
1818 }
1819 }
1820 }
1821 return found->second;
1822}
1823
Timothy Liangb8eeb802018-07-23 16:46:16 -04001824bool MetalCodeGenerator::generateCode() {
Ethan Nicholascc305772017-10-13 16:17:45 -04001825 OutputStream* rawOut = fOut;
1826 fOut = &fHeader;
1827 fProgramKind = fProgram.fKind;
1828 this->writeHeader();
1829 this->writeUniformStruct();
1830 this->writeInputStruct();
Timothy Liang7d637782018-06-05 09:58:07 -04001831 this->writeOutputStruct();
1832 this->writeInterfaceBlocks();
Timothy Liangee84fe12018-05-18 14:38:19 -04001833 this->writeGlobalStruct();
Ethan Nicholascc305772017-10-13 16:17:45 -04001834 StringStream body;
1835 fOut = &body;
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001836 for (const auto& e : fProgram) {
1837 this->writeProgramElement(e);
Ethan Nicholascc305772017-10-13 16:17:45 -04001838 }
1839 fOut = rawOut;
1840
1841 write_stringstream(fHeader, *rawOut);
Chris Daltondba7aab2018-11-15 10:57:49 -05001842 write_stringstream(fExtraFunctions, *rawOut);
Ethan Nicholascc305772017-10-13 16:17:45 -04001843 write_stringstream(body, *rawOut);
Brian Osman8609a242020-09-08 14:01:49 -04001844 return 0 == fErrors.errorCount();
Ethan Nicholascc305772017-10-13 16:17:45 -04001845}
1846
John Stilesa6841be2020-08-06 14:11:56 -04001847} // namespace SkSL