blob: 778a100e048f78b1ca234a8f64ed2b8c530adf39 [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
60static int count_all_returns(const FunctionDefinition& funcDef) {
61 class CountAllReturns : public ProgramVisitor {
62 public:
63 CountAllReturns(const FunctionDefinition& funcDef) {
64 this->visitProgramElement(funcDef);
65 }
66
67 bool visitStatement(const Statement& stmt) override {
Ethan Nicholase6592142020-09-08 10:22:09 -040068 switch (stmt.kind()) {
69 case Statement::Kind::kReturn:
John Stiles44e96be2020-08-31 13:16:04 -040070 ++fNumReturns;
71 [[fallthrough]];
72
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;
79 using INHERITED = ProgramVisitor;
80 };
81
82 return CountAllReturns{funcDef}.fNumReturns;
83}
84
85static int count_returns_at_end_of_control_flow(const FunctionDefinition& funcDef) {
86 class CountReturnsAtEndOfControlFlow : public ProgramVisitor {
87 public:
88 CountReturnsAtEndOfControlFlow(const FunctionDefinition& funcDef) {
89 this->visitProgramElement(funcDef);
90 }
91
92 bool visitStatement(const Statement& stmt) override {
Ethan Nicholase6592142020-09-08 10:22:09 -040093 switch (stmt.kind()) {
94 case Statement::Kind::kBlock: {
John Stiles44e96be2020-08-31 13:16:04 -040095 // Check only the last statement of a block.
96 const auto& blockStmts = stmt.as<Block>().fStatements;
97 return (blockStmts.size() > 0) ? this->visitStatement(*blockStmts.back())
98 : false;
99 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400100 case Statement::Kind::kSwitch:
101 case Statement::Kind::kWhile:
102 case Statement::Kind::kDo:
103 case Statement::Kind::kFor:
John Stiles44e96be2020-08-31 13:16:04 -0400104 // Don't introspect switches or loop structures at all.
105 return false;
106
Ethan Nicholase6592142020-09-08 10:22:09 -0400107 case Statement::Kind::kReturn:
John Stiles44e96be2020-08-31 13:16:04 -0400108 ++fNumReturns;
109 [[fallthrough]];
110
111 default:
John Stiles93442622020-09-11 12:11:27 -0400112 return INHERITED::visitStatement(stmt);
John Stiles44e96be2020-08-31 13:16:04 -0400113 }
114 }
115
116 int fNumReturns = 0;
117 using INHERITED = ProgramVisitor;
118 };
119
120 return CountReturnsAtEndOfControlFlow{funcDef}.fNumReturns;
121}
122
123static int count_returns_in_breakable_constructs(const FunctionDefinition& funcDef) {
124 class CountReturnsInBreakableConstructs : public ProgramVisitor {
125 public:
126 CountReturnsInBreakableConstructs(const FunctionDefinition& funcDef) {
127 this->visitProgramElement(funcDef);
128 }
129
130 bool visitStatement(const Statement& stmt) override {
Ethan Nicholase6592142020-09-08 10:22:09 -0400131 switch (stmt.kind()) {
132 case Statement::Kind::kSwitch:
133 case Statement::Kind::kWhile:
134 case Statement::Kind::kDo:
135 case Statement::Kind::kFor: {
John Stiles44e96be2020-08-31 13:16:04 -0400136 ++fInsideBreakableConstruct;
John Stiles93442622020-09-11 12:11:27 -0400137 bool result = INHERITED::visitStatement(stmt);
John Stiles44e96be2020-08-31 13:16:04 -0400138 --fInsideBreakableConstruct;
139 return result;
140 }
141
Ethan Nicholase6592142020-09-08 10:22:09 -0400142 case Statement::Kind::kReturn:
John Stiles44e96be2020-08-31 13:16:04 -0400143 fNumReturns += (fInsideBreakableConstruct > 0) ? 1 : 0;
144 [[fallthrough]];
145
146 default:
John Stiles93442622020-09-11 12:11:27 -0400147 return INHERITED::visitStatement(stmt);
John Stiles44e96be2020-08-31 13:16:04 -0400148 }
149 }
150
151 int fNumReturns = 0;
152 int fInsideBreakableConstruct = 0;
153 using INHERITED = ProgramVisitor;
154 };
155
156 return CountReturnsInBreakableConstructs{funcDef}.fNumReturns;
157}
158
159static bool has_early_return(const FunctionDefinition& funcDef) {
160 int returnCount = count_all_returns(funcDef);
161 if (returnCount == 0) {
162 return false;
163 }
164
165 int returnsAtEndOfControlFlow = count_returns_at_end_of_control_flow(funcDef);
166 return returnCount > returnsAtEndOfControlFlow;
167}
168
John Stiles991b09d2020-09-10 13:33:40 -0400169static bool contains_recursive_call(const FunctionDeclaration& funcDecl) {
170 class ContainsRecursiveCall : public ProgramVisitor {
171 public:
172 bool visit(const FunctionDeclaration& funcDecl) {
173 fFuncDecl = &funcDecl;
174 return funcDecl.fDefinition ? this->visitProgramElement(*funcDecl.fDefinition)
175 : false;
176 }
177
178 bool visitExpression(const Expression& expr) override {
179 if (expr.is<FunctionCall>() && expr.as<FunctionCall>().fFunction.matches(*fFuncDecl)) {
180 return true;
181 }
182 return INHERITED::visitExpression(expr);
183 }
184
185 bool visitStatement(const Statement& stmt) override {
186 if (stmt.is<InlineMarker>() && stmt.as<InlineMarker>().fFuncDecl->matches(*fFuncDecl)) {
187 return true;
188 }
189 return INHERITED::visitStatement(stmt);
190 }
191
192 const FunctionDeclaration* fFuncDecl;
193 using INHERITED = ProgramVisitor;
194 };
195
196 return ContainsRecursiveCall{}.visit(funcDecl);
197}
198
John Stiles44e96be2020-08-31 13:16:04 -0400199static const Type* copy_if_needed(const Type* src, SymbolTable& symbolTable) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400200 if (src->typeKind() == Type::TypeKind::kArray) {
John Stiles44e96be2020-08-31 13:16:04 -0400201 return symbolTable.takeOwnershipOfSymbol(std::make_unique<Type>(*src));
202 }
203 return src;
204}
205
206} // namespace
207
208void Inliner::reset(const Context& context, const Program::Settings& settings) {
209 fContext = &context;
210 fSettings = &settings;
211 fInlineVarCounter = 0;
212}
213
214std::unique_ptr<Expression> Inliner::inlineExpression(int offset,
215 VariableRewriteMap* varMap,
216 const Expression& expression) {
217 auto expr = [&](const std::unique_ptr<Expression>& e) -> std::unique_ptr<Expression> {
218 if (e) {
219 return this->inlineExpression(offset, varMap, *e);
220 }
221 return nullptr;
222 };
223 auto argList = [&](const std::vector<std::unique_ptr<Expression>>& originalArgs)
224 -> std::vector<std::unique_ptr<Expression>> {
225 std::vector<std::unique_ptr<Expression>> args;
226 args.reserve(originalArgs.size());
227 for (const std::unique_ptr<Expression>& arg : originalArgs) {
228 args.push_back(expr(arg));
229 }
230 return args;
231 };
232
Ethan Nicholase6592142020-09-08 10:22:09 -0400233 switch (expression.kind()) {
234 case Expression::Kind::kBinary: {
John Stiles44e96be2020-08-31 13:16:04 -0400235 const BinaryExpression& b = expression.as<BinaryExpression>();
236 return std::make_unique<BinaryExpression>(offset,
237 expr(b.fLeft),
238 b.fOperator,
239 expr(b.fRight),
Ethan Nicholas30d30222020-09-11 12:27:26 -0400240 &b.type());
John Stiles44e96be2020-08-31 13:16:04 -0400241 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400242 case Expression::Kind::kBoolLiteral:
243 case Expression::Kind::kIntLiteral:
244 case Expression::Kind::kFloatLiteral:
245 case Expression::Kind::kNullLiteral:
John Stiles44e96be2020-08-31 13:16:04 -0400246 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400247 case Expression::Kind::kConstructor: {
John Stiles44e96be2020-08-31 13:16:04 -0400248 const Constructor& constructor = expression.as<Constructor>();
Ethan Nicholas30d30222020-09-11 12:27:26 -0400249 return std::make_unique<Constructor>(offset, &constructor.type(),
John Stiles44e96be2020-08-31 13:16:04 -0400250 argList(constructor.fArguments));
251 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400252 case Expression::Kind::kExternalFunctionCall: {
John Stiles44e96be2020-08-31 13:16:04 -0400253 const ExternalFunctionCall& externalCall = expression.as<ExternalFunctionCall>();
Ethan Nicholas30d30222020-09-11 12:27:26 -0400254 return std::make_unique<ExternalFunctionCall>(offset, &externalCall.type(),
John Stiles44e96be2020-08-31 13:16:04 -0400255 externalCall.fFunction,
256 argList(externalCall.fArguments));
257 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400258 case Expression::Kind::kExternalValue:
John Stiles44e96be2020-08-31 13:16:04 -0400259 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400260 case Expression::Kind::kFieldAccess: {
John Stiles44e96be2020-08-31 13:16:04 -0400261 const FieldAccess& f = expression.as<FieldAccess>();
262 return std::make_unique<FieldAccess>(expr(f.fBase), f.fFieldIndex, f.fOwnerKind);
263 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400264 case Expression::Kind::kFunctionCall: {
John Stiles44e96be2020-08-31 13:16:04 -0400265 const FunctionCall& funcCall = expression.as<FunctionCall>();
Ethan Nicholas30d30222020-09-11 12:27:26 -0400266 return std::make_unique<FunctionCall>(offset, &funcCall.type(), funcCall.fFunction,
John Stiles44e96be2020-08-31 13:16:04 -0400267 argList(funcCall.fArguments));
268 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400269 case Expression::Kind::kFunctionReference:
Brian Osman2b3b35f2020-09-08 09:17:36 -0400270 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400271 case Expression::Kind::kIndex: {
John Stiles44e96be2020-08-31 13:16:04 -0400272 const IndexExpression& idx = expression.as<IndexExpression>();
273 return std::make_unique<IndexExpression>(*fContext, expr(idx.fBase), expr(idx.fIndex));
274 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400275 case Expression::Kind::kPrefix: {
John Stiles44e96be2020-08-31 13:16:04 -0400276 const PrefixExpression& p = expression.as<PrefixExpression>();
277 return std::make_unique<PrefixExpression>(p.fOperator, expr(p.fOperand));
278 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400279 case Expression::Kind::kPostfix: {
John Stiles44e96be2020-08-31 13:16:04 -0400280 const PostfixExpression& p = expression.as<PostfixExpression>();
281 return std::make_unique<PostfixExpression>(expr(p.fOperand), p.fOperator);
282 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400283 case Expression::Kind::kSetting:
John Stiles44e96be2020-08-31 13:16:04 -0400284 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400285 case Expression::Kind::kSwizzle: {
John Stiles44e96be2020-08-31 13:16:04 -0400286 const Swizzle& s = expression.as<Swizzle>();
287 return std::make_unique<Swizzle>(*fContext, expr(s.fBase), s.fComponents);
288 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400289 case Expression::Kind::kTernary: {
John Stiles44e96be2020-08-31 13:16:04 -0400290 const TernaryExpression& t = expression.as<TernaryExpression>();
291 return std::make_unique<TernaryExpression>(offset, expr(t.fTest),
292 expr(t.fIfTrue), expr(t.fIfFalse));
293 }
Brian Osman83ba9302020-09-11 13:33:46 -0400294 case Expression::Kind::kTypeReference:
295 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400296 case Expression::Kind::kVariableReference: {
John Stiles44e96be2020-08-31 13:16:04 -0400297 const VariableReference& v = expression.as<VariableReference>();
298 auto found = varMap->find(&v.fVariable);
299 if (found != varMap->end()) {
300 return std::make_unique<VariableReference>(offset, *found->second, v.fRefKind);
301 }
302 return v.clone();
303 }
304 default:
305 SkASSERT(false);
306 return nullptr;
307 }
308}
309
310std::unique_ptr<Statement> Inliner::inlineStatement(int offset,
311 VariableRewriteMap* varMap,
312 SymbolTable* symbolTableForStatement,
313 const Variable* returnVar,
314 bool haveEarlyReturns,
315 const Statement& statement) {
316 auto stmt = [&](const std::unique_ptr<Statement>& s) -> std::unique_ptr<Statement> {
317 if (s) {
318 return this->inlineStatement(offset, varMap, symbolTableForStatement, returnVar,
319 haveEarlyReturns, *s);
320 }
321 return nullptr;
322 };
323 auto stmts = [&](const std::vector<std::unique_ptr<Statement>>& ss) {
324 std::vector<std::unique_ptr<Statement>> result;
325 for (const auto& s : ss) {
326 result.push_back(stmt(s));
327 }
328 return result;
329 };
330 auto expr = [&](const std::unique_ptr<Expression>& e) -> std::unique_ptr<Expression> {
331 if (e) {
332 return this->inlineExpression(offset, varMap, *e);
333 }
334 return nullptr;
335 };
Ethan Nicholase6592142020-09-08 10:22:09 -0400336 switch (statement.kind()) {
337 case Statement::Kind::kBlock: {
John Stiles44e96be2020-08-31 13:16:04 -0400338 const Block& b = statement.as<Block>();
339 return std::make_unique<Block>(offset, stmts(b.fStatements), b.fSymbols, b.fIsScope);
340 }
341
Ethan Nicholase6592142020-09-08 10:22:09 -0400342 case Statement::Kind::kBreak:
343 case Statement::Kind::kContinue:
344 case Statement::Kind::kDiscard:
John Stiles44e96be2020-08-31 13:16:04 -0400345 return statement.clone();
346
Ethan Nicholase6592142020-09-08 10:22:09 -0400347 case Statement::Kind::kDo: {
John Stiles44e96be2020-08-31 13:16:04 -0400348 const DoStatement& d = statement.as<DoStatement>();
349 return std::make_unique<DoStatement>(offset, stmt(d.fStatement), expr(d.fTest));
350 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400351 case Statement::Kind::kExpression: {
John Stiles44e96be2020-08-31 13:16:04 -0400352 const ExpressionStatement& e = statement.as<ExpressionStatement>();
353 return std::make_unique<ExpressionStatement>(expr(e.fExpression));
354 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400355 case Statement::Kind::kFor: {
John Stiles44e96be2020-08-31 13:16:04 -0400356 const ForStatement& f = statement.as<ForStatement>();
357 // need to ensure initializer is evaluated first so that we've already remapped its
358 // declarations by the time we evaluate test & next
359 std::unique_ptr<Statement> initializer = stmt(f.fInitializer);
360 return std::make_unique<ForStatement>(offset, std::move(initializer), expr(f.fTest),
361 expr(f.fNext), stmt(f.fStatement), f.fSymbols);
362 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400363 case Statement::Kind::kIf: {
John Stiles44e96be2020-08-31 13:16:04 -0400364 const IfStatement& i = statement.as<IfStatement>();
365 return std::make_unique<IfStatement>(offset, i.fIsStatic, expr(i.fTest),
366 stmt(i.fIfTrue), stmt(i.fIfFalse));
367 }
John Stiles98c1f822020-09-09 14:18:53 -0400368 case Statement::Kind::kInlineMarker:
Ethan Nicholase6592142020-09-08 10:22:09 -0400369 case Statement::Kind::kNop:
John Stiles44e96be2020-08-31 13:16:04 -0400370 return statement.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400371 case Statement::Kind::kReturn: {
John Stiles44e96be2020-08-31 13:16:04 -0400372 const ReturnStatement& r = statement.as<ReturnStatement>();
373 if (r.fExpression) {
374 auto assignment = std::make_unique<ExpressionStatement>(
375 std::make_unique<BinaryExpression>(
376 offset,
377 std::make_unique<VariableReference>(offset, *returnVar,
378 VariableReference::kWrite_RefKind),
379 Token::Kind::TK_EQ,
380 expr(r.fExpression),
Ethan Nicholas30d30222020-09-11 12:27:26 -0400381 &returnVar->type()));
John Stiles44e96be2020-08-31 13:16:04 -0400382 if (haveEarlyReturns) {
383 std::vector<std::unique_ptr<Statement>> block;
384 block.push_back(std::move(assignment));
385 block.emplace_back(new BreakStatement(offset));
386 return std::make_unique<Block>(offset, std::move(block), /*symbols=*/nullptr,
387 /*isScope=*/true);
388 } else {
389 return std::move(assignment);
390 }
391 } else {
392 if (haveEarlyReturns) {
393 return std::make_unique<BreakStatement>(offset);
394 } else {
395 return std::make_unique<Nop>();
396 }
397 }
398 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400399 case Statement::Kind::kSwitch: {
John Stiles44e96be2020-08-31 13:16:04 -0400400 const SwitchStatement& ss = statement.as<SwitchStatement>();
401 std::vector<std::unique_ptr<SwitchCase>> cases;
402 for (const auto& sc : ss.fCases) {
403 cases.emplace_back(new SwitchCase(offset, expr(sc->fValue),
404 stmts(sc->fStatements)));
405 }
406 return std::make_unique<SwitchStatement>(offset, ss.fIsStatic, expr(ss.fValue),
407 std::move(cases), ss.fSymbols);
408 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400409 case Statement::Kind::kVarDeclaration: {
John Stiles44e96be2020-08-31 13:16:04 -0400410 const VarDeclaration& decl = statement.as<VarDeclaration>();
411 std::vector<std::unique_ptr<Expression>> sizes;
412 for (const auto& size : decl.fSizes) {
413 sizes.push_back(expr(size));
414 }
415 std::unique_ptr<Expression> initialValue = expr(decl.fValue);
416 const Variable* old = decl.fVar;
417 // need to copy the var name in case the originating function is discarded and we lose
418 // its symbols
419 std::unique_ptr<String> name(new String(old->fName));
420 const String* namePtr = symbolTableForStatement->takeOwnershipOfString(std::move(name));
Ethan Nicholas30d30222020-09-11 12:27:26 -0400421 const Type* typePtr = copy_if_needed(&old->type(), *symbolTableForStatement);
John Stiles44e96be2020-08-31 13:16:04 -0400422 const Variable* clone = symbolTableForStatement->takeOwnershipOfSymbol(
423 std::make_unique<Variable>(offset,
424 old->fModifiers,
425 namePtr->c_str(),
Ethan Nicholas30d30222020-09-11 12:27:26 -0400426 typePtr,
John Stiles44e96be2020-08-31 13:16:04 -0400427 old->fStorage,
428 initialValue.get()));
429 (*varMap)[old] = clone;
430 return std::make_unique<VarDeclaration>(clone, std::move(sizes),
431 std::move(initialValue));
432 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400433 case Statement::Kind::kVarDeclarations: {
John Stiles44e96be2020-08-31 13:16:04 -0400434 const VarDeclarations& decls = *statement.as<VarDeclarationsStatement>().fDeclaration;
435 std::vector<std::unique_ptr<VarDeclaration>> vars;
436 for (const auto& var : decls.fVars) {
437 vars.emplace_back(&stmt(var).release()->as<VarDeclaration>());
438 }
439 const Type* typePtr = copy_if_needed(&decls.fBaseType, *symbolTableForStatement);
440 return std::unique_ptr<Statement>(new VarDeclarationsStatement(
441 std::make_unique<VarDeclarations>(offset, typePtr, std::move(vars))));
442 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400443 case Statement::Kind::kWhile: {
John Stiles44e96be2020-08-31 13:16:04 -0400444 const WhileStatement& w = statement.as<WhileStatement>();
445 return std::make_unique<WhileStatement>(offset, expr(w.fTest), stmt(w.fStatement));
446 }
447 default:
448 SkASSERT(false);
449 return nullptr;
450 }
451}
452
John Stiles6eadf132020-09-08 10:16:10 -0400453Inliner::InlinedCall Inliner::inlineCall(FunctionCall* call,
John Stiles44e96be2020-08-31 13:16:04 -0400454 SymbolTable* symbolTableForCall) {
455 // Inlining is more complicated here than in a typical compiler, because we have to have a
456 // high-level IR and can't just drop statements into the middle of an expression or even use
457 // gotos.
458 //
459 // Since we can't insert statements into an expression, we run the inline function as extra
460 // statements before the statement we're currently processing, relying on a lack of execution
461 // order guarantees. Since we can't use gotos (which are normally used to replace return
462 // statements), we wrap the whole function in a loop and use break statements to jump to the
463 // end.
464 SkASSERT(fSettings);
465 SkASSERT(fContext);
466 SkASSERT(call);
467 SkASSERT(this->isSafeToInline(*call, /*inlineThreshold=*/INT_MAX));
468
John Stiles44e96be2020-08-31 13:16:04 -0400469 std::vector<std::unique_ptr<Expression>>& arguments = call->fArguments;
John Stiles6eadf132020-09-08 10:16:10 -0400470 const int offset = call->fOffset;
John Stiles44e96be2020-08-31 13:16:04 -0400471 const FunctionDefinition& function = *call->fFunction.fDefinition;
John Stiles6eadf132020-09-08 10:16:10 -0400472 const bool hasEarlyReturn = has_early_return(function);
473
John Stiles44e96be2020-08-31 13:16:04 -0400474 InlinedCall inlinedCall;
John Stiles6eadf132020-09-08 10:16:10 -0400475 inlinedCall.fInlinedBody = std::make_unique<Block>(offset,
476 std::vector<std::unique_ptr<Statement>>{},
477 /*symbols=*/nullptr,
478 /*isScope=*/false);
John Stiles98c1f822020-09-09 14:18:53 -0400479
John Stiles6eadf132020-09-08 10:16:10 -0400480 std::vector<std::unique_ptr<Statement>>& inlinedBody = inlinedCall.fInlinedBody->fStatements;
John Stiles98c1f822020-09-09 14:18:53 -0400481 inlinedBody.reserve(1 + // Inline marker
482 1 + // Result variable
483 arguments.size() + // Function arguments (passing in)
484 arguments.size() + // Function arguments (copy out-parameters back)
485 1); // Inlined code (either as a Block or do-while loop)
486
487 inlinedBody.push_back(std::make_unique<InlineMarker>(call->fFunction));
John Stiles44e96be2020-08-31 13:16:04 -0400488
John Stilesa003e812020-09-11 09:43:49 -0400489 auto makeInlineVar = [&](const String& baseName, const Type* type, Modifiers modifiers,
John Stiles44e96be2020-08-31 13:16:04 -0400490 std::unique_ptr<Expression>* initialValue) -> const Variable* {
John Stilesa003e812020-09-11 09:43:49 -0400491 // $floatLiteral or $intLiteral aren't real types that we can use for scratch variables, so
492 // replace them if they ever appear here. If this happens, we likely forgot to coerce a type
493 // somewhere during compilation.
494 if (type == fContext->fFloatLiteral_Type.get()) {
John Stilesd2be5c52020-09-11 14:58:06 -0400495 SkDEBUGFAIL("found a $floatLiteral type while inlining");
John Stilesa003e812020-09-11 09:43:49 -0400496 type = fContext->fFloat_Type.get();
497 } else if (type == fContext->fIntLiteral_Type.get()) {
John Stilesd2be5c52020-09-11 14:58:06 -0400498 SkDEBUGFAIL("found an $intLiteral type while inlining");
John Stilesa003e812020-09-11 09:43:49 -0400499 type = fContext->fInt_Type.get();
500 }
501
John Stilescf936f92020-08-31 17:18:45 -0400502 // If the base name starts with an underscore, like "_coords", we can't append another
503 // underscore, because some OpenGL platforms error out when they see two consecutive
504 // underscores (anywhere in the string!). But in the general case, using the underscore as
505 // a splitter reads nicely enough that it's worth putting in this special case.
506 const char* splitter = baseName.startsWith("_") ? "_X" : "_";
507
508 // Append a unique numeric prefix to avoid name overlap. Check the symbol table to make sure
509 // we're not reusing an existing name. (Note that within a single compilation pass, this
510 // check isn't fully comprehensive, as code isn't always generated in top-to-bottom order.)
511 String uniqueName;
512 for (;;) {
513 uniqueName = String::printf("_%d%s%s", fInlineVarCounter++, splitter, baseName.c_str());
514 StringFragment frag{uniqueName.data(), uniqueName.length()};
515 if ((*symbolTableForCall)[frag] == nullptr) {
516 break;
517 }
518 }
519
John Stiles44e96be2020-08-31 13:16:04 -0400520 // Add our new variable's name to the symbol table.
John Stilescf936f92020-08-31 17:18:45 -0400521 const String* namePtr = symbolTableForCall->takeOwnershipOfString(
522 std::make_unique<String>(std::move(uniqueName)));
John Stiles44e96be2020-08-31 13:16:04 -0400523 StringFragment nameFrag{namePtr->c_str(), namePtr->length()};
524
525 // Add our new variable to the symbol table.
Ethan Nicholas30d30222020-09-11 12:27:26 -0400526 auto newVar = std::make_unique<Variable>(/*offset=*/-1, Modifiers(), nameFrag, type,
John Stiles44e96be2020-08-31 13:16:04 -0400527 Variable::kLocal_Storage, initialValue->get());
528 const Variable* variableSymbol = symbolTableForCall->add(nameFrag, std::move(newVar));
529
530 // Prepare the variable declaration (taking extra care with `out` params to not clobber any
531 // initial value).
532 std::vector<std::unique_ptr<VarDeclaration>> variables;
533 if (initialValue && (modifiers.fFlags & Modifiers::kOut_Flag)) {
534 variables.push_back(std::make_unique<VarDeclaration>(
535 variableSymbol, /*sizes=*/std::vector<std::unique_ptr<Expression>>{},
536 (*initialValue)->clone()));
537 } else {
538 variables.push_back(std::make_unique<VarDeclaration>(
539 variableSymbol, /*sizes=*/std::vector<std::unique_ptr<Expression>>{},
540 std::move(*initialValue)));
541 }
542
543 // Add the new variable-declaration statement to our block of extra statements.
John Stiles39616ec2020-08-31 14:16:06 -0400544 inlinedBody.push_back(std::make_unique<VarDeclarationsStatement>(
John Stilesa003e812020-09-11 09:43:49 -0400545 std::make_unique<VarDeclarations>(offset, type, std::move(variables))));
John Stiles44e96be2020-08-31 13:16:04 -0400546
547 return variableSymbol;
548 };
549
550 // Create a variable to hold the result in the extra statements (excepting void).
551 const Variable* resultVar = nullptr;
552 if (function.fDeclaration.fReturnType != *fContext->fVoid_Type) {
John Stiles44e96be2020-08-31 13:16:04 -0400553 std::unique_ptr<Expression> noInitialValue;
John Stilescf936f92020-08-31 17:18:45 -0400554 resultVar = makeInlineVar(String(function.fDeclaration.fName),
John Stilesa003e812020-09-11 09:43:49 -0400555 &function.fDeclaration.fReturnType, Modifiers{}, &noInitialValue);
John Stiles44e96be2020-08-31 13:16:04 -0400556 }
557
558 // Create variables in the extra statements to hold the arguments, and assign the arguments to
559 // them.
560 VariableRewriteMap varMap;
John Stiles44e96be2020-08-31 13:16:04 -0400561 for (int i = 0; i < (int) arguments.size(); ++i) {
562 const Variable* param = function.fDeclaration.fParameters[i];
563
John Stilesa003e812020-09-11 09:43:49 -0400564 if (arguments[i]->is<VariableReference>()) {
John Stiles44e96be2020-08-31 13:16:04 -0400565 // The argument is just a variable, so we only need to copy it if it's an out parameter
566 // or it's written to within the function.
567 if ((param->fModifiers.fFlags & Modifiers::kOut_Flag) ||
568 !Analysis::StatementWritesToVariable(*function.fBody, *param)) {
569 varMap[param] = &arguments[i]->as<VariableReference>().fVariable;
570 continue;
571 }
572 }
573
Ethan Nicholas30d30222020-09-11 12:27:26 -0400574 varMap[param] = makeInlineVar(String(param->fName), &arguments[i]->type(),
575 param->fModifiers, &arguments[i]);
John Stiles44e96be2020-08-31 13:16:04 -0400576 }
577
578 const Block& body = function.fBody->as<Block>();
John Stiles44e96be2020-08-31 13:16:04 -0400579 auto inlineBlock = std::make_unique<Block>(offset, std::vector<std::unique_ptr<Statement>>{});
580 inlineBlock->fStatements.reserve(body.fStatements.size());
581 for (const std::unique_ptr<Statement>& stmt : body.fStatements) {
582 inlineBlock->fStatements.push_back(this->inlineStatement(
583 offset, &varMap, symbolTableForCall, resultVar, hasEarlyReturn, *stmt));
584 }
585 if (hasEarlyReturn) {
586 // Since we output to backends that don't have a goto statement (which would normally be
587 // used to perform an early return), we fake it by wrapping the function in a
588 // do { } while (false); and then use break statements to jump to the end in order to
589 // emulate a goto.
John Stiles39616ec2020-08-31 14:16:06 -0400590 inlinedBody.push_back(std::make_unique<DoStatement>(
John Stiles44e96be2020-08-31 13:16:04 -0400591 /*offset=*/-1,
592 std::move(inlineBlock),
593 std::make_unique<BoolLiteral>(*fContext, offset, /*value=*/false)));
594 } else {
John Stiles6eadf132020-09-08 10:16:10 -0400595 // No early returns, so we can just dump the code in. We still need to keep the block so we
596 // don't get name conflicts with locals.
John Stiles39616ec2020-08-31 14:16:06 -0400597 inlinedBody.push_back(std::move(inlineBlock));
John Stiles44e96be2020-08-31 13:16:04 -0400598 }
599
600 // Copy the values of `out` parameters into their destinations.
601 for (size_t i = 0; i < arguments.size(); ++i) {
602 const Variable* p = function.fDeclaration.fParameters[i];
603 if (p->fModifiers.fFlags & Modifiers::kOut_Flag) {
604 SkASSERT(varMap.find(p) != varMap.end());
Ethan Nicholase6592142020-09-08 10:22:09 -0400605 if (arguments[i]->kind() == Expression::Kind::kVariableReference &&
John Stiles44e96be2020-08-31 13:16:04 -0400606 &arguments[i]->as<VariableReference>().fVariable == varMap[p]) {
John Stiles6eadf132020-09-08 10:16:10 -0400607 // We didn't create a temporary for this parameter, so there's nothing to copy back
608 // out.
John Stiles44e96be2020-08-31 13:16:04 -0400609 continue;
610 }
611 auto varRef = std::make_unique<VariableReference>(offset, *varMap[p]);
John Stiles39616ec2020-08-31 14:16:06 -0400612 inlinedBody.push_back(std::make_unique<ExpressionStatement>(
John Stiles44e96be2020-08-31 13:16:04 -0400613 std::make_unique<BinaryExpression>(offset,
614 arguments[i]->clone(),
615 Token::Kind::TK_EQ,
616 std::move(varRef),
Ethan Nicholas30d30222020-09-11 12:27:26 -0400617 &arguments[i]->type())));
John Stiles44e96be2020-08-31 13:16:04 -0400618 }
619 }
620
621 if (function.fDeclaration.fReturnType != *fContext->fVoid_Type) {
622 // Return a reference to the result variable as our replacement expression.
623 inlinedCall.fReplacementExpr = std::make_unique<VariableReference>(offset, *resultVar);
624 } else {
625 // It's a void function, so it doesn't actually result in anything, but we have to return
626 // something non-null as a standin.
627 inlinedCall.fReplacementExpr = std::make_unique<BoolLiteral>(*fContext, offset,
628 /*value=*/false);
629 }
630
John Stiles44e96be2020-08-31 13:16:04 -0400631 return inlinedCall;
632}
633
John Stiles93442622020-09-11 12:11:27 -0400634bool Inliner::isSafeToInline(const FunctionCall& functionCall, int inlineThreshold) {
John Stiles44e96be2020-08-31 13:16:04 -0400635 SkASSERT(fSettings);
636
637 if (functionCall.fFunction.fDefinition == nullptr) {
638 // Can't inline something if we don't actually have its definition.
639 return false;
640 }
641 const FunctionDefinition& functionDef = *functionCall.fFunction.fDefinition;
642 if (inlineThreshold < INT_MAX) {
643 if (!(functionDef.fDeclaration.fModifiers.fFlags & Modifiers::kInline_Flag) &&
644 Analysis::NodeCount(functionDef) >= inlineThreshold) {
645 // The function exceeds our maximum inline size and is not flagged 'inline'.
646 return false;
647 }
648 }
John Stiles44e96be2020-08-31 13:16:04 -0400649 if (!fSettings->fCaps || !fSettings->fCaps->canUseDoLoops()) {
650 // We don't have do-while loops. We use do-while loops to simulate early returns, so we
651 // can't inline functions that have an early return.
652 bool hasEarlyReturn = has_early_return(functionDef);
653
654 // If we didn't detect an early return, there shouldn't be any returns in breakable
655 // constructs either.
656 SkASSERT(hasEarlyReturn || count_returns_in_breakable_constructs(functionDef) == 0);
657 return !hasEarlyReturn;
658 }
659 // We have do-while loops, but we don't have any mechanism to simulate early returns within a
660 // breakable construct (switch/for/do/while), so we can't inline if there's a return inside one.
661 bool hasReturnInBreakableConstruct = (count_returns_in_breakable_constructs(functionDef) > 0);
662
663 // If we detected returns in breakable constructs, we should also detect an early return.
664 SkASSERT(!hasReturnInBreakableConstruct || has_early_return(functionDef));
665 return !hasReturnInBreakableConstruct;
666}
667
John Stiles93442622020-09-11 12:11:27 -0400668bool Inliner::analyze(Program& program) {
669 // A candidate function for inlining, containing everything that `inlineCall` needs.
670 struct InlineCandidate {
671 SymbolTable* fSymbols;
672 std::unique_ptr<Statement>* fEnclosingStmt;
673 std::unique_ptr<Expression>* fCandidateExpr;
674 };
675
676 // This is structured much like a ProgramVisitor, but does not actually use ProgramVisitor.
677 // The analyzer needs to keep track of the `unique_ptr<T>*` of statements and expressions so
678 // that they can later be replaced, and ProgramVisitor does not provide this; it only provides a
679 // `const T&`.
680 class InlineCandidateAnalyzer {
681 public:
682 // A list of all the inlining candidates we found during analysis.
683 std::vector<InlineCandidate> fInlineCandidates;
684 // A stack of the symbol tables; since most nodes don't have one, expected to be shallower
685 // than the enclosing-statement stack.
686 std::vector<SymbolTable*> fSymbolTableStack;
687 // A stack of "enclosing" statements--these would be suitable for the inliner to use for
688 // adding new instructions. Not all statements are suitable (e.g. a for-loop's initializer).
689 // The inliner might replace a statement with a block containing the statement.
690 std::vector<std::unique_ptr<Statement>*> fEnclosingStmtStack;
691
692 void visit(Program& program) {
693 fSymbolTableStack.push_back(program.fSymbols.get());
694
695 for (ProgramElement& pe : program) {
696 this->visitProgramElement(&pe);
697 }
698
699 fSymbolTableStack.pop_back();
700 }
701
702 void visitProgramElement(ProgramElement* pe) {
703 switch (pe->kind()) {
704 case ProgramElement::Kind::kFunction: {
705 FunctionDefinition& funcDef = pe->as<FunctionDefinition>();
706 this->visitStatement(&funcDef.fBody);
707 break;
708 }
709 default:
710 // The inliner can't operate outside of a function's scope.
711 break;
712 }
713 }
714
715 void visitStatement(std::unique_ptr<Statement>* stmt,
716 bool isViableAsEnclosingStatement = true) {
717 if (!*stmt) {
718 return;
719 }
720
721 size_t oldEnclosingStmtStackSize = fEnclosingStmtStack.size();
722 size_t oldSymbolStackSize = fSymbolTableStack.size();
723
724 if (isViableAsEnclosingStatement) {
725 fEnclosingStmtStack.push_back(stmt);
726 }
727
728 switch ((*stmt)->kind()) {
729 case Statement::Kind::kBreak:
730 case Statement::Kind::kContinue:
731 case Statement::Kind::kDiscard:
732 case Statement::Kind::kInlineMarker:
733 case Statement::Kind::kNop:
734 break;
735
736 case Statement::Kind::kBlock: {
737 Block& block = (*stmt)->as<Block>();
738 if (block.fSymbols) {
739 fSymbolTableStack.push_back(block.fSymbols.get());
740 }
741
742 for (std::unique_ptr<Statement>& blockStmt : block.fStatements) {
743 this->visitStatement(&blockStmt);
744 }
745 break;
746 }
747 case Statement::Kind::kDo: {
748 DoStatement& doStmt = (*stmt)->as<DoStatement>();
749 // The loop body is a candidate for inlining.
750 this->visitStatement(&doStmt.fStatement);
751 // The inliner isn't smart enough to inline the test-expression for a do-while
752 // loop at this time. There are two limitations:
753 // - We would need to insert the inlined-body block at the very end of the do-
754 // statement's inner fStatement. We don't support that today, but it's doable.
755 // - We cannot inline the test expression if the loop uses `continue` anywhere;
756 // that would skip over the inlined block that evaluates the test expression.
757 // There isn't a good fix for this--any workaround would be more complex than
758 // the cost of a function call. However, loops that don't use `continue` would
759 // still be viable candidates for inlining.
760 break;
761 }
762 case Statement::Kind::kExpression: {
763 ExpressionStatement& expr = (*stmt)->as<ExpressionStatement>();
764 this->visitExpression(&expr.fExpression);
765 break;
766 }
767 case Statement::Kind::kFor: {
768 ForStatement& forStmt = (*stmt)->as<ForStatement>();
769 if (forStmt.fSymbols) {
770 fSymbolTableStack.push_back(forStmt.fSymbols.get());
771 }
772
773 // The initializer and loop body are candidates for inlining.
774 this->visitStatement(&forStmt.fInitializer,
775 /*isViableAsEnclosingStatement=*/false);
776 this->visitStatement(&forStmt.fStatement);
777
778 // The inliner isn't smart enough to inline the test- or increment-expressions
779 // of a for loop loop at this time. There are a handful of limitations:
780 // - We would need to insert the test-expression block at the very beginning of
781 // the for-loop's inner fStatement, and the increment-expression block at the
782 // very end. We don't support that today, but it's doable.
783 // - The for-loop's built-in test-expression would need to be dropped entirely,
784 // and the loop would be halted via a break statement at the end of the
785 // inlined test-expression. This is again something we don't support today,
786 // but it could be implemented.
787 // - We cannot inline the increment-expression if the loop uses `continue`
788 // anywhere; that would skip over the inlined block that evaluates the
789 // increment expression. There isn't a good fix for this--any workaround would
790 // be more complex than the cost of a function call. However, loops that don't
791 // use `continue` would still be viable candidates for increment-expression
792 // inlining.
793 break;
794 }
795 case Statement::Kind::kIf: {
796 IfStatement& ifStmt = (*stmt)->as<IfStatement>();
797 this->visitExpression(&ifStmt.fTest);
798 this->visitStatement(&ifStmt.fIfTrue);
799 this->visitStatement(&ifStmt.fIfFalse);
800 break;
801 }
802 case Statement::Kind::kReturn: {
803 ReturnStatement& returnStmt = (*stmt)->as<ReturnStatement>();
804 this->visitExpression(&returnStmt.fExpression);
805 break;
806 }
807 case Statement::Kind::kSwitch: {
808 SwitchStatement& switchStmt = (*stmt)->as<SwitchStatement>();
809 if (switchStmt.fSymbols) {
810 fSymbolTableStack.push_back(switchStmt.fSymbols.get());
811 }
812
813 this->visitExpression(&switchStmt.fValue);
814 for (std::unique_ptr<SwitchCase>& switchCase : switchStmt.fCases) {
815 // The switch-case's fValue cannot be a FunctionCall; skip it.
816 for (std::unique_ptr<Statement>& caseBlock : switchCase->fStatements) {
817 this->visitStatement(&caseBlock);
818 }
819 }
820 break;
821 }
822 case Statement::Kind::kVarDeclaration: {
823 VarDeclaration& varDeclStmt = (*stmt)->as<VarDeclaration>();
824 // Don't need to scan the declaration's sizes; those are always IntLiterals.
825 this->visitExpression(&varDeclStmt.fValue);
826 break;
827 }
828 case Statement::Kind::kVarDeclarations: {
829 VarDeclarationsStatement& varDecls = (*stmt)->as<VarDeclarationsStatement>();
830 for (std::unique_ptr<Statement>& varDecl : varDecls.fDeclaration->fVars) {
831 this->visitStatement(&varDecl, /*isViableAsEnclosingStatement=*/false);
832 }
833 break;
834 }
835 case Statement::Kind::kWhile: {
836 WhileStatement& whileStmt = (*stmt)->as<WhileStatement>();
837 // The loop body is a candidate for inlining.
838 this->visitStatement(&whileStmt.fStatement);
839 // The inliner isn't smart enough to inline the test-expression for a while
840 // loop at this time. There are two limitations:
841 // - We would need to insert the inlined-body block at the very beginning of the
842 // while loop's inner fStatement. We don't support that today, but it's
843 // doable.
844 // - The while-loop's built-in test-expression would need to be replaced with a
845 // `true` BoolLiteral, and the loop would be halted via a break statement at
846 // the end of the inlined test-expression. This is again something we don't
847 // support today, but it could be implemented.
848 break;
849 }
850 default:
851 SkUNREACHABLE;
852 }
853
854 // Pop our symbol and enclosing-statement stacks.
855 fSymbolTableStack.resize(oldSymbolStackSize);
856 fEnclosingStmtStack.resize(oldEnclosingStmtStackSize);
857 }
858
859 void visitExpression(std::unique_ptr<Expression>* expr) {
860 if (!*expr) {
861 return;
862 }
863
864 switch ((*expr)->kind()) {
865 case Expression::Kind::kBoolLiteral:
866 case Expression::Kind::kDefined:
867 case Expression::Kind::kExternalValue:
868 case Expression::Kind::kFieldAccess:
869 case Expression::Kind::kFloatLiteral:
870 case Expression::Kind::kFunctionReference:
871 case Expression::Kind::kIntLiteral:
872 case Expression::Kind::kNullLiteral:
873 case Expression::Kind::kSetting:
874 case Expression::Kind::kTypeReference:
875 case Expression::Kind::kVariableReference:
876 // Nothing to scan here.
877 break;
878
879 case Expression::Kind::kBinary: {
880 BinaryExpression& binaryExpr = (*expr)->as<BinaryExpression>();
881 this->visitExpression(&binaryExpr.fLeft);
882
883 // Logical-and and logical-or binary expressions do not inline the right side,
884 // because that would invalidate short-circuiting. That is, when evaluating
885 // expressions like these:
886 // (false && x()) // always false
887 // (true || y()) // always true
888 // It is illegal for side-effects from x() or y() to occur. The simplest way to
889 // enforce that rule is to avoid inlining the right side entirely. However, it
890 // is safe for other types of binary expression to inline both sides.
891 bool shortCircuitable = (binaryExpr.fOperator == Token::Kind::TK_LOGICALAND ||
892 binaryExpr.fOperator == Token::Kind::TK_LOGICALOR);
893 if (!shortCircuitable) {
894 this->visitExpression(&binaryExpr.fRight);
895 }
896 break;
897 }
898 case Expression::Kind::kConstructor: {
899 Constructor& constructorExpr = (*expr)->as<Constructor>();
900 for (std::unique_ptr<Expression>& arg : constructorExpr.fArguments) {
901 this->visitExpression(&arg);
902 }
903 break;
904 }
905 case Expression::Kind::kExternalFunctionCall: {
906 ExternalFunctionCall& funcCallExpr = (*expr)->as<ExternalFunctionCall>();
907 for (std::unique_ptr<Expression>& arg : funcCallExpr.fArguments) {
908 this->visitExpression(&arg);
909 }
910 break;
911 }
912 case Expression::Kind::kFunctionCall: {
913 FunctionCall& funcCallExpr = (*expr)->as<FunctionCall>();
914 for (std::unique_ptr<Expression>& arg : funcCallExpr.fArguments) {
915 this->visitExpression(&arg);
916 }
917 this->addInlineCandidate(expr);
918 break;
919 }
920 case Expression::Kind::kIndex:{
921 IndexExpression& indexExpr = (*expr)->as<IndexExpression>();
922 this->visitExpression(&indexExpr.fBase);
923 this->visitExpression(&indexExpr.fIndex);
924 break;
925 }
926 case Expression::Kind::kPostfix: {
927 PostfixExpression& postfixExpr = (*expr)->as<PostfixExpression>();
928 this->visitExpression(&postfixExpr.fOperand);
929 break;
930 }
931 case Expression::Kind::kPrefix: {
932 PrefixExpression& prefixExpr = (*expr)->as<PrefixExpression>();
933 this->visitExpression(&prefixExpr.fOperand);
934 break;
935 }
936 case Expression::Kind::kSwizzle: {
937 Swizzle& swizzleExpr = (*expr)->as<Swizzle>();
938 this->visitExpression(&swizzleExpr.fBase);
939 break;
940 }
941 case Expression::Kind::kTernary: {
942 TernaryExpression& ternaryExpr = (*expr)->as<TernaryExpression>();
943 // The test expression is a candidate for inlining.
944 this->visitExpression(&ternaryExpr.fTest);
945 // The true- and false-expressions cannot be inlined, because we are only
946 // allowed to evaluate one side.
947 break;
948 }
949 default:
950 SkUNREACHABLE;
951 }
952 }
953
954 void addInlineCandidate(std::unique_ptr<Expression>* candidate) {
955 fInlineCandidates.push_back(InlineCandidate{fSymbolTableStack.back(),
956 fEnclosingStmtStack.back(), candidate});
957 }
958 };
959
960 // TODO(johnstiles): the analyzer can detect inlinable functions; actually inlining them will
961 // be tackled in a followup CL.
962 InlineCandidateAnalyzer analyzer;
963 analyzer.visit(program);
964 std::unordered_map<const FunctionDeclaration*, bool> inlinableMap; // <function, safe-to-inline>
965 for (InlineCandidate& candidate : analyzer.fInlineCandidates) {
966 const FunctionCall& funcCall = (*candidate.fCandidateExpr)->as<FunctionCall>();
967 const FunctionDeclaration* funcDecl = &funcCall.fFunction;
968 if (inlinableMap.find(funcDecl) == inlinableMap.end()) {
969 // We do not perform inlining on recursive calls to avoid an infinite death spiral of
970 // inlining.
971 int inlineThreshold = (funcDecl->fCallCount.load() > 1) ? fSettings->fInlineThreshold
972 : INT_MAX;
973 inlinableMap[funcDecl] = this->isSafeToInline(funcCall, inlineThreshold) &&
974 !contains_recursive_call(*funcDecl);
975/*
976 if (inlinableMap[funcDecl]) {
977 printf("-> Inliner discovered valid candidate: %s\n",
978 String(funcDecl->fName).c_str());
979 }
980*/
981 }
982 }
983
984 return false;
985}
986
John Stiles44e96be2020-08-31 13:16:04 -0400987} // namespace SkSL