1 //===- HotColdSplitting.cpp -- Outline Cold Regions -------------*- C++ -*-===//
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 /// \file
10 /// The goal of hot/cold splitting is to improve the memory locality of code.
11 /// The splitting pass does this by identifying cold blocks and moving them into
12 /// separate functions.
13 ///
14 /// When the splitting pass finds a cold block (referred to as "the sink"), it
15 /// grows a maximal cold region around that block. The maximal region contains
16 /// all blocks (post-)dominated by the sink [*]. In theory, these blocks are as
17 /// cold as the sink. Once a region is found, it's split out of the original
18 /// function provided it's profitable to do so.
19 ///
20 /// [*] In practice, there is some added complexity because some blocks are not
21 /// safe to extract.
22 ///
23 /// TODO: Use the PM to get domtrees, and preserve BFI/BPI.
24 /// TODO: Reorder outlined functions.
25 ///
26 //===----------------------------------------------------------------------===//
27 
28 #include "llvm/Transforms/IPO/HotColdSplitting.h"
29 #include "llvm/ADT/PostOrderIterator.h"
30 #include "llvm/ADT/SmallVector.h"
31 #include "llvm/ADT/Statistic.h"
32 #include "llvm/Analysis/AliasAnalysis.h"
33 #include "llvm/Analysis/BlockFrequencyInfo.h"
34 #include "llvm/Analysis/BranchProbabilityInfo.h"
35 #include "llvm/Analysis/CFG.h"
36 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
37 #include "llvm/Analysis/PostDominators.h"
38 #include "llvm/Analysis/ProfileSummaryInfo.h"
39 #include "llvm/Analysis/TargetTransformInfo.h"
40 #include "llvm/IR/BasicBlock.h"
41 #include "llvm/IR/CFG.h"
42 #include "llvm/IR/DataLayout.h"
43 #include "llvm/IR/DiagnosticInfo.h"
44 #include "llvm/IR/Dominators.h"
45 #include "llvm/IR/Function.h"
46 #include "llvm/IR/Instruction.h"
47 #include "llvm/IR/Instructions.h"
48 #include "llvm/IR/IntrinsicInst.h"
49 #include "llvm/IR/Metadata.h"
50 #include "llvm/IR/Module.h"
51 #include "llvm/IR/PassManager.h"
52 #include "llvm/IR/Type.h"
53 #include "llvm/IR/Use.h"
54 #include "llvm/IR/User.h"
55 #include "llvm/IR/Value.h"
56 #include "llvm/InitializePasses.h"
57 #include "llvm/Pass.h"
58 #include "llvm/Support/BlockFrequency.h"
59 #include "llvm/Support/BranchProbability.h"
60 #include "llvm/Support/CommandLine.h"
61 #include "llvm/Support/Debug.h"
62 #include "llvm/Support/raw_ostream.h"
63 #include "llvm/Transforms/IPO.h"
64 #include "llvm/Transforms/Scalar.h"
65 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
66 #include "llvm/Transforms/Utils/Cloning.h"
67 #include "llvm/Transforms/Utils/CodeExtractor.h"
68 #include "llvm/Transforms/Utils/Local.h"
69 #include "llvm/Transforms/Utils/ValueMapper.h"
70 #include <algorithm>
71 #include <cassert>
72 
73 #define DEBUG_TYPE "hotcoldsplit"
74 
75 STATISTIC(NumColdRegionsFound, "Number of cold regions found.");
76 STATISTIC(NumColdRegionsOutlined, "Number of cold regions outlined.");
77 
78 using namespace llvm;
79 
80 static cl::opt<bool> EnableStaticAnalyis("hot-cold-static-analysis",
81                               cl::init(true), cl::Hidden);
82 
83 static cl::opt<int>
84     SplittingThreshold("hotcoldsplit-threshold", cl::init(2), cl::Hidden,
85                        cl::desc("Base penalty for splitting cold code (as a "
86                                 "multiple of TCC_Basic)"));
87 
88 namespace {
89 // Same as blockEndsInUnreachable in CodeGen/BranchFolding.cpp. Do not modify
90 // this function unless you modify the MBB version as well.
91 //
92 /// A no successor, non-return block probably ends in unreachable and is cold.
93 /// Also consider a block that ends in an indirect branch to be a return block,
94 /// since many targets use plain indirect branches to return.
95 bool blockEndsInUnreachable(const BasicBlock &BB) {
96   if (!succ_empty(&BB))
97     return false;
98   if (BB.empty())
99     return true;
100   const Instruction *I = BB.getTerminator();
101   return !(isa<ReturnInst>(I) || isa<IndirectBrInst>(I));
102 }
103 
104 bool unlikelyExecuted(BasicBlock &BB, ProfileSummaryInfo *PSI,
105                       BlockFrequencyInfo *BFI) {
106   // Exception handling blocks are unlikely executed.
107   if (BB.isEHPad() || isa<ResumeInst>(BB.getTerminator()))
108     return true;
109 
110   // The block is cold if it calls/invokes a cold function. However, do not
111   // mark sanitizer traps as cold.
112   for (Instruction &I : BB)
113     if (auto *CB = dyn_cast<CallBase>(&I))
114       if (CB->hasFnAttr(Attribute::Cold) && !CB->getMetadata("nosanitize"))
115         return true;
116 
117   // The block is cold if it has an unreachable terminator, unless it's
118   // preceded by a call to a (possibly warm) noreturn call (e.g. longjmp);
119   // in the case of a longjmp, if the block is cold according to
120   // profile information, we mark it as unlikely to be executed as well.
121   if (blockEndsInUnreachable(BB)) {
122     if (auto *CI =
123             dyn_cast_or_null<CallInst>(BB.getTerminator()->getPrevNode()))
124       if (CI->hasFnAttr(Attribute::NoReturn)) {
125         if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI))
126           return (II->getIntrinsicID() != Intrinsic::eh_sjlj_longjmp) ||
127                  (BFI && PSI->isColdBlock(&BB, BFI));
128         return !CI->getCalledFunction()->getName().contains("longjmp") ||
129                (BFI && PSI->isColdBlock(&BB, BFI));
130       }
131     return true;
132   }
133 
134   return false;
135 }
136 
137 /// Check whether it's safe to outline \p BB.
138 static bool mayExtractBlock(const BasicBlock &BB) {
139   // EH pads are unsafe to outline because doing so breaks EH type tables. It
140   // follows that invoke instructions cannot be extracted, because CodeExtractor
141   // requires unwind destinations to be within the extraction region.
142   //
143   // Resumes that are not reachable from a cleanup landing pad are considered to
144   // be unreachable. It’s not safe to split them out either.
145   auto Term = BB.getTerminator();
146   return !BB.hasAddressTaken() && !BB.isEHPad() && !isa<InvokeInst>(Term) &&
147          !isa<ResumeInst>(Term);
148 }
149 
150 /// Mark \p F cold. Based on this assumption, also optimize it for minimum size.
151 /// If \p UpdateEntryCount is true (set when this is a new split function and
152 /// module has profile data), set entry count to 0 to ensure treated as cold.
153 /// Return true if the function is changed.
154 static bool markFunctionCold(Function &F, bool UpdateEntryCount = false) {
155   assert(!F.hasOptNone() && "Can't mark this cold");
156   bool Changed = false;
157   if (!F.hasFnAttribute(Attribute::Cold)) {
158     F.addFnAttr(Attribute::Cold);
159     Changed = true;
160   }
161   if (!F.hasFnAttribute(Attribute::MinSize)) {
162     F.addFnAttr(Attribute::MinSize);
163     Changed = true;
164   }
165   if (UpdateEntryCount) {
166     // Set the entry count to 0 to ensure it is placed in the unlikely text
167     // section when function sections are enabled.
168     F.setEntryCount(0);
169     Changed = true;
170   }
171 
172   return Changed;
173 }
174 
175 class HotColdSplittingLegacyPass : public ModulePass {
176 public:
177   static char ID;
178   HotColdSplittingLegacyPass() : ModulePass(ID) {
179     initializeHotColdSplittingLegacyPassPass(*PassRegistry::getPassRegistry());
180   }
181 
182   void getAnalysisUsage(AnalysisUsage &AU) const override {
183     AU.addRequired<BlockFrequencyInfoWrapperPass>();
184     AU.addRequired<ProfileSummaryInfoWrapperPass>();
185     AU.addRequired<TargetTransformInfoWrapperPass>();
186     AU.addUsedIfAvailable<AssumptionCacheTracker>();
187   }
188 
189   bool runOnModule(Module &M) override;
190 };
191 
192 } // end anonymous namespace
193 
194 /// Check whether \p F is inherently cold.
195 bool HotColdSplitting::isFunctionCold(const Function &F) const {
196   if (F.hasFnAttribute(Attribute::Cold))
197     return true;
198 
199   if (F.getCallingConv() == CallingConv::Cold)
200     return true;
201 
202   if (PSI->isFunctionEntryCold(&F))
203     return true;
204 
205   return false;
206 }
207 
208 // Returns false if the function should not be considered for hot-cold split
209 // optimization.
210 bool HotColdSplitting::shouldOutlineFrom(const Function &F) const {
211   if (F.hasFnAttribute(Attribute::AlwaysInline))
212     return false;
213 
214   if (F.hasFnAttribute(Attribute::NoInline))
215     return false;
216 
217   // A function marked `noreturn` may contain unreachable terminators: these
218   // should not be considered cold, as the function may be a trampoline.
219   if (F.hasFnAttribute(Attribute::NoReturn))
220     return false;
221 
222   if (F.hasFnAttribute(Attribute::SanitizeAddress) ||
223       F.hasFnAttribute(Attribute::SanitizeHWAddress) ||
224       F.hasFnAttribute(Attribute::SanitizeThread) ||
225       F.hasFnAttribute(Attribute::SanitizeMemory))
226     return false;
227 
228   return true;
229 }
230 
231 /// Get the benefit score of outlining \p Region.
232 static int getOutliningBenefit(ArrayRef<BasicBlock *> Region,
233                                TargetTransformInfo &TTI) {
234   // Sum up the code size costs of non-terminator instructions. Tight coupling
235   // with \ref getOutliningPenalty is needed to model the costs of terminators.
236   int Benefit = 0;
237   for (BasicBlock *BB : Region)
238     for (Instruction &I : BB->instructionsWithoutDebug())
239       if (&I != BB->getTerminator())
240         Benefit +=
241             TTI.getInstructionCost(&I, TargetTransformInfo::TCK_CodeSize);
242 
243   return Benefit;
244 }
245 
246 /// Get the penalty score for outlining \p Region.
247 static int getOutliningPenalty(ArrayRef<BasicBlock *> Region,
248                                unsigned NumInputs, unsigned NumOutputs) {
249   int Penalty = SplittingThreshold;
250   LLVM_DEBUG(dbgs() << "Applying penalty for splitting: " << Penalty << "\n");
251 
252   // If the splitting threshold is set at or below zero, skip the usual
253   // profitability check.
254   if (SplittingThreshold <= 0)
255     return Penalty;
256 
257   // The typical code size cost for materializing an argument for the outlined
258   // call.
259   LLVM_DEBUG(dbgs() << "Applying penalty for: " << NumInputs << " inputs\n");
260   const int CostForArgMaterialization = TargetTransformInfo::TCC_Basic;
261   Penalty += CostForArgMaterialization * NumInputs;
262 
263   // The typical code size cost for an output alloca, its associated store, and
264   // its associated reload.
265   LLVM_DEBUG(dbgs() << "Applying penalty for: " << NumOutputs << " outputs\n");
266   const int CostForRegionOutput = 3 * TargetTransformInfo::TCC_Basic;
267   Penalty += CostForRegionOutput * NumOutputs;
268 
269   // Find the number of distinct exit blocks for the region. Use a conservative
270   // check to determine whether control returns from the region.
271   bool NoBlocksReturn = true;
272   SmallPtrSet<BasicBlock *, 2> SuccsOutsideRegion;
273   for (BasicBlock *BB : Region) {
274     // If a block has no successors, only assume it does not return if it's
275     // unreachable.
276     if (succ_empty(BB)) {
277       NoBlocksReturn &= isa<UnreachableInst>(BB->getTerminator());
278       continue;
279     }
280 
281     for (BasicBlock *SuccBB : successors(BB)) {
282       if (find(Region, SuccBB) == Region.end()) {
283         NoBlocksReturn = false;
284         SuccsOutsideRegion.insert(SuccBB);
285       }
286     }
287   }
288 
289   // Apply a `noreturn` bonus.
290   if (NoBlocksReturn) {
291     LLVM_DEBUG(dbgs() << "Applying bonus for: " << Region.size()
292                       << " non-returning terminators\n");
293     Penalty -= Region.size();
294   }
295 
296   // Apply a penalty for having more than one successor outside of the region.
297   // This penalty accounts for the switch needed in the caller.
298   if (!SuccsOutsideRegion.empty()) {
299     LLVM_DEBUG(dbgs() << "Applying penalty for: " << SuccsOutsideRegion.size()
300                       << " non-region successors\n");
301     Penalty += (SuccsOutsideRegion.size() - 1) * TargetTransformInfo::TCC_Basic;
302   }
303 
304   return Penalty;
305 }
306 
307 Function *HotColdSplitting::extractColdRegion(
308     const BlockSequence &Region, const CodeExtractorAnalysisCache &CEAC,
309     DominatorTree &DT, BlockFrequencyInfo *BFI, TargetTransformInfo &TTI,
310     OptimizationRemarkEmitter &ORE, AssumptionCache *AC, unsigned Count) {
311   assert(!Region.empty());
312 
313   // TODO: Pass BFI and BPI to update profile information.
314   CodeExtractor CE(Region, &DT, /* AggregateArgs */ false, /* BFI */ nullptr,
315                    /* BPI */ nullptr, AC, /* AllowVarArgs */ false,
316                    /* AllowAlloca */ false,
317                    /* Suffix */ "cold." + std::to_string(Count));
318 
319   // Perform a simple cost/benefit analysis to decide whether or not to permit
320   // splitting.
321   SetVector<Value *> Inputs, Outputs, Sinks;
322   CE.findInputsOutputs(Inputs, Outputs, Sinks);
323   int OutliningBenefit = getOutliningBenefit(Region, TTI);
324   int OutliningPenalty =
325       getOutliningPenalty(Region, Inputs.size(), Outputs.size());
326   LLVM_DEBUG(dbgs() << "Split profitability: benefit = " << OutliningBenefit
327                     << ", penalty = " << OutliningPenalty << "\n");
328   if (OutliningBenefit <= OutliningPenalty)
329     return nullptr;
330 
331   Function *OrigF = Region[0]->getParent();
332   if (Function *OutF = CE.extractCodeRegion(CEAC)) {
333     User *U = *OutF->user_begin();
334     CallInst *CI = cast<CallInst>(U);
335     NumColdRegionsOutlined++;
336     if (TTI.useColdCCForColdCall(*OutF)) {
337       OutF->setCallingConv(CallingConv::Cold);
338       CI->setCallingConv(CallingConv::Cold);
339     }
340     CI->setIsNoInline();
341 
342     if (OrigF->hasSection())
343       OutF->setSection(OrigF->getSection());
344 
345     markFunctionCold(*OutF, BFI != nullptr);
346 
347     LLVM_DEBUG(llvm::dbgs() << "Outlined Region: " << *OutF);
348     ORE.emit([&]() {
349       return OptimizationRemark(DEBUG_TYPE, "HotColdSplit",
350                                 &*Region[0]->begin())
351              << ore::NV("Original", OrigF) << " split cold code into "
352              << ore::NV("Split", OutF);
353     });
354     return OutF;
355   }
356 
357   ORE.emit([&]() {
358     return OptimizationRemarkMissed(DEBUG_TYPE, "ExtractFailed",
359                                     &*Region[0]->begin())
360            << "Failed to extract region at block "
361            << ore::NV("Block", Region.front());
362   });
363   return nullptr;
364 }
365 
366 /// A pair of (basic block, score).
367 using BlockTy = std::pair<BasicBlock *, unsigned>;
368 
369 namespace {
370 /// A maximal outlining region. This contains all blocks post-dominated by a
371 /// sink block, the sink block itself, and all blocks dominated by the sink.
372 /// If sink-predecessors and sink-successors cannot be extracted in one region,
373 /// the static constructor returns a list of suitable extraction regions.
374 class OutliningRegion {
375   /// A list of (block, score) pairs. A block's score is non-zero iff it's a
376   /// viable sub-region entry point. Blocks with higher scores are better entry
377   /// points (i.e. they are more distant ancestors of the sink block).
378   SmallVector<BlockTy, 0> Blocks = {};
379 
380   /// The suggested entry point into the region. If the region has multiple
381   /// entry points, all blocks within the region may not be reachable from this
382   /// entry point.
383   BasicBlock *SuggestedEntryPoint = nullptr;
384 
385   /// Whether the entire function is cold.
386   bool EntireFunctionCold = false;
387 
388   /// If \p BB is a viable entry point, return \p Score. Return 0 otherwise.
389   static unsigned getEntryPointScore(BasicBlock &BB, unsigned Score) {
390     return mayExtractBlock(BB) ? Score : 0;
391   }
392 
393   /// These scores should be lower than the score for predecessor blocks,
394   /// because regions starting at predecessor blocks are typically larger.
395   static constexpr unsigned ScoreForSuccBlock = 1;
396   static constexpr unsigned ScoreForSinkBlock = 1;
397 
398   OutliningRegion(const OutliningRegion &) = delete;
399   OutliningRegion &operator=(const OutliningRegion &) = delete;
400 
401 public:
402   OutliningRegion() = default;
403   OutliningRegion(OutliningRegion &&) = default;
404   OutliningRegion &operator=(OutliningRegion &&) = default;
405 
406   static std::vector<OutliningRegion> create(BasicBlock &SinkBB,
407                                              const DominatorTree &DT,
408                                              const PostDominatorTree &PDT) {
409     std::vector<OutliningRegion> Regions;
410     SmallPtrSet<BasicBlock *, 4> RegionBlocks;
411 
412     Regions.emplace_back();
413     OutliningRegion *ColdRegion = &Regions.back();
414 
415     auto addBlockToRegion = [&](BasicBlock *BB, unsigned Score) {
416       RegionBlocks.insert(BB);
417       ColdRegion->Blocks.emplace_back(BB, Score);
418     };
419 
420     // The ancestor farthest-away from SinkBB, and also post-dominated by it.
421     unsigned SinkScore = getEntryPointScore(SinkBB, ScoreForSinkBlock);
422     ColdRegion->SuggestedEntryPoint = (SinkScore > 0) ? &SinkBB : nullptr;
423     unsigned BestScore = SinkScore;
424 
425     // Visit SinkBB's ancestors using inverse DFS.
426     auto PredIt = ++idf_begin(&SinkBB);
427     auto PredEnd = idf_end(&SinkBB);
428     while (PredIt != PredEnd) {
429       BasicBlock &PredBB = **PredIt;
430       bool SinkPostDom = PDT.dominates(&SinkBB, &PredBB);
431 
432       // If the predecessor is cold and has no predecessors, the entire
433       // function must be cold.
434       if (SinkPostDom && pred_empty(&PredBB)) {
435         ColdRegion->EntireFunctionCold = true;
436         return Regions;
437       }
438 
439       // If SinkBB does not post-dominate a predecessor, do not mark the
440       // predecessor (or any of its predecessors) cold.
441       if (!SinkPostDom || !mayExtractBlock(PredBB)) {
442         PredIt.skipChildren();
443         continue;
444       }
445 
446       // Keep track of the post-dominated ancestor farthest away from the sink.
447       // The path length is always >= 2, ensuring that predecessor blocks are
448       // considered as entry points before the sink block.
449       unsigned PredScore = getEntryPointScore(PredBB, PredIt.getPathLength());
450       if (PredScore > BestScore) {
451         ColdRegion->SuggestedEntryPoint = &PredBB;
452         BestScore = PredScore;
453       }
454 
455       addBlockToRegion(&PredBB, PredScore);
456       ++PredIt;
457     }
458 
459     // If the sink can be added to the cold region, do so. It's considered as
460     // an entry point before any sink-successor blocks.
461     //
462     // Otherwise, split cold sink-successor blocks using a separate region.
463     // This satisfies the requirement that all extraction blocks other than the
464     // first have predecessors within the extraction region.
465     if (mayExtractBlock(SinkBB)) {
466       addBlockToRegion(&SinkBB, SinkScore);
467       if (pred_empty(&SinkBB)) {
468         ColdRegion->EntireFunctionCold = true;
469         return Regions;
470       }
471     } else {
472       Regions.emplace_back();
473       ColdRegion = &Regions.back();
474       BestScore = 0;
475     }
476 
477     // Find all successors of SinkBB dominated by SinkBB using DFS.
478     auto SuccIt = ++df_begin(&SinkBB);
479     auto SuccEnd = df_end(&SinkBB);
480     while (SuccIt != SuccEnd) {
481       BasicBlock &SuccBB = **SuccIt;
482       bool SinkDom = DT.dominates(&SinkBB, &SuccBB);
483 
484       // Don't allow the backwards & forwards DFSes to mark the same block.
485       bool DuplicateBlock = RegionBlocks.count(&SuccBB);
486 
487       // If SinkBB does not dominate a successor, do not mark the successor (or
488       // any of its successors) cold.
489       if (DuplicateBlock || !SinkDom || !mayExtractBlock(SuccBB)) {
490         SuccIt.skipChildren();
491         continue;
492       }
493 
494       unsigned SuccScore = getEntryPointScore(SuccBB, ScoreForSuccBlock);
495       if (SuccScore > BestScore) {
496         ColdRegion->SuggestedEntryPoint = &SuccBB;
497         BestScore = SuccScore;
498       }
499 
500       addBlockToRegion(&SuccBB, SuccScore);
501       ++SuccIt;
502     }
503 
504     return Regions;
505   }
506 
507   /// Whether this region has nothing to extract.
508   bool empty() const { return !SuggestedEntryPoint; }
509 
510   /// The blocks in this region.
511   ArrayRef<std::pair<BasicBlock *, unsigned>> blocks() const { return Blocks; }
512 
513   /// Whether the entire function containing this region is cold.
514   bool isEntireFunctionCold() const { return EntireFunctionCold; }
515 
516   /// Remove a sub-region from this region and return it as a block sequence.
517   BlockSequence takeSingleEntrySubRegion(DominatorTree &DT) {
518     assert(!empty() && !isEntireFunctionCold() && "Nothing to extract");
519 
520     // Remove blocks dominated by the suggested entry point from this region.
521     // During the removal, identify the next best entry point into the region.
522     // Ensure that the first extracted block is the suggested entry point.
523     BlockSequence SubRegion = {SuggestedEntryPoint};
524     BasicBlock *NextEntryPoint = nullptr;
525     unsigned NextScore = 0;
526     auto RegionEndIt = Blocks.end();
527     auto RegionStartIt = remove_if(Blocks, [&](const BlockTy &Block) {
528       BasicBlock *BB = Block.first;
529       unsigned Score = Block.second;
530       bool InSubRegion =
531           BB == SuggestedEntryPoint || DT.dominates(SuggestedEntryPoint, BB);
532       if (!InSubRegion && Score > NextScore) {
533         NextEntryPoint = BB;
534         NextScore = Score;
535       }
536       if (InSubRegion && BB != SuggestedEntryPoint)
537         SubRegion.push_back(BB);
538       return InSubRegion;
539     });
540     Blocks.erase(RegionStartIt, RegionEndIt);
541 
542     // Update the suggested entry point.
543     SuggestedEntryPoint = NextEntryPoint;
544 
545     return SubRegion;
546   }
547 };
548 } // namespace
549 
550 bool HotColdSplitting::outlineColdRegions(Function &F, bool HasProfileSummary) {
551   bool Changed = false;
552 
553   // The set of cold blocks.
554   SmallPtrSet<BasicBlock *, 4> ColdBlocks;
555 
556   // The worklist of non-intersecting regions left to outline.
557   SmallVector<OutliningRegion, 2> OutliningWorklist;
558 
559   // Set up an RPO traversal. Experimentally, this performs better (outlines
560   // more) than a PO traversal, because we prevent region overlap by keeping
561   // the first region to contain a block.
562   ReversePostOrderTraversal<Function *> RPOT(&F);
563 
564   // Calculate domtrees lazily. This reduces compile-time significantly.
565   std::unique_ptr<DominatorTree> DT;
566   std::unique_ptr<PostDominatorTree> PDT;
567 
568   // Calculate BFI lazily (it's only used to query ProfileSummaryInfo). This
569   // reduces compile-time significantly. TODO: When we *do* use BFI, we should
570   // be able to salvage its domtrees instead of recomputing them.
571   BlockFrequencyInfo *BFI = nullptr;
572   if (HasProfileSummary)
573     BFI = GetBFI(F);
574 
575   TargetTransformInfo &TTI = GetTTI(F);
576   OptimizationRemarkEmitter &ORE = (*GetORE)(F);
577   AssumptionCache *AC = LookupAC(F);
578 
579   // Find all cold regions.
580   for (BasicBlock *BB : RPOT) {
581     // This block is already part of some outlining region.
582     if (ColdBlocks.count(BB))
583       continue;
584 
585     bool Cold = (BFI && PSI->isColdBlock(BB, BFI)) ||
586                 (EnableStaticAnalyis && unlikelyExecuted(*BB, PSI, BFI));
587     if (!Cold)
588       continue;
589 
590     LLVM_DEBUG({
591       dbgs() << "Found a cold block:\n";
592       BB->dump();
593     });
594 
595     if (!DT)
596       DT = std::make_unique<DominatorTree>(F);
597     if (!PDT)
598       PDT = std::make_unique<PostDominatorTree>(F);
599 
600     auto Regions = OutliningRegion::create(*BB, *DT, *PDT);
601     for (OutliningRegion &Region : Regions) {
602       if (Region.empty())
603         continue;
604 
605       if (Region.isEntireFunctionCold()) {
606         LLVM_DEBUG(dbgs() << "Entire function is cold\n");
607         return markFunctionCold(F);
608       }
609 
610       // If this outlining region intersects with another, drop the new region.
611       //
612       // TODO: It's theoretically possible to outline more by only keeping the
613       // largest region which contains a block, but the extra bookkeeping to do
614       // this is tricky/expensive.
615       bool RegionsOverlap = any_of(Region.blocks(), [&](const BlockTy &Block) {
616         return !ColdBlocks.insert(Block.first).second;
617       });
618       if (RegionsOverlap)
619         continue;
620 
621       OutliningWorklist.emplace_back(std::move(Region));
622       ++NumColdRegionsFound;
623     }
624   }
625 
626   if (OutliningWorklist.empty())
627     return Changed;
628 
629   // Outline single-entry cold regions, splitting up larger regions as needed.
630   unsigned OutlinedFunctionID = 1;
631   // Cache and recycle the CodeExtractor analysis to avoid O(n^2) compile-time.
632   CodeExtractorAnalysisCache CEAC(F);
633   do {
634     OutliningRegion Region = OutliningWorklist.pop_back_val();
635     assert(!Region.empty() && "Empty outlining region in worklist");
636     do {
637       BlockSequence SubRegion = Region.takeSingleEntrySubRegion(*DT);
638       LLVM_DEBUG({
639         dbgs() << "Hot/cold splitting attempting to outline these blocks:\n";
640         for (BasicBlock *BB : SubRegion)
641           BB->dump();
642       });
643 
644       Function *Outlined = extractColdRegion(SubRegion, CEAC, *DT, BFI, TTI,
645                                              ORE, AC, OutlinedFunctionID);
646       if (Outlined) {
647         ++OutlinedFunctionID;
648         Changed = true;
649       }
650     } while (!Region.empty());
651   } while (!OutliningWorklist.empty());
652 
653   return Changed;
654 }
655 
656 bool HotColdSplitting::run(Module &M) {
657   bool Changed = false;
658   bool HasProfileSummary = (M.getProfileSummary(/* IsCS */ false) != nullptr);
659   for (auto It = M.begin(), End = M.end(); It != End; ++It) {
660     Function &F = *It;
661 
662     // Do not touch declarations.
663     if (F.isDeclaration())
664       continue;
665 
666     // Do not modify `optnone` functions.
667     if (F.hasOptNone())
668       continue;
669 
670     // Detect inherently cold functions and mark them as such.
671     if (isFunctionCold(F)) {
672       Changed |= markFunctionCold(F);
673       continue;
674     }
675 
676     if (!shouldOutlineFrom(F)) {
677       LLVM_DEBUG(llvm::dbgs() << "Skipping " << F.getName() << "\n");
678       continue;
679     }
680 
681     LLVM_DEBUG(llvm::dbgs() << "Outlining in " << F.getName() << "\n");
682     Changed |= outlineColdRegions(F, HasProfileSummary);
683   }
684   return Changed;
685 }
686 
687 bool HotColdSplittingLegacyPass::runOnModule(Module &M) {
688   if (skipModule(M))
689     return false;
690   ProfileSummaryInfo *PSI =
691       &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
692   auto GTTI = [this](Function &F) -> TargetTransformInfo & {
693     return this->getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
694   };
695   auto GBFI = [this](Function &F) {
696     return &this->getAnalysis<BlockFrequencyInfoWrapperPass>(F).getBFI();
697   };
698   std::unique_ptr<OptimizationRemarkEmitter> ORE;
699   std::function<OptimizationRemarkEmitter &(Function &)> GetORE =
700       [&ORE](Function &F) -> OptimizationRemarkEmitter & {
701     ORE.reset(new OptimizationRemarkEmitter(&F));
702     return *ORE.get();
703   };
704   auto LookupAC = [this](Function &F) -> AssumptionCache * {
705     if (auto *ACT = getAnalysisIfAvailable<AssumptionCacheTracker>())
706       return ACT->lookupAssumptionCache(F);
707     return nullptr;
708   };
709 
710   return HotColdSplitting(PSI, GBFI, GTTI, &GetORE, LookupAC).run(M);
711 }
712 
713 PreservedAnalyses
714 HotColdSplittingPass::run(Module &M, ModuleAnalysisManager &AM) {
715   auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
716 
717   auto LookupAC = [&FAM](Function &F) -> AssumptionCache * {
718     return FAM.getCachedResult<AssumptionAnalysis>(F);
719   };
720 
721   auto GBFI = [&FAM](Function &F) {
722     return &FAM.getResult<BlockFrequencyAnalysis>(F);
723   };
724 
725   std::function<TargetTransformInfo &(Function &)> GTTI =
726       [&FAM](Function &F) -> TargetTransformInfo & {
727     return FAM.getResult<TargetIRAnalysis>(F);
728   };
729 
730   std::unique_ptr<OptimizationRemarkEmitter> ORE;
731   std::function<OptimizationRemarkEmitter &(Function &)> GetORE =
732       [&ORE](Function &F) -> OptimizationRemarkEmitter & {
733     ORE.reset(new OptimizationRemarkEmitter(&F));
734     return *ORE.get();
735   };
736 
737   ProfileSummaryInfo *PSI = &AM.getResult<ProfileSummaryAnalysis>(M);
738 
739   if (HotColdSplitting(PSI, GBFI, GTTI, &GetORE, LookupAC).run(M))
740     return PreservedAnalyses::none();
741   return PreservedAnalyses::all();
742 }
743 
744 char HotColdSplittingLegacyPass::ID = 0;
745 INITIALIZE_PASS_BEGIN(HotColdSplittingLegacyPass, "hotcoldsplit",
746                       "Hot Cold Splitting", false, false)
747 INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)
748 INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
749 INITIALIZE_PASS_END(HotColdSplittingLegacyPass, "hotcoldsplit",
750                     "Hot Cold Splitting", false, false)
751 
752 ModulePass *llvm::createHotColdSplittingPass() {
753   return new HotColdSplittingLegacyPass();
754 }
755