blob: 903a263a65fee860def7cd346f5c107524fecbf0 [file] [log] [blame]
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +00001//===- 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
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +000014#include "llvm/Analysis/BlockFrequencyInfoImpl.h"
Duncan P. N. Exon Smith87c40fd2014-05-06 01:57:42 +000015#include "llvm/ADT/SCCIterator.h"
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +000016#include "llvm/Support/raw_ostream.h"
Duncan P. N. Exon Smith57cbdfc2014-12-05 19:13:42 +000017#include <numeric>
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +000018
19using namespace llvm;
Duncan P. N. Exon Smithc5a31392014-04-28 20:02:29 +000020using namespace llvm::bfi_detail;
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +000021
Chandler Carruth1b9dde02014-04-22 02:02:50 +000022#define DEBUG_TYPE "block-freq"
23
Duncan P. N. Exon Smithbeaf8132014-06-24 00:26:13 +000024ScaledNumber<uint64_t> BlockMass::toScaled() const {
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +000025 if (isFull())
Duncan P. N. Exon Smithc379c872014-06-23 23:36:17 +000026 return ScaledNumber<uint64_t>(1, 0);
27 return ScaledNumber<uint64_t>(getMass() + 1, -64);
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +000028}
29
30void BlockMass::dump() const { print(dbgs()); }
31
32static char getHexDigit(int N) {
33 assert(N < 16);
34 if (N < 10)
35 return '0' + N;
36 return 'a' + N - 10;
37}
38raw_ostream &BlockMass::print(raw_ostream &OS) const {
39 for (int Digits = 0; Digits < 16; ++Digits)
40 OS << getHexDigit(Mass >> (60 - Digits * 4) & 0xf);
41 return OS;
42}
43
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +000044namespace {
45
46typedef BlockFrequencyInfoImplBase::BlockNode BlockNode;
47typedef BlockFrequencyInfoImplBase::Distribution Distribution;
48typedef BlockFrequencyInfoImplBase::Distribution::WeightList WeightList;
Duncan P. N. Exon Smithbeaf8132014-06-24 00:26:13 +000049typedef BlockFrequencyInfoImplBase::Scaled64 Scaled64;
Duncan P. N. Exon Smithcc88ebf2014-04-22 03:31:31 +000050typedef BlockFrequencyInfoImplBase::LoopData LoopData;
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +000051typedef BlockFrequencyInfoImplBase::Weight Weight;
52typedef BlockFrequencyInfoImplBase::FrequencyData FrequencyData;
53
54/// \brief Dithering mass distributer.
55///
56/// This class splits up a single mass into portions by weight, dithering to
57/// spread out error. No mass is lost. The dithering precision depends on the
58/// precision of the product of \a BlockMass and \a BranchProbability.
59///
60/// The distribution algorithm follows.
61///
62/// 1. Initialize by saving the sum of the weights in \a RemWeight and the
63/// mass to distribute in \a RemMass.
64///
65/// 2. For each portion:
66///
67/// 1. Construct a branch probability, P, as the portion's weight divided
68/// by the current value of \a RemWeight.
69/// 2. Calculate the portion's mass as \a RemMass times P.
70/// 3. Update \a RemWeight and \a RemMass at each portion by subtracting
71/// the current portion's weight and mass.
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +000072struct DitheringDistributer {
73 uint32_t RemWeight;
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +000074 BlockMass RemMass;
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +000075
76 DitheringDistributer(Distribution &Dist, const BlockMass &Mass);
77
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +000078 BlockMass takeMass(uint32_t Weight);
79};
Duncan P. N. Exon Smithb5650e52014-07-11 23:56:50 +000080
81} // end namespace
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +000082
83DitheringDistributer::DitheringDistributer(Distribution &Dist,
84 const BlockMass &Mass) {
85 Dist.normalize();
86 RemWeight = Dist.Total;
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +000087 RemMass = Mass;
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +000088}
89
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +000090BlockMass DitheringDistributer::takeMass(uint32_t Weight) {
91 assert(Weight && "invalid weight");
92 assert(Weight <= RemWeight);
93 BlockMass Mass = RemMass * BranchProbability(Weight, RemWeight);
94
95 // Decrement totals (dither).
96 RemWeight -= Weight;
97 RemMass -= Mass;
98 return Mass;
99}
100
101void Distribution::add(const BlockNode &Node, uint64_t Amount,
102 Weight::DistType Type) {
103 assert(Amount && "invalid weight of 0");
104 uint64_t NewTotal = Total + Amount;
105
106 // Check for overflow. It should be impossible to overflow twice.
107 bool IsOverflow = NewTotal < Total;
108 assert(!(DidOverflow && IsOverflow) && "unexpected repeated overflow");
109 DidOverflow |= IsOverflow;
110
111 // Update the total.
112 Total = NewTotal;
113
114 // Save the weight.
Duncan P. N. Exon Smith60755102014-07-12 00:26:00 +0000115 Weights.push_back(Weight(Type, Node, Amount));
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000116}
117
118static void combineWeight(Weight &W, const Weight &OtherW) {
119 assert(OtherW.TargetNode.isValid());
120 if (!W.Amount) {
121 W = OtherW;
122 return;
123 }
124 assert(W.Type == OtherW.Type);
125 assert(W.TargetNode == OtherW.TargetNode);
Duncan P. N. Exon Smith57cbdfc2014-12-05 19:13:42 +0000126 assert(OtherW.Amount && "Expected non-zero weight");
127 if (W.Amount > W.Amount + OtherW.Amount)
128 // Saturate on overflow.
129 W.Amount = UINT64_MAX;
130 else
131 W.Amount += OtherW.Amount;
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000132}
133static void combineWeightsBySorting(WeightList &Weights) {
134 // Sort so edges to the same node are adjacent.
135 std::sort(Weights.begin(), Weights.end(),
136 [](const Weight &L,
137 const Weight &R) { return L.TargetNode < R.TargetNode; });
138
139 // Combine adjacent edges.
140 WeightList::iterator O = Weights.begin();
141 for (WeightList::const_iterator I = O, L = O, E = Weights.end(); I != E;
142 ++O, (I = L)) {
143 *O = *I;
144
145 // Find the adjacent weights to the same node.
146 for (++L; L != E && I->TargetNode == L->TargetNode; ++L)
147 combineWeight(*O, *L);
148 }
149
150 // Erase extra entries.
151 Weights.erase(O, Weights.end());
152 return;
153}
154static void combineWeightsByHashing(WeightList &Weights) {
155 // Collect weights into a DenseMap.
156 typedef DenseMap<BlockNode::IndexType, Weight> HashTable;
157 HashTable Combined(NextPowerOf2(2 * Weights.size()));
158 for (const Weight &W : Weights)
159 combineWeight(Combined[W.TargetNode.Index], W);
160
161 // Check whether anything changed.
162 if (Weights.size() == Combined.size())
163 return;
164
165 // Fill in the new weights.
166 Weights.clear();
167 Weights.reserve(Combined.size());
168 for (const auto &I : Combined)
169 Weights.push_back(I.second);
170}
171static void combineWeights(WeightList &Weights) {
172 // Use a hash table for many successors to keep this linear.
173 if (Weights.size() > 128) {
174 combineWeightsByHashing(Weights);
175 return;
176 }
177
178 combineWeightsBySorting(Weights);
179}
180static uint64_t shiftRightAndRound(uint64_t N, int Shift) {
181 assert(Shift >= 0);
182 assert(Shift < 64);
183 if (!Shift)
184 return N;
185 return (N >> Shift) + (UINT64_C(1) & N >> (Shift - 1));
186}
187void Distribution::normalize() {
188 // Early exit for termination nodes.
189 if (Weights.empty())
190 return;
191
192 // Only bother if there are multiple successors.
193 if (Weights.size() > 1)
194 combineWeights(Weights);
195
196 // Early exit when combined into a single successor.
197 if (Weights.size() == 1) {
198 Total = 1;
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000199 Weights.front().Amount = 1;
200 return;
201 }
202
203 // Determine how much to shift right so that the total fits into 32-bits.
204 //
205 // If we shift at all, shift by 1 extra. Otherwise, the lower limit of 1
206 // for each weight can cause a 32-bit overflow.
207 int Shift = 0;
208 if (DidOverflow)
209 Shift = 33;
210 else if (Total > UINT32_MAX)
211 Shift = 33 - countLeadingZeros(Total);
212
213 // Early exit if nothing needs to be scaled.
Duncan P. N. Exon Smith57cbdfc2014-12-05 19:13:42 +0000214 if (!Shift) {
215 // If we didn't overflow then combineWeights() shouldn't have changed the
216 // sum of the weights, but let's double-check.
217 assert(Total == std::accumulate(Weights.begin(), Weights.end(), UINT64_C(0),
218 [](uint64_t Sum, const Weight &W) {
219 return Sum + W.Amount;
220 }) &&
221 "Expected total to be correct");
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000222 return;
Duncan P. N. Exon Smith57cbdfc2014-12-05 19:13:42 +0000223 }
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000224
225 // Recompute the total through accumulation (rather than shifting it) so that
Duncan P. N. Exon Smith57cbdfc2014-12-05 19:13:42 +0000226 // it's accurate after shifting and any changes combineWeights() made above.
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000227 Total = 0;
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000228
229 // Sum the weights to each node and shift right if necessary.
230 for (Weight &W : Weights) {
231 // Scale down below UINT32_MAX. Since Shift is larger than necessary, we
232 // can round here without concern about overflow.
233 assert(W.TargetNode.isValid());
234 W.Amount = std::max(UINT64_C(1), shiftRightAndRound(W.Amount, Shift));
235 assert(W.Amount <= UINT32_MAX);
236
237 // Update the total.
238 Total += W.Amount;
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000239 }
240 assert(Total <= UINT32_MAX);
241}
242
243void BlockFrequencyInfoImplBase::clear() {
Duncan P. N. Exon Smithdc2d66e2014-04-22 03:31:34 +0000244 // Swap with a default-constructed std::vector, since std::vector<>::clear()
245 // does not actually clear heap storage.
246 std::vector<FrequencyData>().swap(Freqs);
247 std::vector<WorkingData>().swap(Working);
Duncan P. N. Exon Smithfc7dc932014-04-25 04:30:06 +0000248 Loops.clear();
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000249}
250
251/// \brief Clear all memory not needed downstream.
252///
253/// Releases all memory not used downstream. In particular, saves Freqs.
254static void cleanup(BlockFrequencyInfoImplBase &BFI) {
255 std::vector<FrequencyData> SavedFreqs(std::move(BFI.Freqs));
256 BFI.clear();
257 BFI.Freqs = std::move(SavedFreqs);
258}
259
Duncan P. N. Exon Smithc5a31392014-04-28 20:02:29 +0000260bool BlockFrequencyInfoImplBase::addToDist(Distribution &Dist,
Duncan P. N. Exon Smithd1320402014-04-25 04:38:01 +0000261 const LoopData *OuterLoop,
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000262 const BlockNode &Pred,
263 const BlockNode &Succ,
264 uint64_t Weight) {
265 if (!Weight)
266 Weight = 1;
267
Duncan P. N. Exon Smith39cc6482014-04-25 04:38:06 +0000268 auto isLoopHeader = [&OuterLoop](const BlockNode &Node) {
269 return OuterLoop && OuterLoop->isHeader(Node);
270 };
Duncan P. N. Exon Smithd1320402014-04-25 04:38:01 +0000271
Duncan P. N. Exon Smithda5eaed2014-04-25 18:47:04 +0000272 BlockNode Resolved = Working[Succ.Index].getResolvedNode();
273
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000274#ifndef NDEBUG
Duncan P. N. Exon Smithda5eaed2014-04-25 18:47:04 +0000275 auto debugSuccessor = [&](const char *Type) {
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000276 dbgs() << " =>"
277 << " [" << Type << "] weight = " << Weight;
Duncan P. N. Exon Smithda5eaed2014-04-25 18:47:04 +0000278 if (!isLoopHeader(Resolved))
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000279 dbgs() << ", succ = " << getBlockName(Succ);
280 if (Resolved != Succ)
281 dbgs() << ", resolved = " << getBlockName(Resolved);
282 dbgs() << "\n";
283 };
284 (void)debugSuccessor;
285#endif
286
Duncan P. N. Exon Smithda5eaed2014-04-25 18:47:04 +0000287 if (isLoopHeader(Resolved)) {
288 DEBUG(debugSuccessor("backedge"));
Diego Novillo9a779622015-06-16 19:10:58 +0000289 Dist.addBackedge(Resolved, Weight);
Duncan P. N. Exon Smithc5a31392014-04-28 20:02:29 +0000290 return true;
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000291 }
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000292
Duncan P. N. Exon Smith39cc6482014-04-25 04:38:06 +0000293 if (Working[Resolved.Index].getContainingLoop() != OuterLoop) {
Duncan P. N. Exon Smithda5eaed2014-04-25 18:47:04 +0000294 DEBUG(debugSuccessor(" exit "));
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000295 Dist.addExit(Resolved, Weight);
Duncan P. N. Exon Smithc5a31392014-04-28 20:02:29 +0000296 return true;
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000297 }
298
Duncan P. N. Exon Smithb3380ea2014-04-22 03:31:53 +0000299 if (Resolved < Pred) {
Duncan P. N. Exon Smithc5a31392014-04-28 20:02:29 +0000300 if (!isLoopHeader(Pred)) {
301 // If OuterLoop is an irreducible loop, we can't actually handle this.
302 assert((!OuterLoop || !OuterLoop->isIrreducible()) &&
303 "unhandled irreducible control flow");
304
305 // Irreducible backedge. Abort.
306 DEBUG(debugSuccessor("abort!!!"));
307 return false;
308 }
309
310 // If "Pred" is a loop header, then this isn't really a backedge; rather,
311 // OuterLoop must be irreducible. These false backedges can come only from
312 // secondary loop headers.
313 assert(OuterLoop && OuterLoop->isIrreducible() && !isLoopHeader(Resolved) &&
314 "unhandled irreducible control flow");
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000315 }
316
Duncan P. N. Exon Smithda5eaed2014-04-25 18:47:04 +0000317 DEBUG(debugSuccessor(" local "));
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000318 Dist.addLocal(Resolved, Weight);
Duncan P. N. Exon Smithc5a31392014-04-28 20:02:29 +0000319 return true;
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000320}
321
Duncan P. N. Exon Smithc5a31392014-04-28 20:02:29 +0000322bool BlockFrequencyInfoImplBase::addLoopSuccessorsToDist(
Duncan P. N. Exon Smithd1320402014-04-25 04:38:01 +0000323 const LoopData *OuterLoop, LoopData &Loop, Distribution &Dist) {
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000324 // Copy the exit map into Dist.
Duncan P. N. Exon Smithd1320402014-04-25 04:38:01 +0000325 for (const auto &I : Loop.Exits)
Duncan P. N. Exon Smithc5a31392014-04-28 20:02:29 +0000326 if (!addToDist(Dist, OuterLoop, Loop.getHeader(), I.first,
327 I.second.getMass()))
328 // Irreducible backedge.
329 return false;
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000330
Duncan P. N. Exon Smithc5a31392014-04-28 20:02:29 +0000331 return true;
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000332}
333
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000334/// \brief Compute the loop scale for a loop.
Duncan P. N. Exon Smithd1320402014-04-25 04:38:01 +0000335void BlockFrequencyInfoImplBase::computeLoopScale(LoopData &Loop) {
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000336 // Compute loop scale.
Duncan P. N. Exon Smithc5a31392014-04-28 20:02:29 +0000337 DEBUG(dbgs() << "compute-loop-scale: " << getLoopName(Loop) << "\n");
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000338
Diego Novilloa354f482015-04-01 17:42:27 +0000339 // Infinite loops need special handling. If we give the back edge an infinite
340 // mass, they may saturate all the other scales in the function down to 1,
341 // making all the other region temperatures look exactly the same. Choose an
342 // arbitrary scale to avoid these issues.
343 //
344 // FIXME: An alternate way would be to select a symbolic scale which is later
345 // replaced to be the maximum of all computed scales plus 1. This would
346 // appropriately describe the loop as having a large scale, without skewing
347 // the final frequency computation.
348 const Scaled64 InifiniteLoopScale(1, 12);
349
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000350 // LoopScale == 1 / ExitMass
351 // ExitMass == HeadMass - BackedgeMass
Diego Novillo9a779622015-06-16 19:10:58 +0000352 BlockMass TotalBackedgeMass;
353 for (auto &Mass : Loop.BackedgeMass)
354 TotalBackedgeMass += Mass;
355 BlockMass ExitMass = BlockMass::getFull() - TotalBackedgeMass;
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000356
Diego Novilloa354f482015-04-01 17:42:27 +0000357 // Block scale stores the inverse of the scale. If this is an infinite loop,
358 // its exit mass will be zero. In this case, use an arbitrary scale for the
359 // loop scale.
360 Loop.Scale =
361 ExitMass.isEmpty() ? InifiniteLoopScale : ExitMass.toScaled().inverse();
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000362
363 DEBUG(dbgs() << " - exit-mass = " << ExitMass << " (" << BlockMass::getFull()
Diego Novillo9a779622015-06-16 19:10:58 +0000364 << " - " << TotalBackedgeMass << ")\n"
Duncan P. N. Exon Smithd1320402014-04-25 04:38:01 +0000365 << " - scale = " << Loop.Scale << "\n");
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000366}
367
368/// \brief Package up a loop.
Duncan P. N. Exon Smithd1320402014-04-25 04:38:01 +0000369void BlockFrequencyInfoImplBase::packageLoop(LoopData &Loop) {
Duncan P. N. Exon Smithc5a31392014-04-28 20:02:29 +0000370 DEBUG(dbgs() << "packaging-loop: " << getLoopName(Loop) << "\n");
371
372 // Clear the subloop exits to prevent quadratic memory usage.
373 for (const BlockNode &M : Loop.Nodes) {
374 if (auto *Loop = Working[M.Index].getPackagedLoop())
375 Loop->Exits.clear();
376 DEBUG(dbgs() << " - node: " << getBlockName(M.Index) << "\n");
377 }
Duncan P. N. Exon Smithd1320402014-04-25 04:38:01 +0000378 Loop.IsPackaged = true;
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000379}
380
Diego Novillo9a779622015-06-16 19:10:58 +0000381#ifndef NDEBUG
382static void debugAssign(const BlockFrequencyInfoImplBase &BFI,
383 const DitheringDistributer &D, const BlockNode &T,
384 const BlockMass &M, const char *Desc) {
385 dbgs() << " => assign " << M << " (" << D.RemMass << ")";
386 if (Desc)
387 dbgs() << " [" << Desc << "]";
388 if (T.isValid())
389 dbgs() << " to " << BFI.getBlockName(T);
390 dbgs() << "\n";
391}
392#endif
393
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000394void BlockFrequencyInfoImplBase::distributeMass(const BlockNode &Source,
Duncan P. N. Exon Smithd1320402014-04-25 04:38:01 +0000395 LoopData *OuterLoop,
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000396 Distribution &Dist) {
Duncan P. N. Exon Smithda5eaed2014-04-25 18:47:04 +0000397 BlockMass Mass = Working[Source.Index].getMass();
Duncan P. N. Exon Smithcb7d29d2014-04-25 04:38:43 +0000398 DEBUG(dbgs() << " => mass: " << Mass << "\n");
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000399
400 // Distribute mass to successors as laid out in Dist.
401 DitheringDistributer D(Dist, Mass);
402
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000403 for (const Weight &W : Dist.Weights) {
Duncan P. N. Exon Smithcb7d29d2014-04-25 04:38:43 +0000404 // Check for a local edge (non-backedge and non-exit).
405 BlockMass Taken = D.takeMass(W.Amount);
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000406 if (W.Type == Weight::Local) {
Duncan P. N. Exon Smithda5eaed2014-04-25 18:47:04 +0000407 Working[W.TargetNode.Index].getMass() += Taken;
Diego Novillo9a779622015-06-16 19:10:58 +0000408 DEBUG(debugAssign(*this, D, W.TargetNode, Taken, nullptr));
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000409 continue;
410 }
411
412 // Backedges and exits only make sense if we're processing a loop.
Duncan P. N. Exon Smithd1320402014-04-25 04:38:01 +0000413 assert(OuterLoop && "backedge or exit outside of loop");
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000414
415 // Check for a backedge.
416 if (W.Type == Weight::Backedge) {
Diego Novillo8c49a572015-06-17 16:28:22 +0000417 OuterLoop->BackedgeMass[OuterLoop->getHeaderIndex(W.TargetNode)] += Taken;
Diego Novillo9a779622015-06-16 19:10:58 +0000418 DEBUG(debugAssign(*this, D, W.TargetNode, Taken, "back"));
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000419 continue;
420 }
421
422 // This must be an exit.
423 assert(W.Type == Weight::Exit);
Duncan P. N. Exon Smithcb7d29d2014-04-25 04:38:43 +0000424 OuterLoop->Exits.push_back(std::make_pair(W.TargetNode, Taken));
Diego Novillo9a779622015-06-16 19:10:58 +0000425 DEBUG(debugAssign(*this, D, W.TargetNode, Taken, "exit"));
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000426 }
427}
428
429static void convertFloatingToInteger(BlockFrequencyInfoImplBase &BFI,
Duncan P. N. Exon Smithbeaf8132014-06-24 00:26:13 +0000430 const Scaled64 &Min, const Scaled64 &Max) {
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000431 // Scale the Factor to a size that creates integers. Ideally, integers would
432 // be scaled so that Max == UINT64_MAX so that they can be best
Diego Novilloa354f482015-04-01 17:42:27 +0000433 // differentiated. However, in the presence of large frequency values, small
434 // frequencies are scaled down to 1, making it impossible to differentiate
435 // small, unequal numbers. When the spread between Min and Max frequencies
436 // fits well within MaxBits, we make the scale be at least 8.
437 const unsigned MaxBits = 64;
438 const unsigned SpreadBits = (Max / Min).lg();
439 Scaled64 ScalingFactor;
440 if (SpreadBits <= MaxBits - 3) {
441 // If the values are small enough, make the scaling factor at least 8 to
442 // allow distinguishing small values.
443 ScalingFactor = Min.inverse();
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000444 ScalingFactor <<= 3;
Diego Novilloa354f482015-04-01 17:42:27 +0000445 } else {
446 // If the values need more than MaxBits to be represented, saturate small
447 // frequency values down to 1 by using a scaling factor that benefits large
448 // frequency values.
449 ScalingFactor = Scaled64(1, MaxBits) / Max;
450 }
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000451
452 // Translate the floats to integers.
453 DEBUG(dbgs() << "float-to-int: min = " << Min << ", max = " << Max
454 << ", factor = " << ScalingFactor << "\n");
455 for (size_t Index = 0; Index < BFI.Freqs.size(); ++Index) {
Duncan P. N. Exon Smithbeaf8132014-06-24 00:26:13 +0000456 Scaled64 Scaled = BFI.Freqs[Index].Scaled * ScalingFactor;
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000457 BFI.Freqs[Index].Integer = std::max(UINT64_C(1), Scaled.toInt<uint64_t>());
458 DEBUG(dbgs() << " - " << BFI.getBlockName(Index) << ": float = "
Duncan P. N. Exon Smithbeaf8132014-06-24 00:26:13 +0000459 << BFI.Freqs[Index].Scaled << ", scaled = " << Scaled
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000460 << ", int = " << BFI.Freqs[Index].Integer << "\n");
461 }
462}
463
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000464/// \brief Unwrap a loop package.
465///
466/// Visits all the members of a loop, adjusting their BlockData according to
467/// the loop's pseudo-node.
Duncan P. N. Exon Smith0633f0e2014-04-25 04:38:25 +0000468static void unwrapLoop(BlockFrequencyInfoImplBase &BFI, LoopData &Loop) {
Duncan P. N. Exon Smithc5a31392014-04-28 20:02:29 +0000469 DEBUG(dbgs() << "unwrap-loop-package: " << BFI.getLoopName(Loop)
Duncan P. N. Exon Smith0633f0e2014-04-25 04:38:25 +0000470 << ": mass = " << Loop.Mass << ", scale = " << Loop.Scale
471 << "\n");
Duncan P. N. Exon Smithbeaf8132014-06-24 00:26:13 +0000472 Loop.Scale *= Loop.Mass.toScaled();
Duncan P. N. Exon Smith5291d2a2014-04-25 04:38:27 +0000473 Loop.IsPackaged = false;
Duncan P. N. Exon Smith3f086782014-04-25 04:38:32 +0000474 DEBUG(dbgs() << " => combined-scale = " << Loop.Scale << "\n");
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000475
476 // Propagate the head scale through the loop. Since members are visited in
477 // RPO, the head scale will be updated by the loop scale first, and then the
478 // final head scale will be used for updated the rest of the members.
Duncan P. N. Exon Smith5291d2a2014-04-25 04:38:27 +0000479 for (const BlockNode &N : Loop.Nodes) {
480 const auto &Working = BFI.Working[N.Index];
Duncan P. N. Exon Smithbeaf8132014-06-24 00:26:13 +0000481 Scaled64 &F = Working.isAPackage() ? Working.getPackagedLoop()->Scale
482 : BFI.Freqs[N.Index].Scaled;
483 Scaled64 New = Loop.Scale * F;
Duncan P. N. Exon Smith5291d2a2014-04-25 04:38:27 +0000484 DEBUG(dbgs() << " - " << BFI.getBlockName(N) << ": " << F << " => " << New
485 << "\n");
486 F = New;
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000487 }
488}
489
Duncan P. N. Exon Smith46d9a562014-04-25 04:38:17 +0000490void BlockFrequencyInfoImplBase::unwrapLoops() {
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000491 // Set initial frequencies from loop-local masses.
492 for (size_t Index = 0; Index < Working.size(); ++Index)
Duncan P. N. Exon Smithbeaf8132014-06-24 00:26:13 +0000493 Freqs[Index].Scaled = Working[Index].Mass.toScaled();
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000494
Duncan P. N. Exon Smithda0b21c2014-04-25 04:38:23 +0000495 for (LoopData &Loop : Loops)
Duncan P. N. Exon Smith0633f0e2014-04-25 04:38:25 +0000496 unwrapLoop(*this, Loop);
Duncan P. N. Exon Smith46d9a562014-04-25 04:38:17 +0000497}
498
499void BlockFrequencyInfoImplBase::finalizeMetrics() {
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000500 // Unwrap loop packages in reverse post-order, tracking min and max
501 // frequencies.
Duncan P. N. Exon Smithbeaf8132014-06-24 00:26:13 +0000502 auto Min = Scaled64::getLargest();
503 auto Max = Scaled64::getZero();
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000504 for (size_t Index = 0; Index < Working.size(); ++Index) {
Duncan P. N. Exon Smith46d9a562014-04-25 04:38:17 +0000505 // Update min/max scale.
Duncan P. N. Exon Smithbeaf8132014-06-24 00:26:13 +0000506 Min = std::min(Min, Freqs[Index].Scaled);
507 Max = std::max(Max, Freqs[Index].Scaled);
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000508 }
509
510 // Convert to integers.
511 convertFloatingToInteger(*this, Min, Max);
512
513 // Clean up data structures.
514 cleanup(*this);
515
516 // Print out the final stats.
517 DEBUG(dump());
518}
519
520BlockFrequency
521BlockFrequencyInfoImplBase::getBlockFreq(const BlockNode &Node) const {
522 if (!Node.isValid())
523 return 0;
524 return Freqs[Node.Index].Integer;
525}
Duncan P. N. Exon Smithbeaf8132014-06-24 00:26:13 +0000526Scaled64
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000527BlockFrequencyInfoImplBase::getFloatingBlockFreq(const BlockNode &Node) const {
528 if (!Node.isValid())
Duncan P. N. Exon Smithbeaf8132014-06-24 00:26:13 +0000529 return Scaled64::getZero();
530 return Freqs[Node.Index].Scaled;
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000531}
532
533std::string
534BlockFrequencyInfoImplBase::getBlockName(const BlockNode &Node) const {
535 return std::string();
536}
Duncan P. N. Exon Smithc5a31392014-04-28 20:02:29 +0000537std::string
538BlockFrequencyInfoImplBase::getLoopName(const LoopData &Loop) const {
539 return getBlockName(Loop.getHeader()) + (Loop.isIrreducible() ? "**" : "*");
540}
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000541
542raw_ostream &
543BlockFrequencyInfoImplBase::printBlockFreq(raw_ostream &OS,
544 const BlockNode &Node) const {
545 return OS << getFloatingBlockFreq(Node);
546}
547
548raw_ostream &
549BlockFrequencyInfoImplBase::printBlockFreq(raw_ostream &OS,
550 const BlockFrequency &Freq) const {
Duncan P. N. Exon Smithbeaf8132014-06-24 00:26:13 +0000551 Scaled64 Block(Freq.getFrequency(), 0);
552 Scaled64 Entry(getEntryFreq(), 0);
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000553
554 return OS << Block / Entry;
555}
Duncan P. N. Exon Smithc5a31392014-04-28 20:02:29 +0000556
557void IrreducibleGraph::addNodesInLoop(const BFIBase::LoopData &OuterLoop) {
558 Start = OuterLoop.getHeader();
559 Nodes.reserve(OuterLoop.Nodes.size());
560 for (auto N : OuterLoop.Nodes)
561 addNode(N);
562 indexNodes();
563}
564void IrreducibleGraph::addNodesInFunction() {
565 Start = 0;
566 for (uint32_t Index = 0; Index < BFI.Working.size(); ++Index)
567 if (!BFI.Working[Index].isPackaged())
568 addNode(Index);
569 indexNodes();
570}
571void IrreducibleGraph::indexNodes() {
572 for (auto &I : Nodes)
573 Lookup[I.Node.Index] = &I;
574}
575void IrreducibleGraph::addEdge(IrrNode &Irr, const BlockNode &Succ,
576 const BFIBase::LoopData *OuterLoop) {
577 if (OuterLoop && OuterLoop->isHeader(Succ))
578 return;
579 auto L = Lookup.find(Succ.Index);
580 if (L == Lookup.end())
581 return;
582 IrrNode &SuccIrr = *L->second;
583 Irr.Edges.push_back(&SuccIrr);
584 SuccIrr.Edges.push_front(&Irr);
585 ++SuccIrr.NumIn;
586}
587
588namespace llvm {
589template <> struct GraphTraits<IrreducibleGraph> {
590 typedef bfi_detail::IrreducibleGraph GraphT;
591
Duncan P. N. Exon Smith295b5e72014-04-28 20:22:29 +0000592 typedef const GraphT::IrrNode NodeType;
593 typedef GraphT::IrrNode::iterator ChildIteratorType;
Duncan P. N. Exon Smithc5a31392014-04-28 20:02:29 +0000594
595 static const NodeType *getEntryNode(const GraphT &G) {
596 return G.StartIrr;
597 }
598 static ChildIteratorType child_begin(NodeType *N) { return N->succ_begin(); }
599 static ChildIteratorType child_end(NodeType *N) { return N->succ_end(); }
600};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000601}
Duncan P. N. Exon Smithc5a31392014-04-28 20:02:29 +0000602
603/// \brief Find extra irreducible headers.
604///
605/// Find entry blocks and other blocks with backedges, which exist when \c G
606/// contains irreducible sub-SCCs.
607static void findIrreducibleHeaders(
608 const BlockFrequencyInfoImplBase &BFI,
609 const IrreducibleGraph &G,
610 const std::vector<const IrreducibleGraph::IrrNode *> &SCC,
611 LoopData::NodeList &Headers, LoopData::NodeList &Others) {
612 // Map from nodes in the SCC to whether it's an entry block.
613 SmallDenseMap<const IrreducibleGraph::IrrNode *, bool, 8> InSCC;
614
615 // InSCC also acts the set of nodes in the graph. Seed it.
616 for (const auto *I : SCC)
617 InSCC[I] = false;
618
619 for (auto I = InSCC.begin(), E = InSCC.end(); I != E; ++I) {
620 auto &Irr = *I->first;
621 for (const auto *P : make_range(Irr.pred_begin(), Irr.pred_end())) {
622 if (InSCC.count(P))
623 continue;
624
625 // This is an entry block.
626 I->second = true;
627 Headers.push_back(Irr.Node);
628 DEBUG(dbgs() << " => entry = " << BFI.getBlockName(Irr.Node) << "\n");
629 break;
630 }
631 }
Duncan P. N. Exon Smitha7a90a22014-10-06 17:42:00 +0000632 assert(Headers.size() >= 2 &&
633 "Expected irreducible CFG; -loop-info is likely invalid");
Duncan P. N. Exon Smithc5a31392014-04-28 20:02:29 +0000634 if (Headers.size() == InSCC.size()) {
635 // Every block is a header.
636 std::sort(Headers.begin(), Headers.end());
637 return;
638 }
639
640 // Look for extra headers from irreducible sub-SCCs.
641 for (const auto &I : InSCC) {
642 // Entry blocks are already headers.
643 if (I.second)
644 continue;
645
646 auto &Irr = *I.first;
647 for (const auto *P : make_range(Irr.pred_begin(), Irr.pred_end())) {
648 // Skip forward edges.
649 if (P->Node < Irr.Node)
650 continue;
651
652 // Skip predecessors from entry blocks. These can have inverted
653 // ordering.
654 if (InSCC.lookup(P))
655 continue;
656
657 // Store the extra header.
658 Headers.push_back(Irr.Node);
659 DEBUG(dbgs() << " => extra = " << BFI.getBlockName(Irr.Node) << "\n");
660 break;
661 }
662 if (Headers.back() == Irr.Node)
663 // Added this as a header.
664 continue;
665
666 // This is not a header.
667 Others.push_back(Irr.Node);
668 DEBUG(dbgs() << " => other = " << BFI.getBlockName(Irr.Node) << "\n");
669 }
670 std::sort(Headers.begin(), Headers.end());
671 std::sort(Others.begin(), Others.end());
672}
673
674static void createIrreducibleLoop(
675 BlockFrequencyInfoImplBase &BFI, const IrreducibleGraph &G,
676 LoopData *OuterLoop, std::list<LoopData>::iterator Insert,
677 const std::vector<const IrreducibleGraph::IrrNode *> &SCC) {
678 // Translate the SCC into RPO.
679 DEBUG(dbgs() << " - found-scc\n");
680
681 LoopData::NodeList Headers;
682 LoopData::NodeList Others;
683 findIrreducibleHeaders(BFI, G, SCC, Headers, Others);
684
685 auto Loop = BFI.Loops.emplace(Insert, OuterLoop, Headers.begin(),
686 Headers.end(), Others.begin(), Others.end());
687
688 // Update loop hierarchy.
689 for (const auto &N : Loop->Nodes)
690 if (BFI.Working[N.Index].isLoopHeader())
691 BFI.Working[N.Index].Loop->Parent = &*Loop;
692 else
693 BFI.Working[N.Index].Loop = &*Loop;
694}
695
696iterator_range<std::list<LoopData>::iterator>
697BlockFrequencyInfoImplBase::analyzeIrreducible(
698 const IrreducibleGraph &G, LoopData *OuterLoop,
699 std::list<LoopData>::iterator Insert) {
700 assert((OuterLoop == nullptr) == (Insert == Loops.begin()));
701 auto Prev = OuterLoop ? std::prev(Insert) : Loops.end();
702
703 for (auto I = scc_begin(G); !I.isAtEnd(); ++I) {
704 if (I->size() < 2)
705 continue;
706
707 // Translate the SCC into RPO.
708 createIrreducibleLoop(*this, G, OuterLoop, Insert, *I);
709 }
710
711 if (OuterLoop)
712 return make_range(std::next(Prev), Insert);
713 return make_range(Loops.begin(), Insert);
714}
715
716void
717BlockFrequencyInfoImplBase::updateLoopWithIrreducible(LoopData &OuterLoop) {
718 OuterLoop.Exits.clear();
Diego Novillo9a779622015-06-16 19:10:58 +0000719 for (auto &Mass : OuterLoop.BackedgeMass)
720 Mass = BlockMass::getEmpty();
Duncan P. N. Exon Smithc5a31392014-04-28 20:02:29 +0000721 auto O = OuterLoop.Nodes.begin() + 1;
722 for (auto I = O, E = OuterLoop.Nodes.end(); I != E; ++I)
723 if (!Working[I->Index].isPackaged())
724 *O++ = *I;
725 OuterLoop.Nodes.erase(O, OuterLoop.Nodes.end());
726}
Diego Novillo9a779622015-06-16 19:10:58 +0000727
728void BlockFrequencyInfoImplBase::adjustLoopHeaderMass(LoopData &Loop) {
729 assert(Loop.isIrreducible() && "this only makes sense on irreducible loops");
730
731 // Since the loop has more than one header block, the mass flowing back into
732 // each header will be different. Adjust the mass in each header loop to
733 // reflect the masses flowing through back edges.
734 //
735 // To do this, we distribute the initial mass using the backedge masses
736 // as weights for the distribution.
737 BlockMass LoopMass = BlockMass::getFull();
738 Distribution Dist;
739
740 DEBUG(dbgs() << "adjust-loop-header-mass:\n");
741 for (uint32_t H = 0; H < Loop.NumHeaders; ++H) {
742 auto &HeaderNode = Loop.Nodes[H];
Diego Novillo8c49a572015-06-17 16:28:22 +0000743 auto &BackedgeMass = Loop.BackedgeMass[Loop.getHeaderIndex(HeaderNode)];
Diego Novillo9a779622015-06-16 19:10:58 +0000744 DEBUG(dbgs() << " - Add back edge mass for node "
745 << getBlockName(HeaderNode) << ": " << BackedgeMass << "\n");
Diego Novillof9aa39b2015-09-08 19:22:17 +0000746 if (BackedgeMass.getMass() > 0)
747 Dist.addLocal(HeaderNode, BackedgeMass.getMass());
748 else
749 DEBUG(dbgs() << " Nothing added. Back edge mass is zero\n");
Diego Novillo9a779622015-06-16 19:10:58 +0000750 }
751
752 DitheringDistributer D(Dist, LoopMass);
753
754 DEBUG(dbgs() << " Distribute loop mass " << LoopMass
755 << " to headers using above weights\n");
756 for (const Weight &W : Dist.Weights) {
757 BlockMass Taken = D.takeMass(W.Amount);
758 assert(W.Type == Weight::Local && "all weights should be local");
759 Working[W.TargetNode.Index].getMass() = Taken;
760 DEBUG(debugAssign(*this, D, W.TargetNode, Taken, nullptr));
761 }
762}