1801394a3SAditya Kumar //===- HotColdSplitting.cpp -- Outline Cold Regions -------------*- C++ -*-===//
2801394a3SAditya Kumar //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6801394a3SAditya Kumar //
7801394a3SAditya Kumar //===----------------------------------------------------------------------===//
89d70f2b9SVedant Kumar ///
99d70f2b9SVedant Kumar /// \file
109d70f2b9SVedant Kumar /// The goal of hot/cold splitting is to improve the memory locality of code.
119d70f2b9SVedant Kumar /// The splitting pass does this by identifying cold blocks and moving them into
129d70f2b9SVedant Kumar /// separate functions.
139d70f2b9SVedant Kumar ///
149d70f2b9SVedant Kumar /// When the splitting pass finds a cold block (referred to as "the sink"), it
159d70f2b9SVedant Kumar /// grows a maximal cold region around that block. The maximal region contains
169d70f2b9SVedant Kumar /// all blocks (post-)dominated by the sink [*]. In theory, these blocks are as
179d70f2b9SVedant Kumar /// cold as the sink. Once a region is found, it's split out of the original
189d70f2b9SVedant Kumar /// function provided it's profitable to do so.
199d70f2b9SVedant Kumar ///
209d70f2b9SVedant Kumar /// [*] In practice, there is some added complexity because some blocks are not
219d70f2b9SVedant Kumar /// safe to extract.
229d70f2b9SVedant Kumar ///
239d70f2b9SVedant Kumar /// TODO: Use the PM to get domtrees, and preserve BFI/BPI.
249d70f2b9SVedant Kumar /// TODO: Reorder outlined functions.
259d70f2b9SVedant Kumar ///
26801394a3SAditya Kumar //===----------------------------------------------------------------------===//
27801394a3SAditya Kumar 
2805da2fe5SReid Kleckner #include "llvm/Transforms/IPO/HotColdSplitting.h"
2903aaa3e2SVedant Kumar #include "llvm/ADT/PostOrderIterator.h"
30801394a3SAditya Kumar #include "llvm/ADT/SmallVector.h"
31801394a3SAditya Kumar #include "llvm/ADT/Statistic.h"
32f1985a3fSserge-sans-paille #include "llvm/Analysis/AssumptionCache.h"
33801394a3SAditya Kumar #include "llvm/Analysis/BlockFrequencyInfo.h"
34801394a3SAditya Kumar #include "llvm/Analysis/OptimizationRemarkEmitter.h"
35801394a3SAditya Kumar #include "llvm/Analysis/PostDominators.h"
36801394a3SAditya Kumar #include "llvm/Analysis/ProfileSummaryInfo.h"
37a1f20fccSSebastian Pop #include "llvm/Analysis/TargetTransformInfo.h"
38801394a3SAditya Kumar #include "llvm/IR/BasicBlock.h"
39801394a3SAditya Kumar #include "llvm/IR/CFG.h"
40801394a3SAditya Kumar #include "llvm/IR/DiagnosticInfo.h"
41801394a3SAditya Kumar #include "llvm/IR/Dominators.h"
42801394a3SAditya Kumar #include "llvm/IR/Function.h"
43801394a3SAditya Kumar #include "llvm/IR/Instruction.h"
44801394a3SAditya Kumar #include "llvm/IR/Instructions.h"
45801394a3SAditya Kumar #include "llvm/IR/Module.h"
46801394a3SAditya Kumar #include "llvm/IR/PassManager.h"
47801394a3SAditya Kumar #include "llvm/IR/User.h"
48801394a3SAditya Kumar #include "llvm/IR/Value.h"
4905da2fe5SReid Kleckner #include "llvm/InitializePasses.h"
50801394a3SAditya Kumar #include "llvm/Pass.h"
514c1a1d3cSReid Kleckner #include "llvm/Support/CommandLine.h"
52801394a3SAditya Kumar #include "llvm/Support/Debug.h"
53801394a3SAditya Kumar #include "llvm/Support/raw_ostream.h"
54801394a3SAditya Kumar #include "llvm/Transforms/IPO.h"
55801394a3SAditya Kumar #include "llvm/Transforms/Utils/CodeExtractor.h"
56801394a3SAditya Kumar #include <algorithm>
57801394a3SAditya Kumar #include <cassert>
58f1985a3fSserge-sans-paille #include <limits>
5953ac1448SAditya Kumar #include <string>
60801394a3SAditya Kumar 
61801394a3SAditya Kumar #define DEBUG_TYPE "hotcoldsplit"
62801394a3SAditya Kumar 
63c2990068SVedant Kumar STATISTIC(NumColdRegionsFound, "Number of cold regions found.");
64c2990068SVedant Kumar STATISTIC(NumColdRegionsOutlined, "Number of cold regions outlined.");
65801394a3SAditya Kumar 
66801394a3SAditya Kumar using namespace llvm;
67801394a3SAditya Kumar 
68f902a7ecSAditya Kumar static cl::opt<bool> EnableStaticAnalysis("hot-cold-static-analysis",
69801394a3SAditya Kumar                                           cl::init(true), cl::Hidden);
70801394a3SAditya Kumar 
71d2a895a9SVedant Kumar static cl::opt<int>
72db3f9774SVedant Kumar     SplittingThreshold("hotcoldsplit-threshold", cl::init(2), cl::Hidden,
73db3f9774SVedant Kumar                        cl::desc("Base penalty for splitting cold code (as a "
74db3f9774SVedant Kumar                                 "multiple of TCC_Basic)"));
75801394a3SAditya Kumar 
7653ac1448SAditya Kumar static cl::opt<bool> EnableColdSection(
7753ac1448SAditya Kumar     "enable-cold-section", cl::init(false), cl::Hidden,
7853ac1448SAditya Kumar     cl::desc("Enable placement of extracted cold functions"
7953ac1448SAditya Kumar              " into a separate section after hot-cold splitting."));
8053ac1448SAditya Kumar 
8153ac1448SAditya Kumar static cl::opt<std::string>
8253ac1448SAditya Kumar     ColdSectionName("hotcoldsplit-cold-section-name", cl::init("__llvm_cold"),
8353ac1448SAditya Kumar                     cl::Hidden,
8453ac1448SAditya Kumar                     cl::desc("Name for the section containing cold functions "
8553ac1448SAditya Kumar                              "extracted by hot-cold splitting."));
8653ac1448SAditya Kumar 
871ab4db0fSAditya Kumar static cl::opt<int> MaxParametersForSplit(
881ab4db0fSAditya Kumar     "hotcoldsplit-max-params", cl::init(4), cl::Hidden,
891ab4db0fSAditya Kumar     cl::desc("Maximum number of parameters for a split function"));
901ab4db0fSAditya Kumar 
91801394a3SAditya Kumar namespace {
92542e522bSSebastian Pop // Same as blockEndsInUnreachable in CodeGen/BranchFolding.cpp. Do not modify
93542e522bSSebastian Pop // this function unless you modify the MBB version as well.
94542e522bSSebastian Pop //
95542e522bSSebastian Pop /// A no successor, non-return block probably ends in unreachable and is cold.
96542e522bSSebastian Pop /// Also consider a block that ends in an indirect branch to be a return block,
97542e522bSSebastian Pop /// since many targets use plain indirect branches to return.
blockEndsInUnreachable(const BasicBlock & BB)98801394a3SAditya Kumar bool blockEndsInUnreachable(const BasicBlock &BB) {
99542e522bSSebastian Pop   if (!succ_empty(&BB))
100542e522bSSebastian Pop     return false;
101801394a3SAditya Kumar   if (BB.empty())
102801394a3SAditya Kumar     return true;
103edb12a83SChandler Carruth   const Instruction *I = BB.getTerminator();
104542e522bSSebastian Pop   return !(isa<ReturnInst>(I) || isa<IndirectBrInst>(I));
105801394a3SAditya Kumar }
106801394a3SAditya Kumar 
unlikelyExecuted(BasicBlock & BB)1079afb1c56SVedant Kumar bool unlikelyExecuted(BasicBlock &BB) {
108801394a3SAditya Kumar   // Exception handling blocks are unlikely executed.
109b70e20dbSVedant Kumar   if (BB.isEHPad() || isa<ResumeInst>(BB.getTerminator()))
110801394a3SAditya Kumar     return true;
11103f9f15bSVedant Kumar 
11273522d16SVedant Kumar   // The block is cold if it calls/invokes a cold function. However, do not
11373522d16SVedant Kumar   // mark sanitizer traps as cold.
11403f9f15bSVedant Kumar   for (Instruction &I : BB)
115447e2c30SMircea Trofin     if (auto *CB = dyn_cast<CallBase>(&I))
116*52992f13SEnna1       if (CB->hasFnAttr(Attribute::Cold) &&
117*52992f13SEnna1           !CB->getMetadata(LLVMContext::MD_nosanitize))
118801394a3SAditya Kumar         return true;
119801394a3SAditya Kumar 
12003f9f15bSVedant Kumar   // The block is cold if it has an unreachable terminator, unless it's
1219afb1c56SVedant Kumar   // preceded by a call to a (possibly warm) noreturn call (e.g. longjmp).
12203f9f15bSVedant Kumar   if (blockEndsInUnreachable(BB)) {
12303f9f15bSVedant Kumar     if (auto *CI =
12403f9f15bSVedant Kumar             dyn_cast_or_null<CallInst>(BB.getTerminator()->getPrevNode()))
1259afb1c56SVedant Kumar       if (CI->hasFnAttr(Attribute::NoReturn))
1269afb1c56SVedant Kumar         return false;
12703f9f15bSVedant Kumar     return true;
128801394a3SAditya Kumar   }
12903f9f15bSVedant Kumar 
130801394a3SAditya Kumar   return false;
131801394a3SAditya Kumar }
132801394a3SAditya Kumar 
133c2990068SVedant Kumar /// Check whether it's safe to outline \p BB.
mayExtractBlock(const BasicBlock & BB)134c2990068SVedant Kumar static bool mayExtractBlock(const BasicBlock &BB) {
13565de025dSVedant Kumar   // EH pads are unsafe to outline because doing so breaks EH type tables. It
13665de025dSVedant Kumar   // follows that invoke instructions cannot be extracted, because CodeExtractor
13765de025dSVedant Kumar   // requires unwind destinations to be within the extraction region.
138bd94b428SVedant Kumar   //
139bd94b428SVedant Kumar   // Resumes that are not reachable from a cleanup landing pad are considered to
140bd94b428SVedant Kumar   // be unreachable. It’s not safe to split them out either.
141dcbbc69cSAditya Kumar   if (BB.hasAddressTaken() || BB.isEHPad())
142dcbbc69cSAditya Kumar     return false;
143bd94b428SVedant Kumar   auto Term = BB.getTerminator();
144dcbbc69cSAditya Kumar   return !isa<InvokeInst>(Term) && !isa<ResumeInst>(Term);
145542e522bSSebastian Pop }
146542e522bSSebastian Pop 
147b755a2dfSVedant Kumar /// Mark \p F cold. Based on this assumption, also optimize it for minimum size.
148c36c10ddSTeresa Johnson /// If \p UpdateEntryCount is true (set when this is a new split function and
149c36c10ddSTeresa Johnson /// module has profile data), set entry count to 0 to ensure treated as cold.
150b755a2dfSVedant Kumar /// Return true if the function is changed.
markFunctionCold(Function & F,bool UpdateEntryCount=false)151c36c10ddSTeresa Johnson static bool markFunctionCold(Function &F, bool UpdateEntryCount = false) {
15285bd3978SEvandro Menezes   assert(!F.hasOptNone() && "Can't mark this cold");
15303aaa3e2SVedant Kumar   bool Changed = false;
154b755a2dfSVedant Kumar   if (!F.hasFnAttribute(Attribute::Cold)) {
155b755a2dfSVedant Kumar     F.addFnAttr(Attribute::Cold);
156b755a2dfSVedant Kumar     Changed = true;
157b755a2dfSVedant Kumar   }
15803aaa3e2SVedant Kumar   if (!F.hasFnAttribute(Attribute::MinSize)) {
15903aaa3e2SVedant Kumar     F.addFnAttr(Attribute::MinSize);
16003aaa3e2SVedant Kumar     Changed = true;
161542e522bSSebastian Pop   }
162c36c10ddSTeresa Johnson   if (UpdateEntryCount) {
163c36c10ddSTeresa Johnson     // Set the entry count to 0 to ensure it is placed in the unlikely text
164c36c10ddSTeresa Johnson     // section when function sections are enabled.
165c36c10ddSTeresa Johnson     F.setEntryCount(0);
166c36c10ddSTeresa Johnson     Changed = true;
167c36c10ddSTeresa Johnson   }
168c36c10ddSTeresa Johnson 
16903aaa3e2SVedant Kumar   return Changed;
170801394a3SAditya Kumar }
171801394a3SAditya Kumar 
172801394a3SAditya Kumar class HotColdSplittingLegacyPass : public ModulePass {
173801394a3SAditya Kumar public:
174801394a3SAditya Kumar   static char ID;
HotColdSplittingLegacyPass()175801394a3SAditya Kumar   HotColdSplittingLegacyPass() : ModulePass(ID) {
176801394a3SAditya Kumar     initializeHotColdSplittingLegacyPassPass(*PassRegistry::getPassRegistry());
177801394a3SAditya Kumar   }
178801394a3SAditya Kumar 
getAnalysisUsage(AnalysisUsage & AU) const179801394a3SAditya Kumar   void getAnalysisUsage(AnalysisUsage &AU) const override {
180801394a3SAditya Kumar     AU.addRequired<BlockFrequencyInfoWrapperPass>();
181801394a3SAditya Kumar     AU.addRequired<ProfileSummaryInfoWrapperPass>();
182a1f20fccSSebastian Pop     AU.addRequired<TargetTransformInfoWrapperPass>();
183807960e6SSergey Dmitriev     AU.addUsedIfAvailable<AssumptionCacheTracker>();
184801394a3SAditya Kumar   }
185801394a3SAditya Kumar 
186801394a3SAditya Kumar   bool runOnModule(Module &M) override;
187801394a3SAditya Kumar };
188801394a3SAditya Kumar 
189801394a3SAditya Kumar } // end anonymous namespace
190801394a3SAditya Kumar 
191b755a2dfSVedant Kumar /// Check whether \p F is inherently cold.
isFunctionCold(const Function & F) const192b755a2dfSVedant Kumar bool HotColdSplitting::isFunctionCold(const Function &F) const {
193b755a2dfSVedant Kumar   if (F.hasFnAttribute(Attribute::Cold))
194b755a2dfSVedant Kumar     return true;
195b755a2dfSVedant Kumar 
196b755a2dfSVedant Kumar   if (F.getCallingConv() == CallingConv::Cold)
197b755a2dfSVedant Kumar     return true;
198b755a2dfSVedant Kumar 
199b755a2dfSVedant Kumar   if (PSI->isFunctionEntryCold(&F))
200b755a2dfSVedant Kumar     return true;
201b755a2dfSVedant Kumar 
202b755a2dfSVedant Kumar   return false;
203b755a2dfSVedant Kumar }
204b755a2dfSVedant Kumar 
205801394a3SAditya Kumar // Returns false if the function should not be considered for hot-cold split
2060f30f08bSSebastian Pop // optimization.
shouldOutlineFrom(const Function & F) const207801394a3SAditya Kumar bool HotColdSplitting::shouldOutlineFrom(const Function &F) const {
208801394a3SAditya Kumar   if (F.hasFnAttribute(Attribute::AlwaysInline))
209801394a3SAditya Kumar     return false;
210801394a3SAditya Kumar 
211801394a3SAditya Kumar   if (F.hasFnAttribute(Attribute::NoInline))
212801394a3SAditya Kumar     return false;
213801394a3SAditya Kumar 
214caaacb83SVedant Kumar   // A function marked `noreturn` may contain unreachable terminators: these
215caaacb83SVedant Kumar   // should not be considered cold, as the function may be a trampoline.
216caaacb83SVedant Kumar   if (F.hasFnAttribute(Attribute::NoReturn))
217caaacb83SVedant Kumar     return false;
218caaacb83SVedant Kumar 
21973522d16SVedant Kumar   if (F.hasFnAttribute(Attribute::SanitizeAddress) ||
22073522d16SVedant Kumar       F.hasFnAttribute(Attribute::SanitizeHWAddress) ||
22173522d16SVedant Kumar       F.hasFnAttribute(Attribute::SanitizeThread) ||
22273522d16SVedant Kumar       F.hasFnAttribute(Attribute::SanitizeMemory))
22373522d16SVedant Kumar     return false;
22473522d16SVedant Kumar 
225801394a3SAditya Kumar   return true;
226801394a3SAditya Kumar }
227801394a3SAditya Kumar 
228db3f9774SVedant Kumar /// Get the benefit score of outlining \p Region.
getOutliningBenefit(ArrayRef<BasicBlock * > Region,TargetTransformInfo & TTI)2299b76160eSDavid Sherwood static InstructionCost getOutliningBenefit(ArrayRef<BasicBlock *> Region,
230db3f9774SVedant Kumar                                            TargetTransformInfo &TTI) {
231db3f9774SVedant Kumar   // Sum up the code size costs of non-terminator instructions. Tight coupling
232db3f9774SVedant Kumar   // with \ref getOutliningPenalty is needed to model the costs of terminators.
2339b76160eSDavid Sherwood   InstructionCost Benefit = 0;
234db3f9774SVedant Kumar   for (BasicBlock *BB : Region)
235db3f9774SVedant Kumar     for (Instruction &I : BB->instructionsWithoutDebug())
236db3f9774SVedant Kumar       if (&I != BB->getTerminator())
237db3f9774SVedant Kumar         Benefit +=
238db3f9774SVedant Kumar             TTI.getInstructionCost(&I, TargetTransformInfo::TCK_CodeSize);
239db3f9774SVedant Kumar 
240db3f9774SVedant Kumar   return Benefit;
241db3f9774SVedant Kumar }
242db3f9774SVedant Kumar 
243db3f9774SVedant Kumar /// Get the penalty score for outlining \p Region.
getOutliningPenalty(ArrayRef<BasicBlock * > Region,unsigned NumInputs,unsigned NumOutputs)244db3f9774SVedant Kumar static int getOutliningPenalty(ArrayRef<BasicBlock *> Region,
245db3f9774SVedant Kumar                                unsigned NumInputs, unsigned NumOutputs) {
246db3f9774SVedant Kumar   int Penalty = SplittingThreshold;
247db3f9774SVedant Kumar   LLVM_DEBUG(dbgs() << "Applying penalty for splitting: " << Penalty << "\n");
248db3f9774SVedant Kumar 
249db3f9774SVedant Kumar   // If the splitting threshold is set at or below zero, skip the usual
250db3f9774SVedant Kumar   // profitability check.
251db3f9774SVedant Kumar   if (SplittingThreshold <= 0)
252db3f9774SVedant Kumar     return Penalty;
253db3f9774SVedant Kumar 
254db3f9774SVedant Kumar   // Find the number of distinct exit blocks for the region. Use a conservative
255db3f9774SVedant Kumar   // check to determine whether control returns from the region.
256db3f9774SVedant Kumar   bool NoBlocksReturn = true;
257db3f9774SVedant Kumar   SmallPtrSet<BasicBlock *, 2> SuccsOutsideRegion;
258db3f9774SVedant Kumar   for (BasicBlock *BB : Region) {
259db3f9774SVedant Kumar     // If a block has no successors, only assume it does not return if it's
260db3f9774SVedant Kumar     // unreachable.
261db3f9774SVedant Kumar     if (succ_empty(BB)) {
262db3f9774SVedant Kumar       NoBlocksReturn &= isa<UnreachableInst>(BB->getTerminator());
263db3f9774SVedant Kumar       continue;
264db3f9774SVedant Kumar     }
265db3f9774SVedant Kumar 
266db3f9774SVedant Kumar     for (BasicBlock *SuccBB : successors(BB)) {
267215c1b19SKazu Hirata       if (!is_contained(Region, SuccBB)) {
268db3f9774SVedant Kumar         NoBlocksReturn = false;
269db3f9774SVedant Kumar         SuccsOutsideRegion.insert(SuccBB);
270db3f9774SVedant Kumar       }
271db3f9774SVedant Kumar     }
272db3f9774SVedant Kumar   }
273db3f9774SVedant Kumar 
2741ab4db0fSAditya Kumar   // Count the number of phis in exit blocks with >= 2 incoming values from the
2751ab4db0fSAditya Kumar   // outlining region. These phis are split (\ref severSplitPHINodesOfExits),
2761ab4db0fSAditya Kumar   // and new outputs are created to supply the split phis. CodeExtractor can't
2771ab4db0fSAditya Kumar   // report these new outputs until extraction begins, but it's important to
2781ab4db0fSAditya Kumar   // factor the cost of the outputs into the cost calculation.
2791ab4db0fSAditya Kumar   unsigned NumSplitExitPhis = 0;
2801ab4db0fSAditya Kumar   for (BasicBlock *ExitBB : SuccsOutsideRegion) {
2811ab4db0fSAditya Kumar     for (PHINode &PN : ExitBB->phis()) {
2821ab4db0fSAditya Kumar       // Find all incoming values from the outlining region.
2831ab4db0fSAditya Kumar       int NumIncomingVals = 0;
2841ab4db0fSAditya Kumar       for (unsigned i = 0; i < PN.getNumIncomingValues(); ++i)
28536b8a4f9SKazu Hirata         if (llvm::is_contained(Region, PN.getIncomingBlock(i))) {
2861ab4db0fSAditya Kumar           ++NumIncomingVals;
2871ab4db0fSAditya Kumar           if (NumIncomingVals > 1) {
2881ab4db0fSAditya Kumar             ++NumSplitExitPhis;
2891ab4db0fSAditya Kumar             break;
2901ab4db0fSAditya Kumar           }
2911ab4db0fSAditya Kumar         }
2921ab4db0fSAditya Kumar     }
2931ab4db0fSAditya Kumar   }
2941ab4db0fSAditya Kumar 
2951ab4db0fSAditya Kumar   // Apply a penalty for calling the split function. Factor in the cost of
2961ab4db0fSAditya Kumar   // materializing all of the parameters.
2971ab4db0fSAditya Kumar   int NumOutputsAndSplitPhis = NumOutputs + NumSplitExitPhis;
2981ab4db0fSAditya Kumar   int NumParams = NumInputs + NumOutputsAndSplitPhis;
2991ab4db0fSAditya Kumar   if (NumParams > MaxParametersForSplit) {
3001ab4db0fSAditya Kumar     LLVM_DEBUG(dbgs() << NumInputs << " inputs and " << NumOutputsAndSplitPhis
3011ab4db0fSAditya Kumar                       << " outputs exceeds parameter limit ("
3021ab4db0fSAditya Kumar                       << MaxParametersForSplit << ")\n");
3031ab4db0fSAditya Kumar     return std::numeric_limits<int>::max();
3041ab4db0fSAditya Kumar   }
3051ab4db0fSAditya Kumar   const int CostForArgMaterialization = 2 * TargetTransformInfo::TCC_Basic;
3061ab4db0fSAditya Kumar   LLVM_DEBUG(dbgs() << "Applying penalty for: " << NumParams << " params\n");
3071ab4db0fSAditya Kumar   Penalty += CostForArgMaterialization * NumParams;
3081ab4db0fSAditya Kumar 
3091ab4db0fSAditya Kumar   // Apply the typical code size cost for an output alloca and its associated
3101ab4db0fSAditya Kumar   // reload in the caller. Also penalize the associated store in the callee.
3111ab4db0fSAditya Kumar   LLVM_DEBUG(dbgs() << "Applying penalty for: " << NumOutputsAndSplitPhis
3121ab4db0fSAditya Kumar                     << " outputs/split phis\n");
3131ab4db0fSAditya Kumar   const int CostForRegionOutput = 3 * TargetTransformInfo::TCC_Basic;
3141ab4db0fSAditya Kumar   Penalty += CostForRegionOutput * NumOutputsAndSplitPhis;
3151ab4db0fSAditya Kumar 
316db3f9774SVedant Kumar   // Apply a `noreturn` bonus.
317db3f9774SVedant Kumar   if (NoBlocksReturn) {
318db3f9774SVedant Kumar     LLVM_DEBUG(dbgs() << "Applying bonus for: " << Region.size()
319db3f9774SVedant Kumar                       << " non-returning terminators\n");
320db3f9774SVedant Kumar     Penalty -= Region.size();
321db3f9774SVedant Kumar   }
322db3f9774SVedant Kumar 
323db3f9774SVedant Kumar   // Apply a penalty for having more than one successor outside of the region.
324db3f9774SVedant Kumar   // This penalty accounts for the switch needed in the caller.
3251ab4db0fSAditya Kumar   if (SuccsOutsideRegion.size() > 1) {
326db3f9774SVedant Kumar     LLVM_DEBUG(dbgs() << "Applying penalty for: " << SuccsOutsideRegion.size()
327db3f9774SVedant Kumar                       << " non-region successors\n");
328db3f9774SVedant Kumar     Penalty += (SuccsOutsideRegion.size() - 1) * TargetTransformInfo::TCC_Basic;
329db3f9774SVedant Kumar   }
330db3f9774SVedant Kumar 
331db3f9774SVedant Kumar   return Penalty;
332db3f9774SVedant Kumar }
333db3f9774SVedant Kumar 
extractColdRegion(const BlockSequence & Region,const CodeExtractorAnalysisCache & CEAC,DominatorTree & DT,BlockFrequencyInfo * BFI,TargetTransformInfo & TTI,OptimizationRemarkEmitter & ORE,AssumptionCache * AC,unsigned Count)3349852699dSVedant Kumar Function *HotColdSplitting::extractColdRegion(
3359852699dSVedant Kumar     const BlockSequence &Region, const CodeExtractorAnalysisCache &CEAC,
3369852699dSVedant Kumar     DominatorTree &DT, BlockFrequencyInfo *BFI, TargetTransformInfo &TTI,
3379852699dSVedant Kumar     OptimizationRemarkEmitter &ORE, AssumptionCache *AC, unsigned Count) {
338f431a2f2STeresa Johnson   assert(!Region.empty());
3391217160bSSebastian Pop 
340801394a3SAditya Kumar   // TODO: Pass BFI and BPI to update profile information.
341c2990068SVedant Kumar   CodeExtractor CE(Region, &DT, /* AggregateArgs */ false, /* BFI */ nullptr,
342807960e6SSergey Dmitriev                    /* BPI */ nullptr, AC, /* AllowVarArgs */ false,
34387ec6f41SWilliam S. Moses                    /* AllowAlloca */ false, /* AllocaBlock */ nullptr,
344c8dba682STeresa Johnson                    /* Suffix */ "cold." + std::to_string(Count));
345801394a3SAditya Kumar 
346db3f9774SVedant Kumar   // Perform a simple cost/benefit analysis to decide whether or not to permit
347db3f9774SVedant Kumar   // splitting.
348db3f9774SVedant Kumar   SetVector<Value *> Inputs, Outputs, Sinks;
349db3f9774SVedant Kumar   CE.findInputsOutputs(Inputs, Outputs, Sinks);
3509b76160eSDavid Sherwood   InstructionCost OutliningBenefit = getOutliningBenefit(Region, TTI);
351db3f9774SVedant Kumar   int OutliningPenalty =
352db3f9774SVedant Kumar       getOutliningPenalty(Region, Inputs.size(), Outputs.size());
353db3f9774SVedant Kumar   LLVM_DEBUG(dbgs() << "Split profitability: benefit = " << OutliningBenefit
354db3f9774SVedant Kumar                     << ", penalty = " << OutliningPenalty << "\n");
3559b76160eSDavid Sherwood   if (!OutliningBenefit.isValid() || OutliningBenefit <= OutliningPenalty)
356db3f9774SVedant Kumar     return nullptr;
357db3f9774SVedant Kumar 
358f431a2f2STeresa Johnson   Function *OrigF = Region[0]->getParent();
3599852699dSVedant Kumar   if (Function *OutF = CE.extractCodeRegion(CEAC)) {
360801394a3SAditya Kumar     User *U = *OutF->user_begin();
361801394a3SAditya Kumar     CallInst *CI = cast<CallInst>(U);
362c2990068SVedant Kumar     NumColdRegionsOutlined++;
363d2a895a9SVedant Kumar     if (TTI.useColdCCForColdCall(*OutF)) {
364801394a3SAditya Kumar       OutF->setCallingConv(CallingConv::Cold);
365447e2c30SMircea Trofin       CI->setCallingConv(CallingConv::Cold);
366a1f20fccSSebastian Pop     }
367801394a3SAditya Kumar     CI->setIsNoInline();
36850315461SVedant Kumar 
36953ac1448SAditya Kumar     if (EnableColdSection)
37053ac1448SAditya Kumar       OutF->setSection(ColdSectionName);
37153ac1448SAditya Kumar     else {
37287f14676SBill Wendling       if (OrigF->hasSection())
37387f14676SBill Wendling         OutF->setSection(OrigF->getSection());
37453ac1448SAditya Kumar     }
37587f14676SBill Wendling 
376c36c10ddSTeresa Johnson     markFunctionCold(*OutF, BFI != nullptr);
37750315461SVedant Kumar 
3780f30f08bSSebastian Pop     LLVM_DEBUG(llvm::dbgs() << "Outlined Region: " << *OutF);
379f431a2f2STeresa Johnson     ORE.emit([&]() {
380f431a2f2STeresa Johnson       return OptimizationRemark(DEBUG_TYPE, "HotColdSplit",
381f431a2f2STeresa Johnson                                 &*Region[0]->begin())
382f431a2f2STeresa Johnson              << ore::NV("Original", OrigF) << " split cold code into "
383f431a2f2STeresa Johnson              << ore::NV("Split", OutF);
384f431a2f2STeresa Johnson     });
385801394a3SAditya Kumar     return OutF;
386801394a3SAditya Kumar   }
387801394a3SAditya Kumar 
388801394a3SAditya Kumar   ORE.emit([&]() {
389801394a3SAditya Kumar     return OptimizationRemarkMissed(DEBUG_TYPE, "ExtractFailed",
390801394a3SAditya Kumar                                     &*Region[0]->begin())
391801394a3SAditya Kumar            << "Failed to extract region at block "
392801394a3SAditya Kumar            << ore::NV("Block", Region.front());
393801394a3SAditya Kumar   });
394801394a3SAditya Kumar   return nullptr;
395801394a3SAditya Kumar }
396801394a3SAditya Kumar 
39703aaa3e2SVedant Kumar /// A pair of (basic block, score).
39803aaa3e2SVedant Kumar using BlockTy = std::pair<BasicBlock *, unsigned>;
39903aaa3e2SVedant Kumar 
400b17d2136SBenjamin Kramer namespace {
40103aaa3e2SVedant Kumar /// A maximal outlining region. This contains all blocks post-dominated by a
40203aaa3e2SVedant Kumar /// sink block, the sink block itself, and all blocks dominated by the sink.
40365de025dSVedant Kumar /// If sink-predecessors and sink-successors cannot be extracted in one region,
40465de025dSVedant Kumar /// the static constructor returns a list of suitable extraction regions.
40503aaa3e2SVedant Kumar class OutliningRegion {
40603aaa3e2SVedant Kumar   /// A list of (block, score) pairs. A block's score is non-zero iff it's a
40703aaa3e2SVedant Kumar   /// viable sub-region entry point. Blocks with higher scores are better entry
40803aaa3e2SVedant Kumar   /// points (i.e. they are more distant ancestors of the sink block).
40903aaa3e2SVedant Kumar   SmallVector<BlockTy, 0> Blocks = {};
41003aaa3e2SVedant Kumar 
41103aaa3e2SVedant Kumar   /// The suggested entry point into the region. If the region has multiple
41203aaa3e2SVedant Kumar   /// entry points, all blocks within the region may not be reachable from this
41303aaa3e2SVedant Kumar   /// entry point.
41403aaa3e2SVedant Kumar   BasicBlock *SuggestedEntryPoint = nullptr;
41503aaa3e2SVedant Kumar 
41603aaa3e2SVedant Kumar   /// Whether the entire function is cold.
41703aaa3e2SVedant Kumar   bool EntireFunctionCold = false;
41803aaa3e2SVedant Kumar 
41903aaa3e2SVedant Kumar   /// If \p BB is a viable entry point, return \p Score. Return 0 otherwise.
getEntryPointScore(BasicBlock & BB,unsigned Score)42003aaa3e2SVedant Kumar   static unsigned getEntryPointScore(BasicBlock &BB, unsigned Score) {
42165de025dSVedant Kumar     return mayExtractBlock(BB) ? Score : 0;
42203aaa3e2SVedant Kumar   }
42303aaa3e2SVedant Kumar 
42403aaa3e2SVedant Kumar   /// These scores should be lower than the score for predecessor blocks,
42503aaa3e2SVedant Kumar   /// because regions starting at predecessor blocks are typically larger.
42603aaa3e2SVedant Kumar   static constexpr unsigned ScoreForSuccBlock = 1;
42703aaa3e2SVedant Kumar   static constexpr unsigned ScoreForSinkBlock = 1;
42803aaa3e2SVedant Kumar 
42903aaa3e2SVedant Kumar   OutliningRegion(const OutliningRegion &) = delete;
43003aaa3e2SVedant Kumar   OutliningRegion &operator=(const OutliningRegion &) = delete;
43103aaa3e2SVedant Kumar 
43203aaa3e2SVedant Kumar public:
43303aaa3e2SVedant Kumar   OutliningRegion() = default;
43403aaa3e2SVedant Kumar   OutliningRegion(OutliningRegion &&) = default;
43503aaa3e2SVedant Kumar   OutliningRegion &operator=(OutliningRegion &&) = default;
43603aaa3e2SVedant Kumar 
create(BasicBlock & SinkBB,const DominatorTree & DT,const PostDominatorTree & PDT)43765de025dSVedant Kumar   static std::vector<OutliningRegion> create(BasicBlock &SinkBB,
43865de025dSVedant Kumar                                              const DominatorTree &DT,
43938874c8fSVedant Kumar                                              const PostDominatorTree &PDT) {
44065de025dSVedant Kumar     std::vector<OutliningRegion> Regions;
44103aaa3e2SVedant Kumar     SmallPtrSet<BasicBlock *, 4> RegionBlocks;
44203aaa3e2SVedant Kumar 
44365de025dSVedant Kumar     Regions.emplace_back();
44465de025dSVedant Kumar     OutliningRegion *ColdRegion = &Regions.back();
44565de025dSVedant Kumar 
44603aaa3e2SVedant Kumar     auto addBlockToRegion = [&](BasicBlock *BB, unsigned Score) {
44703aaa3e2SVedant Kumar       RegionBlocks.insert(BB);
44865de025dSVedant Kumar       ColdRegion->Blocks.emplace_back(BB, Score);
44903aaa3e2SVedant Kumar     };
45003aaa3e2SVedant Kumar 
45103aaa3e2SVedant Kumar     // The ancestor farthest-away from SinkBB, and also post-dominated by it.
45203aaa3e2SVedant Kumar     unsigned SinkScore = getEntryPointScore(SinkBB, ScoreForSinkBlock);
45365de025dSVedant Kumar     ColdRegion->SuggestedEntryPoint = (SinkScore > 0) ? &SinkBB : nullptr;
45403aaa3e2SVedant Kumar     unsigned BestScore = SinkScore;
45503aaa3e2SVedant Kumar 
45603aaa3e2SVedant Kumar     // Visit SinkBB's ancestors using inverse DFS.
45703aaa3e2SVedant Kumar     auto PredIt = ++idf_begin(&SinkBB);
45803aaa3e2SVedant Kumar     auto PredEnd = idf_end(&SinkBB);
45903aaa3e2SVedant Kumar     while (PredIt != PredEnd) {
46003aaa3e2SVedant Kumar       BasicBlock &PredBB = **PredIt;
46103aaa3e2SVedant Kumar       bool SinkPostDom = PDT.dominates(&SinkBB, &PredBB);
46203aaa3e2SVedant Kumar 
46303aaa3e2SVedant Kumar       // If the predecessor is cold and has no predecessors, the entire
46403aaa3e2SVedant Kumar       // function must be cold.
46503aaa3e2SVedant Kumar       if (SinkPostDom && pred_empty(&PredBB)) {
46665de025dSVedant Kumar         ColdRegion->EntireFunctionCold = true;
46765de025dSVedant Kumar         return Regions;
46803aaa3e2SVedant Kumar       }
46903aaa3e2SVedant Kumar 
47003aaa3e2SVedant Kumar       // If SinkBB does not post-dominate a predecessor, do not mark the
47103aaa3e2SVedant Kumar       // predecessor (or any of its predecessors) cold.
47203aaa3e2SVedant Kumar       if (!SinkPostDom || !mayExtractBlock(PredBB)) {
47303aaa3e2SVedant Kumar         PredIt.skipChildren();
474801394a3SAditya Kumar         continue;
475c2990068SVedant Kumar       }
476c2990068SVedant Kumar 
47703aaa3e2SVedant Kumar       // Keep track of the post-dominated ancestor farthest away from the sink.
47803aaa3e2SVedant Kumar       // The path length is always >= 2, ensuring that predecessor blocks are
47903aaa3e2SVedant Kumar       // considered as entry points before the sink block.
48003aaa3e2SVedant Kumar       unsigned PredScore = getEntryPointScore(PredBB, PredIt.getPathLength());
48103aaa3e2SVedant Kumar       if (PredScore > BestScore) {
48265de025dSVedant Kumar         ColdRegion->SuggestedEntryPoint = &PredBB;
48303aaa3e2SVedant Kumar         BestScore = PredScore;
48403aaa3e2SVedant Kumar       }
48503aaa3e2SVedant Kumar 
48603aaa3e2SVedant Kumar       addBlockToRegion(&PredBB, PredScore);
48703aaa3e2SVedant Kumar       ++PredIt;
48803aaa3e2SVedant Kumar     }
48903aaa3e2SVedant Kumar 
49065de025dSVedant Kumar     // If the sink can be added to the cold region, do so. It's considered as
49165de025dSVedant Kumar     // an entry point before any sink-successor blocks.
49265de025dSVedant Kumar     //
49365de025dSVedant Kumar     // Otherwise, split cold sink-successor blocks using a separate region.
49465de025dSVedant Kumar     // This satisfies the requirement that all extraction blocks other than the
49565de025dSVedant Kumar     // first have predecessors within the extraction region.
49665de025dSVedant Kumar     if (mayExtractBlock(SinkBB)) {
49703aaa3e2SVedant Kumar       addBlockToRegion(&SinkBB, SinkScore);
498c74026daSVedant Kumar       if (pred_empty(&SinkBB)) {
499c74026daSVedant Kumar         ColdRegion->EntireFunctionCold = true;
500c74026daSVedant Kumar         return Regions;
501c74026daSVedant Kumar       }
50265de025dSVedant Kumar     } else {
50365de025dSVedant Kumar       Regions.emplace_back();
50465de025dSVedant Kumar       ColdRegion = &Regions.back();
50565de025dSVedant Kumar       BestScore = 0;
50665de025dSVedant Kumar     }
50703aaa3e2SVedant Kumar 
50803aaa3e2SVedant Kumar     // Find all successors of SinkBB dominated by SinkBB using DFS.
50903aaa3e2SVedant Kumar     auto SuccIt = ++df_begin(&SinkBB);
51003aaa3e2SVedant Kumar     auto SuccEnd = df_end(&SinkBB);
51103aaa3e2SVedant Kumar     while (SuccIt != SuccEnd) {
51203aaa3e2SVedant Kumar       BasicBlock &SuccBB = **SuccIt;
51303aaa3e2SVedant Kumar       bool SinkDom = DT.dominates(&SinkBB, &SuccBB);
51403aaa3e2SVedant Kumar 
51503aaa3e2SVedant Kumar       // Don't allow the backwards & forwards DFSes to mark the same block.
51603aaa3e2SVedant Kumar       bool DuplicateBlock = RegionBlocks.count(&SuccBB);
51703aaa3e2SVedant Kumar 
51803aaa3e2SVedant Kumar       // If SinkBB does not dominate a successor, do not mark the successor (or
51903aaa3e2SVedant Kumar       // any of its successors) cold.
52003aaa3e2SVedant Kumar       if (DuplicateBlock || !SinkDom || !mayExtractBlock(SuccBB)) {
52103aaa3e2SVedant Kumar         SuccIt.skipChildren();
52203aaa3e2SVedant Kumar         continue;
52303aaa3e2SVedant Kumar       }
52403aaa3e2SVedant Kumar 
52503aaa3e2SVedant Kumar       unsigned SuccScore = getEntryPointScore(SuccBB, ScoreForSuccBlock);
52603aaa3e2SVedant Kumar       if (SuccScore > BestScore) {
52765de025dSVedant Kumar         ColdRegion->SuggestedEntryPoint = &SuccBB;
52803aaa3e2SVedant Kumar         BestScore = SuccScore;
52903aaa3e2SVedant Kumar       }
53003aaa3e2SVedant Kumar 
53103aaa3e2SVedant Kumar       addBlockToRegion(&SuccBB, SuccScore);
53203aaa3e2SVedant Kumar       ++SuccIt;
53303aaa3e2SVedant Kumar     }
53403aaa3e2SVedant Kumar 
53565de025dSVedant Kumar     return Regions;
53603aaa3e2SVedant Kumar   }
53703aaa3e2SVedant Kumar 
53803aaa3e2SVedant Kumar   /// Whether this region has nothing to extract.
empty() const53903aaa3e2SVedant Kumar   bool empty() const { return !SuggestedEntryPoint; }
54003aaa3e2SVedant Kumar 
54103aaa3e2SVedant Kumar   /// The blocks in this region.
blocks() const54203aaa3e2SVedant Kumar   ArrayRef<std::pair<BasicBlock *, unsigned>> blocks() const { return Blocks; }
54303aaa3e2SVedant Kumar 
54403aaa3e2SVedant Kumar   /// Whether the entire function containing this region is cold.
isEntireFunctionCold() const54503aaa3e2SVedant Kumar   bool isEntireFunctionCold() const { return EntireFunctionCold; }
54603aaa3e2SVedant Kumar 
54703aaa3e2SVedant Kumar   /// Remove a sub-region from this region and return it as a block sequence.
takeSingleEntrySubRegion(DominatorTree & DT)54803aaa3e2SVedant Kumar   BlockSequence takeSingleEntrySubRegion(DominatorTree &DT) {
54903aaa3e2SVedant Kumar     assert(!empty() && !isEntireFunctionCold() && "Nothing to extract");
55003aaa3e2SVedant Kumar 
55103aaa3e2SVedant Kumar     // Remove blocks dominated by the suggested entry point from this region.
55203aaa3e2SVedant Kumar     // During the removal, identify the next best entry point into the region.
55303aaa3e2SVedant Kumar     // Ensure that the first extracted block is the suggested entry point.
55403aaa3e2SVedant Kumar     BlockSequence SubRegion = {SuggestedEntryPoint};
55503aaa3e2SVedant Kumar     BasicBlock *NextEntryPoint = nullptr;
55603aaa3e2SVedant Kumar     unsigned NextScore = 0;
55703aaa3e2SVedant Kumar     auto RegionEndIt = Blocks.end();
55803aaa3e2SVedant Kumar     auto RegionStartIt = remove_if(Blocks, [&](const BlockTy &Block) {
55903aaa3e2SVedant Kumar       BasicBlock *BB = Block.first;
56003aaa3e2SVedant Kumar       unsigned Score = Block.second;
56103aaa3e2SVedant Kumar       bool InSubRegion =
56203aaa3e2SVedant Kumar           BB == SuggestedEntryPoint || DT.dominates(SuggestedEntryPoint, BB);
56303aaa3e2SVedant Kumar       if (!InSubRegion && Score > NextScore) {
56403aaa3e2SVedant Kumar         NextEntryPoint = BB;
56503aaa3e2SVedant Kumar         NextScore = Score;
56603aaa3e2SVedant Kumar       }
56703aaa3e2SVedant Kumar       if (InSubRegion && BB != SuggestedEntryPoint)
56803aaa3e2SVedant Kumar         SubRegion.push_back(BB);
56903aaa3e2SVedant Kumar       return InSubRegion;
57003aaa3e2SVedant Kumar     });
57103aaa3e2SVedant Kumar     Blocks.erase(RegionStartIt, RegionEndIt);
57203aaa3e2SVedant Kumar 
57303aaa3e2SVedant Kumar     // Update the suggested entry point.
57403aaa3e2SVedant Kumar     SuggestedEntryPoint = NextEntryPoint;
57503aaa3e2SVedant Kumar 
57603aaa3e2SVedant Kumar     return SubRegion;
57703aaa3e2SVedant Kumar   }
57803aaa3e2SVedant Kumar };
579b17d2136SBenjamin Kramer } // namespace
58003aaa3e2SVedant Kumar 
outlineColdRegions(Function & F,bool HasProfileSummary)581cde65c0fSVedant Kumar bool HotColdSplitting::outlineColdRegions(Function &F, bool HasProfileSummary) {
58203aaa3e2SVedant Kumar   bool Changed = false;
58303aaa3e2SVedant Kumar 
58403aaa3e2SVedant Kumar   // The set of cold blocks.
58503aaa3e2SVedant Kumar   SmallPtrSet<BasicBlock *, 4> ColdBlocks;
58603aaa3e2SVedant Kumar 
58703aaa3e2SVedant Kumar   // The worklist of non-intersecting regions left to outline.
58803aaa3e2SVedant Kumar   SmallVector<OutliningRegion, 2> OutliningWorklist;
58903aaa3e2SVedant Kumar 
59003aaa3e2SVedant Kumar   // Set up an RPO traversal. Experimentally, this performs better (outlines
59103aaa3e2SVedant Kumar   // more) than a PO traversal, because we prevent region overlap by keeping
59203aaa3e2SVedant Kumar   // the first region to contain a block.
59303aaa3e2SVedant Kumar   ReversePostOrderTraversal<Function *> RPOT(&F);
59403aaa3e2SVedant Kumar 
59538874c8fSVedant Kumar   // Calculate domtrees lazily. This reduces compile-time significantly.
596bed7f9eaSFlorian Hahn   std::unique_ptr<DominatorTree> DT;
597bed7f9eaSFlorian Hahn   std::unique_ptr<PostDominatorTree> PDT;
59838874c8fSVedant Kumar 
599cde65c0fSVedant Kumar   // Calculate BFI lazily (it's only used to query ProfileSummaryInfo). This
600bed7f9eaSFlorian Hahn   // reduces compile-time significantly. TODO: When we *do* use BFI, we should
601bed7f9eaSFlorian Hahn   // be able to salvage its domtrees instead of recomputing them.
602cde65c0fSVedant Kumar   BlockFrequencyInfo *BFI = nullptr;
603cde65c0fSVedant Kumar   if (HasProfileSummary)
604cde65c0fSVedant Kumar     BFI = GetBFI(F);
605cde65c0fSVedant Kumar 
60638874c8fSVedant Kumar   TargetTransformInfo &TTI = GetTTI(F);
60738874c8fSVedant Kumar   OptimizationRemarkEmitter &ORE = (*GetORE)(F);
608807960e6SSergey Dmitriev   AssumptionCache *AC = LookupAC(F);
60938874c8fSVedant Kumar 
61003aaa3e2SVedant Kumar   // Find all cold regions.
61103aaa3e2SVedant Kumar   for (BasicBlock *BB : RPOT) {
61203aaa3e2SVedant Kumar     // This block is already part of some outlining region.
61303aaa3e2SVedant Kumar     if (ColdBlocks.count(BB))
61403aaa3e2SVedant Kumar       continue;
61503aaa3e2SVedant Kumar 
616cde65c0fSVedant Kumar     bool Cold = (BFI && PSI->isColdBlock(BB, BFI)) ||
6179afb1c56SVedant Kumar                 (EnableStaticAnalysis && unlikelyExecuted(*BB));
61803aaa3e2SVedant Kumar     if (!Cold)
61903aaa3e2SVedant Kumar       continue;
62003aaa3e2SVedant Kumar 
62103aaa3e2SVedant Kumar     LLVM_DEBUG({
62203aaa3e2SVedant Kumar       dbgs() << "Found a cold block:\n";
62303aaa3e2SVedant Kumar       BB->dump();
62403aaa3e2SVedant Kumar     });
62503aaa3e2SVedant Kumar 
62638874c8fSVedant Kumar     if (!DT)
6270eaee545SJonas Devlieghere       DT = std::make_unique<DominatorTree>(F);
62838874c8fSVedant Kumar     if (!PDT)
6290eaee545SJonas Devlieghere       PDT = std::make_unique<PostDominatorTree>(F);
63038874c8fSVedant Kumar 
63165de025dSVedant Kumar     auto Regions = OutliningRegion::create(*BB, *DT, *PDT);
63265de025dSVedant Kumar     for (OutliningRegion &Region : Regions) {
63303aaa3e2SVedant Kumar       if (Region.empty())
63403aaa3e2SVedant Kumar         continue;
63503aaa3e2SVedant Kumar 
63603aaa3e2SVedant Kumar       if (Region.isEntireFunctionCold()) {
63703aaa3e2SVedant Kumar         LLVM_DEBUG(dbgs() << "Entire function is cold\n");
638b755a2dfSVedant Kumar         return markFunctionCold(F);
63903aaa3e2SVedant Kumar       }
64003aaa3e2SVedant Kumar 
64103aaa3e2SVedant Kumar       // If this outlining region intersects with another, drop the new region.
64203aaa3e2SVedant Kumar       //
64303aaa3e2SVedant Kumar       // TODO: It's theoretically possible to outline more by only keeping the
64403aaa3e2SVedant Kumar       // largest region which contains a block, but the extra bookkeeping to do
64503aaa3e2SVedant Kumar       // this is tricky/expensive.
64603aaa3e2SVedant Kumar       bool RegionsOverlap = any_of(Region.blocks(), [&](const BlockTy &Block) {
64703aaa3e2SVedant Kumar         return !ColdBlocks.insert(Block.first).second;
64803aaa3e2SVedant Kumar       });
64903aaa3e2SVedant Kumar       if (RegionsOverlap)
65003aaa3e2SVedant Kumar         continue;
65103aaa3e2SVedant Kumar 
65203aaa3e2SVedant Kumar       OutliningWorklist.emplace_back(std::move(Region));
65303aaa3e2SVedant Kumar       ++NumColdRegionsFound;
65403aaa3e2SVedant Kumar     }
65565de025dSVedant Kumar   }
65603aaa3e2SVedant Kumar 
6579852699dSVedant Kumar   if (OutliningWorklist.empty())
6589852699dSVedant Kumar     return Changed;
6599852699dSVedant Kumar 
66003aaa3e2SVedant Kumar   // Outline single-entry cold regions, splitting up larger regions as needed.
66103aaa3e2SVedant Kumar   unsigned OutlinedFunctionID = 1;
6629852699dSVedant Kumar   // Cache and recycle the CodeExtractor analysis to avoid O(n^2) compile-time.
6639852699dSVedant Kumar   CodeExtractorAnalysisCache CEAC(F);
6649852699dSVedant Kumar   do {
66503aaa3e2SVedant Kumar     OutliningRegion Region = OutliningWorklist.pop_back_val();
66603aaa3e2SVedant Kumar     assert(!Region.empty() && "Empty outlining region in worklist");
66703aaa3e2SVedant Kumar     do {
66838874c8fSVedant Kumar       BlockSequence SubRegion = Region.takeSingleEntrySubRegion(*DT);
66903aaa3e2SVedant Kumar       LLVM_DEBUG({
67003aaa3e2SVedant Kumar         dbgs() << "Hot/cold splitting attempting to outline these blocks:\n";
67103aaa3e2SVedant Kumar         for (BasicBlock *BB : SubRegion)
67203aaa3e2SVedant Kumar           BB->dump();
67303aaa3e2SVedant Kumar       });
67403aaa3e2SVedant Kumar 
6759852699dSVedant Kumar       Function *Outlined = extractColdRegion(SubRegion, CEAC, *DT, BFI, TTI,
6769852699dSVedant Kumar                                              ORE, AC, OutlinedFunctionID);
67703aaa3e2SVedant Kumar       if (Outlined) {
67803aaa3e2SVedant Kumar         ++OutlinedFunctionID;
67903aaa3e2SVedant Kumar         Changed = true;
68003aaa3e2SVedant Kumar       }
68103aaa3e2SVedant Kumar     } while (!Region.empty());
6829852699dSVedant Kumar   } while (!OutliningWorklist.empty());
68303aaa3e2SVedant Kumar 
68403aaa3e2SVedant Kumar   return Changed;
68503aaa3e2SVedant Kumar }
68603aaa3e2SVedant Kumar 
run(Module & M)68703aaa3e2SVedant Kumar bool HotColdSplitting::run(Module &M) {
68803aaa3e2SVedant Kumar   bool Changed = false;
689a6ff69f6SRong Xu   bool HasProfileSummary = (M.getProfileSummary(/* IsCS */ false) != nullptr);
690be374758SKazu Hirata   for (Function &F : M) {
691b755a2dfSVedant Kumar     // Do not touch declarations.
692b755a2dfSVedant Kumar     if (F.isDeclaration())
693b755a2dfSVedant Kumar       continue;
694b755a2dfSVedant Kumar 
695b755a2dfSVedant Kumar     // Do not modify `optnone` functions.
69685bd3978SEvandro Menezes     if (F.hasOptNone())
697b755a2dfSVedant Kumar       continue;
698b755a2dfSVedant Kumar 
699b755a2dfSVedant Kumar     // Detect inherently cold functions and mark them as such.
700b755a2dfSVedant Kumar     if (isFunctionCold(F)) {
701b755a2dfSVedant Kumar       Changed |= markFunctionCold(F);
702b755a2dfSVedant Kumar       continue;
703b755a2dfSVedant Kumar     }
704b755a2dfSVedant Kumar 
70503aaa3e2SVedant Kumar     if (!shouldOutlineFrom(F)) {
70603aaa3e2SVedant Kumar       LLVM_DEBUG(llvm::dbgs() << "Skipping " << F.getName() << "\n");
70703aaa3e2SVedant Kumar       continue;
70803aaa3e2SVedant Kumar     }
709b755a2dfSVedant Kumar 
710c2990068SVedant Kumar     LLVM_DEBUG(llvm::dbgs() << "Outlining in " << F.getName() << "\n");
711cde65c0fSVedant Kumar     Changed |= outlineColdRegions(F, HasProfileSummary);
712c2990068SVedant Kumar   }
713c2990068SVedant Kumar   return Changed;
714801394a3SAditya Kumar }
715801394a3SAditya Kumar 
runOnModule(Module & M)716801394a3SAditya Kumar bool HotColdSplittingLegacyPass::runOnModule(Module &M) {
717801394a3SAditya Kumar   if (skipModule(M))
718801394a3SAditya Kumar     return false;
719801394a3SAditya Kumar   ProfileSummaryInfo *PSI =
720e7b789b5SVedant Kumar       &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
721a1f20fccSSebastian Pop   auto GTTI = [this](Function &F) -> TargetTransformInfo & {
722a1f20fccSSebastian Pop     return this->getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
723a1f20fccSSebastian Pop   };
724801394a3SAditya Kumar   auto GBFI = [this](Function &F) {
725801394a3SAditya Kumar     return &this->getAnalysis<BlockFrequencyInfoWrapperPass>(F).getBFI();
726801394a3SAditya Kumar   };
727801394a3SAditya Kumar   std::unique_ptr<OptimizationRemarkEmitter> ORE;
728801394a3SAditya Kumar   std::function<OptimizationRemarkEmitter &(Function &)> GetORE =
729801394a3SAditya Kumar       [&ORE](Function &F) -> OptimizationRemarkEmitter & {
730801394a3SAditya Kumar     ORE.reset(new OptimizationRemarkEmitter(&F));
731bce1bf0eSKazu Hirata     return *ORE;
732801394a3SAditya Kumar   };
733807960e6SSergey Dmitriev   auto LookupAC = [this](Function &F) -> AssumptionCache * {
734807960e6SSergey Dmitriev     if (auto *ACT = getAnalysisIfAvailable<AssumptionCacheTracker>())
735807960e6SSergey Dmitriev       return ACT->lookupAssumptionCache(F);
736807960e6SSergey Dmitriev     return nullptr;
737807960e6SSergey Dmitriev   };
738801394a3SAditya Kumar 
739807960e6SSergey Dmitriev   return HotColdSplitting(PSI, GBFI, GTTI, &GetORE, LookupAC).run(M);
740801394a3SAditya Kumar }
741801394a3SAditya Kumar 
7429e20ade7SAditya Kumar PreservedAnalyses
run(Module & M,ModuleAnalysisManager & AM)7439e20ade7SAditya Kumar HotColdSplittingPass::run(Module &M, ModuleAnalysisManager &AM) {
7449e20ade7SAditya Kumar   auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
7459e20ade7SAditya Kumar 
746807960e6SSergey Dmitriev   auto LookupAC = [&FAM](Function &F) -> AssumptionCache * {
747807960e6SSergey Dmitriev     return FAM.getCachedResult<AssumptionAnalysis>(F);
7489e20ade7SAditya Kumar   };
7499e20ade7SAditya Kumar 
7509e20ade7SAditya Kumar   auto GBFI = [&FAM](Function &F) {
7519e20ade7SAditya Kumar     return &FAM.getResult<BlockFrequencyAnalysis>(F);
7529e20ade7SAditya Kumar   };
7539e20ade7SAditya Kumar 
7549e20ade7SAditya Kumar   std::function<TargetTransformInfo &(Function &)> GTTI =
7559e20ade7SAditya Kumar       [&FAM](Function &F) -> TargetTransformInfo & {
7569e20ade7SAditya Kumar     return FAM.getResult<TargetIRAnalysis>(F);
7579e20ade7SAditya Kumar   };
7589e20ade7SAditya Kumar 
7599e20ade7SAditya Kumar   std::unique_ptr<OptimizationRemarkEmitter> ORE;
7609e20ade7SAditya Kumar   std::function<OptimizationRemarkEmitter &(Function &)> GetORE =
7619e20ade7SAditya Kumar       [&ORE](Function &F) -> OptimizationRemarkEmitter & {
7629e20ade7SAditya Kumar     ORE.reset(new OptimizationRemarkEmitter(&F));
763bce1bf0eSKazu Hirata     return *ORE;
7649e20ade7SAditya Kumar   };
7659e20ade7SAditya Kumar 
7669e20ade7SAditya Kumar   ProfileSummaryInfo *PSI = &AM.getResult<ProfileSummaryAnalysis>(M);
7679e20ade7SAditya Kumar 
768807960e6SSergey Dmitriev   if (HotColdSplitting(PSI, GBFI, GTTI, &GetORE, LookupAC).run(M))
7699e20ade7SAditya Kumar     return PreservedAnalyses::none();
7709e20ade7SAditya Kumar   return PreservedAnalyses::all();
7719e20ade7SAditya Kumar }
7729e20ade7SAditya Kumar 
773801394a3SAditya Kumar char HotColdSplittingLegacyPass::ID = 0;
7740628bea5SHans Wennborg INITIALIZE_PASS_BEGIN(HotColdSplittingLegacyPass, "hotcoldsplit",
7750628bea5SHans Wennborg                       "Hot Cold Splitting", false, false)
INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)776801394a3SAditya Kumar INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)
777801394a3SAditya Kumar INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
7780628bea5SHans Wennborg INITIALIZE_PASS_END(HotColdSplittingLegacyPass, "hotcoldsplit",
7790628bea5SHans Wennborg                     "Hot Cold Splitting", false, false)
780801394a3SAditya Kumar 
781801394a3SAditya Kumar ModulePass *llvm::createHotColdSplittingPass() {
782801394a3SAditya Kumar   return new HotColdSplittingLegacyPass();
783801394a3SAditya Kumar }
784