Coverage Report

Created: 2018-07-19 03:59

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