blob: 2f7f621183c969cb6ff7799d9d28dc4069a6c5f5 [file] [log] [blame]
John Stiles44e96be2020-08-31 13:16:04 -04001/*
2 * Copyright 2020 Google LLC
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
7
8#include "src/sksl/SkSLInliner.h"
9
John Stiles2d7973a2020-10-02 15:01:03 -040010#include <limits.h>
John Stiles44e96be2020-08-31 13:16:04 -040011#include <memory>
12#include <unordered_set>
13
14#include "src/sksl/SkSLAnalysis.h"
15#include "src/sksl/ir/SkSLBinaryExpression.h"
16#include "src/sksl/ir/SkSLBoolLiteral.h"
17#include "src/sksl/ir/SkSLBreakStatement.h"
18#include "src/sksl/ir/SkSLConstructor.h"
19#include "src/sksl/ir/SkSLContinueStatement.h"
20#include "src/sksl/ir/SkSLDiscardStatement.h"
21#include "src/sksl/ir/SkSLDoStatement.h"
22#include "src/sksl/ir/SkSLEnum.h"
23#include "src/sksl/ir/SkSLExpressionStatement.h"
24#include "src/sksl/ir/SkSLExternalFunctionCall.h"
25#include "src/sksl/ir/SkSLExternalValueReference.h"
26#include "src/sksl/ir/SkSLField.h"
27#include "src/sksl/ir/SkSLFieldAccess.h"
28#include "src/sksl/ir/SkSLFloatLiteral.h"
29#include "src/sksl/ir/SkSLForStatement.h"
30#include "src/sksl/ir/SkSLFunctionCall.h"
31#include "src/sksl/ir/SkSLFunctionDeclaration.h"
32#include "src/sksl/ir/SkSLFunctionDefinition.h"
33#include "src/sksl/ir/SkSLFunctionReference.h"
34#include "src/sksl/ir/SkSLIfStatement.h"
35#include "src/sksl/ir/SkSLIndexExpression.h"
John Stiles98c1f822020-09-09 14:18:53 -040036#include "src/sksl/ir/SkSLInlineMarker.h"
John Stiles44e96be2020-08-31 13:16:04 -040037#include "src/sksl/ir/SkSLIntLiteral.h"
38#include "src/sksl/ir/SkSLInterfaceBlock.h"
39#include "src/sksl/ir/SkSLLayout.h"
40#include "src/sksl/ir/SkSLNop.h"
41#include "src/sksl/ir/SkSLNullLiteral.h"
42#include "src/sksl/ir/SkSLPostfixExpression.h"
43#include "src/sksl/ir/SkSLPrefixExpression.h"
44#include "src/sksl/ir/SkSLReturnStatement.h"
45#include "src/sksl/ir/SkSLSetting.h"
46#include "src/sksl/ir/SkSLSwitchCase.h"
47#include "src/sksl/ir/SkSLSwitchStatement.h"
48#include "src/sksl/ir/SkSLSwizzle.h"
49#include "src/sksl/ir/SkSLTernaryExpression.h"
50#include "src/sksl/ir/SkSLUnresolvedFunction.h"
51#include "src/sksl/ir/SkSLVarDeclarations.h"
John Stiles44e96be2020-08-31 13:16:04 -040052#include "src/sksl/ir/SkSLVariable.h"
53#include "src/sksl/ir/SkSLVariableReference.h"
John Stiles44e96be2020-08-31 13:16:04 -040054
55namespace SkSL {
56namespace {
57
John Stiles031a7672020-11-13 16:13:18 -050058static constexpr int kInlinedStatementLimit = 2500;
59
John Stiles44e96be2020-08-31 13:16:04 -040060static int count_returns_at_end_of_control_flow(const FunctionDefinition& funcDef) {
61 class CountReturnsAtEndOfControlFlow : public ProgramVisitor {
62 public:
63 CountReturnsAtEndOfControlFlow(const FunctionDefinition& funcDef) {
64 this->visitProgramElement(funcDef);
65 }
66
67 bool visitStatement(const Statement& stmt) override {
Ethan Nicholase6592142020-09-08 10:22:09 -040068 switch (stmt.kind()) {
69 case Statement::Kind::kBlock: {
John Stiles44e96be2020-08-31 13:16:04 -040070 // Check only the last statement of a block.
Ethan Nicholas7bd60432020-09-25 14:31:59 -040071 const auto& block = stmt.as<Block>();
72 return block.children().size() &&
73 this->visitStatement(*block.children().back());
John Stiles44e96be2020-08-31 13:16:04 -040074 }
Ethan Nicholase6592142020-09-08 10:22:09 -040075 case Statement::Kind::kSwitch:
Ethan Nicholase6592142020-09-08 10:22:09 -040076 case Statement::Kind::kDo:
77 case Statement::Kind::kFor:
John Stiles44e96be2020-08-31 13:16:04 -040078 // Don't introspect switches or loop structures at all.
79 return false;
80
Ethan Nicholase6592142020-09-08 10:22:09 -040081 case Statement::Kind::kReturn:
John Stiles44e96be2020-08-31 13:16:04 -040082 ++fNumReturns;
83 [[fallthrough]];
84
85 default:
John Stiles93442622020-09-11 12:11:27 -040086 return INHERITED::visitStatement(stmt);
John Stiles44e96be2020-08-31 13:16:04 -040087 }
88 }
89
90 int fNumReturns = 0;
91 using INHERITED = ProgramVisitor;
92 };
93
94 return CountReturnsAtEndOfControlFlow{funcDef}.fNumReturns;
95}
96
97static int count_returns_in_breakable_constructs(const FunctionDefinition& funcDef) {
98 class CountReturnsInBreakableConstructs : public ProgramVisitor {
99 public:
100 CountReturnsInBreakableConstructs(const FunctionDefinition& funcDef) {
101 this->visitProgramElement(funcDef);
102 }
103
104 bool visitStatement(const Statement& stmt) override {
Ethan Nicholase6592142020-09-08 10:22:09 -0400105 switch (stmt.kind()) {
106 case Statement::Kind::kSwitch:
Ethan Nicholase6592142020-09-08 10:22:09 -0400107 case Statement::Kind::kDo:
108 case Statement::Kind::kFor: {
John Stiles44e96be2020-08-31 13:16:04 -0400109 ++fInsideBreakableConstruct;
John Stiles93442622020-09-11 12:11:27 -0400110 bool result = INHERITED::visitStatement(stmt);
John Stiles44e96be2020-08-31 13:16:04 -0400111 --fInsideBreakableConstruct;
112 return result;
113 }
114
Ethan Nicholase6592142020-09-08 10:22:09 -0400115 case Statement::Kind::kReturn:
John Stiles44e96be2020-08-31 13:16:04 -0400116 fNumReturns += (fInsideBreakableConstruct > 0) ? 1 : 0;
117 [[fallthrough]];
118
119 default:
John Stiles93442622020-09-11 12:11:27 -0400120 return INHERITED::visitStatement(stmt);
John Stiles44e96be2020-08-31 13:16:04 -0400121 }
122 }
123
124 int fNumReturns = 0;
125 int fInsideBreakableConstruct = 0;
126 using INHERITED = ProgramVisitor;
127 };
128
129 return CountReturnsInBreakableConstructs{funcDef}.fNumReturns;
130}
131
John Stiles991b09d2020-09-10 13:33:40 -0400132static bool contains_recursive_call(const FunctionDeclaration& funcDecl) {
133 class ContainsRecursiveCall : public ProgramVisitor {
134 public:
135 bool visit(const FunctionDeclaration& funcDecl) {
136 fFuncDecl = &funcDecl;
Ethan Nicholased84b732020-10-08 11:45:44 -0400137 return funcDecl.definition() ? this->visitProgramElement(*funcDecl.definition())
138 : false;
John Stiles991b09d2020-09-10 13:33:40 -0400139 }
140
141 bool visitExpression(const Expression& expr) override {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400142 if (expr.is<FunctionCall>() && expr.as<FunctionCall>().function().matches(*fFuncDecl)) {
John Stiles991b09d2020-09-10 13:33:40 -0400143 return true;
144 }
145 return INHERITED::visitExpression(expr);
146 }
147
148 bool visitStatement(const Statement& stmt) override {
Ethan Nicholasceb62142020-10-09 16:51:18 -0400149 if (stmt.is<InlineMarker>() &&
150 stmt.as<InlineMarker>().function().matches(*fFuncDecl)) {
John Stiles991b09d2020-09-10 13:33:40 -0400151 return true;
152 }
153 return INHERITED::visitStatement(stmt);
154 }
155
156 const FunctionDeclaration* fFuncDecl;
157 using INHERITED = ProgramVisitor;
158 };
159
160 return ContainsRecursiveCall{}.visit(funcDecl);
161}
162
John Stiles44e96be2020-08-31 13:16:04 -0400163static const Type* copy_if_needed(const Type* src, SymbolTable& symbolTable) {
John Stilesc0c51062020-12-03 17:16:29 -0500164 if (src->isArray()) {
John Stiles74ff1d62020-11-30 11:56:16 -0500165 const Type* innerType = copy_if_needed(&src->componentType(), symbolTable);
John Stilesad2d4942020-12-11 16:55:58 -0500166 return symbolTable.takeOwnershipOfSymbol(Type::MakeArrayType(src->name(), *innerType,
167 src->columns()));
John Stiles44e96be2020-08-31 13:16:04 -0400168 }
169 return src;
170}
171
John Stiles6d696082020-10-01 10:18:54 -0400172static std::unique_ptr<Statement>* find_parent_statement(
173 const std::vector<std::unique_ptr<Statement>*>& stmtStack) {
John Stiles915a38c2020-09-14 09:38:13 -0400174 SkASSERT(!stmtStack.empty());
175
176 // Walk the statement stack from back to front, ignoring the last element (which is the
177 // enclosing statement).
178 auto iter = stmtStack.rbegin();
179 ++iter;
180
181 // Anything counts as a parent statement other than a scopeless Block.
182 for (; iter != stmtStack.rend(); ++iter) {
John Stiles6d696082020-10-01 10:18:54 -0400183 std::unique_ptr<Statement>* stmt = *iter;
184 if (!(*stmt)->is<Block>() || (*stmt)->as<Block>().isScope()) {
John Stiles915a38c2020-09-14 09:38:13 -0400185 return stmt;
186 }
187 }
188
189 // There wasn't any parent statement to be found.
190 return nullptr;
191}
192
John Stilese41b4ee2020-09-28 12:28:16 -0400193std::unique_ptr<Expression> clone_with_ref_kind(const Expression& expr,
194 VariableReference::RefKind refKind) {
195 std::unique_ptr<Expression> clone = expr.clone();
John Stiles70b82422020-09-30 10:55:12 -0400196 class SetRefKindInExpression : public ProgramWriter {
John Stilese41b4ee2020-09-28 12:28:16 -0400197 public:
198 SetRefKindInExpression(VariableReference::RefKind refKind) : fRefKind(refKind) {}
John Stiles70b82422020-09-30 10:55:12 -0400199 bool visitExpression(Expression& expr) override {
John Stilese41b4ee2020-09-28 12:28:16 -0400200 if (expr.is<VariableReference>()) {
John Stiles70b82422020-09-30 10:55:12 -0400201 expr.as<VariableReference>().setRefKind(fRefKind);
John Stilese41b4ee2020-09-28 12:28:16 -0400202 }
203 return INHERITED::visitExpression(expr);
204 }
205
206 private:
207 VariableReference::RefKind fRefKind;
208
John Stiles70b82422020-09-30 10:55:12 -0400209 using INHERITED = ProgramWriter;
John Stilese41b4ee2020-09-28 12:28:16 -0400210 };
211
212 SetRefKindInExpression{refKind}.visitExpression(*clone);
213 return clone;
214}
215
John Stiles77702f12020-12-17 14:38:56 -0500216class CountReturnsWithLimit : public ProgramVisitor {
217public:
218 CountReturnsWithLimit(const FunctionDefinition& funcDef, int limit) : fLimit(limit) {
219 this->visitProgramElement(funcDef);
220 }
221
222 bool visitStatement(const Statement& stmt) override {
223 switch (stmt.kind()) {
224 case Statement::Kind::kReturn: {
225 ++fNumReturns;
226 fDeepestReturn = std::max(fDeepestReturn, fScopedBlockDepth);
227 return (fNumReturns >= fLimit) || INHERITED::visitStatement(stmt);
228 }
229 case Statement::Kind::kBlock: {
230 int depthIncrement = stmt.as<Block>().isScope() ? 1 : 0;
231 fScopedBlockDepth += depthIncrement;
232 bool result = INHERITED::visitStatement(stmt);
233 fScopedBlockDepth -= depthIncrement;
234 return result;
235 }
236 default:
237 return INHERITED::visitStatement(stmt);
238 }
239 }
240
241 int fNumReturns = 0;
242 int fDeepestReturn = 0;
243 int fLimit = 0;
244 int fScopedBlockDepth = 0;
245 using INHERITED = ProgramVisitor;
246};
247
John Stiles44e96be2020-08-31 13:16:04 -0400248} // namespace
249
John Stiles77702f12020-12-17 14:38:56 -0500250Inliner::ReturnComplexity Inliner::GetReturnComplexity(const FunctionDefinition& funcDef) {
251 int returnsAtEndOfControlFlow = count_returns_at_end_of_control_flow(funcDef);
252 CountReturnsWithLimit counter{funcDef, returnsAtEndOfControlFlow + 1};
253
254 if (counter.fNumReturns > returnsAtEndOfControlFlow) {
255 return ReturnComplexity::kEarlyReturns;
256 }
257 if (counter.fNumReturns > 1 || counter.fDeepestReturn > 1) {
258 return ReturnComplexity::kScopedReturns;
259 }
260 return ReturnComplexity::kSingleTopLevelReturn;
261}
262
John Stilesb61ee902020-09-21 12:26:59 -0400263void Inliner::ensureScopedBlocks(Statement* inlinedBody, Statement* parentStmt) {
264 // No changes necessary if this statement isn't actually a block.
265 if (!inlinedBody || !inlinedBody->is<Block>()) {
266 return;
267 }
268
269 // No changes necessary if the parent statement doesn't require a scope.
270 if (!parentStmt || !(parentStmt->is<IfStatement>() || parentStmt->is<ForStatement>() ||
Brian Osmand6f23382020-12-15 17:08:59 -0500271 parentStmt->is<DoStatement>())) {
John Stilesb61ee902020-09-21 12:26:59 -0400272 return;
273 }
274
275 Block& block = inlinedBody->as<Block>();
276
277 // The inliner will create inlined function bodies as a Block containing multiple statements,
278 // but no scope. Normally, this is fine, but if this block is used as the statement for a
279 // do/for/if/while, this isn't actually possible to represent textually; a scope must be added
280 // for the generated code to match the intent. In the case of Blocks nested inside other Blocks,
281 // we add the scope to the outermost block if needed. Zero-statement blocks have similar
282 // issues--if we don't represent the Block textually somehow, we run the risk of accidentally
283 // absorbing the following statement into our loop--so we also add a scope to these.
284 for (Block* nestedBlock = &block;; ) {
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400285 if (nestedBlock->isScope()) {
John Stilesb61ee902020-09-21 12:26:59 -0400286 // We found an explicit scope; all is well.
287 return;
288 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400289 if (nestedBlock->children().size() != 1) {
John Stilesb61ee902020-09-21 12:26:59 -0400290 // We found a block with multiple (or zero) statements, but no scope? Let's add a scope
291 // to the outermost block.
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400292 block.setIsScope(true);
John Stilesb61ee902020-09-21 12:26:59 -0400293 return;
294 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400295 if (!nestedBlock->children()[0]->is<Block>()) {
John Stilesb61ee902020-09-21 12:26:59 -0400296 // This block has exactly one thing inside, and it's not another block. No need to scope
297 // it.
298 return;
299 }
300 // We have to go deeper.
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400301 nestedBlock = &nestedBlock->children()[0]->as<Block>();
John Stilesb61ee902020-09-21 12:26:59 -0400302 }
303}
304
Brian Osman0006ad02020-11-18 15:38:39 -0500305void Inliner::reset(ModifiersPool* modifiers, const Program::Settings* settings) {
Ethan Nicholas041fd0a2020-10-07 16:42:04 -0400306 fModifiers = modifiers;
307 fSettings = settings;
John Stiles44e96be2020-08-31 13:16:04 -0400308 fInlineVarCounter = 0;
John Stiles031a7672020-11-13 16:13:18 -0500309 fInlinedStatementCounter = 0;
John Stiles44e96be2020-08-31 13:16:04 -0400310}
311
John Stiles6f31e272020-12-16 13:30:54 -0500312String Inliner::uniqueNameForInlineVar(String baseName, SymbolTable* symbolTable) {
313 // The inliner runs more than once, so the base name might already have a prefix like "_123_x".
314 // Let's strip that prefix off to make the generated code easier to read.
315 if (baseName.startsWith("_")) {
316 // Determine if we have a string of digits.
317 int offset = 1;
318 while (isdigit(baseName[offset])) {
319 ++offset;
320 }
321 // If we found digits, another underscore, and anything else, that's the inliner prefix.
322 // Strip it off.
323 if (offset > 1 && baseName[offset] == '_' && baseName[offset + 1] != '\0') {
324 baseName.erase(0, offset + 1);
325 } else {
326 // This name doesn't contain an inliner prefix, but it does start with an underscore.
327 // OpenGL disallows two consecutive underscores anywhere in the string, and we'll be
328 // adding one as part of the inliner prefix, so strip the leading underscore.
329 baseName.erase(0, 1);
330 }
331 }
John Stilesc75abb82020-09-14 18:24:12 -0400332
333 // Append a unique numeric prefix to avoid name overlap. Check the symbol table to make sure
334 // we're not reusing an existing name. (Note that within a single compilation pass, this check
335 // isn't fully comprehensive, as code isn't always generated in top-to-bottom order.)
336 String uniqueName;
337 for (;;) {
John Stiles6f31e272020-12-16 13:30:54 -0500338 uniqueName = String::printf("_%d_%s", fInlineVarCounter++, baseName.c_str());
John Stilesc75abb82020-09-14 18:24:12 -0400339 StringFragment frag{uniqueName.data(), uniqueName.length()};
340 if ((*symbolTable)[frag] == nullptr) {
341 break;
342 }
343 }
344
345 return uniqueName;
346}
347
John Stiles44e96be2020-08-31 13:16:04 -0400348std::unique_ptr<Expression> Inliner::inlineExpression(int offset,
349 VariableRewriteMap* varMap,
John Stilesd7cc0932020-11-30 12:24:27 -0500350 SymbolTable* symbolTableForExpression,
John Stiles44e96be2020-08-31 13:16:04 -0400351 const Expression& expression) {
352 auto expr = [&](const std::unique_ptr<Expression>& e) -> std::unique_ptr<Expression> {
353 if (e) {
John Stilesd7cc0932020-11-30 12:24:27 -0500354 return this->inlineExpression(offset, varMap, symbolTableForExpression, *e);
John Stiles44e96be2020-08-31 13:16:04 -0400355 }
356 return nullptr;
357 };
John Stiles8e3b6be2020-10-13 11:14:08 -0400358 auto argList = [&](const ExpressionArray& originalArgs) -> ExpressionArray {
359 ExpressionArray args;
John Stilesf4bda742020-10-14 16:57:41 -0400360 args.reserve_back(originalArgs.size());
John Stiles44e96be2020-08-31 13:16:04 -0400361 for (const std::unique_ptr<Expression>& arg : originalArgs) {
362 args.push_back(expr(arg));
363 }
364 return args;
365 };
366
Ethan Nicholase6592142020-09-08 10:22:09 -0400367 switch (expression.kind()) {
368 case Expression::Kind::kBinary: {
John Stiles44e96be2020-08-31 13:16:04 -0400369 const BinaryExpression& b = expression.as<BinaryExpression>();
370 return std::make_unique<BinaryExpression>(offset,
John Stiles2d4f9592020-10-30 10:29:12 -0400371 expr(b.left()),
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400372 b.getOperator(),
John Stiles2d4f9592020-10-30 10:29:12 -0400373 expr(b.right()),
Ethan Nicholas30d30222020-09-11 12:27:26 -0400374 &b.type());
John Stiles44e96be2020-08-31 13:16:04 -0400375 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400376 case Expression::Kind::kBoolLiteral:
377 case Expression::Kind::kIntLiteral:
378 case Expression::Kind::kFloatLiteral:
379 case Expression::Kind::kNullLiteral:
John Stiles44e96be2020-08-31 13:16:04 -0400380 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400381 case Expression::Kind::kConstructor: {
John Stiles44e96be2020-08-31 13:16:04 -0400382 const Constructor& constructor = expression.as<Constructor>();
John Stilesd7cc0932020-11-30 12:24:27 -0500383 const Type* type = copy_if_needed(&constructor.type(), *symbolTableForExpression);
384 return std::make_unique<Constructor>(offset, type, argList(constructor.arguments()));
John Stiles44e96be2020-08-31 13:16:04 -0400385 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400386 case Expression::Kind::kExternalFunctionCall: {
John Stiles44e96be2020-08-31 13:16:04 -0400387 const ExternalFunctionCall& externalCall = expression.as<ExternalFunctionCall>();
Ethan Nicholas444ccc62020-10-09 10:16:22 -0400388 return std::make_unique<ExternalFunctionCall>(offset, &externalCall.function(),
Ethan Nicholas6e86ec92020-09-30 14:29:56 -0400389 argList(externalCall.arguments()));
John Stiles44e96be2020-08-31 13:16:04 -0400390 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400391 case Expression::Kind::kExternalValue:
John Stiles44e96be2020-08-31 13:16:04 -0400392 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400393 case Expression::Kind::kFieldAccess: {
John Stiles44e96be2020-08-31 13:16:04 -0400394 const FieldAccess& f = expression.as<FieldAccess>();
Ethan Nicholas7a95b202020-10-09 11:55:40 -0400395 return std::make_unique<FieldAccess>(expr(f.base()), f.fieldIndex(), f.ownerKind());
John Stiles44e96be2020-08-31 13:16:04 -0400396 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400397 case Expression::Kind::kFunctionCall: {
John Stiles44e96be2020-08-31 13:16:04 -0400398 const FunctionCall& funcCall = expression.as<FunctionCall>();
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400399 return std::make_unique<FunctionCall>(offset, &funcCall.type(), &funcCall.function(),
400 argList(funcCall.arguments()));
John Stiles44e96be2020-08-31 13:16:04 -0400401 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400402 case Expression::Kind::kFunctionReference:
Brian Osman2b3b35f2020-09-08 09:17:36 -0400403 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400404 case Expression::Kind::kIndex: {
John Stiles44e96be2020-08-31 13:16:04 -0400405 const IndexExpression& idx = expression.as<IndexExpression>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -0400406 return std::make_unique<IndexExpression>(*fContext, expr(idx.base()),
407 expr(idx.index()));
John Stiles44e96be2020-08-31 13:16:04 -0400408 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400409 case Expression::Kind::kPrefix: {
John Stiles44e96be2020-08-31 13:16:04 -0400410 const PrefixExpression& p = expression.as<PrefixExpression>();
Ethan Nicholas444ccc62020-10-09 10:16:22 -0400411 return std::make_unique<PrefixExpression>(p.getOperator(), expr(p.operand()));
John Stiles44e96be2020-08-31 13:16:04 -0400412 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400413 case Expression::Kind::kPostfix: {
John Stiles44e96be2020-08-31 13:16:04 -0400414 const PostfixExpression& p = expression.as<PostfixExpression>();
Ethan Nicholas444ccc62020-10-09 10:16:22 -0400415 return std::make_unique<PostfixExpression>(expr(p.operand()), p.getOperator());
John Stiles44e96be2020-08-31 13:16:04 -0400416 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400417 case Expression::Kind::kSetting:
John Stiles44e96be2020-08-31 13:16:04 -0400418 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400419 case Expression::Kind::kSwizzle: {
John Stiles44e96be2020-08-31 13:16:04 -0400420 const Swizzle& s = expression.as<Swizzle>();
Ethan Nicholas6b4d5812020-10-12 16:11:51 -0400421 return std::make_unique<Swizzle>(*fContext, expr(s.base()), s.components());
John Stiles44e96be2020-08-31 13:16:04 -0400422 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400423 case Expression::Kind::kTernary: {
John Stiles44e96be2020-08-31 13:16:04 -0400424 const TernaryExpression& t = expression.as<TernaryExpression>();
Ethan Nicholasdd218162020-10-08 05:48:01 -0400425 return std::make_unique<TernaryExpression>(offset, expr(t.test()),
426 expr(t.ifTrue()), expr(t.ifFalse()));
John Stiles44e96be2020-08-31 13:16:04 -0400427 }
Brian Osman83ba9302020-09-11 13:33:46 -0400428 case Expression::Kind::kTypeReference:
429 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400430 case Expression::Kind::kVariableReference: {
John Stiles44e96be2020-08-31 13:16:04 -0400431 const VariableReference& v = expression.as<VariableReference>();
Ethan Nicholas78686922020-10-08 06:46:27 -0400432 auto varMapIter = varMap->find(v.variable());
John Stilese41b4ee2020-09-28 12:28:16 -0400433 if (varMapIter != varMap->end()) {
Ethan Nicholas78686922020-10-08 06:46:27 -0400434 return clone_with_ref_kind(*varMapIter->second, v.refKind());
John Stiles44e96be2020-08-31 13:16:04 -0400435 }
436 return v.clone();
437 }
438 default:
439 SkASSERT(false);
440 return nullptr;
441 }
442}
443
444std::unique_ptr<Statement> Inliner::inlineStatement(int offset,
445 VariableRewriteMap* varMap,
446 SymbolTable* symbolTableForStatement,
John Stiles77702f12020-12-17 14:38:56 -0500447 std::unique_ptr<Expression>* resultExpr,
448 ReturnComplexity returnComplexity,
Brian Osman3887a012020-09-30 13:22:27 -0400449 const Statement& statement,
450 bool isBuiltinCode) {
John Stiles44e96be2020-08-31 13:16:04 -0400451 auto stmt = [&](const std::unique_ptr<Statement>& s) -> std::unique_ptr<Statement> {
452 if (s) {
John Stilesa5f3c312020-09-22 12:05:16 -0400453 return this->inlineStatement(offset, varMap, symbolTableForStatement, resultExpr,
John Stiles77702f12020-12-17 14:38:56 -0500454 returnComplexity, *s, isBuiltinCode);
John Stiles44e96be2020-08-31 13:16:04 -0400455 }
456 return nullptr;
457 };
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400458 auto blockStmts = [&](const Block& block) {
John Stiles8f2a0cf2020-10-13 12:48:21 -0400459 StatementArray result;
John Stilesf4bda742020-10-14 16:57:41 -0400460 result.reserve_back(block.children().size());
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400461 for (const std::unique_ptr<Statement>& child : block.children()) {
462 result.push_back(stmt(child));
463 }
464 return result;
465 };
John Stiles8f2a0cf2020-10-13 12:48:21 -0400466 auto stmts = [&](const StatementArray& ss) {
467 StatementArray result;
John Stilesf4bda742020-10-14 16:57:41 -0400468 result.reserve_back(ss.size());
John Stiles44e96be2020-08-31 13:16:04 -0400469 for (const auto& s : ss) {
470 result.push_back(stmt(s));
471 }
472 return result;
473 };
474 auto expr = [&](const std::unique_ptr<Expression>& e) -> std::unique_ptr<Expression> {
475 if (e) {
John Stilesd7cc0932020-11-30 12:24:27 -0500476 return this->inlineExpression(offset, varMap, symbolTableForStatement, *e);
John Stiles44e96be2020-08-31 13:16:04 -0400477 }
478 return nullptr;
479 };
John Stiles031a7672020-11-13 16:13:18 -0500480
481 ++fInlinedStatementCounter;
482
Ethan Nicholase6592142020-09-08 10:22:09 -0400483 switch (statement.kind()) {
484 case Statement::Kind::kBlock: {
John Stiles44e96be2020-08-31 13:16:04 -0400485 const Block& b = statement.as<Block>();
John Stilesa1e2b412020-10-20 14:51:28 -0400486 return std::make_unique<Block>(offset, blockStmts(b),
487 SymbolTable::WrapIfBuiltin(b.symbolTable()),
488 b.isScope());
John Stiles44e96be2020-08-31 13:16:04 -0400489 }
490
Ethan Nicholase6592142020-09-08 10:22:09 -0400491 case Statement::Kind::kBreak:
492 case Statement::Kind::kContinue:
493 case Statement::Kind::kDiscard:
John Stiles44e96be2020-08-31 13:16:04 -0400494 return statement.clone();
495
Ethan Nicholase6592142020-09-08 10:22:09 -0400496 case Statement::Kind::kDo: {
John Stiles44e96be2020-08-31 13:16:04 -0400497 const DoStatement& d = statement.as<DoStatement>();
Ethan Nicholas1fd61162020-09-28 13:14:19 -0400498 return std::make_unique<DoStatement>(offset, stmt(d.statement()), expr(d.test()));
John Stiles44e96be2020-08-31 13:16:04 -0400499 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400500 case Statement::Kind::kExpression: {
John Stiles44e96be2020-08-31 13:16:04 -0400501 const ExpressionStatement& e = statement.as<ExpressionStatement>();
Ethan Nicholasd503a5a2020-09-30 09:29:55 -0400502 return std::make_unique<ExpressionStatement>(expr(e.expression()));
John Stiles44e96be2020-08-31 13:16:04 -0400503 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400504 case Statement::Kind::kFor: {
John Stiles44e96be2020-08-31 13:16:04 -0400505 const ForStatement& f = statement.as<ForStatement>();
506 // need to ensure initializer is evaluated first so that we've already remapped its
507 // declarations by the time we evaluate test & next
Ethan Nicholas0d31ed52020-10-05 14:47:09 -0400508 std::unique_ptr<Statement> initializer = stmt(f.initializer());
509 return std::make_unique<ForStatement>(offset, std::move(initializer), expr(f.test()),
John Stilesa1e2b412020-10-20 14:51:28 -0400510 expr(f.next()), stmt(f.statement()),
511 SymbolTable::WrapIfBuiltin(f.symbols()));
John Stiles44e96be2020-08-31 13:16:04 -0400512 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400513 case Statement::Kind::kIf: {
John Stiles44e96be2020-08-31 13:16:04 -0400514 const IfStatement& i = statement.as<IfStatement>();
Ethan Nicholas8c44eca2020-10-07 16:47:09 -0400515 return std::make_unique<IfStatement>(offset, i.isStatic(), expr(i.test()),
516 stmt(i.ifTrue()), stmt(i.ifFalse()));
John Stiles44e96be2020-08-31 13:16:04 -0400517 }
John Stiles98c1f822020-09-09 14:18:53 -0400518 case Statement::Kind::kInlineMarker:
Ethan Nicholase6592142020-09-08 10:22:09 -0400519 case Statement::Kind::kNop:
John Stiles44e96be2020-08-31 13:16:04 -0400520 return statement.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400521 case Statement::Kind::kReturn: {
John Stiles44e96be2020-08-31 13:16:04 -0400522 const ReturnStatement& r = statement.as<ReturnStatement>();
John Stiles77702f12020-12-17 14:38:56 -0500523 if (!r.expression()) {
524 if (returnComplexity >= ReturnComplexity::kEarlyReturns) {
525 // This function doesn't return a value, but has early returns, so we've wrapped
526 // it in a for loop. Use a continue to jump to the end of the loop and "leave"
527 // the function.
John Stiles7b920442020-12-17 10:43:41 -0500528 return std::make_unique<ContinueStatement>(offset);
John Stiles44e96be2020-08-31 13:16:04 -0400529 } else {
John Stiles77702f12020-12-17 14:38:56 -0500530 // This function doesn't exit early or return a value. A return statement at the
531 // end is a no-op and can be treated as such.
John Stiles44e96be2020-08-31 13:16:04 -0400532 return std::make_unique<Nop>();
533 }
534 }
John Stiles77702f12020-12-17 14:38:56 -0500535
536 // For a function that only contains a single top-level return, we don't need to store
537 // the result in a variable at all. Just move the return value right into the result
538 // expression.
539 SkASSERT(resultExpr);
540 SkASSERT(*resultExpr);
541 if (returnComplexity <= ReturnComplexity::kSingleTopLevelReturn) {
542 *resultExpr = expr(r.expression());
543 return std::make_unique<Nop>();
544 }
545
546 // For more complex functions, assign their result into a variable.
547 auto assignment =
548 std::make_unique<ExpressionStatement>(std::make_unique<BinaryExpression>(
549 offset,
550 clone_with_ref_kind(**resultExpr, VariableReference::RefKind::kWrite),
551 Token::Kind::TK_EQ,
552 expr(r.expression()),
553 &resultExpr->get()->type()));
554
555 // Early returns are wrapped in a for loop; we need to synthesize a continue statement
556 // to "leave" the function.
557 if (returnComplexity >= ReturnComplexity::kEarlyReturns) {
558 StatementArray block;
559 block.reserve_back(2);
560 block.push_back(std::move(assignment));
561 block.push_back(std::make_unique<ContinueStatement>(offset));
562 return std::make_unique<Block>(offset, std::move(block), /*symbols=*/nullptr,
563 /*isScope=*/true);
564 }
565 // Functions without early returns aren't wrapped in a for loop and don't need to worry
566 // about breaking out of the control flow.
567 return std::move(assignment);
568
John Stiles44e96be2020-08-31 13:16:04 -0400569 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400570 case Statement::Kind::kSwitch: {
John Stiles44e96be2020-08-31 13:16:04 -0400571 const SwitchStatement& ss = statement.as<SwitchStatement>();
572 std::vector<std::unique_ptr<SwitchCase>> cases;
John Stiles2d4f9592020-10-30 10:29:12 -0400573 cases.reserve(ss.cases().size());
574 for (const std::unique_ptr<SwitchCase>& sc : ss.cases()) {
575 cases.push_back(std::make_unique<SwitchCase>(offset, expr(sc->value()),
576 stmts(sc->statements())));
John Stiles44e96be2020-08-31 13:16:04 -0400577 }
Ethan Nicholas01b05e52020-10-22 15:53:41 -0400578 return std::make_unique<SwitchStatement>(offset, ss.isStatic(), expr(ss.value()),
John Stilesa1e2b412020-10-20 14:51:28 -0400579 std::move(cases),
Ethan Nicholas01b05e52020-10-22 15:53:41 -0400580 SymbolTable::WrapIfBuiltin(ss.symbols()));
John Stiles44e96be2020-08-31 13:16:04 -0400581 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400582 case Statement::Kind::kVarDeclaration: {
John Stiles44e96be2020-08-31 13:16:04 -0400583 const VarDeclaration& decl = statement.as<VarDeclaration>();
John Stiles35fee4c2020-12-16 18:25:14 +0000584 std::unique_ptr<Expression> initialValue = expr(decl.value());
585 int arraySize = decl.arraySize();
586 const Variable& old = decl.var();
587 // We assign unique names to inlined variables--scopes hide most of the problems in this
588 // regard, but see `InlinerAvoidsVariableNameOverlap` for a counterexample where unique
589 // names are important.
590 auto name = std::make_unique<String>(
591 this->uniqueNameForInlineVar(String(old.name()), symbolTableForStatement));
592 const String* namePtr = symbolTableForStatement->takeOwnershipOfString(std::move(name));
593 const Type* baseTypePtr = copy_if_needed(&decl.baseType(), *symbolTableForStatement);
594 const Type* typePtr = copy_if_needed(&old.type(), *symbolTableForStatement);
595 const Variable* clone = symbolTableForStatement->takeOwnershipOfSymbol(
596 std::make_unique<Variable>(offset,
597 &old.modifiers(),
598 namePtr->c_str(),
599 typePtr,
600 isBuiltinCode,
601 old.storage(),
602 initialValue.get()));
603 (*varMap)[&old] = std::make_unique<VariableReference>(offset, clone);
604 return std::make_unique<VarDeclaration>(clone, baseTypePtr, arraySize,
605 std::move(initialValue));
John Stiles44e96be2020-08-31 13:16:04 -0400606 }
John Stiles44e96be2020-08-31 13:16:04 -0400607 default:
608 SkASSERT(false);
609 return nullptr;
610 }
611}
612
John Stiles7b920442020-12-17 10:43:41 -0500613Inliner::InlineVariable Inliner::makeInlineVariable(const String& baseName,
614 const Type* type,
615 SymbolTable* symbolTable,
616 Modifiers modifiers,
617 bool isBuiltinCode,
618 std::unique_ptr<Expression>* initialValue) {
619 // $floatLiteral or $intLiteral aren't real types that we can use for scratch variables, so
620 // replace them if they ever appear here. If this happens, we likely forgot to coerce a type
621 // somewhere during compilation.
622 if (type == fContext->fFloatLiteral_Type.get()) {
623 SkDEBUGFAIL("found a $floatLiteral type while inlining");
624 type = fContext->fFloat_Type.get();
625 } else if (type == fContext->fIntLiteral_Type.get()) {
626 SkDEBUGFAIL("found an $intLiteral type while inlining");
627 type = fContext->fInt_Type.get();
628 }
629
630 // Provide our new variable with a unique name, and add it to our symbol table.
631 const String* namePtr = symbolTable->takeOwnershipOfString(
632 std::make_unique<String>(this->uniqueNameForInlineVar(baseName, symbolTable)));
633 StringFragment nameFrag{namePtr->c_str(), namePtr->length()};
634
635 // Create our new variable and add it to the symbol table.
636 InlineVariable result;
637 result.fVarSymbol =
638 symbolTable->add(std::make_unique<Variable>(/*offset=*/-1,
639 fModifiers->addToPool(Modifiers()),
640 nameFrag,
641 type,
642 isBuiltinCode,
643 Variable::Storage::kLocal,
644 initialValue->get()));
645
646 // Prepare the variable declaration (taking extra care with `out` params to not clobber any
647 // initial value).
648 if (*initialValue && (modifiers.fFlags & Modifiers::kOut_Flag)) {
649 result.fVarDecl = std::make_unique<VarDeclaration>(result.fVarSymbol, type, /*arraySize=*/0,
650 (*initialValue)->clone());
651 } else {
652 result.fVarDecl = std::make_unique<VarDeclaration>(result.fVarSymbol, type, /*arraySize=*/0,
653 std::move(*initialValue));
654 }
655 return result;
656}
657
John Stiles6eadf132020-09-08 10:16:10 -0400658Inliner::InlinedCall Inliner::inlineCall(FunctionCall* call,
John Stiles78047582020-12-16 16:17:41 -0500659 std::shared_ptr<SymbolTable> symbolTable,
Brian Osman3887a012020-09-30 13:22:27 -0400660 const FunctionDeclaration* caller) {
John Stiles44e96be2020-08-31 13:16:04 -0400661 // Inlining is more complicated here than in a typical compiler, because we have to have a
662 // high-level IR and can't just drop statements into the middle of an expression or even use
663 // gotos.
664 //
665 // Since we can't insert statements into an expression, we run the inline function as extra
666 // statements before the statement we're currently processing, relying on a lack of execution
667 // order guarantees. Since we can't use gotos (which are normally used to replace return
668 // statements), we wrap the whole function in a loop and use break statements to jump to the
669 // end.
670 SkASSERT(fSettings);
671 SkASSERT(fContext);
672 SkASSERT(call);
Ethan Nicholased84b732020-10-08 11:45:44 -0400673 SkASSERT(this->isSafeToInline(call->function().definition()));
John Stiles44e96be2020-08-31 13:16:04 -0400674
John Stiles8e3b6be2020-10-13 11:14:08 -0400675 ExpressionArray& arguments = call->arguments();
John Stiles6eadf132020-09-08 10:16:10 -0400676 const int offset = call->fOffset;
Ethan Nicholased84b732020-10-08 11:45:44 -0400677 const FunctionDefinition& function = *call->function().definition();
John Stiles77702f12020-12-17 14:38:56 -0500678 const ReturnComplexity returnComplexity = GetReturnComplexity(function);
679 bool hasEarlyReturn = (returnComplexity >= ReturnComplexity::kEarlyReturns);
John Stiles6eadf132020-09-08 10:16:10 -0400680
John Stiles44e96be2020-08-31 13:16:04 -0400681 InlinedCall inlinedCall;
John Stiles8f2a0cf2020-10-13 12:48:21 -0400682 inlinedCall.fInlinedBody = std::make_unique<Block>(offset, StatementArray{},
John Stiles6eadf132020-09-08 10:16:10 -0400683 /*symbols=*/nullptr,
684 /*isScope=*/false);
John Stiles98c1f822020-09-09 14:18:53 -0400685
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400686 Block& inlinedBody = *inlinedCall.fInlinedBody;
John Stiles82f373c2020-10-20 13:58:05 -0400687 inlinedBody.children().reserve_back(
688 1 + // Inline marker
689 1 + // Result variable
690 arguments.size() + // Function arguments (passing in)
691 arguments.size() + // Function arguments (copy out-params back)
John Stiles7b920442020-12-17 10:43:41 -0500692 1); // Block for inlined code
John Stiles98c1f822020-09-09 14:18:53 -0400693
Ethan Nicholasceb62142020-10-09 16:51:18 -0400694 inlinedBody.children().push_back(std::make_unique<InlineMarker>(&call->function()));
John Stiles44e96be2020-08-31 13:16:04 -0400695
John Stiles44e96be2020-08-31 13:16:04 -0400696 // Create a variable to hold the result in the extra statements (excepting void).
John Stilese41b4ee2020-09-28 12:28:16 -0400697 std::unique_ptr<Expression> resultExpr;
Ethan Nicholas0a5d0962020-10-14 13:33:18 -0400698 if (function.declaration().returnType() != *fContext->fVoid_Type) {
John Stiles44e96be2020-08-31 13:16:04 -0400699 std::unique_ptr<Expression> noInitialValue;
John Stiles7b920442020-12-17 10:43:41 -0500700 InlineVariable var = this->makeInlineVariable(function.declaration().name(),
701 &function.declaration().returnType(),
702 symbolTable.get(), Modifiers{},
703 caller->isBuiltin(), &noInitialValue);
704 inlinedBody.children().push_back(std::move(var.fVarDecl));
705 resultExpr = std::make_unique<VariableReference>(/*offset=*/-1, var.fVarSymbol);
John Stiles35fee4c2020-12-16 18:25:14 +0000706 }
John Stiles44e96be2020-08-31 13:16:04 -0400707
708 // Create variables in the extra statements to hold the arguments, and assign the arguments to
709 // them.
710 VariableRewriteMap varMap;
John Stilese41b4ee2020-09-28 12:28:16 -0400711 std::vector<int> argsToCopyBack;
John Stiles44e96be2020-08-31 13:16:04 -0400712 for (int i = 0; i < (int) arguments.size(); ++i) {
Ethan Nicholas0a5d0962020-10-14 13:33:18 -0400713 const Variable* param = function.declaration().parameters()[i];
Ethan Nicholas041fd0a2020-10-07 16:42:04 -0400714 bool isOutParam = param->modifiers().fFlags & Modifiers::kOut_Flag;
John Stiles44e96be2020-08-31 13:16:04 -0400715
John Stiles44733aa2020-09-29 17:42:23 -0400716 // If this argument can be inlined trivially (e.g. a swizzle, or a constant array index)...
John Stilesc30fbca2020-11-19 16:25:49 -0500717 if (Analysis::IsTrivialExpression(*arguments[i])) {
John Stilese41b4ee2020-09-28 12:28:16 -0400718 // ... and it's an `out` param, or it isn't written to within the inline function...
Ethan Nicholas0a5d0962020-10-14 13:33:18 -0400719 if (isOutParam || !Analysis::StatementWritesToVariable(*function.body(), *param)) {
John Stilesf201af82020-09-29 16:57:55 -0400720 // ... we don't need to copy it at all! We can just use the existing expression.
721 varMap[param] = arguments[i]->clone();
John Stiles44e96be2020-08-31 13:16:04 -0400722 continue;
723 }
724 }
John Stilese41b4ee2020-09-28 12:28:16 -0400725 if (isOutParam) {
726 argsToCopyBack.push_back(i);
727 }
John Stiles7b920442020-12-17 10:43:41 -0500728 InlineVariable var = this->makeInlineVariable(param->name(), &arguments[i]->type(),
729 symbolTable.get(), param->modifiers(),
730 caller->isBuiltin(), &arguments[i]);
731 inlinedBody.children().push_back(std::move(var.fVarDecl));
732 varMap[param] = std::make_unique<VariableReference>(/*offset=*/-1, var.fVarSymbol);
John Stiles44e96be2020-08-31 13:16:04 -0400733 }
734
Ethan Nicholas0a5d0962020-10-14 13:33:18 -0400735 const Block& body = function.body()->as<Block>();
John Stiles7b920442020-12-17 10:43:41 -0500736 StatementArray* inlineStatements;
737
John Stiles44e96be2020-08-31 13:16:04 -0400738 if (hasEarlyReturn) {
739 // Since we output to backends that don't have a goto statement (which would normally be
John Stiles7b920442020-12-17 10:43:41 -0500740 // used to perform an early return), we fake it by wrapping the function in a single-
741 // iteration for loop, and use a continue statement to jump to the end of the loop
742 // prematurely.
743
744 // int _1_loop = 0;
745 symbolTable = std::make_shared<SymbolTable>(std::move(symbolTable), caller->isBuiltin());
746 const Type* intType = fContext->fInt_Type.get();
747 std::unique_ptr<Expression> initialValue = std::make_unique<IntLiteral>(/*offset=*/-1,
748 /*value=*/0,
749 intType);
750 InlineVariable loopVar = this->makeInlineVariable("loop", intType, symbolTable.get(),
751 Modifiers{}, caller->isBuiltin(),
752 &initialValue);
753
754 // _1_loop < 1;
755 std::unique_ptr<Expression> test = std::make_unique<BinaryExpression>(
John Stiles44e96be2020-08-31 13:16:04 -0400756 /*offset=*/-1,
John Stiles7b920442020-12-17 10:43:41 -0500757 std::make_unique<VariableReference>(/*offset=*/-1, loopVar.fVarSymbol),
758 Token::Kind::TK_LT,
759 std::make_unique<IntLiteral>(/*offset=*/-1, /*value=*/1, intType),
760 fContext->fBool_Type.get());
761
762 // _1_loop++
763 std::unique_ptr<Expression> increment = std::make_unique<PostfixExpression>(
764 std::make_unique<VariableReference>(/*offset=*/-1, loopVar.fVarSymbol,
765 VariableReference::RefKind::kReadWrite),
766 Token::Kind::TK_PLUSPLUS);
767
768 // {...}
769 auto innerBlock = std::make_unique<Block>(offset, StatementArray{},
770 /*symbols=*/nullptr, /*isScope=*/true);
771 inlineStatements = &innerBlock->children();
772
773 // for (int _1_loop = 0; _1_loop < 1; _1_loop++) {...}
774 inlinedBody.children().push_back(std::make_unique<ForStatement>(/*offset=*/-1,
775 std::move(loopVar.fVarDecl),
776 std::move(test),
777 std::move(increment),
778 std::move(innerBlock),
779 symbolTable));
John Stiles44e96be2020-08-31 13:16:04 -0400780 } else {
John Stilesfa9a0832020-12-17 10:43:58 -0500781 // No early returns, so we can just dump the code into our existing scopeless block.
782 inlineStatements = &inlinedBody.children();
John Stiles7b920442020-12-17 10:43:41 -0500783 }
784
785 inlineStatements->reserve_back(body.children().size() + argsToCopyBack.size());
786 for (const std::unique_ptr<Statement>& stmt : body.children()) {
787 inlineStatements->push_back(this->inlineStatement(offset, &varMap, symbolTable.get(),
John Stiles77702f12020-12-17 14:38:56 -0500788 &resultExpr, returnComplexity, *stmt,
John Stiles7b920442020-12-17 10:43:41 -0500789 caller->isBuiltin()));
John Stiles44e96be2020-08-31 13:16:04 -0400790 }
791
John Stilese41b4ee2020-09-28 12:28:16 -0400792 // Copy back the values of `out` parameters into their real destinations.
793 for (int i : argsToCopyBack) {
Ethan Nicholas0a5d0962020-10-14 13:33:18 -0400794 const Variable* p = function.declaration().parameters()[i];
John Stilese41b4ee2020-09-28 12:28:16 -0400795 SkASSERT(varMap.find(p) != varMap.end());
John Stiles7b920442020-12-17 10:43:41 -0500796 inlineStatements->push_back(
John Stilese41b4ee2020-09-28 12:28:16 -0400797 std::make_unique<ExpressionStatement>(std::make_unique<BinaryExpression>(
798 offset,
Ethan Nicholas453f67f2020-10-09 10:43:45 -0400799 clone_with_ref_kind(*arguments[i], VariableReference::RefKind::kWrite),
John Stilese41b4ee2020-09-28 12:28:16 -0400800 Token::Kind::TK_EQ,
801 std::move(varMap[p]),
802 &arguments[i]->type())));
John Stiles44e96be2020-08-31 13:16:04 -0400803 }
804
John Stilese41b4ee2020-09-28 12:28:16 -0400805 if (resultExpr != nullptr) {
806 // Return our result variable as our replacement expression.
John Stilese41b4ee2020-09-28 12:28:16 -0400807 inlinedCall.fReplacementExpr = std::move(resultExpr);
John Stiles44e96be2020-08-31 13:16:04 -0400808 } else {
809 // It's a void function, so it doesn't actually result in anything, but we have to return
810 // something non-null as a standin.
Ethan Nicholas041fd0a2020-10-07 16:42:04 -0400811 inlinedCall.fReplacementExpr = std::make_unique<BoolLiteral>(*fContext,
812 offset,
John Stiles44e96be2020-08-31 13:16:04 -0400813 /*value=*/false);
814 }
815
John Stiles44e96be2020-08-31 13:16:04 -0400816 return inlinedCall;
817}
818
John Stiles2d7973a2020-10-02 15:01:03 -0400819bool Inliner::isSafeToInline(const FunctionDefinition* functionDef) {
John Stiles44e96be2020-08-31 13:16:04 -0400820 SkASSERT(fSettings);
821
John Stiles1c03d332020-10-13 10:30:23 -0400822 // A threshold of zero indicates that the inliner is completely disabled, so we can just return.
823 if (fSettings->fInlineThreshold <= 0) {
824 return false;
825 }
826
John Stiles031a7672020-11-13 16:13:18 -0500827 // Enforce a limit on inlining to avoid pathological cases. (inliner/ExponentialGrowth.sksl)
828 if (fInlinedStatementCounter >= kInlinedStatementLimit) {
829 return false;
830 }
831
John Stiles2d7973a2020-10-02 15:01:03 -0400832 if (functionDef == nullptr) {
John Stiles44e96be2020-08-31 13:16:04 -0400833 // Can't inline something if we don't actually have its definition.
834 return false;
835 }
John Stiles2d7973a2020-10-02 15:01:03 -0400836
John Stiles7b920442020-12-17 10:43:41 -0500837 // We don't have any mechanism to simulate early returns within a breakable construct
838 // (switch/for/do/while), so we can't inline if there's a return inside one.
John Stiles2d7973a2020-10-02 15:01:03 -0400839 bool hasReturnInBreakableConstruct = (count_returns_in_breakable_constructs(*functionDef) > 0);
John Stiles44e96be2020-08-31 13:16:04 -0400840 return !hasReturnInBreakableConstruct;
841}
842
John Stiles2d7973a2020-10-02 15:01:03 -0400843// A candidate function for inlining, containing everything that `inlineCall` needs.
844struct InlineCandidate {
John Stiles78047582020-12-16 16:17:41 -0500845 std::shared_ptr<SymbolTable> fSymbols; // the SymbolTable of the candidate
John Stiles2d7973a2020-10-02 15:01:03 -0400846 std::unique_ptr<Statement>* fParentStmt; // the parent Statement of the enclosing stmt
847 std::unique_ptr<Statement>* fEnclosingStmt; // the Statement containing the candidate
848 std::unique_ptr<Expression>* fCandidateExpr; // the candidate FunctionCall to be inlined
849 FunctionDefinition* fEnclosingFunction; // the Function containing the candidate
John Stiles2d7973a2020-10-02 15:01:03 -0400850};
John Stiles93442622020-09-11 12:11:27 -0400851
John Stiles2d7973a2020-10-02 15:01:03 -0400852struct InlineCandidateList {
853 std::vector<InlineCandidate> fCandidates;
854};
855
856class InlineCandidateAnalyzer {
John Stiles70957c82020-10-02 16:42:10 -0400857public:
858 // A list of all the inlining candidates we found during analysis.
859 InlineCandidateList* fCandidateList;
John Stiles2d7973a2020-10-02 15:01:03 -0400860
John Stiles70957c82020-10-02 16:42:10 -0400861 // A stack of the symbol tables; since most nodes don't have one, expected to be shallower than
862 // the enclosing-statement stack.
John Stiles78047582020-12-16 16:17:41 -0500863 std::vector<std::shared_ptr<SymbolTable>> fSymbolTableStack;
John Stiles70957c82020-10-02 16:42:10 -0400864 // A stack of "enclosing" statements--these would be suitable for the inliner to use for adding
865 // new instructions. Not all statements are suitable (e.g. a for-loop's initializer). The
866 // inliner might replace a statement with a block containing the statement.
867 std::vector<std::unique_ptr<Statement>*> fEnclosingStmtStack;
868 // The function that we're currently processing (i.e. inlining into).
869 FunctionDefinition* fEnclosingFunction = nullptr;
John Stiles93442622020-09-11 12:11:27 -0400870
Brian Osman0006ad02020-11-18 15:38:39 -0500871 void visit(const std::vector<std::unique_ptr<ProgramElement>>& elements,
John Stiles78047582020-12-16 16:17:41 -0500872 std::shared_ptr<SymbolTable> symbols,
Brian Osman0006ad02020-11-18 15:38:39 -0500873 InlineCandidateList* candidateList) {
John Stiles70957c82020-10-02 16:42:10 -0400874 fCandidateList = candidateList;
Brian Osman0006ad02020-11-18 15:38:39 -0500875 fSymbolTableStack.push_back(symbols);
John Stiles93442622020-09-11 12:11:27 -0400876
Brian Osman0006ad02020-11-18 15:38:39 -0500877 for (const std::unique_ptr<ProgramElement>& pe : elements) {
Brian Osman1179fcf2020-10-08 16:04:40 -0400878 this->visitProgramElement(pe.get());
John Stiles93442622020-09-11 12:11:27 -0400879 }
880
John Stiles70957c82020-10-02 16:42:10 -0400881 fSymbolTableStack.pop_back();
882 fCandidateList = nullptr;
883 }
884
885 void visitProgramElement(ProgramElement* pe) {
886 switch (pe->kind()) {
887 case ProgramElement::Kind::kFunction: {
888 FunctionDefinition& funcDef = pe->as<FunctionDefinition>();
Brian Osman0006ad02020-11-18 15:38:39 -0500889 fEnclosingFunction = &funcDef;
890 this->visitStatement(&funcDef.body());
John Stiles70957c82020-10-02 16:42:10 -0400891 break;
John Stiles93442622020-09-11 12:11:27 -0400892 }
John Stiles70957c82020-10-02 16:42:10 -0400893 default:
894 // The inliner can't operate outside of a function's scope.
895 break;
896 }
897 }
898
899 void visitStatement(std::unique_ptr<Statement>* stmt,
900 bool isViableAsEnclosingStatement = true) {
901 if (!*stmt) {
902 return;
John Stiles93442622020-09-11 12:11:27 -0400903 }
904
John Stiles70957c82020-10-02 16:42:10 -0400905 size_t oldEnclosingStmtStackSize = fEnclosingStmtStack.size();
906 size_t oldSymbolStackSize = fSymbolTableStack.size();
John Stiles93442622020-09-11 12:11:27 -0400907
John Stiles70957c82020-10-02 16:42:10 -0400908 if (isViableAsEnclosingStatement) {
909 fEnclosingStmtStack.push_back(stmt);
John Stiles93442622020-09-11 12:11:27 -0400910 }
911
John Stiles70957c82020-10-02 16:42:10 -0400912 switch ((*stmt)->kind()) {
913 case Statement::Kind::kBreak:
914 case Statement::Kind::kContinue:
915 case Statement::Kind::kDiscard:
916 case Statement::Kind::kInlineMarker:
917 case Statement::Kind::kNop:
918 break;
919
920 case Statement::Kind::kBlock: {
921 Block& block = (*stmt)->as<Block>();
922 if (block.symbolTable()) {
John Stiles78047582020-12-16 16:17:41 -0500923 fSymbolTableStack.push_back(block.symbolTable());
John Stiles70957c82020-10-02 16:42:10 -0400924 }
925
926 for (std::unique_ptr<Statement>& stmt : block.children()) {
927 this->visitStatement(&stmt);
928 }
929 break;
John Stiles93442622020-09-11 12:11:27 -0400930 }
John Stiles70957c82020-10-02 16:42:10 -0400931 case Statement::Kind::kDo: {
932 DoStatement& doStmt = (*stmt)->as<DoStatement>();
933 // The loop body is a candidate for inlining.
934 this->visitStatement(&doStmt.statement());
935 // The inliner isn't smart enough to inline the test-expression for a do-while
936 // loop at this time. There are two limitations:
937 // - We would need to insert the inlined-body block at the very end of the do-
938 // statement's inner fStatement. We don't support that today, but it's doable.
939 // - We cannot inline the test expression if the loop uses `continue` anywhere; that
940 // would skip over the inlined block that evaluates the test expression. There
941 // isn't a good fix for this--any workaround would be more complex than the cost
942 // of a function call. However, loops that don't use `continue` would still be
943 // viable candidates for inlining.
944 break;
John Stiles93442622020-09-11 12:11:27 -0400945 }
John Stiles70957c82020-10-02 16:42:10 -0400946 case Statement::Kind::kExpression: {
947 ExpressionStatement& expr = (*stmt)->as<ExpressionStatement>();
948 this->visitExpression(&expr.expression());
949 break;
950 }
951 case Statement::Kind::kFor: {
952 ForStatement& forStmt = (*stmt)->as<ForStatement>();
Ethan Nicholas0d31ed52020-10-05 14:47:09 -0400953 if (forStmt.symbols()) {
John Stiles78047582020-12-16 16:17:41 -0500954 fSymbolTableStack.push_back(forStmt.symbols());
John Stiles70957c82020-10-02 16:42:10 -0400955 }
956
957 // The initializer and loop body are candidates for inlining.
Ethan Nicholas0d31ed52020-10-05 14:47:09 -0400958 this->visitStatement(&forStmt.initializer(),
John Stiles70957c82020-10-02 16:42:10 -0400959 /*isViableAsEnclosingStatement=*/false);
Ethan Nicholas0d31ed52020-10-05 14:47:09 -0400960 this->visitStatement(&forStmt.statement());
John Stiles70957c82020-10-02 16:42:10 -0400961
962 // The inliner isn't smart enough to inline the test- or increment-expressions
963 // of a for loop loop at this time. There are a handful of limitations:
964 // - We would need to insert the test-expression block at the very beginning of the
965 // for-loop's inner fStatement, and the increment-expression block at the very
966 // end. We don't support that today, but it's doable.
967 // - The for-loop's built-in test-expression would need to be dropped entirely,
968 // and the loop would be halted via a break statement at the end of the inlined
969 // test-expression. This is again something we don't support today, but it could
970 // be implemented.
971 // - We cannot inline the increment-expression if the loop uses `continue` anywhere;
972 // that would skip over the inlined block that evaluates the increment expression.
973 // There isn't a good fix for this--any workaround would be more complex than the
974 // cost of a function call. However, loops that don't use `continue` would still
975 // be viable candidates for increment-expression inlining.
976 break;
977 }
978 case Statement::Kind::kIf: {
979 IfStatement& ifStmt = (*stmt)->as<IfStatement>();
Ethan Nicholas8c44eca2020-10-07 16:47:09 -0400980 this->visitExpression(&ifStmt.test());
981 this->visitStatement(&ifStmt.ifTrue());
982 this->visitStatement(&ifStmt.ifFalse());
John Stiles70957c82020-10-02 16:42:10 -0400983 break;
984 }
985 case Statement::Kind::kReturn: {
986 ReturnStatement& returnStmt = (*stmt)->as<ReturnStatement>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -0400987 this->visitExpression(&returnStmt.expression());
John Stiles70957c82020-10-02 16:42:10 -0400988 break;
989 }
990 case Statement::Kind::kSwitch: {
991 SwitchStatement& switchStmt = (*stmt)->as<SwitchStatement>();
Ethan Nicholas01b05e52020-10-22 15:53:41 -0400992 if (switchStmt.symbols()) {
John Stiles78047582020-12-16 16:17:41 -0500993 fSymbolTableStack.push_back(switchStmt.symbols());
John Stiles70957c82020-10-02 16:42:10 -0400994 }
995
Ethan Nicholas01b05e52020-10-22 15:53:41 -0400996 this->visitExpression(&switchStmt.value());
John Stiles2d4f9592020-10-30 10:29:12 -0400997 for (const std::unique_ptr<SwitchCase>& switchCase : switchStmt.cases()) {
John Stiles70957c82020-10-02 16:42:10 -0400998 // The switch-case's fValue cannot be a FunctionCall; skip it.
John Stiles2d4f9592020-10-30 10:29:12 -0400999 for (std::unique_ptr<Statement>& caseBlock : switchCase->statements()) {
John Stiles70957c82020-10-02 16:42:10 -04001000 this->visitStatement(&caseBlock);
1001 }
1002 }
1003 break;
1004 }
1005 case Statement::Kind::kVarDeclaration: {
1006 VarDeclaration& varDeclStmt = (*stmt)->as<VarDeclaration>();
1007 // Don't need to scan the declaration's sizes; those are always IntLiterals.
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001008 this->visitExpression(&varDeclStmt.value());
John Stiles70957c82020-10-02 16:42:10 -04001009 break;
1010 }
John Stiles70957c82020-10-02 16:42:10 -04001011 default:
1012 SkUNREACHABLE;
John Stiles93442622020-09-11 12:11:27 -04001013 }
1014
John Stiles70957c82020-10-02 16:42:10 -04001015 // Pop our symbol and enclosing-statement stacks.
1016 fSymbolTableStack.resize(oldSymbolStackSize);
1017 fEnclosingStmtStack.resize(oldEnclosingStmtStackSize);
1018 }
1019
1020 void visitExpression(std::unique_ptr<Expression>* expr) {
1021 if (!*expr) {
1022 return;
John Stiles93442622020-09-11 12:11:27 -04001023 }
John Stiles70957c82020-10-02 16:42:10 -04001024
1025 switch ((*expr)->kind()) {
1026 case Expression::Kind::kBoolLiteral:
1027 case Expression::Kind::kDefined:
1028 case Expression::Kind::kExternalValue:
1029 case Expression::Kind::kFieldAccess:
1030 case Expression::Kind::kFloatLiteral:
1031 case Expression::Kind::kFunctionReference:
1032 case Expression::Kind::kIntLiteral:
1033 case Expression::Kind::kNullLiteral:
1034 case Expression::Kind::kSetting:
1035 case Expression::Kind::kTypeReference:
1036 case Expression::Kind::kVariableReference:
1037 // Nothing to scan here.
1038 break;
1039
1040 case Expression::Kind::kBinary: {
1041 BinaryExpression& binaryExpr = (*expr)->as<BinaryExpression>();
John Stiles2d4f9592020-10-30 10:29:12 -04001042 this->visitExpression(&binaryExpr.left());
John Stiles70957c82020-10-02 16:42:10 -04001043
1044 // Logical-and and logical-or binary expressions do not inline the right side,
1045 // because that would invalidate short-circuiting. That is, when evaluating
1046 // expressions like these:
1047 // (false && x()) // always false
1048 // (true || y()) // always true
1049 // It is illegal for side-effects from x() or y() to occur. The simplest way to
1050 // enforce that rule is to avoid inlining the right side entirely. However, it is
1051 // safe for other types of binary expression to inline both sides.
1052 Token::Kind op = binaryExpr.getOperator();
1053 bool shortCircuitable = (op == Token::Kind::TK_LOGICALAND ||
1054 op == Token::Kind::TK_LOGICALOR);
1055 if (!shortCircuitable) {
John Stiles2d4f9592020-10-30 10:29:12 -04001056 this->visitExpression(&binaryExpr.right());
John Stiles70957c82020-10-02 16:42:10 -04001057 }
1058 break;
1059 }
1060 case Expression::Kind::kConstructor: {
1061 Constructor& constructorExpr = (*expr)->as<Constructor>();
1062 for (std::unique_ptr<Expression>& arg : constructorExpr.arguments()) {
1063 this->visitExpression(&arg);
1064 }
1065 break;
1066 }
1067 case Expression::Kind::kExternalFunctionCall: {
1068 ExternalFunctionCall& funcCallExpr = (*expr)->as<ExternalFunctionCall>();
1069 for (std::unique_ptr<Expression>& arg : funcCallExpr.arguments()) {
1070 this->visitExpression(&arg);
1071 }
1072 break;
1073 }
1074 case Expression::Kind::kFunctionCall: {
1075 FunctionCall& funcCallExpr = (*expr)->as<FunctionCall>();
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001076 for (std::unique_ptr<Expression>& arg : funcCallExpr.arguments()) {
John Stiles70957c82020-10-02 16:42:10 -04001077 this->visitExpression(&arg);
1078 }
1079 this->addInlineCandidate(expr);
1080 break;
1081 }
1082 case Expression::Kind::kIndex:{
1083 IndexExpression& indexExpr = (*expr)->as<IndexExpression>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04001084 this->visitExpression(&indexExpr.base());
1085 this->visitExpression(&indexExpr.index());
John Stiles70957c82020-10-02 16:42:10 -04001086 break;
1087 }
1088 case Expression::Kind::kPostfix: {
1089 PostfixExpression& postfixExpr = (*expr)->as<PostfixExpression>();
Ethan Nicholas444ccc62020-10-09 10:16:22 -04001090 this->visitExpression(&postfixExpr.operand());
John Stiles70957c82020-10-02 16:42:10 -04001091 break;
1092 }
1093 case Expression::Kind::kPrefix: {
1094 PrefixExpression& prefixExpr = (*expr)->as<PrefixExpression>();
Ethan Nicholas444ccc62020-10-09 10:16:22 -04001095 this->visitExpression(&prefixExpr.operand());
John Stiles70957c82020-10-02 16:42:10 -04001096 break;
1097 }
1098 case Expression::Kind::kSwizzle: {
1099 Swizzle& swizzleExpr = (*expr)->as<Swizzle>();
Ethan Nicholas6b4d5812020-10-12 16:11:51 -04001100 this->visitExpression(&swizzleExpr.base());
John Stiles70957c82020-10-02 16:42:10 -04001101 break;
1102 }
1103 case Expression::Kind::kTernary: {
1104 TernaryExpression& ternaryExpr = (*expr)->as<TernaryExpression>();
1105 // The test expression is a candidate for inlining.
Ethan Nicholasdd218162020-10-08 05:48:01 -04001106 this->visitExpression(&ternaryExpr.test());
John Stiles70957c82020-10-02 16:42:10 -04001107 // The true- and false-expressions cannot be inlined, because we are only allowed to
1108 // evaluate one side.
1109 break;
1110 }
1111 default:
1112 SkUNREACHABLE;
1113 }
1114 }
1115
1116 void addInlineCandidate(std::unique_ptr<Expression>* candidate) {
1117 fCandidateList->fCandidates.push_back(
1118 InlineCandidate{fSymbolTableStack.back(),
1119 find_parent_statement(fEnclosingStmtStack),
1120 fEnclosingStmtStack.back(),
1121 candidate,
John Stiles9b9415e2020-11-23 14:48:06 -05001122 fEnclosingFunction});
John Stiles70957c82020-10-02 16:42:10 -04001123 }
John Stiles2d7973a2020-10-02 15:01:03 -04001124};
John Stiles93442622020-09-11 12:11:27 -04001125
John Stiles9b9415e2020-11-23 14:48:06 -05001126static const FunctionDeclaration& candidate_func(const InlineCandidate& candidate) {
1127 return (*candidate.fCandidateExpr)->as<FunctionCall>().function();
1128}
John Stiles915a38c2020-09-14 09:38:13 -04001129
John Stiles9b9415e2020-11-23 14:48:06 -05001130bool Inliner::candidateCanBeInlined(const InlineCandidate& candidate, InlinabilityCache* cache) {
1131 const FunctionDeclaration& funcDecl = candidate_func(candidate);
John Stiles1c03d332020-10-13 10:30:23 -04001132 auto [iter, wasInserted] = cache->insert({&funcDecl, false});
John Stiles2d7973a2020-10-02 15:01:03 -04001133 if (wasInserted) {
1134 // Recursion is forbidden here to avoid an infinite death spiral of inlining.
John Stiles1c03d332020-10-13 10:30:23 -04001135 iter->second = this->isSafeToInline(funcDecl.definition()) &&
1136 !contains_recursive_call(funcDecl);
John Stiles93442622020-09-11 12:11:27 -04001137 }
1138
John Stiles2d7973a2020-10-02 15:01:03 -04001139 return iter->second;
1140}
1141
John Stiles9b9415e2020-11-23 14:48:06 -05001142int Inliner::getFunctionSize(const FunctionDeclaration& funcDecl, FunctionSizeCache* cache) {
1143 auto [iter, wasInserted] = cache->insert({&funcDecl, 0});
John Stiles2d7973a2020-10-02 15:01:03 -04001144 if (wasInserted) {
John Stiles9b9415e2020-11-23 14:48:06 -05001145 iter->second = Analysis::NodeCountUpToLimit(*funcDecl.definition(),
1146 fSettings->fInlineThreshold);
John Stiles2d7973a2020-10-02 15:01:03 -04001147 }
John Stiles2d7973a2020-10-02 15:01:03 -04001148 return iter->second;
1149}
1150
Brian Osman0006ad02020-11-18 15:38:39 -05001151void Inliner::buildCandidateList(const std::vector<std::unique_ptr<ProgramElement>>& elements,
John Stiles78047582020-12-16 16:17:41 -05001152 std::shared_ptr<SymbolTable> symbols, ProgramUsage* usage,
Brian Osman0006ad02020-11-18 15:38:39 -05001153 InlineCandidateList* candidateList) {
John Stiles2d7973a2020-10-02 15:01:03 -04001154 // This is structured much like a ProgramVisitor, but does not actually use ProgramVisitor.
1155 // The analyzer needs to keep track of the `unique_ptr<T>*` of statements and expressions so
1156 // that they can later be replaced, and ProgramVisitor does not provide this; it only provides a
1157 // `const T&`.
1158 InlineCandidateAnalyzer analyzer;
Brian Osman0006ad02020-11-18 15:38:39 -05001159 analyzer.visit(elements, symbols, candidateList);
John Stiles2d7973a2020-10-02 15:01:03 -04001160
John Stiles0ad233f2020-11-25 11:02:05 -05001161 // Early out if there are no inlining candidates.
John Stiles2d7973a2020-10-02 15:01:03 -04001162 std::vector<InlineCandidate>& candidates = candidateList->fCandidates;
John Stiles0ad233f2020-11-25 11:02:05 -05001163 if (candidates.empty()) {
1164 return;
1165 }
1166
1167 // Remove candidates that are not safe to inline.
John Stiles2d7973a2020-10-02 15:01:03 -04001168 InlinabilityCache cache;
1169 candidates.erase(std::remove_if(candidates.begin(),
1170 candidates.end(),
1171 [&](const InlineCandidate& candidate) {
1172 return !this->candidateCanBeInlined(candidate, &cache);
1173 }),
1174 candidates.end());
1175
John Stiles0ad233f2020-11-25 11:02:05 -05001176 // If the inline threshold is unlimited, or if we have no candidates left, our candidate list is
1177 // complete.
1178 if (fSettings->fInlineThreshold == INT_MAX || candidates.empty()) {
1179 return;
John Stiles2d7973a2020-10-02 15:01:03 -04001180 }
John Stiles0ad233f2020-11-25 11:02:05 -05001181
1182 // Remove candidates on a per-function basis if the effect of inlining would be to make more
1183 // than `inlineThreshold` nodes. (i.e. if Func() would be inlined six times and its size is
1184 // 10 nodes, it should be inlined if the inlineThreshold is 60 or higher.)
1185 FunctionSizeCache functionSizeCache;
1186 FunctionSizeCache candidateTotalCost;
1187 for (InlineCandidate& candidate : candidates) {
1188 const FunctionDeclaration& fnDecl = candidate_func(candidate);
1189 candidateTotalCost[&fnDecl] += this->getFunctionSize(fnDecl, &functionSizeCache);
1190 }
1191
1192 candidates.erase(
1193 std::remove_if(candidates.begin(),
1194 candidates.end(),
1195 [&](const InlineCandidate& candidate) {
1196 const FunctionDeclaration& fnDecl = candidate_func(candidate);
1197 if (fnDecl.modifiers().fFlags & Modifiers::kInline_Flag) {
1198 // Functions marked `inline` ignore size limitations.
1199 return false;
1200 }
1201 if (usage->get(fnDecl) == 1) {
1202 // If a function is only used once, it's cost-free to inline.
1203 return false;
1204 }
1205 if (candidateTotalCost[&fnDecl] <= fSettings->fInlineThreshold) {
1206 // We won't exceed the inline threshold by inlining this.
1207 return false;
1208 }
1209 // Inlining this function will add too many IRNodes.
1210 return true;
1211 }),
1212 candidates.end());
John Stiles2d7973a2020-10-02 15:01:03 -04001213}
1214
Brian Osman0006ad02020-11-18 15:38:39 -05001215bool Inliner::analyze(const std::vector<std::unique_ptr<ProgramElement>>& elements,
John Stiles78047582020-12-16 16:17:41 -05001216 std::shared_ptr<SymbolTable> symbols,
Brian Osman0006ad02020-11-18 15:38:39 -05001217 ProgramUsage* usage) {
John Stilesd34d56e2020-10-12 12:04:47 -04001218 // A threshold of zero indicates that the inliner is completely disabled, so we can just return.
1219 if (fSettings->fInlineThreshold <= 0) {
1220 return false;
1221 }
1222
John Stiles031a7672020-11-13 16:13:18 -05001223 // Enforce a limit on inlining to avoid pathological cases. (inliner/ExponentialGrowth.sksl)
1224 if (fInlinedStatementCounter >= kInlinedStatementLimit) {
1225 return false;
1226 }
1227
John Stiles2d7973a2020-10-02 15:01:03 -04001228 InlineCandidateList candidateList;
John Stiles9b9415e2020-11-23 14:48:06 -05001229 this->buildCandidateList(elements, symbols, usage, &candidateList);
John Stiles2d7973a2020-10-02 15:01:03 -04001230
John Stiles915a38c2020-09-14 09:38:13 -04001231 // Inline the candidates where we've determined that it's safe to do so.
1232 std::unordered_set<const std::unique_ptr<Statement>*> enclosingStmtSet;
1233 bool madeChanges = false;
John Stiles2d7973a2020-10-02 15:01:03 -04001234 for (const InlineCandidate& candidate : candidateList.fCandidates) {
John Stiles915a38c2020-09-14 09:38:13 -04001235 FunctionCall& funcCall = (*candidate.fCandidateExpr)->as<FunctionCall>();
John Stiles915a38c2020-09-14 09:38:13 -04001236
1237 // Inlining two expressions using the same enclosing statement in the same inlining pass
1238 // does not work properly. If this happens, skip it; we'll get it in the next pass.
1239 auto [unusedIter, inserted] = enclosingStmtSet.insert(candidate.fEnclosingStmt);
1240 if (!inserted) {
1241 continue;
1242 }
1243
1244 // Convert the function call to its inlined equivalent.
Brian Osman3887a012020-09-30 13:22:27 -04001245 InlinedCall inlinedCall = this->inlineCall(&funcCall, candidate.fSymbols,
Ethan Nicholas0a5d0962020-10-14 13:33:18 -04001246 &candidate.fEnclosingFunction->declaration());
John Stiles915a38c2020-09-14 09:38:13 -04001247 if (inlinedCall.fInlinedBody) {
1248 // Ensure that the inlined body has a scope if it needs one.
John Stiles6d696082020-10-01 10:18:54 -04001249 this->ensureScopedBlocks(inlinedCall.fInlinedBody.get(), candidate.fParentStmt->get());
John Stiles915a38c2020-09-14 09:38:13 -04001250
Brian Osman010ce6a2020-10-19 16:34:10 -04001251 // Add references within the inlined body
1252 usage->add(inlinedCall.fInlinedBody.get());
1253
John Stiles915a38c2020-09-14 09:38:13 -04001254 // Move the enclosing statement to the end of the unscoped Block containing the inlined
1255 // function, then replace the enclosing statement with that Block.
1256 // Before:
1257 // fInlinedBody = Block{ stmt1, stmt2, stmt3 }
1258 // fEnclosingStmt = stmt4
1259 // After:
1260 // fInlinedBody = null
1261 // fEnclosingStmt = Block{ stmt1, stmt2, stmt3, stmt4 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001262 inlinedCall.fInlinedBody->children().push_back(std::move(*candidate.fEnclosingStmt));
John Stiles915a38c2020-09-14 09:38:13 -04001263 *candidate.fEnclosingStmt = std::move(inlinedCall.fInlinedBody);
1264 }
1265
1266 // Replace the candidate function call with our replacement expression.
Brian Osman010ce6a2020-10-19 16:34:10 -04001267 usage->replace(candidate.fCandidateExpr->get(), inlinedCall.fReplacementExpr.get());
John Stiles915a38c2020-09-14 09:38:13 -04001268 *candidate.fCandidateExpr = std::move(inlinedCall.fReplacementExpr);
1269 madeChanges = true;
1270
John Stiles031a7672020-11-13 16:13:18 -05001271 // Stop inlining if we've reached our hard cap on new statements.
1272 if (fInlinedStatementCounter >= kInlinedStatementLimit) {
1273 break;
1274 }
1275
John Stiles915a38c2020-09-14 09:38:13 -04001276 // Note that nothing was destroyed except for the FunctionCall. All other nodes should
1277 // remain valid.
1278 }
1279
1280 return madeChanges;
John Stiles93442622020-09-11 12:11:27 -04001281}
1282
John Stiles44e96be2020-08-31 13:16:04 -04001283} // namespace SkSL