LLVM 24.0.0git
BlockFrequencyInfoImpl.h
Go to the documentation of this file.
1//==- BlockFrequencyInfoImpl.h - Block Frequency Implementation --*- C++ -*-==//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// Shared implementation of BlockFrequency for IR and Machine Instructions.
10// See the documentation below for BlockFrequencyInfoImpl for details.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_ANALYSIS_BLOCKFREQUENCYINFOIMPL_H
15#define LLVM_ANALYSIS_BLOCKFREQUENCYINFOIMPL_H
16
17#include "llvm/ADT/BitVector.h"
18#include "llvm/ADT/DenseMap.h"
19#include "llvm/ADT/DenseSet.h"
26#include "llvm/ADT/Twine.h"
28#include "llvm/IR/BasicBlock.h"
29#include "llvm/IR/Function.h"
30#include "llvm/IR/ValueHandle.h"
35#include "llvm/Support/Debug.h"
36#include "llvm/Support/Format.h"
39#include <algorithm>
40#include <cassert>
41#include <cstddef>
42#include <cstdint>
43#include <deque>
44#include <iterator>
45#include <limits>
46#include <list>
47#include <optional>
48#include <queue>
49#include <string>
50#include <utility>
51#include <vector>
52
53#define DEBUG_TYPE "block-freq"
54
55namespace llvm {
57
61
62class BranchProbabilityInfo;
63class CycleInfo;
64class Function;
65class MachineBasicBlock;
66class MachineBranchProbabilityInfo;
67class MachineCycleInfo;
68class MachineFunction;
69
70namespace bfi_detail {
71
72struct IrreducibleGraph;
73
74/// Mass of a block.
75///
76/// This class implements a sort of fixed-point fraction always between 0.0 and
77/// 1.0. getMass() == std::numeric_limits<uint64_t>::max() indicates a value of
78/// 1.0.
79///
80/// Masses can be added and subtracted. Simple saturation arithmetic is used,
81/// so arithmetic operations never overflow or underflow.
82///
83/// Masses can be multiplied. Multiplication treats full mass as 1.0 and uses
84/// an inexpensive floating-point algorithm that's off-by-one (almost, but not
85/// quite, maximum precision).
86///
87/// Masses can be scaled by \a BranchProbability at maximum precision.
88class BlockMass {
89 uint64_t Mass = 0;
90
91public:
92 BlockMass() = default;
93 explicit BlockMass(uint64_t Mass) : Mass(Mass) {}
94
95 static BlockMass getEmpty() { return BlockMass(); }
96
97 static BlockMass getFull() {
98 return BlockMass(std::numeric_limits<uint64_t>::max());
99 }
100
101 uint64_t getMass() const { return Mass; }
102
103 bool isFull() const { return Mass == std::numeric_limits<uint64_t>::max(); }
104 bool isEmpty() const { return !Mass; }
105
106 bool operator!() const { return isEmpty(); }
107
108 /// Add another mass.
109 ///
110 /// Adds another mass, saturating at \a isFull() rather than overflowing.
112 uint64_t Sum = Mass + X.Mass;
113 Mass = Sum < Mass ? std::numeric_limits<uint64_t>::max() : Sum;
114 return *this;
115 }
116
117 /// Subtract another mass.
118 ///
119 /// Subtracts another mass, saturating at \a isEmpty() rather than
120 /// undeflowing.
122 uint64_t Diff = Mass - X.Mass;
123 Mass = Diff > Mass ? 0 : Diff;
124 return *this;
125 }
126
128 Mass = P.scale(Mass);
129 return *this;
130 }
131
132 bool operator==(BlockMass X) const { return Mass == X.Mass; }
133 bool operator!=(BlockMass X) const { return Mass != X.Mass; }
134 bool operator<=(BlockMass X) const { return Mass <= X.Mass; }
135 bool operator>=(BlockMass X) const { return Mass >= X.Mass; }
136 bool operator<(BlockMass X) const { return Mass < X.Mass; }
137 bool operator>(BlockMass X) const { return Mass > X.Mass; }
138
139 /// Convert to scaled number.
140 ///
141 /// Convert to \a ScaledNumber. \a isFull() gives 1.0, while \a isEmpty()
142 /// gives slightly above 0.0.
144
145 LLVM_ABI void dump() const;
147};
148
150 return BlockMass(L) += R;
151}
153 return BlockMass(L) -= R;
154}
156 return BlockMass(L) *= R;
157}
159 return BlockMass(R) *= L;
160}
161
163 return X.print(OS);
164}
165
166} // end namespace bfi_detail
167
168/// Base class for BlockFrequencyInfoImpl
169///
170/// BlockFrequencyInfoImplBase has supporting data structures and some
171/// algorithms for BlockFrequencyInfoImplBase. Only algorithms that depend on
172/// the block type (or that call such algorithms) are skipped here.
173///
174/// Nevertheless, the majority of the overall algorithm documentation lives with
175/// BlockFrequencyInfoImpl. See there for details.
177public:
180
181 /// Representative of a block.
182 ///
183 /// This is a simple wrapper around an index into the reverse-post-order
184 /// traversal of the blocks.
185 ///
186 /// Unlike a block pointer, its order has meaning (location in the
187 /// topological sort) and it's class is the same regardless of block type.
188 struct BlockNode {
190
192
193 BlockNode() : Index(std::numeric_limits<uint32_t>::max()) {}
195
196 bool operator==(const BlockNode &X) const { return Index == X.Index; }
197 bool operator!=(const BlockNode &X) const { return Index != X.Index; }
198 bool operator<=(const BlockNode &X) const { return Index <= X.Index; }
199 bool operator>=(const BlockNode &X) const { return Index >= X.Index; }
200 bool operator<(const BlockNode &X) const { return Index < X.Index; }
201 bool operator>(const BlockNode &X) const { return Index > X.Index; }
202
203 bool isValid() const { return Index <= getMaxIndex(); }
204
205 static size_t getMaxIndex() {
206 return std::numeric_limits<uint32_t>::max() - 1;
207 }
208 };
209
210 /// Stats about a block itself.
215
216 /// Data about a loop.
217 ///
218 /// Contains the data necessary to represent a loop as a pseudo-node once it's
219 /// packaged.
220 struct LoopData {
224
225 LoopData *Parent; ///< The parent loop.
226 bool IsPackaged = false; ///< Whether this has been packaged.
227 uint32_t NumHeaders = 1; ///< Number of headers.
228 ExitMap Exits; ///< Successor edges (and weights).
229 NodeList Nodes; ///< Header and the members of the loop.
230 HeaderMassList BackedgeMass; ///< Mass returned to each loop header.
233
235 : Parent(Parent), Nodes(1, Header), BackedgeMass(1) {}
236
237 template <class It>
238 LoopData(LoopData *Parent, It FirstHeader, It LastHeader)
239 : Parent(Parent), Nodes(FirstHeader, LastHeader) {
240 NumHeaders = Nodes.size();
241 BackedgeMass.resize(NumHeaders);
242 }
243
244 template <class It1, class It2>
245 LoopData(LoopData *Parent, It1 FirstHeader, It1 LastHeader, It2 FirstOther,
246 It2 LastOther)
247 : Parent(Parent), Nodes(FirstHeader, LastHeader) {
248 NumHeaders = Nodes.size();
249 Nodes.insert(Nodes.end(), FirstOther, LastOther);
250 BackedgeMass.resize(NumHeaders);
251 }
252
253 bool isHeader(const BlockNode &Node) const {
254 if (isIrreducible())
255 return std::binary_search(Nodes.begin(), Nodes.begin() + NumHeaders,
256 Node);
257 return Node == Nodes[0];
258 }
259
260 BlockNode getHeader() const { return Nodes[0]; }
261 bool isIrreducible() const { return NumHeaders > 1; }
262
264 assert(isHeader(B) && "this is only valid on loop header blocks");
265 if (isIrreducible())
266 return std::lower_bound(Nodes.begin(), Nodes.begin() + NumHeaders, B) -
267 Nodes.begin();
268 return 0;
269 }
270
272 return Nodes.begin() + NumHeaders;
273 }
274
279 };
280
281 /// Index of loop information.
282 struct WorkingData {
283 BlockNode Node; ///< This node.
284 LoopData *Loop = nullptr; ///< The loop this block is inside.
285 BlockMass Mass; ///< Mass distribution from the entry block.
286
288
289 bool isLoopHeader() const { return Loop && Loop->isHeader(Node); }
290
291 /// The innermost loop containing Node that Node does not head.
292 ///
293 /// A block can head several nested loops: createIrreducibleLoop() reuses
294 /// an SCC's entry blocks as the irreducible loop's headers.
296 LoopData *L = Loop;
297 while (L && L->isHeader(Node))
298 L = L->Parent;
299 return L;
300 }
301
302 /// Resolve a node to its representative.
303 ///
304 /// Get the node currently representing Node, which could be a containing
305 /// loop.
306 ///
307 /// This function should only be called when distributing mass. As long as
308 /// there are no irreducible edges to Node, then it will have complexity
309 /// O(1) in this context.
310 ///
311 /// In general, the complexity is O(L), where L is the number of loop
312 /// headers Node has been packaged into. Since this method is called in
313 /// the context of distributing mass, L will be the number of loop headers
314 /// an early exit edge jumps out of.
316 auto *L = getPackagedLoop();
317 return L ? L->getHeader() : Node;
318 }
319
320 /// The outermost loop containing Node that is currently packaged, if any.
321 ///
322 /// Packaging is transient state: this answers what represents Node at the
323 /// level being processed, not where Node sits in the loop nest.
325 if (!Loop || !Loop->IsPackaged)
326 return nullptr;
327 auto *L = Loop;
328 while (L->Parent && L->Parent->IsPackaged)
329 L = L->Parent;
330 return L;
331 }
332
333 /// The mass slot for Node: its own, or that of the outermost packaged
334 /// loop it heads.
336 BlockMass *M = &Mass;
337 for (LoopData *L = Loop; L && L->IsPackaged && L->isHeader(Node);
338 L = L->Parent)
339 M = &L->Mass;
340 return *M;
341 }
342
343 /// Has ContainingLoop been packaged up?
344 bool isPackaged() const { return getResolvedNode() != Node; }
345
346 /// Has Loop been packaged up?
347 bool isAPackage() const { return isLoopHeader() && Loop->IsPackaged; }
348 };
349
350 /// Unscaled probability weight.
351 ///
352 /// Probability weight for an edge in the graph (including the
353 /// successor/target node).
354 ///
355 /// All edges in the original function are 32-bit. However, exit edges from
356 /// loop packages are taken from 64-bit exit masses, so we need 64-bits of
357 /// space in general.
358 ///
359 /// In addition to the raw weight amount, Weight stores the type of the edge
360 /// in the current context (i.e., the context of the loop being processed).
361 /// Is this a local edge within the loop, an exit from the loop, or a
362 /// backedge to the loop header?
373
374 /// Distribution of unscaled probability weight.
375 ///
376 /// Distribution of unscaled probability weight to a set of successors.
377 ///
378 /// This class collates the successor edge weights for later processing.
379 ///
380 /// \a DidOverflow indicates whether \a Total did overflow while adding to
381 /// the distribution. It should never overflow twice.
384
385 WeightList Weights; ///< Individual successor weights.
386 uint64_t Total = 0; ///< Sum of all weights.
387 bool DidOverflow = false; ///< Whether \a Total did overflow.
388
389 Distribution() = default;
390
391 void addLocal(const BlockNode &Node, uint64_t Amount) {
392 add(Node, Amount, Weight::Local);
393 }
394
395 void addExit(const BlockNode &Node, uint64_t Amount) {
396 add(Node, Amount, Weight::Exit);
397 }
398
399 void addBackedge(const BlockNode &Node, uint64_t Amount) {
400 add(Node, Amount, Weight::Backedge);
401 }
402
403 /// Normalize the distribution.
404 ///
405 /// Combines multiple edges to the same \a Weight::TargetNode and scales
406 /// down so that \a Total fits into 32-bits.
407 ///
408 /// This is linear in the size of \a Weights. For the vast majority of
409 /// cases, adjacent edge weights are combined by sorting WeightList and
410 /// combining adjacent weights. However, for very large edge lists an
411 /// auxiliary hash table is used.
412 LLVM_ABI void normalize();
413
414 private:
415 LLVM_ABI void add(const BlockNode &Node, uint64_t Amount,
417 };
418
419 /// Data about each block. This is used downstream.
420 std::vector<FrequencyData> Freqs;
421
422 /// Whether each block is an irreducible loop header.
423 /// This is used downstream.
425
426 /// Loop data: see initializeLoops().
427 std::vector<WorkingData> Working;
428
429 /// Indexed information about loops.
430 std::list<LoopData> Loops;
431
432 /// Virtual destructor.
433 ///
434 /// Need a virtual destructor to mask the compiler warning about
435 /// getBlockName().
436 virtual ~BlockFrequencyInfoImplBase() = default;
437
438 /// Add all edges out of a packaged loop to the distribution.
439 ///
440 /// Adds all edges from LocalLoopHead to Dist. Calls addToDist() to add each
441 /// successor edge.
442 ///
443 /// \return \c true unless there's an irreducible backedge.
444 bool addLoopSuccessorsToDist(const LoopData *OuterLoop, LoopData &Loop,
445 Distribution &Dist);
446
447 /// Add an edge to the distribution.
448 ///
449 /// Adds an edge to Succ to Dist. If \c LoopHead.isValid(), then whether the
450 /// edge is local/exit/backedge is in the context of LoopHead. Otherwise,
451 /// every edge should be a local edge (since all the loops are packaged up).
452 ///
453 /// \return \c true unless aborted due to an irreducible backedge.
454 bool addToDist(Distribution &Dist, const LoopData *OuterLoop,
455 const BlockNode &Pred, const BlockNode &Succ, uint64_t Weight);
456
457 /// Analyze irreducible SCCs.
458 ///
459 /// Separate irreducible SCCs from \c G, which is an explicit graph of \c
460 /// OuterLoop (or the top-level function, if \c OuterLoop is \c nullptr).
461 /// Insert them into \a Loops before \c Insert.
462 ///
463 /// \return the \c LoopData nodes representing the irreducible SCCs.
466 std::list<LoopData>::iterator Insert);
467
468 /// Update a loop after packaging irreducible SCCs inside of it.
469 ///
470 /// Update \c OuterLoop. Before finding irreducible control flow, it was
471 /// partway through \a computeMassInLoop(), so \a LoopData::Exits and \a
472 /// LoopData::BackedgeMass need to be reset. Also, nodes that were packaged
473 /// up need to be removed from \a OuterLoop::Nodes.
474 void updateLoopWithIrreducible(LoopData &OuterLoop);
475
476 /// Distribute mass according to a distribution.
477 ///
478 /// Distributes the mass in Source according to Dist. If LoopHead.isValid(),
479 /// backedges and exits are stored in its entry in Loops.
480 ///
481 /// Mass is distributed in parallel from two copies of the source mass.
482 void distributeMass(const BlockNode &Source, LoopData *OuterLoop,
483 Distribution &Dist);
484
485 /// Compute the loop scale for a loop.
487
488 /// Adjust the mass of all headers in an irreducible loop.
489 ///
490 /// Initially, irreducible loops are assumed to distribute their mass
491 /// equally among its headers. This can lead to wrong frequency estimates
492 /// since some headers may be executed more frequently than others.
493 ///
494 /// This adjusts header mass distribution so it matches the weights of
495 /// the backedges going into each of the loop headers.
497
499
500 /// Package up a loop.
502
503 /// Unwrap loops.
504 void unwrapLoops();
505
506 /// Finalize frequency metrics.
507 ///
508 /// Calculates final frequencies and cleans up no-longer-needed data
509 /// structures.
510 void finalizeMetrics();
511
512 /// Clear all memory.
513 void clear();
514
515 virtual std::string getBlockName(const BlockNode &Node) const;
516 std::string getLoopName(const LoopData &Loop) const;
517
518 virtual raw_ostream &print(raw_ostream &OS) const { return OS; }
519 void dump() const { print(dbgs()); }
520
521 Scaled64 getFloatingBlockFreq(const BlockNode &Node) const;
522
523 BlockFrequency getBlockFreq(const BlockNode &Node) const;
524 std::optional<uint64_t> getBlockProfileCount(const Function &F,
525 const BlockNode &Node) const;
526 std::optional<uint64_t> getProfileCountFromFreq(const Function &F,
527 BlockFrequency Freq) const;
528 bool isIrrLoopHeader(const BlockNode &Node);
529
530 void setBlockFreq(const BlockNode &Node, BlockFrequency Freq);
531
533 assert(!Freqs.empty());
534 return BlockFrequency(Freqs[0].Integer);
535 }
536};
537
538namespace bfi_detail {
539
540template <class BlockT> struct TypeMap {};
553
554/// Get the name of a MachineBasicBlock.
555///
556/// Get the name of a MachineBasicBlock. It's templated so that including from
557/// CodeGen is unnecessary (that would be a layering issue).
558///
559/// This is used mainly for debug output. The name is similar to
560/// MachineBasicBlock::getFullName(), but skips the name of the function.
561template <class BlockT> std::string getBlockName(const BlockT *BB) {
562 assert(BB && "Unexpected nullptr");
563 auto MachineName = "BB" + Twine(BB->getNumber());
564 if (BB->getBasicBlock())
565 return (MachineName + "[" + BB->getName() + "]").str();
566 return MachineName.str();
567}
568/// Get the name of a BasicBlock.
569template <> inline std::string getBlockName(const BasicBlock *BB) {
570 assert(BB && "Unexpected nullptr");
571 return BB->getName().str();
572}
573
574/// Graph of irreducible control flow.
575///
576/// This graph is used for determining the SCCs in a loop (or top-level
577/// function) that has irreducible control flow.
578///
579/// During the block frequency algorithm, the local graphs are defined in a
580/// light-weight way, deferring to the \a BasicBlock or \a MachineBasicBlock
581/// graphs for most edges, but getting others from \a LoopData::ExitMap. The
582/// latter only has successor information.
583///
584/// \a IrreducibleGraph makes this graph explicit. It's in a form that can use
585/// \a GraphTraits (so that \a analyzeIrreducible() can use \a scc_iterator),
586/// and it explicitly lists predecessors and successors. The initialization
587/// that relies on \c MachineBasicBlock is defined in the header.
590
592
606 const IrrNode *StartIrr = nullptr;
607 std::vector<IrrNode> Nodes;
609
610 /// The position of \p N in \a Nodes, for indexing side tables.
611 unsigned getIndex(const IrrNode *N) const { return N - Nodes.data(); }
612
613 /// Construct an explicit graph containing irreducible control flow.
614 ///
615 /// Construct an explicit graph of the control flow in \c OuterLoop (or the
616 /// top-level function, if \c OuterLoop is \c nullptr). Uses \c
617 /// addBlockEdges to add block successors that have not been packaged into
618 /// loops.
619 ///
620 /// \a BlockFrequencyInfoImpl::computeIrreducibleMass() is the only expected
621 /// user of this.
622 template <class BlockEdgesAdder>
624 BlockEdgesAdder addBlockEdges) : BFI(BFI) {
625 initialize(OuterLoop, addBlockEdges);
626 }
627
628 template <class BlockEdgesAdder>
629 void initialize(const BFIBase::LoopData *OuterLoop,
630 BlockEdgesAdder addBlockEdges);
631 LLVM_ABI void addNodesInLoop(const BFIBase::LoopData &OuterLoop);
633
634 void addNode(const BlockNode &Node) {
635 Nodes.emplace_back(Node);
636 BFI.Working[Node.Index].getMass() = BlockMass::getEmpty();
637 }
638
639 LLVM_ABI void indexNodes();
640 template <class BlockEdgesAdder>
641 void addEdges(const BlockNode &Node, const BFIBase::LoopData *OuterLoop,
642 BlockEdgesAdder addBlockEdges);
643 LLVM_ABI void addEdge(IrrNode &Irr, const BlockNode &Succ,
644 const BFIBase::LoopData *OuterLoop);
645};
646
647template <class BlockEdgesAdder>
649 BlockEdgesAdder addBlockEdges) {
650 if (OuterLoop) {
651 addNodesInLoop(*OuterLoop);
652 for (auto N : OuterLoop->Nodes)
653 addEdges(N, OuterLoop, addBlockEdges);
654 } else {
656 for (uint32_t Index = 0; Index < BFI.Working.size(); ++Index)
657 addEdges(Index, OuterLoop, addBlockEdges);
658 }
659 StartIrr = Lookup[Start.Index];
660}
661
662template <class BlockEdgesAdder>
664 const BFIBase::LoopData *OuterLoop,
665 BlockEdgesAdder addBlockEdges) {
666 auto L = Lookup.find(Node.Index);
667 if (L == Lookup.end())
668 return;
669 IrrNode &Irr = *L->second;
670 const auto &Working = BFI.Working[Node.Index];
671
672 if (Working.isAPackage())
673 for (const auto &I : Working.Loop->Exits)
674 addEdge(Irr, I.first, OuterLoop);
675 else
676 addBlockEdges(*this, Irr, OuterLoop);
677}
678
679} // end namespace bfi_detail
680
681/// Shared implementation for block frequency analysis.
682///
683/// This is a shared implementation of BlockFrequencyInfo and
684/// MachineBlockFrequencyInfo, and calculates the relative frequencies of
685/// blocks.
686///
687/// LoopInfo defines a loop as a "non-trivial" SCC dominated by a single block,
688/// which is called the header. A given loop, L, can have sub-loops, which are
689/// loops within the subgraph of L that exclude its header. (A "trivial" SCC
690/// consists of a single block that does not have a self-edge.)
691///
692/// In addition to loops, this algorithm has limited support for irreducible
693/// SCCs, which are SCCs with multiple entry blocks. Irreducible SCCs are
694/// discovered on the fly, and modelled as loops with multiple headers.
695///
696/// The headers of irreducible sub-SCCs consist of its entry blocks and all
697/// nodes that are targets of a backedge within it (excluding backedges within
698/// true sub-loops). Block frequency calculations act as if a block is
699/// inserted that intercepts all the edges to the headers. All backedges and
700/// entries point to this block. Its successors are the headers, which split
701/// the frequency evenly.
702///
703/// This algorithm leverages BlockMass and ScaledNumber to maintain precision,
704/// separates mass distribution from loop scaling, and dithers to eliminate
705/// probability mass loss.
706///
707/// The implementation is split between BlockFrequencyInfoImpl, which knows the
708/// type of graph being modelled (BasicBlock vs. MachineBasicBlock), and
709/// BlockFrequencyInfoImplBase, which doesn't. The base class uses \a
710/// BlockNode, a wrapper around a uint32_t. BlockNode is numbered from 0 in
711/// reverse-post order. This gives two advantages: it's easy to compare the
712/// relative ordering of two nodes, and maps keyed on BlockT can be represented
713/// by vectors.
714///
715/// This algorithm is O(V+E), unless there is irreducible control flow, in
716/// which case it's O(V*E) in the worst case.
717///
718/// These are the main stages:
719///
720/// 0. Reverse post-order traversal (\a initializeRPOT()).
721///
722/// Run a single post-order traversal and save it (in reverse) in RPOT.
723/// All other stages make use of this ordering. Save a lookup from BlockT
724/// to BlockNode (the index into RPOT) in Nodes.
725///
726/// 1. Loop initialization (\a initializeLoops()).
727///
728/// Translate LoopInfo/MachineLoopInfo into a form suitable for the rest of
729/// the algorithm. In particular, store the immediate members of each loop
730/// in reverse post-order.
731///
732/// 2. Calculate mass and scale in loops (\a computeMassInLoops()).
733///
734/// For each loop (bottom-up), distribute mass through the DAG resulting
735/// from ignoring backedges and treating sub-loops as a single pseudo-node.
736/// Track the backedge mass distributed to the loop header, and use it to
737/// calculate the loop scale (number of loop iterations). Immediate
738/// members that represent sub-loops will already have been visited and
739/// packaged into a pseudo-node.
740///
741/// Distributing mass in a loop is a reverse-post-order traversal through
742/// the loop. Start by assigning full mass to the Loop header. For each
743/// node in the loop:
744///
745/// - Fetch and categorize the weight distribution for its successors.
746/// If this is a packaged-subloop, the weight distribution is stored
747/// in \a LoopData::Exits. Otherwise, fetch it from
748/// BranchProbabilityInfo.
749///
750/// - Each successor is categorized as \a Weight::Local, a local edge
751/// within the current loop, \a Weight::Backedge, a backedge to the
752/// loop header, or \a Weight::Exit, any successor outside the loop.
753/// The weight, the successor, and its category are stored in \a
754/// Distribution. There can be multiple edges to each successor.
755///
756/// - If there's a backedge to a non-header, there's an irreducible SCC.
757/// The usual flow is temporarily aborted. \a
758/// computeIrreducibleMass() finds the irreducible SCCs within the
759/// loop, packages them up, and restarts the flow.
760///
761/// - Normalize the distribution: scale weights down so that their sum
762/// is 32-bits, and coalesce multiple edges to the same node.
763///
764/// - Distribute the mass accordingly, dithering to minimize mass loss,
765/// as described in \a distributeMass().
766///
767/// In the case of irreducible loops, instead of a single loop header,
768/// there will be several. The computation of backedge masses is similar
769/// but instead of having a single backedge mass, there will be one
770/// backedge per loop header. In these cases, each backedge will carry
771/// a mass proportional to the edge weights along the corresponding
772/// path.
773///
774/// At the end of propagation, the full mass assigned to the loop will be
775/// distributed among the loop headers proportionally according to the
776/// mass flowing through their backedges.
777///
778/// Finally, calculate the loop scale from the accumulated backedge mass.
779///
780/// 3. Distribute mass in the function (\a computeMassInFunction()).
781///
782/// Finally, distribute mass through the DAG resulting from packaging all
783/// loops in the function. This uses the same algorithm as distributing
784/// mass in a loop, except that there are no exit or backedge edges.
785///
786/// 4. Unpackage loops (\a unwrapLoops()).
787///
788/// Initialize each block's frequency to a floating point representation of
789/// its mass.
790///
791/// Visit loops top-down, scaling the frequencies of its immediate members
792/// by the loop's pseudo-node's frequency.
793///
794/// 5. Convert frequencies to a 64-bit range (\a finalizeMetrics()).
795///
796/// Using the min and max frequencies as a guide, translate floating point
797/// frequencies to an appropriate range in uint64_t.
798///
799/// It has some known flaws.
800///
801/// - The model of irreducible control flow is a rough approximation.
802///
803/// Modelling irreducible control flow exactly involves setting up and
804/// solving a group of infinite geometric series. Such precision is
805/// unlikely to be worthwhile, since most of our algorithms give up on
806/// irreducible control flow anyway.
807///
808/// Nevertheless, we might find that we need to get closer. Here's a sort
809/// of TODO list for the model with diminishing returns, to be completed as
810/// necessary.
811///
812/// - The headers for the \a LoopData representing an irreducible SCC
813/// include non-entry blocks. When these extra blocks exist, they
814/// indicate a self-contained irreducible sub-SCC. We could treat them
815/// as sub-loops, rather than arbitrarily shoving the problematic
816/// blocks into the headers of the main irreducible SCC.
817///
818/// - Entry frequencies are assumed to be evenly split between the
819/// headers of a given irreducible SCC, which is the only option if we
820/// need to compute mass in the SCC before its parent loop. Instead,
821/// we could partially compute mass in the parent loop, and stop when
822/// we get to the SCC. Here, we have the correct ratio of entry
823/// masses, which we can use to adjust their relative frequencies.
824/// Compute mass in the SCC, and then continue propagation in the
825/// parent.
826///
827/// - We can propagate mass iteratively through the SCC, for some fixed
828/// number of iterations. Each iteration starts by assigning the entry
829/// blocks their backedge mass from the prior iteration. The final
830/// mass for each block (and each exit, and the total backedge mass
831/// used for computing loop scale) is the sum of all iterations.
832/// (Running this until fixed point would "solve" the geometric
833/// series by simulation.)
835 using BlockT = typename bfi_detail::TypeMap<BT>::BlockT;
836 using FunctionT = typename bfi_detail::TypeMap<BT>::FunctionT;
837 using BranchProbabilityInfoT =
839 using CycleInfoT = typename bfi_detail::TypeMap<BT>::CycleInfoT;
840 using Successor = GraphTraits<const BlockT *>;
841 using Predecessor = GraphTraits<Inverse<const BlockT *>>;
842
843 const BranchProbabilityInfoT *BPI = nullptr;
844 const CycleInfoT *CI = nullptr;
845 const FunctionT *F = nullptr;
846
847 // All blocks in reverse postorder.
848 std::vector<const BlockT *> RPOT;
849 /// Map from block number to number on RPOT/Freqs.
851 unsigned BlockNumberEpoch;
852
853 BlockNode getNode(const BlockT *BB) const {
854 assert(BlockNumberEpoch ==
856 unsigned BlockNumber = GraphTraits<const BlockT *>::getNumber(BB);
857 return BlockNumber < Nodes.size() ? Nodes[BlockNumber] : BlockNode();
858 }
859
860 const BlockT *getBlock(const BlockNode &Node) const {
861 assert(Node.Index < RPOT.size());
862 return RPOT[Node.Index];
863 }
864
865 /// Run (and save) a post-order traversal.
866 ///
867 /// Saves a reverse post-order traversal of all the nodes in \a F.
868 void initializeRPOT();
869
870 /// Initialize loop data.
871 ///
872 /// Build up \a Loops using \a LoopInfo. \a LoopInfo gives us a mapping from
873 /// each block to the deepest loop it's in, but we need the inverse. For each
874 /// loop, we store in reverse post-order its "immediate" members, defined as
875 /// the header, the headers of immediate sub-loops, and all other blocks in
876 /// the loop that are not in sub-loops.
877 void initializeLoops();
878
879 /// Propagate to a block's successors.
880 ///
881 /// In the context of distributing mass through \c OuterLoop, divide the mass
882 /// currently assigned to \c Node between its successors.
883 ///
884 /// \return \c true unless there's an irreducible backedge.
885 bool propagateMassToSuccessors(LoopData *OuterLoop, const BlockNode &Node);
886
887 /// Compute mass in a particular loop.
888 ///
889 /// Assign mass to \c Loop's header, and then for each block in \c Loop in
890 /// reverse post-order, distribute mass to its successors. Only visits nodes
891 /// that have not been packaged into sub-loops.
892 ///
893 /// \pre \a computeMassInLoop() has been called for each subloop of \c Loop.
894 /// \return \c true unless there's an irreducible backedge.
895 bool computeMassInLoop(LoopData &Loop);
896
897 /// Try to compute mass in the top-level function.
898 ///
899 /// Assign mass to the entry block, and then for each block in reverse
900 /// post-order, distribute mass to its successors. Skips nodes that have
901 /// been packaged into loops.
902 ///
903 /// \pre \a computeMassInLoops() has been called.
904 /// \return \c true unless there's an irreducible backedge.
905 bool tryToComputeMassInFunction();
906
907 /// Compute mass in (and package up) irreducible SCCs.
908 ///
909 /// Find the irreducible SCCs in \c OuterLoop, add them to \a Loops (in front
910 /// of \c Insert), and call \a computeMassInLoop() on each of them.
911 ///
912 /// If \c OuterLoop is \c nullptr, it refers to the top-level function.
913 ///
914 /// \pre \a computeMassInLoop() has been called for each subloop of \c
915 /// OuterLoop.
916 /// \pre \c Insert points at the last loop successfully processed by \a
917 /// computeMassInLoop().
918 /// \pre \c OuterLoop has irreducible SCCs.
919 void computeIrreducibleMass(LoopData *OuterLoop,
920 std::list<LoopData>::iterator Insert);
921
922 /// Compute mass in all loops.
923 ///
924 /// For each loop bottom-up, call \a computeMassInLoop().
925 ///
926 /// \a computeMassInLoop() aborts (and returns \c false) on loops that
927 /// contain a irreducible sub-SCCs. Use \a computeIrreducibleMass() and then
928 /// re-enter \a computeMassInLoop().
929 ///
930 /// \post \a computeMassInLoop() has returned \c true for every loop.
931 void computeMassInLoops();
932
933 /// Compute mass in the top-level function.
934 ///
935 /// Uses \a tryToComputeMassInFunction() and \a computeIrreducibleMass() to
936 /// compute mass in the top-level function.
937 ///
938 /// \post \a tryToComputeMassInFunction() has returned \c true.
939 void computeMassInFunction();
940
941 std::string getBlockName(const BlockNode &Node) const override {
942 return bfi_detail::getBlockName(getBlock(Node));
943 }
944
945 /// The current implementation for computing relative block frequencies does
946 /// not handle correctly control-flow graphs containing irreducible loops. To
947 /// resolve the problem, we apply a post-processing step, which iteratively
948 /// updates block frequencies based on the frequencies of their predesessors.
949 /// This corresponds to finding the stationary point of the Markov chain by
950 /// an iterative method aka "PageRank computation".
951 /// The algorithm takes at most O(|E| * IterativeBFIMaxIterations) steps but
952 /// typically converges faster.
953 ///
954 /// Decide whether we want to apply iterative inference for a given function.
955 bool needIterativeInference() const;
956
957 /// Apply an iterative post-processing to infer correct counts for irr loops.
958 void applyIterativeInference();
959
960 using ProbMatrixType = std::vector<std::vector<std::pair<size_t, Scaled64>>>;
961
962 /// Run iterative inference for a probability matrix and initial frequencies.
963 void iterativeInference(const ProbMatrixType &ProbMatrix,
964 std::vector<Scaled64> &Freq) const;
965
966 /// Find all blocks to apply inference on, that is, reachable from the entry
967 /// and backward reachable from exists along edges with positive probability.
968 void findReachableBlocks(std::vector<const BlockT *> &Blocks) const;
969
970 /// Build a matrix of probabilities with transitions (edges) between the
971 /// blocks: ProbMatrix[I] holds pairs (J, P), where Pr[J -> I | J] = P
972 void initTransitionProbabilities(
973 const std::vector<const BlockT *> &Blocks,
974 const DenseMap<const BlockT *, size_t> &BlockIndex,
975 ProbMatrixType &ProbMatrix) const;
976
977#ifndef NDEBUG
978 /// Compute the discrepancy between current block frequencies and the
979 /// probability matrix.
980 Scaled64 discrepancy(const ProbMatrixType &ProbMatrix,
981 const std::vector<Scaled64> &Freq) const;
982#endif
983
984public:
986
987 const FunctionT *getFunction() const { return F; }
988
989 void calculate(const FunctionT &F, const BranchProbabilityInfoT &BPI,
990 const CycleInfoT &CI);
991
993
994 BlockFrequency getBlockFreq(const BlockT *BB) const {
996 }
997
998 std::optional<uint64_t> getBlockProfileCount(const Function &F,
999 const BlockT *BB) const {
1001 }
1002
1003 std::optional<uint64_t> getProfileCountFromFreq(const Function &F,
1004 BlockFrequency Freq) const {
1006 }
1007
1008 bool isIrrLoopHeader(const BlockT *BB) {
1010 }
1011
1012 void setBlockFreq(const BlockT *BB, BlockFrequency Freq);
1013
1014 Scaled64 getFloatingBlockFreq(const BlockT *BB) const {
1016 }
1017
1018 const BranchProbabilityInfoT &getBPI() const { return *BPI; }
1019
1020 /// Print the frequencies for the current function.
1021 ///
1022 /// Prints the frequencies for the blocks in the current function.
1023 ///
1024 /// Blocks are printed in the natural iteration order of the function, rather
1025 /// than reverse post-order. This provides two advantages: writing -analyze
1026 /// tests is easier (since blocks come out in source order), and even
1027 /// unreachable blocks are printed.
1028 ///
1029 /// \a BlockFrequencyInfoImplBase::print() only knows reverse post-order, so
1030 /// we need to override it here.
1031 raw_ostream &print(raw_ostream &OS) const override;
1032
1034
1036};
1037
1038template <class BT>
1040 const BranchProbabilityInfoT &BPI,
1041 const CycleInfoT &CI) {
1042 // Save the parameters.
1043 this->BPI = &BPI;
1044 this->CI = &CI;
1045 this->F = &F;
1046
1047 // Clean up left-over data structures.
1049 RPOT.clear();
1050 Nodes.clear();
1051
1052 // Initialize.
1053 LLVM_DEBUG(dbgs() << "\nblock-frequency: " << F.getName()
1054 << "\n================="
1055 << std::string(F.getName().size(), '=') << "\n");
1056 initializeRPOT();
1057 initializeLoops();
1058
1059 // Visit loops in post-order to find the local mass distribution, and then do
1060 // the full function.
1061 computeMassInLoops();
1062 computeMassInFunction();
1063 unwrapLoops();
1064 // Apply a post-processing step improving computed frequencies for functions
1065 // with irreducible loops.
1066 if (needIterativeInference())
1067 applyIterativeInference();
1069
1071 // To detect BFI queries for unknown blocks, add entries for unreachable
1072 // blocks, if any. This is to distinguish between known/existing unreachable
1073 // blocks and unknown blocks.
1074 for (const BlockT &BB : F)
1075 if (!getNode(&BB).isValid())
1077 }
1078
1079 RPOT.clear();
1080}
1081
1082template <class BT>
1084 BlockFrequency Freq) {
1086 unsigned BlockNumber = GraphTraits<const BlockT *>::getNumber(BB);
1087 if (Nodes.size() <= BlockNumber)
1089 BlockNode &Node = Nodes[BlockNumber];
1090 if (!Node.isValid()) {
1091 // If BB is a newly added block after BFI is done, we need to create a new
1092 // BlockNode for it assigned with a new index. The index can be determined
1093 // by the size of Freqs.
1094 Node = BlockNode(Freqs.size());
1095 Freqs.emplace_back();
1096 }
1098}
1099
1100template <class BT> void BlockFrequencyInfoImpl<BT>::initializeRPOT() {
1101 const BlockT *Entry = &F->front();
1102 RPOT.reserve(F->size());
1103 for (const BlockT *BB : post_order(Entry))
1104 RPOT.emplace_back(BB);
1105 std::reverse(RPOT.begin(), RPOT.end());
1106
1107 assert(RPOT.size() - 1 <= BlockNode::getMaxIndex() &&
1108 "More nodes in function than Block Frequency Info supports");
1109
1110 LLVM_DEBUG(dbgs() << "reverse-post-order-traversal\n");
1113 for (auto [Idx, Block] : enumerate(RPOT)) {
1114 BlockNode Node = BlockNode(Idx);
1115 LLVM_DEBUG(dbgs() << " - " << Idx << ": " << getBlockName(Node) << "\n");
1117 }
1118
1119 Working.reserve(RPOT.size());
1120 for (size_t Index = 0; Index < RPOT.size(); ++Index)
1121 Working.emplace_back(Index);
1122 Freqs.resize(RPOT.size());
1123}
1124
1125template <class BT> void BlockFrequencyInfoImpl<BT>::initializeLoops() {
1126 LLVM_DEBUG(dbgs() << "loop-detection\n");
1127
1128 LLVM_DEBUG(CI->print(dbgs()));
1129
1130 // Whether \p C describes a loop for BFI. An entry of a cycle an edge
1131 // re-enters heads a loop the forest does not represent, because the cycle
1132 // absorbed it; which entry that is depends on the order the search found
1133 // them in. Represent none of them, so that equal entries stay equal, and
1134 // leave the region to the packaging computeIrreducibleMass does.
1135 auto hasLoop = [&](CycleRef C) {
1136 if (!CI->isReducible(C))
1137 return false;
1138 for (CycleRef A = CI->getParentCycle(C); A; A = CI->getParentCycle(A))
1139 if (!CI->isReducible(A) && CI->isEntry(A, CI->getHeader(C)))
1140 return false;
1141 return true;
1142 };
1143
1144 // Visit loops top down and assign them an index.
1145 std::deque<std::pair<CycleRef, LoopData *>> Q;
1146 for (CycleRef C : CI->toplevel_cycles())
1147 Q.emplace_back(C, nullptr);
1148 if (Q.empty())
1149 return; // Early exit if there are no cycles.
1150 while (!Q.empty()) {
1151 CycleRef Cycle = Q.front().first;
1152 LoopData *Parent = Q.front().second;
1153 Q.pop_front();
1154
1155 if (hasLoop(Cycle)) {
1156 BlockNode Header = getNode(CI->getHeader(Cycle));
1157 Loops.emplace_back(Parent, Header);
1158
1159 Working[Header.Index].Loop = &Loops.back();
1160 LLVM_DEBUG(dbgs() << " - loop = " << getBlockName(Header) << "\n");
1161 Parent = &Loops.back();
1162 }
1163
1164 for (CycleRef C : CI->children(Cycle))
1165 Q.emplace_back(C, Parent);
1166 }
1167
1168 // Visit nodes in reverse post-order and add them to their deepest containing
1169 // loop.
1170 for (size_t Index = 0; Index < RPOT.size(); ++Index) {
1171 // Loop headers have already been mostly mapped.
1172 if (Working[Index].isLoopHeader()) {
1173 LoopData *ContainingLoop = Working[Index].getContainingLoop();
1174 if (ContainingLoop)
1175 ContainingLoop->Nodes.push_back(Index);
1176 continue;
1177 }
1178
1179 CycleRef Cycle = CI->getCycle(RPOT[Index]);
1180 while (Cycle && !hasLoop(Cycle))
1181 Cycle = CI->getParentCycle(Cycle);
1182 if (!Cycle)
1183 continue;
1184
1185 // Add this node to its containing loop's member list.
1186 BlockNode Header = getNode(CI->getHeader(Cycle));
1187 assert(Header.isValid());
1188 const auto &HeaderData = Working[Header.Index];
1189 assert(HeaderData.isLoopHeader());
1190
1191 Working[Index].Loop = HeaderData.Loop;
1192 HeaderData.Loop->Nodes.push_back(Index);
1193 LLVM_DEBUG(dbgs() << " - loop = " << getBlockName(Header)
1194 << ": member = " << getBlockName(Index) << "\n");
1195 }
1196}
1197
1198template <class BT> void BlockFrequencyInfoImpl<BT>::computeMassInLoops() {
1199 // Visit loops with the deepest first, and the top-level loops last. The first
1200 // computeMassInLoop returns false if *L contains an irreducible sub-SCC.
1201 // computeIrreducibleMass then packages each such SCC into a new loop,
1202 // inserted immediately after *L.
1203 for (auto L = Loops.end(), B = Loops.begin(); L != B;) {
1204 --L;
1205 if (computeMassInLoop(*L))
1206 continue;
1207 computeIrreducibleMass(&*L, std::next(L));
1208 if (!computeMassInLoop(*L))
1209 llvm_unreachable("unhandled irreducible control flow");
1210 }
1211}
1212
1213template <class BT>
1214bool BlockFrequencyInfoImpl<BT>::computeMassInLoop(LoopData &Loop) {
1215 // Compute mass in loop.
1216 LLVM_DEBUG(dbgs() << "compute-mass-in-loop: " << getLoopName(Loop) << "\n");
1217
1218 if (Loop.isIrreducible()) {
1219 LLVM_DEBUG(dbgs() << "isIrreducible = true\n");
1220 Distribution Dist;
1221 unsigned NumHeadersWithWeight = 0;
1222 std::optional<uint64_t> MinHeaderWeight;
1223 DenseSet<uint32_t> HeadersWithoutWeight;
1224 HeadersWithoutWeight.reserve(Loop.NumHeaders);
1225 for (uint32_t H = 0; H < Loop.NumHeaders; ++H) {
1226 auto &HeaderNode = Loop.Nodes[H];
1227 const BlockT *Block = getBlock(HeaderNode);
1228 IsIrrLoopHeader.set(Loop.Nodes[H].Index);
1229 std::optional<uint64_t> HeaderWeight = Block->getIrrLoopHeaderWeight();
1230 if (!HeaderWeight) {
1231 LLVM_DEBUG(dbgs() << "Missing irr loop header metadata on "
1232 << getBlockName(HeaderNode) << "\n");
1233 HeadersWithoutWeight.insert(H);
1234 continue;
1235 }
1236 LLVM_DEBUG(dbgs() << getBlockName(HeaderNode)
1237 << " has irr loop header weight " << *HeaderWeight
1238 << "\n");
1239 NumHeadersWithWeight++;
1240 uint64_t HeaderWeightValue = *HeaderWeight;
1241 if (!MinHeaderWeight || HeaderWeightValue < MinHeaderWeight)
1242 MinHeaderWeight = HeaderWeightValue;
1243 if (HeaderWeightValue) {
1244 Dist.addLocal(HeaderNode, HeaderWeightValue);
1245 }
1246 }
1247 // As a heuristic, if some headers don't have a weight, give them the
1248 // minimum weight seen (not to disrupt the existing trends too much by
1249 // using a weight that's in the general range of the other headers' weights,
1250 // and the minimum seems to perform better than the average.)
1251 // FIXME: better update in the passes that drop the header weight.
1252 // If no headers have a weight, give them even weight (use weight 1).
1253 if (!MinHeaderWeight)
1254 MinHeaderWeight = 1;
1255 for (uint32_t H : HeadersWithoutWeight) {
1256 auto &HeaderNode = Loop.Nodes[H];
1257 assert(!getBlock(HeaderNode)->getIrrLoopHeaderWeight() &&
1258 "Shouldn't have a weight metadata");
1259 uint64_t MinWeight = *MinHeaderWeight;
1260 LLVM_DEBUG(dbgs() << "Giving weight " << MinWeight << " to "
1261 << getBlockName(HeaderNode) << "\n");
1262 if (MinWeight)
1263 Dist.addLocal(HeaderNode, MinWeight);
1264 }
1265 distributeIrrLoopHeaderMass(Dist);
1266 for (const BlockNode &M : Loop.Nodes)
1267 if (!propagateMassToSuccessors(&Loop, M))
1268 llvm_unreachable("unhandled irreducible control flow");
1269 if (NumHeadersWithWeight == 0)
1270 // No headers have a metadata. Adjust header mass.
1271 adjustLoopHeaderMass(Loop);
1272 } else {
1273 Working[Loop.getHeader().Index].getMass() = BlockMass::getFull();
1274 if (!propagateMassToSuccessors(&Loop, Loop.getHeader()))
1275 llvm_unreachable("irreducible control flow to loop header!?");
1276 for (const BlockNode &M : Loop.members())
1277 if (!propagateMassToSuccessors(&Loop, M))
1278 // Irreducible backedge.
1279 return false;
1280 }
1281
1282 computeLoopScale(Loop);
1283 packageLoop(Loop);
1284 return true;
1285}
1286
1287template <class BT>
1288bool BlockFrequencyInfoImpl<BT>::tryToComputeMassInFunction() {
1289 // Compute mass in function.
1290 LLVM_DEBUG(dbgs() << "compute-mass-in-function\n");
1291 assert(!Working.empty() && "no blocks in function");
1292 assert(!Working[0].isLoopHeader() && "entry block is a loop header");
1293
1294 Working[0].getMass() = BlockMass::getFull();
1295 for (size_t i = 0, n = RPOT.size(); i != n; ++i) {
1296 // Check for nodes that have been packaged.
1297 if (Working[i].isPackaged())
1298 continue;
1299
1300 if (!propagateMassToSuccessors(nullptr, BlockNode(i)))
1301 return false;
1302 }
1303 return true;
1304}
1305
1306template <class BT> void BlockFrequencyInfoImpl<BT>::computeMassInFunction() {
1307 if (tryToComputeMassInFunction())
1308 return;
1309 computeIrreducibleMass(nullptr, Loops.begin());
1310 if (tryToComputeMassInFunction())
1311 return;
1312 llvm_unreachable("unhandled irreducible control flow");
1313}
1314
1315template <class BT>
1316bool BlockFrequencyInfoImpl<BT>::needIterativeInference() const {
1318 return false;
1319 if (!F->getFunction().hasProfileData())
1320 return false;
1321 // Apply iterative inference only if the function contains irreducible loops;
1322 // otherwise, computed block frequencies are reasonably correct.
1323 for (auto L = Loops.rbegin(), E = Loops.rend(); L != E; ++L) {
1324 if (L->isIrreducible())
1325 return true;
1326 }
1327 return false;
1328}
1329
1330template <class BT> void BlockFrequencyInfoImpl<BT>::applyIterativeInference() {
1331 // Extract blocks for processing: a block is considered for inference iff it
1332 // can be reached from the entry by edges with a positive probability.
1333 // Non-processed blocks are assigned with the zero frequency and are ignored
1334 // in the computation
1335 std::vector<const BlockT *> ReachableBlocks;
1336 findReachableBlocks(ReachableBlocks);
1337 if (ReachableBlocks.empty())
1338 return;
1339
1340 // The map is used to index successors/predecessors of reachable blocks in
1341 // the ReachableBlocks vector
1343 // Extract initial frequencies for the reachable blocks
1344 auto Freq = std::vector<Scaled64>(ReachableBlocks.size());
1345 Scaled64 SumFreq;
1346 for (size_t I = 0; I < ReachableBlocks.size(); I++) {
1347 const BlockT *BB = ReachableBlocks[I];
1348 BlockIndex[BB] = I;
1349 Freq[I] = getFloatingBlockFreq(BB);
1350 SumFreq += Freq[I];
1351 }
1352 assert(!SumFreq.isZero() && "empty initial block frequencies");
1353
1354 LLVM_DEBUG(dbgs() << "Applying iterative inference for " << F->getName()
1355 << " with " << ReachableBlocks.size() << " blocks\n");
1356
1357 // Normalizing frequencies so they sum up to 1.0
1358 for (auto &Value : Freq) {
1359 Value /= SumFreq;
1360 }
1361
1362 // Setting up edge probabilities using sparse matrix representation:
1363 // ProbMatrix[I] holds a vector of pairs (J, P) where Pr[J -> I | J] = P
1364 ProbMatrixType ProbMatrix;
1365 initTransitionProbabilities(ReachableBlocks, BlockIndex, ProbMatrix);
1366
1367 // Run the propagation
1368 iterativeInference(ProbMatrix, Freq);
1369
1370 // Assign computed frequency values
1371 for (const BlockT &BB : *F) {
1372 auto Node = getNode(&BB);
1373 if (!Node.isValid())
1374 continue;
1375 if (auto It = BlockIndex.find(&BB); It != BlockIndex.end())
1376 Freqs[Node.Index].Scaled = Freq[It->second];
1377 else
1378 Freqs[Node.Index].Scaled = Scaled64::getZero();
1379 }
1380}
1381
1382template <class BT>
1383void BlockFrequencyInfoImpl<BT>::iterativeInference(
1384 const ProbMatrixType &ProbMatrix, std::vector<Scaled64> &Freq) const {
1386 "incorrectly specified precision");
1387 // Convert double precision to Scaled64
1388 const auto Precision =
1389 Scaled64::getInverse(static_cast<uint64_t>(1.0 / IterativeBFIPrecision));
1390 const size_t MaxIterations = IterativeBFIMaxIterationsPerBlock * Freq.size();
1391
1392#ifndef NDEBUG
1393 LLVM_DEBUG(dbgs() << " Initial discrepancy = "
1394 << discrepancy(ProbMatrix, Freq).toString() << "\n");
1395#endif
1396
1397 // Successors[I] holds unique sucessors of the I-th block
1398 auto Successors = std::vector<std::vector<size_t>>(Freq.size());
1399 for (size_t I = 0; I < Freq.size(); I++) {
1400 for (const auto &Jump : ProbMatrix[I]) {
1401 Successors[Jump.first].push_back(I);
1402 }
1403 }
1404
1405 // To speedup computation, we maintain a set of "active" blocks whose
1406 // frequencies need to be updated based on the incoming edges.
1407 // The set is dynamic and changes after every update. Initially all blocks
1408 // with a positive frequency are active
1409 auto IsActive = BitVector(Freq.size(), false);
1410 std::queue<size_t> ActiveSet;
1411 for (size_t I = 0; I < Freq.size(); I++) {
1412 if (Freq[I] > 0) {
1413 ActiveSet.push(I);
1414 IsActive[I] = true;
1415 }
1416 }
1417
1418 // Iterate over the blocks propagating frequencies
1419 size_t It = 0;
1420 while (It++ < MaxIterations && !ActiveSet.empty()) {
1421 size_t I = ActiveSet.front();
1422 ActiveSet.pop();
1423 IsActive[I] = false;
1424
1425 // Compute a new frequency for the block: NewFreq := Freq \times ProbMatrix.
1426 // A special care is taken for self-edges that needs to be scaled by
1427 // (1.0 - SelfProb), where SelfProb is the sum of probabilities on the edges
1428 Scaled64 NewFreq;
1429 Scaled64 OneMinusSelfProb = Scaled64::getOne();
1430 for (const auto &Jump : ProbMatrix[I]) {
1431 if (Jump.first == I) {
1432 OneMinusSelfProb -= Jump.second;
1433 } else {
1434 NewFreq += Freq[Jump.first] * Jump.second;
1435 }
1436 }
1437 if (OneMinusSelfProb != Scaled64::getOne())
1438 NewFreq /= OneMinusSelfProb;
1439
1440 // If the block's frequency has changed enough, then
1441 // make sure the block and its successors are in the active set
1442 auto Change = Freq[I] >= NewFreq ? Freq[I] - NewFreq : NewFreq - Freq[I];
1443 if (Change > Precision) {
1444 ActiveSet.push(I);
1445 IsActive[I] = true;
1446 for (size_t Succ : Successors[I]) {
1447 if (!IsActive[Succ]) {
1448 ActiveSet.push(Succ);
1449 IsActive[Succ] = true;
1450 }
1451 }
1452 }
1453
1454 // Update the frequency for the block
1455 Freq[I] = NewFreq;
1456 }
1457
1458 LLVM_DEBUG(dbgs() << " Completed " << It << " inference iterations"
1459 << format(" (%0.0f per block)", double(It) / Freq.size())
1460 << "\n");
1461#ifndef NDEBUG
1462 LLVM_DEBUG(dbgs() << " Final discrepancy = "
1463 << discrepancy(ProbMatrix, Freq).toString() << "\n");
1464#endif
1465}
1466
1467template <class BT>
1468void BlockFrequencyInfoImpl<BT>::findReachableBlocks(
1469 std::vector<const BlockT *> &Blocks) const {
1470 // Find all blocks to apply inference on, that is, reachable from the entry
1471 // along edges with non-zero probablities
1472 std::queue<const BlockT *> Queue;
1474 const BlockT *Entry = &F->front();
1475 Queue.push(Entry);
1476 Reachable.insert(Entry);
1477 while (!Queue.empty()) {
1478 const BlockT *SrcBB = Queue.front();
1479 Queue.pop();
1480 for (auto It : enumerate(children<const BlockT *>(SrcBB))) {
1481 auto EP = BPI->getEdgeProbability(SrcBB, It.index());
1482 if (EP.isZero())
1483 continue;
1484 if (Reachable.insert(It.value()).second)
1485 Queue.push(It.value());
1486 }
1487 }
1488
1489 // Find all blocks to apply inference on, that is, backward reachable from
1490 // the entry along (backward) edges with non-zero probablities
1491 SmallPtrSet<const BlockT *, 8> InverseReachable;
1492 for (const BlockT &BB : *F) {
1493 // An exit block is a block without any successors
1494 bool HasSucc = !llvm::children<const BlockT *>(&BB).empty();
1495 if (!HasSucc && Reachable.count(&BB)) {
1496 Queue.push(&BB);
1497 InverseReachable.insert(&BB);
1498 }
1499 }
1500 while (!Queue.empty()) {
1501 const BlockT *SrcBB = Queue.front();
1502 Queue.pop();
1503 for (const BlockT *DstBB : inverse_children<const BlockT *>(SrcBB)) {
1504 auto EP = BPI->getEdgeProbability(DstBB, SrcBB);
1505 if (EP.isZero())
1506 continue;
1507 if (InverseReachable.insert(DstBB).second)
1508 Queue.push(DstBB);
1509 }
1510 }
1511
1512 // Collect the result
1513 Blocks.reserve(F->size());
1514 for (const BlockT &BB : *F) {
1515 if (Reachable.count(&BB) && InverseReachable.count(&BB)) {
1516 Blocks.push_back(&BB);
1517 }
1518 }
1519}
1520
1521template <class BT>
1522void BlockFrequencyInfoImpl<BT>::initTransitionProbabilities(
1523 const std::vector<const BlockT *> &Blocks,
1524 const DenseMap<const BlockT *, size_t> &BlockIndex,
1525 ProbMatrixType &ProbMatrix) const {
1526 const size_t NumBlocks = Blocks.size();
1527 auto Succs = std::vector<std::vector<std::pair<size_t, Scaled64>>>(NumBlocks);
1528 auto SumProb = std::vector<Scaled64>(NumBlocks);
1529
1530 // Find unique successors and corresponding probabilities for every block
1531 for (size_t Src = 0; Src < NumBlocks; Src++) {
1532 const BlockT *BB = Blocks[Src];
1534 for (auto It : enumerate(children<const BlockT *>(BB))) {
1535 const BlockT *SI = It.value();
1536 // Ignore cold blocks
1537 auto BlockIndexIt = BlockIndex.find(SI);
1538 if (BlockIndexIt == BlockIndex.end())
1539 continue;
1540 // Ignore parallel edges between BB and SI blocks
1541 if (!UniqueSuccs.insert(SI).second)
1542 continue;
1543 // Ignore jumps with zero probability
1544 auto EP = BPI->getEdgeProbability(BB, It.index());
1545 if (EP.isZero())
1546 continue;
1547
1548 auto EdgeProb =
1549 Scaled64::getFraction(EP.getNumerator(), EP.getDenominator());
1550 size_t Dst = BlockIndexIt->second;
1551 Succs[Src].push_back(std::make_pair(Dst, EdgeProb));
1552 SumProb[Src] += EdgeProb;
1553 }
1554 }
1555
1556 // Add transitions for every jump with positive branch probability
1557 ProbMatrix = ProbMatrixType(NumBlocks);
1558 for (size_t Src = 0; Src < NumBlocks; Src++) {
1559 // Ignore blocks w/o successors
1560 if (Succs[Src].empty())
1561 continue;
1562
1563 assert(!SumProb[Src].isZero() && "Zero sum probability of non-exit block");
1564 for (auto &Jump : Succs[Src]) {
1565 size_t Dst = Jump.first;
1566 Scaled64 Prob = Jump.second;
1567 ProbMatrix[Dst].push_back(std::make_pair(Src, Prob / SumProb[Src]));
1568 }
1569 }
1570
1571 // Add transitions from sinks to the source
1572 size_t EntryIdx = BlockIndex.find(&F->front())->second;
1573 for (size_t Src = 0; Src < NumBlocks; Src++) {
1574 if (Succs[Src].empty()) {
1575 ProbMatrix[EntryIdx].push_back(std::make_pair(Src, Scaled64::getOne()));
1576 }
1577 }
1578}
1579
1580#ifndef NDEBUG
1581template <class BT>
1582BlockFrequencyInfoImplBase::Scaled64 BlockFrequencyInfoImpl<BT>::discrepancy(
1583 const ProbMatrixType &ProbMatrix, const std::vector<Scaled64> &Freq) const {
1584 assert(Freq[0] > 0 && "Incorrectly computed frequency of the entry block");
1585 Scaled64 Discrepancy;
1586 for (size_t I = 0; I < ProbMatrix.size(); I++) {
1587 Scaled64 Sum;
1588 for (const auto &Jump : ProbMatrix[I]) {
1589 Sum += Freq[Jump.first] * Jump.second;
1590 }
1591 Discrepancy += Freq[I] >= Sum ? Freq[I] - Sum : Sum - Freq[I];
1592 }
1593 // Normalizing by the frequency of the entry block
1594 return Discrepancy / Freq[0];
1595}
1596#endif
1597
1598template <class BT>
1599void BlockFrequencyInfoImpl<BT>::computeIrreducibleMass(
1600 LoopData *OuterLoop, std::list<LoopData>::iterator Insert) {
1601 LLVM_DEBUG(dbgs() << "analyze-irreducible-in-";
1602 if (OuterLoop) dbgs()
1603 << "loop: " << getLoopName(*OuterLoop) << "\n";
1604 else dbgs() << "function\n");
1605
1606 using namespace bfi_detail;
1607
1608 auto addBlockEdges = [&](IrreducibleGraph &G, IrreducibleGraph::IrrNode &Irr,
1609 const LoopData *OuterLoop) {
1610 const BlockT *BB = RPOT[Irr.Node.Index];
1611 for (const auto *Succ : children<const BlockT *>(BB))
1612 G.addEdge(Irr, getNode(Succ), OuterLoop);
1613 };
1614 IrreducibleGraph G(*this, OuterLoop, addBlockEdges);
1615
1616 for (auto &L : analyzeIrreducible(G, OuterLoop, Insert))
1617 computeMassInLoop(L);
1618
1619 if (!OuterLoop)
1620 return;
1621 updateLoopWithIrreducible(*OuterLoop);
1622}
1623
1624// A helper function that converts a branch probability into weight.
1626 return Prob.getNumerator();
1627}
1628
1629template <class BT>
1630bool
1631BlockFrequencyInfoImpl<BT>::propagateMassToSuccessors(LoopData *OuterLoop,
1632 const BlockNode &Node) {
1633 LLVM_DEBUG(dbgs() << " - node: " << getBlockName(Node) << "\n");
1634 // Calculate probability for successors.
1635 Distribution Dist;
1636 if (auto *Loop = Working[Node.Index].getPackagedLoop()) {
1637 assert(Loop != OuterLoop && "Cannot propagate mass in a packaged loop");
1638 if (!addLoopSuccessorsToDist(OuterLoop, *Loop, Dist))
1639 // Irreducible backedge.
1640 return false;
1641 } else {
1642 const BlockT *BB = getBlock(Node);
1643 for (auto It : enumerate(children<const BlockT *>(BB)))
1644 if (!addToDist(
1645 Dist, OuterLoop, Node, getNode(It.value()),
1646 getWeightFromBranchProb(BPI->getEdgeProbability(BB, It.index()))))
1647 // Irreducible backedge.
1648 return false;
1649 }
1650
1651 // Distribute mass to successors, saving exit and backedge data in the
1652 // loop header.
1653 distributeMass(Node, OuterLoop, Dist);
1654 return true;
1655}
1656
1657template <class BT>
1659 if (!F)
1660 return OS;
1661 OS << "block-frequency-info: " << F->getName() << "\n";
1662 for (const BlockT &BB : *F) {
1663 OS << " - " << bfi_detail::getBlockName(&BB) << ": float = ";
1664 getFloatingBlockFreq(&BB).print(OS, 5)
1665 << ", int = " << getBlockFreq(&BB).getFrequency();
1666 if (std::optional<uint64_t> ProfileCount =
1668 F->getFunction(), getNode(&BB)))
1669 OS << ", count = " << *ProfileCount;
1670 if (std::optional<uint64_t> IrrLoopHeaderWeight =
1671 BB.getIrrLoopHeaderWeight())
1672 OS << ", irr_loop_header_weight = " << *IrrLoopHeaderWeight;
1673 OS << "\n";
1674 }
1675
1676 // Add an extra newline for readability.
1677 OS << "\n";
1678 return OS;
1679}
1680
1681template <class BT>
1684 bool Match = true;
1685 // Gather blocks for numbers so that we can print names and determine whether
1686 // they still exist.
1689 for (const auto &BB : *F)
1690 Blocks[GraphTraits<const BlockT *>::getNumber(&BB)] = &BB;
1691
1692 size_t MinSize = std::min(Nodes.size(), Other.Nodes.size());
1693 for (size_t i = 0; i < MinSize; ++i) {
1694 if (!Blocks[i])
1695 continue; // Block got deleted in the mean time, ignore.
1696 if (Nodes[i].isValid() != Other.Nodes[i].isValid()) {
1697 Match = false;
1698 dbgs() << "Block " << bfi_detail::getBlockName(Blocks[i])
1699 << " existence mismatch.\n";
1700 } else if (Nodes[i].isValid()) {
1701 const auto &Freq = Freqs[Nodes[i].Index];
1702 const auto &OtherFreq = Other.Freqs[Other.Nodes[i].Index];
1703 if (Freq.Integer != OtherFreq.Integer) {
1704 Match = false;
1705 dbgs() << "Freq mismatch: " << bfi_detail::getBlockName(Blocks[i])
1706 << " " << Freq.Integer << " vs " << OtherFreq.Integer << "\n";
1707 }
1708 }
1709 }
1710 // Block with higher numbers must not exist in either state.
1711 for (size_t i = MinSize; i < Nodes.size(); ++i) {
1712 if (Nodes[i].isValid()) {
1713 Match = false;
1714 dbgs() << "Block " << bfi_detail::getBlockName(Blocks[i])
1715 << " existence mismatch.\n";
1716 }
1717 }
1718 for (size_t i = MinSize; i < Other.Nodes.size(); ++i) {
1719 if (Other.Nodes[i].isValid()) {
1720 Match = false;
1721 dbgs() << "Block " << bfi_detail::getBlockName(Blocks[i])
1722 << " existence mismatch.\n";
1723 }
1724 }
1725
1726 if (!Match) {
1727 dbgs() << "This\n";
1728 print(dbgs());
1729 dbgs() << "Other\n";
1730 Other.print(dbgs());
1731 }
1732 assert(Match && "BFI mismatch");
1733}
1734
1735// Graph trait base class for block frequency information graph
1736// viewer.
1737
1739
1740template <class BlockFrequencyInfoT, class BranchProbabilityInfoT>
1743 using NodeRef = typename GTraits::NodeRef;
1744 using EdgeIter = typename GTraits::ChildIteratorType;
1745 using NodeIter = typename GTraits::nodes_iterator;
1746
1748
1751
1752 static StringRef getGraphName(const BlockFrequencyInfoT *G) {
1753 return G->getFunction()->getName();
1754 }
1755
1756 std::string getNodeAttributes(NodeRef Node, const BlockFrequencyInfoT *Graph,
1757 unsigned HotPercentThreshold = 0) {
1758 std::string Result;
1759 if (!HotPercentThreshold)
1760 return Result;
1761
1762 // Compute MaxFrequency on the fly:
1763 if (!MaxFrequency) {
1764 for (NodeIter I = GTraits::nodes_begin(Graph),
1765 E = GTraits::nodes_end(Graph);
1766 I != E; ++I) {
1767 NodeRef N = *I;
1768 MaxFrequency =
1769 std::max(MaxFrequency, Graph->getBlockFreq(N).getFrequency());
1770 }
1771 }
1772 BlockFrequency Freq = Graph->getBlockFreq(Node);
1773 BlockFrequency HotFreq =
1775 BranchProbability::getBranchProbability(HotPercentThreshold, 100));
1776
1777 if (Freq < HotFreq)
1778 return Result;
1779
1780 raw_string_ostream(Result) << "color=\"red\"";
1781 return Result;
1782 }
1783
1784 std::string getNodeLabel(NodeRef Node, const BlockFrequencyInfoT *Graph,
1785 GVDAGType GType, int layout_order = -1) {
1786 std::string Result;
1787 raw_string_ostream OS(Result);
1788
1789 if (layout_order != -1)
1790 OS << Node->getName() << "[" << layout_order << "] : ";
1791 else
1792 OS << Node->getName() << " : ";
1793 switch (GType) {
1794 case GVDT_Fraction:
1795 OS << printBlockFreq(*Graph, *Node);
1796 break;
1797 case GVDT_Integer:
1798 OS << Graph->getBlockFreq(Node).getFrequency();
1799 break;
1800 case GVDT_Count: {
1801 auto Count = Graph->getBlockProfileCount(Node);
1802 if (Count)
1803 OS << *Count;
1804 else
1805 OS << "Unknown";
1806 break;
1807 }
1808 case GVDT_None:
1809 llvm_unreachable("If we are not supposed to render a graph we should "
1810 "never reach this point.");
1811 }
1812 return Result;
1813 }
1814
1816 const BlockFrequencyInfoT *BFI,
1817 const BranchProbabilityInfoT *BPI,
1818 unsigned HotPercentThreshold = 0) {
1819 std::string Str;
1820 if (!BPI)
1821 return Str;
1822
1823 unsigned SuccIdx = std::distance(succ_begin(Node), EI);
1824 BranchProbability BP = BPI->getEdgeProbability(Node, SuccIdx);
1825 uint32_t N = BP.getNumerator();
1826 uint32_t D = BP.getDenominator();
1827 double Percent = 100.0 * N / D;
1828 raw_string_ostream OS(Str);
1829 OS << format("label=\"%.1f%%\"", Percent);
1830
1831 if (HotPercentThreshold) {
1832 BlockFrequency EFreq = BFI->getBlockFreq(Node) * BP;
1834 BranchProbability(HotPercentThreshold, 100);
1835
1836 if (EFreq >= HotFreq)
1837 OS << ",color=\"red\"";
1838 }
1839 return Str;
1840 }
1841};
1842
1843} // end namespace llvm
1844
1845#undef DEBUG_TYPE
1846
1847#endif // LLVM_ANALYSIS_BLOCKFREQUENCYINFOIMPL_H
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static msgpack::DocNode getNode(msgpack::DocNode DN, msgpack::Type Type, MCValue Val)
static void print(raw_ostream &Out, object::Archive::Kind Kind, T Val)
#define X(NUM, ENUM, NAME)
Definition ELF.h:856
This file implements the BitVector class.
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define LLVM_ABI
Definition Compiler.h:215
This file defines the DenseMap class.
This file defines the DenseSet and SmallDenseSet classes.
Find all cycles in a control-flow graph, including irreducible loops.
This file defines the little GraphTraits<X> template class that should be specialized by classes that...
Hexagon Hardware Loops
static bool isZero(Value *V, const DataLayout &DL, DominatorTree *DT, AssumptionCache *AC)
Definition Lint.cpp:539
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define G(x, y, z)
Definition MD5.cpp:55
#define H(x, y, z)
Definition MD5.cpp:56
Branch Probability Basic Block static false std::string getBlockName(const MachineBasicBlock *BB)
Helper to print the name of a MBB.
#define P(N)
This file builds on the ADT/GraphTraits.h file to build a generic graph post order iterator.
static bool isValid(const char C)
Returns true if C is a valid mangled character: <0-9a-zA-Z_>.
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
This file defines the SparseBitVector class.
#define LLVM_DEBUG(...)
Definition Debug.h:119
LLVM Basic Block Representation.
Definition BasicBlock.h:62
Base class for BlockFrequencyInfoImpl.
std::vector< WorkingData > Working
Loop data: see initializeLoops().
std::optional< uint64_t > getProfileCountFromFreq(const Function &F, BlockFrequency Freq) const
virtual ~BlockFrequencyInfoImplBase()=default
Virtual destructor.
std::list< LoopData > Loops
Indexed information about loops.
bool addLoopSuccessorsToDist(const LoopData *OuterLoop, LoopData &Loop, Distribution &Dist)
Add all edges out of a packaged loop to the distribution.
std::optional< uint64_t > getBlockProfileCount(const Function &F, const BlockNode &Node) const
std::string getLoopName(const LoopData &Loop) const
bool isIrrLoopHeader(const BlockNode &Node)
void computeLoopScale(LoopData &Loop)
Compute the loop scale for a loop.
void packageLoop(LoopData &Loop)
Package up a loop.
virtual raw_ostream & print(raw_ostream &OS) const
void finalizeMetrics()
Finalize frequency metrics.
void setBlockFreq(const BlockNode &Node, BlockFrequency Freq)
void updateLoopWithIrreducible(LoopData &OuterLoop)
Update a loop after packaging irreducible SCCs inside of it.
BlockFrequency getBlockFreq(const BlockNode &Node) const
void distributeIrrLoopHeaderMass(Distribution &Dist)
iterator_range< std::list< LoopData >::iterator > analyzeIrreducible(const bfi_detail::IrreducibleGraph &G, LoopData *OuterLoop, std::list< LoopData >::iterator Insert)
Analyze irreducible SCCs.
bool addToDist(Distribution &Dist, const LoopData *OuterLoop, const BlockNode &Pred, const BlockNode &Succ, uint64_t Weight)
Add an edge to the distribution.
Scaled64 getFloatingBlockFreq(const BlockNode &Node) const
void distributeMass(const BlockNode &Source, LoopData *OuterLoop, Distribution &Dist)
Distribute mass according to a distribution.
SparseBitVector IsIrrLoopHeader
Whether each block is an irreducible loop header.
std::vector< FrequencyData > Freqs
Data about each block. This is used downstream.
void adjustLoopHeaderMass(LoopData &Loop)
Adjust the mass of all headers in an irreducible loop.
std::optional< uint64_t > getProfileCountFromFreq(const Function &F, BlockFrequency Freq) const
const BranchProbabilityInfoT & getBPI() const
const FunctionT * getFunction() const
void verifyMatch(BlockFrequencyInfoImpl< BT > &Other) const
std::optional< uint64_t > getBlockProfileCount(const Function &F, const BlockT *BB) const
Scaled64 getFloatingBlockFreq(const BlockT *BB) const
void setBlockFreq(const BlockT *BB, BlockFrequency Freq)
void calculate(const FunctionT &F, const BranchProbabilityInfoT &BPI, const CycleInfoT &CI)
raw_ostream & print(raw_ostream &OS) const override
Print the frequencies for the current function.
BlockFrequency getBlockFreq(const BlockT *BB) const
Analysis providing branch probability information.
static LLVM_ABI BranchProbability getBranchProbability(uint64_t Numerator, uint64_t Denominator)
static uint32_t getDenominator()
uint32_t getNumerator() const
Opaque handle to a cycle within a GenericCycleInfo that wraps the cycle's preorder index.
Implements a dense probed hash-table based set.
Definition DenseSet.h:281
BlockT * getHeader() const
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
Simple representation of a scaled number.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
typename SuperClass::const_iterator const_iterator
void resize(size_type N)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
std::string str() const
Get the contents as an std::string.
Definition StringRef.h:222
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
LLVM Value Representation.
Definition Value.h:75
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:319
bool operator<(BlockMass X) const
bool operator>(BlockMass X) const
LLVM_ABI raw_ostream & print(raw_ostream &OS) const
bool operator==(BlockMass X) const
BlockMass & operator-=(BlockMass X)
Subtract another mass.
bool operator<=(BlockMass X) const
BlockMass & operator*=(BranchProbability P)
bool operator!=(BlockMass X) const
BlockMass & operator+=(BlockMass X)
Add another mass.
bool operator>=(BlockMass X) const
LLVM_ABI ScaledNumber< uint64_t > toScaled() const
Convert to scaled number.
void reserve(size_t Size)
Grow the DenseSet so that it can contain at least NumEntries items before resizing again.
Definition DenseSet.h:93
A range adaptor for a pair of iterators.
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
A raw_ostream that writes to an std::string.
This provides a very simple, boring adaptor for a begin and end iterator into a range type.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ Entry
Definition COFF.h:862
std::string getBlockName(const BlockT *BB)
Get the name of a MachineBasicBlock.
BlockMass operator*(BlockMass L, BranchProbability R)
BlockMass operator+(BlockMass L, BlockMass R)
raw_ostream & operator<<(raw_ostream &OS, BlockMass X)
BlockMass operator-(BlockMass L, BlockMass R)
NodeAddr< NodeBase * > Node
Definition RDFGraph.h:381
bool empty() const
Definition BasicBlock.h:101
This is an optimization pass for GlobalISel generic memory operations.
Printable print(const GCNRegPressure &RP, const GCNSubtarget *ST=nullptr, unsigned DynamicVGPRBlockSize=0)
uint32_t getWeightFromBranchProb(const BranchProbability Prob)
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
Definition STLExtras.h:2554
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
LLVM_ABI llvm::cl::opt< unsigned > IterativeBFIMaxIterationsPerBlock
LLVM_ABI llvm::cl::opt< bool > UseIterativeBFIInference
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
auto post_order(const T &G)
Post-order traversal of a graph.
format_object< Ts... > format(const char *Fmt, const Ts &... Vals)
These are helper functions used to produce formatted output.
Definition Format.h:94
LLVM_ABI llvm::cl::opt< bool > CheckBFIUnknownBlockQueries
RNSuccIterator< NodeRef, BlockT, RegionT > succ_begin(NodeRef Node)
@ Other
Any other memory.
Definition ModRef.h:68
constexpr NextUseDistance max(NextUseDistance A, NextUseDistance B)
iterator_range< typename GraphTraits< Inverse< GraphType > >::ChildIteratorType > inverse_children(const typename GraphTraits< GraphType >::NodeRef &G)
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
std::string toString(const APInt &I, unsigned Radix, bool Signed, bool formatAsCLiteral=false, bool UpperCase=true, bool InsertSeparators=false)
iterator_range< typename GraphTraits< GraphType >::ChildIteratorType > children(const typename GraphTraits< GraphType >::NodeRef &G)
LLVM_ABI Printable printBlockFreq(const BlockFrequencyInfo &BFI, BlockFrequency Freq)
Print the block frequency Freq relative to the current functions entry frequency.
LLVM_ABI llvm::cl::opt< double > IterativeBFIPrecision
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:878
#define N
GraphTraits< BlockFrequencyInfoT * > GTraits
std::string getNodeAttributes(NodeRef Node, const BlockFrequencyInfoT *Graph, unsigned HotPercentThreshold=0)
typename GTraits::nodes_iterator NodeIter
typename GTraits::NodeRef NodeRef
typename GTraits::ChildIteratorType EdgeIter
std::string getNodeLabel(NodeRef Node, const BlockFrequencyInfoT *Graph, GVDAGType GType, int layout_order=-1)
std::string getEdgeAttributes(NodeRef Node, EdgeIter EI, const BlockFrequencyInfoT *BFI, const BranchProbabilityInfoT *BPI, unsigned HotPercentThreshold=0)
BFIDOTGraphTraitsBase(bool isSimple=false)
static StringRef getGraphName(const BlockFrequencyInfoT *G)
Distribution of unscaled probability weight.
void addBackedge(const BlockNode &Node, uint64_t Amount)
WeightList Weights
Individual successor weights.
void addExit(const BlockNode &Node, uint64_t Amount)
void addLocal(const BlockNode &Node, uint64_t Amount)
SmallVector< std::pair< BlockNode, BlockMass >, 4 > ExitMap
LoopData(LoopData *Parent, It1 FirstHeader, It1 LastHeader, It2 FirstOther, It2 LastOther)
ExitMap Exits
Successor edges (and weights).
bool IsPackaged
Whether this has been packaged.
LoopData(LoopData *Parent, It FirstHeader, It LastHeader)
LoopData(LoopData *Parent, const BlockNode &Header)
NodeList::const_iterator members_begin() const
NodeList Nodes
Header and the members of the loop.
HeaderMassList BackedgeMass
Mass returned to each loop header.
HeaderMassList::difference_type getHeaderIndex(const BlockNode &B)
iterator_range< NodeList::const_iterator > members() const
Weight(DistType Type, BlockNode TargetNode, uint64_t Amount)
bool isPackaged() const
Has ContainingLoop been packaged up?
BlockMass Mass
Mass distribution from the entry block.
BlockMass & getMass()
The mass slot for Node: its own, or that of the outermost packaged loop it heads.
bool isAPackage() const
Has Loop been packaged up?
LoopData * Loop
The loop this block is inside.
LoopData * getContainingLoop() const
The innermost loop containing Node that Node does not head.
LoopData * getPackagedLoop() const
The outermost loop containing Node that is currently packaged, if any.
BlockNode getResolvedNode() const
Resolve a node to its representative.
DefaultDOTGraphTraits(bool simple=false)
static nodes_iterator nodes_end(const BlockFrequencyInfo *G)
static nodes_iterator nodes_begin(const BlockFrequencyInfo *G)
typename BlockFrequencyInfoT *::UnknownGraphTypeError NodeRef
Definition GraphTraits.h:95
SmallVectorImpl< const IrrNode * >::const_iterator iterator
Graph of irreducible control flow.
IrreducibleGraph(BFIBase &BFI, const BFIBase::LoopData *OuterLoop, BlockEdgesAdder addBlockEdges)
Construct an explicit graph containing irreducible control flow.
LLVM_ABI void addEdge(IrrNode &Irr, const BlockNode &Succ, const BFIBase::LoopData *OuterLoop)
unsigned getIndex(const IrrNode *N) const
The position of N in Nodes, for indexing side tables.
void addEdges(const BlockNode &Node, const BFIBase::LoopData *OuterLoop, BlockEdgesAdder addBlockEdges)
SmallDenseMap< uint32_t, IrrNode *, 4 > Lookup
void initialize(const BFIBase::LoopData *OuterLoop, BlockEdgesAdder addBlockEdges)
LLVM_ABI void addNodesInLoop(const BFIBase::LoopData &OuterLoop)