1 //==- BlockFrequencyInfoImpl.h - Block Frequency Implementation -*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // Shared implementation of BlockFrequency for IR and Machine Instructions.
11 // See the documentation below for BlockFrequencyInfoImpl for details.
13 //===----------------------------------------------------------------------===//
15 #ifndef LLVM_ANALYSIS_BLOCKFREQUENCYINFOIMPL_H
16 #define LLVM_ANALYSIS_BLOCKFREQUENCYINFOIMPL_H
18 #include "llvm/ADT/DenseMap.h"
19 #include "llvm/ADT/PostOrderIterator.h"
20 #include "llvm/ADT/iterator_range.h"
21 #include "llvm/IR/BasicBlock.h"
22 #include "llvm/Support/BlockFrequency.h"
23 #include "llvm/Support/BranchProbability.h"
24 #include "llvm/Support/Debug.h"
25 #include "llvm/Support/ScaledNumber.h"
26 #include "llvm/Support/raw_ostream.h"
32 #define DEBUG_TYPE "block-freq"
34 //===----------------------------------------------------------------------===//
36 // ScaledNumber definition.
38 // TODO: Move to include/llvm/Support/ScaledNumber.h
40 //===----------------------------------------------------------------------===//
43 class ScaledNumberBase {
45 static const int32_t MaxScale = 16383;
46 static const int32_t MinScale = -16382;
47 static const int DefaultPrecision = 10;
49 static void dump(uint64_t D, int16_t E, int Width);
50 static raw_ostream &print(raw_ostream &OS, uint64_t D, int16_t E, int Width,
52 static std::string toString(uint64_t D, int16_t E, int Width,
54 static int countLeadingZeros32(uint32_t N) { return countLeadingZeros(N); }
55 static int countLeadingZeros64(uint64_t N) { return countLeadingZeros(N); }
56 static uint64_t getHalf(uint64_t N) { return (N >> 1) + (N & 1); }
58 static std::pair<uint64_t, bool> splitSigned(int64_t N) {
60 return std::make_pair(N, false);
61 uint64_t Unsigned = N == INT64_MIN ? UINT64_C(1) << 63 : uint64_t(-N);
62 return std::make_pair(Unsigned, true);
64 static int64_t joinSigned(uint64_t U, bool IsNeg) {
65 if (U > uint64_t(INT64_MAX))
66 return IsNeg ? INT64_MIN : INT64_MAX;
67 return IsNeg ? -int64_t(U) : int64_t(U);
71 /// \brief Simple representation of a scaled number.
73 /// ScaledNumber is a number represented by digits and a scale. It uses simple
74 /// saturation arithmetic and every operation is well-defined for every value.
75 /// It's somewhat similar in behaviour to a soft-float, but is *not* a
76 /// replacement for one. If you're doing numerics, look at \a APFloat instead.
77 /// Nevertheless, we've found these semantics useful for modelling certain cost
80 /// The number is split into a signed scale and unsigned digits. The number
81 /// represented is \c getDigits()*2^getScale(). In this way, the digits are
82 /// much like the mantissa in the x87 long double, but there is no canonical
83 /// form so the same number can be represented by many bit representations.
85 /// ScaledNumber is templated on the underlying integer type for digits, which
86 /// is expected to be unsigned.
88 /// Unlike APFloat, ScaledNumber does not model architecture floating point
89 /// behaviour -- while this might make it a little faster and easier to reason
90 /// about, it certainly makes it more dangerous for general numerics.
92 /// ScaledNumber is totally ordered. However, there is no canonical form, so
93 /// there are multiple representations of most scalars. E.g.:
95 /// ScaledNumber(8u, 0) == ScaledNumber(4u, 1)
96 /// ScaledNumber(4u, 1) == ScaledNumber(2u, 2)
97 /// ScaledNumber(2u, 2) == ScaledNumber(1u, 3)
99 /// ScaledNumber implements most arithmetic operations. Precision is kept
100 /// where possible. Uses simple saturation arithmetic, so that operations
101 /// saturate to 0.0 or getLargest() rather than under or overflowing. It has
102 /// some extra arithmetic for unit inversion. 0.0/0.0 is defined to be 0.0.
103 /// Any other division by 0.0 is defined to be getLargest().
105 /// As a convenience for modifying the exponent, left and right shifting are
106 /// both implemented, and both interpret negative shifts as positive shifts in
107 /// the opposite direction.
109 /// Scales are limited to the range accepted by x87 long double. This makes
110 /// it trivial to add functionality to convert to APFloat (this is already
111 /// relied on for the implementation of printing).
113 /// Possible (and conflicting) future directions:
115 /// 1. Turn this into a wrapper around \a APFloat.
116 /// 2. Share the algorithm implementations with \a APFloat.
117 /// 3. Allow \a ScaledNumber to represent a signed number.
118 template <class DigitsT> class ScaledNumber : ScaledNumberBase {
120 static_assert(!std::numeric_limits<DigitsT>::is_signed,
121 "only unsigned floats supported");
123 typedef DigitsT DigitsType;
126 typedef std::numeric_limits<DigitsType> DigitsLimits;
128 static const int Width = sizeof(DigitsType) * 8;
129 static_assert(Width <= 64, "invalid integer width for digits");
136 ScaledNumber() : Digits(0), Scale(0) {}
138 ScaledNumber(DigitsType Digits, int16_t Scale)
139 : Digits(Digits), Scale(Scale) {}
142 ScaledNumber(const std::pair<uint64_t, int16_t> &X)
143 : Digits(X.first), Scale(X.second) {}
146 static ScaledNumber getZero() { return ScaledNumber(0, 0); }
147 static ScaledNumber getOne() { return ScaledNumber(1, 0); }
148 static ScaledNumber getLargest() {
149 return ScaledNumber(DigitsLimits::max(), MaxScale);
151 static ScaledNumber getFloat(uint64_t N) { return adjustToWidth(N, 0); }
152 static ScaledNumber getInverseFloat(uint64_t N) {
153 return getFloat(N).invert();
155 static ScaledNumber getFraction(DigitsType N, DigitsType D) {
156 return getQuotient(N, D);
159 int16_t getScale() const { return Scale; }
160 DigitsType getDigits() const { return Digits; }
162 /// \brief Convert to the given integer type.
164 /// Convert to \c IntT using simple saturating arithmetic, truncating if
166 template <class IntT> IntT toInt() const;
168 bool isZero() const { return !Digits; }
169 bool isLargest() const { return *this == getLargest(); }
171 if (Scale > 0 || Scale <= -Width)
173 return Digits == DigitsType(1) << -Scale;
176 /// \brief The log base 2, rounded.
178 /// Get the lg of the scalar. lg 0 is defined to be INT32_MIN.
179 int32_t lg() const { return ScaledNumbers::getLg(Digits, Scale); }
181 /// \brief The log base 2, rounded towards INT32_MIN.
183 /// Get the lg floor. lg 0 is defined to be INT32_MIN.
184 int32_t lgFloor() const { return ScaledNumbers::getLgFloor(Digits, Scale); }
186 /// \brief The log base 2, rounded towards INT32_MAX.
188 /// Get the lg ceiling. lg 0 is defined to be INT32_MIN.
189 int32_t lgCeiling() const {
190 return ScaledNumbers::getLgCeiling(Digits, Scale);
193 bool operator==(const ScaledNumber &X) const { return compare(X) == 0; }
194 bool operator<(const ScaledNumber &X) const { return compare(X) < 0; }
195 bool operator!=(const ScaledNumber &X) const { return compare(X) != 0; }
196 bool operator>(const ScaledNumber &X) const { return compare(X) > 0; }
197 bool operator<=(const ScaledNumber &X) const { return compare(X) <= 0; }
198 bool operator>=(const ScaledNumber &X) const { return compare(X) >= 0; }
200 bool operator!() const { return isZero(); }
202 /// \brief Convert to a decimal representation in a string.
204 /// Convert to a string. Uses scientific notation for very large/small
205 /// numbers. Scientific notation is used roughly for numbers outside of the
206 /// range 2^-64 through 2^64.
208 /// \c Precision indicates the number of decimal digits of precision to use;
209 /// 0 requests the maximum available.
211 /// As a special case to make debugging easier, if the number is small enough
212 /// to convert without scientific notation and has more than \c Precision
213 /// digits before the decimal place, it's printed accurately to the first
214 /// digit past zero. E.g., assuming 10 digits of precision:
216 /// 98765432198.7654... => 98765432198.8
217 /// 8765432198.7654... => 8765432198.8
218 /// 765432198.7654... => 765432198.8
219 /// 65432198.7654... => 65432198.77
220 /// 5432198.7654... => 5432198.765
221 std::string toString(unsigned Precision = DefaultPrecision) {
222 return ScaledNumberBase::toString(Digits, Scale, Width, Precision);
225 /// \brief Print a decimal representation.
227 /// Print a string. See toString for documentation.
228 raw_ostream &print(raw_ostream &OS,
229 unsigned Precision = DefaultPrecision) const {
230 return ScaledNumberBase::print(OS, Digits, Scale, Width, Precision);
232 void dump() const { return ScaledNumberBase::dump(Digits, Scale, Width); }
234 ScaledNumber &operator+=(const ScaledNumber &X) {
235 std::tie(Digits, Scale) =
236 ScaledNumbers::getSum(Digits, Scale, X.Digits, X.Scale);
237 // Check for exponent past MaxScale.
238 if (Scale > MaxScale)
239 *this = getLargest();
242 ScaledNumber &operator-=(const ScaledNumber &X) {
243 std::tie(Digits, Scale) =
244 ScaledNumbers::getDifference(Digits, Scale, X.Digits, X.Scale);
247 ScaledNumber &operator*=(const ScaledNumber &X);
248 ScaledNumber &operator/=(const ScaledNumber &X);
249 ScaledNumber &operator<<=(int16_t Shift) {
253 ScaledNumber &operator>>=(int16_t Shift) {
259 void shiftLeft(int32_t Shift);
260 void shiftRight(int32_t Shift);
262 /// \brief Adjust two floats to have matching exponents.
264 /// Adjust \c this and \c X to have matching exponents. Returns the new \c X
265 /// by value. Does nothing if \a isZero() for either.
267 /// The value that compares smaller will lose precision, and possibly become
269 ScaledNumber matchScales(ScaledNumber X) {
270 ScaledNumbers::matchScales(Digits, Scale, X.Digits, X.Scale);
275 /// \brief Scale a large number accurately.
277 /// Scale N (multiply it by this). Uses full precision multiplication, even
278 /// if Width is smaller than 64, so information is not lost.
279 uint64_t scale(uint64_t N) const;
280 uint64_t scaleByInverse(uint64_t N) const {
281 // TODO: implement directly, rather than relying on inverse. Inverse is
283 return inverse().scale(N);
285 int64_t scale(int64_t N) const {
286 std::pair<uint64_t, bool> Unsigned = splitSigned(N);
287 return joinSigned(scale(Unsigned.first), Unsigned.second);
289 int64_t scaleByInverse(int64_t N) const {
290 std::pair<uint64_t, bool> Unsigned = splitSigned(N);
291 return joinSigned(scaleByInverse(Unsigned.first), Unsigned.second);
294 int compare(const ScaledNumber &X) const {
295 return ScaledNumbers::compare(Digits, Scale, X.Digits, X.Scale);
297 int compareTo(uint64_t N) const {
298 ScaledNumber Float = getFloat(N);
299 int Compare = compare(Float);
300 if (Width == 64 || Compare != 0)
303 // Check for precision loss. We know *this == RoundTrip.
304 uint64_t RoundTrip = Float.template toInt<uint64_t>();
305 return N == RoundTrip ? 0 : RoundTrip < N ? -1 : 1;
307 int compareTo(int64_t N) const { return N < 0 ? 1 : compareTo(uint64_t(N)); }
309 ScaledNumber &invert() { return *this = ScaledNumber::getFloat(1) / *this; }
310 ScaledNumber inverse() const { return ScaledNumber(*this).invert(); }
313 static ScaledNumber getProduct(DigitsType LHS, DigitsType RHS) {
314 return ScaledNumbers::getProduct(LHS, RHS);
316 static ScaledNumber getQuotient(DigitsType Dividend, DigitsType Divisor) {
317 return ScaledNumbers::getQuotient(Dividend, Divisor);
320 static int countLeadingZerosWidth(DigitsType Digits) {
322 return countLeadingZeros64(Digits);
324 return countLeadingZeros32(Digits);
325 return countLeadingZeros32(Digits) + Width - 32;
328 /// \brief Adjust a number to width, rounding up if necessary.
330 /// Should only be called for \c Shift close to zero.
332 /// \pre Shift >= MinScale && Shift + 64 <= MaxScale.
333 static ScaledNumber adjustToWidth(uint64_t N, int32_t Shift) {
334 assert(Shift >= MinScale && "Shift should be close to 0");
335 assert(Shift <= MaxScale - 64 && "Shift should be close to 0");
336 auto Adjusted = ScaledNumbers::getAdjusted<DigitsT>(N, Shift);
340 static ScaledNumber getRounded(ScaledNumber P, bool Round) {
345 return ScaledNumbers::getRounded(P.Digits, P.Scale, Round);
349 #define SCALED_NUMBER_BOP(op, base) \
350 template <class DigitsT> \
351 ScaledNumber<DigitsT> operator op(const ScaledNumber<DigitsT> &L, \
352 const ScaledNumber<DigitsT> &R) { \
353 return ScaledNumber<DigitsT>(L) base R; \
355 SCALED_NUMBER_BOP(+, += )
356 SCALED_NUMBER_BOP(-, -= )
357 SCALED_NUMBER_BOP(*, *= )
358 SCALED_NUMBER_BOP(/, /= )
359 SCALED_NUMBER_BOP(<<, <<= )
360 SCALED_NUMBER_BOP(>>, >>= )
361 #undef SCALED_NUMBER_BOP
363 template <class DigitsT>
364 raw_ostream &operator<<(raw_ostream &OS, const ScaledNumber<DigitsT> &X) {
365 return X.print(OS, 10);
368 #define SCALED_NUMBER_COMPARE_TO_TYPE(op, T1, T2) \
369 template <class DigitsT> \
370 bool operator op(const ScaledNumber<DigitsT> &L, T1 R) { \
371 return L.compareTo(T2(R)) op 0; \
373 template <class DigitsT> \
374 bool operator op(T1 L, const ScaledNumber<DigitsT> &R) { \
375 return 0 op R.compareTo(T2(L)); \
377 #define SCALED_NUMBER_COMPARE_TO(op) \
378 SCALED_NUMBER_COMPARE_TO_TYPE(op, uint64_t, uint64_t) \
379 SCALED_NUMBER_COMPARE_TO_TYPE(op, uint32_t, uint64_t) \
380 SCALED_NUMBER_COMPARE_TO_TYPE(op, int64_t, int64_t) \
381 SCALED_NUMBER_COMPARE_TO_TYPE(op, int32_t, int64_t)
382 SCALED_NUMBER_COMPARE_TO(< )
383 SCALED_NUMBER_COMPARE_TO(> )
384 SCALED_NUMBER_COMPARE_TO(== )
385 SCALED_NUMBER_COMPARE_TO(!= )
386 SCALED_NUMBER_COMPARE_TO(<= )
387 SCALED_NUMBER_COMPARE_TO(>= )
388 #undef SCALED_NUMBER_COMPARE_TO
389 #undef SCALED_NUMBER_COMPARE_TO_TYPE
391 template <class DigitsT>
392 uint64_t ScaledNumber<DigitsT>::scale(uint64_t N) const {
393 if (Width == 64 || N <= DigitsLimits::max())
394 return (getFloat(N) * *this).template toInt<uint64_t>();
396 // Defer to the 64-bit version.
397 return ScaledNumber<uint64_t>(Digits, Scale).scale(N);
400 template <class DigitsT>
401 template <class IntT>
402 IntT ScaledNumber<DigitsT>::toInt() const {
403 typedef std::numeric_limits<IntT> Limits;
406 if (*this >= Limits::max())
407 return Limits::max();
411 assert(size_t(Scale) < sizeof(IntT) * 8);
415 assert(size_t(-Scale) < sizeof(IntT) * 8);
421 template <class DigitsT>
422 ScaledNumber<DigitsT> &ScaledNumber<DigitsT>::
423 operator*=(const ScaledNumber &X) {
429 // Save the exponents.
430 int32_t Scales = int32_t(Scale) + int32_t(X.Scale);
432 // Get the raw product.
433 *this = getProduct(Digits, X.Digits);
435 // Combine with exponents.
436 return *this <<= Scales;
438 template <class DigitsT>
439 ScaledNumber<DigitsT> &ScaledNumber<DigitsT>::
440 operator/=(const ScaledNumber &X) {
444 return *this = getLargest();
446 // Save the exponents.
447 int32_t Scales = int32_t(Scale) - int32_t(X.Scale);
449 // Get the raw quotient.
450 *this = getQuotient(Digits, X.Digits);
452 // Combine with exponents.
453 return *this <<= Scales;
455 template <class DigitsT> void ScaledNumber<DigitsT>::shiftLeft(int32_t Shift) {
456 if (!Shift || isZero())
458 assert(Shift != INT32_MIN);
464 // Shift as much as we can in the exponent.
465 int32_t ScaleShift = std::min(Shift, MaxScale - Scale);
467 if (ScaleShift == Shift)
470 // Check this late, since it's rare.
474 // Shift the digits themselves.
476 if (Shift > countLeadingZerosWidth(Digits)) {
478 *this = getLargest();
486 template <class DigitsT> void ScaledNumber<DigitsT>::shiftRight(int32_t Shift) {
487 if (!Shift || isZero())
489 assert(Shift != INT32_MIN);
495 // Shift as much as we can in the exponent.
496 int32_t ScaleShift = std::min(Shift, Scale - MinScale);
498 if (ScaleShift == Shift)
501 // Shift the digits themselves.
503 if (Shift >= Width) {
513 template <class T> struct isPodLike<ScaledNumber<T>> {
514 static const bool value = true;
518 //===----------------------------------------------------------------------===//
520 // BlockMass definition.
522 // TODO: Make this private to BlockFrequencyInfoImpl or delete.
524 //===----------------------------------------------------------------------===//
527 /// \brief Mass of a block.
529 /// This class implements a sort of fixed-point fraction always between 0.0 and
530 /// 1.0. getMass() == UINT64_MAX indicates a value of 1.0.
532 /// Masses can be added and subtracted. Simple saturation arithmetic is used,
533 /// so arithmetic operations never overflow or underflow.
535 /// Masses can be multiplied. Multiplication treats full mass as 1.0 and uses
536 /// an inexpensive floating-point algorithm that's off-by-one (almost, but not
537 /// quite, maximum precision).
539 /// Masses can be scaled by \a BranchProbability at maximum precision.
544 BlockMass() : Mass(0) {}
545 explicit BlockMass(uint64_t Mass) : Mass(Mass) {}
547 static BlockMass getEmpty() { return BlockMass(); }
548 static BlockMass getFull() { return BlockMass(UINT64_MAX); }
550 uint64_t getMass() const { return Mass; }
552 bool isFull() const { return Mass == UINT64_MAX; }
553 bool isEmpty() const { return !Mass; }
555 bool operator!() const { return isEmpty(); }
557 /// \brief Add another mass.
559 /// Adds another mass, saturating at \a isFull() rather than overflowing.
560 BlockMass &operator+=(const BlockMass &X) {
561 uint64_t Sum = Mass + X.Mass;
562 Mass = Sum < Mass ? UINT64_MAX : Sum;
566 /// \brief Subtract another mass.
568 /// Subtracts another mass, saturating at \a isEmpty() rather than
570 BlockMass &operator-=(const BlockMass &X) {
571 uint64_t Diff = Mass - X.Mass;
572 Mass = Diff > Mass ? 0 : Diff;
576 BlockMass &operator*=(const BranchProbability &P) {
577 Mass = P.scale(Mass);
581 bool operator==(const BlockMass &X) const { return Mass == X.Mass; }
582 bool operator!=(const BlockMass &X) const { return Mass != X.Mass; }
583 bool operator<=(const BlockMass &X) const { return Mass <= X.Mass; }
584 bool operator>=(const BlockMass &X) const { return Mass >= X.Mass; }
585 bool operator<(const BlockMass &X) const { return Mass < X.Mass; }
586 bool operator>(const BlockMass &X) const { return Mass > X.Mass; }
588 /// \brief Convert to floating point.
590 /// Convert to a float. \a isFull() gives 1.0, while \a isEmpty() gives
591 /// slightly above 0.0.
592 ScaledNumber<uint64_t> toFloat() const;
595 raw_ostream &print(raw_ostream &OS) const;
598 inline BlockMass operator+(const BlockMass &L, const BlockMass &R) {
599 return BlockMass(L) += R;
601 inline BlockMass operator-(const BlockMass &L, const BlockMass &R) {
602 return BlockMass(L) -= R;
604 inline BlockMass operator*(const BlockMass &L, const BranchProbability &R) {
605 return BlockMass(L) *= R;
607 inline BlockMass operator*(const BranchProbability &L, const BlockMass &R) {
608 return BlockMass(R) *= L;
611 inline raw_ostream &operator<<(raw_ostream &OS, const BlockMass &X) {
615 template <> struct isPodLike<BlockMass> {
616 static const bool value = true;
620 //===----------------------------------------------------------------------===//
622 // BlockFrequencyInfoImpl definition.
624 //===----------------------------------------------------------------------===//
628 class BranchProbabilityInfo;
632 class MachineBasicBlock;
633 class MachineBranchProbabilityInfo;
634 class MachineFunction;
636 class MachineLoopInfo;
638 namespace bfi_detail {
639 struct IrreducibleGraph;
641 // This is part of a workaround for a GCC 4.7 crash on lambdas.
642 template <class BT> struct BlockEdgesAdder;
645 /// \brief Base class for BlockFrequencyInfoImpl
647 /// BlockFrequencyInfoImplBase has supporting data structures and some
648 /// algorithms for BlockFrequencyInfoImplBase. Only algorithms that depend on
649 /// the block type (or that call such algorithms) are skipped here.
651 /// Nevertheless, the majority of the overall algorithm documention lives with
652 /// BlockFrequencyInfoImpl. See there for details.
653 class BlockFrequencyInfoImplBase {
655 typedef ScaledNumber<uint64_t> Float;
657 /// \brief Representative of a block.
659 /// This is a simple wrapper around an index into the reverse-post-order
660 /// traversal of the blocks.
662 /// Unlike a block pointer, its order has meaning (location in the
663 /// topological sort) and it's class is the same regardless of block type.
665 typedef uint32_t IndexType;
668 bool operator==(const BlockNode &X) const { return Index == X.Index; }
669 bool operator!=(const BlockNode &X) const { return Index != X.Index; }
670 bool operator<=(const BlockNode &X) const { return Index <= X.Index; }
671 bool operator>=(const BlockNode &X) const { return Index >= X.Index; }
672 bool operator<(const BlockNode &X) const { return Index < X.Index; }
673 bool operator>(const BlockNode &X) const { return Index > X.Index; }
675 BlockNode() : Index(UINT32_MAX) {}
676 BlockNode(IndexType Index) : Index(Index) {}
678 bool isValid() const { return Index <= getMaxIndex(); }
679 static size_t getMaxIndex() { return UINT32_MAX - 1; }
682 /// \brief Stats about a block itself.
683 struct FrequencyData {
688 /// \brief Data about a loop.
690 /// Contains the data necessary to represent represent a loop as a
691 /// pseudo-node once it's packaged.
693 typedef SmallVector<std::pair<BlockNode, BlockMass>, 4> ExitMap;
694 typedef SmallVector<BlockNode, 4> NodeList;
695 LoopData *Parent; ///< The parent loop.
696 bool IsPackaged; ///< Whether this has been packaged.
697 uint32_t NumHeaders; ///< Number of headers.
698 ExitMap Exits; ///< Successor edges (and weights).
699 NodeList Nodes; ///< Header and the members of the loop.
700 BlockMass BackedgeMass; ///< Mass returned to loop header.
704 LoopData(LoopData *Parent, const BlockNode &Header)
705 : Parent(Parent), IsPackaged(false), NumHeaders(1), Nodes(1, Header) {}
706 template <class It1, class It2>
707 LoopData(LoopData *Parent, It1 FirstHeader, It1 LastHeader, It2 FirstOther,
709 : Parent(Parent), IsPackaged(false), Nodes(FirstHeader, LastHeader) {
710 NumHeaders = Nodes.size();
711 Nodes.insert(Nodes.end(), FirstOther, LastOther);
713 bool isHeader(const BlockNode &Node) const {
715 return std::binary_search(Nodes.begin(), Nodes.begin() + NumHeaders,
717 return Node == Nodes[0];
719 BlockNode getHeader() const { return Nodes[0]; }
720 bool isIrreducible() const { return NumHeaders > 1; }
722 NodeList::const_iterator members_begin() const {
723 return Nodes.begin() + NumHeaders;
725 NodeList::const_iterator members_end() const { return Nodes.end(); }
726 iterator_range<NodeList::const_iterator> members() const {
727 return make_range(members_begin(), members_end());
731 /// \brief Index of loop information.
733 BlockNode Node; ///< This node.
734 LoopData *Loop; ///< The loop this block is inside.
735 BlockMass Mass; ///< Mass distribution from the entry block.
737 WorkingData(const BlockNode &Node) : Node(Node), Loop(nullptr) {}
739 bool isLoopHeader() const { return Loop && Loop->isHeader(Node); }
740 bool isDoubleLoopHeader() const {
741 return isLoopHeader() && Loop->Parent && Loop->Parent->isIrreducible() &&
742 Loop->Parent->isHeader(Node);
745 LoopData *getContainingLoop() const {
748 if (!isDoubleLoopHeader())
750 return Loop->Parent->Parent;
753 /// \brief Resolve a node to its representative.
755 /// Get the node currently representing Node, which could be a containing
758 /// This function should only be called when distributing mass. As long as
759 /// there are no irreducilbe edges to Node, then it will have complexity
760 /// O(1) in this context.
762 /// In general, the complexity is O(L), where L is the number of loop
763 /// headers Node has been packaged into. Since this method is called in
764 /// the context of distributing mass, L will be the number of loop headers
765 /// an early exit edge jumps out of.
766 BlockNode getResolvedNode() const {
767 auto L = getPackagedLoop();
768 return L ? L->getHeader() : Node;
770 LoopData *getPackagedLoop() const {
771 if (!Loop || !Loop->IsPackaged)
774 while (L->Parent && L->Parent->IsPackaged)
779 /// \brief Get the appropriate mass for a node.
781 /// Get appropriate mass for Node. If Node is a loop-header (whose loop
782 /// has been packaged), returns the mass of its pseudo-node. If it's a
783 /// node inside a packaged loop, it returns the loop's mass.
784 BlockMass &getMass() {
787 if (!isADoublePackage())
789 return Loop->Parent->Mass;
792 /// \brief Has ContainingLoop been packaged up?
793 bool isPackaged() const { return getResolvedNode() != Node; }
794 /// \brief Has Loop been packaged up?
795 bool isAPackage() const { return isLoopHeader() && Loop->IsPackaged; }
796 /// \brief Has Loop been packaged up twice?
797 bool isADoublePackage() const {
798 return isDoubleLoopHeader() && Loop->Parent->IsPackaged;
802 /// \brief Unscaled probability weight.
804 /// Probability weight for an edge in the graph (including the
805 /// successor/target node).
807 /// All edges in the original function are 32-bit. However, exit edges from
808 /// loop packages are taken from 64-bit exit masses, so we need 64-bits of
809 /// space in general.
811 /// In addition to the raw weight amount, Weight stores the type of the edge
812 /// in the current context (i.e., the context of the loop being processed).
813 /// Is this a local edge within the loop, an exit from the loop, or a
814 /// backedge to the loop header?
816 enum DistType { Local, Exit, Backedge };
818 BlockNode TargetNode;
820 Weight() : Type(Local), Amount(0) {}
823 /// \brief Distribution of unscaled probability weight.
825 /// Distribution of unscaled probability weight to a set of successors.
827 /// This class collates the successor edge weights for later processing.
829 /// \a DidOverflow indicates whether \a Total did overflow while adding to
830 /// the distribution. It should never overflow twice.
831 struct Distribution {
832 typedef SmallVector<Weight, 4> WeightList;
833 WeightList Weights; ///< Individual successor weights.
834 uint64_t Total; ///< Sum of all weights.
835 bool DidOverflow; ///< Whether \a Total did overflow.
837 Distribution() : Total(0), DidOverflow(false) {}
838 void addLocal(const BlockNode &Node, uint64_t Amount) {
839 add(Node, Amount, Weight::Local);
841 void addExit(const BlockNode &Node, uint64_t Amount) {
842 add(Node, Amount, Weight::Exit);
844 void addBackedge(const BlockNode &Node, uint64_t Amount) {
845 add(Node, Amount, Weight::Backedge);
848 /// \brief Normalize the distribution.
850 /// Combines multiple edges to the same \a Weight::TargetNode and scales
851 /// down so that \a Total fits into 32-bits.
853 /// This is linear in the size of \a Weights. For the vast majority of
854 /// cases, adjacent edge weights are combined by sorting WeightList and
855 /// combining adjacent weights. However, for very large edge lists an
856 /// auxiliary hash table is used.
860 void add(const BlockNode &Node, uint64_t Amount, Weight::DistType Type);
863 /// \brief Data about each block. This is used downstream.
864 std::vector<FrequencyData> Freqs;
866 /// \brief Loop data: see initializeLoops().
867 std::vector<WorkingData> Working;
869 /// \brief Indexed information about loops.
870 std::list<LoopData> Loops;
872 /// \brief Add all edges out of a packaged loop to the distribution.
874 /// Adds all edges from LocalLoopHead to Dist. Calls addToDist() to add each
877 /// \return \c true unless there's an irreducible backedge.
878 bool addLoopSuccessorsToDist(const LoopData *OuterLoop, LoopData &Loop,
881 /// \brief Add an edge to the distribution.
883 /// Adds an edge to Succ to Dist. If \c LoopHead.isValid(), then whether the
884 /// edge is local/exit/backedge is in the context of LoopHead. Otherwise,
885 /// every edge should be a local edge (since all the loops are packaged up).
887 /// \return \c true unless aborted due to an irreducible backedge.
888 bool addToDist(Distribution &Dist, const LoopData *OuterLoop,
889 const BlockNode &Pred, const BlockNode &Succ, uint64_t Weight);
891 LoopData &getLoopPackage(const BlockNode &Head) {
892 assert(Head.Index < Working.size());
893 assert(Working[Head.Index].isLoopHeader());
894 return *Working[Head.Index].Loop;
897 /// \brief Analyze irreducible SCCs.
899 /// Separate irreducible SCCs from \c G, which is an explict graph of \c
900 /// OuterLoop (or the top-level function, if \c OuterLoop is \c nullptr).
901 /// Insert them into \a Loops before \c Insert.
903 /// \return the \c LoopData nodes representing the irreducible SCCs.
904 iterator_range<std::list<LoopData>::iterator>
905 analyzeIrreducible(const bfi_detail::IrreducibleGraph &G, LoopData *OuterLoop,
906 std::list<LoopData>::iterator Insert);
908 /// \brief Update a loop after packaging irreducible SCCs inside of it.
910 /// Update \c OuterLoop. Before finding irreducible control flow, it was
911 /// partway through \a computeMassInLoop(), so \a LoopData::Exits and \a
912 /// LoopData::BackedgeMass need to be reset. Also, nodes that were packaged
913 /// up need to be removed from \a OuterLoop::Nodes.
914 void updateLoopWithIrreducible(LoopData &OuterLoop);
916 /// \brief Distribute mass according to a distribution.
918 /// Distributes the mass in Source according to Dist. If LoopHead.isValid(),
919 /// backedges and exits are stored in its entry in Loops.
921 /// Mass is distributed in parallel from two copies of the source mass.
922 void distributeMass(const BlockNode &Source, LoopData *OuterLoop,
925 /// \brief Compute the loop scale for a loop.
926 void computeLoopScale(LoopData &Loop);
928 /// \brief Package up a loop.
929 void packageLoop(LoopData &Loop);
931 /// \brief Unwrap loops.
934 /// \brief Finalize frequency metrics.
936 /// Calculates final frequencies and cleans up no-longer-needed data
938 void finalizeMetrics();
940 /// \brief Clear all memory.
943 virtual std::string getBlockName(const BlockNode &Node) const;
944 std::string getLoopName(const LoopData &Loop) const;
946 virtual raw_ostream &print(raw_ostream &OS) const { return OS; }
947 void dump() const { print(dbgs()); }
949 Float getFloatingBlockFreq(const BlockNode &Node) const;
951 BlockFrequency getBlockFreq(const BlockNode &Node) const;
953 raw_ostream &printBlockFreq(raw_ostream &OS, const BlockNode &Node) const;
954 raw_ostream &printBlockFreq(raw_ostream &OS,
955 const BlockFrequency &Freq) const;
957 uint64_t getEntryFreq() const {
958 assert(!Freqs.empty());
959 return Freqs[0].Integer;
961 /// \brief Virtual destructor.
963 /// Need a virtual destructor to mask the compiler warning about
965 virtual ~BlockFrequencyInfoImplBase() {}
968 namespace bfi_detail {
969 template <class BlockT> struct TypeMap {};
970 template <> struct TypeMap<BasicBlock> {
971 typedef BasicBlock BlockT;
972 typedef Function FunctionT;
973 typedef BranchProbabilityInfo BranchProbabilityInfoT;
975 typedef LoopInfo LoopInfoT;
977 template <> struct TypeMap<MachineBasicBlock> {
978 typedef MachineBasicBlock BlockT;
979 typedef MachineFunction FunctionT;
980 typedef MachineBranchProbabilityInfo BranchProbabilityInfoT;
981 typedef MachineLoop LoopT;
982 typedef MachineLoopInfo LoopInfoT;
985 /// \brief Get the name of a MachineBasicBlock.
987 /// Get the name of a MachineBasicBlock. It's templated so that including from
988 /// CodeGen is unnecessary (that would be a layering issue).
990 /// This is used mainly for debug output. The name is similar to
991 /// MachineBasicBlock::getFullName(), but skips the name of the function.
992 template <class BlockT> std::string getBlockName(const BlockT *BB) {
993 assert(BB && "Unexpected nullptr");
994 auto MachineName = "BB" + Twine(BB->getNumber());
995 if (BB->getBasicBlock())
996 return (MachineName + "[" + BB->getName() + "]").str();
997 return MachineName.str();
999 /// \brief Get the name of a BasicBlock.
1000 template <> inline std::string getBlockName(const BasicBlock *BB) {
1001 assert(BB && "Unexpected nullptr");
1002 return BB->getName().str();
1005 /// \brief Graph of irreducible control flow.
1007 /// This graph is used for determining the SCCs in a loop (or top-level
1008 /// function) that has irreducible control flow.
1010 /// During the block frequency algorithm, the local graphs are defined in a
1011 /// light-weight way, deferring to the \a BasicBlock or \a MachineBasicBlock
1012 /// graphs for most edges, but getting others from \a LoopData::ExitMap. The
1013 /// latter only has successor information.
1015 /// \a IrreducibleGraph makes this graph explicit. It's in a form that can use
1016 /// \a GraphTraits (so that \a analyzeIrreducible() can use \a scc_iterator),
1017 /// and it explicitly lists predecessors and successors. The initialization
1018 /// that relies on \c MachineBasicBlock is defined in the header.
1019 struct IrreducibleGraph {
1020 typedef BlockFrequencyInfoImplBase BFIBase;
1024 typedef BFIBase::BlockNode BlockNode;
1028 std::deque<const IrrNode *> Edges;
1029 IrrNode(const BlockNode &Node) : Node(Node), NumIn(0) {}
1031 typedef std::deque<const IrrNode *>::const_iterator iterator;
1032 iterator pred_begin() const { return Edges.begin(); }
1033 iterator succ_begin() const { return Edges.begin() + NumIn; }
1034 iterator pred_end() const { return succ_begin(); }
1035 iterator succ_end() const { return Edges.end(); }
1038 const IrrNode *StartIrr;
1039 std::vector<IrrNode> Nodes;
1040 SmallDenseMap<uint32_t, IrrNode *, 4> Lookup;
1042 /// \brief Construct an explicit graph containing irreducible control flow.
1044 /// Construct an explicit graph of the control flow in \c OuterLoop (or the
1045 /// top-level function, if \c OuterLoop is \c nullptr). Uses \c
1046 /// addBlockEdges to add block successors that have not been packaged into
1049 /// \a BlockFrequencyInfoImpl::computeIrreducibleMass() is the only expected
1051 template <class BlockEdgesAdder>
1052 IrreducibleGraph(BFIBase &BFI, const BFIBase::LoopData *OuterLoop,
1053 BlockEdgesAdder addBlockEdges)
1054 : BFI(BFI), StartIrr(nullptr) {
1055 initialize(OuterLoop, addBlockEdges);
1058 template <class BlockEdgesAdder>
1059 void initialize(const BFIBase::LoopData *OuterLoop,
1060 BlockEdgesAdder addBlockEdges);
1061 void addNodesInLoop(const BFIBase::LoopData &OuterLoop);
1062 void addNodesInFunction();
1063 void addNode(const BlockNode &Node) {
1064 Nodes.emplace_back(Node);
1065 BFI.Working[Node.Index].getMass() = BlockMass::getEmpty();
1068 template <class BlockEdgesAdder>
1069 void addEdges(const BlockNode &Node, const BFIBase::LoopData *OuterLoop,
1070 BlockEdgesAdder addBlockEdges);
1071 void addEdge(IrrNode &Irr, const BlockNode &Succ,
1072 const BFIBase::LoopData *OuterLoop);
1074 template <class BlockEdgesAdder>
1075 void IrreducibleGraph::initialize(const BFIBase::LoopData *OuterLoop,
1076 BlockEdgesAdder addBlockEdges) {
1078 addNodesInLoop(*OuterLoop);
1079 for (auto N : OuterLoop->Nodes)
1080 addEdges(N, OuterLoop, addBlockEdges);
1082 addNodesInFunction();
1083 for (uint32_t Index = 0; Index < BFI.Working.size(); ++Index)
1084 addEdges(Index, OuterLoop, addBlockEdges);
1086 StartIrr = Lookup[Start.Index];
1088 template <class BlockEdgesAdder>
1089 void IrreducibleGraph::addEdges(const BlockNode &Node,
1090 const BFIBase::LoopData *OuterLoop,
1091 BlockEdgesAdder addBlockEdges) {
1092 auto L = Lookup.find(Node.Index);
1093 if (L == Lookup.end())
1095 IrrNode &Irr = *L->second;
1096 const auto &Working = BFI.Working[Node.Index];
1098 if (Working.isAPackage())
1099 for (const auto &I : Working.Loop->Exits)
1100 addEdge(Irr, I.first, OuterLoop);
1102 addBlockEdges(*this, Irr, OuterLoop);
1106 /// \brief Shared implementation for block frequency analysis.
1108 /// This is a shared implementation of BlockFrequencyInfo and
1109 /// MachineBlockFrequencyInfo, and calculates the relative frequencies of
1112 /// LoopInfo defines a loop as a "non-trivial" SCC dominated by a single block,
1113 /// which is called the header. A given loop, L, can have sub-loops, which are
1114 /// loops within the subgraph of L that exclude its header. (A "trivial" SCC
1115 /// consists of a single block that does not have a self-edge.)
1117 /// In addition to loops, this algorithm has limited support for irreducible
1118 /// SCCs, which are SCCs with multiple entry blocks. Irreducible SCCs are
1119 /// discovered on they fly, and modelled as loops with multiple headers.
1121 /// The headers of irreducible sub-SCCs consist of its entry blocks and all
1122 /// nodes that are targets of a backedge within it (excluding backedges within
1123 /// true sub-loops). Block frequency calculations act as if a block is
1124 /// inserted that intercepts all the edges to the headers. All backedges and
1125 /// entries point to this block. Its successors are the headers, which split
1126 /// the frequency evenly.
1128 /// This algorithm leverages BlockMass and ScaledNumber to maintain precision,
1129 /// separates mass distribution from loop scaling, and dithers to eliminate
1130 /// probability mass loss.
1132 /// The implementation is split between BlockFrequencyInfoImpl, which knows the
1133 /// type of graph being modelled (BasicBlock vs. MachineBasicBlock), and
1134 /// BlockFrequencyInfoImplBase, which doesn't. The base class uses \a
1135 /// BlockNode, a wrapper around a uint32_t. BlockNode is numbered from 0 in
1136 /// reverse-post order. This gives two advantages: it's easy to compare the
1137 /// relative ordering of two nodes, and maps keyed on BlockT can be represented
1140 /// This algorithm is O(V+E), unless there is irreducible control flow, in
1141 /// which case it's O(V*E) in the worst case.
1143 /// These are the main stages:
1145 /// 0. Reverse post-order traversal (\a initializeRPOT()).
1147 /// Run a single post-order traversal and save it (in reverse) in RPOT.
1148 /// All other stages make use of this ordering. Save a lookup from BlockT
1149 /// to BlockNode (the index into RPOT) in Nodes.
1151 /// 1. Loop initialization (\a initializeLoops()).
1153 /// Translate LoopInfo/MachineLoopInfo into a form suitable for the rest of
1154 /// the algorithm. In particular, store the immediate members of each loop
1155 /// in reverse post-order.
1157 /// 2. Calculate mass and scale in loops (\a computeMassInLoops()).
1159 /// For each loop (bottom-up), distribute mass through the DAG resulting
1160 /// from ignoring backedges and treating sub-loops as a single pseudo-node.
1161 /// Track the backedge mass distributed to the loop header, and use it to
1162 /// calculate the loop scale (number of loop iterations). Immediate
1163 /// members that represent sub-loops will already have been visited and
1164 /// packaged into a pseudo-node.
1166 /// Distributing mass in a loop is a reverse-post-order traversal through
1167 /// the loop. Start by assigning full mass to the Loop header. For each
1168 /// node in the loop:
1170 /// - Fetch and categorize the weight distribution for its successors.
1171 /// If this is a packaged-subloop, the weight distribution is stored
1172 /// in \a LoopData::Exits. Otherwise, fetch it from
1173 /// BranchProbabilityInfo.
1175 /// - Each successor is categorized as \a Weight::Local, a local edge
1176 /// within the current loop, \a Weight::Backedge, a backedge to the
1177 /// loop header, or \a Weight::Exit, any successor outside the loop.
1178 /// The weight, the successor, and its category are stored in \a
1179 /// Distribution. There can be multiple edges to each successor.
1181 /// - If there's a backedge to a non-header, there's an irreducible SCC.
1182 /// The usual flow is temporarily aborted. \a
1183 /// computeIrreducibleMass() finds the irreducible SCCs within the
1184 /// loop, packages them up, and restarts the flow.
1186 /// - Normalize the distribution: scale weights down so that their sum
1187 /// is 32-bits, and coalesce multiple edges to the same node.
1189 /// - Distribute the mass accordingly, dithering to minimize mass loss,
1190 /// as described in \a distributeMass().
1192 /// Finally, calculate the loop scale from the accumulated backedge mass.
1194 /// 3. Distribute mass in the function (\a computeMassInFunction()).
1196 /// Finally, distribute mass through the DAG resulting from packaging all
1197 /// loops in the function. This uses the same algorithm as distributing
1198 /// mass in a loop, except that there are no exit or backedge edges.
1200 /// 4. Unpackage loops (\a unwrapLoops()).
1202 /// Initialize each block's frequency to a floating point representation of
1205 /// Visit loops top-down, scaling the frequencies of its immediate members
1206 /// by the loop's pseudo-node's frequency.
1208 /// 5. Convert frequencies to a 64-bit range (\a finalizeMetrics()).
1210 /// Using the min and max frequencies as a guide, translate floating point
1211 /// frequencies to an appropriate range in uint64_t.
1213 /// It has some known flaws.
1215 /// - Loop scale is limited to 4096 per loop (2^12) to avoid exhausting
1216 /// BlockFrequency's 64-bit integer precision.
1218 /// - The model of irreducible control flow is a rough approximation.
1220 /// Modelling irreducible control flow exactly involves setting up and
1221 /// solving a group of infinite geometric series. Such precision is
1222 /// unlikely to be worthwhile, since most of our algorithms give up on
1223 /// irreducible control flow anyway.
1225 /// Nevertheless, we might find that we need to get closer. Here's a sort
1226 /// of TODO list for the model with diminishing returns, to be completed as
1229 /// - The headers for the \a LoopData representing an irreducible SCC
1230 /// include non-entry blocks. When these extra blocks exist, they
1231 /// indicate a self-contained irreducible sub-SCC. We could treat them
1232 /// as sub-loops, rather than arbitrarily shoving the problematic
1233 /// blocks into the headers of the main irreducible SCC.
1235 /// - Backedge frequencies are assumed to be evenly split between the
1236 /// headers of a given irreducible SCC. Instead, we could track the
1237 /// backedge mass separately for each header, and adjust their relative
1240 /// - Entry frequencies are assumed to be evenly split between the
1241 /// headers of a given irreducible SCC, which is the only option if we
1242 /// need to compute mass in the SCC before its parent loop. Instead,
1243 /// we could partially compute mass in the parent loop, and stop when
1244 /// we get to the SCC. Here, we have the correct ratio of entry
1245 /// masses, which we can use to adjust their relative frequencies.
1246 /// Compute mass in the SCC, and then continue propagation in the
1249 /// - We can propagate mass iteratively through the SCC, for some fixed
1250 /// number of iterations. Each iteration starts by assigning the entry
1251 /// blocks their backedge mass from the prior iteration. The final
1252 /// mass for each block (and each exit, and the total backedge mass
1253 /// used for computing loop scale) is the sum of all iterations.
1254 /// (Running this until fixed point would "solve" the geometric
1255 /// series by simulation.)
1256 template <class BT> class BlockFrequencyInfoImpl : BlockFrequencyInfoImplBase {
1257 typedef typename bfi_detail::TypeMap<BT>::BlockT BlockT;
1258 typedef typename bfi_detail::TypeMap<BT>::FunctionT FunctionT;
1259 typedef typename bfi_detail::TypeMap<BT>::BranchProbabilityInfoT
1260 BranchProbabilityInfoT;
1261 typedef typename bfi_detail::TypeMap<BT>::LoopT LoopT;
1262 typedef typename bfi_detail::TypeMap<BT>::LoopInfoT LoopInfoT;
1264 // This is part of a workaround for a GCC 4.7 crash on lambdas.
1265 friend struct bfi_detail::BlockEdgesAdder<BT>;
1267 typedef GraphTraits<const BlockT *> Successor;
1268 typedef GraphTraits<Inverse<const BlockT *>> Predecessor;
1270 const BranchProbabilityInfoT *BPI;
1271 const LoopInfoT *LI;
1274 // All blocks in reverse postorder.
1275 std::vector<const BlockT *> RPOT;
1276 DenseMap<const BlockT *, BlockNode> Nodes;
1278 typedef typename std::vector<const BlockT *>::const_iterator rpot_iterator;
1280 rpot_iterator rpot_begin() const { return RPOT.begin(); }
1281 rpot_iterator rpot_end() const { return RPOT.end(); }
1283 size_t getIndex(const rpot_iterator &I) const { return I - rpot_begin(); }
1285 BlockNode getNode(const rpot_iterator &I) const {
1286 return BlockNode(getIndex(I));
1288 BlockNode getNode(const BlockT *BB) const { return Nodes.lookup(BB); }
1290 const BlockT *getBlock(const BlockNode &Node) const {
1291 assert(Node.Index < RPOT.size());
1292 return RPOT[Node.Index];
1295 /// \brief Run (and save) a post-order traversal.
1297 /// Saves a reverse post-order traversal of all the nodes in \a F.
1298 void initializeRPOT();
1300 /// \brief Initialize loop data.
1302 /// Build up \a Loops using \a LoopInfo. \a LoopInfo gives us a mapping from
1303 /// each block to the deepest loop it's in, but we need the inverse. For each
1304 /// loop, we store in reverse post-order its "immediate" members, defined as
1305 /// the header, the headers of immediate sub-loops, and all other blocks in
1306 /// the loop that are not in sub-loops.
1307 void initializeLoops();
1309 /// \brief Propagate to a block's successors.
1311 /// In the context of distributing mass through \c OuterLoop, divide the mass
1312 /// currently assigned to \c Node between its successors.
1314 /// \return \c true unless there's an irreducible backedge.
1315 bool propagateMassToSuccessors(LoopData *OuterLoop, const BlockNode &Node);
1317 /// \brief Compute mass in a particular loop.
1319 /// Assign mass to \c Loop's header, and then for each block in \c Loop in
1320 /// reverse post-order, distribute mass to its successors. Only visits nodes
1321 /// that have not been packaged into sub-loops.
1323 /// \pre \a computeMassInLoop() has been called for each subloop of \c Loop.
1324 /// \return \c true unless there's an irreducible backedge.
1325 bool computeMassInLoop(LoopData &Loop);
1327 /// \brief Try to compute mass in the top-level function.
1329 /// Assign mass to the entry block, and then for each block in reverse
1330 /// post-order, distribute mass to its successors. Skips nodes that have
1331 /// been packaged into loops.
1333 /// \pre \a computeMassInLoops() has been called.
1334 /// \return \c true unless there's an irreducible backedge.
1335 bool tryToComputeMassInFunction();
1337 /// \brief Compute mass in (and package up) irreducible SCCs.
1339 /// Find the irreducible SCCs in \c OuterLoop, add them to \a Loops (in front
1340 /// of \c Insert), and call \a computeMassInLoop() on each of them.
1342 /// If \c OuterLoop is \c nullptr, it refers to the top-level function.
1344 /// \pre \a computeMassInLoop() has been called for each subloop of \c
1346 /// \pre \c Insert points at the the last loop successfully processed by \a
1347 /// computeMassInLoop().
1348 /// \pre \c OuterLoop has irreducible SCCs.
1349 void computeIrreducibleMass(LoopData *OuterLoop,
1350 std::list<LoopData>::iterator Insert);
1352 /// \brief Compute mass in all loops.
1354 /// For each loop bottom-up, call \a computeMassInLoop().
1356 /// \a computeMassInLoop() aborts (and returns \c false) on loops that
1357 /// contain a irreducible sub-SCCs. Use \a computeIrreducibleMass() and then
1358 /// re-enter \a computeMassInLoop().
1360 /// \post \a computeMassInLoop() has returned \c true for every loop.
1361 void computeMassInLoops();
1363 /// \brief Compute mass in the top-level function.
1365 /// Uses \a tryToComputeMassInFunction() and \a computeIrreducibleMass() to
1366 /// compute mass in the top-level function.
1368 /// \post \a tryToComputeMassInFunction() has returned \c true.
1369 void computeMassInFunction();
1371 std::string getBlockName(const BlockNode &Node) const override {
1372 return bfi_detail::getBlockName(getBlock(Node));
1376 const FunctionT *getFunction() const { return F; }
1378 void doFunction(const FunctionT *F, const BranchProbabilityInfoT *BPI,
1379 const LoopInfoT *LI);
1380 BlockFrequencyInfoImpl() : BPI(nullptr), LI(nullptr), F(nullptr) {}
1382 using BlockFrequencyInfoImplBase::getEntryFreq;
1383 BlockFrequency getBlockFreq(const BlockT *BB) const {
1384 return BlockFrequencyInfoImplBase::getBlockFreq(getNode(BB));
1386 Float getFloatingBlockFreq(const BlockT *BB) const {
1387 return BlockFrequencyInfoImplBase::getFloatingBlockFreq(getNode(BB));
1390 /// \brief Print the frequencies for the current function.
1392 /// Prints the frequencies for the blocks in the current function.
1394 /// Blocks are printed in the natural iteration order of the function, rather
1395 /// than reverse post-order. This provides two advantages: writing -analyze
1396 /// tests is easier (since blocks come out in source order), and even
1397 /// unreachable blocks are printed.
1399 /// \a BlockFrequencyInfoImplBase::print() only knows reverse post-order, so
1400 /// we need to override it here.
1401 raw_ostream &print(raw_ostream &OS) const override;
1402 using BlockFrequencyInfoImplBase::dump;
1404 using BlockFrequencyInfoImplBase::printBlockFreq;
1405 raw_ostream &printBlockFreq(raw_ostream &OS, const BlockT *BB) const {
1406 return BlockFrequencyInfoImplBase::printBlockFreq(OS, getNode(BB));
1411 void BlockFrequencyInfoImpl<BT>::doFunction(const FunctionT *F,
1412 const BranchProbabilityInfoT *BPI,
1413 const LoopInfoT *LI) {
1414 // Save the parameters.
1419 // Clean up left-over data structures.
1420 BlockFrequencyInfoImplBase::clear();
1425 DEBUG(dbgs() << "\nblock-frequency: " << F->getName() << "\n================="
1426 << std::string(F->getName().size(), '=') << "\n");
1430 // Visit loops in post-order to find thelocal mass distribution, and then do
1431 // the full function.
1432 computeMassInLoops();
1433 computeMassInFunction();
1438 template <class BT> void BlockFrequencyInfoImpl<BT>::initializeRPOT() {
1439 const BlockT *Entry = F->begin();
1440 RPOT.reserve(F->size());
1441 std::copy(po_begin(Entry), po_end(Entry), std::back_inserter(RPOT));
1442 std::reverse(RPOT.begin(), RPOT.end());
1444 assert(RPOT.size() - 1 <= BlockNode::getMaxIndex() &&
1445 "More nodes in function than Block Frequency Info supports");
1447 DEBUG(dbgs() << "reverse-post-order-traversal\n");
1448 for (rpot_iterator I = rpot_begin(), E = rpot_end(); I != E; ++I) {
1449 BlockNode Node = getNode(I);
1450 DEBUG(dbgs() << " - " << getIndex(I) << ": " << getBlockName(Node) << "\n");
1454 Working.reserve(RPOT.size());
1455 for (size_t Index = 0; Index < RPOT.size(); ++Index)
1456 Working.emplace_back(Index);
1457 Freqs.resize(RPOT.size());
1460 template <class BT> void BlockFrequencyInfoImpl<BT>::initializeLoops() {
1461 DEBUG(dbgs() << "loop-detection\n");
1465 // Visit loops top down and assign them an index.
1466 std::deque<std::pair<const LoopT *, LoopData *>> Q;
1467 for (const LoopT *L : *LI)
1468 Q.emplace_back(L, nullptr);
1469 while (!Q.empty()) {
1470 const LoopT *Loop = Q.front().first;
1471 LoopData *Parent = Q.front().second;
1474 BlockNode Header = getNode(Loop->getHeader());
1475 assert(Header.isValid());
1477 Loops.emplace_back(Parent, Header);
1478 Working[Header.Index].Loop = &Loops.back();
1479 DEBUG(dbgs() << " - loop = " << getBlockName(Header) << "\n");
1481 for (const LoopT *L : *Loop)
1482 Q.emplace_back(L, &Loops.back());
1485 // Visit nodes in reverse post-order and add them to their deepest containing
1487 for (size_t Index = 0; Index < RPOT.size(); ++Index) {
1488 // Loop headers have already been mostly mapped.
1489 if (Working[Index].isLoopHeader()) {
1490 LoopData *ContainingLoop = Working[Index].getContainingLoop();
1492 ContainingLoop->Nodes.push_back(Index);
1496 const LoopT *Loop = LI->getLoopFor(RPOT[Index]);
1500 // Add this node to its containing loop's member list.
1501 BlockNode Header = getNode(Loop->getHeader());
1502 assert(Header.isValid());
1503 const auto &HeaderData = Working[Header.Index];
1504 assert(HeaderData.isLoopHeader());
1506 Working[Index].Loop = HeaderData.Loop;
1507 HeaderData.Loop->Nodes.push_back(Index);
1508 DEBUG(dbgs() << " - loop = " << getBlockName(Header)
1509 << ": member = " << getBlockName(Index) << "\n");
1513 template <class BT> void BlockFrequencyInfoImpl<BT>::computeMassInLoops() {
1514 // Visit loops with the deepest first, and the top-level loops last.
1515 for (auto L = Loops.rbegin(), E = Loops.rend(); L != E; ++L) {
1516 if (computeMassInLoop(*L))
1518 auto Next = std::next(L);
1519 computeIrreducibleMass(&*L, L.base());
1520 L = std::prev(Next);
1521 if (computeMassInLoop(*L))
1523 llvm_unreachable("unhandled irreducible control flow");
1528 bool BlockFrequencyInfoImpl<BT>::computeMassInLoop(LoopData &Loop) {
1529 // Compute mass in loop.
1530 DEBUG(dbgs() << "compute-mass-in-loop: " << getLoopName(Loop) << "\n");
1532 if (Loop.isIrreducible()) {
1533 BlockMass Remaining = BlockMass::getFull();
1534 for (uint32_t H = 0; H < Loop.NumHeaders; ++H) {
1535 auto &Mass = Working[Loop.Nodes[H].Index].getMass();
1536 Mass = Remaining * BranchProbability(1, Loop.NumHeaders - H);
1539 for (const BlockNode &M : Loop.Nodes)
1540 if (!propagateMassToSuccessors(&Loop, M))
1541 llvm_unreachable("unhandled irreducible control flow");
1543 Working[Loop.getHeader().Index].getMass() = BlockMass::getFull();
1544 if (!propagateMassToSuccessors(&Loop, Loop.getHeader()))
1545 llvm_unreachable("irreducible control flow to loop header!?");
1546 for (const BlockNode &M : Loop.members())
1547 if (!propagateMassToSuccessors(&Loop, M))
1548 // Irreducible backedge.
1552 computeLoopScale(Loop);
1558 bool BlockFrequencyInfoImpl<BT>::tryToComputeMassInFunction() {
1559 // Compute mass in function.
1560 DEBUG(dbgs() << "compute-mass-in-function\n");
1561 assert(!Working.empty() && "no blocks in function");
1562 assert(!Working[0].isLoopHeader() && "entry block is a loop header");
1564 Working[0].getMass() = BlockMass::getFull();
1565 for (rpot_iterator I = rpot_begin(), IE = rpot_end(); I != IE; ++I) {
1566 // Check for nodes that have been packaged.
1567 BlockNode Node = getNode(I);
1568 if (Working[Node.Index].isPackaged())
1571 if (!propagateMassToSuccessors(nullptr, Node))
1577 template <class BT> void BlockFrequencyInfoImpl<BT>::computeMassInFunction() {
1578 if (tryToComputeMassInFunction())
1580 computeIrreducibleMass(nullptr, Loops.begin());
1581 if (tryToComputeMassInFunction())
1583 llvm_unreachable("unhandled irreducible control flow");
1586 /// \note This should be a lambda, but that crashes GCC 4.7.
1587 namespace bfi_detail {
1588 template <class BT> struct BlockEdgesAdder {
1590 typedef BlockFrequencyInfoImplBase::LoopData LoopData;
1591 typedef GraphTraits<const BlockT *> Successor;
1593 const BlockFrequencyInfoImpl<BT> &BFI;
1594 explicit BlockEdgesAdder(const BlockFrequencyInfoImpl<BT> &BFI)
1596 void operator()(IrreducibleGraph &G, IrreducibleGraph::IrrNode &Irr,
1597 const LoopData *OuterLoop) {
1598 const BlockT *BB = BFI.RPOT[Irr.Node.Index];
1599 for (auto I = Successor::child_begin(BB), E = Successor::child_end(BB);
1601 G.addEdge(Irr, BFI.getNode(*I), OuterLoop);
1606 void BlockFrequencyInfoImpl<BT>::computeIrreducibleMass(
1607 LoopData *OuterLoop, std::list<LoopData>::iterator Insert) {
1608 DEBUG(dbgs() << "analyze-irreducible-in-";
1609 if (OuterLoop) dbgs() << "loop: " << getLoopName(*OuterLoop) << "\n";
1610 else dbgs() << "function\n");
1612 using namespace bfi_detail;
1613 // Ideally, addBlockEdges() would be declared here as a lambda, but that
1615 BlockEdgesAdder<BT> addBlockEdges(*this);
1616 IrreducibleGraph G(*this, OuterLoop, addBlockEdges);
1618 for (auto &L : analyzeIrreducible(G, OuterLoop, Insert))
1619 computeMassInLoop(L);
1623 updateLoopWithIrreducible(*OuterLoop);
1628 BlockFrequencyInfoImpl<BT>::propagateMassToSuccessors(LoopData *OuterLoop,
1629 const BlockNode &Node) {
1630 DEBUG(dbgs() << " - node: " << getBlockName(Node) << "\n");
1631 // Calculate probability for successors.
1633 if (auto *Loop = Working[Node.Index].getPackagedLoop()) {
1634 assert(Loop != OuterLoop && "Cannot propagate mass in a packaged loop");
1635 if (!addLoopSuccessorsToDist(OuterLoop, *Loop, Dist))
1636 // Irreducible backedge.
1639 const BlockT *BB = getBlock(Node);
1640 for (auto SI = Successor::child_begin(BB), SE = Successor::child_end(BB);
1642 // Do not dereference SI, or getEdgeWeight() is linear in the number of
1644 if (!addToDist(Dist, OuterLoop, Node, getNode(*SI),
1645 BPI->getEdgeWeight(BB, SI)))
1646 // Irreducible backedge.
1650 // Distribute mass to successors, saving exit and backedge data in the
1652 distributeMass(Node, OuterLoop, Dist);
1657 raw_ostream &BlockFrequencyInfoImpl<BT>::print(raw_ostream &OS) const {
1660 OS << "block-frequency-info: " << F->getName() << "\n";
1661 for (const BlockT &BB : *F)
1662 OS << " - " << bfi_detail::getBlockName(&BB)
1663 << ": float = " << getFloatingBlockFreq(&BB)
1664 << ", int = " << getBlockFreq(&BB).getFrequency() << "\n";
1666 // Add an extra newline for readability.