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