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