blob: aa74a42244573e9799897a57b39475cad92672d5 [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"
John Stilesdc75a972020-11-25 16:24:55 -050017#include "src/sksl/ir/SkSLStructDefinition.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050018#include "src/sksl/ir/SkSLVariableReference.h"
Ethan Nicholascc305772017-10-13 16:17:45 -040019
Brian Osmanc262a122020-08-06 16:34:34 -040020#include <algorithm>
21
Ethan Nicholascc305772017-10-13 16:17:45 -040022namespace SkSL {
23
John Stilesd6449e92020-11-30 09:13:23 -050024const char* MetalCodeGenerator::OperatorName(Token::Kind op) {
25 switch (op) {
26 case Token::Kind::TK_LOGICALXOR: return "!=";
27 default: return Compiler::OperatorName(op);
28 }
29}
30
John Stilescdcdb042020-07-06 09:03:51 -040031class MetalCodeGenerator::GlobalStructVisitor {
32public:
33 virtual ~GlobalStructVisitor() = default;
34 virtual void VisitInterfaceBlock(const InterfaceBlock& block, const String& blockName) = 0;
35 virtual void VisitTexture(const Type& type, const String& name) = 0;
36 virtual void VisitSampler(const Type& type, const String& name) = 0;
37 virtual void VisitVariable(const Variable& var, const Expression* value) = 0;
38};
39
Timothy Liangee84fe12018-05-18 14:38:19 -040040void MetalCodeGenerator::setupIntrinsics() {
Timothy Liang7d637782018-06-05 09:58:07 -040041#define METAL(x) std::make_pair(kMetal_IntrinsicKind, k ## x ## _MetalIntrinsic)
42#define SPECIAL(x) std::make_pair(kSpecial_IntrinsicKind, k ## x ## _SpecialIntrinsic)
Brian Osman46787d52020-11-24 14:18:23 -050043 fIntrinsicMap[String("distance")] = SPECIAL(Distance);
44 fIntrinsicMap[String("dot")] = SPECIAL(Dot);
45 fIntrinsicMap[String("length")] = SPECIAL(Length);
Timothy Liang651286f2018-06-07 09:55:33 -040046 fIntrinsicMap[String("mod")] = SPECIAL(Mod);
Brian Osman46787d52020-11-24 14:18:23 -050047 fIntrinsicMap[String("normalize")] = SPECIAL(Normalize);
48 fIntrinsicMap[String("sample")] = SPECIAL(Texture);
Ethan Nicholas0dc80872019-02-08 15:46:24 -050049 fIntrinsicMap[String("equal")] = METAL(Equal);
50 fIntrinsicMap[String("notEqual")] = METAL(NotEqual);
Timothy Lianga06f2152018-05-24 15:33:31 -040051 fIntrinsicMap[String("lessThan")] = METAL(LessThan);
52 fIntrinsicMap[String("lessThanEqual")] = METAL(LessThanEqual);
53 fIntrinsicMap[String("greaterThan")] = METAL(GreaterThan);
54 fIntrinsicMap[String("greaterThanEqual")] = METAL(GreaterThanEqual);
Timothy Liangee84fe12018-05-18 14:38:19 -040055}
56
Ethan Nicholascc305772017-10-13 16:17:45 -040057void MetalCodeGenerator::write(const char* s) {
58 if (!s[0]) {
59 return;
60 }
61 if (fAtLineStart) {
62 for (int i = 0; i < fIndentation; i++) {
63 fOut->writeText(" ");
64 }
65 }
66 fOut->writeText(s);
67 fAtLineStart = false;
68}
69
70void MetalCodeGenerator::writeLine(const char* s) {
71 this->write(s);
72 fOut->writeText(fLineEnding);
73 fAtLineStart = true;
74}
75
76void MetalCodeGenerator::write(const String& s) {
77 this->write(s.c_str());
78}
79
80void MetalCodeGenerator::writeLine(const String& s) {
81 this->writeLine(s.c_str());
82}
83
84void MetalCodeGenerator::writeLine() {
85 this->writeLine("");
86}
87
88void MetalCodeGenerator::writeExtension(const Extension& ext) {
Ethan Nicholasefb09e22020-09-30 10:17:00 -040089 this->writeLine("#extension " + ext.name() + " : enable");
Ethan Nicholascc305772017-10-13 16:17:45 -040090}
91
Ethan Nicholas45fa8102020-01-13 10:58:49 -050092String MetalCodeGenerator::typeName(const Type& type) {
Ethan Nicholase6592142020-09-08 10:22:09 -040093 switch (type.typeKind()) {
94 case Type::TypeKind::kVector:
Ethan Nicholas45fa8102020-01-13 10:58:49 -050095 return this->typeName(type.componentType()) + to_string(type.columns());
Ethan Nicholase6592142020-09-08 10:22:09 -040096 case Type::TypeKind::kMatrix:
Ethan Nicholas45fa8102020-01-13 10:58:49 -050097 return this->typeName(type.componentType()) + to_string(type.columns()) + "x" +
98 to_string(type.rows());
Ethan Nicholase6592142020-09-08 10:22:09 -040099 case Type::TypeKind::kSampler:
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500100 return "texture2d<float>"; // FIXME - support other texture types;
Ethan Nicholascc305772017-10-13 16:17:45 -0400101 default:
Timothy Liang43d225f2018-07-19 15:27:13 -0400102 if (type == *fContext.fHalf_Type) {
103 // FIXME - Currently only supporting floats in MSL to avoid type coercion issues.
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500104 return fContext.fFloat_Type->name();
Timothy Liang43d225f2018-07-19 15:27:13 -0400105 } else if (type == *fContext.fByte_Type) {
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500106 return "char";
Timothy Liang43d225f2018-07-19 15:27:13 -0400107 } else if (type == *fContext.fUByte_Type) {
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500108 return "uchar";
Timothy Liang7d637782018-06-05 09:58:07 -0400109 } else {
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500110 return type.name();
Timothy Liang7d637782018-06-05 09:58:07 -0400111 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400112 }
113}
114
John Stilesdc75a972020-11-25 16:24:55 -0500115bool MetalCodeGenerator::writeStructDefinition(const Type& type) {
116 for (const Type* search : fWrittenStructs) {
117 if (*search == type) {
118 // already written
119 return false;
120 }
121 }
122 fWrittenStructs.push_back(&type);
123 this->writeLine("struct " + type.name() + " {");
124 fIndentation++;
125 this->writeFields(type.fields(), type.fOffset);
126 fIndentation--;
127 this->write("}");
128 return true;
129}
130
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500131void MetalCodeGenerator::writeType(const Type& type) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400132 if (type.typeKind() == Type::TypeKind::kStruct) {
John Stilesdc75a972020-11-25 16:24:55 -0500133 if (!this->writeStructDefinition(type)) {
134 this->write(type.name());
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500135 }
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500136 } else {
137 this->write(this->typeName(type));
138 }
139}
140
Ethan Nicholascc305772017-10-13 16:17:45 -0400141void MetalCodeGenerator::writeExpression(const Expression& expr, Precedence parentPrecedence) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400142 switch (expr.kind()) {
143 case Expression::Kind::kBinary:
John Stiles81365af2020-08-18 09:24:00 -0400144 this->writeBinaryExpression(expr.as<BinaryExpression>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400145 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400146 case Expression::Kind::kBoolLiteral:
John Stiles81365af2020-08-18 09:24:00 -0400147 this->writeBoolLiteral(expr.as<BoolLiteral>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400148 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400149 case Expression::Kind::kConstructor:
John Stiles81365af2020-08-18 09:24:00 -0400150 this->writeConstructor(expr.as<Constructor>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400151 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400152 case Expression::Kind::kIntLiteral:
John Stiles81365af2020-08-18 09:24:00 -0400153 this->writeIntLiteral(expr.as<IntLiteral>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400154 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400155 case Expression::Kind::kFieldAccess:
John Stiles81365af2020-08-18 09:24:00 -0400156 this->writeFieldAccess(expr.as<FieldAccess>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400157 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400158 case Expression::Kind::kFloatLiteral:
John Stiles81365af2020-08-18 09:24:00 -0400159 this->writeFloatLiteral(expr.as<FloatLiteral>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400160 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400161 case Expression::Kind::kFunctionCall:
John Stiles81365af2020-08-18 09:24:00 -0400162 this->writeFunctionCall(expr.as<FunctionCall>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400163 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400164 case Expression::Kind::kPrefix:
John Stiles81365af2020-08-18 09:24:00 -0400165 this->writePrefixExpression(expr.as<PrefixExpression>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400166 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400167 case Expression::Kind::kPostfix:
John Stiles81365af2020-08-18 09:24:00 -0400168 this->writePostfixExpression(expr.as<PostfixExpression>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400169 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400170 case Expression::Kind::kSetting:
John Stiles81365af2020-08-18 09:24:00 -0400171 this->writeSetting(expr.as<Setting>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400172 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400173 case Expression::Kind::kSwizzle:
John Stiles81365af2020-08-18 09:24:00 -0400174 this->writeSwizzle(expr.as<Swizzle>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400175 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400176 case Expression::Kind::kVariableReference:
John Stiles81365af2020-08-18 09:24:00 -0400177 this->writeVariableReference(expr.as<VariableReference>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400178 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400179 case Expression::Kind::kTernary:
John Stiles81365af2020-08-18 09:24:00 -0400180 this->writeTernaryExpression(expr.as<TernaryExpression>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400181 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400182 case Expression::Kind::kIndex:
John Stiles81365af2020-08-18 09:24:00 -0400183 this->writeIndexExpression(expr.as<IndexExpression>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400184 break;
185 default:
Ethan Nicholas2a099da2020-01-02 14:40:54 -0500186#ifdef SK_DEBUG
Ethan Nicholascc305772017-10-13 16:17:45 -0400187 ABORT("unsupported expression: %s", expr.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -0500188#endif
189 break;
Ethan Nicholascc305772017-10-13 16:17:45 -0400190 }
191}
192
Timothy Liang6403b0e2018-05-17 10:40:04 -0400193void MetalCodeGenerator::writeIntrinsicCall(const FunctionCall& c) {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400194 auto i = fIntrinsicMap.find(c.function().name());
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400195 SkASSERT(i != fIntrinsicMap.end());
Timothy Liang7d637782018-06-05 09:58:07 -0400196 Intrinsic intrinsic = i->second;
197 int32_t intrinsicId = intrinsic.second;
198 switch (intrinsic.first) {
Timothy Liang6403b0e2018-05-17 10:40:04 -0400199 case kSpecial_IntrinsicKind:
200 return this->writeSpecialIntrinsic(c, (SpecialIntrinsic) intrinsicId);
Timothy Lianga06f2152018-05-24 15:33:31 -0400201 break;
202 case kMetal_IntrinsicKind:
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400203 this->writeExpression(*c.arguments()[0], kSequence_Precedence);
Timothy Lianga06f2152018-05-24 15:33:31 -0400204 switch ((MetalIntrinsic) intrinsicId) {
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500205 case kEqual_MetalIntrinsic:
206 this->write(" == ");
207 break;
208 case kNotEqual_MetalIntrinsic:
209 this->write(" != ");
210 break;
Timothy Lianga06f2152018-05-24 15:33:31 -0400211 case kLessThan_MetalIntrinsic:
212 this->write(" < ");
213 break;
214 case kLessThanEqual_MetalIntrinsic:
215 this->write(" <= ");
216 break;
217 case kGreaterThan_MetalIntrinsic:
218 this->write(" > ");
219 break;
220 case kGreaterThanEqual_MetalIntrinsic:
221 this->write(" >= ");
222 break;
223 default:
224 ABORT("unsupported metal intrinsic kind");
225 }
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400226 this->writeExpression(*c.arguments()[1], kSequence_Precedence);
Timothy Lianga06f2152018-05-24 15:33:31 -0400227 break;
Timothy Liang6403b0e2018-05-17 10:40:04 -0400228 default:
229 ABORT("unsupported intrinsic kind");
230 }
231}
232
Ethan Nicholascc305772017-10-13 16:17:45 -0400233void MetalCodeGenerator::writeFunctionCall(const FunctionCall& c) {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400234 const FunctionDeclaration& function = c.function();
John Stiles8e3b6be2020-10-13 11:14:08 -0400235 const ExpressionArray& arguments = c.arguments();
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400236 const auto& entry = fIntrinsicMap.find(function.name());
Timothy Liang6403b0e2018-05-17 10:40:04 -0400237 if (entry != fIntrinsicMap.end()) {
238 this->writeIntrinsicCall(c);
239 return;
240 }
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400241 const StringFragment& name = function.name();
Ethan Nicholased84b732020-10-08 11:45:44 -0400242 bool builtin = function.isBuiltin();
243 if (builtin && name == "atan" && arguments.size() == 2) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400244 this->write("atan2");
Ethan Nicholased84b732020-10-08 11:45:44 -0400245 } else if (builtin && name == "inversesqrt") {
Timothy Lianga06f2152018-05-24 15:33:31 -0400246 this->write("rsqrt");
Ethan Nicholased84b732020-10-08 11:45:44 -0400247 } else if (builtin && name == "inverse") {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400248 SkASSERT(arguments.size() == 1);
249 this->writeInverseHack(*arguments[0]);
John Stilesa80a3dc2020-10-20 10:24:56 -0400250 } else if (builtin && name == "frexp") {
251 // Our Metal codegen assumes that out params are pointers, but Metal's built-in frexp
252 // actually takes a reference for the exponent, not a pointer. We add in a helper function
253 // here to translate.
254 SkASSERT(arguments.size() == 2);
255 auto [iter, newlyCreated] = fHelpers.insert("frexp");
256 if (newlyCreated) {
257 fExtraFunctions.printf(
258 "float frexp(float arg, thread int* exp) { return frexp(arg, *exp); }\n");
259 }
260 this->write("frexp");
Ethan Nicholased84b732020-10-08 11:45:44 -0400261 } else if (builtin && name == "dFdx") {
Timothy Liang7d637782018-06-05 09:58:07 -0400262 this->write("dfdx");
Ethan Nicholased84b732020-10-08 11:45:44 -0400263 } else if (builtin && name == "dFdy") {
Chris Daltonb8af5ad2019-02-25 14:54:21 -0700264 // Flipping Y also negates the Y derivatives.
265 this->write((fProgram.fSettings.fFlipY) ? "-dfdy" : "dfdy");
Ethan Nicholascc305772017-10-13 16:17:45 -0400266 } else {
Ethan Nicholase2c49992020-10-05 11:49:11 -0400267 this->writeName(name);
Ethan Nicholascc305772017-10-13 16:17:45 -0400268 }
269 this->write("(");
270 const char* separator = "";
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400271 if (this->requirements(function) & kInputs_Requirement) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400272 this->write("_in");
273 separator = ", ";
274 }
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400275 if (this->requirements(function) & kOutputs_Requirement) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400276 this->write(separator);
277 this->write("_out");
278 separator = ", ";
279 }
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400280 if (this->requirements(function) & kUniforms_Requirement) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400281 this->write(separator);
282 this->write("_uniforms");
283 separator = ", ";
284 }
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400285 if (this->requirements(function) & kGlobals_Requirement) {
Timothy Liangee84fe12018-05-18 14:38:19 -0400286 this->write(separator);
287 this->write("_globals");
288 separator = ", ";
289 }
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400290 if (this->requirements(function) & kFragCoord_Requirement) {
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -0400291 this->write(separator);
292 this->write("_fragCoord");
293 separator = ", ";
294 }
Brian Osman5bf3e202020-10-13 10:34:18 -0400295 const std::vector<const Variable*>& parameters = function.parameters();
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400296 for (size_t i = 0; i < arguments.size(); ++i) {
297 const Expression& arg = *arguments[i];
Ethan Nicholascc305772017-10-13 16:17:45 -0400298 this->write(separator);
299 separator = ", ";
Ethan Nicholased84b732020-10-08 11:45:44 -0400300 if (parameters[i]->modifiers().fFlags & Modifiers::kOut_Flag) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400301 this->write("&");
302 }
303 this->writeExpression(arg, kSequence_Precedence);
304 }
305 this->write(")");
306}
307
Chris Daltondba7aab2018-11-15 10:57:49 -0500308void MetalCodeGenerator::writeInverseHack(const Expression& mat) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400309 const Type& type = mat.type();
310 const String& typeName = type.name();
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500311 String name = typeName + "_inverse";
Ethan Nicholas30d30222020-09-11 12:27:26 -0400312 if (type == *fContext.fFloat2x2_Type || type == *fContext.fHalf2x2_Type) {
Chris Daltondba7aab2018-11-15 10:57:49 -0500313 if (fWrittenIntrinsics.find(name) == fWrittenIntrinsics.end()) {
314 fWrittenIntrinsics.insert(name);
315 fExtraFunctions.writeText((
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500316 typeName + " " + name + "(" + typeName + " m) {"
Chris Daltondba7aab2018-11-15 10:57:49 -0500317 " return float2x2(m[1][1], -m[0][1], -m[1][0], m[0][0]) * (1/determinant(m));"
318 "}"
319 ).c_str());
320 }
321 }
Ethan Nicholas30d30222020-09-11 12:27:26 -0400322 else if (type == *fContext.fFloat3x3_Type || type == *fContext.fHalf3x3_Type) {
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500323 if (fWrittenIntrinsics.find(name) == fWrittenIntrinsics.end()) {
324 fWrittenIntrinsics.insert(name);
325 fExtraFunctions.writeText((
326 typeName + " " + name + "(" + typeName + " m) {"
327 " float a00 = m[0][0], a01 = m[0][1], a02 = m[0][2];"
328 " float a10 = m[1][0], a11 = m[1][1], a12 = m[1][2];"
329 " float a20 = m[2][0], a21 = m[2][1], a22 = m[2][2];"
330 " float b01 = a22 * a11 - a12 * a21;"
331 " float b11 = -a22 * a10 + a12 * a20;"
332 " float b21 = a21 * a10 - a11 * a20;"
333 " float det = a00 * b01 + a01 * b11 + a02 * b21;"
334 " return " + typeName +
335 " (b01, (-a22 * a01 + a02 * a21), (a12 * a01 - a02 * a11),"
336 " b11, (a22 * a00 - a02 * a20), (-a12 * a00 + a02 * a10),"
337 " b21, (-a21 * a00 + a01 * a20), (a11 * a00 - a01 * a10)) * "
338 " (1/det);"
339 "}"
340 ).c_str());
341 }
342 }
Ethan Nicholas30d30222020-09-11 12:27:26 -0400343 else if (type == *fContext.fFloat4x4_Type || type == *fContext.fHalf4x4_Type) {
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500344 if (fWrittenIntrinsics.find(name) == fWrittenIntrinsics.end()) {
345 fWrittenIntrinsics.insert(name);
346 fExtraFunctions.writeText((
347 typeName + " " + name + "(" + typeName + " m) {"
348 " float a00 = m[0][0], a01 = m[0][1], a02 = m[0][2], a03 = m[0][3];"
349 " float a10 = m[1][0], a11 = m[1][1], a12 = m[1][2], a13 = m[1][3];"
350 " float a20 = m[2][0], a21 = m[2][1], a22 = m[2][2], a23 = m[2][3];"
351 " float a30 = m[3][0], a31 = m[3][1], a32 = m[3][2], a33 = m[3][3];"
352 " float b00 = a00 * a11 - a01 * a10;"
353 " float b01 = a00 * a12 - a02 * a10;"
354 " float b02 = a00 * a13 - a03 * a10;"
355 " float b03 = a01 * a12 - a02 * a11;"
356 " float b04 = a01 * a13 - a03 * a11;"
357 " float b05 = a02 * a13 - a03 * a12;"
358 " float b06 = a20 * a31 - a21 * a30;"
359 " float b07 = a20 * a32 - a22 * a30;"
360 " float b08 = a20 * a33 - a23 * a30;"
361 " float b09 = a21 * a32 - a22 * a31;"
362 " float b10 = a21 * a33 - a23 * a31;"
363 " float b11 = a22 * a33 - a23 * a32;"
364 " float det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - "
365 " b04 * b07 + b05 * b06;"
366 " return " + typeName + "(a11 * b11 - a12 * b10 + a13 * b09,"
367 " a02 * b10 - a01 * b11 - a03 * b09,"
368 " a31 * b05 - a32 * b04 + a33 * b03,"
369 " a22 * b04 - a21 * b05 - a23 * b03,"
370 " a12 * b08 - a10 * b11 - a13 * b07,"
371 " a00 * b11 - a02 * b08 + a03 * b07,"
372 " a32 * b02 - a30 * b05 - a33 * b01,"
373 " a20 * b05 - a22 * b02 + a23 * b01,"
374 " a10 * b10 - a11 * b08 + a13 * b06,"
375 " a01 * b08 - a00 * b10 - a03 * b06,"
376 " a30 * b04 - a31 * b02 + a33 * b00,"
377 " a21 * b02 - a20 * b04 - a23 * b00,"
378 " a11 * b07 - a10 * b09 - a12 * b06,"
379 " a00 * b09 - a01 * b07 + a02 * b06,"
380 " a31 * b01 - a30 * b03 - a32 * b00,"
381 " a20 * b03 - a21 * b01 + a22 * b00) / det;"
382 "}"
383 ).c_str());
384 }
385 }
Chris Daltondba7aab2018-11-15 10:57:49 -0500386 this->write(name);
387}
388
Timothy Liang6403b0e2018-05-17 10:40:04 -0400389void MetalCodeGenerator::writeSpecialIntrinsic(const FunctionCall & c, SpecialIntrinsic kind) {
John Stiles8e3b6be2020-10-13 11:14:08 -0400390 const ExpressionArray& arguments = c.arguments();
Timothy Liang6403b0e2018-05-17 10:40:04 -0400391 switch (kind) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400392 case kTexture_SpecialIntrinsic: {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400393 this->writeExpression(*arguments[0], kSequence_Precedence);
Timothy Lianga06f2152018-05-24 15:33:31 -0400394 this->write(".sample(");
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400395 this->writeExpression(*arguments[0], kSequence_Precedence);
Timothy Lianga06f2152018-05-24 15:33:31 -0400396 this->write(SAMPLER_SUFFIX);
397 this->write(", ");
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400398 const Type& arg1Type = arguments[1]->type();
Ethan Nicholas30d30222020-09-11 12:27:26 -0400399 if (arg1Type == *fContext.fFloat3_Type) {
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500400 // have to store the vector in a temp variable to avoid double evaluating it
401 String tmpVar = "tmpCoord" + to_string(fVarCount++);
Ethan Nicholas30d30222020-09-11 12:27:26 -0400402 this->fFunctionHeader += " " + this->typeName(arg1Type) + " " + tmpVar + ";\n";
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500403 this->write("(" + tmpVar + " = ");
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400404 this->writeExpression(*arguments[1], kSequence_Precedence);
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500405 this->write(", " + tmpVar + ".xy / " + tmpVar + ".z))");
Timothy Liangee84fe12018-05-18 14:38:19 -0400406 } else {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400407 SkASSERT(arg1Type == *fContext.fFloat2_Type);
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400408 this->writeExpression(*arguments[1], kSequence_Precedence);
Timothy Liangee84fe12018-05-18 14:38:19 -0400409 this->write(")");
410 }
Timothy Liang6403b0e2018-05-17 10:40:04 -0400411 break;
Ethan Nicholas30d30222020-09-11 12:27:26 -0400412 }
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500413 case kMod_SpecialIntrinsic: {
Timothy Liang651286f2018-06-07 09:55:33 -0400414 // 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 -0500415 String tmpX = "tmpX" + to_string(fVarCount++);
416 String tmpY = "tmpY" + to_string(fVarCount++);
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400417 this->fFunctionHeader += " " + this->typeName(arguments[0]->type()) +
Ethan Nicholas30d30222020-09-11 12:27:26 -0400418 " " + tmpX + ", " + tmpY + ";\n";
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500419 this->write("(" + tmpX + " = ");
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400420 this->writeExpression(*arguments[0], kSequence_Precedence);
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500421 this->write(", " + tmpY + " = ");
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400422 this->writeExpression(*arguments[1], kSequence_Precedence);
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500423 this->write(", " + tmpX + " - " + tmpY + " * floor(" + tmpX + " / " + tmpY + "))");
Timothy Liang651286f2018-06-07 09:55:33 -0400424 break;
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500425 }
Brian Osman46787d52020-11-24 14:18:23 -0500426 // GLSL declares scalar versions of most geometric intrinsics, but these don't exist in MSL
427 case kDistance_SpecialIntrinsic: {
428 if (arguments[0]->type().columns() == 1) {
429 this->write("abs(");
430 this->writeExpression(*arguments[0], kAdditive_Precedence);
431 this->write(" - ");
432 this->writeExpression(*arguments[1], kAdditive_Precedence);
433 this->write(")");
434 } else {
435 this->write("distance(");
436 this->writeExpression(*arguments[0], kSequence_Precedence);
437 this->write(", ");
438 this->writeExpression(*arguments[1], kSequence_Precedence);
439 this->write(")");
440 }
441 break;
442 }
443 case kDot_SpecialIntrinsic: {
444 if (arguments[0]->type().columns() == 1) {
445 this->write("(");
446 this->writeExpression(*arguments[0], kMultiplicative_Precedence);
447 this->write(" * ");
448 this->writeExpression(*arguments[1], kMultiplicative_Precedence);
449 this->write(")");
450 } else {
451 this->write("dot(");
452 this->writeExpression(*arguments[0], kSequence_Precedence);
453 this->write(", ");
454 this->writeExpression(*arguments[1], kSequence_Precedence);
455 this->write(")");
456 }
457 break;
458 }
459 case kLength_SpecialIntrinsic: {
460 this->write(arguments[0]->type().columns() == 1 ? "abs(" : "length(");
461 this->writeExpression(*arguments[0], kSequence_Precedence);
462 this->write(")");
463 break;
464 }
465 case kNormalize_SpecialIntrinsic: {
466 this->write(arguments[0]->type().columns() == 1 ? "sign(" : "normalize(");
467 this->writeExpression(*arguments[0], kSequence_Precedence);
468 this->write(")");
469 break;
470 }
Timothy Liang6403b0e2018-05-17 10:40:04 -0400471 default:
472 ABORT("unsupported special intrinsic kind");
473 }
474}
475
John Stilesfcf8cb22020-08-06 14:29:22 -0400476// Assembles a matrix of type floatRxC by resizing another matrix named `x0`.
477// Cells that don't exist in the source matrix will be populated with identity-matrix values.
478void MetalCodeGenerator::assembleMatrixFromMatrix(const Type& sourceMatrix, int rows, int columns) {
479 SkASSERT(rows <= 4);
480 SkASSERT(columns <= 4);
481
482 const char* columnSeparator = "";
483 for (int c = 0; c < columns; ++c) {
484 fExtraFunctions.printf("%sfloat%d(", columnSeparator, rows);
485 columnSeparator = "), ";
486
487 // Determine how many values to take from the source matrix for this row.
488 int swizzleLength = 0;
489 if (c < sourceMatrix.columns()) {
490 swizzleLength = std::min<>(rows, sourceMatrix.rows());
491 }
492
493 // Emit all the values from the source matrix row.
494 bool firstItem;
495 switch (swizzleLength) {
496 case 0: firstItem = true; break;
497 case 1: firstItem = false; fExtraFunctions.printf("x0[%d].x", c); break;
498 case 2: firstItem = false; fExtraFunctions.printf("x0[%d].xy", c); break;
499 case 3: firstItem = false; fExtraFunctions.printf("x0[%d].xyz", c); break;
500 case 4: firstItem = false; fExtraFunctions.printf("x0[%d].xyzw", c); break;
501 default: SkUNREACHABLE;
502 }
503
504 // Emit the placeholder identity-matrix cells.
505 for (int r = swizzleLength; r < rows; ++r) {
506 fExtraFunctions.printf("%s%s", firstItem ? "" : ", ", (r == c) ? "1.0" : "0.0");
507 firstItem = false;
508 }
509 }
510
511 fExtraFunctions.writeText(")");
512}
513
514// Assembles a matrix of type floatRxC by concatenating an arbitrary mix of values, named `x0`,
515// `x1`, etc. An error is written if the expression list don't contain exactly R*C scalars.
John Stiles8e3b6be2020-10-13 11:14:08 -0400516void MetalCodeGenerator::assembleMatrixFromExpressions(const ExpressionArray& args,
517 int rows, int columns) {
John Stilesfcf8cb22020-08-06 14:29:22 -0400518 size_t argIndex = 0;
519 int argPosition = 0;
520
521 const char* columnSeparator = "";
522 for (int c = 0; c < columns; ++c) {
523 fExtraFunctions.printf("%sfloat%d(", columnSeparator, rows);
524 columnSeparator = "), ";
525
526 const char* rowSeparator = "";
527 for (int r = 0; r < rows; ++r) {
528 fExtraFunctions.writeText(rowSeparator);
529 rowSeparator = ", ";
530
531 if (argIndex < args.size()) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400532 const Type& argType = args[argIndex]->type();
Ethan Nicholase6592142020-09-08 10:22:09 -0400533 switch (argType.typeKind()) {
534 case Type::TypeKind::kScalar: {
John Stilesfcf8cb22020-08-06 14:29:22 -0400535 fExtraFunctions.printf("x%zu", argIndex);
536 break;
537 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400538 case Type::TypeKind::kVector: {
John Stilesfcf8cb22020-08-06 14:29:22 -0400539 fExtraFunctions.printf("x%zu[%d]", argIndex, argPosition);
540 break;
541 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400542 case Type::TypeKind::kMatrix: {
John Stilesfcf8cb22020-08-06 14:29:22 -0400543 fExtraFunctions.printf("x%zu[%d][%d]", argIndex,
544 argPosition / argType.rows(),
545 argPosition % argType.rows());
546 break;
547 }
548 default: {
549 SkDEBUGFAIL("incorrect type of argument for matrix constructor");
550 fExtraFunctions.writeText("<error>");
551 break;
552 }
553 }
554
555 ++argPosition;
556 if (argPosition >= argType.columns() * argType.rows()) {
557 ++argIndex;
558 argPosition = 0;
559 }
560 } else {
561 SkDEBUGFAIL("not enough arguments for matrix constructor");
562 fExtraFunctions.writeText("<error>");
563 }
564 }
565 }
566
567 if (argPosition != 0 || argIndex != args.size()) {
568 SkDEBUGFAIL("incorrect number of arguments for matrix constructor");
569 fExtraFunctions.writeText(", <error>");
570 }
571
572 fExtraFunctions.writeText(")");
573}
574
John Stiles1bdafbf2020-05-28 12:17:20 -0400575// Generates a constructor for 'matrix' which reorganizes the input arguments into the proper shape.
576// Keeps track of previously generated constructors so that we won't generate more than one
577// constructor for any given permutation of input argument types. Returns the name of the
578// generated constructor method.
579String MetalCodeGenerator::getMatrixConstructHelper(const Constructor& c) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400580 const Type& matrix = c.type();
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500581 int columns = matrix.columns();
582 int rows = matrix.rows();
John Stiles8e3b6be2020-10-13 11:14:08 -0400583 const ExpressionArray& args = c.arguments();
John Stiles1bdafbf2020-05-28 12:17:20 -0400584
585 // Create the helper-method name and use it as our lookup key.
586 String name;
587 name.appendf("float%dx%d_from", columns, rows);
588 for (const std::unique_ptr<Expression>& expr : args) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400589 name.appendf("_%s", expr->type().displayName().c_str());
John Stiles1bdafbf2020-05-28 12:17:20 -0400590 }
591
592 // If a helper-method has already been synthesized, we don't need to synthesize it again.
593 auto [iter, newlyCreated] = fHelpers.insert(name);
594 if (!newlyCreated) {
595 return name;
596 }
597
598 // Unlike GLSL, Metal requires that matrices are initialized with exactly R vectors of C
599 // components apiece. (In Metal 2.0, you can also supply R*C scalars, but you still cannot
600 // supply a mixture of scalars and vectors.)
601 fExtraFunctions.printf("float%dx%d %s(", columns, rows, name.c_str());
602
603 size_t argIndex = 0;
604 const char* argSeparator = "";
John Stilesfcf8cb22020-08-06 14:29:22 -0400605 for (const std::unique_ptr<Expression>& expr : args) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400606 fExtraFunctions.printf("%s%s x%zu", argSeparator,
Ethan Nicholas30d30222020-09-11 12:27:26 -0400607 expr->type().displayName().c_str(), argIndex++);
John Stiles1bdafbf2020-05-28 12:17:20 -0400608 argSeparator = ", ";
609 }
610
611 fExtraFunctions.printf(") {\n return float%dx%d(", columns, rows);
612
John Stiles9aeed132020-11-24 17:36:06 -0500613 if (args.size() == 1 && args.front()->type().isMatrix()) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400614 this->assembleMatrixFromMatrix(args.front()->type(), rows, columns);
John Stilesfcf8cb22020-08-06 14:29:22 -0400615 } else {
616 this->assembleMatrixFromExpressions(args, rows, columns);
John Stiles1bdafbf2020-05-28 12:17:20 -0400617 }
618
John Stilesfcf8cb22020-08-06 14:29:22 -0400619 fExtraFunctions.writeText(");\n}\n");
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500620 return name;
621}
622
623bool MetalCodeGenerator::canCoerce(const Type& t1, const Type& t2) {
624 if (t1.columns() != t2.columns() || t1.rows() != t2.rows()) {
625 return false;
626 }
627 if (t1.columns() > 1) {
628 return this->canCoerce(t1.componentType(), t2.componentType());
629 }
Ethan Nicholase1f55022019-02-05 17:17:40 -0500630 return t1.isFloat() && t2.isFloat();
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500631}
632
John Stiles1bdafbf2020-05-28 12:17:20 -0400633bool MetalCodeGenerator::matrixConstructHelperIsNeeded(const Constructor& c) {
634 // A matrix construct helper is only necessary if we are, in fact, constructing a matrix.
John Stiles9aeed132020-11-24 17:36:06 -0500635 if (!c.type().isMatrix()) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400636 return false;
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500637 }
John Stiles1bdafbf2020-05-28 12:17:20 -0400638
639 // GLSL is fairly free-form about inputs to its matrix constructors, but Metal is not; it
640 // expects exactly R vectors of C components apiece. (Metal 2.0 also allows a list of R*C
641 // scalars.) Some cases are simple to translate and so we handle those inline--e.g. a list of
642 // scalars can be constructed trivially. In more complex cases, we generate a helper function
643 // that converts our inputs into a properly-shaped matrix.
644 // A matrix construct helper method is always used if any input argument is a matrix.
645 // Helper methods are also necessary when any argument would span multiple rows. For instance:
646 //
647 // float2 x = (1, 2);
648 // float3x2(x, 3, 4, 5, 6) = | 1 3 5 | = no helper needed; conversion can be done inline
649 // | 2 4 6 |
650 //
651 // float2 x = (2, 3);
652 // float3x2(1, x, 4, 5, 6) = | 1 3 5 | = x spans multiple rows; a helper method will be used
653 // | 2 4 6 |
654 //
655 // float4 x = (1, 2, 3, 4);
656 // float2x2(x) = | 1 3 | = x spans multiple rows; a helper method will be used
657 // | 2 4 |
658 //
659
660 int position = 0;
Ethan Nicholasf70f0442020-09-29 12:41:35 -0400661 for (const std::unique_ptr<Expression>& expr : c.arguments()) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400662 // If an input argument is a matrix, we need a helper function.
John Stiles9aeed132020-11-24 17:36:06 -0500663 if (expr->type().isMatrix()) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400664 return true;
665 }
Ethan Nicholas30d30222020-09-11 12:27:26 -0400666 position += expr->type().columns();
667 if (position > c.type().rows()) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400668 // An input argument would span multiple rows; a helper function is required.
669 return true;
670 }
Ethan Nicholas30d30222020-09-11 12:27:26 -0400671 if (position == c.type().rows()) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400672 // We've advanced to the end of a row. Wrap to the start of the next row.
673 position = 0;
674 }
675 }
676
677 return false;
678}
679
680void MetalCodeGenerator::writeConstructor(const Constructor& c, Precedence parentPrecedence) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400681 const Type& constructorType = c.type();
John Stiles1bdafbf2020-05-28 12:17:20 -0400682 // Handle special cases for single-argument constructors.
Ethan Nicholasf70f0442020-09-29 12:41:35 -0400683 if (c.arguments().size() == 1) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400684 // If the type is coercible, emit it directly.
Ethan Nicholasf70f0442020-09-29 12:41:35 -0400685 const Expression& arg = *c.arguments().front();
Ethan Nicholas30d30222020-09-11 12:27:26 -0400686 const Type& argType = arg.type();
687 if (this->canCoerce(constructorType, argType)) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400688 this->writeExpression(arg, parentPrecedence);
689 return;
690 }
691
692 // Metal supports creating matrices with a scalar on the diagonal via the single-argument
693 // matrix constructor.
John Stiles9aeed132020-11-24 17:36:06 -0500694 if (constructorType.isMatrix() && argType.isNumber()) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400695 const Type& matrix = constructorType;
John Stiles1bdafbf2020-05-28 12:17:20 -0400696 this->write("float");
697 this->write(to_string(matrix.columns()));
698 this->write("x");
699 this->write(to_string(matrix.rows()));
700 this->write("(");
701 this->writeExpression(arg, parentPrecedence);
702 this->write(")");
703 return;
704 }
705 }
706
707 // Emit and invoke a matrix-constructor helper method if one is necessary.
708 if (this->matrixConstructHelperIsNeeded(c)) {
709 this->write(this->getMatrixConstructHelper(c));
John Stiles1fa15b12020-05-28 17:36:54 +0000710 this->write("(");
711 const char* separator = "";
Ethan Nicholasf70f0442020-09-29 12:41:35 -0400712 for (const std::unique_ptr<Expression>& expr : c.arguments()) {
John Stiles1fa15b12020-05-28 17:36:54 +0000713 this->write(separator);
714 separator = ", ";
John Stiles1bdafbf2020-05-28 12:17:20 -0400715 this->writeExpression(*expr, kSequence_Precedence);
John Stilesdaa573e2020-05-28 12:17:20 -0400716 }
John Stiles1fa15b12020-05-28 17:36:54 +0000717 this->write(")");
John Stiles1bdafbf2020-05-28 12:17:20 -0400718 return;
John Stilesdaa573e2020-05-28 12:17:20 -0400719 }
John Stiles1bdafbf2020-05-28 12:17:20 -0400720
721 // Explicitly invoke the constructor, passing in the necessary arguments.
Ethan Nicholas30d30222020-09-11 12:27:26 -0400722 this->writeType(constructorType);
John Stiles1bdafbf2020-05-28 12:17:20 -0400723 this->write("(");
724 const char* separator = "";
725 int scalarCount = 0;
Ethan Nicholasf70f0442020-09-29 12:41:35 -0400726 for (const std::unique_ptr<Expression>& arg : c.arguments()) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400727 const Type& argType = arg->type();
John Stiles1bdafbf2020-05-28 12:17:20 -0400728 this->write(separator);
729 separator = ", ";
John Stiles9aeed132020-11-24 17:36:06 -0500730 if (constructorType.isMatrix() &&
Ethan Nicholas30d30222020-09-11 12:27:26 -0400731 argType.columns() < constructorType.rows()) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400732 // Merge scalars and smaller vectors together.
733 if (!scalarCount) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400734 this->writeType(constructorType.componentType());
735 this->write(to_string(constructorType.rows()));
John Stiles1bdafbf2020-05-28 12:17:20 -0400736 this->write("(");
737 }
Ethan Nicholas30d30222020-09-11 12:27:26 -0400738 scalarCount += argType.columns();
John Stiles1bdafbf2020-05-28 12:17:20 -0400739 }
740 this->writeExpression(*arg, kSequence_Precedence);
Ethan Nicholas30d30222020-09-11 12:27:26 -0400741 if (scalarCount && scalarCount == constructorType.rows()) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400742 this->write(")");
743 scalarCount = 0;
744 }
745 }
746 this->write(")");
Ethan Nicholascc305772017-10-13 16:17:45 -0400747}
748
749void MetalCodeGenerator::writeFragCoord() {
Ethan Nicholasf931e402019-07-26 15:40:33 -0400750 if (fRTHeightName.length()) {
751 this->write("float4(_fragCoord.x, ");
752 this->write(fRTHeightName.c_str());
753 this->write(" - _fragCoord.y, 0.0, _fragCoord.w)");
Jim Van Verth6bc650e2019-02-07 14:53:23 -0500754 } else {
755 this->write("float4(_fragCoord.x, _fragCoord.y, 0.0, _fragCoord.w)");
756 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400757}
758
759void MetalCodeGenerator::writeVariableReference(const VariableReference& ref) {
Ethan Nicholas78686922020-10-08 06:46:27 -0400760 switch (ref.variable()->modifiers().fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400761 case SK_FRAGCOLOR_BUILTIN:
Timothy Liang7d637782018-06-05 09:58:07 -0400762 this->write("_out->sk_FragColor");
Ethan Nicholascc305772017-10-13 16:17:45 -0400763 break;
Timothy Liang6403b0e2018-05-17 10:40:04 -0400764 case SK_FRAGCOORD_BUILTIN:
765 this->writeFragCoord();
766 break;
Timothy Liangdc89f192018-06-13 09:20:31 -0400767 case SK_VERTEXID_BUILTIN:
768 this->write("sk_VertexID");
769 break;
770 case SK_INSTANCEID_BUILTIN:
771 this->write("sk_InstanceID");
772 break;
Timothy Liang7b8875d2018-08-10 09:42:31 -0400773 case SK_CLOCKWISE_BUILTIN:
774 // We'd set the front facing winding in the MTLRenderCommandEncoder to be counter
Brian Salomonf4ba4ec2020-03-19 15:54:28 -0400775 // clockwise to match Skia convention.
Timothy Liang7b8875d2018-08-10 09:42:31 -0400776 this->write(fProgram.fSettings.fFlipY ? "_frontFacing" : "(!_frontFacing)");
777 break;
Ethan Nicholascc305772017-10-13 16:17:45 -0400778 default:
Ethan Nicholas78686922020-10-08 06:46:27 -0400779 const Variable& var = *ref.variable();
Ethan Nicholas453f67f2020-10-09 10:43:45 -0400780 if (var.storage() == Variable::Storage::kGlobal) {
Ethan Nicholas78686922020-10-08 06:46:27 -0400781 if (var.modifiers().fFlags & Modifiers::kIn_Flag) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400782 this->write("_in.");
Ethan Nicholas78686922020-10-08 06:46:27 -0400783 } else if (var.modifiers().fFlags & Modifiers::kOut_Flag) {
Timothy Liangee84fe12018-05-18 14:38:19 -0400784 this->write("_out->");
Ethan Nicholas78686922020-10-08 06:46:27 -0400785 } else if (var.modifiers().fFlags & Modifiers::kUniform_Flag &&
786 var.type().typeKind() != Type::TypeKind::kSampler) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400787 this->write("_uniforms.");
788 } else {
Timothy Liangee84fe12018-05-18 14:38:19 -0400789 this->write("_globals->");
Ethan Nicholascc305772017-10-13 16:17:45 -0400790 }
791 }
Ethan Nicholas78686922020-10-08 06:46:27 -0400792 this->writeName(var.name());
Ethan Nicholascc305772017-10-13 16:17:45 -0400793 }
794}
795
796void MetalCodeGenerator::writeIndexExpression(const IndexExpression& expr) {
Ethan Nicholas2a4952d2020-10-08 15:35:56 -0400797 this->writeExpression(*expr.base(), kPostfix_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400798 this->write("[");
Ethan Nicholas2a4952d2020-10-08 15:35:56 -0400799 this->writeExpression(*expr.index(), kTopLevel_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400800 this->write("]");
801}
802
803void MetalCodeGenerator::writeFieldAccess(const FieldAccess& f) {
Ethan Nicholas7a95b202020-10-09 11:55:40 -0400804 const Type::Field* field = &f.base()->type().fields()[f.fieldIndex()];
805 if (FieldAccess::OwnerKind::kDefault == f.ownerKind()) {
806 this->writeExpression(*f.base(), kPostfix_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400807 this->write(".");
808 }
Timothy Liang7d637782018-06-05 09:58:07 -0400809 switch (field->fModifiers.fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400810 case SK_POSITION_BUILTIN:
Timothy Liangb8eeb802018-07-23 16:46:16 -0400811 this->write("_out->sk_Position");
Ethan Nicholascc305772017-10-13 16:17:45 -0400812 break;
813 default:
Timothy Liang7d637782018-06-05 09:58:07 -0400814 if (field->fName == "sk_PointSize") {
815 this->write("_out->sk_PointSize");
816 } else {
Ethan Nicholas7a95b202020-10-09 11:55:40 -0400817 if (FieldAccess::OwnerKind::kAnonymousInterfaceBlock == f.ownerKind()) {
Timothy Liang7d637782018-06-05 09:58:07 -0400818 this->write("_globals->");
819 this->write(fInterfaceBlockNameMap[fInterfaceBlockMap[field]]);
820 this->write("->");
821 }
Timothy Liang651286f2018-06-07 09:55:33 -0400822 this->writeName(field->fName);
Timothy Lianga06f2152018-05-24 15:33:31 -0400823 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400824 }
825}
826
827void MetalCodeGenerator::writeSwizzle(const Swizzle& swizzle) {
Ethan Nicholas6b4d5812020-10-12 16:11:51 -0400828 this->writeExpression(*swizzle.base(), kPostfix_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400829 this->write(".");
Ethan Nicholas6b4d5812020-10-12 16:11:51 -0400830 for (int c : swizzle.components()) {
Brian Osman25647672020-09-15 15:16:56 -0400831 SkASSERT(c >= 0 && c <= 3);
832 this->write(&("x\0y\0z\0w\0"[c * 2]));
Ethan Nicholascc305772017-10-13 16:17:45 -0400833 }
834}
835
836MetalCodeGenerator::Precedence MetalCodeGenerator::GetBinaryPrecedence(Token::Kind op) {
837 switch (op) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400838 case Token::Kind::TK_STAR: // fall through
839 case Token::Kind::TK_SLASH: // fall through
840 case Token::Kind::TK_PERCENT: return MetalCodeGenerator::kMultiplicative_Precedence;
841 case Token::Kind::TK_PLUS: // fall through
842 case Token::Kind::TK_MINUS: return MetalCodeGenerator::kAdditive_Precedence;
843 case Token::Kind::TK_SHL: // fall through
844 case Token::Kind::TK_SHR: return MetalCodeGenerator::kShift_Precedence;
845 case Token::Kind::TK_LT: // fall through
846 case Token::Kind::TK_GT: // fall through
847 case Token::Kind::TK_LTEQ: // fall through
848 case Token::Kind::TK_GTEQ: return MetalCodeGenerator::kRelational_Precedence;
849 case Token::Kind::TK_EQEQ: // fall through
850 case Token::Kind::TK_NEQ: return MetalCodeGenerator::kEquality_Precedence;
851 case Token::Kind::TK_BITWISEAND: return MetalCodeGenerator::kBitwiseAnd_Precedence;
852 case Token::Kind::TK_BITWISEXOR: return MetalCodeGenerator::kBitwiseXor_Precedence;
853 case Token::Kind::TK_BITWISEOR: return MetalCodeGenerator::kBitwiseOr_Precedence;
854 case Token::Kind::TK_LOGICALAND: return MetalCodeGenerator::kLogicalAnd_Precedence;
855 case Token::Kind::TK_LOGICALXOR: return MetalCodeGenerator::kLogicalXor_Precedence;
856 case Token::Kind::TK_LOGICALOR: return MetalCodeGenerator::kLogicalOr_Precedence;
857 case Token::Kind::TK_EQ: // fall through
858 case Token::Kind::TK_PLUSEQ: // fall through
859 case Token::Kind::TK_MINUSEQ: // fall through
860 case Token::Kind::TK_STAREQ: // fall through
861 case Token::Kind::TK_SLASHEQ: // fall through
862 case Token::Kind::TK_PERCENTEQ: // fall through
863 case Token::Kind::TK_SHLEQ: // fall through
864 case Token::Kind::TK_SHREQ: // fall through
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400865 case Token::Kind::TK_BITWISEANDEQ: // fall through
866 case Token::Kind::TK_BITWISEXOREQ: // fall through
867 case Token::Kind::TK_BITWISEOREQ: return MetalCodeGenerator::kAssignment_Precedence;
868 case Token::Kind::TK_COMMA: return MetalCodeGenerator::kSequence_Precedence;
Ethan Nicholascc305772017-10-13 16:17:45 -0400869 default: ABORT("unsupported binary operator");
870 }
871}
872
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500873void MetalCodeGenerator::writeMatrixTimesEqualHelper(const Type& left, const Type& right,
874 const Type& result) {
875 String key = "TimesEqual" + left.name() + right.name();
876 if (fHelpers.find(key) == fHelpers.end()) {
877 fExtraFunctions.printf("%s operator*=(thread %s& left, thread const %s& right) {\n"
878 " left = left * right;\n"
879 " return left;\n"
Ethan Nicholase2c49992020-10-05 11:49:11 -0400880 "}", String(result.name()).c_str(), String(left.name()).c_str(),
881 String(right.name()).c_str());
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500882 }
883}
884
Ethan Nicholascc305772017-10-13 16:17:45 -0400885void MetalCodeGenerator::writeBinaryExpression(const BinaryExpression& b,
886 Precedence parentPrecedence) {
John Stiles2d4f9592020-10-30 10:29:12 -0400887 const Expression& left = *b.left();
888 const Expression& right = *b.right();
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400889 const Type& leftType = left.type();
890 const Type& rightType = right.type();
891 Token::Kind op = b.getOperator();
892 Precedence precedence = GetBinaryPrecedence(b.getOperator());
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500893 bool needParens = precedence >= parentPrecedence;
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400894 switch (op) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400895 case Token::Kind::TK_EQEQ:
John Stiles9aeed132020-11-24 17:36:06 -0500896 if (leftType.isVector()) {
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500897 this->write("all");
898 needParens = true;
899 }
900 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400901 case Token::Kind::TK_NEQ:
John Stiles9aeed132020-11-24 17:36:06 -0500902 if (leftType.isVector()) {
Jim Van Verth36477b42019-04-11 14:57:30 -0400903 this->write("any");
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500904 needParens = true;
905 }
906 break;
907 default:
908 break;
909 }
910 if (needParens) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400911 this->write("(");
912 }
Brian Osman79457ef2020-09-24 15:01:27 -0400913 if (Compiler::IsAssignment(op) && left.is<VariableReference>() &&
Ethan Nicholas453f67f2020-10-09 10:43:45 -0400914 left.as<VariableReference>().variable()->storage() == Variable::Storage::kParameter &&
Ethan Nicholas78686922020-10-08 06:46:27 -0400915 left.as<VariableReference>().variable()->modifiers().fFlags & Modifiers::kOut_Flag) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400916 // writing to an out parameter. Since we have to turn those into pointers, we have to
917 // dereference it here.
918 this->write("*");
919 }
John Stiles9aeed132020-11-24 17:36:06 -0500920 if (op == Token::Kind::TK_STAREQ && leftType.isMatrix() && rightType.isMatrix()) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400921 this->writeMatrixTimesEqualHelper(leftType, rightType, b.type());
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500922 }
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400923 this->writeExpression(left, precedence);
924 if (op != Token::Kind::TK_EQ && Compiler::IsAssignment(op) &&
925 left.kind() == Expression::Kind::kSwizzle && !left.hasSideEffects()) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400926 // This doesn't compile in Metal:
927 // float4 x = float4(1);
928 // x.xy *= float2x2(...);
929 // with the error message "non-const reference cannot bind to vector element",
930 // but switching it to x.xy = x.xy * float2x2(...) fixes it. We perform this tranformation
931 // as long as the LHS has no side effects, and hope for the best otherwise.
932 this->write(" = ");
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400933 this->writeExpression(left, kAssignment_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400934 this->write(" ");
John Stilesd6449e92020-11-30 09:13:23 -0500935 String opName = OperatorName(op);
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400936 SkASSERT(opName.endsWith("="));
937 this->write(opName.substr(0, opName.size() - 1).c_str());
Ethan Nicholascc305772017-10-13 16:17:45 -0400938 this->write(" ");
939 } else {
John Stilesd6449e92020-11-30 09:13:23 -0500940 this->write(String(" ") + OperatorName(op) + " ");
Ethan Nicholascc305772017-10-13 16:17:45 -0400941 }
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400942 this->writeExpression(right, precedence);
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500943 if (needParens) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400944 this->write(")");
945 }
946}
947
948void MetalCodeGenerator::writeTernaryExpression(const TernaryExpression& t,
949 Precedence parentPrecedence) {
950 if (kTernary_Precedence >= parentPrecedence) {
951 this->write("(");
952 }
Ethan Nicholasdd218162020-10-08 05:48:01 -0400953 this->writeExpression(*t.test(), kTernary_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400954 this->write(" ? ");
Ethan Nicholasdd218162020-10-08 05:48:01 -0400955 this->writeExpression(*t.ifTrue(), kTernary_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400956 this->write(" : ");
Ethan Nicholasdd218162020-10-08 05:48:01 -0400957 this->writeExpression(*t.ifFalse(), kTernary_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400958 if (kTernary_Precedence >= parentPrecedence) {
959 this->write(")");
960 }
961}
962
963void MetalCodeGenerator::writePrefixExpression(const PrefixExpression& p,
964 Precedence parentPrecedence) {
965 if (kPrefix_Precedence >= parentPrecedence) {
966 this->write("(");
967 }
John Stilesd6449e92020-11-30 09:13:23 -0500968 this->write(OperatorName(p.getOperator()));
Ethan Nicholas444ccc62020-10-09 10:16:22 -0400969 this->writeExpression(*p.operand(), kPrefix_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400970 if (kPrefix_Precedence >= parentPrecedence) {
971 this->write(")");
972 }
973}
974
975void MetalCodeGenerator::writePostfixExpression(const PostfixExpression& p,
976 Precedence parentPrecedence) {
977 if (kPostfix_Precedence >= parentPrecedence) {
978 this->write("(");
979 }
Ethan Nicholas444ccc62020-10-09 10:16:22 -0400980 this->writeExpression(*p.operand(), kPostfix_Precedence);
John Stilesd6449e92020-11-30 09:13:23 -0500981 this->write(OperatorName(p.getOperator()));
Ethan Nicholascc305772017-10-13 16:17:45 -0400982 if (kPostfix_Precedence >= parentPrecedence) {
983 this->write(")");
984 }
985}
986
987void MetalCodeGenerator::writeBoolLiteral(const BoolLiteral& b) {
Ethan Nicholas59d660c2020-09-28 09:18:15 -0400988 this->write(b.value() ? "true" : "false");
Ethan Nicholascc305772017-10-13 16:17:45 -0400989}
990
991void MetalCodeGenerator::writeIntLiteral(const IntLiteral& i) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400992 if (i.type() == *fContext.fUInt_Type) {
Ethan Nicholase96cdd12020-09-28 16:27:18 -0400993 this->write(to_string(i.value() & 0xffffffff) + "u");
Ethan Nicholascc305772017-10-13 16:17:45 -0400994 } else {
Ethan Nicholase96cdd12020-09-28 16:27:18 -0400995 this->write(to_string((int32_t) i.value()));
Ethan Nicholascc305772017-10-13 16:17:45 -0400996 }
997}
998
999void MetalCodeGenerator::writeFloatLiteral(const FloatLiteral& f) {
Ethan Nicholasa3f22f12020-10-01 12:13:17 -04001000 this->write(to_string(f.value()));
Ethan Nicholascc305772017-10-13 16:17:45 -04001001}
1002
1003void MetalCodeGenerator::writeSetting(const Setting& s) {
1004 ABORT("internal error; setting was not folded to a constant during compilation\n");
1005}
1006
John Stiles569249b2020-11-03 12:18:22 -05001007bool MetalCodeGenerator::writeFunctionDeclaration(const FunctionDeclaration& f) {
Ethan Nicholasf931e402019-07-26 15:40:33 -04001008 fRTHeightName = fProgram.fInputs.fRTHeight ? "_globals->_anonInterface0->u_skRTHeight" : "";
Ethan Nicholascc305772017-10-13 16:17:45 -04001009 const char* separator = "";
John Stiles569249b2020-11-03 12:18:22 -05001010 if ("main" == f.name()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001011 switch (fProgram.fKind) {
1012 case Program::kFragment_Kind:
Timothy Liangb8eeb802018-07-23 16:46:16 -04001013 this->write("fragment Outputs fragmentMain");
Ethan Nicholascc305772017-10-13 16:17:45 -04001014 break;
1015 case Program::kVertex_Kind:
Timothy Liangb8eeb802018-07-23 16:46:16 -04001016 this->write("vertex Outputs vertexMain");
Ethan Nicholascc305772017-10-13 16:17:45 -04001017 break;
1018 default:
John Stiles3fabfc02020-09-25 15:51:28 -04001019 fErrors.error(-1, "unsupported kind of program");
John Stiles569249b2020-11-03 12:18:22 -05001020 return false;
Ethan Nicholascc305772017-10-13 16:17:45 -04001021 }
1022 this->write("(Inputs _in [[stage_in]]");
1023 if (-1 != fUniformBuffer) {
1024 this->write(", constant Uniforms& _uniforms [[buffer(" +
1025 to_string(fUniformBuffer) + ")]]");
1026 }
Brian Osman133724c2020-10-28 14:14:39 -04001027 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04001028 if (e->is<GlobalVarDeclaration>()) {
1029 const GlobalVarDeclaration& decls = e->as<GlobalVarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001030 const VarDeclaration& var = decls.declaration()->as<VarDeclaration>();
1031 if (var.var().type().typeKind() == Type::TypeKind::kSampler) {
1032 if (var.var().modifiers().fLayout.fBinding < 0) {
Brian Osmanc0213602020-10-06 14:43:32 -04001033 fErrors.error(decls.fOffset,
1034 "Metal samplers must have 'layout(binding=...)'");
John Stiles569249b2020-11-03 12:18:22 -05001035 return false;
Timothy Liangee84fe12018-05-18 14:38:19 -04001036 }
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001037 if (var.var().type().dimensions() != SpvDim2D) {
John Stiles569249b2020-11-03 12:18:22 -05001038 // Not yet implemented--Skia currently only uses 2D textures.
Brian Osmanc0213602020-10-06 14:43:32 -04001039 fErrors.error(decls.fOffset, "Unsupported texture dimensions");
John Stiles569249b2020-11-03 12:18:22 -05001040 return false;
Brian Osmanc0213602020-10-06 14:43:32 -04001041 }
1042 this->write(", texture2d<float> ");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001043 this->writeName(var.var().name());
Brian Osmanc0213602020-10-06 14:43:32 -04001044 this->write("[[texture(");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001045 this->write(to_string(var.var().modifiers().fLayout.fBinding));
Brian Osmanc0213602020-10-06 14:43:32 -04001046 this->write(")]]");
1047 this->write(", sampler ");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001048 this->writeName(var.var().name());
Brian Osmanc0213602020-10-06 14:43:32 -04001049 this->write(SAMPLER_SUFFIX);
1050 this->write("[[sampler(");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001051 this->write(to_string(var.var().modifiers().fLayout.fBinding));
Brian Osmanc0213602020-10-06 14:43:32 -04001052 this->write(")]]");
Timothy Liang6403b0e2018-05-17 10:40:04 -04001053 }
Brian Osman1179fcf2020-10-08 16:04:40 -04001054 } else if (e->is<InterfaceBlock>()) {
1055 const InterfaceBlock& intf = e->as<InterfaceBlock>();
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001056 if (intf.typeName() == "sk_PerVertex") {
Timothy Lianga06f2152018-05-24 15:33:31 -04001057 continue;
1058 }
1059 this->write(", constant ");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001060 this->writeType(intf.variable().type());
Timothy Lianga06f2152018-05-24 15:33:31 -04001061 this->write("& " );
1062 this->write(fInterfaceBlockNameMap[&intf]);
1063 this->write(" [[buffer(");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001064 this->write(to_string(intf.variable().modifiers().fLayout.fBinding));
Timothy Lianga06f2152018-05-24 15:33:31 -04001065 this->write(")]]");
Timothy Liang6403b0e2018-05-17 10:40:04 -04001066 }
1067 }
Jim Van Verth6bc650e2019-02-07 14:53:23 -05001068 if (fProgram.fKind == Program::kFragment_Kind) {
1069 if (fProgram.fInputs.fRTHeight && fInterfaceBlockNameMap.empty()) {
Timothy Liang5422f9a2018-08-10 10:57:55 -04001070 this->write(", constant sksl_synthetic_uniforms& _anonInterface0 [[buffer(1)]]");
Ethan Nicholasf931e402019-07-26 15:40:33 -04001071 fRTHeightName = "_anonInterface0.u_skRTHeight";
Timothy Liang5422f9a2018-08-10 10:57:55 -04001072 }
Timothy Liang7b8875d2018-08-10 09:42:31 -04001073 this->write(", bool _frontFacing [[front_facing]]");
Timothy Liang7d637782018-06-05 09:58:07 -04001074 this->write(", float4 _fragCoord [[position]]");
Timothy Liangdc89f192018-06-13 09:20:31 -04001075 } else if (fProgram.fKind == Program::kVertex_Kind) {
1076 this->write(", uint sk_VertexID [[vertex_id]], uint sk_InstanceID [[instance_id]]");
Timothy Liang7d637782018-06-05 09:58:07 -04001077 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001078 separator = ", ";
1079 } else {
John Stiles569249b2020-11-03 12:18:22 -05001080 this->writeType(f.returnType());
Timothy Liang651286f2018-06-07 09:55:33 -04001081 this->write(" ");
John Stiles569249b2020-11-03 12:18:22 -05001082 this->writeName(f.name());
Timothy Liang651286f2018-06-07 09:55:33 -04001083 this->write("(");
John Stiles569249b2020-11-03 12:18:22 -05001084 Requirements requirements = this->requirements(f);
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -04001085 if (requirements & kInputs_Requirement) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001086 this->write("Inputs _in");
1087 separator = ", ";
1088 }
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -04001089 if (requirements & kOutputs_Requirement) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001090 this->write(separator);
Timothy Liangee84fe12018-05-18 14:38:19 -04001091 this->write("thread Outputs* _out");
Ethan Nicholascc305772017-10-13 16:17:45 -04001092 separator = ", ";
1093 }
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -04001094 if (requirements & kUniforms_Requirement) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001095 this->write(separator);
1096 this->write("Uniforms _uniforms");
1097 separator = ", ";
1098 }
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -04001099 if (requirements & kGlobals_Requirement) {
Timothy Liangee84fe12018-05-18 14:38:19 -04001100 this->write(separator);
1101 this->write("thread Globals* _globals");
1102 separator = ", ";
1103 }
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -04001104 if (requirements & kFragCoord_Requirement) {
1105 this->write(separator);
1106 this->write("float4 _fragCoord");
1107 separator = ", ";
1108 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001109 }
John Stiles569249b2020-11-03 12:18:22 -05001110 for (const auto& param : f.parameters()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001111 this->write(separator);
1112 separator = ", ";
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001113 this->writeModifiers(param->modifiers(), false);
Ethan Nicholascc305772017-10-13 16:17:45 -04001114 std::vector<int> sizes;
Ethan Nicholas30d30222020-09-11 12:27:26 -04001115 const Type* type = &param->type();
Ethan Nicholase6592142020-09-08 10:22:09 -04001116 while (type->typeKind() == Type::TypeKind::kArray) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001117 sizes.push_back(type->columns());
1118 type = &type->componentType();
1119 }
1120 this->writeType(*type);
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001121 if (param->modifiers().fFlags & Modifiers::kOut_Flag) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001122 this->write("*");
1123 }
Timothy Liang651286f2018-06-07 09:55:33 -04001124 this->write(" ");
Ethan Nicholase2c49992020-10-05 11:49:11 -04001125 this->writeName(param->name());
Ethan Nicholascc305772017-10-13 16:17:45 -04001126 for (int s : sizes) {
Brian Osmane8c26082020-10-01 17:22:45 -04001127 if (s == Type::kUnsizedArray) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001128 this->write("[]");
1129 } else {
1130 this->write("[" + to_string(s) + "]");
1131 }
1132 }
1133 }
John Stiles569249b2020-11-03 12:18:22 -05001134 this->write(")");
1135 return true;
1136}
Ethan Nicholascc305772017-10-13 16:17:45 -04001137
John Stiles569249b2020-11-03 12:18:22 -05001138void MetalCodeGenerator::writeFunctionPrototype(const FunctionPrototype& f) {
1139 this->writeFunctionDeclaration(f.declaration());
1140 this->writeLine(";");
1141}
1142
1143void MetalCodeGenerator::writeFunction(const FunctionDefinition& f) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001144 SkASSERT(!fProgram.fSettings.fFragColorIsInOut);
Brian Salomondc092132018-04-04 10:14:16 -04001145
John Stiles569249b2020-11-03 12:18:22 -05001146 if (!this->writeFunctionDeclaration(f.declaration())) {
1147 return;
1148 }
1149
1150 this->writeLine(" {");
1151
Ethan Nicholas0a5d0962020-10-14 13:33:18 -04001152 if (f.declaration().name() == "main") {
John Stilescdcdb042020-07-06 09:03:51 -04001153 this->writeGlobalInit();
Timothy Liang7d637782018-06-05 09:58:07 -04001154 this->writeLine(" Outputs _outputStruct;");
1155 this->writeLine(" thread Outputs* _out = &_outputStruct;");
Ethan Nicholascc305772017-10-13 16:17:45 -04001156 }
John Stilesc67b3622020-05-28 17:53:13 -04001157
Ethan Nicholascc305772017-10-13 16:17:45 -04001158 fFunctionHeader = "";
1159 OutputStream* oldOut = fOut;
1160 StringStream buffer;
1161 fOut = &buffer;
1162 fIndentation++;
Ethan Nicholas0a5d0962020-10-14 13:33:18 -04001163 for (const std::unique_ptr<Statement>& stmt : f.body()->as<Block>().children()) {
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001164 if (!stmt->isEmpty()) {
1165 this->writeStatement(*stmt);
1166 this->writeLine();
1167 }
1168 }
Ethan Nicholas0a5d0962020-10-14 13:33:18 -04001169 if (f.declaration().name() == "main") {
Ethan Nicholascc305772017-10-13 16:17:45 -04001170 switch (fProgram.fKind) {
1171 case Program::kFragment_Kind:
Timothy Liang7d637782018-06-05 09:58:07 -04001172 this->writeLine("return *_out;");
Ethan Nicholascc305772017-10-13 16:17:45 -04001173 break;
1174 case Program::kVertex_Kind:
Timothy Liangb8eeb802018-07-23 16:46:16 -04001175 this->writeLine("_out->sk_Position.y = -_out->sk_Position.y;");
Timothy Lianga06f2152018-05-24 15:33:31 -04001176 this->writeLine("return *_out;"); // FIXME - detect if function already has return
Ethan Nicholascc305772017-10-13 16:17:45 -04001177 break;
1178 default:
John Stilesf7d70432020-05-28 15:46:38 -04001179 SkDEBUGFAIL("unsupported kind of program");
Ethan Nicholascc305772017-10-13 16:17:45 -04001180 }
1181 }
1182 fIndentation--;
1183 this->writeLine("}");
1184
1185 fOut = oldOut;
1186 this->write(fFunctionHeader);
1187 this->write(buffer.str());
1188}
1189
1190void MetalCodeGenerator::writeModifiers(const Modifiers& modifiers,
1191 bool globalContext) {
1192 if (modifiers.fFlags & Modifiers::kOut_Flag) {
1193 this->write("thread ");
1194 }
1195 if (modifiers.fFlags & Modifiers::kConst_Flag) {
Timothy Liangee84fe12018-05-18 14:38:19 -04001196 this->write("constant ");
Ethan Nicholascc305772017-10-13 16:17:45 -04001197 }
1198}
1199
1200void MetalCodeGenerator::writeInterfaceBlock(const InterfaceBlock& intf) {
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001201 if ("sk_PerVertex" == intf.typeName()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001202 return;
1203 }
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001204 this->writeModifiers(intf.variable().modifiers(), true);
Timothy Liangdc89f192018-06-13 09:20:31 -04001205 this->write("struct ");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001206 this->writeLine(intf.typeName() + " {");
1207 const Type* structType = &intf.variable().type();
Timothy Lianga06f2152018-05-24 15:33:31 -04001208 fWrittenStructs.push_back(structType);
Ethan Nicholase6592142020-09-08 10:22:09 -04001209 while (structType->typeKind() == Type::TypeKind::kArray) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001210 structType = &structType->componentType();
1211 }
Timothy Liangdc89f192018-06-13 09:20:31 -04001212 fIndentation++;
1213 writeFields(structType->fields(), structType->fOffset, &intf);
Jim Van Verth3d482992019-02-07 10:48:05 -05001214 if (fProgram.fInputs.fRTHeight) {
Timothy Liang7d637782018-06-05 09:58:07 -04001215 this->writeLine("float u_skRTHeight;");
Ethan Nicholascc305772017-10-13 16:17:45 -04001216 }
1217 fIndentation--;
1218 this->write("}");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001219 if (intf.instanceName().size()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001220 this->write(" ");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001221 this->write(intf.instanceName());
1222 for (const auto& size : intf.sizes()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001223 this->write("[");
1224 if (size) {
1225 this->writeExpression(*size, kTopLevel_Precedence);
1226 }
1227 this->write("]");
1228 }
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001229 fInterfaceBlockNameMap[&intf] = intf.instanceName();
Timothy Lianga06f2152018-05-24 15:33:31 -04001230 } else {
Timothy Liang7d637782018-06-05 09:58:07 -04001231 fInterfaceBlockNameMap[&intf] = "_anonInterface" + to_string(fAnonInterfaceCount++);
Ethan Nicholascc305772017-10-13 16:17:45 -04001232 }
1233 this->writeLine(";");
1234}
1235
Timothy Liangdc89f192018-06-13 09:20:31 -04001236void MetalCodeGenerator::writeFields(const std::vector<Type::Field>& fields, int parentOffset,
1237 const InterfaceBlock* parentIntf) {
Timothy Liang609fbe32018-08-10 16:40:49 -04001238 MemoryLayout memoryLayout(MemoryLayout::kMetal_Standard);
Timothy Liangdc89f192018-06-13 09:20:31 -04001239 int currentOffset = 0;
1240 for (const auto& field: fields) {
1241 int fieldOffset = field.fModifiers.fLayout.fOffset;
1242 const Type* fieldType = field.fType;
John Stiles21f5f452020-11-30 09:57:59 -05001243 if (!MemoryLayout::LayoutIsSupported(*fieldType)) {
John Stiles0023c0c2020-11-16 13:32:18 -05001244 fErrors.error(parentOffset, "type '" + fieldType->name() + "' is not permitted here");
1245 return;
1246 }
Timothy Liangdc89f192018-06-13 09:20:31 -04001247 if (fieldOffset != -1) {
1248 if (currentOffset > fieldOffset) {
1249 fErrors.error(parentOffset,
1250 "offset of field '" + field.fName + "' must be at least " +
1251 to_string((int) currentOffset));
Brian Osman8609a242020-09-08 14:01:49 -04001252 return;
Timothy Liangdc89f192018-06-13 09:20:31 -04001253 } else if (currentOffset < fieldOffset) {
1254 this->write("char pad");
1255 this->write(to_string(fPaddingCount++));
1256 this->write("[");
1257 this->write(to_string(fieldOffset - currentOffset));
1258 this->writeLine("];");
1259 currentOffset = fieldOffset;
1260 }
1261 int alignment = memoryLayout.alignment(*fieldType);
1262 if (fieldOffset % alignment) {
1263 fErrors.error(parentOffset,
1264 "offset of field '" + field.fName + "' must be a multiple of " +
1265 to_string((int) alignment));
Brian Osman8609a242020-09-08 14:01:49 -04001266 return;
Timothy Liangdc89f192018-06-13 09:20:31 -04001267 }
1268 }
Brian Osman8609a242020-09-08 14:01:49 -04001269 size_t fieldSize = memoryLayout.size(*fieldType);
1270 if (fieldSize > static_cast<size_t>(std::numeric_limits<int>::max() - currentOffset)) {
1271 fErrors.error(parentOffset, "field offset overflow");
1272 return;
1273 }
1274 currentOffset += fieldSize;
Timothy Liangdc89f192018-06-13 09:20:31 -04001275 std::vector<int> sizes;
Ethan Nicholase6592142020-09-08 10:22:09 -04001276 while (fieldType->typeKind() == Type::TypeKind::kArray) {
Timothy Liangdc89f192018-06-13 09:20:31 -04001277 sizes.push_back(fieldType->columns());
1278 fieldType = &fieldType->componentType();
1279 }
1280 this->writeModifiers(field.fModifiers, false);
1281 this->writeType(*fieldType);
1282 this->write(" ");
1283 this->writeName(field.fName);
1284 for (int s : sizes) {
Brian Osmane8c26082020-10-01 17:22:45 -04001285 if (s == Type::kUnsizedArray) {
Timothy Liangdc89f192018-06-13 09:20:31 -04001286 this->write("[]");
1287 } else {
1288 this->write("[" + to_string(s) + "]");
1289 }
1290 }
1291 this->writeLine(";");
1292 if (parentIntf) {
1293 fInterfaceBlockMap[&field] = parentIntf;
1294 }
1295 }
1296}
1297
Ethan Nicholascc305772017-10-13 16:17:45 -04001298void MetalCodeGenerator::writeVarInitializer(const Variable& var, const Expression& value) {
1299 this->writeExpression(value, kTopLevel_Precedence);
1300}
1301
Timothy Liang651286f2018-06-07 09:55:33 -04001302void MetalCodeGenerator::writeName(const String& name) {
1303 if (fReservedWords.find(name) != fReservedWords.end()) {
1304 this->write("_"); // adding underscore before name to avoid conflict with reserved words
1305 }
1306 this->write(name);
1307}
1308
Brian Osmanc0213602020-10-06 14:43:32 -04001309void MetalCodeGenerator::writeVarDeclaration(const VarDeclaration& var, bool global) {
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001310 if (global && !(var.var().modifiers().fFlags & Modifiers::kConst_Flag)) {
Brian Osmanc0213602020-10-06 14:43:32 -04001311 return;
Ethan Nicholascc305772017-10-13 16:17:45 -04001312 }
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001313 this->writeModifiers(var.var().modifiers(), global);
1314 this->writeType(var.baseType());
Brian Osmanc0213602020-10-06 14:43:32 -04001315 this->write(" ");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001316 this->writeName(var.var().name());
John Stiles2d4f9592020-10-30 10:29:12 -04001317 for (const std::unique_ptr<Expression>& size : var.sizes()) {
Brian Osmanc0213602020-10-06 14:43:32 -04001318 this->write("[");
John Stiles2d4f9592020-10-30 10:29:12 -04001319 if (size) {
1320 this->writeExpression(*size, kTopLevel_Precedence);
Brian Osmanc0213602020-10-06 14:43:32 -04001321 }
1322 this->write("]");
Ethan Nicholascc305772017-10-13 16:17:45 -04001323 }
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001324 if (var.value()) {
Brian Osmanc0213602020-10-06 14:43:32 -04001325 this->write(" = ");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001326 this->writeVarInitializer(var.var(), *var.value());
Brian Osmanc0213602020-10-06 14:43:32 -04001327 }
1328 this->write(";");
Ethan Nicholascc305772017-10-13 16:17:45 -04001329}
1330
1331void MetalCodeGenerator::writeStatement(const Statement& s) {
Ethan Nicholase6592142020-09-08 10:22:09 -04001332 switch (s.kind()) {
1333 case Statement::Kind::kBlock:
John Stiles26f98502020-08-18 09:30:51 -04001334 this->writeBlock(s.as<Block>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001335 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001336 case Statement::Kind::kExpression:
Ethan Nicholasd503a5a2020-09-30 09:29:55 -04001337 this->writeExpression(*s.as<ExpressionStatement>().expression(), kTopLevel_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001338 this->write(";");
1339 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001340 case Statement::Kind::kReturn:
John Stiles26f98502020-08-18 09:30:51 -04001341 this->writeReturnStatement(s.as<ReturnStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001342 break;
Brian Osmanc0213602020-10-06 14:43:32 -04001343 case Statement::Kind::kVarDeclaration:
1344 this->writeVarDeclaration(s.as<VarDeclaration>(), false);
Ethan Nicholascc305772017-10-13 16:17:45 -04001345 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001346 case Statement::Kind::kIf:
John Stiles26f98502020-08-18 09:30:51 -04001347 this->writeIfStatement(s.as<IfStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001348 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001349 case Statement::Kind::kFor:
John Stiles26f98502020-08-18 09:30:51 -04001350 this->writeForStatement(s.as<ForStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001351 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001352 case Statement::Kind::kWhile:
John Stiles26f98502020-08-18 09:30:51 -04001353 this->writeWhileStatement(s.as<WhileStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001354 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001355 case Statement::Kind::kDo:
John Stiles26f98502020-08-18 09:30:51 -04001356 this->writeDoStatement(s.as<DoStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001357 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001358 case Statement::Kind::kSwitch:
John Stiles26f98502020-08-18 09:30:51 -04001359 this->writeSwitchStatement(s.as<SwitchStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001360 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001361 case Statement::Kind::kBreak:
Ethan Nicholascc305772017-10-13 16:17:45 -04001362 this->write("break;");
1363 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001364 case Statement::Kind::kContinue:
Ethan Nicholascc305772017-10-13 16:17:45 -04001365 this->write("continue;");
1366 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001367 case Statement::Kind::kDiscard:
Timothy Lianga06f2152018-05-24 15:33:31 -04001368 this->write("discard_fragment();");
Ethan Nicholascc305772017-10-13 16:17:45 -04001369 break;
John Stiles98c1f822020-09-09 14:18:53 -04001370 case Statement::Kind::kInlineMarker:
Ethan Nicholase6592142020-09-08 10:22:09 -04001371 case Statement::Kind::kNop:
Ethan Nicholascc305772017-10-13 16:17:45 -04001372 this->write(";");
1373 break;
1374 default:
Ethan Nicholas2a099da2020-01-02 14:40:54 -05001375#ifdef SK_DEBUG
Ethan Nicholascc305772017-10-13 16:17:45 -04001376 ABORT("unsupported statement: %s", s.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -05001377#endif
1378 break;
Ethan Nicholascc305772017-10-13 16:17:45 -04001379 }
1380}
1381
Ethan Nicholascc305772017-10-13 16:17:45 -04001382void MetalCodeGenerator::writeBlock(const Block& b) {
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001383 bool isScope = b.isScope();
1384 if (isScope) {
Ethan Nicholas70728ef2020-05-28 07:09:00 -04001385 this->writeLine("{");
1386 fIndentation++;
1387 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001388 for (const std::unique_ptr<Statement>& stmt : b.children()) {
1389 if (!stmt->isEmpty()) {
1390 this->writeStatement(*stmt);
1391 this->writeLine();
1392 }
1393 }
1394 if (isScope) {
Ethan Nicholas70728ef2020-05-28 07:09:00 -04001395 fIndentation--;
1396 this->write("}");
1397 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001398}
1399
1400void MetalCodeGenerator::writeIfStatement(const IfStatement& stmt) {
1401 this->write("if (");
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04001402 this->writeExpression(*stmt.test(), kTopLevel_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001403 this->write(") ");
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04001404 this->writeStatement(*stmt.ifTrue());
1405 if (stmt.ifFalse()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001406 this->write(" else ");
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04001407 this->writeStatement(*stmt.ifFalse());
Ethan Nicholascc305772017-10-13 16:17:45 -04001408 }
1409}
1410
1411void MetalCodeGenerator::writeForStatement(const ForStatement& f) {
1412 this->write("for (");
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04001413 if (f.initializer() && !f.initializer()->isEmpty()) {
1414 this->writeStatement(*f.initializer());
Ethan Nicholascc305772017-10-13 16:17:45 -04001415 } else {
1416 this->write("; ");
1417 }
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04001418 if (f.test()) {
1419 this->writeExpression(*f.test(), kTopLevel_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001420 }
1421 this->write("; ");
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04001422 if (f.next()) {
1423 this->writeExpression(*f.next(), kTopLevel_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001424 }
1425 this->write(") ");
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04001426 this->writeStatement(*f.statement());
Ethan Nicholascc305772017-10-13 16:17:45 -04001427}
1428
1429void MetalCodeGenerator::writeWhileStatement(const WhileStatement& w) {
1430 this->write("while (");
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04001431 this->writeExpression(*w.test(), kTopLevel_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001432 this->write(") ");
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04001433 this->writeStatement(*w.statement());
Ethan Nicholascc305772017-10-13 16:17:45 -04001434}
1435
1436void MetalCodeGenerator::writeDoStatement(const DoStatement& d) {
1437 this->write("do ");
Ethan Nicholas1fd61162020-09-28 13:14:19 -04001438 this->writeStatement(*d.statement());
Ethan Nicholascc305772017-10-13 16:17:45 -04001439 this->write(" while (");
Ethan Nicholas1fd61162020-09-28 13:14:19 -04001440 this->writeExpression(*d.test(), kTopLevel_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001441 this->write(");");
1442}
1443
1444void MetalCodeGenerator::writeSwitchStatement(const SwitchStatement& s) {
1445 this->write("switch (");
Ethan Nicholas01b05e52020-10-22 15:53:41 -04001446 this->writeExpression(*s.value(), kTopLevel_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001447 this->writeLine(") {");
1448 fIndentation++;
John Stiles2d4f9592020-10-30 10:29:12 -04001449 for (const std::unique_ptr<SwitchCase>& c : s.cases()) {
1450 if (c->value()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001451 this->write("case ");
John Stiles2d4f9592020-10-30 10:29:12 -04001452 this->writeExpression(*c->value(), kTopLevel_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001453 this->writeLine(":");
1454 } else {
1455 this->writeLine("default:");
1456 }
1457 fIndentation++;
John Stiles2d4f9592020-10-30 10:29:12 -04001458 for (const auto& stmt : c->statements()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001459 this->writeStatement(*stmt);
1460 this->writeLine();
1461 }
1462 fIndentation--;
1463 }
1464 fIndentation--;
1465 this->write("}");
1466}
1467
1468void MetalCodeGenerator::writeReturnStatement(const ReturnStatement& r) {
1469 this->write("return");
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04001470 if (r.expression()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001471 this->write(" ");
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04001472 this->writeExpression(*r.expression(), kTopLevel_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001473 }
1474 this->write(";");
1475}
1476
1477void MetalCodeGenerator::writeHeader() {
1478 this->write("#include <metal_stdlib>\n");
1479 this->write("#include <simd/simd.h>\n");
1480 this->write("using namespace metal;\n");
1481}
1482
1483void MetalCodeGenerator::writeUniformStruct() {
Brian Osman133724c2020-10-28 14:14:39 -04001484 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04001485 if (e->is<GlobalVarDeclaration>()) {
1486 const GlobalVarDeclaration& decls = e->as<GlobalVarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001487 const Variable& var = decls.declaration()->as<VarDeclaration>().var();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001488 if (var.modifiers().fFlags & Modifiers::kUniform_Flag &&
Brian Osmanc0213602020-10-06 14:43:32 -04001489 var.type().typeKind() != Type::TypeKind::kSampler) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001490 if (-1 == fUniformBuffer) {
1491 this->write("struct Uniforms {\n");
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001492 fUniformBuffer = var.modifiers().fLayout.fSet;
Ethan Nicholascc305772017-10-13 16:17:45 -04001493 if (-1 == fUniformBuffer) {
1494 fErrors.error(decls.fOffset, "Metal uniforms must have 'layout(set=...)'");
1495 }
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001496 } else if (var.modifiers().fLayout.fSet != fUniformBuffer) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001497 if (-1 == fUniformBuffer) {
1498 fErrors.error(decls.fOffset, "Metal backend requires all uniforms to have "
1499 "the same 'layout(set=...)'");
1500 }
1501 }
1502 this->write(" ");
Brian Osmanc0213602020-10-06 14:43:32 -04001503 this->writeType(var.type());
Ethan Nicholascc305772017-10-13 16:17:45 -04001504 this->write(" ");
Brian Osmanc0213602020-10-06 14:43:32 -04001505 this->writeName(var.name());
Ethan Nicholascc305772017-10-13 16:17:45 -04001506 this->write(";\n");
1507 }
1508 }
1509 }
1510 if (-1 != fUniformBuffer) {
1511 this->write("};\n");
1512 }
1513}
1514
1515void MetalCodeGenerator::writeInputStruct() {
1516 this->write("struct Inputs {\n");
Brian Osman133724c2020-10-28 14:14:39 -04001517 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04001518 if (e->is<GlobalVarDeclaration>()) {
1519 const GlobalVarDeclaration& decls = e->as<GlobalVarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001520 const Variable& var = decls.declaration()->as<VarDeclaration>().var();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001521 if (var.modifiers().fFlags & Modifiers::kIn_Flag &&
1522 -1 == var.modifiers().fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001523 this->write(" ");
Brian Osmanc0213602020-10-06 14:43:32 -04001524 this->writeType(var.type());
Ethan Nicholascc305772017-10-13 16:17:45 -04001525 this->write(" ");
Brian Osmanc0213602020-10-06 14:43:32 -04001526 this->writeName(var.name());
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001527 if (-1 != var.modifiers().fLayout.fLocation) {
Brian Osmanc0213602020-10-06 14:43:32 -04001528 if (fProgram.fKind == Program::kVertex_Kind) {
1529 this->write(" [[attribute(" +
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001530 to_string(var.modifiers().fLayout.fLocation) + ")]]");
Brian Osmanc0213602020-10-06 14:43:32 -04001531 } else if (fProgram.fKind == Program::kFragment_Kind) {
1532 this->write(" [[user(locn" +
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001533 to_string(var.modifiers().fLayout.fLocation) + ")]]");
Ethan Nicholascc305772017-10-13 16:17:45 -04001534 }
1535 }
1536 this->write(";\n");
1537 }
1538 }
1539 }
1540 this->write("};\n");
1541}
1542
1543void MetalCodeGenerator::writeOutputStruct() {
1544 this->write("struct Outputs {\n");
Timothy Liang7d637782018-06-05 09:58:07 -04001545 if (fProgram.fKind == Program::kVertex_Kind) {
Timothy Liangb8eeb802018-07-23 16:46:16 -04001546 this->write(" float4 sk_Position [[position]];\n");
Timothy Liang7d637782018-06-05 09:58:07 -04001547 } else if (fProgram.fKind == Program::kFragment_Kind) {
Timothy Liangde0be802018-08-10 13:48:08 -04001548 this->write(" float4 sk_FragColor [[color(0)]];\n");
Timothy Liang7d637782018-06-05 09:58:07 -04001549 }
Brian Osman133724c2020-10-28 14:14:39 -04001550 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04001551 if (e->is<GlobalVarDeclaration>()) {
1552 const GlobalVarDeclaration& decls = e->as<GlobalVarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001553 const Variable& var = decls.declaration()->as<VarDeclaration>().var();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001554 if (var.modifiers().fFlags & Modifiers::kOut_Flag &&
1555 -1 == var.modifiers().fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001556 this->write(" ");
Brian Osmanc0213602020-10-06 14:43:32 -04001557 this->writeType(var.type());
Ethan Nicholascc305772017-10-13 16:17:45 -04001558 this->write(" ");
Brian Osmanc0213602020-10-06 14:43:32 -04001559 this->writeName(var.name());
1560 if (fProgram.fKind == Program::kVertex_Kind) {
1561 this->write(" [[user(locn" +
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001562 to_string(var.modifiers().fLayout.fLocation) + ")]]");
Brian Osmanc0213602020-10-06 14:43:32 -04001563 } else if (fProgram.fKind == Program::kFragment_Kind) {
1564 this->write(" [[color(" +
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001565 to_string(var.modifiers().fLayout.fLocation) +")");
1566 int colorIndex = var.modifiers().fLayout.fIndex;
Brian Osmanc0213602020-10-06 14:43:32 -04001567 if (colorIndex) {
1568 this->write(", index(" + to_string(colorIndex) + ")");
Timothy Liang7d637782018-06-05 09:58:07 -04001569 }
Brian Osmanc0213602020-10-06 14:43:32 -04001570 this->write("]]");
Ethan Nicholascc305772017-10-13 16:17:45 -04001571 }
1572 this->write(";\n");
1573 }
1574 }
Timothy Liang7d637782018-06-05 09:58:07 -04001575 }
1576 if (fProgram.fKind == Program::kVertex_Kind) {
Jim Van Verth3913d3e2020-08-31 15:16:57 -04001577 this->write(" float sk_PointSize [[point_size]];\n");
Timothy Liang7d637782018-06-05 09:58:07 -04001578 }
1579 this->write("};\n");
1580}
1581
1582void MetalCodeGenerator::writeInterfaceBlocks() {
1583 bool wroteInterfaceBlock = false;
Brian Osman133724c2020-10-28 14:14:39 -04001584 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04001585 if (e->is<InterfaceBlock>()) {
1586 this->writeInterfaceBlock(e->as<InterfaceBlock>());
Timothy Liang7d637782018-06-05 09:58:07 -04001587 wroteInterfaceBlock = true;
1588 }
1589 }
Jim Van Verth3d482992019-02-07 10:48:05 -05001590 if (!wroteInterfaceBlock && fProgram.fInputs.fRTHeight) {
Timothy Liang7d637782018-06-05 09:58:07 -04001591 this->writeLine("struct sksl_synthetic_uniforms {");
1592 this->writeLine(" float u_skRTHeight;");
1593 this->writeLine("};");
1594 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001595}
1596
John Stilesdc75a972020-11-25 16:24:55 -05001597void MetalCodeGenerator::writeStructDefinitions() {
1598 for (const ProgramElement* e : fProgram.elements()) {
1599 if (e->is<StructDefinition>()) {
1600 if (this->writeStructDefinition(e->as<StructDefinition>().type())) {
1601 this->writeLine(";");
1602 }
1603 } else if (e->is<GlobalVarDeclaration>()) {
1604 // If a global var declaration introduces a struct type, we need to write that type
1605 // here, since globals are all embedded in a sub-struct.
1606 const Type* type = &e->as<GlobalVarDeclaration>().declaration()
1607 ->as<VarDeclaration>().baseType();
1608 if (type->typeKind() == Type::TypeKind::kStruct) {
1609 if (this->writeStructDefinition(*type)) {
1610 this->writeLine(";");
1611 }
1612 }
1613 }
1614 }
1615}
1616
John Stilescdcdb042020-07-06 09:03:51 -04001617void MetalCodeGenerator::visitGlobalStruct(GlobalStructVisitor* visitor) {
1618 // Visit the interface blocks.
1619 for (const auto& [interfaceType, interfaceName] : fInterfaceBlockNameMap) {
1620 visitor->VisitInterfaceBlock(*interfaceType, interfaceName);
1621 }
Brian Osman133724c2020-10-28 14:14:39 -04001622 for (const ProgramElement* element : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04001623 if (!element->is<GlobalVarDeclaration>()) {
John Stilescdcdb042020-07-06 09:03:51 -04001624 continue;
Timothy Liang7d637782018-06-05 09:58:07 -04001625 }
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001626 const GlobalVarDeclaration& global = element->as<GlobalVarDeclaration>();
1627 const VarDeclaration& decl = global.declaration()->as<VarDeclaration>();
1628 const Variable& var = decl.var();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001629 if ((!var.modifiers().fFlags && -1 == var.modifiers().fLayout.fBuiltin) ||
Brian Osmanc0213602020-10-06 14:43:32 -04001630 var.type().typeKind() == Type::TypeKind::kSampler) {
1631 if (var.type().typeKind() == Type::TypeKind::kSampler) {
1632 // Samplers are represented as a "texture/sampler" duo in the global struct.
1633 visitor->VisitTexture(var.type(), var.name());
1634 visitor->VisitSampler(var.type(), String(var.name()) + SAMPLER_SUFFIX);
1635 } else {
1636 // Visit a regular variable.
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001637 visitor->VisitVariable(var, decl.value().get());
Timothy Liangee84fe12018-05-18 14:38:19 -04001638 }
1639 }
1640 }
John Stilescdcdb042020-07-06 09:03:51 -04001641}
1642
1643void MetalCodeGenerator::writeGlobalStruct() {
1644 class : public GlobalStructVisitor {
1645 public:
1646 void VisitInterfaceBlock(const InterfaceBlock& block, const String& blockName) override {
1647 this->AddElement();
1648 fCodeGen->write(" constant ");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001649 fCodeGen->write(block.typeName());
John Stilescdcdb042020-07-06 09:03:51 -04001650 fCodeGen->write("* ");
1651 fCodeGen->writeName(blockName);
1652 fCodeGen->write(";\n");
1653 }
1654 void VisitTexture(const Type& type, const String& name) override {
1655 this->AddElement();
1656 fCodeGen->write(" ");
1657 fCodeGen->writeType(type);
1658 fCodeGen->write(" ");
1659 fCodeGen->writeName(name);
1660 fCodeGen->write(";\n");
1661 }
1662 void VisitSampler(const Type&, const String& name) override {
1663 this->AddElement();
1664 fCodeGen->write(" sampler ");
1665 fCodeGen->writeName(name);
1666 fCodeGen->write(";\n");
1667 }
1668 void VisitVariable(const Variable& var, const Expression* value) override {
1669 this->AddElement();
1670 fCodeGen->write(" ");
Ethan Nicholas30d30222020-09-11 12:27:26 -04001671 fCodeGen->writeType(var.type());
John Stilescdcdb042020-07-06 09:03:51 -04001672 fCodeGen->write(" ");
Ethan Nicholase2c49992020-10-05 11:49:11 -04001673 fCodeGen->writeName(var.name());
John Stilescdcdb042020-07-06 09:03:51 -04001674 fCodeGen->write(";\n");
1675 }
1676 void AddElement() {
1677 if (fFirst) {
1678 fCodeGen->write("struct Globals {\n");
1679 fFirst = false;
1680 }
1681 }
1682 void Finish() {
1683 if (!fFirst) {
1684 fCodeGen->write("};");
1685 fFirst = true;
1686 }
1687 }
1688
1689 MetalCodeGenerator* fCodeGen = nullptr;
1690 bool fFirst = true;
1691 } visitor;
1692
1693 visitor.fCodeGen = this;
1694 this->visitGlobalStruct(&visitor);
1695 visitor.Finish();
1696}
1697
1698void MetalCodeGenerator::writeGlobalInit() {
1699 class : public GlobalStructVisitor {
1700 public:
1701 void VisitInterfaceBlock(const InterfaceBlock& blockType,
1702 const String& blockName) override {
1703 this->AddElement();
1704 fCodeGen->write("&");
1705 fCodeGen->writeName(blockName);
1706 }
1707 void VisitTexture(const Type&, const String& name) override {
1708 this->AddElement();
1709 fCodeGen->writeName(name);
1710 }
1711 void VisitSampler(const Type&, const String& name) override {
1712 this->AddElement();
1713 fCodeGen->writeName(name);
1714 }
1715 void VisitVariable(const Variable& var, const Expression* value) override {
1716 this->AddElement();
1717 if (value) {
1718 fCodeGen->writeVarInitializer(var, *value);
1719 } else {
1720 fCodeGen->write("{}");
1721 }
1722 }
1723 void AddElement() {
1724 if (fFirst) {
1725 fCodeGen->write(" Globals globalStruct{");
1726 fFirst = false;
1727 } else {
1728 fCodeGen->write(", ");
1729 }
1730 }
1731 void Finish() {
1732 if (!fFirst) {
1733 fCodeGen->writeLine("};");
1734 fCodeGen->writeLine(" thread Globals* _globals = &globalStruct;");
1735 fCodeGen->writeLine(" (void)_globals;");
1736 }
1737 }
1738 MetalCodeGenerator* fCodeGen = nullptr;
1739 bool fFirst = true;
1740 } visitor;
1741
1742 visitor.fCodeGen = this;
1743 this->visitGlobalStruct(&visitor);
1744 visitor.Finish();
Timothy Liangee84fe12018-05-18 14:38:19 -04001745}
1746
Ethan Nicholascc305772017-10-13 16:17:45 -04001747void MetalCodeGenerator::writeProgramElement(const ProgramElement& e) {
Ethan Nicholase6592142020-09-08 10:22:09 -04001748 switch (e.kind()) {
1749 case ProgramElement::Kind::kExtension:
Ethan Nicholascc305772017-10-13 16:17:45 -04001750 break;
Brian Osmanc0213602020-10-06 14:43:32 -04001751 case ProgramElement::Kind::kGlobalVar: {
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001752 const GlobalVarDeclaration& global = e.as<GlobalVarDeclaration>();
1753 const VarDeclaration& decl = global.declaration()->as<VarDeclaration>();
1754 int builtin = decl.var().modifiers().fLayout.fBuiltin;
Brian Osmanc0213602020-10-06 14:43:32 -04001755 if (-1 == builtin) {
1756 // normal var
1757 this->writeVarDeclaration(decl, true);
1758 this->writeLine();
1759 } else if (SK_FRAGCOLOR_BUILTIN == builtin) {
1760 // ignore
Ethan Nicholascc305772017-10-13 16:17:45 -04001761 }
1762 break;
1763 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001764 case ProgramElement::Kind::kInterfaceBlock:
Timothy Liang7d637782018-06-05 09:58:07 -04001765 // handled in writeInterfaceBlocks, do nothing
Ethan Nicholascc305772017-10-13 16:17:45 -04001766 break;
John Stilesdc75a972020-11-25 16:24:55 -05001767 case ProgramElement::Kind::kStructDefinition:
1768 // Handled in writeStructDefinitions. Do nothing.
1769 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001770 case ProgramElement::Kind::kFunction:
John Stiles3dc0da62020-08-19 17:48:31 -04001771 this->writeFunction(e.as<FunctionDefinition>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001772 break;
John Stiles569249b2020-11-03 12:18:22 -05001773 case ProgramElement::Kind::kFunctionPrototype:
1774 this->writeFunctionPrototype(e.as<FunctionPrototype>());
1775 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001776 case ProgramElement::Kind::kModifiers:
Ethan Nicholas077050b2020-10-13 10:30:20 -04001777 this->writeModifiers(e.as<ModifiersDeclaration>().modifiers(), true);
Ethan Nicholascc305772017-10-13 16:17:45 -04001778 this->writeLine(";");
1779 break;
John Stiles712fd6b2020-11-25 22:25:43 -05001780 case ProgramElement::Kind::kEnum:
1781 break;
Ethan Nicholascc305772017-10-13 16:17:45 -04001782 default:
Ethan Nicholas2a099da2020-01-02 14:40:54 -05001783#ifdef SK_DEBUG
1784 ABORT("unsupported program element: %s\n", e.description().c_str());
1785#endif
1786 break;
Ethan Nicholascc305772017-10-13 16:17:45 -04001787 }
1788}
1789
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001790MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const Expression* e) {
1791 if (!e) {
1792 return kNo_Requirements;
1793 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001794 switch (e->kind()) {
1795 case Expression::Kind::kFunctionCall: {
John Stiles3dc0da62020-08-19 17:48:31 -04001796 const FunctionCall& f = e->as<FunctionCall>();
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001797 Requirements result = this->requirements(f.function());
1798 for (const auto& arg : f.arguments()) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001799 result |= this->requirements(arg.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001800 }
1801 return result;
1802 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001803 case Expression::Kind::kConstructor: {
John Stiles3dc0da62020-08-19 17:48:31 -04001804 const Constructor& c = e->as<Constructor>();
Ethan Nicholascc305772017-10-13 16:17:45 -04001805 Requirements result = kNo_Requirements;
Ethan Nicholasf70f0442020-09-29 12:41:35 -04001806 for (const auto& arg : c.arguments()) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001807 result |= this->requirements(arg.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001808 }
1809 return result;
1810 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001811 case Expression::Kind::kFieldAccess: {
John Stiles3dc0da62020-08-19 17:48:31 -04001812 const FieldAccess& f = e->as<FieldAccess>();
Ethan Nicholas7a95b202020-10-09 11:55:40 -04001813 if (FieldAccess::OwnerKind::kAnonymousInterfaceBlock == f.ownerKind()) {
Timothy Liang7d637782018-06-05 09:58:07 -04001814 return kGlobals_Requirement;
1815 }
Ethan Nicholas7a95b202020-10-09 11:55:40 -04001816 return this->requirements(f.base().get());
Timothy Liang7d637782018-06-05 09:58:07 -04001817 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001818 case Expression::Kind::kSwizzle:
Ethan Nicholas6b4d5812020-10-12 16:11:51 -04001819 return this->requirements(e->as<Swizzle>().base().get());
Ethan Nicholase6592142020-09-08 10:22:09 -04001820 case Expression::Kind::kBinary: {
1821 const BinaryExpression& bin = e->as<BinaryExpression>();
John Stiles2d4f9592020-10-30 10:29:12 -04001822 return this->requirements(bin.left().get()) |
1823 this->requirements(bin.right().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001824 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001825 case Expression::Kind::kIndex: {
John Stiles3dc0da62020-08-19 17:48:31 -04001826 const IndexExpression& idx = e->as<IndexExpression>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04001827 return this->requirements(idx.base().get()) | this->requirements(idx.index().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001828 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001829 case Expression::Kind::kPrefix:
Ethan Nicholas444ccc62020-10-09 10:16:22 -04001830 return this->requirements(e->as<PrefixExpression>().operand().get());
Ethan Nicholase6592142020-09-08 10:22:09 -04001831 case Expression::Kind::kPostfix:
Ethan Nicholas444ccc62020-10-09 10:16:22 -04001832 return this->requirements(e->as<PostfixExpression>().operand().get());
Ethan Nicholase6592142020-09-08 10:22:09 -04001833 case Expression::Kind::kTernary: {
John Stiles3dc0da62020-08-19 17:48:31 -04001834 const TernaryExpression& t = e->as<TernaryExpression>();
Ethan Nicholasdd218162020-10-08 05:48:01 -04001835 return this->requirements(t.test().get()) | this->requirements(t.ifTrue().get()) |
1836 this->requirements(t.ifFalse().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001837 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001838 case Expression::Kind::kVariableReference: {
John Stiles3dc0da62020-08-19 17:48:31 -04001839 const VariableReference& v = e->as<VariableReference>();
Ethan Nicholas78686922020-10-08 06:46:27 -04001840 const Modifiers& modifiers = v.variable()->modifiers();
Ethan Nicholascc305772017-10-13 16:17:45 -04001841 Requirements result = kNo_Requirements;
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001842 if (modifiers.fLayout.fBuiltin == SK_FRAGCOORD_BUILTIN) {
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -04001843 result = kGlobals_Requirement | kFragCoord_Requirement;
Ethan Nicholas453f67f2020-10-09 10:43:45 -04001844 } else if (Variable::Storage::kGlobal == v.variable()->storage()) {
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001845 if (modifiers.fFlags & Modifiers::kIn_Flag) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001846 result = kInputs_Requirement;
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001847 } else if (modifiers.fFlags & Modifiers::kOut_Flag) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001848 result = kOutputs_Requirement;
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001849 } else if (modifiers.fFlags & Modifiers::kUniform_Flag &&
Ethan Nicholas78686922020-10-08 06:46:27 -04001850 v.variable()->type().typeKind() != Type::TypeKind::kSampler) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001851 result = kUniforms_Requirement;
Timothy Liangee84fe12018-05-18 14:38:19 -04001852 } else {
1853 result = kGlobals_Requirement;
Ethan Nicholascc305772017-10-13 16:17:45 -04001854 }
1855 }
1856 return result;
1857 }
1858 default:
1859 return kNo_Requirements;
1860 }
1861}
1862
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001863MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const Statement* s) {
1864 if (!s) {
1865 return kNo_Requirements;
1866 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001867 switch (s->kind()) {
1868 case Statement::Kind::kBlock: {
Ethan Nicholascc305772017-10-13 16:17:45 -04001869 Requirements result = kNo_Requirements;
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001870 for (const std::unique_ptr<Statement>& child : s->as<Block>().children()) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001871 result |= this->requirements(child.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001872 }
1873 return result;
1874 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001875 case Statement::Kind::kVarDeclaration: {
John Stiles3dc0da62020-08-19 17:48:31 -04001876 const VarDeclaration& var = s->as<VarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001877 return this->requirements(var.value().get());
Timothy Liang7d637782018-06-05 09:58:07 -04001878 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001879 case Statement::Kind::kExpression:
Ethan Nicholasd503a5a2020-09-30 09:29:55 -04001880 return this->requirements(s->as<ExpressionStatement>().expression().get());
Ethan Nicholase6592142020-09-08 10:22:09 -04001881 case Statement::Kind::kReturn: {
John Stiles3dc0da62020-08-19 17:48:31 -04001882 const ReturnStatement& r = s->as<ReturnStatement>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04001883 return this->requirements(r.expression().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001884 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001885 case Statement::Kind::kIf: {
John Stiles3dc0da62020-08-19 17:48:31 -04001886 const IfStatement& i = s->as<IfStatement>();
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04001887 return this->requirements(i.test().get()) |
1888 this->requirements(i.ifTrue().get()) |
1889 this->requirements(i.ifFalse().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001890 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001891 case Statement::Kind::kFor: {
John Stiles3dc0da62020-08-19 17:48:31 -04001892 const ForStatement& f = s->as<ForStatement>();
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04001893 return this->requirements(f.initializer().get()) |
1894 this->requirements(f.test().get()) |
1895 this->requirements(f.next().get()) |
1896 this->requirements(f.statement().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001897 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001898 case Statement::Kind::kWhile: {
John Stiles3dc0da62020-08-19 17:48:31 -04001899 const WhileStatement& w = s->as<WhileStatement>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04001900 return this->requirements(w.test().get()) |
1901 this->requirements(w.statement().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001902 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001903 case Statement::Kind::kDo: {
John Stiles3dc0da62020-08-19 17:48:31 -04001904 const DoStatement& d = s->as<DoStatement>();
Ethan Nicholas1fd61162020-09-28 13:14:19 -04001905 return this->requirements(d.test().get()) |
1906 this->requirements(d.statement().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001907 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001908 case Statement::Kind::kSwitch: {
John Stiles3dc0da62020-08-19 17:48:31 -04001909 const SwitchStatement& sw = s->as<SwitchStatement>();
Ethan Nicholas01b05e52020-10-22 15:53:41 -04001910 Requirements result = this->requirements(sw.value().get());
John Stiles2d4f9592020-10-30 10:29:12 -04001911 for (const std::unique_ptr<SwitchCase>& sc : sw.cases()) {
1912 for (const auto& st : sc->statements()) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001913 result |= this->requirements(st.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001914 }
1915 }
1916 return result;
1917 }
1918 default:
1919 return kNo_Requirements;
1920 }
1921}
1922
1923MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const FunctionDeclaration& f) {
Ethan Nicholased84b732020-10-08 11:45:44 -04001924 if (f.isBuiltin()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001925 return kNo_Requirements;
1926 }
1927 auto found = fRequirements.find(&f);
1928 if (found == fRequirements.end()) {
Ethan Nicholas65a8f562019-04-19 14:00:26 -04001929 fRequirements[&f] = kNo_Requirements;
Brian Osman133724c2020-10-28 14:14:39 -04001930 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04001931 if (e->is<FunctionDefinition>()) {
1932 const FunctionDefinition& def = e->as<FunctionDefinition>();
Ethan Nicholas0a5d0962020-10-14 13:33:18 -04001933 if (&def.declaration() == &f) {
1934 Requirements reqs = this->requirements(def.body().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001935 fRequirements[&f] = reqs;
1936 return reqs;
1937 }
1938 }
1939 }
John Stiles569249b2020-11-03 12:18:22 -05001940 // We never found a definition for this declared function, but it's legal to prototype a
1941 // function without ever giving a definition, as long as you don't call it.
1942 return kNo_Requirements;
Ethan Nicholascc305772017-10-13 16:17:45 -04001943 }
1944 return found->second;
1945}
1946
Timothy Liangb8eeb802018-07-23 16:46:16 -04001947bool MetalCodeGenerator::generateCode() {
Ethan Nicholascc305772017-10-13 16:17:45 -04001948 OutputStream* rawOut = fOut;
1949 fOut = &fHeader;
1950 fProgramKind = fProgram.fKind;
1951 this->writeHeader();
John Stilesdc75a972020-11-25 16:24:55 -05001952 this->writeStructDefinitions();
Ethan Nicholascc305772017-10-13 16:17:45 -04001953 this->writeUniformStruct();
1954 this->writeInputStruct();
Timothy Liang7d637782018-06-05 09:58:07 -04001955 this->writeOutputStruct();
1956 this->writeInterfaceBlocks();
Timothy Liangee84fe12018-05-18 14:38:19 -04001957 this->writeGlobalStruct();
Ethan Nicholascc305772017-10-13 16:17:45 -04001958 StringStream body;
1959 fOut = &body;
Brian Osman133724c2020-10-28 14:14:39 -04001960 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04001961 this->writeProgramElement(*e);
Ethan Nicholascc305772017-10-13 16:17:45 -04001962 }
1963 fOut = rawOut;
1964
1965 write_stringstream(fHeader, *rawOut);
Chris Daltondba7aab2018-11-15 10:57:49 -05001966 write_stringstream(fExtraFunctions, *rawOut);
Ethan Nicholascc305772017-10-13 16:17:45 -04001967 write_stringstream(body, *rawOut);
Brian Osman8609a242020-09-08 14:01:49 -04001968 return 0 == fErrors.errorCount();
Ethan Nicholascc305772017-10-13 16:17:45 -04001969}
1970
John Stilesa6841be2020-08-06 14:11:56 -04001971} // namespace SkSL