blob: 470fa8f1039abd20d2002f183ea5bb0dc1422dac [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
10#include "limits.h"
11#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"
52#include "src/sksl/ir/SkSLVarDeclarationsStatement.h"
53#include "src/sksl/ir/SkSLVariable.h"
54#include "src/sksl/ir/SkSLVariableReference.h"
55#include "src/sksl/ir/SkSLWhileStatement.h"
56
57namespace SkSL {
58namespace {
59
John Stiles44dff4f2020-09-21 12:28:01 -040060static bool contains_returns_above_limit(const FunctionDefinition& funcDef, int limit) {
61 class CountReturnsWithLimit : public ProgramVisitor {
John Stiles44e96be2020-08-31 13:16:04 -040062 public:
John Stiles44dff4f2020-09-21 12:28:01 -040063 CountReturnsWithLimit(const FunctionDefinition& funcDef, int limit) : fLimit(limit) {
John Stiles44e96be2020-08-31 13:16:04 -040064 this->visitProgramElement(funcDef);
65 }
66
67 bool visitStatement(const Statement& stmt) override {
Ethan Nicholase6592142020-09-08 10:22:09 -040068 switch (stmt.kind()) {
69 case Statement::Kind::kReturn:
John Stiles44e96be2020-08-31 13:16:04 -040070 ++fNumReturns;
John Stiles44dff4f2020-09-21 12:28:01 -040071 return (fNumReturns > fLimit) || INHERITED::visitStatement(stmt);
John Stiles44e96be2020-08-31 13:16:04 -040072
73 default:
John Stiles93442622020-09-11 12:11:27 -040074 return INHERITED::visitStatement(stmt);
John Stiles44e96be2020-08-31 13:16:04 -040075 }
76 }
77
78 int fNumReturns = 0;
John Stiles44dff4f2020-09-21 12:28:01 -040079 int fLimit = 0;
John Stiles44e96be2020-08-31 13:16:04 -040080 using INHERITED = ProgramVisitor;
81 };
82
John Stiles44dff4f2020-09-21 12:28:01 -040083 return CountReturnsWithLimit{funcDef, limit}.fNumReturns > limit;
John Stiles44e96be2020-08-31 13:16:04 -040084}
85
86static int count_returns_at_end_of_control_flow(const FunctionDefinition& funcDef) {
87 class CountReturnsAtEndOfControlFlow : public ProgramVisitor {
88 public:
89 CountReturnsAtEndOfControlFlow(const FunctionDefinition& funcDef) {
90 this->visitProgramElement(funcDef);
91 }
92
93 bool visitStatement(const Statement& stmt) override {
Ethan Nicholase6592142020-09-08 10:22:09 -040094 switch (stmt.kind()) {
95 case Statement::Kind::kBlock: {
John Stiles44e96be2020-08-31 13:16:04 -040096 // Check only the last statement of a block.
Ethan Nicholas7bd60432020-09-25 14:31:59 -040097 const auto& block = stmt.as<Block>();
98 return block.children().size() &&
99 this->visitStatement(*block.children().back());
John Stiles44e96be2020-08-31 13:16:04 -0400100 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400101 case Statement::Kind::kSwitch:
102 case Statement::Kind::kWhile:
103 case Statement::Kind::kDo:
104 case Statement::Kind::kFor:
John Stiles44e96be2020-08-31 13:16:04 -0400105 // Don't introspect switches or loop structures at all.
106 return false;
107
Ethan Nicholase6592142020-09-08 10:22:09 -0400108 case Statement::Kind::kReturn:
John Stiles44e96be2020-08-31 13:16:04 -0400109 ++fNumReturns;
110 [[fallthrough]];
111
112 default:
John Stiles93442622020-09-11 12:11:27 -0400113 return INHERITED::visitStatement(stmt);
John Stiles44e96be2020-08-31 13:16:04 -0400114 }
115 }
116
117 int fNumReturns = 0;
118 using INHERITED = ProgramVisitor;
119 };
120
121 return CountReturnsAtEndOfControlFlow{funcDef}.fNumReturns;
122}
123
124static int count_returns_in_breakable_constructs(const FunctionDefinition& funcDef) {
125 class CountReturnsInBreakableConstructs : public ProgramVisitor {
126 public:
127 CountReturnsInBreakableConstructs(const FunctionDefinition& funcDef) {
128 this->visitProgramElement(funcDef);
129 }
130
131 bool visitStatement(const Statement& stmt) override {
Ethan Nicholase6592142020-09-08 10:22:09 -0400132 switch (stmt.kind()) {
133 case Statement::Kind::kSwitch:
134 case Statement::Kind::kWhile:
135 case Statement::Kind::kDo:
136 case Statement::Kind::kFor: {
John Stiles44e96be2020-08-31 13:16:04 -0400137 ++fInsideBreakableConstruct;
John Stiles93442622020-09-11 12:11:27 -0400138 bool result = INHERITED::visitStatement(stmt);
John Stiles44e96be2020-08-31 13:16:04 -0400139 --fInsideBreakableConstruct;
140 return result;
141 }
142
Ethan Nicholase6592142020-09-08 10:22:09 -0400143 case Statement::Kind::kReturn:
John Stiles44e96be2020-08-31 13:16:04 -0400144 fNumReturns += (fInsideBreakableConstruct > 0) ? 1 : 0;
145 [[fallthrough]];
146
147 default:
John Stiles93442622020-09-11 12:11:27 -0400148 return INHERITED::visitStatement(stmt);
John Stiles44e96be2020-08-31 13:16:04 -0400149 }
150 }
151
152 int fNumReturns = 0;
153 int fInsideBreakableConstruct = 0;
154 using INHERITED = ProgramVisitor;
155 };
156
157 return CountReturnsInBreakableConstructs{funcDef}.fNumReturns;
158}
159
160static bool has_early_return(const FunctionDefinition& funcDef) {
John Stiles44e96be2020-08-31 13:16:04 -0400161 int returnsAtEndOfControlFlow = count_returns_at_end_of_control_flow(funcDef);
John Stiles44dff4f2020-09-21 12:28:01 -0400162 return contains_returns_above_limit(funcDef, returnsAtEndOfControlFlow);
John Stiles44e96be2020-08-31 13:16:04 -0400163}
164
John Stiles991b09d2020-09-10 13:33:40 -0400165static bool contains_recursive_call(const FunctionDeclaration& funcDecl) {
166 class ContainsRecursiveCall : public ProgramVisitor {
167 public:
168 bool visit(const FunctionDeclaration& funcDecl) {
169 fFuncDecl = &funcDecl;
170 return funcDecl.fDefinition ? this->visitProgramElement(*funcDecl.fDefinition)
171 : false;
172 }
173
174 bool visitExpression(const Expression& expr) override {
175 if (expr.is<FunctionCall>() && expr.as<FunctionCall>().fFunction.matches(*fFuncDecl)) {
176 return true;
177 }
178 return INHERITED::visitExpression(expr);
179 }
180
181 bool visitStatement(const Statement& stmt) override {
182 if (stmt.is<InlineMarker>() && stmt.as<InlineMarker>().fFuncDecl->matches(*fFuncDecl)) {
183 return true;
184 }
185 return INHERITED::visitStatement(stmt);
186 }
187
188 const FunctionDeclaration* fFuncDecl;
189 using INHERITED = ProgramVisitor;
190 };
191
192 return ContainsRecursiveCall{}.visit(funcDecl);
193}
194
John Stiles44e96be2020-08-31 13:16:04 -0400195static const Type* copy_if_needed(const Type* src, SymbolTable& symbolTable) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400196 if (src->typeKind() == Type::TypeKind::kArray) {
John Stiles44e96be2020-08-31 13:16:04 -0400197 return symbolTable.takeOwnershipOfSymbol(std::make_unique<Type>(*src));
198 }
199 return src;
200}
201
John Stiles915a38c2020-09-14 09:38:13 -0400202static Statement* find_parent_statement(const std::vector<std::unique_ptr<Statement>*>& stmtStack) {
203 SkASSERT(!stmtStack.empty());
204
205 // Walk the statement stack from back to front, ignoring the last element (which is the
206 // enclosing statement).
207 auto iter = stmtStack.rbegin();
208 ++iter;
209
210 // Anything counts as a parent statement other than a scopeless Block.
211 for (; iter != stmtStack.rend(); ++iter) {
212 Statement* stmt = (*iter)->get();
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400213 if (!stmt->is<Block>() || stmt->as<Block>().isScope()) {
John Stiles915a38c2020-09-14 09:38:13 -0400214 return stmt;
215 }
216 }
217
218 // There wasn't any parent statement to be found.
219 return nullptr;
220}
221
John Stilese41b4ee2020-09-28 12:28:16 -0400222std::unique_ptr<Expression> clone_with_ref_kind(const Expression& expr,
223 VariableReference::RefKind refKind) {
224 std::unique_ptr<Expression> clone = expr.clone();
John Stiles70b82422020-09-30 10:55:12 -0400225 class SetRefKindInExpression : public ProgramWriter {
John Stilese41b4ee2020-09-28 12:28:16 -0400226 public:
227 SetRefKindInExpression(VariableReference::RefKind refKind) : fRefKind(refKind) {}
John Stiles70b82422020-09-30 10:55:12 -0400228 bool visitExpression(Expression& expr) override {
John Stilese41b4ee2020-09-28 12:28:16 -0400229 if (expr.is<VariableReference>()) {
John Stiles70b82422020-09-30 10:55:12 -0400230 expr.as<VariableReference>().setRefKind(fRefKind);
John Stilese41b4ee2020-09-28 12:28:16 -0400231 }
232 return INHERITED::visitExpression(expr);
233 }
234
235 private:
236 VariableReference::RefKind fRefKind;
237
John Stiles70b82422020-09-30 10:55:12 -0400238 using INHERITED = ProgramWriter;
John Stilese41b4ee2020-09-28 12:28:16 -0400239 };
240
241 SetRefKindInExpression{refKind}.visitExpression(*clone);
242 return clone;
243}
244
John Stiles44733aa2020-09-29 17:42:23 -0400245bool is_trivial_argument(const Expression& argument) {
246 return argument.is<VariableReference>() ||
247 (argument.is<Swizzle>() && is_trivial_argument(*argument.as<Swizzle>().fBase)) ||
248 (argument.is<FieldAccess>() && is_trivial_argument(*argument.as<FieldAccess>().fBase)) ||
John Stiles80ccdbd2020-09-30 11:58:16 -0400249 (argument.is<Constructor>() &&
250 argument.as<Constructor>().arguments().size() == 1 &&
251 is_trivial_argument(*argument.as<Constructor>().arguments().front())) ||
John Stiles44733aa2020-09-29 17:42:23 -0400252 (argument.is<IndexExpression>() &&
253 argument.as<IndexExpression>().fIndex->is<IntLiteral>() &&
254 is_trivial_argument(*argument.as<IndexExpression>().fBase));
255}
256
John Stiles44e96be2020-08-31 13:16:04 -0400257} // namespace
258
John Stilesb61ee902020-09-21 12:26:59 -0400259void Inliner::ensureScopedBlocks(Statement* inlinedBody, Statement* parentStmt) {
260 // No changes necessary if this statement isn't actually a block.
261 if (!inlinedBody || !inlinedBody->is<Block>()) {
262 return;
263 }
264
265 // No changes necessary if the parent statement doesn't require a scope.
266 if (!parentStmt || !(parentStmt->is<IfStatement>() || parentStmt->is<ForStatement>() ||
267 parentStmt->is<DoStatement>() || parentStmt->is<WhileStatement>())) {
268 return;
269 }
270
271 Block& block = inlinedBody->as<Block>();
272
273 // The inliner will create inlined function bodies as a Block containing multiple statements,
274 // but no scope. Normally, this is fine, but if this block is used as the statement for a
275 // do/for/if/while, this isn't actually possible to represent textually; a scope must be added
276 // for the generated code to match the intent. In the case of Blocks nested inside other Blocks,
277 // we add the scope to the outermost block if needed. Zero-statement blocks have similar
278 // issues--if we don't represent the Block textually somehow, we run the risk of accidentally
279 // absorbing the following statement into our loop--so we also add a scope to these.
280 for (Block* nestedBlock = &block;; ) {
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400281 if (nestedBlock->isScope()) {
John Stilesb61ee902020-09-21 12:26:59 -0400282 // We found an explicit scope; all is well.
283 return;
284 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400285 if (nestedBlock->children().size() != 1) {
John Stilesb61ee902020-09-21 12:26:59 -0400286 // We found a block with multiple (or zero) statements, but no scope? Let's add a scope
287 // to the outermost block.
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400288 block.setIsScope(true);
John Stilesb61ee902020-09-21 12:26:59 -0400289 return;
290 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400291 if (!nestedBlock->children()[0]->is<Block>()) {
John Stilesb61ee902020-09-21 12:26:59 -0400292 // This block has exactly one thing inside, and it's not another block. No need to scope
293 // it.
294 return;
295 }
296 // We have to go deeper.
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400297 nestedBlock = &nestedBlock->children()[0]->as<Block>();
John Stilesb61ee902020-09-21 12:26:59 -0400298 }
299}
300
John Stiles44e96be2020-08-31 13:16:04 -0400301void Inliner::reset(const Context& context, const Program::Settings& settings) {
302 fContext = &context;
303 fSettings = &settings;
304 fInlineVarCounter = 0;
305}
306
John Stilesc75abb82020-09-14 18:24:12 -0400307String Inliner::uniqueNameForInlineVar(const String& baseName, SymbolTable* symbolTable) {
308 // If the base name starts with an underscore, like "_coords", we can't append another
309 // underscore, because OpenGL disallows two consecutive underscores anywhere in the string. But
310 // in the general case, using the underscore as a splitter reads nicely enough that it's worth
311 // putting in this special case.
312 const char* splitter = baseName.startsWith("_") ? "" : "_";
313
314 // Append a unique numeric prefix to avoid name overlap. Check the symbol table to make sure
315 // we're not reusing an existing name. (Note that within a single compilation pass, this check
316 // isn't fully comprehensive, as code isn't always generated in top-to-bottom order.)
317 String uniqueName;
318 for (;;) {
319 uniqueName = String::printf("_%d%s%s", fInlineVarCounter++, splitter, baseName.c_str());
320 StringFragment frag{uniqueName.data(), uniqueName.length()};
321 if ((*symbolTable)[frag] == nullptr) {
322 break;
323 }
324 }
325
326 return uniqueName;
327}
328
John Stiles44e96be2020-08-31 13:16:04 -0400329std::unique_ptr<Expression> Inliner::inlineExpression(int offset,
330 VariableRewriteMap* varMap,
331 const Expression& expression) {
332 auto expr = [&](const std::unique_ptr<Expression>& e) -> std::unique_ptr<Expression> {
333 if (e) {
334 return this->inlineExpression(offset, varMap, *e);
335 }
336 return nullptr;
337 };
338 auto argList = [&](const std::vector<std::unique_ptr<Expression>>& originalArgs)
339 -> std::vector<std::unique_ptr<Expression>> {
340 std::vector<std::unique_ptr<Expression>> args;
341 args.reserve(originalArgs.size());
342 for (const std::unique_ptr<Expression>& arg : originalArgs) {
343 args.push_back(expr(arg));
344 }
345 return args;
346 };
347
Ethan Nicholase6592142020-09-08 10:22:09 -0400348 switch (expression.kind()) {
349 case Expression::Kind::kBinary: {
John Stiles44e96be2020-08-31 13:16:04 -0400350 const BinaryExpression& b = expression.as<BinaryExpression>();
351 return std::make_unique<BinaryExpression>(offset,
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400352 expr(b.leftPointer()),
353 b.getOperator(),
354 expr(b.rightPointer()),
Ethan Nicholas30d30222020-09-11 12:27:26 -0400355 &b.type());
John Stiles44e96be2020-08-31 13:16:04 -0400356 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400357 case Expression::Kind::kBoolLiteral:
358 case Expression::Kind::kIntLiteral:
359 case Expression::Kind::kFloatLiteral:
360 case Expression::Kind::kNullLiteral:
John Stiles44e96be2020-08-31 13:16:04 -0400361 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400362 case Expression::Kind::kConstructor: {
John Stiles44e96be2020-08-31 13:16:04 -0400363 const Constructor& constructor = expression.as<Constructor>();
Ethan Nicholas30d30222020-09-11 12:27:26 -0400364 return std::make_unique<Constructor>(offset, &constructor.type(),
Ethan Nicholasf70f0442020-09-29 12:41:35 -0400365 argList(constructor.arguments()));
John Stiles44e96be2020-08-31 13:16:04 -0400366 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400367 case Expression::Kind::kExternalFunctionCall: {
John Stiles44e96be2020-08-31 13:16:04 -0400368 const ExternalFunctionCall& externalCall = expression.as<ExternalFunctionCall>();
Ethan Nicholas30d30222020-09-11 12:27:26 -0400369 return std::make_unique<ExternalFunctionCall>(offset, &externalCall.type(),
John Stiles44e96be2020-08-31 13:16:04 -0400370 externalCall.fFunction,
371 argList(externalCall.fArguments));
372 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400373 case Expression::Kind::kExternalValue:
John Stiles44e96be2020-08-31 13:16:04 -0400374 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400375 case Expression::Kind::kFieldAccess: {
John Stiles44e96be2020-08-31 13:16:04 -0400376 const FieldAccess& f = expression.as<FieldAccess>();
377 return std::make_unique<FieldAccess>(expr(f.fBase), f.fFieldIndex, f.fOwnerKind);
378 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400379 case Expression::Kind::kFunctionCall: {
John Stiles44e96be2020-08-31 13:16:04 -0400380 const FunctionCall& funcCall = expression.as<FunctionCall>();
Ethan Nicholas30d30222020-09-11 12:27:26 -0400381 return std::make_unique<FunctionCall>(offset, &funcCall.type(), funcCall.fFunction,
John Stiles44e96be2020-08-31 13:16:04 -0400382 argList(funcCall.fArguments));
383 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400384 case Expression::Kind::kFunctionReference:
Brian Osman2b3b35f2020-09-08 09:17:36 -0400385 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400386 case Expression::Kind::kIndex: {
John Stiles44e96be2020-08-31 13:16:04 -0400387 const IndexExpression& idx = expression.as<IndexExpression>();
388 return std::make_unique<IndexExpression>(*fContext, expr(idx.fBase), expr(idx.fIndex));
389 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400390 case Expression::Kind::kPrefix: {
John Stiles44e96be2020-08-31 13:16:04 -0400391 const PrefixExpression& p = expression.as<PrefixExpression>();
392 return std::make_unique<PrefixExpression>(p.fOperator, expr(p.fOperand));
393 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400394 case Expression::Kind::kPostfix: {
John Stiles44e96be2020-08-31 13:16:04 -0400395 const PostfixExpression& p = expression.as<PostfixExpression>();
396 return std::make_unique<PostfixExpression>(expr(p.fOperand), p.fOperator);
397 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400398 case Expression::Kind::kSetting:
John Stiles44e96be2020-08-31 13:16:04 -0400399 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400400 case Expression::Kind::kSwizzle: {
John Stiles44e96be2020-08-31 13:16:04 -0400401 const Swizzle& s = expression.as<Swizzle>();
402 return std::make_unique<Swizzle>(*fContext, expr(s.fBase), s.fComponents);
403 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400404 case Expression::Kind::kTernary: {
John Stiles44e96be2020-08-31 13:16:04 -0400405 const TernaryExpression& t = expression.as<TernaryExpression>();
406 return std::make_unique<TernaryExpression>(offset, expr(t.fTest),
407 expr(t.fIfTrue), expr(t.fIfFalse));
408 }
Brian Osman83ba9302020-09-11 13:33:46 -0400409 case Expression::Kind::kTypeReference:
410 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400411 case Expression::Kind::kVariableReference: {
John Stiles44e96be2020-08-31 13:16:04 -0400412 const VariableReference& v = expression.as<VariableReference>();
John Stilese41b4ee2020-09-28 12:28:16 -0400413 auto varMapIter = varMap->find(v.fVariable);
414 if (varMapIter != varMap->end()) {
415 return clone_with_ref_kind(*varMapIter->second, v.fRefKind);
John Stiles44e96be2020-08-31 13:16:04 -0400416 }
417 return v.clone();
418 }
419 default:
420 SkASSERT(false);
421 return nullptr;
422 }
423}
424
425std::unique_ptr<Statement> Inliner::inlineStatement(int offset,
426 VariableRewriteMap* varMap,
427 SymbolTable* symbolTableForStatement,
John Stilese41b4ee2020-09-28 12:28:16 -0400428 const Expression* resultExpr,
John Stiles44e96be2020-08-31 13:16:04 -0400429 bool haveEarlyReturns,
430 const Statement& statement) {
431 auto stmt = [&](const std::unique_ptr<Statement>& s) -> std::unique_ptr<Statement> {
432 if (s) {
John Stilesa5f3c312020-09-22 12:05:16 -0400433 return this->inlineStatement(offset, varMap, symbolTableForStatement, resultExpr,
John Stiles44e96be2020-08-31 13:16:04 -0400434 haveEarlyReturns, *s);
435 }
436 return nullptr;
437 };
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400438 auto blockStmts = [&](const Block& block) {
439 std::vector<std::unique_ptr<Statement>> result;
440 for (const std::unique_ptr<Statement>& child : block.children()) {
441 result.push_back(stmt(child));
442 }
443 return result;
444 };
John Stiles44e96be2020-08-31 13:16:04 -0400445 auto stmts = [&](const std::vector<std::unique_ptr<Statement>>& ss) {
446 std::vector<std::unique_ptr<Statement>> result;
447 for (const auto& s : ss) {
448 result.push_back(stmt(s));
449 }
450 return result;
451 };
452 auto expr = [&](const std::unique_ptr<Expression>& e) -> std::unique_ptr<Expression> {
453 if (e) {
454 return this->inlineExpression(offset, varMap, *e);
455 }
456 return nullptr;
457 };
Ethan Nicholase6592142020-09-08 10:22:09 -0400458 switch (statement.kind()) {
459 case Statement::Kind::kBlock: {
John Stiles44e96be2020-08-31 13:16:04 -0400460 const Block& b = statement.as<Block>();
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400461 return std::make_unique<Block>(offset, blockStmts(b), b.symbolTable(), b.isScope());
John Stiles44e96be2020-08-31 13:16:04 -0400462 }
463
Ethan Nicholase6592142020-09-08 10:22:09 -0400464 case Statement::Kind::kBreak:
465 case Statement::Kind::kContinue:
466 case Statement::Kind::kDiscard:
John Stiles44e96be2020-08-31 13:16:04 -0400467 return statement.clone();
468
Ethan Nicholase6592142020-09-08 10:22:09 -0400469 case Statement::Kind::kDo: {
John Stiles44e96be2020-08-31 13:16:04 -0400470 const DoStatement& d = statement.as<DoStatement>();
Ethan Nicholas1fd61162020-09-28 13:14:19 -0400471 return std::make_unique<DoStatement>(offset, stmt(d.statement()), expr(d.test()));
John Stiles44e96be2020-08-31 13:16:04 -0400472 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400473 case Statement::Kind::kExpression: {
John Stiles44e96be2020-08-31 13:16:04 -0400474 const ExpressionStatement& e = statement.as<ExpressionStatement>();
Ethan Nicholasd503a5a2020-09-30 09:29:55 -0400475 return std::make_unique<ExpressionStatement>(expr(e.expression()));
John Stiles44e96be2020-08-31 13:16:04 -0400476 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400477 case Statement::Kind::kFor: {
John Stiles44e96be2020-08-31 13:16:04 -0400478 const ForStatement& f = statement.as<ForStatement>();
479 // need to ensure initializer is evaluated first so that we've already remapped its
480 // declarations by the time we evaluate test & next
481 std::unique_ptr<Statement> initializer = stmt(f.fInitializer);
482 return std::make_unique<ForStatement>(offset, std::move(initializer), expr(f.fTest),
483 expr(f.fNext), stmt(f.fStatement), f.fSymbols);
484 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400485 case Statement::Kind::kIf: {
John Stiles44e96be2020-08-31 13:16:04 -0400486 const IfStatement& i = statement.as<IfStatement>();
487 return std::make_unique<IfStatement>(offset, i.fIsStatic, expr(i.fTest),
488 stmt(i.fIfTrue), stmt(i.fIfFalse));
489 }
John Stiles98c1f822020-09-09 14:18:53 -0400490 case Statement::Kind::kInlineMarker:
Ethan Nicholase6592142020-09-08 10:22:09 -0400491 case Statement::Kind::kNop:
John Stiles44e96be2020-08-31 13:16:04 -0400492 return statement.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400493 case Statement::Kind::kReturn: {
John Stiles44e96be2020-08-31 13:16:04 -0400494 const ReturnStatement& r = statement.as<ReturnStatement>();
495 if (r.fExpression) {
John Stilese41b4ee2020-09-28 12:28:16 -0400496 SkASSERT(resultExpr);
John Stilesa5f3c312020-09-22 12:05:16 -0400497 auto assignment =
498 std::make_unique<ExpressionStatement>(std::make_unique<BinaryExpression>(
499 offset,
John Stilese41b4ee2020-09-28 12:28:16 -0400500 clone_with_ref_kind(*resultExpr, VariableReference::kWrite_RefKind),
John Stilesa5f3c312020-09-22 12:05:16 -0400501 Token::Kind::TK_EQ,
502 expr(r.fExpression),
John Stilese41b4ee2020-09-28 12:28:16 -0400503 &resultExpr->type()));
John Stiles44e96be2020-08-31 13:16:04 -0400504 if (haveEarlyReturns) {
505 std::vector<std::unique_ptr<Statement>> block;
506 block.push_back(std::move(assignment));
507 block.emplace_back(new BreakStatement(offset));
508 return std::make_unique<Block>(offset, std::move(block), /*symbols=*/nullptr,
509 /*isScope=*/true);
510 } else {
511 return std::move(assignment);
512 }
513 } else {
514 if (haveEarlyReturns) {
515 return std::make_unique<BreakStatement>(offset);
516 } else {
517 return std::make_unique<Nop>();
518 }
519 }
520 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400521 case Statement::Kind::kSwitch: {
John Stiles44e96be2020-08-31 13:16:04 -0400522 const SwitchStatement& ss = statement.as<SwitchStatement>();
523 std::vector<std::unique_ptr<SwitchCase>> cases;
524 for (const auto& sc : ss.fCases) {
525 cases.emplace_back(new SwitchCase(offset, expr(sc->fValue),
526 stmts(sc->fStatements)));
527 }
528 return std::make_unique<SwitchStatement>(offset, ss.fIsStatic, expr(ss.fValue),
529 std::move(cases), ss.fSymbols);
530 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400531 case Statement::Kind::kVarDeclaration: {
John Stiles44e96be2020-08-31 13:16:04 -0400532 const VarDeclaration& decl = statement.as<VarDeclaration>();
533 std::vector<std::unique_ptr<Expression>> sizes;
534 for (const auto& size : decl.fSizes) {
535 sizes.push_back(expr(size));
536 }
537 std::unique_ptr<Expression> initialValue = expr(decl.fValue);
538 const Variable* old = decl.fVar;
John Stilesc75abb82020-09-14 18:24:12 -0400539 // We assign unique names to inlined variables--scopes hide most of the problems in this
540 // regard, but see `InlinerAvoidsVariableNameOverlap` for a counterexample where unique
541 // names are important.
542 auto name = std::make_unique<String>(
543 this->uniqueNameForInlineVar(String(old->fName), symbolTableForStatement));
John Stiles44e96be2020-08-31 13:16:04 -0400544 const String* namePtr = symbolTableForStatement->takeOwnershipOfString(std::move(name));
Ethan Nicholas30d30222020-09-11 12:27:26 -0400545 const Type* typePtr = copy_if_needed(&old->type(), *symbolTableForStatement);
John Stiles44e96be2020-08-31 13:16:04 -0400546 const Variable* clone = symbolTableForStatement->takeOwnershipOfSymbol(
547 std::make_unique<Variable>(offset,
548 old->fModifiers,
549 namePtr->c_str(),
Ethan Nicholas30d30222020-09-11 12:27:26 -0400550 typePtr,
John Stiles44e96be2020-08-31 13:16:04 -0400551 old->fStorage,
552 initialValue.get()));
John Stilese41b4ee2020-09-28 12:28:16 -0400553 (*varMap)[old] = std::make_unique<VariableReference>(offset, clone);
John Stiles44e96be2020-08-31 13:16:04 -0400554 return std::make_unique<VarDeclaration>(clone, std::move(sizes),
555 std::move(initialValue));
556 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400557 case Statement::Kind::kVarDeclarations: {
John Stiles44e96be2020-08-31 13:16:04 -0400558 const VarDeclarations& decls = *statement.as<VarDeclarationsStatement>().fDeclaration;
559 std::vector<std::unique_ptr<VarDeclaration>> vars;
560 for (const auto& var : decls.fVars) {
561 vars.emplace_back(&stmt(var).release()->as<VarDeclaration>());
562 }
563 const Type* typePtr = copy_if_needed(&decls.fBaseType, *symbolTableForStatement);
564 return std::unique_ptr<Statement>(new VarDeclarationsStatement(
565 std::make_unique<VarDeclarations>(offset, typePtr, std::move(vars))));
566 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400567 case Statement::Kind::kWhile: {
John Stiles44e96be2020-08-31 13:16:04 -0400568 const WhileStatement& w = statement.as<WhileStatement>();
569 return std::make_unique<WhileStatement>(offset, expr(w.fTest), stmt(w.fStatement));
570 }
571 default:
572 SkASSERT(false);
573 return nullptr;
574 }
575}
576
John Stiles6eadf132020-09-08 10:16:10 -0400577Inliner::InlinedCall Inliner::inlineCall(FunctionCall* call,
John Stiles44e96be2020-08-31 13:16:04 -0400578 SymbolTable* symbolTableForCall) {
579 // Inlining is more complicated here than in a typical compiler, because we have to have a
580 // high-level IR and can't just drop statements into the middle of an expression or even use
581 // gotos.
582 //
583 // Since we can't insert statements into an expression, we run the inline function as extra
584 // statements before the statement we're currently processing, relying on a lack of execution
585 // order guarantees. Since we can't use gotos (which are normally used to replace return
586 // statements), we wrap the whole function in a loop and use break statements to jump to the
587 // end.
588 SkASSERT(fSettings);
589 SkASSERT(fContext);
590 SkASSERT(call);
591 SkASSERT(this->isSafeToInline(*call, /*inlineThreshold=*/INT_MAX));
592
John Stiles44e96be2020-08-31 13:16:04 -0400593 std::vector<std::unique_ptr<Expression>>& arguments = call->fArguments;
John Stiles6eadf132020-09-08 10:16:10 -0400594 const int offset = call->fOffset;
John Stiles44e96be2020-08-31 13:16:04 -0400595 const FunctionDefinition& function = *call->fFunction.fDefinition;
John Stiles6eadf132020-09-08 10:16:10 -0400596 const bool hasEarlyReturn = has_early_return(function);
597
John Stiles44e96be2020-08-31 13:16:04 -0400598 InlinedCall inlinedCall;
John Stiles6eadf132020-09-08 10:16:10 -0400599 inlinedCall.fInlinedBody = std::make_unique<Block>(offset,
600 std::vector<std::unique_ptr<Statement>>{},
601 /*symbols=*/nullptr,
602 /*isScope=*/false);
John Stiles98c1f822020-09-09 14:18:53 -0400603
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400604 Block& inlinedBody = *inlinedCall.fInlinedBody;
605 inlinedBody.children().reserve(1 + // Inline marker
606 1 + // Result variable
607 arguments.size() + // Function arguments (passing in)
John Stilese41b4ee2020-09-28 12:28:16 -0400608 arguments.size() + // Function arguments (copy out-params back)
609 1); // Inlined code (Block or do-while loop)
John Stiles98c1f822020-09-09 14:18:53 -0400610
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400611 inlinedBody.children().push_back(std::make_unique<InlineMarker>(call->fFunction));
John Stiles44e96be2020-08-31 13:16:04 -0400612
John Stilese41b4ee2020-09-28 12:28:16 -0400613 auto makeInlineVar =
614 [&](const String& baseName, const Type* type, Modifiers modifiers,
615 std::unique_ptr<Expression>* initialValue) -> std::unique_ptr<Expression> {
John Stilesa003e812020-09-11 09:43:49 -0400616 // $floatLiteral or $intLiteral aren't real types that we can use for scratch variables, so
617 // replace them if they ever appear here. If this happens, we likely forgot to coerce a type
618 // somewhere during compilation.
619 if (type == fContext->fFloatLiteral_Type.get()) {
John Stilesd2be5c52020-09-11 14:58:06 -0400620 SkDEBUGFAIL("found a $floatLiteral type while inlining");
John Stilesa003e812020-09-11 09:43:49 -0400621 type = fContext->fFloat_Type.get();
622 } else if (type == fContext->fIntLiteral_Type.get()) {
John Stilesd2be5c52020-09-11 14:58:06 -0400623 SkDEBUGFAIL("found an $intLiteral type while inlining");
John Stilesa003e812020-09-11 09:43:49 -0400624 type = fContext->fInt_Type.get();
625 }
626
John Stilesc75abb82020-09-14 18:24:12 -0400627 // Provide our new variable with a unique name, and add it to our symbol table.
628 String uniqueName = this->uniqueNameForInlineVar(baseName, symbolTableForCall);
John Stilescf936f92020-08-31 17:18:45 -0400629 const String* namePtr = symbolTableForCall->takeOwnershipOfString(
630 std::make_unique<String>(std::move(uniqueName)));
John Stiles44e96be2020-08-31 13:16:04 -0400631 StringFragment nameFrag{namePtr->c_str(), namePtr->length()};
632
633 // Add our new variable to the symbol table.
Ethan Nicholas30d30222020-09-11 12:27:26 -0400634 auto newVar = std::make_unique<Variable>(/*offset=*/-1, Modifiers(), nameFrag, type,
John Stiles44e96be2020-08-31 13:16:04 -0400635 Variable::kLocal_Storage, initialValue->get());
636 const Variable* variableSymbol = symbolTableForCall->add(nameFrag, std::move(newVar));
637
638 // Prepare the variable declaration (taking extra care with `out` params to not clobber any
639 // initial value).
640 std::vector<std::unique_ptr<VarDeclaration>> variables;
641 if (initialValue && (modifiers.fFlags & Modifiers::kOut_Flag)) {
642 variables.push_back(std::make_unique<VarDeclaration>(
643 variableSymbol, /*sizes=*/std::vector<std::unique_ptr<Expression>>{},
644 (*initialValue)->clone()));
645 } else {
646 variables.push_back(std::make_unique<VarDeclaration>(
647 variableSymbol, /*sizes=*/std::vector<std::unique_ptr<Expression>>{},
648 std::move(*initialValue)));
649 }
650
651 // Add the new variable-declaration statement to our block of extra statements.
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400652 inlinedBody.children().push_back(std::make_unique<VarDeclarationsStatement>(
John Stilesa003e812020-09-11 09:43:49 -0400653 std::make_unique<VarDeclarations>(offset, type, std::move(variables))));
John Stiles44e96be2020-08-31 13:16:04 -0400654
John Stilese41b4ee2020-09-28 12:28:16 -0400655 return std::make_unique<VariableReference>(offset, variableSymbol);
John Stiles44e96be2020-08-31 13:16:04 -0400656 };
657
658 // Create a variable to hold the result in the extra statements (excepting void).
John Stilese41b4ee2020-09-28 12:28:16 -0400659 std::unique_ptr<Expression> resultExpr;
John Stiles44e96be2020-08-31 13:16:04 -0400660 if (function.fDeclaration.fReturnType != *fContext->fVoid_Type) {
John Stiles44e96be2020-08-31 13:16:04 -0400661 std::unique_ptr<Expression> noInitialValue;
John Stilese41b4ee2020-09-28 12:28:16 -0400662 resultExpr = makeInlineVar(String(function.fDeclaration.fName),
663 &function.fDeclaration.fReturnType,
664 Modifiers{}, &noInitialValue);
665 }
John Stiles44e96be2020-08-31 13:16:04 -0400666
667 // Create variables in the extra statements to hold the arguments, and assign the arguments to
668 // them.
669 VariableRewriteMap varMap;
John Stilese41b4ee2020-09-28 12:28:16 -0400670 std::vector<int> argsToCopyBack;
John Stiles44e96be2020-08-31 13:16:04 -0400671 for (int i = 0; i < (int) arguments.size(); ++i) {
672 const Variable* param = function.fDeclaration.fParameters[i];
John Stilese41b4ee2020-09-28 12:28:16 -0400673 bool isOutParam = param->fModifiers.fFlags & Modifiers::kOut_Flag;
John Stiles44e96be2020-08-31 13:16:04 -0400674
John Stiles44733aa2020-09-29 17:42:23 -0400675 // If this argument can be inlined trivially (e.g. a swizzle, or a constant array index)...
676 if (is_trivial_argument(*arguments[i])) {
John Stilese41b4ee2020-09-28 12:28:16 -0400677 // ... and it's an `out` param, or it isn't written to within the inline function...
678 if (isOutParam || !Analysis::StatementWritesToVariable(*function.fBody, *param)) {
John Stilesf201af82020-09-29 16:57:55 -0400679 // ... we don't need to copy it at all! We can just use the existing expression.
680 varMap[param] = arguments[i]->clone();
John Stiles44e96be2020-08-31 13:16:04 -0400681 continue;
682 }
683 }
684
John Stilese41b4ee2020-09-28 12:28:16 -0400685 if (isOutParam) {
686 argsToCopyBack.push_back(i);
687 }
688
Ethan Nicholas30d30222020-09-11 12:27:26 -0400689 varMap[param] = makeInlineVar(String(param->fName), &arguments[i]->type(),
690 param->fModifiers, &arguments[i]);
John Stiles44e96be2020-08-31 13:16:04 -0400691 }
692
693 const Block& body = function.fBody->as<Block>();
John Stiles44e96be2020-08-31 13:16:04 -0400694 auto inlineBlock = std::make_unique<Block>(offset, std::vector<std::unique_ptr<Statement>>{});
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400695 inlineBlock->children().reserve(body.children().size());
696 for (const std::unique_ptr<Statement>& stmt : body.children()) {
697 inlineBlock->children().push_back(this->inlineStatement(
John Stilese41b4ee2020-09-28 12:28:16 -0400698 offset, &varMap, symbolTableForCall, resultExpr.get(), hasEarlyReturn, *stmt));
John Stiles44e96be2020-08-31 13:16:04 -0400699 }
700 if (hasEarlyReturn) {
701 // Since we output to backends that don't have a goto statement (which would normally be
702 // used to perform an early return), we fake it by wrapping the function in a
703 // do { } while (false); and then use break statements to jump to the end in order to
704 // emulate a goto.
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400705 inlinedBody.children().push_back(std::make_unique<DoStatement>(
John Stiles44e96be2020-08-31 13:16:04 -0400706 /*offset=*/-1,
707 std::move(inlineBlock),
708 std::make_unique<BoolLiteral>(*fContext, offset, /*value=*/false)));
709 } else {
John Stiles6eadf132020-09-08 10:16:10 -0400710 // No early returns, so we can just dump the code in. We still need to keep the block so we
711 // don't get name conflicts with locals.
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400712 inlinedBody.children().push_back(std::move(inlineBlock));
John Stiles44e96be2020-08-31 13:16:04 -0400713 }
714
John Stilese41b4ee2020-09-28 12:28:16 -0400715 // Copy back the values of `out` parameters into their real destinations.
716 for (int i : argsToCopyBack) {
John Stiles44e96be2020-08-31 13:16:04 -0400717 const Variable* p = function.fDeclaration.fParameters[i];
John Stilese41b4ee2020-09-28 12:28:16 -0400718 SkASSERT(varMap.find(p) != varMap.end());
719 inlinedBody.children().push_back(
720 std::make_unique<ExpressionStatement>(std::make_unique<BinaryExpression>(
721 offset,
722 clone_with_ref_kind(*arguments[i], VariableReference::kWrite_RefKind),
723 Token::Kind::TK_EQ,
724 std::move(varMap[p]),
725 &arguments[i]->type())));
John Stiles44e96be2020-08-31 13:16:04 -0400726 }
727
John Stilese41b4ee2020-09-28 12:28:16 -0400728 if (resultExpr != nullptr) {
729 // Return our result variable as our replacement expression.
730 SkASSERT(resultExpr->as<VariableReference>().fRefKind == VariableReference::kRead_RefKind);
731 inlinedCall.fReplacementExpr = std::move(resultExpr);
John Stiles44e96be2020-08-31 13:16:04 -0400732 } else {
733 // It's a void function, so it doesn't actually result in anything, but we have to return
734 // something non-null as a standin.
735 inlinedCall.fReplacementExpr = std::make_unique<BoolLiteral>(*fContext, offset,
736 /*value=*/false);
737 }
738
John Stiles44e96be2020-08-31 13:16:04 -0400739 return inlinedCall;
740}
741
John Stiles93442622020-09-11 12:11:27 -0400742bool Inliner::isSafeToInline(const FunctionCall& functionCall, int inlineThreshold) {
John Stiles44e96be2020-08-31 13:16:04 -0400743 SkASSERT(fSettings);
744
745 if (functionCall.fFunction.fDefinition == nullptr) {
746 // Can't inline something if we don't actually have its definition.
747 return false;
748 }
749 const FunctionDefinition& functionDef = *functionCall.fFunction.fDefinition;
750 if (inlineThreshold < INT_MAX) {
751 if (!(functionDef.fDeclaration.fModifiers.fFlags & Modifiers::kInline_Flag) &&
752 Analysis::NodeCount(functionDef) >= inlineThreshold) {
753 // The function exceeds our maximum inline size and is not flagged 'inline'.
754 return false;
755 }
756 }
John Stiles44e96be2020-08-31 13:16:04 -0400757 if (!fSettings->fCaps || !fSettings->fCaps->canUseDoLoops()) {
758 // We don't have do-while loops. We use do-while loops to simulate early returns, so we
759 // can't inline functions that have an early return.
760 bool hasEarlyReturn = has_early_return(functionDef);
761
762 // If we didn't detect an early return, there shouldn't be any returns in breakable
763 // constructs either.
764 SkASSERT(hasEarlyReturn || count_returns_in_breakable_constructs(functionDef) == 0);
765 return !hasEarlyReturn;
766 }
767 // We have do-while loops, but we don't have any mechanism to simulate early returns within a
768 // breakable construct (switch/for/do/while), so we can't inline if there's a return inside one.
769 bool hasReturnInBreakableConstruct = (count_returns_in_breakable_constructs(functionDef) > 0);
770
771 // If we detected returns in breakable constructs, we should also detect an early return.
772 SkASSERT(!hasReturnInBreakableConstruct || has_early_return(functionDef));
773 return !hasReturnInBreakableConstruct;
774}
775
John Stiles93442622020-09-11 12:11:27 -0400776bool Inliner::analyze(Program& program) {
777 // A candidate function for inlining, containing everything that `inlineCall` needs.
778 struct InlineCandidate {
John Stiles915a38c2020-09-14 09:38:13 -0400779 SymbolTable* fSymbols; // the SymbolTable of the candidate
780 Statement* fParentStmt; // the parent Statement of the enclosing stmt
781 std::unique_ptr<Statement>* fEnclosingStmt; // the Statement containing the candidate
782 std::unique_ptr<Expression>* fCandidateExpr; // the candidate FunctionCall to be inlined
John Stiles93442622020-09-11 12:11:27 -0400783 };
784
785 // This is structured much like a ProgramVisitor, but does not actually use ProgramVisitor.
786 // The analyzer needs to keep track of the `unique_ptr<T>*` of statements and expressions so
787 // that they can later be replaced, and ProgramVisitor does not provide this; it only provides a
788 // `const T&`.
789 class InlineCandidateAnalyzer {
790 public:
791 // A list of all the inlining candidates we found during analysis.
792 std::vector<InlineCandidate> fInlineCandidates;
793 // A stack of the symbol tables; since most nodes don't have one, expected to be shallower
794 // than the enclosing-statement stack.
795 std::vector<SymbolTable*> fSymbolTableStack;
796 // A stack of "enclosing" statements--these would be suitable for the inliner to use for
797 // adding new instructions. Not all statements are suitable (e.g. a for-loop's initializer).
798 // The inliner might replace a statement with a block containing the statement.
799 std::vector<std::unique_ptr<Statement>*> fEnclosingStmtStack;
800
801 void visit(Program& program) {
802 fSymbolTableStack.push_back(program.fSymbols.get());
803
804 for (ProgramElement& pe : program) {
805 this->visitProgramElement(&pe);
806 }
807
808 fSymbolTableStack.pop_back();
809 }
810
811 void visitProgramElement(ProgramElement* pe) {
812 switch (pe->kind()) {
813 case ProgramElement::Kind::kFunction: {
814 FunctionDefinition& funcDef = pe->as<FunctionDefinition>();
815 this->visitStatement(&funcDef.fBody);
816 break;
817 }
818 default:
819 // The inliner can't operate outside of a function's scope.
820 break;
821 }
822 }
823
824 void visitStatement(std::unique_ptr<Statement>* stmt,
825 bool isViableAsEnclosingStatement = true) {
826 if (!*stmt) {
827 return;
828 }
829
830 size_t oldEnclosingStmtStackSize = fEnclosingStmtStack.size();
831 size_t oldSymbolStackSize = fSymbolTableStack.size();
832
833 if (isViableAsEnclosingStatement) {
834 fEnclosingStmtStack.push_back(stmt);
835 }
836
837 switch ((*stmt)->kind()) {
838 case Statement::Kind::kBreak:
839 case Statement::Kind::kContinue:
840 case Statement::Kind::kDiscard:
841 case Statement::Kind::kInlineMarker:
842 case Statement::Kind::kNop:
843 break;
844
845 case Statement::Kind::kBlock: {
846 Block& block = (*stmt)->as<Block>();
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400847 if (block.symbolTable()) {
848 fSymbolTableStack.push_back(block.symbolTable().get());
John Stiles93442622020-09-11 12:11:27 -0400849 }
850
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400851 for (std::unique_ptr<Statement>& stmt : block.children()) {
852 this->visitStatement(&stmt);
John Stiles93442622020-09-11 12:11:27 -0400853 }
854 break;
855 }
856 case Statement::Kind::kDo: {
857 DoStatement& doStmt = (*stmt)->as<DoStatement>();
858 // The loop body is a candidate for inlining.
Ethan Nicholas1fd61162020-09-28 13:14:19 -0400859 this->visitStatement(&doStmt.statement());
John Stiles93442622020-09-11 12:11:27 -0400860 // The inliner isn't smart enough to inline the test-expression for a do-while
861 // loop at this time. There are two limitations:
862 // - We would need to insert the inlined-body block at the very end of the do-
863 // statement's inner fStatement. We don't support that today, but it's doable.
864 // - We cannot inline the test expression if the loop uses `continue` anywhere;
865 // that would skip over the inlined block that evaluates the test expression.
866 // There isn't a good fix for this--any workaround would be more complex than
867 // the cost of a function call. However, loops that don't use `continue` would
868 // still be viable candidates for inlining.
869 break;
870 }
871 case Statement::Kind::kExpression: {
872 ExpressionStatement& expr = (*stmt)->as<ExpressionStatement>();
Ethan Nicholasd503a5a2020-09-30 09:29:55 -0400873 this->visitExpression(&expr.expression());
John Stiles93442622020-09-11 12:11:27 -0400874 break;
875 }
876 case Statement::Kind::kFor: {
877 ForStatement& forStmt = (*stmt)->as<ForStatement>();
878 if (forStmt.fSymbols) {
879 fSymbolTableStack.push_back(forStmt.fSymbols.get());
880 }
881
882 // The initializer and loop body are candidates for inlining.
883 this->visitStatement(&forStmt.fInitializer,
884 /*isViableAsEnclosingStatement=*/false);
885 this->visitStatement(&forStmt.fStatement);
886
887 // The inliner isn't smart enough to inline the test- or increment-expressions
888 // of a for loop loop at this time. There are a handful of limitations:
889 // - We would need to insert the test-expression block at the very beginning of
890 // the for-loop's inner fStatement, and the increment-expression block at the
891 // very end. We don't support that today, but it's doable.
892 // - The for-loop's built-in test-expression would need to be dropped entirely,
893 // and the loop would be halted via a break statement at the end of the
894 // inlined test-expression. This is again something we don't support today,
895 // but it could be implemented.
896 // - We cannot inline the increment-expression if the loop uses `continue`
897 // anywhere; that would skip over the inlined block that evaluates the
898 // increment expression. There isn't a good fix for this--any workaround would
899 // be more complex than the cost of a function call. However, loops that don't
900 // use `continue` would still be viable candidates for increment-expression
901 // inlining.
902 break;
903 }
904 case Statement::Kind::kIf: {
905 IfStatement& ifStmt = (*stmt)->as<IfStatement>();
906 this->visitExpression(&ifStmt.fTest);
907 this->visitStatement(&ifStmt.fIfTrue);
908 this->visitStatement(&ifStmt.fIfFalse);
909 break;
910 }
911 case Statement::Kind::kReturn: {
912 ReturnStatement& returnStmt = (*stmt)->as<ReturnStatement>();
913 this->visitExpression(&returnStmt.fExpression);
914 break;
915 }
916 case Statement::Kind::kSwitch: {
917 SwitchStatement& switchStmt = (*stmt)->as<SwitchStatement>();
918 if (switchStmt.fSymbols) {
919 fSymbolTableStack.push_back(switchStmt.fSymbols.get());
920 }
921
922 this->visitExpression(&switchStmt.fValue);
923 for (std::unique_ptr<SwitchCase>& switchCase : switchStmt.fCases) {
924 // The switch-case's fValue cannot be a FunctionCall; skip it.
925 for (std::unique_ptr<Statement>& caseBlock : switchCase->fStatements) {
926 this->visitStatement(&caseBlock);
927 }
928 }
929 break;
930 }
931 case Statement::Kind::kVarDeclaration: {
932 VarDeclaration& varDeclStmt = (*stmt)->as<VarDeclaration>();
933 // Don't need to scan the declaration's sizes; those are always IntLiterals.
934 this->visitExpression(&varDeclStmt.fValue);
935 break;
936 }
937 case Statement::Kind::kVarDeclarations: {
938 VarDeclarationsStatement& varDecls = (*stmt)->as<VarDeclarationsStatement>();
939 for (std::unique_ptr<Statement>& varDecl : varDecls.fDeclaration->fVars) {
940 this->visitStatement(&varDecl, /*isViableAsEnclosingStatement=*/false);
941 }
942 break;
943 }
944 case Statement::Kind::kWhile: {
945 WhileStatement& whileStmt = (*stmt)->as<WhileStatement>();
946 // The loop body is a candidate for inlining.
947 this->visitStatement(&whileStmt.fStatement);
948 // The inliner isn't smart enough to inline the test-expression for a while
949 // loop at this time. There are two limitations:
950 // - We would need to insert the inlined-body block at the very beginning of the
951 // while loop's inner fStatement. We don't support that today, but it's
952 // doable.
953 // - The while-loop's built-in test-expression would need to be replaced with a
954 // `true` BoolLiteral, and the loop would be halted via a break statement at
955 // the end of the inlined test-expression. This is again something we don't
956 // support today, but it could be implemented.
957 break;
958 }
959 default:
960 SkUNREACHABLE;
961 }
962
963 // Pop our symbol and enclosing-statement stacks.
964 fSymbolTableStack.resize(oldSymbolStackSize);
965 fEnclosingStmtStack.resize(oldEnclosingStmtStackSize);
966 }
967
968 void visitExpression(std::unique_ptr<Expression>* expr) {
969 if (!*expr) {
970 return;
971 }
972
973 switch ((*expr)->kind()) {
974 case Expression::Kind::kBoolLiteral:
975 case Expression::Kind::kDefined:
976 case Expression::Kind::kExternalValue:
977 case Expression::Kind::kFieldAccess:
978 case Expression::Kind::kFloatLiteral:
979 case Expression::Kind::kFunctionReference:
980 case Expression::Kind::kIntLiteral:
981 case Expression::Kind::kNullLiteral:
982 case Expression::Kind::kSetting:
983 case Expression::Kind::kTypeReference:
984 case Expression::Kind::kVariableReference:
985 // Nothing to scan here.
986 break;
987
988 case Expression::Kind::kBinary: {
989 BinaryExpression& binaryExpr = (*expr)->as<BinaryExpression>();
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400990 this->visitExpression(&binaryExpr.leftPointer());
John Stiles93442622020-09-11 12:11:27 -0400991
992 // Logical-and and logical-or binary expressions do not inline the right side,
993 // because that would invalidate short-circuiting. That is, when evaluating
994 // expressions like these:
995 // (false && x()) // always false
996 // (true || y()) // always true
997 // It is illegal for side-effects from x() or y() to occur. The simplest way to
998 // enforce that rule is to avoid inlining the right side entirely. However, it
999 // is safe for other types of binary expression to inline both sides.
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001000 Token::Kind op = binaryExpr.getOperator();
1001 bool shortCircuitable = (op == Token::Kind::TK_LOGICALAND ||
1002 op == Token::Kind::TK_LOGICALOR);
John Stiles93442622020-09-11 12:11:27 -04001003 if (!shortCircuitable) {
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001004 this->visitExpression(&binaryExpr.rightPointer());
John Stiles93442622020-09-11 12:11:27 -04001005 }
1006 break;
1007 }
1008 case Expression::Kind::kConstructor: {
1009 Constructor& constructorExpr = (*expr)->as<Constructor>();
Ethan Nicholasf70f0442020-09-29 12:41:35 -04001010 for (std::unique_ptr<Expression>& arg : constructorExpr.arguments()) {
John Stiles93442622020-09-11 12:11:27 -04001011 this->visitExpression(&arg);
1012 }
1013 break;
1014 }
1015 case Expression::Kind::kExternalFunctionCall: {
1016 ExternalFunctionCall& funcCallExpr = (*expr)->as<ExternalFunctionCall>();
1017 for (std::unique_ptr<Expression>& arg : funcCallExpr.fArguments) {
1018 this->visitExpression(&arg);
1019 }
1020 break;
1021 }
1022 case Expression::Kind::kFunctionCall: {
1023 FunctionCall& funcCallExpr = (*expr)->as<FunctionCall>();
1024 for (std::unique_ptr<Expression>& arg : funcCallExpr.fArguments) {
1025 this->visitExpression(&arg);
1026 }
1027 this->addInlineCandidate(expr);
1028 break;
1029 }
1030 case Expression::Kind::kIndex:{
1031 IndexExpression& indexExpr = (*expr)->as<IndexExpression>();
1032 this->visitExpression(&indexExpr.fBase);
1033 this->visitExpression(&indexExpr.fIndex);
1034 break;
1035 }
1036 case Expression::Kind::kPostfix: {
1037 PostfixExpression& postfixExpr = (*expr)->as<PostfixExpression>();
1038 this->visitExpression(&postfixExpr.fOperand);
1039 break;
1040 }
1041 case Expression::Kind::kPrefix: {
1042 PrefixExpression& prefixExpr = (*expr)->as<PrefixExpression>();
1043 this->visitExpression(&prefixExpr.fOperand);
1044 break;
1045 }
1046 case Expression::Kind::kSwizzle: {
1047 Swizzle& swizzleExpr = (*expr)->as<Swizzle>();
1048 this->visitExpression(&swizzleExpr.fBase);
1049 break;
1050 }
1051 case Expression::Kind::kTernary: {
1052 TernaryExpression& ternaryExpr = (*expr)->as<TernaryExpression>();
1053 // The test expression is a candidate for inlining.
1054 this->visitExpression(&ternaryExpr.fTest);
1055 // The true- and false-expressions cannot be inlined, because we are only
1056 // allowed to evaluate one side.
1057 break;
1058 }
1059 default:
1060 SkUNREACHABLE;
1061 }
1062 }
1063
1064 void addInlineCandidate(std::unique_ptr<Expression>* candidate) {
1065 fInlineCandidates.push_back(InlineCandidate{fSymbolTableStack.back(),
John Stiles915a38c2020-09-14 09:38:13 -04001066 find_parent_statement(fEnclosingStmtStack),
1067 fEnclosingStmtStack.back(),
1068 candidate});
John Stiles93442622020-09-11 12:11:27 -04001069 }
1070 };
1071
John Stiles93442622020-09-11 12:11:27 -04001072 InlineCandidateAnalyzer analyzer;
1073 analyzer.visit(program);
John Stiles915a38c2020-09-14 09:38:13 -04001074
1075 // For each of our candidate function-call sites, check if it is actually safe to inline.
1076 // Memoize our results so we don't check a function more than once.
John Stiles93442622020-09-11 12:11:27 -04001077 std::unordered_map<const FunctionDeclaration*, bool> inlinableMap; // <function, safe-to-inline>
John Stiles915a38c2020-09-14 09:38:13 -04001078 for (const InlineCandidate& candidate : analyzer.fInlineCandidates) {
John Stiles93442622020-09-11 12:11:27 -04001079 const FunctionCall& funcCall = (*candidate.fCandidateExpr)->as<FunctionCall>();
1080 const FunctionDeclaration* funcDecl = &funcCall.fFunction;
1081 if (inlinableMap.find(funcDecl) == inlinableMap.end()) {
1082 // We do not perform inlining on recursive calls to avoid an infinite death spiral of
1083 // inlining.
1084 int inlineThreshold = (funcDecl->fCallCount.load() > 1) ? fSettings->fInlineThreshold
1085 : INT_MAX;
1086 inlinableMap[funcDecl] = this->isSafeToInline(funcCall, inlineThreshold) &&
1087 !contains_recursive_call(*funcDecl);
John Stiles93442622020-09-11 12:11:27 -04001088 }
1089 }
1090
John Stiles915a38c2020-09-14 09:38:13 -04001091 // Inline the candidates where we've determined that it's safe to do so.
1092 std::unordered_set<const std::unique_ptr<Statement>*> enclosingStmtSet;
1093 bool madeChanges = false;
1094 for (const InlineCandidate& candidate : analyzer.fInlineCandidates) {
1095 FunctionCall& funcCall = (*candidate.fCandidateExpr)->as<FunctionCall>();
1096 const FunctionDeclaration* funcDecl = &funcCall.fFunction;
1097
1098 // If we determined that this candidate was not actually inlinable, skip it.
1099 if (!inlinableMap[funcDecl]) {
1100 continue;
1101 }
1102
1103 // Inlining two expressions using the same enclosing statement in the same inlining pass
1104 // does not work properly. If this happens, skip it; we'll get it in the next pass.
1105 auto [unusedIter, inserted] = enclosingStmtSet.insert(candidate.fEnclosingStmt);
1106 if (!inserted) {
1107 continue;
1108 }
1109
1110 // Convert the function call to its inlined equivalent.
1111 InlinedCall inlinedCall = this->inlineCall(&funcCall, candidate.fSymbols);
1112 if (inlinedCall.fInlinedBody) {
1113 // Ensure that the inlined body has a scope if it needs one.
John Stilesb61ee902020-09-21 12:26:59 -04001114 this->ensureScopedBlocks(inlinedCall.fInlinedBody.get(), candidate.fParentStmt);
John Stiles915a38c2020-09-14 09:38:13 -04001115
1116 // Move the enclosing statement to the end of the unscoped Block containing the inlined
1117 // function, then replace the enclosing statement with that Block.
1118 // Before:
1119 // fInlinedBody = Block{ stmt1, stmt2, stmt3 }
1120 // fEnclosingStmt = stmt4
1121 // After:
1122 // fInlinedBody = null
1123 // fEnclosingStmt = Block{ stmt1, stmt2, stmt3, stmt4 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001124 inlinedCall.fInlinedBody->children().push_back(std::move(*candidate.fEnclosingStmt));
John Stiles915a38c2020-09-14 09:38:13 -04001125 *candidate.fEnclosingStmt = std::move(inlinedCall.fInlinedBody);
1126 }
1127
1128 // Replace the candidate function call with our replacement expression.
1129 *candidate.fCandidateExpr = std::move(inlinedCall.fReplacementExpr);
1130 madeChanges = true;
1131
1132 // Note that nothing was destroyed except for the FunctionCall. All other nodes should
1133 // remain valid.
1134 }
1135
1136 return madeChanges;
John Stiles93442622020-09-11 12:11:27 -04001137}
1138
John Stiles44e96be2020-08-31 13:16:04 -04001139} // namespace SkSL