1 //===- PartialInlining.cpp - Inline parts of functions --------------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This pass performs partial inlining, typically by inlining an if statement
10 // that surrounds the body of the function.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/Transforms/IPO/PartialInlining.h"
15 #include "llvm/ADT/DenseMap.h"
16 #include "llvm/ADT/DenseSet.h"
17 #include "llvm/ADT/None.h"
18 #include "llvm/ADT/Optional.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/ADT/SmallVector.h"
21 #include "llvm/ADT/Statistic.h"
22 #include "llvm/Analysis/BlockFrequencyInfo.h"
23 #include "llvm/Analysis/BranchProbabilityInfo.h"
24 #include "llvm/Analysis/InlineCost.h"
25 #include "llvm/Analysis/LoopInfo.h"
26 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
27 #include "llvm/Analysis/ProfileSummaryInfo.h"
28 #include "llvm/Analysis/TargetLibraryInfo.h"
29 #include "llvm/Analysis/TargetTransformInfo.h"
30 #include "llvm/IR/Attributes.h"
31 #include "llvm/IR/BasicBlock.h"
32 #include "llvm/IR/CFG.h"
33 #include "llvm/IR/CallSite.h"
34 #include "llvm/IR/DebugLoc.h"
35 #include "llvm/IR/DiagnosticInfo.h"
36 #include "llvm/IR/Dominators.h"
37 #include "llvm/IR/Function.h"
38 #include "llvm/IR/InstrTypes.h"
39 #include "llvm/IR/Instruction.h"
40 #include "llvm/IR/Instructions.h"
41 #include "llvm/IR/IntrinsicInst.h"
42 #include "llvm/IR/Intrinsics.h"
43 #include "llvm/IR/Module.h"
44 #include "llvm/IR/User.h"
45 #include "llvm/Pass.h"
46 #include "llvm/Support/BlockFrequency.h"
47 #include "llvm/Support/BranchProbability.h"
48 #include "llvm/Support/Casting.h"
49 #include "llvm/Support/CommandLine.h"
50 #include "llvm/Support/ErrorHandling.h"
51 #include "llvm/Transforms/IPO.h"
52 #include "llvm/Transforms/Utils/Cloning.h"
53 #include "llvm/Transforms/Utils/CodeExtractor.h"
54 #include "llvm/Transforms/Utils/ValueMapper.h"
66 #define DEBUG_TYPE "partial-inlining"
68 STATISTIC(NumPartialInlined
,
69 "Number of callsites functions partially inlined into.");
70 STATISTIC(NumColdOutlinePartialInlined
, "Number of times functions with "
71 "cold outlined regions were partially "
72 "inlined into its caller(s).");
73 STATISTIC(NumColdRegionsFound
,
74 "Number of cold single entry/exit regions found.");
75 STATISTIC(NumColdRegionsOutlined
,
76 "Number of cold single entry/exit regions outlined.");
78 // Command line option to disable partial-inlining. The default is false:
80 DisablePartialInlining("disable-partial-inlining", cl::init(false),
81 cl::Hidden
, cl::desc("Disable partial inlining"));
82 // Command line option to disable multi-region partial-inlining. The default is
84 static cl::opt
<bool> DisableMultiRegionPartialInline(
85 "disable-mr-partial-inlining", cl::init(false), cl::Hidden
,
86 cl::desc("Disable multi-region partial inlining"));
88 // Command line option to force outlining in regions with live exit variables.
89 // The default is false:
91 ForceLiveExit("pi-force-live-exit-outline", cl::init(false), cl::Hidden
,
92 cl::desc("Force outline regions with live exits"));
94 // Command line option to enable marking outline functions with Cold Calling
95 // Convention. The default is false:
97 MarkOutlinedColdCC("pi-mark-coldcc", cl::init(false), cl::Hidden
,
98 cl::desc("Mark outline function calls with ColdCC"));
101 // Command line option to debug partial-inlining. The default is none:
102 static cl::opt
<bool> TracePartialInlining("trace-partial-inlining",
103 cl::init(false), cl::Hidden
,
104 cl::desc("Trace partial inlining."));
107 // This is an option used by testing:
108 static cl::opt
<bool> SkipCostAnalysis("skip-partial-inlining-cost-analysis",
109 cl::init(false), cl::ZeroOrMore
,
111 cl::desc("Skip Cost Analysis"));
112 // Used to determine if a cold region is worth outlining based on
113 // its inlining cost compared to the original function. Default is set at 10%.
114 // ie. if the cold region reduces the inlining cost of the original function by
116 static cl::opt
<float> MinRegionSizeRatio(
117 "min-region-size-ratio", cl::init(0.1), cl::Hidden
,
118 cl::desc("Minimum ratio comparing relative sizes of each "
119 "outline candidate and original function"));
120 // Used to tune the minimum number of execution counts needed in the predecessor
121 // block to the cold edge. ie. confidence interval.
122 static cl::opt
<unsigned>
123 MinBlockCounterExecution("min-block-execution", cl::init(100), cl::Hidden
,
124 cl::desc("Minimum block executions to consider "
125 "its BranchProbabilityInfo valid"));
126 // Used to determine when an edge is considered cold. Default is set to 10%. ie.
127 // if the branch probability is 10% or less, then it is deemed as 'cold'.
128 static cl::opt
<float> ColdBranchRatio(
129 "cold-branch-ratio", cl::init(0.1), cl::Hidden
,
130 cl::desc("Minimum BranchProbability to consider a region cold."));
132 static cl::opt
<unsigned> MaxNumInlineBlocks(
133 "max-num-inline-blocks", cl::init(5), cl::Hidden
,
134 cl::desc("Max number of blocks to be partially inlined"));
136 // Command line option to set the maximum number of partial inlining allowed
137 // for the module. The default value of -1 means no limit.
138 static cl::opt
<int> MaxNumPartialInlining(
139 "max-partial-inlining", cl::init(-1), cl::Hidden
, cl::ZeroOrMore
,
140 cl::desc("Max number of partial inlining. The default is unlimited"));
142 // Used only when PGO or user annotated branch data is absent. It is
143 // the least value that is used to weigh the outline region. If BFI
144 // produces larger value, the BFI value will be used.
146 OutlineRegionFreqPercent("outline-region-freq-percent", cl::init(75),
147 cl::Hidden
, cl::ZeroOrMore
,
148 cl::desc("Relative frequency of outline region to "
151 static cl::opt
<unsigned> ExtraOutliningPenalty(
152 "partial-inlining-extra-penalty", cl::init(0), cl::Hidden
,
153 cl::desc("A debug option to add additional penalty to the computed one."));
157 struct FunctionOutliningInfo
{
158 FunctionOutliningInfo() = default;
160 // Returns the number of blocks to be inlined including all blocks
161 // in Entries and one return block.
162 unsigned GetNumInlinedBlocks() const { return Entries
.size() + 1; }
164 // A set of blocks including the function entry that guard
165 // the region to be outlined.
166 SmallVector
<BasicBlock
*, 4> Entries
;
168 // The return block that is not included in the outlined region.
169 BasicBlock
*ReturnBlock
= nullptr;
171 // The dominating block of the region to be outlined.
172 BasicBlock
*NonReturnBlock
= nullptr;
174 // The set of blocks in Entries that that are predecessors to ReturnBlock
175 SmallVector
<BasicBlock
*, 4> ReturnBlockPreds
;
178 struct FunctionOutliningMultiRegionInfo
{
179 FunctionOutliningMultiRegionInfo()
182 // Container for outline regions
183 struct OutlineRegionInfo
{
184 OutlineRegionInfo(ArrayRef
<BasicBlock
*> Region
,
185 BasicBlock
*EntryBlock
, BasicBlock
*ExitBlock
,
186 BasicBlock
*ReturnBlock
)
187 : Region(Region
.begin(), Region
.end()), EntryBlock(EntryBlock
),
188 ExitBlock(ExitBlock
), ReturnBlock(ReturnBlock
) {}
189 SmallVector
<BasicBlock
*, 8> Region
;
190 BasicBlock
*EntryBlock
;
191 BasicBlock
*ExitBlock
;
192 BasicBlock
*ReturnBlock
;
195 SmallVector
<OutlineRegionInfo
, 4> ORI
;
198 struct PartialInlinerImpl
{
201 std::function
<AssumptionCache
&(Function
&)> *GetAC
,
202 function_ref
<AssumptionCache
*(Function
&)> LookupAC
,
203 std::function
<TargetTransformInfo
&(Function
&)> *GTTI
,
204 Optional
<function_ref
<BlockFrequencyInfo
&(Function
&)>> GBFI
,
205 ProfileSummaryInfo
*ProfSI
)
206 : GetAssumptionCache(GetAC
), LookupAssumptionCache(LookupAC
),
207 GetTTI(GTTI
), GetBFI(GBFI
), PSI(ProfSI
) {}
210 // Main part of the transformation that calls helper functions to find
211 // outlining candidates, clone & outline the function, and attempt to
212 // partially inline the resulting function. Returns true if
213 // inlining was successful, false otherwise. Also returns the outline
214 // function (only if we partially inlined early returns) as there is a
215 // possibility to further "peel" early return statements that were left in the
216 // outline function due to code size.
217 std::pair
<bool, Function
*> unswitchFunction(Function
*F
);
219 // This class speculatively clones the function to be partial inlined.
220 // At the end of partial inlining, the remaining callsites to the cloned
221 // function that are not partially inlined will be fixed up to reference
222 // the original function, and the cloned function will be erased.
223 struct FunctionCloner
{
224 // Two constructors, one for single region outlining, the other for
225 // multi-region outlining.
226 FunctionCloner(Function
*F
, FunctionOutliningInfo
*OI
,
227 OptimizationRemarkEmitter
&ORE
,
228 function_ref
<AssumptionCache
*(Function
&)> LookupAC
);
229 FunctionCloner(Function
*F
, FunctionOutliningMultiRegionInfo
*OMRI
,
230 OptimizationRemarkEmitter
&ORE
,
231 function_ref
<AssumptionCache
*(Function
&)> LookupAC
);
234 // Prepare for function outlining: making sure there is only
235 // one incoming edge from the extracted/outlined region to
237 void NormalizeReturnBlock();
239 // Do function outlining for cold regions.
240 bool doMultiRegionFunctionOutlining();
241 // Do function outlining for region after early return block(s).
242 // NOTE: For vararg functions that do the vararg handling in the outlined
243 // function, we temporarily generate IR that does not properly
244 // forward varargs to the outlined function. Calling InlineFunction
245 // will update calls to the outlined functions to properly forward
247 Function
*doSingleRegionFunctionOutlining();
249 Function
*OrigFunc
= nullptr;
250 Function
*ClonedFunc
= nullptr;
252 typedef std::pair
<Function
*, BasicBlock
*> FuncBodyCallerPair
;
253 // Keep track of Outlined Functions and the basic block they're called from.
254 SmallVector
<FuncBodyCallerPair
, 4> OutlinedFunctions
;
256 // ClonedFunc is inlined in one of its callers after function
258 bool IsFunctionInlined
= false;
259 // The cost of the region to be outlined.
260 int OutlinedRegionCost
= 0;
261 // ClonedOI is specific to outlining non-early return blocks.
262 std::unique_ptr
<FunctionOutliningInfo
> ClonedOI
= nullptr;
263 // ClonedOMRI is specific to outlining cold regions.
264 std::unique_ptr
<FunctionOutliningMultiRegionInfo
> ClonedOMRI
= nullptr;
265 std::unique_ptr
<BlockFrequencyInfo
> ClonedFuncBFI
= nullptr;
266 OptimizationRemarkEmitter
&ORE
;
267 function_ref
<AssumptionCache
*(Function
&)> LookupAC
;
271 int NumPartialInlining
= 0;
272 std::function
<AssumptionCache
&(Function
&)> *GetAssumptionCache
;
273 function_ref
<AssumptionCache
*(Function
&)> LookupAssumptionCache
;
274 std::function
<TargetTransformInfo
&(Function
&)> *GetTTI
;
275 Optional
<function_ref
<BlockFrequencyInfo
&(Function
&)>> GetBFI
;
276 ProfileSummaryInfo
*PSI
;
278 // Return the frequency of the OutlininingBB relative to F's entry point.
279 // The result is no larger than 1 and is represented using BP.
280 // (Note that the outlined region's 'head' block can only have incoming
281 // edges from the guarding entry blocks).
282 BranchProbability
getOutliningCallBBRelativeFreq(FunctionCloner
&Cloner
);
284 // Return true if the callee of CS should be partially inlined with
286 bool shouldPartialInline(CallSite CS
, FunctionCloner
&Cloner
,
287 BlockFrequency WeightedOutliningRcost
,
288 OptimizationRemarkEmitter
&ORE
);
290 // Try to inline DuplicateFunction (cloned from F with call to
291 // the OutlinedFunction into its callers. Return true
292 // if there is any successful inlining.
293 bool tryPartialInline(FunctionCloner
&Cloner
);
295 // Compute the mapping from use site of DuplicationFunction to the enclosing
296 // BB's profile count.
297 void computeCallsiteToProfCountMap(Function
*DuplicateFunction
,
298 DenseMap
<User
*, uint64_t> &SiteCountMap
);
300 bool IsLimitReached() {
301 return (MaxNumPartialInlining
!= -1 &&
302 NumPartialInlining
>= MaxNumPartialInlining
);
305 static CallSite
getCallSite(User
*U
) {
307 if (CallInst
*CI
= dyn_cast
<CallInst
>(U
))
309 else if (InvokeInst
*II
= dyn_cast
<InvokeInst
>(U
))
312 llvm_unreachable("All uses must be calls");
316 static CallSite
getOneCallSiteTo(Function
*F
) {
317 User
*User
= *F
->user_begin();
318 return getCallSite(User
);
321 std::tuple
<DebugLoc
, BasicBlock
*> getOneDebugLoc(Function
*F
) {
322 CallSite CS
= getOneCallSiteTo(F
);
323 DebugLoc DLoc
= CS
.getInstruction()->getDebugLoc();
324 BasicBlock
*Block
= CS
.getParent();
325 return std::make_tuple(DLoc
, Block
);
328 // Returns the costs associated with function outlining:
329 // - The first value is the non-weighted runtime cost for making the call
330 // to the outlined function, including the addtional setup cost in the
331 // outlined function itself;
332 // - The second value is the estimated size of the new call sequence in
333 // basic block Cloner.OutliningCallBB;
334 std::tuple
<int, int> computeOutliningCosts(FunctionCloner
&Cloner
);
336 // Compute the 'InlineCost' of block BB. InlineCost is a proxy used to
337 // approximate both the size and runtime cost (Note that in the current
338 // inline cost analysis, there is no clear distinction there either).
339 static int computeBBInlineCost(BasicBlock
*BB
);
341 std::unique_ptr
<FunctionOutliningInfo
> computeOutliningInfo(Function
*F
);
342 std::unique_ptr
<FunctionOutliningMultiRegionInfo
>
343 computeOutliningColdRegionsInfo(Function
*F
, OptimizationRemarkEmitter
&ORE
);
346 struct PartialInlinerLegacyPass
: public ModulePass
{
347 static char ID
; // Pass identification, replacement for typeid
349 PartialInlinerLegacyPass() : ModulePass(ID
) {
350 initializePartialInlinerLegacyPassPass(*PassRegistry::getPassRegistry());
353 void getAnalysisUsage(AnalysisUsage
&AU
) const override
{
354 AU
.addRequired
<AssumptionCacheTracker
>();
355 AU
.addRequired
<ProfileSummaryInfoWrapperPass
>();
356 AU
.addRequired
<TargetTransformInfoWrapperPass
>();
359 bool runOnModule(Module
&M
) override
{
363 AssumptionCacheTracker
*ACT
= &getAnalysis
<AssumptionCacheTracker
>();
364 TargetTransformInfoWrapperPass
*TTIWP
=
365 &getAnalysis
<TargetTransformInfoWrapperPass
>();
366 ProfileSummaryInfo
*PSI
=
367 &getAnalysis
<ProfileSummaryInfoWrapperPass
>().getPSI();
369 std::function
<AssumptionCache
&(Function
&)> GetAssumptionCache
=
370 [&ACT
](Function
&F
) -> AssumptionCache
& {
371 return ACT
->getAssumptionCache(F
);
374 auto LookupAssumptionCache
= [ACT
](Function
&F
) -> AssumptionCache
* {
375 return ACT
->lookupAssumptionCache(F
);
378 std::function
<TargetTransformInfo
&(Function
&)> GetTTI
=
379 [&TTIWP
](Function
&F
) -> TargetTransformInfo
& {
380 return TTIWP
->getTTI(F
);
383 return PartialInlinerImpl(&GetAssumptionCache
, LookupAssumptionCache
,
384 &GetTTI
, NoneType::None
, PSI
)
389 } // end anonymous namespace
391 std::unique_ptr
<FunctionOutliningMultiRegionInfo
>
392 PartialInlinerImpl::computeOutliningColdRegionsInfo(Function
*F
,
393 OptimizationRemarkEmitter
&ORE
) {
394 BasicBlock
*EntryBlock
= &F
->front();
396 DominatorTree
DT(*F
);
398 BranchProbabilityInfo
BPI(*F
, LI
);
399 std::unique_ptr
<BlockFrequencyInfo
> ScopedBFI
;
400 BlockFrequencyInfo
*BFI
;
402 ScopedBFI
.reset(new BlockFrequencyInfo(*F
, BPI
, LI
));
403 BFI
= ScopedBFI
.get();
405 BFI
= &(*GetBFI
)(*F
);
407 // Return if we don't have profiling information.
408 if (!PSI
->hasInstrumentationProfile())
409 return std::unique_ptr
<FunctionOutliningMultiRegionInfo
>();
411 std::unique_ptr
<FunctionOutliningMultiRegionInfo
> OutliningInfo
=
412 llvm::make_unique
<FunctionOutliningMultiRegionInfo
>();
414 auto IsSingleEntry
= [](SmallVectorImpl
<BasicBlock
*> &BlockList
) {
415 BasicBlock
*Dom
= BlockList
.front();
416 return BlockList
.size() > 1 && Dom
->hasNPredecessors(1);
420 [&ORE
](SmallVectorImpl
<BasicBlock
*> &BlockList
) -> BasicBlock
* {
421 BasicBlock
*ExitBlock
= nullptr;
422 for (auto *Block
: BlockList
) {
423 for (auto SI
= succ_begin(Block
); SI
!= succ_end(Block
); ++SI
) {
424 if (!is_contained(BlockList
, *SI
)) {
427 return OptimizationRemarkMissed(DEBUG_TYPE
, "MultiExitRegion",
429 << "Region dominated by "
430 << ore::NV("Block", BlockList
.front()->getName())
431 << " has more than one region exit edge.";
442 auto BBProfileCount
= [BFI
](BasicBlock
*BB
) {
443 return BFI
->getBlockProfileCount(BB
)
444 ? BFI
->getBlockProfileCount(BB
).getValue()
448 // Use the same computeBBInlineCost function to compute the cost savings of
449 // the outlining the candidate region.
450 int OverallFunctionCost
= 0;
452 OverallFunctionCost
+= computeBBInlineCost(&BB
);
455 if (TracePartialInlining
)
456 dbgs() << "OverallFunctionCost = " << OverallFunctionCost
<< "\n";
458 int MinOutlineRegionCost
=
459 static_cast<int>(OverallFunctionCost
* MinRegionSizeRatio
);
460 BranchProbability
MinBranchProbability(
461 static_cast<int>(ColdBranchRatio
* MinBlockCounterExecution
),
462 MinBlockCounterExecution
);
463 bool ColdCandidateFound
= false;
464 BasicBlock
*CurrEntry
= EntryBlock
;
465 std::vector
<BasicBlock
*> DFS
;
466 DenseMap
<BasicBlock
*, bool> VisitedMap
;
467 DFS
.push_back(CurrEntry
);
468 VisitedMap
[CurrEntry
] = true;
469 // Use Depth First Search on the basic blocks to find CFG edges that are
471 // Cold regions considered must also have its inline cost compared to the
472 // overall inline cost of the original function. The region is outlined only
473 // if it reduced the inline cost of the function by 'MinOutlineRegionCost' or
475 while (!DFS
.empty()) {
476 auto *thisBB
= DFS
.back();
478 // Only consider regions with predecessor blocks that are considered
479 // not-cold (default: part of the top 99.99% of all block counters)
480 // AND greater than our minimum block execution count (default: 100).
481 if (PSI
->isColdBlock(thisBB
, BFI
) ||
482 BBProfileCount(thisBB
) < MinBlockCounterExecution
)
484 for (auto SI
= succ_begin(thisBB
); SI
!= succ_end(thisBB
); ++SI
) {
487 VisitedMap
[*SI
] = true;
489 // If branch isn't cold, we skip to the next one.
490 BranchProbability SuccProb
= BPI
.getEdgeProbability(thisBB
, *SI
);
491 if (SuccProb
> MinBranchProbability
)
494 if (TracePartialInlining
) {
495 dbgs() << "Found cold edge: " << thisBB
->getName() << "->"
496 << (*SI
)->getName() << "\nBranch Probability = " << SuccProb
500 SmallVector
<BasicBlock
*, 8> DominateVector
;
501 DT
.getDescendants(*SI
, DominateVector
);
502 // We can only outline single entry regions (for now).
503 if (!IsSingleEntry(DominateVector
))
505 BasicBlock
*ExitBlock
= nullptr;
506 // We can only outline single exit regions (for now).
507 if (!(ExitBlock
= IsSingleExit(DominateVector
)))
509 int OutlineRegionCost
= 0;
510 for (auto *BB
: DominateVector
)
511 OutlineRegionCost
+= computeBBInlineCost(BB
);
514 if (TracePartialInlining
)
515 dbgs() << "OutlineRegionCost = " << OutlineRegionCost
<< "\n";
518 if (OutlineRegionCost
< MinOutlineRegionCost
) {
520 return OptimizationRemarkAnalysis(DEBUG_TYPE
, "TooCostly",
522 << ore::NV("Callee", F
) << " inline cost-savings smaller than "
523 << ore::NV("Cost", MinOutlineRegionCost
);
527 // For now, ignore blocks that belong to a SISE region that is a
528 // candidate for outlining. In the future, we may want to look
529 // at inner regions because the outer region may have live-exit
531 for (auto *BB
: DominateVector
)
532 VisitedMap
[BB
] = true;
533 // ReturnBlock here means the block after the outline call
534 BasicBlock
*ReturnBlock
= ExitBlock
->getSingleSuccessor();
535 // assert(ReturnBlock && "ReturnBlock is NULL somehow!");
536 FunctionOutliningMultiRegionInfo::OutlineRegionInfo
RegInfo(
537 DominateVector
, DominateVector
.front(), ExitBlock
, ReturnBlock
);
538 OutliningInfo
->ORI
.push_back(RegInfo
);
540 if (TracePartialInlining
) {
541 dbgs() << "Found Cold Candidate starting at block: "
542 << DominateVector
.front()->getName() << "\n";
545 ColdCandidateFound
= true;
546 NumColdRegionsFound
++;
549 if (ColdCandidateFound
)
550 return OutliningInfo
;
552 return std::unique_ptr
<FunctionOutliningMultiRegionInfo
>();
555 std::unique_ptr
<FunctionOutliningInfo
>
556 PartialInlinerImpl::computeOutliningInfo(Function
*F
) {
557 BasicBlock
*EntryBlock
= &F
->front();
558 BranchInst
*BR
= dyn_cast
<BranchInst
>(EntryBlock
->getTerminator());
559 if (!BR
|| BR
->isUnconditional())
560 return std::unique_ptr
<FunctionOutliningInfo
>();
562 // Returns true if Succ is BB's successor
563 auto IsSuccessor
= [](BasicBlock
*Succ
, BasicBlock
*BB
) {
564 return is_contained(successors(BB
), Succ
);
567 auto IsReturnBlock
= [](BasicBlock
*BB
) {
568 Instruction
*TI
= BB
->getTerminator();
569 return isa
<ReturnInst
>(TI
);
572 auto GetReturnBlock
= [&](BasicBlock
*Succ1
, BasicBlock
*Succ2
) {
573 if (IsReturnBlock(Succ1
))
574 return std::make_tuple(Succ1
, Succ2
);
575 if (IsReturnBlock(Succ2
))
576 return std::make_tuple(Succ2
, Succ1
);
578 return std::make_tuple
<BasicBlock
*, BasicBlock
*>(nullptr, nullptr);
581 // Detect a triangular shape:
582 auto GetCommonSucc
= [&](BasicBlock
*Succ1
, BasicBlock
*Succ2
) {
583 if (IsSuccessor(Succ1
, Succ2
))
584 return std::make_tuple(Succ1
, Succ2
);
585 if (IsSuccessor(Succ2
, Succ1
))
586 return std::make_tuple(Succ2
, Succ1
);
588 return std::make_tuple
<BasicBlock
*, BasicBlock
*>(nullptr, nullptr);
591 std::unique_ptr
<FunctionOutliningInfo
> OutliningInfo
=
592 llvm::make_unique
<FunctionOutliningInfo
>();
594 BasicBlock
*CurrEntry
= EntryBlock
;
595 bool CandidateFound
= false;
597 // The number of blocks to be inlined has already reached
598 // the limit. When MaxNumInlineBlocks is set to 0 or 1, this
599 // disables partial inlining for the function.
600 if (OutliningInfo
->GetNumInlinedBlocks() >= MaxNumInlineBlocks
)
603 if (succ_size(CurrEntry
) != 2)
606 BasicBlock
*Succ1
= *succ_begin(CurrEntry
);
607 BasicBlock
*Succ2
= *(succ_begin(CurrEntry
) + 1);
609 BasicBlock
*ReturnBlock
, *NonReturnBlock
;
610 std::tie(ReturnBlock
, NonReturnBlock
) = GetReturnBlock(Succ1
, Succ2
);
613 OutliningInfo
->Entries
.push_back(CurrEntry
);
614 OutliningInfo
->ReturnBlock
= ReturnBlock
;
615 OutliningInfo
->NonReturnBlock
= NonReturnBlock
;
616 CandidateFound
= true;
620 BasicBlock
*CommSucc
;
621 BasicBlock
*OtherSucc
;
622 std::tie(CommSucc
, OtherSucc
) = GetCommonSucc(Succ1
, Succ2
);
627 OutliningInfo
->Entries
.push_back(CurrEntry
);
628 CurrEntry
= OtherSucc
;
632 return std::unique_ptr
<FunctionOutliningInfo
>();
634 // Do sanity check of the entries: threre should not
635 // be any successors (not in the entry set) other than
636 // {ReturnBlock, NonReturnBlock}
637 assert(OutliningInfo
->Entries
[0] == &F
->front() &&
638 "Function Entry must be the first in Entries vector");
639 DenseSet
<BasicBlock
*> Entries
;
640 for (BasicBlock
*E
: OutliningInfo
->Entries
)
643 // Returns true of BB has Predecessor which is not
645 auto HasNonEntryPred
= [Entries
](BasicBlock
*BB
) {
646 for (auto Pred
: predecessors(BB
)) {
647 if (!Entries
.count(Pred
))
652 auto CheckAndNormalizeCandidate
=
653 [Entries
, HasNonEntryPred
](FunctionOutliningInfo
*OutliningInfo
) {
654 for (BasicBlock
*E
: OutliningInfo
->Entries
) {
655 for (auto Succ
: successors(E
)) {
656 if (Entries
.count(Succ
))
658 if (Succ
== OutliningInfo
->ReturnBlock
)
659 OutliningInfo
->ReturnBlockPreds
.push_back(E
);
660 else if (Succ
!= OutliningInfo
->NonReturnBlock
)
663 // There should not be any outside incoming edges either:
664 if (HasNonEntryPred(E
))
670 if (!CheckAndNormalizeCandidate(OutliningInfo
.get()))
671 return std::unique_ptr
<FunctionOutliningInfo
>();
673 // Now further growing the candidate's inlining region by
674 // peeling off dominating blocks from the outlining region:
675 while (OutliningInfo
->GetNumInlinedBlocks() < MaxNumInlineBlocks
) {
676 BasicBlock
*Cand
= OutliningInfo
->NonReturnBlock
;
677 if (succ_size(Cand
) != 2)
680 if (HasNonEntryPred(Cand
))
683 BasicBlock
*Succ1
= *succ_begin(Cand
);
684 BasicBlock
*Succ2
= *(succ_begin(Cand
) + 1);
686 BasicBlock
*ReturnBlock
, *NonReturnBlock
;
687 std::tie(ReturnBlock
, NonReturnBlock
) = GetReturnBlock(Succ1
, Succ2
);
688 if (!ReturnBlock
|| ReturnBlock
!= OutliningInfo
->ReturnBlock
)
691 if (NonReturnBlock
->getSinglePredecessor() != Cand
)
694 // Now grow and update OutlininigInfo:
695 OutliningInfo
->Entries
.push_back(Cand
);
696 OutliningInfo
->NonReturnBlock
= NonReturnBlock
;
697 OutliningInfo
->ReturnBlockPreds
.push_back(Cand
);
698 Entries
.insert(Cand
);
701 return OutliningInfo
;
704 // Check if there is PGO data or user annoated branch data:
705 static bool hasProfileData(Function
*F
, FunctionOutliningInfo
*OI
) {
706 if (F
->hasProfileData())
708 // Now check if any of the entry block has MD_prof data:
709 for (auto *E
: OI
->Entries
) {
710 BranchInst
*BR
= dyn_cast
<BranchInst
>(E
->getTerminator());
711 if (!BR
|| BR
->isUnconditional())
714 if (BR
->extractProfMetadata(T
, F
))
721 PartialInlinerImpl::getOutliningCallBBRelativeFreq(FunctionCloner
&Cloner
) {
722 BasicBlock
*OutliningCallBB
= Cloner
.OutlinedFunctions
.back().second
;
724 Cloner
.ClonedFuncBFI
->getBlockFreq(&Cloner
.ClonedFunc
->getEntryBlock());
725 auto OutliningCallFreq
=
726 Cloner
.ClonedFuncBFI
->getBlockFreq(OutliningCallBB
);
727 // FIXME Hackery needed because ClonedFuncBFI is based on the function BEFORE
728 // we outlined any regions, so we may encounter situations where the
729 // OutliningCallFreq is *slightly* bigger than the EntryFreq.
730 if (OutliningCallFreq
.getFrequency() > EntryFreq
.getFrequency()) {
731 OutliningCallFreq
= EntryFreq
;
733 auto OutlineRegionRelFreq
= BranchProbability::getBranchProbability(
734 OutliningCallFreq
.getFrequency(), EntryFreq
.getFrequency());
736 if (hasProfileData(Cloner
.OrigFunc
, Cloner
.ClonedOI
.get()))
737 return OutlineRegionRelFreq
;
739 // When profile data is not available, we need to be conservative in
740 // estimating the overall savings. Static branch prediction can usually
741 // guess the branch direction right (taken/non-taken), but the guessed
742 // branch probability is usually not biased enough. In case when the
743 // outlined region is predicted to be likely, its probability needs
744 // to be made higher (more biased) to not under-estimate the cost of
745 // function outlining. On the other hand, if the outlined region
746 // is predicted to be less likely, the predicted probablity is usually
747 // higher than the actual. For instance, the actual probability of the
748 // less likely target is only 5%, but the guessed probablity can be
749 // 40%. In the latter case, there is no need for further adjustement.
750 // FIXME: add an option for this.
751 if (OutlineRegionRelFreq
< BranchProbability(45, 100))
752 return OutlineRegionRelFreq
;
754 OutlineRegionRelFreq
= std::max(
755 OutlineRegionRelFreq
, BranchProbability(OutlineRegionFreqPercent
, 100));
757 return OutlineRegionRelFreq
;
760 bool PartialInlinerImpl::shouldPartialInline(
761 CallSite CS
, FunctionCloner
&Cloner
,
762 BlockFrequency WeightedOutliningRcost
,
763 OptimizationRemarkEmitter
&ORE
) {
766 Instruction
*Call
= CS
.getInstruction();
767 Function
*Callee
= CS
.getCalledFunction();
768 assert(Callee
== Cloner
.ClonedFunc
);
770 if (SkipCostAnalysis
)
771 return isInlineViable(*Callee
);
773 Function
*Caller
= CS
.getCaller();
774 auto &CalleeTTI
= (*GetTTI
)(*Callee
);
775 InlineCost IC
= getInlineCost(CS
, getInlineParams(), CalleeTTI
,
776 *GetAssumptionCache
, GetBFI
, PSI
, &ORE
);
780 return OptimizationRemarkAnalysis(DEBUG_TYPE
, "AlwaysInline", Call
)
781 << NV("Callee", Cloner
.OrigFunc
)
782 << " should always be fully inlined, not partially";
789 return OptimizationRemarkMissed(DEBUG_TYPE
, "NeverInline", Call
)
790 << NV("Callee", Cloner
.OrigFunc
) << " not partially inlined into "
791 << NV("Caller", Caller
)
792 << " because it should never be inlined (cost=never)";
799 return OptimizationRemarkAnalysis(DEBUG_TYPE
, "TooCostly", Call
)
800 << NV("Callee", Cloner
.OrigFunc
) << " not partially inlined into "
801 << NV("Caller", Caller
) << " because too costly to inline (cost="
802 << NV("Cost", IC
.getCost()) << ", threshold="
803 << NV("Threshold", IC
.getCostDelta() + IC
.getCost()) << ")";
807 const DataLayout
&DL
= Caller
->getParent()->getDataLayout();
809 // The savings of eliminating the call:
810 int NonWeightedSavings
= getCallsiteCost(CS
, DL
);
811 BlockFrequency
NormWeightedSavings(NonWeightedSavings
);
813 // Weighted saving is smaller than weighted cost, return false
814 if (NormWeightedSavings
< WeightedOutliningRcost
) {
816 return OptimizationRemarkAnalysis(DEBUG_TYPE
, "OutliningCallcostTooHigh",
818 << NV("Callee", Cloner
.OrigFunc
) << " not partially inlined into "
819 << NV("Caller", Caller
) << " runtime overhead (overhead="
820 << NV("Overhead", (unsigned)WeightedOutliningRcost
.getFrequency())
822 << NV("Savings", (unsigned)NormWeightedSavings
.getFrequency())
824 << " of making the outlined call is too high";
831 return OptimizationRemarkAnalysis(DEBUG_TYPE
, "CanBePartiallyInlined", Call
)
832 << NV("Callee", Cloner
.OrigFunc
) << " can be partially inlined into "
833 << NV("Caller", Caller
) << " with cost=" << NV("Cost", IC
.getCost())
835 << NV("Threshold", IC
.getCostDelta() + IC
.getCost()) << ")";
840 // TODO: Ideally we should share Inliner's InlineCost Analysis code.
841 // For now use a simplified version. The returned 'InlineCost' will be used
842 // to esimate the size cost as well as runtime cost of the BB.
843 int PartialInlinerImpl::computeBBInlineCost(BasicBlock
*BB
) {
845 const DataLayout
&DL
= BB
->getParent()->getParent()->getDataLayout();
846 for (Instruction
&I
: BB
->instructionsWithoutDebug()) {
847 // Skip free instructions.
848 switch (I
.getOpcode()) {
849 case Instruction::BitCast
:
850 case Instruction::PtrToInt
:
851 case Instruction::IntToPtr
:
852 case Instruction::Alloca
:
853 case Instruction::PHI
:
855 case Instruction::GetElementPtr
:
856 if (cast
<GetElementPtrInst
>(&I
)->hasAllZeroIndices())
863 if (I
.isLifetimeStartOrEnd())
866 if (CallInst
*CI
= dyn_cast
<CallInst
>(&I
)) {
867 InlineCost
+= getCallsiteCost(CallSite(CI
), DL
);
871 if (InvokeInst
*II
= dyn_cast
<InvokeInst
>(&I
)) {
872 InlineCost
+= getCallsiteCost(CallSite(II
), DL
);
876 if (SwitchInst
*SI
= dyn_cast
<SwitchInst
>(&I
)) {
877 InlineCost
+= (SI
->getNumCases() + 1) * InlineConstants::InstrCost
;
880 InlineCost
+= InlineConstants::InstrCost
;
886 PartialInlinerImpl::computeOutliningCosts(FunctionCloner
&Cloner
) {
887 int OutliningFuncCallCost
= 0, OutlinedFunctionCost
= 0;
888 for (auto FuncBBPair
: Cloner
.OutlinedFunctions
) {
889 Function
*OutlinedFunc
= FuncBBPair
.first
;
890 BasicBlock
* OutliningCallBB
= FuncBBPair
.second
;
891 // Now compute the cost of the call sequence to the outlined function
892 // 'OutlinedFunction' in BB 'OutliningCallBB':
893 OutliningFuncCallCost
+= computeBBInlineCost(OutliningCallBB
);
895 // Now compute the cost of the extracted/outlined function itself:
896 for (BasicBlock
&BB
: *OutlinedFunc
)
897 OutlinedFunctionCost
+= computeBBInlineCost(&BB
);
899 assert(OutlinedFunctionCost
>= Cloner
.OutlinedRegionCost
&&
900 "Outlined function cost should be no less than the outlined region");
902 // The code extractor introduces a new root and exit stub blocks with
903 // additional unconditional branches. Those branches will be eliminated
904 // later with bb layout. The cost should be adjusted accordingly:
905 OutlinedFunctionCost
-=
906 2 * InlineConstants::InstrCost
* Cloner
.OutlinedFunctions
.size();
908 int OutliningRuntimeOverhead
=
909 OutliningFuncCallCost
+
910 (OutlinedFunctionCost
- Cloner
.OutlinedRegionCost
) +
911 ExtraOutliningPenalty
;
913 return std::make_tuple(OutliningFuncCallCost
, OutliningRuntimeOverhead
);
916 // Create the callsite to profile count map which is
917 // used to update the original function's entry count,
918 // after the function is partially inlined into the callsite.
919 void PartialInlinerImpl::computeCallsiteToProfCountMap(
920 Function
*DuplicateFunction
,
921 DenseMap
<User
*, uint64_t> &CallSiteToProfCountMap
) {
922 std::vector
<User
*> Users(DuplicateFunction
->user_begin(),
923 DuplicateFunction
->user_end());
924 Function
*CurrentCaller
= nullptr;
925 std::unique_ptr
<BlockFrequencyInfo
> TempBFI
;
926 BlockFrequencyInfo
*CurrentCallerBFI
= nullptr;
928 auto ComputeCurrBFI
= [&,this](Function
*Caller
) {
929 // For the old pass manager:
931 DominatorTree
DT(*Caller
);
933 BranchProbabilityInfo
BPI(*Caller
, LI
);
934 TempBFI
.reset(new BlockFrequencyInfo(*Caller
, BPI
, LI
));
935 CurrentCallerBFI
= TempBFI
.get();
938 CurrentCallerBFI
= &(*GetBFI
)(*Caller
);
942 for (User
*User
: Users
) {
943 CallSite CS
= getCallSite(User
);
944 Function
*Caller
= CS
.getCaller();
945 if (CurrentCaller
!= Caller
) {
946 CurrentCaller
= Caller
;
947 ComputeCurrBFI(Caller
);
949 assert(CurrentCallerBFI
&& "CallerBFI is not set");
951 BasicBlock
*CallBB
= CS
.getInstruction()->getParent();
952 auto Count
= CurrentCallerBFI
->getBlockProfileCount(CallBB
);
954 CallSiteToProfCountMap
[User
] = *Count
;
956 CallSiteToProfCountMap
[User
] = 0;
960 PartialInlinerImpl::FunctionCloner::FunctionCloner(
961 Function
*F
, FunctionOutliningInfo
*OI
, OptimizationRemarkEmitter
&ORE
,
962 function_ref
<AssumptionCache
*(Function
&)> LookupAC
)
963 : OrigFunc(F
), ORE(ORE
), LookupAC(LookupAC
) {
964 ClonedOI
= llvm::make_unique
<FunctionOutliningInfo
>();
966 // Clone the function, so that we can hack away on it.
967 ValueToValueMapTy VMap
;
968 ClonedFunc
= CloneFunction(F
, VMap
);
970 ClonedOI
->ReturnBlock
= cast
<BasicBlock
>(VMap
[OI
->ReturnBlock
]);
971 ClonedOI
->NonReturnBlock
= cast
<BasicBlock
>(VMap
[OI
->NonReturnBlock
]);
972 for (BasicBlock
*BB
: OI
->Entries
) {
973 ClonedOI
->Entries
.push_back(cast
<BasicBlock
>(VMap
[BB
]));
975 for (BasicBlock
*E
: OI
->ReturnBlockPreds
) {
976 BasicBlock
*NewE
= cast
<BasicBlock
>(VMap
[E
]);
977 ClonedOI
->ReturnBlockPreds
.push_back(NewE
);
979 // Go ahead and update all uses to the duplicate, so that we can just
980 // use the inliner functionality when we're done hacking.
981 F
->replaceAllUsesWith(ClonedFunc
);
984 PartialInlinerImpl::FunctionCloner::FunctionCloner(
985 Function
*F
, FunctionOutliningMultiRegionInfo
*OI
,
986 OptimizationRemarkEmitter
&ORE
,
987 function_ref
<AssumptionCache
*(Function
&)> LookupAC
)
988 : OrigFunc(F
), ORE(ORE
), LookupAC(LookupAC
) {
989 ClonedOMRI
= llvm::make_unique
<FunctionOutliningMultiRegionInfo
>();
991 // Clone the function, so that we can hack away on it.
992 ValueToValueMapTy VMap
;
993 ClonedFunc
= CloneFunction(F
, VMap
);
995 // Go through all Outline Candidate Regions and update all BasicBlock
997 for (FunctionOutliningMultiRegionInfo::OutlineRegionInfo RegionInfo
:
999 SmallVector
<BasicBlock
*, 8> Region
;
1000 for (BasicBlock
*BB
: RegionInfo
.Region
) {
1001 Region
.push_back(cast
<BasicBlock
>(VMap
[BB
]));
1003 BasicBlock
*NewEntryBlock
= cast
<BasicBlock
>(VMap
[RegionInfo
.EntryBlock
]);
1004 BasicBlock
*NewExitBlock
= cast
<BasicBlock
>(VMap
[RegionInfo
.ExitBlock
]);
1005 BasicBlock
*NewReturnBlock
= nullptr;
1006 if (RegionInfo
.ReturnBlock
)
1007 NewReturnBlock
= cast
<BasicBlock
>(VMap
[RegionInfo
.ReturnBlock
]);
1008 FunctionOutliningMultiRegionInfo::OutlineRegionInfo
MappedRegionInfo(
1009 Region
, NewEntryBlock
, NewExitBlock
, NewReturnBlock
);
1010 ClonedOMRI
->ORI
.push_back(MappedRegionInfo
);
1012 // Go ahead and update all uses to the duplicate, so that we can just
1013 // use the inliner functionality when we're done hacking.
1014 F
->replaceAllUsesWith(ClonedFunc
);
1017 void PartialInlinerImpl::FunctionCloner::NormalizeReturnBlock() {
1018 auto getFirstPHI
= [](BasicBlock
*BB
) {
1019 BasicBlock::iterator I
= BB
->begin();
1020 PHINode
*FirstPhi
= nullptr;
1021 while (I
!= BB
->end()) {
1022 PHINode
*Phi
= dyn_cast
<PHINode
>(I
);
1033 // Shouldn't need to normalize PHIs if we're not outlining non-early return
1038 // Special hackery is needed with PHI nodes that have inputs from more than
1039 // one extracted block. For simplicity, just split the PHIs into a two-level
1040 // sequence of PHIs, some of which will go in the extracted region, and some
1041 // of which will go outside.
1042 BasicBlock
*PreReturn
= ClonedOI
->ReturnBlock
;
1043 // only split block when necessary:
1044 PHINode
*FirstPhi
= getFirstPHI(PreReturn
);
1045 unsigned NumPredsFromEntries
= ClonedOI
->ReturnBlockPreds
.size();
1047 if (!FirstPhi
|| FirstPhi
->getNumIncomingValues() <= NumPredsFromEntries
+ 1)
1050 auto IsTrivialPhi
= [](PHINode
*PN
) -> Value
* {
1051 Value
*CommonValue
= PN
->getIncomingValue(0);
1052 if (all_of(PN
->incoming_values(),
1053 [&](Value
*V
) { return V
== CommonValue
; }))
1058 ClonedOI
->ReturnBlock
= ClonedOI
->ReturnBlock
->splitBasicBlock(
1059 ClonedOI
->ReturnBlock
->getFirstNonPHI()->getIterator());
1060 BasicBlock::iterator I
= PreReturn
->begin();
1061 Instruction
*Ins
= &ClonedOI
->ReturnBlock
->front();
1062 SmallVector
<Instruction
*, 4> DeadPhis
;
1063 while (I
!= PreReturn
->end()) {
1064 PHINode
*OldPhi
= dyn_cast
<PHINode
>(I
);
1069 PHINode::Create(OldPhi
->getType(), NumPredsFromEntries
+ 1, "", Ins
);
1070 OldPhi
->replaceAllUsesWith(RetPhi
);
1071 Ins
= ClonedOI
->ReturnBlock
->getFirstNonPHI();
1073 RetPhi
->addIncoming(&*I
, PreReturn
);
1074 for (BasicBlock
*E
: ClonedOI
->ReturnBlockPreds
) {
1075 RetPhi
->addIncoming(OldPhi
->getIncomingValueForBlock(E
), E
);
1076 OldPhi
->removeIncomingValue(E
);
1079 // After incoming values splitting, the old phi may become trivial.
1080 // Keeping the trivial phi can introduce definition inside the outline
1081 // region which is live-out, causing necessary overhead (load, store
1082 // arg passing etc).
1083 if (auto *OldPhiVal
= IsTrivialPhi(OldPhi
)) {
1084 OldPhi
->replaceAllUsesWith(OldPhiVal
);
1085 DeadPhis
.push_back(OldPhi
);
1089 for (auto *DP
: DeadPhis
)
1090 DP
->eraseFromParent();
1092 for (auto E
: ClonedOI
->ReturnBlockPreds
) {
1093 E
->getTerminator()->replaceUsesOfWith(PreReturn
, ClonedOI
->ReturnBlock
);
1097 bool PartialInlinerImpl::FunctionCloner::doMultiRegionFunctionOutlining() {
1099 auto ComputeRegionCost
= [](SmallVectorImpl
<BasicBlock
*> &Region
) {
1101 for (BasicBlock
* BB
: Region
)
1102 Cost
+= computeBBInlineCost(BB
);
1106 assert(ClonedOMRI
&& "Expecting OutlineInfo for multi region outline");
1108 if (ClonedOMRI
->ORI
.empty())
1111 // The CodeExtractor needs a dominator tree.
1113 DT
.recalculate(*ClonedFunc
);
1115 // Manually calculate a BlockFrequencyInfo and BranchProbabilityInfo.
1117 BranchProbabilityInfo
BPI(*ClonedFunc
, LI
);
1118 ClonedFuncBFI
.reset(new BlockFrequencyInfo(*ClonedFunc
, BPI
, LI
));
1120 SetVector
<Value
*> Inputs
, Outputs
, Sinks
;
1121 for (FunctionOutliningMultiRegionInfo::OutlineRegionInfo RegionInfo
:
1123 int CurrentOutlinedRegionCost
= ComputeRegionCost(RegionInfo
.Region
);
1125 CodeExtractor
CE(RegionInfo
.Region
, &DT
, /*AggregateArgs*/ false,
1126 ClonedFuncBFI
.get(), &BPI
,
1127 LookupAC(*RegionInfo
.EntryBlock
->getParent()),
1128 /* AllowVarargs */ false);
1130 CE
.findInputsOutputs(Inputs
, Outputs
, Sinks
);
1133 if (TracePartialInlining
) {
1134 dbgs() << "inputs: " << Inputs
.size() << "\n";
1135 dbgs() << "outputs: " << Outputs
.size() << "\n";
1136 for (Value
*value
: Inputs
)
1137 dbgs() << "value used in func: " << *value
<< "\n";
1138 for (Value
*output
: Outputs
)
1139 dbgs() << "instr used in func: " << *output
<< "\n";
1142 // Do not extract regions that have live exit variables.
1143 if (Outputs
.size() > 0 && !ForceLiveExit
)
1146 Function
*OutlinedFunc
= CE
.extractCodeRegion();
1149 CallSite OCS
= PartialInlinerImpl::getOneCallSiteTo(OutlinedFunc
);
1150 BasicBlock
*OutliningCallBB
= OCS
.getInstruction()->getParent();
1151 assert(OutliningCallBB
->getParent() == ClonedFunc
);
1152 OutlinedFunctions
.push_back(std::make_pair(OutlinedFunc
,OutliningCallBB
));
1153 NumColdRegionsOutlined
++;
1154 OutlinedRegionCost
+= CurrentOutlinedRegionCost
;
1156 if (MarkOutlinedColdCC
) {
1157 OutlinedFunc
->setCallingConv(CallingConv::Cold
);
1158 OCS
.setCallingConv(CallingConv::Cold
);
1162 return OptimizationRemarkMissed(DEBUG_TYPE
, "ExtractFailed",
1163 &RegionInfo
.Region
.front()->front())
1164 << "Failed to extract region at block "
1165 << ore::NV("Block", RegionInfo
.Region
.front());
1169 return !OutlinedFunctions
.empty();
1173 PartialInlinerImpl::FunctionCloner::doSingleRegionFunctionOutlining() {
1174 // Returns true if the block is to be partial inlined into the caller
1175 // (i.e. not to be extracted to the out of line function)
1176 auto ToBeInlined
= [&, this](BasicBlock
*BB
) {
1177 return BB
== ClonedOI
->ReturnBlock
||
1178 (std::find(ClonedOI
->Entries
.begin(), ClonedOI
->Entries
.end(), BB
) !=
1179 ClonedOI
->Entries
.end());
1182 assert(ClonedOI
&& "Expecting OutlineInfo for single region outline");
1183 // The CodeExtractor needs a dominator tree.
1185 DT
.recalculate(*ClonedFunc
);
1187 // Manually calculate a BlockFrequencyInfo and BranchProbabilityInfo.
1189 BranchProbabilityInfo
BPI(*ClonedFunc
, LI
);
1190 ClonedFuncBFI
.reset(new BlockFrequencyInfo(*ClonedFunc
, BPI
, LI
));
1192 // Gather up the blocks that we're going to extract.
1193 std::vector
<BasicBlock
*> ToExtract
;
1194 ToExtract
.push_back(ClonedOI
->NonReturnBlock
);
1195 OutlinedRegionCost
+=
1196 PartialInlinerImpl::computeBBInlineCost(ClonedOI
->NonReturnBlock
);
1197 for (BasicBlock
&BB
: *ClonedFunc
)
1198 if (!ToBeInlined(&BB
) && &BB
!= ClonedOI
->NonReturnBlock
) {
1199 ToExtract
.push_back(&BB
);
1200 // FIXME: the code extractor may hoist/sink more code
1201 // into the outlined function which may make the outlining
1202 // overhead (the difference of the outlined function cost
1203 // and OutliningRegionCost) look larger.
1204 OutlinedRegionCost
+= computeBBInlineCost(&BB
);
1207 // Extract the body of the if.
1208 Function
*OutlinedFunc
=
1209 CodeExtractor(ToExtract
, &DT
, /*AggregateArgs*/ false,
1210 ClonedFuncBFI
.get(), &BPI
, LookupAC(*ClonedFunc
),
1211 /* AllowVarargs */ true)
1212 .extractCodeRegion();
1215 BasicBlock
*OutliningCallBB
=
1216 PartialInlinerImpl::getOneCallSiteTo(OutlinedFunc
)
1219 assert(OutliningCallBB
->getParent() == ClonedFunc
);
1220 OutlinedFunctions
.push_back(std::make_pair(OutlinedFunc
, OutliningCallBB
));
1223 return OptimizationRemarkMissed(DEBUG_TYPE
, "ExtractFailed",
1224 &ToExtract
.front()->front())
1225 << "Failed to extract region at block "
1226 << ore::NV("Block", ToExtract
.front());
1229 return OutlinedFunc
;
1232 PartialInlinerImpl::FunctionCloner::~FunctionCloner() {
1233 // Ditch the duplicate, since we're done with it, and rewrite all remaining
1234 // users (function pointers, etc.) back to the original function.
1235 ClonedFunc
->replaceAllUsesWith(OrigFunc
);
1236 ClonedFunc
->eraseFromParent();
1237 if (!IsFunctionInlined
) {
1238 // Remove each function that was speculatively created if there is no
1240 for (auto FuncBBPair
: OutlinedFunctions
) {
1241 Function
*Func
= FuncBBPair
.first
;
1242 Func
->eraseFromParent();
1247 std::pair
<bool, Function
*> PartialInlinerImpl::unswitchFunction(Function
*F
) {
1249 if (F
->hasAddressTaken())
1250 return {false, nullptr};
1252 // Let inliner handle it
1253 if (F
->hasFnAttribute(Attribute::AlwaysInline
))
1254 return {false, nullptr};
1256 if (F
->hasFnAttribute(Attribute::NoInline
))
1257 return {false, nullptr};
1259 if (PSI
->isFunctionEntryCold(F
))
1260 return {false, nullptr};
1262 if (empty(F
->users()))
1263 return {false, nullptr};
1265 OptimizationRemarkEmitter
ORE(F
);
1267 // Only try to outline cold regions if we have a profile summary, which
1268 // implies we have profiling information.
1269 if (PSI
->hasProfileSummary() && F
->hasProfileData() &&
1270 !DisableMultiRegionPartialInline
) {
1271 std::unique_ptr
<FunctionOutliningMultiRegionInfo
> OMRI
=
1272 computeOutliningColdRegionsInfo(F
, ORE
);
1274 FunctionCloner
Cloner(F
, OMRI
.get(), ORE
, LookupAssumptionCache
);
1277 if (TracePartialInlining
) {
1278 dbgs() << "HotCountThreshold = " << PSI
->getHotCountThreshold() << "\n";
1279 dbgs() << "ColdCountThreshold = " << PSI
->getColdCountThreshold()
1283 bool DidOutline
= Cloner
.doMultiRegionFunctionOutlining();
1287 if (TracePartialInlining
) {
1288 dbgs() << ">>>>>> Outlined (Cloned) Function >>>>>>\n";
1289 Cloner
.ClonedFunc
->print(dbgs());
1290 dbgs() << "<<<<<< Outlined (Cloned) Function <<<<<<\n";
1294 if (tryPartialInline(Cloner
))
1295 return {true, nullptr};
1300 // Fall-thru to regular partial inlining if we:
1301 // i) can't find any cold regions to outline, or
1302 // ii) can't inline the outlined function anywhere.
1303 std::unique_ptr
<FunctionOutliningInfo
> OI
= computeOutliningInfo(F
);
1305 return {false, nullptr};
1307 FunctionCloner
Cloner(F
, OI
.get(), ORE
, LookupAssumptionCache
);
1308 Cloner
.NormalizeReturnBlock();
1310 Function
*OutlinedFunction
= Cloner
.doSingleRegionFunctionOutlining();
1312 if (!OutlinedFunction
)
1313 return {false, nullptr};
1315 bool AnyInline
= tryPartialInline(Cloner
);
1318 return {true, OutlinedFunction
};
1320 return {false, nullptr};
1323 bool PartialInlinerImpl::tryPartialInline(FunctionCloner
&Cloner
) {
1324 if (Cloner
.OutlinedFunctions
.empty())
1328 BlockFrequency WeightedRcost
;
1329 int NonWeightedRcost
;
1330 std::tie(SizeCost
, NonWeightedRcost
) = computeOutliningCosts(Cloner
);
1332 // Only calculate RelativeToEntryFreq when we are doing single region
1334 BranchProbability RelativeToEntryFreq
;
1335 if (Cloner
.ClonedOI
) {
1336 RelativeToEntryFreq
= getOutliningCallBBRelativeFreq(Cloner
);
1338 // RelativeToEntryFreq doesn't make sense when we have more than one
1339 // outlined call because each call will have a different relative frequency
1340 // to the entry block. We can consider using the average, but the
1341 // usefulness of that information is questionable. For now, assume we never
1342 // execute the calls to outlined functions.
1343 RelativeToEntryFreq
= BranchProbability(0, 1);
1345 WeightedRcost
= BlockFrequency(NonWeightedRcost
) * RelativeToEntryFreq
;
1347 // The call sequence(s) to the outlined function(s) are larger than the sum of
1348 // the original outlined region size(s), it does not increase the chances of
1349 // inlining the function with outlining (The inliner uses the size increase to
1350 // model the cost of inlining a callee).
1351 if (!SkipCostAnalysis
&& Cloner
.OutlinedRegionCost
< SizeCost
) {
1352 OptimizationRemarkEmitter
OrigFuncORE(Cloner
.OrigFunc
);
1355 std::tie(DLoc
, Block
) = getOneDebugLoc(Cloner
.ClonedFunc
);
1356 OrigFuncORE
.emit([&]() {
1357 return OptimizationRemarkAnalysis(DEBUG_TYPE
, "OutlineRegionTooSmall",
1359 << ore::NV("Function", Cloner
.OrigFunc
)
1360 << " not partially inlined into callers (Original Size = "
1361 << ore::NV("OutlinedRegionOriginalSize", Cloner
.OutlinedRegionCost
)
1362 << ", Size of call sequence to outlined function = "
1363 << ore::NV("NewSize", SizeCost
) << ")";
1368 assert(empty(Cloner
.OrigFunc
->users()) &&
1369 "F's users should all be replaced!");
1371 std::vector
<User
*> Users(Cloner
.ClonedFunc
->user_begin(),
1372 Cloner
.ClonedFunc
->user_end());
1374 DenseMap
<User
*, uint64_t> CallSiteToProfCountMap
;
1375 auto CalleeEntryCount
= Cloner
.OrigFunc
->getEntryCount();
1376 if (CalleeEntryCount
)
1377 computeCallsiteToProfCountMap(Cloner
.ClonedFunc
, CallSiteToProfCountMap
);
1379 uint64_t CalleeEntryCountV
=
1380 (CalleeEntryCount
? CalleeEntryCount
.getCount() : 0);
1382 bool AnyInline
= false;
1383 for (User
*User
: Users
) {
1384 CallSite CS
= getCallSite(User
);
1386 if (IsLimitReached())
1389 OptimizationRemarkEmitter
CallerORE(CS
.getCaller());
1390 if (!shouldPartialInline(CS
, Cloner
, WeightedRcost
, CallerORE
))
1393 // Construct remark before doing the inlining, as after successful inlining
1394 // the callsite is removed.
1395 OptimizationRemark
OR(DEBUG_TYPE
, "PartiallyInlined", CS
.getInstruction());
1396 OR
<< ore::NV("Callee", Cloner
.OrigFunc
) << " partially inlined into "
1397 << ore::NV("Caller", CS
.getCaller());
1399 InlineFunctionInfo
IFI(nullptr, GetAssumptionCache
, PSI
);
1400 // We can only forward varargs when we outlined a single region, else we
1401 // bail on vararg functions.
1402 if (!InlineFunction(CS
, IFI
, nullptr, true,
1403 (Cloner
.ClonedOI
? Cloner
.OutlinedFunctions
.back().first
1409 // Now update the entry count:
1410 if (CalleeEntryCountV
&& CallSiteToProfCountMap
.count(User
)) {
1411 uint64_t CallSiteCount
= CallSiteToProfCountMap
[User
];
1412 CalleeEntryCountV
-= std::min(CalleeEntryCountV
, CallSiteCount
);
1416 NumPartialInlining
++;
1418 if (Cloner
.ClonedOI
)
1419 NumPartialInlined
++;
1421 NumColdOutlinePartialInlined
++;
1426 Cloner
.IsFunctionInlined
= true;
1427 if (CalleeEntryCount
)
1428 Cloner
.OrigFunc
->setEntryCount(
1429 CalleeEntryCount
.setCount(CalleeEntryCountV
));
1430 OptimizationRemarkEmitter
OrigFuncORE(Cloner
.OrigFunc
);
1431 OrigFuncORE
.emit([&]() {
1432 return OptimizationRemark(DEBUG_TYPE
, "PartiallyInlined", Cloner
.OrigFunc
)
1433 << "Partially inlined into at least one caller";
1441 bool PartialInlinerImpl::run(Module
&M
) {
1442 if (DisablePartialInlining
)
1445 std::vector
<Function
*> Worklist
;
1446 Worklist
.reserve(M
.size());
1447 for (Function
&F
: M
)
1448 if (!F
.use_empty() && !F
.isDeclaration())
1449 Worklist
.push_back(&F
);
1451 bool Changed
= false;
1452 while (!Worklist
.empty()) {
1453 Function
*CurrFunc
= Worklist
.back();
1454 Worklist
.pop_back();
1456 if (CurrFunc
->use_empty())
1459 bool Recursive
= false;
1460 for (User
*U
: CurrFunc
->users())
1461 if (Instruction
*I
= dyn_cast
<Instruction
>(U
))
1462 if (I
->getParent()->getParent() == CurrFunc
) {
1469 std::pair
<bool, Function
* > Result
= unswitchFunction(CurrFunc
);
1471 Worklist
.push_back(Result
.second
);
1472 Changed
|= Result
.first
;
1478 char PartialInlinerLegacyPass::ID
= 0;
1480 INITIALIZE_PASS_BEGIN(PartialInlinerLegacyPass
, "partial-inliner",
1481 "Partial Inliner", false, false)
1482 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker
)
1483 INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass
)
1484 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass
)
1485 INITIALIZE_PASS_END(PartialInlinerLegacyPass
, "partial-inliner",
1486 "Partial Inliner", false, false)
1488 ModulePass
*llvm::createPartialInliningPass() {
1489 return new PartialInlinerLegacyPass();
1492 PreservedAnalyses
PartialInlinerPass::run(Module
&M
,
1493 ModuleAnalysisManager
&AM
) {
1494 auto &FAM
= AM
.getResult
<FunctionAnalysisManagerModuleProxy
>(M
).getManager();
1496 std::function
<AssumptionCache
&(Function
&)> GetAssumptionCache
=
1497 [&FAM
](Function
&F
) -> AssumptionCache
& {
1498 return FAM
.getResult
<AssumptionAnalysis
>(F
);
1501 auto LookupAssumptionCache
= [&FAM
](Function
&F
) -> AssumptionCache
* {
1502 return FAM
.getCachedResult
<AssumptionAnalysis
>(F
);
1505 std::function
<BlockFrequencyInfo
&(Function
&)> GetBFI
=
1506 [&FAM
](Function
&F
) -> BlockFrequencyInfo
& {
1507 return FAM
.getResult
<BlockFrequencyAnalysis
>(F
);
1510 std::function
<TargetTransformInfo
&(Function
&)> GetTTI
=
1511 [&FAM
](Function
&F
) -> TargetTransformInfo
& {
1512 return FAM
.getResult
<TargetIRAnalysis
>(F
);
1515 ProfileSummaryInfo
*PSI
= &AM
.getResult
<ProfileSummaryAnalysis
>(M
);
1517 if (PartialInlinerImpl(&GetAssumptionCache
, LookupAssumptionCache
, &GetTTI
,
1520 return PreservedAnalyses::none();
1521 return PreservedAnalyses::all();