blob: 4c71157ea8b14c0d0a966ebca6d40d78d1359ffb [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"
John Stiles44e96be2020-08-31 13:16:04 -040017#include "src/sksl/ir/SkSLBreakStatement.h"
Brian Osmaneb0f29d2021-08-04 11:34:16 -040018#include "src/sksl/ir/SkSLChildCall.h"
John Stiles44e96be2020-08-31 13:16:04 -040019#include "src/sksl/ir/SkSLConstructor.h"
John Stiles7384b372021-04-01 13:48:15 -040020#include "src/sksl/ir/SkSLConstructorArray.h"
John Stilese3ae9682021-08-05 10:35:01 -040021#include "src/sksl/ir/SkSLConstructorArrayCast.h"
John Stiles8cad6372021-04-07 12:31:13 -040022#include "src/sksl/ir/SkSLConstructorCompound.h"
23#include "src/sksl/ir/SkSLConstructorCompoundCast.h"
John Stilese1182782021-03-30 22:09:37 -040024#include "src/sksl/ir/SkSLConstructorDiagonalMatrix.h"
John Stiles5abb9e12021-04-06 13:47:19 -040025#include "src/sksl/ir/SkSLConstructorMatrixResize.h"
John Stilesfd7252f2021-04-04 22:24:40 -040026#include "src/sksl/ir/SkSLConstructorScalarCast.h"
John Stiles2938eea2021-04-01 18:58:25 -040027#include "src/sksl/ir/SkSLConstructorSplat.h"
John Stilesd47330f2021-04-08 23:25:52 -040028#include "src/sksl/ir/SkSLConstructorStruct.h"
John Stiles44e96be2020-08-31 13:16:04 -040029#include "src/sksl/ir/SkSLContinueStatement.h"
30#include "src/sksl/ir/SkSLDiscardStatement.h"
31#include "src/sksl/ir/SkSLDoStatement.h"
John Stiles44e96be2020-08-31 13:16:04 -040032#include "src/sksl/ir/SkSLExpressionStatement.h"
33#include "src/sksl/ir/SkSLExternalFunctionCall.h"
Brian Osmanbe0b3b72021-01-06 14:27:35 -050034#include "src/sksl/ir/SkSLExternalFunctionReference.h"
John Stiles44e96be2020-08-31 13:16:04 -040035#include "src/sksl/ir/SkSLField.h"
36#include "src/sksl/ir/SkSLFieldAccess.h"
John Stiles44e96be2020-08-31 13:16:04 -040037#include "src/sksl/ir/SkSLForStatement.h"
38#include "src/sksl/ir/SkSLFunctionCall.h"
39#include "src/sksl/ir/SkSLFunctionDeclaration.h"
40#include "src/sksl/ir/SkSLFunctionDefinition.h"
41#include "src/sksl/ir/SkSLFunctionReference.h"
42#include "src/sksl/ir/SkSLIfStatement.h"
43#include "src/sksl/ir/SkSLIndexExpression.h"
John Stiles98c1f822020-09-09 14:18:53 -040044#include "src/sksl/ir/SkSLInlineMarker.h"
John Stiles44e96be2020-08-31 13:16:04 -040045#include "src/sksl/ir/SkSLInterfaceBlock.h"
John Stiles7591d4b2021-09-13 13:32:06 -040046#include "src/sksl/ir/SkSLLiteral.h"
John Stiles44e96be2020-08-31 13:16:04 -040047#include "src/sksl/ir/SkSLNop.h"
John Stiles44e96be2020-08-31 13:16:04 -040048#include "src/sksl/ir/SkSLPostfixExpression.h"
49#include "src/sksl/ir/SkSLPrefixExpression.h"
50#include "src/sksl/ir/SkSLReturnStatement.h"
51#include "src/sksl/ir/SkSLSetting.h"
52#include "src/sksl/ir/SkSLSwitchCase.h"
53#include "src/sksl/ir/SkSLSwitchStatement.h"
54#include "src/sksl/ir/SkSLSwizzle.h"
55#include "src/sksl/ir/SkSLTernaryExpression.h"
56#include "src/sksl/ir/SkSLUnresolvedFunction.h"
57#include "src/sksl/ir/SkSLVarDeclarations.h"
John Stiles44e96be2020-08-31 13:16:04 -040058#include "src/sksl/ir/SkSLVariable.h"
59#include "src/sksl/ir/SkSLVariableReference.h"
John Stiles44e96be2020-08-31 13:16:04 -040060
61namespace SkSL {
62namespace {
63
John Stiles031a7672020-11-13 16:13:18 -050064static constexpr int kInlinedStatementLimit = 2500;
65
John Stiles44e96be2020-08-31 13:16:04 -040066static int count_returns_at_end_of_control_flow(const FunctionDefinition& funcDef) {
67 class CountReturnsAtEndOfControlFlow : public ProgramVisitor {
68 public:
69 CountReturnsAtEndOfControlFlow(const FunctionDefinition& funcDef) {
70 this->visitProgramElement(funcDef);
71 }
72
John Stiles5b408a32021-03-17 09:53:32 -040073 bool visitExpression(const Expression& expr) override {
74 // Do not recurse into expressions.
75 return false;
76 }
77
John Stiles44e96be2020-08-31 13:16:04 -040078 bool visitStatement(const Statement& stmt) override {
Ethan Nicholase6592142020-09-08 10:22:09 -040079 switch (stmt.kind()) {
80 case Statement::Kind::kBlock: {
John Stiles44e96be2020-08-31 13:16:04 -040081 // Check only the last statement of a block.
Ethan Nicholas7bd60432020-09-25 14:31:59 -040082 const auto& block = stmt.as<Block>();
83 return block.children().size() &&
84 this->visitStatement(*block.children().back());
John Stiles44e96be2020-08-31 13:16:04 -040085 }
Ethan Nicholase6592142020-09-08 10:22:09 -040086 case Statement::Kind::kSwitch:
Ethan Nicholase6592142020-09-08 10:22:09 -040087 case Statement::Kind::kDo:
88 case Statement::Kind::kFor:
John Stiles44e96be2020-08-31 13:16:04 -040089 // Don't introspect switches or loop structures at all.
90 return false;
91
Ethan Nicholase6592142020-09-08 10:22:09 -040092 case Statement::Kind::kReturn:
John Stiles44e96be2020-08-31 13:16:04 -040093 ++fNumReturns;
94 [[fallthrough]];
95
96 default:
John Stiles93442622020-09-11 12:11:27 -040097 return INHERITED::visitStatement(stmt);
John Stiles44e96be2020-08-31 13:16:04 -040098 }
99 }
100
101 int fNumReturns = 0;
102 using INHERITED = ProgramVisitor;
103 };
104
105 return CountReturnsAtEndOfControlFlow{funcDef}.fNumReturns;
106}
107
John Stiles991b09d2020-09-10 13:33:40 -0400108static bool contains_recursive_call(const FunctionDeclaration& funcDecl) {
109 class ContainsRecursiveCall : public ProgramVisitor {
110 public:
111 bool visit(const FunctionDeclaration& funcDecl) {
112 fFuncDecl = &funcDecl;
Ethan Nicholased84b732020-10-08 11:45:44 -0400113 return funcDecl.definition() ? this->visitProgramElement(*funcDecl.definition())
114 : false;
John Stiles991b09d2020-09-10 13:33:40 -0400115 }
116
117 bool visitExpression(const Expression& expr) override {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400118 if (expr.is<FunctionCall>() && expr.as<FunctionCall>().function().matches(*fFuncDecl)) {
John Stiles991b09d2020-09-10 13:33:40 -0400119 return true;
120 }
121 return INHERITED::visitExpression(expr);
122 }
123
124 bool visitStatement(const Statement& stmt) override {
Ethan Nicholasceb62142020-10-09 16:51:18 -0400125 if (stmt.is<InlineMarker>() &&
126 stmt.as<InlineMarker>().function().matches(*fFuncDecl)) {
John Stiles991b09d2020-09-10 13:33:40 -0400127 return true;
128 }
129 return INHERITED::visitStatement(stmt);
130 }
131
132 const FunctionDeclaration* fFuncDecl;
133 using INHERITED = ProgramVisitor;
134 };
135
136 return ContainsRecursiveCall{}.visit(funcDecl);
137}
138
John Stiles6d696082020-10-01 10:18:54 -0400139static std::unique_ptr<Statement>* find_parent_statement(
140 const std::vector<std::unique_ptr<Statement>*>& stmtStack) {
John Stiles915a38c2020-09-14 09:38:13 -0400141 SkASSERT(!stmtStack.empty());
142
143 // Walk the statement stack from back to front, ignoring the last element (which is the
144 // enclosing statement).
145 auto iter = stmtStack.rbegin();
146 ++iter;
147
148 // Anything counts as a parent statement other than a scopeless Block.
149 for (; iter != stmtStack.rend(); ++iter) {
John Stiles6d696082020-10-01 10:18:54 -0400150 std::unique_ptr<Statement>* stmt = *iter;
151 if (!(*stmt)->is<Block>() || (*stmt)->as<Block>().isScope()) {
John Stiles915a38c2020-09-14 09:38:13 -0400152 return stmt;
153 }
154 }
155
156 // There wasn't any parent statement to be found.
157 return nullptr;
158}
159
John Stilese41b4ee2020-09-28 12:28:16 -0400160std::unique_ptr<Expression> clone_with_ref_kind(const Expression& expr,
161 VariableReference::RefKind refKind) {
162 std::unique_ptr<Expression> clone = expr.clone();
John Stilesbb8cf582021-08-26 23:34:59 -0400163 Analysis::UpdateVariableRefKind(clone.get(), refKind);
John Stilese41b4ee2020-09-28 12:28:16 -0400164 return clone;
165}
166
John Stiles77702f12020-12-17 14:38:56 -0500167class CountReturnsWithLimit : public ProgramVisitor {
168public:
169 CountReturnsWithLimit(const FunctionDefinition& funcDef, int limit) : fLimit(limit) {
170 this->visitProgramElement(funcDef);
171 }
172
John Stiles5b408a32021-03-17 09:53:32 -0400173 bool visitExpression(const Expression& expr) override {
174 // Do not recurse into expressions.
175 return false;
176 }
177
John Stiles77702f12020-12-17 14:38:56 -0500178 bool visitStatement(const Statement& stmt) override {
179 switch (stmt.kind()) {
180 case Statement::Kind::kReturn: {
181 ++fNumReturns;
182 fDeepestReturn = std::max(fDeepestReturn, fScopedBlockDepth);
183 return (fNumReturns >= fLimit) || INHERITED::visitStatement(stmt);
184 }
John Stilesc5ff4862020-12-22 13:47:05 -0500185 case Statement::Kind::kVarDeclaration: {
186 if (fScopedBlockDepth > 1) {
187 fVariablesInBlocks = true;
188 }
189 return INHERITED::visitStatement(stmt);
190 }
John Stiles77702f12020-12-17 14:38:56 -0500191 case Statement::Kind::kBlock: {
192 int depthIncrement = stmt.as<Block>().isScope() ? 1 : 0;
193 fScopedBlockDepth += depthIncrement;
194 bool result = INHERITED::visitStatement(stmt);
195 fScopedBlockDepth -= depthIncrement;
John Stilesc5ff4862020-12-22 13:47:05 -0500196 if (fNumReturns == 0 && fScopedBlockDepth <= 1) {
197 // If closing this block puts us back at the top level, and we haven't
198 // encountered any return statements yet, any vardecls we may have encountered
199 // up until this point can be ignored. They are out of scope now, and they were
200 // never used in a return statement.
201 fVariablesInBlocks = false;
202 }
John Stiles77702f12020-12-17 14:38:56 -0500203 return result;
204 }
205 default:
206 return INHERITED::visitStatement(stmt);
207 }
208 }
209
210 int fNumReturns = 0;
211 int fDeepestReturn = 0;
212 int fLimit = 0;
213 int fScopedBlockDepth = 0;
John Stilesc5ff4862020-12-22 13:47:05 -0500214 bool fVariablesInBlocks = false;
John Stiles77702f12020-12-17 14:38:56 -0500215 using INHERITED = ProgramVisitor;
216};
217
John Stiles44e96be2020-08-31 13:16:04 -0400218} // namespace
219
John Stiles77702f12020-12-17 14:38:56 -0500220Inliner::ReturnComplexity Inliner::GetReturnComplexity(const FunctionDefinition& funcDef) {
221 int returnsAtEndOfControlFlow = count_returns_at_end_of_control_flow(funcDef);
222 CountReturnsWithLimit counter{funcDef, returnsAtEndOfControlFlow + 1};
John Stiles77702f12020-12-17 14:38:56 -0500223 if (counter.fNumReturns > returnsAtEndOfControlFlow) {
224 return ReturnComplexity::kEarlyReturns;
225 }
John Stilesc5ff4862020-12-22 13:47:05 -0500226 if (counter.fNumReturns > 1) {
John Stiles77702f12020-12-17 14:38:56 -0500227 return ReturnComplexity::kScopedReturns;
228 }
John Stilesc5ff4862020-12-22 13:47:05 -0500229 if (counter.fVariablesInBlocks && counter.fDeepestReturn > 1) {
230 return ReturnComplexity::kScopedReturns;
231 }
John Stiles8937cd42021-03-17 19:32:59 +0000232 return ReturnComplexity::kSingleSafeReturn;
John Stiles77702f12020-12-17 14:38:56 -0500233}
234
John Stilesb61ee902020-09-21 12:26:59 -0400235void Inliner::ensureScopedBlocks(Statement* inlinedBody, Statement* parentStmt) {
236 // No changes necessary if this statement isn't actually a block.
237 if (!inlinedBody || !inlinedBody->is<Block>()) {
238 return;
239 }
240
241 // No changes necessary if the parent statement doesn't require a scope.
242 if (!parentStmt || !(parentStmt->is<IfStatement>() || parentStmt->is<ForStatement>() ||
Brian Osmand6f23382020-12-15 17:08:59 -0500243 parentStmt->is<DoStatement>())) {
John Stilesb61ee902020-09-21 12:26:59 -0400244 return;
245 }
246
247 Block& block = inlinedBody->as<Block>();
248
249 // The inliner will create inlined function bodies as a Block containing multiple statements,
250 // but no scope. Normally, this is fine, but if this block is used as the statement for a
251 // do/for/if/while, this isn't actually possible to represent textually; a scope must be added
252 // for the generated code to match the intent. In the case of Blocks nested inside other Blocks,
253 // we add the scope to the outermost block if needed. Zero-statement blocks have similar
254 // issues--if we don't represent the Block textually somehow, we run the risk of accidentally
255 // absorbing the following statement into our loop--so we also add a scope to these.
256 for (Block* nestedBlock = &block;; ) {
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400257 if (nestedBlock->isScope()) {
John Stilesb61ee902020-09-21 12:26:59 -0400258 // We found an explicit scope; all is well.
259 return;
260 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400261 if (nestedBlock->children().size() != 1) {
John Stilesb61ee902020-09-21 12:26:59 -0400262 // We found a block with multiple (or zero) statements, but no scope? Let's add a scope
263 // to the outermost block.
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400264 block.setIsScope(true);
John Stilesb61ee902020-09-21 12:26:59 -0400265 return;
266 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400267 if (!nestedBlock->children()[0]->is<Block>()) {
John Stilesb61ee902020-09-21 12:26:59 -0400268 // This block has exactly one thing inside, and it's not another block. No need to scope
269 // it.
270 return;
271 }
272 // We have to go deeper.
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400273 nestedBlock = &nestedBlock->children()[0]->as<Block>();
John Stilesb61ee902020-09-21 12:26:59 -0400274 }
275}
276
John Stiles10d39d92021-05-04 16:13:14 -0400277void Inliner::reset() {
John Stiles2dda4b62021-09-16 13:18:10 -0400278 fContext->fMangler->reset();
John Stiles031a7672020-11-13 16:13:18 -0500279 fInlinedStatementCounter = 0;
John Stiles44e96be2020-08-31 13:16:04 -0400280}
281
Ethan Nicholas89cfde12021-09-27 11:20:34 -0400282std::unique_ptr<Expression> Inliner::inlineExpression(int line,
John Stiles44e96be2020-08-31 13:16:04 -0400283 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) {
Ethan Nicholas89cfde12021-09-27 11:20:34 -0400288 return this->inlineExpression(line, 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 }
John Stiles7591d4b2021-09-13 13:32:06 -0400309 case Expression::Kind::kLiteral:
John Stiles44e96be2020-08-31 13:16:04 -0400310 return expression.clone();
Brian Osmaneb0f29d2021-08-04 11:34:16 -0400311 case Expression::Kind::kChildCall: {
312 const ChildCall& childCall = expression.as<ChildCall>();
313 return ChildCall::Make(*fContext,
Ethan Nicholas89cfde12021-09-27 11:20:34 -0400314 line,
Brian Osmaneb0f29d2021-08-04 11:34:16 -0400315 childCall.type().clone(symbolTableForExpression),
316 childCall.child(),
317 argList(childCall.arguments()));
318 }
John Stiles7384b372021-04-01 13:48:15 -0400319 case Expression::Kind::kConstructorArray: {
320 const ConstructorArray& ctor = expression.as<ConstructorArray>();
Ethan Nicholas89cfde12021-09-27 11:20:34 -0400321 return ConstructorArray::Make(*fContext, line,
John Stiles7384b372021-04-01 13:48:15 -0400322 *ctor.type().clone(symbolTableForExpression),
323 argList(ctor.arguments()));
324 }
John Stilese3ae9682021-08-05 10:35:01 -0400325 case Expression::Kind::kConstructorArrayCast: {
326 const ConstructorArrayCast& ctor = expression.as<ConstructorArrayCast>();
Ethan Nicholas89cfde12021-09-27 11:20:34 -0400327 return ConstructorArrayCast::Make(*fContext, line,
John Stilese3ae9682021-08-05 10:35:01 -0400328 *ctor.type().clone(symbolTableForExpression),
329 expr(ctor.argument()));
330 }
John Stiles8cad6372021-04-07 12:31:13 -0400331 case Expression::Kind::kConstructorCompound: {
332 const ConstructorCompound& ctor = expression.as<ConstructorCompound>();
Ethan Nicholas89cfde12021-09-27 11:20:34 -0400333 return ConstructorCompound::Make(*fContext, line,
John Stiles2bec8ab2021-04-06 18:40:04 -0400334 *ctor.type().clone(symbolTableForExpression),
335 argList(ctor.arguments()));
336 }
John Stiles8cad6372021-04-07 12:31:13 -0400337 case Expression::Kind::kConstructorCompoundCast: {
338 const ConstructorCompoundCast& ctor = expression.as<ConstructorCompoundCast>();
Ethan Nicholas89cfde12021-09-27 11:20:34 -0400339 return ConstructorCompoundCast::Make(*fContext, line,
John Stiles268a73f2021-04-07 12:30:22 -0400340 *ctor.type().clone(symbolTableForExpression),
341 expr(ctor.argument()));
342 }
John Stilese1182782021-03-30 22:09:37 -0400343 case Expression::Kind::kConstructorDiagonalMatrix: {
344 const ConstructorDiagonalMatrix& ctor = expression.as<ConstructorDiagonalMatrix>();
Ethan Nicholas89cfde12021-09-27 11:20:34 -0400345 return ConstructorDiagonalMatrix::Make(*fContext, line,
John Stilese1182782021-03-30 22:09:37 -0400346 *ctor.type().clone(symbolTableForExpression),
347 expr(ctor.argument()));
348 }
John Stiles5abb9e12021-04-06 13:47:19 -0400349 case Expression::Kind::kConstructorMatrixResize: {
350 const ConstructorMatrixResize& ctor = expression.as<ConstructorMatrixResize>();
Ethan Nicholas89cfde12021-09-27 11:20:34 -0400351 return ConstructorMatrixResize::Make(*fContext, line,
John Stiles5abb9e12021-04-06 13:47:19 -0400352 *ctor.type().clone(symbolTableForExpression),
353 expr(ctor.argument()));
354 }
John Stilesfd7252f2021-04-04 22:24:40 -0400355 case Expression::Kind::kConstructorScalarCast: {
356 const ConstructorScalarCast& ctor = expression.as<ConstructorScalarCast>();
Ethan Nicholas89cfde12021-09-27 11:20:34 -0400357 return ConstructorScalarCast::Make(*fContext, line,
John Stilesfd7252f2021-04-04 22:24:40 -0400358 *ctor.type().clone(symbolTableForExpression),
359 expr(ctor.argument()));
360 }
John Stiles2938eea2021-04-01 18:58:25 -0400361 case Expression::Kind::kConstructorSplat: {
362 const ConstructorSplat& ctor = expression.as<ConstructorSplat>();
Ethan Nicholas89cfde12021-09-27 11:20:34 -0400363 return ConstructorSplat::Make(*fContext, line,
John Stiles2938eea2021-04-01 18:58:25 -0400364 *ctor.type().clone(symbolTableForExpression),
365 expr(ctor.argument()));
366 }
John Stilesd47330f2021-04-08 23:25:52 -0400367 case Expression::Kind::kConstructorStruct: {
368 const ConstructorStruct& ctor = expression.as<ConstructorStruct>();
Ethan Nicholas89cfde12021-09-27 11:20:34 -0400369 return ConstructorStruct::Make(*fContext, line,
John Stilesd47330f2021-04-08 23:25:52 -0400370 *ctor.type().clone(symbolTableForExpression),
371 argList(ctor.arguments()));
372 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400373 case Expression::Kind::kExternalFunctionCall: {
John Stiles44e96be2020-08-31 13:16:04 -0400374 const ExternalFunctionCall& externalCall = expression.as<ExternalFunctionCall>();
Ethan Nicholas89cfde12021-09-27 11:20:34 -0400375 return std::make_unique<ExternalFunctionCall>(line, &externalCall.function(),
Ethan Nicholas6e86ec92020-09-30 14:29:56 -0400376 argList(externalCall.arguments()));
John Stiles44e96be2020-08-31 13:16:04 -0400377 }
Brian Osmanbe0b3b72021-01-06 14:27:35 -0500378 case Expression::Kind::kExternalFunctionReference:
John Stiles44e96be2020-08-31 13:16:04 -0400379 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400380 case Expression::Kind::kFieldAccess: {
John Stiles44e96be2020-08-31 13:16:04 -0400381 const FieldAccess& f = expression.as<FieldAccess>();
John Stiles06d600f2021-03-08 09:18:21 -0500382 return FieldAccess::Make(*fContext, expr(f.base()), f.fieldIndex(), f.ownerKind());
John Stiles44e96be2020-08-31 13:16:04 -0400383 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400384 case Expression::Kind::kFunctionCall: {
John Stiles44e96be2020-08-31 13:16:04 -0400385 const FunctionCall& funcCall = expression.as<FunctionCall>();
John Stilescd7ba502021-03-19 10:54:59 -0400386 return FunctionCall::Make(*fContext,
Ethan Nicholas89cfde12021-09-27 11:20:34 -0400387 line,
John Stilescd7ba502021-03-19 10:54:59 -0400388 funcCall.type().clone(symbolTableForExpression),
389 funcCall.function(),
390 argList(funcCall.arguments()));
John Stiles44e96be2020-08-31 13:16:04 -0400391 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400392 case Expression::Kind::kFunctionReference:
Brian Osman2b3b35f2020-09-08 09:17:36 -0400393 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400394 case Expression::Kind::kIndex: {
John Stiles44e96be2020-08-31 13:16:04 -0400395 const IndexExpression& idx = expression.as<IndexExpression>();
John Stiles51d33982021-03-08 09:18:07 -0500396 return IndexExpression::Make(*fContext, expr(idx.base()), expr(idx.index()));
John Stiles44e96be2020-08-31 13:16:04 -0400397 }
Brian Osman3099f792021-09-01 13:12:16 -0400398 case Expression::Kind::kMethodReference:
399 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400400 case Expression::Kind::kPrefix: {
John Stiles44e96be2020-08-31 13:16:04 -0400401 const PrefixExpression& p = expression.as<PrefixExpression>();
John Stilesb0eb20f2021-02-26 15:29:33 -0500402 return PrefixExpression::Make(*fContext, p.getOperator(), expr(p.operand()));
John Stiles44e96be2020-08-31 13:16:04 -0400403 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400404 case Expression::Kind::kPostfix: {
John Stiles44e96be2020-08-31 13:16:04 -0400405 const PostfixExpression& p = expression.as<PostfixExpression>();
John Stiles52d3b012021-02-26 15:56:48 -0500406 return PostfixExpression::Make(*fContext, expr(p.operand()), p.getOperator());
John Stiles44e96be2020-08-31 13:16:04 -0400407 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400408 case Expression::Kind::kSetting:
John Stiles44e96be2020-08-31 13:16:04 -0400409 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400410 case Expression::Kind::kSwizzle: {
John Stiles44e96be2020-08-31 13:16:04 -0400411 const Swizzle& s = expression.as<Swizzle>();
John Stiles6e88e042021-02-19 14:09:38 -0500412 return Swizzle::Make(*fContext, expr(s.base()), s.components());
John Stiles44e96be2020-08-31 13:16:04 -0400413 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400414 case Expression::Kind::kTernary: {
John Stiles44e96be2020-08-31 13:16:04 -0400415 const TernaryExpression& t = expression.as<TernaryExpression>();
John Stiles90518f72021-02-26 20:44:54 -0500416 return TernaryExpression::Make(*fContext, expr(t.test()),
417 expr(t.ifTrue()), expr(t.ifFalse()));
John Stiles44e96be2020-08-31 13:16:04 -0400418 }
Brian Osman83ba9302020-09-11 13:33:46 -0400419 case Expression::Kind::kTypeReference:
420 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400421 case Expression::Kind::kVariableReference: {
John Stiles44e96be2020-08-31 13:16:04 -0400422 const VariableReference& v = expression.as<VariableReference>();
Ethan Nicholas78686922020-10-08 06:46:27 -0400423 auto varMapIter = varMap->find(v.variable());
John Stilese41b4ee2020-09-28 12:28:16 -0400424 if (varMapIter != varMap->end()) {
Ethan Nicholas78686922020-10-08 06:46:27 -0400425 return clone_with_ref_kind(*varMapIter->second, v.refKind());
John Stiles44e96be2020-08-31 13:16:04 -0400426 }
427 return v.clone();
428 }
429 default:
430 SkASSERT(false);
431 return nullptr;
432 }
433}
434
Ethan Nicholas89cfde12021-09-27 11:20:34 -0400435std::unique_ptr<Statement> Inliner::inlineStatement(int line,
John Stiles44e96be2020-08-31 13:16:04 -0400436 VariableRewriteMap* varMap,
437 SymbolTable* symbolTableForStatement,
John Stiles77702f12020-12-17 14:38:56 -0500438 std::unique_ptr<Expression>* resultExpr,
439 ReturnComplexity returnComplexity,
Brian Osman3887a012020-09-30 13:22:27 -0400440 const Statement& statement,
441 bool isBuiltinCode) {
John Stiles44e96be2020-08-31 13:16:04 -0400442 auto stmt = [&](const std::unique_ptr<Statement>& s) -> std::unique_ptr<Statement> {
443 if (s) {
Ethan Nicholas89cfde12021-09-27 11:20:34 -0400444 return this->inlineStatement(line, varMap, symbolTableForStatement, resultExpr,
John Stiles77702f12020-12-17 14:38:56 -0500445 returnComplexity, *s, isBuiltinCode);
John Stiles44e96be2020-08-31 13:16:04 -0400446 }
447 return nullptr;
448 };
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400449 auto blockStmts = [&](const Block& block) {
John Stiles8f2a0cf2020-10-13 12:48:21 -0400450 StatementArray result;
John Stilesf4bda742020-10-14 16:57:41 -0400451 result.reserve_back(block.children().size());
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400452 for (const std::unique_ptr<Statement>& child : block.children()) {
453 result.push_back(stmt(child));
454 }
455 return result;
456 };
John Stiles44e96be2020-08-31 13:16:04 -0400457 auto expr = [&](const std::unique_ptr<Expression>& e) -> std::unique_ptr<Expression> {
458 if (e) {
Ethan Nicholas89cfde12021-09-27 11:20:34 -0400459 return this->inlineExpression(line, varMap, symbolTableForStatement, *e);
John Stiles44e96be2020-08-31 13:16:04 -0400460 }
461 return nullptr;
462 };
John Stiles031a7672020-11-13 16:13:18 -0500463
464 ++fInlinedStatementCounter;
465
Ethan Nicholase6592142020-09-08 10:22:09 -0400466 switch (statement.kind()) {
467 case Statement::Kind::kBlock: {
John Stiles44e96be2020-08-31 13:16:04 -0400468 const Block& b = statement.as<Block>();
Ethan Nicholas89cfde12021-09-27 11:20:34 -0400469 return Block::Make(line, blockStmts(b),
John Stilesbf16b6c2021-03-12 19:24:31 -0500470 SymbolTable::WrapIfBuiltin(b.symbolTable()),
471 b.isScope());
John Stiles44e96be2020-08-31 13:16:04 -0400472 }
473
Ethan Nicholase6592142020-09-08 10:22:09 -0400474 case Statement::Kind::kBreak:
475 case Statement::Kind::kContinue:
476 case Statement::Kind::kDiscard:
John Stiles44e96be2020-08-31 13:16:04 -0400477 return statement.clone();
478
Ethan Nicholase6592142020-09-08 10:22:09 -0400479 case Statement::Kind::kDo: {
John Stiles44e96be2020-08-31 13:16:04 -0400480 const DoStatement& d = statement.as<DoStatement>();
John Stilesea5822e2021-02-26 11:18:20 -0500481 return DoStatement::Make(*fContext, stmt(d.statement()), expr(d.test()));
John Stiles44e96be2020-08-31 13:16:04 -0400482 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400483 case Statement::Kind::kExpression: {
John Stiles44e96be2020-08-31 13:16:04 -0400484 const ExpressionStatement& e = statement.as<ExpressionStatement>();
John Stiles3e5871c2021-02-25 20:52:03 -0500485 return ExpressionStatement::Make(*fContext, expr(e.expression()));
John Stiles44e96be2020-08-31 13:16:04 -0400486 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400487 case Statement::Kind::kFor: {
John Stiles44e96be2020-08-31 13:16:04 -0400488 const ForStatement& f = statement.as<ForStatement>();
489 // need to ensure initializer is evaluated first so that we've already remapped its
490 // declarations by the time we evaluate test & next
Ethan Nicholas0d31ed52020-10-05 14:47:09 -0400491 std::unique_ptr<Statement> initializer = stmt(f.initializer());
John Stiles9c975c52021-08-31 10:18:57 -0400492 // We can't reuse the unroll info from the original for loop, because it uses a
493 // different induction variable. Ours is a clone.
Ethan Nicholas89cfde12021-09-27 11:20:34 -0400494 return ForStatement::Make(*fContext, line, std::move(initializer), expr(f.test()),
John Stiles9c975c52021-08-31 10:18:57 -0400495 expr(f.next()), stmt(f.statement()), /*unrollInfo=*/nullptr,
John Stilesb321a072021-02-25 16:24:19 -0500496 SymbolTable::WrapIfBuiltin(f.symbols()));
John Stiles44e96be2020-08-31 13:16:04 -0400497 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400498 case Statement::Kind::kIf: {
John Stiles44e96be2020-08-31 13:16:04 -0400499 const IfStatement& i = statement.as<IfStatement>();
Ethan Nicholas89cfde12021-09-27 11:20:34 -0400500 return IfStatement::Make(*fContext, line, i.isStatic(), expr(i.test()),
John Stilescf3059e2021-02-25 14:27:02 -0500501 stmt(i.ifTrue()), stmt(i.ifFalse()));
John Stiles44e96be2020-08-31 13:16:04 -0400502 }
John Stiles98c1f822020-09-09 14:18:53 -0400503 case Statement::Kind::kInlineMarker:
Ethan Nicholase6592142020-09-08 10:22:09 -0400504 case Statement::Kind::kNop:
John Stiles44e96be2020-08-31 13:16:04 -0400505 return statement.clone();
John Stilesea5822e2021-02-26 11:18:20 -0500506
Ethan Nicholase6592142020-09-08 10:22:09 -0400507 case Statement::Kind::kReturn: {
John Stiles44e96be2020-08-31 13:16:04 -0400508 const ReturnStatement& r = statement.as<ReturnStatement>();
John Stiles77702f12020-12-17 14:38:56 -0500509 if (!r.expression()) {
John Stilesdc208472021-03-17 10:58:16 -0400510 // This function doesn't return a value. We won't inline functions with early
511 // returns, so a return statement is a no-op and can be treated as such.
512 return Nop::Make();
John Stiles44e96be2020-08-31 13:16:04 -0400513 }
John Stiles77702f12020-12-17 14:38:56 -0500514
John Stilesc5ff4862020-12-22 13:47:05 -0500515 // If a function only contains a single return, and it doesn't reference variables from
516 // inside an Block's scope, we don't need to store the result in a variable at all. Just
517 // replace the function-call expression with the function's return expression.
John Stiles77702f12020-12-17 14:38:56 -0500518 SkASSERT(resultExpr);
John Stilesc5ff4862020-12-22 13:47:05 -0500519 if (returnComplexity <= ReturnComplexity::kSingleSafeReturn) {
John Stiles77702f12020-12-17 14:38:56 -0500520 *resultExpr = expr(r.expression());
John Stilesa0c04d62021-03-11 23:07:24 -0500521 return Nop::Make();
John Stiles77702f12020-12-17 14:38:56 -0500522 }
523
524 // For more complex functions, assign their result into a variable.
John Stiles511c5002021-02-25 11:17:02 -0500525 SkASSERT(*resultExpr);
John Stiles3e5871c2021-02-25 20:52:03 -0500526 auto assignment = ExpressionStatement::Make(
527 *fContext,
John Stilese2aec432021-03-01 09:27:48 -0500528 BinaryExpression::Make(
529 *fContext,
530 clone_with_ref_kind(**resultExpr, VariableRefKind::kWrite),
John Stiles77702f12020-12-17 14:38:56 -0500531 Token::Kind::TK_EQ,
John Stilese2aec432021-03-01 09:27:48 -0500532 expr(r.expression())));
John Stiles77702f12020-12-17 14:38:56 -0500533
John Stiles77702f12020-12-17 14:38:56 -0500534 // Functions without early returns aren't wrapped in a for loop and don't need to worry
535 // about breaking out of the control flow.
John Stiles3e5871c2021-02-25 20:52:03 -0500536 return assignment;
John Stiles44e96be2020-08-31 13:16:04 -0400537 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400538 case Statement::Kind::kSwitch: {
John Stiles44e96be2020-08-31 13:16:04 -0400539 const SwitchStatement& ss = statement.as<SwitchStatement>();
John Stilesb23a64b2021-03-11 08:27:59 -0500540 StatementArray cases;
541 cases.reserve_back(ss.cases().size());
John Stiles628777c2021-08-04 22:07:41 -0400542 for (const std::unique_ptr<Statement>& switchCaseStmt : ss.cases()) {
543 const SwitchCase& sc = switchCaseStmt->as<SwitchCase>();
Ethan Nicholas89cfde12021-09-27 11:20:34 -0400544 cases.push_back(std::make_unique<SwitchCase>(line, expr(sc.value()),
John Stilesb23a64b2021-03-11 08:27:59 -0500545 stmt(sc.statement())));
John Stiles44e96be2020-08-31 13:16:04 -0400546 }
Ethan Nicholas89cfde12021-09-27 11:20:34 -0400547 return SwitchStatement::Make(*fContext, line, ss.isStatic(), expr(ss.value()),
John Stilese1d1b082021-02-23 13:44:36 -0500548 std::move(cases), SymbolTable::WrapIfBuiltin(ss.symbols()));
John Stiles44e96be2020-08-31 13:16:04 -0400549 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400550 case Statement::Kind::kVarDeclaration: {
John Stiles44e96be2020-08-31 13:16:04 -0400551 const VarDeclaration& decl = statement.as<VarDeclaration>();
John Stiles35fee4c2020-12-16 18:25:14 +0000552 std::unique_ptr<Expression> initialValue = expr(decl.value());
John Stilesddcc8432021-01-15 15:32:32 -0500553 const Variable& variable = decl.var();
554
John Stiles35fee4c2020-12-16 18:25:14 +0000555 // We assign unique names to inlined variables--scopes hide most of the problems in this
556 // regard, but see `InlinerAvoidsVariableNameOverlap` for a counterexample where unique
557 // names are important.
John Stilesd51c9792021-03-18 11:40:14 -0400558 const String* name = symbolTableForStatement->takeOwnershipOfString(
John Stiles2dda4b62021-09-16 13:18:10 -0400559 fContext->fMangler->uniqueName(variable.name(), symbolTableForStatement));
Ethan Nicholas5b9b0db2021-01-21 13:12:01 -0500560 auto clonedVar = std::make_unique<Variable>(
Ethan Nicholas89cfde12021-09-27 11:20:34 -0400561 line,
Ethan Nicholas5b9b0db2021-01-21 13:12:01 -0500562 &variable.modifiers(),
John Stilesd51c9792021-03-18 11:40:14 -0400563 name->c_str(),
Ethan Nicholas5b9b0db2021-01-21 13:12:01 -0500564 variable.type().clone(symbolTableForStatement),
565 isBuiltinCode,
566 variable.storage());
Ethan Nicholas89cfde12021-09-27 11:20:34 -0400567 (*varMap)[&variable] = VariableReference::Make(line, clonedVar.get());
John Stilese67bd132021-03-19 18:39:25 -0400568 auto result = VarDeclaration::Make(*fContext,
569 clonedVar.get(),
570 decl.baseType().clone(symbolTableForStatement),
571 decl.arraySize(),
572 std::move(initialValue));
Ethan Nicholas5b9b0db2021-01-21 13:12:01 -0500573 symbolTableForStatement->takeOwnershipOfSymbol(std::move(clonedVar));
John Stilese67bd132021-03-19 18:39:25 -0400574 return result;
John Stiles44e96be2020-08-31 13:16:04 -0400575 }
John Stiles44e96be2020-08-31 13:16:04 -0400576 default:
577 SkASSERT(false);
578 return nullptr;
579 }
580}
581
John Stiles6eadf132020-09-08 10:16:10 -0400582Inliner::InlinedCall Inliner::inlineCall(FunctionCall* call,
John Stiles78047582020-12-16 16:17:41 -0500583 std::shared_ptr<SymbolTable> symbolTable,
John Stiles30fce9c2021-03-18 09:24:06 -0400584 const ProgramUsage& usage,
Brian Osman3887a012020-09-30 13:22:27 -0400585 const FunctionDeclaration* caller) {
John Stiles941812f2021-09-16 15:12:02 -0400586 using ScratchVariable = Variable::ScratchVariable;
587
John Stiles44e96be2020-08-31 13:16:04 -0400588 // Inlining is more complicated here than in a typical compiler, because we have to have a
589 // high-level IR and can't just drop statements into the middle of an expression or even use
590 // gotos.
591 //
592 // Since we can't insert statements into an expression, we run the inline function as extra
593 // statements before the statement we're currently processing, relying on a lack of execution
594 // order guarantees. Since we can't use gotos (which are normally used to replace return
595 // statements), we wrap the whole function in a loop and use break statements to jump to the
596 // end.
John Stiles44e96be2020-08-31 13:16:04 -0400597 SkASSERT(fContext);
598 SkASSERT(call);
Ethan Nicholased84b732020-10-08 11:45:44 -0400599 SkASSERT(this->isSafeToInline(call->function().definition()));
John Stiles44e96be2020-08-31 13:16:04 -0400600
John Stiles8e3b6be2020-10-13 11:14:08 -0400601 ExpressionArray& arguments = call->arguments();
Ethan Nicholas89cfde12021-09-27 11:20:34 -0400602 const int line = call->fLine;
Ethan Nicholased84b732020-10-08 11:45:44 -0400603 const FunctionDefinition& function = *call->function().definition();
John Stiles28257db2021-03-17 15:18:09 -0400604 const Block& body = function.body()->as<Block>();
John Stiles77702f12020-12-17 14:38:56 -0500605 const ReturnComplexity returnComplexity = GetReturnComplexity(function);
John Stiles6eadf132020-09-08 10:16:10 -0400606
John Stiles28257db2021-03-17 15:18:09 -0400607 StatementArray inlineStatements;
608 int expectedStmtCount = 1 + // Inline marker
609 1 + // Result variable
610 arguments.size() + // Function argument temp-vars
611 body.children().size(); // Inlined code
John Stiles98c1f822020-09-09 14:18:53 -0400612
John Stiles28257db2021-03-17 15:18:09 -0400613 inlineStatements.reserve_back(expectedStmtCount);
614 inlineStatements.push_back(InlineMarker::Make(&call->function()));
John Stiles44e96be2020-08-31 13:16:04 -0400615
John Stilese41b4ee2020-09-28 12:28:16 -0400616 std::unique_ptr<Expression> resultExpr;
John Stiles511c5002021-02-25 11:17:02 -0500617 if (returnComplexity > ReturnComplexity::kSingleSafeReturn &&
John Stiles2558c462021-03-16 17:49:20 -0400618 !function.declaration().returnType().isVoid()) {
John Stiles511c5002021-02-25 11:17:02 -0500619 // Create a variable to hold the result in the extra statements. We don't need to do this
620 // for void-return functions, or in cases that are simple enough that we can just replace
621 // the function-call node with the result expression.
John Stiles941812f2021-09-16 15:12:02 -0400622 ScratchVariable var = Variable::MakeScratchVariable(*fContext,
623 function.declaration().name(),
624 &function.declaration().returnType(),
625 Modifiers{},
626 symbolTable.get(),
627 /*initialValue=*/nullptr);
John Stiles28257db2021-03-17 15:18:09 -0400628 inlineStatements.push_back(std::move(var.fVarDecl));
Ethan Nicholas89cfde12021-09-27 11:20:34 -0400629 resultExpr = VariableReference::Make(/*line=*/-1, var.fVarSymbol);
John Stiles511c5002021-02-25 11:17:02 -0500630 }
John Stiles44e96be2020-08-31 13:16:04 -0400631
632 // Create variables in the extra statements to hold the arguments, and assign the arguments to
633 // them.
634 VariableRewriteMap varMap;
John Stilesbff24ab2021-03-17 13:20:10 -0400635 for (int i = 0; i < arguments.count(); ++i) {
John Stiles049f0df2021-03-19 09:39:44 -0400636 // If the parameter isn't written to within the inline function ...
John Stiles941812f2021-09-16 15:12:02 -0400637 Expression* arg = arguments[i].get();
John Stilesbff24ab2021-03-17 13:20:10 -0400638 const Variable* param = function.declaration().parameters()[i];
John Stiles049f0df2021-03-19 09:39:44 -0400639 const ProgramUsage::VariableCounts& paramUsage = usage.get(*param);
640 if (!paramUsage.fWrite) {
641 // ... and can be inlined trivially (e.g. a swizzle, or a constant array index),
642 // or any expression without side effects that is only accessed at most once...
John Stiles941812f2021-09-16 15:12:02 -0400643 if ((paramUsage.fRead > 1) ? Analysis::IsTrivialExpression(*arg)
644 : !arg->hasSideEffects()) {
John Stilesf201af82020-09-29 16:57:55 -0400645 // ... we don't need to copy it at all! We can just use the existing expression.
John Stiles941812f2021-09-16 15:12:02 -0400646 varMap[param] = arg->clone();
John Stiles44e96be2020-08-31 13:16:04 -0400647 continue;
648 }
649 }
John Stiles941812f2021-09-16 15:12:02 -0400650 ScratchVariable var = Variable::MakeScratchVariable(*fContext,
651 param->name(),
652 &arg->type(),
653 param->modifiers(),
654 symbolTable.get(),
655 std::move(arguments[i]));
John Stiles28257db2021-03-17 15:18:09 -0400656 inlineStatements.push_back(std::move(var.fVarDecl));
Ethan Nicholas89cfde12021-09-27 11:20:34 -0400657 varMap[param] = VariableReference::Make(/*line=*/-1, var.fVarSymbol);
John Stiles44e96be2020-08-31 13:16:04 -0400658 }
659
John Stiles7b920442020-12-17 10:43:41 -0500660 for (const std::unique_ptr<Statement>& stmt : body.children()) {
Ethan Nicholas89cfde12021-09-27 11:20:34 -0400661 inlineStatements.push_back(this->inlineStatement(line, &varMap, symbolTable.get(),
John Stiles28257db2021-03-17 15:18:09 -0400662 &resultExpr, returnComplexity, *stmt,
663 caller->isBuiltin()));
John Stiles44e96be2020-08-31 13:16:04 -0400664 }
665
John Stiles28257db2021-03-17 15:18:09 -0400666 SkASSERT(inlineStatements.count() <= expectedStmtCount);
667
John Stilesbf16b6c2021-03-12 19:24:31 -0500668 // Wrap all of the generated statements in a block. We need a real Block here, so we can't use
669 // MakeUnscoped. This is because we need to add another child statement to the Block later.
John Stiles28257db2021-03-17 15:18:09 -0400670 InlinedCall inlinedCall;
Ethan Nicholas89cfde12021-09-27 11:20:34 -0400671 inlinedCall.fInlinedBody = Block::Make(line, std::move(inlineStatements),
John Stilesbf16b6c2021-03-12 19:24:31 -0500672 /*symbols=*/nullptr, /*isScope=*/false);
673
John Stiles0c2d14a2021-03-01 10:08:08 -0500674 if (resultExpr) {
675 // Return our result expression as-is.
John Stilese41b4ee2020-09-28 12:28:16 -0400676 inlinedCall.fReplacementExpr = std::move(resultExpr);
John Stiles2558c462021-03-16 17:49:20 -0400677 } else if (function.declaration().returnType().isVoid()) {
John Stiles44e96be2020-08-31 13:16:04 -0400678 // It's a void function, so it doesn't actually result in anything, but we have to return
679 // something non-null as a standin.
Ethan Nicholas89cfde12021-09-27 11:20:34 -0400680 inlinedCall.fReplacementExpr = Literal::MakeBool(*fContext, line, /*value=*/false);
John Stiles0c2d14a2021-03-01 10:08:08 -0500681 } else {
682 // It's a non-void function, but it never created a result expression--that is, it never
John Stiles2dda50d2021-03-03 10:46:44 -0500683 // returned anything on any path! This should have been detected in the function finalizer.
684 // Still, discard our output and generate an error.
685 SkDEBUGFAIL("inliner found non-void function that fails to return a value on any path");
Ethan Nicholas89cfde12021-09-27 11:20:34 -0400686 fContext->fErrors->error(function.fLine, "inliner found non-void function '" +
687 function.declaration().name() +
688 "' that fails to return a value on any path");
John Stiles0c2d14a2021-03-01 10:08:08 -0500689 inlinedCall = {};
John Stiles44e96be2020-08-31 13:16:04 -0400690 }
691
John Stiles44e96be2020-08-31 13:16:04 -0400692 return inlinedCall;
693}
694
John Stiles2d7973a2020-10-02 15:01:03 -0400695bool Inliner::isSafeToInline(const FunctionDefinition* functionDef) {
John Stiles1c03d332020-10-13 10:30:23 -0400696 // A threshold of zero indicates that the inliner is completely disabled, so we can just return.
John Stilesd1204642021-02-17 16:30:02 -0500697 if (this->settings().fInlineThreshold <= 0) {
John Stiles1c03d332020-10-13 10:30:23 -0400698 return false;
699 }
700
John Stiles031a7672020-11-13 16:13:18 -0500701 // Enforce a limit on inlining to avoid pathological cases. (inliner/ExponentialGrowth.sksl)
702 if (fInlinedStatementCounter >= kInlinedStatementLimit) {
703 return false;
704 }
705
John Stiles2d7973a2020-10-02 15:01:03 -0400706 if (functionDef == nullptr) {
John Stiles44e96be2020-08-31 13:16:04 -0400707 // Can't inline something if we don't actually have its definition.
708 return false;
709 }
John Stiles2d7973a2020-10-02 15:01:03 -0400710
John Stiles0dd1a772021-03-09 22:14:27 -0500711 if (functionDef->declaration().modifiers().fFlags & Modifiers::kNoInline_Flag) {
712 // Refuse to inline functions decorated with `noinline`.
713 return false;
714 }
715
John Stilesbff24ab2021-03-17 13:20:10 -0400716 // We don't allow inlining a function with out parameters. (See skia:11326 for rationale.)
717 for (const Variable* param : functionDef->declaration().parameters()) {
718 if (param->modifiers().fFlags & Modifiers::Flag::kOut_Flag) {
719 return false;
720 }
721 }
722
John Stilesdc208472021-03-17 10:58:16 -0400723 // We don't have a mechanism to simulate early returns, so we can't inline if there is one.
724 return GetReturnComplexity(*functionDef) < ReturnComplexity::kEarlyReturns;
John Stiles44e96be2020-08-31 13:16:04 -0400725}
726
John Stiles2d7973a2020-10-02 15:01:03 -0400727// A candidate function for inlining, containing everything that `inlineCall` needs.
728struct InlineCandidate {
John Stiles78047582020-12-16 16:17:41 -0500729 std::shared_ptr<SymbolTable> fSymbols; // the SymbolTable of the candidate
John Stiles2d7973a2020-10-02 15:01:03 -0400730 std::unique_ptr<Statement>* fParentStmt; // the parent Statement of the enclosing stmt
731 std::unique_ptr<Statement>* fEnclosingStmt; // the Statement containing the candidate
732 std::unique_ptr<Expression>* fCandidateExpr; // the candidate FunctionCall to be inlined
733 FunctionDefinition* fEnclosingFunction; // the Function containing the candidate
John Stiles2d7973a2020-10-02 15:01:03 -0400734};
John Stiles93442622020-09-11 12:11:27 -0400735
John Stiles2d7973a2020-10-02 15:01:03 -0400736struct InlineCandidateList {
737 std::vector<InlineCandidate> fCandidates;
738};
739
740class InlineCandidateAnalyzer {
John Stiles70957c82020-10-02 16:42:10 -0400741public:
742 // A list of all the inlining candidates we found during analysis.
743 InlineCandidateList* fCandidateList;
John Stiles2d7973a2020-10-02 15:01:03 -0400744
John Stiles70957c82020-10-02 16:42:10 -0400745 // A stack of the symbol tables; since most nodes don't have one, expected to be shallower than
746 // the enclosing-statement stack.
John Stiles78047582020-12-16 16:17:41 -0500747 std::vector<std::shared_ptr<SymbolTable>> fSymbolTableStack;
John Stiles70957c82020-10-02 16:42:10 -0400748 // A stack of "enclosing" statements--these would be suitable for the inliner to use for adding
749 // new instructions. Not all statements are suitable (e.g. a for-loop's initializer). The
750 // inliner might replace a statement with a block containing the statement.
751 std::vector<std::unique_ptr<Statement>*> fEnclosingStmtStack;
752 // The function that we're currently processing (i.e. inlining into).
753 FunctionDefinition* fEnclosingFunction = nullptr;
John Stiles93442622020-09-11 12:11:27 -0400754
Brian Osman0006ad02020-11-18 15:38:39 -0500755 void visit(const std::vector<std::unique_ptr<ProgramElement>>& elements,
John Stiles78047582020-12-16 16:17:41 -0500756 std::shared_ptr<SymbolTable> symbols,
Brian Osman0006ad02020-11-18 15:38:39 -0500757 InlineCandidateList* candidateList) {
John Stiles70957c82020-10-02 16:42:10 -0400758 fCandidateList = candidateList;
Brian Osman0006ad02020-11-18 15:38:39 -0500759 fSymbolTableStack.push_back(symbols);
John Stiles93442622020-09-11 12:11:27 -0400760
Brian Osman0006ad02020-11-18 15:38:39 -0500761 for (const std::unique_ptr<ProgramElement>& pe : elements) {
Brian Osman1179fcf2020-10-08 16:04:40 -0400762 this->visitProgramElement(pe.get());
John Stiles93442622020-09-11 12:11:27 -0400763 }
764
John Stiles70957c82020-10-02 16:42:10 -0400765 fSymbolTableStack.pop_back();
766 fCandidateList = nullptr;
767 }
768
769 void visitProgramElement(ProgramElement* pe) {
770 switch (pe->kind()) {
771 case ProgramElement::Kind::kFunction: {
772 FunctionDefinition& funcDef = pe->as<FunctionDefinition>();
Brian Osman0006ad02020-11-18 15:38:39 -0500773 fEnclosingFunction = &funcDef;
774 this->visitStatement(&funcDef.body());
John Stiles70957c82020-10-02 16:42:10 -0400775 break;
John Stiles93442622020-09-11 12:11:27 -0400776 }
John Stiles70957c82020-10-02 16:42:10 -0400777 default:
778 // The inliner can't operate outside of a function's scope.
779 break;
780 }
781 }
782
783 void visitStatement(std::unique_ptr<Statement>* stmt,
784 bool isViableAsEnclosingStatement = true) {
785 if (!*stmt) {
786 return;
John Stiles93442622020-09-11 12:11:27 -0400787 }
788
John Stiles70957c82020-10-02 16:42:10 -0400789 size_t oldEnclosingStmtStackSize = fEnclosingStmtStack.size();
790 size_t oldSymbolStackSize = fSymbolTableStack.size();
John Stiles93442622020-09-11 12:11:27 -0400791
John Stiles70957c82020-10-02 16:42:10 -0400792 if (isViableAsEnclosingStatement) {
793 fEnclosingStmtStack.push_back(stmt);
John Stiles93442622020-09-11 12:11:27 -0400794 }
795
John Stiles70957c82020-10-02 16:42:10 -0400796 switch ((*stmt)->kind()) {
797 case Statement::Kind::kBreak:
798 case Statement::Kind::kContinue:
799 case Statement::Kind::kDiscard:
800 case Statement::Kind::kInlineMarker:
801 case Statement::Kind::kNop:
802 break;
803
804 case Statement::Kind::kBlock: {
805 Block& block = (*stmt)->as<Block>();
806 if (block.symbolTable()) {
John Stiles78047582020-12-16 16:17:41 -0500807 fSymbolTableStack.push_back(block.symbolTable());
John Stiles70957c82020-10-02 16:42:10 -0400808 }
809
John Stiles628777c2021-08-04 22:07:41 -0400810 for (std::unique_ptr<Statement>& blockStmt : block.children()) {
811 this->visitStatement(&blockStmt);
John Stiles70957c82020-10-02 16:42:10 -0400812 }
813 break;
John Stiles93442622020-09-11 12:11:27 -0400814 }
John Stiles70957c82020-10-02 16:42:10 -0400815 case Statement::Kind::kDo: {
816 DoStatement& doStmt = (*stmt)->as<DoStatement>();
817 // The loop body is a candidate for inlining.
818 this->visitStatement(&doStmt.statement());
819 // The inliner isn't smart enough to inline the test-expression for a do-while
820 // loop at this time. There are two limitations:
821 // - We would need to insert the inlined-body block at the very end of the do-
822 // statement's inner fStatement. We don't support that today, but it's doable.
823 // - We cannot inline the test expression if the loop uses `continue` anywhere; that
824 // would skip over the inlined block that evaluates the test expression. There
825 // isn't a good fix for this--any workaround would be more complex than the cost
826 // of a function call. However, loops that don't use `continue` would still be
827 // viable candidates for inlining.
828 break;
John Stiles93442622020-09-11 12:11:27 -0400829 }
John Stiles70957c82020-10-02 16:42:10 -0400830 case Statement::Kind::kExpression: {
831 ExpressionStatement& expr = (*stmt)->as<ExpressionStatement>();
832 this->visitExpression(&expr.expression());
833 break;
834 }
835 case Statement::Kind::kFor: {
836 ForStatement& forStmt = (*stmt)->as<ForStatement>();
Ethan Nicholas0d31ed52020-10-05 14:47:09 -0400837 if (forStmt.symbols()) {
John Stiles78047582020-12-16 16:17:41 -0500838 fSymbolTableStack.push_back(forStmt.symbols());
John Stiles70957c82020-10-02 16:42:10 -0400839 }
840
841 // The initializer and loop body are candidates for inlining.
Ethan Nicholas0d31ed52020-10-05 14:47:09 -0400842 this->visitStatement(&forStmt.initializer(),
John Stiles70957c82020-10-02 16:42:10 -0400843 /*isViableAsEnclosingStatement=*/false);
Ethan Nicholas0d31ed52020-10-05 14:47:09 -0400844 this->visitStatement(&forStmt.statement());
John Stiles70957c82020-10-02 16:42:10 -0400845
846 // The inliner isn't smart enough to inline the test- or increment-expressions
847 // of a for loop loop at this time. There are a handful of limitations:
848 // - We would need to insert the test-expression block at the very beginning of the
849 // for-loop's inner fStatement, and the increment-expression block at the very
850 // end. We don't support that today, but it's doable.
851 // - The for-loop's built-in test-expression would need to be dropped entirely,
852 // and the loop would be halted via a break statement at the end of the inlined
853 // test-expression. This is again something we don't support today, but it could
854 // be implemented.
855 // - We cannot inline the increment-expression if the loop uses `continue` anywhere;
856 // that would skip over the inlined block that evaluates the increment expression.
857 // There isn't a good fix for this--any workaround would be more complex than the
858 // cost of a function call. However, loops that don't use `continue` would still
859 // be viable candidates for increment-expression inlining.
860 break;
861 }
862 case Statement::Kind::kIf: {
863 IfStatement& ifStmt = (*stmt)->as<IfStatement>();
Ethan Nicholas8c44eca2020-10-07 16:47:09 -0400864 this->visitExpression(&ifStmt.test());
865 this->visitStatement(&ifStmt.ifTrue());
866 this->visitStatement(&ifStmt.ifFalse());
John Stiles70957c82020-10-02 16:42:10 -0400867 break;
868 }
869 case Statement::Kind::kReturn: {
870 ReturnStatement& returnStmt = (*stmt)->as<ReturnStatement>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -0400871 this->visitExpression(&returnStmt.expression());
John Stiles70957c82020-10-02 16:42:10 -0400872 break;
873 }
874 case Statement::Kind::kSwitch: {
875 SwitchStatement& switchStmt = (*stmt)->as<SwitchStatement>();
Ethan Nicholas01b05e52020-10-22 15:53:41 -0400876 if (switchStmt.symbols()) {
John Stiles78047582020-12-16 16:17:41 -0500877 fSymbolTableStack.push_back(switchStmt.symbols());
John Stiles70957c82020-10-02 16:42:10 -0400878 }
879
Ethan Nicholas01b05e52020-10-22 15:53:41 -0400880 this->visitExpression(&switchStmt.value());
John Stilesb23a64b2021-03-11 08:27:59 -0500881 for (const std::unique_ptr<Statement>& switchCase : switchStmt.cases()) {
John Stiles70957c82020-10-02 16:42:10 -0400882 // The switch-case's fValue cannot be a FunctionCall; skip it.
John Stilesb23a64b2021-03-11 08:27:59 -0500883 this->visitStatement(&switchCase->as<SwitchCase>().statement());
John Stiles70957c82020-10-02 16:42:10 -0400884 }
885 break;
886 }
887 case Statement::Kind::kVarDeclaration: {
888 VarDeclaration& varDeclStmt = (*stmt)->as<VarDeclaration>();
889 // Don't need to scan the declaration's sizes; those are always IntLiterals.
Ethan Nicholasc51f33e2020-10-13 13:49:44 -0400890 this->visitExpression(&varDeclStmt.value());
John Stiles70957c82020-10-02 16:42:10 -0400891 break;
892 }
John Stiles70957c82020-10-02 16:42:10 -0400893 default:
894 SkUNREACHABLE;
John Stiles93442622020-09-11 12:11:27 -0400895 }
896
John Stiles70957c82020-10-02 16:42:10 -0400897 // Pop our symbol and enclosing-statement stacks.
898 fSymbolTableStack.resize(oldSymbolStackSize);
899 fEnclosingStmtStack.resize(oldEnclosingStmtStackSize);
900 }
901
902 void visitExpression(std::unique_ptr<Expression>* expr) {
903 if (!*expr) {
904 return;
John Stiles93442622020-09-11 12:11:27 -0400905 }
John Stiles70957c82020-10-02 16:42:10 -0400906
907 switch ((*expr)->kind()) {
Brian Osmanbe0b3b72021-01-06 14:27:35 -0500908 case Expression::Kind::kExternalFunctionReference:
John Stiles70957c82020-10-02 16:42:10 -0400909 case Expression::Kind::kFieldAccess:
John Stiles70957c82020-10-02 16:42:10 -0400910 case Expression::Kind::kFunctionReference:
John Stiles7591d4b2021-09-13 13:32:06 -0400911 case Expression::Kind::kLiteral:
Brian Osman3099f792021-09-01 13:12:16 -0400912 case Expression::Kind::kMethodReference:
John Stiles70957c82020-10-02 16:42:10 -0400913 case Expression::Kind::kSetting:
914 case Expression::Kind::kTypeReference:
915 case Expression::Kind::kVariableReference:
916 // Nothing to scan here.
917 break;
918
919 case Expression::Kind::kBinary: {
920 BinaryExpression& binaryExpr = (*expr)->as<BinaryExpression>();
John Stiles2d4f9592020-10-30 10:29:12 -0400921 this->visitExpression(&binaryExpr.left());
John Stiles70957c82020-10-02 16:42:10 -0400922
923 // Logical-and and logical-or binary expressions do not inline the right side,
924 // because that would invalidate short-circuiting. That is, when evaluating
925 // expressions like these:
926 // (false && x()) // always false
927 // (true || y()) // always true
928 // It is illegal for side-effects from x() or y() to occur. The simplest way to
929 // enforce that rule is to avoid inlining the right side entirely. However, it is
930 // safe for other types of binary expression to inline both sides.
John Stiles45990502021-02-16 10:55:27 -0500931 Operator op = binaryExpr.getOperator();
932 bool shortCircuitable = (op.kind() == Token::Kind::TK_LOGICALAND ||
933 op.kind() == Token::Kind::TK_LOGICALOR);
John Stiles70957c82020-10-02 16:42:10 -0400934 if (!shortCircuitable) {
John Stiles2d4f9592020-10-30 10:29:12 -0400935 this->visitExpression(&binaryExpr.right());
John Stiles70957c82020-10-02 16:42:10 -0400936 }
937 break;
938 }
Brian Osmaneb0f29d2021-08-04 11:34:16 -0400939 case Expression::Kind::kChildCall: {
940 ChildCall& childCallExpr = (*expr)->as<ChildCall>();
941 for (std::unique_ptr<Expression>& arg : childCallExpr.arguments()) {
942 this->visitExpression(&arg);
943 }
944 break;
945 }
John Stiles7384b372021-04-01 13:48:15 -0400946 case Expression::Kind::kConstructorArray:
John Stilese3ae9682021-08-05 10:35:01 -0400947 case Expression::Kind::kConstructorArrayCast:
John Stiles8cad6372021-04-07 12:31:13 -0400948 case Expression::Kind::kConstructorCompound:
949 case Expression::Kind::kConstructorCompoundCast:
John Stiles2938eea2021-04-01 18:58:25 -0400950 case Expression::Kind::kConstructorDiagonalMatrix:
John Stiles5abb9e12021-04-06 13:47:19 -0400951 case Expression::Kind::kConstructorMatrixResize:
John Stilesfd7252f2021-04-04 22:24:40 -0400952 case Expression::Kind::kConstructorScalarCast:
John Stilesd47330f2021-04-08 23:25:52 -0400953 case Expression::Kind::kConstructorSplat:
954 case Expression::Kind::kConstructorStruct: {
John Stiles7384b372021-04-01 13:48:15 -0400955 AnyConstructor& constructorExpr = (*expr)->asAnyConstructor();
956 for (std::unique_ptr<Expression>& arg : constructorExpr.argumentSpan()) {
John Stiles70957c82020-10-02 16:42:10 -0400957 this->visitExpression(&arg);
958 }
959 break;
960 }
961 case Expression::Kind::kExternalFunctionCall: {
962 ExternalFunctionCall& funcCallExpr = (*expr)->as<ExternalFunctionCall>();
963 for (std::unique_ptr<Expression>& arg : funcCallExpr.arguments()) {
964 this->visitExpression(&arg);
965 }
966 break;
967 }
968 case Expression::Kind::kFunctionCall: {
969 FunctionCall& funcCallExpr = (*expr)->as<FunctionCall>();
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400970 for (std::unique_ptr<Expression>& arg : funcCallExpr.arguments()) {
John Stiles70957c82020-10-02 16:42:10 -0400971 this->visitExpression(&arg);
972 }
973 this->addInlineCandidate(expr);
974 break;
975 }
John Stiles708faba2021-03-19 09:43:23 -0400976 case Expression::Kind::kIndex: {
John Stiles70957c82020-10-02 16:42:10 -0400977 IndexExpression& indexExpr = (*expr)->as<IndexExpression>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -0400978 this->visitExpression(&indexExpr.base());
979 this->visitExpression(&indexExpr.index());
John Stiles70957c82020-10-02 16:42:10 -0400980 break;
981 }
982 case Expression::Kind::kPostfix: {
983 PostfixExpression& postfixExpr = (*expr)->as<PostfixExpression>();
Ethan Nicholas444ccc62020-10-09 10:16:22 -0400984 this->visitExpression(&postfixExpr.operand());
John Stiles70957c82020-10-02 16:42:10 -0400985 break;
986 }
987 case Expression::Kind::kPrefix: {
988 PrefixExpression& prefixExpr = (*expr)->as<PrefixExpression>();
Ethan Nicholas444ccc62020-10-09 10:16:22 -0400989 this->visitExpression(&prefixExpr.operand());
John Stiles70957c82020-10-02 16:42:10 -0400990 break;
991 }
992 case Expression::Kind::kSwizzle: {
993 Swizzle& swizzleExpr = (*expr)->as<Swizzle>();
Ethan Nicholas6b4d5812020-10-12 16:11:51 -0400994 this->visitExpression(&swizzleExpr.base());
John Stiles70957c82020-10-02 16:42:10 -0400995 break;
996 }
997 case Expression::Kind::kTernary: {
998 TernaryExpression& ternaryExpr = (*expr)->as<TernaryExpression>();
999 // The test expression is a candidate for inlining.
Ethan Nicholasdd218162020-10-08 05:48:01 -04001000 this->visitExpression(&ternaryExpr.test());
John Stiles70957c82020-10-02 16:42:10 -04001001 // The true- and false-expressions cannot be inlined, because we are only allowed to
1002 // evaluate one side.
1003 break;
1004 }
1005 default:
1006 SkUNREACHABLE;
1007 }
1008 }
1009
1010 void addInlineCandidate(std::unique_ptr<Expression>* candidate) {
1011 fCandidateList->fCandidates.push_back(
1012 InlineCandidate{fSymbolTableStack.back(),
1013 find_parent_statement(fEnclosingStmtStack),
1014 fEnclosingStmtStack.back(),
1015 candidate,
John Stiles9b9415e2020-11-23 14:48:06 -05001016 fEnclosingFunction});
John Stiles70957c82020-10-02 16:42:10 -04001017 }
John Stiles2d7973a2020-10-02 15:01:03 -04001018};
John Stiles93442622020-09-11 12:11:27 -04001019
John Stiles9b9415e2020-11-23 14:48:06 -05001020static const FunctionDeclaration& candidate_func(const InlineCandidate& candidate) {
1021 return (*candidate.fCandidateExpr)->as<FunctionCall>().function();
1022}
John Stiles915a38c2020-09-14 09:38:13 -04001023
John Stiles9b9415e2020-11-23 14:48:06 -05001024bool Inliner::candidateCanBeInlined(const InlineCandidate& candidate, InlinabilityCache* cache) {
1025 const FunctionDeclaration& funcDecl = candidate_func(candidate);
John Stiles1c03d332020-10-13 10:30:23 -04001026 auto [iter, wasInserted] = cache->insert({&funcDecl, false});
John Stiles2d7973a2020-10-02 15:01:03 -04001027 if (wasInserted) {
1028 // Recursion is forbidden here to avoid an infinite death spiral of inlining.
John Stiles132cfdd2021-03-15 22:08:38 +00001029 iter->second = this->isSafeToInline(funcDecl.definition()) &&
1030 !contains_recursive_call(funcDecl);
John Stiles93442622020-09-11 12:11:27 -04001031 }
1032
John Stiles2d7973a2020-10-02 15:01:03 -04001033 return iter->second;
1034}
1035
John Stiles9b9415e2020-11-23 14:48:06 -05001036int Inliner::getFunctionSize(const FunctionDeclaration& funcDecl, FunctionSizeCache* cache) {
1037 auto [iter, wasInserted] = cache->insert({&funcDecl, 0});
John Stiles2d7973a2020-10-02 15:01:03 -04001038 if (wasInserted) {
John Stiles9b9415e2020-11-23 14:48:06 -05001039 iter->second = Analysis::NodeCountUpToLimit(*funcDecl.definition(),
John Stilesd1204642021-02-17 16:30:02 -05001040 this->settings().fInlineThreshold);
John Stiles2d7973a2020-10-02 15:01:03 -04001041 }
John Stiles2d7973a2020-10-02 15:01:03 -04001042 return iter->second;
1043}
1044
Brian Osman0006ad02020-11-18 15:38:39 -05001045void Inliner::buildCandidateList(const std::vector<std::unique_ptr<ProgramElement>>& elements,
John Stiles78047582020-12-16 16:17:41 -05001046 std::shared_ptr<SymbolTable> symbols, ProgramUsage* usage,
Brian Osman0006ad02020-11-18 15:38:39 -05001047 InlineCandidateList* candidateList) {
John Stiles2d7973a2020-10-02 15:01:03 -04001048 // This is structured much like a ProgramVisitor, but does not actually use ProgramVisitor.
1049 // The analyzer needs to keep track of the `unique_ptr<T>*` of statements and expressions so
1050 // that they can later be replaced, and ProgramVisitor does not provide this; it only provides a
1051 // `const T&`.
1052 InlineCandidateAnalyzer analyzer;
Brian Osman0006ad02020-11-18 15:38:39 -05001053 analyzer.visit(elements, symbols, candidateList);
John Stiles2d7973a2020-10-02 15:01:03 -04001054
John Stiles0ad233f2020-11-25 11:02:05 -05001055 // Early out if there are no inlining candidates.
John Stiles2d7973a2020-10-02 15:01:03 -04001056 std::vector<InlineCandidate>& candidates = candidateList->fCandidates;
John Stiles0ad233f2020-11-25 11:02:05 -05001057 if (candidates.empty()) {
1058 return;
1059 }
1060
1061 // Remove candidates that are not safe to inline.
John Stiles2d7973a2020-10-02 15:01:03 -04001062 InlinabilityCache cache;
1063 candidates.erase(std::remove_if(candidates.begin(),
1064 candidates.end(),
1065 [&](const InlineCandidate& candidate) {
1066 return !this->candidateCanBeInlined(candidate, &cache);
1067 }),
1068 candidates.end());
1069
John Stiles0ad233f2020-11-25 11:02:05 -05001070 // If the inline threshold is unlimited, or if we have no candidates left, our candidate list is
1071 // complete.
John Stilesd1204642021-02-17 16:30:02 -05001072 if (this->settings().fInlineThreshold == INT_MAX || candidates.empty()) {
John Stiles0ad233f2020-11-25 11:02:05 -05001073 return;
John Stiles2d7973a2020-10-02 15:01:03 -04001074 }
John Stiles0ad233f2020-11-25 11:02:05 -05001075
1076 // Remove candidates on a per-function basis if the effect of inlining would be to make more
1077 // than `inlineThreshold` nodes. (i.e. if Func() would be inlined six times and its size is
1078 // 10 nodes, it should be inlined if the inlineThreshold is 60 or higher.)
1079 FunctionSizeCache functionSizeCache;
1080 FunctionSizeCache candidateTotalCost;
1081 for (InlineCandidate& candidate : candidates) {
1082 const FunctionDeclaration& fnDecl = candidate_func(candidate);
1083 candidateTotalCost[&fnDecl] += this->getFunctionSize(fnDecl, &functionSizeCache);
1084 }
1085
John Stilesd1204642021-02-17 16:30:02 -05001086 candidates.erase(std::remove_if(candidates.begin(), candidates.end(),
1087 [&](const InlineCandidate& candidate) {
1088 const FunctionDeclaration& fnDecl = candidate_func(candidate);
1089 if (fnDecl.modifiers().fFlags & Modifiers::kInline_Flag) {
1090 // Functions marked `inline` ignore size limitations.
1091 return false;
1092 }
1093 if (usage->get(fnDecl) == 1) {
1094 // If a function is only used once, it's cost-free to inline.
1095 return false;
1096 }
1097 if (candidateTotalCost[&fnDecl] <= this->settings().fInlineThreshold) {
1098 // We won't exceed the inline threshold by inlining this.
1099 return false;
1100 }
1101 // Inlining this function will add too many IRNodes.
1102 return true;
1103 }),
1104 candidates.end());
John Stiles2d7973a2020-10-02 15:01:03 -04001105}
1106
Brian Osman0006ad02020-11-18 15:38:39 -05001107bool Inliner::analyze(const std::vector<std::unique_ptr<ProgramElement>>& elements,
John Stiles78047582020-12-16 16:17:41 -05001108 std::shared_ptr<SymbolTable> symbols,
Brian Osman0006ad02020-11-18 15:38:39 -05001109 ProgramUsage* usage) {
John Stilesd34d56e2020-10-12 12:04:47 -04001110 // A threshold of zero indicates that the inliner is completely disabled, so we can just return.
John Stilesd1204642021-02-17 16:30:02 -05001111 if (this->settings().fInlineThreshold <= 0) {
John Stilesd34d56e2020-10-12 12:04:47 -04001112 return false;
1113 }
1114
John Stiles031a7672020-11-13 16:13:18 -05001115 // Enforce a limit on inlining to avoid pathological cases. (inliner/ExponentialGrowth.sksl)
1116 if (fInlinedStatementCounter >= kInlinedStatementLimit) {
1117 return false;
1118 }
1119
John Stiles2d7973a2020-10-02 15:01:03 -04001120 InlineCandidateList candidateList;
John Stiles9b9415e2020-11-23 14:48:06 -05001121 this->buildCandidateList(elements, symbols, usage, &candidateList);
John Stiles2d7973a2020-10-02 15:01:03 -04001122
John Stiles915a38c2020-09-14 09:38:13 -04001123 // Inline the candidates where we've determined that it's safe to do so.
John Stiles708faba2021-03-19 09:43:23 -04001124 using StatementRemappingTable = std::unordered_map<std::unique_ptr<Statement>*,
1125 std::unique_ptr<Statement>*>;
1126 StatementRemappingTable statementRemappingTable;
1127
John Stiles915a38c2020-09-14 09:38:13 -04001128 bool madeChanges = false;
John Stiles2d7973a2020-10-02 15:01:03 -04001129 for (const InlineCandidate& candidate : candidateList.fCandidates) {
John Stiles915a38c2020-09-14 09:38:13 -04001130 FunctionCall& funcCall = (*candidate.fCandidateExpr)->as<FunctionCall>();
John Stiles915a38c2020-09-14 09:38:13 -04001131
John Stiles915a38c2020-09-14 09:38:13 -04001132 // Convert the function call to its inlined equivalent.
John Stiles30fce9c2021-03-18 09:24:06 -04001133 InlinedCall inlinedCall = this->inlineCall(&funcCall, candidate.fSymbols, *usage,
Ethan Nicholas0a5d0962020-10-14 13:33:18 -04001134 &candidate.fEnclosingFunction->declaration());
John Stiles915a38c2020-09-14 09:38:13 -04001135
John Stiles0c2d14a2021-03-01 10:08:08 -05001136 // Stop if an error was detected during the inlining process.
1137 if (!inlinedCall.fInlinedBody && !inlinedCall.fReplacementExpr) {
1138 break;
John Stiles915a38c2020-09-14 09:38:13 -04001139 }
1140
John Stiles0c2d14a2021-03-01 10:08:08 -05001141 // Ensure that the inlined body has a scope if it needs one.
1142 this->ensureScopedBlocks(inlinedCall.fInlinedBody.get(), candidate.fParentStmt->get());
1143
1144 // Add references within the inlined body
1145 usage->add(inlinedCall.fInlinedBody.get());
1146
John Stiles708faba2021-03-19 09:43:23 -04001147 // Look up the enclosing statement; remap it if necessary.
1148 std::unique_ptr<Statement>* enclosingStmt = candidate.fEnclosingStmt;
1149 for (;;) {
1150 auto iter = statementRemappingTable.find(enclosingStmt);
1151 if (iter == statementRemappingTable.end()) {
1152 break;
1153 }
1154 enclosingStmt = iter->second;
1155 }
1156
John Stiles0c2d14a2021-03-01 10:08:08 -05001157 // Move the enclosing statement to the end of the unscoped Block containing the inlined
1158 // function, then replace the enclosing statement with that Block.
1159 // Before:
1160 // fInlinedBody = Block{ stmt1, stmt2, stmt3 }
1161 // fEnclosingStmt = stmt4
1162 // After:
1163 // fInlinedBody = null
1164 // fEnclosingStmt = Block{ stmt1, stmt2, stmt3, stmt4 }
John Stiles708faba2021-03-19 09:43:23 -04001165 inlinedCall.fInlinedBody->children().push_back(std::move(*enclosingStmt));
1166 *enclosingStmt = std::move(inlinedCall.fInlinedBody);
John Stiles0c2d14a2021-03-01 10:08:08 -05001167
John Stiles915a38c2020-09-14 09:38:13 -04001168 // Replace the candidate function call with our replacement expression.
John Stiles60dbf072021-08-02 14:22:34 -04001169 usage->remove(candidate.fCandidateExpr->get());
1170 usage->add(inlinedCall.fReplacementExpr.get());
John Stiles915a38c2020-09-14 09:38:13 -04001171 *candidate.fCandidateExpr = std::move(inlinedCall.fReplacementExpr);
1172 madeChanges = true;
1173
John Stiles708faba2021-03-19 09:43:23 -04001174 // If anything else pointed at our enclosing statement, it's now pointing at a Block
1175 // containing many other statements as well. Maintain a fix-up table to account for this.
1176 statementRemappingTable[enclosingStmt] = &(*enclosingStmt)->as<Block>().children().back();
1177
John Stiles031a7672020-11-13 16:13:18 -05001178 // Stop inlining if we've reached our hard cap on new statements.
1179 if (fInlinedStatementCounter >= kInlinedStatementLimit) {
1180 break;
1181 }
1182
John Stiles915a38c2020-09-14 09:38:13 -04001183 // Note that nothing was destroyed except for the FunctionCall. All other nodes should
1184 // remain valid.
1185 }
1186
1187 return madeChanges;
John Stiles93442622020-09-11 12:11:27 -04001188}
1189
John Stiles44e96be2020-08-31 13:16:04 -04001190} // namespace SkSL