Debian Codegraph @

src/sksl/SkSLInliner.cpp

raw
1 /*
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 #ifndef SK_ENABLE_OPTIMIZE_SIZE
11
12 #include "include/core/SkSpan.h"
13 #include "include/core/SkTypes.h"
14 #include "include/private/base/SkTArray.h"
15 #include "src/base/SkEnumBitMask.h"
16 #include "src/sksl/SkSLAnalysis.h"
17 #include "src/sksl/SkSLDefines.h"
18 #include "src/sksl/SkSLErrorReporter.h"
19 #include "src/sksl/SkSLOperator.h"
20 #include "src/sksl/SkSLPosition.h"
21 #include "src/sksl/analysis/SkSLProgramUsage.h"
22 #include "src/sksl/ir/SkSLBinaryExpression.h"
23 #include "src/sksl/ir/SkSLBreakStatement.h"
24 #include "src/sksl/ir/SkSLChildCall.h"
25 #include "src/sksl/ir/SkSLConstructor.h"
26 #include "src/sksl/ir/SkSLConstructorArray.h"
27 #include "src/sksl/ir/SkSLConstructorArrayCast.h"
28 #include "src/sksl/ir/SkSLConstructorCompound.h"
29 #include "src/sksl/ir/SkSLConstructorCompoundCast.h"
30 #include "src/sksl/ir/SkSLConstructorDiagonalMatrix.h"
31 #include "src/sksl/ir/SkSLConstructorMatrixResize.h"
32 #include "src/sksl/ir/SkSLConstructorScalarCast.h"
33 #include "src/sksl/ir/SkSLConstructorSplat.h"
34 #include "src/sksl/ir/SkSLConstructorStruct.h"
35 #include "src/sksl/ir/SkSLContinueStatement.h"
36 #include "src/sksl/ir/SkSLDiscardStatement.h"
37 #include "src/sksl/ir/SkSLDoStatement.h"
38 #include "src/sksl/ir/SkSLEmptyExpression.h"
39 #include "src/sksl/ir/SkSLExpressionStatement.h"
40 #include "src/sksl/ir/SkSLFieldAccess.h"
41 #include "src/sksl/ir/SkSLForStatement.h"
42 #include "src/sksl/ir/SkSLFunctionCall.h"
43 #include "src/sksl/ir/SkSLFunctionDeclaration.h"
44 #include "src/sksl/ir/SkSLFunctionDefinition.h"
45 #include "src/sksl/ir/SkSLIRNode.h"
46 #include "src/sksl/ir/SkSLIfStatement.h"
47 #include "src/sksl/ir/SkSLIndexExpression.h"
48 #include "src/sksl/ir/SkSLModifierFlags.h"
49 #include "src/sksl/ir/SkSLNop.h"
50 #include "src/sksl/ir/SkSLPostfixExpression.h"
51 #include "src/sksl/ir/SkSLPrefixExpression.h"
52 #include "src/sksl/ir/SkSLProgramElement.h"
53 #include "src/sksl/ir/SkSLReturnStatement.h"
54 #include "src/sksl/ir/SkSLSetting.h"
55 #include "src/sksl/ir/SkSLStatement.h"
56 #include "src/sksl/ir/SkSLSwitchCase.h"
57 #include "src/sksl/ir/SkSLSwitchStatement.h"
58 #include "src/sksl/ir/SkSLSwizzle.h"
59 #include "src/sksl/ir/SkSLSymbolTable.h"
60 #include "src/sksl/ir/SkSLTernaryExpression.h"
61 #include "src/sksl/ir/SkSLType.h"
62 #include "src/sksl/ir/SkSLVarDeclarations.h"
63 #include "src/sksl/ir/SkSLVariable.h"
64 #include "src/sksl/ir/SkSLVariableReference.h"
65 #include "src/sksl/transform/SkSLTransform.h"
66
67 #include <algorithm>
68 #include <climits>
69 #include <cstddef>
70 #include <memory>
71 #include <string>
72 #include <string_view>
73 #include <utility>
74
75 using namespace skia_private;
76
77 namespace SkSL {
78 namespace {
79
80 static bool is_scopeless_block(Statement* stmt) {
81 return stmt->is<Block>() && !stmt->as<Block>().isScope();
82 }
83
84 static std::unique_ptr<Statement>* find_parent_statement(
85 const std::vector<std::unique_ptr<Statement>*>& stmtStack) {
86 SkASSERT(!stmtStack.empty());
87
88 // Walk the statement stack from back to front, ignoring the last element (which is the
89 // enclosing statement).
90 auto iter = stmtStack.rbegin();
91 ++iter;
92
93 // Anything counts as a parent statement other than a scopeless Block.
94 for (; iter != stmtStack.rend(); ++iter) {
95 std::unique_ptr<Statement>* stmt = *iter;
96 if (!is_scopeless_block(stmt->get())) {
97 return stmt;
98 }
99 }
100
101 // There wasn't any parent statement to be found.
102 return nullptr;
103 }
104
105 std::unique_ptr<Expression> clone_with_ref_kind(const Expression& expr,
106 VariableReference::RefKind refKind,
107 Position pos) {
108 std::unique_ptr<Expression> clone = expr.clone(pos);
109 Analysis::UpdateVariableRefKind(clone.get(), refKind);
110 return clone;
111 }
112
113 } // namespace
114
115 const Variable* Inliner::RemapVariable(const Variable* variable,
116 const VariableRewriteMap* varMap) {
117 std::unique_ptr<Expression>* remap = varMap->find(variable);
118 if (!remap) {
119 SkDEBUGFAILF("rewrite map does not contain variable '%.*s'",
120 (int)variable->name().size(), variable->name().data());
121 return variable;
122 }
123 Expression* expr = remap->get();
124 SkASSERT(expr);
125 if (!expr->is<VariableReference>()) {
126 SkDEBUGFAILF("rewrite map contains non-variable replacement for '%.*s'",
127 (int)variable->name().size(), variable->name().data());
128 return variable;
129 }
130 return expr->as<VariableReference>().variable();
131 }
132
133 void Inliner::ensureScopedBlocks(Statement* inlinedBody, Statement* parentStmt) {
134 // No changes necessary if this statement isn't actually a block.
135 if (!inlinedBody || !inlinedBody->is<Block>()) {
136 return;
137 }
138
139 // No changes necessary if the parent statement doesn't require a scope.
140 if (!parentStmt || !(parentStmt->is<IfStatement>() || parentStmt->is<ForStatement>() ||
141 parentStmt->is<DoStatement>() || is_scopeless_block(parentStmt))) {
142 return;
143 }
144
145 Block& block = inlinedBody->as<Block>();
146
147 // The inliner will create inlined function bodies as a Block containing multiple statements,
148 // but no scope. Normally, this is fine, but if this block is used as the statement for a
149 // do/for/if/while, the block needs to be scoped for the generated code to match the intent.
150 // In the case of Blocks nested inside other Blocks, we add the scope to the outermost block if
151 // needed.
152 for (Block* nestedBlock = &block;; ) {
153 if (nestedBlock->isScope()) {
154 // We found an explicit scope; all is well.
155 return;
156 }
157 if (nestedBlock->children().size() == 1 && nestedBlock->children()[0]->is<Block>()) {
158 // This block wraps another unscoped block; we need to go deeper.
159 nestedBlock = &nestedBlock->children()[0]->as<Block>();
160 continue;
161 }
162 // We found a block containing real statements (not just more blocks), but no scope.
163 // Let's add a scope to the outermost block.
164 block.setBlockKind(Block::Kind::kBracedScope);
165 return;
166 }
167 }
168
169 std::unique_ptr<Expression> Inliner::inlineExpression(Position pos,
170 VariableRewriteMap* varMap,
171 SymbolTable* symbolTableForExpression,
172 const Expression& expression) {
173 auto expr = [&](const std::unique_ptr<Expression>& e) -> std::unique_ptr<Expression> {
174 if (e) {
175 return this->inlineExpression(pos, varMap, symbolTableForExpression, *e);
176 }
177 return nullptr;
178 };
179 auto argList = [&](const ExpressionArray& originalArgs) -> ExpressionArray {
180 ExpressionArray args;
181 args.reserve_exact(originalArgs.size());
182 for (const std::unique_ptr<Expression>& arg : originalArgs) {
183 args.push_back(expr(arg));
184 }
185 return args;
186 };
187 auto childRemap = [&](const Variable& var) -> const Variable& {
188 // If our variable remapping table contains the passed-in variable...
189 if (std::unique_ptr<Expression>* remap = varMap->find(&var)) {
190 // ... the remapped expression _must_ be another variable reference.
191 // SkSL doesn't allow opaque types to participate in complex expressions.
192 if ((*remap)->is<VariableReference>()) {
193 const VariableReference& remappedRef = (*remap)->as<VariableReference>();
194 return *remappedRef.variable();
195 } else {
196 SkDEBUGFAILF("Child effect '%.*s' remaps to unexpected expression '%s'",
197 (int)var.name().size(), var.name().data(),
198 (*remap)->description().c_str());
199 }
200 }
201
202 // There's no remapping for this; return it as-is.
203 return var;
204 };
205
206 switch (expression.kind()) {
207 case Expression::Kind::kBinary: {
208 const BinaryExpression& binaryExpr = expression.as<BinaryExpression>();
209 return BinaryExpression::Make(*fContext,
210 pos,
211 expr(binaryExpr.left()),
212 binaryExpr.getOperator(),
213 expr(binaryExpr.right()));
214 }
215 case Expression::Kind::kEmpty:
216 return expression.clone(pos);
217 case Expression::Kind::kLiteral:
218 return expression.clone(pos);
219 case Expression::Kind::kChildCall: {
220 const ChildCall& childCall = expression.as<ChildCall>();
221 return ChildCall::Make(*fContext,
222 pos,
223 childCall.type().clone(*fContext, symbolTableForExpression),
224 childRemap(childCall.child()),
225 argList(childCall.arguments()));
226 }
227 case Expression::Kind::kConstructorArray: {
228 const ConstructorArray& ctor = expression.as<ConstructorArray>();
229 return ConstructorArray::Make(*fContext,
230 pos,
231 *ctor.type().clone(*fContext, symbolTableForExpression),
232 argList(ctor.arguments()));
233 }
234 case Expression::Kind::kConstructorArrayCast: {
235 const ConstructorArrayCast& ctor = expression.as<ConstructorArrayCast>();
236 return ConstructorArrayCast::Make(
237 *fContext,
238 pos,
239 *ctor.type().clone(*fContext, symbolTableForExpression),
240 expr(ctor.argument()));
241 }
242 case Expression::Kind::kConstructorCompound: {
243 const ConstructorCompound& ctor = expression.as<ConstructorCompound>();
244 return ConstructorCompound::Make(
245 *fContext,
246 pos,
247 *ctor.type().clone(*fContext, symbolTableForExpression),
248 argList(ctor.arguments()));
249 }
250 case Expression::Kind::kConstructorCompoundCast: {
251 const ConstructorCompoundCast& ctor = expression.as<ConstructorCompoundCast>();
252 return ConstructorCompoundCast::Make(
253 *fContext,
254 pos,
255 *ctor.type().clone(*fContext, symbolTableForExpression),
256 expr(ctor.argument()));
257 }
258 case Expression::Kind::kConstructorDiagonalMatrix: {
259 const ConstructorDiagonalMatrix& ctor = expression.as<ConstructorDiagonalMatrix>();
260 return ConstructorDiagonalMatrix::Make(
261 *fContext,
262 pos,
263 *ctor.type().clone(*fContext, symbolTableForExpression),
264 expr(ctor.argument()));
265 }
266 case Expression::Kind::kConstructorMatrixResize: {
267 const ConstructorMatrixResize& ctor = expression.as<ConstructorMatrixResize>();
268 return ConstructorMatrixResize::Make(
269 *fContext,
270 pos,
271 *ctor.type().clone(*fContext, symbolTableForExpression),
272 expr(ctor.argument()));
273 }
274 case Expression::Kind::kConstructorScalarCast: {
275 const ConstructorScalarCast& ctor = expression.as<ConstructorScalarCast>();
276 return ConstructorScalarCast::Make(
277 *fContext,
278 pos,
279 *ctor.type().clone(*fContext, symbolTableForExpression),
280 expr(ctor.argument()));
281 }
282 case Expression::Kind::kConstructorSplat: {
283 const ConstructorSplat& ctor = expression.as<ConstructorSplat>();
284 return ConstructorSplat::Make(*fContext,
285 pos,
286 *ctor.type().clone(*fContext, symbolTableForExpression),
287 expr(ctor.argument()));
288 }
289 case Expression::Kind::kConstructorStruct: {
290 const ConstructorStruct& ctor = expression.as<ConstructorStruct>();
291 return ConstructorStruct::Make(*fContext,
292 pos,
293 *ctor.type().clone(*fContext, symbolTableForExpression),
294 argList(ctor.arguments()));
295 }
296 case Expression::Kind::kFieldAccess: {
297 const FieldAccess& f = expression.as<FieldAccess>();
298 return FieldAccess::Make(*fContext, pos, expr(f.base()), f.fieldIndex(), f.ownerKind());
299 }
300 case Expression::Kind::kFunctionCall: {
301 const FunctionCall& funcCall = expression.as<FunctionCall>();
302 return FunctionCall::Make(*fContext,
303 pos,
304 funcCall.type().clone(*fContext, symbolTableForExpression),
305 funcCall.function(),
306 argList(funcCall.arguments()));
307 }
308 case Expression::Kind::kFunctionReference:
309 return expression.clone(pos);
310 case Expression::Kind::kIndex: {
311 const IndexExpression& idx = expression.as<IndexExpression>();
312 return IndexExpression::Make(*fContext, pos, expr(idx.base()), expr(idx.index()));
313 }
314 case Expression::Kind::kMethodReference:
315 return expression.clone(pos);
316 case Expression::Kind::kPrefix: {
317 const PrefixExpression& p = expression.as<PrefixExpression>();
318 return PrefixExpression::Make(*fContext, pos, p.getOperator(), expr(p.operand()));
319 }
320 case Expression::Kind::kPostfix: {
321 const PostfixExpression& p = expression.as<PostfixExpression>();
322 return PostfixExpression::Make(*fContext, pos, expr(p.operand()), p.getOperator());
323 }
324 case Expression::Kind::kSetting: {
325 const Setting& s = expression.as<Setting>();
326 return Setting::Make(*fContext, pos, s.capsPtr());
327 }
328 case Expression::Kind::kSwizzle: {
329 const Swizzle& s = expression.as<Swizzle>();
330 return Swizzle::Make(*fContext, pos, expr(s.base()), s.components());
331 }
332 case Expression::Kind::kTernary: {
333 const TernaryExpression& t = expression.as<TernaryExpression>();
334 return TernaryExpression::Make(*fContext, pos, expr(t.test()),
335 expr(t.ifTrue()), expr(t.ifFalse()));
336 }
337 case Expression::Kind::kTypeReference:
338 return expression.clone(pos);
339 case Expression::Kind::kVariableReference: {
340 const VariableReference& v = expression.as<VariableReference>();
341 std::unique_ptr<Expression>* remap = varMap->find(v.variable());
342 if (remap) {
343 return clone_with_ref_kind(**remap, v.refKind(), pos);
344 }
345 return expression.clone(pos);
346 }
347 default:
348 SkDEBUGFAILF("unsupported expression: %s", expression.description().c_str());
349 return nullptr;
350 }
351 }
352
353 std::unique_ptr<Statement> Inliner::inlineStatement(Position pos,
354 VariableRewriteMap* varMap,
355 SymbolTable* symbolTableForStatement,
356 std::unique_ptr<Expression>* resultExpr,
357 Analysis::ReturnComplexity returnComplexity,
358 const Statement& statement,
359 const ProgramUsage& usage,
360 bool isBuiltinCode) {
361 auto stmt = [&](const std::unique_ptr<Statement>& s) -> std::unique_ptr<Statement> {
362 if (s) {
363 return this->inlineStatement(pos, varMap, symbolTableForStatement, resultExpr,
364 returnComplexity, *s, usage, isBuiltinCode);
365 }
366 return nullptr;
367 };
368 auto expr = [&](const std::unique_ptr<Expression>& e) -> std::unique_ptr<Expression> {
369 if (e) {
370 return this->inlineExpression(pos, varMap, symbolTableForStatement, *e);
371 }
372 return nullptr;
373 };
374 auto variableModifiers = [&](const Variable& variable,
375 const Expression* initialValue) -> ModifierFlags {
376 return Transform::AddConstToVarModifiers(variable, initialValue, &usage);
377 };
378 auto makeWithChildSymbolTable = [&](auto callback) -> std::unique_ptr<Statement> {
379 SymbolTable* origSymbolTable = symbolTableForStatement;
380 auto childSymbols = std::make_unique<SymbolTable>(origSymbolTable, isBuiltinCode);
381 symbolTableForStatement = childSymbols.get();
382
383 std::unique_ptr<Statement> stmt = callback(std::move(childSymbols));
384
385 symbolTableForStatement = origSymbolTable;
386 return stmt;
387 };
388
389 ++fInlinedStatementCounter;
390
391 switch (statement.kind()) {
392 case Statement::Kind::kBlock:
393 return makeWithChildSymbolTable([&](std::unique_ptr<SymbolTable> symbolTable) {
394 const Block& block = statement.as<Block>();
395 StatementArray statements;
396 statements.reserve_exact(block.children().size());
397 for (const std::unique_ptr<Statement>& child : block.children()) {
398 statements.push_back(stmt(child));
399 }
400 return Block::Make(pos,
401 std::move(statements),
402 block.blockKind(),
403 std::move(symbolTable));
404 });
405
406 case Statement::Kind::kBreak:
407 return BreakStatement::Make(pos);
408
409 case Statement::Kind::kContinue:
410 return ContinueStatement::Make(pos);
411
412 case Statement::Kind::kDiscard:
413 return DiscardStatement::Make(*fContext, pos);
414
415 case Statement::Kind::kDo: {
416 const DoStatement& d = statement.as<DoStatement>();
417 return DoStatement::Make(*fContext, pos, stmt(d.statement()), expr(d.test()));
418 }
419 case Statement::Kind::kExpression: {
420 const ExpressionStatement& e = statement.as<ExpressionStatement>();
421 return ExpressionStatement::Make(*fContext, expr(e.expression()));
422 }
423 case Statement::Kind::kFor:
424 return makeWithChildSymbolTable([&](std::unique_ptr<SymbolTable> symbolTable) {
425 const ForStatement& f = statement.as<ForStatement>();
426 // We need to ensure `initializer` is evaluated first, so that we've already
427 // remapped its declaration by the time we evaluate `test` and `next`.
428 std::unique_ptr<Statement> initializerStmt = stmt(f.initializer());
429 std::unique_ptr<Expression> testExpr = expr(f.test());
430 std::unique_ptr<Expression> nextExpr = expr(f.next());
431 std::unique_ptr<Statement> bodyStmt = stmt(f.statement());
432
433 std::unique_ptr<LoopUnrollInfo> unrollInfo;
434 if (f.unrollInfo()) {
435 // The for loop's unroll-info points to the Variable in the initializer as the
436 // index. This variable has been rewritten into a clone by the inliner, so we
437 // need to update the loop-unroll info to point to the clone.
438 unrollInfo = std::make_unique<LoopUnrollInfo>(*f.unrollInfo());
439 unrollInfo->fIndex = RemapVariable(unrollInfo->fIndex, varMap);
440 }
441
442 return ForStatement::Make(*fContext, pos, ForLoopPositions{},
443 std::move(initializerStmt),
444 std::move(testExpr),
445 std::move(nextExpr),
446 std::move(bodyStmt),
447 std::move(unrollInfo),
448 std::move(symbolTable));
449 });
450
451 case Statement::Kind::kIf: {
452 const IfStatement& i = statement.as<IfStatement>();
453 return IfStatement::Make(*fContext, pos, expr(i.test()),
454 stmt(i.ifTrue()), stmt(i.ifFalse()));
455 }
456 case Statement::Kind::kNop:
457 return Nop::Make();
458
459 case Statement::Kind::kReturn: {
460 const ReturnStatement& r = statement.as<ReturnStatement>();
461 if (!r.expression()) {
462 // This function doesn't return a value. We won't inline functions with early
463 // returns, so a return statement is a no-op and can be treated as such.
464 return Nop::Make();
465 }
466
467 // If a function only contains a single return, and it doesn't reference variables from
468 // inside an Block's scope, we don't need to store the result in a variable at all. Just
469 // replace the function-call expression with the function's return expression.
470 SkASSERT(resultExpr);
471 if (returnComplexity <= Analysis::ReturnComplexity::kSingleSafeReturn) {
472 *resultExpr = expr(r.expression());
473 return Nop::Make();
474 }
475
476 // For more complex functions, we assign their result into a variable. We refuse to
477 // inline anything with early returns, so this should be safe to do; that is, on this
478 // control path, this is the last statement that will occur.
479 SkASSERT(*resultExpr);
480 return ExpressionStatement::Make(
481 *fContext,
482 BinaryExpression::Make(
483 *fContext,
484 pos,
485 clone_with_ref_kind(**resultExpr, VariableRefKind::kWrite, pos),
486 Operator::Kind::EQ,
487 expr(r.expression())));
488 }
489 case Statement::Kind::kSwitch: {
490 const SwitchStatement& ss = statement.as<SwitchStatement>();
491 return SwitchStatement::Make(*fContext, pos, expr(ss.value()), stmt(ss.caseBlock()));
492 }
493 case Statement::Kind::kSwitchCase: {
494 const SwitchCase& sc = statement.as<SwitchCase>();
495 return sc.isDefault() ? SwitchCase::MakeDefault(pos, stmt(sc.statement()))
496 : SwitchCase::Make(pos, sc.value(), stmt(sc.statement()));
497 }
498 case Statement::Kind::kVarDeclaration: {
499 const VarDeclaration& decl = statement.as<VarDeclaration>();
500 std::unique_ptr<Expression> initialValue = expr(decl.value());
501 const Variable* variable = decl.var();
502
503 // We assign unique names to inlined variables--scopes hide most of the problems in this
504 // regard, but see `InlinerAvoidsVariableNameOverlap` for a counterexample where unique
505 // names are important.
506 const std::string* name = symbolTableForStatement->takeOwnershipOfString(
507 fMangler.uniqueName(variable->name(), symbolTableForStatement));
508 auto clonedVar =
509 Variable::Make(pos,
510 variable->modifiersPosition(),
511 variable->layout(),
512 variableModifiers(*variable, initialValue.get()),
513 variable->type().clone(*fContext, symbolTableForStatement),
514 name->c_str(),
515 /*mangledName=*/"",
516 isBuiltinCode,
517 variable->storage());
518 varMap->set(variable, VariableReference::Make(pos, clonedVar.get()));
519 std::unique_ptr<Statement> result =
520 VarDeclaration::Make(*fContext,
521 clonedVar.get(),
522 decl.baseType().clone(*fContext, symbolTableForStatement),
523 decl.arraySize(),
524 std::move(initialValue));
525 symbolTableForStatement->add(*fContext, std::move(clonedVar));
526 return result;
527 }
528 default:
529 SkASSERT(false);
530 return nullptr;
531 }
532 }
533
534 static bool argument_needs_scratch_variable(const Expression* arg,
535 const Variable* param,
536 const ProgramUsage& usage) {
537 // If the parameter isn't written to within the inline function ...
538 const ProgramUsage::VariableCounts& paramUsage = usage.get(*param);
539 if (!paramUsage.fWrite) {
540 // ... and it can be inlined trivially (e.g. a swizzle, or a constant array index),
541 // or it is any expression without side effects that is only accessed at most once...
542 if ((paramUsage.fRead > 1) ? Analysis::IsTrivialExpression(*arg)
543 : !Analysis::HasSideEffects(*arg)) {
544 // ... we don't need to copy it at all! We can just use the existing expression.
545 return false;
546 }
547 }
548 // We need a scratch variable.
549 return true;
550 }
551
552 Inliner::InlinedCall Inliner::inlineCall(const FunctionCall& call,
553 SymbolTable* symbolTable,
554 const ProgramUsage& usage,
555 const FunctionDeclaration* caller) {
556 using ScratchVariable = Variable::ScratchVariable;
557
558 // Inlining is more complicated here than in a typical compiler, because we have to have a
559 // high-level IR and can't just drop statements into the middle of an expression or even use
560 // gotos.
561 //
562 // Since we can't insert statements into an expression, we run the inline function as extra
563 // statements before the statement we're currently processing, relying on a lack of execution
564 // order guarantees.
565 SkASSERT(fContext);
566 SkASSERT(this->isSafeToInline(call.function().definition(), usage));
567
568 const ExpressionArray& arguments = call.arguments();
569 const Position pos = call.fPosition;
570 const FunctionDefinition& function = *call.function().definition();
571 const Block& body = function.body()->as<Block>();
572 const Analysis::ReturnComplexity returnComplexity = Analysis::GetReturnComplexity(function);
573
574 StatementArray inlineStatements;
575 int expectedStmtCount = 1 + // Result variable
576 arguments.size() + // Function argument temp-vars
577 body.children().size(); // Inlined code
578
579 inlineStatements.reserve_exact(expectedStmtCount);
580
581 std::unique_ptr<Expression> resultExpr;
582 if (returnComplexity > Analysis::ReturnComplexity::kSingleSafeReturn &&
583 !function.declaration().returnType().isVoid()) {
584 // Create a variable to hold the result in the extra statements. We don't need to do this
585 // for void-return functions, or in cases that are simple enough that we can just replace
586 // the function-call node with the result expression.
587 ScratchVariable var = Variable::MakeScratchVariable(*fContext,
588 fMangler,
589 function.declaration().name(),
590 &function.declaration().returnType(),
591 symbolTable,
592 /*initialValue=*/nullptr);
593 inlineStatements.push_back(std::move(var.fVarDecl));
594 resultExpr = VariableReference::Make(Position(), var.fVarSymbol);
595 }
596
597 // Create variables in the extra statements to hold the arguments, and assign the arguments to
598 // them.
599 VariableRewriteMap varMap;
600 for (int i = 0; i < arguments.size(); ++i) {
601 const Expression* arg = arguments[i].get();
602 const Variable* param = function.declaration().parameters()[i];
603 if (!argument_needs_scratch_variable(arg, param, usage)) {
604 varMap.set(param, arg->clone());
605 continue;
606 }
607 ScratchVariable var = Variable::MakeScratchVariable(*fContext,
608 fMangler,
609 param->name(),
610 &arg->type(),
611 symbolTable,
612 arg->clone());
613 inlineStatements.push_back(std::move(var.fVarDecl));
614 varMap.set(param, VariableReference::Make(Position(), var.fVarSymbol));
615 }
616
617 for (const std::unique_ptr<Statement>& stmt : body.children()) {
618 inlineStatements.push_back(this->inlineStatement(pos, &varMap, symbolTable,
619 &resultExpr, returnComplexity, *stmt,
620 usage, caller->isBuiltin()));
621 }
622
623 SkASSERT(inlineStatements.size() <= expectedStmtCount);
624
625 // Wrap all of the generated statements in a block. We need a real Block here, because we need
626 // to add another child statement to the Block later.
627 InlinedCall inlinedCall;
628 inlinedCall.fInlinedBody = Block::MakeBlock(pos, std::move(inlineStatements),
629 Block::Kind::kUnbracedBlock);
630 if (resultExpr) {
631 // Return our result expression as-is.
632 inlinedCall.fReplacementExpr = std::move(resultExpr);
633 } else if (function.declaration().returnType().isVoid()) {
634 // It's a void function, so its result is the empty expression.
635 inlinedCall.fReplacementExpr = EmptyExpression::Make(pos, *fContext);
636 } else {
637 // It's a non-void function, but it never created a result expression--that is, it never
638 // returned anything on any path! This should have been detected in the function finalizer.
639 // Still, discard our output and generate an error.
640 SkDEBUGFAIL("inliner found non-void function that fails to return a value on any path");
641 fContext->fErrors->error(function.fPosition, "inliner found non-void function '" +
642 std::string(function.declaration().name()) +
643 "' that fails to return a value on any path");
644 inlinedCall = {};
645 }
646
647 return inlinedCall;
648 }
649
650 bool Inliner::overInlineStatementLimit() const {
651 // Enforce a limit on inlining to avoid pathological cases. (inliner/ExponentialGrowth.sksl)
652 // Modules, which are entirely built-in SkSL, do not need to be limited in this way.
653 static constexpr int kInlinedStatementLimit = 2500;
654 return !fContext->fConfig->isBuiltinCode() &&
655 fInlinedStatementCounter >= kInlinedStatementLimit;
656 }
657
658 bool Inliner::isSafeToInline(const FunctionDefinition* functionDef, const ProgramUsage& usage) {
659 // A threshold of zero indicates that the inliner is completely disabled, so we can just return.
660 if (this->settings().fInlineThreshold <= 0) {
661 return false;
662 }
663
664 // Enforce a limit on inlining to avoid pathological cases. (inliner/ExponentialGrowth.sksl)
665 if (this->overInlineStatementLimit()) {
666 return false;
667 }
668
669 if (functionDef == nullptr) {
670 // Can't inline something if we don't actually have its definition.
671 return false;
672 }
673
674 if (functionDef->declaration().modifierFlags().isNoInline()) {
675 // Refuse to inline functions decorated with `noinline`.
676 return false;
677 }
678
679 for (const Variable* param : functionDef->declaration().parameters()) {
680 // We don't allow inlining functions with parameters that are written-to, if they...
681 // - are `out` parameters (see skbug.com/40042700 for rationale.)
682 // - are arrays or structures (introducing temporary copies is non-trivial)
683 if ((param->modifierFlags() & ModifierFlag::kOut) ||
684 param->type().isArray() ||
685 param->type().isStruct()) {
686 ProgramUsage::VariableCounts counts = usage.get(*param);
687 if (counts.fWrite > 0) {
688 return false;
689 }
690 }
691 }
692
693 // We don't have a mechanism to simulate early returns, so we can't inline if there is one.
694 return Analysis::GetReturnComplexity(*functionDef) < Analysis::ReturnComplexity::kEarlyReturns;
695 }
696
697 // A candidate function for inlining, containing everything that `inlineCall` needs.
698 struct InlineCandidate {
699 SymbolTable* fSymbols; // the SymbolTable of the candidate
700 std::unique_ptr<Statement>* fParentStmt; // the parent Statement of the enclosing stmt
701 std::unique_ptr<Statement>* fEnclosingStmt; // the Statement containing the candidate
702 std::unique_ptr<Expression>* fCandidateExpr; // the candidate FunctionCall to be inlined
703 FunctionDefinition* fEnclosingFunction; // the Function containing the candidate
704 };
705
706 struct InlineCandidateList {
707 std::vector<InlineCandidate> fCandidates;
708 };
709
710 class InlineCandidateAnalyzer {
711 public:
712 // A list of all the inlining candidates we found during analysis.
713 InlineCandidateList* fCandidateList;
714
715 // A stack of the symbol tables; since most nodes don't have one, expected to be shallower than
716 // the enclosing-statement stack.
717 std::vector<SymbolTable*> fSymbolTableStack;
718 // A stack of "enclosing" statements--these would be suitable for the inliner to use for adding
719 // new instructions. Not all statements are suitable (e.g. a for-loop's initializer). The
720 // inliner might replace a statement with a block containing the statement.
721 std::vector<std::unique_ptr<Statement>*> fEnclosingStmtStack;
722 // The function that we're currently processing (i.e. inlining into).
723 FunctionDefinition* fEnclosingFunction = nullptr;
724
725 void visit(const std::vector<std::unique_ptr<ProgramElement>>& elements,
726 SymbolTable* symbols,
727 InlineCandidateList* candidateList) {
728 fCandidateList = candidateList;
729 fSymbolTableStack.push_back(symbols);
730
731 for (const std::unique_ptr<ProgramElement>& pe : elements) {
732 this->visitProgramElement(pe.get());
733 }
734
735 fSymbolTableStack.pop_back();
736 fCandidateList = nullptr;
737 }
738
739 void visitProgramElement(ProgramElement* pe) {
740 switch (pe->kind()) {
741 case ProgramElement::Kind::kFunction: {
742 FunctionDefinition& funcDef = pe->as<FunctionDefinition>();
743
744 // If this function has parameter names that would shadow globally-scoped names, we
745 // don't scan it for inline candidates, because it's too late to mangle the names.
746 bool foundShadowingParameterName = false;
747 for (const Variable* param : funcDef.declaration().parameters()) {
748 if (fSymbolTableStack.front()->find(param->name())) {
749 foundShadowingParameterName = true;
750 break;
751 }
752 }
753
754 if (!foundShadowingParameterName) {
755 fEnclosingFunction = &funcDef;
756 this->visitStatement(&funcDef.body());
757 }
758 break;
759 }
760 default:
761 // The inliner can't operate outside of a function's scope.
762 break;
763 }
764 }
765
766 void visitStatement(std::unique_ptr<Statement>* stmt,
767 bool isViableAsEnclosingStatement = true) {
768 if (!*stmt) {
769 return;
770 }
771
772 Analysis::SymbolTableStackBuilder scopedStackBuilder(stmt->get(), &fSymbolTableStack);
773 // If this statement contains symbols that would shadow globally-scoped names, we don't look
774 // for any inline candidates, because it's too late to mangle the names.
775 if (scopedStackBuilder.foundSymbolTable() &&
776 fSymbolTableStack.back()->wouldShadowSymbolsFrom(fSymbolTableStack.front())) {
777 return;
778 }
779
780 size_t oldEnclosingStmtStackSize = fEnclosingStmtStack.size();
781
782 if (isViableAsEnclosingStatement) {
783 fEnclosingStmtStack.push_back(stmt);
784 }
785
786 switch ((*stmt)->kind()) {
787 case Statement::Kind::kBreak:
788 case Statement::Kind::kContinue:
789 case Statement::Kind::kDiscard:
790 case Statement::Kind::kNop:
791 break;
792
793 case Statement::Kind::kBlock: {
794 Block& block = (*stmt)->as<Block>();
795 for (std::unique_ptr<Statement>& blockStmt : block.children()) {
796 this->visitStatement(&blockStmt);
797 }
798 break;
799 }
800 case Statement::Kind::kDo: {
801 DoStatement& doStmt = (*stmt)->as<DoStatement>();
802 // The loop body is a candidate for inlining.
803 this->visitStatement(&doStmt.statement());
804 // The inliner isn't smart enough to inline the test-expression for a do-while
805 // loop at this time. There are two limitations:
806 // - We would need to insert the inlined-body block at the very end of the do-
807 // statement's inner fStatement. We don't support that today, but it's doable.
808 // - We cannot inline the test expression if the loop uses `continue` anywhere; that
809 // would skip over the inlined block that evaluates the test expression. There
810 // isn't a good fix for this--any workaround would be more complex than the cost
811 // of a function call. However, loops that don't use `continue` would still be
812 // viable candidates for inlining.
813 break;
814 }
815 case Statement::Kind::kExpression: {
816 ExpressionStatement& expr = (*stmt)->as<ExpressionStatement>();
817 this->visitExpression(&expr.expression());
818 break;
819 }
820 case Statement::Kind::kFor: {
821 ForStatement& forStmt = (*stmt)->as<ForStatement>();
822 // The initializer and loop body are candidates for inlining.
823 this->visitStatement(&forStmt.initializer(),
824 /*isViableAsEnclosingStatement=*/false);
825 this->visitStatement(&forStmt.statement());
826
827 // The inliner isn't smart enough to inline the test- or increment-expressions
828 // of a for loop loop at this time. There are a handful of limitations:
829 // - We would need to insert the test-expression block at the very beginning of the
830 // for-loop's inner fStatement, and the increment-expression block at the very
831 // end. We don't support that today, but it's doable.
832 // - The for-loop's built-in test-expression would need to be dropped entirely,
833 // and the loop would be halted via a break statement at the end of the inlined
834 // test-expression. This is again something we don't support today, but it could
835 // be implemented.
836 // - We cannot inline the increment-expression if the loop uses `continue` anywhere;
837 // that would skip over the inlined block that evaluates the increment expression.
838 // There isn't a good fix for this--any workaround would be more complex than the
839 // cost of a function call. However, loops that don't use `continue` would still
840 // be viable candidates for increment-expression inlining.
841 break;
842 }
843 case Statement::Kind::kIf: {
844 IfStatement& ifStmt = (*stmt)->as<IfStatement>();
845 this->visitExpression(&ifStmt.test());
846 this->visitStatement(&ifStmt.ifTrue());
847 this->visitStatement(&ifStmt.ifFalse());
848 break;
849 }
850 case Statement::Kind::kReturn: {
851 ReturnStatement& returnStmt = (*stmt)->as<ReturnStatement>();
852 this->visitExpression(&returnStmt.expression());
853 break;
854 }
855 case Statement::Kind::kSwitch: {
856 SwitchStatement& switchStmt = (*stmt)->as<SwitchStatement>();
857 this->visitExpression(&switchStmt.value());
858 for (const std::unique_ptr<Statement>& switchCase : switchStmt.cases()) {
859 // The switch-case's fValue cannot be a FunctionCall; skip it.
860 this->visitStatement(&switchCase->as<SwitchCase>().statement());
861 }
862 break;
863 }
864 case Statement::Kind::kVarDeclaration: {
865 VarDeclaration& varDeclStmt = (*stmt)->as<VarDeclaration>();
866 // Don't need to scan the declaration's sizes; those are always literals.
867 this->visitExpression(&varDeclStmt.value());
868 break;
869 }
870 default:
871 SkUNREACHABLE;
872 }
873
874 // Pop our symbol and enclosing-statement stacks.
875 fEnclosingStmtStack.resize(oldEnclosingStmtStackSize);
876 }
877
878 void visitExpression(std::unique_ptr<Expression>* expr) {
879 if (!*expr) {
880 return;
881 }
882
883 switch ((*expr)->kind()) {
884 case Expression::Kind::kFieldAccess:
885 case Expression::Kind::kFunctionReference:
886 case Expression::Kind::kLiteral:
887 case Expression::Kind::kMethodReference:
888 case Expression::Kind::kSetting:
889 case Expression::Kind::kTypeReference:
890 case Expression::Kind::kVariableReference:
891 // Nothing to scan here.
892 break;
893
894 case Expression::Kind::kBinary: {
895 BinaryExpression& binaryExpr = (*expr)->as<BinaryExpression>();
896 this->visitExpression(&binaryExpr.left());
897
898 // Logical-and and logical-or binary expressions do not inline the right side,
899 // because that would invalidate short-circuiting. That is, when evaluating
900 // expressions like these:
901 // (false && x()) // always false
902 // (true || y()) // always true
903 // It is illegal for side-effects from x() or y() to occur. The simplest way to
904 // enforce that rule is to avoid inlining the right side entirely. However, it is
905 // safe for other types of binary expression to inline both sides.
906 Operator op = binaryExpr.getOperator();
907 bool shortCircuitable = (op.kind() == Operator::Kind::LOGICALAND ||
908 op.kind() == Operator::Kind::LOGICALOR);
909 if (!shortCircuitable) {
910 this->visitExpression(&binaryExpr.right());
911 }
912 break;
913 }
914 case Expression::Kind::kChildCall: {
915 ChildCall& childCallExpr = (*expr)->as<ChildCall>();
916 for (std::unique_ptr<Expression>& arg : childCallExpr.arguments()) {
917 this->visitExpression(&arg);
918 }
919 break;
920 }
921 case Expression::Kind::kConstructorArray:
922 case Expression::Kind::kConstructorArrayCast:
923 case Expression::Kind::kConstructorCompound:
924 case Expression::Kind::kConstructorCompoundCast:
925 case Expression::Kind::kConstructorDiagonalMatrix:
926 case Expression::Kind::kConstructorMatrixResize:
927 case Expression::Kind::kConstructorScalarCast:
928 case Expression::Kind::kConstructorSplat:
929 case Expression::Kind::kConstructorStruct: {
930 AnyConstructor& constructorExpr = (*expr)->asAnyConstructor();
931 for (std::unique_ptr<Expression>& arg : constructorExpr.argumentSpan()) {
932 this->visitExpression(&arg);
933 }
934 break;
935 }
936 case Expression::Kind::kFunctionCall: {
937 FunctionCall& funcCallExpr = (*expr)->as<FunctionCall>();
938 for (std::unique_ptr<Expression>& arg : funcCallExpr.arguments()) {
939 this->visitExpression(&arg);
940 }
941 this->addInlineCandidate(expr);
942 break;
943 }
944 case Expression::Kind::kIndex: {
945 IndexExpression& indexExpr = (*expr)->as<IndexExpression>();
946 this->visitExpression(&indexExpr.base());
947 this->visitExpression(&indexExpr.index());
948 break;
949 }
950 case Expression::Kind::kPostfix: {
951 PostfixExpression& postfixExpr = (*expr)->as<PostfixExpression>();
952 this->visitExpression(&postfixExpr.operand());
953 break;
954 }
955 case Expression::Kind::kPrefix: {
956 PrefixExpression& prefixExpr = (*expr)->as<PrefixExpression>();
957 this->visitExpression(&prefixExpr.operand());
958 break;
959 }
960 case Expression::Kind::kSwizzle: {
961 Swizzle& swizzleExpr = (*expr)->as<Swizzle>();
962 this->visitExpression(&swizzleExpr.base());
963 break;
964 }
965 case Expression::Kind::kTernary: {
966 TernaryExpression& ternaryExpr = (*expr)->as<TernaryExpression>();
967 // The test expression is a candidate for inlining.
968 this->visitExpression(&ternaryExpr.test());
969 // The true- and false-expressions cannot be inlined, because we are only allowed to
970 // evaluate one side.
971 break;
972 }
973 default:
974 SkUNREACHABLE;
975 }
976 }
977
978 void addInlineCandidate(std::unique_ptr<Expression>* candidate) {
979 fCandidateList->fCandidates.push_back(
980 InlineCandidate{fSymbolTableStack.back(),
981 find_parent_statement(fEnclosingStmtStack),
982 fEnclosingStmtStack.back(),
983 candidate,
984 fEnclosingFunction});
985 }
986 };
987
988 static const FunctionDeclaration& candidate_func(const InlineCandidate& candidate) {
989 return (*candidate.fCandidateExpr)->as<FunctionCall>().function();
990 }
991
992 bool Inliner::functionCanBeInlined(const FunctionDeclaration& funcDecl,
993 const ProgramUsage& usage,
994 InlinabilityCache* cache) {
995 if (const bool* cachedInlinability = cache->find(&funcDecl)) {
996 return *cachedInlinability;
997 }
998 bool inlinability = this->isSafeToInline(funcDecl.definition(), usage);
999 cache->set(&funcDecl, inlinability);
1000 return inlinability;
1001 }
1002
1003 bool Inliner::candidateCanBeInlined(const InlineCandidate& candidate,
1004 const ProgramUsage& usage,
1005 InlinabilityCache* cache) {
1006 // Check the cache to see if this function is safe to inline.
1007 const FunctionDeclaration& funcDecl = candidate_func(candidate);
1008 if (!this->functionCanBeInlined(funcDecl, usage, cache)) {
1009 return false;
1010 }
1011
1012 // Even if the function is safe, the arguments we are passing may not be. In particular, we
1013 // can't make copies of opaque values, so we need to reject inline candidates that would need to
1014 // do this. Every call has different arguments, so this part is not cacheable. (skbug.com/40044923)
1015 const FunctionCall& call = candidate.fCandidateExpr->get()->as<FunctionCall>();
1016 const ExpressionArray& arguments = call.arguments();
1017 for (int i = 0; i < arguments.size(); ++i) {
1018 const Expression* arg = arguments[i].get();
1019 if (arg->type().isOpaque()) {
1020 const Variable* param = funcDecl.parameters()[i];
1021 if (argument_needs_scratch_variable(arg, param, usage)) {
1022 return false;
1023 }
1024 }
1025 }
1026
1027 return true;
1028 }
1029
1030 int Inliner::getFunctionSize(const FunctionDeclaration& funcDecl, FunctionSizeCache* cache) {
1031 if (const int* cachedSize = cache->find(&funcDecl)) {
1032 return *cachedSize;
1033 }
1034 int size = Analysis::NodeCountUpToLimit(*funcDecl.definition(),
1035 this->settings().fInlineThreshold);
1036 cache->set(&funcDecl, size);
1037 return size;
1038 }
1039
1040 void Inliner::buildCandidateList(const std::vector<std::unique_ptr<ProgramElement>>& elements,
1041 SymbolTable* symbols,
1042 ProgramUsage* usage,
1043 InlineCandidateList* candidateList) {
1044 // This is structured much like a ProgramVisitor, but does not actually use ProgramVisitor.
1045 // The analyzer needs to keep track of the `unique_ptr<T>*` of statements and expressions so
1046 // that they can later be replaced, and ProgramVisitor does not provide this; it only provides a
1047 // `const T&`.
1048 InlineCandidateAnalyzer analyzer;
1049 analyzer.visit(elements, symbols, candidateList);
1050
1051 // Early out if there are no inlining candidates.
1052 std::vector<InlineCandidate>& candidates = candidateList->fCandidates;
1053 if (candidates.empty()) {
1054 return;
1055 }
1056
1057 // Remove candidates that are not safe to inline.
1058 InlinabilityCache cache;
1059 candidates.erase(std::remove_if(candidates.begin(),
1060 candidates.end(),
1061 [&](const InlineCandidate& candidate) {
1062 return !this->candidateCanBeInlined(
1063 candidate, *usage, &cache);
1064 }),
1065 candidates.end());
1066
1067 // If the inline threshold is unlimited, or if we have no candidates left, our candidate list is
1068 // complete.
1069 if (this->settings().fInlineThreshold == INT_MAX || candidates.empty()) {
1070 return;
1071 }
1072
1073 // Remove candidates on a per-function basis if the effect of inlining would be to make more
1074 // than `inlineThreshold` nodes. (i.e. if Func() would be inlined six times and its size is
1075 // 10 nodes, it should be inlined if the inlineThreshold is 60 or higher.)
1076 FunctionSizeCache functionSizeCache;
1077 FunctionSizeCache candidateTotalCost;
1078 for (InlineCandidate& candidate : candidates) {
1079 const FunctionDeclaration& fnDecl = candidate_func(candidate);
1080 candidateTotalCost[&fnDecl] += this->getFunctionSize(fnDecl, &functionSizeCache);
1081 }
1082
1083 candidates.erase(std::remove_if(candidates.begin(), candidates.end(),
1084 [&](const InlineCandidate& candidate) {
1085 const FunctionDeclaration& fnDecl = candidate_func(candidate);
1086 if (fnDecl.modifierFlags().isInline()) {
1087 // Functions marked `inline` ignore size limitations.
1088 return false;
1089 }
1090 if (usage->get(fnDecl) == 1) {
1091 // If a function is only used once, it's cost-free to inline.
1092 return false;
1093 }
1094 if (candidateTotalCost[&fnDecl] <= this->settings().fInlineThreshold) {
1095 // We won't exceed the inline threshold by inlining this.
1096 return false;
1097 }
1098 // Inlining this function will add too many IRNodes.
1099 return true;
1100 }),
1101 candidates.end());
1102 }
1103
1104 bool Inliner::analyze(const std::vector<std::unique_ptr<ProgramElement>>& elements,
1105 SymbolTable* symbols,
1106 ProgramUsage* usage) {
1107 // A threshold of zero indicates that the inliner is completely disabled, so we can just return.
1108 if (this->settings().fInlineThreshold <= 0) {
1109 return false;
1110 }
1111
1112 // Enforce a limit on inlining to avoid pathological cases. (inliner/ExponentialGrowth.sksl)
1113 if (this->overInlineStatementLimit()) {
1114 return false;
1115 }
1116
1117 InlineCandidateList candidateList;
1118 this->buildCandidateList(elements, symbols, usage, &candidateList);
1119
1120 // Inline the candidates where we've determined that it's safe to do so.
1121 using StatementRemappingTable = THashMap<std::unique_ptr<Statement>*,
1122 std::unique_ptr<Statement>*>;
1123 StatementRemappingTable statementRemappingTable;
1124
1125 bool madeChanges = false;
1126 for (const InlineCandidate& candidate : candidateList.fCandidates) {
1127 const FunctionCall& funcCall = (*candidate.fCandidateExpr)->as<FunctionCall>();
1128
1129 // Convert the function call to its inlined equivalent.
1130 InlinedCall inlinedCall = this->inlineCall(funcCall, candidate.fSymbols, *usage,
1131 &candidate.fEnclosingFunction->declaration());
1132
1133 // Stop if an error was detected during the inlining process.
1134 if (!inlinedCall.fInlinedBody && !inlinedCall.fReplacementExpr) {
1135 break;
1136 }
1137
1138 // Ensure that the inlined body has a scope if it needs one.
1139 this->ensureScopedBlocks(inlinedCall.fInlinedBody.get(), candidate.fParentStmt->get());
1140
1141 // Add references within the inlined body
1142 usage->add(inlinedCall.fInlinedBody.get());
1143
1144 // Look up the enclosing statement; remap it if necessary.
1145 std::unique_ptr<Statement>* enclosingStmt = candidate.fEnclosingStmt;
1146 for (;;) {
1147 std::unique_ptr<Statement>** remappedStmt = statementRemappingTable.find(enclosingStmt);
1148 if (!remappedStmt) {
1149 break;
1150 }
1151 enclosingStmt = *remappedStmt;
1152 }
1153
1154 // Move the enclosing statement to the end of the unscoped Block containing the inlined
1155 // function, then replace the enclosing statement with that Block.
1156 // Before:
1157 // fInlinedBody = Block{ stmt1, stmt2, stmt3 }
1158 // fEnclosingStmt = stmt4
1159 // After:
1160 // fInlinedBody = null
1161 // fEnclosingStmt = Block{ stmt1, stmt2, stmt3, stmt4 }
1162 inlinedCall.fInlinedBody->children().push_back(std::move(*enclosingStmt));
1163 *enclosingStmt = std::move(inlinedCall.fInlinedBody);
1164
1165 // Replace the candidate function call with our replacement expression.
1166 usage->remove(candidate.fCandidateExpr->get());
1167 usage->add(inlinedCall.fReplacementExpr.get());
1168 *candidate.fCandidateExpr = std::move(inlinedCall.fReplacementExpr);
1169 madeChanges = true;
1170
1171 // If anything else pointed at our enclosing statement, it's now pointing at a Block
1172 // containing many other statements as well. Maintain a fix-up table to account for this.
1173 statementRemappingTable.set(enclosingStmt,&(*enclosingStmt)->as<Block>().children().back());
1174
1175 // Stop inlining if we've reached our hard cap on new statements.
1176 if (this->overInlineStatementLimit()) {
1177 break;
1178 }
1179
1180 // Note that nothing was destroyed except for the FunctionCall. All other nodes should
1181 // remain valid.
1182 }
1183
1184 return madeChanges;
1185 }
1186
1187 } // namespace SkSL
1188
1189 #endif // SK_ENABLE_OPTIMIZE_SIZE