MC: range-loopify
[oota-llvm.git] / include / llvm / Analysis / BlockFrequencyInfoImpl.h
1 //==- BlockFrequencyInfoImpl.h - Block Frequency Implementation -*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // Shared implementation of BlockFrequency for IR and Machine Instructions.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #ifndef LLVM_ANALYSIS_BLOCKFREQUENCYINFOIMPL_H
15 #define LLVM_ANALYSIS_BLOCKFREQUENCYINFOIMPL_H
16
17 #include "llvm/ADT/DenseMap.h"
18 #include "llvm/ADT/PostOrderIterator.h"
19 #include "llvm/ADT/iterator_range.h"
20 #include "llvm/IR/BasicBlock.h"
21 #include "llvm/Support/BlockFrequency.h"
22 #include "llvm/Support/BranchProbability.h"
23 #include "llvm/Support/Debug.h"
24 #include "llvm/Support/raw_ostream.h"
25 #include <string>
26 #include <vector>
27 #include <list>
28
29 #define DEBUG_TYPE "block-freq"
30
31 //===----------------------------------------------------------------------===//
32 //
33 // UnsignedFloat definition.
34 //
35 // TODO: Make this private to BlockFrequencyInfoImpl or delete.
36 //
37 //===----------------------------------------------------------------------===//
38 namespace llvm {
39
40 class UnsignedFloatBase {
41 public:
42   static const int32_t MaxExponent = 16383;
43   static const int32_t MinExponent = -16382;
44   static const int DefaultPrecision = 10;
45
46   static void dump(uint64_t D, int16_t E, int Width);
47   static raw_ostream &print(raw_ostream &OS, uint64_t D, int16_t E, int Width,
48                             unsigned Precision);
49   static std::string toString(uint64_t D, int16_t E, int Width,
50                               unsigned Precision);
51   static int countLeadingZeros32(uint32_t N) { return countLeadingZeros(N); }
52   static int countLeadingZeros64(uint64_t N) { return countLeadingZeros(N); }
53   static uint64_t getHalf(uint64_t N) { return (N >> 1) + (N & 1); }
54
55   static std::pair<uint64_t, bool> splitSigned(int64_t N) {
56     if (N >= 0)
57       return std::make_pair(N, false);
58     uint64_t Unsigned = N == INT64_MIN ? UINT64_C(1) << 63 : uint64_t(-N);
59     return std::make_pair(Unsigned, true);
60   }
61   static int64_t joinSigned(uint64_t U, bool IsNeg) {
62     if (U > uint64_t(INT64_MAX))
63       return IsNeg ? INT64_MIN : INT64_MAX;
64     return IsNeg ? -int64_t(U) : int64_t(U);
65   }
66
67   static int32_t extractLg(const std::pair<int32_t, int> &Lg) {
68     return Lg.first;
69   }
70   static int32_t extractLgFloor(const std::pair<int32_t, int> &Lg) {
71     return Lg.first - (Lg.second > 0);
72   }
73   static int32_t extractLgCeiling(const std::pair<int32_t, int> &Lg) {
74     return Lg.first + (Lg.second < 0);
75   }
76
77   static std::pair<uint64_t, int16_t> divide64(uint64_t L, uint64_t R);
78   static std::pair<uint64_t, int16_t> multiply64(uint64_t L, uint64_t R);
79
80   static int compare(uint64_t L, uint64_t R, int Shift) {
81     assert(Shift >= 0);
82     assert(Shift < 64);
83
84     uint64_t L_adjusted = L >> Shift;
85     if (L_adjusted < R)
86       return -1;
87     if (L_adjusted > R)
88       return 1;
89
90     return L > L_adjusted << Shift ? 1 : 0;
91   }
92 };
93
94 /// \brief Simple representation of an unsigned floating point.
95 ///
96 /// UnsignedFloat is a unsigned floating point number.  It uses simple
97 /// saturation arithmetic, and every operation is well-defined for every value.
98 ///
99 /// The number is split into a signed exponent and unsigned digits.  The number
100 /// represented is \c getDigits()*2^getExponent().  In this way, the digits are
101 /// much like the mantissa in the x87 long double, but there is no canonical
102 /// form, so the same number can be represented by many bit representations
103 /// (it's always in "denormal" mode).
104 ///
105 /// UnsignedFloat is templated on the underlying integer type for digits, which
106 /// is expected to be one of uint64_t, uint32_t, uint16_t or uint8_t.
107 ///
108 /// Unlike builtin floating point types, UnsignedFloat is portable.
109 ///
110 /// Unlike APFloat, UnsignedFloat does not model architecture floating point
111 /// behaviour (this should make it a little faster), and implements most
112 /// operators (this makes it usable).
113 ///
114 /// UnsignedFloat is totally ordered.  However, there is no canonical form, so
115 /// there are multiple representations of most scalars.  E.g.:
116 ///
117 ///     UnsignedFloat(8u, 0) == UnsignedFloat(4u, 1)
118 ///     UnsignedFloat(4u, 1) == UnsignedFloat(2u, 2)
119 ///     UnsignedFloat(2u, 2) == UnsignedFloat(1u, 3)
120 ///
121 /// UnsignedFloat implements most arithmetic operations.  Precision is kept
122 /// where possible.  Uses simple saturation arithmetic, so that operations
123 /// saturate to 0.0 or getLargest() rather than under or overflowing.  It has
124 /// some extra arithmetic for unit inversion.  0.0/0.0 is defined to be 0.0.
125 /// Any other division by 0.0 is defined to be getLargest().
126 ///
127 /// As a convenience for modifying the exponent, left and right shifting are
128 /// both implemented, and both interpret negative shifts as positive shifts in
129 /// the opposite direction.
130 ///
131 /// Exponents are limited to the range accepted by x87 long double.  This makes
132 /// it trivial to add functionality to convert to APFloat (this is already
133 /// relied on for the implementation of printing).
134 ///
135 /// The current plan is to gut this and make the necessary parts of it (even
136 /// more) private to BlockFrequencyInfo.
137 template <class DigitsT> class UnsignedFloat : UnsignedFloatBase {
138 public:
139   static_assert(!std::numeric_limits<DigitsT>::is_signed,
140                 "only unsigned floats supported");
141
142   typedef DigitsT DigitsType;
143
144 private:
145   typedef std::numeric_limits<DigitsType> DigitsLimits;
146
147   static const int Width = sizeof(DigitsType) * 8;
148   static_assert(Width <= 64, "invalid integer width for digits");
149
150 private:
151   DigitsType Digits;
152   int16_t Exponent;
153
154 public:
155   UnsignedFloat() : Digits(0), Exponent(0) {}
156
157   UnsignedFloat(DigitsType Digits, int16_t Exponent)
158       : Digits(Digits), Exponent(Exponent) {}
159
160 private:
161   UnsignedFloat(const std::pair<uint64_t, int16_t> &X)
162       : Digits(X.first), Exponent(X.second) {}
163
164 public:
165   static UnsignedFloat getZero() { return UnsignedFloat(0, 0); }
166   static UnsignedFloat getOne() { return UnsignedFloat(1, 0); }
167   static UnsignedFloat getLargest() {
168     return UnsignedFloat(DigitsLimits::max(), MaxExponent);
169   }
170   static UnsignedFloat getFloat(uint64_t N) { return adjustToWidth(N, 0); }
171   static UnsignedFloat getInverseFloat(uint64_t N) {
172     return getFloat(N).invert();
173   }
174   static UnsignedFloat getFraction(DigitsType N, DigitsType D) {
175     return getQuotient(N, D);
176   }
177
178   int16_t getExponent() const { return Exponent; }
179   DigitsType getDigits() const { return Digits; }
180
181   /// \brief Convert to the given integer type.
182   ///
183   /// Convert to \c IntT using simple saturating arithmetic, truncating if
184   /// necessary.
185   template <class IntT> IntT toInt() const;
186
187   bool isZero() const { return !Digits; }
188   bool isLargest() const { return *this == getLargest(); }
189   bool isOne() const {
190     if (Exponent > 0 || Exponent <= -Width)
191       return false;
192     return Digits == DigitsType(1) << -Exponent;
193   }
194
195   /// \brief The log base 2, rounded.
196   ///
197   /// Get the lg of the scalar.  lg 0 is defined to be INT32_MIN.
198   int32_t lg() const { return extractLg(lgImpl()); }
199
200   /// \brief The log base 2, rounded towards INT32_MIN.
201   ///
202   /// Get the lg floor.  lg 0 is defined to be INT32_MIN.
203   int32_t lgFloor() const { return extractLgFloor(lgImpl()); }
204
205   /// \brief The log base 2, rounded towards INT32_MAX.
206   ///
207   /// Get the lg ceiling.  lg 0 is defined to be INT32_MIN.
208   int32_t lgCeiling() const { return extractLgCeiling(lgImpl()); }
209
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; }
215   bool operator>=(const UnsignedFloat &X) const { return compare(X) >= 0; }
216
217   bool operator!() const { return isZero(); }
218
219   /// \brief Convert to a decimal representation in a string.
220   ///
221   /// Convert to a string.  Uses scientific notation for very large/small
222   /// numbers.  Scientific notation is used roughly for numbers outside of the
223   /// range 2^-64 through 2^64.
224   ///
225   /// \c Precision indicates the number of decimal digits of precision to use;
226   /// 0 requests the maximum available.
227   ///
228   /// As a special case to make debugging easier, if the number is small enough
229   /// to convert without scientific notation and has more than \c Precision
230   /// digits before the decimal place, it's printed accurately to the first
231   /// digit past zero.  E.g., assuming 10 digits of precision:
232   ///
233   ///     98765432198.7654... => 98765432198.8
234   ///      8765432198.7654... =>  8765432198.8
235   ///       765432198.7654... =>   765432198.8
236   ///        65432198.7654... =>    65432198.77
237   ///         5432198.7654... =>     5432198.765
238   std::string toString(unsigned Precision = DefaultPrecision) {
239     return UnsignedFloatBase::toString(Digits, Exponent, Width, Precision);
240   }
241
242   /// \brief Print a decimal representation.
243   ///
244   /// Print a string.  See toString for documentation.
245   raw_ostream &print(raw_ostream &OS,
246                      unsigned Precision = DefaultPrecision) const {
247     return UnsignedFloatBase::print(OS, Digits, Exponent, Width, Precision);
248   }
249   void dump() const { return UnsignedFloatBase::dump(Digits, Exponent, Width); }
250
251   UnsignedFloat &operator+=(const UnsignedFloat &X);
252   UnsignedFloat &operator-=(const UnsignedFloat &X);
253   UnsignedFloat &operator*=(const UnsignedFloat &X);
254   UnsignedFloat &operator/=(const UnsignedFloat &X);
255   UnsignedFloat &operator<<=(int16_t Shift) { shiftLeft(Shift); return *this; }
256   UnsignedFloat &operator>>=(int16_t Shift) { shiftRight(Shift); return *this; }
257
258 private:
259   void shiftLeft(int32_t Shift);
260   void shiftRight(int32_t Shift);
261
262   /// \brief Adjust two floats to have matching exponents.
263   ///
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.
266   ///
267   /// The value that compares smaller will lose precision, and possibly become
268   /// \a isZero().
269   UnsignedFloat matchExponents(UnsignedFloat X);
270
271   /// \brief Increase exponent to match another float.
272   ///
273   /// Increases \c this to have an exponent matching \c X.  May decrease the
274   /// exponent of \c X in the process, and \c this may possibly become \a
275   /// isZero().
276   void increaseExponentToMatch(UnsignedFloat &X, int32_t ExponentDiff);
277
278 public:
279   /// \brief Scale a large number accurately.
280   ///
281   /// Scale N (multiply it by this).  Uses full precision multiplication, even
282   /// if Width is smaller than 64, so information is not lost.
283   uint64_t scale(uint64_t N) const;
284   uint64_t scaleByInverse(uint64_t N) const {
285     // TODO: implement directly, rather than relying on inverse.  Inverse is
286     // expensive.
287     return inverse().scale(N);
288   }
289   int64_t scale(int64_t N) const {
290     std::pair<uint64_t, bool> Unsigned = splitSigned(N);
291     return joinSigned(scale(Unsigned.first), Unsigned.second);
292   }
293   int64_t scaleByInverse(int64_t N) const {
294     std::pair<uint64_t, bool> Unsigned = splitSigned(N);
295     return joinSigned(scaleByInverse(Unsigned.first), Unsigned.second);
296   }
297
298   int compare(const UnsignedFloat &X) const;
299   int compareTo(uint64_t N) const {
300     UnsignedFloat Float = getFloat(N);
301     int Compare = compare(Float);
302     if (Width == 64 || Compare != 0)
303       return Compare;
304
305     // Check for precision loss.  We know *this == RoundTrip.
306     uint64_t RoundTrip = Float.template toInt<uint64_t>();
307     return N == RoundTrip ? 0 : RoundTrip < N ? -1 : 1;
308   }
309   int compareTo(int64_t N) const { return N < 0 ? 1 : compareTo(uint64_t(N)); }
310
311   UnsignedFloat &invert() { return *this = UnsignedFloat::getFloat(1) / *this; }
312   UnsignedFloat inverse() const { return UnsignedFloat(*this).invert(); }
313
314 private:
315   static UnsignedFloat getProduct(DigitsType L, DigitsType R);
316   static UnsignedFloat getQuotient(DigitsType Dividend, DigitsType Divisor);
317
318   std::pair<int32_t, int> lgImpl() const;
319   static int countLeadingZerosWidth(DigitsType Digits) {
320     if (Width == 64)
321       return countLeadingZeros64(Digits);
322     if (Width == 32)
323       return countLeadingZeros32(Digits);
324     return countLeadingZeros32(Digits) + Width - 32;
325   }
326
327   static UnsignedFloat adjustToWidth(uint64_t N, int32_t S) {
328     assert(S >= MinExponent);
329     assert(S <= MaxExponent);
330     if (Width == 64 || N <= DigitsLimits::max())
331       return UnsignedFloat(N, S);
332
333     // Shift right.
334     int Shift = 64 - Width - countLeadingZeros64(N);
335     DigitsType Shifted = N >> Shift;
336
337     // Round.
338     assert(S + Shift <= MaxExponent);
339     return getRounded(UnsignedFloat(Shifted, S + Shift),
340                       N & UINT64_C(1) << (Shift - 1));
341   }
342
343   static UnsignedFloat getRounded(UnsignedFloat P, bool Round) {
344     if (!Round)
345       return P;
346     if (P.Digits == DigitsLimits::max())
347       // Careful of overflow in the exponent.
348       return UnsignedFloat(1, P.Exponent) <<= Width;
349     return UnsignedFloat(P.Digits + 1, P.Exponent);
350   }
351 };
352
353 #define UNSIGNED_FLOAT_BOP(op, base)                                           \
354   template <class DigitsT>                                                     \
355   UnsignedFloat<DigitsT> operator op(const UnsignedFloat<DigitsT> &L,          \
356                                      const UnsignedFloat<DigitsT> &R) {        \
357     return UnsignedFloat<DigitsT>(L) base R;                                   \
358   }
359 UNSIGNED_FLOAT_BOP(+, += )
360 UNSIGNED_FLOAT_BOP(-, -= )
361 UNSIGNED_FLOAT_BOP(*, *= )
362 UNSIGNED_FLOAT_BOP(/, /= )
363 UNSIGNED_FLOAT_BOP(<<, <<= )
364 UNSIGNED_FLOAT_BOP(>>, >>= )
365 #undef UNSIGNED_FLOAT_BOP
366
367 template <class DigitsT>
368 raw_ostream &operator<<(raw_ostream &OS, const UnsignedFloat<DigitsT> &X) {
369   return X.print(OS, 10);
370 }
371
372 #define UNSIGNED_FLOAT_COMPARE_TO_TYPE(op, T1, T2)                             \
373   template <class DigitsT>                                                     \
374   bool operator op(const UnsignedFloat<DigitsT> &L, T1 R) {                    \
375     return L.compareTo(T2(R)) op 0;                                            \
376   }                                                                            \
377   template <class DigitsT>                                                     \
378   bool operator op(T1 L, const UnsignedFloat<DigitsT> &R) {                    \
379     return 0 op R.compareTo(T2(L));                                            \
380   }
381 #define UNSIGNED_FLOAT_COMPARE_TO(op)                                          \
382   UNSIGNED_FLOAT_COMPARE_TO_TYPE(op, uint64_t, uint64_t)                       \
383   UNSIGNED_FLOAT_COMPARE_TO_TYPE(op, uint32_t, uint64_t)                       \
384   UNSIGNED_FLOAT_COMPARE_TO_TYPE(op, int64_t, int64_t)                         \
385   UNSIGNED_FLOAT_COMPARE_TO_TYPE(op, int32_t, int64_t)
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 UNSIGNED_FLOAT_COMPARE_TO(>= )
392 #undef UNSIGNED_FLOAT_COMPARE_TO
393 #undef UNSIGNED_FLOAT_COMPARE_TO_TYPE
394
395 template <class DigitsT>
396 uint64_t UnsignedFloat<DigitsT>::scale(uint64_t N) const {
397   if (Width == 64 || N <= DigitsLimits::max())
398     return (getFloat(N) * *this).template toInt<uint64_t>();
399
400   // Defer to the 64-bit version.
401   return UnsignedFloat<uint64_t>(Digits, Exponent).scale(N);
402 }
403
404 template <class DigitsT>
405 UnsignedFloat<DigitsT> UnsignedFloat<DigitsT>::getProduct(DigitsType L,
406                                                           DigitsType R) {
407   // Check for zero.
408   if (!L || !R)
409     return getZero();
410
411   // Check for numbers that we can compute with 64-bit math.
412   if (Width <= 32 || (L <= UINT32_MAX && R <= UINT32_MAX))
413     return adjustToWidth(uint64_t(L) * uint64_t(R), 0);
414
415   // Do the full thing.
416   return UnsignedFloat(multiply64(L, R));
417 }
418 template <class DigitsT>
419 UnsignedFloat<DigitsT> UnsignedFloat<DigitsT>::getQuotient(DigitsType Dividend,
420                                                            DigitsType Divisor) {
421   // Check for zero.
422   if (!Dividend)
423     return getZero();
424   if (!Divisor)
425     return getLargest();
426
427   if (Width == 64)
428     return UnsignedFloat(divide64(Dividend, Divisor));
429
430   // We can compute this with 64-bit math.
431   int Shift = countLeadingZeros64(Dividend);
432   uint64_t Shifted = uint64_t(Dividend) << Shift;
433   uint64_t Quotient = Shifted / Divisor;
434
435   // If Quotient needs to be shifted, then adjustToWidth will round.
436   if (Quotient > DigitsLimits::max())
437     return adjustToWidth(Quotient, -Shift);
438
439   // Round based on the value of the next bit.
440   return getRounded(UnsignedFloat(Quotient, -Shift),
441                     Shifted % Divisor >= getHalf(Divisor));
442 }
443
444 template <class DigitsT>
445 template <class IntT>
446 IntT UnsignedFloat<DigitsT>::toInt() const {
447   typedef std::numeric_limits<IntT> Limits;
448   if (*this < 1)
449     return 0;
450   if (*this >= Limits::max())
451     return Limits::max();
452
453   IntT N = Digits;
454   if (Exponent > 0) {
455     assert(size_t(Exponent) < sizeof(IntT) * 8);
456     return N << Exponent;
457   }
458   if (Exponent < 0) {
459     assert(size_t(-Exponent) < sizeof(IntT) * 8);
460     return N >> -Exponent;
461   }
462   return N;
463 }
464
465 template <class DigitsT>
466 std::pair<int32_t, int> UnsignedFloat<DigitsT>::lgImpl() const {
467   if (isZero())
468     return std::make_pair(INT32_MIN, 0);
469
470   // Get the floor of the lg of Digits.
471   int32_t LocalFloor = Width - countLeadingZerosWidth(Digits) - 1;
472
473   // Get the floor of the lg of this.
474   int32_t Floor = Exponent + LocalFloor;
475   if (Digits == UINT64_C(1) << LocalFloor)
476     return std::make_pair(Floor, 0);
477
478   // Round based on the next digit.
479   assert(LocalFloor >= 1);
480   bool Round = Digits & UINT64_C(1) << (LocalFloor - 1);
481   return std::make_pair(Floor + Round, Round ? 1 : -1);
482 }
483
484 template <class DigitsT>
485 UnsignedFloat<DigitsT> UnsignedFloat<DigitsT>::matchExponents(UnsignedFloat X) {
486   if (isZero() || X.isZero() || Exponent == X.Exponent)
487     return X;
488
489   int32_t Diff = int32_t(X.Exponent) - int32_t(Exponent);
490   if (Diff > 0)
491     increaseExponentToMatch(X, Diff);
492   else
493     X.increaseExponentToMatch(*this, -Diff);
494   return X;
495 }
496 template <class DigitsT>
497 void UnsignedFloat<DigitsT>::increaseExponentToMatch(UnsignedFloat &X,
498                                                      int32_t ExponentDiff) {
499   assert(ExponentDiff > 0);
500   if (ExponentDiff >= 2 * Width) {
501     *this = getZero();
502     return;
503   }
504
505   // Use up any leading zeros on X, and then shift this.
506   int32_t ShiftX = std::min(countLeadingZerosWidth(X.Digits), ExponentDiff);
507   assert(ShiftX < Width);
508
509   int32_t ShiftThis = ExponentDiff - ShiftX;
510   if (ShiftThis >= Width) {
511     *this = getZero();
512     return;
513   }
514
515   X.Digits <<= ShiftX;
516   X.Exponent -= ShiftX;
517   Digits >>= ShiftThis;
518   Exponent += ShiftThis;
519   return;
520 }
521
522 template <class DigitsT>
523 UnsignedFloat<DigitsT> &UnsignedFloat<DigitsT>::
524 operator+=(const UnsignedFloat &X) {
525   if (isLargest() || X.isZero())
526     return *this;
527   if (isZero() || X.isLargest())
528     return *this = X;
529
530   // Normalize exponents.
531   UnsignedFloat Scaled = matchExponents(X);
532
533   // Check for zero again.
534   if (isZero())
535     return *this = Scaled;
536   if (Scaled.isZero())
537     return *this;
538
539   // Compute sum.
540   DigitsType Sum = Digits + Scaled.Digits;
541   bool DidOverflow = Sum < Digits;
542   Digits = Sum;
543   if (!DidOverflow)
544     return *this;
545
546   if (Exponent == MaxExponent)
547     return *this = getLargest();
548
549   ++Exponent;
550   Digits = UINT64_C(1) << (Width - 1) | Digits >> 1;
551
552   return *this;
553 }
554 template <class DigitsT>
555 UnsignedFloat<DigitsT> &UnsignedFloat<DigitsT>::
556 operator-=(const UnsignedFloat &X) {
557   if (X.isZero())
558     return *this;
559   if (*this <= X)
560     return *this = getZero();
561
562   // Normalize exponents.
563   UnsignedFloat Scaled = matchExponents(X);
564   assert(Digits >= Scaled.Digits);
565
566   // Compute difference.
567   if (!Scaled.isZero()) {
568     Digits -= Scaled.Digits;
569     return *this;
570   }
571
572   // Check if X just barely lost its last bit.  E.g., for 32-bit:
573   //
574   //   1*2^32 - 1*2^0 == 0xffffffff != 1*2^32
575   if (*this == UnsignedFloat(1, X.lgFloor() + Width)) {
576     Digits = DigitsType(0) - 1;
577     --Exponent;
578   }
579   return *this;
580 }
581 template <class DigitsT>
582 UnsignedFloat<DigitsT> &UnsignedFloat<DigitsT>::
583 operator*=(const UnsignedFloat &X) {
584   if (isZero())
585     return *this;
586   if (X.isZero())
587     return *this = X;
588
589   // Save the exponents.
590   int32_t Exponents = int32_t(Exponent) + int32_t(X.Exponent);
591
592   // Get the raw product.
593   *this = getProduct(Digits, X.Digits);
594
595   // Combine with exponents.
596   return *this <<= Exponents;
597 }
598 template <class DigitsT>
599 UnsignedFloat<DigitsT> &UnsignedFloat<DigitsT>::
600 operator/=(const UnsignedFloat &X) {
601   if (isZero())
602     return *this;
603   if (X.isZero())
604     return *this = getLargest();
605
606   // Save the exponents.
607   int32_t Exponents = int32_t(Exponent) - int32_t(X.Exponent);
608
609   // Get the raw quotient.
610   *this = getQuotient(Digits, X.Digits);
611
612   // Combine with exponents.
613   return *this <<= Exponents;
614 }
615 template <class DigitsT>
616 void UnsignedFloat<DigitsT>::shiftLeft(int32_t Shift) {
617   if (!Shift || isZero())
618     return;
619   assert(Shift != INT32_MIN);
620   if (Shift < 0) {
621     shiftRight(-Shift);
622     return;
623   }
624
625   // Shift as much as we can in the exponent.
626   int32_t ExponentShift = std::min(Shift, MaxExponent - Exponent);
627   Exponent += ExponentShift;
628   if (ExponentShift == Shift)
629     return;
630
631   // Check this late, since it's rare.
632   if (isLargest())
633     return;
634
635   // Shift the digits themselves.
636   Shift -= ExponentShift;
637   if (Shift > countLeadingZerosWidth(Digits)) {
638     // Saturate.
639     *this = getLargest();
640     return;
641   }
642
643   Digits <<= Shift;
644   return;
645 }
646
647 template <class DigitsT>
648 void UnsignedFloat<DigitsT>::shiftRight(int32_t Shift) {
649   if (!Shift || isZero())
650     return;
651   assert(Shift != INT32_MIN);
652   if (Shift < 0) {
653     shiftLeft(-Shift);
654     return;
655   }
656
657   // Shift as much as we can in the exponent.
658   int32_t ExponentShift = std::min(Shift, Exponent - MinExponent);
659   Exponent -= ExponentShift;
660   if (ExponentShift == Shift)
661     return;
662
663   // Shift the digits themselves.
664   Shift -= ExponentShift;
665   if (Shift >= Width) {
666     // Saturate.
667     *this = getZero();
668     return;
669   }
670
671   Digits >>= Shift;
672   return;
673 }
674
675 template <class DigitsT>
676 int UnsignedFloat<DigitsT>::compare(const UnsignedFloat &X) const {
677   // Check for zero.
678   if (isZero())
679     return X.isZero() ? 0 : -1;
680   if (X.isZero())
681     return 1;
682
683   // Check for the scale.  Use lgFloor to be sure that the exponent difference
684   // is always lower than 64.
685   int32_t lgL = lgFloor(), lgR = X.lgFloor();
686   if (lgL != lgR)
687     return lgL < lgR ? -1 : 1;
688
689   // Compare digits.
690   if (Exponent < X.Exponent)
691     return UnsignedFloatBase::compare(Digits, X.Digits, X.Exponent - Exponent);
692
693   return -UnsignedFloatBase::compare(X.Digits, Digits, Exponent - X.Exponent);
694 }
695
696 template <class T> struct isPodLike<UnsignedFloat<T>> {
697   static const bool value = true;
698 };
699 }
700
701 //===----------------------------------------------------------------------===//
702 //
703 // BlockMass definition.
704 //
705 // TODO: Make this private to BlockFrequencyInfoImpl or delete.
706 //
707 //===----------------------------------------------------------------------===//
708 namespace llvm {
709
710 /// \brief Mass of a block.
711 ///
712 /// This class implements a sort of fixed-point fraction always between 0.0 and
713 /// 1.0.  getMass() == UINT64_MAX indicates a value of 1.0.
714 ///
715 /// Masses can be added and subtracted.  Simple saturation arithmetic is used,
716 /// so arithmetic operations never overflow or underflow.
717 ///
718 /// Masses can be multiplied.  Multiplication treats full mass as 1.0 and uses
719 /// an inexpensive floating-point algorithm that's off-by-one (almost, but not
720 /// quite, maximum precision).
721 ///
722 /// Masses can be scaled by \a BranchProbability at maximum precision.
723 class BlockMass {
724   uint64_t Mass;
725
726 public:
727   BlockMass() : Mass(0) {}
728   explicit BlockMass(uint64_t Mass) : Mass(Mass) {}
729
730   static BlockMass getEmpty() { return BlockMass(); }
731   static BlockMass getFull() { return BlockMass(UINT64_MAX); }
732
733   uint64_t getMass() const { return Mass; }
734
735   bool isFull() const { return Mass == UINT64_MAX; }
736   bool isEmpty() const { return !Mass; }
737
738   bool operator!() const { return isEmpty(); }
739
740   /// \brief Add another mass.
741   ///
742   /// Adds another mass, saturating at \a isFull() rather than overflowing.
743   BlockMass &operator+=(const BlockMass &X) {
744     uint64_t Sum = Mass + X.Mass;
745     Mass = Sum < Mass ? UINT64_MAX : Sum;
746     return *this;
747   }
748
749   /// \brief Subtract another mass.
750   ///
751   /// Subtracts another mass, saturating at \a isEmpty() rather than
752   /// undeflowing.
753   BlockMass &operator-=(const BlockMass &X) {
754     uint64_t Diff = Mass - X.Mass;
755     Mass = Diff > Mass ? 0 : Diff;
756     return *this;
757   }
758
759   /// \brief Scale by another mass.
760   ///
761   /// The current implementation is a little imprecise, but it's relatively
762   /// fast, never overflows, and maintains the property that 1.0*1.0==1.0
763   /// (where isFull represents the number 1.0).  It's an approximation of
764   /// 128-bit multiply that gets right-shifted by 64-bits.
765   ///
766   /// For a given digit size, multiplying two-digit numbers looks like:
767   ///
768   ///                  U1 .    L1
769   ///                * U2 .    L2
770   ///                ============
771   ///           0 .       . L1*L2
772   ///     +     0 . U1*L2 .     0 // (shift left once by a digit-size)
773   ///     +     0 . U2*L1 .     0 // (shift left once by a digit-size)
774   ///     + U1*L2 .     0 .     0 // (shift left twice by a digit-size)
775   ///
776   /// BlockMass has 64-bit numbers.  Split each into two 32-bit digits, stored
777   /// 64-bit.  Add 1 to the lower digits, to model isFull as 1.0; this won't
778   /// overflow, since we have 64-bit storage for each digit.
779   ///
780   /// To do this accurately, (a) multiply into two 64-bit digits, incrementing
781   /// the upper digit on overflows of the lower digit (carry), (b) subtract 1
782   /// from the lower digit, decrementing the upper digit on underflow (carry),
783   /// and (c) truncate the lower digit.  For the 1.0*1.0 case, the upper digit
784   /// will be 0 at the end of step (a), and then will underflow back to isFull
785   /// (1.0) in step (b).
786   ///
787   /// Instead, the implementation does something a little faster with a small
788   /// loss of accuracy: ignore the lower 64-bit digit entirely.  The loss of
789   /// accuracy is small, since the sum of the unmodelled carries is 0 or 1
790   /// (i.e., step (a) will overflow at most once, and step (b) will underflow
791   /// only if step (a) overflows).
792   ///
793   /// This is the formula we're calculating:
794   ///
795   ///     U1.L1 * U2.L2 == U1 * U2 + (U1 * (L2+1))>>32 + (U2 * (L1+1))>>32
796   ///
797   /// As a demonstration of 1.0*1.0, consider two 4-bit numbers that are both
798   /// full (1111).
799   ///
800   ///     U1.L1 * U2.L2 == U1 * U2 + (U1 * (L2+1))>>2 + (U2 * (L1+1))>>2
801   ///     11.11 * 11.11 == 11 * 11 + (11 * (11+1))/4 + (11 * (11+1))/4
802   ///                   == 1001 + (11 * 100)/4 + (11 * 100)/4
803   ///                   == 1001 + 1100/4 + 1100/4
804   ///                   == 1001 + 0011 + 0011
805   ///                   == 1111
806   BlockMass &operator*=(const BlockMass &X) {
807     uint64_t U1 = Mass >> 32, L1 = Mass & UINT32_MAX, U2 = X.Mass >> 32,
808              L2 = X.Mass & UINT32_MAX;
809     Mass = U1 * U2 + (U1 * (L2 + 1) >> 32) + ((L1 + 1) * U2 >> 32);
810     return *this;
811   }
812
813   /// \brief Multiply by a branch probability.
814   ///
815   /// Multiply by P.  Guarantees full precision.
816   ///
817   /// This could be naively implemented by multiplying by the numerator and
818   /// dividing by the denominator, but in what order?  Multiplying first can
819   /// overflow, while dividing first will lose precision (potentially, changing
820   /// a non-zero mass to zero).
821   ///
822   /// The implementation mixes the two methods.  Since \a BranchProbability
823   /// uses 32-bits and \a BlockMass 64-bits, shift the mass as far to the left
824   /// as there is room, then divide by the denominator to get a quotient.
825   /// Multiplying by the numerator and right shifting gives a first
826   /// approximation.
827   ///
828   /// Calculate the error in this first approximation by calculating the
829   /// opposite mass (multiply by the opposite numerator and shift) and
830   /// subtracting both from teh original mass.
831   ///
832   /// Add to the first approximation the correct fraction of this error value.
833   /// This time, multiply first and then divide, since there is no danger of
834   /// overflow.
835   ///
836   /// \pre P represents a fraction between 0.0 and 1.0.
837   BlockMass &operator*=(const BranchProbability &P);
838
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; }
844   bool operator>(const BlockMass &X) const { return Mass > X.Mass; }
845
846   /// \brief Convert to floating point.
847   ///
848   /// Convert to a float.  \a isFull() gives 1.0, while \a isEmpty() gives
849   /// slightly above 0.0.
850   UnsignedFloat<uint64_t> toFloat() const;
851
852   void dump() const;
853   raw_ostream &print(raw_ostream &OS) const;
854 };
855
856 inline BlockMass operator+(const BlockMass &L, const BlockMass &R) {
857   return BlockMass(L) += R;
858 }
859 inline BlockMass operator-(const BlockMass &L, const BlockMass &R) {
860   return BlockMass(L) -= R;
861 }
862 inline BlockMass operator*(const BlockMass &L, const BlockMass &R) {
863   return BlockMass(L) *= R;
864 }
865 inline BlockMass operator*(const BlockMass &L, const BranchProbability &R) {
866   return BlockMass(L) *= R;
867 }
868 inline BlockMass operator*(const BranchProbability &L, const BlockMass &R) {
869   return BlockMass(R) *= L;
870 }
871
872 inline raw_ostream &operator<<(raw_ostream &OS, const BlockMass &X) {
873   return X.print(OS);
874 }
875
876 template <> struct isPodLike<BlockMass> {
877   static const bool value = true;
878 };
879 }
880
881 //===----------------------------------------------------------------------===//
882 //
883 // BlockFrequencyInfoImpl definition.
884 //
885 //===----------------------------------------------------------------------===//
886 namespace llvm {
887
888 class BasicBlock;
889 class BranchProbabilityInfo;
890 class Function;
891 class Loop;
892 class LoopInfo;
893 class MachineBasicBlock;
894 class MachineBranchProbabilityInfo;
895 class MachineFunction;
896 class MachineLoop;
897 class MachineLoopInfo;
898
899 /// \brief Base class for BlockFrequencyInfoImpl
900 ///
901 /// BlockFrequencyInfoImplBase has supporting data structures and some
902 /// algorithms for BlockFrequencyInfoImplBase.  Only algorithms that depend on
903 /// the block type (or that call such algorithms) are skipped here.
904 ///
905 /// Nevertheless, the majority of the overall algorithm documention lives with
906 /// BlockFrequencyInfoImpl.  See there for details.
907 class BlockFrequencyInfoImplBase {
908 public:
909   typedef UnsignedFloat<uint64_t> Float;
910
911   /// \brief Representative of a block.
912   ///
913   /// This is a simple wrapper around an index into the reverse-post-order
914   /// traversal of the blocks.
915   ///
916   /// Unlike a block pointer, its order has meaning (location in the
917   /// topological sort) and it's class is the same regardless of block type.
918   struct BlockNode {
919     typedef uint32_t IndexType;
920     IndexType Index;
921
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; }
927     bool operator>(const BlockNode &X) const { return Index > X.Index; }
928
929     BlockNode() : Index(UINT32_MAX) {}
930     BlockNode(IndexType Index) : Index(Index) {}
931
932     bool isValid() const { return Index <= getMaxIndex(); }
933     static size_t getMaxIndex() { return UINT32_MAX - 1; }
934   };
935
936   /// \brief Stats about a block itself.
937   struct FrequencyData {
938     Float Floating;
939     uint64_t Integer;
940   };
941
942   /// \brief Data about a loop.
943   ///
944   /// Contains the data necessary to represent represent a loop as a
945   /// pseudo-node once it's packaged.
946   struct LoopData {
947     typedef SmallVector<std::pair<BlockNode, BlockMass>, 4> ExitMap;
948     typedef SmallVector<BlockNode, 4> NodeList;
949     LoopData *Parent;       ///< The parent loop.
950     bool IsPackaged;        ///< Whether this has been packaged.
951     ExitMap Exits;          ///< Successor edges (and weights).
952     NodeList Nodes;         ///< Header and the members of the loop.
953     BlockMass BackedgeMass; ///< Mass returned to loop header.
954     BlockMass Mass;
955     Float Scale;
956
957     LoopData(LoopData *Parent, const BlockNode &Header)
958         : Parent(Parent), IsPackaged(false), Nodes(1, Header) {}
959     bool isHeader(const BlockNode &Node) const { return Node == Nodes[0]; }
960     BlockNode getHeader() const { return Nodes[0]; }
961
962     NodeList::const_iterator members_begin() const { return Nodes.begin() + 1; }
963     NodeList::const_iterator members_end() const { return Nodes.end(); }
964     iterator_range<NodeList::const_iterator> members() const {
965       return make_range(members_begin(), members_end());
966     }
967   };
968
969   /// \brief Index of loop information.
970   struct WorkingData {
971     BlockNode Node; ///< This node.
972     LoopData *Loop; ///< The loop this block is inside.
973     BlockMass Mass; ///< Mass distribution from the entry block.
974
975     WorkingData(const BlockNode &Node) : Node(Node), Loop(nullptr) {}
976
977     bool isLoopHeader() const { return Loop && Loop->isHeader(Node); }
978
979     LoopData *getContainingLoop() const {
980       return isLoopHeader() ? Loop->Parent : Loop;
981     }
982
983     /// \brief Resolve a node to its representative.
984     ///
985     /// Get the node currently representing Node, which could be a containing
986     /// loop.
987     ///
988     /// This function should only be called when distributing mass.  As long as
989     /// there are no irreducilbe edges to Node, then it will have complexity
990     /// O(1) in this context.
991     ///
992     /// In general, the complexity is O(L), where L is the number of loop
993     /// headers Node has been packaged into.  Since this method is called in
994     /// the context of distributing mass, L will be the number of loop headers
995     /// an early exit edge jumps out of.
996     BlockNode getResolvedNode() const {
997       auto L = getPackagedLoop();
998       return L ? L->getHeader() : Node;
999     }
1000     LoopData *getPackagedLoop() const {
1001       if (!Loop || !Loop->IsPackaged)
1002         return nullptr;
1003       auto L = Loop;
1004       while (L->Parent && L->Parent->IsPackaged)
1005         L = L->Parent;
1006       return L;
1007     }
1008
1009     /// \brief Get the appropriate mass for a node.
1010     ///
1011     /// Get appropriate mass for Node.  If Node is a loop-header (whose loop
1012     /// has been packaged), returns the mass of its pseudo-node.  If it's a
1013     /// node inside a packaged loop, it returns the loop's mass.
1014     BlockMass &getMass() { return isAPackage() ? Loop->Mass : Mass; }
1015
1016     /// \brief Has ContainingLoop been packaged up?
1017     bool isPackaged() const { return getResolvedNode() != Node; }
1018     /// \brief Has Loop been packaged up?
1019     bool isAPackage() const { return isLoopHeader() && Loop->IsPackaged; }
1020   };
1021
1022   /// \brief Unscaled probability weight.
1023   ///
1024   /// Probability weight for an edge in the graph (including the
1025   /// successor/target node).
1026   ///
1027   /// All edges in the original function are 32-bit.  However, exit edges from
1028   /// loop packages are taken from 64-bit exit masses, so we need 64-bits of
1029   /// space in general.
1030   ///
1031   /// In addition to the raw weight amount, Weight stores the type of the edge
1032   /// in the current context (i.e., the context of the loop being processed).
1033   /// Is this a local edge within the loop, an exit from the loop, or a
1034   /// backedge to the loop header?
1035   struct Weight {
1036     enum DistType { Local, Exit, Backedge };
1037     DistType Type;
1038     BlockNode TargetNode;
1039     uint64_t Amount;
1040     Weight() : Type(Local), Amount(0) {}
1041   };
1042
1043   /// \brief Distribution of unscaled probability weight.
1044   ///
1045   /// Distribution of unscaled probability weight to a set of successors.
1046   ///
1047   /// This class collates the successor edge weights for later processing.
1048   ///
1049   /// \a DidOverflow indicates whether \a Total did overflow while adding to
1050   /// the distribution.  It should never overflow twice.
1051   struct Distribution {
1052     typedef SmallVector<Weight, 4> WeightList;
1053     WeightList Weights;    ///< Individual successor weights.
1054     uint64_t Total;        ///< Sum of all weights.
1055     bool DidOverflow;      ///< Whether \a Total did overflow.
1056
1057     Distribution() : Total(0), DidOverflow(false) {}
1058     void addLocal(const BlockNode &Node, uint64_t Amount) {
1059       add(Node, Amount, Weight::Local);
1060     }
1061     void addExit(const BlockNode &Node, uint64_t Amount) {
1062       add(Node, Amount, Weight::Exit);
1063     }
1064     void addBackedge(const BlockNode &Node, uint64_t Amount) {
1065       add(Node, Amount, Weight::Backedge);
1066     }
1067
1068     /// \brief Normalize the distribution.
1069     ///
1070     /// Combines multiple edges to the same \a Weight::TargetNode and scales
1071     /// down so that \a Total fits into 32-bits.
1072     ///
1073     /// This is linear in the size of \a Weights.  For the vast majority of
1074     /// cases, adjacent edge weights are combined by sorting WeightList and
1075     /// combining adjacent weights.  However, for very large edge lists an
1076     /// auxiliary hash table is used.
1077     void normalize();
1078
1079   private:
1080     void add(const BlockNode &Node, uint64_t Amount, Weight::DistType Type);
1081   };
1082
1083   /// \brief Data about each block.  This is used downstream.
1084   std::vector<FrequencyData> Freqs;
1085
1086   /// \brief Loop data: see initializeLoops().
1087   std::vector<WorkingData> Working;
1088
1089   /// \brief Indexed information about loops.
1090   std::list<LoopData> Loops;
1091
1092   /// \brief Add all edges out of a packaged loop to the distribution.
1093   ///
1094   /// Adds all edges from LocalLoopHead to Dist.  Calls addToDist() to add each
1095   /// successor edge.
1096   void addLoopSuccessorsToDist(const LoopData *OuterLoop, LoopData &Loop,
1097                                Distribution &Dist);
1098
1099   /// \brief Add an edge to the distribution.
1100   ///
1101   /// Adds an edge to Succ to Dist.  If \c LoopHead.isValid(), then whether the
1102   /// edge is local/exit/backedge is in the context of LoopHead.  Otherwise,
1103   /// every edge should be a local edge (since all the loops are packaged up).
1104   void addToDist(Distribution &Dist, const LoopData *OuterLoop,
1105                  const BlockNode &Pred, const BlockNode &Succ, uint64_t Weight);
1106
1107   LoopData &getLoopPackage(const BlockNode &Head) {
1108     assert(Head.Index < Working.size());
1109     assert(Working[Head.Index].isLoopHeader());
1110     return *Working[Head.Index].Loop;
1111   }
1112
1113   /// \brief Distribute mass according to a distribution.
1114   ///
1115   /// Distributes the mass in Source according to Dist.  If LoopHead.isValid(),
1116   /// backedges and exits are stored in its entry in Loops.
1117   ///
1118   /// Mass is distributed in parallel from two copies of the source mass.
1119   void distributeMass(const BlockNode &Source, LoopData *OuterLoop,
1120                       Distribution &Dist);
1121
1122   /// \brief Compute the loop scale for a loop.
1123   void computeLoopScale(LoopData &Loop);
1124
1125   /// \brief Package up a loop.
1126   void packageLoop(LoopData &Loop);
1127
1128   /// \brief Unwrap loops.
1129   void unwrapLoops();
1130
1131   /// \brief Finalize frequency metrics.
1132   ///
1133   /// Calculates final frequencies and cleans up no-longer-needed data
1134   /// structures.
1135   void finalizeMetrics();
1136
1137   /// \brief Clear all memory.
1138   void clear();
1139
1140   virtual std::string getBlockName(const BlockNode &Node) const;
1141
1142   virtual raw_ostream &print(raw_ostream &OS) const { return OS; }
1143   void dump() const { print(dbgs()); }
1144
1145   Float getFloatingBlockFreq(const BlockNode &Node) const;
1146
1147   BlockFrequency getBlockFreq(const BlockNode &Node) const;
1148
1149   raw_ostream &printBlockFreq(raw_ostream &OS, const BlockNode &Node) const;
1150   raw_ostream &printBlockFreq(raw_ostream &OS,
1151                               const BlockFrequency &Freq) const;
1152
1153   uint64_t getEntryFreq() const {
1154     assert(!Freqs.empty());
1155     return Freqs[0].Integer;
1156   }
1157   /// \brief Virtual destructor.
1158   ///
1159   /// Need a virtual destructor to mask the compiler warning about
1160   /// getBlockName().
1161   virtual ~BlockFrequencyInfoImplBase() {}
1162 };
1163
1164 namespace bfi_detail {
1165 template <class BlockT> struct TypeMap {};
1166 template <> struct TypeMap<BasicBlock> {
1167   typedef BasicBlock BlockT;
1168   typedef Function FunctionT;
1169   typedef BranchProbabilityInfo BranchProbabilityInfoT;
1170   typedef Loop LoopT;
1171   typedef LoopInfo LoopInfoT;
1172 };
1173 template <> struct TypeMap<MachineBasicBlock> {
1174   typedef MachineBasicBlock BlockT;
1175   typedef MachineFunction FunctionT;
1176   typedef MachineBranchProbabilityInfo BranchProbabilityInfoT;
1177   typedef MachineLoop LoopT;
1178   typedef MachineLoopInfo LoopInfoT;
1179 };
1180
1181 /// \brief Get the name of a MachineBasicBlock.
1182 ///
1183 /// Get the name of a MachineBasicBlock.  It's templated so that including from
1184 /// CodeGen is unnecessary (that would be a layering issue).
1185 ///
1186 /// This is used mainly for debug output.  The name is similar to
1187 /// MachineBasicBlock::getFullName(), but skips the name of the function.
1188 template <class BlockT> std::string getBlockName(const BlockT *BB) {
1189   assert(BB && "Unexpected nullptr");
1190   auto MachineName = "BB" + Twine(BB->getNumber());
1191   if (BB->getBasicBlock())
1192     return (MachineName + "[" + BB->getName() + "]").str();
1193   return MachineName.str();
1194 }
1195 /// \brief Get the name of a BasicBlock.
1196 template <> inline std::string getBlockName(const BasicBlock *BB) {
1197   assert(BB && "Unexpected nullptr");
1198   return BB->getName().str();
1199 }
1200 }
1201
1202 /// \brief Shared implementation for block frequency analysis.
1203 ///
1204 /// This is a shared implementation of BlockFrequencyInfo and
1205 /// MachineBlockFrequencyInfo, and calculates the relative frequencies of
1206 /// blocks.
1207 ///
1208 /// This algorithm leverages BlockMass and UnsignedFloat to maintain precision,
1209 /// separates mass distribution from loop scaling, and dithers to eliminate
1210 /// probability mass loss.
1211 ///
1212 /// The implementation is split between BlockFrequencyInfoImpl, which knows the
1213 /// type of graph being modelled (BasicBlock vs. MachineBasicBlock), and
1214 /// BlockFrequencyInfoImplBase, which doesn't.  The base class uses \a
1215 /// BlockNode, a wrapper around a uint32_t.  BlockNode is numbered from 0 in
1216 /// reverse-post order.  This gives two advantages:  it's easy to compare the
1217 /// relative ordering of two nodes, and maps keyed on BlockT can be represented
1218 /// by vectors.
1219 ///
1220 /// This algorithm is O(V+E), unless there is irreducible control flow, in
1221 /// which case it's O(V*E) in the worst case.
1222 ///
1223 /// These are the main stages:
1224 ///
1225 ///  0. Reverse post-order traversal (\a initializeRPOT()).
1226 ///
1227 ///     Run a single post-order traversal and save it (in reverse) in RPOT.
1228 ///     All other stages make use of this ordering.  Save a lookup from BlockT
1229 ///     to BlockNode (the index into RPOT) in Nodes.
1230 ///
1231 ///  1. Loop indexing (\a initializeLoops()).
1232 ///
1233 ///     Translate LoopInfo/MachineLoopInfo into a form suitable for the rest of
1234 ///     the algorithm.  In particular, store the immediate members of each loop
1235 ///     in reverse post-order.
1236 ///
1237 ///  2. Calculate mass and scale in loops (\a computeMassInLoops()).
1238 ///
1239 ///     For each loop (bottom-up), distribute mass through the DAG resulting
1240 ///     from ignoring backedges and treating sub-loops as a single pseudo-node.
1241 ///     Track the backedge mass distributed to the loop header, and use it to
1242 ///     calculate the loop scale (number of loop iterations).
1243 ///
1244 ///     Visiting loops bottom-up is a post-order traversal of loop headers.
1245 ///     For each loop, immediate members that represent sub-loops will already
1246 ///     have been visited and packaged into a pseudo-node.
1247 ///
1248 ///     Distributing mass in a loop is a reverse-post-order traversal through
1249 ///     the loop.  Start by assigning full mass to the Loop header.  For each
1250 ///     node in the loop:
1251 ///
1252 ///         - Fetch and categorize the weight distribution for its successors.
1253 ///           If this is a packaged-subloop, the weight distribution is stored
1254 ///           in \a LoopData::Exits.  Otherwise, fetch it from
1255 ///           BranchProbabilityInfo.
1256 ///
1257 ///         - Each successor is categorized as \a Weight::Local, a local edge
1258 ///           within the current loop, \a Weight::Backedge, a backedge to the
1259 ///           loop header, or \a Weight::Exit, any successor outside the loop.
1260 ///           The weight, the successor, and its category are stored in \a
1261 ///           Distribution.  There can be multiple edges to each successor.
1262 ///
1263 ///         - Normalize the distribution:  scale weights down so that their sum
1264 ///           is 32-bits, and coalesce multiple edges to the same node.
1265 ///
1266 ///         - Distribute the mass accordingly, dithering to minimize mass loss,
1267 ///           as described in \a distributeMass().
1268 ///
1269 ///     Finally, calculate the loop scale from the accumulated backedge mass.
1270 ///
1271 ///  3. Distribute mass in the function (\a computeMassInFunction()).
1272 ///
1273 ///     Finally, distribute mass through the DAG resulting from packaging all
1274 ///     loops in the function.  This uses the same algorithm as distributing
1275 ///     mass in a loop, except that there are no exit or backedge edges.
1276 ///
1277 ///  4. Loop unpackaging and cleanup (\a finalizeMetrics()).
1278 ///
1279 ///     Initialize the frequency to a floating point representation of its
1280 ///     mass.
1281 ///
1282 ///     Visit loops top-down (reverse post-order), scaling the loop header's
1283 ///     frequency by its psuedo-node's mass and loop scale.  Keep track of the
1284 ///     minimum and maximum final frequencies.
1285 ///
1286 ///     Using the min and max frequencies as a guide, translate floating point
1287 ///     frequencies to an appropriate range in uint64_t.
1288 ///
1289 /// It has some known flaws.
1290 ///
1291 ///   - Irreducible control flow isn't modelled correctly.  In particular,
1292 ///     LoopInfo and MachineLoopInfo ignore irreducible backedges.  The main
1293 ///     result is that irreducible SCCs will under-scaled.  No mass is lost,
1294 ///     but the computed branch weights for the loop pseudo-node will be
1295 ///     incorrect.
1296 ///
1297 ///     Modelling irreducible control flow exactly involves setting up and
1298 ///     solving a group of infinite geometric series.  Such precision is
1299 ///     unlikely to be worthwhile, since most of our algorithms give up on
1300 ///     irreducible control flow anyway.
1301 ///
1302 ///     Nevertheless, we might find that we need to get closer.  If
1303 ///     LoopInfo/MachineLoopInfo flags loops with irreducible control flow
1304 ///     (and/or the function as a whole), we can find the SCCs, compute an
1305 ///     approximate exit frequency for the SCC as a whole, and scale up
1306 ///     accordingly.
1307 ///
1308 ///   - Loop scale is limited to 4096 per loop (2^12) to avoid exhausting
1309 ///     BlockFrequency's 64-bit integer precision.
1310 template <class BT> class BlockFrequencyInfoImpl : BlockFrequencyInfoImplBase {
1311   typedef typename bfi_detail::TypeMap<BT>::BlockT BlockT;
1312   typedef typename bfi_detail::TypeMap<BT>::FunctionT FunctionT;
1313   typedef typename bfi_detail::TypeMap<BT>::BranchProbabilityInfoT
1314   BranchProbabilityInfoT;
1315   typedef typename bfi_detail::TypeMap<BT>::LoopT LoopT;
1316   typedef typename bfi_detail::TypeMap<BT>::LoopInfoT LoopInfoT;
1317
1318   typedef GraphTraits<const BlockT *> Successor;
1319   typedef GraphTraits<Inverse<const BlockT *>> Predecessor;
1320
1321   const BranchProbabilityInfoT *BPI;
1322   const LoopInfoT *LI;
1323   const FunctionT *F;
1324
1325   // All blocks in reverse postorder.
1326   std::vector<const BlockT *> RPOT;
1327   DenseMap<const BlockT *, BlockNode> Nodes;
1328
1329   typedef typename std::vector<const BlockT *>::const_iterator rpot_iterator;
1330
1331   rpot_iterator rpot_begin() const { return RPOT.begin(); }
1332   rpot_iterator rpot_end() const { return RPOT.end(); }
1333
1334   size_t getIndex(const rpot_iterator &I) const { return I - rpot_begin(); }
1335
1336   BlockNode getNode(const rpot_iterator &I) const {
1337     return BlockNode(getIndex(I));
1338   }
1339   BlockNode getNode(const BlockT *BB) const { return Nodes.lookup(BB); }
1340
1341   const BlockT *getBlock(const BlockNode &Node) const {
1342     assert(Node.Index < RPOT.size());
1343     return RPOT[Node.Index];
1344   }
1345
1346   /// \brief Run (and save) a post-order traversal.
1347   ///
1348   /// Saves a reverse post-order traversal of all the nodes in \a F.
1349   void initializeRPOT();
1350
1351   /// \brief Initialize loop data.
1352   ///
1353   /// Build up \a Loops using \a LoopInfo.  \a LoopInfo gives us a mapping from
1354   /// each block to the deepest loop it's in, but we need the inverse.  For each
1355   /// loop, we store in reverse post-order its "immediate" members, defined as
1356   /// the header, the headers of immediate sub-loops, and all other blocks in
1357   /// the loop that are not in sub-loops.
1358   void initializeLoops();
1359
1360   /// \brief Propagate to a block's successors.
1361   ///
1362   /// In the context of distributing mass through \c OuterLoop, divide the mass
1363   /// currently assigned to \c Node between its successors.
1364   void propagateMassToSuccessors(LoopData *OuterLoop, const BlockNode &Node);
1365
1366   /// \brief Compute mass in a particular loop.
1367   ///
1368   /// Assign mass to \c Loop's header, and then for each block in \c Loop in
1369   /// reverse post-order, distribute mass to its successors.  Only visits nodes
1370   /// that have not been packaged into sub-loops.
1371   ///
1372   /// \pre \a computeMassInLoop() has been called for each subloop of \c Loop.
1373   void computeMassInLoop(LoopData &Loop);
1374
1375   /// \brief Compute mass in all loops.
1376   ///
1377   /// For each loop bottom-up, call \a computeMassInLoop().
1378   void computeMassInLoops();
1379
1380   /// \brief Compute mass in the top-level function.
1381   ///
1382   /// Assign mass to the entry block, and then for each block in reverse
1383   /// post-order, distribute mass to its successors.  Skips nodes that have
1384   /// been packaged into loops.
1385   ///
1386   /// \pre \a computeMassInLoops() has been called.
1387   void computeMassInFunction();
1388
1389   std::string getBlockName(const BlockNode &Node) const override {
1390     return bfi_detail::getBlockName(getBlock(Node));
1391   }
1392
1393 public:
1394   const FunctionT *getFunction() const { return F; }
1395
1396   void doFunction(const FunctionT *F, const BranchProbabilityInfoT *BPI,
1397                   const LoopInfoT *LI);
1398   BlockFrequencyInfoImpl() : BPI(0), LI(0), F(0) {}
1399
1400   using BlockFrequencyInfoImplBase::getEntryFreq;
1401   BlockFrequency getBlockFreq(const BlockT *BB) const {
1402     return BlockFrequencyInfoImplBase::getBlockFreq(getNode(BB));
1403   }
1404   Float getFloatingBlockFreq(const BlockT *BB) const {
1405     return BlockFrequencyInfoImplBase::getFloatingBlockFreq(getNode(BB));
1406   }
1407
1408   /// \brief Print the frequencies for the current function.
1409   ///
1410   /// Prints the frequencies for the blocks in the current function.
1411   ///
1412   /// Blocks are printed in the natural iteration order of the function, rather
1413   /// than reverse post-order.  This provides two advantages:  writing -analyze
1414   /// tests is easier (since blocks come out in source order), and even
1415   /// unreachable blocks are printed.
1416   ///
1417   /// \a BlockFrequencyInfoImplBase::print() only knows reverse post-order, so
1418   /// we need to override it here.
1419   raw_ostream &print(raw_ostream &OS) const override;
1420   using BlockFrequencyInfoImplBase::dump;
1421
1422   using BlockFrequencyInfoImplBase::printBlockFreq;
1423   raw_ostream &printBlockFreq(raw_ostream &OS, const BlockT *BB) const {
1424     return BlockFrequencyInfoImplBase::printBlockFreq(OS, getNode(BB));
1425   }
1426 };
1427
1428 template <class BT>
1429 void BlockFrequencyInfoImpl<BT>::doFunction(const FunctionT *F,
1430                                             const BranchProbabilityInfoT *BPI,
1431                                             const LoopInfoT *LI) {
1432   // Save the parameters.
1433   this->BPI = BPI;
1434   this->LI = LI;
1435   this->F = F;
1436
1437   // Clean up left-over data structures.
1438   BlockFrequencyInfoImplBase::clear();
1439   RPOT.clear();
1440   Nodes.clear();
1441
1442   // Initialize.
1443   DEBUG(dbgs() << "\nblock-frequency: " << F->getName() << "\n================="
1444                << std::string(F->getName().size(), '=') << "\n");
1445   initializeRPOT();
1446   initializeLoops();
1447
1448   // Visit loops in post-order to find thelocal mass distribution, and then do
1449   // the full function.
1450   computeMassInLoops();
1451   computeMassInFunction();
1452   unwrapLoops();
1453   finalizeMetrics();
1454 }
1455
1456 template <class BT> void BlockFrequencyInfoImpl<BT>::initializeRPOT() {
1457   const BlockT *Entry = F->begin();
1458   RPOT.reserve(F->size());
1459   std::copy(po_begin(Entry), po_end(Entry), std::back_inserter(RPOT));
1460   std::reverse(RPOT.begin(), RPOT.end());
1461
1462   assert(RPOT.size() - 1 <= BlockNode::getMaxIndex() &&
1463          "More nodes in function than Block Frequency Info supports");
1464
1465   DEBUG(dbgs() << "reverse-post-order-traversal\n");
1466   for (rpot_iterator I = rpot_begin(), E = rpot_end(); I != E; ++I) {
1467     BlockNode Node = getNode(I);
1468     DEBUG(dbgs() << " - " << getIndex(I) << ": " << getBlockName(Node) << "\n");
1469     Nodes[*I] = Node;
1470   }
1471
1472   Working.reserve(RPOT.size());
1473   for (size_t Index = 0; Index < RPOT.size(); ++Index)
1474     Working.emplace_back(Index);
1475   Freqs.resize(RPOT.size());
1476 }
1477
1478 template <class BT> void BlockFrequencyInfoImpl<BT>::initializeLoops() {
1479   DEBUG(dbgs() << "loop-detection\n");
1480   if (LI->empty())
1481     return;
1482
1483   // Visit loops top down and assign them an index.
1484   std::deque<std::pair<const LoopT *, LoopData *>> Q;
1485   for (const LoopT *L : *LI)
1486     Q.emplace_back(L, nullptr);
1487   while (!Q.empty()) {
1488     const LoopT *Loop = Q.front().first;
1489     LoopData *Parent = Q.front().second;
1490     Q.pop_front();
1491
1492     BlockNode Header = getNode(Loop->getHeader());
1493     assert(Header.isValid());
1494
1495     Loops.emplace_back(Parent, Header);
1496     Working[Header.Index].Loop = &Loops.back();
1497     DEBUG(dbgs() << " - loop = " << getBlockName(Header) << "\n");
1498
1499     for (const LoopT *L : *Loop)
1500       Q.emplace_back(L, &Loops.back());
1501   }
1502
1503   // Visit nodes in reverse post-order and add them to their deepest containing
1504   // loop.
1505   for (size_t Index = 0; Index < RPOT.size(); ++Index) {
1506     // Loop headers have already been mostly mapped.
1507     if (Working[Index].isLoopHeader()) {
1508       LoopData *ContainingLoop = Working[Index].getContainingLoop();
1509       if (ContainingLoop)
1510         ContainingLoop->Nodes.push_back(Index);
1511       continue;
1512     }
1513
1514     const LoopT *Loop = LI->getLoopFor(RPOT[Index]);
1515     if (!Loop)
1516       continue;
1517
1518     // Add this node to its containing loop's member list.
1519     BlockNode Header = getNode(Loop->getHeader());
1520     assert(Header.isValid());
1521     const auto &HeaderData = Working[Header.Index];
1522     assert(HeaderData.isLoopHeader());
1523
1524     Working[Index].Loop = HeaderData.Loop;
1525     HeaderData.Loop->Nodes.push_back(Index);
1526     DEBUG(dbgs() << " - loop = " << getBlockName(Header)
1527                  << ": member = " << getBlockName(Index) << "\n");
1528   }
1529 }
1530
1531 template <class BT> void BlockFrequencyInfoImpl<BT>::computeMassInLoops() {
1532   // Visit loops with the deepest first, and the top-level loops last.
1533   for (auto L = Loops.rbegin(), E = Loops.rend(); L != E; ++L)
1534     computeMassInLoop(*L);
1535 }
1536
1537 template <class BT>
1538 void BlockFrequencyInfoImpl<BT>::computeMassInLoop(LoopData &Loop) {
1539   // Compute mass in loop.
1540   DEBUG(dbgs() << "compute-mass-in-loop: " << getBlockName(Loop.getHeader())
1541                << "\n");
1542
1543   Working[Loop.getHeader().Index].getMass() = BlockMass::getFull();
1544   propagateMassToSuccessors(&Loop, Loop.getHeader());
1545
1546   for (const BlockNode &M : Loop.members())
1547     propagateMassToSuccessors(&Loop, M);
1548
1549   computeLoopScale(Loop);
1550   packageLoop(Loop);
1551 }
1552
1553 template <class BT> void BlockFrequencyInfoImpl<BT>::computeMassInFunction() {
1554   // Compute mass in function.
1555   DEBUG(dbgs() << "compute-mass-in-function\n");
1556   assert(!Working.empty() && "no blocks in function");
1557   assert(!Working[0].isLoopHeader() && "entry block is a loop header");
1558
1559   Working[0].getMass() = BlockMass::getFull();
1560   for (rpot_iterator I = rpot_begin(), IE = rpot_end(); I != IE; ++I) {
1561     // Check for nodes that have been packaged.
1562     BlockNode Node = getNode(I);
1563     if (Working[Node.Index].isPackaged())
1564       continue;
1565
1566     propagateMassToSuccessors(nullptr, Node);
1567   }
1568 }
1569
1570 template <class BT>
1571 void
1572 BlockFrequencyInfoImpl<BT>::propagateMassToSuccessors(LoopData *OuterLoop,
1573                                                       const BlockNode &Node) {
1574   DEBUG(dbgs() << " - node: " << getBlockName(Node) << "\n");
1575   // Calculate probability for successors.
1576   Distribution Dist;
1577   if (auto *Loop = Working[Node.Index].getPackagedLoop()) {
1578     assert(Loop != OuterLoop && "Cannot propagate mass in a packaged loop");
1579     addLoopSuccessorsToDist(OuterLoop, *Loop, Dist);
1580   } else {
1581     const BlockT *BB = getBlock(Node);
1582     for (auto SI = Successor::child_begin(BB), SE = Successor::child_end(BB);
1583          SI != SE; ++SI)
1584       // Do not dereference SI, or getEdgeWeight() is linear in the number of
1585       // successors.
1586       addToDist(Dist, OuterLoop, Node, getNode(*SI),
1587                 BPI->getEdgeWeight(BB, SI));
1588   }
1589
1590   // Distribute mass to successors, saving exit and backedge data in the
1591   // loop header.
1592   distributeMass(Node, OuterLoop, Dist);
1593 }
1594
1595 template <class BT>
1596 raw_ostream &BlockFrequencyInfoImpl<BT>::print(raw_ostream &OS) const {
1597   if (!F)
1598     return OS;
1599   OS << "block-frequency-info: " << F->getName() << "\n";
1600   for (const BlockT &BB : *F)
1601     OS << " - " << bfi_detail::getBlockName(&BB)
1602        << ": float = " << getFloatingBlockFreq(&BB)
1603        << ", int = " << getBlockFreq(&BB).getFrequency() << "\n";
1604
1605   // Add an extra newline for readability.
1606   OS << "\n";
1607   return OS;
1608 }
1609 }
1610
1611 #undef DEBUG_TYPE
1612
1613 #endif