1 //===- BlockFrequencyImplInfo.cpp - Block Frequency Info Implementation ---===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // Loops should be simplified before this analysis.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/Analysis/BlockFrequencyInfoImpl.h"
15 #include "llvm/ADT/SCCIterator.h"
16 #include "llvm/Support/raw_ostream.h"
20 using namespace llvm::bfi_detail;
22 #define DEBUG_TYPE "block-freq"
24 ScaledNumber<uint64_t> BlockMass::toScaled() const {
26 return ScaledNumber<uint64_t>(1, 0);
27 return ScaledNumber<uint64_t>(getMass() + 1, -64);
30 void BlockMass::dump() const { print(dbgs()); }
32 static char getHexDigit(int N) {
38 raw_ostream &BlockMass::print(raw_ostream &OS) const {
39 for (int Digits = 0; Digits < 16; ++Digits)
40 OS << getHexDigit(Mass >> (60 - Digits * 4) & 0xf);
46 typedef BlockFrequencyInfoImplBase::BlockNode BlockNode;
47 typedef BlockFrequencyInfoImplBase::Distribution Distribution;
48 typedef BlockFrequencyInfoImplBase::Distribution::WeightList WeightList;
49 typedef BlockFrequencyInfoImplBase::Scaled64 Scaled64;
50 typedef BlockFrequencyInfoImplBase::LoopData LoopData;
51 typedef BlockFrequencyInfoImplBase::Weight Weight;
52 typedef BlockFrequencyInfoImplBase::FrequencyData FrequencyData;
54 /// \brief Dithering mass distributer.
56 /// This class splits up a single mass into portions by weight, dithering to
57 /// spread out error. No mass is lost. The dithering precision depends on the
58 /// precision of the product of \a BlockMass and \a BranchProbability.
60 /// The distribution algorithm follows.
62 /// 1. Initialize by saving the sum of the weights in \a RemWeight and the
63 /// mass to distribute in \a RemMass.
65 /// 2. For each portion:
67 /// 1. Construct a branch probability, P, as the portion's weight divided
68 /// by the current value of \a RemWeight.
69 /// 2. Calculate the portion's mass as \a RemMass times P.
70 /// 3. Update \a RemWeight and \a RemMass at each portion by subtracting
71 /// the current portion's weight and mass.
72 struct DitheringDistributer {
76 DitheringDistributer(Distribution &Dist, const BlockMass &Mass);
78 BlockMass takeMass(uint32_t Weight);
83 DitheringDistributer::DitheringDistributer(Distribution &Dist,
84 const BlockMass &Mass) {
86 RemWeight = Dist.Total;
90 BlockMass DitheringDistributer::takeMass(uint32_t Weight) {
91 assert(Weight && "invalid weight");
92 assert(Weight <= RemWeight);
93 BlockMass Mass = RemMass * BranchProbability(Weight, RemWeight);
95 // Decrement totals (dither).
101 void Distribution::add(const BlockNode &Node, uint64_t Amount,
102 Weight::DistType Type) {
103 assert(Amount && "invalid weight of 0");
104 uint64_t NewTotal = Total + Amount;
106 // Check for overflow. It should be impossible to overflow twice.
107 bool IsOverflow = NewTotal < Total;
108 assert(!(DidOverflow && IsOverflow) && "unexpected repeated overflow");
109 DidOverflow |= IsOverflow;
115 Weights.push_back(Weight(Type, Node, Amount));
118 static void combineWeight(Weight &W, const Weight &OtherW) {
119 assert(OtherW.TargetNode.isValid());
124 assert(W.Type == OtherW.Type);
125 assert(W.TargetNode == OtherW.TargetNode);
126 assert(OtherW.Amount && "Expected non-zero weight");
127 if (W.Amount > W.Amount + OtherW.Amount)
128 // Saturate on overflow.
129 W.Amount = UINT64_MAX;
131 W.Amount += OtherW.Amount;
133 static void combineWeightsBySorting(WeightList &Weights) {
134 // Sort so edges to the same node are adjacent.
135 std::sort(Weights.begin(), Weights.end(),
137 const Weight &R) { return L.TargetNode < R.TargetNode; });
139 // Combine adjacent edges.
140 WeightList::iterator O = Weights.begin();
141 for (WeightList::const_iterator I = O, L = O, E = Weights.end(); I != E;
145 // Find the adjacent weights to the same node.
146 for (++L; L != E && I->TargetNode == L->TargetNode; ++L)
147 combineWeight(*O, *L);
150 // Erase extra entries.
151 Weights.erase(O, Weights.end());
154 static void combineWeightsByHashing(WeightList &Weights) {
155 // Collect weights into a DenseMap.
156 typedef DenseMap<BlockNode::IndexType, Weight> HashTable;
157 HashTable Combined(NextPowerOf2(2 * Weights.size()));
158 for (const Weight &W : Weights)
159 combineWeight(Combined[W.TargetNode.Index], W);
161 // Check whether anything changed.
162 if (Weights.size() == Combined.size())
165 // Fill in the new weights.
167 Weights.reserve(Combined.size());
168 for (const auto &I : Combined)
169 Weights.push_back(I.second);
171 static void combineWeights(WeightList &Weights) {
172 // Use a hash table for many successors to keep this linear.
173 if (Weights.size() > 128) {
174 combineWeightsByHashing(Weights);
178 combineWeightsBySorting(Weights);
180 static uint64_t shiftRightAndRound(uint64_t N, int Shift) {
185 return (N >> Shift) + (UINT64_C(1) & N >> (Shift - 1));
187 void Distribution::normalize() {
188 // Early exit for termination nodes.
192 // Only bother if there are multiple successors.
193 if (Weights.size() > 1)
194 combineWeights(Weights);
196 // Early exit when combined into a single successor.
197 if (Weights.size() == 1) {
199 Weights.front().Amount = 1;
203 // Determine how much to shift right so that the total fits into 32-bits.
205 // If we shift at all, shift by 1 extra. Otherwise, the lower limit of 1
206 // for each weight can cause a 32-bit overflow.
210 else if (Total > UINT32_MAX)
211 Shift = 33 - countLeadingZeros(Total);
213 // Early exit if nothing needs to be scaled.
215 // If we didn't overflow then combineWeights() shouldn't have changed the
216 // sum of the weights, but let's double-check.
217 assert(Total == std::accumulate(Weights.begin(), Weights.end(), UINT64_C(0),
218 [](uint64_t Sum, const Weight &W) {
219 return Sum + W.Amount;
221 "Expected total to be correct");
225 // Recompute the total through accumulation (rather than shifting it) so that
226 // it's accurate after shifting and any changes combineWeights() made above.
229 // Sum the weights to each node and shift right if necessary.
230 for (Weight &W : Weights) {
231 // Scale down below UINT32_MAX. Since Shift is larger than necessary, we
232 // can round here without concern about overflow.
233 assert(W.TargetNode.isValid());
234 W.Amount = std::max(UINT64_C(1), shiftRightAndRound(W.Amount, Shift));
235 assert(W.Amount <= UINT32_MAX);
240 assert(Total <= UINT32_MAX);
243 void BlockFrequencyInfoImplBase::clear() {
244 // Swap with a default-constructed std::vector, since std::vector<>::clear()
245 // does not actually clear heap storage.
246 std::vector<FrequencyData>().swap(Freqs);
247 std::vector<WorkingData>().swap(Working);
251 /// \brief Clear all memory not needed downstream.
253 /// Releases all memory not used downstream. In particular, saves Freqs.
254 static void cleanup(BlockFrequencyInfoImplBase &BFI) {
255 std::vector<FrequencyData> SavedFreqs(std::move(BFI.Freqs));
257 BFI.Freqs = std::move(SavedFreqs);
260 bool BlockFrequencyInfoImplBase::addToDist(Distribution &Dist,
261 const LoopData *OuterLoop,
262 const BlockNode &Pred,
263 const BlockNode &Succ,
268 auto isLoopHeader = [&OuterLoop](const BlockNode &Node) {
269 return OuterLoop && OuterLoop->isHeader(Node);
272 BlockNode Resolved = Working[Succ.Index].getResolvedNode();
275 auto debugSuccessor = [&](const char *Type) {
277 << " [" << Type << "] weight = " << Weight;
278 if (!isLoopHeader(Resolved))
279 dbgs() << ", succ = " << getBlockName(Succ);
280 if (Resolved != Succ)
281 dbgs() << ", resolved = " << getBlockName(Resolved);
284 (void)debugSuccessor;
287 if (isLoopHeader(Resolved)) {
288 DEBUG(debugSuccessor("backedge"));
289 Dist.addBackedge(OuterLoop->getHeader(), Weight);
293 if (Working[Resolved.Index].getContainingLoop() != OuterLoop) {
294 DEBUG(debugSuccessor(" exit "));
295 Dist.addExit(Resolved, Weight);
299 if (Resolved < Pred) {
300 if (!isLoopHeader(Pred)) {
301 // If OuterLoop is an irreducible loop, we can't actually handle this.
302 assert((!OuterLoop || !OuterLoop->isIrreducible()) &&
303 "unhandled irreducible control flow");
305 // Irreducible backedge. Abort.
306 DEBUG(debugSuccessor("abort!!!"));
310 // If "Pred" is a loop header, then this isn't really a backedge; rather,
311 // OuterLoop must be irreducible. These false backedges can come only from
312 // secondary loop headers.
313 assert(OuterLoop && OuterLoop->isIrreducible() && !isLoopHeader(Resolved) &&
314 "unhandled irreducible control flow");
317 DEBUG(debugSuccessor(" local "));
318 Dist.addLocal(Resolved, Weight);
322 bool BlockFrequencyInfoImplBase::addLoopSuccessorsToDist(
323 const LoopData *OuterLoop, LoopData &Loop, Distribution &Dist) {
324 // Copy the exit map into Dist.
325 for (const auto &I : Loop.Exits)
326 if (!addToDist(Dist, OuterLoop, Loop.getHeader(), I.first,
328 // Irreducible backedge.
334 /// \brief Compute the loop scale for a loop.
335 void BlockFrequencyInfoImplBase::computeLoopScale(LoopData &Loop) {
336 // Compute loop scale.
337 DEBUG(dbgs() << "compute-loop-scale: " << getLoopName(Loop) << "\n");
339 // Infinite loops need special handling. If we give the back edge an infinite
340 // mass, they may saturate all the other scales in the function down to 1,
341 // making all the other region temperatures look exactly the same. Choose an
342 // arbitrary scale to avoid these issues.
344 // FIXME: An alternate way would be to select a symbolic scale which is later
345 // replaced to be the maximum of all computed scales plus 1. This would
346 // appropriately describe the loop as having a large scale, without skewing
347 // the final frequency computation.
348 const Scaled64 InifiniteLoopScale(1, 12);
350 // LoopScale == 1 / ExitMass
351 // ExitMass == HeadMass - BackedgeMass
352 BlockMass ExitMass = BlockMass::getFull() - Loop.BackedgeMass;
354 // Block scale stores the inverse of the scale. If this is an infinite loop,
355 // its exit mass will be zero. In this case, use an arbitrary scale for the
358 ExitMass.isEmpty() ? InifiniteLoopScale : ExitMass.toScaled().inverse();
360 DEBUG(dbgs() << " - exit-mass = " << ExitMass << " (" << BlockMass::getFull()
361 << " - " << Loop.BackedgeMass << ")\n"
362 << " - scale = " << Loop.Scale << "\n");
365 /// \brief Package up a loop.
366 void BlockFrequencyInfoImplBase::packageLoop(LoopData &Loop) {
367 DEBUG(dbgs() << "packaging-loop: " << getLoopName(Loop) << "\n");
369 // Clear the subloop exits to prevent quadratic memory usage.
370 for (const BlockNode &M : Loop.Nodes) {
371 if (auto *Loop = Working[M.Index].getPackagedLoop())
373 DEBUG(dbgs() << " - node: " << getBlockName(M.Index) << "\n");
375 Loop.IsPackaged = true;
378 void BlockFrequencyInfoImplBase::distributeMass(const BlockNode &Source,
380 Distribution &Dist) {
381 BlockMass Mass = Working[Source.Index].getMass();
382 DEBUG(dbgs() << " => mass: " << Mass << "\n");
384 // Distribute mass to successors as laid out in Dist.
385 DitheringDistributer D(Dist, Mass);
388 auto debugAssign = [&](const BlockNode &T, const BlockMass &M,
390 dbgs() << " => assign " << M << " (" << D.RemMass << ")";
392 dbgs() << " [" << Desc << "]";
394 dbgs() << " to " << getBlockName(T);
400 for (const Weight &W : Dist.Weights) {
401 // Check for a local edge (non-backedge and non-exit).
402 BlockMass Taken = D.takeMass(W.Amount);
403 if (W.Type == Weight::Local) {
404 Working[W.TargetNode.Index].getMass() += Taken;
405 DEBUG(debugAssign(W.TargetNode, Taken, nullptr));
409 // Backedges and exits only make sense if we're processing a loop.
410 assert(OuterLoop && "backedge or exit outside of loop");
412 // Check for a backedge.
413 if (W.Type == Weight::Backedge) {
414 OuterLoop->BackedgeMass += Taken;
415 DEBUG(debugAssign(BlockNode(), Taken, "back"));
419 // This must be an exit.
420 assert(W.Type == Weight::Exit);
421 OuterLoop->Exits.push_back(std::make_pair(W.TargetNode, Taken));
422 DEBUG(debugAssign(W.TargetNode, Taken, "exit"));
426 static void convertFloatingToInteger(BlockFrequencyInfoImplBase &BFI,
427 const Scaled64 &Min, const Scaled64 &Max) {
428 // Scale the Factor to a size that creates integers. Ideally, integers would
429 // be scaled so that Max == UINT64_MAX so that they can be best
430 // differentiated. However, in the presence of large frequency values, small
431 // frequencies are scaled down to 1, making it impossible to differentiate
432 // small, unequal numbers. When the spread between Min and Max frequencies
433 // fits well within MaxBits, we make the scale be at least 8.
434 const unsigned MaxBits = 64;
435 const unsigned SpreadBits = (Max / Min).lg();
436 Scaled64 ScalingFactor;
437 if (SpreadBits <= MaxBits - 3) {
438 // If the values are small enough, make the scaling factor at least 8 to
439 // allow distinguishing small values.
440 ScalingFactor = Min.inverse();
443 // If the values need more than MaxBits to be represented, saturate small
444 // frequency values down to 1 by using a scaling factor that benefits large
446 ScalingFactor = Scaled64(1, MaxBits) / Max;
449 // Translate the floats to integers.
450 DEBUG(dbgs() << "float-to-int: min = " << Min << ", max = " << Max
451 << ", factor = " << ScalingFactor << "\n");
452 for (size_t Index = 0; Index < BFI.Freqs.size(); ++Index) {
453 Scaled64 Scaled = BFI.Freqs[Index].Scaled * ScalingFactor;
454 BFI.Freqs[Index].Integer = std::max(UINT64_C(1), Scaled.toInt<uint64_t>());
455 DEBUG(dbgs() << " - " << BFI.getBlockName(Index) << ": float = "
456 << BFI.Freqs[Index].Scaled << ", scaled = " << Scaled
457 << ", int = " << BFI.Freqs[Index].Integer << "\n");
461 /// \brief Unwrap a loop package.
463 /// Visits all the members of a loop, adjusting their BlockData according to
464 /// the loop's pseudo-node.
465 static void unwrapLoop(BlockFrequencyInfoImplBase &BFI, LoopData &Loop) {
466 DEBUG(dbgs() << "unwrap-loop-package: " << BFI.getLoopName(Loop)
467 << ": mass = " << Loop.Mass << ", scale = " << Loop.Scale
469 Loop.Scale *= Loop.Mass.toScaled();
470 Loop.IsPackaged = false;
471 DEBUG(dbgs() << " => combined-scale = " << Loop.Scale << "\n");
473 // Propagate the head scale through the loop. Since members are visited in
474 // RPO, the head scale will be updated by the loop scale first, and then the
475 // final head scale will be used for updated the rest of the members.
476 for (const BlockNode &N : Loop.Nodes) {
477 const auto &Working = BFI.Working[N.Index];
478 Scaled64 &F = Working.isAPackage() ? Working.getPackagedLoop()->Scale
479 : BFI.Freqs[N.Index].Scaled;
480 Scaled64 New = Loop.Scale * F;
481 DEBUG(dbgs() << " - " << BFI.getBlockName(N) << ": " << F << " => " << New
487 void BlockFrequencyInfoImplBase::unwrapLoops() {
488 // Set initial frequencies from loop-local masses.
489 for (size_t Index = 0; Index < Working.size(); ++Index)
490 Freqs[Index].Scaled = Working[Index].Mass.toScaled();
492 for (LoopData &Loop : Loops)
493 unwrapLoop(*this, Loop);
496 void BlockFrequencyInfoImplBase::finalizeMetrics() {
497 // Unwrap loop packages in reverse post-order, tracking min and max
499 auto Min = Scaled64::getLargest();
500 auto Max = Scaled64::getZero();
501 for (size_t Index = 0; Index < Working.size(); ++Index) {
502 // Update min/max scale.
503 Min = std::min(Min, Freqs[Index].Scaled);
504 Max = std::max(Max, Freqs[Index].Scaled);
507 // Convert to integers.
508 convertFloatingToInteger(*this, Min, Max);
510 // Clean up data structures.
513 // Print out the final stats.
518 BlockFrequencyInfoImplBase::getBlockFreq(const BlockNode &Node) const {
521 return Freqs[Node.Index].Integer;
524 BlockFrequencyInfoImplBase::getFloatingBlockFreq(const BlockNode &Node) const {
526 return Scaled64::getZero();
527 return Freqs[Node.Index].Scaled;
531 BlockFrequencyInfoImplBase::getBlockName(const BlockNode &Node) const {
532 return std::string();
535 BlockFrequencyInfoImplBase::getLoopName(const LoopData &Loop) const {
536 return getBlockName(Loop.getHeader()) + (Loop.isIrreducible() ? "**" : "*");
540 BlockFrequencyInfoImplBase::printBlockFreq(raw_ostream &OS,
541 const BlockNode &Node) const {
542 return OS << getFloatingBlockFreq(Node);
546 BlockFrequencyInfoImplBase::printBlockFreq(raw_ostream &OS,
547 const BlockFrequency &Freq) const {
548 Scaled64 Block(Freq.getFrequency(), 0);
549 Scaled64 Entry(getEntryFreq(), 0);
551 return OS << Block / Entry;
554 void IrreducibleGraph::addNodesInLoop(const BFIBase::LoopData &OuterLoop) {
555 Start = OuterLoop.getHeader();
556 Nodes.reserve(OuterLoop.Nodes.size());
557 for (auto N : OuterLoop.Nodes)
561 void IrreducibleGraph::addNodesInFunction() {
563 for (uint32_t Index = 0; Index < BFI.Working.size(); ++Index)
564 if (!BFI.Working[Index].isPackaged())
568 void IrreducibleGraph::indexNodes() {
569 for (auto &I : Nodes)
570 Lookup[I.Node.Index] = &I;
572 void IrreducibleGraph::addEdge(IrrNode &Irr, const BlockNode &Succ,
573 const BFIBase::LoopData *OuterLoop) {
574 if (OuterLoop && OuterLoop->isHeader(Succ))
576 auto L = Lookup.find(Succ.Index);
577 if (L == Lookup.end())
579 IrrNode &SuccIrr = *L->second;
580 Irr.Edges.push_back(&SuccIrr);
581 SuccIrr.Edges.push_front(&Irr);
586 template <> struct GraphTraits<IrreducibleGraph> {
587 typedef bfi_detail::IrreducibleGraph GraphT;
589 typedef const GraphT::IrrNode NodeType;
590 typedef GraphT::IrrNode::iterator ChildIteratorType;
592 static const NodeType *getEntryNode(const GraphT &G) {
595 static ChildIteratorType child_begin(NodeType *N) { return N->succ_begin(); }
596 static ChildIteratorType child_end(NodeType *N) { return N->succ_end(); }
600 /// \brief Find extra irreducible headers.
602 /// Find entry blocks and other blocks with backedges, which exist when \c G
603 /// contains irreducible sub-SCCs.
604 static void findIrreducibleHeaders(
605 const BlockFrequencyInfoImplBase &BFI,
606 const IrreducibleGraph &G,
607 const std::vector<const IrreducibleGraph::IrrNode *> &SCC,
608 LoopData::NodeList &Headers, LoopData::NodeList &Others) {
609 // Map from nodes in the SCC to whether it's an entry block.
610 SmallDenseMap<const IrreducibleGraph::IrrNode *, bool, 8> InSCC;
612 // InSCC also acts the set of nodes in the graph. Seed it.
613 for (const auto *I : SCC)
616 for (auto I = InSCC.begin(), E = InSCC.end(); I != E; ++I) {
617 auto &Irr = *I->first;
618 for (const auto *P : make_range(Irr.pred_begin(), Irr.pred_end())) {
622 // This is an entry block.
624 Headers.push_back(Irr.Node);
625 DEBUG(dbgs() << " => entry = " << BFI.getBlockName(Irr.Node) << "\n");
629 assert(Headers.size() >= 2 &&
630 "Expected irreducible CFG; -loop-info is likely invalid");
631 if (Headers.size() == InSCC.size()) {
632 // Every block is a header.
633 std::sort(Headers.begin(), Headers.end());
637 // Look for extra headers from irreducible sub-SCCs.
638 for (const auto &I : InSCC) {
639 // Entry blocks are already headers.
643 auto &Irr = *I.first;
644 for (const auto *P : make_range(Irr.pred_begin(), Irr.pred_end())) {
645 // Skip forward edges.
646 if (P->Node < Irr.Node)
649 // Skip predecessors from entry blocks. These can have inverted
654 // Store the extra header.
655 Headers.push_back(Irr.Node);
656 DEBUG(dbgs() << " => extra = " << BFI.getBlockName(Irr.Node) << "\n");
659 if (Headers.back() == Irr.Node)
660 // Added this as a header.
663 // This is not a header.
664 Others.push_back(Irr.Node);
665 DEBUG(dbgs() << " => other = " << BFI.getBlockName(Irr.Node) << "\n");
667 std::sort(Headers.begin(), Headers.end());
668 std::sort(Others.begin(), Others.end());
671 static void createIrreducibleLoop(
672 BlockFrequencyInfoImplBase &BFI, const IrreducibleGraph &G,
673 LoopData *OuterLoop, std::list<LoopData>::iterator Insert,
674 const std::vector<const IrreducibleGraph::IrrNode *> &SCC) {
675 // Translate the SCC into RPO.
676 DEBUG(dbgs() << " - found-scc\n");
678 LoopData::NodeList Headers;
679 LoopData::NodeList Others;
680 findIrreducibleHeaders(BFI, G, SCC, Headers, Others);
682 auto Loop = BFI.Loops.emplace(Insert, OuterLoop, Headers.begin(),
683 Headers.end(), Others.begin(), Others.end());
685 // Update loop hierarchy.
686 for (const auto &N : Loop->Nodes)
687 if (BFI.Working[N.Index].isLoopHeader())
688 BFI.Working[N.Index].Loop->Parent = &*Loop;
690 BFI.Working[N.Index].Loop = &*Loop;
693 iterator_range<std::list<LoopData>::iterator>
694 BlockFrequencyInfoImplBase::analyzeIrreducible(
695 const IrreducibleGraph &G, LoopData *OuterLoop,
696 std::list<LoopData>::iterator Insert) {
697 assert((OuterLoop == nullptr) == (Insert == Loops.begin()));
698 auto Prev = OuterLoop ? std::prev(Insert) : Loops.end();
700 for (auto I = scc_begin(G); !I.isAtEnd(); ++I) {
704 // Translate the SCC into RPO.
705 createIrreducibleLoop(*this, G, OuterLoop, Insert, *I);
709 return make_range(std::next(Prev), Insert);
710 return make_range(Loops.begin(), Insert);
714 BlockFrequencyInfoImplBase::updateLoopWithIrreducible(LoopData &OuterLoop) {
715 OuterLoop.Exits.clear();
716 OuterLoop.BackedgeMass = BlockMass::getEmpty();
717 auto O = OuterLoop.Nodes.begin() + 1;
718 for (auto I = O, E = OuterLoop.Nodes.end(); I != E; ++I)
719 if (!Working[I->Index].isPackaged())
721 OuterLoop.Nodes.erase(O, OuterLoop.Nodes.end());