blob: ba6fb7f9d4db884cc81720dca7222309192bd574 [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"
54#include "src/sksl/ir/SkSLWhileStatement.h"
55
56namespace SkSL {
57namespace {
58
John Stiles031a7672020-11-13 16:13:18 -050059static constexpr int kInlinedStatementLimit = 2500;
60
John Stiles44dff4f2020-09-21 12:28:01 -040061static bool contains_returns_above_limit(const FunctionDefinition& funcDef, int limit) {
62 class CountReturnsWithLimit : public ProgramVisitor {
John Stiles44e96be2020-08-31 13:16:04 -040063 public:
John Stiles44dff4f2020-09-21 12:28:01 -040064 CountReturnsWithLimit(const FunctionDefinition& funcDef, int limit) : fLimit(limit) {
John Stiles44e96be2020-08-31 13:16:04 -040065 this->visitProgramElement(funcDef);
66 }
67
68 bool visitStatement(const Statement& stmt) override {
Ethan Nicholase6592142020-09-08 10:22:09 -040069 switch (stmt.kind()) {
70 case Statement::Kind::kReturn:
John Stiles44e96be2020-08-31 13:16:04 -040071 ++fNumReturns;
John Stiles44dff4f2020-09-21 12:28:01 -040072 return (fNumReturns > fLimit) || INHERITED::visitStatement(stmt);
John Stiles44e96be2020-08-31 13:16:04 -040073
74 default:
John Stiles93442622020-09-11 12:11:27 -040075 return INHERITED::visitStatement(stmt);
John Stiles44e96be2020-08-31 13:16:04 -040076 }
77 }
78
79 int fNumReturns = 0;
John Stiles44dff4f2020-09-21 12:28:01 -040080 int fLimit = 0;
John Stiles44e96be2020-08-31 13:16:04 -040081 using INHERITED = ProgramVisitor;
82 };
83
John Stiles44dff4f2020-09-21 12:28:01 -040084 return CountReturnsWithLimit{funcDef, limit}.fNumReturns > limit;
John Stiles44e96be2020-08-31 13:16:04 -040085}
86
87static int count_returns_at_end_of_control_flow(const FunctionDefinition& funcDef) {
88 class CountReturnsAtEndOfControlFlow : public ProgramVisitor {
89 public:
90 CountReturnsAtEndOfControlFlow(const FunctionDefinition& funcDef) {
91 this->visitProgramElement(funcDef);
92 }
93
94 bool visitStatement(const Statement& stmt) override {
Ethan Nicholase6592142020-09-08 10:22:09 -040095 switch (stmt.kind()) {
96 case Statement::Kind::kBlock: {
John Stiles44e96be2020-08-31 13:16:04 -040097 // Check only the last statement of a block.
Ethan Nicholas7bd60432020-09-25 14:31:59 -040098 const auto& block = stmt.as<Block>();
99 return block.children().size() &&
100 this->visitStatement(*block.children().back());
John Stiles44e96be2020-08-31 13:16:04 -0400101 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400102 case Statement::Kind::kSwitch:
103 case Statement::Kind::kWhile:
104 case Statement::Kind::kDo:
105 case Statement::Kind::kFor:
John Stiles44e96be2020-08-31 13:16:04 -0400106 // Don't introspect switches or loop structures at all.
107 return false;
108
Ethan Nicholase6592142020-09-08 10:22:09 -0400109 case Statement::Kind::kReturn:
John Stiles44e96be2020-08-31 13:16:04 -0400110 ++fNumReturns;
111 [[fallthrough]];
112
113 default:
John Stiles93442622020-09-11 12:11:27 -0400114 return INHERITED::visitStatement(stmt);
John Stiles44e96be2020-08-31 13:16:04 -0400115 }
116 }
117
118 int fNumReturns = 0;
119 using INHERITED = ProgramVisitor;
120 };
121
122 return CountReturnsAtEndOfControlFlow{funcDef}.fNumReturns;
123}
124
125static int count_returns_in_breakable_constructs(const FunctionDefinition& funcDef) {
126 class CountReturnsInBreakableConstructs : public ProgramVisitor {
127 public:
128 CountReturnsInBreakableConstructs(const FunctionDefinition& funcDef) {
129 this->visitProgramElement(funcDef);
130 }
131
132 bool visitStatement(const Statement& stmt) override {
Ethan Nicholase6592142020-09-08 10:22:09 -0400133 switch (stmt.kind()) {
134 case Statement::Kind::kSwitch:
135 case Statement::Kind::kWhile:
136 case Statement::Kind::kDo:
137 case Statement::Kind::kFor: {
John Stiles44e96be2020-08-31 13:16:04 -0400138 ++fInsideBreakableConstruct;
John Stiles93442622020-09-11 12:11:27 -0400139 bool result = INHERITED::visitStatement(stmt);
John Stiles44e96be2020-08-31 13:16:04 -0400140 --fInsideBreakableConstruct;
141 return result;
142 }
143
Ethan Nicholase6592142020-09-08 10:22:09 -0400144 case Statement::Kind::kReturn:
John Stiles44e96be2020-08-31 13:16:04 -0400145 fNumReturns += (fInsideBreakableConstruct > 0) ? 1 : 0;
146 [[fallthrough]];
147
148 default:
John Stiles93442622020-09-11 12:11:27 -0400149 return INHERITED::visitStatement(stmt);
John Stiles44e96be2020-08-31 13:16:04 -0400150 }
151 }
152
153 int fNumReturns = 0;
154 int fInsideBreakableConstruct = 0;
155 using INHERITED = ProgramVisitor;
156 };
157
158 return CountReturnsInBreakableConstructs{funcDef}.fNumReturns;
159}
160
161static bool has_early_return(const FunctionDefinition& funcDef) {
John Stiles44e96be2020-08-31 13:16:04 -0400162 int returnsAtEndOfControlFlow = count_returns_at_end_of_control_flow(funcDef);
John Stiles44dff4f2020-09-21 12:28:01 -0400163 return contains_returns_above_limit(funcDef, returnsAtEndOfControlFlow);
John Stiles44e96be2020-08-31 13:16:04 -0400164}
165
John Stiles991b09d2020-09-10 13:33:40 -0400166static bool contains_recursive_call(const FunctionDeclaration& funcDecl) {
167 class ContainsRecursiveCall : public ProgramVisitor {
168 public:
169 bool visit(const FunctionDeclaration& funcDecl) {
170 fFuncDecl = &funcDecl;
Ethan Nicholased84b732020-10-08 11:45:44 -0400171 return funcDecl.definition() ? this->visitProgramElement(*funcDecl.definition())
172 : false;
John Stiles991b09d2020-09-10 13:33:40 -0400173 }
174
175 bool visitExpression(const Expression& expr) override {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400176 if (expr.is<FunctionCall>() && expr.as<FunctionCall>().function().matches(*fFuncDecl)) {
John Stiles991b09d2020-09-10 13:33:40 -0400177 return true;
178 }
179 return INHERITED::visitExpression(expr);
180 }
181
182 bool visitStatement(const Statement& stmt) override {
Ethan Nicholasceb62142020-10-09 16:51:18 -0400183 if (stmt.is<InlineMarker>() &&
184 stmt.as<InlineMarker>().function().matches(*fFuncDecl)) {
John Stiles991b09d2020-09-10 13:33:40 -0400185 return true;
186 }
187 return INHERITED::visitStatement(stmt);
188 }
189
190 const FunctionDeclaration* fFuncDecl;
191 using INHERITED = ProgramVisitor;
192 };
193
194 return ContainsRecursiveCall{}.visit(funcDecl);
195}
196
John Stiles44e96be2020-08-31 13:16:04 -0400197static const Type* copy_if_needed(const Type* src, SymbolTable& symbolTable) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400198 if (src->typeKind() == Type::TypeKind::kArray) {
Ethan Nicholase2c49992020-10-05 11:49:11 -0400199 return symbolTable.takeOwnershipOfSymbol(std::make_unique<Type>(src->name(),
200 src->typeKind(),
201 src->componentType(),
202 src->columns()));
John Stiles44e96be2020-08-31 13:16:04 -0400203 }
204 return src;
205}
206
John Stiles6d696082020-10-01 10:18:54 -0400207static std::unique_ptr<Statement>* find_parent_statement(
208 const std::vector<std::unique_ptr<Statement>*>& stmtStack) {
John Stiles915a38c2020-09-14 09:38:13 -0400209 SkASSERT(!stmtStack.empty());
210
211 // Walk the statement stack from back to front, ignoring the last element (which is the
212 // enclosing statement).
213 auto iter = stmtStack.rbegin();
214 ++iter;
215
216 // Anything counts as a parent statement other than a scopeless Block.
217 for (; iter != stmtStack.rend(); ++iter) {
John Stiles6d696082020-10-01 10:18:54 -0400218 std::unique_ptr<Statement>* stmt = *iter;
219 if (!(*stmt)->is<Block>() || (*stmt)->as<Block>().isScope()) {
John Stiles915a38c2020-09-14 09:38:13 -0400220 return stmt;
221 }
222 }
223
224 // There wasn't any parent statement to be found.
225 return nullptr;
226}
227
John Stilese41b4ee2020-09-28 12:28:16 -0400228std::unique_ptr<Expression> clone_with_ref_kind(const Expression& expr,
229 VariableReference::RefKind refKind) {
230 std::unique_ptr<Expression> clone = expr.clone();
John Stiles70b82422020-09-30 10:55:12 -0400231 class SetRefKindInExpression : public ProgramWriter {
John Stilese41b4ee2020-09-28 12:28:16 -0400232 public:
233 SetRefKindInExpression(VariableReference::RefKind refKind) : fRefKind(refKind) {}
John Stiles70b82422020-09-30 10:55:12 -0400234 bool visitExpression(Expression& expr) override {
John Stilese41b4ee2020-09-28 12:28:16 -0400235 if (expr.is<VariableReference>()) {
John Stiles70b82422020-09-30 10:55:12 -0400236 expr.as<VariableReference>().setRefKind(fRefKind);
John Stilese41b4ee2020-09-28 12:28:16 -0400237 }
238 return INHERITED::visitExpression(expr);
239 }
240
241 private:
242 VariableReference::RefKind fRefKind;
243
John Stiles70b82422020-09-30 10:55:12 -0400244 using INHERITED = ProgramWriter;
John Stilese41b4ee2020-09-28 12:28:16 -0400245 };
246
247 SetRefKindInExpression{refKind}.visitExpression(*clone);
248 return clone;
249}
250
John Stiles44733aa2020-09-29 17:42:23 -0400251bool is_trivial_argument(const Expression& argument) {
252 return argument.is<VariableReference>() ||
Ethan Nicholas6b4d5812020-10-12 16:11:51 -0400253 (argument.is<Swizzle>() && is_trivial_argument(*argument.as<Swizzle>().base())) ||
Ethan Nicholas7a95b202020-10-09 11:55:40 -0400254 (argument.is<FieldAccess>() &&
255 is_trivial_argument(*argument.as<FieldAccess>().base())) ||
John Stiles80ccdbd2020-09-30 11:58:16 -0400256 (argument.is<Constructor>() &&
257 argument.as<Constructor>().arguments().size() == 1 &&
258 is_trivial_argument(*argument.as<Constructor>().arguments().front())) ||
John Stiles44733aa2020-09-29 17:42:23 -0400259 (argument.is<IndexExpression>() &&
Ethan Nicholas2a4952d2020-10-08 15:35:56 -0400260 argument.as<IndexExpression>().index()->is<IntLiteral>() &&
261 is_trivial_argument(*argument.as<IndexExpression>().base()));
John Stiles44733aa2020-09-29 17:42:23 -0400262}
263
John Stiles44e96be2020-08-31 13:16:04 -0400264} // namespace
265
John Stilesb61ee902020-09-21 12:26:59 -0400266void Inliner::ensureScopedBlocks(Statement* inlinedBody, Statement* parentStmt) {
267 // No changes necessary if this statement isn't actually a block.
268 if (!inlinedBody || !inlinedBody->is<Block>()) {
269 return;
270 }
271
272 // No changes necessary if the parent statement doesn't require a scope.
273 if (!parentStmt || !(parentStmt->is<IfStatement>() || parentStmt->is<ForStatement>() ||
274 parentStmt->is<DoStatement>() || parentStmt->is<WhileStatement>())) {
275 return;
276 }
277
278 Block& block = inlinedBody->as<Block>();
279
280 // The inliner will create inlined function bodies as a Block containing multiple statements,
281 // but no scope. Normally, this is fine, but if this block is used as the statement for a
282 // do/for/if/while, this isn't actually possible to represent textually; a scope must be added
283 // for the generated code to match the intent. In the case of Blocks nested inside other Blocks,
284 // we add the scope to the outermost block if needed. Zero-statement blocks have similar
285 // issues--if we don't represent the Block textually somehow, we run the risk of accidentally
286 // absorbing the following statement into our loop--so we also add a scope to these.
287 for (Block* nestedBlock = &block;; ) {
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400288 if (nestedBlock->isScope()) {
John Stilesb61ee902020-09-21 12:26:59 -0400289 // We found an explicit scope; all is well.
290 return;
291 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400292 if (nestedBlock->children().size() != 1) {
John Stilesb61ee902020-09-21 12:26:59 -0400293 // We found a block with multiple (or zero) statements, but no scope? Let's add a scope
294 // to the outermost block.
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400295 block.setIsScope(true);
John Stilesb61ee902020-09-21 12:26:59 -0400296 return;
297 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400298 if (!nestedBlock->children()[0]->is<Block>()) {
John Stilesb61ee902020-09-21 12:26:59 -0400299 // This block has exactly one thing inside, and it's not another block. No need to scope
300 // it.
301 return;
302 }
303 // We have to go deeper.
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400304 nestedBlock = &nestedBlock->children()[0]->as<Block>();
John Stilesb61ee902020-09-21 12:26:59 -0400305 }
306}
307
Brian Osman0006ad02020-11-18 15:38:39 -0500308void Inliner::reset(ModifiersPool* modifiers, const Program::Settings* settings) {
Ethan Nicholas041fd0a2020-10-07 16:42:04 -0400309 fModifiers = modifiers;
310 fSettings = settings;
John Stiles44e96be2020-08-31 13:16:04 -0400311 fInlineVarCounter = 0;
John Stiles031a7672020-11-13 16:13:18 -0500312 fInlinedStatementCounter = 0;
John Stiles44e96be2020-08-31 13:16:04 -0400313}
314
John Stilesc75abb82020-09-14 18:24:12 -0400315String Inliner::uniqueNameForInlineVar(const String& baseName, SymbolTable* symbolTable) {
316 // If the base name starts with an underscore, like "_coords", we can't append another
317 // underscore, because OpenGL disallows two consecutive underscores anywhere in the string. But
318 // in the general case, using the underscore as a splitter reads nicely enough that it's worth
319 // putting in this special case.
320 const char* splitter = baseName.startsWith("_") ? "" : "_";
321
322 // Append a unique numeric prefix to avoid name overlap. Check the symbol table to make sure
323 // we're not reusing an existing name. (Note that within a single compilation pass, this check
324 // isn't fully comprehensive, as code isn't always generated in top-to-bottom order.)
325 String uniqueName;
326 for (;;) {
327 uniqueName = String::printf("_%d%s%s", fInlineVarCounter++, splitter, baseName.c_str());
328 StringFragment frag{uniqueName.data(), uniqueName.length()};
329 if ((*symbolTable)[frag] == nullptr) {
330 break;
331 }
332 }
333
334 return uniqueName;
335}
336
John Stiles44e96be2020-08-31 13:16:04 -0400337std::unique_ptr<Expression> Inliner::inlineExpression(int offset,
338 VariableRewriteMap* varMap,
339 const Expression& expression) {
340 auto expr = [&](const std::unique_ptr<Expression>& e) -> std::unique_ptr<Expression> {
341 if (e) {
342 return this->inlineExpression(offset, varMap, *e);
343 }
344 return nullptr;
345 };
John Stiles8e3b6be2020-10-13 11:14:08 -0400346 auto argList = [&](const ExpressionArray& originalArgs) -> ExpressionArray {
347 ExpressionArray args;
John Stilesf4bda742020-10-14 16:57:41 -0400348 args.reserve_back(originalArgs.size());
John Stiles44e96be2020-08-31 13:16:04 -0400349 for (const std::unique_ptr<Expression>& arg : originalArgs) {
350 args.push_back(expr(arg));
351 }
352 return args;
353 };
354
Ethan Nicholase6592142020-09-08 10:22:09 -0400355 switch (expression.kind()) {
356 case Expression::Kind::kBinary: {
John Stiles44e96be2020-08-31 13:16:04 -0400357 const BinaryExpression& b = expression.as<BinaryExpression>();
358 return std::make_unique<BinaryExpression>(offset,
John Stiles2d4f9592020-10-30 10:29:12 -0400359 expr(b.left()),
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400360 b.getOperator(),
John Stiles2d4f9592020-10-30 10:29:12 -0400361 expr(b.right()),
Ethan Nicholas30d30222020-09-11 12:27:26 -0400362 &b.type());
John Stiles44e96be2020-08-31 13:16:04 -0400363 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400364 case Expression::Kind::kBoolLiteral:
365 case Expression::Kind::kIntLiteral:
366 case Expression::Kind::kFloatLiteral:
367 case Expression::Kind::kNullLiteral:
John Stiles44e96be2020-08-31 13:16:04 -0400368 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400369 case Expression::Kind::kConstructor: {
John Stiles44e96be2020-08-31 13:16:04 -0400370 const Constructor& constructor = expression.as<Constructor>();
Ethan Nicholas30d30222020-09-11 12:27:26 -0400371 return std::make_unique<Constructor>(offset, &constructor.type(),
Ethan Nicholasf70f0442020-09-29 12:41:35 -0400372 argList(constructor.arguments()));
John Stiles44e96be2020-08-31 13:16:04 -0400373 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400374 case Expression::Kind::kExternalFunctionCall: {
John Stiles44e96be2020-08-31 13:16:04 -0400375 const ExternalFunctionCall& externalCall = expression.as<ExternalFunctionCall>();
Ethan Nicholas444ccc62020-10-09 10:16:22 -0400376 return std::make_unique<ExternalFunctionCall>(offset, &externalCall.function(),
Ethan Nicholas6e86ec92020-09-30 14:29:56 -0400377 argList(externalCall.arguments()));
John Stiles44e96be2020-08-31 13:16:04 -0400378 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400379 case Expression::Kind::kExternalValue:
John Stiles44e96be2020-08-31 13:16:04 -0400380 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400381 case Expression::Kind::kFieldAccess: {
John Stiles44e96be2020-08-31 13:16:04 -0400382 const FieldAccess& f = expression.as<FieldAccess>();
Ethan Nicholas7a95b202020-10-09 11:55:40 -0400383 return std::make_unique<FieldAccess>(expr(f.base()), f.fieldIndex(), f.ownerKind());
John Stiles44e96be2020-08-31 13:16:04 -0400384 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400385 case Expression::Kind::kFunctionCall: {
John Stiles44e96be2020-08-31 13:16:04 -0400386 const FunctionCall& funcCall = expression.as<FunctionCall>();
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400387 return std::make_unique<FunctionCall>(offset, &funcCall.type(), &funcCall.function(),
388 argList(funcCall.arguments()));
John Stiles44e96be2020-08-31 13:16:04 -0400389 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400390 case Expression::Kind::kFunctionReference:
Brian Osman2b3b35f2020-09-08 09:17:36 -0400391 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400392 case Expression::Kind::kIndex: {
John Stiles44e96be2020-08-31 13:16:04 -0400393 const IndexExpression& idx = expression.as<IndexExpression>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -0400394 return std::make_unique<IndexExpression>(*fContext, expr(idx.base()),
395 expr(idx.index()));
John Stiles44e96be2020-08-31 13:16:04 -0400396 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400397 case Expression::Kind::kPrefix: {
John Stiles44e96be2020-08-31 13:16:04 -0400398 const PrefixExpression& p = expression.as<PrefixExpression>();
Ethan Nicholas444ccc62020-10-09 10:16:22 -0400399 return std::make_unique<PrefixExpression>(p.getOperator(), expr(p.operand()));
John Stiles44e96be2020-08-31 13:16:04 -0400400 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400401 case Expression::Kind::kPostfix: {
John Stiles44e96be2020-08-31 13:16:04 -0400402 const PostfixExpression& p = expression.as<PostfixExpression>();
Ethan Nicholas444ccc62020-10-09 10:16:22 -0400403 return std::make_unique<PostfixExpression>(expr(p.operand()), p.getOperator());
John Stiles44e96be2020-08-31 13:16:04 -0400404 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400405 case Expression::Kind::kSetting:
John Stiles44e96be2020-08-31 13:16:04 -0400406 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400407 case Expression::Kind::kSwizzle: {
John Stiles44e96be2020-08-31 13:16:04 -0400408 const Swizzle& s = expression.as<Swizzle>();
Ethan Nicholas6b4d5812020-10-12 16:11:51 -0400409 return std::make_unique<Swizzle>(*fContext, expr(s.base()), s.components());
John Stiles44e96be2020-08-31 13:16:04 -0400410 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400411 case Expression::Kind::kTernary: {
John Stiles44e96be2020-08-31 13:16:04 -0400412 const TernaryExpression& t = expression.as<TernaryExpression>();
Ethan Nicholasdd218162020-10-08 05:48:01 -0400413 return std::make_unique<TernaryExpression>(offset, expr(t.test()),
414 expr(t.ifTrue()), expr(t.ifFalse()));
John Stiles44e96be2020-08-31 13:16:04 -0400415 }
Brian Osman83ba9302020-09-11 13:33:46 -0400416 case Expression::Kind::kTypeReference:
417 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400418 case Expression::Kind::kVariableReference: {
John Stiles44e96be2020-08-31 13:16:04 -0400419 const VariableReference& v = expression.as<VariableReference>();
Ethan Nicholas78686922020-10-08 06:46:27 -0400420 auto varMapIter = varMap->find(v.variable());
John Stilese41b4ee2020-09-28 12:28:16 -0400421 if (varMapIter != varMap->end()) {
Ethan Nicholas78686922020-10-08 06:46:27 -0400422 return clone_with_ref_kind(*varMapIter->second, v.refKind());
John Stiles44e96be2020-08-31 13:16:04 -0400423 }
424 return v.clone();
425 }
426 default:
427 SkASSERT(false);
428 return nullptr;
429 }
430}
431
432std::unique_ptr<Statement> Inliner::inlineStatement(int offset,
433 VariableRewriteMap* varMap,
434 SymbolTable* symbolTableForStatement,
John Stilese41b4ee2020-09-28 12:28:16 -0400435 const Expression* resultExpr,
John Stiles44e96be2020-08-31 13:16:04 -0400436 bool haveEarlyReturns,
Brian Osman3887a012020-09-30 13:22:27 -0400437 const Statement& statement,
438 bool isBuiltinCode) {
John Stiles44e96be2020-08-31 13:16:04 -0400439 auto stmt = [&](const std::unique_ptr<Statement>& s) -> std::unique_ptr<Statement> {
440 if (s) {
John Stilesa5f3c312020-09-22 12:05:16 -0400441 return this->inlineStatement(offset, varMap, symbolTableForStatement, resultExpr,
Brian Osman3887a012020-09-30 13:22:27 -0400442 haveEarlyReturns, *s, isBuiltinCode);
John Stiles44e96be2020-08-31 13:16:04 -0400443 }
444 return nullptr;
445 };
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400446 auto blockStmts = [&](const Block& block) {
John Stiles8f2a0cf2020-10-13 12:48:21 -0400447 StatementArray result;
John Stilesf4bda742020-10-14 16:57:41 -0400448 result.reserve_back(block.children().size());
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400449 for (const std::unique_ptr<Statement>& child : block.children()) {
450 result.push_back(stmt(child));
451 }
452 return result;
453 };
John Stiles8f2a0cf2020-10-13 12:48:21 -0400454 auto stmts = [&](const StatementArray& ss) {
455 StatementArray result;
John Stilesf4bda742020-10-14 16:57:41 -0400456 result.reserve_back(ss.size());
John Stiles44e96be2020-08-31 13:16:04 -0400457 for (const auto& s : ss) {
458 result.push_back(stmt(s));
459 }
460 return result;
461 };
462 auto expr = [&](const std::unique_ptr<Expression>& e) -> std::unique_ptr<Expression> {
463 if (e) {
464 return this->inlineExpression(offset, varMap, *e);
465 }
466 return nullptr;
467 };
John Stiles031a7672020-11-13 16:13:18 -0500468
469 ++fInlinedStatementCounter;
470
Ethan Nicholase6592142020-09-08 10:22:09 -0400471 switch (statement.kind()) {
472 case Statement::Kind::kBlock: {
John Stiles44e96be2020-08-31 13:16:04 -0400473 const Block& b = statement.as<Block>();
John Stilesa1e2b412020-10-20 14:51:28 -0400474 return std::make_unique<Block>(offset, blockStmts(b),
475 SymbolTable::WrapIfBuiltin(b.symbolTable()),
476 b.isScope());
John Stiles44e96be2020-08-31 13:16:04 -0400477 }
478
Ethan Nicholase6592142020-09-08 10:22:09 -0400479 case Statement::Kind::kBreak:
480 case Statement::Kind::kContinue:
481 case Statement::Kind::kDiscard:
John Stiles44e96be2020-08-31 13:16:04 -0400482 return statement.clone();
483
Ethan Nicholase6592142020-09-08 10:22:09 -0400484 case Statement::Kind::kDo: {
John Stiles44e96be2020-08-31 13:16:04 -0400485 const DoStatement& d = statement.as<DoStatement>();
Ethan Nicholas1fd61162020-09-28 13:14:19 -0400486 return std::make_unique<DoStatement>(offset, stmt(d.statement()), expr(d.test()));
John Stiles44e96be2020-08-31 13:16:04 -0400487 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400488 case Statement::Kind::kExpression: {
John Stiles44e96be2020-08-31 13:16:04 -0400489 const ExpressionStatement& e = statement.as<ExpressionStatement>();
Ethan Nicholasd503a5a2020-09-30 09:29:55 -0400490 return std::make_unique<ExpressionStatement>(expr(e.expression()));
John Stiles44e96be2020-08-31 13:16:04 -0400491 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400492 case Statement::Kind::kFor: {
John Stiles44e96be2020-08-31 13:16:04 -0400493 const ForStatement& f = statement.as<ForStatement>();
494 // need to ensure initializer is evaluated first so that we've already remapped its
495 // declarations by the time we evaluate test & next
Ethan Nicholas0d31ed52020-10-05 14:47:09 -0400496 std::unique_ptr<Statement> initializer = stmt(f.initializer());
497 return std::make_unique<ForStatement>(offset, std::move(initializer), expr(f.test()),
John Stilesa1e2b412020-10-20 14:51:28 -0400498 expr(f.next()), stmt(f.statement()),
499 SymbolTable::WrapIfBuiltin(f.symbols()));
John Stiles44e96be2020-08-31 13:16:04 -0400500 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400501 case Statement::Kind::kIf: {
John Stiles44e96be2020-08-31 13:16:04 -0400502 const IfStatement& i = statement.as<IfStatement>();
Ethan Nicholas8c44eca2020-10-07 16:47:09 -0400503 return std::make_unique<IfStatement>(offset, i.isStatic(), expr(i.test()),
504 stmt(i.ifTrue()), stmt(i.ifFalse()));
John Stiles44e96be2020-08-31 13:16:04 -0400505 }
John Stiles98c1f822020-09-09 14:18:53 -0400506 case Statement::Kind::kInlineMarker:
Ethan Nicholase6592142020-09-08 10:22:09 -0400507 case Statement::Kind::kNop:
John Stiles44e96be2020-08-31 13:16:04 -0400508 return statement.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400509 case Statement::Kind::kReturn: {
John Stiles44e96be2020-08-31 13:16:04 -0400510 const ReturnStatement& r = statement.as<ReturnStatement>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -0400511 if (r.expression()) {
John Stilese41b4ee2020-09-28 12:28:16 -0400512 SkASSERT(resultExpr);
John Stilesa5f3c312020-09-22 12:05:16 -0400513 auto assignment =
514 std::make_unique<ExpressionStatement>(std::make_unique<BinaryExpression>(
515 offset,
Ethan Nicholas453f67f2020-10-09 10:43:45 -0400516 clone_with_ref_kind(*resultExpr,
517 VariableReference::RefKind::kWrite),
John Stilesa5f3c312020-09-22 12:05:16 -0400518 Token::Kind::TK_EQ,
Ethan Nicholas2a4952d2020-10-08 15:35:56 -0400519 expr(r.expression()),
John Stilese41b4ee2020-09-28 12:28:16 -0400520 &resultExpr->type()));
John Stiles44e96be2020-08-31 13:16:04 -0400521 if (haveEarlyReturns) {
John Stiles8f2a0cf2020-10-13 12:48:21 -0400522 StatementArray block;
John Stilesf4bda742020-10-14 16:57:41 -0400523 block.reserve_back(2);
John Stiles44e96be2020-08-31 13:16:04 -0400524 block.push_back(std::move(assignment));
John Stiles8f2a0cf2020-10-13 12:48:21 -0400525 block.push_back(std::make_unique<BreakStatement>(offset));
John Stiles44e96be2020-08-31 13:16:04 -0400526 return std::make_unique<Block>(offset, std::move(block), /*symbols=*/nullptr,
527 /*isScope=*/true);
528 } else {
529 return std::move(assignment);
530 }
531 } else {
532 if (haveEarlyReturns) {
533 return std::make_unique<BreakStatement>(offset);
534 } else {
535 return std::make_unique<Nop>();
536 }
537 }
538 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400539 case Statement::Kind::kSwitch: {
John Stiles44e96be2020-08-31 13:16:04 -0400540 const SwitchStatement& ss = statement.as<SwitchStatement>();
541 std::vector<std::unique_ptr<SwitchCase>> cases;
John Stiles2d4f9592020-10-30 10:29:12 -0400542 cases.reserve(ss.cases().size());
543 for (const std::unique_ptr<SwitchCase>& sc : ss.cases()) {
544 cases.push_back(std::make_unique<SwitchCase>(offset, expr(sc->value()),
545 stmts(sc->statements())));
John Stiles44e96be2020-08-31 13:16:04 -0400546 }
Ethan Nicholas01b05e52020-10-22 15:53:41 -0400547 return std::make_unique<SwitchStatement>(offset, ss.isStatic(), expr(ss.value()),
John Stilesa1e2b412020-10-20 14:51:28 -0400548 std::move(cases),
Ethan Nicholas01b05e52020-10-22 15:53:41 -0400549 SymbolTable::WrapIfBuiltin(ss.symbols()));
John Stiles44e96be2020-08-31 13:16:04 -0400550 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400551 case Statement::Kind::kVarDeclaration: {
John Stiles44e96be2020-08-31 13:16:04 -0400552 const VarDeclaration& decl = statement.as<VarDeclaration>();
John Stiles87ae34e2020-10-13 12:50:11 -0400553 ExpressionArray sizes;
John Stiles2d4f9592020-10-30 10:29:12 -0400554 sizes.reserve_back(decl.sizes().count());
555 for (const std::unique_ptr<Expression>& size : decl.sizes()) {
556 sizes.push_back(expr(size));
John Stiles44e96be2020-08-31 13:16:04 -0400557 }
Ethan Nicholasc51f33e2020-10-13 13:49:44 -0400558 std::unique_ptr<Expression> initialValue = expr(decl.value());
559 const Variable& old = decl.var();
John Stilesc75abb82020-09-14 18:24:12 -0400560 // We assign unique names to inlined variables--scopes hide most of the problems in this
561 // regard, but see `InlinerAvoidsVariableNameOverlap` for a counterexample where unique
562 // names are important.
563 auto name = std::make_unique<String>(
Ethan Nicholasc51f33e2020-10-13 13:49:44 -0400564 this->uniqueNameForInlineVar(String(old.name()), symbolTableForStatement));
John Stiles44e96be2020-08-31 13:16:04 -0400565 const String* namePtr = symbolTableForStatement->takeOwnershipOfString(std::move(name));
Ethan Nicholasc51f33e2020-10-13 13:49:44 -0400566 const Type* baseTypePtr = copy_if_needed(&decl.baseType(), *symbolTableForStatement);
567 const Type* typePtr = copy_if_needed(&old.type(), *symbolTableForStatement);
John Stiles44e96be2020-08-31 13:16:04 -0400568 const Variable* clone = symbolTableForStatement->takeOwnershipOfSymbol(
569 std::make_unique<Variable>(offset,
John Stiles586df952020-11-12 18:27:13 -0500570 &old.modifiers(),
John Stiles44e96be2020-08-31 13:16:04 -0400571 namePtr->c_str(),
Ethan Nicholas30d30222020-09-11 12:27:26 -0400572 typePtr,
Brian Osman3887a012020-09-30 13:22:27 -0400573 isBuiltinCode,
Ethan Nicholasc51f33e2020-10-13 13:49:44 -0400574 old.storage(),
John Stiles44e96be2020-08-31 13:16:04 -0400575 initialValue.get()));
Ethan Nicholasc51f33e2020-10-13 13:49:44 -0400576 (*varMap)[&old] = std::make_unique<VariableReference>(offset, clone);
Brian Osmanc0213602020-10-06 14:43:32 -0400577 return std::make_unique<VarDeclaration>(clone, baseTypePtr, std::move(sizes),
John Stiles44e96be2020-08-31 13:16:04 -0400578 std::move(initialValue));
579 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400580 case Statement::Kind::kWhile: {
John Stiles44e96be2020-08-31 13:16:04 -0400581 const WhileStatement& w = statement.as<WhileStatement>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -0400582 return std::make_unique<WhileStatement>(offset, expr(w.test()), stmt(w.statement()));
John Stiles44e96be2020-08-31 13:16:04 -0400583 }
584 default:
585 SkASSERT(false);
586 return nullptr;
587 }
588}
589
John Stiles6eadf132020-09-08 10:16:10 -0400590Inliner::InlinedCall Inliner::inlineCall(FunctionCall* call,
Brian Osman3887a012020-09-30 13:22:27 -0400591 SymbolTable* symbolTableForCall,
592 const FunctionDeclaration* caller) {
John Stiles44e96be2020-08-31 13:16:04 -0400593 // Inlining is more complicated here than in a typical compiler, because we have to have a
594 // high-level IR and can't just drop statements into the middle of an expression or even use
595 // gotos.
596 //
597 // Since we can't insert statements into an expression, we run the inline function as extra
598 // statements before the statement we're currently processing, relying on a lack of execution
599 // order guarantees. Since we can't use gotos (which are normally used to replace return
600 // statements), we wrap the whole function in a loop and use break statements to jump to the
601 // end.
602 SkASSERT(fSettings);
603 SkASSERT(fContext);
604 SkASSERT(call);
Ethan Nicholased84b732020-10-08 11:45:44 -0400605 SkASSERT(this->isSafeToInline(call->function().definition()));
John Stiles44e96be2020-08-31 13:16:04 -0400606
John Stiles8e3b6be2020-10-13 11:14:08 -0400607 ExpressionArray& arguments = call->arguments();
John Stiles6eadf132020-09-08 10:16:10 -0400608 const int offset = call->fOffset;
Ethan Nicholased84b732020-10-08 11:45:44 -0400609 const FunctionDefinition& function = *call->function().definition();
John Stiles6eadf132020-09-08 10:16:10 -0400610 const bool hasEarlyReturn = has_early_return(function);
611
John Stiles44e96be2020-08-31 13:16:04 -0400612 InlinedCall inlinedCall;
John Stiles8f2a0cf2020-10-13 12:48:21 -0400613 inlinedCall.fInlinedBody = std::make_unique<Block>(offset, StatementArray{},
John Stiles6eadf132020-09-08 10:16:10 -0400614 /*symbols=*/nullptr,
615 /*isScope=*/false);
John Stiles98c1f822020-09-09 14:18:53 -0400616
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400617 Block& inlinedBody = *inlinedCall.fInlinedBody;
John Stiles82f373c2020-10-20 13:58:05 -0400618 inlinedBody.children().reserve_back(
619 1 + // Inline marker
620 1 + // Result variable
621 arguments.size() + // Function arguments (passing in)
622 arguments.size() + // Function arguments (copy out-params back)
623 1); // Inlined code (Block or do-while loop)
John Stiles98c1f822020-09-09 14:18:53 -0400624
Ethan Nicholasceb62142020-10-09 16:51:18 -0400625 inlinedBody.children().push_back(std::make_unique<InlineMarker>(&call->function()));
John Stiles44e96be2020-08-31 13:16:04 -0400626
John Stilese41b4ee2020-09-28 12:28:16 -0400627 auto makeInlineVar =
628 [&](const String& baseName, const Type* type, Modifiers modifiers,
629 std::unique_ptr<Expression>* initialValue) -> std::unique_ptr<Expression> {
John Stilesa003e812020-09-11 09:43:49 -0400630 // $floatLiteral or $intLiteral aren't real types that we can use for scratch variables, so
631 // replace them if they ever appear here. If this happens, we likely forgot to coerce a type
632 // somewhere during compilation.
633 if (type == fContext->fFloatLiteral_Type.get()) {
John Stilesd2be5c52020-09-11 14:58:06 -0400634 SkDEBUGFAIL("found a $floatLiteral type while inlining");
John Stilesa003e812020-09-11 09:43:49 -0400635 type = fContext->fFloat_Type.get();
636 } else if (type == fContext->fIntLiteral_Type.get()) {
John Stilesd2be5c52020-09-11 14:58:06 -0400637 SkDEBUGFAIL("found an $intLiteral type while inlining");
John Stilesa003e812020-09-11 09:43:49 -0400638 type = fContext->fInt_Type.get();
639 }
640
John Stilesc75abb82020-09-14 18:24:12 -0400641 // Provide our new variable with a unique name, and add it to our symbol table.
642 String uniqueName = this->uniqueNameForInlineVar(baseName, symbolTableForCall);
John Stilescf936f92020-08-31 17:18:45 -0400643 const String* namePtr = symbolTableForCall->takeOwnershipOfString(
644 std::make_unique<String>(std::move(uniqueName)));
John Stiles44e96be2020-08-31 13:16:04 -0400645 StringFragment nameFrag{namePtr->c_str(), namePtr->length()};
646
647 // Add our new variable to the symbol table.
John Stilesb8cc6652020-10-08 09:12:07 -0400648 const Variable* variableSymbol = symbolTableForCall->add(std::make_unique<Variable>(
John Stiles586df952020-11-12 18:27:13 -0500649 /*offset=*/-1, fModifiers->addToPool(Modifiers()),
Ethan Nicholased84b732020-10-08 11:45:44 -0400650 nameFrag, type, caller->isBuiltin(),
Ethan Nicholas453f67f2020-10-09 10:43:45 -0400651 Variable::Storage::kLocal, initialValue->get()));
John Stiles44e96be2020-08-31 13:16:04 -0400652
653 // Prepare the variable declaration (taking extra care with `out` params to not clobber any
654 // initial value).
Brian Osmanc0213602020-10-06 14:43:32 -0400655 std::unique_ptr<Statement> variable;
John Stiles44e96be2020-08-31 13:16:04 -0400656 if (initialValue && (modifiers.fFlags & Modifiers::kOut_Flag)) {
Brian Osmanc0213602020-10-06 14:43:32 -0400657 variable = std::make_unique<VarDeclaration>(
John Stiles87ae34e2020-10-13 12:50:11 -0400658 variableSymbol, type, /*sizes=*/ExpressionArray{}, (*initialValue)->clone());
John Stiles44e96be2020-08-31 13:16:04 -0400659 } else {
Brian Osmanc0213602020-10-06 14:43:32 -0400660 variable = std::make_unique<VarDeclaration>(
John Stiles87ae34e2020-10-13 12:50:11 -0400661 variableSymbol, type, /*sizes=*/ExpressionArray{}, std::move(*initialValue));
John Stiles44e96be2020-08-31 13:16:04 -0400662 }
663
664 // Add the new variable-declaration statement to our block of extra statements.
Brian Osmanc0213602020-10-06 14:43:32 -0400665 inlinedBody.children().push_back(std::move(variable));
John Stiles44e96be2020-08-31 13:16:04 -0400666
John Stilese41b4ee2020-09-28 12:28:16 -0400667 return std::make_unique<VariableReference>(offset, variableSymbol);
John Stiles44e96be2020-08-31 13:16:04 -0400668 };
669
670 // Create a variable to hold the result in the extra statements (excepting void).
John Stilese41b4ee2020-09-28 12:28:16 -0400671 std::unique_ptr<Expression> resultExpr;
Ethan Nicholas0a5d0962020-10-14 13:33:18 -0400672 if (function.declaration().returnType() != *fContext->fVoid_Type) {
John Stiles44e96be2020-08-31 13:16:04 -0400673 std::unique_ptr<Expression> noInitialValue;
Ethan Nicholas0a5d0962020-10-14 13:33:18 -0400674 resultExpr = makeInlineVar(String(function.declaration().name()),
675 &function.declaration().returnType(),
John Stilese41b4ee2020-09-28 12:28:16 -0400676 Modifiers{}, &noInitialValue);
677 }
John Stiles44e96be2020-08-31 13:16:04 -0400678
679 // Create variables in the extra statements to hold the arguments, and assign the arguments to
680 // them.
681 VariableRewriteMap varMap;
John Stilese41b4ee2020-09-28 12:28:16 -0400682 std::vector<int> argsToCopyBack;
John Stiles44e96be2020-08-31 13:16:04 -0400683 for (int i = 0; i < (int) arguments.size(); ++i) {
Ethan Nicholas0a5d0962020-10-14 13:33:18 -0400684 const Variable* param = function.declaration().parameters()[i];
Ethan Nicholas041fd0a2020-10-07 16:42:04 -0400685 bool isOutParam = param->modifiers().fFlags & Modifiers::kOut_Flag;
John Stiles44e96be2020-08-31 13:16:04 -0400686
John Stiles44733aa2020-09-29 17:42:23 -0400687 // If this argument can be inlined trivially (e.g. a swizzle, or a constant array index)...
688 if (is_trivial_argument(*arguments[i])) {
John Stilese41b4ee2020-09-28 12:28:16 -0400689 // ... and it's an `out` param, or it isn't written to within the inline function...
Ethan Nicholas0a5d0962020-10-14 13:33:18 -0400690 if (isOutParam || !Analysis::StatementWritesToVariable(*function.body(), *param)) {
John Stilesf201af82020-09-29 16:57:55 -0400691 // ... we don't need to copy it at all! We can just use the existing expression.
692 varMap[param] = arguments[i]->clone();
John Stiles44e96be2020-08-31 13:16:04 -0400693 continue;
694 }
695 }
696
John Stilese41b4ee2020-09-28 12:28:16 -0400697 if (isOutParam) {
698 argsToCopyBack.push_back(i);
699 }
700
Ethan Nicholase2c49992020-10-05 11:49:11 -0400701 varMap[param] = makeInlineVar(String(param->name()), &arguments[i]->type(),
Ethan Nicholas041fd0a2020-10-07 16:42:04 -0400702 param->modifiers(), &arguments[i]);
John Stiles44e96be2020-08-31 13:16:04 -0400703 }
704
Ethan Nicholas0a5d0962020-10-14 13:33:18 -0400705 const Block& body = function.body()->as<Block>();
John Stiles8f2a0cf2020-10-13 12:48:21 -0400706 auto inlineBlock = std::make_unique<Block>(offset, StatementArray{});
John Stilesf4bda742020-10-14 16:57:41 -0400707 inlineBlock->children().reserve_back(body.children().size());
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400708 for (const std::unique_ptr<Statement>& stmt : body.children()) {
Brian Osman3887a012020-09-30 13:22:27 -0400709 inlineBlock->children().push_back(this->inlineStatement(offset, &varMap, symbolTableForCall,
710 resultExpr.get(), hasEarlyReturn,
Ethan Nicholased84b732020-10-08 11:45:44 -0400711 *stmt, caller->isBuiltin()));
John Stiles44e96be2020-08-31 13:16:04 -0400712 }
713 if (hasEarlyReturn) {
714 // Since we output to backends that don't have a goto statement (which would normally be
715 // used to perform an early return), we fake it by wrapping the function in a
716 // do { } while (false); and then use break statements to jump to the end in order to
717 // emulate a goto.
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400718 inlinedBody.children().push_back(std::make_unique<DoStatement>(
John Stiles44e96be2020-08-31 13:16:04 -0400719 /*offset=*/-1,
720 std::move(inlineBlock),
721 std::make_unique<BoolLiteral>(*fContext, offset, /*value=*/false)));
722 } else {
John Stiles6eadf132020-09-08 10:16:10 -0400723 // No early returns, so we can just dump the code in. We still need to keep the block so we
724 // don't get name conflicts with locals.
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400725 inlinedBody.children().push_back(std::move(inlineBlock));
John Stiles44e96be2020-08-31 13:16:04 -0400726 }
727
John Stilese41b4ee2020-09-28 12:28:16 -0400728 // Copy back the values of `out` parameters into their real destinations.
729 for (int i : argsToCopyBack) {
Ethan Nicholas0a5d0962020-10-14 13:33:18 -0400730 const Variable* p = function.declaration().parameters()[i];
John Stilese41b4ee2020-09-28 12:28:16 -0400731 SkASSERT(varMap.find(p) != varMap.end());
732 inlinedBody.children().push_back(
733 std::make_unique<ExpressionStatement>(std::make_unique<BinaryExpression>(
734 offset,
Ethan Nicholas453f67f2020-10-09 10:43:45 -0400735 clone_with_ref_kind(*arguments[i], VariableReference::RefKind::kWrite),
John Stilese41b4ee2020-09-28 12:28:16 -0400736 Token::Kind::TK_EQ,
737 std::move(varMap[p]),
738 &arguments[i]->type())));
John Stiles44e96be2020-08-31 13:16:04 -0400739 }
740
John Stilese41b4ee2020-09-28 12:28:16 -0400741 if (resultExpr != nullptr) {
742 // Return our result variable as our replacement expression.
Ethan Nicholas453f67f2020-10-09 10:43:45 -0400743 SkASSERT(resultExpr->as<VariableReference>().refKind() ==
744 VariableReference::RefKind::kRead);
John Stilese41b4ee2020-09-28 12:28:16 -0400745 inlinedCall.fReplacementExpr = std::move(resultExpr);
John Stiles44e96be2020-08-31 13:16:04 -0400746 } else {
747 // It's a void function, so it doesn't actually result in anything, but we have to return
748 // something non-null as a standin.
Ethan Nicholas041fd0a2020-10-07 16:42:04 -0400749 inlinedCall.fReplacementExpr = std::make_unique<BoolLiteral>(*fContext,
750 offset,
John Stiles44e96be2020-08-31 13:16:04 -0400751 /*value=*/false);
752 }
753
John Stiles44e96be2020-08-31 13:16:04 -0400754 return inlinedCall;
755}
756
John Stiles2d7973a2020-10-02 15:01:03 -0400757bool Inliner::isSafeToInline(const FunctionDefinition* functionDef) {
John Stiles44e96be2020-08-31 13:16:04 -0400758 SkASSERT(fSettings);
759
John Stiles1c03d332020-10-13 10:30:23 -0400760 // A threshold of zero indicates that the inliner is completely disabled, so we can just return.
761 if (fSettings->fInlineThreshold <= 0) {
762 return false;
763 }
764
John Stiles031a7672020-11-13 16:13:18 -0500765 // Enforce a limit on inlining to avoid pathological cases. (inliner/ExponentialGrowth.sksl)
766 if (fInlinedStatementCounter >= kInlinedStatementLimit) {
767 return false;
768 }
769
John Stiles2d7973a2020-10-02 15:01:03 -0400770 if (functionDef == nullptr) {
John Stiles44e96be2020-08-31 13:16:04 -0400771 // Can't inline something if we don't actually have its definition.
772 return false;
773 }
John Stiles2d7973a2020-10-02 15:01:03 -0400774
Brian Osmand7e76592020-11-02 12:26:22 -0500775 if (!fCaps || !fCaps->canUseDoLoops()) {
John Stiles44e96be2020-08-31 13:16:04 -0400776 // We don't have do-while loops. We use do-while loops to simulate early returns, so we
777 // can't inline functions that have an early return.
John Stiles2d7973a2020-10-02 15:01:03 -0400778 bool hasEarlyReturn = has_early_return(*functionDef);
John Stiles44e96be2020-08-31 13:16:04 -0400779
780 // If we didn't detect an early return, there shouldn't be any returns in breakable
781 // constructs either.
John Stiles2d7973a2020-10-02 15:01:03 -0400782 SkASSERT(hasEarlyReturn || count_returns_in_breakable_constructs(*functionDef) == 0);
John Stiles44e96be2020-08-31 13:16:04 -0400783 return !hasEarlyReturn;
784 }
785 // We have do-while loops, but we don't have any mechanism to simulate early returns within a
786 // 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 -0400787 bool hasReturnInBreakableConstruct = (count_returns_in_breakable_constructs(*functionDef) > 0);
John Stiles44e96be2020-08-31 13:16:04 -0400788
789 // If we detected returns in breakable constructs, we should also detect an early return.
John Stiles2d7973a2020-10-02 15:01:03 -0400790 SkASSERT(!hasReturnInBreakableConstruct || has_early_return(*functionDef));
John Stiles44e96be2020-08-31 13:16:04 -0400791 return !hasReturnInBreakableConstruct;
792}
793
John Stiles2d7973a2020-10-02 15:01:03 -0400794// A candidate function for inlining, containing everything that `inlineCall` needs.
795struct InlineCandidate {
796 SymbolTable* fSymbols; // the SymbolTable of the candidate
797 std::unique_ptr<Statement>* fParentStmt; // the parent Statement of the enclosing stmt
798 std::unique_ptr<Statement>* fEnclosingStmt; // the Statement containing the candidate
799 std::unique_ptr<Expression>* fCandidateExpr; // the candidate FunctionCall to be inlined
800 FunctionDefinition* fEnclosingFunction; // the Function containing the candidate
801 bool fIsLargeFunction; // does candidate exceed the inline threshold?
802};
John Stiles93442622020-09-11 12:11:27 -0400803
John Stiles2d7973a2020-10-02 15:01:03 -0400804struct InlineCandidateList {
805 std::vector<InlineCandidate> fCandidates;
806};
807
808class InlineCandidateAnalyzer {
John Stiles70957c82020-10-02 16:42:10 -0400809public:
810 // A list of all the inlining candidates we found during analysis.
811 InlineCandidateList* fCandidateList;
John Stiles2d7973a2020-10-02 15:01:03 -0400812
John Stiles70957c82020-10-02 16:42:10 -0400813 // A stack of the symbol tables; since most nodes don't have one, expected to be shallower than
814 // the enclosing-statement stack.
815 std::vector<SymbolTable*> fSymbolTableStack;
816 // A stack of "enclosing" statements--these would be suitable for the inliner to use for adding
817 // new instructions. Not all statements are suitable (e.g. a for-loop's initializer). The
818 // inliner might replace a statement with a block containing the statement.
819 std::vector<std::unique_ptr<Statement>*> fEnclosingStmtStack;
820 // The function that we're currently processing (i.e. inlining into).
821 FunctionDefinition* fEnclosingFunction = nullptr;
John Stiles93442622020-09-11 12:11:27 -0400822
Brian Osman0006ad02020-11-18 15:38:39 -0500823 void visit(const std::vector<std::unique_ptr<ProgramElement>>& elements,
824 SymbolTable* symbols,
825 InlineCandidateList* candidateList) {
John Stiles70957c82020-10-02 16:42:10 -0400826 fCandidateList = candidateList;
Brian Osman0006ad02020-11-18 15:38:39 -0500827 fSymbolTableStack.push_back(symbols);
John Stiles93442622020-09-11 12:11:27 -0400828
Brian Osman0006ad02020-11-18 15:38:39 -0500829 for (const std::unique_ptr<ProgramElement>& pe : elements) {
Brian Osman1179fcf2020-10-08 16:04:40 -0400830 this->visitProgramElement(pe.get());
John Stiles93442622020-09-11 12:11:27 -0400831 }
832
John Stiles70957c82020-10-02 16:42:10 -0400833 fSymbolTableStack.pop_back();
834 fCandidateList = nullptr;
835 }
836
837 void visitProgramElement(ProgramElement* pe) {
838 switch (pe->kind()) {
839 case ProgramElement::Kind::kFunction: {
840 FunctionDefinition& funcDef = pe->as<FunctionDefinition>();
Brian Osman0006ad02020-11-18 15:38:39 -0500841 fEnclosingFunction = &funcDef;
842 this->visitStatement(&funcDef.body());
John Stiles70957c82020-10-02 16:42:10 -0400843 break;
John Stiles93442622020-09-11 12:11:27 -0400844 }
John Stiles70957c82020-10-02 16:42:10 -0400845 default:
846 // The inliner can't operate outside of a function's scope.
847 break;
848 }
849 }
850
851 void visitStatement(std::unique_ptr<Statement>* stmt,
852 bool isViableAsEnclosingStatement = true) {
853 if (!*stmt) {
854 return;
John Stiles93442622020-09-11 12:11:27 -0400855 }
856
John Stiles70957c82020-10-02 16:42:10 -0400857 size_t oldEnclosingStmtStackSize = fEnclosingStmtStack.size();
858 size_t oldSymbolStackSize = fSymbolTableStack.size();
John Stiles93442622020-09-11 12:11:27 -0400859
John Stiles70957c82020-10-02 16:42:10 -0400860 if (isViableAsEnclosingStatement) {
861 fEnclosingStmtStack.push_back(stmt);
John Stiles93442622020-09-11 12:11:27 -0400862 }
863
John Stiles70957c82020-10-02 16:42:10 -0400864 switch ((*stmt)->kind()) {
865 case Statement::Kind::kBreak:
866 case Statement::Kind::kContinue:
867 case Statement::Kind::kDiscard:
868 case Statement::Kind::kInlineMarker:
869 case Statement::Kind::kNop:
870 break;
871
872 case Statement::Kind::kBlock: {
873 Block& block = (*stmt)->as<Block>();
874 if (block.symbolTable()) {
875 fSymbolTableStack.push_back(block.symbolTable().get());
876 }
877
878 for (std::unique_ptr<Statement>& stmt : block.children()) {
879 this->visitStatement(&stmt);
880 }
881 break;
John Stiles93442622020-09-11 12:11:27 -0400882 }
John Stiles70957c82020-10-02 16:42:10 -0400883 case Statement::Kind::kDo: {
884 DoStatement& doStmt = (*stmt)->as<DoStatement>();
885 // The loop body is a candidate for inlining.
886 this->visitStatement(&doStmt.statement());
887 // The inliner isn't smart enough to inline the test-expression for a do-while
888 // loop at this time. There are two limitations:
889 // - We would need to insert the inlined-body block at the very end of the do-
890 // statement's inner fStatement. We don't support that today, but it's doable.
891 // - We cannot inline the test expression if the loop uses `continue` anywhere; that
892 // would skip over the inlined block that evaluates the test expression. There
893 // isn't a good fix for this--any workaround would be more complex than the cost
894 // of a function call. However, loops that don't use `continue` would still be
895 // viable candidates for inlining.
896 break;
John Stiles93442622020-09-11 12:11:27 -0400897 }
John Stiles70957c82020-10-02 16:42:10 -0400898 case Statement::Kind::kExpression: {
899 ExpressionStatement& expr = (*stmt)->as<ExpressionStatement>();
900 this->visitExpression(&expr.expression());
901 break;
902 }
903 case Statement::Kind::kFor: {
904 ForStatement& forStmt = (*stmt)->as<ForStatement>();
Ethan Nicholas0d31ed52020-10-05 14:47:09 -0400905 if (forStmt.symbols()) {
906 fSymbolTableStack.push_back(forStmt.symbols().get());
John Stiles70957c82020-10-02 16:42:10 -0400907 }
908
909 // The initializer and loop body are candidates for inlining.
Ethan Nicholas0d31ed52020-10-05 14:47:09 -0400910 this->visitStatement(&forStmt.initializer(),
John Stiles70957c82020-10-02 16:42:10 -0400911 /*isViableAsEnclosingStatement=*/false);
Ethan Nicholas0d31ed52020-10-05 14:47:09 -0400912 this->visitStatement(&forStmt.statement());
John Stiles70957c82020-10-02 16:42:10 -0400913
914 // The inliner isn't smart enough to inline the test- or increment-expressions
915 // of a for loop loop at this time. There are a handful of limitations:
916 // - We would need to insert the test-expression block at the very beginning of the
917 // for-loop's inner fStatement, and the increment-expression block at the very
918 // end. We don't support that today, but it's doable.
919 // - The for-loop's built-in test-expression would need to be dropped entirely,
920 // and the loop would be halted via a break statement at the end of the inlined
921 // test-expression. This is again something we don't support today, but it could
922 // be implemented.
923 // - We cannot inline the increment-expression if the loop uses `continue` anywhere;
924 // that would skip over the inlined block that evaluates the increment expression.
925 // There isn't a good fix for this--any workaround would be more complex than the
926 // cost of a function call. However, loops that don't use `continue` would still
927 // be viable candidates for increment-expression inlining.
928 break;
929 }
930 case Statement::Kind::kIf: {
931 IfStatement& ifStmt = (*stmt)->as<IfStatement>();
Ethan Nicholas8c44eca2020-10-07 16:47:09 -0400932 this->visitExpression(&ifStmt.test());
933 this->visitStatement(&ifStmt.ifTrue());
934 this->visitStatement(&ifStmt.ifFalse());
John Stiles70957c82020-10-02 16:42:10 -0400935 break;
936 }
937 case Statement::Kind::kReturn: {
938 ReturnStatement& returnStmt = (*stmt)->as<ReturnStatement>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -0400939 this->visitExpression(&returnStmt.expression());
John Stiles70957c82020-10-02 16:42:10 -0400940 break;
941 }
942 case Statement::Kind::kSwitch: {
943 SwitchStatement& switchStmt = (*stmt)->as<SwitchStatement>();
Ethan Nicholas01b05e52020-10-22 15:53:41 -0400944 if (switchStmt.symbols()) {
945 fSymbolTableStack.push_back(switchStmt.symbols().get());
John Stiles70957c82020-10-02 16:42:10 -0400946 }
947
Ethan Nicholas01b05e52020-10-22 15:53:41 -0400948 this->visitExpression(&switchStmt.value());
John Stiles2d4f9592020-10-30 10:29:12 -0400949 for (const std::unique_ptr<SwitchCase>& switchCase : switchStmt.cases()) {
John Stiles70957c82020-10-02 16:42:10 -0400950 // The switch-case's fValue cannot be a FunctionCall; skip it.
John Stiles2d4f9592020-10-30 10:29:12 -0400951 for (std::unique_ptr<Statement>& caseBlock : switchCase->statements()) {
John Stiles70957c82020-10-02 16:42:10 -0400952 this->visitStatement(&caseBlock);
953 }
954 }
955 break;
956 }
957 case Statement::Kind::kVarDeclaration: {
958 VarDeclaration& varDeclStmt = (*stmt)->as<VarDeclaration>();
959 // Don't need to scan the declaration's sizes; those are always IntLiterals.
Ethan Nicholasc51f33e2020-10-13 13:49:44 -0400960 this->visitExpression(&varDeclStmt.value());
John Stiles70957c82020-10-02 16:42:10 -0400961 break;
962 }
John Stiles70957c82020-10-02 16:42:10 -0400963 case Statement::Kind::kWhile: {
964 WhileStatement& whileStmt = (*stmt)->as<WhileStatement>();
965 // The loop body is a candidate for inlining.
Ethan Nicholas2a4952d2020-10-08 15:35:56 -0400966 this->visitStatement(&whileStmt.statement());
John Stiles70957c82020-10-02 16:42:10 -0400967 // The inliner isn't smart enough to inline the test-expression for a while loop at
968 // this time. There are two limitations:
969 // - We would need to insert the inlined-body block at the very beginning of the
970 // while loop's inner fStatement. We don't support that today, but it's doable.
971 // - The while-loop's built-in test-expression would need to be replaced with a
972 // `true` BoolLiteral, and the loop would be halted via a break statement at the
973 // end of the inlined test-expression. This is again something we don't support
974 // today, but it could be implemented.
975 break;
976 }
977 default:
978 SkUNREACHABLE;
John Stiles93442622020-09-11 12:11:27 -0400979 }
980
John Stiles70957c82020-10-02 16:42:10 -0400981 // Pop our symbol and enclosing-statement stacks.
982 fSymbolTableStack.resize(oldSymbolStackSize);
983 fEnclosingStmtStack.resize(oldEnclosingStmtStackSize);
984 }
985
986 void visitExpression(std::unique_ptr<Expression>* expr) {
987 if (!*expr) {
988 return;
John Stiles93442622020-09-11 12:11:27 -0400989 }
John Stiles70957c82020-10-02 16:42:10 -0400990
991 switch ((*expr)->kind()) {
992 case Expression::Kind::kBoolLiteral:
993 case Expression::Kind::kDefined:
994 case Expression::Kind::kExternalValue:
995 case Expression::Kind::kFieldAccess:
996 case Expression::Kind::kFloatLiteral:
997 case Expression::Kind::kFunctionReference:
998 case Expression::Kind::kIntLiteral:
999 case Expression::Kind::kNullLiteral:
1000 case Expression::Kind::kSetting:
1001 case Expression::Kind::kTypeReference:
1002 case Expression::Kind::kVariableReference:
1003 // Nothing to scan here.
1004 break;
1005
1006 case Expression::Kind::kBinary: {
1007 BinaryExpression& binaryExpr = (*expr)->as<BinaryExpression>();
John Stiles2d4f9592020-10-30 10:29:12 -04001008 this->visitExpression(&binaryExpr.left());
John Stiles70957c82020-10-02 16:42:10 -04001009
1010 // Logical-and and logical-or binary expressions do not inline the right side,
1011 // because that would invalidate short-circuiting. That is, when evaluating
1012 // expressions like these:
1013 // (false && x()) // always false
1014 // (true || y()) // always true
1015 // It is illegal for side-effects from x() or y() to occur. The simplest way to
1016 // enforce that rule is to avoid inlining the right side entirely. However, it is
1017 // safe for other types of binary expression to inline both sides.
1018 Token::Kind op = binaryExpr.getOperator();
1019 bool shortCircuitable = (op == Token::Kind::TK_LOGICALAND ||
1020 op == Token::Kind::TK_LOGICALOR);
1021 if (!shortCircuitable) {
John Stiles2d4f9592020-10-30 10:29:12 -04001022 this->visitExpression(&binaryExpr.right());
John Stiles70957c82020-10-02 16:42:10 -04001023 }
1024 break;
1025 }
1026 case Expression::Kind::kConstructor: {
1027 Constructor& constructorExpr = (*expr)->as<Constructor>();
1028 for (std::unique_ptr<Expression>& arg : constructorExpr.arguments()) {
1029 this->visitExpression(&arg);
1030 }
1031 break;
1032 }
1033 case Expression::Kind::kExternalFunctionCall: {
1034 ExternalFunctionCall& funcCallExpr = (*expr)->as<ExternalFunctionCall>();
1035 for (std::unique_ptr<Expression>& arg : funcCallExpr.arguments()) {
1036 this->visitExpression(&arg);
1037 }
1038 break;
1039 }
1040 case Expression::Kind::kFunctionCall: {
1041 FunctionCall& funcCallExpr = (*expr)->as<FunctionCall>();
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001042 for (std::unique_ptr<Expression>& arg : funcCallExpr.arguments()) {
John Stiles70957c82020-10-02 16:42:10 -04001043 this->visitExpression(&arg);
1044 }
1045 this->addInlineCandidate(expr);
1046 break;
1047 }
1048 case Expression::Kind::kIndex:{
1049 IndexExpression& indexExpr = (*expr)->as<IndexExpression>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04001050 this->visitExpression(&indexExpr.base());
1051 this->visitExpression(&indexExpr.index());
John Stiles70957c82020-10-02 16:42:10 -04001052 break;
1053 }
1054 case Expression::Kind::kPostfix: {
1055 PostfixExpression& postfixExpr = (*expr)->as<PostfixExpression>();
Ethan Nicholas444ccc62020-10-09 10:16:22 -04001056 this->visitExpression(&postfixExpr.operand());
John Stiles70957c82020-10-02 16:42:10 -04001057 break;
1058 }
1059 case Expression::Kind::kPrefix: {
1060 PrefixExpression& prefixExpr = (*expr)->as<PrefixExpression>();
Ethan Nicholas444ccc62020-10-09 10:16:22 -04001061 this->visitExpression(&prefixExpr.operand());
John Stiles70957c82020-10-02 16:42:10 -04001062 break;
1063 }
1064 case Expression::Kind::kSwizzle: {
1065 Swizzle& swizzleExpr = (*expr)->as<Swizzle>();
Ethan Nicholas6b4d5812020-10-12 16:11:51 -04001066 this->visitExpression(&swizzleExpr.base());
John Stiles70957c82020-10-02 16:42:10 -04001067 break;
1068 }
1069 case Expression::Kind::kTernary: {
1070 TernaryExpression& ternaryExpr = (*expr)->as<TernaryExpression>();
1071 // The test expression is a candidate for inlining.
Ethan Nicholasdd218162020-10-08 05:48:01 -04001072 this->visitExpression(&ternaryExpr.test());
John Stiles70957c82020-10-02 16:42:10 -04001073 // The true- and false-expressions cannot be inlined, because we are only allowed to
1074 // evaluate one side.
1075 break;
1076 }
1077 default:
1078 SkUNREACHABLE;
1079 }
1080 }
1081
1082 void addInlineCandidate(std::unique_ptr<Expression>* candidate) {
1083 fCandidateList->fCandidates.push_back(
1084 InlineCandidate{fSymbolTableStack.back(),
1085 find_parent_statement(fEnclosingStmtStack),
1086 fEnclosingStmtStack.back(),
1087 candidate,
1088 fEnclosingFunction,
1089 /*isLargeFunction=*/false});
1090 }
John Stiles2d7973a2020-10-02 15:01:03 -04001091};
John Stiles93442622020-09-11 12:11:27 -04001092
John Stiles2d7973a2020-10-02 15:01:03 -04001093bool Inliner::candidateCanBeInlined(const InlineCandidate& candidate, InlinabilityCache* cache) {
John Stiles1c03d332020-10-13 10:30:23 -04001094 const FunctionDeclaration& funcDecl =
1095 (*candidate.fCandidateExpr)->as<FunctionCall>().function();
John Stiles915a38c2020-09-14 09:38:13 -04001096
John Stiles1c03d332020-10-13 10:30:23 -04001097 auto [iter, wasInserted] = cache->insert({&funcDecl, false});
John Stiles2d7973a2020-10-02 15:01:03 -04001098 if (wasInserted) {
1099 // Recursion is forbidden here to avoid an infinite death spiral of inlining.
John Stiles1c03d332020-10-13 10:30:23 -04001100 iter->second = this->isSafeToInline(funcDecl.definition()) &&
1101 !contains_recursive_call(funcDecl);
John Stiles93442622020-09-11 12:11:27 -04001102 }
1103
John Stiles2d7973a2020-10-02 15:01:03 -04001104 return iter->second;
1105}
1106
John Stiles1c03d332020-10-13 10:30:23 -04001107bool Inliner::isLargeFunction(const FunctionDefinition* functionDef) {
1108 return Analysis::NodeCountExceeds(*functionDef, fSettings->fInlineThreshold);
1109}
John Stiles2d7973a2020-10-02 15:01:03 -04001110
John Stiles1c03d332020-10-13 10:30:23 -04001111bool Inliner::isLargeFunction(const InlineCandidate& candidate, LargeFunctionCache* cache) {
1112 const FunctionDeclaration& funcDecl =
1113 (*candidate.fCandidateExpr)->as<FunctionCall>().function();
1114
1115 auto [iter, wasInserted] = cache->insert({&funcDecl, false});
John Stiles2d7973a2020-10-02 15:01:03 -04001116 if (wasInserted) {
John Stiles1c03d332020-10-13 10:30:23 -04001117 iter->second = this->isLargeFunction(funcDecl.definition());
John Stiles2d7973a2020-10-02 15:01:03 -04001118 }
1119
1120 return iter->second;
1121}
1122
Brian Osman0006ad02020-11-18 15:38:39 -05001123void Inliner::buildCandidateList(const std::vector<std::unique_ptr<ProgramElement>>& elements,
1124 SymbolTable* symbols,
1125 InlineCandidateList* candidateList) {
John Stiles2d7973a2020-10-02 15:01:03 -04001126 // This is structured much like a ProgramVisitor, but does not actually use ProgramVisitor.
1127 // The analyzer needs to keep track of the `unique_ptr<T>*` of statements and expressions so
1128 // that they can later be replaced, and ProgramVisitor does not provide this; it only provides a
1129 // `const T&`.
1130 InlineCandidateAnalyzer analyzer;
Brian Osman0006ad02020-11-18 15:38:39 -05001131 analyzer.visit(elements, symbols, candidateList);
John Stiles2d7973a2020-10-02 15:01:03 -04001132
1133 // Remove candidates that are not safe to inline.
1134 std::vector<InlineCandidate>& candidates = candidateList->fCandidates;
1135 InlinabilityCache cache;
1136 candidates.erase(std::remove_if(candidates.begin(),
1137 candidates.end(),
1138 [&](const InlineCandidate& candidate) {
1139 return !this->candidateCanBeInlined(candidate, &cache);
1140 }),
1141 candidates.end());
1142
1143 // Determine whether each candidate function exceeds our inlining size threshold or not. These
1144 // can still be valid candidates if they are only called one time, so we don't remove them from
1145 // the candidate list, but they will not be inlined if they're called more than once.
1146 LargeFunctionCache largeFunctionCache;
1147 for (InlineCandidate& candidate : candidates) {
1148 candidate.fIsLargeFunction = this->isLargeFunction(candidate, &largeFunctionCache);
1149 }
1150}
1151
Brian Osman0006ad02020-11-18 15:38:39 -05001152bool Inliner::analyze(const std::vector<std::unique_ptr<ProgramElement>>& elements,
1153 SymbolTable* symbols,
1154 ProgramUsage* usage) {
John Stilesd34d56e2020-10-12 12:04:47 -04001155 // A threshold of zero indicates that the inliner is completely disabled, so we can just return.
1156 if (fSettings->fInlineThreshold <= 0) {
1157 return false;
1158 }
1159
John Stiles031a7672020-11-13 16:13:18 -05001160 // Enforce a limit on inlining to avoid pathological cases. (inliner/ExponentialGrowth.sksl)
1161 if (fInlinedStatementCounter >= kInlinedStatementLimit) {
1162 return false;
1163 }
1164
John Stiles2d7973a2020-10-02 15:01:03 -04001165 InlineCandidateList candidateList;
Brian Osman0006ad02020-11-18 15:38:39 -05001166 this->buildCandidateList(elements, symbols, &candidateList);
John Stiles2d7973a2020-10-02 15:01:03 -04001167
John Stiles915a38c2020-09-14 09:38:13 -04001168 // Inline the candidates where we've determined that it's safe to do so.
1169 std::unordered_set<const std::unique_ptr<Statement>*> enclosingStmtSet;
1170 bool madeChanges = false;
John Stiles2d7973a2020-10-02 15:01:03 -04001171 for (const InlineCandidate& candidate : candidateList.fCandidates) {
John Stiles915a38c2020-09-14 09:38:13 -04001172 FunctionCall& funcCall = (*candidate.fCandidateExpr)->as<FunctionCall>();
Brian Osman010ce6a2020-10-19 16:34:10 -04001173 const FunctionDeclaration& funcDecl = funcCall.function();
John Stiles915a38c2020-09-14 09:38:13 -04001174
John Stiles2d7973a2020-10-02 15:01:03 -04001175 // If the function is large, not marked `inline`, and is called more than once, it's a bad
1176 // idea to inline it.
1177 if (candidate.fIsLargeFunction &&
Brian Osman010ce6a2020-10-19 16:34:10 -04001178 !(funcDecl.modifiers().fFlags & Modifiers::kInline_Flag) && usage->get(funcDecl) > 1) {
John Stiles915a38c2020-09-14 09:38:13 -04001179 continue;
1180 }
1181
1182 // Inlining two expressions using the same enclosing statement in the same inlining pass
1183 // does not work properly. If this happens, skip it; we'll get it in the next pass.
1184 auto [unusedIter, inserted] = enclosingStmtSet.insert(candidate.fEnclosingStmt);
1185 if (!inserted) {
1186 continue;
1187 }
1188
1189 // Convert the function call to its inlined equivalent.
Brian Osman3887a012020-09-30 13:22:27 -04001190 InlinedCall inlinedCall = this->inlineCall(&funcCall, candidate.fSymbols,
Ethan Nicholas0a5d0962020-10-14 13:33:18 -04001191 &candidate.fEnclosingFunction->declaration());
John Stiles915a38c2020-09-14 09:38:13 -04001192 if (inlinedCall.fInlinedBody) {
1193 // Ensure that the inlined body has a scope if it needs one.
John Stiles6d696082020-10-01 10:18:54 -04001194 this->ensureScopedBlocks(inlinedCall.fInlinedBody.get(), candidate.fParentStmt->get());
John Stiles915a38c2020-09-14 09:38:13 -04001195
Brian Osman010ce6a2020-10-19 16:34:10 -04001196 // Add references within the inlined body
1197 usage->add(inlinedCall.fInlinedBody.get());
1198
John Stiles915a38c2020-09-14 09:38:13 -04001199 // Move the enclosing statement to the end of the unscoped Block containing the inlined
1200 // function, then replace the enclosing statement with that Block.
1201 // Before:
1202 // fInlinedBody = Block{ stmt1, stmt2, stmt3 }
1203 // fEnclosingStmt = stmt4
1204 // After:
1205 // fInlinedBody = null
1206 // fEnclosingStmt = Block{ stmt1, stmt2, stmt3, stmt4 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001207 inlinedCall.fInlinedBody->children().push_back(std::move(*candidate.fEnclosingStmt));
John Stiles915a38c2020-09-14 09:38:13 -04001208 *candidate.fEnclosingStmt = std::move(inlinedCall.fInlinedBody);
1209 }
1210
1211 // Replace the candidate function call with our replacement expression.
Brian Osman010ce6a2020-10-19 16:34:10 -04001212 usage->replace(candidate.fCandidateExpr->get(), inlinedCall.fReplacementExpr.get());
John Stiles915a38c2020-09-14 09:38:13 -04001213 *candidate.fCandidateExpr = std::move(inlinedCall.fReplacementExpr);
1214 madeChanges = true;
1215
John Stiles031a7672020-11-13 16:13:18 -05001216 // Stop inlining if we've reached our hard cap on new statements.
1217 if (fInlinedStatementCounter >= kInlinedStatementLimit) {
1218 break;
1219 }
1220
John Stiles915a38c2020-09-14 09:38:13 -04001221 // Note that nothing was destroyed except for the FunctionCall. All other nodes should
1222 // remain valid.
1223 }
1224
1225 return madeChanges;
John Stiles93442622020-09-11 12:11:27 -04001226}
1227
John Stiles44e96be2020-08-31 13:16:04 -04001228} // namespace SkSL