blob: d8cc3e889e2fdefe6439033b66ba3fa6bf961a86 [file] [log] [blame]
Jakob Stoklund Olesen8bfe5082011-01-06 01:21:53 +00001//===-- SpillPlacement.cpp - Optimal Spill Code Placement -----------------===//
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// This file implements the spill code placement analysis.
11//
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
14// bias.
15//
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.
19//
20// The Hopfield network minimizes (possibly locally) its energy function:
21//
22// E = -sum_n V_n * ( B_n + sum_{n, m linked by b} V_m * F_b )
23//
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.
27//
28//===----------------------------------------------------------------------===//
29
30#include "SpillPlacement.h"
31#include "llvm/CodeGen/EdgeBundles.h"
32#include "llvm/CodeGen/LiveIntervalAnalysis.h"
33#include "llvm/CodeGen/MachineBasicBlock.h"
34#include "llvm/CodeGen/MachineFunction.h"
35#include "llvm/CodeGen/MachineLoopInfo.h"
36#include "llvm/CodeGen/Passes.h"
37#include "llvm/Support/Debug.h"
38#include "llvm/Support/Format.h"
39
40using namespace llvm;
41
42char SpillPlacement::ID = 0;
43INITIALIZE_PASS_BEGIN(SpillPlacement, "spill-code-placement",
44 "Spill Code Placement Analysis", true, true)
45INITIALIZE_PASS_DEPENDENCY(EdgeBundles)
46INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
47INITIALIZE_PASS_END(SpillPlacement, "spill-code-placement",
48 "Spill Code Placement Analysis", true, true)
49
50char &llvm::SpillPlacementID = SpillPlacement::ID;
51
52void SpillPlacement::getAnalysisUsage(AnalysisUsage &AU) const {
53 AU.setPreservesAll();
54 AU.addRequiredTransitive<EdgeBundles>();
55 AU.addRequiredTransitive<MachineLoopInfo>();
56 MachineFunctionPass::getAnalysisUsage(AU);
57}
58
59/// Node - Each edge bundle corresponds to a Hopfield node.
60///
61/// The node contains precomputed frequency data that only depends on the CFG,
62/// but Bias and Links are computed each time placeSpills is called.
63///
64/// The node Value is positive when the variable should be in a register. The
65/// value can change when linked nodes change, but convergence is very fast
66/// because all weights are positive.
67///
68struct SpillPlacement::Node {
69 /// Frequency - Total block frequency feeding into[0] or out of[1] the bundle.
70 /// Ideally, these two numbers should be identical, but inaccuracies in the
71 /// block frequency estimates means that we need to normalize ingoing and
72 /// outgoing frequencies separately so they are commensurate.
73 float Frequency[2];
74
75 /// Bias - Normalized contributions from non-transparent blocks.
76 /// A bundle connected to a MustSpill block has a huge negative bias,
77 /// otherwise it is a number in the range [-2;2].
78 float Bias;
79
80 /// Value - Output value of this node computed from the Bias and links.
81 /// This is always in the range [-1;1]. A positive number means the variable
82 /// should go in a register through this bundle.
83 float Value;
84
85 typedef SmallVector<std::pair<float, unsigned>, 4> LinkVector;
86
87 /// Links - (Weight, BundleNo) for all transparent blocks connecting to other
88 /// bundles. The weights are all positive and add up to at most 2, weights
89 /// from ingoing and outgoing nodes separately add up to a most 1. The weight
90 /// sum can be less than 2 when the variable is not live into / out of some
91 /// connected basic blocks.
92 LinkVector Links;
93
94 /// preferReg - Return true when this node prefers to be in a register.
95 bool preferReg() const {
96 // Undecided nodes (Value==0) go on the stack.
97 return Value > 0;
98 }
99
100 /// mustSpill - Return True if this node is so biased that it must spill.
101 bool mustSpill() const {
102 // Actually, we must spill if Bias < sum(weights).
103 // It may be worth it to compute the weight sum here?
104 return Bias < -2.0f;
105 }
106
107 /// Node - Create a blank Node.
108 Node() {
109 Frequency[0] = Frequency[1] = 0;
110 }
111
112 /// clear - Reset per-query data, but preserve frequencies that only depend on
113 // the CFG.
114 void clear() {
115 Bias = Value = 0;
116 Links.clear();
117 }
118
119 /// addLink - Add a link to bundle b with weight w.
120 /// out=0 for an ingoing link, and 1 for an outgoing link.
121 void addLink(unsigned b, float w, bool out) {
122 // Normalize w relative to all connected blocks from that direction.
123 w /= Frequency[out];
124
125 // There can be multiple links to the same bundle, add them up.
126 for (LinkVector::iterator I = Links.begin(), E = Links.end(); I != E; ++I)
127 if (I->second == b) {
128 I->first += w;
129 return;
130 }
131 // This must be the first link to b.
132 Links.push_back(std::make_pair(w, b));
133 }
134
135 /// addBias - Bias this node from an ingoing[0] or outgoing[1] link.
136 void addBias(float w, bool out) {
137 // Normalize w relative to all connected blocks from that direction.
138 w /= Frequency[out];
139 Bias += w;
140 }
141
142 /// update - Recompute Value from Bias and Links. Return true when node
143 /// preference changes.
144 bool update(const Node nodes[]) {
145 // Compute the weighted sum of inputs.
146 float Sum = Bias;
147 for (LinkVector::iterator I = Links.begin(), E = Links.end(); I != E; ++I)
148 Sum += I->first * nodes[I->second].Value;
149
150 // The weighted sum is going to be in the range [-2;2]. Ideally, we should
151 // simply set Value = sign(Sum), but we will add a dead zone around 0 for
152 // two reasons:
153 // 1. It avoids arbitrary bias when all links are 0 as is possible during
154 // initial iterations.
155 // 2. It helps tame rounding errors when the links nominally sum to 0.
156 const float Thres = 1e-4;
157 bool Before = preferReg();
158 if (Sum < -Thres)
159 Value = -1;
160 else if (Sum > Thres)
161 Value = 1;
162 else
163 Value = 0;
164 return Before != preferReg();
165 }
166};
167
168bool SpillPlacement::runOnMachineFunction(MachineFunction &mf) {
169 MF = &mf;
170 bundles = &getAnalysis<EdgeBundles>();
171 loops = &getAnalysis<MachineLoopInfo>();
172
173 assert(!nodes && "Leaking node array");
174 nodes = new Node[bundles->getNumBundles()];
175
176 // Compute total ingoing and outgoing block frequencies for all bundles.
177 for (MachineFunction::iterator I = mf.begin(), E = mf.end(); I != E; ++I) {
178 float Freq = getBlockFrequency(I);
179 unsigned Num = I->getNumber();
180 nodes[bundles->getBundle(Num, 1)].Frequency[0] += Freq;
181 nodes[bundles->getBundle(Num, 0)].Frequency[1] += Freq;
182 }
183
184 // We never change the function.
185 return false;
186}
187
188void SpillPlacement::releaseMemory() {
189 delete[] nodes;
190 nodes = 0;
191}
192
193/// activate - mark node n as active if it wasn't already.
194void SpillPlacement::activate(unsigned n) {
195 if (ActiveNodes->test(n))
196 return;
197 ActiveNodes->set(n);
198 nodes[n].clear();
199}
200
201
202/// prepareNodes - Compute node biases and weights from a set of constraints.
203/// Set a bit in NodeMask for each active node.
204void SpillPlacement::
205prepareNodes(const SmallVectorImpl<BlockConstraint> &LiveBlocks) {
206 DEBUG(dbgs() << "Building Hopfield network from " << LiveBlocks.size()
207 << " constraint blocks:\n");
208 for (SmallVectorImpl<BlockConstraint>::const_iterator I = LiveBlocks.begin(),
209 E = LiveBlocks.end(); I != E; ++I) {
210 MachineBasicBlock *MBB = MF->getBlockNumbered(I->Number);
211 float Freq = getBlockFrequency(MBB);
212 DEBUG(dbgs() << " BB#" << I->Number << format(", Freq = %.1f", Freq));
213
214 // Is this a transparent block? Link ingoing and outgoing bundles.
215 if (I->Entry == DontCare && I->Exit == DontCare) {
216 unsigned ib = bundles->getBundle(I->Number, 0);
217 unsigned ob = bundles->getBundle(I->Number, 1);
218 DEBUG(dbgs() << ", transparent EB#" << ib << " -> EB#" << ob << '\n');
219
220 // Ignore self-loops.
221 if (ib == ob)
222 continue;
223 activate(ib);
224 activate(ob);
225 nodes[ib].addLink(ob, Freq, 1);
226 nodes[ob].addLink(ib, Freq, 0);
227 continue;
228 }
229
230 // This block is not transparent, but it can still add bias.
231 const float Bias[] = {
232 0, // DontCare,
233 1, // PrefReg,
234 -1, // PrefSpill
235 -HUGE_VALF // MustSpill
236 };
237
238 // Live-in to block?
239 if (I->Entry != DontCare) {
240 unsigned ib = bundles->getBundle(I->Number, 0);
241 activate(ib);
242 nodes[ib].addBias(Freq * Bias[I->Entry], 1);
243 DEBUG(dbgs() << format(", entry EB#%u %+.1f", ib, Freq * Bias[I->Entry]));
244 }
245
246 // Live-out from block?
247 if (I->Exit != DontCare) {
248 unsigned ob = bundles->getBundle(I->Number, 1);
249 activate(ob);
250 nodes[ob].addBias(Freq * Bias[I->Exit], 0);
251 DEBUG(dbgs() << format(", exit EB#%u %+.1f", ob, Freq * Bias[I->Exit]));
252 }
253
254 DEBUG(dbgs() << '\n');
255 }
256}
257
258/// iterate - Repeatedly update the Hopfield nodes until stability or the
259/// maximum number of iterations is reached.
260/// @param Linked - Numbers of linked nodes that need updating.
261void SpillPlacement::iterate(const SmallVectorImpl<unsigned> &Linked) {
262 DEBUG(dbgs() << "Iterating over " << Linked.size() << " linked nodes:\n");
263 if (Linked.empty())
264 return;
265
266 // Run up to 10 iterations. The edge bundle numbering is closely related to
267 // basic block numbering, so there is a strong tendency towards chains of
268 // linked nodes with sequential numbers. By scanning the linked nodes
269 // backwards and forwards, we make it very likely that a single node can
270 // affect the entire network in a single iteration. That means very fast
271 // convergence, usually in a single iteration.
272 for (unsigned iteration = 0; iteration != 10; ++iteration) {
273 // Scan backwards, skipping the last node which was just updated.
274 bool Changed = false;
275 for (SmallVectorImpl<unsigned>::const_reverse_iterator I =
276 llvm::next(Linked.rbegin()), E = Linked.rend(); I != E; ++I) {
277 unsigned n = *I;
278 bool C = nodes[n].update(nodes);
279 Changed |= C;
280 DEBUG(dbgs() << " \\EB#" << n << format(" = %+2.0f", nodes[n].Value)
281 << (C ? " *\n" : "\n"));
282 }
283 if (!Changed)
284 return;
285
286 // Scan forwards, skipping the first node which was just updated.
287 Changed = false;
288 for (SmallVectorImpl<unsigned>::const_iterator I =
289 llvm::next(Linked.begin()), E = Linked.end(); I != E; ++I) {
290 unsigned n = *I;
291 bool C = nodes[n].update(nodes);
292 Changed |= C;
293 DEBUG(dbgs() << " /EB#" << n << format(" = %+2.0f", nodes[n].Value)
294 << (C ? " *\n" : "\n"));
295 }
296 if (!Changed)
297 return;
298 }
299}
300
301bool
302SpillPlacement::placeSpills(const SmallVectorImpl<BlockConstraint> &LiveBlocks,
303 BitVector &RegBundles) {
304 // Reuse RegBundles as our ActiveNodes vector.
305 ActiveNodes = &RegBundles;
306 ActiveNodes->clear();
307 ActiveNodes->resize(bundles->getNumBundles());
308
309 // Compute active nodes, links and biases.
310 prepareNodes(LiveBlocks);
311
312 // Update all active nodes, and find the ones that are actually linked to
313 // something so their value may change when iterating.
314 DEBUG(dbgs() << "Network has " << RegBundles.count() << " active nodes:\n");
315 SmallVector<unsigned, 8> Linked;
316 for (int n = RegBundles.find_first(); n>=0; n = RegBundles.find_next(n)) {
317 nodes[n].update(nodes);
318 // A node that must spill, or a node without any links is not going to
319 // change its value ever again, so exclude it from iterations.
320 if (!nodes[n].Links.empty() && !nodes[n].mustSpill())
321 Linked.push_back(n);
322
323 DEBUG({
324 dbgs() << " EB#" << n << format(" = %+2.0f", nodes[n].Value)
325 << format(", Bias %+.2f", nodes[n].Bias)
326 << format(", Freq %.1f/%.1f", nodes[n].Frequency[0],
327 nodes[n].Frequency[1]);
328 for (unsigned i = 0, e = nodes[n].Links.size(); i != e; ++i)
329 dbgs() << format(", %.2f -> EB#%u", nodes[n].Links[i].first,
330 nodes[n].Links[i].second);
331 dbgs() << '\n';
332 });
333 }
334
335 // Iterate the network to convergence.
336 iterate(Linked);
337
338 // Write preferences back to RegBundles.
339 bool Perfect = true;
340 for (int n = RegBundles.find_first(); n>=0; n = RegBundles.find_next(n))
341 if (!nodes[n].preferReg()) {
342 RegBundles.reset(n);
343 Perfect = false;
344 }
345 return Perfect;
346}
347
348/// getBlockFrequency - Return our best estimate of the block frequency which is
349/// the expected number of block executions per function invocation.
350float SpillPlacement::getBlockFrequency(const MachineBasicBlock *MBB) {
351 // Use the unnormalized spill weight for real block frequencies.
352 return LiveIntervals::getSpillWeight(true, false, loops->getLoopDepth(MBB));
353}
354