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