LLVM  10.0.0
HotColdSplitting.cpp
Go to the documentation of this file.
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 
30 #include "llvm/ADT/SmallVector.h"
31 #include "llvm/ADT/Statistic.h"
35 #include "llvm/Analysis/CFG.h"
40 #include "llvm/IR/BasicBlock.h"
41 #include "llvm/IR/CFG.h"
42 #include "llvm/IR/CallSite.h"
43 #include "llvm/IR/DataLayout.h"
44 #include "llvm/IR/DiagnosticInfo.h"
45 #include "llvm/IR/Dominators.h"
46 #include "llvm/IR/Function.h"
47 #include "llvm/IR/Instruction.h"
48 #include "llvm/IR/Instructions.h"
49 #include "llvm/IR/IntrinsicInst.h"
50 #include "llvm/IR/Metadata.h"
51 #include "llvm/IR/Module.h"
52 #include "llvm/IR/PassManager.h"
53 #include "llvm/IR/Type.h"
54 #include "llvm/IR/Use.h"
55 #include "llvm/IR/User.h"
56 #include "llvm/IR/Value.h"
57 #include "llvm/InitializePasses.h"
58 #include "llvm/Pass.h"
62 #include "llvm/Support/Debug.h"
64 #include "llvm/Transforms/IPO.h"
65 #include "llvm/Transforms/Scalar.h"
71 #include <algorithm>
72 #include <cassert>
73 
74 #define DEBUG_TYPE "hotcoldsplit"
75 
76 STATISTIC(NumColdRegionsFound, "Number of cold regions found.");
77 STATISTIC(NumColdRegionsOutlined, "Number of cold regions outlined.");
78 
79 using namespace llvm;
80 
81 static cl::opt<bool> EnableStaticAnalyis("hot-cold-static-analysis",
82  cl::init(true), cl::Hidden);
83 
84 static cl::opt<int>
85  SplittingThreshold("hotcoldsplit-threshold", cl::init(2), cl::Hidden,
86  cl::desc("Base penalty for splitting cold code (as a "
87  "multiple of TCC_Basic)"));
88 
89 namespace {
90 // Same as blockEndsInUnreachable in CodeGen/BranchFolding.cpp. Do not modify
91 // this function unless you modify the MBB version as well.
92 //
93 /// A no successor, non-return block probably ends in unreachable and is cold.
94 /// Also consider a block that ends in an indirect branch to be a return block,
95 /// since many targets use plain indirect branches to return.
96 bool blockEndsInUnreachable(const BasicBlock &BB) {
97  if (!succ_empty(&BB))
98  return false;
99  if (BB.empty())
100  return true;
101  const Instruction *I = BB.getTerminator();
102  return !(isa<ReturnInst>(I) || isa<IndirectBrInst>(I));
103 }
104 
105 bool unlikelyExecuted(BasicBlock &BB) {
106  // Exception handling blocks are unlikely executed.
107  if (BB.isEHPad() || isa<ResumeInst>(BB.getTerminator()))
108  return true;
109 
110  // The block is cold if it calls/invokes a cold function. However, do not
111  // mark sanitizer traps as cold.
112  for (Instruction &I : BB)
113  if (auto CS = CallSite(&I))
114  if (CS.hasFnAttr(Attribute::Cold) && !CS->getMetadata("nosanitize"))
115  return true;
116 
117  // The block is cold if it has an unreachable terminator, unless it's
118  // preceded by a call to a (possibly warm) noreturn call (e.g. longjmp).
119  if (blockEndsInUnreachable(BB)) {
120  if (auto *CI =
121  dyn_cast_or_null<CallInst>(BB.getTerminator()->getPrevNode()))
122  if (CI->hasFnAttr(Attribute::NoReturn))
123  return false;
124  return true;
125  }
126 
127  return false;
128 }
129 
130 /// Check whether it's safe to outline \p BB.
131 static bool mayExtractBlock(const BasicBlock &BB) {
132  // EH pads are unsafe to outline because doing so breaks EH type tables. It
133  // follows that invoke instructions cannot be extracted, because CodeExtractor
134  // requires unwind destinations to be within the extraction region.
135  //
136  // Resumes that are not reachable from a cleanup landing pad are considered to
137  // be unreachable. It’s not safe to split them out either.
138  auto Term = BB.getTerminator();
139  return !BB.hasAddressTaken() && !BB.isEHPad() && !isa<InvokeInst>(Term) &&
140  !isa<ResumeInst>(Term);
141 }
142 
143 /// Mark \p F cold. Based on this assumption, also optimize it for minimum size.
144 /// If \p UpdateEntryCount is true (set when this is a new split function and
145 /// module has profile data), set entry count to 0 to ensure treated as cold.
146 /// Return true if the function is changed.
147 static bool markFunctionCold(Function &F, bool UpdateEntryCount = false) {
148  assert(!F.hasOptNone() && "Can't mark this cold");
149  bool Changed = false;
152  Changed = true;
153  }
154  if (!F.hasFnAttribute(Attribute::MinSize)) {
155  F.addFnAttr(Attribute::MinSize);
156  Changed = true;
157  }
158  if (UpdateEntryCount) {
159  // Set the entry count to 0 to ensure it is placed in the unlikely text
160  // section when function sections are enabled.
161  F.setEntryCount(0);
162  Changed = true;
163  }
164 
165  return Changed;
166 }
167 
168 class HotColdSplittingLegacyPass : public ModulePass {
169 public:
170  static char ID;
171  HotColdSplittingLegacyPass() : ModulePass(ID) {
173  }
174 
175  void getAnalysisUsage(AnalysisUsage &AU) const override {
180  }
181 
182  bool runOnModule(Module &M) override;
183 };
184 
185 } // end anonymous namespace
186 
187 /// Check whether \p F is inherently cold.
188 bool HotColdSplitting::isFunctionCold(const Function &F) const {
190  return true;
191 
193  return true;
194 
195  if (PSI->isFunctionEntryCold(&F))
196  return true;
197 
198  return false;
199 }
200 
201 // Returns false if the function should not be considered for hot-cold split
202 // optimization.
203 bool HotColdSplitting::shouldOutlineFrom(const Function &F) const {
204  if (F.hasFnAttribute(Attribute::AlwaysInline))
205  return false;
206 
207  if (F.hasFnAttribute(Attribute::NoInline))
208  return false;
209 
210  // A function marked `noreturn` may contain unreachable terminators: these
211  // should not be considered cold, as the function may be a trampoline.
212  if (F.hasFnAttribute(Attribute::NoReturn))
213  return false;
214 
215  if (F.hasFnAttribute(Attribute::SanitizeAddress) ||
216  F.hasFnAttribute(Attribute::SanitizeHWAddress) ||
217  F.hasFnAttribute(Attribute::SanitizeThread) ||
218  F.hasFnAttribute(Attribute::SanitizeMemory))
219  return false;
220 
221  return true;
222 }
223 
224 /// Get the benefit score of outlining \p Region.
226  TargetTransformInfo &TTI) {
227  // Sum up the code size costs of non-terminator instructions. Tight coupling
228  // with \ref getOutliningPenalty is needed to model the costs of terminators.
229  int Benefit = 0;
230  for (BasicBlock *BB : Region)
231  for (Instruction &I : BB->instructionsWithoutDebug())
232  if (&I != BB->getTerminator())
233  Benefit +=
235 
236  return Benefit;
237 }
238 
239 /// Get the penalty score for outlining \p Region.
241  unsigned NumInputs, unsigned NumOutputs) {
242  int Penalty = SplittingThreshold;
243  LLVM_DEBUG(dbgs() << "Applying penalty for splitting: " << Penalty << "\n");
244 
245  // If the splitting threshold is set at or below zero, skip the usual
246  // profitability check.
247  if (SplittingThreshold <= 0)
248  return Penalty;
249 
250  // The typical code size cost for materializing an argument for the outlined
251  // call.
252  LLVM_DEBUG(dbgs() << "Applying penalty for: " << NumInputs << " inputs\n");
253  const int CostForArgMaterialization = TargetTransformInfo::TCC_Basic;
254  Penalty += CostForArgMaterialization * NumInputs;
255 
256  // The typical code size cost for an output alloca, its associated store, and
257  // its associated reload.
258  LLVM_DEBUG(dbgs() << "Applying penalty for: " << NumOutputs << " outputs\n");
259  const int CostForRegionOutput = 3 * TargetTransformInfo::TCC_Basic;
260  Penalty += CostForRegionOutput * NumOutputs;
261 
262  // Find the number of distinct exit blocks for the region. Use a conservative
263  // check to determine whether control returns from the region.
264  bool NoBlocksReturn = true;
265  SmallPtrSet<BasicBlock *, 2> SuccsOutsideRegion;
266  for (BasicBlock *BB : Region) {
267  // If a block has no successors, only assume it does not return if it's
268  // unreachable.
269  if (succ_empty(BB)) {
270  NoBlocksReturn &= isa<UnreachableInst>(BB->getTerminator());
271  continue;
272  }
273 
274  for (BasicBlock *SuccBB : successors(BB)) {
275  if (find(Region, SuccBB) == Region.end()) {
276  NoBlocksReturn = false;
277  SuccsOutsideRegion.insert(SuccBB);
278  }
279  }
280  }
281 
282  // Apply a `noreturn` bonus.
283  if (NoBlocksReturn) {
284  LLVM_DEBUG(dbgs() << "Applying bonus for: " << Region.size()
285  << " non-returning terminators\n");
286  Penalty -= Region.size();
287  }
288 
289  // Apply a penalty for having more than one successor outside of the region.
290  // This penalty accounts for the switch needed in the caller.
291  if (!SuccsOutsideRegion.empty()) {
292  LLVM_DEBUG(dbgs() << "Applying penalty for: " << SuccsOutsideRegion.size()
293  << " non-region successors\n");
294  Penalty += (SuccsOutsideRegion.size() - 1) * TargetTransformInfo::TCC_Basic;
295  }
296 
297  return Penalty;
298 }
299 
300 Function *HotColdSplitting::extractColdRegion(
301  const BlockSequence &Region, const CodeExtractorAnalysisCache &CEAC,
303  OptimizationRemarkEmitter &ORE, AssumptionCache *AC, unsigned Count) {
304  assert(!Region.empty());
305 
306  // TODO: Pass BFI and BPI to update profile information.
307  CodeExtractor CE(Region, &DT, /* AggregateArgs */ false, /* BFI */ nullptr,
308  /* BPI */ nullptr, AC, /* AllowVarArgs */ false,
309  /* AllowAlloca */ false,
310  /* Suffix */ "cold." + std::to_string(Count));
311 
312  // Perform a simple cost/benefit analysis to decide whether or not to permit
313  // splitting.
314  SetVector<Value *> Inputs, Outputs, Sinks;
315  CE.findInputsOutputs(Inputs, Outputs, Sinks);
316  int OutliningBenefit = getOutliningBenefit(Region, TTI);
317  int OutliningPenalty =
318  getOutliningPenalty(Region, Inputs.size(), Outputs.size());
319  LLVM_DEBUG(dbgs() << "Split profitability: benefit = " << OutliningBenefit
320  << ", penalty = " << OutliningPenalty << "\n");
321  if (OutliningBenefit <= OutliningPenalty)
322  return nullptr;
323 
324  Function *OrigF = Region[0]->getParent();
325  if (Function *OutF = CE.extractCodeRegion(CEAC)) {
326  User *U = *OutF->user_begin();
327  CallInst *CI = cast<CallInst>(U);
328  CallSite CS(CI);
329  NumColdRegionsOutlined++;
330  if (TTI.useColdCCForColdCall(*OutF)) {
331  OutF->setCallingConv(CallingConv::Cold);
332  CS.setCallingConv(CallingConv::Cold);
333  }
334  CI->setIsNoInline();
335 
336  if (OrigF->hasSection())
337  OutF->setSection(OrigF->getSection());
338 
339  markFunctionCold(*OutF, BFI != nullptr);
340 
341  LLVM_DEBUG(llvm::dbgs() << "Outlined Region: " << *OutF);
342  ORE.emit([&]() {
343  return OptimizationRemark(DEBUG_TYPE, "HotColdSplit",
344  &*Region[0]->begin())
345  << ore::NV("Original", OrigF) << " split cold code into "
346  << ore::NV("Split", OutF);
347  });
348  return OutF;
349  }
350 
351  ORE.emit([&]() {
352  return OptimizationRemarkMissed(DEBUG_TYPE, "ExtractFailed",
353  &*Region[0]->begin())
354  << "Failed to extract region at block "
355  << ore::NV("Block", Region.front());
356  });
357  return nullptr;
358 }
359 
360 /// A pair of (basic block, score).
361 using BlockTy = std::pair<BasicBlock *, unsigned>;
362 
363 namespace {
364 /// A maximal outlining region. This contains all blocks post-dominated by a
365 /// sink block, the sink block itself, and all blocks dominated by the sink.
366 /// If sink-predecessors and sink-successors cannot be extracted in one region,
367 /// the static constructor returns a list of suitable extraction regions.
368 class OutliningRegion {
369  /// A list of (block, score) pairs. A block's score is non-zero iff it's a
370  /// viable sub-region entry point. Blocks with higher scores are better entry
371  /// points (i.e. they are more distant ancestors of the sink block).
372  SmallVector<BlockTy, 0> Blocks = {};
373 
374  /// The suggested entry point into the region. If the region has multiple
375  /// entry points, all blocks within the region may not be reachable from this
376  /// entry point.
377  BasicBlock *SuggestedEntryPoint = nullptr;
378 
379  /// Whether the entire function is cold.
380  bool EntireFunctionCold = false;
381 
382  /// If \p BB is a viable entry point, return \p Score. Return 0 otherwise.
383  static unsigned getEntryPointScore(BasicBlock &BB, unsigned Score) {
384  return mayExtractBlock(BB) ? Score : 0;
385  }
386 
387  /// These scores should be lower than the score for predecessor blocks,
388  /// because regions starting at predecessor blocks are typically larger.
389  static constexpr unsigned ScoreForSuccBlock = 1;
390  static constexpr unsigned ScoreForSinkBlock = 1;
391 
392  OutliningRegion(const OutliningRegion &) = delete;
393  OutliningRegion &operator=(const OutliningRegion &) = delete;
394 
395 public:
396  OutliningRegion() = default;
397  OutliningRegion(OutliningRegion &&) = default;
398  OutliningRegion &operator=(OutliningRegion &&) = default;
399 
400  static std::vector<OutliningRegion> create(BasicBlock &SinkBB,
401  const DominatorTree &DT,
402  const PostDominatorTree &PDT) {
403  std::vector<OutliningRegion> Regions;
404  SmallPtrSet<BasicBlock *, 4> RegionBlocks;
405 
406  Regions.emplace_back();
407  OutliningRegion *ColdRegion = &Regions.back();
408 
409  auto addBlockToRegion = [&](BasicBlock *BB, unsigned Score) {
410  RegionBlocks.insert(BB);
411  ColdRegion->Blocks.emplace_back(BB, Score);
412  };
413 
414  // The ancestor farthest-away from SinkBB, and also post-dominated by it.
415  unsigned SinkScore = getEntryPointScore(SinkBB, ScoreForSinkBlock);
416  ColdRegion->SuggestedEntryPoint = (SinkScore > 0) ? &SinkBB : nullptr;
417  unsigned BestScore = SinkScore;
418 
419  // Visit SinkBB's ancestors using inverse DFS.
420  auto PredIt = ++idf_begin(&SinkBB);
421  auto PredEnd = idf_end(&SinkBB);
422  while (PredIt != PredEnd) {
423  BasicBlock &PredBB = **PredIt;
424  bool SinkPostDom = PDT.dominates(&SinkBB, &PredBB);
425 
426  // If the predecessor is cold and has no predecessors, the entire
427  // function must be cold.
428  if (SinkPostDom && pred_empty(&PredBB)) {
429  ColdRegion->EntireFunctionCold = true;
430  return Regions;
431  }
432 
433  // If SinkBB does not post-dominate a predecessor, do not mark the
434  // predecessor (or any of its predecessors) cold.
435  if (!SinkPostDom || !mayExtractBlock(PredBB)) {
436  PredIt.skipChildren();
437  continue;
438  }
439 
440  // Keep track of the post-dominated ancestor farthest away from the sink.
441  // The path length is always >= 2, ensuring that predecessor blocks are
442  // considered as entry points before the sink block.
443  unsigned PredScore = getEntryPointScore(PredBB, PredIt.getPathLength());
444  if (PredScore > BestScore) {
445  ColdRegion->SuggestedEntryPoint = &PredBB;
446  BestScore = PredScore;
447  }
448 
449  addBlockToRegion(&PredBB, PredScore);
450  ++PredIt;
451  }
452 
453  // If the sink can be added to the cold region, do so. It's considered as
454  // an entry point before any sink-successor blocks.
455  //
456  // Otherwise, split cold sink-successor blocks using a separate region.
457  // This satisfies the requirement that all extraction blocks other than the
458  // first have predecessors within the extraction region.
459  if (mayExtractBlock(SinkBB)) {
460  addBlockToRegion(&SinkBB, SinkScore);
461  } else {
462  Regions.emplace_back();
463  ColdRegion = &Regions.back();
464  BestScore = 0;
465  }
466 
467  // Find all successors of SinkBB dominated by SinkBB using DFS.
468  auto SuccIt = ++df_begin(&SinkBB);
469  auto SuccEnd = df_end(&SinkBB);
470  while (SuccIt != SuccEnd) {
471  BasicBlock &SuccBB = **SuccIt;
472  bool SinkDom = DT.dominates(&SinkBB, &SuccBB);
473 
474  // Don't allow the backwards & forwards DFSes to mark the same block.
475  bool DuplicateBlock = RegionBlocks.count(&SuccBB);
476 
477  // If SinkBB does not dominate a successor, do not mark the successor (or
478  // any of its successors) cold.
479  if (DuplicateBlock || !SinkDom || !mayExtractBlock(SuccBB)) {
480  SuccIt.skipChildren();
481  continue;
482  }
483 
484  unsigned SuccScore = getEntryPointScore(SuccBB, ScoreForSuccBlock);
485  if (SuccScore > BestScore) {
486  ColdRegion->SuggestedEntryPoint = &SuccBB;
487  BestScore = SuccScore;
488  }
489 
490  addBlockToRegion(&SuccBB, SuccScore);
491  ++SuccIt;
492  }
493 
494  return Regions;
495  }
496 
497  /// Whether this region has nothing to extract.
498  bool empty() const { return !SuggestedEntryPoint; }
499 
500  /// The blocks in this region.
501  ArrayRef<std::pair<BasicBlock *, unsigned>> blocks() const { return Blocks; }
502 
503  /// Whether the entire function containing this region is cold.
504  bool isEntireFunctionCold() const { return EntireFunctionCold; }
505 
506  /// Remove a sub-region from this region and return it as a block sequence.
507  BlockSequence takeSingleEntrySubRegion(DominatorTree &DT) {
508  assert(!empty() && !isEntireFunctionCold() && "Nothing to extract");
509 
510  // Remove blocks dominated by the suggested entry point from this region.
511  // During the removal, identify the next best entry point into the region.
512  // Ensure that the first extracted block is the suggested entry point.
513  BlockSequence SubRegion = {SuggestedEntryPoint};
514  BasicBlock *NextEntryPoint = nullptr;
515  unsigned NextScore = 0;
516  auto RegionEndIt = Blocks.end();
517  auto RegionStartIt = remove_if(Blocks, [&](const BlockTy &Block) {
518  BasicBlock *BB = Block.first;
519  unsigned Score = Block.second;
520  bool InSubRegion =
521  BB == SuggestedEntryPoint || DT.dominates(SuggestedEntryPoint, BB);
522  if (!InSubRegion && Score > NextScore) {
523  NextEntryPoint = BB;
524  NextScore = Score;
525  }
526  if (InSubRegion && BB != SuggestedEntryPoint)
527  SubRegion.push_back(BB);
528  return InSubRegion;
529  });
530  Blocks.erase(RegionStartIt, RegionEndIt);
531 
532  // Update the suggested entry point.
533  SuggestedEntryPoint = NextEntryPoint;
534 
535  return SubRegion;
536  }
537 };
538 } // namespace
539 
540 bool HotColdSplitting::outlineColdRegions(Function &F, bool HasProfileSummary) {
541  bool Changed = false;
542 
543  // The set of cold blocks.
544  SmallPtrSet<BasicBlock *, 4> ColdBlocks;
545 
546  // The worklist of non-intersecting regions left to outline.
547  SmallVector<OutliningRegion, 2> OutliningWorklist;
548 
549  // Set up an RPO traversal. Experimentally, this performs better (outlines
550  // more) than a PO traversal, because we prevent region overlap by keeping
551  // the first region to contain a block.
553 
554  // Calculate domtrees lazily. This reduces compile-time significantly.
555  std::unique_ptr<DominatorTree> DT;
556  std::unique_ptr<PostDominatorTree> PDT;
557 
558  // Calculate BFI lazily (it's only used to query ProfileSummaryInfo). This
559  // reduces compile-time significantly. TODO: When we *do* use BFI, we should
560  // be able to salvage its domtrees instead of recomputing them.
561  BlockFrequencyInfo *BFI = nullptr;
562  if (HasProfileSummary)
563  BFI = GetBFI(F);
564 
565  TargetTransformInfo &TTI = GetTTI(F);
566  OptimizationRemarkEmitter &ORE = (*GetORE)(F);
567  AssumptionCache *AC = LookupAC(F);
568 
569  // Find all cold regions.
570  for (BasicBlock *BB : RPOT) {
571  // This block is already part of some outlining region.
572  if (ColdBlocks.count(BB))
573  continue;
574 
575  bool Cold = (BFI && PSI->isColdBlock(BB, BFI)) ||
576  (EnableStaticAnalyis && unlikelyExecuted(*BB));
577  if (!Cold)
578  continue;
579 
580  LLVM_DEBUG({
581  dbgs() << "Found a cold block:\n";
582  BB->dump();
583  });
584 
585  if (!DT)
586  DT = std::make_unique<DominatorTree>(F);
587  if (!PDT)
588  PDT = std::make_unique<PostDominatorTree>(F);
589 
590  auto Regions = OutliningRegion::create(*BB, *DT, *PDT);
591  for (OutliningRegion &Region : Regions) {
592  if (Region.empty())
593  continue;
594 
595  if (Region.isEntireFunctionCold()) {
596  LLVM_DEBUG(dbgs() << "Entire function is cold\n");
597  return markFunctionCold(F);
598  }
599 
600  // If this outlining region intersects with another, drop the new region.
601  //
602  // TODO: It's theoretically possible to outline more by only keeping the
603  // largest region which contains a block, but the extra bookkeeping to do
604  // this is tricky/expensive.
605  bool RegionsOverlap = any_of(Region.blocks(), [&](const BlockTy &Block) {
606  return !ColdBlocks.insert(Block.first).second;
607  });
608  if (RegionsOverlap)
609  continue;
610 
611  OutliningWorklist.emplace_back(std::move(Region));
612  ++NumColdRegionsFound;
613  }
614  }
615 
616  if (OutliningWorklist.empty())
617  return Changed;
618 
619  // Outline single-entry cold regions, splitting up larger regions as needed.
620  unsigned OutlinedFunctionID = 1;
621  // Cache and recycle the CodeExtractor analysis to avoid O(n^2) compile-time.
623  do {
624  OutliningRegion Region = OutliningWorklist.pop_back_val();
625  assert(!Region.empty() && "Empty outlining region in worklist");
626  do {
627  BlockSequence SubRegion = Region.takeSingleEntrySubRegion(*DT);
628  LLVM_DEBUG({
629  dbgs() << "Hot/cold splitting attempting to outline these blocks:\n";
630  for (BasicBlock *BB : SubRegion)
631  BB->dump();
632  });
633 
634  Function *Outlined = extractColdRegion(SubRegion, CEAC, *DT, BFI, TTI,
635  ORE, AC, OutlinedFunctionID);
636  if (Outlined) {
637  ++OutlinedFunctionID;
638  Changed = true;
639  }
640  } while (!Region.empty());
641  } while (!OutliningWorklist.empty());
642 
643  return Changed;
644 }
645 
647  bool Changed = false;
648  bool HasProfileSummary = (M.getProfileSummary(/* IsCS */ false) != nullptr);
649  for (auto It = M.begin(), End = M.end(); It != End; ++It) {
650  Function &F = *It;
651 
652  // Do not touch declarations.
653  if (F.isDeclaration())
654  continue;
655 
656  // Do not modify `optnone` functions.
657  if (F.hasOptNone())
658  continue;
659 
660  // Detect inherently cold functions and mark them as such.
661  if (isFunctionCold(F)) {
662  Changed |= markFunctionCold(F);
663  continue;
664  }
665 
666  if (!shouldOutlineFrom(F)) {
667  LLVM_DEBUG(llvm::dbgs() << "Skipping " << F.getName() << "\n");
668  continue;
669  }
670 
671  LLVM_DEBUG(llvm::dbgs() << "Outlining in " << F.getName() << "\n");
672  Changed |= outlineColdRegions(F, HasProfileSummary);
673  }
674  return Changed;
675 }
676 
677 bool HotColdSplittingLegacyPass::runOnModule(Module &M) {
678  if (skipModule(M))
679  return false;
680  ProfileSummaryInfo *PSI =
681  &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
682  auto GTTI = [this](Function &F) -> TargetTransformInfo & {
683  return this->getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
684  };
685  auto GBFI = [this](Function &F) {
686  return &this->getAnalysis<BlockFrequencyInfoWrapperPass>(F).getBFI();
687  };
688  std::unique_ptr<OptimizationRemarkEmitter> ORE;
689  std::function<OptimizationRemarkEmitter &(Function &)> GetORE =
690  [&ORE](Function &F) -> OptimizationRemarkEmitter & {
691  ORE.reset(new OptimizationRemarkEmitter(&F));
692  return *ORE.get();
693  };
694  auto LookupAC = [this](Function &F) -> AssumptionCache * {
695  if (auto *ACT = getAnalysisIfAvailable<AssumptionCacheTracker>())
696  return ACT->lookupAssumptionCache(F);
697  return nullptr;
698  };
699 
700  return HotColdSplitting(PSI, GBFI, GTTI, &GetORE, LookupAC).run(M);
701 }
702 
705  auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
706 
707  auto LookupAC = [&FAM](Function &F) -> AssumptionCache * {
708  return FAM.getCachedResult<AssumptionAnalysis>(F);
709  };
710 
711  auto GBFI = [&FAM](Function &F) {
712  return &FAM.getResult<BlockFrequencyAnalysis>(F);
713  };
714 
715  std::function<TargetTransformInfo &(Function &)> GTTI =
716  [&FAM](Function &F) -> TargetTransformInfo & {
717  return FAM.getResult<TargetIRAnalysis>(F);
718  };
719 
720  std::unique_ptr<OptimizationRemarkEmitter> ORE;
721  std::function<OptimizationRemarkEmitter &(Function &)> GetORE =
722  [&ORE](Function &F) -> OptimizationRemarkEmitter & {
723  ORE.reset(new OptimizationRemarkEmitter(&F));
724  return *ORE.get();
725  };
726 
728 
729  if (HotColdSplitting(PSI, GBFI, GTTI, &GetORE, LookupAC).run(M))
730  return PreservedAnalyses::none();
731  return PreservedAnalyses::all();
732 }
733 
735 INITIALIZE_PASS_BEGIN(HotColdSplittingLegacyPass, "hotcoldsplit",
736  "Hot Cold Splitting", false, false)
739 INITIALIZE_PASS_END(HotColdSplittingLegacyPass, "hotcoldsplit",
740  "Hot Cold Splitting", false, false)
741 
743  return new HotColdSplittingLegacyPass();
744 }
StringRef getSection() const
Get the custom section of this global if it has one.
Definition: GlobalObject.h:109
INITIALIZE_PASS_BEGIN(HotColdSplittingLegacyPass, "hotcoldsplit", "Hot Cold Splitting", false, false) INITIALIZE_PASS_END(HotColdSplittingLegacyPass
Utility class for extracting code into a new function.
Definition: CodeExtractor.h:85
reference emplace_back(ArgTypes &&... Args)
Definition: SmallVector.h:641
Diagnostic information for missed-optimization remarks.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
const_iterator begin(StringRef path, Style style=Style::native)
Get begin iterator over path.
Definition: Path.cpp:224
DiagnosticInfoOptimizationBase::Argument NV
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Definition: PassManager.h:777
This class represents lattice values for constants.
Definition: AllocatorList.h:23
bool hasOptNone() const
Do not optimize this function (-O0).
Definition: Function.h:627
size_type size() const
Determine the number of elements in the SetVector.
Definition: SetVector.h:77
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:66
PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
void push_back(const T &Elt)
Definition: SmallVector.h:211
Hot Cold Splitting
bool useColdCCForColdCall(Function &F) const
Return true if the input function which is cold at all call sites, should use coldcc calling conventi...
Analysis providing profile information.
This class represents a function call, abstracting a target machine&#39;s calling convention.
static cl::opt< bool > EnableStaticAnalyis("hot-cold-static-analysis", cl::init(true), cl::Hidden)
This file contains the declarations for metadata subclasses.
An immutable pass that tracks lazily created AssumptionCache objects.
Metadata * getProfileSummary(bool IsCS)
Returns profile summary metadata.
Definition: Module.cpp:557
A cache of @llvm.assume calls within a function.
Analysis pass providing the TargetTransformInfo.
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
Definition: Function.h:323
F(f)
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
Definition: BasicBlock.cpp:144
This defines the Use class.
int getInstructionCost(const Instruction *I, enum TargetCostKind kind) const
Query the cost of a specified instruction.
void dump() const
Support for debugging, callable in GDB: V->dump()
Definition: AsmWriter.cpp:4466
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition: PassSupport.h:50
void setEntryCount(ProfileCount Count, const DenseSet< GlobalValue::GUID > *Imports=nullptr)
Set the entry count for this function.
Definition: Function.cpp:1548
An analysis pass based on legacy pass manager to deliver ProfileSummaryInfo.
Legacy analysis pass which computes BlockFrequencyInfo.
bool empty() const
Definition: BasicBlock.h:284
STATISTIC(NumColdRegionsFound, "Number of cold regions found.")
static bool blockEndsInUnreachable(const MachineBasicBlock *MBB)
A no successor, non-return block probably ends in unreachable and is cold.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
Definition: APInt.h:32
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
Definition: Dominators.h:144
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
Definition: PassManager.h:157
idf_iterator< T > idf_begin(const T &G)
idf_iterator< T > idf_end(const T &G)
BlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate IR basic block frequen...
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:435
Wrapper pass for TargetTransformInfo.
A set of analyses that are preserved following a run of a transformation pass.
Definition: PassManager.h:154
LLVM Basic Block Representation.
Definition: BasicBlock.h:57
bool dominates(const Instruction *I1, const Instruction *I2) const
Return true if I1 dominates I2.
An analysis pass based on the new PM to deliver ProfileSummaryInfo.
df_iterator< T > df_end(const T &G)
iterator_range< filter_iterator< BasicBlock::const_iterator, std::function< bool(const Instruction &)> > > instructionsWithoutDebug() const
Return a const iterator range over the instructions in the block, skipping any debug instructions...
Definition: BasicBlock.cpp:94
LLVM_NODISCARD bool empty() const
Definition: SmallPtrSet.h:91
void setIsNoInline()
Definition: InstrTypes.h:1657
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Definition: SmallPtrSet.h:370
Diagnostic information for applied optimization remarks.
Represent the analysis usage information of a pass.
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly...
Definition: STLExtras.h:1189
A cache for the CodeExtractor analysis.
Definition: CodeExtractor.h:46
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
Definition: SmallPtrSet.h:381
bool pred_empty(const BasicBlock *BB)
Definition: CFG.h:116
auto remove_if(R &&Range, UnaryPredicate P) -> decltype(adl_begin(Range))
Provide wrappers to std::remove_if which take ranges instead of having to pass begin/end explicitly...
Definition: STLExtras.h:1222
bool succ_empty(const Instruction *I)
Definition: CFG.h:253
iterator erase(const_iterator CI)
Definition: SmallVector.h:434
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: PassManager.h:160
auto find(R &&Range, const T &Val) -> decltype(adl_begin(Range))
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly...
Definition: STLExtras.h:1203
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
constexpr bool empty(const T &RangeOrContainer)
Test whether RangeOrContainer is empty. Similar to C++17 std::empty.
Definition: STLExtras.h:192
size_type size() const
Definition: SmallPtrSet.h:92
A function analysis which provides an AssumptionCache.
bool hasAddressTaken() const
Returns true if there are any uses of this basic block other than direct branches, switches, etc.
Definition: BasicBlock.h:396
Analysis pass which computes BlockFrequencyInfo.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
Definition: SmallPtrSet.h:443
std::pair< BasicBlock *, unsigned > BlockTy
A pair of (basic block, score).
void emit(DiagnosticInfoOptimizationBase &OptDiag)
Output the remark via the diagnostic handler and to the optimization record file. ...
void initializeHotColdSplittingLegacyPassPass(PassRegistry &)
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
static cl::opt< int > SplittingThreshold("hotcoldsplit-threshold", cl::init(2), cl::Hidden, cl::desc("Base penalty for splitting cold code (as a " "multiple of TCC_Basic)"))
CallingConv::ID getCallingConv() const
getCallingConv()/setCallingConv(CC) - These method get and set the calling convention of this functio...
Definition: Function.h:212
bool hasSection() const
Check if this global has a custom object file section.
Definition: GlobalObject.h:101
This is a &#39;vector&#39; (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:837
bool dominates(const Instruction *Def, const Use &U) const
Return true if Def dominates a use in User.
Definition: Dominators.cpp:249
Module.h This file contains the declarations for the Module class.
LLVM_NODISCARD T pop_back_val()
Definition: SmallVector.h:374
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:132
static int getOutliningBenefit(ArrayRef< BasicBlock *> Region, TargetTransformInfo &TTI)
Get the benefit score of outlining Region.
df_iterator< T > df_begin(const T &G)
PostDominatorTree Class - Concrete subclass of DominatorTree that is used to compute the post-dominat...
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
iterator end()
Definition: Module.h:601
ModulePass * createHotColdSplittingPass()
createHotColdSplittingPass - This pass outlines cold blocks into a separate function(s).
LLVM_NODISCARD bool empty() const
Definition: SmallVector.h:55
static int getOutliningPenalty(ArrayRef< BasicBlock *> Region, unsigned NumInputs, unsigned NumOutputs)
Get the penalty score for outlining Region.
StringRef getName() const
Return a constant reference to the value&#39;s name.
Definition: Value.cpp:215
#define I(x, y, z)
Definition: MD5.cpp:58
ModulePass class - This class is used to implement unstructured interprocedural optimizations and ana...
Definition: Pass.h:222
iterator begin()
Definition: Module.h:599
const std::string to_string(const T &Value)
Definition: ScopedPrinter.h:61
bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
Definition: Globals.cpp:231
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
user_iterator user_begin()
Definition: Value.h:396
The cost of a typical &#39;add&#39; instruction.
bool isEHPad() const
Return true if this basic block is an exception handling block.
Definition: BasicBlock.h:411
AnalysisUsage & addUsedIfAvailable()
Add the specified Pass class to the set of analyses used by this pass.
#define DEBUG_TYPE
succ_range successors(Instruction *I)
Definition: CFG.h:259
hotcoldsplit
void addFnAttr(Attribute::AttrKind Kind)
Add function attributes to this function.
Definition: Function.h:229
A container for analyses that lazily runs them and caches their results.
This pass exposes codegen information to IR-level passes.
This header defines various interfaces for pass management in LLVM.
#define LLVM_DEBUG(X)
Definition: Debug.h:122
The optimization diagnostic interface.
An analysis over an "outer" IR unit that provides access to an analysis manager over an "inner" IR un...
Definition: PassManager.h:1045