BFI: Clean up BlockMass
[oota-llvm.git] / lib / Analysis / BlockFrequencyInfoImpl.cpp
1 //===- BlockFrequencyImplInfo.cpp - Block Frequency Info Implementation ---===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // Loops should be simplified before this analysis.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/Analysis/BlockFrequencyInfoImpl.h"
15 #include "llvm/ADT/SCCIterator.h"
16 #include "llvm/Support/raw_ostream.h"
17 #include <deque>
18
19 using namespace llvm;
20 using namespace llvm::bfi_detail;
21
22 #define DEBUG_TYPE "block-freq"
23
24 ScaledNumber<uint64_t> BlockMass::toScaled() const {
25   if (isFull())
26     return ScaledNumber<uint64_t>(1, 0);
27   return ScaledNumber<uint64_t>(getMass() + 1, -64);
28 }
29
30 void BlockMass::dump() const { print(dbgs()); }
31
32 static char getHexDigit(int N) {
33   assert(N < 16);
34   if (N < 10)
35     return '0' + N;
36   return 'a' + N - 10;
37 }
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);
41   return OS;
42 }
43
44 namespace {
45
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;
53
54 /// \brief Dithering mass distributer.
55 ///
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.
59 ///
60 /// The distribution algorithm follows.
61 ///
62 ///  1. Initialize by saving the sum of the weights in \a RemWeight and the
63 ///     mass to distribute in \a RemMass.
64 ///
65 ///  2. For each portion:
66 ///
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 {
73   uint32_t RemWeight;
74   BlockMass RemMass;
75
76   DitheringDistributer(Distribution &Dist, const BlockMass &Mass);
77
78   BlockMass takeMass(uint32_t Weight);
79 };
80
81 } // end namespace
82
83 DitheringDistributer::DitheringDistributer(Distribution &Dist,
84                                            const BlockMass &Mass) {
85   Dist.normalize();
86   RemWeight = Dist.Total;
87   RemMass = Mass;
88 }
89
90 BlockMass DitheringDistributer::takeMass(uint32_t Weight) {
91   assert(Weight && "invalid weight");
92   assert(Weight <= RemWeight);
93   BlockMass Mass = RemMass * BranchProbability(Weight, RemWeight);
94
95   // Decrement totals (dither).
96   RemWeight -= Weight;
97   RemMass -= Mass;
98   return Mass;
99 }
100
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;
105
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;
110
111   // Update the total.
112   Total = NewTotal;
113
114   // Save the weight.
115   Weight W;
116   W.TargetNode = Node;
117   W.Amount = Amount;
118   W.Type = Type;
119   Weights.push_back(W);
120 }
121
122 static void combineWeight(Weight &W, const Weight &OtherW) {
123   assert(OtherW.TargetNode.isValid());
124   if (!W.Amount) {
125     W = OtherW;
126     return;
127   }
128   assert(W.Type == OtherW.Type);
129   assert(W.TargetNode == OtherW.TargetNode);
130   assert(W.Amount < W.Amount + OtherW.Amount && "Unexpected overflow");
131   W.Amount += OtherW.Amount;
132 }
133 static void combineWeightsBySorting(WeightList &Weights) {
134   // Sort so edges to the same node are adjacent.
135   std::sort(Weights.begin(), Weights.end(),
136             [](const Weight &L,
137                const Weight &R) { return L.TargetNode < R.TargetNode; });
138
139   // Combine adjacent edges.
140   WeightList::iterator O = Weights.begin();
141   for (WeightList::const_iterator I = O, L = O, E = Weights.end(); I != E;
142        ++O, (I = L)) {
143     *O = *I;
144
145     // Find the adjacent weights to the same node.
146     for (++L; L != E && I->TargetNode == L->TargetNode; ++L)
147       combineWeight(*O, *L);
148   }
149
150   // Erase extra entries.
151   Weights.erase(O, Weights.end());
152   return;
153 }
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);
160
161   // Check whether anything changed.
162   if (Weights.size() == Combined.size())
163     return;
164
165   // Fill in the new weights.
166   Weights.clear();
167   Weights.reserve(Combined.size());
168   for (const auto &I : Combined)
169     Weights.push_back(I.second);
170 }
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);
175     return;
176   }
177
178   combineWeightsBySorting(Weights);
179 }
180 static uint64_t shiftRightAndRound(uint64_t N, int Shift) {
181   assert(Shift >= 0);
182   assert(Shift < 64);
183   if (!Shift)
184     return N;
185   return (N >> Shift) + (UINT64_C(1) & N >> (Shift - 1));
186 }
187 void Distribution::normalize() {
188   // Early exit for termination nodes.
189   if (Weights.empty())
190     return;
191
192   // Only bother if there are multiple successors.
193   if (Weights.size() > 1)
194     combineWeights(Weights);
195
196   // Early exit when combined into a single successor.
197   if (Weights.size() == 1) {
198     Total = 1;
199     Weights.front().Amount = 1;
200     return;
201   }
202
203   // Determine how much to shift right so that the total fits into 32-bits.
204   //
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.
207   int Shift = 0;
208   if (DidOverflow)
209     Shift = 33;
210   else if (Total > UINT32_MAX)
211     Shift = 33 - countLeadingZeros(Total);
212
213   // Early exit if nothing needs to be scaled.
214   if (!Shift)
215     return;
216
217   // Recompute the total through accumulation (rather than shifting it) so that
218   // it's accurate after shifting.
219   Total = 0;
220
221   // Sum the weights to each node and shift right if necessary.
222   for (Weight &W : Weights) {
223     // Scale down below UINT32_MAX.  Since Shift is larger than necessary, we
224     // can round here without concern about overflow.
225     assert(W.TargetNode.isValid());
226     W.Amount = std::max(UINT64_C(1), shiftRightAndRound(W.Amount, Shift));
227     assert(W.Amount <= UINT32_MAX);
228
229     // Update the total.
230     Total += W.Amount;
231   }
232   assert(Total <= UINT32_MAX);
233 }
234
235 void BlockFrequencyInfoImplBase::clear() {
236   // Swap with a default-constructed std::vector, since std::vector<>::clear()
237   // does not actually clear heap storage.
238   std::vector<FrequencyData>().swap(Freqs);
239   std::vector<WorkingData>().swap(Working);
240   Loops.clear();
241 }
242
243 /// \brief Clear all memory not needed downstream.
244 ///
245 /// Releases all memory not used downstream.  In particular, saves Freqs.
246 static void cleanup(BlockFrequencyInfoImplBase &BFI) {
247   std::vector<FrequencyData> SavedFreqs(std::move(BFI.Freqs));
248   BFI.clear();
249   BFI.Freqs = std::move(SavedFreqs);
250 }
251
252 bool BlockFrequencyInfoImplBase::addToDist(Distribution &Dist,
253                                            const LoopData *OuterLoop,
254                                            const BlockNode &Pred,
255                                            const BlockNode &Succ,
256                                            uint64_t Weight) {
257   if (!Weight)
258     Weight = 1;
259
260   auto isLoopHeader = [&OuterLoop](const BlockNode &Node) {
261     return OuterLoop && OuterLoop->isHeader(Node);
262   };
263
264   BlockNode Resolved = Working[Succ.Index].getResolvedNode();
265
266 #ifndef NDEBUG
267   auto debugSuccessor = [&](const char *Type) {
268     dbgs() << "  =>"
269            << " [" << Type << "] weight = " << Weight;
270     if (!isLoopHeader(Resolved))
271       dbgs() << ", succ = " << getBlockName(Succ);
272     if (Resolved != Succ)
273       dbgs() << ", resolved = " << getBlockName(Resolved);
274     dbgs() << "\n";
275   };
276   (void)debugSuccessor;
277 #endif
278
279   if (isLoopHeader(Resolved)) {
280     DEBUG(debugSuccessor("backedge"));
281     Dist.addBackedge(OuterLoop->getHeader(), Weight);
282     return true;
283   }
284
285   if (Working[Resolved.Index].getContainingLoop() != OuterLoop) {
286     DEBUG(debugSuccessor("  exit  "));
287     Dist.addExit(Resolved, Weight);
288     return true;
289   }
290
291   if (Resolved < Pred) {
292     if (!isLoopHeader(Pred)) {
293       // If OuterLoop is an irreducible loop, we can't actually handle this.
294       assert((!OuterLoop || !OuterLoop->isIrreducible()) &&
295              "unhandled irreducible control flow");
296
297       // Irreducible backedge.  Abort.
298       DEBUG(debugSuccessor("abort!!!"));
299       return false;
300     }
301
302     // If "Pred" is a loop header, then this isn't really a backedge; rather,
303     // OuterLoop must be irreducible.  These false backedges can come only from
304     // secondary loop headers.
305     assert(OuterLoop && OuterLoop->isIrreducible() && !isLoopHeader(Resolved) &&
306            "unhandled irreducible control flow");
307   }
308
309   DEBUG(debugSuccessor(" local  "));
310   Dist.addLocal(Resolved, Weight);
311   return true;
312 }
313
314 bool BlockFrequencyInfoImplBase::addLoopSuccessorsToDist(
315     const LoopData *OuterLoop, LoopData &Loop, Distribution &Dist) {
316   // Copy the exit map into Dist.
317   for (const auto &I : Loop.Exits)
318     if (!addToDist(Dist, OuterLoop, Loop.getHeader(), I.first,
319                    I.second.getMass()))
320       // Irreducible backedge.
321       return false;
322
323   return true;
324 }
325
326 /// \brief Get the maximum allowed loop scale.
327 ///
328 /// Gives the maximum number of estimated iterations allowed for a loop.  Very
329 /// large numbers cause problems downstream (even within 64-bits).
330 static Scaled64 getMaxLoopScale() { return Scaled64(1, 12); }
331
332 /// \brief Compute the loop scale for a loop.
333 void BlockFrequencyInfoImplBase::computeLoopScale(LoopData &Loop) {
334   // Compute loop scale.
335   DEBUG(dbgs() << "compute-loop-scale: " << getLoopName(Loop) << "\n");
336
337   // LoopScale == 1 / ExitMass
338   // ExitMass == HeadMass - BackedgeMass
339   BlockMass ExitMass = BlockMass::getFull() - Loop.BackedgeMass;
340
341   // Block scale stores the inverse of the scale.
342   Loop.Scale = ExitMass.toScaled().inverse();
343
344   DEBUG(dbgs() << " - exit-mass = " << ExitMass << " (" << BlockMass::getFull()
345                << " - " << Loop.BackedgeMass << ")\n"
346                << " - scale = " << Loop.Scale << "\n");
347
348   if (Loop.Scale > getMaxLoopScale()) {
349     Loop.Scale = getMaxLoopScale();
350     DEBUG(dbgs() << " - reduced-to-max-scale: " << getMaxLoopScale() << "\n");
351   }
352 }
353
354 /// \brief Package up a loop.
355 void BlockFrequencyInfoImplBase::packageLoop(LoopData &Loop) {
356   DEBUG(dbgs() << "packaging-loop: " << getLoopName(Loop) << "\n");
357
358   // Clear the subloop exits to prevent quadratic memory usage.
359   for (const BlockNode &M : Loop.Nodes) {
360     if (auto *Loop = Working[M.Index].getPackagedLoop())
361       Loop->Exits.clear();
362     DEBUG(dbgs() << " - node: " << getBlockName(M.Index) << "\n");
363   }
364   Loop.IsPackaged = true;
365 }
366
367 void BlockFrequencyInfoImplBase::distributeMass(const BlockNode &Source,
368                                                 LoopData *OuterLoop,
369                                                 Distribution &Dist) {
370   BlockMass Mass = Working[Source.Index].getMass();
371   DEBUG(dbgs() << "  => mass:  " << Mass << "\n");
372
373   // Distribute mass to successors as laid out in Dist.
374   DitheringDistributer D(Dist, Mass);
375
376 #ifndef NDEBUG
377   auto debugAssign = [&](const BlockNode &T, const BlockMass &M,
378                          const char *Desc) {
379     dbgs() << "  => assign " << M << " (" << D.RemMass << ")";
380     if (Desc)
381       dbgs() << " [" << Desc << "]";
382     if (T.isValid())
383       dbgs() << " to " << getBlockName(T);
384     dbgs() << "\n";
385   };
386   (void)debugAssign;
387 #endif
388
389   for (const Weight &W : Dist.Weights) {
390     // Check for a local edge (non-backedge and non-exit).
391     BlockMass Taken = D.takeMass(W.Amount);
392     if (W.Type == Weight::Local) {
393       Working[W.TargetNode.Index].getMass() += Taken;
394       DEBUG(debugAssign(W.TargetNode, Taken, nullptr));
395       continue;
396     }
397
398     // Backedges and exits only make sense if we're processing a loop.
399     assert(OuterLoop && "backedge or exit outside of loop");
400
401     // Check for a backedge.
402     if (W.Type == Weight::Backedge) {
403       OuterLoop->BackedgeMass += Taken;
404       DEBUG(debugAssign(BlockNode(), Taken, "back"));
405       continue;
406     }
407
408     // This must be an exit.
409     assert(W.Type == Weight::Exit);
410     OuterLoop->Exits.push_back(std::make_pair(W.TargetNode, Taken));
411     DEBUG(debugAssign(W.TargetNode, Taken, "exit"));
412   }
413 }
414
415 static void convertFloatingToInteger(BlockFrequencyInfoImplBase &BFI,
416                                      const Scaled64 &Min, const Scaled64 &Max) {
417   // Scale the Factor to a size that creates integers.  Ideally, integers would
418   // be scaled so that Max == UINT64_MAX so that they can be best
419   // differentiated.  However, the register allocator currently deals poorly
420   // with large numbers.  Instead, push Min up a little from 1 to give some
421   // room to differentiate small, unequal numbers.
422   //
423   // TODO: fix issues downstream so that ScalingFactor can be
424   // Scaled64(1,64)/Max.
425   Scaled64 ScalingFactor = Min.inverse();
426   if ((Max / Min).lg() < 60)
427     ScalingFactor <<= 3;
428
429   // Translate the floats to integers.
430   DEBUG(dbgs() << "float-to-int: min = " << Min << ", max = " << Max
431                << ", factor = " << ScalingFactor << "\n");
432   for (size_t Index = 0; Index < BFI.Freqs.size(); ++Index) {
433     Scaled64 Scaled = BFI.Freqs[Index].Scaled * ScalingFactor;
434     BFI.Freqs[Index].Integer = std::max(UINT64_C(1), Scaled.toInt<uint64_t>());
435     DEBUG(dbgs() << " - " << BFI.getBlockName(Index) << ": float = "
436                  << BFI.Freqs[Index].Scaled << ", scaled = " << Scaled
437                  << ", int = " << BFI.Freqs[Index].Integer << "\n");
438   }
439 }
440
441 /// \brief Unwrap a loop package.
442 ///
443 /// Visits all the members of a loop, adjusting their BlockData according to
444 /// the loop's pseudo-node.
445 static void unwrapLoop(BlockFrequencyInfoImplBase &BFI, LoopData &Loop) {
446   DEBUG(dbgs() << "unwrap-loop-package: " << BFI.getLoopName(Loop)
447                << ": mass = " << Loop.Mass << ", scale = " << Loop.Scale
448                << "\n");
449   Loop.Scale *= Loop.Mass.toScaled();
450   Loop.IsPackaged = false;
451   DEBUG(dbgs() << "  => combined-scale = " << Loop.Scale << "\n");
452
453   // Propagate the head scale through the loop.  Since members are visited in
454   // RPO, the head scale will be updated by the loop scale first, and then the
455   // final head scale will be used for updated the rest of the members.
456   for (const BlockNode &N : Loop.Nodes) {
457     const auto &Working = BFI.Working[N.Index];
458     Scaled64 &F = Working.isAPackage() ? Working.getPackagedLoop()->Scale
459                                        : BFI.Freqs[N.Index].Scaled;
460     Scaled64 New = Loop.Scale * F;
461     DEBUG(dbgs() << " - " << BFI.getBlockName(N) << ": " << F << " => " << New
462                  << "\n");
463     F = New;
464   }
465 }
466
467 void BlockFrequencyInfoImplBase::unwrapLoops() {
468   // Set initial frequencies from loop-local masses.
469   for (size_t Index = 0; Index < Working.size(); ++Index)
470     Freqs[Index].Scaled = Working[Index].Mass.toScaled();
471
472   for (LoopData &Loop : Loops)
473     unwrapLoop(*this, Loop);
474 }
475
476 void BlockFrequencyInfoImplBase::finalizeMetrics() {
477   // Unwrap loop packages in reverse post-order, tracking min and max
478   // frequencies.
479   auto Min = Scaled64::getLargest();
480   auto Max = Scaled64::getZero();
481   for (size_t Index = 0; Index < Working.size(); ++Index) {
482     // Update min/max scale.
483     Min = std::min(Min, Freqs[Index].Scaled);
484     Max = std::max(Max, Freqs[Index].Scaled);
485   }
486
487   // Convert to integers.
488   convertFloatingToInteger(*this, Min, Max);
489
490   // Clean up data structures.
491   cleanup(*this);
492
493   // Print out the final stats.
494   DEBUG(dump());
495 }
496
497 BlockFrequency
498 BlockFrequencyInfoImplBase::getBlockFreq(const BlockNode &Node) const {
499   if (!Node.isValid())
500     return 0;
501   return Freqs[Node.Index].Integer;
502 }
503 Scaled64
504 BlockFrequencyInfoImplBase::getFloatingBlockFreq(const BlockNode &Node) const {
505   if (!Node.isValid())
506     return Scaled64::getZero();
507   return Freqs[Node.Index].Scaled;
508 }
509
510 std::string
511 BlockFrequencyInfoImplBase::getBlockName(const BlockNode &Node) const {
512   return std::string();
513 }
514 std::string
515 BlockFrequencyInfoImplBase::getLoopName(const LoopData &Loop) const {
516   return getBlockName(Loop.getHeader()) + (Loop.isIrreducible() ? "**" : "*");
517 }
518
519 raw_ostream &
520 BlockFrequencyInfoImplBase::printBlockFreq(raw_ostream &OS,
521                                            const BlockNode &Node) const {
522   return OS << getFloatingBlockFreq(Node);
523 }
524
525 raw_ostream &
526 BlockFrequencyInfoImplBase::printBlockFreq(raw_ostream &OS,
527                                            const BlockFrequency &Freq) const {
528   Scaled64 Block(Freq.getFrequency(), 0);
529   Scaled64 Entry(getEntryFreq(), 0);
530
531   return OS << Block / Entry;
532 }
533
534 void IrreducibleGraph::addNodesInLoop(const BFIBase::LoopData &OuterLoop) {
535   Start = OuterLoop.getHeader();
536   Nodes.reserve(OuterLoop.Nodes.size());
537   for (auto N : OuterLoop.Nodes)
538     addNode(N);
539   indexNodes();
540 }
541 void IrreducibleGraph::addNodesInFunction() {
542   Start = 0;
543   for (uint32_t Index = 0; Index < BFI.Working.size(); ++Index)
544     if (!BFI.Working[Index].isPackaged())
545       addNode(Index);
546   indexNodes();
547 }
548 void IrreducibleGraph::indexNodes() {
549   for (auto &I : Nodes)
550     Lookup[I.Node.Index] = &I;
551 }
552 void IrreducibleGraph::addEdge(IrrNode &Irr, const BlockNode &Succ,
553                                const BFIBase::LoopData *OuterLoop) {
554   if (OuterLoop && OuterLoop->isHeader(Succ))
555     return;
556   auto L = Lookup.find(Succ.Index);
557   if (L == Lookup.end())
558     return;
559   IrrNode &SuccIrr = *L->second;
560   Irr.Edges.push_back(&SuccIrr);
561   SuccIrr.Edges.push_front(&Irr);
562   ++SuccIrr.NumIn;
563 }
564
565 namespace llvm {
566 template <> struct GraphTraits<IrreducibleGraph> {
567   typedef bfi_detail::IrreducibleGraph GraphT;
568
569   typedef const GraphT::IrrNode NodeType;
570   typedef GraphT::IrrNode::iterator ChildIteratorType;
571
572   static const NodeType *getEntryNode(const GraphT &G) {
573     return G.StartIrr;
574   }
575   static ChildIteratorType child_begin(NodeType *N) { return N->succ_begin(); }
576   static ChildIteratorType child_end(NodeType *N) { return N->succ_end(); }
577 };
578 }
579
580 /// \brief Find extra irreducible headers.
581 ///
582 /// Find entry blocks and other blocks with backedges, which exist when \c G
583 /// contains irreducible sub-SCCs.
584 static void findIrreducibleHeaders(
585     const BlockFrequencyInfoImplBase &BFI,
586     const IrreducibleGraph &G,
587     const std::vector<const IrreducibleGraph::IrrNode *> &SCC,
588     LoopData::NodeList &Headers, LoopData::NodeList &Others) {
589   // Map from nodes in the SCC to whether it's an entry block.
590   SmallDenseMap<const IrreducibleGraph::IrrNode *, bool, 8> InSCC;
591
592   // InSCC also acts the set of nodes in the graph.  Seed it.
593   for (const auto *I : SCC)
594     InSCC[I] = false;
595
596   for (auto I = InSCC.begin(), E = InSCC.end(); I != E; ++I) {
597     auto &Irr = *I->first;
598     for (const auto *P : make_range(Irr.pred_begin(), Irr.pred_end())) {
599       if (InSCC.count(P))
600         continue;
601
602       // This is an entry block.
603       I->second = true;
604       Headers.push_back(Irr.Node);
605       DEBUG(dbgs() << "  => entry = " << BFI.getBlockName(Irr.Node) << "\n");
606       break;
607     }
608   }
609   assert(Headers.size() >= 2 && "Should be irreducible");
610   if (Headers.size() == InSCC.size()) {
611     // Every block is a header.
612     std::sort(Headers.begin(), Headers.end());
613     return;
614   }
615
616   // Look for extra headers from irreducible sub-SCCs.
617   for (const auto &I : InSCC) {
618     // Entry blocks are already headers.
619     if (I.second)
620       continue;
621
622     auto &Irr = *I.first;
623     for (const auto *P : make_range(Irr.pred_begin(), Irr.pred_end())) {
624       // Skip forward edges.
625       if (P->Node < Irr.Node)
626         continue;
627
628       // Skip predecessors from entry blocks.  These can have inverted
629       // ordering.
630       if (InSCC.lookup(P))
631         continue;
632
633       // Store the extra header.
634       Headers.push_back(Irr.Node);
635       DEBUG(dbgs() << "  => extra = " << BFI.getBlockName(Irr.Node) << "\n");
636       break;
637     }
638     if (Headers.back() == Irr.Node)
639       // Added this as a header.
640       continue;
641
642     // This is not a header.
643     Others.push_back(Irr.Node);
644     DEBUG(dbgs() << "  => other = " << BFI.getBlockName(Irr.Node) << "\n");
645   }
646   std::sort(Headers.begin(), Headers.end());
647   std::sort(Others.begin(), Others.end());
648 }
649
650 static void createIrreducibleLoop(
651     BlockFrequencyInfoImplBase &BFI, const IrreducibleGraph &G,
652     LoopData *OuterLoop, std::list<LoopData>::iterator Insert,
653     const std::vector<const IrreducibleGraph::IrrNode *> &SCC) {
654   // Translate the SCC into RPO.
655   DEBUG(dbgs() << " - found-scc\n");
656
657   LoopData::NodeList Headers;
658   LoopData::NodeList Others;
659   findIrreducibleHeaders(BFI, G, SCC, Headers, Others);
660
661   auto Loop = BFI.Loops.emplace(Insert, OuterLoop, Headers.begin(),
662                                 Headers.end(), Others.begin(), Others.end());
663
664   // Update loop hierarchy.
665   for (const auto &N : Loop->Nodes)
666     if (BFI.Working[N.Index].isLoopHeader())
667       BFI.Working[N.Index].Loop->Parent = &*Loop;
668     else
669       BFI.Working[N.Index].Loop = &*Loop;
670 }
671
672 iterator_range<std::list<LoopData>::iterator>
673 BlockFrequencyInfoImplBase::analyzeIrreducible(
674     const IrreducibleGraph &G, LoopData *OuterLoop,
675     std::list<LoopData>::iterator Insert) {
676   assert((OuterLoop == nullptr) == (Insert == Loops.begin()));
677   auto Prev = OuterLoop ? std::prev(Insert) : Loops.end();
678
679   for (auto I = scc_begin(G); !I.isAtEnd(); ++I) {
680     if (I->size() < 2)
681       continue;
682
683     // Translate the SCC into RPO.
684     createIrreducibleLoop(*this, G, OuterLoop, Insert, *I);
685   }
686
687   if (OuterLoop)
688     return make_range(std::next(Prev), Insert);
689   return make_range(Loops.begin(), Insert);
690 }
691
692 void
693 BlockFrequencyInfoImplBase::updateLoopWithIrreducible(LoopData &OuterLoop) {
694   OuterLoop.Exits.clear();
695   OuterLoop.BackedgeMass = BlockMass::getEmpty();
696   auto O = OuterLoop.Nodes.begin() + 1;
697   for (auto I = O, E = OuterLoop.Nodes.end(); I != E; ++I)
698     if (!Working[I->Index].isPackaged())
699       *O++ = *I;
700   OuterLoop.Nodes.erase(O, OuterLoop.Nodes.end());
701 }