60#define DEBUG_TYPE "hotcoldsplit"
62STATISTIC(NumColdRegionsFound,
"Number of cold regions found.");
63STATISTIC(NumColdRegionsOutlined,
"Number of cold regions outlined.");
95 auto SumWt = TrueWt + FalseWt;
102 if (TrueProb <= ColdProbThresh)
105 if (FalseProb <= ColdProbThresh)
118 if (CB->hasFnAttr(Attribute::Cold) &&
119 !CB->getMetadata(LLVMContext::MD_nosanitize))
127 if (CI->hasFnAttr(Attribute::NoReturn))
136static bool mayExtractBlock(
const BasicBlock &BB) {
156 BB, [](
const Instruction &
I) {
return I.getType()->isTokenTy(); })) {
167static bool markFunctionCold(
Function &
F,
bool UpdateEntryCount =
false) {
168 assert(!
F.hasOptNone() &&
"Can't mark this cold");
170 if (!
F.hasFnAttribute(Attribute::Cold)) {
171 F.addFnAttr(Attribute::Cold);
174 if (!
F.hasMinSize()) {
175 F.addFnAttr(Attribute::MinSize);
178 if (UpdateEntryCount) {
191bool HotColdSplitting::isFunctionCold(
const Function &
F)
const {
192 if (
F.hasFnAttribute(Attribute::Cold))
198 if (PSI->isFunctionEntryCold(&
F))
204bool HotColdSplitting::isBasicBlockCold(
209 if (PSI->isColdBlock(BB, BFI))
213 analyzeProfMetadata(BB, ColdProbThresh, AnnotatedColdBlocks);
217 if (AnnotatedColdBlocks.
count(BB))
221 if (Opts.hot_cold_static_analysis && unlikelyExecuted(*BB))
229bool HotColdSplitting::shouldOutlineFrom(
const Function &
F)
const {
230 if (
F.hasFnAttribute(Attribute::AlwaysInline))
238 if (
F.hasFnAttribute(Attribute::NoReturn))
241 if (
F.hasFnAttribute(Attribute::SanitizeAddress) ||
242 F.hasFnAttribute(Attribute::SanitizeHWAddress) ||
243 F.hasFnAttribute(Attribute::SanitizeThread) ||
244 F.hasFnAttribute(Attribute::SanitizeConcurrency) ||
245 F.hasFnAttribute(Attribute::SanitizeMemory))
249 if (
F.hasPersonalityFn())
264 if (&
I != BB->getTerminator())
274 unsigned NumInputs,
unsigned NumOutputs) {
275 int Penalty = Opts.hotcoldsplit_threshold;
276 LLVM_DEBUG(
dbgs() <<
"Applying penalty for splitting: " << Penalty <<
"\n");
280 if (Opts.hotcoldsplit_threshold <= 0)
285 bool NoBlocksReturn =
true;
297 NoBlocksReturn =
false;
298 SuccsOutsideRegion.
insert(SuccBB);
308 unsigned NumSplitExitPhis = 0;
309 for (
BasicBlock *ExitBB : SuccsOutsideRegion) {
310 for (
PHINode &PN : ExitBB->phis()) {
312 int NumIncomingVals = 0;
313 for (
unsigned i = 0; i < PN.getNumIncomingValues(); ++i)
316 if (NumIncomingVals > 1) {
326 int NumOutputsAndSplitPhis = NumOutputs + NumSplitExitPhis;
327 int NumParams = NumInputs + NumOutputsAndSplitPhis;
328 if (NumParams > Opts.hotcoldsplit_max_params) {
329 LLVM_DEBUG(
dbgs() << NumInputs <<
" inputs and " << NumOutputsAndSplitPhis
330 <<
" outputs exceeds parameter limit ("
331 << Opts.hotcoldsplit_max_params <<
")\n");
332 return std::numeric_limits<int>::max();
335 LLVM_DEBUG(
dbgs() <<
"Applying penalty for: " << NumParams <<
" params\n");
336 Penalty += CostForArgMaterialization * NumParams;
340 LLVM_DEBUG(
dbgs() <<
"Applying penalty for: " << NumOutputsAndSplitPhis
341 <<
" outputs/split phis\n");
343 Penalty += CostForRegionOutput * NumOutputsAndSplitPhis;
346 if (NoBlocksReturn) {
348 <<
" non-returning terminators\n");
354 if (SuccsOutsideRegion.
size() > 1) {
356 <<
" non-region successors\n");
364bool HotColdSplitting::isSplittingBeneficial(
CodeExtractor &CE,
371 SetVector<Value *> Inputs, Outputs, Sinks;
372 CE.findInputsOutputs(Inputs, Outputs, Sinks);
374 int OutliningPenalty =
376 LLVM_DEBUG(
dbgs() <<
"Split profitability: benefit = " << OutliningBenefit
377 <<
", penalty = " << OutliningPenalty <<
"\n");
378 if (!OutliningBenefit.
isValid() || OutliningBenefit <= OutliningPenalty)
386Function *HotColdSplitting::extractColdRegion(
391 if (
Function *OutF =
CE.extractCodeRegion(CEAC)) {
392 User *
U = *OutF->user_begin();
394 NumColdRegionsOutlined++;
401 if (Opts.enable_cold_section)
402 OutF->setSection(Opts.hotcoldsplit_cold_section_name);
408 markFunctionCold(*OutF,
true);
412 return OptimizationRemark(
DEBUG_TYPE,
"HotColdSplit",
413 &*EntryPoint.
begin())
414 <<
ore::NV(
"Original", OrigF) <<
" split cold code into "
421 return OptimizationRemarkMissed(
DEBUG_TYPE,
"ExtractFailed",
422 &*EntryPoint.
begin())
423 <<
"Failed to extract region at block "
424 <<
ore::NV(
"Block", &EntryPoint);
430using BlockTy = std::pair<BasicBlock *, unsigned>;
437class OutliningRegion {
449 bool EntireFunctionCold =
false;
452 static unsigned getEntryPointScore(
BasicBlock &BB,
unsigned Score) {
453 return mayExtractBlock(BB) ? Score : 0;
458 static constexpr unsigned ScoreForSuccBlock = 1;
459 static constexpr unsigned ScoreForSinkBlock = 1;
461 OutliningRegion(
const OutliningRegion &) =
delete;
462 OutliningRegion &operator=(
const OutliningRegion &) =
delete;
465 OutliningRegion() =
default;
466 OutliningRegion(OutliningRegion &&) =
default;
467 OutliningRegion &operator=(OutliningRegion &&) =
default;
469 static std::vector<OutliningRegion> create(
BasicBlock &SinkBB,
472 std::vector<OutliningRegion> Regions;
475 Regions.emplace_back();
476 OutliningRegion *ColdRegion = &Regions.back();
478 auto addBlockToRegion = [&](
BasicBlock *BB,
unsigned Score) {
480 ColdRegion->Blocks.emplace_back(BB, Score);
484 unsigned SinkScore = getEntryPointScore(SinkBB, ScoreForSinkBlock);
485 ColdRegion->SuggestedEntryPoint = (SinkScore > 0) ? &SinkBB :
nullptr;
486 unsigned BestScore = SinkScore;
490 auto PredEnd =
idf_end(&SinkBB);
491 while (PredIt != PredEnd) {
493 bool SinkPostDom = PDT.
dominates(&SinkBB, &PredBB);
498 ColdRegion->EntireFunctionCold =
true;
504 if (!SinkPostDom || !mayExtractBlock(PredBB)) {
505 PredIt.skipChildren();
512 unsigned PredScore = getEntryPointScore(PredBB, PredIt.getPathLength());
513 if (PredScore > BestScore) {
514 ColdRegion->SuggestedEntryPoint = &PredBB;
515 BestScore = PredScore;
518 addBlockToRegion(&PredBB, PredScore);
528 if (mayExtractBlock(SinkBB)) {
529 addBlockToRegion(&SinkBB, SinkScore);
531 ColdRegion->EntireFunctionCold =
true;
535 Regions.emplace_back();
536 ColdRegion = &Regions.back();
542 auto SuccEnd =
df_end(&SinkBB);
543 while (SuccIt != SuccEnd) {
545 bool SinkDom = DT.
dominates(&SinkBB, &SuccBB);
548 bool DuplicateBlock = RegionBlocks.
count(&SuccBB);
552 if (DuplicateBlock || !SinkDom || !mayExtractBlock(SuccBB)) {
553 SuccIt.skipChildren();
557 unsigned SuccScore = getEntryPointScore(SuccBB, ScoreForSuccBlock);
558 if (SuccScore > BestScore) {
559 ColdRegion->SuggestedEntryPoint = &SuccBB;
560 BestScore = SuccScore;
563 addBlockToRegion(&SuccBB, SuccScore);
571 bool empty()
const {
return !SuggestedEntryPoint; }
577 bool isEntireFunctionCold()
const {
return EntireFunctionCold; }
581 assert(!empty() && !isEntireFunctionCold() &&
"Nothing to extract");
588 unsigned NextScore = 0;
589 auto RegionEndIt = Blocks.
end();
592 unsigned Score =
Block.second;
594 BB == SuggestedEntryPoint || DT.
dominates(SuggestedEntryPoint, BB);
595 if (!InSubRegion && Score > NextScore) {
599 if (InSubRegion && BB != SuggestedEntryPoint)
603 Blocks.
erase(RegionStartIt, RegionEndIt);
606 SuggestedEntryPoint = NextEntryPoint;
613bool HotColdSplitting::outlineColdRegions(
Function &
F,
bool HasProfileSummary) {
615 SmallPtrSet<BasicBlock *, 4> ColdBlocks;
618 SmallPtrSet<BasicBlock *, 4> CannotBeOutlinedColdBlocks;
621 SmallPtrSet<BasicBlock *, 4> AnnotatedColdBlocks;
630 ReversePostOrderTraversal<Function *> RPOT(&
F);
633 std::unique_ptr<DominatorTree> DT;
634 std::unique_ptr<PostDominatorTree> PDT;
639 BlockFrequencyInfo *BFI =
nullptr;
640 if (HasProfileSummary)
643 TargetTransformInfo &
TTI = GetTTI(
F);
644 OptimizationRemarkEmitter &ORE = (*GetORE)(
F);
645 AssumptionCache *AC = LookupAC(
F);
648 if (Opts.hotcoldsplit_cold_probability_denom)
650 BranchProbability(1, *Opts.hotcoldsplit_cold_probability_denom);
652 unsigned OutlinedFunctionID = 1;
654 for (BasicBlock *BB : RPOT) {
656 if (ColdBlocks.
count(BB))
660 if (CannotBeOutlinedColdBlocks.
count(BB))
663 if (!isBasicBlockCold(BB, ColdProbThresh, AnnotatedColdBlocks, BFI))
667 dbgs() <<
"Found a cold block:\n";
672 DT = std::make_unique<DominatorTree>(
F);
674 PDT = std::make_unique<PostDominatorTree>(
F);
676 auto Regions = OutliningRegion::create(*BB, *DT, *PDT);
677 for (OutliningRegion &Region : Regions) {
681 if (
Region.isEntireFunctionCold()) {
689 dbgs() <<
"Hot/cold splitting attempting to outline these blocks:\n";
690 for (BasicBlock *BB : SubRegion)
696 SubRegion, &*DT,
false,
nullptr,
700 "cold." + std::to_string(OutlinedFunctionID),
704 if (
CE.isEligible() && isSplittingBeneficial(CE, SubRegion,
TTI) &&
717 for (
auto *
Block : SubRegion)
718 dbgs() <<
" contains cold block:" <<
Block->getName() <<
"\n";
722 std::make_pair(SubRegion[0], std::move(CE)));
723 ++OutlinedFunctionID;
726 for (
auto *
Block : SubRegion)
727 if ((DT->dominates(BB,
Block) && PDT->dominates(
Block, BB)) ||
728 (PDT->dominates(BB,
Block) && DT->dominates(
Block, BB)))
732 }
while (!
Region.empty());
734 ++NumColdRegionsFound;
738 if (OutliningWorklist.
empty())
743 CodeExtractorAnalysisCache CEAC(
F);
744 for (
auto &BCE : OutliningWorklist) {
746 extractColdRegion(*BCE.first, BCE.second, CEAC, BFI,
TTI, ORE);
747 assert(Outlined &&
"Should be outlined");
756 bool HasProfileSummary = (M.getProfileSummary(
false) !=
nullptr);
759 if (
F.isDeclaration())
766 if (isFunctionCold(
F))
769 if (!shouldOutlineFrom(
F)) {
775 Changed |= outlineColdRegions(
F, HasProfileSummary);
797 std::unique_ptr<OptimizationRemarkEmitter> ORE;
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
bbsections Prepares for basic block by splitting functions into clusters of basic blocks
static bool blockEndsInUnreachable(const MachineBasicBlock *MBB)
A no successor, non-return block probably ends in unreachable and is cold.
std::pair< BasicBlock *, unsigned > BlockTy
A pair of (basic block, score).
static InstructionCost getOutliningBenefit(ArrayRef< BasicBlock * > Region, TargetTransformInfo &TTI)
Get the benefit score of outlining Region.
static int getOutliningPenalty(const IPOOptions &Opts, ArrayRef< BasicBlock * > Region, unsigned NumInputs, unsigned NumOutputs)
Get the penalty score for outlining Region.
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
Module.h This file contains the declarations for the Module class.
This header defines various interfaces for pass management in LLVM.
FunctionAnalysisManager FAM
This file builds on the ADT/GraphTraits.h file to build a generic graph post order iterator.
This file contains the declarations for profiling metadata utility functions.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
A function analysis which provides an AssumptionCache.
A cache of @llvm.assume calls within a function.
LLVM Basic Block Representation.
iterator begin()
Instruction iterator methods.
const Function * getParent() const
Return the enclosing method, or null if none.
bool hasAddressTaken() const
Returns true if there are any uses of this basic block other than direct branches,...
bool isEHPad() const
Return true if this basic block is an exception handling block.
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Analysis pass which computes BlockFrequencyInfo.
BlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate IR basic block frequen...
static LLVM_ABI BranchProbability getBranchProbability(uint64_t Numerator, uint64_t Denominator)
BranchProbability getCompl() const
void setCallingConv(CallingConv::ID CC)
Conditional Branch instruction.
BasicBlock * getSuccessor(unsigned i) const
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
LLVM_ABI bool dominates(const BasicBlock *BB, const Use &U) const
Return true if the (end of the) basic block BB dominates the use U.
StringRef getSection() const
Get the custom section of this global if it has one.
bool hasSection() const
Check if this global has a custom object file section.
LLVM_ABI PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
LLVM_ABI bool run(Module &M)
A Module instance is used to store all the information related to an LLVM module.
PostDominatorTree Class - Concrete subclass of DominatorTree that is used to compute the post-dominat...
LLVM_ABI bool dominates(const Instruction *I1, const Instruction *I2) const
Return true if I1 dominates I2.
A set of analyses that are preserved following a run of a transformation pass.
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
An analysis pass based on the new PM to deliver ProfileSummaryInfo.
Analysis providing profile information.
size_type size() const
Determine the number of elements in the SetVector.
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
void insert_range(Range &&R)
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool contains(ConstPtrType Ptr) const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
reference emplace_back(ArgTypes &&... Args)
iterator erase(const_iterator CI)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Analysis pass providing the TargetTransformInfo.
LLVM_ABI void dump() const
Support for debugging, callable in GDB: V->dump()
@ Cold
Attempts to make code in the caller as efficient as possible under the assumption that the call is no...
@ CE
Windows NT (Windows on ARM)
@ User
could "use" a pointer
DiagnosticInfoOptimizationBase::Argument NV
This is an optimization pass for GlobalISel generic memory operations.
bool succ_empty(const Instruction *I)
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
auto successors(const MachineBasicBlock *BB)
df_iterator< T > df_begin(const T &G)
InnerAnalysisManagerProxy< FunctionAnalysisManager, Module > FunctionAnalysisManagerModuleProxy
Provide the FunctionAnalysisManager to Module proxy.
SmallVector< BasicBlock *, 0 > BlockSequence
A sequence of basic blocks.
bool isScopedEHPersonality(EHPersonality Pers)
Returns true if this personality uses scope-style EH IR instructions: catchswitch,...
auto dyn_cast_or_null(const Y &Val)
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
const IPOOptions & getIPOOptions(const LLVMContext &C)
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly.
LLVM_ABI EHPersonality classifyEHPersonality(const Value *Pers)
See if the given exception handling personality function is one that we understand.
idf_iterator< T > idf_end(const T &G)
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
auto remove_if(R &&Range, UnaryPredicate P)
Provide wrappers to std::remove_if which take ranges instead of having to pass begin/end explicitly.
idf_iterator< T > idf_begin(const T &G)
LLVM_ABI bool extractBranchWeights(const MDNode *ProfileData, SmallVectorImpl< uint32_t > &Weights)
Extract branch weights from MD_prof metadata.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
bool pred_empty(const BasicBlock *BB)
df_iterator< T > df_end(const T &G)
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.