blob: a5fe246277c66f806c3e508510ac9fed6b712e37 [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
John Stiles2d7973a2020-10-02 15:01:03 -040010#include <limits.h>
John Stiles44e96be2020-08-31 13:16:04 -040011#include <memory>
12#include <unordered_set>
13
Ethan Nicholasdaed2592021-03-04 14:30:25 -050014#include "include/private/SkSLLayout.h"
John Stiles44e96be2020-08-31 13:16:04 -040015#include "src/sksl/SkSLAnalysis.h"
16#include "src/sksl/ir/SkSLBinaryExpression.h"
17#include "src/sksl/ir/SkSLBoolLiteral.h"
18#include "src/sksl/ir/SkSLBreakStatement.h"
19#include "src/sksl/ir/SkSLConstructor.h"
John Stiles7384b372021-04-01 13:48:15 -040020#include "src/sksl/ir/SkSLConstructorArray.h"
John Stilese3ae9682021-08-05 10:35:01 -040021#include "src/sksl/ir/SkSLConstructorArrayCast.h"
John Stiles8cad6372021-04-07 12:31:13 -040022#include "src/sksl/ir/SkSLConstructorCompound.h"
23#include "src/sksl/ir/SkSLConstructorCompoundCast.h"
John Stilese1182782021-03-30 22:09:37 -040024#include "src/sksl/ir/SkSLConstructorDiagonalMatrix.h"
John Stiles5abb9e12021-04-06 13:47:19 -040025#include "src/sksl/ir/SkSLConstructorMatrixResize.h"
John Stilesfd7252f2021-04-04 22:24:40 -040026#include "src/sksl/ir/SkSLConstructorScalarCast.h"
John Stiles2938eea2021-04-01 18:58:25 -040027#include "src/sksl/ir/SkSLConstructorSplat.h"
John Stilesd47330f2021-04-08 23:25:52 -040028#include "src/sksl/ir/SkSLConstructorStruct.h"
John Stiles44e96be2020-08-31 13:16:04 -040029#include "src/sksl/ir/SkSLContinueStatement.h"
30#include "src/sksl/ir/SkSLDiscardStatement.h"
31#include "src/sksl/ir/SkSLDoStatement.h"
John Stiles44e96be2020-08-31 13:16:04 -040032#include "src/sksl/ir/SkSLExpressionStatement.h"
33#include "src/sksl/ir/SkSLExternalFunctionCall.h"
Brian Osmanbe0b3b72021-01-06 14:27:35 -050034#include "src/sksl/ir/SkSLExternalFunctionReference.h"
John Stiles44e96be2020-08-31 13:16:04 -040035#include "src/sksl/ir/SkSLField.h"
36#include "src/sksl/ir/SkSLFieldAccess.h"
37#include "src/sksl/ir/SkSLFloatLiteral.h"
38#include "src/sksl/ir/SkSLForStatement.h"
39#include "src/sksl/ir/SkSLFunctionCall.h"
40#include "src/sksl/ir/SkSLFunctionDeclaration.h"
41#include "src/sksl/ir/SkSLFunctionDefinition.h"
42#include "src/sksl/ir/SkSLFunctionReference.h"
43#include "src/sksl/ir/SkSLIfStatement.h"
44#include "src/sksl/ir/SkSLIndexExpression.h"
John Stiles98c1f822020-09-09 14:18:53 -040045#include "src/sksl/ir/SkSLInlineMarker.h"
John Stiles44e96be2020-08-31 13:16:04 -040046#include "src/sksl/ir/SkSLIntLiteral.h"
47#include "src/sksl/ir/SkSLInterfaceBlock.h"
John Stiles44e96be2020-08-31 13:16:04 -040048#include "src/sksl/ir/SkSLNop.h"
John Stiles44e96be2020-08-31 13:16:04 -040049#include "src/sksl/ir/SkSLPostfixExpression.h"
50#include "src/sksl/ir/SkSLPrefixExpression.h"
51#include "src/sksl/ir/SkSLReturnStatement.h"
52#include "src/sksl/ir/SkSLSetting.h"
53#include "src/sksl/ir/SkSLSwitchCase.h"
54#include "src/sksl/ir/SkSLSwitchStatement.h"
55#include "src/sksl/ir/SkSLSwizzle.h"
56#include "src/sksl/ir/SkSLTernaryExpression.h"
57#include "src/sksl/ir/SkSLUnresolvedFunction.h"
58#include "src/sksl/ir/SkSLVarDeclarations.h"
John Stiles44e96be2020-08-31 13:16:04 -040059#include "src/sksl/ir/SkSLVariable.h"
60#include "src/sksl/ir/SkSLVariableReference.h"
John Stiles44e96be2020-08-31 13:16:04 -040061
62namespace SkSL {
63namespace {
64
John Stiles031a7672020-11-13 16:13:18 -050065static constexpr int kInlinedStatementLimit = 2500;
66
John Stiles44e96be2020-08-31 13:16:04 -040067static int count_returns_at_end_of_control_flow(const FunctionDefinition& funcDef) {
68 class CountReturnsAtEndOfControlFlow : public ProgramVisitor {
69 public:
70 CountReturnsAtEndOfControlFlow(const FunctionDefinition& funcDef) {
71 this->visitProgramElement(funcDef);
72 }
73
John Stiles5b408a32021-03-17 09:53:32 -040074 bool visitExpression(const Expression& expr) override {
75 // Do not recurse into expressions.
76 return false;
77 }
78
John Stiles44e96be2020-08-31 13:16:04 -040079 bool visitStatement(const Statement& stmt) override {
Ethan Nicholase6592142020-09-08 10:22:09 -040080 switch (stmt.kind()) {
81 case Statement::Kind::kBlock: {
John Stiles44e96be2020-08-31 13:16:04 -040082 // Check only the last statement of a block.
Ethan Nicholas7bd60432020-09-25 14:31:59 -040083 const auto& block = stmt.as<Block>();
84 return block.children().size() &&
85 this->visitStatement(*block.children().back());
John Stiles44e96be2020-08-31 13:16:04 -040086 }
Ethan Nicholase6592142020-09-08 10:22:09 -040087 case Statement::Kind::kSwitch:
Ethan Nicholase6592142020-09-08 10:22:09 -040088 case Statement::Kind::kDo:
89 case Statement::Kind::kFor:
John Stiles44e96be2020-08-31 13:16:04 -040090 // Don't introspect switches or loop structures at all.
91 return false;
92
Ethan Nicholase6592142020-09-08 10:22:09 -040093 case Statement::Kind::kReturn:
John Stiles44e96be2020-08-31 13:16:04 -040094 ++fNumReturns;
95 [[fallthrough]];
96
97 default:
John Stiles93442622020-09-11 12:11:27 -040098 return INHERITED::visitStatement(stmt);
John Stiles44e96be2020-08-31 13:16:04 -040099 }
100 }
101
102 int fNumReturns = 0;
103 using INHERITED = ProgramVisitor;
104 };
105
106 return CountReturnsAtEndOfControlFlow{funcDef}.fNumReturns;
107}
108
John Stiles991b09d2020-09-10 13:33:40 -0400109static bool contains_recursive_call(const FunctionDeclaration& funcDecl) {
110 class ContainsRecursiveCall : public ProgramVisitor {
111 public:
112 bool visit(const FunctionDeclaration& funcDecl) {
113 fFuncDecl = &funcDecl;
Ethan Nicholased84b732020-10-08 11:45:44 -0400114 return funcDecl.definition() ? this->visitProgramElement(*funcDecl.definition())
115 : false;
John Stiles991b09d2020-09-10 13:33:40 -0400116 }
117
118 bool visitExpression(const Expression& expr) override {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400119 if (expr.is<FunctionCall>() && expr.as<FunctionCall>().function().matches(*fFuncDecl)) {
John Stiles991b09d2020-09-10 13:33:40 -0400120 return true;
121 }
122 return INHERITED::visitExpression(expr);
123 }
124
125 bool visitStatement(const Statement& stmt) override {
Ethan Nicholasceb62142020-10-09 16:51:18 -0400126 if (stmt.is<InlineMarker>() &&
127 stmt.as<InlineMarker>().function().matches(*fFuncDecl)) {
John Stiles991b09d2020-09-10 13:33:40 -0400128 return true;
129 }
130 return INHERITED::visitStatement(stmt);
131 }
132
133 const FunctionDeclaration* fFuncDecl;
134 using INHERITED = ProgramVisitor;
135 };
136
137 return ContainsRecursiveCall{}.visit(funcDecl);
138}
139
John Stiles6d696082020-10-01 10:18:54 -0400140static std::unique_ptr<Statement>* find_parent_statement(
141 const std::vector<std::unique_ptr<Statement>*>& stmtStack) {
John Stiles915a38c2020-09-14 09:38:13 -0400142 SkASSERT(!stmtStack.empty());
143
144 // Walk the statement stack from back to front, ignoring the last element (which is the
145 // enclosing statement).
146 auto iter = stmtStack.rbegin();
147 ++iter;
148
149 // Anything counts as a parent statement other than a scopeless Block.
150 for (; iter != stmtStack.rend(); ++iter) {
John Stiles6d696082020-10-01 10:18:54 -0400151 std::unique_ptr<Statement>* stmt = *iter;
152 if (!(*stmt)->is<Block>() || (*stmt)->as<Block>().isScope()) {
John Stiles915a38c2020-09-14 09:38:13 -0400153 return stmt;
154 }
155 }
156
157 // There wasn't any parent statement to be found.
158 return nullptr;
159}
160
John Stilese41b4ee2020-09-28 12:28:16 -0400161std::unique_ptr<Expression> clone_with_ref_kind(const Expression& expr,
162 VariableReference::RefKind refKind) {
163 std::unique_ptr<Expression> clone = expr.clone();
John Stiles47c0a742021-02-09 09:30:35 -0500164 Analysis::UpdateRefKind(clone.get(), refKind);
John Stilese41b4ee2020-09-28 12:28:16 -0400165 return clone;
166}
167
John Stiles77702f12020-12-17 14:38:56 -0500168class CountReturnsWithLimit : public ProgramVisitor {
169public:
170 CountReturnsWithLimit(const FunctionDefinition& funcDef, int limit) : fLimit(limit) {
171 this->visitProgramElement(funcDef);
172 }
173
John Stiles5b408a32021-03-17 09:53:32 -0400174 bool visitExpression(const Expression& expr) override {
175 // Do not recurse into expressions.
176 return false;
177 }
178
John Stiles77702f12020-12-17 14:38:56 -0500179 bool visitStatement(const Statement& stmt) override {
180 switch (stmt.kind()) {
181 case Statement::Kind::kReturn: {
182 ++fNumReturns;
183 fDeepestReturn = std::max(fDeepestReturn, fScopedBlockDepth);
184 return (fNumReturns >= fLimit) || INHERITED::visitStatement(stmt);
185 }
John Stilesc5ff4862020-12-22 13:47:05 -0500186 case Statement::Kind::kVarDeclaration: {
187 if (fScopedBlockDepth > 1) {
188 fVariablesInBlocks = true;
189 }
190 return INHERITED::visitStatement(stmt);
191 }
John Stiles77702f12020-12-17 14:38:56 -0500192 case Statement::Kind::kBlock: {
193 int depthIncrement = stmt.as<Block>().isScope() ? 1 : 0;
194 fScopedBlockDepth += depthIncrement;
195 bool result = INHERITED::visitStatement(stmt);
196 fScopedBlockDepth -= depthIncrement;
John Stilesc5ff4862020-12-22 13:47:05 -0500197 if (fNumReturns == 0 && fScopedBlockDepth <= 1) {
198 // If closing this block puts us back at the top level, and we haven't
199 // encountered any return statements yet, any vardecls we may have encountered
200 // up until this point can be ignored. They are out of scope now, and they were
201 // never used in a return statement.
202 fVariablesInBlocks = false;
203 }
John Stiles77702f12020-12-17 14:38:56 -0500204 return result;
205 }
206 default:
207 return INHERITED::visitStatement(stmt);
208 }
209 }
210
211 int fNumReturns = 0;
212 int fDeepestReturn = 0;
213 int fLimit = 0;
214 int fScopedBlockDepth = 0;
John Stilesc5ff4862020-12-22 13:47:05 -0500215 bool fVariablesInBlocks = false;
John Stiles77702f12020-12-17 14:38:56 -0500216 using INHERITED = ProgramVisitor;
217};
218
John Stiles44e96be2020-08-31 13:16:04 -0400219} // namespace
220
John Stiles77702f12020-12-17 14:38:56 -0500221Inliner::ReturnComplexity Inliner::GetReturnComplexity(const FunctionDefinition& funcDef) {
222 int returnsAtEndOfControlFlow = count_returns_at_end_of_control_flow(funcDef);
223 CountReturnsWithLimit counter{funcDef, returnsAtEndOfControlFlow + 1};
John Stiles77702f12020-12-17 14:38:56 -0500224 if (counter.fNumReturns > returnsAtEndOfControlFlow) {
225 return ReturnComplexity::kEarlyReturns;
226 }
John Stilesc5ff4862020-12-22 13:47:05 -0500227 if (counter.fNumReturns > 1) {
John Stiles77702f12020-12-17 14:38:56 -0500228 return ReturnComplexity::kScopedReturns;
229 }
John Stilesc5ff4862020-12-22 13:47:05 -0500230 if (counter.fVariablesInBlocks && counter.fDeepestReturn > 1) {
231 return ReturnComplexity::kScopedReturns;
232 }
John Stiles8937cd42021-03-17 19:32:59 +0000233 return ReturnComplexity::kSingleSafeReturn;
John Stiles77702f12020-12-17 14:38:56 -0500234}
235
John Stilesb61ee902020-09-21 12:26:59 -0400236void Inliner::ensureScopedBlocks(Statement* inlinedBody, Statement* parentStmt) {
237 // No changes necessary if this statement isn't actually a block.
238 if (!inlinedBody || !inlinedBody->is<Block>()) {
239 return;
240 }
241
242 // No changes necessary if the parent statement doesn't require a scope.
243 if (!parentStmt || !(parentStmt->is<IfStatement>() || parentStmt->is<ForStatement>() ||
Brian Osmand6f23382020-12-15 17:08:59 -0500244 parentStmt->is<DoStatement>())) {
John Stilesb61ee902020-09-21 12:26:59 -0400245 return;
246 }
247
248 Block& block = inlinedBody->as<Block>();
249
250 // The inliner will create inlined function bodies as a Block containing multiple statements,
251 // but no scope. Normally, this is fine, but if this block is used as the statement for a
252 // do/for/if/while, this isn't actually possible to represent textually; a scope must be added
253 // for the generated code to match the intent. In the case of Blocks nested inside other Blocks,
254 // we add the scope to the outermost block if needed. Zero-statement blocks have similar
255 // issues--if we don't represent the Block textually somehow, we run the risk of accidentally
256 // absorbing the following statement into our loop--so we also add a scope to these.
257 for (Block* nestedBlock = &block;; ) {
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400258 if (nestedBlock->isScope()) {
John Stilesb61ee902020-09-21 12:26:59 -0400259 // We found an explicit scope; all is well.
260 return;
261 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400262 if (nestedBlock->children().size() != 1) {
John Stilesb61ee902020-09-21 12:26:59 -0400263 // We found a block with multiple (or zero) statements, but no scope? Let's add a scope
264 // to the outermost block.
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400265 block.setIsScope(true);
John Stilesb61ee902020-09-21 12:26:59 -0400266 return;
267 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400268 if (!nestedBlock->children()[0]->is<Block>()) {
John Stilesb61ee902020-09-21 12:26:59 -0400269 // This block has exactly one thing inside, and it's not another block. No need to scope
270 // it.
271 return;
272 }
273 // We have to go deeper.
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400274 nestedBlock = &nestedBlock->children()[0]->as<Block>();
John Stilesb61ee902020-09-21 12:26:59 -0400275 }
276}
277
John Stiles10d39d92021-05-04 16:13:14 -0400278void Inliner::reset() {
Ethan Nicholas6f4eee22021-01-11 12:37:42 -0500279 fMangler.reset();
John Stiles031a7672020-11-13 16:13:18 -0500280 fInlinedStatementCounter = 0;
John Stiles44e96be2020-08-31 13:16:04 -0400281}
282
283std::unique_ptr<Expression> Inliner::inlineExpression(int offset,
284 VariableRewriteMap* varMap,
John Stilesd7cc0932020-11-30 12:24:27 -0500285 SymbolTable* symbolTableForExpression,
John Stiles44e96be2020-08-31 13:16:04 -0400286 const Expression& expression) {
287 auto expr = [&](const std::unique_ptr<Expression>& e) -> std::unique_ptr<Expression> {
288 if (e) {
John Stilesd7cc0932020-11-30 12:24:27 -0500289 return this->inlineExpression(offset, varMap, symbolTableForExpression, *e);
John Stiles44e96be2020-08-31 13:16:04 -0400290 }
291 return nullptr;
292 };
John Stiles8e3b6be2020-10-13 11:14:08 -0400293 auto argList = [&](const ExpressionArray& originalArgs) -> ExpressionArray {
294 ExpressionArray args;
John Stilesf4bda742020-10-14 16:57:41 -0400295 args.reserve_back(originalArgs.size());
John Stiles44e96be2020-08-31 13:16:04 -0400296 for (const std::unique_ptr<Expression>& arg : originalArgs) {
297 args.push_back(expr(arg));
298 }
299 return args;
300 };
301
Ethan Nicholase6592142020-09-08 10:22:09 -0400302 switch (expression.kind()) {
303 case Expression::Kind::kBinary: {
John Stiles6a1a98c2021-01-14 18:35:34 -0500304 const BinaryExpression& binaryExpr = expression.as<BinaryExpression>();
John Stilese2aec432021-03-01 09:27:48 -0500305 return BinaryExpression::Make(*fContext,
306 expr(binaryExpr.left()),
307 binaryExpr.getOperator(),
308 expr(binaryExpr.right()));
John Stiles44e96be2020-08-31 13:16:04 -0400309 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400310 case Expression::Kind::kBoolLiteral:
311 case Expression::Kind::kIntLiteral:
312 case Expression::Kind::kFloatLiteral:
John Stiles44e96be2020-08-31 13:16:04 -0400313 return expression.clone();
John Stiles7384b372021-04-01 13:48:15 -0400314 case Expression::Kind::kConstructorArray: {
315 const ConstructorArray& ctor = expression.as<ConstructorArray>();
316 return ConstructorArray::Make(*fContext, offset,
317 *ctor.type().clone(symbolTableForExpression),
318 argList(ctor.arguments()));
319 }
John Stilese3ae9682021-08-05 10:35:01 -0400320 case Expression::Kind::kConstructorArrayCast: {
321 const ConstructorArrayCast& ctor = expression.as<ConstructorArrayCast>();
322 return ConstructorArrayCast::Make(*fContext, offset,
323 *ctor.type().clone(symbolTableForExpression),
324 expr(ctor.argument()));
325 }
John Stiles8cad6372021-04-07 12:31:13 -0400326 case Expression::Kind::kConstructorCompound: {
327 const ConstructorCompound& ctor = expression.as<ConstructorCompound>();
328 return ConstructorCompound::Make(*fContext, offset,
John Stiles2bec8ab2021-04-06 18:40:04 -0400329 *ctor.type().clone(symbolTableForExpression),
330 argList(ctor.arguments()));
331 }
John Stiles8cad6372021-04-07 12:31:13 -0400332 case Expression::Kind::kConstructorCompoundCast: {
333 const ConstructorCompoundCast& ctor = expression.as<ConstructorCompoundCast>();
334 return ConstructorCompoundCast::Make(*fContext, offset,
John Stiles268a73f2021-04-07 12:30:22 -0400335 *ctor.type().clone(symbolTableForExpression),
336 expr(ctor.argument()));
337 }
John Stilese1182782021-03-30 22:09:37 -0400338 case Expression::Kind::kConstructorDiagonalMatrix: {
339 const ConstructorDiagonalMatrix& ctor = expression.as<ConstructorDiagonalMatrix>();
340 return ConstructorDiagonalMatrix::Make(*fContext, offset,
341 *ctor.type().clone(symbolTableForExpression),
342 expr(ctor.argument()));
343 }
John Stiles5abb9e12021-04-06 13:47:19 -0400344 case Expression::Kind::kConstructorMatrixResize: {
345 const ConstructorMatrixResize& ctor = expression.as<ConstructorMatrixResize>();
346 return ConstructorMatrixResize::Make(*fContext, offset,
347 *ctor.type().clone(symbolTableForExpression),
348 expr(ctor.argument()));
349 }
John Stilesfd7252f2021-04-04 22:24:40 -0400350 case Expression::Kind::kConstructorScalarCast: {
351 const ConstructorScalarCast& ctor = expression.as<ConstructorScalarCast>();
352 return ConstructorScalarCast::Make(*fContext, offset,
353 *ctor.type().clone(symbolTableForExpression),
354 expr(ctor.argument()));
355 }
John Stiles2938eea2021-04-01 18:58:25 -0400356 case Expression::Kind::kConstructorSplat: {
357 const ConstructorSplat& ctor = expression.as<ConstructorSplat>();
358 return ConstructorSplat::Make(*fContext, offset,
359 *ctor.type().clone(symbolTableForExpression),
360 expr(ctor.argument()));
361 }
John Stilesd47330f2021-04-08 23:25:52 -0400362 case Expression::Kind::kConstructorStruct: {
363 const ConstructorStruct& ctor = expression.as<ConstructorStruct>();
364 return ConstructorStruct::Make(*fContext, offset,
365 *ctor.type().clone(symbolTableForExpression),
366 argList(ctor.arguments()));
367 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400368 case Expression::Kind::kExternalFunctionCall: {
John Stiles44e96be2020-08-31 13:16:04 -0400369 const ExternalFunctionCall& externalCall = expression.as<ExternalFunctionCall>();
Ethan Nicholas444ccc62020-10-09 10:16:22 -0400370 return std::make_unique<ExternalFunctionCall>(offset, &externalCall.function(),
Ethan Nicholas6e86ec92020-09-30 14:29:56 -0400371 argList(externalCall.arguments()));
John Stiles44e96be2020-08-31 13:16:04 -0400372 }
Brian Osmanbe0b3b72021-01-06 14:27:35 -0500373 case Expression::Kind::kExternalFunctionReference:
John Stiles44e96be2020-08-31 13:16:04 -0400374 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400375 case Expression::Kind::kFieldAccess: {
John Stiles44e96be2020-08-31 13:16:04 -0400376 const FieldAccess& f = expression.as<FieldAccess>();
John Stiles06d600f2021-03-08 09:18:21 -0500377 return FieldAccess::Make(*fContext, expr(f.base()), f.fieldIndex(), f.ownerKind());
John Stiles44e96be2020-08-31 13:16:04 -0400378 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400379 case Expression::Kind::kFunctionCall: {
John Stiles44e96be2020-08-31 13:16:04 -0400380 const FunctionCall& funcCall = expression.as<FunctionCall>();
John Stilescd7ba502021-03-19 10:54:59 -0400381 return FunctionCall::Make(*fContext,
382 offset,
383 funcCall.type().clone(symbolTableForExpression),
384 funcCall.function(),
385 argList(funcCall.arguments()));
John Stiles44e96be2020-08-31 13:16:04 -0400386 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400387 case Expression::Kind::kFunctionReference:
Brian Osman2b3b35f2020-09-08 09:17:36 -0400388 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400389 case Expression::Kind::kIndex: {
John Stiles44e96be2020-08-31 13:16:04 -0400390 const IndexExpression& idx = expression.as<IndexExpression>();
John Stiles51d33982021-03-08 09:18:07 -0500391 return IndexExpression::Make(*fContext, expr(idx.base()), expr(idx.index()));
John Stiles44e96be2020-08-31 13:16:04 -0400392 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400393 case Expression::Kind::kPrefix: {
John Stiles44e96be2020-08-31 13:16:04 -0400394 const PrefixExpression& p = expression.as<PrefixExpression>();
John Stilesb0eb20f2021-02-26 15:29:33 -0500395 return PrefixExpression::Make(*fContext, p.getOperator(), expr(p.operand()));
John Stiles44e96be2020-08-31 13:16:04 -0400396 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400397 case Expression::Kind::kPostfix: {
John Stiles44e96be2020-08-31 13:16:04 -0400398 const PostfixExpression& p = expression.as<PostfixExpression>();
John Stiles52d3b012021-02-26 15:56:48 -0500399 return PostfixExpression::Make(*fContext, expr(p.operand()), p.getOperator());
John Stiles44e96be2020-08-31 13:16:04 -0400400 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400401 case Expression::Kind::kSetting:
John Stiles44e96be2020-08-31 13:16:04 -0400402 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400403 case Expression::Kind::kSwizzle: {
John Stiles44e96be2020-08-31 13:16:04 -0400404 const Swizzle& s = expression.as<Swizzle>();
John Stiles6e88e042021-02-19 14:09:38 -0500405 return Swizzle::Make(*fContext, expr(s.base()), s.components());
John Stiles44e96be2020-08-31 13:16:04 -0400406 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400407 case Expression::Kind::kTernary: {
John Stiles44e96be2020-08-31 13:16:04 -0400408 const TernaryExpression& t = expression.as<TernaryExpression>();
John Stiles90518f72021-02-26 20:44:54 -0500409 return TernaryExpression::Make(*fContext, expr(t.test()),
410 expr(t.ifTrue()), expr(t.ifFalse()));
John Stiles44e96be2020-08-31 13:16:04 -0400411 }
Brian Osman83ba9302020-09-11 13:33:46 -0400412 case Expression::Kind::kTypeReference:
413 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400414 case Expression::Kind::kVariableReference: {
John Stiles44e96be2020-08-31 13:16:04 -0400415 const VariableReference& v = expression.as<VariableReference>();
Ethan Nicholas78686922020-10-08 06:46:27 -0400416 auto varMapIter = varMap->find(v.variable());
John Stilese41b4ee2020-09-28 12:28:16 -0400417 if (varMapIter != varMap->end()) {
Ethan Nicholas78686922020-10-08 06:46:27 -0400418 return clone_with_ref_kind(*varMapIter->second, v.refKind());
John Stiles44e96be2020-08-31 13:16:04 -0400419 }
420 return v.clone();
421 }
422 default:
423 SkASSERT(false);
424 return nullptr;
425 }
426}
427
428std::unique_ptr<Statement> Inliner::inlineStatement(int offset,
429 VariableRewriteMap* varMap,
430 SymbolTable* symbolTableForStatement,
John Stiles77702f12020-12-17 14:38:56 -0500431 std::unique_ptr<Expression>* resultExpr,
432 ReturnComplexity returnComplexity,
Brian Osman3887a012020-09-30 13:22:27 -0400433 const Statement& statement,
434 bool isBuiltinCode) {
John Stiles44e96be2020-08-31 13:16:04 -0400435 auto stmt = [&](const std::unique_ptr<Statement>& s) -> std::unique_ptr<Statement> {
436 if (s) {
John Stilesa5f3c312020-09-22 12:05:16 -0400437 return this->inlineStatement(offset, varMap, symbolTableForStatement, resultExpr,
John Stiles77702f12020-12-17 14:38:56 -0500438 returnComplexity, *s, isBuiltinCode);
John Stiles44e96be2020-08-31 13:16:04 -0400439 }
440 return nullptr;
441 };
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400442 auto blockStmts = [&](const Block& block) {
John Stiles8f2a0cf2020-10-13 12:48:21 -0400443 StatementArray result;
John Stilesf4bda742020-10-14 16:57:41 -0400444 result.reserve_back(block.children().size());
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400445 for (const std::unique_ptr<Statement>& child : block.children()) {
446 result.push_back(stmt(child));
447 }
448 return result;
449 };
John Stiles44e96be2020-08-31 13:16:04 -0400450 auto expr = [&](const std::unique_ptr<Expression>& e) -> std::unique_ptr<Expression> {
451 if (e) {
John Stilesd7cc0932020-11-30 12:24:27 -0500452 return this->inlineExpression(offset, varMap, symbolTableForStatement, *e);
John Stiles44e96be2020-08-31 13:16:04 -0400453 }
454 return nullptr;
455 };
John Stiles031a7672020-11-13 16:13:18 -0500456
457 ++fInlinedStatementCounter;
458
Ethan Nicholase6592142020-09-08 10:22:09 -0400459 switch (statement.kind()) {
460 case Statement::Kind::kBlock: {
John Stiles44e96be2020-08-31 13:16:04 -0400461 const Block& b = statement.as<Block>();
John Stilesbf16b6c2021-03-12 19:24:31 -0500462 return Block::Make(offset, blockStmts(b),
463 SymbolTable::WrapIfBuiltin(b.symbolTable()),
464 b.isScope());
John Stiles44e96be2020-08-31 13:16:04 -0400465 }
466
Ethan Nicholase6592142020-09-08 10:22:09 -0400467 case Statement::Kind::kBreak:
468 case Statement::Kind::kContinue:
469 case Statement::Kind::kDiscard:
John Stiles44e96be2020-08-31 13:16:04 -0400470 return statement.clone();
471
Ethan Nicholase6592142020-09-08 10:22:09 -0400472 case Statement::Kind::kDo: {
John Stiles44e96be2020-08-31 13:16:04 -0400473 const DoStatement& d = statement.as<DoStatement>();
John Stilesea5822e2021-02-26 11:18:20 -0500474 return DoStatement::Make(*fContext, stmt(d.statement()), expr(d.test()));
John Stiles44e96be2020-08-31 13:16:04 -0400475 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400476 case Statement::Kind::kExpression: {
John Stiles44e96be2020-08-31 13:16:04 -0400477 const ExpressionStatement& e = statement.as<ExpressionStatement>();
John Stiles3e5871c2021-02-25 20:52:03 -0500478 return ExpressionStatement::Make(*fContext, expr(e.expression()));
John Stiles44e96be2020-08-31 13:16:04 -0400479 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400480 case Statement::Kind::kFor: {
John Stiles44e96be2020-08-31 13:16:04 -0400481 const ForStatement& f = statement.as<ForStatement>();
482 // need to ensure initializer is evaluated first so that we've already remapped its
483 // declarations by the time we evaluate test & next
Ethan Nicholas0d31ed52020-10-05 14:47:09 -0400484 std::unique_ptr<Statement> initializer = stmt(f.initializer());
John Stilesb321a072021-02-25 16:24:19 -0500485 return ForStatement::Make(*fContext, offset, std::move(initializer), expr(f.test()),
486 expr(f.next()), stmt(f.statement()),
487 SymbolTable::WrapIfBuiltin(f.symbols()));
John Stiles44e96be2020-08-31 13:16:04 -0400488 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400489 case Statement::Kind::kIf: {
John Stiles44e96be2020-08-31 13:16:04 -0400490 const IfStatement& i = statement.as<IfStatement>();
John Stilescf3059e2021-02-25 14:27:02 -0500491 return IfStatement::Make(*fContext, offset, i.isStatic(), expr(i.test()),
492 stmt(i.ifTrue()), stmt(i.ifFalse()));
John Stiles44e96be2020-08-31 13:16:04 -0400493 }
John Stiles98c1f822020-09-09 14:18:53 -0400494 case Statement::Kind::kInlineMarker:
Ethan Nicholase6592142020-09-08 10:22:09 -0400495 case Statement::Kind::kNop:
John Stiles44e96be2020-08-31 13:16:04 -0400496 return statement.clone();
John Stilesea5822e2021-02-26 11:18:20 -0500497
Ethan Nicholase6592142020-09-08 10:22:09 -0400498 case Statement::Kind::kReturn: {
John Stiles44e96be2020-08-31 13:16:04 -0400499 const ReturnStatement& r = statement.as<ReturnStatement>();
John Stiles77702f12020-12-17 14:38:56 -0500500 if (!r.expression()) {
John Stilesdc208472021-03-17 10:58:16 -0400501 // This function doesn't return a value. We won't inline functions with early
502 // returns, so a return statement is a no-op and can be treated as such.
503 return Nop::Make();
John Stiles44e96be2020-08-31 13:16:04 -0400504 }
John Stiles77702f12020-12-17 14:38:56 -0500505
John Stilesc5ff4862020-12-22 13:47:05 -0500506 // If a function only contains a single return, and it doesn't reference variables from
507 // inside an Block's scope, we don't need to store the result in a variable at all. Just
508 // replace the function-call expression with the function's return expression.
John Stiles77702f12020-12-17 14:38:56 -0500509 SkASSERT(resultExpr);
John Stilesc5ff4862020-12-22 13:47:05 -0500510 if (returnComplexity <= ReturnComplexity::kSingleSafeReturn) {
John Stiles77702f12020-12-17 14:38:56 -0500511 *resultExpr = expr(r.expression());
John Stilesa0c04d62021-03-11 23:07:24 -0500512 return Nop::Make();
John Stiles77702f12020-12-17 14:38:56 -0500513 }
514
515 // For more complex functions, assign their result into a variable.
John Stiles511c5002021-02-25 11:17:02 -0500516 SkASSERT(*resultExpr);
John Stiles3e5871c2021-02-25 20:52:03 -0500517 auto assignment = ExpressionStatement::Make(
518 *fContext,
John Stilese2aec432021-03-01 09:27:48 -0500519 BinaryExpression::Make(
520 *fContext,
521 clone_with_ref_kind(**resultExpr, VariableRefKind::kWrite),
John Stiles77702f12020-12-17 14:38:56 -0500522 Token::Kind::TK_EQ,
John Stilese2aec432021-03-01 09:27:48 -0500523 expr(r.expression())));
John Stiles77702f12020-12-17 14:38:56 -0500524
John Stiles77702f12020-12-17 14:38:56 -0500525 // Functions without early returns aren't wrapped in a for loop and don't need to worry
526 // about breaking out of the control flow.
John Stiles3e5871c2021-02-25 20:52:03 -0500527 return assignment;
John Stiles44e96be2020-08-31 13:16:04 -0400528 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400529 case Statement::Kind::kSwitch: {
John Stiles44e96be2020-08-31 13:16:04 -0400530 const SwitchStatement& ss = statement.as<SwitchStatement>();
John Stilesb23a64b2021-03-11 08:27:59 -0500531 StatementArray cases;
532 cases.reserve_back(ss.cases().size());
John Stiles628777c2021-08-04 22:07:41 -0400533 for (const std::unique_ptr<Statement>& switchCaseStmt : ss.cases()) {
534 const SwitchCase& sc = switchCaseStmt->as<SwitchCase>();
John Stilesb23a64b2021-03-11 08:27:59 -0500535 cases.push_back(std::make_unique<SwitchCase>(offset, expr(sc.value()),
536 stmt(sc.statement())));
John Stiles44e96be2020-08-31 13:16:04 -0400537 }
John Stilese1d1b082021-02-23 13:44:36 -0500538 return SwitchStatement::Make(*fContext, offset, ss.isStatic(), expr(ss.value()),
539 std::move(cases), SymbolTable::WrapIfBuiltin(ss.symbols()));
John Stiles44e96be2020-08-31 13:16:04 -0400540 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400541 case Statement::Kind::kVarDeclaration: {
John Stiles44e96be2020-08-31 13:16:04 -0400542 const VarDeclaration& decl = statement.as<VarDeclaration>();
John Stiles35fee4c2020-12-16 18:25:14 +0000543 std::unique_ptr<Expression> initialValue = expr(decl.value());
John Stilesddcc8432021-01-15 15:32:32 -0500544 const Variable& variable = decl.var();
545
John Stiles35fee4c2020-12-16 18:25:14 +0000546 // We assign unique names to inlined variables--scopes hide most of the problems in this
547 // regard, but see `InlinerAvoidsVariableNameOverlap` for a counterexample where unique
548 // names are important.
John Stilesd51c9792021-03-18 11:40:14 -0400549 const String* name = symbolTableForStatement->takeOwnershipOfString(
Ethan Nicholasd2e09602021-06-10 11:21:59 -0400550 fMangler.uniqueName(String(variable.name()), symbolTableForStatement));
Ethan Nicholas5b9b0db2021-01-21 13:12:01 -0500551 auto clonedVar = std::make_unique<Variable>(
552 offset,
553 &variable.modifiers(),
John Stilesd51c9792021-03-18 11:40:14 -0400554 name->c_str(),
Ethan Nicholas5b9b0db2021-01-21 13:12:01 -0500555 variable.type().clone(symbolTableForStatement),
556 isBuiltinCode,
557 variable.storage());
John Stilesa94e0262021-04-27 17:29:59 -0400558 (*varMap)[&variable] = VariableReference::Make(offset, clonedVar.get());
John Stilese67bd132021-03-19 18:39:25 -0400559 auto result = VarDeclaration::Make(*fContext,
560 clonedVar.get(),
561 decl.baseType().clone(symbolTableForStatement),
562 decl.arraySize(),
563 std::move(initialValue));
Ethan Nicholas5b9b0db2021-01-21 13:12:01 -0500564 symbolTableForStatement->takeOwnershipOfSymbol(std::move(clonedVar));
John Stilese67bd132021-03-19 18:39:25 -0400565 return result;
John Stiles44e96be2020-08-31 13:16:04 -0400566 }
John Stiles44e96be2020-08-31 13:16:04 -0400567 default:
568 SkASSERT(false);
569 return nullptr;
570 }
571}
572
John Stiles7b920442020-12-17 10:43:41 -0500573Inliner::InlineVariable Inliner::makeInlineVariable(const String& baseName,
574 const Type* type,
575 SymbolTable* symbolTable,
576 Modifiers modifiers,
577 bool isBuiltinCode,
578 std::unique_ptr<Expression>* initialValue) {
579 // $floatLiteral or $intLiteral aren't real types that we can use for scratch variables, so
580 // replace them if they ever appear here. If this happens, we likely forgot to coerce a type
581 // somewhere during compilation.
John Stiles14975272021-01-12 11:41:14 -0500582 if (type->isLiteral()) {
583 SkDEBUGFAIL("found a $literal type while inlining");
584 type = &type->scalarTypeForLiteral();
John Stiles7b920442020-12-17 10:43:41 -0500585 }
586
John Stilesbff24ab2021-03-17 13:20:10 -0400587 // Out parameters aren't supported.
588 SkASSERT(!(modifiers.fFlags & Modifiers::kOut_Flag));
589
John Stiles7b920442020-12-17 10:43:41 -0500590 // Provide our new variable with a unique name, and add it to our symbol table.
John Stilesd51c9792021-03-18 11:40:14 -0400591 const String* name =
592 symbolTable->takeOwnershipOfString(fMangler.uniqueName(baseName, symbolTable));
John Stiles7b920442020-12-17 10:43:41 -0500593
594 // Create our new variable and add it to the symbol table.
595 InlineVariable result;
Ethan Nicholas5b9b0db2021-01-21 13:12:01 -0500596 auto var = std::make_unique<Variable>(/*offset=*/-1,
John Stilesf2872e62021-05-04 11:38:43 -0400597 this->modifiersPool().add(Modifiers{}),
John Stilesd51c9792021-03-18 11:40:14 -0400598 name->c_str(),
Ethan Nicholas5b9b0db2021-01-21 13:12:01 -0500599 type,
600 isBuiltinCode,
601 Variable::Storage::kLocal);
John Stiles7b920442020-12-17 10:43:41 -0500602
John Stilesbff24ab2021-03-17 13:20:10 -0400603 // Create our variable declaration.
John Stilese67bd132021-03-19 18:39:25 -0400604 result.fVarDecl = VarDeclaration::Make(*fContext, var.get(), type, /*arraySize=*/0,
605 std::move(*initialValue));
Ethan Nicholas5b9b0db2021-01-21 13:12:01 -0500606 result.fVarSymbol = symbolTable->add(std::move(var));
John Stiles7b920442020-12-17 10:43:41 -0500607 return result;
608}
609
John Stiles6eadf132020-09-08 10:16:10 -0400610Inliner::InlinedCall Inliner::inlineCall(FunctionCall* call,
John Stiles78047582020-12-16 16:17:41 -0500611 std::shared_ptr<SymbolTable> symbolTable,
John Stiles30fce9c2021-03-18 09:24:06 -0400612 const ProgramUsage& usage,
Brian Osman3887a012020-09-30 13:22:27 -0400613 const FunctionDeclaration* caller) {
John Stiles44e96be2020-08-31 13:16:04 -0400614 // Inlining is more complicated here than in a typical compiler, because we have to have a
615 // high-level IR and can't just drop statements into the middle of an expression or even use
616 // gotos.
617 //
618 // Since we can't insert statements into an expression, we run the inline function as extra
619 // statements before the statement we're currently processing, relying on a lack of execution
620 // order guarantees. Since we can't use gotos (which are normally used to replace return
621 // statements), we wrap the whole function in a loop and use break statements to jump to the
622 // end.
John Stiles44e96be2020-08-31 13:16:04 -0400623 SkASSERT(fContext);
624 SkASSERT(call);
Ethan Nicholased84b732020-10-08 11:45:44 -0400625 SkASSERT(this->isSafeToInline(call->function().definition()));
John Stiles44e96be2020-08-31 13:16:04 -0400626
John Stiles8e3b6be2020-10-13 11:14:08 -0400627 ExpressionArray& arguments = call->arguments();
John Stiles6eadf132020-09-08 10:16:10 -0400628 const int offset = call->fOffset;
Ethan Nicholased84b732020-10-08 11:45:44 -0400629 const FunctionDefinition& function = *call->function().definition();
John Stiles28257db2021-03-17 15:18:09 -0400630 const Block& body = function.body()->as<Block>();
John Stiles77702f12020-12-17 14:38:56 -0500631 const ReturnComplexity returnComplexity = GetReturnComplexity(function);
John Stiles6eadf132020-09-08 10:16:10 -0400632
John Stiles28257db2021-03-17 15:18:09 -0400633 StatementArray inlineStatements;
634 int expectedStmtCount = 1 + // Inline marker
635 1 + // Result variable
636 arguments.size() + // Function argument temp-vars
637 body.children().size(); // Inlined code
John Stiles98c1f822020-09-09 14:18:53 -0400638
John Stiles28257db2021-03-17 15:18:09 -0400639 inlineStatements.reserve_back(expectedStmtCount);
640 inlineStatements.push_back(InlineMarker::Make(&call->function()));
John Stiles44e96be2020-08-31 13:16:04 -0400641
John Stilese41b4ee2020-09-28 12:28:16 -0400642 std::unique_ptr<Expression> resultExpr;
John Stiles511c5002021-02-25 11:17:02 -0500643 if (returnComplexity > ReturnComplexity::kSingleSafeReturn &&
John Stiles2558c462021-03-16 17:49:20 -0400644 !function.declaration().returnType().isVoid()) {
John Stiles511c5002021-02-25 11:17:02 -0500645 // Create a variable to hold the result in the extra statements. We don't need to do this
646 // for void-return functions, or in cases that are simple enough that we can just replace
647 // the function-call node with the result expression.
John Stiles44e96be2020-08-31 13:16:04 -0400648 std::unique_ptr<Expression> noInitialValue;
Ethan Nicholasd2e09602021-06-10 11:21:59 -0400649 InlineVariable var = this->makeInlineVariable(String(function.declaration().name()),
John Stiles7b920442020-12-17 10:43:41 -0500650 &function.declaration().returnType(),
651 symbolTable.get(), Modifiers{},
652 caller->isBuiltin(), &noInitialValue);
John Stiles28257db2021-03-17 15:18:09 -0400653 inlineStatements.push_back(std::move(var.fVarDecl));
John Stilesa94e0262021-04-27 17:29:59 -0400654 resultExpr = VariableReference::Make(/*offset=*/-1, var.fVarSymbol);
John Stiles511c5002021-02-25 11:17:02 -0500655 }
John Stiles44e96be2020-08-31 13:16:04 -0400656
657 // Create variables in the extra statements to hold the arguments, and assign the arguments to
658 // them.
659 VariableRewriteMap varMap;
John Stilesbff24ab2021-03-17 13:20:10 -0400660 for (int i = 0; i < arguments.count(); ++i) {
John Stiles049f0df2021-03-19 09:39:44 -0400661 // If the parameter isn't written to within the inline function ...
John Stilesbff24ab2021-03-17 13:20:10 -0400662 const Variable* param = function.declaration().parameters()[i];
John Stiles049f0df2021-03-19 09:39:44 -0400663 const ProgramUsage::VariableCounts& paramUsage = usage.get(*param);
664 if (!paramUsage.fWrite) {
665 // ... and can be inlined trivially (e.g. a swizzle, or a constant array index),
666 // or any expression without side effects that is only accessed at most once...
667 if ((paramUsage.fRead > 1) ? Analysis::IsTrivialExpression(*arguments[i])
668 : !arguments[i]->hasSideEffects()) {
John Stilesf201af82020-09-29 16:57:55 -0400669 // ... we don't need to copy it at all! We can just use the existing expression.
670 varMap[param] = arguments[i]->clone();
John Stiles44e96be2020-08-31 13:16:04 -0400671 continue;
672 }
673 }
Ethan Nicholasd2e09602021-06-10 11:21:59 -0400674 InlineVariable var = this->makeInlineVariable(String(param->name()), &arguments[i]->type(),
John Stiles7b920442020-12-17 10:43:41 -0500675 symbolTable.get(), param->modifiers(),
676 caller->isBuiltin(), &arguments[i]);
John Stiles28257db2021-03-17 15:18:09 -0400677 inlineStatements.push_back(std::move(var.fVarDecl));
John Stilesa94e0262021-04-27 17:29:59 -0400678 varMap[param] = VariableReference::Make(/*offset=*/-1, var.fVarSymbol);
John Stiles44e96be2020-08-31 13:16:04 -0400679 }
680
John Stiles7b920442020-12-17 10:43:41 -0500681 for (const std::unique_ptr<Statement>& stmt : body.children()) {
John Stiles28257db2021-03-17 15:18:09 -0400682 inlineStatements.push_back(this->inlineStatement(offset, &varMap, symbolTable.get(),
683 &resultExpr, returnComplexity, *stmt,
684 caller->isBuiltin()));
John Stiles44e96be2020-08-31 13:16:04 -0400685 }
686
John Stiles28257db2021-03-17 15:18:09 -0400687 SkASSERT(inlineStatements.count() <= expectedStmtCount);
688
John Stilesbf16b6c2021-03-12 19:24:31 -0500689 // Wrap all of the generated statements in a block. We need a real Block here, so we can't use
690 // MakeUnscoped. This is because we need to add another child statement to the Block later.
John Stiles28257db2021-03-17 15:18:09 -0400691 InlinedCall inlinedCall;
692 inlinedCall.fInlinedBody = Block::Make(offset, std::move(inlineStatements),
John Stilesbf16b6c2021-03-12 19:24:31 -0500693 /*symbols=*/nullptr, /*isScope=*/false);
694
John Stiles0c2d14a2021-03-01 10:08:08 -0500695 if (resultExpr) {
696 // Return our result expression as-is.
John Stilese41b4ee2020-09-28 12:28:16 -0400697 inlinedCall.fReplacementExpr = std::move(resultExpr);
John Stiles2558c462021-03-16 17:49:20 -0400698 } else if (function.declaration().returnType().isVoid()) {
John Stiles44e96be2020-08-31 13:16:04 -0400699 // It's a void function, so it doesn't actually result in anything, but we have to return
700 // something non-null as a standin.
John Stiles9ce80f72021-03-11 22:35:19 -0500701 inlinedCall.fReplacementExpr = BoolLiteral::Make(*fContext, offset, /*value=*/false);
John Stiles0c2d14a2021-03-01 10:08:08 -0500702 } else {
703 // It's a non-void function, but it never created a result expression--that is, it never
John Stiles2dda50d2021-03-03 10:46:44 -0500704 // returned anything on any path! This should have been detected in the function finalizer.
705 // Still, discard our output and generate an error.
706 SkDEBUGFAIL("inliner found non-void function that fails to return a value on any path");
707 fContext->fErrors.error(function.fOffset, "inliner found non-void function '" +
John Stiles0c2d14a2021-03-01 10:08:08 -0500708 function.declaration().name() +
John Stiles2dda50d2021-03-03 10:46:44 -0500709 "' that fails to return a value on any path");
John Stiles0c2d14a2021-03-01 10:08:08 -0500710 inlinedCall = {};
John Stiles44e96be2020-08-31 13:16:04 -0400711 }
712
John Stiles44e96be2020-08-31 13:16:04 -0400713 return inlinedCall;
714}
715
John Stiles2d7973a2020-10-02 15:01:03 -0400716bool Inliner::isSafeToInline(const FunctionDefinition* functionDef) {
John Stiles1c03d332020-10-13 10:30:23 -0400717 // A threshold of zero indicates that the inliner is completely disabled, so we can just return.
John Stilesd1204642021-02-17 16:30:02 -0500718 if (this->settings().fInlineThreshold <= 0) {
John Stiles1c03d332020-10-13 10:30:23 -0400719 return false;
720 }
721
John Stiles031a7672020-11-13 16:13:18 -0500722 // Enforce a limit on inlining to avoid pathological cases. (inliner/ExponentialGrowth.sksl)
723 if (fInlinedStatementCounter >= kInlinedStatementLimit) {
724 return false;
725 }
726
John Stiles2d7973a2020-10-02 15:01:03 -0400727 if (functionDef == nullptr) {
John Stiles44e96be2020-08-31 13:16:04 -0400728 // Can't inline something if we don't actually have its definition.
729 return false;
730 }
John Stiles2d7973a2020-10-02 15:01:03 -0400731
John Stiles0dd1a772021-03-09 22:14:27 -0500732 if (functionDef->declaration().modifiers().fFlags & Modifiers::kNoInline_Flag) {
733 // Refuse to inline functions decorated with `noinline`.
734 return false;
735 }
736
John Stilesbff24ab2021-03-17 13:20:10 -0400737 // We don't allow inlining a function with out parameters. (See skia:11326 for rationale.)
738 for (const Variable* param : functionDef->declaration().parameters()) {
739 if (param->modifiers().fFlags & Modifiers::Flag::kOut_Flag) {
740 return false;
741 }
742 }
743
John Stilesdc208472021-03-17 10:58:16 -0400744 // We don't have a mechanism to simulate early returns, so we can't inline if there is one.
745 return GetReturnComplexity(*functionDef) < ReturnComplexity::kEarlyReturns;
John Stiles44e96be2020-08-31 13:16:04 -0400746}
747
John Stiles2d7973a2020-10-02 15:01:03 -0400748// A candidate function for inlining, containing everything that `inlineCall` needs.
749struct InlineCandidate {
John Stiles78047582020-12-16 16:17:41 -0500750 std::shared_ptr<SymbolTable> fSymbols; // the SymbolTable of the candidate
John Stiles2d7973a2020-10-02 15:01:03 -0400751 std::unique_ptr<Statement>* fParentStmt; // the parent Statement of the enclosing stmt
752 std::unique_ptr<Statement>* fEnclosingStmt; // the Statement containing the candidate
753 std::unique_ptr<Expression>* fCandidateExpr; // the candidate FunctionCall to be inlined
754 FunctionDefinition* fEnclosingFunction; // the Function containing the candidate
John Stiles2d7973a2020-10-02 15:01:03 -0400755};
John Stiles93442622020-09-11 12:11:27 -0400756
John Stiles2d7973a2020-10-02 15:01:03 -0400757struct InlineCandidateList {
758 std::vector<InlineCandidate> fCandidates;
759};
760
761class InlineCandidateAnalyzer {
John Stiles70957c82020-10-02 16:42:10 -0400762public:
763 // A list of all the inlining candidates we found during analysis.
764 InlineCandidateList* fCandidateList;
John Stiles2d7973a2020-10-02 15:01:03 -0400765
John Stiles70957c82020-10-02 16:42:10 -0400766 // A stack of the symbol tables; since most nodes don't have one, expected to be shallower than
767 // the enclosing-statement stack.
John Stiles78047582020-12-16 16:17:41 -0500768 std::vector<std::shared_ptr<SymbolTable>> fSymbolTableStack;
John Stiles70957c82020-10-02 16:42:10 -0400769 // A stack of "enclosing" statements--these would be suitable for the inliner to use for adding
770 // new instructions. Not all statements are suitable (e.g. a for-loop's initializer). The
771 // inliner might replace a statement with a block containing the statement.
772 std::vector<std::unique_ptr<Statement>*> fEnclosingStmtStack;
773 // The function that we're currently processing (i.e. inlining into).
774 FunctionDefinition* fEnclosingFunction = nullptr;
John Stiles93442622020-09-11 12:11:27 -0400775
Brian Osman0006ad02020-11-18 15:38:39 -0500776 void visit(const std::vector<std::unique_ptr<ProgramElement>>& elements,
John Stiles78047582020-12-16 16:17:41 -0500777 std::shared_ptr<SymbolTable> symbols,
Brian Osman0006ad02020-11-18 15:38:39 -0500778 InlineCandidateList* candidateList) {
John Stiles70957c82020-10-02 16:42:10 -0400779 fCandidateList = candidateList;
Brian Osman0006ad02020-11-18 15:38:39 -0500780 fSymbolTableStack.push_back(symbols);
John Stiles93442622020-09-11 12:11:27 -0400781
Brian Osman0006ad02020-11-18 15:38:39 -0500782 for (const std::unique_ptr<ProgramElement>& pe : elements) {
Brian Osman1179fcf2020-10-08 16:04:40 -0400783 this->visitProgramElement(pe.get());
John Stiles93442622020-09-11 12:11:27 -0400784 }
785
John Stiles70957c82020-10-02 16:42:10 -0400786 fSymbolTableStack.pop_back();
787 fCandidateList = nullptr;
788 }
789
790 void visitProgramElement(ProgramElement* pe) {
791 switch (pe->kind()) {
792 case ProgramElement::Kind::kFunction: {
793 FunctionDefinition& funcDef = pe->as<FunctionDefinition>();
Brian Osman0006ad02020-11-18 15:38:39 -0500794 fEnclosingFunction = &funcDef;
795 this->visitStatement(&funcDef.body());
John Stiles70957c82020-10-02 16:42:10 -0400796 break;
John Stiles93442622020-09-11 12:11:27 -0400797 }
John Stiles70957c82020-10-02 16:42:10 -0400798 default:
799 // The inliner can't operate outside of a function's scope.
800 break;
801 }
802 }
803
804 void visitStatement(std::unique_ptr<Statement>* stmt,
805 bool isViableAsEnclosingStatement = true) {
806 if (!*stmt) {
807 return;
John Stiles93442622020-09-11 12:11:27 -0400808 }
809
John Stiles70957c82020-10-02 16:42:10 -0400810 size_t oldEnclosingStmtStackSize = fEnclosingStmtStack.size();
811 size_t oldSymbolStackSize = fSymbolTableStack.size();
John Stiles93442622020-09-11 12:11:27 -0400812
John Stiles70957c82020-10-02 16:42:10 -0400813 if (isViableAsEnclosingStatement) {
814 fEnclosingStmtStack.push_back(stmt);
John Stiles93442622020-09-11 12:11:27 -0400815 }
816
John Stiles70957c82020-10-02 16:42:10 -0400817 switch ((*stmt)->kind()) {
818 case Statement::Kind::kBreak:
819 case Statement::Kind::kContinue:
820 case Statement::Kind::kDiscard:
821 case Statement::Kind::kInlineMarker:
822 case Statement::Kind::kNop:
823 break;
824
825 case Statement::Kind::kBlock: {
826 Block& block = (*stmt)->as<Block>();
827 if (block.symbolTable()) {
John Stiles78047582020-12-16 16:17:41 -0500828 fSymbolTableStack.push_back(block.symbolTable());
John Stiles70957c82020-10-02 16:42:10 -0400829 }
830
John Stiles628777c2021-08-04 22:07:41 -0400831 for (std::unique_ptr<Statement>& blockStmt : block.children()) {
832 this->visitStatement(&blockStmt);
John Stiles70957c82020-10-02 16:42:10 -0400833 }
834 break;
John Stiles93442622020-09-11 12:11:27 -0400835 }
John Stiles70957c82020-10-02 16:42:10 -0400836 case Statement::Kind::kDo: {
837 DoStatement& doStmt = (*stmt)->as<DoStatement>();
838 // The loop body is a candidate for inlining.
839 this->visitStatement(&doStmt.statement());
840 // The inliner isn't smart enough to inline the test-expression for a do-while
841 // loop at this time. There are two limitations:
842 // - We would need to insert the inlined-body block at the very end of the do-
843 // statement's inner fStatement. We don't support that today, but it's doable.
844 // - We cannot inline the test expression if the loop uses `continue` anywhere; that
845 // would skip over the inlined block that evaluates the test expression. There
846 // isn't a good fix for this--any workaround would be more complex than the cost
847 // of a function call. However, loops that don't use `continue` would still be
848 // viable candidates for inlining.
849 break;
John Stiles93442622020-09-11 12:11:27 -0400850 }
John Stiles70957c82020-10-02 16:42:10 -0400851 case Statement::Kind::kExpression: {
852 ExpressionStatement& expr = (*stmt)->as<ExpressionStatement>();
853 this->visitExpression(&expr.expression());
854 break;
855 }
856 case Statement::Kind::kFor: {
857 ForStatement& forStmt = (*stmt)->as<ForStatement>();
Ethan Nicholas0d31ed52020-10-05 14:47:09 -0400858 if (forStmt.symbols()) {
John Stiles78047582020-12-16 16:17:41 -0500859 fSymbolTableStack.push_back(forStmt.symbols());
John Stiles70957c82020-10-02 16:42:10 -0400860 }
861
862 // The initializer and loop body are candidates for inlining.
Ethan Nicholas0d31ed52020-10-05 14:47:09 -0400863 this->visitStatement(&forStmt.initializer(),
John Stiles70957c82020-10-02 16:42:10 -0400864 /*isViableAsEnclosingStatement=*/false);
Ethan Nicholas0d31ed52020-10-05 14:47:09 -0400865 this->visitStatement(&forStmt.statement());
John Stiles70957c82020-10-02 16:42:10 -0400866
867 // The inliner isn't smart enough to inline the test- or increment-expressions
868 // of a for loop loop at this time. There are a handful of limitations:
869 // - We would need to insert the test-expression block at the very beginning of the
870 // for-loop's inner fStatement, and the increment-expression block at the very
871 // end. We don't support that today, but it's doable.
872 // - The for-loop's built-in test-expression would need to be dropped entirely,
873 // and the loop would be halted via a break statement at the end of the inlined
874 // test-expression. This is again something we don't support today, but it could
875 // be implemented.
876 // - We cannot inline the increment-expression if the loop uses `continue` anywhere;
877 // that would skip over the inlined block that evaluates the increment expression.
878 // There isn't a good fix for this--any workaround would be more complex than the
879 // cost of a function call. However, loops that don't use `continue` would still
880 // be viable candidates for increment-expression inlining.
881 break;
882 }
883 case Statement::Kind::kIf: {
884 IfStatement& ifStmt = (*stmt)->as<IfStatement>();
Ethan Nicholas8c44eca2020-10-07 16:47:09 -0400885 this->visitExpression(&ifStmt.test());
886 this->visitStatement(&ifStmt.ifTrue());
887 this->visitStatement(&ifStmt.ifFalse());
John Stiles70957c82020-10-02 16:42:10 -0400888 break;
889 }
890 case Statement::Kind::kReturn: {
891 ReturnStatement& returnStmt = (*stmt)->as<ReturnStatement>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -0400892 this->visitExpression(&returnStmt.expression());
John Stiles70957c82020-10-02 16:42:10 -0400893 break;
894 }
895 case Statement::Kind::kSwitch: {
896 SwitchStatement& switchStmt = (*stmt)->as<SwitchStatement>();
Ethan Nicholas01b05e52020-10-22 15:53:41 -0400897 if (switchStmt.symbols()) {
John Stiles78047582020-12-16 16:17:41 -0500898 fSymbolTableStack.push_back(switchStmt.symbols());
John Stiles70957c82020-10-02 16:42:10 -0400899 }
900
Ethan Nicholas01b05e52020-10-22 15:53:41 -0400901 this->visitExpression(&switchStmt.value());
John Stilesb23a64b2021-03-11 08:27:59 -0500902 for (const std::unique_ptr<Statement>& switchCase : switchStmt.cases()) {
John Stiles70957c82020-10-02 16:42:10 -0400903 // The switch-case's fValue cannot be a FunctionCall; skip it.
John Stilesb23a64b2021-03-11 08:27:59 -0500904 this->visitStatement(&switchCase->as<SwitchCase>().statement());
John Stiles70957c82020-10-02 16:42:10 -0400905 }
906 break;
907 }
908 case Statement::Kind::kVarDeclaration: {
909 VarDeclaration& varDeclStmt = (*stmt)->as<VarDeclaration>();
910 // Don't need to scan the declaration's sizes; those are always IntLiterals.
Ethan Nicholasc51f33e2020-10-13 13:49:44 -0400911 this->visitExpression(&varDeclStmt.value());
John Stiles70957c82020-10-02 16:42:10 -0400912 break;
913 }
John Stiles70957c82020-10-02 16:42:10 -0400914 default:
915 SkUNREACHABLE;
John Stiles93442622020-09-11 12:11:27 -0400916 }
917
John Stiles70957c82020-10-02 16:42:10 -0400918 // Pop our symbol and enclosing-statement stacks.
919 fSymbolTableStack.resize(oldSymbolStackSize);
920 fEnclosingStmtStack.resize(oldEnclosingStmtStackSize);
921 }
922
923 void visitExpression(std::unique_ptr<Expression>* expr) {
924 if (!*expr) {
925 return;
John Stiles93442622020-09-11 12:11:27 -0400926 }
John Stiles70957c82020-10-02 16:42:10 -0400927
928 switch ((*expr)->kind()) {
929 case Expression::Kind::kBoolLiteral:
Brian Osmanbe0b3b72021-01-06 14:27:35 -0500930 case Expression::Kind::kExternalFunctionReference:
John Stiles70957c82020-10-02 16:42:10 -0400931 case Expression::Kind::kFieldAccess:
932 case Expression::Kind::kFloatLiteral:
933 case Expression::Kind::kFunctionReference:
934 case Expression::Kind::kIntLiteral:
John Stiles70957c82020-10-02 16:42:10 -0400935 case Expression::Kind::kSetting:
936 case Expression::Kind::kTypeReference:
937 case Expression::Kind::kVariableReference:
938 // Nothing to scan here.
939 break;
940
941 case Expression::Kind::kBinary: {
942 BinaryExpression& binaryExpr = (*expr)->as<BinaryExpression>();
John Stiles2d4f9592020-10-30 10:29:12 -0400943 this->visitExpression(&binaryExpr.left());
John Stiles70957c82020-10-02 16:42:10 -0400944
945 // Logical-and and logical-or binary expressions do not inline the right side,
946 // because that would invalidate short-circuiting. That is, when evaluating
947 // expressions like these:
948 // (false && x()) // always false
949 // (true || y()) // always true
950 // It is illegal for side-effects from x() or y() to occur. The simplest way to
951 // enforce that rule is to avoid inlining the right side entirely. However, it is
952 // safe for other types of binary expression to inline both sides.
John Stiles45990502021-02-16 10:55:27 -0500953 Operator op = binaryExpr.getOperator();
954 bool shortCircuitable = (op.kind() == Token::Kind::TK_LOGICALAND ||
955 op.kind() == Token::Kind::TK_LOGICALOR);
John Stiles70957c82020-10-02 16:42:10 -0400956 if (!shortCircuitable) {
John Stiles2d4f9592020-10-30 10:29:12 -0400957 this->visitExpression(&binaryExpr.right());
John Stiles70957c82020-10-02 16:42:10 -0400958 }
959 break;
960 }
John Stiles7384b372021-04-01 13:48:15 -0400961 case Expression::Kind::kConstructorArray:
John Stilese3ae9682021-08-05 10:35:01 -0400962 case Expression::Kind::kConstructorArrayCast:
John Stiles8cad6372021-04-07 12:31:13 -0400963 case Expression::Kind::kConstructorCompound:
964 case Expression::Kind::kConstructorCompoundCast:
John Stiles2938eea2021-04-01 18:58:25 -0400965 case Expression::Kind::kConstructorDiagonalMatrix:
John Stiles5abb9e12021-04-06 13:47:19 -0400966 case Expression::Kind::kConstructorMatrixResize:
John Stilesfd7252f2021-04-04 22:24:40 -0400967 case Expression::Kind::kConstructorScalarCast:
John Stilesd47330f2021-04-08 23:25:52 -0400968 case Expression::Kind::kConstructorSplat:
969 case Expression::Kind::kConstructorStruct: {
John Stiles7384b372021-04-01 13:48:15 -0400970 AnyConstructor& constructorExpr = (*expr)->asAnyConstructor();
971 for (std::unique_ptr<Expression>& arg : constructorExpr.argumentSpan()) {
John Stiles70957c82020-10-02 16:42:10 -0400972 this->visitExpression(&arg);
973 }
974 break;
975 }
976 case Expression::Kind::kExternalFunctionCall: {
977 ExternalFunctionCall& funcCallExpr = (*expr)->as<ExternalFunctionCall>();
978 for (std::unique_ptr<Expression>& arg : funcCallExpr.arguments()) {
979 this->visitExpression(&arg);
980 }
981 break;
982 }
983 case Expression::Kind::kFunctionCall: {
984 FunctionCall& funcCallExpr = (*expr)->as<FunctionCall>();
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400985 for (std::unique_ptr<Expression>& arg : funcCallExpr.arguments()) {
John Stiles70957c82020-10-02 16:42:10 -0400986 this->visitExpression(&arg);
987 }
988 this->addInlineCandidate(expr);
989 break;
990 }
John Stiles708faba2021-03-19 09:43:23 -0400991 case Expression::Kind::kIndex: {
John Stiles70957c82020-10-02 16:42:10 -0400992 IndexExpression& indexExpr = (*expr)->as<IndexExpression>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -0400993 this->visitExpression(&indexExpr.base());
994 this->visitExpression(&indexExpr.index());
John Stiles70957c82020-10-02 16:42:10 -0400995 break;
996 }
997 case Expression::Kind::kPostfix: {
998 PostfixExpression& postfixExpr = (*expr)->as<PostfixExpression>();
Ethan Nicholas444ccc62020-10-09 10:16:22 -0400999 this->visitExpression(&postfixExpr.operand());
John Stiles70957c82020-10-02 16:42:10 -04001000 break;
1001 }
1002 case Expression::Kind::kPrefix: {
1003 PrefixExpression& prefixExpr = (*expr)->as<PrefixExpression>();
Ethan Nicholas444ccc62020-10-09 10:16:22 -04001004 this->visitExpression(&prefixExpr.operand());
John Stiles70957c82020-10-02 16:42:10 -04001005 break;
1006 }
1007 case Expression::Kind::kSwizzle: {
1008 Swizzle& swizzleExpr = (*expr)->as<Swizzle>();
Ethan Nicholas6b4d5812020-10-12 16:11:51 -04001009 this->visitExpression(&swizzleExpr.base());
John Stiles70957c82020-10-02 16:42:10 -04001010 break;
1011 }
1012 case Expression::Kind::kTernary: {
1013 TernaryExpression& ternaryExpr = (*expr)->as<TernaryExpression>();
1014 // The test expression is a candidate for inlining.
Ethan Nicholasdd218162020-10-08 05:48:01 -04001015 this->visitExpression(&ternaryExpr.test());
John Stiles70957c82020-10-02 16:42:10 -04001016 // The true- and false-expressions cannot be inlined, because we are only allowed to
1017 // evaluate one side.
1018 break;
1019 }
1020 default:
1021 SkUNREACHABLE;
1022 }
1023 }
1024
1025 void addInlineCandidate(std::unique_ptr<Expression>* candidate) {
1026 fCandidateList->fCandidates.push_back(
1027 InlineCandidate{fSymbolTableStack.back(),
1028 find_parent_statement(fEnclosingStmtStack),
1029 fEnclosingStmtStack.back(),
1030 candidate,
John Stiles9b9415e2020-11-23 14:48:06 -05001031 fEnclosingFunction});
John Stiles70957c82020-10-02 16:42:10 -04001032 }
John Stiles2d7973a2020-10-02 15:01:03 -04001033};
John Stiles93442622020-09-11 12:11:27 -04001034
John Stiles9b9415e2020-11-23 14:48:06 -05001035static const FunctionDeclaration& candidate_func(const InlineCandidate& candidate) {
1036 return (*candidate.fCandidateExpr)->as<FunctionCall>().function();
1037}
John Stiles915a38c2020-09-14 09:38:13 -04001038
John Stiles9b9415e2020-11-23 14:48:06 -05001039bool Inliner::candidateCanBeInlined(const InlineCandidate& candidate, InlinabilityCache* cache) {
1040 const FunctionDeclaration& funcDecl = candidate_func(candidate);
John Stiles1c03d332020-10-13 10:30:23 -04001041 auto [iter, wasInserted] = cache->insert({&funcDecl, false});
John Stiles2d7973a2020-10-02 15:01:03 -04001042 if (wasInserted) {
1043 // Recursion is forbidden here to avoid an infinite death spiral of inlining.
John Stiles132cfdd2021-03-15 22:08:38 +00001044 iter->second = this->isSafeToInline(funcDecl.definition()) &&
1045 !contains_recursive_call(funcDecl);
John Stiles93442622020-09-11 12:11:27 -04001046 }
1047
John Stiles2d7973a2020-10-02 15:01:03 -04001048 return iter->second;
1049}
1050
John Stiles9b9415e2020-11-23 14:48:06 -05001051int Inliner::getFunctionSize(const FunctionDeclaration& funcDecl, FunctionSizeCache* cache) {
1052 auto [iter, wasInserted] = cache->insert({&funcDecl, 0});
John Stiles2d7973a2020-10-02 15:01:03 -04001053 if (wasInserted) {
John Stiles9b9415e2020-11-23 14:48:06 -05001054 iter->second = Analysis::NodeCountUpToLimit(*funcDecl.definition(),
John Stilesd1204642021-02-17 16:30:02 -05001055 this->settings().fInlineThreshold);
John Stiles2d7973a2020-10-02 15:01:03 -04001056 }
John Stiles2d7973a2020-10-02 15:01:03 -04001057 return iter->second;
1058}
1059
Brian Osman0006ad02020-11-18 15:38:39 -05001060void Inliner::buildCandidateList(const std::vector<std::unique_ptr<ProgramElement>>& elements,
John Stiles78047582020-12-16 16:17:41 -05001061 std::shared_ptr<SymbolTable> symbols, ProgramUsage* usage,
Brian Osman0006ad02020-11-18 15:38:39 -05001062 InlineCandidateList* candidateList) {
John Stiles2d7973a2020-10-02 15:01:03 -04001063 // This is structured much like a ProgramVisitor, but does not actually use ProgramVisitor.
1064 // The analyzer needs to keep track of the `unique_ptr<T>*` of statements and expressions so
1065 // that they can later be replaced, and ProgramVisitor does not provide this; it only provides a
1066 // `const T&`.
1067 InlineCandidateAnalyzer analyzer;
Brian Osman0006ad02020-11-18 15:38:39 -05001068 analyzer.visit(elements, symbols, candidateList);
John Stiles2d7973a2020-10-02 15:01:03 -04001069
John Stiles0ad233f2020-11-25 11:02:05 -05001070 // Early out if there are no inlining candidates.
John Stiles2d7973a2020-10-02 15:01:03 -04001071 std::vector<InlineCandidate>& candidates = candidateList->fCandidates;
John Stiles0ad233f2020-11-25 11:02:05 -05001072 if (candidates.empty()) {
1073 return;
1074 }
1075
1076 // Remove candidates that are not safe to inline.
John Stiles2d7973a2020-10-02 15:01:03 -04001077 InlinabilityCache cache;
1078 candidates.erase(std::remove_if(candidates.begin(),
1079 candidates.end(),
1080 [&](const InlineCandidate& candidate) {
1081 return !this->candidateCanBeInlined(candidate, &cache);
1082 }),
1083 candidates.end());
1084
John Stiles0ad233f2020-11-25 11:02:05 -05001085 // If the inline threshold is unlimited, or if we have no candidates left, our candidate list is
1086 // complete.
John Stilesd1204642021-02-17 16:30:02 -05001087 if (this->settings().fInlineThreshold == INT_MAX || candidates.empty()) {
John Stiles0ad233f2020-11-25 11:02:05 -05001088 return;
John Stiles2d7973a2020-10-02 15:01:03 -04001089 }
John Stiles0ad233f2020-11-25 11:02:05 -05001090
1091 // Remove candidates on a per-function basis if the effect of inlining would be to make more
1092 // than `inlineThreshold` nodes. (i.e. if Func() would be inlined six times and its size is
1093 // 10 nodes, it should be inlined if the inlineThreshold is 60 or higher.)
1094 FunctionSizeCache functionSizeCache;
1095 FunctionSizeCache candidateTotalCost;
1096 for (InlineCandidate& candidate : candidates) {
1097 const FunctionDeclaration& fnDecl = candidate_func(candidate);
1098 candidateTotalCost[&fnDecl] += this->getFunctionSize(fnDecl, &functionSizeCache);
1099 }
1100
John Stilesd1204642021-02-17 16:30:02 -05001101 candidates.erase(std::remove_if(candidates.begin(), candidates.end(),
1102 [&](const InlineCandidate& candidate) {
1103 const FunctionDeclaration& fnDecl = candidate_func(candidate);
1104 if (fnDecl.modifiers().fFlags & Modifiers::kInline_Flag) {
1105 // Functions marked `inline` ignore size limitations.
1106 return false;
1107 }
1108 if (usage->get(fnDecl) == 1) {
1109 // If a function is only used once, it's cost-free to inline.
1110 return false;
1111 }
1112 if (candidateTotalCost[&fnDecl] <= this->settings().fInlineThreshold) {
1113 // We won't exceed the inline threshold by inlining this.
1114 return false;
1115 }
1116 // Inlining this function will add too many IRNodes.
1117 return true;
1118 }),
1119 candidates.end());
John Stiles2d7973a2020-10-02 15:01:03 -04001120}
1121
Brian Osman0006ad02020-11-18 15:38:39 -05001122bool Inliner::analyze(const std::vector<std::unique_ptr<ProgramElement>>& elements,
John Stiles78047582020-12-16 16:17:41 -05001123 std::shared_ptr<SymbolTable> symbols,
Brian Osman0006ad02020-11-18 15:38:39 -05001124 ProgramUsage* usage) {
John Stilesd34d56e2020-10-12 12:04:47 -04001125 // A threshold of zero indicates that the inliner is completely disabled, so we can just return.
John Stilesd1204642021-02-17 16:30:02 -05001126 if (this->settings().fInlineThreshold <= 0) {
John Stilesd34d56e2020-10-12 12:04:47 -04001127 return false;
1128 }
1129
John Stiles031a7672020-11-13 16:13:18 -05001130 // Enforce a limit on inlining to avoid pathological cases. (inliner/ExponentialGrowth.sksl)
1131 if (fInlinedStatementCounter >= kInlinedStatementLimit) {
1132 return false;
1133 }
1134
John Stiles2d7973a2020-10-02 15:01:03 -04001135 InlineCandidateList candidateList;
John Stiles9b9415e2020-11-23 14:48:06 -05001136 this->buildCandidateList(elements, symbols, usage, &candidateList);
John Stiles2d7973a2020-10-02 15:01:03 -04001137
John Stiles915a38c2020-09-14 09:38:13 -04001138 // Inline the candidates where we've determined that it's safe to do so.
John Stiles708faba2021-03-19 09:43:23 -04001139 using StatementRemappingTable = std::unordered_map<std::unique_ptr<Statement>*,
1140 std::unique_ptr<Statement>*>;
1141 StatementRemappingTable statementRemappingTable;
1142
John Stiles915a38c2020-09-14 09:38:13 -04001143 bool madeChanges = false;
John Stiles2d7973a2020-10-02 15:01:03 -04001144 for (const InlineCandidate& candidate : candidateList.fCandidates) {
John Stiles915a38c2020-09-14 09:38:13 -04001145 FunctionCall& funcCall = (*candidate.fCandidateExpr)->as<FunctionCall>();
John Stiles915a38c2020-09-14 09:38:13 -04001146
John Stiles915a38c2020-09-14 09:38:13 -04001147 // Convert the function call to its inlined equivalent.
John Stiles30fce9c2021-03-18 09:24:06 -04001148 InlinedCall inlinedCall = this->inlineCall(&funcCall, candidate.fSymbols, *usage,
Ethan Nicholas0a5d0962020-10-14 13:33:18 -04001149 &candidate.fEnclosingFunction->declaration());
John Stiles915a38c2020-09-14 09:38:13 -04001150
John Stiles0c2d14a2021-03-01 10:08:08 -05001151 // Stop if an error was detected during the inlining process.
1152 if (!inlinedCall.fInlinedBody && !inlinedCall.fReplacementExpr) {
1153 break;
John Stiles915a38c2020-09-14 09:38:13 -04001154 }
1155
John Stiles0c2d14a2021-03-01 10:08:08 -05001156 // Ensure that the inlined body has a scope if it needs one.
1157 this->ensureScopedBlocks(inlinedCall.fInlinedBody.get(), candidate.fParentStmt->get());
1158
1159 // Add references within the inlined body
1160 usage->add(inlinedCall.fInlinedBody.get());
1161
John Stiles708faba2021-03-19 09:43:23 -04001162 // Look up the enclosing statement; remap it if necessary.
1163 std::unique_ptr<Statement>* enclosingStmt = candidate.fEnclosingStmt;
1164 for (;;) {
1165 auto iter = statementRemappingTable.find(enclosingStmt);
1166 if (iter == statementRemappingTable.end()) {
1167 break;
1168 }
1169 enclosingStmt = iter->second;
1170 }
1171
John Stiles0c2d14a2021-03-01 10:08:08 -05001172 // Move the enclosing statement to the end of the unscoped Block containing the inlined
1173 // function, then replace the enclosing statement with that Block.
1174 // Before:
1175 // fInlinedBody = Block{ stmt1, stmt2, stmt3 }
1176 // fEnclosingStmt = stmt4
1177 // After:
1178 // fInlinedBody = null
1179 // fEnclosingStmt = Block{ stmt1, stmt2, stmt3, stmt4 }
John Stiles708faba2021-03-19 09:43:23 -04001180 inlinedCall.fInlinedBody->children().push_back(std::move(*enclosingStmt));
1181 *enclosingStmt = std::move(inlinedCall.fInlinedBody);
John Stiles0c2d14a2021-03-01 10:08:08 -05001182
John Stiles915a38c2020-09-14 09:38:13 -04001183 // Replace the candidate function call with our replacement expression.
John Stiles60dbf072021-08-02 14:22:34 -04001184 usage->remove(candidate.fCandidateExpr->get());
1185 usage->add(inlinedCall.fReplacementExpr.get());
John Stiles915a38c2020-09-14 09:38:13 -04001186 *candidate.fCandidateExpr = std::move(inlinedCall.fReplacementExpr);
1187 madeChanges = true;
1188
John Stiles708faba2021-03-19 09:43:23 -04001189 // If anything else pointed at our enclosing statement, it's now pointing at a Block
1190 // containing many other statements as well. Maintain a fix-up table to account for this.
1191 statementRemappingTable[enclosingStmt] = &(*enclosingStmt)->as<Block>().children().back();
1192
John Stiles031a7672020-11-13 16:13:18 -05001193 // Stop inlining if we've reached our hard cap on new statements.
1194 if (fInlinedStatementCounter >= kInlinedStatementLimit) {
1195 break;
1196 }
1197
John Stiles915a38c2020-09-14 09:38:13 -04001198 // Note that nothing was destroyed except for the FunctionCall. All other nodes should
1199 // remain valid.
1200 }
1201
1202 return madeChanges;
John Stiles93442622020-09-11 12:11:27 -04001203}
1204
John Stiles44e96be2020-08-31 13:16:04 -04001205} // namespace SkSL