blob: 08ebcc47a807b18faad1d7101b13a62028dfa9b0 [file] [log] [blame]
Duncan P. N. Exon Smith9a11d662014-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 Smith9a11d662014-04-21 17:57:07 +000014#include "llvm/Analysis/BlockFrequencyInfoImpl.h"
Eugene Zelenko15a56d42017-07-21 21:37:46 +000015#include "llvm/ADT/APInt.h"
16#include "llvm/ADT/DenseMap.h"
17#include "llvm/ADT/GraphTraits.h"
18#include "llvm/ADT/None.h"
Duncan P. N. Exon Smithcca77fc2014-05-06 01:57:42 +000019#include "llvm/ADT/SCCIterator.h"
Nico Weber0f38c602018-04-30 14:59:11 +000020#include "llvm/Config/llvm-config.h"
Xinliang David Li7f4f1f62016-06-22 17:12:12 +000021#include "llvm/IR/Function.h"
Eugene Zelenko15a56d42017-07-21 21:37:46 +000022#include "llvm/Support/BlockFrequency.h"
23#include "llvm/Support/BranchProbability.h"
24#include "llvm/Support/Compiler.h"
25#include "llvm/Support/Debug.h"
26#include "llvm/Support/ScaledNumber.h"
27#include "llvm/Support/MathExtras.h"
Duncan P. N. Exon Smith9a11d662014-04-21 17:57:07 +000028#include "llvm/Support/raw_ostream.h"
Eugene Zelenko15a56d42017-07-21 21:37:46 +000029#include <algorithm>
30#include <cassert>
31#include <cstddef>
32#include <cstdint>
33#include <iterator>
34#include <list>
Duncan P. N. Exon Smith1a283402014-12-05 19:13:42 +000035#include <numeric>
Eugene Zelenko15a56d42017-07-21 21:37:46 +000036#include <utility>
37#include <vector>
Duncan P. N. Exon Smith9a11d662014-04-21 17:57:07 +000038
39using namespace llvm;
Duncan P. N. Exon Smith96837f72014-04-28 20:02:29 +000040using namespace llvm::bfi_detail;
Duncan P. N. Exon Smith9a11d662014-04-21 17:57:07 +000041
Chandler Carruth8677f2f2014-04-22 02:02:50 +000042#define DEBUG_TYPE "block-freq"
43
Duncan P. N. Exon Smith6ecab5a2014-06-24 00:26:13 +000044ScaledNumber<uint64_t> BlockMass::toScaled() const {
Duncan P. N. Exon Smith9a11d662014-04-21 17:57:07 +000045 if (isFull())
Duncan P. N. Exon Smith7c21d702014-06-23 23:36:17 +000046 return ScaledNumber<uint64_t>(1, 0);
47 return ScaledNumber<uint64_t>(getMass() + 1, -64);
Duncan P. N. Exon Smith9a11d662014-04-21 17:57:07 +000048}
49
Aaron Ballman1d03d382017-10-15 14:32:27 +000050#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Yaron Keren55307982016-01-29 20:50:44 +000051LLVM_DUMP_METHOD void BlockMass::dump() const { print(dbgs()); }
Matthias Braun88d20752017-01-28 02:02:38 +000052#endif
Duncan P. N. Exon Smith9a11d662014-04-21 17:57:07 +000053
54static char getHexDigit(int N) {
55 assert(N < 16);
56 if (N < 10)
57 return '0' + N;
58 return 'a' + N - 10;
59}
Eugene Zelenko380d47d2016-02-02 18:20:45 +000060
Duncan P. N. Exon Smith9a11d662014-04-21 17:57:07 +000061raw_ostream &BlockMass::print(raw_ostream &OS) const {
62 for (int Digits = 0; Digits < 16; ++Digits)
63 OS << getHexDigit(Mass >> (60 - Digits * 4) & 0xf);
64 return OS;
65}
66
Duncan P. N. Exon Smith9a11d662014-04-21 17:57:07 +000067namespace {
68
Eugene Zelenko15a56d42017-07-21 21:37:46 +000069using BlockNode = BlockFrequencyInfoImplBase::BlockNode;
70using Distribution = BlockFrequencyInfoImplBase::Distribution;
71using WeightList = BlockFrequencyInfoImplBase::Distribution::WeightList;
72using Scaled64 = BlockFrequencyInfoImplBase::Scaled64;
73using LoopData = BlockFrequencyInfoImplBase::LoopData;
74using Weight = BlockFrequencyInfoImplBase::Weight;
75using FrequencyData = BlockFrequencyInfoImplBase::FrequencyData;
Duncan P. N. Exon Smith9a11d662014-04-21 17:57:07 +000076
Adrian Prantl26b584c2018-05-01 15:54:18 +000077/// Dithering mass distributer.
Duncan P. N. Exon Smith9a11d662014-04-21 17:57:07 +000078///
79/// This class splits up a single mass into portions by weight, dithering to
80/// spread out error. No mass is lost. The dithering precision depends on the
81/// precision of the product of \a BlockMass and \a BranchProbability.
82///
83/// The distribution algorithm follows.
84///
85/// 1. Initialize by saving the sum of the weights in \a RemWeight and the
86/// mass to distribute in \a RemMass.
87///
88/// 2. For each portion:
89///
90/// 1. Construct a branch probability, P, as the portion's weight divided
91/// by the current value of \a RemWeight.
92/// 2. Calculate the portion's mass as \a RemMass times P.
93/// 3. Update \a RemWeight and \a RemMass at each portion by subtracting
94/// the current portion's weight and mass.
Duncan P. N. Exon Smith9a11d662014-04-21 17:57:07 +000095struct DitheringDistributer {
96 uint32_t RemWeight;
Duncan P. N. Exon Smith9a11d662014-04-21 17:57:07 +000097 BlockMass RemMass;
Duncan P. N. Exon Smith9a11d662014-04-21 17:57:07 +000098
99 DitheringDistributer(Distribution &Dist, const BlockMass &Mass);
100
Duncan P. N. Exon Smith9a11d662014-04-21 17:57:07 +0000101 BlockMass takeMass(uint32_t Weight);
102};
Duncan P. N. Exon Smith1c224d82014-07-11 23:56:50 +0000103
Eugene Zelenko380d47d2016-02-02 18:20:45 +0000104} // end anonymous namespace
Duncan P. N. Exon Smith9a11d662014-04-21 17:57:07 +0000105
106DitheringDistributer::DitheringDistributer(Distribution &Dist,
107 const BlockMass &Mass) {
108 Dist.normalize();
109 RemWeight = Dist.Total;
Duncan P. N. Exon Smith9a11d662014-04-21 17:57:07 +0000110 RemMass = Mass;
Duncan P. N. Exon Smith9a11d662014-04-21 17:57:07 +0000111}
112
Duncan P. N. Exon Smith9a11d662014-04-21 17:57:07 +0000113BlockMass DitheringDistributer::takeMass(uint32_t Weight) {
114 assert(Weight && "invalid weight");
115 assert(Weight <= RemWeight);
116 BlockMass Mass = RemMass * BranchProbability(Weight, RemWeight);
117
118 // Decrement totals (dither).
119 RemWeight -= Weight;
120 RemMass -= Mass;
121 return Mass;
122}
123
124void Distribution::add(const BlockNode &Node, uint64_t Amount,
125 Weight::DistType Type) {
126 assert(Amount && "invalid weight of 0");
127 uint64_t NewTotal = Total + Amount;
128
129 // Check for overflow. It should be impossible to overflow twice.
130 bool IsOverflow = NewTotal < Total;
131 assert(!(DidOverflow && IsOverflow) && "unexpected repeated overflow");
132 DidOverflow |= IsOverflow;
133
134 // Update the total.
135 Total = NewTotal;
136
137 // Save the weight.
Duncan P. N. Exon Smith8ff87722014-07-12 00:26:00 +0000138 Weights.push_back(Weight(Type, Node, Amount));
Duncan P. N. Exon Smith9a11d662014-04-21 17:57:07 +0000139}
140
141static void combineWeight(Weight &W, const Weight &OtherW) {
142 assert(OtherW.TargetNode.isValid());
143 if (!W.Amount) {
144 W = OtherW;
145 return;
146 }
147 assert(W.Type == OtherW.Type);
148 assert(W.TargetNode == OtherW.TargetNode);
Duncan P. N. Exon Smith1a283402014-12-05 19:13:42 +0000149 assert(OtherW.Amount && "Expected non-zero weight");
150 if (W.Amount > W.Amount + OtherW.Amount)
151 // Saturate on overflow.
152 W.Amount = UINT64_MAX;
153 else
154 W.Amount += OtherW.Amount;
Duncan P. N. Exon Smith9a11d662014-04-21 17:57:07 +0000155}
Eugene Zelenko380d47d2016-02-02 18:20:45 +0000156
Duncan P. N. Exon Smith9a11d662014-04-21 17:57:07 +0000157static void combineWeightsBySorting(WeightList &Weights) {
158 // Sort so edges to the same node are adjacent.
Fangrui Song3b35e172018-09-27 02:13:45 +0000159 llvm::sort(Weights, [](const Weight &L, const Weight &R) {
160 return L.TargetNode < R.TargetNode;
161 });
Duncan P. N. Exon Smith9a11d662014-04-21 17:57:07 +0000162
163 // Combine adjacent edges.
164 WeightList::iterator O = Weights.begin();
165 for (WeightList::const_iterator I = O, L = O, E = Weights.end(); I != E;
166 ++O, (I = L)) {
167 *O = *I;
168
169 // Find the adjacent weights to the same node.
170 for (++L; L != E && I->TargetNode == L->TargetNode; ++L)
171 combineWeight(*O, *L);
172 }
173
174 // Erase extra entries.
175 Weights.erase(O, Weights.end());
Duncan P. N. Exon Smith9a11d662014-04-21 17:57:07 +0000176}
Eugene Zelenko380d47d2016-02-02 18:20:45 +0000177
Duncan P. N. Exon Smith9a11d662014-04-21 17:57:07 +0000178static void combineWeightsByHashing(WeightList &Weights) {
179 // Collect weights into a DenseMap.
Eugene Zelenko15a56d42017-07-21 21:37:46 +0000180 using HashTable = DenseMap<BlockNode::IndexType, Weight>;
181
Duncan P. N. Exon Smith9a11d662014-04-21 17:57:07 +0000182 HashTable Combined(NextPowerOf2(2 * Weights.size()));
183 for (const Weight &W : Weights)
184 combineWeight(Combined[W.TargetNode.Index], W);
185
186 // Check whether anything changed.
187 if (Weights.size() == Combined.size())
188 return;
189
190 // Fill in the new weights.
191 Weights.clear();
192 Weights.reserve(Combined.size());
193 for (const auto &I : Combined)
194 Weights.push_back(I.second);
195}
Eugene Zelenko380d47d2016-02-02 18:20:45 +0000196
Duncan P. N. Exon Smith9a11d662014-04-21 17:57:07 +0000197static void combineWeights(WeightList &Weights) {
198 // Use a hash table for many successors to keep this linear.
199 if (Weights.size() > 128) {
200 combineWeightsByHashing(Weights);
201 return;
202 }
203
204 combineWeightsBySorting(Weights);
205}
Eugene Zelenko380d47d2016-02-02 18:20:45 +0000206
Duncan P. N. Exon Smith9a11d662014-04-21 17:57:07 +0000207static uint64_t shiftRightAndRound(uint64_t N, int Shift) {
208 assert(Shift >= 0);
209 assert(Shift < 64);
210 if (!Shift)
211 return N;
212 return (N >> Shift) + (UINT64_C(1) & N >> (Shift - 1));
213}
Eugene Zelenko380d47d2016-02-02 18:20:45 +0000214
Duncan P. N. Exon Smith9a11d662014-04-21 17:57:07 +0000215void Distribution::normalize() {
216 // Early exit for termination nodes.
217 if (Weights.empty())
218 return;
219
220 // Only bother if there are multiple successors.
221 if (Weights.size() > 1)
222 combineWeights(Weights);
223
224 // Early exit when combined into a single successor.
225 if (Weights.size() == 1) {
226 Total = 1;
Duncan P. N. Exon Smith9a11d662014-04-21 17:57:07 +0000227 Weights.front().Amount = 1;
228 return;
229 }
230
231 // Determine how much to shift right so that the total fits into 32-bits.
232 //
233 // If we shift at all, shift by 1 extra. Otherwise, the lower limit of 1
234 // for each weight can cause a 32-bit overflow.
235 int Shift = 0;
236 if (DidOverflow)
237 Shift = 33;
238 else if (Total > UINT32_MAX)
239 Shift = 33 - countLeadingZeros(Total);
240
241 // Early exit if nothing needs to be scaled.
Duncan P. N. Exon Smith1a283402014-12-05 19:13:42 +0000242 if (!Shift) {
243 // If we didn't overflow then combineWeights() shouldn't have changed the
244 // sum of the weights, but let's double-check.
245 assert(Total == std::accumulate(Weights.begin(), Weights.end(), UINT64_C(0),
246 [](uint64_t Sum, const Weight &W) {
247 return Sum + W.Amount;
248 }) &&
249 "Expected total to be correct");
Duncan P. N. Exon Smith9a11d662014-04-21 17:57:07 +0000250 return;
Duncan P. N. Exon Smith1a283402014-12-05 19:13:42 +0000251 }
Duncan P. N. Exon Smith9a11d662014-04-21 17:57:07 +0000252
253 // Recompute the total through accumulation (rather than shifting it) so that
Duncan P. N. Exon Smith1a283402014-12-05 19:13:42 +0000254 // it's accurate after shifting and any changes combineWeights() made above.
Duncan P. N. Exon Smith9a11d662014-04-21 17:57:07 +0000255 Total = 0;
Duncan P. N. Exon Smith9a11d662014-04-21 17:57:07 +0000256
257 // Sum the weights to each node and shift right if necessary.
258 for (Weight &W : Weights) {
259 // Scale down below UINT32_MAX. Since Shift is larger than necessary, we
260 // can round here without concern about overflow.
261 assert(W.TargetNode.isValid());
262 W.Amount = std::max(UINT64_C(1), shiftRightAndRound(W.Amount, Shift));
263 assert(W.Amount <= UINT32_MAX);
264
265 // Update the total.
266 Total += W.Amount;
Duncan P. N. Exon Smith9a11d662014-04-21 17:57:07 +0000267 }
268 assert(Total <= UINT32_MAX);
269}
270
271void BlockFrequencyInfoImplBase::clear() {
Duncan P. N. Exon Smith153a2652014-04-22 03:31:34 +0000272 // Swap with a default-constructed std::vector, since std::vector<>::clear()
273 // does not actually clear heap storage.
274 std::vector<FrequencyData>().swap(Freqs);
Hiroshi Yamauchidd33e172017-11-02 22:26:51 +0000275 IsIrrLoopHeader.clear();
Duncan P. N. Exon Smith153a2652014-04-22 03:31:34 +0000276 std::vector<WorkingData>().swap(Working);
Duncan P. N. Exon Smith6f1f9f42014-04-25 04:30:06 +0000277 Loops.clear();
Duncan P. N. Exon Smith9a11d662014-04-21 17:57:07 +0000278}
279
Adrian Prantl26b584c2018-05-01 15:54:18 +0000280/// Clear all memory not needed downstream.
Duncan P. N. Exon Smith9a11d662014-04-21 17:57:07 +0000281///
282/// Releases all memory not used downstream. In particular, saves Freqs.
283static void cleanup(BlockFrequencyInfoImplBase &BFI) {
284 std::vector<FrequencyData> SavedFreqs(std::move(BFI.Freqs));
Hiroshi Yamauchidd33e172017-11-02 22:26:51 +0000285 SparseBitVector<> SavedIsIrrLoopHeader(std::move(BFI.IsIrrLoopHeader));
Duncan P. N. Exon Smith9a11d662014-04-21 17:57:07 +0000286 BFI.clear();
287 BFI.Freqs = std::move(SavedFreqs);
Hiroshi Yamauchidd33e172017-11-02 22:26:51 +0000288 BFI.IsIrrLoopHeader = std::move(SavedIsIrrLoopHeader);
Duncan P. N. Exon Smith9a11d662014-04-21 17:57:07 +0000289}
290
Duncan P. N. Exon Smith96837f72014-04-28 20:02:29 +0000291bool BlockFrequencyInfoImplBase::addToDist(Distribution &Dist,
Duncan P. N. Exon Smith336238c2014-04-25 04:38:01 +0000292 const LoopData *OuterLoop,
Duncan P. N. Exon Smith9a11d662014-04-21 17:57:07 +0000293 const BlockNode &Pred,
294 const BlockNode &Succ,
295 uint64_t Weight) {
296 if (!Weight)
297 Weight = 1;
298
Duncan P. N. Exon Smith7e261812014-04-25 04:38:06 +0000299 auto isLoopHeader = [&OuterLoop](const BlockNode &Node) {
300 return OuterLoop && OuterLoop->isHeader(Node);
301 };
Duncan P. N. Exon Smith336238c2014-04-25 04:38:01 +0000302
Duncan P. N. Exon Smith2d181672014-04-25 18:47:04 +0000303 BlockNode Resolved = Working[Succ.Index].getResolvedNode();
304
Duncan P. N. Exon Smith9a11d662014-04-21 17:57:07 +0000305#ifndef NDEBUG
Duncan P. N. Exon Smith2d181672014-04-25 18:47:04 +0000306 auto debugSuccessor = [&](const char *Type) {
Duncan P. N. Exon Smith9a11d662014-04-21 17:57:07 +0000307 dbgs() << " =>"
308 << " [" << Type << "] weight = " << Weight;
Duncan P. N. Exon Smith2d181672014-04-25 18:47:04 +0000309 if (!isLoopHeader(Resolved))
Duncan P. N. Exon Smith9a11d662014-04-21 17:57:07 +0000310 dbgs() << ", succ = " << getBlockName(Succ);
311 if (Resolved != Succ)
312 dbgs() << ", resolved = " << getBlockName(Resolved);
313 dbgs() << "\n";
314 };
315 (void)debugSuccessor;
316#endif
317
Duncan P. N. Exon Smith2d181672014-04-25 18:47:04 +0000318 if (isLoopHeader(Resolved)) {
Nicola Zaghen0818e782018-05-14 12:53:11 +0000319 LLVM_DEBUG(debugSuccessor("backedge"));
Diego Novillo3f53fc82015-06-16 19:10:58 +0000320 Dist.addBackedge(Resolved, Weight);
Duncan P. N. Exon Smith96837f72014-04-28 20:02:29 +0000321 return true;
Duncan P. N. Exon Smith9a11d662014-04-21 17:57:07 +0000322 }
Duncan P. N. Exon Smith9a11d662014-04-21 17:57:07 +0000323
Duncan P. N. Exon Smith7e261812014-04-25 04:38:06 +0000324 if (Working[Resolved.Index].getContainingLoop() != OuterLoop) {
Nicola Zaghen0818e782018-05-14 12:53:11 +0000325 LLVM_DEBUG(debugSuccessor(" exit "));
Duncan P. N. Exon Smith9a11d662014-04-21 17:57:07 +0000326 Dist.addExit(Resolved, Weight);
Duncan P. N. Exon Smith96837f72014-04-28 20:02:29 +0000327 return true;
Duncan P. N. Exon Smith9a11d662014-04-21 17:57:07 +0000328 }
329
Duncan P. N. Exon Smith846a1432014-04-22 03:31:53 +0000330 if (Resolved < Pred) {
Duncan P. N. Exon Smith96837f72014-04-28 20:02:29 +0000331 if (!isLoopHeader(Pred)) {
332 // If OuterLoop is an irreducible loop, we can't actually handle this.
333 assert((!OuterLoop || !OuterLoop->isIrreducible()) &&
334 "unhandled irreducible control flow");
335
336 // Irreducible backedge. Abort.
Nicola Zaghen0818e782018-05-14 12:53:11 +0000337 LLVM_DEBUG(debugSuccessor("abort!!!"));
Duncan P. N. Exon Smith96837f72014-04-28 20:02:29 +0000338 return false;
339 }
340
341 // If "Pred" is a loop header, then this isn't really a backedge; rather,
342 // OuterLoop must be irreducible. These false backedges can come only from
343 // secondary loop headers.
344 assert(OuterLoop && OuterLoop->isIrreducible() && !isLoopHeader(Resolved) &&
345 "unhandled irreducible control flow");
Duncan P. N. Exon Smith9a11d662014-04-21 17:57:07 +0000346 }
347
Nicola Zaghen0818e782018-05-14 12:53:11 +0000348 LLVM_DEBUG(debugSuccessor(" local "));
Duncan P. N. Exon Smith9a11d662014-04-21 17:57:07 +0000349 Dist.addLocal(Resolved, Weight);
Duncan P. N. Exon Smith96837f72014-04-28 20:02:29 +0000350 return true;
Duncan P. N. Exon Smith9a11d662014-04-21 17:57:07 +0000351}
352
Duncan P. N. Exon Smith96837f72014-04-28 20:02:29 +0000353bool BlockFrequencyInfoImplBase::addLoopSuccessorsToDist(
Duncan P. N. Exon Smith336238c2014-04-25 04:38:01 +0000354 const LoopData *OuterLoop, LoopData &Loop, Distribution &Dist) {
Duncan P. N. Exon Smith9a11d662014-04-21 17:57:07 +0000355 // Copy the exit map into Dist.
Duncan P. N. Exon Smith336238c2014-04-25 04:38:01 +0000356 for (const auto &I : Loop.Exits)
Duncan P. N. Exon Smith96837f72014-04-28 20:02:29 +0000357 if (!addToDist(Dist, OuterLoop, Loop.getHeader(), I.first,
358 I.second.getMass()))
359 // Irreducible backedge.
360 return false;
Duncan P. N. Exon Smith9a11d662014-04-21 17:57:07 +0000361
Duncan P. N. Exon Smith96837f72014-04-28 20:02:29 +0000362 return true;
Duncan P. N. Exon Smith9a11d662014-04-21 17:57:07 +0000363}
364
Adrian Prantl26b584c2018-05-01 15:54:18 +0000365/// Compute the loop scale for a loop.
Duncan P. N. Exon Smith336238c2014-04-25 04:38:01 +0000366void BlockFrequencyInfoImplBase::computeLoopScale(LoopData &Loop) {
Duncan P. N. Exon Smith9a11d662014-04-21 17:57:07 +0000367 // Compute loop scale.
Nicola Zaghen0818e782018-05-14 12:53:11 +0000368 LLVM_DEBUG(dbgs() << "compute-loop-scale: " << getLoopName(Loop) << "\n");
Duncan P. N. Exon Smith9a11d662014-04-21 17:57:07 +0000369
Diego Novillo32d90202015-04-01 17:42:27 +0000370 // Infinite loops need special handling. If we give the back edge an infinite
371 // mass, they may saturate all the other scales in the function down to 1,
372 // making all the other region temperatures look exactly the same. Choose an
373 // arbitrary scale to avoid these issues.
374 //
375 // FIXME: An alternate way would be to select a symbolic scale which is later
376 // replaced to be the maximum of all computed scales plus 1. This would
377 // appropriately describe the loop as having a large scale, without skewing
378 // the final frequency computation.
Sanjay Patelaef806ec2016-05-09 16:07:45 +0000379 const Scaled64 InfiniteLoopScale(1, 12);
Diego Novillo32d90202015-04-01 17:42:27 +0000380
Duncan P. N. Exon Smith9a11d662014-04-21 17:57:07 +0000381 // LoopScale == 1 / ExitMass
382 // ExitMass == HeadMass - BackedgeMass
Diego Novillo3f53fc82015-06-16 19:10:58 +0000383 BlockMass TotalBackedgeMass;
384 for (auto &Mass : Loop.BackedgeMass)
385 TotalBackedgeMass += Mass;
386 BlockMass ExitMass = BlockMass::getFull() - TotalBackedgeMass;
Duncan P. N. Exon Smith9a11d662014-04-21 17:57:07 +0000387
Diego Novillo32d90202015-04-01 17:42:27 +0000388 // Block scale stores the inverse of the scale. If this is an infinite loop,
389 // its exit mass will be zero. In this case, use an arbitrary scale for the
390 // loop scale.
391 Loop.Scale =
Sanjay Patelaef806ec2016-05-09 16:07:45 +0000392 ExitMass.isEmpty() ? InfiniteLoopScale : ExitMass.toScaled().inverse();
Duncan P. N. Exon Smith9a11d662014-04-21 17:57:07 +0000393
Nicola Zaghen0818e782018-05-14 12:53:11 +0000394 LLVM_DEBUG(dbgs() << " - exit-mass = " << ExitMass << " ("
395 << BlockMass::getFull() << " - " << TotalBackedgeMass
396 << ")\n"
397 << " - scale = " << Loop.Scale << "\n");
Duncan P. N. Exon Smith9a11d662014-04-21 17:57:07 +0000398}
399
Adrian Prantl26b584c2018-05-01 15:54:18 +0000400/// Package up a loop.
Duncan P. N. Exon Smith336238c2014-04-25 04:38:01 +0000401void BlockFrequencyInfoImplBase::packageLoop(LoopData &Loop) {
Nicola Zaghen0818e782018-05-14 12:53:11 +0000402 LLVM_DEBUG(dbgs() << "packaging-loop: " << getLoopName(Loop) << "\n");
Duncan P. N. Exon Smith96837f72014-04-28 20:02:29 +0000403
404 // Clear the subloop exits to prevent quadratic memory usage.
405 for (const BlockNode &M : Loop.Nodes) {
406 if (auto *Loop = Working[M.Index].getPackagedLoop())
407 Loop->Exits.clear();
Nicola Zaghen0818e782018-05-14 12:53:11 +0000408 LLVM_DEBUG(dbgs() << " - node: " << getBlockName(M.Index) << "\n");
Duncan P. N. Exon Smith96837f72014-04-28 20:02:29 +0000409 }
Duncan P. N. Exon Smith336238c2014-04-25 04:38:01 +0000410 Loop.IsPackaged = true;
Duncan P. N. Exon Smith9a11d662014-04-21 17:57:07 +0000411}
412
Diego Novillo3f53fc82015-06-16 19:10:58 +0000413#ifndef NDEBUG
414static void debugAssign(const BlockFrequencyInfoImplBase &BFI,
415 const DitheringDistributer &D, const BlockNode &T,
416 const BlockMass &M, const char *Desc) {
417 dbgs() << " => assign " << M << " (" << D.RemMass << ")";
418 if (Desc)
419 dbgs() << " [" << Desc << "]";
420 if (T.isValid())
421 dbgs() << " to " << BFI.getBlockName(T);
422 dbgs() << "\n";
423}
424#endif
425
Duncan P. N. Exon Smith9a11d662014-04-21 17:57:07 +0000426void BlockFrequencyInfoImplBase::distributeMass(const BlockNode &Source,
Duncan P. N. Exon Smith336238c2014-04-25 04:38:01 +0000427 LoopData *OuterLoop,
Duncan P. N. Exon Smith9a11d662014-04-21 17:57:07 +0000428 Distribution &Dist) {
Duncan P. N. Exon Smith2d181672014-04-25 18:47:04 +0000429 BlockMass Mass = Working[Source.Index].getMass();
Nicola Zaghen0818e782018-05-14 12:53:11 +0000430 LLVM_DEBUG(dbgs() << " => mass: " << Mass << "\n");
Duncan P. N. Exon Smith9a11d662014-04-21 17:57:07 +0000431
432 // Distribute mass to successors as laid out in Dist.
433 DitheringDistributer D(Dist, Mass);
434
Duncan P. N. Exon Smith9a11d662014-04-21 17:57:07 +0000435 for (const Weight &W : Dist.Weights) {
Duncan P. N. Exon Smith39087bf2014-04-25 04:38:43 +0000436 // Check for a local edge (non-backedge and non-exit).
437 BlockMass Taken = D.takeMass(W.Amount);
Duncan P. N. Exon Smith9a11d662014-04-21 17:57:07 +0000438 if (W.Type == Weight::Local) {
Duncan P. N. Exon Smith2d181672014-04-25 18:47:04 +0000439 Working[W.TargetNode.Index].getMass() += Taken;
Nicola Zaghen0818e782018-05-14 12:53:11 +0000440 LLVM_DEBUG(debugAssign(*this, D, W.TargetNode, Taken, nullptr));
Duncan P. N. Exon Smith9a11d662014-04-21 17:57:07 +0000441 continue;
442 }
443
444 // Backedges and exits only make sense if we're processing a loop.
Duncan P. N. Exon Smith336238c2014-04-25 04:38:01 +0000445 assert(OuterLoop && "backedge or exit outside of loop");
Duncan P. N. Exon Smith9a11d662014-04-21 17:57:07 +0000446
447 // Check for a backedge.
448 if (W.Type == Weight::Backedge) {
Diego Novillo5057ee82015-06-17 16:28:22 +0000449 OuterLoop->BackedgeMass[OuterLoop->getHeaderIndex(W.TargetNode)] += Taken;
Nicola Zaghen0818e782018-05-14 12:53:11 +0000450 LLVM_DEBUG(debugAssign(*this, D, W.TargetNode, Taken, "back"));
Duncan P. N. Exon Smith9a11d662014-04-21 17:57:07 +0000451 continue;
452 }
453
454 // This must be an exit.
455 assert(W.Type == Weight::Exit);
Duncan P. N. Exon Smith39087bf2014-04-25 04:38:43 +0000456 OuterLoop->Exits.push_back(std::make_pair(W.TargetNode, Taken));
Nicola Zaghen0818e782018-05-14 12:53:11 +0000457 LLVM_DEBUG(debugAssign(*this, D, W.TargetNode, Taken, "exit"));
Duncan P. N. Exon Smith9a11d662014-04-21 17:57:07 +0000458 }
459}
460
461static void convertFloatingToInteger(BlockFrequencyInfoImplBase &BFI,
Duncan P. N. Exon Smith6ecab5a2014-06-24 00:26:13 +0000462 const Scaled64 &Min, const Scaled64 &Max) {
Duncan P. N. Exon Smith9a11d662014-04-21 17:57:07 +0000463 // Scale the Factor to a size that creates integers. Ideally, integers would
464 // be scaled so that Max == UINT64_MAX so that they can be best
Diego Novillo32d90202015-04-01 17:42:27 +0000465 // differentiated. However, in the presence of large frequency values, small
466 // frequencies are scaled down to 1, making it impossible to differentiate
467 // small, unequal numbers. When the spread between Min and Max frequencies
468 // fits well within MaxBits, we make the scale be at least 8.
469 const unsigned MaxBits = 64;
470 const unsigned SpreadBits = (Max / Min).lg();
471 Scaled64 ScalingFactor;
472 if (SpreadBits <= MaxBits - 3) {
473 // If the values are small enough, make the scaling factor at least 8 to
474 // allow distinguishing small values.
475 ScalingFactor = Min.inverse();
Duncan P. N. Exon Smith9a11d662014-04-21 17:57:07 +0000476 ScalingFactor <<= 3;
Diego Novillo32d90202015-04-01 17:42:27 +0000477 } else {
478 // If the values need more than MaxBits to be represented, saturate small
479 // frequency values down to 1 by using a scaling factor that benefits large
480 // frequency values.
481 ScalingFactor = Scaled64(1, MaxBits) / Max;
482 }
Duncan P. N. Exon Smith9a11d662014-04-21 17:57:07 +0000483
484 // Translate the floats to integers.
Nicola Zaghen0818e782018-05-14 12:53:11 +0000485 LLVM_DEBUG(dbgs() << "float-to-int: min = " << Min << ", max = " << Max
486 << ", factor = " << ScalingFactor << "\n");
Duncan P. N. Exon Smith9a11d662014-04-21 17:57:07 +0000487 for (size_t Index = 0; Index < BFI.Freqs.size(); ++Index) {
Duncan P. N. Exon Smith6ecab5a2014-06-24 00:26:13 +0000488 Scaled64 Scaled = BFI.Freqs[Index].Scaled * ScalingFactor;
Duncan P. N. Exon Smith9a11d662014-04-21 17:57:07 +0000489 BFI.Freqs[Index].Integer = std::max(UINT64_C(1), Scaled.toInt<uint64_t>());
Nicola Zaghen0818e782018-05-14 12:53:11 +0000490 LLVM_DEBUG(dbgs() << " - " << BFI.getBlockName(Index) << ": float = "
491 << BFI.Freqs[Index].Scaled << ", scaled = " << Scaled
492 << ", int = " << BFI.Freqs[Index].Integer << "\n");
Duncan P. N. Exon Smith9a11d662014-04-21 17:57:07 +0000493 }
494}
495
Adrian Prantl26b584c2018-05-01 15:54:18 +0000496/// Unwrap a loop package.
Duncan P. N. Exon Smith9a11d662014-04-21 17:57:07 +0000497///
498/// Visits all the members of a loop, adjusting their BlockData according to
499/// the loop's pseudo-node.
Duncan P. N. Exon Smithf47649f2014-04-25 04:38:25 +0000500static void unwrapLoop(BlockFrequencyInfoImplBase &BFI, LoopData &Loop) {
Nicola Zaghen0818e782018-05-14 12:53:11 +0000501 LLVM_DEBUG(dbgs() << "unwrap-loop-package: " << BFI.getLoopName(Loop)
502 << ": mass = " << Loop.Mass << ", scale = " << Loop.Scale
503 << "\n");
Duncan P. N. Exon Smith6ecab5a2014-06-24 00:26:13 +0000504 Loop.Scale *= Loop.Mass.toScaled();
Duncan P. N. Exon Smith58aa6072014-04-25 04:38:27 +0000505 Loop.IsPackaged = false;
Nicola Zaghen0818e782018-05-14 12:53:11 +0000506 LLVM_DEBUG(dbgs() << " => combined-scale = " << Loop.Scale << "\n");
Duncan P. N. Exon Smith9a11d662014-04-21 17:57:07 +0000507
508 // Propagate the head scale through the loop. Since members are visited in
509 // RPO, the head scale will be updated by the loop scale first, and then the
510 // final head scale will be used for updated the rest of the members.
Duncan P. N. Exon Smith58aa6072014-04-25 04:38:27 +0000511 for (const BlockNode &N : Loop.Nodes) {
512 const auto &Working = BFI.Working[N.Index];
Duncan P. N. Exon Smith6ecab5a2014-06-24 00:26:13 +0000513 Scaled64 &F = Working.isAPackage() ? Working.getPackagedLoop()->Scale
514 : BFI.Freqs[N.Index].Scaled;
515 Scaled64 New = Loop.Scale * F;
Nicola Zaghen0818e782018-05-14 12:53:11 +0000516 LLVM_DEBUG(dbgs() << " - " << BFI.getBlockName(N) << ": " << F << " => "
517 << New << "\n");
Duncan P. N. Exon Smith58aa6072014-04-25 04:38:27 +0000518 F = New;
Duncan P. N. Exon Smith9a11d662014-04-21 17:57:07 +0000519 }
520}
521
Duncan P. N. Exon Smith34757652014-04-25 04:38:17 +0000522void BlockFrequencyInfoImplBase::unwrapLoops() {
Duncan P. N. Exon Smith9a11d662014-04-21 17:57:07 +0000523 // Set initial frequencies from loop-local masses.
524 for (size_t Index = 0; Index < Working.size(); ++Index)
Duncan P. N. Exon Smith6ecab5a2014-06-24 00:26:13 +0000525 Freqs[Index].Scaled = Working[Index].Mass.toScaled();
Duncan P. N. Exon Smith9a11d662014-04-21 17:57:07 +0000526
Duncan P. N. Exon Smithed306d02014-04-25 04:38:23 +0000527 for (LoopData &Loop : Loops)
Duncan P. N. Exon Smithf47649f2014-04-25 04:38:25 +0000528 unwrapLoop(*this, Loop);
Duncan P. N. Exon Smith34757652014-04-25 04:38:17 +0000529}
530
531void BlockFrequencyInfoImplBase::finalizeMetrics() {
Duncan P. N. Exon Smith9a11d662014-04-21 17:57:07 +0000532 // Unwrap loop packages in reverse post-order, tracking min and max
533 // frequencies.
Duncan P. N. Exon Smith6ecab5a2014-06-24 00:26:13 +0000534 auto Min = Scaled64::getLargest();
535 auto Max = Scaled64::getZero();
Duncan P. N. Exon Smith9a11d662014-04-21 17:57:07 +0000536 for (size_t Index = 0; Index < Working.size(); ++Index) {
Duncan P. N. Exon Smith34757652014-04-25 04:38:17 +0000537 // Update min/max scale.
Duncan P. N. Exon Smith6ecab5a2014-06-24 00:26:13 +0000538 Min = std::min(Min, Freqs[Index].Scaled);
539 Max = std::max(Max, Freqs[Index].Scaled);
Duncan P. N. Exon Smith9a11d662014-04-21 17:57:07 +0000540 }
541
542 // Convert to integers.
543 convertFloatingToInteger(*this, Min, Max);
544
545 // Clean up data structures.
546 cleanup(*this);
547
548 // Print out the final stats.
Nicola Zaghen0818e782018-05-14 12:53:11 +0000549 LLVM_DEBUG(dump());
Duncan P. N. Exon Smith9a11d662014-04-21 17:57:07 +0000550}
551
552BlockFrequency
553BlockFrequencyInfoImplBase::getBlockFreq(const BlockNode &Node) const {
554 if (!Node.isValid())
555 return 0;
556 return Freqs[Node.Index].Integer;
557}
Eugene Zelenko380d47d2016-02-02 18:20:45 +0000558
Xinliang David Li7f4f1f62016-06-22 17:12:12 +0000559Optional<uint64_t>
560BlockFrequencyInfoImplBase::getBlockProfileCount(const Function &F,
561 const BlockNode &Node) const {
Sean Silvae9e07462016-08-02 02:15:45 +0000562 return getProfileCountFromFreq(F, getBlockFreq(Node).getFrequency());
563}
564
565Optional<uint64_t>
566BlockFrequencyInfoImplBase::getProfileCountFromFreq(const Function &F,
567 uint64_t Freq) const {
Xinliang David Li7f4f1f62016-06-22 17:12:12 +0000568 auto EntryCount = F.getEntryCount();
569 if (!EntryCount)
570 return None;
571 // Use 128 bit APInt to do the arithmetic to avoid overflow.
Easwaran Ramanfd335152018-01-17 22:24:23 +0000572 APInt BlockCount(128, EntryCount.getCount());
Sean Silvae9e07462016-08-02 02:15:45 +0000573 APInt BlockFreq(128, Freq);
Xinliang David Li7f4f1f62016-06-22 17:12:12 +0000574 APInt EntryFreq(128, getEntryFreq());
575 BlockCount *= BlockFreq;
Easwaran Raman21f571c2018-08-16 00:26:59 +0000576 // Rounded division of BlockCount by EntryFreq. Since EntryFreq is unsigned
577 // lshr by 1 gives EntryFreq/2.
578 BlockCount = (BlockCount + EntryFreq.lshr(1)).udiv(EntryFreq);
Xinliang David Li7f4f1f62016-06-22 17:12:12 +0000579 return BlockCount.getLimitedValue();
580}
581
Hiroshi Yamauchidd33e172017-11-02 22:26:51 +0000582bool
583BlockFrequencyInfoImplBase::isIrrLoopHeader(const BlockNode &Node) {
584 if (!Node.isValid())
585 return false;
586 return IsIrrLoopHeader.test(Node.Index);
587}
588
Duncan P. N. Exon Smith6ecab5a2014-06-24 00:26:13 +0000589Scaled64
Duncan P. N. Exon Smith9a11d662014-04-21 17:57:07 +0000590BlockFrequencyInfoImplBase::getFloatingBlockFreq(const BlockNode &Node) const {
591 if (!Node.isValid())
Duncan P. N. Exon Smith6ecab5a2014-06-24 00:26:13 +0000592 return Scaled64::getZero();
593 return Freqs[Node.Index].Scaled;
Duncan P. N. Exon Smith9a11d662014-04-21 17:57:07 +0000594}
595
Manman Ren0f342072015-10-15 14:59:40 +0000596void BlockFrequencyInfoImplBase::setBlockFreq(const BlockNode &Node,
597 uint64_t Freq) {
598 assert(Node.isValid() && "Expected valid node");
599 assert(Node.Index < Freqs.size() && "Expected legal index");
600 Freqs[Node.Index].Integer = Freq;
601}
602
Duncan P. N. Exon Smith9a11d662014-04-21 17:57:07 +0000603std::string
604BlockFrequencyInfoImplBase::getBlockName(const BlockNode &Node) const {
Eugene Zelenko15a56d42017-07-21 21:37:46 +0000605 return {};
Duncan P. N. Exon Smith9a11d662014-04-21 17:57:07 +0000606}
Eugene Zelenko380d47d2016-02-02 18:20:45 +0000607
Duncan P. N. Exon Smith96837f72014-04-28 20:02:29 +0000608std::string
609BlockFrequencyInfoImplBase::getLoopName(const LoopData &Loop) const {
610 return getBlockName(Loop.getHeader()) + (Loop.isIrreducible() ? "**" : "*");
611}
Duncan P. N. Exon Smith9a11d662014-04-21 17:57:07 +0000612
613raw_ostream &
614BlockFrequencyInfoImplBase::printBlockFreq(raw_ostream &OS,
615 const BlockNode &Node) const {
616 return OS << getFloatingBlockFreq(Node);
617}
618
619raw_ostream &
620BlockFrequencyInfoImplBase::printBlockFreq(raw_ostream &OS,
621 const BlockFrequency &Freq) const {
Duncan P. N. Exon Smith6ecab5a2014-06-24 00:26:13 +0000622 Scaled64 Block(Freq.getFrequency(), 0);
623 Scaled64 Entry(getEntryFreq(), 0);
Duncan P. N. Exon Smith9a11d662014-04-21 17:57:07 +0000624
625 return OS << Block / Entry;
626}
Duncan P. N. Exon Smith96837f72014-04-28 20:02:29 +0000627
628void IrreducibleGraph::addNodesInLoop(const BFIBase::LoopData &OuterLoop) {
629 Start = OuterLoop.getHeader();
630 Nodes.reserve(OuterLoop.Nodes.size());
631 for (auto N : OuterLoop.Nodes)
632 addNode(N);
633 indexNodes();
634}
Eugene Zelenko380d47d2016-02-02 18:20:45 +0000635
Duncan P. N. Exon Smith96837f72014-04-28 20:02:29 +0000636void IrreducibleGraph::addNodesInFunction() {
637 Start = 0;
638 for (uint32_t Index = 0; Index < BFI.Working.size(); ++Index)
639 if (!BFI.Working[Index].isPackaged())
640 addNode(Index);
641 indexNodes();
642}
Eugene Zelenko380d47d2016-02-02 18:20:45 +0000643
Duncan P. N. Exon Smith96837f72014-04-28 20:02:29 +0000644void IrreducibleGraph::indexNodes() {
645 for (auto &I : Nodes)
646 Lookup[I.Node.Index] = &I;
647}
Eugene Zelenko380d47d2016-02-02 18:20:45 +0000648
Duncan P. N. Exon Smith96837f72014-04-28 20:02:29 +0000649void IrreducibleGraph::addEdge(IrrNode &Irr, const BlockNode &Succ,
650 const BFIBase::LoopData *OuterLoop) {
651 if (OuterLoop && OuterLoop->isHeader(Succ))
652 return;
653 auto L = Lookup.find(Succ.Index);
654 if (L == Lookup.end())
655 return;
656 IrrNode &SuccIrr = *L->second;
657 Irr.Edges.push_back(&SuccIrr);
658 SuccIrr.Edges.push_front(&Irr);
659 ++SuccIrr.NumIn;
660}
661
662namespace llvm {
Duncan P. N. Exon Smith96837f72014-04-28 20:02:29 +0000663
Eugene Zelenko15a56d42017-07-21 21:37:46 +0000664template <> struct GraphTraits<IrreducibleGraph> {
665 using GraphT = bfi_detail::IrreducibleGraph;
666 using NodeRef = const GraphT::IrrNode *;
667 using ChildIteratorType = GraphT::IrrNode::iterator;
Duncan P. N. Exon Smith96837f72014-04-28 20:02:29 +0000668
Tim Shen22fca382016-08-22 21:09:30 +0000669 static NodeRef getEntryNode(const GraphT &G) { return G.StartIrr; }
670 static ChildIteratorType child_begin(NodeRef N) { return N->succ_begin(); }
671 static ChildIteratorType child_end(NodeRef N) { return N->succ_end(); }
Duncan P. N. Exon Smith96837f72014-04-28 20:02:29 +0000672};
Eugene Zelenko15a56d42017-07-21 21:37:46 +0000673
Eugene Zelenko380d47d2016-02-02 18:20:45 +0000674} // end namespace llvm
Duncan P. N. Exon Smith96837f72014-04-28 20:02:29 +0000675
Adrian Prantl26b584c2018-05-01 15:54:18 +0000676/// Find extra irreducible headers.
Duncan P. N. Exon Smith96837f72014-04-28 20:02:29 +0000677///
678/// Find entry blocks and other blocks with backedges, which exist when \c G
679/// contains irreducible sub-SCCs.
680static void findIrreducibleHeaders(
681 const BlockFrequencyInfoImplBase &BFI,
682 const IrreducibleGraph &G,
683 const std::vector<const IrreducibleGraph::IrrNode *> &SCC,
684 LoopData::NodeList &Headers, LoopData::NodeList &Others) {
685 // Map from nodes in the SCC to whether it's an entry block.
686 SmallDenseMap<const IrreducibleGraph::IrrNode *, bool, 8> InSCC;
687
688 // InSCC also acts the set of nodes in the graph. Seed it.
689 for (const auto *I : SCC)
690 InSCC[I] = false;
691
692 for (auto I = InSCC.begin(), E = InSCC.end(); I != E; ++I) {
693 auto &Irr = *I->first;
694 for (const auto *P : make_range(Irr.pred_begin(), Irr.pred_end())) {
695 if (InSCC.count(P))
696 continue;
697
698 // This is an entry block.
699 I->second = true;
700 Headers.push_back(Irr.Node);
Nicola Zaghen0818e782018-05-14 12:53:11 +0000701 LLVM_DEBUG(dbgs() << " => entry = " << BFI.getBlockName(Irr.Node)
702 << "\n");
Duncan P. N. Exon Smith96837f72014-04-28 20:02:29 +0000703 break;
704 }
705 }
Duncan P. N. Exon Smith76097122014-10-06 17:42:00 +0000706 assert(Headers.size() >= 2 &&
707 "Expected irreducible CFG; -loop-info is likely invalid");
Duncan P. N. Exon Smith96837f72014-04-28 20:02:29 +0000708 if (Headers.size() == InSCC.size()) {
709 // Every block is a header.
Fangrui Song3b35e172018-09-27 02:13:45 +0000710 llvm::sort(Headers);
Duncan P. N. Exon Smith96837f72014-04-28 20:02:29 +0000711 return;
712 }
713
714 // Look for extra headers from irreducible sub-SCCs.
715 for (const auto &I : InSCC) {
716 // Entry blocks are already headers.
717 if (I.second)
718 continue;
719
720 auto &Irr = *I.first;
721 for (const auto *P : make_range(Irr.pred_begin(), Irr.pred_end())) {
722 // Skip forward edges.
723 if (P->Node < Irr.Node)
724 continue;
725
726 // Skip predecessors from entry blocks. These can have inverted
727 // ordering.
728 if (InSCC.lookup(P))
729 continue;
730
731 // Store the extra header.
732 Headers.push_back(Irr.Node);
Nicola Zaghen0818e782018-05-14 12:53:11 +0000733 LLVM_DEBUG(dbgs() << " => extra = " << BFI.getBlockName(Irr.Node)
734 << "\n");
Duncan P. N. Exon Smith96837f72014-04-28 20:02:29 +0000735 break;
736 }
737 if (Headers.back() == Irr.Node)
738 // Added this as a header.
739 continue;
740
741 // This is not a header.
742 Others.push_back(Irr.Node);
Nicola Zaghen0818e782018-05-14 12:53:11 +0000743 LLVM_DEBUG(dbgs() << " => other = " << BFI.getBlockName(Irr.Node) << "\n");
Duncan P. N. Exon Smith96837f72014-04-28 20:02:29 +0000744 }
Fangrui Song3b35e172018-09-27 02:13:45 +0000745 llvm::sort(Headers);
746 llvm::sort(Others);
Duncan P. N. Exon Smith96837f72014-04-28 20:02:29 +0000747}
748
749static void createIrreducibleLoop(
750 BlockFrequencyInfoImplBase &BFI, const IrreducibleGraph &G,
751 LoopData *OuterLoop, std::list<LoopData>::iterator Insert,
752 const std::vector<const IrreducibleGraph::IrrNode *> &SCC) {
753 // Translate the SCC into RPO.
Nicola Zaghen0818e782018-05-14 12:53:11 +0000754 LLVM_DEBUG(dbgs() << " - found-scc\n");
Duncan P. N. Exon Smith96837f72014-04-28 20:02:29 +0000755
756 LoopData::NodeList Headers;
757 LoopData::NodeList Others;
758 findIrreducibleHeaders(BFI, G, SCC, Headers, Others);
759
760 auto Loop = BFI.Loops.emplace(Insert, OuterLoop, Headers.begin(),
761 Headers.end(), Others.begin(), Others.end());
762
763 // Update loop hierarchy.
764 for (const auto &N : Loop->Nodes)
765 if (BFI.Working[N.Index].isLoopHeader())
766 BFI.Working[N.Index].Loop->Parent = &*Loop;
767 else
768 BFI.Working[N.Index].Loop = &*Loop;
769}
770
771iterator_range<std::list<LoopData>::iterator>
772BlockFrequencyInfoImplBase::analyzeIrreducible(
773 const IrreducibleGraph &G, LoopData *OuterLoop,
774 std::list<LoopData>::iterator Insert) {
775 assert((OuterLoop == nullptr) == (Insert == Loops.begin()));
776 auto Prev = OuterLoop ? std::prev(Insert) : Loops.end();
777
778 for (auto I = scc_begin(G); !I.isAtEnd(); ++I) {
779 if (I->size() < 2)
780 continue;
781
782 // Translate the SCC into RPO.
783 createIrreducibleLoop(*this, G, OuterLoop, Insert, *I);
784 }
785
786 if (OuterLoop)
787 return make_range(std::next(Prev), Insert);
788 return make_range(Loops.begin(), Insert);
789}
790
791void
792BlockFrequencyInfoImplBase::updateLoopWithIrreducible(LoopData &OuterLoop) {
793 OuterLoop.Exits.clear();
Diego Novillo3f53fc82015-06-16 19:10:58 +0000794 for (auto &Mass : OuterLoop.BackedgeMass)
795 Mass = BlockMass::getEmpty();
Duncan P. N. Exon Smith96837f72014-04-28 20:02:29 +0000796 auto O = OuterLoop.Nodes.begin() + 1;
797 for (auto I = O, E = OuterLoop.Nodes.end(); I != E; ++I)
798 if (!Working[I->Index].isPackaged())
799 *O++ = *I;
800 OuterLoop.Nodes.erase(O, OuterLoop.Nodes.end());
801}
Diego Novillo3f53fc82015-06-16 19:10:58 +0000802
803void BlockFrequencyInfoImplBase::adjustLoopHeaderMass(LoopData &Loop) {
804 assert(Loop.isIrreducible() && "this only makes sense on irreducible loops");
805
806 // Since the loop has more than one header block, the mass flowing back into
807 // each header will be different. Adjust the mass in each header loop to
808 // reflect the masses flowing through back edges.
809 //
810 // To do this, we distribute the initial mass using the backedge masses
811 // as weights for the distribution.
812 BlockMass LoopMass = BlockMass::getFull();
813 Distribution Dist;
814
Nicola Zaghen0818e782018-05-14 12:53:11 +0000815 LLVM_DEBUG(dbgs() << "adjust-loop-header-mass:\n");
Diego Novillo3f53fc82015-06-16 19:10:58 +0000816 for (uint32_t H = 0; H < Loop.NumHeaders; ++H) {
817 auto &HeaderNode = Loop.Nodes[H];
Diego Novillo5057ee82015-06-17 16:28:22 +0000818 auto &BackedgeMass = Loop.BackedgeMass[Loop.getHeaderIndex(HeaderNode)];
Nicola Zaghen0818e782018-05-14 12:53:11 +0000819 LLVM_DEBUG(dbgs() << " - Add back edge mass for node "
820 << getBlockName(HeaderNode) << ": " << BackedgeMass
821 << "\n");
Diego Novillo965f2c22015-09-08 19:22:17 +0000822 if (BackedgeMass.getMass() > 0)
823 Dist.addLocal(HeaderNode, BackedgeMass.getMass());
824 else
Nicola Zaghen0818e782018-05-14 12:53:11 +0000825 LLVM_DEBUG(dbgs() << " Nothing added. Back edge mass is zero\n");
Diego Novillo3f53fc82015-06-16 19:10:58 +0000826 }
827
828 DitheringDistributer D(Dist, LoopMass);
829
Nicola Zaghen0818e782018-05-14 12:53:11 +0000830 LLVM_DEBUG(dbgs() << " Distribute loop mass " << LoopMass
831 << " to headers using above weights\n");
Diego Novillo3f53fc82015-06-16 19:10:58 +0000832 for (const Weight &W : Dist.Weights) {
833 BlockMass Taken = D.takeMass(W.Amount);
834 assert(W.Type == Weight::Local && "all weights should be local");
835 Working[W.TargetNode.Index].getMass() = Taken;
Nicola Zaghen0818e782018-05-14 12:53:11 +0000836 LLVM_DEBUG(debugAssign(*this, D, W.TargetNode, Taken, nullptr));
Diego Novillo3f53fc82015-06-16 19:10:58 +0000837 }
838}
Hiroshi Yamauchidd33e172017-11-02 22:26:51 +0000839
840void BlockFrequencyInfoImplBase::distributeIrrLoopHeaderMass(Distribution &Dist) {
841 BlockMass LoopMass = BlockMass::getFull();
842 DitheringDistributer D(Dist, LoopMass);
843 for (const Weight &W : Dist.Weights) {
844 BlockMass Taken = D.takeMass(W.Amount);
845 assert(W.Type == Weight::Local && "all weights should be local");
846 Working[W.TargetNode.Index].getMass() = Taken;
Nicola Zaghen0818e782018-05-14 12:53:11 +0000847 LLVM_DEBUG(debugAssign(*this, D, W.TargetNode, Taken, nullptr));
Hiroshi Yamauchidd33e172017-11-02 22:26:51 +0000848 }
849}