blob: 7fd4a8fa585cb6d2113804c656d53852b2e176fd [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
Ethan Nicholasdaed2592021-03-04 14:30:25 -050014#include "include/private/SkSLLayout.h"
John Stiles44e96be2020-08-31 13:16:04 -040015#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/SkSLContinueStatement.h"
21#include "src/sksl/ir/SkSLDiscardStatement.h"
22#include "src/sksl/ir/SkSLDoStatement.h"
23#include "src/sksl/ir/SkSLEnum.h"
24#include "src/sksl/ir/SkSLExpressionStatement.h"
25#include "src/sksl/ir/SkSLExternalFunctionCall.h"
Brian Osmanbe0b3b72021-01-06 14:27:35 -050026#include "src/sksl/ir/SkSLExternalFunctionReference.h"
John Stiles44e96be2020-08-31 13:16:04 -040027#include "src/sksl/ir/SkSLField.h"
28#include "src/sksl/ir/SkSLFieldAccess.h"
29#include "src/sksl/ir/SkSLFloatLiteral.h"
30#include "src/sksl/ir/SkSLForStatement.h"
31#include "src/sksl/ir/SkSLFunctionCall.h"
32#include "src/sksl/ir/SkSLFunctionDeclaration.h"
33#include "src/sksl/ir/SkSLFunctionDefinition.h"
34#include "src/sksl/ir/SkSLFunctionReference.h"
35#include "src/sksl/ir/SkSLIfStatement.h"
36#include "src/sksl/ir/SkSLIndexExpression.h"
John Stiles98c1f822020-09-09 14:18:53 -040037#include "src/sksl/ir/SkSLInlineMarker.h"
John Stiles44e96be2020-08-31 13:16:04 -040038#include "src/sksl/ir/SkSLIntLiteral.h"
39#include "src/sksl/ir/SkSLInterfaceBlock.h"
John Stiles44e96be2020-08-31 13:16:04 -040040#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
John Stiles5b408a32021-03-17 09:53:32 -040066 bool visitExpression(const Expression& expr) override {
67 // Do not recurse into expressions.
68 return false;
69 }
70
John Stiles44e96be2020-08-31 13:16:04 -040071 bool visitStatement(const Statement& stmt) override {
Ethan Nicholase6592142020-09-08 10:22:09 -040072 switch (stmt.kind()) {
73 case Statement::Kind::kBlock: {
John Stiles44e96be2020-08-31 13:16:04 -040074 // Check only the last statement of a block.
Ethan Nicholas7bd60432020-09-25 14:31:59 -040075 const auto& block = stmt.as<Block>();
76 return block.children().size() &&
77 this->visitStatement(*block.children().back());
John Stiles44e96be2020-08-31 13:16:04 -040078 }
Ethan Nicholase6592142020-09-08 10:22:09 -040079 case Statement::Kind::kSwitch:
Ethan Nicholase6592142020-09-08 10:22:09 -040080 case Statement::Kind::kDo:
81 case Statement::Kind::kFor:
John Stiles44e96be2020-08-31 13:16:04 -040082 // Don't introspect switches or loop structures at all.
83 return false;
84
Ethan Nicholase6592142020-09-08 10:22:09 -040085 case Statement::Kind::kReturn:
John Stiles44e96be2020-08-31 13:16:04 -040086 ++fNumReturns;
87 [[fallthrough]];
88
89 default:
John Stiles93442622020-09-11 12:11:27 -040090 return INHERITED::visitStatement(stmt);
John Stiles44e96be2020-08-31 13:16:04 -040091 }
92 }
93
94 int fNumReturns = 0;
95 using INHERITED = ProgramVisitor;
96 };
97
98 return CountReturnsAtEndOfControlFlow{funcDef}.fNumReturns;
99}
100
John Stiles991b09d2020-09-10 13:33:40 -0400101static bool contains_recursive_call(const FunctionDeclaration& funcDecl) {
102 class ContainsRecursiveCall : public ProgramVisitor {
103 public:
104 bool visit(const FunctionDeclaration& funcDecl) {
105 fFuncDecl = &funcDecl;
Ethan Nicholased84b732020-10-08 11:45:44 -0400106 return funcDecl.definition() ? this->visitProgramElement(*funcDecl.definition())
107 : false;
John Stiles991b09d2020-09-10 13:33:40 -0400108 }
109
110 bool visitExpression(const Expression& expr) override {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400111 if (expr.is<FunctionCall>() && expr.as<FunctionCall>().function().matches(*fFuncDecl)) {
John Stiles991b09d2020-09-10 13:33:40 -0400112 return true;
113 }
114 return INHERITED::visitExpression(expr);
115 }
116
117 bool visitStatement(const Statement& stmt) override {
Ethan Nicholasceb62142020-10-09 16:51:18 -0400118 if (stmt.is<InlineMarker>() &&
119 stmt.as<InlineMarker>().function().matches(*fFuncDecl)) {
John Stiles991b09d2020-09-10 13:33:40 -0400120 return true;
121 }
122 return INHERITED::visitStatement(stmt);
123 }
124
125 const FunctionDeclaration* fFuncDecl;
126 using INHERITED = ProgramVisitor;
127 };
128
129 return ContainsRecursiveCall{}.visit(funcDecl);
130}
131
John Stiles6d696082020-10-01 10:18:54 -0400132static std::unique_ptr<Statement>* find_parent_statement(
133 const std::vector<std::unique_ptr<Statement>*>& stmtStack) {
John Stiles915a38c2020-09-14 09:38:13 -0400134 SkASSERT(!stmtStack.empty());
135
136 // Walk the statement stack from back to front, ignoring the last element (which is the
137 // enclosing statement).
138 auto iter = stmtStack.rbegin();
139 ++iter;
140
141 // Anything counts as a parent statement other than a scopeless Block.
142 for (; iter != stmtStack.rend(); ++iter) {
John Stiles6d696082020-10-01 10:18:54 -0400143 std::unique_ptr<Statement>* stmt = *iter;
144 if (!(*stmt)->is<Block>() || (*stmt)->as<Block>().isScope()) {
John Stiles915a38c2020-09-14 09:38:13 -0400145 return stmt;
146 }
147 }
148
149 // There wasn't any parent statement to be found.
150 return nullptr;
151}
152
John Stilese41b4ee2020-09-28 12:28:16 -0400153std::unique_ptr<Expression> clone_with_ref_kind(const Expression& expr,
154 VariableReference::RefKind refKind) {
155 std::unique_ptr<Expression> clone = expr.clone();
John Stiles47c0a742021-02-09 09:30:35 -0500156 Analysis::UpdateRefKind(clone.get(), refKind);
John Stilese41b4ee2020-09-28 12:28:16 -0400157 return clone;
158}
159
John Stiles77702f12020-12-17 14:38:56 -0500160class CountReturnsWithLimit : public ProgramVisitor {
161public:
162 CountReturnsWithLimit(const FunctionDefinition& funcDef, int limit) : fLimit(limit) {
163 this->visitProgramElement(funcDef);
164 }
165
John Stiles5b408a32021-03-17 09:53:32 -0400166 bool visitExpression(const Expression& expr) override {
167 // Do not recurse into expressions.
168 return false;
169 }
170
John Stiles77702f12020-12-17 14:38:56 -0500171 bool visitStatement(const Statement& stmt) override {
172 switch (stmt.kind()) {
173 case Statement::Kind::kReturn: {
174 ++fNumReturns;
175 fDeepestReturn = std::max(fDeepestReturn, fScopedBlockDepth);
176 return (fNumReturns >= fLimit) || INHERITED::visitStatement(stmt);
177 }
John Stilesc5ff4862020-12-22 13:47:05 -0500178 case Statement::Kind::kVarDeclaration: {
John Stiles99b2d042021-03-15 11:42:47 -0400179 ++fNumNonReturnStatements;
John Stilesc5ff4862020-12-22 13:47:05 -0500180 if (fScopedBlockDepth > 1) {
181 fVariablesInBlocks = true;
182 }
183 return INHERITED::visitStatement(stmt);
184 }
John Stiles77702f12020-12-17 14:38:56 -0500185 case Statement::Kind::kBlock: {
John Stiles99b2d042021-03-15 11:42:47 -0400186 // Don't count Block as a statement.
John Stiles77702f12020-12-17 14:38:56 -0500187 int depthIncrement = stmt.as<Block>().isScope() ? 1 : 0;
188 fScopedBlockDepth += depthIncrement;
189 bool result = INHERITED::visitStatement(stmt);
190 fScopedBlockDepth -= depthIncrement;
John Stilesc5ff4862020-12-22 13:47:05 -0500191 if (fNumReturns == 0 && fScopedBlockDepth <= 1) {
192 // If closing this block puts us back at the top level, and we haven't
193 // encountered any return statements yet, any vardecls we may have encountered
194 // up until this point can be ignored. They are out of scope now, and they were
195 // never used in a return statement.
196 fVariablesInBlocks = false;
197 }
John Stiles77702f12020-12-17 14:38:56 -0500198 return result;
199 }
John Stiles99b2d042021-03-15 11:42:47 -0400200 case Statement::Kind::kNop:
201 case Statement::Kind::kInlineMarker:
202 // Don't count no-op statements.
203 return false;
John Stiles77702f12020-12-17 14:38:56 -0500204 default:
John Stiles99b2d042021-03-15 11:42:47 -0400205 ++fNumNonReturnStatements;
John Stiles77702f12020-12-17 14:38:56 -0500206 return INHERITED::visitStatement(stmt);
207 }
208 }
209
210 int fNumReturns = 0;
John Stiles99b2d042021-03-15 11:42:47 -0400211 int fNumNonReturnStatements = 0;
John Stiles77702f12020-12-17 14:38:56 -0500212 int fDeepestReturn = 0;
213 int fLimit = 0;
214 int fScopedBlockDepth = 0;
John Stilesc5ff4862020-12-22 13:47:05 -0500215 bool fVariablesInBlocks = false;
John Stiles77702f12020-12-17 14:38:56 -0500216 using INHERITED = ProgramVisitor;
217};
218
John Stiles44e96be2020-08-31 13:16:04 -0400219} // namespace
220
John Stiles77702f12020-12-17 14:38:56 -0500221Inliner::ReturnComplexity Inliner::GetReturnComplexity(const FunctionDefinition& funcDef) {
222 int returnsAtEndOfControlFlow = count_returns_at_end_of_control_flow(funcDef);
223 CountReturnsWithLimit counter{funcDef, returnsAtEndOfControlFlow + 1};
John Stiles77702f12020-12-17 14:38:56 -0500224 if (counter.fNumReturns > returnsAtEndOfControlFlow) {
225 return ReturnComplexity::kEarlyReturns;
226 }
John Stilesc5ff4862020-12-22 13:47:05 -0500227 if (counter.fNumReturns > 1) {
John Stiles77702f12020-12-17 14:38:56 -0500228 return ReturnComplexity::kScopedReturns;
229 }
John Stilesc5ff4862020-12-22 13:47:05 -0500230 if (counter.fVariablesInBlocks && counter.fDeepestReturn > 1) {
231 return ReturnComplexity::kScopedReturns;
232 }
John Stiles99b2d042021-03-15 11:42:47 -0400233 if (counter.fNumNonReturnStatements > 0) {
234 return ReturnComplexity::kSingleSafeReturn;
235 }
236 return ReturnComplexity::kOnlySingleReturn;
John Stiles77702f12020-12-17 14:38:56 -0500237}
238
John Stilesb61ee902020-09-21 12:26:59 -0400239void Inliner::ensureScopedBlocks(Statement* inlinedBody, Statement* parentStmt) {
240 // No changes necessary if this statement isn't actually a block.
241 if (!inlinedBody || !inlinedBody->is<Block>()) {
242 return;
243 }
244
245 // No changes necessary if the parent statement doesn't require a scope.
246 if (!parentStmt || !(parentStmt->is<IfStatement>() || parentStmt->is<ForStatement>() ||
Brian Osmand6f23382020-12-15 17:08:59 -0500247 parentStmt->is<DoStatement>())) {
John Stilesb61ee902020-09-21 12:26:59 -0400248 return;
249 }
250
251 Block& block = inlinedBody->as<Block>();
252
253 // The inliner will create inlined function bodies as a Block containing multiple statements,
254 // but no scope. Normally, this is fine, but if this block is used as the statement for a
255 // do/for/if/while, this isn't actually possible to represent textually; a scope must be added
256 // for the generated code to match the intent. In the case of Blocks nested inside other Blocks,
257 // we add the scope to the outermost block if needed. Zero-statement blocks have similar
258 // issues--if we don't represent the Block textually somehow, we run the risk of accidentally
259 // absorbing the following statement into our loop--so we also add a scope to these.
260 for (Block* nestedBlock = &block;; ) {
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400261 if (nestedBlock->isScope()) {
John Stilesb61ee902020-09-21 12:26:59 -0400262 // We found an explicit scope; all is well.
263 return;
264 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400265 if (nestedBlock->children().size() != 1) {
John Stilesb61ee902020-09-21 12:26:59 -0400266 // We found a block with multiple (or zero) statements, but no scope? Let's add a scope
267 // to the outermost block.
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400268 block.setIsScope(true);
John Stilesb61ee902020-09-21 12:26:59 -0400269 return;
270 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400271 if (!nestedBlock->children()[0]->is<Block>()) {
John Stilesb61ee902020-09-21 12:26:59 -0400272 // This block has exactly one thing inside, and it's not another block. No need to scope
273 // it.
274 return;
275 }
276 // We have to go deeper.
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400277 nestedBlock = &nestedBlock->children()[0]->as<Block>();
John Stilesb61ee902020-09-21 12:26:59 -0400278 }
279}
280
John Stilesd1204642021-02-17 16:30:02 -0500281void Inliner::reset(ModifiersPool* modifiers) {
Ethan Nicholas041fd0a2020-10-07 16:42:04 -0400282 fModifiers = modifiers;
Ethan Nicholas6f4eee22021-01-11 12:37:42 -0500283 fMangler.reset();
John Stiles031a7672020-11-13 16:13:18 -0500284 fInlinedStatementCounter = 0;
John Stiles44e96be2020-08-31 13:16:04 -0400285}
286
287std::unique_ptr<Expression> Inliner::inlineExpression(int offset,
288 VariableRewriteMap* varMap,
John Stilesd7cc0932020-11-30 12:24:27 -0500289 SymbolTable* symbolTableForExpression,
John Stiles44e96be2020-08-31 13:16:04 -0400290 const Expression& expression) {
291 auto expr = [&](const std::unique_ptr<Expression>& e) -> std::unique_ptr<Expression> {
292 if (e) {
John Stilesd7cc0932020-11-30 12:24:27 -0500293 return this->inlineExpression(offset, varMap, symbolTableForExpression, *e);
John Stiles44e96be2020-08-31 13:16:04 -0400294 }
295 return nullptr;
296 };
John Stiles8e3b6be2020-10-13 11:14:08 -0400297 auto argList = [&](const ExpressionArray& originalArgs) -> ExpressionArray {
298 ExpressionArray args;
John Stilesf4bda742020-10-14 16:57:41 -0400299 args.reserve_back(originalArgs.size());
John Stiles44e96be2020-08-31 13:16:04 -0400300 for (const std::unique_ptr<Expression>& arg : originalArgs) {
301 args.push_back(expr(arg));
302 }
303 return args;
304 };
305
Ethan Nicholase6592142020-09-08 10:22:09 -0400306 switch (expression.kind()) {
307 case Expression::Kind::kBinary: {
John Stiles6a1a98c2021-01-14 18:35:34 -0500308 const BinaryExpression& binaryExpr = expression.as<BinaryExpression>();
John Stilese2aec432021-03-01 09:27:48 -0500309 return BinaryExpression::Make(*fContext,
310 expr(binaryExpr.left()),
311 binaryExpr.getOperator(),
312 expr(binaryExpr.right()));
John Stiles44e96be2020-08-31 13:16:04 -0400313 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400314 case Expression::Kind::kBoolLiteral:
315 case Expression::Kind::kIntLiteral:
316 case Expression::Kind::kFloatLiteral:
John Stiles44e96be2020-08-31 13:16:04 -0400317 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400318 case Expression::Kind::kConstructor: {
John Stiles44e96be2020-08-31 13:16:04 -0400319 const Constructor& constructor = expression.as<Constructor>();
John Stiles23521a82021-03-02 17:02:51 -0500320 auto inlinedCtor = Constructor::Convert(
321 *fContext, offset, *constructor.type().clone(symbolTableForExpression),
322 argList(constructor.arguments()));
323 SkASSERT(inlinedCtor);
324 return inlinedCtor;
John Stiles44e96be2020-08-31 13:16:04 -0400325 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400326 case Expression::Kind::kExternalFunctionCall: {
John Stiles44e96be2020-08-31 13:16:04 -0400327 const ExternalFunctionCall& externalCall = expression.as<ExternalFunctionCall>();
Ethan Nicholas444ccc62020-10-09 10:16:22 -0400328 return std::make_unique<ExternalFunctionCall>(offset, &externalCall.function(),
Ethan Nicholas6e86ec92020-09-30 14:29:56 -0400329 argList(externalCall.arguments()));
John Stiles44e96be2020-08-31 13:16:04 -0400330 }
Brian Osmanbe0b3b72021-01-06 14:27:35 -0500331 case Expression::Kind::kExternalFunctionReference:
John Stiles44e96be2020-08-31 13:16:04 -0400332 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400333 case Expression::Kind::kFieldAccess: {
John Stiles44e96be2020-08-31 13:16:04 -0400334 const FieldAccess& f = expression.as<FieldAccess>();
John Stiles06d600f2021-03-08 09:18:21 -0500335 return FieldAccess::Make(*fContext, expr(f.base()), f.fieldIndex(), f.ownerKind());
John Stiles44e96be2020-08-31 13:16:04 -0400336 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400337 case Expression::Kind::kFunctionCall: {
John Stiles44e96be2020-08-31 13:16:04 -0400338 const FunctionCall& funcCall = expression.as<FunctionCall>();
John Stilesddcc8432021-01-15 15:32:32 -0500339 return std::make_unique<FunctionCall>(offset,
340 funcCall.type().clone(symbolTableForExpression),
341 &funcCall.function(),
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400342 argList(funcCall.arguments()));
John Stiles44e96be2020-08-31 13:16:04 -0400343 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400344 case Expression::Kind::kFunctionReference:
Brian Osman2b3b35f2020-09-08 09:17:36 -0400345 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400346 case Expression::Kind::kIndex: {
John Stiles44e96be2020-08-31 13:16:04 -0400347 const IndexExpression& idx = expression.as<IndexExpression>();
John Stiles51d33982021-03-08 09:18:07 -0500348 return IndexExpression::Make(*fContext, expr(idx.base()), expr(idx.index()));
John Stiles44e96be2020-08-31 13:16:04 -0400349 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400350 case Expression::Kind::kPrefix: {
John Stiles44e96be2020-08-31 13:16:04 -0400351 const PrefixExpression& p = expression.as<PrefixExpression>();
John Stilesb0eb20f2021-02-26 15:29:33 -0500352 return PrefixExpression::Make(*fContext, p.getOperator(), expr(p.operand()));
John Stiles44e96be2020-08-31 13:16:04 -0400353 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400354 case Expression::Kind::kPostfix: {
John Stiles44e96be2020-08-31 13:16:04 -0400355 const PostfixExpression& p = expression.as<PostfixExpression>();
John Stiles52d3b012021-02-26 15:56:48 -0500356 return PostfixExpression::Make(*fContext, expr(p.operand()), p.getOperator());
John Stiles44e96be2020-08-31 13:16:04 -0400357 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400358 case Expression::Kind::kSetting:
John Stiles44e96be2020-08-31 13:16:04 -0400359 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400360 case Expression::Kind::kSwizzle: {
John Stiles44e96be2020-08-31 13:16:04 -0400361 const Swizzle& s = expression.as<Swizzle>();
John Stiles6e88e042021-02-19 14:09:38 -0500362 return Swizzle::Make(*fContext, expr(s.base()), s.components());
John Stiles44e96be2020-08-31 13:16:04 -0400363 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400364 case Expression::Kind::kTernary: {
John Stiles44e96be2020-08-31 13:16:04 -0400365 const TernaryExpression& t = expression.as<TernaryExpression>();
John Stiles90518f72021-02-26 20:44:54 -0500366 return TernaryExpression::Make(*fContext, expr(t.test()),
367 expr(t.ifTrue()), expr(t.ifFalse()));
John Stiles44e96be2020-08-31 13:16:04 -0400368 }
Brian Osman83ba9302020-09-11 13:33:46 -0400369 case Expression::Kind::kTypeReference:
370 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400371 case Expression::Kind::kVariableReference: {
John Stiles44e96be2020-08-31 13:16:04 -0400372 const VariableReference& v = expression.as<VariableReference>();
Ethan Nicholas78686922020-10-08 06:46:27 -0400373 auto varMapIter = varMap->find(v.variable());
John Stilese41b4ee2020-09-28 12:28:16 -0400374 if (varMapIter != varMap->end()) {
Ethan Nicholas78686922020-10-08 06:46:27 -0400375 return clone_with_ref_kind(*varMapIter->second, v.refKind());
John Stiles44e96be2020-08-31 13:16:04 -0400376 }
377 return v.clone();
378 }
379 default:
380 SkASSERT(false);
381 return nullptr;
382 }
383}
384
385std::unique_ptr<Statement> Inliner::inlineStatement(int offset,
386 VariableRewriteMap* varMap,
387 SymbolTable* symbolTableForStatement,
John Stiles77702f12020-12-17 14:38:56 -0500388 std::unique_ptr<Expression>* resultExpr,
389 ReturnComplexity returnComplexity,
Brian Osman3887a012020-09-30 13:22:27 -0400390 const Statement& statement,
391 bool isBuiltinCode) {
John Stiles44e96be2020-08-31 13:16:04 -0400392 auto stmt = [&](const std::unique_ptr<Statement>& s) -> std::unique_ptr<Statement> {
393 if (s) {
John Stilesa5f3c312020-09-22 12:05:16 -0400394 return this->inlineStatement(offset, varMap, symbolTableForStatement, resultExpr,
John Stiles77702f12020-12-17 14:38:56 -0500395 returnComplexity, *s, isBuiltinCode);
John Stiles44e96be2020-08-31 13:16:04 -0400396 }
397 return nullptr;
398 };
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400399 auto blockStmts = [&](const Block& block) {
John Stiles8f2a0cf2020-10-13 12:48:21 -0400400 StatementArray result;
John Stilesf4bda742020-10-14 16:57:41 -0400401 result.reserve_back(block.children().size());
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400402 for (const std::unique_ptr<Statement>& child : block.children()) {
403 result.push_back(stmt(child));
404 }
405 return result;
406 };
John Stiles44e96be2020-08-31 13:16:04 -0400407 auto expr = [&](const std::unique_ptr<Expression>& e) -> std::unique_ptr<Expression> {
408 if (e) {
John Stilesd7cc0932020-11-30 12:24:27 -0500409 return this->inlineExpression(offset, varMap, symbolTableForStatement, *e);
John Stiles44e96be2020-08-31 13:16:04 -0400410 }
411 return nullptr;
412 };
John Stiles031a7672020-11-13 16:13:18 -0500413
414 ++fInlinedStatementCounter;
415
Ethan Nicholase6592142020-09-08 10:22:09 -0400416 switch (statement.kind()) {
417 case Statement::Kind::kBlock: {
John Stiles44e96be2020-08-31 13:16:04 -0400418 const Block& b = statement.as<Block>();
John Stilesbf16b6c2021-03-12 19:24:31 -0500419 return Block::Make(offset, blockStmts(b),
420 SymbolTable::WrapIfBuiltin(b.symbolTable()),
421 b.isScope());
John Stiles44e96be2020-08-31 13:16:04 -0400422 }
423
Ethan Nicholase6592142020-09-08 10:22:09 -0400424 case Statement::Kind::kBreak:
425 case Statement::Kind::kContinue:
426 case Statement::Kind::kDiscard:
John Stiles44e96be2020-08-31 13:16:04 -0400427 return statement.clone();
428
Ethan Nicholase6592142020-09-08 10:22:09 -0400429 case Statement::Kind::kDo: {
John Stiles44e96be2020-08-31 13:16:04 -0400430 const DoStatement& d = statement.as<DoStatement>();
John Stilesea5822e2021-02-26 11:18:20 -0500431 return DoStatement::Make(*fContext, stmt(d.statement()), expr(d.test()));
John Stiles44e96be2020-08-31 13:16:04 -0400432 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400433 case Statement::Kind::kExpression: {
John Stiles44e96be2020-08-31 13:16:04 -0400434 const ExpressionStatement& e = statement.as<ExpressionStatement>();
John Stiles3e5871c2021-02-25 20:52:03 -0500435 return ExpressionStatement::Make(*fContext, expr(e.expression()));
John Stiles44e96be2020-08-31 13:16:04 -0400436 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400437 case Statement::Kind::kFor: {
John Stiles44e96be2020-08-31 13:16:04 -0400438 const ForStatement& f = statement.as<ForStatement>();
439 // need to ensure initializer is evaluated first so that we've already remapped its
440 // declarations by the time we evaluate test & next
Ethan Nicholas0d31ed52020-10-05 14:47:09 -0400441 std::unique_ptr<Statement> initializer = stmt(f.initializer());
John Stilesb321a072021-02-25 16:24:19 -0500442 return ForStatement::Make(*fContext, offset, std::move(initializer), expr(f.test()),
443 expr(f.next()), stmt(f.statement()),
444 SymbolTable::WrapIfBuiltin(f.symbols()));
John Stiles44e96be2020-08-31 13:16:04 -0400445 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400446 case Statement::Kind::kIf: {
John Stiles44e96be2020-08-31 13:16:04 -0400447 const IfStatement& i = statement.as<IfStatement>();
John Stilescf3059e2021-02-25 14:27:02 -0500448 return IfStatement::Make(*fContext, offset, i.isStatic(), expr(i.test()),
449 stmt(i.ifTrue()), stmt(i.ifFalse()));
John Stiles44e96be2020-08-31 13:16:04 -0400450 }
John Stiles98c1f822020-09-09 14:18:53 -0400451 case Statement::Kind::kInlineMarker:
Ethan Nicholase6592142020-09-08 10:22:09 -0400452 case Statement::Kind::kNop:
John Stiles44e96be2020-08-31 13:16:04 -0400453 return statement.clone();
John Stilesea5822e2021-02-26 11:18:20 -0500454
Ethan Nicholase6592142020-09-08 10:22:09 -0400455 case Statement::Kind::kReturn: {
John Stiles44e96be2020-08-31 13:16:04 -0400456 const ReturnStatement& r = statement.as<ReturnStatement>();
John Stiles77702f12020-12-17 14:38:56 -0500457 if (!r.expression()) {
John Stilesdc208472021-03-17 10:58:16 -0400458 // This function doesn't return a value. We won't inline functions with early
459 // returns, so a return statement is a no-op and can be treated as such.
460 return Nop::Make();
John Stiles44e96be2020-08-31 13:16:04 -0400461 }
John Stiles77702f12020-12-17 14:38:56 -0500462
John Stilesc5ff4862020-12-22 13:47:05 -0500463 // If a function only contains a single return, and it doesn't reference variables from
464 // inside an Block's scope, we don't need to store the result in a variable at all. Just
465 // replace the function-call expression with the function's return expression.
John Stiles77702f12020-12-17 14:38:56 -0500466 SkASSERT(resultExpr);
John Stilesc5ff4862020-12-22 13:47:05 -0500467 if (returnComplexity <= ReturnComplexity::kSingleSafeReturn) {
John Stiles77702f12020-12-17 14:38:56 -0500468 *resultExpr = expr(r.expression());
John Stilesa0c04d62021-03-11 23:07:24 -0500469 return Nop::Make();
John Stiles77702f12020-12-17 14:38:56 -0500470 }
471
472 // For more complex functions, assign their result into a variable.
John Stiles511c5002021-02-25 11:17:02 -0500473 SkASSERT(*resultExpr);
John Stiles3e5871c2021-02-25 20:52:03 -0500474 auto assignment = ExpressionStatement::Make(
475 *fContext,
John Stilese2aec432021-03-01 09:27:48 -0500476 BinaryExpression::Make(
477 *fContext,
478 clone_with_ref_kind(**resultExpr, VariableRefKind::kWrite),
John Stiles77702f12020-12-17 14:38:56 -0500479 Token::Kind::TK_EQ,
John Stilese2aec432021-03-01 09:27:48 -0500480 expr(r.expression())));
John Stiles77702f12020-12-17 14:38:56 -0500481
John Stiles77702f12020-12-17 14:38:56 -0500482 // Functions without early returns aren't wrapped in a for loop and don't need to worry
483 // about breaking out of the control flow.
John Stiles3e5871c2021-02-25 20:52:03 -0500484 return assignment;
John Stiles44e96be2020-08-31 13:16:04 -0400485 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400486 case Statement::Kind::kSwitch: {
John Stiles44e96be2020-08-31 13:16:04 -0400487 const SwitchStatement& ss = statement.as<SwitchStatement>();
John Stilesb23a64b2021-03-11 08:27:59 -0500488 StatementArray cases;
489 cases.reserve_back(ss.cases().size());
490 for (const std::unique_ptr<Statement>& statement : ss.cases()) {
491 const SwitchCase& sc = statement->as<SwitchCase>();
492 cases.push_back(std::make_unique<SwitchCase>(offset, expr(sc.value()),
493 stmt(sc.statement())));
John Stiles44e96be2020-08-31 13:16:04 -0400494 }
John Stilese1d1b082021-02-23 13:44:36 -0500495 return SwitchStatement::Make(*fContext, offset, ss.isStatic(), expr(ss.value()),
496 std::move(cases), SymbolTable::WrapIfBuiltin(ss.symbols()));
John Stiles44e96be2020-08-31 13:16:04 -0400497 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400498 case Statement::Kind::kVarDeclaration: {
John Stiles44e96be2020-08-31 13:16:04 -0400499 const VarDeclaration& decl = statement.as<VarDeclaration>();
John Stiles35fee4c2020-12-16 18:25:14 +0000500 std::unique_ptr<Expression> initialValue = expr(decl.value());
John Stilesddcc8432021-01-15 15:32:32 -0500501 const Variable& variable = decl.var();
502
John Stiles35fee4c2020-12-16 18:25:14 +0000503 // We assign unique names to inlined variables--scopes hide most of the problems in this
504 // regard, but see `InlinerAvoidsVariableNameOverlap` for a counterexample where unique
505 // names are important.
John Stilesddcc8432021-01-15 15:32:32 -0500506 auto name = std::make_unique<String>(fMangler.uniqueName(variable.name(),
Ethan Nicholas6f4eee22021-01-11 12:37:42 -0500507 symbolTableForStatement));
John Stiles35fee4c2020-12-16 18:25:14 +0000508 const String* namePtr = symbolTableForStatement->takeOwnershipOfString(std::move(name));
Ethan Nicholas5b9b0db2021-01-21 13:12:01 -0500509 auto clonedVar = std::make_unique<Variable>(
510 offset,
511 &variable.modifiers(),
512 namePtr->c_str(),
513 variable.type().clone(symbolTableForStatement),
514 isBuiltinCode,
515 variable.storage());
516 (*varMap)[&variable] = std::make_unique<VariableReference>(offset, clonedVar.get());
517 auto result = std::make_unique<VarDeclaration>(clonedVar.get(),
John Stilesddcc8432021-01-15 15:32:32 -0500518 decl.baseType().clone(symbolTableForStatement),
519 decl.arraySize(),
John Stiles35fee4c2020-12-16 18:25:14 +0000520 std::move(initialValue));
Ethan Nicholas5b9b0db2021-01-21 13:12:01 -0500521 clonedVar->setDeclaration(result.get());
522 symbolTableForStatement->takeOwnershipOfSymbol(std::move(clonedVar));
523 return std::move(result);
John Stiles44e96be2020-08-31 13:16:04 -0400524 }
John Stiles44e96be2020-08-31 13:16:04 -0400525 default:
526 SkASSERT(false);
527 return nullptr;
528 }
529}
530
John Stiles7b920442020-12-17 10:43:41 -0500531Inliner::InlineVariable Inliner::makeInlineVariable(const String& baseName,
532 const Type* type,
533 SymbolTable* symbolTable,
534 Modifiers modifiers,
535 bool isBuiltinCode,
536 std::unique_ptr<Expression>* initialValue) {
537 // $floatLiteral or $intLiteral aren't real types that we can use for scratch variables, so
538 // replace them if they ever appear here. If this happens, we likely forgot to coerce a type
539 // somewhere during compilation.
John Stiles14975272021-01-12 11:41:14 -0500540 if (type->isLiteral()) {
541 SkDEBUGFAIL("found a $literal type while inlining");
542 type = &type->scalarTypeForLiteral();
John Stiles7b920442020-12-17 10:43:41 -0500543 }
544
545 // Provide our new variable with a unique name, and add it to our symbol table.
546 const String* namePtr = symbolTable->takeOwnershipOfString(
Ethan Nicholas6f4eee22021-01-11 12:37:42 -0500547 std::make_unique<String>(fMangler.uniqueName(baseName, symbolTable)));
John Stiles7b920442020-12-17 10:43:41 -0500548 StringFragment nameFrag{namePtr->c_str(), namePtr->length()};
549
550 // Create our new variable and add it to the symbol table.
551 InlineVariable result;
Ethan Nicholas5b9b0db2021-01-21 13:12:01 -0500552 auto var = std::make_unique<Variable>(/*offset=*/-1,
553 fModifiers->addToPool(Modifiers()),
554 nameFrag,
555 type,
556 isBuiltinCode,
557 Variable::Storage::kLocal);
John Stiles7b920442020-12-17 10:43:41 -0500558
559 // Prepare the variable declaration (taking extra care with `out` params to not clobber any
560 // initial value).
561 if (*initialValue && (modifiers.fFlags & Modifiers::kOut_Flag)) {
Ethan Nicholas5b9b0db2021-01-21 13:12:01 -0500562 result.fVarDecl = std::make_unique<VarDeclaration>(var.get(), type, /*arraySize=*/0,
John Stiles7b920442020-12-17 10:43:41 -0500563 (*initialValue)->clone());
564 } else {
Ethan Nicholas5b9b0db2021-01-21 13:12:01 -0500565 result.fVarDecl = std::make_unique<VarDeclaration>(var.get(), type, /*arraySize=*/0,
John Stiles7b920442020-12-17 10:43:41 -0500566 std::move(*initialValue));
567 }
Ethan Nicholas5b9b0db2021-01-21 13:12:01 -0500568 var->setDeclaration(&result.fVarDecl->as<VarDeclaration>());
569 result.fVarSymbol = symbolTable->add(std::move(var));
John Stiles7b920442020-12-17 10:43:41 -0500570 return result;
571}
572
John Stiles6eadf132020-09-08 10:16:10 -0400573Inliner::InlinedCall Inliner::inlineCall(FunctionCall* call,
John Stiles78047582020-12-16 16:17:41 -0500574 std::shared_ptr<SymbolTable> symbolTable,
Brian Osman3887a012020-09-30 13:22:27 -0400575 const FunctionDeclaration* caller) {
John Stiles44e96be2020-08-31 13:16:04 -0400576 // Inlining is more complicated here than in a typical compiler, because we have to have a
577 // high-level IR and can't just drop statements into the middle of an expression or even use
578 // gotos.
579 //
580 // Since we can't insert statements into an expression, we run the inline function as extra
581 // statements before the statement we're currently processing, relying on a lack of execution
582 // order guarantees. Since we can't use gotos (which are normally used to replace return
583 // statements), we wrap the whole function in a loop and use break statements to jump to the
584 // end.
John Stiles44e96be2020-08-31 13:16:04 -0400585 SkASSERT(fContext);
586 SkASSERT(call);
Ethan Nicholased84b732020-10-08 11:45:44 -0400587 SkASSERT(this->isSafeToInline(call->function().definition()));
John Stiles44e96be2020-08-31 13:16:04 -0400588
John Stiles8e3b6be2020-10-13 11:14:08 -0400589 ExpressionArray& arguments = call->arguments();
John Stiles6eadf132020-09-08 10:16:10 -0400590 const int offset = call->fOffset;
Ethan Nicholased84b732020-10-08 11:45:44 -0400591 const FunctionDefinition& function = *call->function().definition();
John Stiles77702f12020-12-17 14:38:56 -0500592 const ReturnComplexity returnComplexity = GetReturnComplexity(function);
John Stiles6eadf132020-09-08 10:16:10 -0400593
John Stiles44e96be2020-08-31 13:16:04 -0400594 InlinedCall inlinedCall;
John Stilesbf16b6c2021-03-12 19:24:31 -0500595 StatementArray inlinedBlockStmts;
596 inlinedBlockStmts.reserve_back(1 + // Inline marker
597 1 + // Result variable
598 arguments.size() + // Function arguments (passing in)
599 arguments.size() + // Function arguments (copy out-params back)
600 1); // Block for inlined code
John Stiles98c1f822020-09-09 14:18:53 -0400601
John Stilesbf16b6c2021-03-12 19:24:31 -0500602 inlinedBlockStmts.push_back(InlineMarker::Make(&call->function()));
John Stiles44e96be2020-08-31 13:16:04 -0400603
John Stilese41b4ee2020-09-28 12:28:16 -0400604 std::unique_ptr<Expression> resultExpr;
John Stiles511c5002021-02-25 11:17:02 -0500605 if (returnComplexity > ReturnComplexity::kSingleSafeReturn &&
John Stiles2558c462021-03-16 17:49:20 -0400606 !function.declaration().returnType().isVoid()) {
John Stiles511c5002021-02-25 11:17:02 -0500607 // Create a variable to hold the result in the extra statements. We don't need to do this
608 // for void-return functions, or in cases that are simple enough that we can just replace
609 // the function-call node with the result expression.
John Stiles44e96be2020-08-31 13:16:04 -0400610 std::unique_ptr<Expression> noInitialValue;
John Stiles7b920442020-12-17 10:43:41 -0500611 InlineVariable var = this->makeInlineVariable(function.declaration().name(),
612 &function.declaration().returnType(),
613 symbolTable.get(), Modifiers{},
614 caller->isBuiltin(), &noInitialValue);
John Stilesbf16b6c2021-03-12 19:24:31 -0500615 inlinedBlockStmts.push_back(std::move(var.fVarDecl));
John Stiles7b920442020-12-17 10:43:41 -0500616 resultExpr = std::make_unique<VariableReference>(/*offset=*/-1, var.fVarSymbol);
John Stiles511c5002021-02-25 11:17:02 -0500617 }
John Stiles44e96be2020-08-31 13:16:04 -0400618
619 // Create variables in the extra statements to hold the arguments, and assign the arguments to
620 // them.
621 VariableRewriteMap varMap;
John Stilese41b4ee2020-09-28 12:28:16 -0400622 std::vector<int> argsToCopyBack;
John Stiles44e96be2020-08-31 13:16:04 -0400623 for (int i = 0; i < (int) arguments.size(); ++i) {
Ethan Nicholas0a5d0962020-10-14 13:33:18 -0400624 const Variable* param = function.declaration().parameters()[i];
Ethan Nicholas041fd0a2020-10-07 16:42:04 -0400625 bool isOutParam = param->modifiers().fFlags & Modifiers::kOut_Flag;
John Stiles44e96be2020-08-31 13:16:04 -0400626
John Stiles44733aa2020-09-29 17:42:23 -0400627 // If this argument can be inlined trivially (e.g. a swizzle, or a constant array index)...
John Stilesc30fbca2020-11-19 16:25:49 -0500628 if (Analysis::IsTrivialExpression(*arguments[i])) {
John Stilese41b4ee2020-09-28 12:28:16 -0400629 // ... and it's an `out` param, or it isn't written to within the inline function...
Ethan Nicholas0a5d0962020-10-14 13:33:18 -0400630 if (isOutParam || !Analysis::StatementWritesToVariable(*function.body(), *param)) {
John Stilesf201af82020-09-29 16:57:55 -0400631 // ... we don't need to copy it at all! We can just use the existing expression.
632 varMap[param] = arguments[i]->clone();
John Stiles44e96be2020-08-31 13:16:04 -0400633 continue;
634 }
635 }
John Stilese41b4ee2020-09-28 12:28:16 -0400636 if (isOutParam) {
637 argsToCopyBack.push_back(i);
638 }
John Stiles7b920442020-12-17 10:43:41 -0500639 InlineVariable var = this->makeInlineVariable(param->name(), &arguments[i]->type(),
640 symbolTable.get(), param->modifiers(),
641 caller->isBuiltin(), &arguments[i]);
John Stilesbf16b6c2021-03-12 19:24:31 -0500642 inlinedBlockStmts.push_back(std::move(var.fVarDecl));
John Stiles7b920442020-12-17 10:43:41 -0500643 varMap[param] = std::make_unique<VariableReference>(/*offset=*/-1, var.fVarSymbol);
John Stiles44e96be2020-08-31 13:16:04 -0400644 }
645
Ethan Nicholas0a5d0962020-10-14 13:33:18 -0400646 const Block& body = function.body()->as<Block>();
John Stilesdc208472021-03-17 10:58:16 -0400647 StatementArray* inlineStatements = &inlinedBlockStmts;
John Stiles7b920442020-12-17 10:43:41 -0500648
649 inlineStatements->reserve_back(body.children().size() + argsToCopyBack.size());
650 for (const std::unique_ptr<Statement>& stmt : body.children()) {
651 inlineStatements->push_back(this->inlineStatement(offset, &varMap, symbolTable.get(),
John Stiles77702f12020-12-17 14:38:56 -0500652 &resultExpr, returnComplexity, *stmt,
John Stiles7b920442020-12-17 10:43:41 -0500653 caller->isBuiltin()));
John Stiles44e96be2020-08-31 13:16:04 -0400654 }
655
John Stilese41b4ee2020-09-28 12:28:16 -0400656 // Copy back the values of `out` parameters into their real destinations.
657 for (int i : argsToCopyBack) {
Ethan Nicholas0a5d0962020-10-14 13:33:18 -0400658 const Variable* p = function.declaration().parameters()[i];
John Stilese41b4ee2020-09-28 12:28:16 -0400659 SkASSERT(varMap.find(p) != varMap.end());
John Stiles3e5871c2021-02-25 20:52:03 -0500660 inlineStatements->push_back(ExpressionStatement::Make(
661 *fContext,
John Stilese2aec432021-03-01 09:27:48 -0500662 BinaryExpression::Make(*fContext,
663 clone_with_ref_kind(*arguments[i], VariableRefKind::kWrite),
664 Token::Kind::TK_EQ,
665 std::move(varMap[p]))));
John Stiles44e96be2020-08-31 13:16:04 -0400666 }
667
John Stilesbf16b6c2021-03-12 19:24:31 -0500668 // Wrap all of the generated statements in a block. We need a real Block here, so we can't use
669 // MakeUnscoped. This is because we need to add another child statement to the Block later.
670 inlinedCall.fInlinedBody = Block::Make(offset, std::move(inlinedBlockStmts),
671 /*symbols=*/nullptr, /*isScope=*/false);
672
John Stiles0c2d14a2021-03-01 10:08:08 -0500673 if (resultExpr) {
674 // Return our result expression as-is.
John Stilese41b4ee2020-09-28 12:28:16 -0400675 inlinedCall.fReplacementExpr = std::move(resultExpr);
John Stiles2558c462021-03-16 17:49:20 -0400676 } else if (function.declaration().returnType().isVoid()) {
John Stiles44e96be2020-08-31 13:16:04 -0400677 // It's a void function, so it doesn't actually result in anything, but we have to return
678 // something non-null as a standin.
John Stiles9ce80f72021-03-11 22:35:19 -0500679 inlinedCall.fReplacementExpr = BoolLiteral::Make(*fContext, offset, /*value=*/false);
John Stiles0c2d14a2021-03-01 10:08:08 -0500680 } else {
681 // It's a non-void function, but it never created a result expression--that is, it never
John Stiles2dda50d2021-03-03 10:46:44 -0500682 // returned anything on any path! This should have been detected in the function finalizer.
683 // Still, discard our output and generate an error.
684 SkDEBUGFAIL("inliner found non-void function that fails to return a value on any path");
685 fContext->fErrors.error(function.fOffset, "inliner found non-void function '" +
John Stiles0c2d14a2021-03-01 10:08:08 -0500686 function.declaration().name() +
John Stiles2dda50d2021-03-03 10:46:44 -0500687 "' that fails to return a value on any path");
John Stiles0c2d14a2021-03-01 10:08:08 -0500688 inlinedCall = {};
John Stiles44e96be2020-08-31 13:16:04 -0400689 }
690
John Stiles44e96be2020-08-31 13:16:04 -0400691 return inlinedCall;
692}
693
John Stiles2d7973a2020-10-02 15:01:03 -0400694bool Inliner::isSafeToInline(const FunctionDefinition* functionDef) {
John Stiles1c03d332020-10-13 10:30:23 -0400695 // A threshold of zero indicates that the inliner is completely disabled, so we can just return.
John Stilesd1204642021-02-17 16:30:02 -0500696 if (this->settings().fInlineThreshold <= 0) {
John Stiles1c03d332020-10-13 10:30:23 -0400697 return false;
698 }
699
John Stiles031a7672020-11-13 16:13:18 -0500700 // Enforce a limit on inlining to avoid pathological cases. (inliner/ExponentialGrowth.sksl)
701 if (fInlinedStatementCounter >= kInlinedStatementLimit) {
702 return false;
703 }
704
John Stiles2d7973a2020-10-02 15:01:03 -0400705 if (functionDef == nullptr) {
John Stiles44e96be2020-08-31 13:16:04 -0400706 // Can't inline something if we don't actually have its definition.
707 return false;
708 }
John Stiles2d7973a2020-10-02 15:01:03 -0400709
John Stiles0dd1a772021-03-09 22:14:27 -0500710 if (functionDef->declaration().modifiers().fFlags & Modifiers::kNoInline_Flag) {
711 // Refuse to inline functions decorated with `noinline`.
712 return false;
713 }
714
John Stilesdc208472021-03-17 10:58:16 -0400715 // We don't have a mechanism to simulate early returns, so we can't inline if there is one.
716 return GetReturnComplexity(*functionDef) < ReturnComplexity::kEarlyReturns;
John Stiles44e96be2020-08-31 13:16:04 -0400717}
718
John Stiles2d7973a2020-10-02 15:01:03 -0400719// A candidate function for inlining, containing everything that `inlineCall` needs.
720struct InlineCandidate {
John Stiles78047582020-12-16 16:17:41 -0500721 std::shared_ptr<SymbolTable> fSymbols; // the SymbolTable of the candidate
John Stiles2d7973a2020-10-02 15:01:03 -0400722 std::unique_ptr<Statement>* fParentStmt; // the parent Statement of the enclosing stmt
723 std::unique_ptr<Statement>* fEnclosingStmt; // the Statement containing the candidate
724 std::unique_ptr<Expression>* fCandidateExpr; // the candidate FunctionCall to be inlined
725 FunctionDefinition* fEnclosingFunction; // the Function containing the candidate
John Stiles2d7973a2020-10-02 15:01:03 -0400726};
John Stiles93442622020-09-11 12:11:27 -0400727
John Stiles2d7973a2020-10-02 15:01:03 -0400728struct InlineCandidateList {
729 std::vector<InlineCandidate> fCandidates;
730};
731
732class InlineCandidateAnalyzer {
John Stiles70957c82020-10-02 16:42:10 -0400733public:
734 // A list of all the inlining candidates we found during analysis.
735 InlineCandidateList* fCandidateList;
John Stiles2d7973a2020-10-02 15:01:03 -0400736
John Stiles70957c82020-10-02 16:42:10 -0400737 // A stack of the symbol tables; since most nodes don't have one, expected to be shallower than
738 // the enclosing-statement stack.
John Stiles78047582020-12-16 16:17:41 -0500739 std::vector<std::shared_ptr<SymbolTable>> fSymbolTableStack;
John Stiles70957c82020-10-02 16:42:10 -0400740 // A stack of "enclosing" statements--these would be suitable for the inliner to use for adding
741 // new instructions. Not all statements are suitable (e.g. a for-loop's initializer). The
742 // inliner might replace a statement with a block containing the statement.
743 std::vector<std::unique_ptr<Statement>*> fEnclosingStmtStack;
744 // The function that we're currently processing (i.e. inlining into).
745 FunctionDefinition* fEnclosingFunction = nullptr;
John Stiles93442622020-09-11 12:11:27 -0400746
Brian Osman0006ad02020-11-18 15:38:39 -0500747 void visit(const std::vector<std::unique_ptr<ProgramElement>>& elements,
John Stiles78047582020-12-16 16:17:41 -0500748 std::shared_ptr<SymbolTable> symbols,
Brian Osman0006ad02020-11-18 15:38:39 -0500749 InlineCandidateList* candidateList) {
John Stiles70957c82020-10-02 16:42:10 -0400750 fCandidateList = candidateList;
Brian Osman0006ad02020-11-18 15:38:39 -0500751 fSymbolTableStack.push_back(symbols);
John Stiles93442622020-09-11 12:11:27 -0400752
Brian Osman0006ad02020-11-18 15:38:39 -0500753 for (const std::unique_ptr<ProgramElement>& pe : elements) {
Brian Osman1179fcf2020-10-08 16:04:40 -0400754 this->visitProgramElement(pe.get());
John Stiles93442622020-09-11 12:11:27 -0400755 }
756
John Stiles70957c82020-10-02 16:42:10 -0400757 fSymbolTableStack.pop_back();
758 fCandidateList = nullptr;
759 }
760
761 void visitProgramElement(ProgramElement* pe) {
762 switch (pe->kind()) {
763 case ProgramElement::Kind::kFunction: {
764 FunctionDefinition& funcDef = pe->as<FunctionDefinition>();
Brian Osman0006ad02020-11-18 15:38:39 -0500765 fEnclosingFunction = &funcDef;
766 this->visitStatement(&funcDef.body());
John Stiles70957c82020-10-02 16:42:10 -0400767 break;
John Stiles93442622020-09-11 12:11:27 -0400768 }
John Stiles70957c82020-10-02 16:42:10 -0400769 default:
770 // The inliner can't operate outside of a function's scope.
771 break;
772 }
773 }
774
775 void visitStatement(std::unique_ptr<Statement>* stmt,
776 bool isViableAsEnclosingStatement = true) {
777 if (!*stmt) {
778 return;
John Stiles93442622020-09-11 12:11:27 -0400779 }
780
John Stiles70957c82020-10-02 16:42:10 -0400781 size_t oldEnclosingStmtStackSize = fEnclosingStmtStack.size();
782 size_t oldSymbolStackSize = fSymbolTableStack.size();
John Stiles93442622020-09-11 12:11:27 -0400783
John Stiles70957c82020-10-02 16:42:10 -0400784 if (isViableAsEnclosingStatement) {
785 fEnclosingStmtStack.push_back(stmt);
John Stiles93442622020-09-11 12:11:27 -0400786 }
787
John Stiles70957c82020-10-02 16:42:10 -0400788 switch ((*stmt)->kind()) {
789 case Statement::Kind::kBreak:
790 case Statement::Kind::kContinue:
791 case Statement::Kind::kDiscard:
792 case Statement::Kind::kInlineMarker:
793 case Statement::Kind::kNop:
794 break;
795
796 case Statement::Kind::kBlock: {
797 Block& block = (*stmt)->as<Block>();
798 if (block.symbolTable()) {
John Stiles78047582020-12-16 16:17:41 -0500799 fSymbolTableStack.push_back(block.symbolTable());
John Stiles70957c82020-10-02 16:42:10 -0400800 }
801
802 for (std::unique_ptr<Statement>& stmt : block.children()) {
803 this->visitStatement(&stmt);
804 }
805 break;
John Stiles93442622020-09-11 12:11:27 -0400806 }
John Stiles70957c82020-10-02 16:42:10 -0400807 case Statement::Kind::kDo: {
808 DoStatement& doStmt = (*stmt)->as<DoStatement>();
809 // The loop body is a candidate for inlining.
810 this->visitStatement(&doStmt.statement());
811 // The inliner isn't smart enough to inline the test-expression for a do-while
812 // loop at this time. There are two limitations:
813 // - We would need to insert the inlined-body block at the very end of the do-
814 // statement's inner fStatement. We don't support that today, but it's doable.
815 // - We cannot inline the test expression if the loop uses `continue` anywhere; that
816 // would skip over the inlined block that evaluates the test expression. There
817 // isn't a good fix for this--any workaround would be more complex than the cost
818 // of a function call. However, loops that don't use `continue` would still be
819 // viable candidates for inlining.
820 break;
John Stiles93442622020-09-11 12:11:27 -0400821 }
John Stiles70957c82020-10-02 16:42:10 -0400822 case Statement::Kind::kExpression: {
823 ExpressionStatement& expr = (*stmt)->as<ExpressionStatement>();
824 this->visitExpression(&expr.expression());
825 break;
826 }
827 case Statement::Kind::kFor: {
828 ForStatement& forStmt = (*stmt)->as<ForStatement>();
Ethan Nicholas0d31ed52020-10-05 14:47:09 -0400829 if (forStmt.symbols()) {
John Stiles78047582020-12-16 16:17:41 -0500830 fSymbolTableStack.push_back(forStmt.symbols());
John Stiles70957c82020-10-02 16:42:10 -0400831 }
832
833 // The initializer and loop body are candidates for inlining.
Ethan Nicholas0d31ed52020-10-05 14:47:09 -0400834 this->visitStatement(&forStmt.initializer(),
John Stiles70957c82020-10-02 16:42:10 -0400835 /*isViableAsEnclosingStatement=*/false);
Ethan Nicholas0d31ed52020-10-05 14:47:09 -0400836 this->visitStatement(&forStmt.statement());
John Stiles70957c82020-10-02 16:42:10 -0400837
838 // The inliner isn't smart enough to inline the test- or increment-expressions
839 // of a for loop loop at this time. There are a handful of limitations:
840 // - We would need to insert the test-expression block at the very beginning of the
841 // for-loop's inner fStatement, and the increment-expression block at the very
842 // end. We don't support that today, but it's doable.
843 // - The for-loop's built-in test-expression would need to be dropped entirely,
844 // and the loop would be halted via a break statement at the end of the inlined
845 // test-expression. This is again something we don't support today, but it could
846 // be implemented.
847 // - We cannot inline the increment-expression if the loop uses `continue` anywhere;
848 // that would skip over the inlined block that evaluates the increment expression.
849 // There isn't a good fix for this--any workaround would be more complex than the
850 // cost of a function call. However, loops that don't use `continue` would still
851 // be viable candidates for increment-expression inlining.
852 break;
853 }
854 case Statement::Kind::kIf: {
855 IfStatement& ifStmt = (*stmt)->as<IfStatement>();
Ethan Nicholas8c44eca2020-10-07 16:47:09 -0400856 this->visitExpression(&ifStmt.test());
857 this->visitStatement(&ifStmt.ifTrue());
858 this->visitStatement(&ifStmt.ifFalse());
John Stiles70957c82020-10-02 16:42:10 -0400859 break;
860 }
861 case Statement::Kind::kReturn: {
862 ReturnStatement& returnStmt = (*stmt)->as<ReturnStatement>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -0400863 this->visitExpression(&returnStmt.expression());
John Stiles70957c82020-10-02 16:42:10 -0400864 break;
865 }
866 case Statement::Kind::kSwitch: {
867 SwitchStatement& switchStmt = (*stmt)->as<SwitchStatement>();
Ethan Nicholas01b05e52020-10-22 15:53:41 -0400868 if (switchStmt.symbols()) {
John Stiles78047582020-12-16 16:17:41 -0500869 fSymbolTableStack.push_back(switchStmt.symbols());
John Stiles70957c82020-10-02 16:42:10 -0400870 }
871
Ethan Nicholas01b05e52020-10-22 15:53:41 -0400872 this->visitExpression(&switchStmt.value());
John Stilesb23a64b2021-03-11 08:27:59 -0500873 for (const std::unique_ptr<Statement>& switchCase : switchStmt.cases()) {
John Stiles70957c82020-10-02 16:42:10 -0400874 // The switch-case's fValue cannot be a FunctionCall; skip it.
John Stilesb23a64b2021-03-11 08:27:59 -0500875 this->visitStatement(&switchCase->as<SwitchCase>().statement());
John Stiles70957c82020-10-02 16:42:10 -0400876 }
877 break;
878 }
879 case Statement::Kind::kVarDeclaration: {
880 VarDeclaration& varDeclStmt = (*stmt)->as<VarDeclaration>();
881 // Don't need to scan the declaration's sizes; those are always IntLiterals.
Ethan Nicholasc51f33e2020-10-13 13:49:44 -0400882 this->visitExpression(&varDeclStmt.value());
John Stiles70957c82020-10-02 16:42:10 -0400883 break;
884 }
John Stiles70957c82020-10-02 16:42:10 -0400885 default:
886 SkUNREACHABLE;
John Stiles93442622020-09-11 12:11:27 -0400887 }
888
John Stiles70957c82020-10-02 16:42:10 -0400889 // Pop our symbol and enclosing-statement stacks.
890 fSymbolTableStack.resize(oldSymbolStackSize);
891 fEnclosingStmtStack.resize(oldEnclosingStmtStackSize);
892 }
893
894 void visitExpression(std::unique_ptr<Expression>* expr) {
895 if (!*expr) {
896 return;
John Stiles93442622020-09-11 12:11:27 -0400897 }
John Stiles70957c82020-10-02 16:42:10 -0400898
899 switch ((*expr)->kind()) {
900 case Expression::Kind::kBoolLiteral:
901 case Expression::Kind::kDefined:
Brian Osmanbe0b3b72021-01-06 14:27:35 -0500902 case Expression::Kind::kExternalFunctionReference:
John Stiles70957c82020-10-02 16:42:10 -0400903 case Expression::Kind::kFieldAccess:
904 case Expression::Kind::kFloatLiteral:
905 case Expression::Kind::kFunctionReference:
906 case Expression::Kind::kIntLiteral:
John Stiles70957c82020-10-02 16:42:10 -0400907 case Expression::Kind::kSetting:
908 case Expression::Kind::kTypeReference:
909 case Expression::Kind::kVariableReference:
910 // Nothing to scan here.
911 break;
912
913 case Expression::Kind::kBinary: {
914 BinaryExpression& binaryExpr = (*expr)->as<BinaryExpression>();
John Stiles2d4f9592020-10-30 10:29:12 -0400915 this->visitExpression(&binaryExpr.left());
John Stiles70957c82020-10-02 16:42:10 -0400916
917 // Logical-and and logical-or binary expressions do not inline the right side,
918 // because that would invalidate short-circuiting. That is, when evaluating
919 // expressions like these:
920 // (false && x()) // always false
921 // (true || y()) // always true
922 // It is illegal for side-effects from x() or y() to occur. The simplest way to
923 // enforce that rule is to avoid inlining the right side entirely. However, it is
924 // safe for other types of binary expression to inline both sides.
John Stiles45990502021-02-16 10:55:27 -0500925 Operator op = binaryExpr.getOperator();
926 bool shortCircuitable = (op.kind() == Token::Kind::TK_LOGICALAND ||
927 op.kind() == Token::Kind::TK_LOGICALOR);
John Stiles70957c82020-10-02 16:42:10 -0400928 if (!shortCircuitable) {
John Stiles2d4f9592020-10-30 10:29:12 -0400929 this->visitExpression(&binaryExpr.right());
John Stiles70957c82020-10-02 16:42:10 -0400930 }
931 break;
932 }
933 case Expression::Kind::kConstructor: {
934 Constructor& constructorExpr = (*expr)->as<Constructor>();
935 for (std::unique_ptr<Expression>& arg : constructorExpr.arguments()) {
936 this->visitExpression(&arg);
937 }
938 break;
939 }
940 case Expression::Kind::kExternalFunctionCall: {
941 ExternalFunctionCall& funcCallExpr = (*expr)->as<ExternalFunctionCall>();
942 for (std::unique_ptr<Expression>& arg : funcCallExpr.arguments()) {
943 this->visitExpression(&arg);
944 }
945 break;
946 }
947 case Expression::Kind::kFunctionCall: {
948 FunctionCall& funcCallExpr = (*expr)->as<FunctionCall>();
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400949 for (std::unique_ptr<Expression>& arg : funcCallExpr.arguments()) {
John Stiles70957c82020-10-02 16:42:10 -0400950 this->visitExpression(&arg);
951 }
952 this->addInlineCandidate(expr);
953 break;
954 }
955 case Expression::Kind::kIndex:{
956 IndexExpression& indexExpr = (*expr)->as<IndexExpression>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -0400957 this->visitExpression(&indexExpr.base());
958 this->visitExpression(&indexExpr.index());
John Stiles70957c82020-10-02 16:42:10 -0400959 break;
960 }
961 case Expression::Kind::kPostfix: {
962 PostfixExpression& postfixExpr = (*expr)->as<PostfixExpression>();
Ethan Nicholas444ccc62020-10-09 10:16:22 -0400963 this->visitExpression(&postfixExpr.operand());
John Stiles70957c82020-10-02 16:42:10 -0400964 break;
965 }
966 case Expression::Kind::kPrefix: {
967 PrefixExpression& prefixExpr = (*expr)->as<PrefixExpression>();
Ethan Nicholas444ccc62020-10-09 10:16:22 -0400968 this->visitExpression(&prefixExpr.operand());
John Stiles70957c82020-10-02 16:42:10 -0400969 break;
970 }
971 case Expression::Kind::kSwizzle: {
972 Swizzle& swizzleExpr = (*expr)->as<Swizzle>();
Ethan Nicholas6b4d5812020-10-12 16:11:51 -0400973 this->visitExpression(&swizzleExpr.base());
John Stiles70957c82020-10-02 16:42:10 -0400974 break;
975 }
976 case Expression::Kind::kTernary: {
977 TernaryExpression& ternaryExpr = (*expr)->as<TernaryExpression>();
978 // The test expression is a candidate for inlining.
Ethan Nicholasdd218162020-10-08 05:48:01 -0400979 this->visitExpression(&ternaryExpr.test());
John Stiles70957c82020-10-02 16:42:10 -0400980 // The true- and false-expressions cannot be inlined, because we are only allowed to
981 // evaluate one side.
982 break;
983 }
984 default:
985 SkUNREACHABLE;
986 }
987 }
988
989 void addInlineCandidate(std::unique_ptr<Expression>* candidate) {
990 fCandidateList->fCandidates.push_back(
991 InlineCandidate{fSymbolTableStack.back(),
992 find_parent_statement(fEnclosingStmtStack),
993 fEnclosingStmtStack.back(),
994 candidate,
John Stiles9b9415e2020-11-23 14:48:06 -0500995 fEnclosingFunction});
John Stiles70957c82020-10-02 16:42:10 -0400996 }
John Stiles2d7973a2020-10-02 15:01:03 -0400997};
John Stiles93442622020-09-11 12:11:27 -0400998
John Stiles9b9415e2020-11-23 14:48:06 -0500999static const FunctionDeclaration& candidate_func(const InlineCandidate& candidate) {
1000 return (*candidate.fCandidateExpr)->as<FunctionCall>().function();
1001}
John Stiles915a38c2020-09-14 09:38:13 -04001002
John Stiles9b9415e2020-11-23 14:48:06 -05001003bool Inliner::candidateCanBeInlined(const InlineCandidate& candidate, InlinabilityCache* cache) {
1004 const FunctionDeclaration& funcDecl = candidate_func(candidate);
John Stiles1c03d332020-10-13 10:30:23 -04001005 auto [iter, wasInserted] = cache->insert({&funcDecl, false});
John Stiles2d7973a2020-10-02 15:01:03 -04001006 if (wasInserted) {
1007 // Recursion is forbidden here to avoid an infinite death spiral of inlining.
John Stiles132cfdd2021-03-15 22:08:38 +00001008 iter->second = this->isSafeToInline(funcDecl.definition()) &&
1009 !contains_recursive_call(funcDecl);
John Stiles93442622020-09-11 12:11:27 -04001010 }
1011
John Stiles2d7973a2020-10-02 15:01:03 -04001012 return iter->second;
1013}
1014
John Stiles9b9415e2020-11-23 14:48:06 -05001015int Inliner::getFunctionSize(const FunctionDeclaration& funcDecl, FunctionSizeCache* cache) {
1016 auto [iter, wasInserted] = cache->insert({&funcDecl, 0});
John Stiles2d7973a2020-10-02 15:01:03 -04001017 if (wasInserted) {
John Stiles9b9415e2020-11-23 14:48:06 -05001018 iter->second = Analysis::NodeCountUpToLimit(*funcDecl.definition(),
John Stilesd1204642021-02-17 16:30:02 -05001019 this->settings().fInlineThreshold);
John Stiles2d7973a2020-10-02 15:01:03 -04001020 }
John Stiles2d7973a2020-10-02 15:01:03 -04001021 return iter->second;
1022}
1023
Brian Osman0006ad02020-11-18 15:38:39 -05001024void Inliner::buildCandidateList(const std::vector<std::unique_ptr<ProgramElement>>& elements,
John Stiles78047582020-12-16 16:17:41 -05001025 std::shared_ptr<SymbolTable> symbols, ProgramUsage* usage,
Brian Osman0006ad02020-11-18 15:38:39 -05001026 InlineCandidateList* candidateList) {
John Stiles2d7973a2020-10-02 15:01:03 -04001027 // This is structured much like a ProgramVisitor, but does not actually use ProgramVisitor.
1028 // The analyzer needs to keep track of the `unique_ptr<T>*` of statements and expressions so
1029 // that they can later be replaced, and ProgramVisitor does not provide this; it only provides a
1030 // `const T&`.
1031 InlineCandidateAnalyzer analyzer;
Brian Osman0006ad02020-11-18 15:38:39 -05001032 analyzer.visit(elements, symbols, candidateList);
John Stiles2d7973a2020-10-02 15:01:03 -04001033
John Stiles0ad233f2020-11-25 11:02:05 -05001034 // Early out if there are no inlining candidates.
John Stiles2d7973a2020-10-02 15:01:03 -04001035 std::vector<InlineCandidate>& candidates = candidateList->fCandidates;
John Stiles0ad233f2020-11-25 11:02:05 -05001036 if (candidates.empty()) {
1037 return;
1038 }
1039
1040 // Remove candidates that are not safe to inline.
John Stiles2d7973a2020-10-02 15:01:03 -04001041 InlinabilityCache cache;
1042 candidates.erase(std::remove_if(candidates.begin(),
1043 candidates.end(),
1044 [&](const InlineCandidate& candidate) {
1045 return !this->candidateCanBeInlined(candidate, &cache);
1046 }),
1047 candidates.end());
1048
John Stiles0ad233f2020-11-25 11:02:05 -05001049 // If the inline threshold is unlimited, or if we have no candidates left, our candidate list is
1050 // complete.
John Stilesd1204642021-02-17 16:30:02 -05001051 if (this->settings().fInlineThreshold == INT_MAX || candidates.empty()) {
John Stiles0ad233f2020-11-25 11:02:05 -05001052 return;
John Stiles2d7973a2020-10-02 15:01:03 -04001053 }
John Stiles0ad233f2020-11-25 11:02:05 -05001054
1055 // Remove candidates on a per-function basis if the effect of inlining would be to make more
1056 // than `inlineThreshold` nodes. (i.e. if Func() would be inlined six times and its size is
1057 // 10 nodes, it should be inlined if the inlineThreshold is 60 or higher.)
1058 FunctionSizeCache functionSizeCache;
1059 FunctionSizeCache candidateTotalCost;
1060 for (InlineCandidate& candidate : candidates) {
1061 const FunctionDeclaration& fnDecl = candidate_func(candidate);
1062 candidateTotalCost[&fnDecl] += this->getFunctionSize(fnDecl, &functionSizeCache);
1063 }
1064
John Stilesd1204642021-02-17 16:30:02 -05001065 candidates.erase(std::remove_if(candidates.begin(), candidates.end(),
1066 [&](const InlineCandidate& candidate) {
1067 const FunctionDeclaration& fnDecl = candidate_func(candidate);
1068 if (fnDecl.modifiers().fFlags & Modifiers::kInline_Flag) {
1069 // Functions marked `inline` ignore size limitations.
1070 return false;
1071 }
1072 if (usage->get(fnDecl) == 1) {
1073 // If a function is only used once, it's cost-free to inline.
1074 return false;
1075 }
1076 if (candidateTotalCost[&fnDecl] <= this->settings().fInlineThreshold) {
1077 // We won't exceed the inline threshold by inlining this.
1078 return false;
1079 }
1080 // Inlining this function will add too many IRNodes.
1081 return true;
1082 }),
1083 candidates.end());
John Stiles2d7973a2020-10-02 15:01:03 -04001084}
1085
Brian Osman0006ad02020-11-18 15:38:39 -05001086bool Inliner::analyze(const std::vector<std::unique_ptr<ProgramElement>>& elements,
John Stiles78047582020-12-16 16:17:41 -05001087 std::shared_ptr<SymbolTable> symbols,
Brian Osman0006ad02020-11-18 15:38:39 -05001088 ProgramUsage* usage) {
John Stilesd34d56e2020-10-12 12:04:47 -04001089 // A threshold of zero indicates that the inliner is completely disabled, so we can just return.
John Stilesd1204642021-02-17 16:30:02 -05001090 if (this->settings().fInlineThreshold <= 0) {
John Stilesd34d56e2020-10-12 12:04:47 -04001091 return false;
1092 }
1093
John Stiles031a7672020-11-13 16:13:18 -05001094 // Enforce a limit on inlining to avoid pathological cases. (inliner/ExponentialGrowth.sksl)
1095 if (fInlinedStatementCounter >= kInlinedStatementLimit) {
1096 return false;
1097 }
1098
John Stiles2d7973a2020-10-02 15:01:03 -04001099 InlineCandidateList candidateList;
John Stiles9b9415e2020-11-23 14:48:06 -05001100 this->buildCandidateList(elements, symbols, usage, &candidateList);
John Stiles2d7973a2020-10-02 15:01:03 -04001101
John Stiles915a38c2020-09-14 09:38:13 -04001102 // Inline the candidates where we've determined that it's safe to do so.
1103 std::unordered_set<const std::unique_ptr<Statement>*> enclosingStmtSet;
1104 bool madeChanges = false;
John Stiles2d7973a2020-10-02 15:01:03 -04001105 for (const InlineCandidate& candidate : candidateList.fCandidates) {
John Stiles915a38c2020-09-14 09:38:13 -04001106 FunctionCall& funcCall = (*candidate.fCandidateExpr)->as<FunctionCall>();
John Stiles915a38c2020-09-14 09:38:13 -04001107
1108 // Inlining two expressions using the same enclosing statement in the same inlining pass
1109 // does not work properly. If this happens, skip it; we'll get it in the next pass.
1110 auto [unusedIter, inserted] = enclosingStmtSet.insert(candidate.fEnclosingStmt);
1111 if (!inserted) {
1112 continue;
1113 }
1114
1115 // Convert the function call to its inlined equivalent.
Brian Osman3887a012020-09-30 13:22:27 -04001116 InlinedCall inlinedCall = this->inlineCall(&funcCall, candidate.fSymbols,
Ethan Nicholas0a5d0962020-10-14 13:33:18 -04001117 &candidate.fEnclosingFunction->declaration());
John Stiles915a38c2020-09-14 09:38:13 -04001118
John Stiles0c2d14a2021-03-01 10:08:08 -05001119 // Stop if an error was detected during the inlining process.
1120 if (!inlinedCall.fInlinedBody && !inlinedCall.fReplacementExpr) {
1121 break;
John Stiles915a38c2020-09-14 09:38:13 -04001122 }
1123
John Stiles0c2d14a2021-03-01 10:08:08 -05001124 // Ensure that the inlined body has a scope if it needs one.
1125 this->ensureScopedBlocks(inlinedCall.fInlinedBody.get(), candidate.fParentStmt->get());
1126
1127 // Add references within the inlined body
1128 usage->add(inlinedCall.fInlinedBody.get());
1129
1130 // Move the enclosing statement to the end of the unscoped Block containing the inlined
1131 // function, then replace the enclosing statement with that Block.
1132 // Before:
1133 // fInlinedBody = Block{ stmt1, stmt2, stmt3 }
1134 // fEnclosingStmt = stmt4
1135 // After:
1136 // fInlinedBody = null
1137 // fEnclosingStmt = Block{ stmt1, stmt2, stmt3, stmt4 }
1138 inlinedCall.fInlinedBody->children().push_back(std::move(*candidate.fEnclosingStmt));
1139 *candidate.fEnclosingStmt = std::move(inlinedCall.fInlinedBody);
1140
John Stiles915a38c2020-09-14 09:38:13 -04001141 // Replace the candidate function call with our replacement expression.
Brian Osman010ce6a2020-10-19 16:34:10 -04001142 usage->replace(candidate.fCandidateExpr->get(), inlinedCall.fReplacementExpr.get());
John Stiles915a38c2020-09-14 09:38:13 -04001143 *candidate.fCandidateExpr = std::move(inlinedCall.fReplacementExpr);
1144 madeChanges = true;
1145
John Stiles031a7672020-11-13 16:13:18 -05001146 // Stop inlining if we've reached our hard cap on new statements.
1147 if (fInlinedStatementCounter >= kInlinedStatementLimit) {
1148 break;
1149 }
1150
John Stiles915a38c2020-09-14 09:38:13 -04001151 // Note that nothing was destroyed except for the FunctionCall. All other nodes should
1152 // remain valid.
1153 }
1154
1155 return madeChanges;
John Stiles93442622020-09-11 12:11:27 -04001156}
1157
John Stiles44e96be2020-08-31 13:16:04 -04001158} // namespace SkSL