#include "llvm/Transforms/IPO/HotColdSplitting.h"
#include "llvm/ADT/PostOrderIterator.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/Analysis/AssumptionCache.h"
#include "llvm/Analysis/BlockFrequencyInfo.h"
#include "llvm/Analysis/OptimizationRemarkEmitter.h"
#include "llvm/Analysis/PostDominators.h"
#include "llvm/Analysis/ProfileSummaryInfo.h"
#include "llvm/Analysis/TargetTransformInfo.h"
#include "llvm/IR/BasicBlock.h"
#include "llvm/IR/CFG.h"
#include "llvm/IR/DiagnosticInfo.h"
#include "llvm/IR/Dominators.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/Instruction.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/PassManager.h"
#include "llvm/IR/User.h"
#include "llvm/IR/Value.h"
#include "llvm/InitializePasses.h"
#include "llvm/Pass.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Transforms/IPO.h"
#include "llvm/Transforms/Utils/CodeExtractor.h"
#include <algorithm>
#include <cassert>
#include <limits>
#include <string>
#define DEBUG_TYPE "hotcoldsplit"
STATISTIC(NumColdRegionsFound, "Number of cold regions found.");
STATISTIC(NumColdRegionsOutlined, "Number of cold regions outlined.");
using namespace llvm;
static cl::opt<bool> EnableStaticAnalysis("hot-cold-static-analysis",
cl::init(true), cl::Hidden);
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)"));
static cl::opt<bool> EnableColdSection(
"enable-cold-section", cl::init(false), cl::Hidden,
cl::desc("Enable placement of extracted cold functions"
" into a separate section after hot-cold splitting."));
static cl::opt<std::string>
ColdSectionName("hotcoldsplit-cold-section-name", cl::init("__llvm_cold"),
cl::Hidden,
cl::desc("Name for the section containing cold functions "
"extracted by hot-cold splitting."));
static cl::opt<int> MaxParametersForSplit(
"hotcoldsplit-max-params", cl::init(4), cl::Hidden,
cl::desc("Maximum number of parameters for a split function"));
namespace {
bool blockEndsInUnreachable(const BasicBlock &BB) {
if (!succ_empty(&BB))
return false;
if (BB.empty())
return true;
const Instruction *I = BB.getTerminator();
return !(isa<ReturnInst>(I) || isa<IndirectBrInst>(I));
}
bool unlikelyExecuted(BasicBlock &BB) {
if (BB.isEHPad() || isa<ResumeInst>(BB.getTerminator()))
return true;
for (Instruction &I : BB)
if (auto *CB = dyn_cast<CallBase>(&I))
if (CB->hasFnAttr(Attribute::Cold) &&
!CB->getMetadata(LLVMContext::MD_nosanitize))
return true;
if (blockEndsInUnreachable(BB)) {
if (auto *CI =
dyn_cast_or_null<CallInst>(BB.getTerminator()->getPrevNode()))
if (CI->hasFnAttr(Attribute::NoReturn))
return false;
return true;
}
return false;
}
static bool mayExtractBlock(const BasicBlock &BB) {
if (BB.hasAddressTaken() || BB.isEHPad())
return false;
auto Term = BB.getTerminator();
return !isa<InvokeInst>(Term) && !isa<ResumeInst>(Term);
}
static bool markFunctionCold(Function &F, bool UpdateEntryCount = false) {
assert(!F.hasOptNone() && "Can't mark this cold");
bool Changed = false;
if (!F.hasFnAttribute(Attribute::Cold)) {
F.addFnAttr(Attribute::Cold);
Changed = true;
}
if (!F.hasFnAttribute(Attribute::MinSize)) {
F.addFnAttr(Attribute::MinSize);
Changed = true;
}
if (UpdateEntryCount) {
F.setEntryCount(0);
Changed = true;
}
return Changed;
}
class HotColdSplittingLegacyPass : public ModulePass {
public:
static char ID;
HotColdSplittingLegacyPass() : ModulePass(ID) {
initializeHotColdSplittingLegacyPassPass(*PassRegistry::getPassRegistry());
}
void getAnalysisUsage(AnalysisUsage &AU) const override {
AU.addRequired<BlockFrequencyInfoWrapperPass>();
AU.addRequired<ProfileSummaryInfoWrapperPass>();
AU.addRequired<TargetTransformInfoWrapperPass>();
AU.addUsedIfAvailable<AssumptionCacheTracker>();
}
bool runOnModule(Module &M) override;
};
}
bool HotColdSplitting::isFunctionCold(const Function &F) const {
if (F.hasFnAttribute(Attribute::Cold))
return true;
if (F.getCallingConv() == CallingConv::Cold)
return true;
if (PSI->isFunctionEntryCold(&F))
return true;
return false;
}
bool HotColdSplitting::shouldOutlineFrom(const Function &F) const {
if (F.hasFnAttribute(Attribute::AlwaysInline))
return false;
if (F.hasFnAttribute(Attribute::NoInline))
return false;
if (F.hasFnAttribute(Attribute::NoReturn))
return false;
if (F.hasFnAttribute(Attribute::SanitizeAddress) ||
F.hasFnAttribute(Attribute::SanitizeHWAddress) ||
F.hasFnAttribute(Attribute::SanitizeThread) ||
F.hasFnAttribute(Attribute::SanitizeMemory))
return false;
return true;
}
static InstructionCost getOutliningBenefit(ArrayRef<BasicBlock *> Region,
TargetTransformInfo &TTI) {
InstructionCost Benefit = 0;
for (BasicBlock *BB : Region)
for (Instruction &I : BB->instructionsWithoutDebug())
if (&I != BB->getTerminator())
Benefit +=
TTI.getInstructionCost(&I, TargetTransformInfo::TCK_CodeSize);
return Benefit;
}
static int getOutliningPenalty(ArrayRef<BasicBlock *> Region,
unsigned NumInputs, unsigned NumOutputs) {
int Penalty = SplittingThreshold;
LLVM_DEBUG(dbgs() << "Applying penalty for splitting: " << Penalty << "\n");
if (SplittingThreshold <= 0)
return Penalty;
bool NoBlocksReturn = true;
SmallPtrSet<BasicBlock *, 2> SuccsOutsideRegion;
for (BasicBlock *BB : Region) {
if (succ_empty(BB)) {
NoBlocksReturn &= isa<UnreachableInst>(BB->getTerminator());
continue;
}
for (BasicBlock *SuccBB : successors(BB)) {
if (!is_contained(Region, SuccBB)) {
NoBlocksReturn = false;
SuccsOutsideRegion.insert(SuccBB);
}
}
}
unsigned NumSplitExitPhis = 0;
for (BasicBlock *ExitBB : SuccsOutsideRegion) {
for (PHINode &PN : ExitBB->phis()) {
int NumIncomingVals = 0;
for (unsigned i = 0; i < PN.getNumIncomingValues(); ++i)
if (llvm::is_contained(Region, PN.getIncomingBlock(i))) {
++NumIncomingVals;
if (NumIncomingVals > 1) {
++NumSplitExitPhis;
break;
}
}
}
}
int NumOutputsAndSplitPhis = NumOutputs + NumSplitExitPhis;
int NumParams = NumInputs + NumOutputsAndSplitPhis;
if (NumParams > MaxParametersForSplit) {
LLVM_DEBUG(dbgs() << NumInputs << " inputs and " << NumOutputsAndSplitPhis
<< " outputs exceeds parameter limit ("
<< MaxParametersForSplit << ")\n");
return std::numeric_limits<int>::max();
}
const int CostForArgMaterialization = 2 * TargetTransformInfo::TCC_Basic;
LLVM_DEBUG(dbgs() << "Applying penalty for: " << NumParams << " params\n");
Penalty += CostForArgMaterialization * NumParams;
LLVM_DEBUG(dbgs() << "Applying penalty for: " << NumOutputsAndSplitPhis
<< " outputs/split phis\n");
const int CostForRegionOutput = 3 * TargetTransformInfo::TCC_Basic;
Penalty += CostForRegionOutput * NumOutputsAndSplitPhis;
if (NoBlocksReturn) {
LLVM_DEBUG(dbgs() << "Applying bonus for: " << Region.size()
<< " non-returning terminators\n");
Penalty -= Region.size();
}
if (SuccsOutsideRegion.size() > 1) {
LLVM_DEBUG(dbgs() << "Applying penalty for: " << SuccsOutsideRegion.size()
<< " non-region successors\n");
Penalty += (SuccsOutsideRegion.size() - 1) * TargetTransformInfo::TCC_Basic;
}
return Penalty;
}
Function *HotColdSplitting::extractColdRegion(
const BlockSequence &Region, const CodeExtractorAnalysisCache &CEAC,
DominatorTree &DT, BlockFrequencyInfo *BFI, TargetTransformInfo &TTI,
OptimizationRemarkEmitter &ORE, AssumptionCache *AC, unsigned Count) {
assert(!Region.empty());
CodeExtractor CE(Region, &DT, false, nullptr,
nullptr, AC, false,
false, nullptr,
"cold." + std::to_string(Count));
SetVector<Value *> Inputs, Outputs, Sinks;
CE.findInputsOutputs(Inputs, Outputs, Sinks);
InstructionCost OutliningBenefit = getOutliningBenefit(Region, TTI);
int OutliningPenalty =
getOutliningPenalty(Region, Inputs.size(), Outputs.size());
LLVM_DEBUG(dbgs() << "Split profitability: benefit = " << OutliningBenefit
<< ", penalty = " << OutliningPenalty << "\n");
if (!OutliningBenefit.isValid() || OutliningBenefit <= OutliningPenalty)
return nullptr;
Function *OrigF = Region[0]->getParent();
if (Function *OutF = CE.extractCodeRegion(CEAC)) {
User *U = *OutF->user_begin();
CallInst *CI = cast<CallInst>(U);
NumColdRegionsOutlined++;
if (TTI.useColdCCForColdCall(*OutF)) {
OutF->setCallingConv(CallingConv::Cold);
CI->setCallingConv(CallingConv::Cold);
}
CI->setIsNoInline();
if (EnableColdSection)
OutF->setSection(ColdSectionName);
else {
if (OrigF->hasSection())
OutF->setSection(OrigF->getSection());
}
markFunctionCold(*OutF, BFI != nullptr);
LLVM_DEBUG(llvm::dbgs() << "Outlined Region: " << *OutF);
ORE.emit([&]() {
return OptimizationRemark(DEBUG_TYPE, "HotColdSplit",
&*Region[0]->begin())
<< ore::NV("Original", OrigF) << " split cold code into "
<< ore::NV("Split", OutF);
});
return OutF;
}
ORE.emit([&]() {
return OptimizationRemarkMissed(DEBUG_TYPE, "ExtractFailed",
&*Region[0]->begin())
<< "Failed to extract region at block "
<< ore::NV("Block", Region.front());
});
return nullptr;
}
using BlockTy = std::pair<BasicBlock *, unsigned>;
namespace {
class OutliningRegion {
SmallVector<BlockTy, 0> Blocks = {};
BasicBlock *SuggestedEntryPoint = nullptr;
bool EntireFunctionCold = false;
static unsigned getEntryPointScore(BasicBlock &BB, unsigned Score) {
return mayExtractBlock(BB) ? Score : 0;
}
static constexpr unsigned ScoreForSuccBlock = 1;
static constexpr unsigned ScoreForSinkBlock = 1;
OutliningRegion(const OutliningRegion &) = delete;
OutliningRegion &operator=(const OutliningRegion &) = delete;
public:
OutliningRegion() = default;
OutliningRegion(OutliningRegion &&) = default;
OutliningRegion &operator=(OutliningRegion &&) = default;
static std::vector<OutliningRegion> create(BasicBlock &SinkBB,
const DominatorTree &DT,
const PostDominatorTree &PDT) {
std::vector<OutliningRegion> Regions;
SmallPtrSet<BasicBlock *, 4> RegionBlocks;
Regions.emplace_back();
OutliningRegion *ColdRegion = &Regions.back();
auto addBlockToRegion = [&](BasicBlock *BB, unsigned Score) {
RegionBlocks.insert(BB);
ColdRegion->Blocks.emplace_back(BB, Score);
};
unsigned SinkScore = getEntryPointScore(SinkBB, ScoreForSinkBlock);
ColdRegion->SuggestedEntryPoint = (SinkScore > 0) ? &SinkBB : nullptr;
unsigned BestScore = SinkScore;
auto PredIt = ++idf_begin(&SinkBB);
auto PredEnd = idf_end(&SinkBB);
while (PredIt != PredEnd) {
BasicBlock &PredBB = **PredIt;
bool SinkPostDom = PDT.dominates(&SinkBB, &PredBB);
if (SinkPostDom && pred_empty(&PredBB)) {
ColdRegion->EntireFunctionCold = true;
return Regions;
}
if (!SinkPostDom || !mayExtractBlock(PredBB)) {
PredIt.skipChildren();
continue;
}
unsigned PredScore = getEntryPointScore(PredBB, PredIt.getPathLength());
if (PredScore > BestScore) {
ColdRegion->SuggestedEntryPoint = &PredBB;
BestScore = PredScore;
}
addBlockToRegion(&PredBB, PredScore);
++PredIt;
}
if (mayExtractBlock(SinkBB)) {
addBlockToRegion(&SinkBB, SinkScore);
if (pred_empty(&SinkBB)) {
ColdRegion->EntireFunctionCold = true;
return Regions;
}
} else {
Regions.emplace_back();
ColdRegion = &Regions.back();
BestScore = 0;
}
auto SuccIt = ++df_begin(&SinkBB);
auto SuccEnd = df_end(&SinkBB);
while (SuccIt != SuccEnd) {
BasicBlock &SuccBB = **SuccIt;
bool SinkDom = DT.dominates(&SinkBB, &SuccBB);
bool DuplicateBlock = RegionBlocks.count(&SuccBB);
if (DuplicateBlock || !SinkDom || !mayExtractBlock(SuccBB)) {
SuccIt.skipChildren();
continue;
}
unsigned SuccScore = getEntryPointScore(SuccBB, ScoreForSuccBlock);
if (SuccScore > BestScore) {
ColdRegion->SuggestedEntryPoint = &SuccBB;
BestScore = SuccScore;
}
addBlockToRegion(&SuccBB, SuccScore);
++SuccIt;
}
return Regions;
}
bool empty() const { return !SuggestedEntryPoint; }
ArrayRef<std::pair<BasicBlock *, unsigned>> blocks() const { return Blocks; }
bool isEntireFunctionCold() const { return EntireFunctionCold; }
BlockSequence takeSingleEntrySubRegion(DominatorTree &DT) {
assert(!empty() && !isEntireFunctionCold() && "Nothing to extract");
BlockSequence SubRegion = {SuggestedEntryPoint};
BasicBlock *NextEntryPoint = nullptr;
unsigned NextScore = 0;
auto RegionEndIt = Blocks.end();
auto RegionStartIt = remove_if(Blocks, [&](const BlockTy &Block) {
BasicBlock *BB = Block.first;
unsigned Score = Block.second;
bool InSubRegion =
BB == SuggestedEntryPoint || DT.dominates(SuggestedEntryPoint, BB);
if (!InSubRegion && Score > NextScore) {
NextEntryPoint = BB;
NextScore = Score;
}
if (InSubRegion && BB != SuggestedEntryPoint)
SubRegion.push_back(BB);
return InSubRegion;
});
Blocks.erase(RegionStartIt, RegionEndIt);
SuggestedEntryPoint = NextEntryPoint;
return SubRegion;
}
};
}
bool HotColdSplitting::outlineColdRegions(Function &F, bool HasProfileSummary) {
bool Changed = false;
SmallPtrSet<BasicBlock *, 4> ColdBlocks;
SmallVector<OutliningRegion, 2> OutliningWorklist;
ReversePostOrderTraversal<Function *> RPOT(&F);
std::unique_ptr<DominatorTree> DT;
std::unique_ptr<PostDominatorTree> PDT;
BlockFrequencyInfo *BFI = nullptr;
if (HasProfileSummary)
BFI = GetBFI(F);
TargetTransformInfo &TTI = GetTTI(F);
OptimizationRemarkEmitter &ORE = (*GetORE)(F);
AssumptionCache *AC = LookupAC(F);
for (BasicBlock *BB : RPOT) {
if (ColdBlocks.count(BB))
continue;
bool Cold = (BFI && PSI->isColdBlock(BB, BFI)) ||
(EnableStaticAnalysis && unlikelyExecuted(*BB));
if (!Cold)
continue;
LLVM_DEBUG({
dbgs() << "Found a cold block:\n";
BB->dump();
});
if (!DT)
DT = std::make_unique<DominatorTree>(F);
if (!PDT)
PDT = std::make_unique<PostDominatorTree>(F);
auto Regions = OutliningRegion::create(*BB, *DT, *PDT);
for (OutliningRegion &Region : Regions) {
if (Region.empty())
continue;
if (Region.isEntireFunctionCold()) {
LLVM_DEBUG(dbgs() << "Entire function is cold\n");
return markFunctionCold(F);
}
bool RegionsOverlap = any_of(Region.blocks(), [&](const BlockTy &Block) {
return !ColdBlocks.insert(Block.first).second;
});
if (RegionsOverlap)
continue;
OutliningWorklist.emplace_back(std::move(Region));
++NumColdRegionsFound;
}
}
if (OutliningWorklist.empty())
return Changed;
unsigned OutlinedFunctionID = 1;
CodeExtractorAnalysisCache CEAC(F);
do {
OutliningRegion Region = OutliningWorklist.pop_back_val();
assert(!Region.empty() && "Empty outlining region in worklist");
do {
BlockSequence SubRegion = Region.takeSingleEntrySubRegion(*DT);
LLVM_DEBUG({
dbgs() << "Hot/cold splitting attempting to outline these blocks:\n";
for (BasicBlock *BB : SubRegion)
BB->dump();
});
Function *Outlined = extractColdRegion(SubRegion, CEAC, *DT, BFI, TTI,
ORE, AC, OutlinedFunctionID);
if (Outlined) {
++OutlinedFunctionID;
Changed = true;
}
} while (!Region.empty());
} while (!OutliningWorklist.empty());
return Changed;
}
bool HotColdSplitting::run(Module &M) {
bool Changed = false;
bool HasProfileSummary = (M.getProfileSummary( false) != nullptr);
for (Function &F : M) {
if (F.isDeclaration())
continue;
if (F.hasOptNone())
continue;
if (isFunctionCold(F)) {
Changed |= markFunctionCold(F);
continue;
}
if (!shouldOutlineFrom(F)) {
LLVM_DEBUG(llvm::dbgs() << "Skipping " << F.getName() << "\n");
continue;
}
LLVM_DEBUG(llvm::dbgs() << "Outlining in " << F.getName() << "\n");
Changed |= outlineColdRegions(F, HasProfileSummary);
}
return Changed;
}
bool HotColdSplittingLegacyPass::runOnModule(Module &M) {
if (skipModule(M))
return false;
ProfileSummaryInfo *PSI =
&getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
auto GTTI = [this](Function &F) -> TargetTransformInfo & {
return this->getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
};
auto GBFI = [this](Function &F) {
return &this->getAnalysis<BlockFrequencyInfoWrapperPass>(F).getBFI();
};
std::unique_ptr<OptimizationRemarkEmitter> ORE;
std::function<OptimizationRemarkEmitter &(Function &)> GetORE =
[&ORE](Function &F) -> OptimizationRemarkEmitter & {
ORE.reset(new OptimizationRemarkEmitter(&F));
return *ORE;
};
auto LookupAC = [this](Function &F) -> AssumptionCache * {
if (auto *ACT = getAnalysisIfAvailable<AssumptionCacheTracker>())
return ACT->lookupAssumptionCache(F);
return nullptr;
};
return HotColdSplitting(PSI, GBFI, GTTI, &GetORE, LookupAC).run(M);
}
PreservedAnalyses
HotColdSplittingPass::run(Module &M, ModuleAnalysisManager &AM) {
auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
auto LookupAC = [&FAM](Function &F) -> AssumptionCache * {
return FAM.getCachedResult<AssumptionAnalysis>(F);
};
auto GBFI = [&FAM](Function &F) {
return &FAM.getResult<BlockFrequencyAnalysis>(F);
};
std::function<TargetTransformInfo &(Function &)> GTTI =
[&FAM](Function &F) -> TargetTransformInfo & {
return FAM.getResult<TargetIRAnalysis>(F);
};
std::unique_ptr<OptimizationRemarkEmitter> ORE;
std::function<OptimizationRemarkEmitter &(Function &)> GetORE =
[&ORE](Function &F) -> OptimizationRemarkEmitter & {
ORE.reset(new OptimizationRemarkEmitter(&F));
return *ORE;
};
ProfileSummaryInfo *PSI = &AM.getResult<ProfileSummaryAnalysis>(M);
if (HotColdSplitting(PSI, GBFI, GTTI, &GetORE, LookupAC).run(M))
return PreservedAnalyses::none();
return PreservedAnalyses::all();
}
char HotColdSplittingLegacyPass::ID = 0;
INITIALIZE_PASS_BEGIN(HotColdSplittingLegacyPass, "hotcoldsplit",
"Hot Cold Splitting", false, false)
INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)
INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
INITIALIZE_PASS_END(HotColdSplittingLegacyPass, "hotcoldsplit",
"Hot Cold Splitting", false, false)
ModulePass *llvm::createHotColdSplittingPass() {
return new HotColdSplittingLegacyPass();
}