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