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