blob: 00c6d2bf9079b134680d14146a4fd335133ab3b0 [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 Stiles44e96be2020-08-31 13:16:04 -0400222} // namespace
223
John Stilesb61ee902020-09-21 12:26:59 -0400224void Inliner::ensureScopedBlocks(Statement* inlinedBody, Statement* parentStmt) {
225 // No changes necessary if this statement isn't actually a block.
226 if (!inlinedBody || !inlinedBody->is<Block>()) {
227 return;
228 }
229
230 // No changes necessary if the parent statement doesn't require a scope.
231 if (!parentStmt || !(parentStmt->is<IfStatement>() || parentStmt->is<ForStatement>() ||
232 parentStmt->is<DoStatement>() || parentStmt->is<WhileStatement>())) {
233 return;
234 }
235
236 Block& block = inlinedBody->as<Block>();
237
238 // The inliner will create inlined function bodies as a Block containing multiple statements,
239 // but no scope. Normally, this is fine, but if this block is used as the statement for a
240 // do/for/if/while, this isn't actually possible to represent textually; a scope must be added
241 // for the generated code to match the intent. In the case of Blocks nested inside other Blocks,
242 // we add the scope to the outermost block if needed. Zero-statement blocks have similar
243 // issues--if we don't represent the Block textually somehow, we run the risk of accidentally
244 // absorbing the following statement into our loop--so we also add a scope to these.
245 for (Block* nestedBlock = &block;; ) {
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400246 if (nestedBlock->isScope()) {
John Stilesb61ee902020-09-21 12:26:59 -0400247 // We found an explicit scope; all is well.
248 return;
249 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400250 if (nestedBlock->children().size() != 1) {
John Stilesb61ee902020-09-21 12:26:59 -0400251 // We found a block with multiple (or zero) statements, but no scope? Let's add a scope
252 // to the outermost block.
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400253 block.setIsScope(true);
John Stilesb61ee902020-09-21 12:26:59 -0400254 return;
255 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400256 if (!nestedBlock->children()[0]->is<Block>()) {
John Stilesb61ee902020-09-21 12:26:59 -0400257 // This block has exactly one thing inside, and it's not another block. No need to scope
258 // it.
259 return;
260 }
261 // We have to go deeper.
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400262 nestedBlock = &nestedBlock->children()[0]->as<Block>();
John Stilesb61ee902020-09-21 12:26:59 -0400263 }
264}
265
John Stiles44e96be2020-08-31 13:16:04 -0400266void Inliner::reset(const Context& context, const Program::Settings& settings) {
267 fContext = &context;
268 fSettings = &settings;
269 fInlineVarCounter = 0;
270}
271
John Stilesc75abb82020-09-14 18:24:12 -0400272String Inliner::uniqueNameForInlineVar(const String& baseName, SymbolTable* symbolTable) {
273 // If the base name starts with an underscore, like "_coords", we can't append another
274 // underscore, because OpenGL disallows two consecutive underscores anywhere in the string. But
275 // in the general case, using the underscore as a splitter reads nicely enough that it's worth
276 // putting in this special case.
277 const char* splitter = baseName.startsWith("_") ? "" : "_";
278
279 // Append a unique numeric prefix to avoid name overlap. Check the symbol table to make sure
280 // we're not reusing an existing name. (Note that within a single compilation pass, this check
281 // isn't fully comprehensive, as code isn't always generated in top-to-bottom order.)
282 String uniqueName;
283 for (;;) {
284 uniqueName = String::printf("_%d%s%s", fInlineVarCounter++, splitter, baseName.c_str());
285 StringFragment frag{uniqueName.data(), uniqueName.length()};
286 if ((*symbolTable)[frag] == nullptr) {
287 break;
288 }
289 }
290
291 return uniqueName;
292}
293
John Stiles44e96be2020-08-31 13:16:04 -0400294std::unique_ptr<Expression> Inliner::inlineExpression(int offset,
295 VariableRewriteMap* varMap,
296 const Expression& expression) {
297 auto expr = [&](const std::unique_ptr<Expression>& e) -> std::unique_ptr<Expression> {
298 if (e) {
299 return this->inlineExpression(offset, varMap, *e);
300 }
301 return nullptr;
302 };
303 auto argList = [&](const std::vector<std::unique_ptr<Expression>>& originalArgs)
304 -> std::vector<std::unique_ptr<Expression>> {
305 std::vector<std::unique_ptr<Expression>> args;
306 args.reserve(originalArgs.size());
307 for (const std::unique_ptr<Expression>& arg : originalArgs) {
308 args.push_back(expr(arg));
309 }
310 return args;
311 };
312
Ethan Nicholase6592142020-09-08 10:22:09 -0400313 switch (expression.kind()) {
314 case Expression::Kind::kBinary: {
John Stiles44e96be2020-08-31 13:16:04 -0400315 const BinaryExpression& b = expression.as<BinaryExpression>();
316 return std::make_unique<BinaryExpression>(offset,
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400317 expr(b.leftPointer()),
318 b.getOperator(),
319 expr(b.rightPointer()),
Ethan Nicholas30d30222020-09-11 12:27:26 -0400320 &b.type());
John Stiles44e96be2020-08-31 13:16:04 -0400321 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400322 case Expression::Kind::kBoolLiteral:
323 case Expression::Kind::kIntLiteral:
324 case Expression::Kind::kFloatLiteral:
325 case Expression::Kind::kNullLiteral:
John Stiles44e96be2020-08-31 13:16:04 -0400326 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400327 case Expression::Kind::kConstructor: {
John Stiles44e96be2020-08-31 13:16:04 -0400328 const Constructor& constructor = expression.as<Constructor>();
Ethan Nicholas30d30222020-09-11 12:27:26 -0400329 return std::make_unique<Constructor>(offset, &constructor.type(),
John Stiles44e96be2020-08-31 13:16:04 -0400330 argList(constructor.fArguments));
331 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400332 case Expression::Kind::kExternalFunctionCall: {
John Stiles44e96be2020-08-31 13:16:04 -0400333 const ExternalFunctionCall& externalCall = expression.as<ExternalFunctionCall>();
Ethan Nicholas30d30222020-09-11 12:27:26 -0400334 return std::make_unique<ExternalFunctionCall>(offset, &externalCall.type(),
John Stiles44e96be2020-08-31 13:16:04 -0400335 externalCall.fFunction,
336 argList(externalCall.fArguments));
337 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400338 case Expression::Kind::kExternalValue:
John Stiles44e96be2020-08-31 13:16:04 -0400339 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400340 case Expression::Kind::kFieldAccess: {
John Stiles44e96be2020-08-31 13:16:04 -0400341 const FieldAccess& f = expression.as<FieldAccess>();
342 return std::make_unique<FieldAccess>(expr(f.fBase), f.fFieldIndex, f.fOwnerKind);
343 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400344 case Expression::Kind::kFunctionCall: {
John Stiles44e96be2020-08-31 13:16:04 -0400345 const FunctionCall& funcCall = expression.as<FunctionCall>();
Ethan Nicholas30d30222020-09-11 12:27:26 -0400346 return std::make_unique<FunctionCall>(offset, &funcCall.type(), funcCall.fFunction,
John Stiles44e96be2020-08-31 13:16:04 -0400347 argList(funcCall.fArguments));
348 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400349 case Expression::Kind::kFunctionReference:
Brian Osman2b3b35f2020-09-08 09:17:36 -0400350 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400351 case Expression::Kind::kIndex: {
John Stiles44e96be2020-08-31 13:16:04 -0400352 const IndexExpression& idx = expression.as<IndexExpression>();
353 return std::make_unique<IndexExpression>(*fContext, expr(idx.fBase), expr(idx.fIndex));
354 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400355 case Expression::Kind::kPrefix: {
John Stiles44e96be2020-08-31 13:16:04 -0400356 const PrefixExpression& p = expression.as<PrefixExpression>();
357 return std::make_unique<PrefixExpression>(p.fOperator, expr(p.fOperand));
358 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400359 case Expression::Kind::kPostfix: {
John Stiles44e96be2020-08-31 13:16:04 -0400360 const PostfixExpression& p = expression.as<PostfixExpression>();
361 return std::make_unique<PostfixExpression>(expr(p.fOperand), p.fOperator);
362 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400363 case Expression::Kind::kSetting:
John Stiles44e96be2020-08-31 13:16:04 -0400364 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400365 case Expression::Kind::kSwizzle: {
John Stiles44e96be2020-08-31 13:16:04 -0400366 const Swizzle& s = expression.as<Swizzle>();
367 return std::make_unique<Swizzle>(*fContext, expr(s.fBase), s.fComponents);
368 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400369 case Expression::Kind::kTernary: {
John Stiles44e96be2020-08-31 13:16:04 -0400370 const TernaryExpression& t = expression.as<TernaryExpression>();
371 return std::make_unique<TernaryExpression>(offset, expr(t.fTest),
372 expr(t.fIfTrue), expr(t.fIfFalse));
373 }
Brian Osman83ba9302020-09-11 13:33:46 -0400374 case Expression::Kind::kTypeReference:
375 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400376 case Expression::Kind::kVariableReference: {
John Stiles44e96be2020-08-31 13:16:04 -0400377 const VariableReference& v = expression.as<VariableReference>();
Brian Osman79457ef2020-09-24 15:01:27 -0400378 auto found = varMap->find(v.fVariable);
John Stiles44e96be2020-08-31 13:16:04 -0400379 if (found != varMap->end()) {
Brian Osman79457ef2020-09-24 15:01:27 -0400380 return std::make_unique<VariableReference>(offset, found->second, v.fRefKind);
John Stiles44e96be2020-08-31 13:16:04 -0400381 }
382 return v.clone();
383 }
384 default:
385 SkASSERT(false);
386 return nullptr;
387 }
388}
389
390std::unique_ptr<Statement> Inliner::inlineStatement(int offset,
391 VariableRewriteMap* varMap,
392 SymbolTable* symbolTableForStatement,
John Stilesa5f3c312020-09-22 12:05:16 -0400393 const VariableExpression& resultExpr,
John Stiles44e96be2020-08-31 13:16:04 -0400394 bool haveEarlyReturns,
395 const Statement& statement) {
396 auto stmt = [&](const std::unique_ptr<Statement>& s) -> std::unique_ptr<Statement> {
397 if (s) {
John Stilesa5f3c312020-09-22 12:05:16 -0400398 return this->inlineStatement(offset, varMap, symbolTableForStatement, resultExpr,
John Stiles44e96be2020-08-31 13:16:04 -0400399 haveEarlyReturns, *s);
400 }
401 return nullptr;
402 };
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400403 auto blockStmts = [&](const Block& block) {
404 std::vector<std::unique_ptr<Statement>> result;
405 for (const std::unique_ptr<Statement>& child : block.children()) {
406 result.push_back(stmt(child));
407 }
408 return result;
409 };
John Stiles44e96be2020-08-31 13:16:04 -0400410 auto stmts = [&](const std::vector<std::unique_ptr<Statement>>& ss) {
411 std::vector<std::unique_ptr<Statement>> result;
412 for (const auto& s : ss) {
413 result.push_back(stmt(s));
414 }
415 return result;
416 };
417 auto expr = [&](const std::unique_ptr<Expression>& e) -> std::unique_ptr<Expression> {
418 if (e) {
419 return this->inlineExpression(offset, varMap, *e);
420 }
421 return nullptr;
422 };
Ethan Nicholase6592142020-09-08 10:22:09 -0400423 switch (statement.kind()) {
424 case Statement::Kind::kBlock: {
John Stiles44e96be2020-08-31 13:16:04 -0400425 const Block& b = statement.as<Block>();
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400426 return std::make_unique<Block>(offset, blockStmts(b), b.symbolTable(), b.isScope());
John Stiles44e96be2020-08-31 13:16:04 -0400427 }
428
Ethan Nicholase6592142020-09-08 10:22:09 -0400429 case Statement::Kind::kBreak:
430 case Statement::Kind::kContinue:
431 case Statement::Kind::kDiscard:
John Stiles44e96be2020-08-31 13:16:04 -0400432 return statement.clone();
433
Ethan Nicholase6592142020-09-08 10:22:09 -0400434 case Statement::Kind::kDo: {
John Stiles44e96be2020-08-31 13:16:04 -0400435 const DoStatement& d = statement.as<DoStatement>();
436 return std::make_unique<DoStatement>(offset, stmt(d.fStatement), expr(d.fTest));
437 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400438 case Statement::Kind::kExpression: {
John Stiles44e96be2020-08-31 13:16:04 -0400439 const ExpressionStatement& e = statement.as<ExpressionStatement>();
440 return std::make_unique<ExpressionStatement>(expr(e.fExpression));
441 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400442 case Statement::Kind::kFor: {
John Stiles44e96be2020-08-31 13:16:04 -0400443 const ForStatement& f = statement.as<ForStatement>();
444 // need to ensure initializer is evaluated first so that we've already remapped its
445 // declarations by the time we evaluate test & next
446 std::unique_ptr<Statement> initializer = stmt(f.fInitializer);
447 return std::make_unique<ForStatement>(offset, std::move(initializer), expr(f.fTest),
448 expr(f.fNext), stmt(f.fStatement), f.fSymbols);
449 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400450 case Statement::Kind::kIf: {
John Stiles44e96be2020-08-31 13:16:04 -0400451 const IfStatement& i = statement.as<IfStatement>();
452 return std::make_unique<IfStatement>(offset, i.fIsStatic, expr(i.fTest),
453 stmt(i.fIfTrue), stmt(i.fIfFalse));
454 }
John Stiles98c1f822020-09-09 14:18:53 -0400455 case Statement::Kind::kInlineMarker:
Ethan Nicholase6592142020-09-08 10:22:09 -0400456 case Statement::Kind::kNop:
John Stiles44e96be2020-08-31 13:16:04 -0400457 return statement.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400458 case Statement::Kind::kReturn: {
John Stiles44e96be2020-08-31 13:16:04 -0400459 const ReturnStatement& r = statement.as<ReturnStatement>();
460 if (r.fExpression) {
John Stilesa5f3c312020-09-22 12:05:16 -0400461 auto assignment =
462 std::make_unique<ExpressionStatement>(std::make_unique<BinaryExpression>(
463 offset,
464 resultExpr.cloneWithRefKind(VariableReference::kWrite_RefKind),
465 Token::Kind::TK_EQ,
466 expr(r.fExpression),
467 &resultExpr.type()));
John Stiles44e96be2020-08-31 13:16:04 -0400468 if (haveEarlyReturns) {
469 std::vector<std::unique_ptr<Statement>> block;
470 block.push_back(std::move(assignment));
471 block.emplace_back(new BreakStatement(offset));
472 return std::make_unique<Block>(offset, std::move(block), /*symbols=*/nullptr,
473 /*isScope=*/true);
474 } else {
475 return std::move(assignment);
476 }
477 } else {
478 if (haveEarlyReturns) {
479 return std::make_unique<BreakStatement>(offset);
480 } else {
481 return std::make_unique<Nop>();
482 }
483 }
484 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400485 case Statement::Kind::kSwitch: {
John Stiles44e96be2020-08-31 13:16:04 -0400486 const SwitchStatement& ss = statement.as<SwitchStatement>();
487 std::vector<std::unique_ptr<SwitchCase>> cases;
488 for (const auto& sc : ss.fCases) {
489 cases.emplace_back(new SwitchCase(offset, expr(sc->fValue),
490 stmts(sc->fStatements)));
491 }
492 return std::make_unique<SwitchStatement>(offset, ss.fIsStatic, expr(ss.fValue),
493 std::move(cases), ss.fSymbols);
494 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400495 case Statement::Kind::kVarDeclaration: {
John Stiles44e96be2020-08-31 13:16:04 -0400496 const VarDeclaration& decl = statement.as<VarDeclaration>();
497 std::vector<std::unique_ptr<Expression>> sizes;
498 for (const auto& size : decl.fSizes) {
499 sizes.push_back(expr(size));
500 }
501 std::unique_ptr<Expression> initialValue = expr(decl.fValue);
502 const Variable* old = decl.fVar;
John Stilesc75abb82020-09-14 18:24:12 -0400503 // We assign unique names to inlined variables--scopes hide most of the problems in this
504 // regard, but see `InlinerAvoidsVariableNameOverlap` for a counterexample where unique
505 // names are important.
506 auto name = std::make_unique<String>(
507 this->uniqueNameForInlineVar(String(old->fName), symbolTableForStatement));
John Stiles44e96be2020-08-31 13:16:04 -0400508 const String* namePtr = symbolTableForStatement->takeOwnershipOfString(std::move(name));
Ethan Nicholas30d30222020-09-11 12:27:26 -0400509 const Type* typePtr = copy_if_needed(&old->type(), *symbolTableForStatement);
John Stiles44e96be2020-08-31 13:16:04 -0400510 const Variable* clone = symbolTableForStatement->takeOwnershipOfSymbol(
511 std::make_unique<Variable>(offset,
512 old->fModifiers,
513 namePtr->c_str(),
Ethan Nicholas30d30222020-09-11 12:27:26 -0400514 typePtr,
John Stiles44e96be2020-08-31 13:16:04 -0400515 old->fStorage,
516 initialValue.get()));
517 (*varMap)[old] = clone;
518 return std::make_unique<VarDeclaration>(clone, std::move(sizes),
519 std::move(initialValue));
520 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400521 case Statement::Kind::kVarDeclarations: {
John Stiles44e96be2020-08-31 13:16:04 -0400522 const VarDeclarations& decls = *statement.as<VarDeclarationsStatement>().fDeclaration;
523 std::vector<std::unique_ptr<VarDeclaration>> vars;
524 for (const auto& var : decls.fVars) {
525 vars.emplace_back(&stmt(var).release()->as<VarDeclaration>());
526 }
527 const Type* typePtr = copy_if_needed(&decls.fBaseType, *symbolTableForStatement);
528 return std::unique_ptr<Statement>(new VarDeclarationsStatement(
529 std::make_unique<VarDeclarations>(offset, typePtr, std::move(vars))));
530 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400531 case Statement::Kind::kWhile: {
John Stiles44e96be2020-08-31 13:16:04 -0400532 const WhileStatement& w = statement.as<WhileStatement>();
533 return std::make_unique<WhileStatement>(offset, expr(w.fTest), stmt(w.fStatement));
534 }
535 default:
536 SkASSERT(false);
537 return nullptr;
538 }
539}
540
John Stiles6eadf132020-09-08 10:16:10 -0400541Inliner::InlinedCall Inliner::inlineCall(FunctionCall* call,
John Stiles44e96be2020-08-31 13:16:04 -0400542 SymbolTable* symbolTableForCall) {
543 // Inlining is more complicated here than in a typical compiler, because we have to have a
544 // high-level IR and can't just drop statements into the middle of an expression or even use
545 // gotos.
546 //
547 // Since we can't insert statements into an expression, we run the inline function as extra
548 // statements before the statement we're currently processing, relying on a lack of execution
549 // order guarantees. Since we can't use gotos (which are normally used to replace return
550 // statements), we wrap the whole function in a loop and use break statements to jump to the
551 // end.
552 SkASSERT(fSettings);
553 SkASSERT(fContext);
554 SkASSERT(call);
555 SkASSERT(this->isSafeToInline(*call, /*inlineThreshold=*/INT_MAX));
556
John Stiles44e96be2020-08-31 13:16:04 -0400557 std::vector<std::unique_ptr<Expression>>& arguments = call->fArguments;
John Stiles6eadf132020-09-08 10:16:10 -0400558 const int offset = call->fOffset;
John Stiles44e96be2020-08-31 13:16:04 -0400559 const FunctionDefinition& function = *call->fFunction.fDefinition;
John Stiles6eadf132020-09-08 10:16:10 -0400560 const bool hasEarlyReturn = has_early_return(function);
561
John Stiles44e96be2020-08-31 13:16:04 -0400562 InlinedCall inlinedCall;
John Stiles6eadf132020-09-08 10:16:10 -0400563 inlinedCall.fInlinedBody = std::make_unique<Block>(offset,
564 std::vector<std::unique_ptr<Statement>>{},
565 /*symbols=*/nullptr,
566 /*isScope=*/false);
John Stiles98c1f822020-09-09 14:18:53 -0400567
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400568 Block& inlinedBody = *inlinedCall.fInlinedBody;
569 inlinedBody.children().reserve(1 + // Inline marker
570 1 + // Result variable
571 arguments.size() + // Function arguments (passing in)
572 arguments.size() + // Function arguments (copy out-parameters
573 // back)
574 1); // Inlined code (either as a Block or do-while
575 // loop)
John Stiles98c1f822020-09-09 14:18:53 -0400576
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400577 inlinedBody.children().push_back(std::make_unique<InlineMarker>(call->fFunction));
John Stiles44e96be2020-08-31 13:16:04 -0400578
John Stilesa003e812020-09-11 09:43:49 -0400579 auto makeInlineVar = [&](const String& baseName, const Type* type, Modifiers modifiers,
John Stiles44e96be2020-08-31 13:16:04 -0400580 std::unique_ptr<Expression>* initialValue) -> const Variable* {
John Stilesa003e812020-09-11 09:43:49 -0400581 // $floatLiteral or $intLiteral aren't real types that we can use for scratch variables, so
582 // replace them if they ever appear here. If this happens, we likely forgot to coerce a type
583 // somewhere during compilation.
584 if (type == fContext->fFloatLiteral_Type.get()) {
John Stilesd2be5c52020-09-11 14:58:06 -0400585 SkDEBUGFAIL("found a $floatLiteral type while inlining");
John Stilesa003e812020-09-11 09:43:49 -0400586 type = fContext->fFloat_Type.get();
587 } else if (type == fContext->fIntLiteral_Type.get()) {
John Stilesd2be5c52020-09-11 14:58:06 -0400588 SkDEBUGFAIL("found an $intLiteral type while inlining");
John Stilesa003e812020-09-11 09:43:49 -0400589 type = fContext->fInt_Type.get();
590 }
591
John Stilesc75abb82020-09-14 18:24:12 -0400592 // Provide our new variable with a unique name, and add it to our symbol table.
593 String uniqueName = this->uniqueNameForInlineVar(baseName, symbolTableForCall);
John Stilescf936f92020-08-31 17:18:45 -0400594 const String* namePtr = symbolTableForCall->takeOwnershipOfString(
595 std::make_unique<String>(std::move(uniqueName)));
John Stiles44e96be2020-08-31 13:16:04 -0400596 StringFragment nameFrag{namePtr->c_str(), namePtr->length()};
597
598 // Add our new variable to the symbol table.
Ethan Nicholas30d30222020-09-11 12:27:26 -0400599 auto newVar = std::make_unique<Variable>(/*offset=*/-1, Modifiers(), nameFrag, type,
John Stiles44e96be2020-08-31 13:16:04 -0400600 Variable::kLocal_Storage, initialValue->get());
601 const Variable* variableSymbol = symbolTableForCall->add(nameFrag, std::move(newVar));
602
603 // Prepare the variable declaration (taking extra care with `out` params to not clobber any
604 // initial value).
605 std::vector<std::unique_ptr<VarDeclaration>> variables;
606 if (initialValue && (modifiers.fFlags & Modifiers::kOut_Flag)) {
607 variables.push_back(std::make_unique<VarDeclaration>(
608 variableSymbol, /*sizes=*/std::vector<std::unique_ptr<Expression>>{},
609 (*initialValue)->clone()));
610 } else {
611 variables.push_back(std::make_unique<VarDeclaration>(
612 variableSymbol, /*sizes=*/std::vector<std::unique_ptr<Expression>>{},
613 std::move(*initialValue)));
614 }
615
616 // Add the new variable-declaration statement to our block of extra statements.
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400617 inlinedBody.children().push_back(std::make_unique<VarDeclarationsStatement>(
John Stilesa003e812020-09-11 09:43:49 -0400618 std::make_unique<VarDeclarations>(offset, type, std::move(variables))));
John Stiles44e96be2020-08-31 13:16:04 -0400619
620 return variableSymbol;
621 };
622
623 // Create a variable to hold the result in the extra statements (excepting void).
John Stilesa5f3c312020-09-22 12:05:16 -0400624 VariableExpression resultExpr;
John Stiles44e96be2020-08-31 13:16:04 -0400625 if (function.fDeclaration.fReturnType != *fContext->fVoid_Type) {
John Stiles44e96be2020-08-31 13:16:04 -0400626 std::unique_ptr<Expression> noInitialValue;
John Stilesa5f3c312020-09-22 12:05:16 -0400627 const Variable* var = makeInlineVar(String(function.fDeclaration.fName),
628 &function.fDeclaration.fReturnType,
629 Modifiers{}, &noInitialValue);
Brian Osman79457ef2020-09-24 15:01:27 -0400630 resultExpr.fInnerVariable = std::make_unique<VariableReference>(offset, var);
John Stiles44e96be2020-08-31 13:16:04 -0400631 }
632
633 // Create variables in the extra statements to hold the arguments, and assign the arguments to
634 // them.
635 VariableRewriteMap varMap;
John Stiles44e96be2020-08-31 13:16:04 -0400636 for (int i = 0; i < (int) arguments.size(); ++i) {
637 const Variable* param = function.fDeclaration.fParameters[i];
638
John Stilesa003e812020-09-11 09:43:49 -0400639 if (arguments[i]->is<VariableReference>()) {
John Stiles44e96be2020-08-31 13:16:04 -0400640 // The argument is just a variable, so we only need to copy it if it's an out parameter
641 // or it's written to within the function.
642 if ((param->fModifiers.fFlags & Modifiers::kOut_Flag) ||
643 !Analysis::StatementWritesToVariable(*function.fBody, *param)) {
Brian Osman79457ef2020-09-24 15:01:27 -0400644 varMap[param] = arguments[i]->as<VariableReference>().fVariable;
John Stiles44e96be2020-08-31 13:16:04 -0400645 continue;
646 }
647 }
648
Ethan Nicholas30d30222020-09-11 12:27:26 -0400649 varMap[param] = makeInlineVar(String(param->fName), &arguments[i]->type(),
650 param->fModifiers, &arguments[i]);
John Stiles44e96be2020-08-31 13:16:04 -0400651 }
652
653 const Block& body = function.fBody->as<Block>();
John Stiles44e96be2020-08-31 13:16:04 -0400654 auto inlineBlock = std::make_unique<Block>(offset, std::vector<std::unique_ptr<Statement>>{});
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400655 inlineBlock->children().reserve(body.children().size());
656 for (const std::unique_ptr<Statement>& stmt : body.children()) {
657 inlineBlock->children().push_back(this->inlineStatement(
John Stilesa5f3c312020-09-22 12:05:16 -0400658 offset, &varMap, symbolTableForCall, resultExpr, hasEarlyReturn, *stmt));
John Stiles44e96be2020-08-31 13:16:04 -0400659 }
660 if (hasEarlyReturn) {
661 // Since we output to backends that don't have a goto statement (which would normally be
662 // used to perform an early return), we fake it by wrapping the function in a
663 // do { } while (false); and then use break statements to jump to the end in order to
664 // emulate a goto.
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400665 inlinedBody.children().push_back(std::make_unique<DoStatement>(
John Stiles44e96be2020-08-31 13:16:04 -0400666 /*offset=*/-1,
667 std::move(inlineBlock),
668 std::make_unique<BoolLiteral>(*fContext, offset, /*value=*/false)));
669 } else {
John Stiles6eadf132020-09-08 10:16:10 -0400670 // No early returns, so we can just dump the code in. We still need to keep the block so we
671 // don't get name conflicts with locals.
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400672 inlinedBody.children().push_back(std::move(inlineBlock));
John Stiles44e96be2020-08-31 13:16:04 -0400673 }
674
675 // Copy the values of `out` parameters into their destinations.
676 for (size_t i = 0; i < arguments.size(); ++i) {
677 const Variable* p = function.fDeclaration.fParameters[i];
678 if (p->fModifiers.fFlags & Modifiers::kOut_Flag) {
679 SkASSERT(varMap.find(p) != varMap.end());
John Stiles978674a2020-09-23 15:24:51 -0400680 if (arguments[i]->is<VariableReference>() &&
Brian Osman79457ef2020-09-24 15:01:27 -0400681 arguments[i]->as<VariableReference>().fVariable == varMap[p]) {
John Stiles6eadf132020-09-08 10:16:10 -0400682 // We didn't create a temporary for this parameter, so there's nothing to copy back
683 // out.
John Stiles44e96be2020-08-31 13:16:04 -0400684 continue;
685 }
Brian Osman79457ef2020-09-24 15:01:27 -0400686 auto varRef = std::make_unique<VariableReference>(offset, varMap[p]);
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400687 inlinedBody.children().push_back(std::make_unique<ExpressionStatement>(
John Stiles44e96be2020-08-31 13:16:04 -0400688 std::make_unique<BinaryExpression>(offset,
689 arguments[i]->clone(),
690 Token::Kind::TK_EQ,
691 std::move(varRef),
Ethan Nicholas30d30222020-09-11 12:27:26 -0400692 &arguments[i]->type())));
John Stiles44e96be2020-08-31 13:16:04 -0400693 }
694 }
695
696 if (function.fDeclaration.fReturnType != *fContext->fVoid_Type) {
697 // Return a reference to the result variable as our replacement expression.
John Stilesa5f3c312020-09-22 12:05:16 -0400698 resultExpr.fInnerVariable->setRefKind(VariableReference::kRead_RefKind);
699 inlinedCall.fReplacementExpr = resultExpr.fOuterExpression
700 ? std::move(resultExpr.fOuterExpression)
701 : std::move(resultExpr.fInnerVariable);
John Stiles44e96be2020-08-31 13:16:04 -0400702 } else {
703 // It's a void function, so it doesn't actually result in anything, but we have to return
704 // something non-null as a standin.
705 inlinedCall.fReplacementExpr = std::make_unique<BoolLiteral>(*fContext, offset,
706 /*value=*/false);
707 }
708
John Stiles44e96be2020-08-31 13:16:04 -0400709 return inlinedCall;
710}
711
John Stiles93442622020-09-11 12:11:27 -0400712bool Inliner::isSafeToInline(const FunctionCall& functionCall, int inlineThreshold) {
John Stiles44e96be2020-08-31 13:16:04 -0400713 SkASSERT(fSettings);
714
715 if (functionCall.fFunction.fDefinition == nullptr) {
716 // Can't inline something if we don't actually have its definition.
717 return false;
718 }
719 const FunctionDefinition& functionDef = *functionCall.fFunction.fDefinition;
720 if (inlineThreshold < INT_MAX) {
721 if (!(functionDef.fDeclaration.fModifiers.fFlags & Modifiers::kInline_Flag) &&
722 Analysis::NodeCount(functionDef) >= inlineThreshold) {
723 // The function exceeds our maximum inline size and is not flagged 'inline'.
724 return false;
725 }
726 }
John Stiles44e96be2020-08-31 13:16:04 -0400727 if (!fSettings->fCaps || !fSettings->fCaps->canUseDoLoops()) {
728 // We don't have do-while loops. We use do-while loops to simulate early returns, so we
729 // can't inline functions that have an early return.
730 bool hasEarlyReturn = has_early_return(functionDef);
731
732 // If we didn't detect an early return, there shouldn't be any returns in breakable
733 // constructs either.
734 SkASSERT(hasEarlyReturn || count_returns_in_breakable_constructs(functionDef) == 0);
735 return !hasEarlyReturn;
736 }
737 // We have do-while loops, but we don't have any mechanism to simulate early returns within a
738 // breakable construct (switch/for/do/while), so we can't inline if there's a return inside one.
739 bool hasReturnInBreakableConstruct = (count_returns_in_breakable_constructs(functionDef) > 0);
740
741 // If we detected returns in breakable constructs, we should also detect an early return.
742 SkASSERT(!hasReturnInBreakableConstruct || has_early_return(functionDef));
743 return !hasReturnInBreakableConstruct;
744}
745
John Stiles93442622020-09-11 12:11:27 -0400746bool Inliner::analyze(Program& program) {
747 // A candidate function for inlining, containing everything that `inlineCall` needs.
748 struct InlineCandidate {
John Stiles915a38c2020-09-14 09:38:13 -0400749 SymbolTable* fSymbols; // the SymbolTable of the candidate
750 Statement* fParentStmt; // the parent Statement of the enclosing stmt
751 std::unique_ptr<Statement>* fEnclosingStmt; // the Statement containing the candidate
752 std::unique_ptr<Expression>* fCandidateExpr; // the candidate FunctionCall to be inlined
John Stiles93442622020-09-11 12:11:27 -0400753 };
754
755 // This is structured much like a ProgramVisitor, but does not actually use ProgramVisitor.
756 // The analyzer needs to keep track of the `unique_ptr<T>*` of statements and expressions so
757 // that they can later be replaced, and ProgramVisitor does not provide this; it only provides a
758 // `const T&`.
759 class InlineCandidateAnalyzer {
760 public:
761 // A list of all the inlining candidates we found during analysis.
762 std::vector<InlineCandidate> fInlineCandidates;
763 // A stack of the symbol tables; since most nodes don't have one, expected to be shallower
764 // than the enclosing-statement stack.
765 std::vector<SymbolTable*> fSymbolTableStack;
766 // A stack of "enclosing" statements--these would be suitable for the inliner to use for
767 // adding new instructions. Not all statements are suitable (e.g. a for-loop's initializer).
768 // The inliner might replace a statement with a block containing the statement.
769 std::vector<std::unique_ptr<Statement>*> fEnclosingStmtStack;
770
771 void visit(Program& program) {
772 fSymbolTableStack.push_back(program.fSymbols.get());
773
774 for (ProgramElement& pe : program) {
775 this->visitProgramElement(&pe);
776 }
777
778 fSymbolTableStack.pop_back();
779 }
780
781 void visitProgramElement(ProgramElement* pe) {
782 switch (pe->kind()) {
783 case ProgramElement::Kind::kFunction: {
784 FunctionDefinition& funcDef = pe->as<FunctionDefinition>();
785 this->visitStatement(&funcDef.fBody);
786 break;
787 }
788 default:
789 // The inliner can't operate outside of a function's scope.
790 break;
791 }
792 }
793
794 void visitStatement(std::unique_ptr<Statement>* stmt,
795 bool isViableAsEnclosingStatement = true) {
796 if (!*stmt) {
797 return;
798 }
799
800 size_t oldEnclosingStmtStackSize = fEnclosingStmtStack.size();
801 size_t oldSymbolStackSize = fSymbolTableStack.size();
802
803 if (isViableAsEnclosingStatement) {
804 fEnclosingStmtStack.push_back(stmt);
805 }
806
807 switch ((*stmt)->kind()) {
808 case Statement::Kind::kBreak:
809 case Statement::Kind::kContinue:
810 case Statement::Kind::kDiscard:
811 case Statement::Kind::kInlineMarker:
812 case Statement::Kind::kNop:
813 break;
814
815 case Statement::Kind::kBlock: {
816 Block& block = (*stmt)->as<Block>();
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400817 if (block.symbolTable()) {
818 fSymbolTableStack.push_back(block.symbolTable().get());
John Stiles93442622020-09-11 12:11:27 -0400819 }
820
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400821 for (std::unique_ptr<Statement>& stmt : block.children()) {
822 this->visitStatement(&stmt);
John Stiles93442622020-09-11 12:11:27 -0400823 }
824 break;
825 }
826 case Statement::Kind::kDo: {
827 DoStatement& doStmt = (*stmt)->as<DoStatement>();
828 // The loop body is a candidate for inlining.
829 this->visitStatement(&doStmt.fStatement);
830 // The inliner isn't smart enough to inline the test-expression for a do-while
831 // loop at this time. There are two limitations:
832 // - We would need to insert the inlined-body block at the very end of the do-
833 // statement's inner fStatement. We don't support that today, but it's doable.
834 // - We cannot inline the test expression if the loop uses `continue` anywhere;
835 // that would skip over the inlined block that evaluates the test expression.
836 // There isn't a good fix for this--any workaround would be more complex than
837 // the cost of a function call. However, loops that don't use `continue` would
838 // still be viable candidates for inlining.
839 break;
840 }
841 case Statement::Kind::kExpression: {
842 ExpressionStatement& expr = (*stmt)->as<ExpressionStatement>();
843 this->visitExpression(&expr.fExpression);
844 break;
845 }
846 case Statement::Kind::kFor: {
847 ForStatement& forStmt = (*stmt)->as<ForStatement>();
848 if (forStmt.fSymbols) {
849 fSymbolTableStack.push_back(forStmt.fSymbols.get());
850 }
851
852 // The initializer and loop body are candidates for inlining.
853 this->visitStatement(&forStmt.fInitializer,
854 /*isViableAsEnclosingStatement=*/false);
855 this->visitStatement(&forStmt.fStatement);
856
857 // The inliner isn't smart enough to inline the test- or increment-expressions
858 // of a for loop loop at this time. There are a handful of limitations:
859 // - We would need to insert the test-expression block at the very beginning of
860 // the for-loop's inner fStatement, and the increment-expression block at the
861 // very end. We don't support that today, but it's doable.
862 // - The for-loop's built-in test-expression would need to be dropped entirely,
863 // and the loop would be halted via a break statement at the end of the
864 // inlined test-expression. This is again something we don't support today,
865 // but it could be implemented.
866 // - We cannot inline the increment-expression if the loop uses `continue`
867 // anywhere; that would skip over the inlined block that evaluates the
868 // increment expression. There isn't a good fix for this--any workaround would
869 // be more complex than the cost of a function call. However, loops that don't
870 // use `continue` would still be viable candidates for increment-expression
871 // inlining.
872 break;
873 }
874 case Statement::Kind::kIf: {
875 IfStatement& ifStmt = (*stmt)->as<IfStatement>();
876 this->visitExpression(&ifStmt.fTest);
877 this->visitStatement(&ifStmt.fIfTrue);
878 this->visitStatement(&ifStmt.fIfFalse);
879 break;
880 }
881 case Statement::Kind::kReturn: {
882 ReturnStatement& returnStmt = (*stmt)->as<ReturnStatement>();
883 this->visitExpression(&returnStmt.fExpression);
884 break;
885 }
886 case Statement::Kind::kSwitch: {
887 SwitchStatement& switchStmt = (*stmt)->as<SwitchStatement>();
888 if (switchStmt.fSymbols) {
889 fSymbolTableStack.push_back(switchStmt.fSymbols.get());
890 }
891
892 this->visitExpression(&switchStmt.fValue);
893 for (std::unique_ptr<SwitchCase>& switchCase : switchStmt.fCases) {
894 // The switch-case's fValue cannot be a FunctionCall; skip it.
895 for (std::unique_ptr<Statement>& caseBlock : switchCase->fStatements) {
896 this->visitStatement(&caseBlock);
897 }
898 }
899 break;
900 }
901 case Statement::Kind::kVarDeclaration: {
902 VarDeclaration& varDeclStmt = (*stmt)->as<VarDeclaration>();
903 // Don't need to scan the declaration's sizes; those are always IntLiterals.
904 this->visitExpression(&varDeclStmt.fValue);
905 break;
906 }
907 case Statement::Kind::kVarDeclarations: {
908 VarDeclarationsStatement& varDecls = (*stmt)->as<VarDeclarationsStatement>();
909 for (std::unique_ptr<Statement>& varDecl : varDecls.fDeclaration->fVars) {
910 this->visitStatement(&varDecl, /*isViableAsEnclosingStatement=*/false);
911 }
912 break;
913 }
914 case Statement::Kind::kWhile: {
915 WhileStatement& whileStmt = (*stmt)->as<WhileStatement>();
916 // The loop body is a candidate for inlining.
917 this->visitStatement(&whileStmt.fStatement);
918 // The inliner isn't smart enough to inline the test-expression for a while
919 // loop at this time. There are two limitations:
920 // - We would need to insert the inlined-body block at the very beginning of the
921 // while loop's inner fStatement. We don't support that today, but it's
922 // doable.
923 // - The while-loop's built-in test-expression would need to be replaced with a
924 // `true` BoolLiteral, and the loop would be halted via a break statement at
925 // the end of the inlined test-expression. This is again something we don't
926 // support today, but it could be implemented.
927 break;
928 }
929 default:
930 SkUNREACHABLE;
931 }
932
933 // Pop our symbol and enclosing-statement stacks.
934 fSymbolTableStack.resize(oldSymbolStackSize);
935 fEnclosingStmtStack.resize(oldEnclosingStmtStackSize);
936 }
937
938 void visitExpression(std::unique_ptr<Expression>* expr) {
939 if (!*expr) {
940 return;
941 }
942
943 switch ((*expr)->kind()) {
944 case Expression::Kind::kBoolLiteral:
945 case Expression::Kind::kDefined:
946 case Expression::Kind::kExternalValue:
947 case Expression::Kind::kFieldAccess:
948 case Expression::Kind::kFloatLiteral:
949 case Expression::Kind::kFunctionReference:
950 case Expression::Kind::kIntLiteral:
951 case Expression::Kind::kNullLiteral:
952 case Expression::Kind::kSetting:
953 case Expression::Kind::kTypeReference:
954 case Expression::Kind::kVariableReference:
955 // Nothing to scan here.
956 break;
957
958 case Expression::Kind::kBinary: {
959 BinaryExpression& binaryExpr = (*expr)->as<BinaryExpression>();
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400960 this->visitExpression(&binaryExpr.leftPointer());
John Stiles93442622020-09-11 12:11:27 -0400961
962 // Logical-and and logical-or binary expressions do not inline the right side,
963 // because that would invalidate short-circuiting. That is, when evaluating
964 // expressions like these:
965 // (false && x()) // always false
966 // (true || y()) // always true
967 // It is illegal for side-effects from x() or y() to occur. The simplest way to
968 // enforce that rule is to avoid inlining the right side entirely. However, it
969 // is safe for other types of binary expression to inline both sides.
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400970 Token::Kind op = binaryExpr.getOperator();
971 bool shortCircuitable = (op == Token::Kind::TK_LOGICALAND ||
972 op == Token::Kind::TK_LOGICALOR);
John Stiles93442622020-09-11 12:11:27 -0400973 if (!shortCircuitable) {
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400974 this->visitExpression(&binaryExpr.rightPointer());
John Stiles93442622020-09-11 12:11:27 -0400975 }
976 break;
977 }
978 case Expression::Kind::kConstructor: {
979 Constructor& constructorExpr = (*expr)->as<Constructor>();
980 for (std::unique_ptr<Expression>& arg : constructorExpr.fArguments) {
981 this->visitExpression(&arg);
982 }
983 break;
984 }
985 case Expression::Kind::kExternalFunctionCall: {
986 ExternalFunctionCall& funcCallExpr = (*expr)->as<ExternalFunctionCall>();
987 for (std::unique_ptr<Expression>& arg : funcCallExpr.fArguments) {
988 this->visitExpression(&arg);
989 }
990 break;
991 }
992 case Expression::Kind::kFunctionCall: {
993 FunctionCall& funcCallExpr = (*expr)->as<FunctionCall>();
994 for (std::unique_ptr<Expression>& arg : funcCallExpr.fArguments) {
995 this->visitExpression(&arg);
996 }
997 this->addInlineCandidate(expr);
998 break;
999 }
1000 case Expression::Kind::kIndex:{
1001 IndexExpression& indexExpr = (*expr)->as<IndexExpression>();
1002 this->visitExpression(&indexExpr.fBase);
1003 this->visitExpression(&indexExpr.fIndex);
1004 break;
1005 }
1006 case Expression::Kind::kPostfix: {
1007 PostfixExpression& postfixExpr = (*expr)->as<PostfixExpression>();
1008 this->visitExpression(&postfixExpr.fOperand);
1009 break;
1010 }
1011 case Expression::Kind::kPrefix: {
1012 PrefixExpression& prefixExpr = (*expr)->as<PrefixExpression>();
1013 this->visitExpression(&prefixExpr.fOperand);
1014 break;
1015 }
1016 case Expression::Kind::kSwizzle: {
1017 Swizzle& swizzleExpr = (*expr)->as<Swizzle>();
1018 this->visitExpression(&swizzleExpr.fBase);
1019 break;
1020 }
1021 case Expression::Kind::kTernary: {
1022 TernaryExpression& ternaryExpr = (*expr)->as<TernaryExpression>();
1023 // The test expression is a candidate for inlining.
1024 this->visitExpression(&ternaryExpr.fTest);
1025 // The true- and false-expressions cannot be inlined, because we are only
1026 // allowed to evaluate one side.
1027 break;
1028 }
1029 default:
1030 SkUNREACHABLE;
1031 }
1032 }
1033
1034 void addInlineCandidate(std::unique_ptr<Expression>* candidate) {
1035 fInlineCandidates.push_back(InlineCandidate{fSymbolTableStack.back(),
John Stiles915a38c2020-09-14 09:38:13 -04001036 find_parent_statement(fEnclosingStmtStack),
1037 fEnclosingStmtStack.back(),
1038 candidate});
John Stiles93442622020-09-11 12:11:27 -04001039 }
1040 };
1041
John Stiles93442622020-09-11 12:11:27 -04001042 InlineCandidateAnalyzer analyzer;
1043 analyzer.visit(program);
John Stiles915a38c2020-09-14 09:38:13 -04001044
1045 // For each of our candidate function-call sites, check if it is actually safe to inline.
1046 // Memoize our results so we don't check a function more than once.
John Stiles93442622020-09-11 12:11:27 -04001047 std::unordered_map<const FunctionDeclaration*, bool> inlinableMap; // <function, safe-to-inline>
John Stiles915a38c2020-09-14 09:38:13 -04001048 for (const InlineCandidate& candidate : analyzer.fInlineCandidates) {
John Stiles93442622020-09-11 12:11:27 -04001049 const FunctionCall& funcCall = (*candidate.fCandidateExpr)->as<FunctionCall>();
1050 const FunctionDeclaration* funcDecl = &funcCall.fFunction;
1051 if (inlinableMap.find(funcDecl) == inlinableMap.end()) {
1052 // We do not perform inlining on recursive calls to avoid an infinite death spiral of
1053 // inlining.
1054 int inlineThreshold = (funcDecl->fCallCount.load() > 1) ? fSettings->fInlineThreshold
1055 : INT_MAX;
1056 inlinableMap[funcDecl] = this->isSafeToInline(funcCall, inlineThreshold) &&
1057 !contains_recursive_call(*funcDecl);
John Stiles93442622020-09-11 12:11:27 -04001058 }
1059 }
1060
John Stiles915a38c2020-09-14 09:38:13 -04001061 // Inline the candidates where we've determined that it's safe to do so.
1062 std::unordered_set<const std::unique_ptr<Statement>*> enclosingStmtSet;
1063 bool madeChanges = false;
1064 for (const InlineCandidate& candidate : analyzer.fInlineCandidates) {
1065 FunctionCall& funcCall = (*candidate.fCandidateExpr)->as<FunctionCall>();
1066 const FunctionDeclaration* funcDecl = &funcCall.fFunction;
1067
1068 // If we determined that this candidate was not actually inlinable, skip it.
1069 if (!inlinableMap[funcDecl]) {
1070 continue;
1071 }
1072
1073 // Inlining two expressions using the same enclosing statement in the same inlining pass
1074 // does not work properly. If this happens, skip it; we'll get it in the next pass.
1075 auto [unusedIter, inserted] = enclosingStmtSet.insert(candidate.fEnclosingStmt);
1076 if (!inserted) {
1077 continue;
1078 }
1079
1080 // Convert the function call to its inlined equivalent.
1081 InlinedCall inlinedCall = this->inlineCall(&funcCall, candidate.fSymbols);
1082 if (inlinedCall.fInlinedBody) {
1083 // Ensure that the inlined body has a scope if it needs one.
John Stilesb61ee902020-09-21 12:26:59 -04001084 this->ensureScopedBlocks(inlinedCall.fInlinedBody.get(), candidate.fParentStmt);
John Stiles915a38c2020-09-14 09:38:13 -04001085
1086 // Move the enclosing statement to the end of the unscoped Block containing the inlined
1087 // function, then replace the enclosing statement with that Block.
1088 // Before:
1089 // fInlinedBody = Block{ stmt1, stmt2, stmt3 }
1090 // fEnclosingStmt = stmt4
1091 // After:
1092 // fInlinedBody = null
1093 // fEnclosingStmt = Block{ stmt1, stmt2, stmt3, stmt4 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001094 inlinedCall.fInlinedBody->children().push_back(std::move(*candidate.fEnclosingStmt));
John Stiles915a38c2020-09-14 09:38:13 -04001095 *candidate.fEnclosingStmt = std::move(inlinedCall.fInlinedBody);
1096 }
1097
1098 // Replace the candidate function call with our replacement expression.
1099 *candidate.fCandidateExpr = std::move(inlinedCall.fReplacementExpr);
1100 madeChanges = true;
1101
1102 // Note that nothing was destroyed except for the FunctionCall. All other nodes should
1103 // remain valid.
1104 }
1105
1106 return madeChanges;
John Stiles93442622020-09-11 12:11:27 -04001107}
1108
John Stiles44e96be2020-08-31 13:16:04 -04001109} // namespace SkSL