blob: 41dc4b591a13b2afd360a572f2cfbc9e2f45d67f [file] [log] [blame]
John Stiles44e96be2020-08-31 13:16:04 -04001/*
2 * Copyright 2020 Google LLC
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
7
8#include "src/sksl/SkSLInliner.h"
9
John Stiles2d7973a2020-10-02 15:01:03 -040010#include <limits.h>
John Stiles44e96be2020-08-31 13:16:04 -040011#include <memory>
12#include <unordered_set>
13
14#include "src/sksl/SkSLAnalysis.h"
15#include "src/sksl/ir/SkSLBinaryExpression.h"
16#include "src/sksl/ir/SkSLBoolLiteral.h"
17#include "src/sksl/ir/SkSLBreakStatement.h"
18#include "src/sksl/ir/SkSLConstructor.h"
19#include "src/sksl/ir/SkSLContinueStatement.h"
20#include "src/sksl/ir/SkSLDiscardStatement.h"
21#include "src/sksl/ir/SkSLDoStatement.h"
22#include "src/sksl/ir/SkSLEnum.h"
23#include "src/sksl/ir/SkSLExpressionStatement.h"
24#include "src/sksl/ir/SkSLExternalFunctionCall.h"
Brian Osmanbe0b3b72021-01-06 14:27:35 -050025#include "src/sksl/ir/SkSLExternalFunctionReference.h"
John Stiles44e96be2020-08-31 13:16:04 -040026#include "src/sksl/ir/SkSLField.h"
27#include "src/sksl/ir/SkSLFieldAccess.h"
28#include "src/sksl/ir/SkSLFloatLiteral.h"
29#include "src/sksl/ir/SkSLForStatement.h"
30#include "src/sksl/ir/SkSLFunctionCall.h"
31#include "src/sksl/ir/SkSLFunctionDeclaration.h"
32#include "src/sksl/ir/SkSLFunctionDefinition.h"
33#include "src/sksl/ir/SkSLFunctionReference.h"
34#include "src/sksl/ir/SkSLIfStatement.h"
35#include "src/sksl/ir/SkSLIndexExpression.h"
John Stiles98c1f822020-09-09 14:18:53 -040036#include "src/sksl/ir/SkSLInlineMarker.h"
John Stiles44e96be2020-08-31 13:16:04 -040037#include "src/sksl/ir/SkSLIntLiteral.h"
38#include "src/sksl/ir/SkSLInterfaceBlock.h"
39#include "src/sksl/ir/SkSLLayout.h"
40#include "src/sksl/ir/SkSLNop.h"
John Stiles44e96be2020-08-31 13:16:04 -040041#include "src/sksl/ir/SkSLPostfixExpression.h"
42#include "src/sksl/ir/SkSLPrefixExpression.h"
43#include "src/sksl/ir/SkSLReturnStatement.h"
44#include "src/sksl/ir/SkSLSetting.h"
45#include "src/sksl/ir/SkSLSwitchCase.h"
46#include "src/sksl/ir/SkSLSwitchStatement.h"
47#include "src/sksl/ir/SkSLSwizzle.h"
48#include "src/sksl/ir/SkSLTernaryExpression.h"
49#include "src/sksl/ir/SkSLUnresolvedFunction.h"
50#include "src/sksl/ir/SkSLVarDeclarations.h"
John Stiles44e96be2020-08-31 13:16:04 -040051#include "src/sksl/ir/SkSLVariable.h"
52#include "src/sksl/ir/SkSLVariableReference.h"
John Stiles44e96be2020-08-31 13:16:04 -040053
54namespace SkSL {
55namespace {
56
John Stiles031a7672020-11-13 16:13:18 -050057static constexpr int kInlinedStatementLimit = 2500;
58
John Stiles44e96be2020-08-31 13:16:04 -040059static int count_returns_at_end_of_control_flow(const FunctionDefinition& funcDef) {
60 class CountReturnsAtEndOfControlFlow : public ProgramVisitor {
61 public:
62 CountReturnsAtEndOfControlFlow(const FunctionDefinition& funcDef) {
63 this->visitProgramElement(funcDef);
64 }
65
66 bool visitStatement(const Statement& stmt) override {
Ethan Nicholase6592142020-09-08 10:22:09 -040067 switch (stmt.kind()) {
68 case Statement::Kind::kBlock: {
John Stiles44e96be2020-08-31 13:16:04 -040069 // Check only the last statement of a block.
Ethan Nicholas7bd60432020-09-25 14:31:59 -040070 const auto& block = stmt.as<Block>();
71 return block.children().size() &&
72 this->visitStatement(*block.children().back());
John Stiles44e96be2020-08-31 13:16:04 -040073 }
Ethan Nicholase6592142020-09-08 10:22:09 -040074 case Statement::Kind::kSwitch:
Ethan Nicholase6592142020-09-08 10:22:09 -040075 case Statement::Kind::kDo:
76 case Statement::Kind::kFor:
John Stiles44e96be2020-08-31 13:16:04 -040077 // Don't introspect switches or loop structures at all.
78 return false;
79
Ethan Nicholase6592142020-09-08 10:22:09 -040080 case Statement::Kind::kReturn:
John Stiles44e96be2020-08-31 13:16:04 -040081 ++fNumReturns;
82 [[fallthrough]];
83
84 default:
John Stiles93442622020-09-11 12:11:27 -040085 return INHERITED::visitStatement(stmt);
John Stiles44e96be2020-08-31 13:16:04 -040086 }
87 }
88
89 int fNumReturns = 0;
90 using INHERITED = ProgramVisitor;
91 };
92
93 return CountReturnsAtEndOfControlFlow{funcDef}.fNumReturns;
94}
95
John Stiles74ebd7e2020-12-17 14:41:50 -050096static int count_returns_in_continuable_constructs(const FunctionDefinition& funcDef) {
97 class CountReturnsInContinuableConstructs : public ProgramVisitor {
John Stiles44e96be2020-08-31 13:16:04 -040098 public:
John Stiles74ebd7e2020-12-17 14:41:50 -050099 CountReturnsInContinuableConstructs(const FunctionDefinition& funcDef) {
John Stiles44e96be2020-08-31 13:16:04 -0400100 this->visitProgramElement(funcDef);
101 }
102
103 bool visitStatement(const Statement& stmt) override {
Ethan Nicholase6592142020-09-08 10:22:09 -0400104 switch (stmt.kind()) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400105 case Statement::Kind::kDo:
106 case Statement::Kind::kFor: {
John Stiles74ebd7e2020-12-17 14:41:50 -0500107 ++fInsideContinuableConstruct;
John Stiles93442622020-09-11 12:11:27 -0400108 bool result = INHERITED::visitStatement(stmt);
John Stiles74ebd7e2020-12-17 14:41:50 -0500109 --fInsideContinuableConstruct;
John Stiles44e96be2020-08-31 13:16:04 -0400110 return result;
111 }
112
Ethan Nicholase6592142020-09-08 10:22:09 -0400113 case Statement::Kind::kReturn:
John Stiles74ebd7e2020-12-17 14:41:50 -0500114 fNumReturns += (fInsideContinuableConstruct > 0) ? 1 : 0;
John Stiles44e96be2020-08-31 13:16:04 -0400115 [[fallthrough]];
116
117 default:
John Stiles93442622020-09-11 12:11:27 -0400118 return INHERITED::visitStatement(stmt);
John Stiles44e96be2020-08-31 13:16:04 -0400119 }
120 }
121
122 int fNumReturns = 0;
John Stiles74ebd7e2020-12-17 14:41:50 -0500123 int fInsideContinuableConstruct = 0;
John Stiles44e96be2020-08-31 13:16:04 -0400124 using INHERITED = ProgramVisitor;
125 };
126
John Stiles74ebd7e2020-12-17 14:41:50 -0500127 return CountReturnsInContinuableConstructs{funcDef}.fNumReturns;
John Stiles44e96be2020-08-31 13:16:04 -0400128}
129
John Stiles991b09d2020-09-10 13:33:40 -0400130static bool contains_recursive_call(const FunctionDeclaration& funcDecl) {
131 class ContainsRecursiveCall : public ProgramVisitor {
132 public:
133 bool visit(const FunctionDeclaration& funcDecl) {
134 fFuncDecl = &funcDecl;
Ethan Nicholased84b732020-10-08 11:45:44 -0400135 return funcDecl.definition() ? this->visitProgramElement(*funcDecl.definition())
136 : false;
John Stiles991b09d2020-09-10 13:33:40 -0400137 }
138
139 bool visitExpression(const Expression& expr) override {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400140 if (expr.is<FunctionCall>() && expr.as<FunctionCall>().function().matches(*fFuncDecl)) {
John Stiles991b09d2020-09-10 13:33:40 -0400141 return true;
142 }
143 return INHERITED::visitExpression(expr);
144 }
145
146 bool visitStatement(const Statement& stmt) override {
Ethan Nicholasceb62142020-10-09 16:51:18 -0400147 if (stmt.is<InlineMarker>() &&
148 stmt.as<InlineMarker>().function().matches(*fFuncDecl)) {
John Stiles991b09d2020-09-10 13:33:40 -0400149 return true;
150 }
151 return INHERITED::visitStatement(stmt);
152 }
153
154 const FunctionDeclaration* fFuncDecl;
155 using INHERITED = ProgramVisitor;
156 };
157
158 return ContainsRecursiveCall{}.visit(funcDecl);
159}
160
John Stiles6a1a98c2021-01-14 18:35:34 -0500161static const Type* copy_if_needed(const Type* type, SymbolTable* symbolTable) {
162 if (type->isArray()) {
163 const Symbol* copiedType = (*symbolTable)[type->name()];
164 if (!copiedType) {
165 copiedType = symbolTable->add(Type::MakeArrayType(type->name(), type->componentType(),
166 type->columns()));
167 }
168 return &copiedType->as<Type>();
John Stiles44e96be2020-08-31 13:16:04 -0400169 }
John Stiles6a1a98c2021-01-14 18:35:34 -0500170 return type;
John Stiles44e96be2020-08-31 13:16:04 -0400171}
172
John Stiles6d696082020-10-01 10:18:54 -0400173static std::unique_ptr<Statement>* find_parent_statement(
174 const std::vector<std::unique_ptr<Statement>*>& stmtStack) {
John Stiles915a38c2020-09-14 09:38:13 -0400175 SkASSERT(!stmtStack.empty());
176
177 // Walk the statement stack from back to front, ignoring the last element (which is the
178 // enclosing statement).
179 auto iter = stmtStack.rbegin();
180 ++iter;
181
182 // Anything counts as a parent statement other than a scopeless Block.
183 for (; iter != stmtStack.rend(); ++iter) {
John Stiles6d696082020-10-01 10:18:54 -0400184 std::unique_ptr<Statement>* stmt = *iter;
185 if (!(*stmt)->is<Block>() || (*stmt)->as<Block>().isScope()) {
John Stiles915a38c2020-09-14 09:38:13 -0400186 return stmt;
187 }
188 }
189
190 // There wasn't any parent statement to be found.
191 return nullptr;
192}
193
John Stilese41b4ee2020-09-28 12:28:16 -0400194std::unique_ptr<Expression> clone_with_ref_kind(const Expression& expr,
195 VariableReference::RefKind refKind) {
196 std::unique_ptr<Expression> clone = expr.clone();
John Stiles70b82422020-09-30 10:55:12 -0400197 class SetRefKindInExpression : public ProgramWriter {
John Stilese41b4ee2020-09-28 12:28:16 -0400198 public:
199 SetRefKindInExpression(VariableReference::RefKind refKind) : fRefKind(refKind) {}
John Stiles70b82422020-09-30 10:55:12 -0400200 bool visitExpression(Expression& expr) override {
John Stilese41b4ee2020-09-28 12:28:16 -0400201 if (expr.is<VariableReference>()) {
John Stiles70b82422020-09-30 10:55:12 -0400202 expr.as<VariableReference>().setRefKind(fRefKind);
John Stilese41b4ee2020-09-28 12:28:16 -0400203 }
204 return INHERITED::visitExpression(expr);
205 }
206
207 private:
208 VariableReference::RefKind fRefKind;
209
John Stiles70b82422020-09-30 10:55:12 -0400210 using INHERITED = ProgramWriter;
John Stilese41b4ee2020-09-28 12:28:16 -0400211 };
212
213 SetRefKindInExpression{refKind}.visitExpression(*clone);
214 return clone;
215}
216
John Stiles77702f12020-12-17 14:38:56 -0500217class CountReturnsWithLimit : public ProgramVisitor {
218public:
219 CountReturnsWithLimit(const FunctionDefinition& funcDef, int limit) : fLimit(limit) {
220 this->visitProgramElement(funcDef);
221 }
222
223 bool visitStatement(const Statement& stmt) override {
224 switch (stmt.kind()) {
225 case Statement::Kind::kReturn: {
226 ++fNumReturns;
227 fDeepestReturn = std::max(fDeepestReturn, fScopedBlockDepth);
228 return (fNumReturns >= fLimit) || INHERITED::visitStatement(stmt);
229 }
John Stilesc5ff4862020-12-22 13:47:05 -0500230 case Statement::Kind::kVarDeclaration: {
231 if (fScopedBlockDepth > 1) {
232 fVariablesInBlocks = true;
233 }
234 return INHERITED::visitStatement(stmt);
235 }
John Stiles77702f12020-12-17 14:38:56 -0500236 case Statement::Kind::kBlock: {
237 int depthIncrement = stmt.as<Block>().isScope() ? 1 : 0;
238 fScopedBlockDepth += depthIncrement;
239 bool result = INHERITED::visitStatement(stmt);
240 fScopedBlockDepth -= depthIncrement;
John Stilesc5ff4862020-12-22 13:47:05 -0500241 if (fNumReturns == 0 && fScopedBlockDepth <= 1) {
242 // If closing this block puts us back at the top level, and we haven't
243 // encountered any return statements yet, any vardecls we may have encountered
244 // up until this point can be ignored. They are out of scope now, and they were
245 // never used in a return statement.
246 fVariablesInBlocks = false;
247 }
John Stiles77702f12020-12-17 14:38:56 -0500248 return result;
249 }
250 default:
251 return INHERITED::visitStatement(stmt);
252 }
253 }
254
255 int fNumReturns = 0;
256 int fDeepestReturn = 0;
257 int fLimit = 0;
258 int fScopedBlockDepth = 0;
John Stilesc5ff4862020-12-22 13:47:05 -0500259 bool fVariablesInBlocks = false;
John Stiles77702f12020-12-17 14:38:56 -0500260 using INHERITED = ProgramVisitor;
261};
262
John Stiles44e96be2020-08-31 13:16:04 -0400263} // namespace
264
John Stiles77702f12020-12-17 14:38:56 -0500265Inliner::ReturnComplexity Inliner::GetReturnComplexity(const FunctionDefinition& funcDef) {
266 int returnsAtEndOfControlFlow = count_returns_at_end_of_control_flow(funcDef);
267 CountReturnsWithLimit counter{funcDef, returnsAtEndOfControlFlow + 1};
John Stiles77702f12020-12-17 14:38:56 -0500268 if (counter.fNumReturns > returnsAtEndOfControlFlow) {
269 return ReturnComplexity::kEarlyReturns;
270 }
John Stilesc5ff4862020-12-22 13:47:05 -0500271 if (counter.fNumReturns > 1) {
John Stiles77702f12020-12-17 14:38:56 -0500272 return ReturnComplexity::kScopedReturns;
273 }
John Stilesc5ff4862020-12-22 13:47:05 -0500274 if (counter.fVariablesInBlocks && counter.fDeepestReturn > 1) {
275 return ReturnComplexity::kScopedReturns;
276 }
277 return ReturnComplexity::kSingleSafeReturn;
John Stiles77702f12020-12-17 14:38:56 -0500278}
279
John Stilesb61ee902020-09-21 12:26:59 -0400280void Inliner::ensureScopedBlocks(Statement* inlinedBody, Statement* parentStmt) {
281 // No changes necessary if this statement isn't actually a block.
282 if (!inlinedBody || !inlinedBody->is<Block>()) {
283 return;
284 }
285
286 // No changes necessary if the parent statement doesn't require a scope.
287 if (!parentStmt || !(parentStmt->is<IfStatement>() || parentStmt->is<ForStatement>() ||
Brian Osmand6f23382020-12-15 17:08:59 -0500288 parentStmt->is<DoStatement>())) {
John Stilesb61ee902020-09-21 12:26:59 -0400289 return;
290 }
291
292 Block& block = inlinedBody->as<Block>();
293
294 // The inliner will create inlined function bodies as a Block containing multiple statements,
295 // but no scope. Normally, this is fine, but if this block is used as the statement for a
296 // do/for/if/while, this isn't actually possible to represent textually; a scope must be added
297 // for the generated code to match the intent. In the case of Blocks nested inside other Blocks,
298 // we add the scope to the outermost block if needed. Zero-statement blocks have similar
299 // issues--if we don't represent the Block textually somehow, we run the risk of accidentally
300 // absorbing the following statement into our loop--so we also add a scope to these.
301 for (Block* nestedBlock = &block;; ) {
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400302 if (nestedBlock->isScope()) {
John Stilesb61ee902020-09-21 12:26:59 -0400303 // We found an explicit scope; all is well.
304 return;
305 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400306 if (nestedBlock->children().size() != 1) {
John Stilesb61ee902020-09-21 12:26:59 -0400307 // We found a block with multiple (or zero) statements, but no scope? Let's add a scope
308 // to the outermost block.
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400309 block.setIsScope(true);
John Stilesb61ee902020-09-21 12:26:59 -0400310 return;
311 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400312 if (!nestedBlock->children()[0]->is<Block>()) {
John Stilesb61ee902020-09-21 12:26:59 -0400313 // This block has exactly one thing inside, and it's not another block. No need to scope
314 // it.
315 return;
316 }
317 // We have to go deeper.
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400318 nestedBlock = &nestedBlock->children()[0]->as<Block>();
John Stilesb61ee902020-09-21 12:26:59 -0400319 }
320}
321
Brian Osman0006ad02020-11-18 15:38:39 -0500322void Inliner::reset(ModifiersPool* modifiers, const Program::Settings* settings) {
Ethan Nicholas041fd0a2020-10-07 16:42:04 -0400323 fModifiers = modifiers;
324 fSettings = settings;
Ethan Nicholas6f4eee22021-01-11 12:37:42 -0500325 fMangler.reset();
John Stiles031a7672020-11-13 16:13:18 -0500326 fInlinedStatementCounter = 0;
John Stiles44e96be2020-08-31 13:16:04 -0400327}
328
329std::unique_ptr<Expression> Inliner::inlineExpression(int offset,
330 VariableRewriteMap* varMap,
John Stilesd7cc0932020-11-30 12:24:27 -0500331 SymbolTable* symbolTableForExpression,
John Stiles44e96be2020-08-31 13:16:04 -0400332 const Expression& expression) {
333 auto expr = [&](const std::unique_ptr<Expression>& e) -> std::unique_ptr<Expression> {
334 if (e) {
John Stilesd7cc0932020-11-30 12:24:27 -0500335 return this->inlineExpression(offset, varMap, symbolTableForExpression, *e);
John Stiles44e96be2020-08-31 13:16:04 -0400336 }
337 return nullptr;
338 };
John Stiles8e3b6be2020-10-13 11:14:08 -0400339 auto argList = [&](const ExpressionArray& originalArgs) -> ExpressionArray {
340 ExpressionArray args;
John Stilesf4bda742020-10-14 16:57:41 -0400341 args.reserve_back(originalArgs.size());
John Stiles44e96be2020-08-31 13:16:04 -0400342 for (const std::unique_ptr<Expression>& arg : originalArgs) {
343 args.push_back(expr(arg));
344 }
345 return args;
346 };
347
Ethan Nicholase6592142020-09-08 10:22:09 -0400348 switch (expression.kind()) {
349 case Expression::Kind::kBinary: {
John Stiles6a1a98c2021-01-14 18:35:34 -0500350 const BinaryExpression& binaryExpr = expression.as<BinaryExpression>();
351 const Type* type = copy_if_needed(&binaryExpr.type(), symbolTableForExpression);
John Stiles44e96be2020-08-31 13:16:04 -0400352 return std::make_unique<BinaryExpression>(offset,
John Stiles6a1a98c2021-01-14 18:35:34 -0500353 expr(binaryExpr.left()),
354 binaryExpr.getOperator(),
355 expr(binaryExpr.right()),
356 type);
John Stiles44e96be2020-08-31 13:16:04 -0400357 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400358 case Expression::Kind::kBoolLiteral:
359 case Expression::Kind::kIntLiteral:
360 case Expression::Kind::kFloatLiteral:
John Stiles44e96be2020-08-31 13:16:04 -0400361 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400362 case Expression::Kind::kConstructor: {
John Stiles44e96be2020-08-31 13:16:04 -0400363 const Constructor& constructor = expression.as<Constructor>();
John Stiles6a1a98c2021-01-14 18:35:34 -0500364 const Type* type = copy_if_needed(&constructor.type(), symbolTableForExpression);
John Stilesd7cc0932020-11-30 12:24:27 -0500365 return std::make_unique<Constructor>(offset, type, argList(constructor.arguments()));
John Stiles44e96be2020-08-31 13:16:04 -0400366 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400367 case Expression::Kind::kExternalFunctionCall: {
John Stiles44e96be2020-08-31 13:16:04 -0400368 const ExternalFunctionCall& externalCall = expression.as<ExternalFunctionCall>();
Ethan Nicholas444ccc62020-10-09 10:16:22 -0400369 return std::make_unique<ExternalFunctionCall>(offset, &externalCall.function(),
Ethan Nicholas6e86ec92020-09-30 14:29:56 -0400370 argList(externalCall.arguments()));
John Stiles44e96be2020-08-31 13:16:04 -0400371 }
Brian Osmanbe0b3b72021-01-06 14:27:35 -0500372 case Expression::Kind::kExternalFunctionReference:
John Stiles44e96be2020-08-31 13:16:04 -0400373 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400374 case Expression::Kind::kFieldAccess: {
John Stiles44e96be2020-08-31 13:16:04 -0400375 const FieldAccess& f = expression.as<FieldAccess>();
Ethan Nicholas7a95b202020-10-09 11:55:40 -0400376 return std::make_unique<FieldAccess>(expr(f.base()), f.fieldIndex(), f.ownerKind());
John Stiles44e96be2020-08-31 13:16:04 -0400377 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400378 case Expression::Kind::kFunctionCall: {
John Stiles44e96be2020-08-31 13:16:04 -0400379 const FunctionCall& funcCall = expression.as<FunctionCall>();
John Stiles6a1a98c2021-01-14 18:35:34 -0500380 const Type* type = copy_if_needed(&funcCall.type(), symbolTableForExpression);
381 return std::make_unique<FunctionCall>(offset, type, &funcCall.function(),
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400382 argList(funcCall.arguments()));
John Stiles44e96be2020-08-31 13:16:04 -0400383 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400384 case Expression::Kind::kFunctionReference:
Brian Osman2b3b35f2020-09-08 09:17:36 -0400385 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400386 case Expression::Kind::kIndex: {
John Stiles44e96be2020-08-31 13:16:04 -0400387 const IndexExpression& idx = expression.as<IndexExpression>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -0400388 return std::make_unique<IndexExpression>(*fContext, expr(idx.base()),
389 expr(idx.index()));
John Stiles44e96be2020-08-31 13:16:04 -0400390 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400391 case Expression::Kind::kPrefix: {
John Stiles44e96be2020-08-31 13:16:04 -0400392 const PrefixExpression& p = expression.as<PrefixExpression>();
Ethan Nicholas444ccc62020-10-09 10:16:22 -0400393 return std::make_unique<PrefixExpression>(p.getOperator(), expr(p.operand()));
John Stiles44e96be2020-08-31 13:16:04 -0400394 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400395 case Expression::Kind::kPostfix: {
John Stiles44e96be2020-08-31 13:16:04 -0400396 const PostfixExpression& p = expression.as<PostfixExpression>();
Ethan Nicholas444ccc62020-10-09 10:16:22 -0400397 return std::make_unique<PostfixExpression>(expr(p.operand()), p.getOperator());
John Stiles44e96be2020-08-31 13:16:04 -0400398 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400399 case Expression::Kind::kSetting:
John Stiles44e96be2020-08-31 13:16:04 -0400400 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400401 case Expression::Kind::kSwizzle: {
John Stiles44e96be2020-08-31 13:16:04 -0400402 const Swizzle& s = expression.as<Swizzle>();
Ethan Nicholas6b4d5812020-10-12 16:11:51 -0400403 return std::make_unique<Swizzle>(*fContext, expr(s.base()), s.components());
John Stiles44e96be2020-08-31 13:16:04 -0400404 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400405 case Expression::Kind::kTernary: {
John Stiles44e96be2020-08-31 13:16:04 -0400406 const TernaryExpression& t = expression.as<TernaryExpression>();
Ethan Nicholasdd218162020-10-08 05:48:01 -0400407 return std::make_unique<TernaryExpression>(offset, expr(t.test()),
408 expr(t.ifTrue()), expr(t.ifFalse()));
John Stiles44e96be2020-08-31 13:16:04 -0400409 }
Brian Osman83ba9302020-09-11 13:33:46 -0400410 case Expression::Kind::kTypeReference:
411 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400412 case Expression::Kind::kVariableReference: {
John Stiles44e96be2020-08-31 13:16:04 -0400413 const VariableReference& v = expression.as<VariableReference>();
Ethan Nicholas78686922020-10-08 06:46:27 -0400414 auto varMapIter = varMap->find(v.variable());
John Stilese41b4ee2020-09-28 12:28:16 -0400415 if (varMapIter != varMap->end()) {
Ethan Nicholas78686922020-10-08 06:46:27 -0400416 return clone_with_ref_kind(*varMapIter->second, v.refKind());
John Stiles44e96be2020-08-31 13:16:04 -0400417 }
418 return v.clone();
419 }
420 default:
421 SkASSERT(false);
422 return nullptr;
423 }
424}
425
426std::unique_ptr<Statement> Inliner::inlineStatement(int offset,
427 VariableRewriteMap* varMap,
428 SymbolTable* symbolTableForStatement,
John Stiles77702f12020-12-17 14:38:56 -0500429 std::unique_ptr<Expression>* resultExpr,
430 ReturnComplexity returnComplexity,
Brian Osman3887a012020-09-30 13:22:27 -0400431 const Statement& statement,
432 bool isBuiltinCode) {
John Stiles44e96be2020-08-31 13:16:04 -0400433 auto stmt = [&](const std::unique_ptr<Statement>& s) -> std::unique_ptr<Statement> {
434 if (s) {
John Stilesa5f3c312020-09-22 12:05:16 -0400435 return this->inlineStatement(offset, varMap, symbolTableForStatement, resultExpr,
John Stiles77702f12020-12-17 14:38:56 -0500436 returnComplexity, *s, isBuiltinCode);
John Stiles44e96be2020-08-31 13:16:04 -0400437 }
438 return nullptr;
439 };
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400440 auto blockStmts = [&](const Block& block) {
John Stiles8f2a0cf2020-10-13 12:48:21 -0400441 StatementArray result;
John Stilesf4bda742020-10-14 16:57:41 -0400442 result.reserve_back(block.children().size());
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400443 for (const std::unique_ptr<Statement>& child : block.children()) {
444 result.push_back(stmt(child));
445 }
446 return result;
447 };
John Stiles8f2a0cf2020-10-13 12:48:21 -0400448 auto stmts = [&](const StatementArray& ss) {
449 StatementArray result;
John Stilesf4bda742020-10-14 16:57:41 -0400450 result.reserve_back(ss.size());
John Stiles44e96be2020-08-31 13:16:04 -0400451 for (const auto& s : ss) {
452 result.push_back(stmt(s));
453 }
454 return result;
455 };
456 auto expr = [&](const std::unique_ptr<Expression>& e) -> std::unique_ptr<Expression> {
457 if (e) {
John Stilesd7cc0932020-11-30 12:24:27 -0500458 return this->inlineExpression(offset, varMap, symbolTableForStatement, *e);
John Stiles44e96be2020-08-31 13:16:04 -0400459 }
460 return nullptr;
461 };
John Stiles031a7672020-11-13 16:13:18 -0500462
463 ++fInlinedStatementCounter;
464
Ethan Nicholase6592142020-09-08 10:22:09 -0400465 switch (statement.kind()) {
466 case Statement::Kind::kBlock: {
John Stiles44e96be2020-08-31 13:16:04 -0400467 const Block& b = statement.as<Block>();
John Stilesa1e2b412020-10-20 14:51:28 -0400468 return std::make_unique<Block>(offset, blockStmts(b),
469 SymbolTable::WrapIfBuiltin(b.symbolTable()),
470 b.isScope());
John Stiles44e96be2020-08-31 13:16:04 -0400471 }
472
Ethan Nicholase6592142020-09-08 10:22:09 -0400473 case Statement::Kind::kBreak:
474 case Statement::Kind::kContinue:
475 case Statement::Kind::kDiscard:
John Stiles44e96be2020-08-31 13:16:04 -0400476 return statement.clone();
477
Ethan Nicholase6592142020-09-08 10:22:09 -0400478 case Statement::Kind::kDo: {
John Stiles44e96be2020-08-31 13:16:04 -0400479 const DoStatement& d = statement.as<DoStatement>();
Ethan Nicholas1fd61162020-09-28 13:14:19 -0400480 return std::make_unique<DoStatement>(offset, stmt(d.statement()), expr(d.test()));
John Stiles44e96be2020-08-31 13:16:04 -0400481 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400482 case Statement::Kind::kExpression: {
John Stiles44e96be2020-08-31 13:16:04 -0400483 const ExpressionStatement& e = statement.as<ExpressionStatement>();
Ethan Nicholasd503a5a2020-09-30 09:29:55 -0400484 return std::make_unique<ExpressionStatement>(expr(e.expression()));
John Stiles44e96be2020-08-31 13:16:04 -0400485 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400486 case Statement::Kind::kFor: {
John Stiles44e96be2020-08-31 13:16:04 -0400487 const ForStatement& f = statement.as<ForStatement>();
488 // need to ensure initializer is evaluated first so that we've already remapped its
489 // declarations by the time we evaluate test & next
Ethan Nicholas0d31ed52020-10-05 14:47:09 -0400490 std::unique_ptr<Statement> initializer = stmt(f.initializer());
491 return std::make_unique<ForStatement>(offset, std::move(initializer), expr(f.test()),
John Stilesa1e2b412020-10-20 14:51:28 -0400492 expr(f.next()), stmt(f.statement()),
493 SymbolTable::WrapIfBuiltin(f.symbols()));
John Stiles44e96be2020-08-31 13:16:04 -0400494 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400495 case Statement::Kind::kIf: {
John Stiles44e96be2020-08-31 13:16:04 -0400496 const IfStatement& i = statement.as<IfStatement>();
Ethan Nicholas8c44eca2020-10-07 16:47:09 -0400497 return std::make_unique<IfStatement>(offset, i.isStatic(), expr(i.test()),
498 stmt(i.ifTrue()), stmt(i.ifFalse()));
John Stiles44e96be2020-08-31 13:16:04 -0400499 }
John Stiles98c1f822020-09-09 14:18:53 -0400500 case Statement::Kind::kInlineMarker:
Ethan Nicholase6592142020-09-08 10:22:09 -0400501 case Statement::Kind::kNop:
John Stiles44e96be2020-08-31 13:16:04 -0400502 return statement.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400503 case Statement::Kind::kReturn: {
John Stiles44e96be2020-08-31 13:16:04 -0400504 const ReturnStatement& r = statement.as<ReturnStatement>();
John Stiles77702f12020-12-17 14:38:56 -0500505 if (!r.expression()) {
506 if (returnComplexity >= ReturnComplexity::kEarlyReturns) {
507 // This function doesn't return a value, but has early returns, so we've wrapped
508 // it in a for loop. Use a continue to jump to the end of the loop and "leave"
509 // the function.
John Stiles7b920442020-12-17 10:43:41 -0500510 return std::make_unique<ContinueStatement>(offset);
John Stiles44e96be2020-08-31 13:16:04 -0400511 } else {
John Stiles77702f12020-12-17 14:38:56 -0500512 // This function doesn't exit early or return a value. A return statement at the
513 // end is a no-op and can be treated as such.
John Stiles44e96be2020-08-31 13:16:04 -0400514 return std::make_unique<Nop>();
515 }
516 }
John Stiles77702f12020-12-17 14:38:56 -0500517
John Stilesc5ff4862020-12-22 13:47:05 -0500518 // If a function only contains a single return, and it doesn't reference variables from
519 // inside an Block's scope, we don't need to store the result in a variable at all. Just
520 // replace the function-call expression with the function's return expression.
John Stiles77702f12020-12-17 14:38:56 -0500521 SkASSERT(resultExpr);
522 SkASSERT(*resultExpr);
John Stilesc5ff4862020-12-22 13:47:05 -0500523 if (returnComplexity <= ReturnComplexity::kSingleSafeReturn) {
John Stiles77702f12020-12-17 14:38:56 -0500524 *resultExpr = expr(r.expression());
525 return std::make_unique<Nop>();
526 }
527
528 // For more complex functions, assign their result into a variable.
John Stiles6a1a98c2021-01-14 18:35:34 -0500529 const Type* resultType = copy_if_needed(&resultExpr->get()->type(),
530 symbolTableForStatement);
John Stiles77702f12020-12-17 14:38:56 -0500531 auto assignment =
532 std::make_unique<ExpressionStatement>(std::make_unique<BinaryExpression>(
533 offset,
534 clone_with_ref_kind(**resultExpr, VariableReference::RefKind::kWrite),
535 Token::Kind::TK_EQ,
536 expr(r.expression()),
John Stiles6a1a98c2021-01-14 18:35:34 -0500537 resultType));
John Stiles77702f12020-12-17 14:38:56 -0500538
539 // Early returns are wrapped in a for loop; we need to synthesize a continue statement
540 // to "leave" the function.
541 if (returnComplexity >= ReturnComplexity::kEarlyReturns) {
542 StatementArray block;
543 block.reserve_back(2);
544 block.push_back(std::move(assignment));
545 block.push_back(std::make_unique<ContinueStatement>(offset));
546 return std::make_unique<Block>(offset, std::move(block), /*symbols=*/nullptr,
547 /*isScope=*/true);
548 }
549 // Functions without early returns aren't wrapped in a for loop and don't need to worry
550 // about breaking out of the control flow.
551 return std::move(assignment);
552
John Stiles44e96be2020-08-31 13:16:04 -0400553 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400554 case Statement::Kind::kSwitch: {
John Stiles44e96be2020-08-31 13:16:04 -0400555 const SwitchStatement& ss = statement.as<SwitchStatement>();
556 std::vector<std::unique_ptr<SwitchCase>> cases;
John Stiles2d4f9592020-10-30 10:29:12 -0400557 cases.reserve(ss.cases().size());
558 for (const std::unique_ptr<SwitchCase>& sc : ss.cases()) {
559 cases.push_back(std::make_unique<SwitchCase>(offset, expr(sc->value()),
560 stmts(sc->statements())));
John Stiles44e96be2020-08-31 13:16:04 -0400561 }
Ethan Nicholas01b05e52020-10-22 15:53:41 -0400562 return std::make_unique<SwitchStatement>(offset, ss.isStatic(), expr(ss.value()),
John Stilesa1e2b412020-10-20 14:51:28 -0400563 std::move(cases),
Ethan Nicholas01b05e52020-10-22 15:53:41 -0400564 SymbolTable::WrapIfBuiltin(ss.symbols()));
John Stiles44e96be2020-08-31 13:16:04 -0400565 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400566 case Statement::Kind::kVarDeclaration: {
John Stiles44e96be2020-08-31 13:16:04 -0400567 const VarDeclaration& decl = statement.as<VarDeclaration>();
John Stiles35fee4c2020-12-16 18:25:14 +0000568 std::unique_ptr<Expression> initialValue = expr(decl.value());
569 int arraySize = decl.arraySize();
570 const Variable& old = decl.var();
571 // We assign unique names to inlined variables--scopes hide most of the problems in this
572 // regard, but see `InlinerAvoidsVariableNameOverlap` for a counterexample where unique
573 // names are important.
Ethan Nicholas6f4eee22021-01-11 12:37:42 -0500574 auto name = std::make_unique<String>(fMangler.uniqueName(String(old.name()),
575 symbolTableForStatement));
John Stiles35fee4c2020-12-16 18:25:14 +0000576 const String* namePtr = symbolTableForStatement->takeOwnershipOfString(std::move(name));
John Stiles6a1a98c2021-01-14 18:35:34 -0500577 const Type* baseTypePtr = copy_if_needed(&decl.baseType(), symbolTableForStatement);
578 const Type* typePtr = copy_if_needed(&old.type(), symbolTableForStatement);
John Stiles35fee4c2020-12-16 18:25:14 +0000579 const Variable* clone = symbolTableForStatement->takeOwnershipOfSymbol(
580 std::make_unique<Variable>(offset,
581 &old.modifiers(),
582 namePtr->c_str(),
583 typePtr,
584 isBuiltinCode,
585 old.storage(),
586 initialValue.get()));
587 (*varMap)[&old] = std::make_unique<VariableReference>(offset, clone);
588 return std::make_unique<VarDeclaration>(clone, baseTypePtr, arraySize,
589 std::move(initialValue));
John Stiles44e96be2020-08-31 13:16:04 -0400590 }
John Stiles44e96be2020-08-31 13:16:04 -0400591 default:
592 SkASSERT(false);
593 return nullptr;
594 }
595}
596
John Stiles7b920442020-12-17 10:43:41 -0500597Inliner::InlineVariable Inliner::makeInlineVariable(const String& baseName,
598 const Type* type,
599 SymbolTable* symbolTable,
600 Modifiers modifiers,
601 bool isBuiltinCode,
602 std::unique_ptr<Expression>* initialValue) {
603 // $floatLiteral or $intLiteral aren't real types that we can use for scratch variables, so
604 // replace them if they ever appear here. If this happens, we likely forgot to coerce a type
605 // somewhere during compilation.
John Stiles14975272021-01-12 11:41:14 -0500606 if (type->isLiteral()) {
607 SkDEBUGFAIL("found a $literal type while inlining");
608 type = &type->scalarTypeForLiteral();
John Stiles7b920442020-12-17 10:43:41 -0500609 }
610
611 // Provide our new variable with a unique name, and add it to our symbol table.
612 const String* namePtr = symbolTable->takeOwnershipOfString(
Ethan Nicholas6f4eee22021-01-11 12:37:42 -0500613 std::make_unique<String>(fMangler.uniqueName(baseName, symbolTable)));
John Stiles7b920442020-12-17 10:43:41 -0500614 StringFragment nameFrag{namePtr->c_str(), namePtr->length()};
615
616 // Create our new variable and add it to the symbol table.
617 InlineVariable result;
618 result.fVarSymbol =
619 symbolTable->add(std::make_unique<Variable>(/*offset=*/-1,
620 fModifiers->addToPool(Modifiers()),
621 nameFrag,
622 type,
623 isBuiltinCode,
624 Variable::Storage::kLocal,
625 initialValue->get()));
626
627 // Prepare the variable declaration (taking extra care with `out` params to not clobber any
628 // initial value).
629 if (*initialValue && (modifiers.fFlags & Modifiers::kOut_Flag)) {
630 result.fVarDecl = std::make_unique<VarDeclaration>(result.fVarSymbol, type, /*arraySize=*/0,
631 (*initialValue)->clone());
632 } else {
633 result.fVarDecl = std::make_unique<VarDeclaration>(result.fVarSymbol, type, /*arraySize=*/0,
634 std::move(*initialValue));
635 }
636 return result;
637}
638
John Stiles6eadf132020-09-08 10:16:10 -0400639Inliner::InlinedCall Inliner::inlineCall(FunctionCall* call,
John Stiles78047582020-12-16 16:17:41 -0500640 std::shared_ptr<SymbolTable> symbolTable,
Brian Osman3887a012020-09-30 13:22:27 -0400641 const FunctionDeclaration* caller) {
John Stiles44e96be2020-08-31 13:16:04 -0400642 // Inlining is more complicated here than in a typical compiler, because we have to have a
643 // high-level IR and can't just drop statements into the middle of an expression or even use
644 // gotos.
645 //
646 // Since we can't insert statements into an expression, we run the inline function as extra
647 // statements before the statement we're currently processing, relying on a lack of execution
648 // order guarantees. Since we can't use gotos (which are normally used to replace return
649 // statements), we wrap the whole function in a loop and use break statements to jump to the
650 // end.
651 SkASSERT(fSettings);
652 SkASSERT(fContext);
653 SkASSERT(call);
Ethan Nicholased84b732020-10-08 11:45:44 -0400654 SkASSERT(this->isSafeToInline(call->function().definition()));
John Stiles44e96be2020-08-31 13:16:04 -0400655
John Stiles8e3b6be2020-10-13 11:14:08 -0400656 ExpressionArray& arguments = call->arguments();
John Stiles6eadf132020-09-08 10:16:10 -0400657 const int offset = call->fOffset;
Ethan Nicholased84b732020-10-08 11:45:44 -0400658 const FunctionDefinition& function = *call->function().definition();
John Stiles77702f12020-12-17 14:38:56 -0500659 const ReturnComplexity returnComplexity = GetReturnComplexity(function);
660 bool hasEarlyReturn = (returnComplexity >= ReturnComplexity::kEarlyReturns);
John Stiles6eadf132020-09-08 10:16:10 -0400661
John Stiles44e96be2020-08-31 13:16:04 -0400662 InlinedCall inlinedCall;
John Stiles8f2a0cf2020-10-13 12:48:21 -0400663 inlinedCall.fInlinedBody = std::make_unique<Block>(offset, StatementArray{},
John Stiles6eadf132020-09-08 10:16:10 -0400664 /*symbols=*/nullptr,
665 /*isScope=*/false);
John Stiles98c1f822020-09-09 14:18:53 -0400666
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400667 Block& inlinedBody = *inlinedCall.fInlinedBody;
John Stiles82f373c2020-10-20 13:58:05 -0400668 inlinedBody.children().reserve_back(
669 1 + // Inline marker
670 1 + // Result variable
671 arguments.size() + // Function arguments (passing in)
672 arguments.size() + // Function arguments (copy out-params back)
John Stiles7b920442020-12-17 10:43:41 -0500673 1); // Block for inlined code
John Stiles98c1f822020-09-09 14:18:53 -0400674
Ethan Nicholasceb62142020-10-09 16:51:18 -0400675 inlinedBody.children().push_back(std::make_unique<InlineMarker>(&call->function()));
John Stiles44e96be2020-08-31 13:16:04 -0400676
John Stiles44e96be2020-08-31 13:16:04 -0400677 // Create a variable to hold the result in the extra statements (excepting void).
John Stilese41b4ee2020-09-28 12:28:16 -0400678 std::unique_ptr<Expression> resultExpr;
John Stiles54e7c052021-01-11 14:22:36 -0500679 if (function.declaration().returnType() != *fContext->fTypes.fVoid) {
John Stiles44e96be2020-08-31 13:16:04 -0400680 std::unique_ptr<Expression> noInitialValue;
John Stiles7b920442020-12-17 10:43:41 -0500681 InlineVariable var = this->makeInlineVariable(function.declaration().name(),
682 &function.declaration().returnType(),
683 symbolTable.get(), Modifiers{},
684 caller->isBuiltin(), &noInitialValue);
685 inlinedBody.children().push_back(std::move(var.fVarDecl));
686 resultExpr = std::make_unique<VariableReference>(/*offset=*/-1, var.fVarSymbol);
John Stiles35fee4c2020-12-16 18:25:14 +0000687 }
John Stiles44e96be2020-08-31 13:16:04 -0400688
689 // Create variables in the extra statements to hold the arguments, and assign the arguments to
690 // them.
691 VariableRewriteMap varMap;
John Stilese41b4ee2020-09-28 12:28:16 -0400692 std::vector<int> argsToCopyBack;
John Stiles44e96be2020-08-31 13:16:04 -0400693 for (int i = 0; i < (int) arguments.size(); ++i) {
Ethan Nicholas0a5d0962020-10-14 13:33:18 -0400694 const Variable* param = function.declaration().parameters()[i];
Ethan Nicholas041fd0a2020-10-07 16:42:04 -0400695 bool isOutParam = param->modifiers().fFlags & Modifiers::kOut_Flag;
John Stiles44e96be2020-08-31 13:16:04 -0400696
John Stiles44733aa2020-09-29 17:42:23 -0400697 // If this argument can be inlined trivially (e.g. a swizzle, or a constant array index)...
John Stilesc30fbca2020-11-19 16:25:49 -0500698 if (Analysis::IsTrivialExpression(*arguments[i])) {
John Stilese41b4ee2020-09-28 12:28:16 -0400699 // ... and it's an `out` param, or it isn't written to within the inline function...
Ethan Nicholas0a5d0962020-10-14 13:33:18 -0400700 if (isOutParam || !Analysis::StatementWritesToVariable(*function.body(), *param)) {
John Stilesf201af82020-09-29 16:57:55 -0400701 // ... we don't need to copy it at all! We can just use the existing expression.
702 varMap[param] = arguments[i]->clone();
John Stiles44e96be2020-08-31 13:16:04 -0400703 continue;
704 }
705 }
John Stilese41b4ee2020-09-28 12:28:16 -0400706 if (isOutParam) {
707 argsToCopyBack.push_back(i);
708 }
John Stiles7b920442020-12-17 10:43:41 -0500709 InlineVariable var = this->makeInlineVariable(param->name(), &arguments[i]->type(),
710 symbolTable.get(), param->modifiers(),
711 caller->isBuiltin(), &arguments[i]);
712 inlinedBody.children().push_back(std::move(var.fVarDecl));
713 varMap[param] = std::make_unique<VariableReference>(/*offset=*/-1, var.fVarSymbol);
John Stiles44e96be2020-08-31 13:16:04 -0400714 }
715
Ethan Nicholas0a5d0962020-10-14 13:33:18 -0400716 const Block& body = function.body()->as<Block>();
John Stiles7b920442020-12-17 10:43:41 -0500717 StatementArray* inlineStatements;
718
John Stiles44e96be2020-08-31 13:16:04 -0400719 if (hasEarlyReturn) {
720 // Since we output to backends that don't have a goto statement (which would normally be
John Stiles7b920442020-12-17 10:43:41 -0500721 // used to perform an early return), we fake it by wrapping the function in a single-
722 // iteration for loop, and use a continue statement to jump to the end of the loop
723 // prematurely.
724
725 // int _1_loop = 0;
726 symbolTable = std::make_shared<SymbolTable>(std::move(symbolTable), caller->isBuiltin());
John Stiles54e7c052021-01-11 14:22:36 -0500727 const Type* intType = fContext->fTypes.fInt.get();
John Stiles7b920442020-12-17 10:43:41 -0500728 std::unique_ptr<Expression> initialValue = std::make_unique<IntLiteral>(/*offset=*/-1,
729 /*value=*/0,
730 intType);
731 InlineVariable loopVar = this->makeInlineVariable("loop", intType, symbolTable.get(),
732 Modifiers{}, caller->isBuiltin(),
733 &initialValue);
734
735 // _1_loop < 1;
736 std::unique_ptr<Expression> test = std::make_unique<BinaryExpression>(
John Stiles44e96be2020-08-31 13:16:04 -0400737 /*offset=*/-1,
John Stiles7b920442020-12-17 10:43:41 -0500738 std::make_unique<VariableReference>(/*offset=*/-1, loopVar.fVarSymbol),
739 Token::Kind::TK_LT,
740 std::make_unique<IntLiteral>(/*offset=*/-1, /*value=*/1, intType),
John Stiles54e7c052021-01-11 14:22:36 -0500741 fContext->fTypes.fBool.get());
John Stiles7b920442020-12-17 10:43:41 -0500742
743 // _1_loop++
744 std::unique_ptr<Expression> increment = std::make_unique<PostfixExpression>(
745 std::make_unique<VariableReference>(/*offset=*/-1, loopVar.fVarSymbol,
746 VariableReference::RefKind::kReadWrite),
747 Token::Kind::TK_PLUSPLUS);
748
749 // {...}
750 auto innerBlock = std::make_unique<Block>(offset, StatementArray{},
751 /*symbols=*/nullptr, /*isScope=*/true);
752 inlineStatements = &innerBlock->children();
753
754 // for (int _1_loop = 0; _1_loop < 1; _1_loop++) {...}
755 inlinedBody.children().push_back(std::make_unique<ForStatement>(/*offset=*/-1,
756 std::move(loopVar.fVarDecl),
757 std::move(test),
758 std::move(increment),
759 std::move(innerBlock),
760 symbolTable));
John Stiles44e96be2020-08-31 13:16:04 -0400761 } else {
John Stilesfa9a0832020-12-17 10:43:58 -0500762 // No early returns, so we can just dump the code into our existing scopeless block.
763 inlineStatements = &inlinedBody.children();
John Stiles7b920442020-12-17 10:43:41 -0500764 }
765
766 inlineStatements->reserve_back(body.children().size() + argsToCopyBack.size());
767 for (const std::unique_ptr<Statement>& stmt : body.children()) {
768 inlineStatements->push_back(this->inlineStatement(offset, &varMap, symbolTable.get(),
John Stiles77702f12020-12-17 14:38:56 -0500769 &resultExpr, returnComplexity, *stmt,
John Stiles7b920442020-12-17 10:43:41 -0500770 caller->isBuiltin()));
John Stiles44e96be2020-08-31 13:16:04 -0400771 }
772
John Stilese41b4ee2020-09-28 12:28:16 -0400773 // Copy back the values of `out` parameters into their real destinations.
774 for (int i : argsToCopyBack) {
Ethan Nicholas0a5d0962020-10-14 13:33:18 -0400775 const Variable* p = function.declaration().parameters()[i];
John Stilese41b4ee2020-09-28 12:28:16 -0400776 SkASSERT(varMap.find(p) != varMap.end());
John Stiles7b920442020-12-17 10:43:41 -0500777 inlineStatements->push_back(
John Stilese41b4ee2020-09-28 12:28:16 -0400778 std::make_unique<ExpressionStatement>(std::make_unique<BinaryExpression>(
779 offset,
Ethan Nicholas453f67f2020-10-09 10:43:45 -0400780 clone_with_ref_kind(*arguments[i], VariableReference::RefKind::kWrite),
John Stilese41b4ee2020-09-28 12:28:16 -0400781 Token::Kind::TK_EQ,
782 std::move(varMap[p]),
783 &arguments[i]->type())));
John Stiles44e96be2020-08-31 13:16:04 -0400784 }
785
John Stilese41b4ee2020-09-28 12:28:16 -0400786 if (resultExpr != nullptr) {
787 // Return our result variable as our replacement expression.
John Stilese41b4ee2020-09-28 12:28:16 -0400788 inlinedCall.fReplacementExpr = std::move(resultExpr);
John Stiles44e96be2020-08-31 13:16:04 -0400789 } else {
790 // It's a void function, so it doesn't actually result in anything, but we have to return
791 // something non-null as a standin.
Ethan Nicholas041fd0a2020-10-07 16:42:04 -0400792 inlinedCall.fReplacementExpr = std::make_unique<BoolLiteral>(*fContext,
793 offset,
John Stiles44e96be2020-08-31 13:16:04 -0400794 /*value=*/false);
795 }
796
John Stiles44e96be2020-08-31 13:16:04 -0400797 return inlinedCall;
798}
799
John Stiles2d7973a2020-10-02 15:01:03 -0400800bool Inliner::isSafeToInline(const FunctionDefinition* functionDef) {
John Stiles44e96be2020-08-31 13:16:04 -0400801 SkASSERT(fSettings);
802
John Stiles1c03d332020-10-13 10:30:23 -0400803 // A threshold of zero indicates that the inliner is completely disabled, so we can just return.
804 if (fSettings->fInlineThreshold <= 0) {
805 return false;
806 }
807
John Stiles031a7672020-11-13 16:13:18 -0500808 // Enforce a limit on inlining to avoid pathological cases. (inliner/ExponentialGrowth.sksl)
809 if (fInlinedStatementCounter >= kInlinedStatementLimit) {
810 return false;
811 }
812
John Stiles2d7973a2020-10-02 15:01:03 -0400813 if (functionDef == nullptr) {
John Stiles44e96be2020-08-31 13:16:04 -0400814 // Can't inline something if we don't actually have its definition.
815 return false;
816 }
John Stiles2d7973a2020-10-02 15:01:03 -0400817
John Stiles74ebd7e2020-12-17 14:41:50 -0500818 // We don't have any mechanism to simulate early returns within a construct that supports
819 // continues (for/do/while), so we can't inline if there's a return inside one.
820 bool hasReturnInContinuableConstruct =
821 (count_returns_in_continuable_constructs(*functionDef) > 0);
822 return !hasReturnInContinuableConstruct;
John Stiles44e96be2020-08-31 13:16:04 -0400823}
824
John Stiles2d7973a2020-10-02 15:01:03 -0400825// A candidate function for inlining, containing everything that `inlineCall` needs.
826struct InlineCandidate {
John Stiles78047582020-12-16 16:17:41 -0500827 std::shared_ptr<SymbolTable> fSymbols; // the SymbolTable of the candidate
John Stiles2d7973a2020-10-02 15:01:03 -0400828 std::unique_ptr<Statement>* fParentStmt; // the parent Statement of the enclosing stmt
829 std::unique_ptr<Statement>* fEnclosingStmt; // the Statement containing the candidate
830 std::unique_ptr<Expression>* fCandidateExpr; // the candidate FunctionCall to be inlined
831 FunctionDefinition* fEnclosingFunction; // the Function containing the candidate
John Stiles2d7973a2020-10-02 15:01:03 -0400832};
John Stiles93442622020-09-11 12:11:27 -0400833
John Stiles2d7973a2020-10-02 15:01:03 -0400834struct InlineCandidateList {
835 std::vector<InlineCandidate> fCandidates;
836};
837
838class InlineCandidateAnalyzer {
John Stiles70957c82020-10-02 16:42:10 -0400839public:
840 // A list of all the inlining candidates we found during analysis.
841 InlineCandidateList* fCandidateList;
John Stiles2d7973a2020-10-02 15:01:03 -0400842
John Stiles70957c82020-10-02 16:42:10 -0400843 // A stack of the symbol tables; since most nodes don't have one, expected to be shallower than
844 // the enclosing-statement stack.
John Stiles78047582020-12-16 16:17:41 -0500845 std::vector<std::shared_ptr<SymbolTable>> fSymbolTableStack;
John Stiles70957c82020-10-02 16:42:10 -0400846 // A stack of "enclosing" statements--these would be suitable for the inliner to use for adding
847 // new instructions. Not all statements are suitable (e.g. a for-loop's initializer). The
848 // inliner might replace a statement with a block containing the statement.
849 std::vector<std::unique_ptr<Statement>*> fEnclosingStmtStack;
850 // The function that we're currently processing (i.e. inlining into).
851 FunctionDefinition* fEnclosingFunction = nullptr;
John Stiles93442622020-09-11 12:11:27 -0400852
Brian Osman0006ad02020-11-18 15:38:39 -0500853 void visit(const std::vector<std::unique_ptr<ProgramElement>>& elements,
John Stiles78047582020-12-16 16:17:41 -0500854 std::shared_ptr<SymbolTable> symbols,
Brian Osman0006ad02020-11-18 15:38:39 -0500855 InlineCandidateList* candidateList) {
John Stiles70957c82020-10-02 16:42:10 -0400856 fCandidateList = candidateList;
Brian Osman0006ad02020-11-18 15:38:39 -0500857 fSymbolTableStack.push_back(symbols);
John Stiles93442622020-09-11 12:11:27 -0400858
Brian Osman0006ad02020-11-18 15:38:39 -0500859 for (const std::unique_ptr<ProgramElement>& pe : elements) {
Brian Osman1179fcf2020-10-08 16:04:40 -0400860 this->visitProgramElement(pe.get());
John Stiles93442622020-09-11 12:11:27 -0400861 }
862
John Stiles70957c82020-10-02 16:42:10 -0400863 fSymbolTableStack.pop_back();
864 fCandidateList = nullptr;
865 }
866
867 void visitProgramElement(ProgramElement* pe) {
868 switch (pe->kind()) {
869 case ProgramElement::Kind::kFunction: {
870 FunctionDefinition& funcDef = pe->as<FunctionDefinition>();
Brian Osman0006ad02020-11-18 15:38:39 -0500871 fEnclosingFunction = &funcDef;
872 this->visitStatement(&funcDef.body());
John Stiles70957c82020-10-02 16:42:10 -0400873 break;
John Stiles93442622020-09-11 12:11:27 -0400874 }
John Stiles70957c82020-10-02 16:42:10 -0400875 default:
876 // The inliner can't operate outside of a function's scope.
877 break;
878 }
879 }
880
881 void visitStatement(std::unique_ptr<Statement>* stmt,
882 bool isViableAsEnclosingStatement = true) {
883 if (!*stmt) {
884 return;
John Stiles93442622020-09-11 12:11:27 -0400885 }
886
John Stiles70957c82020-10-02 16:42:10 -0400887 size_t oldEnclosingStmtStackSize = fEnclosingStmtStack.size();
888 size_t oldSymbolStackSize = fSymbolTableStack.size();
John Stiles93442622020-09-11 12:11:27 -0400889
John Stiles70957c82020-10-02 16:42:10 -0400890 if (isViableAsEnclosingStatement) {
891 fEnclosingStmtStack.push_back(stmt);
John Stiles93442622020-09-11 12:11:27 -0400892 }
893
John Stiles70957c82020-10-02 16:42:10 -0400894 switch ((*stmt)->kind()) {
895 case Statement::Kind::kBreak:
896 case Statement::Kind::kContinue:
897 case Statement::Kind::kDiscard:
898 case Statement::Kind::kInlineMarker:
899 case Statement::Kind::kNop:
900 break;
901
902 case Statement::Kind::kBlock: {
903 Block& block = (*stmt)->as<Block>();
904 if (block.symbolTable()) {
John Stiles78047582020-12-16 16:17:41 -0500905 fSymbolTableStack.push_back(block.symbolTable());
John Stiles70957c82020-10-02 16:42:10 -0400906 }
907
908 for (std::unique_ptr<Statement>& stmt : block.children()) {
909 this->visitStatement(&stmt);
910 }
911 break;
John Stiles93442622020-09-11 12:11:27 -0400912 }
John Stiles70957c82020-10-02 16:42:10 -0400913 case Statement::Kind::kDo: {
914 DoStatement& doStmt = (*stmt)->as<DoStatement>();
915 // The loop body is a candidate for inlining.
916 this->visitStatement(&doStmt.statement());
917 // The inliner isn't smart enough to inline the test-expression for a do-while
918 // loop at this time. There are two limitations:
919 // - We would need to insert the inlined-body block at the very end of the do-
920 // statement's inner fStatement. We don't support that today, but it's doable.
921 // - We cannot inline the test expression if the loop uses `continue` anywhere; that
922 // would skip over the inlined block that evaluates the test expression. There
923 // isn't a good fix for this--any workaround would be more complex than the cost
924 // of a function call. However, loops that don't use `continue` would still be
925 // viable candidates for inlining.
926 break;
John Stiles93442622020-09-11 12:11:27 -0400927 }
John Stiles70957c82020-10-02 16:42:10 -0400928 case Statement::Kind::kExpression: {
929 ExpressionStatement& expr = (*stmt)->as<ExpressionStatement>();
930 this->visitExpression(&expr.expression());
931 break;
932 }
933 case Statement::Kind::kFor: {
934 ForStatement& forStmt = (*stmt)->as<ForStatement>();
Ethan Nicholas0d31ed52020-10-05 14:47:09 -0400935 if (forStmt.symbols()) {
John Stiles78047582020-12-16 16:17:41 -0500936 fSymbolTableStack.push_back(forStmt.symbols());
John Stiles70957c82020-10-02 16:42:10 -0400937 }
938
939 // The initializer and loop body are candidates for inlining.
Ethan Nicholas0d31ed52020-10-05 14:47:09 -0400940 this->visitStatement(&forStmt.initializer(),
John Stiles70957c82020-10-02 16:42:10 -0400941 /*isViableAsEnclosingStatement=*/false);
Ethan Nicholas0d31ed52020-10-05 14:47:09 -0400942 this->visitStatement(&forStmt.statement());
John Stiles70957c82020-10-02 16:42:10 -0400943
944 // The inliner isn't smart enough to inline the test- or increment-expressions
945 // of a for loop loop at this time. There are a handful of limitations:
946 // - We would need to insert the test-expression block at the very beginning of the
947 // for-loop's inner fStatement, and the increment-expression block at the very
948 // end. We don't support that today, but it's doable.
949 // - The for-loop's built-in test-expression would need to be dropped entirely,
950 // and the loop would be halted via a break statement at the end of the inlined
951 // test-expression. This is again something we don't support today, but it could
952 // be implemented.
953 // - We cannot inline the increment-expression if the loop uses `continue` anywhere;
954 // that would skip over the inlined block that evaluates the increment expression.
955 // There isn't a good fix for this--any workaround would be more complex than the
956 // cost of a function call. However, loops that don't use `continue` would still
957 // be viable candidates for increment-expression inlining.
958 break;
959 }
960 case Statement::Kind::kIf: {
961 IfStatement& ifStmt = (*stmt)->as<IfStatement>();
Ethan Nicholas8c44eca2020-10-07 16:47:09 -0400962 this->visitExpression(&ifStmt.test());
963 this->visitStatement(&ifStmt.ifTrue());
964 this->visitStatement(&ifStmt.ifFalse());
John Stiles70957c82020-10-02 16:42:10 -0400965 break;
966 }
967 case Statement::Kind::kReturn: {
968 ReturnStatement& returnStmt = (*stmt)->as<ReturnStatement>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -0400969 this->visitExpression(&returnStmt.expression());
John Stiles70957c82020-10-02 16:42:10 -0400970 break;
971 }
972 case Statement::Kind::kSwitch: {
973 SwitchStatement& switchStmt = (*stmt)->as<SwitchStatement>();
Ethan Nicholas01b05e52020-10-22 15:53:41 -0400974 if (switchStmt.symbols()) {
John Stiles78047582020-12-16 16:17:41 -0500975 fSymbolTableStack.push_back(switchStmt.symbols());
John Stiles70957c82020-10-02 16:42:10 -0400976 }
977
Ethan Nicholas01b05e52020-10-22 15:53:41 -0400978 this->visitExpression(&switchStmt.value());
John Stiles2d4f9592020-10-30 10:29:12 -0400979 for (const std::unique_ptr<SwitchCase>& switchCase : switchStmt.cases()) {
John Stiles70957c82020-10-02 16:42:10 -0400980 // The switch-case's fValue cannot be a FunctionCall; skip it.
John Stiles2d4f9592020-10-30 10:29:12 -0400981 for (std::unique_ptr<Statement>& caseBlock : switchCase->statements()) {
John Stiles70957c82020-10-02 16:42:10 -0400982 this->visitStatement(&caseBlock);
983 }
984 }
985 break;
986 }
987 case Statement::Kind::kVarDeclaration: {
988 VarDeclaration& varDeclStmt = (*stmt)->as<VarDeclaration>();
989 // Don't need to scan the declaration's sizes; those are always IntLiterals.
Ethan Nicholasc51f33e2020-10-13 13:49:44 -0400990 this->visitExpression(&varDeclStmt.value());
John Stiles70957c82020-10-02 16:42:10 -0400991 break;
992 }
John Stiles70957c82020-10-02 16:42:10 -0400993 default:
994 SkUNREACHABLE;
John Stiles93442622020-09-11 12:11:27 -0400995 }
996
John Stiles70957c82020-10-02 16:42:10 -0400997 // Pop our symbol and enclosing-statement stacks.
998 fSymbolTableStack.resize(oldSymbolStackSize);
999 fEnclosingStmtStack.resize(oldEnclosingStmtStackSize);
1000 }
1001
1002 void visitExpression(std::unique_ptr<Expression>* expr) {
1003 if (!*expr) {
1004 return;
John Stiles93442622020-09-11 12:11:27 -04001005 }
John Stiles70957c82020-10-02 16:42:10 -04001006
1007 switch ((*expr)->kind()) {
1008 case Expression::Kind::kBoolLiteral:
1009 case Expression::Kind::kDefined:
Brian Osmanbe0b3b72021-01-06 14:27:35 -05001010 case Expression::Kind::kExternalFunctionReference:
John Stiles70957c82020-10-02 16:42:10 -04001011 case Expression::Kind::kFieldAccess:
1012 case Expression::Kind::kFloatLiteral:
1013 case Expression::Kind::kFunctionReference:
1014 case Expression::Kind::kIntLiteral:
John Stiles70957c82020-10-02 16:42:10 -04001015 case Expression::Kind::kSetting:
1016 case Expression::Kind::kTypeReference:
1017 case Expression::Kind::kVariableReference:
1018 // Nothing to scan here.
1019 break;
1020
1021 case Expression::Kind::kBinary: {
1022 BinaryExpression& binaryExpr = (*expr)->as<BinaryExpression>();
John Stiles2d4f9592020-10-30 10:29:12 -04001023 this->visitExpression(&binaryExpr.left());
John Stiles70957c82020-10-02 16:42:10 -04001024
1025 // Logical-and and logical-or binary expressions do not inline the right side,
1026 // because that would invalidate short-circuiting. That is, when evaluating
1027 // expressions like these:
1028 // (false && x()) // always false
1029 // (true || y()) // always true
1030 // It is illegal for side-effects from x() or y() to occur. The simplest way to
1031 // enforce that rule is to avoid inlining the right side entirely. However, it is
1032 // safe for other types of binary expression to inline both sides.
1033 Token::Kind op = binaryExpr.getOperator();
1034 bool shortCircuitable = (op == Token::Kind::TK_LOGICALAND ||
1035 op == Token::Kind::TK_LOGICALOR);
1036 if (!shortCircuitable) {
John Stiles2d4f9592020-10-30 10:29:12 -04001037 this->visitExpression(&binaryExpr.right());
John Stiles70957c82020-10-02 16:42:10 -04001038 }
1039 break;
1040 }
1041 case Expression::Kind::kConstructor: {
1042 Constructor& constructorExpr = (*expr)->as<Constructor>();
1043 for (std::unique_ptr<Expression>& arg : constructorExpr.arguments()) {
1044 this->visitExpression(&arg);
1045 }
1046 break;
1047 }
1048 case Expression::Kind::kExternalFunctionCall: {
1049 ExternalFunctionCall& funcCallExpr = (*expr)->as<ExternalFunctionCall>();
1050 for (std::unique_ptr<Expression>& arg : funcCallExpr.arguments()) {
1051 this->visitExpression(&arg);
1052 }
1053 break;
1054 }
1055 case Expression::Kind::kFunctionCall: {
1056 FunctionCall& funcCallExpr = (*expr)->as<FunctionCall>();
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001057 for (std::unique_ptr<Expression>& arg : funcCallExpr.arguments()) {
John Stiles70957c82020-10-02 16:42:10 -04001058 this->visitExpression(&arg);
1059 }
1060 this->addInlineCandidate(expr);
1061 break;
1062 }
1063 case Expression::Kind::kIndex:{
1064 IndexExpression& indexExpr = (*expr)->as<IndexExpression>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04001065 this->visitExpression(&indexExpr.base());
1066 this->visitExpression(&indexExpr.index());
John Stiles70957c82020-10-02 16:42:10 -04001067 break;
1068 }
1069 case Expression::Kind::kPostfix: {
1070 PostfixExpression& postfixExpr = (*expr)->as<PostfixExpression>();
Ethan Nicholas444ccc62020-10-09 10:16:22 -04001071 this->visitExpression(&postfixExpr.operand());
John Stiles70957c82020-10-02 16:42:10 -04001072 break;
1073 }
1074 case Expression::Kind::kPrefix: {
1075 PrefixExpression& prefixExpr = (*expr)->as<PrefixExpression>();
Ethan Nicholas444ccc62020-10-09 10:16:22 -04001076 this->visitExpression(&prefixExpr.operand());
John Stiles70957c82020-10-02 16:42:10 -04001077 break;
1078 }
1079 case Expression::Kind::kSwizzle: {
1080 Swizzle& swizzleExpr = (*expr)->as<Swizzle>();
Ethan Nicholas6b4d5812020-10-12 16:11:51 -04001081 this->visitExpression(&swizzleExpr.base());
John Stiles70957c82020-10-02 16:42:10 -04001082 break;
1083 }
1084 case Expression::Kind::kTernary: {
1085 TernaryExpression& ternaryExpr = (*expr)->as<TernaryExpression>();
1086 // The test expression is a candidate for inlining.
Ethan Nicholasdd218162020-10-08 05:48:01 -04001087 this->visitExpression(&ternaryExpr.test());
John Stiles70957c82020-10-02 16:42:10 -04001088 // The true- and false-expressions cannot be inlined, because we are only allowed to
1089 // evaluate one side.
1090 break;
1091 }
1092 default:
1093 SkUNREACHABLE;
1094 }
1095 }
1096
1097 void addInlineCandidate(std::unique_ptr<Expression>* candidate) {
1098 fCandidateList->fCandidates.push_back(
1099 InlineCandidate{fSymbolTableStack.back(),
1100 find_parent_statement(fEnclosingStmtStack),
1101 fEnclosingStmtStack.back(),
1102 candidate,
John Stiles9b9415e2020-11-23 14:48:06 -05001103 fEnclosingFunction});
John Stiles70957c82020-10-02 16:42:10 -04001104 }
John Stiles2d7973a2020-10-02 15:01:03 -04001105};
John Stiles93442622020-09-11 12:11:27 -04001106
John Stiles9b9415e2020-11-23 14:48:06 -05001107static const FunctionDeclaration& candidate_func(const InlineCandidate& candidate) {
1108 return (*candidate.fCandidateExpr)->as<FunctionCall>().function();
1109}
John Stiles915a38c2020-09-14 09:38:13 -04001110
John Stiles9b9415e2020-11-23 14:48:06 -05001111bool Inliner::candidateCanBeInlined(const InlineCandidate& candidate, InlinabilityCache* cache) {
1112 const FunctionDeclaration& funcDecl = candidate_func(candidate);
John Stiles1c03d332020-10-13 10:30:23 -04001113 auto [iter, wasInserted] = cache->insert({&funcDecl, false});
John Stiles2d7973a2020-10-02 15:01:03 -04001114 if (wasInserted) {
1115 // Recursion is forbidden here to avoid an infinite death spiral of inlining.
John Stiles1c03d332020-10-13 10:30:23 -04001116 iter->second = this->isSafeToInline(funcDecl.definition()) &&
1117 !contains_recursive_call(funcDecl);
John Stiles93442622020-09-11 12:11:27 -04001118 }
1119
John Stiles2d7973a2020-10-02 15:01:03 -04001120 return iter->second;
1121}
1122
John Stiles9b9415e2020-11-23 14:48:06 -05001123int Inliner::getFunctionSize(const FunctionDeclaration& funcDecl, FunctionSizeCache* cache) {
1124 auto [iter, wasInserted] = cache->insert({&funcDecl, 0});
John Stiles2d7973a2020-10-02 15:01:03 -04001125 if (wasInserted) {
John Stiles9b9415e2020-11-23 14:48:06 -05001126 iter->second = Analysis::NodeCountUpToLimit(*funcDecl.definition(),
1127 fSettings->fInlineThreshold);
John Stiles2d7973a2020-10-02 15:01:03 -04001128 }
John Stiles2d7973a2020-10-02 15:01:03 -04001129 return iter->second;
1130}
1131
Brian Osman0006ad02020-11-18 15:38:39 -05001132void Inliner::buildCandidateList(const std::vector<std::unique_ptr<ProgramElement>>& elements,
John Stiles78047582020-12-16 16:17:41 -05001133 std::shared_ptr<SymbolTable> symbols, ProgramUsage* usage,
Brian Osman0006ad02020-11-18 15:38:39 -05001134 InlineCandidateList* candidateList) {
John Stiles2d7973a2020-10-02 15:01:03 -04001135 // This is structured much like a ProgramVisitor, but does not actually use ProgramVisitor.
1136 // The analyzer needs to keep track of the `unique_ptr<T>*` of statements and expressions so
1137 // that they can later be replaced, and ProgramVisitor does not provide this; it only provides a
1138 // `const T&`.
1139 InlineCandidateAnalyzer analyzer;
Brian Osman0006ad02020-11-18 15:38:39 -05001140 analyzer.visit(elements, symbols, candidateList);
John Stiles2d7973a2020-10-02 15:01:03 -04001141
John Stiles0ad233f2020-11-25 11:02:05 -05001142 // Early out if there are no inlining candidates.
John Stiles2d7973a2020-10-02 15:01:03 -04001143 std::vector<InlineCandidate>& candidates = candidateList->fCandidates;
John Stiles0ad233f2020-11-25 11:02:05 -05001144 if (candidates.empty()) {
1145 return;
1146 }
1147
1148 // Remove candidates that are not safe to inline.
John Stiles2d7973a2020-10-02 15:01:03 -04001149 InlinabilityCache cache;
1150 candidates.erase(std::remove_if(candidates.begin(),
1151 candidates.end(),
1152 [&](const InlineCandidate& candidate) {
1153 return !this->candidateCanBeInlined(candidate, &cache);
1154 }),
1155 candidates.end());
1156
John Stiles0ad233f2020-11-25 11:02:05 -05001157 // If the inline threshold is unlimited, or if we have no candidates left, our candidate list is
1158 // complete.
1159 if (fSettings->fInlineThreshold == INT_MAX || candidates.empty()) {
1160 return;
John Stiles2d7973a2020-10-02 15:01:03 -04001161 }
John Stiles0ad233f2020-11-25 11:02:05 -05001162
1163 // Remove candidates on a per-function basis if the effect of inlining would be to make more
1164 // than `inlineThreshold` nodes. (i.e. if Func() would be inlined six times and its size is
1165 // 10 nodes, it should be inlined if the inlineThreshold is 60 or higher.)
1166 FunctionSizeCache functionSizeCache;
1167 FunctionSizeCache candidateTotalCost;
1168 for (InlineCandidate& candidate : candidates) {
1169 const FunctionDeclaration& fnDecl = candidate_func(candidate);
1170 candidateTotalCost[&fnDecl] += this->getFunctionSize(fnDecl, &functionSizeCache);
1171 }
1172
1173 candidates.erase(
1174 std::remove_if(candidates.begin(),
1175 candidates.end(),
1176 [&](const InlineCandidate& candidate) {
1177 const FunctionDeclaration& fnDecl = candidate_func(candidate);
1178 if (fnDecl.modifiers().fFlags & Modifiers::kInline_Flag) {
1179 // Functions marked `inline` ignore size limitations.
1180 return false;
1181 }
1182 if (usage->get(fnDecl) == 1) {
1183 // If a function is only used once, it's cost-free to inline.
1184 return false;
1185 }
1186 if (candidateTotalCost[&fnDecl] <= fSettings->fInlineThreshold) {
1187 // We won't exceed the inline threshold by inlining this.
1188 return false;
1189 }
1190 // Inlining this function will add too many IRNodes.
1191 return true;
1192 }),
1193 candidates.end());
John Stiles2d7973a2020-10-02 15:01:03 -04001194}
1195
Brian Osman0006ad02020-11-18 15:38:39 -05001196bool Inliner::analyze(const std::vector<std::unique_ptr<ProgramElement>>& elements,
John Stiles78047582020-12-16 16:17:41 -05001197 std::shared_ptr<SymbolTable> symbols,
Brian Osman0006ad02020-11-18 15:38:39 -05001198 ProgramUsage* usage) {
John Stilesd34d56e2020-10-12 12:04:47 -04001199 // A threshold of zero indicates that the inliner is completely disabled, so we can just return.
1200 if (fSettings->fInlineThreshold <= 0) {
1201 return false;
1202 }
1203
John Stiles031a7672020-11-13 16:13:18 -05001204 // Enforce a limit on inlining to avoid pathological cases. (inliner/ExponentialGrowth.sksl)
1205 if (fInlinedStatementCounter >= kInlinedStatementLimit) {
1206 return false;
1207 }
1208
John Stiles2d7973a2020-10-02 15:01:03 -04001209 InlineCandidateList candidateList;
John Stiles9b9415e2020-11-23 14:48:06 -05001210 this->buildCandidateList(elements, symbols, usage, &candidateList);
John Stiles2d7973a2020-10-02 15:01:03 -04001211
John Stiles915a38c2020-09-14 09:38:13 -04001212 // Inline the candidates where we've determined that it's safe to do so.
1213 std::unordered_set<const std::unique_ptr<Statement>*> enclosingStmtSet;
1214 bool madeChanges = false;
John Stiles2d7973a2020-10-02 15:01:03 -04001215 for (const InlineCandidate& candidate : candidateList.fCandidates) {
John Stiles915a38c2020-09-14 09:38:13 -04001216 FunctionCall& funcCall = (*candidate.fCandidateExpr)->as<FunctionCall>();
John Stiles915a38c2020-09-14 09:38:13 -04001217
1218 // Inlining two expressions using the same enclosing statement in the same inlining pass
1219 // does not work properly. If this happens, skip it; we'll get it in the next pass.
1220 auto [unusedIter, inserted] = enclosingStmtSet.insert(candidate.fEnclosingStmt);
1221 if (!inserted) {
1222 continue;
1223 }
1224
1225 // Convert the function call to its inlined equivalent.
Brian Osman3887a012020-09-30 13:22:27 -04001226 InlinedCall inlinedCall = this->inlineCall(&funcCall, candidate.fSymbols,
Ethan Nicholas0a5d0962020-10-14 13:33:18 -04001227 &candidate.fEnclosingFunction->declaration());
John Stiles915a38c2020-09-14 09:38:13 -04001228 if (inlinedCall.fInlinedBody) {
1229 // Ensure that the inlined body has a scope if it needs one.
John Stiles6d696082020-10-01 10:18:54 -04001230 this->ensureScopedBlocks(inlinedCall.fInlinedBody.get(), candidate.fParentStmt->get());
John Stiles915a38c2020-09-14 09:38:13 -04001231
Brian Osman010ce6a2020-10-19 16:34:10 -04001232 // Add references within the inlined body
1233 usage->add(inlinedCall.fInlinedBody.get());
1234
John Stiles915a38c2020-09-14 09:38:13 -04001235 // Move the enclosing statement to the end of the unscoped Block containing the inlined
1236 // function, then replace the enclosing statement with that Block.
1237 // Before:
1238 // fInlinedBody = Block{ stmt1, stmt2, stmt3 }
1239 // fEnclosingStmt = stmt4
1240 // After:
1241 // fInlinedBody = null
1242 // fEnclosingStmt = Block{ stmt1, stmt2, stmt3, stmt4 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001243 inlinedCall.fInlinedBody->children().push_back(std::move(*candidate.fEnclosingStmt));
John Stiles915a38c2020-09-14 09:38:13 -04001244 *candidate.fEnclosingStmt = std::move(inlinedCall.fInlinedBody);
1245 }
1246
1247 // Replace the candidate function call with our replacement expression.
Brian Osman010ce6a2020-10-19 16:34:10 -04001248 usage->replace(candidate.fCandidateExpr->get(), inlinedCall.fReplacementExpr.get());
John Stiles915a38c2020-09-14 09:38:13 -04001249 *candidate.fCandidateExpr = std::move(inlinedCall.fReplacementExpr);
1250 madeChanges = true;
1251
John Stiles031a7672020-11-13 16:13:18 -05001252 // Stop inlining if we've reached our hard cap on new statements.
1253 if (fInlinedStatementCounter >= kInlinedStatementLimit) {
1254 break;
1255 }
1256
John Stiles915a38c2020-09-14 09:38:13 -04001257 // Note that nothing was destroyed except for the FunctionCall. All other nodes should
1258 // remain valid.
1259 }
1260
1261 return madeChanges;
John Stiles93442622020-09-11 12:11:27 -04001262}
1263
John Stiles44e96be2020-08-31 13:16:04 -04001264} // namespace SkSL