blob: ef872d578f95203f9a82ea9d867a4af941319bc1 [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;
437
438 // Use unique variable names based on the function signature. Otherwise there are situations in
439 // which an inlined function is later inlined into another function, and we end up with
440 // duplicate names like 'inlineResult0' because the counter was reset. (skbug.com/10526)
441 String raw = function.fDeclaration.description();
442 String inlineSalt;
443 for (size_t i = 0; i < raw.length(); ++i) {
444 char c = raw[i];
445 if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') ||
446 c == '_') {
447 inlineSalt += c;
448 }
449 }
450
451 auto makeInlineVar = [&](const String& name, const Type& type, Modifiers modifiers,
452 std::unique_ptr<Expression>* initialValue) -> const Variable* {
453 // Add our new variable's name to the symbol table.
454 const String* namePtr =
455 symbolTableForCall->takeOwnershipOfString(std::make_unique<String>(name));
456 StringFragment nameFrag{namePtr->c_str(), namePtr->length()};
457
458 // Add our new variable to the symbol table.
459 auto newVar = std::make_unique<Variable>(/*offset=*/-1, Modifiers(), nameFrag, type,
460 Variable::kLocal_Storage, initialValue->get());
461 const Variable* variableSymbol = symbolTableForCall->add(nameFrag, std::move(newVar));
462
463 // Prepare the variable declaration (taking extra care with `out` params to not clobber any
464 // initial value).
465 std::vector<std::unique_ptr<VarDeclaration>> variables;
466 if (initialValue && (modifiers.fFlags & Modifiers::kOut_Flag)) {
467 variables.push_back(std::make_unique<VarDeclaration>(
468 variableSymbol, /*sizes=*/std::vector<std::unique_ptr<Expression>>{},
469 (*initialValue)->clone()));
470 } else {
471 variables.push_back(std::make_unique<VarDeclaration>(
472 variableSymbol, /*sizes=*/std::vector<std::unique_ptr<Expression>>{},
473 std::move(*initialValue)));
474 }
475
476 // Add the new variable-declaration statement to our block of extra statements.
477 inlinedCall.fInlinedBody.push_back(std::make_unique<VarDeclarationsStatement>(
478 std::make_unique<VarDeclarations>(offset, &type, std::move(variables))));
479
480 return variableSymbol;
481 };
482
483 // Create a variable to hold the result in the extra statements (excepting void).
484 const Variable* resultVar = nullptr;
485 if (function.fDeclaration.fReturnType != *fContext->fVoid_Type) {
486 int varIndex = fInlineVarCounter++;
487
488 std::unique_ptr<Expression> noInitialValue;
489 resultVar = makeInlineVar(String::printf("_inlineResult%s%d", inlineSalt.c_str(), varIndex),
490 function.fDeclaration.fReturnType, Modifiers{}, &noInitialValue);
491 }
492
493 // Create variables in the extra statements to hold the arguments, and assign the arguments to
494 // them.
495 VariableRewriteMap varMap;
496 int argIndex = fInlineVarCounter++;
497 for (int i = 0; i < (int) arguments.size(); ++i) {
498 const Variable* param = function.fDeclaration.fParameters[i];
499
500 if (arguments[i]->fKind == Expression::kVariableReference_Kind) {
501 // The argument is just a variable, so we only need to copy it if it's an out parameter
502 // or it's written to within the function.
503 if ((param->fModifiers.fFlags & Modifiers::kOut_Flag) ||
504 !Analysis::StatementWritesToVariable(*function.fBody, *param)) {
505 varMap[param] = &arguments[i]->as<VariableReference>().fVariable;
506 continue;
507 }
508 }
509
510 varMap[param] = makeInlineVar(
511 String::printf("_inlineArg%s%d_%d", inlineSalt.c_str(), argIndex, i),
512 arguments[i]->fType, param->fModifiers, &arguments[i]);
513 }
514
515 const Block& body = function.fBody->as<Block>();
516 bool hasEarlyReturn = has_early_return(function);
517 auto inlineBlock = std::make_unique<Block>(offset, std::vector<std::unique_ptr<Statement>>{});
518 inlineBlock->fStatements.reserve(body.fStatements.size());
519 for (const std::unique_ptr<Statement>& stmt : body.fStatements) {
520 inlineBlock->fStatements.push_back(this->inlineStatement(
521 offset, &varMap, symbolTableForCall, resultVar, hasEarlyReturn, *stmt));
522 }
523 if (hasEarlyReturn) {
524 // Since we output to backends that don't have a goto statement (which would normally be
525 // used to perform an early return), we fake it by wrapping the function in a
526 // do { } while (false); and then use break statements to jump to the end in order to
527 // emulate a goto.
528 inlinedCall.fInlinedBody.push_back(std::make_unique<DoStatement>(
529 /*offset=*/-1,
530 std::move(inlineBlock),
531 std::make_unique<BoolLiteral>(*fContext, offset, /*value=*/false)));
532 } else {
533 // No early returns, so we can just dump the code in. We need to use a block so we don't get
534 // name conflicts with locals.
535 inlinedCall.fInlinedBody.push_back(std::move(inlineBlock));
536 }
537
538 // Copy the values of `out` parameters into their destinations.
539 for (size_t i = 0; i < arguments.size(); ++i) {
540 const Variable* p = function.fDeclaration.fParameters[i];
541 if (p->fModifiers.fFlags & Modifiers::kOut_Flag) {
542 SkASSERT(varMap.find(p) != varMap.end());
543 if (arguments[i]->fKind == Expression::kVariableReference_Kind &&
544 &arguments[i]->as<VariableReference>().fVariable == varMap[p]) {
545 // we didn't create a temporary for this parameter, so there's nothing to copy back
546 // out
547 continue;
548 }
549 auto varRef = std::make_unique<VariableReference>(offset, *varMap[p]);
550 inlinedCall.fInlinedBody.push_back(std::make_unique<ExpressionStatement>(
551 std::make_unique<BinaryExpression>(offset,
552 arguments[i]->clone(),
553 Token::Kind::TK_EQ,
554 std::move(varRef),
555 arguments[i]->fType)));
556 }
557 }
558
559 if (function.fDeclaration.fReturnType != *fContext->fVoid_Type) {
560 // Return a reference to the result variable as our replacement expression.
561 inlinedCall.fReplacementExpr = std::make_unique<VariableReference>(offset, *resultVar);
562 } else {
563 // It's a void function, so it doesn't actually result in anything, but we have to return
564 // something non-null as a standin.
565 inlinedCall.fReplacementExpr = std::make_unique<BoolLiteral>(*fContext, offset,
566 /*value=*/false);
567 }
568
569 return inlinedCall;
570}
571
572bool Inliner::isSafeToInline(const FunctionCall& functionCall,
573 int inlineThreshold) {
574 SkASSERT(fSettings);
575
576 if (functionCall.fFunction.fDefinition == nullptr) {
577 // Can't inline something if we don't actually have its definition.
578 return false;
579 }
580 const FunctionDefinition& functionDef = *functionCall.fFunction.fDefinition;
581 if (inlineThreshold < INT_MAX) {
582 if (!(functionDef.fDeclaration.fModifiers.fFlags & Modifiers::kInline_Flag) &&
583 Analysis::NodeCount(functionDef) >= inlineThreshold) {
584 // The function exceeds our maximum inline size and is not flagged 'inline'.
585 return false;
586 }
587 }
588 if (!fSettings->fCaps || !fSettings->fCaps->canUseDoLoops()) {
589 // We don't have do-while loops. We use do-while loops to simulate early returns, so we
590 // can't inline functions that have an early return.
591 bool hasEarlyReturn = has_early_return(functionDef);
592
593 // If we didn't detect an early return, there shouldn't be any returns in breakable
594 // constructs either.
595 SkASSERT(hasEarlyReturn || count_returns_in_breakable_constructs(functionDef) == 0);
596 return !hasEarlyReturn;
597 }
598 // We have do-while loops, but we don't have any mechanism to simulate early returns within a
599 // breakable construct (switch/for/do/while), so we can't inline if there's a return inside one.
600 bool hasReturnInBreakableConstruct = (count_returns_in_breakable_constructs(functionDef) > 0);
601
602 // If we detected returns in breakable constructs, we should also detect an early return.
603 SkASSERT(!hasReturnInBreakableConstruct || has_early_return(functionDef));
604 return !hasReturnInBreakableConstruct;
605}
606
607} // namespace SkSL