19 #include "llvm/Config/llvm-config.h" 41 #define DEBUG_TYPE "block-freq" 49 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 61 for (
int Digits = 0; Digits < 16; ++Digits)
94 struct DitheringDistributer {
98 DitheringDistributer(Distribution &Dist,
const BlockMass &Mass);
105 DitheringDistributer::DitheringDistributer(Distribution &Dist,
108 RemWeight = Dist.Total;
113 assert(Weight &&
"invalid weight");
114 assert(Weight <= RemWeight);
124 Weight::DistType
Type) {
125 assert(Amount &&
"invalid weight of 0");
126 uint64_t NewTotal = Total + Amount;
129 bool IsOverflow = NewTotal < Total;
130 assert(!(DidOverflow && IsOverflow) &&
"unexpected repeated overflow");
131 DidOverflow |= IsOverflow;
137 Weights.push_back(Weight(Type, Node, Amount));
141 assert(OtherW.TargetNode.isValid());
146 assert(W.Type == OtherW.Type);
147 assert(W.TargetNode == OtherW.TargetNode);
148 assert(OtherW.Amount &&
"Expected non-zero weight");
149 if (W.Amount > W.Amount + OtherW.Amount)
153 W.Amount += OtherW.Amount;
158 llvm::sort(Weights, [](
const Weight &L,
const Weight &R) {
159 return L.TargetNode < R.TargetNode;
163 WeightList::iterator
O = Weights.begin();
164 for (WeightList::const_iterator
I = O, L = O,
E = Weights.end();
I !=
E;
169 for (++L; L !=
E && I->TargetNode == L->TargetNode; ++L)
174 Weights.erase(O, Weights.end());
182 for (
const Weight &
W : Weights)
186 if (Weights.size() == Combined.size())
191 Weights.reserve(Combined.size());
192 for (
const auto &
I : Combined)
193 Weights.push_back(
I.second);
198 if (Weights.size() > 128) {
211 return (N >> Shift) + (UINT64_C(1) & N >> (Shift - 1));
214 void Distribution::normalize() {
220 if (Weights.size() > 1)
224 if (Weights.size() == 1) {
226 Weights.front().Amount = 1;
237 else if (Total > UINT32_MAX)
244 assert(Total == std::accumulate(Weights.begin(), Weights.end(), UINT64_C(0),
245 [](uint64_t Sum,
const Weight &
W) {
246 return Sum +
W.Amount;
248 "Expected total to be correct");
257 for (Weight &
W : Weights) {
260 assert(
W.TargetNode.isValid());
262 assert(
W.Amount <= UINT32_MAX);
267 assert(Total <= UINT32_MAX);
273 std::vector<FrequencyData>().
swap(Freqs);
274 IsIrrLoopHeader.clear();
275 std::vector<WorkingData>().
swap(Working);
283 std::vector<FrequencyData> SavedFreqs(std::move(BFI.
Freqs));
286 BFI.
Freqs = std::move(SavedFreqs);
298 auto isLoopHeader = [&OuterLoop](
const BlockNode &Node) {
299 return OuterLoop && OuterLoop->
isHeader(Node);
305 auto debugSuccessor = [&](
const char *
Type) {
307 <<
" [" <<
Type <<
"] weight = " << Weight;
308 if (!isLoopHeader(Resolved))
310 if (Resolved != Succ)
314 (void)debugSuccessor;
317 if (isLoopHeader(Resolved)) {
323 if (Working[Resolved.
Index].getContainingLoop() != OuterLoop) {
325 Dist.
addExit(Resolved, Weight);
329 if (Resolved < Pred) {
330 if (!isLoopHeader(Pred)) {
333 "unhandled irreducible control flow");
344 "unhandled irreducible control flow");
355 for (
const auto &
I : Loop.
Exits)
356 if (!addToDist(Dist, OuterLoop, Loop.
getHeader(),
I.first,
367 LLVM_DEBUG(
dbgs() <<
"compute-loop-scale: " << getLoopName(Loop) <<
"\n");
378 const Scaled64 InfiniteLoopScale(1, 12);
384 TotalBackedgeMass += Mass;
396 <<
" - scale = " << Loop.
Scale <<
"\n");
401 LLVM_DEBUG(
dbgs() <<
"packaging-loop: " << getLoopName(Loop) <<
"\n");
405 if (
auto *Loop = Working[M.
Index].getPackagedLoop())
414 const DitheringDistributer &
D,
const BlockNode &
T,
416 dbgs() <<
" => assign " << M <<
" (" << D.RemMass <<
")";
418 dbgs() <<
" [" << Desc <<
"]";
432 DitheringDistributer
D(Dist, Mass);
434 for (
const Weight &
W : Dist.
Weights) {
437 if (W.
Type == Weight::Local) {
444 assert(OuterLoop &&
"backedge or exit outside of loop");
447 if (W.
Type == Weight::Backedge) {
468 const unsigned MaxBits = 64;
469 const unsigned SpreadBits = (Max / Min).lg();
471 if (SpreadBits <= MaxBits - 3) {
480 ScalingFactor =
Scaled64(1, MaxBits) / Max;
484 LLVM_DEBUG(
dbgs() <<
"float-to-int: min = " << Min <<
", max = " << Max
485 <<
", factor = " << ScalingFactor <<
"\n");
490 << BFI.
Freqs[
Index].Scaled <<
", scaled = " << Scaled
491 <<
", int = " << BFI.
Freqs[
Index].Integer <<
"\n");
501 <<
": mass = " << Loop.Mass <<
", scale = " << Loop.Scale
503 Loop.Scale *= Loop.Mass.toScaled();
504 Loop.IsPackaged =
false;
505 LLVM_DEBUG(
dbgs() <<
" => combined-scale = " << Loop.Scale <<
"\n");
510 for (
const BlockNode &
N : Loop.Nodes) {
511 const auto &Working = BFI.
Working[N.Index];
512 Scaled64 &
F = Working.isAPackage() ? Working.getPackagedLoop()->Scale
513 : BFI.
Freqs[N.Index].Scaled;
533 auto Min = Scaled64::getLargest();
534 auto Max = Scaled64::getZero();
555 return Freqs[Node.
Index].Integer;
561 bool AllowSynthetic)
const {
562 return getProfileCountFromFreq(F, getBlockFreq(Node).getFrequency(),
569 bool AllowSynthetic)
const {
574 APInt BlockCount(128, EntryCount.getCount());
575 APInt BlockFreq(128, Freq);
576 APInt EntryFreq(128, getEntryFreq());
577 BlockCount *= BlockFreq;
580 BlockCount = (BlockCount + EntryFreq.
lshr(1)).udiv(EntryFreq);
581 return BlockCount.getLimitedValue();
588 return IsIrrLoopHeader.test(Node.
Index);
594 return Scaled64::getZero();
595 return Freqs[Node.
Index].Scaled;
601 assert(Node.
Index < Freqs.size() &&
"Expected legal index");
602 Freqs[Node.
Index].Integer = Freq;
618 return OS << getFloatingBlockFreq(Node);
627 return OS << Block / Entry;
633 for (
auto N : OuterLoop.
Nodes)
641 if (!
BFI.Working[
Index].isPackaged())
647 for (
auto &
I : Nodes)
653 if (OuterLoop && OuterLoop->
isHeader(Succ))
659 Irr.
Edges.push_back(&SuccIrr);
660 SuccIrr.
Edges.push_front(&Irr);
685 const std::vector<const IrreducibleGraph::IrrNode *> &SCC,
691 for (
const auto *
I : SCC)
695 auto &Irr = *
I->first;
696 for (
const auto *
P :
make_range(Irr.pred_begin(), Irr.pred_end())) {
702 Headers.push_back(Irr.Node);
708 assert(Headers.size() >= 2 &&
709 "Expected irreducible CFG; -loop-info is likely invalid");
710 if (Headers.size() == InSCC.
size()) {
717 for (
const auto &
I : InSCC) {
722 auto &Irr = *
I.first;
723 for (
const auto *
P :
make_range(Irr.pred_begin(), Irr.pred_end())) {
725 if (
P->Node < Irr.Node)
734 Headers.push_back(Irr.Node);
739 if (Headers.back() == Irr.Node)
744 Others.push_back(Irr.Node);
753 LoopData *OuterLoop, std::list<LoopData>::iterator Insert,
754 const std::vector<const IrreducibleGraph::IrrNode *> &SCC) {
762 auto Loop = BFI.
Loops.emplace(Insert, OuterLoop, Headers.begin(),
763 Headers.end(), Others.begin(), Others.end());
766 for (
const auto &
N :
Loop->Nodes)
767 if (BFI.
Working[
N.Index].isLoopHeader())
776 std::list<LoopData>::iterator Insert) {
777 assert((OuterLoop ==
nullptr) == (Insert ==
Loops.begin()));
778 auto Prev = OuterLoop ? std::prev(Insert) :
Loops.end();
800 if (!Working[
I->Index].isPackaged())
819 auto &HeaderNode = Loop.
Nodes[
H];
824 if (BackedgeMass.getMass() > 0)
825 Dist.
addLocal(HeaderNode, BackedgeMass.getMass());
830 DitheringDistributer
D(Dist, LoopMass);
833 <<
" to headers using above weights\n");
834 for (
const Weight &
W : Dist.
Weights) {
836 assert(W.
Type == Weight::Local &&
"all weights should be local");
844 DitheringDistributer
D(Dist, LoopMass);
845 for (
const Weight &
W : Dist.
Weights) {
847 assert(W.
Type == Weight::Local &&
"all weights should be local");
static void combineWeights(WeightList &Weights)
void addNodesInLoop(const BFIBase::LoopData &OuterLoop)
This builds on the llvm/ADT/GraphTraits.h file to find the strongly connected components (SCCs) of a ...
static uint64_t shiftRightAndRound(uint64_t N, int Shift)
static void combineWeightsBySorting(WeightList &Weights)
bool IsPackaged
Whether this has been packaged.
This class represents lattice values for constants.
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds...
static char getHexDigit(int N)
void push_back(const T &Elt)
GraphT::IrrNode::iterator ChildIteratorType
iterator succ_begin() const
Stats about a block itself.
raw_ostream & printBlockFreq(raw_ostream &OS, const BlockNode &Node) const
uint64_t getFrequency() const
Returns the frequency as a fixpoint number scaled by the entry frequency.
raw_ostream & print(raw_ostream &OS) const
static NodeRef getEntryNode(const GraphT &G)
void addLocal(const BlockNode &Node, uint64_t Amount)
static ChildIteratorType child_end(NodeRef N)
static void cleanup(BlockFrequencyInfoImplBase &BFI)
Clear all memory not needed downstream.
static void combineWeight(Weight &W, const Weight &OtherW)
BlockNode getHeader() const
uint32_t NumHeaders
Number of headers.
void setBlockFreq(const BlockNode &Node, uint64_t Freq)
SparseBitVector IsIrrLoopHeader
Whether each block is an irreducible loop header.
iterator succ_end() const
Scaled64 getFloatingBlockFreq(const BlockNode &Node) const
virtual std::string getBlockName(const BlockNode &Node) const
static int Lookup(ArrayRef< TableEntry > Table, unsigned Opcode)
void addEdge(IrrNode &Irr, const BlockNode &Succ, const BFIBase::LoopData *OuterLoop)
void adjustLoopHeaderMass(LoopData &Loop)
Adjust the mass of all headers in an irreducible loop.
static void debugAssign(const BlockFrequencyInfoImplBase &BFI, const DitheringDistributer &D, const BlockNode &T, const BlockMass &M, const char *Desc)
This file implements a class to represent arbitrary precision integral constant values and operations...
scc_iterator< T > scc_begin(const T &G)
Construct the begin iterator for a deduced graph type T.
static void findIrreducibleHeaders(const BlockFrequencyInfoImplBase &BFI, const IrreducibleGraph &G, const std::vector< const IrreducibleGraph::IrrNode *> &SCC, LoopData::NodeList &Headers, LoopData::NodeList &Others)
Find extra irreducible headers.
Graph of irreducible control flow.
ScaledNumber< uint64_t > Scaled64
void computeLoopScale(LoopData &Loop)
Compute the loop scale for a loop.
void addBackedge(const BlockNode &Node, uint64_t Amount)
std::string getLoopName(const LoopData &Loop) const
bool isHeader(const BlockNode &Node) const
static ChildIteratorType child_begin(NodeRef N)
bool addToDist(Distribution &Dist, const LoopData *OuterLoop, const BlockNode &Pred, const BlockNode &Succ, uint64_t Weight)
Add an edge to the distribution.
bool isIrrLoopHeader(const BlockNode &Node)
Optional< uint64_t > getBlockProfileCount(const Function &F, const BlockNode &Node, bool AllowSynthetic=false) const
static void createIrreducibleLoop(BlockFrequencyInfoImplBase &BFI, const IrreducibleGraph &G, LoopData *OuterLoop, std::list< LoopData >::iterator Insert, const std::vector< const IrreducibleGraph::IrrNode *> &SCC)
std::vector< FrequencyData > Freqs
Data about each block. This is used downstream.
bool isIrreducible() const
static void convertFloatingToInteger(BlockFrequencyInfoImplBase &BFI, const Scaled64 &Min, const Scaled64 &Max)
iterator_range< std::list< LoopData >::iterator > analyzeIrreducible(const bfi_detail::IrreducibleGraph &G, LoopData *OuterLoop, std::list< LoopData >::iterator Insert)
Analyze irreducible SCCs.
The instances of the Type class are immutable: once they are created, they are never changed...
ScaledNumber inverse() const
void distributeIrrLoopHeaderMass(Distribution &Dist)
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
Distribution of unscaled probability weight.
ProfileCount getEntryCount(bool AllowSynthetic=false) const
Get the entry count for this function.
IntT toInt() const
Convert to the given integer type.
static void unwrapLoop(BlockFrequencyInfoImplBase &BFI, LoopData &Loop)
Unwrap a loop package.
void clear()
Clear all memory.
void addNodesInFunction()
uint64_t NextPowerOf2(uint64_t A)
Returns the next power of two (in 64-bits) that is strictly greater than A.
iterator erase(const_iterator CI)
unsigned countLeadingZeros(T Val, ZeroBehavior ZB=ZB_Width)
Count number of 0's from the most significant bit to the least stopping at the first 1...
void addExit(const BlockNode &Node, uint64_t Amount)
APInt lshr(unsigned shiftAmt) const
Logical right-shift function.
void sort(IteratorTy Start, IteratorTy End)
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
Align max(MaybeAlign Lhs, Align Rhs)
ExitMap Exits
Successor edges (and weights).
static uint64_t add(uint64_t LeftOp, uint64_t RightOp)
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static BlockMass getEmpty()
SmallVector< Weight, 4 > WeightList
ScaledNumber< uint64_t > toScaled() const
Convert to scaled number.
std::list< LoopData > Loops
Indexed information about loops.
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
A range adaptor for a pair of iterators.
std::string getBlockName(const BlockT *BB)
Get the name of a MachineBasicBlock.
Class for arbitrary precision integers.
void updateLoopWithIrreducible(LoopData &OuterLoop)
Update a loop after packaging irreducible SCCs inside of it.
SmallVector< NodeAddr< NodeBase * >, 4 > NodeList
Unscaled probability weight.
static void combineWeightsByHashing(WeightList &Weights)
Represents a single loop in the control flow graph.
void packageLoop(LoopData &Loop)
Package up a loop.
static BlockMass getFull()
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
void distributeMass(const BlockNode &Source, LoopData *OuterLoop, Distribution &Dist)
Distribute mass according to a distribution.
NodeList Nodes
Header and the members of the loop.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
ScaledNumber< uint64_t > Scaled64
std::vector< WorkingData > Working
Loop data: see initializeLoops().
HeaderMassList BackedgeMass
Mass returned to each loop header.
This class implements an extremely fast bulk output stream that can only output to a stream...
BlockFrequency getBlockFreq(const BlockNode &Node) const
std::deque< const IrrNode * > Edges
Optional< uint64_t > getProfileCountFromFreq(const Function &F, uint64_t Freq, bool AllowSynthetic=false) const
Base class for BlockFrequencyInfoImpl.
bool addLoopSuccessorsToDist(const LoopData *OuterLoop, LoopData &Loop, Distribution &Dist)
Add all edges out of a packaged loop to the distribution.
void unwrapLoops()
Unwrap loops.
HeaderMassList::difference_type getHeaderIndex(const BlockNode &B)
Representative of a block.
void finalizeMetrics()
Finalize frequency metrics.
WeightList Weights
Individual successor weights.