1 //===-- SpillPlacement.cpp - Optimal Spill Code Placement -----------------===//
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 // This file implements the spill code placement analysis.
12 // Each edge bundle corresponds to a node in a Hopfield network. Constraints on
13 // basic blocks are weighted by the block frequency and added to become the node
16 // Transparent basic blocks have the variable live through, but don't care if it
17 // is spilled or in a register. These blocks become connections in the Hopfield
18 // network, again weighted by block frequency.
20 // The Hopfield network minimizes (possibly locally) its energy function:
22 // E = -sum_n V_n * ( B_n + sum_{n, m linked by b} V_m * F_b )
24 // The energy function represents the expected spill code execution frequency,
25 // or the cost of spilling. This is a Lyapunov function which never increases
26 // when a node is updated. It is guaranteed to converge to a local minimum.
28 //===----------------------------------------------------------------------===//
30 #include "SpillPlacement.h"
31 #include "llvm/ADT/BitVector.h"
32 #include "llvm/CodeGen/EdgeBundles.h"
33 #include "llvm/CodeGen/MachineBasicBlock.h"
34 #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
35 #include "llvm/CodeGen/MachineFunction.h"
36 #include "llvm/CodeGen/MachineLoopInfo.h"
37 #include "llvm/CodeGen/Passes.h"
38 #include "llvm/Support/Debug.h"
39 #include "llvm/Support/Format.h"
40 #include "llvm/Support/ManagedStatic.h"
44 #define DEBUG_TYPE "spillplacement"
46 char SpillPlacement::ID = 0;
47 INITIALIZE_PASS_BEGIN(SpillPlacement, "spill-code-placement",
48 "Spill Code Placement Analysis", true, true)
49 INITIALIZE_PASS_DEPENDENCY(EdgeBundles)
50 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
51 INITIALIZE_PASS_END(SpillPlacement, "spill-code-placement",
52 "Spill Code Placement Analysis", true, true)
54 char &llvm::SpillPlacementID = SpillPlacement::ID;
56 void SpillPlacement::getAnalysisUsage(AnalysisUsage &AU) const {
58 AU.addRequired<MachineBlockFrequencyInfo>();
59 AU.addRequiredTransitive<EdgeBundles>();
60 AU.addRequiredTransitive<MachineLoopInfo>();
61 MachineFunctionPass::getAnalysisUsage(AU);
65 static ManagedStatic<BlockFrequency> Threshold;
68 /// Decision threshold. A node gets the output value 0 if the weighted sum of
69 /// its inputs falls in the open interval (-Threshold;Threshold).
70 static BlockFrequency getThreshold() { return *Threshold; }
72 /// \brief Set the threshold for a given entry frequency.
74 /// Set the threshold relative to \c Entry. Since the threshold is used as a
75 /// bound on the open interval (-Threshold;Threshold), 1 is the minimum
77 static void setThreshold(const BlockFrequency &Entry) {
78 // Apparently 2 is a good threshold when Entry==2^14, but we need to scale
79 // it. Divide by 2^13, rounding as appropriate.
80 uint64_t Freq = Entry.getFrequency();
81 uint64_t Scaled = (Freq >> 13) + bool(Freq & (1 << 12));
82 *Threshold = std::max(UINT64_C(1), Scaled);
85 /// Node - Each edge bundle corresponds to a Hopfield node.
87 /// The node contains precomputed frequency data that only depends on the CFG,
88 /// but Bias and Links are computed each time placeSpills is called.
90 /// The node Value is positive when the variable should be in a register. The
91 /// value can change when linked nodes change, but convergence is very fast
92 /// because all weights are positive.
94 struct SpillPlacement::Node {
95 /// BiasN - Sum of blocks that prefer a spill.
97 /// BiasP - Sum of blocks that prefer a register.
100 /// Value - Output value of this node computed from the Bias and links.
101 /// This is always on of the values {-1, 0, 1}. A positive number means the
102 /// variable should go in a register through this bundle.
105 typedef SmallVector<std::pair<BlockFrequency, unsigned>, 4> LinkVector;
107 /// Links - (Weight, BundleNo) for all transparent blocks connecting to other
108 /// bundles. The weights are all positive block frequencies.
111 /// SumLinkWeights - Cached sum of the weights of all links + ThresHold.
112 BlockFrequency SumLinkWeights;
114 /// preferReg - Return true when this node prefers to be in a register.
115 bool preferReg() const {
116 // Undecided nodes (Value==0) go on the stack.
120 /// mustSpill - Return True if this node is so biased that it must spill.
121 bool mustSpill() const {
122 // We must spill if Bias < -sum(weights) or the MustSpill flag was set.
123 // BiasN is saturated when MustSpill is set, make sure this still returns
124 // true when the RHS saturates. Note that SumLinkWeights includes Threshold.
125 return BiasN >= BiasP + SumLinkWeights;
128 /// clear - Reset per-query data, but preserve frequencies that only depend on
131 BiasN = BiasP = Value = 0;
132 SumLinkWeights = getThreshold();
136 /// addLink - Add a link to bundle b with weight w.
137 void addLink(unsigned b, BlockFrequency w) {
138 // Update cached sum.
141 // There can be multiple links to the same bundle, add them up.
142 for (LinkVector::iterator I = Links.begin(), E = Links.end(); I != E; ++I)
143 if (I->second == b) {
147 // This must be the first link to b.
148 Links.push_back(std::make_pair(w, b));
151 /// addBias - Bias this node.
152 void addBias(BlockFrequency freq, BorderConstraint direction) {
163 BiasN = BlockFrequency::getMaxFrequency();
168 /// update - Recompute Value from Bias and Links. Return true when node
169 /// preference changes.
170 bool update(const Node nodes[]) {
171 // Compute the weighted sum of inputs.
172 BlockFrequency SumN = BiasN;
173 BlockFrequency SumP = BiasP;
174 for (LinkVector::iterator I = Links.begin(), E = Links.end(); I != E; ++I) {
175 if (nodes[I->second].Value == -1)
177 else if (nodes[I->second].Value == 1)
181 // Each weighted sum is going to be less than the total frequency of the
182 // bundle. Ideally, we should simply set Value = sign(SumP - SumN), but we
183 // will add a dead zone around 0 for two reasons:
185 // 1. It avoids arbitrary bias when all links are 0 as is possible during
186 // initial iterations.
187 // 2. It helps tame rounding errors when the links nominally sum to 0.
189 bool Before = preferReg();
190 if (SumN >= SumP + getThreshold())
192 else if (SumP >= SumN + getThreshold())
196 return Before != preferReg();
200 bool SpillPlacement::runOnMachineFunction(MachineFunction &mf) {
202 bundles = &getAnalysis<EdgeBundles>();
203 loops = &getAnalysis<MachineLoopInfo>();
205 assert(!nodes && "Leaking node array");
206 nodes = new Node[bundles->getNumBundles()];
208 // Compute total ingoing and outgoing block frequencies for all bundles.
209 BlockFrequencies.resize(mf.getNumBlockIDs());
210 MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
211 setThreshold(MBFI->getEntryFreq());
212 for (MachineFunction::iterator I = mf.begin(), E = mf.end(); I != E; ++I) {
213 unsigned Num = I->getNumber();
214 BlockFrequencies[Num] = MBFI->getBlockFreq(I);
217 // We never change the function.
221 void SpillPlacement::releaseMemory() {
226 /// activate - mark node n as active if it wasn't already.
227 void SpillPlacement::activate(unsigned n) {
228 if (ActiveNodes->test(n))
233 // Very large bundles usually come from big switches, indirect branches,
234 // landing pads, or loops with many 'continue' statements. It is difficult to
235 // allocate registers when so many different blocks are involved.
237 // Give a small negative bias to large bundles such that a substantial
238 // fraction of the connected blocks need to be interested before we consider
239 // expanding the region through the bundle. This helps compile time by
240 // limiting the number of blocks visited and the number of links in the
242 if (bundles->getBlocks(n).size() > 100) {
244 nodes[n].BiasN = (MBFI->getEntryFreq() / 16);
249 /// addConstraints - Compute node biases and weights from a set of constraints.
250 /// Set a bit in NodeMask for each active node.
251 void SpillPlacement::addConstraints(ArrayRef<BlockConstraint> LiveBlocks) {
252 for (ArrayRef<BlockConstraint>::iterator I = LiveBlocks.begin(),
253 E = LiveBlocks.end(); I != E; ++I) {
254 BlockFrequency Freq = BlockFrequencies[I->Number];
257 if (I->Entry != DontCare) {
258 unsigned ib = bundles->getBundle(I->Number, 0);
260 nodes[ib].addBias(Freq, I->Entry);
263 // Live-out from block?
264 if (I->Exit != DontCare) {
265 unsigned ob = bundles->getBundle(I->Number, 1);
267 nodes[ob].addBias(Freq, I->Exit);
272 /// addPrefSpill - Same as addConstraints(PrefSpill)
273 void SpillPlacement::addPrefSpill(ArrayRef<unsigned> Blocks, bool Strong) {
274 for (ArrayRef<unsigned>::iterator I = Blocks.begin(), E = Blocks.end();
276 BlockFrequency Freq = BlockFrequencies[*I];
279 unsigned ib = bundles->getBundle(*I, 0);
280 unsigned ob = bundles->getBundle(*I, 1);
283 nodes[ib].addBias(Freq, PrefSpill);
284 nodes[ob].addBias(Freq, PrefSpill);
288 void SpillPlacement::addLinks(ArrayRef<unsigned> Links) {
289 for (ArrayRef<unsigned>::iterator I = Links.begin(), E = Links.end(); I != E;
291 unsigned Number = *I;
292 unsigned ib = bundles->getBundle(Number, 0);
293 unsigned ob = bundles->getBundle(Number, 1);
295 // Ignore self-loops.
300 if (nodes[ib].Links.empty() && !nodes[ib].mustSpill())
301 Linked.push_back(ib);
302 if (nodes[ob].Links.empty() && !nodes[ob].mustSpill())
303 Linked.push_back(ob);
304 BlockFrequency Freq = BlockFrequencies[Number];
305 nodes[ib].addLink(ob, Freq);
306 nodes[ob].addLink(ib, Freq);
310 bool SpillPlacement::scanActiveBundles() {
312 RecentPositive.clear();
313 for (int n = ActiveNodes->find_first(); n>=0; n = ActiveNodes->find_next(n)) {
314 nodes[n].update(nodes);
315 // A node that must spill, or a node without any links is not going to
316 // change its value ever again, so exclude it from iterations.
317 if (nodes[n].mustSpill())
319 if (!nodes[n].Links.empty())
321 if (nodes[n].preferReg())
322 RecentPositive.push_back(n);
324 return !RecentPositive.empty();
327 /// iterate - Repeatedly update the Hopfield nodes until stability or the
328 /// maximum number of iterations is reached.
329 /// @param Linked - Numbers of linked nodes that need updating.
330 void SpillPlacement::iterate() {
331 // First update the recently positive nodes. They have likely received new
332 // negative bias that will turn them off.
333 while (!RecentPositive.empty())
334 nodes[RecentPositive.pop_back_val()].update(nodes);
339 // Run up to 10 iterations. The edge bundle numbering is closely related to
340 // basic block numbering, so there is a strong tendency towards chains of
341 // linked nodes with sequential numbers. By scanning the linked nodes
342 // backwards and forwards, we make it very likely that a single node can
343 // affect the entire network in a single iteration. That means very fast
344 // convergence, usually in a single iteration.
345 for (unsigned iteration = 0; iteration != 10; ++iteration) {
346 // Scan backwards, skipping the last node when iteration is not zero. When
347 // iteration is not zero, the last node was just updated.
348 bool Changed = false;
349 for (SmallVectorImpl<unsigned>::const_reverse_iterator I =
350 iteration == 0 ? Linked.rbegin() : std::next(Linked.rbegin()),
351 E = Linked.rend(); I != E; ++I) {
353 if (nodes[n].update(nodes)) {
355 if (nodes[n].preferReg())
356 RecentPositive.push_back(n);
359 if (!Changed || !RecentPositive.empty())
362 // Scan forwards, skipping the first node which was just updated.
364 for (SmallVectorImpl<unsigned>::const_iterator I =
365 std::next(Linked.begin()), E = Linked.end(); I != E; ++I) {
367 if (nodes[n].update(nodes)) {
369 if (nodes[n].preferReg())
370 RecentPositive.push_back(n);
373 if (!Changed || !RecentPositive.empty())
378 void SpillPlacement::prepare(BitVector &RegBundles) {
380 RecentPositive.clear();
381 // Reuse RegBundles as our ActiveNodes vector.
382 ActiveNodes = &RegBundles;
383 ActiveNodes->clear();
384 ActiveNodes->resize(bundles->getNumBundles());
388 SpillPlacement::finish() {
389 assert(ActiveNodes && "Call prepare() first");
391 // Write preferences back to ActiveNodes.
393 for (int n = ActiveNodes->find_first(); n>=0; n = ActiveNodes->find_next(n))
394 if (!nodes[n].preferReg()) {
395 ActiveNodes->reset(n);
398 ActiveNodes = nullptr;