blob: 5b3fb4e5ede471d1e331735f2745a7e272810b90 [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 Stiles44dff4f2020-09-21 12:28:01 -040059static bool contains_returns_above_limit(const FunctionDefinition& funcDef, int limit) {
60 class CountReturnsWithLimit : public ProgramVisitor {
John Stiles44e96be2020-08-31 13:16:04 -040061 public:
John Stiles44dff4f2020-09-21 12:28:01 -040062 CountReturnsWithLimit(const FunctionDefinition& funcDef, int limit) : fLimit(limit) {
John Stiles44e96be2020-08-31 13:16:04 -040063 this->visitProgramElement(funcDef);
64 }
65
66 bool visitStatement(const Statement& stmt) override {
Ethan Nicholase6592142020-09-08 10:22:09 -040067 switch (stmt.kind()) {
68 case Statement::Kind::kReturn:
John Stiles44e96be2020-08-31 13:16:04 -040069 ++fNumReturns;
John Stiles44dff4f2020-09-21 12:28:01 -040070 return (fNumReturns > fLimit) || INHERITED::visitStatement(stmt);
John Stiles44e96be2020-08-31 13:16:04 -040071
72 default:
John Stiles93442622020-09-11 12:11:27 -040073 return INHERITED::visitStatement(stmt);
John Stiles44e96be2020-08-31 13:16:04 -040074 }
75 }
76
77 int fNumReturns = 0;
John Stiles44dff4f2020-09-21 12:28:01 -040078 int fLimit = 0;
John Stiles44e96be2020-08-31 13:16:04 -040079 using INHERITED = ProgramVisitor;
80 };
81
John Stiles44dff4f2020-09-21 12:28:01 -040082 return CountReturnsWithLimit{funcDef, limit}.fNumReturns > limit;
John Stiles44e96be2020-08-31 13:16:04 -040083}
84
85static int count_returns_at_end_of_control_flow(const FunctionDefinition& funcDef) {
86 class CountReturnsAtEndOfControlFlow : public ProgramVisitor {
87 public:
88 CountReturnsAtEndOfControlFlow(const FunctionDefinition& funcDef) {
89 this->visitProgramElement(funcDef);
90 }
91
92 bool visitStatement(const Statement& stmt) override {
Ethan Nicholase6592142020-09-08 10:22:09 -040093 switch (stmt.kind()) {
94 case Statement::Kind::kBlock: {
John Stiles44e96be2020-08-31 13:16:04 -040095 // Check only the last statement of a block.
Ethan Nicholas7bd60432020-09-25 14:31:59 -040096 const auto& block = stmt.as<Block>();
97 return block.children().size() &&
98 this->visitStatement(*block.children().back());
John Stiles44e96be2020-08-31 13:16:04 -040099 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400100 case Statement::Kind::kSwitch:
101 case Statement::Kind::kWhile:
102 case Statement::Kind::kDo:
103 case Statement::Kind::kFor:
John Stiles44e96be2020-08-31 13:16:04 -0400104 // Don't introspect switches or loop structures at all.
105 return false;
106
Ethan Nicholase6592142020-09-08 10:22:09 -0400107 case Statement::Kind::kReturn:
John Stiles44e96be2020-08-31 13:16:04 -0400108 ++fNumReturns;
109 [[fallthrough]];
110
111 default:
John Stiles93442622020-09-11 12:11:27 -0400112 return INHERITED::visitStatement(stmt);
John Stiles44e96be2020-08-31 13:16:04 -0400113 }
114 }
115
116 int fNumReturns = 0;
117 using INHERITED = ProgramVisitor;
118 };
119
120 return CountReturnsAtEndOfControlFlow{funcDef}.fNumReturns;
121}
122
123static int count_returns_in_breakable_constructs(const FunctionDefinition& funcDef) {
124 class CountReturnsInBreakableConstructs : public ProgramVisitor {
125 public:
126 CountReturnsInBreakableConstructs(const FunctionDefinition& funcDef) {
127 this->visitProgramElement(funcDef);
128 }
129
130 bool visitStatement(const Statement& stmt) override {
Ethan Nicholase6592142020-09-08 10:22:09 -0400131 switch (stmt.kind()) {
132 case Statement::Kind::kSwitch:
133 case Statement::Kind::kWhile:
134 case Statement::Kind::kDo:
135 case Statement::Kind::kFor: {
John Stiles44e96be2020-08-31 13:16:04 -0400136 ++fInsideBreakableConstruct;
John Stiles93442622020-09-11 12:11:27 -0400137 bool result = INHERITED::visitStatement(stmt);
John Stiles44e96be2020-08-31 13:16:04 -0400138 --fInsideBreakableConstruct;
139 return result;
140 }
141
Ethan Nicholase6592142020-09-08 10:22:09 -0400142 case Statement::Kind::kReturn:
John Stiles44e96be2020-08-31 13:16:04 -0400143 fNumReturns += (fInsideBreakableConstruct > 0) ? 1 : 0;
144 [[fallthrough]];
145
146 default:
John Stiles93442622020-09-11 12:11:27 -0400147 return INHERITED::visitStatement(stmt);
John Stiles44e96be2020-08-31 13:16:04 -0400148 }
149 }
150
151 int fNumReturns = 0;
152 int fInsideBreakableConstruct = 0;
153 using INHERITED = ProgramVisitor;
154 };
155
156 return CountReturnsInBreakableConstructs{funcDef}.fNumReturns;
157}
158
159static bool has_early_return(const FunctionDefinition& funcDef) {
John Stiles44e96be2020-08-31 13:16:04 -0400160 int returnsAtEndOfControlFlow = count_returns_at_end_of_control_flow(funcDef);
John Stiles44dff4f2020-09-21 12:28:01 -0400161 return contains_returns_above_limit(funcDef, returnsAtEndOfControlFlow);
John Stiles44e96be2020-08-31 13:16:04 -0400162}
163
John Stiles991b09d2020-09-10 13:33:40 -0400164static bool contains_recursive_call(const FunctionDeclaration& funcDecl) {
165 class ContainsRecursiveCall : public ProgramVisitor {
166 public:
167 bool visit(const FunctionDeclaration& funcDecl) {
168 fFuncDecl = &funcDecl;
169 return funcDecl.fDefinition ? this->visitProgramElement(*funcDecl.fDefinition)
170 : false;
171 }
172
173 bool visitExpression(const Expression& expr) override {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400174 if (expr.is<FunctionCall>() && expr.as<FunctionCall>().function().matches(*fFuncDecl)) {
John Stiles991b09d2020-09-10 13:33:40 -0400175 return true;
176 }
177 return INHERITED::visitExpression(expr);
178 }
179
180 bool visitStatement(const Statement& stmt) override {
181 if (stmt.is<InlineMarker>() && stmt.as<InlineMarker>().fFuncDecl->matches(*fFuncDecl)) {
182 return true;
183 }
184 return INHERITED::visitStatement(stmt);
185 }
186
187 const FunctionDeclaration* fFuncDecl;
188 using INHERITED = ProgramVisitor;
189 };
190
191 return ContainsRecursiveCall{}.visit(funcDecl);
192}
193
John Stiles44e96be2020-08-31 13:16:04 -0400194static const Type* copy_if_needed(const Type* src, SymbolTable& symbolTable) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400195 if (src->typeKind() == Type::TypeKind::kArray) {
Ethan Nicholase2c49992020-10-05 11:49:11 -0400196 return symbolTable.takeOwnershipOfSymbol(std::make_unique<Type>(src->name(),
197 src->typeKind(),
198 src->componentType(),
199 src->columns()));
John Stiles44e96be2020-08-31 13:16:04 -0400200 }
201 return src;
202}
203
John Stiles6d696082020-10-01 10:18:54 -0400204static std::unique_ptr<Statement>* find_parent_statement(
205 const std::vector<std::unique_ptr<Statement>*>& stmtStack) {
John Stiles915a38c2020-09-14 09:38:13 -0400206 SkASSERT(!stmtStack.empty());
207
208 // Walk the statement stack from back to front, ignoring the last element (which is the
209 // enclosing statement).
210 auto iter = stmtStack.rbegin();
211 ++iter;
212
213 // Anything counts as a parent statement other than a scopeless Block.
214 for (; iter != stmtStack.rend(); ++iter) {
John Stiles6d696082020-10-01 10:18:54 -0400215 std::unique_ptr<Statement>* stmt = *iter;
216 if (!(*stmt)->is<Block>() || (*stmt)->as<Block>().isScope()) {
John Stiles915a38c2020-09-14 09:38:13 -0400217 return stmt;
218 }
219 }
220
221 // There wasn't any parent statement to be found.
222 return nullptr;
223}
224
John Stilese41b4ee2020-09-28 12:28:16 -0400225std::unique_ptr<Expression> clone_with_ref_kind(const Expression& expr,
226 VariableReference::RefKind refKind) {
227 std::unique_ptr<Expression> clone = expr.clone();
John Stiles70b82422020-09-30 10:55:12 -0400228 class SetRefKindInExpression : public ProgramWriter {
John Stilese41b4ee2020-09-28 12:28:16 -0400229 public:
230 SetRefKindInExpression(VariableReference::RefKind refKind) : fRefKind(refKind) {}
John Stiles70b82422020-09-30 10:55:12 -0400231 bool visitExpression(Expression& expr) override {
John Stilese41b4ee2020-09-28 12:28:16 -0400232 if (expr.is<VariableReference>()) {
John Stiles70b82422020-09-30 10:55:12 -0400233 expr.as<VariableReference>().setRefKind(fRefKind);
John Stilese41b4ee2020-09-28 12:28:16 -0400234 }
235 return INHERITED::visitExpression(expr);
236 }
237
238 private:
239 VariableReference::RefKind fRefKind;
240
John Stiles70b82422020-09-30 10:55:12 -0400241 using INHERITED = ProgramWriter;
John Stilese41b4ee2020-09-28 12:28:16 -0400242 };
243
244 SetRefKindInExpression{refKind}.visitExpression(*clone);
245 return clone;
246}
247
John Stiles44733aa2020-09-29 17:42:23 -0400248bool is_trivial_argument(const Expression& argument) {
249 return argument.is<VariableReference>() ||
250 (argument.is<Swizzle>() && is_trivial_argument(*argument.as<Swizzle>().fBase)) ||
251 (argument.is<FieldAccess>() && is_trivial_argument(*argument.as<FieldAccess>().fBase)) ||
John Stiles80ccdbd2020-09-30 11:58:16 -0400252 (argument.is<Constructor>() &&
253 argument.as<Constructor>().arguments().size() == 1 &&
254 is_trivial_argument(*argument.as<Constructor>().arguments().front())) ||
John Stiles44733aa2020-09-29 17:42:23 -0400255 (argument.is<IndexExpression>() &&
256 argument.as<IndexExpression>().fIndex->is<IntLiteral>() &&
257 is_trivial_argument(*argument.as<IndexExpression>().fBase));
258}
259
John Stiles44e96be2020-08-31 13:16:04 -0400260} // namespace
261
John Stilesb61ee902020-09-21 12:26:59 -0400262void Inliner::ensureScopedBlocks(Statement* inlinedBody, Statement* parentStmt) {
263 // No changes necessary if this statement isn't actually a block.
264 if (!inlinedBody || !inlinedBody->is<Block>()) {
265 return;
266 }
267
268 // No changes necessary if the parent statement doesn't require a scope.
269 if (!parentStmt || !(parentStmt->is<IfStatement>() || parentStmt->is<ForStatement>() ||
270 parentStmt->is<DoStatement>() || parentStmt->is<WhileStatement>())) {
271 return;
272 }
273
274 Block& block = inlinedBody->as<Block>();
275
276 // The inliner will create inlined function bodies as a Block containing multiple statements,
277 // but no scope. Normally, this is fine, but if this block is used as the statement for a
278 // do/for/if/while, this isn't actually possible to represent textually; a scope must be added
279 // for the generated code to match the intent. In the case of Blocks nested inside other Blocks,
280 // we add the scope to the outermost block if needed. Zero-statement blocks have similar
281 // issues--if we don't represent the Block textually somehow, we run the risk of accidentally
282 // absorbing the following statement into our loop--so we also add a scope to these.
283 for (Block* nestedBlock = &block;; ) {
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400284 if (nestedBlock->isScope()) {
John Stilesb61ee902020-09-21 12:26:59 -0400285 // We found an explicit scope; all is well.
286 return;
287 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400288 if (nestedBlock->children().size() != 1) {
John Stilesb61ee902020-09-21 12:26:59 -0400289 // We found a block with multiple (or zero) statements, but no scope? Let's add a scope
290 // to the outermost block.
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400291 block.setIsScope(true);
John Stilesb61ee902020-09-21 12:26:59 -0400292 return;
293 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400294 if (!nestedBlock->children()[0]->is<Block>()) {
John Stilesb61ee902020-09-21 12:26:59 -0400295 // This block has exactly one thing inside, and it's not another block. No need to scope
296 // it.
297 return;
298 }
299 // We have to go deeper.
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400300 nestedBlock = &nestedBlock->children()[0]->as<Block>();
John Stilesb61ee902020-09-21 12:26:59 -0400301 }
302}
303
John Stiles44e96be2020-08-31 13:16:04 -0400304void Inliner::reset(const Context& context, const Program::Settings& settings) {
305 fContext = &context;
306 fSettings = &settings;
307 fInlineVarCounter = 0;
308}
309
John Stilesc75abb82020-09-14 18:24:12 -0400310String Inliner::uniqueNameForInlineVar(const String& baseName, SymbolTable* symbolTable) {
311 // If the base name starts with an underscore, like "_coords", we can't append another
312 // underscore, because OpenGL disallows two consecutive underscores anywhere in the string. But
313 // in the general case, using the underscore as a splitter reads nicely enough that it's worth
314 // putting in this special case.
315 const char* splitter = baseName.startsWith("_") ? "" : "_";
316
317 // Append a unique numeric prefix to avoid name overlap. Check the symbol table to make sure
318 // we're not reusing an existing name. (Note that within a single compilation pass, this check
319 // isn't fully comprehensive, as code isn't always generated in top-to-bottom order.)
320 String uniqueName;
321 for (;;) {
322 uniqueName = String::printf("_%d%s%s", fInlineVarCounter++, splitter, baseName.c_str());
323 StringFragment frag{uniqueName.data(), uniqueName.length()};
324 if ((*symbolTable)[frag] == nullptr) {
325 break;
326 }
327 }
328
329 return uniqueName;
330}
331
John Stiles44e96be2020-08-31 13:16:04 -0400332std::unique_ptr<Expression> Inliner::inlineExpression(int offset,
333 VariableRewriteMap* varMap,
334 const Expression& expression) {
335 auto expr = [&](const std::unique_ptr<Expression>& e) -> std::unique_ptr<Expression> {
336 if (e) {
337 return this->inlineExpression(offset, varMap, *e);
338 }
339 return nullptr;
340 };
341 auto argList = [&](const std::vector<std::unique_ptr<Expression>>& originalArgs)
342 -> std::vector<std::unique_ptr<Expression>> {
343 std::vector<std::unique_ptr<Expression>> args;
344 args.reserve(originalArgs.size());
345 for (const std::unique_ptr<Expression>& arg : originalArgs) {
346 args.push_back(expr(arg));
347 }
348 return args;
349 };
350
Ethan Nicholase6592142020-09-08 10:22:09 -0400351 switch (expression.kind()) {
352 case Expression::Kind::kBinary: {
John Stiles44e96be2020-08-31 13:16:04 -0400353 const BinaryExpression& b = expression.as<BinaryExpression>();
354 return std::make_unique<BinaryExpression>(offset,
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400355 expr(b.leftPointer()),
356 b.getOperator(),
357 expr(b.rightPointer()),
Ethan Nicholas30d30222020-09-11 12:27:26 -0400358 &b.type());
John Stiles44e96be2020-08-31 13:16:04 -0400359 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400360 case Expression::Kind::kBoolLiteral:
361 case Expression::Kind::kIntLiteral:
362 case Expression::Kind::kFloatLiteral:
363 case Expression::Kind::kNullLiteral:
John Stiles44e96be2020-08-31 13:16:04 -0400364 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400365 case Expression::Kind::kConstructor: {
John Stiles44e96be2020-08-31 13:16:04 -0400366 const Constructor& constructor = expression.as<Constructor>();
Ethan Nicholas30d30222020-09-11 12:27:26 -0400367 return std::make_unique<Constructor>(offset, &constructor.type(),
Ethan Nicholasf70f0442020-09-29 12:41:35 -0400368 argList(constructor.arguments()));
John Stiles44e96be2020-08-31 13:16:04 -0400369 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400370 case Expression::Kind::kExternalFunctionCall: {
John Stiles44e96be2020-08-31 13:16:04 -0400371 const ExternalFunctionCall& externalCall = expression.as<ExternalFunctionCall>();
Ethan Nicholas30d30222020-09-11 12:27:26 -0400372 return std::make_unique<ExternalFunctionCall>(offset, &externalCall.type(),
Ethan Nicholas6e86ec92020-09-30 14:29:56 -0400373 externalCall.function(),
374 argList(externalCall.arguments()));
John Stiles44e96be2020-08-31 13:16:04 -0400375 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400376 case Expression::Kind::kExternalValue:
John Stiles44e96be2020-08-31 13:16:04 -0400377 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400378 case Expression::Kind::kFieldAccess: {
John Stiles44e96be2020-08-31 13:16:04 -0400379 const FieldAccess& f = expression.as<FieldAccess>();
380 return std::make_unique<FieldAccess>(expr(f.fBase), f.fFieldIndex, f.fOwnerKind);
381 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400382 case Expression::Kind::kFunctionCall: {
John Stiles44e96be2020-08-31 13:16:04 -0400383 const FunctionCall& funcCall = expression.as<FunctionCall>();
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400384 return std::make_unique<FunctionCall>(offset, &funcCall.type(), &funcCall.function(),
385 argList(funcCall.arguments()));
John Stiles44e96be2020-08-31 13:16:04 -0400386 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400387 case Expression::Kind::kFunctionReference:
Brian Osman2b3b35f2020-09-08 09:17:36 -0400388 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400389 case Expression::Kind::kIndex: {
John Stiles44e96be2020-08-31 13:16:04 -0400390 const IndexExpression& idx = expression.as<IndexExpression>();
391 return std::make_unique<IndexExpression>(*fContext, expr(idx.fBase), expr(idx.fIndex));
392 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400393 case Expression::Kind::kPrefix: {
John Stiles44e96be2020-08-31 13:16:04 -0400394 const PrefixExpression& p = expression.as<PrefixExpression>();
395 return std::make_unique<PrefixExpression>(p.fOperator, expr(p.fOperand));
396 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400397 case Expression::Kind::kPostfix: {
John Stiles44e96be2020-08-31 13:16:04 -0400398 const PostfixExpression& p = expression.as<PostfixExpression>();
399 return std::make_unique<PostfixExpression>(expr(p.fOperand), p.fOperator);
400 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400401 case Expression::Kind::kSetting:
John Stiles44e96be2020-08-31 13:16:04 -0400402 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400403 case Expression::Kind::kSwizzle: {
John Stiles44e96be2020-08-31 13:16:04 -0400404 const Swizzle& s = expression.as<Swizzle>();
405 return std::make_unique<Swizzle>(*fContext, expr(s.fBase), s.fComponents);
406 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400407 case Expression::Kind::kTernary: {
John Stiles44e96be2020-08-31 13:16:04 -0400408 const TernaryExpression& t = expression.as<TernaryExpression>();
409 return std::make_unique<TernaryExpression>(offset, expr(t.fTest),
410 expr(t.fIfTrue), expr(t.fIfFalse));
411 }
Brian Osman83ba9302020-09-11 13:33:46 -0400412 case Expression::Kind::kTypeReference:
413 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400414 case Expression::Kind::kVariableReference: {
John Stiles44e96be2020-08-31 13:16:04 -0400415 const VariableReference& v = expression.as<VariableReference>();
John Stilese41b4ee2020-09-28 12:28:16 -0400416 auto varMapIter = varMap->find(v.fVariable);
417 if (varMapIter != varMap->end()) {
418 return clone_with_ref_kind(*varMapIter->second, v.fRefKind);
John Stiles44e96be2020-08-31 13:16:04 -0400419 }
420 return v.clone();
421 }
422 default:
423 SkASSERT(false);
424 return nullptr;
425 }
426}
427
428std::unique_ptr<Statement> Inliner::inlineStatement(int offset,
429 VariableRewriteMap* varMap,
430 SymbolTable* symbolTableForStatement,
John Stilese41b4ee2020-09-28 12:28:16 -0400431 const Expression* resultExpr,
John Stiles44e96be2020-08-31 13:16:04 -0400432 bool haveEarlyReturns,
Brian Osman3887a012020-09-30 13:22:27 -0400433 const Statement& statement,
434 bool isBuiltinCode) {
John Stiles44e96be2020-08-31 13:16:04 -0400435 auto stmt = [&](const std::unique_ptr<Statement>& s) -> std::unique_ptr<Statement> {
436 if (s) {
John Stilesa5f3c312020-09-22 12:05:16 -0400437 return this->inlineStatement(offset, varMap, symbolTableForStatement, resultExpr,
Brian Osman3887a012020-09-30 13:22:27 -0400438 haveEarlyReturns, *s, isBuiltinCode);
John Stiles44e96be2020-08-31 13:16:04 -0400439 }
440 return nullptr;
441 };
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400442 auto blockStmts = [&](const Block& block) {
443 std::vector<std::unique_ptr<Statement>> result;
444 for (const std::unique_ptr<Statement>& child : block.children()) {
445 result.push_back(stmt(child));
446 }
447 return result;
448 };
John Stiles44e96be2020-08-31 13:16:04 -0400449 auto stmts = [&](const std::vector<std::unique_ptr<Statement>>& ss) {
450 std::vector<std::unique_ptr<Statement>> result;
451 for (const auto& s : ss) {
452 result.push_back(stmt(s));
453 }
454 return result;
455 };
456 auto expr = [&](const std::unique_ptr<Expression>& e) -> std::unique_ptr<Expression> {
457 if (e) {
458 return this->inlineExpression(offset, varMap, *e);
459 }
460 return nullptr;
461 };
Ethan Nicholase6592142020-09-08 10:22:09 -0400462 switch (statement.kind()) {
463 case Statement::Kind::kBlock: {
John Stiles44e96be2020-08-31 13:16:04 -0400464 const Block& b = statement.as<Block>();
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400465 return std::make_unique<Block>(offset, blockStmts(b), b.symbolTable(), b.isScope());
John Stiles44e96be2020-08-31 13:16:04 -0400466 }
467
Ethan Nicholase6592142020-09-08 10:22:09 -0400468 case Statement::Kind::kBreak:
469 case Statement::Kind::kContinue:
470 case Statement::Kind::kDiscard:
John Stiles44e96be2020-08-31 13:16:04 -0400471 return statement.clone();
472
Ethan Nicholase6592142020-09-08 10:22:09 -0400473 case Statement::Kind::kDo: {
John Stiles44e96be2020-08-31 13:16:04 -0400474 const DoStatement& d = statement.as<DoStatement>();
Ethan Nicholas1fd61162020-09-28 13:14:19 -0400475 return std::make_unique<DoStatement>(offset, stmt(d.statement()), expr(d.test()));
John Stiles44e96be2020-08-31 13:16:04 -0400476 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400477 case Statement::Kind::kExpression: {
John Stiles44e96be2020-08-31 13:16:04 -0400478 const ExpressionStatement& e = statement.as<ExpressionStatement>();
Ethan Nicholasd503a5a2020-09-30 09:29:55 -0400479 return std::make_unique<ExpressionStatement>(expr(e.expression()));
John Stiles44e96be2020-08-31 13:16:04 -0400480 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400481 case Statement::Kind::kFor: {
John Stiles44e96be2020-08-31 13:16:04 -0400482 const ForStatement& f = statement.as<ForStatement>();
483 // need to ensure initializer is evaluated first so that we've already remapped its
484 // declarations by the time we evaluate test & next
Ethan Nicholas0d31ed52020-10-05 14:47:09 -0400485 std::unique_ptr<Statement> initializer = stmt(f.initializer());
486 return std::make_unique<ForStatement>(offset, std::move(initializer), expr(f.test()),
487 expr(f.next()), stmt(f.statement()), f.symbols());
John Stiles44e96be2020-08-31 13:16:04 -0400488 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400489 case Statement::Kind::kIf: {
John Stiles44e96be2020-08-31 13:16:04 -0400490 const IfStatement& i = statement.as<IfStatement>();
491 return std::make_unique<IfStatement>(offset, i.fIsStatic, expr(i.fTest),
492 stmt(i.fIfTrue), stmt(i.fIfFalse));
493 }
John Stiles98c1f822020-09-09 14:18:53 -0400494 case Statement::Kind::kInlineMarker:
Ethan Nicholase6592142020-09-08 10:22:09 -0400495 case Statement::Kind::kNop:
John Stiles44e96be2020-08-31 13:16:04 -0400496 return statement.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400497 case Statement::Kind::kReturn: {
John Stiles44e96be2020-08-31 13:16:04 -0400498 const ReturnStatement& r = statement.as<ReturnStatement>();
499 if (r.fExpression) {
John Stilese41b4ee2020-09-28 12:28:16 -0400500 SkASSERT(resultExpr);
John Stilesa5f3c312020-09-22 12:05:16 -0400501 auto assignment =
502 std::make_unique<ExpressionStatement>(std::make_unique<BinaryExpression>(
503 offset,
John Stilese41b4ee2020-09-28 12:28:16 -0400504 clone_with_ref_kind(*resultExpr, VariableReference::kWrite_RefKind),
John Stilesa5f3c312020-09-22 12:05:16 -0400505 Token::Kind::TK_EQ,
506 expr(r.fExpression),
John Stilese41b4ee2020-09-28 12:28:16 -0400507 &resultExpr->type()));
John Stiles44e96be2020-08-31 13:16:04 -0400508 if (haveEarlyReturns) {
509 std::vector<std::unique_ptr<Statement>> block;
510 block.push_back(std::move(assignment));
511 block.emplace_back(new BreakStatement(offset));
512 return std::make_unique<Block>(offset, std::move(block), /*symbols=*/nullptr,
513 /*isScope=*/true);
514 } else {
515 return std::move(assignment);
516 }
517 } else {
518 if (haveEarlyReturns) {
519 return std::make_unique<BreakStatement>(offset);
520 } else {
521 return std::make_unique<Nop>();
522 }
523 }
524 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400525 case Statement::Kind::kSwitch: {
John Stiles44e96be2020-08-31 13:16:04 -0400526 const SwitchStatement& ss = statement.as<SwitchStatement>();
527 std::vector<std::unique_ptr<SwitchCase>> cases;
528 for (const auto& sc : ss.fCases) {
529 cases.emplace_back(new SwitchCase(offset, expr(sc->fValue),
530 stmts(sc->fStatements)));
531 }
532 return std::make_unique<SwitchStatement>(offset, ss.fIsStatic, expr(ss.fValue),
533 std::move(cases), ss.fSymbols);
534 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400535 case Statement::Kind::kVarDeclaration: {
John Stiles44e96be2020-08-31 13:16:04 -0400536 const VarDeclaration& decl = statement.as<VarDeclaration>();
537 std::vector<std::unique_ptr<Expression>> sizes;
538 for (const auto& size : decl.fSizes) {
539 sizes.push_back(expr(size));
540 }
541 std::unique_ptr<Expression> initialValue = expr(decl.fValue);
542 const Variable* old = decl.fVar;
John Stilesc75abb82020-09-14 18:24:12 -0400543 // We assign unique names to inlined variables--scopes hide most of the problems in this
544 // regard, but see `InlinerAvoidsVariableNameOverlap` for a counterexample where unique
545 // names are important.
546 auto name = std::make_unique<String>(
Ethan Nicholase2c49992020-10-05 11:49:11 -0400547 this->uniqueNameForInlineVar(String(old->name()), symbolTableForStatement));
John Stiles44e96be2020-08-31 13:16:04 -0400548 const String* namePtr = symbolTableForStatement->takeOwnershipOfString(std::move(name));
Brian Osmanc0213602020-10-06 14:43:32 -0400549 const Type* baseTypePtr = copy_if_needed(&decl.fBaseType, *symbolTableForStatement);
Ethan Nicholas30d30222020-09-11 12:27:26 -0400550 const Type* typePtr = copy_if_needed(&old->type(), *symbolTableForStatement);
John Stiles44e96be2020-08-31 13:16:04 -0400551 const Variable* clone = symbolTableForStatement->takeOwnershipOfSymbol(
552 std::make_unique<Variable>(offset,
553 old->fModifiers,
554 namePtr->c_str(),
Ethan Nicholas30d30222020-09-11 12:27:26 -0400555 typePtr,
Brian Osman3887a012020-09-30 13:22:27 -0400556 isBuiltinCode,
John Stiles44e96be2020-08-31 13:16:04 -0400557 old->fStorage,
558 initialValue.get()));
John Stilese41b4ee2020-09-28 12:28:16 -0400559 (*varMap)[old] = std::make_unique<VariableReference>(offset, clone);
Brian Osmanc0213602020-10-06 14:43:32 -0400560 return std::make_unique<VarDeclaration>(clone, baseTypePtr, std::move(sizes),
John Stiles44e96be2020-08-31 13:16:04 -0400561 std::move(initialValue));
562 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400563 case Statement::Kind::kWhile: {
John Stiles44e96be2020-08-31 13:16:04 -0400564 const WhileStatement& w = statement.as<WhileStatement>();
565 return std::make_unique<WhileStatement>(offset, expr(w.fTest), stmt(w.fStatement));
566 }
567 default:
568 SkASSERT(false);
569 return nullptr;
570 }
571}
572
John Stiles6eadf132020-09-08 10:16:10 -0400573Inliner::InlinedCall Inliner::inlineCall(FunctionCall* call,
Brian Osman3887a012020-09-30 13:22:27 -0400574 SymbolTable* symbolTableForCall,
575 const FunctionDeclaration* caller) {
John Stiles44e96be2020-08-31 13:16:04 -0400576 // Inlining is more complicated here than in a typical compiler, because we have to have a
577 // high-level IR and can't just drop statements into the middle of an expression or even use
578 // gotos.
579 //
580 // Since we can't insert statements into an expression, we run the inline function as extra
581 // statements before the statement we're currently processing, relying on a lack of execution
582 // order guarantees. Since we can't use gotos (which are normally used to replace return
583 // statements), we wrap the whole function in a loop and use break statements to jump to the
584 // end.
585 SkASSERT(fSettings);
586 SkASSERT(fContext);
587 SkASSERT(call);
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400588 SkASSERT(this->isSafeToInline(call->function().fDefinition));
John Stiles44e96be2020-08-31 13:16:04 -0400589
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400590 std::vector<std::unique_ptr<Expression>>& arguments = call->arguments();
John Stiles6eadf132020-09-08 10:16:10 -0400591 const int offset = call->fOffset;
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400592 const FunctionDefinition& function = *call->function().fDefinition;
John Stiles6eadf132020-09-08 10:16:10 -0400593 const bool hasEarlyReturn = has_early_return(function);
594
John Stiles44e96be2020-08-31 13:16:04 -0400595 InlinedCall inlinedCall;
John Stiles6eadf132020-09-08 10:16:10 -0400596 inlinedCall.fInlinedBody = std::make_unique<Block>(offset,
597 std::vector<std::unique_ptr<Statement>>{},
598 /*symbols=*/nullptr,
599 /*isScope=*/false);
John Stiles98c1f822020-09-09 14:18:53 -0400600
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400601 Block& inlinedBody = *inlinedCall.fInlinedBody;
602 inlinedBody.children().reserve(1 + // Inline marker
603 1 + // Result variable
604 arguments.size() + // Function arguments (passing in)
John Stilese41b4ee2020-09-28 12:28:16 -0400605 arguments.size() + // Function arguments (copy out-params back)
606 1); // Inlined code (Block or do-while loop)
John Stiles98c1f822020-09-09 14:18:53 -0400607
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400608 inlinedBody.children().push_back(std::make_unique<InlineMarker>(call->function()));
John Stiles44e96be2020-08-31 13:16:04 -0400609
John Stilese41b4ee2020-09-28 12:28:16 -0400610 auto makeInlineVar =
611 [&](const String& baseName, const Type* type, Modifiers modifiers,
612 std::unique_ptr<Expression>* initialValue) -> std::unique_ptr<Expression> {
John Stilesa003e812020-09-11 09:43:49 -0400613 // $floatLiteral or $intLiteral aren't real types that we can use for scratch variables, so
614 // replace them if they ever appear here. If this happens, we likely forgot to coerce a type
615 // somewhere during compilation.
616 if (type == fContext->fFloatLiteral_Type.get()) {
John Stilesd2be5c52020-09-11 14:58:06 -0400617 SkDEBUGFAIL("found a $floatLiteral type while inlining");
John Stilesa003e812020-09-11 09:43:49 -0400618 type = fContext->fFloat_Type.get();
619 } else if (type == fContext->fIntLiteral_Type.get()) {
John Stilesd2be5c52020-09-11 14:58:06 -0400620 SkDEBUGFAIL("found an $intLiteral type while inlining");
John Stilesa003e812020-09-11 09:43:49 -0400621 type = fContext->fInt_Type.get();
622 }
623
John Stilesc75abb82020-09-14 18:24:12 -0400624 // Provide our new variable with a unique name, and add it to our symbol table.
625 String uniqueName = this->uniqueNameForInlineVar(baseName, symbolTableForCall);
John Stilescf936f92020-08-31 17:18:45 -0400626 const String* namePtr = symbolTableForCall->takeOwnershipOfString(
627 std::make_unique<String>(std::move(uniqueName)));
John Stiles44e96be2020-08-31 13:16:04 -0400628 StringFragment nameFrag{namePtr->c_str(), namePtr->length()};
629
630 // Add our new variable to the symbol table.
Ethan Nicholas30d30222020-09-11 12:27:26 -0400631 auto newVar = std::make_unique<Variable>(/*offset=*/-1, Modifiers(), nameFrag, type,
Brian Osman3887a012020-09-30 13:22:27 -0400632 caller->fBuiltin, Variable::kLocal_Storage,
633 initialValue->get());
John Stiles44e96be2020-08-31 13:16:04 -0400634 const Variable* variableSymbol = symbolTableForCall->add(nameFrag, std::move(newVar));
635
636 // Prepare the variable declaration (taking extra care with `out` params to not clobber any
637 // initial value).
Brian Osmanc0213602020-10-06 14:43:32 -0400638 std::unique_ptr<Statement> variable;
John Stiles44e96be2020-08-31 13:16:04 -0400639 if (initialValue && (modifiers.fFlags & Modifiers::kOut_Flag)) {
Brian Osmanc0213602020-10-06 14:43:32 -0400640 variable = std::make_unique<VarDeclaration>(
641 variableSymbol, type, /*sizes=*/std::vector<std::unique_ptr<Expression>>{},
642 (*initialValue)->clone());
John Stiles44e96be2020-08-31 13:16:04 -0400643 } else {
Brian Osmanc0213602020-10-06 14:43:32 -0400644 variable = std::make_unique<VarDeclaration>(
645 variableSymbol, type, /*sizes=*/std::vector<std::unique_ptr<Expression>>{},
646 std::move(*initialValue));
John Stiles44e96be2020-08-31 13:16:04 -0400647 }
648
649 // Add the new variable-declaration statement to our block of extra statements.
Brian Osmanc0213602020-10-06 14:43:32 -0400650 inlinedBody.children().push_back(std::move(variable));
John Stiles44e96be2020-08-31 13:16:04 -0400651
John Stilese41b4ee2020-09-28 12:28:16 -0400652 return std::make_unique<VariableReference>(offset, variableSymbol);
John Stiles44e96be2020-08-31 13:16:04 -0400653 };
654
655 // Create a variable to hold the result in the extra statements (excepting void).
John Stilese41b4ee2020-09-28 12:28:16 -0400656 std::unique_ptr<Expression> resultExpr;
John Stiles44e96be2020-08-31 13:16:04 -0400657 if (function.fDeclaration.fReturnType != *fContext->fVoid_Type) {
John Stiles44e96be2020-08-31 13:16:04 -0400658 std::unique_ptr<Expression> noInitialValue;
Ethan Nicholase2c49992020-10-05 11:49:11 -0400659 resultExpr = makeInlineVar(String(function.fDeclaration.name()),
John Stilese41b4ee2020-09-28 12:28:16 -0400660 &function.fDeclaration.fReturnType,
661 Modifiers{}, &noInitialValue);
662 }
John Stiles44e96be2020-08-31 13:16:04 -0400663
664 // Create variables in the extra statements to hold the arguments, and assign the arguments to
665 // them.
666 VariableRewriteMap varMap;
John Stilese41b4ee2020-09-28 12:28:16 -0400667 std::vector<int> argsToCopyBack;
John Stiles44e96be2020-08-31 13:16:04 -0400668 for (int i = 0; i < (int) arguments.size(); ++i) {
669 const Variable* param = function.fDeclaration.fParameters[i];
John Stilese41b4ee2020-09-28 12:28:16 -0400670 bool isOutParam = param->fModifiers.fFlags & Modifiers::kOut_Flag;
John Stiles44e96be2020-08-31 13:16:04 -0400671
John Stiles44733aa2020-09-29 17:42:23 -0400672 // If this argument can be inlined trivially (e.g. a swizzle, or a constant array index)...
673 if (is_trivial_argument(*arguments[i])) {
John Stilese41b4ee2020-09-28 12:28:16 -0400674 // ... and it's an `out` param, or it isn't written to within the inline function...
675 if (isOutParam || !Analysis::StatementWritesToVariable(*function.fBody, *param)) {
John Stilesf201af82020-09-29 16:57:55 -0400676 // ... we don't need to copy it at all! We can just use the existing expression.
677 varMap[param] = arguments[i]->clone();
John Stiles44e96be2020-08-31 13:16:04 -0400678 continue;
679 }
680 }
681
John Stilese41b4ee2020-09-28 12:28:16 -0400682 if (isOutParam) {
683 argsToCopyBack.push_back(i);
684 }
685
Ethan Nicholase2c49992020-10-05 11:49:11 -0400686 varMap[param] = makeInlineVar(String(param->name()), &arguments[i]->type(),
Ethan Nicholas30d30222020-09-11 12:27:26 -0400687 param->fModifiers, &arguments[i]);
John Stiles44e96be2020-08-31 13:16:04 -0400688 }
689
690 const Block& body = function.fBody->as<Block>();
John Stiles44e96be2020-08-31 13:16:04 -0400691 auto inlineBlock = std::make_unique<Block>(offset, std::vector<std::unique_ptr<Statement>>{});
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400692 inlineBlock->children().reserve(body.children().size());
693 for (const std::unique_ptr<Statement>& stmt : body.children()) {
Brian Osman3887a012020-09-30 13:22:27 -0400694 inlineBlock->children().push_back(this->inlineStatement(offset, &varMap, symbolTableForCall,
695 resultExpr.get(), hasEarlyReturn,
696 *stmt, caller->fBuiltin));
John Stiles44e96be2020-08-31 13:16:04 -0400697 }
698 if (hasEarlyReturn) {
699 // Since we output to backends that don't have a goto statement (which would normally be
700 // used to perform an early return), we fake it by wrapping the function in a
701 // do { } while (false); and then use break statements to jump to the end in order to
702 // emulate a goto.
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400703 inlinedBody.children().push_back(std::make_unique<DoStatement>(
John Stiles44e96be2020-08-31 13:16:04 -0400704 /*offset=*/-1,
705 std::move(inlineBlock),
706 std::make_unique<BoolLiteral>(*fContext, offset, /*value=*/false)));
707 } else {
John Stiles6eadf132020-09-08 10:16:10 -0400708 // No early returns, so we can just dump the code in. We still need to keep the block so we
709 // don't get name conflicts with locals.
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400710 inlinedBody.children().push_back(std::move(inlineBlock));
John Stiles44e96be2020-08-31 13:16:04 -0400711 }
712
John Stilese41b4ee2020-09-28 12:28:16 -0400713 // Copy back the values of `out` parameters into their real destinations.
714 for (int i : argsToCopyBack) {
John Stiles44e96be2020-08-31 13:16:04 -0400715 const Variable* p = function.fDeclaration.fParameters[i];
John Stilese41b4ee2020-09-28 12:28:16 -0400716 SkASSERT(varMap.find(p) != varMap.end());
717 inlinedBody.children().push_back(
718 std::make_unique<ExpressionStatement>(std::make_unique<BinaryExpression>(
719 offset,
720 clone_with_ref_kind(*arguments[i], VariableReference::kWrite_RefKind),
721 Token::Kind::TK_EQ,
722 std::move(varMap[p]),
723 &arguments[i]->type())));
John Stiles44e96be2020-08-31 13:16:04 -0400724 }
725
John Stilese41b4ee2020-09-28 12:28:16 -0400726 if (resultExpr != nullptr) {
727 // Return our result variable as our replacement expression.
728 SkASSERT(resultExpr->as<VariableReference>().fRefKind == VariableReference::kRead_RefKind);
729 inlinedCall.fReplacementExpr = std::move(resultExpr);
John Stiles44e96be2020-08-31 13:16:04 -0400730 } else {
731 // It's a void function, so it doesn't actually result in anything, but we have to return
732 // something non-null as a standin.
733 inlinedCall.fReplacementExpr = std::make_unique<BoolLiteral>(*fContext, offset,
734 /*value=*/false);
735 }
736
John Stiles44e96be2020-08-31 13:16:04 -0400737 return inlinedCall;
738}
739
John Stiles2d7973a2020-10-02 15:01:03 -0400740bool Inliner::isSafeToInline(const FunctionDefinition* functionDef) {
John Stiles44e96be2020-08-31 13:16:04 -0400741 SkASSERT(fSettings);
742
John Stiles2d7973a2020-10-02 15:01:03 -0400743 if (functionDef == nullptr) {
John Stiles44e96be2020-08-31 13:16:04 -0400744 // Can't inline something if we don't actually have its definition.
745 return false;
746 }
John Stiles2d7973a2020-10-02 15:01:03 -0400747
John Stiles44e96be2020-08-31 13:16:04 -0400748 if (!fSettings->fCaps || !fSettings->fCaps->canUseDoLoops()) {
749 // We don't have do-while loops. We use do-while loops to simulate early returns, so we
750 // can't inline functions that have an early return.
John Stiles2d7973a2020-10-02 15:01:03 -0400751 bool hasEarlyReturn = has_early_return(*functionDef);
John Stiles44e96be2020-08-31 13:16:04 -0400752
753 // If we didn't detect an early return, there shouldn't be any returns in breakable
754 // constructs either.
John Stiles2d7973a2020-10-02 15:01:03 -0400755 SkASSERT(hasEarlyReturn || count_returns_in_breakable_constructs(*functionDef) == 0);
John Stiles44e96be2020-08-31 13:16:04 -0400756 return !hasEarlyReturn;
757 }
758 // We have do-while loops, but we don't have any mechanism to simulate early returns within a
759 // 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 -0400760 bool hasReturnInBreakableConstruct = (count_returns_in_breakable_constructs(*functionDef) > 0);
John Stiles44e96be2020-08-31 13:16:04 -0400761
762 // If we detected returns in breakable constructs, we should also detect an early return.
John Stiles2d7973a2020-10-02 15:01:03 -0400763 SkASSERT(!hasReturnInBreakableConstruct || has_early_return(*functionDef));
John Stiles44e96be2020-08-31 13:16:04 -0400764 return !hasReturnInBreakableConstruct;
765}
766
John Stiles2d7973a2020-10-02 15:01:03 -0400767// A candidate function for inlining, containing everything that `inlineCall` needs.
768struct InlineCandidate {
769 SymbolTable* fSymbols; // the SymbolTable of the candidate
770 std::unique_ptr<Statement>* fParentStmt; // the parent Statement of the enclosing stmt
771 std::unique_ptr<Statement>* fEnclosingStmt; // the Statement containing the candidate
772 std::unique_ptr<Expression>* fCandidateExpr; // the candidate FunctionCall to be inlined
773 FunctionDefinition* fEnclosingFunction; // the Function containing the candidate
774 bool fIsLargeFunction; // does candidate exceed the inline threshold?
775};
John Stiles93442622020-09-11 12:11:27 -0400776
John Stiles2d7973a2020-10-02 15:01:03 -0400777struct InlineCandidateList {
778 std::vector<InlineCandidate> fCandidates;
779};
780
781class InlineCandidateAnalyzer {
John Stiles70957c82020-10-02 16:42:10 -0400782public:
783 // A list of all the inlining candidates we found during analysis.
784 InlineCandidateList* fCandidateList;
John Stiles2d7973a2020-10-02 15:01:03 -0400785
John Stiles70957c82020-10-02 16:42:10 -0400786 // A stack of the symbol tables; since most nodes don't have one, expected to be shallower than
787 // the enclosing-statement stack.
788 std::vector<SymbolTable*> fSymbolTableStack;
789 // A stack of "enclosing" statements--these would be suitable for the inliner to use for adding
790 // new instructions. Not all statements are suitable (e.g. a for-loop's initializer). The
791 // inliner might replace a statement with a block containing the statement.
792 std::vector<std::unique_ptr<Statement>*> fEnclosingStmtStack;
793 // The function that we're currently processing (i.e. inlining into).
794 FunctionDefinition* fEnclosingFunction = nullptr;
John Stiles93442622020-09-11 12:11:27 -0400795
John Stiles70957c82020-10-02 16:42:10 -0400796 void visit(Program& program, InlineCandidateList* candidateList) {
797 fCandidateList = candidateList;
798 fSymbolTableStack.push_back(program.fSymbols.get());
John Stiles93442622020-09-11 12:11:27 -0400799
John Stiles70957c82020-10-02 16:42:10 -0400800 for (ProgramElement& pe : program) {
801 this->visitProgramElement(&pe);
John Stiles93442622020-09-11 12:11:27 -0400802 }
803
John Stiles70957c82020-10-02 16:42:10 -0400804 fSymbolTableStack.pop_back();
805 fCandidateList = nullptr;
806 }
807
808 void visitProgramElement(ProgramElement* pe) {
809 switch (pe->kind()) {
810 case ProgramElement::Kind::kFunction: {
811 FunctionDefinition& funcDef = pe->as<FunctionDefinition>();
812 fEnclosingFunction = &funcDef;
813 this->visitStatement(&funcDef.fBody);
814 break;
John Stiles93442622020-09-11 12:11:27 -0400815 }
John Stiles70957c82020-10-02 16:42:10 -0400816 default:
817 // The inliner can't operate outside of a function's scope.
818 break;
819 }
820 }
821
822 void visitStatement(std::unique_ptr<Statement>* stmt,
823 bool isViableAsEnclosingStatement = true) {
824 if (!*stmt) {
825 return;
John Stiles93442622020-09-11 12:11:27 -0400826 }
827
John Stiles70957c82020-10-02 16:42:10 -0400828 size_t oldEnclosingStmtStackSize = fEnclosingStmtStack.size();
829 size_t oldSymbolStackSize = fSymbolTableStack.size();
John Stiles93442622020-09-11 12:11:27 -0400830
John Stiles70957c82020-10-02 16:42:10 -0400831 if (isViableAsEnclosingStatement) {
832 fEnclosingStmtStack.push_back(stmt);
John Stiles93442622020-09-11 12:11:27 -0400833 }
834
John Stiles70957c82020-10-02 16:42:10 -0400835 switch ((*stmt)->kind()) {
836 case Statement::Kind::kBreak:
837 case Statement::Kind::kContinue:
838 case Statement::Kind::kDiscard:
839 case Statement::Kind::kInlineMarker:
840 case Statement::Kind::kNop:
841 break;
842
843 case Statement::Kind::kBlock: {
844 Block& block = (*stmt)->as<Block>();
845 if (block.symbolTable()) {
846 fSymbolTableStack.push_back(block.symbolTable().get());
847 }
848
849 for (std::unique_ptr<Statement>& stmt : block.children()) {
850 this->visitStatement(&stmt);
851 }
852 break;
John Stiles93442622020-09-11 12:11:27 -0400853 }
John Stiles70957c82020-10-02 16:42:10 -0400854 case Statement::Kind::kDo: {
855 DoStatement& doStmt = (*stmt)->as<DoStatement>();
856 // The loop body is a candidate for inlining.
857 this->visitStatement(&doStmt.statement());
858 // The inliner isn't smart enough to inline the test-expression for a do-while
859 // loop at this time. There are two limitations:
860 // - We would need to insert the inlined-body block at the very end of the do-
861 // statement's inner fStatement. We don't support that today, but it's doable.
862 // - We cannot inline the test expression if the loop uses `continue` anywhere; that
863 // would skip over the inlined block that evaluates the test expression. There
864 // isn't a good fix for this--any workaround would be more complex than the cost
865 // of a function call. However, loops that don't use `continue` would still be
866 // viable candidates for inlining.
867 break;
John Stiles93442622020-09-11 12:11:27 -0400868 }
John Stiles70957c82020-10-02 16:42:10 -0400869 case Statement::Kind::kExpression: {
870 ExpressionStatement& expr = (*stmt)->as<ExpressionStatement>();
871 this->visitExpression(&expr.expression());
872 break;
873 }
874 case Statement::Kind::kFor: {
875 ForStatement& forStmt = (*stmt)->as<ForStatement>();
Ethan Nicholas0d31ed52020-10-05 14:47:09 -0400876 if (forStmt.symbols()) {
877 fSymbolTableStack.push_back(forStmt.symbols().get());
John Stiles70957c82020-10-02 16:42:10 -0400878 }
879
880 // The initializer and loop body are candidates for inlining.
Ethan Nicholas0d31ed52020-10-05 14:47:09 -0400881 this->visitStatement(&forStmt.initializer(),
John Stiles70957c82020-10-02 16:42:10 -0400882 /*isViableAsEnclosingStatement=*/false);
Ethan Nicholas0d31ed52020-10-05 14:47:09 -0400883 this->visitStatement(&forStmt.statement());
John Stiles70957c82020-10-02 16:42:10 -0400884
885 // The inliner isn't smart enough to inline the test- or increment-expressions
886 // of a for loop loop at this time. There are a handful of limitations:
887 // - We would need to insert the test-expression block at the very beginning of the
888 // for-loop's inner fStatement, and the increment-expression block at the very
889 // end. We don't support that today, but it's doable.
890 // - The for-loop's built-in test-expression would need to be dropped entirely,
891 // and the loop would be halted via a break statement at the end of the inlined
892 // test-expression. This is again something we don't support today, but it could
893 // be implemented.
894 // - We cannot inline the increment-expression if the loop uses `continue` anywhere;
895 // that would skip over the inlined block that evaluates the increment expression.
896 // There isn't a good fix for this--any workaround would be more complex than the
897 // cost of a function call. However, loops that don't use `continue` would still
898 // be viable candidates for increment-expression inlining.
899 break;
900 }
901 case Statement::Kind::kIf: {
902 IfStatement& ifStmt = (*stmt)->as<IfStatement>();
903 this->visitExpression(&ifStmt.fTest);
904 this->visitStatement(&ifStmt.fIfTrue);
905 this->visitStatement(&ifStmt.fIfFalse);
906 break;
907 }
908 case Statement::Kind::kReturn: {
909 ReturnStatement& returnStmt = (*stmt)->as<ReturnStatement>();
910 this->visitExpression(&returnStmt.fExpression);
911 break;
912 }
913 case Statement::Kind::kSwitch: {
914 SwitchStatement& switchStmt = (*stmt)->as<SwitchStatement>();
915 if (switchStmt.fSymbols) {
916 fSymbolTableStack.push_back(switchStmt.fSymbols.get());
917 }
918
919 this->visitExpression(&switchStmt.fValue);
920 for (std::unique_ptr<SwitchCase>& switchCase : switchStmt.fCases) {
921 // The switch-case's fValue cannot be a FunctionCall; skip it.
922 for (std::unique_ptr<Statement>& caseBlock : switchCase->fStatements) {
923 this->visitStatement(&caseBlock);
924 }
925 }
926 break;
927 }
928 case Statement::Kind::kVarDeclaration: {
929 VarDeclaration& varDeclStmt = (*stmt)->as<VarDeclaration>();
930 // Don't need to scan the declaration's sizes; those are always IntLiterals.
931 this->visitExpression(&varDeclStmt.fValue);
932 break;
933 }
John Stiles70957c82020-10-02 16:42:10 -0400934 case Statement::Kind::kWhile: {
935 WhileStatement& whileStmt = (*stmt)->as<WhileStatement>();
936 // The loop body is a candidate for inlining.
937 this->visitStatement(&whileStmt.fStatement);
938 // The inliner isn't smart enough to inline the test-expression for a while loop at
939 // this time. There are two limitations:
940 // - We would need to insert the inlined-body block at the very beginning of the
941 // while loop's inner fStatement. We don't support that today, but it's doable.
942 // - The while-loop's built-in test-expression would need to be replaced with a
943 // `true` BoolLiteral, and the loop would be halted via a break statement at the
944 // end of the inlined test-expression. This is again something we don't support
945 // today, but it could be implemented.
946 break;
947 }
948 default:
949 SkUNREACHABLE;
John Stiles93442622020-09-11 12:11:27 -0400950 }
951
John Stiles70957c82020-10-02 16:42:10 -0400952 // Pop our symbol and enclosing-statement stacks.
953 fSymbolTableStack.resize(oldSymbolStackSize);
954 fEnclosingStmtStack.resize(oldEnclosingStmtStackSize);
955 }
956
957 void visitExpression(std::unique_ptr<Expression>* expr) {
958 if (!*expr) {
959 return;
John Stiles93442622020-09-11 12:11:27 -0400960 }
John Stiles70957c82020-10-02 16:42:10 -0400961
962 switch ((*expr)->kind()) {
963 case Expression::Kind::kBoolLiteral:
964 case Expression::Kind::kDefined:
965 case Expression::Kind::kExternalValue:
966 case Expression::Kind::kFieldAccess:
967 case Expression::Kind::kFloatLiteral:
968 case Expression::Kind::kFunctionReference:
969 case Expression::Kind::kIntLiteral:
970 case Expression::Kind::kNullLiteral:
971 case Expression::Kind::kSetting:
972 case Expression::Kind::kTypeReference:
973 case Expression::Kind::kVariableReference:
974 // Nothing to scan here.
975 break;
976
977 case Expression::Kind::kBinary: {
978 BinaryExpression& binaryExpr = (*expr)->as<BinaryExpression>();
979 this->visitExpression(&binaryExpr.leftPointer());
980
981 // Logical-and and logical-or binary expressions do not inline the right side,
982 // because that would invalidate short-circuiting. That is, when evaluating
983 // expressions like these:
984 // (false && x()) // always false
985 // (true || y()) // always true
986 // It is illegal for side-effects from x() or y() to occur. The simplest way to
987 // enforce that rule is to avoid inlining the right side entirely. However, it is
988 // safe for other types of binary expression to inline both sides.
989 Token::Kind op = binaryExpr.getOperator();
990 bool shortCircuitable = (op == Token::Kind::TK_LOGICALAND ||
991 op == Token::Kind::TK_LOGICALOR);
992 if (!shortCircuitable) {
993 this->visitExpression(&binaryExpr.rightPointer());
994 }
995 break;
996 }
997 case Expression::Kind::kConstructor: {
998 Constructor& constructorExpr = (*expr)->as<Constructor>();
999 for (std::unique_ptr<Expression>& arg : constructorExpr.arguments()) {
1000 this->visitExpression(&arg);
1001 }
1002 break;
1003 }
1004 case Expression::Kind::kExternalFunctionCall: {
1005 ExternalFunctionCall& funcCallExpr = (*expr)->as<ExternalFunctionCall>();
1006 for (std::unique_ptr<Expression>& arg : funcCallExpr.arguments()) {
1007 this->visitExpression(&arg);
1008 }
1009 break;
1010 }
1011 case Expression::Kind::kFunctionCall: {
1012 FunctionCall& funcCallExpr = (*expr)->as<FunctionCall>();
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001013 for (std::unique_ptr<Expression>& arg : funcCallExpr.arguments()) {
John Stiles70957c82020-10-02 16:42:10 -04001014 this->visitExpression(&arg);
1015 }
1016 this->addInlineCandidate(expr);
1017 break;
1018 }
1019 case Expression::Kind::kIndex:{
1020 IndexExpression& indexExpr = (*expr)->as<IndexExpression>();
1021 this->visitExpression(&indexExpr.fBase);
1022 this->visitExpression(&indexExpr.fIndex);
1023 break;
1024 }
1025 case Expression::Kind::kPostfix: {
1026 PostfixExpression& postfixExpr = (*expr)->as<PostfixExpression>();
1027 this->visitExpression(&postfixExpr.fOperand);
1028 break;
1029 }
1030 case Expression::Kind::kPrefix: {
1031 PrefixExpression& prefixExpr = (*expr)->as<PrefixExpression>();
1032 this->visitExpression(&prefixExpr.fOperand);
1033 break;
1034 }
1035 case Expression::Kind::kSwizzle: {
1036 Swizzle& swizzleExpr = (*expr)->as<Swizzle>();
1037 this->visitExpression(&swizzleExpr.fBase);
1038 break;
1039 }
1040 case Expression::Kind::kTernary: {
1041 TernaryExpression& ternaryExpr = (*expr)->as<TernaryExpression>();
1042 // The test expression is a candidate for inlining.
1043 this->visitExpression(&ternaryExpr.fTest);
1044 // The true- and false-expressions cannot be inlined, because we are only allowed to
1045 // evaluate one side.
1046 break;
1047 }
1048 default:
1049 SkUNREACHABLE;
1050 }
1051 }
1052
1053 void addInlineCandidate(std::unique_ptr<Expression>* candidate) {
1054 fCandidateList->fCandidates.push_back(
1055 InlineCandidate{fSymbolTableStack.back(),
1056 find_parent_statement(fEnclosingStmtStack),
1057 fEnclosingStmtStack.back(),
1058 candidate,
1059 fEnclosingFunction,
1060 /*isLargeFunction=*/false});
1061 }
John Stiles2d7973a2020-10-02 15:01:03 -04001062};
John Stiles93442622020-09-11 12:11:27 -04001063
John Stiles2d7973a2020-10-02 15:01:03 -04001064bool Inliner::candidateCanBeInlined(const InlineCandidate& candidate, InlinabilityCache* cache) {
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001065 const FunctionDeclaration& funcDecl =
1066 (*candidate.fCandidateExpr)->as<FunctionCall>().function();
John Stiles915a38c2020-09-14 09:38:13 -04001067
John Stiles2d7973a2020-10-02 15:01:03 -04001068 auto [iter, wasInserted] = cache->insert({&funcDecl, false});
1069 if (wasInserted) {
1070 // Recursion is forbidden here to avoid an infinite death spiral of inlining.
1071 iter->second = this->isSafeToInline(funcDecl.fDefinition) &&
1072 !contains_recursive_call(funcDecl);
John Stiles93442622020-09-11 12:11:27 -04001073 }
1074
John Stiles2d7973a2020-10-02 15:01:03 -04001075 return iter->second;
1076}
1077
1078bool Inliner::isLargeFunction(const FunctionDefinition* functionDef) {
1079 return Analysis::NodeCountExceeds(*functionDef, fSettings->fInlineThreshold);
1080}
1081
1082bool Inliner::isLargeFunction(const InlineCandidate& candidate, LargeFunctionCache* cache) {
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001083 const FunctionDeclaration& funcDecl =
1084 (*candidate.fCandidateExpr)->as<FunctionCall>().function();
John Stiles2d7973a2020-10-02 15:01:03 -04001085
1086 auto [iter, wasInserted] = cache->insert({&funcDecl, false});
1087 if (wasInserted) {
1088 iter->second = this->isLargeFunction(funcDecl.fDefinition);
1089 }
1090
1091 return iter->second;
1092}
1093
1094void Inliner::buildCandidateList(Program& program, InlineCandidateList* candidateList) {
1095 // This is structured much like a ProgramVisitor, but does not actually use ProgramVisitor.
1096 // The analyzer needs to keep track of the `unique_ptr<T>*` of statements and expressions so
1097 // that they can later be replaced, and ProgramVisitor does not provide this; it only provides a
1098 // `const T&`.
1099 InlineCandidateAnalyzer analyzer;
1100 analyzer.visit(program, candidateList);
1101
1102 // Remove candidates that are not safe to inline.
1103 std::vector<InlineCandidate>& candidates = candidateList->fCandidates;
1104 InlinabilityCache cache;
1105 candidates.erase(std::remove_if(candidates.begin(),
1106 candidates.end(),
1107 [&](const InlineCandidate& candidate) {
1108 return !this->candidateCanBeInlined(candidate, &cache);
1109 }),
1110 candidates.end());
1111
1112 // Determine whether each candidate function exceeds our inlining size threshold or not. These
1113 // can still be valid candidates if they are only called one time, so we don't remove them from
1114 // the candidate list, but they will not be inlined if they're called more than once.
1115 LargeFunctionCache largeFunctionCache;
1116 for (InlineCandidate& candidate : candidates) {
1117 candidate.fIsLargeFunction = this->isLargeFunction(candidate, &largeFunctionCache);
1118 }
1119}
1120
1121bool Inliner::analyze(Program& program) {
1122 InlineCandidateList candidateList;
1123 this->buildCandidateList(program, &candidateList);
1124
John Stiles915a38c2020-09-14 09:38:13 -04001125 // Inline the candidates where we've determined that it's safe to do so.
1126 std::unordered_set<const std::unique_ptr<Statement>*> enclosingStmtSet;
1127 bool madeChanges = false;
John Stiles2d7973a2020-10-02 15:01:03 -04001128 for (const InlineCandidate& candidate : candidateList.fCandidates) {
John Stiles915a38c2020-09-14 09:38:13 -04001129 FunctionCall& funcCall = (*candidate.fCandidateExpr)->as<FunctionCall>();
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001130 const FunctionDeclaration* funcDecl = &funcCall.function();
John Stiles915a38c2020-09-14 09:38:13 -04001131
John Stiles2d7973a2020-10-02 15:01:03 -04001132 // If the function is large, not marked `inline`, and is called more than once, it's a bad
1133 // idea to inline it.
1134 if (candidate.fIsLargeFunction &&
1135 !(funcDecl->fModifiers.fFlags & Modifiers::kInline_Flag) &&
1136 funcDecl->fCallCount.load() > 1) {
John Stiles915a38c2020-09-14 09:38:13 -04001137 continue;
1138 }
1139
1140 // Inlining two expressions using the same enclosing statement in the same inlining pass
1141 // does not work properly. If this happens, skip it; we'll get it in the next pass.
1142 auto [unusedIter, inserted] = enclosingStmtSet.insert(candidate.fEnclosingStmt);
1143 if (!inserted) {
1144 continue;
1145 }
1146
1147 // Convert the function call to its inlined equivalent.
Brian Osman3887a012020-09-30 13:22:27 -04001148 InlinedCall inlinedCall = this->inlineCall(&funcCall, candidate.fSymbols,
1149 &candidate.fEnclosingFunction->fDeclaration);
John Stiles915a38c2020-09-14 09:38:13 -04001150 if (inlinedCall.fInlinedBody) {
1151 // Ensure that the inlined body has a scope if it needs one.
John Stiles6d696082020-10-01 10:18:54 -04001152 this->ensureScopedBlocks(inlinedCall.fInlinedBody.get(), candidate.fParentStmt->get());
John Stiles915a38c2020-09-14 09:38:13 -04001153
1154 // Move the enclosing statement to the end of the unscoped Block containing the inlined
1155 // function, then replace the enclosing statement with that Block.
1156 // Before:
1157 // fInlinedBody = Block{ stmt1, stmt2, stmt3 }
1158 // fEnclosingStmt = stmt4
1159 // After:
1160 // fInlinedBody = null
1161 // fEnclosingStmt = Block{ stmt1, stmt2, stmt3, stmt4 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001162 inlinedCall.fInlinedBody->children().push_back(std::move(*candidate.fEnclosingStmt));
John Stiles915a38c2020-09-14 09:38:13 -04001163 *candidate.fEnclosingStmt = std::move(inlinedCall.fInlinedBody);
1164 }
1165
1166 // Replace the candidate function call with our replacement expression.
1167 *candidate.fCandidateExpr = std::move(inlinedCall.fReplacementExpr);
1168 madeChanges = true;
1169
1170 // Note that nothing was destroyed except for the FunctionCall. All other nodes should
1171 // remain valid.
1172 }
1173
1174 return madeChanges;
John Stiles93442622020-09-11 12:11:27 -04001175}
1176
John Stiles44e96be2020-08-31 13:16:04 -04001177} // namespace SkSL