51#define DEBUG_TYPE "branch-prob"
55 cl::desc(
"Print the branch probability info."));
59 cl::desc(
"The option to specify the name of the function "
60 "whose branch probability info is printed."));
63 "Branch Probability Analysis",
false,
true)
165class BPIConstruction {
167 BPIConstruction(BranchProbabilityInfo &BPI) : BPI(BPI) {}
168 void calculate(
const Function &
F,
const LoopInfo &LI,
169 const TargetLibraryInfo *TLI, DominatorTree *DT,
170 PostDominatorTree *PDT);
185 using SccMap = DenseMap<const BasicBlock *, int>;
191 using SccBlockTypeMap = DenseMap<const BasicBlock *, uint32_t>;
194 using SccBlockTypeMaps = std::vector<SccBlockTypeMap>;
197 SccBlockTypeMaps SccBlocks;
208 bool isSCCHeader(
const BasicBlock *BB,
int SccNum)
const {
209 return getSccBlockType(BB, SccNum) & Header;
213 bool isSCCExitingBlock(
const BasicBlock *BB,
int SccNum)
const {
214 return getSccBlockType(BB, SccNum) & Exiting;
219 void getSccEnterBlocks(
int SccNum,
220 SmallVectorImpl<BasicBlock *> &Enters)
const;
224 void getSccExitBlocks(
int SccNum,
225 SmallVectorImpl<BasicBlock *> &Exits)
const;
230 uint32_t getSccBlockType(
const BasicBlock *BB,
int SccNum)
const;
233 void calculateSccBlockType(
const BasicBlock *BB,
int SccNum);
238 using LoopData = std::pair<Loop *, int>;
242 explicit LoopBlock(
const BasicBlock *BB,
const LoopInfo &LI,
243 const SccInfo &SccI);
245 const BasicBlock *getBlock()
const {
return BB; }
247 LoopData getLoopData()
const {
return LD; }
248 Loop *getLoop()
const {
return LD.first; }
249 int getSccNum()
const {
return LD.second; }
251 bool belongsToLoop()
const {
return getLoop() || getSccNum() != -1; }
252 bool belongsToSameLoop(
const LoopBlock &LB)
const {
253 return (LB.getLoop() && getLoop() == LB.getLoop()) ||
254 (LB.getSccNum() != -1 && getSccNum() == LB.getSccNum());
259 LoopData LD = {
nullptr, -1};
263 using LoopEdge = std::pair<const LoopBlock &, const LoopBlock &>;
266 LoopBlock getLoopBlock(
const BasicBlock *BB)
const {
267 return LoopBlock(BB, *LI, *SccI);
273 bool isLoopEnteringEdge(
const LoopEdge &
Edge)
const;
277 bool isLoopExitingEdge(
const LoopEdge &
Edge)
const;
280 bool isLoopEnteringExitingEdge(
const LoopEdge &
Edge)
const;
283 bool isLoopBackEdge(
const LoopEdge &
Edge)
const;
285 void getLoopEnterBlocks(
const LoopBlock &LB,
286 SmallVectorImpl<BasicBlock *> &Enters)
const;
288 void getLoopExitBlocks(
const LoopBlock &LB,
289 SmallVectorImpl<BasicBlock *> &Exits)
const;
293 std::optional<uint32_t> getEstimatedBlockWeight(
const BasicBlock *BB)
const;
298 std::optional<uint32_t> getEstimatedLoopWeight(
const LoopData &
L)
const;
302 std::optional<uint32_t> getEstimatedEdgeWeight(
const LoopEdge &
Edge)
const;
307 template <
class IterT>
308 std::optional<uint32_t>
309 getMaxEstimatedEdgeWeight(
const LoopBlock &SrcBB,
316 bool updateEstimatedBlockWeight(LoopBlock &LoopBB, uint32_t BBWeight,
317 SmallVectorImpl<BasicBlock *> &BlockWorkList,
318 SmallVectorImpl<LoopBlock> &LoopWorkList);
322 void propagateEstimatedBlockWeight(
const LoopBlock &LoopBB, DominatorTree *DT,
323 PostDominatorTree *PDT, uint32_t BBWeight,
324 SmallVectorImpl<BasicBlock *> &WorkList,
325 SmallVectorImpl<LoopBlock> &LoopWorkList);
328 std::optional<uint32_t> getInitialEstimatedBlockWeight(
const BasicBlock *BB);
331 void estimateBlockWeights(
const Function &
F, DominatorTree *DT,
332 PostDominatorTree *PDT);
336 bool calcEstimatedHeuristics(
const BasicBlock *BB);
337 bool calcMetadataWeights(
const BasicBlock *BB);
338 bool calcPointerHeuristics(
const BasicBlock *BB);
339 bool calcZeroHeuristics(
const BasicBlock *BB,
const TargetLibraryInfo *TLI);
340 bool calcFloatingPointHeuristics(
const BasicBlock *BB);
342 BranchProbabilityInfo &BPI;
344 const LoopInfo *LI =
nullptr;
347 std::unique_ptr<const SccInfo> SccI;
350 SmallDenseMap<const BasicBlock *, uint32_t> EstimatedBlockWeight;
353 SmallDenseMap<LoopData, uint32_t> EstimatedLoopWeight;
356BPIConstruction::SccInfo::SccInfo(
const Function &
F) {
361 for (scc_iterator<const Function *> It =
scc_begin(&
F); !It.isAtEnd();
365 const std::vector<const BasicBlock *> &Scc = *It;
370 for (
const auto *BB : Scc) {
372 SccNums[BB] = SccNum;
373 calculateSccBlockType(BB, SccNum);
379int BPIConstruction::SccInfo::getSCCNum(
const BasicBlock *BB)
const {
380 auto SccIt = SccNums.find(BB);
381 if (SccIt == SccNums.end())
383 return SccIt->second;
386void BPIConstruction::SccInfo::getSccEnterBlocks(
387 int SccNum, SmallVectorImpl<BasicBlock *> &Enters)
const {
389 for (
auto MapIt : SccBlocks[SccNum]) {
390 const auto *BB = MapIt.first;
391 if (isSCCHeader(BB, SccNum))
393 if (getSCCNum(Pred) != SccNum)
398void BPIConstruction::SccInfo::getSccExitBlocks(
399 int SccNum, SmallVectorImpl<BasicBlock *> &Exits)
const {
400 for (
auto MapIt : SccBlocks[SccNum]) {
401 const auto *BB = MapIt.first;
402 if (isSCCExitingBlock(BB, SccNum))
404 if (getSCCNum(Succ) != SccNum)
409uint32_t BPIConstruction::SccInfo::getSccBlockType(
const BasicBlock *BB,
411 assert(getSCCNum(BB) == SccNum);
413 assert(SccBlocks.size() >
static_cast<unsigned>(SccNum) &&
"Unknown SCC");
414 const auto &SccBlockTypes = SccBlocks[SccNum];
416 auto It = SccBlockTypes.find(BB);
417 if (It != SccBlockTypes.end()) {
423void BPIConstruction::SccInfo::calculateSccBlockType(
const BasicBlock *BB,
425 assert(getSCCNum(BB) == SccNum);
431 return getSCCNum(Pred) != SccNum;
436 return getSCCNum(Succ) != SccNum;
438 BlockType |= Exiting;
442 if (SccBlocks.size() <=
static_cast<unsigned>(SccNum))
443 SccBlocks.resize(SccNum + 1);
444 auto &SccBlockTypes = SccBlocks[SccNum];
446 if (BlockType != Inner) {
448 std::tie(std::ignore, IsInserted) =
449 SccBlockTypes.insert(std::make_pair(BB, BlockType));
450 assert(IsInserted &&
"Duplicated block in SCC");
454BPIConstruction::LoopBlock::LoopBlock(
const BasicBlock *BB,
const LoopInfo &LI,
459 LD.second = SccI.getSCCNum(BB);
463bool BPIConstruction::isLoopEnteringEdge(
const LoopEdge &Edge)
const {
464 const auto &SrcBlock =
Edge.first;
465 const auto &DstBlock =
Edge.second;
466 return (DstBlock.getLoop() &&
467 !DstBlock.getLoop()->contains(SrcBlock.getLoop())) ||
469 (DstBlock.getSccNum() != -1 &&
470 SrcBlock.getSccNum() != DstBlock.getSccNum());
473bool BPIConstruction::isLoopExitingEdge(
const LoopEdge &
Edge)
const {
474 return isLoopEnteringEdge({
Edge.second,
Edge.first});
477bool BPIConstruction::isLoopEnteringExitingEdge(
const LoopEdge &
Edge)
const {
478 return isLoopEnteringEdge(
Edge) || isLoopExitingEdge(
Edge);
481bool BPIConstruction::isLoopBackEdge(
const LoopEdge &
Edge)
const {
482 const auto &SrcBlock =
Edge.first;
483 const auto &DstBlock =
Edge.second;
484 return SrcBlock.belongsToSameLoop(DstBlock) &&
485 ((DstBlock.getLoop() &&
486 DstBlock.getLoop()->getHeader() == DstBlock.getBlock()) ||
487 (DstBlock.getSccNum() != -1 &&
488 SccI->isSCCHeader(DstBlock.getBlock(), DstBlock.getSccNum())));
491void BPIConstruction::getLoopEnterBlocks(
492 const LoopBlock &LB, SmallVectorImpl<BasicBlock *> &Enters)
const {
494 auto *Header = LB.getLoop()->getHeader();
497 assert(LB.getSccNum() != -1 &&
"LB doesn't belong to any loop?");
498 SccI->getSccEnterBlocks(LB.getSccNum(), Enters);
502void BPIConstruction::getLoopExitBlocks(
503 const LoopBlock &LB, SmallVectorImpl<BasicBlock *> &Exits)
const {
505 LB.getLoop()->getExitBlocks(Exits);
507 assert(LB.getSccNum() != -1 &&
"LB doesn't belong to any loop?");
508 SccI->getSccExitBlocks(LB.getSccNum(), Exits);
516bool BPIConstruction::calcMetadataWeights(
const BasicBlock *BB) {
533 uint64_t WeightSum = 0;
535 SmallVector<unsigned, 2> UnreachableIdxs;
536 SmallVector<unsigned, 2> ReachableIdxs;
540 for (
unsigned I = 0,
E = Weights.
size();
I !=
E; ++
I) {
541 WeightSum += Weights[
I];
542 const LoopBlock SrcLoopBB = getLoopBlock(BB);
543 const LoopBlock DstLoopBB = getLoopBlock(*Succs++);
544 auto EstimatedWeight = getEstimatedEdgeWeight({SrcLoopBB, DstLoopBB});
545 if (EstimatedWeight &&
555 uint64_t ScalingFactor =
556 (WeightSum > UINT32_MAX) ? WeightSum / UINT32_MAX + 1 : 1;
558 if (ScalingFactor > 1) {
561 Weights[
I] /= ScalingFactor;
562 WeightSum += Weights[
I];
565 assert(WeightSum <= UINT32_MAX &&
566 "Expected weights to scale down to 32 bits");
568 if (WeightSum == 0 || ReachableIdxs.
size() == 0) {
577 BP.
push_back({ Weights[
I],
static_cast<uint32_t
>(WeightSum) });
581 if (UnreachableIdxs.
size() == 0 || ReachableIdxs.
size() == 0) {
587 for (
auto I : UnreachableIdxs)
588 if (UnreachableProb < BP[
I]) {
589 BP[
I] = UnreachableProb;
613 for (
auto I : UnreachableIdxs)
614 NewUnreachableSum += BP[
I];
616 BranchProbability NewReachableSum =
620 for (
auto I : ReachableIdxs)
621 OldReachableSum += BP[
I];
623 if (OldReachableSum != NewReachableSum) {
624 if (OldReachableSum.
isZero()) {
628 BranchProbability PerEdge = NewReachableSum / ReachableIdxs.size();
629 for (
auto I : ReachableIdxs)
632 for (
auto I : ReachableIdxs) {
638 BP[
I].getNumerator();
639 uint32_t Div =
static_cast<uint32_t
>(
653bool BPIConstruction::calcPointerHeuristics(
const BasicBlock *BB) {
671 case ICmpInst::ICMP_NE:
674 case ICmpInst::ICMP_EQ:
686computeUnlikelySuccessors(
const BasicBlock *BB, Loop *L,
687 SmallPtrSetImpl<const BasicBlock*> &UnlikelyBlocks) {
730 if (!
L->contains(CmpLHS))
737 if (!CmpPHI || !
L->contains(CmpPHI))
741 SmallPtrSet<PHINode*, 8> VisitedInsts;
744 VisitedInsts.
insert(CmpPHI);
745 while (!WorkList.
empty()) {
747 for (BasicBlock *
B :
P->blocks()) {
751 Value *
V =
P->getIncomingValueForBlock(
B);
755 if (VisitedInsts.
insert(PN).second)
787std::optional<uint32_t>
788BPIConstruction::getEstimatedBlockWeight(
const BasicBlock *BB)
const {
789 auto WeightIt = EstimatedBlockWeight.find(BB);
790 if (WeightIt == EstimatedBlockWeight.end())
792 return WeightIt->second;
795std::optional<uint32_t>
796BPIConstruction::getEstimatedLoopWeight(
const LoopData &L)
const {
797 auto WeightIt = EstimatedLoopWeight.find(L);
798 if (WeightIt == EstimatedLoopWeight.end())
800 return WeightIt->second;
803std::optional<uint32_t>
804BPIConstruction::getEstimatedEdgeWeight(
const LoopEdge &
Edge)
const {
807 return isLoopEnteringEdge(
Edge)
808 ? getEstimatedLoopWeight(
Edge.second.getLoopData())
809 : getEstimatedBlockWeight(
Edge.second.getBlock());
812template <
class IterT>
813std::optional<uint32_t> BPIConstruction::getMaxEstimatedEdgeWeight(
815 std::optional<uint32_t> MaxWeight;
816 for (
const BasicBlock *DstBB : Successors) {
817 const LoopBlock DstLoopBB = getLoopBlock(DstBB);
818 auto Weight = getEstimatedEdgeWeight({SrcLoopBB, DstLoopBB});
823 if (!MaxWeight || *MaxWeight < *Weight)
835bool BPIConstruction::updateEstimatedBlockWeight(
836 LoopBlock &LoopBB, uint32_t BBWeight,
837 SmallVectorImpl<BasicBlock *> &BlockWorkList,
838 SmallVectorImpl<LoopBlock> &LoopWorkList) {
846 if (!EstimatedBlockWeight.insert({BB, BBWeight}).second)
850 LoopBlock PredLoop = getLoopBlock(PredBlock);
852 if (isLoopExitingEdge({PredLoop, LoopBB})) {
853 if (!EstimatedLoopWeight.count(PredLoop.getLoopData()))
855 }
else if (!EstimatedBlockWeight.count(PredBlock))
873void BPIConstruction::propagateEstimatedBlockWeight(
874 const LoopBlock &LoopBB, DominatorTree *DT, PostDominatorTree *PDT,
875 uint32_t BBWeight, SmallVectorImpl<BasicBlock *> &BlockWorkList,
876 SmallVectorImpl<LoopBlock> &LoopWorkList) {
878 const auto *DTStartNode = DT->
getNode(BB);
879 const auto *PDTStartNode = PDT->
getNode(BB);
882 for (
const auto *DTNode = DTStartNode; DTNode !=
nullptr;
883 DTNode = DTNode->getIDom()) {
884 auto *DomBB = DTNode->getBlock();
891 LoopBlock DomLoopBB = getLoopBlock(DomBB);
892 const LoopEdge
Edge{DomLoopBB, LoopBB};
894 if (!isLoopEnteringExitingEdge(
Edge)) {
895 if (!updateEstimatedBlockWeight(DomLoopBB, BBWeight, BlockWorkList,
900 }
else if (isLoopExitingEdge(
Edge)) {
906std::optional<uint32_t>
907BPIConstruction::getInitialEstimatedBlockWeight(
const BasicBlock *BB) {
909 auto hasNoReturn = [&](
const BasicBlock *BB) {
912 if (CI->hasFnAttr(Attribute::NoReturn))
927 return hasNoReturn(BB)
936 for (
const auto &
I : *BB)
938 if (CI->hasFnAttr(Attribute::Cold))
947void BPIConstruction::estimateBlockWeights(
const Function &
F, DominatorTree *DT,
948 PostDominatorTree *PDT) {
949 SmallVector<BasicBlock *, 8> BlockWorkList;
951 SmallDenseMap<LoopData, SmallVector<BasicBlock *, 4>> LoopExitBlocks;
955 ReversePostOrderTraversal<const Function *> RPOT(&
F);
956 for (
const auto *BB : RPOT)
957 if (
auto BBWeight = getInitialEstimatedBlockWeight(BB))
960 propagateEstimatedBlockWeight(getLoopBlock(BB), DT, PDT, *BBWeight,
961 BlockWorkList, LoopWorkList);
968 while (!LoopWorkList.
empty()) {
970 const LoopData
LD = LoopBB.getLoopData();
971 if (EstimatedLoopWeight.count(LD))
975 SmallVectorImpl<BasicBlock *> &Exits = Res.first->second;
977 getLoopExitBlocks(LoopBB, Exits);
978 auto LoopWeight = getMaxEstimatedEdgeWeight(
986 EstimatedLoopWeight.insert({
LD, *LoopWeight});
988 getLoopEnterBlocks(LoopBB, BlockWorkList);
992 while (!BlockWorkList.
empty()) {
995 if (EstimatedBlockWeight.count(BB))
1004 const LoopBlock LoopBB = getLoopBlock(BB);
1005 auto MaxWeight = getMaxEstimatedEdgeWeight(LoopBB,
successors(BB));
1008 propagateEstimatedBlockWeight(LoopBB, DT, PDT, *MaxWeight,
1009 BlockWorkList, LoopWorkList);
1011 }
while (!BlockWorkList.
empty() || !LoopWorkList.
empty());
1017bool BPIConstruction::calcEstimatedHeuristics(
const BasicBlock *BB) {
1019 "expected more than one successor!");
1021 const LoopBlock LoopBB = getLoopBlock(BB);
1023 SmallPtrSet<const BasicBlock *, 8> UnlikelyBlocks;
1025 if (LoopBB.getLoop())
1026 computeUnlikelySuccessors(BB, LoopBB.getLoop(), UnlikelyBlocks);
1029 bool FoundEstimatedWeight =
false;
1030 SmallVector<uint32_t, 4> SuccWeights;
1031 uint64_t TotalWeight = 0;
1033 for (
const BasicBlock *SuccBB :
successors(BB)) {
1034 std::optional<uint32_t> Weight;
1035 const LoopBlock SuccLoopBB = getLoopBlock(SuccBB);
1036 const LoopEdge
Edge{LoopBB, SuccLoopBB};
1038 Weight = getEstimatedEdgeWeight(
Edge);
1040 if (isLoopExitingEdge(
Edge) &&
1049 bool IsUnlikelyEdge = LoopBB.getLoop() && UnlikelyBlocks.
contains(SuccBB);
1050 if (IsUnlikelyEdge &&
1060 FoundEstimatedWeight =
true;
1064 TotalWeight += WeightVal;
1071 if (!FoundEstimatedWeight || TotalWeight == 0)
1075 const unsigned SuccCount = SuccWeights.
size();
1079 if (TotalWeight > UINT32_MAX) {
1080 uint64_t ScalingFactor = TotalWeight / UINT32_MAX + 1;
1082 for (
unsigned Idx = 0; Idx < SuccCount; ++Idx) {
1083 SuccWeights[Idx] /= ScalingFactor;
1087 TotalWeight += SuccWeights[Idx];
1089 assert(TotalWeight <= UINT32_MAX &&
"Total weight overflows");
1096 for (
unsigned Idx = 0; Idx < SuccCount; ++Idx) {
1097 EdgeProbabilities[Idx] =
1098 BranchProbability(SuccWeights[Idx], (uint32_t)TotalWeight);
1104bool BPIConstruction::calcZeroHeuristics(
const BasicBlock *BB,
1105 const TargetLibraryInfo *TLI) {
1115 auto GetConstantInt = [](
Value *
V) {
1122 ConstantInt *CV = GetConstantInt(
RHS);
1129 if (
LHS->getOpcode() == Instruction::And)
1130 if (ConstantInt *AndRHS = GetConstantInt(
LHS->getOperand(1)))
1131 if (AndRHS->getValue().isPowerOf2())
1135 LibFunc
Func = LibFunc::NotLibFunc;
1142 if (Func == LibFunc_strcasecmp ||
1143 Func == LibFunc_strcmp ||
1144 Func == LibFunc_strncasecmp ||
1145 Func == LibFunc_strncmp ||
1146 Func == LibFunc_memcmp ||
1147 Func == LibFunc_bcmp) {
1159 default:
return false;
1162 }
else if (CV->
isZero()) {
1169 default:
return false;
1172 }
else if (CV->
isOne()) {
1176 default:
return false;
1186 default:
return false;
1200bool BPIConstruction::calcFloatingPointHeuristics(
const BasicBlock *BB) {
1215 }
else if (FCmp->
getPredicate() == FCmpInst::FCMP_ORD) {
1218 }
else if (FCmp->
getPredicate() == FCmpInst::FCMP_UNO) {
1226void BPIConstruction::calculate(
const Function &
F,
const LoopInfo &LoopI,
1227 const TargetLibraryInfo *TLI, DominatorTree *DT,
1228 PostDominatorTree *PDT) {
1231 SccI = std::make_unique<SccInfo>(
F);
1233 std::unique_ptr<DominatorTree> DTPtr;
1234 std::unique_ptr<PostDominatorTree> PDTPtr;
1237 DTPtr = std::make_unique<DominatorTree>(
const_cast<Function &
>(
F));
1242 PDTPtr = std::make_unique<PostDominatorTree>(
const_cast<Function &
>(
F));
1246 estimateBlockWeights(
F, DT, PDT);
1250 for (
const auto *BB :
post_order(&
F.getEntryBlock())) {
1256 if (calcMetadataWeights(BB))
1258 if (calcEstimatedHeuristics(BB))
1260 if (calcPointerHeuristics(BB))
1262 if (calcZeroHeuristics(BB, TLI))
1264 if (calcFloatingPointHeuristics(BB))
1272BranchProbabilityInfo::allocEdges(
const BasicBlock *BB) {
1274 assert(BlockNumberEpoch == LastF->getBlockNumberEpoch());
1276 if (NumSuccs == 0) {
1280 if (EdgeStarts.size() <= BB->
getNumber())
1281 EdgeStarts.resize(LastF->getMaxBlockNumber(), 0);
1282 unsigned EdgeStart = Probs.size();
1283 EdgeStarts[BB->
getNumber()] = EdgeStart + 1;
1284 Probs.append(NumSuccs, {});
1289BranchProbabilityInfo::getEdges(
const BasicBlock *BB)
const {
1291 assert(BlockNumberEpoch == LastF->getBlockNumberEpoch());
1292 if (EdgeStarts.size() <= BB->
getNumber())
1294 if (
unsigned EdgeStart = EdgeStarts[BB->
getNumber()]) {
1295 const BranchProbability *
Start = &Probs[EdgeStart - 1];
1296 size_t Count = SIZE_MAX;
1306 FunctionAnalysisManager::Invalidator &) {
1315 OS <<
"---- Branch Probabilities ----\n";
1318 assert(LastF &&
"Cannot print prior to running over a function");
1319 for (
const auto &BI : *LastF) {
1338 unsigned IndexInSuccessors)
const {
1340 return P[IndexInSuccessors];
1355 if (It.value() == Dst)
1356 Prob +=
P[It.index()];
1364 assert(Src->getTerminator()->getNumSuccessors() == Probs.size());
1367 for (
unsigned SuccIdx = 0; SuccIdx < Probs.size(); ++SuccIdx) {
1368 P[SuccIdx] = Probs[SuccIdx];
1369 LLVM_DEBUG(
dbgs() <<
"set edge " << Src->getName() <<
" -> " << SuccIdx
1370 <<
" successor probability to " << Probs[SuccIdx]
1372 TotalNumerator += Probs[SuccIdx].getNumerator();
1384 (void)TotalNumerator;
1398 for (
unsigned i = 0; i != DstP.
size(); ++i) {
1400 LLVM_DEBUG(
dbgs() <<
"set edge " << Dst->getName() <<
" -> " << i
1401 <<
" successor probability to " << SrcP[i] <<
"\n");
1406 assert(Src->getTerminator()->getNumSuccessors() == 2);
1421 Src->printAsOperand(OS,
false, Src->getModule());
1423 Dst->printAsOperand(OS,
false, Dst->getModule());
1424 OS <<
" probability is " << Prob
1425 << (
isEdgeHot(Src, Dst) ?
" [HOT edge]\n" :
"\n");
1433 assert(BlockNumberEpoch == LastF->getBlockNumberEpoch());
1434 if (EdgeStarts.size() > BB->
getNumber())
1445 BlockNumberEpoch =
F.getBlockNumberEpoch();
1448 BPIConstruction(*this).calculate(
F, LoopI, TLI, DT, PDT);
1476 BPI.calculate(
F, LI, &TLI, &DT, &PDT);
1499 OS <<
"Printing analysis 'Branch Probability Analysis' for function '"
1500 <<
F.getName() <<
"':\n";
for(const MachineOperand &MO :llvm::drop_begin(OldMI.operands(), Desc.getNumOperands()))
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static void print(raw_ostream &Out, object::Archive::Kind Kind, T Val)
This file contains the simple types necessary to represent the attributes associated with functions a...
BlockExecWeight
Set of dedicated "absolute" execution weights for a block.
@ NORETURN
Weight to a block containing non returning call.
@ UNWIND
Weight to 'unwind' block of an invoke instruction.
@ COLD
Weight to a 'cold' block.
@ ZERO
Special weight used for cases with exact zero probability.
@ UNREACHABLE
Weight to an 'unreachable' block.
@ DEFAULT
Default weight is used in cases when there is no dedicated execution weight set.
@ LOWEST_NON_ZERO
Minimal possible non zero weight.
static constexpr BranchProbability FPTakenProb(FPH_TAKEN_WEIGHT, FPH_TAKEN_WEIGHT+FPH_NONTAKEN_WEIGHT)
static const uint32_t FPH_TAKEN_WEIGHT
static const uint32_t LBH_TAKEN_WEIGHT
static const uint32_t ZH_NONTAKEN_WEIGHT
static const uint32_t PH_NONTAKEN_WEIGHT
static constexpr BranchProbability UR_TAKEN_PROB
Unreachable-terminating branch taken probability.
static const uint32_t PH_TAKEN_WEIGHT
Heuristics and lookup tables for non-loop branches: Pointer Heuristics (PH)
static constexpr BranchProbability FPUntakenProb(FPH_NONTAKEN_WEIGHT, FPH_TAKEN_WEIGHT+FPH_NONTAKEN_WEIGHT)
static constexpr BranchProbability PtrTakenProb(PH_TAKEN_WEIGHT, PH_TAKEN_WEIGHT+PH_NONTAKEN_WEIGHT)
static constexpr BranchProbability PtrUntakenProb(PH_NONTAKEN_WEIGHT, PH_TAKEN_WEIGHT+PH_NONTAKEN_WEIGHT)
static const uint32_t ZH_TAKEN_WEIGHT
Zero Heuristics (ZH)
static const uint32_t FPH_NONTAKEN_WEIGHT
static constexpr BranchProbability ZeroTakenProb(ZH_TAKEN_WEIGHT, ZH_TAKEN_WEIGHT+ZH_NONTAKEN_WEIGHT)
static const uint32_t LBH_NONTAKEN_WEIGHT
static constexpr BranchProbability ZeroUntakenProb(ZH_NONTAKEN_WEIGHT, ZH_TAKEN_WEIGHT+ZH_NONTAKEN_WEIGHT)
static const uint32_t FPH_ORD_WEIGHT
This is the probability for an ordered floating point comparison.
static const uint32_t FPH_UNO_WEIGHT
This is the probability for an unordered floating point comparison, it means one or two of the operan...
static cl::opt< std::string > PrintBranchProbFuncName("print-bpi-func-name", cl::Hidden, cl::desc("The option to specify the name of the function " "whose branch probability info is printed."))
static constexpr BranchProbability FPOrdTakenProb(FPH_ORD_WEIGHT, FPH_ORD_WEIGHT+FPH_UNO_WEIGHT)
static cl::opt< bool > PrintBranchProb("print-bpi", cl::init(false), cl::Hidden, cl::desc("Print the branch probability info."))
static constexpr BranchProbability FPOrdUntakenProb(FPH_UNO_WEIGHT, FPH_ORD_WEIGHT+FPH_UNO_WEIGHT)
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
This header defines various interfaces for pass management in LLVM.
#define INITIALIZE_PASS_DEPENDENCY(depName)
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
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.
const SmallVectorImpl< MachineOperand > & Cond
This builds on the llvm/ADT/GraphTraits.h file to find the strongly connected components (SCCs) of a ...
std::pair< BasicBlock *, BasicBlock * > Edge
This file defines the SmallVector class.
This templated class represents "all analyses that operate over <aparticular IR unit>" (e....
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Represent the analysis usage information of a pass.
AnalysisUsage & addRequired()
void setPreservesAll()
Set by analyses that do not transform their input at all.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
size_t size() const
Get the array size.
bool empty() const
Check if the array is empty.
LLVM Basic Block Representation.
unsigned getNumber() const
const Function * getParent() const
Return the enclosing method, or null if none.
LLVM_ABI const CallInst * getTerminatingDeoptimizeCall() const
Returns the call instruction calling @llvm.experimental.deoptimize prior to the terminating return in...
LLVM_ABI const DataLayout & getDataLayout() const
Get the data layout of the module this basic block belongs to.
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 BranchProbabilityInfo.
LLVM_ABI BranchProbabilityInfo run(Function &F, FunctionAnalysisManager &AM)
Run the analysis pass over a function and produce BPI.
Legacy analysis pass which computes BranchProbabilityInfo.
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
BranchProbabilityInfoWrapperPass()
bool runOnFunction(Function &F) override
runOnFunction - Virtual method overriden by subclasses to do the per-function processing of the pass.
void print(raw_ostream &OS, const Module *M=nullptr) const override
print - Print out the internal state of the pass.
Analysis providing branch probability information.
LLVM_ABI void eraseBlock(const BasicBlock *BB)
Forget analysis results for the given basic block.
LLVM_ABI bool invalidate(Function &, const PreservedAnalyses &PA, FunctionAnalysisManager::Invalidator &)
LLVM_ABI BranchProbability getEdgeProbability(const BasicBlock *Src, unsigned IndexInSuccessors) const
Get an edge's probability, relative to other out-edges of the Src.
LLVM_ABI void calculate(const Function &F, const LoopInfo &LI, const TargetLibraryInfo *TLI, DominatorTree *DT, PostDominatorTree *PDT)
LLVM_ABI void setEdgeProbability(const BasicBlock *Src, ArrayRef< BranchProbability > Probs)
Set the raw probabilities for all edges from the given block.
LLVM_ABI bool isEdgeHot(const BasicBlock *Src, const BasicBlock *Dst) const
Test if an edge is hot relative to other out-edges of the Src.
LLVM_ABI void swapSuccEdgesProbabilities(const BasicBlock *Src)
Swap outgoing edges probabilities for Src with branch terminator.
LLVM_ABI void print(raw_ostream &OS) const
LLVM_ABI raw_ostream & printEdgeProbability(raw_ostream &OS, const BasicBlock *Src, const BasicBlock *Dst) const
Print an edge's probability.
LLVM_ABI void copyEdgeProbabilities(BasicBlock *Src, BasicBlock *Dst)
Copy outgoing edge probabilities from Src to Dst.
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
static constexpr BranchProbability getOne()
static uint32_t getDenominator()
static constexpr BranchProbability getUnknown()
static constexpr BranchProbability getZero()
uint32_t getNumerator() const
static constexpr BranchProbability getRaw(uint32_t N)
Represents analyses that only rely on functions' control flow.
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation or the function signa...
@ ICMP_SLT
signed less than
@ ICMP_SGT
signed greater than
bool isTrueWhenEqual() const
This is just a convenience.
Predicate getPredicate() const
Return the predicate for this instruction.
Value * getCondition() const
BasicBlock * getSuccessor(unsigned i) const
bool isMinusOne() const
This function will return true iff every bit in this constant is set to true.
bool isOne() const
This is just a convenience method to make client code smaller for a common case.
bool isZero() const
This is just a convenience method to make client code smaller for a common code.
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Analysis pass which computes a DominatorTree.
DomTreeNodeBase< NodeT > * getNode(const NodeT *BB) const
getNode - return the (Post)DominatorTree node for the specified basic block.
Legacy analysis pass which computes a DominatorTree.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
static bool isEquality(Predicate Pred)
static bool isEquality(Predicate P)
Return true if this predicate is either EQ or NE.
LLVM_ABI unsigned getNumSuccessors() const LLVM_READONLY
Return the number of successors that this instruction has.
Analysis pass that exposes the LoopInfo for a function.
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
The legacy pass manager's analysis pass to compute loop information.
A Module instance is used to store all the information related to an LLVM module.
Represent a mutable reference to an array (0 or more elements consecutively in memory),...
AnalysisType & getAnalysis() const
getAnalysis<AnalysisType>() - This function is used by subclasses to get to the analysis information ...
Analysis pass which computes a PostDominatorTree.
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 all()
Construct a special preserved set that preserves all passes.
PreservedAnalysisChecker getChecker() const
Build a checker for this PreservedAnalyses and the specified analysis type.
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
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
void push_back(const T &Elt)
Analysis pass providing the TargetLibraryInfo.
Provides information about what library functions are available for the current target.
bool getLibFunc(StringRef funcName, LibFunc &F) const
Searches for a particular function name.
bool isPointerTy() const
True if this is an instance of PointerType.
Value * getOperand(unsigned i) const
Type * getType() const
All values are typed, get the type of this value.
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
This class implements an extremely fast bulk output stream that can only output to a stream.
@ BasicBlock
Various leaf nodes.
BlockType
Used as immediate MachineOperands for block signatures.
initializer< Ty > init(const Ty &Val)
NodeAddr< FuncNode * > Func
friend class Instruction
Iterator for Instructions in a `BasicBlock.
This is an optimization pass for GlobalISel generic memory operations.
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
auto pred_end(const MachineBasicBlock *BB)
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
auto successors(const MachineBasicBlock *BB)
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
scc_iterator< T > scc_begin(const T &G)
Construct the begin iterator for a deduced graph type T.
LLVM_ABI Constant * ConstantFoldCompareInstOperands(unsigned Predicate, Constant *LHS, Constant *RHS, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr, const Instruction *I=nullptr)
Attempt to constant fold a compare instruction (icmp/fcmp) with the specified operands.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
constexpr T divideNearest(U Numerator, V Denominator)
Returns (Numerator / Denominator) rounded by round-half-up.
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
auto reverse(ContainerTy &&C)
LLVM_ABI MDNode * getValidBranchWeightMDNode(const Instruction &I)
Get the valid branch weights metadata node.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
auto succ_size(const MachineBasicBlock *BB)
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
auto post_order(const T &G)
Post-order traversal of a graph.
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...
LLVM_ABI Constant * ConstantFoldBinaryOpOperands(unsigned Opcode, Constant *LHS, Constant *RHS, const DataLayout &DL)
Attempt to constant fold a binary operation with the specified operands.
MutableArrayRef(T &OneElt) -> MutableArrayRef< T >
RNSuccIterator< NodeRef, BlockT, RegionT > succ_begin(NodeRef Node)
iterator_range(Container &&) -> iterator_range< llvm::detail::IterOfRange< Container > >
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
auto count(R &&Range, const E &Element)
Wrapper function around std::count to count the number of times an element Element occurs in the give...
ArrayRef(const T &OneElt) -> ArrayRef< T >
LLVM_ABI bool extractBranchWeights(const MDNode *ProfileData, SmallVectorImpl< uint32_t > &Weights)
Extract branch weights from MD_prof metadata.
auto pred_begin(const MachineBasicBlock *BB)
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
auto predecessors(const MachineBasicBlock *BB)
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
A special type used by analysis passes to provide an address that identifies that particular analysis...