blob: 95ccb80fc42dad5b2604aca30d4652089b8185c9 [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"
John Stiles0023c0c2020-11-16 13:32:18 -050011#include "src/sksl/SkSLMemoryLayout.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050012#include "src/sksl/ir/SkSLExpressionStatement.h"
13#include "src/sksl/ir/SkSLExtension.h"
14#include "src/sksl/ir/SkSLIndexExpression.h"
15#include "src/sksl/ir/SkSLModifiersDeclaration.h"
16#include "src/sksl/ir/SkSLNop.h"
17#include "src/sksl/ir/SkSLVariableReference.h"
Ethan Nicholascc305772017-10-13 16:17:45 -040018
Brian Osmanc262a122020-08-06 16:34:34 -040019#include <algorithm>
20
Ethan Nicholascc305772017-10-13 16:17:45 -040021namespace SkSL {
22
John Stilesd6449e92020-11-30 09:13:23 -050023const char* MetalCodeGenerator::OperatorName(Token::Kind op) {
24 switch (op) {
25 case Token::Kind::TK_LOGICALXOR: return "!=";
26 default: return Compiler::OperatorName(op);
27 }
28}
29
John Stilescdcdb042020-07-06 09:03:51 -040030class MetalCodeGenerator::GlobalStructVisitor {
31public:
32 virtual ~GlobalStructVisitor() = default;
33 virtual void VisitInterfaceBlock(const InterfaceBlock& block, const String& blockName) = 0;
34 virtual void VisitTexture(const Type& type, const String& name) = 0;
35 virtual void VisitSampler(const Type& type, const String& name) = 0;
36 virtual void VisitVariable(const Variable& var, const Expression* value) = 0;
37};
38
Timothy Liangee84fe12018-05-18 14:38:19 -040039void MetalCodeGenerator::setupIntrinsics() {
Timothy Liang7d637782018-06-05 09:58:07 -040040#define METAL(x) std::make_pair(kMetal_IntrinsicKind, k ## x ## _MetalIntrinsic)
41#define SPECIAL(x) std::make_pair(kSpecial_IntrinsicKind, k ## x ## _SpecialIntrinsic)
Brian Osman46787d52020-11-24 14:18:23 -050042 fIntrinsicMap[String("distance")] = SPECIAL(Distance);
43 fIntrinsicMap[String("dot")] = SPECIAL(Dot);
44 fIntrinsicMap[String("length")] = SPECIAL(Length);
Timothy Liang651286f2018-06-07 09:55:33 -040045 fIntrinsicMap[String("mod")] = SPECIAL(Mod);
Brian Osman46787d52020-11-24 14:18:23 -050046 fIntrinsicMap[String("normalize")] = SPECIAL(Normalize);
47 fIntrinsicMap[String("sample")] = SPECIAL(Texture);
Ethan Nicholas0dc80872019-02-08 15:46:24 -050048 fIntrinsicMap[String("equal")] = METAL(Equal);
49 fIntrinsicMap[String("notEqual")] = METAL(NotEqual);
Timothy Lianga06f2152018-05-24 15:33:31 -040050 fIntrinsicMap[String("lessThan")] = METAL(LessThan);
51 fIntrinsicMap[String("lessThanEqual")] = METAL(LessThanEqual);
52 fIntrinsicMap[String("greaterThan")] = METAL(GreaterThan);
53 fIntrinsicMap[String("greaterThanEqual")] = METAL(GreaterThanEqual);
Timothy Liangee84fe12018-05-18 14:38:19 -040054}
55
Ethan Nicholascc305772017-10-13 16:17:45 -040056void MetalCodeGenerator::write(const char* s) {
57 if (!s[0]) {
58 return;
59 }
60 if (fAtLineStart) {
61 for (int i = 0; i < fIndentation; i++) {
62 fOut->writeText(" ");
63 }
64 }
65 fOut->writeText(s);
66 fAtLineStart = false;
67}
68
69void MetalCodeGenerator::writeLine(const char* s) {
70 this->write(s);
71 fOut->writeText(fLineEnding);
72 fAtLineStart = true;
73}
74
75void MetalCodeGenerator::write(const String& s) {
76 this->write(s.c_str());
77}
78
79void MetalCodeGenerator::writeLine(const String& s) {
80 this->writeLine(s.c_str());
81}
82
83void MetalCodeGenerator::writeLine() {
84 this->writeLine("");
85}
86
87void MetalCodeGenerator::writeExtension(const Extension& ext) {
Ethan Nicholasefb09e22020-09-30 10:17:00 -040088 this->writeLine("#extension " + ext.name() + " : enable");
Ethan Nicholascc305772017-10-13 16:17:45 -040089}
90
Ethan Nicholas45fa8102020-01-13 10:58:49 -050091String MetalCodeGenerator::typeName(const Type& type) {
Ethan Nicholase6592142020-09-08 10:22:09 -040092 switch (type.typeKind()) {
93 case Type::TypeKind::kVector:
Ethan Nicholas45fa8102020-01-13 10:58:49 -050094 return this->typeName(type.componentType()) + to_string(type.columns());
Ethan Nicholase6592142020-09-08 10:22:09 -040095 case Type::TypeKind::kMatrix:
Ethan Nicholas45fa8102020-01-13 10:58:49 -050096 return this->typeName(type.componentType()) + to_string(type.columns()) + "x" +
97 to_string(type.rows());
Ethan Nicholase6592142020-09-08 10:22:09 -040098 case Type::TypeKind::kSampler:
Ethan Nicholas45fa8102020-01-13 10:58:49 -050099 return "texture2d<float>"; // FIXME - support other texture types;
Ethan Nicholascc305772017-10-13 16:17:45 -0400100 default:
Timothy Liang43d225f2018-07-19 15:27:13 -0400101 if (type == *fContext.fHalf_Type) {
102 // FIXME - Currently only supporting floats in MSL to avoid type coercion issues.
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500103 return fContext.fFloat_Type->name();
Timothy Liang43d225f2018-07-19 15:27:13 -0400104 } else if (type == *fContext.fByte_Type) {
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500105 return "char";
Timothy Liang43d225f2018-07-19 15:27:13 -0400106 } else if (type == *fContext.fUByte_Type) {
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500107 return "uchar";
Timothy Liang7d637782018-06-05 09:58:07 -0400108 } else {
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500109 return type.name();
Timothy Liang7d637782018-06-05 09:58:07 -0400110 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400111 }
112}
113
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500114void MetalCodeGenerator::writeType(const Type& type) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400115 if (type.typeKind() == Type::TypeKind::kStruct) {
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500116 for (const Type* search : fWrittenStructs) {
117 if (*search == type) {
118 // already written
119 this->write(type.name());
120 return;
121 }
122 }
123 fWrittenStructs.push_back(&type);
124 this->writeLine("struct " + type.name() + " {");
125 fIndentation++;
126 this->writeFields(type.fields(), type.fOffset);
127 fIndentation--;
128 this->write("}");
129 } else {
130 this->write(this->typeName(type));
131 }
132}
133
Ethan Nicholascc305772017-10-13 16:17:45 -0400134void MetalCodeGenerator::writeExpression(const Expression& expr, Precedence parentPrecedence) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400135 switch (expr.kind()) {
136 case Expression::Kind::kBinary:
John Stiles81365af2020-08-18 09:24:00 -0400137 this->writeBinaryExpression(expr.as<BinaryExpression>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400138 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400139 case Expression::Kind::kBoolLiteral:
John Stiles81365af2020-08-18 09:24:00 -0400140 this->writeBoolLiteral(expr.as<BoolLiteral>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400141 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400142 case Expression::Kind::kConstructor:
John Stiles81365af2020-08-18 09:24:00 -0400143 this->writeConstructor(expr.as<Constructor>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400144 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400145 case Expression::Kind::kIntLiteral:
John Stiles81365af2020-08-18 09:24:00 -0400146 this->writeIntLiteral(expr.as<IntLiteral>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400147 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400148 case Expression::Kind::kFieldAccess:
John Stiles81365af2020-08-18 09:24:00 -0400149 this->writeFieldAccess(expr.as<FieldAccess>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400150 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400151 case Expression::Kind::kFloatLiteral:
John Stiles81365af2020-08-18 09:24:00 -0400152 this->writeFloatLiteral(expr.as<FloatLiteral>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400153 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400154 case Expression::Kind::kFunctionCall:
John Stiles81365af2020-08-18 09:24:00 -0400155 this->writeFunctionCall(expr.as<FunctionCall>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400156 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400157 case Expression::Kind::kPrefix:
John Stiles81365af2020-08-18 09:24:00 -0400158 this->writePrefixExpression(expr.as<PrefixExpression>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400159 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400160 case Expression::Kind::kPostfix:
John Stiles81365af2020-08-18 09:24:00 -0400161 this->writePostfixExpression(expr.as<PostfixExpression>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400162 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400163 case Expression::Kind::kSetting:
John Stiles81365af2020-08-18 09:24:00 -0400164 this->writeSetting(expr.as<Setting>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400165 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400166 case Expression::Kind::kSwizzle:
John Stiles81365af2020-08-18 09:24:00 -0400167 this->writeSwizzle(expr.as<Swizzle>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400168 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400169 case Expression::Kind::kVariableReference:
John Stiles81365af2020-08-18 09:24:00 -0400170 this->writeVariableReference(expr.as<VariableReference>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400171 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400172 case Expression::Kind::kTernary:
John Stiles81365af2020-08-18 09:24:00 -0400173 this->writeTernaryExpression(expr.as<TernaryExpression>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400174 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400175 case Expression::Kind::kIndex:
John Stiles81365af2020-08-18 09:24:00 -0400176 this->writeIndexExpression(expr.as<IndexExpression>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400177 break;
178 default:
Ethan Nicholas2a099da2020-01-02 14:40:54 -0500179#ifdef SK_DEBUG
Ethan Nicholascc305772017-10-13 16:17:45 -0400180 ABORT("unsupported expression: %s", expr.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -0500181#endif
182 break;
Ethan Nicholascc305772017-10-13 16:17:45 -0400183 }
184}
185
Timothy Liang6403b0e2018-05-17 10:40:04 -0400186void MetalCodeGenerator::writeIntrinsicCall(const FunctionCall& c) {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400187 auto i = fIntrinsicMap.find(c.function().name());
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400188 SkASSERT(i != fIntrinsicMap.end());
Timothy Liang7d637782018-06-05 09:58:07 -0400189 Intrinsic intrinsic = i->second;
190 int32_t intrinsicId = intrinsic.second;
191 switch (intrinsic.first) {
Timothy Liang6403b0e2018-05-17 10:40:04 -0400192 case kSpecial_IntrinsicKind:
193 return this->writeSpecialIntrinsic(c, (SpecialIntrinsic) intrinsicId);
Timothy Lianga06f2152018-05-24 15:33:31 -0400194 break;
195 case kMetal_IntrinsicKind:
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400196 this->writeExpression(*c.arguments()[0], kSequence_Precedence);
Timothy Lianga06f2152018-05-24 15:33:31 -0400197 switch ((MetalIntrinsic) intrinsicId) {
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500198 case kEqual_MetalIntrinsic:
199 this->write(" == ");
200 break;
201 case kNotEqual_MetalIntrinsic:
202 this->write(" != ");
203 break;
Timothy Lianga06f2152018-05-24 15:33:31 -0400204 case kLessThan_MetalIntrinsic:
205 this->write(" < ");
206 break;
207 case kLessThanEqual_MetalIntrinsic:
208 this->write(" <= ");
209 break;
210 case kGreaterThan_MetalIntrinsic:
211 this->write(" > ");
212 break;
213 case kGreaterThanEqual_MetalIntrinsic:
214 this->write(" >= ");
215 break;
216 default:
217 ABORT("unsupported metal intrinsic kind");
218 }
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400219 this->writeExpression(*c.arguments()[1], kSequence_Precedence);
Timothy Lianga06f2152018-05-24 15:33:31 -0400220 break;
Timothy Liang6403b0e2018-05-17 10:40:04 -0400221 default:
222 ABORT("unsupported intrinsic kind");
223 }
224}
225
Ethan Nicholascc305772017-10-13 16:17:45 -0400226void MetalCodeGenerator::writeFunctionCall(const FunctionCall& c) {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400227 const FunctionDeclaration& function = c.function();
John Stiles8e3b6be2020-10-13 11:14:08 -0400228 const ExpressionArray& arguments = c.arguments();
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400229 const auto& entry = fIntrinsicMap.find(function.name());
Timothy Liang6403b0e2018-05-17 10:40:04 -0400230 if (entry != fIntrinsicMap.end()) {
231 this->writeIntrinsicCall(c);
232 return;
233 }
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400234 const StringFragment& name = function.name();
Ethan Nicholased84b732020-10-08 11:45:44 -0400235 bool builtin = function.isBuiltin();
236 if (builtin && name == "atan" && arguments.size() == 2) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400237 this->write("atan2");
Ethan Nicholased84b732020-10-08 11:45:44 -0400238 } else if (builtin && name == "inversesqrt") {
Timothy Lianga06f2152018-05-24 15:33:31 -0400239 this->write("rsqrt");
Ethan Nicholased84b732020-10-08 11:45:44 -0400240 } else if (builtin && name == "inverse") {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400241 SkASSERT(arguments.size() == 1);
242 this->writeInverseHack(*arguments[0]);
John Stilesa80a3dc2020-10-20 10:24:56 -0400243 } else if (builtin && name == "frexp") {
244 // Our Metal codegen assumes that out params are pointers, but Metal's built-in frexp
245 // actually takes a reference for the exponent, not a pointer. We add in a helper function
246 // here to translate.
247 SkASSERT(arguments.size() == 2);
248 auto [iter, newlyCreated] = fHelpers.insert("frexp");
249 if (newlyCreated) {
250 fExtraFunctions.printf(
251 "float frexp(float arg, thread int* exp) { return frexp(arg, *exp); }\n");
252 }
253 this->write("frexp");
Ethan Nicholased84b732020-10-08 11:45:44 -0400254 } else if (builtin && name == "dFdx") {
Timothy Liang7d637782018-06-05 09:58:07 -0400255 this->write("dfdx");
Ethan Nicholased84b732020-10-08 11:45:44 -0400256 } else if (builtin && name == "dFdy") {
Chris Daltonb8af5ad2019-02-25 14:54:21 -0700257 // Flipping Y also negates the Y derivatives.
258 this->write((fProgram.fSettings.fFlipY) ? "-dfdy" : "dfdy");
Ethan Nicholascc305772017-10-13 16:17:45 -0400259 } else {
Ethan Nicholase2c49992020-10-05 11:49:11 -0400260 this->writeName(name);
Ethan Nicholascc305772017-10-13 16:17:45 -0400261 }
262 this->write("(");
263 const char* separator = "";
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400264 if (this->requirements(function) & kInputs_Requirement) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400265 this->write("_in");
266 separator = ", ";
267 }
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400268 if (this->requirements(function) & kOutputs_Requirement) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400269 this->write(separator);
270 this->write("_out");
271 separator = ", ";
272 }
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400273 if (this->requirements(function) & kUniforms_Requirement) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400274 this->write(separator);
275 this->write("_uniforms");
276 separator = ", ";
277 }
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400278 if (this->requirements(function) & kGlobals_Requirement) {
Timothy Liangee84fe12018-05-18 14:38:19 -0400279 this->write(separator);
280 this->write("_globals");
281 separator = ", ";
282 }
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400283 if (this->requirements(function) & kFragCoord_Requirement) {
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -0400284 this->write(separator);
285 this->write("_fragCoord");
286 separator = ", ";
287 }
Brian Osman5bf3e202020-10-13 10:34:18 -0400288 const std::vector<const Variable*>& parameters = function.parameters();
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400289 for (size_t i = 0; i < arguments.size(); ++i) {
290 const Expression& arg = *arguments[i];
Ethan Nicholascc305772017-10-13 16:17:45 -0400291 this->write(separator);
292 separator = ", ";
Ethan Nicholased84b732020-10-08 11:45:44 -0400293 if (parameters[i]->modifiers().fFlags & Modifiers::kOut_Flag) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400294 this->write("&");
295 }
296 this->writeExpression(arg, kSequence_Precedence);
297 }
298 this->write(")");
299}
300
Chris Daltondba7aab2018-11-15 10:57:49 -0500301void MetalCodeGenerator::writeInverseHack(const Expression& mat) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400302 const Type& type = mat.type();
303 const String& typeName = type.name();
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500304 String name = typeName + "_inverse";
Ethan Nicholas30d30222020-09-11 12:27:26 -0400305 if (type == *fContext.fFloat2x2_Type || type == *fContext.fHalf2x2_Type) {
Chris Daltondba7aab2018-11-15 10:57:49 -0500306 if (fWrittenIntrinsics.find(name) == fWrittenIntrinsics.end()) {
307 fWrittenIntrinsics.insert(name);
308 fExtraFunctions.writeText((
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500309 typeName + " " + name + "(" + typeName + " m) {"
Chris Daltondba7aab2018-11-15 10:57:49 -0500310 " return float2x2(m[1][1], -m[0][1], -m[1][0], m[0][0]) * (1/determinant(m));"
311 "}"
312 ).c_str());
313 }
314 }
Ethan Nicholas30d30222020-09-11 12:27:26 -0400315 else if (type == *fContext.fFloat3x3_Type || type == *fContext.fHalf3x3_Type) {
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500316 if (fWrittenIntrinsics.find(name) == fWrittenIntrinsics.end()) {
317 fWrittenIntrinsics.insert(name);
318 fExtraFunctions.writeText((
319 typeName + " " + name + "(" + typeName + " m) {"
320 " float a00 = m[0][0], a01 = m[0][1], a02 = m[0][2];"
321 " float a10 = m[1][0], a11 = m[1][1], a12 = m[1][2];"
322 " float a20 = m[2][0], a21 = m[2][1], a22 = m[2][2];"
323 " float b01 = a22 * a11 - a12 * a21;"
324 " float b11 = -a22 * a10 + a12 * a20;"
325 " float b21 = a21 * a10 - a11 * a20;"
326 " float det = a00 * b01 + a01 * b11 + a02 * b21;"
327 " return " + typeName +
328 " (b01, (-a22 * a01 + a02 * a21), (a12 * a01 - a02 * a11),"
329 " b11, (a22 * a00 - a02 * a20), (-a12 * a00 + a02 * a10),"
330 " b21, (-a21 * a00 + a01 * a20), (a11 * a00 - a01 * a10)) * "
331 " (1/det);"
332 "}"
333 ).c_str());
334 }
335 }
Ethan Nicholas30d30222020-09-11 12:27:26 -0400336 else if (type == *fContext.fFloat4x4_Type || type == *fContext.fHalf4x4_Type) {
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500337 if (fWrittenIntrinsics.find(name) == fWrittenIntrinsics.end()) {
338 fWrittenIntrinsics.insert(name);
339 fExtraFunctions.writeText((
340 typeName + " " + name + "(" + typeName + " m) {"
341 " float a00 = m[0][0], a01 = m[0][1], a02 = m[0][2], a03 = m[0][3];"
342 " float a10 = m[1][0], a11 = m[1][1], a12 = m[1][2], a13 = m[1][3];"
343 " float a20 = m[2][0], a21 = m[2][1], a22 = m[2][2], a23 = m[2][3];"
344 " float a30 = m[3][0], a31 = m[3][1], a32 = m[3][2], a33 = m[3][3];"
345 " float b00 = a00 * a11 - a01 * a10;"
346 " float b01 = a00 * a12 - a02 * a10;"
347 " float b02 = a00 * a13 - a03 * a10;"
348 " float b03 = a01 * a12 - a02 * a11;"
349 " float b04 = a01 * a13 - a03 * a11;"
350 " float b05 = a02 * a13 - a03 * a12;"
351 " float b06 = a20 * a31 - a21 * a30;"
352 " float b07 = a20 * a32 - a22 * a30;"
353 " float b08 = a20 * a33 - a23 * a30;"
354 " float b09 = a21 * a32 - a22 * a31;"
355 " float b10 = a21 * a33 - a23 * a31;"
356 " float b11 = a22 * a33 - a23 * a32;"
357 " float det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - "
358 " b04 * b07 + b05 * b06;"
359 " return " + typeName + "(a11 * b11 - a12 * b10 + a13 * b09,"
360 " a02 * b10 - a01 * b11 - a03 * b09,"
361 " a31 * b05 - a32 * b04 + a33 * b03,"
362 " a22 * b04 - a21 * b05 - a23 * b03,"
363 " a12 * b08 - a10 * b11 - a13 * b07,"
364 " a00 * b11 - a02 * b08 + a03 * b07,"
365 " a32 * b02 - a30 * b05 - a33 * b01,"
366 " a20 * b05 - a22 * b02 + a23 * b01,"
367 " a10 * b10 - a11 * b08 + a13 * b06,"
368 " a01 * b08 - a00 * b10 - a03 * b06,"
369 " a30 * b04 - a31 * b02 + a33 * b00,"
370 " a21 * b02 - a20 * b04 - a23 * b00,"
371 " a11 * b07 - a10 * b09 - a12 * b06,"
372 " a00 * b09 - a01 * b07 + a02 * b06,"
373 " a31 * b01 - a30 * b03 - a32 * b00,"
374 " a20 * b03 - a21 * b01 + a22 * b00) / det;"
375 "}"
376 ).c_str());
377 }
378 }
Chris Daltondba7aab2018-11-15 10:57:49 -0500379 this->write(name);
380}
381
Timothy Liang6403b0e2018-05-17 10:40:04 -0400382void MetalCodeGenerator::writeSpecialIntrinsic(const FunctionCall & c, SpecialIntrinsic kind) {
John Stiles8e3b6be2020-10-13 11:14:08 -0400383 const ExpressionArray& arguments = c.arguments();
Timothy Liang6403b0e2018-05-17 10:40:04 -0400384 switch (kind) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400385 case kTexture_SpecialIntrinsic: {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400386 this->writeExpression(*arguments[0], kSequence_Precedence);
Timothy Lianga06f2152018-05-24 15:33:31 -0400387 this->write(".sample(");
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400388 this->writeExpression(*arguments[0], kSequence_Precedence);
Timothy Lianga06f2152018-05-24 15:33:31 -0400389 this->write(SAMPLER_SUFFIX);
390 this->write(", ");
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400391 const Type& arg1Type = arguments[1]->type();
Ethan Nicholas30d30222020-09-11 12:27:26 -0400392 if (arg1Type == *fContext.fFloat3_Type) {
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500393 // have to store the vector in a temp variable to avoid double evaluating it
394 String tmpVar = "tmpCoord" + to_string(fVarCount++);
Ethan Nicholas30d30222020-09-11 12:27:26 -0400395 this->fFunctionHeader += " " + this->typeName(arg1Type) + " " + tmpVar + ";\n";
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500396 this->write("(" + tmpVar + " = ");
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400397 this->writeExpression(*arguments[1], kSequence_Precedence);
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500398 this->write(", " + tmpVar + ".xy / " + tmpVar + ".z))");
Timothy Liangee84fe12018-05-18 14:38:19 -0400399 } else {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400400 SkASSERT(arg1Type == *fContext.fFloat2_Type);
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400401 this->writeExpression(*arguments[1], kSequence_Precedence);
Timothy Liangee84fe12018-05-18 14:38:19 -0400402 this->write(")");
403 }
Timothy Liang6403b0e2018-05-17 10:40:04 -0400404 break;
Ethan Nicholas30d30222020-09-11 12:27:26 -0400405 }
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500406 case kMod_SpecialIntrinsic: {
Timothy Liang651286f2018-06-07 09:55:33 -0400407 // 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 -0500408 String tmpX = "tmpX" + to_string(fVarCount++);
409 String tmpY = "tmpY" + to_string(fVarCount++);
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400410 this->fFunctionHeader += " " + this->typeName(arguments[0]->type()) +
Ethan Nicholas30d30222020-09-11 12:27:26 -0400411 " " + tmpX + ", " + tmpY + ";\n";
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500412 this->write("(" + tmpX + " = ");
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400413 this->writeExpression(*arguments[0], kSequence_Precedence);
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500414 this->write(", " + tmpY + " = ");
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400415 this->writeExpression(*arguments[1], kSequence_Precedence);
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500416 this->write(", " + tmpX + " - " + tmpY + " * floor(" + tmpX + " / " + tmpY + "))");
Timothy Liang651286f2018-06-07 09:55:33 -0400417 break;
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500418 }
Brian Osman46787d52020-11-24 14:18:23 -0500419 // GLSL declares scalar versions of most geometric intrinsics, but these don't exist in MSL
420 case kDistance_SpecialIntrinsic: {
421 if (arguments[0]->type().columns() == 1) {
422 this->write("abs(");
423 this->writeExpression(*arguments[0], kAdditive_Precedence);
424 this->write(" - ");
425 this->writeExpression(*arguments[1], kAdditive_Precedence);
426 this->write(")");
427 } else {
428 this->write("distance(");
429 this->writeExpression(*arguments[0], kSequence_Precedence);
430 this->write(", ");
431 this->writeExpression(*arguments[1], kSequence_Precedence);
432 this->write(")");
433 }
434 break;
435 }
436 case kDot_SpecialIntrinsic: {
437 if (arguments[0]->type().columns() == 1) {
438 this->write("(");
439 this->writeExpression(*arguments[0], kMultiplicative_Precedence);
440 this->write(" * ");
441 this->writeExpression(*arguments[1], kMultiplicative_Precedence);
442 this->write(")");
443 } else {
444 this->write("dot(");
445 this->writeExpression(*arguments[0], kSequence_Precedence);
446 this->write(", ");
447 this->writeExpression(*arguments[1], kSequence_Precedence);
448 this->write(")");
449 }
450 break;
451 }
452 case kLength_SpecialIntrinsic: {
453 this->write(arguments[0]->type().columns() == 1 ? "abs(" : "length(");
454 this->writeExpression(*arguments[0], kSequence_Precedence);
455 this->write(")");
456 break;
457 }
458 case kNormalize_SpecialIntrinsic: {
459 this->write(arguments[0]->type().columns() == 1 ? "sign(" : "normalize(");
460 this->writeExpression(*arguments[0], kSequence_Precedence);
461 this->write(")");
462 break;
463 }
Timothy Liang6403b0e2018-05-17 10:40:04 -0400464 default:
465 ABORT("unsupported special intrinsic kind");
466 }
467}
468
John Stilesfcf8cb22020-08-06 14:29:22 -0400469// Assembles a matrix of type floatRxC by resizing another matrix named `x0`.
470// Cells that don't exist in the source matrix will be populated with identity-matrix values.
471void MetalCodeGenerator::assembleMatrixFromMatrix(const Type& sourceMatrix, int rows, int columns) {
472 SkASSERT(rows <= 4);
473 SkASSERT(columns <= 4);
474
475 const char* columnSeparator = "";
476 for (int c = 0; c < columns; ++c) {
477 fExtraFunctions.printf("%sfloat%d(", columnSeparator, rows);
478 columnSeparator = "), ";
479
480 // Determine how many values to take from the source matrix for this row.
481 int swizzleLength = 0;
482 if (c < sourceMatrix.columns()) {
483 swizzleLength = std::min<>(rows, sourceMatrix.rows());
484 }
485
486 // Emit all the values from the source matrix row.
487 bool firstItem;
488 switch (swizzleLength) {
489 case 0: firstItem = true; break;
490 case 1: firstItem = false; fExtraFunctions.printf("x0[%d].x", c); break;
491 case 2: firstItem = false; fExtraFunctions.printf("x0[%d].xy", c); break;
492 case 3: firstItem = false; fExtraFunctions.printf("x0[%d].xyz", c); break;
493 case 4: firstItem = false; fExtraFunctions.printf("x0[%d].xyzw", c); break;
494 default: SkUNREACHABLE;
495 }
496
497 // Emit the placeholder identity-matrix cells.
498 for (int r = swizzleLength; r < rows; ++r) {
499 fExtraFunctions.printf("%s%s", firstItem ? "" : ", ", (r == c) ? "1.0" : "0.0");
500 firstItem = false;
501 }
502 }
503
504 fExtraFunctions.writeText(")");
505}
506
507// Assembles a matrix of type floatRxC by concatenating an arbitrary mix of values, named `x0`,
508// `x1`, etc. An error is written if the expression list don't contain exactly R*C scalars.
John Stiles8e3b6be2020-10-13 11:14:08 -0400509void MetalCodeGenerator::assembleMatrixFromExpressions(const ExpressionArray& args,
510 int rows, int columns) {
John Stilesfcf8cb22020-08-06 14:29:22 -0400511 size_t argIndex = 0;
512 int argPosition = 0;
513
514 const char* columnSeparator = "";
515 for (int c = 0; c < columns; ++c) {
516 fExtraFunctions.printf("%sfloat%d(", columnSeparator, rows);
517 columnSeparator = "), ";
518
519 const char* rowSeparator = "";
520 for (int r = 0; r < rows; ++r) {
521 fExtraFunctions.writeText(rowSeparator);
522 rowSeparator = ", ";
523
524 if (argIndex < args.size()) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400525 const Type& argType = args[argIndex]->type();
Ethan Nicholase6592142020-09-08 10:22:09 -0400526 switch (argType.typeKind()) {
527 case Type::TypeKind::kScalar: {
John Stilesfcf8cb22020-08-06 14:29:22 -0400528 fExtraFunctions.printf("x%zu", argIndex);
529 break;
530 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400531 case Type::TypeKind::kVector: {
John Stilesfcf8cb22020-08-06 14:29:22 -0400532 fExtraFunctions.printf("x%zu[%d]", argIndex, argPosition);
533 break;
534 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400535 case Type::TypeKind::kMatrix: {
John Stilesfcf8cb22020-08-06 14:29:22 -0400536 fExtraFunctions.printf("x%zu[%d][%d]", argIndex,
537 argPosition / argType.rows(),
538 argPosition % argType.rows());
539 break;
540 }
541 default: {
542 SkDEBUGFAIL("incorrect type of argument for matrix constructor");
543 fExtraFunctions.writeText("<error>");
544 break;
545 }
546 }
547
548 ++argPosition;
549 if (argPosition >= argType.columns() * argType.rows()) {
550 ++argIndex;
551 argPosition = 0;
552 }
553 } else {
554 SkDEBUGFAIL("not enough arguments for matrix constructor");
555 fExtraFunctions.writeText("<error>");
556 }
557 }
558 }
559
560 if (argPosition != 0 || argIndex != args.size()) {
561 SkDEBUGFAIL("incorrect number of arguments for matrix constructor");
562 fExtraFunctions.writeText(", <error>");
563 }
564
565 fExtraFunctions.writeText(")");
566}
567
John Stiles1bdafbf2020-05-28 12:17:20 -0400568// Generates a constructor for 'matrix' which reorganizes the input arguments into the proper shape.
569// Keeps track of previously generated constructors so that we won't generate more than one
570// constructor for any given permutation of input argument types. Returns the name of the
571// generated constructor method.
572String MetalCodeGenerator::getMatrixConstructHelper(const Constructor& c) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400573 const Type& matrix = c.type();
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500574 int columns = matrix.columns();
575 int rows = matrix.rows();
John Stiles8e3b6be2020-10-13 11:14:08 -0400576 const ExpressionArray& args = c.arguments();
John Stiles1bdafbf2020-05-28 12:17:20 -0400577
578 // Create the helper-method name and use it as our lookup key.
579 String name;
580 name.appendf("float%dx%d_from", columns, rows);
581 for (const std::unique_ptr<Expression>& expr : args) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400582 name.appendf("_%s", expr->type().displayName().c_str());
John Stiles1bdafbf2020-05-28 12:17:20 -0400583 }
584
585 // If a helper-method has already been synthesized, we don't need to synthesize it again.
586 auto [iter, newlyCreated] = fHelpers.insert(name);
587 if (!newlyCreated) {
588 return name;
589 }
590
591 // Unlike GLSL, Metal requires that matrices are initialized with exactly R vectors of C
592 // components apiece. (In Metal 2.0, you can also supply R*C scalars, but you still cannot
593 // supply a mixture of scalars and vectors.)
594 fExtraFunctions.printf("float%dx%d %s(", columns, rows, name.c_str());
595
596 size_t argIndex = 0;
597 const char* argSeparator = "";
John Stilesfcf8cb22020-08-06 14:29:22 -0400598 for (const std::unique_ptr<Expression>& expr : args) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400599 fExtraFunctions.printf("%s%s x%zu", argSeparator,
Ethan Nicholas30d30222020-09-11 12:27:26 -0400600 expr->type().displayName().c_str(), argIndex++);
John Stiles1bdafbf2020-05-28 12:17:20 -0400601 argSeparator = ", ";
602 }
603
604 fExtraFunctions.printf(") {\n return float%dx%d(", columns, rows);
605
John Stiles9aeed132020-11-24 17:36:06 -0500606 if (args.size() == 1 && args.front()->type().isMatrix()) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400607 this->assembleMatrixFromMatrix(args.front()->type(), rows, columns);
John Stilesfcf8cb22020-08-06 14:29:22 -0400608 } else {
609 this->assembleMatrixFromExpressions(args, rows, columns);
John Stiles1bdafbf2020-05-28 12:17:20 -0400610 }
611
John Stilesfcf8cb22020-08-06 14:29:22 -0400612 fExtraFunctions.writeText(");\n}\n");
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500613 return name;
614}
615
616bool MetalCodeGenerator::canCoerce(const Type& t1, const Type& t2) {
617 if (t1.columns() != t2.columns() || t1.rows() != t2.rows()) {
618 return false;
619 }
620 if (t1.columns() > 1) {
621 return this->canCoerce(t1.componentType(), t2.componentType());
622 }
Ethan Nicholase1f55022019-02-05 17:17:40 -0500623 return t1.isFloat() && t2.isFloat();
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500624}
625
John Stiles1bdafbf2020-05-28 12:17:20 -0400626bool MetalCodeGenerator::matrixConstructHelperIsNeeded(const Constructor& c) {
627 // A matrix construct helper is only necessary if we are, in fact, constructing a matrix.
John Stiles9aeed132020-11-24 17:36:06 -0500628 if (!c.type().isMatrix()) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400629 return false;
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500630 }
John Stiles1bdafbf2020-05-28 12:17:20 -0400631
632 // GLSL is fairly free-form about inputs to its matrix constructors, but Metal is not; it
633 // expects exactly R vectors of C components apiece. (Metal 2.0 also allows a list of R*C
634 // scalars.) Some cases are simple to translate and so we handle those inline--e.g. a list of
635 // scalars can be constructed trivially. In more complex cases, we generate a helper function
636 // that converts our inputs into a properly-shaped matrix.
637 // A matrix construct helper method is always used if any input argument is a matrix.
638 // Helper methods are also necessary when any argument would span multiple rows. For instance:
639 //
640 // float2 x = (1, 2);
641 // float3x2(x, 3, 4, 5, 6) = | 1 3 5 | = no helper needed; conversion can be done inline
642 // | 2 4 6 |
643 //
644 // float2 x = (2, 3);
645 // float3x2(1, x, 4, 5, 6) = | 1 3 5 | = x spans multiple rows; a helper method will be used
646 // | 2 4 6 |
647 //
648 // float4 x = (1, 2, 3, 4);
649 // float2x2(x) = | 1 3 | = x spans multiple rows; a helper method will be used
650 // | 2 4 |
651 //
652
653 int position = 0;
Ethan Nicholasf70f0442020-09-29 12:41:35 -0400654 for (const std::unique_ptr<Expression>& expr : c.arguments()) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400655 // If an input argument is a matrix, we need a helper function.
John Stiles9aeed132020-11-24 17:36:06 -0500656 if (expr->type().isMatrix()) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400657 return true;
658 }
Ethan Nicholas30d30222020-09-11 12:27:26 -0400659 position += expr->type().columns();
660 if (position > c.type().rows()) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400661 // An input argument would span multiple rows; a helper function is required.
662 return true;
663 }
Ethan Nicholas30d30222020-09-11 12:27:26 -0400664 if (position == c.type().rows()) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400665 // We've advanced to the end of a row. Wrap to the start of the next row.
666 position = 0;
667 }
668 }
669
670 return false;
671}
672
673void MetalCodeGenerator::writeConstructor(const Constructor& c, Precedence parentPrecedence) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400674 const Type& constructorType = c.type();
John Stiles1bdafbf2020-05-28 12:17:20 -0400675 // Handle special cases for single-argument constructors.
Ethan Nicholasf70f0442020-09-29 12:41:35 -0400676 if (c.arguments().size() == 1) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400677 // If the type is coercible, emit it directly.
Ethan Nicholasf70f0442020-09-29 12:41:35 -0400678 const Expression& arg = *c.arguments().front();
Ethan Nicholas30d30222020-09-11 12:27:26 -0400679 const Type& argType = arg.type();
680 if (this->canCoerce(constructorType, argType)) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400681 this->writeExpression(arg, parentPrecedence);
682 return;
683 }
684
685 // Metal supports creating matrices with a scalar on the diagonal via the single-argument
686 // matrix constructor.
John Stiles9aeed132020-11-24 17:36:06 -0500687 if (constructorType.isMatrix() && argType.isNumber()) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400688 const Type& matrix = constructorType;
John Stiles1bdafbf2020-05-28 12:17:20 -0400689 this->write("float");
690 this->write(to_string(matrix.columns()));
691 this->write("x");
692 this->write(to_string(matrix.rows()));
693 this->write("(");
694 this->writeExpression(arg, parentPrecedence);
695 this->write(")");
696 return;
697 }
698 }
699
700 // Emit and invoke a matrix-constructor helper method if one is necessary.
701 if (this->matrixConstructHelperIsNeeded(c)) {
702 this->write(this->getMatrixConstructHelper(c));
John Stiles1fa15b12020-05-28 17:36:54 +0000703 this->write("(");
704 const char* separator = "";
Ethan Nicholasf70f0442020-09-29 12:41:35 -0400705 for (const std::unique_ptr<Expression>& expr : c.arguments()) {
John Stiles1fa15b12020-05-28 17:36:54 +0000706 this->write(separator);
707 separator = ", ";
John Stiles1bdafbf2020-05-28 12:17:20 -0400708 this->writeExpression(*expr, kSequence_Precedence);
John Stilesdaa573e2020-05-28 12:17:20 -0400709 }
John Stiles1fa15b12020-05-28 17:36:54 +0000710 this->write(")");
John Stiles1bdafbf2020-05-28 12:17:20 -0400711 return;
John Stilesdaa573e2020-05-28 12:17:20 -0400712 }
John Stiles1bdafbf2020-05-28 12:17:20 -0400713
714 // Explicitly invoke the constructor, passing in the necessary arguments.
Ethan Nicholas30d30222020-09-11 12:27:26 -0400715 this->writeType(constructorType);
John Stiles1bdafbf2020-05-28 12:17:20 -0400716 this->write("(");
717 const char* separator = "";
718 int scalarCount = 0;
Ethan Nicholasf70f0442020-09-29 12:41:35 -0400719 for (const std::unique_ptr<Expression>& arg : c.arguments()) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400720 const Type& argType = arg->type();
John Stiles1bdafbf2020-05-28 12:17:20 -0400721 this->write(separator);
722 separator = ", ";
John Stiles9aeed132020-11-24 17:36:06 -0500723 if (constructorType.isMatrix() &&
Ethan Nicholas30d30222020-09-11 12:27:26 -0400724 argType.columns() < constructorType.rows()) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400725 // Merge scalars and smaller vectors together.
726 if (!scalarCount) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400727 this->writeType(constructorType.componentType());
728 this->write(to_string(constructorType.rows()));
John Stiles1bdafbf2020-05-28 12:17:20 -0400729 this->write("(");
730 }
Ethan Nicholas30d30222020-09-11 12:27:26 -0400731 scalarCount += argType.columns();
John Stiles1bdafbf2020-05-28 12:17:20 -0400732 }
733 this->writeExpression(*arg, kSequence_Precedence);
Ethan Nicholas30d30222020-09-11 12:27:26 -0400734 if (scalarCount && scalarCount == constructorType.rows()) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400735 this->write(")");
736 scalarCount = 0;
737 }
738 }
739 this->write(")");
Ethan Nicholascc305772017-10-13 16:17:45 -0400740}
741
742void MetalCodeGenerator::writeFragCoord() {
Ethan Nicholasf931e402019-07-26 15:40:33 -0400743 if (fRTHeightName.length()) {
744 this->write("float4(_fragCoord.x, ");
745 this->write(fRTHeightName.c_str());
746 this->write(" - _fragCoord.y, 0.0, _fragCoord.w)");
Jim Van Verth6bc650e2019-02-07 14:53:23 -0500747 } else {
748 this->write("float4(_fragCoord.x, _fragCoord.y, 0.0, _fragCoord.w)");
749 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400750}
751
752void MetalCodeGenerator::writeVariableReference(const VariableReference& ref) {
Ethan Nicholas78686922020-10-08 06:46:27 -0400753 switch (ref.variable()->modifiers().fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400754 case SK_FRAGCOLOR_BUILTIN:
Timothy Liang7d637782018-06-05 09:58:07 -0400755 this->write("_out->sk_FragColor");
Ethan Nicholascc305772017-10-13 16:17:45 -0400756 break;
Timothy Liang6403b0e2018-05-17 10:40:04 -0400757 case SK_FRAGCOORD_BUILTIN:
758 this->writeFragCoord();
759 break;
Timothy Liangdc89f192018-06-13 09:20:31 -0400760 case SK_VERTEXID_BUILTIN:
761 this->write("sk_VertexID");
762 break;
763 case SK_INSTANCEID_BUILTIN:
764 this->write("sk_InstanceID");
765 break;
Timothy Liang7b8875d2018-08-10 09:42:31 -0400766 case SK_CLOCKWISE_BUILTIN:
767 // We'd set the front facing winding in the MTLRenderCommandEncoder to be counter
Brian Salomonf4ba4ec2020-03-19 15:54:28 -0400768 // clockwise to match Skia convention.
Timothy Liang7b8875d2018-08-10 09:42:31 -0400769 this->write(fProgram.fSettings.fFlipY ? "_frontFacing" : "(!_frontFacing)");
770 break;
Ethan Nicholascc305772017-10-13 16:17:45 -0400771 default:
Ethan Nicholas78686922020-10-08 06:46:27 -0400772 const Variable& var = *ref.variable();
Ethan Nicholas453f67f2020-10-09 10:43:45 -0400773 if (var.storage() == Variable::Storage::kGlobal) {
Ethan Nicholas78686922020-10-08 06:46:27 -0400774 if (var.modifiers().fFlags & Modifiers::kIn_Flag) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400775 this->write("_in.");
Ethan Nicholas78686922020-10-08 06:46:27 -0400776 } else if (var.modifiers().fFlags & Modifiers::kOut_Flag) {
Timothy Liangee84fe12018-05-18 14:38:19 -0400777 this->write("_out->");
Ethan Nicholas78686922020-10-08 06:46:27 -0400778 } else if (var.modifiers().fFlags & Modifiers::kUniform_Flag &&
779 var.type().typeKind() != Type::TypeKind::kSampler) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400780 this->write("_uniforms.");
781 } else {
Timothy Liangee84fe12018-05-18 14:38:19 -0400782 this->write("_globals->");
Ethan Nicholascc305772017-10-13 16:17:45 -0400783 }
784 }
Ethan Nicholas78686922020-10-08 06:46:27 -0400785 this->writeName(var.name());
Ethan Nicholascc305772017-10-13 16:17:45 -0400786 }
787}
788
789void MetalCodeGenerator::writeIndexExpression(const IndexExpression& expr) {
Ethan Nicholas2a4952d2020-10-08 15:35:56 -0400790 this->writeExpression(*expr.base(), kPostfix_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400791 this->write("[");
Ethan Nicholas2a4952d2020-10-08 15:35:56 -0400792 this->writeExpression(*expr.index(), kTopLevel_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400793 this->write("]");
794}
795
796void MetalCodeGenerator::writeFieldAccess(const FieldAccess& f) {
Ethan Nicholas7a95b202020-10-09 11:55:40 -0400797 const Type::Field* field = &f.base()->type().fields()[f.fieldIndex()];
798 if (FieldAccess::OwnerKind::kDefault == f.ownerKind()) {
799 this->writeExpression(*f.base(), kPostfix_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400800 this->write(".");
801 }
Timothy Liang7d637782018-06-05 09:58:07 -0400802 switch (field->fModifiers.fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400803 case SK_POSITION_BUILTIN:
Timothy Liangb8eeb802018-07-23 16:46:16 -0400804 this->write("_out->sk_Position");
Ethan Nicholascc305772017-10-13 16:17:45 -0400805 break;
806 default:
Timothy Liang7d637782018-06-05 09:58:07 -0400807 if (field->fName == "sk_PointSize") {
808 this->write("_out->sk_PointSize");
809 } else {
Ethan Nicholas7a95b202020-10-09 11:55:40 -0400810 if (FieldAccess::OwnerKind::kAnonymousInterfaceBlock == f.ownerKind()) {
Timothy Liang7d637782018-06-05 09:58:07 -0400811 this->write("_globals->");
812 this->write(fInterfaceBlockNameMap[fInterfaceBlockMap[field]]);
813 this->write("->");
814 }
Timothy Liang651286f2018-06-07 09:55:33 -0400815 this->writeName(field->fName);
Timothy Lianga06f2152018-05-24 15:33:31 -0400816 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400817 }
818}
819
820void MetalCodeGenerator::writeSwizzle(const Swizzle& swizzle) {
Ethan Nicholas6b4d5812020-10-12 16:11:51 -0400821 this->writeExpression(*swizzle.base(), kPostfix_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400822 this->write(".");
Ethan Nicholas6b4d5812020-10-12 16:11:51 -0400823 for (int c : swizzle.components()) {
Brian Osman25647672020-09-15 15:16:56 -0400824 SkASSERT(c >= 0 && c <= 3);
825 this->write(&("x\0y\0z\0w\0"[c * 2]));
Ethan Nicholascc305772017-10-13 16:17:45 -0400826 }
827}
828
829MetalCodeGenerator::Precedence MetalCodeGenerator::GetBinaryPrecedence(Token::Kind op) {
830 switch (op) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400831 case Token::Kind::TK_STAR: // fall through
832 case Token::Kind::TK_SLASH: // fall through
833 case Token::Kind::TK_PERCENT: return MetalCodeGenerator::kMultiplicative_Precedence;
834 case Token::Kind::TK_PLUS: // fall through
835 case Token::Kind::TK_MINUS: return MetalCodeGenerator::kAdditive_Precedence;
836 case Token::Kind::TK_SHL: // fall through
837 case Token::Kind::TK_SHR: return MetalCodeGenerator::kShift_Precedence;
838 case Token::Kind::TK_LT: // fall through
839 case Token::Kind::TK_GT: // fall through
840 case Token::Kind::TK_LTEQ: // fall through
841 case Token::Kind::TK_GTEQ: return MetalCodeGenerator::kRelational_Precedence;
842 case Token::Kind::TK_EQEQ: // fall through
843 case Token::Kind::TK_NEQ: return MetalCodeGenerator::kEquality_Precedence;
844 case Token::Kind::TK_BITWISEAND: return MetalCodeGenerator::kBitwiseAnd_Precedence;
845 case Token::Kind::TK_BITWISEXOR: return MetalCodeGenerator::kBitwiseXor_Precedence;
846 case Token::Kind::TK_BITWISEOR: return MetalCodeGenerator::kBitwiseOr_Precedence;
847 case Token::Kind::TK_LOGICALAND: return MetalCodeGenerator::kLogicalAnd_Precedence;
848 case Token::Kind::TK_LOGICALXOR: return MetalCodeGenerator::kLogicalXor_Precedence;
849 case Token::Kind::TK_LOGICALOR: return MetalCodeGenerator::kLogicalOr_Precedence;
850 case Token::Kind::TK_EQ: // fall through
851 case Token::Kind::TK_PLUSEQ: // fall through
852 case Token::Kind::TK_MINUSEQ: // fall through
853 case Token::Kind::TK_STAREQ: // fall through
854 case Token::Kind::TK_SLASHEQ: // fall through
855 case Token::Kind::TK_PERCENTEQ: // fall through
856 case Token::Kind::TK_SHLEQ: // fall through
857 case Token::Kind::TK_SHREQ: // fall through
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400858 case Token::Kind::TK_BITWISEANDEQ: // fall through
859 case Token::Kind::TK_BITWISEXOREQ: // fall through
860 case Token::Kind::TK_BITWISEOREQ: return MetalCodeGenerator::kAssignment_Precedence;
861 case Token::Kind::TK_COMMA: return MetalCodeGenerator::kSequence_Precedence;
Ethan Nicholascc305772017-10-13 16:17:45 -0400862 default: ABORT("unsupported binary operator");
863 }
864}
865
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500866void MetalCodeGenerator::writeMatrixTimesEqualHelper(const Type& left, const Type& right,
867 const Type& result) {
868 String key = "TimesEqual" + left.name() + right.name();
869 if (fHelpers.find(key) == fHelpers.end()) {
870 fExtraFunctions.printf("%s operator*=(thread %s& left, thread const %s& right) {\n"
871 " left = left * right;\n"
872 " return left;\n"
Ethan Nicholase2c49992020-10-05 11:49:11 -0400873 "}", String(result.name()).c_str(), String(left.name()).c_str(),
874 String(right.name()).c_str());
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500875 }
876}
877
Ethan Nicholascc305772017-10-13 16:17:45 -0400878void MetalCodeGenerator::writeBinaryExpression(const BinaryExpression& b,
879 Precedence parentPrecedence) {
John Stiles2d4f9592020-10-30 10:29:12 -0400880 const Expression& left = *b.left();
881 const Expression& right = *b.right();
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400882 const Type& leftType = left.type();
883 const Type& rightType = right.type();
884 Token::Kind op = b.getOperator();
885 Precedence precedence = GetBinaryPrecedence(b.getOperator());
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500886 bool needParens = precedence >= parentPrecedence;
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400887 switch (op) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400888 case Token::Kind::TK_EQEQ:
John Stiles9aeed132020-11-24 17:36:06 -0500889 if (leftType.isVector()) {
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500890 this->write("all");
891 needParens = true;
892 }
893 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400894 case Token::Kind::TK_NEQ:
John Stiles9aeed132020-11-24 17:36:06 -0500895 if (leftType.isVector()) {
Jim Van Verth36477b42019-04-11 14:57:30 -0400896 this->write("any");
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500897 needParens = true;
898 }
899 break;
900 default:
901 break;
902 }
903 if (needParens) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400904 this->write("(");
905 }
Brian Osman79457ef2020-09-24 15:01:27 -0400906 if (Compiler::IsAssignment(op) && left.is<VariableReference>() &&
Ethan Nicholas453f67f2020-10-09 10:43:45 -0400907 left.as<VariableReference>().variable()->storage() == Variable::Storage::kParameter &&
Ethan Nicholas78686922020-10-08 06:46:27 -0400908 left.as<VariableReference>().variable()->modifiers().fFlags & Modifiers::kOut_Flag) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400909 // writing to an out parameter. Since we have to turn those into pointers, we have to
910 // dereference it here.
911 this->write("*");
912 }
John Stiles9aeed132020-11-24 17:36:06 -0500913 if (op == Token::Kind::TK_STAREQ && leftType.isMatrix() && rightType.isMatrix()) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400914 this->writeMatrixTimesEqualHelper(leftType, rightType, b.type());
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500915 }
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400916 this->writeExpression(left, precedence);
917 if (op != Token::Kind::TK_EQ && Compiler::IsAssignment(op) &&
918 left.kind() == Expression::Kind::kSwizzle && !left.hasSideEffects()) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400919 // This doesn't compile in Metal:
920 // float4 x = float4(1);
921 // x.xy *= float2x2(...);
922 // with the error message "non-const reference cannot bind to vector element",
923 // but switching it to x.xy = x.xy * float2x2(...) fixes it. We perform this tranformation
924 // as long as the LHS has no side effects, and hope for the best otherwise.
925 this->write(" = ");
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400926 this->writeExpression(left, kAssignment_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400927 this->write(" ");
John Stilesd6449e92020-11-30 09:13:23 -0500928 String opName = OperatorName(op);
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400929 SkASSERT(opName.endsWith("="));
930 this->write(opName.substr(0, opName.size() - 1).c_str());
Ethan Nicholascc305772017-10-13 16:17:45 -0400931 this->write(" ");
932 } else {
John Stilesd6449e92020-11-30 09:13:23 -0500933 this->write(String(" ") + OperatorName(op) + " ");
Ethan Nicholascc305772017-10-13 16:17:45 -0400934 }
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400935 this->writeExpression(right, precedence);
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500936 if (needParens) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400937 this->write(")");
938 }
939}
940
941void MetalCodeGenerator::writeTernaryExpression(const TernaryExpression& t,
942 Precedence parentPrecedence) {
943 if (kTernary_Precedence >= parentPrecedence) {
944 this->write("(");
945 }
Ethan Nicholasdd218162020-10-08 05:48:01 -0400946 this->writeExpression(*t.test(), kTernary_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400947 this->write(" ? ");
Ethan Nicholasdd218162020-10-08 05:48:01 -0400948 this->writeExpression(*t.ifTrue(), kTernary_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400949 this->write(" : ");
Ethan Nicholasdd218162020-10-08 05:48:01 -0400950 this->writeExpression(*t.ifFalse(), kTernary_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400951 if (kTernary_Precedence >= parentPrecedence) {
952 this->write(")");
953 }
954}
955
956void MetalCodeGenerator::writePrefixExpression(const PrefixExpression& p,
957 Precedence parentPrecedence) {
958 if (kPrefix_Precedence >= parentPrecedence) {
959 this->write("(");
960 }
John Stilesd6449e92020-11-30 09:13:23 -0500961 this->write(OperatorName(p.getOperator()));
Ethan Nicholas444ccc62020-10-09 10:16:22 -0400962 this->writeExpression(*p.operand(), kPrefix_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400963 if (kPrefix_Precedence >= parentPrecedence) {
964 this->write(")");
965 }
966}
967
968void MetalCodeGenerator::writePostfixExpression(const PostfixExpression& p,
969 Precedence parentPrecedence) {
970 if (kPostfix_Precedence >= parentPrecedence) {
971 this->write("(");
972 }
Ethan Nicholas444ccc62020-10-09 10:16:22 -0400973 this->writeExpression(*p.operand(), kPostfix_Precedence);
John Stilesd6449e92020-11-30 09:13:23 -0500974 this->write(OperatorName(p.getOperator()));
Ethan Nicholascc305772017-10-13 16:17:45 -0400975 if (kPostfix_Precedence >= parentPrecedence) {
976 this->write(")");
977 }
978}
979
980void MetalCodeGenerator::writeBoolLiteral(const BoolLiteral& b) {
Ethan Nicholas59d660c2020-09-28 09:18:15 -0400981 this->write(b.value() ? "true" : "false");
Ethan Nicholascc305772017-10-13 16:17:45 -0400982}
983
984void MetalCodeGenerator::writeIntLiteral(const IntLiteral& i) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400985 if (i.type() == *fContext.fUInt_Type) {
Ethan Nicholase96cdd12020-09-28 16:27:18 -0400986 this->write(to_string(i.value() & 0xffffffff) + "u");
Ethan Nicholascc305772017-10-13 16:17:45 -0400987 } else {
Ethan Nicholase96cdd12020-09-28 16:27:18 -0400988 this->write(to_string((int32_t) i.value()));
Ethan Nicholascc305772017-10-13 16:17:45 -0400989 }
990}
991
992void MetalCodeGenerator::writeFloatLiteral(const FloatLiteral& f) {
Ethan Nicholasa3f22f12020-10-01 12:13:17 -0400993 this->write(to_string(f.value()));
Ethan Nicholascc305772017-10-13 16:17:45 -0400994}
995
996void MetalCodeGenerator::writeSetting(const Setting& s) {
997 ABORT("internal error; setting was not folded to a constant during compilation\n");
998}
999
John Stiles569249b2020-11-03 12:18:22 -05001000bool MetalCodeGenerator::writeFunctionDeclaration(const FunctionDeclaration& f) {
Ethan Nicholasf931e402019-07-26 15:40:33 -04001001 fRTHeightName = fProgram.fInputs.fRTHeight ? "_globals->_anonInterface0->u_skRTHeight" : "";
Ethan Nicholascc305772017-10-13 16:17:45 -04001002 const char* separator = "";
John Stiles569249b2020-11-03 12:18:22 -05001003 if ("main" == f.name()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001004 switch (fProgram.fKind) {
1005 case Program::kFragment_Kind:
Timothy Liangb8eeb802018-07-23 16:46:16 -04001006 this->write("fragment Outputs fragmentMain");
Ethan Nicholascc305772017-10-13 16:17:45 -04001007 break;
1008 case Program::kVertex_Kind:
Timothy Liangb8eeb802018-07-23 16:46:16 -04001009 this->write("vertex Outputs vertexMain");
Ethan Nicholascc305772017-10-13 16:17:45 -04001010 break;
1011 default:
John Stiles3fabfc02020-09-25 15:51:28 -04001012 fErrors.error(-1, "unsupported kind of program");
John Stiles569249b2020-11-03 12:18:22 -05001013 return false;
Ethan Nicholascc305772017-10-13 16:17:45 -04001014 }
1015 this->write("(Inputs _in [[stage_in]]");
1016 if (-1 != fUniformBuffer) {
1017 this->write(", constant Uniforms& _uniforms [[buffer(" +
1018 to_string(fUniformBuffer) + ")]]");
1019 }
Brian Osman133724c2020-10-28 14:14:39 -04001020 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04001021 if (e->is<GlobalVarDeclaration>()) {
1022 const GlobalVarDeclaration& decls = e->as<GlobalVarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001023 const VarDeclaration& var = decls.declaration()->as<VarDeclaration>();
1024 if (var.var().type().typeKind() == Type::TypeKind::kSampler) {
1025 if (var.var().modifiers().fLayout.fBinding < 0) {
Brian Osmanc0213602020-10-06 14:43:32 -04001026 fErrors.error(decls.fOffset,
1027 "Metal samplers must have 'layout(binding=...)'");
John Stiles569249b2020-11-03 12:18:22 -05001028 return false;
Timothy Liangee84fe12018-05-18 14:38:19 -04001029 }
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001030 if (var.var().type().dimensions() != SpvDim2D) {
John Stiles569249b2020-11-03 12:18:22 -05001031 // Not yet implemented--Skia currently only uses 2D textures.
Brian Osmanc0213602020-10-06 14:43:32 -04001032 fErrors.error(decls.fOffset, "Unsupported texture dimensions");
John Stiles569249b2020-11-03 12:18:22 -05001033 return false;
Brian Osmanc0213602020-10-06 14:43:32 -04001034 }
1035 this->write(", texture2d<float> ");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001036 this->writeName(var.var().name());
Brian Osmanc0213602020-10-06 14:43:32 -04001037 this->write("[[texture(");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001038 this->write(to_string(var.var().modifiers().fLayout.fBinding));
Brian Osmanc0213602020-10-06 14:43:32 -04001039 this->write(")]]");
1040 this->write(", sampler ");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001041 this->writeName(var.var().name());
Brian Osmanc0213602020-10-06 14:43:32 -04001042 this->write(SAMPLER_SUFFIX);
1043 this->write("[[sampler(");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001044 this->write(to_string(var.var().modifiers().fLayout.fBinding));
Brian Osmanc0213602020-10-06 14:43:32 -04001045 this->write(")]]");
Timothy Liang6403b0e2018-05-17 10:40:04 -04001046 }
Brian Osman1179fcf2020-10-08 16:04:40 -04001047 } else if (e->is<InterfaceBlock>()) {
1048 const InterfaceBlock& intf = e->as<InterfaceBlock>();
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001049 if (intf.typeName() == "sk_PerVertex") {
Timothy Lianga06f2152018-05-24 15:33:31 -04001050 continue;
1051 }
1052 this->write(", constant ");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001053 this->writeType(intf.variable().type());
Timothy Lianga06f2152018-05-24 15:33:31 -04001054 this->write("& " );
1055 this->write(fInterfaceBlockNameMap[&intf]);
1056 this->write(" [[buffer(");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001057 this->write(to_string(intf.variable().modifiers().fLayout.fBinding));
Timothy Lianga06f2152018-05-24 15:33:31 -04001058 this->write(")]]");
Timothy Liang6403b0e2018-05-17 10:40:04 -04001059 }
1060 }
Jim Van Verth6bc650e2019-02-07 14:53:23 -05001061 if (fProgram.fKind == Program::kFragment_Kind) {
1062 if (fProgram.fInputs.fRTHeight && fInterfaceBlockNameMap.empty()) {
Timothy Liang5422f9a2018-08-10 10:57:55 -04001063 this->write(", constant sksl_synthetic_uniforms& _anonInterface0 [[buffer(1)]]");
Ethan Nicholasf931e402019-07-26 15:40:33 -04001064 fRTHeightName = "_anonInterface0.u_skRTHeight";
Timothy Liang5422f9a2018-08-10 10:57:55 -04001065 }
Timothy Liang7b8875d2018-08-10 09:42:31 -04001066 this->write(", bool _frontFacing [[front_facing]]");
Timothy Liang7d637782018-06-05 09:58:07 -04001067 this->write(", float4 _fragCoord [[position]]");
Timothy Liangdc89f192018-06-13 09:20:31 -04001068 } else if (fProgram.fKind == Program::kVertex_Kind) {
1069 this->write(", uint sk_VertexID [[vertex_id]], uint sk_InstanceID [[instance_id]]");
Timothy Liang7d637782018-06-05 09:58:07 -04001070 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001071 separator = ", ";
1072 } else {
John Stiles569249b2020-11-03 12:18:22 -05001073 this->writeType(f.returnType());
Timothy Liang651286f2018-06-07 09:55:33 -04001074 this->write(" ");
John Stiles569249b2020-11-03 12:18:22 -05001075 this->writeName(f.name());
Timothy Liang651286f2018-06-07 09:55:33 -04001076 this->write("(");
John Stiles569249b2020-11-03 12:18:22 -05001077 Requirements requirements = this->requirements(f);
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -04001078 if (requirements & kInputs_Requirement) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001079 this->write("Inputs _in");
1080 separator = ", ";
1081 }
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -04001082 if (requirements & kOutputs_Requirement) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001083 this->write(separator);
Timothy Liangee84fe12018-05-18 14:38:19 -04001084 this->write("thread Outputs* _out");
Ethan Nicholascc305772017-10-13 16:17:45 -04001085 separator = ", ";
1086 }
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -04001087 if (requirements & kUniforms_Requirement) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001088 this->write(separator);
1089 this->write("Uniforms _uniforms");
1090 separator = ", ";
1091 }
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -04001092 if (requirements & kGlobals_Requirement) {
Timothy Liangee84fe12018-05-18 14:38:19 -04001093 this->write(separator);
1094 this->write("thread Globals* _globals");
1095 separator = ", ";
1096 }
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -04001097 if (requirements & kFragCoord_Requirement) {
1098 this->write(separator);
1099 this->write("float4 _fragCoord");
1100 separator = ", ";
1101 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001102 }
John Stiles569249b2020-11-03 12:18:22 -05001103 for (const auto& param : f.parameters()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001104 this->write(separator);
1105 separator = ", ";
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001106 this->writeModifiers(param->modifiers(), false);
Ethan Nicholascc305772017-10-13 16:17:45 -04001107 std::vector<int> sizes;
Ethan Nicholas30d30222020-09-11 12:27:26 -04001108 const Type* type = &param->type();
Ethan Nicholase6592142020-09-08 10:22:09 -04001109 while (type->typeKind() == Type::TypeKind::kArray) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001110 sizes.push_back(type->columns());
1111 type = &type->componentType();
1112 }
1113 this->writeType(*type);
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001114 if (param->modifiers().fFlags & Modifiers::kOut_Flag) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001115 this->write("*");
1116 }
Timothy Liang651286f2018-06-07 09:55:33 -04001117 this->write(" ");
Ethan Nicholase2c49992020-10-05 11:49:11 -04001118 this->writeName(param->name());
Ethan Nicholascc305772017-10-13 16:17:45 -04001119 for (int s : sizes) {
Brian Osmane8c26082020-10-01 17:22:45 -04001120 if (s == Type::kUnsizedArray) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001121 this->write("[]");
1122 } else {
1123 this->write("[" + to_string(s) + "]");
1124 }
1125 }
1126 }
John Stiles569249b2020-11-03 12:18:22 -05001127 this->write(")");
1128 return true;
1129}
Ethan Nicholascc305772017-10-13 16:17:45 -04001130
John Stiles569249b2020-11-03 12:18:22 -05001131void MetalCodeGenerator::writeFunctionPrototype(const FunctionPrototype& f) {
1132 this->writeFunctionDeclaration(f.declaration());
1133 this->writeLine(";");
1134}
1135
1136void MetalCodeGenerator::writeFunction(const FunctionDefinition& f) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001137 SkASSERT(!fProgram.fSettings.fFragColorIsInOut);
Brian Salomondc092132018-04-04 10:14:16 -04001138
John Stiles569249b2020-11-03 12:18:22 -05001139 if (!this->writeFunctionDeclaration(f.declaration())) {
1140 return;
1141 }
1142
1143 this->writeLine(" {");
1144
Ethan Nicholas0a5d0962020-10-14 13:33:18 -04001145 if (f.declaration().name() == "main") {
John Stilescdcdb042020-07-06 09:03:51 -04001146 this->writeGlobalInit();
Timothy Liang7d637782018-06-05 09:58:07 -04001147 this->writeLine(" Outputs _outputStruct;");
1148 this->writeLine(" thread Outputs* _out = &_outputStruct;");
Ethan Nicholascc305772017-10-13 16:17:45 -04001149 }
John Stilesc67b3622020-05-28 17:53:13 -04001150
Ethan Nicholascc305772017-10-13 16:17:45 -04001151 fFunctionHeader = "";
1152 OutputStream* oldOut = fOut;
1153 StringStream buffer;
1154 fOut = &buffer;
1155 fIndentation++;
Ethan Nicholas0a5d0962020-10-14 13:33:18 -04001156 for (const std::unique_ptr<Statement>& stmt : f.body()->as<Block>().children()) {
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001157 if (!stmt->isEmpty()) {
1158 this->writeStatement(*stmt);
1159 this->writeLine();
1160 }
1161 }
Ethan Nicholas0a5d0962020-10-14 13:33:18 -04001162 if (f.declaration().name() == "main") {
Ethan Nicholascc305772017-10-13 16:17:45 -04001163 switch (fProgram.fKind) {
1164 case Program::kFragment_Kind:
Timothy Liang7d637782018-06-05 09:58:07 -04001165 this->writeLine("return *_out;");
Ethan Nicholascc305772017-10-13 16:17:45 -04001166 break;
1167 case Program::kVertex_Kind:
Timothy Liangb8eeb802018-07-23 16:46:16 -04001168 this->writeLine("_out->sk_Position.y = -_out->sk_Position.y;");
Timothy Lianga06f2152018-05-24 15:33:31 -04001169 this->writeLine("return *_out;"); // FIXME - detect if function already has return
Ethan Nicholascc305772017-10-13 16:17:45 -04001170 break;
1171 default:
John Stilesf7d70432020-05-28 15:46:38 -04001172 SkDEBUGFAIL("unsupported kind of program");
Ethan Nicholascc305772017-10-13 16:17:45 -04001173 }
1174 }
1175 fIndentation--;
1176 this->writeLine("}");
1177
1178 fOut = oldOut;
1179 this->write(fFunctionHeader);
1180 this->write(buffer.str());
1181}
1182
1183void MetalCodeGenerator::writeModifiers(const Modifiers& modifiers,
1184 bool globalContext) {
1185 if (modifiers.fFlags & Modifiers::kOut_Flag) {
1186 this->write("thread ");
1187 }
1188 if (modifiers.fFlags & Modifiers::kConst_Flag) {
Timothy Liangee84fe12018-05-18 14:38:19 -04001189 this->write("constant ");
Ethan Nicholascc305772017-10-13 16:17:45 -04001190 }
1191}
1192
1193void MetalCodeGenerator::writeInterfaceBlock(const InterfaceBlock& intf) {
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001194 if ("sk_PerVertex" == intf.typeName()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001195 return;
1196 }
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001197 this->writeModifiers(intf.variable().modifiers(), true);
Timothy Liangdc89f192018-06-13 09:20:31 -04001198 this->write("struct ");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001199 this->writeLine(intf.typeName() + " {");
1200 const Type* structType = &intf.variable().type();
Timothy Lianga06f2152018-05-24 15:33:31 -04001201 fWrittenStructs.push_back(structType);
Ethan Nicholase6592142020-09-08 10:22:09 -04001202 while (structType->typeKind() == Type::TypeKind::kArray) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001203 structType = &structType->componentType();
1204 }
Timothy Liangdc89f192018-06-13 09:20:31 -04001205 fIndentation++;
1206 writeFields(structType->fields(), structType->fOffset, &intf);
Jim Van Verth3d482992019-02-07 10:48:05 -05001207 if (fProgram.fInputs.fRTHeight) {
Timothy Liang7d637782018-06-05 09:58:07 -04001208 this->writeLine("float u_skRTHeight;");
Ethan Nicholascc305772017-10-13 16:17:45 -04001209 }
1210 fIndentation--;
1211 this->write("}");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001212 if (intf.instanceName().size()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001213 this->write(" ");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001214 this->write(intf.instanceName());
1215 for (const auto& size : intf.sizes()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001216 this->write("[");
1217 if (size) {
1218 this->writeExpression(*size, kTopLevel_Precedence);
1219 }
1220 this->write("]");
1221 }
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001222 fInterfaceBlockNameMap[&intf] = intf.instanceName();
Timothy Lianga06f2152018-05-24 15:33:31 -04001223 } else {
Timothy Liang7d637782018-06-05 09:58:07 -04001224 fInterfaceBlockNameMap[&intf] = "_anonInterface" + to_string(fAnonInterfaceCount++);
Ethan Nicholascc305772017-10-13 16:17:45 -04001225 }
1226 this->writeLine(";");
1227}
1228
Timothy Liangdc89f192018-06-13 09:20:31 -04001229void MetalCodeGenerator::writeFields(const std::vector<Type::Field>& fields, int parentOffset,
1230 const InterfaceBlock* parentIntf) {
Timothy Liang609fbe32018-08-10 16:40:49 -04001231 MemoryLayout memoryLayout(MemoryLayout::kMetal_Standard);
Timothy Liangdc89f192018-06-13 09:20:31 -04001232 int currentOffset = 0;
1233 for (const auto& field: fields) {
1234 int fieldOffset = field.fModifiers.fLayout.fOffset;
1235 const Type* fieldType = field.fType;
John Stiles0023c0c2020-11-16 13:32:18 -05001236 if (!memoryLayout.layoutIsSupported(*fieldType)) {
1237 fErrors.error(parentOffset, "type '" + fieldType->name() + "' is not permitted here");
1238 return;
1239 }
Timothy Liangdc89f192018-06-13 09:20:31 -04001240 if (fieldOffset != -1) {
1241 if (currentOffset > fieldOffset) {
1242 fErrors.error(parentOffset,
1243 "offset of field '" + field.fName + "' must be at least " +
1244 to_string((int) currentOffset));
Brian Osman8609a242020-09-08 14:01:49 -04001245 return;
Timothy Liangdc89f192018-06-13 09:20:31 -04001246 } else if (currentOffset < fieldOffset) {
1247 this->write("char pad");
1248 this->write(to_string(fPaddingCount++));
1249 this->write("[");
1250 this->write(to_string(fieldOffset - currentOffset));
1251 this->writeLine("];");
1252 currentOffset = fieldOffset;
1253 }
1254 int alignment = memoryLayout.alignment(*fieldType);
1255 if (fieldOffset % alignment) {
1256 fErrors.error(parentOffset,
1257 "offset of field '" + field.fName + "' must be a multiple of " +
1258 to_string((int) alignment));
Brian Osman8609a242020-09-08 14:01:49 -04001259 return;
Timothy Liangdc89f192018-06-13 09:20:31 -04001260 }
1261 }
Brian Osman8609a242020-09-08 14:01:49 -04001262 size_t fieldSize = memoryLayout.size(*fieldType);
1263 if (fieldSize > static_cast<size_t>(std::numeric_limits<int>::max() - currentOffset)) {
1264 fErrors.error(parentOffset, "field offset overflow");
1265 return;
1266 }
1267 currentOffset += fieldSize;
Timothy Liangdc89f192018-06-13 09:20:31 -04001268 std::vector<int> sizes;
Ethan Nicholase6592142020-09-08 10:22:09 -04001269 while (fieldType->typeKind() == Type::TypeKind::kArray) {
Timothy Liangdc89f192018-06-13 09:20:31 -04001270 sizes.push_back(fieldType->columns());
1271 fieldType = &fieldType->componentType();
1272 }
1273 this->writeModifiers(field.fModifiers, false);
1274 this->writeType(*fieldType);
1275 this->write(" ");
1276 this->writeName(field.fName);
1277 for (int s : sizes) {
Brian Osmane8c26082020-10-01 17:22:45 -04001278 if (s == Type::kUnsizedArray) {
Timothy Liangdc89f192018-06-13 09:20:31 -04001279 this->write("[]");
1280 } else {
1281 this->write("[" + to_string(s) + "]");
1282 }
1283 }
1284 this->writeLine(";");
1285 if (parentIntf) {
1286 fInterfaceBlockMap[&field] = parentIntf;
1287 }
1288 }
1289}
1290
Ethan Nicholascc305772017-10-13 16:17:45 -04001291void MetalCodeGenerator::writeVarInitializer(const Variable& var, const Expression& value) {
1292 this->writeExpression(value, kTopLevel_Precedence);
1293}
1294
Timothy Liang651286f2018-06-07 09:55:33 -04001295void MetalCodeGenerator::writeName(const String& name) {
1296 if (fReservedWords.find(name) != fReservedWords.end()) {
1297 this->write("_"); // adding underscore before name to avoid conflict with reserved words
1298 }
1299 this->write(name);
1300}
1301
Brian Osmanc0213602020-10-06 14:43:32 -04001302void MetalCodeGenerator::writeVarDeclaration(const VarDeclaration& var, bool global) {
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001303 if (global && !(var.var().modifiers().fFlags & Modifiers::kConst_Flag)) {
Brian Osmanc0213602020-10-06 14:43:32 -04001304 return;
Ethan Nicholascc305772017-10-13 16:17:45 -04001305 }
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001306 this->writeModifiers(var.var().modifiers(), global);
1307 this->writeType(var.baseType());
Brian Osmanc0213602020-10-06 14:43:32 -04001308 this->write(" ");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001309 this->writeName(var.var().name());
John Stiles2d4f9592020-10-30 10:29:12 -04001310 for (const std::unique_ptr<Expression>& size : var.sizes()) {
Brian Osmanc0213602020-10-06 14:43:32 -04001311 this->write("[");
John Stiles2d4f9592020-10-30 10:29:12 -04001312 if (size) {
1313 this->writeExpression(*size, kTopLevel_Precedence);
Brian Osmanc0213602020-10-06 14:43:32 -04001314 }
1315 this->write("]");
Ethan Nicholascc305772017-10-13 16:17:45 -04001316 }
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001317 if (var.value()) {
Brian Osmanc0213602020-10-06 14:43:32 -04001318 this->write(" = ");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001319 this->writeVarInitializer(var.var(), *var.value());
Brian Osmanc0213602020-10-06 14:43:32 -04001320 }
1321 this->write(";");
Ethan Nicholascc305772017-10-13 16:17:45 -04001322}
1323
1324void MetalCodeGenerator::writeStatement(const Statement& s) {
Ethan Nicholase6592142020-09-08 10:22:09 -04001325 switch (s.kind()) {
1326 case Statement::Kind::kBlock:
John Stiles26f98502020-08-18 09:30:51 -04001327 this->writeBlock(s.as<Block>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001328 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001329 case Statement::Kind::kExpression:
Ethan Nicholasd503a5a2020-09-30 09:29:55 -04001330 this->writeExpression(*s.as<ExpressionStatement>().expression(), kTopLevel_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001331 this->write(";");
1332 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001333 case Statement::Kind::kReturn:
John Stiles26f98502020-08-18 09:30:51 -04001334 this->writeReturnStatement(s.as<ReturnStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001335 break;
Brian Osmanc0213602020-10-06 14:43:32 -04001336 case Statement::Kind::kVarDeclaration:
1337 this->writeVarDeclaration(s.as<VarDeclaration>(), false);
Ethan Nicholascc305772017-10-13 16:17:45 -04001338 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001339 case Statement::Kind::kIf:
John Stiles26f98502020-08-18 09:30:51 -04001340 this->writeIfStatement(s.as<IfStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001341 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001342 case Statement::Kind::kFor:
John Stiles26f98502020-08-18 09:30:51 -04001343 this->writeForStatement(s.as<ForStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001344 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001345 case Statement::Kind::kWhile:
John Stiles26f98502020-08-18 09:30:51 -04001346 this->writeWhileStatement(s.as<WhileStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001347 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001348 case Statement::Kind::kDo:
John Stiles26f98502020-08-18 09:30:51 -04001349 this->writeDoStatement(s.as<DoStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001350 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001351 case Statement::Kind::kSwitch:
John Stiles26f98502020-08-18 09:30:51 -04001352 this->writeSwitchStatement(s.as<SwitchStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001353 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001354 case Statement::Kind::kBreak:
Ethan Nicholascc305772017-10-13 16:17:45 -04001355 this->write("break;");
1356 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001357 case Statement::Kind::kContinue:
Ethan Nicholascc305772017-10-13 16:17:45 -04001358 this->write("continue;");
1359 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001360 case Statement::Kind::kDiscard:
Timothy Lianga06f2152018-05-24 15:33:31 -04001361 this->write("discard_fragment();");
Ethan Nicholascc305772017-10-13 16:17:45 -04001362 break;
John Stiles98c1f822020-09-09 14:18:53 -04001363 case Statement::Kind::kInlineMarker:
Ethan Nicholase6592142020-09-08 10:22:09 -04001364 case Statement::Kind::kNop:
Ethan Nicholascc305772017-10-13 16:17:45 -04001365 this->write(";");
1366 break;
1367 default:
Ethan Nicholas2a099da2020-01-02 14:40:54 -05001368#ifdef SK_DEBUG
Ethan Nicholascc305772017-10-13 16:17:45 -04001369 ABORT("unsupported statement: %s", s.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -05001370#endif
1371 break;
Ethan Nicholascc305772017-10-13 16:17:45 -04001372 }
1373}
1374
Ethan Nicholascc305772017-10-13 16:17:45 -04001375void MetalCodeGenerator::writeBlock(const Block& b) {
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001376 bool isScope = b.isScope();
1377 if (isScope) {
Ethan Nicholas70728ef2020-05-28 07:09:00 -04001378 this->writeLine("{");
1379 fIndentation++;
1380 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001381 for (const std::unique_ptr<Statement>& stmt : b.children()) {
1382 if (!stmt->isEmpty()) {
1383 this->writeStatement(*stmt);
1384 this->writeLine();
1385 }
1386 }
1387 if (isScope) {
Ethan Nicholas70728ef2020-05-28 07:09:00 -04001388 fIndentation--;
1389 this->write("}");
1390 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001391}
1392
1393void MetalCodeGenerator::writeIfStatement(const IfStatement& stmt) {
1394 this->write("if (");
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04001395 this->writeExpression(*stmt.test(), kTopLevel_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001396 this->write(") ");
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04001397 this->writeStatement(*stmt.ifTrue());
1398 if (stmt.ifFalse()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001399 this->write(" else ");
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04001400 this->writeStatement(*stmt.ifFalse());
Ethan Nicholascc305772017-10-13 16:17:45 -04001401 }
1402}
1403
1404void MetalCodeGenerator::writeForStatement(const ForStatement& f) {
1405 this->write("for (");
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04001406 if (f.initializer() && !f.initializer()->isEmpty()) {
1407 this->writeStatement(*f.initializer());
Ethan Nicholascc305772017-10-13 16:17:45 -04001408 } else {
1409 this->write("; ");
1410 }
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04001411 if (f.test()) {
1412 this->writeExpression(*f.test(), kTopLevel_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001413 }
1414 this->write("; ");
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04001415 if (f.next()) {
1416 this->writeExpression(*f.next(), kTopLevel_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001417 }
1418 this->write(") ");
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04001419 this->writeStatement(*f.statement());
Ethan Nicholascc305772017-10-13 16:17:45 -04001420}
1421
1422void MetalCodeGenerator::writeWhileStatement(const WhileStatement& w) {
1423 this->write("while (");
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04001424 this->writeExpression(*w.test(), kTopLevel_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001425 this->write(") ");
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04001426 this->writeStatement(*w.statement());
Ethan Nicholascc305772017-10-13 16:17:45 -04001427}
1428
1429void MetalCodeGenerator::writeDoStatement(const DoStatement& d) {
1430 this->write("do ");
Ethan Nicholas1fd61162020-09-28 13:14:19 -04001431 this->writeStatement(*d.statement());
Ethan Nicholascc305772017-10-13 16:17:45 -04001432 this->write(" while (");
Ethan Nicholas1fd61162020-09-28 13:14:19 -04001433 this->writeExpression(*d.test(), kTopLevel_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001434 this->write(");");
1435}
1436
1437void MetalCodeGenerator::writeSwitchStatement(const SwitchStatement& s) {
1438 this->write("switch (");
Ethan Nicholas01b05e52020-10-22 15:53:41 -04001439 this->writeExpression(*s.value(), kTopLevel_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001440 this->writeLine(") {");
1441 fIndentation++;
John Stiles2d4f9592020-10-30 10:29:12 -04001442 for (const std::unique_ptr<SwitchCase>& c : s.cases()) {
1443 if (c->value()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001444 this->write("case ");
John Stiles2d4f9592020-10-30 10:29:12 -04001445 this->writeExpression(*c->value(), kTopLevel_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001446 this->writeLine(":");
1447 } else {
1448 this->writeLine("default:");
1449 }
1450 fIndentation++;
John Stiles2d4f9592020-10-30 10:29:12 -04001451 for (const auto& stmt : c->statements()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001452 this->writeStatement(*stmt);
1453 this->writeLine();
1454 }
1455 fIndentation--;
1456 }
1457 fIndentation--;
1458 this->write("}");
1459}
1460
1461void MetalCodeGenerator::writeReturnStatement(const ReturnStatement& r) {
1462 this->write("return");
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04001463 if (r.expression()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001464 this->write(" ");
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04001465 this->writeExpression(*r.expression(), kTopLevel_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001466 }
1467 this->write(";");
1468}
1469
1470void MetalCodeGenerator::writeHeader() {
1471 this->write("#include <metal_stdlib>\n");
1472 this->write("#include <simd/simd.h>\n");
1473 this->write("using namespace metal;\n");
1474}
1475
1476void MetalCodeGenerator::writeUniformStruct() {
Brian Osman133724c2020-10-28 14:14:39 -04001477 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04001478 if (e->is<GlobalVarDeclaration>()) {
1479 const GlobalVarDeclaration& decls = e->as<GlobalVarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001480 const Variable& var = decls.declaration()->as<VarDeclaration>().var();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001481 if (var.modifiers().fFlags & Modifiers::kUniform_Flag &&
Brian Osmanc0213602020-10-06 14:43:32 -04001482 var.type().typeKind() != Type::TypeKind::kSampler) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001483 if (-1 == fUniformBuffer) {
1484 this->write("struct Uniforms {\n");
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001485 fUniformBuffer = var.modifiers().fLayout.fSet;
Ethan Nicholascc305772017-10-13 16:17:45 -04001486 if (-1 == fUniformBuffer) {
1487 fErrors.error(decls.fOffset, "Metal uniforms must have 'layout(set=...)'");
1488 }
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001489 } else if (var.modifiers().fLayout.fSet != fUniformBuffer) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001490 if (-1 == fUniformBuffer) {
1491 fErrors.error(decls.fOffset, "Metal backend requires all uniforms to have "
1492 "the same 'layout(set=...)'");
1493 }
1494 }
1495 this->write(" ");
Brian Osmanc0213602020-10-06 14:43:32 -04001496 this->writeType(var.type());
Ethan Nicholascc305772017-10-13 16:17:45 -04001497 this->write(" ");
Brian Osmanc0213602020-10-06 14:43:32 -04001498 this->writeName(var.name());
Ethan Nicholascc305772017-10-13 16:17:45 -04001499 this->write(";\n");
1500 }
1501 }
1502 }
1503 if (-1 != fUniformBuffer) {
1504 this->write("};\n");
1505 }
1506}
1507
1508void MetalCodeGenerator::writeInputStruct() {
1509 this->write("struct Inputs {\n");
Brian Osman133724c2020-10-28 14:14:39 -04001510 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04001511 if (e->is<GlobalVarDeclaration>()) {
1512 const GlobalVarDeclaration& decls = e->as<GlobalVarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001513 const Variable& var = decls.declaration()->as<VarDeclaration>().var();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001514 if (var.modifiers().fFlags & Modifiers::kIn_Flag &&
1515 -1 == var.modifiers().fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001516 this->write(" ");
Brian Osmanc0213602020-10-06 14:43:32 -04001517 this->writeType(var.type());
Ethan Nicholascc305772017-10-13 16:17:45 -04001518 this->write(" ");
Brian Osmanc0213602020-10-06 14:43:32 -04001519 this->writeName(var.name());
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001520 if (-1 != var.modifiers().fLayout.fLocation) {
Brian Osmanc0213602020-10-06 14:43:32 -04001521 if (fProgram.fKind == Program::kVertex_Kind) {
1522 this->write(" [[attribute(" +
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001523 to_string(var.modifiers().fLayout.fLocation) + ")]]");
Brian Osmanc0213602020-10-06 14:43:32 -04001524 } else if (fProgram.fKind == Program::kFragment_Kind) {
1525 this->write(" [[user(locn" +
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001526 to_string(var.modifiers().fLayout.fLocation) + ")]]");
Ethan Nicholascc305772017-10-13 16:17:45 -04001527 }
1528 }
1529 this->write(";\n");
1530 }
1531 }
1532 }
1533 this->write("};\n");
1534}
1535
1536void MetalCodeGenerator::writeOutputStruct() {
1537 this->write("struct Outputs {\n");
Timothy Liang7d637782018-06-05 09:58:07 -04001538 if (fProgram.fKind == Program::kVertex_Kind) {
Timothy Liangb8eeb802018-07-23 16:46:16 -04001539 this->write(" float4 sk_Position [[position]];\n");
Timothy Liang7d637782018-06-05 09:58:07 -04001540 } else if (fProgram.fKind == Program::kFragment_Kind) {
Timothy Liangde0be802018-08-10 13:48:08 -04001541 this->write(" float4 sk_FragColor [[color(0)]];\n");
Timothy Liang7d637782018-06-05 09:58:07 -04001542 }
Brian Osman133724c2020-10-28 14:14:39 -04001543 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04001544 if (e->is<GlobalVarDeclaration>()) {
1545 const GlobalVarDeclaration& decls = e->as<GlobalVarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001546 const Variable& var = decls.declaration()->as<VarDeclaration>().var();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001547 if (var.modifiers().fFlags & Modifiers::kOut_Flag &&
1548 -1 == var.modifiers().fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001549 this->write(" ");
Brian Osmanc0213602020-10-06 14:43:32 -04001550 this->writeType(var.type());
Ethan Nicholascc305772017-10-13 16:17:45 -04001551 this->write(" ");
Brian Osmanc0213602020-10-06 14:43:32 -04001552 this->writeName(var.name());
1553 if (fProgram.fKind == Program::kVertex_Kind) {
1554 this->write(" [[user(locn" +
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001555 to_string(var.modifiers().fLayout.fLocation) + ")]]");
Brian Osmanc0213602020-10-06 14:43:32 -04001556 } else if (fProgram.fKind == Program::kFragment_Kind) {
1557 this->write(" [[color(" +
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001558 to_string(var.modifiers().fLayout.fLocation) +")");
1559 int colorIndex = var.modifiers().fLayout.fIndex;
Brian Osmanc0213602020-10-06 14:43:32 -04001560 if (colorIndex) {
1561 this->write(", index(" + to_string(colorIndex) + ")");
Timothy Liang7d637782018-06-05 09:58:07 -04001562 }
Brian Osmanc0213602020-10-06 14:43:32 -04001563 this->write("]]");
Ethan Nicholascc305772017-10-13 16:17:45 -04001564 }
1565 this->write(";\n");
1566 }
1567 }
Timothy Liang7d637782018-06-05 09:58:07 -04001568 }
1569 if (fProgram.fKind == Program::kVertex_Kind) {
Jim Van Verth3913d3e2020-08-31 15:16:57 -04001570 this->write(" float sk_PointSize [[point_size]];\n");
Timothy Liang7d637782018-06-05 09:58:07 -04001571 }
1572 this->write("};\n");
1573}
1574
1575void MetalCodeGenerator::writeInterfaceBlocks() {
1576 bool wroteInterfaceBlock = false;
Brian Osman133724c2020-10-28 14:14:39 -04001577 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04001578 if (e->is<InterfaceBlock>()) {
1579 this->writeInterfaceBlock(e->as<InterfaceBlock>());
Timothy Liang7d637782018-06-05 09:58:07 -04001580 wroteInterfaceBlock = true;
1581 }
1582 }
Jim Van Verth3d482992019-02-07 10:48:05 -05001583 if (!wroteInterfaceBlock && fProgram.fInputs.fRTHeight) {
Timothy Liang7d637782018-06-05 09:58:07 -04001584 this->writeLine("struct sksl_synthetic_uniforms {");
1585 this->writeLine(" float u_skRTHeight;");
1586 this->writeLine("};");
1587 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001588}
1589
John Stilescdcdb042020-07-06 09:03:51 -04001590void MetalCodeGenerator::visitGlobalStruct(GlobalStructVisitor* visitor) {
1591 // Visit the interface blocks.
1592 for (const auto& [interfaceType, interfaceName] : fInterfaceBlockNameMap) {
1593 visitor->VisitInterfaceBlock(*interfaceType, interfaceName);
1594 }
Brian Osman133724c2020-10-28 14:14:39 -04001595 for (const ProgramElement* element : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04001596 if (!element->is<GlobalVarDeclaration>()) {
John Stilescdcdb042020-07-06 09:03:51 -04001597 continue;
Timothy Liang7d637782018-06-05 09:58:07 -04001598 }
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001599 const GlobalVarDeclaration& global = element->as<GlobalVarDeclaration>();
1600 const VarDeclaration& decl = global.declaration()->as<VarDeclaration>();
1601 const Variable& var = decl.var();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001602 if ((!var.modifiers().fFlags && -1 == var.modifiers().fLayout.fBuiltin) ||
Brian Osmanc0213602020-10-06 14:43:32 -04001603 var.type().typeKind() == Type::TypeKind::kSampler) {
1604 if (var.type().typeKind() == Type::TypeKind::kSampler) {
1605 // Samplers are represented as a "texture/sampler" duo in the global struct.
1606 visitor->VisitTexture(var.type(), var.name());
1607 visitor->VisitSampler(var.type(), String(var.name()) + SAMPLER_SUFFIX);
1608 } else {
1609 // Visit a regular variable.
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001610 visitor->VisitVariable(var, decl.value().get());
Timothy Liangee84fe12018-05-18 14:38:19 -04001611 }
1612 }
1613 }
John Stilescdcdb042020-07-06 09:03:51 -04001614}
1615
1616void MetalCodeGenerator::writeGlobalStruct() {
1617 class : public GlobalStructVisitor {
1618 public:
1619 void VisitInterfaceBlock(const InterfaceBlock& block, const String& blockName) override {
1620 this->AddElement();
1621 fCodeGen->write(" constant ");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001622 fCodeGen->write(block.typeName());
John Stilescdcdb042020-07-06 09:03:51 -04001623 fCodeGen->write("* ");
1624 fCodeGen->writeName(blockName);
1625 fCodeGen->write(";\n");
1626 }
1627 void VisitTexture(const Type& type, const String& name) override {
1628 this->AddElement();
1629 fCodeGen->write(" ");
1630 fCodeGen->writeType(type);
1631 fCodeGen->write(" ");
1632 fCodeGen->writeName(name);
1633 fCodeGen->write(";\n");
1634 }
1635 void VisitSampler(const Type&, const String& name) override {
1636 this->AddElement();
1637 fCodeGen->write(" sampler ");
1638 fCodeGen->writeName(name);
1639 fCodeGen->write(";\n");
1640 }
1641 void VisitVariable(const Variable& var, const Expression* value) override {
1642 this->AddElement();
1643 fCodeGen->write(" ");
Ethan Nicholas30d30222020-09-11 12:27:26 -04001644 fCodeGen->writeType(var.type());
John Stilescdcdb042020-07-06 09:03:51 -04001645 fCodeGen->write(" ");
Ethan Nicholase2c49992020-10-05 11:49:11 -04001646 fCodeGen->writeName(var.name());
John Stilescdcdb042020-07-06 09:03:51 -04001647 fCodeGen->write(";\n");
1648 }
1649 void AddElement() {
1650 if (fFirst) {
1651 fCodeGen->write("struct Globals {\n");
1652 fFirst = false;
1653 }
1654 }
1655 void Finish() {
1656 if (!fFirst) {
1657 fCodeGen->write("};");
1658 fFirst = true;
1659 }
1660 }
1661
1662 MetalCodeGenerator* fCodeGen = nullptr;
1663 bool fFirst = true;
1664 } visitor;
1665
1666 visitor.fCodeGen = this;
1667 this->visitGlobalStruct(&visitor);
1668 visitor.Finish();
1669}
1670
1671void MetalCodeGenerator::writeGlobalInit() {
1672 class : public GlobalStructVisitor {
1673 public:
1674 void VisitInterfaceBlock(const InterfaceBlock& blockType,
1675 const String& blockName) override {
1676 this->AddElement();
1677 fCodeGen->write("&");
1678 fCodeGen->writeName(blockName);
1679 }
1680 void VisitTexture(const Type&, const String& name) override {
1681 this->AddElement();
1682 fCodeGen->writeName(name);
1683 }
1684 void VisitSampler(const Type&, const String& name) override {
1685 this->AddElement();
1686 fCodeGen->writeName(name);
1687 }
1688 void VisitVariable(const Variable& var, const Expression* value) override {
1689 this->AddElement();
1690 if (value) {
1691 fCodeGen->writeVarInitializer(var, *value);
1692 } else {
1693 fCodeGen->write("{}");
1694 }
1695 }
1696 void AddElement() {
1697 if (fFirst) {
1698 fCodeGen->write(" Globals globalStruct{");
1699 fFirst = false;
1700 } else {
1701 fCodeGen->write(", ");
1702 }
1703 }
1704 void Finish() {
1705 if (!fFirst) {
1706 fCodeGen->writeLine("};");
1707 fCodeGen->writeLine(" thread Globals* _globals = &globalStruct;");
1708 fCodeGen->writeLine(" (void)_globals;");
1709 }
1710 }
1711 MetalCodeGenerator* fCodeGen = nullptr;
1712 bool fFirst = true;
1713 } visitor;
1714
1715 visitor.fCodeGen = this;
1716 this->visitGlobalStruct(&visitor);
1717 visitor.Finish();
Timothy Liangee84fe12018-05-18 14:38:19 -04001718}
1719
Ethan Nicholascc305772017-10-13 16:17:45 -04001720void MetalCodeGenerator::writeProgramElement(const ProgramElement& e) {
Ethan Nicholase6592142020-09-08 10:22:09 -04001721 switch (e.kind()) {
1722 case ProgramElement::Kind::kExtension:
Ethan Nicholascc305772017-10-13 16:17:45 -04001723 break;
Brian Osmanc0213602020-10-06 14:43:32 -04001724 case ProgramElement::Kind::kGlobalVar: {
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001725 const GlobalVarDeclaration& global = e.as<GlobalVarDeclaration>();
1726 const VarDeclaration& decl = global.declaration()->as<VarDeclaration>();
1727 int builtin = decl.var().modifiers().fLayout.fBuiltin;
Brian Osmanc0213602020-10-06 14:43:32 -04001728 if (-1 == builtin) {
1729 // normal var
1730 this->writeVarDeclaration(decl, true);
1731 this->writeLine();
1732 } else if (SK_FRAGCOLOR_BUILTIN == builtin) {
1733 // ignore
Ethan Nicholascc305772017-10-13 16:17:45 -04001734 }
1735 break;
1736 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001737 case ProgramElement::Kind::kInterfaceBlock:
Timothy Liang7d637782018-06-05 09:58:07 -04001738 // handled in writeInterfaceBlocks, do nothing
Ethan Nicholascc305772017-10-13 16:17:45 -04001739 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001740 case ProgramElement::Kind::kFunction:
John Stiles3dc0da62020-08-19 17:48:31 -04001741 this->writeFunction(e.as<FunctionDefinition>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001742 break;
John Stiles569249b2020-11-03 12:18:22 -05001743 case ProgramElement::Kind::kFunctionPrototype:
1744 this->writeFunctionPrototype(e.as<FunctionPrototype>());
1745 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001746 case ProgramElement::Kind::kModifiers:
Ethan Nicholas077050b2020-10-13 10:30:20 -04001747 this->writeModifiers(e.as<ModifiersDeclaration>().modifiers(), true);
Ethan Nicholascc305772017-10-13 16:17:45 -04001748 this->writeLine(";");
1749 break;
John Stiles712fd6b2020-11-25 22:25:43 -05001750 case ProgramElement::Kind::kEnum:
1751 break;
Ethan Nicholascc305772017-10-13 16:17:45 -04001752 default:
Ethan Nicholas2a099da2020-01-02 14:40:54 -05001753#ifdef SK_DEBUG
1754 ABORT("unsupported program element: %s\n", e.description().c_str());
1755#endif
1756 break;
Ethan Nicholascc305772017-10-13 16:17:45 -04001757 }
1758}
1759
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001760MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const Expression* e) {
1761 if (!e) {
1762 return kNo_Requirements;
1763 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001764 switch (e->kind()) {
1765 case Expression::Kind::kFunctionCall: {
John Stiles3dc0da62020-08-19 17:48:31 -04001766 const FunctionCall& f = e->as<FunctionCall>();
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001767 Requirements result = this->requirements(f.function());
1768 for (const auto& arg : f.arguments()) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001769 result |= this->requirements(arg.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001770 }
1771 return result;
1772 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001773 case Expression::Kind::kConstructor: {
John Stiles3dc0da62020-08-19 17:48:31 -04001774 const Constructor& c = e->as<Constructor>();
Ethan Nicholascc305772017-10-13 16:17:45 -04001775 Requirements result = kNo_Requirements;
Ethan Nicholasf70f0442020-09-29 12:41:35 -04001776 for (const auto& arg : c.arguments()) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001777 result |= this->requirements(arg.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001778 }
1779 return result;
1780 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001781 case Expression::Kind::kFieldAccess: {
John Stiles3dc0da62020-08-19 17:48:31 -04001782 const FieldAccess& f = e->as<FieldAccess>();
Ethan Nicholas7a95b202020-10-09 11:55:40 -04001783 if (FieldAccess::OwnerKind::kAnonymousInterfaceBlock == f.ownerKind()) {
Timothy Liang7d637782018-06-05 09:58:07 -04001784 return kGlobals_Requirement;
1785 }
Ethan Nicholas7a95b202020-10-09 11:55:40 -04001786 return this->requirements(f.base().get());
Timothy Liang7d637782018-06-05 09:58:07 -04001787 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001788 case Expression::Kind::kSwizzle:
Ethan Nicholas6b4d5812020-10-12 16:11:51 -04001789 return this->requirements(e->as<Swizzle>().base().get());
Ethan Nicholase6592142020-09-08 10:22:09 -04001790 case Expression::Kind::kBinary: {
1791 const BinaryExpression& bin = e->as<BinaryExpression>();
John Stiles2d4f9592020-10-30 10:29:12 -04001792 return this->requirements(bin.left().get()) |
1793 this->requirements(bin.right().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001794 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001795 case Expression::Kind::kIndex: {
John Stiles3dc0da62020-08-19 17:48:31 -04001796 const IndexExpression& idx = e->as<IndexExpression>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04001797 return this->requirements(idx.base().get()) | this->requirements(idx.index().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001798 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001799 case Expression::Kind::kPrefix:
Ethan Nicholas444ccc62020-10-09 10:16:22 -04001800 return this->requirements(e->as<PrefixExpression>().operand().get());
Ethan Nicholase6592142020-09-08 10:22:09 -04001801 case Expression::Kind::kPostfix:
Ethan Nicholas444ccc62020-10-09 10:16:22 -04001802 return this->requirements(e->as<PostfixExpression>().operand().get());
Ethan Nicholase6592142020-09-08 10:22:09 -04001803 case Expression::Kind::kTernary: {
John Stiles3dc0da62020-08-19 17:48:31 -04001804 const TernaryExpression& t = e->as<TernaryExpression>();
Ethan Nicholasdd218162020-10-08 05:48:01 -04001805 return this->requirements(t.test().get()) | this->requirements(t.ifTrue().get()) |
1806 this->requirements(t.ifFalse().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001807 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001808 case Expression::Kind::kVariableReference: {
John Stiles3dc0da62020-08-19 17:48:31 -04001809 const VariableReference& v = e->as<VariableReference>();
Ethan Nicholas78686922020-10-08 06:46:27 -04001810 const Modifiers& modifiers = v.variable()->modifiers();
Ethan Nicholascc305772017-10-13 16:17:45 -04001811 Requirements result = kNo_Requirements;
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001812 if (modifiers.fLayout.fBuiltin == SK_FRAGCOORD_BUILTIN) {
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -04001813 result = kGlobals_Requirement | kFragCoord_Requirement;
Ethan Nicholas453f67f2020-10-09 10:43:45 -04001814 } else if (Variable::Storage::kGlobal == v.variable()->storage()) {
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001815 if (modifiers.fFlags & Modifiers::kIn_Flag) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001816 result = kInputs_Requirement;
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001817 } else if (modifiers.fFlags & Modifiers::kOut_Flag) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001818 result = kOutputs_Requirement;
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001819 } else if (modifiers.fFlags & Modifiers::kUniform_Flag &&
Ethan Nicholas78686922020-10-08 06:46:27 -04001820 v.variable()->type().typeKind() != Type::TypeKind::kSampler) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001821 result = kUniforms_Requirement;
Timothy Liangee84fe12018-05-18 14:38:19 -04001822 } else {
1823 result = kGlobals_Requirement;
Ethan Nicholascc305772017-10-13 16:17:45 -04001824 }
1825 }
1826 return result;
1827 }
1828 default:
1829 return kNo_Requirements;
1830 }
1831}
1832
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001833MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const Statement* s) {
1834 if (!s) {
1835 return kNo_Requirements;
1836 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001837 switch (s->kind()) {
1838 case Statement::Kind::kBlock: {
Ethan Nicholascc305772017-10-13 16:17:45 -04001839 Requirements result = kNo_Requirements;
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001840 for (const std::unique_ptr<Statement>& child : s->as<Block>().children()) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001841 result |= this->requirements(child.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001842 }
1843 return result;
1844 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001845 case Statement::Kind::kVarDeclaration: {
John Stiles3dc0da62020-08-19 17:48:31 -04001846 const VarDeclaration& var = s->as<VarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001847 return this->requirements(var.value().get());
Timothy Liang7d637782018-06-05 09:58:07 -04001848 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001849 case Statement::Kind::kExpression:
Ethan Nicholasd503a5a2020-09-30 09:29:55 -04001850 return this->requirements(s->as<ExpressionStatement>().expression().get());
Ethan Nicholase6592142020-09-08 10:22:09 -04001851 case Statement::Kind::kReturn: {
John Stiles3dc0da62020-08-19 17:48:31 -04001852 const ReturnStatement& r = s->as<ReturnStatement>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04001853 return this->requirements(r.expression().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001854 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001855 case Statement::Kind::kIf: {
John Stiles3dc0da62020-08-19 17:48:31 -04001856 const IfStatement& i = s->as<IfStatement>();
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04001857 return this->requirements(i.test().get()) |
1858 this->requirements(i.ifTrue().get()) |
1859 this->requirements(i.ifFalse().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001860 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001861 case Statement::Kind::kFor: {
John Stiles3dc0da62020-08-19 17:48:31 -04001862 const ForStatement& f = s->as<ForStatement>();
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04001863 return this->requirements(f.initializer().get()) |
1864 this->requirements(f.test().get()) |
1865 this->requirements(f.next().get()) |
1866 this->requirements(f.statement().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001867 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001868 case Statement::Kind::kWhile: {
John Stiles3dc0da62020-08-19 17:48:31 -04001869 const WhileStatement& w = s->as<WhileStatement>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04001870 return this->requirements(w.test().get()) |
1871 this->requirements(w.statement().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001872 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001873 case Statement::Kind::kDo: {
John Stiles3dc0da62020-08-19 17:48:31 -04001874 const DoStatement& d = s->as<DoStatement>();
Ethan Nicholas1fd61162020-09-28 13:14:19 -04001875 return this->requirements(d.test().get()) |
1876 this->requirements(d.statement().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001877 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001878 case Statement::Kind::kSwitch: {
John Stiles3dc0da62020-08-19 17:48:31 -04001879 const SwitchStatement& sw = s->as<SwitchStatement>();
Ethan Nicholas01b05e52020-10-22 15:53:41 -04001880 Requirements result = this->requirements(sw.value().get());
John Stiles2d4f9592020-10-30 10:29:12 -04001881 for (const std::unique_ptr<SwitchCase>& sc : sw.cases()) {
1882 for (const auto& st : sc->statements()) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001883 result |= this->requirements(st.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001884 }
1885 }
1886 return result;
1887 }
1888 default:
1889 return kNo_Requirements;
1890 }
1891}
1892
1893MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const FunctionDeclaration& f) {
Ethan Nicholased84b732020-10-08 11:45:44 -04001894 if (f.isBuiltin()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001895 return kNo_Requirements;
1896 }
1897 auto found = fRequirements.find(&f);
1898 if (found == fRequirements.end()) {
Ethan Nicholas65a8f562019-04-19 14:00:26 -04001899 fRequirements[&f] = kNo_Requirements;
Brian Osman133724c2020-10-28 14:14:39 -04001900 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04001901 if (e->is<FunctionDefinition>()) {
1902 const FunctionDefinition& def = e->as<FunctionDefinition>();
Ethan Nicholas0a5d0962020-10-14 13:33:18 -04001903 if (&def.declaration() == &f) {
1904 Requirements reqs = this->requirements(def.body().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001905 fRequirements[&f] = reqs;
1906 return reqs;
1907 }
1908 }
1909 }
John Stiles569249b2020-11-03 12:18:22 -05001910 // We never found a definition for this declared function, but it's legal to prototype a
1911 // function without ever giving a definition, as long as you don't call it.
1912 return kNo_Requirements;
Ethan Nicholascc305772017-10-13 16:17:45 -04001913 }
1914 return found->second;
1915}
1916
Timothy Liangb8eeb802018-07-23 16:46:16 -04001917bool MetalCodeGenerator::generateCode() {
Ethan Nicholascc305772017-10-13 16:17:45 -04001918 OutputStream* rawOut = fOut;
1919 fOut = &fHeader;
1920 fProgramKind = fProgram.fKind;
1921 this->writeHeader();
1922 this->writeUniformStruct();
1923 this->writeInputStruct();
Timothy Liang7d637782018-06-05 09:58:07 -04001924 this->writeOutputStruct();
1925 this->writeInterfaceBlocks();
Timothy Liangee84fe12018-05-18 14:38:19 -04001926 this->writeGlobalStruct();
Ethan Nicholascc305772017-10-13 16:17:45 -04001927 StringStream body;
1928 fOut = &body;
Brian Osman133724c2020-10-28 14:14:39 -04001929 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04001930 this->writeProgramElement(*e);
Ethan Nicholascc305772017-10-13 16:17:45 -04001931 }
1932 fOut = rawOut;
1933
1934 write_stringstream(fHeader, *rawOut);
Chris Daltondba7aab2018-11-15 10:57:49 -05001935 write_stringstream(fExtraFunctions, *rawOut);
Ethan Nicholascc305772017-10-13 16:17:45 -04001936 write_stringstream(body, *rawOut);
Brian Osman8609a242020-09-08 14:01:49 -04001937 return 0 == fErrors.errorCount();
Ethan Nicholascc305772017-10-13 16:17:45 -04001938}
1939
John Stilesa6841be2020-08-06 14:11:56 -04001940} // namespace SkSL