21 using namespace llvm::bfi_detail;
23 #define DEBUG_TYPE "block-freq"
31 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
43 for (
int Digits = 0; Digits < 16; ++Digits)
76 struct DitheringDistributer {
80 DitheringDistributer(Distribution &Dist,
const BlockMass &Mass);
87 DitheringDistributer::DitheringDistributer(Distribution &Dist,
90 RemWeight = Dist.Total;
95 assert(Weight &&
"invalid weight");
96 assert(Weight <= RemWeight);
106 Weight::DistType
Type) {
107 assert(Amount &&
"invalid weight of 0");
108 uint64_t NewTotal = Total + Amount;
111 bool IsOverflow = NewTotal < Total;
112 assert(!(DidOverflow && IsOverflow) &&
"unexpected repeated overflow");
113 DidOverflow |= IsOverflow;
119 Weights.push_back(Weight(Type, Node, Amount));
123 assert(OtherW.TargetNode.isValid());
128 assert(W.Type == OtherW.Type);
129 assert(W.TargetNode == OtherW.TargetNode);
130 assert(OtherW.Amount &&
"Expected non-zero weight");
131 if (W.Amount > W.Amount + OtherW.Amount)
133 W.Amount = UINT64_MAX;
135 W.Amount += OtherW.Amount;
140 std::sort(Weights.begin(), Weights.end(),
142 const Weight &R) {
return L.TargetNode < R.TargetNode; });
145 WeightList::iterator O = Weights.begin();
146 for (WeightList::const_iterator
I = O, L = O,
E = Weights.end();
I !=
E;
151 for (++L; L !=
E && I->TargetNode == L->TargetNode; ++
L)
156 Weights.erase(O, Weights.end());
163 for (
const Weight &W : Weights)
167 if (Weights.size() == Combined.size())
172 Weights.reserve(Combined.size());
173 for (
const auto &
I : Combined)
174 Weights.push_back(
I.second);
179 if (Weights.size() > 128) {
192 return (N >> Shift) + (UINT64_C(1) & N >> (Shift - 1));
195 void Distribution::normalize() {
201 if (Weights.size() > 1)
205 if (Weights.size() == 1) {
207 Weights.front().Amount = 1;
218 else if (Total > UINT32_MAX)
225 assert(Total == std::accumulate(Weights.begin(), Weights.end(), UINT64_C(0),
226 [](uint64_t Sum,
const Weight &W) {
227 return Sum + W.Amount;
229 "Expected total to be correct");
238 for (
Weight &W : Weights) {
241 assert(W.TargetNode.isValid());
243 assert(W.Amount <= UINT32_MAX);
248 assert(Total <= UINT32_MAX);
254 std::vector<FrequencyData>().
swap(Freqs);
255 std::vector<WorkingData>().
swap(Working);
263 std::vector<FrequencyData> SavedFreqs(std::move(BFI.
Freqs));
265 BFI.
Freqs = std::move(SavedFreqs);
276 auto isLoopHeader = [&OuterLoop](
const BlockNode &Node) {
277 return OuterLoop && OuterLoop->
isHeader(Node);
283 auto debugSuccessor = [&](
const char *
Type) {
285 <<
" [" << Type <<
"] weight = " << Weight;
286 if (!isLoopHeader(Resolved))
288 if (Resolved != Succ)
292 (void)debugSuccessor;
295 if (isLoopHeader(Resolved)) {
296 DEBUG(debugSuccessor(
"backedge"));
301 if (Working[Resolved.
Index].getContainingLoop() != OuterLoop) {
302 DEBUG(debugSuccessor(
" exit "));
303 Dist.
addExit(Resolved, Weight);
307 if (Resolved < Pred) {
308 if (!isLoopHeader(Pred)) {
311 "unhandled irreducible control flow");
314 DEBUG(debugSuccessor(
"abort!!!"));
322 "unhandled irreducible control flow");
325 DEBUG(debugSuccessor(
" local "));
333 for (
const auto &
I : Loop.
Exits)
334 if (!addToDist(Dist, OuterLoop, Loop.
getHeader(),
I.first,
345 DEBUG(
dbgs() <<
"compute-loop-scale: " << getLoopName(Loop) <<
"\n");
356 const Scaled64 InfiniteLoopScale(1, 12);
362 TotalBackedgeMass += Mass;
372 <<
" - " << TotalBackedgeMass <<
")\n"
373 <<
" - scale = " << Loop.
Scale <<
"\n");
378 DEBUG(
dbgs() <<
"packaging-loop: " << getLoopName(Loop) <<
"\n");
382 if (
auto *Loop = Working[M.
Index].getPackagedLoop())
391 const DitheringDistributer &
D,
const BlockNode &
T,
393 dbgs() <<
" => assign " << M <<
" (" << D.RemMass <<
")";
395 dbgs() <<
" [" << Desc <<
"]";
406 DEBUG(
dbgs() <<
" => mass: " << Mass <<
"\n");
409 DitheringDistributer
D(Dist, Mass);
414 if (W.
Type == Weight::Local) {
421 assert(OuterLoop &&
"backedge or exit outside of loop");
424 if (W.
Type == Weight::Backedge) {
438 const Scaled64 &
Min,
const Scaled64 &Max) {
445 const unsigned MaxBits = 64;
446 const unsigned SpreadBits = (Max /
Min).lg();
447 Scaled64 ScalingFactor;
448 if (SpreadBits <= MaxBits - 3) {
451 ScalingFactor = Min.inverse();
457 ScalingFactor = Scaled64(1, MaxBits) / Max;
461 DEBUG(
dbgs() <<
"float-to-int: min = " << Min <<
", max = " << Max
462 <<
", factor = " << ScalingFactor <<
"\n");
463 for (
size_t Index = 0; Index < BFI.
Freqs.size(); ++Index) {
464 Scaled64 Scaled = BFI.
Freqs[Index].Scaled * ScalingFactor;
465 BFI.
Freqs[Index].Integer =
std::max(UINT64_C(1), Scaled.toInt<uint64_t>());
467 << BFI.
Freqs[Index].Scaled <<
", scaled = " << Scaled
468 <<
", int = " << BFI.
Freqs[Index].Integer <<
"\n");
478 <<
": mass = " << Loop.Mass <<
", scale = " << Loop.Scale
480 Loop.Scale *= Loop.Mass.toScaled();
481 Loop.IsPackaged =
false;
482 DEBUG(
dbgs() <<
" => combined-scale = " << Loop.Scale <<
"\n");
487 for (
const BlockNode &
N : Loop.Nodes) {
488 const auto &Working = BFI.
Working[N.Index];
489 Scaled64 &
F = Working.isAPackage() ? Working.getPackagedLoop()->Scale
490 : BFI.
Freqs[N.Index].Scaled;
491 Scaled64 New = Loop.Scale *
F;
500 for (
size_t Index = 0; Index < Working.size(); ++Index)
501 Freqs[Index].Scaled = Working[Index].Mass.
toScaled();
510 auto Min = Scaled64::getLargest();
511 auto Max = Scaled64::getZero();
512 for (
size_t Index = 0; Index < Working.size(); ++Index) {
515 Max =
std::max(Max, Freqs[Index].Scaled);
532 return Freqs[Node.
Index].Integer;
538 return getProfileCountFromFreq(F, getBlockFreq(Node).getFrequency());
543 uint64_t Freq)
const {
548 APInt BlockCount(128, EntryCount.getValue());
549 APInt BlockFreq(128, Freq);
550 APInt EntryFreq(128, getEntryFreq());
551 BlockCount *= BlockFreq;
552 BlockCount = BlockCount.udiv(EntryFreq);
553 return BlockCount.getLimitedValue();
559 return Scaled64::getZero();
560 return Freqs[Node.
Index].Scaled;
566 assert(Node.
Index < Freqs.size() &&
"Expected legal index");
567 Freqs[Node.
Index].Integer = Freq;
572 return std::string();
583 return OS << getFloatingBlockFreq(Node);
592 return OS << Block / Entry;
598 for (
auto N : OuterLoop.
Nodes)
618 if (OuterLoop && OuterLoop->
isHeader(Succ))
624 Irr.
Edges.push_back(&SuccIrr);
625 SuccIrr.
Edges.push_front(&Irr);
649 const std::vector<const IrreducibleGraph::IrrNode *> &SCC,
655 for (
const auto *
I : SCC)
659 auto &Irr = *
I->first;
660 for (
const auto *
P :
make_range(Irr.pred_begin(), Irr.pred_end())) {
666 Headers.push_back(Irr.Node);
671 assert(Headers.size() >= 2 &&
672 "Expected irreducible CFG; -loop-info is likely invalid");
673 if (Headers.size() == InSCC.
size()) {
675 std::sort(Headers.begin(), Headers.end());
680 for (
const auto &
I : InSCC) {
685 auto &Irr = *
I.first;
686 for (
const auto *
P :
make_range(Irr.pred_begin(), Irr.pred_end())) {
688 if (
P->Node < Irr.Node)
697 Headers.push_back(Irr.Node);
701 if (Headers.back() == Irr.Node)
706 Others.push_back(Irr.Node);
709 std::sort(Headers.begin(), Headers.end());
715 LoopData *OuterLoop, std::list<LoopData>::iterator Insert,
716 const std::vector<const IrreducibleGraph::IrrNode *> &SCC) {
724 auto Loop = BFI.
Loops.emplace(Insert, OuterLoop, Headers.begin(),
725 Headers.end(), Others.begin(), Others.end());
728 for (
const auto &
N :
Loop->Nodes)
729 if (BFI.
Working[
N.Index].isLoopHeader())
738 std::list<LoopData>::iterator Insert) {
739 assert((OuterLoop ==
nullptr) == (Insert ==
Loops.begin()));
740 auto Prev = OuterLoop ? std::prev(Insert) :
Loops.end();
762 if (!Working[
I->Index].isPackaged())
779 DEBUG(
dbgs() <<
"adjust-loop-header-mass:\n");
781 auto &HeaderNode = Loop.
Nodes[
H];
783 DEBUG(
dbgs() <<
" - Add back edge mass for node "
784 <<
getBlockName(HeaderNode) <<
": " << BackedgeMass <<
"\n");
785 if (BackedgeMass.getMass() > 0)
786 Dist.
addLocal(HeaderNode, BackedgeMass.getMass());
788 DEBUG(
dbgs() <<
" Nothing added. Back edge mass is zero\n");
791 DitheringDistributer
D(Dist, LoopMass);
793 DEBUG(
dbgs() <<
" Distribute loop mass " << LoopMass
794 <<
" to headers using above weights\n");
797 assert(W.
Type == Weight::Local &&
"all weights should be local");
void push_back(const T &Elt)
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)
GCNRegPressure max(const GCNRegPressure &P1, const GCNRegPressure &P2)
bool IsPackaged
Whether this has been packaged.
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds...
static char getHexDigit(int N)
Maximum length of the test input libFuzzer tries to guess a good value based on the corpus and reports it always prefer smaller inputs during the corpus shuffle When libFuzzer itself reports a bug this exit code will be used If indicates the maximal total time in seconds to run the fuzzer minimizes the provided crash input Use with tries to cleanse the provided crash input to make it contain fewer original bytes Use with exact_artifact_path to specify the output Experimental Use value profile to guide fuzzing Number of jobs to run If min(jobs, NumberOfCpuCores()/2)\" is used.") FUZZER_FLAG_INT(reload
MachineInstrBuilder MachineInstrBuilder &DefMI const MCInstrDesc & Desc
Stats about a block itself.
static NodeRef getEntryNode(const GraphT &G)
void addLocal(const BlockNode &Node, uint64_t Amount)
static ChildIteratorType child_end(NodeRef N)
SmallDenseMap< uint32_t, IrrNode *, 4 > Lookup
static void cleanup(BlockFrequencyInfoImplBase &BFI)
Clear all memory not needed downstream.
static void combineWeight(Weight &W, const Weight &OtherW)
uint64_t getFrequency() const
Returns the frequency as a fixpoint number scaled by the entry frequency.
uint32_t NumHeaders
Number of headers.
std::size_t 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 setBlockFreq(const BlockNode &Node, uint64_t Freq)
GraphT::IrrNode::iterator ChildIteratorType
raw_ostream & print(raw_ostream &OS) const
ScaledNumber< uint64_t > toScaled() const
Convert to scaled number.
BlockFrequency getBlockFreq(const BlockNode &Node) const
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)
scc_iterator< T > scc_begin(const T &G)
Construct the begin iterator for a deduced graph type T.
Graph of irreducible control flow.
ScaledNumber inverse() const
Optional< uint64_t > getEntryCount() const
Get the entry count for this function.
void computeLoopScale(LoopData &Loop)
Compute the loop scale for a loop.
void addBackedge(const BlockNode &Node, uint64_t Amount)
Optional< uint64_t > getBlockProfileCount(const Function &F, const BlockNode &Node) const
static ChildIteratorType child_begin(NodeRef N)
const GraphT::IrrNode * NodeRef
bool addToDist(Distribution &Dist, const LoopData *OuterLoop, const BlockNode &Pred, const BlockNode &Succ, uint64_t Weight)
Add an edge to the distribution.
std::vector< FrequencyData > Freqs
Data about each block. This is used downstream.
void dump(const SparseBitVector< ElementSize > &LHS, raw_ostream &out)
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...
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator begin()
std::string getLoopName(const LoopData &Loop) const
Distribution of unscaled probability weight.
void addNode(const BlockNode &Node)
Scaled64 getFloatingBlockFreq(const BlockNode &Node) const
raw_ostream & printBlockFreq(raw_ostream &OS, const BlockNode &Node) const
static void unwrapLoop(BlockFrequencyInfoImplBase &BFI, LoopData &Loop)
Unwrap a loop package.
bool isHeader(const BlockNode &Node) const
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)
void addExit(const BlockNode &Node, uint64_t Amount)
iterator succ_begin() const
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
ExitMap Exits
Successor edges (and weights).
virtual std::string getBlockName(const BlockNode &Node) const
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.
static BlockMass getEmpty()
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.
static void createIrreducibleLoop(BlockFrequencyInfoImplBase &BFI, const IrreducibleGraph &G, LoopData *OuterLoop, std::list< LoopData >::iterator Insert, const std::vector< const IrreducibleGraph::IrrNode * > &SCC)
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.
bfi_detail::IrreducibleGraph GraphT
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
Unscaled probability weight.
static void combineWeightsByHashing(WeightList &Weights)
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator end()
Represents a single loop in the control flow graph.
void packageLoop(LoopData &Loop)
Package up a loop.
LLVM_ATTRIBUTE_ALWAYS_INLINE size_type size() const
Optional< uint64_t > getProfileCountFromFreq(const Function &F, uint64_t Freq) const
static BlockMass getFull()
bool isIrreducible() const
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())
std::vector< WorkingData > Working
Loop data: see initializeLoops().
std::vector< IrrNode > Nodes
HeaderMassList BackedgeMass
Mass returned to each loop header.
This class implements an extremely fast bulk output stream that can only output to a stream...
std::deque< const IrrNode * > Edges
Base class for BlockFrequencyInfoImpl.
void sort(Policy policy, RandomAccessIterator Start, RandomAccessIterator End, const Comparator &Comp=Comparator())
bool addLoopSuccessorsToDist(const LoopData *OuterLoop, LoopData &Loop, Distribution &Dist)
Add all edges out of a packaged loop to the distribution.
iterator succ_end() const
SmallVector< NodeAddr< NodeBase * >, 4 > NodeList
void unwrapLoops()
Unwrap loops.
HeaderMassList::difference_type getHeaderIndex(const BlockNode &B)
BlockNode getHeader() const
Representative of a block.
void finalizeMetrics()
Finalize frequency metrics.
WeightList Weights
Individual successor weights.