blob: 8e2e402a2ddf06c7a64c6400e575483e1a90b54b [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
14#include "src/sksl/SkSLAnalysis.h"
15#include "src/sksl/ir/SkSLBinaryExpression.h"
16#include "src/sksl/ir/SkSLBoolLiteral.h"
17#include "src/sksl/ir/SkSLBreakStatement.h"
18#include "src/sksl/ir/SkSLConstructor.h"
19#include "src/sksl/ir/SkSLContinueStatement.h"
20#include "src/sksl/ir/SkSLDiscardStatement.h"
21#include "src/sksl/ir/SkSLDoStatement.h"
22#include "src/sksl/ir/SkSLEnum.h"
23#include "src/sksl/ir/SkSLExpressionStatement.h"
24#include "src/sksl/ir/SkSLExternalFunctionCall.h"
25#include "src/sksl/ir/SkSLExternalValueReference.h"
26#include "src/sksl/ir/SkSLField.h"
27#include "src/sksl/ir/SkSLFieldAccess.h"
28#include "src/sksl/ir/SkSLFloatLiteral.h"
29#include "src/sksl/ir/SkSLForStatement.h"
30#include "src/sksl/ir/SkSLFunctionCall.h"
31#include "src/sksl/ir/SkSLFunctionDeclaration.h"
32#include "src/sksl/ir/SkSLFunctionDefinition.h"
33#include "src/sksl/ir/SkSLFunctionReference.h"
34#include "src/sksl/ir/SkSLIfStatement.h"
35#include "src/sksl/ir/SkSLIndexExpression.h"
John Stiles98c1f822020-09-09 14:18:53 -040036#include "src/sksl/ir/SkSLInlineMarker.h"
John Stiles44e96be2020-08-31 13:16:04 -040037#include "src/sksl/ir/SkSLIntLiteral.h"
38#include "src/sksl/ir/SkSLInterfaceBlock.h"
39#include "src/sksl/ir/SkSLLayout.h"
40#include "src/sksl/ir/SkSLNop.h"
41#include "src/sksl/ir/SkSLNullLiteral.h"
42#include "src/sksl/ir/SkSLPostfixExpression.h"
43#include "src/sksl/ir/SkSLPrefixExpression.h"
44#include "src/sksl/ir/SkSLReturnStatement.h"
45#include "src/sksl/ir/SkSLSetting.h"
46#include "src/sksl/ir/SkSLSwitchCase.h"
47#include "src/sksl/ir/SkSLSwitchStatement.h"
48#include "src/sksl/ir/SkSLSwizzle.h"
49#include "src/sksl/ir/SkSLTernaryExpression.h"
50#include "src/sksl/ir/SkSLUnresolvedFunction.h"
51#include "src/sksl/ir/SkSLVarDeclarations.h"
John Stiles44e96be2020-08-31 13:16:04 -040052#include "src/sksl/ir/SkSLVariable.h"
53#include "src/sksl/ir/SkSLVariableReference.h"
John Stiles44e96be2020-08-31 13:16:04 -040054
55namespace SkSL {
56namespace {
57
John Stiles031a7672020-11-13 16:13:18 -050058static constexpr int kInlinedStatementLimit = 2500;
59
John Stiles9e948122020-12-16 18:24:48 +000060static bool contains_returns_above_limit(const FunctionDefinition& funcDef, int limit) {
John Stiles44dff4f2020-09-21 12:28:01 -040061 class CountReturnsWithLimit : public ProgramVisitor {
John Stiles44e96be2020-08-31 13:16:04 -040062 public:
John Stiles44dff4f2020-09-21 12:28:01 -040063 CountReturnsWithLimit(const FunctionDefinition& funcDef, int limit) : fLimit(limit) {
John Stiles44e96be2020-08-31 13:16:04 -040064 this->visitProgramElement(funcDef);
65 }
66
67 bool visitStatement(const Statement& stmt) override {
Ethan Nicholase6592142020-09-08 10:22:09 -040068 switch (stmt.kind()) {
69 case Statement::Kind::kReturn:
John Stiles44e96be2020-08-31 13:16:04 -040070 ++fNumReturns;
John Stiles9e948122020-12-16 18:24:48 +000071 return (fNumReturns > fLimit) || INHERITED::visitStatement(stmt);
John Stiles44e96be2020-08-31 13:16:04 -040072
73 default:
John Stiles93442622020-09-11 12:11:27 -040074 return INHERITED::visitStatement(stmt);
John Stiles44e96be2020-08-31 13:16:04 -040075 }
76 }
77
78 int fNumReturns = 0;
John Stiles44dff4f2020-09-21 12:28:01 -040079 int fLimit = 0;
John Stiles44e96be2020-08-31 13:16:04 -040080 using INHERITED = ProgramVisitor;
81 };
82
John Stiles9e948122020-12-16 18:24:48 +000083 return CountReturnsWithLimit{funcDef, limit}.fNumReturns > limit;
John Stiles44e96be2020-08-31 13:16:04 -040084}
85
86static int count_returns_at_end_of_control_flow(const FunctionDefinition& funcDef) {
87 class CountReturnsAtEndOfControlFlow : public ProgramVisitor {
88 public:
89 CountReturnsAtEndOfControlFlow(const FunctionDefinition& funcDef) {
90 this->visitProgramElement(funcDef);
91 }
92
93 bool visitStatement(const Statement& stmt) override {
Ethan Nicholase6592142020-09-08 10:22:09 -040094 switch (stmt.kind()) {
95 case Statement::Kind::kBlock: {
John Stiles44e96be2020-08-31 13:16:04 -040096 // Check only the last statement of a block.
Ethan Nicholas7bd60432020-09-25 14:31:59 -040097 const auto& block = stmt.as<Block>();
98 return block.children().size() &&
99 this->visitStatement(*block.children().back());
John Stiles44e96be2020-08-31 13:16:04 -0400100 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400101 case Statement::Kind::kSwitch:
Ethan Nicholase6592142020-09-08 10:22:09 -0400102 case Statement::Kind::kDo:
103 case Statement::Kind::kFor:
John Stiles44e96be2020-08-31 13:16:04 -0400104 // Don't introspect switches or loop structures at all.
105 return false;
106
Ethan Nicholase6592142020-09-08 10:22:09 -0400107 case Statement::Kind::kReturn:
John Stiles44e96be2020-08-31 13:16:04 -0400108 ++fNumReturns;
109 [[fallthrough]];
110
111 default:
John Stiles93442622020-09-11 12:11:27 -0400112 return INHERITED::visitStatement(stmt);
John Stiles44e96be2020-08-31 13:16:04 -0400113 }
114 }
115
116 int fNumReturns = 0;
117 using INHERITED = ProgramVisitor;
118 };
119
120 return CountReturnsAtEndOfControlFlow{funcDef}.fNumReturns;
121}
122
123static int count_returns_in_breakable_constructs(const FunctionDefinition& funcDef) {
124 class CountReturnsInBreakableConstructs : public ProgramVisitor {
125 public:
126 CountReturnsInBreakableConstructs(const FunctionDefinition& funcDef) {
127 this->visitProgramElement(funcDef);
128 }
129
130 bool visitStatement(const Statement& stmt) override {
Ethan Nicholase6592142020-09-08 10:22:09 -0400131 switch (stmt.kind()) {
132 case Statement::Kind::kSwitch:
Ethan Nicholase6592142020-09-08 10:22:09 -0400133 case Statement::Kind::kDo:
134 case Statement::Kind::kFor: {
John Stiles44e96be2020-08-31 13:16:04 -0400135 ++fInsideBreakableConstruct;
John Stiles93442622020-09-11 12:11:27 -0400136 bool result = INHERITED::visitStatement(stmt);
John Stiles44e96be2020-08-31 13:16:04 -0400137 --fInsideBreakableConstruct;
138 return result;
139 }
140
Ethan Nicholase6592142020-09-08 10:22:09 -0400141 case Statement::Kind::kReturn:
John Stiles44e96be2020-08-31 13:16:04 -0400142 fNumReturns += (fInsideBreakableConstruct > 0) ? 1 : 0;
143 [[fallthrough]];
144
145 default:
John Stiles93442622020-09-11 12:11:27 -0400146 return INHERITED::visitStatement(stmt);
John Stiles44e96be2020-08-31 13:16:04 -0400147 }
148 }
149
150 int fNumReturns = 0;
151 int fInsideBreakableConstruct = 0;
152 using INHERITED = ProgramVisitor;
153 };
154
155 return CountReturnsInBreakableConstructs{funcDef}.fNumReturns;
156}
157
John Stiles9e948122020-12-16 18:24:48 +0000158static bool has_early_return(const FunctionDefinition& funcDef) {
159 int returnsAtEndOfControlFlow = count_returns_at_end_of_control_flow(funcDef);
160 return contains_returns_above_limit(funcDef, returnsAtEndOfControlFlow);
161}
162
John Stiles991b09d2020-09-10 13:33:40 -0400163static bool contains_recursive_call(const FunctionDeclaration& funcDecl) {
164 class ContainsRecursiveCall : public ProgramVisitor {
165 public:
166 bool visit(const FunctionDeclaration& funcDecl) {
167 fFuncDecl = &funcDecl;
Ethan Nicholased84b732020-10-08 11:45:44 -0400168 return funcDecl.definition() ? this->visitProgramElement(*funcDecl.definition())
169 : false;
John Stiles991b09d2020-09-10 13:33:40 -0400170 }
171
172 bool visitExpression(const Expression& expr) override {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400173 if (expr.is<FunctionCall>() && expr.as<FunctionCall>().function().matches(*fFuncDecl)) {
John Stiles991b09d2020-09-10 13:33:40 -0400174 return true;
175 }
176 return INHERITED::visitExpression(expr);
177 }
178
179 bool visitStatement(const Statement& stmt) override {
Ethan Nicholasceb62142020-10-09 16:51:18 -0400180 if (stmt.is<InlineMarker>() &&
181 stmt.as<InlineMarker>().function().matches(*fFuncDecl)) {
John Stiles991b09d2020-09-10 13:33:40 -0400182 return true;
183 }
184 return INHERITED::visitStatement(stmt);
185 }
186
187 const FunctionDeclaration* fFuncDecl;
188 using INHERITED = ProgramVisitor;
189 };
190
191 return ContainsRecursiveCall{}.visit(funcDecl);
192}
193
John Stiles44e96be2020-08-31 13:16:04 -0400194static const Type* copy_if_needed(const Type* src, SymbolTable& symbolTable) {
John Stilesc0c51062020-12-03 17:16:29 -0500195 if (src->isArray()) {
John Stiles74ff1d62020-11-30 11:56:16 -0500196 const Type* innerType = copy_if_needed(&src->componentType(), symbolTable);
John Stilesad2d4942020-12-11 16:55:58 -0500197 return symbolTable.takeOwnershipOfSymbol(Type::MakeArrayType(src->name(), *innerType,
198 src->columns()));
John Stiles44e96be2020-08-31 13:16:04 -0400199 }
200 return src;
201}
202
John Stiles6d696082020-10-01 10:18:54 -0400203static std::unique_ptr<Statement>* find_parent_statement(
204 const std::vector<std::unique_ptr<Statement>*>& stmtStack) {
John Stiles915a38c2020-09-14 09:38:13 -0400205 SkASSERT(!stmtStack.empty());
206
207 // Walk the statement stack from back to front, ignoring the last element (which is the
208 // enclosing statement).
209 auto iter = stmtStack.rbegin();
210 ++iter;
211
212 // Anything counts as a parent statement other than a scopeless Block.
213 for (; iter != stmtStack.rend(); ++iter) {
John Stiles6d696082020-10-01 10:18:54 -0400214 std::unique_ptr<Statement>* stmt = *iter;
215 if (!(*stmt)->is<Block>() || (*stmt)->as<Block>().isScope()) {
John Stiles915a38c2020-09-14 09:38:13 -0400216 return stmt;
217 }
218 }
219
220 // There wasn't any parent statement to be found.
221 return nullptr;
222}
223
John Stilese41b4ee2020-09-28 12:28:16 -0400224std::unique_ptr<Expression> clone_with_ref_kind(const Expression& expr,
225 VariableReference::RefKind refKind) {
226 std::unique_ptr<Expression> clone = expr.clone();
John Stiles70b82422020-09-30 10:55:12 -0400227 class SetRefKindInExpression : public ProgramWriter {
John Stilese41b4ee2020-09-28 12:28:16 -0400228 public:
229 SetRefKindInExpression(VariableReference::RefKind refKind) : fRefKind(refKind) {}
John Stiles70b82422020-09-30 10:55:12 -0400230 bool visitExpression(Expression& expr) override {
John Stilese41b4ee2020-09-28 12:28:16 -0400231 if (expr.is<VariableReference>()) {
John Stiles70b82422020-09-30 10:55:12 -0400232 expr.as<VariableReference>().setRefKind(fRefKind);
John Stilese41b4ee2020-09-28 12:28:16 -0400233 }
234 return INHERITED::visitExpression(expr);
235 }
236
237 private:
238 VariableReference::RefKind fRefKind;
239
John Stiles70b82422020-09-30 10:55:12 -0400240 using INHERITED = ProgramWriter;
John Stilese41b4ee2020-09-28 12:28:16 -0400241 };
242
243 SetRefKindInExpression{refKind}.visitExpression(*clone);
244 return clone;
245}
246
John Stiles44e96be2020-08-31 13:16:04 -0400247} // namespace
248
John Stilesb61ee902020-09-21 12:26:59 -0400249void Inliner::ensureScopedBlocks(Statement* inlinedBody, Statement* parentStmt) {
250 // No changes necessary if this statement isn't actually a block.
251 if (!inlinedBody || !inlinedBody->is<Block>()) {
252 return;
253 }
254
255 // No changes necessary if the parent statement doesn't require a scope.
256 if (!parentStmt || !(parentStmt->is<IfStatement>() || parentStmt->is<ForStatement>() ||
Brian Osmand6f23382020-12-15 17:08:59 -0500257 parentStmt->is<DoStatement>())) {
John Stilesb61ee902020-09-21 12:26:59 -0400258 return;
259 }
260
261 Block& block = inlinedBody->as<Block>();
262
263 // The inliner will create inlined function bodies as a Block containing multiple statements,
264 // but no scope. Normally, this is fine, but if this block is used as the statement for a
265 // do/for/if/while, this isn't actually possible to represent textually; a scope must be added
266 // for the generated code to match the intent. In the case of Blocks nested inside other Blocks,
267 // we add the scope to the outermost block if needed. Zero-statement blocks have similar
268 // issues--if we don't represent the Block textually somehow, we run the risk of accidentally
269 // absorbing the following statement into our loop--so we also add a scope to these.
270 for (Block* nestedBlock = &block;; ) {
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400271 if (nestedBlock->isScope()) {
John Stilesb61ee902020-09-21 12:26:59 -0400272 // We found an explicit scope; all is well.
273 return;
274 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400275 if (nestedBlock->children().size() != 1) {
John Stilesb61ee902020-09-21 12:26:59 -0400276 // We found a block with multiple (or zero) statements, but no scope? Let's add a scope
277 // to the outermost block.
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400278 block.setIsScope(true);
John Stilesb61ee902020-09-21 12:26:59 -0400279 return;
280 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400281 if (!nestedBlock->children()[0]->is<Block>()) {
John Stilesb61ee902020-09-21 12:26:59 -0400282 // This block has exactly one thing inside, and it's not another block. No need to scope
283 // it.
284 return;
285 }
286 // We have to go deeper.
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400287 nestedBlock = &nestedBlock->children()[0]->as<Block>();
John Stilesb61ee902020-09-21 12:26:59 -0400288 }
289}
290
Brian Osman0006ad02020-11-18 15:38:39 -0500291void Inliner::reset(ModifiersPool* modifiers, const Program::Settings* settings) {
Ethan Nicholas041fd0a2020-10-07 16:42:04 -0400292 fModifiers = modifiers;
293 fSettings = settings;
John Stiles44e96be2020-08-31 13:16:04 -0400294 fInlineVarCounter = 0;
John Stiles031a7672020-11-13 16:13:18 -0500295 fInlinedStatementCounter = 0;
John Stiles44e96be2020-08-31 13:16:04 -0400296}
297
John Stiles6f31e272020-12-16 13:30:54 -0500298String Inliner::uniqueNameForInlineVar(String baseName, SymbolTable* symbolTable) {
299 // The inliner runs more than once, so the base name might already have a prefix like "_123_x".
300 // Let's strip that prefix off to make the generated code easier to read.
301 if (baseName.startsWith("_")) {
302 // Determine if we have a string of digits.
303 int offset = 1;
304 while (isdigit(baseName[offset])) {
305 ++offset;
306 }
307 // If we found digits, another underscore, and anything else, that's the inliner prefix.
308 // Strip it off.
309 if (offset > 1 && baseName[offset] == '_' && baseName[offset + 1] != '\0') {
310 baseName.erase(0, offset + 1);
311 } else {
312 // This name doesn't contain an inliner prefix, but it does start with an underscore.
313 // OpenGL disallows two consecutive underscores anywhere in the string, and we'll be
314 // adding one as part of the inliner prefix, so strip the leading underscore.
315 baseName.erase(0, 1);
316 }
317 }
John Stilesc75abb82020-09-14 18:24:12 -0400318
319 // Append a unique numeric prefix to avoid name overlap. Check the symbol table to make sure
320 // we're not reusing an existing name. (Note that within a single compilation pass, this check
321 // isn't fully comprehensive, as code isn't always generated in top-to-bottom order.)
322 String uniqueName;
323 for (;;) {
John Stiles6f31e272020-12-16 13:30:54 -0500324 uniqueName = String::printf("_%d_%s", fInlineVarCounter++, baseName.c_str());
John Stilesc75abb82020-09-14 18:24:12 -0400325 StringFragment frag{uniqueName.data(), uniqueName.length()};
326 if ((*symbolTable)[frag] == nullptr) {
327 break;
328 }
329 }
330
331 return uniqueName;
332}
333
John Stiles44e96be2020-08-31 13:16:04 -0400334std::unique_ptr<Expression> Inliner::inlineExpression(int offset,
335 VariableRewriteMap* varMap,
John Stilesd7cc0932020-11-30 12:24:27 -0500336 SymbolTable* symbolTableForExpression,
John Stiles44e96be2020-08-31 13:16:04 -0400337 const Expression& expression) {
338 auto expr = [&](const std::unique_ptr<Expression>& e) -> std::unique_ptr<Expression> {
339 if (e) {
John Stilesd7cc0932020-11-30 12:24:27 -0500340 return this->inlineExpression(offset, varMap, symbolTableForExpression, *e);
John Stiles44e96be2020-08-31 13:16:04 -0400341 }
342 return nullptr;
343 };
John Stiles8e3b6be2020-10-13 11:14:08 -0400344 auto argList = [&](const ExpressionArray& originalArgs) -> ExpressionArray {
345 ExpressionArray args;
John Stilesf4bda742020-10-14 16:57:41 -0400346 args.reserve_back(originalArgs.size());
John Stiles44e96be2020-08-31 13:16:04 -0400347 for (const std::unique_ptr<Expression>& arg : originalArgs) {
348 args.push_back(expr(arg));
349 }
350 return args;
351 };
352
Ethan Nicholase6592142020-09-08 10:22:09 -0400353 switch (expression.kind()) {
354 case Expression::Kind::kBinary: {
John Stiles44e96be2020-08-31 13:16:04 -0400355 const BinaryExpression& b = expression.as<BinaryExpression>();
356 return std::make_unique<BinaryExpression>(offset,
John Stiles2d4f9592020-10-30 10:29:12 -0400357 expr(b.left()),
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400358 b.getOperator(),
John Stiles2d4f9592020-10-30 10:29:12 -0400359 expr(b.right()),
Ethan Nicholas30d30222020-09-11 12:27:26 -0400360 &b.type());
John Stiles44e96be2020-08-31 13:16:04 -0400361 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400362 case Expression::Kind::kBoolLiteral:
363 case Expression::Kind::kIntLiteral:
364 case Expression::Kind::kFloatLiteral:
365 case Expression::Kind::kNullLiteral:
John Stiles44e96be2020-08-31 13:16:04 -0400366 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400367 case Expression::Kind::kConstructor: {
John Stiles44e96be2020-08-31 13:16:04 -0400368 const Constructor& constructor = expression.as<Constructor>();
John Stilesd7cc0932020-11-30 12:24:27 -0500369 const Type* type = copy_if_needed(&constructor.type(), *symbolTableForExpression);
370 return std::make_unique<Constructor>(offset, type, argList(constructor.arguments()));
John Stiles44e96be2020-08-31 13:16:04 -0400371 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400372 case Expression::Kind::kExternalFunctionCall: {
John Stiles44e96be2020-08-31 13:16:04 -0400373 const ExternalFunctionCall& externalCall = expression.as<ExternalFunctionCall>();
Ethan Nicholas444ccc62020-10-09 10:16:22 -0400374 return std::make_unique<ExternalFunctionCall>(offset, &externalCall.function(),
Ethan Nicholas6e86ec92020-09-30 14:29:56 -0400375 argList(externalCall.arguments()));
John Stiles44e96be2020-08-31 13:16:04 -0400376 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400377 case Expression::Kind::kExternalValue:
John Stiles44e96be2020-08-31 13:16:04 -0400378 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400379 case Expression::Kind::kFieldAccess: {
John Stiles44e96be2020-08-31 13:16:04 -0400380 const FieldAccess& f = expression.as<FieldAccess>();
Ethan Nicholas7a95b202020-10-09 11:55:40 -0400381 return std::make_unique<FieldAccess>(expr(f.base()), f.fieldIndex(), f.ownerKind());
John Stiles44e96be2020-08-31 13:16:04 -0400382 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400383 case Expression::Kind::kFunctionCall: {
John Stiles44e96be2020-08-31 13:16:04 -0400384 const FunctionCall& funcCall = expression.as<FunctionCall>();
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400385 return std::make_unique<FunctionCall>(offset, &funcCall.type(), &funcCall.function(),
386 argList(funcCall.arguments()));
John Stiles44e96be2020-08-31 13:16:04 -0400387 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400388 case Expression::Kind::kFunctionReference:
Brian Osman2b3b35f2020-09-08 09:17:36 -0400389 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400390 case Expression::Kind::kIndex: {
John Stiles44e96be2020-08-31 13:16:04 -0400391 const IndexExpression& idx = expression.as<IndexExpression>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -0400392 return std::make_unique<IndexExpression>(*fContext, expr(idx.base()),
393 expr(idx.index()));
John Stiles44e96be2020-08-31 13:16:04 -0400394 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400395 case Expression::Kind::kPrefix: {
John Stiles44e96be2020-08-31 13:16:04 -0400396 const PrefixExpression& p = expression.as<PrefixExpression>();
Ethan Nicholas444ccc62020-10-09 10:16:22 -0400397 return std::make_unique<PrefixExpression>(p.getOperator(), expr(p.operand()));
John Stiles44e96be2020-08-31 13:16:04 -0400398 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400399 case Expression::Kind::kPostfix: {
John Stiles44e96be2020-08-31 13:16:04 -0400400 const PostfixExpression& p = expression.as<PostfixExpression>();
Ethan Nicholas444ccc62020-10-09 10:16:22 -0400401 return std::make_unique<PostfixExpression>(expr(p.operand()), p.getOperator());
John Stiles44e96be2020-08-31 13:16:04 -0400402 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400403 case Expression::Kind::kSetting:
John Stiles44e96be2020-08-31 13:16:04 -0400404 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400405 case Expression::Kind::kSwizzle: {
John Stiles44e96be2020-08-31 13:16:04 -0400406 const Swizzle& s = expression.as<Swizzle>();
Ethan Nicholas6b4d5812020-10-12 16:11:51 -0400407 return std::make_unique<Swizzle>(*fContext, expr(s.base()), s.components());
John Stiles44e96be2020-08-31 13:16:04 -0400408 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400409 case Expression::Kind::kTernary: {
John Stiles44e96be2020-08-31 13:16:04 -0400410 const TernaryExpression& t = expression.as<TernaryExpression>();
Ethan Nicholasdd218162020-10-08 05:48:01 -0400411 return std::make_unique<TernaryExpression>(offset, expr(t.test()),
412 expr(t.ifTrue()), expr(t.ifFalse()));
John Stiles44e96be2020-08-31 13:16:04 -0400413 }
Brian Osman83ba9302020-09-11 13:33:46 -0400414 case Expression::Kind::kTypeReference:
415 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400416 case Expression::Kind::kVariableReference: {
John Stiles44e96be2020-08-31 13:16:04 -0400417 const VariableReference& v = expression.as<VariableReference>();
Ethan Nicholas78686922020-10-08 06:46:27 -0400418 auto varMapIter = varMap->find(v.variable());
John Stilese41b4ee2020-09-28 12:28:16 -0400419 if (varMapIter != varMap->end()) {
Ethan Nicholas78686922020-10-08 06:46:27 -0400420 return clone_with_ref_kind(*varMapIter->second, v.refKind());
John Stiles44e96be2020-08-31 13:16:04 -0400421 }
422 return v.clone();
423 }
424 default:
425 SkASSERT(false);
426 return nullptr;
427 }
428}
429
430std::unique_ptr<Statement> Inliner::inlineStatement(int offset,
431 VariableRewriteMap* varMap,
432 SymbolTable* symbolTableForStatement,
John Stiles9e948122020-12-16 18:24:48 +0000433 const Expression* resultExpr,
434 bool haveEarlyReturns,
Brian Osman3887a012020-09-30 13:22:27 -0400435 const Statement& statement,
436 bool isBuiltinCode) {
John Stiles44e96be2020-08-31 13:16:04 -0400437 auto stmt = [&](const std::unique_ptr<Statement>& s) -> std::unique_ptr<Statement> {
438 if (s) {
John Stilesa5f3c312020-09-22 12:05:16 -0400439 return this->inlineStatement(offset, varMap, symbolTableForStatement, resultExpr,
John Stiles9e948122020-12-16 18:24:48 +0000440 haveEarlyReturns, *s, isBuiltinCode);
John Stiles44e96be2020-08-31 13:16:04 -0400441 }
442 return nullptr;
443 };
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400444 auto blockStmts = [&](const Block& block) {
John Stiles8f2a0cf2020-10-13 12:48:21 -0400445 StatementArray result;
John Stilesf4bda742020-10-14 16:57:41 -0400446 result.reserve_back(block.children().size());
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400447 for (const std::unique_ptr<Statement>& child : block.children()) {
448 result.push_back(stmt(child));
449 }
450 return result;
451 };
John Stiles8f2a0cf2020-10-13 12:48:21 -0400452 auto stmts = [&](const StatementArray& ss) {
453 StatementArray result;
John Stilesf4bda742020-10-14 16:57:41 -0400454 result.reserve_back(ss.size());
John Stiles44e96be2020-08-31 13:16:04 -0400455 for (const auto& s : ss) {
456 result.push_back(stmt(s));
457 }
458 return result;
459 };
460 auto expr = [&](const std::unique_ptr<Expression>& e) -> std::unique_ptr<Expression> {
461 if (e) {
John Stilesd7cc0932020-11-30 12:24:27 -0500462 return this->inlineExpression(offset, varMap, symbolTableForStatement, *e);
John Stiles44e96be2020-08-31 13:16:04 -0400463 }
464 return nullptr;
465 };
John Stiles031a7672020-11-13 16:13:18 -0500466
467 ++fInlinedStatementCounter;
468
Ethan Nicholase6592142020-09-08 10:22:09 -0400469 switch (statement.kind()) {
470 case Statement::Kind::kBlock: {
John Stiles44e96be2020-08-31 13:16:04 -0400471 const Block& b = statement.as<Block>();
John Stilesa1e2b412020-10-20 14:51:28 -0400472 return std::make_unique<Block>(offset, blockStmts(b),
473 SymbolTable::WrapIfBuiltin(b.symbolTable()),
474 b.isScope());
John Stiles44e96be2020-08-31 13:16:04 -0400475 }
476
Ethan Nicholase6592142020-09-08 10:22:09 -0400477 case Statement::Kind::kBreak:
478 case Statement::Kind::kContinue:
479 case Statement::Kind::kDiscard:
John Stiles44e96be2020-08-31 13:16:04 -0400480 return statement.clone();
481
Ethan Nicholase6592142020-09-08 10:22:09 -0400482 case Statement::Kind::kDo: {
John Stiles44e96be2020-08-31 13:16:04 -0400483 const DoStatement& d = statement.as<DoStatement>();
Ethan Nicholas1fd61162020-09-28 13:14:19 -0400484 return std::make_unique<DoStatement>(offset, stmt(d.statement()), expr(d.test()));
John Stiles44e96be2020-08-31 13:16:04 -0400485 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400486 case Statement::Kind::kExpression: {
John Stiles44e96be2020-08-31 13:16:04 -0400487 const ExpressionStatement& e = statement.as<ExpressionStatement>();
Ethan Nicholasd503a5a2020-09-30 09:29:55 -0400488 return std::make_unique<ExpressionStatement>(expr(e.expression()));
John Stiles44e96be2020-08-31 13:16:04 -0400489 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400490 case Statement::Kind::kFor: {
John Stiles44e96be2020-08-31 13:16:04 -0400491 const ForStatement& f = statement.as<ForStatement>();
492 // need to ensure initializer is evaluated first so that we've already remapped its
493 // declarations by the time we evaluate test & next
Ethan Nicholas0d31ed52020-10-05 14:47:09 -0400494 std::unique_ptr<Statement> initializer = stmt(f.initializer());
495 return std::make_unique<ForStatement>(offset, std::move(initializer), expr(f.test()),
John Stilesa1e2b412020-10-20 14:51:28 -0400496 expr(f.next()), stmt(f.statement()),
497 SymbolTable::WrapIfBuiltin(f.symbols()));
John Stiles44e96be2020-08-31 13:16:04 -0400498 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400499 case Statement::Kind::kIf: {
John Stiles44e96be2020-08-31 13:16:04 -0400500 const IfStatement& i = statement.as<IfStatement>();
Ethan Nicholas8c44eca2020-10-07 16:47:09 -0400501 return std::make_unique<IfStatement>(offset, i.isStatic(), expr(i.test()),
502 stmt(i.ifTrue()), stmt(i.ifFalse()));
John Stiles44e96be2020-08-31 13:16:04 -0400503 }
John Stiles98c1f822020-09-09 14:18:53 -0400504 case Statement::Kind::kInlineMarker:
Ethan Nicholase6592142020-09-08 10:22:09 -0400505 case Statement::Kind::kNop:
John Stiles44e96be2020-08-31 13:16:04 -0400506 return statement.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400507 case Statement::Kind::kReturn: {
John Stiles44e96be2020-08-31 13:16:04 -0400508 const ReturnStatement& r = statement.as<ReturnStatement>();
John Stiles9e948122020-12-16 18:24:48 +0000509 if (r.expression()) {
510 SkASSERT(resultExpr);
511 auto assignment =
512 std::make_unique<ExpressionStatement>(std::make_unique<BinaryExpression>(
513 offset,
514 clone_with_ref_kind(*resultExpr,
515 VariableReference::RefKind::kWrite),
516 Token::Kind::TK_EQ,
517 expr(r.expression()),
518 &resultExpr->type()));
519 if (haveEarlyReturns) {
520 StatementArray block;
521 block.reserve_back(2);
522 block.push_back(std::move(assignment));
523 block.push_back(std::make_unique<BreakStatement>(offset));
524 return std::make_unique<Block>(offset, std::move(block), /*symbols=*/nullptr,
525 /*isScope=*/true);
526 } else {
527 return std::move(assignment);
528 }
529 } else {
530 if (haveEarlyReturns) {
John Stiles44e96be2020-08-31 13:16:04 -0400531 return std::make_unique<BreakStatement>(offset);
532 } else {
533 return std::make_unique<Nop>();
534 }
535 }
536 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400537 case Statement::Kind::kSwitch: {
John Stiles44e96be2020-08-31 13:16:04 -0400538 const SwitchStatement& ss = statement.as<SwitchStatement>();
539 std::vector<std::unique_ptr<SwitchCase>> cases;
John Stiles2d4f9592020-10-30 10:29:12 -0400540 cases.reserve(ss.cases().size());
541 for (const std::unique_ptr<SwitchCase>& sc : ss.cases()) {
542 cases.push_back(std::make_unique<SwitchCase>(offset, expr(sc->value()),
543 stmts(sc->statements())));
John Stiles44e96be2020-08-31 13:16:04 -0400544 }
Ethan Nicholas01b05e52020-10-22 15:53:41 -0400545 return std::make_unique<SwitchStatement>(offset, ss.isStatic(), expr(ss.value()),
John Stilesa1e2b412020-10-20 14:51:28 -0400546 std::move(cases),
Ethan Nicholas01b05e52020-10-22 15:53:41 -0400547 SymbolTable::WrapIfBuiltin(ss.symbols()));
John Stiles44e96be2020-08-31 13:16:04 -0400548 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400549 case Statement::Kind::kVarDeclaration: {
John Stiles44e96be2020-08-31 13:16:04 -0400550 const VarDeclaration& decl = statement.as<VarDeclaration>();
John Stiles35fee4c2020-12-16 18:25:14 +0000551 std::unique_ptr<Expression> initialValue = expr(decl.value());
552 int arraySize = decl.arraySize();
553 const Variable& old = decl.var();
554 // We assign unique names to inlined variables--scopes hide most of the problems in this
555 // regard, but see `InlinerAvoidsVariableNameOverlap` for a counterexample where unique
556 // names are important.
557 auto name = std::make_unique<String>(
558 this->uniqueNameForInlineVar(String(old.name()), symbolTableForStatement));
559 const String* namePtr = symbolTableForStatement->takeOwnershipOfString(std::move(name));
560 const Type* baseTypePtr = copy_if_needed(&decl.baseType(), *symbolTableForStatement);
561 const Type* typePtr = copy_if_needed(&old.type(), *symbolTableForStatement);
562 const Variable* clone = symbolTableForStatement->takeOwnershipOfSymbol(
563 std::make_unique<Variable>(offset,
564 &old.modifiers(),
565 namePtr->c_str(),
566 typePtr,
567 isBuiltinCode,
568 old.storage(),
569 initialValue.get()));
570 (*varMap)[&old] = std::make_unique<VariableReference>(offset, clone);
571 return std::make_unique<VarDeclaration>(clone, baseTypePtr, arraySize,
572 std::move(initialValue));
John Stiles44e96be2020-08-31 13:16:04 -0400573 }
John Stiles44e96be2020-08-31 13:16:04 -0400574 default:
575 SkASSERT(false);
576 return nullptr;
577 }
578}
579
John Stiles6eadf132020-09-08 10:16:10 -0400580Inliner::InlinedCall Inliner::inlineCall(FunctionCall* call,
John Stiles78047582020-12-16 16:17:41 -0500581 std::shared_ptr<SymbolTable> symbolTable,
Brian Osman3887a012020-09-30 13:22:27 -0400582 const FunctionDeclaration* caller) {
John Stiles44e96be2020-08-31 13:16:04 -0400583 // Inlining is more complicated here than in a typical compiler, because we have to have a
584 // high-level IR and can't just drop statements into the middle of an expression or even use
585 // gotos.
586 //
587 // Since we can't insert statements into an expression, we run the inline function as extra
588 // statements before the statement we're currently processing, relying on a lack of execution
589 // order guarantees. Since we can't use gotos (which are normally used to replace return
590 // statements), we wrap the whole function in a loop and use break statements to jump to the
591 // end.
592 SkASSERT(fSettings);
593 SkASSERT(fContext);
594 SkASSERT(call);
Ethan Nicholased84b732020-10-08 11:45:44 -0400595 SkASSERT(this->isSafeToInline(call->function().definition()));
John Stiles44e96be2020-08-31 13:16:04 -0400596
John Stiles8e3b6be2020-10-13 11:14:08 -0400597 ExpressionArray& arguments = call->arguments();
John Stiles6eadf132020-09-08 10:16:10 -0400598 const int offset = call->fOffset;
Ethan Nicholased84b732020-10-08 11:45:44 -0400599 const FunctionDefinition& function = *call->function().definition();
John Stiles9e948122020-12-16 18:24:48 +0000600 const bool hasEarlyReturn = has_early_return(function);
John Stiles6eadf132020-09-08 10:16:10 -0400601
John Stiles44e96be2020-08-31 13:16:04 -0400602 InlinedCall inlinedCall;
John Stiles8f2a0cf2020-10-13 12:48:21 -0400603 inlinedCall.fInlinedBody = std::make_unique<Block>(offset, StatementArray{},
John Stiles6eadf132020-09-08 10:16:10 -0400604 /*symbols=*/nullptr,
605 /*isScope=*/false);
John Stiles98c1f822020-09-09 14:18:53 -0400606
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400607 Block& inlinedBody = *inlinedCall.fInlinedBody;
John Stiles82f373c2020-10-20 13:58:05 -0400608 inlinedBody.children().reserve_back(
609 1 + // Inline marker
610 1 + // Result variable
611 arguments.size() + // Function arguments (passing in)
612 arguments.size() + // Function arguments (copy out-params back)
613 1); // Inlined code (Block or do-while loop)
John Stiles98c1f822020-09-09 14:18:53 -0400614
Ethan Nicholasceb62142020-10-09 16:51:18 -0400615 inlinedBody.children().push_back(std::make_unique<InlineMarker>(&call->function()));
John Stiles44e96be2020-08-31 13:16:04 -0400616
John Stilese41b4ee2020-09-28 12:28:16 -0400617 auto makeInlineVar =
618 [&](const String& baseName, const Type* type, Modifiers modifiers,
619 std::unique_ptr<Expression>* initialValue) -> std::unique_ptr<Expression> {
John Stilesa003e812020-09-11 09:43:49 -0400620 // $floatLiteral or $intLiteral aren't real types that we can use for scratch variables, so
621 // replace them if they ever appear here. If this happens, we likely forgot to coerce a type
622 // somewhere during compilation.
623 if (type == fContext->fFloatLiteral_Type.get()) {
John Stilesd2be5c52020-09-11 14:58:06 -0400624 SkDEBUGFAIL("found a $floatLiteral type while inlining");
John Stilesa003e812020-09-11 09:43:49 -0400625 type = fContext->fFloat_Type.get();
626 } else if (type == fContext->fIntLiteral_Type.get()) {
John Stilesd2be5c52020-09-11 14:58:06 -0400627 SkDEBUGFAIL("found an $intLiteral type while inlining");
John Stilesa003e812020-09-11 09:43:49 -0400628 type = fContext->fInt_Type.get();
629 }
630
John Stilesc75abb82020-09-14 18:24:12 -0400631 // Provide our new variable with a unique name, and add it to our symbol table.
John Stiles78047582020-12-16 16:17:41 -0500632 const String* namePtr = symbolTable->takeOwnershipOfString(std::make_unique<String>(
633 this->uniqueNameForInlineVar(baseName, symbolTable.get())));
John Stiles44e96be2020-08-31 13:16:04 -0400634 StringFragment nameFrag{namePtr->c_str(), namePtr->length()};
635
636 // Add our new variable to the symbol table.
John Stiles78047582020-12-16 16:17:41 -0500637 const Variable* variableSymbol = symbolTable->add(std::make_unique<Variable>(
John Stiles586df952020-11-12 18:27:13 -0500638 /*offset=*/-1, fModifiers->addToPool(Modifiers()),
Ethan Nicholased84b732020-10-08 11:45:44 -0400639 nameFrag, type, caller->isBuiltin(),
Ethan Nicholas453f67f2020-10-09 10:43:45 -0400640 Variable::Storage::kLocal, initialValue->get()));
John Stiles44e96be2020-08-31 13:16:04 -0400641
642 // Prepare the variable declaration (taking extra care with `out` params to not clobber any
643 // initial value).
Brian Osmanc0213602020-10-06 14:43:32 -0400644 std::unique_ptr<Statement> variable;
John Stiles44e96be2020-08-31 13:16:04 -0400645 if (initialValue && (modifiers.fFlags & Modifiers::kOut_Flag)) {
John Stiles62a56462020-12-03 10:41:58 -0500646 variable = std::make_unique<VarDeclaration>(variableSymbol, type, /*arraySize=*/0,
647 (*initialValue)->clone());
John Stiles44e96be2020-08-31 13:16:04 -0400648 } else {
John Stiles62a56462020-12-03 10:41:58 -0500649 variable = std::make_unique<VarDeclaration>(variableSymbol, type, /*arraySize=*/0,
650 std::move(*initialValue));
John Stiles44e96be2020-08-31 13:16:04 -0400651 }
652
653 // Add the new variable-declaration statement to our block of extra statements.
Brian Osmanc0213602020-10-06 14:43:32 -0400654 inlinedBody.children().push_back(std::move(variable));
John Stiles44e96be2020-08-31 13:16:04 -0400655
John Stilese41b4ee2020-09-28 12:28:16 -0400656 return std::make_unique<VariableReference>(offset, variableSymbol);
John Stiles44e96be2020-08-31 13:16:04 -0400657 };
658
659 // Create a variable to hold the result in the extra statements (excepting void).
John Stilese41b4ee2020-09-28 12:28:16 -0400660 std::unique_ptr<Expression> resultExpr;
Ethan Nicholas0a5d0962020-10-14 13:33:18 -0400661 if (function.declaration().returnType() != *fContext->fVoid_Type) {
John Stiles44e96be2020-08-31 13:16:04 -0400662 std::unique_ptr<Expression> noInitialValue;
Ethan Nicholas0a5d0962020-10-14 13:33:18 -0400663 resultExpr = makeInlineVar(String(function.declaration().name()),
664 &function.declaration().returnType(),
John Stilese41b4ee2020-09-28 12:28:16 -0400665 Modifiers{}, &noInitialValue);
John Stiles35fee4c2020-12-16 18:25:14 +0000666 }
John Stiles44e96be2020-08-31 13:16:04 -0400667
668 // Create variables in the extra statements to hold the arguments, and assign the arguments to
669 // them.
670 VariableRewriteMap varMap;
John Stilese41b4ee2020-09-28 12:28:16 -0400671 std::vector<int> argsToCopyBack;
John Stiles44e96be2020-08-31 13:16:04 -0400672 for (int i = 0; i < (int) arguments.size(); ++i) {
Ethan Nicholas0a5d0962020-10-14 13:33:18 -0400673 const Variable* param = function.declaration().parameters()[i];
Ethan Nicholas041fd0a2020-10-07 16:42:04 -0400674 bool isOutParam = param->modifiers().fFlags & Modifiers::kOut_Flag;
John Stiles44e96be2020-08-31 13:16:04 -0400675
John Stiles44733aa2020-09-29 17:42:23 -0400676 // If this argument can be inlined trivially (e.g. a swizzle, or a constant array index)...
John Stilesc30fbca2020-11-19 16:25:49 -0500677 if (Analysis::IsTrivialExpression(*arguments[i])) {
John Stilese41b4ee2020-09-28 12:28:16 -0400678 // ... and it's an `out` param, or it isn't written to within the inline function...
Ethan Nicholas0a5d0962020-10-14 13:33:18 -0400679 if (isOutParam || !Analysis::StatementWritesToVariable(*function.body(), *param)) {
John Stilesf201af82020-09-29 16:57:55 -0400680 // ... we don't need to copy it at all! We can just use the existing expression.
681 varMap[param] = arguments[i]->clone();
John Stiles44e96be2020-08-31 13:16:04 -0400682 continue;
683 }
684 }
685
John Stilese41b4ee2020-09-28 12:28:16 -0400686 if (isOutParam) {
687 argsToCopyBack.push_back(i);
688 }
689
Ethan Nicholase2c49992020-10-05 11:49:11 -0400690 varMap[param] = makeInlineVar(String(param->name()), &arguments[i]->type(),
Ethan Nicholas041fd0a2020-10-07 16:42:04 -0400691 param->modifiers(), &arguments[i]);
John Stiles44e96be2020-08-31 13:16:04 -0400692 }
693
Ethan Nicholas0a5d0962020-10-14 13:33:18 -0400694 const Block& body = function.body()->as<Block>();
John Stilesd0590052020-12-15 15:21:03 -0500695 auto inlineBlock = std::make_unique<Block>(offset, StatementArray{},
696 /*symbols=*/nullptr, /*isScope=*/hasEarlyReturn);
John Stilesf4bda742020-10-14 16:57:41 -0400697 inlineBlock->children().reserve_back(body.children().size());
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400698 for (const std::unique_ptr<Statement>& stmt : body.children()) {
John Stiles78047582020-12-16 16:17:41 -0500699 inlineBlock->children().push_back(this->inlineStatement(offset, &varMap, symbolTable.get(),
John Stiles9e948122020-12-16 18:24:48 +0000700 resultExpr.get(), hasEarlyReturn,
Ethan Nicholased84b732020-10-08 11:45:44 -0400701 *stmt, caller->isBuiltin()));
John Stiles44e96be2020-08-31 13:16:04 -0400702 }
703 if (hasEarlyReturn) {
704 // Since we output to backends that don't have a goto statement (which would normally be
705 // used to perform an early return), we fake it by wrapping the function in a
706 // do { } while (false); and then use break statements to jump to the end in order to
707 // emulate a goto.
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400708 inlinedBody.children().push_back(std::make_unique<DoStatement>(
John Stiles44e96be2020-08-31 13:16:04 -0400709 /*offset=*/-1,
710 std::move(inlineBlock),
711 std::make_unique<BoolLiteral>(*fContext, offset, /*value=*/false)));
712 } else {
John Stiles6eadf132020-09-08 10:16:10 -0400713 // No early returns, so we can just dump the code in. We still need to keep the block so we
714 // don't get name conflicts with locals.
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400715 inlinedBody.children().push_back(std::move(inlineBlock));
John Stiles44e96be2020-08-31 13:16:04 -0400716 }
717
John Stilese41b4ee2020-09-28 12:28:16 -0400718 // Copy back the values of `out` parameters into their real destinations.
719 for (int i : argsToCopyBack) {
Ethan Nicholas0a5d0962020-10-14 13:33:18 -0400720 const Variable* p = function.declaration().parameters()[i];
John Stilese41b4ee2020-09-28 12:28:16 -0400721 SkASSERT(varMap.find(p) != varMap.end());
722 inlinedBody.children().push_back(
723 std::make_unique<ExpressionStatement>(std::make_unique<BinaryExpression>(
724 offset,
Ethan Nicholas453f67f2020-10-09 10:43:45 -0400725 clone_with_ref_kind(*arguments[i], VariableReference::RefKind::kWrite),
John Stilese41b4ee2020-09-28 12:28:16 -0400726 Token::Kind::TK_EQ,
727 std::move(varMap[p]),
728 &arguments[i]->type())));
John Stiles44e96be2020-08-31 13:16:04 -0400729 }
730
John Stilese41b4ee2020-09-28 12:28:16 -0400731 if (resultExpr != nullptr) {
732 // Return our result variable as our replacement expression.
John Stiles9e948122020-12-16 18:24:48 +0000733 SkASSERT(resultExpr->as<VariableReference>().refKind() ==
734 VariableReference::RefKind::kRead);
John Stilese41b4ee2020-09-28 12:28:16 -0400735 inlinedCall.fReplacementExpr = std::move(resultExpr);
John Stiles44e96be2020-08-31 13:16:04 -0400736 } else {
737 // It's a void function, so it doesn't actually result in anything, but we have to return
738 // something non-null as a standin.
Ethan Nicholas041fd0a2020-10-07 16:42:04 -0400739 inlinedCall.fReplacementExpr = std::make_unique<BoolLiteral>(*fContext,
740 offset,
John Stiles44e96be2020-08-31 13:16:04 -0400741 /*value=*/false);
742 }
743
John Stiles44e96be2020-08-31 13:16:04 -0400744 return inlinedCall;
745}
746
John Stiles2d7973a2020-10-02 15:01:03 -0400747bool Inliner::isSafeToInline(const FunctionDefinition* functionDef) {
John Stiles44e96be2020-08-31 13:16:04 -0400748 SkASSERT(fSettings);
749
John Stiles1c03d332020-10-13 10:30:23 -0400750 // A threshold of zero indicates that the inliner is completely disabled, so we can just return.
751 if (fSettings->fInlineThreshold <= 0) {
752 return false;
753 }
754
John Stiles031a7672020-11-13 16:13:18 -0500755 // Enforce a limit on inlining to avoid pathological cases. (inliner/ExponentialGrowth.sksl)
756 if (fInlinedStatementCounter >= kInlinedStatementLimit) {
757 return false;
758 }
759
John Stiles2d7973a2020-10-02 15:01:03 -0400760 if (functionDef == nullptr) {
John Stiles44e96be2020-08-31 13:16:04 -0400761 // Can't inline something if we don't actually have its definition.
762 return false;
763 }
John Stiles2d7973a2020-10-02 15:01:03 -0400764
John Stiles345d7212020-12-15 18:06:29 -0500765 if (!fCaps || !fCaps->canUseDoLoops()) {
John Stiles9e948122020-12-16 18:24:48 +0000766 // We don't have do-while loops. We use do-while loops to simulate early returns, so we
767 // can't inline functions that have an early return.
768 bool hasEarlyReturn = has_early_return(*functionDef);
769
John Stiles44e96be2020-08-31 13:16:04 -0400770 // If we didn't detect an early return, there shouldn't be any returns in breakable
771 // constructs either.
John Stiles2d7973a2020-10-02 15:01:03 -0400772 SkASSERT(hasEarlyReturn || count_returns_in_breakable_constructs(*functionDef) == 0);
John Stiles44e96be2020-08-31 13:16:04 -0400773 return !hasEarlyReturn;
774 }
775 // We have do-while loops, but we don't have any mechanism to simulate early returns within a
776 // breakable construct (switch/for/do/while), so we can't inline if there's a return inside one.
John Stiles2d7973a2020-10-02 15:01:03 -0400777 bool hasReturnInBreakableConstruct = (count_returns_in_breakable_constructs(*functionDef) > 0);
John Stiles44e96be2020-08-31 13:16:04 -0400778
779 // If we detected returns in breakable constructs, we should also detect an early return.
John Stiles9e948122020-12-16 18:24:48 +0000780 SkASSERT(!hasReturnInBreakableConstruct || has_early_return(*functionDef));
John Stiles44e96be2020-08-31 13:16:04 -0400781 return !hasReturnInBreakableConstruct;
782}
783
John Stiles2d7973a2020-10-02 15:01:03 -0400784// A candidate function for inlining, containing everything that `inlineCall` needs.
785struct InlineCandidate {
John Stiles78047582020-12-16 16:17:41 -0500786 std::shared_ptr<SymbolTable> fSymbols; // the SymbolTable of the candidate
John Stiles2d7973a2020-10-02 15:01:03 -0400787 std::unique_ptr<Statement>* fParentStmt; // the parent Statement of the enclosing stmt
788 std::unique_ptr<Statement>* fEnclosingStmt; // the Statement containing the candidate
789 std::unique_ptr<Expression>* fCandidateExpr; // the candidate FunctionCall to be inlined
790 FunctionDefinition* fEnclosingFunction; // the Function containing the candidate
John Stiles2d7973a2020-10-02 15:01:03 -0400791};
John Stiles93442622020-09-11 12:11:27 -0400792
John Stiles2d7973a2020-10-02 15:01:03 -0400793struct InlineCandidateList {
794 std::vector<InlineCandidate> fCandidates;
795};
796
797class InlineCandidateAnalyzer {
John Stiles70957c82020-10-02 16:42:10 -0400798public:
799 // A list of all the inlining candidates we found during analysis.
800 InlineCandidateList* fCandidateList;
John Stiles2d7973a2020-10-02 15:01:03 -0400801
John Stiles70957c82020-10-02 16:42:10 -0400802 // A stack of the symbol tables; since most nodes don't have one, expected to be shallower than
803 // the enclosing-statement stack.
John Stiles78047582020-12-16 16:17:41 -0500804 std::vector<std::shared_ptr<SymbolTable>> fSymbolTableStack;
John Stiles70957c82020-10-02 16:42:10 -0400805 // A stack of "enclosing" statements--these would be suitable for the inliner to use for adding
806 // new instructions. Not all statements are suitable (e.g. a for-loop's initializer). The
807 // inliner might replace a statement with a block containing the statement.
808 std::vector<std::unique_ptr<Statement>*> fEnclosingStmtStack;
809 // The function that we're currently processing (i.e. inlining into).
810 FunctionDefinition* fEnclosingFunction = nullptr;
John Stiles93442622020-09-11 12:11:27 -0400811
Brian Osman0006ad02020-11-18 15:38:39 -0500812 void visit(const std::vector<std::unique_ptr<ProgramElement>>& elements,
John Stiles78047582020-12-16 16:17:41 -0500813 std::shared_ptr<SymbolTable> symbols,
Brian Osman0006ad02020-11-18 15:38:39 -0500814 InlineCandidateList* candidateList) {
John Stiles70957c82020-10-02 16:42:10 -0400815 fCandidateList = candidateList;
Brian Osman0006ad02020-11-18 15:38:39 -0500816 fSymbolTableStack.push_back(symbols);
John Stiles93442622020-09-11 12:11:27 -0400817
Brian Osman0006ad02020-11-18 15:38:39 -0500818 for (const std::unique_ptr<ProgramElement>& pe : elements) {
Brian Osman1179fcf2020-10-08 16:04:40 -0400819 this->visitProgramElement(pe.get());
John Stiles93442622020-09-11 12:11:27 -0400820 }
821
John Stiles70957c82020-10-02 16:42:10 -0400822 fSymbolTableStack.pop_back();
823 fCandidateList = nullptr;
824 }
825
826 void visitProgramElement(ProgramElement* pe) {
827 switch (pe->kind()) {
828 case ProgramElement::Kind::kFunction: {
829 FunctionDefinition& funcDef = pe->as<FunctionDefinition>();
Brian Osman0006ad02020-11-18 15:38:39 -0500830 fEnclosingFunction = &funcDef;
831 this->visitStatement(&funcDef.body());
John Stiles70957c82020-10-02 16:42:10 -0400832 break;
John Stiles93442622020-09-11 12:11:27 -0400833 }
John Stiles70957c82020-10-02 16:42:10 -0400834 default:
835 // The inliner can't operate outside of a function's scope.
836 break;
837 }
838 }
839
840 void visitStatement(std::unique_ptr<Statement>* stmt,
841 bool isViableAsEnclosingStatement = true) {
842 if (!*stmt) {
843 return;
John Stiles93442622020-09-11 12:11:27 -0400844 }
845
John Stiles70957c82020-10-02 16:42:10 -0400846 size_t oldEnclosingStmtStackSize = fEnclosingStmtStack.size();
847 size_t oldSymbolStackSize = fSymbolTableStack.size();
John Stiles93442622020-09-11 12:11:27 -0400848
John Stiles70957c82020-10-02 16:42:10 -0400849 if (isViableAsEnclosingStatement) {
850 fEnclosingStmtStack.push_back(stmt);
John Stiles93442622020-09-11 12:11:27 -0400851 }
852
John Stiles70957c82020-10-02 16:42:10 -0400853 switch ((*stmt)->kind()) {
854 case Statement::Kind::kBreak:
855 case Statement::Kind::kContinue:
856 case Statement::Kind::kDiscard:
857 case Statement::Kind::kInlineMarker:
858 case Statement::Kind::kNop:
859 break;
860
861 case Statement::Kind::kBlock: {
862 Block& block = (*stmt)->as<Block>();
863 if (block.symbolTable()) {
John Stiles78047582020-12-16 16:17:41 -0500864 fSymbolTableStack.push_back(block.symbolTable());
John Stiles70957c82020-10-02 16:42:10 -0400865 }
866
867 for (std::unique_ptr<Statement>& stmt : block.children()) {
868 this->visitStatement(&stmt);
869 }
870 break;
John Stiles93442622020-09-11 12:11:27 -0400871 }
John Stiles70957c82020-10-02 16:42:10 -0400872 case Statement::Kind::kDo: {
873 DoStatement& doStmt = (*stmt)->as<DoStatement>();
874 // The loop body is a candidate for inlining.
875 this->visitStatement(&doStmt.statement());
876 // The inliner isn't smart enough to inline the test-expression for a do-while
877 // loop at this time. There are two limitations:
878 // - We would need to insert the inlined-body block at the very end of the do-
879 // statement's inner fStatement. We don't support that today, but it's doable.
880 // - We cannot inline the test expression if the loop uses `continue` anywhere; that
881 // would skip over the inlined block that evaluates the test expression. There
882 // isn't a good fix for this--any workaround would be more complex than the cost
883 // of a function call. However, loops that don't use `continue` would still be
884 // viable candidates for inlining.
885 break;
John Stiles93442622020-09-11 12:11:27 -0400886 }
John Stiles70957c82020-10-02 16:42:10 -0400887 case Statement::Kind::kExpression: {
888 ExpressionStatement& expr = (*stmt)->as<ExpressionStatement>();
889 this->visitExpression(&expr.expression());
890 break;
891 }
892 case Statement::Kind::kFor: {
893 ForStatement& forStmt = (*stmt)->as<ForStatement>();
Ethan Nicholas0d31ed52020-10-05 14:47:09 -0400894 if (forStmt.symbols()) {
John Stiles78047582020-12-16 16:17:41 -0500895 fSymbolTableStack.push_back(forStmt.symbols());
John Stiles70957c82020-10-02 16:42:10 -0400896 }
897
898 // The initializer and loop body are candidates for inlining.
Ethan Nicholas0d31ed52020-10-05 14:47:09 -0400899 this->visitStatement(&forStmt.initializer(),
John Stiles70957c82020-10-02 16:42:10 -0400900 /*isViableAsEnclosingStatement=*/false);
Ethan Nicholas0d31ed52020-10-05 14:47:09 -0400901 this->visitStatement(&forStmt.statement());
John Stiles70957c82020-10-02 16:42:10 -0400902
903 // The inliner isn't smart enough to inline the test- or increment-expressions
904 // of a for loop loop at this time. There are a handful of limitations:
905 // - We would need to insert the test-expression block at the very beginning of the
906 // for-loop's inner fStatement, and the increment-expression block at the very
907 // end. We don't support that today, but it's doable.
908 // - The for-loop's built-in test-expression would need to be dropped entirely,
909 // and the loop would be halted via a break statement at the end of the inlined
910 // test-expression. This is again something we don't support today, but it could
911 // be implemented.
912 // - We cannot inline the increment-expression if the loop uses `continue` anywhere;
913 // that would skip over the inlined block that evaluates the increment expression.
914 // There isn't a good fix for this--any workaround would be more complex than the
915 // cost of a function call. However, loops that don't use `continue` would still
916 // be viable candidates for increment-expression inlining.
917 break;
918 }
919 case Statement::Kind::kIf: {
920 IfStatement& ifStmt = (*stmt)->as<IfStatement>();
Ethan Nicholas8c44eca2020-10-07 16:47:09 -0400921 this->visitExpression(&ifStmt.test());
922 this->visitStatement(&ifStmt.ifTrue());
923 this->visitStatement(&ifStmt.ifFalse());
John Stiles70957c82020-10-02 16:42:10 -0400924 break;
925 }
926 case Statement::Kind::kReturn: {
927 ReturnStatement& returnStmt = (*stmt)->as<ReturnStatement>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -0400928 this->visitExpression(&returnStmt.expression());
John Stiles70957c82020-10-02 16:42:10 -0400929 break;
930 }
931 case Statement::Kind::kSwitch: {
932 SwitchStatement& switchStmt = (*stmt)->as<SwitchStatement>();
Ethan Nicholas01b05e52020-10-22 15:53:41 -0400933 if (switchStmt.symbols()) {
John Stiles78047582020-12-16 16:17:41 -0500934 fSymbolTableStack.push_back(switchStmt.symbols());
John Stiles70957c82020-10-02 16:42:10 -0400935 }
936
Ethan Nicholas01b05e52020-10-22 15:53:41 -0400937 this->visitExpression(&switchStmt.value());
John Stiles2d4f9592020-10-30 10:29:12 -0400938 for (const std::unique_ptr<SwitchCase>& switchCase : switchStmt.cases()) {
John Stiles70957c82020-10-02 16:42:10 -0400939 // The switch-case's fValue cannot be a FunctionCall; skip it.
John Stiles2d4f9592020-10-30 10:29:12 -0400940 for (std::unique_ptr<Statement>& caseBlock : switchCase->statements()) {
John Stiles70957c82020-10-02 16:42:10 -0400941 this->visitStatement(&caseBlock);
942 }
943 }
944 break;
945 }
946 case Statement::Kind::kVarDeclaration: {
947 VarDeclaration& varDeclStmt = (*stmt)->as<VarDeclaration>();
948 // Don't need to scan the declaration's sizes; those are always IntLiterals.
Ethan Nicholasc51f33e2020-10-13 13:49:44 -0400949 this->visitExpression(&varDeclStmt.value());
John Stiles70957c82020-10-02 16:42:10 -0400950 break;
951 }
John Stiles70957c82020-10-02 16:42:10 -0400952 default:
953 SkUNREACHABLE;
John Stiles93442622020-09-11 12:11:27 -0400954 }
955
John Stiles70957c82020-10-02 16:42:10 -0400956 // Pop our symbol and enclosing-statement stacks.
957 fSymbolTableStack.resize(oldSymbolStackSize);
958 fEnclosingStmtStack.resize(oldEnclosingStmtStackSize);
959 }
960
961 void visitExpression(std::unique_ptr<Expression>* expr) {
962 if (!*expr) {
963 return;
John Stiles93442622020-09-11 12:11:27 -0400964 }
John Stiles70957c82020-10-02 16:42:10 -0400965
966 switch ((*expr)->kind()) {
967 case Expression::Kind::kBoolLiteral:
968 case Expression::Kind::kDefined:
969 case Expression::Kind::kExternalValue:
970 case Expression::Kind::kFieldAccess:
971 case Expression::Kind::kFloatLiteral:
972 case Expression::Kind::kFunctionReference:
973 case Expression::Kind::kIntLiteral:
974 case Expression::Kind::kNullLiteral:
975 case Expression::Kind::kSetting:
976 case Expression::Kind::kTypeReference:
977 case Expression::Kind::kVariableReference:
978 // Nothing to scan here.
979 break;
980
981 case Expression::Kind::kBinary: {
982 BinaryExpression& binaryExpr = (*expr)->as<BinaryExpression>();
John Stiles2d4f9592020-10-30 10:29:12 -0400983 this->visitExpression(&binaryExpr.left());
John Stiles70957c82020-10-02 16:42:10 -0400984
985 // Logical-and and logical-or binary expressions do not inline the right side,
986 // because that would invalidate short-circuiting. That is, when evaluating
987 // expressions like these:
988 // (false && x()) // always false
989 // (true || y()) // always true
990 // It is illegal for side-effects from x() or y() to occur. The simplest way to
991 // enforce that rule is to avoid inlining the right side entirely. However, it is
992 // safe for other types of binary expression to inline both sides.
993 Token::Kind op = binaryExpr.getOperator();
994 bool shortCircuitable = (op == Token::Kind::TK_LOGICALAND ||
995 op == Token::Kind::TK_LOGICALOR);
996 if (!shortCircuitable) {
John Stiles2d4f9592020-10-30 10:29:12 -0400997 this->visitExpression(&binaryExpr.right());
John Stiles70957c82020-10-02 16:42:10 -0400998 }
999 break;
1000 }
1001 case Expression::Kind::kConstructor: {
1002 Constructor& constructorExpr = (*expr)->as<Constructor>();
1003 for (std::unique_ptr<Expression>& arg : constructorExpr.arguments()) {
1004 this->visitExpression(&arg);
1005 }
1006 break;
1007 }
1008 case Expression::Kind::kExternalFunctionCall: {
1009 ExternalFunctionCall& funcCallExpr = (*expr)->as<ExternalFunctionCall>();
1010 for (std::unique_ptr<Expression>& arg : funcCallExpr.arguments()) {
1011 this->visitExpression(&arg);
1012 }
1013 break;
1014 }
1015 case Expression::Kind::kFunctionCall: {
1016 FunctionCall& funcCallExpr = (*expr)->as<FunctionCall>();
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001017 for (std::unique_ptr<Expression>& arg : funcCallExpr.arguments()) {
John Stiles70957c82020-10-02 16:42:10 -04001018 this->visitExpression(&arg);
1019 }
1020 this->addInlineCandidate(expr);
1021 break;
1022 }
1023 case Expression::Kind::kIndex:{
1024 IndexExpression& indexExpr = (*expr)->as<IndexExpression>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04001025 this->visitExpression(&indexExpr.base());
1026 this->visitExpression(&indexExpr.index());
John Stiles70957c82020-10-02 16:42:10 -04001027 break;
1028 }
1029 case Expression::Kind::kPostfix: {
1030 PostfixExpression& postfixExpr = (*expr)->as<PostfixExpression>();
Ethan Nicholas444ccc62020-10-09 10:16:22 -04001031 this->visitExpression(&postfixExpr.operand());
John Stiles70957c82020-10-02 16:42:10 -04001032 break;
1033 }
1034 case Expression::Kind::kPrefix: {
1035 PrefixExpression& prefixExpr = (*expr)->as<PrefixExpression>();
Ethan Nicholas444ccc62020-10-09 10:16:22 -04001036 this->visitExpression(&prefixExpr.operand());
John Stiles70957c82020-10-02 16:42:10 -04001037 break;
1038 }
1039 case Expression::Kind::kSwizzle: {
1040 Swizzle& swizzleExpr = (*expr)->as<Swizzle>();
Ethan Nicholas6b4d5812020-10-12 16:11:51 -04001041 this->visitExpression(&swizzleExpr.base());
John Stiles70957c82020-10-02 16:42:10 -04001042 break;
1043 }
1044 case Expression::Kind::kTernary: {
1045 TernaryExpression& ternaryExpr = (*expr)->as<TernaryExpression>();
1046 // The test expression is a candidate for inlining.
Ethan Nicholasdd218162020-10-08 05:48:01 -04001047 this->visitExpression(&ternaryExpr.test());
John Stiles70957c82020-10-02 16:42:10 -04001048 // The true- and false-expressions cannot be inlined, because we are only allowed to
1049 // evaluate one side.
1050 break;
1051 }
1052 default:
1053 SkUNREACHABLE;
1054 }
1055 }
1056
1057 void addInlineCandidate(std::unique_ptr<Expression>* candidate) {
1058 fCandidateList->fCandidates.push_back(
1059 InlineCandidate{fSymbolTableStack.back(),
1060 find_parent_statement(fEnclosingStmtStack),
1061 fEnclosingStmtStack.back(),
1062 candidate,
John Stiles9b9415e2020-11-23 14:48:06 -05001063 fEnclosingFunction});
John Stiles70957c82020-10-02 16:42:10 -04001064 }
John Stiles2d7973a2020-10-02 15:01:03 -04001065};
John Stiles93442622020-09-11 12:11:27 -04001066
John Stiles9b9415e2020-11-23 14:48:06 -05001067static const FunctionDeclaration& candidate_func(const InlineCandidate& candidate) {
1068 return (*candidate.fCandidateExpr)->as<FunctionCall>().function();
1069}
John Stiles915a38c2020-09-14 09:38:13 -04001070
John Stiles9b9415e2020-11-23 14:48:06 -05001071bool Inliner::candidateCanBeInlined(const InlineCandidate& candidate, InlinabilityCache* cache) {
1072 const FunctionDeclaration& funcDecl = candidate_func(candidate);
John Stiles1c03d332020-10-13 10:30:23 -04001073 auto [iter, wasInserted] = cache->insert({&funcDecl, false});
John Stiles2d7973a2020-10-02 15:01:03 -04001074 if (wasInserted) {
1075 // Recursion is forbidden here to avoid an infinite death spiral of inlining.
John Stiles1c03d332020-10-13 10:30:23 -04001076 iter->second = this->isSafeToInline(funcDecl.definition()) &&
1077 !contains_recursive_call(funcDecl);
John Stiles93442622020-09-11 12:11:27 -04001078 }
1079
John Stiles2d7973a2020-10-02 15:01:03 -04001080 return iter->second;
1081}
1082
John Stiles9b9415e2020-11-23 14:48:06 -05001083int Inliner::getFunctionSize(const FunctionDeclaration& funcDecl, FunctionSizeCache* cache) {
1084 auto [iter, wasInserted] = cache->insert({&funcDecl, 0});
John Stiles2d7973a2020-10-02 15:01:03 -04001085 if (wasInserted) {
John Stiles9b9415e2020-11-23 14:48:06 -05001086 iter->second = Analysis::NodeCountUpToLimit(*funcDecl.definition(),
1087 fSettings->fInlineThreshold);
John Stiles2d7973a2020-10-02 15:01:03 -04001088 }
John Stiles2d7973a2020-10-02 15:01:03 -04001089 return iter->second;
1090}
1091
Brian Osman0006ad02020-11-18 15:38:39 -05001092void Inliner::buildCandidateList(const std::vector<std::unique_ptr<ProgramElement>>& elements,
John Stiles78047582020-12-16 16:17:41 -05001093 std::shared_ptr<SymbolTable> symbols, ProgramUsage* usage,
Brian Osman0006ad02020-11-18 15:38:39 -05001094 InlineCandidateList* candidateList) {
John Stiles2d7973a2020-10-02 15:01:03 -04001095 // This is structured much like a ProgramVisitor, but does not actually use ProgramVisitor.
1096 // The analyzer needs to keep track of the `unique_ptr<T>*` of statements and expressions so
1097 // that they can later be replaced, and ProgramVisitor does not provide this; it only provides a
1098 // `const T&`.
1099 InlineCandidateAnalyzer analyzer;
Brian Osman0006ad02020-11-18 15:38:39 -05001100 analyzer.visit(elements, symbols, candidateList);
John Stiles2d7973a2020-10-02 15:01:03 -04001101
John Stiles0ad233f2020-11-25 11:02:05 -05001102 // Early out if there are no inlining candidates.
John Stiles2d7973a2020-10-02 15:01:03 -04001103 std::vector<InlineCandidate>& candidates = candidateList->fCandidates;
John Stiles0ad233f2020-11-25 11:02:05 -05001104 if (candidates.empty()) {
1105 return;
1106 }
1107
1108 // Remove candidates that are not safe to inline.
John Stiles2d7973a2020-10-02 15:01:03 -04001109 InlinabilityCache cache;
1110 candidates.erase(std::remove_if(candidates.begin(),
1111 candidates.end(),
1112 [&](const InlineCandidate& candidate) {
1113 return !this->candidateCanBeInlined(candidate, &cache);
1114 }),
1115 candidates.end());
1116
John Stiles0ad233f2020-11-25 11:02:05 -05001117 // If the inline threshold is unlimited, or if we have no candidates left, our candidate list is
1118 // complete.
1119 if (fSettings->fInlineThreshold == INT_MAX || candidates.empty()) {
1120 return;
John Stiles2d7973a2020-10-02 15:01:03 -04001121 }
John Stiles0ad233f2020-11-25 11:02:05 -05001122
1123 // Remove candidates on a per-function basis if the effect of inlining would be to make more
1124 // than `inlineThreshold` nodes. (i.e. if Func() would be inlined six times and its size is
1125 // 10 nodes, it should be inlined if the inlineThreshold is 60 or higher.)
1126 FunctionSizeCache functionSizeCache;
1127 FunctionSizeCache candidateTotalCost;
1128 for (InlineCandidate& candidate : candidates) {
1129 const FunctionDeclaration& fnDecl = candidate_func(candidate);
1130 candidateTotalCost[&fnDecl] += this->getFunctionSize(fnDecl, &functionSizeCache);
1131 }
1132
1133 candidates.erase(
1134 std::remove_if(candidates.begin(),
1135 candidates.end(),
1136 [&](const InlineCandidate& candidate) {
1137 const FunctionDeclaration& fnDecl = candidate_func(candidate);
1138 if (fnDecl.modifiers().fFlags & Modifiers::kInline_Flag) {
1139 // Functions marked `inline` ignore size limitations.
1140 return false;
1141 }
1142 if (usage->get(fnDecl) == 1) {
1143 // If a function is only used once, it's cost-free to inline.
1144 return false;
1145 }
1146 if (candidateTotalCost[&fnDecl] <= fSettings->fInlineThreshold) {
1147 // We won't exceed the inline threshold by inlining this.
1148 return false;
1149 }
1150 // Inlining this function will add too many IRNodes.
1151 return true;
1152 }),
1153 candidates.end());
John Stiles2d7973a2020-10-02 15:01:03 -04001154}
1155
Brian Osman0006ad02020-11-18 15:38:39 -05001156bool Inliner::analyze(const std::vector<std::unique_ptr<ProgramElement>>& elements,
John Stiles78047582020-12-16 16:17:41 -05001157 std::shared_ptr<SymbolTable> symbols,
Brian Osman0006ad02020-11-18 15:38:39 -05001158 ProgramUsage* usage) {
John Stilesd34d56e2020-10-12 12:04:47 -04001159 // A threshold of zero indicates that the inliner is completely disabled, so we can just return.
1160 if (fSettings->fInlineThreshold <= 0) {
1161 return false;
1162 }
1163
John Stiles031a7672020-11-13 16:13:18 -05001164 // Enforce a limit on inlining to avoid pathological cases. (inliner/ExponentialGrowth.sksl)
1165 if (fInlinedStatementCounter >= kInlinedStatementLimit) {
1166 return false;
1167 }
1168
John Stiles2d7973a2020-10-02 15:01:03 -04001169 InlineCandidateList candidateList;
John Stiles9b9415e2020-11-23 14:48:06 -05001170 this->buildCandidateList(elements, symbols, usage, &candidateList);
John Stiles2d7973a2020-10-02 15:01:03 -04001171
John Stiles915a38c2020-09-14 09:38:13 -04001172 // Inline the candidates where we've determined that it's safe to do so.
1173 std::unordered_set<const std::unique_ptr<Statement>*> enclosingStmtSet;
1174 bool madeChanges = false;
John Stiles2d7973a2020-10-02 15:01:03 -04001175 for (const InlineCandidate& candidate : candidateList.fCandidates) {
John Stiles915a38c2020-09-14 09:38:13 -04001176 FunctionCall& funcCall = (*candidate.fCandidateExpr)->as<FunctionCall>();
John Stiles915a38c2020-09-14 09:38:13 -04001177
1178 // Inlining two expressions using the same enclosing statement in the same inlining pass
1179 // does not work properly. If this happens, skip it; we'll get it in the next pass.
1180 auto [unusedIter, inserted] = enclosingStmtSet.insert(candidate.fEnclosingStmt);
1181 if (!inserted) {
1182 continue;
1183 }
1184
1185 // Convert the function call to its inlined equivalent.
Brian Osman3887a012020-09-30 13:22:27 -04001186 InlinedCall inlinedCall = this->inlineCall(&funcCall, candidate.fSymbols,
Ethan Nicholas0a5d0962020-10-14 13:33:18 -04001187 &candidate.fEnclosingFunction->declaration());
John Stiles915a38c2020-09-14 09:38:13 -04001188 if (inlinedCall.fInlinedBody) {
1189 // Ensure that the inlined body has a scope if it needs one.
John Stiles6d696082020-10-01 10:18:54 -04001190 this->ensureScopedBlocks(inlinedCall.fInlinedBody.get(), candidate.fParentStmt->get());
John Stiles915a38c2020-09-14 09:38:13 -04001191
Brian Osman010ce6a2020-10-19 16:34:10 -04001192 // Add references within the inlined body
1193 usage->add(inlinedCall.fInlinedBody.get());
1194
John Stiles915a38c2020-09-14 09:38:13 -04001195 // Move the enclosing statement to the end of the unscoped Block containing the inlined
1196 // function, then replace the enclosing statement with that Block.
1197 // Before:
1198 // fInlinedBody = Block{ stmt1, stmt2, stmt3 }
1199 // fEnclosingStmt = stmt4
1200 // After:
1201 // fInlinedBody = null
1202 // fEnclosingStmt = Block{ stmt1, stmt2, stmt3, stmt4 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001203 inlinedCall.fInlinedBody->children().push_back(std::move(*candidate.fEnclosingStmt));
John Stiles915a38c2020-09-14 09:38:13 -04001204 *candidate.fEnclosingStmt = std::move(inlinedCall.fInlinedBody);
1205 }
1206
1207 // Replace the candidate function call with our replacement expression.
Brian Osman010ce6a2020-10-19 16:34:10 -04001208 usage->replace(candidate.fCandidateExpr->get(), inlinedCall.fReplacementExpr.get());
John Stiles915a38c2020-09-14 09:38:13 -04001209 *candidate.fCandidateExpr = std::move(inlinedCall.fReplacementExpr);
1210 madeChanges = true;
1211
John Stiles031a7672020-11-13 16:13:18 -05001212 // Stop inlining if we've reached our hard cap on new statements.
1213 if (fInlinedStatementCounter >= kInlinedStatementLimit) {
1214 break;
1215 }
1216
John Stiles915a38c2020-09-14 09:38:13 -04001217 // Note that nothing was destroyed except for the FunctionCall. All other nodes should
1218 // remain valid.
1219 }
1220
1221 return madeChanges;
John Stiles93442622020-09-11 12:11:27 -04001222}
1223
John Stiles44e96be2020-08-31 13:16:04 -04001224} // namespace SkSL