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