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/APFloat.h"
16 #include "llvm/ADT/SCCIterator.h"
17 #include "llvm/Support/raw_ostream.h"
21 using namespace llvm::bfi_detail;
23 #define DEBUG_TYPE "block-freq"
25 //===----------------------------------------------------------------------===//
27 // UnsignedFloat implementation.
29 //===----------------------------------------------------------------------===//
31 const int32_t UnsignedFloatBase::MaxExponent;
32 const int32_t UnsignedFloatBase::MinExponent;
35 static void appendDigit(std::string &Str, unsigned D) {
40 static void appendNumber(std::string &Str, uint64_t N) {
42 appendDigit(Str, N % 10);
47 static bool doesRoundUp(char Digit) {
60 static std::string toStringAPFloat(uint64_t D, int E, unsigned Precision) {
61 assert(E >= UnsignedFloatBase::MinExponent);
62 assert(E <= UnsignedFloatBase::MaxExponent);
64 // Find a new E, but don't let it increase past MaxExponent.
65 int LeadingZeros = UnsignedFloatBase::countLeadingZeros64(D);
66 int NewE = std::min(UnsignedFloatBase::MaxExponent, E + 63 - LeadingZeros);
67 int Shift = 63 - (NewE - E);
68 assert(Shift <= LeadingZeros);
69 assert(Shift == LeadingZeros || NewE == UnsignedFloatBase::MaxExponent);
73 // Check for a denormal.
74 unsigned AdjustedE = E + 16383;
76 assert(E == UnsignedFloatBase::MaxExponent);
80 // Build the float and print it.
81 uint64_t RawBits[2] = {D, AdjustedE};
82 APFloat Float(APFloat::x87DoubleExtended, APInt(80, RawBits));
83 SmallVector<char, 24> Chars;
84 Float.toString(Chars, Precision, 0);
85 return std::string(Chars.begin(), Chars.end());
88 static std::string stripTrailingZeros(const std::string &Float) {
89 size_t NonZero = Float.find_last_not_of('0');
90 assert(NonZero != std::string::npos && "no . in floating point string");
92 if (Float[NonZero] == '.')
95 return Float.substr(0, NonZero + 1);
98 std::string UnsignedFloatBase::toString(uint64_t D, int16_t E, int Width,
103 // Canonicalize exponent and digits.
111 if (int Shift = std::min(int16_t(countLeadingZeros64(D)), E)) {
118 } else if (E > -64) {
120 Below0 = D << (64 + E);
121 } else if (E > -120) {
122 Below0 = D >> (-E - 64);
123 Extra = D << (128 + E);
124 ExtraShift = -64 - E;
127 // Fall back on APFloat for very small and very large numbers.
128 if (!Above0 && !Below0)
129 return toStringAPFloat(D, E, Precision);
131 // Append the digits before the decimal.
133 size_t DigitsOut = 0;
135 appendNumber(Str, Above0);
136 DigitsOut = Str.size();
139 std::reverse(Str.begin(), Str.end());
141 // Return early if there's nothing after the decimal.
145 // Append the decimal and beyond.
147 uint64_t Error = UINT64_C(1) << (64 - Width);
149 // We need to shift Below0 to the right to make space for calculating
150 // digits. Save the precision we're losing in Extra.
151 Extra = (Below0 & 0xf) << 56 | (Extra >> 8);
154 size_t AfterDot = Str.size();
164 Below0 += (Extra >> 60);
165 Extra = Extra & (UINT64_MAX >> 4);
166 appendDigit(Str, Below0 >> 60);
167 Below0 = Below0 & (UINT64_MAX >> 4);
168 if (DigitsOut || Str.back() != '0')
171 } while (Error && (Below0 << 4 | Extra >> 60) >= Error / 2 &&
172 (!Precision || DigitsOut <= Precision || SinceDot < 2));
174 // Return early for maximum precision.
175 if (!Precision || DigitsOut <= Precision)
176 return stripTrailingZeros(Str);
178 // Find where to truncate.
180 std::max(Str.size() - (DigitsOut - Precision), AfterDot + 1);
182 // Check if there's anything to truncate.
183 if (Truncate >= Str.size())
184 return stripTrailingZeros(Str);
186 bool Carry = doesRoundUp(Str[Truncate]);
188 return stripTrailingZeros(Str.substr(0, Truncate));
190 // Round with the first truncated digit.
191 for (std::string::reverse_iterator I(Str.begin() + Truncate), E = Str.rend();
205 // Add "1" in front if we still need to carry.
206 return stripTrailingZeros(std::string(Carry, '1') + Str.substr(0, Truncate));
209 raw_ostream &UnsignedFloatBase::print(raw_ostream &OS, uint64_t D, int16_t E,
210 int Width, unsigned Precision) {
211 return OS << toString(D, E, Width, Precision);
214 void UnsignedFloatBase::dump(uint64_t D, int16_t E, int Width) {
215 print(dbgs(), D, E, Width, 0) << "[" << Width << ":" << D << "*2^" << E
219 static std::pair<uint64_t, int16_t>
220 getRoundedFloat(uint64_t N, bool ShouldRound, int64_t Shift) {
223 // Rounding caused an overflow.
224 return std::make_pair(UINT64_C(1), Shift + 64);
225 return std::make_pair(N, Shift);
228 std::pair<uint64_t, int16_t> UnsignedFloatBase::divide64(uint64_t Dividend,
230 // Input should be sanitized.
234 // Minimize size of divisor.
236 if (int Zeros = countTrailingZeros(Divisor)) {
241 // Check for powers of two.
243 return std::make_pair(Dividend, Shift);
245 // Maximize size of dividend.
246 if (int Zeros = countLeadingZeros64(Dividend)) {
251 // Start with the result of a divide.
252 uint64_t Quotient = Dividend / Divisor;
255 // Continue building the quotient with long division.
257 // TODO: continue with largers digits.
258 while (!(Quotient >> 63) && Dividend) {
259 // Shift Dividend, and check for overflow.
260 bool IsOverflow = Dividend >> 63;
265 bool DoesDivide = IsOverflow || Divisor <= Dividend;
266 Quotient = (Quotient << 1) | uint64_t(DoesDivide);
267 Dividend -= DoesDivide ? Divisor : 0;
271 if (Dividend >= getHalf(Divisor))
273 // Rounding caused an overflow in Quotient.
274 return std::make_pair(UINT64_C(1), Shift + 64);
276 return getRoundedFloat(Quotient, Dividend >= getHalf(Divisor), Shift);
279 std::pair<uint64_t, int16_t> UnsignedFloatBase::multiply64(uint64_t L,
281 // Separate into two 32-bit digits (U.L).
282 uint64_t UL = L >> 32, LL = L & UINT32_MAX, UR = R >> 32, LR = R & UINT32_MAX;
284 // Compute cross products.
285 uint64_t P1 = UL * UR, P2 = UL * LR, P3 = LL * UR, P4 = LL * LR;
287 // Sum into two 64-bit digits.
288 uint64_t Upper = P1, Lower = P4;
289 auto addWithCarry = [&](uint64_t N) {
290 uint64_t NewLower = Lower + (N << 32);
291 Upper += (N >> 32) + (NewLower < Lower);
297 // Check whether the upper digit is empty.
299 return std::make_pair(Lower, 0);
301 // Shift as little as possible to maximize precision.
302 unsigned LeadingZeros = countLeadingZeros64(Upper);
303 int16_t Shift = 64 - LeadingZeros;
305 Upper = Upper << LeadingZeros | Lower >> Shift;
306 bool ShouldRound = Shift && (Lower & UINT64_C(1) << (Shift - 1));
307 return getRoundedFloat(Upper, ShouldRound, Shift);
310 //===----------------------------------------------------------------------===//
312 // BlockMass implementation.
314 //===----------------------------------------------------------------------===//
315 UnsignedFloat<uint64_t> BlockMass::toFloat() const {
317 return UnsignedFloat<uint64_t>(1, 0);
318 return UnsignedFloat<uint64_t>(getMass() + 1, -64);
321 void BlockMass::dump() const { print(dbgs()); }
323 static char getHexDigit(int N) {
329 raw_ostream &BlockMass::print(raw_ostream &OS) const {
330 for (int Digits = 0; Digits < 16; ++Digits)
331 OS << getHexDigit(Mass >> (60 - Digits * 4) & 0xf);
335 //===----------------------------------------------------------------------===//
337 // BlockFrequencyInfoImpl implementation.
339 //===----------------------------------------------------------------------===//
342 typedef BlockFrequencyInfoImplBase::BlockNode BlockNode;
343 typedef BlockFrequencyInfoImplBase::Distribution Distribution;
344 typedef BlockFrequencyInfoImplBase::Distribution::WeightList WeightList;
345 typedef BlockFrequencyInfoImplBase::Float Float;
346 typedef BlockFrequencyInfoImplBase::LoopData LoopData;
347 typedef BlockFrequencyInfoImplBase::Weight Weight;
348 typedef BlockFrequencyInfoImplBase::FrequencyData FrequencyData;
350 /// \brief Dithering mass distributer.
352 /// This class splits up a single mass into portions by weight, dithering to
353 /// spread out error. No mass is lost. The dithering precision depends on the
354 /// precision of the product of \a BlockMass and \a BranchProbability.
356 /// The distribution algorithm follows.
358 /// 1. Initialize by saving the sum of the weights in \a RemWeight and the
359 /// mass to distribute in \a RemMass.
361 /// 2. For each portion:
363 /// 1. Construct a branch probability, P, as the portion's weight divided
364 /// by the current value of \a RemWeight.
365 /// 2. Calculate the portion's mass as \a RemMass times P.
366 /// 3. Update \a RemWeight and \a RemMass at each portion by subtracting
367 /// the current portion's weight and mass.
368 struct DitheringDistributer {
372 DitheringDistributer(Distribution &Dist, const BlockMass &Mass);
374 BlockMass takeMass(uint32_t Weight);
378 DitheringDistributer::DitheringDistributer(Distribution &Dist,
379 const BlockMass &Mass) {
381 RemWeight = Dist.Total;
385 BlockMass DitheringDistributer::takeMass(uint32_t Weight) {
386 assert(Weight && "invalid weight");
387 assert(Weight <= RemWeight);
388 BlockMass Mass = RemMass * BranchProbability(Weight, RemWeight);
390 // Decrement totals (dither).
396 void Distribution::add(const BlockNode &Node, uint64_t Amount,
397 Weight::DistType Type) {
398 assert(Amount && "invalid weight of 0");
399 uint64_t NewTotal = Total + Amount;
401 // Check for overflow. It should be impossible to overflow twice.
402 bool IsOverflow = NewTotal < Total;
403 assert(!(DidOverflow && IsOverflow) && "unexpected repeated overflow");
404 DidOverflow |= IsOverflow;
414 Weights.push_back(W);
417 static void combineWeight(Weight &W, const Weight &OtherW) {
418 assert(OtherW.TargetNode.isValid());
423 assert(W.Type == OtherW.Type);
424 assert(W.TargetNode == OtherW.TargetNode);
425 assert(W.Amount < W.Amount + OtherW.Amount && "Unexpected overflow");
426 W.Amount += OtherW.Amount;
428 static void combineWeightsBySorting(WeightList &Weights) {
429 // Sort so edges to the same node are adjacent.
430 std::sort(Weights.begin(), Weights.end(),
432 const Weight &R) { return L.TargetNode < R.TargetNode; });
434 // Combine adjacent edges.
435 WeightList::iterator O = Weights.begin();
436 for (WeightList::const_iterator I = O, L = O, E = Weights.end(); I != E;
440 // Find the adjacent weights to the same node.
441 for (++L; L != E && I->TargetNode == L->TargetNode; ++L)
442 combineWeight(*O, *L);
445 // Erase extra entries.
446 Weights.erase(O, Weights.end());
449 static void combineWeightsByHashing(WeightList &Weights) {
450 // Collect weights into a DenseMap.
451 typedef DenseMap<BlockNode::IndexType, Weight> HashTable;
452 HashTable Combined(NextPowerOf2(2 * Weights.size()));
453 for (const Weight &W : Weights)
454 combineWeight(Combined[W.TargetNode.Index], W);
456 // Check whether anything changed.
457 if (Weights.size() == Combined.size())
460 // Fill in the new weights.
462 Weights.reserve(Combined.size());
463 for (const auto &I : Combined)
464 Weights.push_back(I.second);
466 static void combineWeights(WeightList &Weights) {
467 // Use a hash table for many successors to keep this linear.
468 if (Weights.size() > 128) {
469 combineWeightsByHashing(Weights);
473 combineWeightsBySorting(Weights);
475 static uint64_t shiftRightAndRound(uint64_t N, int Shift) {
480 return (N >> Shift) + (UINT64_C(1) & N >> (Shift - 1));
482 void Distribution::normalize() {
483 // Early exit for termination nodes.
487 // Only bother if there are multiple successors.
488 if (Weights.size() > 1)
489 combineWeights(Weights);
491 // Early exit when combined into a single successor.
492 if (Weights.size() == 1) {
494 Weights.front().Amount = 1;
498 // Determine how much to shift right so that the total fits into 32-bits.
500 // If we shift at all, shift by 1 extra. Otherwise, the lower limit of 1
501 // for each weight can cause a 32-bit overflow.
505 else if (Total > UINT32_MAX)
506 Shift = 33 - countLeadingZeros(Total);
508 // Early exit if nothing needs to be scaled.
512 // Recompute the total through accumulation (rather than shifting it) so that
513 // it's accurate after shifting.
516 // Sum the weights to each node and shift right if necessary.
517 for (Weight &W : Weights) {
518 // Scale down below UINT32_MAX. Since Shift is larger than necessary, we
519 // can round here without concern about overflow.
520 assert(W.TargetNode.isValid());
521 W.Amount = std::max(UINT64_C(1), shiftRightAndRound(W.Amount, Shift));
522 assert(W.Amount <= UINT32_MAX);
527 assert(Total <= UINT32_MAX);
530 void BlockFrequencyInfoImplBase::clear() {
531 // Swap with a default-constructed std::vector, since std::vector<>::clear()
532 // does not actually clear heap storage.
533 std::vector<FrequencyData>().swap(Freqs);
534 std::vector<WorkingData>().swap(Working);
538 /// \brief Clear all memory not needed downstream.
540 /// Releases all memory not used downstream. In particular, saves Freqs.
541 static void cleanup(BlockFrequencyInfoImplBase &BFI) {
542 std::vector<FrequencyData> SavedFreqs(std::move(BFI.Freqs));
544 BFI.Freqs = std::move(SavedFreqs);
547 bool BlockFrequencyInfoImplBase::addToDist(Distribution &Dist,
548 const LoopData *OuterLoop,
549 const BlockNode &Pred,
550 const BlockNode &Succ,
555 auto isLoopHeader = [&OuterLoop](const BlockNode &Node) {
556 return OuterLoop && OuterLoop->isHeader(Node);
559 BlockNode Resolved = Working[Succ.Index].getResolvedNode();
562 auto debugSuccessor = [&](const char *Type) {
564 << " [" << Type << "] weight = " << Weight;
565 if (!isLoopHeader(Resolved))
566 dbgs() << ", succ = " << getBlockName(Succ);
567 if (Resolved != Succ)
568 dbgs() << ", resolved = " << getBlockName(Resolved);
571 (void)debugSuccessor;
574 if (isLoopHeader(Resolved)) {
575 DEBUG(debugSuccessor("backedge"));
576 Dist.addBackedge(OuterLoop->getHeader(), Weight);
580 if (Working[Resolved.Index].getContainingLoop() != OuterLoop) {
581 DEBUG(debugSuccessor(" exit "));
582 Dist.addExit(Resolved, Weight);
586 if (Resolved < Pred) {
587 if (!isLoopHeader(Pred)) {
588 // If OuterLoop is an irreducible loop, we can't actually handle this.
589 assert((!OuterLoop || !OuterLoop->isIrreducible()) &&
590 "unhandled irreducible control flow");
592 // Irreducible backedge. Abort.
593 DEBUG(debugSuccessor("abort!!!"));
597 // If "Pred" is a loop header, then this isn't really a backedge; rather,
598 // OuterLoop must be irreducible. These false backedges can come only from
599 // secondary loop headers.
600 assert(OuterLoop && OuterLoop->isIrreducible() && !isLoopHeader(Resolved) &&
601 "unhandled irreducible control flow");
604 DEBUG(debugSuccessor(" local "));
605 Dist.addLocal(Resolved, Weight);
609 bool BlockFrequencyInfoImplBase::addLoopSuccessorsToDist(
610 const LoopData *OuterLoop, LoopData &Loop, Distribution &Dist) {
611 // Copy the exit map into Dist.
612 for (const auto &I : Loop.Exits)
613 if (!addToDist(Dist, OuterLoop, Loop.getHeader(), I.first,
615 // Irreducible backedge.
621 /// \brief Get the maximum allowed loop scale.
623 /// Gives the maximum number of estimated iterations allowed for a loop. Very
624 /// large numbers cause problems downstream (even within 64-bits).
625 static Float getMaxLoopScale() { return Float(1, 12); }
627 /// \brief Compute the loop scale for a loop.
628 void BlockFrequencyInfoImplBase::computeLoopScale(LoopData &Loop) {
629 // Compute loop scale.
630 DEBUG(dbgs() << "compute-loop-scale: " << getLoopName(Loop) << "\n");
632 // LoopScale == 1 / ExitMass
633 // ExitMass == HeadMass - BackedgeMass
634 BlockMass ExitMass = BlockMass::getFull() - Loop.BackedgeMass;
636 // Block scale stores the inverse of the scale.
637 Loop.Scale = ExitMass.toFloat().inverse();
639 DEBUG(dbgs() << " - exit-mass = " << ExitMass << " (" << BlockMass::getFull()
640 << " - " << Loop.BackedgeMass << ")\n"
641 << " - scale = " << Loop.Scale << "\n");
643 if (Loop.Scale > getMaxLoopScale()) {
644 Loop.Scale = getMaxLoopScale();
645 DEBUG(dbgs() << " - reduced-to-max-scale: " << getMaxLoopScale() << "\n");
649 /// \brief Package up a loop.
650 void BlockFrequencyInfoImplBase::packageLoop(LoopData &Loop) {
651 DEBUG(dbgs() << "packaging-loop: " << getLoopName(Loop) << "\n");
653 // Clear the subloop exits to prevent quadratic memory usage.
654 for (const BlockNode &M : Loop.Nodes) {
655 if (auto *Loop = Working[M.Index].getPackagedLoop())
657 DEBUG(dbgs() << " - node: " << getBlockName(M.Index) << "\n");
659 Loop.IsPackaged = true;
662 void BlockFrequencyInfoImplBase::distributeMass(const BlockNode &Source,
664 Distribution &Dist) {
665 BlockMass Mass = Working[Source.Index].getMass();
666 DEBUG(dbgs() << " => mass: " << Mass << "\n");
668 // Distribute mass to successors as laid out in Dist.
669 DitheringDistributer D(Dist, Mass);
672 auto debugAssign = [&](const BlockNode &T, const BlockMass &M,
674 dbgs() << " => assign " << M << " (" << D.RemMass << ")";
676 dbgs() << " [" << Desc << "]";
678 dbgs() << " to " << getBlockName(T);
684 for (const Weight &W : Dist.Weights) {
685 // Check for a local edge (non-backedge and non-exit).
686 BlockMass Taken = D.takeMass(W.Amount);
687 if (W.Type == Weight::Local) {
688 Working[W.TargetNode.Index].getMass() += Taken;
689 DEBUG(debugAssign(W.TargetNode, Taken, nullptr));
693 // Backedges and exits only make sense if we're processing a loop.
694 assert(OuterLoop && "backedge or exit outside of loop");
696 // Check for a backedge.
697 if (W.Type == Weight::Backedge) {
698 OuterLoop->BackedgeMass += Taken;
699 DEBUG(debugAssign(BlockNode(), Taken, "back"));
703 // This must be an exit.
704 assert(W.Type == Weight::Exit);
705 OuterLoop->Exits.push_back(std::make_pair(W.TargetNode, Taken));
706 DEBUG(debugAssign(W.TargetNode, Taken, "exit"));
710 static void convertFloatingToInteger(BlockFrequencyInfoImplBase &BFI,
711 const Float &Min, const Float &Max) {
712 // Scale the Factor to a size that creates integers. Ideally, integers would
713 // be scaled so that Max == UINT64_MAX so that they can be best
714 // differentiated. However, the register allocator currently deals poorly
715 // with large numbers. Instead, push Min up a little from 1 to give some
716 // room to differentiate small, unequal numbers.
718 // TODO: fix issues downstream so that ScalingFactor can be Float(1,64)/Max.
719 Float ScalingFactor = Min.inverse();
720 if ((Max / Min).lg() < 60)
723 // Translate the floats to integers.
724 DEBUG(dbgs() << "float-to-int: min = " << Min << ", max = " << Max
725 << ", factor = " << ScalingFactor << "\n");
726 for (size_t Index = 0; Index < BFI.Freqs.size(); ++Index) {
727 Float Scaled = BFI.Freqs[Index].Floating * ScalingFactor;
728 BFI.Freqs[Index].Integer = std::max(UINT64_C(1), Scaled.toInt<uint64_t>());
729 DEBUG(dbgs() << " - " << BFI.getBlockName(Index) << ": float = "
730 << BFI.Freqs[Index].Floating << ", scaled = " << Scaled
731 << ", int = " << BFI.Freqs[Index].Integer << "\n");
735 /// \brief Unwrap a loop package.
737 /// Visits all the members of a loop, adjusting their BlockData according to
738 /// the loop's pseudo-node.
739 static void unwrapLoop(BlockFrequencyInfoImplBase &BFI, LoopData &Loop) {
740 DEBUG(dbgs() << "unwrap-loop-package: " << BFI.getLoopName(Loop)
741 << ": mass = " << Loop.Mass << ", scale = " << Loop.Scale
743 Loop.Scale *= Loop.Mass.toFloat();
744 Loop.IsPackaged = false;
745 DEBUG(dbgs() << " => combined-scale = " << Loop.Scale << "\n");
747 // Propagate the head scale through the loop. Since members are visited in
748 // RPO, the head scale will be updated by the loop scale first, and then the
749 // final head scale will be used for updated the rest of the members.
750 for (const BlockNode &N : Loop.Nodes) {
751 const auto &Working = BFI.Working[N.Index];
752 Float &F = Working.isAPackage() ? Working.getPackagedLoop()->Scale
753 : BFI.Freqs[N.Index].Floating;
754 Float New = Loop.Scale * F;
755 DEBUG(dbgs() << " - " << BFI.getBlockName(N) << ": " << F << " => " << New
761 void BlockFrequencyInfoImplBase::unwrapLoops() {
762 // Set initial frequencies from loop-local masses.
763 for (size_t Index = 0; Index < Working.size(); ++Index)
764 Freqs[Index].Floating = Working[Index].Mass.toFloat();
766 for (LoopData &Loop : Loops)
767 unwrapLoop(*this, Loop);
770 void BlockFrequencyInfoImplBase::finalizeMetrics() {
771 // Unwrap loop packages in reverse post-order, tracking min and max
773 auto Min = Float::getLargest();
774 auto Max = Float::getZero();
775 for (size_t Index = 0; Index < Working.size(); ++Index) {
776 // Update min/max scale.
777 Min = std::min(Min, Freqs[Index].Floating);
778 Max = std::max(Max, Freqs[Index].Floating);
781 // Convert to integers.
782 convertFloatingToInteger(*this, Min, Max);
784 // Clean up data structures.
787 // Print out the final stats.
792 BlockFrequencyInfoImplBase::getBlockFreq(const BlockNode &Node) const {
795 return Freqs[Node.Index].Integer;
798 BlockFrequencyInfoImplBase::getFloatingBlockFreq(const BlockNode &Node) const {
800 return Float::getZero();
801 return Freqs[Node.Index].Floating;
805 BlockFrequencyInfoImplBase::getBlockName(const BlockNode &Node) const {
806 return std::string();
809 BlockFrequencyInfoImplBase::getLoopName(const LoopData &Loop) const {
810 return getBlockName(Loop.getHeader()) + (Loop.isIrreducible() ? "**" : "*");
814 BlockFrequencyInfoImplBase::printBlockFreq(raw_ostream &OS,
815 const BlockNode &Node) const {
816 return OS << getFloatingBlockFreq(Node);
820 BlockFrequencyInfoImplBase::printBlockFreq(raw_ostream &OS,
821 const BlockFrequency &Freq) const {
822 Float Block(Freq.getFrequency(), 0);
823 Float Entry(getEntryFreq(), 0);
825 return OS << Block / Entry;
828 void IrreducibleGraph::addNodesInLoop(const BFIBase::LoopData &OuterLoop) {
829 Start = OuterLoop.getHeader();
830 Nodes.reserve(OuterLoop.Nodes.size());
831 for (auto N : OuterLoop.Nodes)
835 void IrreducibleGraph::addNodesInFunction() {
837 for (uint32_t Index = 0; Index < BFI.Working.size(); ++Index)
838 if (!BFI.Working[Index].isPackaged())
842 void IrreducibleGraph::indexNodes() {
843 for (auto &I : Nodes)
844 Lookup[I.Node.Index] = &I;
846 void IrreducibleGraph::addEdge(IrrNode &Irr, const BlockNode &Succ,
847 const BFIBase::LoopData *OuterLoop) {
848 if (OuterLoop && OuterLoop->isHeader(Succ))
850 auto L = Lookup.find(Succ.Index);
851 if (L == Lookup.end())
853 IrrNode &SuccIrr = *L->second;
854 Irr.Edges.push_back(&SuccIrr);
855 SuccIrr.Edges.push_front(&Irr);
860 template <> struct GraphTraits<IrreducibleGraph> {
861 typedef bfi_detail::IrreducibleGraph GraphT;
863 typedef const GraphT::IrrNode NodeType;
864 typedef GraphT::IrrNode::iterator ChildIteratorType;
866 static const NodeType *getEntryNode(const GraphT &G) {
869 static ChildIteratorType child_begin(NodeType *N) { return N->succ_begin(); }
870 static ChildIteratorType child_end(NodeType *N) { return N->succ_end(); }
874 /// \brief Find extra irreducible headers.
876 /// Find entry blocks and other blocks with backedges, which exist when \c G
877 /// contains irreducible sub-SCCs.
878 static void findIrreducibleHeaders(
879 const BlockFrequencyInfoImplBase &BFI,
880 const IrreducibleGraph &G,
881 const std::vector<const IrreducibleGraph::IrrNode *> &SCC,
882 LoopData::NodeList &Headers, LoopData::NodeList &Others) {
883 // Map from nodes in the SCC to whether it's an entry block.
884 SmallDenseMap<const IrreducibleGraph::IrrNode *, bool, 8> InSCC;
886 // InSCC also acts the set of nodes in the graph. Seed it.
887 for (const auto *I : SCC)
890 for (auto I = InSCC.begin(), E = InSCC.end(); I != E; ++I) {
891 auto &Irr = *I->first;
892 for (const auto *P : make_range(Irr.pred_begin(), Irr.pred_end())) {
896 // This is an entry block.
898 Headers.push_back(Irr.Node);
899 DEBUG(dbgs() << " => entry = " << BFI.getBlockName(Irr.Node) << "\n");
903 assert(Headers.size() >= 2 && "Should be irreducible");
904 if (Headers.size() == InSCC.size()) {
905 // Every block is a header.
906 std::sort(Headers.begin(), Headers.end());
910 // Look for extra headers from irreducible sub-SCCs.
911 for (const auto &I : InSCC) {
912 // Entry blocks are already headers.
916 auto &Irr = *I.first;
917 for (const auto *P : make_range(Irr.pred_begin(), Irr.pred_end())) {
918 // Skip forward edges.
919 if (P->Node < Irr.Node)
922 // Skip predecessors from entry blocks. These can have inverted
927 // Store the extra header.
928 Headers.push_back(Irr.Node);
929 DEBUG(dbgs() << " => extra = " << BFI.getBlockName(Irr.Node) << "\n");
932 if (Headers.back() == Irr.Node)
933 // Added this as a header.
936 // This is not a header.
937 Others.push_back(Irr.Node);
938 DEBUG(dbgs() << " => other = " << BFI.getBlockName(Irr.Node) << "\n");
940 std::sort(Headers.begin(), Headers.end());
941 std::sort(Others.begin(), Others.end());
944 static void createIrreducibleLoop(
945 BlockFrequencyInfoImplBase &BFI, const IrreducibleGraph &G,
946 LoopData *OuterLoop, std::list<LoopData>::iterator Insert,
947 const std::vector<const IrreducibleGraph::IrrNode *> &SCC) {
948 // Translate the SCC into RPO.
949 DEBUG(dbgs() << " - found-scc\n");
951 LoopData::NodeList Headers;
952 LoopData::NodeList Others;
953 findIrreducibleHeaders(BFI, G, SCC, Headers, Others);
955 auto Loop = BFI.Loops.emplace(Insert, OuterLoop, Headers.begin(),
956 Headers.end(), Others.begin(), Others.end());
958 // Update loop hierarchy.
959 for (const auto &N : Loop->Nodes)
960 if (BFI.Working[N.Index].isLoopHeader())
961 BFI.Working[N.Index].Loop->Parent = &*Loop;
963 BFI.Working[N.Index].Loop = &*Loop;
966 iterator_range<std::list<LoopData>::iterator>
967 BlockFrequencyInfoImplBase::analyzeIrreducible(
968 const IrreducibleGraph &G, LoopData *OuterLoop,
969 std::list<LoopData>::iterator Insert) {
970 assert((OuterLoop == nullptr) == (Insert == Loops.begin()));
971 auto Prev = OuterLoop ? std::prev(Insert) : Loops.end();
973 for (auto I = scc_begin(G); !I.isAtEnd(); ++I) {
977 // Translate the SCC into RPO.
978 createIrreducibleLoop(*this, G, OuterLoop, Insert, *I);
982 return make_range(std::next(Prev), Insert);
983 return make_range(Loops.begin(), Insert);
987 BlockFrequencyInfoImplBase::updateLoopWithIrreducible(LoopData &OuterLoop) {
988 OuterLoop.Exits.clear();
989 OuterLoop.BackedgeMass = BlockMass::getEmpty();
990 auto O = OuterLoop.Nodes.begin() + 1;
991 for (auto I = O, E = OuterLoop.Nodes.end(); I != E; ++I)
992 if (!Working[I->Index].isPackaged())
994 OuterLoop.Nodes.erase(O, OuterLoop.Nodes.end());