blob: b98c2b619dcc2c28e4adf7dccf8e1f0652fea208 [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"
Brian Osmaneb0f29d2021-08-04 11:34:16 -040019#include "src/sksl/ir/SkSLChildCall.h"
John Stiles44e96be2020-08-31 13:16:04 -040020#include "src/sksl/ir/SkSLConstructor.h"
John Stiles7384b372021-04-01 13:48:15 -040021#include "src/sksl/ir/SkSLConstructorArray.h"
John Stilese3ae9682021-08-05 10:35:01 -040022#include "src/sksl/ir/SkSLConstructorArrayCast.h"
John Stiles8cad6372021-04-07 12:31:13 -040023#include "src/sksl/ir/SkSLConstructorCompound.h"
24#include "src/sksl/ir/SkSLConstructorCompoundCast.h"
John Stilese1182782021-03-30 22:09:37 -040025#include "src/sksl/ir/SkSLConstructorDiagonalMatrix.h"
John Stiles5abb9e12021-04-06 13:47:19 -040026#include "src/sksl/ir/SkSLConstructorMatrixResize.h"
John Stilesfd7252f2021-04-04 22:24:40 -040027#include "src/sksl/ir/SkSLConstructorScalarCast.h"
John Stiles2938eea2021-04-01 18:58:25 -040028#include "src/sksl/ir/SkSLConstructorSplat.h"
John Stilesd47330f2021-04-08 23:25:52 -040029#include "src/sksl/ir/SkSLConstructorStruct.h"
John Stiles44e96be2020-08-31 13:16:04 -040030#include "src/sksl/ir/SkSLContinueStatement.h"
31#include "src/sksl/ir/SkSLDiscardStatement.h"
32#include "src/sksl/ir/SkSLDoStatement.h"
John Stiles44e96be2020-08-31 13:16:04 -040033#include "src/sksl/ir/SkSLExpressionStatement.h"
34#include "src/sksl/ir/SkSLExternalFunctionCall.h"
Brian Osmanbe0b3b72021-01-06 14:27:35 -050035#include "src/sksl/ir/SkSLExternalFunctionReference.h"
John Stiles44e96be2020-08-31 13:16:04 -040036#include "src/sksl/ir/SkSLField.h"
37#include "src/sksl/ir/SkSLFieldAccess.h"
38#include "src/sksl/ir/SkSLFloatLiteral.h"
39#include "src/sksl/ir/SkSLForStatement.h"
40#include "src/sksl/ir/SkSLFunctionCall.h"
41#include "src/sksl/ir/SkSLFunctionDeclaration.h"
42#include "src/sksl/ir/SkSLFunctionDefinition.h"
43#include "src/sksl/ir/SkSLFunctionReference.h"
44#include "src/sksl/ir/SkSLIfStatement.h"
45#include "src/sksl/ir/SkSLIndexExpression.h"
John Stiles98c1f822020-09-09 14:18:53 -040046#include "src/sksl/ir/SkSLInlineMarker.h"
John Stiles44e96be2020-08-31 13:16:04 -040047#include "src/sksl/ir/SkSLIntLiteral.h"
48#include "src/sksl/ir/SkSLInterfaceBlock.h"
John Stiles44e96be2020-08-31 13:16:04 -040049#include "src/sksl/ir/SkSLNop.h"
John Stiles44e96be2020-08-31 13:16:04 -040050#include "src/sksl/ir/SkSLPostfixExpression.h"
51#include "src/sksl/ir/SkSLPrefixExpression.h"
52#include "src/sksl/ir/SkSLReturnStatement.h"
53#include "src/sksl/ir/SkSLSetting.h"
54#include "src/sksl/ir/SkSLSwitchCase.h"
55#include "src/sksl/ir/SkSLSwitchStatement.h"
56#include "src/sksl/ir/SkSLSwizzle.h"
57#include "src/sksl/ir/SkSLTernaryExpression.h"
58#include "src/sksl/ir/SkSLUnresolvedFunction.h"
59#include "src/sksl/ir/SkSLVarDeclarations.h"
John Stiles44e96be2020-08-31 13:16:04 -040060#include "src/sksl/ir/SkSLVariable.h"
61#include "src/sksl/ir/SkSLVariableReference.h"
John Stiles44e96be2020-08-31 13:16:04 -040062
63namespace SkSL {
64namespace {
65
John Stiles031a7672020-11-13 16:13:18 -050066static constexpr int kInlinedStatementLimit = 2500;
67
John Stiles44e96be2020-08-31 13:16:04 -040068static int count_returns_at_end_of_control_flow(const FunctionDefinition& funcDef) {
69 class CountReturnsAtEndOfControlFlow : public ProgramVisitor {
70 public:
71 CountReturnsAtEndOfControlFlow(const FunctionDefinition& funcDef) {
72 this->visitProgramElement(funcDef);
73 }
74
John Stiles5b408a32021-03-17 09:53:32 -040075 bool visitExpression(const Expression& expr) override {
76 // Do not recurse into expressions.
77 return false;
78 }
79
John Stiles44e96be2020-08-31 13:16:04 -040080 bool visitStatement(const Statement& stmt) override {
Ethan Nicholase6592142020-09-08 10:22:09 -040081 switch (stmt.kind()) {
82 case Statement::Kind::kBlock: {
John Stiles44e96be2020-08-31 13:16:04 -040083 // Check only the last statement of a block.
Ethan Nicholas7bd60432020-09-25 14:31:59 -040084 const auto& block = stmt.as<Block>();
85 return block.children().size() &&
86 this->visitStatement(*block.children().back());
John Stiles44e96be2020-08-31 13:16:04 -040087 }
Ethan Nicholase6592142020-09-08 10:22:09 -040088 case Statement::Kind::kSwitch:
Ethan Nicholase6592142020-09-08 10:22:09 -040089 case Statement::Kind::kDo:
90 case Statement::Kind::kFor:
John Stiles44e96be2020-08-31 13:16:04 -040091 // Don't introspect switches or loop structures at all.
92 return false;
93
Ethan Nicholase6592142020-09-08 10:22:09 -040094 case Statement::Kind::kReturn:
John Stiles44e96be2020-08-31 13:16:04 -040095 ++fNumReturns;
96 [[fallthrough]];
97
98 default:
John Stiles93442622020-09-11 12:11:27 -040099 return INHERITED::visitStatement(stmt);
John Stiles44e96be2020-08-31 13:16:04 -0400100 }
101 }
102
103 int fNumReturns = 0;
104 using INHERITED = ProgramVisitor;
105 };
106
107 return CountReturnsAtEndOfControlFlow{funcDef}.fNumReturns;
108}
109
John Stiles991b09d2020-09-10 13:33:40 -0400110static bool contains_recursive_call(const FunctionDeclaration& funcDecl) {
111 class ContainsRecursiveCall : public ProgramVisitor {
112 public:
113 bool visit(const FunctionDeclaration& funcDecl) {
114 fFuncDecl = &funcDecl;
Ethan Nicholased84b732020-10-08 11:45:44 -0400115 return funcDecl.definition() ? this->visitProgramElement(*funcDecl.definition())
116 : false;
John Stiles991b09d2020-09-10 13:33:40 -0400117 }
118
119 bool visitExpression(const Expression& expr) override {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400120 if (expr.is<FunctionCall>() && expr.as<FunctionCall>().function().matches(*fFuncDecl)) {
John Stiles991b09d2020-09-10 13:33:40 -0400121 return true;
122 }
123 return INHERITED::visitExpression(expr);
124 }
125
126 bool visitStatement(const Statement& stmt) override {
Ethan Nicholasceb62142020-10-09 16:51:18 -0400127 if (stmt.is<InlineMarker>() &&
128 stmt.as<InlineMarker>().function().matches(*fFuncDecl)) {
John Stiles991b09d2020-09-10 13:33:40 -0400129 return true;
130 }
131 return INHERITED::visitStatement(stmt);
132 }
133
134 const FunctionDeclaration* fFuncDecl;
135 using INHERITED = ProgramVisitor;
136 };
137
138 return ContainsRecursiveCall{}.visit(funcDecl);
139}
140
John Stiles6d696082020-10-01 10:18:54 -0400141static std::unique_ptr<Statement>* find_parent_statement(
142 const std::vector<std::unique_ptr<Statement>*>& stmtStack) {
John Stiles915a38c2020-09-14 09:38:13 -0400143 SkASSERT(!stmtStack.empty());
144
145 // Walk the statement stack from back to front, ignoring the last element (which is the
146 // enclosing statement).
147 auto iter = stmtStack.rbegin();
148 ++iter;
149
150 // Anything counts as a parent statement other than a scopeless Block.
151 for (; iter != stmtStack.rend(); ++iter) {
John Stiles6d696082020-10-01 10:18:54 -0400152 std::unique_ptr<Statement>* stmt = *iter;
153 if (!(*stmt)->is<Block>() || (*stmt)->as<Block>().isScope()) {
John Stiles915a38c2020-09-14 09:38:13 -0400154 return stmt;
155 }
156 }
157
158 // There wasn't any parent statement to be found.
159 return nullptr;
160}
161
John Stilese41b4ee2020-09-28 12:28:16 -0400162std::unique_ptr<Expression> clone_with_ref_kind(const Expression& expr,
163 VariableReference::RefKind refKind) {
164 std::unique_ptr<Expression> clone = expr.clone();
John Stilesbb8cf582021-08-26 23:34:59 -0400165 Analysis::UpdateVariableRefKind(clone.get(), refKind);
John Stilese41b4ee2020-09-28 12:28:16 -0400166 return clone;
167}
168
John Stiles77702f12020-12-17 14:38:56 -0500169class CountReturnsWithLimit : public ProgramVisitor {
170public:
171 CountReturnsWithLimit(const FunctionDefinition& funcDef, int limit) : fLimit(limit) {
172 this->visitProgramElement(funcDef);
173 }
174
John Stiles5b408a32021-03-17 09:53:32 -0400175 bool visitExpression(const Expression& expr) override {
176 // Do not recurse into expressions.
177 return false;
178 }
179
John Stiles77702f12020-12-17 14:38:56 -0500180 bool visitStatement(const Statement& stmt) override {
181 switch (stmt.kind()) {
182 case Statement::Kind::kReturn: {
183 ++fNumReturns;
184 fDeepestReturn = std::max(fDeepestReturn, fScopedBlockDepth);
185 return (fNumReturns >= fLimit) || INHERITED::visitStatement(stmt);
186 }
John Stilesc5ff4862020-12-22 13:47:05 -0500187 case Statement::Kind::kVarDeclaration: {
188 if (fScopedBlockDepth > 1) {
189 fVariablesInBlocks = true;
190 }
191 return INHERITED::visitStatement(stmt);
192 }
John Stiles77702f12020-12-17 14:38:56 -0500193 case Statement::Kind::kBlock: {
194 int depthIncrement = stmt.as<Block>().isScope() ? 1 : 0;
195 fScopedBlockDepth += depthIncrement;
196 bool result = INHERITED::visitStatement(stmt);
197 fScopedBlockDepth -= depthIncrement;
John Stilesc5ff4862020-12-22 13:47:05 -0500198 if (fNumReturns == 0 && fScopedBlockDepth <= 1) {
199 // If closing this block puts us back at the top level, and we haven't
200 // encountered any return statements yet, any vardecls we may have encountered
201 // up until this point can be ignored. They are out of scope now, and they were
202 // never used in a return statement.
203 fVariablesInBlocks = false;
204 }
John Stiles77702f12020-12-17 14:38:56 -0500205 return result;
206 }
207 default:
208 return INHERITED::visitStatement(stmt);
209 }
210 }
211
212 int fNumReturns = 0;
213 int fDeepestReturn = 0;
214 int fLimit = 0;
215 int fScopedBlockDepth = 0;
John Stilesc5ff4862020-12-22 13:47:05 -0500216 bool fVariablesInBlocks = false;
John Stiles77702f12020-12-17 14:38:56 -0500217 using INHERITED = ProgramVisitor;
218};
219
John Stiles44e96be2020-08-31 13:16:04 -0400220} // namespace
221
John Stiles77702f12020-12-17 14:38:56 -0500222Inliner::ReturnComplexity Inliner::GetReturnComplexity(const FunctionDefinition& funcDef) {
223 int returnsAtEndOfControlFlow = count_returns_at_end_of_control_flow(funcDef);
224 CountReturnsWithLimit counter{funcDef, returnsAtEndOfControlFlow + 1};
John Stiles77702f12020-12-17 14:38:56 -0500225 if (counter.fNumReturns > returnsAtEndOfControlFlow) {
226 return ReturnComplexity::kEarlyReturns;
227 }
John Stilesc5ff4862020-12-22 13:47:05 -0500228 if (counter.fNumReturns > 1) {
John Stiles77702f12020-12-17 14:38:56 -0500229 return ReturnComplexity::kScopedReturns;
230 }
John Stilesc5ff4862020-12-22 13:47:05 -0500231 if (counter.fVariablesInBlocks && counter.fDeepestReturn > 1) {
232 return ReturnComplexity::kScopedReturns;
233 }
John Stiles8937cd42021-03-17 19:32:59 +0000234 return ReturnComplexity::kSingleSafeReturn;
John Stiles77702f12020-12-17 14:38:56 -0500235}
236
John Stilesb61ee902020-09-21 12:26:59 -0400237void Inliner::ensureScopedBlocks(Statement* inlinedBody, Statement* parentStmt) {
238 // No changes necessary if this statement isn't actually a block.
239 if (!inlinedBody || !inlinedBody->is<Block>()) {
240 return;
241 }
242
243 // No changes necessary if the parent statement doesn't require a scope.
244 if (!parentStmt || !(parentStmt->is<IfStatement>() || parentStmt->is<ForStatement>() ||
Brian Osmand6f23382020-12-15 17:08:59 -0500245 parentStmt->is<DoStatement>())) {
John Stilesb61ee902020-09-21 12:26:59 -0400246 return;
247 }
248
249 Block& block = inlinedBody->as<Block>();
250
251 // The inliner will create inlined function bodies as a Block containing multiple statements,
252 // but no scope. Normally, this is fine, but if this block is used as the statement for a
253 // do/for/if/while, this isn't actually possible to represent textually; a scope must be added
254 // for the generated code to match the intent. In the case of Blocks nested inside other Blocks,
255 // we add the scope to the outermost block if needed. Zero-statement blocks have similar
256 // issues--if we don't represent the Block textually somehow, we run the risk of accidentally
257 // absorbing the following statement into our loop--so we also add a scope to these.
258 for (Block* nestedBlock = &block;; ) {
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400259 if (nestedBlock->isScope()) {
John Stilesb61ee902020-09-21 12:26:59 -0400260 // We found an explicit scope; all is well.
261 return;
262 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400263 if (nestedBlock->children().size() != 1) {
John Stilesb61ee902020-09-21 12:26:59 -0400264 // We found a block with multiple (or zero) statements, but no scope? Let's add a scope
265 // to the outermost block.
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400266 block.setIsScope(true);
John Stilesb61ee902020-09-21 12:26:59 -0400267 return;
268 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400269 if (!nestedBlock->children()[0]->is<Block>()) {
John Stilesb61ee902020-09-21 12:26:59 -0400270 // This block has exactly one thing inside, and it's not another block. No need to scope
271 // it.
272 return;
273 }
274 // We have to go deeper.
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400275 nestedBlock = &nestedBlock->children()[0]->as<Block>();
John Stilesb61ee902020-09-21 12:26:59 -0400276 }
277}
278
John Stiles10d39d92021-05-04 16:13:14 -0400279void Inliner::reset() {
Ethan Nicholas6f4eee22021-01-11 12:37:42 -0500280 fMangler.reset();
John Stiles031a7672020-11-13 16:13:18 -0500281 fInlinedStatementCounter = 0;
John Stiles44e96be2020-08-31 13:16:04 -0400282}
283
284std::unique_ptr<Expression> Inliner::inlineExpression(int offset,
285 VariableRewriteMap* varMap,
John Stilesd7cc0932020-11-30 12:24:27 -0500286 SymbolTable* symbolTableForExpression,
John Stiles44e96be2020-08-31 13:16:04 -0400287 const Expression& expression) {
288 auto expr = [&](const std::unique_ptr<Expression>& e) -> std::unique_ptr<Expression> {
289 if (e) {
John Stilesd7cc0932020-11-30 12:24:27 -0500290 return this->inlineExpression(offset, varMap, symbolTableForExpression, *e);
John Stiles44e96be2020-08-31 13:16:04 -0400291 }
292 return nullptr;
293 };
John Stiles8e3b6be2020-10-13 11:14:08 -0400294 auto argList = [&](const ExpressionArray& originalArgs) -> ExpressionArray {
295 ExpressionArray args;
John Stilesf4bda742020-10-14 16:57:41 -0400296 args.reserve_back(originalArgs.size());
John Stiles44e96be2020-08-31 13:16:04 -0400297 for (const std::unique_ptr<Expression>& arg : originalArgs) {
298 args.push_back(expr(arg));
299 }
300 return args;
301 };
302
Ethan Nicholase6592142020-09-08 10:22:09 -0400303 switch (expression.kind()) {
304 case Expression::Kind::kBinary: {
John Stiles6a1a98c2021-01-14 18:35:34 -0500305 const BinaryExpression& binaryExpr = expression.as<BinaryExpression>();
John Stilese2aec432021-03-01 09:27:48 -0500306 return BinaryExpression::Make(*fContext,
307 expr(binaryExpr.left()),
308 binaryExpr.getOperator(),
309 expr(binaryExpr.right()));
John Stiles44e96be2020-08-31 13:16:04 -0400310 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400311 case Expression::Kind::kBoolLiteral:
312 case Expression::Kind::kIntLiteral:
313 case Expression::Kind::kFloatLiteral:
John Stiles44e96be2020-08-31 13:16:04 -0400314 return expression.clone();
Brian Osmaneb0f29d2021-08-04 11:34:16 -0400315 case Expression::Kind::kChildCall: {
316 const ChildCall& childCall = expression.as<ChildCall>();
317 return ChildCall::Make(*fContext,
318 offset,
319 childCall.type().clone(symbolTableForExpression),
320 childCall.child(),
321 argList(childCall.arguments()));
322 }
John Stiles7384b372021-04-01 13:48:15 -0400323 case Expression::Kind::kConstructorArray: {
324 const ConstructorArray& ctor = expression.as<ConstructorArray>();
325 return ConstructorArray::Make(*fContext, offset,
326 *ctor.type().clone(symbolTableForExpression),
327 argList(ctor.arguments()));
328 }
John Stilese3ae9682021-08-05 10:35:01 -0400329 case Expression::Kind::kConstructorArrayCast: {
330 const ConstructorArrayCast& ctor = expression.as<ConstructorArrayCast>();
331 return ConstructorArrayCast::Make(*fContext, offset,
332 *ctor.type().clone(symbolTableForExpression),
333 expr(ctor.argument()));
334 }
John Stiles8cad6372021-04-07 12:31:13 -0400335 case Expression::Kind::kConstructorCompound: {
336 const ConstructorCompound& ctor = expression.as<ConstructorCompound>();
337 return ConstructorCompound::Make(*fContext, offset,
John Stiles2bec8ab2021-04-06 18:40:04 -0400338 *ctor.type().clone(symbolTableForExpression),
339 argList(ctor.arguments()));
340 }
John Stiles8cad6372021-04-07 12:31:13 -0400341 case Expression::Kind::kConstructorCompoundCast: {
342 const ConstructorCompoundCast& ctor = expression.as<ConstructorCompoundCast>();
343 return ConstructorCompoundCast::Make(*fContext, offset,
John Stiles268a73f2021-04-07 12:30:22 -0400344 *ctor.type().clone(symbolTableForExpression),
345 expr(ctor.argument()));
346 }
John Stilese1182782021-03-30 22:09:37 -0400347 case Expression::Kind::kConstructorDiagonalMatrix: {
348 const ConstructorDiagonalMatrix& ctor = expression.as<ConstructorDiagonalMatrix>();
349 return ConstructorDiagonalMatrix::Make(*fContext, offset,
350 *ctor.type().clone(symbolTableForExpression),
351 expr(ctor.argument()));
352 }
John Stiles5abb9e12021-04-06 13:47:19 -0400353 case Expression::Kind::kConstructorMatrixResize: {
354 const ConstructorMatrixResize& ctor = expression.as<ConstructorMatrixResize>();
355 return ConstructorMatrixResize::Make(*fContext, offset,
356 *ctor.type().clone(symbolTableForExpression),
357 expr(ctor.argument()));
358 }
John Stilesfd7252f2021-04-04 22:24:40 -0400359 case Expression::Kind::kConstructorScalarCast: {
360 const ConstructorScalarCast& ctor = expression.as<ConstructorScalarCast>();
361 return ConstructorScalarCast::Make(*fContext, offset,
362 *ctor.type().clone(symbolTableForExpression),
363 expr(ctor.argument()));
364 }
John Stiles2938eea2021-04-01 18:58:25 -0400365 case Expression::Kind::kConstructorSplat: {
366 const ConstructorSplat& ctor = expression.as<ConstructorSplat>();
367 return ConstructorSplat::Make(*fContext, offset,
368 *ctor.type().clone(symbolTableForExpression),
369 expr(ctor.argument()));
370 }
John Stilesd47330f2021-04-08 23:25:52 -0400371 case Expression::Kind::kConstructorStruct: {
372 const ConstructorStruct& ctor = expression.as<ConstructorStruct>();
373 return ConstructorStruct::Make(*fContext, offset,
374 *ctor.type().clone(symbolTableForExpression),
375 argList(ctor.arguments()));
376 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400377 case Expression::Kind::kExternalFunctionCall: {
John Stiles44e96be2020-08-31 13:16:04 -0400378 const ExternalFunctionCall& externalCall = expression.as<ExternalFunctionCall>();
Ethan Nicholas444ccc62020-10-09 10:16:22 -0400379 return std::make_unique<ExternalFunctionCall>(offset, &externalCall.function(),
Ethan Nicholas6e86ec92020-09-30 14:29:56 -0400380 argList(externalCall.arguments()));
John Stiles44e96be2020-08-31 13:16:04 -0400381 }
Brian Osmanbe0b3b72021-01-06 14:27:35 -0500382 case Expression::Kind::kExternalFunctionReference:
John Stiles44e96be2020-08-31 13:16:04 -0400383 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400384 case Expression::Kind::kFieldAccess: {
John Stiles44e96be2020-08-31 13:16:04 -0400385 const FieldAccess& f = expression.as<FieldAccess>();
John Stiles06d600f2021-03-08 09:18:21 -0500386 return FieldAccess::Make(*fContext, expr(f.base()), f.fieldIndex(), f.ownerKind());
John Stiles44e96be2020-08-31 13:16:04 -0400387 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400388 case Expression::Kind::kFunctionCall: {
John Stiles44e96be2020-08-31 13:16:04 -0400389 const FunctionCall& funcCall = expression.as<FunctionCall>();
John Stilescd7ba502021-03-19 10:54:59 -0400390 return FunctionCall::Make(*fContext,
391 offset,
392 funcCall.type().clone(symbolTableForExpression),
393 funcCall.function(),
394 argList(funcCall.arguments()));
John Stiles44e96be2020-08-31 13:16:04 -0400395 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400396 case Expression::Kind::kFunctionReference:
Brian Osman2b3b35f2020-09-08 09:17:36 -0400397 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400398 case Expression::Kind::kIndex: {
John Stiles44e96be2020-08-31 13:16:04 -0400399 const IndexExpression& idx = expression.as<IndexExpression>();
John Stiles51d33982021-03-08 09:18:07 -0500400 return IndexExpression::Make(*fContext, expr(idx.base()), expr(idx.index()));
John Stiles44e96be2020-08-31 13:16:04 -0400401 }
Brian Osman3099f792021-09-01 13:12:16 -0400402 case Expression::Kind::kMethodReference:
403 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400404 case Expression::Kind::kPrefix: {
John Stiles44e96be2020-08-31 13:16:04 -0400405 const PrefixExpression& p = expression.as<PrefixExpression>();
John Stilesb0eb20f2021-02-26 15:29:33 -0500406 return PrefixExpression::Make(*fContext, p.getOperator(), expr(p.operand()));
John Stiles44e96be2020-08-31 13:16:04 -0400407 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400408 case Expression::Kind::kPostfix: {
John Stiles44e96be2020-08-31 13:16:04 -0400409 const PostfixExpression& p = expression.as<PostfixExpression>();
John Stiles52d3b012021-02-26 15:56:48 -0500410 return PostfixExpression::Make(*fContext, expr(p.operand()), p.getOperator());
John Stiles44e96be2020-08-31 13:16:04 -0400411 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400412 case Expression::Kind::kSetting:
John Stiles44e96be2020-08-31 13:16:04 -0400413 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400414 case Expression::Kind::kSwizzle: {
John Stiles44e96be2020-08-31 13:16:04 -0400415 const Swizzle& s = expression.as<Swizzle>();
John Stiles6e88e042021-02-19 14:09:38 -0500416 return Swizzle::Make(*fContext, expr(s.base()), s.components());
John Stiles44e96be2020-08-31 13:16:04 -0400417 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400418 case Expression::Kind::kTernary: {
John Stiles44e96be2020-08-31 13:16:04 -0400419 const TernaryExpression& t = expression.as<TernaryExpression>();
John Stiles90518f72021-02-26 20:44:54 -0500420 return TernaryExpression::Make(*fContext, expr(t.test()),
421 expr(t.ifTrue()), expr(t.ifFalse()));
John Stiles44e96be2020-08-31 13:16:04 -0400422 }
Brian Osman83ba9302020-09-11 13:33:46 -0400423 case Expression::Kind::kTypeReference:
424 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400425 case Expression::Kind::kVariableReference: {
John Stiles44e96be2020-08-31 13:16:04 -0400426 const VariableReference& v = expression.as<VariableReference>();
Ethan Nicholas78686922020-10-08 06:46:27 -0400427 auto varMapIter = varMap->find(v.variable());
John Stilese41b4ee2020-09-28 12:28:16 -0400428 if (varMapIter != varMap->end()) {
Ethan Nicholas78686922020-10-08 06:46:27 -0400429 return clone_with_ref_kind(*varMapIter->second, v.refKind());
John Stiles44e96be2020-08-31 13:16:04 -0400430 }
431 return v.clone();
432 }
433 default:
434 SkASSERT(false);
435 return nullptr;
436 }
437}
438
439std::unique_ptr<Statement> Inliner::inlineStatement(int offset,
440 VariableRewriteMap* varMap,
441 SymbolTable* symbolTableForStatement,
John Stiles77702f12020-12-17 14:38:56 -0500442 std::unique_ptr<Expression>* resultExpr,
443 ReturnComplexity returnComplexity,
Brian Osman3887a012020-09-30 13:22:27 -0400444 const Statement& statement,
445 bool isBuiltinCode) {
John Stiles44e96be2020-08-31 13:16:04 -0400446 auto stmt = [&](const std::unique_ptr<Statement>& s) -> std::unique_ptr<Statement> {
447 if (s) {
John Stilesa5f3c312020-09-22 12:05:16 -0400448 return this->inlineStatement(offset, varMap, symbolTableForStatement, resultExpr,
John Stiles77702f12020-12-17 14:38:56 -0500449 returnComplexity, *s, isBuiltinCode);
John Stiles44e96be2020-08-31 13:16:04 -0400450 }
451 return nullptr;
452 };
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400453 auto blockStmts = [&](const Block& block) {
John Stiles8f2a0cf2020-10-13 12:48:21 -0400454 StatementArray result;
John Stilesf4bda742020-10-14 16:57:41 -0400455 result.reserve_back(block.children().size());
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400456 for (const std::unique_ptr<Statement>& child : block.children()) {
457 result.push_back(stmt(child));
458 }
459 return result;
460 };
John Stiles44e96be2020-08-31 13:16:04 -0400461 auto expr = [&](const std::unique_ptr<Expression>& e) -> std::unique_ptr<Expression> {
462 if (e) {
John Stilesd7cc0932020-11-30 12:24:27 -0500463 return this->inlineExpression(offset, varMap, symbolTableForStatement, *e);
John Stiles44e96be2020-08-31 13:16:04 -0400464 }
465 return nullptr;
466 };
John Stiles031a7672020-11-13 16:13:18 -0500467
468 ++fInlinedStatementCounter;
469
Ethan Nicholase6592142020-09-08 10:22:09 -0400470 switch (statement.kind()) {
471 case Statement::Kind::kBlock: {
John Stiles44e96be2020-08-31 13:16:04 -0400472 const Block& b = statement.as<Block>();
John Stilesbf16b6c2021-03-12 19:24:31 -0500473 return Block::Make(offset, blockStmts(b),
474 SymbolTable::WrapIfBuiltin(b.symbolTable()),
475 b.isScope());
John Stiles44e96be2020-08-31 13:16:04 -0400476 }
477
Ethan Nicholase6592142020-09-08 10:22:09 -0400478 case Statement::Kind::kBreak:
479 case Statement::Kind::kContinue:
480 case Statement::Kind::kDiscard:
John Stiles44e96be2020-08-31 13:16:04 -0400481 return statement.clone();
482
Ethan Nicholase6592142020-09-08 10:22:09 -0400483 case Statement::Kind::kDo: {
John Stiles44e96be2020-08-31 13:16:04 -0400484 const DoStatement& d = statement.as<DoStatement>();
John Stilesea5822e2021-02-26 11:18:20 -0500485 return DoStatement::Make(*fContext, stmt(d.statement()), expr(d.test()));
John Stiles44e96be2020-08-31 13:16:04 -0400486 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400487 case Statement::Kind::kExpression: {
John Stiles44e96be2020-08-31 13:16:04 -0400488 const ExpressionStatement& e = statement.as<ExpressionStatement>();
John Stiles3e5871c2021-02-25 20:52:03 -0500489 return ExpressionStatement::Make(*fContext, expr(e.expression()));
John Stiles44e96be2020-08-31 13:16:04 -0400490 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400491 case Statement::Kind::kFor: {
John Stiles44e96be2020-08-31 13:16:04 -0400492 const ForStatement& f = statement.as<ForStatement>();
493 // need to ensure initializer is evaluated first so that we've already remapped its
494 // declarations by the time we evaluate test & next
Ethan Nicholas0d31ed52020-10-05 14:47:09 -0400495 std::unique_ptr<Statement> initializer = stmt(f.initializer());
John Stiles9c975c52021-08-31 10:18:57 -0400496 // We can't reuse the unroll info from the original for loop, because it uses a
497 // different induction variable. Ours is a clone.
John Stilesb321a072021-02-25 16:24:19 -0500498 return ForStatement::Make(*fContext, offset, std::move(initializer), expr(f.test()),
John Stiles9c975c52021-08-31 10:18:57 -0400499 expr(f.next()), stmt(f.statement()), /*unrollInfo=*/nullptr,
John Stilesb321a072021-02-25 16:24:19 -0500500 SymbolTable::WrapIfBuiltin(f.symbols()));
John Stiles44e96be2020-08-31 13:16:04 -0400501 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400502 case Statement::Kind::kIf: {
John Stiles44e96be2020-08-31 13:16:04 -0400503 const IfStatement& i = statement.as<IfStatement>();
John Stilescf3059e2021-02-25 14:27:02 -0500504 return IfStatement::Make(*fContext, offset, i.isStatic(), expr(i.test()),
505 stmt(i.ifTrue()), stmt(i.ifFalse()));
John Stiles44e96be2020-08-31 13:16:04 -0400506 }
John Stiles98c1f822020-09-09 14:18:53 -0400507 case Statement::Kind::kInlineMarker:
Ethan Nicholase6592142020-09-08 10:22:09 -0400508 case Statement::Kind::kNop:
John Stiles44e96be2020-08-31 13:16:04 -0400509 return statement.clone();
John Stilesea5822e2021-02-26 11:18:20 -0500510
Ethan Nicholase6592142020-09-08 10:22:09 -0400511 case Statement::Kind::kReturn: {
John Stiles44e96be2020-08-31 13:16:04 -0400512 const ReturnStatement& r = statement.as<ReturnStatement>();
John Stiles77702f12020-12-17 14:38:56 -0500513 if (!r.expression()) {
John Stilesdc208472021-03-17 10:58:16 -0400514 // This function doesn't return a value. We won't inline functions with early
515 // returns, so a return statement is a no-op and can be treated as such.
516 return Nop::Make();
John Stiles44e96be2020-08-31 13:16:04 -0400517 }
John Stiles77702f12020-12-17 14:38:56 -0500518
John Stilesc5ff4862020-12-22 13:47:05 -0500519 // If a function only contains a single return, and it doesn't reference variables from
520 // inside an Block's scope, we don't need to store the result in a variable at all. Just
521 // replace the function-call expression with the function's return expression.
John Stiles77702f12020-12-17 14:38:56 -0500522 SkASSERT(resultExpr);
John Stilesc5ff4862020-12-22 13:47:05 -0500523 if (returnComplexity <= ReturnComplexity::kSingleSafeReturn) {
John Stiles77702f12020-12-17 14:38:56 -0500524 *resultExpr = expr(r.expression());
John Stilesa0c04d62021-03-11 23:07:24 -0500525 return Nop::Make();
John Stiles77702f12020-12-17 14:38:56 -0500526 }
527
528 // For more complex functions, assign their result into a variable.
John Stiles511c5002021-02-25 11:17:02 -0500529 SkASSERT(*resultExpr);
John Stiles3e5871c2021-02-25 20:52:03 -0500530 auto assignment = ExpressionStatement::Make(
531 *fContext,
John Stilese2aec432021-03-01 09:27:48 -0500532 BinaryExpression::Make(
533 *fContext,
534 clone_with_ref_kind(**resultExpr, VariableRefKind::kWrite),
John Stiles77702f12020-12-17 14:38:56 -0500535 Token::Kind::TK_EQ,
John Stilese2aec432021-03-01 09:27:48 -0500536 expr(r.expression())));
John Stiles77702f12020-12-17 14:38:56 -0500537
John Stiles77702f12020-12-17 14:38:56 -0500538 // Functions without early returns aren't wrapped in a for loop and don't need to worry
539 // about breaking out of the control flow.
John Stiles3e5871c2021-02-25 20:52:03 -0500540 return assignment;
John Stiles44e96be2020-08-31 13:16:04 -0400541 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400542 case Statement::Kind::kSwitch: {
John Stiles44e96be2020-08-31 13:16:04 -0400543 const SwitchStatement& ss = statement.as<SwitchStatement>();
John Stilesb23a64b2021-03-11 08:27:59 -0500544 StatementArray cases;
545 cases.reserve_back(ss.cases().size());
John Stiles628777c2021-08-04 22:07:41 -0400546 for (const std::unique_ptr<Statement>& switchCaseStmt : ss.cases()) {
547 const SwitchCase& sc = switchCaseStmt->as<SwitchCase>();
John Stilesb23a64b2021-03-11 08:27:59 -0500548 cases.push_back(std::make_unique<SwitchCase>(offset, expr(sc.value()),
549 stmt(sc.statement())));
John Stiles44e96be2020-08-31 13:16:04 -0400550 }
John Stilese1d1b082021-02-23 13:44:36 -0500551 return SwitchStatement::Make(*fContext, offset, ss.isStatic(), expr(ss.value()),
552 std::move(cases), SymbolTable::WrapIfBuiltin(ss.symbols()));
John Stiles44e96be2020-08-31 13:16:04 -0400553 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400554 case Statement::Kind::kVarDeclaration: {
John Stiles44e96be2020-08-31 13:16:04 -0400555 const VarDeclaration& decl = statement.as<VarDeclaration>();
John Stiles35fee4c2020-12-16 18:25:14 +0000556 std::unique_ptr<Expression> initialValue = expr(decl.value());
John Stilesddcc8432021-01-15 15:32:32 -0500557 const Variable& variable = decl.var();
558
John Stiles35fee4c2020-12-16 18:25:14 +0000559 // We assign unique names to inlined variables--scopes hide most of the problems in this
560 // regard, but see `InlinerAvoidsVariableNameOverlap` for a counterexample where unique
561 // names are important.
John Stilesd51c9792021-03-18 11:40:14 -0400562 const String* name = symbolTableForStatement->takeOwnershipOfString(
Ethan Nicholasd2e09602021-06-10 11:21:59 -0400563 fMangler.uniqueName(String(variable.name()), symbolTableForStatement));
Ethan Nicholas5b9b0db2021-01-21 13:12:01 -0500564 auto clonedVar = std::make_unique<Variable>(
565 offset,
566 &variable.modifiers(),
John Stilesd51c9792021-03-18 11:40:14 -0400567 name->c_str(),
Ethan Nicholas5b9b0db2021-01-21 13:12:01 -0500568 variable.type().clone(symbolTableForStatement),
569 isBuiltinCode,
570 variable.storage());
John Stilesa94e0262021-04-27 17:29:59 -0400571 (*varMap)[&variable] = VariableReference::Make(offset, clonedVar.get());
John Stilese67bd132021-03-19 18:39:25 -0400572 auto result = VarDeclaration::Make(*fContext,
573 clonedVar.get(),
574 decl.baseType().clone(symbolTableForStatement),
575 decl.arraySize(),
576 std::move(initialValue));
Ethan Nicholas5b9b0db2021-01-21 13:12:01 -0500577 symbolTableForStatement->takeOwnershipOfSymbol(std::move(clonedVar));
John Stilese67bd132021-03-19 18:39:25 -0400578 return result;
John Stiles44e96be2020-08-31 13:16:04 -0400579 }
John Stiles44e96be2020-08-31 13:16:04 -0400580 default:
581 SkASSERT(false);
582 return nullptr;
583 }
584}
585
John Stiles7b920442020-12-17 10:43:41 -0500586Inliner::InlineVariable Inliner::makeInlineVariable(const String& baseName,
587 const Type* type,
588 SymbolTable* symbolTable,
589 Modifiers modifiers,
590 bool isBuiltinCode,
591 std::unique_ptr<Expression>* initialValue) {
592 // $floatLiteral or $intLiteral aren't real types that we can use for scratch variables, so
593 // replace them if they ever appear here. If this happens, we likely forgot to coerce a type
594 // somewhere during compilation.
John Stiles14975272021-01-12 11:41:14 -0500595 if (type->isLiteral()) {
596 SkDEBUGFAIL("found a $literal type while inlining");
597 type = &type->scalarTypeForLiteral();
John Stiles7b920442020-12-17 10:43:41 -0500598 }
599
John Stilesbff24ab2021-03-17 13:20:10 -0400600 // Out parameters aren't supported.
601 SkASSERT(!(modifiers.fFlags & Modifiers::kOut_Flag));
602
John Stiles7b920442020-12-17 10:43:41 -0500603 // Provide our new variable with a unique name, and add it to our symbol table.
John Stilesd51c9792021-03-18 11:40:14 -0400604 const String* name =
605 symbolTable->takeOwnershipOfString(fMangler.uniqueName(baseName, symbolTable));
John Stiles7b920442020-12-17 10:43:41 -0500606
607 // Create our new variable and add it to the symbol table.
608 InlineVariable result;
Ethan Nicholas5b9b0db2021-01-21 13:12:01 -0500609 auto var = std::make_unique<Variable>(/*offset=*/-1,
John Stilesf2872e62021-05-04 11:38:43 -0400610 this->modifiersPool().add(Modifiers{}),
John Stilesd51c9792021-03-18 11:40:14 -0400611 name->c_str(),
Ethan Nicholas5b9b0db2021-01-21 13:12:01 -0500612 type,
613 isBuiltinCode,
614 Variable::Storage::kLocal);
John Stilesd77dda52021-08-24 09:59:34 -0400615 // If we are creating an array type, reduce it to base type plus array-size.
616 int arraySize = 0;
617 if (type->isArray()) {
618 arraySize = type->columns();
619 type = &type->componentType();
620 }
John Stilesbff24ab2021-03-17 13:20:10 -0400621 // Create our variable declaration.
John Stilesd77dda52021-08-24 09:59:34 -0400622 result.fVarDecl = VarDeclaration::Make(*fContext, var.get(), type, arraySize,
John Stilese67bd132021-03-19 18:39:25 -0400623 std::move(*initialValue));
Ethan Nicholas5b9b0db2021-01-21 13:12:01 -0500624 result.fVarSymbol = symbolTable->add(std::move(var));
John Stiles7b920442020-12-17 10:43:41 -0500625 return result;
626}
627
John Stiles6eadf132020-09-08 10:16:10 -0400628Inliner::InlinedCall Inliner::inlineCall(FunctionCall* call,
John Stiles78047582020-12-16 16:17:41 -0500629 std::shared_ptr<SymbolTable> symbolTable,
John Stiles30fce9c2021-03-18 09:24:06 -0400630 const ProgramUsage& usage,
Brian Osman3887a012020-09-30 13:22:27 -0400631 const FunctionDeclaration* caller) {
John Stiles44e96be2020-08-31 13:16:04 -0400632 // Inlining is more complicated here than in a typical compiler, because we have to have a
633 // high-level IR and can't just drop statements into the middle of an expression or even use
634 // gotos.
635 //
636 // Since we can't insert statements into an expression, we run the inline function as extra
637 // statements before the statement we're currently processing, relying on a lack of execution
638 // order guarantees. Since we can't use gotos (which are normally used to replace return
639 // statements), we wrap the whole function in a loop and use break statements to jump to the
640 // end.
John Stiles44e96be2020-08-31 13:16:04 -0400641 SkASSERT(fContext);
642 SkASSERT(call);
Ethan Nicholased84b732020-10-08 11:45:44 -0400643 SkASSERT(this->isSafeToInline(call->function().definition()));
John Stiles44e96be2020-08-31 13:16:04 -0400644
John Stiles8e3b6be2020-10-13 11:14:08 -0400645 ExpressionArray& arguments = call->arguments();
John Stiles6eadf132020-09-08 10:16:10 -0400646 const int offset = call->fOffset;
Ethan Nicholased84b732020-10-08 11:45:44 -0400647 const FunctionDefinition& function = *call->function().definition();
John Stiles28257db2021-03-17 15:18:09 -0400648 const Block& body = function.body()->as<Block>();
John Stiles77702f12020-12-17 14:38:56 -0500649 const ReturnComplexity returnComplexity = GetReturnComplexity(function);
John Stiles6eadf132020-09-08 10:16:10 -0400650
John Stiles28257db2021-03-17 15:18:09 -0400651 StatementArray inlineStatements;
652 int expectedStmtCount = 1 + // Inline marker
653 1 + // Result variable
654 arguments.size() + // Function argument temp-vars
655 body.children().size(); // Inlined code
John Stiles98c1f822020-09-09 14:18:53 -0400656
John Stiles28257db2021-03-17 15:18:09 -0400657 inlineStatements.reserve_back(expectedStmtCount);
658 inlineStatements.push_back(InlineMarker::Make(&call->function()));
John Stiles44e96be2020-08-31 13:16:04 -0400659
John Stilese41b4ee2020-09-28 12:28:16 -0400660 std::unique_ptr<Expression> resultExpr;
John Stiles511c5002021-02-25 11:17:02 -0500661 if (returnComplexity > ReturnComplexity::kSingleSafeReturn &&
John Stiles2558c462021-03-16 17:49:20 -0400662 !function.declaration().returnType().isVoid()) {
John Stiles511c5002021-02-25 11:17:02 -0500663 // Create a variable to hold the result in the extra statements. We don't need to do this
664 // for void-return functions, or in cases that are simple enough that we can just replace
665 // the function-call node with the result expression.
John Stiles44e96be2020-08-31 13:16:04 -0400666 std::unique_ptr<Expression> noInitialValue;
Ethan Nicholasd2e09602021-06-10 11:21:59 -0400667 InlineVariable var = this->makeInlineVariable(String(function.declaration().name()),
John Stiles7b920442020-12-17 10:43:41 -0500668 &function.declaration().returnType(),
669 symbolTable.get(), Modifiers{},
670 caller->isBuiltin(), &noInitialValue);
John Stiles28257db2021-03-17 15:18:09 -0400671 inlineStatements.push_back(std::move(var.fVarDecl));
John Stilesa94e0262021-04-27 17:29:59 -0400672 resultExpr = VariableReference::Make(/*offset=*/-1, var.fVarSymbol);
John Stiles511c5002021-02-25 11:17:02 -0500673 }
John Stiles44e96be2020-08-31 13:16:04 -0400674
675 // Create variables in the extra statements to hold the arguments, and assign the arguments to
676 // them.
677 VariableRewriteMap varMap;
John Stilesbff24ab2021-03-17 13:20:10 -0400678 for (int i = 0; i < arguments.count(); ++i) {
John Stiles049f0df2021-03-19 09:39:44 -0400679 // If the parameter isn't written to within the inline function ...
John Stilesbff24ab2021-03-17 13:20:10 -0400680 const Variable* param = function.declaration().parameters()[i];
John Stiles049f0df2021-03-19 09:39:44 -0400681 const ProgramUsage::VariableCounts& paramUsage = usage.get(*param);
682 if (!paramUsage.fWrite) {
683 // ... and can be inlined trivially (e.g. a swizzle, or a constant array index),
684 // or any expression without side effects that is only accessed at most once...
685 if ((paramUsage.fRead > 1) ? Analysis::IsTrivialExpression(*arguments[i])
686 : !arguments[i]->hasSideEffects()) {
John Stilesf201af82020-09-29 16:57:55 -0400687 // ... we don't need to copy it at all! We can just use the existing expression.
688 varMap[param] = arguments[i]->clone();
John Stiles44e96be2020-08-31 13:16:04 -0400689 continue;
690 }
691 }
Ethan Nicholasd2e09602021-06-10 11:21:59 -0400692 InlineVariable var = this->makeInlineVariable(String(param->name()), &arguments[i]->type(),
John Stiles7b920442020-12-17 10:43:41 -0500693 symbolTable.get(), param->modifiers(),
694 caller->isBuiltin(), &arguments[i]);
John Stiles28257db2021-03-17 15:18:09 -0400695 inlineStatements.push_back(std::move(var.fVarDecl));
John Stilesa94e0262021-04-27 17:29:59 -0400696 varMap[param] = VariableReference::Make(/*offset=*/-1, var.fVarSymbol);
John Stiles44e96be2020-08-31 13:16:04 -0400697 }
698
John Stiles7b920442020-12-17 10:43:41 -0500699 for (const std::unique_ptr<Statement>& stmt : body.children()) {
John Stiles28257db2021-03-17 15:18:09 -0400700 inlineStatements.push_back(this->inlineStatement(offset, &varMap, symbolTable.get(),
701 &resultExpr, returnComplexity, *stmt,
702 caller->isBuiltin()));
John Stiles44e96be2020-08-31 13:16:04 -0400703 }
704
John Stiles28257db2021-03-17 15:18:09 -0400705 SkASSERT(inlineStatements.count() <= expectedStmtCount);
706
John Stilesbf16b6c2021-03-12 19:24:31 -0500707 // Wrap all of the generated statements in a block. We need a real Block here, so we can't use
708 // MakeUnscoped. This is because we need to add another child statement to the Block later.
John Stiles28257db2021-03-17 15:18:09 -0400709 InlinedCall inlinedCall;
710 inlinedCall.fInlinedBody = Block::Make(offset, std::move(inlineStatements),
John Stilesbf16b6c2021-03-12 19:24:31 -0500711 /*symbols=*/nullptr, /*isScope=*/false);
712
John Stiles0c2d14a2021-03-01 10:08:08 -0500713 if (resultExpr) {
714 // Return our result expression as-is.
John Stilese41b4ee2020-09-28 12:28:16 -0400715 inlinedCall.fReplacementExpr = std::move(resultExpr);
John Stiles2558c462021-03-16 17:49:20 -0400716 } else if (function.declaration().returnType().isVoid()) {
John Stiles44e96be2020-08-31 13:16:04 -0400717 // It's a void function, so it doesn't actually result in anything, but we have to return
718 // something non-null as a standin.
John Stiles9ce80f72021-03-11 22:35:19 -0500719 inlinedCall.fReplacementExpr = BoolLiteral::Make(*fContext, offset, /*value=*/false);
John Stiles0c2d14a2021-03-01 10:08:08 -0500720 } else {
721 // It's a non-void function, but it never created a result expression--that is, it never
John Stiles2dda50d2021-03-03 10:46:44 -0500722 // returned anything on any path! This should have been detected in the function finalizer.
723 // Still, discard our output and generate an error.
724 SkDEBUGFAIL("inliner found non-void function that fails to return a value on any path");
Ethan Nicholas39f6da42021-08-23 13:10:07 -0400725 fContext->fErrors->error(function.fOffset, "inliner found non-void function '" +
Ethan Nicholas8d116542021-08-11 13:27:16 -0400726 function.declaration().name() +
727 "' that fails to return a value on any path");
John Stiles0c2d14a2021-03-01 10:08:08 -0500728 inlinedCall = {};
John Stiles44e96be2020-08-31 13:16:04 -0400729 }
730
John Stiles44e96be2020-08-31 13:16:04 -0400731 return inlinedCall;
732}
733
John Stiles2d7973a2020-10-02 15:01:03 -0400734bool Inliner::isSafeToInline(const FunctionDefinition* functionDef) {
John Stiles1c03d332020-10-13 10:30:23 -0400735 // A threshold of zero indicates that the inliner is completely disabled, so we can just return.
John Stilesd1204642021-02-17 16:30:02 -0500736 if (this->settings().fInlineThreshold <= 0) {
John Stiles1c03d332020-10-13 10:30:23 -0400737 return false;
738 }
739
John Stiles031a7672020-11-13 16:13:18 -0500740 // Enforce a limit on inlining to avoid pathological cases. (inliner/ExponentialGrowth.sksl)
741 if (fInlinedStatementCounter >= kInlinedStatementLimit) {
742 return false;
743 }
744
John Stiles2d7973a2020-10-02 15:01:03 -0400745 if (functionDef == nullptr) {
John Stiles44e96be2020-08-31 13:16:04 -0400746 // Can't inline something if we don't actually have its definition.
747 return false;
748 }
John Stiles2d7973a2020-10-02 15:01:03 -0400749
John Stiles0dd1a772021-03-09 22:14:27 -0500750 if (functionDef->declaration().modifiers().fFlags & Modifiers::kNoInline_Flag) {
751 // Refuse to inline functions decorated with `noinline`.
752 return false;
753 }
754
John Stilesbff24ab2021-03-17 13:20:10 -0400755 // We don't allow inlining a function with out parameters. (See skia:11326 for rationale.)
756 for (const Variable* param : functionDef->declaration().parameters()) {
757 if (param->modifiers().fFlags & Modifiers::Flag::kOut_Flag) {
758 return false;
759 }
760 }
761
John Stilesdc208472021-03-17 10:58:16 -0400762 // We don't have a mechanism to simulate early returns, so we can't inline if there is one.
763 return GetReturnComplexity(*functionDef) < ReturnComplexity::kEarlyReturns;
John Stiles44e96be2020-08-31 13:16:04 -0400764}
765
John Stiles2d7973a2020-10-02 15:01:03 -0400766// A candidate function for inlining, containing everything that `inlineCall` needs.
767struct InlineCandidate {
John Stiles78047582020-12-16 16:17:41 -0500768 std::shared_ptr<SymbolTable> fSymbols; // the SymbolTable of the candidate
John Stiles2d7973a2020-10-02 15:01:03 -0400769 std::unique_ptr<Statement>* fParentStmt; // the parent Statement of the enclosing stmt
770 std::unique_ptr<Statement>* fEnclosingStmt; // the Statement containing the candidate
771 std::unique_ptr<Expression>* fCandidateExpr; // the candidate FunctionCall to be inlined
772 FunctionDefinition* fEnclosingFunction; // the Function containing the candidate
John Stiles2d7973a2020-10-02 15:01:03 -0400773};
John Stiles93442622020-09-11 12:11:27 -0400774
John Stiles2d7973a2020-10-02 15:01:03 -0400775struct InlineCandidateList {
776 std::vector<InlineCandidate> fCandidates;
777};
778
779class InlineCandidateAnalyzer {
John Stiles70957c82020-10-02 16:42:10 -0400780public:
781 // A list of all the inlining candidates we found during analysis.
782 InlineCandidateList* fCandidateList;
John Stiles2d7973a2020-10-02 15:01:03 -0400783
John Stiles70957c82020-10-02 16:42:10 -0400784 // A stack of the symbol tables; since most nodes don't have one, expected to be shallower than
785 // the enclosing-statement stack.
John Stiles78047582020-12-16 16:17:41 -0500786 std::vector<std::shared_ptr<SymbolTable>> fSymbolTableStack;
John Stiles70957c82020-10-02 16:42:10 -0400787 // A stack of "enclosing" statements--these would be suitable for the inliner to use for adding
788 // new instructions. Not all statements are suitable (e.g. a for-loop's initializer). The
789 // inliner might replace a statement with a block containing the statement.
790 std::vector<std::unique_ptr<Statement>*> fEnclosingStmtStack;
791 // The function that we're currently processing (i.e. inlining into).
792 FunctionDefinition* fEnclosingFunction = nullptr;
John Stiles93442622020-09-11 12:11:27 -0400793
Brian Osman0006ad02020-11-18 15:38:39 -0500794 void visit(const std::vector<std::unique_ptr<ProgramElement>>& elements,
John Stiles78047582020-12-16 16:17:41 -0500795 std::shared_ptr<SymbolTable> symbols,
Brian Osman0006ad02020-11-18 15:38:39 -0500796 InlineCandidateList* candidateList) {
John Stiles70957c82020-10-02 16:42:10 -0400797 fCandidateList = candidateList;
Brian Osman0006ad02020-11-18 15:38:39 -0500798 fSymbolTableStack.push_back(symbols);
John Stiles93442622020-09-11 12:11:27 -0400799
Brian Osman0006ad02020-11-18 15:38:39 -0500800 for (const std::unique_ptr<ProgramElement>& pe : elements) {
Brian Osman1179fcf2020-10-08 16:04:40 -0400801 this->visitProgramElement(pe.get());
John Stiles93442622020-09-11 12:11:27 -0400802 }
803
John Stiles70957c82020-10-02 16:42:10 -0400804 fSymbolTableStack.pop_back();
805 fCandidateList = nullptr;
806 }
807
808 void visitProgramElement(ProgramElement* pe) {
809 switch (pe->kind()) {
810 case ProgramElement::Kind::kFunction: {
811 FunctionDefinition& funcDef = pe->as<FunctionDefinition>();
Brian Osman0006ad02020-11-18 15:38:39 -0500812 fEnclosingFunction = &funcDef;
813 this->visitStatement(&funcDef.body());
John Stiles70957c82020-10-02 16:42:10 -0400814 break;
John Stiles93442622020-09-11 12:11:27 -0400815 }
John Stiles70957c82020-10-02 16:42:10 -0400816 default:
817 // The inliner can't operate outside of a function's scope.
818 break;
819 }
820 }
821
822 void visitStatement(std::unique_ptr<Statement>* stmt,
823 bool isViableAsEnclosingStatement = true) {
824 if (!*stmt) {
825 return;
John Stiles93442622020-09-11 12:11:27 -0400826 }
827
John Stiles70957c82020-10-02 16:42:10 -0400828 size_t oldEnclosingStmtStackSize = fEnclosingStmtStack.size();
829 size_t oldSymbolStackSize = fSymbolTableStack.size();
John Stiles93442622020-09-11 12:11:27 -0400830
John Stiles70957c82020-10-02 16:42:10 -0400831 if (isViableAsEnclosingStatement) {
832 fEnclosingStmtStack.push_back(stmt);
John Stiles93442622020-09-11 12:11:27 -0400833 }
834
John Stiles70957c82020-10-02 16:42:10 -0400835 switch ((*stmt)->kind()) {
836 case Statement::Kind::kBreak:
837 case Statement::Kind::kContinue:
838 case Statement::Kind::kDiscard:
839 case Statement::Kind::kInlineMarker:
840 case Statement::Kind::kNop:
841 break;
842
843 case Statement::Kind::kBlock: {
844 Block& block = (*stmt)->as<Block>();
845 if (block.symbolTable()) {
John Stiles78047582020-12-16 16:17:41 -0500846 fSymbolTableStack.push_back(block.symbolTable());
John Stiles70957c82020-10-02 16:42:10 -0400847 }
848
John Stiles628777c2021-08-04 22:07:41 -0400849 for (std::unique_ptr<Statement>& blockStmt : block.children()) {
850 this->visitStatement(&blockStmt);
John Stiles70957c82020-10-02 16:42:10 -0400851 }
852 break;
John Stiles93442622020-09-11 12:11:27 -0400853 }
John Stiles70957c82020-10-02 16:42:10 -0400854 case Statement::Kind::kDo: {
855 DoStatement& doStmt = (*stmt)->as<DoStatement>();
856 // The loop body is a candidate for inlining.
857 this->visitStatement(&doStmt.statement());
858 // The inliner isn't smart enough to inline the test-expression for a do-while
859 // loop at this time. There are two limitations:
860 // - We would need to insert the inlined-body block at the very end of the do-
861 // statement's inner fStatement. We don't support that today, but it's doable.
862 // - We cannot inline the test expression if the loop uses `continue` anywhere; that
863 // would skip over the inlined block that evaluates the test expression. There
864 // isn't a good fix for this--any workaround would be more complex than the cost
865 // of a function call. However, loops that don't use `continue` would still be
866 // viable candidates for inlining.
867 break;
John Stiles93442622020-09-11 12:11:27 -0400868 }
John Stiles70957c82020-10-02 16:42:10 -0400869 case Statement::Kind::kExpression: {
870 ExpressionStatement& expr = (*stmt)->as<ExpressionStatement>();
871 this->visitExpression(&expr.expression());
872 break;
873 }
874 case Statement::Kind::kFor: {
875 ForStatement& forStmt = (*stmt)->as<ForStatement>();
Ethan Nicholas0d31ed52020-10-05 14:47:09 -0400876 if (forStmt.symbols()) {
John Stiles78047582020-12-16 16:17:41 -0500877 fSymbolTableStack.push_back(forStmt.symbols());
John Stiles70957c82020-10-02 16:42:10 -0400878 }
879
880 // The initializer and loop body are candidates for inlining.
Ethan Nicholas0d31ed52020-10-05 14:47:09 -0400881 this->visitStatement(&forStmt.initializer(),
John Stiles70957c82020-10-02 16:42:10 -0400882 /*isViableAsEnclosingStatement=*/false);
Ethan Nicholas0d31ed52020-10-05 14:47:09 -0400883 this->visitStatement(&forStmt.statement());
John Stiles70957c82020-10-02 16:42:10 -0400884
885 // The inliner isn't smart enough to inline the test- or increment-expressions
886 // of a for loop loop at this time. There are a handful of limitations:
887 // - We would need to insert the test-expression block at the very beginning of the
888 // for-loop's inner fStatement, and the increment-expression block at the very
889 // end. We don't support that today, but it's doable.
890 // - The for-loop's built-in test-expression would need to be dropped entirely,
891 // and the loop would be halted via a break statement at the end of the inlined
892 // test-expression. This is again something we don't support today, but it could
893 // be implemented.
894 // - We cannot inline the increment-expression if the loop uses `continue` anywhere;
895 // that would skip over the inlined block that evaluates the increment expression.
896 // There isn't a good fix for this--any workaround would be more complex than the
897 // cost of a function call. However, loops that don't use `continue` would still
898 // be viable candidates for increment-expression inlining.
899 break;
900 }
901 case Statement::Kind::kIf: {
902 IfStatement& ifStmt = (*stmt)->as<IfStatement>();
Ethan Nicholas8c44eca2020-10-07 16:47:09 -0400903 this->visitExpression(&ifStmt.test());
904 this->visitStatement(&ifStmt.ifTrue());
905 this->visitStatement(&ifStmt.ifFalse());
John Stiles70957c82020-10-02 16:42:10 -0400906 break;
907 }
908 case Statement::Kind::kReturn: {
909 ReturnStatement& returnStmt = (*stmt)->as<ReturnStatement>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -0400910 this->visitExpression(&returnStmt.expression());
John Stiles70957c82020-10-02 16:42:10 -0400911 break;
912 }
913 case Statement::Kind::kSwitch: {
914 SwitchStatement& switchStmt = (*stmt)->as<SwitchStatement>();
Ethan Nicholas01b05e52020-10-22 15:53:41 -0400915 if (switchStmt.symbols()) {
John Stiles78047582020-12-16 16:17:41 -0500916 fSymbolTableStack.push_back(switchStmt.symbols());
John Stiles70957c82020-10-02 16:42:10 -0400917 }
918
Ethan Nicholas01b05e52020-10-22 15:53:41 -0400919 this->visitExpression(&switchStmt.value());
John Stilesb23a64b2021-03-11 08:27:59 -0500920 for (const std::unique_ptr<Statement>& switchCase : switchStmt.cases()) {
John Stiles70957c82020-10-02 16:42:10 -0400921 // The switch-case's fValue cannot be a FunctionCall; skip it.
John Stilesb23a64b2021-03-11 08:27:59 -0500922 this->visitStatement(&switchCase->as<SwitchCase>().statement());
John Stiles70957c82020-10-02 16:42:10 -0400923 }
924 break;
925 }
926 case Statement::Kind::kVarDeclaration: {
927 VarDeclaration& varDeclStmt = (*stmt)->as<VarDeclaration>();
928 // Don't need to scan the declaration's sizes; those are always IntLiterals.
Ethan Nicholasc51f33e2020-10-13 13:49:44 -0400929 this->visitExpression(&varDeclStmt.value());
John Stiles70957c82020-10-02 16:42:10 -0400930 break;
931 }
John Stiles70957c82020-10-02 16:42:10 -0400932 default:
933 SkUNREACHABLE;
John Stiles93442622020-09-11 12:11:27 -0400934 }
935
John Stiles70957c82020-10-02 16:42:10 -0400936 // Pop our symbol and enclosing-statement stacks.
937 fSymbolTableStack.resize(oldSymbolStackSize);
938 fEnclosingStmtStack.resize(oldEnclosingStmtStackSize);
939 }
940
941 void visitExpression(std::unique_ptr<Expression>* expr) {
942 if (!*expr) {
943 return;
John Stiles93442622020-09-11 12:11:27 -0400944 }
John Stiles70957c82020-10-02 16:42:10 -0400945
946 switch ((*expr)->kind()) {
947 case Expression::Kind::kBoolLiteral:
Brian Osmanbe0b3b72021-01-06 14:27:35 -0500948 case Expression::Kind::kExternalFunctionReference:
John Stiles70957c82020-10-02 16:42:10 -0400949 case Expression::Kind::kFieldAccess:
950 case Expression::Kind::kFloatLiteral:
951 case Expression::Kind::kFunctionReference:
952 case Expression::Kind::kIntLiteral:
Brian Osman3099f792021-09-01 13:12:16 -0400953 case Expression::Kind::kMethodReference:
John Stiles70957c82020-10-02 16:42:10 -0400954 case Expression::Kind::kSetting:
955 case Expression::Kind::kTypeReference:
956 case Expression::Kind::kVariableReference:
957 // Nothing to scan here.
958 break;
959
960 case Expression::Kind::kBinary: {
961 BinaryExpression& binaryExpr = (*expr)->as<BinaryExpression>();
John Stiles2d4f9592020-10-30 10:29:12 -0400962 this->visitExpression(&binaryExpr.left());
John Stiles70957c82020-10-02 16:42:10 -0400963
964 // Logical-and and logical-or binary expressions do not inline the right side,
965 // because that would invalidate short-circuiting. That is, when evaluating
966 // expressions like these:
967 // (false && x()) // always false
968 // (true || y()) // always true
969 // It is illegal for side-effects from x() or y() to occur. The simplest way to
970 // enforce that rule is to avoid inlining the right side entirely. However, it is
971 // safe for other types of binary expression to inline both sides.
John Stiles45990502021-02-16 10:55:27 -0500972 Operator op = binaryExpr.getOperator();
973 bool shortCircuitable = (op.kind() == Token::Kind::TK_LOGICALAND ||
974 op.kind() == Token::Kind::TK_LOGICALOR);
John Stiles70957c82020-10-02 16:42:10 -0400975 if (!shortCircuitable) {
John Stiles2d4f9592020-10-30 10:29:12 -0400976 this->visitExpression(&binaryExpr.right());
John Stiles70957c82020-10-02 16:42:10 -0400977 }
978 break;
979 }
Brian Osmaneb0f29d2021-08-04 11:34:16 -0400980 case Expression::Kind::kChildCall: {
981 ChildCall& childCallExpr = (*expr)->as<ChildCall>();
982 for (std::unique_ptr<Expression>& arg : childCallExpr.arguments()) {
983 this->visitExpression(&arg);
984 }
985 break;
986 }
John Stiles7384b372021-04-01 13:48:15 -0400987 case Expression::Kind::kConstructorArray:
John Stilese3ae9682021-08-05 10:35:01 -0400988 case Expression::Kind::kConstructorArrayCast:
John Stiles8cad6372021-04-07 12:31:13 -0400989 case Expression::Kind::kConstructorCompound:
990 case Expression::Kind::kConstructorCompoundCast:
John Stiles2938eea2021-04-01 18:58:25 -0400991 case Expression::Kind::kConstructorDiagonalMatrix:
John Stiles5abb9e12021-04-06 13:47:19 -0400992 case Expression::Kind::kConstructorMatrixResize:
John Stilesfd7252f2021-04-04 22:24:40 -0400993 case Expression::Kind::kConstructorScalarCast:
John Stilesd47330f2021-04-08 23:25:52 -0400994 case Expression::Kind::kConstructorSplat:
995 case Expression::Kind::kConstructorStruct: {
John Stiles7384b372021-04-01 13:48:15 -0400996 AnyConstructor& constructorExpr = (*expr)->asAnyConstructor();
997 for (std::unique_ptr<Expression>& arg : constructorExpr.argumentSpan()) {
John Stiles70957c82020-10-02 16:42:10 -0400998 this->visitExpression(&arg);
999 }
1000 break;
1001 }
1002 case Expression::Kind::kExternalFunctionCall: {
1003 ExternalFunctionCall& funcCallExpr = (*expr)->as<ExternalFunctionCall>();
1004 for (std::unique_ptr<Expression>& arg : funcCallExpr.arguments()) {
1005 this->visitExpression(&arg);
1006 }
1007 break;
1008 }
1009 case Expression::Kind::kFunctionCall: {
1010 FunctionCall& funcCallExpr = (*expr)->as<FunctionCall>();
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001011 for (std::unique_ptr<Expression>& arg : funcCallExpr.arguments()) {
John Stiles70957c82020-10-02 16:42:10 -04001012 this->visitExpression(&arg);
1013 }
1014 this->addInlineCandidate(expr);
1015 break;
1016 }
John Stiles708faba2021-03-19 09:43:23 -04001017 case Expression::Kind::kIndex: {
John Stiles70957c82020-10-02 16:42:10 -04001018 IndexExpression& indexExpr = (*expr)->as<IndexExpression>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04001019 this->visitExpression(&indexExpr.base());
1020 this->visitExpression(&indexExpr.index());
John Stiles70957c82020-10-02 16:42:10 -04001021 break;
1022 }
1023 case Expression::Kind::kPostfix: {
1024 PostfixExpression& postfixExpr = (*expr)->as<PostfixExpression>();
Ethan Nicholas444ccc62020-10-09 10:16:22 -04001025 this->visitExpression(&postfixExpr.operand());
John Stiles70957c82020-10-02 16:42:10 -04001026 break;
1027 }
1028 case Expression::Kind::kPrefix: {
1029 PrefixExpression& prefixExpr = (*expr)->as<PrefixExpression>();
Ethan Nicholas444ccc62020-10-09 10:16:22 -04001030 this->visitExpression(&prefixExpr.operand());
John Stiles70957c82020-10-02 16:42:10 -04001031 break;
1032 }
1033 case Expression::Kind::kSwizzle: {
1034 Swizzle& swizzleExpr = (*expr)->as<Swizzle>();
Ethan Nicholas6b4d5812020-10-12 16:11:51 -04001035 this->visitExpression(&swizzleExpr.base());
John Stiles70957c82020-10-02 16:42:10 -04001036 break;
1037 }
1038 case Expression::Kind::kTernary: {
1039 TernaryExpression& ternaryExpr = (*expr)->as<TernaryExpression>();
1040 // The test expression is a candidate for inlining.
Ethan Nicholasdd218162020-10-08 05:48:01 -04001041 this->visitExpression(&ternaryExpr.test());
John Stiles70957c82020-10-02 16:42:10 -04001042 // The true- and false-expressions cannot be inlined, because we are only allowed to
1043 // evaluate one side.
1044 break;
1045 }
1046 default:
1047 SkUNREACHABLE;
1048 }
1049 }
1050
1051 void addInlineCandidate(std::unique_ptr<Expression>* candidate) {
1052 fCandidateList->fCandidates.push_back(
1053 InlineCandidate{fSymbolTableStack.back(),
1054 find_parent_statement(fEnclosingStmtStack),
1055 fEnclosingStmtStack.back(),
1056 candidate,
John Stiles9b9415e2020-11-23 14:48:06 -05001057 fEnclosingFunction});
John Stiles70957c82020-10-02 16:42:10 -04001058 }
John Stiles2d7973a2020-10-02 15:01:03 -04001059};
John Stiles93442622020-09-11 12:11:27 -04001060
John Stiles9b9415e2020-11-23 14:48:06 -05001061static const FunctionDeclaration& candidate_func(const InlineCandidate& candidate) {
1062 return (*candidate.fCandidateExpr)->as<FunctionCall>().function();
1063}
John Stiles915a38c2020-09-14 09:38:13 -04001064
John Stiles9b9415e2020-11-23 14:48:06 -05001065bool Inliner::candidateCanBeInlined(const InlineCandidate& candidate, InlinabilityCache* cache) {
1066 const FunctionDeclaration& funcDecl = candidate_func(candidate);
John Stiles1c03d332020-10-13 10:30:23 -04001067 auto [iter, wasInserted] = cache->insert({&funcDecl, false});
John Stiles2d7973a2020-10-02 15:01:03 -04001068 if (wasInserted) {
1069 // Recursion is forbidden here to avoid an infinite death spiral of inlining.
John Stiles132cfdd2021-03-15 22:08:38 +00001070 iter->second = this->isSafeToInline(funcDecl.definition()) &&
1071 !contains_recursive_call(funcDecl);
John Stiles93442622020-09-11 12:11:27 -04001072 }
1073
John Stiles2d7973a2020-10-02 15:01:03 -04001074 return iter->second;
1075}
1076
John Stiles9b9415e2020-11-23 14:48:06 -05001077int Inliner::getFunctionSize(const FunctionDeclaration& funcDecl, FunctionSizeCache* cache) {
1078 auto [iter, wasInserted] = cache->insert({&funcDecl, 0});
John Stiles2d7973a2020-10-02 15:01:03 -04001079 if (wasInserted) {
John Stiles9b9415e2020-11-23 14:48:06 -05001080 iter->second = Analysis::NodeCountUpToLimit(*funcDecl.definition(),
John Stilesd1204642021-02-17 16:30:02 -05001081 this->settings().fInlineThreshold);
John Stiles2d7973a2020-10-02 15:01:03 -04001082 }
John Stiles2d7973a2020-10-02 15:01:03 -04001083 return iter->second;
1084}
1085
Brian Osman0006ad02020-11-18 15:38:39 -05001086void Inliner::buildCandidateList(const std::vector<std::unique_ptr<ProgramElement>>& elements,
John Stiles78047582020-12-16 16:17:41 -05001087 std::shared_ptr<SymbolTable> symbols, ProgramUsage* usage,
Brian Osman0006ad02020-11-18 15:38:39 -05001088 InlineCandidateList* candidateList) {
John Stiles2d7973a2020-10-02 15:01:03 -04001089 // This is structured much like a ProgramVisitor, but does not actually use ProgramVisitor.
1090 // The analyzer needs to keep track of the `unique_ptr<T>*` of statements and expressions so
1091 // that they can later be replaced, and ProgramVisitor does not provide this; it only provides a
1092 // `const T&`.
1093 InlineCandidateAnalyzer analyzer;
Brian Osman0006ad02020-11-18 15:38:39 -05001094 analyzer.visit(elements, symbols, candidateList);
John Stiles2d7973a2020-10-02 15:01:03 -04001095
John Stiles0ad233f2020-11-25 11:02:05 -05001096 // Early out if there are no inlining candidates.
John Stiles2d7973a2020-10-02 15:01:03 -04001097 std::vector<InlineCandidate>& candidates = candidateList->fCandidates;
John Stiles0ad233f2020-11-25 11:02:05 -05001098 if (candidates.empty()) {
1099 return;
1100 }
1101
1102 // Remove candidates that are not safe to inline.
John Stiles2d7973a2020-10-02 15:01:03 -04001103 InlinabilityCache cache;
1104 candidates.erase(std::remove_if(candidates.begin(),
1105 candidates.end(),
1106 [&](const InlineCandidate& candidate) {
1107 return !this->candidateCanBeInlined(candidate, &cache);
1108 }),
1109 candidates.end());
1110
John Stiles0ad233f2020-11-25 11:02:05 -05001111 // If the inline threshold is unlimited, or if we have no candidates left, our candidate list is
1112 // complete.
John Stilesd1204642021-02-17 16:30:02 -05001113 if (this->settings().fInlineThreshold == INT_MAX || candidates.empty()) {
John Stiles0ad233f2020-11-25 11:02:05 -05001114 return;
John Stiles2d7973a2020-10-02 15:01:03 -04001115 }
John Stiles0ad233f2020-11-25 11:02:05 -05001116
1117 // Remove candidates on a per-function basis if the effect of inlining would be to make more
1118 // than `inlineThreshold` nodes. (i.e. if Func() would be inlined six times and its size is
1119 // 10 nodes, it should be inlined if the inlineThreshold is 60 or higher.)
1120 FunctionSizeCache functionSizeCache;
1121 FunctionSizeCache candidateTotalCost;
1122 for (InlineCandidate& candidate : candidates) {
1123 const FunctionDeclaration& fnDecl = candidate_func(candidate);
1124 candidateTotalCost[&fnDecl] += this->getFunctionSize(fnDecl, &functionSizeCache);
1125 }
1126
John Stilesd1204642021-02-17 16:30:02 -05001127 candidates.erase(std::remove_if(candidates.begin(), candidates.end(),
1128 [&](const InlineCandidate& candidate) {
1129 const FunctionDeclaration& fnDecl = candidate_func(candidate);
1130 if (fnDecl.modifiers().fFlags & Modifiers::kInline_Flag) {
1131 // Functions marked `inline` ignore size limitations.
1132 return false;
1133 }
1134 if (usage->get(fnDecl) == 1) {
1135 // If a function is only used once, it's cost-free to inline.
1136 return false;
1137 }
1138 if (candidateTotalCost[&fnDecl] <= this->settings().fInlineThreshold) {
1139 // We won't exceed the inline threshold by inlining this.
1140 return false;
1141 }
1142 // Inlining this function will add too many IRNodes.
1143 return true;
1144 }),
1145 candidates.end());
John Stiles2d7973a2020-10-02 15:01:03 -04001146}
1147
Brian Osman0006ad02020-11-18 15:38:39 -05001148bool Inliner::analyze(const std::vector<std::unique_ptr<ProgramElement>>& elements,
John Stiles78047582020-12-16 16:17:41 -05001149 std::shared_ptr<SymbolTable> symbols,
Brian Osman0006ad02020-11-18 15:38:39 -05001150 ProgramUsage* usage) {
John Stilesd34d56e2020-10-12 12:04:47 -04001151 // A threshold of zero indicates that the inliner is completely disabled, so we can just return.
John Stilesd1204642021-02-17 16:30:02 -05001152 if (this->settings().fInlineThreshold <= 0) {
John Stilesd34d56e2020-10-12 12:04:47 -04001153 return false;
1154 }
1155
John Stiles031a7672020-11-13 16:13:18 -05001156 // Enforce a limit on inlining to avoid pathological cases. (inliner/ExponentialGrowth.sksl)
1157 if (fInlinedStatementCounter >= kInlinedStatementLimit) {
1158 return false;
1159 }
1160
John Stiles2d7973a2020-10-02 15:01:03 -04001161 InlineCandidateList candidateList;
John Stiles9b9415e2020-11-23 14:48:06 -05001162 this->buildCandidateList(elements, symbols, usage, &candidateList);
John Stiles2d7973a2020-10-02 15:01:03 -04001163
John Stiles915a38c2020-09-14 09:38:13 -04001164 // Inline the candidates where we've determined that it's safe to do so.
John Stiles708faba2021-03-19 09:43:23 -04001165 using StatementRemappingTable = std::unordered_map<std::unique_ptr<Statement>*,
1166 std::unique_ptr<Statement>*>;
1167 StatementRemappingTable statementRemappingTable;
1168
John Stiles915a38c2020-09-14 09:38:13 -04001169 bool madeChanges = false;
John Stiles2d7973a2020-10-02 15:01:03 -04001170 for (const InlineCandidate& candidate : candidateList.fCandidates) {
John Stiles915a38c2020-09-14 09:38:13 -04001171 FunctionCall& funcCall = (*candidate.fCandidateExpr)->as<FunctionCall>();
John Stiles915a38c2020-09-14 09:38:13 -04001172
John Stiles915a38c2020-09-14 09:38:13 -04001173 // Convert the function call to its inlined equivalent.
John Stiles30fce9c2021-03-18 09:24:06 -04001174 InlinedCall inlinedCall = this->inlineCall(&funcCall, candidate.fSymbols, *usage,
Ethan Nicholas0a5d0962020-10-14 13:33:18 -04001175 &candidate.fEnclosingFunction->declaration());
John Stiles915a38c2020-09-14 09:38:13 -04001176
John Stiles0c2d14a2021-03-01 10:08:08 -05001177 // Stop if an error was detected during the inlining process.
1178 if (!inlinedCall.fInlinedBody && !inlinedCall.fReplacementExpr) {
1179 break;
John Stiles915a38c2020-09-14 09:38:13 -04001180 }
1181
John Stiles0c2d14a2021-03-01 10:08:08 -05001182 // Ensure that the inlined body has a scope if it needs one.
1183 this->ensureScopedBlocks(inlinedCall.fInlinedBody.get(), candidate.fParentStmt->get());
1184
1185 // Add references within the inlined body
1186 usage->add(inlinedCall.fInlinedBody.get());
1187
John Stiles708faba2021-03-19 09:43:23 -04001188 // Look up the enclosing statement; remap it if necessary.
1189 std::unique_ptr<Statement>* enclosingStmt = candidate.fEnclosingStmt;
1190 for (;;) {
1191 auto iter = statementRemappingTable.find(enclosingStmt);
1192 if (iter == statementRemappingTable.end()) {
1193 break;
1194 }
1195 enclosingStmt = iter->second;
1196 }
1197
John Stiles0c2d14a2021-03-01 10:08:08 -05001198 // Move the enclosing statement to the end of the unscoped Block containing the inlined
1199 // function, then replace the enclosing statement with that Block.
1200 // Before:
1201 // fInlinedBody = Block{ stmt1, stmt2, stmt3 }
1202 // fEnclosingStmt = stmt4
1203 // After:
1204 // fInlinedBody = null
1205 // fEnclosingStmt = Block{ stmt1, stmt2, stmt3, stmt4 }
John Stiles708faba2021-03-19 09:43:23 -04001206 inlinedCall.fInlinedBody->children().push_back(std::move(*enclosingStmt));
1207 *enclosingStmt = std::move(inlinedCall.fInlinedBody);
John Stiles0c2d14a2021-03-01 10:08:08 -05001208
John Stiles915a38c2020-09-14 09:38:13 -04001209 // Replace the candidate function call with our replacement expression.
John Stiles60dbf072021-08-02 14:22:34 -04001210 usage->remove(candidate.fCandidateExpr->get());
1211 usage->add(inlinedCall.fReplacementExpr.get());
John Stiles915a38c2020-09-14 09:38:13 -04001212 *candidate.fCandidateExpr = std::move(inlinedCall.fReplacementExpr);
1213 madeChanges = true;
1214
John Stiles708faba2021-03-19 09:43:23 -04001215 // If anything else pointed at our enclosing statement, it's now pointing at a Block
1216 // containing many other statements as well. Maintain a fix-up table to account for this.
1217 statementRemappingTable[enclosingStmt] = &(*enclosingStmt)->as<Block>().children().back();
1218
John Stiles031a7672020-11-13 16:13:18 -05001219 // Stop inlining if we've reached our hard cap on new statements.
1220 if (fInlinedStatementCounter >= kInlinedStatementLimit) {
1221 break;
1222 }
1223
John Stiles915a38c2020-09-14 09:38:13 -04001224 // Note that nothing was destroyed except for the FunctionCall. All other nodes should
1225 // remain valid.
1226 }
1227
1228 return madeChanges;
John Stiles93442622020-09-11 12:11:27 -04001229}
1230
John Stiles44e96be2020-08-31 13:16:04 -04001231} // namespace SkSL