1 //===- BlockFrequencyImplInfo.cpp - Block Frequency Info Implementation ---===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // Loops should be simplified before this analysis.
12 //===----------------------------------------------------------------------===//
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"
22 //===----------------------------------------------------------------------===//
24 // PositiveFloat implementation.
26 //===----------------------------------------------------------------------===//
27 const int PositiveFloatBase::MaxExponent;
28 const int PositiveFloatBase::MinExponent;
30 static void appendDigit(std::string &Str, unsigned D) {
35 static void appendNumber(std::string &Str, uint64_t N) {
37 appendDigit(Str, N % 10);
42 static bool doesRoundUp(char Digit) {
55 static std::string toStringAPFloat(uint64_t D, int E, unsigned Precision) {
56 assert(E >= PositiveFloatBase::MinExponent);
57 assert(E <= PositiveFloatBase::MaxExponent);
59 // Find a new E, but don't let it increase past MaxExponent.
60 int LeadingZeros = PositiveFloatBase::countLeadingZeros64(D);
61 int NewE = std::min(PositiveFloatBase::MaxExponent, E + 63 - LeadingZeros);
62 int Shift = 63 - (NewE - E);
63 assert(Shift <= LeadingZeros);
64 assert(Shift == LeadingZeros || NewE == PositiveFloatBase::MaxExponent);
68 // Check for a denormal.
69 unsigned AdjustedE = E + 16383;
71 assert(E == PositiveFloatBase::MaxExponent);
75 // Build the float and print it.
76 uint64_t RawBits[2] = {D, AdjustedE};
77 APFloat Float(APFloat::x87DoubleExtended, APInt(80, RawBits));
78 SmallVector<char, 24> Chars;
79 Float.toString(Chars, Precision, 0);
80 return std::string(Chars.begin(), Chars.end());
83 static std::string stripTrailingZeros(std::string Float) {
84 size_t NonZero = Float.find_last_not_of('0');
85 assert(NonZero != std::string::npos && "no . in floating point string");
87 if (Float[NonZero] == '.')
90 return Float.substr(0, NonZero + 1);
93 std::string PositiveFloatBase::toString(uint64_t D, int16_t E, int Width,
98 // Canonicalize exponent and digits.
106 if (int Shift = std::min(int16_t(countLeadingZeros64(D)), E)) {
113 } else if (E > -64) {
115 Below0 = D << (64 + E);
116 } else if (E > -120) {
117 Below0 = D >> (-E - 64);
118 Extra = D << (128 + E);
119 ExtraShift = -64 - E;
122 // Fall back on APFloat for very small and very large numbers.
123 if (!Above0 && !Below0)
124 return toStringAPFloat(D, E, Precision);
126 // Append the digits before the decimal.
128 size_t DigitsOut = 0;
130 appendNumber(Str, Above0);
131 DigitsOut = Str.size();
134 std::reverse(Str.begin(), Str.end());
136 // Return early if there's nothing after the decimal.
140 // Append the decimal and beyond.
142 uint64_t Error = UINT64_C(1) << (64 - Width);
144 // We need to shift Below0 to the right to make space for calculating
145 // digits. Save the precision we're losing in Extra.
146 Extra = (Below0 & 0xf) << 56 | (Extra >> 8);
149 size_t AfterDot = Str.size();
159 Below0 += (Extra >> 60);
160 Extra = Extra & (UINT64_MAX >> 4);
161 appendDigit(Str, Below0 >> 60);
162 Below0 = Below0 & (UINT64_MAX >> 4);
163 if (DigitsOut || Str.back() != '0')
166 } while (Error && (Below0 << 4 | Extra >> 60) >= Error / 2 &&
167 (!Precision || DigitsOut <= Precision || SinceDot < 2));
169 // Return early for maximum precision.
170 if (!Precision || DigitsOut <= Precision)
171 return stripTrailingZeros(Str);
173 // Find where to truncate.
175 std::max(Str.size() - (DigitsOut - Precision), AfterDot + 1);
177 // Check if there's anything to truncate.
178 if (Truncate >= Str.size())
179 return stripTrailingZeros(Str);
181 bool Carry = doesRoundUp(Str[Truncate]);
183 return stripTrailingZeros(Str.substr(0, Truncate));
185 // Round with the first truncated digit.
186 for (std::string::reverse_iterator I(Str.begin() + Truncate), E = Str.rend();
200 // Add "1" in front if we still need to carry.
201 return stripTrailingZeros(std::string(Carry, '1') + Str.substr(0, Truncate));
204 raw_ostream &PositiveFloatBase::print(raw_ostream &OS, uint64_t D, int16_t E,
205 int Width, unsigned Precision) {
206 return OS << toString(D, E, Width, Precision);
209 void PositiveFloatBase::dump(uint64_t D, int16_t E, int Width) {
210 print(dbgs(), D, E, Width, 0) << "[" << Width << ":" << D << "*2^" << E
214 static std::pair<uint64_t, int16_t>
215 getRoundedFloat(uint64_t N, bool ShouldRound, int64_t Shift) {
218 // Rounding caused an overflow.
219 return std::make_pair(UINT64_C(1), Shift + 64);
220 return std::make_pair(N, Shift);
223 std::pair<uint64_t, int16_t> PositiveFloatBase::divide64(uint64_t Dividend,
225 // Input should be sanitized.
229 // Minimize size of divisor.
231 if (int Zeros = countTrailingZeros(Divisor)) {
236 // Check for powers of two.
238 return std::make_pair(Dividend, Shift);
240 // Maximize size of dividend.
241 if (int Zeros = countLeadingZeros64(Dividend)) {
246 // Start with the result of a divide.
247 uint64_t Quotient = Dividend / Divisor;
250 // Continue building the quotient with long division.
252 // TODO: continue with largers digits.
253 while (!(Quotient >> 63) && Dividend) {
254 // Shift Dividend, and check for overflow.
255 bool IsOverflow = Dividend >> 63;
260 bool DoesDivide = IsOverflow || Divisor <= Dividend;
261 Quotient = (Quotient << 1) | uint64_t(DoesDivide);
262 Dividend -= DoesDivide ? Divisor : 0;
266 if (Dividend >= getHalf(Divisor))
268 // Rounding caused an overflow in Quotient.
269 return std::make_pair(UINT64_C(1), Shift + 64);
271 return getRoundedFloat(Quotient, Dividend >= getHalf(Divisor), Shift);
274 static void addWithCarry(uint64_t &Upper, uint64_t &Lower, uint64_t N) {
275 uint64_t NewLower = Lower + (N << 32);
276 Upper += (N >> 32) + (NewLower < Lower);
280 std::pair<uint64_t, int16_t> PositiveFloatBase::multiply64(uint64_t L,
282 // Separate into two 32-bit digits (U.L).
283 uint64_t UL = L >> 32, LL = L & UINT32_MAX, UR = R >> 32, LR = R & UINT32_MAX;
285 // Compute cross products.
286 uint64_t P1 = UL * UR, P2 = UL * LR, P3 = LL * UR, P4 = LL * LR;
288 // Sum into two 64-bit digits.
289 uint64_t Upper = P1, Lower = P4;
290 addWithCarry(Upper, Lower, P2);
291 addWithCarry(Upper, Lower, P3);
293 // Check for the lower 32 bits.
295 return std::make_pair(Lower, 0);
297 // Shift as little as possible to maximize precision.
298 unsigned LeadingZeros = countLeadingZeros64(Upper);
299 int16_t Shift = 64 - LeadingZeros;
301 Upper = Upper << LeadingZeros | Lower >> Shift;
302 bool ShouldRound = Shift && (Lower & UINT64_C(1) << (Shift - 1));
303 return getRoundedFloat(Upper, ShouldRound, Shift);
306 //===----------------------------------------------------------------------===//
308 // BlockMass implementation.
310 //===----------------------------------------------------------------------===//
311 BlockMass &BlockMass::operator*=(const BranchProbability &P) {
312 uint32_t N = P.getNumerator(), D = P.getDenominator();
313 assert(D || "divide by 0");
314 assert(N <= D || "fraction greater than 1");
316 // Fast path for multiplying by 1.0.
320 // Get as much precision as we can.
321 int Shift = countLeadingZeros(Mass);
322 uint64_t ShiftedQuotient = (Mass << Shift) / D;
323 uint64_t Product = ShiftedQuotient * N >> Shift;
325 // Now check for what's lost.
326 uint64_t Left = ShiftedQuotient * (D - N) >> Shift;
327 uint64_t Lost = Mass - Product - Left;
329 // TODO: prove this assertion.
330 assert(Lost <= UINT32_MAX);
332 // Take the product plus a portion of the spoils.
333 Mass = Product + Lost * N / D;
337 PositiveFloat<uint64_t> BlockMass::toFloat() const {
339 return PositiveFloat<uint64_t>(1, 0);
340 return PositiveFloat<uint64_t>(getMass() + 1, -64);
343 void BlockMass::dump() const { print(dbgs()); }
345 static char getHexDigit(int N) {
351 raw_ostream &BlockMass::print(raw_ostream &OS) const {
352 for (int Digits = 0; Digits < 16; ++Digits)
353 OS << getHexDigit(Mass >> (60 - Digits * 4) & 0xf);
357 //===----------------------------------------------------------------------===//
359 // BlockFrequencyInfoImpl implementation.
361 //===----------------------------------------------------------------------===//
364 typedef BlockFrequencyInfoImplBase::BlockNode BlockNode;
365 typedef BlockFrequencyInfoImplBase::Distribution Distribution;
366 typedef BlockFrequencyInfoImplBase::Distribution::WeightList WeightList;
367 typedef BlockFrequencyInfoImplBase::Float Float;
368 typedef BlockFrequencyInfoImplBase::PackagedLoopData PackagedLoopData;
369 typedef BlockFrequencyInfoImplBase::Weight Weight;
370 typedef BlockFrequencyInfoImplBase::FrequencyData FrequencyData;
372 /// \brief Dithering mass distributer.
374 /// This class splits up a single mass into portions by weight, dithering to
375 /// spread out error. No mass is lost. The dithering precision depends on the
376 /// precision of the product of \a BlockMass and \a BranchProbability.
378 /// The distribution algorithm follows.
380 /// 1. Initialize by saving the sum of the weights in \a RemWeight and the
381 /// mass to distribute in \a RemMass.
383 /// 2. For each portion:
385 /// 1. Construct a branch probability, P, as the portion's weight divided
386 /// by the current value of \a RemWeight.
387 /// 2. Calculate the portion's mass as \a RemMass times P.
388 /// 3. Update \a RemWeight and \a RemMass at each portion by subtracting
389 /// the current portion's weight and mass.
391 /// Mass is distributed in two ways: full distribution and forward
392 /// distribution. The latter ignores backedges, and uses the parallel fields
393 /// \a RemForwardWeight and \a RemForwardMass.
394 struct DitheringDistributer {
396 uint32_t RemForwardWeight;
399 BlockMass RemForwardMass;
401 DitheringDistributer(Distribution &Dist, const BlockMass &Mass);
403 BlockMass takeLocalMass(uint32_t Weight) {
404 (void)takeMass(Weight);
405 return takeForwardMass(Weight);
407 BlockMass takeExitMass(uint32_t Weight) {
408 (void)takeForwardMass(Weight);
409 return takeMass(Weight);
411 BlockMass takeBackedgeMass(uint32_t Weight) { return takeMass(Weight); }
414 BlockMass takeForwardMass(uint32_t Weight);
415 BlockMass takeMass(uint32_t Weight);
419 DitheringDistributer::DitheringDistributer(Distribution &Dist,
420 const BlockMass &Mass) {
422 RemWeight = Dist.Total;
423 RemForwardWeight = Dist.ForwardTotal;
425 RemForwardMass = Dist.ForwardTotal ? Mass : BlockMass();
428 BlockMass DitheringDistributer::takeForwardMass(uint32_t Weight) {
429 // Compute the amount of mass to take.
430 assert(Weight && "invalid weight");
431 assert(Weight <= RemForwardWeight);
432 BlockMass Mass = RemForwardMass * BranchProbability(Weight, RemForwardWeight);
434 // Decrement totals (dither).
435 RemForwardWeight -= Weight;
436 RemForwardMass -= Mass;
439 BlockMass DitheringDistributer::takeMass(uint32_t Weight) {
440 assert(Weight && "invalid weight");
441 assert(Weight <= RemWeight);
442 BlockMass Mass = RemMass * BranchProbability(Weight, RemWeight);
444 // Decrement totals (dither).
450 void Distribution::add(const BlockNode &Node, uint64_t Amount,
451 Weight::DistType Type) {
452 assert(Amount && "invalid weight of 0");
453 uint64_t NewTotal = Total + Amount;
455 // Check for overflow. It should be impossible to overflow twice.
456 bool IsOverflow = NewTotal < Total;
457 assert(!(DidOverflow && IsOverflow) && "unexpected repeated overflow");
458 DidOverflow |= IsOverflow;
468 Weights.push_back(W);
470 if (Type == Weight::Backedge)
473 // Update forward total. Don't worry about overflow here, since then Total
474 // will exceed 32-bits and they'll both be recomputed in normalize().
475 ForwardTotal += Amount;
478 static void combineWeight(Weight &W, const Weight &OtherW) {
479 assert(OtherW.TargetNode.isValid());
484 assert(W.Type == OtherW.Type);
485 assert(W.TargetNode == OtherW.TargetNode);
486 assert(W.Amount < W.Amount + OtherW.Amount);
487 W.Amount += OtherW.Amount;
489 static void combineWeightsBySorting(WeightList &Weights) {
490 // Sort so edges to the same node are adjacent.
491 std::sort(Weights.begin(), Weights.end(),
493 const Weight &R) { return L.TargetNode < R.TargetNode; });
495 // Combine adjacent edges.
496 WeightList::iterator O = Weights.begin();
497 for (WeightList::const_iterator I = O, L = O, E = Weights.end(); I != E;
501 // Find the adjacent weights to the same node.
502 for (++L; L != E && I->TargetNode == L->TargetNode; ++L)
503 combineWeight(*O, *L);
506 // Erase extra entries.
507 Weights.erase(O, Weights.end());
510 static void combineWeightsByHashing(WeightList &Weights) {
511 // Collect weights into a DenseMap.
512 typedef DenseMap<BlockNode::IndexType, Weight> HashTable;
513 HashTable Combined(NextPowerOf2(2 * Weights.size()));
514 for (const Weight &W : Weights)
515 combineWeight(Combined[W.TargetNode.Index], W);
517 // Check whether anything changed.
518 if (Weights.size() == Combined.size())
521 // Fill in the new weights.
523 Weights.reserve(Combined.size());
524 for (const auto &I : Combined)
525 Weights.push_back(I.second);
527 static void combineWeights(WeightList &Weights) {
528 // Use a hash table for many successors to keep this linear.
529 if (Weights.size() > 128) {
530 combineWeightsByHashing(Weights);
534 combineWeightsBySorting(Weights);
536 static uint64_t shiftRightAndRound(uint64_t N, int Shift) {
541 return (N >> Shift) + (UINT64_C(1) & N >> (Shift - 1));
543 void Distribution::normalize() {
544 // Early exit for termination nodes.
548 // Only bother if there are multiple successors.
549 if (Weights.size() > 1)
550 combineWeights(Weights);
552 // Early exit when combined into a single successor.
553 if (Weights.size() == 1) {
555 ForwardTotal = Weights.front().Type != Weight::Backedge;
556 Weights.front().Amount = 1;
560 // Determine how much to shift right so that the total fits into 32-bits.
562 // If we shift at all, shift by 1 extra. Otherwise, the lower limit of 1
563 // for each weight can cause a 32-bit overflow.
567 else if (Total > UINT32_MAX)
568 Shift = 33 - countLeadingZeros(Total);
570 // Early exit if nothing needs to be scaled.
574 // Recompute the total through accumulation (rather than shifting it) so that
575 // it's accurate after shifting. ForwardTotal is dirty here anyway.
579 // Sum the weights to each node and shift right if necessary.
580 for (Weight &W : Weights) {
581 // Scale down below UINT32_MAX. Since Shift is larger than necessary, we
582 // can round here without concern about overflow.
583 assert(W.TargetNode.isValid());
584 W.Amount = std::max(UINT64_C(1), shiftRightAndRound(W.Amount, Shift));
585 assert(W.Amount <= UINT32_MAX);
589 if (W.Type == Weight::Backedge)
592 // Update the forward total.
593 ForwardTotal += W.Amount;
595 assert(Total <= UINT32_MAX);
598 void BlockFrequencyInfoImplBase::clear() {
599 *this = BlockFrequencyInfoImplBase();
602 /// \brief Clear all memory not needed downstream.
604 /// Releases all memory not used downstream. In particular, saves Freqs.
605 static void cleanup(BlockFrequencyInfoImplBase &BFI) {
606 std::vector<FrequencyData> SavedFreqs(std::move(BFI.Freqs));
608 BFI.Freqs = std::move(SavedFreqs);
611 /// \brief Get a possibly packaged node.
613 /// Get the node currently representing Node, which could be a containing
616 /// This function should only be called when distributing mass. As long as
617 /// there are no irreducilbe edges to Node, then it will have complexity O(1)
620 /// In general, the complexity is O(L), where L is the number of loop headers
621 /// Node has been packaged into. Since this method is called in the context
622 /// of distributing mass, L will be the number of loop headers an early exit
623 /// edge jumps out of.
624 static BlockNode getPackagedNode(const BlockFrequencyInfoImplBase &BFI,
625 const BlockNode &Node) {
626 assert(Node.isValid());
627 if (!BFI.Working[Node.Index].IsPackaged)
629 if (!BFI.Working[Node.Index].ContainingLoop.isValid())
631 return getPackagedNode(BFI, BFI.Working[Node.Index].ContainingLoop);
634 /// \brief Get the appropriate mass for a possible pseudo-node loop package.
636 /// Get appropriate mass for Node. If Node is a loop-header (whose loop has
637 /// been packaged), returns the mass of its pseudo-node. If it's a node inside
638 /// a packaged loop, it returns the loop's pseudo-node.
639 static BlockMass &getPackageMass(BlockFrequencyInfoImplBase &BFI,
640 const BlockNode &Node) {
641 assert(Node.isValid());
642 assert(!BFI.Working[Node.Index].IsPackaged);
643 if (!BFI.Working[Node.Index].IsAPackage)
644 return BFI.Working[Node.Index].Mass;
646 return BFI.getLoopPackage(Node).Mass;
649 void BlockFrequencyInfoImplBase::addToDist(Distribution &Dist,
650 const BlockNode &LoopHead,
651 const BlockNode &Pred,
652 const BlockNode &Succ,
658 auto debugSuccessor = [&](const char *Type, const BlockNode &Resolved) {
660 << " [" << Type << "] weight = " << Weight;
661 if (Succ != LoopHead)
662 dbgs() << ", succ = " << getBlockName(Succ);
663 if (Resolved != Succ)
664 dbgs() << ", resolved = " << getBlockName(Resolved);
667 (void)debugSuccessor;
670 if (Succ == LoopHead) {
671 DEBUG(debugSuccessor("backedge", Succ));
672 Dist.addBackedge(LoopHead, Weight);
675 BlockNode Resolved = getPackagedNode(*this, Succ);
676 assert(Resolved != LoopHead);
678 if (Working[Resolved.Index].ContainingLoop != LoopHead) {
679 DEBUG(debugSuccessor(" exit ", Resolved));
680 Dist.addExit(Resolved, Weight);
684 if (!LoopHead.isValid() && Resolved < Pred) {
685 // Irreducible backedge. Skip this edge in the distribution.
686 DEBUG(debugSuccessor("skipped ", Resolved));
690 DEBUG(debugSuccessor(" local ", Resolved));
691 Dist.addLocal(Resolved, Weight);
694 void BlockFrequencyInfoImplBase::addLoopSuccessorsToDist(
695 const BlockNode &LoopHead, const BlockNode &LocalLoopHead,
696 Distribution &Dist) {
697 PackagedLoopData &LoopPackage = getLoopPackage(LocalLoopHead);
698 const PackagedLoopData::ExitMap &Exits = LoopPackage.Exits;
700 // Copy the exit map into Dist.
701 for (const auto &I : Exits)
702 addToDist(Dist, LoopHead, LocalLoopHead, I.first, I.second.getMass());
704 // We don't need this map any more. Clear it to prevent quadratic memory
705 // usage in deeply nested loops with irreducible control flow.
706 LoopPackage.Exits.clear();
709 /// \brief Get the maximum allowed loop scale.
711 /// Gives the maximum number of estimated iterations allowed for a loop.
712 /// Downstream users have trouble with very large numbers (even within
713 /// 64-bits). Perhaps they can be changed to use PositiveFloat.
715 /// TODO: change downstream users so that this can be increased or removed.
716 static Float getMaxLoopScale() { return Float(1, 12); }
718 /// \brief Compute the loop scale for a loop.
719 void BlockFrequencyInfoImplBase::computeLoopScale(const BlockNode &LoopHead) {
720 // Compute loop scale.
721 DEBUG(dbgs() << "compute-loop-scale: " << getBlockName(LoopHead) << "\n");
723 // LoopScale == 1 / ExitMass
724 // ExitMass == HeadMass - BackedgeMass
725 PackagedLoopData &LoopPackage = getLoopPackage(LoopHead);
726 BlockMass ExitMass = BlockMass::getFull() - LoopPackage.BackedgeMass;
728 // Block scale stores the inverse of the scale.
729 LoopPackage.Scale = ExitMass.toFloat().inverse();
731 DEBUG(dbgs() << " - exit-mass = " << ExitMass << " (" << BlockMass::getFull()
732 << " - " << LoopPackage.BackedgeMass << ")\n"
733 << " - scale = " << LoopPackage.Scale << "\n");
735 if (LoopPackage.Scale > getMaxLoopScale()) {
736 LoopPackage.Scale = getMaxLoopScale();
737 DEBUG(dbgs() << " - reduced-to-max-scale: " << getMaxLoopScale() << "\n");
741 /// \brief Package up a loop.
742 void BlockFrequencyInfoImplBase::packageLoop(const BlockNode &LoopHead) {
743 DEBUG(dbgs() << "packaging-loop: " << getBlockName(LoopHead) << "\n");
744 Working[LoopHead.Index].IsAPackage = true;
745 for (const BlockNode &M : getLoopPackage(LoopHead).Members) {
746 DEBUG(dbgs() << " - node: " << getBlockName(M.Index) << "\n");
747 Working[M.Index].IsPackaged = true;
751 void BlockFrequencyInfoImplBase::distributeMass(const BlockNode &Source,
752 const BlockNode &LoopHead,
753 Distribution &Dist) {
754 BlockMass Mass = getPackageMass(*this, Source);
755 DEBUG(dbgs() << " => mass: " << Mass
756 << " ( general | forward )\n");
758 // Distribute mass to successors as laid out in Dist.
759 DitheringDistributer D(Dist, Mass);
762 auto debugAssign = [&](const BlockNode &T, const BlockMass &M,
764 dbgs() << " => assign " << M << " (" << D.RemMass << "|"
765 << D.RemForwardMass << ")";
767 dbgs() << " [" << Desc << "]";
769 dbgs() << " to " << getBlockName(T);
775 PackagedLoopData *LoopPackage = 0;
776 if (LoopHead.isValid())
777 LoopPackage = &getLoopPackage(LoopHead);
778 for (const Weight &W : Dist.Weights) {
779 // Check for a local edge (forward and non-exit).
780 if (W.Type == Weight::Local) {
781 BlockMass Local = D.takeLocalMass(W.Amount);
782 getPackageMass(*this, W.TargetNode) += Local;
783 DEBUG(debugAssign(W.TargetNode, Local, nullptr));
787 // Backedges and exits only make sense if we're processing a loop.
788 assert(LoopPackage && "backedge or exit outside of loop");
790 // Check for a backedge.
791 if (W.Type == Weight::Backedge) {
792 BlockMass Back = D.takeBackedgeMass(W.Amount);
793 LoopPackage->BackedgeMass += Back;
794 DEBUG(debugAssign(BlockNode(), Back, "back"));
798 // This must be an exit.
799 assert(W.Type == Weight::Exit);
800 BlockMass Exit = D.takeExitMass(W.Amount);
801 LoopPackage->Exits.push_back(std::make_pair(W.TargetNode, Exit));
802 DEBUG(debugAssign(W.TargetNode, Exit, "exit"));
806 static void convertFloatingToInteger(BlockFrequencyInfoImplBase &BFI,
807 const Float &Min, const Float &Max) {
808 // Scale the Factor to a size that creates integers. Ideally, integers would
809 // be scaled so that Max == UINT64_MAX so that they can be best
810 // differentiated. However, the register allocator currently deals poorly
811 // with large numbers. Instead, push Min up a little from 1 to give some
812 // room to differentiate small, unequal numbers.
814 // TODO: fix issues downstream so that ScalingFactor can be Float(1,64)/Max.
815 Float ScalingFactor = Min.inverse();
816 if ((Max / Min).lg() < 60)
819 // Translate the floats to integers.
820 DEBUG(dbgs() << "float-to-int: min = " << Min << ", max = " << Max
821 << ", factor = " << ScalingFactor << "\n");
822 for (size_t Index = 0; Index < BFI.Freqs.size(); ++Index) {
823 Float Scaled = BFI.Freqs[Index].Floating * ScalingFactor;
824 BFI.Freqs[Index].Integer = std::max(UINT64_C(1), Scaled.toInt<uint64_t>());
825 DEBUG(dbgs() << " - " << BFI.getBlockName(Index) << ": float = "
826 << BFI.Freqs[Index].Floating << ", scaled = " << Scaled
827 << ", int = " << BFI.Freqs[Index].Integer << "\n");
831 static void scaleBlockData(BlockFrequencyInfoImplBase &BFI,
832 const BlockNode &Node,
833 const PackagedLoopData &Loop) {
834 Float F = Loop.Mass.toFloat() * Loop.Scale;
836 Float &Current = BFI.Freqs[Node.Index].Floating;
837 Float Updated = Current * F;
839 DEBUG(dbgs() << " - " << BFI.getBlockName(Node) << ": " << Current << " => "
845 /// \brief Unwrap a loop package.
847 /// Visits all the members of a loop, adjusting their BlockData according to
848 /// the loop's pseudo-node.
849 static void unwrapLoopPackage(BlockFrequencyInfoImplBase &BFI,
850 const BlockNode &Head) {
851 assert(Head.isValid());
853 PackagedLoopData &LoopPackage = BFI.getLoopPackage(Head);
854 DEBUG(dbgs() << "unwrap-loop-package: " << BFI.getBlockName(Head)
855 << ": mass = " << LoopPackage.Mass
856 << ", scale = " << LoopPackage.Scale << "\n");
857 scaleBlockData(BFI, Head, LoopPackage);
859 // Propagate the head scale through the loop. Since members are visited in
860 // RPO, the head scale will be updated by the loop scale first, and then the
861 // final head scale will be used for updated the rest of the members.
862 for (const BlockNode &M : LoopPackage.Members) {
863 const FrequencyData &HeadData = BFI.Freqs[Head.Index];
864 FrequencyData &Freqs = BFI.Freqs[M.Index];
865 Float NewFreq = Freqs.Floating * HeadData.Floating;
866 DEBUG(dbgs() << " - " << BFI.getBlockName(M) << ": " << Freqs.Floating
867 << " => " << NewFreq << "\n");
868 Freqs.Floating = NewFreq;
872 void BlockFrequencyInfoImplBase::finalizeMetrics() {
873 // Set initial frequencies from loop-local masses.
874 for (size_t Index = 0; Index < Working.size(); ++Index)
875 Freqs[Index].Floating = Working[Index].Mass.toFloat();
877 // Unwrap loop packages in reverse post-order, tracking min and max
879 auto Min = Float::getLargest();
880 auto Max = Float::getZero();
881 for (size_t Index = 0; Index < Working.size(); ++Index) {
882 if (Working[Index].isLoopHeader())
883 unwrapLoopPackage(*this, BlockNode(Index));
886 Min = std::min(Min, Freqs[Index].Floating);
887 Max = std::max(Max, Freqs[Index].Floating);
890 // Convert to integers.
891 convertFloatingToInteger(*this, Min, Max);
893 // Clean up data structures.
896 // Print out the final stats.
901 BlockFrequencyInfoImplBase::getBlockFreq(const BlockNode &Node) const {
904 return Freqs[Node.Index].Integer;
907 BlockFrequencyInfoImplBase::getFloatingBlockFreq(const BlockNode &Node) const {
909 return Float::getZero();
910 return Freqs[Node.Index].Floating;
914 BlockFrequencyInfoImplBase::getBlockName(const BlockNode &Node) const {
915 return std::string();
919 BlockFrequencyInfoImplBase::printBlockFreq(raw_ostream &OS,
920 const BlockNode &Node) const {
921 return OS << getFloatingBlockFreq(Node);
925 BlockFrequencyInfoImplBase::printBlockFreq(raw_ostream &OS,
926 const BlockFrequency &Freq) const {
927 Float Block(Freq.getFrequency(), 0);
928 Float Entry(getEntryFreq(), 0);
930 return OS << Block / Entry;