blob: 2688aa93dc67696eab9c229c545e327b3dcd865d [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 Stiles44e96be2020-08-31 13:16:04 -0400251} // namespace
252
John Stilesb61ee902020-09-21 12:26:59 -0400253void Inliner::ensureScopedBlocks(Statement* inlinedBody, Statement* parentStmt) {
254 // No changes necessary if this statement isn't actually a block.
255 if (!inlinedBody || !inlinedBody->is<Block>()) {
256 return;
257 }
258
259 // No changes necessary if the parent statement doesn't require a scope.
260 if (!parentStmt || !(parentStmt->is<IfStatement>() || parentStmt->is<ForStatement>() ||
261 parentStmt->is<DoStatement>() || parentStmt->is<WhileStatement>())) {
262 return;
263 }
264
265 Block& block = inlinedBody->as<Block>();
266
267 // The inliner will create inlined function bodies as a Block containing multiple statements,
268 // but no scope. Normally, this is fine, but if this block is used as the statement for a
269 // do/for/if/while, this isn't actually possible to represent textually; a scope must be added
270 // for the generated code to match the intent. In the case of Blocks nested inside other Blocks,
271 // we add the scope to the outermost block if needed. Zero-statement blocks have similar
272 // issues--if we don't represent the Block textually somehow, we run the risk of accidentally
273 // absorbing the following statement into our loop--so we also add a scope to these.
274 for (Block* nestedBlock = &block;; ) {
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400275 if (nestedBlock->isScope()) {
John Stilesb61ee902020-09-21 12:26:59 -0400276 // We found an explicit scope; all is well.
277 return;
278 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400279 if (nestedBlock->children().size() != 1) {
John Stilesb61ee902020-09-21 12:26:59 -0400280 // We found a block with multiple (or zero) statements, but no scope? Let's add a scope
281 // to the outermost block.
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400282 block.setIsScope(true);
John Stilesb61ee902020-09-21 12:26:59 -0400283 return;
284 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400285 if (!nestedBlock->children()[0]->is<Block>()) {
John Stilesb61ee902020-09-21 12:26:59 -0400286 // This block has exactly one thing inside, and it's not another block. No need to scope
287 // it.
288 return;
289 }
290 // We have to go deeper.
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400291 nestedBlock = &nestedBlock->children()[0]->as<Block>();
John Stilesb61ee902020-09-21 12:26:59 -0400292 }
293}
294
Brian Osman0006ad02020-11-18 15:38:39 -0500295void Inliner::reset(ModifiersPool* modifiers, const Program::Settings* settings) {
Ethan Nicholas041fd0a2020-10-07 16:42:04 -0400296 fModifiers = modifiers;
297 fSettings = settings;
John Stiles44e96be2020-08-31 13:16:04 -0400298 fInlineVarCounter = 0;
John Stiles031a7672020-11-13 16:13:18 -0500299 fInlinedStatementCounter = 0;
John Stiles44e96be2020-08-31 13:16:04 -0400300}
301
John Stilesc75abb82020-09-14 18:24:12 -0400302String Inliner::uniqueNameForInlineVar(const String& baseName, SymbolTable* symbolTable) {
303 // If the base name starts with an underscore, like "_coords", we can't append another
304 // underscore, because OpenGL disallows two consecutive underscores anywhere in the string. But
305 // in the general case, using the underscore as a splitter reads nicely enough that it's worth
306 // putting in this special case.
307 const char* splitter = baseName.startsWith("_") ? "" : "_";
308
309 // Append a unique numeric prefix to avoid name overlap. Check the symbol table to make sure
310 // we're not reusing an existing name. (Note that within a single compilation pass, this check
311 // isn't fully comprehensive, as code isn't always generated in top-to-bottom order.)
312 String uniqueName;
313 for (;;) {
314 uniqueName = String::printf("_%d%s%s", fInlineVarCounter++, splitter, baseName.c_str());
315 StringFragment frag{uniqueName.data(), uniqueName.length()};
316 if ((*symbolTable)[frag] == nullptr) {
317 break;
318 }
319 }
320
321 return uniqueName;
322}
323
John Stiles44e96be2020-08-31 13:16:04 -0400324std::unique_ptr<Expression> Inliner::inlineExpression(int offset,
325 VariableRewriteMap* varMap,
326 const Expression& expression) {
327 auto expr = [&](const std::unique_ptr<Expression>& e) -> std::unique_ptr<Expression> {
328 if (e) {
329 return this->inlineExpression(offset, varMap, *e);
330 }
331 return nullptr;
332 };
John Stiles8e3b6be2020-10-13 11:14:08 -0400333 auto argList = [&](const ExpressionArray& originalArgs) -> ExpressionArray {
334 ExpressionArray args;
John Stilesf4bda742020-10-14 16:57:41 -0400335 args.reserve_back(originalArgs.size());
John Stiles44e96be2020-08-31 13:16:04 -0400336 for (const std::unique_ptr<Expression>& arg : originalArgs) {
337 args.push_back(expr(arg));
338 }
339 return args;
340 };
341
Ethan Nicholase6592142020-09-08 10:22:09 -0400342 switch (expression.kind()) {
343 case Expression::Kind::kBinary: {
John Stiles44e96be2020-08-31 13:16:04 -0400344 const BinaryExpression& b = expression.as<BinaryExpression>();
345 return std::make_unique<BinaryExpression>(offset,
John Stiles2d4f9592020-10-30 10:29:12 -0400346 expr(b.left()),
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400347 b.getOperator(),
John Stiles2d4f9592020-10-30 10:29:12 -0400348 expr(b.right()),
Ethan Nicholas30d30222020-09-11 12:27:26 -0400349 &b.type());
John Stiles44e96be2020-08-31 13:16:04 -0400350 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400351 case Expression::Kind::kBoolLiteral:
352 case Expression::Kind::kIntLiteral:
353 case Expression::Kind::kFloatLiteral:
354 case Expression::Kind::kNullLiteral:
John Stiles44e96be2020-08-31 13:16:04 -0400355 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400356 case Expression::Kind::kConstructor: {
John Stiles44e96be2020-08-31 13:16:04 -0400357 const Constructor& constructor = expression.as<Constructor>();
Ethan Nicholas30d30222020-09-11 12:27:26 -0400358 return std::make_unique<Constructor>(offset, &constructor.type(),
Ethan Nicholasf70f0442020-09-29 12:41:35 -0400359 argList(constructor.arguments()));
John Stiles44e96be2020-08-31 13:16:04 -0400360 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400361 case Expression::Kind::kExternalFunctionCall: {
John Stiles44e96be2020-08-31 13:16:04 -0400362 const ExternalFunctionCall& externalCall = expression.as<ExternalFunctionCall>();
Ethan Nicholas444ccc62020-10-09 10:16:22 -0400363 return std::make_unique<ExternalFunctionCall>(offset, &externalCall.function(),
Ethan Nicholas6e86ec92020-09-30 14:29:56 -0400364 argList(externalCall.arguments()));
John Stiles44e96be2020-08-31 13:16:04 -0400365 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400366 case Expression::Kind::kExternalValue:
John Stiles44e96be2020-08-31 13:16:04 -0400367 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400368 case Expression::Kind::kFieldAccess: {
John Stiles44e96be2020-08-31 13:16:04 -0400369 const FieldAccess& f = expression.as<FieldAccess>();
Ethan Nicholas7a95b202020-10-09 11:55:40 -0400370 return std::make_unique<FieldAccess>(expr(f.base()), f.fieldIndex(), f.ownerKind());
John Stiles44e96be2020-08-31 13:16:04 -0400371 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400372 case Expression::Kind::kFunctionCall: {
John Stiles44e96be2020-08-31 13:16:04 -0400373 const FunctionCall& funcCall = expression.as<FunctionCall>();
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400374 return std::make_unique<FunctionCall>(offset, &funcCall.type(), &funcCall.function(),
375 argList(funcCall.arguments()));
John Stiles44e96be2020-08-31 13:16:04 -0400376 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400377 case Expression::Kind::kFunctionReference:
Brian Osman2b3b35f2020-09-08 09:17:36 -0400378 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400379 case Expression::Kind::kIndex: {
John Stiles44e96be2020-08-31 13:16:04 -0400380 const IndexExpression& idx = expression.as<IndexExpression>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -0400381 return std::make_unique<IndexExpression>(*fContext, expr(idx.base()),
382 expr(idx.index()));
John Stiles44e96be2020-08-31 13:16:04 -0400383 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400384 case Expression::Kind::kPrefix: {
John Stiles44e96be2020-08-31 13:16:04 -0400385 const PrefixExpression& p = expression.as<PrefixExpression>();
Ethan Nicholas444ccc62020-10-09 10:16:22 -0400386 return std::make_unique<PrefixExpression>(p.getOperator(), expr(p.operand()));
John Stiles44e96be2020-08-31 13:16:04 -0400387 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400388 case Expression::Kind::kPostfix: {
John Stiles44e96be2020-08-31 13:16:04 -0400389 const PostfixExpression& p = expression.as<PostfixExpression>();
Ethan Nicholas444ccc62020-10-09 10:16:22 -0400390 return std::make_unique<PostfixExpression>(expr(p.operand()), p.getOperator());
John Stiles44e96be2020-08-31 13:16:04 -0400391 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400392 case Expression::Kind::kSetting:
John Stiles44e96be2020-08-31 13:16:04 -0400393 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400394 case Expression::Kind::kSwizzle: {
John Stiles44e96be2020-08-31 13:16:04 -0400395 const Swizzle& s = expression.as<Swizzle>();
Ethan Nicholas6b4d5812020-10-12 16:11:51 -0400396 return std::make_unique<Swizzle>(*fContext, expr(s.base()), s.components());
John Stiles44e96be2020-08-31 13:16:04 -0400397 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400398 case Expression::Kind::kTernary: {
John Stiles44e96be2020-08-31 13:16:04 -0400399 const TernaryExpression& t = expression.as<TernaryExpression>();
Ethan Nicholasdd218162020-10-08 05:48:01 -0400400 return std::make_unique<TernaryExpression>(offset, expr(t.test()),
401 expr(t.ifTrue()), expr(t.ifFalse()));
John Stiles44e96be2020-08-31 13:16:04 -0400402 }
Brian Osman83ba9302020-09-11 13:33:46 -0400403 case Expression::Kind::kTypeReference:
404 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400405 case Expression::Kind::kVariableReference: {
John Stiles44e96be2020-08-31 13:16:04 -0400406 const VariableReference& v = expression.as<VariableReference>();
Ethan Nicholas78686922020-10-08 06:46:27 -0400407 auto varMapIter = varMap->find(v.variable());
John Stilese41b4ee2020-09-28 12:28:16 -0400408 if (varMapIter != varMap->end()) {
Ethan Nicholas78686922020-10-08 06:46:27 -0400409 return clone_with_ref_kind(*varMapIter->second, v.refKind());
John Stiles44e96be2020-08-31 13:16:04 -0400410 }
411 return v.clone();
412 }
413 default:
414 SkASSERT(false);
415 return nullptr;
416 }
417}
418
419std::unique_ptr<Statement> Inliner::inlineStatement(int offset,
420 VariableRewriteMap* varMap,
421 SymbolTable* symbolTableForStatement,
John Stilese41b4ee2020-09-28 12:28:16 -0400422 const Expression* resultExpr,
John Stiles44e96be2020-08-31 13:16:04 -0400423 bool haveEarlyReturns,
Brian Osman3887a012020-09-30 13:22:27 -0400424 const Statement& statement,
425 bool isBuiltinCode) {
John Stiles44e96be2020-08-31 13:16:04 -0400426 auto stmt = [&](const std::unique_ptr<Statement>& s) -> std::unique_ptr<Statement> {
427 if (s) {
John Stilesa5f3c312020-09-22 12:05:16 -0400428 return this->inlineStatement(offset, varMap, symbolTableForStatement, resultExpr,
Brian Osman3887a012020-09-30 13:22:27 -0400429 haveEarlyReturns, *s, isBuiltinCode);
John Stiles44e96be2020-08-31 13:16:04 -0400430 }
431 return nullptr;
432 };
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400433 auto blockStmts = [&](const Block& block) {
John Stiles8f2a0cf2020-10-13 12:48:21 -0400434 StatementArray result;
John Stilesf4bda742020-10-14 16:57:41 -0400435 result.reserve_back(block.children().size());
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400436 for (const std::unique_ptr<Statement>& child : block.children()) {
437 result.push_back(stmt(child));
438 }
439 return result;
440 };
John Stiles8f2a0cf2020-10-13 12:48:21 -0400441 auto stmts = [&](const StatementArray& ss) {
442 StatementArray result;
John Stilesf4bda742020-10-14 16:57:41 -0400443 result.reserve_back(ss.size());
John Stiles44e96be2020-08-31 13:16:04 -0400444 for (const auto& s : ss) {
445 result.push_back(stmt(s));
446 }
447 return result;
448 };
449 auto expr = [&](const std::unique_ptr<Expression>& e) -> std::unique_ptr<Expression> {
450 if (e) {
451 return this->inlineExpression(offset, varMap, *e);
452 }
453 return nullptr;
454 };
John Stiles031a7672020-11-13 16:13:18 -0500455
456 ++fInlinedStatementCounter;
457
Ethan Nicholase6592142020-09-08 10:22:09 -0400458 switch (statement.kind()) {
459 case Statement::Kind::kBlock: {
John Stiles44e96be2020-08-31 13:16:04 -0400460 const Block& b = statement.as<Block>();
John Stilesa1e2b412020-10-20 14:51:28 -0400461 return std::make_unique<Block>(offset, blockStmts(b),
462 SymbolTable::WrapIfBuiltin(b.symbolTable()),
463 b.isScope());
John Stiles44e96be2020-08-31 13:16:04 -0400464 }
465
Ethan Nicholase6592142020-09-08 10:22:09 -0400466 case Statement::Kind::kBreak:
467 case Statement::Kind::kContinue:
468 case Statement::Kind::kDiscard:
John Stiles44e96be2020-08-31 13:16:04 -0400469 return statement.clone();
470
Ethan Nicholase6592142020-09-08 10:22:09 -0400471 case Statement::Kind::kDo: {
John Stiles44e96be2020-08-31 13:16:04 -0400472 const DoStatement& d = statement.as<DoStatement>();
Ethan Nicholas1fd61162020-09-28 13:14:19 -0400473 return std::make_unique<DoStatement>(offset, stmt(d.statement()), expr(d.test()));
John Stiles44e96be2020-08-31 13:16:04 -0400474 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400475 case Statement::Kind::kExpression: {
John Stiles44e96be2020-08-31 13:16:04 -0400476 const ExpressionStatement& e = statement.as<ExpressionStatement>();
Ethan Nicholasd503a5a2020-09-30 09:29:55 -0400477 return std::make_unique<ExpressionStatement>(expr(e.expression()));
John Stiles44e96be2020-08-31 13:16:04 -0400478 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400479 case Statement::Kind::kFor: {
John Stiles44e96be2020-08-31 13:16:04 -0400480 const ForStatement& f = statement.as<ForStatement>();
481 // need to ensure initializer is evaluated first so that we've already remapped its
482 // declarations by the time we evaluate test & next
Ethan Nicholas0d31ed52020-10-05 14:47:09 -0400483 std::unique_ptr<Statement> initializer = stmt(f.initializer());
484 return std::make_unique<ForStatement>(offset, std::move(initializer), expr(f.test()),
John Stilesa1e2b412020-10-20 14:51:28 -0400485 expr(f.next()), stmt(f.statement()),
486 SymbolTable::WrapIfBuiltin(f.symbols()));
John Stiles44e96be2020-08-31 13:16:04 -0400487 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400488 case Statement::Kind::kIf: {
John Stiles44e96be2020-08-31 13:16:04 -0400489 const IfStatement& i = statement.as<IfStatement>();
Ethan Nicholas8c44eca2020-10-07 16:47:09 -0400490 return std::make_unique<IfStatement>(offset, i.isStatic(), expr(i.test()),
491 stmt(i.ifTrue()), stmt(i.ifFalse()));
John Stiles44e96be2020-08-31 13:16:04 -0400492 }
John Stiles98c1f822020-09-09 14:18:53 -0400493 case Statement::Kind::kInlineMarker:
Ethan Nicholase6592142020-09-08 10:22:09 -0400494 case Statement::Kind::kNop:
John Stiles44e96be2020-08-31 13:16:04 -0400495 return statement.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400496 case Statement::Kind::kReturn: {
John Stiles44e96be2020-08-31 13:16:04 -0400497 const ReturnStatement& r = statement.as<ReturnStatement>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -0400498 if (r.expression()) {
John Stilese41b4ee2020-09-28 12:28:16 -0400499 SkASSERT(resultExpr);
John Stilesa5f3c312020-09-22 12:05:16 -0400500 auto assignment =
501 std::make_unique<ExpressionStatement>(std::make_unique<BinaryExpression>(
502 offset,
Ethan Nicholas453f67f2020-10-09 10:43:45 -0400503 clone_with_ref_kind(*resultExpr,
504 VariableReference::RefKind::kWrite),
John Stilesa5f3c312020-09-22 12:05:16 -0400505 Token::Kind::TK_EQ,
Ethan Nicholas2a4952d2020-10-08 15:35:56 -0400506 expr(r.expression()),
John Stilese41b4ee2020-09-28 12:28:16 -0400507 &resultExpr->type()));
John Stiles44e96be2020-08-31 13:16:04 -0400508 if (haveEarlyReturns) {
John Stiles8f2a0cf2020-10-13 12:48:21 -0400509 StatementArray block;
John Stilesf4bda742020-10-14 16:57:41 -0400510 block.reserve_back(2);
John Stiles44e96be2020-08-31 13:16:04 -0400511 block.push_back(std::move(assignment));
John Stiles8f2a0cf2020-10-13 12:48:21 -0400512 block.push_back(std::make_unique<BreakStatement>(offset));
John Stiles44e96be2020-08-31 13:16:04 -0400513 return std::make_unique<Block>(offset, std::move(block), /*symbols=*/nullptr,
514 /*isScope=*/true);
515 } else {
516 return std::move(assignment);
517 }
518 } else {
519 if (haveEarlyReturns) {
520 return std::make_unique<BreakStatement>(offset);
521 } else {
522 return std::make_unique<Nop>();
523 }
524 }
525 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400526 case Statement::Kind::kSwitch: {
John Stiles44e96be2020-08-31 13:16:04 -0400527 const SwitchStatement& ss = statement.as<SwitchStatement>();
528 std::vector<std::unique_ptr<SwitchCase>> cases;
John Stiles2d4f9592020-10-30 10:29:12 -0400529 cases.reserve(ss.cases().size());
530 for (const std::unique_ptr<SwitchCase>& sc : ss.cases()) {
531 cases.push_back(std::make_unique<SwitchCase>(offset, expr(sc->value()),
532 stmts(sc->statements())));
John Stiles44e96be2020-08-31 13:16:04 -0400533 }
Ethan Nicholas01b05e52020-10-22 15:53:41 -0400534 return std::make_unique<SwitchStatement>(offset, ss.isStatic(), expr(ss.value()),
John Stilesa1e2b412020-10-20 14:51:28 -0400535 std::move(cases),
Ethan Nicholas01b05e52020-10-22 15:53:41 -0400536 SymbolTable::WrapIfBuiltin(ss.symbols()));
John Stiles44e96be2020-08-31 13:16:04 -0400537 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400538 case Statement::Kind::kVarDeclaration: {
John Stiles44e96be2020-08-31 13:16:04 -0400539 const VarDeclaration& decl = statement.as<VarDeclaration>();
John Stiles87ae34e2020-10-13 12:50:11 -0400540 ExpressionArray sizes;
John Stiles2d4f9592020-10-30 10:29:12 -0400541 sizes.reserve_back(decl.sizes().count());
542 for (const std::unique_ptr<Expression>& size : decl.sizes()) {
543 sizes.push_back(expr(size));
John Stiles44e96be2020-08-31 13:16:04 -0400544 }
Ethan Nicholasc51f33e2020-10-13 13:49:44 -0400545 std::unique_ptr<Expression> initialValue = expr(decl.value());
546 const Variable& old = decl.var();
John Stilesc75abb82020-09-14 18:24:12 -0400547 // We assign unique names to inlined variables--scopes hide most of the problems in this
548 // regard, but see `InlinerAvoidsVariableNameOverlap` for a counterexample where unique
549 // names are important.
550 auto name = std::make_unique<String>(
Ethan Nicholasc51f33e2020-10-13 13:49:44 -0400551 this->uniqueNameForInlineVar(String(old.name()), symbolTableForStatement));
John Stiles44e96be2020-08-31 13:16:04 -0400552 const String* namePtr = symbolTableForStatement->takeOwnershipOfString(std::move(name));
Ethan Nicholasc51f33e2020-10-13 13:49:44 -0400553 const Type* baseTypePtr = copy_if_needed(&decl.baseType(), *symbolTableForStatement);
554 const Type* typePtr = copy_if_needed(&old.type(), *symbolTableForStatement);
John Stiles44e96be2020-08-31 13:16:04 -0400555 const Variable* clone = symbolTableForStatement->takeOwnershipOfSymbol(
556 std::make_unique<Variable>(offset,
John Stiles586df952020-11-12 18:27:13 -0500557 &old.modifiers(),
John Stiles44e96be2020-08-31 13:16:04 -0400558 namePtr->c_str(),
Ethan Nicholas30d30222020-09-11 12:27:26 -0400559 typePtr,
Brian Osman3887a012020-09-30 13:22:27 -0400560 isBuiltinCode,
Ethan Nicholasc51f33e2020-10-13 13:49:44 -0400561 old.storage(),
John Stiles44e96be2020-08-31 13:16:04 -0400562 initialValue.get()));
Ethan Nicholasc51f33e2020-10-13 13:49:44 -0400563 (*varMap)[&old] = std::make_unique<VariableReference>(offset, clone);
Brian Osmanc0213602020-10-06 14:43:32 -0400564 return std::make_unique<VarDeclaration>(clone, baseTypePtr, std::move(sizes),
John Stiles44e96be2020-08-31 13:16:04 -0400565 std::move(initialValue));
566 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400567 case Statement::Kind::kWhile: {
John Stiles44e96be2020-08-31 13:16:04 -0400568 const WhileStatement& w = statement.as<WhileStatement>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -0400569 return std::make_unique<WhileStatement>(offset, expr(w.test()), stmt(w.statement()));
John Stiles44e96be2020-08-31 13:16:04 -0400570 }
571 default:
572 SkASSERT(false);
573 return nullptr;
574 }
575}
576
John Stiles6eadf132020-09-08 10:16:10 -0400577Inliner::InlinedCall Inliner::inlineCall(FunctionCall* call,
Brian Osman3887a012020-09-30 13:22:27 -0400578 SymbolTable* symbolTableForCall,
579 const FunctionDeclaration* caller) {
John Stiles44e96be2020-08-31 13:16:04 -0400580 // Inlining is more complicated here than in a typical compiler, because we have to have a
581 // high-level IR and can't just drop statements into the middle of an expression or even use
582 // gotos.
583 //
584 // Since we can't insert statements into an expression, we run the inline function as extra
585 // statements before the statement we're currently processing, relying on a lack of execution
586 // order guarantees. Since we can't use gotos (which are normally used to replace return
587 // statements), we wrap the whole function in a loop and use break statements to jump to the
588 // end.
589 SkASSERT(fSettings);
590 SkASSERT(fContext);
591 SkASSERT(call);
Ethan Nicholased84b732020-10-08 11:45:44 -0400592 SkASSERT(this->isSafeToInline(call->function().definition()));
John Stiles44e96be2020-08-31 13:16:04 -0400593
John Stiles8e3b6be2020-10-13 11:14:08 -0400594 ExpressionArray& arguments = call->arguments();
John Stiles6eadf132020-09-08 10:16:10 -0400595 const int offset = call->fOffset;
Ethan Nicholased84b732020-10-08 11:45:44 -0400596 const FunctionDefinition& function = *call->function().definition();
John Stiles6eadf132020-09-08 10:16:10 -0400597 const bool hasEarlyReturn = has_early_return(function);
598
John Stiles44e96be2020-08-31 13:16:04 -0400599 InlinedCall inlinedCall;
John Stiles8f2a0cf2020-10-13 12:48:21 -0400600 inlinedCall.fInlinedBody = std::make_unique<Block>(offset, StatementArray{},
John Stiles6eadf132020-09-08 10:16:10 -0400601 /*symbols=*/nullptr,
602 /*isScope=*/false);
John Stiles98c1f822020-09-09 14:18:53 -0400603
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400604 Block& inlinedBody = *inlinedCall.fInlinedBody;
John Stiles82f373c2020-10-20 13:58:05 -0400605 inlinedBody.children().reserve_back(
606 1 + // Inline marker
607 1 + // Result variable
608 arguments.size() + // Function arguments (passing in)
609 arguments.size() + // Function arguments (copy out-params back)
610 1); // Inlined code (Block or do-while loop)
John Stiles98c1f822020-09-09 14:18:53 -0400611
Ethan Nicholasceb62142020-10-09 16:51:18 -0400612 inlinedBody.children().push_back(std::make_unique<InlineMarker>(&call->function()));
John Stiles44e96be2020-08-31 13:16:04 -0400613
John Stilese41b4ee2020-09-28 12:28:16 -0400614 auto makeInlineVar =
615 [&](const String& baseName, const Type* type, Modifiers modifiers,
616 std::unique_ptr<Expression>* initialValue) -> std::unique_ptr<Expression> {
John Stilesa003e812020-09-11 09:43:49 -0400617 // $floatLiteral or $intLiteral aren't real types that we can use for scratch variables, so
618 // replace them if they ever appear here. If this happens, we likely forgot to coerce a type
619 // somewhere during compilation.
620 if (type == fContext->fFloatLiteral_Type.get()) {
John Stilesd2be5c52020-09-11 14:58:06 -0400621 SkDEBUGFAIL("found a $floatLiteral type while inlining");
John Stilesa003e812020-09-11 09:43:49 -0400622 type = fContext->fFloat_Type.get();
623 } else if (type == fContext->fIntLiteral_Type.get()) {
John Stilesd2be5c52020-09-11 14:58:06 -0400624 SkDEBUGFAIL("found an $intLiteral type while inlining");
John Stilesa003e812020-09-11 09:43:49 -0400625 type = fContext->fInt_Type.get();
626 }
627
John Stilesc75abb82020-09-14 18:24:12 -0400628 // Provide our new variable with a unique name, and add it to our symbol table.
629 String uniqueName = this->uniqueNameForInlineVar(baseName, symbolTableForCall);
John Stilescf936f92020-08-31 17:18:45 -0400630 const String* namePtr = symbolTableForCall->takeOwnershipOfString(
631 std::make_unique<String>(std::move(uniqueName)));
John Stiles44e96be2020-08-31 13:16:04 -0400632 StringFragment nameFrag{namePtr->c_str(), namePtr->length()};
633
634 // Add our new variable to the symbol table.
John Stilesb8cc6652020-10-08 09:12:07 -0400635 const Variable* variableSymbol = symbolTableForCall->add(std::make_unique<Variable>(
John Stiles586df952020-11-12 18:27:13 -0500636 /*offset=*/-1, fModifiers->addToPool(Modifiers()),
Ethan Nicholased84b732020-10-08 11:45:44 -0400637 nameFrag, type, caller->isBuiltin(),
Ethan Nicholas453f67f2020-10-09 10:43:45 -0400638 Variable::Storage::kLocal, initialValue->get()));
John Stiles44e96be2020-08-31 13:16:04 -0400639
640 // Prepare the variable declaration (taking extra care with `out` params to not clobber any
641 // initial value).
Brian Osmanc0213602020-10-06 14:43:32 -0400642 std::unique_ptr<Statement> variable;
John Stiles44e96be2020-08-31 13:16:04 -0400643 if (initialValue && (modifiers.fFlags & Modifiers::kOut_Flag)) {
Brian Osmanc0213602020-10-06 14:43:32 -0400644 variable = std::make_unique<VarDeclaration>(
John Stiles87ae34e2020-10-13 12:50:11 -0400645 variableSymbol, type, /*sizes=*/ExpressionArray{}, (*initialValue)->clone());
John Stiles44e96be2020-08-31 13:16:04 -0400646 } else {
Brian Osmanc0213602020-10-06 14:43:32 -0400647 variable = std::make_unique<VarDeclaration>(
John Stiles87ae34e2020-10-13 12:50:11 -0400648 variableSymbol, type, /*sizes=*/ExpressionArray{}, std::move(*initialValue));
John Stiles44e96be2020-08-31 13:16:04 -0400649 }
650
651 // Add the new variable-declaration statement to our block of extra statements.
Brian Osmanc0213602020-10-06 14:43:32 -0400652 inlinedBody.children().push_back(std::move(variable));
John Stiles44e96be2020-08-31 13:16:04 -0400653
John Stilese41b4ee2020-09-28 12:28:16 -0400654 return std::make_unique<VariableReference>(offset, variableSymbol);
John Stiles44e96be2020-08-31 13:16:04 -0400655 };
656
657 // Create a variable to hold the result in the extra statements (excepting void).
John Stilese41b4ee2020-09-28 12:28:16 -0400658 std::unique_ptr<Expression> resultExpr;
Ethan Nicholas0a5d0962020-10-14 13:33:18 -0400659 if (function.declaration().returnType() != *fContext->fVoid_Type) {
John Stiles44e96be2020-08-31 13:16:04 -0400660 std::unique_ptr<Expression> noInitialValue;
Ethan Nicholas0a5d0962020-10-14 13:33:18 -0400661 resultExpr = makeInlineVar(String(function.declaration().name()),
662 &function.declaration().returnType(),
John Stilese41b4ee2020-09-28 12:28:16 -0400663 Modifiers{}, &noInitialValue);
664 }
John Stiles44e96be2020-08-31 13:16:04 -0400665
666 // Create variables in the extra statements to hold the arguments, and assign the arguments to
667 // them.
668 VariableRewriteMap varMap;
John Stilese41b4ee2020-09-28 12:28:16 -0400669 std::vector<int> argsToCopyBack;
John Stiles44e96be2020-08-31 13:16:04 -0400670 for (int i = 0; i < (int) arguments.size(); ++i) {
Ethan Nicholas0a5d0962020-10-14 13:33:18 -0400671 const Variable* param = function.declaration().parameters()[i];
Ethan Nicholas041fd0a2020-10-07 16:42:04 -0400672 bool isOutParam = param->modifiers().fFlags & Modifiers::kOut_Flag;
John Stiles44e96be2020-08-31 13:16:04 -0400673
John Stiles44733aa2020-09-29 17:42:23 -0400674 // If this argument can be inlined trivially (e.g. a swizzle, or a constant array index)...
John Stilesc30fbca2020-11-19 16:25:49 -0500675 if (Analysis::IsTrivialExpression(*arguments[i])) {
John Stilese41b4ee2020-09-28 12:28:16 -0400676 // ... and it's an `out` param, or it isn't written to within the inline function...
Ethan Nicholas0a5d0962020-10-14 13:33:18 -0400677 if (isOutParam || !Analysis::StatementWritesToVariable(*function.body(), *param)) {
John Stilesf201af82020-09-29 16:57:55 -0400678 // ... we don't need to copy it at all! We can just use the existing expression.
679 varMap[param] = arguments[i]->clone();
John Stiles44e96be2020-08-31 13:16:04 -0400680 continue;
681 }
682 }
683
John Stilese41b4ee2020-09-28 12:28:16 -0400684 if (isOutParam) {
685 argsToCopyBack.push_back(i);
686 }
687
Ethan Nicholase2c49992020-10-05 11:49:11 -0400688 varMap[param] = makeInlineVar(String(param->name()), &arguments[i]->type(),
Ethan Nicholas041fd0a2020-10-07 16:42:04 -0400689 param->modifiers(), &arguments[i]);
John Stiles44e96be2020-08-31 13:16:04 -0400690 }
691
Ethan Nicholas0a5d0962020-10-14 13:33:18 -0400692 const Block& body = function.body()->as<Block>();
John Stiles8f2a0cf2020-10-13 12:48:21 -0400693 auto inlineBlock = std::make_unique<Block>(offset, StatementArray{});
John Stilesf4bda742020-10-14 16:57:41 -0400694 inlineBlock->children().reserve_back(body.children().size());
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400695 for (const std::unique_ptr<Statement>& stmt : body.children()) {
Brian Osman3887a012020-09-30 13:22:27 -0400696 inlineBlock->children().push_back(this->inlineStatement(offset, &varMap, symbolTableForCall,
697 resultExpr.get(), hasEarlyReturn,
Ethan Nicholased84b732020-10-08 11:45:44 -0400698 *stmt, caller->isBuiltin()));
John Stiles44e96be2020-08-31 13:16:04 -0400699 }
700 if (hasEarlyReturn) {
701 // Since we output to backends that don't have a goto statement (which would normally be
702 // used to perform an early return), we fake it by wrapping the function in a
703 // do { } while (false); and then use break statements to jump to the end in order to
704 // emulate a goto.
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400705 inlinedBody.children().push_back(std::make_unique<DoStatement>(
John Stiles44e96be2020-08-31 13:16:04 -0400706 /*offset=*/-1,
707 std::move(inlineBlock),
708 std::make_unique<BoolLiteral>(*fContext, offset, /*value=*/false)));
709 } else {
John Stiles6eadf132020-09-08 10:16:10 -0400710 // No early returns, so we can just dump the code in. We still need to keep the block so we
711 // don't get name conflicts with locals.
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400712 inlinedBody.children().push_back(std::move(inlineBlock));
John Stiles44e96be2020-08-31 13:16:04 -0400713 }
714
John Stilese41b4ee2020-09-28 12:28:16 -0400715 // Copy back the values of `out` parameters into their real destinations.
716 for (int i : argsToCopyBack) {
Ethan Nicholas0a5d0962020-10-14 13:33:18 -0400717 const Variable* p = function.declaration().parameters()[i];
John Stilese41b4ee2020-09-28 12:28:16 -0400718 SkASSERT(varMap.find(p) != varMap.end());
719 inlinedBody.children().push_back(
720 std::make_unique<ExpressionStatement>(std::make_unique<BinaryExpression>(
721 offset,
Ethan Nicholas453f67f2020-10-09 10:43:45 -0400722 clone_with_ref_kind(*arguments[i], VariableReference::RefKind::kWrite),
John Stilese41b4ee2020-09-28 12:28:16 -0400723 Token::Kind::TK_EQ,
724 std::move(varMap[p]),
725 &arguments[i]->type())));
John Stiles44e96be2020-08-31 13:16:04 -0400726 }
727
John Stilese41b4ee2020-09-28 12:28:16 -0400728 if (resultExpr != nullptr) {
729 // Return our result variable as our replacement expression.
Ethan Nicholas453f67f2020-10-09 10:43:45 -0400730 SkASSERT(resultExpr->as<VariableReference>().refKind() ==
731 VariableReference::RefKind::kRead);
John Stilese41b4ee2020-09-28 12:28:16 -0400732 inlinedCall.fReplacementExpr = std::move(resultExpr);
John Stiles44e96be2020-08-31 13:16:04 -0400733 } else {
734 // It's a void function, so it doesn't actually result in anything, but we have to return
735 // something non-null as a standin.
Ethan Nicholas041fd0a2020-10-07 16:42:04 -0400736 inlinedCall.fReplacementExpr = std::make_unique<BoolLiteral>(*fContext,
737 offset,
John Stiles44e96be2020-08-31 13:16:04 -0400738 /*value=*/false);
739 }
740
John Stiles44e96be2020-08-31 13:16:04 -0400741 return inlinedCall;
742}
743
John Stiles2d7973a2020-10-02 15:01:03 -0400744bool Inliner::isSafeToInline(const FunctionDefinition* functionDef) {
John Stiles44e96be2020-08-31 13:16:04 -0400745 SkASSERT(fSettings);
746
John Stiles1c03d332020-10-13 10:30:23 -0400747 // A threshold of zero indicates that the inliner is completely disabled, so we can just return.
748 if (fSettings->fInlineThreshold <= 0) {
749 return false;
750 }
751
John Stiles031a7672020-11-13 16:13:18 -0500752 // Enforce a limit on inlining to avoid pathological cases. (inliner/ExponentialGrowth.sksl)
753 if (fInlinedStatementCounter >= kInlinedStatementLimit) {
754 return false;
755 }
756
John Stiles2d7973a2020-10-02 15:01:03 -0400757 if (functionDef == nullptr) {
John Stiles44e96be2020-08-31 13:16:04 -0400758 // Can't inline something if we don't actually have its definition.
759 return false;
760 }
John Stiles2d7973a2020-10-02 15:01:03 -0400761
Brian Osmand7e76592020-11-02 12:26:22 -0500762 if (!fCaps || !fCaps->canUseDoLoops()) {
John Stiles44e96be2020-08-31 13:16:04 -0400763 // We don't have do-while loops. We use do-while loops to simulate early returns, so we
764 // can't inline functions that have an early return.
John Stiles2d7973a2020-10-02 15:01:03 -0400765 bool hasEarlyReturn = has_early_return(*functionDef);
John Stiles44e96be2020-08-31 13:16:04 -0400766
767 // If we didn't detect an early return, there shouldn't be any returns in breakable
768 // constructs either.
John Stiles2d7973a2020-10-02 15:01:03 -0400769 SkASSERT(hasEarlyReturn || count_returns_in_breakable_constructs(*functionDef) == 0);
John Stiles44e96be2020-08-31 13:16:04 -0400770 return !hasEarlyReturn;
771 }
772 // We have do-while loops, but we don't have any mechanism to simulate early returns within a
773 // 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 -0400774 bool hasReturnInBreakableConstruct = (count_returns_in_breakable_constructs(*functionDef) > 0);
John Stiles44e96be2020-08-31 13:16:04 -0400775
776 // If we detected returns in breakable constructs, we should also detect an early return.
John Stiles2d7973a2020-10-02 15:01:03 -0400777 SkASSERT(!hasReturnInBreakableConstruct || has_early_return(*functionDef));
John Stiles44e96be2020-08-31 13:16:04 -0400778 return !hasReturnInBreakableConstruct;
779}
780
John Stiles2d7973a2020-10-02 15:01:03 -0400781// A candidate function for inlining, containing everything that `inlineCall` needs.
782struct InlineCandidate {
783 SymbolTable* fSymbols; // the SymbolTable of the candidate
784 std::unique_ptr<Statement>* fParentStmt; // the parent Statement of the enclosing stmt
785 std::unique_ptr<Statement>* fEnclosingStmt; // the Statement containing the candidate
786 std::unique_ptr<Expression>* fCandidateExpr; // the candidate FunctionCall to be inlined
787 FunctionDefinition* fEnclosingFunction; // the Function containing the candidate
John Stiles2d7973a2020-10-02 15:01:03 -0400788};
John Stiles93442622020-09-11 12:11:27 -0400789
John Stiles2d7973a2020-10-02 15:01:03 -0400790struct InlineCandidateList {
791 std::vector<InlineCandidate> fCandidates;
792};
793
794class InlineCandidateAnalyzer {
John Stiles70957c82020-10-02 16:42:10 -0400795public:
796 // A list of all the inlining candidates we found during analysis.
797 InlineCandidateList* fCandidateList;
John Stiles2d7973a2020-10-02 15:01:03 -0400798
John Stiles70957c82020-10-02 16:42:10 -0400799 // A stack of the symbol tables; since most nodes don't have one, expected to be shallower than
800 // the enclosing-statement stack.
801 std::vector<SymbolTable*> fSymbolTableStack;
802 // A stack of "enclosing" statements--these would be suitable for the inliner to use for adding
803 // new instructions. Not all statements are suitable (e.g. a for-loop's initializer). The
804 // inliner might replace a statement with a block containing the statement.
805 std::vector<std::unique_ptr<Statement>*> fEnclosingStmtStack;
806 // The function that we're currently processing (i.e. inlining into).
807 FunctionDefinition* fEnclosingFunction = nullptr;
John Stiles93442622020-09-11 12:11:27 -0400808
Brian Osman0006ad02020-11-18 15:38:39 -0500809 void visit(const std::vector<std::unique_ptr<ProgramElement>>& elements,
810 SymbolTable* symbols,
811 InlineCandidateList* candidateList) {
John Stiles70957c82020-10-02 16:42:10 -0400812 fCandidateList = candidateList;
Brian Osman0006ad02020-11-18 15:38:39 -0500813 fSymbolTableStack.push_back(symbols);
John Stiles93442622020-09-11 12:11:27 -0400814
Brian Osman0006ad02020-11-18 15:38:39 -0500815 for (const std::unique_ptr<ProgramElement>& pe : elements) {
Brian Osman1179fcf2020-10-08 16:04:40 -0400816 this->visitProgramElement(pe.get());
John Stiles93442622020-09-11 12:11:27 -0400817 }
818
John Stiles70957c82020-10-02 16:42:10 -0400819 fSymbolTableStack.pop_back();
820 fCandidateList = nullptr;
821 }
822
823 void visitProgramElement(ProgramElement* pe) {
824 switch (pe->kind()) {
825 case ProgramElement::Kind::kFunction: {
826 FunctionDefinition& funcDef = pe->as<FunctionDefinition>();
Brian Osman0006ad02020-11-18 15:38:39 -0500827 fEnclosingFunction = &funcDef;
828 this->visitStatement(&funcDef.body());
John Stiles70957c82020-10-02 16:42:10 -0400829 break;
John Stiles93442622020-09-11 12:11:27 -0400830 }
John Stiles70957c82020-10-02 16:42:10 -0400831 default:
832 // The inliner can't operate outside of a function's scope.
833 break;
834 }
835 }
836
837 void visitStatement(std::unique_ptr<Statement>* stmt,
838 bool isViableAsEnclosingStatement = true) {
839 if (!*stmt) {
840 return;
John Stiles93442622020-09-11 12:11:27 -0400841 }
842
John Stiles70957c82020-10-02 16:42:10 -0400843 size_t oldEnclosingStmtStackSize = fEnclosingStmtStack.size();
844 size_t oldSymbolStackSize = fSymbolTableStack.size();
John Stiles93442622020-09-11 12:11:27 -0400845
John Stiles70957c82020-10-02 16:42:10 -0400846 if (isViableAsEnclosingStatement) {
847 fEnclosingStmtStack.push_back(stmt);
John Stiles93442622020-09-11 12:11:27 -0400848 }
849
John Stiles70957c82020-10-02 16:42:10 -0400850 switch ((*stmt)->kind()) {
851 case Statement::Kind::kBreak:
852 case Statement::Kind::kContinue:
853 case Statement::Kind::kDiscard:
854 case Statement::Kind::kInlineMarker:
855 case Statement::Kind::kNop:
856 break;
857
858 case Statement::Kind::kBlock: {
859 Block& block = (*stmt)->as<Block>();
860 if (block.symbolTable()) {
861 fSymbolTableStack.push_back(block.symbolTable().get());
862 }
863
864 for (std::unique_ptr<Statement>& stmt : block.children()) {
865 this->visitStatement(&stmt);
866 }
867 break;
John Stiles93442622020-09-11 12:11:27 -0400868 }
John Stiles70957c82020-10-02 16:42:10 -0400869 case Statement::Kind::kDo: {
870 DoStatement& doStmt = (*stmt)->as<DoStatement>();
871 // The loop body is a candidate for inlining.
872 this->visitStatement(&doStmt.statement());
873 // The inliner isn't smart enough to inline the test-expression for a do-while
874 // loop at this time. There are two limitations:
875 // - We would need to insert the inlined-body block at the very end of the do-
876 // statement's inner fStatement. We don't support that today, but it's doable.
877 // - We cannot inline the test expression if the loop uses `continue` anywhere; that
878 // would skip over the inlined block that evaluates the test expression. There
879 // isn't a good fix for this--any workaround would be more complex than the cost
880 // of a function call. However, loops that don't use `continue` would still be
881 // viable candidates for inlining.
882 break;
John Stiles93442622020-09-11 12:11:27 -0400883 }
John Stiles70957c82020-10-02 16:42:10 -0400884 case Statement::Kind::kExpression: {
885 ExpressionStatement& expr = (*stmt)->as<ExpressionStatement>();
886 this->visitExpression(&expr.expression());
887 break;
888 }
889 case Statement::Kind::kFor: {
890 ForStatement& forStmt = (*stmt)->as<ForStatement>();
Ethan Nicholas0d31ed52020-10-05 14:47:09 -0400891 if (forStmt.symbols()) {
892 fSymbolTableStack.push_back(forStmt.symbols().get());
John Stiles70957c82020-10-02 16:42:10 -0400893 }
894
895 // The initializer and loop body are candidates for inlining.
Ethan Nicholas0d31ed52020-10-05 14:47:09 -0400896 this->visitStatement(&forStmt.initializer(),
John Stiles70957c82020-10-02 16:42:10 -0400897 /*isViableAsEnclosingStatement=*/false);
Ethan Nicholas0d31ed52020-10-05 14:47:09 -0400898 this->visitStatement(&forStmt.statement());
John Stiles70957c82020-10-02 16:42:10 -0400899
900 // The inliner isn't smart enough to inline the test- or increment-expressions
901 // of a for loop loop at this time. There are a handful of limitations:
902 // - We would need to insert the test-expression block at the very beginning of the
903 // for-loop's inner fStatement, and the increment-expression block at the very
904 // end. We don't support that today, but it's doable.
905 // - The for-loop's built-in test-expression would need to be dropped entirely,
906 // and the loop would be halted via a break statement at the end of the inlined
907 // test-expression. This is again something we don't support today, but it could
908 // be implemented.
909 // - We cannot inline the increment-expression if the loop uses `continue` anywhere;
910 // that would skip over the inlined block that evaluates the increment expression.
911 // There isn't a good fix for this--any workaround would be more complex than the
912 // cost of a function call. However, loops that don't use `continue` would still
913 // be viable candidates for increment-expression inlining.
914 break;
915 }
916 case Statement::Kind::kIf: {
917 IfStatement& ifStmt = (*stmt)->as<IfStatement>();
Ethan Nicholas8c44eca2020-10-07 16:47:09 -0400918 this->visitExpression(&ifStmt.test());
919 this->visitStatement(&ifStmt.ifTrue());
920 this->visitStatement(&ifStmt.ifFalse());
John Stiles70957c82020-10-02 16:42:10 -0400921 break;
922 }
923 case Statement::Kind::kReturn: {
924 ReturnStatement& returnStmt = (*stmt)->as<ReturnStatement>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -0400925 this->visitExpression(&returnStmt.expression());
John Stiles70957c82020-10-02 16:42:10 -0400926 break;
927 }
928 case Statement::Kind::kSwitch: {
929 SwitchStatement& switchStmt = (*stmt)->as<SwitchStatement>();
Ethan Nicholas01b05e52020-10-22 15:53:41 -0400930 if (switchStmt.symbols()) {
931 fSymbolTableStack.push_back(switchStmt.symbols().get());
John Stiles70957c82020-10-02 16:42:10 -0400932 }
933
Ethan Nicholas01b05e52020-10-22 15:53:41 -0400934 this->visitExpression(&switchStmt.value());
John Stiles2d4f9592020-10-30 10:29:12 -0400935 for (const std::unique_ptr<SwitchCase>& switchCase : switchStmt.cases()) {
John Stiles70957c82020-10-02 16:42:10 -0400936 // The switch-case's fValue cannot be a FunctionCall; skip it.
John Stiles2d4f9592020-10-30 10:29:12 -0400937 for (std::unique_ptr<Statement>& caseBlock : switchCase->statements()) {
John Stiles70957c82020-10-02 16:42:10 -0400938 this->visitStatement(&caseBlock);
939 }
940 }
941 break;
942 }
943 case Statement::Kind::kVarDeclaration: {
944 VarDeclaration& varDeclStmt = (*stmt)->as<VarDeclaration>();
945 // Don't need to scan the declaration's sizes; those are always IntLiterals.
Ethan Nicholasc51f33e2020-10-13 13:49:44 -0400946 this->visitExpression(&varDeclStmt.value());
John Stiles70957c82020-10-02 16:42:10 -0400947 break;
948 }
John Stiles70957c82020-10-02 16:42:10 -0400949 case Statement::Kind::kWhile: {
950 WhileStatement& whileStmt = (*stmt)->as<WhileStatement>();
951 // The loop body is a candidate for inlining.
Ethan Nicholas2a4952d2020-10-08 15:35:56 -0400952 this->visitStatement(&whileStmt.statement());
John Stiles70957c82020-10-02 16:42:10 -0400953 // The inliner isn't smart enough to inline the test-expression for a while loop at
954 // this time. There are two limitations:
955 // - We would need to insert the inlined-body block at the very beginning of the
956 // while loop's inner fStatement. We don't support that today, but it's doable.
957 // - The while-loop's built-in test-expression would need to be replaced with a
958 // `true` BoolLiteral, and the loop would be halted via a break statement at the
959 // end of the inlined test-expression. This is again something we don't support
960 // today, but it could be implemented.
961 break;
962 }
963 default:
964 SkUNREACHABLE;
John Stiles93442622020-09-11 12:11:27 -0400965 }
966
John Stiles70957c82020-10-02 16:42:10 -0400967 // Pop our symbol and enclosing-statement stacks.
968 fSymbolTableStack.resize(oldSymbolStackSize);
969 fEnclosingStmtStack.resize(oldEnclosingStmtStackSize);
970 }
971
972 void visitExpression(std::unique_ptr<Expression>* expr) {
973 if (!*expr) {
974 return;
John Stiles93442622020-09-11 12:11:27 -0400975 }
John Stiles70957c82020-10-02 16:42:10 -0400976
977 switch ((*expr)->kind()) {
978 case Expression::Kind::kBoolLiteral:
979 case Expression::Kind::kDefined:
980 case Expression::Kind::kExternalValue:
981 case Expression::Kind::kFieldAccess:
982 case Expression::Kind::kFloatLiteral:
983 case Expression::Kind::kFunctionReference:
984 case Expression::Kind::kIntLiteral:
985 case Expression::Kind::kNullLiteral:
986 case Expression::Kind::kSetting:
987 case Expression::Kind::kTypeReference:
988 case Expression::Kind::kVariableReference:
989 // Nothing to scan here.
990 break;
991
992 case Expression::Kind::kBinary: {
993 BinaryExpression& binaryExpr = (*expr)->as<BinaryExpression>();
John Stiles2d4f9592020-10-30 10:29:12 -0400994 this->visitExpression(&binaryExpr.left());
John Stiles70957c82020-10-02 16:42:10 -0400995
996 // Logical-and and logical-or binary expressions do not inline the right side,
997 // because that would invalidate short-circuiting. That is, when evaluating
998 // expressions like these:
999 // (false && x()) // always false
1000 // (true || y()) // always true
1001 // It is illegal for side-effects from x() or y() to occur. The simplest way to
1002 // enforce that rule is to avoid inlining the right side entirely. However, it is
1003 // safe for other types of binary expression to inline both sides.
1004 Token::Kind op = binaryExpr.getOperator();
1005 bool shortCircuitable = (op == Token::Kind::TK_LOGICALAND ||
1006 op == Token::Kind::TK_LOGICALOR);
1007 if (!shortCircuitable) {
John Stiles2d4f9592020-10-30 10:29:12 -04001008 this->visitExpression(&binaryExpr.right());
John Stiles70957c82020-10-02 16:42:10 -04001009 }
1010 break;
1011 }
1012 case Expression::Kind::kConstructor: {
1013 Constructor& constructorExpr = (*expr)->as<Constructor>();
1014 for (std::unique_ptr<Expression>& arg : constructorExpr.arguments()) {
1015 this->visitExpression(&arg);
1016 }
1017 break;
1018 }
1019 case Expression::Kind::kExternalFunctionCall: {
1020 ExternalFunctionCall& funcCallExpr = (*expr)->as<ExternalFunctionCall>();
1021 for (std::unique_ptr<Expression>& arg : funcCallExpr.arguments()) {
1022 this->visitExpression(&arg);
1023 }
1024 break;
1025 }
1026 case Expression::Kind::kFunctionCall: {
1027 FunctionCall& funcCallExpr = (*expr)->as<FunctionCall>();
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001028 for (std::unique_ptr<Expression>& arg : funcCallExpr.arguments()) {
John Stiles70957c82020-10-02 16:42:10 -04001029 this->visitExpression(&arg);
1030 }
1031 this->addInlineCandidate(expr);
1032 break;
1033 }
1034 case Expression::Kind::kIndex:{
1035 IndexExpression& indexExpr = (*expr)->as<IndexExpression>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04001036 this->visitExpression(&indexExpr.base());
1037 this->visitExpression(&indexExpr.index());
John Stiles70957c82020-10-02 16:42:10 -04001038 break;
1039 }
1040 case Expression::Kind::kPostfix: {
1041 PostfixExpression& postfixExpr = (*expr)->as<PostfixExpression>();
Ethan Nicholas444ccc62020-10-09 10:16:22 -04001042 this->visitExpression(&postfixExpr.operand());
John Stiles70957c82020-10-02 16:42:10 -04001043 break;
1044 }
1045 case Expression::Kind::kPrefix: {
1046 PrefixExpression& prefixExpr = (*expr)->as<PrefixExpression>();
Ethan Nicholas444ccc62020-10-09 10:16:22 -04001047 this->visitExpression(&prefixExpr.operand());
John Stiles70957c82020-10-02 16:42:10 -04001048 break;
1049 }
1050 case Expression::Kind::kSwizzle: {
1051 Swizzle& swizzleExpr = (*expr)->as<Swizzle>();
Ethan Nicholas6b4d5812020-10-12 16:11:51 -04001052 this->visitExpression(&swizzleExpr.base());
John Stiles70957c82020-10-02 16:42:10 -04001053 break;
1054 }
1055 case Expression::Kind::kTernary: {
1056 TernaryExpression& ternaryExpr = (*expr)->as<TernaryExpression>();
1057 // The test expression is a candidate for inlining.
Ethan Nicholasdd218162020-10-08 05:48:01 -04001058 this->visitExpression(&ternaryExpr.test());
John Stiles70957c82020-10-02 16:42:10 -04001059 // The true- and false-expressions cannot be inlined, because we are only allowed to
1060 // evaluate one side.
1061 break;
1062 }
1063 default:
1064 SkUNREACHABLE;
1065 }
1066 }
1067
1068 void addInlineCandidate(std::unique_ptr<Expression>* candidate) {
1069 fCandidateList->fCandidates.push_back(
1070 InlineCandidate{fSymbolTableStack.back(),
1071 find_parent_statement(fEnclosingStmtStack),
1072 fEnclosingStmtStack.back(),
1073 candidate,
John Stiles9b9415e2020-11-23 14:48:06 -05001074 fEnclosingFunction});
John Stiles70957c82020-10-02 16:42:10 -04001075 }
John Stiles2d7973a2020-10-02 15:01:03 -04001076};
John Stiles93442622020-09-11 12:11:27 -04001077
John Stiles9b9415e2020-11-23 14:48:06 -05001078static const FunctionDeclaration& candidate_func(const InlineCandidate& candidate) {
1079 return (*candidate.fCandidateExpr)->as<FunctionCall>().function();
1080}
John Stiles915a38c2020-09-14 09:38:13 -04001081
John Stiles9b9415e2020-11-23 14:48:06 -05001082bool Inliner::candidateCanBeInlined(const InlineCandidate& candidate, InlinabilityCache* cache) {
1083 const FunctionDeclaration& funcDecl = candidate_func(candidate);
John Stiles1c03d332020-10-13 10:30:23 -04001084 auto [iter, wasInserted] = cache->insert({&funcDecl, false});
John Stiles2d7973a2020-10-02 15:01:03 -04001085 if (wasInserted) {
1086 // Recursion is forbidden here to avoid an infinite death spiral of inlining.
John Stiles1c03d332020-10-13 10:30:23 -04001087 iter->second = this->isSafeToInline(funcDecl.definition()) &&
1088 !contains_recursive_call(funcDecl);
John Stiles93442622020-09-11 12:11:27 -04001089 }
1090
John Stiles2d7973a2020-10-02 15:01:03 -04001091 return iter->second;
1092}
1093
John Stiles9b9415e2020-11-23 14:48:06 -05001094int Inliner::getFunctionSize(const FunctionDeclaration& funcDecl, FunctionSizeCache* cache) {
1095 auto [iter, wasInserted] = cache->insert({&funcDecl, 0});
John Stiles2d7973a2020-10-02 15:01:03 -04001096 if (wasInserted) {
John Stiles9b9415e2020-11-23 14:48:06 -05001097 iter->second = Analysis::NodeCountUpToLimit(*funcDecl.definition(),
1098 fSettings->fInlineThreshold);
John Stiles2d7973a2020-10-02 15:01:03 -04001099 }
John Stiles2d7973a2020-10-02 15:01:03 -04001100 return iter->second;
1101}
1102
Brian Osman0006ad02020-11-18 15:38:39 -05001103void Inliner::buildCandidateList(const std::vector<std::unique_ptr<ProgramElement>>& elements,
John Stiles9b9415e2020-11-23 14:48:06 -05001104 SymbolTable* symbols, ProgramUsage* usage,
Brian Osman0006ad02020-11-18 15:38:39 -05001105 InlineCandidateList* candidateList) {
John Stiles2d7973a2020-10-02 15:01:03 -04001106 // This is structured much like a ProgramVisitor, but does not actually use ProgramVisitor.
1107 // The analyzer needs to keep track of the `unique_ptr<T>*` of statements and expressions so
1108 // that they can later be replaced, and ProgramVisitor does not provide this; it only provides a
1109 // `const T&`.
1110 InlineCandidateAnalyzer analyzer;
Brian Osman0006ad02020-11-18 15:38:39 -05001111 analyzer.visit(elements, symbols, candidateList);
John Stiles2d7973a2020-10-02 15:01:03 -04001112
John Stiles0ad233f2020-11-25 11:02:05 -05001113 // Early out if there are no inlining candidates.
John Stiles2d7973a2020-10-02 15:01:03 -04001114 std::vector<InlineCandidate>& candidates = candidateList->fCandidates;
John Stiles0ad233f2020-11-25 11:02:05 -05001115 if (candidates.empty()) {
1116 return;
1117 }
1118
1119 // Remove candidates that are not safe to inline.
John Stiles2d7973a2020-10-02 15:01:03 -04001120 InlinabilityCache cache;
1121 candidates.erase(std::remove_if(candidates.begin(),
1122 candidates.end(),
1123 [&](const InlineCandidate& candidate) {
1124 return !this->candidateCanBeInlined(candidate, &cache);
1125 }),
1126 candidates.end());
1127
John Stiles0ad233f2020-11-25 11:02:05 -05001128 // If the inline threshold is unlimited, or if we have no candidates left, our candidate list is
1129 // complete.
1130 if (fSettings->fInlineThreshold == INT_MAX || candidates.empty()) {
1131 return;
John Stiles2d7973a2020-10-02 15:01:03 -04001132 }
John Stiles0ad233f2020-11-25 11:02:05 -05001133
1134 // Remove candidates on a per-function basis if the effect of inlining would be to make more
1135 // than `inlineThreshold` nodes. (i.e. if Func() would be inlined six times and its size is
1136 // 10 nodes, it should be inlined if the inlineThreshold is 60 or higher.)
1137 FunctionSizeCache functionSizeCache;
1138 FunctionSizeCache candidateTotalCost;
1139 for (InlineCandidate& candidate : candidates) {
1140 const FunctionDeclaration& fnDecl = candidate_func(candidate);
1141 candidateTotalCost[&fnDecl] += this->getFunctionSize(fnDecl, &functionSizeCache);
1142 }
1143
1144 candidates.erase(
1145 std::remove_if(candidates.begin(),
1146 candidates.end(),
1147 [&](const InlineCandidate& candidate) {
1148 const FunctionDeclaration& fnDecl = candidate_func(candidate);
1149 if (fnDecl.modifiers().fFlags & Modifiers::kInline_Flag) {
1150 // Functions marked `inline` ignore size limitations.
1151 return false;
1152 }
1153 if (usage->get(fnDecl) == 1) {
1154 // If a function is only used once, it's cost-free to inline.
1155 return false;
1156 }
1157 if (candidateTotalCost[&fnDecl] <= fSettings->fInlineThreshold) {
1158 // We won't exceed the inline threshold by inlining this.
1159 return false;
1160 }
1161 // Inlining this function will add too many IRNodes.
1162 return true;
1163 }),
1164 candidates.end());
John Stiles2d7973a2020-10-02 15:01:03 -04001165}
1166
Brian Osman0006ad02020-11-18 15:38:39 -05001167bool Inliner::analyze(const std::vector<std::unique_ptr<ProgramElement>>& elements,
1168 SymbolTable* symbols,
1169 ProgramUsage* usage) {
John Stilesd34d56e2020-10-12 12:04:47 -04001170 // A threshold of zero indicates that the inliner is completely disabled, so we can just return.
1171 if (fSettings->fInlineThreshold <= 0) {
1172 return false;
1173 }
1174
John Stiles031a7672020-11-13 16:13:18 -05001175 // Enforce a limit on inlining to avoid pathological cases. (inliner/ExponentialGrowth.sksl)
1176 if (fInlinedStatementCounter >= kInlinedStatementLimit) {
1177 return false;
1178 }
1179
John Stiles2d7973a2020-10-02 15:01:03 -04001180 InlineCandidateList candidateList;
John Stiles9b9415e2020-11-23 14:48:06 -05001181 this->buildCandidateList(elements, symbols, usage, &candidateList);
John Stiles2d7973a2020-10-02 15:01:03 -04001182
John Stiles915a38c2020-09-14 09:38:13 -04001183 // Inline the candidates where we've determined that it's safe to do so.
1184 std::unordered_set<const std::unique_ptr<Statement>*> enclosingStmtSet;
1185 bool madeChanges = false;
John Stiles2d7973a2020-10-02 15:01:03 -04001186 for (const InlineCandidate& candidate : candidateList.fCandidates) {
John Stiles915a38c2020-09-14 09:38:13 -04001187 FunctionCall& funcCall = (*candidate.fCandidateExpr)->as<FunctionCall>();
John Stiles915a38c2020-09-14 09:38:13 -04001188
1189 // Inlining two expressions using the same enclosing statement in the same inlining pass
1190 // does not work properly. If this happens, skip it; we'll get it in the next pass.
1191 auto [unusedIter, inserted] = enclosingStmtSet.insert(candidate.fEnclosingStmt);
1192 if (!inserted) {
1193 continue;
1194 }
1195
1196 // Convert the function call to its inlined equivalent.
Brian Osman3887a012020-09-30 13:22:27 -04001197 InlinedCall inlinedCall = this->inlineCall(&funcCall, candidate.fSymbols,
Ethan Nicholas0a5d0962020-10-14 13:33:18 -04001198 &candidate.fEnclosingFunction->declaration());
John Stiles915a38c2020-09-14 09:38:13 -04001199 if (inlinedCall.fInlinedBody) {
1200 // Ensure that the inlined body has a scope if it needs one.
John Stiles6d696082020-10-01 10:18:54 -04001201 this->ensureScopedBlocks(inlinedCall.fInlinedBody.get(), candidate.fParentStmt->get());
John Stiles915a38c2020-09-14 09:38:13 -04001202
Brian Osman010ce6a2020-10-19 16:34:10 -04001203 // Add references within the inlined body
1204 usage->add(inlinedCall.fInlinedBody.get());
1205
John Stiles915a38c2020-09-14 09:38:13 -04001206 // Move the enclosing statement to the end of the unscoped Block containing the inlined
1207 // function, then replace the enclosing statement with that Block.
1208 // Before:
1209 // fInlinedBody = Block{ stmt1, stmt2, stmt3 }
1210 // fEnclosingStmt = stmt4
1211 // After:
1212 // fInlinedBody = null
1213 // fEnclosingStmt = Block{ stmt1, stmt2, stmt3, stmt4 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001214 inlinedCall.fInlinedBody->children().push_back(std::move(*candidate.fEnclosingStmt));
John Stiles915a38c2020-09-14 09:38:13 -04001215 *candidate.fEnclosingStmt = std::move(inlinedCall.fInlinedBody);
1216 }
1217
1218 // Replace the candidate function call with our replacement expression.
Brian Osman010ce6a2020-10-19 16:34:10 -04001219 usage->replace(candidate.fCandidateExpr->get(), inlinedCall.fReplacementExpr.get());
John Stiles915a38c2020-09-14 09:38:13 -04001220 *candidate.fCandidateExpr = std::move(inlinedCall.fReplacementExpr);
1221 madeChanges = true;
1222
John Stiles031a7672020-11-13 16:13:18 -05001223 // Stop inlining if we've reached our hard cap on new statements.
1224 if (fInlinedStatementCounter >= kInlinedStatementLimit) {
1225 break;
1226 }
1227
John Stiles915a38c2020-09-14 09:38:13 -04001228 // Note that nothing was destroyed except for the FunctionCall. All other nodes should
1229 // remain valid.
1230 }
1231
1232 return madeChanges;
John Stiles93442622020-09-11 12:11:27 -04001233}
1234
John Stiles44e96be2020-08-31 13:16:04 -04001235} // namespace SkSL