Aditya Kumar | 801394a | 2018-09-07 15:03:49 +0000 | [diff] [blame] | 1 | //===- HotColdSplitting.cpp -- Outline Cold Regions -------------*- C++ -*-===// |
| 2 | // |
| 3 | // The LLVM Compiler Infrastructure |
| 4 | // |
| 5 | // This file is distributed under the University of Illinois Open Source |
| 6 | // License. See LICENSE.TXT for details. |
| 7 | // |
| 8 | //===----------------------------------------------------------------------===// |
| 9 | // |
| 10 | // Outline cold regions to a separate function. |
| 11 | // TODO: Update BFI and BPI |
| 12 | // TODO: Add all the outlined functions to a separate section. |
| 13 | // |
| 14 | //===----------------------------------------------------------------------===// |
| 15 | |
Vedant Kumar | 03aaa3e | 2018-12-07 20:23:52 +0000 | [diff] [blame] | 16 | #include "llvm/ADT/PostOrderIterator.h" |
Aditya Kumar | 801394a | 2018-09-07 15:03:49 +0000 | [diff] [blame] | 17 | #include "llvm/ADT/SmallVector.h" |
| 18 | #include "llvm/ADT/Statistic.h" |
| 19 | #include "llvm/Analysis/AliasAnalysis.h" |
| 20 | #include "llvm/Analysis/BlockFrequencyInfo.h" |
| 21 | #include "llvm/Analysis/BranchProbabilityInfo.h" |
| 22 | #include "llvm/Analysis/CFG.h" |
| 23 | #include "llvm/Analysis/OptimizationRemarkEmitter.h" |
| 24 | #include "llvm/Analysis/PostDominators.h" |
| 25 | #include "llvm/Analysis/ProfileSummaryInfo.h" |
Sebastian Pop | a1f20fc | 2018-09-10 15:08:02 +0000 | [diff] [blame] | 26 | #include "llvm/Analysis/TargetTransformInfo.h" |
Aditya Kumar | 801394a | 2018-09-07 15:03:49 +0000 | [diff] [blame] | 27 | #include "llvm/IR/BasicBlock.h" |
| 28 | #include "llvm/IR/CFG.h" |
Vedant Kumar | 03f9f15 | 2018-12-07 20:24:04 +0000 | [diff] [blame] | 29 | #include "llvm/IR/CallSite.h" |
Aditya Kumar | 801394a | 2018-09-07 15:03:49 +0000 | [diff] [blame] | 30 | #include "llvm/IR/DataLayout.h" |
| 31 | #include "llvm/IR/DiagnosticInfo.h" |
| 32 | #include "llvm/IR/Dominators.h" |
| 33 | #include "llvm/IR/Function.h" |
| 34 | #include "llvm/IR/Instruction.h" |
| 35 | #include "llvm/IR/Instructions.h" |
Vedant Kumar | dd4be53 | 2018-10-29 19:15:39 +0000 | [diff] [blame] | 36 | #include "llvm/IR/IntrinsicInst.h" |
Aditya Kumar | 801394a | 2018-09-07 15:03:49 +0000 | [diff] [blame] | 37 | #include "llvm/IR/Metadata.h" |
| 38 | #include "llvm/IR/Module.h" |
| 39 | #include "llvm/IR/PassManager.h" |
| 40 | #include "llvm/IR/Type.h" |
| 41 | #include "llvm/IR/Use.h" |
| 42 | #include "llvm/IR/User.h" |
| 43 | #include "llvm/IR/Value.h" |
| 44 | #include "llvm/Pass.h" |
| 45 | #include "llvm/Support/BlockFrequency.h" |
| 46 | #include "llvm/Support/BranchProbability.h" |
| 47 | #include "llvm/Support/Debug.h" |
| 48 | #include "llvm/Support/raw_ostream.h" |
| 49 | #include "llvm/Transforms/IPO.h" |
Aditya Kumar | 9e20ade | 2018-10-03 05:55:20 +0000 | [diff] [blame] | 50 | #include "llvm/Transforms/IPO/HotColdSplitting.h" |
Aditya Kumar | 801394a | 2018-09-07 15:03:49 +0000 | [diff] [blame] | 51 | #include "llvm/Transforms/Scalar.h" |
| 52 | #include "llvm/Transforms/Utils/BasicBlockUtils.h" |
| 53 | #include "llvm/Transforms/Utils/Cloning.h" |
| 54 | #include "llvm/Transforms/Utils/CodeExtractor.h" |
| 55 | #include "llvm/Transforms/Utils/Local.h" |
| 56 | #include "llvm/Transforms/Utils/SSAUpdater.h" |
| 57 | #include "llvm/Transforms/Utils/ValueMapper.h" |
| 58 | #include <algorithm> |
| 59 | #include <cassert> |
| 60 | |
| 61 | #define DEBUG_TYPE "hotcoldsplit" |
| 62 | |
Vedant Kumar | c299006 | 2018-10-24 22:15:41 +0000 | [diff] [blame] | 63 | STATISTIC(NumColdRegionsFound, "Number of cold regions found."); |
| 64 | STATISTIC(NumColdRegionsOutlined, "Number of cold regions outlined."); |
Aditya Kumar | 801394a | 2018-09-07 15:03:49 +0000 | [diff] [blame] | 65 | |
| 66 | using namespace llvm; |
| 67 | |
| 68 | static cl::opt<bool> EnableStaticAnalyis("hot-cold-static-analysis", |
| 69 | cl::init(true), cl::Hidden); |
| 70 | |
Vedant Kumar | d2a895a | 2018-11-04 23:11:57 +0000 | [diff] [blame] | 71 | static cl::opt<int> |
Vedant Kumar | 32a014d | 2019-01-17 21:29:34 +0000 | [diff] [blame^] | 72 | SplittingThreshold("hotcoldsplit-threshold", cl::init(3), cl::Hidden, |
| 73 | cl::desc("Code size threshold for splitting cold code " |
| 74 | "(as a multiple of TCC_Basic)")); |
Aditya Kumar | 801394a | 2018-09-07 15:03:49 +0000 | [diff] [blame] | 75 | |
| 76 | namespace { |
| 77 | |
| 78 | struct PostDomTree : PostDomTreeBase<BasicBlock> { |
| 79 | PostDomTree(Function &F) { recalculate(F); } |
| 80 | }; |
| 81 | |
Vedant Kumar | c299006 | 2018-10-24 22:15:41 +0000 | [diff] [blame] | 82 | /// A sequence of basic blocks. |
| 83 | /// |
| 84 | /// A 0-sized SmallVector is slightly cheaper to move than a std::vector. |
| 85 | using BlockSequence = SmallVector<BasicBlock *, 0>; |
Aditya Kumar | 801394a | 2018-09-07 15:03:49 +0000 | [diff] [blame] | 86 | |
Sebastian Pop | 542e522 | 2018-10-15 21:43:11 +0000 | [diff] [blame] | 87 | // Same as blockEndsInUnreachable in CodeGen/BranchFolding.cpp. Do not modify |
| 88 | // this function unless you modify the MBB version as well. |
| 89 | // |
| 90 | /// A no successor, non-return block probably ends in unreachable and is cold. |
| 91 | /// Also consider a block that ends in an indirect branch to be a return block, |
| 92 | /// since many targets use plain indirect branches to return. |
Aditya Kumar | 801394a | 2018-09-07 15:03:49 +0000 | [diff] [blame] | 93 | bool blockEndsInUnreachable(const BasicBlock &BB) { |
Sebastian Pop | 542e522 | 2018-10-15 21:43:11 +0000 | [diff] [blame] | 94 | if (!succ_empty(&BB)) |
| 95 | return false; |
Aditya Kumar | 801394a | 2018-09-07 15:03:49 +0000 | [diff] [blame] | 96 | if (BB.empty()) |
| 97 | return true; |
Chandler Carruth | edb12a8 | 2018-10-15 10:04:59 +0000 | [diff] [blame] | 98 | const Instruction *I = BB.getTerminator(); |
Sebastian Pop | 542e522 | 2018-10-15 21:43:11 +0000 | [diff] [blame] | 99 | return !(isa<ReturnInst>(I) || isa<IndirectBrInst>(I)); |
Aditya Kumar | 801394a | 2018-09-07 15:03:49 +0000 | [diff] [blame] | 100 | } |
| 101 | |
Vedant Kumar | 03f9f15 | 2018-12-07 20:24:04 +0000 | [diff] [blame] | 102 | bool unlikelyExecuted(BasicBlock &BB) { |
Aditya Kumar | 801394a | 2018-09-07 15:03:49 +0000 | [diff] [blame] | 103 | // Exception handling blocks are unlikely executed. |
| 104 | if (BB.isEHPad()) |
| 105 | return true; |
Vedant Kumar | 03f9f15 | 2018-12-07 20:24:04 +0000 | [diff] [blame] | 106 | |
| 107 | // The block is cold if it calls/invokes a cold function. |
| 108 | for (Instruction &I : BB) |
| 109 | if (auto CS = CallSite(&I)) |
| 110 | if (CS.hasFnAttr(Attribute::Cold)) |
Aditya Kumar | 801394a | 2018-09-07 15:03:49 +0000 | [diff] [blame] | 111 | return true; |
| 112 | |
Vedant Kumar | 03f9f15 | 2018-12-07 20:24:04 +0000 | [diff] [blame] | 113 | // The block is cold if it has an unreachable terminator, unless it's |
| 114 | // preceded by a call to a (possibly warm) noreturn call (e.g. longjmp). |
| 115 | if (blockEndsInUnreachable(BB)) { |
| 116 | if (auto *CI = |
| 117 | dyn_cast_or_null<CallInst>(BB.getTerminator()->getPrevNode())) |
| 118 | if (CI->hasFnAttr(Attribute::NoReturn)) |
Aditya Kumar | 801394a | 2018-09-07 15:03:49 +0000 | [diff] [blame] | 119 | return false; |
Vedant Kumar | 03f9f15 | 2018-12-07 20:24:04 +0000 | [diff] [blame] | 120 | return true; |
| 121 | } |
| 122 | |
Aditya Kumar | 801394a | 2018-09-07 15:03:49 +0000 | [diff] [blame] | 123 | return false; |
| 124 | } |
| 125 | |
Vedant Kumar | c299006 | 2018-10-24 22:15:41 +0000 | [diff] [blame] | 126 | /// Check whether it's safe to outline \p BB. |
| 127 | static bool mayExtractBlock(const BasicBlock &BB) { |
Vedant Kumar | b3a7cae | 2018-12-11 18:05:31 +0000 | [diff] [blame] | 128 | return !BB.hasAddressTaken() && !BB.isEHPad(); |
Sebastian Pop | 542e522 | 2018-10-15 21:43:11 +0000 | [diff] [blame] | 129 | } |
| 130 | |
Vedant Kumar | 03aaa3e | 2018-12-07 20:23:52 +0000 | [diff] [blame] | 131 | /// Check whether \p Region is profitable to outline. |
| 132 | static bool isProfitableToOutline(const BlockSequence &Region, |
Vedant Kumar | d2a895a | 2018-11-04 23:11:57 +0000 | [diff] [blame] | 133 | TargetTransformInfo &TTI) { |
Vedant Kumar | 32a014d | 2019-01-17 21:29:34 +0000 | [diff] [blame^] | 134 | // If the splitting threshold is set at or below zero, skip the usual |
| 135 | // profitability check. |
| 136 | if (SplittingThreshold <= 0) |
| 137 | return true; |
| 138 | |
Vedant Kumar | 03aaa3e | 2018-12-07 20:23:52 +0000 | [diff] [blame] | 139 | if (Region.size() > 1) |
| 140 | return true; |
| 141 | |
Vedant Kumar | d2a895a | 2018-11-04 23:11:57 +0000 | [diff] [blame] | 142 | int Cost = 0; |
Vedant Kumar | 03aaa3e | 2018-12-07 20:23:52 +0000 | [diff] [blame] | 143 | const BasicBlock &BB = *Region[0]; |
Vedant Kumar | dd4be53 | 2018-10-29 19:15:39 +0000 | [diff] [blame] | 144 | for (const Instruction &I : BB) { |
| 145 | if (isa<DbgInfoIntrinsic>(&I) || &I == BB.getTerminator()) |
| 146 | continue; |
Vedant Kumar | d2a895a | 2018-11-04 23:11:57 +0000 | [diff] [blame] | 147 | |
| 148 | Cost += TTI.getInstructionCost(&I, TargetTransformInfo::TCK_CodeSize); |
| 149 | |
Vedant Kumar | 32a014d | 2019-01-17 21:29:34 +0000 | [diff] [blame^] | 150 | if (Cost >= (SplittingThreshold * TargetTransformInfo::TCC_Basic)) |
Vedant Kumar | dd4be53 | 2018-10-29 19:15:39 +0000 | [diff] [blame] | 151 | return true; |
| 152 | } |
| 153 | return false; |
| 154 | } |
| 155 | |
Vedant Kumar | 03aaa3e | 2018-12-07 20:23:52 +0000 | [diff] [blame] | 156 | /// Mark \p F cold. Return true if it's changed. |
| 157 | static bool markEntireFunctionCold(Function &F) { |
| 158 | assert(!F.hasFnAttribute(Attribute::OptimizeNone) && "Can't mark this cold"); |
| 159 | bool Changed = false; |
| 160 | if (!F.hasFnAttribute(Attribute::MinSize)) { |
| 161 | F.addFnAttr(Attribute::MinSize); |
| 162 | Changed = true; |
Aditya Kumar | 801394a | 2018-09-07 15:03:49 +0000 | [diff] [blame] | 163 | } |
Vedant Kumar | 03aaa3e | 2018-12-07 20:23:52 +0000 | [diff] [blame] | 164 | // TODO: Move this function into a cold section. |
| 165 | return Changed; |
Aditya Kumar | 801394a | 2018-09-07 15:03:49 +0000 | [diff] [blame] | 166 | } |
| 167 | |
| 168 | class HotColdSplitting { |
| 169 | public: |
| 170 | HotColdSplitting(ProfileSummaryInfo *ProfSI, |
| 171 | function_ref<BlockFrequencyInfo *(Function &)> GBFI, |
Sebastian Pop | a1f20fc | 2018-09-10 15:08:02 +0000 | [diff] [blame] | 172 | function_ref<TargetTransformInfo &(Function &)> GTTI, |
Aditya Kumar | 801394a | 2018-09-07 15:03:49 +0000 | [diff] [blame] | 173 | std::function<OptimizationRemarkEmitter &(Function &)> *GORE) |
Sebastian Pop | a1f20fc | 2018-09-10 15:08:02 +0000 | [diff] [blame] | 174 | : PSI(ProfSI), GetBFI(GBFI), GetTTI(GTTI), GetORE(GORE) {} |
Aditya Kumar | 801394a | 2018-09-07 15:03:49 +0000 | [diff] [blame] | 175 | bool run(Module &M); |
| 176 | |
| 177 | private: |
| 178 | bool shouldOutlineFrom(const Function &F) const; |
Vedant Kumar | 03aaa3e | 2018-12-07 20:23:52 +0000 | [diff] [blame] | 179 | bool outlineColdRegions(Function &F, ProfileSummaryInfo &PSI, |
| 180 | BlockFrequencyInfo *BFI, TargetTransformInfo &TTI, |
| 181 | DominatorTree &DT, PostDomTree &PDT, |
| 182 | OptimizationRemarkEmitter &ORE); |
Vedant Kumar | c299006 | 2018-10-24 22:15:41 +0000 | [diff] [blame] | 183 | Function *extractColdRegion(const BlockSequence &Region, DominatorTree &DT, |
Vedant Kumar | d2a895a | 2018-11-04 23:11:57 +0000 | [diff] [blame] | 184 | BlockFrequencyInfo *BFI, TargetTransformInfo &TTI, |
Teresa Johnson | c8dba68 | 2018-10-24 18:53:47 +0000 | [diff] [blame] | 185 | OptimizationRemarkEmitter &ORE, unsigned Count); |
Aditya Kumar | 801394a | 2018-09-07 15:03:49 +0000 | [diff] [blame] | 186 | SmallPtrSet<const Function *, 2> OutlinedFunctions; |
| 187 | ProfileSummaryInfo *PSI; |
| 188 | function_ref<BlockFrequencyInfo *(Function &)> GetBFI; |
Sebastian Pop | a1f20fc | 2018-09-10 15:08:02 +0000 | [diff] [blame] | 189 | function_ref<TargetTransformInfo &(Function &)> GetTTI; |
Aditya Kumar | 801394a | 2018-09-07 15:03:49 +0000 | [diff] [blame] | 190 | std::function<OptimizationRemarkEmitter &(Function &)> *GetORE; |
| 191 | }; |
| 192 | |
| 193 | class HotColdSplittingLegacyPass : public ModulePass { |
| 194 | public: |
| 195 | static char ID; |
| 196 | HotColdSplittingLegacyPass() : ModulePass(ID) { |
| 197 | initializeHotColdSplittingLegacyPassPass(*PassRegistry::getPassRegistry()); |
| 198 | } |
| 199 | |
| 200 | void getAnalysisUsage(AnalysisUsage &AU) const override { |
| 201 | AU.addRequired<AssumptionCacheTracker>(); |
| 202 | AU.addRequired<BlockFrequencyInfoWrapperPass>(); |
| 203 | AU.addRequired<ProfileSummaryInfoWrapperPass>(); |
Sebastian Pop | a1f20fc | 2018-09-10 15:08:02 +0000 | [diff] [blame] | 204 | AU.addRequired<TargetTransformInfoWrapperPass>(); |
Aditya Kumar | 801394a | 2018-09-07 15:03:49 +0000 | [diff] [blame] | 205 | } |
| 206 | |
| 207 | bool runOnModule(Module &M) override; |
| 208 | }; |
| 209 | |
| 210 | } // end anonymous namespace |
| 211 | |
| 212 | // Returns false if the function should not be considered for hot-cold split |
Sebastian Pop | 0f30f08 | 2018-09-14 20:36:19 +0000 | [diff] [blame] | 213 | // optimization. |
Aditya Kumar | 801394a | 2018-09-07 15:03:49 +0000 | [diff] [blame] | 214 | bool HotColdSplitting::shouldOutlineFrom(const Function &F) const { |
Sebastian Pop | 0f30f08 | 2018-09-14 20:36:19 +0000 | [diff] [blame] | 215 | // Do not try to outline again from an already outlined cold function. |
| 216 | if (OutlinedFunctions.count(&F)) |
| 217 | return false; |
| 218 | |
Aditya Kumar | 801394a | 2018-09-07 15:03:49 +0000 | [diff] [blame] | 219 | if (F.size() <= 2) |
| 220 | return false; |
| 221 | |
Vedant Kumar | c299006 | 2018-10-24 22:15:41 +0000 | [diff] [blame] | 222 | // TODO: Consider only skipping functions marked `optnone` or `cold`. |
| 223 | |
Aditya Kumar | 801394a | 2018-09-07 15:03:49 +0000 | [diff] [blame] | 224 | if (F.hasAddressTaken()) |
| 225 | return false; |
| 226 | |
| 227 | if (F.hasFnAttribute(Attribute::AlwaysInline)) |
| 228 | return false; |
| 229 | |
| 230 | if (F.hasFnAttribute(Attribute::NoInline)) |
| 231 | return false; |
| 232 | |
| 233 | if (F.getCallingConv() == CallingConv::Cold) |
| 234 | return false; |
| 235 | |
| 236 | if (PSI->isFunctionEntryCold(&F)) |
| 237 | return false; |
| 238 | return true; |
| 239 | } |
| 240 | |
Vedant Kumar | c299006 | 2018-10-24 22:15:41 +0000 | [diff] [blame] | 241 | Function *HotColdSplitting::extractColdRegion(const BlockSequence &Region, |
| 242 | DominatorTree &DT, |
| 243 | BlockFrequencyInfo *BFI, |
Vedant Kumar | d2a895a | 2018-11-04 23:11:57 +0000 | [diff] [blame] | 244 | TargetTransformInfo &TTI, |
Vedant Kumar | c299006 | 2018-10-24 22:15:41 +0000 | [diff] [blame] | 245 | OptimizationRemarkEmitter &ORE, |
| 246 | unsigned Count) { |
Teresa Johnson | f431a2f | 2018-10-22 19:06:42 +0000 | [diff] [blame] | 247 | assert(!Region.empty()); |
Sebastian Pop | 1217160 | 2018-09-14 20:36:10 +0000 | [diff] [blame] | 248 | |
Aditya Kumar | 801394a | 2018-09-07 15:03:49 +0000 | [diff] [blame] | 249 | // TODO: Pass BFI and BPI to update profile information. |
Vedant Kumar | c299006 | 2018-10-24 22:15:41 +0000 | [diff] [blame] | 250 | CodeExtractor CE(Region, &DT, /* AggregateArgs */ false, /* BFI */ nullptr, |
Teresa Johnson | c8dba68 | 2018-10-24 18:53:47 +0000 | [diff] [blame] | 251 | /* BPI */ nullptr, /* AllowVarArgs */ false, |
| 252 | /* AllowAlloca */ false, |
| 253 | /* Suffix */ "cold." + std::to_string(Count)); |
Aditya Kumar | 801394a | 2018-09-07 15:03:49 +0000 | [diff] [blame] | 254 | |
| 255 | SetVector<Value *> Inputs, Outputs, Sinks; |
| 256 | CE.findInputsOutputs(Inputs, Outputs, Sinks); |
| 257 | |
| 258 | // Do not extract regions that have live exit variables. |
Vedant Kumar | c299006 | 2018-10-24 22:15:41 +0000 | [diff] [blame] | 259 | if (Outputs.size() > 0) { |
| 260 | LLVM_DEBUG(llvm::dbgs() << "Not outlining; live outputs\n"); |
Aditya Kumar | 801394a | 2018-09-07 15:03:49 +0000 | [diff] [blame] | 261 | return nullptr; |
Vedant Kumar | c299006 | 2018-10-24 22:15:41 +0000 | [diff] [blame] | 262 | } |
Aditya Kumar | 801394a | 2018-09-07 15:03:49 +0000 | [diff] [blame] | 263 | |
Vedant Kumar | c299006 | 2018-10-24 22:15:41 +0000 | [diff] [blame] | 264 | // TODO: Run MergeBasicBlockIntoOnlyPred on the outlined function. |
Teresa Johnson | f431a2f | 2018-10-22 19:06:42 +0000 | [diff] [blame] | 265 | Function *OrigF = Region[0]->getParent(); |
Aditya Kumar | 801394a | 2018-09-07 15:03:49 +0000 | [diff] [blame] | 266 | if (Function *OutF = CE.extractCodeRegion()) { |
| 267 | User *U = *OutF->user_begin(); |
| 268 | CallInst *CI = cast<CallInst>(U); |
| 269 | CallSite CS(CI); |
Vedant Kumar | c299006 | 2018-10-24 22:15:41 +0000 | [diff] [blame] | 270 | NumColdRegionsOutlined++; |
Vedant Kumar | d2a895a | 2018-11-04 23:11:57 +0000 | [diff] [blame] | 271 | if (TTI.useColdCCForColdCall(*OutF)) { |
Sebastian Pop | a1f20fc | 2018-09-10 15:08:02 +0000 | [diff] [blame] | 272 | OutF->setCallingConv(CallingConv::Cold); |
| 273 | CS.setCallingConv(CallingConv::Cold); |
| 274 | } |
Aditya Kumar | 801394a | 2018-09-07 15:03:49 +0000 | [diff] [blame] | 275 | CI->setIsNoInline(); |
Vedant Kumar | 5031546 | 2018-10-23 19:41:12 +0000 | [diff] [blame] | 276 | |
| 277 | // Try to make the outlined code as small as possible on the assumption |
| 278 | // that it's cold. |
Vedant Kumar | 03aaa3e | 2018-12-07 20:23:52 +0000 | [diff] [blame] | 279 | markEntireFunctionCold(*OutF); |
Vedant Kumar | 5031546 | 2018-10-23 19:41:12 +0000 | [diff] [blame] | 280 | |
Sebastian Pop | 0f30f08 | 2018-09-14 20:36:19 +0000 | [diff] [blame] | 281 | LLVM_DEBUG(llvm::dbgs() << "Outlined Region: " << *OutF); |
Teresa Johnson | f431a2f | 2018-10-22 19:06:42 +0000 | [diff] [blame] | 282 | ORE.emit([&]() { |
| 283 | return OptimizationRemark(DEBUG_TYPE, "HotColdSplit", |
| 284 | &*Region[0]->begin()) |
| 285 | << ore::NV("Original", OrigF) << " split cold code into " |
| 286 | << ore::NV("Split", OutF); |
| 287 | }); |
Aditya Kumar | 801394a | 2018-09-07 15:03:49 +0000 | [diff] [blame] | 288 | return OutF; |
| 289 | } |
| 290 | |
| 291 | ORE.emit([&]() { |
| 292 | return OptimizationRemarkMissed(DEBUG_TYPE, "ExtractFailed", |
| 293 | &*Region[0]->begin()) |
| 294 | << "Failed to extract region at block " |
| 295 | << ore::NV("Block", Region.front()); |
| 296 | }); |
| 297 | return nullptr; |
| 298 | } |
| 299 | |
Vedant Kumar | 03aaa3e | 2018-12-07 20:23:52 +0000 | [diff] [blame] | 300 | /// A pair of (basic block, score). |
| 301 | using BlockTy = std::pair<BasicBlock *, unsigned>; |
| 302 | |
Benjamin Kramer | b17d213 | 2019-01-12 18:36:22 +0000 | [diff] [blame] | 303 | namespace { |
Vedant Kumar | 03aaa3e | 2018-12-07 20:23:52 +0000 | [diff] [blame] | 304 | /// A maximal outlining region. This contains all blocks post-dominated by a |
| 305 | /// sink block, the sink block itself, and all blocks dominated by the sink. |
| 306 | class OutliningRegion { |
| 307 | /// A list of (block, score) pairs. A block's score is non-zero iff it's a |
| 308 | /// viable sub-region entry point. Blocks with higher scores are better entry |
| 309 | /// points (i.e. they are more distant ancestors of the sink block). |
| 310 | SmallVector<BlockTy, 0> Blocks = {}; |
| 311 | |
| 312 | /// The suggested entry point into the region. If the region has multiple |
| 313 | /// entry points, all blocks within the region may not be reachable from this |
| 314 | /// entry point. |
| 315 | BasicBlock *SuggestedEntryPoint = nullptr; |
| 316 | |
| 317 | /// Whether the entire function is cold. |
| 318 | bool EntireFunctionCold = false; |
| 319 | |
| 320 | /// Whether or not \p BB could be the entry point of an extracted region. |
| 321 | static bool isViableEntryPoint(BasicBlock &BB) { return !BB.isEHPad(); } |
| 322 | |
| 323 | /// If \p BB is a viable entry point, return \p Score. Return 0 otherwise. |
| 324 | static unsigned getEntryPointScore(BasicBlock &BB, unsigned Score) { |
| 325 | return isViableEntryPoint(BB) ? Score : 0; |
| 326 | } |
| 327 | |
| 328 | /// These scores should be lower than the score for predecessor blocks, |
| 329 | /// because regions starting at predecessor blocks are typically larger. |
| 330 | static constexpr unsigned ScoreForSuccBlock = 1; |
| 331 | static constexpr unsigned ScoreForSinkBlock = 1; |
| 332 | |
| 333 | OutliningRegion(const OutliningRegion &) = delete; |
| 334 | OutliningRegion &operator=(const OutliningRegion &) = delete; |
| 335 | |
| 336 | public: |
| 337 | OutliningRegion() = default; |
| 338 | OutliningRegion(OutliningRegion &&) = default; |
| 339 | OutliningRegion &operator=(OutliningRegion &&) = default; |
| 340 | |
| 341 | static OutliningRegion create(BasicBlock &SinkBB, const DominatorTree &DT, |
| 342 | const PostDomTree &PDT) { |
| 343 | OutliningRegion ColdRegion; |
| 344 | |
| 345 | SmallPtrSet<BasicBlock *, 4> RegionBlocks; |
| 346 | |
| 347 | auto addBlockToRegion = [&](BasicBlock *BB, unsigned Score) { |
| 348 | RegionBlocks.insert(BB); |
| 349 | ColdRegion.Blocks.emplace_back(BB, Score); |
| 350 | assert(RegionBlocks.size() == ColdRegion.Blocks.size() && "Duplicate BB"); |
| 351 | }; |
| 352 | |
| 353 | // The ancestor farthest-away from SinkBB, and also post-dominated by it. |
| 354 | unsigned SinkScore = getEntryPointScore(SinkBB, ScoreForSinkBlock); |
| 355 | ColdRegion.SuggestedEntryPoint = (SinkScore > 0) ? &SinkBB : nullptr; |
| 356 | unsigned BestScore = SinkScore; |
| 357 | |
| 358 | // Visit SinkBB's ancestors using inverse DFS. |
| 359 | auto PredIt = ++idf_begin(&SinkBB); |
| 360 | auto PredEnd = idf_end(&SinkBB); |
| 361 | while (PredIt != PredEnd) { |
| 362 | BasicBlock &PredBB = **PredIt; |
| 363 | bool SinkPostDom = PDT.dominates(&SinkBB, &PredBB); |
| 364 | |
| 365 | // If the predecessor is cold and has no predecessors, the entire |
| 366 | // function must be cold. |
| 367 | if (SinkPostDom && pred_empty(&PredBB)) { |
| 368 | ColdRegion.EntireFunctionCold = true; |
| 369 | return ColdRegion; |
| 370 | } |
| 371 | |
| 372 | // If SinkBB does not post-dominate a predecessor, do not mark the |
| 373 | // predecessor (or any of its predecessors) cold. |
| 374 | if (!SinkPostDom || !mayExtractBlock(PredBB)) { |
| 375 | PredIt.skipChildren(); |
| 376 | continue; |
| 377 | } |
| 378 | |
| 379 | // Keep track of the post-dominated ancestor farthest away from the sink. |
| 380 | // The path length is always >= 2, ensuring that predecessor blocks are |
| 381 | // considered as entry points before the sink block. |
| 382 | unsigned PredScore = getEntryPointScore(PredBB, PredIt.getPathLength()); |
| 383 | if (PredScore > BestScore) { |
| 384 | ColdRegion.SuggestedEntryPoint = &PredBB; |
| 385 | BestScore = PredScore; |
| 386 | } |
| 387 | |
| 388 | addBlockToRegion(&PredBB, PredScore); |
| 389 | ++PredIt; |
Vedant Kumar | c299006 | 2018-10-24 22:15:41 +0000 | [diff] [blame] | 390 | } |
| 391 | |
Vedant Kumar | 03aaa3e | 2018-12-07 20:23:52 +0000 | [diff] [blame] | 392 | // Add SinkBB to the cold region. It's considered as an entry point before |
| 393 | // any sink-successor blocks. |
| 394 | addBlockToRegion(&SinkBB, SinkScore); |
| 395 | |
| 396 | // Find all successors of SinkBB dominated by SinkBB using DFS. |
| 397 | auto SuccIt = ++df_begin(&SinkBB); |
| 398 | auto SuccEnd = df_end(&SinkBB); |
| 399 | while (SuccIt != SuccEnd) { |
| 400 | BasicBlock &SuccBB = **SuccIt; |
| 401 | bool SinkDom = DT.dominates(&SinkBB, &SuccBB); |
| 402 | |
| 403 | // Don't allow the backwards & forwards DFSes to mark the same block. |
| 404 | bool DuplicateBlock = RegionBlocks.count(&SuccBB); |
| 405 | |
| 406 | // If SinkBB does not dominate a successor, do not mark the successor (or |
| 407 | // any of its successors) cold. |
| 408 | if (DuplicateBlock || !SinkDom || !mayExtractBlock(SuccBB)) { |
| 409 | SuccIt.skipChildren(); |
| 410 | continue; |
| 411 | } |
| 412 | |
| 413 | unsigned SuccScore = getEntryPointScore(SuccBB, ScoreForSuccBlock); |
| 414 | if (SuccScore > BestScore) { |
| 415 | ColdRegion.SuggestedEntryPoint = &SuccBB; |
| 416 | BestScore = SuccScore; |
| 417 | } |
| 418 | |
| 419 | addBlockToRegion(&SuccBB, SuccScore); |
| 420 | ++SuccIt; |
| 421 | } |
| 422 | |
| 423 | return ColdRegion; |
| 424 | } |
| 425 | |
| 426 | /// Whether this region has nothing to extract. |
| 427 | bool empty() const { return !SuggestedEntryPoint; } |
| 428 | |
| 429 | /// The blocks in this region. |
| 430 | ArrayRef<std::pair<BasicBlock *, unsigned>> blocks() const { return Blocks; } |
| 431 | |
| 432 | /// Whether the entire function containing this region is cold. |
| 433 | bool isEntireFunctionCold() const { return EntireFunctionCold; } |
| 434 | |
| 435 | /// Remove a sub-region from this region and return it as a block sequence. |
| 436 | BlockSequence takeSingleEntrySubRegion(DominatorTree &DT) { |
| 437 | assert(!empty() && !isEntireFunctionCold() && "Nothing to extract"); |
| 438 | |
| 439 | // Remove blocks dominated by the suggested entry point from this region. |
| 440 | // During the removal, identify the next best entry point into the region. |
| 441 | // Ensure that the first extracted block is the suggested entry point. |
| 442 | BlockSequence SubRegion = {SuggestedEntryPoint}; |
| 443 | BasicBlock *NextEntryPoint = nullptr; |
| 444 | unsigned NextScore = 0; |
| 445 | auto RegionEndIt = Blocks.end(); |
| 446 | auto RegionStartIt = remove_if(Blocks, [&](const BlockTy &Block) { |
| 447 | BasicBlock *BB = Block.first; |
| 448 | unsigned Score = Block.second; |
| 449 | bool InSubRegion = |
| 450 | BB == SuggestedEntryPoint || DT.dominates(SuggestedEntryPoint, BB); |
| 451 | if (!InSubRegion && Score > NextScore) { |
| 452 | NextEntryPoint = BB; |
| 453 | NextScore = Score; |
| 454 | } |
| 455 | if (InSubRegion && BB != SuggestedEntryPoint) |
| 456 | SubRegion.push_back(BB); |
| 457 | return InSubRegion; |
| 458 | }); |
| 459 | Blocks.erase(RegionStartIt, RegionEndIt); |
| 460 | |
| 461 | // Update the suggested entry point. |
| 462 | SuggestedEntryPoint = NextEntryPoint; |
| 463 | |
| 464 | return SubRegion; |
| 465 | } |
| 466 | }; |
Benjamin Kramer | b17d213 | 2019-01-12 18:36:22 +0000 | [diff] [blame] | 467 | } // namespace |
Vedant Kumar | 03aaa3e | 2018-12-07 20:23:52 +0000 | [diff] [blame] | 468 | |
| 469 | bool HotColdSplitting::outlineColdRegions(Function &F, ProfileSummaryInfo &PSI, |
| 470 | BlockFrequencyInfo *BFI, |
| 471 | TargetTransformInfo &TTI, |
| 472 | DominatorTree &DT, PostDomTree &PDT, |
| 473 | OptimizationRemarkEmitter &ORE) { |
| 474 | bool Changed = false; |
| 475 | |
| 476 | // The set of cold blocks. |
| 477 | SmallPtrSet<BasicBlock *, 4> ColdBlocks; |
| 478 | |
| 479 | // The worklist of non-intersecting regions left to outline. |
| 480 | SmallVector<OutliningRegion, 2> OutliningWorklist; |
| 481 | |
| 482 | // Set up an RPO traversal. Experimentally, this performs better (outlines |
| 483 | // more) than a PO traversal, because we prevent region overlap by keeping |
| 484 | // the first region to contain a block. |
| 485 | ReversePostOrderTraversal<Function *> RPOT(&F); |
| 486 | |
| 487 | // Find all cold regions. |
| 488 | for (BasicBlock *BB : RPOT) { |
| 489 | // Skip blocks which can't be outlined. |
| 490 | if (!mayExtractBlock(*BB)) |
| 491 | continue; |
| 492 | |
| 493 | // This block is already part of some outlining region. |
| 494 | if (ColdBlocks.count(BB)) |
| 495 | continue; |
| 496 | |
| 497 | bool Cold = PSI.isColdBlock(BB, BFI) || |
| 498 | (EnableStaticAnalyis && unlikelyExecuted(*BB)); |
| 499 | if (!Cold) |
| 500 | continue; |
| 501 | |
| 502 | LLVM_DEBUG({ |
| 503 | dbgs() << "Found a cold block:\n"; |
| 504 | BB->dump(); |
| 505 | }); |
| 506 | |
| 507 | auto Region = OutliningRegion::create(*BB, DT, PDT); |
| 508 | if (Region.empty()) |
| 509 | continue; |
| 510 | |
| 511 | if (Region.isEntireFunctionCold()) { |
| 512 | LLVM_DEBUG(dbgs() << "Entire function is cold\n"); |
| 513 | return markEntireFunctionCold(F); |
| 514 | } |
| 515 | |
| 516 | // If this outlining region intersects with another, drop the new region. |
| 517 | // |
| 518 | // TODO: It's theoretically possible to outline more by only keeping the |
| 519 | // largest region which contains a block, but the extra bookkeeping to do |
| 520 | // this is tricky/expensive. |
| 521 | bool RegionsOverlap = any_of(Region.blocks(), [&](const BlockTy &Block) { |
| 522 | return !ColdBlocks.insert(Block.first).second; |
| 523 | }); |
| 524 | if (RegionsOverlap) |
| 525 | continue; |
| 526 | |
| 527 | OutliningWorklist.emplace_back(std::move(Region)); |
| 528 | ++NumColdRegionsFound; |
| 529 | } |
| 530 | |
| 531 | // Outline single-entry cold regions, splitting up larger regions as needed. |
| 532 | unsigned OutlinedFunctionID = 1; |
| 533 | while (!OutliningWorklist.empty()) { |
| 534 | OutliningRegion Region = OutliningWorklist.pop_back_val(); |
| 535 | assert(!Region.empty() && "Empty outlining region in worklist"); |
| 536 | do { |
| 537 | BlockSequence SubRegion = Region.takeSingleEntrySubRegion(DT); |
| 538 | if (!isProfitableToOutline(SubRegion, TTI)) { |
| 539 | LLVM_DEBUG({ |
| 540 | dbgs() << "Skipping outlining; not profitable to outline\n"; |
| 541 | SubRegion[0]->dump(); |
| 542 | }); |
| 543 | continue; |
| 544 | } |
| 545 | |
| 546 | LLVM_DEBUG({ |
| 547 | dbgs() << "Hot/cold splitting attempting to outline these blocks:\n"; |
| 548 | for (BasicBlock *BB : SubRegion) |
| 549 | BB->dump(); |
| 550 | }); |
| 551 | |
| 552 | Function *Outlined = |
| 553 | extractColdRegion(SubRegion, DT, BFI, TTI, ORE, OutlinedFunctionID); |
| 554 | if (Outlined) { |
| 555 | ++OutlinedFunctionID; |
| 556 | OutlinedFunctions.insert(Outlined); |
| 557 | Changed = true; |
| 558 | } |
| 559 | } while (!Region.empty()); |
| 560 | } |
| 561 | |
| 562 | return Changed; |
| 563 | } |
| 564 | |
| 565 | bool HotColdSplitting::run(Module &M) { |
| 566 | bool Changed = false; |
| 567 | OutlinedFunctions.clear(); |
| 568 | for (auto &F : M) { |
| 569 | if (!shouldOutlineFrom(F)) { |
| 570 | LLVM_DEBUG(llvm::dbgs() << "Skipping " << F.getName() << "\n"); |
| 571 | continue; |
| 572 | } |
Vedant Kumar | c299006 | 2018-10-24 22:15:41 +0000 | [diff] [blame] | 573 | LLVM_DEBUG(llvm::dbgs() << "Outlining in " << F.getName() << "\n"); |
Aditya Kumar | 801394a | 2018-09-07 15:03:49 +0000 | [diff] [blame] | 574 | DominatorTree DT(F); |
| 575 | PostDomTree PDT(F); |
| 576 | PDT.recalculate(F); |
Vedant Kumar | c299006 | 2018-10-24 22:15:41 +0000 | [diff] [blame] | 577 | BlockFrequencyInfo *BFI = GetBFI(F); |
Vedant Kumar | d2a895a | 2018-11-04 23:11:57 +0000 | [diff] [blame] | 578 | TargetTransformInfo &TTI = GetTTI(F); |
Vedant Kumar | c299006 | 2018-10-24 22:15:41 +0000 | [diff] [blame] | 579 | OptimizationRemarkEmitter &ORE = (*GetORE)(F); |
Vedant Kumar | 03aaa3e | 2018-12-07 20:23:52 +0000 | [diff] [blame] | 580 | Changed |= outlineColdRegions(F, *PSI, BFI, TTI, DT, PDT, ORE); |
Aditya Kumar | 801394a | 2018-09-07 15:03:49 +0000 | [diff] [blame] | 581 | } |
Vedant Kumar | c299006 | 2018-10-24 22:15:41 +0000 | [diff] [blame] | 582 | return Changed; |
Aditya Kumar | 801394a | 2018-09-07 15:03:49 +0000 | [diff] [blame] | 583 | } |
| 584 | |
| 585 | bool HotColdSplittingLegacyPass::runOnModule(Module &M) { |
| 586 | if (skipModule(M)) |
| 587 | return false; |
| 588 | ProfileSummaryInfo *PSI = |
Vedant Kumar | e7b789b | 2018-11-19 05:23:16 +0000 | [diff] [blame] | 589 | &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI(); |
Sebastian Pop | a1f20fc | 2018-09-10 15:08:02 +0000 | [diff] [blame] | 590 | auto GTTI = [this](Function &F) -> TargetTransformInfo & { |
| 591 | return this->getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F); |
| 592 | }; |
Aditya Kumar | 801394a | 2018-09-07 15:03:49 +0000 | [diff] [blame] | 593 | auto GBFI = [this](Function &F) { |
| 594 | return &this->getAnalysis<BlockFrequencyInfoWrapperPass>(F).getBFI(); |
| 595 | }; |
| 596 | std::unique_ptr<OptimizationRemarkEmitter> ORE; |
| 597 | std::function<OptimizationRemarkEmitter &(Function &)> GetORE = |
| 598 | [&ORE](Function &F) -> OptimizationRemarkEmitter & { |
| 599 | ORE.reset(new OptimizationRemarkEmitter(&F)); |
| 600 | return *ORE.get(); |
| 601 | }; |
| 602 | |
Sebastian Pop | a1f20fc | 2018-09-10 15:08:02 +0000 | [diff] [blame] | 603 | return HotColdSplitting(PSI, GBFI, GTTI, &GetORE).run(M); |
Aditya Kumar | 801394a | 2018-09-07 15:03:49 +0000 | [diff] [blame] | 604 | } |
| 605 | |
Aditya Kumar | 9e20ade | 2018-10-03 05:55:20 +0000 | [diff] [blame] | 606 | PreservedAnalyses |
| 607 | HotColdSplittingPass::run(Module &M, ModuleAnalysisManager &AM) { |
| 608 | auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager(); |
| 609 | |
| 610 | std::function<AssumptionCache &(Function &)> GetAssumptionCache = |
| 611 | [&FAM](Function &F) -> AssumptionCache & { |
| 612 | return FAM.getResult<AssumptionAnalysis>(F); |
| 613 | }; |
| 614 | |
| 615 | auto GBFI = [&FAM](Function &F) { |
| 616 | return &FAM.getResult<BlockFrequencyAnalysis>(F); |
| 617 | }; |
| 618 | |
| 619 | std::function<TargetTransformInfo &(Function &)> GTTI = |
| 620 | [&FAM](Function &F) -> TargetTransformInfo & { |
| 621 | return FAM.getResult<TargetIRAnalysis>(F); |
| 622 | }; |
| 623 | |
| 624 | std::unique_ptr<OptimizationRemarkEmitter> ORE; |
| 625 | std::function<OptimizationRemarkEmitter &(Function &)> GetORE = |
| 626 | [&ORE](Function &F) -> OptimizationRemarkEmitter & { |
| 627 | ORE.reset(new OptimizationRemarkEmitter(&F)); |
| 628 | return *ORE.get(); |
| 629 | }; |
| 630 | |
| 631 | ProfileSummaryInfo *PSI = &AM.getResult<ProfileSummaryAnalysis>(M); |
| 632 | |
| 633 | if (HotColdSplitting(PSI, GBFI, GTTI, &GetORE).run(M)) |
| 634 | return PreservedAnalyses::none(); |
| 635 | return PreservedAnalyses::all(); |
| 636 | } |
| 637 | |
Aditya Kumar | 801394a | 2018-09-07 15:03:49 +0000 | [diff] [blame] | 638 | char HotColdSplittingLegacyPass::ID = 0; |
| 639 | INITIALIZE_PASS_BEGIN(HotColdSplittingLegacyPass, "hotcoldsplit", |
| 640 | "Hot Cold Splitting", false, false) |
| 641 | INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass) |
| 642 | INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass) |
| 643 | INITIALIZE_PASS_END(HotColdSplittingLegacyPass, "hotcoldsplit", |
| 644 | "Hot Cold Splitting", false, false) |
| 645 | |
| 646 | ModulePass *llvm::createHotColdSplittingPass() { |
| 647 | return new HotColdSplittingLegacyPass(); |
| 648 | } |