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.
12 //===----------------------------------------------------------------------===//
14 #ifndef LLVM_ANALYSIS_BLOCKFREQUENCYINFOIMPL_H
15 #define LLVM_ANALYSIS_BLOCKFREQUENCYINFOIMPL_H
17 #include "llvm/ADT/DenseMap.h"
18 #include "llvm/ADT/PostOrderIterator.h"
19 #include "llvm/IR/BasicBlock.h"
20 #include "llvm/Support/BlockFrequency.h"
21 #include "llvm/Support/BranchProbability.h"
22 #include "llvm/Support/Debug.h"
23 #include "llvm/Support/raw_ostream.h"
28 #define DEBUG_TYPE "block-freq"
30 //===----------------------------------------------------------------------===//
32 // UnsignedFloat definition.
34 // TODO: Make this private to BlockFrequencyInfoImpl or delete.
36 //===----------------------------------------------------------------------===//
39 class UnsignedFloatBase {
41 static const int32_t MaxExponent = 16383;
42 static const int32_t MinExponent = -16382;
43 static const int DefaultPrecision = 10;
45 static void dump(uint64_t D, int16_t E, int Width);
46 static raw_ostream &print(raw_ostream &OS, uint64_t D, int16_t E, int Width,
48 static std::string toString(uint64_t D, int16_t E, int Width,
50 static int countLeadingZeros32(uint32_t N) { return countLeadingZeros(N); }
51 static int countLeadingZeros64(uint64_t N) { return countLeadingZeros(N); }
52 static uint64_t getHalf(uint64_t N) { return (N >> 1) + (N & 1); }
54 static std::pair<uint64_t, bool> splitSigned(int64_t N) {
56 return std::make_pair(N, false);
57 uint64_t Unsigned = N == INT64_MIN ? UINT64_C(1) << 63 : uint64_t(-N);
58 return std::make_pair(Unsigned, true);
60 static int64_t joinSigned(uint64_t U, bool IsNeg) {
61 if (U > uint64_t(INT64_MAX))
62 return IsNeg ? INT64_MIN : INT64_MAX;
63 return IsNeg ? -int64_t(U) : int64_t(U);
66 static int32_t extractLg(const std::pair<int32_t, int> &Lg) {
69 static int32_t extractLgFloor(const std::pair<int32_t, int> &Lg) {
70 return Lg.first - (Lg.second > 0);
72 static int32_t extractLgCeiling(const std::pair<int32_t, int> &Lg) {
73 return Lg.first + (Lg.second < 0);
76 static std::pair<uint64_t, int16_t> divide64(uint64_t L, uint64_t R);
77 static std::pair<uint64_t, int16_t> multiply64(uint64_t L, uint64_t R);
79 static int compare(uint64_t L, uint64_t R, int Shift) {
83 uint64_t L_adjusted = L >> Shift;
89 return L > L_adjusted << Shift ? 1 : 0;
93 /// \brief Simple representation of an unsigned floating point.
95 /// UnsignedFloat is a unsigned floating point number. It uses simple
96 /// saturation arithmetic, and every operation is well-defined for every value.
98 /// The number is split into a signed exponent and unsigned digits. The number
99 /// represented is \c getDigits()*2^getExponent(). In this way, the digits are
100 /// much like the mantissa in the x87 long double, but there is no canonical
101 /// form, so the same number can be represented by many bit representations
102 /// (it's always in "denormal" mode).
104 /// UnsignedFloat is templated on the underlying integer type for digits, which
105 /// is expected to be one of uint64_t, uint32_t, uint16_t or uint8_t.
107 /// Unlike builtin floating point types, UnsignedFloat is portable.
109 /// Unlike APFloat, UnsignedFloat does not model architecture floating point
110 /// behaviour (this should make it a little faster), and implements most
111 /// operators (this makes it usable).
113 /// UnsignedFloat is totally ordered. However, there is no canonical form, so
114 /// there are multiple representations of most scalars. E.g.:
116 /// UnsignedFloat(8u, 0) == UnsignedFloat(4u, 1)
117 /// UnsignedFloat(4u, 1) == UnsignedFloat(2u, 2)
118 /// UnsignedFloat(2u, 2) == UnsignedFloat(1u, 3)
120 /// UnsignedFloat implements most arithmetic operations. Precision is kept
121 /// where possible. Uses simple saturation arithmetic, so that operations
122 /// saturate to 0.0 or getLargest() rather than under or overflowing. It has
123 /// some extra arithmetic for unit inversion. 0.0/0.0 is defined to be 0.0.
124 /// Any other division by 0.0 is defined to be getLargest().
126 /// As a convenience for modifying the exponent, left and right shifting are
127 /// both implemented, and both interpret negative shifts as positive shifts in
128 /// the opposite direction.
130 /// Exponents are limited to the range accepted by x87 long double. This makes
131 /// it trivial to add functionality to convert to APFloat (this is already
132 /// relied on for the implementation of printing).
134 /// The current plan is to gut this and make the necessary parts of it (even
135 /// more) private to BlockFrequencyInfo.
136 template <class DigitsT> class UnsignedFloat : UnsignedFloatBase {
138 static_assert(!std::numeric_limits<DigitsT>::is_signed,
139 "only unsigned floats supported");
141 typedef DigitsT DigitsType;
144 typedef std::numeric_limits<DigitsType> DigitsLimits;
146 static const int Width = sizeof(DigitsType) * 8;
147 static_assert(Width <= 64, "invalid integer width for digits");
154 UnsignedFloat() : Digits(0), Exponent(0) {}
156 UnsignedFloat(DigitsType Digits, int16_t Exponent)
157 : Digits(Digits), Exponent(Exponent) {}
160 UnsignedFloat(const std::pair<uint64_t, int16_t> &X)
161 : Digits(X.first), Exponent(X.second) {}
164 static UnsignedFloat getZero() { return UnsignedFloat(0, 0); }
165 static UnsignedFloat getOne() { return UnsignedFloat(1, 0); }
166 static UnsignedFloat getLargest() {
167 return UnsignedFloat(DigitsLimits::max(), MaxExponent);
169 static UnsignedFloat getFloat(uint64_t N) { return adjustToWidth(N, 0); }
170 static UnsignedFloat getInverseFloat(uint64_t N) {
171 return getFloat(N).invert();
173 static UnsignedFloat getFraction(DigitsType N, DigitsType D) {
174 return getQuotient(N, D);
177 int16_t getExponent() const { return Exponent; }
178 DigitsType getDigits() const { return Digits; }
180 /// \brief Convert to the given integer type.
182 /// Convert to \c IntT using simple saturating arithmetic, truncating if
184 template <class IntT> IntT toInt() const;
186 bool isZero() const { return !Digits; }
187 bool isLargest() const { return *this == getLargest(); }
189 if (Exponent > 0 || Exponent <= -Width)
191 return Digits == DigitsType(1) << -Exponent;
194 /// \brief The log base 2, rounded.
196 /// Get the lg of the scalar. lg 0 is defined to be INT32_MIN.
197 int32_t lg() const { return extractLg(lgImpl()); }
199 /// \brief The log base 2, rounded towards INT32_MIN.
201 /// Get the lg floor. lg 0 is defined to be INT32_MIN.
202 int32_t lgFloor() const { return extractLgFloor(lgImpl()); }
204 /// \brief The log base 2, rounded towards INT32_MAX.
206 /// Get the lg ceiling. lg 0 is defined to be INT32_MIN.
207 int32_t lgCeiling() const { return extractLgCeiling(lgImpl()); }
209 bool operator==(const UnsignedFloat &X) const { return compare(X) == 0; }
210 bool operator<(const UnsignedFloat &X) const { return compare(X) < 0; }
211 bool operator!=(const UnsignedFloat &X) const { return compare(X) != 0; }
212 bool operator>(const UnsignedFloat &X) const { return compare(X) > 0; }
213 bool operator<=(const UnsignedFloat &X) const { return compare(X) <= 0; }
214 bool operator>=(const UnsignedFloat &X) const { return compare(X) >= 0; }
216 bool operator!() const { return isZero(); }
218 /// \brief Convert to a decimal representation in a string.
220 /// Convert to a string. Uses scientific notation for very large/small
221 /// numbers. Scientific notation is used roughly for numbers outside of the
222 /// range 2^-64 through 2^64.
224 /// \c Precision indicates the number of decimal digits of precision to use;
225 /// 0 requests the maximum available.
227 /// As a special case to make debugging easier, if the number is small enough
228 /// to convert without scientific notation and has more than \c Precision
229 /// digits before the decimal place, it's printed accurately to the first
230 /// digit past zero. E.g., assuming 10 digits of precision:
232 /// 98765432198.7654... => 98765432198.8
233 /// 8765432198.7654... => 8765432198.8
234 /// 765432198.7654... => 765432198.8
235 /// 65432198.7654... => 65432198.77
236 /// 5432198.7654... => 5432198.765
237 std::string toString(unsigned Precision = DefaultPrecision) {
238 return UnsignedFloatBase::toString(Digits, Exponent, Width, Precision);
241 /// \brief Print a decimal representation.
243 /// Print a string. See toString for documentation.
244 raw_ostream &print(raw_ostream &OS,
245 unsigned Precision = DefaultPrecision) const {
246 return UnsignedFloatBase::print(OS, Digits, Exponent, Width, Precision);
248 void dump() const { return UnsignedFloatBase::dump(Digits, Exponent, Width); }
250 UnsignedFloat &operator+=(const UnsignedFloat &X);
251 UnsignedFloat &operator-=(const UnsignedFloat &X);
252 UnsignedFloat &operator*=(const UnsignedFloat &X);
253 UnsignedFloat &operator/=(const UnsignedFloat &X);
254 UnsignedFloat &operator<<=(int16_t Shift) { shiftLeft(Shift); return *this; }
255 UnsignedFloat &operator>>=(int16_t Shift) { shiftRight(Shift); return *this; }
258 void shiftLeft(int32_t Shift);
259 void shiftRight(int32_t Shift);
261 /// \brief Adjust two floats to have matching exponents.
263 /// Adjust \c this and \c X to have matching exponents. Returns the new \c X
264 /// by value. Does nothing if \a isZero() for either.
266 /// The value that compares smaller will lose precision, and possibly become
268 UnsignedFloat matchExponents(UnsignedFloat X);
270 /// \brief Increase exponent to match another float.
272 /// Increases \c this to have an exponent matching \c X. May decrease the
273 /// exponent of \c X in the process, and \c this may possibly become \a
275 void increaseExponentToMatch(UnsignedFloat &X, int32_t ExponentDiff);
278 /// \brief Scale a large number accurately.
280 /// Scale N (multiply it by this). Uses full precision multiplication, even
281 /// if Width is smaller than 64, so information is not lost.
282 uint64_t scale(uint64_t N) const;
283 uint64_t scaleByInverse(uint64_t N) const {
284 // TODO: implement directly, rather than relying on inverse. Inverse is
286 return inverse().scale(N);
288 int64_t scale(int64_t N) const {
289 std::pair<uint64_t, bool> Unsigned = splitSigned(N);
290 return joinSigned(scale(Unsigned.first), Unsigned.second);
292 int64_t scaleByInverse(int64_t N) const {
293 std::pair<uint64_t, bool> Unsigned = splitSigned(N);
294 return joinSigned(scaleByInverse(Unsigned.first), Unsigned.second);
297 int compare(const UnsignedFloat &X) const;
298 int compareTo(uint64_t N) const {
299 UnsignedFloat Float = getFloat(N);
300 int Compare = compare(Float);
301 if (Width == 64 || Compare != 0)
304 // Check for precision loss. We know *this == RoundTrip.
305 uint64_t RoundTrip = Float.template toInt<uint64_t>();
306 return N == RoundTrip ? 0 : RoundTrip < N ? -1 : 1;
308 int compareTo(int64_t N) const { return N < 0 ? 1 : compareTo(uint64_t(N)); }
310 UnsignedFloat &invert() { return *this = UnsignedFloat::getFloat(1) / *this; }
311 UnsignedFloat inverse() const { return UnsignedFloat(*this).invert(); }
314 static UnsignedFloat getProduct(DigitsType L, DigitsType R);
315 static UnsignedFloat getQuotient(DigitsType Dividend, DigitsType Divisor);
317 std::pair<int32_t, int> lgImpl() const;
318 static int countLeadingZerosWidth(DigitsType Digits) {
320 return countLeadingZeros64(Digits);
322 return countLeadingZeros32(Digits);
323 return countLeadingZeros32(Digits) + Width - 32;
326 static UnsignedFloat adjustToWidth(uint64_t N, int32_t S) {
327 assert(S >= MinExponent);
328 assert(S <= MaxExponent);
329 if (Width == 64 || N <= DigitsLimits::max())
330 return UnsignedFloat(N, S);
333 int Shift = 64 - Width - countLeadingZeros64(N);
334 DigitsType Shifted = N >> Shift;
337 assert(S + Shift <= MaxExponent);
338 return getRounded(UnsignedFloat(Shifted, S + Shift),
339 N & UINT64_C(1) << (Shift - 1));
342 static UnsignedFloat getRounded(UnsignedFloat P, bool Round) {
345 if (P.Digits == DigitsLimits::max())
346 // Careful of overflow in the exponent.
347 return UnsignedFloat(1, P.Exponent) <<= Width;
348 return UnsignedFloat(P.Digits + 1, P.Exponent);
352 #define UNSIGNED_FLOAT_BOP(op, base) \
353 template <class DigitsT> \
354 UnsignedFloat<DigitsT> operator op(const UnsignedFloat<DigitsT> &L, \
355 const UnsignedFloat<DigitsT> &R) { \
356 return UnsignedFloat<DigitsT>(L) base R; \
358 UNSIGNED_FLOAT_BOP(+, += )
359 UNSIGNED_FLOAT_BOP(-, -= )
360 UNSIGNED_FLOAT_BOP(*, *= )
361 UNSIGNED_FLOAT_BOP(/, /= )
362 UNSIGNED_FLOAT_BOP(<<, <<= )
363 UNSIGNED_FLOAT_BOP(>>, >>= )
364 #undef UNSIGNED_FLOAT_BOP
366 template <class DigitsT>
367 raw_ostream &operator<<(raw_ostream &OS, const UnsignedFloat<DigitsT> &X) {
368 return X.print(OS, 10);
371 #define UNSIGNED_FLOAT_COMPARE_TO_TYPE(op, T1, T2) \
372 template <class DigitsT> \
373 bool operator op(const UnsignedFloat<DigitsT> &L, T1 R) { \
374 return L.compareTo(T2(R)) op 0; \
376 template <class DigitsT> \
377 bool operator op(T1 L, const UnsignedFloat<DigitsT> &R) { \
378 return 0 op R.compareTo(T2(L)); \
380 #define UNSIGNED_FLOAT_COMPARE_TO(op) \
381 UNSIGNED_FLOAT_COMPARE_TO_TYPE(op, uint64_t, uint64_t) \
382 UNSIGNED_FLOAT_COMPARE_TO_TYPE(op, uint32_t, uint64_t) \
383 UNSIGNED_FLOAT_COMPARE_TO_TYPE(op, int64_t, int64_t) \
384 UNSIGNED_FLOAT_COMPARE_TO_TYPE(op, int32_t, int64_t)
385 UNSIGNED_FLOAT_COMPARE_TO(< )
386 UNSIGNED_FLOAT_COMPARE_TO(> )
387 UNSIGNED_FLOAT_COMPARE_TO(== )
388 UNSIGNED_FLOAT_COMPARE_TO(!= )
389 UNSIGNED_FLOAT_COMPARE_TO(<= )
390 UNSIGNED_FLOAT_COMPARE_TO(>= )
391 #undef UNSIGNED_FLOAT_COMPARE_TO
392 #undef UNSIGNED_FLOAT_COMPARE_TO_TYPE
394 template <class DigitsT>
395 uint64_t UnsignedFloat<DigitsT>::scale(uint64_t N) const {
396 if (Width == 64 || N <= DigitsLimits::max())
397 return (getFloat(N) * *this).template toInt<uint64_t>();
399 // Defer to the 64-bit version.
400 return UnsignedFloat<uint64_t>(Digits, Exponent).scale(N);
403 template <class DigitsT>
404 UnsignedFloat<DigitsT> UnsignedFloat<DigitsT>::getProduct(DigitsType L,
410 // Check for numbers that we can compute with 64-bit math.
411 if (Width <= 32 || (L <= UINT32_MAX && R <= UINT32_MAX))
412 return adjustToWidth(uint64_t(L) * uint64_t(R), 0);
414 // Do the full thing.
415 return UnsignedFloat(multiply64(L, R));
417 template <class DigitsT>
418 UnsignedFloat<DigitsT> UnsignedFloat<DigitsT>::getQuotient(DigitsType Dividend,
419 DigitsType Divisor) {
427 return UnsignedFloat(divide64(Dividend, Divisor));
429 // We can compute this with 64-bit math.
430 int Shift = countLeadingZeros64(Dividend);
431 uint64_t Shifted = uint64_t(Dividend) << Shift;
432 uint64_t Quotient = Shifted / Divisor;
434 // If Quotient needs to be shifted, then adjustToWidth will round.
435 if (Quotient > DigitsLimits::max())
436 return adjustToWidth(Quotient, -Shift);
438 // Round based on the value of the next bit.
439 return getRounded(UnsignedFloat(Quotient, -Shift),
440 Shifted % Divisor >= getHalf(Divisor));
443 template <class DigitsT>
444 template <class IntT>
445 IntT UnsignedFloat<DigitsT>::toInt() const {
446 typedef std::numeric_limits<IntT> Limits;
449 if (*this >= Limits::max())
450 return Limits::max();
454 assert(size_t(Exponent) < sizeof(IntT) * 8);
455 return N << Exponent;
458 assert(size_t(-Exponent) < sizeof(IntT) * 8);
459 return N >> -Exponent;
464 template <class DigitsT>
465 std::pair<int32_t, int> UnsignedFloat<DigitsT>::lgImpl() const {
467 return std::make_pair(INT32_MIN, 0);
469 // Get the floor of the lg of Digits.
470 int32_t LocalFloor = Width - countLeadingZerosWidth(Digits) - 1;
472 // Get the floor of the lg of this.
473 int32_t Floor = Exponent + LocalFloor;
474 if (Digits == UINT64_C(1) << LocalFloor)
475 return std::make_pair(Floor, 0);
477 // Round based on the next digit.
478 assert(LocalFloor >= 1);
479 bool Round = Digits & UINT64_C(1) << (LocalFloor - 1);
480 return std::make_pair(Floor + Round, Round ? 1 : -1);
483 template <class DigitsT>
484 UnsignedFloat<DigitsT> UnsignedFloat<DigitsT>::matchExponents(UnsignedFloat X) {
485 if (isZero() || X.isZero() || Exponent == X.Exponent)
488 int32_t Diff = int32_t(X.Exponent) - int32_t(Exponent);
490 increaseExponentToMatch(X, Diff);
492 X.increaseExponentToMatch(*this, -Diff);
495 template <class DigitsT>
496 void UnsignedFloat<DigitsT>::increaseExponentToMatch(UnsignedFloat &X,
497 int32_t ExponentDiff) {
498 assert(ExponentDiff > 0);
499 if (ExponentDiff >= 2 * Width) {
504 // Use up any leading zeros on X, and then shift this.
505 int32_t ShiftX = std::min(countLeadingZerosWidth(X.Digits), ExponentDiff);
506 assert(ShiftX < Width);
508 int32_t ShiftThis = ExponentDiff - ShiftX;
509 if (ShiftThis >= Width) {
515 X.Exponent -= ShiftX;
516 Digits >>= ShiftThis;
517 Exponent += ShiftThis;
521 template <class DigitsT>
522 UnsignedFloat<DigitsT> &UnsignedFloat<DigitsT>::
523 operator+=(const UnsignedFloat &X) {
524 if (isLargest() || X.isZero())
526 if (isZero() || X.isLargest())
529 // Normalize exponents.
530 UnsignedFloat Scaled = matchExponents(X);
532 // Check for zero again.
534 return *this = Scaled;
539 DigitsType Sum = Digits + Scaled.Digits;
540 bool DidOverflow = Sum < Digits;
545 if (Exponent == MaxExponent)
546 return *this = getLargest();
549 Digits = UINT64_C(1) << (Width - 1) | Digits >> 1;
553 template <class DigitsT>
554 UnsignedFloat<DigitsT> &UnsignedFloat<DigitsT>::
555 operator-=(const UnsignedFloat &X) {
559 return *this = getZero();
561 // Normalize exponents.
562 UnsignedFloat Scaled = matchExponents(X);
563 assert(Digits >= Scaled.Digits);
565 // Compute difference.
566 if (!Scaled.isZero()) {
567 Digits -= Scaled.Digits;
571 // Check if X just barely lost its last bit. E.g., for 32-bit:
573 // 1*2^32 - 1*2^0 == 0xffffffff != 1*2^32
574 if (*this == UnsignedFloat(1, X.lgFloor() + Width)) {
575 Digits = DigitsType(0) - 1;
580 template <class DigitsT>
581 UnsignedFloat<DigitsT> &UnsignedFloat<DigitsT>::
582 operator*=(const UnsignedFloat &X) {
588 // Save the exponents.
589 int32_t Exponents = int32_t(Exponent) + int32_t(X.Exponent);
591 // Get the raw product.
592 *this = getProduct(Digits, X.Digits);
594 // Combine with exponents.
595 return *this <<= Exponents;
597 template <class DigitsT>
598 UnsignedFloat<DigitsT> &UnsignedFloat<DigitsT>::
599 operator/=(const UnsignedFloat &X) {
603 return *this = getLargest();
605 // Save the exponents.
606 int32_t Exponents = int32_t(Exponent) - int32_t(X.Exponent);
608 // Get the raw quotient.
609 *this = getQuotient(Digits, X.Digits);
611 // Combine with exponents.
612 return *this <<= Exponents;
614 template <class DigitsT>
615 void UnsignedFloat<DigitsT>::shiftLeft(int32_t Shift) {
616 if (!Shift || isZero())
618 assert(Shift != INT32_MIN);
624 // Shift as much as we can in the exponent.
625 int32_t ExponentShift = std::min(Shift, MaxExponent - Exponent);
626 Exponent += ExponentShift;
627 if (ExponentShift == Shift)
630 // Check this late, since it's rare.
634 // Shift the digits themselves.
635 Shift -= ExponentShift;
636 if (Shift > countLeadingZerosWidth(Digits)) {
638 *this = getLargest();
646 template <class DigitsT>
647 void UnsignedFloat<DigitsT>::shiftRight(int32_t Shift) {
648 if (!Shift || isZero())
650 assert(Shift != INT32_MIN);
656 // Shift as much as we can in the exponent.
657 int32_t ExponentShift = std::min(Shift, Exponent - MinExponent);
658 Exponent -= ExponentShift;
659 if (ExponentShift == Shift)
662 // Shift the digits themselves.
663 Shift -= ExponentShift;
664 if (Shift >= Width) {
674 template <class DigitsT>
675 int UnsignedFloat<DigitsT>::compare(const UnsignedFloat &X) const {
678 return X.isZero() ? 0 : -1;
682 // Check for the scale. Use lgFloor to be sure that the exponent difference
683 // is always lower than 64.
684 int32_t lgL = lgFloor(), lgR = X.lgFloor();
686 return lgL < lgR ? -1 : 1;
689 if (Exponent < X.Exponent)
690 return UnsignedFloatBase::compare(Digits, X.Digits, X.Exponent - Exponent);
692 return -UnsignedFloatBase::compare(X.Digits, Digits, Exponent - X.Exponent);
695 template <class T> struct isPodLike<UnsignedFloat<T>> {
696 static const bool value = true;
700 //===----------------------------------------------------------------------===//
702 // BlockMass definition.
704 // TODO: Make this private to BlockFrequencyInfoImpl or delete.
706 //===----------------------------------------------------------------------===//
709 /// \brief Mass of a block.
711 /// This class implements a sort of fixed-point fraction always between 0.0 and
712 /// 1.0. getMass() == UINT64_MAX indicates a value of 1.0.
714 /// Masses can be added and subtracted. Simple saturation arithmetic is used,
715 /// so arithmetic operations never overflow or underflow.
717 /// Masses can be multiplied. Multiplication treats full mass as 1.0 and uses
718 /// an inexpensive floating-point algorithm that's off-by-one (almost, but not
719 /// quite, maximum precision).
721 /// Masses can be scaled by \a BranchProbability at maximum precision.
726 BlockMass() : Mass(0) {}
727 explicit BlockMass(uint64_t Mass) : Mass(Mass) {}
729 static BlockMass getEmpty() { return BlockMass(); }
730 static BlockMass getFull() { return BlockMass(UINT64_MAX); }
732 uint64_t getMass() const { return Mass; }
734 bool isFull() const { return Mass == UINT64_MAX; }
735 bool isEmpty() const { return !Mass; }
737 bool operator!() const { return isEmpty(); }
739 /// \brief Add another mass.
741 /// Adds another mass, saturating at \a isFull() rather than overflowing.
742 BlockMass &operator+=(const BlockMass &X) {
743 uint64_t Sum = Mass + X.Mass;
744 Mass = Sum < Mass ? UINT64_MAX : Sum;
748 /// \brief Subtract another mass.
750 /// Subtracts another mass, saturating at \a isEmpty() rather than
752 BlockMass &operator-=(const BlockMass &X) {
753 uint64_t Diff = Mass - X.Mass;
754 Mass = Diff > Mass ? 0 : Diff;
758 /// \brief Scale by another mass.
760 /// The current implementation is a little imprecise, but it's relatively
761 /// fast, never overflows, and maintains the property that 1.0*1.0==1.0
762 /// (where isFull represents the number 1.0). It's an approximation of
763 /// 128-bit multiply that gets right-shifted by 64-bits.
765 /// For a given digit size, multiplying two-digit numbers looks like:
771 /// + 0 . U1*L2 . 0 // (shift left once by a digit-size)
772 /// + 0 . U2*L1 . 0 // (shift left once by a digit-size)
773 /// + U1*L2 . 0 . 0 // (shift left twice by a digit-size)
775 /// BlockMass has 64-bit numbers. Split each into two 32-bit digits, stored
776 /// 64-bit. Add 1 to the lower digits, to model isFull as 1.0; this won't
777 /// overflow, since we have 64-bit storage for each digit.
779 /// To do this accurately, (a) multiply into two 64-bit digits, incrementing
780 /// the upper digit on overflows of the lower digit (carry), (b) subtract 1
781 /// from the lower digit, decrementing the upper digit on underflow (carry),
782 /// and (c) truncate the lower digit. For the 1.0*1.0 case, the upper digit
783 /// will be 0 at the end of step (a), and then will underflow back to isFull
784 /// (1.0) in step (b).
786 /// Instead, the implementation does something a little faster with a small
787 /// loss of accuracy: ignore the lower 64-bit digit entirely. The loss of
788 /// accuracy is small, since the sum of the unmodelled carries is 0 or 1
789 /// (i.e., step (a) will overflow at most once, and step (b) will underflow
790 /// only if step (a) overflows).
792 /// This is the formula we're calculating:
794 /// U1.L1 * U2.L2 == U1 * U2 + (U1 * (L2+1))>>32 + (U2 * (L1+1))>>32
796 /// As a demonstration of 1.0*1.0, consider two 4-bit numbers that are both
799 /// U1.L1 * U2.L2 == U1 * U2 + (U1 * (L2+1))>>2 + (U2 * (L1+1))>>2
800 /// 11.11 * 11.11 == 11 * 11 + (11 * (11+1))/4 + (11 * (11+1))/4
801 /// == 1001 + (11 * 100)/4 + (11 * 100)/4
802 /// == 1001 + 1100/4 + 1100/4
803 /// == 1001 + 0011 + 0011
805 BlockMass &operator*=(const BlockMass &X) {
806 uint64_t U1 = Mass >> 32, L1 = Mass & UINT32_MAX, U2 = X.Mass >> 32,
807 L2 = X.Mass & UINT32_MAX;
808 Mass = U1 * U2 + (U1 * (L2 + 1) >> 32) + ((L1 + 1) * U2 >> 32);
812 /// \brief Multiply by a branch probability.
814 /// Multiply by P. Guarantees full precision.
816 /// This could be naively implemented by multiplying by the numerator and
817 /// dividing by the denominator, but in what order? Multiplying first can
818 /// overflow, while dividing first will lose precision (potentially, changing
819 /// a non-zero mass to zero).
821 /// The implementation mixes the two methods. Since \a BranchProbability
822 /// uses 32-bits and \a BlockMass 64-bits, shift the mass as far to the left
823 /// as there is room, then divide by the denominator to get a quotient.
824 /// Multiplying by the numerator and right shifting gives a first
827 /// Calculate the error in this first approximation by calculating the
828 /// opposite mass (multiply by the opposite numerator and shift) and
829 /// subtracting both from teh original mass.
831 /// Add to the first approximation the correct fraction of this error value.
832 /// This time, multiply first and then divide, since there is no danger of
835 /// \pre P represents a fraction between 0.0 and 1.0.
836 BlockMass &operator*=(const BranchProbability &P);
838 bool operator==(const BlockMass &X) const { return Mass == X.Mass; }
839 bool operator!=(const BlockMass &X) const { return Mass != X.Mass; }
840 bool operator<=(const BlockMass &X) const { return Mass <= X.Mass; }
841 bool operator>=(const BlockMass &X) const { return Mass >= X.Mass; }
842 bool operator<(const BlockMass &X) const { return Mass < X.Mass; }
843 bool operator>(const BlockMass &X) const { return Mass > X.Mass; }
845 /// \brief Convert to floating point.
847 /// Convert to a float. \a isFull() gives 1.0, while \a isEmpty() gives
848 /// slightly above 0.0.
849 UnsignedFloat<uint64_t> toFloat() const;
852 raw_ostream &print(raw_ostream &OS) const;
855 inline BlockMass operator+(const BlockMass &L, const BlockMass &R) {
856 return BlockMass(L) += R;
858 inline BlockMass operator-(const BlockMass &L, const BlockMass &R) {
859 return BlockMass(L) -= R;
861 inline BlockMass operator*(const BlockMass &L, const BlockMass &R) {
862 return BlockMass(L) *= R;
864 inline BlockMass operator*(const BlockMass &L, const BranchProbability &R) {
865 return BlockMass(L) *= R;
867 inline BlockMass operator*(const BranchProbability &L, const BlockMass &R) {
868 return BlockMass(R) *= L;
871 inline raw_ostream &operator<<(raw_ostream &OS, const BlockMass &X) {
875 template <> struct isPodLike<BlockMass> {
876 static const bool value = true;
880 //===----------------------------------------------------------------------===//
882 // BlockFrequencyInfoImpl definition.
884 //===----------------------------------------------------------------------===//
888 class BranchProbabilityInfo;
892 class MachineBasicBlock;
893 class MachineBranchProbabilityInfo;
894 class MachineFunction;
896 class MachineLoopInfo;
898 /// \brief Base class for BlockFrequencyInfoImpl
900 /// BlockFrequencyInfoImplBase has supporting data structures and some
901 /// algorithms for BlockFrequencyInfoImplBase. Only algorithms that depend on
902 /// the block type (or that call such algorithms) are skipped here.
904 /// Nevertheless, the majority of the overall algorithm documention lives with
905 /// BlockFrequencyInfoImpl. See there for details.
906 class BlockFrequencyInfoImplBase {
908 typedef UnsignedFloat<uint64_t> Float;
910 /// \brief Representative of a block.
912 /// This is a simple wrapper around an index into the reverse-post-order
913 /// traversal of the blocks.
915 /// Unlike a block pointer, its order has meaning (location in the
916 /// topological sort) and it's class is the same regardless of block type.
918 typedef uint32_t IndexType;
921 bool operator==(const BlockNode &X) const { return Index == X.Index; }
922 bool operator!=(const BlockNode &X) const { return Index != X.Index; }
923 bool operator<=(const BlockNode &X) const { return Index <= X.Index; }
924 bool operator>=(const BlockNode &X) const { return Index >= X.Index; }
925 bool operator<(const BlockNode &X) const { return Index < X.Index; }
926 bool operator>(const BlockNode &X) const { return Index > X.Index; }
928 BlockNode() : Index(UINT32_MAX) {}
929 BlockNode(IndexType Index) : Index(Index) {}
931 bool isValid() const { return Index <= getMaxIndex(); }
932 static size_t getMaxIndex() { return UINT32_MAX - 1; }
935 /// \brief Stats about a block itself.
936 struct FrequencyData {
941 /// \brief Data about a loop.
943 /// Contains the data necessary to represent represent a loop as a
944 /// pseudo-node once it's packaged.
946 typedef SmallVector<std::pair<BlockNode, BlockMass>, 4> ExitMap;
947 typedef SmallVector<BlockNode, 4> MemberList;
948 BlockNode Header; ///< Header.
949 bool IsPackaged; ///< Whether this has been packaged.
950 ExitMap Exits; ///< Successor edges (and weights).
951 MemberList Members; ///< Members of the loop.
952 BlockMass BackedgeMass; ///< Mass returned to loop header.
956 LoopData(const BlockNode &Header) : Header(Header), IsPackaged(false) {}
959 /// \brief Index of loop information.
961 LoopData *Loop; ///< The loop this block is the header of.
962 LoopData *ContainingLoop; ///< The block whose loop this block is inside.
963 BlockMass Mass; ///< Mass distribution from the entry block.
965 WorkingData() : Loop(nullptr), ContainingLoop(nullptr) {}
967 bool hasLoopHeader() const { return ContainingLoop; }
968 bool isLoopHeader() const { return Loop; }
970 BlockNode getContainingHeader() const {
972 return ContainingLoop->Header;
976 /// \brief Has ContainingLoop been packaged up?
977 bool isPackaged() const {
978 return ContainingLoop && ContainingLoop->IsPackaged;
980 /// \brief Has Loop been packaged up?
981 bool isAPackage() const { return Loop && Loop->IsPackaged; }
984 /// \brief Unscaled probability weight.
986 /// Probability weight for an edge in the graph (including the
987 /// successor/target node).
989 /// All edges in the original function are 32-bit. However, exit edges from
990 /// loop packages are taken from 64-bit exit masses, so we need 64-bits of
991 /// space in general.
993 /// In addition to the raw weight amount, Weight stores the type of the edge
994 /// in the current context (i.e., the context of the loop being processed).
995 /// Is this a local edge within the loop, an exit from the loop, or a
996 /// backedge to the loop header?
998 enum DistType { Local, Exit, Backedge };
1000 BlockNode TargetNode;
1002 Weight() : Type(Local), Amount(0) {}
1005 /// \brief Distribution of unscaled probability weight.
1007 /// Distribution of unscaled probability weight to a set of successors.
1009 /// This class collates the successor edge weights for later processing.
1011 /// \a DidOverflow indicates whether \a Total did overflow while adding to
1012 /// the distribution. It should never overflow twice. There's no flag for
1013 /// whether \a ForwardTotal overflows, since when \a Total exceeds 32-bits
1014 /// they both get re-computed during \a normalize().
1015 struct Distribution {
1016 typedef SmallVector<Weight, 4> WeightList;
1017 WeightList Weights; ///< Individual successor weights.
1018 uint64_t Total; ///< Sum of all weights.
1019 bool DidOverflow; ///< Whether \a Total did overflow.
1020 uint32_t ForwardTotal; ///< Total excluding backedges.
1022 Distribution() : Total(0), DidOverflow(false), ForwardTotal(0) {}
1023 void addLocal(const BlockNode &Node, uint64_t Amount) {
1024 add(Node, Amount, Weight::Local);
1026 void addExit(const BlockNode &Node, uint64_t Amount) {
1027 add(Node, Amount, Weight::Exit);
1029 void addBackedge(const BlockNode &Node, uint64_t Amount) {
1030 add(Node, Amount, Weight::Backedge);
1033 /// \brief Normalize the distribution.
1035 /// Combines multiple edges to the same \a Weight::TargetNode and scales
1036 /// down so that \a Total fits into 32-bits.
1038 /// This is linear in the size of \a Weights. For the vast majority of
1039 /// cases, adjacent edge weights are combined by sorting WeightList and
1040 /// combining adjacent weights. However, for very large edge lists an
1041 /// auxiliary hash table is used.
1045 void add(const BlockNode &Node, uint64_t Amount, Weight::DistType Type);
1048 /// \brief Data about each block. This is used downstream.
1049 std::vector<FrequencyData> Freqs;
1051 /// \brief Loop data: see initializeLoops().
1052 std::vector<WorkingData> Working;
1054 /// \brief Indexed information about loops.
1055 std::list<LoopData> Loops;
1057 /// \brief Add all edges out of a packaged loop to the distribution.
1059 /// Adds all edges from LocalLoopHead to Dist. Calls addToDist() to add each
1061 void addLoopSuccessorsToDist(const BlockNode &LoopHead,
1062 const BlockNode &LocalLoopHead,
1063 Distribution &Dist);
1065 /// \brief Add an edge to the distribution.
1067 /// Adds an edge to Succ to Dist. If \c LoopHead.isValid(), then whether the
1068 /// edge is forward/exit/backedge is in the context of LoopHead. Otherwise,
1069 /// every edge should be a forward edge (since all the loops are packaged
1071 void addToDist(Distribution &Dist, const BlockNode &LoopHead,
1072 const BlockNode &Pred, const BlockNode &Succ, uint64_t Weight);
1074 LoopData &getLoopPackage(const BlockNode &Head) {
1075 assert(Head.Index < Working.size());
1076 assert(Working[Head.Index].Loop != nullptr);
1077 return *Working[Head.Index].Loop;
1080 /// \brief Distribute mass according to a distribution.
1082 /// Distributes the mass in Source according to Dist. If LoopHead.isValid(),
1083 /// backedges and exits are stored in its entry in Loops.
1085 /// Mass is distributed in parallel from two copies of the source mass.
1087 /// The first mass (forward) represents the distribution of mass through the
1088 /// local DAG. This distribution should lose mass at loop exits and ignore
1091 /// The second mass (general) represents the behavior of the loop in the
1092 /// global context. In a given distribution from the head, how much mass
1093 /// exits, and to where? How much mass returns to the loop head?
1095 /// The forward mass should be split up between local successors and exits,
1096 /// but only actually distributed to the local successors. The general mass
1097 /// should be split up between all three types of successors, but distributed
1098 /// only to exits and backedges.
1099 void distributeMass(const BlockNode &Source, const BlockNode &LoopHead,
1100 Distribution &Dist);
1102 /// \brief Compute the loop scale for a loop.
1103 void computeLoopScale(const BlockNode &LoopHead);
1105 /// \brief Package up a loop.
1106 void packageLoop(const BlockNode &LoopHead);
1108 /// \brief Finalize frequency metrics.
1110 /// Unwraps loop packages, calculates final frequencies, and cleans up
1111 /// no-longer-needed data structures.
1112 void finalizeMetrics();
1114 /// \brief Clear all memory.
1117 virtual std::string getBlockName(const BlockNode &Node) const;
1119 virtual raw_ostream &print(raw_ostream &OS) const { return OS; }
1120 void dump() const { print(dbgs()); }
1122 Float getFloatingBlockFreq(const BlockNode &Node) const;
1124 BlockFrequency getBlockFreq(const BlockNode &Node) const;
1126 raw_ostream &printBlockFreq(raw_ostream &OS, const BlockNode &Node) const;
1127 raw_ostream &printBlockFreq(raw_ostream &OS,
1128 const BlockFrequency &Freq) const;
1130 uint64_t getEntryFreq() const {
1131 assert(!Freqs.empty());
1132 return Freqs[0].Integer;
1134 /// \brief Virtual destructor.
1136 /// Need a virtual destructor to mask the compiler warning about
1138 virtual ~BlockFrequencyInfoImplBase() {}
1141 namespace bfi_detail {
1142 template <class BlockT> struct TypeMap {};
1143 template <> struct TypeMap<BasicBlock> {
1144 typedef BasicBlock BlockT;
1145 typedef Function FunctionT;
1146 typedef BranchProbabilityInfo BranchProbabilityInfoT;
1148 typedef LoopInfo LoopInfoT;
1150 template <> struct TypeMap<MachineBasicBlock> {
1151 typedef MachineBasicBlock BlockT;
1152 typedef MachineFunction FunctionT;
1153 typedef MachineBranchProbabilityInfo BranchProbabilityInfoT;
1154 typedef MachineLoop LoopT;
1155 typedef MachineLoopInfo LoopInfoT;
1158 /// \brief Get the name of a MachineBasicBlock.
1160 /// Get the name of a MachineBasicBlock. It's templated so that including from
1161 /// CodeGen is unnecessary (that would be a layering issue).
1163 /// This is used mainly for debug output. The name is similar to
1164 /// MachineBasicBlock::getFullName(), but skips the name of the function.
1165 template <class BlockT> std::string getBlockName(const BlockT *BB) {
1166 assert(BB && "Unexpected nullptr");
1167 auto MachineName = "BB" + Twine(BB->getNumber());
1168 if (BB->getBasicBlock())
1169 return (MachineName + "[" + BB->getName() + "]").str();
1170 return MachineName.str();
1172 /// \brief Get the name of a BasicBlock.
1173 template <> inline std::string getBlockName(const BasicBlock *BB) {
1174 assert(BB && "Unexpected nullptr");
1175 return BB->getName().str();
1179 /// \brief Shared implementation for block frequency analysis.
1181 /// This is a shared implementation of BlockFrequencyInfo and
1182 /// MachineBlockFrequencyInfo, and calculates the relative frequencies of
1185 /// This algorithm leverages BlockMass and UnsignedFloat to maintain precision,
1186 /// separates mass distribution from loop scaling, and dithers to eliminate
1187 /// probability mass loss.
1189 /// The implementation is split between BlockFrequencyInfoImpl, which knows the
1190 /// type of graph being modelled (BasicBlock vs. MachineBasicBlock), and
1191 /// BlockFrequencyInfoImplBase, which doesn't. The base class uses \a
1192 /// BlockNode, a wrapper around a uint32_t. BlockNode is numbered from 0 in
1193 /// reverse-post order. This gives two advantages: it's easy to compare the
1194 /// relative ordering of two nodes, and maps keyed on BlockT can be represented
1197 /// This algorithm is O(V+E), unless there is irreducible control flow, in
1198 /// which case it's O(V*E) in the worst case.
1200 /// These are the main stages:
1202 /// 0. Reverse post-order traversal (\a initializeRPOT()).
1204 /// Run a single post-order traversal and save it (in reverse) in RPOT.
1205 /// All other stages make use of this ordering. Save a lookup from BlockT
1206 /// to BlockNode (the index into RPOT) in Nodes.
1208 /// 1. Loop indexing (\a initializeLoops()).
1210 /// Translate LoopInfo/MachineLoopInfo into a form suitable for the rest of
1211 /// the algorithm. In particular, store the immediate members of each loop
1212 /// in reverse post-order.
1214 /// 2. Calculate mass and scale in loops (\a computeMassInLoops()).
1216 /// For each loop (bottom-up), distribute mass through the DAG resulting
1217 /// from ignoring backedges and treating sub-loops as a single pseudo-node.
1218 /// Track the backedge mass distributed to the loop header, and use it to
1219 /// calculate the loop scale (number of loop iterations).
1221 /// Visiting loops bottom-up is a post-order traversal of loop headers.
1222 /// For each loop, immediate members that represent sub-loops will already
1223 /// have been visited and packaged into a pseudo-node.
1225 /// Distributing mass in a loop is a reverse-post-order traversal through
1226 /// the loop. Start by assigning full mass to the Loop header. For each
1227 /// node in the loop:
1229 /// - Fetch and categorize the weight distribution for its successors.
1230 /// If this is a packaged-subloop, the weight distribution is stored
1231 /// in \a LoopData::Exits. Otherwise, fetch it from
1232 /// BranchProbabilityInfo.
1234 /// - Each successor is categorized as \a Weight::Local, a normal
1235 /// forward edge within the current loop, \a Weight::Backedge, a
1236 /// backedge to the loop header, or \a Weight::Exit, any successor
1237 /// outside the loop. The weight, the successor, and its category
1238 /// are stored in \a Distribution. There can be multiple edges to
1241 /// - Normalize the distribution: scale weights down so that their sum
1242 /// is 32-bits, and coalesce multiple edges to the same node.
1244 /// - Distribute the mass accordingly, dithering to minimize mass loss,
1245 /// as described in \a distributeMass(). Mass is distributed in
1246 /// parallel in two ways: forward, and general. Local successors
1247 /// take their mass from the forward mass, while exit and backedge
1248 /// successors take their mass from the general mass. Additionally,
1249 /// exit edges use up (ignored) mass from the forward mass, and local
1250 /// edges use up (ignored) mass from the general distribution.
1252 /// Finally, calculate the loop scale from the accumulated backedge mass.
1254 /// 3. Distribute mass in the function (\a computeMassInFunction()).
1256 /// Finally, distribute mass through the DAG resulting from packaging all
1257 /// loops in the function. This uses the same algorithm as distributing
1258 /// mass in a loop, except that there are no exit or backedge edges.
1260 /// 4. Loop unpackaging and cleanup (\a finalizeMetrics()).
1262 /// Initialize the frequency to a floating point representation of its
1265 /// Visit loops top-down (reverse post-order), scaling the loop header's
1266 /// frequency by its psuedo-node's mass and loop scale. Keep track of the
1267 /// minimum and maximum final frequencies.
1269 /// Using the min and max frequencies as a guide, translate floating point
1270 /// frequencies to an appropriate range in uint64_t.
1272 /// It has some known flaws.
1274 /// - Irreducible control flow isn't modelled correctly. In particular,
1275 /// LoopInfo and MachineLoopInfo ignore irreducible backedges. The main
1276 /// result is that irreducible SCCs will under-scaled. No mass is lost,
1277 /// but the computed branch weights for the loop pseudo-node will be
1280 /// Modelling irreducible control flow exactly involves setting up and
1281 /// solving a group of infinite geometric series. Such precision is
1282 /// unlikely to be worthwhile, since most of our algorithms give up on
1283 /// irreducible control flow anyway.
1285 /// Nevertheless, we might find that we need to get closer. If
1286 /// LoopInfo/MachineLoopInfo flags loops with irreducible control flow
1287 /// (and/or the function as a whole), we can find the SCCs, compute an
1288 /// approximate exit frequency for the SCC as a whole, and scale up
1291 /// - Loop scale is limited to 4096 per loop (2^12) to avoid exhausting
1292 /// BlockFrequency's 64-bit integer precision.
1293 template <class BT> class BlockFrequencyInfoImpl : BlockFrequencyInfoImplBase {
1294 typedef typename bfi_detail::TypeMap<BT>::BlockT BlockT;
1295 typedef typename bfi_detail::TypeMap<BT>::FunctionT FunctionT;
1296 typedef typename bfi_detail::TypeMap<BT>::BranchProbabilityInfoT
1297 BranchProbabilityInfoT;
1298 typedef typename bfi_detail::TypeMap<BT>::LoopT LoopT;
1299 typedef typename bfi_detail::TypeMap<BT>::LoopInfoT LoopInfoT;
1301 typedef GraphTraits<const BlockT *> Successor;
1302 typedef GraphTraits<Inverse<const BlockT *>> Predecessor;
1304 const BranchProbabilityInfoT *BPI;
1305 const LoopInfoT *LI;
1308 // All blocks in reverse postorder.
1309 std::vector<const BlockT *> RPOT;
1310 DenseMap<const BlockT *, BlockNode> Nodes;
1312 typedef typename std::vector<const BlockT *>::const_iterator rpot_iterator;
1314 rpot_iterator rpot_begin() const { return RPOT.begin(); }
1315 rpot_iterator rpot_end() const { return RPOT.end(); }
1317 size_t getIndex(const rpot_iterator &I) const { return I - rpot_begin(); }
1319 BlockNode getNode(const rpot_iterator &I) const {
1320 return BlockNode(getIndex(I));
1322 BlockNode getNode(const BlockT *BB) const { return Nodes.lookup(BB); }
1324 const BlockT *getBlock(const BlockNode &Node) const {
1325 assert(Node.Index < RPOT.size());
1326 return RPOT[Node.Index];
1329 void initializeRPOT();
1330 void initializeLoops();
1331 void runOnFunction(const FunctionT *F);
1333 void propagateMassToSuccessors(const BlockNode &LoopHead,
1334 const BlockNode &Node);
1335 void computeMassInLoops();
1336 void computeMassInLoop(const BlockNode &LoopHead);
1337 void computeMassInFunction();
1339 std::string getBlockName(const BlockNode &Node) const override {
1340 return bfi_detail::getBlockName(getBlock(Node));
1344 const FunctionT *getFunction() const { return F; }
1346 void doFunction(const FunctionT *F, const BranchProbabilityInfoT *BPI,
1347 const LoopInfoT *LI);
1348 BlockFrequencyInfoImpl() : BPI(0), LI(0), F(0) {}
1350 using BlockFrequencyInfoImplBase::getEntryFreq;
1351 BlockFrequency getBlockFreq(const BlockT *BB) const {
1352 return BlockFrequencyInfoImplBase::getBlockFreq(getNode(BB));
1354 Float getFloatingBlockFreq(const BlockT *BB) const {
1355 return BlockFrequencyInfoImplBase::getFloatingBlockFreq(getNode(BB));
1358 /// \brief Print the frequencies for the current function.
1360 /// Prints the frequencies for the blocks in the current function.
1362 /// Blocks are printed in the natural iteration order of the function, rather
1363 /// than reverse post-order. This provides two advantages: writing -analyze
1364 /// tests is easier (since blocks come out in source order), and even
1365 /// unreachable blocks are printed.
1367 /// \a BlockFrequencyInfoImplBase::print() only knows reverse post-order, so
1368 /// we need to override it here.
1369 raw_ostream &print(raw_ostream &OS) const override;
1370 using BlockFrequencyInfoImplBase::dump;
1372 using BlockFrequencyInfoImplBase::printBlockFreq;
1373 raw_ostream &printBlockFreq(raw_ostream &OS, const BlockT *BB) const {
1374 return BlockFrequencyInfoImplBase::printBlockFreq(OS, getNode(BB));
1379 void BlockFrequencyInfoImpl<BT>::doFunction(const FunctionT *F,
1380 const BranchProbabilityInfoT *BPI,
1381 const LoopInfoT *LI) {
1382 // Save the parameters.
1387 // Clean up left-over data structures.
1388 BlockFrequencyInfoImplBase::clear();
1393 DEBUG(dbgs() << "\nblock-frequency: " << F->getName() << "\n================="
1394 << std::string(F->getName().size(), '=') << "\n");
1398 // Visit loops in post-order to find thelocal mass distribution, and then do
1399 // the full function.
1400 computeMassInLoops();
1401 computeMassInFunction();
1405 template <class BT> void BlockFrequencyInfoImpl<BT>::initializeRPOT() {
1406 const BlockT *Entry = F->begin();
1407 RPOT.reserve(F->size());
1408 std::copy(po_begin(Entry), po_end(Entry), std::back_inserter(RPOT));
1409 std::reverse(RPOT.begin(), RPOT.end());
1411 assert(RPOT.size() - 1 <= BlockNode::getMaxIndex() &&
1412 "More nodes in function than Block Frequency Info supports");
1414 DEBUG(dbgs() << "reverse-post-order-traversal\n");
1415 for (rpot_iterator I = rpot_begin(), E = rpot_end(); I != E; ++I) {
1416 BlockNode Node = getNode(I);
1417 DEBUG(dbgs() << " - " << getIndex(I) << ": " << getBlockName(Node) << "\n");
1421 Working.resize(RPOT.size());
1422 Freqs.resize(RPOT.size());
1425 template <class BT> void BlockFrequencyInfoImpl<BT>::initializeLoops() {
1426 DEBUG(dbgs() << "loop-detection\n");
1430 // Visit loops top down and assign them an index.
1431 std::deque<const LoopT *> Q;
1432 Q.insert(Q.end(), LI->begin(), LI->end());
1433 while (!Q.empty()) {
1434 const LoopT *Loop = Q.front();
1436 Q.insert(Q.end(), Loop->begin(), Loop->end());
1438 // Save the order this loop was visited.
1439 BlockNode Header = getNode(Loop->getHeader());
1440 assert(Header.isValid());
1442 Loops.emplace_back(Header);
1443 Working[Header.Index].Loop = &Loops.back();
1444 DEBUG(dbgs() << " - loop = " << getBlockName(Header) << "\n");
1447 // Visit nodes in reverse post-order and add them to their deepest containing
1449 for (size_t Index = 0; Index < RPOT.size(); ++Index) {
1450 const LoopT *Loop = LI->getLoopFor(RPOT[Index]);
1454 // If this is a loop header, find its parent loop (if any).
1455 if (Working[Index].isLoopHeader())
1456 if (!(Loop = Loop->getParentLoop()))
1459 // Add this node to its containing loop's member list.
1460 BlockNode Header = getNode(Loop->getHeader());
1461 assert(Header.isValid());
1462 const auto &HeaderData = Working[Header.Index];
1463 assert(HeaderData.isLoopHeader());
1465 Working[Index].ContainingLoop = HeaderData.Loop;
1466 HeaderData.Loop->Members.push_back(Index);
1467 DEBUG(dbgs() << " - loop = " << getBlockName(Header)
1468 << ": member = " << getBlockName(Index) << "\n");
1472 template <class BT> void BlockFrequencyInfoImpl<BT>::computeMassInLoops() {
1473 // Visit loops with the deepest first, and the top-level loops last.
1474 for (auto L = Loops.rbegin(), E = Loops.rend(); L != E; ++L)
1475 computeMassInLoop(L->Header);
1479 void BlockFrequencyInfoImpl<BT>::computeMassInLoop(const BlockNode &LoopHead) {
1480 // Compute mass in loop.
1481 DEBUG(dbgs() << "compute-mass-in-loop: " << getBlockName(LoopHead) << "\n");
1483 Working[LoopHead.Index].Mass = BlockMass::getFull();
1484 propagateMassToSuccessors(LoopHead, LoopHead);
1486 for (const BlockNode &M : getLoopPackage(LoopHead).Members)
1487 propagateMassToSuccessors(LoopHead, M);
1489 computeLoopScale(LoopHead);
1490 packageLoop(LoopHead);
1493 template <class BT> void BlockFrequencyInfoImpl<BT>::computeMassInFunction() {
1494 // Compute mass in function.
1495 DEBUG(dbgs() << "compute-mass-in-function\n");
1496 assert(!Working.empty() && "no blocks in function");
1497 assert(!Working[0].isLoopHeader() && "entry block is a loop header");
1499 Working[0].Mass = BlockMass::getFull();
1500 for (rpot_iterator I = rpot_begin(), IE = rpot_end(); I != IE; ++I) {
1501 // Check for nodes that have been packaged.
1502 BlockNode Node = getNode(I);
1503 if (Working[Node.Index].hasLoopHeader())
1506 propagateMassToSuccessors(BlockNode(), Node);
1512 BlockFrequencyInfoImpl<BT>::propagateMassToSuccessors(const BlockNode &LoopHead,
1513 const BlockNode &Node) {
1514 DEBUG(dbgs() << " - node: " << getBlockName(Node) << "\n");
1515 // Calculate probability for successors.
1517 if (Node != LoopHead && Working[Node.Index].isLoopHeader())
1518 addLoopSuccessorsToDist(LoopHead, Node, Dist);
1520 const BlockT *BB = getBlock(Node);
1521 for (auto SI = Successor::child_begin(BB), SE = Successor::child_end(BB);
1523 // Do not dereference SI, or getEdgeWeight() is linear in the number of
1525 addToDist(Dist, LoopHead, Node, getNode(*SI), BPI->getEdgeWeight(BB, SI));
1528 // Distribute mass to successors, saving exit and backedge data in the
1530 distributeMass(Node, LoopHead, Dist);
1534 raw_ostream &BlockFrequencyInfoImpl<BT>::print(raw_ostream &OS) const {
1537 OS << "block-frequency-info: " << F->getName() << "\n";
1538 for (const BlockT &BB : *F)
1539 OS << " - " << bfi_detail::getBlockName(&BB)
1540 << ": float = " << getFloatingBlockFreq(&BB)
1541 << ", int = " << getBlockFreq(&BB).getFrequency() << "\n";
1543 // Add an extra newline for readability.