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