Fixing MSVC after r206622?
[oota-llvm.git] / lib / Analysis / BlockFrequencyInfoImpl.cpp
1 //===- BlockFrequencyImplInfo.cpp - Block Frequency Info Implementation ---===//
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 // Loops should be simplified before this analysis.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #define DEBUG_TYPE "block-freq"
15 #include "llvm/Analysis/BlockFrequencyInfoImpl.h"
16 #include "llvm/ADT/APFloat.h"
17 #include "llvm/Support/raw_ostream.h"
18 #include <deque>
19
20 using namespace llvm;
21
22 //===----------------------------------------------------------------------===//
23 //
24 // PositiveFloat implementation.
25 //
26 //===----------------------------------------------------------------------===//
27 #ifndef _MSC_VER
28 const int PositiveFloatBase::MaxExponent;
29 const int PositiveFloatBase::MinExponent;
30 #endif
31
32 static void appendDigit(std::string &Str, unsigned D) {
33   assert(D < 10);
34   Str += '0' + D % 10;
35 }
36
37 static void appendNumber(std::string &Str, uint64_t N) {
38   while (N) {
39     appendDigit(Str, N % 10);
40     N /= 10;
41   }
42 }
43
44 static bool doesRoundUp(char Digit) {
45   switch (Digit) {
46   case '5':
47   case '6':
48   case '7':
49   case '8':
50   case '9':
51     return true;
52   default:
53     return false;
54   }
55 }
56
57 static std::string toStringAPFloat(uint64_t D, int E, unsigned Precision) {
58   assert(E >= PositiveFloatBase::MinExponent);
59   assert(E <= PositiveFloatBase::MaxExponent);
60
61   // Find a new E, but don't let it increase past MaxExponent.
62   int LeadingZeros = PositiveFloatBase::countLeadingZeros64(D);
63   int NewE = std::min(PositiveFloatBase::MaxExponent, E + 63 - LeadingZeros);
64   int Shift = 63 - (NewE - E);
65   assert(Shift <= LeadingZeros);
66   assert(Shift == LeadingZeros || NewE == PositiveFloatBase::MaxExponent);
67   D <<= Shift;
68   E = NewE;
69
70   // Check for a denormal.
71   unsigned AdjustedE = E + 16383;
72   if (!(D >> 63)) {
73     assert(E == PositiveFloatBase::MaxExponent);
74     AdjustedE = 0;
75   }
76
77   // Build the float and print it.
78   uint64_t RawBits[2] = {D, AdjustedE};
79   APFloat Float(APFloat::x87DoubleExtended, APInt(80, RawBits));
80   SmallVector<char, 24> Chars;
81   Float.toString(Chars, Precision, 0);
82   return std::string(Chars.begin(), Chars.end());
83 }
84
85 static std::string stripTrailingZeros(std::string Float) {
86   size_t NonZero = Float.find_last_not_of('0');
87   assert(NonZero != std::string::npos && "no . in floating point string");
88
89   if (Float[NonZero] == '.')
90     ++NonZero;
91
92   return Float.substr(0, NonZero + 1);
93 }
94
95 std::string PositiveFloatBase::toString(uint64_t D, int16_t E, int Width,
96                                         unsigned Precision) {
97   if (!D)
98     return "0.0";
99
100   // Canonicalize exponent and digits.
101   uint64_t Above0 = 0;
102   uint64_t Below0 = 0;
103   uint64_t Extra = 0;
104   int ExtraShift = 0;
105   if (E == 0) {
106     Above0 = D;
107   } else if (E > 0) {
108     if (int Shift = std::min(int16_t(countLeadingZeros64(D)), E)) {
109       D <<= Shift;
110       E -= Shift;
111
112       if (!E)
113         Above0 = D;
114     }
115   } else if (E > -64) {
116     Above0 = D >> -E;
117     Below0 = D << (64 + E);
118   } else if (E > -120) {
119     Below0 = D >> (-E - 64);
120     Extra = D << (128 + E);
121     ExtraShift = -64 - E;
122   }
123
124   // Fall back on APFloat for very small and very large numbers.
125   if (!Above0 && !Below0)
126     return toStringAPFloat(D, E, Precision);
127
128   // Append the digits before the decimal.
129   std::string Str;
130   size_t DigitsOut = 0;
131   if (Above0) {
132     appendNumber(Str, Above0);
133     DigitsOut = Str.size();
134   } else
135     appendDigit(Str, 0);
136   std::reverse(Str.begin(), Str.end());
137
138   // Return early if there's nothing after the decimal.
139   if (!Below0)
140     return Str + ".0";
141
142   // Append the decimal and beyond.
143   Str += '.';
144   uint64_t Error = UINT64_C(1) << (64 - Width);
145
146   // We need to shift Below0 to the right to make space for calculating
147   // digits.  Save the precision we're losing in Extra.
148   Extra = (Below0 & 0xf) << 56 | (Extra >> 8);
149   Below0 >>= 4;
150   size_t SinceDot = 0;
151   size_t AfterDot = Str.size();
152   do {
153     if (ExtraShift) {
154       --ExtraShift;
155       Error *= 5;
156     } else
157       Error *= 10;
158
159     Below0 *= 10;
160     Extra *= 10;
161     Below0 += (Extra >> 60);
162     Extra = Extra & (UINT64_MAX >> 4);
163     appendDigit(Str, Below0 >> 60);
164     Below0 = Below0 & (UINT64_MAX >> 4);
165     if (DigitsOut || Str.back() != '0')
166       ++DigitsOut;
167     ++SinceDot;
168   } while (Error && (Below0 << 4 | Extra >> 60) >= Error / 2 &&
169            (!Precision || DigitsOut <= Precision || SinceDot < 2));
170
171   // Return early for maximum precision.
172   if (!Precision || DigitsOut <= Precision)
173     return stripTrailingZeros(Str);
174
175   // Find where to truncate.
176   size_t Truncate =
177       std::max(Str.size() - (DigitsOut - Precision), AfterDot + 1);
178
179   // Check if there's anything to truncate.
180   if (Truncate >= Str.size())
181     return stripTrailingZeros(Str);
182
183   bool Carry = doesRoundUp(Str[Truncate]);
184   if (!Carry)
185     return stripTrailingZeros(Str.substr(0, Truncate));
186
187   // Round with the first truncated digit.
188   for (std::string::reverse_iterator I(Str.begin() + Truncate), E = Str.rend();
189        I != E; ++I) {
190     if (*I == '.')
191       continue;
192     if (*I == '9') {
193       *I = '0';
194       continue;
195     }
196
197     ++*I;
198     Carry = false;
199     break;
200   }
201
202   // Add "1" in front if we still need to carry.
203   return stripTrailingZeros(std::string(Carry, '1') + Str.substr(0, Truncate));
204 }
205
206 raw_ostream &PositiveFloatBase::print(raw_ostream &OS, uint64_t D, int16_t E,
207                                       int Width, unsigned Precision) {
208   return OS << toString(D, E, Width, Precision);
209 }
210
211 void PositiveFloatBase::dump(uint64_t D, int16_t E, int Width) {
212   print(dbgs(), D, E, Width, 0) << "[" << Width << ":" << D << "*2^" << E
213                                 << "]";
214 }
215
216 static std::pair<uint64_t, int16_t>
217 getRoundedFloat(uint64_t N, bool ShouldRound, int64_t Shift) {
218   if (ShouldRound)
219     if (!++N)
220       // Rounding caused an overflow.
221       return std::make_pair(UINT64_C(1), Shift + 64);
222   return std::make_pair(N, Shift);
223 }
224
225 std::pair<uint64_t, int16_t> PositiveFloatBase::divide64(uint64_t Dividend,
226                                                          uint64_t Divisor) {
227   // Input should be sanitized.
228   assert(Divisor);
229   assert(Dividend);
230
231   // Minimize size of divisor.
232   int16_t Shift = 0;
233   if (int Zeros = countTrailingZeros(Divisor)) {
234     Shift -= Zeros;
235     Divisor >>= Zeros;
236   }
237
238   // Check for powers of two.
239   if (Divisor == 1)
240     return std::make_pair(Dividend, Shift);
241
242   // Maximize size of dividend.
243   if (int Zeros = countLeadingZeros64(Dividend)) {
244     Shift -= Zeros;
245     Dividend <<= Zeros;
246   }
247
248   // Start with the result of a divide.
249   uint64_t Quotient = Dividend / Divisor;
250   Dividend %= Divisor;
251
252   // Continue building the quotient with long division.
253   //
254   // TODO: continue with largers digits.
255   while (!(Quotient >> 63) && Dividend) {
256     // Shift Dividend, and check for overflow.
257     bool IsOverflow = Dividend >> 63;
258     Dividend <<= 1;
259     --Shift;
260
261     // Divide.
262     bool DoesDivide = IsOverflow || Divisor <= Dividend;
263     Quotient = (Quotient << 1) | uint64_t(DoesDivide);
264     Dividend -= DoesDivide ? Divisor : 0;
265   }
266
267   // Round.
268   if (Dividend >= getHalf(Divisor))
269     if (!++Quotient)
270       // Rounding caused an overflow in Quotient.
271       return std::make_pair(UINT64_C(1), Shift + 64);
272
273   return getRoundedFloat(Quotient, Dividend >= getHalf(Divisor), Shift);
274 }
275
276 static void addWithCarry(uint64_t &Upper, uint64_t &Lower, uint64_t N) {
277   uint64_t NewLower = Lower + (N << 32);
278   Upper += (N >> 32) + (NewLower < Lower);
279   Lower = NewLower;
280 }
281
282 std::pair<uint64_t, int16_t> PositiveFloatBase::multiply64(uint64_t L,
283                                                            uint64_t R) {
284   // Separate into two 32-bit digits (U.L).
285   uint64_t UL = L >> 32, LL = L & UINT32_MAX, UR = R >> 32, LR = R & UINT32_MAX;
286
287   // Compute cross products.
288   uint64_t P1 = UL * UR, P2 = UL * LR, P3 = LL * UR, P4 = LL * LR;
289
290   // Sum into two 64-bit digits.
291   uint64_t Upper = P1, Lower = P4;
292   addWithCarry(Upper, Lower, P2);
293   addWithCarry(Upper, Lower, P3);
294
295   // Check for the lower 32 bits.
296   if (!Upper)
297     return std::make_pair(Lower, 0);
298
299   // Shift as little as possible to maximize precision.
300   unsigned LeadingZeros = countLeadingZeros64(Upper);
301   int16_t Shift = 64 - LeadingZeros;
302   if (LeadingZeros)
303     Upper = Upper << LeadingZeros | Lower >> Shift;
304   bool ShouldRound = Shift && (Lower & UINT64_C(1) << (Shift - 1));
305   return getRoundedFloat(Upper, ShouldRound, Shift);
306 }
307
308 //===----------------------------------------------------------------------===//
309 //
310 // BlockMass implementation.
311 //
312 //===----------------------------------------------------------------------===//
313 BlockMass &BlockMass::operator*=(const BranchProbability &P) {
314   uint32_t N = P.getNumerator(), D = P.getDenominator();
315   assert(D || "divide by 0");
316   assert(N <= D || "fraction greater than 1");
317
318   // Fast path for multiplying by 1.0.
319   if (!Mass || N == D)
320     return *this;
321
322   // Get as much precision as we can.
323   int Shift = countLeadingZeros(Mass);
324   uint64_t ShiftedQuotient = (Mass << Shift) / D;
325   uint64_t Product = ShiftedQuotient * N >> Shift;
326
327   // Now check for what's lost.
328   uint64_t Left = ShiftedQuotient * (D - N) >> Shift;
329   uint64_t Lost = Mass - Product - Left;
330
331   // TODO: prove this assertion.
332   assert(Lost <= UINT32_MAX);
333
334   // Take the product plus a portion of the spoils.
335   Mass = Product + Lost * N / D;
336   return *this;
337 }
338
339 PositiveFloat<uint64_t> BlockMass::toFloat() const {
340   if (isFull())
341     return PositiveFloat<uint64_t>(1, 0);
342   return PositiveFloat<uint64_t>(getMass() + 1, -64);
343 }
344
345 void BlockMass::dump() const { print(dbgs()); }
346
347 static char getHexDigit(int N) {
348   assert(N < 16);
349   if (N < 10)
350     return '0' + N;
351   return 'a' + N - 10;
352 }
353 raw_ostream &BlockMass::print(raw_ostream &OS) const {
354   for (int Digits = 0; Digits < 16; ++Digits)
355     OS << getHexDigit(Mass >> (60 - Digits * 4) & 0xf);
356   return OS;
357 }
358
359 //===----------------------------------------------------------------------===//
360 //
361 // BlockFrequencyInfoImpl implementation.
362 //
363 //===----------------------------------------------------------------------===//
364 namespace {
365
366 typedef BlockFrequencyInfoImplBase::BlockNode BlockNode;
367 typedef BlockFrequencyInfoImplBase::Distribution Distribution;
368 typedef BlockFrequencyInfoImplBase::Distribution::WeightList WeightList;
369 typedef BlockFrequencyInfoImplBase::Float Float;
370 typedef BlockFrequencyInfoImplBase::PackagedLoopData PackagedLoopData;
371 typedef BlockFrequencyInfoImplBase::Weight Weight;
372 typedef BlockFrequencyInfoImplBase::FrequencyData FrequencyData;
373
374 /// \brief Dithering mass distributer.
375 ///
376 /// This class splits up a single mass into portions by weight, dithering to
377 /// spread out error.  No mass is lost.  The dithering precision depends on the
378 /// precision of the product of \a BlockMass and \a BranchProbability.
379 ///
380 /// The distribution algorithm follows.
381 ///
382 ///  1. Initialize by saving the sum of the weights in \a RemWeight and the
383 ///     mass to distribute in \a RemMass.
384 ///
385 ///  2. For each portion:
386 ///
387 ///      1. Construct a branch probability, P, as the portion's weight divided
388 ///         by the current value of \a RemWeight.
389 ///      2. Calculate the portion's mass as \a RemMass times P.
390 ///      3. Update \a RemWeight and \a RemMass at each portion by subtracting
391 ///         the current portion's weight and mass.
392 ///
393 /// Mass is distributed in two ways: full distribution and forward
394 /// distribution.  The latter ignores backedges, and uses the parallel fields
395 /// \a RemForwardWeight and \a RemForwardMass.
396 struct DitheringDistributer {
397   uint32_t RemWeight;
398   uint32_t RemForwardWeight;
399
400   BlockMass RemMass;
401   BlockMass RemForwardMass;
402
403   DitheringDistributer(Distribution &Dist, const BlockMass &Mass);
404
405   BlockMass takeLocalMass(uint32_t Weight) {
406     (void)takeMass(Weight);
407     return takeForwardMass(Weight);
408   }
409   BlockMass takeExitMass(uint32_t Weight) {
410     (void)takeForwardMass(Weight);
411     return takeMass(Weight);
412   }
413   BlockMass takeBackedgeMass(uint32_t Weight) { return takeMass(Weight); }
414
415 private:
416   BlockMass takeForwardMass(uint32_t Weight);
417   BlockMass takeMass(uint32_t Weight);
418 };
419 }
420
421 DitheringDistributer::DitheringDistributer(Distribution &Dist,
422                                            const BlockMass &Mass) {
423   Dist.normalize();
424   RemWeight = Dist.Total;
425   RemForwardWeight = Dist.ForwardTotal;
426   RemMass = Mass;
427   RemForwardMass = Dist.ForwardTotal ? Mass : BlockMass();
428 }
429
430 BlockMass DitheringDistributer::takeForwardMass(uint32_t Weight) {
431   // Compute the amount of mass to take.
432   assert(Weight && "invalid weight");
433   assert(Weight <= RemForwardWeight);
434   BlockMass Mass = RemForwardMass * BranchProbability(Weight, RemForwardWeight);
435
436   // Decrement totals (dither).
437   RemForwardWeight -= Weight;
438   RemForwardMass -= Mass;
439   return Mass;
440 }
441 BlockMass DitheringDistributer::takeMass(uint32_t Weight) {
442   assert(Weight && "invalid weight");
443   assert(Weight <= RemWeight);
444   BlockMass Mass = RemMass * BranchProbability(Weight, RemWeight);
445
446   // Decrement totals (dither).
447   RemWeight -= Weight;
448   RemMass -= Mass;
449   return Mass;
450 }
451
452 void Distribution::add(const BlockNode &Node, uint64_t Amount,
453                        Weight::DistType Type) {
454   assert(Amount && "invalid weight of 0");
455   uint64_t NewTotal = Total + Amount;
456
457   // Check for overflow.  It should be impossible to overflow twice.
458   bool IsOverflow = NewTotal < Total;
459   assert(!(DidOverflow && IsOverflow) && "unexpected repeated overflow");
460   DidOverflow |= IsOverflow;
461
462   // Update the total.
463   Total = NewTotal;
464
465   // Save the weight.
466   Weight W;
467   W.TargetNode = Node;
468   W.Amount = Amount;
469   W.Type = Type;
470   Weights.push_back(W);
471
472   if (Type == Weight::Backedge)
473     return;
474
475   // Update forward total.  Don't worry about overflow here, since then Total
476   // will exceed 32-bits and they'll both be recomputed in normalize().
477   ForwardTotal += Amount;
478 }
479
480 static void combineWeight(Weight &W, const Weight &OtherW) {
481   assert(OtherW.TargetNode.isValid());
482   if (!W.Amount) {
483     W = OtherW;
484     return;
485   }
486   assert(W.Type == OtherW.Type);
487   assert(W.TargetNode == OtherW.TargetNode);
488   assert(W.Amount < W.Amount + OtherW.Amount);
489   W.Amount += OtherW.Amount;
490 }
491 static void combineWeightsBySorting(WeightList &Weights) {
492   // Sort so edges to the same node are adjacent.
493   std::sort(Weights.begin(), Weights.end(),
494             [](const Weight &L,
495                const Weight &R) { return L.TargetNode < R.TargetNode; });
496
497   // Combine adjacent edges.
498   WeightList::iterator O = Weights.begin();
499   for (WeightList::const_iterator I = O, L = O, E = Weights.end(); I != E;
500        ++O, (I = L)) {
501     *O = *I;
502
503     // Find the adjacent weights to the same node.
504     for (++L; L != E && I->TargetNode == L->TargetNode; ++L)
505       combineWeight(*O, *L);
506   }
507
508   // Erase extra entries.
509   Weights.erase(O, Weights.end());
510   return;
511 }
512 static void combineWeightsByHashing(WeightList &Weights) {
513   // Collect weights into a DenseMap.
514   typedef DenseMap<BlockNode::IndexType, Weight> HashTable;
515   HashTable Combined(NextPowerOf2(2 * Weights.size()));
516   for (const Weight &W : Weights)
517     combineWeight(Combined[W.TargetNode.Index], W);
518
519   // Check whether anything changed.
520   if (Weights.size() == Combined.size())
521     return;
522
523   // Fill in the new weights.
524   Weights.clear();
525   Weights.reserve(Combined.size());
526   for (const auto &I : Combined)
527     Weights.push_back(I.second);
528 }
529 static void combineWeights(WeightList &Weights) {
530   // Use a hash table for many successors to keep this linear.
531   if (Weights.size() > 128) {
532     combineWeightsByHashing(Weights);
533     return;
534   }
535
536   combineWeightsBySorting(Weights);
537 }
538 static uint64_t shiftRightAndRound(uint64_t N, int Shift) {
539   assert(Shift >= 0);
540   assert(Shift < 64);
541   if (!Shift)
542     return N;
543   return (N >> Shift) + (UINT64_C(1) & N >> (Shift - 1));
544 }
545 void Distribution::normalize() {
546   // Early exit for termination nodes.
547   if (Weights.empty())
548     return;
549
550   // Only bother if there are multiple successors.
551   if (Weights.size() > 1)
552     combineWeights(Weights);
553
554   // Early exit when combined into a single successor.
555   if (Weights.size() == 1) {
556     Total = 1;
557     ForwardTotal = Weights.front().Type != Weight::Backedge;
558     Weights.front().Amount = 1;
559     return;
560   }
561
562   // Determine how much to shift right so that the total fits into 32-bits.
563   //
564   // If we shift at all, shift by 1 extra.  Otherwise, the lower limit of 1
565   // for each weight can cause a 32-bit overflow.
566   int Shift = 0;
567   if (DidOverflow)
568     Shift = 33;
569   else if (Total > UINT32_MAX)
570     Shift = 33 - countLeadingZeros(Total);
571
572   // Early exit if nothing needs to be scaled.
573   if (!Shift)
574     return;
575
576   // Recompute the total through accumulation (rather than shifting it) so that
577   // it's accurate after shifting.  ForwardTotal is dirty here anyway.
578   Total = 0;
579   ForwardTotal = 0;
580
581   // Sum the weights to each node and shift right if necessary.
582   for (Weight &W : Weights) {
583     // Scale down below UINT32_MAX.  Since Shift is larger than necessary, we
584     // can round here without concern about overflow.
585     assert(W.TargetNode.isValid());
586     W.Amount = std::max(UINT64_C(1), shiftRightAndRound(W.Amount, Shift));
587     assert(W.Amount <= UINT32_MAX);
588
589     // Update the total.
590     Total += W.Amount;
591     if (W.Type == Weight::Backedge)
592       continue;
593
594     // Update the forward total.
595     ForwardTotal += W.Amount;
596   }
597   assert(Total <= UINT32_MAX);
598 }
599
600 void BlockFrequencyInfoImplBase::clear() {
601   *this = BlockFrequencyInfoImplBase();
602 }
603
604 /// \brief Clear all memory not needed downstream.
605 ///
606 /// Releases all memory not used downstream.  In particular, saves Freqs.
607 static void cleanup(BlockFrequencyInfoImplBase &BFI) {
608   std::vector<FrequencyData> SavedFreqs(std::move(BFI.Freqs));
609   BFI.clear();
610   BFI.Freqs = std::move(SavedFreqs);
611 }
612
613 /// \brief Get a possibly packaged node.
614 ///
615 /// Get the node currently representing Node, which could be a containing
616 /// loop.
617 ///
618 /// This function should only be called when distributing mass.  As long as
619 /// there are no irreducilbe edges to Node, then it will have complexity O(1)
620 /// in this context.
621 ///
622 /// In general, the complexity is O(L), where L is the number of loop headers
623 /// Node has been packaged into.  Since this method is called in the context
624 /// of distributing mass, L will be the number of loop headers an early exit
625 /// edge jumps out of.
626 static BlockNode getPackagedNode(const BlockFrequencyInfoImplBase &BFI,
627                                  const BlockNode &Node) {
628   assert(Node.isValid());
629   if (!BFI.Working[Node.Index].IsPackaged)
630     return Node;
631   if (!BFI.Working[Node.Index].ContainingLoop.isValid())
632     return Node;
633   return getPackagedNode(BFI, BFI.Working[Node.Index].ContainingLoop);
634 }
635
636 /// \brief Get the appropriate mass for a possible pseudo-node loop package.
637 ///
638 /// Get appropriate mass for Node.  If Node is a loop-header (whose loop has
639 /// been packaged), returns the mass of its pseudo-node.  If it's a node inside
640 /// a packaged loop, it returns the loop's pseudo-node.
641 static BlockMass &getPackageMass(BlockFrequencyInfoImplBase &BFI,
642                                  const BlockNode &Node) {
643   assert(Node.isValid());
644   assert(!BFI.Working[Node.Index].IsPackaged);
645   if (!BFI.Working[Node.Index].IsAPackage)
646     return BFI.Working[Node.Index].Mass;
647
648   return BFI.getLoopPackage(Node).Mass;
649 }
650
651 void BlockFrequencyInfoImplBase::addToDist(Distribution &Dist,
652                                            const BlockNode &LoopHead,
653                                            const BlockNode &Pred,
654                                            const BlockNode &Succ,
655                                            uint64_t Weight) {
656   if (!Weight)
657     Weight = 1;
658
659 #ifndef NDEBUG
660   auto debugSuccessor = [&](const char *Type, const BlockNode &Resolved) {
661     dbgs() << "  =>"
662            << " [" << Type << "] weight = " << Weight;
663     if (Succ != LoopHead)
664       dbgs() << ", succ = " << getBlockName(Succ);
665     if (Resolved != Succ)
666       dbgs() << ", resolved = " << getBlockName(Resolved);
667     dbgs() << "\n";
668   };
669   (void)debugSuccessor;
670 #endif
671
672   if (Succ == LoopHead) {
673     DEBUG(debugSuccessor("backedge", Succ));
674     Dist.addBackedge(LoopHead, Weight);
675     return;
676   }
677   BlockNode Resolved = getPackagedNode(*this, Succ);
678   assert(Resolved != LoopHead);
679
680   if (Working[Resolved.Index].ContainingLoop != LoopHead) {
681     DEBUG(debugSuccessor("  exit  ", Resolved));
682     Dist.addExit(Resolved, Weight);
683     return;
684   }
685
686   if (!LoopHead.isValid() && Resolved < Pred) {
687     // Irreducible backedge.  Skip this edge in the distribution.
688     DEBUG(debugSuccessor("skipped ", Resolved));
689     return;
690   }
691
692   DEBUG(debugSuccessor(" local  ", Resolved));
693   Dist.addLocal(Resolved, Weight);
694 }
695
696 void BlockFrequencyInfoImplBase::addLoopSuccessorsToDist(
697     const BlockNode &LoopHead, const BlockNode &LocalLoopHead,
698     Distribution &Dist) {
699   PackagedLoopData &LoopPackage = getLoopPackage(LocalLoopHead);
700   const PackagedLoopData::ExitMap &Exits = LoopPackage.Exits;
701
702   // Copy the exit map into Dist.
703   for (const auto &I : Exits)
704     addToDist(Dist, LoopHead, LocalLoopHead, I.first, I.second.getMass());
705
706   // We don't need this map any more.  Clear it to prevent quadratic memory
707   // usage in deeply nested loops with irreducible control flow.
708   LoopPackage.Exits.clear();
709 }
710
711 /// \brief Get the maximum allowed loop scale.
712 ///
713 /// Gives the maximum number of estimated iterations allowed for a loop.
714 /// Downstream users have trouble with very large numbers (even within
715 /// 64-bits).  Perhaps they can be changed to use PositiveFloat.
716 ///
717 /// TODO: change downstream users so that this can be increased or removed.
718 static Float getMaxLoopScale() { return Float(1, 12); }
719
720 /// \brief Compute the loop scale for a loop.
721 void BlockFrequencyInfoImplBase::computeLoopScale(const BlockNode &LoopHead) {
722   // Compute loop scale.
723   DEBUG(dbgs() << "compute-loop-scale: " << getBlockName(LoopHead) << "\n");
724
725   // LoopScale == 1 / ExitMass
726   // ExitMass == HeadMass - BackedgeMass
727   PackagedLoopData &LoopPackage = getLoopPackage(LoopHead);
728   BlockMass ExitMass = BlockMass::getFull() - LoopPackage.BackedgeMass;
729
730   // Block scale stores the inverse of the scale.
731   LoopPackage.Scale = ExitMass.toFloat().inverse();
732
733   DEBUG(dbgs() << " - exit-mass = " << ExitMass << " (" << BlockMass::getFull()
734                << " - " << LoopPackage.BackedgeMass << ")\n"
735                << " - scale = " << LoopPackage.Scale << "\n");
736
737   if (LoopPackage.Scale > getMaxLoopScale()) {
738     LoopPackage.Scale = getMaxLoopScale();
739     DEBUG(dbgs() << " - reduced-to-max-scale: " << getMaxLoopScale() << "\n");
740   }
741 }
742
743 /// \brief Package up a loop.
744 void BlockFrequencyInfoImplBase::packageLoop(const BlockNode &LoopHead) {
745   DEBUG(dbgs() << "packaging-loop: " << getBlockName(LoopHead) << "\n");
746   Working[LoopHead.Index].IsAPackage = true;
747   for (const BlockNode &M : getLoopPackage(LoopHead).Members) {
748     DEBUG(dbgs() << " - node: " << getBlockName(M.Index) << "\n");
749     Working[M.Index].IsPackaged = true;
750   }
751 }
752
753 void BlockFrequencyInfoImplBase::distributeMass(const BlockNode &Source,
754                                                 const BlockNode &LoopHead,
755                                                 Distribution &Dist) {
756   BlockMass Mass = getPackageMass(*this, Source);
757   DEBUG(dbgs() << "  => mass:  " << Mass
758                << " (    general     |    forward     )\n");
759
760   // Distribute mass to successors as laid out in Dist.
761   DitheringDistributer D(Dist, Mass);
762
763 #ifndef NDEBUG
764   auto debugAssign = [&](const BlockNode &T, const BlockMass &M,
765                          const char *Desc) {
766     dbgs() << "  => assign " << M << " (" << D.RemMass << "|"
767            << D.RemForwardMass << ")";
768     if (Desc)
769       dbgs() << " [" << Desc << "]";
770     if (T.isValid())
771       dbgs() << " to " << getBlockName(T);
772     dbgs() << "\n";
773   };
774   (void)debugAssign;
775 #endif
776
777   PackagedLoopData *LoopPackage = 0;
778   if (LoopHead.isValid())
779     LoopPackage = &getLoopPackage(LoopHead);
780   for (const Weight &W : Dist.Weights) {
781     // Check for a local edge (forward and non-exit).
782     if (W.Type == Weight::Local) {
783       BlockMass Local = D.takeLocalMass(W.Amount);
784       getPackageMass(*this, W.TargetNode) += Local;
785       DEBUG(debugAssign(W.TargetNode, Local, nullptr));
786       continue;
787     }
788
789     // Backedges and exits only make sense if we're processing a loop.
790     assert(LoopPackage && "backedge or exit outside of loop");
791
792     // Check for a backedge.
793     if (W.Type == Weight::Backedge) {
794       BlockMass Back = D.takeBackedgeMass(W.Amount);
795       LoopPackage->BackedgeMass += Back;
796       DEBUG(debugAssign(BlockNode(), Back, "back"));
797       continue;
798     }
799
800     // This must be an exit.
801     assert(W.Type == Weight::Exit);
802     BlockMass Exit = D.takeExitMass(W.Amount);
803     LoopPackage->Exits.push_back(std::make_pair(W.TargetNode, Exit));
804     DEBUG(debugAssign(W.TargetNode, Exit, "exit"));
805   }
806 }
807
808 static void convertFloatingToInteger(BlockFrequencyInfoImplBase &BFI,
809                                      const Float &Min, const Float &Max) {
810   // Scale the Factor to a size that creates integers.  Ideally, integers would
811   // be scaled so that Max == UINT64_MAX so that they can be best
812   // differentiated.  However, the register allocator currently deals poorly
813   // with large numbers.  Instead, push Min up a little from 1 to give some
814   // room to differentiate small, unequal numbers.
815   //
816   // TODO: fix issues downstream so that ScalingFactor can be Float(1,64)/Max.
817   Float ScalingFactor = Min.inverse();
818   if ((Max / Min).lg() < 60)
819     ScalingFactor <<= 3;
820
821   // Translate the floats to integers.
822   DEBUG(dbgs() << "float-to-int: min = " << Min << ", max = " << Max
823                << ", factor = " << ScalingFactor << "\n");
824   for (size_t Index = 0; Index < BFI.Freqs.size(); ++Index) {
825     Float Scaled = BFI.Freqs[Index].Floating * ScalingFactor;
826     BFI.Freqs[Index].Integer = std::max(UINT64_C(1), Scaled.toInt<uint64_t>());
827     DEBUG(dbgs() << " - " << BFI.getBlockName(Index) << ": float = "
828                  << BFI.Freqs[Index].Floating << ", scaled = " << Scaled
829                  << ", int = " << BFI.Freqs[Index].Integer << "\n");
830   }
831 }
832
833 static void scaleBlockData(BlockFrequencyInfoImplBase &BFI,
834                            const BlockNode &Node,
835                            const PackagedLoopData &Loop) {
836   Float F = Loop.Mass.toFloat() * Loop.Scale;
837
838   Float &Current = BFI.Freqs[Node.Index].Floating;
839   Float Updated = Current * F;
840
841   DEBUG(dbgs() << " - " << BFI.getBlockName(Node) << ": " << Current << " => "
842                << Updated << "\n");
843
844   Current = Updated;
845 }
846
847 /// \brief Unwrap a loop package.
848 ///
849 /// Visits all the members of a loop, adjusting their BlockData according to
850 /// the loop's pseudo-node.
851 static void unwrapLoopPackage(BlockFrequencyInfoImplBase &BFI,
852                               const BlockNode &Head) {
853   assert(Head.isValid());
854
855   PackagedLoopData &LoopPackage = BFI.getLoopPackage(Head);
856   DEBUG(dbgs() << "unwrap-loop-package: " << BFI.getBlockName(Head)
857                << ": mass = " << LoopPackage.Mass
858                << ", scale = " << LoopPackage.Scale << "\n");
859   scaleBlockData(BFI, Head, LoopPackage);
860
861   // Propagate the head scale through the loop.  Since members are visited in
862   // RPO, the head scale will be updated by the loop scale first, and then the
863   // final head scale will be used for updated the rest of the members.
864   for (const BlockNode &M : LoopPackage.Members) {
865     const FrequencyData &HeadData = BFI.Freqs[Head.Index];
866     FrequencyData &Freqs = BFI.Freqs[M.Index];
867     Float NewFreq = Freqs.Floating * HeadData.Floating;
868     DEBUG(dbgs() << " - " << BFI.getBlockName(M) << ": " << Freqs.Floating
869                  << " => " << NewFreq << "\n");
870     Freqs.Floating = NewFreq;
871   }
872 }
873
874 void BlockFrequencyInfoImplBase::finalizeMetrics() {
875   // Set initial frequencies from loop-local masses.
876   for (size_t Index = 0; Index < Working.size(); ++Index)
877     Freqs[Index].Floating = Working[Index].Mass.toFloat();
878
879   // Unwrap loop packages in reverse post-order, tracking min and max
880   // frequencies.
881   auto Min = Float::getLargest();
882   auto Max = Float::getZero();
883   for (size_t Index = 0; Index < Working.size(); ++Index) {
884     if (Working[Index].isLoopHeader())
885       unwrapLoopPackage(*this, BlockNode(Index));
886
887     // Update max scale.
888     Min = std::min(Min, Freqs[Index].Floating);
889     Max = std::max(Max, Freqs[Index].Floating);
890   }
891
892   // Convert to integers.
893   convertFloatingToInteger(*this, Min, Max);
894
895   // Clean up data structures.
896   cleanup(*this);
897
898   // Print out the final stats.
899   DEBUG(dump());
900 }
901
902 BlockFrequency
903 BlockFrequencyInfoImplBase::getBlockFreq(const BlockNode &Node) const {
904   if (!Node.isValid())
905     return 0;
906   return Freqs[Node.Index].Integer;
907 }
908 Float
909 BlockFrequencyInfoImplBase::getFloatingBlockFreq(const BlockNode &Node) const {
910   if (!Node.isValid())
911     return Float::getZero();
912   return Freqs[Node.Index].Floating;
913 }
914
915 std::string
916 BlockFrequencyInfoImplBase::getBlockName(const BlockNode &Node) const {
917   return std::string();
918 }
919
920 raw_ostream &
921 BlockFrequencyInfoImplBase::printBlockFreq(raw_ostream &OS,
922                                            const BlockNode &Node) const {
923   return OS << getFloatingBlockFreq(Node);
924 }
925
926 raw_ostream &
927 BlockFrequencyInfoImplBase::printBlockFreq(raw_ostream &OS,
928                                            const BlockFrequency &Freq) const {
929   Float Block(Freq.getFrequency(), 0);
930   Float Entry(getEntryFreq(), 0);
931
932   return OS << Block / Entry;
933 }