• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
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 
10 #include <limits.h>
11 #include <memory>
12 #include <unordered_set>
13 
14 #include "include/private/SkSLLayout.h"
15 #include "src/sksl/SkSLAnalysis.h"
16 #include "src/sksl/ir/SkSLBinaryExpression.h"
17 #include "src/sksl/ir/SkSLBoolLiteral.h"
18 #include "src/sksl/ir/SkSLBreakStatement.h"
19 #include "src/sksl/ir/SkSLConstructor.h"
20 #include "src/sksl/ir/SkSLConstructorArray.h"
21 #include "src/sksl/ir/SkSLConstructorCompound.h"
22 #include "src/sksl/ir/SkSLConstructorCompoundCast.h"
23 #include "src/sksl/ir/SkSLConstructorDiagonalMatrix.h"
24 #include "src/sksl/ir/SkSLConstructorMatrixResize.h"
25 #include "src/sksl/ir/SkSLConstructorScalarCast.h"
26 #include "src/sksl/ir/SkSLConstructorSplat.h"
27 #include "src/sksl/ir/SkSLConstructorStruct.h"
28 #include "src/sksl/ir/SkSLContinueStatement.h"
29 #include "src/sksl/ir/SkSLDiscardStatement.h"
30 #include "src/sksl/ir/SkSLDoStatement.h"
31 #include "src/sksl/ir/SkSLEnum.h"
32 #include "src/sksl/ir/SkSLExpressionStatement.h"
33 #include "src/sksl/ir/SkSLExternalFunctionCall.h"
34 #include "src/sksl/ir/SkSLExternalFunctionReference.h"
35 #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"
42 #include "src/sksl/ir/SkSLFunctionReference.h"
43 #include "src/sksl/ir/SkSLIfStatement.h"
44 #include "src/sksl/ir/SkSLIndexExpression.h"
45 #include "src/sksl/ir/SkSLInlineMarker.h"
46 #include "src/sksl/ir/SkSLIntLiteral.h"
47 #include "src/sksl/ir/SkSLInterfaceBlock.h"
48 #include "src/sksl/ir/SkSLNop.h"
49 #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"
53 #include "src/sksl/ir/SkSLSwitchCase.h"
54 #include "src/sksl/ir/SkSLSwitchStatement.h"
55 #include "src/sksl/ir/SkSLSwizzle.h"
56 #include "src/sksl/ir/SkSLTernaryExpression.h"
57 #include "src/sksl/ir/SkSLUnresolvedFunction.h"
58 #include "src/sksl/ir/SkSLVarDeclarations.h"
59 #include "src/sksl/ir/SkSLVariable.h"
60 #include "src/sksl/ir/SkSLVariableReference.h"
61 
62 namespace SkSL {
63 namespace {
64 
65 static constexpr int kInlinedStatementLimit = 2500;
66 
count_returns_at_end_of_control_flow(const FunctionDefinition & funcDef)67 static int count_returns_at_end_of_control_flow(const FunctionDefinition& funcDef) {
68     class CountReturnsAtEndOfControlFlow : public ProgramVisitor {
69     public:
70         CountReturnsAtEndOfControlFlow(const FunctionDefinition& funcDef) {
71             this->visitProgramElement(funcDef);
72         }
73 
74         bool visitExpression(const Expression& expr) override {
75             // Do not recurse into expressions.
76             return false;
77         }
78 
79         bool visitStatement(const Statement& stmt) override {
80             switch (stmt.kind()) {
81                 case Statement::Kind::kBlock: {
82                     // Check only the last statement of a block.
83                     const auto& block = stmt.as<Block>();
84                     return block.children().size() &&
85                            this->visitStatement(*block.children().back());
86                 }
87                 case Statement::Kind::kSwitch:
88                 case Statement::Kind::kDo:
89                 case Statement::Kind::kFor:
90                     // Don't introspect switches or loop structures at all.
91                     return false;
92 
93                 case Statement::Kind::kReturn:
94                     ++fNumReturns;
95                     [[fallthrough]];
96 
97                 default:
98                     return INHERITED::visitStatement(stmt);
99             }
100         }
101 
102         int fNumReturns = 0;
103         using INHERITED = ProgramVisitor;
104     };
105 
106     return CountReturnsAtEndOfControlFlow{funcDef}.fNumReturns;
107 }
108 
contains_recursive_call(const FunctionDeclaration & funcDecl)109 static bool contains_recursive_call(const FunctionDeclaration& funcDecl) {
110     class ContainsRecursiveCall : public ProgramVisitor {
111     public:
112         bool visit(const FunctionDeclaration& funcDecl) {
113             fFuncDecl = &funcDecl;
114             return funcDecl.definition() ? this->visitProgramElement(*funcDecl.definition())
115                                          : false;
116         }
117 
118         bool visitExpression(const Expression& expr) override {
119             if (expr.is<FunctionCall>() && expr.as<FunctionCall>().function().matches(*fFuncDecl)) {
120                 return true;
121             }
122             return INHERITED::visitExpression(expr);
123         }
124 
125         bool visitStatement(const Statement& stmt) override {
126             if (stmt.is<InlineMarker>() &&
127                 stmt.as<InlineMarker>().function().matches(*fFuncDecl)) {
128                 return true;
129             }
130             return INHERITED::visitStatement(stmt);
131         }
132 
133         const FunctionDeclaration* fFuncDecl;
134         using INHERITED = ProgramVisitor;
135     };
136 
137     return ContainsRecursiveCall{}.visit(funcDecl);
138 }
139 
find_parent_statement(const std::vector<std::unique_ptr<Statement> * > & stmtStack)140 static std::unique_ptr<Statement>* find_parent_statement(
141         const std::vector<std::unique_ptr<Statement>*>& stmtStack) {
142     SkASSERT(!stmtStack.empty());
143 
144     // Walk the statement stack from back to front, ignoring the last element (which is the
145     // enclosing statement).
146     auto iter = stmtStack.rbegin();
147     ++iter;
148 
149     // Anything counts as a parent statement other than a scopeless Block.
150     for (; iter != stmtStack.rend(); ++iter) {
151         std::unique_ptr<Statement>* stmt = *iter;
152         if (!(*stmt)->is<Block>() || (*stmt)->as<Block>().isScope()) {
153             return stmt;
154         }
155     }
156 
157     // There wasn't any parent statement to be found.
158     return nullptr;
159 }
160 
clone_with_ref_kind(const Expression & expr,VariableReference::RefKind refKind)161 std::unique_ptr<Expression> clone_with_ref_kind(const Expression& expr,
162                                                 VariableReference::RefKind refKind) {
163     std::unique_ptr<Expression> clone = expr.clone();
164     Analysis::UpdateRefKind(clone.get(), refKind);
165     return clone;
166 }
167 
168 class CountReturnsWithLimit : public ProgramVisitor {
169 public:
CountReturnsWithLimit(const FunctionDefinition & funcDef,int limit)170     CountReturnsWithLimit(const FunctionDefinition& funcDef, int limit) : fLimit(limit) {
171         this->visitProgramElement(funcDef);
172     }
173 
visitExpression(const Expression & expr)174     bool visitExpression(const Expression& expr) override {
175         // Do not recurse into expressions.
176         return false;
177     }
178 
visitStatement(const Statement & stmt)179     bool visitStatement(const Statement& stmt) override {
180         switch (stmt.kind()) {
181             case Statement::Kind::kReturn: {
182                 ++fNumReturns;
183                 fDeepestReturn = std::max(fDeepestReturn, fScopedBlockDepth);
184                 return (fNumReturns >= fLimit) || INHERITED::visitStatement(stmt);
185             }
186             case Statement::Kind::kVarDeclaration: {
187                 if (fScopedBlockDepth > 1) {
188                     fVariablesInBlocks = true;
189                 }
190                 return INHERITED::visitStatement(stmt);
191             }
192             case Statement::Kind::kBlock: {
193                 int depthIncrement = stmt.as<Block>().isScope() ? 1 : 0;
194                 fScopedBlockDepth += depthIncrement;
195                 bool result = INHERITED::visitStatement(stmt);
196                 fScopedBlockDepth -= depthIncrement;
197                 if (fNumReturns == 0 && fScopedBlockDepth <= 1) {
198                     // If closing this block puts us back at the top level, and we haven't
199                     // encountered any return statements yet, any vardecls we may have encountered
200                     // up until this point can be ignored. They are out of scope now, and they were
201                     // never used in a return statement.
202                     fVariablesInBlocks = false;
203                 }
204                 return result;
205             }
206             default:
207                 return INHERITED::visitStatement(stmt);
208         }
209     }
210 
211     int fNumReturns = 0;
212     int fDeepestReturn = 0;
213     int fLimit = 0;
214     int fScopedBlockDepth = 0;
215     bool fVariablesInBlocks = false;
216     using INHERITED = ProgramVisitor;
217 };
218 
219 }  // namespace
220 
GetReturnComplexity(const FunctionDefinition & funcDef)221 Inliner::ReturnComplexity Inliner::GetReturnComplexity(const FunctionDefinition& funcDef) {
222     int returnsAtEndOfControlFlow = count_returns_at_end_of_control_flow(funcDef);
223     CountReturnsWithLimit counter{funcDef, returnsAtEndOfControlFlow + 1};
224     if (counter.fNumReturns > returnsAtEndOfControlFlow) {
225         return ReturnComplexity::kEarlyReturns;
226     }
227     if (counter.fNumReturns > 1) {
228         return ReturnComplexity::kScopedReturns;
229     }
230     if (counter.fVariablesInBlocks && counter.fDeepestReturn > 1) {
231         return ReturnComplexity::kScopedReturns;
232     }
233     return ReturnComplexity::kSingleSafeReturn;
234 }
235 
ensureScopedBlocks(Statement * inlinedBody,Statement * parentStmt)236 void Inliner::ensureScopedBlocks(Statement* inlinedBody, Statement* parentStmt) {
237     // No changes necessary if this statement isn't actually a block.
238     if (!inlinedBody || !inlinedBody->is<Block>()) {
239         return;
240     }
241 
242     // No changes necessary if the parent statement doesn't require a scope.
243     if (!parentStmt || !(parentStmt->is<IfStatement>() || parentStmt->is<ForStatement>() ||
244                          parentStmt->is<DoStatement>())) {
245         return;
246     }
247 
248     Block& block = inlinedBody->as<Block>();
249 
250     // The inliner will create inlined function bodies as a Block containing multiple statements,
251     // but no scope. Normally, this is fine, but if this block is used as the statement for a
252     // do/for/if/while, this isn't actually possible to represent textually; a scope must be added
253     // for the generated code to match the intent. In the case of Blocks nested inside other Blocks,
254     // we add the scope to the outermost block if needed. Zero-statement blocks have similar
255     // issues--if we don't represent the Block textually somehow, we run the risk of accidentally
256     // absorbing the following statement into our loop--so we also add a scope to these.
257     for (Block* nestedBlock = &block;; ) {
258         if (nestedBlock->isScope()) {
259             // We found an explicit scope; all is well.
260             return;
261         }
262         if (nestedBlock->children().size() != 1) {
263             // We found a block with multiple (or zero) statements, but no scope? Let's add a scope
264             // to the outermost block.
265             block.setIsScope(true);
266             return;
267         }
268         if (!nestedBlock->children()[0]->is<Block>()) {
269             // This block has exactly one thing inside, and it's not another block. No need to scope
270             // it.
271             return;
272         }
273         // We have to go deeper.
274         nestedBlock = &nestedBlock->children()[0]->as<Block>();
275     }
276 }
277 
reset()278 void Inliner::reset() {
279     fMangler.reset();
280     fInlinedStatementCounter = 0;
281 }
282 
inlineExpression(int offset,VariableRewriteMap * varMap,SymbolTable * symbolTableForExpression,const Expression & expression)283 std::unique_ptr<Expression> Inliner::inlineExpression(int offset,
284                                                       VariableRewriteMap* varMap,
285                                                       SymbolTable* symbolTableForExpression,
286                                                       const Expression& expression) {
287     auto expr = [&](const std::unique_ptr<Expression>& e) -> std::unique_ptr<Expression> {
288         if (e) {
289             return this->inlineExpression(offset, varMap, symbolTableForExpression, *e);
290         }
291         return nullptr;
292     };
293     auto argList = [&](const ExpressionArray& originalArgs) -> ExpressionArray {
294         ExpressionArray args;
295         args.reserve_back(originalArgs.size());
296         for (const std::unique_ptr<Expression>& arg : originalArgs) {
297             args.push_back(expr(arg));
298         }
299         return args;
300     };
301 
302     switch (expression.kind()) {
303         case Expression::Kind::kBinary: {
304             const BinaryExpression& binaryExpr = expression.as<BinaryExpression>();
305             return BinaryExpression::Make(*fContext,
306                                           expr(binaryExpr.left()),
307                                           binaryExpr.getOperator(),
308                                           expr(binaryExpr.right()));
309         }
310         case Expression::Kind::kBoolLiteral:
311         case Expression::Kind::kIntLiteral:
312         case Expression::Kind::kFloatLiteral:
313             return expression.clone();
314         case Expression::Kind::kConstructorArray: {
315             const ConstructorArray& ctor = expression.as<ConstructorArray>();
316             return ConstructorArray::Make(*fContext, offset,
317                                           *ctor.type().clone(symbolTableForExpression),
318                                           argList(ctor.arguments()));
319         }
320         case Expression::Kind::kConstructorCompound: {
321             const ConstructorCompound& ctor = expression.as<ConstructorCompound>();
322             return ConstructorCompound::Make(*fContext, offset,
323                                               *ctor.type().clone(symbolTableForExpression),
324                                               argList(ctor.arguments()));
325         }
326         case Expression::Kind::kConstructorCompoundCast: {
327             const ConstructorCompoundCast& ctor = expression.as<ConstructorCompoundCast>();
328             return ConstructorCompoundCast::Make(*fContext, offset,
329                                                   *ctor.type().clone(symbolTableForExpression),
330                                                   expr(ctor.argument()));
331         }
332         case Expression::Kind::kConstructorDiagonalMatrix: {
333             const ConstructorDiagonalMatrix& ctor = expression.as<ConstructorDiagonalMatrix>();
334             return ConstructorDiagonalMatrix::Make(*fContext, offset,
335                                                    *ctor.type().clone(symbolTableForExpression),
336                                                    expr(ctor.argument()));
337         }
338         case Expression::Kind::kConstructorMatrixResize: {
339             const ConstructorMatrixResize& ctor = expression.as<ConstructorMatrixResize>();
340             return ConstructorMatrixResize::Make(*fContext, offset,
341                                                  *ctor.type().clone(symbolTableForExpression),
342                                                  expr(ctor.argument()));
343         }
344         case Expression::Kind::kConstructorScalarCast: {
345             const ConstructorScalarCast& ctor = expression.as<ConstructorScalarCast>();
346             return ConstructorScalarCast::Make(*fContext, offset,
347                                                *ctor.type().clone(symbolTableForExpression),
348                                                expr(ctor.argument()));
349         }
350         case Expression::Kind::kConstructorSplat: {
351             const ConstructorSplat& ctor = expression.as<ConstructorSplat>();
352             return ConstructorSplat::Make(*fContext, offset,
353                                           *ctor.type().clone(symbolTableForExpression),
354                                           expr(ctor.argument()));
355         }
356         case Expression::Kind::kConstructorStruct: {
357             const ConstructorStruct& ctor = expression.as<ConstructorStruct>();
358             return ConstructorStruct::Make(*fContext, offset,
359                                            *ctor.type().clone(symbolTableForExpression),
360                                            argList(ctor.arguments()));
361         }
362         case Expression::Kind::kExternalFunctionCall: {
363             const ExternalFunctionCall& externalCall = expression.as<ExternalFunctionCall>();
364             return std::make_unique<ExternalFunctionCall>(offset, &externalCall.function(),
365                                                           argList(externalCall.arguments()));
366         }
367         case Expression::Kind::kExternalFunctionReference:
368             return expression.clone();
369         case Expression::Kind::kFieldAccess: {
370             const FieldAccess& f = expression.as<FieldAccess>();
371             return FieldAccess::Make(*fContext, expr(f.base()), f.fieldIndex(), f.ownerKind());
372         }
373         case Expression::Kind::kFunctionCall: {
374             const FunctionCall& funcCall = expression.as<FunctionCall>();
375             return FunctionCall::Make(*fContext,
376                                       offset,
377                                       funcCall.type().clone(symbolTableForExpression),
378                                       funcCall.function(),
379                                       argList(funcCall.arguments()));
380         }
381         case Expression::Kind::kFunctionReference:
382             return expression.clone();
383         case Expression::Kind::kIndex: {
384             const IndexExpression& idx = expression.as<IndexExpression>();
385             return IndexExpression::Make(*fContext, expr(idx.base()), expr(idx.index()));
386         }
387         case Expression::Kind::kPrefix: {
388             const PrefixExpression& p = expression.as<PrefixExpression>();
389             return PrefixExpression::Make(*fContext, p.getOperator(), expr(p.operand()));
390         }
391         case Expression::Kind::kPostfix: {
392             const PostfixExpression& p = expression.as<PostfixExpression>();
393             return PostfixExpression::Make(*fContext, expr(p.operand()), p.getOperator());
394         }
395         case Expression::Kind::kSetting:
396             return expression.clone();
397         case Expression::Kind::kSwizzle: {
398             const Swizzle& s = expression.as<Swizzle>();
399             return Swizzle::Make(*fContext, expr(s.base()), s.components());
400         }
401         case Expression::Kind::kTernary: {
402             const TernaryExpression& t = expression.as<TernaryExpression>();
403             return TernaryExpression::Make(*fContext, expr(t.test()),
404                                            expr(t.ifTrue()), expr(t.ifFalse()));
405         }
406         case Expression::Kind::kTypeReference:
407             return expression.clone();
408         case Expression::Kind::kVariableReference: {
409             const VariableReference& v = expression.as<VariableReference>();
410             auto varMapIter = varMap->find(v.variable());
411             if (varMapIter != varMap->end()) {
412                 return clone_with_ref_kind(*varMapIter->second, v.refKind());
413             }
414             return v.clone();
415         }
416         default:
417             SkASSERT(false);
418             return nullptr;
419     }
420 }
421 
inlineStatement(int offset,VariableRewriteMap * varMap,SymbolTable * symbolTableForStatement,std::unique_ptr<Expression> * resultExpr,ReturnComplexity returnComplexity,const Statement & statement,bool isBuiltinCode)422 std::unique_ptr<Statement> Inliner::inlineStatement(int offset,
423                                                     VariableRewriteMap* varMap,
424                                                     SymbolTable* symbolTableForStatement,
425                                                     std::unique_ptr<Expression>* resultExpr,
426                                                     ReturnComplexity returnComplexity,
427                                                     const Statement& statement,
428                                                     bool isBuiltinCode) {
429     auto stmt = [&](const std::unique_ptr<Statement>& s) -> std::unique_ptr<Statement> {
430         if (s) {
431             return this->inlineStatement(offset, varMap, symbolTableForStatement, resultExpr,
432                                          returnComplexity, *s, isBuiltinCode);
433         }
434         return nullptr;
435     };
436     auto blockStmts = [&](const Block& block) {
437         StatementArray result;
438         result.reserve_back(block.children().size());
439         for (const std::unique_ptr<Statement>& child : block.children()) {
440             result.push_back(stmt(child));
441         }
442         return result;
443     };
444     auto expr = [&](const std::unique_ptr<Expression>& e) -> std::unique_ptr<Expression> {
445         if (e) {
446             return this->inlineExpression(offset, varMap, symbolTableForStatement, *e);
447         }
448         return nullptr;
449     };
450 
451     ++fInlinedStatementCounter;
452 
453     switch (statement.kind()) {
454         case Statement::Kind::kBlock: {
455             const Block& b = statement.as<Block>();
456             return Block::Make(offset, blockStmts(b),
457                                SymbolTable::WrapIfBuiltin(b.symbolTable()),
458                                b.isScope());
459         }
460 
461         case Statement::Kind::kBreak:
462         case Statement::Kind::kContinue:
463         case Statement::Kind::kDiscard:
464             return statement.clone();
465 
466         case Statement::Kind::kDo: {
467             const DoStatement& d = statement.as<DoStatement>();
468             return DoStatement::Make(*fContext, stmt(d.statement()), expr(d.test()));
469         }
470         case Statement::Kind::kExpression: {
471             const ExpressionStatement& e = statement.as<ExpressionStatement>();
472             return ExpressionStatement::Make(*fContext, expr(e.expression()));
473         }
474         case Statement::Kind::kFor: {
475             const ForStatement& f = statement.as<ForStatement>();
476             // need to ensure initializer is evaluated first so that we've already remapped its
477             // declarations by the time we evaluate test & next
478             std::unique_ptr<Statement> initializer = stmt(f.initializer());
479             return ForStatement::Make(*fContext, offset, std::move(initializer), expr(f.test()),
480                                       expr(f.next()), stmt(f.statement()),
481                                       SymbolTable::WrapIfBuiltin(f.symbols()));
482         }
483         case Statement::Kind::kIf: {
484             const IfStatement& i = statement.as<IfStatement>();
485             return IfStatement::Make(*fContext, offset, i.isStatic(), expr(i.test()),
486                                      stmt(i.ifTrue()), stmt(i.ifFalse()));
487         }
488         case Statement::Kind::kInlineMarker:
489         case Statement::Kind::kNop:
490             return statement.clone();
491 
492         case Statement::Kind::kReturn: {
493             const ReturnStatement& r = statement.as<ReturnStatement>();
494             if (!r.expression()) {
495                 // This function doesn't return a value. We won't inline functions with early
496                 // returns, so a return statement is a no-op and can be treated as such.
497                 return Nop::Make();
498             }
499 
500             // If a function only contains a single return, and it doesn't reference variables from
501             // inside an Block's scope, we don't need to store the result in a variable at all. Just
502             // replace the function-call expression with the function's return expression.
503             SkASSERT(resultExpr);
504             if (returnComplexity <= ReturnComplexity::kSingleSafeReturn) {
505                 *resultExpr = expr(r.expression());
506                 return Nop::Make();
507             }
508 
509             // For more complex functions, assign their result into a variable.
510             SkASSERT(*resultExpr);
511             auto assignment = ExpressionStatement::Make(
512                     *fContext,
513                     BinaryExpression::Make(
514                             *fContext,
515                             clone_with_ref_kind(**resultExpr, VariableRefKind::kWrite),
516                             Token::Kind::TK_EQ,
517                             expr(r.expression())));
518 
519             // Functions without early returns aren't wrapped in a for loop and don't need to worry
520             // about breaking out of the control flow.
521             return assignment;
522         }
523         case Statement::Kind::kSwitch: {
524             const SwitchStatement& ss = statement.as<SwitchStatement>();
525             StatementArray cases;
526             cases.reserve_back(ss.cases().size());
527             for (const std::unique_ptr<Statement>& statement : ss.cases()) {
528                 const SwitchCase& sc = statement->as<SwitchCase>();
529                 cases.push_back(std::make_unique<SwitchCase>(offset, expr(sc.value()),
530                                                              stmt(sc.statement())));
531             }
532             return SwitchStatement::Make(*fContext, offset, ss.isStatic(), expr(ss.value()),
533                                         std::move(cases), SymbolTable::WrapIfBuiltin(ss.symbols()));
534         }
535         case Statement::Kind::kVarDeclaration: {
536             const VarDeclaration& decl = statement.as<VarDeclaration>();
537             std::unique_ptr<Expression> initialValue = expr(decl.value());
538             const Variable& variable = decl.var();
539 
540             // We assign unique names to inlined variables--scopes hide most of the problems in this
541             // regard, but see `InlinerAvoidsVariableNameOverlap` for a counterexample where unique
542             // names are important.
543             const String* name = symbolTableForStatement->takeOwnershipOfString(
544                     fMangler.uniqueName(variable.name(), symbolTableForStatement));
545             auto clonedVar = std::make_unique<Variable>(
546                                                      offset,
547                                                      &variable.modifiers(),
548                                                      name->c_str(),
549                                                      variable.type().clone(symbolTableForStatement),
550                                                      isBuiltinCode,
551                                                      variable.storage());
552             (*varMap)[&variable] = VariableReference::Make(offset, clonedVar.get());
553             auto result = VarDeclaration::Make(*fContext,
554                                                clonedVar.get(),
555                                                decl.baseType().clone(symbolTableForStatement),
556                                                decl.arraySize(),
557                                                std::move(initialValue));
558             symbolTableForStatement->takeOwnershipOfSymbol(std::move(clonedVar));
559             return result;
560         }
561         default:
562             SkASSERT(false);
563             return nullptr;
564     }
565 }
566 
makeInlineVariable(const String & baseName,const Type * type,SymbolTable * symbolTable,Modifiers modifiers,bool isBuiltinCode,std::unique_ptr<Expression> * initialValue)567 Inliner::InlineVariable Inliner::makeInlineVariable(const String& baseName,
568                                                     const Type* type,
569                                                     SymbolTable* symbolTable,
570                                                     Modifiers modifiers,
571                                                     bool isBuiltinCode,
572                                                     std::unique_ptr<Expression>* initialValue) {
573     // $floatLiteral or $intLiteral aren't real types that we can use for scratch variables, so
574     // replace them if they ever appear here. If this happens, we likely forgot to coerce a type
575     // somewhere during compilation.
576     if (type->isLiteral()) {
577         SkDEBUGFAIL("found a $literal type while inlining");
578         type = &type->scalarTypeForLiteral();
579     }
580 
581     // Out parameters aren't supported.
582     SkASSERT(!(modifiers.fFlags & Modifiers::kOut_Flag));
583 
584     // Provide our new variable with a unique name, and add it to our symbol table.
585     const String* name =
586             symbolTable->takeOwnershipOfString(fMangler.uniqueName(baseName, symbolTable));
587 
588     // Create our new variable and add it to the symbol table.
589     InlineVariable result;
590     auto var = std::make_unique<Variable>(/*offset=*/-1,
591                                           this->modifiersPool().add(Modifiers{}),
592                                           name->c_str(),
593                                           type,
594                                           isBuiltinCode,
595                                           Variable::Storage::kLocal);
596 
597     // Create our variable declaration.
598     result.fVarDecl = VarDeclaration::Make(*fContext, var.get(), type, /*arraySize=*/0,
599                                            std::move(*initialValue));
600     result.fVarSymbol = symbolTable->add(std::move(var));
601     return result;
602 }
603 
inlineCall(FunctionCall * call,std::shared_ptr<SymbolTable> symbolTable,const ProgramUsage & usage,const FunctionDeclaration * caller)604 Inliner::InlinedCall Inliner::inlineCall(FunctionCall* call,
605                                          std::shared_ptr<SymbolTable> symbolTable,
606                                          const ProgramUsage& usage,
607                                          const FunctionDeclaration* caller) {
608     // Inlining is more complicated here than in a typical compiler, because we have to have a
609     // high-level IR and can't just drop statements into the middle of an expression or even use
610     // gotos.
611     //
612     // Since we can't insert statements into an expression, we run the inline function as extra
613     // statements before the statement we're currently processing, relying on a lack of execution
614     // order guarantees. Since we can't use gotos (which are normally used to replace return
615     // statements), we wrap the whole function in a loop and use break statements to jump to the
616     // end.
617     SkASSERT(fContext);
618     SkASSERT(call);
619     SkASSERT(this->isSafeToInline(call->function().definition()));
620 
621     ExpressionArray& arguments = call->arguments();
622     const int offset = call->fOffset;
623     const FunctionDefinition& function = *call->function().definition();
624     const Block& body = function.body()->as<Block>();
625     const ReturnComplexity returnComplexity = GetReturnComplexity(function);
626 
627     StatementArray inlineStatements;
628     int expectedStmtCount = 1 +                      // Inline marker
629                             1 +                      // Result variable
630                             arguments.size() +       // Function argument temp-vars
631                             body.children().size();  // Inlined code
632 
633     inlineStatements.reserve_back(expectedStmtCount);
634     inlineStatements.push_back(InlineMarker::Make(&call->function()));
635 
636     std::unique_ptr<Expression> resultExpr;
637     if (returnComplexity > ReturnComplexity::kSingleSafeReturn &&
638         !function.declaration().returnType().isVoid()) {
639         // Create a variable to hold the result in the extra statements. We don't need to do this
640         // for void-return functions, or in cases that are simple enough that we can just replace
641         // the function-call node with the result expression.
642         std::unique_ptr<Expression> noInitialValue;
643         InlineVariable var = this->makeInlineVariable(function.declaration().name(),
644                                                       &function.declaration().returnType(),
645                                                       symbolTable.get(), Modifiers{},
646                                                       caller->isBuiltin(), &noInitialValue);
647         inlineStatements.push_back(std::move(var.fVarDecl));
648         resultExpr = VariableReference::Make(/*offset=*/-1, var.fVarSymbol);
649     }
650 
651     // Create variables in the extra statements to hold the arguments, and assign the arguments to
652     // them.
653     VariableRewriteMap varMap;
654     for (int i = 0; i < arguments.count(); ++i) {
655         // If the parameter isn't written to within the inline function ...
656         const Variable* param = function.declaration().parameters()[i];
657         const ProgramUsage::VariableCounts& paramUsage = usage.get(*param);
658         if (!paramUsage.fWrite) {
659             // ... and can be inlined trivially (e.g. a swizzle, or a constant array index),
660             // or any expression without side effects that is only accessed at most once...
661             if ((paramUsage.fRead > 1) ? Analysis::IsTrivialExpression(*arguments[i])
662                                        : !arguments[i]->hasSideEffects()) {
663                 // ... we don't need to copy it at all! We can just use the existing expression.
664                 varMap[param] = arguments[i]->clone();
665                 continue;
666             }
667         }
668         InlineVariable var = this->makeInlineVariable(param->name(), &arguments[i]->type(),
669                                                       symbolTable.get(), param->modifiers(),
670                                                       caller->isBuiltin(), &arguments[i]);
671         inlineStatements.push_back(std::move(var.fVarDecl));
672         varMap[param] = VariableReference::Make(/*offset=*/-1, var.fVarSymbol);
673     }
674 
675     for (const std::unique_ptr<Statement>& stmt : body.children()) {
676         inlineStatements.push_back(this->inlineStatement(offset, &varMap, symbolTable.get(),
677                                                          &resultExpr, returnComplexity, *stmt,
678                                                          caller->isBuiltin()));
679     }
680 
681     SkASSERT(inlineStatements.count() <= expectedStmtCount);
682 
683     // Wrap all of the generated statements in a block. We need a real Block here, so we can't use
684     // MakeUnscoped. This is because we need to add another child statement to the Block later.
685     InlinedCall inlinedCall;
686     inlinedCall.fInlinedBody = Block::Make(offset, std::move(inlineStatements),
687                                            /*symbols=*/nullptr, /*isScope=*/false);
688 
689     if (resultExpr) {
690         // Return our result expression as-is.
691         inlinedCall.fReplacementExpr = std::move(resultExpr);
692     } else if (function.declaration().returnType().isVoid()) {
693         // It's a void function, so it doesn't actually result in anything, but we have to return
694         // something non-null as a standin.
695         inlinedCall.fReplacementExpr = BoolLiteral::Make(*fContext, offset, /*value=*/false);
696     } else {
697         // It's a non-void function, but it never created a result expression--that is, it never
698         // returned anything on any path! This should have been detected in the function finalizer.
699         // Still, discard our output and generate an error.
700         SkDEBUGFAIL("inliner found non-void function that fails to return a value on any path");
701         fContext->fErrors.error(function.fOffset, "inliner found non-void function '" +
702                                                   function.declaration().name() +
703                                                   "' that fails to return a value on any path");
704         inlinedCall = {};
705     }
706 
707     return inlinedCall;
708 }
709 
isSafeToInline(const FunctionDefinition * functionDef)710 bool Inliner::isSafeToInline(const FunctionDefinition* functionDef) {
711     // A threshold of zero indicates that the inliner is completely disabled, so we can just return.
712     if (this->settings().fInlineThreshold <= 0) {
713         return false;
714     }
715 
716     // Enforce a limit on inlining to avoid pathological cases. (inliner/ExponentialGrowth.sksl)
717     if (fInlinedStatementCounter >= kInlinedStatementLimit) {
718         return false;
719     }
720 
721     if (functionDef == nullptr) {
722         // Can't inline something if we don't actually have its definition.
723         return false;
724     }
725 
726     if (functionDef->declaration().modifiers().fFlags & Modifiers::kNoInline_Flag) {
727         // Refuse to inline functions decorated with `noinline`.
728         return false;
729     }
730 
731     // We don't allow inlining a function with out parameters. (See skia:11326 for rationale.)
732     for (const Variable* param : functionDef->declaration().parameters()) {
733         if (param->modifiers().fFlags & Modifiers::Flag::kOut_Flag) {
734             return false;
735         }
736     }
737 
738     // We don't have a mechanism to simulate early returns, so we can't inline if there is one.
739     return GetReturnComplexity(*functionDef) < ReturnComplexity::kEarlyReturns;
740 }
741 
742 // A candidate function for inlining, containing everything that `inlineCall` needs.
743 struct InlineCandidate {
744     std::shared_ptr<SymbolTable> fSymbols;        // the SymbolTable of the candidate
745     std::unique_ptr<Statement>* fParentStmt;      // the parent Statement of the enclosing stmt
746     std::unique_ptr<Statement>* fEnclosingStmt;   // the Statement containing the candidate
747     std::unique_ptr<Expression>* fCandidateExpr;  // the candidate FunctionCall to be inlined
748     FunctionDefinition* fEnclosingFunction;       // the Function containing the candidate
749 };
750 
751 struct InlineCandidateList {
752     std::vector<InlineCandidate> fCandidates;
753 };
754 
755 class InlineCandidateAnalyzer {
756 public:
757     // A list of all the inlining candidates we found during analysis.
758     InlineCandidateList* fCandidateList;
759 
760     // A stack of the symbol tables; since most nodes don't have one, expected to be shallower than
761     // the enclosing-statement stack.
762     std::vector<std::shared_ptr<SymbolTable>> fSymbolTableStack;
763     // A stack of "enclosing" statements--these would be suitable for the inliner to use for adding
764     // new instructions. Not all statements are suitable (e.g. a for-loop's initializer). The
765     // inliner might replace a statement with a block containing the statement.
766     std::vector<std::unique_ptr<Statement>*> fEnclosingStmtStack;
767     // The function that we're currently processing (i.e. inlining into).
768     FunctionDefinition* fEnclosingFunction = nullptr;
769 
visit(const std::vector<std::unique_ptr<ProgramElement>> & elements,std::shared_ptr<SymbolTable> symbols,InlineCandidateList * candidateList)770     void visit(const std::vector<std::unique_ptr<ProgramElement>>& elements,
771                std::shared_ptr<SymbolTable> symbols,
772                InlineCandidateList* candidateList) {
773         fCandidateList = candidateList;
774         fSymbolTableStack.push_back(symbols);
775 
776         for (const std::unique_ptr<ProgramElement>& pe : elements) {
777             this->visitProgramElement(pe.get());
778         }
779 
780         fSymbolTableStack.pop_back();
781         fCandidateList = nullptr;
782     }
783 
visitProgramElement(ProgramElement * pe)784     void visitProgramElement(ProgramElement* pe) {
785         switch (pe->kind()) {
786             case ProgramElement::Kind::kFunction: {
787                 FunctionDefinition& funcDef = pe->as<FunctionDefinition>();
788                 fEnclosingFunction = &funcDef;
789                 this->visitStatement(&funcDef.body());
790                 break;
791             }
792             default:
793                 // The inliner can't operate outside of a function's scope.
794                 break;
795         }
796     }
797 
visitStatement(std::unique_ptr<Statement> * stmt,bool isViableAsEnclosingStatement=true)798     void visitStatement(std::unique_ptr<Statement>* stmt,
799                         bool isViableAsEnclosingStatement = true) {
800         if (!*stmt) {
801             return;
802         }
803 
804         size_t oldEnclosingStmtStackSize = fEnclosingStmtStack.size();
805         size_t oldSymbolStackSize = fSymbolTableStack.size();
806 
807         if (isViableAsEnclosingStatement) {
808             fEnclosingStmtStack.push_back(stmt);
809         }
810 
811         switch ((*stmt)->kind()) {
812             case Statement::Kind::kBreak:
813             case Statement::Kind::kContinue:
814             case Statement::Kind::kDiscard:
815             case Statement::Kind::kInlineMarker:
816             case Statement::Kind::kNop:
817                 break;
818 
819             case Statement::Kind::kBlock: {
820                 Block& block = (*stmt)->as<Block>();
821                 if (block.symbolTable()) {
822                     fSymbolTableStack.push_back(block.symbolTable());
823                 }
824 
825                 for (std::unique_ptr<Statement>& stmt : block.children()) {
826                     this->visitStatement(&stmt);
827                 }
828                 break;
829             }
830             case Statement::Kind::kDo: {
831                 DoStatement& doStmt = (*stmt)->as<DoStatement>();
832                 // The loop body is a candidate for inlining.
833                 this->visitStatement(&doStmt.statement());
834                 // The inliner isn't smart enough to inline the test-expression for a do-while
835                 // loop at this time. There are two limitations:
836                 // - We would need to insert the inlined-body block at the very end of the do-
837                 //   statement's inner fStatement. We don't support that today, but it's doable.
838                 // - We cannot inline the test expression if the loop uses `continue` anywhere; that
839                 //   would skip over the inlined block that evaluates the test expression. There
840                 //   isn't a good fix for this--any workaround would be more complex than the cost
841                 //   of a function call. However, loops that don't use `continue` would still be
842                 //   viable candidates for inlining.
843                 break;
844             }
845             case Statement::Kind::kExpression: {
846                 ExpressionStatement& expr = (*stmt)->as<ExpressionStatement>();
847                 this->visitExpression(&expr.expression());
848                 break;
849             }
850             case Statement::Kind::kFor: {
851                 ForStatement& forStmt = (*stmt)->as<ForStatement>();
852                 if (forStmt.symbols()) {
853                     fSymbolTableStack.push_back(forStmt.symbols());
854                 }
855 
856                 // The initializer and loop body are candidates for inlining.
857                 this->visitStatement(&forStmt.initializer(),
858                                      /*isViableAsEnclosingStatement=*/false);
859                 this->visitStatement(&forStmt.statement());
860 
861                 // The inliner isn't smart enough to inline the test- or increment-expressions
862                 // of a for loop loop at this time. There are a handful of limitations:
863                 // - We would need to insert the test-expression block at the very beginning of the
864                 //   for-loop's inner fStatement, and the increment-expression block at the very
865                 //   end. We don't support that today, but it's doable.
866                 // - The for-loop's built-in test-expression would need to be dropped entirely,
867                 //   and the loop would be halted via a break statement at the end of the inlined
868                 //   test-expression. This is again something we don't support today, but it could
869                 //   be implemented.
870                 // - We cannot inline the increment-expression if the loop uses `continue` anywhere;
871                 //   that would skip over the inlined block that evaluates the increment expression.
872                 //   There isn't a good fix for this--any workaround would be more complex than the
873                 //   cost of a function call. However, loops that don't use `continue` would still
874                 //   be viable candidates for increment-expression inlining.
875                 break;
876             }
877             case Statement::Kind::kIf: {
878                 IfStatement& ifStmt = (*stmt)->as<IfStatement>();
879                 this->visitExpression(&ifStmt.test());
880                 this->visitStatement(&ifStmt.ifTrue());
881                 this->visitStatement(&ifStmt.ifFalse());
882                 break;
883             }
884             case Statement::Kind::kReturn: {
885                 ReturnStatement& returnStmt = (*stmt)->as<ReturnStatement>();
886                 this->visitExpression(&returnStmt.expression());
887                 break;
888             }
889             case Statement::Kind::kSwitch: {
890                 SwitchStatement& switchStmt = (*stmt)->as<SwitchStatement>();
891                 if (switchStmt.symbols()) {
892                     fSymbolTableStack.push_back(switchStmt.symbols());
893                 }
894 
895                 this->visitExpression(&switchStmt.value());
896                 for (const std::unique_ptr<Statement>& switchCase : switchStmt.cases()) {
897                     // The switch-case's fValue cannot be a FunctionCall; skip it.
898                     this->visitStatement(&switchCase->as<SwitchCase>().statement());
899                 }
900                 break;
901             }
902             case Statement::Kind::kVarDeclaration: {
903                 VarDeclaration& varDeclStmt = (*stmt)->as<VarDeclaration>();
904                 // Don't need to scan the declaration's sizes; those are always IntLiterals.
905                 this->visitExpression(&varDeclStmt.value());
906                 break;
907             }
908             default:
909                 SkUNREACHABLE;
910         }
911 
912         // Pop our symbol and enclosing-statement stacks.
913         fSymbolTableStack.resize(oldSymbolStackSize);
914         fEnclosingStmtStack.resize(oldEnclosingStmtStackSize);
915     }
916 
visitExpression(std::unique_ptr<Expression> * expr)917     void visitExpression(std::unique_ptr<Expression>* expr) {
918         if (!*expr) {
919             return;
920         }
921 
922         switch ((*expr)->kind()) {
923             case Expression::Kind::kBoolLiteral:
924             case Expression::Kind::kExternalFunctionReference:
925             case Expression::Kind::kFieldAccess:
926             case Expression::Kind::kFloatLiteral:
927             case Expression::Kind::kFunctionReference:
928             case Expression::Kind::kIntLiteral:
929             case Expression::Kind::kSetting:
930             case Expression::Kind::kTypeReference:
931             case Expression::Kind::kVariableReference:
932                 // Nothing to scan here.
933                 break;
934 
935             case Expression::Kind::kBinary: {
936                 BinaryExpression& binaryExpr = (*expr)->as<BinaryExpression>();
937                 this->visitExpression(&binaryExpr.left());
938 
939                 // Logical-and and logical-or binary expressions do not inline the right side,
940                 // because that would invalidate short-circuiting. That is, when evaluating
941                 // expressions like these:
942                 //    (false && x())   // always false
943                 //    (true || y())    // always true
944                 // It is illegal for side-effects from x() or y() to occur. The simplest way to
945                 // enforce that rule is to avoid inlining the right side entirely. However, it is
946                 // safe for other types of binary expression to inline both sides.
947                 Operator op = binaryExpr.getOperator();
948                 bool shortCircuitable = (op.kind() == Token::Kind::TK_LOGICALAND ||
949                                          op.kind() == Token::Kind::TK_LOGICALOR);
950                 if (!shortCircuitable) {
951                     this->visitExpression(&binaryExpr.right());
952                 }
953                 break;
954             }
955             case Expression::Kind::kConstructorArray:
956             case Expression::Kind::kConstructorCompound:
957             case Expression::Kind::kConstructorCompoundCast:
958             case Expression::Kind::kConstructorDiagonalMatrix:
959             case Expression::Kind::kConstructorMatrixResize:
960             case Expression::Kind::kConstructorScalarCast:
961             case Expression::Kind::kConstructorSplat:
962             case Expression::Kind::kConstructorStruct: {
963                 AnyConstructor& constructorExpr = (*expr)->asAnyConstructor();
964                 for (std::unique_ptr<Expression>& arg : constructorExpr.argumentSpan()) {
965                     this->visitExpression(&arg);
966                 }
967                 break;
968             }
969             case Expression::Kind::kExternalFunctionCall: {
970                 ExternalFunctionCall& funcCallExpr = (*expr)->as<ExternalFunctionCall>();
971                 for (std::unique_ptr<Expression>& arg : funcCallExpr.arguments()) {
972                     this->visitExpression(&arg);
973                 }
974                 break;
975             }
976             case Expression::Kind::kFunctionCall: {
977                 FunctionCall& funcCallExpr = (*expr)->as<FunctionCall>();
978                 for (std::unique_ptr<Expression>& arg : funcCallExpr.arguments()) {
979                     this->visitExpression(&arg);
980                 }
981                 this->addInlineCandidate(expr);
982                 break;
983             }
984             case Expression::Kind::kIndex: {
985                 IndexExpression& indexExpr = (*expr)->as<IndexExpression>();
986                 this->visitExpression(&indexExpr.base());
987                 this->visitExpression(&indexExpr.index());
988                 break;
989             }
990             case Expression::Kind::kPostfix: {
991                 PostfixExpression& postfixExpr = (*expr)->as<PostfixExpression>();
992                 this->visitExpression(&postfixExpr.operand());
993                 break;
994             }
995             case Expression::Kind::kPrefix: {
996                 PrefixExpression& prefixExpr = (*expr)->as<PrefixExpression>();
997                 this->visitExpression(&prefixExpr.operand());
998                 break;
999             }
1000             case Expression::Kind::kSwizzle: {
1001                 Swizzle& swizzleExpr = (*expr)->as<Swizzle>();
1002                 this->visitExpression(&swizzleExpr.base());
1003                 break;
1004             }
1005             case Expression::Kind::kTernary: {
1006                 TernaryExpression& ternaryExpr = (*expr)->as<TernaryExpression>();
1007                 // The test expression is a candidate for inlining.
1008                 this->visitExpression(&ternaryExpr.test());
1009                 // The true- and false-expressions cannot be inlined, because we are only allowed to
1010                 // evaluate one side.
1011                 break;
1012             }
1013             default:
1014                 SkUNREACHABLE;
1015         }
1016     }
1017 
addInlineCandidate(std::unique_ptr<Expression> * candidate)1018     void addInlineCandidate(std::unique_ptr<Expression>* candidate) {
1019         fCandidateList->fCandidates.push_back(
1020                 InlineCandidate{fSymbolTableStack.back(),
1021                                 find_parent_statement(fEnclosingStmtStack),
1022                                 fEnclosingStmtStack.back(),
1023                                 candidate,
1024                                 fEnclosingFunction});
1025     }
1026 };
1027 
candidate_func(const InlineCandidate & candidate)1028 static const FunctionDeclaration& candidate_func(const InlineCandidate& candidate) {
1029     return (*candidate.fCandidateExpr)->as<FunctionCall>().function();
1030 }
1031 
candidateCanBeInlined(const InlineCandidate & candidate,InlinabilityCache * cache)1032 bool Inliner::candidateCanBeInlined(const InlineCandidate& candidate, InlinabilityCache* cache) {
1033     const FunctionDeclaration& funcDecl = candidate_func(candidate);
1034     auto [iter, wasInserted] = cache->insert({&funcDecl, false});
1035     if (wasInserted) {
1036         // Recursion is forbidden here to avoid an infinite death spiral of inlining.
1037         iter->second = this->isSafeToInline(funcDecl.definition()) &&
1038                        !contains_recursive_call(funcDecl);
1039     }
1040 
1041     return iter->second;
1042 }
1043 
getFunctionSize(const FunctionDeclaration & funcDecl,FunctionSizeCache * cache)1044 int Inliner::getFunctionSize(const FunctionDeclaration& funcDecl, FunctionSizeCache* cache) {
1045     auto [iter, wasInserted] = cache->insert({&funcDecl, 0});
1046     if (wasInserted) {
1047         iter->second = Analysis::NodeCountUpToLimit(*funcDecl.definition(),
1048                                                     this->settings().fInlineThreshold);
1049     }
1050     return iter->second;
1051 }
1052 
buildCandidateList(const std::vector<std::unique_ptr<ProgramElement>> & elements,std::shared_ptr<SymbolTable> symbols,ProgramUsage * usage,InlineCandidateList * candidateList)1053 void Inliner::buildCandidateList(const std::vector<std::unique_ptr<ProgramElement>>& elements,
1054                                  std::shared_ptr<SymbolTable> symbols, ProgramUsage* usage,
1055                                  InlineCandidateList* candidateList) {
1056     // This is structured much like a ProgramVisitor, but does not actually use ProgramVisitor.
1057     // The analyzer needs to keep track of the `unique_ptr<T>*` of statements and expressions so
1058     // that they can later be replaced, and ProgramVisitor does not provide this; it only provides a
1059     // `const T&`.
1060     InlineCandidateAnalyzer analyzer;
1061     analyzer.visit(elements, symbols, candidateList);
1062 
1063     // Early out if there are no inlining candidates.
1064     std::vector<InlineCandidate>& candidates = candidateList->fCandidates;
1065     if (candidates.empty()) {
1066         return;
1067     }
1068 
1069     // Remove candidates that are not safe to inline.
1070     InlinabilityCache cache;
1071     candidates.erase(std::remove_if(candidates.begin(),
1072                                     candidates.end(),
1073                                     [&](const InlineCandidate& candidate) {
1074                                         return !this->candidateCanBeInlined(candidate, &cache);
1075                                     }),
1076                      candidates.end());
1077 
1078     // If the inline threshold is unlimited, or if we have no candidates left, our candidate list is
1079     // complete.
1080     if (this->settings().fInlineThreshold == INT_MAX || candidates.empty()) {
1081         return;
1082     }
1083 
1084     // Remove candidates on a per-function basis if the effect of inlining would be to make more
1085     // than `inlineThreshold` nodes. (i.e. if Func() would be inlined six times and its size is
1086     // 10 nodes, it should be inlined if the inlineThreshold is 60 or higher.)
1087     FunctionSizeCache functionSizeCache;
1088     FunctionSizeCache candidateTotalCost;
1089     for (InlineCandidate& candidate : candidates) {
1090         const FunctionDeclaration& fnDecl = candidate_func(candidate);
1091         candidateTotalCost[&fnDecl] += this->getFunctionSize(fnDecl, &functionSizeCache);
1092     }
1093 
1094     candidates.erase(std::remove_if(candidates.begin(), candidates.end(),
1095                         [&](const InlineCandidate& candidate) {
1096                             const FunctionDeclaration& fnDecl = candidate_func(candidate);
1097                             if (fnDecl.modifiers().fFlags & Modifiers::kInline_Flag) {
1098                                 // Functions marked `inline` ignore size limitations.
1099                                 return false;
1100                             }
1101                             if (usage->get(fnDecl) == 1) {
1102                                 // If a function is only used once, it's cost-free to inline.
1103                                 return false;
1104                             }
1105                             if (candidateTotalCost[&fnDecl] <= this->settings().fInlineThreshold) {
1106                                 // We won't exceed the inline threshold by inlining this.
1107                                 return false;
1108                             }
1109                             // Inlining this function will add too many IRNodes.
1110                             return true;
1111                         }),
1112          candidates.end());
1113 }
1114 
analyze(const std::vector<std::unique_ptr<ProgramElement>> & elements,std::shared_ptr<SymbolTable> symbols,ProgramUsage * usage)1115 bool Inliner::analyze(const std::vector<std::unique_ptr<ProgramElement>>& elements,
1116                       std::shared_ptr<SymbolTable> symbols,
1117                       ProgramUsage* usage) {
1118     // A threshold of zero indicates that the inliner is completely disabled, so we can just return.
1119     if (this->settings().fInlineThreshold <= 0) {
1120         return false;
1121     }
1122 
1123     // Enforce a limit on inlining to avoid pathological cases. (inliner/ExponentialGrowth.sksl)
1124     if (fInlinedStatementCounter >= kInlinedStatementLimit) {
1125         return false;
1126     }
1127 
1128     InlineCandidateList candidateList;
1129     this->buildCandidateList(elements, symbols, usage, &candidateList);
1130 
1131     // Inline the candidates where we've determined that it's safe to do so.
1132     using StatementRemappingTable = std::unordered_map<std::unique_ptr<Statement>*,
1133                                                        std::unique_ptr<Statement>*>;
1134     StatementRemappingTable statementRemappingTable;
1135 
1136     bool madeChanges = false;
1137     for (const InlineCandidate& candidate : candidateList.fCandidates) {
1138         FunctionCall& funcCall = (*candidate.fCandidateExpr)->as<FunctionCall>();
1139 
1140         // Convert the function call to its inlined equivalent.
1141         InlinedCall inlinedCall = this->inlineCall(&funcCall, candidate.fSymbols, *usage,
1142                                                    &candidate.fEnclosingFunction->declaration());
1143 
1144         // Stop if an error was detected during the inlining process.
1145         if (!inlinedCall.fInlinedBody && !inlinedCall.fReplacementExpr) {
1146             break;
1147         }
1148 
1149         // Ensure that the inlined body has a scope if it needs one.
1150         this->ensureScopedBlocks(inlinedCall.fInlinedBody.get(), candidate.fParentStmt->get());
1151 
1152         // Add references within the inlined body
1153         usage->add(inlinedCall.fInlinedBody.get());
1154 
1155         // Look up the enclosing statement; remap it if necessary.
1156         std::unique_ptr<Statement>* enclosingStmt = candidate.fEnclosingStmt;
1157         for (;;) {
1158             auto iter = statementRemappingTable.find(enclosingStmt);
1159             if (iter == statementRemappingTable.end()) {
1160                 break;
1161             }
1162             enclosingStmt = iter->second;
1163         }
1164 
1165         // Move the enclosing statement to the end of the unscoped Block containing the inlined
1166         // function, then replace the enclosing statement with that Block.
1167         // Before:
1168         //     fInlinedBody = Block{ stmt1, stmt2, stmt3 }
1169         //     fEnclosingStmt = stmt4
1170         // After:
1171         //     fInlinedBody = null
1172         //     fEnclosingStmt = Block{ stmt1, stmt2, stmt3, stmt4 }
1173         inlinedCall.fInlinedBody->children().push_back(std::move(*enclosingStmt));
1174         *enclosingStmt = std::move(inlinedCall.fInlinedBody);
1175 
1176         // Replace the candidate function call with our replacement expression.
1177         usage->replace(candidate.fCandidateExpr->get(), inlinedCall.fReplacementExpr.get());
1178         *candidate.fCandidateExpr = std::move(inlinedCall.fReplacementExpr);
1179         madeChanges = true;
1180 
1181         // If anything else pointed at our enclosing statement, it's now pointing at a Block
1182         // containing many other statements as well. Maintain a fix-up table to account for this.
1183         statementRemappingTable[enclosingStmt] = &(*enclosingStmt)->as<Block>().children().back();
1184 
1185         // Stop inlining if we've reached our hard cap on new statements.
1186         if (fInlinedStatementCounter >= kInlinedStatementLimit) {
1187             break;
1188         }
1189 
1190         // Note that nothing was destroyed except for the FunctionCall. All other nodes should
1191         // remain valid.
1192     }
1193 
1194     return madeChanges;
1195 }
1196 
1197 }  // namespace SkSL
1198