blob: de21703b8fa649f2a55c401b6b9263138cd52343 [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 Stilesfd7252f2021-04-04 22:24:40 -040022#include "src/sksl/ir/SkSLConstructorScalarCast.h"
John Stiles2938eea2021-04-01 18:58:25 -040023#include "src/sksl/ir/SkSLConstructorSplat.h"
John Stilesb14a8192021-04-05 11:40:46 -040024#include "src/sksl/ir/SkSLConstructorVectorCast.h"
John Stiles44e96be2020-08-31 13:16:04 -040025#include "src/sksl/ir/SkSLContinueStatement.h"
26#include "src/sksl/ir/SkSLDiscardStatement.h"
27#include "src/sksl/ir/SkSLDoStatement.h"
28#include "src/sksl/ir/SkSLEnum.h"
29#include "src/sksl/ir/SkSLExpressionStatement.h"
30#include "src/sksl/ir/SkSLExternalFunctionCall.h"
Brian Osmanbe0b3b72021-01-06 14:27:35 -050031#include "src/sksl/ir/SkSLExternalFunctionReference.h"
John Stiles44e96be2020-08-31 13:16:04 -040032#include "src/sksl/ir/SkSLField.h"
33#include "src/sksl/ir/SkSLFieldAccess.h"
34#include "src/sksl/ir/SkSLFloatLiteral.h"
35#include "src/sksl/ir/SkSLForStatement.h"
36#include "src/sksl/ir/SkSLFunctionCall.h"
37#include "src/sksl/ir/SkSLFunctionDeclaration.h"
38#include "src/sksl/ir/SkSLFunctionDefinition.h"
39#include "src/sksl/ir/SkSLFunctionReference.h"
40#include "src/sksl/ir/SkSLIfStatement.h"
41#include "src/sksl/ir/SkSLIndexExpression.h"
John Stiles98c1f822020-09-09 14:18:53 -040042#include "src/sksl/ir/SkSLInlineMarker.h"
John Stiles44e96be2020-08-31 13:16:04 -040043#include "src/sksl/ir/SkSLIntLiteral.h"
44#include "src/sksl/ir/SkSLInterfaceBlock.h"
John Stiles44e96be2020-08-31 13:16:04 -040045#include "src/sksl/ir/SkSLNop.h"
John Stiles44e96be2020-08-31 13:16:04 -040046#include "src/sksl/ir/SkSLPostfixExpression.h"
47#include "src/sksl/ir/SkSLPrefixExpression.h"
48#include "src/sksl/ir/SkSLReturnStatement.h"
49#include "src/sksl/ir/SkSLSetting.h"
50#include "src/sksl/ir/SkSLSwitchCase.h"
51#include "src/sksl/ir/SkSLSwitchStatement.h"
52#include "src/sksl/ir/SkSLSwizzle.h"
53#include "src/sksl/ir/SkSLTernaryExpression.h"
54#include "src/sksl/ir/SkSLUnresolvedFunction.h"
55#include "src/sksl/ir/SkSLVarDeclarations.h"
John Stiles44e96be2020-08-31 13:16:04 -040056#include "src/sksl/ir/SkSLVariable.h"
57#include "src/sksl/ir/SkSLVariableReference.h"
John Stiles44e96be2020-08-31 13:16:04 -040058
59namespace SkSL {
60namespace {
61
John Stiles031a7672020-11-13 16:13:18 -050062static constexpr int kInlinedStatementLimit = 2500;
63
John Stiles44e96be2020-08-31 13:16:04 -040064static int count_returns_at_end_of_control_flow(const FunctionDefinition& funcDef) {
65 class CountReturnsAtEndOfControlFlow : public ProgramVisitor {
66 public:
67 CountReturnsAtEndOfControlFlow(const FunctionDefinition& funcDef) {
68 this->visitProgramElement(funcDef);
69 }
70
John Stiles5b408a32021-03-17 09:53:32 -040071 bool visitExpression(const Expression& expr) override {
72 // Do not recurse into expressions.
73 return false;
74 }
75
John Stiles44e96be2020-08-31 13:16:04 -040076 bool visitStatement(const Statement& stmt) override {
Ethan Nicholase6592142020-09-08 10:22:09 -040077 switch (stmt.kind()) {
78 case Statement::Kind::kBlock: {
John Stiles44e96be2020-08-31 13:16:04 -040079 // Check only the last statement of a block.
Ethan Nicholas7bd60432020-09-25 14:31:59 -040080 const auto& block = stmt.as<Block>();
81 return block.children().size() &&
82 this->visitStatement(*block.children().back());
John Stiles44e96be2020-08-31 13:16:04 -040083 }
Ethan Nicholase6592142020-09-08 10:22:09 -040084 case Statement::Kind::kSwitch:
Ethan Nicholase6592142020-09-08 10:22:09 -040085 case Statement::Kind::kDo:
86 case Statement::Kind::kFor:
John Stiles44e96be2020-08-31 13:16:04 -040087 // Don't introspect switches or loop structures at all.
88 return false;
89
Ethan Nicholase6592142020-09-08 10:22:09 -040090 case Statement::Kind::kReturn:
John Stiles44e96be2020-08-31 13:16:04 -040091 ++fNumReturns;
92 [[fallthrough]];
93
94 default:
John Stiles93442622020-09-11 12:11:27 -040095 return INHERITED::visitStatement(stmt);
John Stiles44e96be2020-08-31 13:16:04 -040096 }
97 }
98
99 int fNumReturns = 0;
100 using INHERITED = ProgramVisitor;
101 };
102
103 return CountReturnsAtEndOfControlFlow{funcDef}.fNumReturns;
104}
105
John Stiles991b09d2020-09-10 13:33:40 -0400106static bool contains_recursive_call(const FunctionDeclaration& funcDecl) {
107 class ContainsRecursiveCall : public ProgramVisitor {
108 public:
109 bool visit(const FunctionDeclaration& funcDecl) {
110 fFuncDecl = &funcDecl;
Ethan Nicholased84b732020-10-08 11:45:44 -0400111 return funcDecl.definition() ? this->visitProgramElement(*funcDecl.definition())
112 : false;
John Stiles991b09d2020-09-10 13:33:40 -0400113 }
114
115 bool visitExpression(const Expression& expr) override {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400116 if (expr.is<FunctionCall>() && expr.as<FunctionCall>().function().matches(*fFuncDecl)) {
John Stiles991b09d2020-09-10 13:33:40 -0400117 return true;
118 }
119 return INHERITED::visitExpression(expr);
120 }
121
122 bool visitStatement(const Statement& stmt) override {
Ethan Nicholasceb62142020-10-09 16:51:18 -0400123 if (stmt.is<InlineMarker>() &&
124 stmt.as<InlineMarker>().function().matches(*fFuncDecl)) {
John Stiles991b09d2020-09-10 13:33:40 -0400125 return true;
126 }
127 return INHERITED::visitStatement(stmt);
128 }
129
130 const FunctionDeclaration* fFuncDecl;
131 using INHERITED = ProgramVisitor;
132 };
133
134 return ContainsRecursiveCall{}.visit(funcDecl);
135}
136
John Stiles6d696082020-10-01 10:18:54 -0400137static std::unique_ptr<Statement>* find_parent_statement(
138 const std::vector<std::unique_ptr<Statement>*>& stmtStack) {
John Stiles915a38c2020-09-14 09:38:13 -0400139 SkASSERT(!stmtStack.empty());
140
141 // Walk the statement stack from back to front, ignoring the last element (which is the
142 // enclosing statement).
143 auto iter = stmtStack.rbegin();
144 ++iter;
145
146 // Anything counts as a parent statement other than a scopeless Block.
147 for (; iter != stmtStack.rend(); ++iter) {
John Stiles6d696082020-10-01 10:18:54 -0400148 std::unique_ptr<Statement>* stmt = *iter;
149 if (!(*stmt)->is<Block>() || (*stmt)->as<Block>().isScope()) {
John Stiles915a38c2020-09-14 09:38:13 -0400150 return stmt;
151 }
152 }
153
154 // There wasn't any parent statement to be found.
155 return nullptr;
156}
157
John Stilese41b4ee2020-09-28 12:28:16 -0400158std::unique_ptr<Expression> clone_with_ref_kind(const Expression& expr,
159 VariableReference::RefKind refKind) {
160 std::unique_ptr<Expression> clone = expr.clone();
John Stiles47c0a742021-02-09 09:30:35 -0500161 Analysis::UpdateRefKind(clone.get(), refKind);
John Stilese41b4ee2020-09-28 12:28:16 -0400162 return clone;
163}
164
John Stiles77702f12020-12-17 14:38:56 -0500165class CountReturnsWithLimit : public ProgramVisitor {
166public:
167 CountReturnsWithLimit(const FunctionDefinition& funcDef, int limit) : fLimit(limit) {
168 this->visitProgramElement(funcDef);
169 }
170
John Stiles5b408a32021-03-17 09:53:32 -0400171 bool visitExpression(const Expression& expr) override {
172 // Do not recurse into expressions.
173 return false;
174 }
175
John Stiles77702f12020-12-17 14:38:56 -0500176 bool visitStatement(const Statement& stmt) override {
177 switch (stmt.kind()) {
178 case Statement::Kind::kReturn: {
179 ++fNumReturns;
180 fDeepestReturn = std::max(fDeepestReturn, fScopedBlockDepth);
181 return (fNumReturns >= fLimit) || INHERITED::visitStatement(stmt);
182 }
John Stilesc5ff4862020-12-22 13:47:05 -0500183 case Statement::Kind::kVarDeclaration: {
184 if (fScopedBlockDepth > 1) {
185 fVariablesInBlocks = true;
186 }
187 return INHERITED::visitStatement(stmt);
188 }
John Stiles77702f12020-12-17 14:38:56 -0500189 case Statement::Kind::kBlock: {
190 int depthIncrement = stmt.as<Block>().isScope() ? 1 : 0;
191 fScopedBlockDepth += depthIncrement;
192 bool result = INHERITED::visitStatement(stmt);
193 fScopedBlockDepth -= depthIncrement;
John Stilesc5ff4862020-12-22 13:47:05 -0500194 if (fNumReturns == 0 && fScopedBlockDepth <= 1) {
195 // If closing this block puts us back at the top level, and we haven't
196 // encountered any return statements yet, any vardecls we may have encountered
197 // up until this point can be ignored. They are out of scope now, and they were
198 // never used in a return statement.
199 fVariablesInBlocks = false;
200 }
John Stiles77702f12020-12-17 14:38:56 -0500201 return result;
202 }
203 default:
204 return INHERITED::visitStatement(stmt);
205 }
206 }
207
208 int fNumReturns = 0;
209 int fDeepestReturn = 0;
210 int fLimit = 0;
211 int fScopedBlockDepth = 0;
John Stilesc5ff4862020-12-22 13:47:05 -0500212 bool fVariablesInBlocks = false;
John Stiles77702f12020-12-17 14:38:56 -0500213 using INHERITED = ProgramVisitor;
214};
215
John Stiles44e96be2020-08-31 13:16:04 -0400216} // namespace
217
John Stiles77702f12020-12-17 14:38:56 -0500218Inliner::ReturnComplexity Inliner::GetReturnComplexity(const FunctionDefinition& funcDef) {
219 int returnsAtEndOfControlFlow = count_returns_at_end_of_control_flow(funcDef);
220 CountReturnsWithLimit counter{funcDef, returnsAtEndOfControlFlow + 1};
John Stiles77702f12020-12-17 14:38:56 -0500221 if (counter.fNumReturns > returnsAtEndOfControlFlow) {
222 return ReturnComplexity::kEarlyReturns;
223 }
John Stilesc5ff4862020-12-22 13:47:05 -0500224 if (counter.fNumReturns > 1) {
John Stiles77702f12020-12-17 14:38:56 -0500225 return ReturnComplexity::kScopedReturns;
226 }
John Stilesc5ff4862020-12-22 13:47:05 -0500227 if (counter.fVariablesInBlocks && counter.fDeepestReturn > 1) {
228 return ReturnComplexity::kScopedReturns;
229 }
John Stiles8937cd42021-03-17 19:32:59 +0000230 return ReturnComplexity::kSingleSafeReturn;
John Stiles77702f12020-12-17 14:38:56 -0500231}
232
John Stilesb61ee902020-09-21 12:26:59 -0400233void Inliner::ensureScopedBlocks(Statement* inlinedBody, Statement* parentStmt) {
234 // No changes necessary if this statement isn't actually a block.
235 if (!inlinedBody || !inlinedBody->is<Block>()) {
236 return;
237 }
238
239 // No changes necessary if the parent statement doesn't require a scope.
240 if (!parentStmt || !(parentStmt->is<IfStatement>() || parentStmt->is<ForStatement>() ||
Brian Osmand6f23382020-12-15 17:08:59 -0500241 parentStmt->is<DoStatement>())) {
John Stilesb61ee902020-09-21 12:26:59 -0400242 return;
243 }
244
245 Block& block = inlinedBody->as<Block>();
246
247 // The inliner will create inlined function bodies as a Block containing multiple statements,
248 // but no scope. Normally, this is fine, but if this block is used as the statement for a
249 // do/for/if/while, this isn't actually possible to represent textually; a scope must be added
250 // for the generated code to match the intent. In the case of Blocks nested inside other Blocks,
251 // we add the scope to the outermost block if needed. Zero-statement blocks have similar
252 // issues--if we don't represent the Block textually somehow, we run the risk of accidentally
253 // absorbing the following statement into our loop--so we also add a scope to these.
254 for (Block* nestedBlock = &block;; ) {
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400255 if (nestedBlock->isScope()) {
John Stilesb61ee902020-09-21 12:26:59 -0400256 // We found an explicit scope; all is well.
257 return;
258 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400259 if (nestedBlock->children().size() != 1) {
John Stilesb61ee902020-09-21 12:26:59 -0400260 // We found a block with multiple (or zero) statements, but no scope? Let's add a scope
261 // to the outermost block.
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400262 block.setIsScope(true);
John Stilesb61ee902020-09-21 12:26:59 -0400263 return;
264 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400265 if (!nestedBlock->children()[0]->is<Block>()) {
John Stilesb61ee902020-09-21 12:26:59 -0400266 // This block has exactly one thing inside, and it's not another block. No need to scope
267 // it.
268 return;
269 }
270 // We have to go deeper.
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400271 nestedBlock = &nestedBlock->children()[0]->as<Block>();
John Stilesb61ee902020-09-21 12:26:59 -0400272 }
273}
274
John Stilesd1204642021-02-17 16:30:02 -0500275void Inliner::reset(ModifiersPool* modifiers) {
Ethan Nicholas041fd0a2020-10-07 16:42:04 -0400276 fModifiers = modifiers;
Ethan Nicholas6f4eee22021-01-11 12:37:42 -0500277 fMangler.reset();
John Stiles031a7672020-11-13 16:13:18 -0500278 fInlinedStatementCounter = 0;
John Stiles44e96be2020-08-31 13:16:04 -0400279}
280
281std::unique_ptr<Expression> Inliner::inlineExpression(int offset,
282 VariableRewriteMap* varMap,
John Stilesd7cc0932020-11-30 12:24:27 -0500283 SymbolTable* symbolTableForExpression,
John Stiles44e96be2020-08-31 13:16:04 -0400284 const Expression& expression) {
285 auto expr = [&](const std::unique_ptr<Expression>& e) -> std::unique_ptr<Expression> {
286 if (e) {
John Stilesd7cc0932020-11-30 12:24:27 -0500287 return this->inlineExpression(offset, varMap, symbolTableForExpression, *e);
John Stiles44e96be2020-08-31 13:16:04 -0400288 }
289 return nullptr;
290 };
John Stiles8e3b6be2020-10-13 11:14:08 -0400291 auto argList = [&](const ExpressionArray& originalArgs) -> ExpressionArray {
292 ExpressionArray args;
John Stilesf4bda742020-10-14 16:57:41 -0400293 args.reserve_back(originalArgs.size());
John Stiles44e96be2020-08-31 13:16:04 -0400294 for (const std::unique_ptr<Expression>& arg : originalArgs) {
295 args.push_back(expr(arg));
296 }
297 return args;
298 };
299
Ethan Nicholase6592142020-09-08 10:22:09 -0400300 switch (expression.kind()) {
301 case Expression::Kind::kBinary: {
John Stiles6a1a98c2021-01-14 18:35:34 -0500302 const BinaryExpression& binaryExpr = expression.as<BinaryExpression>();
John Stilese2aec432021-03-01 09:27:48 -0500303 return BinaryExpression::Make(*fContext,
304 expr(binaryExpr.left()),
305 binaryExpr.getOperator(),
306 expr(binaryExpr.right()));
John Stiles44e96be2020-08-31 13:16:04 -0400307 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400308 case Expression::Kind::kBoolLiteral:
309 case Expression::Kind::kIntLiteral:
310 case Expression::Kind::kFloatLiteral:
John Stiles44e96be2020-08-31 13:16:04 -0400311 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400312 case Expression::Kind::kConstructor: {
John Stiles44e96be2020-08-31 13:16:04 -0400313 const Constructor& constructor = expression.as<Constructor>();
John Stiles23521a82021-03-02 17:02:51 -0500314 auto inlinedCtor = Constructor::Convert(
315 *fContext, offset, *constructor.type().clone(symbolTableForExpression),
316 argList(constructor.arguments()));
317 SkASSERT(inlinedCtor);
318 return inlinedCtor;
John Stiles44e96be2020-08-31 13:16:04 -0400319 }
John Stiles7384b372021-04-01 13:48:15 -0400320 case Expression::Kind::kConstructorArray: {
321 const ConstructorArray& ctor = expression.as<ConstructorArray>();
322 return ConstructorArray::Make(*fContext, offset,
323 *ctor.type().clone(symbolTableForExpression),
324 argList(ctor.arguments()));
325 }
John Stilese1182782021-03-30 22:09:37 -0400326 case Expression::Kind::kConstructorDiagonalMatrix: {
327 const ConstructorDiagonalMatrix& ctor = expression.as<ConstructorDiagonalMatrix>();
328 return ConstructorDiagonalMatrix::Make(*fContext, offset,
329 *ctor.type().clone(symbolTableForExpression),
330 expr(ctor.argument()));
331 }
John Stilesfd7252f2021-04-04 22:24:40 -0400332 case Expression::Kind::kConstructorScalarCast: {
333 const ConstructorScalarCast& ctor = expression.as<ConstructorScalarCast>();
334 return ConstructorScalarCast::Make(*fContext, offset,
335 *ctor.type().clone(symbolTableForExpression),
336 expr(ctor.argument()));
337 }
John Stiles2938eea2021-04-01 18:58:25 -0400338 case Expression::Kind::kConstructorSplat: {
339 const ConstructorSplat& ctor = expression.as<ConstructorSplat>();
340 return ConstructorSplat::Make(*fContext, offset,
341 *ctor.type().clone(symbolTableForExpression),
342 expr(ctor.argument()));
343 }
John Stilesb14a8192021-04-05 11:40:46 -0400344 case Expression::Kind::kConstructorVectorCast: {
345 const ConstructorVectorCast& ctor = expression.as<ConstructorVectorCast>();
346 return ConstructorVectorCast::Make(*fContext, offset,
347 *ctor.type().clone(symbolTableForExpression),
348 expr(ctor.argument()));
349 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400350 case Expression::Kind::kExternalFunctionCall: {
John Stiles44e96be2020-08-31 13:16:04 -0400351 const ExternalFunctionCall& externalCall = expression.as<ExternalFunctionCall>();
Ethan Nicholas444ccc62020-10-09 10:16:22 -0400352 return std::make_unique<ExternalFunctionCall>(offset, &externalCall.function(),
Ethan Nicholas6e86ec92020-09-30 14:29:56 -0400353 argList(externalCall.arguments()));
John Stiles44e96be2020-08-31 13:16:04 -0400354 }
Brian Osmanbe0b3b72021-01-06 14:27:35 -0500355 case Expression::Kind::kExternalFunctionReference:
John Stiles44e96be2020-08-31 13:16:04 -0400356 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400357 case Expression::Kind::kFieldAccess: {
John Stiles44e96be2020-08-31 13:16:04 -0400358 const FieldAccess& f = expression.as<FieldAccess>();
John Stiles06d600f2021-03-08 09:18:21 -0500359 return FieldAccess::Make(*fContext, expr(f.base()), f.fieldIndex(), f.ownerKind());
John Stiles44e96be2020-08-31 13:16:04 -0400360 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400361 case Expression::Kind::kFunctionCall: {
John Stiles44e96be2020-08-31 13:16:04 -0400362 const FunctionCall& funcCall = expression.as<FunctionCall>();
John Stilescd7ba502021-03-19 10:54:59 -0400363 return FunctionCall::Make(*fContext,
364 offset,
365 funcCall.type().clone(symbolTableForExpression),
366 funcCall.function(),
367 argList(funcCall.arguments()));
John Stiles44e96be2020-08-31 13:16:04 -0400368 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400369 case Expression::Kind::kFunctionReference:
Brian Osman2b3b35f2020-09-08 09:17:36 -0400370 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400371 case Expression::Kind::kIndex: {
John Stiles44e96be2020-08-31 13:16:04 -0400372 const IndexExpression& idx = expression.as<IndexExpression>();
John Stiles51d33982021-03-08 09:18:07 -0500373 return IndexExpression::Make(*fContext, expr(idx.base()), expr(idx.index()));
John Stiles44e96be2020-08-31 13:16:04 -0400374 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400375 case Expression::Kind::kPrefix: {
John Stiles44e96be2020-08-31 13:16:04 -0400376 const PrefixExpression& p = expression.as<PrefixExpression>();
John Stilesb0eb20f2021-02-26 15:29:33 -0500377 return PrefixExpression::Make(*fContext, p.getOperator(), expr(p.operand()));
John Stiles44e96be2020-08-31 13:16:04 -0400378 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400379 case Expression::Kind::kPostfix: {
John Stiles44e96be2020-08-31 13:16:04 -0400380 const PostfixExpression& p = expression.as<PostfixExpression>();
John Stiles52d3b012021-02-26 15:56:48 -0500381 return PostfixExpression::Make(*fContext, expr(p.operand()), p.getOperator());
John Stiles44e96be2020-08-31 13:16:04 -0400382 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400383 case Expression::Kind::kSetting:
John Stiles44e96be2020-08-31 13:16:04 -0400384 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400385 case Expression::Kind::kSwizzle: {
John Stiles44e96be2020-08-31 13:16:04 -0400386 const Swizzle& s = expression.as<Swizzle>();
John Stiles6e88e042021-02-19 14:09:38 -0500387 return Swizzle::Make(*fContext, expr(s.base()), s.components());
John Stiles44e96be2020-08-31 13:16:04 -0400388 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400389 case Expression::Kind::kTernary: {
John Stiles44e96be2020-08-31 13:16:04 -0400390 const TernaryExpression& t = expression.as<TernaryExpression>();
John Stiles90518f72021-02-26 20:44:54 -0500391 return TernaryExpression::Make(*fContext, expr(t.test()),
392 expr(t.ifTrue()), expr(t.ifFalse()));
John Stiles44e96be2020-08-31 13:16:04 -0400393 }
Brian Osman83ba9302020-09-11 13:33:46 -0400394 case Expression::Kind::kTypeReference:
395 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400396 case Expression::Kind::kVariableReference: {
John Stiles44e96be2020-08-31 13:16:04 -0400397 const VariableReference& v = expression.as<VariableReference>();
Ethan Nicholas78686922020-10-08 06:46:27 -0400398 auto varMapIter = varMap->find(v.variable());
John Stilese41b4ee2020-09-28 12:28:16 -0400399 if (varMapIter != varMap->end()) {
Ethan Nicholas78686922020-10-08 06:46:27 -0400400 return clone_with_ref_kind(*varMapIter->second, v.refKind());
John Stiles44e96be2020-08-31 13:16:04 -0400401 }
402 return v.clone();
403 }
404 default:
405 SkASSERT(false);
406 return nullptr;
407 }
408}
409
410std::unique_ptr<Statement> Inliner::inlineStatement(int offset,
411 VariableRewriteMap* varMap,
412 SymbolTable* symbolTableForStatement,
John Stiles77702f12020-12-17 14:38:56 -0500413 std::unique_ptr<Expression>* resultExpr,
414 ReturnComplexity returnComplexity,
Brian Osman3887a012020-09-30 13:22:27 -0400415 const Statement& statement,
416 bool isBuiltinCode) {
John Stiles44e96be2020-08-31 13:16:04 -0400417 auto stmt = [&](const std::unique_ptr<Statement>& s) -> std::unique_ptr<Statement> {
418 if (s) {
John Stilesa5f3c312020-09-22 12:05:16 -0400419 return this->inlineStatement(offset, varMap, symbolTableForStatement, resultExpr,
John Stiles77702f12020-12-17 14:38:56 -0500420 returnComplexity, *s, isBuiltinCode);
John Stiles44e96be2020-08-31 13:16:04 -0400421 }
422 return nullptr;
423 };
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400424 auto blockStmts = [&](const Block& block) {
John Stiles8f2a0cf2020-10-13 12:48:21 -0400425 StatementArray result;
John Stilesf4bda742020-10-14 16:57:41 -0400426 result.reserve_back(block.children().size());
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400427 for (const std::unique_ptr<Statement>& child : block.children()) {
428 result.push_back(stmt(child));
429 }
430 return result;
431 };
John Stiles44e96be2020-08-31 13:16:04 -0400432 auto expr = [&](const std::unique_ptr<Expression>& e) -> std::unique_ptr<Expression> {
433 if (e) {
John Stilesd7cc0932020-11-30 12:24:27 -0500434 return this->inlineExpression(offset, varMap, symbolTableForStatement, *e);
John Stiles44e96be2020-08-31 13:16:04 -0400435 }
436 return nullptr;
437 };
John Stiles031a7672020-11-13 16:13:18 -0500438
439 ++fInlinedStatementCounter;
440
Ethan Nicholase6592142020-09-08 10:22:09 -0400441 switch (statement.kind()) {
442 case Statement::Kind::kBlock: {
John Stiles44e96be2020-08-31 13:16:04 -0400443 const Block& b = statement.as<Block>();
John Stilesbf16b6c2021-03-12 19:24:31 -0500444 return Block::Make(offset, blockStmts(b),
445 SymbolTable::WrapIfBuiltin(b.symbolTable()),
446 b.isScope());
John Stiles44e96be2020-08-31 13:16:04 -0400447 }
448
Ethan Nicholase6592142020-09-08 10:22:09 -0400449 case Statement::Kind::kBreak:
450 case Statement::Kind::kContinue:
451 case Statement::Kind::kDiscard:
John Stiles44e96be2020-08-31 13:16:04 -0400452 return statement.clone();
453
Ethan Nicholase6592142020-09-08 10:22:09 -0400454 case Statement::Kind::kDo: {
John Stiles44e96be2020-08-31 13:16:04 -0400455 const DoStatement& d = statement.as<DoStatement>();
John Stilesea5822e2021-02-26 11:18:20 -0500456 return DoStatement::Make(*fContext, stmt(d.statement()), expr(d.test()));
John Stiles44e96be2020-08-31 13:16:04 -0400457 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400458 case Statement::Kind::kExpression: {
John Stiles44e96be2020-08-31 13:16:04 -0400459 const ExpressionStatement& e = statement.as<ExpressionStatement>();
John Stiles3e5871c2021-02-25 20:52:03 -0500460 return ExpressionStatement::Make(*fContext, expr(e.expression()));
John Stiles44e96be2020-08-31 13:16:04 -0400461 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400462 case Statement::Kind::kFor: {
John Stiles44e96be2020-08-31 13:16:04 -0400463 const ForStatement& f = statement.as<ForStatement>();
464 // need to ensure initializer is evaluated first so that we've already remapped its
465 // declarations by the time we evaluate test & next
Ethan Nicholas0d31ed52020-10-05 14:47:09 -0400466 std::unique_ptr<Statement> initializer = stmt(f.initializer());
John Stilesb321a072021-02-25 16:24:19 -0500467 return ForStatement::Make(*fContext, offset, std::move(initializer), expr(f.test()),
468 expr(f.next()), stmt(f.statement()),
469 SymbolTable::WrapIfBuiltin(f.symbols()));
John Stiles44e96be2020-08-31 13:16:04 -0400470 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400471 case Statement::Kind::kIf: {
John Stiles44e96be2020-08-31 13:16:04 -0400472 const IfStatement& i = statement.as<IfStatement>();
John Stilescf3059e2021-02-25 14:27:02 -0500473 return IfStatement::Make(*fContext, offset, i.isStatic(), expr(i.test()),
474 stmt(i.ifTrue()), stmt(i.ifFalse()));
John Stiles44e96be2020-08-31 13:16:04 -0400475 }
John Stiles98c1f822020-09-09 14:18:53 -0400476 case Statement::Kind::kInlineMarker:
Ethan Nicholase6592142020-09-08 10:22:09 -0400477 case Statement::Kind::kNop:
John Stiles44e96be2020-08-31 13:16:04 -0400478 return statement.clone();
John Stilesea5822e2021-02-26 11:18:20 -0500479
Ethan Nicholase6592142020-09-08 10:22:09 -0400480 case Statement::Kind::kReturn: {
John Stiles44e96be2020-08-31 13:16:04 -0400481 const ReturnStatement& r = statement.as<ReturnStatement>();
John Stiles77702f12020-12-17 14:38:56 -0500482 if (!r.expression()) {
John Stilesdc208472021-03-17 10:58:16 -0400483 // This function doesn't return a value. We won't inline functions with early
484 // returns, so a return statement is a no-op and can be treated as such.
485 return Nop::Make();
John Stiles44e96be2020-08-31 13:16:04 -0400486 }
John Stiles77702f12020-12-17 14:38:56 -0500487
John Stilesc5ff4862020-12-22 13:47:05 -0500488 // If a function only contains a single return, and it doesn't reference variables from
489 // inside an Block's scope, we don't need to store the result in a variable at all. Just
490 // replace the function-call expression with the function's return expression.
John Stiles77702f12020-12-17 14:38:56 -0500491 SkASSERT(resultExpr);
John Stilesc5ff4862020-12-22 13:47:05 -0500492 if (returnComplexity <= ReturnComplexity::kSingleSafeReturn) {
John Stiles77702f12020-12-17 14:38:56 -0500493 *resultExpr = expr(r.expression());
John Stilesa0c04d62021-03-11 23:07:24 -0500494 return Nop::Make();
John Stiles77702f12020-12-17 14:38:56 -0500495 }
496
497 // For more complex functions, assign their result into a variable.
John Stiles511c5002021-02-25 11:17:02 -0500498 SkASSERT(*resultExpr);
John Stiles3e5871c2021-02-25 20:52:03 -0500499 auto assignment = ExpressionStatement::Make(
500 *fContext,
John Stilese2aec432021-03-01 09:27:48 -0500501 BinaryExpression::Make(
502 *fContext,
503 clone_with_ref_kind(**resultExpr, VariableRefKind::kWrite),
John Stiles77702f12020-12-17 14:38:56 -0500504 Token::Kind::TK_EQ,
John Stilese2aec432021-03-01 09:27:48 -0500505 expr(r.expression())));
John Stiles77702f12020-12-17 14:38:56 -0500506
John Stiles77702f12020-12-17 14:38:56 -0500507 // Functions without early returns aren't wrapped in a for loop and don't need to worry
508 // about breaking out of the control flow.
John Stiles3e5871c2021-02-25 20:52:03 -0500509 return assignment;
John Stiles44e96be2020-08-31 13:16:04 -0400510 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400511 case Statement::Kind::kSwitch: {
John Stiles44e96be2020-08-31 13:16:04 -0400512 const SwitchStatement& ss = statement.as<SwitchStatement>();
John Stilesb23a64b2021-03-11 08:27:59 -0500513 StatementArray cases;
514 cases.reserve_back(ss.cases().size());
515 for (const std::unique_ptr<Statement>& statement : ss.cases()) {
516 const SwitchCase& sc = statement->as<SwitchCase>();
517 cases.push_back(std::make_unique<SwitchCase>(offset, expr(sc.value()),
518 stmt(sc.statement())));
John Stiles44e96be2020-08-31 13:16:04 -0400519 }
John Stilese1d1b082021-02-23 13:44:36 -0500520 return SwitchStatement::Make(*fContext, offset, ss.isStatic(), expr(ss.value()),
521 std::move(cases), SymbolTable::WrapIfBuiltin(ss.symbols()));
John Stiles44e96be2020-08-31 13:16:04 -0400522 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400523 case Statement::Kind::kVarDeclaration: {
John Stiles44e96be2020-08-31 13:16:04 -0400524 const VarDeclaration& decl = statement.as<VarDeclaration>();
John Stiles35fee4c2020-12-16 18:25:14 +0000525 std::unique_ptr<Expression> initialValue = expr(decl.value());
John Stilesddcc8432021-01-15 15:32:32 -0500526 const Variable& variable = decl.var();
527
John Stiles35fee4c2020-12-16 18:25:14 +0000528 // We assign unique names to inlined variables--scopes hide most of the problems in this
529 // regard, but see `InlinerAvoidsVariableNameOverlap` for a counterexample where unique
530 // names are important.
John Stilesd51c9792021-03-18 11:40:14 -0400531 const String* name = symbolTableForStatement->takeOwnershipOfString(
532 fMangler.uniqueName(variable.name(), symbolTableForStatement));
Ethan Nicholas5b9b0db2021-01-21 13:12:01 -0500533 auto clonedVar = std::make_unique<Variable>(
534 offset,
535 &variable.modifiers(),
John Stilesd51c9792021-03-18 11:40:14 -0400536 name->c_str(),
Ethan Nicholas5b9b0db2021-01-21 13:12:01 -0500537 variable.type().clone(symbolTableForStatement),
538 isBuiltinCode,
539 variable.storage());
540 (*varMap)[&variable] = std::make_unique<VariableReference>(offset, clonedVar.get());
John Stilese67bd132021-03-19 18:39:25 -0400541 auto result = VarDeclaration::Make(*fContext,
542 clonedVar.get(),
543 decl.baseType().clone(symbolTableForStatement),
544 decl.arraySize(),
545 std::move(initialValue));
Ethan Nicholas5b9b0db2021-01-21 13:12:01 -0500546 symbolTableForStatement->takeOwnershipOfSymbol(std::move(clonedVar));
John Stilese67bd132021-03-19 18:39:25 -0400547 return result;
John Stiles44e96be2020-08-31 13:16:04 -0400548 }
John Stiles44e96be2020-08-31 13:16:04 -0400549 default:
550 SkASSERT(false);
551 return nullptr;
552 }
553}
554
John Stiles7b920442020-12-17 10:43:41 -0500555Inliner::InlineVariable Inliner::makeInlineVariable(const String& baseName,
556 const Type* type,
557 SymbolTable* symbolTable,
558 Modifiers modifiers,
559 bool isBuiltinCode,
560 std::unique_ptr<Expression>* initialValue) {
561 // $floatLiteral or $intLiteral aren't real types that we can use for scratch variables, so
562 // replace them if they ever appear here. If this happens, we likely forgot to coerce a type
563 // somewhere during compilation.
John Stiles14975272021-01-12 11:41:14 -0500564 if (type->isLiteral()) {
565 SkDEBUGFAIL("found a $literal type while inlining");
566 type = &type->scalarTypeForLiteral();
John Stiles7b920442020-12-17 10:43:41 -0500567 }
568
John Stilesbff24ab2021-03-17 13:20:10 -0400569 // Out parameters aren't supported.
570 SkASSERT(!(modifiers.fFlags & Modifiers::kOut_Flag));
571
John Stiles7b920442020-12-17 10:43:41 -0500572 // Provide our new variable with a unique name, and add it to our symbol table.
John Stilesd51c9792021-03-18 11:40:14 -0400573 const String* name =
574 symbolTable->takeOwnershipOfString(fMangler.uniqueName(baseName, symbolTable));
John Stiles7b920442020-12-17 10:43:41 -0500575
576 // Create our new variable and add it to the symbol table.
577 InlineVariable result;
Ethan Nicholas5b9b0db2021-01-21 13:12:01 -0500578 auto var = std::make_unique<Variable>(/*offset=*/-1,
579 fModifiers->addToPool(Modifiers()),
John Stilesd51c9792021-03-18 11:40:14 -0400580 name->c_str(),
Ethan Nicholas5b9b0db2021-01-21 13:12:01 -0500581 type,
582 isBuiltinCode,
583 Variable::Storage::kLocal);
John Stiles7b920442020-12-17 10:43:41 -0500584
John Stilesbff24ab2021-03-17 13:20:10 -0400585 // Create our variable declaration.
John Stilese67bd132021-03-19 18:39:25 -0400586 result.fVarDecl = VarDeclaration::Make(*fContext, var.get(), type, /*arraySize=*/0,
587 std::move(*initialValue));
Ethan Nicholas5b9b0db2021-01-21 13:12:01 -0500588 result.fVarSymbol = symbolTable->add(std::move(var));
John Stiles7b920442020-12-17 10:43:41 -0500589 return result;
590}
591
John Stiles6eadf132020-09-08 10:16:10 -0400592Inliner::InlinedCall Inliner::inlineCall(FunctionCall* call,
John Stiles78047582020-12-16 16:17:41 -0500593 std::shared_ptr<SymbolTable> symbolTable,
John Stiles30fce9c2021-03-18 09:24:06 -0400594 const ProgramUsage& usage,
Brian Osman3887a012020-09-30 13:22:27 -0400595 const FunctionDeclaration* caller) {
John Stiles44e96be2020-08-31 13:16:04 -0400596 // Inlining is more complicated here than in a typical compiler, because we have to have a
597 // high-level IR and can't just drop statements into the middle of an expression or even use
598 // gotos.
599 //
600 // Since we can't insert statements into an expression, we run the inline function as extra
601 // statements before the statement we're currently processing, relying on a lack of execution
602 // order guarantees. Since we can't use gotos (which are normally used to replace return
603 // statements), we wrap the whole function in a loop and use break statements to jump to the
604 // end.
John Stiles44e96be2020-08-31 13:16:04 -0400605 SkASSERT(fContext);
606 SkASSERT(call);
Ethan Nicholased84b732020-10-08 11:45:44 -0400607 SkASSERT(this->isSafeToInline(call->function().definition()));
John Stiles44e96be2020-08-31 13:16:04 -0400608
John Stiles8e3b6be2020-10-13 11:14:08 -0400609 ExpressionArray& arguments = call->arguments();
John Stiles6eadf132020-09-08 10:16:10 -0400610 const int offset = call->fOffset;
Ethan Nicholased84b732020-10-08 11:45:44 -0400611 const FunctionDefinition& function = *call->function().definition();
John Stiles28257db2021-03-17 15:18:09 -0400612 const Block& body = function.body()->as<Block>();
John Stiles77702f12020-12-17 14:38:56 -0500613 const ReturnComplexity returnComplexity = GetReturnComplexity(function);
John Stiles6eadf132020-09-08 10:16:10 -0400614
John Stiles28257db2021-03-17 15:18:09 -0400615 StatementArray inlineStatements;
616 int expectedStmtCount = 1 + // Inline marker
617 1 + // Result variable
618 arguments.size() + // Function argument temp-vars
619 body.children().size(); // Inlined code
John Stiles98c1f822020-09-09 14:18:53 -0400620
John Stiles28257db2021-03-17 15:18:09 -0400621 inlineStatements.reserve_back(expectedStmtCount);
622 inlineStatements.push_back(InlineMarker::Make(&call->function()));
John Stiles44e96be2020-08-31 13:16:04 -0400623
John Stilese41b4ee2020-09-28 12:28:16 -0400624 std::unique_ptr<Expression> resultExpr;
John Stiles511c5002021-02-25 11:17:02 -0500625 if (returnComplexity > ReturnComplexity::kSingleSafeReturn &&
John Stiles2558c462021-03-16 17:49:20 -0400626 !function.declaration().returnType().isVoid()) {
John Stiles511c5002021-02-25 11:17:02 -0500627 // Create a variable to hold the result in the extra statements. We don't need to do this
628 // for void-return functions, or in cases that are simple enough that we can just replace
629 // the function-call node with the result expression.
John Stiles44e96be2020-08-31 13:16:04 -0400630 std::unique_ptr<Expression> noInitialValue;
John Stiles7b920442020-12-17 10:43:41 -0500631 InlineVariable var = this->makeInlineVariable(function.declaration().name(),
632 &function.declaration().returnType(),
633 symbolTable.get(), Modifiers{},
634 caller->isBuiltin(), &noInitialValue);
John Stiles28257db2021-03-17 15:18:09 -0400635 inlineStatements.push_back(std::move(var.fVarDecl));
John Stiles7b920442020-12-17 10:43:41 -0500636 resultExpr = std::make_unique<VariableReference>(/*offset=*/-1, var.fVarSymbol);
John Stiles511c5002021-02-25 11:17:02 -0500637 }
John Stiles44e96be2020-08-31 13:16:04 -0400638
639 // Create variables in the extra statements to hold the arguments, and assign the arguments to
640 // them.
641 VariableRewriteMap varMap;
John Stilesbff24ab2021-03-17 13:20:10 -0400642 for (int i = 0; i < arguments.count(); ++i) {
John Stiles049f0df2021-03-19 09:39:44 -0400643 // If the parameter isn't written to within the inline function ...
John Stilesbff24ab2021-03-17 13:20:10 -0400644 const Variable* param = function.declaration().parameters()[i];
John Stiles049f0df2021-03-19 09:39:44 -0400645 const ProgramUsage::VariableCounts& paramUsage = usage.get(*param);
646 if (!paramUsage.fWrite) {
647 // ... and can be inlined trivially (e.g. a swizzle, or a constant array index),
648 // or any expression without side effects that is only accessed at most once...
649 if ((paramUsage.fRead > 1) ? Analysis::IsTrivialExpression(*arguments[i])
650 : !arguments[i]->hasSideEffects()) {
John Stilesf201af82020-09-29 16:57:55 -0400651 // ... we don't need to copy it at all! We can just use the existing expression.
652 varMap[param] = arguments[i]->clone();
John Stiles44e96be2020-08-31 13:16:04 -0400653 continue;
654 }
655 }
John Stiles7b920442020-12-17 10:43:41 -0500656 InlineVariable var = this->makeInlineVariable(param->name(), &arguments[i]->type(),
657 symbolTable.get(), param->modifiers(),
658 caller->isBuiltin(), &arguments[i]);
John Stiles28257db2021-03-17 15:18:09 -0400659 inlineStatements.push_back(std::move(var.fVarDecl));
John Stiles7b920442020-12-17 10:43:41 -0500660 varMap[param] = std::make_unique<VariableReference>(/*offset=*/-1, var.fVarSymbol);
John Stiles44e96be2020-08-31 13:16:04 -0400661 }
662
John Stiles7b920442020-12-17 10:43:41 -0500663 for (const std::unique_ptr<Statement>& stmt : body.children()) {
John Stiles28257db2021-03-17 15:18:09 -0400664 inlineStatements.push_back(this->inlineStatement(offset, &varMap, symbolTable.get(),
665 &resultExpr, returnComplexity, *stmt,
666 caller->isBuiltin()));
John Stiles44e96be2020-08-31 13:16:04 -0400667 }
668
John Stiles28257db2021-03-17 15:18:09 -0400669 SkASSERT(inlineStatements.count() <= expectedStmtCount);
670
John Stilesbf16b6c2021-03-12 19:24:31 -0500671 // Wrap all of the generated statements in a block. We need a real Block here, so we can't use
672 // MakeUnscoped. This is because we need to add another child statement to the Block later.
John Stiles28257db2021-03-17 15:18:09 -0400673 InlinedCall inlinedCall;
674 inlinedCall.fInlinedBody = Block::Make(offset, std::move(inlineStatements),
John Stilesbf16b6c2021-03-12 19:24:31 -0500675 /*symbols=*/nullptr, /*isScope=*/false);
676
John Stiles0c2d14a2021-03-01 10:08:08 -0500677 if (resultExpr) {
678 // Return our result expression as-is.
John Stilese41b4ee2020-09-28 12:28:16 -0400679 inlinedCall.fReplacementExpr = std::move(resultExpr);
John Stiles2558c462021-03-16 17:49:20 -0400680 } else if (function.declaration().returnType().isVoid()) {
John Stiles44e96be2020-08-31 13:16:04 -0400681 // It's a void function, so it doesn't actually result in anything, but we have to return
682 // something non-null as a standin.
John Stiles9ce80f72021-03-11 22:35:19 -0500683 inlinedCall.fReplacementExpr = BoolLiteral::Make(*fContext, offset, /*value=*/false);
John Stiles0c2d14a2021-03-01 10:08:08 -0500684 } else {
685 // It's a non-void function, but it never created a result expression--that is, it never
John Stiles2dda50d2021-03-03 10:46:44 -0500686 // returned anything on any path! This should have been detected in the function finalizer.
687 // Still, discard our output and generate an error.
688 SkDEBUGFAIL("inliner found non-void function that fails to return a value on any path");
689 fContext->fErrors.error(function.fOffset, "inliner found non-void function '" +
John Stiles0c2d14a2021-03-01 10:08:08 -0500690 function.declaration().name() +
John Stiles2dda50d2021-03-03 10:46:44 -0500691 "' that fails to return a value on any path");
John Stiles0c2d14a2021-03-01 10:08:08 -0500692 inlinedCall = {};
John Stiles44e96be2020-08-31 13:16:04 -0400693 }
694
John Stiles44e96be2020-08-31 13:16:04 -0400695 return inlinedCall;
696}
697
John Stiles2d7973a2020-10-02 15:01:03 -0400698bool Inliner::isSafeToInline(const FunctionDefinition* functionDef) {
John Stiles1c03d332020-10-13 10:30:23 -0400699 // A threshold of zero indicates that the inliner is completely disabled, so we can just return.
John Stilesd1204642021-02-17 16:30:02 -0500700 if (this->settings().fInlineThreshold <= 0) {
John Stiles1c03d332020-10-13 10:30:23 -0400701 return false;
702 }
703
John Stiles031a7672020-11-13 16:13:18 -0500704 // Enforce a limit on inlining to avoid pathological cases. (inliner/ExponentialGrowth.sksl)
705 if (fInlinedStatementCounter >= kInlinedStatementLimit) {
706 return false;
707 }
708
John Stiles2d7973a2020-10-02 15:01:03 -0400709 if (functionDef == nullptr) {
John Stiles44e96be2020-08-31 13:16:04 -0400710 // Can't inline something if we don't actually have its definition.
711 return false;
712 }
John Stiles2d7973a2020-10-02 15:01:03 -0400713
John Stiles0dd1a772021-03-09 22:14:27 -0500714 if (functionDef->declaration().modifiers().fFlags & Modifiers::kNoInline_Flag) {
715 // Refuse to inline functions decorated with `noinline`.
716 return false;
717 }
718
John Stilesbff24ab2021-03-17 13:20:10 -0400719 // We don't allow inlining a function with out parameters. (See skia:11326 for rationale.)
720 for (const Variable* param : functionDef->declaration().parameters()) {
721 if (param->modifiers().fFlags & Modifiers::Flag::kOut_Flag) {
722 return false;
723 }
724 }
725
John Stilesdc208472021-03-17 10:58:16 -0400726 // We don't have a mechanism to simulate early returns, so we can't inline if there is one.
727 return GetReturnComplexity(*functionDef) < ReturnComplexity::kEarlyReturns;
John Stiles44e96be2020-08-31 13:16:04 -0400728}
729
John Stiles2d7973a2020-10-02 15:01:03 -0400730// A candidate function for inlining, containing everything that `inlineCall` needs.
731struct InlineCandidate {
John Stiles78047582020-12-16 16:17:41 -0500732 std::shared_ptr<SymbolTable> fSymbols; // the SymbolTable of the candidate
John Stiles2d7973a2020-10-02 15:01:03 -0400733 std::unique_ptr<Statement>* fParentStmt; // the parent Statement of the enclosing stmt
734 std::unique_ptr<Statement>* fEnclosingStmt; // the Statement containing the candidate
735 std::unique_ptr<Expression>* fCandidateExpr; // the candidate FunctionCall to be inlined
736 FunctionDefinition* fEnclosingFunction; // the Function containing the candidate
John Stiles2d7973a2020-10-02 15:01:03 -0400737};
John Stiles93442622020-09-11 12:11:27 -0400738
John Stiles2d7973a2020-10-02 15:01:03 -0400739struct InlineCandidateList {
740 std::vector<InlineCandidate> fCandidates;
741};
742
743class InlineCandidateAnalyzer {
John Stiles70957c82020-10-02 16:42:10 -0400744public:
745 // A list of all the inlining candidates we found during analysis.
746 InlineCandidateList* fCandidateList;
John Stiles2d7973a2020-10-02 15:01:03 -0400747
John Stiles70957c82020-10-02 16:42:10 -0400748 // A stack of the symbol tables; since most nodes don't have one, expected to be shallower than
749 // the enclosing-statement stack.
John Stiles78047582020-12-16 16:17:41 -0500750 std::vector<std::shared_ptr<SymbolTable>> fSymbolTableStack;
John Stiles70957c82020-10-02 16:42:10 -0400751 // A stack of "enclosing" statements--these would be suitable for the inliner to use for adding
752 // new instructions. Not all statements are suitable (e.g. a for-loop's initializer). The
753 // inliner might replace a statement with a block containing the statement.
754 std::vector<std::unique_ptr<Statement>*> fEnclosingStmtStack;
755 // The function that we're currently processing (i.e. inlining into).
756 FunctionDefinition* fEnclosingFunction = nullptr;
John Stiles93442622020-09-11 12:11:27 -0400757
Brian Osman0006ad02020-11-18 15:38:39 -0500758 void visit(const std::vector<std::unique_ptr<ProgramElement>>& elements,
John Stiles78047582020-12-16 16:17:41 -0500759 std::shared_ptr<SymbolTable> symbols,
Brian Osman0006ad02020-11-18 15:38:39 -0500760 InlineCandidateList* candidateList) {
John Stiles70957c82020-10-02 16:42:10 -0400761 fCandidateList = candidateList;
Brian Osman0006ad02020-11-18 15:38:39 -0500762 fSymbolTableStack.push_back(symbols);
John Stiles93442622020-09-11 12:11:27 -0400763
Brian Osman0006ad02020-11-18 15:38:39 -0500764 for (const std::unique_ptr<ProgramElement>& pe : elements) {
Brian Osman1179fcf2020-10-08 16:04:40 -0400765 this->visitProgramElement(pe.get());
John Stiles93442622020-09-11 12:11:27 -0400766 }
767
John Stiles70957c82020-10-02 16:42:10 -0400768 fSymbolTableStack.pop_back();
769 fCandidateList = nullptr;
770 }
771
772 void visitProgramElement(ProgramElement* pe) {
773 switch (pe->kind()) {
774 case ProgramElement::Kind::kFunction: {
775 FunctionDefinition& funcDef = pe->as<FunctionDefinition>();
Brian Osman0006ad02020-11-18 15:38:39 -0500776 fEnclosingFunction = &funcDef;
777 this->visitStatement(&funcDef.body());
John Stiles70957c82020-10-02 16:42:10 -0400778 break;
John Stiles93442622020-09-11 12:11:27 -0400779 }
John Stiles70957c82020-10-02 16:42:10 -0400780 default:
781 // The inliner can't operate outside of a function's scope.
782 break;
783 }
784 }
785
786 void visitStatement(std::unique_ptr<Statement>* stmt,
787 bool isViableAsEnclosingStatement = true) {
788 if (!*stmt) {
789 return;
John Stiles93442622020-09-11 12:11:27 -0400790 }
791
John Stiles70957c82020-10-02 16:42:10 -0400792 size_t oldEnclosingStmtStackSize = fEnclosingStmtStack.size();
793 size_t oldSymbolStackSize = fSymbolTableStack.size();
John Stiles93442622020-09-11 12:11:27 -0400794
John Stiles70957c82020-10-02 16:42:10 -0400795 if (isViableAsEnclosingStatement) {
796 fEnclosingStmtStack.push_back(stmt);
John Stiles93442622020-09-11 12:11:27 -0400797 }
798
John Stiles70957c82020-10-02 16:42:10 -0400799 switch ((*stmt)->kind()) {
800 case Statement::Kind::kBreak:
801 case Statement::Kind::kContinue:
802 case Statement::Kind::kDiscard:
803 case Statement::Kind::kInlineMarker:
804 case Statement::Kind::kNop:
805 break;
806
807 case Statement::Kind::kBlock: {
808 Block& block = (*stmt)->as<Block>();
809 if (block.symbolTable()) {
John Stiles78047582020-12-16 16:17:41 -0500810 fSymbolTableStack.push_back(block.symbolTable());
John Stiles70957c82020-10-02 16:42:10 -0400811 }
812
813 for (std::unique_ptr<Statement>& stmt : block.children()) {
814 this->visitStatement(&stmt);
815 }
816 break;
John Stiles93442622020-09-11 12:11:27 -0400817 }
John Stiles70957c82020-10-02 16:42:10 -0400818 case Statement::Kind::kDo: {
819 DoStatement& doStmt = (*stmt)->as<DoStatement>();
820 // The loop body is a candidate for inlining.
821 this->visitStatement(&doStmt.statement());
822 // The inliner isn't smart enough to inline the test-expression for a do-while
823 // loop at this time. There are two limitations:
824 // - We would need to insert the inlined-body block at the very end of the do-
825 // statement's inner fStatement. We don't support that today, but it's doable.
826 // - We cannot inline the test expression if the loop uses `continue` anywhere; that
827 // would skip over the inlined block that evaluates the test expression. There
828 // isn't a good fix for this--any workaround would be more complex than the cost
829 // of a function call. However, loops that don't use `continue` would still be
830 // viable candidates for inlining.
831 break;
John Stiles93442622020-09-11 12:11:27 -0400832 }
John Stiles70957c82020-10-02 16:42:10 -0400833 case Statement::Kind::kExpression: {
834 ExpressionStatement& expr = (*stmt)->as<ExpressionStatement>();
835 this->visitExpression(&expr.expression());
836 break;
837 }
838 case Statement::Kind::kFor: {
839 ForStatement& forStmt = (*stmt)->as<ForStatement>();
Ethan Nicholas0d31ed52020-10-05 14:47:09 -0400840 if (forStmt.symbols()) {
John Stiles78047582020-12-16 16:17:41 -0500841 fSymbolTableStack.push_back(forStmt.symbols());
John Stiles70957c82020-10-02 16:42:10 -0400842 }
843
844 // The initializer and loop body are candidates for inlining.
Ethan Nicholas0d31ed52020-10-05 14:47:09 -0400845 this->visitStatement(&forStmt.initializer(),
John Stiles70957c82020-10-02 16:42:10 -0400846 /*isViableAsEnclosingStatement=*/false);
Ethan Nicholas0d31ed52020-10-05 14:47:09 -0400847 this->visitStatement(&forStmt.statement());
John Stiles70957c82020-10-02 16:42:10 -0400848
849 // The inliner isn't smart enough to inline the test- or increment-expressions
850 // of a for loop loop at this time. There are a handful of limitations:
851 // - We would need to insert the test-expression block at the very beginning of the
852 // for-loop's inner fStatement, and the increment-expression block at the very
853 // end. We don't support that today, but it's doable.
854 // - The for-loop's built-in test-expression would need to be dropped entirely,
855 // and the loop would be halted via a break statement at the end of the inlined
856 // test-expression. This is again something we don't support today, but it could
857 // be implemented.
858 // - We cannot inline the increment-expression if the loop uses `continue` anywhere;
859 // that would skip over the inlined block that evaluates the increment expression.
860 // There isn't a good fix for this--any workaround would be more complex than the
861 // cost of a function call. However, loops that don't use `continue` would still
862 // be viable candidates for increment-expression inlining.
863 break;
864 }
865 case Statement::Kind::kIf: {
866 IfStatement& ifStmt = (*stmt)->as<IfStatement>();
Ethan Nicholas8c44eca2020-10-07 16:47:09 -0400867 this->visitExpression(&ifStmt.test());
868 this->visitStatement(&ifStmt.ifTrue());
869 this->visitStatement(&ifStmt.ifFalse());
John Stiles70957c82020-10-02 16:42:10 -0400870 break;
871 }
872 case Statement::Kind::kReturn: {
873 ReturnStatement& returnStmt = (*stmt)->as<ReturnStatement>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -0400874 this->visitExpression(&returnStmt.expression());
John Stiles70957c82020-10-02 16:42:10 -0400875 break;
876 }
877 case Statement::Kind::kSwitch: {
878 SwitchStatement& switchStmt = (*stmt)->as<SwitchStatement>();
Ethan Nicholas01b05e52020-10-22 15:53:41 -0400879 if (switchStmt.symbols()) {
John Stiles78047582020-12-16 16:17:41 -0500880 fSymbolTableStack.push_back(switchStmt.symbols());
John Stiles70957c82020-10-02 16:42:10 -0400881 }
882
Ethan Nicholas01b05e52020-10-22 15:53:41 -0400883 this->visitExpression(&switchStmt.value());
John Stilesb23a64b2021-03-11 08:27:59 -0500884 for (const std::unique_ptr<Statement>& switchCase : switchStmt.cases()) {
John Stiles70957c82020-10-02 16:42:10 -0400885 // The switch-case's fValue cannot be a FunctionCall; skip it.
John Stilesb23a64b2021-03-11 08:27:59 -0500886 this->visitStatement(&switchCase->as<SwitchCase>().statement());
John Stiles70957c82020-10-02 16:42:10 -0400887 }
888 break;
889 }
890 case Statement::Kind::kVarDeclaration: {
891 VarDeclaration& varDeclStmt = (*stmt)->as<VarDeclaration>();
892 // Don't need to scan the declaration's sizes; those are always IntLiterals.
Ethan Nicholasc51f33e2020-10-13 13:49:44 -0400893 this->visitExpression(&varDeclStmt.value());
John Stiles70957c82020-10-02 16:42:10 -0400894 break;
895 }
John Stiles70957c82020-10-02 16:42:10 -0400896 default:
897 SkUNREACHABLE;
John Stiles93442622020-09-11 12:11:27 -0400898 }
899
John Stiles70957c82020-10-02 16:42:10 -0400900 // Pop our symbol and enclosing-statement stacks.
901 fSymbolTableStack.resize(oldSymbolStackSize);
902 fEnclosingStmtStack.resize(oldEnclosingStmtStackSize);
903 }
904
905 void visitExpression(std::unique_ptr<Expression>* expr) {
906 if (!*expr) {
907 return;
John Stiles93442622020-09-11 12:11:27 -0400908 }
John Stiles70957c82020-10-02 16:42:10 -0400909
910 switch ((*expr)->kind()) {
911 case Expression::Kind::kBoolLiteral:
912 case Expression::Kind::kDefined:
Brian Osmanbe0b3b72021-01-06 14:27:35 -0500913 case Expression::Kind::kExternalFunctionReference:
John Stiles70957c82020-10-02 16:42:10 -0400914 case Expression::Kind::kFieldAccess:
915 case Expression::Kind::kFloatLiteral:
916 case Expression::Kind::kFunctionReference:
917 case Expression::Kind::kIntLiteral:
John Stiles70957c82020-10-02 16:42:10 -0400918 case Expression::Kind::kSetting:
919 case Expression::Kind::kTypeReference:
920 case Expression::Kind::kVariableReference:
921 // Nothing to scan here.
922 break;
923
924 case Expression::Kind::kBinary: {
925 BinaryExpression& binaryExpr = (*expr)->as<BinaryExpression>();
John Stiles2d4f9592020-10-30 10:29:12 -0400926 this->visitExpression(&binaryExpr.left());
John Stiles70957c82020-10-02 16:42:10 -0400927
928 // Logical-and and logical-or binary expressions do not inline the right side,
929 // because that would invalidate short-circuiting. That is, when evaluating
930 // expressions like these:
931 // (false && x()) // always false
932 // (true || y()) // always true
933 // It is illegal for side-effects from x() or y() to occur. The simplest way to
934 // enforce that rule is to avoid inlining the right side entirely. However, it is
935 // safe for other types of binary expression to inline both sides.
John Stiles45990502021-02-16 10:55:27 -0500936 Operator op = binaryExpr.getOperator();
937 bool shortCircuitable = (op.kind() == Token::Kind::TK_LOGICALAND ||
938 op.kind() == Token::Kind::TK_LOGICALOR);
John Stiles70957c82020-10-02 16:42:10 -0400939 if (!shortCircuitable) {
John Stiles2d4f9592020-10-30 10:29:12 -0400940 this->visitExpression(&binaryExpr.right());
John Stiles70957c82020-10-02 16:42:10 -0400941 }
942 break;
943 }
John Stiles7384b372021-04-01 13:48:15 -0400944 case Expression::Kind::kConstructor:
945 case Expression::Kind::kConstructorArray:
John Stiles2938eea2021-04-01 18:58:25 -0400946 case Expression::Kind::kConstructorDiagonalMatrix:
John Stilesfd7252f2021-04-04 22:24:40 -0400947 case Expression::Kind::kConstructorScalarCast:
John Stilesb14a8192021-04-05 11:40:46 -0400948 case Expression::Kind::kConstructorSplat:
949 case Expression::Kind::kConstructorVectorCast: {
John Stiles7384b372021-04-01 13:48:15 -0400950 AnyConstructor& constructorExpr = (*expr)->asAnyConstructor();
951 for (std::unique_ptr<Expression>& arg : constructorExpr.argumentSpan()) {
John Stiles70957c82020-10-02 16:42:10 -0400952 this->visitExpression(&arg);
953 }
954 break;
955 }
956 case Expression::Kind::kExternalFunctionCall: {
957 ExternalFunctionCall& funcCallExpr = (*expr)->as<ExternalFunctionCall>();
958 for (std::unique_ptr<Expression>& arg : funcCallExpr.arguments()) {
959 this->visitExpression(&arg);
960 }
961 break;
962 }
963 case Expression::Kind::kFunctionCall: {
964 FunctionCall& funcCallExpr = (*expr)->as<FunctionCall>();
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400965 for (std::unique_ptr<Expression>& arg : funcCallExpr.arguments()) {
John Stiles70957c82020-10-02 16:42:10 -0400966 this->visitExpression(&arg);
967 }
968 this->addInlineCandidate(expr);
969 break;
970 }
John Stiles708faba2021-03-19 09:43:23 -0400971 case Expression::Kind::kIndex: {
John Stiles70957c82020-10-02 16:42:10 -0400972 IndexExpression& indexExpr = (*expr)->as<IndexExpression>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -0400973 this->visitExpression(&indexExpr.base());
974 this->visitExpression(&indexExpr.index());
John Stiles70957c82020-10-02 16:42:10 -0400975 break;
976 }
977 case Expression::Kind::kPostfix: {
978 PostfixExpression& postfixExpr = (*expr)->as<PostfixExpression>();
Ethan Nicholas444ccc62020-10-09 10:16:22 -0400979 this->visitExpression(&postfixExpr.operand());
John Stiles70957c82020-10-02 16:42:10 -0400980 break;
981 }
982 case Expression::Kind::kPrefix: {
983 PrefixExpression& prefixExpr = (*expr)->as<PrefixExpression>();
Ethan Nicholas444ccc62020-10-09 10:16:22 -0400984 this->visitExpression(&prefixExpr.operand());
John Stiles70957c82020-10-02 16:42:10 -0400985 break;
986 }
987 case Expression::Kind::kSwizzle: {
988 Swizzle& swizzleExpr = (*expr)->as<Swizzle>();
Ethan Nicholas6b4d5812020-10-12 16:11:51 -0400989 this->visitExpression(&swizzleExpr.base());
John Stiles70957c82020-10-02 16:42:10 -0400990 break;
991 }
992 case Expression::Kind::kTernary: {
993 TernaryExpression& ternaryExpr = (*expr)->as<TernaryExpression>();
994 // The test expression is a candidate for inlining.
Ethan Nicholasdd218162020-10-08 05:48:01 -0400995 this->visitExpression(&ternaryExpr.test());
John Stiles70957c82020-10-02 16:42:10 -0400996 // The true- and false-expressions cannot be inlined, because we are only allowed to
997 // evaluate one side.
998 break;
999 }
1000 default:
1001 SkUNREACHABLE;
1002 }
1003 }
1004
1005 void addInlineCandidate(std::unique_ptr<Expression>* candidate) {
1006 fCandidateList->fCandidates.push_back(
1007 InlineCandidate{fSymbolTableStack.back(),
1008 find_parent_statement(fEnclosingStmtStack),
1009 fEnclosingStmtStack.back(),
1010 candidate,
John Stiles9b9415e2020-11-23 14:48:06 -05001011 fEnclosingFunction});
John Stiles70957c82020-10-02 16:42:10 -04001012 }
John Stiles2d7973a2020-10-02 15:01:03 -04001013};
John Stiles93442622020-09-11 12:11:27 -04001014
John Stiles9b9415e2020-11-23 14:48:06 -05001015static const FunctionDeclaration& candidate_func(const InlineCandidate& candidate) {
1016 return (*candidate.fCandidateExpr)->as<FunctionCall>().function();
1017}
John Stiles915a38c2020-09-14 09:38:13 -04001018
John Stiles9b9415e2020-11-23 14:48:06 -05001019bool Inliner::candidateCanBeInlined(const InlineCandidate& candidate, InlinabilityCache* cache) {
1020 const FunctionDeclaration& funcDecl = candidate_func(candidate);
John Stiles1c03d332020-10-13 10:30:23 -04001021 auto [iter, wasInserted] = cache->insert({&funcDecl, false});
John Stiles2d7973a2020-10-02 15:01:03 -04001022 if (wasInserted) {
1023 // Recursion is forbidden here to avoid an infinite death spiral of inlining.
John Stiles132cfdd2021-03-15 22:08:38 +00001024 iter->second = this->isSafeToInline(funcDecl.definition()) &&
1025 !contains_recursive_call(funcDecl);
John Stiles93442622020-09-11 12:11:27 -04001026 }
1027
John Stiles2d7973a2020-10-02 15:01:03 -04001028 return iter->second;
1029}
1030
John Stiles9b9415e2020-11-23 14:48:06 -05001031int Inliner::getFunctionSize(const FunctionDeclaration& funcDecl, FunctionSizeCache* cache) {
1032 auto [iter, wasInserted] = cache->insert({&funcDecl, 0});
John Stiles2d7973a2020-10-02 15:01:03 -04001033 if (wasInserted) {
John Stiles9b9415e2020-11-23 14:48:06 -05001034 iter->second = Analysis::NodeCountUpToLimit(*funcDecl.definition(),
John Stilesd1204642021-02-17 16:30:02 -05001035 this->settings().fInlineThreshold);
John Stiles2d7973a2020-10-02 15:01:03 -04001036 }
John Stiles2d7973a2020-10-02 15:01:03 -04001037 return iter->second;
1038}
1039
Brian Osman0006ad02020-11-18 15:38:39 -05001040void Inliner::buildCandidateList(const std::vector<std::unique_ptr<ProgramElement>>& elements,
John Stiles78047582020-12-16 16:17:41 -05001041 std::shared_ptr<SymbolTable> symbols, ProgramUsage* usage,
Brian Osman0006ad02020-11-18 15:38:39 -05001042 InlineCandidateList* candidateList) {
John Stiles2d7973a2020-10-02 15:01:03 -04001043 // This is structured much like a ProgramVisitor, but does not actually use ProgramVisitor.
1044 // The analyzer needs to keep track of the `unique_ptr<T>*` of statements and expressions so
1045 // that they can later be replaced, and ProgramVisitor does not provide this; it only provides a
1046 // `const T&`.
1047 InlineCandidateAnalyzer analyzer;
Brian Osman0006ad02020-11-18 15:38:39 -05001048 analyzer.visit(elements, symbols, candidateList);
John Stiles2d7973a2020-10-02 15:01:03 -04001049
John Stiles0ad233f2020-11-25 11:02:05 -05001050 // Early out if there are no inlining candidates.
John Stiles2d7973a2020-10-02 15:01:03 -04001051 std::vector<InlineCandidate>& candidates = candidateList->fCandidates;
John Stiles0ad233f2020-11-25 11:02:05 -05001052 if (candidates.empty()) {
1053 return;
1054 }
1055
1056 // Remove candidates that are not safe to inline.
John Stiles2d7973a2020-10-02 15:01:03 -04001057 InlinabilityCache cache;
1058 candidates.erase(std::remove_if(candidates.begin(),
1059 candidates.end(),
1060 [&](const InlineCandidate& candidate) {
1061 return !this->candidateCanBeInlined(candidate, &cache);
1062 }),
1063 candidates.end());
1064
John Stiles0ad233f2020-11-25 11:02:05 -05001065 // If the inline threshold is unlimited, or if we have no candidates left, our candidate list is
1066 // complete.
John Stilesd1204642021-02-17 16:30:02 -05001067 if (this->settings().fInlineThreshold == INT_MAX || candidates.empty()) {
John Stiles0ad233f2020-11-25 11:02:05 -05001068 return;
John Stiles2d7973a2020-10-02 15:01:03 -04001069 }
John Stiles0ad233f2020-11-25 11:02:05 -05001070
1071 // Remove candidates on a per-function basis if the effect of inlining would be to make more
1072 // than `inlineThreshold` nodes. (i.e. if Func() would be inlined six times and its size is
1073 // 10 nodes, it should be inlined if the inlineThreshold is 60 or higher.)
1074 FunctionSizeCache functionSizeCache;
1075 FunctionSizeCache candidateTotalCost;
1076 for (InlineCandidate& candidate : candidates) {
1077 const FunctionDeclaration& fnDecl = candidate_func(candidate);
1078 candidateTotalCost[&fnDecl] += this->getFunctionSize(fnDecl, &functionSizeCache);
1079 }
1080
John Stilesd1204642021-02-17 16:30:02 -05001081 candidates.erase(std::remove_if(candidates.begin(), candidates.end(),
1082 [&](const InlineCandidate& candidate) {
1083 const FunctionDeclaration& fnDecl = candidate_func(candidate);
1084 if (fnDecl.modifiers().fFlags & Modifiers::kInline_Flag) {
1085 // Functions marked `inline` ignore size limitations.
1086 return false;
1087 }
1088 if (usage->get(fnDecl) == 1) {
1089 // If a function is only used once, it's cost-free to inline.
1090 return false;
1091 }
1092 if (candidateTotalCost[&fnDecl] <= this->settings().fInlineThreshold) {
1093 // We won't exceed the inline threshold by inlining this.
1094 return false;
1095 }
1096 // Inlining this function will add too many IRNodes.
1097 return true;
1098 }),
1099 candidates.end());
John Stiles2d7973a2020-10-02 15:01:03 -04001100}
1101
Brian Osman0006ad02020-11-18 15:38:39 -05001102bool Inliner::analyze(const std::vector<std::unique_ptr<ProgramElement>>& elements,
John Stiles78047582020-12-16 16:17:41 -05001103 std::shared_ptr<SymbolTable> symbols,
Brian Osman0006ad02020-11-18 15:38:39 -05001104 ProgramUsage* usage) {
John Stilesd34d56e2020-10-12 12:04:47 -04001105 // A threshold of zero indicates that the inliner is completely disabled, so we can just return.
John Stilesd1204642021-02-17 16:30:02 -05001106 if (this->settings().fInlineThreshold <= 0) {
John Stilesd34d56e2020-10-12 12:04:47 -04001107 return false;
1108 }
1109
John Stiles031a7672020-11-13 16:13:18 -05001110 // Enforce a limit on inlining to avoid pathological cases. (inliner/ExponentialGrowth.sksl)
1111 if (fInlinedStatementCounter >= kInlinedStatementLimit) {
1112 return false;
1113 }
1114
John Stiles2d7973a2020-10-02 15:01:03 -04001115 InlineCandidateList candidateList;
John Stiles9b9415e2020-11-23 14:48:06 -05001116 this->buildCandidateList(elements, symbols, usage, &candidateList);
John Stiles2d7973a2020-10-02 15:01:03 -04001117
John Stiles915a38c2020-09-14 09:38:13 -04001118 // Inline the candidates where we've determined that it's safe to do so.
John Stiles708faba2021-03-19 09:43:23 -04001119 using StatementRemappingTable = std::unordered_map<std::unique_ptr<Statement>*,
1120 std::unique_ptr<Statement>*>;
1121 StatementRemappingTable statementRemappingTable;
1122
John Stiles915a38c2020-09-14 09:38:13 -04001123 bool madeChanges = false;
John Stiles2d7973a2020-10-02 15:01:03 -04001124 for (const InlineCandidate& candidate : candidateList.fCandidates) {
John Stiles915a38c2020-09-14 09:38:13 -04001125 FunctionCall& funcCall = (*candidate.fCandidateExpr)->as<FunctionCall>();
John Stiles915a38c2020-09-14 09:38:13 -04001126
John Stiles915a38c2020-09-14 09:38:13 -04001127 // Convert the function call to its inlined equivalent.
John Stiles30fce9c2021-03-18 09:24:06 -04001128 InlinedCall inlinedCall = this->inlineCall(&funcCall, candidate.fSymbols, *usage,
Ethan Nicholas0a5d0962020-10-14 13:33:18 -04001129 &candidate.fEnclosingFunction->declaration());
John Stiles915a38c2020-09-14 09:38:13 -04001130
John Stiles0c2d14a2021-03-01 10:08:08 -05001131 // Stop if an error was detected during the inlining process.
1132 if (!inlinedCall.fInlinedBody && !inlinedCall.fReplacementExpr) {
1133 break;
John Stiles915a38c2020-09-14 09:38:13 -04001134 }
1135
John Stiles0c2d14a2021-03-01 10:08:08 -05001136 // Ensure that the inlined body has a scope if it needs one.
1137 this->ensureScopedBlocks(inlinedCall.fInlinedBody.get(), candidate.fParentStmt->get());
1138
1139 // Add references within the inlined body
1140 usage->add(inlinedCall.fInlinedBody.get());
1141
John Stiles708faba2021-03-19 09:43:23 -04001142 // Look up the enclosing statement; remap it if necessary.
1143 std::unique_ptr<Statement>* enclosingStmt = candidate.fEnclosingStmt;
1144 for (;;) {
1145 auto iter = statementRemappingTable.find(enclosingStmt);
1146 if (iter == statementRemappingTable.end()) {
1147 break;
1148 }
1149 enclosingStmt = iter->second;
1150 }
1151
John Stiles0c2d14a2021-03-01 10:08:08 -05001152 // Move the enclosing statement to the end of the unscoped Block containing the inlined
1153 // function, then replace the enclosing statement with that Block.
1154 // Before:
1155 // fInlinedBody = Block{ stmt1, stmt2, stmt3 }
1156 // fEnclosingStmt = stmt4
1157 // After:
1158 // fInlinedBody = null
1159 // fEnclosingStmt = Block{ stmt1, stmt2, stmt3, stmt4 }
John Stiles708faba2021-03-19 09:43:23 -04001160 inlinedCall.fInlinedBody->children().push_back(std::move(*enclosingStmt));
1161 *enclosingStmt = std::move(inlinedCall.fInlinedBody);
John Stiles0c2d14a2021-03-01 10:08:08 -05001162
John Stiles915a38c2020-09-14 09:38:13 -04001163 // Replace the candidate function call with our replacement expression.
Brian Osman010ce6a2020-10-19 16:34:10 -04001164 usage->replace(candidate.fCandidateExpr->get(), inlinedCall.fReplacementExpr.get());
John Stiles915a38c2020-09-14 09:38:13 -04001165 *candidate.fCandidateExpr = std::move(inlinedCall.fReplacementExpr);
1166 madeChanges = true;
1167
John Stiles708faba2021-03-19 09:43:23 -04001168 // If anything else pointed at our enclosing statement, it's now pointing at a Block
1169 // containing many other statements as well. Maintain a fix-up table to account for this.
1170 statementRemappingTable[enclosingStmt] = &(*enclosingStmt)->as<Block>().children().back();
1171
John Stiles031a7672020-11-13 16:13:18 -05001172 // Stop inlining if we've reached our hard cap on new statements.
1173 if (fInlinedStatementCounter >= kInlinedStatementLimit) {
1174 break;
1175 }
1176
John Stiles915a38c2020-09-14 09:38:13 -04001177 // Note that nothing was destroyed except for the FunctionCall. All other nodes should
1178 // remain valid.
1179 }
1180
1181 return madeChanges;
John Stiles93442622020-09-11 12:11:27 -04001182}
1183
John Stiles44e96be2020-08-31 13:16:04 -04001184} // namespace SkSL