xref: /netbsd-src/external/apache2/llvm/dist/llvm/include/llvm/Analysis/BlockFrequencyInfoImpl.h (revision 82d56013d7b633d116a93943de88e08335357a7c)
1 //==- BlockFrequencyInfoImpl.h - Block Frequency Implementation --*- C++ -*-==//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // Shared implementation of BlockFrequency for IR and Machine Instructions.
10 // See the documentation below for BlockFrequencyInfoImpl for details.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #ifndef LLVM_ANALYSIS_BLOCKFREQUENCYINFOIMPL_H
15 #define LLVM_ANALYSIS_BLOCKFREQUENCYINFOIMPL_H
16 
17 #include "llvm/ADT/DenseMap.h"
18 #include "llvm/ADT/DenseSet.h"
19 #include "llvm/ADT/GraphTraits.h"
20 #include "llvm/ADT/Optional.h"
21 #include "llvm/ADT/PostOrderIterator.h"
22 #include "llvm/ADT/SmallVector.h"
23 #include "llvm/ADT/SparseBitVector.h"
24 #include "llvm/ADT/Twine.h"
25 #include "llvm/ADT/iterator_range.h"
26 #include "llvm/IR/BasicBlock.h"
27 #include "llvm/IR/ValueHandle.h"
28 #include "llvm/Support/BlockFrequency.h"
29 #include "llvm/Support/BranchProbability.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/DOTGraphTraits.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/Format.h"
35 #include "llvm/Support/ScaledNumber.h"
36 #include "llvm/Support/raw_ostream.h"
37 #include <algorithm>
38 #include <cassert>
39 #include <cstddef>
40 #include <cstdint>
41 #include <deque>
42 #include <iterator>
43 #include <limits>
44 #include <list>
45 #include <string>
46 #include <utility>
47 #include <vector>
48 
49 #define DEBUG_TYPE "block-freq"
50 
51 namespace llvm {
52 extern llvm::cl::opt<bool> CheckBFIUnknownBlockQueries;
53 
54 class BranchProbabilityInfo;
55 class Function;
56 class Loop;
57 class LoopInfo;
58 class MachineBasicBlock;
59 class MachineBranchProbabilityInfo;
60 class MachineFunction;
61 class MachineLoop;
62 class MachineLoopInfo;
63 
64 namespace bfi_detail {
65 
66 struct IrreducibleGraph;
67 
68 // This is part of a workaround for a GCC 4.7 crash on lambdas.
69 template <class BT> struct BlockEdgesAdder;
70 
71 /// Mass of a block.
72 ///
73 /// This class implements a sort of fixed-point fraction always between 0.0 and
74 /// 1.0.  getMass() == std::numeric_limits<uint64_t>::max() indicates a value of
75 /// 1.0.
76 ///
77 /// Masses can be added and subtracted.  Simple saturation arithmetic is used,
78 /// so arithmetic operations never overflow or underflow.
79 ///
80 /// Masses can be multiplied.  Multiplication treats full mass as 1.0 and uses
81 /// an inexpensive floating-point algorithm that's off-by-one (almost, but not
82 /// quite, maximum precision).
83 ///
84 /// Masses can be scaled by \a BranchProbability at maximum precision.
85 class BlockMass {
86   uint64_t Mass = 0;
87 
88 public:
89   BlockMass() = default;
BlockMass(uint64_t Mass)90   explicit BlockMass(uint64_t Mass) : Mass(Mass) {}
91 
getEmpty()92   static BlockMass getEmpty() { return BlockMass(); }
93 
getFull()94   static BlockMass getFull() {
95     return BlockMass(std::numeric_limits<uint64_t>::max());
96   }
97 
getMass()98   uint64_t getMass() const { return Mass; }
99 
isFull()100   bool isFull() const { return Mass == std::numeric_limits<uint64_t>::max(); }
isEmpty()101   bool isEmpty() const { return !Mass; }
102 
103   bool operator!() const { return isEmpty(); }
104 
105   /// Add another mass.
106   ///
107   /// Adds another mass, saturating at \a isFull() rather than overflowing.
108   BlockMass &operator+=(BlockMass X) {
109     uint64_t Sum = Mass + X.Mass;
110     Mass = Sum < Mass ? std::numeric_limits<uint64_t>::max() : Sum;
111     return *this;
112   }
113 
114   /// Subtract another mass.
115   ///
116   /// Subtracts another mass, saturating at \a isEmpty() rather than
117   /// undeflowing.
118   BlockMass &operator-=(BlockMass X) {
119     uint64_t Diff = Mass - X.Mass;
120     Mass = Diff > Mass ? 0 : Diff;
121     return *this;
122   }
123 
124   BlockMass &operator*=(BranchProbability P) {
125     Mass = P.scale(Mass);
126     return *this;
127   }
128 
129   bool operator==(BlockMass X) const { return Mass == X.Mass; }
130   bool operator!=(BlockMass X) const { return Mass != X.Mass; }
131   bool operator<=(BlockMass X) const { return Mass <= X.Mass; }
132   bool operator>=(BlockMass X) const { return Mass >= X.Mass; }
133   bool operator<(BlockMass X) const { return Mass < X.Mass; }
134   bool operator>(BlockMass X) const { return Mass > X.Mass; }
135 
136   /// Convert to scaled number.
137   ///
138   /// Convert to \a ScaledNumber.  \a isFull() gives 1.0, while \a isEmpty()
139   /// gives slightly above 0.0.
140   ScaledNumber<uint64_t> toScaled() const;
141 
142   void dump() const;
143   raw_ostream &print(raw_ostream &OS) const;
144 };
145 
146 inline BlockMass operator+(BlockMass L, BlockMass R) {
147   return BlockMass(L) += R;
148 }
149 inline BlockMass operator-(BlockMass L, BlockMass R) {
150   return BlockMass(L) -= R;
151 }
152 inline BlockMass operator*(BlockMass L, BranchProbability R) {
153   return BlockMass(L) *= R;
154 }
155 inline BlockMass operator*(BranchProbability L, BlockMass R) {
156   return BlockMass(R) *= L;
157 }
158 
159 inline raw_ostream &operator<<(raw_ostream &OS, BlockMass X) {
160   return X.print(OS);
161 }
162 
163 } // end namespace bfi_detail
164 
165 /// Base class for BlockFrequencyInfoImpl
166 ///
167 /// BlockFrequencyInfoImplBase has supporting data structures and some
168 /// algorithms for BlockFrequencyInfoImplBase.  Only algorithms that depend on
169 /// the block type (or that call such algorithms) are skipped here.
170 ///
171 /// Nevertheless, the majority of the overall algorithm documentation lives with
172 /// BlockFrequencyInfoImpl.  See there for details.
173 class BlockFrequencyInfoImplBase {
174 public:
175   using Scaled64 = ScaledNumber<uint64_t>;
176   using BlockMass = bfi_detail::BlockMass;
177 
178   /// Representative of a block.
179   ///
180   /// This is a simple wrapper around an index into the reverse-post-order
181   /// traversal of the blocks.
182   ///
183   /// Unlike a block pointer, its order has meaning (location in the
184   /// topological sort) and it's class is the same regardless of block type.
185   struct BlockNode {
186     using IndexType = uint32_t;
187 
188     IndexType Index;
189 
BlockNodeBlockNode190     BlockNode() : Index(std::numeric_limits<uint32_t>::max()) {}
BlockNodeBlockNode191     BlockNode(IndexType Index) : Index(Index) {}
192 
193     bool operator==(const BlockNode &X) const { return Index == X.Index; }
194     bool operator!=(const BlockNode &X) const { return Index != X.Index; }
195     bool operator<=(const BlockNode &X) const { return Index <= X.Index; }
196     bool operator>=(const BlockNode &X) const { return Index >= X.Index; }
197     bool operator<(const BlockNode &X) const { return Index < X.Index; }
198     bool operator>(const BlockNode &X) const { return Index > X.Index; }
199 
isValidBlockNode200     bool isValid() const { return Index <= getMaxIndex(); }
201 
getMaxIndexBlockNode202     static size_t getMaxIndex() {
203        return std::numeric_limits<uint32_t>::max() - 1;
204     }
205   };
206 
207   /// Stats about a block itself.
208   struct FrequencyData {
209     Scaled64 Scaled;
210     uint64_t Integer;
211   };
212 
213   /// Data about a loop.
214   ///
215   /// Contains the data necessary to represent a loop as a pseudo-node once it's
216   /// packaged.
217   struct LoopData {
218     using ExitMap = SmallVector<std::pair<BlockNode, BlockMass>, 4>;
219     using NodeList = SmallVector<BlockNode, 4>;
220     using HeaderMassList = SmallVector<BlockMass, 1>;
221 
222     LoopData *Parent;            ///< The parent loop.
223     bool IsPackaged = false;     ///< Whether this has been packaged.
224     uint32_t NumHeaders = 1;     ///< Number of headers.
225     ExitMap Exits;               ///< Successor edges (and weights).
226     NodeList Nodes;              ///< Header and the members of the loop.
227     HeaderMassList BackedgeMass; ///< Mass returned to each loop header.
228     BlockMass Mass;
229     Scaled64 Scale;
230 
LoopDataLoopData231     LoopData(LoopData *Parent, const BlockNode &Header)
232       : Parent(Parent), Nodes(1, Header), BackedgeMass(1) {}
233 
234     template <class It1, class It2>
LoopDataLoopData235     LoopData(LoopData *Parent, It1 FirstHeader, It1 LastHeader, It2 FirstOther,
236              It2 LastOther)
237         : Parent(Parent), Nodes(FirstHeader, LastHeader) {
238       NumHeaders = Nodes.size();
239       Nodes.insert(Nodes.end(), FirstOther, LastOther);
240       BackedgeMass.resize(NumHeaders);
241     }
242 
isHeaderLoopData243     bool isHeader(const BlockNode &Node) const {
244       if (isIrreducible())
245         return std::binary_search(Nodes.begin(), Nodes.begin() + NumHeaders,
246                                   Node);
247       return Node == Nodes[0];
248     }
249 
getHeaderLoopData250     BlockNode getHeader() const { return Nodes[0]; }
isIrreducibleLoopData251     bool isIrreducible() const { return NumHeaders > 1; }
252 
getHeaderIndexLoopData253     HeaderMassList::difference_type getHeaderIndex(const BlockNode &B) {
254       assert(isHeader(B) && "this is only valid on loop header blocks");
255       if (isIrreducible())
256         return std::lower_bound(Nodes.begin(), Nodes.begin() + NumHeaders, B) -
257                Nodes.begin();
258       return 0;
259     }
260 
members_beginLoopData261     NodeList::const_iterator members_begin() const {
262       return Nodes.begin() + NumHeaders;
263     }
264 
members_endLoopData265     NodeList::const_iterator members_end() const { return Nodes.end(); }
membersLoopData266     iterator_range<NodeList::const_iterator> members() const {
267       return make_range(members_begin(), members_end());
268     }
269   };
270 
271   /// Index of loop information.
272   struct WorkingData {
273     BlockNode Node;           ///< This node.
274     LoopData *Loop = nullptr; ///< The loop this block is inside.
275     BlockMass Mass;           ///< Mass distribution from the entry block.
276 
WorkingDataWorkingData277     WorkingData(const BlockNode &Node) : Node(Node) {}
278 
isLoopHeaderWorkingData279     bool isLoopHeader() const { return Loop && Loop->isHeader(Node); }
280 
isDoubleLoopHeaderWorkingData281     bool isDoubleLoopHeader() const {
282       return isLoopHeader() && Loop->Parent && Loop->Parent->isIrreducible() &&
283              Loop->Parent->isHeader(Node);
284     }
285 
getContainingLoopWorkingData286     LoopData *getContainingLoop() const {
287       if (!isLoopHeader())
288         return Loop;
289       if (!isDoubleLoopHeader())
290         return Loop->Parent;
291       return Loop->Parent->Parent;
292     }
293 
294     /// Resolve a node to its representative.
295     ///
296     /// Get the node currently representing Node, which could be a containing
297     /// loop.
298     ///
299     /// This function should only be called when distributing mass.  As long as
300     /// there are no irreducible edges to Node, then it will have complexity
301     /// O(1) in this context.
302     ///
303     /// In general, the complexity is O(L), where L is the number of loop
304     /// headers Node has been packaged into.  Since this method is called in
305     /// the context of distributing mass, L will be the number of loop headers
306     /// an early exit edge jumps out of.
getResolvedNodeWorkingData307     BlockNode getResolvedNode() const {
308       auto L = getPackagedLoop();
309       return L ? L->getHeader() : Node;
310     }
311 
getPackagedLoopWorkingData312     LoopData *getPackagedLoop() const {
313       if (!Loop || !Loop->IsPackaged)
314         return nullptr;
315       auto L = Loop;
316       while (L->Parent && L->Parent->IsPackaged)
317         L = L->Parent;
318       return L;
319     }
320 
321     /// Get the appropriate mass for a node.
322     ///
323     /// Get appropriate mass for Node.  If Node is a loop-header (whose loop
324     /// has been packaged), returns the mass of its pseudo-node.  If it's a
325     /// node inside a packaged loop, it returns the loop's mass.
getMassWorkingData326     BlockMass &getMass() {
327       if (!isAPackage())
328         return Mass;
329       if (!isADoublePackage())
330         return Loop->Mass;
331       return Loop->Parent->Mass;
332     }
333 
334     /// Has ContainingLoop been packaged up?
isPackagedWorkingData335     bool isPackaged() const { return getResolvedNode() != Node; }
336 
337     /// Has Loop been packaged up?
isAPackageWorkingData338     bool isAPackage() const { return isLoopHeader() && Loop->IsPackaged; }
339 
340     /// Has Loop been packaged up twice?
isADoublePackageWorkingData341     bool isADoublePackage() const {
342       return isDoubleLoopHeader() && Loop->Parent->IsPackaged;
343     }
344   };
345 
346   /// Unscaled probability weight.
347   ///
348   /// Probability weight for an edge in the graph (including the
349   /// successor/target node).
350   ///
351   /// All edges in the original function are 32-bit.  However, exit edges from
352   /// loop packages are taken from 64-bit exit masses, so we need 64-bits of
353   /// space in general.
354   ///
355   /// In addition to the raw weight amount, Weight stores the type of the edge
356   /// in the current context (i.e., the context of the loop being processed).
357   /// Is this a local edge within the loop, an exit from the loop, or a
358   /// backedge to the loop header?
359   struct Weight {
360     enum DistType { Local, Exit, Backedge };
361     DistType Type = Local;
362     BlockNode TargetNode;
363     uint64_t Amount = 0;
364 
365     Weight() = default;
WeightWeight366     Weight(DistType Type, BlockNode TargetNode, uint64_t Amount)
367         : Type(Type), TargetNode(TargetNode), Amount(Amount) {}
368   };
369 
370   /// Distribution of unscaled probability weight.
371   ///
372   /// Distribution of unscaled probability weight to a set of successors.
373   ///
374   /// This class collates the successor edge weights for later processing.
375   ///
376   /// \a DidOverflow indicates whether \a Total did overflow while adding to
377   /// the distribution.  It should never overflow twice.
378   struct Distribution {
379     using WeightList = SmallVector<Weight, 4>;
380 
381     WeightList Weights;       ///< Individual successor weights.
382     uint64_t Total = 0;       ///< Sum of all weights.
383     bool DidOverflow = false; ///< Whether \a Total did overflow.
384 
385     Distribution() = default;
386 
addLocalDistribution387     void addLocal(const BlockNode &Node, uint64_t Amount) {
388       add(Node, Amount, Weight::Local);
389     }
390 
addExitDistribution391     void addExit(const BlockNode &Node, uint64_t Amount) {
392       add(Node, Amount, Weight::Exit);
393     }
394 
addBackedgeDistribution395     void addBackedge(const BlockNode &Node, uint64_t Amount) {
396       add(Node, Amount, Weight::Backedge);
397     }
398 
399     /// Normalize the distribution.
400     ///
401     /// Combines multiple edges to the same \a Weight::TargetNode and scales
402     /// down so that \a Total fits into 32-bits.
403     ///
404     /// This is linear in the size of \a Weights.  For the vast majority of
405     /// cases, adjacent edge weights are combined by sorting WeightList and
406     /// combining adjacent weights.  However, for very large edge lists an
407     /// auxiliary hash table is used.
408     void normalize();
409 
410   private:
411     void add(const BlockNode &Node, uint64_t Amount, Weight::DistType Type);
412   };
413 
414   /// Data about each block.  This is used downstream.
415   std::vector<FrequencyData> Freqs;
416 
417   /// Whether each block is an irreducible loop header.
418   /// This is used downstream.
419   SparseBitVector<> IsIrrLoopHeader;
420 
421   /// Loop data: see initializeLoops().
422   std::vector<WorkingData> Working;
423 
424   /// Indexed information about loops.
425   std::list<LoopData> Loops;
426 
427   /// Virtual destructor.
428   ///
429   /// Need a virtual destructor to mask the compiler warning about
430   /// getBlockName().
431   virtual ~BlockFrequencyInfoImplBase() = default;
432 
433   /// Add all edges out of a packaged loop to the distribution.
434   ///
435   /// Adds all edges from LocalLoopHead to Dist.  Calls addToDist() to add each
436   /// successor edge.
437   ///
438   /// \return \c true unless there's an irreducible backedge.
439   bool addLoopSuccessorsToDist(const LoopData *OuterLoop, LoopData &Loop,
440                                Distribution &Dist);
441 
442   /// Add an edge to the distribution.
443   ///
444   /// Adds an edge to Succ to Dist.  If \c LoopHead.isValid(), then whether the
445   /// edge is local/exit/backedge is in the context of LoopHead.  Otherwise,
446   /// every edge should be a local edge (since all the loops are packaged up).
447   ///
448   /// \return \c true unless aborted due to an irreducible backedge.
449   bool addToDist(Distribution &Dist, const LoopData *OuterLoop,
450                  const BlockNode &Pred, const BlockNode &Succ, uint64_t Weight);
451 
getLoopPackage(const BlockNode & Head)452   LoopData &getLoopPackage(const BlockNode &Head) {
453     assert(Head.Index < Working.size());
454     assert(Working[Head.Index].isLoopHeader());
455     return *Working[Head.Index].Loop;
456   }
457 
458   /// Analyze irreducible SCCs.
459   ///
460   /// Separate irreducible SCCs from \c G, which is an explicit graph of \c
461   /// OuterLoop (or the top-level function, if \c OuterLoop is \c nullptr).
462   /// Insert them into \a Loops before \c Insert.
463   ///
464   /// \return the \c LoopData nodes representing the irreducible SCCs.
465   iterator_range<std::list<LoopData>::iterator>
466   analyzeIrreducible(const bfi_detail::IrreducibleGraph &G, LoopData *OuterLoop,
467                      std::list<LoopData>::iterator Insert);
468 
469   /// Update a loop after packaging irreducible SCCs inside of it.
470   ///
471   /// Update \c OuterLoop.  Before finding irreducible control flow, it was
472   /// partway through \a computeMassInLoop(), so \a LoopData::Exits and \a
473   /// LoopData::BackedgeMass need to be reset.  Also, nodes that were packaged
474   /// up need to be removed from \a OuterLoop::Nodes.
475   void updateLoopWithIrreducible(LoopData &OuterLoop);
476 
477   /// Distribute mass according to a distribution.
478   ///
479   /// Distributes the mass in Source according to Dist.  If LoopHead.isValid(),
480   /// backedges and exits are stored in its entry in Loops.
481   ///
482   /// Mass is distributed in parallel from two copies of the source mass.
483   void distributeMass(const BlockNode &Source, LoopData *OuterLoop,
484                       Distribution &Dist);
485 
486   /// Compute the loop scale for a loop.
487   void computeLoopScale(LoopData &Loop);
488 
489   /// Adjust the mass of all headers in an irreducible loop.
490   ///
491   /// Initially, irreducible loops are assumed to distribute their mass
492   /// equally among its headers. This can lead to wrong frequency estimates
493   /// since some headers may be executed more frequently than others.
494   ///
495   /// This adjusts header mass distribution so it matches the weights of
496   /// the backedges going into each of the loop headers.
497   void adjustLoopHeaderMass(LoopData &Loop);
498 
499   void distributeIrrLoopHeaderMass(Distribution &Dist);
500 
501   /// Package up a loop.
502   void packageLoop(LoopData &Loop);
503 
504   /// Unwrap loops.
505   void unwrapLoops();
506 
507   /// Finalize frequency metrics.
508   ///
509   /// Calculates final frequencies and cleans up no-longer-needed data
510   /// structures.
511   void finalizeMetrics();
512 
513   /// Clear all memory.
514   void clear();
515 
516   virtual std::string getBlockName(const BlockNode &Node) const;
517   std::string getLoopName(const LoopData &Loop) const;
518 
print(raw_ostream & OS)519   virtual raw_ostream &print(raw_ostream &OS) const { return OS; }
dump()520   void dump() const { print(dbgs()); }
521 
522   Scaled64 getFloatingBlockFreq(const BlockNode &Node) const;
523 
524   BlockFrequency getBlockFreq(const BlockNode &Node) const;
525   Optional<uint64_t> getBlockProfileCount(const Function &F,
526                                           const BlockNode &Node,
527                                           bool AllowSynthetic = false) const;
528   Optional<uint64_t> getProfileCountFromFreq(const Function &F,
529                                              uint64_t Freq,
530                                              bool AllowSynthetic = false) const;
531   bool isIrrLoopHeader(const BlockNode &Node);
532 
533   void setBlockFreq(const BlockNode &Node, uint64_t Freq);
534 
535   raw_ostream &printBlockFreq(raw_ostream &OS, const BlockNode &Node) const;
536   raw_ostream &printBlockFreq(raw_ostream &OS,
537                               const BlockFrequency &Freq) const;
538 
getEntryFreq()539   uint64_t getEntryFreq() const {
540     assert(!Freqs.empty());
541     return Freqs[0].Integer;
542   }
543 };
544 
545 namespace bfi_detail {
546 
547 template <class BlockT> struct TypeMap {};
548 template <> struct TypeMap<BasicBlock> {
549   using BlockT = BasicBlock;
550   using BlockKeyT = AssertingVH<const BasicBlock>;
551   using FunctionT = Function;
552   using BranchProbabilityInfoT = BranchProbabilityInfo;
553   using LoopT = Loop;
554   using LoopInfoT = LoopInfo;
555 };
556 template <> struct TypeMap<MachineBasicBlock> {
557   using BlockT = MachineBasicBlock;
558   using BlockKeyT = const MachineBasicBlock *;
559   using FunctionT = MachineFunction;
560   using BranchProbabilityInfoT = MachineBranchProbabilityInfo;
561   using LoopT = MachineLoop;
562   using LoopInfoT = MachineLoopInfo;
563 };
564 
565 template <class BlockT, class BFIImplT>
566 class BFICallbackVH;
567 
568 /// Get the name of a MachineBasicBlock.
569 ///
570 /// Get the name of a MachineBasicBlock.  It's templated so that including from
571 /// CodeGen is unnecessary (that would be a layering issue).
572 ///
573 /// This is used mainly for debug output.  The name is similar to
574 /// MachineBasicBlock::getFullName(), but skips the name of the function.
575 template <class BlockT> std::string getBlockName(const BlockT *BB) {
576   assert(BB && "Unexpected nullptr");
577   auto MachineName = "BB" + Twine(BB->getNumber());
578   if (BB->getBasicBlock())
579     return (MachineName + "[" + BB->getName() + "]").str();
580   return MachineName.str();
581 }
582 /// Get the name of a BasicBlock.
583 template <> inline std::string getBlockName(const BasicBlock *BB) {
584   assert(BB && "Unexpected nullptr");
585   return BB->getName().str();
586 }
587 
588 /// Graph of irreducible control flow.
589 ///
590 /// This graph is used for determining the SCCs in a loop (or top-level
591 /// function) that has irreducible control flow.
592 ///
593 /// During the block frequency algorithm, the local graphs are defined in a
594 /// light-weight way, deferring to the \a BasicBlock or \a MachineBasicBlock
595 /// graphs for most edges, but getting others from \a LoopData::ExitMap.  The
596 /// latter only has successor information.
597 ///
598 /// \a IrreducibleGraph makes this graph explicit.  It's in a form that can use
599 /// \a GraphTraits (so that \a analyzeIrreducible() can use \a scc_iterator),
600 /// and it explicitly lists predecessors and successors.  The initialization
601 /// that relies on \c MachineBasicBlock is defined in the header.
602 struct IrreducibleGraph {
603   using BFIBase = BlockFrequencyInfoImplBase;
604 
605   BFIBase &BFI;
606 
607   using BlockNode = BFIBase::BlockNode;
608   struct IrrNode {
609     BlockNode Node;
610     unsigned NumIn = 0;
611     std::deque<const IrrNode *> Edges;
612 
613     IrrNode(const BlockNode &Node) : Node(Node) {}
614 
615     using iterator = std::deque<const IrrNode *>::const_iterator;
616 
617     iterator pred_begin() const { return Edges.begin(); }
618     iterator succ_begin() const { return Edges.begin() + NumIn; }
619     iterator pred_end() const { return succ_begin(); }
620     iterator succ_end() const { return Edges.end(); }
621   };
622   BlockNode Start;
623   const IrrNode *StartIrr = nullptr;
624   std::vector<IrrNode> Nodes;
625   SmallDenseMap<uint32_t, IrrNode *, 4> Lookup;
626 
627   /// Construct an explicit graph containing irreducible control flow.
628   ///
629   /// Construct an explicit graph of the control flow in \c OuterLoop (or the
630   /// top-level function, if \c OuterLoop is \c nullptr).  Uses \c
631   /// addBlockEdges to add block successors that have not been packaged into
632   /// loops.
633   ///
634   /// \a BlockFrequencyInfoImpl::computeIrreducibleMass() is the only expected
635   /// user of this.
636   template <class BlockEdgesAdder>
637   IrreducibleGraph(BFIBase &BFI, const BFIBase::LoopData *OuterLoop,
638                    BlockEdgesAdder addBlockEdges) : BFI(BFI) {
639     initialize(OuterLoop, addBlockEdges);
640   }
641 
642   template <class BlockEdgesAdder>
643   void initialize(const BFIBase::LoopData *OuterLoop,
644                   BlockEdgesAdder addBlockEdges);
645   void addNodesInLoop(const BFIBase::LoopData &OuterLoop);
646   void addNodesInFunction();
647 
648   void addNode(const BlockNode &Node) {
649     Nodes.emplace_back(Node);
650     BFI.Working[Node.Index].getMass() = BlockMass::getEmpty();
651   }
652 
653   void indexNodes();
654   template <class BlockEdgesAdder>
655   void addEdges(const BlockNode &Node, const BFIBase::LoopData *OuterLoop,
656                 BlockEdgesAdder addBlockEdges);
657   void addEdge(IrrNode &Irr, const BlockNode &Succ,
658                const BFIBase::LoopData *OuterLoop);
659 };
660 
661 template <class BlockEdgesAdder>
662 void IrreducibleGraph::initialize(const BFIBase::LoopData *OuterLoop,
663                                   BlockEdgesAdder addBlockEdges) {
664   if (OuterLoop) {
665     addNodesInLoop(*OuterLoop);
666     for (auto N : OuterLoop->Nodes)
667       addEdges(N, OuterLoop, addBlockEdges);
668   } else {
669     addNodesInFunction();
670     for (uint32_t Index = 0; Index < BFI.Working.size(); ++Index)
671       addEdges(Index, OuterLoop, addBlockEdges);
672   }
673   StartIrr = Lookup[Start.Index];
674 }
675 
676 template <class BlockEdgesAdder>
677 void IrreducibleGraph::addEdges(const BlockNode &Node,
678                                 const BFIBase::LoopData *OuterLoop,
679                                 BlockEdgesAdder addBlockEdges) {
680   auto L = Lookup.find(Node.Index);
681   if (L == Lookup.end())
682     return;
683   IrrNode &Irr = *L->second;
684   const auto &Working = BFI.Working[Node.Index];
685 
686   if (Working.isAPackage())
687     for (const auto &I : Working.Loop->Exits)
688       addEdge(Irr, I.first, OuterLoop);
689   else
690     addBlockEdges(*this, Irr, OuterLoop);
691 }
692 
693 } // end namespace bfi_detail
694 
695 /// Shared implementation for block frequency analysis.
696 ///
697 /// This is a shared implementation of BlockFrequencyInfo and
698 /// MachineBlockFrequencyInfo, and calculates the relative frequencies of
699 /// blocks.
700 ///
701 /// LoopInfo defines a loop as a "non-trivial" SCC dominated by a single block,
702 /// which is called the header.  A given loop, L, can have sub-loops, which are
703 /// loops within the subgraph of L that exclude its header.  (A "trivial" SCC
704 /// consists of a single block that does not have a self-edge.)
705 ///
706 /// In addition to loops, this algorithm has limited support for irreducible
707 /// SCCs, which are SCCs with multiple entry blocks.  Irreducible SCCs are
708 /// discovered on the fly, and modelled as loops with multiple headers.
709 ///
710 /// The headers of irreducible sub-SCCs consist of its entry blocks and all
711 /// nodes that are targets of a backedge within it (excluding backedges within
712 /// true sub-loops).  Block frequency calculations act as if a block is
713 /// inserted that intercepts all the edges to the headers.  All backedges and
714 /// entries point to this block.  Its successors are the headers, which split
715 /// the frequency evenly.
716 ///
717 /// This algorithm leverages BlockMass and ScaledNumber to maintain precision,
718 /// separates mass distribution from loop scaling, and dithers to eliminate
719 /// probability mass loss.
720 ///
721 /// The implementation is split between BlockFrequencyInfoImpl, which knows the
722 /// type of graph being modelled (BasicBlock vs. MachineBasicBlock), and
723 /// BlockFrequencyInfoImplBase, which doesn't.  The base class uses \a
724 /// BlockNode, a wrapper around a uint32_t.  BlockNode is numbered from 0 in
725 /// reverse-post order.  This gives two advantages:  it's easy to compare the
726 /// relative ordering of two nodes, and maps keyed on BlockT can be represented
727 /// by vectors.
728 ///
729 /// This algorithm is O(V+E), unless there is irreducible control flow, in
730 /// which case it's O(V*E) in the worst case.
731 ///
732 /// These are the main stages:
733 ///
734 ///  0. Reverse post-order traversal (\a initializeRPOT()).
735 ///
736 ///     Run a single post-order traversal and save it (in reverse) in RPOT.
737 ///     All other stages make use of this ordering.  Save a lookup from BlockT
738 ///     to BlockNode (the index into RPOT) in Nodes.
739 ///
740 ///  1. Loop initialization (\a initializeLoops()).
741 ///
742 ///     Translate LoopInfo/MachineLoopInfo into a form suitable for the rest of
743 ///     the algorithm.  In particular, store the immediate members of each loop
744 ///     in reverse post-order.
745 ///
746 ///  2. Calculate mass and scale in loops (\a computeMassInLoops()).
747 ///
748 ///     For each loop (bottom-up), distribute mass through the DAG resulting
749 ///     from ignoring backedges and treating sub-loops as a single pseudo-node.
750 ///     Track the backedge mass distributed to the loop header, and use it to
751 ///     calculate the loop scale (number of loop iterations).  Immediate
752 ///     members that represent sub-loops will already have been visited and
753 ///     packaged into a pseudo-node.
754 ///
755 ///     Distributing mass in a loop is a reverse-post-order traversal through
756 ///     the loop.  Start by assigning full mass to the Loop header.  For each
757 ///     node in the loop:
758 ///
759 ///         - Fetch and categorize the weight distribution for its successors.
760 ///           If this is a packaged-subloop, the weight distribution is stored
761 ///           in \a LoopData::Exits.  Otherwise, fetch it from
762 ///           BranchProbabilityInfo.
763 ///
764 ///         - Each successor is categorized as \a Weight::Local, a local edge
765 ///           within the current loop, \a Weight::Backedge, a backedge to the
766 ///           loop header, or \a Weight::Exit, any successor outside the loop.
767 ///           The weight, the successor, and its category are stored in \a
768 ///           Distribution.  There can be multiple edges to each successor.
769 ///
770 ///         - If there's a backedge to a non-header, there's an irreducible SCC.
771 ///           The usual flow is temporarily aborted.  \a
772 ///           computeIrreducibleMass() finds the irreducible SCCs within the
773 ///           loop, packages them up, and restarts the flow.
774 ///
775 ///         - Normalize the distribution:  scale weights down so that their sum
776 ///           is 32-bits, and coalesce multiple edges to the same node.
777 ///
778 ///         - Distribute the mass accordingly, dithering to minimize mass loss,
779 ///           as described in \a distributeMass().
780 ///
781 ///     In the case of irreducible loops, instead of a single loop header,
782 ///     there will be several. The computation of backedge masses is similar
783 ///     but instead of having a single backedge mass, there will be one
784 ///     backedge per loop header. In these cases, each backedge will carry
785 ///     a mass proportional to the edge weights along the corresponding
786 ///     path.
787 ///
788 ///     At the end of propagation, the full mass assigned to the loop will be
789 ///     distributed among the loop headers proportionally according to the
790 ///     mass flowing through their backedges.
791 ///
792 ///     Finally, calculate the loop scale from the accumulated backedge mass.
793 ///
794 ///  3. Distribute mass in the function (\a computeMassInFunction()).
795 ///
796 ///     Finally, distribute mass through the DAG resulting from packaging all
797 ///     loops in the function.  This uses the same algorithm as distributing
798 ///     mass in a loop, except that there are no exit or backedge edges.
799 ///
800 ///  4. Unpackage loops (\a unwrapLoops()).
801 ///
802 ///     Initialize each block's frequency to a floating point representation of
803 ///     its mass.
804 ///
805 ///     Visit loops top-down, scaling the frequencies of its immediate members
806 ///     by the loop's pseudo-node's frequency.
807 ///
808 ///  5. Convert frequencies to a 64-bit range (\a finalizeMetrics()).
809 ///
810 ///     Using the min and max frequencies as a guide, translate floating point
811 ///     frequencies to an appropriate range in uint64_t.
812 ///
813 /// It has some known flaws.
814 ///
815 ///   - The model of irreducible control flow is a rough approximation.
816 ///
817 ///     Modelling irreducible control flow exactly involves setting up and
818 ///     solving a group of infinite geometric series.  Such precision is
819 ///     unlikely to be worthwhile, since most of our algorithms give up on
820 ///     irreducible control flow anyway.
821 ///
822 ///     Nevertheless, we might find that we need to get closer.  Here's a sort
823 ///     of TODO list for the model with diminishing returns, to be completed as
824 ///     necessary.
825 ///
826 ///       - The headers for the \a LoopData representing an irreducible SCC
827 ///         include non-entry blocks.  When these extra blocks exist, they
828 ///         indicate a self-contained irreducible sub-SCC.  We could treat them
829 ///         as sub-loops, rather than arbitrarily shoving the problematic
830 ///         blocks into the headers of the main irreducible SCC.
831 ///
832 ///       - Entry frequencies are assumed to be evenly split between the
833 ///         headers of a given irreducible SCC, which is the only option if we
834 ///         need to compute mass in the SCC before its parent loop.  Instead,
835 ///         we could partially compute mass in the parent loop, and stop when
836 ///         we get to the SCC.  Here, we have the correct ratio of entry
837 ///         masses, which we can use to adjust their relative frequencies.
838 ///         Compute mass in the SCC, and then continue propagation in the
839 ///         parent.
840 ///
841 ///       - We can propagate mass iteratively through the SCC, for some fixed
842 ///         number of iterations.  Each iteration starts by assigning the entry
843 ///         blocks their backedge mass from the prior iteration.  The final
844 ///         mass for each block (and each exit, and the total backedge mass
845 ///         used for computing loop scale) is the sum of all iterations.
846 ///         (Running this until fixed point would "solve" the geometric
847 ///         series by simulation.)
848 template <class BT> class BlockFrequencyInfoImpl : BlockFrequencyInfoImplBase {
849   // This is part of a workaround for a GCC 4.7 crash on lambdas.
850   friend struct bfi_detail::BlockEdgesAdder<BT>;
851 
852   using BlockT = typename bfi_detail::TypeMap<BT>::BlockT;
853   using BlockKeyT = typename bfi_detail::TypeMap<BT>::BlockKeyT;
854   using FunctionT = typename bfi_detail::TypeMap<BT>::FunctionT;
855   using BranchProbabilityInfoT =
856       typename bfi_detail::TypeMap<BT>::BranchProbabilityInfoT;
857   using LoopT = typename bfi_detail::TypeMap<BT>::LoopT;
858   using LoopInfoT = typename bfi_detail::TypeMap<BT>::LoopInfoT;
859   using Successor = GraphTraits<const BlockT *>;
860   using Predecessor = GraphTraits<Inverse<const BlockT *>>;
861   using BFICallbackVH =
862       bfi_detail::BFICallbackVH<BlockT, BlockFrequencyInfoImpl>;
863 
864   const BranchProbabilityInfoT *BPI = nullptr;
865   const LoopInfoT *LI = nullptr;
866   const FunctionT *F = nullptr;
867 
868   // All blocks in reverse postorder.
869   std::vector<const BlockT *> RPOT;
870   DenseMap<BlockKeyT, std::pair<BlockNode, BFICallbackVH>> Nodes;
871 
872   using rpot_iterator = typename std::vector<const BlockT *>::const_iterator;
873 
874   rpot_iterator rpot_begin() const { return RPOT.begin(); }
875   rpot_iterator rpot_end() const { return RPOT.end(); }
876 
877   size_t getIndex(const rpot_iterator &I) const { return I - rpot_begin(); }
878 
879   BlockNode getNode(const rpot_iterator &I) const {
880     return BlockNode(getIndex(I));
881   }
882 
883   BlockNode getNode(const BlockT *BB) const { return Nodes.lookup(BB).first; }
884 
885   const BlockT *getBlock(const BlockNode &Node) const {
886     assert(Node.Index < RPOT.size());
887     return RPOT[Node.Index];
888   }
889 
890   /// Run (and save) a post-order traversal.
891   ///
892   /// Saves a reverse post-order traversal of all the nodes in \a F.
893   void initializeRPOT();
894 
895   /// Initialize loop data.
896   ///
897   /// Build up \a Loops using \a LoopInfo.  \a LoopInfo gives us a mapping from
898   /// each block to the deepest loop it's in, but we need the inverse.  For each
899   /// loop, we store in reverse post-order its "immediate" members, defined as
900   /// the header, the headers of immediate sub-loops, and all other blocks in
901   /// the loop that are not in sub-loops.
902   void initializeLoops();
903 
904   /// Propagate to a block's successors.
905   ///
906   /// In the context of distributing mass through \c OuterLoop, divide the mass
907   /// currently assigned to \c Node between its successors.
908   ///
909   /// \return \c true unless there's an irreducible backedge.
910   bool propagateMassToSuccessors(LoopData *OuterLoop, const BlockNode &Node);
911 
912   /// Compute mass in a particular loop.
913   ///
914   /// Assign mass to \c Loop's header, and then for each block in \c Loop in
915   /// reverse post-order, distribute mass to its successors.  Only visits nodes
916   /// that have not been packaged into sub-loops.
917   ///
918   /// \pre \a computeMassInLoop() has been called for each subloop of \c Loop.
919   /// \return \c true unless there's an irreducible backedge.
920   bool computeMassInLoop(LoopData &Loop);
921 
922   /// Try to compute mass in the top-level function.
923   ///
924   /// Assign mass to the entry block, and then for each block in reverse
925   /// post-order, distribute mass to its successors.  Skips nodes that have
926   /// been packaged into loops.
927   ///
928   /// \pre \a computeMassInLoops() has been called.
929   /// \return \c true unless there's an irreducible backedge.
930   bool tryToComputeMassInFunction();
931 
932   /// Compute mass in (and package up) irreducible SCCs.
933   ///
934   /// Find the irreducible SCCs in \c OuterLoop, add them to \a Loops (in front
935   /// of \c Insert), and call \a computeMassInLoop() on each of them.
936   ///
937   /// If \c OuterLoop is \c nullptr, it refers to the top-level function.
938   ///
939   /// \pre \a computeMassInLoop() has been called for each subloop of \c
940   /// OuterLoop.
941   /// \pre \c Insert points at the last loop successfully processed by \a
942   /// computeMassInLoop().
943   /// \pre \c OuterLoop has irreducible SCCs.
944   void computeIrreducibleMass(LoopData *OuterLoop,
945                               std::list<LoopData>::iterator Insert);
946 
947   /// Compute mass in all loops.
948   ///
949   /// For each loop bottom-up, call \a computeMassInLoop().
950   ///
951   /// \a computeMassInLoop() aborts (and returns \c false) on loops that
952   /// contain a irreducible sub-SCCs.  Use \a computeIrreducibleMass() and then
953   /// re-enter \a computeMassInLoop().
954   ///
955   /// \post \a computeMassInLoop() has returned \c true for every loop.
956   void computeMassInLoops();
957 
958   /// Compute mass in the top-level function.
959   ///
960   /// Uses \a tryToComputeMassInFunction() and \a computeIrreducibleMass() to
961   /// compute mass in the top-level function.
962   ///
963   /// \post \a tryToComputeMassInFunction() has returned \c true.
964   void computeMassInFunction();
965 
966   std::string getBlockName(const BlockNode &Node) const override {
967     return bfi_detail::getBlockName(getBlock(Node));
968   }
969 
970 public:
971   BlockFrequencyInfoImpl() = default;
972 
973   const FunctionT *getFunction() const { return F; }
974 
975   void calculate(const FunctionT &F, const BranchProbabilityInfoT &BPI,
976                  const LoopInfoT &LI);
977 
978   using BlockFrequencyInfoImplBase::getEntryFreq;
979 
980   BlockFrequency getBlockFreq(const BlockT *BB) const {
981     return BlockFrequencyInfoImplBase::getBlockFreq(getNode(BB));
982   }
983 
984   Optional<uint64_t> getBlockProfileCount(const Function &F,
985                                           const BlockT *BB,
986                                           bool AllowSynthetic = false) const {
987     return BlockFrequencyInfoImplBase::getBlockProfileCount(F, getNode(BB),
988                                                             AllowSynthetic);
989   }
990 
991   Optional<uint64_t> getProfileCountFromFreq(const Function &F,
992                                              uint64_t Freq,
993                                              bool AllowSynthetic = false) const {
994     return BlockFrequencyInfoImplBase::getProfileCountFromFreq(F, Freq,
995                                                                AllowSynthetic);
996   }
997 
998   bool isIrrLoopHeader(const BlockT *BB) {
999     return BlockFrequencyInfoImplBase::isIrrLoopHeader(getNode(BB));
1000   }
1001 
1002   void setBlockFreq(const BlockT *BB, uint64_t Freq);
1003 
1004   void forgetBlock(const BlockT *BB) {
1005     // We don't erase corresponding items from `Freqs`, `RPOT` and other to
1006     // avoid invalidating indices. Doing so would have saved some memory, but
1007     // it's not worth it.
1008     Nodes.erase(BB);
1009   }
1010 
1011   Scaled64 getFloatingBlockFreq(const BlockT *BB) const {
1012     return BlockFrequencyInfoImplBase::getFloatingBlockFreq(getNode(BB));
1013   }
1014 
1015   const BranchProbabilityInfoT &getBPI() const { return *BPI; }
1016 
1017   /// Print the frequencies for the current function.
1018   ///
1019   /// Prints the frequencies for the blocks in the current function.
1020   ///
1021   /// Blocks are printed in the natural iteration order of the function, rather
1022   /// than reverse post-order.  This provides two advantages:  writing -analyze
1023   /// tests is easier (since blocks come out in source order), and even
1024   /// unreachable blocks are printed.
1025   ///
1026   /// \a BlockFrequencyInfoImplBase::print() only knows reverse post-order, so
1027   /// we need to override it here.
1028   raw_ostream &print(raw_ostream &OS) const override;
1029 
1030   using BlockFrequencyInfoImplBase::dump;
1031   using BlockFrequencyInfoImplBase::printBlockFreq;
1032 
1033   raw_ostream &printBlockFreq(raw_ostream &OS, const BlockT *BB) const {
1034     return BlockFrequencyInfoImplBase::printBlockFreq(OS, getNode(BB));
1035   }
1036 
1037   void verifyMatch(BlockFrequencyInfoImpl<BT> &Other) const;
1038 };
1039 
1040 namespace bfi_detail {
1041 
1042 template <class BFIImplT>
1043 class BFICallbackVH<BasicBlock, BFIImplT> : public CallbackVH {
1044   BFIImplT *BFIImpl;
1045 
1046 public:
1047   BFICallbackVH() = default;
1048 
1049   BFICallbackVH(const BasicBlock *BB, BFIImplT *BFIImpl)
1050       : CallbackVH(BB), BFIImpl(BFIImpl) {}
1051 
1052   virtual ~BFICallbackVH() = default;
1053 
1054   void deleted() override {
1055     BFIImpl->forgetBlock(cast<BasicBlock>(getValPtr()));
1056   }
1057 };
1058 
1059 /// Dummy implementation since MachineBasicBlocks aren't Values, so ValueHandles
1060 /// don't apply to them.
1061 template <class BFIImplT>
1062 class BFICallbackVH<MachineBasicBlock, BFIImplT> {
1063 public:
1064   BFICallbackVH() = default;
1065   BFICallbackVH(const MachineBasicBlock *, BFIImplT *) {}
1066 };
1067 
1068 } // end namespace bfi_detail
1069 
1070 template <class BT>
1071 void BlockFrequencyInfoImpl<BT>::calculate(const FunctionT &F,
1072                                            const BranchProbabilityInfoT &BPI,
1073                                            const LoopInfoT &LI) {
1074   // Save the parameters.
1075   this->BPI = &BPI;
1076   this->LI = &LI;
1077   this->F = &F;
1078 
1079   // Clean up left-over data structures.
1080   BlockFrequencyInfoImplBase::clear();
1081   RPOT.clear();
1082   Nodes.clear();
1083 
1084   // Initialize.
1085   LLVM_DEBUG(dbgs() << "\nblock-frequency: " << F.getName()
1086                     << "\n================="
1087                     << std::string(F.getName().size(), '=') << "\n");
1088   initializeRPOT();
1089   initializeLoops();
1090 
1091   // Visit loops in post-order to find the local mass distribution, and then do
1092   // the full function.
1093   computeMassInLoops();
1094   computeMassInFunction();
1095   unwrapLoops();
1096   finalizeMetrics();
1097 
1098   if (CheckBFIUnknownBlockQueries) {
1099     // To detect BFI queries for unknown blocks, add entries for unreachable
1100     // blocks, if any. This is to distinguish between known/existing unreachable
1101     // blocks and unknown blocks.
1102     for (const BlockT &BB : F)
1103       if (!Nodes.count(&BB))
1104         setBlockFreq(&BB, 0);
1105   }
1106 }
1107 
1108 template <class BT>
1109 void BlockFrequencyInfoImpl<BT>::setBlockFreq(const BlockT *BB, uint64_t Freq) {
1110   if (Nodes.count(BB))
1111     BlockFrequencyInfoImplBase::setBlockFreq(getNode(BB), Freq);
1112   else {
1113     // If BB is a newly added block after BFI is done, we need to create a new
1114     // BlockNode for it assigned with a new index. The index can be determined
1115     // by the size of Freqs.
1116     BlockNode NewNode(Freqs.size());
1117     Nodes[BB] = {NewNode, BFICallbackVH(BB, this)};
1118     Freqs.emplace_back();
1119     BlockFrequencyInfoImplBase::setBlockFreq(NewNode, Freq);
1120   }
1121 }
1122 
1123 template <class BT> void BlockFrequencyInfoImpl<BT>::initializeRPOT() {
1124   const BlockT *Entry = &F->front();
1125   RPOT.reserve(F->size());
1126   std::copy(po_begin(Entry), po_end(Entry), std::back_inserter(RPOT));
1127   std::reverse(RPOT.begin(), RPOT.end());
1128 
1129   assert(RPOT.size() - 1 <= BlockNode::getMaxIndex() &&
1130          "More nodes in function than Block Frequency Info supports");
1131 
1132   LLVM_DEBUG(dbgs() << "reverse-post-order-traversal\n");
1133   for (rpot_iterator I = rpot_begin(), E = rpot_end(); I != E; ++I) {
1134     BlockNode Node = getNode(I);
1135     LLVM_DEBUG(dbgs() << " - " << getIndex(I) << ": " << getBlockName(Node)
1136                       << "\n");
1137     Nodes[*I] = {Node, BFICallbackVH(*I, this)};
1138   }
1139 
1140   Working.reserve(RPOT.size());
1141   for (size_t Index = 0; Index < RPOT.size(); ++Index)
1142     Working.emplace_back(Index);
1143   Freqs.resize(RPOT.size());
1144 }
1145 
1146 template <class BT> void BlockFrequencyInfoImpl<BT>::initializeLoops() {
1147   LLVM_DEBUG(dbgs() << "loop-detection\n");
1148   if (LI->empty())
1149     return;
1150 
1151   // Visit loops top down and assign them an index.
1152   std::deque<std::pair<const LoopT *, LoopData *>> Q;
1153   for (const LoopT *L : *LI)
1154     Q.emplace_back(L, nullptr);
1155   while (!Q.empty()) {
1156     const LoopT *Loop = Q.front().first;
1157     LoopData *Parent = Q.front().second;
1158     Q.pop_front();
1159 
1160     BlockNode Header = getNode(Loop->getHeader());
1161     assert(Header.isValid());
1162 
1163     Loops.emplace_back(Parent, Header);
1164     Working[Header.Index].Loop = &Loops.back();
1165     LLVM_DEBUG(dbgs() << " - loop = " << getBlockName(Header) << "\n");
1166 
1167     for (const LoopT *L : *Loop)
1168       Q.emplace_back(L, &Loops.back());
1169   }
1170 
1171   // Visit nodes in reverse post-order and add them to their deepest containing
1172   // loop.
1173   for (size_t Index = 0; Index < RPOT.size(); ++Index) {
1174     // Loop headers have already been mostly mapped.
1175     if (Working[Index].isLoopHeader()) {
1176       LoopData *ContainingLoop = Working[Index].getContainingLoop();
1177       if (ContainingLoop)
1178         ContainingLoop->Nodes.push_back(Index);
1179       continue;
1180     }
1181 
1182     const LoopT *Loop = LI->getLoopFor(RPOT[Index]);
1183     if (!Loop)
1184       continue;
1185 
1186     // Add this node to its containing loop's member list.
1187     BlockNode Header = getNode(Loop->getHeader());
1188     assert(Header.isValid());
1189     const auto &HeaderData = Working[Header.Index];
1190     assert(HeaderData.isLoopHeader());
1191 
1192     Working[Index].Loop = HeaderData.Loop;
1193     HeaderData.Loop->Nodes.push_back(Index);
1194     LLVM_DEBUG(dbgs() << " - loop = " << getBlockName(Header)
1195                       << ": member = " << getBlockName(Index) << "\n");
1196   }
1197 }
1198 
1199 template <class BT> void BlockFrequencyInfoImpl<BT>::computeMassInLoops() {
1200   // Visit loops with the deepest first, and the top-level loops last.
1201   for (auto L = Loops.rbegin(), E = Loops.rend(); L != E; ++L) {
1202     if (computeMassInLoop(*L))
1203       continue;
1204     auto Next = std::next(L);
1205     computeIrreducibleMass(&*L, L.base());
1206     L = std::prev(Next);
1207     if (computeMassInLoop(*L))
1208       continue;
1209     llvm_unreachable("unhandled irreducible control flow");
1210   }
1211 }
1212 
1213 template <class BT>
1214 bool BlockFrequencyInfoImpl<BT>::computeMassInLoop(LoopData &Loop) {
1215   // Compute mass in loop.
1216   LLVM_DEBUG(dbgs() << "compute-mass-in-loop: " << getLoopName(Loop) << "\n");
1217 
1218   if (Loop.isIrreducible()) {
1219     LLVM_DEBUG(dbgs() << "isIrreducible = true\n");
1220     Distribution Dist;
1221     unsigned NumHeadersWithWeight = 0;
1222     Optional<uint64_t> MinHeaderWeight;
1223     DenseSet<uint32_t> HeadersWithoutWeight;
1224     HeadersWithoutWeight.reserve(Loop.NumHeaders);
1225     for (uint32_t H = 0; H < Loop.NumHeaders; ++H) {
1226       auto &HeaderNode = Loop.Nodes[H];
1227       const BlockT *Block = getBlock(HeaderNode);
1228       IsIrrLoopHeader.set(Loop.Nodes[H].Index);
1229       Optional<uint64_t> HeaderWeight = Block->getIrrLoopHeaderWeight();
1230       if (!HeaderWeight) {
1231         LLVM_DEBUG(dbgs() << "Missing irr loop header metadata on "
1232                           << getBlockName(HeaderNode) << "\n");
1233         HeadersWithoutWeight.insert(H);
1234         continue;
1235       }
1236       LLVM_DEBUG(dbgs() << getBlockName(HeaderNode)
1237                         << " has irr loop header weight "
1238                         << HeaderWeight.getValue() << "\n");
1239       NumHeadersWithWeight++;
1240       uint64_t HeaderWeightValue = HeaderWeight.getValue();
1241       if (!MinHeaderWeight || HeaderWeightValue < MinHeaderWeight)
1242         MinHeaderWeight = HeaderWeightValue;
1243       if (HeaderWeightValue) {
1244         Dist.addLocal(HeaderNode, HeaderWeightValue);
1245       }
1246     }
1247     // As a heuristic, if some headers don't have a weight, give them the
1248     // minimum weight seen (not to disrupt the existing trends too much by
1249     // using a weight that's in the general range of the other headers' weights,
1250     // and the minimum seems to perform better than the average.)
1251     // FIXME: better update in the passes that drop the header weight.
1252     // If no headers have a weight, give them even weight (use weight 1).
1253     if (!MinHeaderWeight)
1254       MinHeaderWeight = 1;
1255     for (uint32_t H : HeadersWithoutWeight) {
1256       auto &HeaderNode = Loop.Nodes[H];
1257       assert(!getBlock(HeaderNode)->getIrrLoopHeaderWeight() &&
1258              "Shouldn't have a weight metadata");
1259       uint64_t MinWeight = MinHeaderWeight.getValue();
1260       LLVM_DEBUG(dbgs() << "Giving weight " << MinWeight << " to "
1261                         << getBlockName(HeaderNode) << "\n");
1262       if (MinWeight)
1263         Dist.addLocal(HeaderNode, MinWeight);
1264     }
1265     distributeIrrLoopHeaderMass(Dist);
1266     for (const BlockNode &M : Loop.Nodes)
1267       if (!propagateMassToSuccessors(&Loop, M))
1268         llvm_unreachable("unhandled irreducible control flow");
1269     if (NumHeadersWithWeight == 0)
1270       // No headers have a metadata. Adjust header mass.
1271       adjustLoopHeaderMass(Loop);
1272   } else {
1273     Working[Loop.getHeader().Index].getMass() = BlockMass::getFull();
1274     if (!propagateMassToSuccessors(&Loop, Loop.getHeader()))
1275       llvm_unreachable("irreducible control flow to loop header!?");
1276     for (const BlockNode &M : Loop.members())
1277       if (!propagateMassToSuccessors(&Loop, M))
1278         // Irreducible backedge.
1279         return false;
1280   }
1281 
1282   computeLoopScale(Loop);
1283   packageLoop(Loop);
1284   return true;
1285 }
1286 
1287 template <class BT>
1288 bool BlockFrequencyInfoImpl<BT>::tryToComputeMassInFunction() {
1289   // Compute mass in function.
1290   LLVM_DEBUG(dbgs() << "compute-mass-in-function\n");
1291   assert(!Working.empty() && "no blocks in function");
1292   assert(!Working[0].isLoopHeader() && "entry block is a loop header");
1293 
1294   Working[0].getMass() = BlockMass::getFull();
1295   for (rpot_iterator I = rpot_begin(), IE = rpot_end(); I != IE; ++I) {
1296     // Check for nodes that have been packaged.
1297     BlockNode Node = getNode(I);
1298     if (Working[Node.Index].isPackaged())
1299       continue;
1300 
1301     if (!propagateMassToSuccessors(nullptr, Node))
1302       return false;
1303   }
1304   return true;
1305 }
1306 
1307 template <class BT> void BlockFrequencyInfoImpl<BT>::computeMassInFunction() {
1308   if (tryToComputeMassInFunction())
1309     return;
1310   computeIrreducibleMass(nullptr, Loops.begin());
1311   if (tryToComputeMassInFunction())
1312     return;
1313   llvm_unreachable("unhandled irreducible control flow");
1314 }
1315 
1316 /// \note This should be a lambda, but that crashes GCC 4.7.
1317 namespace bfi_detail {
1318 
1319 template <class BT> struct BlockEdgesAdder {
1320   using BlockT = BT;
1321   using LoopData = BlockFrequencyInfoImplBase::LoopData;
1322   using Successor = GraphTraits<const BlockT *>;
1323 
1324   const BlockFrequencyInfoImpl<BT> &BFI;
1325 
1326   explicit BlockEdgesAdder(const BlockFrequencyInfoImpl<BT> &BFI)
1327       : BFI(BFI) {}
1328 
1329   void operator()(IrreducibleGraph &G, IrreducibleGraph::IrrNode &Irr,
1330                   const LoopData *OuterLoop) {
1331     const BlockT *BB = BFI.RPOT[Irr.Node.Index];
1332     for (const auto Succ : children<const BlockT *>(BB))
1333       G.addEdge(Irr, BFI.getNode(Succ), OuterLoop);
1334   }
1335 };
1336 
1337 } // end namespace bfi_detail
1338 
1339 template <class BT>
1340 void BlockFrequencyInfoImpl<BT>::computeIrreducibleMass(
1341     LoopData *OuterLoop, std::list<LoopData>::iterator Insert) {
1342   LLVM_DEBUG(dbgs() << "analyze-irreducible-in-";
1343              if (OuterLoop) dbgs()
1344              << "loop: " << getLoopName(*OuterLoop) << "\n";
1345              else dbgs() << "function\n");
1346 
1347   using namespace bfi_detail;
1348 
1349   // Ideally, addBlockEdges() would be declared here as a lambda, but that
1350   // crashes GCC 4.7.
1351   BlockEdgesAdder<BT> addBlockEdges(*this);
1352   IrreducibleGraph G(*this, OuterLoop, addBlockEdges);
1353 
1354   for (auto &L : analyzeIrreducible(G, OuterLoop, Insert))
1355     computeMassInLoop(L);
1356 
1357   if (!OuterLoop)
1358     return;
1359   updateLoopWithIrreducible(*OuterLoop);
1360 }
1361 
1362 // A helper function that converts a branch probability into weight.
1363 inline uint32_t getWeightFromBranchProb(const BranchProbability Prob) {
1364   return Prob.getNumerator();
1365 }
1366 
1367 template <class BT>
1368 bool
1369 BlockFrequencyInfoImpl<BT>::propagateMassToSuccessors(LoopData *OuterLoop,
1370                                                       const BlockNode &Node) {
1371   LLVM_DEBUG(dbgs() << " - node: " << getBlockName(Node) << "\n");
1372   // Calculate probability for successors.
1373   Distribution Dist;
1374   if (auto *Loop = Working[Node.Index].getPackagedLoop()) {
1375     assert(Loop != OuterLoop && "Cannot propagate mass in a packaged loop");
1376     if (!addLoopSuccessorsToDist(OuterLoop, *Loop, Dist))
1377       // Irreducible backedge.
1378       return false;
1379   } else {
1380     const BlockT *BB = getBlock(Node);
1381     for (auto SI = GraphTraits<const BlockT *>::child_begin(BB),
1382               SE = GraphTraits<const BlockT *>::child_end(BB);
1383          SI != SE; ++SI)
1384       if (!addToDist(
1385               Dist, OuterLoop, Node, getNode(*SI),
1386               getWeightFromBranchProb(BPI->getEdgeProbability(BB, SI))))
1387         // Irreducible backedge.
1388         return false;
1389   }
1390 
1391   // Distribute mass to successors, saving exit and backedge data in the
1392   // loop header.
1393   distributeMass(Node, OuterLoop, Dist);
1394   return true;
1395 }
1396 
1397 template <class BT>
1398 raw_ostream &BlockFrequencyInfoImpl<BT>::print(raw_ostream &OS) const {
1399   if (!F)
1400     return OS;
1401   OS << "block-frequency-info: " << F->getName() << "\n";
1402   for (const BlockT &BB : *F) {
1403     OS << " - " << bfi_detail::getBlockName(&BB) << ": float = ";
1404     getFloatingBlockFreq(&BB).print(OS, 5)
1405         << ", int = " << getBlockFreq(&BB).getFrequency();
1406     if (Optional<uint64_t> ProfileCount =
1407         BlockFrequencyInfoImplBase::getBlockProfileCount(
1408             F->getFunction(), getNode(&BB)))
1409       OS << ", count = " << ProfileCount.getValue();
1410     if (Optional<uint64_t> IrrLoopHeaderWeight =
1411         BB.getIrrLoopHeaderWeight())
1412       OS << ", irr_loop_header_weight = " << IrrLoopHeaderWeight.getValue();
1413     OS << "\n";
1414   }
1415 
1416   // Add an extra newline for readability.
1417   OS << "\n";
1418   return OS;
1419 }
1420 
1421 template <class BT>
1422 void BlockFrequencyInfoImpl<BT>::verifyMatch(
1423     BlockFrequencyInfoImpl<BT> &Other) const {
1424   bool Match = true;
1425   DenseMap<const BlockT *, BlockNode> ValidNodes;
1426   DenseMap<const BlockT *, BlockNode> OtherValidNodes;
1427   for (auto &Entry : Nodes) {
1428     const BlockT *BB = Entry.first;
1429     if (BB) {
1430       ValidNodes[BB] = Entry.second.first;
1431     }
1432   }
1433   for (auto &Entry : Other.Nodes) {
1434     const BlockT *BB = Entry.first;
1435     if (BB) {
1436       OtherValidNodes[BB] = Entry.second.first;
1437     }
1438   }
1439   unsigned NumValidNodes = ValidNodes.size();
1440   unsigned NumOtherValidNodes = OtherValidNodes.size();
1441   if (NumValidNodes != NumOtherValidNodes) {
1442     Match = false;
1443     dbgs() << "Number of blocks mismatch: " << NumValidNodes << " vs "
1444            << NumOtherValidNodes << "\n";
1445   } else {
1446     for (auto &Entry : ValidNodes) {
1447       const BlockT *BB = Entry.first;
1448       BlockNode Node = Entry.second;
1449       if (OtherValidNodes.count(BB)) {
1450         BlockNode OtherNode = OtherValidNodes[BB];
1451         const auto &Freq = Freqs[Node.Index];
1452         const auto &OtherFreq = Other.Freqs[OtherNode.Index];
1453         if (Freq.Integer != OtherFreq.Integer) {
1454           Match = false;
1455           dbgs() << "Freq mismatch: " << bfi_detail::getBlockName(BB) << " "
1456                  << Freq.Integer << " vs " << OtherFreq.Integer << "\n";
1457         }
1458       } else {
1459         Match = false;
1460         dbgs() << "Block " << bfi_detail::getBlockName(BB) << " index "
1461                << Node.Index << " does not exist in Other.\n";
1462       }
1463     }
1464     // If there's a valid node in OtherValidNodes that's not in ValidNodes,
1465     // either the above num check or the check on OtherValidNodes will fail.
1466   }
1467   if (!Match) {
1468     dbgs() << "This\n";
1469     print(dbgs());
1470     dbgs() << "Other\n";
1471     Other.print(dbgs());
1472   }
1473   assert(Match && "BFI mismatch");
1474 }
1475 
1476 // Graph trait base class for block frequency information graph
1477 // viewer.
1478 
1479 enum GVDAGType { GVDT_None, GVDT_Fraction, GVDT_Integer, GVDT_Count };
1480 
1481 template <class BlockFrequencyInfoT, class BranchProbabilityInfoT>
1482 struct BFIDOTGraphTraitsBase : public DefaultDOTGraphTraits {
1483   using GTraits = GraphTraits<BlockFrequencyInfoT *>;
1484   using NodeRef = typename GTraits::NodeRef;
1485   using EdgeIter = typename GTraits::ChildIteratorType;
1486   using NodeIter = typename GTraits::nodes_iterator;
1487 
1488   uint64_t MaxFrequency = 0;
1489 
1490   explicit BFIDOTGraphTraitsBase(bool isSimple = false)
1491       : DefaultDOTGraphTraits(isSimple) {}
1492 
1493   static StringRef getGraphName(const BlockFrequencyInfoT *G) {
1494     return G->getFunction()->getName();
1495   }
1496 
1497   std::string getNodeAttributes(NodeRef Node, const BlockFrequencyInfoT *Graph,
1498                                 unsigned HotPercentThreshold = 0) {
1499     std::string Result;
1500     if (!HotPercentThreshold)
1501       return Result;
1502 
1503     // Compute MaxFrequency on the fly:
1504     if (!MaxFrequency) {
1505       for (NodeIter I = GTraits::nodes_begin(Graph),
1506                     E = GTraits::nodes_end(Graph);
1507            I != E; ++I) {
1508         NodeRef N = *I;
1509         MaxFrequency =
1510             std::max(MaxFrequency, Graph->getBlockFreq(N).getFrequency());
1511       }
1512     }
1513     BlockFrequency Freq = Graph->getBlockFreq(Node);
1514     BlockFrequency HotFreq =
1515         (BlockFrequency(MaxFrequency) *
1516          BranchProbability::getBranchProbability(HotPercentThreshold, 100));
1517 
1518     if (Freq < HotFreq)
1519       return Result;
1520 
1521     raw_string_ostream OS(Result);
1522     OS << "color=\"red\"";
1523     OS.flush();
1524     return Result;
1525   }
1526 
1527   std::string getNodeLabel(NodeRef Node, const BlockFrequencyInfoT *Graph,
1528                            GVDAGType GType, int layout_order = -1) {
1529     std::string Result;
1530     raw_string_ostream OS(Result);
1531 
1532     if (layout_order != -1)
1533       OS << Node->getName() << "[" << layout_order << "] : ";
1534     else
1535       OS << Node->getName() << " : ";
1536     switch (GType) {
1537     case GVDT_Fraction:
1538       Graph->printBlockFreq(OS, Node);
1539       break;
1540     case GVDT_Integer:
1541       OS << Graph->getBlockFreq(Node).getFrequency();
1542       break;
1543     case GVDT_Count: {
1544       auto Count = Graph->getBlockProfileCount(Node);
1545       if (Count)
1546         OS << Count.getValue();
1547       else
1548         OS << "Unknown";
1549       break;
1550     }
1551     case GVDT_None:
1552       llvm_unreachable("If we are not supposed to render a graph we should "
1553                        "never reach this point.");
1554     }
1555     return Result;
1556   }
1557 
1558   std::string getEdgeAttributes(NodeRef Node, EdgeIter EI,
1559                                 const BlockFrequencyInfoT *BFI,
1560                                 const BranchProbabilityInfoT *BPI,
1561                                 unsigned HotPercentThreshold = 0) {
1562     std::string Str;
1563     if (!BPI)
1564       return Str;
1565 
1566     BranchProbability BP = BPI->getEdgeProbability(Node, EI);
1567     uint32_t N = BP.getNumerator();
1568     uint32_t D = BP.getDenominator();
1569     double Percent = 100.0 * N / D;
1570     raw_string_ostream OS(Str);
1571     OS << format("label=\"%.1f%%\"", Percent);
1572 
1573     if (HotPercentThreshold) {
1574       BlockFrequency EFreq = BFI->getBlockFreq(Node) * BP;
1575       BlockFrequency HotFreq = BlockFrequency(MaxFrequency) *
1576                                BranchProbability(HotPercentThreshold, 100);
1577 
1578       if (EFreq >= HotFreq) {
1579         OS << ",color=\"red\"";
1580       }
1581     }
1582 
1583     OS.flush();
1584     return Str;
1585   }
1586 };
1587 
1588 } // end namespace llvm
1589 
1590 #undef DEBUG_TYPE
1591 
1592 #endif // LLVM_ANALYSIS_BLOCKFREQUENCYINFOIMPL_H
1593