blob: 2d61939885cabb55cb2e9a654e0472aeb1587e16 [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"
John Stiles7384b372021-04-01 13:48:15 -040020#include "src/sksl/ir/SkSLConstructorArray.h"
John Stilese1182782021-03-30 22:09:37 -040021#include "src/sksl/ir/SkSLConstructorDiagonalMatrix.h"
John Stiles2938eea2021-04-01 18:58:25 -040022#include "src/sksl/ir/SkSLConstructorSplat.h"
John Stiles44e96be2020-08-31 13:16:04 -040023#include "src/sksl/ir/SkSLContinueStatement.h"
24#include "src/sksl/ir/SkSLDiscardStatement.h"
25#include "src/sksl/ir/SkSLDoStatement.h"
26#include "src/sksl/ir/SkSLEnum.h"
27#include "src/sksl/ir/SkSLExpressionStatement.h"
28#include "src/sksl/ir/SkSLExternalFunctionCall.h"
Brian Osmanbe0b3b72021-01-06 14:27:35 -050029#include "src/sksl/ir/SkSLExternalFunctionReference.h"
John Stiles44e96be2020-08-31 13:16:04 -040030#include "src/sksl/ir/SkSLField.h"
31#include "src/sksl/ir/SkSLFieldAccess.h"
32#include "src/sksl/ir/SkSLFloatLiteral.h"
33#include "src/sksl/ir/SkSLForStatement.h"
34#include "src/sksl/ir/SkSLFunctionCall.h"
35#include "src/sksl/ir/SkSLFunctionDeclaration.h"
36#include "src/sksl/ir/SkSLFunctionDefinition.h"
37#include "src/sksl/ir/SkSLFunctionReference.h"
38#include "src/sksl/ir/SkSLIfStatement.h"
39#include "src/sksl/ir/SkSLIndexExpression.h"
John Stiles98c1f822020-09-09 14:18:53 -040040#include "src/sksl/ir/SkSLInlineMarker.h"
John Stiles44e96be2020-08-31 13:16:04 -040041#include "src/sksl/ir/SkSLIntLiteral.h"
42#include "src/sksl/ir/SkSLInterfaceBlock.h"
John Stiles44e96be2020-08-31 13:16:04 -040043#include "src/sksl/ir/SkSLNop.h"
John Stiles44e96be2020-08-31 13:16:04 -040044#include "src/sksl/ir/SkSLPostfixExpression.h"
45#include "src/sksl/ir/SkSLPrefixExpression.h"
46#include "src/sksl/ir/SkSLReturnStatement.h"
47#include "src/sksl/ir/SkSLSetting.h"
48#include "src/sksl/ir/SkSLSwitchCase.h"
49#include "src/sksl/ir/SkSLSwitchStatement.h"
50#include "src/sksl/ir/SkSLSwizzle.h"
51#include "src/sksl/ir/SkSLTernaryExpression.h"
52#include "src/sksl/ir/SkSLUnresolvedFunction.h"
53#include "src/sksl/ir/SkSLVarDeclarations.h"
John Stiles44e96be2020-08-31 13:16:04 -040054#include "src/sksl/ir/SkSLVariable.h"
55#include "src/sksl/ir/SkSLVariableReference.h"
John Stiles44e96be2020-08-31 13:16:04 -040056
57namespace SkSL {
58namespace {
59
John Stiles031a7672020-11-13 16:13:18 -050060static constexpr int kInlinedStatementLimit = 2500;
61
John Stiles44e96be2020-08-31 13:16:04 -040062static int count_returns_at_end_of_control_flow(const FunctionDefinition& funcDef) {
63 class CountReturnsAtEndOfControlFlow : public ProgramVisitor {
64 public:
65 CountReturnsAtEndOfControlFlow(const FunctionDefinition& funcDef) {
66 this->visitProgramElement(funcDef);
67 }
68
John Stiles5b408a32021-03-17 09:53:32 -040069 bool visitExpression(const Expression& expr) override {
70 // Do not recurse into expressions.
71 return false;
72 }
73
John Stiles44e96be2020-08-31 13:16:04 -040074 bool visitStatement(const Statement& stmt) override {
Ethan Nicholase6592142020-09-08 10:22:09 -040075 switch (stmt.kind()) {
76 case Statement::Kind::kBlock: {
John Stiles44e96be2020-08-31 13:16:04 -040077 // Check only the last statement of a block.
Ethan Nicholas7bd60432020-09-25 14:31:59 -040078 const auto& block = stmt.as<Block>();
79 return block.children().size() &&
80 this->visitStatement(*block.children().back());
John Stiles44e96be2020-08-31 13:16:04 -040081 }
Ethan Nicholase6592142020-09-08 10:22:09 -040082 case Statement::Kind::kSwitch:
Ethan Nicholase6592142020-09-08 10:22:09 -040083 case Statement::Kind::kDo:
84 case Statement::Kind::kFor:
John Stiles44e96be2020-08-31 13:16:04 -040085 // Don't introspect switches or loop structures at all.
86 return false;
87
Ethan Nicholase6592142020-09-08 10:22:09 -040088 case Statement::Kind::kReturn:
John Stiles44e96be2020-08-31 13:16:04 -040089 ++fNumReturns;
90 [[fallthrough]];
91
92 default:
John Stiles93442622020-09-11 12:11:27 -040093 return INHERITED::visitStatement(stmt);
John Stiles44e96be2020-08-31 13:16:04 -040094 }
95 }
96
97 int fNumReturns = 0;
98 using INHERITED = ProgramVisitor;
99 };
100
101 return CountReturnsAtEndOfControlFlow{funcDef}.fNumReturns;
102}
103
John Stiles991b09d2020-09-10 13:33:40 -0400104static bool contains_recursive_call(const FunctionDeclaration& funcDecl) {
105 class ContainsRecursiveCall : public ProgramVisitor {
106 public:
107 bool visit(const FunctionDeclaration& funcDecl) {
108 fFuncDecl = &funcDecl;
Ethan Nicholased84b732020-10-08 11:45:44 -0400109 return funcDecl.definition() ? this->visitProgramElement(*funcDecl.definition())
110 : false;
John Stiles991b09d2020-09-10 13:33:40 -0400111 }
112
113 bool visitExpression(const Expression& expr) override {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400114 if (expr.is<FunctionCall>() && expr.as<FunctionCall>().function().matches(*fFuncDecl)) {
John Stiles991b09d2020-09-10 13:33:40 -0400115 return true;
116 }
117 return INHERITED::visitExpression(expr);
118 }
119
120 bool visitStatement(const Statement& stmt) override {
Ethan Nicholasceb62142020-10-09 16:51:18 -0400121 if (stmt.is<InlineMarker>() &&
122 stmt.as<InlineMarker>().function().matches(*fFuncDecl)) {
John Stiles991b09d2020-09-10 13:33:40 -0400123 return true;
124 }
125 return INHERITED::visitStatement(stmt);
126 }
127
128 const FunctionDeclaration* fFuncDecl;
129 using INHERITED = ProgramVisitor;
130 };
131
132 return ContainsRecursiveCall{}.visit(funcDecl);
133}
134
John Stiles6d696082020-10-01 10:18:54 -0400135static std::unique_ptr<Statement>* find_parent_statement(
136 const std::vector<std::unique_ptr<Statement>*>& stmtStack) {
John Stiles915a38c2020-09-14 09:38:13 -0400137 SkASSERT(!stmtStack.empty());
138
139 // Walk the statement stack from back to front, ignoring the last element (which is the
140 // enclosing statement).
141 auto iter = stmtStack.rbegin();
142 ++iter;
143
144 // Anything counts as a parent statement other than a scopeless Block.
145 for (; iter != stmtStack.rend(); ++iter) {
John Stiles6d696082020-10-01 10:18:54 -0400146 std::unique_ptr<Statement>* stmt = *iter;
147 if (!(*stmt)->is<Block>() || (*stmt)->as<Block>().isScope()) {
John Stiles915a38c2020-09-14 09:38:13 -0400148 return stmt;
149 }
150 }
151
152 // There wasn't any parent statement to be found.
153 return nullptr;
154}
155
John Stilese41b4ee2020-09-28 12:28:16 -0400156std::unique_ptr<Expression> clone_with_ref_kind(const Expression& expr,
157 VariableReference::RefKind refKind) {
158 std::unique_ptr<Expression> clone = expr.clone();
John Stiles47c0a742021-02-09 09:30:35 -0500159 Analysis::UpdateRefKind(clone.get(), refKind);
John Stilese41b4ee2020-09-28 12:28:16 -0400160 return clone;
161}
162
John Stiles77702f12020-12-17 14:38:56 -0500163class CountReturnsWithLimit : public ProgramVisitor {
164public:
165 CountReturnsWithLimit(const FunctionDefinition& funcDef, int limit) : fLimit(limit) {
166 this->visitProgramElement(funcDef);
167 }
168
John Stiles5b408a32021-03-17 09:53:32 -0400169 bool visitExpression(const Expression& expr) override {
170 // Do not recurse into expressions.
171 return false;
172 }
173
John Stiles77702f12020-12-17 14:38:56 -0500174 bool visitStatement(const Statement& stmt) override {
175 switch (stmt.kind()) {
176 case Statement::Kind::kReturn: {
177 ++fNumReturns;
178 fDeepestReturn = std::max(fDeepestReturn, fScopedBlockDepth);
179 return (fNumReturns >= fLimit) || INHERITED::visitStatement(stmt);
180 }
John Stilesc5ff4862020-12-22 13:47:05 -0500181 case Statement::Kind::kVarDeclaration: {
182 if (fScopedBlockDepth > 1) {
183 fVariablesInBlocks = true;
184 }
185 return INHERITED::visitStatement(stmt);
186 }
John Stiles77702f12020-12-17 14:38:56 -0500187 case Statement::Kind::kBlock: {
188 int depthIncrement = stmt.as<Block>().isScope() ? 1 : 0;
189 fScopedBlockDepth += depthIncrement;
190 bool result = INHERITED::visitStatement(stmt);
191 fScopedBlockDepth -= depthIncrement;
John Stilesc5ff4862020-12-22 13:47:05 -0500192 if (fNumReturns == 0 && fScopedBlockDepth <= 1) {
193 // If closing this block puts us back at the top level, and we haven't
194 // encountered any return statements yet, any vardecls we may have encountered
195 // up until this point can be ignored. They are out of scope now, and they were
196 // never used in a return statement.
197 fVariablesInBlocks = false;
198 }
John Stiles77702f12020-12-17 14:38:56 -0500199 return result;
200 }
201 default:
202 return INHERITED::visitStatement(stmt);
203 }
204 }
205
206 int fNumReturns = 0;
207 int fDeepestReturn = 0;
208 int fLimit = 0;
209 int fScopedBlockDepth = 0;
John Stilesc5ff4862020-12-22 13:47:05 -0500210 bool fVariablesInBlocks = false;
John Stiles77702f12020-12-17 14:38:56 -0500211 using INHERITED = ProgramVisitor;
212};
213
John Stiles44e96be2020-08-31 13:16:04 -0400214} // namespace
215
John Stiles77702f12020-12-17 14:38:56 -0500216Inliner::ReturnComplexity Inliner::GetReturnComplexity(const FunctionDefinition& funcDef) {
217 int returnsAtEndOfControlFlow = count_returns_at_end_of_control_flow(funcDef);
218 CountReturnsWithLimit counter{funcDef, returnsAtEndOfControlFlow + 1};
John Stiles77702f12020-12-17 14:38:56 -0500219 if (counter.fNumReturns > returnsAtEndOfControlFlow) {
220 return ReturnComplexity::kEarlyReturns;
221 }
John Stilesc5ff4862020-12-22 13:47:05 -0500222 if (counter.fNumReturns > 1) {
John Stiles77702f12020-12-17 14:38:56 -0500223 return ReturnComplexity::kScopedReturns;
224 }
John Stilesc5ff4862020-12-22 13:47:05 -0500225 if (counter.fVariablesInBlocks && counter.fDeepestReturn > 1) {
226 return ReturnComplexity::kScopedReturns;
227 }
John Stiles8937cd42021-03-17 19:32:59 +0000228 return ReturnComplexity::kSingleSafeReturn;
John Stiles77702f12020-12-17 14:38:56 -0500229}
230
John Stilesb61ee902020-09-21 12:26:59 -0400231void Inliner::ensureScopedBlocks(Statement* inlinedBody, Statement* parentStmt) {
232 // No changes necessary if this statement isn't actually a block.
233 if (!inlinedBody || !inlinedBody->is<Block>()) {
234 return;
235 }
236
237 // No changes necessary if the parent statement doesn't require a scope.
238 if (!parentStmt || !(parentStmt->is<IfStatement>() || parentStmt->is<ForStatement>() ||
Brian Osmand6f23382020-12-15 17:08:59 -0500239 parentStmt->is<DoStatement>())) {
John Stilesb61ee902020-09-21 12:26:59 -0400240 return;
241 }
242
243 Block& block = inlinedBody->as<Block>();
244
245 // The inliner will create inlined function bodies as a Block containing multiple statements,
246 // but no scope. Normally, this is fine, but if this block is used as the statement for a
247 // do/for/if/while, this isn't actually possible to represent textually; a scope must be added
248 // for the generated code to match the intent. In the case of Blocks nested inside other Blocks,
249 // we add the scope to the outermost block if needed. Zero-statement blocks have similar
250 // issues--if we don't represent the Block textually somehow, we run the risk of accidentally
251 // absorbing the following statement into our loop--so we also add a scope to these.
252 for (Block* nestedBlock = &block;; ) {
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400253 if (nestedBlock->isScope()) {
John Stilesb61ee902020-09-21 12:26:59 -0400254 // We found an explicit scope; all is well.
255 return;
256 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400257 if (nestedBlock->children().size() != 1) {
John Stilesb61ee902020-09-21 12:26:59 -0400258 // We found a block with multiple (or zero) statements, but no scope? Let's add a scope
259 // to the outermost block.
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400260 block.setIsScope(true);
John Stilesb61ee902020-09-21 12:26:59 -0400261 return;
262 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400263 if (!nestedBlock->children()[0]->is<Block>()) {
John Stilesb61ee902020-09-21 12:26:59 -0400264 // This block has exactly one thing inside, and it's not another block. No need to scope
265 // it.
266 return;
267 }
268 // We have to go deeper.
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400269 nestedBlock = &nestedBlock->children()[0]->as<Block>();
John Stilesb61ee902020-09-21 12:26:59 -0400270 }
271}
272
John Stilesd1204642021-02-17 16:30:02 -0500273void Inliner::reset(ModifiersPool* modifiers) {
Ethan Nicholas041fd0a2020-10-07 16:42:04 -0400274 fModifiers = modifiers;
Ethan Nicholas6f4eee22021-01-11 12:37:42 -0500275 fMangler.reset();
John Stiles031a7672020-11-13 16:13:18 -0500276 fInlinedStatementCounter = 0;
John Stiles44e96be2020-08-31 13:16:04 -0400277}
278
279std::unique_ptr<Expression> Inliner::inlineExpression(int offset,
280 VariableRewriteMap* varMap,
John Stilesd7cc0932020-11-30 12:24:27 -0500281 SymbolTable* symbolTableForExpression,
John Stiles44e96be2020-08-31 13:16:04 -0400282 const Expression& expression) {
283 auto expr = [&](const std::unique_ptr<Expression>& e) -> std::unique_ptr<Expression> {
284 if (e) {
John Stilesd7cc0932020-11-30 12:24:27 -0500285 return this->inlineExpression(offset, varMap, symbolTableForExpression, *e);
John Stiles44e96be2020-08-31 13:16:04 -0400286 }
287 return nullptr;
288 };
John Stiles8e3b6be2020-10-13 11:14:08 -0400289 auto argList = [&](const ExpressionArray& originalArgs) -> ExpressionArray {
290 ExpressionArray args;
John Stilesf4bda742020-10-14 16:57:41 -0400291 args.reserve_back(originalArgs.size());
John Stiles44e96be2020-08-31 13:16:04 -0400292 for (const std::unique_ptr<Expression>& arg : originalArgs) {
293 args.push_back(expr(arg));
294 }
295 return args;
296 };
297
Ethan Nicholase6592142020-09-08 10:22:09 -0400298 switch (expression.kind()) {
299 case Expression::Kind::kBinary: {
John Stiles6a1a98c2021-01-14 18:35:34 -0500300 const BinaryExpression& binaryExpr = expression.as<BinaryExpression>();
John Stilese2aec432021-03-01 09:27:48 -0500301 return BinaryExpression::Make(*fContext,
302 expr(binaryExpr.left()),
303 binaryExpr.getOperator(),
304 expr(binaryExpr.right()));
John Stiles44e96be2020-08-31 13:16:04 -0400305 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400306 case Expression::Kind::kBoolLiteral:
307 case Expression::Kind::kIntLiteral:
308 case Expression::Kind::kFloatLiteral:
John Stiles44e96be2020-08-31 13:16:04 -0400309 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400310 case Expression::Kind::kConstructor: {
John Stiles44e96be2020-08-31 13:16:04 -0400311 const Constructor& constructor = expression.as<Constructor>();
John Stiles23521a82021-03-02 17:02:51 -0500312 auto inlinedCtor = Constructor::Convert(
313 *fContext, offset, *constructor.type().clone(symbolTableForExpression),
314 argList(constructor.arguments()));
315 SkASSERT(inlinedCtor);
316 return inlinedCtor;
John Stiles44e96be2020-08-31 13:16:04 -0400317 }
John Stiles7384b372021-04-01 13:48:15 -0400318 case Expression::Kind::kConstructorArray: {
319 const ConstructorArray& ctor = expression.as<ConstructorArray>();
320 return ConstructorArray::Make(*fContext, offset,
321 *ctor.type().clone(symbolTableForExpression),
322 argList(ctor.arguments()));
323 }
John Stilese1182782021-03-30 22:09:37 -0400324 case Expression::Kind::kConstructorDiagonalMatrix: {
325 const ConstructorDiagonalMatrix& ctor = expression.as<ConstructorDiagonalMatrix>();
326 return ConstructorDiagonalMatrix::Make(*fContext, offset,
327 *ctor.type().clone(symbolTableForExpression),
328 expr(ctor.argument()));
329 }
John Stiles2938eea2021-04-01 18:58:25 -0400330 case Expression::Kind::kConstructorSplat: {
331 const ConstructorSplat& ctor = expression.as<ConstructorSplat>();
332 return ConstructorSplat::Make(*fContext, offset,
333 *ctor.type().clone(symbolTableForExpression),
334 expr(ctor.argument()));
335 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400336 case Expression::Kind::kExternalFunctionCall: {
John Stiles44e96be2020-08-31 13:16:04 -0400337 const ExternalFunctionCall& externalCall = expression.as<ExternalFunctionCall>();
Ethan Nicholas444ccc62020-10-09 10:16:22 -0400338 return std::make_unique<ExternalFunctionCall>(offset, &externalCall.function(),
Ethan Nicholas6e86ec92020-09-30 14:29:56 -0400339 argList(externalCall.arguments()));
John Stiles44e96be2020-08-31 13:16:04 -0400340 }
Brian Osmanbe0b3b72021-01-06 14:27:35 -0500341 case Expression::Kind::kExternalFunctionReference:
John Stiles44e96be2020-08-31 13:16:04 -0400342 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400343 case Expression::Kind::kFieldAccess: {
John Stiles44e96be2020-08-31 13:16:04 -0400344 const FieldAccess& f = expression.as<FieldAccess>();
John Stiles06d600f2021-03-08 09:18:21 -0500345 return FieldAccess::Make(*fContext, expr(f.base()), f.fieldIndex(), f.ownerKind());
John Stiles44e96be2020-08-31 13:16:04 -0400346 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400347 case Expression::Kind::kFunctionCall: {
John Stiles44e96be2020-08-31 13:16:04 -0400348 const FunctionCall& funcCall = expression.as<FunctionCall>();
John Stilescd7ba502021-03-19 10:54:59 -0400349 return FunctionCall::Make(*fContext,
350 offset,
351 funcCall.type().clone(symbolTableForExpression),
352 funcCall.function(),
353 argList(funcCall.arguments()));
John Stiles44e96be2020-08-31 13:16:04 -0400354 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400355 case Expression::Kind::kFunctionReference:
Brian Osman2b3b35f2020-09-08 09:17:36 -0400356 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400357 case Expression::Kind::kIndex: {
John Stiles44e96be2020-08-31 13:16:04 -0400358 const IndexExpression& idx = expression.as<IndexExpression>();
John Stiles51d33982021-03-08 09:18:07 -0500359 return IndexExpression::Make(*fContext, expr(idx.base()), expr(idx.index()));
John Stiles44e96be2020-08-31 13:16:04 -0400360 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400361 case Expression::Kind::kPrefix: {
John Stiles44e96be2020-08-31 13:16:04 -0400362 const PrefixExpression& p = expression.as<PrefixExpression>();
John Stilesb0eb20f2021-02-26 15:29:33 -0500363 return PrefixExpression::Make(*fContext, p.getOperator(), expr(p.operand()));
John Stiles44e96be2020-08-31 13:16:04 -0400364 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400365 case Expression::Kind::kPostfix: {
John Stiles44e96be2020-08-31 13:16:04 -0400366 const PostfixExpression& p = expression.as<PostfixExpression>();
John Stiles52d3b012021-02-26 15:56:48 -0500367 return PostfixExpression::Make(*fContext, expr(p.operand()), p.getOperator());
John Stiles44e96be2020-08-31 13:16:04 -0400368 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400369 case Expression::Kind::kSetting:
John Stiles44e96be2020-08-31 13:16:04 -0400370 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400371 case Expression::Kind::kSwizzle: {
John Stiles44e96be2020-08-31 13:16:04 -0400372 const Swizzle& s = expression.as<Swizzle>();
John Stiles6e88e042021-02-19 14:09:38 -0500373 return Swizzle::Make(*fContext, expr(s.base()), s.components());
John Stiles44e96be2020-08-31 13:16:04 -0400374 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400375 case Expression::Kind::kTernary: {
John Stiles44e96be2020-08-31 13:16:04 -0400376 const TernaryExpression& t = expression.as<TernaryExpression>();
John Stiles90518f72021-02-26 20:44:54 -0500377 return TernaryExpression::Make(*fContext, expr(t.test()),
378 expr(t.ifTrue()), expr(t.ifFalse()));
John Stiles44e96be2020-08-31 13:16:04 -0400379 }
Brian Osman83ba9302020-09-11 13:33:46 -0400380 case Expression::Kind::kTypeReference:
381 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400382 case Expression::Kind::kVariableReference: {
John Stiles44e96be2020-08-31 13:16:04 -0400383 const VariableReference& v = expression.as<VariableReference>();
Ethan Nicholas78686922020-10-08 06:46:27 -0400384 auto varMapIter = varMap->find(v.variable());
John Stilese41b4ee2020-09-28 12:28:16 -0400385 if (varMapIter != varMap->end()) {
Ethan Nicholas78686922020-10-08 06:46:27 -0400386 return clone_with_ref_kind(*varMapIter->second, v.refKind());
John Stiles44e96be2020-08-31 13:16:04 -0400387 }
388 return v.clone();
389 }
390 default:
391 SkASSERT(false);
392 return nullptr;
393 }
394}
395
396std::unique_ptr<Statement> Inliner::inlineStatement(int offset,
397 VariableRewriteMap* varMap,
398 SymbolTable* symbolTableForStatement,
John Stiles77702f12020-12-17 14:38:56 -0500399 std::unique_ptr<Expression>* resultExpr,
400 ReturnComplexity returnComplexity,
Brian Osman3887a012020-09-30 13:22:27 -0400401 const Statement& statement,
402 bool isBuiltinCode) {
John Stiles44e96be2020-08-31 13:16:04 -0400403 auto stmt = [&](const std::unique_ptr<Statement>& s) -> std::unique_ptr<Statement> {
404 if (s) {
John Stilesa5f3c312020-09-22 12:05:16 -0400405 return this->inlineStatement(offset, varMap, symbolTableForStatement, resultExpr,
John Stiles77702f12020-12-17 14:38:56 -0500406 returnComplexity, *s, isBuiltinCode);
John Stiles44e96be2020-08-31 13:16:04 -0400407 }
408 return nullptr;
409 };
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400410 auto blockStmts = [&](const Block& block) {
John Stiles8f2a0cf2020-10-13 12:48:21 -0400411 StatementArray result;
John Stilesf4bda742020-10-14 16:57:41 -0400412 result.reserve_back(block.children().size());
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400413 for (const std::unique_ptr<Statement>& child : block.children()) {
414 result.push_back(stmt(child));
415 }
416 return result;
417 };
John Stiles44e96be2020-08-31 13:16:04 -0400418 auto expr = [&](const std::unique_ptr<Expression>& e) -> std::unique_ptr<Expression> {
419 if (e) {
John Stilesd7cc0932020-11-30 12:24:27 -0500420 return this->inlineExpression(offset, varMap, symbolTableForStatement, *e);
John Stiles44e96be2020-08-31 13:16:04 -0400421 }
422 return nullptr;
423 };
John Stiles031a7672020-11-13 16:13:18 -0500424
425 ++fInlinedStatementCounter;
426
Ethan Nicholase6592142020-09-08 10:22:09 -0400427 switch (statement.kind()) {
428 case Statement::Kind::kBlock: {
John Stiles44e96be2020-08-31 13:16:04 -0400429 const Block& b = statement.as<Block>();
John Stilesbf16b6c2021-03-12 19:24:31 -0500430 return Block::Make(offset, blockStmts(b),
431 SymbolTable::WrapIfBuiltin(b.symbolTable()),
432 b.isScope());
John Stiles44e96be2020-08-31 13:16:04 -0400433 }
434
Ethan Nicholase6592142020-09-08 10:22:09 -0400435 case Statement::Kind::kBreak:
436 case Statement::Kind::kContinue:
437 case Statement::Kind::kDiscard:
John Stiles44e96be2020-08-31 13:16:04 -0400438 return statement.clone();
439
Ethan Nicholase6592142020-09-08 10:22:09 -0400440 case Statement::Kind::kDo: {
John Stiles44e96be2020-08-31 13:16:04 -0400441 const DoStatement& d = statement.as<DoStatement>();
John Stilesea5822e2021-02-26 11:18:20 -0500442 return DoStatement::Make(*fContext, stmt(d.statement()), expr(d.test()));
John Stiles44e96be2020-08-31 13:16:04 -0400443 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400444 case Statement::Kind::kExpression: {
John Stiles44e96be2020-08-31 13:16:04 -0400445 const ExpressionStatement& e = statement.as<ExpressionStatement>();
John Stiles3e5871c2021-02-25 20:52:03 -0500446 return ExpressionStatement::Make(*fContext, expr(e.expression()));
John Stiles44e96be2020-08-31 13:16:04 -0400447 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400448 case Statement::Kind::kFor: {
John Stiles44e96be2020-08-31 13:16:04 -0400449 const ForStatement& f = statement.as<ForStatement>();
450 // need to ensure initializer is evaluated first so that we've already remapped its
451 // declarations by the time we evaluate test & next
Ethan Nicholas0d31ed52020-10-05 14:47:09 -0400452 std::unique_ptr<Statement> initializer = stmt(f.initializer());
John Stilesb321a072021-02-25 16:24:19 -0500453 return ForStatement::Make(*fContext, offset, std::move(initializer), expr(f.test()),
454 expr(f.next()), stmt(f.statement()),
455 SymbolTable::WrapIfBuiltin(f.symbols()));
John Stiles44e96be2020-08-31 13:16:04 -0400456 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400457 case Statement::Kind::kIf: {
John Stiles44e96be2020-08-31 13:16:04 -0400458 const IfStatement& i = statement.as<IfStatement>();
John Stilescf3059e2021-02-25 14:27:02 -0500459 return IfStatement::Make(*fContext, offset, i.isStatic(), expr(i.test()),
460 stmt(i.ifTrue()), stmt(i.ifFalse()));
John Stiles44e96be2020-08-31 13:16:04 -0400461 }
John Stiles98c1f822020-09-09 14:18:53 -0400462 case Statement::Kind::kInlineMarker:
Ethan Nicholase6592142020-09-08 10:22:09 -0400463 case Statement::Kind::kNop:
John Stiles44e96be2020-08-31 13:16:04 -0400464 return statement.clone();
John Stilesea5822e2021-02-26 11:18:20 -0500465
Ethan Nicholase6592142020-09-08 10:22:09 -0400466 case Statement::Kind::kReturn: {
John Stiles44e96be2020-08-31 13:16:04 -0400467 const ReturnStatement& r = statement.as<ReturnStatement>();
John Stiles77702f12020-12-17 14:38:56 -0500468 if (!r.expression()) {
John Stilesdc208472021-03-17 10:58:16 -0400469 // This function doesn't return a value. We won't inline functions with early
470 // returns, so a return statement is a no-op and can be treated as such.
471 return Nop::Make();
John Stiles44e96be2020-08-31 13:16:04 -0400472 }
John Stiles77702f12020-12-17 14:38:56 -0500473
John Stilesc5ff4862020-12-22 13:47:05 -0500474 // If a function only contains a single return, and it doesn't reference variables from
475 // inside an Block's scope, we don't need to store the result in a variable at all. Just
476 // replace the function-call expression with the function's return expression.
John Stiles77702f12020-12-17 14:38:56 -0500477 SkASSERT(resultExpr);
John Stilesc5ff4862020-12-22 13:47:05 -0500478 if (returnComplexity <= ReturnComplexity::kSingleSafeReturn) {
John Stiles77702f12020-12-17 14:38:56 -0500479 *resultExpr = expr(r.expression());
John Stilesa0c04d62021-03-11 23:07:24 -0500480 return Nop::Make();
John Stiles77702f12020-12-17 14:38:56 -0500481 }
482
483 // For more complex functions, assign their result into a variable.
John Stiles511c5002021-02-25 11:17:02 -0500484 SkASSERT(*resultExpr);
John Stiles3e5871c2021-02-25 20:52:03 -0500485 auto assignment = ExpressionStatement::Make(
486 *fContext,
John Stilese2aec432021-03-01 09:27:48 -0500487 BinaryExpression::Make(
488 *fContext,
489 clone_with_ref_kind(**resultExpr, VariableRefKind::kWrite),
John Stiles77702f12020-12-17 14:38:56 -0500490 Token::Kind::TK_EQ,
John Stilese2aec432021-03-01 09:27:48 -0500491 expr(r.expression())));
John Stiles77702f12020-12-17 14:38:56 -0500492
John Stiles77702f12020-12-17 14:38:56 -0500493 // Functions without early returns aren't wrapped in a for loop and don't need to worry
494 // about breaking out of the control flow.
John Stiles3e5871c2021-02-25 20:52:03 -0500495 return assignment;
John Stiles44e96be2020-08-31 13:16:04 -0400496 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400497 case Statement::Kind::kSwitch: {
John Stiles44e96be2020-08-31 13:16:04 -0400498 const SwitchStatement& ss = statement.as<SwitchStatement>();
John Stilesb23a64b2021-03-11 08:27:59 -0500499 StatementArray cases;
500 cases.reserve_back(ss.cases().size());
501 for (const std::unique_ptr<Statement>& statement : ss.cases()) {
502 const SwitchCase& sc = statement->as<SwitchCase>();
503 cases.push_back(std::make_unique<SwitchCase>(offset, expr(sc.value()),
504 stmt(sc.statement())));
John Stiles44e96be2020-08-31 13:16:04 -0400505 }
John Stilese1d1b082021-02-23 13:44:36 -0500506 return SwitchStatement::Make(*fContext, offset, ss.isStatic(), expr(ss.value()),
507 std::move(cases), SymbolTable::WrapIfBuiltin(ss.symbols()));
John Stiles44e96be2020-08-31 13:16:04 -0400508 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400509 case Statement::Kind::kVarDeclaration: {
John Stiles44e96be2020-08-31 13:16:04 -0400510 const VarDeclaration& decl = statement.as<VarDeclaration>();
John Stiles35fee4c2020-12-16 18:25:14 +0000511 std::unique_ptr<Expression> initialValue = expr(decl.value());
John Stilesddcc8432021-01-15 15:32:32 -0500512 const Variable& variable = decl.var();
513
John Stiles35fee4c2020-12-16 18:25:14 +0000514 // We assign unique names to inlined variables--scopes hide most of the problems in this
515 // regard, but see `InlinerAvoidsVariableNameOverlap` for a counterexample where unique
516 // names are important.
John Stilesd51c9792021-03-18 11:40:14 -0400517 const String* name = symbolTableForStatement->takeOwnershipOfString(
518 fMangler.uniqueName(variable.name(), symbolTableForStatement));
Ethan Nicholas5b9b0db2021-01-21 13:12:01 -0500519 auto clonedVar = std::make_unique<Variable>(
520 offset,
521 &variable.modifiers(),
John Stilesd51c9792021-03-18 11:40:14 -0400522 name->c_str(),
Ethan Nicholas5b9b0db2021-01-21 13:12:01 -0500523 variable.type().clone(symbolTableForStatement),
524 isBuiltinCode,
525 variable.storage());
526 (*varMap)[&variable] = std::make_unique<VariableReference>(offset, clonedVar.get());
John Stilese67bd132021-03-19 18:39:25 -0400527 auto result = VarDeclaration::Make(*fContext,
528 clonedVar.get(),
529 decl.baseType().clone(symbolTableForStatement),
530 decl.arraySize(),
531 std::move(initialValue));
Ethan Nicholas5b9b0db2021-01-21 13:12:01 -0500532 symbolTableForStatement->takeOwnershipOfSymbol(std::move(clonedVar));
John Stilese67bd132021-03-19 18:39:25 -0400533 return result;
John Stiles44e96be2020-08-31 13:16:04 -0400534 }
John Stiles44e96be2020-08-31 13:16:04 -0400535 default:
536 SkASSERT(false);
537 return nullptr;
538 }
539}
540
John Stiles7b920442020-12-17 10:43:41 -0500541Inliner::InlineVariable Inliner::makeInlineVariable(const String& baseName,
542 const Type* type,
543 SymbolTable* symbolTable,
544 Modifiers modifiers,
545 bool isBuiltinCode,
546 std::unique_ptr<Expression>* initialValue) {
547 // $floatLiteral or $intLiteral aren't real types that we can use for scratch variables, so
548 // replace them if they ever appear here. If this happens, we likely forgot to coerce a type
549 // somewhere during compilation.
John Stiles14975272021-01-12 11:41:14 -0500550 if (type->isLiteral()) {
551 SkDEBUGFAIL("found a $literal type while inlining");
552 type = &type->scalarTypeForLiteral();
John Stiles7b920442020-12-17 10:43:41 -0500553 }
554
John Stilesbff24ab2021-03-17 13:20:10 -0400555 // Out parameters aren't supported.
556 SkASSERT(!(modifiers.fFlags & Modifiers::kOut_Flag));
557
John Stiles7b920442020-12-17 10:43:41 -0500558 // Provide our new variable with a unique name, and add it to our symbol table.
John Stilesd51c9792021-03-18 11:40:14 -0400559 const String* name =
560 symbolTable->takeOwnershipOfString(fMangler.uniqueName(baseName, symbolTable));
John Stiles7b920442020-12-17 10:43:41 -0500561
562 // Create our new variable and add it to the symbol table.
563 InlineVariable result;
Ethan Nicholas5b9b0db2021-01-21 13:12:01 -0500564 auto var = std::make_unique<Variable>(/*offset=*/-1,
565 fModifiers->addToPool(Modifiers()),
John Stilesd51c9792021-03-18 11:40:14 -0400566 name->c_str(),
Ethan Nicholas5b9b0db2021-01-21 13:12:01 -0500567 type,
568 isBuiltinCode,
569 Variable::Storage::kLocal);
John Stiles7b920442020-12-17 10:43:41 -0500570
John Stilesbff24ab2021-03-17 13:20:10 -0400571 // Create our variable declaration.
John Stilese67bd132021-03-19 18:39:25 -0400572 result.fVarDecl = VarDeclaration::Make(*fContext, var.get(), type, /*arraySize=*/0,
573 std::move(*initialValue));
Ethan Nicholas5b9b0db2021-01-21 13:12:01 -0500574 result.fVarSymbol = symbolTable->add(std::move(var));
John Stiles7b920442020-12-17 10:43:41 -0500575 return result;
576}
577
John Stiles6eadf132020-09-08 10:16:10 -0400578Inliner::InlinedCall Inliner::inlineCall(FunctionCall* call,
John Stiles78047582020-12-16 16:17:41 -0500579 std::shared_ptr<SymbolTable> symbolTable,
John Stiles30fce9c2021-03-18 09:24:06 -0400580 const ProgramUsage& usage,
Brian Osman3887a012020-09-30 13:22:27 -0400581 const FunctionDeclaration* caller) {
John Stiles44e96be2020-08-31 13:16:04 -0400582 // Inlining is more complicated here than in a typical compiler, because we have to have a
583 // high-level IR and can't just drop statements into the middle of an expression or even use
584 // gotos.
585 //
586 // Since we can't insert statements into an expression, we run the inline function as extra
587 // statements before the statement we're currently processing, relying on a lack of execution
588 // order guarantees. Since we can't use gotos (which are normally used to replace return
589 // statements), we wrap the whole function in a loop and use break statements to jump to the
590 // end.
John Stiles44e96be2020-08-31 13:16:04 -0400591 SkASSERT(fContext);
592 SkASSERT(call);
Ethan Nicholased84b732020-10-08 11:45:44 -0400593 SkASSERT(this->isSafeToInline(call->function().definition()));
John Stiles44e96be2020-08-31 13:16:04 -0400594
John Stiles8e3b6be2020-10-13 11:14:08 -0400595 ExpressionArray& arguments = call->arguments();
John Stiles6eadf132020-09-08 10:16:10 -0400596 const int offset = call->fOffset;
Ethan Nicholased84b732020-10-08 11:45:44 -0400597 const FunctionDefinition& function = *call->function().definition();
John Stiles28257db2021-03-17 15:18:09 -0400598 const Block& body = function.body()->as<Block>();
John Stiles77702f12020-12-17 14:38:56 -0500599 const ReturnComplexity returnComplexity = GetReturnComplexity(function);
John Stiles6eadf132020-09-08 10:16:10 -0400600
John Stiles28257db2021-03-17 15:18:09 -0400601 StatementArray inlineStatements;
602 int expectedStmtCount = 1 + // Inline marker
603 1 + // Result variable
604 arguments.size() + // Function argument temp-vars
605 body.children().size(); // Inlined code
John Stiles98c1f822020-09-09 14:18:53 -0400606
John Stiles28257db2021-03-17 15:18:09 -0400607 inlineStatements.reserve_back(expectedStmtCount);
608 inlineStatements.push_back(InlineMarker::Make(&call->function()));
John Stiles44e96be2020-08-31 13:16:04 -0400609
John Stilese41b4ee2020-09-28 12:28:16 -0400610 std::unique_ptr<Expression> resultExpr;
John Stiles511c5002021-02-25 11:17:02 -0500611 if (returnComplexity > ReturnComplexity::kSingleSafeReturn &&
John Stiles2558c462021-03-16 17:49:20 -0400612 !function.declaration().returnType().isVoid()) {
John Stiles511c5002021-02-25 11:17:02 -0500613 // Create a variable to hold the result in the extra statements. We don't need to do this
614 // for void-return functions, or in cases that are simple enough that we can just replace
615 // the function-call node with the result expression.
John Stiles44e96be2020-08-31 13:16:04 -0400616 std::unique_ptr<Expression> noInitialValue;
John Stiles7b920442020-12-17 10:43:41 -0500617 InlineVariable var = this->makeInlineVariable(function.declaration().name(),
618 &function.declaration().returnType(),
619 symbolTable.get(), Modifiers{},
620 caller->isBuiltin(), &noInitialValue);
John Stiles28257db2021-03-17 15:18:09 -0400621 inlineStatements.push_back(std::move(var.fVarDecl));
John Stiles7b920442020-12-17 10:43:41 -0500622 resultExpr = std::make_unique<VariableReference>(/*offset=*/-1, var.fVarSymbol);
John Stiles511c5002021-02-25 11:17:02 -0500623 }
John Stiles44e96be2020-08-31 13:16:04 -0400624
625 // Create variables in the extra statements to hold the arguments, and assign the arguments to
626 // them.
627 VariableRewriteMap varMap;
John Stilesbff24ab2021-03-17 13:20:10 -0400628 for (int i = 0; i < arguments.count(); ++i) {
John Stiles049f0df2021-03-19 09:39:44 -0400629 // If the parameter isn't written to within the inline function ...
John Stilesbff24ab2021-03-17 13:20:10 -0400630 const Variable* param = function.declaration().parameters()[i];
John Stiles049f0df2021-03-19 09:39:44 -0400631 const ProgramUsage::VariableCounts& paramUsage = usage.get(*param);
632 if (!paramUsage.fWrite) {
633 // ... and can be inlined trivially (e.g. a swizzle, or a constant array index),
634 // or any expression without side effects that is only accessed at most once...
635 if ((paramUsage.fRead > 1) ? Analysis::IsTrivialExpression(*arguments[i])
636 : !arguments[i]->hasSideEffects()) {
John Stilesf201af82020-09-29 16:57:55 -0400637 // ... we don't need to copy it at all! We can just use the existing expression.
638 varMap[param] = arguments[i]->clone();
John Stiles44e96be2020-08-31 13:16:04 -0400639 continue;
640 }
641 }
John Stiles7b920442020-12-17 10:43:41 -0500642 InlineVariable var = this->makeInlineVariable(param->name(), &arguments[i]->type(),
643 symbolTable.get(), param->modifiers(),
644 caller->isBuiltin(), &arguments[i]);
John Stiles28257db2021-03-17 15:18:09 -0400645 inlineStatements.push_back(std::move(var.fVarDecl));
John Stiles7b920442020-12-17 10:43:41 -0500646 varMap[param] = std::make_unique<VariableReference>(/*offset=*/-1, var.fVarSymbol);
John Stiles44e96be2020-08-31 13:16:04 -0400647 }
648
John Stiles7b920442020-12-17 10:43:41 -0500649 for (const std::unique_ptr<Statement>& stmt : body.children()) {
John Stiles28257db2021-03-17 15:18:09 -0400650 inlineStatements.push_back(this->inlineStatement(offset, &varMap, symbolTable.get(),
651 &resultExpr, returnComplexity, *stmt,
652 caller->isBuiltin()));
John Stiles44e96be2020-08-31 13:16:04 -0400653 }
654
John Stiles28257db2021-03-17 15:18:09 -0400655 SkASSERT(inlineStatements.count() <= expectedStmtCount);
656
John Stilesbf16b6c2021-03-12 19:24:31 -0500657 // Wrap all of the generated statements in a block. We need a real Block here, so we can't use
658 // MakeUnscoped. This is because we need to add another child statement to the Block later.
John Stiles28257db2021-03-17 15:18:09 -0400659 InlinedCall inlinedCall;
660 inlinedCall.fInlinedBody = Block::Make(offset, std::move(inlineStatements),
John Stilesbf16b6c2021-03-12 19:24:31 -0500661 /*symbols=*/nullptr, /*isScope=*/false);
662
John Stiles0c2d14a2021-03-01 10:08:08 -0500663 if (resultExpr) {
664 // Return our result expression as-is.
John Stilese41b4ee2020-09-28 12:28:16 -0400665 inlinedCall.fReplacementExpr = std::move(resultExpr);
John Stiles2558c462021-03-16 17:49:20 -0400666 } else if (function.declaration().returnType().isVoid()) {
John Stiles44e96be2020-08-31 13:16:04 -0400667 // It's a void function, so it doesn't actually result in anything, but we have to return
668 // something non-null as a standin.
John Stiles9ce80f72021-03-11 22:35:19 -0500669 inlinedCall.fReplacementExpr = BoolLiteral::Make(*fContext, offset, /*value=*/false);
John Stiles0c2d14a2021-03-01 10:08:08 -0500670 } else {
671 // It's a non-void function, but it never created a result expression--that is, it never
John Stiles2dda50d2021-03-03 10:46:44 -0500672 // returned anything on any path! This should have been detected in the function finalizer.
673 // Still, discard our output and generate an error.
674 SkDEBUGFAIL("inliner found non-void function that fails to return a value on any path");
675 fContext->fErrors.error(function.fOffset, "inliner found non-void function '" +
John Stiles0c2d14a2021-03-01 10:08:08 -0500676 function.declaration().name() +
John Stiles2dda50d2021-03-03 10:46:44 -0500677 "' that fails to return a value on any path");
John Stiles0c2d14a2021-03-01 10:08:08 -0500678 inlinedCall = {};
John Stiles44e96be2020-08-31 13:16:04 -0400679 }
680
John Stiles44e96be2020-08-31 13:16:04 -0400681 return inlinedCall;
682}
683
John Stiles2d7973a2020-10-02 15:01:03 -0400684bool Inliner::isSafeToInline(const FunctionDefinition* functionDef) {
John Stiles1c03d332020-10-13 10:30:23 -0400685 // A threshold of zero indicates that the inliner is completely disabled, so we can just return.
John Stilesd1204642021-02-17 16:30:02 -0500686 if (this->settings().fInlineThreshold <= 0) {
John Stiles1c03d332020-10-13 10:30:23 -0400687 return false;
688 }
689
John Stiles031a7672020-11-13 16:13:18 -0500690 // Enforce a limit on inlining to avoid pathological cases. (inliner/ExponentialGrowth.sksl)
691 if (fInlinedStatementCounter >= kInlinedStatementLimit) {
692 return false;
693 }
694
John Stiles2d7973a2020-10-02 15:01:03 -0400695 if (functionDef == nullptr) {
John Stiles44e96be2020-08-31 13:16:04 -0400696 // Can't inline something if we don't actually have its definition.
697 return false;
698 }
John Stiles2d7973a2020-10-02 15:01:03 -0400699
John Stiles0dd1a772021-03-09 22:14:27 -0500700 if (functionDef->declaration().modifiers().fFlags & Modifiers::kNoInline_Flag) {
701 // Refuse to inline functions decorated with `noinline`.
702 return false;
703 }
704
John Stilesbff24ab2021-03-17 13:20:10 -0400705 // We don't allow inlining a function with out parameters. (See skia:11326 for rationale.)
706 for (const Variable* param : functionDef->declaration().parameters()) {
707 if (param->modifiers().fFlags & Modifiers::Flag::kOut_Flag) {
708 return false;
709 }
710 }
711
John Stilesdc208472021-03-17 10:58:16 -0400712 // We don't have a mechanism to simulate early returns, so we can't inline if there is one.
713 return GetReturnComplexity(*functionDef) < ReturnComplexity::kEarlyReturns;
John Stiles44e96be2020-08-31 13:16:04 -0400714}
715
John Stiles2d7973a2020-10-02 15:01:03 -0400716// A candidate function for inlining, containing everything that `inlineCall` needs.
717struct InlineCandidate {
John Stiles78047582020-12-16 16:17:41 -0500718 std::shared_ptr<SymbolTable> fSymbols; // the SymbolTable of the candidate
John Stiles2d7973a2020-10-02 15:01:03 -0400719 std::unique_ptr<Statement>* fParentStmt; // the parent Statement of the enclosing stmt
720 std::unique_ptr<Statement>* fEnclosingStmt; // the Statement containing the candidate
721 std::unique_ptr<Expression>* fCandidateExpr; // the candidate FunctionCall to be inlined
722 FunctionDefinition* fEnclosingFunction; // the Function containing the candidate
John Stiles2d7973a2020-10-02 15:01:03 -0400723};
John Stiles93442622020-09-11 12:11:27 -0400724
John Stiles2d7973a2020-10-02 15:01:03 -0400725struct InlineCandidateList {
726 std::vector<InlineCandidate> fCandidates;
727};
728
729class InlineCandidateAnalyzer {
John Stiles70957c82020-10-02 16:42:10 -0400730public:
731 // A list of all the inlining candidates we found during analysis.
732 InlineCandidateList* fCandidateList;
John Stiles2d7973a2020-10-02 15:01:03 -0400733
John Stiles70957c82020-10-02 16:42:10 -0400734 // A stack of the symbol tables; since most nodes don't have one, expected to be shallower than
735 // the enclosing-statement stack.
John Stiles78047582020-12-16 16:17:41 -0500736 std::vector<std::shared_ptr<SymbolTable>> fSymbolTableStack;
John Stiles70957c82020-10-02 16:42:10 -0400737 // A stack of "enclosing" statements--these would be suitable for the inliner to use for adding
738 // new instructions. Not all statements are suitable (e.g. a for-loop's initializer). The
739 // inliner might replace a statement with a block containing the statement.
740 std::vector<std::unique_ptr<Statement>*> fEnclosingStmtStack;
741 // The function that we're currently processing (i.e. inlining into).
742 FunctionDefinition* fEnclosingFunction = nullptr;
John Stiles93442622020-09-11 12:11:27 -0400743
Brian Osman0006ad02020-11-18 15:38:39 -0500744 void visit(const std::vector<std::unique_ptr<ProgramElement>>& elements,
John Stiles78047582020-12-16 16:17:41 -0500745 std::shared_ptr<SymbolTable> symbols,
Brian Osman0006ad02020-11-18 15:38:39 -0500746 InlineCandidateList* candidateList) {
John Stiles70957c82020-10-02 16:42:10 -0400747 fCandidateList = candidateList;
Brian Osman0006ad02020-11-18 15:38:39 -0500748 fSymbolTableStack.push_back(symbols);
John Stiles93442622020-09-11 12:11:27 -0400749
Brian Osman0006ad02020-11-18 15:38:39 -0500750 for (const std::unique_ptr<ProgramElement>& pe : elements) {
Brian Osman1179fcf2020-10-08 16:04:40 -0400751 this->visitProgramElement(pe.get());
John Stiles93442622020-09-11 12:11:27 -0400752 }
753
John Stiles70957c82020-10-02 16:42:10 -0400754 fSymbolTableStack.pop_back();
755 fCandidateList = nullptr;
756 }
757
758 void visitProgramElement(ProgramElement* pe) {
759 switch (pe->kind()) {
760 case ProgramElement::Kind::kFunction: {
761 FunctionDefinition& funcDef = pe->as<FunctionDefinition>();
Brian Osman0006ad02020-11-18 15:38:39 -0500762 fEnclosingFunction = &funcDef;
763 this->visitStatement(&funcDef.body());
John Stiles70957c82020-10-02 16:42:10 -0400764 break;
John Stiles93442622020-09-11 12:11:27 -0400765 }
John Stiles70957c82020-10-02 16:42:10 -0400766 default:
767 // The inliner can't operate outside of a function's scope.
768 break;
769 }
770 }
771
772 void visitStatement(std::unique_ptr<Statement>* stmt,
773 bool isViableAsEnclosingStatement = true) {
774 if (!*stmt) {
775 return;
John Stiles93442622020-09-11 12:11:27 -0400776 }
777
John Stiles70957c82020-10-02 16:42:10 -0400778 size_t oldEnclosingStmtStackSize = fEnclosingStmtStack.size();
779 size_t oldSymbolStackSize = fSymbolTableStack.size();
John Stiles93442622020-09-11 12:11:27 -0400780
John Stiles70957c82020-10-02 16:42:10 -0400781 if (isViableAsEnclosingStatement) {
782 fEnclosingStmtStack.push_back(stmt);
John Stiles93442622020-09-11 12:11:27 -0400783 }
784
John Stiles70957c82020-10-02 16:42:10 -0400785 switch ((*stmt)->kind()) {
786 case Statement::Kind::kBreak:
787 case Statement::Kind::kContinue:
788 case Statement::Kind::kDiscard:
789 case Statement::Kind::kInlineMarker:
790 case Statement::Kind::kNop:
791 break;
792
793 case Statement::Kind::kBlock: {
794 Block& block = (*stmt)->as<Block>();
795 if (block.symbolTable()) {
John Stiles78047582020-12-16 16:17:41 -0500796 fSymbolTableStack.push_back(block.symbolTable());
John Stiles70957c82020-10-02 16:42:10 -0400797 }
798
799 for (std::unique_ptr<Statement>& stmt : block.children()) {
800 this->visitStatement(&stmt);
801 }
802 break;
John Stiles93442622020-09-11 12:11:27 -0400803 }
John Stiles70957c82020-10-02 16:42:10 -0400804 case Statement::Kind::kDo: {
805 DoStatement& doStmt = (*stmt)->as<DoStatement>();
806 // The loop body is a candidate for inlining.
807 this->visitStatement(&doStmt.statement());
808 // The inliner isn't smart enough to inline the test-expression for a do-while
809 // loop at this time. There are two limitations:
810 // - We would need to insert the inlined-body block at the very end of the do-
811 // statement's inner fStatement. We don't support that today, but it's doable.
812 // - We cannot inline the test expression if the loop uses `continue` anywhere; that
813 // would skip over the inlined block that evaluates the test expression. There
814 // isn't a good fix for this--any workaround would be more complex than the cost
815 // of a function call. However, loops that don't use `continue` would still be
816 // viable candidates for inlining.
817 break;
John Stiles93442622020-09-11 12:11:27 -0400818 }
John Stiles70957c82020-10-02 16:42:10 -0400819 case Statement::Kind::kExpression: {
820 ExpressionStatement& expr = (*stmt)->as<ExpressionStatement>();
821 this->visitExpression(&expr.expression());
822 break;
823 }
824 case Statement::Kind::kFor: {
825 ForStatement& forStmt = (*stmt)->as<ForStatement>();
Ethan Nicholas0d31ed52020-10-05 14:47:09 -0400826 if (forStmt.symbols()) {
John Stiles78047582020-12-16 16:17:41 -0500827 fSymbolTableStack.push_back(forStmt.symbols());
John Stiles70957c82020-10-02 16:42:10 -0400828 }
829
830 // The initializer and loop body are candidates for inlining.
Ethan Nicholas0d31ed52020-10-05 14:47:09 -0400831 this->visitStatement(&forStmt.initializer(),
John Stiles70957c82020-10-02 16:42:10 -0400832 /*isViableAsEnclosingStatement=*/false);
Ethan Nicholas0d31ed52020-10-05 14:47:09 -0400833 this->visitStatement(&forStmt.statement());
John Stiles70957c82020-10-02 16:42:10 -0400834
835 // The inliner isn't smart enough to inline the test- or increment-expressions
836 // of a for loop loop at this time. There are a handful of limitations:
837 // - We would need to insert the test-expression block at the very beginning of the
838 // for-loop's inner fStatement, and the increment-expression block at the very
839 // end. We don't support that today, but it's doable.
840 // - The for-loop's built-in test-expression would need to be dropped entirely,
841 // and the loop would be halted via a break statement at the end of the inlined
842 // test-expression. This is again something we don't support today, but it could
843 // be implemented.
844 // - We cannot inline the increment-expression if the loop uses `continue` anywhere;
845 // that would skip over the inlined block that evaluates the increment expression.
846 // There isn't a good fix for this--any workaround would be more complex than the
847 // cost of a function call. However, loops that don't use `continue` would still
848 // be viable candidates for increment-expression inlining.
849 break;
850 }
851 case Statement::Kind::kIf: {
852 IfStatement& ifStmt = (*stmt)->as<IfStatement>();
Ethan Nicholas8c44eca2020-10-07 16:47:09 -0400853 this->visitExpression(&ifStmt.test());
854 this->visitStatement(&ifStmt.ifTrue());
855 this->visitStatement(&ifStmt.ifFalse());
John Stiles70957c82020-10-02 16:42:10 -0400856 break;
857 }
858 case Statement::Kind::kReturn: {
859 ReturnStatement& returnStmt = (*stmt)->as<ReturnStatement>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -0400860 this->visitExpression(&returnStmt.expression());
John Stiles70957c82020-10-02 16:42:10 -0400861 break;
862 }
863 case Statement::Kind::kSwitch: {
864 SwitchStatement& switchStmt = (*stmt)->as<SwitchStatement>();
Ethan Nicholas01b05e52020-10-22 15:53:41 -0400865 if (switchStmt.symbols()) {
John Stiles78047582020-12-16 16:17:41 -0500866 fSymbolTableStack.push_back(switchStmt.symbols());
John Stiles70957c82020-10-02 16:42:10 -0400867 }
868
Ethan Nicholas01b05e52020-10-22 15:53:41 -0400869 this->visitExpression(&switchStmt.value());
John Stilesb23a64b2021-03-11 08:27:59 -0500870 for (const std::unique_ptr<Statement>& switchCase : switchStmt.cases()) {
John Stiles70957c82020-10-02 16:42:10 -0400871 // The switch-case's fValue cannot be a FunctionCall; skip it.
John Stilesb23a64b2021-03-11 08:27:59 -0500872 this->visitStatement(&switchCase->as<SwitchCase>().statement());
John Stiles70957c82020-10-02 16:42:10 -0400873 }
874 break;
875 }
876 case Statement::Kind::kVarDeclaration: {
877 VarDeclaration& varDeclStmt = (*stmt)->as<VarDeclaration>();
878 // Don't need to scan the declaration's sizes; those are always IntLiterals.
Ethan Nicholasc51f33e2020-10-13 13:49:44 -0400879 this->visitExpression(&varDeclStmt.value());
John Stiles70957c82020-10-02 16:42:10 -0400880 break;
881 }
John Stiles70957c82020-10-02 16:42:10 -0400882 default:
883 SkUNREACHABLE;
John Stiles93442622020-09-11 12:11:27 -0400884 }
885
John Stiles70957c82020-10-02 16:42:10 -0400886 // Pop our symbol and enclosing-statement stacks.
887 fSymbolTableStack.resize(oldSymbolStackSize);
888 fEnclosingStmtStack.resize(oldEnclosingStmtStackSize);
889 }
890
891 void visitExpression(std::unique_ptr<Expression>* expr) {
892 if (!*expr) {
893 return;
John Stiles93442622020-09-11 12:11:27 -0400894 }
John Stiles70957c82020-10-02 16:42:10 -0400895
896 switch ((*expr)->kind()) {
897 case Expression::Kind::kBoolLiteral:
898 case Expression::Kind::kDefined:
Brian Osmanbe0b3b72021-01-06 14:27:35 -0500899 case Expression::Kind::kExternalFunctionReference:
John Stiles70957c82020-10-02 16:42:10 -0400900 case Expression::Kind::kFieldAccess:
901 case Expression::Kind::kFloatLiteral:
902 case Expression::Kind::kFunctionReference:
903 case Expression::Kind::kIntLiteral:
John Stiles70957c82020-10-02 16:42:10 -0400904 case Expression::Kind::kSetting:
905 case Expression::Kind::kTypeReference:
906 case Expression::Kind::kVariableReference:
907 // Nothing to scan here.
908 break;
909
910 case Expression::Kind::kBinary: {
911 BinaryExpression& binaryExpr = (*expr)->as<BinaryExpression>();
John Stiles2d4f9592020-10-30 10:29:12 -0400912 this->visitExpression(&binaryExpr.left());
John Stiles70957c82020-10-02 16:42:10 -0400913
914 // Logical-and and logical-or binary expressions do not inline the right side,
915 // because that would invalidate short-circuiting. That is, when evaluating
916 // expressions like these:
917 // (false && x()) // always false
918 // (true || y()) // always true
919 // It is illegal for side-effects from x() or y() to occur. The simplest way to
920 // enforce that rule is to avoid inlining the right side entirely. However, it is
921 // safe for other types of binary expression to inline both sides.
John Stiles45990502021-02-16 10:55:27 -0500922 Operator op = binaryExpr.getOperator();
923 bool shortCircuitable = (op.kind() == Token::Kind::TK_LOGICALAND ||
924 op.kind() == Token::Kind::TK_LOGICALOR);
John Stiles70957c82020-10-02 16:42:10 -0400925 if (!shortCircuitable) {
John Stiles2d4f9592020-10-30 10:29:12 -0400926 this->visitExpression(&binaryExpr.right());
John Stiles70957c82020-10-02 16:42:10 -0400927 }
928 break;
929 }
John Stiles7384b372021-04-01 13:48:15 -0400930 case Expression::Kind::kConstructor:
931 case Expression::Kind::kConstructorArray:
John Stiles2938eea2021-04-01 18:58:25 -0400932 case Expression::Kind::kConstructorDiagonalMatrix:
933 case Expression::Kind::kConstructorSplat: {
John Stiles7384b372021-04-01 13:48:15 -0400934 AnyConstructor& constructorExpr = (*expr)->asAnyConstructor();
935 for (std::unique_ptr<Expression>& arg : constructorExpr.argumentSpan()) {
John Stiles70957c82020-10-02 16:42:10 -0400936 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 }
John Stiles708faba2021-03-19 09:43:23 -0400955 case Expression::Kind::kIndex: {
John Stiles70957c82020-10-02 16:42:10 -0400956 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.
John Stiles708faba2021-03-19 09:43:23 -04001103 using StatementRemappingTable = std::unordered_map<std::unique_ptr<Statement>*,
1104 std::unique_ptr<Statement>*>;
1105 StatementRemappingTable statementRemappingTable;
1106
John Stiles915a38c2020-09-14 09:38:13 -04001107 bool madeChanges = false;
John Stiles2d7973a2020-10-02 15:01:03 -04001108 for (const InlineCandidate& candidate : candidateList.fCandidates) {
John Stiles915a38c2020-09-14 09:38:13 -04001109 FunctionCall& funcCall = (*candidate.fCandidateExpr)->as<FunctionCall>();
John Stiles915a38c2020-09-14 09:38:13 -04001110
John Stiles915a38c2020-09-14 09:38:13 -04001111 // Convert the function call to its inlined equivalent.
John Stiles30fce9c2021-03-18 09:24:06 -04001112 InlinedCall inlinedCall = this->inlineCall(&funcCall, candidate.fSymbols, *usage,
Ethan Nicholas0a5d0962020-10-14 13:33:18 -04001113 &candidate.fEnclosingFunction->declaration());
John Stiles915a38c2020-09-14 09:38:13 -04001114
John Stiles0c2d14a2021-03-01 10:08:08 -05001115 // Stop if an error was detected during the inlining process.
1116 if (!inlinedCall.fInlinedBody && !inlinedCall.fReplacementExpr) {
1117 break;
John Stiles915a38c2020-09-14 09:38:13 -04001118 }
1119
John Stiles0c2d14a2021-03-01 10:08:08 -05001120 // Ensure that the inlined body has a scope if it needs one.
1121 this->ensureScopedBlocks(inlinedCall.fInlinedBody.get(), candidate.fParentStmt->get());
1122
1123 // Add references within the inlined body
1124 usage->add(inlinedCall.fInlinedBody.get());
1125
John Stiles708faba2021-03-19 09:43:23 -04001126 // Look up the enclosing statement; remap it if necessary.
1127 std::unique_ptr<Statement>* enclosingStmt = candidate.fEnclosingStmt;
1128 for (;;) {
1129 auto iter = statementRemappingTable.find(enclosingStmt);
1130 if (iter == statementRemappingTable.end()) {
1131 break;
1132 }
1133 enclosingStmt = iter->second;
1134 }
1135
John Stiles0c2d14a2021-03-01 10:08:08 -05001136 // Move the enclosing statement to the end of the unscoped Block containing the inlined
1137 // function, then replace the enclosing statement with that Block.
1138 // Before:
1139 // fInlinedBody = Block{ stmt1, stmt2, stmt3 }
1140 // fEnclosingStmt = stmt4
1141 // After:
1142 // fInlinedBody = null
1143 // fEnclosingStmt = Block{ stmt1, stmt2, stmt3, stmt4 }
John Stiles708faba2021-03-19 09:43:23 -04001144 inlinedCall.fInlinedBody->children().push_back(std::move(*enclosingStmt));
1145 *enclosingStmt = std::move(inlinedCall.fInlinedBody);
John Stiles0c2d14a2021-03-01 10:08:08 -05001146
John Stiles915a38c2020-09-14 09:38:13 -04001147 // Replace the candidate function call with our replacement expression.
Brian Osman010ce6a2020-10-19 16:34:10 -04001148 usage->replace(candidate.fCandidateExpr->get(), inlinedCall.fReplacementExpr.get());
John Stiles915a38c2020-09-14 09:38:13 -04001149 *candidate.fCandidateExpr = std::move(inlinedCall.fReplacementExpr);
1150 madeChanges = true;
1151
John Stiles708faba2021-03-19 09:43:23 -04001152 // If anything else pointed at our enclosing statement, it's now pointing at a Block
1153 // containing many other statements as well. Maintain a fix-up table to account for this.
1154 statementRemappingTable[enclosingStmt] = &(*enclosingStmt)->as<Block>().children().back();
1155
John Stiles031a7672020-11-13 16:13:18 -05001156 // Stop inlining if we've reached our hard cap on new statements.
1157 if (fInlinedStatementCounter >= kInlinedStatementLimit) {
1158 break;
1159 }
1160
John Stiles915a38c2020-09-14 09:38:13 -04001161 // Note that nothing was destroyed except for the FunctionCall. All other nodes should
1162 // remain valid.
1163 }
1164
1165 return madeChanges;
John Stiles93442622020-09-11 12:11:27 -04001166}
1167
John Stiles44e96be2020-08-31 13:16:04 -04001168} // namespace SkSL