1 //===- PartialInlining.cpp - Inline parts of functions --------------------===//
2 //
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
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This pass performs partial inlining, typically by inlining an if statement
10 // that surrounds the body of the function.
11 //
12 //===----------------------------------------------------------------------===//
13 
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/DebugLoc.h"
34 #include "llvm/IR/DiagnosticInfo.h"
35 #include "llvm/IR/Dominators.h"
36 #include "llvm/IR/Function.h"
37 #include "llvm/IR/InstrTypes.h"
38 #include "llvm/IR/Instruction.h"
39 #include "llvm/IR/Instructions.h"
40 #include "llvm/IR/IntrinsicInst.h"
41 #include "llvm/IR/Intrinsics.h"
42 #include "llvm/IR/Module.h"
43 #include "llvm/IR/User.h"
44 #include "llvm/InitializePasses.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"
55 #include <algorithm>
56 #include <cassert>
57 #include <cstdint>
58 #include <functional>
59 #include <iterator>
60 #include <memory>
61 #include <tuple>
62 #include <vector>
63 
64 using namespace llvm;
65 
66 #define DEBUG_TYPE "partial-inlining"
67 
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.");
77 
78 // Command line option to disable partial-inlining. The default is false:
79 static cl::opt<bool>
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
83 // false:
84 static cl::opt<bool> DisableMultiRegionPartialInline(
85     "disable-mr-partial-inlining", cl::init(false), cl::Hidden,
86     cl::desc("Disable multi-region partial inlining"));
87 
88 // Command line option to force outlining in regions with live exit variables.
89 // The default is false:
90 static cl::opt<bool>
91     ForceLiveExit("pi-force-live-exit-outline", cl::init(false), cl::Hidden,
92                cl::desc("Force outline regions with live exits"));
93 
94 // Command line option to enable marking outline functions with Cold Calling
95 // Convention. The default is false:
96 static cl::opt<bool>
97     MarkOutlinedColdCC("pi-mark-coldcc", cl::init(false), cl::Hidden,
98                        cl::desc("Mark outline function calls with ColdCC"));
99 
100 // This is an option used by testing:
101 static cl::opt<bool> SkipCostAnalysis("skip-partial-inlining-cost-analysis",
102                                       cl::init(false), cl::ZeroOrMore,
103                                       cl::ReallyHidden,
104                                       cl::desc("Skip Cost Analysis"));
105 // Used to determine if a cold region is worth outlining based on
106 // its inlining cost compared to the original function.  Default is set at 10%.
107 // ie. if the cold region reduces the inlining cost of the original function by
108 // at least 10%.
109 static cl::opt<float> MinRegionSizeRatio(
110     "min-region-size-ratio", cl::init(0.1), cl::Hidden,
111     cl::desc("Minimum ratio comparing relative sizes of each "
112              "outline candidate and original function"));
113 // Used to tune the minimum number of execution counts needed in the predecessor
114 // block to the cold edge. ie. confidence interval.
115 static cl::opt<unsigned>
116     MinBlockCounterExecution("min-block-execution", cl::init(100), cl::Hidden,
117                              cl::desc("Minimum block executions to consider "
118                                       "its BranchProbabilityInfo valid"));
119 // Used to determine when an edge is considered cold. Default is set to 10%. ie.
120 // if the branch probability is 10% or less, then it is deemed as 'cold'.
121 static cl::opt<float> ColdBranchRatio(
122     "cold-branch-ratio", cl::init(0.1), cl::Hidden,
123     cl::desc("Minimum BranchProbability to consider a region cold."));
124 
125 static cl::opt<unsigned> MaxNumInlineBlocks(
126     "max-num-inline-blocks", cl::init(5), cl::Hidden,
127     cl::desc("Max number of blocks to be partially inlined"));
128 
129 // Command line option to set the maximum number of partial inlining allowed
130 // for the module. The default value of -1 means no limit.
131 static cl::opt<int> MaxNumPartialInlining(
132     "max-partial-inlining", cl::init(-1), cl::Hidden, cl::ZeroOrMore,
133     cl::desc("Max number of partial inlining. The default is unlimited"));
134 
135 // Used only when PGO or user annotated branch data is absent. It is
136 // the least value that is used to weigh the outline region. If BFI
137 // produces larger value, the BFI value will be used.
138 static cl::opt<int>
139     OutlineRegionFreqPercent("outline-region-freq-percent", cl::init(75),
140                              cl::Hidden, cl::ZeroOrMore,
141                              cl::desc("Relative frequency of outline region to "
142                                       "the entry block"));
143 
144 static cl::opt<unsigned> ExtraOutliningPenalty(
145     "partial-inlining-extra-penalty", cl::init(0), cl::Hidden,
146     cl::desc("A debug option to add additional penalty to the computed one."));
147 
148 namespace {
149 
150 struct FunctionOutliningInfo {
151   FunctionOutliningInfo() = default;
152 
153   // Returns the number of blocks to be inlined including all blocks
154   // in Entries and one return block.
155   unsigned getNumInlinedBlocks() const { return Entries.size() + 1; }
156 
157   // A set of blocks including the function entry that guard
158   // the region to be outlined.
159   SmallVector<BasicBlock *, 4> Entries;
160 
161   // The return block that is not included in the outlined region.
162   BasicBlock *ReturnBlock = nullptr;
163 
164   // The dominating block of the region to be outlined.
165   BasicBlock *NonReturnBlock = nullptr;
166 
167   // The set of blocks in Entries that that are predecessors to ReturnBlock
168   SmallVector<BasicBlock *, 4> ReturnBlockPreds;
169 };
170 
171 struct FunctionOutliningMultiRegionInfo {
172   FunctionOutliningMultiRegionInfo()
173       : ORI() {}
174 
175   // Container for outline regions
176   struct OutlineRegionInfo {
177     OutlineRegionInfo(ArrayRef<BasicBlock *> Region,
178                       BasicBlock *EntryBlock, BasicBlock *ExitBlock,
179                       BasicBlock *ReturnBlock)
180         : Region(Region.begin(), Region.end()), EntryBlock(EntryBlock),
181           ExitBlock(ExitBlock), ReturnBlock(ReturnBlock) {}
182     SmallVector<BasicBlock *, 8> Region;
183     BasicBlock *EntryBlock;
184     BasicBlock *ExitBlock;
185     BasicBlock *ReturnBlock;
186   };
187 
188   SmallVector<OutlineRegionInfo, 4> ORI;
189 };
190 
191 struct PartialInlinerImpl {
192 
193   PartialInlinerImpl(
194       function_ref<AssumptionCache &(Function &)> GetAC,
195       function_ref<AssumptionCache *(Function &)> LookupAC,
196       function_ref<TargetTransformInfo &(Function &)> GTTI,
197       function_ref<const TargetLibraryInfo &(Function &)> GTLI,
198       ProfileSummaryInfo &ProfSI,
199       function_ref<BlockFrequencyInfo &(Function &)> GBFI = nullptr)
200       : GetAssumptionCache(GetAC), LookupAssumptionCache(LookupAC),
201         GetTTI(GTTI), GetBFI(GBFI), GetTLI(GTLI), PSI(ProfSI) {}
202 
203   bool run(Module &M);
204   // Main part of the transformation that calls helper functions to find
205   // outlining candidates, clone & outline the function, and attempt to
206   // partially inline the resulting function. Returns true if
207   // inlining was successful, false otherwise.  Also returns the outline
208   // function (only if we partially inlined early returns) as there is a
209   // possibility to further "peel" early return statements that were left in the
210   // outline function due to code size.
211   std::pair<bool, Function *> unswitchFunction(Function &F);
212 
213   // This class speculatively clones the function to be partial inlined.
214   // At the end of partial inlining, the remaining callsites to the cloned
215   // function that are not partially inlined will be fixed up to reference
216   // the original function, and the cloned function will be erased.
217   struct FunctionCloner {
218     // Two constructors, one for single region outlining, the other for
219     // multi-region outlining.
220     FunctionCloner(Function *F, FunctionOutliningInfo *OI,
221                    OptimizationRemarkEmitter &ORE,
222                    function_ref<AssumptionCache *(Function &)> LookupAC,
223                    function_ref<TargetTransformInfo &(Function &)> GetTTI);
224     FunctionCloner(Function *F, FunctionOutliningMultiRegionInfo *OMRI,
225                    OptimizationRemarkEmitter &ORE,
226                    function_ref<AssumptionCache *(Function &)> LookupAC,
227                    function_ref<TargetTransformInfo &(Function &)> GetTTI);
228 
229     ~FunctionCloner();
230 
231     // Prepare for function outlining: making sure there is only
232     // one incoming edge from the extracted/outlined region to
233     // the return block.
234     void normalizeReturnBlock() const;
235 
236     // Do function outlining for cold regions.
237     bool doMultiRegionFunctionOutlining();
238     // Do function outlining for region after early return block(s).
239     // NOTE: For vararg functions that do the vararg handling in the outlined
240     //       function, we temporarily generate IR that does not properly
241     //       forward varargs to the outlined function. Calling InlineFunction
242     //       will update calls to the outlined functions to properly forward
243     //       the varargs.
244     Function *doSingleRegionFunctionOutlining();
245 
246     Function *OrigFunc = nullptr;
247     Function *ClonedFunc = nullptr;
248 
249     typedef std::pair<Function *, BasicBlock *> FuncBodyCallerPair;
250     // Keep track of Outlined Functions and the basic block they're called from.
251     SmallVector<FuncBodyCallerPair, 4> OutlinedFunctions;
252 
253     // ClonedFunc is inlined in one of its callers after function
254     // outlining.
255     bool IsFunctionInlined = false;
256     // The cost of the region to be outlined.
257     int OutlinedRegionCost = 0;
258     // ClonedOI is specific to outlining non-early return blocks.
259     std::unique_ptr<FunctionOutliningInfo> ClonedOI = nullptr;
260     // ClonedOMRI is specific to outlining cold regions.
261     std::unique_ptr<FunctionOutliningMultiRegionInfo> ClonedOMRI = nullptr;
262     std::unique_ptr<BlockFrequencyInfo> ClonedFuncBFI = nullptr;
263     OptimizationRemarkEmitter &ORE;
264     function_ref<AssumptionCache *(Function &)> LookupAC;
265     function_ref<TargetTransformInfo &(Function &)> GetTTI;
266   };
267 
268 private:
269   int NumPartialInlining = 0;
270   function_ref<AssumptionCache &(Function &)> GetAssumptionCache;
271   function_ref<AssumptionCache *(Function &)> LookupAssumptionCache;
272   function_ref<TargetTransformInfo &(Function &)> GetTTI;
273   function_ref<BlockFrequencyInfo &(Function &)> GetBFI;
274   function_ref<const TargetLibraryInfo &(Function &)> GetTLI;
275   ProfileSummaryInfo &PSI;
276 
277   // Return the frequency of the OutlininingBB relative to F's entry point.
278   // The result is no larger than 1 and is represented using BP.
279   // (Note that the outlined region's 'head' block can only have incoming
280   // edges from the guarding entry blocks).
281   BranchProbability
282   getOutliningCallBBRelativeFreq(FunctionCloner &Cloner) const;
283 
284   // Return true if the callee of CB should be partially inlined with
285   // profit.
286   bool shouldPartialInline(CallBase &CB, FunctionCloner &Cloner,
287                            BlockFrequency WeightedOutliningRcost,
288                            OptimizationRemarkEmitter &ORE) const;
289 
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);
294 
295   // Compute the mapping from use site of DuplicationFunction to the enclosing
296   // BB's profile count.
297   void
298   computeCallsiteToProfCountMap(Function *DuplicateFunction,
299                                 DenseMap<User *, uint64_t> &SiteCountMap) const;
300 
301   bool isLimitReached() const {
302     return (MaxNumPartialInlining != -1 &&
303             NumPartialInlining >= MaxNumPartialInlining);
304   }
305 
306   static CallBase *getSupportedCallBase(User *U) {
307     if (isa<CallInst>(U) || isa<InvokeInst>(U))
308       return cast<CallBase>(U);
309     llvm_unreachable("All uses must be calls");
310     return nullptr;
311   }
312 
313   static CallBase *getOneCallSiteTo(Function &F) {
314     User *User = *F.user_begin();
315     return getSupportedCallBase(User);
316   }
317 
318   std::tuple<DebugLoc, BasicBlock *> getOneDebugLoc(Function &F) const {
319     CallBase *CB = getOneCallSiteTo(F);
320     DebugLoc DLoc = CB->getDebugLoc();
321     BasicBlock *Block = CB->getParent();
322     return std::make_tuple(DLoc, Block);
323   }
324 
325   // Returns the costs associated with function outlining:
326   // - The first value is the non-weighted runtime cost for making the call
327   //   to the outlined function, including the addtional  setup cost in the
328   //    outlined function itself;
329   // - The second value is the estimated size of the new call sequence in
330   //   basic block Cloner.OutliningCallBB;
331   std::tuple<int, int> computeOutliningCosts(FunctionCloner &Cloner) const;
332 
333   // Compute the 'InlineCost' of block BB. InlineCost is a proxy used to
334   // approximate both the size and runtime cost (Note that in the current
335   // inline cost analysis, there is no clear distinction there either).
336   static int computeBBInlineCost(BasicBlock *BB, TargetTransformInfo *TTI);
337 
338   std::unique_ptr<FunctionOutliningInfo>
339   computeOutliningInfo(Function &F) const;
340 
341   std::unique_ptr<FunctionOutliningMultiRegionInfo>
342   computeOutliningColdRegionsInfo(Function &F,
343                                   OptimizationRemarkEmitter &ORE) const;
344 };
345 
346 struct PartialInlinerLegacyPass : public ModulePass {
347   static char ID; // Pass identification, replacement for typeid
348 
349   PartialInlinerLegacyPass() : ModulePass(ID) {
350     initializePartialInlinerLegacyPassPass(*PassRegistry::getPassRegistry());
351   }
352 
353   void getAnalysisUsage(AnalysisUsage &AU) const override {
354     AU.addRequired<AssumptionCacheTracker>();
355     AU.addRequired<ProfileSummaryInfoWrapperPass>();
356     AU.addRequired<TargetTransformInfoWrapperPass>();
357     AU.addRequired<TargetLibraryInfoWrapperPass>();
358   }
359 
360   bool runOnModule(Module &M) override {
361     if (skipModule(M))
362       return false;
363 
364     AssumptionCacheTracker *ACT = &getAnalysis<AssumptionCacheTracker>();
365     TargetTransformInfoWrapperPass *TTIWP =
366         &getAnalysis<TargetTransformInfoWrapperPass>();
367     ProfileSummaryInfo &PSI =
368         getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
369 
370     auto GetAssumptionCache = [&ACT](Function &F) -> AssumptionCache & {
371       return ACT->getAssumptionCache(F);
372     };
373 
374     auto LookupAssumptionCache = [ACT](Function &F) -> AssumptionCache * {
375       return ACT->lookupAssumptionCache(F);
376     };
377 
378     auto GetTTI = [&TTIWP](Function &F) -> TargetTransformInfo & {
379       return TTIWP->getTTI(F);
380     };
381 
382     auto GetTLI = [this](Function &F) -> TargetLibraryInfo & {
383       return this->getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
384     };
385 
386     return PartialInlinerImpl(GetAssumptionCache, LookupAssumptionCache, GetTTI,
387                               GetTLI, PSI)
388         .run(M);
389   }
390 };
391 
392 } // end anonymous namespace
393 
394 std::unique_ptr<FunctionOutliningMultiRegionInfo>
395 PartialInlinerImpl::computeOutliningColdRegionsInfo(
396     Function &F, OptimizationRemarkEmitter &ORE) const {
397   BasicBlock *EntryBlock = &F.front();
398 
399   DominatorTree DT(F);
400   LoopInfo LI(DT);
401   BranchProbabilityInfo BPI(F, LI);
402   std::unique_ptr<BlockFrequencyInfo> ScopedBFI;
403   BlockFrequencyInfo *BFI;
404   if (!GetBFI) {
405     ScopedBFI.reset(new BlockFrequencyInfo(F, BPI, LI));
406     BFI = ScopedBFI.get();
407   } else
408     BFI = &(GetBFI(F));
409 
410   // Return if we don't have profiling information.
411   if (!PSI.hasInstrumentationProfile())
412     return std::unique_ptr<FunctionOutliningMultiRegionInfo>();
413 
414   std::unique_ptr<FunctionOutliningMultiRegionInfo> OutliningInfo =
415       std::make_unique<FunctionOutliningMultiRegionInfo>();
416 
417   auto IsSingleExit =
418       [&ORE](SmallVectorImpl<BasicBlock *> &BlockList) -> BasicBlock * {
419     BasicBlock *ExitBlock = nullptr;
420     for (auto *Block : BlockList) {
421       for (auto SI = succ_begin(Block); SI != succ_end(Block); ++SI) {
422         if (!is_contained(BlockList, *SI)) {
423           if (ExitBlock) {
424             ORE.emit([&]() {
425               return OptimizationRemarkMissed(DEBUG_TYPE, "MultiExitRegion",
426                                               &SI->front())
427                      << "Region dominated by "
428                      << ore::NV("Block", BlockList.front()->getName())
429                      << " has more than one region exit edge.";
430             });
431             return nullptr;
432           }
433 
434           ExitBlock = Block;
435         }
436       }
437     }
438     return ExitBlock;
439   };
440 
441   auto BBProfileCount = [BFI](BasicBlock *BB) {
442     return BFI->getBlockProfileCount(BB)
443                ? BFI->getBlockProfileCount(BB).getValue()
444                : 0;
445   };
446 
447   // Use the same computeBBInlineCost function to compute the cost savings of
448   // the outlining the candidate region.
449   TargetTransformInfo *FTTI = &GetTTI(F);
450   int OverallFunctionCost = 0;
451   for (auto &BB : F)
452     OverallFunctionCost += computeBBInlineCost(&BB, FTTI);
453 
454   LLVM_DEBUG(dbgs() << "OverallFunctionCost = " << OverallFunctionCost
455                     << "\n";);
456 
457   int MinOutlineRegionCost =
458       static_cast<int>(OverallFunctionCost * MinRegionSizeRatio);
459   BranchProbability MinBranchProbability(
460       static_cast<int>(ColdBranchRatio * MinBlockCounterExecution),
461       MinBlockCounterExecution);
462   bool ColdCandidateFound = false;
463   BasicBlock *CurrEntry = EntryBlock;
464   std::vector<BasicBlock *> DFS;
465   DenseMap<BasicBlock *, bool> VisitedMap;
466   DFS.push_back(CurrEntry);
467   VisitedMap[CurrEntry] = true;
468 
469   // Use Depth First Search on the basic blocks to find CFG edges that are
470   // considered cold.
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
474   // more.
475   while (!DFS.empty()) {
476     auto *ThisBB = DFS.back();
477     DFS.pop_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)
483       continue;
484     for (auto SI = succ_begin(ThisBB); SI != succ_end(ThisBB); ++SI) {
485       if (VisitedMap[*SI])
486         continue;
487       VisitedMap[*SI] = true;
488       DFS.push_back(*SI);
489       // If branch isn't cold, we skip to the next one.
490       BranchProbability SuccProb = BPI.getEdgeProbability(ThisBB, *SI);
491       if (SuccProb > MinBranchProbability)
492         continue;
493 
494       LLVM_DEBUG(dbgs() << "Found cold edge: " << ThisBB->getName() << "->"
495                         << SI->getName()
496                         << "\nBranch Probability = " << SuccProb << "\n";);
497 
498       SmallVector<BasicBlock *, 8> DominateVector;
499       DT.getDescendants(*SI, DominateVector);
500       assert(!DominateVector.empty() &&
501              "SI should be reachable and have at least itself as descendant");
502 
503       // We can only outline single entry regions (for now).
504       if (!DominateVector.front()->hasNPredecessors(1)) {
505         LLVM_DEBUG(dbgs() << "ABORT: Block " << SI->getName()
506                           << " doesn't have a single predecessor in the "
507                              "dominator tree\n";);
508         continue;
509       }
510 
511       BasicBlock *ExitBlock = nullptr;
512       // We can only outline single exit regions (for now).
513       if (!(ExitBlock = IsSingleExit(DominateVector))) {
514         LLVM_DEBUG(dbgs() << "ABORT: Block " << SI->getName()
515                           << " doesn't have a unique successor\n";);
516         continue;
517       }
518 
519       int OutlineRegionCost = 0;
520       for (auto *BB : DominateVector)
521         OutlineRegionCost += computeBBInlineCost(BB, &GetTTI(*BB->getParent()));
522 
523       LLVM_DEBUG(dbgs() << "OutlineRegionCost = " << OutlineRegionCost
524                         << "\n";);
525 
526       if (!SkipCostAnalysis && OutlineRegionCost < MinOutlineRegionCost) {
527         ORE.emit([&]() {
528           return OptimizationRemarkAnalysis(DEBUG_TYPE, "TooCostly",
529                                             &SI->front())
530                  << ore::NV("Callee", &F)
531                  << " inline cost-savings smaller than "
532                  << ore::NV("Cost", MinOutlineRegionCost);
533         });
534 
535         LLVM_DEBUG(dbgs() << "ABORT: Outline region cost is smaller than "
536                           << MinOutlineRegionCost << "\n";);
537         continue;
538       }
539 
540       // For now, ignore blocks that belong to a SISE region that is a
541       // candidate for outlining.  In the future, we may want to look
542       // at inner regions because the outer region may have live-exit
543       // variables.
544       for (auto *BB : DominateVector)
545         VisitedMap[BB] = true;
546 
547       // ReturnBlock here means the block after the outline call
548       BasicBlock *ReturnBlock = ExitBlock->getSingleSuccessor();
549       FunctionOutliningMultiRegionInfo::OutlineRegionInfo RegInfo(
550           DominateVector, DominateVector.front(), ExitBlock, ReturnBlock);
551       OutliningInfo->ORI.push_back(RegInfo);
552       LLVM_DEBUG(dbgs() << "Found Cold Candidate starting at block: "
553                         << DominateVector.front()->getName() << "\n";);
554       ColdCandidateFound = true;
555       NumColdRegionsFound++;
556     }
557   }
558 
559   if (ColdCandidateFound)
560     return OutliningInfo;
561 
562   return std::unique_ptr<FunctionOutliningMultiRegionInfo>();
563 }
564 
565 std::unique_ptr<FunctionOutliningInfo>
566 PartialInlinerImpl::computeOutliningInfo(Function &F) const {
567   BasicBlock *EntryBlock = &F.front();
568   BranchInst *BR = dyn_cast<BranchInst>(EntryBlock->getTerminator());
569   if (!BR || BR->isUnconditional())
570     return std::unique_ptr<FunctionOutliningInfo>();
571 
572   // Returns true if Succ is BB's successor
573   auto IsSuccessor = [](BasicBlock *Succ, BasicBlock *BB) {
574     return is_contained(successors(BB), Succ);
575   };
576 
577   auto IsReturnBlock = [](BasicBlock *BB) {
578     Instruction *TI = BB->getTerminator();
579     return isa<ReturnInst>(TI);
580   };
581 
582   auto GetReturnBlock = [&](BasicBlock *Succ1, BasicBlock *Succ2) {
583     if (IsReturnBlock(Succ1))
584       return std::make_tuple(Succ1, Succ2);
585     if (IsReturnBlock(Succ2))
586       return std::make_tuple(Succ2, Succ1);
587 
588     return std::make_tuple<BasicBlock *, BasicBlock *>(nullptr, nullptr);
589   };
590 
591   // Detect a triangular shape:
592   auto GetCommonSucc = [&](BasicBlock *Succ1, BasicBlock *Succ2) {
593     if (IsSuccessor(Succ1, Succ2))
594       return std::make_tuple(Succ1, Succ2);
595     if (IsSuccessor(Succ2, Succ1))
596       return std::make_tuple(Succ2, Succ1);
597 
598     return std::make_tuple<BasicBlock *, BasicBlock *>(nullptr, nullptr);
599   };
600 
601   std::unique_ptr<FunctionOutliningInfo> OutliningInfo =
602       std::make_unique<FunctionOutliningInfo>();
603 
604   BasicBlock *CurrEntry = EntryBlock;
605   bool CandidateFound = false;
606   do {
607     // The number of blocks to be inlined has already reached
608     // the limit. When MaxNumInlineBlocks is set to 0 or 1, this
609     // disables partial inlining for the function.
610     if (OutliningInfo->getNumInlinedBlocks() >= MaxNumInlineBlocks)
611       break;
612 
613     if (succ_size(CurrEntry) != 2)
614       break;
615 
616     BasicBlock *Succ1 = *succ_begin(CurrEntry);
617     BasicBlock *Succ2 = *(succ_begin(CurrEntry) + 1);
618 
619     BasicBlock *ReturnBlock, *NonReturnBlock;
620     std::tie(ReturnBlock, NonReturnBlock) = GetReturnBlock(Succ1, Succ2);
621 
622     if (ReturnBlock) {
623       OutliningInfo->Entries.push_back(CurrEntry);
624       OutliningInfo->ReturnBlock = ReturnBlock;
625       OutliningInfo->NonReturnBlock = NonReturnBlock;
626       CandidateFound = true;
627       break;
628     }
629 
630     BasicBlock *CommSucc, *OtherSucc;
631     std::tie(CommSucc, OtherSucc) = GetCommonSucc(Succ1, Succ2);
632 
633     if (!CommSucc)
634       break;
635 
636     OutliningInfo->Entries.push_back(CurrEntry);
637     CurrEntry = OtherSucc;
638   } while (true);
639 
640   if (!CandidateFound)
641     return std::unique_ptr<FunctionOutliningInfo>();
642 
643   // Do sanity check of the entries: threre should not
644   // be any successors (not in the entry set) other than
645   // {ReturnBlock, NonReturnBlock}
646   assert(OutliningInfo->Entries[0] == &F.front() &&
647          "Function Entry must be the first in Entries vector");
648   DenseSet<BasicBlock *> Entries;
649   for (BasicBlock *E : OutliningInfo->Entries)
650     Entries.insert(E);
651 
652   // Returns true of BB has Predecessor which is not
653   // in Entries set.
654   auto HasNonEntryPred = [Entries](BasicBlock *BB) {
655     for (auto *Pred : predecessors(BB)) {
656       if (!Entries.count(Pred))
657         return true;
658     }
659     return false;
660   };
661   auto CheckAndNormalizeCandidate =
662       [Entries, HasNonEntryPred](FunctionOutliningInfo *OutliningInfo) {
663         for (BasicBlock *E : OutliningInfo->Entries) {
664           for (auto *Succ : successors(E)) {
665             if (Entries.count(Succ))
666               continue;
667             if (Succ == OutliningInfo->ReturnBlock)
668               OutliningInfo->ReturnBlockPreds.push_back(E);
669             else if (Succ != OutliningInfo->NonReturnBlock)
670               return false;
671           }
672           // There should not be any outside incoming edges either:
673           if (HasNonEntryPred(E))
674             return false;
675         }
676         return true;
677       };
678 
679   if (!CheckAndNormalizeCandidate(OutliningInfo.get()))
680     return std::unique_ptr<FunctionOutliningInfo>();
681 
682   // Now further growing the candidate's inlining region by
683   // peeling off dominating blocks from the outlining region:
684   while (OutliningInfo->getNumInlinedBlocks() < MaxNumInlineBlocks) {
685     BasicBlock *Cand = OutliningInfo->NonReturnBlock;
686     if (succ_size(Cand) != 2)
687       break;
688 
689     if (HasNonEntryPred(Cand))
690       break;
691 
692     BasicBlock *Succ1 = *succ_begin(Cand);
693     BasicBlock *Succ2 = *(succ_begin(Cand) + 1);
694 
695     BasicBlock *ReturnBlock, *NonReturnBlock;
696     std::tie(ReturnBlock, NonReturnBlock) = GetReturnBlock(Succ1, Succ2);
697     if (!ReturnBlock || ReturnBlock != OutliningInfo->ReturnBlock)
698       break;
699 
700     if (NonReturnBlock->getSinglePredecessor() != Cand)
701       break;
702 
703     // Now grow and update OutlininigInfo:
704     OutliningInfo->Entries.push_back(Cand);
705     OutliningInfo->NonReturnBlock = NonReturnBlock;
706     OutliningInfo->ReturnBlockPreds.push_back(Cand);
707     Entries.insert(Cand);
708   }
709 
710   return OutliningInfo;
711 }
712 
713 // Check if there is PGO data or user annotated branch data:
714 static bool hasProfileData(const Function &F, const FunctionOutliningInfo &OI) {
715   if (F.hasProfileData())
716     return true;
717   // Now check if any of the entry block has MD_prof data:
718   for (auto *E : OI.Entries) {
719     BranchInst *BR = dyn_cast<BranchInst>(E->getTerminator());
720     if (!BR || BR->isUnconditional())
721       continue;
722     uint64_t T, F;
723     if (BR->extractProfMetadata(T, F))
724       return true;
725   }
726   return false;
727 }
728 
729 BranchProbability PartialInlinerImpl::getOutliningCallBBRelativeFreq(
730     FunctionCloner &Cloner) const {
731   BasicBlock *OutliningCallBB = Cloner.OutlinedFunctions.back().second;
732   auto EntryFreq =
733       Cloner.ClonedFuncBFI->getBlockFreq(&Cloner.ClonedFunc->getEntryBlock());
734   auto OutliningCallFreq =
735       Cloner.ClonedFuncBFI->getBlockFreq(OutliningCallBB);
736   // FIXME Hackery needed because ClonedFuncBFI is based on the function BEFORE
737   // we outlined any regions, so we may encounter situations where the
738   // OutliningCallFreq is *slightly* bigger than the EntryFreq.
739   if (OutliningCallFreq.getFrequency() > EntryFreq.getFrequency())
740     OutliningCallFreq = EntryFreq;
741 
742   auto OutlineRegionRelFreq = BranchProbability::getBranchProbability(
743       OutliningCallFreq.getFrequency(), EntryFreq.getFrequency());
744 
745   if (hasProfileData(*Cloner.OrigFunc, *Cloner.ClonedOI.get()))
746     return OutlineRegionRelFreq;
747 
748   // When profile data is not available, we need to be conservative in
749   // estimating the overall savings. Static branch prediction can usually
750   // guess the branch direction right (taken/non-taken), but the guessed
751   // branch probability is usually not biased enough. In case when the
752   // outlined region is predicted to be likely, its probability needs
753   // to be made higher (more biased) to not under-estimate the cost of
754   // function outlining. On the other hand, if the outlined region
755   // is predicted to be less likely, the predicted probablity is usually
756   // higher than the actual. For instance, the actual probability of the
757   // less likely target is only 5%, but the guessed probablity can be
758   // 40%. In the latter case, there is no need for further adjustement.
759   // FIXME: add an option for this.
760   if (OutlineRegionRelFreq < BranchProbability(45, 100))
761     return OutlineRegionRelFreq;
762 
763   OutlineRegionRelFreq = std::max(
764       OutlineRegionRelFreq, BranchProbability(OutlineRegionFreqPercent, 100));
765 
766   return OutlineRegionRelFreq;
767 }
768 
769 bool PartialInlinerImpl::shouldPartialInline(
770     CallBase &CB, FunctionCloner &Cloner, BlockFrequency WeightedOutliningRcost,
771     OptimizationRemarkEmitter &ORE) const {
772   using namespace ore;
773 
774   Function *Callee = CB.getCalledFunction();
775   assert(Callee == Cloner.ClonedFunc);
776 
777   if (SkipCostAnalysis)
778     return isInlineViable(*Callee).isSuccess();
779 
780   Function *Caller = CB.getCaller();
781   auto &CalleeTTI = GetTTI(*Callee);
782   bool RemarksEnabled =
783       Callee->getContext().getDiagHandlerPtr()->isMissedOptRemarkEnabled(
784           DEBUG_TYPE);
785   InlineCost IC =
786       getInlineCost(CB, getInlineParams(), CalleeTTI, GetAssumptionCache,
787                     GetTLI, GetBFI, &PSI, RemarksEnabled ? &ORE : nullptr);
788 
789   if (IC.isAlways()) {
790     ORE.emit([&]() {
791       return OptimizationRemarkAnalysis(DEBUG_TYPE, "AlwaysInline", &CB)
792              << NV("Callee", Cloner.OrigFunc)
793              << " should always be fully inlined, not partially";
794     });
795     return false;
796   }
797 
798   if (IC.isNever()) {
799     ORE.emit([&]() {
800       return OptimizationRemarkMissed(DEBUG_TYPE, "NeverInline", &CB)
801              << NV("Callee", Cloner.OrigFunc) << " not partially inlined into "
802              << NV("Caller", Caller)
803              << " because it should never be inlined (cost=never)";
804     });
805     return false;
806   }
807 
808   if (!IC) {
809     ORE.emit([&]() {
810       return OptimizationRemarkAnalysis(DEBUG_TYPE, "TooCostly", &CB)
811              << NV("Callee", Cloner.OrigFunc) << " not partially inlined into "
812              << NV("Caller", Caller) << " because too costly to inline (cost="
813              << NV("Cost", IC.getCost()) << ", threshold="
814              << NV("Threshold", IC.getCostDelta() + IC.getCost()) << ")";
815     });
816     return false;
817   }
818   const DataLayout &DL = Caller->getParent()->getDataLayout();
819 
820   // The savings of eliminating the call:
821   int NonWeightedSavings = getCallsiteCost(CB, DL);
822   BlockFrequency NormWeightedSavings(NonWeightedSavings);
823 
824   // Weighted saving is smaller than weighted cost, return false
825   if (NormWeightedSavings < WeightedOutliningRcost) {
826     ORE.emit([&]() {
827       return OptimizationRemarkAnalysis(DEBUG_TYPE, "OutliningCallcostTooHigh",
828                                         &CB)
829              << NV("Callee", Cloner.OrigFunc) << " not partially inlined into "
830              << NV("Caller", Caller) << " runtime overhead (overhead="
831              << NV("Overhead", (unsigned)WeightedOutliningRcost.getFrequency())
832              << ", savings="
833              << NV("Savings", (unsigned)NormWeightedSavings.getFrequency())
834              << ")"
835              << " of making the outlined call is too high";
836     });
837 
838     return false;
839   }
840 
841   ORE.emit([&]() {
842     return OptimizationRemarkAnalysis(DEBUG_TYPE, "CanBePartiallyInlined", &CB)
843            << NV("Callee", Cloner.OrigFunc) << " can be partially inlined into "
844            << NV("Caller", Caller) << " with cost=" << NV("Cost", IC.getCost())
845            << " (threshold="
846            << NV("Threshold", IC.getCostDelta() + IC.getCost()) << ")";
847   });
848   return true;
849 }
850 
851 // TODO: Ideally  we should share Inliner's InlineCost Analysis code.
852 // For now use a simplified version. The returned 'InlineCost' will be used
853 // to esimate the size cost as well as runtime cost of the BB.
854 int PartialInlinerImpl::computeBBInlineCost(BasicBlock *BB,
855                                             TargetTransformInfo *TTI) {
856   int InlineCost = 0;
857   const DataLayout &DL = BB->getParent()->getParent()->getDataLayout();
858   for (Instruction &I : BB->instructionsWithoutDebug()) {
859     // Skip free instructions.
860     switch (I.getOpcode()) {
861     case Instruction::BitCast:
862     case Instruction::PtrToInt:
863     case Instruction::IntToPtr:
864     case Instruction::Alloca:
865     case Instruction::PHI:
866       continue;
867     case Instruction::GetElementPtr:
868       if (cast<GetElementPtrInst>(&I)->hasAllZeroIndices())
869         continue;
870       break;
871     default:
872       break;
873     }
874 
875     if (I.isLifetimeStartOrEnd())
876       continue;
877 
878     if (auto *II = dyn_cast<IntrinsicInst>(&I)) {
879       Intrinsic::ID IID = II->getIntrinsicID();
880       SmallVector<Type *, 4> Tys;
881       FastMathFlags FMF;
882       for (Value *Val : II->args())
883         Tys.push_back(Val->getType());
884 
885       if (auto *FPMO = dyn_cast<FPMathOperator>(II))
886         FMF = FPMO->getFastMathFlags();
887 
888       IntrinsicCostAttributes ICA(IID, II->getType(), Tys, FMF);
889       InlineCost += TTI->getIntrinsicInstrCost(ICA, TTI::TCK_SizeAndLatency);
890       continue;
891     }
892 
893     if (CallInst *CI = dyn_cast<CallInst>(&I)) {
894       InlineCost += getCallsiteCost(*CI, DL);
895       continue;
896     }
897 
898     if (InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
899       InlineCost += getCallsiteCost(*II, DL);
900       continue;
901     }
902 
903     if (SwitchInst *SI = dyn_cast<SwitchInst>(&I)) {
904       InlineCost += (SI->getNumCases() + 1) * InlineConstants::InstrCost;
905       continue;
906     }
907     InlineCost += InlineConstants::InstrCost;
908   }
909   return InlineCost;
910 }
911 
912 std::tuple<int, int>
913 PartialInlinerImpl::computeOutliningCosts(FunctionCloner &Cloner) const {
914   int OutliningFuncCallCost = 0, OutlinedFunctionCost = 0;
915   for (auto FuncBBPair : Cloner.OutlinedFunctions) {
916     Function *OutlinedFunc = FuncBBPair.first;
917     BasicBlock* OutliningCallBB = FuncBBPair.second;
918     // Now compute the cost of the call sequence to the outlined function
919     // 'OutlinedFunction' in BB 'OutliningCallBB':
920     auto *OutlinedFuncTTI = &GetTTI(*OutlinedFunc);
921     OutliningFuncCallCost +=
922         computeBBInlineCost(OutliningCallBB, OutlinedFuncTTI);
923 
924     // Now compute the cost of the extracted/outlined function itself:
925     for (BasicBlock &BB : *OutlinedFunc)
926       OutlinedFunctionCost += computeBBInlineCost(&BB, OutlinedFuncTTI);
927   }
928   assert(OutlinedFunctionCost >= Cloner.OutlinedRegionCost &&
929          "Outlined function cost should be no less than the outlined region");
930 
931   // The code extractor introduces a new root and exit stub blocks with
932   // additional unconditional branches. Those branches will be eliminated
933   // later with bb layout. The cost should be adjusted accordingly:
934   OutlinedFunctionCost -=
935       2 * InlineConstants::InstrCost * Cloner.OutlinedFunctions.size();
936 
937   int OutliningRuntimeOverhead =
938       OutliningFuncCallCost +
939       (OutlinedFunctionCost - Cloner.OutlinedRegionCost) +
940       ExtraOutliningPenalty;
941 
942   return std::make_tuple(OutliningFuncCallCost, OutliningRuntimeOverhead);
943 }
944 
945 // Create the callsite to profile count map which is
946 // used to update the original function's entry count,
947 // after the function is partially inlined into the callsite.
948 void PartialInlinerImpl::computeCallsiteToProfCountMap(
949     Function *DuplicateFunction,
950     DenseMap<User *, uint64_t> &CallSiteToProfCountMap) const {
951   std::vector<User *> Users(DuplicateFunction->user_begin(),
952                             DuplicateFunction->user_end());
953   Function *CurrentCaller = nullptr;
954   std::unique_ptr<BlockFrequencyInfo> TempBFI;
955   BlockFrequencyInfo *CurrentCallerBFI = nullptr;
956 
957   auto ComputeCurrBFI = [&,this](Function *Caller) {
958       // For the old pass manager:
959       if (!GetBFI) {
960         DominatorTree DT(*Caller);
961         LoopInfo LI(DT);
962         BranchProbabilityInfo BPI(*Caller, LI);
963         TempBFI.reset(new BlockFrequencyInfo(*Caller, BPI, LI));
964         CurrentCallerBFI = TempBFI.get();
965       } else {
966         // New pass manager:
967         CurrentCallerBFI = &(GetBFI(*Caller));
968       }
969   };
970 
971   for (User *User : Users) {
972     CallBase *CB = getSupportedCallBase(User);
973     Function *Caller = CB->getCaller();
974     if (CurrentCaller != Caller) {
975       CurrentCaller = Caller;
976       ComputeCurrBFI(Caller);
977     } else {
978       assert(CurrentCallerBFI && "CallerBFI is not set");
979     }
980     BasicBlock *CallBB = CB->getParent();
981     auto Count = CurrentCallerBFI->getBlockProfileCount(CallBB);
982     if (Count)
983       CallSiteToProfCountMap[User] = *Count;
984     else
985       CallSiteToProfCountMap[User] = 0;
986   }
987 }
988 
989 PartialInlinerImpl::FunctionCloner::FunctionCloner(
990     Function *F, FunctionOutliningInfo *OI, OptimizationRemarkEmitter &ORE,
991     function_ref<AssumptionCache *(Function &)> LookupAC,
992     function_ref<TargetTransformInfo &(Function &)> GetTTI)
993     : OrigFunc(F), ORE(ORE), LookupAC(LookupAC), GetTTI(GetTTI) {
994   ClonedOI = std::make_unique<FunctionOutliningInfo>();
995 
996   // Clone the function, so that we can hack away on it.
997   ValueToValueMapTy VMap;
998   ClonedFunc = CloneFunction(F, VMap);
999 
1000   ClonedOI->ReturnBlock = cast<BasicBlock>(VMap[OI->ReturnBlock]);
1001   ClonedOI->NonReturnBlock = cast<BasicBlock>(VMap[OI->NonReturnBlock]);
1002   for (BasicBlock *BB : OI->Entries)
1003     ClonedOI->Entries.push_back(cast<BasicBlock>(VMap[BB]));
1004 
1005   for (BasicBlock *E : OI->ReturnBlockPreds) {
1006     BasicBlock *NewE = cast<BasicBlock>(VMap[E]);
1007     ClonedOI->ReturnBlockPreds.push_back(NewE);
1008   }
1009   // Go ahead and update all uses to the duplicate, so that we can just
1010   // use the inliner functionality when we're done hacking.
1011   F->replaceAllUsesWith(ClonedFunc);
1012 }
1013 
1014 PartialInlinerImpl::FunctionCloner::FunctionCloner(
1015     Function *F, FunctionOutliningMultiRegionInfo *OI,
1016     OptimizationRemarkEmitter &ORE,
1017     function_ref<AssumptionCache *(Function &)> LookupAC,
1018     function_ref<TargetTransformInfo &(Function &)> GetTTI)
1019     : OrigFunc(F), ORE(ORE), LookupAC(LookupAC), GetTTI(GetTTI) {
1020   ClonedOMRI = std::make_unique<FunctionOutliningMultiRegionInfo>();
1021 
1022   // Clone the function, so that we can hack away on it.
1023   ValueToValueMapTy VMap;
1024   ClonedFunc = CloneFunction(F, VMap);
1025 
1026   // Go through all Outline Candidate Regions and update all BasicBlock
1027   // information.
1028   for (FunctionOutliningMultiRegionInfo::OutlineRegionInfo RegionInfo :
1029        OI->ORI) {
1030     SmallVector<BasicBlock *, 8> Region;
1031     for (BasicBlock *BB : RegionInfo.Region)
1032       Region.push_back(cast<BasicBlock>(VMap[BB]));
1033 
1034     BasicBlock *NewEntryBlock = cast<BasicBlock>(VMap[RegionInfo.EntryBlock]);
1035     BasicBlock *NewExitBlock = cast<BasicBlock>(VMap[RegionInfo.ExitBlock]);
1036     BasicBlock *NewReturnBlock = nullptr;
1037     if (RegionInfo.ReturnBlock)
1038       NewReturnBlock = cast<BasicBlock>(VMap[RegionInfo.ReturnBlock]);
1039     FunctionOutliningMultiRegionInfo::OutlineRegionInfo MappedRegionInfo(
1040         Region, NewEntryBlock, NewExitBlock, NewReturnBlock);
1041     ClonedOMRI->ORI.push_back(MappedRegionInfo);
1042   }
1043   // Go ahead and update all uses to the duplicate, so that we can just
1044   // use the inliner functionality when we're done hacking.
1045   F->replaceAllUsesWith(ClonedFunc);
1046 }
1047 
1048 void PartialInlinerImpl::FunctionCloner::normalizeReturnBlock() const {
1049   auto GetFirstPHI = [](BasicBlock *BB) {
1050     BasicBlock::iterator I = BB->begin();
1051     PHINode *FirstPhi = nullptr;
1052     while (I != BB->end()) {
1053       PHINode *Phi = dyn_cast<PHINode>(I);
1054       if (!Phi)
1055         break;
1056       if (!FirstPhi) {
1057         FirstPhi = Phi;
1058         break;
1059       }
1060     }
1061     return FirstPhi;
1062   };
1063 
1064   // Shouldn't need to normalize PHIs if we're not outlining non-early return
1065   // blocks.
1066   if (!ClonedOI)
1067     return;
1068 
1069   // Special hackery is needed with PHI nodes that have inputs from more than
1070   // one extracted block.  For simplicity, just split the PHIs into a two-level
1071   // sequence of PHIs, some of which will go in the extracted region, and some
1072   // of which will go outside.
1073   BasicBlock *PreReturn = ClonedOI->ReturnBlock;
1074   // only split block when necessary:
1075   PHINode *FirstPhi = GetFirstPHI(PreReturn);
1076   unsigned NumPredsFromEntries = ClonedOI->ReturnBlockPreds.size();
1077 
1078   if (!FirstPhi || FirstPhi->getNumIncomingValues() <= NumPredsFromEntries + 1)
1079     return;
1080 
1081   auto IsTrivialPhi = [](PHINode *PN) -> Value * {
1082     Value *CommonValue = PN->getIncomingValue(0);
1083     if (all_of(PN->incoming_values(),
1084                [&](Value *V) { return V == CommonValue; }))
1085       return CommonValue;
1086     return nullptr;
1087   };
1088 
1089   ClonedOI->ReturnBlock = ClonedOI->ReturnBlock->splitBasicBlock(
1090       ClonedOI->ReturnBlock->getFirstNonPHI()->getIterator());
1091   BasicBlock::iterator I = PreReturn->begin();
1092   Instruction *Ins = &ClonedOI->ReturnBlock->front();
1093   SmallVector<Instruction *, 4> DeadPhis;
1094   while (I != PreReturn->end()) {
1095     PHINode *OldPhi = dyn_cast<PHINode>(I);
1096     if (!OldPhi)
1097       break;
1098 
1099     PHINode *RetPhi =
1100         PHINode::Create(OldPhi->getType(), NumPredsFromEntries + 1, "", Ins);
1101     OldPhi->replaceAllUsesWith(RetPhi);
1102     Ins = ClonedOI->ReturnBlock->getFirstNonPHI();
1103 
1104     RetPhi->addIncoming(&*I, PreReturn);
1105     for (BasicBlock *E : ClonedOI->ReturnBlockPreds) {
1106       RetPhi->addIncoming(OldPhi->getIncomingValueForBlock(E), E);
1107       OldPhi->removeIncomingValue(E);
1108     }
1109 
1110     // After incoming values splitting, the old phi may become trivial.
1111     // Keeping the trivial phi can introduce definition inside the outline
1112     // region which is live-out, causing necessary overhead (load, store
1113     // arg passing etc).
1114     if (auto *OldPhiVal = IsTrivialPhi(OldPhi)) {
1115       OldPhi->replaceAllUsesWith(OldPhiVal);
1116       DeadPhis.push_back(OldPhi);
1117     }
1118     ++I;
1119   }
1120   for (auto *DP : DeadPhis)
1121     DP->eraseFromParent();
1122 
1123   for (auto *E : ClonedOI->ReturnBlockPreds)
1124     E->getTerminator()->replaceUsesOfWith(PreReturn, ClonedOI->ReturnBlock);
1125 }
1126 
1127 bool PartialInlinerImpl::FunctionCloner::doMultiRegionFunctionOutlining() {
1128 
1129   auto ComputeRegionCost = [&](SmallVectorImpl<BasicBlock *> &Region) {
1130     int Cost = 0;
1131     for (BasicBlock* BB : Region)
1132       Cost += computeBBInlineCost(BB, &GetTTI(*BB->getParent()));
1133     return Cost;
1134   };
1135 
1136   assert(ClonedOMRI && "Expecting OutlineInfo for multi region outline");
1137 
1138   if (ClonedOMRI->ORI.empty())
1139     return false;
1140 
1141   // The CodeExtractor needs a dominator tree.
1142   DominatorTree DT;
1143   DT.recalculate(*ClonedFunc);
1144 
1145   // Manually calculate a BlockFrequencyInfo and BranchProbabilityInfo.
1146   LoopInfo LI(DT);
1147   BranchProbabilityInfo BPI(*ClonedFunc, LI);
1148   ClonedFuncBFI.reset(new BlockFrequencyInfo(*ClonedFunc, BPI, LI));
1149 
1150   // Cache and recycle the CodeExtractor analysis to avoid O(n^2) compile-time.
1151   CodeExtractorAnalysisCache CEAC(*ClonedFunc);
1152 
1153   SetVector<Value *> Inputs, Outputs, Sinks;
1154   for (FunctionOutliningMultiRegionInfo::OutlineRegionInfo RegionInfo :
1155        ClonedOMRI->ORI) {
1156     int CurrentOutlinedRegionCost = ComputeRegionCost(RegionInfo.Region);
1157 
1158     CodeExtractor CE(RegionInfo.Region, &DT, /*AggregateArgs*/ false,
1159                      ClonedFuncBFI.get(), &BPI,
1160                      LookupAC(*RegionInfo.EntryBlock->getParent()),
1161                      /* AllowVarargs */ false);
1162 
1163     CE.findInputsOutputs(Inputs, Outputs, Sinks);
1164 
1165     LLVM_DEBUG({
1166       dbgs() << "inputs: " << Inputs.size() << "\n";
1167       dbgs() << "outputs: " << Outputs.size() << "\n";
1168       for (Value *value : Inputs)
1169         dbgs() << "value used in func: " << *value << "\n";
1170       for (Value *output : Outputs)
1171         dbgs() << "instr used in func: " << *output << "\n";
1172     });
1173 
1174     // Do not extract regions that have live exit variables.
1175     if (Outputs.size() > 0 && !ForceLiveExit)
1176       continue;
1177 
1178     if (Function *OutlinedFunc = CE.extractCodeRegion(CEAC)) {
1179       CallBase *OCS = PartialInlinerImpl::getOneCallSiteTo(*OutlinedFunc);
1180       BasicBlock *OutliningCallBB = OCS->getParent();
1181       assert(OutliningCallBB->getParent() == ClonedFunc);
1182       OutlinedFunctions.push_back(std::make_pair(OutlinedFunc,OutliningCallBB));
1183       NumColdRegionsOutlined++;
1184       OutlinedRegionCost += CurrentOutlinedRegionCost;
1185 
1186       if (MarkOutlinedColdCC) {
1187         OutlinedFunc->setCallingConv(CallingConv::Cold);
1188         OCS->setCallingConv(CallingConv::Cold);
1189       }
1190     } else
1191       ORE.emit([&]() {
1192         return OptimizationRemarkMissed(DEBUG_TYPE, "ExtractFailed",
1193                                         &RegionInfo.Region.front()->front())
1194                << "Failed to extract region at block "
1195                << ore::NV("Block", RegionInfo.Region.front());
1196       });
1197   }
1198 
1199   return !OutlinedFunctions.empty();
1200 }
1201 
1202 Function *
1203 PartialInlinerImpl::FunctionCloner::doSingleRegionFunctionOutlining() {
1204   // Returns true if the block is to be partial inlined into the caller
1205   // (i.e. not to be extracted to the out of line function)
1206   auto ToBeInlined = [&, this](BasicBlock *BB) {
1207     return BB == ClonedOI->ReturnBlock ||
1208            llvm::is_contained(ClonedOI->Entries, BB);
1209   };
1210 
1211   assert(ClonedOI && "Expecting OutlineInfo for single region outline");
1212   // The CodeExtractor needs a dominator tree.
1213   DominatorTree DT;
1214   DT.recalculate(*ClonedFunc);
1215 
1216   // Manually calculate a BlockFrequencyInfo and BranchProbabilityInfo.
1217   LoopInfo LI(DT);
1218   BranchProbabilityInfo BPI(*ClonedFunc, LI);
1219   ClonedFuncBFI.reset(new BlockFrequencyInfo(*ClonedFunc, BPI, LI));
1220 
1221   // Gather up the blocks that we're going to extract.
1222   std::vector<BasicBlock *> ToExtract;
1223   auto *ClonedFuncTTI = &GetTTI(*ClonedFunc);
1224   ToExtract.push_back(ClonedOI->NonReturnBlock);
1225   OutlinedRegionCost += PartialInlinerImpl::computeBBInlineCost(
1226       ClonedOI->NonReturnBlock, ClonedFuncTTI);
1227   for (BasicBlock &BB : *ClonedFunc)
1228     if (!ToBeInlined(&BB) && &BB != ClonedOI->NonReturnBlock) {
1229       ToExtract.push_back(&BB);
1230       // FIXME: the code extractor may hoist/sink more code
1231       // into the outlined function which may make the outlining
1232       // overhead (the difference of the outlined function cost
1233       // and OutliningRegionCost) look larger.
1234       OutlinedRegionCost += computeBBInlineCost(&BB, ClonedFuncTTI);
1235     }
1236 
1237   // Extract the body of the if.
1238   CodeExtractorAnalysisCache CEAC(*ClonedFunc);
1239   Function *OutlinedFunc =
1240       CodeExtractor(ToExtract, &DT, /*AggregateArgs*/ false,
1241                     ClonedFuncBFI.get(), &BPI, LookupAC(*ClonedFunc),
1242                     /* AllowVarargs */ true)
1243           .extractCodeRegion(CEAC);
1244 
1245   if (OutlinedFunc) {
1246     BasicBlock *OutliningCallBB =
1247         PartialInlinerImpl::getOneCallSiteTo(*OutlinedFunc)->getParent();
1248     assert(OutliningCallBB->getParent() == ClonedFunc);
1249     OutlinedFunctions.push_back(std::make_pair(OutlinedFunc, OutliningCallBB));
1250   } else
1251     ORE.emit([&]() {
1252       return OptimizationRemarkMissed(DEBUG_TYPE, "ExtractFailed",
1253                                       &ToExtract.front()->front())
1254              << "Failed to extract region at block "
1255              << ore::NV("Block", ToExtract.front());
1256     });
1257 
1258   return OutlinedFunc;
1259 }
1260 
1261 PartialInlinerImpl::FunctionCloner::~FunctionCloner() {
1262   // Ditch the duplicate, since we're done with it, and rewrite all remaining
1263   // users (function pointers, etc.) back to the original function.
1264   ClonedFunc->replaceAllUsesWith(OrigFunc);
1265   ClonedFunc->eraseFromParent();
1266   if (!IsFunctionInlined) {
1267     // Remove each function that was speculatively created if there is no
1268     // reference.
1269     for (auto FuncBBPair : OutlinedFunctions) {
1270       Function *Func = FuncBBPair.first;
1271       Func->eraseFromParent();
1272     }
1273   }
1274 }
1275 
1276 std::pair<bool, Function *> PartialInlinerImpl::unswitchFunction(Function &F) {
1277   if (F.hasAddressTaken())
1278     return {false, nullptr};
1279 
1280   // Let inliner handle it
1281   if (F.hasFnAttribute(Attribute::AlwaysInline))
1282     return {false, nullptr};
1283 
1284   if (F.hasFnAttribute(Attribute::NoInline))
1285     return {false, nullptr};
1286 
1287   if (PSI.isFunctionEntryCold(&F))
1288     return {false, nullptr};
1289 
1290   if (F.users().empty())
1291     return {false, nullptr};
1292 
1293   OptimizationRemarkEmitter ORE(&F);
1294 
1295   // Only try to outline cold regions if we have a profile summary, which
1296   // implies we have profiling information.
1297   if (PSI.hasProfileSummary() && F.hasProfileData() &&
1298       !DisableMultiRegionPartialInline) {
1299     std::unique_ptr<FunctionOutliningMultiRegionInfo> OMRI =
1300         computeOutliningColdRegionsInfo(F, ORE);
1301     if (OMRI) {
1302       FunctionCloner Cloner(&F, OMRI.get(), ORE, LookupAssumptionCache, GetTTI);
1303 
1304       LLVM_DEBUG({
1305         dbgs() << "HotCountThreshold = " << PSI.getHotCountThreshold() << "\n";
1306         dbgs() << "ColdCountThreshold = " << PSI.getColdCountThreshold()
1307                << "\n";
1308       });
1309 
1310       bool DidOutline = Cloner.doMultiRegionFunctionOutlining();
1311 
1312       if (DidOutline) {
1313         LLVM_DEBUG({
1314           dbgs() << ">>>>>> Outlined (Cloned) Function >>>>>>\n";
1315           Cloner.ClonedFunc->print(dbgs());
1316           dbgs() << "<<<<<< Outlined (Cloned) Function <<<<<<\n";
1317         });
1318 
1319         if (tryPartialInline(Cloner))
1320           return {true, nullptr};
1321       }
1322     }
1323   }
1324 
1325   // Fall-thru to regular partial inlining if we:
1326   //    i) can't find any cold regions to outline, or
1327   //   ii) can't inline the outlined function anywhere.
1328   std::unique_ptr<FunctionOutliningInfo> OI = computeOutliningInfo(F);
1329   if (!OI)
1330     return {false, nullptr};
1331 
1332   FunctionCloner Cloner(&F, OI.get(), ORE, LookupAssumptionCache, GetTTI);
1333   Cloner.normalizeReturnBlock();
1334 
1335   Function *OutlinedFunction = Cloner.doSingleRegionFunctionOutlining();
1336 
1337   if (!OutlinedFunction)
1338     return {false, nullptr};
1339 
1340   if (tryPartialInline(Cloner))
1341     return {true, OutlinedFunction};
1342 
1343   return {false, nullptr};
1344 }
1345 
1346 bool PartialInlinerImpl::tryPartialInline(FunctionCloner &Cloner) {
1347   if (Cloner.OutlinedFunctions.empty())
1348     return false;
1349 
1350   int SizeCost = 0;
1351   BlockFrequency WeightedRcost;
1352   int NonWeightedRcost;
1353   std::tie(SizeCost, NonWeightedRcost) = computeOutliningCosts(Cloner);
1354 
1355   // Only calculate RelativeToEntryFreq when we are doing single region
1356   // outlining.
1357   BranchProbability RelativeToEntryFreq;
1358   if (Cloner.ClonedOI)
1359     RelativeToEntryFreq = getOutliningCallBBRelativeFreq(Cloner);
1360   else
1361     // RelativeToEntryFreq doesn't make sense when we have more than one
1362     // outlined call because each call will have a different relative frequency
1363     // to the entry block.  We can consider using the average, but the
1364     // usefulness of that information is questionable. For now, assume we never
1365     // execute the calls to outlined functions.
1366     RelativeToEntryFreq = BranchProbability(0, 1);
1367 
1368   WeightedRcost = BlockFrequency(NonWeightedRcost) * RelativeToEntryFreq;
1369 
1370   // The call sequence(s) to the outlined function(s) are larger than the sum of
1371   // the original outlined region size(s), it does not increase the chances of
1372   // inlining the function with outlining (The inliner uses the size increase to
1373   // model the cost of inlining a callee).
1374   if (!SkipCostAnalysis && Cloner.OutlinedRegionCost < SizeCost) {
1375     OptimizationRemarkEmitter OrigFuncORE(Cloner.OrigFunc);
1376     DebugLoc DLoc;
1377     BasicBlock *Block;
1378     std::tie(DLoc, Block) = getOneDebugLoc(*Cloner.ClonedFunc);
1379     OrigFuncORE.emit([&]() {
1380       return OptimizationRemarkAnalysis(DEBUG_TYPE, "OutlineRegionTooSmall",
1381                                         DLoc, Block)
1382              << ore::NV("Function", Cloner.OrigFunc)
1383              << " not partially inlined into callers (Original Size = "
1384              << ore::NV("OutlinedRegionOriginalSize", Cloner.OutlinedRegionCost)
1385              << ", Size of call sequence to outlined function = "
1386              << ore::NV("NewSize", SizeCost) << ")";
1387     });
1388     return false;
1389   }
1390 
1391   assert(Cloner.OrigFunc->users().empty() &&
1392          "F's users should all be replaced!");
1393 
1394   std::vector<User *> Users(Cloner.ClonedFunc->user_begin(),
1395                             Cloner.ClonedFunc->user_end());
1396 
1397   DenseMap<User *, uint64_t> CallSiteToProfCountMap;
1398   auto CalleeEntryCount = Cloner.OrigFunc->getEntryCount();
1399   if (CalleeEntryCount)
1400     computeCallsiteToProfCountMap(Cloner.ClonedFunc, CallSiteToProfCountMap);
1401 
1402   uint64_t CalleeEntryCountV =
1403       (CalleeEntryCount ? CalleeEntryCount.getCount() : 0);
1404 
1405   bool AnyInline = false;
1406   for (User *User : Users) {
1407     CallBase *CB = getSupportedCallBase(User);
1408 
1409     if (isLimitReached())
1410       continue;
1411 
1412     OptimizationRemarkEmitter CallerORE(CB->getCaller());
1413     if (!shouldPartialInline(*CB, Cloner, WeightedRcost, CallerORE))
1414       continue;
1415 
1416     // Construct remark before doing the inlining, as after successful inlining
1417     // the callsite is removed.
1418     OptimizationRemark OR(DEBUG_TYPE, "PartiallyInlined", CB);
1419     OR << ore::NV("Callee", Cloner.OrigFunc) << " partially inlined into "
1420        << ore::NV("Caller", CB->getCaller());
1421 
1422     InlineFunctionInfo IFI(nullptr, GetAssumptionCache, &PSI);
1423     // We can only forward varargs when we outlined a single region, else we
1424     // bail on vararg functions.
1425     if (!InlineFunction(*CB, IFI, nullptr, true,
1426                         (Cloner.ClonedOI ? Cloner.OutlinedFunctions.back().first
1427                                          : nullptr))
1428              .isSuccess())
1429       continue;
1430 
1431     CallerORE.emit(OR);
1432 
1433     // Now update the entry count:
1434     if (CalleeEntryCountV && CallSiteToProfCountMap.count(User)) {
1435       uint64_t CallSiteCount = CallSiteToProfCountMap[User];
1436       CalleeEntryCountV -= std::min(CalleeEntryCountV, CallSiteCount);
1437     }
1438 
1439     AnyInline = true;
1440     NumPartialInlining++;
1441     // Update the stats
1442     if (Cloner.ClonedOI)
1443       NumPartialInlined++;
1444     else
1445       NumColdOutlinePartialInlined++;
1446   }
1447 
1448   if (AnyInline) {
1449     Cloner.IsFunctionInlined = true;
1450     if (CalleeEntryCount)
1451       Cloner.OrigFunc->setEntryCount(
1452           CalleeEntryCount.setCount(CalleeEntryCountV));
1453     OptimizationRemarkEmitter OrigFuncORE(Cloner.OrigFunc);
1454     OrigFuncORE.emit([&]() {
1455       return OptimizationRemark(DEBUG_TYPE, "PartiallyInlined", Cloner.OrigFunc)
1456              << "Partially inlined into at least one caller";
1457     });
1458   }
1459 
1460   return AnyInline;
1461 }
1462 
1463 bool PartialInlinerImpl::run(Module &M) {
1464   if (DisablePartialInlining)
1465     return false;
1466 
1467   std::vector<Function *> Worklist;
1468   Worklist.reserve(M.size());
1469   for (Function &F : M)
1470     if (!F.use_empty() && !F.isDeclaration())
1471       Worklist.push_back(&F);
1472 
1473   bool Changed = false;
1474   while (!Worklist.empty()) {
1475     Function *CurrFunc = Worklist.back();
1476     Worklist.pop_back();
1477 
1478     if (CurrFunc->use_empty())
1479       continue;
1480 
1481     bool Recursive = false;
1482     for (User *U : CurrFunc->users())
1483       if (Instruction *I = dyn_cast<Instruction>(U))
1484         if (I->getParent()->getParent() == CurrFunc) {
1485           Recursive = true;
1486           break;
1487         }
1488     if (Recursive)
1489       continue;
1490 
1491     std::pair<bool, Function *> Result = unswitchFunction(*CurrFunc);
1492     if (Result.second)
1493       Worklist.push_back(Result.second);
1494     Changed |= Result.first;
1495   }
1496 
1497   return Changed;
1498 }
1499 
1500 char PartialInlinerLegacyPass::ID = 0;
1501 
1502 INITIALIZE_PASS_BEGIN(PartialInlinerLegacyPass, "partial-inliner",
1503                       "Partial Inliner", false, false)
1504 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
1505 INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)
1506 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
1507 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
1508 INITIALIZE_PASS_END(PartialInlinerLegacyPass, "partial-inliner",
1509                     "Partial Inliner", false, false)
1510 
1511 ModulePass *llvm::createPartialInliningPass() {
1512   return new PartialInlinerLegacyPass();
1513 }
1514 
1515 PreservedAnalyses PartialInlinerPass::run(Module &M,
1516                                           ModuleAnalysisManager &AM) {
1517   auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
1518 
1519   auto GetAssumptionCache = [&FAM](Function &F) -> AssumptionCache & {
1520     return FAM.getResult<AssumptionAnalysis>(F);
1521   };
1522 
1523   auto LookupAssumptionCache = [&FAM](Function &F) -> AssumptionCache * {
1524     return FAM.getCachedResult<AssumptionAnalysis>(F);
1525   };
1526 
1527   auto GetBFI = [&FAM](Function &F) -> BlockFrequencyInfo & {
1528     return FAM.getResult<BlockFrequencyAnalysis>(F);
1529   };
1530 
1531   auto GetTTI = [&FAM](Function &F) -> TargetTransformInfo & {
1532     return FAM.getResult<TargetIRAnalysis>(F);
1533   };
1534 
1535   auto GetTLI = [&FAM](Function &F) -> TargetLibraryInfo & {
1536     return FAM.getResult<TargetLibraryAnalysis>(F);
1537   };
1538 
1539   ProfileSummaryInfo &PSI = AM.getResult<ProfileSummaryAnalysis>(M);
1540 
1541   if (PartialInlinerImpl(GetAssumptionCache, LookupAssumptionCache, GetTTI,
1542                          GetTLI, PSI, GetBFI)
1543           .run(M))
1544     return PreservedAnalyses::none();
1545   return PreservedAnalyses::all();
1546 }
1547