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 // ScaledNumber implementation.
29 //===----------------------------------------------------------------------===//
31 const int32_t ScaledNumberBase::MaxScale;
32 const int32_t ScaledNumberBase::MinScale;
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 >= ScaledNumberBase::MinScale);
62 assert(E <= ScaledNumberBase::MaxScale);
64 // Find a new E, but don't let it increase past MaxScale.
65 int LeadingZeros = ScaledNumberBase::countLeadingZeros64(D);
66 int NewE = std::min(ScaledNumberBase::MaxScale, E + 63 - LeadingZeros);
67 int Shift = 63 - (NewE - E);
68 assert(Shift <= LeadingZeros);
69 assert(Shift == LeadingZeros || NewE == ScaledNumberBase::MaxScale);
73 // Check for a denormal.
74 unsigned AdjustedE = E + 16383;
76 assert(E == ScaledNumberBase::MaxScale);
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 ScaledNumberBase::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 &ScaledNumberBase::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 ScaledNumberBase::dump(uint64_t D, int16_t E, int Width) {
215 print(dbgs(), D, E, Width, 0) << "[" << Width << ":" << D << "*2^" << E
219 //===----------------------------------------------------------------------===//
221 // BlockMass implementation.
223 //===----------------------------------------------------------------------===//
224 ScaledNumber<uint64_t> BlockMass::toFloat() const {
226 return ScaledNumber<uint64_t>(1, 0);
227 return ScaledNumber<uint64_t>(getMass() + 1, -64);
230 void BlockMass::dump() const { print(dbgs()); }
232 static char getHexDigit(int N) {
238 raw_ostream &BlockMass::print(raw_ostream &OS) const {
239 for (int Digits = 0; Digits < 16; ++Digits)
240 OS << getHexDigit(Mass >> (60 - Digits * 4) & 0xf);
244 //===----------------------------------------------------------------------===//
246 // BlockFrequencyInfoImpl implementation.
248 //===----------------------------------------------------------------------===//
251 typedef BlockFrequencyInfoImplBase::BlockNode BlockNode;
252 typedef BlockFrequencyInfoImplBase::Distribution Distribution;
253 typedef BlockFrequencyInfoImplBase::Distribution::WeightList WeightList;
254 typedef BlockFrequencyInfoImplBase::Float Float;
255 typedef BlockFrequencyInfoImplBase::LoopData LoopData;
256 typedef BlockFrequencyInfoImplBase::Weight Weight;
257 typedef BlockFrequencyInfoImplBase::FrequencyData FrequencyData;
259 /// \brief Dithering mass distributer.
261 /// This class splits up a single mass into portions by weight, dithering to
262 /// spread out error. No mass is lost. The dithering precision depends on the
263 /// precision of the product of \a BlockMass and \a BranchProbability.
265 /// The distribution algorithm follows.
267 /// 1. Initialize by saving the sum of the weights in \a RemWeight and the
268 /// mass to distribute in \a RemMass.
270 /// 2. For each portion:
272 /// 1. Construct a branch probability, P, as the portion's weight divided
273 /// by the current value of \a RemWeight.
274 /// 2. Calculate the portion's mass as \a RemMass times P.
275 /// 3. Update \a RemWeight and \a RemMass at each portion by subtracting
276 /// the current portion's weight and mass.
277 struct DitheringDistributer {
281 DitheringDistributer(Distribution &Dist, const BlockMass &Mass);
283 BlockMass takeMass(uint32_t Weight);
287 DitheringDistributer::DitheringDistributer(Distribution &Dist,
288 const BlockMass &Mass) {
290 RemWeight = Dist.Total;
294 BlockMass DitheringDistributer::takeMass(uint32_t Weight) {
295 assert(Weight && "invalid weight");
296 assert(Weight <= RemWeight);
297 BlockMass Mass = RemMass * BranchProbability(Weight, RemWeight);
299 // Decrement totals (dither).
305 void Distribution::add(const BlockNode &Node, uint64_t Amount,
306 Weight::DistType Type) {
307 assert(Amount && "invalid weight of 0");
308 uint64_t NewTotal = Total + Amount;
310 // Check for overflow. It should be impossible to overflow twice.
311 bool IsOverflow = NewTotal < Total;
312 assert(!(DidOverflow && IsOverflow) && "unexpected repeated overflow");
313 DidOverflow |= IsOverflow;
323 Weights.push_back(W);
326 static void combineWeight(Weight &W, const Weight &OtherW) {
327 assert(OtherW.TargetNode.isValid());
332 assert(W.Type == OtherW.Type);
333 assert(W.TargetNode == OtherW.TargetNode);
334 assert(W.Amount < W.Amount + OtherW.Amount && "Unexpected overflow");
335 W.Amount += OtherW.Amount;
337 static void combineWeightsBySorting(WeightList &Weights) {
338 // Sort so edges to the same node are adjacent.
339 std::sort(Weights.begin(), Weights.end(),
341 const Weight &R) { return L.TargetNode < R.TargetNode; });
343 // Combine adjacent edges.
344 WeightList::iterator O = Weights.begin();
345 for (WeightList::const_iterator I = O, L = O, E = Weights.end(); I != E;
349 // Find the adjacent weights to the same node.
350 for (++L; L != E && I->TargetNode == L->TargetNode; ++L)
351 combineWeight(*O, *L);
354 // Erase extra entries.
355 Weights.erase(O, Weights.end());
358 static void combineWeightsByHashing(WeightList &Weights) {
359 // Collect weights into a DenseMap.
360 typedef DenseMap<BlockNode::IndexType, Weight> HashTable;
361 HashTable Combined(NextPowerOf2(2 * Weights.size()));
362 for (const Weight &W : Weights)
363 combineWeight(Combined[W.TargetNode.Index], W);
365 // Check whether anything changed.
366 if (Weights.size() == Combined.size())
369 // Fill in the new weights.
371 Weights.reserve(Combined.size());
372 for (const auto &I : Combined)
373 Weights.push_back(I.second);
375 static void combineWeights(WeightList &Weights) {
376 // Use a hash table for many successors to keep this linear.
377 if (Weights.size() > 128) {
378 combineWeightsByHashing(Weights);
382 combineWeightsBySorting(Weights);
384 static uint64_t shiftRightAndRound(uint64_t N, int Shift) {
389 return (N >> Shift) + (UINT64_C(1) & N >> (Shift - 1));
391 void Distribution::normalize() {
392 // Early exit for termination nodes.
396 // Only bother if there are multiple successors.
397 if (Weights.size() > 1)
398 combineWeights(Weights);
400 // Early exit when combined into a single successor.
401 if (Weights.size() == 1) {
403 Weights.front().Amount = 1;
407 // Determine how much to shift right so that the total fits into 32-bits.
409 // If we shift at all, shift by 1 extra. Otherwise, the lower limit of 1
410 // for each weight can cause a 32-bit overflow.
414 else if (Total > UINT32_MAX)
415 Shift = 33 - countLeadingZeros(Total);
417 // Early exit if nothing needs to be scaled.
421 // Recompute the total through accumulation (rather than shifting it) so that
422 // it's accurate after shifting.
425 // Sum the weights to each node and shift right if necessary.
426 for (Weight &W : Weights) {
427 // Scale down below UINT32_MAX. Since Shift is larger than necessary, we
428 // can round here without concern about overflow.
429 assert(W.TargetNode.isValid());
430 W.Amount = std::max(UINT64_C(1), shiftRightAndRound(W.Amount, Shift));
431 assert(W.Amount <= UINT32_MAX);
436 assert(Total <= UINT32_MAX);
439 void BlockFrequencyInfoImplBase::clear() {
440 // Swap with a default-constructed std::vector, since std::vector<>::clear()
441 // does not actually clear heap storage.
442 std::vector<FrequencyData>().swap(Freqs);
443 std::vector<WorkingData>().swap(Working);
447 /// \brief Clear all memory not needed downstream.
449 /// Releases all memory not used downstream. In particular, saves Freqs.
450 static void cleanup(BlockFrequencyInfoImplBase &BFI) {
451 std::vector<FrequencyData> SavedFreqs(std::move(BFI.Freqs));
453 BFI.Freqs = std::move(SavedFreqs);
456 bool BlockFrequencyInfoImplBase::addToDist(Distribution &Dist,
457 const LoopData *OuterLoop,
458 const BlockNode &Pred,
459 const BlockNode &Succ,
464 auto isLoopHeader = [&OuterLoop](const BlockNode &Node) {
465 return OuterLoop && OuterLoop->isHeader(Node);
468 BlockNode Resolved = Working[Succ.Index].getResolvedNode();
471 auto debugSuccessor = [&](const char *Type) {
473 << " [" << Type << "] weight = " << Weight;
474 if (!isLoopHeader(Resolved))
475 dbgs() << ", succ = " << getBlockName(Succ);
476 if (Resolved != Succ)
477 dbgs() << ", resolved = " << getBlockName(Resolved);
480 (void)debugSuccessor;
483 if (isLoopHeader(Resolved)) {
484 DEBUG(debugSuccessor("backedge"));
485 Dist.addBackedge(OuterLoop->getHeader(), Weight);
489 if (Working[Resolved.Index].getContainingLoop() != OuterLoop) {
490 DEBUG(debugSuccessor(" exit "));
491 Dist.addExit(Resolved, Weight);
495 if (Resolved < Pred) {
496 if (!isLoopHeader(Pred)) {
497 // If OuterLoop is an irreducible loop, we can't actually handle this.
498 assert((!OuterLoop || !OuterLoop->isIrreducible()) &&
499 "unhandled irreducible control flow");
501 // Irreducible backedge. Abort.
502 DEBUG(debugSuccessor("abort!!!"));
506 // If "Pred" is a loop header, then this isn't really a backedge; rather,
507 // OuterLoop must be irreducible. These false backedges can come only from
508 // secondary loop headers.
509 assert(OuterLoop && OuterLoop->isIrreducible() && !isLoopHeader(Resolved) &&
510 "unhandled irreducible control flow");
513 DEBUG(debugSuccessor(" local "));
514 Dist.addLocal(Resolved, Weight);
518 bool BlockFrequencyInfoImplBase::addLoopSuccessorsToDist(
519 const LoopData *OuterLoop, LoopData &Loop, Distribution &Dist) {
520 // Copy the exit map into Dist.
521 for (const auto &I : Loop.Exits)
522 if (!addToDist(Dist, OuterLoop, Loop.getHeader(), I.first,
524 // Irreducible backedge.
530 /// \brief Get the maximum allowed loop scale.
532 /// Gives the maximum number of estimated iterations allowed for a loop. Very
533 /// large numbers cause problems downstream (even within 64-bits).
534 static Float getMaxLoopScale() { return Float(1, 12); }
536 /// \brief Compute the loop scale for a loop.
537 void BlockFrequencyInfoImplBase::computeLoopScale(LoopData &Loop) {
538 // Compute loop scale.
539 DEBUG(dbgs() << "compute-loop-scale: " << getLoopName(Loop) << "\n");
541 // LoopScale == 1 / ExitMass
542 // ExitMass == HeadMass - BackedgeMass
543 BlockMass ExitMass = BlockMass::getFull() - Loop.BackedgeMass;
545 // Block scale stores the inverse of the scale.
546 Loop.Scale = ExitMass.toFloat().inverse();
548 DEBUG(dbgs() << " - exit-mass = " << ExitMass << " (" << BlockMass::getFull()
549 << " - " << Loop.BackedgeMass << ")\n"
550 << " - scale = " << Loop.Scale << "\n");
552 if (Loop.Scale > getMaxLoopScale()) {
553 Loop.Scale = getMaxLoopScale();
554 DEBUG(dbgs() << " - reduced-to-max-scale: " << getMaxLoopScale() << "\n");
558 /// \brief Package up a loop.
559 void BlockFrequencyInfoImplBase::packageLoop(LoopData &Loop) {
560 DEBUG(dbgs() << "packaging-loop: " << getLoopName(Loop) << "\n");
562 // Clear the subloop exits to prevent quadratic memory usage.
563 for (const BlockNode &M : Loop.Nodes) {
564 if (auto *Loop = Working[M.Index].getPackagedLoop())
566 DEBUG(dbgs() << " - node: " << getBlockName(M.Index) << "\n");
568 Loop.IsPackaged = true;
571 void BlockFrequencyInfoImplBase::distributeMass(const BlockNode &Source,
573 Distribution &Dist) {
574 BlockMass Mass = Working[Source.Index].getMass();
575 DEBUG(dbgs() << " => mass: " << Mass << "\n");
577 // Distribute mass to successors as laid out in Dist.
578 DitheringDistributer D(Dist, Mass);
581 auto debugAssign = [&](const BlockNode &T, const BlockMass &M,
583 dbgs() << " => assign " << M << " (" << D.RemMass << ")";
585 dbgs() << " [" << Desc << "]";
587 dbgs() << " to " << getBlockName(T);
593 for (const Weight &W : Dist.Weights) {
594 // Check for a local edge (non-backedge and non-exit).
595 BlockMass Taken = D.takeMass(W.Amount);
596 if (W.Type == Weight::Local) {
597 Working[W.TargetNode.Index].getMass() += Taken;
598 DEBUG(debugAssign(W.TargetNode, Taken, nullptr));
602 // Backedges and exits only make sense if we're processing a loop.
603 assert(OuterLoop && "backedge or exit outside of loop");
605 // Check for a backedge.
606 if (W.Type == Weight::Backedge) {
607 OuterLoop->BackedgeMass += Taken;
608 DEBUG(debugAssign(BlockNode(), Taken, "back"));
612 // This must be an exit.
613 assert(W.Type == Weight::Exit);
614 OuterLoop->Exits.push_back(std::make_pair(W.TargetNode, Taken));
615 DEBUG(debugAssign(W.TargetNode, Taken, "exit"));
619 static void convertFloatingToInteger(BlockFrequencyInfoImplBase &BFI,
620 const Float &Min, const Float &Max) {
621 // Scale the Factor to a size that creates integers. Ideally, integers would
622 // be scaled so that Max == UINT64_MAX so that they can be best
623 // differentiated. However, the register allocator currently deals poorly
624 // with large numbers. Instead, push Min up a little from 1 to give some
625 // room to differentiate small, unequal numbers.
627 // TODO: fix issues downstream so that ScalingFactor can be Float(1,64)/Max.
628 Float ScalingFactor = Min.inverse();
629 if ((Max / Min).lg() < 60)
632 // Translate the floats to integers.
633 DEBUG(dbgs() << "float-to-int: min = " << Min << ", max = " << Max
634 << ", factor = " << ScalingFactor << "\n");
635 for (size_t Index = 0; Index < BFI.Freqs.size(); ++Index) {
636 Float Scaled = BFI.Freqs[Index].Floating * ScalingFactor;
637 BFI.Freqs[Index].Integer = std::max(UINT64_C(1), Scaled.toInt<uint64_t>());
638 DEBUG(dbgs() << " - " << BFI.getBlockName(Index) << ": float = "
639 << BFI.Freqs[Index].Floating << ", scaled = " << Scaled
640 << ", int = " << BFI.Freqs[Index].Integer << "\n");
644 /// \brief Unwrap a loop package.
646 /// Visits all the members of a loop, adjusting their BlockData according to
647 /// the loop's pseudo-node.
648 static void unwrapLoop(BlockFrequencyInfoImplBase &BFI, LoopData &Loop) {
649 DEBUG(dbgs() << "unwrap-loop-package: " << BFI.getLoopName(Loop)
650 << ": mass = " << Loop.Mass << ", scale = " << Loop.Scale
652 Loop.Scale *= Loop.Mass.toFloat();
653 Loop.IsPackaged = false;
654 DEBUG(dbgs() << " => combined-scale = " << Loop.Scale << "\n");
656 // Propagate the head scale through the loop. Since members are visited in
657 // RPO, the head scale will be updated by the loop scale first, and then the
658 // final head scale will be used for updated the rest of the members.
659 for (const BlockNode &N : Loop.Nodes) {
660 const auto &Working = BFI.Working[N.Index];
661 Float &F = Working.isAPackage() ? Working.getPackagedLoop()->Scale
662 : BFI.Freqs[N.Index].Floating;
663 Float New = Loop.Scale * F;
664 DEBUG(dbgs() << " - " << BFI.getBlockName(N) << ": " << F << " => " << New
670 void BlockFrequencyInfoImplBase::unwrapLoops() {
671 // Set initial frequencies from loop-local masses.
672 for (size_t Index = 0; Index < Working.size(); ++Index)
673 Freqs[Index].Floating = Working[Index].Mass.toFloat();
675 for (LoopData &Loop : Loops)
676 unwrapLoop(*this, Loop);
679 void BlockFrequencyInfoImplBase::finalizeMetrics() {
680 // Unwrap loop packages in reverse post-order, tracking min and max
682 auto Min = Float::getLargest();
683 auto Max = Float::getZero();
684 for (size_t Index = 0; Index < Working.size(); ++Index) {
685 // Update min/max scale.
686 Min = std::min(Min, Freqs[Index].Floating);
687 Max = std::max(Max, Freqs[Index].Floating);
690 // Convert to integers.
691 convertFloatingToInteger(*this, Min, Max);
693 // Clean up data structures.
696 // Print out the final stats.
701 BlockFrequencyInfoImplBase::getBlockFreq(const BlockNode &Node) const {
704 return Freqs[Node.Index].Integer;
707 BlockFrequencyInfoImplBase::getFloatingBlockFreq(const BlockNode &Node) const {
709 return Float::getZero();
710 return Freqs[Node.Index].Floating;
714 BlockFrequencyInfoImplBase::getBlockName(const BlockNode &Node) const {
715 return std::string();
718 BlockFrequencyInfoImplBase::getLoopName(const LoopData &Loop) const {
719 return getBlockName(Loop.getHeader()) + (Loop.isIrreducible() ? "**" : "*");
723 BlockFrequencyInfoImplBase::printBlockFreq(raw_ostream &OS,
724 const BlockNode &Node) const {
725 return OS << getFloatingBlockFreq(Node);
729 BlockFrequencyInfoImplBase::printBlockFreq(raw_ostream &OS,
730 const BlockFrequency &Freq) const {
731 Float Block(Freq.getFrequency(), 0);
732 Float Entry(getEntryFreq(), 0);
734 return OS << Block / Entry;
737 void IrreducibleGraph::addNodesInLoop(const BFIBase::LoopData &OuterLoop) {
738 Start = OuterLoop.getHeader();
739 Nodes.reserve(OuterLoop.Nodes.size());
740 for (auto N : OuterLoop.Nodes)
744 void IrreducibleGraph::addNodesInFunction() {
746 for (uint32_t Index = 0; Index < BFI.Working.size(); ++Index)
747 if (!BFI.Working[Index].isPackaged())
751 void IrreducibleGraph::indexNodes() {
752 for (auto &I : Nodes)
753 Lookup[I.Node.Index] = &I;
755 void IrreducibleGraph::addEdge(IrrNode &Irr, const BlockNode &Succ,
756 const BFIBase::LoopData *OuterLoop) {
757 if (OuterLoop && OuterLoop->isHeader(Succ))
759 auto L = Lookup.find(Succ.Index);
760 if (L == Lookup.end())
762 IrrNode &SuccIrr = *L->second;
763 Irr.Edges.push_back(&SuccIrr);
764 SuccIrr.Edges.push_front(&Irr);
769 template <> struct GraphTraits<IrreducibleGraph> {
770 typedef bfi_detail::IrreducibleGraph GraphT;
772 typedef const GraphT::IrrNode NodeType;
773 typedef GraphT::IrrNode::iterator ChildIteratorType;
775 static const NodeType *getEntryNode(const GraphT &G) {
778 static ChildIteratorType child_begin(NodeType *N) { return N->succ_begin(); }
779 static ChildIteratorType child_end(NodeType *N) { return N->succ_end(); }
783 /// \brief Find extra irreducible headers.
785 /// Find entry blocks and other blocks with backedges, which exist when \c G
786 /// contains irreducible sub-SCCs.
787 static void findIrreducibleHeaders(
788 const BlockFrequencyInfoImplBase &BFI,
789 const IrreducibleGraph &G,
790 const std::vector<const IrreducibleGraph::IrrNode *> &SCC,
791 LoopData::NodeList &Headers, LoopData::NodeList &Others) {
792 // Map from nodes in the SCC to whether it's an entry block.
793 SmallDenseMap<const IrreducibleGraph::IrrNode *, bool, 8> InSCC;
795 // InSCC also acts the set of nodes in the graph. Seed it.
796 for (const auto *I : SCC)
799 for (auto I = InSCC.begin(), E = InSCC.end(); I != E; ++I) {
800 auto &Irr = *I->first;
801 for (const auto *P : make_range(Irr.pred_begin(), Irr.pred_end())) {
805 // This is an entry block.
807 Headers.push_back(Irr.Node);
808 DEBUG(dbgs() << " => entry = " << BFI.getBlockName(Irr.Node) << "\n");
812 assert(Headers.size() >= 2 && "Should be irreducible");
813 if (Headers.size() == InSCC.size()) {
814 // Every block is a header.
815 std::sort(Headers.begin(), Headers.end());
819 // Look for extra headers from irreducible sub-SCCs.
820 for (const auto &I : InSCC) {
821 // Entry blocks are already headers.
825 auto &Irr = *I.first;
826 for (const auto *P : make_range(Irr.pred_begin(), Irr.pred_end())) {
827 // Skip forward edges.
828 if (P->Node < Irr.Node)
831 // Skip predecessors from entry blocks. These can have inverted
836 // Store the extra header.
837 Headers.push_back(Irr.Node);
838 DEBUG(dbgs() << " => extra = " << BFI.getBlockName(Irr.Node) << "\n");
841 if (Headers.back() == Irr.Node)
842 // Added this as a header.
845 // This is not a header.
846 Others.push_back(Irr.Node);
847 DEBUG(dbgs() << " => other = " << BFI.getBlockName(Irr.Node) << "\n");
849 std::sort(Headers.begin(), Headers.end());
850 std::sort(Others.begin(), Others.end());
853 static void createIrreducibleLoop(
854 BlockFrequencyInfoImplBase &BFI, const IrreducibleGraph &G,
855 LoopData *OuterLoop, std::list<LoopData>::iterator Insert,
856 const std::vector<const IrreducibleGraph::IrrNode *> &SCC) {
857 // Translate the SCC into RPO.
858 DEBUG(dbgs() << " - found-scc\n");
860 LoopData::NodeList Headers;
861 LoopData::NodeList Others;
862 findIrreducibleHeaders(BFI, G, SCC, Headers, Others);
864 auto Loop = BFI.Loops.emplace(Insert, OuterLoop, Headers.begin(),
865 Headers.end(), Others.begin(), Others.end());
867 // Update loop hierarchy.
868 for (const auto &N : Loop->Nodes)
869 if (BFI.Working[N.Index].isLoopHeader())
870 BFI.Working[N.Index].Loop->Parent = &*Loop;
872 BFI.Working[N.Index].Loop = &*Loop;
875 iterator_range<std::list<LoopData>::iterator>
876 BlockFrequencyInfoImplBase::analyzeIrreducible(
877 const IrreducibleGraph &G, LoopData *OuterLoop,
878 std::list<LoopData>::iterator Insert) {
879 assert((OuterLoop == nullptr) == (Insert == Loops.begin()));
880 auto Prev = OuterLoop ? std::prev(Insert) : Loops.end();
882 for (auto I = scc_begin(G); !I.isAtEnd(); ++I) {
886 // Translate the SCC into RPO.
887 createIrreducibleLoop(*this, G, OuterLoop, Insert, *I);
891 return make_range(std::next(Prev), Insert);
892 return make_range(Loops.begin(), Insert);
896 BlockFrequencyInfoImplBase::updateLoopWithIrreducible(LoopData &OuterLoop) {
897 OuterLoop.Exits.clear();
898 OuterLoop.BackedgeMass = BlockMass::getEmpty();
899 auto O = OuterLoop.Nodes.begin() + 1;
900 for (auto I = O, E = OuterLoop.Nodes.end(); I != E; ++I)
901 if (!Working[I->Index].isPackaged())
903 OuterLoop.Nodes.erase(O, OuterLoop.Nodes.end());