blob: 1ec8742b4a4bcc2f7e963ac79098447ea4e49e69 [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 Stiles5abb9e12021-04-06 13:47:19 -040022#include "src/sksl/ir/SkSLConstructorMatrixResize.h"
John Stilesfd7252f2021-04-04 22:24:40 -040023#include "src/sksl/ir/SkSLConstructorScalarCast.h"
John Stiles2938eea2021-04-01 18:58:25 -040024#include "src/sksl/ir/SkSLConstructorSplat.h"
John Stilesb14a8192021-04-05 11:40:46 -040025#include "src/sksl/ir/SkSLConstructorVectorCast.h"
John Stiles44e96be2020-08-31 13:16:04 -040026#include "src/sksl/ir/SkSLContinueStatement.h"
27#include "src/sksl/ir/SkSLDiscardStatement.h"
28#include "src/sksl/ir/SkSLDoStatement.h"
29#include "src/sksl/ir/SkSLEnum.h"
30#include "src/sksl/ir/SkSLExpressionStatement.h"
31#include "src/sksl/ir/SkSLExternalFunctionCall.h"
Brian Osmanbe0b3b72021-01-06 14:27:35 -050032#include "src/sksl/ir/SkSLExternalFunctionReference.h"
John Stiles44e96be2020-08-31 13:16:04 -040033#include "src/sksl/ir/SkSLField.h"
34#include "src/sksl/ir/SkSLFieldAccess.h"
35#include "src/sksl/ir/SkSLFloatLiteral.h"
36#include "src/sksl/ir/SkSLForStatement.h"
37#include "src/sksl/ir/SkSLFunctionCall.h"
38#include "src/sksl/ir/SkSLFunctionDeclaration.h"
39#include "src/sksl/ir/SkSLFunctionDefinition.h"
40#include "src/sksl/ir/SkSLFunctionReference.h"
41#include "src/sksl/ir/SkSLIfStatement.h"
42#include "src/sksl/ir/SkSLIndexExpression.h"
John Stiles98c1f822020-09-09 14:18:53 -040043#include "src/sksl/ir/SkSLInlineMarker.h"
John Stiles44e96be2020-08-31 13:16:04 -040044#include "src/sksl/ir/SkSLIntLiteral.h"
45#include "src/sksl/ir/SkSLInterfaceBlock.h"
John Stiles44e96be2020-08-31 13:16:04 -040046#include "src/sksl/ir/SkSLNop.h"
John Stiles44e96be2020-08-31 13:16:04 -040047#include "src/sksl/ir/SkSLPostfixExpression.h"
48#include "src/sksl/ir/SkSLPrefixExpression.h"
49#include "src/sksl/ir/SkSLReturnStatement.h"
50#include "src/sksl/ir/SkSLSetting.h"
51#include "src/sksl/ir/SkSLSwitchCase.h"
52#include "src/sksl/ir/SkSLSwitchStatement.h"
53#include "src/sksl/ir/SkSLSwizzle.h"
54#include "src/sksl/ir/SkSLTernaryExpression.h"
55#include "src/sksl/ir/SkSLUnresolvedFunction.h"
56#include "src/sksl/ir/SkSLVarDeclarations.h"
John Stiles44e96be2020-08-31 13:16:04 -040057#include "src/sksl/ir/SkSLVariable.h"
58#include "src/sksl/ir/SkSLVariableReference.h"
John Stiles44e96be2020-08-31 13:16:04 -040059
60namespace SkSL {
61namespace {
62
John Stiles031a7672020-11-13 16:13:18 -050063static constexpr int kInlinedStatementLimit = 2500;
64
John Stiles44e96be2020-08-31 13:16:04 -040065static int count_returns_at_end_of_control_flow(const FunctionDefinition& funcDef) {
66 class CountReturnsAtEndOfControlFlow : public ProgramVisitor {
67 public:
68 CountReturnsAtEndOfControlFlow(const FunctionDefinition& funcDef) {
69 this->visitProgramElement(funcDef);
70 }
71
John Stiles5b408a32021-03-17 09:53:32 -040072 bool visitExpression(const Expression& expr) override {
73 // Do not recurse into expressions.
74 return false;
75 }
76
John Stiles44e96be2020-08-31 13:16:04 -040077 bool visitStatement(const Statement& stmt) override {
Ethan Nicholase6592142020-09-08 10:22:09 -040078 switch (stmt.kind()) {
79 case Statement::Kind::kBlock: {
John Stiles44e96be2020-08-31 13:16:04 -040080 // Check only the last statement of a block.
Ethan Nicholas7bd60432020-09-25 14:31:59 -040081 const auto& block = stmt.as<Block>();
82 return block.children().size() &&
83 this->visitStatement(*block.children().back());
John Stiles44e96be2020-08-31 13:16:04 -040084 }
Ethan Nicholase6592142020-09-08 10:22:09 -040085 case Statement::Kind::kSwitch:
Ethan Nicholase6592142020-09-08 10:22:09 -040086 case Statement::Kind::kDo:
87 case Statement::Kind::kFor:
John Stiles44e96be2020-08-31 13:16:04 -040088 // Don't introspect switches or loop structures at all.
89 return false;
90
Ethan Nicholase6592142020-09-08 10:22:09 -040091 case Statement::Kind::kReturn:
John Stiles44e96be2020-08-31 13:16:04 -040092 ++fNumReturns;
93 [[fallthrough]];
94
95 default:
John Stiles93442622020-09-11 12:11:27 -040096 return INHERITED::visitStatement(stmt);
John Stiles44e96be2020-08-31 13:16:04 -040097 }
98 }
99
100 int fNumReturns = 0;
101 using INHERITED = ProgramVisitor;
102 };
103
104 return CountReturnsAtEndOfControlFlow{funcDef}.fNumReturns;
105}
106
John Stiles991b09d2020-09-10 13:33:40 -0400107static bool contains_recursive_call(const FunctionDeclaration& funcDecl) {
108 class ContainsRecursiveCall : public ProgramVisitor {
109 public:
110 bool visit(const FunctionDeclaration& funcDecl) {
111 fFuncDecl = &funcDecl;
Ethan Nicholased84b732020-10-08 11:45:44 -0400112 return funcDecl.definition() ? this->visitProgramElement(*funcDecl.definition())
113 : false;
John Stiles991b09d2020-09-10 13:33:40 -0400114 }
115
116 bool visitExpression(const Expression& expr) override {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400117 if (expr.is<FunctionCall>() && expr.as<FunctionCall>().function().matches(*fFuncDecl)) {
John Stiles991b09d2020-09-10 13:33:40 -0400118 return true;
119 }
120 return INHERITED::visitExpression(expr);
121 }
122
123 bool visitStatement(const Statement& stmt) override {
Ethan Nicholasceb62142020-10-09 16:51:18 -0400124 if (stmt.is<InlineMarker>() &&
125 stmt.as<InlineMarker>().function().matches(*fFuncDecl)) {
John Stiles991b09d2020-09-10 13:33:40 -0400126 return true;
127 }
128 return INHERITED::visitStatement(stmt);
129 }
130
131 const FunctionDeclaration* fFuncDecl;
132 using INHERITED = ProgramVisitor;
133 };
134
135 return ContainsRecursiveCall{}.visit(funcDecl);
136}
137
John Stiles6d696082020-10-01 10:18:54 -0400138static std::unique_ptr<Statement>* find_parent_statement(
139 const std::vector<std::unique_ptr<Statement>*>& stmtStack) {
John Stiles915a38c2020-09-14 09:38:13 -0400140 SkASSERT(!stmtStack.empty());
141
142 // Walk the statement stack from back to front, ignoring the last element (which is the
143 // enclosing statement).
144 auto iter = stmtStack.rbegin();
145 ++iter;
146
147 // Anything counts as a parent statement other than a scopeless Block.
148 for (; iter != stmtStack.rend(); ++iter) {
John Stiles6d696082020-10-01 10:18:54 -0400149 std::unique_ptr<Statement>* stmt = *iter;
150 if (!(*stmt)->is<Block>() || (*stmt)->as<Block>().isScope()) {
John Stiles915a38c2020-09-14 09:38:13 -0400151 return stmt;
152 }
153 }
154
155 // There wasn't any parent statement to be found.
156 return nullptr;
157}
158
John Stilese41b4ee2020-09-28 12:28:16 -0400159std::unique_ptr<Expression> clone_with_ref_kind(const Expression& expr,
160 VariableReference::RefKind refKind) {
161 std::unique_ptr<Expression> clone = expr.clone();
John Stiles47c0a742021-02-09 09:30:35 -0500162 Analysis::UpdateRefKind(clone.get(), refKind);
John Stilese41b4ee2020-09-28 12:28:16 -0400163 return clone;
164}
165
John Stiles77702f12020-12-17 14:38:56 -0500166class CountReturnsWithLimit : public ProgramVisitor {
167public:
168 CountReturnsWithLimit(const FunctionDefinition& funcDef, int limit) : fLimit(limit) {
169 this->visitProgramElement(funcDef);
170 }
171
John Stiles5b408a32021-03-17 09:53:32 -0400172 bool visitExpression(const Expression& expr) override {
173 // Do not recurse into expressions.
174 return false;
175 }
176
John Stiles77702f12020-12-17 14:38:56 -0500177 bool visitStatement(const Statement& stmt) override {
178 switch (stmt.kind()) {
179 case Statement::Kind::kReturn: {
180 ++fNumReturns;
181 fDeepestReturn = std::max(fDeepestReturn, fScopedBlockDepth);
182 return (fNumReturns >= fLimit) || INHERITED::visitStatement(stmt);
183 }
John Stilesc5ff4862020-12-22 13:47:05 -0500184 case Statement::Kind::kVarDeclaration: {
185 if (fScopedBlockDepth > 1) {
186 fVariablesInBlocks = true;
187 }
188 return INHERITED::visitStatement(stmt);
189 }
John Stiles77702f12020-12-17 14:38:56 -0500190 case Statement::Kind::kBlock: {
191 int depthIncrement = stmt.as<Block>().isScope() ? 1 : 0;
192 fScopedBlockDepth += depthIncrement;
193 bool result = INHERITED::visitStatement(stmt);
194 fScopedBlockDepth -= depthIncrement;
John Stilesc5ff4862020-12-22 13:47:05 -0500195 if (fNumReturns == 0 && fScopedBlockDepth <= 1) {
196 // If closing this block puts us back at the top level, and we haven't
197 // encountered any return statements yet, any vardecls we may have encountered
198 // up until this point can be ignored. They are out of scope now, and they were
199 // never used in a return statement.
200 fVariablesInBlocks = false;
201 }
John Stiles77702f12020-12-17 14:38:56 -0500202 return result;
203 }
204 default:
205 return INHERITED::visitStatement(stmt);
206 }
207 }
208
209 int fNumReturns = 0;
210 int fDeepestReturn = 0;
211 int fLimit = 0;
212 int fScopedBlockDepth = 0;
John Stilesc5ff4862020-12-22 13:47:05 -0500213 bool fVariablesInBlocks = false;
John Stiles77702f12020-12-17 14:38:56 -0500214 using INHERITED = ProgramVisitor;
215};
216
John Stiles44e96be2020-08-31 13:16:04 -0400217} // namespace
218
John Stiles77702f12020-12-17 14:38:56 -0500219Inliner::ReturnComplexity Inliner::GetReturnComplexity(const FunctionDefinition& funcDef) {
220 int returnsAtEndOfControlFlow = count_returns_at_end_of_control_flow(funcDef);
221 CountReturnsWithLimit counter{funcDef, returnsAtEndOfControlFlow + 1};
John Stiles77702f12020-12-17 14:38:56 -0500222 if (counter.fNumReturns > returnsAtEndOfControlFlow) {
223 return ReturnComplexity::kEarlyReturns;
224 }
John Stilesc5ff4862020-12-22 13:47:05 -0500225 if (counter.fNumReturns > 1) {
John Stiles77702f12020-12-17 14:38:56 -0500226 return ReturnComplexity::kScopedReturns;
227 }
John Stilesc5ff4862020-12-22 13:47:05 -0500228 if (counter.fVariablesInBlocks && counter.fDeepestReturn > 1) {
229 return ReturnComplexity::kScopedReturns;
230 }
John Stiles8937cd42021-03-17 19:32:59 +0000231 return ReturnComplexity::kSingleSafeReturn;
John Stiles77702f12020-12-17 14:38:56 -0500232}
233
John Stilesb61ee902020-09-21 12:26:59 -0400234void Inliner::ensureScopedBlocks(Statement* inlinedBody, Statement* parentStmt) {
235 // No changes necessary if this statement isn't actually a block.
236 if (!inlinedBody || !inlinedBody->is<Block>()) {
237 return;
238 }
239
240 // No changes necessary if the parent statement doesn't require a scope.
241 if (!parentStmt || !(parentStmt->is<IfStatement>() || parentStmt->is<ForStatement>() ||
Brian Osmand6f23382020-12-15 17:08:59 -0500242 parentStmt->is<DoStatement>())) {
John Stilesb61ee902020-09-21 12:26:59 -0400243 return;
244 }
245
246 Block& block = inlinedBody->as<Block>();
247
248 // The inliner will create inlined function bodies as a Block containing multiple statements,
249 // but no scope. Normally, this is fine, but if this block is used as the statement for a
250 // do/for/if/while, this isn't actually possible to represent textually; a scope must be added
251 // for the generated code to match the intent. In the case of Blocks nested inside other Blocks,
252 // we add the scope to the outermost block if needed. Zero-statement blocks have similar
253 // issues--if we don't represent the Block textually somehow, we run the risk of accidentally
254 // absorbing the following statement into our loop--so we also add a scope to these.
255 for (Block* nestedBlock = &block;; ) {
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400256 if (nestedBlock->isScope()) {
John Stilesb61ee902020-09-21 12:26:59 -0400257 // We found an explicit scope; all is well.
258 return;
259 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400260 if (nestedBlock->children().size() != 1) {
John Stilesb61ee902020-09-21 12:26:59 -0400261 // We found a block with multiple (or zero) statements, but no scope? Let's add a scope
262 // to the outermost block.
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400263 block.setIsScope(true);
John Stilesb61ee902020-09-21 12:26:59 -0400264 return;
265 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400266 if (!nestedBlock->children()[0]->is<Block>()) {
John Stilesb61ee902020-09-21 12:26:59 -0400267 // This block has exactly one thing inside, and it's not another block. No need to scope
268 // it.
269 return;
270 }
271 // We have to go deeper.
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400272 nestedBlock = &nestedBlock->children()[0]->as<Block>();
John Stilesb61ee902020-09-21 12:26:59 -0400273 }
274}
275
John Stilesd1204642021-02-17 16:30:02 -0500276void Inliner::reset(ModifiersPool* modifiers) {
Ethan Nicholas041fd0a2020-10-07 16:42:04 -0400277 fModifiers = modifiers;
Ethan Nicholas6f4eee22021-01-11 12:37:42 -0500278 fMangler.reset();
John Stiles031a7672020-11-13 16:13:18 -0500279 fInlinedStatementCounter = 0;
John Stiles44e96be2020-08-31 13:16:04 -0400280}
281
282std::unique_ptr<Expression> Inliner::inlineExpression(int offset,
283 VariableRewriteMap* varMap,
John Stilesd7cc0932020-11-30 12:24:27 -0500284 SymbolTable* symbolTableForExpression,
John Stiles44e96be2020-08-31 13:16:04 -0400285 const Expression& expression) {
286 auto expr = [&](const std::unique_ptr<Expression>& e) -> std::unique_ptr<Expression> {
287 if (e) {
John Stilesd7cc0932020-11-30 12:24:27 -0500288 return this->inlineExpression(offset, varMap, symbolTableForExpression, *e);
John Stiles44e96be2020-08-31 13:16:04 -0400289 }
290 return nullptr;
291 };
John Stiles8e3b6be2020-10-13 11:14:08 -0400292 auto argList = [&](const ExpressionArray& originalArgs) -> ExpressionArray {
293 ExpressionArray args;
John Stilesf4bda742020-10-14 16:57:41 -0400294 args.reserve_back(originalArgs.size());
John Stiles44e96be2020-08-31 13:16:04 -0400295 for (const std::unique_ptr<Expression>& arg : originalArgs) {
296 args.push_back(expr(arg));
297 }
298 return args;
299 };
300
Ethan Nicholase6592142020-09-08 10:22:09 -0400301 switch (expression.kind()) {
302 case Expression::Kind::kBinary: {
John Stiles6a1a98c2021-01-14 18:35:34 -0500303 const BinaryExpression& binaryExpr = expression.as<BinaryExpression>();
John Stilese2aec432021-03-01 09:27:48 -0500304 return BinaryExpression::Make(*fContext,
305 expr(binaryExpr.left()),
306 binaryExpr.getOperator(),
307 expr(binaryExpr.right()));
John Stiles44e96be2020-08-31 13:16:04 -0400308 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400309 case Expression::Kind::kBoolLiteral:
310 case Expression::Kind::kIntLiteral:
311 case Expression::Kind::kFloatLiteral:
John Stiles44e96be2020-08-31 13:16:04 -0400312 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400313 case Expression::Kind::kConstructor: {
John Stiles44e96be2020-08-31 13:16:04 -0400314 const Constructor& constructor = expression.as<Constructor>();
John Stiles23521a82021-03-02 17:02:51 -0500315 auto inlinedCtor = Constructor::Convert(
316 *fContext, offset, *constructor.type().clone(symbolTableForExpression),
317 argList(constructor.arguments()));
318 SkASSERT(inlinedCtor);
319 return inlinedCtor;
John Stiles44e96be2020-08-31 13:16:04 -0400320 }
John Stiles7384b372021-04-01 13:48:15 -0400321 case Expression::Kind::kConstructorArray: {
322 const ConstructorArray& ctor = expression.as<ConstructorArray>();
323 return ConstructorArray::Make(*fContext, offset,
324 *ctor.type().clone(symbolTableForExpression),
325 argList(ctor.arguments()));
326 }
John Stilese1182782021-03-30 22:09:37 -0400327 case Expression::Kind::kConstructorDiagonalMatrix: {
328 const ConstructorDiagonalMatrix& ctor = expression.as<ConstructorDiagonalMatrix>();
329 return ConstructorDiagonalMatrix::Make(*fContext, offset,
330 *ctor.type().clone(symbolTableForExpression),
331 expr(ctor.argument()));
332 }
John Stiles5abb9e12021-04-06 13:47:19 -0400333 case Expression::Kind::kConstructorMatrixResize: {
334 const ConstructorMatrixResize& ctor = expression.as<ConstructorMatrixResize>();
335 return ConstructorMatrixResize::Make(*fContext, offset,
336 *ctor.type().clone(symbolTableForExpression),
337 expr(ctor.argument()));
338 }
John Stilesfd7252f2021-04-04 22:24:40 -0400339 case Expression::Kind::kConstructorScalarCast: {
340 const ConstructorScalarCast& ctor = expression.as<ConstructorScalarCast>();
341 return ConstructorScalarCast::Make(*fContext, offset,
342 *ctor.type().clone(symbolTableForExpression),
343 expr(ctor.argument()));
344 }
John Stiles2938eea2021-04-01 18:58:25 -0400345 case Expression::Kind::kConstructorSplat: {
346 const ConstructorSplat& ctor = expression.as<ConstructorSplat>();
347 return ConstructorSplat::Make(*fContext, offset,
348 *ctor.type().clone(symbolTableForExpression),
349 expr(ctor.argument()));
350 }
John Stilesb14a8192021-04-05 11:40:46 -0400351 case Expression::Kind::kConstructorVectorCast: {
352 const ConstructorVectorCast& ctor = expression.as<ConstructorVectorCast>();
353 return ConstructorVectorCast::Make(*fContext, offset,
354 *ctor.type().clone(symbolTableForExpression),
355 expr(ctor.argument()));
356 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400357 case Expression::Kind::kExternalFunctionCall: {
John Stiles44e96be2020-08-31 13:16:04 -0400358 const ExternalFunctionCall& externalCall = expression.as<ExternalFunctionCall>();
Ethan Nicholas444ccc62020-10-09 10:16:22 -0400359 return std::make_unique<ExternalFunctionCall>(offset, &externalCall.function(),
Ethan Nicholas6e86ec92020-09-30 14:29:56 -0400360 argList(externalCall.arguments()));
John Stiles44e96be2020-08-31 13:16:04 -0400361 }
Brian Osmanbe0b3b72021-01-06 14:27:35 -0500362 case Expression::Kind::kExternalFunctionReference:
John Stiles44e96be2020-08-31 13:16:04 -0400363 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400364 case Expression::Kind::kFieldAccess: {
John Stiles44e96be2020-08-31 13:16:04 -0400365 const FieldAccess& f = expression.as<FieldAccess>();
John Stiles06d600f2021-03-08 09:18:21 -0500366 return FieldAccess::Make(*fContext, expr(f.base()), f.fieldIndex(), f.ownerKind());
John Stiles44e96be2020-08-31 13:16:04 -0400367 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400368 case Expression::Kind::kFunctionCall: {
John Stiles44e96be2020-08-31 13:16:04 -0400369 const FunctionCall& funcCall = expression.as<FunctionCall>();
John Stilescd7ba502021-03-19 10:54:59 -0400370 return FunctionCall::Make(*fContext,
371 offset,
372 funcCall.type().clone(symbolTableForExpression),
373 funcCall.function(),
374 argList(funcCall.arguments()));
John Stiles44e96be2020-08-31 13:16:04 -0400375 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400376 case Expression::Kind::kFunctionReference:
Brian Osman2b3b35f2020-09-08 09:17:36 -0400377 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400378 case Expression::Kind::kIndex: {
John Stiles44e96be2020-08-31 13:16:04 -0400379 const IndexExpression& idx = expression.as<IndexExpression>();
John Stiles51d33982021-03-08 09:18:07 -0500380 return IndexExpression::Make(*fContext, expr(idx.base()), expr(idx.index()));
John Stiles44e96be2020-08-31 13:16:04 -0400381 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400382 case Expression::Kind::kPrefix: {
John Stiles44e96be2020-08-31 13:16:04 -0400383 const PrefixExpression& p = expression.as<PrefixExpression>();
John Stilesb0eb20f2021-02-26 15:29:33 -0500384 return PrefixExpression::Make(*fContext, p.getOperator(), expr(p.operand()));
John Stiles44e96be2020-08-31 13:16:04 -0400385 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400386 case Expression::Kind::kPostfix: {
John Stiles44e96be2020-08-31 13:16:04 -0400387 const PostfixExpression& p = expression.as<PostfixExpression>();
John Stiles52d3b012021-02-26 15:56:48 -0500388 return PostfixExpression::Make(*fContext, expr(p.operand()), p.getOperator());
John Stiles44e96be2020-08-31 13:16:04 -0400389 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400390 case Expression::Kind::kSetting:
John Stiles44e96be2020-08-31 13:16:04 -0400391 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400392 case Expression::Kind::kSwizzle: {
John Stiles44e96be2020-08-31 13:16:04 -0400393 const Swizzle& s = expression.as<Swizzle>();
John Stiles6e88e042021-02-19 14:09:38 -0500394 return Swizzle::Make(*fContext, expr(s.base()), s.components());
John Stiles44e96be2020-08-31 13:16:04 -0400395 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400396 case Expression::Kind::kTernary: {
John Stiles44e96be2020-08-31 13:16:04 -0400397 const TernaryExpression& t = expression.as<TernaryExpression>();
John Stiles90518f72021-02-26 20:44:54 -0500398 return TernaryExpression::Make(*fContext, expr(t.test()),
399 expr(t.ifTrue()), expr(t.ifFalse()));
John Stiles44e96be2020-08-31 13:16:04 -0400400 }
Brian Osman83ba9302020-09-11 13:33:46 -0400401 case Expression::Kind::kTypeReference:
402 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400403 case Expression::Kind::kVariableReference: {
John Stiles44e96be2020-08-31 13:16:04 -0400404 const VariableReference& v = expression.as<VariableReference>();
Ethan Nicholas78686922020-10-08 06:46:27 -0400405 auto varMapIter = varMap->find(v.variable());
John Stilese41b4ee2020-09-28 12:28:16 -0400406 if (varMapIter != varMap->end()) {
Ethan Nicholas78686922020-10-08 06:46:27 -0400407 return clone_with_ref_kind(*varMapIter->second, v.refKind());
John Stiles44e96be2020-08-31 13:16:04 -0400408 }
409 return v.clone();
410 }
411 default:
412 SkASSERT(false);
413 return nullptr;
414 }
415}
416
417std::unique_ptr<Statement> Inliner::inlineStatement(int offset,
418 VariableRewriteMap* varMap,
419 SymbolTable* symbolTableForStatement,
John Stiles77702f12020-12-17 14:38:56 -0500420 std::unique_ptr<Expression>* resultExpr,
421 ReturnComplexity returnComplexity,
Brian Osman3887a012020-09-30 13:22:27 -0400422 const Statement& statement,
423 bool isBuiltinCode) {
John Stiles44e96be2020-08-31 13:16:04 -0400424 auto stmt = [&](const std::unique_ptr<Statement>& s) -> std::unique_ptr<Statement> {
425 if (s) {
John Stilesa5f3c312020-09-22 12:05:16 -0400426 return this->inlineStatement(offset, varMap, symbolTableForStatement, resultExpr,
John Stiles77702f12020-12-17 14:38:56 -0500427 returnComplexity, *s, isBuiltinCode);
John Stiles44e96be2020-08-31 13:16:04 -0400428 }
429 return nullptr;
430 };
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400431 auto blockStmts = [&](const Block& block) {
John Stiles8f2a0cf2020-10-13 12:48:21 -0400432 StatementArray result;
John Stilesf4bda742020-10-14 16:57:41 -0400433 result.reserve_back(block.children().size());
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400434 for (const std::unique_ptr<Statement>& child : block.children()) {
435 result.push_back(stmt(child));
436 }
437 return result;
438 };
John Stiles44e96be2020-08-31 13:16:04 -0400439 auto expr = [&](const std::unique_ptr<Expression>& e) -> std::unique_ptr<Expression> {
440 if (e) {
John Stilesd7cc0932020-11-30 12:24:27 -0500441 return this->inlineExpression(offset, varMap, symbolTableForStatement, *e);
John Stiles44e96be2020-08-31 13:16:04 -0400442 }
443 return nullptr;
444 };
John Stiles031a7672020-11-13 16:13:18 -0500445
446 ++fInlinedStatementCounter;
447
Ethan Nicholase6592142020-09-08 10:22:09 -0400448 switch (statement.kind()) {
449 case Statement::Kind::kBlock: {
John Stiles44e96be2020-08-31 13:16:04 -0400450 const Block& b = statement.as<Block>();
John Stilesbf16b6c2021-03-12 19:24:31 -0500451 return Block::Make(offset, blockStmts(b),
452 SymbolTable::WrapIfBuiltin(b.symbolTable()),
453 b.isScope());
John Stiles44e96be2020-08-31 13:16:04 -0400454 }
455
Ethan Nicholase6592142020-09-08 10:22:09 -0400456 case Statement::Kind::kBreak:
457 case Statement::Kind::kContinue:
458 case Statement::Kind::kDiscard:
John Stiles44e96be2020-08-31 13:16:04 -0400459 return statement.clone();
460
Ethan Nicholase6592142020-09-08 10:22:09 -0400461 case Statement::Kind::kDo: {
John Stiles44e96be2020-08-31 13:16:04 -0400462 const DoStatement& d = statement.as<DoStatement>();
John Stilesea5822e2021-02-26 11:18:20 -0500463 return DoStatement::Make(*fContext, stmt(d.statement()), expr(d.test()));
John Stiles44e96be2020-08-31 13:16:04 -0400464 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400465 case Statement::Kind::kExpression: {
John Stiles44e96be2020-08-31 13:16:04 -0400466 const ExpressionStatement& e = statement.as<ExpressionStatement>();
John Stiles3e5871c2021-02-25 20:52:03 -0500467 return ExpressionStatement::Make(*fContext, expr(e.expression()));
John Stiles44e96be2020-08-31 13:16:04 -0400468 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400469 case Statement::Kind::kFor: {
John Stiles44e96be2020-08-31 13:16:04 -0400470 const ForStatement& f = statement.as<ForStatement>();
471 // need to ensure initializer is evaluated first so that we've already remapped its
472 // declarations by the time we evaluate test & next
Ethan Nicholas0d31ed52020-10-05 14:47:09 -0400473 std::unique_ptr<Statement> initializer = stmt(f.initializer());
John Stilesb321a072021-02-25 16:24:19 -0500474 return ForStatement::Make(*fContext, offset, std::move(initializer), expr(f.test()),
475 expr(f.next()), stmt(f.statement()),
476 SymbolTable::WrapIfBuiltin(f.symbols()));
John Stiles44e96be2020-08-31 13:16:04 -0400477 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400478 case Statement::Kind::kIf: {
John Stiles44e96be2020-08-31 13:16:04 -0400479 const IfStatement& i = statement.as<IfStatement>();
John Stilescf3059e2021-02-25 14:27:02 -0500480 return IfStatement::Make(*fContext, offset, i.isStatic(), expr(i.test()),
481 stmt(i.ifTrue()), stmt(i.ifFalse()));
John Stiles44e96be2020-08-31 13:16:04 -0400482 }
John Stiles98c1f822020-09-09 14:18:53 -0400483 case Statement::Kind::kInlineMarker:
Ethan Nicholase6592142020-09-08 10:22:09 -0400484 case Statement::Kind::kNop:
John Stiles44e96be2020-08-31 13:16:04 -0400485 return statement.clone();
John Stilesea5822e2021-02-26 11:18:20 -0500486
Ethan Nicholase6592142020-09-08 10:22:09 -0400487 case Statement::Kind::kReturn: {
John Stiles44e96be2020-08-31 13:16:04 -0400488 const ReturnStatement& r = statement.as<ReturnStatement>();
John Stiles77702f12020-12-17 14:38:56 -0500489 if (!r.expression()) {
John Stilesdc208472021-03-17 10:58:16 -0400490 // This function doesn't return a value. We won't inline functions with early
491 // returns, so a return statement is a no-op and can be treated as such.
492 return Nop::Make();
John Stiles44e96be2020-08-31 13:16:04 -0400493 }
John Stiles77702f12020-12-17 14:38:56 -0500494
John Stilesc5ff4862020-12-22 13:47:05 -0500495 // If a function only contains a single return, and it doesn't reference variables from
496 // inside an Block's scope, we don't need to store the result in a variable at all. Just
497 // replace the function-call expression with the function's return expression.
John Stiles77702f12020-12-17 14:38:56 -0500498 SkASSERT(resultExpr);
John Stilesc5ff4862020-12-22 13:47:05 -0500499 if (returnComplexity <= ReturnComplexity::kSingleSafeReturn) {
John Stiles77702f12020-12-17 14:38:56 -0500500 *resultExpr = expr(r.expression());
John Stilesa0c04d62021-03-11 23:07:24 -0500501 return Nop::Make();
John Stiles77702f12020-12-17 14:38:56 -0500502 }
503
504 // For more complex functions, assign their result into a variable.
John Stiles511c5002021-02-25 11:17:02 -0500505 SkASSERT(*resultExpr);
John Stiles3e5871c2021-02-25 20:52:03 -0500506 auto assignment = ExpressionStatement::Make(
507 *fContext,
John Stilese2aec432021-03-01 09:27:48 -0500508 BinaryExpression::Make(
509 *fContext,
510 clone_with_ref_kind(**resultExpr, VariableRefKind::kWrite),
John Stiles77702f12020-12-17 14:38:56 -0500511 Token::Kind::TK_EQ,
John Stilese2aec432021-03-01 09:27:48 -0500512 expr(r.expression())));
John Stiles77702f12020-12-17 14:38:56 -0500513
John Stiles77702f12020-12-17 14:38:56 -0500514 // Functions without early returns aren't wrapped in a for loop and don't need to worry
515 // about breaking out of the control flow.
John Stiles3e5871c2021-02-25 20:52:03 -0500516 return assignment;
John Stiles44e96be2020-08-31 13:16:04 -0400517 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400518 case Statement::Kind::kSwitch: {
John Stiles44e96be2020-08-31 13:16:04 -0400519 const SwitchStatement& ss = statement.as<SwitchStatement>();
John Stilesb23a64b2021-03-11 08:27:59 -0500520 StatementArray cases;
521 cases.reserve_back(ss.cases().size());
522 for (const std::unique_ptr<Statement>& statement : ss.cases()) {
523 const SwitchCase& sc = statement->as<SwitchCase>();
524 cases.push_back(std::make_unique<SwitchCase>(offset, expr(sc.value()),
525 stmt(sc.statement())));
John Stiles44e96be2020-08-31 13:16:04 -0400526 }
John Stilese1d1b082021-02-23 13:44:36 -0500527 return SwitchStatement::Make(*fContext, offset, ss.isStatic(), expr(ss.value()),
528 std::move(cases), SymbolTable::WrapIfBuiltin(ss.symbols()));
John Stiles44e96be2020-08-31 13:16:04 -0400529 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400530 case Statement::Kind::kVarDeclaration: {
John Stiles44e96be2020-08-31 13:16:04 -0400531 const VarDeclaration& decl = statement.as<VarDeclaration>();
John Stiles35fee4c2020-12-16 18:25:14 +0000532 std::unique_ptr<Expression> initialValue = expr(decl.value());
John Stilesddcc8432021-01-15 15:32:32 -0500533 const Variable& variable = decl.var();
534
John Stiles35fee4c2020-12-16 18:25:14 +0000535 // We assign unique names to inlined variables--scopes hide most of the problems in this
536 // regard, but see `InlinerAvoidsVariableNameOverlap` for a counterexample where unique
537 // names are important.
John Stilesd51c9792021-03-18 11:40:14 -0400538 const String* name = symbolTableForStatement->takeOwnershipOfString(
539 fMangler.uniqueName(variable.name(), symbolTableForStatement));
Ethan Nicholas5b9b0db2021-01-21 13:12:01 -0500540 auto clonedVar = std::make_unique<Variable>(
541 offset,
542 &variable.modifiers(),
John Stilesd51c9792021-03-18 11:40:14 -0400543 name->c_str(),
Ethan Nicholas5b9b0db2021-01-21 13:12:01 -0500544 variable.type().clone(symbolTableForStatement),
545 isBuiltinCode,
546 variable.storage());
547 (*varMap)[&variable] = std::make_unique<VariableReference>(offset, clonedVar.get());
John Stilese67bd132021-03-19 18:39:25 -0400548 auto result = VarDeclaration::Make(*fContext,
549 clonedVar.get(),
550 decl.baseType().clone(symbolTableForStatement),
551 decl.arraySize(),
552 std::move(initialValue));
Ethan Nicholas5b9b0db2021-01-21 13:12:01 -0500553 symbolTableForStatement->takeOwnershipOfSymbol(std::move(clonedVar));
John Stilese67bd132021-03-19 18:39:25 -0400554 return result;
John Stiles44e96be2020-08-31 13:16:04 -0400555 }
John Stiles44e96be2020-08-31 13:16:04 -0400556 default:
557 SkASSERT(false);
558 return nullptr;
559 }
560}
561
John Stiles7b920442020-12-17 10:43:41 -0500562Inliner::InlineVariable Inliner::makeInlineVariable(const String& baseName,
563 const Type* type,
564 SymbolTable* symbolTable,
565 Modifiers modifiers,
566 bool isBuiltinCode,
567 std::unique_ptr<Expression>* initialValue) {
568 // $floatLiteral or $intLiteral aren't real types that we can use for scratch variables, so
569 // replace them if they ever appear here. If this happens, we likely forgot to coerce a type
570 // somewhere during compilation.
John Stiles14975272021-01-12 11:41:14 -0500571 if (type->isLiteral()) {
572 SkDEBUGFAIL("found a $literal type while inlining");
573 type = &type->scalarTypeForLiteral();
John Stiles7b920442020-12-17 10:43:41 -0500574 }
575
John Stilesbff24ab2021-03-17 13:20:10 -0400576 // Out parameters aren't supported.
577 SkASSERT(!(modifiers.fFlags & Modifiers::kOut_Flag));
578
John Stiles7b920442020-12-17 10:43:41 -0500579 // Provide our new variable with a unique name, and add it to our symbol table.
John Stilesd51c9792021-03-18 11:40:14 -0400580 const String* name =
581 symbolTable->takeOwnershipOfString(fMangler.uniqueName(baseName, symbolTable));
John Stiles7b920442020-12-17 10:43:41 -0500582
583 // Create our new variable and add it to the symbol table.
584 InlineVariable result;
Ethan Nicholas5b9b0db2021-01-21 13:12:01 -0500585 auto var = std::make_unique<Variable>(/*offset=*/-1,
586 fModifiers->addToPool(Modifiers()),
John Stilesd51c9792021-03-18 11:40:14 -0400587 name->c_str(),
Ethan Nicholas5b9b0db2021-01-21 13:12:01 -0500588 type,
589 isBuiltinCode,
590 Variable::Storage::kLocal);
John Stiles7b920442020-12-17 10:43:41 -0500591
John Stilesbff24ab2021-03-17 13:20:10 -0400592 // Create our variable declaration.
John Stilese67bd132021-03-19 18:39:25 -0400593 result.fVarDecl = VarDeclaration::Make(*fContext, var.get(), type, /*arraySize=*/0,
594 std::move(*initialValue));
Ethan Nicholas5b9b0db2021-01-21 13:12:01 -0500595 result.fVarSymbol = symbolTable->add(std::move(var));
John Stiles7b920442020-12-17 10:43:41 -0500596 return result;
597}
598
John Stiles6eadf132020-09-08 10:16:10 -0400599Inliner::InlinedCall Inliner::inlineCall(FunctionCall* call,
John Stiles78047582020-12-16 16:17:41 -0500600 std::shared_ptr<SymbolTable> symbolTable,
John Stiles30fce9c2021-03-18 09:24:06 -0400601 const ProgramUsage& usage,
Brian Osman3887a012020-09-30 13:22:27 -0400602 const FunctionDeclaration* caller) {
John Stiles44e96be2020-08-31 13:16:04 -0400603 // Inlining is more complicated here than in a typical compiler, because we have to have a
604 // high-level IR and can't just drop statements into the middle of an expression or even use
605 // gotos.
606 //
607 // Since we can't insert statements into an expression, we run the inline function as extra
608 // statements before the statement we're currently processing, relying on a lack of execution
609 // order guarantees. Since we can't use gotos (which are normally used to replace return
610 // statements), we wrap the whole function in a loop and use break statements to jump to the
611 // end.
John Stiles44e96be2020-08-31 13:16:04 -0400612 SkASSERT(fContext);
613 SkASSERT(call);
Ethan Nicholased84b732020-10-08 11:45:44 -0400614 SkASSERT(this->isSafeToInline(call->function().definition()));
John Stiles44e96be2020-08-31 13:16:04 -0400615
John Stiles8e3b6be2020-10-13 11:14:08 -0400616 ExpressionArray& arguments = call->arguments();
John Stiles6eadf132020-09-08 10:16:10 -0400617 const int offset = call->fOffset;
Ethan Nicholased84b732020-10-08 11:45:44 -0400618 const FunctionDefinition& function = *call->function().definition();
John Stiles28257db2021-03-17 15:18:09 -0400619 const Block& body = function.body()->as<Block>();
John Stiles77702f12020-12-17 14:38:56 -0500620 const ReturnComplexity returnComplexity = GetReturnComplexity(function);
John Stiles6eadf132020-09-08 10:16:10 -0400621
John Stiles28257db2021-03-17 15:18:09 -0400622 StatementArray inlineStatements;
623 int expectedStmtCount = 1 + // Inline marker
624 1 + // Result variable
625 arguments.size() + // Function argument temp-vars
626 body.children().size(); // Inlined code
John Stiles98c1f822020-09-09 14:18:53 -0400627
John Stiles28257db2021-03-17 15:18:09 -0400628 inlineStatements.reserve_back(expectedStmtCount);
629 inlineStatements.push_back(InlineMarker::Make(&call->function()));
John Stiles44e96be2020-08-31 13:16:04 -0400630
John Stilese41b4ee2020-09-28 12:28:16 -0400631 std::unique_ptr<Expression> resultExpr;
John Stiles511c5002021-02-25 11:17:02 -0500632 if (returnComplexity > ReturnComplexity::kSingleSafeReturn &&
John Stiles2558c462021-03-16 17:49:20 -0400633 !function.declaration().returnType().isVoid()) {
John Stiles511c5002021-02-25 11:17:02 -0500634 // Create a variable to hold the result in the extra statements. We don't need to do this
635 // for void-return functions, or in cases that are simple enough that we can just replace
636 // the function-call node with the result expression.
John Stiles44e96be2020-08-31 13:16:04 -0400637 std::unique_ptr<Expression> noInitialValue;
John Stiles7b920442020-12-17 10:43:41 -0500638 InlineVariable var = this->makeInlineVariable(function.declaration().name(),
639 &function.declaration().returnType(),
640 symbolTable.get(), Modifiers{},
641 caller->isBuiltin(), &noInitialValue);
John Stiles28257db2021-03-17 15:18:09 -0400642 inlineStatements.push_back(std::move(var.fVarDecl));
John Stiles7b920442020-12-17 10:43:41 -0500643 resultExpr = std::make_unique<VariableReference>(/*offset=*/-1, var.fVarSymbol);
John Stiles511c5002021-02-25 11:17:02 -0500644 }
John Stiles44e96be2020-08-31 13:16:04 -0400645
646 // Create variables in the extra statements to hold the arguments, and assign the arguments to
647 // them.
648 VariableRewriteMap varMap;
John Stilesbff24ab2021-03-17 13:20:10 -0400649 for (int i = 0; i < arguments.count(); ++i) {
John Stiles049f0df2021-03-19 09:39:44 -0400650 // If the parameter isn't written to within the inline function ...
John Stilesbff24ab2021-03-17 13:20:10 -0400651 const Variable* param = function.declaration().parameters()[i];
John Stiles049f0df2021-03-19 09:39:44 -0400652 const ProgramUsage::VariableCounts& paramUsage = usage.get(*param);
653 if (!paramUsage.fWrite) {
654 // ... and can be inlined trivially (e.g. a swizzle, or a constant array index),
655 // or any expression without side effects that is only accessed at most once...
656 if ((paramUsage.fRead > 1) ? Analysis::IsTrivialExpression(*arguments[i])
657 : !arguments[i]->hasSideEffects()) {
John Stilesf201af82020-09-29 16:57:55 -0400658 // ... we don't need to copy it at all! We can just use the existing expression.
659 varMap[param] = arguments[i]->clone();
John Stiles44e96be2020-08-31 13:16:04 -0400660 continue;
661 }
662 }
John Stiles7b920442020-12-17 10:43:41 -0500663 InlineVariable var = this->makeInlineVariable(param->name(), &arguments[i]->type(),
664 symbolTable.get(), param->modifiers(),
665 caller->isBuiltin(), &arguments[i]);
John Stiles28257db2021-03-17 15:18:09 -0400666 inlineStatements.push_back(std::move(var.fVarDecl));
John Stiles7b920442020-12-17 10:43:41 -0500667 varMap[param] = std::make_unique<VariableReference>(/*offset=*/-1, var.fVarSymbol);
John Stiles44e96be2020-08-31 13:16:04 -0400668 }
669
John Stiles7b920442020-12-17 10:43:41 -0500670 for (const std::unique_ptr<Statement>& stmt : body.children()) {
John Stiles28257db2021-03-17 15:18:09 -0400671 inlineStatements.push_back(this->inlineStatement(offset, &varMap, symbolTable.get(),
672 &resultExpr, returnComplexity, *stmt,
673 caller->isBuiltin()));
John Stiles44e96be2020-08-31 13:16:04 -0400674 }
675
John Stiles28257db2021-03-17 15:18:09 -0400676 SkASSERT(inlineStatements.count() <= expectedStmtCount);
677
John Stilesbf16b6c2021-03-12 19:24:31 -0500678 // Wrap all of the generated statements in a block. We need a real Block here, so we can't use
679 // MakeUnscoped. This is because we need to add another child statement to the Block later.
John Stiles28257db2021-03-17 15:18:09 -0400680 InlinedCall inlinedCall;
681 inlinedCall.fInlinedBody = Block::Make(offset, std::move(inlineStatements),
John Stilesbf16b6c2021-03-12 19:24:31 -0500682 /*symbols=*/nullptr, /*isScope=*/false);
683
John Stiles0c2d14a2021-03-01 10:08:08 -0500684 if (resultExpr) {
685 // Return our result expression as-is.
John Stilese41b4ee2020-09-28 12:28:16 -0400686 inlinedCall.fReplacementExpr = std::move(resultExpr);
John Stiles2558c462021-03-16 17:49:20 -0400687 } else if (function.declaration().returnType().isVoid()) {
John Stiles44e96be2020-08-31 13:16:04 -0400688 // It's a void function, so it doesn't actually result in anything, but we have to return
689 // something non-null as a standin.
John Stiles9ce80f72021-03-11 22:35:19 -0500690 inlinedCall.fReplacementExpr = BoolLiteral::Make(*fContext, offset, /*value=*/false);
John Stiles0c2d14a2021-03-01 10:08:08 -0500691 } else {
692 // It's a non-void function, but it never created a result expression--that is, it never
John Stiles2dda50d2021-03-03 10:46:44 -0500693 // returned anything on any path! This should have been detected in the function finalizer.
694 // Still, discard our output and generate an error.
695 SkDEBUGFAIL("inliner found non-void function that fails to return a value on any path");
696 fContext->fErrors.error(function.fOffset, "inliner found non-void function '" +
John Stiles0c2d14a2021-03-01 10:08:08 -0500697 function.declaration().name() +
John Stiles2dda50d2021-03-03 10:46:44 -0500698 "' that fails to return a value on any path");
John Stiles0c2d14a2021-03-01 10:08:08 -0500699 inlinedCall = {};
John Stiles44e96be2020-08-31 13:16:04 -0400700 }
701
John Stiles44e96be2020-08-31 13:16:04 -0400702 return inlinedCall;
703}
704
John Stiles2d7973a2020-10-02 15:01:03 -0400705bool Inliner::isSafeToInline(const FunctionDefinition* functionDef) {
John Stiles1c03d332020-10-13 10:30:23 -0400706 // A threshold of zero indicates that the inliner is completely disabled, so we can just return.
John Stilesd1204642021-02-17 16:30:02 -0500707 if (this->settings().fInlineThreshold <= 0) {
John Stiles1c03d332020-10-13 10:30:23 -0400708 return false;
709 }
710
John Stiles031a7672020-11-13 16:13:18 -0500711 // Enforce a limit on inlining to avoid pathological cases. (inliner/ExponentialGrowth.sksl)
712 if (fInlinedStatementCounter >= kInlinedStatementLimit) {
713 return false;
714 }
715
John Stiles2d7973a2020-10-02 15:01:03 -0400716 if (functionDef == nullptr) {
John Stiles44e96be2020-08-31 13:16:04 -0400717 // Can't inline something if we don't actually have its definition.
718 return false;
719 }
John Stiles2d7973a2020-10-02 15:01:03 -0400720
John Stiles0dd1a772021-03-09 22:14:27 -0500721 if (functionDef->declaration().modifiers().fFlags & Modifiers::kNoInline_Flag) {
722 // Refuse to inline functions decorated with `noinline`.
723 return false;
724 }
725
John Stilesbff24ab2021-03-17 13:20:10 -0400726 // We don't allow inlining a function with out parameters. (See skia:11326 for rationale.)
727 for (const Variable* param : functionDef->declaration().parameters()) {
728 if (param->modifiers().fFlags & Modifiers::Flag::kOut_Flag) {
729 return false;
730 }
731 }
732
John Stilesdc208472021-03-17 10:58:16 -0400733 // We don't have a mechanism to simulate early returns, so we can't inline if there is one.
734 return GetReturnComplexity(*functionDef) < ReturnComplexity::kEarlyReturns;
John Stiles44e96be2020-08-31 13:16:04 -0400735}
736
John Stiles2d7973a2020-10-02 15:01:03 -0400737// A candidate function for inlining, containing everything that `inlineCall` needs.
738struct InlineCandidate {
John Stiles78047582020-12-16 16:17:41 -0500739 std::shared_ptr<SymbolTable> fSymbols; // the SymbolTable of the candidate
John Stiles2d7973a2020-10-02 15:01:03 -0400740 std::unique_ptr<Statement>* fParentStmt; // the parent Statement of the enclosing stmt
741 std::unique_ptr<Statement>* fEnclosingStmt; // the Statement containing the candidate
742 std::unique_ptr<Expression>* fCandidateExpr; // the candidate FunctionCall to be inlined
743 FunctionDefinition* fEnclosingFunction; // the Function containing the candidate
John Stiles2d7973a2020-10-02 15:01:03 -0400744};
John Stiles93442622020-09-11 12:11:27 -0400745
John Stiles2d7973a2020-10-02 15:01:03 -0400746struct InlineCandidateList {
747 std::vector<InlineCandidate> fCandidates;
748};
749
750class InlineCandidateAnalyzer {
John Stiles70957c82020-10-02 16:42:10 -0400751public:
752 // A list of all the inlining candidates we found during analysis.
753 InlineCandidateList* fCandidateList;
John Stiles2d7973a2020-10-02 15:01:03 -0400754
John Stiles70957c82020-10-02 16:42:10 -0400755 // A stack of the symbol tables; since most nodes don't have one, expected to be shallower than
756 // the enclosing-statement stack.
John Stiles78047582020-12-16 16:17:41 -0500757 std::vector<std::shared_ptr<SymbolTable>> fSymbolTableStack;
John Stiles70957c82020-10-02 16:42:10 -0400758 // A stack of "enclosing" statements--these would be suitable for the inliner to use for adding
759 // new instructions. Not all statements are suitable (e.g. a for-loop's initializer). The
760 // inliner might replace a statement with a block containing the statement.
761 std::vector<std::unique_ptr<Statement>*> fEnclosingStmtStack;
762 // The function that we're currently processing (i.e. inlining into).
763 FunctionDefinition* fEnclosingFunction = nullptr;
John Stiles93442622020-09-11 12:11:27 -0400764
Brian Osman0006ad02020-11-18 15:38:39 -0500765 void visit(const std::vector<std::unique_ptr<ProgramElement>>& elements,
John Stiles78047582020-12-16 16:17:41 -0500766 std::shared_ptr<SymbolTable> symbols,
Brian Osman0006ad02020-11-18 15:38:39 -0500767 InlineCandidateList* candidateList) {
John Stiles70957c82020-10-02 16:42:10 -0400768 fCandidateList = candidateList;
Brian Osman0006ad02020-11-18 15:38:39 -0500769 fSymbolTableStack.push_back(symbols);
John Stiles93442622020-09-11 12:11:27 -0400770
Brian Osman0006ad02020-11-18 15:38:39 -0500771 for (const std::unique_ptr<ProgramElement>& pe : elements) {
Brian Osman1179fcf2020-10-08 16:04:40 -0400772 this->visitProgramElement(pe.get());
John Stiles93442622020-09-11 12:11:27 -0400773 }
774
John Stiles70957c82020-10-02 16:42:10 -0400775 fSymbolTableStack.pop_back();
776 fCandidateList = nullptr;
777 }
778
779 void visitProgramElement(ProgramElement* pe) {
780 switch (pe->kind()) {
781 case ProgramElement::Kind::kFunction: {
782 FunctionDefinition& funcDef = pe->as<FunctionDefinition>();
Brian Osman0006ad02020-11-18 15:38:39 -0500783 fEnclosingFunction = &funcDef;
784 this->visitStatement(&funcDef.body());
John Stiles70957c82020-10-02 16:42:10 -0400785 break;
John Stiles93442622020-09-11 12:11:27 -0400786 }
John Stiles70957c82020-10-02 16:42:10 -0400787 default:
788 // The inliner can't operate outside of a function's scope.
789 break;
790 }
791 }
792
793 void visitStatement(std::unique_ptr<Statement>* stmt,
794 bool isViableAsEnclosingStatement = true) {
795 if (!*stmt) {
796 return;
John Stiles93442622020-09-11 12:11:27 -0400797 }
798
John Stiles70957c82020-10-02 16:42:10 -0400799 size_t oldEnclosingStmtStackSize = fEnclosingStmtStack.size();
800 size_t oldSymbolStackSize = fSymbolTableStack.size();
John Stiles93442622020-09-11 12:11:27 -0400801
John Stiles70957c82020-10-02 16:42:10 -0400802 if (isViableAsEnclosingStatement) {
803 fEnclosingStmtStack.push_back(stmt);
John Stiles93442622020-09-11 12:11:27 -0400804 }
805
John Stiles70957c82020-10-02 16:42:10 -0400806 switch ((*stmt)->kind()) {
807 case Statement::Kind::kBreak:
808 case Statement::Kind::kContinue:
809 case Statement::Kind::kDiscard:
810 case Statement::Kind::kInlineMarker:
811 case Statement::Kind::kNop:
812 break;
813
814 case Statement::Kind::kBlock: {
815 Block& block = (*stmt)->as<Block>();
816 if (block.symbolTable()) {
John Stiles78047582020-12-16 16:17:41 -0500817 fSymbolTableStack.push_back(block.symbolTable());
John Stiles70957c82020-10-02 16:42:10 -0400818 }
819
820 for (std::unique_ptr<Statement>& stmt : block.children()) {
821 this->visitStatement(&stmt);
822 }
823 break;
John Stiles93442622020-09-11 12:11:27 -0400824 }
John Stiles70957c82020-10-02 16:42:10 -0400825 case Statement::Kind::kDo: {
826 DoStatement& doStmt = (*stmt)->as<DoStatement>();
827 // The loop body is a candidate for inlining.
828 this->visitStatement(&doStmt.statement());
829 // The inliner isn't smart enough to inline the test-expression for a do-while
830 // loop at this time. There are two limitations:
831 // - We would need to insert the inlined-body block at the very end of the do-
832 // statement's inner fStatement. We don't support that today, but it's doable.
833 // - We cannot inline the test expression if the loop uses `continue` anywhere; that
834 // would skip over the inlined block that evaluates the test expression. There
835 // isn't a good fix for this--any workaround would be more complex than the cost
836 // of a function call. However, loops that don't use `continue` would still be
837 // viable candidates for inlining.
838 break;
John Stiles93442622020-09-11 12:11:27 -0400839 }
John Stiles70957c82020-10-02 16:42:10 -0400840 case Statement::Kind::kExpression: {
841 ExpressionStatement& expr = (*stmt)->as<ExpressionStatement>();
842 this->visitExpression(&expr.expression());
843 break;
844 }
845 case Statement::Kind::kFor: {
846 ForStatement& forStmt = (*stmt)->as<ForStatement>();
Ethan Nicholas0d31ed52020-10-05 14:47:09 -0400847 if (forStmt.symbols()) {
John Stiles78047582020-12-16 16:17:41 -0500848 fSymbolTableStack.push_back(forStmt.symbols());
John Stiles70957c82020-10-02 16:42:10 -0400849 }
850
851 // The initializer and loop body are candidates for inlining.
Ethan Nicholas0d31ed52020-10-05 14:47:09 -0400852 this->visitStatement(&forStmt.initializer(),
John Stiles70957c82020-10-02 16:42:10 -0400853 /*isViableAsEnclosingStatement=*/false);
Ethan Nicholas0d31ed52020-10-05 14:47:09 -0400854 this->visitStatement(&forStmt.statement());
John Stiles70957c82020-10-02 16:42:10 -0400855
856 // The inliner isn't smart enough to inline the test- or increment-expressions
857 // of a for loop loop at this time. There are a handful of limitations:
858 // - We would need to insert the test-expression block at the very beginning of the
859 // for-loop's inner fStatement, and the increment-expression block at the very
860 // end. We don't support that today, but it's doable.
861 // - The for-loop's built-in test-expression would need to be dropped entirely,
862 // and the loop would be halted via a break statement at the end of the inlined
863 // test-expression. This is again something we don't support today, but it could
864 // be implemented.
865 // - We cannot inline the increment-expression if the loop uses `continue` anywhere;
866 // that would skip over the inlined block that evaluates the increment expression.
867 // There isn't a good fix for this--any workaround would be more complex than the
868 // cost of a function call. However, loops that don't use `continue` would still
869 // be viable candidates for increment-expression inlining.
870 break;
871 }
872 case Statement::Kind::kIf: {
873 IfStatement& ifStmt = (*stmt)->as<IfStatement>();
Ethan Nicholas8c44eca2020-10-07 16:47:09 -0400874 this->visitExpression(&ifStmt.test());
875 this->visitStatement(&ifStmt.ifTrue());
876 this->visitStatement(&ifStmt.ifFalse());
John Stiles70957c82020-10-02 16:42:10 -0400877 break;
878 }
879 case Statement::Kind::kReturn: {
880 ReturnStatement& returnStmt = (*stmt)->as<ReturnStatement>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -0400881 this->visitExpression(&returnStmt.expression());
John Stiles70957c82020-10-02 16:42:10 -0400882 break;
883 }
884 case Statement::Kind::kSwitch: {
885 SwitchStatement& switchStmt = (*stmt)->as<SwitchStatement>();
Ethan Nicholas01b05e52020-10-22 15:53:41 -0400886 if (switchStmt.symbols()) {
John Stiles78047582020-12-16 16:17:41 -0500887 fSymbolTableStack.push_back(switchStmt.symbols());
John Stiles70957c82020-10-02 16:42:10 -0400888 }
889
Ethan Nicholas01b05e52020-10-22 15:53:41 -0400890 this->visitExpression(&switchStmt.value());
John Stilesb23a64b2021-03-11 08:27:59 -0500891 for (const std::unique_ptr<Statement>& switchCase : switchStmt.cases()) {
John Stiles70957c82020-10-02 16:42:10 -0400892 // The switch-case's fValue cannot be a FunctionCall; skip it.
John Stilesb23a64b2021-03-11 08:27:59 -0500893 this->visitStatement(&switchCase->as<SwitchCase>().statement());
John Stiles70957c82020-10-02 16:42:10 -0400894 }
895 break;
896 }
897 case Statement::Kind::kVarDeclaration: {
898 VarDeclaration& varDeclStmt = (*stmt)->as<VarDeclaration>();
899 // Don't need to scan the declaration's sizes; those are always IntLiterals.
Ethan Nicholasc51f33e2020-10-13 13:49:44 -0400900 this->visitExpression(&varDeclStmt.value());
John Stiles70957c82020-10-02 16:42:10 -0400901 break;
902 }
John Stiles70957c82020-10-02 16:42:10 -0400903 default:
904 SkUNREACHABLE;
John Stiles93442622020-09-11 12:11:27 -0400905 }
906
John Stiles70957c82020-10-02 16:42:10 -0400907 // Pop our symbol and enclosing-statement stacks.
908 fSymbolTableStack.resize(oldSymbolStackSize);
909 fEnclosingStmtStack.resize(oldEnclosingStmtStackSize);
910 }
911
912 void visitExpression(std::unique_ptr<Expression>* expr) {
913 if (!*expr) {
914 return;
John Stiles93442622020-09-11 12:11:27 -0400915 }
John Stiles70957c82020-10-02 16:42:10 -0400916
917 switch ((*expr)->kind()) {
918 case Expression::Kind::kBoolLiteral:
919 case Expression::Kind::kDefined:
Brian Osmanbe0b3b72021-01-06 14:27:35 -0500920 case Expression::Kind::kExternalFunctionReference:
John Stiles70957c82020-10-02 16:42:10 -0400921 case Expression::Kind::kFieldAccess:
922 case Expression::Kind::kFloatLiteral:
923 case Expression::Kind::kFunctionReference:
924 case Expression::Kind::kIntLiteral:
John Stiles70957c82020-10-02 16:42:10 -0400925 case Expression::Kind::kSetting:
926 case Expression::Kind::kTypeReference:
927 case Expression::Kind::kVariableReference:
928 // Nothing to scan here.
929 break;
930
931 case Expression::Kind::kBinary: {
932 BinaryExpression& binaryExpr = (*expr)->as<BinaryExpression>();
John Stiles2d4f9592020-10-30 10:29:12 -0400933 this->visitExpression(&binaryExpr.left());
John Stiles70957c82020-10-02 16:42:10 -0400934
935 // Logical-and and logical-or binary expressions do not inline the right side,
936 // because that would invalidate short-circuiting. That is, when evaluating
937 // expressions like these:
938 // (false && x()) // always false
939 // (true || y()) // always true
940 // It is illegal for side-effects from x() or y() to occur. The simplest way to
941 // enforce that rule is to avoid inlining the right side entirely. However, it is
942 // safe for other types of binary expression to inline both sides.
John Stiles45990502021-02-16 10:55:27 -0500943 Operator op = binaryExpr.getOperator();
944 bool shortCircuitable = (op.kind() == Token::Kind::TK_LOGICALAND ||
945 op.kind() == Token::Kind::TK_LOGICALOR);
John Stiles70957c82020-10-02 16:42:10 -0400946 if (!shortCircuitable) {
John Stiles2d4f9592020-10-30 10:29:12 -0400947 this->visitExpression(&binaryExpr.right());
John Stiles70957c82020-10-02 16:42:10 -0400948 }
949 break;
950 }
John Stiles7384b372021-04-01 13:48:15 -0400951 case Expression::Kind::kConstructor:
952 case Expression::Kind::kConstructorArray:
John Stiles2938eea2021-04-01 18:58:25 -0400953 case Expression::Kind::kConstructorDiagonalMatrix:
John Stiles5abb9e12021-04-06 13:47:19 -0400954 case Expression::Kind::kConstructorMatrixResize:
John Stilesfd7252f2021-04-04 22:24:40 -0400955 case Expression::Kind::kConstructorScalarCast:
John Stilesb14a8192021-04-05 11:40:46 -0400956 case Expression::Kind::kConstructorSplat:
957 case Expression::Kind::kConstructorVectorCast: {
John Stiles7384b372021-04-01 13:48:15 -0400958 AnyConstructor& constructorExpr = (*expr)->asAnyConstructor();
959 for (std::unique_ptr<Expression>& arg : constructorExpr.argumentSpan()) {
John Stiles70957c82020-10-02 16:42:10 -0400960 this->visitExpression(&arg);
961 }
962 break;
963 }
964 case Expression::Kind::kExternalFunctionCall: {
965 ExternalFunctionCall& funcCallExpr = (*expr)->as<ExternalFunctionCall>();
966 for (std::unique_ptr<Expression>& arg : funcCallExpr.arguments()) {
967 this->visitExpression(&arg);
968 }
969 break;
970 }
971 case Expression::Kind::kFunctionCall: {
972 FunctionCall& funcCallExpr = (*expr)->as<FunctionCall>();
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400973 for (std::unique_ptr<Expression>& arg : funcCallExpr.arguments()) {
John Stiles70957c82020-10-02 16:42:10 -0400974 this->visitExpression(&arg);
975 }
976 this->addInlineCandidate(expr);
977 break;
978 }
John Stiles708faba2021-03-19 09:43:23 -0400979 case Expression::Kind::kIndex: {
John Stiles70957c82020-10-02 16:42:10 -0400980 IndexExpression& indexExpr = (*expr)->as<IndexExpression>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -0400981 this->visitExpression(&indexExpr.base());
982 this->visitExpression(&indexExpr.index());
John Stiles70957c82020-10-02 16:42:10 -0400983 break;
984 }
985 case Expression::Kind::kPostfix: {
986 PostfixExpression& postfixExpr = (*expr)->as<PostfixExpression>();
Ethan Nicholas444ccc62020-10-09 10:16:22 -0400987 this->visitExpression(&postfixExpr.operand());
John Stiles70957c82020-10-02 16:42:10 -0400988 break;
989 }
990 case Expression::Kind::kPrefix: {
991 PrefixExpression& prefixExpr = (*expr)->as<PrefixExpression>();
Ethan Nicholas444ccc62020-10-09 10:16:22 -0400992 this->visitExpression(&prefixExpr.operand());
John Stiles70957c82020-10-02 16:42:10 -0400993 break;
994 }
995 case Expression::Kind::kSwizzle: {
996 Swizzle& swizzleExpr = (*expr)->as<Swizzle>();
Ethan Nicholas6b4d5812020-10-12 16:11:51 -0400997 this->visitExpression(&swizzleExpr.base());
John Stiles70957c82020-10-02 16:42:10 -0400998 break;
999 }
1000 case Expression::Kind::kTernary: {
1001 TernaryExpression& ternaryExpr = (*expr)->as<TernaryExpression>();
1002 // The test expression is a candidate for inlining.
Ethan Nicholasdd218162020-10-08 05:48:01 -04001003 this->visitExpression(&ternaryExpr.test());
John Stiles70957c82020-10-02 16:42:10 -04001004 // The true- and false-expressions cannot be inlined, because we are only allowed to
1005 // evaluate one side.
1006 break;
1007 }
1008 default:
1009 SkUNREACHABLE;
1010 }
1011 }
1012
1013 void addInlineCandidate(std::unique_ptr<Expression>* candidate) {
1014 fCandidateList->fCandidates.push_back(
1015 InlineCandidate{fSymbolTableStack.back(),
1016 find_parent_statement(fEnclosingStmtStack),
1017 fEnclosingStmtStack.back(),
1018 candidate,
John Stiles9b9415e2020-11-23 14:48:06 -05001019 fEnclosingFunction});
John Stiles70957c82020-10-02 16:42:10 -04001020 }
John Stiles2d7973a2020-10-02 15:01:03 -04001021};
John Stiles93442622020-09-11 12:11:27 -04001022
John Stiles9b9415e2020-11-23 14:48:06 -05001023static const FunctionDeclaration& candidate_func(const InlineCandidate& candidate) {
1024 return (*candidate.fCandidateExpr)->as<FunctionCall>().function();
1025}
John Stiles915a38c2020-09-14 09:38:13 -04001026
John Stiles9b9415e2020-11-23 14:48:06 -05001027bool Inliner::candidateCanBeInlined(const InlineCandidate& candidate, InlinabilityCache* cache) {
1028 const FunctionDeclaration& funcDecl = candidate_func(candidate);
John Stiles1c03d332020-10-13 10:30:23 -04001029 auto [iter, wasInserted] = cache->insert({&funcDecl, false});
John Stiles2d7973a2020-10-02 15:01:03 -04001030 if (wasInserted) {
1031 // Recursion is forbidden here to avoid an infinite death spiral of inlining.
John Stiles132cfdd2021-03-15 22:08:38 +00001032 iter->second = this->isSafeToInline(funcDecl.definition()) &&
1033 !contains_recursive_call(funcDecl);
John Stiles93442622020-09-11 12:11:27 -04001034 }
1035
John Stiles2d7973a2020-10-02 15:01:03 -04001036 return iter->second;
1037}
1038
John Stiles9b9415e2020-11-23 14:48:06 -05001039int Inliner::getFunctionSize(const FunctionDeclaration& funcDecl, FunctionSizeCache* cache) {
1040 auto [iter, wasInserted] = cache->insert({&funcDecl, 0});
John Stiles2d7973a2020-10-02 15:01:03 -04001041 if (wasInserted) {
John Stiles9b9415e2020-11-23 14:48:06 -05001042 iter->second = Analysis::NodeCountUpToLimit(*funcDecl.definition(),
John Stilesd1204642021-02-17 16:30:02 -05001043 this->settings().fInlineThreshold);
John Stiles2d7973a2020-10-02 15:01:03 -04001044 }
John Stiles2d7973a2020-10-02 15:01:03 -04001045 return iter->second;
1046}
1047
Brian Osman0006ad02020-11-18 15:38:39 -05001048void Inliner::buildCandidateList(const std::vector<std::unique_ptr<ProgramElement>>& elements,
John Stiles78047582020-12-16 16:17:41 -05001049 std::shared_ptr<SymbolTable> symbols, ProgramUsage* usage,
Brian Osman0006ad02020-11-18 15:38:39 -05001050 InlineCandidateList* candidateList) {
John Stiles2d7973a2020-10-02 15:01:03 -04001051 // This is structured much like a ProgramVisitor, but does not actually use ProgramVisitor.
1052 // The analyzer needs to keep track of the `unique_ptr<T>*` of statements and expressions so
1053 // that they can later be replaced, and ProgramVisitor does not provide this; it only provides a
1054 // `const T&`.
1055 InlineCandidateAnalyzer analyzer;
Brian Osman0006ad02020-11-18 15:38:39 -05001056 analyzer.visit(elements, symbols, candidateList);
John Stiles2d7973a2020-10-02 15:01:03 -04001057
John Stiles0ad233f2020-11-25 11:02:05 -05001058 // Early out if there are no inlining candidates.
John Stiles2d7973a2020-10-02 15:01:03 -04001059 std::vector<InlineCandidate>& candidates = candidateList->fCandidates;
John Stiles0ad233f2020-11-25 11:02:05 -05001060 if (candidates.empty()) {
1061 return;
1062 }
1063
1064 // Remove candidates that are not safe to inline.
John Stiles2d7973a2020-10-02 15:01:03 -04001065 InlinabilityCache cache;
1066 candidates.erase(std::remove_if(candidates.begin(),
1067 candidates.end(),
1068 [&](const InlineCandidate& candidate) {
1069 return !this->candidateCanBeInlined(candidate, &cache);
1070 }),
1071 candidates.end());
1072
John Stiles0ad233f2020-11-25 11:02:05 -05001073 // If the inline threshold is unlimited, or if we have no candidates left, our candidate list is
1074 // complete.
John Stilesd1204642021-02-17 16:30:02 -05001075 if (this->settings().fInlineThreshold == INT_MAX || candidates.empty()) {
John Stiles0ad233f2020-11-25 11:02:05 -05001076 return;
John Stiles2d7973a2020-10-02 15:01:03 -04001077 }
John Stiles0ad233f2020-11-25 11:02:05 -05001078
1079 // Remove candidates on a per-function basis if the effect of inlining would be to make more
1080 // than `inlineThreshold` nodes. (i.e. if Func() would be inlined six times and its size is
1081 // 10 nodes, it should be inlined if the inlineThreshold is 60 or higher.)
1082 FunctionSizeCache functionSizeCache;
1083 FunctionSizeCache candidateTotalCost;
1084 for (InlineCandidate& candidate : candidates) {
1085 const FunctionDeclaration& fnDecl = candidate_func(candidate);
1086 candidateTotalCost[&fnDecl] += this->getFunctionSize(fnDecl, &functionSizeCache);
1087 }
1088
John Stilesd1204642021-02-17 16:30:02 -05001089 candidates.erase(std::remove_if(candidates.begin(), candidates.end(),
1090 [&](const InlineCandidate& candidate) {
1091 const FunctionDeclaration& fnDecl = candidate_func(candidate);
1092 if (fnDecl.modifiers().fFlags & Modifiers::kInline_Flag) {
1093 // Functions marked `inline` ignore size limitations.
1094 return false;
1095 }
1096 if (usage->get(fnDecl) == 1) {
1097 // If a function is only used once, it's cost-free to inline.
1098 return false;
1099 }
1100 if (candidateTotalCost[&fnDecl] <= this->settings().fInlineThreshold) {
1101 // We won't exceed the inline threshold by inlining this.
1102 return false;
1103 }
1104 // Inlining this function will add too many IRNodes.
1105 return true;
1106 }),
1107 candidates.end());
John Stiles2d7973a2020-10-02 15:01:03 -04001108}
1109
Brian Osman0006ad02020-11-18 15:38:39 -05001110bool Inliner::analyze(const std::vector<std::unique_ptr<ProgramElement>>& elements,
John Stiles78047582020-12-16 16:17:41 -05001111 std::shared_ptr<SymbolTable> symbols,
Brian Osman0006ad02020-11-18 15:38:39 -05001112 ProgramUsage* usage) {
John Stilesd34d56e2020-10-12 12:04:47 -04001113 // A threshold of zero indicates that the inliner is completely disabled, so we can just return.
John Stilesd1204642021-02-17 16:30:02 -05001114 if (this->settings().fInlineThreshold <= 0) {
John Stilesd34d56e2020-10-12 12:04:47 -04001115 return false;
1116 }
1117
John Stiles031a7672020-11-13 16:13:18 -05001118 // Enforce a limit on inlining to avoid pathological cases. (inliner/ExponentialGrowth.sksl)
1119 if (fInlinedStatementCounter >= kInlinedStatementLimit) {
1120 return false;
1121 }
1122
John Stiles2d7973a2020-10-02 15:01:03 -04001123 InlineCandidateList candidateList;
John Stiles9b9415e2020-11-23 14:48:06 -05001124 this->buildCandidateList(elements, symbols, usage, &candidateList);
John Stiles2d7973a2020-10-02 15:01:03 -04001125
John Stiles915a38c2020-09-14 09:38:13 -04001126 // Inline the candidates where we've determined that it's safe to do so.
John Stiles708faba2021-03-19 09:43:23 -04001127 using StatementRemappingTable = std::unordered_map<std::unique_ptr<Statement>*,
1128 std::unique_ptr<Statement>*>;
1129 StatementRemappingTable statementRemappingTable;
1130
John Stiles915a38c2020-09-14 09:38:13 -04001131 bool madeChanges = false;
John Stiles2d7973a2020-10-02 15:01:03 -04001132 for (const InlineCandidate& candidate : candidateList.fCandidates) {
John Stiles915a38c2020-09-14 09:38:13 -04001133 FunctionCall& funcCall = (*candidate.fCandidateExpr)->as<FunctionCall>();
John Stiles915a38c2020-09-14 09:38:13 -04001134
John Stiles915a38c2020-09-14 09:38:13 -04001135 // Convert the function call to its inlined equivalent.
John Stiles30fce9c2021-03-18 09:24:06 -04001136 InlinedCall inlinedCall = this->inlineCall(&funcCall, candidate.fSymbols, *usage,
Ethan Nicholas0a5d0962020-10-14 13:33:18 -04001137 &candidate.fEnclosingFunction->declaration());
John Stiles915a38c2020-09-14 09:38:13 -04001138
John Stiles0c2d14a2021-03-01 10:08:08 -05001139 // Stop if an error was detected during the inlining process.
1140 if (!inlinedCall.fInlinedBody && !inlinedCall.fReplacementExpr) {
1141 break;
John Stiles915a38c2020-09-14 09:38:13 -04001142 }
1143
John Stiles0c2d14a2021-03-01 10:08:08 -05001144 // Ensure that the inlined body has a scope if it needs one.
1145 this->ensureScopedBlocks(inlinedCall.fInlinedBody.get(), candidate.fParentStmt->get());
1146
1147 // Add references within the inlined body
1148 usage->add(inlinedCall.fInlinedBody.get());
1149
John Stiles708faba2021-03-19 09:43:23 -04001150 // Look up the enclosing statement; remap it if necessary.
1151 std::unique_ptr<Statement>* enclosingStmt = candidate.fEnclosingStmt;
1152 for (;;) {
1153 auto iter = statementRemappingTable.find(enclosingStmt);
1154 if (iter == statementRemappingTable.end()) {
1155 break;
1156 }
1157 enclosingStmt = iter->second;
1158 }
1159
John Stiles0c2d14a2021-03-01 10:08:08 -05001160 // Move the enclosing statement to the end of the unscoped Block containing the inlined
1161 // function, then replace the enclosing statement with that Block.
1162 // Before:
1163 // fInlinedBody = Block{ stmt1, stmt2, stmt3 }
1164 // fEnclosingStmt = stmt4
1165 // After:
1166 // fInlinedBody = null
1167 // fEnclosingStmt = Block{ stmt1, stmt2, stmt3, stmt4 }
John Stiles708faba2021-03-19 09:43:23 -04001168 inlinedCall.fInlinedBody->children().push_back(std::move(*enclosingStmt));
1169 *enclosingStmt = std::move(inlinedCall.fInlinedBody);
John Stiles0c2d14a2021-03-01 10:08:08 -05001170
John Stiles915a38c2020-09-14 09:38:13 -04001171 // Replace the candidate function call with our replacement expression.
Brian Osman010ce6a2020-10-19 16:34:10 -04001172 usage->replace(candidate.fCandidateExpr->get(), inlinedCall.fReplacementExpr.get());
John Stiles915a38c2020-09-14 09:38:13 -04001173 *candidate.fCandidateExpr = std::move(inlinedCall.fReplacementExpr);
1174 madeChanges = true;
1175
John Stiles708faba2021-03-19 09:43:23 -04001176 // If anything else pointed at our enclosing statement, it's now pointing at a Block
1177 // containing many other statements as well. Maintain a fix-up table to account for this.
1178 statementRemappingTable[enclosingStmt] = &(*enclosingStmt)->as<Block>().children().back();
1179
John Stiles031a7672020-11-13 16:13:18 -05001180 // Stop inlining if we've reached our hard cap on new statements.
1181 if (fInlinedStatementCounter >= kInlinedStatementLimit) {
1182 break;
1183 }
1184
John Stiles915a38c2020-09-14 09:38:13 -04001185 // Note that nothing was destroyed except for the FunctionCall. All other nodes should
1186 // remain valid.
1187 }
1188
1189 return madeChanges;
John Stiles93442622020-09-11 12:11:27 -04001190}
1191
John Stiles44e96be2020-08-31 13:16:04 -04001192} // namespace SkSL