Debian Codegraph @

src/sksl/codegen/SkSLMetalCodeGenerator.cpp

raw
1 /*
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 #include "src/sksl/codegen/SkSLMetalCodeGenerator.h"
8
9 #include "include/core/SkSpan.h"
10 #include "include/core/SkTypes.h"
11 #include "include/private/base/SkTArray.h"
12 #include "include/private/base/SkTo.h"
13 #include "src/base/SkEnumBitMask.h"
14 #include "src/base/SkScopeExit.h"
15 #include "src/core/SkTHash.h"
16 #include "src/core/SkTraceEvent.h"
17 #include "src/sksl/SkSLAnalysis.h"
18 #include "src/sksl/SkSLBuiltinTypes.h"
19 #include "src/sksl/SkSLCompiler.h"
20 #include "src/sksl/SkSLContext.h"
21 #include "src/sksl/SkSLDefines.h"
22 #include "src/sksl/SkSLErrorReporter.h"
23 #include "src/sksl/SkSLIntrinsicList.h"
24 #include "src/sksl/SkSLMemoryLayout.h"
25 #include "src/sksl/SkSLOperator.h"
26 #include "src/sksl/SkSLOutputStream.h"
27 #include "src/sksl/SkSLPosition.h"
28 #include "src/sksl/SkSLProgramSettings.h"
29 #include "src/sksl/SkSLString.h"
30 #include "src/sksl/SkSLStringStream.h"
31 #include "src/sksl/SkSLUtil.h"
32 #include "src/sksl/analysis/SkSLProgramVisitor.h"
33 #include "src/sksl/codegen/SkSLCodeGenTypes.h"
34 #include "src/sksl/codegen/SkSLCodeGenerator.h"
35 #include "src/sksl/codegen/SkSLNativeShader.h"
36 #include "src/sksl/ir/SkSLBinaryExpression.h"
37 #include "src/sksl/ir/SkSLBlock.h"
38 #include "src/sksl/ir/SkSLConstructor.h"
39 #include "src/sksl/ir/SkSLConstructorArrayCast.h"
40 #include "src/sksl/ir/SkSLConstructorCompound.h"
41 #include "src/sksl/ir/SkSLConstructorMatrixResize.h"
42 #include "src/sksl/ir/SkSLDoStatement.h"
43 #include "src/sksl/ir/SkSLExpression.h"
44 #include "src/sksl/ir/SkSLExpressionStatement.h"
45 #include "src/sksl/ir/SkSLExtension.h"
46 #include "src/sksl/ir/SkSLFieldAccess.h"
47 #include "src/sksl/ir/SkSLForStatement.h"
48 #include "src/sksl/ir/SkSLFunctionCall.h"
49 #include "src/sksl/ir/SkSLFunctionDeclaration.h"
50 #include "src/sksl/ir/SkSLFunctionDefinition.h"
51 #include "src/sksl/ir/SkSLFunctionPrototype.h"
52 #include "src/sksl/ir/SkSLIRHelpers.h"
53 #include "src/sksl/ir/SkSLIRNode.h"
54 #include "src/sksl/ir/SkSLIfStatement.h"
55 #include "src/sksl/ir/SkSLIndexExpression.h"
56 #include "src/sksl/ir/SkSLInterfaceBlock.h"
57 #include "src/sksl/ir/SkSLLayout.h"
58 #include "src/sksl/ir/SkSLLiteral.h"
59 #include "src/sksl/ir/SkSLModifierFlags.h"
60 #include "src/sksl/ir/SkSLNop.h"
61 #include "src/sksl/ir/SkSLPostfixExpression.h"
62 #include "src/sksl/ir/SkSLPrefixExpression.h"
63 #include "src/sksl/ir/SkSLProgram.h"
64 #include "src/sksl/ir/SkSLProgramElement.h"
65 #include "src/sksl/ir/SkSLReturnStatement.h"
66 #include "src/sksl/ir/SkSLSetting.h"
67 #include "src/sksl/ir/SkSLStatement.h"
68 #include "src/sksl/ir/SkSLStructDefinition.h"
69 #include "src/sksl/ir/SkSLSwitchCase.h"
70 #include "src/sksl/ir/SkSLSwitchStatement.h"
71 #include "src/sksl/ir/SkSLSwizzle.h"
72 #include "src/sksl/ir/SkSLTernaryExpression.h"
73 #include "src/sksl/ir/SkSLType.h"
74 #include "src/sksl/ir/SkSLVarDeclarations.h"
75 #include "src/sksl/ir/SkSLVariable.h"
76 #include "src/sksl/ir/SkSLVariableReference.h"
77 #include "src/sksl/spirv.h"
78
79 #include <algorithm>
80 #include <cstddef>
81 #include <cstdint>
82 #include <functional>
83 #include <initializer_list>
84 #include <limits>
85 #include <memory>
86 #include <string>
87 #include <string_view>
88 #include <utility>
89 #include <vector>
90
91 using namespace skia_private;
92
93 namespace SkSL {
94
95 class MetalCodeGenerator : public CodeGenerator {
96 public:
97 MetalCodeGenerator(const Context* context,
98 const ShaderCaps* caps,
99 const Program* program,
100 OutputStream* out,
101 PrettyPrint pp)
102 : CodeGenerator(context, caps, program, out)
103 , fReservedWords({"atan2", "rsqrt", "rint", "dfdx", "dfdy", "vertex", "fragment"})
104 , fLineEnding("\n")
105 , fPrettyPrint(pp) {}
106
107 bool generateCode() override;
108
109 protected:
110 using Precedence = OperatorPrecedence;
111
112 using Requirements = int;
113 static constexpr Requirements kNo_Requirements = 0;
114 static constexpr Requirements kInputs_Requirement = 1 << 0;
115 static constexpr Requirements kOutputs_Requirement = 1 << 1;
116 static constexpr Requirements kUniforms_Requirement = 1 << 2;
117 static constexpr Requirements kGlobals_Requirement = 1 << 3;
118 static constexpr Requirements kFragCoord_Requirement = 1 << 4;
119 static constexpr Requirements kSampleMaskIn_Requirement = 1 << 5;
120 static constexpr Requirements kVertexID_Requirement = 1 << 6;
121 static constexpr Requirements kInstanceID_Requirement = 1 << 7;
122 static constexpr Requirements kThreadgroups_Requirement = 1 << 8;
123
124 class GlobalStructVisitor;
125 void visitGlobalStruct(GlobalStructVisitor* visitor);
126
127 class ThreadgroupStructVisitor;
128 void visitThreadgroupStruct(ThreadgroupStructVisitor* visitor);
129
130 void write(std::string_view s);
131
132 void writeLine(std::string_view s = std::string_view());
133
134 void finishLine();
135
136 void writeHeader();
137
138 void writeSampler2DPolyfill();
139
140 void writeUniformStruct();
141
142 void writeInterpolatedAttributes(const Variable& var);
143
144 void writeInputStruct();
145
146 void writeOutputStruct();
147
148 void writeInterfaceBlocks();
149
150 void writeStructDefinitions();
151
152 void writeConstantVariables();
153
154 void writeFields(SkSpan<const Field> fields, Position pos);
155
156 int size(const Type* type, bool isPacked) const;
157
158 int alignment(const Type* type, bool isPacked) const;
159
160 void writeGlobalStruct();
161
162 void writeGlobalInit();
163
164 void writeThreadgroupStruct();
165
166 void writeThreadgroupInit();
167
168 void writePrecisionModifier();
169
170 std::string typeName(const Type& type);
171
172 void writeStructDefinition(const StructDefinition& s);
173
174 void writeType(const Type& type);
175
176 void writeExtension(const Extension& ext);
177
178 void writeInterfaceBlock(const InterfaceBlock& intf);
179
180 void writeFunctionRequirementParams(const FunctionDeclaration& f,
181 const char*& separator);
182
183 void writeFunctionRequirementArgs(const FunctionDeclaration& f, const char*& separator);
184
185 bool writeFunctionDeclaration(const FunctionDeclaration& f);
186
187 void writeFunction(const FunctionDefinition& f);
188
189 void writeFunctionPrototype(const FunctionPrototype& f);
190
191 void writeLayout(const Layout& layout);
192
193 void writeModifiers(ModifierFlags flags);
194
195 void writeVarInitializer(const Variable& var, const Expression& value);
196
197 void writeName(std::string_view name);
198
199 void writeVarDeclaration(const VarDeclaration& decl);
200
201 void writeFragCoord();
202
203 void writeVariableReference(const VariableReference& ref);
204
205 void writeExpression(const Expression& expr, Precedence parentPrecedence);
206
207 void writeMinAbsHack(Expression& absExpr, Expression& otherExpr);
208
209 std::string getInversePolyfill(const ExpressionArray& arguments);
210
211 std::string getBitcastIntrinsic(const Type& outType);
212
213 std::string getTempVariable(const Type& varType);
214
215 void writeFunctionCall(const FunctionCall& c);
216
217 bool matrixConstructHelperIsNeeded(const ConstructorCompound& c);
218 std::string getMatrixConstructHelper(const AnyConstructor& c);
219 void assembleMatrixFromMatrix(const Type& sourceMatrix, int columns, int rows);
220 void assembleMatrixFromExpressions(const AnyConstructor& ctor, int columns, int rows);
221
222 void writeMatrixCompMult();
223
224 void writeOuterProduct();
225
226 void writeMatrixTimesEqualHelper(const Type& left, const Type& right, const Type& result);
227
228 void writeMatrixDivisionHelpers(const Type& type);
229
230 void writeMatrixEqualityHelpers(const Type& left, const Type& right);
231
232 std::string getVectorFromMat2x2ConstructorHelper(const Type& matrixType);
233
234 void writeArrayEqualityHelpers(const Type& type);
235
236 void writeStructEqualityHelpers(const Type& type);
237
238 void writeEqualityHelpers(const Type& leftType, const Type& rightType);
239
240 void writeArgumentList(const ExpressionArray& arguments);
241
242 void writeSimpleIntrinsic(const FunctionCall& c);
243
244 void writeScalarizedIntrinsicCall(const FunctionCall& c);
245
246 bool writeIntrinsicCall(const FunctionCall& c, IntrinsicKind kind);
247
248 void writeConstructorCompound(const ConstructorCompound& c, Precedence parentPrecedence);
249
250 void writeConstructorCompoundVector(const ConstructorCompound& c, Precedence parentPrecedence);
251
252 void writeConstructorCompoundMatrix(const ConstructorCompound& c, Precedence parentPrecedence);
253
254 void writeConstructorMatrixResize(const ConstructorMatrixResize& c,
255 Precedence parentPrecedence);
256
257 void writeAnyConstructor(const AnyConstructor& c,
258 const char* leftBracket,
259 const char* rightBracket,
260 Precedence parentPrecedence);
261
262 void writeCastConstructor(const AnyConstructor& c,
263 const char* leftBracket,
264 const char* rightBracket,
265 Precedence parentPrecedence);
266
267 void writeConstructorArrayCast(const ConstructorArrayCast& c, Precedence parentPrecedence);
268
269 void writeFieldAccess(const FieldAccess& f);
270
271 void writeSwizzle(const Swizzle& swizzle);
272
273 // Returns `floatCxR(1.0, 1.0, 1.0, 1.0, ...)`.
274 std::string splatMatrixOf1(const Type& type);
275
276 // Splats a scalar expression across a matrix of arbitrary size.
277 void writeNumberAsMatrix(const Expression& expr, const Type& matrixType);
278
279 void writeBinaryExpressionElement(const Expression& expr,
280 Operator op,
281 const Expression& other,
282 Precedence precedence);
283
284 void writeBinaryExpression(const BinaryExpression& b, Precedence parentPrecedence);
285
286 void writeTernaryExpression(const TernaryExpression& t, Precedence parentPrecedence);
287
288 void writeIndexExpression(const IndexExpression& expr);
289
290 void writeIndexInnerExpression(const Expression& expr);
291
292 void writePrefixExpression(const PrefixExpression& p, Precedence parentPrecedence);
293
294 void writePostfixExpression(const PostfixExpression& p, Precedence parentPrecedence);
295
296 void writeLiteral(const Literal& f);
297
298 void writeStatement(const Statement& s);
299
300 void writeStatements(const StatementArray& statements);
301
302 void writeBlock(const Block& b);
303
304 void writeIfStatement(const IfStatement& stmt);
305
306 void writeForStatement(const ForStatement& f);
307
308 void writeDoStatement(const DoStatement& d);
309
310 void writeExpressionStatement(const ExpressionStatement& s);
311
312 void writeSwitchStatement(const SwitchStatement& s);
313
314 void writeReturnStatementFromMain();
315
316 void writeReturnStatement(const ReturnStatement& r);
317
318 void writeProgramElement(const ProgramElement& e);
319
320 Requirements requirements(const FunctionDeclaration& f);
321
322 Requirements requirements(const Statement* s);
323
324 // For compute shader main functions, writes and initializes the _in and _out structs (the
325 // instances, not the types themselves)
326 void writeComputeMainInputs();
327
328 int getUniformBinding(const Layout& layout);
329
330 int getUniformSet(const Layout& layout);
331
332 void writeWithIndexSubstitution(const std::function<void()>& fn);
333
334 skia_private::THashSet<std::string_view> fReservedWords;
335 skia_private::THashMap<const Type*, std::string> fInterfaceBlockNameMap;
336 int fAnonInterfaceCount = 0;
337 int fPaddingCount = 0;
338 const char* fLineEnding;
339 std::string fFunctionHeader;
340 StringStream fExtraFunctions;
341 StringStream fExtraFunctionPrototypes;
342 int fVarCount = 0;
343 int fIndentation = 0;
344 bool fAtLineStart = false;
345 // true if we have run into usages of dFdx / dFdy
346 bool fFoundDerivatives = false;
347 skia_private::THashMap<const FunctionDeclaration*, Requirements> fRequirements;
348 skia_private::THashSet<std::string> fHelpers;
349 int fUniformBuffer = -1;
350 std::string fRTFlipName;
351 const FunctionDeclaration* fCurrentFunction = nullptr;
352 int fSwizzleHelperCount = 0;
353 static constexpr char kTextureSuffix[] = "_Tex";
354 static constexpr char kSamplerSuffix[] = "_Smplr";
355
356 // If we might use an index expression more than once, we need to capture the result in a
357 // temporary variable to avoid double-evaluation. This should generally only occur when emitting
358 // a function call, since we need to polyfill GLSL-style out-parameter support. (skbug.com/40045204)
359 // The map holds <index-expression, temp-variable name>.
360 using IndexSubstitutionMap = skia_private::THashMap<const Expression*, std::string>;
361
362 // When fIndexSubstitution is null (usually), index-substitution does not need to be performed.
363 struct IndexSubstitutionData {
364 IndexSubstitutionMap fMap;
365 StringStream fMainStream;
366 StringStream fPrefixStream;
367 bool fCreateSubstitutes = true;
368 };
369 std::unique_ptr<IndexSubstitutionData> fIndexSubstitutionData;
370 PrettyPrint fPrettyPrint;
371
372 // Workaround/polyfill flags
373 bool fWrittenInverse2 = false, fWrittenInverse3 = false, fWrittenInverse4 = false;
374 bool fWrittenMatrixCompMult = false;
375 bool fWrittenOuterProduct = false;
376 };
377
378 static const char* operator_name(Operator op) {
379 switch (op.kind()) {
380 case Operator::Kind::LOGICALXOR: return " != ";
381 default: return op.operatorName();
382 }
383 }
384
385 class MetalCodeGenerator::GlobalStructVisitor {
386 public:
387 virtual ~GlobalStructVisitor() = default;
388 virtual void visitInterfaceBlock(const InterfaceBlock& block, std::string_view blockName) {}
389 virtual void visitTexture(const Type& type, std::string_view name) {}
390 virtual void visitSampler(const Type& type, std::string_view name) {}
391 virtual void visitConstantVariable(const VarDeclaration& decl) {}
392 virtual void visitNonconstantVariable(const Variable& var, const Expression* value) {}
393 };
394
395 class MetalCodeGenerator::ThreadgroupStructVisitor {
396 public:
397 virtual ~ThreadgroupStructVisitor() = default;
398 virtual void visitNonconstantVariable(const Variable& var) = 0;
399 };
400
401 void MetalCodeGenerator::write(std::string_view s) {
402 if (s.empty()) {
403 return;
404 }
405 if (fAtLineStart && fPrettyPrint == PrettyPrint::kYes) {
406 for (int i = 0; i < fIndentation; i++) {
407 fOut->writeText(" ");
408 }
409 }
410 fOut->writeText(std::string(s).c_str());
411 fAtLineStart = false;
412 }
413
414 void MetalCodeGenerator::writeLine(std::string_view s) {
415 this->write(s);
416 fOut->writeText(fLineEnding);
417 fAtLineStart = true;
418 }
419
420 void MetalCodeGenerator::finishLine() {
421 if (!fAtLineStart) {
422 this->writeLine();
423 }
424 }
425
426 void MetalCodeGenerator::writeExtension(const Extension& ext) {
427 this->writeLine("#extension " + std::string(ext.name()) + " : enable");
428 }
429
430 std::string MetalCodeGenerator::typeName(const Type& raw) {
431 // we need to know the modifiers for textures
432 const Type& type = raw.resolve().scalarTypeForLiteral();
433 switch (type.typeKind()) {
434 case Type::TypeKind::kArray: {
435 std::string typeName = this->typeName(type.componentType());
436 if (type.isUnsizedArray()) {
437 return String::printf("const device %s*", typeName.c_str());
438 } else {
439 SkASSERTF(type.columns() > 0, "invalid array size: %s", type.description().c_str());
440 return String::printf("array<%s, %d>", typeName.c_str(), type.columns());
441 }
442 }
443 case Type::TypeKind::kVector:
444 return this->typeName(type.componentType()) + std::to_string(type.columns());
445
446 case Type::TypeKind::kMatrix:
447 return this->typeName(type.componentType()) + std::to_string(type.columns()) + "x" +
448 std::to_string(type.rows());
449
450 case Type::TypeKind::kSampler:
451 if (type.dimensions() != SpvDim2D) {
452 fContext.fErrors->error(Position(), "Unsupported texture dimensions");
453 }
454 return "sampler2D";
455
456 case Type::TypeKind::kTexture:
457 switch (type.textureAccess()) {
458 case Type::TextureAccess::kSample: return "texture2d<half>";
459 case Type::TextureAccess::kRead: return "texture2d<half, access::read>";
460 case Type::TextureAccess::kWrite: return "texture2d<half, access::write>";
461 case Type::TextureAccess::kReadWrite: return "texture2d<half, access::read_write>";
462 default: break;
463 }
464 SkUNREACHABLE;
465
466 case Type::TypeKind::kAtomic:
467 // SkSL currently only supports the atomicUint type.
468 SkASSERT(type.matches(*fContext.fTypes.fAtomicUInt));
469 return "atomic_uint";
470
471 default:
472 return std::string(type.name());
473 }
474 }
475
476 void MetalCodeGenerator::writeStructDefinition(const StructDefinition& s) {
477 const Type& type = s.type();
478 this->writeLine("struct " + type.displayName() + " {");
479 fIndentation++;
480 this->writeFields(type.fields(), type.fPosition);
481 fIndentation--;
482 this->writeLine("};");
483 }
484
485 void MetalCodeGenerator::writeType(const Type& type) {
486 this->write(this->typeName(type));
487 }
488
489 void MetalCodeGenerator::writeExpression(const Expression& expr, Precedence parentPrecedence) {
490 switch (expr.kind()) {
491 case Expression::Kind::kBinary:
492 this->writeBinaryExpression(expr.as<BinaryExpression>(), parentPrecedence);
493 break;
494 case Expression::Kind::kConstructorArray:
495 case Expression::Kind::kConstructorStruct:
496 this->writeAnyConstructor(expr.asAnyConstructor(), "{", "}", parentPrecedence);
497 break;
498 case Expression::Kind::kConstructorArrayCast:
499 this->writeConstructorArrayCast(expr.as<ConstructorArrayCast>(), parentPrecedence);
500 break;
501 case Expression::Kind::kConstructorCompound:
502 this->writeConstructorCompound(expr.as<ConstructorCompound>(), parentPrecedence);
503 break;
504 case Expression::Kind::kConstructorDiagonalMatrix:
505 case Expression::Kind::kConstructorSplat:
506 this->writeAnyConstructor(expr.asAnyConstructor(), "(", ")", parentPrecedence);
507 break;
508 case Expression::Kind::kConstructorMatrixResize:
509 this->writeConstructorMatrixResize(expr.as<ConstructorMatrixResize>(),
510 parentPrecedence);
511 break;
512 case Expression::Kind::kConstructorScalarCast:
513 case Expression::Kind::kConstructorCompoundCast:
514 this->writeCastConstructor(expr.asAnyConstructor(), "(", ")", parentPrecedence);
515 break;
516 case Expression::Kind::kEmpty:
517 this->write("false");
518 break;
519 case Expression::Kind::kFieldAccess:
520 this->writeFieldAccess(expr.as<FieldAccess>());
521 break;
522 case Expression::Kind::kLiteral:
523 this->writeLiteral(expr.as<Literal>());
524 break;
525 case Expression::Kind::kFunctionCall:
526 this->writeFunctionCall(expr.as<FunctionCall>());
527 break;
528 case Expression::Kind::kPrefix:
529 this->writePrefixExpression(expr.as<PrefixExpression>(), parentPrecedence);
530 break;
531 case Expression::Kind::kPostfix:
532 this->writePostfixExpression(expr.as<PostfixExpression>(), parentPrecedence);
533 break;
534 case Expression::Kind::kSetting:
535 this->writeExpression(*expr.as<Setting>().toLiteral(fCaps), parentPrecedence);
536 break;
537 case Expression::Kind::kSwizzle:
538 this->writeSwizzle(expr.as<Swizzle>());
539 break;
540 case Expression::Kind::kVariableReference:
541 this->writeVariableReference(expr.as<VariableReference>());
542 break;
543 case Expression::Kind::kTernary:
544 this->writeTernaryExpression(expr.as<TernaryExpression>(), parentPrecedence);
545 break;
546 case Expression::Kind::kIndex:
547 this->writeIndexExpression(expr.as<IndexExpression>());
548 break;
549 default:
550 SkDEBUGFAILF("unsupported expression: %s", expr.description().c_str());
551 break;
552 }
553 }
554
555 // returns true if we should pass by reference instead of by value
556 static bool pass_by_reference(const Type& type, ModifierFlags flags) {
557 return (flags & ModifierFlag::kOut) && !type.isUnsizedArray();
558 }
559
560 // returns true if we need to specify an address space modifier
561 static bool needs_address_space(const Type& type, ModifierFlags modifiers) {
562 return type.isUnsizedArray() || pass_by_reference(type, modifiers);
563 }
564
565 // returns true if the InterfaceBlock has the `buffer` modifier
566 static bool is_buffer(const InterfaceBlock& block) {
567 return block.var()->modifierFlags().isBuffer();
568 }
569
570 // returns true if the InterfaceBlock has the `readonly` modifier
571 static bool is_readonly(const InterfaceBlock& block) {
572 return block.var()->modifierFlags().isReadOnly();
573 }
574
575 std::string MetalCodeGenerator::getBitcastIntrinsic(const Type& outType) {
576 return "as_type<" + outType.displayName() + ">";
577 }
578
579 void MetalCodeGenerator::writeWithIndexSubstitution(const std::function<void()>& fn) {
580 auto oldIndexSubstitutionData = std::make_unique<IndexSubstitutionData>();
581 fIndexSubstitutionData.swap(oldIndexSubstitutionData);
582
583 // Invoke our helper function, with output going into our temporary stream.
584 {
585 AutoOutputStream outputToMainStream(this, &fIndexSubstitutionData->fMainStream);
586 fn();
587 }
588
589 if (fIndexSubstitutionData->fPrefixStream.bytesWritten() == 0) {
590 // Emit the main stream into the program as-is.
591 write_stringstream(fIndexSubstitutionData->fMainStream, *fOut);
592 } else {
593 // Emit the prefix stream and main stream into the program as a sequence-expression.
594 // (Each prefix-expression must end with a comma.)
595 this->write("(");
596 write_stringstream(fIndexSubstitutionData->fPrefixStream, *fOut);
597 write_stringstream(fIndexSubstitutionData->fMainStream, *fOut);
598 this->write(")");
599 }
600
601 fIndexSubstitutionData.swap(oldIndexSubstitutionData);
602 }
603
604 void MetalCodeGenerator::writeFunctionCall(const FunctionCall& c) {
605 const FunctionDeclaration& function = c.function();
606
607 // Many intrinsics need to be rewritten in Metal.
608 if (function.isIntrinsic()) {
609 if (this->writeIntrinsicCall(c, function.intrinsicKind())) {
610 return;
611 }
612 }
613
614 // Look for out parameters. SkSL guarantees GLSL's out-param semantics, and we need to emulate
615 // it if an out-param is encountered. (Specifically, out-parameters in GLSL are only written
616 // back to the original variable at the end of the function call; also, swizzles are supported,
617 // whereas Metal doesn't allow a swizzle to be passed to a `floatN&`.)
618 const ExpressionArray& arguments = c.arguments();
619 SkSpan<Variable* const> parameters = function.parameters();
620 SkASSERT(SkToSizeT(arguments.size()) == parameters.size());
621
622 bool foundOutParam = false;
623 STArray<16, std::string> scratchVarName;
624 scratchVarName.push_back_n(arguments.size(), std::string());
625
626 for (int index = 0; index < arguments.size(); ++index) {
627 // If this is an out parameter...
628 if (parameters[index]->modifierFlags() & ModifierFlag::kOut) {
629 // Assignability was verified at IRGeneration time, so this should always succeed.
630 [[maybe_unused]] Analysis::AssignmentInfo info;
631 SkASSERT(Analysis::IsAssignable(*arguments[index], &info));
632
633 scratchVarName[index] = this->getTempVariable(arguments[index]->type());
634 foundOutParam = true;
635 }
636 }
637
638 if (foundOutParam) {
639 // Out parameters need to be written back to at the end of the function. To do this, we
640 // generate a comma-separated sequence expression that copies the out-param expressions into
641 // our temporary variables, calls the original function--storing its result into a scratch
642 // variable--and then writes the temp variables back into the original out params using the
643 // original out-param expressions. This would look something like:
644 //
645 // ((_skResult = func((_skTemp = myOutParam.x), 123)), (myOutParam.x = _skTemp), _skResult)
646 // ^ ^ ^ ^
647 // return value passes copy of argument copies back into argument return value
648 //
649 // While these expressions are complex, they allow us to maintain the proper sequencing that
650 // is necessary for out-parameters, as well as allowing us to support things like swizzles
651 // and array indices which Metal references cannot natively handle.
652
653 // We will be emitting inout expressions twice, so it's important to enable index
654 // substitution in case we encounter any side-effecting indexes.
655 this->writeWithIndexSubstitution([&] {
656 this->write("((");
657
658 // ((_skResult =
659 std::string scratchResultName;
660 if (!function.returnType().isVoid()) {
661 scratchResultName = this->getTempVariable(c.type());
662 this->write(scratchResultName);
663 this->write(" = ");
664 }
665
666 // ((_skResult = func(
667 this->write(function.mangledName());
668 this->write("(");
669
670 // ((_skResult = func((_skTemp = myOutParam.x), 123
671 const char* separator = "";
672 this->writeFunctionRequirementArgs(function, separator);
673
674 for (int i = 0; i < arguments.size(); ++i) {
675 this->write(separator);
676 separator = ", ";
677 if (parameters[i]->modifierFlags() & ModifierFlag::kOut) {
678 SkASSERT(!scratchVarName[i].empty());
679 if (parameters[i]->modifierFlags() & ModifierFlag::kIn) {
680 // `inout` parameters initialize the scratch variable with the passed-in
681 // argument's value.
682 this->write("(");
683 this->write(scratchVarName[i]);
684 this->write(" = ");
685 this->writeExpression(*arguments[i], Precedence::kAssignment);
686 this->write(")");
687 } else {
688 // `out` parameters pass a reference to the uninitialized scratch variable.
689 this->write(scratchVarName[i]);
690 }
691 } else {
692 // Regular parameters are passed as-is.
693 this->writeExpression(*arguments[i], Precedence::kSequence);
694 }
695 }
696
697 // ((_skResult = func((_skTemp = myOutParam.x), 123))
698 this->write("))");
699
700 // ((_skResult = func((_skTemp = myOutParam.x), 123)), (myOutParam.x = _skTemp)
701 for (int i = 0; i < arguments.size(); ++i) {
702 if (!scratchVarName[i].empty()) {
703 this->write(", (");
704 this->writeExpression(*arguments[i], Precedence::kAssignment);
705 this->write(" = ");
706 this->write(scratchVarName[i]);
707 this->write(")");
708 }
709 }
710
711 // ((_skResult = func((_skTemp = myOutParam.x), 123)), (myOutParam.x = _skTemp),
712 // _skResult
713 if (!scratchResultName.empty()) {
714 this->write(", ");
715 this->write(scratchResultName);
716 }
717
718 // ((_skResult = func((_skTemp = myOutParam.x), 123)), (myOutParam.x = _skTemp),
719 // _skResult)
720 this->write(")");
721 });
722 } else {
723 // Emit the function call as-is, only prepending the required arguments.
724 this->write(function.mangledName());
725 this->write("(");
726 const char* separator = "";
727 this->writeFunctionRequirementArgs(function, separator);
728 for (int i = 0; i < arguments.size(); ++i) {
729 SkASSERT(scratchVarName[i].empty());
730 this->write(separator);
731 separator = ", ";
732 this->writeExpression(*arguments[i], Precedence::kSequence);
733 }
734 this->write(")");
735 }
736 }
737
738 static constexpr char kInverse2x2[] =
739 "template <typename T>"
740 "matrix<T, 2, 2> mat2_inverse(matrix<T, 2, 2> m) {"
741 "return matrix<T, 2, 2>(m[1].y, -m[0].y, -m[1].x, m[0].x) * (1/determinant(m));"
742 "}";
743
744 static constexpr char kInverse3x3[] =
745 "template <typename T>"
746 "matrix<T, 3, 3> mat3_inverse(matrix<T, 3, 3> m) {"
747 "T "
748 "a00 = m[0].x, a01 = m[0].y, a02 = m[0].z,"
749 "a10 = m[1].x, a11 = m[1].y, a12 = m[1].z,"
750 "a20 = m[2].x, a21 = m[2].y, a22 = m[2].z,"
751 "b01 = a22*a11 - a12*a21,"
752 "b11 = -a22*a10 + a12*a20,"
753 "b21 = a21*a10 - a11*a20,"
754 "det = a00*b01 + a01*b11 + a02*b21;"
755 "return matrix<T, 3, 3>("
756 "b01, (-a22*a01 + a02*a21), ( a12*a01 - a02*a11),"
757 "b11, ( a22*a00 - a02*a20), (-a12*a00 + a02*a10),"
758 "b21, (-a21*a00 + a01*a20), ( a11*a00 - a01*a10)) * (1/det);"
759 "}";
760
761 static constexpr char kInverse4x4[] =
762 "template <typename T>"
763 "matrix<T, 4, 4> mat4_inverse(matrix<T, 4, 4> m) {"
764 "T "
765 "a00 = m[0].x, a01 = m[0].y, a02 = m[0].z, a03 = m[0].w,"
766 "a10 = m[1].x, a11 = m[1].y, a12 = m[1].z, a13 = m[1].w,"
767 "a20 = m[2].x, a21 = m[2].y, a22 = m[2].z, a23 = m[2].w,"
768 "a30 = m[3].x, a31 = m[3].y, a32 = m[3].z, a33 = m[3].w,"
769 "b00 = a00*a11 - a01*a10,"
770 "b01 = a00*a12 - a02*a10,"
771 "b02 = a00*a13 - a03*a10,"
772 "b03 = a01*a12 - a02*a11,"
773 "b04 = a01*a13 - a03*a11,"
774 "b05 = a02*a13 - a03*a12,"
775 "b06 = a20*a31 - a21*a30,"
776 "b07 = a20*a32 - a22*a30,"
777 "b08 = a20*a33 - a23*a30,"
778 "b09 = a21*a32 - a22*a31,"
779 "b10 = a21*a33 - a23*a31,"
780 "b11 = a22*a33 - a23*a32,"
781 "det = b00*b11 - b01*b10 + b02*b09 + b03*b08 - b04*b07 + b05*b06;"
782 "return matrix<T, 4, 4>("
783 "a11*b11 - a12*b10 + a13*b09,"
784 "a02*b10 - a01*b11 - a03*b09,"
785 "a31*b05 - a32*b04 + a33*b03,"
786 "a22*b04 - a21*b05 - a23*b03,"
787 "a12*b08 - a10*b11 - a13*b07,"
788 "a00*b11 - a02*b08 + a03*b07,"
789 "a32*b02 - a30*b05 - a33*b01,"
790 "a20*b05 - a22*b02 + a23*b01,"
791 "a10*b10 - a11*b08 + a13*b06,"
792 "a01*b08 - a00*b10 - a03*b06,"
793 "a30*b04 - a31*b02 + a33*b00,"
794 "a21*b02 - a20*b04 - a23*b00,"
795 "a11*b07 - a10*b09 - a12*b06,"
796 "a00*b09 - a01*b07 + a02*b06,"
797 "a31*b01 - a30*b03 - a32*b00,"
798 "a20*b03 - a21*b01 + a22*b00) * (1/det);"
799 "}";
800
801 std::string MetalCodeGenerator::getInversePolyfill(const ExpressionArray& arguments) {
802 // Only use polyfills for a function taking a single-argument square matrix.
803 SkASSERT(arguments.size() == 1);
804 const Type& type = arguments.front()->type();
805 if (type.isMatrix() && type.rows() == type.columns()) {
806 switch (type.rows()) {
807 case 2:
808 if (!fWrittenInverse2) {
809 fWrittenInverse2 = true;
810 fExtraFunctions.writeText(kInverse2x2);
811 }
812 return "mat2_inverse";
813 case 3:
814 if (!fWrittenInverse3) {
815 fWrittenInverse3 = true;
816 fExtraFunctions.writeText(kInverse3x3);
817 }
818 return "mat3_inverse";
819 case 4:
820 if (!fWrittenInverse4) {
821 fWrittenInverse4 = true;
822 fExtraFunctions.writeText(kInverse4x4);
823 }
824 return "mat4_inverse";
825 }
826 }
827 SkDEBUGFAILF("no polyfill for inverse(%s)", type.description().c_str());
828 return "inverse";
829 }
830
831 void MetalCodeGenerator::writeMatrixCompMult() {
832 static constexpr char kMatrixCompMult[] =
833 "template <typename T, int C, int R>"
834 "matrix<T, C, R> matrixCompMult(matrix<T, C, R> a, const matrix<T, C, R> b) {"
835 "for (int c = 0; c < C; ++c) { a[c] *= b[c]; }"
836 "return a;"
837 "}";
838 if (!fWrittenMatrixCompMult) {
839 fWrittenMatrixCompMult = true;
840 fExtraFunctions.writeText(kMatrixCompMult);
841 }
842 }
843
844 void MetalCodeGenerator::writeOuterProduct() {
845 static constexpr char kOuterProduct[] =
846 "template <typename T, int C, int R>"
847 "matrix<T, C, R> outerProduct(const vec<T, R> a, const vec<T, C> b) {"
848 "matrix<T, C, R> m;"
849 "for (int c = 0; c < C; ++c) { m[c] = a * b[c]; }"
850 "return m;"
851 "}";
852 if (!fWrittenOuterProduct) {
853 fWrittenOuterProduct = true;
854 fExtraFunctions.writeText(kOuterProduct);
855 }
856 }
857
858 std::string MetalCodeGenerator::getTempVariable(const Type& type) {
859 std::string tempVar = "_skTemp" + std::to_string(fVarCount++);
860 this->fFunctionHeader += " " + this->typeName(type) + " " + tempVar + ";\n";
861 return tempVar;
862 }
863
864 void MetalCodeGenerator::writeSimpleIntrinsic(const FunctionCall& c) {
865 // Write out an intrinsic function call exactly as-is. No muss no fuss.
866 this->write(c.function().name());
867 this->writeArgumentList(c.arguments());
868 }
869
870 void MetalCodeGenerator::writeArgumentList(const ExpressionArray& arguments) {
871 this->write("(");
872 const char* separator = "";
873 for (const std::unique_ptr<Expression>& arg : arguments) {
874 this->write(separator);
875 separator = ", ";
876 this->writeExpression(*arg, Precedence::kSequence);
877 }
878 this->write(")");
879 }
880
881 void MetalCodeGenerator::writeScalarizedIntrinsicCall(const FunctionCall& c){
882 SkASSERT(!c.arguments().empty());
883 const ExpressionArray& arguments = c.arguments();
884 const Expression& primaryArg = *arguments[0];
885 int columns = primaryArg.type().columns();
886
887 static constexpr std::array<const char*, 4> kSwizzleChars = { "x", "y", "z", "w" };
888 this->writeWithIndexSubstitution([&]() {
889 this->writeType(primaryArg.type());
890 this->write("(");
891 for (int i = 0; i < columns; ++i) {
892 if (i) { this->write(", "); }
893 this->write(c.function().mangledName());
894 this->write("(");
895 for (int32_t j = 0; j < arguments.size(); ++j) {
896 if (j) { this->write(", "); }
897 if (arguments[j]->type().isScalar()) {
898 this->writeExpression(*arguments[j], Precedence::kSequence);
899 } else {
900 this->writeIndexInnerExpression(*arguments[j]);
901 this->write(".");
902 this->write(kSwizzleChars[i]);
903 }
904 }
905 this->write(")");
906 }
907 this->write(")");
908 });
909 }
910
911 bool MetalCodeGenerator::writeIntrinsicCall(const FunctionCall& c, IntrinsicKind kind) {
912 const ExpressionArray& arguments = c.arguments();
913 switch (kind) {
914 case k_textureRead_IntrinsicKind: {
915 this->writeExpression(*arguments[0], Precedence::kExpression);
916 this->write(".read(");
917 this->writeExpression(*arguments[1], Precedence::kSequence);
918 this->write(")");
919 return true;
920 }
921 case k_textureWrite_IntrinsicKind: {
922 this->writeExpression(*arguments[0], Precedence::kExpression);
923 this->write(".write(");
924 this->writeExpression(*arguments[2], Precedence::kSequence);
925 this->write(", ");
926 this->writeExpression(*arguments[1], Precedence::kSequence);
927 this->write(")");
928 return true;
929 }
930 case k_textureWidth_IntrinsicKind: {
931 this->writeExpression(*arguments[0], Precedence::kExpression);
932 this->write(".get_width()");
933 return true;
934 }
935 case k_textureHeight_IntrinsicKind: {
936 this->writeExpression(*arguments[0], Precedence::kExpression);
937 this->write(".get_height()");
938 return true;
939 }
940 case k_mod_IntrinsicKind: {
941 // fmod(x, y) in metal calculates x - y * trunc(x / y) instead of x - y * floor(x / y)
942 std::string tmpX = this->getTempVariable(arguments[0]->type());
943 std::string tmpY = this->getTempVariable(arguments[1]->type());
944 this->write("(" + tmpX + " = ");
945 this->writeExpression(*arguments[0], Precedence::kSequence);
946 this->write(", " + tmpY + " = ");
947 this->writeExpression(*arguments[1], Precedence::kSequence);
948 this->write(", " + tmpX + " - " + tmpY + " * floor(" + tmpX + " / " + tmpY + "))");
949 return true;
950 }
951 case k_pow_IntrinsicKind: {
952 // The Metal equivalent to GLSL's pow() is powr(). Metal's pow() allows negative base
953 // values, which is presumably more expensive to compute.
954 this->write("powr(");
955 this->writeExpression(*arguments[0], Precedence::kSequence);
956 this->write(", ");
957 this->writeExpression(*arguments[1], Precedence::kSequence);
958 this->write(")");
959 return true;
960 }
961 // GLSL declares scalar versions of most geometric intrinsics, but these don't exist in MSL
962 case k_distance_IntrinsicKind: {
963 if (arguments[0]->type().columns() == 1) {
964 this->write("abs(");
965 this->writeExpression(*arguments[0], Precedence::kAdditive);
966 this->write(" - ");
967 this->writeExpression(*arguments[1], Precedence::kAdditive);
968 this->write(")");
969 } else {
970 this->writeSimpleIntrinsic(c);
971 }
972 return true;
973 }
974 case k_dot_IntrinsicKind: {
975 if (arguments[0]->type().columns() == 1) {
976 this->write("(");
977 this->writeExpression(*arguments[0], Precedence::kMultiplicative);
978 this->write(" * ");
979 this->writeExpression(*arguments[1], Precedence::kMultiplicative);
980 this->write(")");
981 } else {
982 this->writeSimpleIntrinsic(c);
983 }
984 return true;
985 }
986 case k_faceforward_IntrinsicKind: {
987 if (arguments[0]->type().columns() == 1) {
988 // ((((Nref) * (I) < 0) ? 1 : -1) * (N))
989 this->write("((((");
990 this->writeExpression(*arguments[2], Precedence::kSequence);
991 this->write(") * (");
992 this->writeExpression(*arguments[1], Precedence::kSequence);
993 this->write(") < 0) ? 1 : -1) * (");
994 this->writeExpression(*arguments[0], Precedence::kSequence);
995 this->write("))");
996 } else {
997 this->writeSimpleIntrinsic(c);
998 }
999 return true;
1000 }
1001 case k_length_IntrinsicKind: {
1002 this->write(arguments[0]->type().columns() == 1 ? "abs(" : "length(");
1003 this->writeExpression(*arguments[0], Precedence::kSequence);
1004 this->write(")");
1005 return true;
1006 }
1007 case k_normalize_IntrinsicKind: {
1008 this->write(arguments[0]->type().columns() == 1 ? "sign(" : "normalize(");
1009 this->writeExpression(*arguments[0], Precedence::kSequence);
1010 this->write(")");
1011 return true;
1012 }
1013 case k_packUnorm2x16_IntrinsicKind: {
1014 this->write("pack_float_to_unorm2x16(");
1015 this->writeExpression(*arguments[0], Precedence::kSequence);
1016 this->write(")");
1017 return true;
1018 }
1019 case k_unpackUnorm2x16_IntrinsicKind: {
1020 this->write("unpack_unorm2x16_to_float(");
1021 this->writeExpression(*arguments[0], Precedence::kSequence);
1022 this->write(")");
1023 return true;
1024 }
1025 case k_packSnorm2x16_IntrinsicKind: {
1026 this->write("pack_float_to_snorm2x16(");
1027 this->writeExpression(*arguments[0], Precedence::kSequence);
1028 this->write(")");
1029 return true;
1030 }
1031 case k_unpackSnorm2x16_IntrinsicKind: {
1032 this->write("unpack_snorm2x16_to_float(");
1033 this->writeExpression(*arguments[0], Precedence::kSequence);
1034 this->write(")");
1035 return true;
1036 }
1037 case k_packUnorm4x8_IntrinsicKind: {
1038 this->write("pack_float_to_unorm4x8(");
1039 this->writeExpression(*arguments[0], Precedence::kSequence);
1040 this->write(")");
1041 return true;
1042 }
1043 case k_unpackUnorm4x8_IntrinsicKind: {
1044 this->write("unpack_unorm4x8_to_float(");
1045 this->writeExpression(*arguments[0], Precedence::kSequence);
1046 this->write(")");
1047 return true;
1048 }
1049 case k_packSnorm4x8_IntrinsicKind: {
1050 this->write("pack_float_to_snorm4x8(");
1051 this->writeExpression(*arguments[0], Precedence::kSequence);
1052 this->write(")");
1053 return true;
1054 }
1055 case k_unpackSnorm4x8_IntrinsicKind: {
1056 this->write("unpack_snorm4x8_to_float(");
1057 this->writeExpression(*arguments[0], Precedence::kSequence);
1058 this->write(")");
1059 return true;
1060 }
1061 case k_packHalf2x16_IntrinsicKind: {
1062 this->write("as_type<uint>(half2(");
1063 this->writeExpression(*arguments[0], Precedence::kSequence);
1064 this->write("))");
1065 return true;
1066 }
1067 case k_unpackHalf2x16_IntrinsicKind: {
1068 this->write("float2(as_type<half2>(");
1069 this->writeExpression(*arguments[0], Precedence::kSequence);
1070 this->write("))");
1071 return true;
1072 }
1073 case k_floatBitsToInt_IntrinsicKind:
1074 case k_floatBitsToUint_IntrinsicKind:
1075 case k_intBitsToFloat_IntrinsicKind:
1076 case k_uintBitsToFloat_IntrinsicKind: {
1077 this->write(this->getBitcastIntrinsic(c.type()));
1078 this->write("(");
1079 this->writeExpression(*arguments[0], Precedence::kSequence);
1080 this->write(")");
1081 return true;
1082 }
1083 case k_degrees_IntrinsicKind: {
1084 this->write("((");
1085 this->writeExpression(*arguments[0], Precedence::kSequence);
1086 this->write(") * 57.2957795)");
1087 return true;
1088 }
1089 case k_radians_IntrinsicKind: {
1090 this->write("((");
1091 this->writeExpression(*arguments[0], Precedence::kSequence);
1092 this->write(") * 0.0174532925)");
1093 return true;
1094 }
1095 case k_dFdx_IntrinsicKind: {
1096 this->write("dfdx");
1097 this->writeArgumentList(c.arguments());
1098 return true;
1099 }
1100 case k_dFdy_IntrinsicKind: {
1101 if (!fRTFlipName.empty()) {
1102 this->write("(" + fRTFlipName + ".y * dfdy");
1103 } else {
1104 this->write("(dfdy");
1105 }
1106 this->writeArgumentList(c.arguments());
1107 this->write(")");
1108 return true;
1109 }
1110 case k_inverse_IntrinsicKind: {
1111 this->write(this->getInversePolyfill(arguments));
1112 this->writeArgumentList(c.arguments());
1113 return true;
1114 }
1115 case k_inversesqrt_IntrinsicKind: {
1116 this->write("rsqrt");
1117 this->writeArgumentList(c.arguments());
1118 return true;
1119 }
1120 case k_atan_IntrinsicKind: {
1121 this->write(c.arguments().size() == 2 ? "atan2" : "atan");
1122 this->writeArgumentList(c.arguments());
1123 return true;
1124 }
1125 case k_reflect_IntrinsicKind: {
1126 if (arguments[0]->type().columns() == 1) {
1127 // We need to synthesize `I - 2 * N * I * N`.
1128 std::string tmpI = this->getTempVariable(arguments[0]->type());
1129 std::string tmpN = this->getTempVariable(arguments[1]->type());
1130
1131 // (_skTempI = ...
1132 this->write("(" + tmpI + " = ");
1133 this->writeExpression(*arguments[0], Precedence::kSequence);
1134
1135 // , _skTempN = ...
1136 this->write(", " + tmpN + " = ");
1137 this->writeExpression(*arguments[1], Precedence::kSequence);
1138
1139 // , _skTempI - 2 * _skTempN * _skTempI * _skTempN)
1140 this->write(", " + tmpI + " - 2 * " + tmpN + " * " + tmpI + " * " + tmpN + ")");
1141 } else {
1142 this->writeSimpleIntrinsic(c);
1143 }
1144 return true;
1145 }
1146 case k_refract_IntrinsicKind: {
1147 if (arguments[0]->type().columns() == 1) {
1148 // Metal does implement refract for vectors; rather than reimplementing refract from
1149 // scratch, we can replace the call with `refract(float2(I,0), float2(N,0), eta).x`.
1150 this->write("(refract(float2(");
1151 this->writeExpression(*arguments[0], Precedence::kSequence);
1152 this->write(", 0), float2(");
1153 this->writeExpression(*arguments[1], Precedence::kSequence);
1154 this->write(", 0), ");
1155 this->writeExpression(*arguments[2], Precedence::kSequence);
1156 this->write(").x)");
1157 } else {
1158 this->writeSimpleIntrinsic(c);
1159 }
1160 return true;
1161 }
1162 case k_roundEven_IntrinsicKind: {
1163 this->write("rint");
1164 this->writeArgumentList(c.arguments());
1165 return true;
1166 }
1167 case k_bitCount_IntrinsicKind: {
1168 // Cast to the signed return type required in SkSL
1169 if (!c.arguments()[0]->type().componentType().isSigned()) {
1170 this->write(this->typeName(c.type()));
1171 }
1172 this->write("(popcount(");
1173 this->writeExpression(*arguments[0], Precedence::kSequence);
1174 this->write("))");
1175 return true;
1176 }
1177 case k_findLSB_IntrinsicKind: {
1178 // Create a temp variable to store the expression, to avoid double-evaluating it.
1179 std::string skTemp = this->getTempVariable(arguments[0]->type());
1180 std::string signedType = this->typeName(c.type()); // The return type is always signed
1181 std::string exprType = this->typeName(arguments[0]->type());
1182
1183 // ctz returns numbits(type) on zero inputs; GLSL documents it as generating -1 instead.
1184 // - Use select to detect zero inputs and force a -1 result.
1185 // - ctz returns an unsigned value for unsigned inputs, so we have to cast back to int
1186
1187 // (_skTemp1 = (.....), select(int4(ctz(_skTemp1)), int4(-1), _skTemp1 == int4(0)))
1188 this->write("(");
1189 this->write(skTemp);
1190 this->write(" = (");
1191 this->writeExpression(*arguments[0], Precedence::kSequence);
1192 this->write("), select(");
1193 if (!c.arguments()[0]->type().componentType().isSigned()) {
1194 this->write(signedType);
1195 }
1196 this->write("(ctz(");
1197 this->write(skTemp);
1198 this->write(")), ");
1199 this->write(signedType);
1200 this->write("(-1), ");
1201 this->write(skTemp);
1202 this->write(" == ");
1203 this->write(exprType);
1204 this->write("(0)))");
1205 return true;
1206 }
1207 case k_findMSB_IntrinsicKind: {
1208 // Create a temp variable to store the expression, to avoid double-evaluating it.
1209 std::string skTemp1 = this->getTempVariable(arguments[0]->type());
1210 std::string signedType = this->typeName(c.type()); // The return type is always signed
1211 std::string exprType = this->typeName(arguments[0]->type());
1212
1213 // GLSL findMSB is actually quite different from Metal's clz:
1214 // - For signed negative numbers, it returns the first zero bit, not the first one bit!
1215 // - For an empty input (0/~0 depending on sign), findMSB gives -1; clz is numbits(type)
1216 // - clz is relative to the MSB whereas findMSB returns a 0-based bit number
1217 // - clz returns an unsigned value for unsigned inputs, so we have to cast back to int
1218
1219 // (_skTemp1 = (.....),
1220 this->write("(");
1221 this->write(skTemp1);
1222 this->write(" = (");
1223 this->writeExpression(*arguments[0], Precedence::kSequence);
1224 this->write("), ");
1225
1226 // Signed input types might be negative; we need another helper variable to negate the
1227 // input (since we can only find one bits, not zero bits).
1228 std::string skTemp2;
1229 if (arguments[0]->type().isSigned()) {
1230 // ... _skTemp2 = (select(_skTemp1, ~_skTemp1, _skTemp1 < 0)),
1231 skTemp2 = this->getTempVariable(arguments[0]->type());
1232 this->write(skTemp2);
1233 this->write(" = (select(");
1234 this->write(skTemp1);
1235 this->write(", ~");
1236 this->write(skTemp1);
1237 this->write(", ");
1238 this->write(skTemp1);
1239 this->write(" < 0)), ");
1240 } else {
1241 skTemp2 = skTemp1;
1242 }
1243
1244 // ... select(int4(31) - int4(clz(_skTemp2)), int4(-1), _skTemp2 == int4(0)))
1245 this->write("select(31 - "); // Assuming 32-bit integer types
1246 if (!c.arguments()[0]->type().componentType().isSigned()) {
1247 this->write(signedType);
1248 }
1249 this->write("(clz(");
1250 this->write(skTemp2);
1251 this->write(")), ");
1252 this->write(signedType);
1253 this->write("(-1), ");
1254 this->write(skTemp2);
1255 this->write(" == ");
1256 this->write(exprType);
1257 this->write("(0)))");
1258 return true;
1259 }
1260 case k_sign_IntrinsicKind: {
1261 if (arguments[0]->type().componentType().isInteger()) {
1262 // Create a temp variable to store the expression, to avoid double-evaluating it.
1263 std::string skTemp = this->getTempVariable(arguments[0]->type());
1264 std::string exprType = this->typeName(arguments[0]->type());
1265
1266 // (_skTemp = (.....),
1267 this->write("(");
1268 this->write(skTemp);
1269 this->write(" = (");
1270 this->writeExpression(*arguments[0], Precedence::kSequence);
1271 this->write("), ");
1272
1273 // ... select(select(int4(0), int4(-1), _skTemp < 0), int4(1), _skTemp > 0))
1274 this->write("select(select(");
1275 this->write(exprType);
1276 this->write("(0), ");
1277 this->write(exprType);
1278 this->write("(-1), ");
1279 this->write(skTemp);
1280 this->write(" < 0), ");
1281 this->write(exprType);
1282 this->write("(1), ");
1283 this->write(skTemp);
1284 this->write(" > 0))");
1285 } else {
1286 this->writeSimpleIntrinsic(c);
1287 }
1288 return true;
1289 }
1290 case k_matrixCompMult_IntrinsicKind: {
1291 this->writeMatrixCompMult();
1292 this->writeSimpleIntrinsic(c);
1293 return true;
1294 }
1295 case k_outerProduct_IntrinsicKind: {
1296 this->writeOuterProduct();
1297 this->writeSimpleIntrinsic(c);
1298 return true;
1299 }
1300 case k_mix_IntrinsicKind: {
1301 SkASSERT(c.arguments().size() == 3);
1302 if (arguments[2]->type().componentType().isBoolean()) {
1303 // The Boolean forms of GLSL mix() use the select() intrinsic in Metal.
1304 this->write("select");
1305 this->writeArgumentList(c.arguments());
1306 return true;
1307 }
1308 // The basic form of mix() is supported by Metal as-is.
1309 this->writeSimpleIntrinsic(c);
1310 return true;
1311 }
1312 case k_equal_IntrinsicKind:
1313 case k_greaterThan_IntrinsicKind:
1314 case k_greaterThanEqual_IntrinsicKind:
1315 case k_lessThan_IntrinsicKind:
1316 case k_lessThanEqual_IntrinsicKind:
1317 case k_notEqual_IntrinsicKind: {
1318 this->write("(");
1319 this->writeExpression(*c.arguments()[0], Precedence::kRelational);
1320 switch (kind) {
1321 case k_equal_IntrinsicKind:
1322 this->write(" == ");
1323 break;
1324 case k_notEqual_IntrinsicKind:
1325 this->write(" != ");
1326 break;
1327 case k_lessThan_IntrinsicKind:
1328 this->write(" < ");
1329 break;
1330 case k_lessThanEqual_IntrinsicKind:
1331 this->write(" <= ");
1332 break;
1333 case k_greaterThan_IntrinsicKind:
1334 this->write(" > ");
1335 break;
1336 case k_greaterThanEqual_IntrinsicKind:
1337 this->write(" >= ");
1338 break;
1339 default:
1340 SK_ABORT("unsupported comparison intrinsic kind");
1341 }
1342 this->writeExpression(*c.arguments()[1], Precedence::kRelational);
1343 this->write(")");
1344 return true;
1345 }
1346 case k_storageBarrier_IntrinsicKind:
1347 this->write("threadgroup_barrier(mem_flags::mem_device)");
1348 return true;
1349 case k_workgroupBarrier_IntrinsicKind:
1350 this->write("threadgroup_barrier(mem_flags::mem_threadgroup)");
1351 return true;
1352 case k_atomicAdd_IntrinsicKind:
1353 this->write("atomic_fetch_add_explicit(&");
1354 this->writeExpression(*c.arguments()[0], Precedence::kSequence);
1355 this->write(", ");
1356 this->writeExpression(*c.arguments()[1], Precedence::kSequence);
1357 this->write(", memory_order_relaxed)");
1358 return true;
1359 case k_atomicLoad_IntrinsicKind:
1360 this->write("atomic_load_explicit(&");
1361 this->writeExpression(*c.arguments()[0], Precedence::kSequence);
1362 this->write(", memory_order_relaxed)");
1363 return true;
1364 case k_atomicStore_IntrinsicKind:
1365 this->write("atomic_store_explicit(&");
1366 this->writeExpression(*c.arguments()[0], Precedence::kSequence);
1367 this->write(", ");
1368 this->writeExpression(*c.arguments()[1], Precedence::kSequence);
1369 this->write(", memory_order_relaxed)");
1370 return true;
1371 case k_min_IntrinsicKind:
1372 [[fallthrough]];
1373 case k_max_IntrinsicKind:
1374 [[fallthrough]];
1375 case k_clamp_IntrinsicKind: {
1376 SkASSERT(c.function().mangledName() == "min" || c.function().mangledName() == "max" ||
1377 c.function().mangledName() == "clamp");
1378 SkASSERT(!c.type().isMatrix());
1379 if (fCaps.fVectorClampMinMaxSupport || !c.type().isVector()) {
1380 this->writeSimpleIntrinsic(c);
1381 } else {
1382 this->writeScalarizedIntrinsicCall(c);
1383 }
1384 return true;
1385 }
1386 default:
1387 return false;
1388 }
1389 }
1390
1391 // Assembles a matrix of type floatRxC by resizing another matrix named `x0`.
1392 // Cells that don't exist in the source matrix will be populated with identity-matrix values.
1393 void MetalCodeGenerator::assembleMatrixFromMatrix(const Type& sourceMatrix, int columns, int rows) {
1394 SkASSERT(rows <= 4);
1395 SkASSERT(columns <= 4);
1396
1397 std::string matrixType = this->typeName(sourceMatrix.componentType());
1398
1399 const char* separator = "";
1400 for (int c = 0; c < columns; ++c) {
1401 fExtraFunctions.printf("%s%s%d(", separator, matrixType.c_str(), rows);
1402 separator = "), ";
1403
1404 // Determine how many values to take from the source matrix for this row.
1405 int swizzleLength = 0;
1406 if (c < sourceMatrix.columns()) {
1407 swizzleLength = std::min<>(rows, sourceMatrix.rows());
1408 }
1409
1410 // Emit all the values from the source matrix row.
1411 bool firstItem;
1412 switch (swizzleLength) {
1413 case 0: firstItem = true; break;
1414 case 1: firstItem = false; fExtraFunctions.printf("x0[%d].x", c); break;
1415 case 2: firstItem = false; fExtraFunctions.printf("x0[%d].xy", c); break;
1416 case 3: firstItem = false; fExtraFunctions.printf("x0[%d].xyz", c); break;
1417 case 4: firstItem = false; fExtraFunctions.printf("x0[%d].xyzw", c); break;
1418 default: SkUNREACHABLE;
1419 }
1420
1421 // Emit the placeholder identity-matrix cells.
1422 for (int r = swizzleLength; r < rows; ++r) {
1423 fExtraFunctions.printf("%s%s", firstItem ? "" : ", ", (r == c) ? "1.0" : "0.0");
1424 firstItem = false;
1425 }
1426 }
1427
1428 fExtraFunctions.writeText(")");
1429 }
1430
1431 // Assembles a matrix of type floatCxR by concatenating an arbitrary mix of values, named `x0`,
1432 // `x1`, etc. An error is written if the expression list don't contain exactly C*R scalars.
1433 void MetalCodeGenerator::assembleMatrixFromExpressions(const AnyConstructor& ctor,
1434 int columns,
1435 int rows) {
1436 SkASSERT(rows <= 4);
1437 SkASSERT(columns <= 4);
1438
1439 std::string matrixType = this->typeName(ctor.type().componentType());
1440 size_t argIndex = 0;
1441 int argPosition = 0;
1442 auto args = ctor.argumentSpan();
1443
1444 static constexpr char kSwizzle[] = "xyzw";
1445 const char* separator = "";
1446 for (int c = 0; c < columns; ++c) {
1447 fExtraFunctions.printf("%s%s%d(", separator, matrixType.c_str(), rows);
1448 separator = "), ";
1449
1450 const char* columnSeparator = "";
1451 for (int r = 0; r < rows;) {
1452 fExtraFunctions.writeText(columnSeparator);
1453 columnSeparator = ", ";
1454
1455 if (argIndex < args.size()) {
1456 const Type& argType = args[argIndex]->type();
1457 switch (argType.typeKind()) {
1458 case Type::TypeKind::kScalar: {
1459 fExtraFunctions.printf("x%zu", argIndex);
1460 ++r;
1461 ++argPosition;
1462 break;
1463 }
1464 case Type::TypeKind::kVector: {
1465 fExtraFunctions.printf("x%zu.", argIndex);
1466 do {
1467 fExtraFunctions.write8(kSwizzle[argPosition]);
1468 ++r;
1469 ++argPosition;
1470 } while (r < rows && argPosition < argType.columns());
1471 break;
1472 }
1473 case Type::TypeKind::kMatrix: {
1474 fExtraFunctions.printf("x%zu[%d].", argIndex, argPosition / argType.rows());
1475 do {
1476 fExtraFunctions.write8(kSwizzle[argPosition]);
1477 ++r;
1478 ++argPosition;
1479 } while (r < rows && (argPosition % argType.rows()) != 0);
1480 break;
1481 }
1482 default: {
1483 SkDEBUGFAIL("incorrect type of argument for matrix constructor");
1484 fExtraFunctions.writeText("<error>");
1485 break;
1486 }
1487 }
1488
1489 if (argPosition >= argType.columns() * argType.rows()) {
1490 ++argIndex;
1491 argPosition = 0;
1492 }
1493 } else {
1494 SkDEBUGFAIL("not enough arguments for matrix constructor");
1495 fExtraFunctions.writeText("<error>");
1496 }
1497 }
1498 }
1499
1500 if (argPosition != 0 || argIndex != args.size()) {
1501 SkDEBUGFAIL("incorrect number of arguments for matrix constructor");
1502 fExtraFunctions.writeText(", <error>");
1503 }
1504
1505 fExtraFunctions.writeText(")");
1506 }
1507
1508 // Generates a constructor for 'matrix' which reorganizes the input arguments into the proper shape.
1509 // Keeps track of previously generated constructors so that we won't generate more than one
1510 // constructor for any given permutation of input argument types. Returns the name of the
1511 // generated constructor method.
1512 std::string MetalCodeGenerator::getMatrixConstructHelper(const AnyConstructor& c) {
1513 const Type& type = c.type();
1514 int columns = type.columns();
1515 int rows = type.rows();
1516 auto args = c.argumentSpan();
1517 std::string typeName = this->typeName(type);
1518
1519 // Create the helper-method name and use it as our lookup key.
1520 std::string name = String::printf("%s_from", typeName.c_str());
1521 for (const std::unique_ptr<Expression>& expr : args) {
1522 String::appendf(&name, "_%s", this->typeName(expr->type()).c_str());
1523 }
1524
1525 // If a helper-method has not been synthesized yet, create it now.
1526 if (!fHelpers.contains(name)) {
1527 fHelpers.add(name);
1528
1529 // Unlike GLSL, Metal requires that matrices are initialized with exactly R vectors of C
1530 // components apiece. (In Metal 2.0, you can also supply R*C scalars, but you still cannot
1531 // supply a mixture of scalars and vectors.)
1532 fExtraFunctions.printf("%s %s(", typeName.c_str(), name.c_str());
1533
1534 size_t argIndex = 0;
1535 const char* argSeparator = "";
1536 for (const std::unique_ptr<Expression>& expr : args) {
1537 fExtraFunctions.printf("%s%s x%zu", argSeparator,
1538 this->typeName(expr->type()).c_str(), argIndex++);
1539 argSeparator = ", ";
1540 }
1541
1542 fExtraFunctions.printf(") {\n return %s(", typeName.c_str());
1543
1544 if (args.size() == 1 && args.front()->type().isMatrix()) {
1545 this->assembleMatrixFromMatrix(args.front()->type(), columns, rows);
1546 } else {
1547 this->assembleMatrixFromExpressions(c, columns, rows);
1548 }
1549
1550 fExtraFunctions.writeText(");\n}\n");
1551 }
1552 return name;
1553 }
1554
1555 bool MetalCodeGenerator::matrixConstructHelperIsNeeded(const ConstructorCompound& c) {
1556 SkASSERT(c.type().isMatrix());
1557
1558 // GLSL is fairly free-form about inputs to its matrix constructors, but Metal is not; it
1559 // expects exactly R vectors of C components apiece. (Metal 2.0 also allows a list of R*C
1560 // scalars.) Some cases are simple to translate and so we handle those inline--e.g. a list of
1561 // scalars can be constructed trivially. In more complex cases, we generate a helper function
1562 // that converts our inputs into a properly-shaped matrix.
1563 // A matrix construct helper method is always used if any input argument is a matrix.
1564 // Helper methods are also necessary when any argument would span multiple rows. For instance:
1565 //
1566 // float2 x = (1, 2);
1567 // float3x2(x, 3, 4, 5, 6) = | 1 3 5 | = no helper needed; conversion can be done inline
1568 // | 2 4 6 |
1569 //
1570 // float2 x = (2, 3);
1571 // float3x2(1, x, 4, 5, 6) = | 1 3 5 | = x spans multiple rows; a helper method will be used
1572 // | 2 4 6 |
1573 //
1574 // float4 x = (1, 2, 3, 4);
1575 // float2x2(x) = | 1 3 | = x spans multiple rows; a helper method will be used
1576 // | 2 4 |
1577 //
1578
1579 int position = 0;
1580 for (const std::unique_ptr<Expression>& expr : c.arguments()) {
1581 // If an input argument is a matrix, we need a helper function.
1582 if (expr->type().isMatrix()) {
1583 return true;
1584 }
1585 position += expr->type().columns();
1586 if (position > c.type().rows()) {
1587 // An input argument would span multiple rows; a helper function is required.
1588 return true;
1589 }
1590 if (position == c.type().rows()) {
1591 // We've advanced to the end of a row. Wrap to the start of the next row.
1592 position = 0;
1593 }
1594 }
1595
1596 return false;
1597 }
1598
1599 void MetalCodeGenerator::writeConstructorMatrixResize(const ConstructorMatrixResize& c,
1600 Precedence parentPrecedence) {
1601 // Matrix-resize via casting doesn't natively exist in Metal at all, so we always need to use a
1602 // matrix-construct helper here.
1603 this->write(this->getMatrixConstructHelper(c));
1604 this->write("(");
1605 this->writeExpression(*c.argument(), Precedence::kSequence);
1606 this->write(")");
1607 }
1608
1609 void MetalCodeGenerator::writeConstructorCompound(const ConstructorCompound& c,
1610 Precedence parentPrecedence) {
1611 if (c.type().isVector()) {
1612 this->writeConstructorCompoundVector(c, parentPrecedence);
1613 } else if (c.type().isMatrix()) {
1614 this->writeConstructorCompoundMatrix(c, parentPrecedence);
1615 } else {
1616 fContext.fErrors->error(c.fPosition, "unsupported compound constructor");
1617 }
1618 }
1619
1620 void MetalCodeGenerator::writeConstructorArrayCast(const ConstructorArrayCast& c,
1621 Precedence parentPrecedence) {
1622 const Type& inType = c.argument()->type().componentType();
1623 const Type& outType = c.type().componentType();
1624 std::string inTypeName = this->typeName(inType);
1625 std::string outTypeName = this->typeName(outType);
1626
1627 std::string name = "array_of_" + outTypeName + "_from_" + inTypeName;
1628 if (!fHelpers.contains(name)) {
1629 fHelpers.add(name);
1630 fExtraFunctions.printf(
1631 "template <size_t N>"
1632 "array<%s, N> %s(thread const array<%s, N>& x) {"
1633 "array<%s, N> result;"
1634 "for (int i = 0; i < N; ++i) {"
1635 "result[i] = %s(x[i]);"
1636 "}"
1637 "return result;"
1638 "}",
1639 outTypeName.c_str(), name.c_str(), inTypeName.c_str(),
1640 outTypeName.c_str(),
1641 outTypeName.c_str());
1642 }
1643
1644 this->write(name);
1645 this->write("(");
1646 this->writeExpression(*c.argument(), Precedence::kSequence);
1647 this->write(")");
1648 }
1649
1650 std::string MetalCodeGenerator::getVectorFromMat2x2ConstructorHelper(const Type& matrixType) {
1651 SkASSERT(matrixType.isMatrix());
1652 SkASSERT(matrixType.rows() == 2);
1653 SkASSERT(matrixType.columns() == 2);
1654
1655 std::string baseType = this->typeName(matrixType.componentType());
1656 std::string name = String::printf("%s4_from_%s2x2", baseType.c_str(), baseType.c_str());
1657 if (!fHelpers.contains(name)) {
1658 fHelpers.add(name);
1659
1660 fExtraFunctions.printf(
1661 "%s4 %s(%s2x2 x) {"
1662 "return %s4(x[0].xy, x[1].xy);"
1663 "}", baseType.c_str(), name.c_str(), baseType.c_str(), baseType.c_str());
1664 }
1665
1666 return name;
1667 }
1668
1669 void MetalCodeGenerator::writeConstructorCompoundVector(const ConstructorCompound& c,
1670 Precedence parentPrecedence) {
1671 SkASSERT(c.type().isVector());
1672
1673 // Metal supports constructing vectors from a mix of scalars and vectors, but not matrices.
1674 // GLSL supports vec4(mat2x2), so we detect that case here and emit a helper function.
1675 if (c.type().columns() == 4 && c.argumentSpan().size() == 1) {
1676 const Expression& expr = *c.argumentSpan().front();
1677 if (expr.type().isMatrix()) {
1678 this->write(this->getVectorFromMat2x2ConstructorHelper(expr.type()));
1679 this->write("(");
1680 this->writeExpression(expr, Precedence::kSequence);
1681 this->write(")");
1682 return;
1683 }
1684 }
1685
1686 this->writeAnyConstructor(c, "(", ")", parentPrecedence);
1687 }
1688
1689 void MetalCodeGenerator::writeConstructorCompoundMatrix(const ConstructorCompound& c,
1690 Precedence parentPrecedence) {
1691 SkASSERT(c.type().isMatrix());
1692
1693 // Emit and invoke a matrix-constructor helper method if one is necessary.
1694 if (this->matrixConstructHelperIsNeeded(c)) {
1695 this->write(this->getMatrixConstructHelper(c));
1696 this->write("(");
1697 const char* separator = "";
1698 for (const std::unique_ptr<Expression>& expr : c.arguments()) {
1699 this->write(separator);
1700 separator = ", ";
1701 this->writeExpression(*expr, Precedence::kSequence);
1702 }
1703 this->write(")");
1704 return;
1705 }
1706
1707 // Metal doesn't allow creating matrices by passing in scalars and vectors in a jumble; it
1708 // requires your scalars to be grouped up into columns. Because `matrixConstructHelperIsNeeded`
1709 // returned false, we know that none of our scalars/vectors "wrap" across across a column, so we
1710 // can group our inputs up and synthesize a constructor for each column.
1711 const Type& matrixType = c.type();
1712 const Type& columnType = matrixType.columnType(fContext);
1713
1714 this->writeType(matrixType);
1715 this->write("(");
1716 const char* separator = "";
1717 int scalarCount = 0;
1718 for (const std::unique_ptr<Expression>& arg : c.arguments()) {
1719 this->write(separator);
1720 separator = ", ";
1721 if (arg->type().columns() < matrixType.rows()) {
1722 // Write a `floatN(` constructor to group scalars and smaller vectors together.
1723 if (!scalarCount) {
1724 this->writeType(columnType);
1725 this->write("(");
1726 }
1727 scalarCount += arg->type().columns();
1728 }
1729 this->writeExpression(*arg, Precedence::kSequence);
1730 if (scalarCount && scalarCount == matrixType.rows()) {
1731 // Close our `floatN(...` constructor block from above.
1732 this->write(")");
1733 scalarCount = 0;
1734 }
1735 }
1736 this->write(")");
1737 }
1738
1739 void MetalCodeGenerator::writeAnyConstructor(const AnyConstructor& c,
1740 const char* leftBracket,
1741 const char* rightBracket,
1742 Precedence parentPrecedence) {
1743 this->writeType(c.type());
1744 this->write(leftBracket);
1745 const char* separator = "";
1746 for (const std::unique_ptr<Expression>& arg : c.argumentSpan()) {
1747 this->write(separator);
1748 separator = ", ";
1749 this->writeExpression(*arg, Precedence::kSequence);
1750 }
1751 this->write(rightBracket);
1752 }
1753
1754 void MetalCodeGenerator::writeCastConstructor(const AnyConstructor& c,
1755 const char* leftBracket,
1756 const char* rightBracket,
1757 Precedence parentPrecedence) {
1758 return this->writeAnyConstructor(c, leftBracket, rightBracket, parentPrecedence);
1759 }
1760
1761 void MetalCodeGenerator::writeFragCoord() {
1762 if (!fRTFlipName.empty()) {
1763 this->write("float4(_fragCoord.x, ");
1764 this->write(fRTFlipName.c_str());
1765 this->write(".x + ");
1766 this->write(fRTFlipName.c_str());
1767 this->write(".y * _fragCoord.y, 0.0, _fragCoord.w)");
1768 } else {
1769 this->write("float4(_fragCoord.x, _fragCoord.y, 0.0, _fragCoord.w)");
1770 }
1771 }
1772
1773 static bool is_compute_builtin(const Variable& var) {
1774 switch (var.layout().fBuiltin) {
1775 case SK_NUMWORKGROUPS_BUILTIN:
1776 case SK_WORKGROUPID_BUILTIN:
1777 case SK_LOCALINVOCATIONID_BUILTIN:
1778 case SK_GLOBALINVOCATIONID_BUILTIN:
1779 case SK_LOCALINVOCATIONINDEX_BUILTIN:
1780 return true;
1781 default:
1782 break;
1783 }
1784 return false;
1785 }
1786
1787 // true if the var is part of the Inputs struct
1788 static bool is_input(const Variable& var) {
1789 SkASSERT(var.storage() == VariableStorage::kGlobal);
1790 return var.modifierFlags() & ModifierFlag::kIn &&
1791 (var.layout().fBuiltin == -1 || is_compute_builtin(var)) &&
1792 var.type().typeKind() != Type::TypeKind::kTexture;
1793 }
1794
1795 // true if the var is part of the Outputs struct
1796 static bool is_output(const Variable& var) {
1797 SkASSERT(var.storage() == VariableStorage::kGlobal);
1798 // inout vars get written into the Inputs struct, so we exclude them from Outputs
1799 return (var.modifierFlags() & ModifierFlag::kOut) &&
1800 !(var.modifierFlags() & ModifierFlag::kIn) &&
1801 var.layout().fBuiltin == -1 &&
1802 var.type().typeKind() != Type::TypeKind::kTexture;
1803 }
1804
1805 // true if the var is part of the Uniforms struct
1806 static bool is_uniforms(const Variable& var) {
1807 SkASSERT(var.storage() == VariableStorage::kGlobal);
1808 return var.modifierFlags().isUniform() &&
1809 var.type().typeKind() != Type::TypeKind::kSampler;
1810 }
1811
1812 // true if the var is part of the Threadgroups struct
1813 static bool is_threadgroup(const Variable& var) {
1814 SkASSERT(var.storage() == VariableStorage::kGlobal);
1815 return var.modifierFlags().isWorkgroup();
1816 }
1817
1818 // true if the var is part of the Globals struct
1819 static bool is_in_globals(const Variable& var) {
1820 SkASSERT(var.storage() == VariableStorage::kGlobal);
1821 return !var.modifierFlags().isConst();
1822 }
1823
1824 void MetalCodeGenerator::writeVariableReference(const VariableReference& ref) {
1825 switch (ref.variable()->layout().fBuiltin) {
1826 case SK_FRAGCOLOR_BUILTIN:
1827 this->write("_out.sk_FragColor");
1828 break;
1829 case SK_SAMPLEMASK_BUILTIN:
1830 this->write("_out.sk_SampleMask");
1831 break;
1832 case SK_SECONDARYFRAGCOLOR_BUILTIN:
1833 if (fCaps.fDualSourceBlendingSupport) {
1834 this->write("_out.sk_SecondaryFragColor");
1835 } else {
1836 fContext.fErrors->error(ref.position(), "'sk_SecondaryFragColor' not supported");
1837 }
1838 break;
1839 case SK_FRAGCOORD_BUILTIN:
1840 this->writeFragCoord();
1841 break;
1842 case SK_SAMPLEMASKIN_BUILTIN:
1843 this->write("sk_SampleMaskIn");
1844 break;
1845 case SK_VERTEXID_BUILTIN:
1846 this->write("sk_VertexID");
1847 break;
1848 case SK_INSTANCEID_BUILTIN:
1849 this->write("sk_InstanceID");
1850 break;
1851 case SK_CLOCKWISE_BUILTIN:
1852 // We'd set the front facing winding in the MTLRenderCommandEncoder to be counter
1853 // clockwise to match Skia convention.
1854 if (!fRTFlipName.empty()) {
1855 this->write("(" + fRTFlipName + ".y < 0 ? _frontFacing : !_frontFacing)");
1856 } else {
1857 this->write("_frontFacing");
1858 }
1859 break;
1860 case SK_LASTFRAGCOLOR_BUILTIN:
1861 if (fCaps.fFBFetchColorName) {
1862 this->write(fCaps.fFBFetchColorName);
1863 } else {
1864 fContext.fErrors->error(ref.position(), "'sk_LastFragColor' not supported");
1865 }
1866 break;
1867 default:
1868 const Variable& var = *ref.variable();
1869 if (var.storage() == Variable::Storage::kGlobal) {
1870 if (is_input(var)) {
1871 this->write("_in.");
1872 } else if (is_output(var)) {
1873 this->write("_out.");
1874 } else if (is_uniforms(var)) {
1875 this->write("_uniforms.");
1876 } else if (is_threadgroup(var)) {
1877 this->write("_threadgroups.");
1878 } else if (is_in_globals(var)) {
1879 this->write("_globals.");
1880 }
1881 }
1882 this->writeName(var.mangledName());
1883 }
1884 }
1885
1886 void MetalCodeGenerator::writeIndexInnerExpression(const Expression& expr) {
1887 if (fIndexSubstitutionData) {
1888 // If this expression already exists in the index-substitution map, use the substitute.
1889 if (const std::string* existing = fIndexSubstitutionData->fMap.find(&expr)) {
1890 this->write(*existing);
1891 return;
1892 }
1893
1894 // If this expression is non-trivial, we will need to create a scratch variable and store
1895 // its value there.
1896 if (fIndexSubstitutionData->fCreateSubstitutes && !Analysis::IsTrivialExpression(expr)) {
1897 // Create a substitute variable and emit it into the main stream.
1898 std::string scratchVar = this->getTempVariable(expr.type());
1899 this->write(scratchVar);
1900
1901 // Initialize the substitute variable in the prefix-stream.
1902 AutoOutputStream outputToPrefixStream(this, &fIndexSubstitutionData->fPrefixStream);
1903 this->write(scratchVar);
1904 this->write(" = ");
1905 this->writeExpression(expr, Precedence::kAssignment);
1906 this->write(", ");
1907
1908 // Remember the substitute variable in our map.
1909 fIndexSubstitutionData->fMap.set(&expr, std::move(scratchVar));
1910 return;
1911 }
1912 }
1913
1914 // We don't require index-substitution; just emit the expression normally.
1915 this->writeExpression(expr, Precedence::kExpression);
1916 }
1917
1918 void MetalCodeGenerator::writeIndexExpression(const IndexExpression& expr) {
1919 // Metal does not seem to handle assignment into `vec.zyx[i]` properly--it compiles, but the
1920 // results are wrong. We rewrite the expression as `vec[uint3(2,1,0)[i]]` instead. (Filed with
1921 // Apple as FB12055941.)
1922 if (expr.base()->is<Swizzle>() && expr.base()->as<Swizzle>().components().size() > 1) {
1923 const Swizzle& swizzle = expr.base()->as<Swizzle>();
1924 this->writeExpression(*swizzle.base(), Precedence::kPostfix);
1925 this->write("[uint" + std::to_string(swizzle.components().size()) + "(");
1926 auto separator = SkSL::String::Separator();
1927 for (int8_t component : swizzle.components()) {
1928 this->write(separator());
1929 this->write(std::to_string(component));
1930 }
1931 this->write(")[");
1932 this->writeIndexInnerExpression(*expr.index());
1933 this->write("]]");
1934 } else {
1935 this->writeExpression(*expr.base(), Precedence::kPostfix);
1936 this->write("[");
1937 this->writeIndexInnerExpression(*expr.index());
1938 this->write("]");
1939 }
1940 }
1941
1942 void MetalCodeGenerator::writeFieldAccess(const FieldAccess& f) {
1943 const Field* field = &f.base()->type().fields()[f.fieldIndex()];
1944 if (FieldAccess::OwnerKind::kDefault == f.ownerKind()) {
1945 this->writeExpression(*f.base(), Precedence::kPostfix);
1946 this->write(".");
1947 }
1948 switch (field->fLayout.fBuiltin) {
1949 case SK_POSITION_BUILTIN:
1950 this->write("_out.sk_Position");
1951 break;
1952 case SK_POINTSIZE_BUILTIN:
1953 this->write("_out.sk_PointSize");
1954 break;
1955 default:
1956 if (FieldAccess::OwnerKind::kAnonymousInterfaceBlock == f.ownerKind()) {
1957 this->write("_globals.");
1958 this->write(fInterfaceBlockNameMap[&f.base()->type()]);
1959 this->write("->");
1960 }
1961 this->writeName(field->fName);
1962 }
1963 }
1964
1965 void MetalCodeGenerator::writeSwizzle(const Swizzle& swizzle) {
1966 this->writeExpression(*swizzle.base(), Precedence::kPostfix);
1967 this->write(".");
1968 this->write(Swizzle::MaskString(swizzle.components()));
1969 }
1970
1971 void MetalCodeGenerator::writeMatrixTimesEqualHelper(const Type& left, const Type& right,
1972 const Type& result) {
1973 SkASSERT(left.isMatrix());
1974 SkASSERT(right.isMatrix());
1975 SkASSERT(result.isMatrix());
1976
1977 std::string key = "Matrix *= " + this->typeName(left) + ":" + this->typeName(right);
1978
1979 if (!fHelpers.contains(key)) {
1980 fHelpers.add(key);
1981 fExtraFunctions.printf("thread %s& operator*=(thread %s& left, thread const %s& right) {\n"
1982 " left = left * right;\n"
1983 " return left;\n"
1984 "}\n",
1985 this->typeName(result).c_str(), this->typeName(left).c_str(),
1986 this->typeName(right).c_str());
1987 }
1988 }
1989
1990 void MetalCodeGenerator::writeMatrixEqualityHelpers(const Type& left, const Type& right) {
1991 SkASSERT(left.isMatrix());
1992 SkASSERT(right.isMatrix());
1993 SkASSERT(left.rows() == right.rows());
1994 SkASSERT(left.columns() == right.columns());
1995
1996 std::string key = "Matrix == " + this->typeName(left) + ":" + this->typeName(right);
1997
1998 if (!fHelpers.contains(key)) {
1999 fHelpers.add(key);
2000 fExtraFunctionPrototypes.printf(
2001 "thread bool operator==(const %s left, const %s right);"
2002 "thread bool operator!=(const %s left, const %s right);",
2003 this->typeName(left).c_str(),
2004 this->typeName(right).c_str(),
2005 this->typeName(left).c_str(),
2006 this->typeName(right).c_str());
2007
2008 fExtraFunctions.printf(
2009 "thread bool operator==(const %s left, const %s right) {"
2010 "return ",
2011 this->typeName(left).c_str(), this->typeName(right).c_str());
2012
2013 const char* separator = "";
2014 for (int index=0; index<left.columns(); ++index) {
2015 fExtraFunctions.printf("%sall(left[%d] == right[%d])", separator, index, index);
2016 separator = " && ";
2017 }
2018
2019 fExtraFunctions.printf(
2020 ";"
2021 "}"
2022 "thread bool operator!=(const %s left, const %s right) {"
2023 "return !(left == right);"
2024 "}",
2025 this->typeName(left).c_str(), this->typeName(right).c_str());
2026 }
2027 }
2028
2029 void MetalCodeGenerator::writeMatrixDivisionHelpers(const Type& type) {
2030 SkASSERT(type.isMatrix());
2031
2032 std::string key = "Matrix / " + this->typeName(type);
2033
2034 if (!fHelpers.contains(key)) {
2035 fHelpers.add(key);
2036 std::string typeName = this->typeName(type);
2037
2038 fExtraFunctions.printf(
2039 "thread %s operator/(const %s left, const %s right) {\n"
2040 " return %s(",
2041 typeName.c_str(), typeName.c_str(), typeName.c_str(), typeName.c_str());
2042
2043 const char* separator = "";
2044 for (int index=0; index<type.columns(); ++index) {
2045 fExtraFunctions.printf("%sleft[%d] / right[%d]", separator, index, index);
2046 separator = ", ";
2047 }
2048
2049 fExtraFunctions.printf(");\n"
2050 "}\n"
2051 "thread %s& operator/=(thread %s& left, thread const %s& right) {\n"
2052 " left = left / right;\n"
2053 " return left;\n"
2054 "}\n",
2055 typeName.c_str(), typeName.c_str(), typeName.c_str());
2056 }
2057 }
2058
2059 void MetalCodeGenerator::writeArrayEqualityHelpers(const Type& type) {
2060 SkASSERT(type.isArray());
2061
2062 // If the array's component type needs a helper as well, we need to emit that one first.
2063 this->writeEqualityHelpers(type.componentType(), type.componentType());
2064
2065 std::string key = "ArrayEquality []";
2066 if (!fHelpers.contains(key)) {
2067 fHelpers.add(key);
2068 fExtraFunctionPrototypes.writeText(
2069 "template <typename T1, typename T2>"
2070 "bool operator==(const array_ref<T1> left, const array_ref<T2> right);"
2071 "template <typename T1, typename T2>"
2072 "bool operator!=(const array_ref<T1> left, const array_ref<T2> right);");
2073 fExtraFunctions.writeText(
2074 "template <typename T1, typename T2>"
2075 "bool operator==(const array_ref<T1> left, const array_ref<T2> right) {"
2076 "if (left.size() != right.size()) {"
2077 "return false;"
2078 "}"
2079 "for (size_t index = 0; index < left.size(); ++index) {"
2080 "if (!all(left[index] == right[index])) {"
2081 "return false;"
2082 "}"
2083 "}"
2084 "return true;"
2085 "}"
2086
2087 "template <typename T1, typename T2>"
2088 "bool operator!=(const array_ref<T1> left, const array_ref<T2> right) {"
2089 "return !(left == right);"
2090 "}");
2091 }
2092 }
2093
2094 void MetalCodeGenerator::writeStructEqualityHelpers(const Type& type) {
2095 SkASSERT(type.isStruct());
2096 std::string key = "StructEquality " + this->typeName(type);
2097
2098 if (!fHelpers.contains(key)) {
2099 fHelpers.add(key);
2100 // If one of the struct's fields needs a helper as well, we need to emit that one first.
2101 for (const Field& field : type.fields()) {
2102 this->writeEqualityHelpers(*field.fType, *field.fType);
2103 }
2104
2105 // Write operator== and operator!= for this struct, since those are assumed to exist in SkSL
2106 // and GLSL but do not exist by default in Metal.
2107 fExtraFunctionPrototypes.printf(
2108 "thread bool operator==(thread const %s& left, thread const %s& right);"
2109 "thread bool operator!=(thread const %s& left, thread const %s& right);",
2110 this->typeName(type).c_str(),
2111 this->typeName(type).c_str(),
2112 this->typeName(type).c_str(),
2113 this->typeName(type).c_str());
2114
2115 fExtraFunctions.printf(
2116 "thread bool operator==(thread const %s& left, thread const %s& right) {"
2117 "return ",
2118 this->typeName(type).c_str(),
2119 this->typeName(type).c_str());
2120
2121 const char* separator = "";
2122 for (const Field& field : type.fields()) {
2123 if (field.fType->isArray()) {
2124 fExtraFunctions.printf(
2125 "%s(make_array_ref(left.%.*s) == make_array_ref(right.%.*s))",
2126 separator,
2127 (int)field.fName.size(), field.fName.data(),
2128 (int)field.fName.size(), field.fName.data());
2129 } else {
2130 fExtraFunctions.printf("%sall(left.%.*s == right.%.*s)",
2131 separator,
2132 (int)field.fName.size(), field.fName.data(),
2133 (int)field.fName.size(), field.fName.data());
2134 }
2135 separator = " && ";
2136 }
2137 fExtraFunctions.printf(
2138 ";"
2139 "}"
2140 "thread bool operator!=(thread const %s& left, thread const %s& right) {"
2141 "return !(left == right);"
2142 "}",
2143 this->typeName(type).c_str(),
2144 this->typeName(type).c_str());
2145 }
2146 }
2147
2148 void MetalCodeGenerator::writeEqualityHelpers(const Type& leftType, const Type& rightType) {
2149 if (leftType.isArray() && rightType.isArray()) {
2150 this->writeArrayEqualityHelpers(leftType);
2151 return;
2152 }
2153 if (leftType.isStruct() && rightType.isStruct()) {
2154 this->writeStructEqualityHelpers(leftType);
2155 return;
2156 }
2157 if (leftType.isMatrix() && rightType.isMatrix()) {
2158 this->writeMatrixEqualityHelpers(leftType, rightType);
2159 return;
2160 }
2161 }
2162
2163 std::string MetalCodeGenerator::splatMatrixOf1(const Type& type) {
2164 std::string str = this->typeName(type) + '(';
2165
2166 auto separator = SkSL::String::Separator();
2167 for (int index = type.slotCount(); index--;) {
2168 str += separator();
2169 str += "1.0";
2170 }
2171
2172 return str + ')';
2173 }
2174
2175 void MetalCodeGenerator::writeNumberAsMatrix(const Expression& expr, const Type& matrixType) {
2176 SkASSERT(expr.type().isNumber());
2177 SkASSERT(matrixType.isMatrix());
2178
2179 // Componentwise multiply the scalar against a matrix of the desired size which contains all 1s.
2180 this->write("(");
2181 this->write(this->splatMatrixOf1(matrixType));
2182 this->write(" * ");
2183 this->writeExpression(expr, Precedence::kMultiplicative);
2184 this->write(")");
2185 }
2186
2187 void MetalCodeGenerator::writeBinaryExpressionElement(const Expression& expr,
2188 Operator op,
2189 const Expression& other,
2190 Precedence precedence) {
2191 bool needMatrixSplatOnScalar = other.type().isMatrix() && expr.type().isNumber() &&
2192 op.isValidForMatrixOrVector() &&
2193 op.removeAssignment().kind() != Operator::Kind::STAR;
2194 if (needMatrixSplatOnScalar) {
2195 this->writeNumberAsMatrix(expr, other.type());
2196 } else if (op.isEquality() && expr.type().isArray()) {
2197 this->write("make_array_ref(");
2198 this->writeExpression(expr, precedence);
2199 this->write(")");
2200 } else {
2201 this->writeExpression(expr, precedence);
2202 }
2203 }
2204
2205 void MetalCodeGenerator::writeBinaryExpression(const BinaryExpression& b,
2206 Precedence parentPrecedence) {
2207 const Expression& left = *b.left();
2208 const Expression& right = *b.right();
2209 const Type& leftType = left.type();
2210 const Type& rightType = right.type();
2211 Operator op = b.getOperator();
2212 Precedence precedence = op.getBinaryPrecedence();
2213 bool needParens = precedence >= parentPrecedence;
2214 switch (op.kind()) {
2215 case Operator::Kind::EQEQ:
2216 this->writeEqualityHelpers(leftType, rightType);
2217 if (leftType.isVector()) {
2218 this->write("all");
2219 needParens = true;
2220 }
2221 break;
2222 case Operator::Kind::NEQ:
2223 this->writeEqualityHelpers(leftType, rightType);
2224 if (leftType.isVector()) {
2225 this->write("any");
2226 needParens = true;
2227 }
2228 break;
2229 default:
2230 break;
2231 }
2232 if (leftType.isMatrix() && rightType.isMatrix() && op.kind() == Operator::Kind::STAREQ) {
2233 this->writeMatrixTimesEqualHelper(leftType, rightType, b.type());
2234 }
2235 if (op.removeAssignment().kind() == Operator::Kind::SLASH &&
2236 ((leftType.isMatrix() && rightType.isMatrix()) ||
2237 (leftType.isScalar() && rightType.isMatrix()) ||
2238 (leftType.isMatrix() && rightType.isScalar()))) {
2239 this->writeMatrixDivisionHelpers(leftType.isMatrix() ? leftType : rightType);
2240 }
2241
2242 if (needParens) {
2243 this->write("(");
2244 }
2245
2246 // Some expressions need to be rewritten from `lhs *= rhs` to `lhs = lhs * rhs`, e.g.:
2247 // float4 x = float4(1);
2248 // x.xy *= float2x2(...);
2249 // will report the error "non-const reference cannot bind to vector element."
2250 if (op.isCompoundAssignment() && left.kind() == Expression::Kind::kSwizzle) {
2251 // We need to do the rewrite. This could be dangerous if the lhs contains an index
2252 // expression with a side effect (such as `array[Func()]`), so we enable index-substitution
2253 // here for the LHS; any index-expression with side effects will be evaluated into a scratch
2254 // variable.
2255 this->writeWithIndexSubstitution([&] {
2256 this->writeExpression(left, precedence);
2257 this->write(" = ");
2258 this->writeExpression(left, Precedence::kAssignment);
2259 this->write(operator_name(op.removeAssignment()));
2260
2261 // We never want to create index-expression substitutes on the RHS of the expression;
2262 // the RHS is only emitted one time.
2263 fIndexSubstitutionData->fCreateSubstitutes = false;
2264
2265 this->writeBinaryExpressionElement(right, op, left,
2266 op.removeAssignment().getBinaryPrecedence());
2267 });
2268 } else {
2269 // We don't need any rewrite; emit the binary expression as-is.
2270 this->writeBinaryExpressionElement(left, op, right, precedence);
2271 this->write(operator_name(op));
2272 this->writeBinaryExpressionElement(right, op, left, precedence);
2273 }
2274
2275 if (needParens) {
2276 this->write(")");
2277 }
2278 }
2279
2280 void MetalCodeGenerator::writeTernaryExpression(const TernaryExpression& t,
2281 Precedence parentPrecedence) {
2282 if (Precedence::kTernary >= parentPrecedence) {
2283 this->write("(");
2284 }
2285 this->writeExpression(*t.test(), Precedence::kTernary);
2286 this->write(" ? ");
2287 this->writeExpression(*t.ifTrue(), Precedence::kTernary);
2288 this->write(" : ");
2289 this->writeExpression(*t.ifFalse(), Precedence::kTernary);
2290 if (Precedence::kTernary >= parentPrecedence) {
2291 this->write(")");
2292 }
2293 }
2294
2295 void MetalCodeGenerator::writePrefixExpression(const PrefixExpression& p,
2296 Precedence parentPrecedence) {
2297 const Operator op = p.getOperator();
2298 switch (op.kind()) {
2299 case Operator::Kind::PLUS:
2300 // According to the MSL specification, the arithmetic unary operators (+ and –) do not
2301 // act upon matrix-typed operands. We treat the unary "+" as a no-op for all operands.
2302 this->writeExpression(*p.operand(), Precedence::kPrefix);
2303 return;
2304
2305 case Operator::Kind::MINUS:
2306 // Transform the unary `-` on a matrix type to a multiplication by -1.
2307 if (p.operand()->type().isMatrix()) {
2308 this->write(p.type().componentType().highPrecision() ? "(-1.0 * "
2309 : "(-1.0h * ");
2310 this->writeExpression(*p.operand(), Precedence::kMultiplicative);
2311 this->write(")");
2312 return;
2313 }
2314 break;
2315
2316 case Operator::Kind::PLUSPLUS:
2317 case Operator::Kind::MINUSMINUS:
2318 if (p.operand()->type().isMatrix()) {
2319 // Transform `++x` or `--x` on a matrix type to `mat += T(1.0, ...)` or
2320 // `mat -= T(1.0, ...)`.
2321 this->write("(");
2322 this->writeExpression(*p.operand(), Precedence::kAssignment);
2323 this->write(op.kind() == Operator::Kind::PLUSPLUS ? " += " : " -= ");
2324 this->write(this->splatMatrixOf1(p.operand()->type()));
2325 this->write(")");
2326 return;
2327 }
2328 break;
2329
2330 default:
2331 break;
2332 }
2333
2334 if (Precedence::kPrefix >= parentPrecedence) {
2335 this->write("(");
2336 }
2337
2338 this->write(op.tightOperatorName());
2339 this->writeExpression(*p.operand(), Precedence::kPrefix);
2340
2341 if (Precedence::kPrefix >= parentPrecedence) {
2342 this->write(")");
2343 }
2344 }
2345
2346 void MetalCodeGenerator::writePostfixExpression(const PostfixExpression& p,
2347 Precedence parentPrecedence) {
2348 const Operator op = p.getOperator();
2349 switch (op.kind()) {
2350 case Operator::Kind::PLUSPLUS:
2351 case Operator::Kind::MINUSMINUS:
2352 if (p.operand()->type().isMatrix()) {
2353 // We need to transform `x++` or `x--` into `+=` and `-=` on a matrix.
2354 // Unfortunately, that requires making a temporary copy of the old value and
2355 // emitting a sequence expression: `((temp = mat), (mat += T(1.0, ...)), temp)`.
2356 std::string tempMatrix = this->getTempVariable(p.operand()->type());
2357 this->write("((");
2358 this->write(tempMatrix);
2359 this->write(" = ");
2360 this->writeExpression(*p.operand(), Precedence::kAssignment);
2361 this->write("), (");
2362 this->writeExpression(*p.operand(), Precedence::kAssignment);
2363 this->write(op.kind() == Operator::Kind::PLUSPLUS ? " += " : " -= ");
2364 this->write(this->splatMatrixOf1(p.operand()->type()));
2365 this->write("), ");
2366 this->write(tempMatrix);
2367 this->write(")");
2368 return;
2369 }
2370 break;
2371
2372 default:
2373 break;
2374 }
2375
2376 if (Precedence::kPostfix >= parentPrecedence) {
2377 this->write("(");
2378 }
2379 this->writeExpression(*p.operand(), Precedence::kPostfix);
2380 this->write(op.tightOperatorName());
2381 if (Precedence::kPostfix >= parentPrecedence) {
2382 this->write(")");
2383 }
2384 }
2385
2386 void MetalCodeGenerator::writeLiteral(const Literal& l) {
2387 const Type& type = l.type();
2388 if (type.isFloat()) {
2389 this->write(l.description(OperatorPrecedence::kExpression));
2390 if (!l.type().highPrecision()) {
2391 this->write("h");
2392 }
2393 return;
2394 }
2395 if (type.isInteger()) {
2396 if (type.matches(*fContext.fTypes.fUInt)) {
2397 this->write(std::to_string(l.intValue() & 0xffffffff));
2398 this->write("u");
2399 } else if (type.matches(*fContext.fTypes.fUShort)) {
2400 this->write(std::to_string(l.intValue() & 0xffff));
2401 this->write("u");
2402 } else {
2403 this->write(std::to_string(l.intValue()));
2404 }
2405 return;
2406 }
2407 SkASSERT(type.isBoolean());
2408 this->write(l.description(OperatorPrecedence::kExpression));
2409 }
2410
2411 void MetalCodeGenerator::writeFunctionRequirementArgs(const FunctionDeclaration& f,
2412 const char*& separator) {
2413 Requirements requirements = this->requirements(f);
2414 if (requirements & kInputs_Requirement) {
2415 this->write(separator);
2416 this->write("_in");
2417 separator = ", ";
2418 }
2419 if (requirements & kOutputs_Requirement) {
2420 this->write(separator);
2421 this->write("_out");
2422 separator = ", ";
2423 }
2424 if (requirements & kUniforms_Requirement) {
2425 this->write(separator);
2426 this->write("_uniforms");
2427 separator = ", ";
2428 }
2429 if (requirements & kGlobals_Requirement) {
2430 this->write(separator);
2431 this->write("_globals");
2432 separator = ", ";
2433 }
2434 if (requirements & kFragCoord_Requirement) {
2435 this->write(separator);
2436 this->write("_fragCoord");
2437 separator = ", ";
2438 }
2439 if (requirements & kSampleMaskIn_Requirement) {
2440 this->write(separator);
2441 this->write("sk_SampleMaskIn");
2442 separator = ", ";
2443 }
2444 if (requirements & kVertexID_Requirement) {
2445 this->write(separator);
2446 this->write("sk_VertexID");
2447 separator = ", ";
2448 }
2449 if (requirements & kInstanceID_Requirement) {
2450 this->write(separator);
2451 this->write("sk_InstanceID");
2452 separator = ", ";
2453 }
2454 if (requirements & kThreadgroups_Requirement) {
2455 this->write(separator);
2456 this->write("_threadgroups");
2457 separator = ", ";
2458 }
2459 }
2460
2461 void MetalCodeGenerator::writeFunctionRequirementParams(const FunctionDeclaration& f,
2462 const char*& separator) {
2463 Requirements requirements = this->requirements(f);
2464 if (requirements & kInputs_Requirement) {
2465 this->write(separator);
2466 this->write("Inputs _in");
2467 separator = ", ";
2468 }
2469 if (requirements & kOutputs_Requirement) {
2470 this->write(separator);
2471 this->write("thread Outputs& _out");
2472 separator = ", ";
2473 }
2474 if (requirements & kUniforms_Requirement) {
2475 this->write(separator);
2476 this->write("Uniforms _uniforms");
2477 separator = ", ";
2478 }
2479 if (requirements & kGlobals_Requirement) {
2480 this->write(separator);
2481 this->write("thread Globals& _globals");
2482 separator = ", ";
2483 }
2484 if (requirements & kFragCoord_Requirement) {
2485 this->write(separator);
2486 this->write("float4 _fragCoord");
2487 separator = ", ";
2488 }
2489 if (requirements & kSampleMaskIn_Requirement) {
2490 this->write(separator);
2491 this->write("uint sk_SampleMaskIn");
2492 separator = ", ";
2493 }
2494 if (requirements & kVertexID_Requirement) {
2495 this->write(separator);
2496 this->write("uint sk_VertexID");
2497 separator = ", ";
2498 }
2499 if (requirements & kInstanceID_Requirement) {
2500 this->write(separator);
2501 this->write("uint sk_InstanceID");
2502 separator = ", ";
2503 }
2504 if (requirements & kThreadgroups_Requirement) {
2505 this->write(separator);
2506 this->write("threadgroup Threadgroups& _threadgroups");
2507 separator = ", ";
2508 }
2509 }
2510
2511 int MetalCodeGenerator::getUniformBinding(const Layout& layout) {
2512 return (layout.fBinding >= 0) ? layout.fBinding
2513 : fProgram.fConfig->fSettings.fDefaultUniformBinding;
2514 }
2515
2516 int MetalCodeGenerator::getUniformSet(const Layout& layout) {
2517 return (layout.fSet >= 0) ? layout.fSet
2518 : fProgram.fConfig->fSettings.fDefaultUniformSet;
2519 }
2520
2521 bool MetalCodeGenerator::writeFunctionDeclaration(const FunctionDeclaration& f) {
2522 fRTFlipName = (fProgram.fInterface.fRTFlipUniform != Program::Interface::kRTFlip_None)
2523 ? "_globals._anonInterface0->" SKSL_RTFLIP_NAME
2524 : "";
2525 const char* separator = "";
2526 if (f.isMain()) {
2527 if (ProgramConfig::IsFragment(fProgram.fConfig->fKind)) {
2528 this->write("fragment Outputs fragmentMain(");
2529 } else if (ProgramConfig::IsVertex(fProgram.fConfig->fKind)) {
2530 this->write("vertex Outputs vertexMain(");
2531 } else if (ProgramConfig::IsCompute(fProgram.fConfig->fKind)) {
2532 this->write("kernel void computeMain(");
2533 } else {
2534 fContext.fErrors->error(Position(), "unsupported kind of program");
2535 return false;
2536 }
2537 if (!ProgramConfig::IsCompute(fProgram.fConfig->fKind)) {
2538 this->write("Inputs _in [[stage_in]]");
2539 separator = ", ";
2540 }
2541 if (-1 != fUniformBuffer) {
2542 this->write(separator);
2543 this->write("constant Uniforms& _uniforms [[buffer(" +
2544 std::to_string(fUniformBuffer) + ")]]");
2545 separator = ", ";
2546 }
2547 for (const ProgramElement* e : fProgram.elements()) {
2548 if (e->is<GlobalVarDeclaration>()) {
2549 const GlobalVarDeclaration& decls = e->as<GlobalVarDeclaration>();
2550 const VarDeclaration& decl = decls.varDeclaration();
2551 const Variable* var = decl.var();
2552 const SkSL::Type::TypeKind varKind = var->type().typeKind();
2553
2554 if (varKind == Type::TypeKind::kSampler || varKind == Type::TypeKind::kTexture) {
2555 if (var->type().dimensions() != SpvDim2D) {
2556 // Not yet implemented--Skia currently only uses 2D textures.
2557 fContext.fErrors->error(decls.fPosition, "Unsupported texture dimensions");
2558 return false;
2559 }
2560
2561 int binding = getUniformBinding(var->layout());
2562 this->write(separator);
2563 separator = ", ";
2564
2565 if (varKind == Type::TypeKind::kSampler) {
2566 this->writeType(var->type().textureType());
2567 this->write(" ");
2568 this->writeName(var->mangledName());
2569 this->write(kTextureSuffix);
2570 this->write(" [[texture(");
2571 this->write(std::to_string(binding));
2572 this->write(")]], sampler ");
2573 this->writeName(var->mangledName());
2574 this->write(kSamplerSuffix);
2575 this->write(" [[sampler(");
2576 this->write(std::to_string(binding));
2577 this->write(")]]");
2578 } else {
2579 SkASSERT(varKind == Type::TypeKind::kTexture);
2580 this->writeType(var->type());
2581 this->write(" ");
2582 this->writeName(var->mangledName());
2583 this->write(" [[texture(");
2584 this->write(std::to_string(binding));
2585 this->write(")]]");
2586 }
2587 } else if (ProgramConfig::IsCompute(fProgram.fConfig->fKind)) {
2588 std::string_view attr;
2589 switch (var->layout().fBuiltin) {
2590 case SK_NUMWORKGROUPS_BUILTIN:
2591 attr = " [[threadgroups_per_grid]]";
2592 break;
2593 case SK_WORKGROUPID_BUILTIN:
2594 attr = " [[threadgroup_position_in_grid]]";
2595 break;
2596 case SK_LOCALINVOCATIONID_BUILTIN:
2597 attr = " [[thread_position_in_threadgroup]]";
2598 break;
2599 case SK_GLOBALINVOCATIONID_BUILTIN:
2600 attr = " [[thread_position_in_grid]]";
2601 break;
2602 case SK_LOCALINVOCATIONINDEX_BUILTIN:
2603 attr = " [[thread_index_in_threadgroup]]";
2604 break;
2605 default:
2606 break;
2607 }
2608 if (!attr.empty()) {
2609 this->write(separator);
2610 this->writeType(var->type());
2611 this->write(" ");
2612 this->write(var->name());
2613 this->write(attr);
2614 separator = ", ";
2615 }
2616 }
2617 } else if (e->is<InterfaceBlock>()) {
2618 const InterfaceBlock& intf = e->as<InterfaceBlock>();
2619 if (intf.typeName() == "sk_PerVertex") {
2620 continue;
2621 }
2622 this->write(separator);
2623 if (is_readonly(intf)) {
2624 this->write("const ");
2625 }
2626 this->write(is_buffer(intf) ? "device " : "constant ");
2627 this->writeType(intf.var()->type());
2628 this->write("& " );
2629 this->write(fInterfaceBlockNameMap[&intf.var()->type()]);
2630 this->write(" [[buffer(");
2631 this->write(std::to_string(this->getUniformBinding(intf.var()->layout())));
2632 this->write(")]]");
2633 separator = ", ";
2634 }
2635 }
2636 if (ProgramConfig::IsFragment(fProgram.fConfig->fKind)) {
2637 if (fProgram.fInterface.fRTFlipUniform != Program::Interface::kRTFlip_None &&
2638 fInterfaceBlockNameMap.empty()) {
2639 this->write(separator);
2640 this->write("constant sksl_synthetic_uniforms& _anonInterface0 [[buffer(1)]]");
2641 fRTFlipName = "_anonInterface0." SKSL_RTFLIP_NAME;
2642 separator = ", ";
2643 }
2644 this->write(separator);
2645 this->write("bool _frontFacing [[front_facing]], float4 _fragCoord [[position]]");
2646 if (this->requirements(f) & kSampleMaskIn_Requirement) {
2647 this->write(", uint sk_SampleMaskIn [[sample_mask]]");
2648 }
2649 if (fProgram.fInterface.fUseLastFragColor && fCaps.fFBFetchColorName) {
2650 this->write(", half4 " + std::string(fCaps.fFBFetchColorName) +
2651 " [[color(0)]]\n");
2652 }
2653 separator = ", ";
2654 } else if (ProgramConfig::IsVertex(fProgram.fConfig->fKind)) {
2655 this->write(separator);
2656 this->write("uint sk_VertexID [[vertex_id]], uint sk_InstanceID [[instance_id]]");
2657 separator = ", ";
2658 }
2659 } else {
2660 this->writeType(f.returnType());
2661 this->write(" ");
2662 this->writeName(f.mangledName());
2663 this->write("(");
2664 this->writeFunctionRequirementParams(f, separator);
2665 }
2666 for (const Variable* param : f.parameters()) {
2667 // This is a workaround for our test files. They use the runtime effect signature, so main
2668 // takes a coords parameter. We detect these at IR generation time, and we omit them from
2669 // the declaration here, so the function is valid Metal. (Well, valid as long as the
2670 // coordinates aren't actually referenced.)
2671 if (f.isMain() && param == f.getMainCoordsParameter()) {
2672 continue;
2673 }
2674 this->write(separator);
2675 separator = ", ";
2676 this->writeModifiers(param->modifierFlags());
2677 this->writeType(param->type());
2678 if (pass_by_reference(param->type(), param->modifierFlags())) {
2679 this->write("&");
2680 }
2681 this->write(" ");
2682 this->writeName(param->mangledName());
2683 }
2684 this->write(")");
2685 return true;
2686 }
2687
2688 void MetalCodeGenerator::writeFunctionPrototype(const FunctionPrototype& f) {
2689 this->writeFunctionDeclaration(f.declaration());
2690 this->writeLine(";");
2691 }
2692
2693 static bool is_block_ending_with_return(const Statement* stmt) {
2694 // This function detects (potentially nested) blocks that end in a return statement.
2695 if (!stmt->is<Block>()) {
2696 return false;
2697 }
2698 const StatementArray& block = stmt->as<Block>().children();
2699 for (int index = block.size(); index--; ) {
2700 stmt = block[index].get();
2701 if (stmt->is<ReturnStatement>()) {
2702 return true;
2703 }
2704 if (stmt->is<Block>()) {
2705 return is_block_ending_with_return(stmt);
2706 }
2707 if (!stmt->is<Nop>()) {
2708 break;
2709 }
2710 }
2711 return false;
2712 }
2713
2714 void MetalCodeGenerator::writeComputeMainInputs() {
2715 // Compute shaders only have input variables (e.g. sk_GlobalInvocationID) and access program
2716 // inputs/outputs via the Globals and Uniforms structs. We collect the allowed "in" parameters
2717 // into an Input struct here, since the rest of the code expects the normal _in / _out pattern.
2718 this->write("Inputs _in = { ");
2719 const char* separator = "";
2720 for (const ProgramElement* e : fProgram.elements()) {
2721 if (e->is<GlobalVarDeclaration>()) {
2722 const GlobalVarDeclaration& decls = e->as<GlobalVarDeclaration>();
2723 const Variable* var = decls.varDeclaration().var();
2724 if (is_input(*var)) {
2725 this->write(separator);
2726 separator = ", ";
2727 this->writeName(var->mangledName());
2728 }
2729 }
2730 }
2731 this->writeLine(" };");
2732 }
2733
2734 void MetalCodeGenerator::writeFunction(const FunctionDefinition& f) {
2735 SkASSERT(!fProgram.fConfig->fSettings.fFragColorIsInOut);
2736
2737 if (!this->writeFunctionDeclaration(f.declaration())) {
2738 return;
2739 }
2740
2741 fCurrentFunction = &f.declaration();
2742 SkScopeExit clearCurrentFunction([&] { fCurrentFunction = nullptr; });
2743
2744 this->writeLine(" {");
2745
2746 if (f.declaration().isMain()) {
2747 fIndentation++;
2748 this->writeGlobalInit();
2749 if (ProgramConfig::IsCompute(fProgram.fConfig->fKind)) {
2750 this->writeThreadgroupInit();
2751 this->writeComputeMainInputs();
2752 }
2753 else {
2754 this->writeLine("Outputs _out;");
2755 this->writeLine("(void)_out;");
2756 }
2757 fIndentation--;
2758 }
2759
2760 fFunctionHeader.clear();
2761 StringStream buffer;
2762 {
2763 AutoOutputStream outputToBuffer(this, &buffer);
2764 fIndentation++;
2765 for (const std::unique_ptr<Statement>& stmt : f.body()->as<Block>().children()) {
2766 if (!stmt->isEmpty()) {
2767 this->writeStatement(*stmt);
2768 this->finishLine();
2769 }
2770 }
2771 if (f.declaration().isMain()) {
2772 // If the main function doesn't end with a return, we need to synthesize one here.
2773 if (!is_block_ending_with_return(f.body().get())) {
2774 this->writeReturnStatementFromMain();
2775 this->finishLine();
2776 }
2777 }
2778 fIndentation--;
2779 this->writeLine("}");
2780 }
2781 this->write(fFunctionHeader);
2782 this->write(buffer.str());
2783 }
2784
2785 void MetalCodeGenerator::writeModifiers(ModifierFlags flags) {
2786 if (ProgramConfig::IsCompute(fProgram.fConfig->fKind) &&
2787 (flags & (ModifierFlag::kIn | ModifierFlag::kOut))) {
2788 this->write("device ");
2789 } else if (flags & ModifierFlag::kOut) {
2790 this->write("thread ");
2791 }
2792 if (flags.isConst()) {
2793 this->write("const ");
2794 }
2795 }
2796
2797 void MetalCodeGenerator::writeInterfaceBlock(const InterfaceBlock& intf) {
2798 if (intf.typeName() == "sk_PerVertex") {
2799 return;
2800 }
2801 const Type* structType = &intf.var()->type().componentType();
2802 this->writeModifiers(intf.var()->modifierFlags());
2803 this->write("struct ");
2804 this->writeType(*structType);
2805 this->writeLine(" {");
2806 fIndentation++;
2807 this->writeFields(structType->fields(), structType->fPosition);
2808 if (fProgram.fInterface.fRTFlipUniform != Program::Interface::kRTFlip_None) {
2809 this->writeLine("float2 " SKSL_RTFLIP_NAME ";");
2810 }
2811 fIndentation--;
2812 this->write("}");
2813 if (!intf.instanceName().empty()) {
2814 this->write(" ");
2815 this->write(intf.instanceName());
2816 if (intf.arraySize() > 0) {
2817 this->write("[");
2818 this->write(std::to_string(intf.arraySize()));
2819 this->write("]");
2820 }
2821 fInterfaceBlockNameMap.set(&intf.var()->type(), std::string(intf.instanceName()));
2822 } else {
2823 fInterfaceBlockNameMap.set(&intf.var()->type(),
2824 "_anonInterface" + std::to_string(fAnonInterfaceCount++));
2825 }
2826 this->writeLine(";");
2827 }
2828
2829 void MetalCodeGenerator::writeFields(SkSpan<const Field> fields, Position parentPos) {
2830 MemoryLayout memoryLayout(MemoryLayout::Standard::kMetal);
2831 int currentOffset = 0;
2832 for (const Field& field : fields) {
2833 int fieldOffset = field.fLayout.fOffset;
2834 const Type* fieldType = field.fType;
2835 if (!memoryLayout.isSupported(*fieldType)) {
2836 fContext.fErrors->error(parentPos, "type '" + std::string(fieldType->name()) +
2837 "' is not permitted here");
2838 return;
2839 }
2840 if (fieldOffset != -1) {
2841 if (currentOffset > fieldOffset) {
2842 fContext.fErrors->error(field.fPosition,
2843 "offset of field '" + std::string(field.fName) +
2844 "' must be at least " + std::to_string(currentOffset));
2845 return;
2846 } else if (currentOffset < fieldOffset) {
2847 this->write("char pad");
2848 this->write(std::to_string(fPaddingCount++));
2849 this->write("[");
2850 this->write(std::to_string(fieldOffset - currentOffset));
2851 this->writeLine("];");
2852 currentOffset = fieldOffset;
2853 }
2854 int alignment = memoryLayout.alignment(*fieldType);
2855 if (fieldOffset % alignment) {
2856 fContext.fErrors->error(field.fPosition,
2857 "offset of field '" + std::string(field.fName) +
2858 "' must be a multiple of " + std::to_string(alignment));
2859 return;
2860 }
2861 }
2862 if (fieldType->isUnsizedArray()) {
2863 // An unsized array always appears as the last member of a storage block. We declare
2864 // it as a one-element array and allow dereferencing past the capacity.
2865 // TODO(armansito): This is because C++ does not support flexible array members like C99
2866 // does. This generally works but it can lead to UB as compilers are free to insert
2867 // padding past the first element of the array. An alternative approach is to declare
2868 // the struct without the unsized array member and replace variable references with a
2869 // buffer offset calculation based on sizeof().
2870 this->writeModifiers(field.fModifierFlags);
2871 this->writeType(fieldType->componentType());
2872 this->write(" ");
2873 this->writeName(field.fName);
2874 this->write("[1]");
2875 } else {
2876 size_t fieldSize = memoryLayout.size(*fieldType);
2877 if (fieldSize > static_cast<size_t>(std::numeric_limits<int>::max() - currentOffset)) {
2878 fContext.fErrors->error(parentPos, "field offset overflow");
2879 return;
2880 }
2881 currentOffset += fieldSize;
2882 this->writeModifiers(field.fModifierFlags);
2883 this->writeType(*fieldType);
2884 this->write(" ");
2885 this->writeName(field.fName);
2886 }
2887 this->writeLine(";");
2888 }
2889 }
2890
2891 void MetalCodeGenerator::writeVarInitializer(const Variable& var, const Expression& value) {
2892 this->writeExpression(value, Precedence::kExpression);
2893 }
2894
2895 void MetalCodeGenerator::writeName(std::string_view name) {
2896 if (fReservedWords.contains(name)) {
2897 this->write("_"); // adding underscore before name to avoid conflict with reserved words
2898 }
2899 this->write(name);
2900 }
2901
2902 void MetalCodeGenerator::writeVarDeclaration(const VarDeclaration& varDecl) {
2903 this->writeModifiers(varDecl.var()->modifierFlags());
2904 this->writeType(varDecl.var()->type());
2905 this->write(" ");
2906 this->writeName(varDecl.var()->mangledName());
2907 if (varDecl.value()) {
2908 this->write(" = ");
2909 this->writeVarInitializer(*varDecl.var(), *varDecl.value());
2910 }
2911 this->write(";");
2912 }
2913
2914 void MetalCodeGenerator::writeStatement(const Statement& s) {
2915 switch (s.kind()) {
2916 case Statement::Kind::kBlock:
2917 this->writeBlock(s.as<Block>());
2918 break;
2919 case Statement::Kind::kExpression:
2920 this->writeExpressionStatement(s.as<ExpressionStatement>());
2921 break;
2922 case Statement::Kind::kReturn:
2923 this->writeReturnStatement(s.as<ReturnStatement>());
2924 break;
2925 case Statement::Kind::kVarDeclaration:
2926 this->writeVarDeclaration(s.as<VarDeclaration>());
2927 break;
2928 case Statement::Kind::kIf:
2929 this->writeIfStatement(s.as<IfStatement>());
2930 break;
2931 case Statement::Kind::kFor:
2932 this->writeForStatement(s.as<ForStatement>());
2933 break;
2934 case Statement::Kind::kDo:
2935 this->writeDoStatement(s.as<DoStatement>());
2936 break;
2937 case Statement::Kind::kSwitch:
2938 this->writeSwitchStatement(s.as<SwitchStatement>());
2939 break;
2940 case Statement::Kind::kBreak:
2941 this->write("break;");
2942 break;
2943 case Statement::Kind::kContinue:
2944 this->write("continue;");
2945 break;
2946 case Statement::Kind::kDiscard:
2947 this->write("discard_fragment();");
2948 break;
2949 case Statement::Kind::kNop:
2950 this->write(";");
2951 break;
2952 default:
2953 SkDEBUGFAILF("unsupported statement: %s", s.description().c_str());
2954 break;
2955 }
2956 }
2957
2958 void MetalCodeGenerator::writeBlock(const Block& b) {
2959 // Write scope markers if this block is a scope, or if the block is empty (since we need to emit
2960 // something here to make the code valid).
2961 bool isScope = b.isScope() || b.isEmpty();
2962 if (isScope) {
2963 this->writeLine("{");
2964 fIndentation++;
2965 }
2966 for (const std::unique_ptr<Statement>& stmt : b.children()) {
2967 if (!stmt->isEmpty()) {
2968 this->writeStatement(*stmt);
2969 this->finishLine();
2970 }
2971 }
2972 if (isScope) {
2973 fIndentation--;
2974 this->write("}");
2975 }
2976 }
2977
2978 void MetalCodeGenerator::writeIfStatement(const IfStatement& stmt) {
2979 this->write("if (");
2980 this->writeExpression(*stmt.test(), Precedence::kExpression);
2981 this->write(") ");
2982 this->writeStatement(*stmt.ifTrue());
2983 if (stmt.ifFalse()) {
2984 this->write(" else ");
2985 this->writeStatement(*stmt.ifFalse());
2986 }
2987 }
2988
2989 void MetalCodeGenerator::writeForStatement(const ForStatement& f) {
2990 // Emit loops of the form 'for(;test;)' as 'while(test)', which is probably how they started
2991 if (!f.initializer() && f.test() && !f.next()) {
2992 this->write("while (");
2993 this->writeExpression(*f.test(), Precedence::kExpression);
2994 this->write(") ");
2995 this->writeStatement(*f.statement());
2996 return;
2997 }
2998
2999 this->write("for (");
3000 if (f.initializer() && !f.initializer()->isEmpty()) {
3001 this->writeStatement(*f.initializer());
3002 } else {
3003 this->write("; ");
3004 }
3005 if (f.test()) {
3006 this->writeExpression(*f.test(), Precedence::kExpression);
3007 }
3008 this->write("; ");
3009 if (f.next()) {
3010 this->writeExpression(*f.next(), Precedence::kExpression);
3011 }
3012 this->write(") ");
3013 this->writeStatement(*f.statement());
3014 }
3015
3016 void MetalCodeGenerator::writeDoStatement(const DoStatement& d) {
3017 this->write("do ");
3018 this->writeStatement(*d.statement());
3019 this->write(" while (");
3020 this->writeExpression(*d.test(), Precedence::kExpression);
3021 this->write(");");
3022 }
3023
3024 void MetalCodeGenerator::writeExpressionStatement(const ExpressionStatement& s) {
3025 if (fProgram.fConfig->fSettings.fOptimize && !Analysis::HasSideEffects(*s.expression())) {
3026 // Don't emit dead expressions.
3027 return;
3028 }
3029 this->writeExpression(*s.expression(), Precedence::kStatement);
3030 this->write(";");
3031 }
3032
3033 void MetalCodeGenerator::writeSwitchStatement(const SwitchStatement& s) {
3034 this->write("switch (");
3035 this->writeExpression(*s.value(), Precedence::kExpression);
3036 this->writeLine(") {");
3037 fIndentation++;
3038 for (const std::unique_ptr<Statement>& stmt : s.cases()) {
3039 const SwitchCase& c = stmt->as<SwitchCase>();
3040 if (c.isDefault()) {
3041 this->writeLine("default:");
3042 } else {
3043 this->write("case ");
3044 this->write(std::to_string(c.value()));
3045 this->writeLine(":");
3046 }
3047 if (!c.statement()->isEmpty()) {
3048 fIndentation++;
3049 this->writeStatement(*c.statement());
3050 this->finishLine();
3051 fIndentation--;
3052 }
3053 }
3054 fIndentation--;
3055 this->write("}");
3056 }
3057
3058 void MetalCodeGenerator::writeReturnStatementFromMain() {
3059 // main functions in Metal return a magic _out parameter that doesn't exist in SkSL.
3060 if (ProgramConfig::IsVertex(fProgram.fConfig->fKind) ||
3061 ProgramConfig::IsFragment(fProgram.fConfig->fKind)) {
3062 this->write("return _out;");
3063 } else if (ProgramConfig::IsCompute(fProgram.fConfig->fKind)) {
3064 this->write("return;");
3065 } else {
3066 SkDEBUGFAIL("unsupported kind of program");
3067 }
3068 }
3069
3070 void MetalCodeGenerator::writeReturnStatement(const ReturnStatement& r) {
3071 if (fCurrentFunction && fCurrentFunction->isMain()) {
3072 if (r.expression()) {
3073 if (r.expression()->type().matches(*fContext.fTypes.fHalf4)) {
3074 this->write("_out.sk_FragColor = ");
3075 this->writeExpression(*r.expression(), Precedence::kExpression);
3076 this->writeLine(";");
3077 } else {
3078 fContext.fErrors->error(r.fPosition,
3079 "Metal does not support returning '" +
3080 r.expression()->type().description() + "' from main()");
3081 }
3082 }
3083 this->writeReturnStatementFromMain();
3084 return;
3085 }
3086
3087 this->write("return");
3088 if (r.expression()) {
3089 this->write(" ");
3090 this->writeExpression(*r.expression(), Precedence::kExpression);
3091 }
3092 this->write(";");
3093 }
3094
3095 void MetalCodeGenerator::writeHeader() {
3096 this->writeLine("#include <metal_stdlib>");
3097 this->writeLine("#include <simd/simd.h>");
3098 this->writeLine("#ifdef __clang__");
3099 this->writeLine("#pragma clang diagnostic ignored \"-Wall\"");
3100 this->writeLine("#endif");
3101 this->writeLine("using namespace metal;");
3102 }
3103
3104 void MetalCodeGenerator::writeSampler2DPolyfill() {
3105 class : public GlobalStructVisitor {
3106 public:
3107 void visitSampler(const Type&, std::string_view) override {
3108 if (fWrotePolyfill) {
3109 return;
3110 }
3111 fWrotePolyfill = true;
3112
3113 std::string polyfill = SkSL::String::printf(
3114 "struct sampler2D {"
3115 "texture2d<half> tex;"
3116 "sampler smp;"
3117 "};"
3118 "half4 sample(sampler2D i, float2 p, float b=%g) { return i.tex.sample(i.smp, p, bias(b)); }"
3119 "half4 sample(sampler2D i, float3 p, float b=%g) { return i.tex.sample(i.smp, p.xy / p.z, bias(b)); }"
3120 "half4 sampleLod(sampler2D i, float2 p, float lod) { return i.tex.sample(i.smp, p, level(lod)); }"
3121 "half4 sampleLod(sampler2D i, float3 p, float lod) {"
3122 "return i.tex.sample(i.smp, p.xy / p.z, level(lod));"
3123 "}"
3124 "half4 sampleGrad(sampler2D i, float2 p, float2 dPdx, float2 dPdy) {"
3125 "return i.tex.sample(i.smp, p, gradient2d(dPdx, dPdy));"
3126 "}",
3127 fTextureBias,
3128 fTextureBias);
3129 fCodeGen->write(polyfill.c_str());
3130 }
3131
3132 MetalCodeGenerator* fCodeGen = nullptr;
3133 float fTextureBias = 0.0f;
3134 bool fWrotePolyfill = false;
3135 } visitor;
3136
3137 visitor.fCodeGen = this;
3138 visitor.fTextureBias = fProgram.fConfig->fSettings.fSharpenTextures ? kSharpenTexturesBias
3139 : 0.0f;
3140 this->visitGlobalStruct(&visitor);
3141 }
3142
3143 void MetalCodeGenerator::writeUniformStruct() {
3144 for (const ProgramElement* e : fProgram.elements()) {
3145 if (e->is<GlobalVarDeclaration>()) {
3146 const GlobalVarDeclaration& decls = e->as<GlobalVarDeclaration>();
3147 const Variable& var = *decls.varDeclaration().var();
3148 if (var.modifierFlags().isUniform()) {
3149 SkASSERT(var.type().typeKind() != Type::TypeKind::kSampler &&
3150 var.type().typeKind() != Type::TypeKind::kTexture);
3151 int uniformSet = this->getUniformSet(var.layout());
3152 // Make sure that the program's uniform-set value is consistent throughout.
3153 if (-1 == fUniformBuffer) {
3154 this->write("struct Uniforms {\n");
3155 fUniformBuffer = uniformSet;
3156 } else if (uniformSet != fUniformBuffer) {
3157 fContext.fErrors->error(decls.fPosition,
3158 "Metal backend requires all uniforms to have the same "
3159 "'layout(set=...)'");
3160 }
3161 this->write(" ");
3162 this->writeType(var.type());
3163 this->write(" ");
3164 this->writeName(var.mangledName());
3165 this->write(";\n");
3166 }
3167 }
3168 }
3169 if (-1 != fUniformBuffer) {
3170 this->write("};\n");
3171 }
3172 }
3173
3174 void MetalCodeGenerator::writeInterpolatedAttributes(const Variable& var) {
3175 SkASSERT((is_output(var) && ProgramConfig::IsVertex(fProgram.fConfig->fKind)) ||
3176 (is_input(var) && ProgramConfig::IsFragment(fProgram.fConfig->fKind)));
3177 // Always include the location
3178 this->write(" [[user(locn");
3179 this->write(std::to_string(var.layout().fLocation));
3180 this->write(")");
3181
3182 if (var.modifierFlags().isFlat()) {
3183 this->write(" flat");
3184 } else if (var.modifierFlags().isNoPerspective()) {
3185 this->write(" center_no_perspective");
3186 } // else default behavior is center_perspective
3187
3188 this->write("]]");
3189 }
3190
3191 void MetalCodeGenerator::writeInputStruct() {
3192 this->write("struct Inputs {\n");
3193 for (const ProgramElement* e : fProgram.elements()) {
3194 if (e->is<GlobalVarDeclaration>()) {
3195 const GlobalVarDeclaration& decls = e->as<GlobalVarDeclaration>();
3196 const Variable& var = *decls.varDeclaration().var();
3197 if (is_input(var)) {
3198 this->write(" ");
3199 if (ProgramConfig::IsCompute(fProgram.fConfig->fKind) &&
3200 needs_address_space(var.type(), var.modifierFlags())) {
3201 // TODO: address space support
3202 this->write("device ");
3203 }
3204 this->writeType(var.type());
3205 if (pass_by_reference(var.type(), var.modifierFlags())) {
3206 this->write("&");
3207 }
3208 this->write(" ");
3209 this->writeName(var.mangledName());
3210 if (-1 != var.layout().fLocation) {
3211 if (ProgramConfig::IsVertex(fProgram.fConfig->fKind)) {
3212 this->write(" [[attribute(" + std::to_string(var.layout().fLocation) +
3213 ")]]");
3214 } else if (ProgramConfig::IsFragment(fProgram.fConfig->fKind)) {
3215 // Write attributes for the fragment input that are consistent with
3216 // what's annotated on the vertex output.
3217 this->writeInterpolatedAttributes(var);
3218 }
3219 }
3220 this->write(";\n");
3221 }
3222 }
3223 }
3224 this->write("};\n");
3225 }
3226
3227 void MetalCodeGenerator::writeOutputStruct() {
3228 this->write("struct Outputs {\n");
3229 if (ProgramConfig::IsVertex(fProgram.fConfig->fKind)) {
3230 this->write(" float4 sk_Position [[position]];\n");
3231 } else if (ProgramConfig::IsFragment(fProgram.fConfig->fKind)) {
3232 this->write(" half4 sk_FragColor [[color(0)]];\n");
3233 if (fProgram.fInterface.fOutputSecondaryColor) {
3234 this->write(" half4 sk_SecondaryFragColor [[color(0), index(1)]];\n");
3235 }
3236 }
3237 for (const ProgramElement* e : fProgram.elements()) {
3238 if (e->is<GlobalVarDeclaration>()) {
3239 const GlobalVarDeclaration& decls = e->as<GlobalVarDeclaration>();
3240 const Variable& var = *decls.varDeclaration().var();
3241 if (var.layout().fBuiltin == SK_SAMPLEMASK_BUILTIN) {
3242 this->write(" uint sk_SampleMask [[sample_mask]];\n");
3243 continue;
3244 }
3245 if (is_output(var)) {
3246 this->write(" ");
3247 if (ProgramConfig::IsCompute(fProgram.fConfig->fKind) &&
3248 needs_address_space(var.type(), var.modifierFlags())) {
3249 // TODO: address space support
3250 this->write("device ");
3251 }
3252 this->writeType(var.type());
3253 if (ProgramConfig::IsCompute(fProgram.fConfig->fKind) &&
3254 pass_by_reference(var.type(), var.modifierFlags())) {
3255 this->write("&");
3256 }
3257 this->write(" ");
3258 this->writeName(var.mangledName());
3259
3260 int location = var.layout().fLocation;
3261 if (!ProgramConfig::IsCompute(fProgram.fConfig->fKind) && location < 0 &&
3262 var.type().typeKind() != Type::TypeKind::kTexture) {
3263 fContext.fErrors->error(var.fPosition,
3264 "Metal out variables must have 'layout(location=...)'");
3265 } else if (ProgramConfig::IsVertex(fProgram.fConfig->fKind)) {
3266 // Write attributes for the vertex output that are consistent with what's
3267 // annotated on the fragment input.
3268 this->writeInterpolatedAttributes(var);
3269 } else if (ProgramConfig::IsFragment(fProgram.fConfig->fKind)) {
3270 this->write(" [[color(" + std::to_string(location) + ")");
3271 int colorIndex = var.layout().fIndex;
3272 if (colorIndex) {
3273 this->write(", index(" + std::to_string(colorIndex) + ")");
3274 }
3275 this->write("]]");
3276 }
3277 this->write(";\n");
3278 }
3279 }
3280 }
3281 if (ProgramConfig::IsVertex(fProgram.fConfig->fKind)) {
3282 this->write(" float sk_PointSize [[point_size]];\n");
3283 }
3284 this->write("};\n");
3285 }
3286
3287 void MetalCodeGenerator::writeInterfaceBlocks() {
3288 bool wroteInterfaceBlock = false;
3289 for (const ProgramElement* e : fProgram.elements()) {
3290 if (e->is<InterfaceBlock>()) {
3291 this->writeInterfaceBlock(e->as<InterfaceBlock>());
3292 wroteInterfaceBlock = true;
3293 }
3294 }
3295 if (!wroteInterfaceBlock &&
3296 fProgram.fInterface.fRTFlipUniform != Program::Interface::kRTFlip_None) {
3297 this->writeLine("struct sksl_synthetic_uniforms {"
3298 "float2 " SKSL_RTFLIP_NAME ";"
3299 "};");
3300 }
3301 }
3302
3303 void MetalCodeGenerator::writeStructDefinitions() {
3304 for (const ProgramElement* e : fProgram.elements()) {
3305 if (e->is<StructDefinition>()) {
3306 this->writeStructDefinition(e->as<StructDefinition>());
3307 }
3308 }
3309 }
3310
3311 void MetalCodeGenerator::writeConstantVariables() {
3312 class : public GlobalStructVisitor {
3313 public:
3314 void visitConstantVariable(const VarDeclaration& decl) override {
3315 fCodeGen->write("constant ");
3316 fCodeGen->writeVarDeclaration(decl);
3317 fCodeGen->finishLine();
3318 }
3319
3320 MetalCodeGenerator* fCodeGen = nullptr;
3321 } visitor;
3322
3323 visitor.fCodeGen = this;
3324 this->visitGlobalStruct(&visitor);
3325 }
3326
3327 void MetalCodeGenerator::visitGlobalStruct(GlobalStructVisitor* visitor) {
3328 for (const ProgramElement* element : fProgram.elements()) {
3329 if (element->is<InterfaceBlock>()) {
3330 const auto* ib = &element->as<InterfaceBlock>();
3331 if (ib->typeName() != "sk_PerVertex") {
3332 visitor->visitInterfaceBlock(*ib, fInterfaceBlockNameMap[&ib->var()->type()]);
3333 }
3334 continue;
3335 }
3336 if (!element->is<GlobalVarDeclaration>()) {
3337 continue;
3338 }
3339 const GlobalVarDeclaration& global = element->as<GlobalVarDeclaration>();
3340 const VarDeclaration& decl = global.varDeclaration();
3341 const Variable& var = *decl.var();
3342 if (decl.baseType().typeKind() == Type::TypeKind::kSampler) {
3343 visitor->visitSampler(var.type(), var.mangledName());
3344 continue;
3345 }
3346 if (decl.baseType().typeKind() == Type::TypeKind::kTexture) {
3347 visitor->visitTexture(var.type(), var.mangledName());
3348 continue;
3349 }
3350 if (!(var.modifierFlags() & ~ModifierFlag::kConst) && var.layout().fBuiltin == -1) {
3351 if (is_in_globals(var)) {
3352 // Visit a regular global variable.
3353 visitor->visitNonconstantVariable(var, decl.value().get());
3354 } else {
3355 // Visit a constant-expression variable.
3356 SkASSERT(var.modifierFlags().isConst());
3357 visitor->visitConstantVariable(decl);
3358 }
3359 }
3360 }
3361 }
3362
3363 void MetalCodeGenerator::writeGlobalStruct() {
3364 class : public GlobalStructVisitor {
3365 public:
3366 void visitInterfaceBlock(const InterfaceBlock& block,
3367 std::string_view blockName) override {
3368 this->addElement();
3369 fCodeGen->write(" ");
3370 if (is_readonly(block)) {
3371 fCodeGen->write("const ");
3372 }
3373 fCodeGen->write(is_buffer(block) ? "device " : "constant ");
3374 fCodeGen->write(block.typeName());
3375 fCodeGen->write("* ");
3376 fCodeGen->writeName(blockName);
3377 fCodeGen->write(";\n");
3378 }
3379 void visitTexture(const Type& type, std::string_view name) override {
3380 this->addElement();
3381 fCodeGen->write(" ");
3382 fCodeGen->writeType(type);
3383 fCodeGen->write(" ");
3384 fCodeGen->writeName(name);
3385 fCodeGen->write(";\n");
3386 }
3387 void visitSampler(const Type&, std::string_view name) override {
3388 this->addElement();
3389 fCodeGen->write(" sampler2D ");
3390 fCodeGen->writeName(name);
3391 fCodeGen->write(";\n");
3392 }
3393 void visitConstantVariable(const VarDeclaration& decl) override {
3394 // Constants aren't added to the global struct.
3395 }
3396 void visitNonconstantVariable(const Variable& var, const Expression* value) override {
3397 this->addElement();
3398 fCodeGen->write(" ");
3399 fCodeGen->writeModifiers(var.modifierFlags());
3400 fCodeGen->writeType(var.type());
3401 fCodeGen->write(" ");
3402 fCodeGen->writeName(var.mangledName());
3403 fCodeGen->write(";\n");
3404 }
3405 void addElement() {
3406 if (fFirst) {
3407 fCodeGen->write("struct Globals {\n");
3408 fFirst = false;
3409 }
3410 }
3411 void finish() {
3412 if (!fFirst) {
3413 fCodeGen->writeLine("};");
3414 fFirst = true;
3415 }
3416 }
3417
3418 MetalCodeGenerator* fCodeGen = nullptr;
3419 bool fFirst = true;
3420 } visitor;
3421
3422 visitor.fCodeGen = this;
3423 this->visitGlobalStruct(&visitor);
3424 visitor.finish();
3425 }
3426
3427 void MetalCodeGenerator::writeGlobalInit() {
3428 class : public GlobalStructVisitor {
3429 public:
3430 void visitInterfaceBlock(const InterfaceBlock& blockType,
3431 std::string_view blockName) override {
3432 this->addElement();
3433 fCodeGen->write("&");
3434 fCodeGen->writeName(blockName);
3435 }
3436 void visitTexture(const Type&, std::string_view name) override {
3437 this->addElement();
3438 fCodeGen->writeName(name);
3439 }
3440 void visitSampler(const Type&, std::string_view name) override {
3441 this->addElement();
3442 fCodeGen->write("{");
3443 fCodeGen->writeName(name);
3444 fCodeGen->write(kTextureSuffix);
3445 fCodeGen->write(", ");
3446 fCodeGen->writeName(name);
3447 fCodeGen->write(kSamplerSuffix);
3448 fCodeGen->write("}");
3449 }
3450 void visitConstantVariable(const VarDeclaration& decl) override {
3451 // Constant-expression variables aren't put in the global struct.
3452 }
3453 void visitNonconstantVariable(const Variable& var, const Expression* value) override {
3454 this->addElement();
3455 if (value) {
3456 fCodeGen->writeVarInitializer(var, *value);
3457 } else {
3458 fCodeGen->write("{}");
3459 }
3460 }
3461 void addElement() {
3462 if (fFirst) {
3463 fCodeGen->write("Globals _globals{");
3464 fFirst = false;
3465 } else {
3466 fCodeGen->write(", ");
3467 }
3468 }
3469 void finish() {
3470 if (!fFirst) {
3471 fCodeGen->writeLine("};");
3472 fCodeGen->writeLine("(void)_globals;");
3473 }
3474 }
3475 MetalCodeGenerator* fCodeGen = nullptr;
3476 bool fFirst = true;
3477 } visitor;
3478
3479 visitor.fCodeGen = this;
3480 this->visitGlobalStruct(&visitor);
3481 visitor.finish();
3482 }
3483
3484 void MetalCodeGenerator::visitThreadgroupStruct(ThreadgroupStructVisitor* visitor) {
3485 for (const ProgramElement* element : fProgram.elements()) {
3486 if (!element->is<GlobalVarDeclaration>()) {
3487 continue;
3488 }
3489 const GlobalVarDeclaration& global = element->as<GlobalVarDeclaration>();
3490 const VarDeclaration& decl = global.varDeclaration();
3491 const Variable& var = *decl.var();
3492 if (var.modifierFlags().isWorkgroup()) {
3493 SkASSERT(!decl.value());
3494 SkASSERT(!var.modifierFlags().isConst());
3495 visitor->visitNonconstantVariable(var);
3496 }
3497 }
3498 }
3499
3500 void MetalCodeGenerator::writeThreadgroupStruct() {
3501 class : public ThreadgroupStructVisitor {
3502 public:
3503 void visitNonconstantVariable(const Variable& var) override {
3504 this->addElement();
3505 fCodeGen->write(" ");
3506 fCodeGen->writeModifiers(var.modifierFlags());
3507 fCodeGen->writeType(var.type());
3508 fCodeGen->write(" ");
3509 fCodeGen->writeName(var.mangledName());
3510 fCodeGen->write(";\n");
3511 }
3512 void addElement() {
3513 if (fFirst) {
3514 fCodeGen->write("struct Threadgroups {\n");
3515 fFirst = false;
3516 }
3517 }
3518 void finish() {
3519 if (!fFirst) {
3520 fCodeGen->writeLine("};");
3521 fFirst = true;
3522 }
3523 }
3524
3525 MetalCodeGenerator* fCodeGen = nullptr;
3526 bool fFirst = true;
3527 } visitor;
3528
3529 visitor.fCodeGen = this;
3530 this->visitThreadgroupStruct(&visitor);
3531 visitor.finish();
3532 }
3533
3534 void MetalCodeGenerator::writeThreadgroupInit() {
3535 class : public ThreadgroupStructVisitor {
3536 public:
3537 void visitNonconstantVariable(const Variable& var) override {
3538 this->addElement();
3539 fCodeGen->write("{}");
3540 }
3541 void addElement() {
3542 if (fFirst) {
3543 fCodeGen->write("threadgroup Threadgroups _threadgroups{");
3544 fFirst = false;
3545 } else {
3546 fCodeGen->write(", ");
3547 }
3548 }
3549 void finish() {
3550 if (!fFirst) {
3551 fCodeGen->writeLine("};");
3552 fCodeGen->writeLine("(void)_threadgroups;");
3553 }
3554 }
3555 MetalCodeGenerator* fCodeGen = nullptr;
3556 bool fFirst = true;
3557 } visitor;
3558
3559 visitor.fCodeGen = this;
3560 this->visitThreadgroupStruct(&visitor);
3561 visitor.finish();
3562 }
3563
3564 void MetalCodeGenerator::writeProgramElement(const ProgramElement& e) {
3565 switch (e.kind()) {
3566 case ProgramElement::Kind::kExtension:
3567 break;
3568 case ProgramElement::Kind::kGlobalVar:
3569 break;
3570 case ProgramElement::Kind::kInterfaceBlock:
3571 // Handled in writeInterfaceBlocks; do nothing.
3572 break;
3573 case ProgramElement::Kind::kStructDefinition:
3574 // Handled in writeStructDefinitions; do nothing.
3575 break;
3576 case ProgramElement::Kind::kFunction:
3577 this->writeFunction(e.as<FunctionDefinition>());
3578 break;
3579 case ProgramElement::Kind::kFunctionPrototype:
3580 this->writeFunctionPrototype(e.as<FunctionPrototype>());
3581 break;
3582 case ProgramElement::Kind::kModifiers:
3583 // Not necessary in Metal; do nothing.
3584 break;
3585 default:
3586 SkDEBUGFAILF("unsupported program element: %s\n", e.description().c_str());
3587 break;
3588 }
3589 }
3590
3591 MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const Statement* s) {
3592 class RequirementsVisitor : public ProgramVisitor {
3593 public:
3594 using ProgramVisitor::visitStatement;
3595
3596 bool visitExpression(const Expression& e) override {
3597 switch (e.kind()) {
3598 case Expression::Kind::kFunctionCall: {
3599 const FunctionCall& f = e.as<FunctionCall>();
3600 fRequirements |= fCodeGen->requirements(f.function());
3601 break;
3602 }
3603 case Expression::Kind::kFieldAccess: {
3604 const FieldAccess& f = e.as<FieldAccess>();
3605 if (f.ownerKind() == FieldAccess::OwnerKind::kAnonymousInterfaceBlock) {
3606 fRequirements |= kGlobals_Requirement;
3607 return false; // don't recurse into the base variable
3608 }
3609 break;
3610 }
3611 case Expression::Kind::kVariableReference: {
3612 const Variable& var = *e.as<VariableReference>().variable();
3613
3614 if (var.layout().fBuiltin == SK_FRAGCOORD_BUILTIN) {
3615 fRequirements |= kGlobals_Requirement | kFragCoord_Requirement;
3616 } else if (var.layout().fBuiltin == SK_SAMPLEMASKIN_BUILTIN) {
3617 fRequirements |= kSampleMaskIn_Requirement;
3618 } else if (var.layout().fBuiltin == SK_SAMPLEMASK_BUILTIN) {
3619 fRequirements |= kOutputs_Requirement;
3620 } else if (var.layout().fBuiltin == SK_VERTEXID_BUILTIN) {
3621 fRequirements |= kVertexID_Requirement;
3622 } else if (var.layout().fBuiltin == SK_INSTANCEID_BUILTIN) {
3623 fRequirements |= kInstanceID_Requirement;
3624 } else if (var.storage() == Variable::Storage::kGlobal) {
3625 if (is_input(var)) {
3626 fRequirements |= kInputs_Requirement;
3627 } else if (is_output(var)) {
3628 fRequirements |= kOutputs_Requirement;
3629 } else if (is_uniforms(var)) {
3630 fRequirements |= kUniforms_Requirement;
3631 } else if (is_threadgroup(var)) {
3632 fRequirements |= kThreadgroups_Requirement;
3633 } else if (is_in_globals(var)) {
3634 fRequirements |= kGlobals_Requirement;
3635 }
3636 }
3637 break;
3638 }
3639 default:
3640 break;
3641 }
3642 return ProgramVisitor::visitExpression(e);
3643 }
3644
3645 MetalCodeGenerator* fCodeGen;
3646 Requirements fRequirements = kNo_Requirements;
3647 };
3648
3649 RequirementsVisitor visitor;
3650 if (s) {
3651 visitor.fCodeGen = this;
3652 visitor.visitStatement(*s);
3653 }
3654 return visitor.fRequirements;
3655 }
3656
3657 MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const FunctionDeclaration& f) {
3658 Requirements* found = fRequirements.find(&f);
3659 if (!found) {
3660 fRequirements.set(&f, kNo_Requirements);
3661 for (const ProgramElement* e : fProgram.elements()) {
3662 if (e->is<FunctionDefinition>()) {
3663 const FunctionDefinition& def = e->as<FunctionDefinition>();
3664 if (&def.declaration() == &f) {
3665 Requirements reqs = this->requirements(def.body().get());
3666 fRequirements.set(&f, reqs);
3667 return reqs;
3668 }
3669 }
3670 }
3671
3672 // We never found a definition for this declared function, but it's legal to prototype a
3673 // function without ever giving a definition, as long as you don't call it.
3674 return kNo_Requirements;
3675 }
3676 return *found;
3677 }
3678
3679 bool MetalCodeGenerator::generateCode() {
3680 StringStream header;
3681 {
3682 AutoOutputStream outputToHeader(this, &header, &fIndentation);
3683 this->writeHeader();
3684 this->writeConstantVariables();
3685 this->writeSampler2DPolyfill();
3686 this->writeStructDefinitions();
3687 this->writeUniformStruct();
3688 this->writeInputStruct();
3689 if (!ProgramConfig::IsCompute(fProgram.fConfig->fKind)) {
3690 this->writeOutputStruct();
3691 }
3692 this->writeInterfaceBlocks();
3693 this->writeGlobalStruct();
3694 this->writeThreadgroupStruct();
3695
3696 // Emit prototypes for every built-in function; these aren't always added in perfect order.
3697 for (const ProgramElement* e : fProgram.fSharedElements) {
3698 if (e->is<FunctionDefinition>()) {
3699 this->writeFunctionDeclaration(e->as<FunctionDefinition>().declaration());
3700 this->writeLine(";");
3701 }
3702 }
3703 }
3704 StringStream body;
3705 {
3706 AutoOutputStream outputToBody(this, &body, &fIndentation);
3707
3708 for (const ProgramElement* e : fProgram.elements()) {
3709 this->writeProgramElement(*e);
3710 }
3711 }
3712 write_stringstream(header, *fOut);
3713 write_stringstream(fExtraFunctionPrototypes, *fOut);
3714 write_stringstream(fExtraFunctions, *fOut);
3715 write_stringstream(body, *fOut);
3716 return fContext.fErrors->errorCount() == 0;
3717 }
3718
3719 bool ToMetal(Program& program, const ShaderCaps* caps, OutputStream& out, PrettyPrint pp) {
3720 TRACE_EVENT0("skia.shaders", "SkSL::ToMetal");
3721 SkASSERT(caps != nullptr);
3722
3723 program.fContext->fErrors->setSource(*program.fSource);
3724 MetalCodeGenerator cg(program.fContext.get(), caps, &program, &out, pp);
3725 bool result = cg.generateCode();
3726 program.fContext->fErrors->setSource(std::string_view());
3727
3728 return result;
3729 }
3730
3731 bool ToMetal(Program& program, const ShaderCaps* caps, OutputStream& out) {
3732 #if defined(SK_DEBUG)
3733 constexpr PrettyPrint defaultPrintOpts = PrettyPrint::kYes;
3734 #else
3735 constexpr PrettyPrint defaultPrintOpts = PrettyPrint::kNo;
3736 #endif
3737 return ToMetal(program, caps, out, defaultPrintOpts);
3738 }
3739
3740 bool ToMetal(Program& program, const ShaderCaps* caps, NativeShader* out) {
3741 StringStream buffer;
3742 if (!ToMetal(program, caps, buffer)) {
3743 return false;
3744 }
3745 out->fText = buffer.str();
3746 return true;
3747 }
3748
3749 } // namespace SkSL