14#ifndef LLVM_ANALYSIS_BLOCKFREQUENCYINFOIMPL_H
15#define LLVM_ANALYSIS_BLOCKFREQUENCYINFOIMPL_H
54#define DEBUG_TYPE "block-freq"
66class BranchProbabilityInfo;
69class MachineBasicBlock;
70class MachineBranchProbabilityInfo;
71class MachineCycleInfo;
102 return BlockMass(std::numeric_limits<uint64_t>::max());
107 bool isFull()
const {
return Mass == std::numeric_limits<uint64_t>::max(); }
117 Mass = Sum < Mass ? std::numeric_limits<uint64_t>::max() : Sum;
127 Mass = Diff > Mass ? 0 : Diff;
132 Mass =
P.scale(Mass);
210 return std::numeric_limits<uint32_t>::max() - 1;
278 while (L && L->isHeader(
Node))
298 return L ? L->getHeader() :
Node;
309 while (L->Parent && L->Parent->IsPackaged)
449 std::list<LoopData>::iterator Insert);
484 Scaled64 getFloatingBlockFreq(
const BlockNode &
Node)
const;
487 std::optional<uint64_t> getBlockProfileCount(
const Function &
F,
488 const BlockNode &
Node)
const;
489 std::optional<uint64_t> getProfileCountFromFreq(
const Function &
F,
491 bool isIrrLoopHeader(
const BlockNode &
Node);
501namespace bfi_detail {
525 assert(BB &&
"Unexpected nullptr");
526 auto MachineName =
"BB" +
Twine(BB->getNumber());
527 if (BB->getBasicBlock())
528 return (MachineName +
"[" + BB->getName() +
"]").str();
529 return MachineName.str();
533 assert(BB &&
"Unexpected nullptr");
585 template <
class BlockEdgesAdder>
587 BlockEdgesAdder addBlockEdges) :
BFI(
BFI) {
591 template <
class BlockEdgesAdder>
592 void initialize(
const BFIBase::LoopData *OuterLoop,
593 BlockEdgesAdder addBlockEdges);
600 "mass distributed before the region was packaged");
604 template <
class BlockEdgesAdder>
606 BlockEdgesAdder addBlockEdges);
608 const BFIBase::LoopData *OuterLoop);
611template <
class BlockEdgesAdder>
613 BlockEdgesAdder addBlockEdges) {
616 for (
auto N : OuterLoop->
Nodes)
620 for (
uint32_t Index = 0; Index <
BFI.Working.size(); ++Index)
621 addEdges(Index, OuterLoop, addBlockEdges);
626template <
class BlockEdgesAdder>
629 BlockEdgesAdder addBlockEdges) {
634 const auto &Working =
BFI.Working[
Node.Index];
636 if (Working.isAPackage())
637 for (
const auto &
I : Working.Loop->Exits)
640 addBlockEdges(*
this, Irr, OuterLoop);
763 using BranchProbabilityInfoT =
769 const BranchProbabilityInfoT *BPI =
nullptr;
770 const CycleInfoT *CI =
nullptr;
771 const FunctionT *F =
nullptr;
774 std::vector<const BlockT *> RPOT;
777 unsigned BlockNumberEpoch;
779 BlockNode getNode(
const BlockT *BB)
const {
780 assert(BlockNumberEpoch ==
783 return BlockNumber < Nodes.size() ? Nodes[BlockNumber] :
BlockNode();
788 return RPOT[
Node.Index];
792 void initializeRPOT();
801 void initializeLoops();
835 void computeIrreducibleMass(
LoopData *OuterLoop,
836 std::list<LoopData>::iterator Insert);
843 void computeMassInLoops();
852 void computeMassInFunction();
854 std::string getBlockName(
const BlockNode &
Node)
const override {
868 bool needIterativeInference()
const;
871 void applyIterativeInference();
873 using ProbMatrixType = std::vector<std::vector<std::pair<size_t, Scaled64>>>;
876 void iterativeInference(
const ProbMatrixType &ProbMatrix,
878 std::vector<Scaled64> &Freq)
const;
882 void findReachableBlocks(
BitVector &Blocks)
const;
886 void initTransitionProbabilities(
const BitVector &Blocks,
887 ProbMatrixType &ProbMatrix)
const;
892 Scaled64 discrepancy(
const ProbMatrixType &ProbMatrix,
893 const std::vector<Scaled64> &Freq)
const;
901 void calculate(
const FunctionT &F,
const BranchProbabilityInfoT &BPI,
902 const CycleInfoT &CI);
911 const BlockT *BB)
const {
930 const BranchProbabilityInfoT &
getBPI()
const {
return *BPI; }
952 const BranchProbabilityInfoT &BPI,
953 const CycleInfoT &CI) {
967 <<
"\n================="
968 << std::string(F.getName().size(),
'=') <<
"\n");
979 computeMassInLoops();
980 computeMassInFunction();
985 if (needIterativeInference())
986 applyIterativeInference();
993 for (
const BlockT &BB : F)
1006 if (Nodes.size() <= BlockNumber)
1009 if (!
Node.isValid()) {
1014 Freqs.emplace_back();
1019template <
class BT>
void BlockFrequencyInfoImpl<BT>::initializeRPOT() {
1020 const BlockT *Entry = &
F->front();
1021 RPOT.reserve(
F->size());
1023 RPOT.emplace_back(BB);
1024 std::reverse(RPOT.begin(), RPOT.end());
1026 assert(RPOT.size() - 1 <= BlockNode::getMaxIndex() &&
1027 "More nodes in function than Block Frequency Info supports");
1033 BlockNode
Node = BlockNode(Idx);
1038 Working.reserve(RPOT.size());
1039 for (
size_t Index = 0; Index < RPOT.size(); ++Index)
1040 Working.emplace_back(Index);
1041 Freqs.resize(RPOT.size());
1044template <
class BT>
void BlockFrequencyInfoImpl<BT>::initializeLoops() {
1055 if (!CI->isReducible(
C))
1057 for (
CycleRef A = CI->getParentCycle(
C);
A;
A = CI->getParentCycle(
A))
1058 if (!CI->isReducible(
A) && CI->isEntry(
A, CI->getHeader(
C)))
1064 std::deque<std::pair<CycleRef, LoopData *>> Q;
1065 for (
CycleRef C : CI->toplevel_cycles())
1066 Q.emplace_back(
C,
nullptr);
1069 while (!Q.empty()) {
1071 LoopData *Parent = Q.front().second;
1074 if (hasLoop(Cycle)) {
1075 BlockNode Header =
getNode(CI->getHeader(Cycle));
1076 Loops.emplace_back(Parent, Header);
1078 Working[Header.Index].Loop = &
Loops.back();
1080 Parent = &
Loops.back();
1081 }
else if (!CI->isReducible(Cycle)) {
1085 Parent->ContainsIrreducible =
true;
1087 TopContainsIrreducible =
true;
1091 Q.emplace_back(
C, Parent);
1096 for (
size_t Index = 0;
Index < RPOT.size(); ++
Index) {
1098 if (Working[Index].isLoopHeader()) {
1099 LoopData *ContainingLoop = Working[
Index].getContainingLoop();
1101 ContainingLoop->Nodes.push_back(Index);
1105 CycleRef Cycle = CI->getCycle(RPOT[Index]);
1106 while (Cycle && !hasLoop(Cycle))
1107 Cycle = CI->getParentCycle(Cycle);
1112 BlockNode Header =
getNode(CI->getHeader(Cycle));
1113 assert(Header.isValid());
1114 const auto &HeaderData = Working[Header.Index];
1115 assert(HeaderData.isLoopHeader());
1117 Working[
Index].Loop = HeaderData.Loop;
1118 HeaderData.Loop->Nodes.push_back(Index);
1124template <
class BT>
void BlockFrequencyInfoImpl<BT>::computeMassInLoops() {
1127 for (
auto L =
Loops.end(),
B =
Loops.begin(); L !=
B;) {
1129 if (
L->ContainsIrreducible)
1130 computeIrreducibleMass(&*L, std::next(L));
1131 computeMassInLoop(*L);
1136void BlockFrequencyInfoImpl<BT>::computeMassInLoop(LoopData &
Loop) {
1139 if (
Loop.isIrreducible()) {
1141 solveIrreducibleMass(
Loop);
1143 Working[
Loop.
getHeader().Index].getMass() = BlockMass::getFull();
1145 for (
const BlockNode &M :
Loop.members())
1146 propagateMassToSuccessors(&
Loop, M);
1149 computeLoopScale(
Loop);
1154void BlockFrequencyInfoImpl<BT>::getSuccWeights(
1155 const BlockNode &Node,
1158 if (
auto *L = Working[
Node.Index].getPackagedLoop()) {
1159 for (
const auto &
E :
L->Exits)
1160 Out.emplace_back(Working[
E.first.Index].getResolvedNode(),
1161 E.second.getMass());
1164 const BlockT *BB = getBlock(Node);
1166 BlockNode Succ =
getNode(It.value());
1167 if (!Succ.isValid())
1171 Out.emplace_back(Working[Succ.Index].getResolvedNode(),
1172 std::max<uint64_t>(1, W));
1181void BlockFrequencyInfoImpl<BT>::solveIrreducibleMass(LoopData &
Loop) {
1182 const size_t N =
Loop.Nodes.size();
1187 for (
size_t I = 0;
I !=
N; ++
I) {
1188 getSuccWeights(
Loop.Nodes[
I], Succs);
1192 Scaled64 InvTotal = Scaled64::getInverse(
Total);
1193 for (
const auto &S : Succs) {
1194 Scaled64 Pr = Scaled64(S.second, 0) * InvTotal;
1198 if (It !=
Loop.Nodes.
end() && *It == S.first)
1201 Ex.emplace_back(
I, S.first, Pr);
1211 for (
size_t I = 0;
I !=
N; ++
I)
1212 if (
auto W = getBlock(
Loop.Nodes[
I])->getIrrLoopHeaderWeight()) {
1213 F[
I] = Scaled64(*W, 0);
1218 Pinned.assign(
N,
false);
1219 F.assign(
N, Scaled64::getInverse(
N));
1224 const unsigned MaxIterations = 16;
1227 for (
unsigned It = 0; It != MaxIterations; ++It) {
1228 G.assign(
N, Scaled64::getZero());
1229 for (
auto [
I, J, Pr] :
P)
1232 for (
size_t I = 0;
I !=
N; ++
I) {
1239 Scaled64 Ratio =
New / Sum;
1241 for (
size_t I = 0;
I !=
N; ++
I) {
1242 Scaled64 Was = Ratio *
F[
I];
1243 Delta +=
G[
I] >= Was ?
G[
I] - Was : Was -
G[
I];
1247 if (Delta < New * Scaled64(1, -32))
1255 for (
size_t I = 0;
I !=
N; ++
I)
1258 BlockMass TotalExit;
1259 for (
auto [
I, Succ, Pr] : Ex) {
1261 Loop.Exits.emplace_back(Succ, BlockMass(M));
1262 TotalExit += BlockMass(M);
1264 Loop.BackedgeMass = BlockMass::getFull() - TotalExit;
1267template <
class BT>
void BlockFrequencyInfoImpl<BT>::computeMassInFunction() {
1268 if (TopContainsIrreducible)
1269 computeIrreducibleMass(
nullptr,
Loops.begin());
1272 assert(!Working.empty() &&
"no blocks in function");
1273 assert(!Working[0].isLoopHeader() &&
"entry block is a loop header");
1275 Working[0].getMass() = BlockMass::getFull();
1276 for (
size_t i = 0, n = RPOT.size(); i != n; ++i) {
1278 if (Working[i].isPackaged())
1281 propagateMassToSuccessors(
nullptr, BlockNode(i));
1286bool BlockFrequencyInfoImpl<BT>::needIterativeInference()
const {
1289 if (!
F->getFunction().hasProfileData())
1293 for (
auto L =
Loops.rbegin(),
E =
Loops.rend(); L !=
E; ++L) {
1294 if (
L->isIrreducible())
1300template <
class BT>
void BlockFrequencyInfoImpl<BT>::applyIterativeInference() {
1306 findReachableBlocks(ReachableBlocks);
1307 if (ReachableBlocks.none())
1311 auto Freq = std::vector<Scaled64>(ReachableBlocks.size());
1313 for (
const BlockT &BB : *
F) {
1315 if (!ReachableBlocks[
Number])
1317 Freq[
Number] = getFloatingBlockFreq(&BB);
1320 assert(!SumFreq.isZero() &&
"empty initial block frequencies");
1322 LLVM_DEBUG(
dbgs() <<
"Applying iterative inference for " <<
F->getName()
1323 <<
" with " << ReachableBlocks.count() <<
" blocks\n");
1326 for (
auto &
Value : Freq) {
1332 ProbMatrixType ProbMatrix;
1333 initTransitionProbabilities(ReachableBlocks, ProbMatrix);
1336 iterativeInference(ProbMatrix, ReachableBlocks, Freq);
1339 for (
const BlockT &BB : *
F) {
1341 if (!
Node.isValid())
1344 Freqs[
Node.Index].Scaled =
1345 ReachableBlocks[
Number] ? Freq[
Number] : Scaled64::getZero();
1350void BlockFrequencyInfoImpl<BT>::iterativeInference(
1351 const ProbMatrixType &ProbMatrix,
const BitVector &Blocks,
1352 std::vector<Scaled64> &Freq)
const {
1355 assert(0.0 < PrecisionValue && PrecisionValue < 1.0 &&
1356 "incorrectly specified precision");
1358 const auto Precision =
1359 Scaled64::getInverse(
static_cast<uint64_t>(1.0 / PrecisionValue));
1360 const size_t MaxIterations =
1365 << discrepancy(ProbMatrix, Freq).
toString() <<
"\n");
1369 auto Successors = std::vector<std::vector<size_t>>(Freq.size());
1370 for (
size_t I = 0;
I < Freq.size();
I++) {
1371 for (
const auto &Jump : ProbMatrix[
I]) {
1372 Successors[Jump.first].push_back(
I);
1380 auto IsActive =
BitVector(Freq.size(),
false);
1381 std::queue<size_t> ActiveSet;
1382 for (
unsigned I : Blocks.set_bits()) {
1391 while (It++ < MaxIterations && !ActiveSet.empty()) {
1392 size_t I = ActiveSet.front();
1394 IsActive[
I] =
false;
1400 Scaled64 OneMinusSelfProb = Scaled64::getOne();
1401 for (
const auto &Jump : ProbMatrix[
I]) {
1402 if (Jump.first ==
I) {
1403 OneMinusSelfProb -= Jump.second;
1405 NewFreq += Freq[Jump.first] * Jump.second;
1408 if (OneMinusSelfProb != Scaled64::getOne())
1409 NewFreq /= OneMinusSelfProb;
1413 auto Change = Freq[
I] >= NewFreq ? Freq[
I] - NewFreq : NewFreq - Freq[
I];
1414 if (Change > Precision) {
1417 for (
size_t Succ : Successors[
I]) {
1418 if (!IsActive[Succ]) {
1419 ActiveSet.push(Succ);
1420 IsActive[Succ] =
true;
1429 LLVM_DEBUG(
dbgs() <<
" Completed " << It <<
" inference iterations"
1430 <<
format(
" (%0.0f per block)",
double(It) / Freq.size())
1434 << discrepancy(ProbMatrix, Freq).
toString() <<
"\n");
1439void BlockFrequencyInfoImpl<BT>::findReachableBlocks(
BitVector &Blocks)
const {
1441 auto number = [](
const BlockT *BB) {
1447 std::queue<const BlockT *>
Queue;
1449 const BlockT *
Entry = &
F->front();
1451 Reachable.set(
number(Entry));
1452 while (!
Queue.empty()) {
1453 const BlockT *SrcBB =
Queue.front();
1456 auto EP = BPI->getEdgeProbability(SrcBB, It.index());
1460 if (!Reachable.test(
Number)) {
1462 Queue.push(It.value());
1470 for (
const BlockT &BB : *
F) {
1473 if (!HasSucc && Reachable.test(
number(&BB))) {
1475 InverseReachable.set(
number(&BB));
1478 while (!
Queue.empty()) {
1479 const BlockT *SrcBB =
Queue.front();
1482 auto EP = BPI->getEdgeProbability(DstBB, SrcBB);
1486 if (!InverseReachable.test(
Number)) {
1487 InverseReachable.set(
Number);
1494 Reachable &= InverseReachable;
1495 Blocks = std::move(Reachable);
1499void BlockFrequencyInfoImpl<BT>::initTransitionProbabilities(
1500 const BitVector &Blocks, ProbMatrixType &ProbMatrix)
const {
1501 const size_t NumBlocks = Blocks.size();
1502 auto Succs = std::vector<std::vector<std::pair<size_t, Scaled64>>>(NumBlocks);
1503 auto SumProb = std::vector<Scaled64>(NumBlocks);
1506 for (
const BlockT &BB : *
F) {
1512 const BlockT *
SI = It.value();
1518 if (!UniqueSuccs.insert(
SI).second)
1521 auto EP = BPI->getEdgeProbability(&BB, It.index());
1526 Scaled64::getFraction(EP.getNumerator(), EP.getDenominator());
1527 Succs[Src].push_back(std::make_pair(Dst, EdgeProb));
1528 SumProb[Src] += EdgeProb;
1533 ProbMatrix = ProbMatrixType(NumBlocks);
1534 for (
size_t Src = 0; Src < NumBlocks; Src++) {
1536 if (Succs[Src].
empty())
1539 assert(!SumProb[Src].
isZero() &&
"Zero sum probability of non-exit block");
1540 for (
auto &Jump : Succs[Src]) {
1541 size_t Dst = Jump.first;
1542 Scaled64 Prob = Jump.second;
1543 ProbMatrix[Dst].push_back(std::make_pair(Src, Prob / SumProb[Src]));
1549 for (
size_t Src = 0; Src < NumBlocks; Src++) {
1550 if (Blocks[Src] && Succs[Src].
empty()) {
1551 ProbMatrix[EntryIdx].push_back(std::make_pair(Src, Scaled64::getOne()));
1559 const ProbMatrixType &ProbMatrix,
const std::vector<Scaled64> &Freq)
const {
1561 assert(Freq[EntryIdx] > 0 &&
1562 "Incorrectly computed frequency of the entry block");
1563 Scaled64 Discrepancy;
1564 for (
size_t I = 0;
I < ProbMatrix.size();
I++) {
1566 for (
const auto &Jump : ProbMatrix[
I]) {
1567 Sum += Freq[Jump.first] * Jump.second;
1569 Discrepancy += Freq[
I] >= Sum ? Freq[
I] - Sum : Sum - Freq[
I];
1572 return Discrepancy / Freq[EntryIdx];
1577void BlockFrequencyInfoImpl<BT>::computeIrreducibleMass(
1578 LoopData *OuterLoop, std::list<LoopData>::iterator Insert) {
1580 if (OuterLoop)
dbgs()
1581 <<
"loop: " << getLoopName(*OuterLoop) <<
"\n";
1582 else dbgs() <<
"function\n");
1586 auto addBlockEdges = [&](IrreducibleGraph &
G, IrreducibleGraph::IrrNode &Irr,
1587 const LoopData *OuterLoop) {
1588 const BlockT *BB = RPOT[Irr.Node.Index];
1590 G.addEdge(Irr,
getNode(Succ), OuterLoop);
1592 IrreducibleGraph
G(*
this, OuterLoop, addBlockEdges);
1594 for (
auto &L : analyzeIrreducible(
G, OuterLoop, Insert))
1595 computeMassInLoop(L);
1601 assert(OuterLoop->Exits.empty() &&
"unexpected exits before distribution");
1602 assert(OuterLoop->BackedgeMass.isEmpty() &&
1603 "unexpected backedge mass before distribution");
1604 auto O = OuterLoop->Nodes.begin() + 1;
1605 for (
auto I = O,
E = OuterLoop->Nodes.end();
I !=
E; ++
I)
1606 if (!Working[
I->Index].isPackaged())
1608 OuterLoop->Nodes.erase(O, OuterLoop->Nodes.end());
1617void BlockFrequencyInfoImpl<BT>::propagateMassToSuccessors(
1618 LoopData *OuterLoop,
const BlockNode &
Node) {
1622 if (
auto *
Loop = Working[
Node.Index].getPackagedLoop()) {
1623 assert(
Loop != OuterLoop &&
"Cannot propagate mass in a packaged loop");
1624 addLoopSuccessorsToDist(OuterLoop, *
Loop, Dist);
1626 const BlockT *BB = getBlock(Node);
1629 Dist, OuterLoop, Node,
getNode(It.value()),
1635 distributeMass(Node, OuterLoop, Dist);
1642 OS <<
"block-frequency-info: " << F->getName() <<
"\n";
1643 for (
const BlockT &BB : *F) {
1647 if (std::optional<uint64_t> ProfileCount =
1649 F->getFunction(), getNode(&BB)))
1650 OS <<
", count = " << *ProfileCount;
1651 if (std::optional<uint64_t> IrrLoopHeaderWeight =
1652 BB.getIrrLoopHeaderWeight())
1653 OS <<
", irr_loop_header_weight = " << *IrrLoopHeaderWeight;
1670 for (
const auto &BB : *F)
1673 size_t MinSize = std::min(Nodes.size(),
Other.Nodes.size());
1674 for (
size_t i = 0; i < MinSize; ++i) {
1680 <<
" existence mismatch.\n";
1681 }
else if (Nodes[i].
isValid()) {
1682 const auto &Freq =
Freqs[Nodes[i].Index];
1683 const auto &OtherFreq =
Other.Freqs[
Other.Nodes[i].Index];
1684 if (Freq.Integer != OtherFreq.Integer) {
1687 <<
" " << Freq.Integer <<
" vs " << OtherFreq.Integer <<
"\n";
1692 for (
size_t i = MinSize; i < Nodes.size(); ++i) {
1696 <<
" existence mismatch.\n";
1699 for (
size_t i = MinSize; i <
Other.Nodes.size(); ++i) {
1700 if (
Other.Nodes[i].isValid()) {
1703 <<
" existence mismatch.\n";
1710 dbgs() <<
"Other\n";
1713 assert(Match &&
"BFI mismatch");
1721template <
class BlockFrequencyInfoT,
class BranchProbabilityInfoT>
1734 return G->getFunction()->getName();
1738 unsigned HotPercentThreshold = 0) {
1740 if (!HotPercentThreshold)
1766 GVDAGType GType,
int layout_order = -1) {
1770 if (layout_order != -1)
1771 OS <<
Node->getName() <<
"[" << layout_order <<
"] : ";
1773 OS <<
Node->getName() <<
" : ";
1779 OS <<
Graph->getBlockFreq(
Node).getFrequency();
1791 "never reach this point.");
1797 const BlockFrequencyInfoT *BFI,
1798 const BranchProbabilityInfoT *BPI,
1799 unsigned HotPercentThreshold = 0) {
1812 if (HotPercentThreshold) {
1817 if (EFreq >= HotFreq)
1818 OS <<
",color=\"red\"";
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static msgpack::DocNode getNode(msgpack::DocNode DN, msgpack::Type Type, MCValue Val)
static void print(raw_ostream &Out, object::Archive::Kind Kind, T Val)
This file implements the BitVector class.
static constexpr std::size_t number(BlockVerifier::State S)
static uint64_t scale(uint64_t Num, uint32_t N, uint32_t D)
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file defines the DenseMap class.
Find all cycles in a control-flow graph, including irreducible loops.
This file defines the little GraphTraits<X> template class that should be specialized by classes that...
static bool isZero(Value *V, const DataLayout &DL, DominatorTree *DT, AssumptionCache *AC)
Branch Probability Basic Block static false std::string getBlockName(const MachineBasicBlock *BB)
Helper to print the name of a MBB.
This file builds on the ADT/GraphTraits.h file to build a generic graph post order iterator.
static bool isValid(const char C)
Returns true if C is a valid mangled character: <0-9a-zA-Z_>.
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
This file defines the SparseBitVector class.
LLVM Basic Block Representation.
Base class for BlockFrequencyInfoImpl.
std::vector< WorkingData > Working
Loop data: see initializeLoops().
std::optional< uint64_t > getProfileCountFromFreq(const Function &F, BlockFrequency Freq) const
virtual ~BlockFrequencyInfoImplBase()=default
Virtual destructor.
std::list< LoopData > Loops
Indexed information about loops.
void addToDist(Distribution &Dist, const LoopData *OuterLoop, const BlockNode &Pred, const BlockNode &Succ, uint64_t Weight)
Add an edge to the distribution.
std::optional< uint64_t > getBlockProfileCount(const Function &F, const BlockNode &Node) const
ScaledNumber< uint64_t > Scaled64
std::string getLoopName(const LoopData &Loop) const
bool TopContainsIrreducible
Has an irreducible SCC outside every loop.
bool isIrrLoopHeader(const BlockNode &Node)
void computeLoopScale(LoopData &Loop)
Compute the loop scale for a loop.
bfi_detail::BlockMass BlockMass
void packageLoop(LoopData &Loop)
Package up a loop.
virtual raw_ostream & print(raw_ostream &OS) const
void finalizeMetrics()
Finalize frequency metrics.
void setBlockFreq(const BlockNode &Node, BlockFrequency Freq)
BlockFrequency getEntryFreq() const
void clear()
Clear all memory.
bool CheckUnknownBlockQueries
-check-bfi-unknown-block-queries of the function's context.
BlockFrequency getBlockFreq(const BlockNode &Node) const
iterator_range< std::list< LoopData >::iterator > analyzeIrreducible(const bfi_detail::IrreducibleGraph &G, LoopData *OuterLoop, std::list< LoopData >::iterator Insert)
Analyze irreducible SCCs.
void unwrapLoops()
Unwrap loops.
Scaled64 getFloatingBlockFreq(const BlockNode &Node) const
void distributeMass(const BlockNode &Source, LoopData *OuterLoop, Distribution &Dist)
Distribute mass according to a distribution.
SparseBitVector IsIrrLoopHeader
Whether each block is an irreducible loop header.
void addLoopSuccessorsToDist(const LoopData *OuterLoop, LoopData &Loop, Distribution &Dist)
Add all edges out of a packaged loop to the distribution.
std::vector< FrequencyData > Freqs
Data about each block. This is used downstream.
bool isIrrLoopHeader(const BlockT *BB)
std::optional< uint64_t > getProfileCountFromFreq(const Function &F, BlockFrequency Freq) const
const BranchProbabilityInfoT & getBPI() const
const FunctionT * getFunction() const
void verifyMatch(BlockFrequencyInfoImpl< BT > &Other) const
std::optional< uint64_t > getBlockProfileCount(const Function &F, const BlockT *BB) const
Scaled64 getFloatingBlockFreq(const BlockT *BB) const
void setBlockFreq(const BlockT *BB, BlockFrequency Freq)
void calculate(const FunctionT &F, const BranchProbabilityInfoT &BPI, const CycleInfoT &CI)
BlockFrequencyInfoImpl()=default
raw_ostream & print(raw_ostream &OS) const override
Print the frequencies for the current function.
BlockFrequency getBlockFreq(const BlockT *BB) const
Analysis providing branch probability information.
static LLVM_ABI BranchProbability getBranchProbability(uint64_t Numerator, uint64_t Denominator)
static uint32_t getDenominator()
uint32_t getNumerator() const
Opaque handle to a cycle within a GenericCycleInfo that wraps the cycle's preorder index.
This is an important class for using LLVM in a threaded context.
BlockT * getHeader() const
Represents a single loop in the control flow graph.
Simple representation of a scaled number.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
typename SuperClass::const_iterator const_iterator
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
std::string str() const
Get the contents as an std::string.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
The instances of the Type class are immutable: once they are created, they are never changed.
LLVM Value Representation.
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
bool operator<(BlockMass X) const
bool operator>(BlockMass X) const
LLVM_ABI raw_ostream & print(raw_ostream &OS) const
bool operator==(BlockMass X) const
static BlockMass getEmpty()
LLVM_ABI void dump() const
BlockMass & operator-=(BlockMass X)
Subtract another mass.
bool operator<=(BlockMass X) const
BlockMass & operator*=(BranchProbability P)
static BlockMass getFull()
bool operator!=(BlockMass X) const
BlockMass & operator+=(BlockMass X)
Add another mass.
bool operator>=(BlockMass X) const
LLVM_ABI ScaledNumber< uint64_t > toScaled() const
Convert to scaled number.
A range adaptor for a pair of iterators.
This class implements an extremely fast bulk output stream that can only output to a stream.
A raw_ostream that writes to an std::string.
This provides a very simple, boring adaptor for a begin and end iterator into a range type.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
std::string getBlockName(const BlockT *BB)
Get the name of a MachineBasicBlock.
BlockMass operator*(BlockMass L, BranchProbability R)
BlockMass operator+(BlockMass L, BlockMass R)
raw_ostream & operator<<(raw_ostream &OS, BlockMass X)
BlockMass operator-(BlockMass L, BlockMass R)
NodeAddr< NodeBase * > Node
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI unsigned getIterativeBFIMaxIterationsPerBlock(const LLVMContext &C)
Return -iterative-bfi-max-iterations-per-block.
Printable print(const GCNRegPressure &RP, const GCNSubtarget *ST=nullptr, unsigned DynamicVGPRBlockSize=0)
uint32_t getWeightFromBranchProb(const BranchProbability Prob)
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
LLVM_ABI llvm::cl::opt< bool > UseIterativeBFIInference
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
auto post_order(const T &G)
Post-order traversal of a graph.
format_object< Ts... > format(const char *Fmt, const Ts &... Vals)
These are helper functions used to produce formatted output.
RNSuccIterator< NodeRef, BlockT, RegionT > succ_begin(NodeRef Node)
auto lower_bound(R &&Range, T &&Value)
Provide wrappers to std::lower_bound which take ranges instead of having to pass begin/end explicitly...
constexpr NextUseDistance max(NextUseDistance A, NextUseDistance B)
iterator_range< typename GraphTraits< Inverse< GraphType > >::ChildIteratorType > inverse_children(const typename GraphTraits< GraphType >::NodeRef &G)
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
std::string toString(const APInt &I, unsigned Radix, bool Signed, bool formatAsCLiteral=false, bool UpperCase=true, bool InsertSeparators=false)
auto make_second_range(ContainerTy &&c)
Given a container of pairs, return a range over the second elements.
auto sum_of(R &&Range, E Init=E{0})
Returns the sum of all values in Range with Init initial value.
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
iterator_range< typename GraphTraits< GraphType >::ChildIteratorType > children(const typename GraphTraits< GraphType >::NodeRef &G)
LLVM_ABI Printable printBlockFreq(const BlockFrequencyInfo &BFI, BlockFrequency Freq)
Print the block frequency Freq relative to the current functions entry frequency.
LLVM_ABI bool shouldCheckBFIUnknownBlockQueries(const LLVMContext &C)
Return -check-bfi-unknown-block-queries.
LLVM_ABI double getIterativeBFIPrecision(const LLVMContext &C)
Return -iterative-bfi-precision.
Implement std::hash so that hash_code can be used in STL containers.
GraphTraits< BlockFrequencyInfoT * > GTraits
std::string getNodeAttributes(NodeRef Node, const BlockFrequencyInfoT *Graph, unsigned HotPercentThreshold=0)
typename GTraits::nodes_iterator NodeIter
typename GTraits::NodeRef NodeRef
typename GTraits::ChildIteratorType EdgeIter
std::string getNodeLabel(NodeRef Node, const BlockFrequencyInfoT *Graph, GVDAGType GType, int layout_order=-1)
std::string getEdgeAttributes(NodeRef Node, EdgeIter EI, const BlockFrequencyInfoT *BFI, const BranchProbabilityInfoT *BPI, unsigned HotPercentThreshold=0)
BFIDOTGraphTraitsBase(bool isSimple=false)
static StringRef getGraphName(const BlockFrequencyInfoT *G)
Representative of a block.
bool operator==(const BlockNode &X) const
bool operator!=(const BlockNode &X) const
bool operator<(const BlockNode &X) const
bool operator>=(const BlockNode &X) const
BlockNode(IndexType Index)
static size_t getMaxIndex()
bool operator<=(const BlockNode &X) const
bool operator>(const BlockNode &X) const
Distribution of unscaled probability weight.
void addBackedge(const BlockNode &Node, uint64_t Amount)
SmallVector< Weight, 4 > WeightList
WeightList Weights
Individual successor weights.
uint64_t Total
Sum of all weights.
void addExit(const BlockNode &Node, uint64_t Amount)
bool DidOverflow
Whether Total did overflow.
void addLocal(const BlockNode &Node, uint64_t Amount)
Stats about a block itself.
bool isHeader(const BlockNode &Node) const
SmallVector< std::pair< BlockNode, BlockMass >, 4 > ExitMap
LoopData * Parent
The parent loop.
ExitMap Exits
Successor edges (and weights).
bool IsPackaged
Whether this has been packaged.
LoopData(LoopData *Parent, const BlockNode &Header)
SmallVector< BlockNode, 4 > NodeList
BlockMass BackedgeMass
Mass that circulates, not exits.
NodeList::const_iterator members_end() const
NodeList::const_iterator members_begin() const
bool isIrreducible() const
BlockNode getHeader() const
NodeList Nodes
Header and the members of the loop.
LoopData(LoopData *Parent, NodeList &&Members)
An irreducible SCC.
iterator_range< NodeList::const_iterator > members() const
Unscaled probability weight.
Weight(DistType Type, BlockNode TargetNode, uint64_t Amount)
bool isPackaged() const
Has ContainingLoop been packaged up?
BlockMass Mass
Mass distribution from the entry block.
BlockMass & getMass()
The mass slot for Node: its own, or that of the outermost packaged loop it heads.
WorkingData(const BlockNode &Node)
bool isAPackage() const
Has Loop been packaged up?
bool isLoopHeader() const
LoopData * Loop
The loop this block is inside.
LoopData * getContainingLoop() const
The innermost loop containing Node that Node does not head.
LoopData * getPackagedLoop() const
The outermost loop containing Node that is currently packaged, if any.
BlockNode getResolvedNode() const
Resolve a node to its representative.
DefaultDOTGraphTraits(bool simple=false)
static nodes_iterator nodes_end(const BlockFrequencyInfo *G)
static nodes_iterator nodes_begin(const BlockFrequencyInfo *G)
typename BlockFrequencyInfoT *::UnknownGraphTypeError NodeRef
IrrNode(const BlockNode &Node)
SmallVectorImpl< const IrrNode * >::const_iterator iterator
SmallVector< const IrrNode *, 4 > Succs
iterator succ_begin() const
iterator succ_end() const
Graph of irreducible control flow.
LLVM_ABI void addNodesInFunction()
IrreducibleGraph(BFIBase &BFI, const BFIBase::LoopData *OuterLoop, BlockEdgesAdder addBlockEdges)
Construct an explicit graph containing irreducible control flow.
LLVM_ABI void indexNodes()
LLVM_ABI void addEdge(IrrNode &Irr, const BlockNode &Succ, const BFIBase::LoopData *OuterLoop)
unsigned getIndex(const IrrNode *N) const
The position of N in Nodes, for indexing side tables.
BlockFrequencyInfoImplBase BFIBase
void addEdges(const BlockNode &Node, const BFIBase::LoopData *OuterLoop, BlockEdgesAdder addBlockEdges)
BFIBase::BlockNode BlockNode
std::vector< IrrNode > Nodes
SmallDenseMap< uint32_t, IrrNode *, 4 > Lookup
void initialize(const BFIBase::LoopData *OuterLoop, BlockEdgesAdder addBlockEdges)
void addNode(const BlockNode &Node)
LLVM_ABI void addNodesInLoop(const BFIBase::LoopData &OuterLoop)
BranchProbabilityInfo BranchProbabilityInfoT
MachineFunction FunctionT
MachineBranchProbabilityInfo BranchProbabilityInfoT
MachineCycleInfo CycleInfoT