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