BFI: Mark the end of namespaces
[oota-llvm.git] / include / llvm / Analysis / BlockFrequencyInfoImpl.h
1 //==- BlockFrequencyInfoImpl.h - Block Frequency Implementation -*- C++ -*-===//
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 // Shared implementation of BlockFrequency for IR and Machine Instructions.
11 // See the documentation below for BlockFrequencyInfoImpl for details.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #ifndef LLVM_ANALYSIS_BLOCKFREQUENCYINFOIMPL_H
16 #define LLVM_ANALYSIS_BLOCKFREQUENCYINFOIMPL_H
17
18 #include "llvm/ADT/DenseMap.h"
19 #include "llvm/ADT/PostOrderIterator.h"
20 #include "llvm/ADT/iterator_range.h"
21 #include "llvm/IR/BasicBlock.h"
22 #include "llvm/Support/BlockFrequency.h"
23 #include "llvm/Support/BranchProbability.h"
24 #include "llvm/Support/Debug.h"
25 #include "llvm/Support/ScaledNumber.h"
26 #include "llvm/Support/raw_ostream.h"
27 #include <deque>
28 #include <list>
29 #include <string>
30 #include <vector>
31
32 #define DEBUG_TYPE "block-freq"
33
34 //===----------------------------------------------------------------------===//
35 //
36 // BlockMass definition.
37 //
38 // TODO: Make this private to BlockFrequencyInfoImpl or delete.
39 //
40 //===----------------------------------------------------------------------===//
41 namespace llvm {
42
43 /// \brief Mass of a block.
44 ///
45 /// This class implements a sort of fixed-point fraction always between 0.0 and
46 /// 1.0.  getMass() == UINT64_MAX indicates a value of 1.0.
47 ///
48 /// Masses can be added and subtracted.  Simple saturation arithmetic is used,
49 /// so arithmetic operations never overflow or underflow.
50 ///
51 /// Masses can be multiplied.  Multiplication treats full mass as 1.0 and uses
52 /// an inexpensive floating-point algorithm that's off-by-one (almost, but not
53 /// quite, maximum precision).
54 ///
55 /// Masses can be scaled by \a BranchProbability at maximum precision.
56 class BlockMass {
57   uint64_t Mass;
58
59 public:
60   BlockMass() : Mass(0) {}
61   explicit BlockMass(uint64_t Mass) : Mass(Mass) {}
62
63   static BlockMass getEmpty() { return BlockMass(); }
64   static BlockMass getFull() { return BlockMass(UINT64_MAX); }
65
66   uint64_t getMass() const { return Mass; }
67
68   bool isFull() const { return Mass == UINT64_MAX; }
69   bool isEmpty() const { return !Mass; }
70
71   bool operator!() const { return isEmpty(); }
72
73   /// \brief Add another mass.
74   ///
75   /// Adds another mass, saturating at \a isFull() rather than overflowing.
76   BlockMass &operator+=(const BlockMass &X) {
77     uint64_t Sum = Mass + X.Mass;
78     Mass = Sum < Mass ? UINT64_MAX : Sum;
79     return *this;
80   }
81
82   /// \brief Subtract another mass.
83   ///
84   /// Subtracts another mass, saturating at \a isEmpty() rather than
85   /// undeflowing.
86   BlockMass &operator-=(const BlockMass &X) {
87     uint64_t Diff = Mass - X.Mass;
88     Mass = Diff > Mass ? 0 : Diff;
89     return *this;
90   }
91
92   BlockMass &operator*=(const BranchProbability &P) {
93     Mass = P.scale(Mass);
94     return *this;
95   }
96
97   bool operator==(const BlockMass &X) const { return Mass == X.Mass; }
98   bool operator!=(const BlockMass &X) const { return Mass != X.Mass; }
99   bool operator<=(const BlockMass &X) const { return Mass <= X.Mass; }
100   bool operator>=(const BlockMass &X) const { return Mass >= X.Mass; }
101   bool operator<(const BlockMass &X) const { return Mass < X.Mass; }
102   bool operator>(const BlockMass &X) const { return Mass > X.Mass; }
103
104   /// \brief Convert to scaled number.
105   ///
106   /// Convert to \a ScaledNumber.  \a isFull() gives 1.0, while \a isEmpty()
107   /// gives slightly above 0.0.
108   ScaledNumber<uint64_t> toScaled() const;
109
110   void dump() const;
111   raw_ostream &print(raw_ostream &OS) const;
112 };
113
114 inline BlockMass operator+(const BlockMass &L, const BlockMass &R) {
115   return BlockMass(L) += R;
116 }
117 inline BlockMass operator-(const BlockMass &L, const BlockMass &R) {
118   return BlockMass(L) -= R;
119 }
120 inline BlockMass operator*(const BlockMass &L, const BranchProbability &R) {
121   return BlockMass(L) *= R;
122 }
123 inline BlockMass operator*(const BranchProbability &L, const BlockMass &R) {
124   return BlockMass(R) *= L;
125 }
126
127 inline raw_ostream &operator<<(raw_ostream &OS, const BlockMass &X) {
128   return X.print(OS);
129 }
130
131 template <> struct isPodLike<BlockMass> {
132   static const bool value = true;
133 };
134
135 } // end namespace llvm
136
137 //===----------------------------------------------------------------------===//
138 //
139 // BlockFrequencyInfoImpl definition.
140 //
141 //===----------------------------------------------------------------------===//
142 namespace llvm {
143
144 class BasicBlock;
145 class BranchProbabilityInfo;
146 class Function;
147 class Loop;
148 class LoopInfo;
149 class MachineBasicBlock;
150 class MachineBranchProbabilityInfo;
151 class MachineFunction;
152 class MachineLoop;
153 class MachineLoopInfo;
154
155 namespace bfi_detail {
156 struct IrreducibleGraph;
157
158 // This is part of a workaround for a GCC 4.7 crash on lambdas.
159 template <class BT> struct BlockEdgesAdder;
160 }
161
162 /// \brief Base class for BlockFrequencyInfoImpl
163 ///
164 /// BlockFrequencyInfoImplBase has supporting data structures and some
165 /// algorithms for BlockFrequencyInfoImplBase.  Only algorithms that depend on
166 /// the block type (or that call such algorithms) are skipped here.
167 ///
168 /// Nevertheless, the majority of the overall algorithm documention lives with
169 /// BlockFrequencyInfoImpl.  See there for details.
170 class BlockFrequencyInfoImplBase {
171 public:
172   typedef ScaledNumber<uint64_t> Scaled64;
173
174   /// \brief Representative of a block.
175   ///
176   /// This is a simple wrapper around an index into the reverse-post-order
177   /// traversal of the blocks.
178   ///
179   /// Unlike a block pointer, its order has meaning (location in the
180   /// topological sort) and it's class is the same regardless of block type.
181   struct BlockNode {
182     typedef uint32_t IndexType;
183     IndexType Index;
184
185     bool operator==(const BlockNode &X) const { return Index == X.Index; }
186     bool operator!=(const BlockNode &X) const { return Index != X.Index; }
187     bool operator<=(const BlockNode &X) const { return Index <= X.Index; }
188     bool operator>=(const BlockNode &X) const { return Index >= X.Index; }
189     bool operator<(const BlockNode &X) const { return Index < X.Index; }
190     bool operator>(const BlockNode &X) const { return Index > X.Index; }
191
192     BlockNode() : Index(UINT32_MAX) {}
193     BlockNode(IndexType Index) : Index(Index) {}
194
195     bool isValid() const { return Index <= getMaxIndex(); }
196     static size_t getMaxIndex() { return UINT32_MAX - 1; }
197   };
198
199   /// \brief Stats about a block itself.
200   struct FrequencyData {
201     Scaled64 Scaled;
202     uint64_t Integer;
203   };
204
205   /// \brief Data about a loop.
206   ///
207   /// Contains the data necessary to represent represent a loop as a
208   /// pseudo-node once it's packaged.
209   struct LoopData {
210     typedef SmallVector<std::pair<BlockNode, BlockMass>, 4> ExitMap;
211     typedef SmallVector<BlockNode, 4> NodeList;
212     LoopData *Parent;       ///< The parent loop.
213     bool IsPackaged;        ///< Whether this has been packaged.
214     uint32_t NumHeaders;    ///< Number of headers.
215     ExitMap Exits;          ///< Successor edges (and weights).
216     NodeList Nodes;         ///< Header and the members of the loop.
217     BlockMass BackedgeMass; ///< Mass returned to loop header.
218     BlockMass Mass;
219     Scaled64 Scale;
220
221     LoopData(LoopData *Parent, const BlockNode &Header)
222         : Parent(Parent), IsPackaged(false), NumHeaders(1), Nodes(1, Header) {}
223     template <class It1, class It2>
224     LoopData(LoopData *Parent, It1 FirstHeader, It1 LastHeader, It2 FirstOther,
225              It2 LastOther)
226         : Parent(Parent), IsPackaged(false), Nodes(FirstHeader, LastHeader) {
227       NumHeaders = Nodes.size();
228       Nodes.insert(Nodes.end(), FirstOther, LastOther);
229     }
230     bool isHeader(const BlockNode &Node) const {
231       if (isIrreducible())
232         return std::binary_search(Nodes.begin(), Nodes.begin() + NumHeaders,
233                                   Node);
234       return Node == Nodes[0];
235     }
236     BlockNode getHeader() const { return Nodes[0]; }
237     bool isIrreducible() const { return NumHeaders > 1; }
238
239     NodeList::const_iterator members_begin() const {
240       return Nodes.begin() + NumHeaders;
241     }
242     NodeList::const_iterator members_end() const { return Nodes.end(); }
243     iterator_range<NodeList::const_iterator> members() const {
244       return make_range(members_begin(), members_end());
245     }
246   };
247
248   /// \brief Index of loop information.
249   struct WorkingData {
250     BlockNode Node; ///< This node.
251     LoopData *Loop; ///< The loop this block is inside.
252     BlockMass Mass; ///< Mass distribution from the entry block.
253
254     WorkingData(const BlockNode &Node) : Node(Node), Loop(nullptr) {}
255
256     bool isLoopHeader() const { return Loop && Loop->isHeader(Node); }
257     bool isDoubleLoopHeader() const {
258       return isLoopHeader() && Loop->Parent && Loop->Parent->isIrreducible() &&
259              Loop->Parent->isHeader(Node);
260     }
261
262     LoopData *getContainingLoop() const {
263       if (!isLoopHeader())
264         return Loop;
265       if (!isDoubleLoopHeader())
266         return Loop->Parent;
267       return Loop->Parent->Parent;
268     }
269
270     /// \brief Resolve a node to its representative.
271     ///
272     /// Get the node currently representing Node, which could be a containing
273     /// loop.
274     ///
275     /// This function should only be called when distributing mass.  As long as
276     /// there are no irreducilbe edges to Node, then it will have complexity
277     /// O(1) in this context.
278     ///
279     /// In general, the complexity is O(L), where L is the number of loop
280     /// headers Node has been packaged into.  Since this method is called in
281     /// the context of distributing mass, L will be the number of loop headers
282     /// an early exit edge jumps out of.
283     BlockNode getResolvedNode() const {
284       auto L = getPackagedLoop();
285       return L ? L->getHeader() : Node;
286     }
287     LoopData *getPackagedLoop() const {
288       if (!Loop || !Loop->IsPackaged)
289         return nullptr;
290       auto L = Loop;
291       while (L->Parent && L->Parent->IsPackaged)
292         L = L->Parent;
293       return L;
294     }
295
296     /// \brief Get the appropriate mass for a node.
297     ///
298     /// Get appropriate mass for Node.  If Node is a loop-header (whose loop
299     /// has been packaged), returns the mass of its pseudo-node.  If it's a
300     /// node inside a packaged loop, it returns the loop's mass.
301     BlockMass &getMass() {
302       if (!isAPackage())
303         return Mass;
304       if (!isADoublePackage())
305         return Loop->Mass;
306       return Loop->Parent->Mass;
307     }
308
309     /// \brief Has ContainingLoop been packaged up?
310     bool isPackaged() const { return getResolvedNode() != Node; }
311     /// \brief Has Loop been packaged up?
312     bool isAPackage() const { return isLoopHeader() && Loop->IsPackaged; }
313     /// \brief Has Loop been packaged up twice?
314     bool isADoublePackage() const {
315       return isDoubleLoopHeader() && Loop->Parent->IsPackaged;
316     }
317   };
318
319   /// \brief Unscaled probability weight.
320   ///
321   /// Probability weight for an edge in the graph (including the
322   /// successor/target node).
323   ///
324   /// All edges in the original function are 32-bit.  However, exit edges from
325   /// loop packages are taken from 64-bit exit masses, so we need 64-bits of
326   /// space in general.
327   ///
328   /// In addition to the raw weight amount, Weight stores the type of the edge
329   /// in the current context (i.e., the context of the loop being processed).
330   /// Is this a local edge within the loop, an exit from the loop, or a
331   /// backedge to the loop header?
332   struct Weight {
333     enum DistType { Local, Exit, Backedge };
334     DistType Type;
335     BlockNode TargetNode;
336     uint64_t Amount;
337     Weight() : Type(Local), Amount(0) {}
338   };
339
340   /// \brief Distribution of unscaled probability weight.
341   ///
342   /// Distribution of unscaled probability weight to a set of successors.
343   ///
344   /// This class collates the successor edge weights for later processing.
345   ///
346   /// \a DidOverflow indicates whether \a Total did overflow while adding to
347   /// the distribution.  It should never overflow twice.
348   struct Distribution {
349     typedef SmallVector<Weight, 4> WeightList;
350     WeightList Weights;    ///< Individual successor weights.
351     uint64_t Total;        ///< Sum of all weights.
352     bool DidOverflow;      ///< Whether \a Total did overflow.
353
354     Distribution() : Total(0), DidOverflow(false) {}
355     void addLocal(const BlockNode &Node, uint64_t Amount) {
356       add(Node, Amount, Weight::Local);
357     }
358     void addExit(const BlockNode &Node, uint64_t Amount) {
359       add(Node, Amount, Weight::Exit);
360     }
361     void addBackedge(const BlockNode &Node, uint64_t Amount) {
362       add(Node, Amount, Weight::Backedge);
363     }
364
365     /// \brief Normalize the distribution.
366     ///
367     /// Combines multiple edges to the same \a Weight::TargetNode and scales
368     /// down so that \a Total fits into 32-bits.
369     ///
370     /// This is linear in the size of \a Weights.  For the vast majority of
371     /// cases, adjacent edge weights are combined by sorting WeightList and
372     /// combining adjacent weights.  However, for very large edge lists an
373     /// auxiliary hash table is used.
374     void normalize();
375
376   private:
377     void add(const BlockNode &Node, uint64_t Amount, Weight::DistType Type);
378   };
379
380   /// \brief Data about each block.  This is used downstream.
381   std::vector<FrequencyData> Freqs;
382
383   /// \brief Loop data: see initializeLoops().
384   std::vector<WorkingData> Working;
385
386   /// \brief Indexed information about loops.
387   std::list<LoopData> Loops;
388
389   /// \brief Add all edges out of a packaged loop to the distribution.
390   ///
391   /// Adds all edges from LocalLoopHead to Dist.  Calls addToDist() to add each
392   /// successor edge.
393   ///
394   /// \return \c true unless there's an irreducible backedge.
395   bool addLoopSuccessorsToDist(const LoopData *OuterLoop, LoopData &Loop,
396                                Distribution &Dist);
397
398   /// \brief Add an edge to the distribution.
399   ///
400   /// Adds an edge to Succ to Dist.  If \c LoopHead.isValid(), then whether the
401   /// edge is local/exit/backedge is in the context of LoopHead.  Otherwise,
402   /// every edge should be a local edge (since all the loops are packaged up).
403   ///
404   /// \return \c true unless aborted due to an irreducible backedge.
405   bool addToDist(Distribution &Dist, const LoopData *OuterLoop,
406                  const BlockNode &Pred, const BlockNode &Succ, uint64_t Weight);
407
408   LoopData &getLoopPackage(const BlockNode &Head) {
409     assert(Head.Index < Working.size());
410     assert(Working[Head.Index].isLoopHeader());
411     return *Working[Head.Index].Loop;
412   }
413
414   /// \brief Analyze irreducible SCCs.
415   ///
416   /// Separate irreducible SCCs from \c G, which is an explict graph of \c
417   /// OuterLoop (or the top-level function, if \c OuterLoop is \c nullptr).
418   /// Insert them into \a Loops before \c Insert.
419   ///
420   /// \return the \c LoopData nodes representing the irreducible SCCs.
421   iterator_range<std::list<LoopData>::iterator>
422   analyzeIrreducible(const bfi_detail::IrreducibleGraph &G, LoopData *OuterLoop,
423                      std::list<LoopData>::iterator Insert);
424
425   /// \brief Update a loop after packaging irreducible SCCs inside of it.
426   ///
427   /// Update \c OuterLoop.  Before finding irreducible control flow, it was
428   /// partway through \a computeMassInLoop(), so \a LoopData::Exits and \a
429   /// LoopData::BackedgeMass need to be reset.  Also, nodes that were packaged
430   /// up need to be removed from \a OuterLoop::Nodes.
431   void updateLoopWithIrreducible(LoopData &OuterLoop);
432
433   /// \brief Distribute mass according to a distribution.
434   ///
435   /// Distributes the mass in Source according to Dist.  If LoopHead.isValid(),
436   /// backedges and exits are stored in its entry in Loops.
437   ///
438   /// Mass is distributed in parallel from two copies of the source mass.
439   void distributeMass(const BlockNode &Source, LoopData *OuterLoop,
440                       Distribution &Dist);
441
442   /// \brief Compute the loop scale for a loop.
443   void computeLoopScale(LoopData &Loop);
444
445   /// \brief Package up a loop.
446   void packageLoop(LoopData &Loop);
447
448   /// \brief Unwrap loops.
449   void unwrapLoops();
450
451   /// \brief Finalize frequency metrics.
452   ///
453   /// Calculates final frequencies and cleans up no-longer-needed data
454   /// structures.
455   void finalizeMetrics();
456
457   /// \brief Clear all memory.
458   void clear();
459
460   virtual std::string getBlockName(const BlockNode &Node) const;
461   std::string getLoopName(const LoopData &Loop) const;
462
463   virtual raw_ostream &print(raw_ostream &OS) const { return OS; }
464   void dump() const { print(dbgs()); }
465
466   Scaled64 getFloatingBlockFreq(const BlockNode &Node) const;
467
468   BlockFrequency getBlockFreq(const BlockNode &Node) const;
469
470   raw_ostream &printBlockFreq(raw_ostream &OS, const BlockNode &Node) const;
471   raw_ostream &printBlockFreq(raw_ostream &OS,
472                               const BlockFrequency &Freq) const;
473
474   uint64_t getEntryFreq() const {
475     assert(!Freqs.empty());
476     return Freqs[0].Integer;
477   }
478   /// \brief Virtual destructor.
479   ///
480   /// Need a virtual destructor to mask the compiler warning about
481   /// getBlockName().
482   virtual ~BlockFrequencyInfoImplBase() {}
483 };
484
485 namespace bfi_detail {
486 template <class BlockT> struct TypeMap {};
487 template <> struct TypeMap<BasicBlock> {
488   typedef BasicBlock BlockT;
489   typedef Function FunctionT;
490   typedef BranchProbabilityInfo BranchProbabilityInfoT;
491   typedef Loop LoopT;
492   typedef LoopInfo LoopInfoT;
493 };
494 template <> struct TypeMap<MachineBasicBlock> {
495   typedef MachineBasicBlock BlockT;
496   typedef MachineFunction FunctionT;
497   typedef MachineBranchProbabilityInfo BranchProbabilityInfoT;
498   typedef MachineLoop LoopT;
499   typedef MachineLoopInfo LoopInfoT;
500 };
501
502 /// \brief Get the name of a MachineBasicBlock.
503 ///
504 /// Get the name of a MachineBasicBlock.  It's templated so that including from
505 /// CodeGen is unnecessary (that would be a layering issue).
506 ///
507 /// This is used mainly for debug output.  The name is similar to
508 /// MachineBasicBlock::getFullName(), but skips the name of the function.
509 template <class BlockT> std::string getBlockName(const BlockT *BB) {
510   assert(BB && "Unexpected nullptr");
511   auto MachineName = "BB" + Twine(BB->getNumber());
512   if (BB->getBasicBlock())
513     return (MachineName + "[" + BB->getName() + "]").str();
514   return MachineName.str();
515 }
516 /// \brief Get the name of a BasicBlock.
517 template <> inline std::string getBlockName(const BasicBlock *BB) {
518   assert(BB && "Unexpected nullptr");
519   return BB->getName().str();
520 }
521
522 /// \brief Graph of irreducible control flow.
523 ///
524 /// This graph is used for determining the SCCs in a loop (or top-level
525 /// function) that has irreducible control flow.
526 ///
527 /// During the block frequency algorithm, the local graphs are defined in a
528 /// light-weight way, deferring to the \a BasicBlock or \a MachineBasicBlock
529 /// graphs for most edges, but getting others from \a LoopData::ExitMap.  The
530 /// latter only has successor information.
531 ///
532 /// \a IrreducibleGraph makes this graph explicit.  It's in a form that can use
533 /// \a GraphTraits (so that \a analyzeIrreducible() can use \a scc_iterator),
534 /// and it explicitly lists predecessors and successors.  The initialization
535 /// that relies on \c MachineBasicBlock is defined in the header.
536 struct IrreducibleGraph {
537   typedef BlockFrequencyInfoImplBase BFIBase;
538
539   BFIBase &BFI;
540
541   typedef BFIBase::BlockNode BlockNode;
542   struct IrrNode {
543     BlockNode Node;
544     unsigned NumIn;
545     std::deque<const IrrNode *> Edges;
546     IrrNode(const BlockNode &Node) : Node(Node), NumIn(0) {}
547
548     typedef std::deque<const IrrNode *>::const_iterator iterator;
549     iterator pred_begin() const { return Edges.begin(); }
550     iterator succ_begin() const { return Edges.begin() + NumIn; }
551     iterator pred_end() const { return succ_begin(); }
552     iterator succ_end() const { return Edges.end(); }
553   };
554   BlockNode Start;
555   const IrrNode *StartIrr;
556   std::vector<IrrNode> Nodes;
557   SmallDenseMap<uint32_t, IrrNode *, 4> Lookup;
558
559   /// \brief Construct an explicit graph containing irreducible control flow.
560   ///
561   /// Construct an explicit graph of the control flow in \c OuterLoop (or the
562   /// top-level function, if \c OuterLoop is \c nullptr).  Uses \c
563   /// addBlockEdges to add block successors that have not been packaged into
564   /// loops.
565   ///
566   /// \a BlockFrequencyInfoImpl::computeIrreducibleMass() is the only expected
567   /// user of this.
568   template <class BlockEdgesAdder>
569   IrreducibleGraph(BFIBase &BFI, const BFIBase::LoopData *OuterLoop,
570                    BlockEdgesAdder addBlockEdges)
571       : BFI(BFI), StartIrr(nullptr) {
572     initialize(OuterLoop, addBlockEdges);
573   }
574
575   template <class BlockEdgesAdder>
576   void initialize(const BFIBase::LoopData *OuterLoop,
577                   BlockEdgesAdder addBlockEdges);
578   void addNodesInLoop(const BFIBase::LoopData &OuterLoop);
579   void addNodesInFunction();
580   void addNode(const BlockNode &Node) {
581     Nodes.emplace_back(Node);
582     BFI.Working[Node.Index].getMass() = BlockMass::getEmpty();
583   }
584   void indexNodes();
585   template <class BlockEdgesAdder>
586   void addEdges(const BlockNode &Node, const BFIBase::LoopData *OuterLoop,
587                 BlockEdgesAdder addBlockEdges);
588   void addEdge(IrrNode &Irr, const BlockNode &Succ,
589                const BFIBase::LoopData *OuterLoop);
590 };
591 template <class BlockEdgesAdder>
592 void IrreducibleGraph::initialize(const BFIBase::LoopData *OuterLoop,
593                                   BlockEdgesAdder addBlockEdges) {
594   if (OuterLoop) {
595     addNodesInLoop(*OuterLoop);
596     for (auto N : OuterLoop->Nodes)
597       addEdges(N, OuterLoop, addBlockEdges);
598   } else {
599     addNodesInFunction();
600     for (uint32_t Index = 0; Index < BFI.Working.size(); ++Index)
601       addEdges(Index, OuterLoop, addBlockEdges);
602   }
603   StartIrr = Lookup[Start.Index];
604 }
605 template <class BlockEdgesAdder>
606 void IrreducibleGraph::addEdges(const BlockNode &Node,
607                                 const BFIBase::LoopData *OuterLoop,
608                                 BlockEdgesAdder addBlockEdges) {
609   auto L = Lookup.find(Node.Index);
610   if (L == Lookup.end())
611     return;
612   IrrNode &Irr = *L->second;
613   const auto &Working = BFI.Working[Node.Index];
614
615   if (Working.isAPackage())
616     for (const auto &I : Working.Loop->Exits)
617       addEdge(Irr, I.first, OuterLoop);
618   else
619     addBlockEdges(*this, Irr, OuterLoop);
620 }
621 }
622
623 /// \brief Shared implementation for block frequency analysis.
624 ///
625 /// This is a shared implementation of BlockFrequencyInfo and
626 /// MachineBlockFrequencyInfo, and calculates the relative frequencies of
627 /// blocks.
628 ///
629 /// LoopInfo defines a loop as a "non-trivial" SCC dominated by a single block,
630 /// which is called the header.  A given loop, L, can have sub-loops, which are
631 /// loops within the subgraph of L that exclude its header.  (A "trivial" SCC
632 /// consists of a single block that does not have a self-edge.)
633 ///
634 /// In addition to loops, this algorithm has limited support for irreducible
635 /// SCCs, which are SCCs with multiple entry blocks.  Irreducible SCCs are
636 /// discovered on they fly, and modelled as loops with multiple headers.
637 ///
638 /// The headers of irreducible sub-SCCs consist of its entry blocks and all
639 /// nodes that are targets of a backedge within it (excluding backedges within
640 /// true sub-loops).  Block frequency calculations act as if a block is
641 /// inserted that intercepts all the edges to the headers.  All backedges and
642 /// entries point to this block.  Its successors are the headers, which split
643 /// the frequency evenly.
644 ///
645 /// This algorithm leverages BlockMass and ScaledNumber to maintain precision,
646 /// separates mass distribution from loop scaling, and dithers to eliminate
647 /// probability mass loss.
648 ///
649 /// The implementation is split between BlockFrequencyInfoImpl, which knows the
650 /// type of graph being modelled (BasicBlock vs. MachineBasicBlock), and
651 /// BlockFrequencyInfoImplBase, which doesn't.  The base class uses \a
652 /// BlockNode, a wrapper around a uint32_t.  BlockNode is numbered from 0 in
653 /// reverse-post order.  This gives two advantages:  it's easy to compare the
654 /// relative ordering of two nodes, and maps keyed on BlockT can be represented
655 /// by vectors.
656 ///
657 /// This algorithm is O(V+E), unless there is irreducible control flow, in
658 /// which case it's O(V*E) in the worst case.
659 ///
660 /// These are the main stages:
661 ///
662 ///  0. Reverse post-order traversal (\a initializeRPOT()).
663 ///
664 ///     Run a single post-order traversal and save it (in reverse) in RPOT.
665 ///     All other stages make use of this ordering.  Save a lookup from BlockT
666 ///     to BlockNode (the index into RPOT) in Nodes.
667 ///
668 ///  1. Loop initialization (\a initializeLoops()).
669 ///
670 ///     Translate LoopInfo/MachineLoopInfo into a form suitable for the rest of
671 ///     the algorithm.  In particular, store the immediate members of each loop
672 ///     in reverse post-order.
673 ///
674 ///  2. Calculate mass and scale in loops (\a computeMassInLoops()).
675 ///
676 ///     For each loop (bottom-up), distribute mass through the DAG resulting
677 ///     from ignoring backedges and treating sub-loops as a single pseudo-node.
678 ///     Track the backedge mass distributed to the loop header, and use it to
679 ///     calculate the loop scale (number of loop iterations).  Immediate
680 ///     members that represent sub-loops will already have been visited and
681 ///     packaged into a pseudo-node.
682 ///
683 ///     Distributing mass in a loop is a reverse-post-order traversal through
684 ///     the loop.  Start by assigning full mass to the Loop header.  For each
685 ///     node in the loop:
686 ///
687 ///         - Fetch and categorize the weight distribution for its successors.
688 ///           If this is a packaged-subloop, the weight distribution is stored
689 ///           in \a LoopData::Exits.  Otherwise, fetch it from
690 ///           BranchProbabilityInfo.
691 ///
692 ///         - Each successor is categorized as \a Weight::Local, a local edge
693 ///           within the current loop, \a Weight::Backedge, a backedge to the
694 ///           loop header, or \a Weight::Exit, any successor outside the loop.
695 ///           The weight, the successor, and its category are stored in \a
696 ///           Distribution.  There can be multiple edges to each successor.
697 ///
698 ///         - If there's a backedge to a non-header, there's an irreducible SCC.
699 ///           The usual flow is temporarily aborted.  \a
700 ///           computeIrreducibleMass() finds the irreducible SCCs within the
701 ///           loop, packages them up, and restarts the flow.
702 ///
703 ///         - Normalize the distribution:  scale weights down so that their sum
704 ///           is 32-bits, and coalesce multiple edges to the same node.
705 ///
706 ///         - Distribute the mass accordingly, dithering to minimize mass loss,
707 ///           as described in \a distributeMass().
708 ///
709 ///     Finally, calculate the loop scale from the accumulated backedge mass.
710 ///
711 ///  3. Distribute mass in the function (\a computeMassInFunction()).
712 ///
713 ///     Finally, distribute mass through the DAG resulting from packaging all
714 ///     loops in the function.  This uses the same algorithm as distributing
715 ///     mass in a loop, except that there are no exit or backedge edges.
716 ///
717 ///  4. Unpackage loops (\a unwrapLoops()).
718 ///
719 ///     Initialize each block's frequency to a floating point representation of
720 ///     its mass.
721 ///
722 ///     Visit loops top-down, scaling the frequencies of its immediate members
723 ///     by the loop's pseudo-node's frequency.
724 ///
725 ///  5. Convert frequencies to a 64-bit range (\a finalizeMetrics()).
726 ///
727 ///     Using the min and max frequencies as a guide, translate floating point
728 ///     frequencies to an appropriate range in uint64_t.
729 ///
730 /// It has some known flaws.
731 ///
732 ///   - Loop scale is limited to 4096 per loop (2^12) to avoid exhausting
733 ///     BlockFrequency's 64-bit integer precision.
734 ///
735 ///   - The model of irreducible control flow is a rough approximation.
736 ///
737 ///     Modelling irreducible control flow exactly involves setting up and
738 ///     solving a group of infinite geometric series.  Such precision is
739 ///     unlikely to be worthwhile, since most of our algorithms give up on
740 ///     irreducible control flow anyway.
741 ///
742 ///     Nevertheless, we might find that we need to get closer.  Here's a sort
743 ///     of TODO list for the model with diminishing returns, to be completed as
744 ///     necessary.
745 ///
746 ///       - The headers for the \a LoopData representing an irreducible SCC
747 ///         include non-entry blocks.  When these extra blocks exist, they
748 ///         indicate a self-contained irreducible sub-SCC.  We could treat them
749 ///         as sub-loops, rather than arbitrarily shoving the problematic
750 ///         blocks into the headers of the main irreducible SCC.
751 ///
752 ///       - Backedge frequencies are assumed to be evenly split between the
753 ///         headers of a given irreducible SCC.  Instead, we could track the
754 ///         backedge mass separately for each header, and adjust their relative
755 ///         frequencies.
756 ///
757 ///       - Entry frequencies are assumed to be evenly split between the
758 ///         headers of a given irreducible SCC, which is the only option if we
759 ///         need to compute mass in the SCC before its parent loop.  Instead,
760 ///         we could partially compute mass in the parent loop, and stop when
761 ///         we get to the SCC.  Here, we have the correct ratio of entry
762 ///         masses, which we can use to adjust their relative frequencies.
763 ///         Compute mass in the SCC, and then continue propagation in the
764 ///         parent.
765 ///
766 ///       - We can propagate mass iteratively through the SCC, for some fixed
767 ///         number of iterations.  Each iteration starts by assigning the entry
768 ///         blocks their backedge mass from the prior iteration.  The final
769 ///         mass for each block (and each exit, and the total backedge mass
770 ///         used for computing loop scale) is the sum of all iterations.
771 ///         (Running this until fixed point would "solve" the geometric
772 ///         series by simulation.)
773 template <class BT> class BlockFrequencyInfoImpl : BlockFrequencyInfoImplBase {
774   typedef typename bfi_detail::TypeMap<BT>::BlockT BlockT;
775   typedef typename bfi_detail::TypeMap<BT>::FunctionT FunctionT;
776   typedef typename bfi_detail::TypeMap<BT>::BranchProbabilityInfoT
777   BranchProbabilityInfoT;
778   typedef typename bfi_detail::TypeMap<BT>::LoopT LoopT;
779   typedef typename bfi_detail::TypeMap<BT>::LoopInfoT LoopInfoT;
780
781   // This is part of a workaround for a GCC 4.7 crash on lambdas.
782   friend struct bfi_detail::BlockEdgesAdder<BT>;
783
784   typedef GraphTraits<const BlockT *> Successor;
785   typedef GraphTraits<Inverse<const BlockT *>> Predecessor;
786
787   const BranchProbabilityInfoT *BPI;
788   const LoopInfoT *LI;
789   const FunctionT *F;
790
791   // All blocks in reverse postorder.
792   std::vector<const BlockT *> RPOT;
793   DenseMap<const BlockT *, BlockNode> Nodes;
794
795   typedef typename std::vector<const BlockT *>::const_iterator rpot_iterator;
796
797   rpot_iterator rpot_begin() const { return RPOT.begin(); }
798   rpot_iterator rpot_end() const { return RPOT.end(); }
799
800   size_t getIndex(const rpot_iterator &I) const { return I - rpot_begin(); }
801
802   BlockNode getNode(const rpot_iterator &I) const {
803     return BlockNode(getIndex(I));
804   }
805   BlockNode getNode(const BlockT *BB) const { return Nodes.lookup(BB); }
806
807   const BlockT *getBlock(const BlockNode &Node) const {
808     assert(Node.Index < RPOT.size());
809     return RPOT[Node.Index];
810   }
811
812   /// \brief Run (and save) a post-order traversal.
813   ///
814   /// Saves a reverse post-order traversal of all the nodes in \a F.
815   void initializeRPOT();
816
817   /// \brief Initialize loop data.
818   ///
819   /// Build up \a Loops using \a LoopInfo.  \a LoopInfo gives us a mapping from
820   /// each block to the deepest loop it's in, but we need the inverse.  For each
821   /// loop, we store in reverse post-order its "immediate" members, defined as
822   /// the header, the headers of immediate sub-loops, and all other blocks in
823   /// the loop that are not in sub-loops.
824   void initializeLoops();
825
826   /// \brief Propagate to a block's successors.
827   ///
828   /// In the context of distributing mass through \c OuterLoop, divide the mass
829   /// currently assigned to \c Node between its successors.
830   ///
831   /// \return \c true unless there's an irreducible backedge.
832   bool propagateMassToSuccessors(LoopData *OuterLoop, const BlockNode &Node);
833
834   /// \brief Compute mass in a particular loop.
835   ///
836   /// Assign mass to \c Loop's header, and then for each block in \c Loop in
837   /// reverse post-order, distribute mass to its successors.  Only visits nodes
838   /// that have not been packaged into sub-loops.
839   ///
840   /// \pre \a computeMassInLoop() has been called for each subloop of \c Loop.
841   /// \return \c true unless there's an irreducible backedge.
842   bool computeMassInLoop(LoopData &Loop);
843
844   /// \brief Try to compute mass in the top-level function.
845   ///
846   /// Assign mass to the entry block, and then for each block in reverse
847   /// post-order, distribute mass to its successors.  Skips nodes that have
848   /// been packaged into loops.
849   ///
850   /// \pre \a computeMassInLoops() has been called.
851   /// \return \c true unless there's an irreducible backedge.
852   bool tryToComputeMassInFunction();
853
854   /// \brief Compute mass in (and package up) irreducible SCCs.
855   ///
856   /// Find the irreducible SCCs in \c OuterLoop, add them to \a Loops (in front
857   /// of \c Insert), and call \a computeMassInLoop() on each of them.
858   ///
859   /// If \c OuterLoop is \c nullptr, it refers to the top-level function.
860   ///
861   /// \pre \a computeMassInLoop() has been called for each subloop of \c
862   /// OuterLoop.
863   /// \pre \c Insert points at the the last loop successfully processed by \a
864   /// computeMassInLoop().
865   /// \pre \c OuterLoop has irreducible SCCs.
866   void computeIrreducibleMass(LoopData *OuterLoop,
867                               std::list<LoopData>::iterator Insert);
868
869   /// \brief Compute mass in all loops.
870   ///
871   /// For each loop bottom-up, call \a computeMassInLoop().
872   ///
873   /// \a computeMassInLoop() aborts (and returns \c false) on loops that
874   /// contain a irreducible sub-SCCs.  Use \a computeIrreducibleMass() and then
875   /// re-enter \a computeMassInLoop().
876   ///
877   /// \post \a computeMassInLoop() has returned \c true for every loop.
878   void computeMassInLoops();
879
880   /// \brief Compute mass in the top-level function.
881   ///
882   /// Uses \a tryToComputeMassInFunction() and \a computeIrreducibleMass() to
883   /// compute mass in the top-level function.
884   ///
885   /// \post \a tryToComputeMassInFunction() has returned \c true.
886   void computeMassInFunction();
887
888   std::string getBlockName(const BlockNode &Node) const override {
889     return bfi_detail::getBlockName(getBlock(Node));
890   }
891
892 public:
893   const FunctionT *getFunction() const { return F; }
894
895   void doFunction(const FunctionT *F, const BranchProbabilityInfoT *BPI,
896                   const LoopInfoT *LI);
897   BlockFrequencyInfoImpl() : BPI(nullptr), LI(nullptr), F(nullptr) {}
898
899   using BlockFrequencyInfoImplBase::getEntryFreq;
900   BlockFrequency getBlockFreq(const BlockT *BB) const {
901     return BlockFrequencyInfoImplBase::getBlockFreq(getNode(BB));
902   }
903   Scaled64 getFloatingBlockFreq(const BlockT *BB) const {
904     return BlockFrequencyInfoImplBase::getFloatingBlockFreq(getNode(BB));
905   }
906
907   /// \brief Print the frequencies for the current function.
908   ///
909   /// Prints the frequencies for the blocks in the current function.
910   ///
911   /// Blocks are printed in the natural iteration order of the function, rather
912   /// than reverse post-order.  This provides two advantages:  writing -analyze
913   /// tests is easier (since blocks come out in source order), and even
914   /// unreachable blocks are printed.
915   ///
916   /// \a BlockFrequencyInfoImplBase::print() only knows reverse post-order, so
917   /// we need to override it here.
918   raw_ostream &print(raw_ostream &OS) const override;
919   using BlockFrequencyInfoImplBase::dump;
920
921   using BlockFrequencyInfoImplBase::printBlockFreq;
922   raw_ostream &printBlockFreq(raw_ostream &OS, const BlockT *BB) const {
923     return BlockFrequencyInfoImplBase::printBlockFreq(OS, getNode(BB));
924   }
925 };
926
927 template <class BT>
928 void BlockFrequencyInfoImpl<BT>::doFunction(const FunctionT *F,
929                                             const BranchProbabilityInfoT *BPI,
930                                             const LoopInfoT *LI) {
931   // Save the parameters.
932   this->BPI = BPI;
933   this->LI = LI;
934   this->F = F;
935
936   // Clean up left-over data structures.
937   BlockFrequencyInfoImplBase::clear();
938   RPOT.clear();
939   Nodes.clear();
940
941   // Initialize.
942   DEBUG(dbgs() << "\nblock-frequency: " << F->getName() << "\n================="
943                << std::string(F->getName().size(), '=') << "\n");
944   initializeRPOT();
945   initializeLoops();
946
947   // Visit loops in post-order to find thelocal mass distribution, and then do
948   // the full function.
949   computeMassInLoops();
950   computeMassInFunction();
951   unwrapLoops();
952   finalizeMetrics();
953 }
954
955 template <class BT> void BlockFrequencyInfoImpl<BT>::initializeRPOT() {
956   const BlockT *Entry = F->begin();
957   RPOT.reserve(F->size());
958   std::copy(po_begin(Entry), po_end(Entry), std::back_inserter(RPOT));
959   std::reverse(RPOT.begin(), RPOT.end());
960
961   assert(RPOT.size() - 1 <= BlockNode::getMaxIndex() &&
962          "More nodes in function than Block Frequency Info supports");
963
964   DEBUG(dbgs() << "reverse-post-order-traversal\n");
965   for (rpot_iterator I = rpot_begin(), E = rpot_end(); I != E; ++I) {
966     BlockNode Node = getNode(I);
967     DEBUG(dbgs() << " - " << getIndex(I) << ": " << getBlockName(Node) << "\n");
968     Nodes[*I] = Node;
969   }
970
971   Working.reserve(RPOT.size());
972   for (size_t Index = 0; Index < RPOT.size(); ++Index)
973     Working.emplace_back(Index);
974   Freqs.resize(RPOT.size());
975 }
976
977 template <class BT> void BlockFrequencyInfoImpl<BT>::initializeLoops() {
978   DEBUG(dbgs() << "loop-detection\n");
979   if (LI->empty())
980     return;
981
982   // Visit loops top down and assign them an index.
983   std::deque<std::pair<const LoopT *, LoopData *>> Q;
984   for (const LoopT *L : *LI)
985     Q.emplace_back(L, nullptr);
986   while (!Q.empty()) {
987     const LoopT *Loop = Q.front().first;
988     LoopData *Parent = Q.front().second;
989     Q.pop_front();
990
991     BlockNode Header = getNode(Loop->getHeader());
992     assert(Header.isValid());
993
994     Loops.emplace_back(Parent, Header);
995     Working[Header.Index].Loop = &Loops.back();
996     DEBUG(dbgs() << " - loop = " << getBlockName(Header) << "\n");
997
998     for (const LoopT *L : *Loop)
999       Q.emplace_back(L, &Loops.back());
1000   }
1001
1002   // Visit nodes in reverse post-order and add them to their deepest containing
1003   // loop.
1004   for (size_t Index = 0; Index < RPOT.size(); ++Index) {
1005     // Loop headers have already been mostly mapped.
1006     if (Working[Index].isLoopHeader()) {
1007       LoopData *ContainingLoop = Working[Index].getContainingLoop();
1008       if (ContainingLoop)
1009         ContainingLoop->Nodes.push_back(Index);
1010       continue;
1011     }
1012
1013     const LoopT *Loop = LI->getLoopFor(RPOT[Index]);
1014     if (!Loop)
1015       continue;
1016
1017     // Add this node to its containing loop's member list.
1018     BlockNode Header = getNode(Loop->getHeader());
1019     assert(Header.isValid());
1020     const auto &HeaderData = Working[Header.Index];
1021     assert(HeaderData.isLoopHeader());
1022
1023     Working[Index].Loop = HeaderData.Loop;
1024     HeaderData.Loop->Nodes.push_back(Index);
1025     DEBUG(dbgs() << " - loop = " << getBlockName(Header)
1026                  << ": member = " << getBlockName(Index) << "\n");
1027   }
1028 }
1029
1030 template <class BT> void BlockFrequencyInfoImpl<BT>::computeMassInLoops() {
1031   // Visit loops with the deepest first, and the top-level loops last.
1032   for (auto L = Loops.rbegin(), E = Loops.rend(); L != E; ++L) {
1033     if (computeMassInLoop(*L))
1034       continue;
1035     auto Next = std::next(L);
1036     computeIrreducibleMass(&*L, L.base());
1037     L = std::prev(Next);
1038     if (computeMassInLoop(*L))
1039       continue;
1040     llvm_unreachable("unhandled irreducible control flow");
1041   }
1042 }
1043
1044 template <class BT>
1045 bool BlockFrequencyInfoImpl<BT>::computeMassInLoop(LoopData &Loop) {
1046   // Compute mass in loop.
1047   DEBUG(dbgs() << "compute-mass-in-loop: " << getLoopName(Loop) << "\n");
1048
1049   if (Loop.isIrreducible()) {
1050     BlockMass Remaining = BlockMass::getFull();
1051     for (uint32_t H = 0; H < Loop.NumHeaders; ++H) {
1052       auto &Mass = Working[Loop.Nodes[H].Index].getMass();
1053       Mass = Remaining * BranchProbability(1, Loop.NumHeaders - H);
1054       Remaining -= Mass;
1055     }
1056     for (const BlockNode &M : Loop.Nodes)
1057       if (!propagateMassToSuccessors(&Loop, M))
1058         llvm_unreachable("unhandled irreducible control flow");
1059   } else {
1060     Working[Loop.getHeader().Index].getMass() = BlockMass::getFull();
1061     if (!propagateMassToSuccessors(&Loop, Loop.getHeader()))
1062       llvm_unreachable("irreducible control flow to loop header!?");
1063     for (const BlockNode &M : Loop.members())
1064       if (!propagateMassToSuccessors(&Loop, M))
1065         // Irreducible backedge.
1066         return false;
1067   }
1068
1069   computeLoopScale(Loop);
1070   packageLoop(Loop);
1071   return true;
1072 }
1073
1074 template <class BT>
1075 bool BlockFrequencyInfoImpl<BT>::tryToComputeMassInFunction() {
1076   // Compute mass in function.
1077   DEBUG(dbgs() << "compute-mass-in-function\n");
1078   assert(!Working.empty() && "no blocks in function");
1079   assert(!Working[0].isLoopHeader() && "entry block is a loop header");
1080
1081   Working[0].getMass() = BlockMass::getFull();
1082   for (rpot_iterator I = rpot_begin(), IE = rpot_end(); I != IE; ++I) {
1083     // Check for nodes that have been packaged.
1084     BlockNode Node = getNode(I);
1085     if (Working[Node.Index].isPackaged())
1086       continue;
1087
1088     if (!propagateMassToSuccessors(nullptr, Node))
1089       return false;
1090   }
1091   return true;
1092 }
1093
1094 template <class BT> void BlockFrequencyInfoImpl<BT>::computeMassInFunction() {
1095   if (tryToComputeMassInFunction())
1096     return;
1097   computeIrreducibleMass(nullptr, Loops.begin());
1098   if (tryToComputeMassInFunction())
1099     return;
1100   llvm_unreachable("unhandled irreducible control flow");
1101 }
1102
1103 /// \note This should be a lambda, but that crashes GCC 4.7.
1104 namespace bfi_detail {
1105 template <class BT> struct BlockEdgesAdder {
1106   typedef BT BlockT;
1107   typedef BlockFrequencyInfoImplBase::LoopData LoopData;
1108   typedef GraphTraits<const BlockT *> Successor;
1109
1110   const BlockFrequencyInfoImpl<BT> &BFI;
1111   explicit BlockEdgesAdder(const BlockFrequencyInfoImpl<BT> &BFI)
1112       : BFI(BFI) {}
1113   void operator()(IrreducibleGraph &G, IrreducibleGraph::IrrNode &Irr,
1114                   const LoopData *OuterLoop) {
1115     const BlockT *BB = BFI.RPOT[Irr.Node.Index];
1116     for (auto I = Successor::child_begin(BB), E = Successor::child_end(BB);
1117          I != E; ++I)
1118       G.addEdge(Irr, BFI.getNode(*I), OuterLoop);
1119   }
1120 };
1121 }
1122 template <class BT>
1123 void BlockFrequencyInfoImpl<BT>::computeIrreducibleMass(
1124     LoopData *OuterLoop, std::list<LoopData>::iterator Insert) {
1125   DEBUG(dbgs() << "analyze-irreducible-in-";
1126         if (OuterLoop) dbgs() << "loop: " << getLoopName(*OuterLoop) << "\n";
1127         else dbgs() << "function\n");
1128
1129   using namespace bfi_detail;
1130   // Ideally, addBlockEdges() would be declared here as a lambda, but that
1131   // crashes GCC 4.7.
1132   BlockEdgesAdder<BT> addBlockEdges(*this);
1133   IrreducibleGraph G(*this, OuterLoop, addBlockEdges);
1134
1135   for (auto &L : analyzeIrreducible(G, OuterLoop, Insert))
1136     computeMassInLoop(L);
1137
1138   if (!OuterLoop)
1139     return;
1140   updateLoopWithIrreducible(*OuterLoop);
1141 }
1142
1143 template <class BT>
1144 bool
1145 BlockFrequencyInfoImpl<BT>::propagateMassToSuccessors(LoopData *OuterLoop,
1146                                                       const BlockNode &Node) {
1147   DEBUG(dbgs() << " - node: " << getBlockName(Node) << "\n");
1148   // Calculate probability for successors.
1149   Distribution Dist;
1150   if (auto *Loop = Working[Node.Index].getPackagedLoop()) {
1151     assert(Loop != OuterLoop && "Cannot propagate mass in a packaged loop");
1152     if (!addLoopSuccessorsToDist(OuterLoop, *Loop, Dist))
1153       // Irreducible backedge.
1154       return false;
1155   } else {
1156     const BlockT *BB = getBlock(Node);
1157     for (auto SI = Successor::child_begin(BB), SE = Successor::child_end(BB);
1158          SI != SE; ++SI)
1159       // Do not dereference SI, or getEdgeWeight() is linear in the number of
1160       // successors.
1161       if (!addToDist(Dist, OuterLoop, Node, getNode(*SI),
1162                      BPI->getEdgeWeight(BB, SI)))
1163         // Irreducible backedge.
1164         return false;
1165   }
1166
1167   // Distribute mass to successors, saving exit and backedge data in the
1168   // loop header.
1169   distributeMass(Node, OuterLoop, Dist);
1170   return true;
1171 }
1172
1173 template <class BT>
1174 raw_ostream &BlockFrequencyInfoImpl<BT>::print(raw_ostream &OS) const {
1175   if (!F)
1176     return OS;
1177   OS << "block-frequency-info: " << F->getName() << "\n";
1178   for (const BlockT &BB : *F)
1179     OS << " - " << bfi_detail::getBlockName(&BB)
1180        << ": float = " << getFloatingBlockFreq(&BB)
1181        << ", int = " << getBlockFreq(&BB).getFrequency() << "\n";
1182
1183   // Add an extra newline for readability.
1184   OS << "\n";
1185   return OS;
1186 }
1187
1188 } // end namespace llvm
1189
1190 #undef DEBUG_TYPE
1191
1192 #endif