blob: 5b5f004e2302c0ca9ae2be526f74e95f5136dc78 [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();
225 class SetRefKindInExpression : public ProgramVisitor {
226 public:
227 SetRefKindInExpression(VariableReference::RefKind refKind) : fRefKind(refKind) {}
228 bool visitExpression(const Expression& expr) override {
229 if (expr.is<VariableReference>()) {
230 // TODO: create a const-savvy ProgramVisitor and remove const_cast
231 const_cast<VariableReference&>(expr.as<VariableReference>()).setRefKind(fRefKind);
232 }
233 return INHERITED::visitExpression(expr);
234 }
235
236 private:
237 VariableReference::RefKind fRefKind;
238
239 using INHERITED = ProgramVisitor;
240 };
241
242 SetRefKindInExpression{refKind}.visitExpression(*clone);
243 return clone;
244}
245
John Stiles44e96be2020-08-31 13:16:04 -0400246} // namespace
247
John Stilesb61ee902020-09-21 12:26:59 -0400248void Inliner::ensureScopedBlocks(Statement* inlinedBody, Statement* parentStmt) {
249 // No changes necessary if this statement isn't actually a block.
250 if (!inlinedBody || !inlinedBody->is<Block>()) {
251 return;
252 }
253
254 // No changes necessary if the parent statement doesn't require a scope.
255 if (!parentStmt || !(parentStmt->is<IfStatement>() || parentStmt->is<ForStatement>() ||
256 parentStmt->is<DoStatement>() || parentStmt->is<WhileStatement>())) {
257 return;
258 }
259
260 Block& block = inlinedBody->as<Block>();
261
262 // The inliner will create inlined function bodies as a Block containing multiple statements,
263 // but no scope. Normally, this is fine, but if this block is used as the statement for a
264 // do/for/if/while, this isn't actually possible to represent textually; a scope must be added
265 // for the generated code to match the intent. In the case of Blocks nested inside other Blocks,
266 // we add the scope to the outermost block if needed. Zero-statement blocks have similar
267 // issues--if we don't represent the Block textually somehow, we run the risk of accidentally
268 // absorbing the following statement into our loop--so we also add a scope to these.
269 for (Block* nestedBlock = &block;; ) {
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400270 if (nestedBlock->isScope()) {
John Stilesb61ee902020-09-21 12:26:59 -0400271 // We found an explicit scope; all is well.
272 return;
273 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400274 if (nestedBlock->children().size() != 1) {
John Stilesb61ee902020-09-21 12:26:59 -0400275 // We found a block with multiple (or zero) statements, but no scope? Let's add a scope
276 // to the outermost block.
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400277 block.setIsScope(true);
John Stilesb61ee902020-09-21 12:26:59 -0400278 return;
279 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400280 if (!nestedBlock->children()[0]->is<Block>()) {
John Stilesb61ee902020-09-21 12:26:59 -0400281 // This block has exactly one thing inside, and it's not another block. No need to scope
282 // it.
283 return;
284 }
285 // We have to go deeper.
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400286 nestedBlock = &nestedBlock->children()[0]->as<Block>();
John Stilesb61ee902020-09-21 12:26:59 -0400287 }
288}
289
John Stiles44e96be2020-08-31 13:16:04 -0400290void Inliner::reset(const Context& context, const Program::Settings& settings) {
291 fContext = &context;
292 fSettings = &settings;
293 fInlineVarCounter = 0;
294}
295
John Stilesc75abb82020-09-14 18:24:12 -0400296String Inliner::uniqueNameForInlineVar(const String& baseName, SymbolTable* symbolTable) {
297 // If the base name starts with an underscore, like "_coords", we can't append another
298 // underscore, because OpenGL disallows two consecutive underscores anywhere in the string. But
299 // in the general case, using the underscore as a splitter reads nicely enough that it's worth
300 // putting in this special case.
301 const char* splitter = baseName.startsWith("_") ? "" : "_";
302
303 // Append a unique numeric prefix to avoid name overlap. Check the symbol table to make sure
304 // we're not reusing an existing name. (Note that within a single compilation pass, this check
305 // isn't fully comprehensive, as code isn't always generated in top-to-bottom order.)
306 String uniqueName;
307 for (;;) {
308 uniqueName = String::printf("_%d%s%s", fInlineVarCounter++, splitter, baseName.c_str());
309 StringFragment frag{uniqueName.data(), uniqueName.length()};
310 if ((*symbolTable)[frag] == nullptr) {
311 break;
312 }
313 }
314
315 return uniqueName;
316}
317
John Stiles44e96be2020-08-31 13:16:04 -0400318std::unique_ptr<Expression> Inliner::inlineExpression(int offset,
319 VariableRewriteMap* varMap,
320 const Expression& expression) {
321 auto expr = [&](const std::unique_ptr<Expression>& e) -> std::unique_ptr<Expression> {
322 if (e) {
323 return this->inlineExpression(offset, varMap, *e);
324 }
325 return nullptr;
326 };
327 auto argList = [&](const std::vector<std::unique_ptr<Expression>>& originalArgs)
328 -> std::vector<std::unique_ptr<Expression>> {
329 std::vector<std::unique_ptr<Expression>> args;
330 args.reserve(originalArgs.size());
331 for (const std::unique_ptr<Expression>& arg : originalArgs) {
332 args.push_back(expr(arg));
333 }
334 return args;
335 };
336
Ethan Nicholase6592142020-09-08 10:22:09 -0400337 switch (expression.kind()) {
338 case Expression::Kind::kBinary: {
John Stiles44e96be2020-08-31 13:16:04 -0400339 const BinaryExpression& b = expression.as<BinaryExpression>();
340 return std::make_unique<BinaryExpression>(offset,
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400341 expr(b.leftPointer()),
342 b.getOperator(),
343 expr(b.rightPointer()),
Ethan Nicholas30d30222020-09-11 12:27:26 -0400344 &b.type());
John Stiles44e96be2020-08-31 13:16:04 -0400345 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400346 case Expression::Kind::kBoolLiteral:
347 case Expression::Kind::kIntLiteral:
348 case Expression::Kind::kFloatLiteral:
349 case Expression::Kind::kNullLiteral:
John Stiles44e96be2020-08-31 13:16:04 -0400350 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400351 case Expression::Kind::kConstructor: {
John Stiles44e96be2020-08-31 13:16:04 -0400352 const Constructor& constructor = expression.as<Constructor>();
Ethan Nicholas30d30222020-09-11 12:27:26 -0400353 return std::make_unique<Constructor>(offset, &constructor.type(),
John Stiles44e96be2020-08-31 13:16:04 -0400354 argList(constructor.fArguments));
355 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400356 case Expression::Kind::kExternalFunctionCall: {
John Stiles44e96be2020-08-31 13:16:04 -0400357 const ExternalFunctionCall& externalCall = expression.as<ExternalFunctionCall>();
Ethan Nicholas30d30222020-09-11 12:27:26 -0400358 return std::make_unique<ExternalFunctionCall>(offset, &externalCall.type(),
John Stiles44e96be2020-08-31 13:16:04 -0400359 externalCall.fFunction,
360 argList(externalCall.fArguments));
361 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400362 case Expression::Kind::kExternalValue:
John Stiles44e96be2020-08-31 13:16:04 -0400363 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400364 case Expression::Kind::kFieldAccess: {
John Stiles44e96be2020-08-31 13:16:04 -0400365 const FieldAccess& f = expression.as<FieldAccess>();
366 return std::make_unique<FieldAccess>(expr(f.fBase), f.fFieldIndex, f.fOwnerKind);
367 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400368 case Expression::Kind::kFunctionCall: {
John Stiles44e96be2020-08-31 13:16:04 -0400369 const FunctionCall& funcCall = expression.as<FunctionCall>();
Ethan Nicholas30d30222020-09-11 12:27:26 -0400370 return std::make_unique<FunctionCall>(offset, &funcCall.type(), funcCall.fFunction,
John Stiles44e96be2020-08-31 13:16:04 -0400371 argList(funcCall.fArguments));
372 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400373 case Expression::Kind::kFunctionReference:
Brian Osman2b3b35f2020-09-08 09:17:36 -0400374 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400375 case Expression::Kind::kIndex: {
John Stiles44e96be2020-08-31 13:16:04 -0400376 const IndexExpression& idx = expression.as<IndexExpression>();
377 return std::make_unique<IndexExpression>(*fContext, expr(idx.fBase), expr(idx.fIndex));
378 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400379 case Expression::Kind::kPrefix: {
John Stiles44e96be2020-08-31 13:16:04 -0400380 const PrefixExpression& p = expression.as<PrefixExpression>();
381 return std::make_unique<PrefixExpression>(p.fOperator, expr(p.fOperand));
382 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400383 case Expression::Kind::kPostfix: {
John Stiles44e96be2020-08-31 13:16:04 -0400384 const PostfixExpression& p = expression.as<PostfixExpression>();
385 return std::make_unique<PostfixExpression>(expr(p.fOperand), p.fOperator);
386 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400387 case Expression::Kind::kSetting:
John Stiles44e96be2020-08-31 13:16:04 -0400388 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400389 case Expression::Kind::kSwizzle: {
John Stiles44e96be2020-08-31 13:16:04 -0400390 const Swizzle& s = expression.as<Swizzle>();
391 return std::make_unique<Swizzle>(*fContext, expr(s.fBase), s.fComponents);
392 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400393 case Expression::Kind::kTernary: {
John Stiles44e96be2020-08-31 13:16:04 -0400394 const TernaryExpression& t = expression.as<TernaryExpression>();
395 return std::make_unique<TernaryExpression>(offset, expr(t.fTest),
396 expr(t.fIfTrue), expr(t.fIfFalse));
397 }
Brian Osman83ba9302020-09-11 13:33:46 -0400398 case Expression::Kind::kTypeReference:
399 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400400 case Expression::Kind::kVariableReference: {
John Stiles44e96be2020-08-31 13:16:04 -0400401 const VariableReference& v = expression.as<VariableReference>();
John Stilese41b4ee2020-09-28 12:28:16 -0400402 auto varMapIter = varMap->find(v.fVariable);
403 if (varMapIter != varMap->end()) {
404 return clone_with_ref_kind(*varMapIter->second, v.fRefKind);
John Stiles44e96be2020-08-31 13:16:04 -0400405 }
406 return v.clone();
407 }
408 default:
409 SkASSERT(false);
410 return nullptr;
411 }
412}
413
414std::unique_ptr<Statement> Inliner::inlineStatement(int offset,
415 VariableRewriteMap* varMap,
416 SymbolTable* symbolTableForStatement,
John Stilese41b4ee2020-09-28 12:28:16 -0400417 const Expression* resultExpr,
John Stiles44e96be2020-08-31 13:16:04 -0400418 bool haveEarlyReturns,
419 const Statement& statement) {
420 auto stmt = [&](const std::unique_ptr<Statement>& s) -> std::unique_ptr<Statement> {
421 if (s) {
John Stilesa5f3c312020-09-22 12:05:16 -0400422 return this->inlineStatement(offset, varMap, symbolTableForStatement, resultExpr,
John Stiles44e96be2020-08-31 13:16:04 -0400423 haveEarlyReturns, *s);
424 }
425 return nullptr;
426 };
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400427 auto blockStmts = [&](const Block& block) {
428 std::vector<std::unique_ptr<Statement>> result;
429 for (const std::unique_ptr<Statement>& child : block.children()) {
430 result.push_back(stmt(child));
431 }
432 return result;
433 };
John Stiles44e96be2020-08-31 13:16:04 -0400434 auto stmts = [&](const std::vector<std::unique_ptr<Statement>>& ss) {
435 std::vector<std::unique_ptr<Statement>> result;
436 for (const auto& s : ss) {
437 result.push_back(stmt(s));
438 }
439 return result;
440 };
441 auto expr = [&](const std::unique_ptr<Expression>& e) -> std::unique_ptr<Expression> {
442 if (e) {
443 return this->inlineExpression(offset, varMap, *e);
444 }
445 return nullptr;
446 };
Ethan Nicholase6592142020-09-08 10:22:09 -0400447 switch (statement.kind()) {
448 case Statement::Kind::kBlock: {
John Stiles44e96be2020-08-31 13:16:04 -0400449 const Block& b = statement.as<Block>();
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400450 return std::make_unique<Block>(offset, blockStmts(b), b.symbolTable(), b.isScope());
John Stiles44e96be2020-08-31 13:16:04 -0400451 }
452
Ethan Nicholase6592142020-09-08 10:22:09 -0400453 case Statement::Kind::kBreak:
454 case Statement::Kind::kContinue:
455 case Statement::Kind::kDiscard:
John Stiles44e96be2020-08-31 13:16:04 -0400456 return statement.clone();
457
Ethan Nicholase6592142020-09-08 10:22:09 -0400458 case Statement::Kind::kDo: {
John Stiles44e96be2020-08-31 13:16:04 -0400459 const DoStatement& d = statement.as<DoStatement>();
460 return std::make_unique<DoStatement>(offset, stmt(d.fStatement), expr(d.fTest));
461 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400462 case Statement::Kind::kExpression: {
John Stiles44e96be2020-08-31 13:16:04 -0400463 const ExpressionStatement& e = statement.as<ExpressionStatement>();
464 return std::make_unique<ExpressionStatement>(expr(e.fExpression));
465 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400466 case Statement::Kind::kFor: {
John Stiles44e96be2020-08-31 13:16:04 -0400467 const ForStatement& f = statement.as<ForStatement>();
468 // need to ensure initializer is evaluated first so that we've already remapped its
469 // declarations by the time we evaluate test & next
470 std::unique_ptr<Statement> initializer = stmt(f.fInitializer);
471 return std::make_unique<ForStatement>(offset, std::move(initializer), expr(f.fTest),
472 expr(f.fNext), stmt(f.fStatement), f.fSymbols);
473 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400474 case Statement::Kind::kIf: {
John Stiles44e96be2020-08-31 13:16:04 -0400475 const IfStatement& i = statement.as<IfStatement>();
476 return std::make_unique<IfStatement>(offset, i.fIsStatic, expr(i.fTest),
477 stmt(i.fIfTrue), stmt(i.fIfFalse));
478 }
John Stiles98c1f822020-09-09 14:18:53 -0400479 case Statement::Kind::kInlineMarker:
Ethan Nicholase6592142020-09-08 10:22:09 -0400480 case Statement::Kind::kNop:
John Stiles44e96be2020-08-31 13:16:04 -0400481 return statement.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400482 case Statement::Kind::kReturn: {
John Stiles44e96be2020-08-31 13:16:04 -0400483 const ReturnStatement& r = statement.as<ReturnStatement>();
484 if (r.fExpression) {
John Stilese41b4ee2020-09-28 12:28:16 -0400485 SkASSERT(resultExpr);
John Stilesa5f3c312020-09-22 12:05:16 -0400486 auto assignment =
487 std::make_unique<ExpressionStatement>(std::make_unique<BinaryExpression>(
488 offset,
John Stilese41b4ee2020-09-28 12:28:16 -0400489 clone_with_ref_kind(*resultExpr, VariableReference::kWrite_RefKind),
John Stilesa5f3c312020-09-22 12:05:16 -0400490 Token::Kind::TK_EQ,
491 expr(r.fExpression),
John Stilese41b4ee2020-09-28 12:28:16 -0400492 &resultExpr->type()));
John Stiles44e96be2020-08-31 13:16:04 -0400493 if (haveEarlyReturns) {
494 std::vector<std::unique_ptr<Statement>> block;
495 block.push_back(std::move(assignment));
496 block.emplace_back(new BreakStatement(offset));
497 return std::make_unique<Block>(offset, std::move(block), /*symbols=*/nullptr,
498 /*isScope=*/true);
499 } else {
500 return std::move(assignment);
501 }
502 } else {
503 if (haveEarlyReturns) {
504 return std::make_unique<BreakStatement>(offset);
505 } else {
506 return std::make_unique<Nop>();
507 }
508 }
509 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400510 case Statement::Kind::kSwitch: {
John Stiles44e96be2020-08-31 13:16:04 -0400511 const SwitchStatement& ss = statement.as<SwitchStatement>();
512 std::vector<std::unique_ptr<SwitchCase>> cases;
513 for (const auto& sc : ss.fCases) {
514 cases.emplace_back(new SwitchCase(offset, expr(sc->fValue),
515 stmts(sc->fStatements)));
516 }
517 return std::make_unique<SwitchStatement>(offset, ss.fIsStatic, expr(ss.fValue),
518 std::move(cases), ss.fSymbols);
519 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400520 case Statement::Kind::kVarDeclaration: {
John Stiles44e96be2020-08-31 13:16:04 -0400521 const VarDeclaration& decl = statement.as<VarDeclaration>();
522 std::vector<std::unique_ptr<Expression>> sizes;
523 for (const auto& size : decl.fSizes) {
524 sizes.push_back(expr(size));
525 }
526 std::unique_ptr<Expression> initialValue = expr(decl.fValue);
527 const Variable* old = decl.fVar;
John Stilesc75abb82020-09-14 18:24:12 -0400528 // We assign unique names to inlined variables--scopes hide most of the problems in this
529 // regard, but see `InlinerAvoidsVariableNameOverlap` for a counterexample where unique
530 // names are important.
531 auto name = std::make_unique<String>(
532 this->uniqueNameForInlineVar(String(old->fName), symbolTableForStatement));
John Stiles44e96be2020-08-31 13:16:04 -0400533 const String* namePtr = symbolTableForStatement->takeOwnershipOfString(std::move(name));
Ethan Nicholas30d30222020-09-11 12:27:26 -0400534 const Type* typePtr = copy_if_needed(&old->type(), *symbolTableForStatement);
John Stiles44e96be2020-08-31 13:16:04 -0400535 const Variable* clone = symbolTableForStatement->takeOwnershipOfSymbol(
536 std::make_unique<Variable>(offset,
537 old->fModifiers,
538 namePtr->c_str(),
Ethan Nicholas30d30222020-09-11 12:27:26 -0400539 typePtr,
John Stiles44e96be2020-08-31 13:16:04 -0400540 old->fStorage,
541 initialValue.get()));
John Stilese41b4ee2020-09-28 12:28:16 -0400542 (*varMap)[old] = std::make_unique<VariableReference>(offset, clone);
John Stiles44e96be2020-08-31 13:16:04 -0400543 return std::make_unique<VarDeclaration>(clone, std::move(sizes),
544 std::move(initialValue));
545 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400546 case Statement::Kind::kVarDeclarations: {
John Stiles44e96be2020-08-31 13:16:04 -0400547 const VarDeclarations& decls = *statement.as<VarDeclarationsStatement>().fDeclaration;
548 std::vector<std::unique_ptr<VarDeclaration>> vars;
549 for (const auto& var : decls.fVars) {
550 vars.emplace_back(&stmt(var).release()->as<VarDeclaration>());
551 }
552 const Type* typePtr = copy_if_needed(&decls.fBaseType, *symbolTableForStatement);
553 return std::unique_ptr<Statement>(new VarDeclarationsStatement(
554 std::make_unique<VarDeclarations>(offset, typePtr, std::move(vars))));
555 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400556 case Statement::Kind::kWhile: {
John Stiles44e96be2020-08-31 13:16:04 -0400557 const WhileStatement& w = statement.as<WhileStatement>();
558 return std::make_unique<WhileStatement>(offset, expr(w.fTest), stmt(w.fStatement));
559 }
560 default:
561 SkASSERT(false);
562 return nullptr;
563 }
564}
565
John Stiles6eadf132020-09-08 10:16:10 -0400566Inliner::InlinedCall Inliner::inlineCall(FunctionCall* call,
John Stiles44e96be2020-08-31 13:16:04 -0400567 SymbolTable* symbolTableForCall) {
568 // Inlining is more complicated here than in a typical compiler, because we have to have a
569 // high-level IR and can't just drop statements into the middle of an expression or even use
570 // gotos.
571 //
572 // Since we can't insert statements into an expression, we run the inline function as extra
573 // statements before the statement we're currently processing, relying on a lack of execution
574 // order guarantees. Since we can't use gotos (which are normally used to replace return
575 // statements), we wrap the whole function in a loop and use break statements to jump to the
576 // end.
577 SkASSERT(fSettings);
578 SkASSERT(fContext);
579 SkASSERT(call);
580 SkASSERT(this->isSafeToInline(*call, /*inlineThreshold=*/INT_MAX));
581
John Stiles44e96be2020-08-31 13:16:04 -0400582 std::vector<std::unique_ptr<Expression>>& arguments = call->fArguments;
John Stiles6eadf132020-09-08 10:16:10 -0400583 const int offset = call->fOffset;
John Stiles44e96be2020-08-31 13:16:04 -0400584 const FunctionDefinition& function = *call->fFunction.fDefinition;
John Stiles6eadf132020-09-08 10:16:10 -0400585 const bool hasEarlyReturn = has_early_return(function);
586
John Stiles44e96be2020-08-31 13:16:04 -0400587 InlinedCall inlinedCall;
John Stiles6eadf132020-09-08 10:16:10 -0400588 inlinedCall.fInlinedBody = std::make_unique<Block>(offset,
589 std::vector<std::unique_ptr<Statement>>{},
590 /*symbols=*/nullptr,
591 /*isScope=*/false);
John Stiles98c1f822020-09-09 14:18:53 -0400592
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400593 Block& inlinedBody = *inlinedCall.fInlinedBody;
594 inlinedBody.children().reserve(1 + // Inline marker
595 1 + // Result variable
596 arguments.size() + // Function arguments (passing in)
John Stilese41b4ee2020-09-28 12:28:16 -0400597 arguments.size() + // Function arguments (copy out-params back)
598 1); // Inlined code (Block or do-while loop)
John Stiles98c1f822020-09-09 14:18:53 -0400599
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400600 inlinedBody.children().push_back(std::make_unique<InlineMarker>(call->fFunction));
John Stiles44e96be2020-08-31 13:16:04 -0400601
John Stilese41b4ee2020-09-28 12:28:16 -0400602 auto makeInlineVar =
603 [&](const String& baseName, const Type* type, Modifiers modifiers,
604 std::unique_ptr<Expression>* initialValue) -> std::unique_ptr<Expression> {
John Stilesa003e812020-09-11 09:43:49 -0400605 // $floatLiteral or $intLiteral aren't real types that we can use for scratch variables, so
606 // replace them if they ever appear here. If this happens, we likely forgot to coerce a type
607 // somewhere during compilation.
608 if (type == fContext->fFloatLiteral_Type.get()) {
John Stilesd2be5c52020-09-11 14:58:06 -0400609 SkDEBUGFAIL("found a $floatLiteral type while inlining");
John Stilesa003e812020-09-11 09:43:49 -0400610 type = fContext->fFloat_Type.get();
611 } else if (type == fContext->fIntLiteral_Type.get()) {
John Stilesd2be5c52020-09-11 14:58:06 -0400612 SkDEBUGFAIL("found an $intLiteral type while inlining");
John Stilesa003e812020-09-11 09:43:49 -0400613 type = fContext->fInt_Type.get();
614 }
615
John Stilesc75abb82020-09-14 18:24:12 -0400616 // Provide our new variable with a unique name, and add it to our symbol table.
617 String uniqueName = this->uniqueNameForInlineVar(baseName, symbolTableForCall);
John Stilescf936f92020-08-31 17:18:45 -0400618 const String* namePtr = symbolTableForCall->takeOwnershipOfString(
619 std::make_unique<String>(std::move(uniqueName)));
John Stiles44e96be2020-08-31 13:16:04 -0400620 StringFragment nameFrag{namePtr->c_str(), namePtr->length()};
621
622 // Add our new variable to the symbol table.
Ethan Nicholas30d30222020-09-11 12:27:26 -0400623 auto newVar = std::make_unique<Variable>(/*offset=*/-1, Modifiers(), nameFrag, type,
John Stiles44e96be2020-08-31 13:16:04 -0400624 Variable::kLocal_Storage, initialValue->get());
625 const Variable* variableSymbol = symbolTableForCall->add(nameFrag, std::move(newVar));
626
627 // Prepare the variable declaration (taking extra care with `out` params to not clobber any
628 // initial value).
629 std::vector<std::unique_ptr<VarDeclaration>> variables;
630 if (initialValue && (modifiers.fFlags & Modifiers::kOut_Flag)) {
631 variables.push_back(std::make_unique<VarDeclaration>(
632 variableSymbol, /*sizes=*/std::vector<std::unique_ptr<Expression>>{},
633 (*initialValue)->clone()));
634 } else {
635 variables.push_back(std::make_unique<VarDeclaration>(
636 variableSymbol, /*sizes=*/std::vector<std::unique_ptr<Expression>>{},
637 std::move(*initialValue)));
638 }
639
640 // Add the new variable-declaration statement to our block of extra statements.
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400641 inlinedBody.children().push_back(std::make_unique<VarDeclarationsStatement>(
John Stilesa003e812020-09-11 09:43:49 -0400642 std::make_unique<VarDeclarations>(offset, type, std::move(variables))));
John Stiles44e96be2020-08-31 13:16:04 -0400643
John Stilese41b4ee2020-09-28 12:28:16 -0400644 return std::make_unique<VariableReference>(offset, variableSymbol);
John Stiles44e96be2020-08-31 13:16:04 -0400645 };
646
647 // Create a variable to hold the result in the extra statements (excepting void).
John Stilese41b4ee2020-09-28 12:28:16 -0400648 std::unique_ptr<Expression> resultExpr;
John Stiles44e96be2020-08-31 13:16:04 -0400649 if (function.fDeclaration.fReturnType != *fContext->fVoid_Type) {
John Stiles44e96be2020-08-31 13:16:04 -0400650 std::unique_ptr<Expression> noInitialValue;
John Stilese41b4ee2020-09-28 12:28:16 -0400651 resultExpr = makeInlineVar(String(function.fDeclaration.fName),
652 &function.fDeclaration.fReturnType,
653 Modifiers{}, &noInitialValue);
654 }
John Stiles44e96be2020-08-31 13:16:04 -0400655
656 // Create variables in the extra statements to hold the arguments, and assign the arguments to
657 // them.
658 VariableRewriteMap varMap;
John Stilese41b4ee2020-09-28 12:28:16 -0400659 std::vector<int> argsToCopyBack;
John Stiles44e96be2020-08-31 13:16:04 -0400660 for (int i = 0; i < (int) arguments.size(); ++i) {
661 const Variable* param = function.fDeclaration.fParameters[i];
John Stilese41b4ee2020-09-28 12:28:16 -0400662 bool isOutParam = param->fModifiers.fFlags & Modifiers::kOut_Flag;
John Stiles44e96be2020-08-31 13:16:04 -0400663
John Stilese41b4ee2020-09-28 12:28:16 -0400664 // If this is a plain VariableReference...
John Stilesa003e812020-09-11 09:43:49 -0400665 if (arguments[i]->is<VariableReference>()) {
John Stilese41b4ee2020-09-28 12:28:16 -0400666 // ... and it's an `out` param, or it isn't written to within the inline function...
667 if (isOutParam || !Analysis::StatementWritesToVariable(*function.fBody, *param)) {
668 // ... we don't need to copy it at all! We can just use the existing variable.
669 varMap[param] = arguments[i]->as<VariableReference>().clone();
John Stiles44e96be2020-08-31 13:16:04 -0400670 continue;
671 }
672 }
673
John Stilese41b4ee2020-09-28 12:28:16 -0400674 if (isOutParam) {
675 argsToCopyBack.push_back(i);
676 }
677
Ethan Nicholas30d30222020-09-11 12:27:26 -0400678 varMap[param] = makeInlineVar(String(param->fName), &arguments[i]->type(),
679 param->fModifiers, &arguments[i]);
John Stiles44e96be2020-08-31 13:16:04 -0400680 }
681
682 const Block& body = function.fBody->as<Block>();
John Stiles44e96be2020-08-31 13:16:04 -0400683 auto inlineBlock = std::make_unique<Block>(offset, std::vector<std::unique_ptr<Statement>>{});
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400684 inlineBlock->children().reserve(body.children().size());
685 for (const std::unique_ptr<Statement>& stmt : body.children()) {
686 inlineBlock->children().push_back(this->inlineStatement(
John Stilese41b4ee2020-09-28 12:28:16 -0400687 offset, &varMap, symbolTableForCall, resultExpr.get(), hasEarlyReturn, *stmt));
John Stiles44e96be2020-08-31 13:16:04 -0400688 }
689 if (hasEarlyReturn) {
690 // Since we output to backends that don't have a goto statement (which would normally be
691 // used to perform an early return), we fake it by wrapping the function in a
692 // do { } while (false); and then use break statements to jump to the end in order to
693 // emulate a goto.
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400694 inlinedBody.children().push_back(std::make_unique<DoStatement>(
John Stiles44e96be2020-08-31 13:16:04 -0400695 /*offset=*/-1,
696 std::move(inlineBlock),
697 std::make_unique<BoolLiteral>(*fContext, offset, /*value=*/false)));
698 } else {
John Stiles6eadf132020-09-08 10:16:10 -0400699 // No early returns, so we can just dump the code in. We still need to keep the block so we
700 // don't get name conflicts with locals.
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400701 inlinedBody.children().push_back(std::move(inlineBlock));
John Stiles44e96be2020-08-31 13:16:04 -0400702 }
703
John Stilese41b4ee2020-09-28 12:28:16 -0400704 // Copy back the values of `out` parameters into their real destinations.
705 for (int i : argsToCopyBack) {
John Stiles44e96be2020-08-31 13:16:04 -0400706 const Variable* p = function.fDeclaration.fParameters[i];
John Stilese41b4ee2020-09-28 12:28:16 -0400707 SkASSERT(varMap.find(p) != varMap.end());
708 inlinedBody.children().push_back(
709 std::make_unique<ExpressionStatement>(std::make_unique<BinaryExpression>(
710 offset,
711 clone_with_ref_kind(*arguments[i], VariableReference::kWrite_RefKind),
712 Token::Kind::TK_EQ,
713 std::move(varMap[p]),
714 &arguments[i]->type())));
John Stiles44e96be2020-08-31 13:16:04 -0400715 }
716
John Stilese41b4ee2020-09-28 12:28:16 -0400717 if (resultExpr != nullptr) {
718 // Return our result variable as our replacement expression.
719 SkASSERT(resultExpr->as<VariableReference>().fRefKind == VariableReference::kRead_RefKind);
720 inlinedCall.fReplacementExpr = std::move(resultExpr);
John Stiles44e96be2020-08-31 13:16:04 -0400721 } else {
722 // It's a void function, so it doesn't actually result in anything, but we have to return
723 // something non-null as a standin.
724 inlinedCall.fReplacementExpr = std::make_unique<BoolLiteral>(*fContext, offset,
725 /*value=*/false);
726 }
727
John Stiles44e96be2020-08-31 13:16:04 -0400728 return inlinedCall;
729}
730
John Stiles93442622020-09-11 12:11:27 -0400731bool Inliner::isSafeToInline(const FunctionCall& functionCall, int inlineThreshold) {
John Stiles44e96be2020-08-31 13:16:04 -0400732 SkASSERT(fSettings);
733
734 if (functionCall.fFunction.fDefinition == nullptr) {
735 // Can't inline something if we don't actually have its definition.
736 return false;
737 }
738 const FunctionDefinition& functionDef = *functionCall.fFunction.fDefinition;
739 if (inlineThreshold < INT_MAX) {
740 if (!(functionDef.fDeclaration.fModifiers.fFlags & Modifiers::kInline_Flag) &&
741 Analysis::NodeCount(functionDef) >= inlineThreshold) {
742 // The function exceeds our maximum inline size and is not flagged 'inline'.
743 return false;
744 }
745 }
John Stiles44e96be2020-08-31 13:16:04 -0400746 if (!fSettings->fCaps || !fSettings->fCaps->canUseDoLoops()) {
747 // We don't have do-while loops. We use do-while loops to simulate early returns, so we
748 // can't inline functions that have an early return.
749 bool hasEarlyReturn = has_early_return(functionDef);
750
751 // If we didn't detect an early return, there shouldn't be any returns in breakable
752 // constructs either.
753 SkASSERT(hasEarlyReturn || count_returns_in_breakable_constructs(functionDef) == 0);
754 return !hasEarlyReturn;
755 }
756 // We have do-while loops, but we don't have any mechanism to simulate early returns within a
757 // breakable construct (switch/for/do/while), so we can't inline if there's a return inside one.
758 bool hasReturnInBreakableConstruct = (count_returns_in_breakable_constructs(functionDef) > 0);
759
760 // If we detected returns in breakable constructs, we should also detect an early return.
761 SkASSERT(!hasReturnInBreakableConstruct || has_early_return(functionDef));
762 return !hasReturnInBreakableConstruct;
763}
764
John Stiles93442622020-09-11 12:11:27 -0400765bool Inliner::analyze(Program& program) {
766 // A candidate function for inlining, containing everything that `inlineCall` needs.
767 struct InlineCandidate {
John Stiles915a38c2020-09-14 09:38:13 -0400768 SymbolTable* fSymbols; // the SymbolTable of the candidate
769 Statement* fParentStmt; // the parent Statement of the enclosing stmt
770 std::unique_ptr<Statement>* fEnclosingStmt; // the Statement containing the candidate
771 std::unique_ptr<Expression>* fCandidateExpr; // the candidate FunctionCall to be inlined
John Stiles93442622020-09-11 12:11:27 -0400772 };
773
774 // This is structured much like a ProgramVisitor, but does not actually use ProgramVisitor.
775 // The analyzer needs to keep track of the `unique_ptr<T>*` of statements and expressions so
776 // that they can later be replaced, and ProgramVisitor does not provide this; it only provides a
777 // `const T&`.
778 class InlineCandidateAnalyzer {
779 public:
780 // A list of all the inlining candidates we found during analysis.
781 std::vector<InlineCandidate> fInlineCandidates;
782 // A stack of the symbol tables; since most nodes don't have one, expected to be shallower
783 // than the enclosing-statement stack.
784 std::vector<SymbolTable*> fSymbolTableStack;
785 // A stack of "enclosing" statements--these would be suitable for the inliner to use for
786 // adding new instructions. Not all statements are suitable (e.g. a for-loop's initializer).
787 // The inliner might replace a statement with a block containing the statement.
788 std::vector<std::unique_ptr<Statement>*> fEnclosingStmtStack;
789
790 void visit(Program& program) {
791 fSymbolTableStack.push_back(program.fSymbols.get());
792
793 for (ProgramElement& pe : program) {
794 this->visitProgramElement(&pe);
795 }
796
797 fSymbolTableStack.pop_back();
798 }
799
800 void visitProgramElement(ProgramElement* pe) {
801 switch (pe->kind()) {
802 case ProgramElement::Kind::kFunction: {
803 FunctionDefinition& funcDef = pe->as<FunctionDefinition>();
804 this->visitStatement(&funcDef.fBody);
805 break;
806 }
807 default:
808 // The inliner can't operate outside of a function's scope.
809 break;
810 }
811 }
812
813 void visitStatement(std::unique_ptr<Statement>* stmt,
814 bool isViableAsEnclosingStatement = true) {
815 if (!*stmt) {
816 return;
817 }
818
819 size_t oldEnclosingStmtStackSize = fEnclosingStmtStack.size();
820 size_t oldSymbolStackSize = fSymbolTableStack.size();
821
822 if (isViableAsEnclosingStatement) {
823 fEnclosingStmtStack.push_back(stmt);
824 }
825
826 switch ((*stmt)->kind()) {
827 case Statement::Kind::kBreak:
828 case Statement::Kind::kContinue:
829 case Statement::Kind::kDiscard:
830 case Statement::Kind::kInlineMarker:
831 case Statement::Kind::kNop:
832 break;
833
834 case Statement::Kind::kBlock: {
835 Block& block = (*stmt)->as<Block>();
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400836 if (block.symbolTable()) {
837 fSymbolTableStack.push_back(block.symbolTable().get());
John Stiles93442622020-09-11 12:11:27 -0400838 }
839
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400840 for (std::unique_ptr<Statement>& stmt : block.children()) {
841 this->visitStatement(&stmt);
John Stiles93442622020-09-11 12:11:27 -0400842 }
843 break;
844 }
845 case Statement::Kind::kDo: {
846 DoStatement& doStmt = (*stmt)->as<DoStatement>();
847 // The loop body is a candidate for inlining.
848 this->visitStatement(&doStmt.fStatement);
849 // The inliner isn't smart enough to inline the test-expression for a do-while
850 // loop at this time. There are two limitations:
851 // - We would need to insert the inlined-body block at the very end of the do-
852 // statement's inner fStatement. We don't support that today, but it's doable.
853 // - We cannot inline the test expression if the loop uses `continue` anywhere;
854 // that would skip over the inlined block that evaluates the test expression.
855 // There isn't a good fix for this--any workaround would be more complex than
856 // the cost of a function call. However, loops that don't use `continue` would
857 // still be viable candidates for inlining.
858 break;
859 }
860 case Statement::Kind::kExpression: {
861 ExpressionStatement& expr = (*stmt)->as<ExpressionStatement>();
862 this->visitExpression(&expr.fExpression);
863 break;
864 }
865 case Statement::Kind::kFor: {
866 ForStatement& forStmt = (*stmt)->as<ForStatement>();
867 if (forStmt.fSymbols) {
868 fSymbolTableStack.push_back(forStmt.fSymbols.get());
869 }
870
871 // The initializer and loop body are candidates for inlining.
872 this->visitStatement(&forStmt.fInitializer,
873 /*isViableAsEnclosingStatement=*/false);
874 this->visitStatement(&forStmt.fStatement);
875
876 // The inliner isn't smart enough to inline the test- or increment-expressions
877 // of a for loop loop at this time. There are a handful of limitations:
878 // - We would need to insert the test-expression block at the very beginning of
879 // the for-loop's inner fStatement, and the increment-expression block at the
880 // very end. We don't support that today, but it's doable.
881 // - The for-loop's built-in test-expression would need to be dropped entirely,
882 // and the loop would be halted via a break statement at the end of the
883 // inlined test-expression. This is again something we don't support today,
884 // but it could be implemented.
885 // - We cannot inline the increment-expression if the loop uses `continue`
886 // anywhere; that would skip over the inlined block that evaluates the
887 // increment expression. There isn't a good fix for this--any workaround would
888 // be more complex than the cost of a function call. However, loops that don't
889 // use `continue` would still be viable candidates for increment-expression
890 // inlining.
891 break;
892 }
893 case Statement::Kind::kIf: {
894 IfStatement& ifStmt = (*stmt)->as<IfStatement>();
895 this->visitExpression(&ifStmt.fTest);
896 this->visitStatement(&ifStmt.fIfTrue);
897 this->visitStatement(&ifStmt.fIfFalse);
898 break;
899 }
900 case Statement::Kind::kReturn: {
901 ReturnStatement& returnStmt = (*stmt)->as<ReturnStatement>();
902 this->visitExpression(&returnStmt.fExpression);
903 break;
904 }
905 case Statement::Kind::kSwitch: {
906 SwitchStatement& switchStmt = (*stmt)->as<SwitchStatement>();
907 if (switchStmt.fSymbols) {
908 fSymbolTableStack.push_back(switchStmt.fSymbols.get());
909 }
910
911 this->visitExpression(&switchStmt.fValue);
912 for (std::unique_ptr<SwitchCase>& switchCase : switchStmt.fCases) {
913 // The switch-case's fValue cannot be a FunctionCall; skip it.
914 for (std::unique_ptr<Statement>& caseBlock : switchCase->fStatements) {
915 this->visitStatement(&caseBlock);
916 }
917 }
918 break;
919 }
920 case Statement::Kind::kVarDeclaration: {
921 VarDeclaration& varDeclStmt = (*stmt)->as<VarDeclaration>();
922 // Don't need to scan the declaration's sizes; those are always IntLiterals.
923 this->visitExpression(&varDeclStmt.fValue);
924 break;
925 }
926 case Statement::Kind::kVarDeclarations: {
927 VarDeclarationsStatement& varDecls = (*stmt)->as<VarDeclarationsStatement>();
928 for (std::unique_ptr<Statement>& varDecl : varDecls.fDeclaration->fVars) {
929 this->visitStatement(&varDecl, /*isViableAsEnclosingStatement=*/false);
930 }
931 break;
932 }
933 case Statement::Kind::kWhile: {
934 WhileStatement& whileStmt = (*stmt)->as<WhileStatement>();
935 // The loop body is a candidate for inlining.
936 this->visitStatement(&whileStmt.fStatement);
937 // The inliner isn't smart enough to inline the test-expression for a while
938 // loop at this time. There are two limitations:
939 // - We would need to insert the inlined-body block at the very beginning of the
940 // while loop's inner fStatement. We don't support that today, but it's
941 // doable.
942 // - The while-loop's built-in test-expression would need to be replaced with a
943 // `true` BoolLiteral, and the loop would be halted via a break statement at
944 // the end of the inlined test-expression. This is again something we don't
945 // support today, but it could be implemented.
946 break;
947 }
948 default:
949 SkUNREACHABLE;
950 }
951
952 // Pop our symbol and enclosing-statement stacks.
953 fSymbolTableStack.resize(oldSymbolStackSize);
954 fEnclosingStmtStack.resize(oldEnclosingStmtStackSize);
955 }
956
957 void visitExpression(std::unique_ptr<Expression>* expr) {
958 if (!*expr) {
959 return;
960 }
961
962 switch ((*expr)->kind()) {
963 case Expression::Kind::kBoolLiteral:
964 case Expression::Kind::kDefined:
965 case Expression::Kind::kExternalValue:
966 case Expression::Kind::kFieldAccess:
967 case Expression::Kind::kFloatLiteral:
968 case Expression::Kind::kFunctionReference:
969 case Expression::Kind::kIntLiteral:
970 case Expression::Kind::kNullLiteral:
971 case Expression::Kind::kSetting:
972 case Expression::Kind::kTypeReference:
973 case Expression::Kind::kVariableReference:
974 // Nothing to scan here.
975 break;
976
977 case Expression::Kind::kBinary: {
978 BinaryExpression& binaryExpr = (*expr)->as<BinaryExpression>();
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400979 this->visitExpression(&binaryExpr.leftPointer());
John Stiles93442622020-09-11 12:11:27 -0400980
981 // Logical-and and logical-or binary expressions do not inline the right side,
982 // because that would invalidate short-circuiting. That is, when evaluating
983 // expressions like these:
984 // (false && x()) // always false
985 // (true || y()) // always true
986 // It is illegal for side-effects from x() or y() to occur. The simplest way to
987 // enforce that rule is to avoid inlining the right side entirely. However, it
988 // is safe for other types of binary expression to inline both sides.
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400989 Token::Kind op = binaryExpr.getOperator();
990 bool shortCircuitable = (op == Token::Kind::TK_LOGICALAND ||
991 op == Token::Kind::TK_LOGICALOR);
John Stiles93442622020-09-11 12:11:27 -0400992 if (!shortCircuitable) {
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400993 this->visitExpression(&binaryExpr.rightPointer());
John Stiles93442622020-09-11 12:11:27 -0400994 }
995 break;
996 }
997 case Expression::Kind::kConstructor: {
998 Constructor& constructorExpr = (*expr)->as<Constructor>();
999 for (std::unique_ptr<Expression>& arg : constructorExpr.fArguments) {
1000 this->visitExpression(&arg);
1001 }
1002 break;
1003 }
1004 case Expression::Kind::kExternalFunctionCall: {
1005 ExternalFunctionCall& funcCallExpr = (*expr)->as<ExternalFunctionCall>();
1006 for (std::unique_ptr<Expression>& arg : funcCallExpr.fArguments) {
1007 this->visitExpression(&arg);
1008 }
1009 break;
1010 }
1011 case Expression::Kind::kFunctionCall: {
1012 FunctionCall& funcCallExpr = (*expr)->as<FunctionCall>();
1013 for (std::unique_ptr<Expression>& arg : funcCallExpr.fArguments) {
1014 this->visitExpression(&arg);
1015 }
1016 this->addInlineCandidate(expr);
1017 break;
1018 }
1019 case Expression::Kind::kIndex:{
1020 IndexExpression& indexExpr = (*expr)->as<IndexExpression>();
1021 this->visitExpression(&indexExpr.fBase);
1022 this->visitExpression(&indexExpr.fIndex);
1023 break;
1024 }
1025 case Expression::Kind::kPostfix: {
1026 PostfixExpression& postfixExpr = (*expr)->as<PostfixExpression>();
1027 this->visitExpression(&postfixExpr.fOperand);
1028 break;
1029 }
1030 case Expression::Kind::kPrefix: {
1031 PrefixExpression& prefixExpr = (*expr)->as<PrefixExpression>();
1032 this->visitExpression(&prefixExpr.fOperand);
1033 break;
1034 }
1035 case Expression::Kind::kSwizzle: {
1036 Swizzle& swizzleExpr = (*expr)->as<Swizzle>();
1037 this->visitExpression(&swizzleExpr.fBase);
1038 break;
1039 }
1040 case Expression::Kind::kTernary: {
1041 TernaryExpression& ternaryExpr = (*expr)->as<TernaryExpression>();
1042 // The test expression is a candidate for inlining.
1043 this->visitExpression(&ternaryExpr.fTest);
1044 // The true- and false-expressions cannot be inlined, because we are only
1045 // allowed to evaluate one side.
1046 break;
1047 }
1048 default:
1049 SkUNREACHABLE;
1050 }
1051 }
1052
1053 void addInlineCandidate(std::unique_ptr<Expression>* candidate) {
1054 fInlineCandidates.push_back(InlineCandidate{fSymbolTableStack.back(),
John Stiles915a38c2020-09-14 09:38:13 -04001055 find_parent_statement(fEnclosingStmtStack),
1056 fEnclosingStmtStack.back(),
1057 candidate});
John Stiles93442622020-09-11 12:11:27 -04001058 }
1059 };
1060
John Stiles93442622020-09-11 12:11:27 -04001061 InlineCandidateAnalyzer analyzer;
1062 analyzer.visit(program);
John Stiles915a38c2020-09-14 09:38:13 -04001063
1064 // For each of our candidate function-call sites, check if it is actually safe to inline.
1065 // Memoize our results so we don't check a function more than once.
John Stiles93442622020-09-11 12:11:27 -04001066 std::unordered_map<const FunctionDeclaration*, bool> inlinableMap; // <function, safe-to-inline>
John Stiles915a38c2020-09-14 09:38:13 -04001067 for (const InlineCandidate& candidate : analyzer.fInlineCandidates) {
John Stiles93442622020-09-11 12:11:27 -04001068 const FunctionCall& funcCall = (*candidate.fCandidateExpr)->as<FunctionCall>();
1069 const FunctionDeclaration* funcDecl = &funcCall.fFunction;
1070 if (inlinableMap.find(funcDecl) == inlinableMap.end()) {
1071 // We do not perform inlining on recursive calls to avoid an infinite death spiral of
1072 // inlining.
1073 int inlineThreshold = (funcDecl->fCallCount.load() > 1) ? fSettings->fInlineThreshold
1074 : INT_MAX;
1075 inlinableMap[funcDecl] = this->isSafeToInline(funcCall, inlineThreshold) &&
1076 !contains_recursive_call(*funcDecl);
John Stiles93442622020-09-11 12:11:27 -04001077 }
1078 }
1079
John Stiles915a38c2020-09-14 09:38:13 -04001080 // Inline the candidates where we've determined that it's safe to do so.
1081 std::unordered_set<const std::unique_ptr<Statement>*> enclosingStmtSet;
1082 bool madeChanges = false;
1083 for (const InlineCandidate& candidate : analyzer.fInlineCandidates) {
1084 FunctionCall& funcCall = (*candidate.fCandidateExpr)->as<FunctionCall>();
1085 const FunctionDeclaration* funcDecl = &funcCall.fFunction;
1086
1087 // If we determined that this candidate was not actually inlinable, skip it.
1088 if (!inlinableMap[funcDecl]) {
1089 continue;
1090 }
1091
1092 // Inlining two expressions using the same enclosing statement in the same inlining pass
1093 // does not work properly. If this happens, skip it; we'll get it in the next pass.
1094 auto [unusedIter, inserted] = enclosingStmtSet.insert(candidate.fEnclosingStmt);
1095 if (!inserted) {
1096 continue;
1097 }
1098
1099 // Convert the function call to its inlined equivalent.
1100 InlinedCall inlinedCall = this->inlineCall(&funcCall, candidate.fSymbols);
1101 if (inlinedCall.fInlinedBody) {
1102 // Ensure that the inlined body has a scope if it needs one.
John Stilesb61ee902020-09-21 12:26:59 -04001103 this->ensureScopedBlocks(inlinedCall.fInlinedBody.get(), candidate.fParentStmt);
John Stiles915a38c2020-09-14 09:38:13 -04001104
1105 // Move the enclosing statement to the end of the unscoped Block containing the inlined
1106 // function, then replace the enclosing statement with that Block.
1107 // Before:
1108 // fInlinedBody = Block{ stmt1, stmt2, stmt3 }
1109 // fEnclosingStmt = stmt4
1110 // After:
1111 // fInlinedBody = null
1112 // fEnclosingStmt = Block{ stmt1, stmt2, stmt3, stmt4 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001113 inlinedCall.fInlinedBody->children().push_back(std::move(*candidate.fEnclosingStmt));
John Stiles915a38c2020-09-14 09:38:13 -04001114 *candidate.fEnclosingStmt = std::move(inlinedCall.fInlinedBody);
1115 }
1116
1117 // Replace the candidate function call with our replacement expression.
1118 *candidate.fCandidateExpr = std::move(inlinedCall.fReplacementExpr);
1119 madeChanges = true;
1120
1121 // Note that nothing was destroyed except for the FunctionCall. All other nodes should
1122 // remain valid.
1123 }
1124
1125 return madeChanges;
John Stiles93442622020-09-11 12:11:27 -04001126}
1127
John Stiles44e96be2020-08-31 13:16:04 -04001128} // namespace SkSL