blob: 32f2df7ba8615363717b6cfee0c205718583fcc4 [file] [log] [blame]
John Stiles44e96be2020-08-31 13:16:04 -04001/*
2 * Copyright 2020 Google LLC
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
7
8#include "src/sksl/SkSLInliner.h"
9
John Stiles2d7973a2020-10-02 15:01:03 -040010#include <limits.h>
John Stiles44e96be2020-08-31 13:16:04 -040011#include <memory>
12#include <unordered_set>
13
Ethan Nicholasdaed2592021-03-04 14:30:25 -050014#include "include/private/SkSLLayout.h"
John Stiles44e96be2020-08-31 13:16:04 -040015#include "src/sksl/SkSLAnalysis.h"
16#include "src/sksl/ir/SkSLBinaryExpression.h"
17#include "src/sksl/ir/SkSLBoolLiteral.h"
18#include "src/sksl/ir/SkSLBreakStatement.h"
19#include "src/sksl/ir/SkSLConstructor.h"
20#include "src/sksl/ir/SkSLContinueStatement.h"
21#include "src/sksl/ir/SkSLDiscardStatement.h"
22#include "src/sksl/ir/SkSLDoStatement.h"
23#include "src/sksl/ir/SkSLEnum.h"
24#include "src/sksl/ir/SkSLExpressionStatement.h"
25#include "src/sksl/ir/SkSLExternalFunctionCall.h"
Brian Osmanbe0b3b72021-01-06 14:27:35 -050026#include "src/sksl/ir/SkSLExternalFunctionReference.h"
John Stiles44e96be2020-08-31 13:16:04 -040027#include "src/sksl/ir/SkSLField.h"
28#include "src/sksl/ir/SkSLFieldAccess.h"
29#include "src/sksl/ir/SkSLFloatLiteral.h"
30#include "src/sksl/ir/SkSLForStatement.h"
31#include "src/sksl/ir/SkSLFunctionCall.h"
32#include "src/sksl/ir/SkSLFunctionDeclaration.h"
33#include "src/sksl/ir/SkSLFunctionDefinition.h"
34#include "src/sksl/ir/SkSLFunctionReference.h"
35#include "src/sksl/ir/SkSLIfStatement.h"
36#include "src/sksl/ir/SkSLIndexExpression.h"
John Stiles98c1f822020-09-09 14:18:53 -040037#include "src/sksl/ir/SkSLInlineMarker.h"
John Stiles44e96be2020-08-31 13:16:04 -040038#include "src/sksl/ir/SkSLIntLiteral.h"
39#include "src/sksl/ir/SkSLInterfaceBlock.h"
John Stiles44e96be2020-08-31 13:16:04 -040040#include "src/sksl/ir/SkSLNop.h"
John Stiles44e96be2020-08-31 13:16:04 -040041#include "src/sksl/ir/SkSLPostfixExpression.h"
42#include "src/sksl/ir/SkSLPrefixExpression.h"
43#include "src/sksl/ir/SkSLReturnStatement.h"
44#include "src/sksl/ir/SkSLSetting.h"
45#include "src/sksl/ir/SkSLSwitchCase.h"
46#include "src/sksl/ir/SkSLSwitchStatement.h"
47#include "src/sksl/ir/SkSLSwizzle.h"
48#include "src/sksl/ir/SkSLTernaryExpression.h"
49#include "src/sksl/ir/SkSLUnresolvedFunction.h"
50#include "src/sksl/ir/SkSLVarDeclarations.h"
John Stiles44e96be2020-08-31 13:16:04 -040051#include "src/sksl/ir/SkSLVariable.h"
52#include "src/sksl/ir/SkSLVariableReference.h"
John Stiles44e96be2020-08-31 13:16:04 -040053
54namespace SkSL {
55namespace {
56
John Stiles031a7672020-11-13 16:13:18 -050057static constexpr int kInlinedStatementLimit = 2500;
58
John Stiles44e96be2020-08-31 13:16:04 -040059static int count_returns_at_end_of_control_flow(const FunctionDefinition& funcDef) {
60 class CountReturnsAtEndOfControlFlow : public ProgramVisitor {
61 public:
62 CountReturnsAtEndOfControlFlow(const FunctionDefinition& funcDef) {
63 this->visitProgramElement(funcDef);
64 }
65
John Stiles5b408a32021-03-17 09:53:32 -040066 bool visitExpression(const Expression& expr) override {
67 // Do not recurse into expressions.
68 return false;
69 }
70
John Stiles44e96be2020-08-31 13:16:04 -040071 bool visitStatement(const Statement& stmt) override {
Ethan Nicholase6592142020-09-08 10:22:09 -040072 switch (stmt.kind()) {
73 case Statement::Kind::kBlock: {
John Stiles44e96be2020-08-31 13:16:04 -040074 // Check only the last statement of a block.
Ethan Nicholas7bd60432020-09-25 14:31:59 -040075 const auto& block = stmt.as<Block>();
76 return block.children().size() &&
77 this->visitStatement(*block.children().back());
John Stiles44e96be2020-08-31 13:16:04 -040078 }
Ethan Nicholase6592142020-09-08 10:22:09 -040079 case Statement::Kind::kSwitch:
Ethan Nicholase6592142020-09-08 10:22:09 -040080 case Statement::Kind::kDo:
81 case Statement::Kind::kFor:
John Stiles44e96be2020-08-31 13:16:04 -040082 // Don't introspect switches or loop structures at all.
83 return false;
84
Ethan Nicholase6592142020-09-08 10:22:09 -040085 case Statement::Kind::kReturn:
John Stiles44e96be2020-08-31 13:16:04 -040086 ++fNumReturns;
87 [[fallthrough]];
88
89 default:
John Stiles93442622020-09-11 12:11:27 -040090 return INHERITED::visitStatement(stmt);
John Stiles44e96be2020-08-31 13:16:04 -040091 }
92 }
93
94 int fNumReturns = 0;
95 using INHERITED = ProgramVisitor;
96 };
97
98 return CountReturnsAtEndOfControlFlow{funcDef}.fNumReturns;
99}
100
John Stiles74ebd7e2020-12-17 14:41:50 -0500101static int count_returns_in_continuable_constructs(const FunctionDefinition& funcDef) {
102 class CountReturnsInContinuableConstructs : public ProgramVisitor {
John Stiles44e96be2020-08-31 13:16:04 -0400103 public:
John Stiles74ebd7e2020-12-17 14:41:50 -0500104 CountReturnsInContinuableConstructs(const FunctionDefinition& funcDef) {
John Stiles44e96be2020-08-31 13:16:04 -0400105 this->visitProgramElement(funcDef);
106 }
107
John Stiles5b408a32021-03-17 09:53:32 -0400108 bool visitExpression(const Expression& expr) override {
109 // Do not recurse into expressions.
110 return false;
111 }
112
John Stiles44e96be2020-08-31 13:16:04 -0400113 bool visitStatement(const Statement& stmt) override {
Ethan Nicholase6592142020-09-08 10:22:09 -0400114 switch (stmt.kind()) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400115 case Statement::Kind::kDo:
116 case Statement::Kind::kFor: {
John Stiles74ebd7e2020-12-17 14:41:50 -0500117 ++fInsideContinuableConstruct;
John Stiles93442622020-09-11 12:11:27 -0400118 bool result = INHERITED::visitStatement(stmt);
John Stiles74ebd7e2020-12-17 14:41:50 -0500119 --fInsideContinuableConstruct;
John Stiles44e96be2020-08-31 13:16:04 -0400120 return result;
121 }
122
Ethan Nicholase6592142020-09-08 10:22:09 -0400123 case Statement::Kind::kReturn:
John Stiles74ebd7e2020-12-17 14:41:50 -0500124 fNumReturns += (fInsideContinuableConstruct > 0) ? 1 : 0;
John Stiles44e96be2020-08-31 13:16:04 -0400125 [[fallthrough]];
126
127 default:
John Stiles93442622020-09-11 12:11:27 -0400128 return INHERITED::visitStatement(stmt);
John Stiles44e96be2020-08-31 13:16:04 -0400129 }
130 }
131
132 int fNumReturns = 0;
John Stiles74ebd7e2020-12-17 14:41:50 -0500133 int fInsideContinuableConstruct = 0;
John Stiles44e96be2020-08-31 13:16:04 -0400134 using INHERITED = ProgramVisitor;
135 };
136
John Stiles74ebd7e2020-12-17 14:41:50 -0500137 return CountReturnsInContinuableConstructs{funcDef}.fNumReturns;
John Stiles44e96be2020-08-31 13:16:04 -0400138}
139
John Stiles991b09d2020-09-10 13:33:40 -0400140static bool contains_recursive_call(const FunctionDeclaration& funcDecl) {
141 class ContainsRecursiveCall : public ProgramVisitor {
142 public:
143 bool visit(const FunctionDeclaration& funcDecl) {
144 fFuncDecl = &funcDecl;
Ethan Nicholased84b732020-10-08 11:45:44 -0400145 return funcDecl.definition() ? this->visitProgramElement(*funcDecl.definition())
146 : false;
John Stiles991b09d2020-09-10 13:33:40 -0400147 }
148
149 bool visitExpression(const Expression& expr) override {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400150 if (expr.is<FunctionCall>() && expr.as<FunctionCall>().function().matches(*fFuncDecl)) {
John Stiles991b09d2020-09-10 13:33:40 -0400151 return true;
152 }
153 return INHERITED::visitExpression(expr);
154 }
155
156 bool visitStatement(const Statement& stmt) override {
Ethan Nicholasceb62142020-10-09 16:51:18 -0400157 if (stmt.is<InlineMarker>() &&
158 stmt.as<InlineMarker>().function().matches(*fFuncDecl)) {
John Stiles991b09d2020-09-10 13:33:40 -0400159 return true;
160 }
161 return INHERITED::visitStatement(stmt);
162 }
163
164 const FunctionDeclaration* fFuncDecl;
165 using INHERITED = ProgramVisitor;
166 };
167
168 return ContainsRecursiveCall{}.visit(funcDecl);
169}
170
John Stiles6d696082020-10-01 10:18:54 -0400171static std::unique_ptr<Statement>* find_parent_statement(
172 const std::vector<std::unique_ptr<Statement>*>& stmtStack) {
John Stiles915a38c2020-09-14 09:38:13 -0400173 SkASSERT(!stmtStack.empty());
174
175 // Walk the statement stack from back to front, ignoring the last element (which is the
176 // enclosing statement).
177 auto iter = stmtStack.rbegin();
178 ++iter;
179
180 // Anything counts as a parent statement other than a scopeless Block.
181 for (; iter != stmtStack.rend(); ++iter) {
John Stiles6d696082020-10-01 10:18:54 -0400182 std::unique_ptr<Statement>* stmt = *iter;
183 if (!(*stmt)->is<Block>() || (*stmt)->as<Block>().isScope()) {
John Stiles915a38c2020-09-14 09:38:13 -0400184 return stmt;
185 }
186 }
187
188 // There wasn't any parent statement to be found.
189 return nullptr;
190}
191
John Stilese41b4ee2020-09-28 12:28:16 -0400192std::unique_ptr<Expression> clone_with_ref_kind(const Expression& expr,
193 VariableReference::RefKind refKind) {
194 std::unique_ptr<Expression> clone = expr.clone();
John Stiles47c0a742021-02-09 09:30:35 -0500195 Analysis::UpdateRefKind(clone.get(), refKind);
John Stilese41b4ee2020-09-28 12:28:16 -0400196 return clone;
197}
198
John Stiles77702f12020-12-17 14:38:56 -0500199class CountReturnsWithLimit : public ProgramVisitor {
200public:
201 CountReturnsWithLimit(const FunctionDefinition& funcDef, int limit) : fLimit(limit) {
202 this->visitProgramElement(funcDef);
203 }
204
John Stiles5b408a32021-03-17 09:53:32 -0400205 bool visitExpression(const Expression& expr) override {
206 // Do not recurse into expressions.
207 return false;
208 }
209
John Stiles77702f12020-12-17 14:38:56 -0500210 bool visitStatement(const Statement& stmt) override {
211 switch (stmt.kind()) {
212 case Statement::Kind::kReturn: {
213 ++fNumReturns;
214 fDeepestReturn = std::max(fDeepestReturn, fScopedBlockDepth);
215 return (fNumReturns >= fLimit) || INHERITED::visitStatement(stmt);
216 }
John Stilesc5ff4862020-12-22 13:47:05 -0500217 case Statement::Kind::kVarDeclaration: {
John Stiles99b2d042021-03-15 11:42:47 -0400218 ++fNumNonReturnStatements;
John Stilesc5ff4862020-12-22 13:47:05 -0500219 if (fScopedBlockDepth > 1) {
220 fVariablesInBlocks = true;
221 }
222 return INHERITED::visitStatement(stmt);
223 }
John Stiles77702f12020-12-17 14:38:56 -0500224 case Statement::Kind::kBlock: {
John Stiles99b2d042021-03-15 11:42:47 -0400225 // Don't count Block as a statement.
John Stiles77702f12020-12-17 14:38:56 -0500226 int depthIncrement = stmt.as<Block>().isScope() ? 1 : 0;
227 fScopedBlockDepth += depthIncrement;
228 bool result = INHERITED::visitStatement(stmt);
229 fScopedBlockDepth -= depthIncrement;
John Stilesc5ff4862020-12-22 13:47:05 -0500230 if (fNumReturns == 0 && fScopedBlockDepth <= 1) {
231 // If closing this block puts us back at the top level, and we haven't
232 // encountered any return statements yet, any vardecls we may have encountered
233 // up until this point can be ignored. They are out of scope now, and they were
234 // never used in a return statement.
235 fVariablesInBlocks = false;
236 }
John Stiles77702f12020-12-17 14:38:56 -0500237 return result;
238 }
John Stiles99b2d042021-03-15 11:42:47 -0400239 case Statement::Kind::kNop:
240 case Statement::Kind::kInlineMarker:
241 // Don't count no-op statements.
242 return false;
John Stiles77702f12020-12-17 14:38:56 -0500243 default:
John Stiles99b2d042021-03-15 11:42:47 -0400244 ++fNumNonReturnStatements;
John Stiles77702f12020-12-17 14:38:56 -0500245 return INHERITED::visitStatement(stmt);
246 }
247 }
248
249 int fNumReturns = 0;
John Stiles99b2d042021-03-15 11:42:47 -0400250 int fNumNonReturnStatements = 0;
John Stiles77702f12020-12-17 14:38:56 -0500251 int fDeepestReturn = 0;
252 int fLimit = 0;
253 int fScopedBlockDepth = 0;
John Stilesc5ff4862020-12-22 13:47:05 -0500254 bool fVariablesInBlocks = false;
John Stiles77702f12020-12-17 14:38:56 -0500255 using INHERITED = ProgramVisitor;
256};
257
John Stiles44e96be2020-08-31 13:16:04 -0400258} // namespace
259
John Stiles77702f12020-12-17 14:38:56 -0500260Inliner::ReturnComplexity Inliner::GetReturnComplexity(const FunctionDefinition& funcDef) {
261 int returnsAtEndOfControlFlow = count_returns_at_end_of_control_flow(funcDef);
262 CountReturnsWithLimit counter{funcDef, returnsAtEndOfControlFlow + 1};
John Stiles77702f12020-12-17 14:38:56 -0500263 if (counter.fNumReturns > returnsAtEndOfControlFlow) {
264 return ReturnComplexity::kEarlyReturns;
265 }
John Stilesc5ff4862020-12-22 13:47:05 -0500266 if (counter.fNumReturns > 1) {
John Stiles77702f12020-12-17 14:38:56 -0500267 return ReturnComplexity::kScopedReturns;
268 }
John Stilesc5ff4862020-12-22 13:47:05 -0500269 if (counter.fVariablesInBlocks && counter.fDeepestReturn > 1) {
270 return ReturnComplexity::kScopedReturns;
271 }
John Stiles99b2d042021-03-15 11:42:47 -0400272 if (counter.fNumNonReturnStatements > 0) {
273 return ReturnComplexity::kSingleSafeReturn;
274 }
275 return ReturnComplexity::kOnlySingleReturn;
John Stiles77702f12020-12-17 14:38:56 -0500276}
277
John Stilesb61ee902020-09-21 12:26:59 -0400278void Inliner::ensureScopedBlocks(Statement* inlinedBody, Statement* parentStmt) {
279 // No changes necessary if this statement isn't actually a block.
280 if (!inlinedBody || !inlinedBody->is<Block>()) {
281 return;
282 }
283
284 // No changes necessary if the parent statement doesn't require a scope.
285 if (!parentStmt || !(parentStmt->is<IfStatement>() || parentStmt->is<ForStatement>() ||
Brian Osmand6f23382020-12-15 17:08:59 -0500286 parentStmt->is<DoStatement>())) {
John Stilesb61ee902020-09-21 12:26:59 -0400287 return;
288 }
289
290 Block& block = inlinedBody->as<Block>();
291
292 // The inliner will create inlined function bodies as a Block containing multiple statements,
293 // but no scope. Normally, this is fine, but if this block is used as the statement for a
294 // do/for/if/while, this isn't actually possible to represent textually; a scope must be added
295 // for the generated code to match the intent. In the case of Blocks nested inside other Blocks,
296 // we add the scope to the outermost block if needed. Zero-statement blocks have similar
297 // issues--if we don't represent the Block textually somehow, we run the risk of accidentally
298 // absorbing the following statement into our loop--so we also add a scope to these.
299 for (Block* nestedBlock = &block;; ) {
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400300 if (nestedBlock->isScope()) {
John Stilesb61ee902020-09-21 12:26:59 -0400301 // We found an explicit scope; all is well.
302 return;
303 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400304 if (nestedBlock->children().size() != 1) {
John Stilesb61ee902020-09-21 12:26:59 -0400305 // We found a block with multiple (or zero) statements, but no scope? Let's add a scope
306 // to the outermost block.
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400307 block.setIsScope(true);
John Stilesb61ee902020-09-21 12:26:59 -0400308 return;
309 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400310 if (!nestedBlock->children()[0]->is<Block>()) {
John Stilesb61ee902020-09-21 12:26:59 -0400311 // This block has exactly one thing inside, and it's not another block. No need to scope
312 // it.
313 return;
314 }
315 // We have to go deeper.
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400316 nestedBlock = &nestedBlock->children()[0]->as<Block>();
John Stilesb61ee902020-09-21 12:26:59 -0400317 }
318}
319
John Stilesd1204642021-02-17 16:30:02 -0500320void Inliner::reset(ModifiersPool* modifiers) {
Ethan Nicholas041fd0a2020-10-07 16:42:04 -0400321 fModifiers = modifiers;
Ethan Nicholas6f4eee22021-01-11 12:37:42 -0500322 fMangler.reset();
John Stiles031a7672020-11-13 16:13:18 -0500323 fInlinedStatementCounter = 0;
John Stiles44e96be2020-08-31 13:16:04 -0400324}
325
326std::unique_ptr<Expression> Inliner::inlineExpression(int offset,
327 VariableRewriteMap* varMap,
John Stilesd7cc0932020-11-30 12:24:27 -0500328 SymbolTable* symbolTableForExpression,
John Stiles44e96be2020-08-31 13:16:04 -0400329 const Expression& expression) {
330 auto expr = [&](const std::unique_ptr<Expression>& e) -> std::unique_ptr<Expression> {
331 if (e) {
John Stilesd7cc0932020-11-30 12:24:27 -0500332 return this->inlineExpression(offset, varMap, symbolTableForExpression, *e);
John Stiles44e96be2020-08-31 13:16:04 -0400333 }
334 return nullptr;
335 };
John Stiles8e3b6be2020-10-13 11:14:08 -0400336 auto argList = [&](const ExpressionArray& originalArgs) -> ExpressionArray {
337 ExpressionArray args;
John Stilesf4bda742020-10-14 16:57:41 -0400338 args.reserve_back(originalArgs.size());
John Stiles44e96be2020-08-31 13:16:04 -0400339 for (const std::unique_ptr<Expression>& arg : originalArgs) {
340 args.push_back(expr(arg));
341 }
342 return args;
343 };
344
Ethan Nicholase6592142020-09-08 10:22:09 -0400345 switch (expression.kind()) {
346 case Expression::Kind::kBinary: {
John Stiles6a1a98c2021-01-14 18:35:34 -0500347 const BinaryExpression& binaryExpr = expression.as<BinaryExpression>();
John Stilese2aec432021-03-01 09:27:48 -0500348 return BinaryExpression::Make(*fContext,
349 expr(binaryExpr.left()),
350 binaryExpr.getOperator(),
351 expr(binaryExpr.right()));
John Stiles44e96be2020-08-31 13:16:04 -0400352 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400353 case Expression::Kind::kBoolLiteral:
354 case Expression::Kind::kIntLiteral:
355 case Expression::Kind::kFloatLiteral:
John Stiles44e96be2020-08-31 13:16:04 -0400356 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400357 case Expression::Kind::kConstructor: {
John Stiles44e96be2020-08-31 13:16:04 -0400358 const Constructor& constructor = expression.as<Constructor>();
John Stiles23521a82021-03-02 17:02:51 -0500359 auto inlinedCtor = Constructor::Convert(
360 *fContext, offset, *constructor.type().clone(symbolTableForExpression),
361 argList(constructor.arguments()));
362 SkASSERT(inlinedCtor);
363 return inlinedCtor;
John Stiles44e96be2020-08-31 13:16:04 -0400364 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400365 case Expression::Kind::kExternalFunctionCall: {
John Stiles44e96be2020-08-31 13:16:04 -0400366 const ExternalFunctionCall& externalCall = expression.as<ExternalFunctionCall>();
Ethan Nicholas444ccc62020-10-09 10:16:22 -0400367 return std::make_unique<ExternalFunctionCall>(offset, &externalCall.function(),
Ethan Nicholas6e86ec92020-09-30 14:29:56 -0400368 argList(externalCall.arguments()));
John Stiles44e96be2020-08-31 13:16:04 -0400369 }
Brian Osmanbe0b3b72021-01-06 14:27:35 -0500370 case Expression::Kind::kExternalFunctionReference:
John Stiles44e96be2020-08-31 13:16:04 -0400371 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400372 case Expression::Kind::kFieldAccess: {
John Stiles44e96be2020-08-31 13:16:04 -0400373 const FieldAccess& f = expression.as<FieldAccess>();
John Stiles06d600f2021-03-08 09:18:21 -0500374 return FieldAccess::Make(*fContext, expr(f.base()), f.fieldIndex(), f.ownerKind());
John Stiles44e96be2020-08-31 13:16:04 -0400375 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400376 case Expression::Kind::kFunctionCall: {
John Stiles44e96be2020-08-31 13:16:04 -0400377 const FunctionCall& funcCall = expression.as<FunctionCall>();
John Stilesddcc8432021-01-15 15:32:32 -0500378 return std::make_unique<FunctionCall>(offset,
379 funcCall.type().clone(symbolTableForExpression),
380 &funcCall.function(),
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400381 argList(funcCall.arguments()));
John Stiles44e96be2020-08-31 13:16:04 -0400382 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400383 case Expression::Kind::kFunctionReference:
Brian Osman2b3b35f2020-09-08 09:17:36 -0400384 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400385 case Expression::Kind::kIndex: {
John Stiles44e96be2020-08-31 13:16:04 -0400386 const IndexExpression& idx = expression.as<IndexExpression>();
John Stiles51d33982021-03-08 09:18:07 -0500387 return IndexExpression::Make(*fContext, expr(idx.base()), expr(idx.index()));
John Stiles44e96be2020-08-31 13:16:04 -0400388 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400389 case Expression::Kind::kPrefix: {
John Stiles44e96be2020-08-31 13:16:04 -0400390 const PrefixExpression& p = expression.as<PrefixExpression>();
John Stilesb0eb20f2021-02-26 15:29:33 -0500391 return PrefixExpression::Make(*fContext, p.getOperator(), expr(p.operand()));
John Stiles44e96be2020-08-31 13:16:04 -0400392 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400393 case Expression::Kind::kPostfix: {
John Stiles44e96be2020-08-31 13:16:04 -0400394 const PostfixExpression& p = expression.as<PostfixExpression>();
John Stiles52d3b012021-02-26 15:56:48 -0500395 return PostfixExpression::Make(*fContext, expr(p.operand()), p.getOperator());
John Stiles44e96be2020-08-31 13:16:04 -0400396 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400397 case Expression::Kind::kSetting:
John Stiles44e96be2020-08-31 13:16:04 -0400398 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400399 case Expression::Kind::kSwizzle: {
John Stiles44e96be2020-08-31 13:16:04 -0400400 const Swizzle& s = expression.as<Swizzle>();
John Stiles6e88e042021-02-19 14:09:38 -0500401 return Swizzle::Make(*fContext, expr(s.base()), s.components());
John Stiles44e96be2020-08-31 13:16:04 -0400402 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400403 case Expression::Kind::kTernary: {
John Stiles44e96be2020-08-31 13:16:04 -0400404 const TernaryExpression& t = expression.as<TernaryExpression>();
John Stiles90518f72021-02-26 20:44:54 -0500405 return TernaryExpression::Make(*fContext, expr(t.test()),
406 expr(t.ifTrue()), expr(t.ifFalse()));
John Stiles44e96be2020-08-31 13:16:04 -0400407 }
Brian Osman83ba9302020-09-11 13:33:46 -0400408 case Expression::Kind::kTypeReference:
409 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400410 case Expression::Kind::kVariableReference: {
John Stiles44e96be2020-08-31 13:16:04 -0400411 const VariableReference& v = expression.as<VariableReference>();
Ethan Nicholas78686922020-10-08 06:46:27 -0400412 auto varMapIter = varMap->find(v.variable());
John Stilese41b4ee2020-09-28 12:28:16 -0400413 if (varMapIter != varMap->end()) {
Ethan Nicholas78686922020-10-08 06:46:27 -0400414 return clone_with_ref_kind(*varMapIter->second, v.refKind());
John Stiles44e96be2020-08-31 13:16:04 -0400415 }
416 return v.clone();
417 }
418 default:
419 SkASSERT(false);
420 return nullptr;
421 }
422}
423
424std::unique_ptr<Statement> Inliner::inlineStatement(int offset,
425 VariableRewriteMap* varMap,
426 SymbolTable* symbolTableForStatement,
John Stiles77702f12020-12-17 14:38:56 -0500427 std::unique_ptr<Expression>* resultExpr,
428 ReturnComplexity returnComplexity,
Brian Osman3887a012020-09-30 13:22:27 -0400429 const Statement& statement,
430 bool isBuiltinCode) {
John Stiles44e96be2020-08-31 13:16:04 -0400431 auto stmt = [&](const std::unique_ptr<Statement>& s) -> std::unique_ptr<Statement> {
432 if (s) {
John Stilesa5f3c312020-09-22 12:05:16 -0400433 return this->inlineStatement(offset, varMap, symbolTableForStatement, resultExpr,
John Stiles77702f12020-12-17 14:38:56 -0500434 returnComplexity, *s, isBuiltinCode);
John Stiles44e96be2020-08-31 13:16:04 -0400435 }
436 return nullptr;
437 };
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400438 auto blockStmts = [&](const Block& block) {
John Stiles8f2a0cf2020-10-13 12:48:21 -0400439 StatementArray result;
John Stilesf4bda742020-10-14 16:57:41 -0400440 result.reserve_back(block.children().size());
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400441 for (const std::unique_ptr<Statement>& child : block.children()) {
442 result.push_back(stmt(child));
443 }
444 return result;
445 };
John Stiles44e96be2020-08-31 13:16:04 -0400446 auto expr = [&](const std::unique_ptr<Expression>& e) -> std::unique_ptr<Expression> {
447 if (e) {
John Stilesd7cc0932020-11-30 12:24:27 -0500448 return this->inlineExpression(offset, varMap, symbolTableForStatement, *e);
John Stiles44e96be2020-08-31 13:16:04 -0400449 }
450 return nullptr;
451 };
John Stiles031a7672020-11-13 16:13:18 -0500452
453 ++fInlinedStatementCounter;
454
Ethan Nicholase6592142020-09-08 10:22:09 -0400455 switch (statement.kind()) {
456 case Statement::Kind::kBlock: {
John Stiles44e96be2020-08-31 13:16:04 -0400457 const Block& b = statement.as<Block>();
John Stilesbf16b6c2021-03-12 19:24:31 -0500458 return Block::Make(offset, blockStmts(b),
459 SymbolTable::WrapIfBuiltin(b.symbolTable()),
460 b.isScope());
John Stiles44e96be2020-08-31 13:16:04 -0400461 }
462
Ethan Nicholase6592142020-09-08 10:22:09 -0400463 case Statement::Kind::kBreak:
464 case Statement::Kind::kContinue:
465 case Statement::Kind::kDiscard:
John Stiles44e96be2020-08-31 13:16:04 -0400466 return statement.clone();
467
Ethan Nicholase6592142020-09-08 10:22:09 -0400468 case Statement::Kind::kDo: {
John Stiles44e96be2020-08-31 13:16:04 -0400469 const DoStatement& d = statement.as<DoStatement>();
John Stilesea5822e2021-02-26 11:18:20 -0500470 return DoStatement::Make(*fContext, stmt(d.statement()), expr(d.test()));
John Stiles44e96be2020-08-31 13:16:04 -0400471 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400472 case Statement::Kind::kExpression: {
John Stiles44e96be2020-08-31 13:16:04 -0400473 const ExpressionStatement& e = statement.as<ExpressionStatement>();
John Stiles3e5871c2021-02-25 20:52:03 -0500474 return ExpressionStatement::Make(*fContext, expr(e.expression()));
John Stiles44e96be2020-08-31 13:16:04 -0400475 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400476 case Statement::Kind::kFor: {
John Stiles44e96be2020-08-31 13:16:04 -0400477 const ForStatement& f = statement.as<ForStatement>();
478 // need to ensure initializer is evaluated first so that we've already remapped its
479 // declarations by the time we evaluate test & next
Ethan Nicholas0d31ed52020-10-05 14:47:09 -0400480 std::unique_ptr<Statement> initializer = stmt(f.initializer());
John Stilesb321a072021-02-25 16:24:19 -0500481 return ForStatement::Make(*fContext, offset, std::move(initializer), expr(f.test()),
482 expr(f.next()), stmt(f.statement()),
483 SymbolTable::WrapIfBuiltin(f.symbols()));
John Stiles44e96be2020-08-31 13:16:04 -0400484 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400485 case Statement::Kind::kIf: {
John Stiles44e96be2020-08-31 13:16:04 -0400486 const IfStatement& i = statement.as<IfStatement>();
John Stilescf3059e2021-02-25 14:27:02 -0500487 return IfStatement::Make(*fContext, offset, i.isStatic(), expr(i.test()),
488 stmt(i.ifTrue()), stmt(i.ifFalse()));
John Stiles44e96be2020-08-31 13:16:04 -0400489 }
John Stiles98c1f822020-09-09 14:18:53 -0400490 case Statement::Kind::kInlineMarker:
Ethan Nicholase6592142020-09-08 10:22:09 -0400491 case Statement::Kind::kNop:
John Stiles44e96be2020-08-31 13:16:04 -0400492 return statement.clone();
John Stilesea5822e2021-02-26 11:18:20 -0500493
Ethan Nicholase6592142020-09-08 10:22:09 -0400494 case Statement::Kind::kReturn: {
John Stiles44e96be2020-08-31 13:16:04 -0400495 const ReturnStatement& r = statement.as<ReturnStatement>();
John Stiles77702f12020-12-17 14:38:56 -0500496 if (!r.expression()) {
497 if (returnComplexity >= ReturnComplexity::kEarlyReturns) {
498 // This function doesn't return a value, but has early returns, so we've wrapped
499 // it in a for loop. Use a continue to jump to the end of the loop and "leave"
500 // the function.
John Stilesa0c04d62021-03-11 23:07:24 -0500501 return ContinueStatement::Make(offset);
John Stiles44e96be2020-08-31 13:16:04 -0400502 } else {
John Stiles77702f12020-12-17 14:38:56 -0500503 // This function doesn't exit early or return a value. A return statement at the
504 // end is a no-op and can be treated as such.
John Stilesa0c04d62021-03-11 23:07:24 -0500505 return Nop::Make();
John Stiles44e96be2020-08-31 13:16:04 -0400506 }
507 }
John Stiles77702f12020-12-17 14:38:56 -0500508
John Stilesc5ff4862020-12-22 13:47:05 -0500509 // If a function only contains a single return, and it doesn't reference variables from
510 // inside an Block's scope, we don't need to store the result in a variable at all. Just
511 // replace the function-call expression with the function's return expression.
John Stiles77702f12020-12-17 14:38:56 -0500512 SkASSERT(resultExpr);
John Stilesc5ff4862020-12-22 13:47:05 -0500513 if (returnComplexity <= ReturnComplexity::kSingleSafeReturn) {
John Stiles77702f12020-12-17 14:38:56 -0500514 *resultExpr = expr(r.expression());
John Stilesa0c04d62021-03-11 23:07:24 -0500515 return Nop::Make();
John Stiles77702f12020-12-17 14:38:56 -0500516 }
517
518 // For more complex functions, assign their result into a variable.
John Stiles511c5002021-02-25 11:17:02 -0500519 SkASSERT(*resultExpr);
John Stiles3e5871c2021-02-25 20:52:03 -0500520 auto assignment = ExpressionStatement::Make(
521 *fContext,
John Stilese2aec432021-03-01 09:27:48 -0500522 BinaryExpression::Make(
523 *fContext,
524 clone_with_ref_kind(**resultExpr, VariableRefKind::kWrite),
John Stiles77702f12020-12-17 14:38:56 -0500525 Token::Kind::TK_EQ,
John Stilese2aec432021-03-01 09:27:48 -0500526 expr(r.expression())));
John Stiles77702f12020-12-17 14:38:56 -0500527
528 // Early returns are wrapped in a for loop; we need to synthesize a continue statement
529 // to "leave" the function.
530 if (returnComplexity >= ReturnComplexity::kEarlyReturns) {
531 StatementArray block;
532 block.reserve_back(2);
533 block.push_back(std::move(assignment));
John Stilesa0c04d62021-03-11 23:07:24 -0500534 block.push_back(ContinueStatement::Make(offset));
John Stilesbf16b6c2021-03-12 19:24:31 -0500535 return Block::Make(offset, std::move(block), /*symbols=*/nullptr, /*isScope=*/true);
John Stiles77702f12020-12-17 14:38:56 -0500536 }
537 // Functions without early returns aren't wrapped in a for loop and don't need to worry
538 // about breaking out of the control flow.
John Stiles3e5871c2021-02-25 20:52:03 -0500539 return assignment;
John Stiles44e96be2020-08-31 13:16:04 -0400540 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400541 case Statement::Kind::kSwitch: {
John Stiles44e96be2020-08-31 13:16:04 -0400542 const SwitchStatement& ss = statement.as<SwitchStatement>();
John Stilesb23a64b2021-03-11 08:27:59 -0500543 StatementArray cases;
544 cases.reserve_back(ss.cases().size());
545 for (const std::unique_ptr<Statement>& statement : ss.cases()) {
546 const SwitchCase& sc = statement->as<SwitchCase>();
547 cases.push_back(std::make_unique<SwitchCase>(offset, expr(sc.value()),
548 stmt(sc.statement())));
John Stiles44e96be2020-08-31 13:16:04 -0400549 }
John Stilese1d1b082021-02-23 13:44:36 -0500550 return SwitchStatement::Make(*fContext, offset, ss.isStatic(), expr(ss.value()),
551 std::move(cases), SymbolTable::WrapIfBuiltin(ss.symbols()));
John Stiles44e96be2020-08-31 13:16:04 -0400552 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400553 case Statement::Kind::kVarDeclaration: {
John Stiles44e96be2020-08-31 13:16:04 -0400554 const VarDeclaration& decl = statement.as<VarDeclaration>();
John Stiles35fee4c2020-12-16 18:25:14 +0000555 std::unique_ptr<Expression> initialValue = expr(decl.value());
John Stilesddcc8432021-01-15 15:32:32 -0500556 const Variable& variable = decl.var();
557
John Stiles35fee4c2020-12-16 18:25:14 +0000558 // We assign unique names to inlined variables--scopes hide most of the problems in this
559 // regard, but see `InlinerAvoidsVariableNameOverlap` for a counterexample where unique
560 // names are important.
John Stilesddcc8432021-01-15 15:32:32 -0500561 auto name = std::make_unique<String>(fMangler.uniqueName(variable.name(),
Ethan Nicholas6f4eee22021-01-11 12:37:42 -0500562 symbolTableForStatement));
John Stiles35fee4c2020-12-16 18:25:14 +0000563 const String* namePtr = symbolTableForStatement->takeOwnershipOfString(std::move(name));
Ethan Nicholas5b9b0db2021-01-21 13:12:01 -0500564 auto clonedVar = std::make_unique<Variable>(
565 offset,
566 &variable.modifiers(),
567 namePtr->c_str(),
568 variable.type().clone(symbolTableForStatement),
569 isBuiltinCode,
570 variable.storage());
571 (*varMap)[&variable] = std::make_unique<VariableReference>(offset, clonedVar.get());
572 auto result = std::make_unique<VarDeclaration>(clonedVar.get(),
John Stilesddcc8432021-01-15 15:32:32 -0500573 decl.baseType().clone(symbolTableForStatement),
574 decl.arraySize(),
John Stiles35fee4c2020-12-16 18:25:14 +0000575 std::move(initialValue));
Ethan Nicholas5b9b0db2021-01-21 13:12:01 -0500576 clonedVar->setDeclaration(result.get());
577 symbolTableForStatement->takeOwnershipOfSymbol(std::move(clonedVar));
578 return std::move(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
600 // Provide our new variable with a unique name, and add it to our symbol table.
601 const String* namePtr = symbolTable->takeOwnershipOfString(
Ethan Nicholas6f4eee22021-01-11 12:37:42 -0500602 std::make_unique<String>(fMangler.uniqueName(baseName, symbolTable)));
John Stiles7b920442020-12-17 10:43:41 -0500603 StringFragment nameFrag{namePtr->c_str(), namePtr->length()};
604
605 // Create our new variable and add it to the symbol table.
606 InlineVariable result;
Ethan Nicholas5b9b0db2021-01-21 13:12:01 -0500607 auto var = std::make_unique<Variable>(/*offset=*/-1,
608 fModifiers->addToPool(Modifiers()),
609 nameFrag,
610 type,
611 isBuiltinCode,
612 Variable::Storage::kLocal);
John Stiles7b920442020-12-17 10:43:41 -0500613
614 // Prepare the variable declaration (taking extra care with `out` params to not clobber any
615 // initial value).
616 if (*initialValue && (modifiers.fFlags & Modifiers::kOut_Flag)) {
Ethan Nicholas5b9b0db2021-01-21 13:12:01 -0500617 result.fVarDecl = std::make_unique<VarDeclaration>(var.get(), type, /*arraySize=*/0,
John Stiles7b920442020-12-17 10:43:41 -0500618 (*initialValue)->clone());
619 } else {
Ethan Nicholas5b9b0db2021-01-21 13:12:01 -0500620 result.fVarDecl = std::make_unique<VarDeclaration>(var.get(), type, /*arraySize=*/0,
John Stiles7b920442020-12-17 10:43:41 -0500621 std::move(*initialValue));
622 }
Ethan Nicholas5b9b0db2021-01-21 13:12:01 -0500623 var->setDeclaration(&result.fVarDecl->as<VarDeclaration>());
624 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,
Brian Osman3887a012020-09-30 13:22:27 -0400630 const FunctionDeclaration* caller) {
John Stiles44e96be2020-08-31 13:16:04 -0400631 // Inlining is more complicated here than in a typical compiler, because we have to have a
632 // high-level IR and can't just drop statements into the middle of an expression or even use
633 // gotos.
634 //
635 // Since we can't insert statements into an expression, we run the inline function as extra
636 // statements before the statement we're currently processing, relying on a lack of execution
637 // order guarantees. Since we can't use gotos (which are normally used to replace return
638 // statements), we wrap the whole function in a loop and use break statements to jump to the
639 // end.
John Stiles44e96be2020-08-31 13:16:04 -0400640 SkASSERT(fContext);
641 SkASSERT(call);
Ethan Nicholased84b732020-10-08 11:45:44 -0400642 SkASSERT(this->isSafeToInline(call->function().definition()));
John Stiles44e96be2020-08-31 13:16:04 -0400643
John Stiles8e3b6be2020-10-13 11:14:08 -0400644 ExpressionArray& arguments = call->arguments();
John Stiles6eadf132020-09-08 10:16:10 -0400645 const int offset = call->fOffset;
Ethan Nicholased84b732020-10-08 11:45:44 -0400646 const FunctionDefinition& function = *call->function().definition();
John Stiles77702f12020-12-17 14:38:56 -0500647 const ReturnComplexity returnComplexity = GetReturnComplexity(function);
648 bool hasEarlyReturn = (returnComplexity >= ReturnComplexity::kEarlyReturns);
John Stiles6eadf132020-09-08 10:16:10 -0400649
John Stiles44e96be2020-08-31 13:16:04 -0400650 InlinedCall inlinedCall;
John Stilesbf16b6c2021-03-12 19:24:31 -0500651 StatementArray inlinedBlockStmts;
652 inlinedBlockStmts.reserve_back(1 + // Inline marker
653 1 + // Result variable
654 arguments.size() + // Function arguments (passing in)
655 arguments.size() + // Function arguments (copy out-params back)
656 1); // Block for inlined code
John Stiles98c1f822020-09-09 14:18:53 -0400657
John Stilesbf16b6c2021-03-12 19:24:31 -0500658 inlinedBlockStmts.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;
John Stiles7b920442020-12-17 10:43:41 -0500667 InlineVariable var = this->makeInlineVariable(function.declaration().name(),
668 &function.declaration().returnType(),
669 symbolTable.get(), Modifiers{},
670 caller->isBuiltin(), &noInitialValue);
John Stilesbf16b6c2021-03-12 19:24:31 -0500671 inlinedBlockStmts.push_back(std::move(var.fVarDecl));
John Stiles7b920442020-12-17 10:43:41 -0500672 resultExpr = std::make_unique<VariableReference>(/*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 Stilese41b4ee2020-09-28 12:28:16 -0400678 std::vector<int> argsToCopyBack;
John Stiles44e96be2020-08-31 13:16:04 -0400679 for (int i = 0; i < (int) arguments.size(); ++i) {
Ethan Nicholas0a5d0962020-10-14 13:33:18 -0400680 const Variable* param = function.declaration().parameters()[i];
Ethan Nicholas041fd0a2020-10-07 16:42:04 -0400681 bool isOutParam = param->modifiers().fFlags & Modifiers::kOut_Flag;
John Stiles44e96be2020-08-31 13:16:04 -0400682
John Stiles44733aa2020-09-29 17:42:23 -0400683 // If this argument can be inlined trivially (e.g. a swizzle, or a constant array index)...
John Stilesc30fbca2020-11-19 16:25:49 -0500684 if (Analysis::IsTrivialExpression(*arguments[i])) {
John Stilese41b4ee2020-09-28 12:28:16 -0400685 // ... and it's an `out` param, or it isn't written to within the inline function...
Ethan Nicholas0a5d0962020-10-14 13:33:18 -0400686 if (isOutParam || !Analysis::StatementWritesToVariable(*function.body(), *param)) {
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 }
John Stilese41b4ee2020-09-28 12:28:16 -0400692 if (isOutParam) {
693 argsToCopyBack.push_back(i);
694 }
John Stiles7b920442020-12-17 10:43:41 -0500695 InlineVariable var = this->makeInlineVariable(param->name(), &arguments[i]->type(),
696 symbolTable.get(), param->modifiers(),
697 caller->isBuiltin(), &arguments[i]);
John Stilesbf16b6c2021-03-12 19:24:31 -0500698 inlinedBlockStmts.push_back(std::move(var.fVarDecl));
John Stiles7b920442020-12-17 10:43:41 -0500699 varMap[param] = std::make_unique<VariableReference>(/*offset=*/-1, var.fVarSymbol);
John Stiles44e96be2020-08-31 13:16:04 -0400700 }
701
Ethan Nicholas0a5d0962020-10-14 13:33:18 -0400702 const Block& body = function.body()->as<Block>();
John Stiles7b920442020-12-17 10:43:41 -0500703 StatementArray* inlineStatements;
704
John Stiles44e96be2020-08-31 13:16:04 -0400705 if (hasEarlyReturn) {
706 // Since we output to backends that don't have a goto statement (which would normally be
John Stiles7b920442020-12-17 10:43:41 -0500707 // used to perform an early return), we fake it by wrapping the function in a single-
708 // iteration for loop, and use a continue statement to jump to the end of the loop
709 // prematurely.
710
711 // int _1_loop = 0;
712 symbolTable = std::make_shared<SymbolTable>(std::move(symbolTable), caller->isBuiltin());
John Stiles54e7c052021-01-11 14:22:36 -0500713 const Type* intType = fContext->fTypes.fInt.get();
John Stiles9ce80f72021-03-11 22:35:19 -0500714 std::unique_ptr<Expression> initialValue = IntLiteral::Make(/*offset=*/-1,
715 /*value=*/0,
716 intType);
John Stiles7b920442020-12-17 10:43:41 -0500717 InlineVariable loopVar = this->makeInlineVariable("loop", intType, symbolTable.get(),
718 Modifiers{}, caller->isBuiltin(),
719 &initialValue);
720
721 // _1_loop < 1;
John Stilese2aec432021-03-01 09:27:48 -0500722 std::unique_ptr<Expression> test = BinaryExpression::Make(
723 *fContext,
John Stiles7b920442020-12-17 10:43:41 -0500724 std::make_unique<VariableReference>(/*offset=*/-1, loopVar.fVarSymbol),
725 Token::Kind::TK_LT,
John Stiles9ce80f72021-03-11 22:35:19 -0500726 IntLiteral::Make(/*offset=*/-1, /*value=*/1, intType));
John Stiles7b920442020-12-17 10:43:41 -0500727
728 // _1_loop++
John Stiles52d3b012021-02-26 15:56:48 -0500729 std::unique_ptr<Expression> increment = PostfixExpression::Make(
730 *fContext,
John Stiles7b920442020-12-17 10:43:41 -0500731 std::make_unique<VariableReference>(/*offset=*/-1, loopVar.fVarSymbol,
732 VariableReference::RefKind::kReadWrite),
733 Token::Kind::TK_PLUSPLUS);
734
735 // {...}
John Stilesbf16b6c2021-03-12 19:24:31 -0500736 auto innerBlock = Block::Make(offset, StatementArray{},
737 /*symbols=*/nullptr, /*isScope=*/true);
John Stiles7b920442020-12-17 10:43:41 -0500738 inlineStatements = &innerBlock->children();
739
740 // for (int _1_loop = 0; _1_loop < 1; _1_loop++) {...}
John Stilesbf16b6c2021-03-12 19:24:31 -0500741 inlinedBlockStmts.push_back(ForStatement::Make(*fContext, /*offset=*/-1,
742 std::move(loopVar.fVarDecl),
743 std::move(test),
744 std::move(increment),
745 std::move(innerBlock),
746 symbolTable));
John Stiles44e96be2020-08-31 13:16:04 -0400747 } else {
John Stilesfa9a0832020-12-17 10:43:58 -0500748 // No early returns, so we can just dump the code into our existing scopeless block.
John Stilesbf16b6c2021-03-12 19:24:31 -0500749 inlineStatements = &inlinedBlockStmts;
John Stiles7b920442020-12-17 10:43:41 -0500750 }
751
752 inlineStatements->reserve_back(body.children().size() + argsToCopyBack.size());
753 for (const std::unique_ptr<Statement>& stmt : body.children()) {
754 inlineStatements->push_back(this->inlineStatement(offset, &varMap, symbolTable.get(),
John Stiles77702f12020-12-17 14:38:56 -0500755 &resultExpr, returnComplexity, *stmt,
John Stiles7b920442020-12-17 10:43:41 -0500756 caller->isBuiltin()));
John Stiles44e96be2020-08-31 13:16:04 -0400757 }
758
John Stilese41b4ee2020-09-28 12:28:16 -0400759 // Copy back the values of `out` parameters into their real destinations.
760 for (int i : argsToCopyBack) {
Ethan Nicholas0a5d0962020-10-14 13:33:18 -0400761 const Variable* p = function.declaration().parameters()[i];
John Stilese41b4ee2020-09-28 12:28:16 -0400762 SkASSERT(varMap.find(p) != varMap.end());
John Stiles3e5871c2021-02-25 20:52:03 -0500763 inlineStatements->push_back(ExpressionStatement::Make(
764 *fContext,
John Stilese2aec432021-03-01 09:27:48 -0500765 BinaryExpression::Make(*fContext,
766 clone_with_ref_kind(*arguments[i], VariableRefKind::kWrite),
767 Token::Kind::TK_EQ,
768 std::move(varMap[p]))));
John Stiles44e96be2020-08-31 13:16:04 -0400769 }
770
John Stilesbf16b6c2021-03-12 19:24:31 -0500771 // Wrap all of the generated statements in a block. We need a real Block here, so we can't use
772 // MakeUnscoped. This is because we need to add another child statement to the Block later.
773 inlinedCall.fInlinedBody = Block::Make(offset, std::move(inlinedBlockStmts),
774 /*symbols=*/nullptr, /*isScope=*/false);
775
John Stiles0c2d14a2021-03-01 10:08:08 -0500776 if (resultExpr) {
777 // Return our result expression as-is.
John Stilese41b4ee2020-09-28 12:28:16 -0400778 inlinedCall.fReplacementExpr = std::move(resultExpr);
John Stiles2558c462021-03-16 17:49:20 -0400779 } else if (function.declaration().returnType().isVoid()) {
John Stiles44e96be2020-08-31 13:16:04 -0400780 // It's a void function, so it doesn't actually result in anything, but we have to return
781 // something non-null as a standin.
John Stiles9ce80f72021-03-11 22:35:19 -0500782 inlinedCall.fReplacementExpr = BoolLiteral::Make(*fContext, offset, /*value=*/false);
John Stiles0c2d14a2021-03-01 10:08:08 -0500783 } else {
784 // It's a non-void function, but it never created a result expression--that is, it never
John Stiles2dda50d2021-03-03 10:46:44 -0500785 // returned anything on any path! This should have been detected in the function finalizer.
786 // Still, discard our output and generate an error.
787 SkDEBUGFAIL("inliner found non-void function that fails to return a value on any path");
788 fContext->fErrors.error(function.fOffset, "inliner found non-void function '" +
John Stiles0c2d14a2021-03-01 10:08:08 -0500789 function.declaration().name() +
John Stiles2dda50d2021-03-03 10:46:44 -0500790 "' that fails to return a value on any path");
John Stiles0c2d14a2021-03-01 10:08:08 -0500791 inlinedCall = {};
John Stiles44e96be2020-08-31 13:16:04 -0400792 }
793
John Stiles44e96be2020-08-31 13:16:04 -0400794 return inlinedCall;
795}
796
John Stiles2d7973a2020-10-02 15:01:03 -0400797bool Inliner::isSafeToInline(const FunctionDefinition* functionDef) {
John Stiles1c03d332020-10-13 10:30:23 -0400798 // A threshold of zero indicates that the inliner is completely disabled, so we can just return.
John Stilesd1204642021-02-17 16:30:02 -0500799 if (this->settings().fInlineThreshold <= 0) {
John Stiles1c03d332020-10-13 10:30:23 -0400800 return false;
801 }
802
John Stiles031a7672020-11-13 16:13:18 -0500803 // Enforce a limit on inlining to avoid pathological cases. (inliner/ExponentialGrowth.sksl)
804 if (fInlinedStatementCounter >= kInlinedStatementLimit) {
805 return false;
806 }
807
John Stiles2d7973a2020-10-02 15:01:03 -0400808 if (functionDef == nullptr) {
John Stiles44e96be2020-08-31 13:16:04 -0400809 // Can't inline something if we don't actually have its definition.
810 return false;
811 }
John Stiles2d7973a2020-10-02 15:01:03 -0400812
John Stiles0dd1a772021-03-09 22:14:27 -0500813 if (functionDef->declaration().modifiers().fFlags & Modifiers::kNoInline_Flag) {
814 // Refuse to inline functions decorated with `noinline`.
815 return false;
816 }
817
John Stiles74ebd7e2020-12-17 14:41:50 -0500818 // We don't have any mechanism to simulate early returns within a construct that supports
819 // continues (for/do/while), so we can't inline if there's a return inside one.
820 bool hasReturnInContinuableConstruct =
821 (count_returns_in_continuable_constructs(*functionDef) > 0);
822 return !hasReturnInContinuableConstruct;
John Stiles44e96be2020-08-31 13:16:04 -0400823}
824
John Stiles2d7973a2020-10-02 15:01:03 -0400825// A candidate function for inlining, containing everything that `inlineCall` needs.
826struct InlineCandidate {
John Stiles78047582020-12-16 16:17:41 -0500827 std::shared_ptr<SymbolTable> fSymbols; // the SymbolTable of the candidate
John Stiles2d7973a2020-10-02 15:01:03 -0400828 std::unique_ptr<Statement>* fParentStmt; // the parent Statement of the enclosing stmt
829 std::unique_ptr<Statement>* fEnclosingStmt; // the Statement containing the candidate
830 std::unique_ptr<Expression>* fCandidateExpr; // the candidate FunctionCall to be inlined
831 FunctionDefinition* fEnclosingFunction; // the Function containing the candidate
John Stiles2d7973a2020-10-02 15:01:03 -0400832};
John Stiles93442622020-09-11 12:11:27 -0400833
John Stiles2d7973a2020-10-02 15:01:03 -0400834struct InlineCandidateList {
835 std::vector<InlineCandidate> fCandidates;
836};
837
838class InlineCandidateAnalyzer {
John Stiles70957c82020-10-02 16:42:10 -0400839public:
840 // A list of all the inlining candidates we found during analysis.
841 InlineCandidateList* fCandidateList;
John Stiles2d7973a2020-10-02 15:01:03 -0400842
John Stiles70957c82020-10-02 16:42:10 -0400843 // A stack of the symbol tables; since most nodes don't have one, expected to be shallower than
844 // the enclosing-statement stack.
John Stiles78047582020-12-16 16:17:41 -0500845 std::vector<std::shared_ptr<SymbolTable>> fSymbolTableStack;
John Stiles70957c82020-10-02 16:42:10 -0400846 // A stack of "enclosing" statements--these would be suitable for the inliner to use for adding
847 // new instructions. Not all statements are suitable (e.g. a for-loop's initializer). The
848 // inliner might replace a statement with a block containing the statement.
849 std::vector<std::unique_ptr<Statement>*> fEnclosingStmtStack;
850 // The function that we're currently processing (i.e. inlining into).
851 FunctionDefinition* fEnclosingFunction = nullptr;
John Stiles93442622020-09-11 12:11:27 -0400852
Brian Osman0006ad02020-11-18 15:38:39 -0500853 void visit(const std::vector<std::unique_ptr<ProgramElement>>& elements,
John Stiles78047582020-12-16 16:17:41 -0500854 std::shared_ptr<SymbolTable> symbols,
Brian Osman0006ad02020-11-18 15:38:39 -0500855 InlineCandidateList* candidateList) {
John Stiles70957c82020-10-02 16:42:10 -0400856 fCandidateList = candidateList;
Brian Osman0006ad02020-11-18 15:38:39 -0500857 fSymbolTableStack.push_back(symbols);
John Stiles93442622020-09-11 12:11:27 -0400858
Brian Osman0006ad02020-11-18 15:38:39 -0500859 for (const std::unique_ptr<ProgramElement>& pe : elements) {
Brian Osman1179fcf2020-10-08 16:04:40 -0400860 this->visitProgramElement(pe.get());
John Stiles93442622020-09-11 12:11:27 -0400861 }
862
John Stiles70957c82020-10-02 16:42:10 -0400863 fSymbolTableStack.pop_back();
864 fCandidateList = nullptr;
865 }
866
867 void visitProgramElement(ProgramElement* pe) {
868 switch (pe->kind()) {
869 case ProgramElement::Kind::kFunction: {
870 FunctionDefinition& funcDef = pe->as<FunctionDefinition>();
Brian Osman0006ad02020-11-18 15:38:39 -0500871 fEnclosingFunction = &funcDef;
872 this->visitStatement(&funcDef.body());
John Stiles70957c82020-10-02 16:42:10 -0400873 break;
John Stiles93442622020-09-11 12:11:27 -0400874 }
John Stiles70957c82020-10-02 16:42:10 -0400875 default:
876 // The inliner can't operate outside of a function's scope.
877 break;
878 }
879 }
880
881 void visitStatement(std::unique_ptr<Statement>* stmt,
882 bool isViableAsEnclosingStatement = true) {
883 if (!*stmt) {
884 return;
John Stiles93442622020-09-11 12:11:27 -0400885 }
886
John Stiles70957c82020-10-02 16:42:10 -0400887 size_t oldEnclosingStmtStackSize = fEnclosingStmtStack.size();
888 size_t oldSymbolStackSize = fSymbolTableStack.size();
John Stiles93442622020-09-11 12:11:27 -0400889
John Stiles70957c82020-10-02 16:42:10 -0400890 if (isViableAsEnclosingStatement) {
891 fEnclosingStmtStack.push_back(stmt);
John Stiles93442622020-09-11 12:11:27 -0400892 }
893
John Stiles70957c82020-10-02 16:42:10 -0400894 switch ((*stmt)->kind()) {
895 case Statement::Kind::kBreak:
896 case Statement::Kind::kContinue:
897 case Statement::Kind::kDiscard:
898 case Statement::Kind::kInlineMarker:
899 case Statement::Kind::kNop:
900 break;
901
902 case Statement::Kind::kBlock: {
903 Block& block = (*stmt)->as<Block>();
904 if (block.symbolTable()) {
John Stiles78047582020-12-16 16:17:41 -0500905 fSymbolTableStack.push_back(block.symbolTable());
John Stiles70957c82020-10-02 16:42:10 -0400906 }
907
908 for (std::unique_ptr<Statement>& stmt : block.children()) {
909 this->visitStatement(&stmt);
910 }
911 break;
John Stiles93442622020-09-11 12:11:27 -0400912 }
John Stiles70957c82020-10-02 16:42:10 -0400913 case Statement::Kind::kDo: {
914 DoStatement& doStmt = (*stmt)->as<DoStatement>();
915 // The loop body is a candidate for inlining.
916 this->visitStatement(&doStmt.statement());
917 // The inliner isn't smart enough to inline the test-expression for a do-while
918 // loop at this time. There are two limitations:
919 // - We would need to insert the inlined-body block at the very end of the do-
920 // statement's inner fStatement. We don't support that today, but it's doable.
921 // - We cannot inline the test expression if the loop uses `continue` anywhere; that
922 // would skip over the inlined block that evaluates the test expression. There
923 // isn't a good fix for this--any workaround would be more complex than the cost
924 // of a function call. However, loops that don't use `continue` would still be
925 // viable candidates for inlining.
926 break;
John Stiles93442622020-09-11 12:11:27 -0400927 }
John Stiles70957c82020-10-02 16:42:10 -0400928 case Statement::Kind::kExpression: {
929 ExpressionStatement& expr = (*stmt)->as<ExpressionStatement>();
930 this->visitExpression(&expr.expression());
931 break;
932 }
933 case Statement::Kind::kFor: {
934 ForStatement& forStmt = (*stmt)->as<ForStatement>();
Ethan Nicholas0d31ed52020-10-05 14:47:09 -0400935 if (forStmt.symbols()) {
John Stiles78047582020-12-16 16:17:41 -0500936 fSymbolTableStack.push_back(forStmt.symbols());
John Stiles70957c82020-10-02 16:42:10 -0400937 }
938
939 // The initializer and loop body are candidates for inlining.
Ethan Nicholas0d31ed52020-10-05 14:47:09 -0400940 this->visitStatement(&forStmt.initializer(),
John Stiles70957c82020-10-02 16:42:10 -0400941 /*isViableAsEnclosingStatement=*/false);
Ethan Nicholas0d31ed52020-10-05 14:47:09 -0400942 this->visitStatement(&forStmt.statement());
John Stiles70957c82020-10-02 16:42:10 -0400943
944 // The inliner isn't smart enough to inline the test- or increment-expressions
945 // of a for loop loop at this time. There are a handful of limitations:
946 // - We would need to insert the test-expression block at the very beginning of the
947 // for-loop's inner fStatement, and the increment-expression block at the very
948 // end. We don't support that today, but it's doable.
949 // - The for-loop's built-in test-expression would need to be dropped entirely,
950 // and the loop would be halted via a break statement at the end of the inlined
951 // test-expression. This is again something we don't support today, but it could
952 // be implemented.
953 // - We cannot inline the increment-expression if the loop uses `continue` anywhere;
954 // that would skip over the inlined block that evaluates the increment expression.
955 // There isn't a good fix for this--any workaround would be more complex than the
956 // cost of a function call. However, loops that don't use `continue` would still
957 // be viable candidates for increment-expression inlining.
958 break;
959 }
960 case Statement::Kind::kIf: {
961 IfStatement& ifStmt = (*stmt)->as<IfStatement>();
Ethan Nicholas8c44eca2020-10-07 16:47:09 -0400962 this->visitExpression(&ifStmt.test());
963 this->visitStatement(&ifStmt.ifTrue());
964 this->visitStatement(&ifStmt.ifFalse());
John Stiles70957c82020-10-02 16:42:10 -0400965 break;
966 }
967 case Statement::Kind::kReturn: {
968 ReturnStatement& returnStmt = (*stmt)->as<ReturnStatement>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -0400969 this->visitExpression(&returnStmt.expression());
John Stiles70957c82020-10-02 16:42:10 -0400970 break;
971 }
972 case Statement::Kind::kSwitch: {
973 SwitchStatement& switchStmt = (*stmt)->as<SwitchStatement>();
Ethan Nicholas01b05e52020-10-22 15:53:41 -0400974 if (switchStmt.symbols()) {
John Stiles78047582020-12-16 16:17:41 -0500975 fSymbolTableStack.push_back(switchStmt.symbols());
John Stiles70957c82020-10-02 16:42:10 -0400976 }
977
Ethan Nicholas01b05e52020-10-22 15:53:41 -0400978 this->visitExpression(&switchStmt.value());
John Stilesb23a64b2021-03-11 08:27:59 -0500979 for (const std::unique_ptr<Statement>& switchCase : switchStmt.cases()) {
John Stiles70957c82020-10-02 16:42:10 -0400980 // The switch-case's fValue cannot be a FunctionCall; skip it.
John Stilesb23a64b2021-03-11 08:27:59 -0500981 this->visitStatement(&switchCase->as<SwitchCase>().statement());
John Stiles70957c82020-10-02 16:42:10 -0400982 }
983 break;
984 }
985 case Statement::Kind::kVarDeclaration: {
986 VarDeclaration& varDeclStmt = (*stmt)->as<VarDeclaration>();
987 // Don't need to scan the declaration's sizes; those are always IntLiterals.
Ethan Nicholasc51f33e2020-10-13 13:49:44 -0400988 this->visitExpression(&varDeclStmt.value());
John Stiles70957c82020-10-02 16:42:10 -0400989 break;
990 }
John Stiles70957c82020-10-02 16:42:10 -0400991 default:
992 SkUNREACHABLE;
John Stiles93442622020-09-11 12:11:27 -0400993 }
994
John Stiles70957c82020-10-02 16:42:10 -0400995 // Pop our symbol and enclosing-statement stacks.
996 fSymbolTableStack.resize(oldSymbolStackSize);
997 fEnclosingStmtStack.resize(oldEnclosingStmtStackSize);
998 }
999
1000 void visitExpression(std::unique_ptr<Expression>* expr) {
1001 if (!*expr) {
1002 return;
John Stiles93442622020-09-11 12:11:27 -04001003 }
John Stiles70957c82020-10-02 16:42:10 -04001004
1005 switch ((*expr)->kind()) {
1006 case Expression::Kind::kBoolLiteral:
1007 case Expression::Kind::kDefined:
Brian Osmanbe0b3b72021-01-06 14:27:35 -05001008 case Expression::Kind::kExternalFunctionReference:
John Stiles70957c82020-10-02 16:42:10 -04001009 case Expression::Kind::kFieldAccess:
1010 case Expression::Kind::kFloatLiteral:
1011 case Expression::Kind::kFunctionReference:
1012 case Expression::Kind::kIntLiteral:
John Stiles70957c82020-10-02 16:42:10 -04001013 case Expression::Kind::kSetting:
1014 case Expression::Kind::kTypeReference:
1015 case Expression::Kind::kVariableReference:
1016 // Nothing to scan here.
1017 break;
1018
1019 case Expression::Kind::kBinary: {
1020 BinaryExpression& binaryExpr = (*expr)->as<BinaryExpression>();
John Stiles2d4f9592020-10-30 10:29:12 -04001021 this->visitExpression(&binaryExpr.left());
John Stiles70957c82020-10-02 16:42:10 -04001022
1023 // Logical-and and logical-or binary expressions do not inline the right side,
1024 // because that would invalidate short-circuiting. That is, when evaluating
1025 // expressions like these:
1026 // (false && x()) // always false
1027 // (true || y()) // always true
1028 // It is illegal for side-effects from x() or y() to occur. The simplest way to
1029 // enforce that rule is to avoid inlining the right side entirely. However, it is
1030 // safe for other types of binary expression to inline both sides.
John Stiles45990502021-02-16 10:55:27 -05001031 Operator op = binaryExpr.getOperator();
1032 bool shortCircuitable = (op.kind() == Token::Kind::TK_LOGICALAND ||
1033 op.kind() == Token::Kind::TK_LOGICALOR);
John Stiles70957c82020-10-02 16:42:10 -04001034 if (!shortCircuitable) {
John Stiles2d4f9592020-10-30 10:29:12 -04001035 this->visitExpression(&binaryExpr.right());
John Stiles70957c82020-10-02 16:42:10 -04001036 }
1037 break;
1038 }
1039 case Expression::Kind::kConstructor: {
1040 Constructor& constructorExpr = (*expr)->as<Constructor>();
1041 for (std::unique_ptr<Expression>& arg : constructorExpr.arguments()) {
1042 this->visitExpression(&arg);
1043 }
1044 break;
1045 }
1046 case Expression::Kind::kExternalFunctionCall: {
1047 ExternalFunctionCall& funcCallExpr = (*expr)->as<ExternalFunctionCall>();
1048 for (std::unique_ptr<Expression>& arg : funcCallExpr.arguments()) {
1049 this->visitExpression(&arg);
1050 }
1051 break;
1052 }
1053 case Expression::Kind::kFunctionCall: {
1054 FunctionCall& funcCallExpr = (*expr)->as<FunctionCall>();
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001055 for (std::unique_ptr<Expression>& arg : funcCallExpr.arguments()) {
John Stiles70957c82020-10-02 16:42:10 -04001056 this->visitExpression(&arg);
1057 }
1058 this->addInlineCandidate(expr);
1059 break;
1060 }
1061 case Expression::Kind::kIndex:{
1062 IndexExpression& indexExpr = (*expr)->as<IndexExpression>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04001063 this->visitExpression(&indexExpr.base());
1064 this->visitExpression(&indexExpr.index());
John Stiles70957c82020-10-02 16:42:10 -04001065 break;
1066 }
1067 case Expression::Kind::kPostfix: {
1068 PostfixExpression& postfixExpr = (*expr)->as<PostfixExpression>();
Ethan Nicholas444ccc62020-10-09 10:16:22 -04001069 this->visitExpression(&postfixExpr.operand());
John Stiles70957c82020-10-02 16:42:10 -04001070 break;
1071 }
1072 case Expression::Kind::kPrefix: {
1073 PrefixExpression& prefixExpr = (*expr)->as<PrefixExpression>();
Ethan Nicholas444ccc62020-10-09 10:16:22 -04001074 this->visitExpression(&prefixExpr.operand());
John Stiles70957c82020-10-02 16:42:10 -04001075 break;
1076 }
1077 case Expression::Kind::kSwizzle: {
1078 Swizzle& swizzleExpr = (*expr)->as<Swizzle>();
Ethan Nicholas6b4d5812020-10-12 16:11:51 -04001079 this->visitExpression(&swizzleExpr.base());
John Stiles70957c82020-10-02 16:42:10 -04001080 break;
1081 }
1082 case Expression::Kind::kTernary: {
1083 TernaryExpression& ternaryExpr = (*expr)->as<TernaryExpression>();
1084 // The test expression is a candidate for inlining.
Ethan Nicholasdd218162020-10-08 05:48:01 -04001085 this->visitExpression(&ternaryExpr.test());
John Stiles70957c82020-10-02 16:42:10 -04001086 // The true- and false-expressions cannot be inlined, because we are only allowed to
1087 // evaluate one side.
1088 break;
1089 }
1090 default:
1091 SkUNREACHABLE;
1092 }
1093 }
1094
1095 void addInlineCandidate(std::unique_ptr<Expression>* candidate) {
1096 fCandidateList->fCandidates.push_back(
1097 InlineCandidate{fSymbolTableStack.back(),
1098 find_parent_statement(fEnclosingStmtStack),
1099 fEnclosingStmtStack.back(),
1100 candidate,
John Stiles9b9415e2020-11-23 14:48:06 -05001101 fEnclosingFunction});
John Stiles70957c82020-10-02 16:42:10 -04001102 }
John Stiles2d7973a2020-10-02 15:01:03 -04001103};
John Stiles93442622020-09-11 12:11:27 -04001104
John Stiles9b9415e2020-11-23 14:48:06 -05001105static const FunctionDeclaration& candidate_func(const InlineCandidate& candidate) {
1106 return (*candidate.fCandidateExpr)->as<FunctionCall>().function();
1107}
John Stiles915a38c2020-09-14 09:38:13 -04001108
John Stiles9b9415e2020-11-23 14:48:06 -05001109bool Inliner::candidateCanBeInlined(const InlineCandidate& candidate, InlinabilityCache* cache) {
1110 const FunctionDeclaration& funcDecl = candidate_func(candidate);
John Stiles1c03d332020-10-13 10:30:23 -04001111 auto [iter, wasInserted] = cache->insert({&funcDecl, false});
John Stiles2d7973a2020-10-02 15:01:03 -04001112 if (wasInserted) {
1113 // Recursion is forbidden here to avoid an infinite death spiral of inlining.
John Stiles132cfdd2021-03-15 22:08:38 +00001114 iter->second = this->isSafeToInline(funcDecl.definition()) &&
1115 !contains_recursive_call(funcDecl);
John Stiles93442622020-09-11 12:11:27 -04001116 }
1117
John Stiles2d7973a2020-10-02 15:01:03 -04001118 return iter->second;
1119}
1120
John Stiles9b9415e2020-11-23 14:48:06 -05001121int Inliner::getFunctionSize(const FunctionDeclaration& funcDecl, FunctionSizeCache* cache) {
1122 auto [iter, wasInserted] = cache->insert({&funcDecl, 0});
John Stiles2d7973a2020-10-02 15:01:03 -04001123 if (wasInserted) {
John Stiles9b9415e2020-11-23 14:48:06 -05001124 iter->second = Analysis::NodeCountUpToLimit(*funcDecl.definition(),
John Stilesd1204642021-02-17 16:30:02 -05001125 this->settings().fInlineThreshold);
John Stiles2d7973a2020-10-02 15:01:03 -04001126 }
John Stiles2d7973a2020-10-02 15:01:03 -04001127 return iter->second;
1128}
1129
Brian Osman0006ad02020-11-18 15:38:39 -05001130void Inliner::buildCandidateList(const std::vector<std::unique_ptr<ProgramElement>>& elements,
John Stiles78047582020-12-16 16:17:41 -05001131 std::shared_ptr<SymbolTable> symbols, ProgramUsage* usage,
Brian Osman0006ad02020-11-18 15:38:39 -05001132 InlineCandidateList* candidateList) {
John Stiles2d7973a2020-10-02 15:01:03 -04001133 // This is structured much like a ProgramVisitor, but does not actually use ProgramVisitor.
1134 // The analyzer needs to keep track of the `unique_ptr<T>*` of statements and expressions so
1135 // that they can later be replaced, and ProgramVisitor does not provide this; it only provides a
1136 // `const T&`.
1137 InlineCandidateAnalyzer analyzer;
Brian Osman0006ad02020-11-18 15:38:39 -05001138 analyzer.visit(elements, symbols, candidateList);
John Stiles2d7973a2020-10-02 15:01:03 -04001139
John Stiles0ad233f2020-11-25 11:02:05 -05001140 // Early out if there are no inlining candidates.
John Stiles2d7973a2020-10-02 15:01:03 -04001141 std::vector<InlineCandidate>& candidates = candidateList->fCandidates;
John Stiles0ad233f2020-11-25 11:02:05 -05001142 if (candidates.empty()) {
1143 return;
1144 }
1145
1146 // Remove candidates that are not safe to inline.
John Stiles2d7973a2020-10-02 15:01:03 -04001147 InlinabilityCache cache;
1148 candidates.erase(std::remove_if(candidates.begin(),
1149 candidates.end(),
1150 [&](const InlineCandidate& candidate) {
1151 return !this->candidateCanBeInlined(candidate, &cache);
1152 }),
1153 candidates.end());
1154
John Stiles0ad233f2020-11-25 11:02:05 -05001155 // If the inline threshold is unlimited, or if we have no candidates left, our candidate list is
1156 // complete.
John Stilesd1204642021-02-17 16:30:02 -05001157 if (this->settings().fInlineThreshold == INT_MAX || candidates.empty()) {
John Stiles0ad233f2020-11-25 11:02:05 -05001158 return;
John Stiles2d7973a2020-10-02 15:01:03 -04001159 }
John Stiles0ad233f2020-11-25 11:02:05 -05001160
1161 // Remove candidates on a per-function basis if the effect of inlining would be to make more
1162 // than `inlineThreshold` nodes. (i.e. if Func() would be inlined six times and its size is
1163 // 10 nodes, it should be inlined if the inlineThreshold is 60 or higher.)
1164 FunctionSizeCache functionSizeCache;
1165 FunctionSizeCache candidateTotalCost;
1166 for (InlineCandidate& candidate : candidates) {
1167 const FunctionDeclaration& fnDecl = candidate_func(candidate);
1168 candidateTotalCost[&fnDecl] += this->getFunctionSize(fnDecl, &functionSizeCache);
1169 }
1170
John Stilesd1204642021-02-17 16:30:02 -05001171 candidates.erase(std::remove_if(candidates.begin(), candidates.end(),
1172 [&](const InlineCandidate& candidate) {
1173 const FunctionDeclaration& fnDecl = candidate_func(candidate);
1174 if (fnDecl.modifiers().fFlags & Modifiers::kInline_Flag) {
1175 // Functions marked `inline` ignore size limitations.
1176 return false;
1177 }
1178 if (usage->get(fnDecl) == 1) {
1179 // If a function is only used once, it's cost-free to inline.
1180 return false;
1181 }
1182 if (candidateTotalCost[&fnDecl] <= this->settings().fInlineThreshold) {
1183 // We won't exceed the inline threshold by inlining this.
1184 return false;
1185 }
1186 // Inlining this function will add too many IRNodes.
1187 return true;
1188 }),
1189 candidates.end());
John Stiles2d7973a2020-10-02 15:01:03 -04001190}
1191
Brian Osman0006ad02020-11-18 15:38:39 -05001192bool Inliner::analyze(const std::vector<std::unique_ptr<ProgramElement>>& elements,
John Stiles78047582020-12-16 16:17:41 -05001193 std::shared_ptr<SymbolTable> symbols,
Brian Osman0006ad02020-11-18 15:38:39 -05001194 ProgramUsage* usage) {
John Stilesd34d56e2020-10-12 12:04:47 -04001195 // A threshold of zero indicates that the inliner is completely disabled, so we can just return.
John Stilesd1204642021-02-17 16:30:02 -05001196 if (this->settings().fInlineThreshold <= 0) {
John Stilesd34d56e2020-10-12 12:04:47 -04001197 return false;
1198 }
1199
John Stiles031a7672020-11-13 16:13:18 -05001200 // Enforce a limit on inlining to avoid pathological cases. (inliner/ExponentialGrowth.sksl)
1201 if (fInlinedStatementCounter >= kInlinedStatementLimit) {
1202 return false;
1203 }
1204
John Stiles2d7973a2020-10-02 15:01:03 -04001205 InlineCandidateList candidateList;
John Stiles9b9415e2020-11-23 14:48:06 -05001206 this->buildCandidateList(elements, symbols, usage, &candidateList);
John Stiles2d7973a2020-10-02 15:01:03 -04001207
John Stiles915a38c2020-09-14 09:38:13 -04001208 // Inline the candidates where we've determined that it's safe to do so.
1209 std::unordered_set<const std::unique_ptr<Statement>*> enclosingStmtSet;
1210 bool madeChanges = false;
John Stiles2d7973a2020-10-02 15:01:03 -04001211 for (const InlineCandidate& candidate : candidateList.fCandidates) {
John Stiles915a38c2020-09-14 09:38:13 -04001212 FunctionCall& funcCall = (*candidate.fCandidateExpr)->as<FunctionCall>();
John Stiles915a38c2020-09-14 09:38:13 -04001213
1214 // Inlining two expressions using the same enclosing statement in the same inlining pass
1215 // does not work properly. If this happens, skip it; we'll get it in the next pass.
1216 auto [unusedIter, inserted] = enclosingStmtSet.insert(candidate.fEnclosingStmt);
1217 if (!inserted) {
1218 continue;
1219 }
1220
1221 // Convert the function call to its inlined equivalent.
Brian Osman3887a012020-09-30 13:22:27 -04001222 InlinedCall inlinedCall = this->inlineCall(&funcCall, candidate.fSymbols,
Ethan Nicholas0a5d0962020-10-14 13:33:18 -04001223 &candidate.fEnclosingFunction->declaration());
John Stiles915a38c2020-09-14 09:38:13 -04001224
John Stiles0c2d14a2021-03-01 10:08:08 -05001225 // Stop if an error was detected during the inlining process.
1226 if (!inlinedCall.fInlinedBody && !inlinedCall.fReplacementExpr) {
1227 break;
John Stiles915a38c2020-09-14 09:38:13 -04001228 }
1229
John Stiles0c2d14a2021-03-01 10:08:08 -05001230 // Ensure that the inlined body has a scope if it needs one.
1231 this->ensureScopedBlocks(inlinedCall.fInlinedBody.get(), candidate.fParentStmt->get());
1232
1233 // Add references within the inlined body
1234 usage->add(inlinedCall.fInlinedBody.get());
1235
1236 // Move the enclosing statement to the end of the unscoped Block containing the inlined
1237 // function, then replace the enclosing statement with that Block.
1238 // Before:
1239 // fInlinedBody = Block{ stmt1, stmt2, stmt3 }
1240 // fEnclosingStmt = stmt4
1241 // After:
1242 // fInlinedBody = null
1243 // fEnclosingStmt = Block{ stmt1, stmt2, stmt3, stmt4 }
1244 inlinedCall.fInlinedBody->children().push_back(std::move(*candidate.fEnclosingStmt));
1245 *candidate.fEnclosingStmt = std::move(inlinedCall.fInlinedBody);
1246
John Stiles915a38c2020-09-14 09:38:13 -04001247 // Replace the candidate function call with our replacement expression.
Brian Osman010ce6a2020-10-19 16:34:10 -04001248 usage->replace(candidate.fCandidateExpr->get(), inlinedCall.fReplacementExpr.get());
John Stiles915a38c2020-09-14 09:38:13 -04001249 *candidate.fCandidateExpr = std::move(inlinedCall.fReplacementExpr);
1250 madeChanges = true;
1251
John Stiles031a7672020-11-13 16:13:18 -05001252 // Stop inlining if we've reached our hard cap on new statements.
1253 if (fInlinedStatementCounter >= kInlinedStatementLimit) {
1254 break;
1255 }
1256
John Stiles915a38c2020-09-14 09:38:13 -04001257 // Note that nothing was destroyed except for the FunctionCall. All other nodes should
1258 // remain valid.
1259 }
1260
1261 return madeChanges;
John Stiles93442622020-09-11 12:11:27 -04001262}
1263
John Stiles44e96be2020-08-31 13:16:04 -04001264} // namespace SkSL