14#ifndef LLVM_ANALYSIS_BLOCKFREQUENCYINFOIMPL_H
15#define LLVM_ANALYSIS_BLOCKFREQUENCYINFOIMPL_H
52#define DEBUG_TYPE "block-freq"
61class BranchProbabilityInfo;
65class MachineBasicBlock;
66class MachineBranchProbabilityInfo;
99 return BlockMass(std::numeric_limits<uint64_t>::max());
104 bool isFull()
const {
return Mass == std::numeric_limits<uint64_t>::max(); }
114 Mass = Sum < Mass ? std::numeric_limits<uint64_t>::max() : Sum;
124 Mass = Diff > Mass ? 0 : Diff;
129 Mass =
P.scale(Mass);
207 return std::numeric_limits<uint32_t>::max() - 1;
238 template <
class It1,
class It2>
243 Nodes.insert(
Nodes.end(), FirstOther, LastOther);
295 return Loop->Parent->Parent;
313 return L ? L->getHeader() :
Node;
320 while (L->Parent && L->Parent->IsPackaged)
335 return Loop->Parent->Mass;
466 std::list<LoopData>::iterator Insert);
521 Scaled64 getFloatingBlockFreq(
const BlockNode &
Node)
const;
524 std::optional<uint64_t> getBlockProfileCount(
const Function &
F,
525 const BlockNode &
Node)
const;
526 std::optional<uint64_t> getProfileCountFromFreq(
const Function &
F,
528 bool isIrrLoopHeader(
const BlockNode &
Node);
538namespace bfi_detail {
564 assert(BB &&
"Unexpected nullptr");
565 auto MachineName =
"BB" +
Twine(BB->getNumber());
566 if (BB->getBasicBlock())
567 return (MachineName +
"[" + BB->getName() +
"]").str();
568 return MachineName.str();
572 assert(BB &&
"Unexpected nullptr");
603 using iterator = std::deque<const IrrNode *>::const_iterator;
624 template <
class BlockEdgesAdder>
626 BlockEdgesAdder addBlockEdges) :
BFI(
BFI) {
630 template <
class BlockEdgesAdder>
631 void initialize(
const BFIBase::LoopData *OuterLoop,
632 BlockEdgesAdder addBlockEdges);
642 template <
class BlockEdgesAdder>
644 BlockEdgesAdder addBlockEdges);
646 const BFIBase::LoopData *OuterLoop);
649template <
class BlockEdgesAdder>
651 BlockEdgesAdder addBlockEdges) {
654 for (
auto N : OuterLoop->
Nodes)
658 for (
uint32_t Index = 0; Index <
BFI.Working.size(); ++Index)
659 addEdges(Index, OuterLoop, addBlockEdges);
664template <
class BlockEdgesAdder>
667 BlockEdgesAdder addBlockEdges) {
672 const auto &Working =
BFI.Working[
Node.Index];
674 if (Working.isAPackage())
675 for (
const auto &
I : Working.Loop->Exits)
678 addBlockEdges(*
this, Irr, OuterLoop);
839 using BranchProbabilityInfoT =
846 const BranchProbabilityInfoT *BPI =
nullptr;
847 const LoopInfoT *LI =
nullptr;
848 const FunctionT *F =
nullptr;
851 std::vector<const BlockT *> RPOT;
854 unsigned BlockNumberEpoch;
856 BlockNode getNode(
const BlockT *BB)
const {
857 assert(BlockNumberEpoch ==
860 return BlockNumber < Nodes.size() ? Nodes[BlockNumber] :
BlockNode();
865 return RPOT[
Node.Index];
871 void initializeRPOT();
880 void initializeLoops();
908 bool tryToComputeMassInFunction();
922 void computeIrreducibleMass(
LoopData *OuterLoop,
923 std::list<LoopData>::iterator Insert);
934 void computeMassInLoops();
942 void computeMassInFunction();
944 std::string getBlockName(
const BlockNode &
Node)
const override {
958 bool needIterativeInference()
const;
961 void applyIterativeInference();
963 using ProbMatrixType = std::vector<std::vector<std::pair<size_t, Scaled64>>>;
966 void iterativeInference(
const ProbMatrixType &ProbMatrix,
967 std::vector<Scaled64> &Freq)
const;
971 void findReachableBlocks(std::vector<const BlockT *> &Blocks)
const;
975 void initTransitionProbabilities(
976 const std::vector<const BlockT *> &Blocks,
978 ProbMatrixType &ProbMatrix)
const;
983 Scaled64 discrepancy(
const ProbMatrixType &ProbMatrix,
984 const std::vector<Scaled64> &Freq)
const;
992 void calculate(
const FunctionT &F,
const BranchProbabilityInfoT &BPI,
993 const LoopInfoT &LI);
1002 const BlockT *BB)
const {
1021 const BranchProbabilityInfoT &
getBPI()
const {
return *BPI; }
1043 const BranchProbabilityInfoT &BPI,
1044 const LoopInfoT &LI) {
1057 <<
"\n================="
1058 << std::string(F.getName().size(),
'=') <<
"\n");
1064 computeMassInLoops();
1065 computeMassInFunction();
1069 if (needIterativeInference())
1070 applyIterativeInference();
1077 for (
const BlockT &BB : F)
1090 if (Nodes.size() <= BlockNumber)
1093 if (!
Node.isValid()) {
1098 Freqs.emplace_back();
1103template <
class BT>
void BlockFrequencyInfoImpl<BT>::initializeRPOT() {
1104 const BlockT *Entry = &
F->front();
1105 RPOT.reserve(
F->size());
1107 RPOT.emplace_back(BB);
1108 std::reverse(RPOT.begin(), RPOT.end());
1110 assert(RPOT.size() - 1 <= BlockNode::getMaxIndex() &&
1111 "More nodes in function than Block Frequency Info supports");
1117 BlockNode
Node = BlockNode(Idx);
1122 Working.reserve(RPOT.size());
1123 for (
size_t Index = 0; Index < RPOT.size(); ++Index)
1124 Working.emplace_back(Index);
1125 Freqs.resize(RPOT.size());
1128template <
class BT>
void BlockFrequencyInfoImpl<BT>::initializeLoops() {
1134 std::deque<std::pair<const LoopT *, LoopData *>> Q;
1135 for (
const LoopT *L : *LI)
1136 Q.emplace_back(L,
nullptr);
1137 while (!Q.empty()) {
1138 const LoopT *
Loop = Q.front().first;
1139 LoopData *Parent = Q.front().second;
1143 assert(Header.isValid());
1145 Loops.emplace_back(Parent, Header);
1146 Working[Header.Index].Loop = &
Loops.back();
1149 for (
const LoopT *L : *
Loop)
1150 Q.emplace_back(L, &
Loops.back());
1155 for (
size_t Index = 0;
Index < RPOT.size(); ++
Index) {
1157 if (Working[Index].isLoopHeader()) {
1158 LoopData *ContainingLoop = Working[
Index].getContainingLoop();
1160 ContainingLoop->Nodes.push_back(Index);
1164 const LoopT *
Loop = LI->getLoopFor(RPOT[Index]);
1170 assert(Header.isValid());
1171 const auto &HeaderData = Working[Header.Index];
1172 assert(HeaderData.isLoopHeader());
1174 Working[
Index].Loop = HeaderData.Loop;
1175 HeaderData.Loop->Nodes.push_back(Index);
1181template <
class BT>
void BlockFrequencyInfoImpl<BT>::computeMassInLoops() {
1183 for (
auto L =
Loops.rbegin(),
E =
Loops.rend(); L !=
E; ++L) {
1184 if (computeMassInLoop(*L))
1186 auto Next = std::next(L);
1187 computeIrreducibleMass(&*L,
L.base());
1188 L = std::prev(
Next);
1189 if (computeMassInLoop(*L))
1196bool BlockFrequencyInfoImpl<BT>::computeMassInLoop(LoopData &
Loop) {
1200 if (
Loop.isIrreducible()) {
1203 unsigned NumHeadersWithWeight = 0;
1204 std::optional<uint64_t> MinHeaderWeight;
1207 for (uint32_t
H = 0;
H <
Loop.NumHeaders; ++
H) {
1208 auto &HeaderNode =
Loop.Nodes[
H];
1209 const BlockT *
Block = getBlock(HeaderNode);
1210 IsIrrLoopHeader.set(
Loop.Nodes[
H].Index);
1211 std::optional<uint64_t> HeaderWeight =
Block->getIrrLoopHeaderWeight();
1212 if (!HeaderWeight) {
1215 HeadersWithoutWeight.insert(
H);
1219 <<
" has irr loop header weight " << *HeaderWeight
1221 NumHeadersWithWeight++;
1222 uint64_t HeaderWeightValue = *HeaderWeight;
1223 if (!MinHeaderWeight || HeaderWeightValue < MinHeaderWeight)
1224 MinHeaderWeight = HeaderWeightValue;
1225 if (HeaderWeightValue) {
1226 Dist.addLocal(HeaderNode, HeaderWeightValue);
1235 if (!MinHeaderWeight)
1236 MinHeaderWeight = 1;
1237 for (uint32_t
H : HeadersWithoutWeight) {
1238 auto &HeaderNode =
Loop.Nodes[
H];
1239 assert(!getBlock(HeaderNode)->getIrrLoopHeaderWeight() &&
1240 "Shouldn't have a weight metadata");
1241 uint64_t MinWeight = *MinHeaderWeight;
1245 Dist.addLocal(HeaderNode, MinWeight);
1247 distributeIrrLoopHeaderMass(Dist);
1248 for (
const BlockNode &M :
Loop.Nodes)
1249 if (!propagateMassToSuccessors(&
Loop, M))
1251 if (NumHeadersWithWeight == 0)
1253 adjustLoopHeaderMass(
Loop);
1255 Working[
Loop.
getHeader().Index].getMass() = BlockMass::getFull();
1258 for (
const BlockNode &M :
Loop.members())
1259 if (!propagateMassToSuccessors(&
Loop, M))
1264 computeLoopScale(
Loop);
1270bool BlockFrequencyInfoImpl<BT>::tryToComputeMassInFunction() {
1273 assert(!Working.empty() &&
"no blocks in function");
1274 assert(!Working[0].isLoopHeader() &&
"entry block is a loop header");
1276 Working[0].getMass() = BlockMass::getFull();
1277 for (
size_t i = 0, n = RPOT.size(); i != n; ++i) {
1279 if (Working[i].isPackaged())
1282 if (!propagateMassToSuccessors(
nullptr, BlockNode(i)))
1288template <
class BT>
void BlockFrequencyInfoImpl<BT>::computeMassInFunction() {
1289 if (tryToComputeMassInFunction())
1291 computeIrreducibleMass(
nullptr,
Loops.begin());
1292 if (tryToComputeMassInFunction())
1298bool BlockFrequencyInfoImpl<BT>::needIterativeInference()
const {
1301 if (!
F->getFunction().hasProfileData())
1305 for (
auto L =
Loops.rbegin(),
E =
Loops.rend(); L !=
E; ++L) {
1306 if (
L->isIrreducible())
1312template <
class BT>
void BlockFrequencyInfoImpl<BT>::applyIterativeInference() {
1317 std::vector<const BlockT *> ReachableBlocks;
1318 findReachableBlocks(ReachableBlocks);
1319 if (ReachableBlocks.empty())
1326 auto Freq = std::vector<Scaled64>(ReachableBlocks.size());
1328 for (
size_t I = 0;
I < ReachableBlocks.size();
I++) {
1329 const BlockT *BB = ReachableBlocks[
I];
1331 Freq[
I] = getFloatingBlockFreq(BB);
1334 assert(!SumFreq.isZero() &&
"empty initial block frequencies");
1336 LLVM_DEBUG(
dbgs() <<
"Applying iterative inference for " <<
F->getName()
1337 <<
" with " << ReachableBlocks.size() <<
" blocks\n");
1340 for (
auto &
Value : Freq) {
1346 ProbMatrixType ProbMatrix;
1347 initTransitionProbabilities(ReachableBlocks, BlockIndex, ProbMatrix);
1350 iterativeInference(ProbMatrix, Freq);
1353 for (
const BlockT &BB : *
F) {
1355 if (!
Node.isValid())
1357 if (
auto It = BlockIndex.find(&BB); It != BlockIndex.end())
1358 Freqs[
Node.Index].Scaled = Freq[It->second];
1360 Freqs[
Node.Index].Scaled = Scaled64::getZero();
1365void BlockFrequencyInfoImpl<BT>::iterativeInference(
1366 const ProbMatrixType &ProbMatrix, std::vector<Scaled64> &Freq)
const {
1368 "incorrectly specified precision");
1370 const auto Precision =
1376 << discrepancy(ProbMatrix, Freq).
toString() <<
"\n");
1380 auto Successors = std::vector<std::vector<size_t>>(Freq.size());
1381 for (
size_t I = 0;
I < Freq.size();
I++) {
1382 for (
const auto &Jump : ProbMatrix[
I]) {
1383 Successors[Jump.first].push_back(
I);
1391 auto IsActive =
BitVector(Freq.size(),
false);
1392 std::queue<size_t> ActiveSet;
1393 for (
size_t I = 0;
I < Freq.size();
I++) {
1402 while (It++ < MaxIterations && !ActiveSet.empty()) {
1403 size_t I = ActiveSet.front();
1405 IsActive[
I] =
false;
1411 Scaled64 OneMinusSelfProb = Scaled64::getOne();
1412 for (
const auto &Jump : ProbMatrix[
I]) {
1413 if (Jump.first ==
I) {
1414 OneMinusSelfProb -= Jump.second;
1416 NewFreq += Freq[Jump.first] * Jump.second;
1419 if (OneMinusSelfProb != Scaled64::getOne())
1420 NewFreq /= OneMinusSelfProb;
1424 auto Change = Freq[
I] >= NewFreq ? Freq[
I] - NewFreq : NewFreq - Freq[
I];
1425 if (Change > Precision) {
1428 for (
size_t Succ : Successors[
I]) {
1429 if (!IsActive[Succ]) {
1430 ActiveSet.push(Succ);
1431 IsActive[Succ] =
true;
1440 LLVM_DEBUG(
dbgs() <<
" Completed " << It <<
" inference iterations"
1441 <<
format(
" (%0.0f per block)",
double(It) / Freq.size())
1445 << discrepancy(ProbMatrix, Freq).
toString() <<
"\n");
1450void BlockFrequencyInfoImpl<BT>::findReachableBlocks(
1451 std::vector<const BlockT *> &Blocks)
const {
1454 std::queue<const BlockT *>
Queue;
1456 const BlockT *
Entry = &
F->front();
1458 Reachable.insert(Entry);
1459 while (!
Queue.empty()) {
1460 const BlockT *SrcBB =
Queue.front();
1463 auto EP = BPI->getEdgeProbability(SrcBB, It.index());
1466 if (Reachable.insert(It.value()).second)
1467 Queue.push(It.value());
1474 for (
const BlockT &BB : *
F) {
1477 if (!HasSucc && Reachable.count(&BB)) {
1479 InverseReachable.insert(&BB);
1482 while (!
Queue.empty()) {
1483 const BlockT *SrcBB =
Queue.front();
1486 auto EP = BPI->getEdgeProbability(DstBB, SrcBB);
1489 if (InverseReachable.insert(DstBB).second)
1495 Blocks.reserve(
F->size());
1496 for (
const BlockT &BB : *
F) {
1497 if (Reachable.count(&BB) && InverseReachable.count(&BB)) {
1498 Blocks.push_back(&BB);
1504void BlockFrequencyInfoImpl<BT>::initTransitionProbabilities(
1505 const std::vector<const BlockT *> &Blocks,
1507 ProbMatrixType &ProbMatrix)
const {
1508 const size_t NumBlocks = Blocks.size();
1509 auto Succs = std::vector<std::vector<std::pair<size_t, Scaled64>>>(NumBlocks);
1510 auto SumProb = std::vector<Scaled64>(NumBlocks);
1513 for (
size_t Src = 0; Src < NumBlocks; Src++) {
1514 const BlockT *BB = Blocks[Src];
1517 const BlockT *
SI = It.value();
1519 auto BlockIndexIt = BlockIndex.find(
SI);
1520 if (BlockIndexIt == BlockIndex.end())
1523 if (!UniqueSuccs.insert(
SI).second)
1526 auto EP = BPI->getEdgeProbability(BB, It.index());
1531 Scaled64::getFraction(EP.getNumerator(), EP.getDenominator());
1532 size_t Dst = BlockIndexIt->second;
1533 Succs[Src].push_back(std::make_pair(Dst, EdgeProb));
1534 SumProb[Src] += EdgeProb;
1539 ProbMatrix = ProbMatrixType(NumBlocks);
1540 for (
size_t Src = 0; Src < NumBlocks; Src++) {
1542 if (Succs[Src].
empty())
1545 assert(!SumProb[Src].
isZero() &&
"Zero sum probability of non-exit block");
1546 for (
auto &Jump : Succs[Src]) {
1547 size_t Dst = Jump.first;
1548 Scaled64 Prob = Jump.second;
1549 ProbMatrix[Dst].push_back(std::make_pair(Src, Prob / SumProb[Src]));
1554 size_t EntryIdx = BlockIndex.find(&
F->front())->second;
1555 for (
size_t Src = 0; Src < NumBlocks; Src++) {
1556 if (Succs[Src].
empty()) {
1557 ProbMatrix[EntryIdx].push_back(std::make_pair(Src, Scaled64::getOne()));
1565 const ProbMatrixType &ProbMatrix,
const std::vector<Scaled64> &Freq)
const {
1566 assert(Freq[0] > 0 &&
"Incorrectly computed frequency of the entry block");
1567 Scaled64 Discrepancy;
1568 for (
size_t I = 0;
I < ProbMatrix.size();
I++) {
1570 for (
const auto &Jump : ProbMatrix[
I]) {
1571 Sum += Freq[Jump.first] * Jump.second;
1573 Discrepancy += Freq[
I] >= Sum ? Freq[
I] - Sum : Sum - Freq[
I];
1576 return Discrepancy / Freq[0];
1581void BlockFrequencyInfoImpl<BT>::computeIrreducibleMass(
1582 LoopData *OuterLoop, std::list<LoopData>::iterator Insert) {
1584 if (OuterLoop)
dbgs()
1585 <<
"loop: " << getLoopName(*OuterLoop) <<
"\n";
1586 else dbgs() <<
"function\n");
1590 auto addBlockEdges = [&](IrreducibleGraph &
G, IrreducibleGraph::IrrNode &Irr,
1591 const LoopData *OuterLoop) {
1592 const BlockT *BB = RPOT[Irr.Node.Index];
1594 G.addEdge(Irr,
getNode(Succ), OuterLoop);
1596 IrreducibleGraph
G(*
this, OuterLoop, addBlockEdges);
1598 for (
auto &L : analyzeIrreducible(
G, OuterLoop, Insert))
1599 computeMassInLoop(L);
1603 updateLoopWithIrreducible(*OuterLoop);
1613BlockFrequencyInfoImpl<BT>::propagateMassToSuccessors(LoopData *OuterLoop,
1614 const BlockNode &
Node) {
1618 if (
auto *Loop = Working[
Node.Index].getPackagedLoop()) {
1619 assert(Loop != OuterLoop &&
"Cannot propagate mass in a packaged loop");
1620 if (!addLoopSuccessorsToDist(OuterLoop, *Loop, Dist))
1624 const BlockT *BB = getBlock(Node);
1627 Dist, OuterLoop, Node,
getNode(It.value()),
1635 distributeMass(Node, OuterLoop, Dist);
1643 OS <<
"block-frequency-info: " << F->getName() <<
"\n";
1644 for (
const BlockT &BB : *F) {
1648 if (std::optional<uint64_t> ProfileCount =
1650 F->getFunction(), getNode(&BB)))
1651 OS <<
", count = " << *ProfileCount;
1652 if (std::optional<uint64_t> IrrLoopHeaderWeight =
1653 BB.getIrrLoopHeaderWeight())
1654 OS <<
", irr_loop_header_weight = " << *IrrLoopHeaderWeight;
1671 for (
const auto &BB : *F)
1674 size_t MinSize = std::min(Nodes.size(),
Other.Nodes.size());
1675 for (
size_t i = 0; i < MinSize; ++i) {
1681 <<
" existence mismatch.\n";
1682 }
else if (Nodes[i].
isValid()) {
1683 const auto &Freq =
Freqs[Nodes[i].Index];
1684 const auto &OtherFreq =
Other.Freqs[
Other.Nodes[i].Index];
1685 if (Freq.Integer != OtherFreq.Integer) {
1688 <<
" " << Freq.Integer <<
" vs " << OtherFreq.Integer <<
"\n";
1693 for (
size_t i = MinSize; i < Nodes.size(); ++i) {
1697 <<
" existence mismatch.\n";
1700 for (
size_t i = MinSize; i <
Other.Nodes.size(); ++i) {
1701 if (
Other.Nodes[i].isValid()) {
1704 <<
" existence mismatch.\n";
1711 dbgs() <<
"Other\n";
1714 assert(Match &&
"BFI mismatch");
1722template <
class BlockFrequencyInfoT,
class BranchProbabilityInfoT>
1735 return G->getFunction()->getName();
1739 unsigned HotPercentThreshold = 0) {
1741 if (!HotPercentThreshold)
1751 std::max(
MaxFrequency, Graph->getBlockFreq(
N).getFrequency());
1767 GVDAGType GType,
int layout_order = -1) {
1771 if (layout_order != -1)
1772 OS <<
Node->getName() <<
"[" << layout_order <<
"] : ";
1774 OS <<
Node->getName() <<
" : ";
1780 OS << Graph->getBlockFreq(
Node).getFrequency();
1783 auto Count = Graph->getBlockProfileCount(
Node);
1792 "never reach this point.");
1798 const BlockFrequencyInfoT *BFI,
1799 const BranchProbabilityInfoT *BPI,
1800 unsigned HotPercentThreshold = 0) {
1813 if (HotPercentThreshold) {
1818 if (EFreq >= HotFreq)
1819 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 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.
This file defines the DenseSet and SmallDenseSet classes.
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.
bool addLoopSuccessorsToDist(const LoopData *OuterLoop, LoopData &Loop, Distribution &Dist)
Add all edges out of a packaged loop 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 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 updateLoopWithIrreducible(LoopData &OuterLoop)
Update a loop after packaging irreducible SCCs inside of it.
void clear()
Clear all memory.
BlockFrequency getBlockFreq(const BlockNode &Node) const
void distributeIrrLoopHeaderMass(Distribution &Dist)
iterator_range< std::list< LoopData >::iterator > analyzeIrreducible(const bfi_detail::IrreducibleGraph &G, LoopData *OuterLoop, std::list< LoopData >::iterator Insert)
Analyze irreducible SCCs.
bool addToDist(Distribution &Dist, const LoopData *OuterLoop, const BlockNode &Pred, const BlockNode &Succ, uint64_t Weight)
Add an edge to the distribution.
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.
std::vector< FrequencyData > Freqs
Data about each block. This is used downstream.
void adjustLoopHeaderMass(LoopData &Loop)
Adjust the mass of all headers in an irreducible loop.
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 calculate(const FunctionT &F, const BranchProbabilityInfoT &BPI, const LoopInfoT &LI)
void setBlockFreq(const BlockT *BB, BlockFrequency Freq)
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
Implements a dense probed hash-table based set.
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.
typename SuperClass::const_iterator const_iterator
ptrdiff_t difference_type
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.
void reserve(size_t Size)
Grow the DenseSet so that it can contain at least NumEntries items before resizing again.
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.
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< unsigned > IterativeBFIMaxIterationsPerBlock
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.
LLVM_ABI llvm::cl::opt< bool > CheckBFIUnknownBlockQueries
RNSuccIterator< NodeRef, BlockT, RegionT > succ_begin(NodeRef Node)
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)
iterator_range< typename GraphTraits< GraphType >::ChildIteratorType > children(const typename GraphTraits< GraphType >::NodeRef &G)
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Next
LLVM_ABI Printable printBlockFreq(const BlockFrequencyInfo &BFI, BlockFrequency Freq)
Print the block frequency Freq relative to the current functions entry frequency.
LLVM_ABI llvm::cl::opt< double > IterativeBFIPrecision
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.
LoopData(LoopData *Parent, It1 FirstHeader, It1 LastHeader, It2 FirstOther, It2 LastOther)
ExitMap Exits
Successor edges (and weights).
uint32_t NumHeaders
Number of headers.
bool IsPackaged
Whether this has been packaged.
LoopData(LoopData *Parent, const BlockNode &Header)
SmallVector< BlockNode, 4 > NodeList
NodeList::const_iterator members_end() const
NodeList::const_iterator members_begin() const
bool isIrreducible() const
BlockNode getHeader() const
SmallVector< BlockMass, 1 > HeaderMassList
NodeList Nodes
Header and the members of the loop.
HeaderMassList BackedgeMass
Mass returned to each loop header.
HeaderMassList::difference_type getHeaderIndex(const BlockNode &B)
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()
Get the appropriate mass for a node.
WorkingData(const BlockNode &Node)
bool isAPackage() const
Has Loop been packaged up?
bool isLoopHeader() const
bool isDoubleLoopHeader() const
LoopData * Loop
The loop this block is inside.
LoopData * getContainingLoop() const
LoopData * getPackagedLoop() const
BlockNode getResolvedNode() const
Resolve a node to its representative.
bool isADoublePackage() const
Has Loop been packaged up twice?
DefaultDOTGraphTraits(bool simple=false)
static nodes_iterator nodes_end(const BlockFrequencyInfo *G)
static nodes_iterator nodes_begin(const BlockFrequencyInfo *G)
typename BlockFrequencyInfoT *::UnknownGraphTypeError NodeRef
iterator pred_end() const
IrrNode(const BlockNode &Node)
iterator pred_begin() const
iterator succ_begin() const
std::deque< const IrrNode * >::const_iterator iterator
std::deque< const IrrNode * > Edges
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)
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
MachineLoopInfo LoopInfoT
MachineFunction FunctionT
MachineBranchProbabilityInfo BranchProbabilityInfoT