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