blob: 1c8bc24f6756e1ea1824e3b5107f48c5c2a112b2 [file] [log] [blame]
ethannicholasb3058bd2016-07-01 08:22:01 -07001/*
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 */
Ethan Nicholas11d53972016-11-28 11:23:23 -05007
Mike Kleinc0bd9f92019-04-23 12:05:21 -05008#include "src/sksl/SkSLIRGenerator.h"
ethannicholasb3058bd2016-07-01 08:22:01 -07009
10#include "limits.h"
John Stiles44e96be2020-08-31 13:16:04 -040011#include <iterator>
John Stilesfbd050b2020-08-03 13:21:46 -040012#include <memory>
Ethan Nicholasaf197692017-02-27 13:26:45 -050013#include <unordered_set>
ethannicholasb3058bd2016-07-01 08:22:01 -070014
Ethan Nicholasdaed2592021-03-04 14:30:25 -050015#include "include/private/SkSLLayout.h"
John Stiles6bef6a72020-12-02 14:26:04 -050016#include "include/private/SkTArray.h"
Ethan Nicholasbe65cd52021-05-18 12:09:01 -040017#include "include/sksl/DSLCore.h"
John Stilesb2705a12021-02-19 10:55:14 -050018#include "src/core/SkScopeExit.h"
Ethan Nicholas6e0fa402020-08-20 14:08:23 -040019#include "src/sksl/SkSLAnalysis.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050020#include "src/sksl/SkSLCompiler.h"
John Stilesdc8ec312021-01-11 11:05:21 -050021#include "src/sksl/SkSLConstantFolder.h"
Brian Osman00185012021-02-04 16:07:11 -050022#include "src/sksl/SkSLOperators.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050023#include "src/sksl/SkSLParser.h"
Brian Osman3000d6b2020-07-31 15:57:28 -040024#include "src/sksl/SkSLUtil.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050025#include "src/sksl/ir/SkSLBinaryExpression.h"
26#include "src/sksl/ir/SkSLBoolLiteral.h"
27#include "src/sksl/ir/SkSLBreakStatement.h"
28#include "src/sksl/ir/SkSLConstructor.h"
29#include "src/sksl/ir/SkSLContinueStatement.h"
30#include "src/sksl/ir/SkSLDiscardStatement.h"
31#include "src/sksl/ir/SkSLDoStatement.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050032#include "src/sksl/ir/SkSLExpressionStatement.h"
Ethan Nicholas9e6a3932019-05-17 16:31:21 -040033#include "src/sksl/ir/SkSLExternalFunctionCall.h"
Brian Osmanbe0b3b72021-01-06 14:27:35 -050034#include "src/sksl/ir/SkSLExternalFunctionReference.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050035#include "src/sksl/ir/SkSLField.h"
36#include "src/sksl/ir/SkSLFieldAccess.h"
37#include "src/sksl/ir/SkSLFloatLiteral.h"
38#include "src/sksl/ir/SkSLForStatement.h"
39#include "src/sksl/ir/SkSLFunctionCall.h"
40#include "src/sksl/ir/SkSLFunctionDeclaration.h"
41#include "src/sksl/ir/SkSLFunctionDefinition.h"
John Stiles569249b2020-11-03 12:18:22 -050042#include "src/sksl/ir/SkSLFunctionPrototype.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050043#include "src/sksl/ir/SkSLFunctionReference.h"
44#include "src/sksl/ir/SkSLIfStatement.h"
45#include "src/sksl/ir/SkSLIndexExpression.h"
46#include "src/sksl/ir/SkSLIntLiteral.h"
47#include "src/sksl/ir/SkSLInterfaceBlock.h"
Chris Daltonb0fd4b12019-10-29 13:41:22 -060048#include "src/sksl/ir/SkSLNop.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050049#include "src/sksl/ir/SkSLPostfixExpression.h"
50#include "src/sksl/ir/SkSLPrefixExpression.h"
51#include "src/sksl/ir/SkSLReturnStatement.h"
52#include "src/sksl/ir/SkSLSetting.h"
John Stilesdc75a972020-11-25 16:24:55 -050053#include "src/sksl/ir/SkSLStructDefinition.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050054#include "src/sksl/ir/SkSLSwitchCase.h"
55#include "src/sksl/ir/SkSLSwitchStatement.h"
56#include "src/sksl/ir/SkSLSwizzle.h"
57#include "src/sksl/ir/SkSLTernaryExpression.h"
58#include "src/sksl/ir/SkSLUnresolvedFunction.h"
59#include "src/sksl/ir/SkSLVarDeclarations.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050060#include "src/sksl/ir/SkSLVariable.h"
61#include "src/sksl/ir/SkSLVariableReference.h"
ethannicholasb3058bd2016-07-01 08:22:01 -070062
63namespace SkSL {
64
65class AutoSymbolTable {
66public:
Ethan Nicholas11d53972016-11-28 11:23:23 -050067 AutoSymbolTable(IRGenerator* ir)
ethannicholasb3058bd2016-07-01 08:22:01 -070068 : fIR(ir)
69 , fPrevious(fIR->fSymbolTable) {
70 fIR->pushSymbolTable();
71 }
72
73 ~AutoSymbolTable() {
74 fIR->popSymbolTable();
Ethan Nicholasd9d33c32018-06-12 11:05:59 -040075 SkASSERT(fPrevious == fIR->fSymbolTable);
ethannicholasb3058bd2016-07-01 08:22:01 -070076 }
77
78 IRGenerator* fIR;
79 std::shared_ptr<SymbolTable> fPrevious;
80};
81
John Stilesc1a98b82021-02-24 13:35:02 -050082IRGenerator::IRGenerator(const Context* context)
John Stiles10d39d92021-05-04 16:13:14 -040083 : fContext(*context) {}
Brian Osman0006ad02020-11-18 15:38:39 -050084
85void IRGenerator::pushSymbolTable() {
86 auto childSymTable = std::make_shared<SymbolTable>(std::move(fSymbolTable), fIsBuiltinCode);
87 fSymbolTable = std::move(childSymTable);
88}
89
90void IRGenerator::popSymbolTable() {
91 fSymbolTable = fSymbolTable->fParent;
92}
93
John Stilese3a91cf2021-01-26 10:13:58 -050094bool IRGenerator::detectVarDeclarationWithoutScope(const Statement& stmt) {
95 // Parsing an AST node containing a single variable declaration creates a lone VarDeclaration
96 // statement. An AST with multiple variable declarations creates an unscoped Block containing
97 // multiple VarDeclaration statements. We need to detect either case.
98 const Variable* var;
99 if (stmt.is<VarDeclaration>()) {
100 // The single-variable case. No blocks at all.
101 var = &stmt.as<VarDeclaration>().var();
102 } else if (stmt.is<Block>()) {
103 // The multiple-variable case: an unscoped, non-empty block...
104 const Block& block = stmt.as<Block>();
105 if (block.isScope() || block.children().empty()) {
106 return false;
107 }
108 // ... holding a variable declaration.
109 const Statement& innerStmt = *block.children().front();
110 if (!innerStmt.is<VarDeclaration>()) {
111 return false;
112 }
113 var = &innerStmt.as<VarDeclaration>().var();
114 } else {
115 // This statement wasn't a variable declaration. No problem.
116 return false;
117 }
118
119 // Report an error.
120 SkASSERT(var);
121 this->errorReporter().error(stmt.fOffset,
122 "variable '" + var->name() + "' must be created in a scope");
123 return true;
124}
125
Ethan Nicholas962dec42021-06-10 13:06:39 -0400126std::unique_ptr<Extension> IRGenerator::convertExtension(int offset, skstd::string_view name) {
John Stilesd1204642021-02-17 16:30:02 -0500127 if (this->programKind() != ProgramKind::kFragment &&
128 this->programKind() != ProgramKind::kVertex &&
129 this->programKind() != ProgramKind::kGeometry) {
John Stilesb30151e2021-01-11 16:13:08 -0500130 this->errorReporter().error(offset, "extensions are not allowed here");
Brian Osman16f376f2020-09-02 12:30:59 -0400131 return nullptr;
132 }
133
John Stilesfbd050b2020-08-03 13:21:46 -0400134 return std::make_unique<Extension>(offset, name);
ethannicholasb3058bd2016-07-01 08:22:01 -0700135}
136
John Stiles20c09f92021-03-12 09:25:04 -0500137std::unique_ptr<Statement> IRGenerator::convertStatement(const ASTNode& statement) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700138 switch (statement.fKind) {
Ethan Nicholasfc994162019-06-06 10:04:27 -0400139 case ASTNode::Kind::kBlock:
140 return this->convertBlock(statement);
141 case ASTNode::Kind::kVarDeclarations:
142 return this->convertVarDeclarationStatement(statement);
143 case ASTNode::Kind::kIf:
144 return this->convertIf(statement);
145 case ASTNode::Kind::kFor:
146 return this->convertFor(statement);
147 case ASTNode::Kind::kWhile:
148 return this->convertWhile(statement);
149 case ASTNode::Kind::kDo:
150 return this->convertDo(statement);
151 case ASTNode::Kind::kSwitch:
152 return this->convertSwitch(statement);
153 case ASTNode::Kind::kReturn:
154 return this->convertReturn(statement);
155 case ASTNode::Kind::kBreak:
156 return this->convertBreak(statement);
157 case ASTNode::Kind::kContinue:
158 return this->convertContinue(statement);
159 case ASTNode::Kind::kDiscard:
160 return this->convertDiscard(statement);
John Stilesdc75a972020-11-25 16:24:55 -0500161 case ASTNode::Kind::kType:
162 // TODO: add IRNode for struct definition inside a function
163 return nullptr;
Ethan Nicholasfc994162019-06-06 10:04:27 -0400164 default:
165 // it's an expression
166 std::unique_ptr<Statement> result = this->convertExpressionStatement(statement);
John Stilesd1204642021-02-17 16:30:02 -0500167 if (fRTAdjust && this->programKind() == ProgramKind::kGeometry) {
John Stilese67bd132021-03-19 18:39:25 -0400168 SkASSERT(result->is<ExpressionStatement>());
Ethan Nicholasd503a5a2020-09-30 09:29:55 -0400169 Expression& expr = *result->as<ExpressionStatement>().expression();
John Stilese67bd132021-03-19 18:39:25 -0400170 if (expr.is<FunctionCall>()) {
John Stiles403a3632020-08-20 12:11:48 -0400171 FunctionCall& fc = expr.as<FunctionCall>();
Ethan Nicholased84b732020-10-08 11:45:44 -0400172 if (fc.function().isBuiltin() && fc.function().name() == "EmitVertex") {
John Stiles8f2a0cf2020-10-13 12:48:21 -0400173 StatementArray statements;
John Stilesf4bda742020-10-14 16:57:41 -0400174 statements.reserve_back(2);
Robert Phillipsfe8da172018-01-24 14:52:02 +0000175 statements.push_back(getNormalizeSkPositionCode());
176 statements.push_back(std::move(result));
John Stilesbf16b6c2021-03-12 19:24:31 -0500177 return Block::Make(statement.fOffset, std::move(statements),
178 fSymbolTable, /*isScope=*/true);
Robert Phillipsfe8da172018-01-24 14:52:02 +0000179 }
180 }
181 }
182 return result;
ethannicholasb3058bd2016-07-01 08:22:01 -0700183 }
184}
185
Ethan Nicholasfc994162019-06-06 10:04:27 -0400186std::unique_ptr<Block> IRGenerator::convertBlock(const ASTNode& block) {
187 SkASSERT(block.fKind == ASTNode::Kind::kBlock);
ethannicholasb3058bd2016-07-01 08:22:01 -0700188 AutoSymbolTable table(this);
John Stiles8f2a0cf2020-10-13 12:48:21 -0400189 StatementArray statements;
Ethan Nicholasfc994162019-06-06 10:04:27 -0400190 for (const auto& child : block) {
191 std::unique_ptr<Statement> statement = this->convertStatement(child);
ethannicholasb3058bd2016-07-01 08:22:01 -0700192 if (!statement) {
193 return nullptr;
194 }
195 statements.push_back(std::move(statement));
196 }
John Stilesbf16b6c2021-03-12 19:24:31 -0500197 return Block::Make(block.fOffset, std::move(statements), fSymbolTable);
ethannicholasb3058bd2016-07-01 08:22:01 -0700198}
199
Ethan Nicholasfc994162019-06-06 10:04:27 -0400200std::unique_ptr<Statement> IRGenerator::convertVarDeclarationStatement(const ASTNode& s) {
201 SkASSERT(s.fKind == ASTNode::Kind::kVarDeclarations);
Ethan Nicholas453f67f2020-10-09 10:43:45 -0400202 auto decls = this->convertVarDeclarations(s, Variable::Storage::kLocal);
Brian Osmanc0213602020-10-06 14:43:32 -0400203 if (decls.empty()) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700204 return nullptr;
205 }
John Stilesbf16b6c2021-03-12 19:24:31 -0500206 return Block::MakeUnscoped(s.fOffset, std::move(decls));
ethannicholasb3058bd2016-07-01 08:22:01 -0700207}
208
John Stiles80b02af2021-02-12 17:07:51 -0500209int IRGenerator::convertArraySize(const Type& type, int offset, const ASTNode& s) {
Brian Osman4cf85072021-01-14 14:18:10 -0500210 if (!s) {
211 this->errorReporter().error(offset, "array must have a size");
212 return 0;
213 }
Ethan Nicholas489e5522021-01-20 10:53:11 -0500214 auto size = this->convertExpression(s);
215 if (!size) {
216 return 0;
217 }
John Stiles7253a202021-08-23 09:24:33 -0400218 return type.convertArraySize(fContext, std::move(size));
Brian Osman4cf85072021-01-14 14:18:10 -0500219}
220
Ethan Nicholas489e5522021-01-20 10:53:11 -0500221void IRGenerator::checkVarDeclaration(int offset, const Modifiers& modifiers, const Type* baseType,
222 Variable::Storage storage) {
John Stilese6095982021-02-04 12:42:01 -0500223 if (this->strictES2Mode() && baseType->isArray()) {
224 this->errorReporter().error(offset, "array size must appear after variable name");
225 }
226
John Stiles3624aba2020-12-22 16:29:53 -0500227 if (baseType->componentType().isOpaque() && storage != Variable::Storage::kGlobal) {
John Stilesb30151e2021-01-11 16:13:08 -0500228 this->errorReporter().error(
Ethan Nicholas489e5522021-01-20 10:53:11 -0500229 offset,
John Stilesb30151e2021-01-11 16:13:08 -0500230 "variables of type '" + baseType->displayName() + "' must be global");
Brian Osman82329002020-07-21 09:39:27 -0400231 }
Brian Osman8c264792021-07-01 16:41:27 -0400232 if ((modifiers.fFlags & Modifiers::kIn_Flag) && baseType->isMatrix()) {
233 this->errorReporter().error(offset, "'in' variables may not have matrix type");
234 }
235 if ((modifiers.fFlags & Modifiers::kIn_Flag) && (modifiers.fFlags & Modifiers::kUniform_Flag)) {
236 this->errorReporter().error(offset, "'in uniform' variables not permitted");
Brian Osman2fe83fe2019-12-16 13:17:59 -0500237 }
John Stilesbb2ef922021-07-26 08:32:07 -0400238 if (this->isRuntimeEffect()) {
Brian Osman5c625822021-04-06 14:28:07 -0400239 if (modifiers.fFlags & Modifiers::kIn_Flag) {
Brian Osman39675882021-03-31 14:37:10 -0400240 this->errorReporter().error(offset, "'in' variables not permitted in runtime effects");
Brian Osmana4b91692020-08-10 14:26:16 -0400241 }
242 }
Brian Osman5c625822021-04-06 14:28:07 -0400243 if (baseType->isEffectChild() && !(modifiers.fFlags & Modifiers::kUniform_Flag)) {
244 this->errorReporter().error(
245 offset, "variables of type '" + baseType->displayName() + "' must be uniform");
246 }
Brian Osmanb32d66b2020-04-30 17:12:03 -0400247 if (modifiers.fLayout.fFlags & Layout::kSRGBUnpremul_Flag) {
John Stilesbb2ef922021-07-26 08:32:07 -0400248 if (!this->isRuntimeEffect()) {
Ethan Nicholas489e5522021-01-20 10:53:11 -0500249 this->errorReporter().error(offset,
John Stilesb30151e2021-01-11 16:13:08 -0500250 "'srgb_unpremul' is only permitted in runtime effects");
Brian Osmanb32d66b2020-04-30 17:12:03 -0400251 }
252 if (!(modifiers.fFlags & Modifiers::kUniform_Flag)) {
Ethan Nicholas489e5522021-01-20 10:53:11 -0500253 this->errorReporter().error(offset,
John Stilesb30151e2021-01-11 16:13:08 -0500254 "'srgb_unpremul' is only permitted on 'uniform' variables");
Brian Osmanb32d66b2020-04-30 17:12:03 -0400255 }
256 auto validColorXformType = [](const Type& t) {
John Stiles9aeed132020-11-24 17:36:06 -0500257 return t.isVector() && t.componentType().isFloat() &&
Brian Osmanb32d66b2020-04-30 17:12:03 -0400258 (t.columns() == 3 || t.columns() == 4);
259 };
John Stilesc0c51062020-12-03 17:16:29 -0500260 if (!validColorXformType(*baseType) && !(baseType->isArray() &&
Brian Osmanb32d66b2020-04-30 17:12:03 -0400261 validColorXformType(baseType->componentType()))) {
Ethan Nicholas489e5522021-01-20 10:53:11 -0500262 this->errorReporter().error(offset,
John Stilesb30151e2021-01-11 16:13:08 -0500263 "'srgb_unpremul' is only permitted on half3, half4, "
264 "float3, or float4 variables");
Brian Osmanb32d66b2020-04-30 17:12:03 -0400265 }
266 }
John Stilesb806da42021-08-04 16:26:47 -0400267 int permitted = Modifiers::kConst_Flag | Modifiers::kHighp_Flag | Modifiers::kMediump_Flag |
268 Modifiers::kLowp_Flag;
Ethan Nicholas453f67f2020-10-09 10:43:45 -0400269 if (storage == Variable::Storage::kGlobal) {
Brian Osman9ca38ff2021-02-18 12:58:54 -0500270 permitted |= Modifiers::kIn_Flag | Modifiers::kOut_Flag | Modifiers::kUniform_Flag |
Brian Osmane49703f2021-04-19 11:15:24 -0400271 Modifiers::kFlat_Flag | Modifiers::kNoPerspective_Flag;
Ethan Nicholas63d7ee32020-08-17 10:57:12 -0400272 }
Brian Osmana654faa2021-02-26 11:52:59 -0500273 // TODO(skbug.com/11301): Migrate above checks into building a mask of permitted layout flags
Ethan Nicholas371f6e12021-05-04 14:30:02 -0400274 CheckModifiers(fContext, offset, modifiers, permitted, /*permittedLayoutFlags=*/~0);
Ethan Nicholas489e5522021-01-20 10:53:11 -0500275}
276
Ethan Nicholasbd974002021-02-22 16:20:06 -0500277std::unique_ptr<Variable> IRGenerator::convertVar(int offset, const Modifiers& modifiers,
Ethan Nicholas962dec42021-06-10 13:06:39 -0400278 const Type* baseType, skstd::string_view name,
Ethan Nicholasbd974002021-02-22 16:20:06 -0500279 bool isArray,
280 std::unique_ptr<Expression> arraySize,
281 Variable::Storage storage) {
Ethan Nicholas489e5522021-01-20 10:53:11 -0500282 if (modifiers.fLayout.fLocation == 0 && modifiers.fLayout.fIndex == 0 &&
John Stilesd1204642021-02-17 16:30:02 -0500283 (modifiers.fFlags & Modifiers::kOut_Flag) &&
John Stilese67bd132021-03-19 18:39:25 -0400284 this->programKind() == ProgramKind::kFragment && name != Compiler::FRAGCOLOR_NAME) {
Ethan Nicholas489e5522021-01-20 10:53:11 -0500285 this->errorReporter().error(offset,
286 "out location=0, index=0 is reserved for sk_FragColor");
287 }
288 const Type* type = baseType;
289 int arraySizeValue = 0;
290 if (isArray) {
Ethan Nicholas489e5522021-01-20 10:53:11 -0500291 SkASSERT(arraySize);
John Stiles7253a202021-08-23 09:24:33 -0400292 arraySizeValue = type->convertArraySize(fContext, std::move(arraySize));
John Stiles80b02af2021-02-12 17:07:51 -0500293 if (!arraySizeValue) {
294 return {};
295 }
Ethan Nicholas489e5522021-01-20 10:53:11 -0500296 type = fSymbolTable->addArrayDimension(type, arraySizeValue);
297 }
John Stilesf2872e62021-05-04 11:38:43 -0400298 return std::make_unique<Variable>(offset, this->modifiersPool().add(modifiers), name,
299 type, fIsBuiltinCode, storage);
Ethan Nicholasbd974002021-02-22 16:20:06 -0500300}
301
302std::unique_ptr<Statement> IRGenerator::convertVarDeclaration(std::unique_ptr<Variable> var,
Ethan Nicholasdd2fdea2021-07-20 15:23:04 -0400303 std::unique_ptr<Expression> value,
304 bool addToSymbolTable) {
John Stilese67bd132021-03-19 18:39:25 -0400305 std::unique_ptr<Statement> varDecl = VarDeclaration::Convert(fContext, var.get(),
306 std::move(value));
307 if (!varDecl) {
308 return nullptr;
309 }
310
311 // Detect the declaration of magical variables.
312 if ((var->storage() == Variable::Storage::kGlobal) && var->name() == Compiler::FRAGCOLOR_NAME) {
313 // Silently ignore duplicate definitions of `sk_FragColor`.
314 const Symbol* symbol = (*fSymbolTable)[var->name()];
315 if (symbol) {
Brian Osman7b361492021-02-25 11:25:30 -0500316 return nullptr;
317 }
John Stilese67bd132021-03-19 18:39:25 -0400318 } else if ((var->storage() == Variable::Storage::kGlobal ||
319 var->storage() == Variable::Storage::kInterfaceBlock) &&
320 var->name() == Compiler::RTADJUST_NAME) {
321 // `sk_RTAdjust` is special, and makes the IR generator emit position-fixup expressions.
322 if (fRTAdjust) {
323 this->errorReporter().error(var->fOffset, "duplicate definition of 'sk_RTAdjust'");
Brian Osman7b361492021-02-25 11:25:30 -0500324 return nullptr;
325 }
John Stilese67bd132021-03-19 18:39:25 -0400326 if (var->type() != *fContext.fTypes.fFloat4) {
327 this->errorReporter().error(var->fOffset, "sk_RTAdjust must have type 'float4'");
Brian Osmanfc4b9912021-03-05 16:45:06 -0500328 return nullptr;
329 }
Ethan Nicholas489e5522021-01-20 10:53:11 -0500330 fRTAdjust = var.get();
331 }
John Stilese67bd132021-03-19 18:39:25 -0400332
Ethan Nicholasdd2fdea2021-07-20 15:23:04 -0400333 if (addToSymbolTable) {
334 fSymbolTable->add(std::move(var));
335 } else {
336 fSymbolTable->takeOwnershipOfSymbol(std::move(var));
337 }
John Stilese67bd132021-03-19 18:39:25 -0400338 return varDecl;
Ethan Nicholasbd974002021-02-22 16:20:06 -0500339}
340
341std::unique_ptr<Statement> IRGenerator::convertVarDeclaration(int offset,
342 const Modifiers& modifiers,
343 const Type* baseType,
Ethan Nicholas962dec42021-06-10 13:06:39 -0400344 skstd::string_view name,
Ethan Nicholasbd974002021-02-22 16:20:06 -0500345 bool isArray,
346 std::unique_ptr<Expression> arraySize,
347 std::unique_ptr<Expression> value,
348 Variable::Storage storage) {
349 std::unique_ptr<Variable> var = this->convertVar(offset, modifiers, baseType, name, isArray,
350 std::move(arraySize), storage);
351 if (!var) {
352 return nullptr;
353 }
354 return this->convertVarDeclaration(std::move(var), std::move(value));
Ethan Nicholas489e5522021-01-20 10:53:11 -0500355}
356
357StatementArray IRGenerator::convertVarDeclarations(const ASTNode& decls,
358 Variable::Storage storage) {
359 SkASSERT(decls.fKind == ASTNode::Kind::kVarDeclarations);
360 auto declarationsIter = decls.begin();
361 const Modifiers& modifiers = declarationsIter++->getModifiers();
362 const ASTNode& rawType = *(declarationsIter++);
363 const Type* baseType = this->convertType(rawType);
364 if (!baseType) {
365 return {};
366 }
John Stilesb806da42021-08-04 16:26:47 -0400367 baseType = baseType->applyPrecisionQualifiers(fContext, modifiers, fSymbolTable.get(),
368 decls.fOffset);
369 if (!baseType) {
370 return {};
371 }
Ethan Nicholas489e5522021-01-20 10:53:11 -0500372
373 this->checkVarDeclaration(decls.fOffset, modifiers, baseType, storage);
John Stiles8f2a0cf2020-10-13 12:48:21 -0400374
375 StatementArray varDecls;
John Stilesf621e232020-08-25 13:33:02 -0400376 for (; declarationsIter != decls.end(); ++declarationsIter) {
377 const ASTNode& varDecl = *declarationsIter;
Ethan Nicholasfc994162019-06-06 10:04:27 -0400378 const ASTNode::VarData& varData = varDecl.getVarData();
Ethan Nicholas489e5522021-01-20 10:53:11 -0500379 std::unique_ptr<Expression> arraySize;
380 std::unique_ptr<Expression> value;
Ethan Nicholasfc994162019-06-06 10:04:27 -0400381 auto iter = varDecl.begin();
Ethan Nicholas489e5522021-01-20 10:53:11 -0500382 if (iter != varDecl.end() && varData.fIsArray) {
John Stiles8f633ef2021-08-21 17:13:11 -0400383 if (!*iter) {
Ethan Nicholas489e5522021-01-20 10:53:11 -0500384 this->errorReporter().error(decls.fOffset, "array must have a size");
John Stilesfabed8b2021-03-29 09:38:59 -0400385 continue;
ethannicholasb3058bd2016-07-01 08:22:01 -0700386 }
John Stiles8f633ef2021-08-21 17:13:11 -0400387 arraySize = this->convertExpression(*iter++);
388 if (!arraySize) {
389 continue;
390 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700391 }
Brian Osman4cf85072021-01-14 14:18:10 -0500392 if (iter != varDecl.end()) {
Ethan Nicholasfc994162019-06-06 10:04:27 -0400393 value = this->convertExpression(*iter);
ethannicholasb3058bd2016-07-01 08:22:01 -0700394 if (!value) {
John Stilesfabed8b2021-03-29 09:38:59 -0400395 continue;
ethannicholasb3058bd2016-07-01 08:22:01 -0700396 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700397 }
Ethan Nicholas489e5522021-01-20 10:53:11 -0500398 std::unique_ptr<Statement> varDeclStmt = this->convertVarDeclaration(varDecl.fOffset,
399 modifiers,
400 baseType,
401 varData.fName,
402 varData.fIsArray,
403 std::move(arraySize),
404 std::move(value),
405 storage);
406 if (varDeclStmt) {
407 varDecls.push_back(std::move(varDeclStmt));
ethannicholasf789b382016-08-03 12:43:36 -0700408 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700409 }
Brian Osmanc0213602020-10-06 14:43:32 -0400410 return varDecls;
ethannicholasb3058bd2016-07-01 08:22:01 -0700411}
412
Ethan Nicholasfc994162019-06-06 10:04:27 -0400413std::unique_ptr<ModifiersDeclaration> IRGenerator::convertModifiersDeclaration(const ASTNode& m) {
John Stilesd1204642021-02-17 16:30:02 -0500414 if (this->programKind() != ProgramKind::kFragment &&
415 this->programKind() != ProgramKind::kVertex &&
416 this->programKind() != ProgramKind::kGeometry) {
John Stilesb30151e2021-01-11 16:13:08 -0500417 this->errorReporter().error(m.fOffset, "layout qualifiers are not allowed here");
Brian Osman16f376f2020-09-02 12:30:59 -0400418 return nullptr;
419 }
420
Ethan Nicholasfc994162019-06-06 10:04:27 -0400421 SkASSERT(m.fKind == ASTNode::Kind::kModifiers);
422 Modifiers modifiers = m.getModifiers();
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -0400423 if (modifiers.fLayout.fInvocations != -1) {
John Stilesd1204642021-02-17 16:30:02 -0500424 if (this->programKind() != ProgramKind::kGeometry) {
John Stilesb30151e2021-01-11 16:13:08 -0500425 this->errorReporter().error(m.fOffset,
426 "'invocations' is only legal in geometry shaders");
Ethan Nicholasf06576b2019-04-03 15:45:25 -0400427 return nullptr;
428 }
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -0400429 fInvocations = modifiers.fLayout.fInvocations;
John Stilesc1a98b82021-02-24 13:35:02 -0500430 if (!this->caps().gsInvocationsSupport()) {
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -0400431 modifiers.fLayout.fInvocations = -1;
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -0400432 if (modifiers.fLayout.description() == "") {
433 return nullptr;
434 }
435 }
436 }
John Stilesc1a98b82021-02-24 13:35:02 -0500437 if (modifiers.fLayout.fMaxVertices != -1 && fInvocations > 0 &&
438 !this->caps().gsInvocationsSupport()) {
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -0400439 modifiers.fLayout.fMaxVertices *= fInvocations;
440 }
John Stilesf2872e62021-05-04 11:38:43 -0400441 return std::make_unique<ModifiersDeclaration>(this->modifiersPool().add(modifiers));
ethannicholas5961bc92016-10-12 06:39:56 -0700442}
443
John Stilesad2319f2020-09-02 15:01:47 -0400444std::unique_ptr<Statement> IRGenerator::convertIf(const ASTNode& n) {
445 SkASSERT(n.fKind == ASTNode::Kind::kIf);
446 auto iter = n.begin();
Ethan Nicholasd6b6f3e2021-01-22 15:18:25 -0500447 std::unique_ptr<Expression> test = this->convertExpression(*(iter++));
John Stilesad2319f2020-09-02 15:01:47 -0400448 if (!test) {
449 return nullptr;
450 }
451 std::unique_ptr<Statement> ifTrue = this->convertStatement(*(iter++));
452 if (!ifTrue) {
453 return nullptr;
454 }
John Stilescf3059e2021-02-25 14:27:02 -0500455 if (this->detectVarDeclarationWithoutScope(*ifTrue)) {
456 return nullptr;
457 }
John Stilesad2319f2020-09-02 15:01:47 -0400458 std::unique_ptr<Statement> ifFalse;
459 if (iter != n.end()) {
460 ifFalse = this->convertStatement(*(iter++));
461 if (!ifFalse) {
462 return nullptr;
463 }
John Stilescf3059e2021-02-25 14:27:02 -0500464 if (this->detectVarDeclarationWithoutScope(*ifFalse)) {
465 return nullptr;
466 }
John Stilesad2319f2020-09-02 15:01:47 -0400467 }
John Stiles5ede6e32021-01-11 13:00:49 -0500468 bool isStatic = n.getBool();
John Stiles23521a82021-03-02 17:02:51 -0500469 return IfStatement::Convert(fContext, n.fOffset, isStatic, std::move(test),
470 std::move(ifTrue), std::move(ifFalse));
John Stilesad2319f2020-09-02 15:01:47 -0400471}
472
Ethan Nicholasfc994162019-06-06 10:04:27 -0400473std::unique_ptr<Statement> IRGenerator::convertFor(const ASTNode& f) {
474 SkASSERT(f.fKind == ASTNode::Kind::kFor);
ethannicholasb3058bd2016-07-01 08:22:01 -0700475 AutoSymbolTable table(this);
ethannicholas22f939e2016-10-13 13:25:34 -0700476 std::unique_ptr<Statement> initializer;
Ethan Nicholasfc994162019-06-06 10:04:27 -0400477 auto iter = f.begin();
478 if (*iter) {
479 initializer = this->convertStatement(*iter);
ethannicholas22f939e2016-10-13 13:25:34 -0700480 if (!initializer) {
481 return nullptr;
482 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700483 }
Ethan Nicholasfc994162019-06-06 10:04:27 -0400484 ++iter;
ethannicholas22f939e2016-10-13 13:25:34 -0700485 std::unique_ptr<Expression> test;
Ethan Nicholasfc994162019-06-06 10:04:27 -0400486 if (*iter) {
Ethan Nicholas2ed0d942021-01-20 07:51:23 -0500487 test = this->convertExpression(*iter);
ethannicholas22f939e2016-10-13 13:25:34 -0700488 if (!test) {
489 return nullptr;
490 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700491 }
Ethan Nicholasfc994162019-06-06 10:04:27 -0400492 ++iter;
ethannicholas22f939e2016-10-13 13:25:34 -0700493 std::unique_ptr<Expression> next;
Ethan Nicholasfc994162019-06-06 10:04:27 -0400494 if (*iter) {
495 next = this->convertExpression(*iter);
ethannicholas22f939e2016-10-13 13:25:34 -0700496 if (!next) {
497 return nullptr;
498 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700499 }
Ethan Nicholasfc994162019-06-06 10:04:27 -0400500 ++iter;
501 std::unique_ptr<Statement> statement = this->convertStatement(*iter);
ethannicholasb3058bd2016-07-01 08:22:01 -0700502 if (!statement) {
503 return nullptr;
504 }
John Stiles2b6ec982021-03-04 10:46:39 -0500505 if (this->detectVarDeclarationWithoutScope(*statement)) {
506 return nullptr;
507 }
Brian Osman77ba8102021-01-12 17:15:30 -0500508
John Stiles23521a82021-03-02 17:02:51 -0500509 return ForStatement::Convert(fContext, f.fOffset, std::move(initializer), std::move(test),
510 std::move(next), std::move(statement), fSymbolTable);
Ethan Nicholas9ead3df2021-01-06 12:10:48 -0500511}
512
513std::unique_ptr<Statement> IRGenerator::convertWhile(const ASTNode& w) {
514 SkASSERT(w.fKind == ASTNode::Kind::kWhile);
Ethan Nicholasfc994162019-06-06 10:04:27 -0400515 auto iter = w.begin();
Ethan Nicholas9ead3df2021-01-06 12:10:48 -0500516 std::unique_ptr<Expression> test = this->convertExpression(*(iter++));
ethannicholasb3058bd2016-07-01 08:22:01 -0700517 if (!test) {
518 return nullptr;
519 }
Ethan Nicholasfc994162019-06-06 10:04:27 -0400520 std::unique_ptr<Statement> statement = this->convertStatement(*(iter++));
ethannicholasb3058bd2016-07-01 08:22:01 -0700521 if (!statement) {
522 return nullptr;
523 }
John Stilesb321a072021-02-25 16:24:19 -0500524 if (this->detectVarDeclarationWithoutScope(*statement)) {
525 return nullptr;
526 }
John Stiles23521a82021-03-02 17:02:51 -0500527 return ForStatement::ConvertWhile(fContext, w.fOffset, std::move(test), std::move(statement),
528 fSymbolTable);
ethannicholasb3058bd2016-07-01 08:22:01 -0700529}
530
Ethan Nicholas2ed0d942021-01-20 07:51:23 -0500531std::unique_ptr<Statement> IRGenerator::convertDo(const ASTNode& d) {
532 SkASSERT(d.fKind == ASTNode::Kind::kDo);
Ethan Nicholasfc994162019-06-06 10:04:27 -0400533 auto iter = d.begin();
534 std::unique_ptr<Statement> statement = this->convertStatement(*(iter++));
535 if (!statement) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700536 return nullptr;
537 }
Ethan Nicholas2ed0d942021-01-20 07:51:23 -0500538 std::unique_ptr<Expression> test = this->convertExpression(*(iter++));
Ethan Nicholasfc994162019-06-06 10:04:27 -0400539 if (!test) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700540 return nullptr;
541 }
John Stilesea5822e2021-02-26 11:18:20 -0500542 if (this->detectVarDeclarationWithoutScope(*statement)) {
543 return nullptr;
544 }
John Stiles23521a82021-03-02 17:02:51 -0500545 return DoStatement::Convert(fContext, std::move(statement), std::move(test));
ethannicholasb3058bd2016-07-01 08:22:01 -0700546}
547
Ethan Nicholascfefec02021-02-09 15:22:57 -0500548std::unique_ptr<Statement> IRGenerator::convertSwitch(const ASTNode& s) {
549 SkASSERT(s.fKind == ASTNode::Kind::kSwitch);
550
551 auto iter = s.begin();
552 std::unique_ptr<Expression> value = this->convertExpression(*(iter++));
553 if (!value) {
554 return nullptr;
555 }
556 AutoSymbolTable table(this);
557 ExpressionArray caseValues;
John Stilesc3ce43b2021-03-09 15:37:01 -0500558 StatementArray caseStatements;
Ethan Nicholascfefec02021-02-09 15:22:57 -0500559 for (; iter != s.end(); ++iter) {
560 const ASTNode& c = *iter;
561 SkASSERT(c.fKind == ASTNode::Kind::kSwitchCase);
562 std::unique_ptr<Expression>& caseValue = caseValues.emplace_back();
563 auto childIter = c.begin();
564 if (*childIter) {
565 caseValue = this->convertExpression(*childIter);
566 if (!caseValue) {
567 return nullptr;
568 }
Ethan Nicholasaf197692017-02-27 13:26:45 -0500569 }
Ethan Nicholasfc994162019-06-06 10:04:27 -0400570 ++childIter;
John Stilesc3ce43b2021-03-09 15:37:01 -0500571
John Stilesbf16b6c2021-03-12 19:24:31 -0500572 StatementArray statements;
Ethan Nicholasfc994162019-06-06 10:04:27 -0400573 for (; childIter != c.end(); ++childIter) {
574 std::unique_ptr<Statement> converted = this->convertStatement(*childIter);
Ethan Nicholasaf197692017-02-27 13:26:45 -0500575 if (!converted) {
576 return nullptr;
577 }
578 statements.push_back(std::move(converted));
579 }
John Stilesbf16b6c2021-03-12 19:24:31 -0500580
581 caseStatements.push_back(Block::MakeUnscoped(c.fOffset, std::move(statements)));
Ethan Nicholasaf197692017-02-27 13:26:45 -0500582 }
John Stiles23521a82021-03-02 17:02:51 -0500583 return SwitchStatement::Convert(fContext, s.fOffset, s.getBool(), std::move(value),
584 std::move(caseValues), std::move(caseStatements), fSymbolTable);
Ethan Nicholasaf197692017-02-27 13:26:45 -0500585}
586
Ethan Nicholasfc994162019-06-06 10:04:27 -0400587std::unique_ptr<Statement> IRGenerator::convertExpressionStatement(const ASTNode& s) {
588 std::unique_ptr<Expression> e = this->convertExpression(s);
ethannicholasb3058bd2016-07-01 08:22:01 -0700589 if (!e) {
590 return nullptr;
591 }
John Stiles3e5871c2021-02-25 20:52:03 -0500592 return ExpressionStatement::Make(fContext, std::move(e));
ethannicholasb3058bd2016-07-01 08:22:01 -0700593}
594
Ethan Nicholas1ff76092021-01-28 10:02:43 -0500595std::unique_ptr<Statement> IRGenerator::convertReturn(int offset,
596 std::unique_ptr<Expression> result) {
John Stilesa0c04d62021-03-11 23:07:24 -0500597 return ReturnStatement::Make(offset, std::move(result));
Ethan Nicholas1ff76092021-01-28 10:02:43 -0500598}
599
600std::unique_ptr<Statement> IRGenerator::convertReturn(const ASTNode& r) {
601 SkASSERT(r.fKind == ASTNode::Kind::kReturn);
602 if (r.begin() != r.end()) {
603 std::unique_ptr<Expression> value = this->convertExpression(*r.begin());
604 if (!value) {
605 return nullptr;
606 }
607 return this->convertReturn(r.fOffset, std::move(value));
608 } else {
609 return this->convertReturn(r.fOffset, /*result=*/nullptr);
ethannicholasb3058bd2016-07-01 08:22:01 -0700610 }
611}
612
Ethan Nicholasfc994162019-06-06 10:04:27 -0400613std::unique_ptr<Statement> IRGenerator::convertBreak(const ASTNode& b) {
614 SkASSERT(b.fKind == ASTNode::Kind::kBreak);
John Stilesa0c04d62021-03-11 23:07:24 -0500615 return BreakStatement::Make(b.fOffset);
ethannicholasb3058bd2016-07-01 08:22:01 -0700616}
617
Ethan Nicholasfc994162019-06-06 10:04:27 -0400618std::unique_ptr<Statement> IRGenerator::convertContinue(const ASTNode& c) {
619 SkASSERT(c.fKind == ASTNode::Kind::kContinue);
John Stilesa0c04d62021-03-11 23:07:24 -0500620 return ContinueStatement::Make(c.fOffset);
ethannicholasb3058bd2016-07-01 08:22:01 -0700621}
622
Ethan Nicholasfc994162019-06-06 10:04:27 -0400623std::unique_ptr<Statement> IRGenerator::convertDiscard(const ASTNode& d) {
624 SkASSERT(d.fKind == ASTNode::Kind::kDiscard);
Brian Osman8c264792021-07-01 16:41:27 -0400625 if (this->programKind() != ProgramKind::kFragment) {
John Stilesb30151e2021-01-11 16:13:08 -0500626 this->errorReporter().error(d.fOffset,
627 "discard statement is only permitted in fragment shaders");
Brian Osmanf2876b02020-12-15 15:40:32 -0500628 return nullptr;
629 }
John Stilesa0c04d62021-03-11 23:07:24 -0500630 return DiscardStatement::Make(d.fOffset);
ethannicholasb3058bd2016-07-01 08:22:01 -0700631}
632
Ethan Nicholasaae47c82017-11-10 15:34:03 -0500633std::unique_ptr<Block> IRGenerator::applyInvocationIDWorkaround(std::unique_ptr<Block> main) {
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -0400634 Layout invokeLayout;
635 Modifiers invokeModifiers(invokeLayout, Modifiers::kHasSideEffects_Flag);
John Stiles586df952020-11-12 18:27:13 -0500636 const FunctionDeclaration* invokeDecl = fSymbolTable->add(std::make_unique<FunctionDeclaration>(
637 /*offset=*/-1,
John Stilesf2872e62021-05-04 11:38:43 -0400638 this->modifiersPool().add(invokeModifiers),
John Stiles586df952020-11-12 18:27:13 -0500639 "_invoke",
640 std::vector<const Variable*>(),
John Stiles54e7c052021-01-11 14:22:36 -0500641 fContext.fTypes.fVoid.get(),
John Stiles586df952020-11-12 18:27:13 -0500642 fIsBuiltinCode));
John Stiles842ee5b2021-08-27 12:37:27 -0400643 IntrinsicSet referencedIntrinsics;
644 main = this->finalizeFunction(*invokeDecl, std::move(main), &referencedIntrinsics);
645 auto invokeDef = std::make_unique<FunctionDefinition>(/*offset=*/-1, invokeDecl,
646 fIsBuiltinCode, std::move(main),
647 std::move(referencedIntrinsics));
John Stiles0d07e142020-12-30 18:03:09 -0500648 invokeDecl->setDefinition(invokeDef.get());
649 fProgramElements->push_back(std::move(invokeDef));
Ethan Nicholasbe65cd52021-05-18 12:09:01 -0400650
651 using namespace SkSL::dsl;
Ethan Nicholasa2d22b22021-07-15 10:35:54 -0400652 DSLGlobalVar loopIdx("sk_InvocationID");
Ethan Nicholasbe65cd52021-05-18 12:09:01 -0400653 std::unique_ptr<Expression> endPrimitive = this->convertIdentifier(/*offset=*/-1,
654 "EndPrimitive");
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400655 SkASSERT(endPrimitive);
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -0400656
Ethan Nicholasbe65cd52021-05-18 12:09:01 -0400657 std::unique_ptr<Statement> block = DSLBlock(
658 For(loopIdx = 0, loopIdx < fInvocations, loopIdx++, DSLBlock(
659 DSLFunction(invokeDecl)(),
660 DSLExpression(std::move(endPrimitive))({})
661 ))
662 ).release();
663 return std::unique_ptr<Block>(&block.release()->as<Block>());
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -0400664}
665
Robert Phillipsfe8da172018-01-24 14:52:02 +0000666std::unique_ptr<Statement> IRGenerator::getNormalizeSkPositionCode() {
John Stilesd45ebbc2021-05-18 16:54:36 -0400667 using namespace SkSL::dsl;
668 using SkSL::dsl::Swizzle; // disambiguate from SkSL::Swizzle
669
Brian Osman88cda172020-10-09 12:05:16 -0400670 const Variable* skPerVertex = nullptr;
671 if (const ProgramElement* perVertexDecl = fIntrinsics->find(Compiler::PERVERTEX_NAME)) {
Ethan Nicholase6ed3c22021-07-08 10:38:43 -0400672 SkASSERT(perVertexDecl->is<SkSL::InterfaceBlock>());
673 skPerVertex = &perVertexDecl->as<SkSL::InterfaceBlock>().variable();
Brian Osman88cda172020-10-09 12:05:16 -0400674 }
675
Brian Osman88cda172020-10-09 12:05:16 -0400676 SkASSERT(skPerVertex && fRTAdjust);
John Stiles5acf6a82020-11-10 22:38:01 -0500677 auto Ref = [](const Variable* var) -> std::unique_ptr<Expression> {
John Stilesd45ebbc2021-05-18 16:54:36 -0400678 return VariableReference::Make(/*offset=*/-1, var);
John Stiles5acf6a82020-11-10 22:38:01 -0500679 };
680 auto Field = [&](const Variable* var, int idx) -> std::unique_ptr<Expression> {
John Stiles06d600f2021-03-08 09:18:21 -0500681 return FieldAccess::Make(fContext, Ref(var), idx,
682 FieldAccess::OwnerKind::kAnonymousInterfaceBlock);
John Stiles5acf6a82020-11-10 22:38:01 -0500683 };
John Stilesd45ebbc2021-05-18 16:54:36 -0400684 auto Pos = [&]() -> DSLExpression {
685 return DSLExpression(FieldAccess::Make(fContext, Ref(skPerVertex), /*fieldIndex=*/0,
686 FieldAccess::OwnerKind::kAnonymousInterfaceBlock));
John Stiles5acf6a82020-11-10 22:38:01 -0500687 };
John Stilesd45ebbc2021-05-18 16:54:36 -0400688 auto Adjust = [&]() -> DSLExpression {
689 return DSLExpression(fRTAdjustInterfaceBlock
690 ? Field(fRTAdjustInterfaceBlock, fRTAdjustFieldIndex)
691 : Ref(fRTAdjust));
John Stiles5acf6a82020-11-10 22:38:01 -0500692 };
John Stiles750109b2020-10-30 13:45:46 -0400693
John Stilesd45ebbc2021-05-18 16:54:36 -0400694 return DSLStatement(
695 Pos() = Float4(Swizzle(Pos(), X, Y) * Swizzle(Adjust(), X, Z) +
696 Swizzle(Pos(), W, W) * Swizzle(Adjust(), Y, W),
697 0,
698 Pos().w())
699 ).release();
Robert Phillipsfe8da172018-01-24 14:52:02 +0000700}
701
Ethan Nicholas371f6e12021-05-04 14:30:02 -0400702void IRGenerator::CheckModifiers(const Context& context,
703 int offset,
Brian Osmana654faa2021-02-26 11:52:59 -0500704 const Modifiers& modifiers,
705 int permittedModifierFlags,
706 int permittedLayoutFlags) {
Brian Osmanb5de6be2021-08-10 15:16:34 -0400707 static constexpr struct { Modifiers::Flag flag; const char* name; } kModifierFlags[] = {
708 { Modifiers::kConst_Flag, "const" },
709 { Modifiers::kIn_Flag, "in" },
710 { Modifiers::kOut_Flag, "out" },
711 { Modifiers::kUniform_Flag, "uniform" },
712 { Modifiers::kFlat_Flag, "flat" },
713 { Modifiers::kNoPerspective_Flag, "noperspective" },
714 { Modifiers::kHasSideEffects_Flag, "sk_has_side_effects" },
715 { Modifiers::kInline_Flag, "inline" },
716 { Modifiers::kNoInline_Flag, "noinline" },
717 { Modifiers::kHighp_Flag, "highp" },
718 { Modifiers::kMediump_Flag, "mediump" },
719 { Modifiers::kLowp_Flag, "lowp" },
John Stilesefde90d2021-08-12 23:06:24 -0400720 { Modifiers::kES3_Flag, "$es3" },
Brian Osmana654faa2021-02-26 11:52:59 -0500721 };
722
Brian Osmanb5de6be2021-08-10 15:16:34 -0400723 int modifierFlags = modifiers.fFlags;
724 for (const auto& f : kModifierFlags) {
725 if (modifierFlags & f.flag) {
726 if (!(permittedModifierFlags & f.flag)) {
Ethan Nicholas39f6da42021-08-23 13:10:07 -0400727 context.fErrors->error(offset, "'" + String(f.name) + "' is not permitted here");
Brian Osmanb5de6be2021-08-10 15:16:34 -0400728 }
729 modifierFlags &= ~f.flag;
730 }
731 }
732 SkASSERT(modifierFlags == 0);
733
734 static constexpr struct { Layout::Flag flag; const char* name; } kLayoutFlags[] = {
735 { Layout::kOriginUpperLeft_Flag, "origin_upper_left"},
736 { Layout::kPushConstant_Flag, "push_constant"},
737 { Layout::kBlendSupportAllEquations_Flag, "blend_support_all_equations"},
738 { Layout::kSRGBUnpremul_Flag, "srgb_unpremul"},
739 { Layout::kLocation_Flag, "location"},
740 { Layout::kOffset_Flag, "offset"},
741 { Layout::kBinding_Flag, "binding"},
742 { Layout::kIndex_Flag, "index"},
743 { Layout::kSet_Flag, "set"},
744 { Layout::kBuiltin_Flag, "builtin"},
745 { Layout::kInputAttachmentIndex_Flag, "input_attachment_index"},
746 { Layout::kPrimitive_Flag, "primitive-type"},
747 { Layout::kMaxVertices_Flag, "max_vertices"},
748 { Layout::kInvocations_Flag, "invocations"},
749 };
Brian Osmana654faa2021-02-26 11:52:59 -0500750
751 int layoutFlags = modifiers.fLayout.fFlags;
Brian Osmanb5de6be2021-08-10 15:16:34 -0400752 for (const auto& lf : kLayoutFlags) {
753 if (layoutFlags & lf.flag) {
754 if (!(permittedLayoutFlags & lf.flag)) {
Ethan Nicholas39f6da42021-08-23 13:10:07 -0400755 context.fErrors->error(
Brian Osmanb5de6be2021-08-10 15:16:34 -0400756 offset, "layout qualifier '" + String(lf.name) + "' is not permitted here");
Brian Osmana654faa2021-02-26 11:52:59 -0500757 }
Brian Osmanb5de6be2021-08-10 15:16:34 -0400758 layoutFlags &= ~lf.flag;
Brian Osmana654faa2021-02-26 11:52:59 -0500759 }
Brian Osmanb5de6be2021-08-10 15:16:34 -0400760 }
Brian Osmana654faa2021-02-26 11:52:59 -0500761 SkASSERT(layoutFlags == 0);
Ethan Nicholas63d7ee32020-08-17 10:57:12 -0400762}
763
Ethan Nicholasebc9fad2021-07-09 15:35:23 -0400764std::unique_ptr<Block> IRGenerator::finalizeFunction(const FunctionDeclaration& funcDecl,
John Stiles842ee5b2021-08-27 12:37:27 -0400765 std::unique_ptr<Block> body,
766 IntrinsicSet* referencedIntrinsics) {
Ethan Nicholasebc9fad2021-07-09 15:35:23 -0400767 bool isMain = funcDecl.isMain();
768 bool needInvocationIDWorkaround = fInvocations != -1 && isMain &&
769 !this->caps().gsInvocationsSupport();
770 if (needInvocationIDWorkaround) {
771 body = this->applyInvocationIDWorkaround(std::move(body));
772 }
773 if (ProgramKind::kVertex == this->programKind() && isMain && fRTAdjust) {
774 body->children().push_back(this->getNormalizeSkPositionCode());
775 }
776
John Stiles8d130842021-08-27 12:42:45 -0400777 FunctionDefinition::FinalizeFunctionBody(fContext, funcDecl, body.get(), referencedIntrinsics);
Ethan Nicholasebc9fad2021-07-09 15:35:23 -0400778 return body;
Ethan Nicholase2c05042021-02-03 10:27:22 -0500779}
780
Ethan Nicholasfc994162019-06-06 10:04:27 -0400781void IRGenerator::convertFunction(const ASTNode& f) {
782 auto iter = f.begin();
Brian Osmand8070392020-09-09 15:50:02 -0400783 const Type* returnType = this->convertType(*(iter++), /*allowVoid=*/true);
John Stilesb9af7232020-08-20 15:57:48 -0400784 if (returnType == nullptr) {
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -0400785 return;
ethannicholasb3058bd2016-07-01 08:22:01 -0700786 }
John Stilesb9af7232020-08-20 15:57:48 -0400787 const ASTNode::FunctionData& funcData = f.getFunctionData();
Ethan Nicholas371f6e12021-05-04 14:30:02 -0400788 std::vector<std::unique_ptr<Variable>> parameters;
789 parameters.reserve(funcData.fParameterCount);
John Stilesb9af7232020-08-20 15:57:48 -0400790 for (size_t i = 0; i < funcData.fParameterCount; ++i) {
Ethan Nicholasfc994162019-06-06 10:04:27 -0400791 const ASTNode& param = *(iter++);
792 SkASSERT(param.fKind == ASTNode::Kind::kParameter);
John Stilesece1bf02021-03-08 11:15:55 -0500793 const ASTNode::ParameterData& pd = param.getParameterData();
Ethan Nicholasfc994162019-06-06 10:04:27 -0400794 auto paramIter = param.begin();
795 const Type* type = this->convertType(*(paramIter++));
ethannicholasb3058bd2016-07-01 08:22:01 -0700796 if (!type) {
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -0400797 return;
ethannicholasb3058bd2016-07-01 08:22:01 -0700798 }
John Stilesd39aec92020-12-03 14:37:16 -0500799 if (pd.fIsArray) {
John Stiles80b02af2021-02-12 17:07:51 -0500800 int arraySize = this->convertArraySize(*type, param.fOffset, *paramIter++);
Brian Osman4cf85072021-01-14 14:18:10 -0500801 if (!arraySize) {
802 return;
803 }
John Stilesa2179502020-12-03 14:37:57 -0500804 type = fSymbolTable->addArrayDimension(type, arraySize);
ethannicholasb3058bd2016-07-01 08:22:01 -0700805 }
Brian Osman8dbdf232020-10-12 14:40:24 -0400806
Ethan Nicholas371f6e12021-05-04 14:30:02 -0400807 parameters.push_back(std::make_unique<Variable>(param.fOffset,
808 this->modifiersPool().add(pd.fModifiers),
809 pd.fName,
810 type,
811 fIsBuiltinCode,
812 Variable::Storage::kParameter));
ethannicholasb3058bd2016-07-01 08:22:01 -0700813 }
814
Ethan Nicholas371f6e12021-05-04 14:30:02 -0400815 // Conservatively assume all user-defined functions have side effects.
816 Modifiers declModifiers = funcData.fModifiers;
817 if (!fIsBuiltinCode) {
818 declModifiers.fFlags |= Modifiers::kHasSideEffects_Flag;
Ethan Nicholas00543112018-07-31 09:44:36 -0400819 }
820
Ethan Nicholas371f6e12021-05-04 14:30:02 -0400821 if (fContext.fConfig->fSettings.fForceNoInline) {
822 // Apply the `noinline` modifier to every function. This allows us to test Runtime
823 // Effects without any inlining, even when the code is later added to a paint.
824 declModifiers.fFlags &= ~Modifiers::kInline_Flag;
825 declModifiers.fFlags |= Modifiers::kNoInline_Flag;
ethannicholasb3058bd2016-07-01 08:22:01 -0700826 }
Ethan Nicholas371f6e12021-05-04 14:30:02 -0400827
828 const FunctionDeclaration* decl = FunctionDeclaration::Convert(
829 fContext,
830 *fSymbolTable,
Ethan Nicholas371f6e12021-05-04 14:30:02 -0400831 f.fOffset,
832 this->modifiersPool().add(declModifiers),
833 funcData.fName,
834 std::move(parameters),
835 returnType,
836 fIsBuiltinCode);
ethannicholasb3058bd2016-07-01 08:22:01 -0700837 if (!decl) {
Ethan Nicholas371f6e12021-05-04 14:30:02 -0400838 return;
ethannicholasb3058bd2016-07-01 08:22:01 -0700839 }
John Stiles569249b2020-11-03 12:18:22 -0500840 if (iter == f.end()) {
841 // If there's no body, we've found a prototype.
842 fProgramElements->push_back(std::make_unique<FunctionPrototype>(f.fOffset, decl,
843 fIsBuiltinCode));
844 } else {
845 // Compile function body.
ethannicholasd598f792016-07-25 10:08:54 -0700846 AutoSymbolTable table(this);
John Stiles569249b2020-11-03 12:18:22 -0500847 for (const Variable* param : decl->parameters()) {
848 fSymbolTable->addWithoutOwnership(param);
ethannicholasb3058bd2016-07-01 08:22:01 -0700849 }
Ethan Nicholasfc994162019-06-06 10:04:27 -0400850 std::unique_ptr<Block> body = this->convertBlock(*iter);
ethannicholasd598f792016-07-25 10:08:54 -0700851 if (!body) {
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -0400852 return;
853 }
John Stiles842ee5b2021-08-27 12:37:27 -0400854 IntrinsicSet referencedIntrinsics;
855 body = this->finalizeFunction(*decl, std::move(body), &referencedIntrinsics);
John Stiles607d36b2020-10-19 15:00:01 -0400856 auto result = std::make_unique<FunctionDefinition>(
John Stiles842ee5b2021-08-27 12:37:27 -0400857 f.fOffset, decl, fIsBuiltinCode, std::move(body), std::move(referencedIntrinsics));
Ethan Nicholased84b732020-10-08 11:45:44 -0400858 decl->setDefinition(result.get());
Ethan Nicholas0a5d0962020-10-14 13:33:18 -0400859 result->setSource(&f);
Ethan Nicholasdb80f692019-11-22 14:06:12 -0500860 fProgramElements->push_back(std::move(result));
ethannicholasb3058bd2016-07-01 08:22:01 -0700861 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700862}
863
John Stilesdc75a972020-11-25 16:24:55 -0500864std::unique_ptr<StructDefinition> IRGenerator::convertStructDefinition(const ASTNode& node) {
865 SkASSERT(node.fKind == ASTNode::Kind::kType);
866
867 const Type* type = this->convertType(node);
868 if (!type) {
869 return nullptr;
870 }
John Stilesc0c51062020-12-03 17:16:29 -0500871 if (!type->isStruct()) {
John Stilesb30151e2021-01-11 16:13:08 -0500872 this->errorReporter().error(node.fOffset,
873 "expected a struct here, found '" + type->name() + "'");
John Stilesdc75a972020-11-25 16:24:55 -0500874 return nullptr;
875 }
Brian Osman02bc5222021-01-28 11:00:20 -0500876 SkDEBUGCODE(auto [iter, wasInserted] =) fDefinedStructs.insert(type);
877 SkASSERT(wasInserted);
John Stilesdc75a972020-11-25 16:24:55 -0500878 return std::make_unique<StructDefinition>(node.fOffset, *type);
879}
880
Ethan Nicholase6ed3c22021-07-08 10:38:43 -0400881std::unique_ptr<SkSL::InterfaceBlock> IRGenerator::convertInterfaceBlock(const ASTNode& intf) {
John Stilesd1204642021-02-17 16:30:02 -0500882 if (this->programKind() != ProgramKind::kFragment &&
883 this->programKind() != ProgramKind::kVertex &&
884 this->programKind() != ProgramKind::kGeometry) {
John Stilesb30151e2021-01-11 16:13:08 -0500885 this->errorReporter().error(intf.fOffset, "interface block is not allowed here");
Brian Osman16f376f2020-09-02 12:30:59 -0400886 return nullptr;
887 }
888
Ethan Nicholasfc994162019-06-06 10:04:27 -0400889 SkASSERT(intf.fKind == ASTNode::Kind::kInterfaceBlock);
John Stilesece1bf02021-03-08 11:15:55 -0500890 const ASTNode::InterfaceBlockData& id = intf.getInterfaceBlockData();
ethannicholasb3058bd2016-07-01 08:22:01 -0700891 std::shared_ptr<SymbolTable> old = fSymbolTable;
John Stiles869cdef2020-10-30 14:24:24 -0400892 std::shared_ptr<SymbolTable> symbols;
ethannicholasb3058bd2016-07-01 08:22:01 -0700893 std::vector<Type::Field> fields;
Robert Phillipsfe8da172018-01-24 14:52:02 +0000894 bool foundRTAdjust = false;
Ethan Nicholasfc994162019-06-06 10:04:27 -0400895 auto iter = intf.begin();
John Stiles869cdef2020-10-30 14:24:24 -0400896 {
897 AutoSymbolTable table(this);
898 symbols = fSymbolTable;
John Stiles869cdef2020-10-30 14:24:24 -0400899 for (size_t i = 0; i < id.fDeclarationCount; ++i) {
900 StatementArray decls = this->convertVarDeclarations(*(iter++),
901 Variable::Storage::kInterfaceBlock);
902 if (decls.empty()) {
903 return nullptr;
Ethan Nicholas0dd30d92017-05-01 16:57:07 -0400904 }
John Stiles869cdef2020-10-30 14:24:24 -0400905 for (const auto& decl : decls) {
906 const VarDeclaration& vd = decl->as<VarDeclaration>();
John Stiles869cdef2020-10-30 14:24:24 -0400907 if (&vd.var() == fRTAdjust) {
908 foundRTAdjust = true;
John Stiles54e7c052021-01-11 14:22:36 -0500909 SkASSERT(vd.var().type() == *fContext.fTypes.fFloat4);
John Stiles869cdef2020-10-30 14:24:24 -0400910 fRTAdjustFieldIndex = fields.size();
911 }
912 fields.push_back(Type::Field(vd.var().modifiers(), vd.var().name(),
913 &vd.var().type()));
Ethan Nicholas0dd30d92017-05-01 16:57:07 -0400914 }
Ethan Nicholas11d53972016-11-28 11:23:23 -0500915 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700916 }
Ethan Nicholasd2e09602021-06-10 11:21:59 -0400917 const Type* type = old->takeOwnershipOfSymbol(Type::MakeStructType(intf.fOffset,
Ethan Nicholas27f06eb2021-07-26 16:39:40 -0400918 id.fTypeName,
John Stilesad2d4942020-12-11 16:55:58 -0500919 fields));
John Stilesd39aec02020-12-03 10:42:26 -0500920 int arraySize = 0;
John Stilesd39aec92020-12-03 14:37:16 -0500921 if (id.fIsArray) {
Ethan Nicholasfc994162019-06-06 10:04:27 -0400922 const ASTNode& size = *(iter++);
Ethan Nicholas50afc172017-02-16 14:49:57 -0500923 if (size) {
Brian Osman4cf85072021-01-14 14:18:10 -0500924 // convertArraySize rejects unsized arrays. This is the one place we allow those, but
925 // we've already checked for that, so this is verifying the other aspects (constant,
926 // positive, not too large).
John Stiles80b02af2021-02-12 17:07:51 -0500927 arraySize = this->convertArraySize(*type, size.fOffset, size);
Brian Osman4cf85072021-01-14 14:18:10 -0500928 if (!arraySize) {
John Stilesd39aec02020-12-03 10:42:26 -0500929 return nullptr;
930 }
Ethan Nicholas50afc172017-02-16 14:49:57 -0500931 } else {
John Stilesd39aec02020-12-03 10:42:26 -0500932 arraySize = Type::kUnsizedArray;
Ethan Nicholas50afc172017-02-16 14:49:57 -0500933 }
John Stilesa2179502020-12-03 14:37:57 -0500934 type = symbols->addArrayDimension(type, arraySize);
Ethan Nicholas50afc172017-02-16 14:49:57 -0500935 }
Brian Osman5bf3e202020-10-13 10:34:18 -0400936 const Variable* var = old->takeOwnershipOfSymbol(
John Stiles3ae071e2020-08-05 15:29:29 -0400937 std::make_unique<Variable>(intf.fOffset,
John Stilesf2872e62021-05-04 11:38:43 -0400938 this->modifiersPool().add(id.fModifiers),
Ethan Nicholasd2e09602021-06-10 11:21:59 -0400939 id.fInstanceName.length() ? id.fInstanceName : id.fTypeName,
Ethan Nicholas30d30222020-09-11 12:27:26 -0400940 type,
Brian Osman3887a012020-09-30 13:22:27 -0400941 fIsBuiltinCode,
Ethan Nicholas453f67f2020-10-09 10:43:45 -0400942 Variable::Storage::kGlobal));
Robert Phillipsfe8da172018-01-24 14:52:02 +0000943 if (foundRTAdjust) {
944 fRTAdjustInterfaceBlock = var;
945 }
Ethan Nicholasd2e09602021-06-10 11:21:59 -0400946 if (id.fInstanceName.length()) {
John Stilesb8cc6652020-10-08 09:12:07 -0400947 old->addWithoutOwnership(var);
ethannicholasb3058bd2016-07-01 08:22:01 -0700948 } else {
949 for (size_t i = 0; i < fields.size(); i++) {
John Stilesb8cc6652020-10-08 09:12:07 -0400950 old->add(std::make_unique<Field>(intf.fOffset, var, (int)i));
ethannicholasb3058bd2016-07-01 08:22:01 -0700951 }
952 }
Ethan Nicholase6ed3c22021-07-08 10:38:43 -0400953 return std::make_unique<SkSL::InterfaceBlock>(intf.fOffset,
954 var,
Ethan Nicholas3533ff12021-08-02 12:53:29 -0400955 id.fTypeName,
956 id.fInstanceName,
Ethan Nicholase6ed3c22021-07-08 10:38:43 -0400957 arraySize,
958 symbols);
ethannicholasb3058bd2016-07-01 08:22:01 -0700959}
960
John Stiles7bd70332020-11-30 17:04:09 -0500961void IRGenerator::convertGlobalVarDeclarations(const ASTNode& decl) {
962 StatementArray decls = this->convertVarDeclarations(decl, Variable::Storage::kGlobal);
963 for (std::unique_ptr<Statement>& stmt : decls) {
Brian Osman02bc5222021-01-28 11:00:20 -0500964 const Type* type = &stmt->as<VarDeclaration>().baseType();
965 if (type->isStruct()) {
966 auto [iter, wasInserted] = fDefinedStructs.insert(type);
967 if (wasInserted) {
968 fProgramElements->push_back(
969 std::make_unique<StructDefinition>(decl.fOffset, *type));
970 }
971 }
Ethan Nicholas624a5292021-04-16 14:54:43 -0400972 fProgramElements->push_back(std::make_unique<GlobalVarDeclaration>(std::move(stmt)));
John Stiles7bd70332020-11-30 17:04:09 -0500973 }
974}
975
John Stiles823c5042021-08-17 12:09:00 -0400976static bool type_contains_private_fields(const Type& type) {
John Stilesb4b627e2020-11-13 15:55:27 -0500977 // Checks for usage of private types, including fields inside a struct.
978 if (type.isPrivate()) {
979 return true;
980 }
John Stilesc0c51062020-12-03 17:16:29 -0500981 if (type.isStruct()) {
John Stilesb4b627e2020-11-13 15:55:27 -0500982 for (const auto& f : type.fields()) {
John Stiles823c5042021-08-17 12:09:00 -0400983 if (type_contains_private_fields(*f.fType)) {
John Stilesb4b627e2020-11-13 15:55:27 -0500984 return true;
985 }
986 }
987 }
988 return false;
989}
990
Brian Osmand8070392020-09-09 15:50:02 -0400991const Type* IRGenerator::convertType(const ASTNode& type, bool allowVoid) {
Ethan Nicholas962dec42021-06-10 13:06:39 -0400992 skstd::string_view name = type.getStringView();
Brian Osman00fea5b2021-01-28 09:46:30 -0500993 const Symbol* symbol = (*fSymbolTable)[name];
John Stiles6bef6a72020-12-02 14:26:04 -0500994 if (!symbol || !symbol->is<Type>()) {
Brian Osman00fea5b2021-01-28 09:46:30 -0500995 this->errorReporter().error(type.fOffset, "unknown type '" + name + "'");
John Stiles7bd70332020-11-30 17:04:09 -0500996 return nullptr;
ethannicholasb3058bd2016-07-01 08:22:01 -0700997 }
John Stiles6bef6a72020-12-02 14:26:04 -0500998 const Type* result = &symbol->as<Type>();
John Stiles7bd70332020-11-30 17:04:09 -0500999 const bool isArray = (type.begin() != type.end());
John Stiles2558c462021-03-16 17:49:20 -04001000 if (result->isVoid() && !allowVoid) {
John Stiles80b02af2021-02-12 17:07:51 -05001001 this->errorReporter().error(type.fOffset,
1002 "type '" + name + "' not allowed in this context");
1003 return nullptr;
John Stiles7bd70332020-11-30 17:04:09 -05001004 }
John Stiles823c5042021-08-17 12:09:00 -04001005 if (!fIsBuiltinCode) {
1006 if (type_contains_private_fields(*result)) {
1007 this->errorReporter().error(type.fOffset, "type '" + name + "' is private");
1008 return nullptr;
1009 }
1010 if (this->strictES2Mode() && !result->allowedInES2()) {
1011 this->errorReporter().error(type.fOffset, "type '" + name + "' is not supported");
1012 return nullptr;
1013 }
John Stiles7bd70332020-11-30 17:04:09 -05001014 }
John Stiles6bef6a72020-12-02 14:26:04 -05001015 if (isArray) {
John Stilesd39aec92020-12-03 14:37:16 -05001016 auto iter = type.begin();
John Stiles80b02af2021-02-12 17:07:51 -05001017 int arraySize = this->convertArraySize(*result, type.fOffset, *iter);
Brian Osman4cf85072021-01-14 14:18:10 -05001018 if (!arraySize) {
1019 return nullptr;
1020 }
John Stilesa2179502020-12-03 14:37:57 -05001021 result = fSymbolTable->addArrayDimension(result, arraySize);
John Stiles7bd70332020-11-30 17:04:09 -05001022 }
John Stiles6bef6a72020-12-02 14:26:04 -05001023 return result;
ethannicholasb3058bd2016-07-01 08:22:01 -07001024}
1025
Ethan Nicholasfc994162019-06-06 10:04:27 -04001026std::unique_ptr<Expression> IRGenerator::convertExpression(const ASTNode& expr) {
ethannicholasb3058bd2016-07-01 08:22:01 -07001027 switch (expr.fKind) {
Ethan Nicholasfc994162019-06-06 10:04:27 -04001028 case ASTNode::Kind::kBinary:
1029 return this->convertBinaryExpression(expr);
1030 case ASTNode::Kind::kBool:
John Stiles9ce80f72021-03-11 22:35:19 -05001031 return BoolLiteral::Make(fContext, expr.fOffset, expr.getBool());
Ethan Nicholasfc994162019-06-06 10:04:27 -04001032 case ASTNode::Kind::kCall:
1033 return this->convertCallExpression(expr);
1034 case ASTNode::Kind::kField:
1035 return this->convertFieldExpression(expr);
1036 case ASTNode::Kind::kFloat:
John Stiles9ce80f72021-03-11 22:35:19 -05001037 return FloatLiteral::Make(fContext, expr.fOffset, expr.getFloat());
Ethan Nicholasfc994162019-06-06 10:04:27 -04001038 case ASTNode::Kind::kIdentifier:
1039 return this->convertIdentifier(expr);
1040 case ASTNode::Kind::kIndex:
1041 return this->convertIndexExpression(expr);
1042 case ASTNode::Kind::kInt:
John Stiles9ce80f72021-03-11 22:35:19 -05001043 return IntLiteral::Make(fContext, expr.fOffset, expr.getInt());
Ethan Nicholasfc994162019-06-06 10:04:27 -04001044 case ASTNode::Kind::kPostfix:
1045 return this->convertPostfixExpression(expr);
1046 case ASTNode::Kind::kPrefix:
1047 return this->convertPrefixExpression(expr);
1048 case ASTNode::Kind::kTernary:
1049 return this->convertTernaryExpression(expr);
ethannicholasb3058bd2016-07-01 08:22:01 -07001050 default:
John Stilesfbb905e2021-08-25 15:51:50 -04001051 SkDEBUGFAIL("unsupported expression");
Ethan Nicholas2a099da2020-01-02 14:40:54 -05001052 return nullptr;
ethannicholasb3058bd2016-07-01 08:22:01 -07001053 }
1054}
1055
Ethan Nicholas962dec42021-06-10 13:06:39 -04001056std::unique_ptr<Expression> IRGenerator::convertIdentifier(int offset, skstd::string_view name) {
Ethan Nicholas9ead3df2021-01-06 12:10:48 -05001057 const Symbol* result = (*fSymbolTable)[name];
ethannicholasb3058bd2016-07-01 08:22:01 -07001058 if (!result) {
John Stilesb30151e2021-01-11 16:13:08 -05001059 this->errorReporter().error(offset, "unknown identifier '" + name + "'");
ethannicholasb3058bd2016-07-01 08:22:01 -07001060 return nullptr;
1061 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001062 switch (result->kind()) {
1063 case Symbol::Kind::kFunctionDeclaration: {
ethannicholasd598f792016-07-25 10:08:54 -07001064 std::vector<const FunctionDeclaration*> f = {
John Stiles17c5b702020-08-18 10:40:03 -04001065 &result->as<FunctionDeclaration>()
ethannicholasb3058bd2016-07-01 08:22:01 -07001066 };
Ethan Nicholas9ead3df2021-01-06 12:10:48 -05001067 return std::make_unique<FunctionReference>(fContext, offset, f);
ethannicholasb3058bd2016-07-01 08:22:01 -07001068 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001069 case Symbol::Kind::kUnresolvedFunction: {
John Stiles17c5b702020-08-18 10:40:03 -04001070 const UnresolvedFunction* f = &result->as<UnresolvedFunction>();
Ethan Nicholas9ead3df2021-01-06 12:10:48 -05001071 return std::make_unique<FunctionReference>(fContext, offset, f->functions());
ethannicholasb3058bd2016-07-01 08:22:01 -07001072 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001073 case Symbol::Kind::kVariable: {
John Stiles17c5b702020-08-18 10:40:03 -04001074 const Variable* var = &result->as<Variable>();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001075 const Modifiers& modifiers = var->modifiers();
1076 switch (modifiers.fLayout.fBuiltin) {
Ethan Nicholascd700e92018-08-24 16:43:57 -04001077 case SK_FRAGCOORD_BUILTIN:
Brian Salomond8d85b92021-07-07 09:41:17 -04001078 if (caps().canUseFragCoord()) {
1079 fInputs.fUseFlipRTUniform = true;
Ethan Nicholascd700e92018-08-24 16:43:57 -04001080 }
Brian Salomond8d85b92021-07-07 09:41:17 -04001081 break;
1082 case SK_CLOCKWISE_BUILTIN:
1083 fInputs.fUseFlipRTUniform = true;
1084 break;
Ethan Nicholascd700e92018-08-24 16:43:57 -04001085 }
Ethan Nicholas86a43402017-01-19 13:32:00 -05001086 // default to kRead_RefKind; this will be corrected later if the variable is written to
John Stilesa94e0262021-04-27 17:29:59 -04001087 return VariableReference::Make(offset, var, VariableReference::RefKind::kRead);
ethannicholasb3058bd2016-07-01 08:22:01 -07001088 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001089 case Symbol::Kind::kField: {
John Stiles17c5b702020-08-18 10:40:03 -04001090 const Field* field = &result->as<Field>();
John Stilesa94e0262021-04-27 17:29:59 -04001091 auto base = VariableReference::Make(offset, &field->owner(),
1092 VariableReference::RefKind::kRead);
John Stiles06d600f2021-03-08 09:18:21 -05001093 return FieldAccess::Make(fContext, std::move(base), field->fieldIndex(),
1094 FieldAccess::OwnerKind::kAnonymousInterfaceBlock);
ethannicholasb3058bd2016-07-01 08:22:01 -07001095 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001096 case Symbol::Kind::kType: {
John Stiles17c5b702020-08-18 10:40:03 -04001097 const Type* t = &result->as<Type>();
Ethan Nicholas9ead3df2021-01-06 12:10:48 -05001098 return std::make_unique<TypeReference>(fContext, offset, t);
ethannicholasb3058bd2016-07-01 08:22:01 -07001099 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001100 case Symbol::Kind::kExternal: {
Brian Osmanbe0b3b72021-01-06 14:27:35 -05001101 const ExternalFunction* r = &result->as<ExternalFunction>();
1102 return std::make_unique<ExternalFunctionReference>(offset, r);
Ethan Nicholas91164d12019-05-15 15:29:54 -04001103 }
ethannicholasb3058bd2016-07-01 08:22:01 -07001104 default:
John Stilesf57207b2021-02-02 17:50:34 -05001105 SK_ABORT("unsupported symbol type %d\n", (int) result->kind());
ethannicholasb3058bd2016-07-01 08:22:01 -07001106 }
Ethan Nicholasc0709392017-06-27 11:20:22 -04001107}
1108
Ethan Nicholas9ead3df2021-01-06 12:10:48 -05001109std::unique_ptr<Expression> IRGenerator::convertIdentifier(const ASTNode& identifier) {
Ethan Nicholas962dec42021-06-10 13:06:39 -04001110 return this->convertIdentifier(identifier.fOffset, identifier.getStringView());
Ethan Nicholas9ead3df2021-01-06 12:10:48 -05001111}
1112
Ethan Nicholas11d53972016-11-28 11:23:23 -05001113std::unique_ptr<Expression> IRGenerator::coerce(std::unique_ptr<Expression> expr,
ethannicholasd598f792016-07-25 10:08:54 -07001114 const Type& type) {
John Stiles54f00492021-02-19 11:46:10 -05001115 return type.coerceExpression(std::move(expr), fContext);
ethannicholasb3058bd2016-07-01 08:22:01 -07001116}
1117
Ethan Nicholasfc994162019-06-06 10:04:27 -04001118std::unique_ptr<Expression> IRGenerator::convertBinaryExpression(const ASTNode& expression) {
1119 SkASSERT(expression.fKind == ASTNode::Kind::kBinary);
1120 auto iter = expression.begin();
1121 std::unique_ptr<Expression> left = this->convertExpression(*(iter++));
ethannicholasb3058bd2016-07-01 08:22:01 -07001122 if (!left) {
1123 return nullptr;
1124 }
John Stiles0f464502020-11-20 12:52:22 -05001125 std::unique_ptr<Expression> right = this->convertExpression(*(iter++));
ethannicholasb3058bd2016-07-01 08:22:01 -07001126 if (!right) {
1127 return nullptr;
1128 }
John Stiles23521a82021-03-02 17:02:51 -05001129 return BinaryExpression::Convert(fContext, std::move(left), expression.getOperator(),
1130 std::move(right));
ethannicholasb3058bd2016-07-01 08:22:01 -07001131}
1132
Ethan Nicholas9ead3df2021-01-06 12:10:48 -05001133std::unique_ptr<Expression> IRGenerator::convertTernaryExpression(const ASTNode& node) {
1134 SkASSERT(node.fKind == ASTNode::Kind::kTernary);
1135 auto iter = node.begin();
1136 std::unique_ptr<Expression> test = this->convertExpression(*(iter++));
1137 if (!test) {
1138 return nullptr;
1139 }
1140 std::unique_ptr<Expression> ifTrue = this->convertExpression(*(iter++));
1141 if (!ifTrue) {
1142 return nullptr;
1143 }
1144 std::unique_ptr<Expression> ifFalse = this->convertExpression(*(iter++));
1145 if (!ifFalse) {
1146 return nullptr;
1147 }
John Stiles23521a82021-03-02 17:02:51 -05001148 return TernaryExpression::Convert(fContext, std::move(test),
1149 std::move(ifTrue), std::move(ifFalse));
Ethan Nicholas9ead3df2021-01-06 12:10:48 -05001150}
1151
Ethan Nicholasc18bb512020-07-28 14:46:53 -04001152void IRGenerator::copyIntrinsicIfNeeded(const FunctionDeclaration& function) {
Brian Osman00a8b5b2020-10-02 09:06:04 -04001153 if (const ProgramElement* found = fIntrinsics->findAndInclude(function.description())) {
Brian Osman2b469eb2020-09-21 11:32:10 -04001154 const FunctionDefinition& original = found->as<FunctionDefinition>();
John Stiles9878d9e2020-09-22 15:40:16 -04001155
1156 // Sort the referenced intrinsics into a consistent order; otherwise our output will become
1157 // non-deterministic.
Ethan Nicholas0a5d0962020-10-14 13:33:18 -04001158 std::vector<const FunctionDeclaration*> intrinsics(original.referencedIntrinsics().begin(),
1159 original.referencedIntrinsics().end());
John Stiles9878d9e2020-09-22 15:40:16 -04001160 std::sort(intrinsics.begin(), intrinsics.end(),
1161 [](const FunctionDeclaration* a, const FunctionDeclaration* b) {
Ethan Nicholased84b732020-10-08 11:45:44 -04001162 if (a->isBuiltin() != b->isBuiltin()) {
1163 return a->isBuiltin() < b->isBuiltin();
John Stiles9878d9e2020-09-22 15:40:16 -04001164 }
1165 if (a->fOffset != b->fOffset) {
1166 return a->fOffset < b->fOffset;
1167 }
Ethan Nicholase2c49992020-10-05 11:49:11 -04001168 if (a->name() != b->name()) {
1169 return a->name() < b->name();
John Stiles9878d9e2020-09-22 15:40:16 -04001170 }
1171 return a->description() < b->description();
1172 });
1173 for (const FunctionDeclaration* f : intrinsics) {
Ethan Nicholasc18bb512020-07-28 14:46:53 -04001174 this->copyIntrinsicIfNeeded(*f);
1175 }
John Stiles607d36b2020-10-19 15:00:01 -04001176
Brian Osman0006ad02020-11-18 15:38:39 -05001177 fSharedElements->push_back(found);
Ethan Nicholasc18bb512020-07-28 14:46:53 -04001178 }
1179}
1180
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001181std::unique_ptr<Expression> IRGenerator::call(int offset,
Ethan Nicholas11d53972016-11-28 11:23:23 -05001182 const FunctionDeclaration& function,
John Stiles8e3b6be2020-10-13 11:14:08 -04001183 ExpressionArray arguments) {
Ethan Nicholased84b732020-10-08 11:45:44 -04001184 if (function.isBuiltin()) {
John Stiles12eb0ee2021-06-01 14:14:50 -04001185 if (function.intrinsicKind() == k_dFdy_IntrinsicKind) {
Brian Salomond8d85b92021-07-07 09:41:17 -04001186 fInputs.fUseFlipRTUniform = true;
John Stiles12eb0ee2021-06-01 14:14:50 -04001187 }
Brian Osman00a8b5b2020-10-02 09:06:04 -04001188 if (!fIsBuiltinCode && fIntrinsics) {
Ethan Nicholasc18bb512020-07-28 14:46:53 -04001189 this->copyIntrinsicIfNeeded(function);
Ethan Nicholasdb80f692019-11-22 14:06:12 -05001190 }
1191 }
John Stilesea9ab822020-08-31 09:55:04 -04001192
John Stilescd7ba502021-03-19 10:54:59 -04001193 return FunctionCall::Convert(fContext, offset, function, std::move(arguments));
ethannicholasb3058bd2016-07-01 08:22:01 -07001194}
1195
1196/**
Ethan Nicholasdcba08e2017-08-02 10:52:54 -04001197 * Determines the cost of coercing the arguments of a function to the required types. Cost has no
Brian Osman0acb5b52020-09-02 13:45:47 -04001198 * particular meaning other than "lower costs are preferred". Returns CoercionCost::Impossible() if
1199 * the call is not valid.
ethannicholasb3058bd2016-07-01 08:22:01 -07001200 */
Brian Osman0acb5b52020-09-02 13:45:47 -04001201CoercionCost IRGenerator::callCost(const FunctionDeclaration& function,
John Stiles8e3b6be2020-10-13 11:14:08 -04001202 const ExpressionArray& arguments) {
John Stilesefde90d2021-08-12 23:06:24 -04001203 if (this->strictES2Mode() && (function.modifiers().fFlags & Modifiers::kES3_Flag)) {
1204 return CoercionCost::Impossible();
1205 }
Ethan Nicholased84b732020-10-08 11:45:44 -04001206 if (function.parameters().size() != arguments.size()) {
Brian Osman0acb5b52020-09-02 13:45:47 -04001207 return CoercionCost::Impossible();
ethannicholasb3058bd2016-07-01 08:22:01 -07001208 }
John Stilesfa889112020-10-12 19:03:43 -04001209 FunctionDeclaration::ParamTypes types;
ethannicholas471e8942016-10-28 09:02:46 -07001210 const Type* ignored;
1211 if (!function.determineFinalTypes(arguments, &types, &ignored)) {
Brian Osman0acb5b52020-09-02 13:45:47 -04001212 return CoercionCost::Impossible();
ethannicholas471e8942016-10-28 09:02:46 -07001213 }
Brian Osman0acb5b52020-09-02 13:45:47 -04001214 CoercionCost total = CoercionCost::Free();
ethannicholasb3058bd2016-07-01 08:22:01 -07001215 for (size_t i = 0; i < arguments.size(); i++) {
Brian Osman0acb5b52020-09-02 13:45:47 -04001216 total = total + arguments[i]->coercionCost(*types[i]);
ethannicholasb3058bd2016-07-01 08:22:01 -07001217 }
Ethan Nicholasdcba08e2017-08-02 10:52:54 -04001218 return total;
ethannicholasb3058bd2016-07-01 08:22:01 -07001219}
1220
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001221std::unique_ptr<Expression> IRGenerator::call(int offset,
Ethan Nicholas11d53972016-11-28 11:23:23 -05001222 std::unique_ptr<Expression> functionValue,
John Stiles8e3b6be2020-10-13 11:14:08 -04001223 ExpressionArray arguments) {
Ethan Nicholase6592142020-09-08 10:22:09 -04001224 switch (functionValue->kind()) {
1225 case Expression::Kind::kTypeReference:
John Stiles23521a82021-03-02 17:02:51 -05001226 return Constructor::Convert(fContext,
1227 offset,
1228 functionValue->as<TypeReference>().value(),
1229 std::move(arguments));
Brian Osmanbe0b3b72021-01-06 14:27:35 -05001230 case Expression::Kind::kExternalFunctionReference: {
1231 const ExternalFunction& f = functionValue->as<ExternalFunctionReference>().function();
1232 int count = f.callParameterCount();
Ethan Nicholas9e6a3932019-05-17 16:31:21 -04001233 if (count != (int) arguments.size()) {
John Stilesb30151e2021-01-11 16:13:08 -05001234 this->errorReporter().error(offset, "external function expected " +
1235 to_string(count) + " arguments, but found " +
1236 to_string((int)arguments.size()));
Ethan Nicholas9e6a3932019-05-17 16:31:21 -04001237 return nullptr;
1238 }
1239 static constexpr int PARAMETER_MAX = 16;
1240 SkASSERT(count < PARAMETER_MAX);
1241 const Type* types[PARAMETER_MAX];
Brian Osmanbe0b3b72021-01-06 14:27:35 -05001242 f.getCallParameterTypes(types);
Ethan Nicholas9e6a3932019-05-17 16:31:21 -04001243 for (int i = 0; i < count; ++i) {
1244 arguments[i] = this->coerce(std::move(arguments[i]), *types[i]);
1245 if (!arguments[i]) {
1246 return nullptr;
1247 }
1248 }
Brian Osmanbe0b3b72021-01-06 14:27:35 -05001249 return std::make_unique<ExternalFunctionCall>(offset, &f, std::move(arguments));
ethannicholasb3058bd2016-07-01 08:22:01 -07001250 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001251 case Expression::Kind::kFunctionReference: {
John Stilesce591b72020-08-27 11:47:30 -04001252 const FunctionReference& ref = functionValue->as<FunctionReference>();
Ethan Nicholas5194a702020-10-12 11:12:12 -04001253 const std::vector<const FunctionDeclaration*>& functions = ref.functions();
Brian Osman0acb5b52020-09-02 13:45:47 -04001254 CoercionCost bestCost = CoercionCost::Impossible();
Ethan Nicholas9e6a3932019-05-17 16:31:21 -04001255 const FunctionDeclaration* best = nullptr;
Ethan Nicholas5194a702020-10-12 11:12:12 -04001256 if (functions.size() > 1) {
1257 for (const auto& f : functions) {
Brian Osman0acb5b52020-09-02 13:45:47 -04001258 CoercionCost cost = this->callCost(*f, arguments);
Ethan Nicholas9e6a3932019-05-17 16:31:21 -04001259 if (cost < bestCost) {
1260 bestCost = cost;
1261 best = f;
1262 }
1263 }
1264 if (best) {
1265 return this->call(offset, *best, std::move(arguments));
1266 }
Ethan Nicholas5194a702020-10-12 11:12:12 -04001267 String msg = "no match for " + functions[0]->name() + "(";
Ethan Nicholas9e6a3932019-05-17 16:31:21 -04001268 String separator;
1269 for (size_t i = 0; i < arguments.size(); i++) {
1270 msg += separator;
1271 separator = ", ";
Ethan Nicholas30d30222020-09-11 12:27:26 -04001272 msg += arguments[i]->type().displayName();
Ethan Nicholas9e6a3932019-05-17 16:31:21 -04001273 }
1274 msg += ")";
John Stilesb30151e2021-01-11 16:13:08 -05001275 this->errorReporter().error(offset, msg);
Ethan Nicholas9e6a3932019-05-17 16:31:21 -04001276 return nullptr;
1277 }
Ethan Nicholas5194a702020-10-12 11:12:12 -04001278 return this->call(offset, *functions[0], std::move(arguments));
ethannicholasb3058bd2016-07-01 08:22:01 -07001279 }
Ethan Nicholas9e6a3932019-05-17 16:31:21 -04001280 default:
John Stilesb30151e2021-01-11 16:13:08 -05001281 this->errorReporter().error(offset, "not a function");
Ethan Nicholas9e6a3932019-05-17 16:31:21 -04001282 return nullptr;
ethannicholasb3058bd2016-07-01 08:22:01 -07001283 }
ethannicholasb3058bd2016-07-01 08:22:01 -07001284}
1285
Ethan Nicholasfc994162019-06-06 10:04:27 -04001286std::unique_ptr<Expression> IRGenerator::convertPrefixExpression(const ASTNode& expression) {
1287 SkASSERT(expression.fKind == ASTNode::Kind::kPrefix);
1288 std::unique_ptr<Expression> base = this->convertExpression(*expression.begin());
ethannicholasb3058bd2016-07-01 08:22:01 -07001289 if (!base) {
1290 return nullptr;
1291 }
John Stiles23521a82021-03-02 17:02:51 -05001292 return PrefixExpression::Convert(fContext, expression.getOperator(), std::move(base));
ethannicholasb3058bd2016-07-01 08:22:01 -07001293}
1294
ethannicholasb3058bd2016-07-01 08:22:01 -07001295std::unique_ptr<Expression> IRGenerator::convertSwizzle(std::unique_ptr<Expression> base,
Ethan Nicholas962dec42021-06-10 13:06:39 -04001296 skstd::string_view fields) {
Ethan Nicholas59ff4e22021-07-12 12:28:57 -04001297 return Swizzle::Convert(fContext, std::move(base), fields);
ethannicholasb3058bd2016-07-01 08:22:01 -07001298}
1299
Ethan Nicholasfc994162019-06-06 10:04:27 -04001300std::unique_ptr<Expression> IRGenerator::convertIndexExpression(const ASTNode& index) {
1301 SkASSERT(index.fKind == ASTNode::Kind::kIndex);
1302 auto iter = index.begin();
1303 std::unique_ptr<Expression> base = this->convertExpression(*(iter++));
ethannicholasb3058bd2016-07-01 08:22:01 -07001304 if (!base) {
1305 return nullptr;
1306 }
Ethan Nicholas4d2bbbb2021-01-12 11:56:23 -05001307 if (iter == index.end()) {
Ethan Nicholas251e6342021-07-20 13:16:19 -04001308 if (base->is<TypeReference>()) {
1309 this->errorReporter().error(index.fOffset, "array must have a size");
1310 } else {
1311 this->errorReporter().error(base->fOffset, "missing index in '[]'");
1312 }
Brian Osman4cf85072021-01-14 14:18:10 -05001313 return nullptr;
Ethan Nicholas4d2bbbb2021-01-12 11:56:23 -05001314 }
1315 std::unique_ptr<Expression> converted = this->convertExpression(*(iter++));
1316 if (!converted) {
1317 return nullptr;
1318 }
John Stilesbb8cf582021-08-26 23:34:59 -04001319 return IndexExpression::Convert(fContext, *fSymbolTable, std::move(base), std::move(converted));
John Stiles1b27c3d2020-12-07 12:14:55 -05001320}
1321
Ethan Nicholasfc994162019-06-06 10:04:27 -04001322std::unique_ptr<Expression> IRGenerator::convertCallExpression(const ASTNode& callNode) {
1323 SkASSERT(callNode.fKind == ASTNode::Kind::kCall);
1324 auto iter = callNode.begin();
1325 std::unique_ptr<Expression> base = this->convertExpression(*(iter++));
1326 if (!base) {
1327 return nullptr;
1328 }
John Stiles8e3b6be2020-10-13 11:14:08 -04001329 ExpressionArray arguments;
Ethan Nicholasfc994162019-06-06 10:04:27 -04001330 for (; iter != callNode.end(); ++iter) {
1331 std::unique_ptr<Expression> converted = this->convertExpression(*iter);
1332 if (!converted) {
1333 return nullptr;
1334 }
1335 arguments.push_back(std::move(converted));
1336 }
1337 return this->call(callNode.fOffset, std::move(base), std::move(arguments));
1338}
1339
1340std::unique_ptr<Expression> IRGenerator::convertFieldExpression(const ASTNode& fieldNode) {
1341 std::unique_ptr<Expression> base = this->convertExpression(*fieldNode.begin());
1342 if (!base) {
1343 return nullptr;
1344 }
Ethan Nicholas962dec42021-06-10 13:06:39 -04001345 const skstd::string_view& field = fieldNode.getStringView();
Ethan Nicholas30d30222020-09-11 12:27:26 -04001346 const Type& baseType = base->type();
Ethan Nicholas5c75e832021-06-10 18:28:19 -04001347 if (baseType == *fContext.fTypes.fSkCaps || baseType.isStruct()) {
John Stiles06d600f2021-03-08 09:18:21 -05001348 return FieldAccess::Convert(fContext, std::move(base), field);
Ethan Nicholasfc994162019-06-06 10:04:27 -04001349 }
John Stiles06d600f2021-03-08 09:18:21 -05001350 return this->convertSwizzle(std::move(base), field);
Ethan Nicholasfc994162019-06-06 10:04:27 -04001351}
1352
1353std::unique_ptr<Expression> IRGenerator::convertPostfixExpression(const ASTNode& expression) {
Ethan Nicholas9ead3df2021-01-06 12:10:48 -05001354 SkASSERT(expression.fKind == ASTNode::Kind::kPostfix);
Ethan Nicholasfc994162019-06-06 10:04:27 -04001355 std::unique_ptr<Expression> base = this->convertExpression(*expression.begin());
1356 if (!base) {
1357 return nullptr;
1358 }
John Stiles23521a82021-03-02 17:02:51 -05001359 return PostfixExpression::Convert(fContext, std::move(base), expression.getOperator());
ethannicholasb3058bd2016-07-01 08:22:01 -07001360}
1361
1362void IRGenerator::checkValid(const Expression& expr) {
Ethan Nicholase6592142020-09-08 10:22:09 -04001363 switch (expr.kind()) {
John Stilesdc435fa2020-12-30 18:07:10 -05001364 case Expression::Kind::kFunctionCall: {
1365 const FunctionDeclaration& decl = expr.as<FunctionCall>().function();
1366 if (!decl.isBuiltin() && !decl.definition()) {
John Stilesb30151e2021-01-11 16:13:08 -05001367 this->errorReporter().error(expr.fOffset,
1368 "function '" + decl.description() + "' is not defined");
John Stilesdc435fa2020-12-30 18:07:10 -05001369 }
1370 break;
1371 }
John Stiles973009b2021-02-17 17:18:01 -05001372 case Expression::Kind::kFunctionReference:
1373 case Expression::Kind::kTypeReference:
1374 SkDEBUGFAIL("invalid reference-expression, should have been reported by coerce()");
1375 this->errorReporter().error(expr.fOffset, "invalid expression");
1376 break;
ethannicholasb3058bd2016-07-01 08:22:01 -07001377 default:
John Stiles54e7c052021-01-11 14:22:36 -05001378 if (expr.type() == *fContext.fTypes.fInvalid) {
John Stilesb30151e2021-01-11 16:13:08 -05001379 this->errorReporter().error(expr.fOffset, "invalid expression");
ethannicholasea4567c2016-10-17 11:24:37 -07001380 }
John Stiles973009b2021-02-17 17:18:01 -05001381 break;
ethannicholasb3058bd2016-07-01 08:22:01 -07001382 }
1383}
1384
Brian Osman9496fe52020-11-18 14:48:19 -05001385void IRGenerator::findAndDeclareBuiltinVariables() {
1386 class BuiltinVariableScanner : public ProgramVisitor {
Brian Osman8e2ef022020-09-30 13:26:43 -04001387 public:
Brian Osman9496fe52020-11-18 14:48:19 -05001388 BuiltinVariableScanner(IRGenerator* generator) : fGenerator(generator) {}
Brian Osman8e2ef022020-09-30 13:26:43 -04001389
Brian Osman9496fe52020-11-18 14:48:19 -05001390 void addDeclaringElement(const String& name) {
Brian Osman00a8b5b2020-10-02 09:06:04 -04001391 // If this is the *first* time we've seen this builtin, findAndInclude will return
1392 // the corresponding ProgramElement.
Brian Osman9496fe52020-11-18 14:48:19 -05001393 if (const ProgramElement* decl = fGenerator->fIntrinsics->findAndInclude(name)) {
Ethan Nicholase6ed3c22021-07-08 10:38:43 -04001394 SkASSERT(decl->is<GlobalVarDeclaration>() || decl->is<SkSL::InterfaceBlock>());
Brian Osman9496fe52020-11-18 14:48:19 -05001395 fNewElements.push_back(decl);
Brian Osman00a8b5b2020-10-02 09:06:04 -04001396 }
1397 }
1398
John Stiles4d6310a2021-01-26 19:58:22 -05001399 bool visitProgramElement(const ProgramElement& pe) override {
1400 if (pe.is<FunctionDefinition>()) {
1401 const FunctionDefinition& funcDef = pe.as<FunctionDefinition>();
1402 // We synthesize writes to sk_FragColor if main() returns a color, even if it's
1403 // otherwise unreferenced. Check main's return type to see if it's half4.
John Stilese8da4d22021-03-24 09:19:45 -04001404 if (funcDef.declaration().isMain() &&
John Stiles4d6310a2021-01-26 19:58:22 -05001405 funcDef.declaration().returnType() == *fGenerator->fContext.fTypes.fHalf4) {
1406 fPreserveFragColor = true;
1407 }
1408 }
1409 return INHERITED::visitProgramElement(pe);
1410 }
1411
Brian Osman9496fe52020-11-18 14:48:19 -05001412 bool visitExpression(const Expression& e) override {
Ethan Nicholas78686922020-10-08 06:46:27 -04001413 if (e.is<VariableReference>() && e.as<VariableReference>().variable()->isBuiltin()) {
Ethan Nicholasd2e09602021-06-10 11:21:59 -04001414 this->addDeclaringElement(String(e.as<VariableReference>().variable()->name()));
Brian Osman8e2ef022020-09-30 13:26:43 -04001415 }
Brian Osman8e2ef022020-09-30 13:26:43 -04001416 return INHERITED::visitExpression(e);
1417 }
1418
1419 IRGenerator* fGenerator;
Brian Osman9496fe52020-11-18 14:48:19 -05001420 std::vector<const ProgramElement*> fNewElements;
John Stiles4d6310a2021-01-26 19:58:22 -05001421 bool fPreserveFragColor = false;
Brian Osman8e2ef022020-09-30 13:26:43 -04001422
Brian Osman9496fe52020-11-18 14:48:19 -05001423 using INHERITED = ProgramVisitor;
Brian Osman8e2ef022020-09-30 13:26:43 -04001424 using INHERITED::visitProgramElement;
1425 };
1426
Brian Osman9496fe52020-11-18 14:48:19 -05001427 BuiltinVariableScanner scanner(this);
Ethan Nicholas624a5292021-04-16 14:54:43 -04001428 SkASSERT(fProgramElements);
Brian Osman00a8b5b2020-10-02 09:06:04 -04001429 for (auto& e : *fProgramElements) {
Brian Osman9496fe52020-11-18 14:48:19 -05001430 scanner.visitProgramElement(*e);
Brian Osman8e2ef022020-09-30 13:26:43 -04001431 }
Brian Osman00a8b5b2020-10-02 09:06:04 -04001432
John Stiles4d6310a2021-01-26 19:58:22 -05001433 if (scanner.fPreserveFragColor) {
1434 // main() returns a half4, so make sure we don't dead-strip sk_FragColor.
John Stilese67bd132021-03-19 18:39:25 -04001435 scanner.addDeclaringElement(Compiler::FRAGCOLOR_NAME);
John Stiles4d6310a2021-01-26 19:58:22 -05001436 }
1437
John Stilesd1204642021-02-17 16:30:02 -05001438 switch (this->programKind()) {
John Stilesdbd4e6f2021-02-16 13:29:15 -05001439 case ProgramKind::kFragment:
John Stiles4d6310a2021-01-26 19:58:22 -05001440 // Vulkan requires certain builtin variables be present, even if they're unused. At one
1441 // time, validation errors would result if sk_Clockwise was missing. Now, it's just
1442 // (Adreno) driver bugs that drop or corrupt draws if they're missing.
Brian Osman9496fe52020-11-18 14:48:19 -05001443 scanner.addDeclaringElement("sk_Clockwise");
Brian Osman00a8b5b2020-10-02 09:06:04 -04001444 break;
1445 default:
1446 break;
1447 }
1448
Brian Osman9496fe52020-11-18 14:48:19 -05001449 fSharedElements->insert(
1450 fSharedElements->begin(), scanner.fNewElements.begin(), scanner.fNewElements.end());
Brian Osman8e2ef022020-09-30 13:26:43 -04001451}
1452
Ethan Nicholas8b3dd342021-03-23 12:32:56 -04001453void IRGenerator::start(const ParsedModule& base,
1454 bool isBuiltinCode,
Ethan Nicholas8b3dd342021-03-23 12:32:56 -04001455 std::vector<std::unique_ptr<ProgramElement>>* elements,
1456 std::vector<const ProgramElement*>* sharedElements) {
Ethan Nicholas624a5292021-04-16 14:54:43 -04001457 fProgramElements = elements;
1458 fSharedElements = sharedElements;
Brian Osman88cda172020-10-09 12:05:16 -04001459 fSymbolTable = base.fSymbols;
1460 fIntrinsics = base.fIntrinsics.get();
1461 if (fIntrinsics) {
1462 fIntrinsics->resetAlreadyIncluded();
1463 }
1464 fIsBuiltinCode = isBuiltinCode;
1465
Brian Salomond8d85b92021-07-07 09:41:17 -04001466 fInputs = {};
Brian Osman88cda172020-10-09 12:05:16 -04001467 fInvocations = -1;
1468 fRTAdjust = nullptr;
1469 fRTAdjustInterfaceBlock = nullptr;
Brian Osman02bc5222021-01-28 11:00:20 -05001470 fDefinedStructs.clear();
Ethan Nicholas8b3dd342021-03-23 12:32:56 -04001471 this->pushSymbolTable();
Brian Osman88cda172020-10-09 12:05:16 -04001472
John Stilesd1204642021-02-17 16:30:02 -05001473 if (this->programKind() == ProgramKind::kGeometry && !fIsBuiltinCode) {
Brian Osman68c1d402020-10-12 16:36:38 -04001474 // Declare sk_InvocationID programmatically. With invocations support, it's an 'in' builtin.
1475 // If we're applying the workaround, then it's a plain global.
John Stilesc1a98b82021-02-24 13:35:02 -05001476 bool workaround = !this->caps().gsInvocationsSupport();
Brian Osman68c1d402020-10-12 16:36:38 -04001477 Modifiers m;
1478 if (!workaround) {
1479 m.fFlags = Modifiers::kIn_Flag;
1480 m.fLayout.fBuiltin = SK_INVOCATIONID_BUILTIN;
1481 }
John Stilesf2872e62021-05-04 11:38:43 -04001482 auto var = std::make_unique<Variable>(/*offset=*/-1, this->modifiersPool().add(m),
John Stilese67bd132021-03-19 18:39:25 -04001483 "sk_InvocationID", fContext.fTypes.fInt.get(),
1484 /*builtin=*/false, Variable::Storage::kGlobal);
1485 auto decl = VarDeclaration::Make(fContext, var.get(), fContext.fTypes.fInt.get(),
1486 /*arraySize=*/0, /*value=*/nullptr);
Brian Osman68c1d402020-10-12 16:36:38 -04001487 fSymbolTable->add(std::move(var));
Ethan Nicholas624a5292021-04-16 14:54:43 -04001488 fProgramElements->push_back(std::make_unique<GlobalVarDeclaration>(std::move(decl)));
Brian Osman68c1d402020-10-12 16:36:38 -04001489 }
1490
Ethan Nicholas55a63af2021-05-18 10:12:58 -04001491 if (this->settings().fExternalFunctions) {
John Stilesaecf8d52021-05-14 12:15:01 -04001492 // Add any external values to the new symbol table, so they're only visible to this Program.
Ethan Nicholas55a63af2021-05-18 10:12:58 -04001493 for (const std::unique_ptr<ExternalFunction>& ef : *this->settings().fExternalFunctions) {
Brian Osmanbe0b3b72021-01-06 14:27:35 -05001494 fSymbolTable->addWithoutOwnership(ef.get());
Brian Osman88cda172020-10-09 12:05:16 -04001495 }
1496 }
John Stilesaecf8d52021-05-14 12:15:01 -04001497
John Stilesbb2ef922021-07-26 08:32:07 -04001498 if (this->isRuntimeEffect() && !fContext.fConfig->fSettings.fEnforceES2Restrictions) {
John Stiles325c8082021-05-17 14:49:05 -04001499 // We're compiling a runtime effect, but we're not enforcing ES2 restrictions. Add various
John Stiles12eb0ee2021-06-01 14:14:50 -04001500 // non-ES2 types to our symbol table to allow them to be tested.
John Stilesaecf8d52021-05-14 12:15:01 -04001501 fSymbolTable->addAlias("mat2x2", fContext.fTypes.fFloat2x2.get());
1502 fSymbolTable->addAlias("mat2x3", fContext.fTypes.fFloat2x3.get());
1503 fSymbolTable->addAlias("mat2x4", fContext.fTypes.fFloat2x4.get());
1504 fSymbolTable->addAlias("mat3x2", fContext.fTypes.fFloat3x2.get());
1505 fSymbolTable->addAlias("mat3x3", fContext.fTypes.fFloat3x3.get());
1506 fSymbolTable->addAlias("mat3x4", fContext.fTypes.fFloat3x4.get());
1507 fSymbolTable->addAlias("mat4x2", fContext.fTypes.fFloat4x2.get());
1508 fSymbolTable->addAlias("mat4x3", fContext.fTypes.fFloat4x3.get());
1509 fSymbolTable->addAlias("mat4x4", fContext.fTypes.fFloat4x4.get());
1510
1511 fSymbolTable->addAlias("float2x3", fContext.fTypes.fFloat2x3.get());
1512 fSymbolTable->addAlias("float2x4", fContext.fTypes.fFloat2x4.get());
1513 fSymbolTable->addAlias("float3x2", fContext.fTypes.fFloat3x2.get());
1514 fSymbolTable->addAlias("float3x4", fContext.fTypes.fFloat3x4.get());
1515 fSymbolTable->addAlias("float4x2", fContext.fTypes.fFloat4x2.get());
1516 fSymbolTable->addAlias("float4x3", fContext.fTypes.fFloat4x3.get());
1517
1518 fSymbolTable->addAlias("half2x3", fContext.fTypes.fHalf2x3.get());
1519 fSymbolTable->addAlias("half2x4", fContext.fTypes.fHalf2x4.get());
1520 fSymbolTable->addAlias("half3x2", fContext.fTypes.fHalf3x2.get());
1521 fSymbolTable->addAlias("half3x4", fContext.fTypes.fHalf3x4.get());
1522 fSymbolTable->addAlias("half4x2", fContext.fTypes.fHalf4x2.get());
1523 fSymbolTable->addAlias("half4x3", fContext.fTypes.fHalf4x3.get());
John Stiles325c8082021-05-17 14:49:05 -04001524
1525 fSymbolTable->addAlias("uint", fContext.fTypes.fUInt.get());
1526 fSymbolTable->addAlias("uint2", fContext.fTypes.fUInt2.get());
1527 fSymbolTable->addAlias("uint3", fContext.fTypes.fUInt3.get());
1528 fSymbolTable->addAlias("uint4", fContext.fTypes.fUInt4.get());
John Stiles26487162021-08-10 16:03:44 -04001529
1530 fSymbolTable->addAlias("short", fContext.fTypes.fShort.get());
1531 fSymbolTable->addAlias("short2", fContext.fTypes.fShort2.get());
1532 fSymbolTable->addAlias("short3", fContext.fTypes.fShort3.get());
1533 fSymbolTable->addAlias("short4", fContext.fTypes.fShort4.get());
1534
1535 fSymbolTable->addAlias("ushort", fContext.fTypes.fUShort.get());
1536 fSymbolTable->addAlias("ushort2", fContext.fTypes.fUShort2.get());
1537 fSymbolTable->addAlias("ushort3", fContext.fTypes.fUShort3.get());
1538 fSymbolTable->addAlias("ushort4", fContext.fTypes.fUShort4.get());
John Stilesaecf8d52021-05-14 12:15:01 -04001539 }
Ethan Nicholas8b3dd342021-03-23 12:32:56 -04001540}
Brian Osman88cda172020-10-09 12:05:16 -04001541
Ethan Nicholas8b3dd342021-03-23 12:32:56 -04001542IRGenerator::IRBundle IRGenerator::finish() {
Brian Osman9496fe52020-11-18 14:48:19 -05001543 // Variables defined in the pre-includes need their declaring elements added to the program
Brian Osman00a8b5b2020-10-02 09:06:04 -04001544 if (!fIsBuiltinCode && fIntrinsics) {
Brian Osman9496fe52020-11-18 14:48:19 -05001545 this->findAndDeclareBuiltinVariables();
Brian Osman00a8b5b2020-10-02 09:06:04 -04001546 }
Brian Osman8e2ef022020-09-30 13:26:43 -04001547
Brian Osmanea485e52021-01-15 13:20:32 -05001548 // Do a pass looking for dangling FunctionReference or TypeReference expressions
Brian Osmanc95d3a12020-09-09 10:56:27 -04001549 class FindIllegalExpressions : public ProgramVisitor {
1550 public:
1551 FindIllegalExpressions(IRGenerator* generator) : fGenerator(generator) {}
1552
1553 bool visitExpression(const Expression& e) override {
1554 fGenerator->checkValid(e);
1555 return INHERITED::visitExpression(e);
1556 }
1557
1558 IRGenerator* fGenerator;
1559 using INHERITED = ProgramVisitor;
1560 using INHERITED::visitProgramElement;
1561 };
1562 for (const auto& pe : *fProgramElements) {
1563 FindIllegalExpressions{this}.visitProgramElement(*pe);
1564 }
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -04001565
Brian Osmanea485e52021-01-15 13:20:32 -05001566 // If we're in ES2 mode (runtime effects), do a pass to enforce Appendix A, Section 5 of the
1567 // GLSL ES 1.00 spec -- Indexing. Don't bother if we've already found errors - this logic
1568 // assumes that all loops meet the criteria of Section 4, and if they don't, could crash.
1569 if (this->strictES2Mode() && this->errorReporter().errorCount() == 0) {
1570 for (const auto& pe : *fProgramElements) {
1571 Analysis::ValidateIndexingForES2(*pe, this->errorReporter());
1572 }
1573 }
1574
Brian Osman7da06572021-07-21 15:19:34 -04001575 if (this->strictES2Mode()) {
1576 Analysis::DetectStaticRecursion(SkMakeSpan(*fProgramElements), this->errorReporter());
1577 }
1578
John Stilesf2872e62021-05-04 11:38:43 -04001579 return IRBundle{std::move(*fProgramElements),
1580 std::move(*fSharedElements),
John Stilesf2872e62021-05-04 11:38:43 -04001581 std::move(fSymbolTable),
1582 fInputs};
Ethan Nicholas8b3dd342021-03-23 12:32:56 -04001583}
1584
1585IRGenerator::IRBundle IRGenerator::convertProgram(
1586 const ParsedModule& base,
1587 bool isBuiltinCode,
Ethan Nicholas6823b502021-06-15 11:42:07 -04001588 skstd::string_view text) {
1589 Parser parser(text, *fSymbolTable, this->errorReporter());
Ethan Nicholas8b3dd342021-03-23 12:32:56 -04001590 fFile = parser.compilationUnit();
1591 if (this->errorReporter().errorCount() == 0) {
1592 SkASSERT(fFile);
1593 for (const auto& decl : fFile->root()) {
1594 switch (decl.fKind) {
1595 case ASTNode::Kind::kVarDeclarations:
1596 this->convertGlobalVarDeclarations(decl);
1597 break;
1598
Ethan Nicholas8b3dd342021-03-23 12:32:56 -04001599 case ASTNode::Kind::kFunction:
1600 this->convertFunction(decl);
1601 break;
1602
1603 case ASTNode::Kind::kModifiers: {
1604 std::unique_ptr<ModifiersDeclaration> f =
1605 this->convertModifiersDeclaration(decl);
1606 if (f) {
1607 fProgramElements->push_back(std::move(f));
1608 }
1609 break;
1610 }
1611 case ASTNode::Kind::kInterfaceBlock: {
Ethan Nicholase6ed3c22021-07-08 10:38:43 -04001612 std::unique_ptr<SkSL::InterfaceBlock> i = this->convertInterfaceBlock(decl);
Ethan Nicholas8b3dd342021-03-23 12:32:56 -04001613 if (i) {
1614 fProgramElements->push_back(std::move(i));
1615 }
1616 break;
1617 }
1618 case ASTNode::Kind::kExtension: {
1619 std::unique_ptr<Extension> e = this->convertExtension(decl.fOffset,
Ethan Nicholas962dec42021-06-10 13:06:39 -04001620 decl.getStringView());
Ethan Nicholas8b3dd342021-03-23 12:32:56 -04001621 if (e) {
1622 fProgramElements->push_back(std::move(e));
1623 }
1624 break;
1625 }
Ethan Nicholas8b3dd342021-03-23 12:32:56 -04001626 case ASTNode::Kind::kType: {
1627 std::unique_ptr<StructDefinition> s = this->convertStructDefinition(decl);
1628 if (s) {
1629 fProgramElements->push_back(std::move(s));
1630 }
1631 break;
1632 }
1633 default:
John Stilesfbb905e2021-08-25 15:51:50 -04001634 SkDEBUGFAIL("unsupported declaration");
Ethan Nicholas8b3dd342021-03-23 12:32:56 -04001635 break;
1636 }
1637 }
1638 }
1639 return this->finish();
Brian Osman88cda172020-10-09 12:05:16 -04001640}
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -04001641
John Stilesa6841be2020-08-06 14:11:56 -04001642} // namespace SkSL