blob: eb9e02ee1e8057241cb3c642c7198718080f9d3a [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"
36#include "src/sksl/ir/SkSLIntLiteral.h"
37#include "src/sksl/ir/SkSLInterfaceBlock.h"
38#include "src/sksl/ir/SkSLLayout.h"
39#include "src/sksl/ir/SkSLNop.h"
40#include "src/sksl/ir/SkSLNullLiteral.h"
41#include "src/sksl/ir/SkSLPostfixExpression.h"
42#include "src/sksl/ir/SkSLPrefixExpression.h"
43#include "src/sksl/ir/SkSLReturnStatement.h"
44#include "src/sksl/ir/SkSLSetting.h"
45#include "src/sksl/ir/SkSLSwitchCase.h"
46#include "src/sksl/ir/SkSLSwitchStatement.h"
47#include "src/sksl/ir/SkSLSwizzle.h"
48#include "src/sksl/ir/SkSLTernaryExpression.h"
49#include "src/sksl/ir/SkSLUnresolvedFunction.h"
50#include "src/sksl/ir/SkSLVarDeclarations.h"
51#include "src/sksl/ir/SkSLVarDeclarationsStatement.h"
52#include "src/sksl/ir/SkSLVariable.h"
53#include "src/sksl/ir/SkSLVariableReference.h"
54#include "src/sksl/ir/SkSLWhileStatement.h"
55
56namespace SkSL {
57namespace {
58
59static int count_all_returns(const FunctionDefinition& funcDef) {
60 class CountAllReturns : public ProgramVisitor {
61 public:
62 CountAllReturns(const FunctionDefinition& funcDef) {
63 this->visitProgramElement(funcDef);
64 }
65
66 bool visitStatement(const Statement& stmt) override {
67 switch (stmt.fKind) {
68 case Statement::kReturn_Kind:
69 ++fNumReturns;
70 [[fallthrough]];
71
72 default:
73 return this->INHERITED::visitStatement(stmt);
74 }
75 }
76
77 int fNumReturns = 0;
78 using INHERITED = ProgramVisitor;
79 };
80
81 return CountAllReturns{funcDef}.fNumReturns;
82}
83
84static int count_returns_at_end_of_control_flow(const FunctionDefinition& funcDef) {
85 class CountReturnsAtEndOfControlFlow : public ProgramVisitor {
86 public:
87 CountReturnsAtEndOfControlFlow(const FunctionDefinition& funcDef) {
88 this->visitProgramElement(funcDef);
89 }
90
91 bool visitStatement(const Statement& stmt) override {
92 switch (stmt.fKind) {
93 case Statement::kBlock_Kind: {
94 // Check only the last statement of a block.
95 const auto& blockStmts = stmt.as<Block>().fStatements;
96 return (blockStmts.size() > 0) ? this->visitStatement(*blockStmts.back())
97 : false;
98 }
99 case Statement::kSwitch_Kind:
100 case Statement::kWhile_Kind:
101 case Statement::kDo_Kind:
102 case Statement::kFor_Kind:
103 // Don't introspect switches or loop structures at all.
104 return false;
105
106 case Statement::kReturn_Kind:
107 ++fNumReturns;
108 [[fallthrough]];
109
110 default:
111 return this->INHERITED::visitStatement(stmt);
112 }
113 }
114
115 int fNumReturns = 0;
116 using INHERITED = ProgramVisitor;
117 };
118
119 return CountReturnsAtEndOfControlFlow{funcDef}.fNumReturns;
120}
121
122static int count_returns_in_breakable_constructs(const FunctionDefinition& funcDef) {
123 class CountReturnsInBreakableConstructs : public ProgramVisitor {
124 public:
125 CountReturnsInBreakableConstructs(const FunctionDefinition& funcDef) {
126 this->visitProgramElement(funcDef);
127 }
128
129 bool visitStatement(const Statement& stmt) override {
130 switch (stmt.fKind) {
131 case Statement::kSwitch_Kind:
132 case Statement::kWhile_Kind:
133 case Statement::kDo_Kind:
134 case Statement::kFor_Kind: {
135 ++fInsideBreakableConstruct;
136 bool result = this->INHERITED::visitStatement(stmt);
137 --fInsideBreakableConstruct;
138 return result;
139 }
140
141 case Statement::kReturn_Kind:
142 fNumReturns += (fInsideBreakableConstruct > 0) ? 1 : 0;
143 [[fallthrough]];
144
145 default:
146 return this->INHERITED::visitStatement(stmt);
147 }
148 }
149
150 int fNumReturns = 0;
151 int fInsideBreakableConstruct = 0;
152 using INHERITED = ProgramVisitor;
153 };
154
155 return CountReturnsInBreakableConstructs{funcDef}.fNumReturns;
156}
157
158static bool has_early_return(const FunctionDefinition& funcDef) {
159 int returnCount = count_all_returns(funcDef);
160 if (returnCount == 0) {
161 return false;
162 }
163
164 int returnsAtEndOfControlFlow = count_returns_at_end_of_control_flow(funcDef);
165 return returnCount > returnsAtEndOfControlFlow;
166}
167
168static const Type* copy_if_needed(const Type* src, SymbolTable& symbolTable) {
169 if (src->kind() == Type::kArray_Kind) {
170 return symbolTable.takeOwnershipOfSymbol(std::make_unique<Type>(*src));
171 }
172 return src;
173}
174
175} // namespace
176
177void Inliner::reset(const Context& context, const Program::Settings& settings) {
178 fContext = &context;
179 fSettings = &settings;
180 fInlineVarCounter = 0;
181}
182
183std::unique_ptr<Expression> Inliner::inlineExpression(int offset,
184 VariableRewriteMap* varMap,
185 const Expression& expression) {
186 auto expr = [&](const std::unique_ptr<Expression>& e) -> std::unique_ptr<Expression> {
187 if (e) {
188 return this->inlineExpression(offset, varMap, *e);
189 }
190 return nullptr;
191 };
192 auto argList = [&](const std::vector<std::unique_ptr<Expression>>& originalArgs)
193 -> std::vector<std::unique_ptr<Expression>> {
194 std::vector<std::unique_ptr<Expression>> args;
195 args.reserve(originalArgs.size());
196 for (const std::unique_ptr<Expression>& arg : originalArgs) {
197 args.push_back(expr(arg));
198 }
199 return args;
200 };
201
202 switch (expression.fKind) {
203 case Expression::kBinary_Kind: {
204 const BinaryExpression& b = expression.as<BinaryExpression>();
205 return std::make_unique<BinaryExpression>(offset,
206 expr(b.fLeft),
207 b.fOperator,
208 expr(b.fRight),
209 b.fType);
210 }
211 case Expression::kBoolLiteral_Kind:
212 case Expression::kIntLiteral_Kind:
213 case Expression::kFloatLiteral_Kind:
214 case Expression::kNullLiteral_Kind:
215 return expression.clone();
216 case Expression::kConstructor_Kind: {
217 const Constructor& constructor = expression.as<Constructor>();
218 return std::make_unique<Constructor>(offset, constructor.fType,
219 argList(constructor.fArguments));
220 }
221 case Expression::kExternalFunctionCall_Kind: {
222 const ExternalFunctionCall& externalCall = expression.as<ExternalFunctionCall>();
223 return std::make_unique<ExternalFunctionCall>(offset, externalCall.fType,
224 externalCall.fFunction,
225 argList(externalCall.fArguments));
226 }
227 case Expression::kExternalValue_Kind:
228 return expression.clone();
229 case Expression::kFieldAccess_Kind: {
230 const FieldAccess& f = expression.as<FieldAccess>();
231 return std::make_unique<FieldAccess>(expr(f.fBase), f.fFieldIndex, f.fOwnerKind);
232 }
233 case Expression::kFunctionCall_Kind: {
234 const FunctionCall& funcCall = expression.as<FunctionCall>();
235 return std::make_unique<FunctionCall>(offset, funcCall.fType, funcCall.fFunction,
236 argList(funcCall.fArguments));
237 }
238 case Expression::kIndex_Kind: {
239 const IndexExpression& idx = expression.as<IndexExpression>();
240 return std::make_unique<IndexExpression>(*fContext, expr(idx.fBase), expr(idx.fIndex));
241 }
242 case Expression::kPrefix_Kind: {
243 const PrefixExpression& p = expression.as<PrefixExpression>();
244 return std::make_unique<PrefixExpression>(p.fOperator, expr(p.fOperand));
245 }
246 case Expression::kPostfix_Kind: {
247 const PostfixExpression& p = expression.as<PostfixExpression>();
248 return std::make_unique<PostfixExpression>(expr(p.fOperand), p.fOperator);
249 }
250 case Expression::kSetting_Kind:
251 return expression.clone();
252 case Expression::kSwizzle_Kind: {
253 const Swizzle& s = expression.as<Swizzle>();
254 return std::make_unique<Swizzle>(*fContext, expr(s.fBase), s.fComponents);
255 }
256 case Expression::kTernary_Kind: {
257 const TernaryExpression& t = expression.as<TernaryExpression>();
258 return std::make_unique<TernaryExpression>(offset, expr(t.fTest),
259 expr(t.fIfTrue), expr(t.fIfFalse));
260 }
261 case Expression::kVariableReference_Kind: {
262 const VariableReference& v = expression.as<VariableReference>();
263 auto found = varMap->find(&v.fVariable);
264 if (found != varMap->end()) {
265 return std::make_unique<VariableReference>(offset, *found->second, v.fRefKind);
266 }
267 return v.clone();
268 }
269 default:
270 SkASSERT(false);
271 return nullptr;
272 }
273}
274
275std::unique_ptr<Statement> Inliner::inlineStatement(int offset,
276 VariableRewriteMap* varMap,
277 SymbolTable* symbolTableForStatement,
278 const Variable* returnVar,
279 bool haveEarlyReturns,
280 const Statement& statement) {
281 auto stmt = [&](const std::unique_ptr<Statement>& s) -> std::unique_ptr<Statement> {
282 if (s) {
283 return this->inlineStatement(offset, varMap, symbolTableForStatement, returnVar,
284 haveEarlyReturns, *s);
285 }
286 return nullptr;
287 };
288 auto stmts = [&](const std::vector<std::unique_ptr<Statement>>& ss) {
289 std::vector<std::unique_ptr<Statement>> result;
290 for (const auto& s : ss) {
291 result.push_back(stmt(s));
292 }
293 return result;
294 };
295 auto expr = [&](const std::unique_ptr<Expression>& e) -> std::unique_ptr<Expression> {
296 if (e) {
297 return this->inlineExpression(offset, varMap, *e);
298 }
299 return nullptr;
300 };
301 switch (statement.fKind) {
302 case Statement::kBlock_Kind: {
303 const Block& b = statement.as<Block>();
304 return std::make_unique<Block>(offset, stmts(b.fStatements), b.fSymbols, b.fIsScope);
305 }
306
307 case Statement::kBreak_Kind:
308 case Statement::kContinue_Kind:
309 case Statement::kDiscard_Kind:
310 return statement.clone();
311
312 case Statement::kDo_Kind: {
313 const DoStatement& d = statement.as<DoStatement>();
314 return std::make_unique<DoStatement>(offset, stmt(d.fStatement), expr(d.fTest));
315 }
316 case Statement::kExpression_Kind: {
317 const ExpressionStatement& e = statement.as<ExpressionStatement>();
318 return std::make_unique<ExpressionStatement>(expr(e.fExpression));
319 }
320 case Statement::kFor_Kind: {
321 const ForStatement& f = statement.as<ForStatement>();
322 // need to ensure initializer is evaluated first so that we've already remapped its
323 // declarations by the time we evaluate test & next
324 std::unique_ptr<Statement> initializer = stmt(f.fInitializer);
325 return std::make_unique<ForStatement>(offset, std::move(initializer), expr(f.fTest),
326 expr(f.fNext), stmt(f.fStatement), f.fSymbols);
327 }
328 case Statement::kIf_Kind: {
329 const IfStatement& i = statement.as<IfStatement>();
330 return std::make_unique<IfStatement>(offset, i.fIsStatic, expr(i.fTest),
331 stmt(i.fIfTrue), stmt(i.fIfFalse));
332 }
333 case Statement::kNop_Kind:
334 return statement.clone();
335 case Statement::kReturn_Kind: {
336 const ReturnStatement& r = statement.as<ReturnStatement>();
337 if (r.fExpression) {
338 auto assignment = std::make_unique<ExpressionStatement>(
339 std::make_unique<BinaryExpression>(
340 offset,
341 std::make_unique<VariableReference>(offset, *returnVar,
342 VariableReference::kWrite_RefKind),
343 Token::Kind::TK_EQ,
344 expr(r.fExpression),
345 returnVar->fType));
346 if (haveEarlyReturns) {
347 std::vector<std::unique_ptr<Statement>> block;
348 block.push_back(std::move(assignment));
349 block.emplace_back(new BreakStatement(offset));
350 return std::make_unique<Block>(offset, std::move(block), /*symbols=*/nullptr,
351 /*isScope=*/true);
352 } else {
353 return std::move(assignment);
354 }
355 } else {
356 if (haveEarlyReturns) {
357 return std::make_unique<BreakStatement>(offset);
358 } else {
359 return std::make_unique<Nop>();
360 }
361 }
362 }
363 case Statement::kSwitch_Kind: {
364 const SwitchStatement& ss = statement.as<SwitchStatement>();
365 std::vector<std::unique_ptr<SwitchCase>> cases;
366 for (const auto& sc : ss.fCases) {
367 cases.emplace_back(new SwitchCase(offset, expr(sc->fValue),
368 stmts(sc->fStatements)));
369 }
370 return std::make_unique<SwitchStatement>(offset, ss.fIsStatic, expr(ss.fValue),
371 std::move(cases), ss.fSymbols);
372 }
373 case Statement::kVarDeclaration_Kind: {
374 const VarDeclaration& decl = statement.as<VarDeclaration>();
375 std::vector<std::unique_ptr<Expression>> sizes;
376 for (const auto& size : decl.fSizes) {
377 sizes.push_back(expr(size));
378 }
379 std::unique_ptr<Expression> initialValue = expr(decl.fValue);
380 const Variable* old = decl.fVar;
381 // need to copy the var name in case the originating function is discarded and we lose
382 // its symbols
383 std::unique_ptr<String> name(new String(old->fName));
384 const String* namePtr = symbolTableForStatement->takeOwnershipOfString(std::move(name));
385 const Type* typePtr = copy_if_needed(&old->fType, *symbolTableForStatement);
386 const Variable* clone = symbolTableForStatement->takeOwnershipOfSymbol(
387 std::make_unique<Variable>(offset,
388 old->fModifiers,
389 namePtr->c_str(),
390 *typePtr,
391 old->fStorage,
392 initialValue.get()));
393 (*varMap)[old] = clone;
394 return std::make_unique<VarDeclaration>(clone, std::move(sizes),
395 std::move(initialValue));
396 }
397 case Statement::kVarDeclarations_Kind: {
398 const VarDeclarations& decls = *statement.as<VarDeclarationsStatement>().fDeclaration;
399 std::vector<std::unique_ptr<VarDeclaration>> vars;
400 for (const auto& var : decls.fVars) {
401 vars.emplace_back(&stmt(var).release()->as<VarDeclaration>());
402 }
403 const Type* typePtr = copy_if_needed(&decls.fBaseType, *symbolTableForStatement);
404 return std::unique_ptr<Statement>(new VarDeclarationsStatement(
405 std::make_unique<VarDeclarations>(offset, typePtr, std::move(vars))));
406 }
407 case Statement::kWhile_Kind: {
408 const WhileStatement& w = statement.as<WhileStatement>();
409 return std::make_unique<WhileStatement>(offset, expr(w.fTest), stmt(w.fStatement));
410 }
411 default:
412 SkASSERT(false);
413 return nullptr;
414 }
415}
416
417Inliner::InlinedCall Inliner::inlineCall(std::unique_ptr<FunctionCall> call,
418 SymbolTable* symbolTableForCall) {
419 // Inlining is more complicated here than in a typical compiler, because we have to have a
420 // high-level IR and can't just drop statements into the middle of an expression or even use
421 // gotos.
422 //
423 // Since we can't insert statements into an expression, we run the inline function as extra
424 // statements before the statement we're currently processing, relying on a lack of execution
425 // order guarantees. Since we can't use gotos (which are normally used to replace return
426 // statements), we wrap the whole function in a loop and use break statements to jump to the
427 // end.
428 SkASSERT(fSettings);
429 SkASSERT(fContext);
430 SkASSERT(call);
431 SkASSERT(this->isSafeToInline(*call, /*inlineThreshold=*/INT_MAX));
432
433 int offset = call->fOffset;
434 std::vector<std::unique_ptr<Expression>>& arguments = call->fArguments;
435 const FunctionDefinition& function = *call->fFunction.fDefinition;
436 InlinedCall inlinedCall;
John Stiles39616ec2020-08-31 14:16:06 -0400437 std::vector<std::unique_ptr<Statement>> inlinedBody;
John Stiles44e96be2020-08-31 13:16:04 -0400438
439 // Use unique variable names based on the function signature. Otherwise there are situations in
440 // which an inlined function is later inlined into another function, and we end up with
441 // duplicate names like 'inlineResult0' because the counter was reset. (skbug.com/10526)
442 String raw = function.fDeclaration.description();
443 String inlineSalt;
444 for (size_t i = 0; i < raw.length(); ++i) {
445 char c = raw[i];
446 if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') ||
447 c == '_') {
448 inlineSalt += c;
449 }
450 }
451
452 auto makeInlineVar = [&](const String& name, const Type& type, Modifiers modifiers,
453 std::unique_ptr<Expression>* initialValue) -> const Variable* {
454 // Add our new variable's name to the symbol table.
455 const String* namePtr =
456 symbolTableForCall->takeOwnershipOfString(std::make_unique<String>(name));
457 StringFragment nameFrag{namePtr->c_str(), namePtr->length()};
458
459 // Add our new variable to the symbol table.
460 auto newVar = std::make_unique<Variable>(/*offset=*/-1, Modifiers(), nameFrag, type,
461 Variable::kLocal_Storage, initialValue->get());
462 const Variable* variableSymbol = symbolTableForCall->add(nameFrag, std::move(newVar));
463
464 // Prepare the variable declaration (taking extra care with `out` params to not clobber any
465 // initial value).
466 std::vector<std::unique_ptr<VarDeclaration>> variables;
467 if (initialValue && (modifiers.fFlags & Modifiers::kOut_Flag)) {
468 variables.push_back(std::make_unique<VarDeclaration>(
469 variableSymbol, /*sizes=*/std::vector<std::unique_ptr<Expression>>{},
470 (*initialValue)->clone()));
471 } else {
472 variables.push_back(std::make_unique<VarDeclaration>(
473 variableSymbol, /*sizes=*/std::vector<std::unique_ptr<Expression>>{},
474 std::move(*initialValue)));
475 }
476
477 // Add the new variable-declaration statement to our block of extra statements.
John Stiles39616ec2020-08-31 14:16:06 -0400478 inlinedBody.push_back(std::make_unique<VarDeclarationsStatement>(
John Stiles44e96be2020-08-31 13:16:04 -0400479 std::make_unique<VarDeclarations>(offset, &type, std::move(variables))));
480
481 return variableSymbol;
482 };
483
484 // Create a variable to hold the result in the extra statements (excepting void).
485 const Variable* resultVar = nullptr;
486 if (function.fDeclaration.fReturnType != *fContext->fVoid_Type) {
487 int varIndex = fInlineVarCounter++;
488
489 std::unique_ptr<Expression> noInitialValue;
490 resultVar = makeInlineVar(String::printf("_inlineResult%s%d", inlineSalt.c_str(), varIndex),
491 function.fDeclaration.fReturnType, Modifiers{}, &noInitialValue);
492 }
493
494 // Create variables in the extra statements to hold the arguments, and assign the arguments to
495 // them.
496 VariableRewriteMap varMap;
497 int argIndex = fInlineVarCounter++;
498 for (int i = 0; i < (int) arguments.size(); ++i) {
499 const Variable* param = function.fDeclaration.fParameters[i];
500
501 if (arguments[i]->fKind == Expression::kVariableReference_Kind) {
502 // The argument is just a variable, so we only need to copy it if it's an out parameter
503 // or it's written to within the function.
504 if ((param->fModifiers.fFlags & Modifiers::kOut_Flag) ||
505 !Analysis::StatementWritesToVariable(*function.fBody, *param)) {
506 varMap[param] = &arguments[i]->as<VariableReference>().fVariable;
507 continue;
508 }
509 }
510
511 varMap[param] = makeInlineVar(
512 String::printf("_inlineArg%s%d_%d", inlineSalt.c_str(), argIndex, i),
513 arguments[i]->fType, param->fModifiers, &arguments[i]);
514 }
515
516 const Block& body = function.fBody->as<Block>();
517 bool hasEarlyReturn = has_early_return(function);
518 auto inlineBlock = std::make_unique<Block>(offset, std::vector<std::unique_ptr<Statement>>{});
519 inlineBlock->fStatements.reserve(body.fStatements.size());
520 for (const std::unique_ptr<Statement>& stmt : body.fStatements) {
521 inlineBlock->fStatements.push_back(this->inlineStatement(
522 offset, &varMap, symbolTableForCall, resultVar, hasEarlyReturn, *stmt));
523 }
524 if (hasEarlyReturn) {
525 // Since we output to backends that don't have a goto statement (which would normally be
526 // used to perform an early return), we fake it by wrapping the function in a
527 // do { } while (false); and then use break statements to jump to the end in order to
528 // emulate a goto.
John Stiles39616ec2020-08-31 14:16:06 -0400529 inlinedBody.push_back(std::make_unique<DoStatement>(
John Stiles44e96be2020-08-31 13:16:04 -0400530 /*offset=*/-1,
531 std::move(inlineBlock),
532 std::make_unique<BoolLiteral>(*fContext, offset, /*value=*/false)));
533 } else {
534 // No early returns, so we can just dump the code in. We need to use a block so we don't get
535 // name conflicts with locals.
John Stiles39616ec2020-08-31 14:16:06 -0400536 inlinedBody.push_back(std::move(inlineBlock));
John Stiles44e96be2020-08-31 13:16:04 -0400537 }
538
539 // Copy the values of `out` parameters into their destinations.
540 for (size_t i = 0; i < arguments.size(); ++i) {
541 const Variable* p = function.fDeclaration.fParameters[i];
542 if (p->fModifiers.fFlags & Modifiers::kOut_Flag) {
543 SkASSERT(varMap.find(p) != varMap.end());
544 if (arguments[i]->fKind == Expression::kVariableReference_Kind &&
545 &arguments[i]->as<VariableReference>().fVariable == varMap[p]) {
546 // we didn't create a temporary for this parameter, so there's nothing to copy back
547 // out
548 continue;
549 }
550 auto varRef = std::make_unique<VariableReference>(offset, *varMap[p]);
John Stiles39616ec2020-08-31 14:16:06 -0400551 inlinedBody.push_back(std::make_unique<ExpressionStatement>(
John Stiles44e96be2020-08-31 13:16:04 -0400552 std::make_unique<BinaryExpression>(offset,
553 arguments[i]->clone(),
554 Token::Kind::TK_EQ,
555 std::move(varRef),
556 arguments[i]->fType)));
557 }
558 }
559
560 if (function.fDeclaration.fReturnType != *fContext->fVoid_Type) {
561 // Return a reference to the result variable as our replacement expression.
562 inlinedCall.fReplacementExpr = std::make_unique<VariableReference>(offset, *resultVar);
563 } else {
564 // It's a void function, so it doesn't actually result in anything, but we have to return
565 // something non-null as a standin.
566 inlinedCall.fReplacementExpr = std::make_unique<BoolLiteral>(*fContext, offset,
567 /*value=*/false);
568 }
569
John Stiles39616ec2020-08-31 14:16:06 -0400570 switch (inlinedBody.size()) {
571 case 0:
572 break;
573 case 1:
574 inlinedCall.fInlinedBody = std::move(inlinedBody.front());
575 break;
576 default:
577 inlinedCall.fInlinedBody = std::make_unique<Block>(offset, std::move(inlinedBody),
578 /*symbols=*/nullptr,
579 /*isScope=*/false);
580 break;
581 }
582
John Stiles44e96be2020-08-31 13:16:04 -0400583 return inlinedCall;
584}
585
586bool Inliner::isSafeToInline(const FunctionCall& functionCall,
587 int inlineThreshold) {
588 SkASSERT(fSettings);
589
590 if (functionCall.fFunction.fDefinition == nullptr) {
591 // Can't inline something if we don't actually have its definition.
592 return false;
593 }
594 const FunctionDefinition& functionDef = *functionCall.fFunction.fDefinition;
595 if (inlineThreshold < INT_MAX) {
596 if (!(functionDef.fDeclaration.fModifiers.fFlags & Modifiers::kInline_Flag) &&
597 Analysis::NodeCount(functionDef) >= inlineThreshold) {
598 // The function exceeds our maximum inline size and is not flagged 'inline'.
599 return false;
600 }
601 }
602 if (!fSettings->fCaps || !fSettings->fCaps->canUseDoLoops()) {
603 // We don't have do-while loops. We use do-while loops to simulate early returns, so we
604 // can't inline functions that have an early return.
605 bool hasEarlyReturn = has_early_return(functionDef);
606
607 // If we didn't detect an early return, there shouldn't be any returns in breakable
608 // constructs either.
609 SkASSERT(hasEarlyReturn || count_returns_in_breakable_constructs(functionDef) == 0);
610 return !hasEarlyReturn;
611 }
612 // We have do-while loops, but we don't have any mechanism to simulate early returns within a
613 // breakable construct (switch/for/do/while), so we can't inline if there's a return inside one.
614 bool hasReturnInBreakableConstruct = (count_returns_in_breakable_constructs(functionDef) > 0);
615
616 // If we detected returns in breakable constructs, we should also detect an early return.
617 SkASSERT(!hasReturnInBreakableConstruct || has_early_return(functionDef));
618 return !hasReturnInBreakableConstruct;
619}
620
621} // namespace SkSL