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 #define DEBUG_TYPE "spillplacement"
31 #include "SpillPlacement.h"
32 #include "llvm/ADT/BitVector.h"
33 #include "llvm/CodeGen/EdgeBundles.h"
34 #include "llvm/CodeGen/MachineBasicBlock.h"
35 #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
36 #include "llvm/CodeGen/MachineFunction.h"
37 #include "llvm/CodeGen/MachineLoopInfo.h"
38 #include "llvm/CodeGen/Passes.h"
39 #include "llvm/Support/Debug.h"
40 #include "llvm/Support/Format.h"
44 char SpillPlacement::ID = 0;
45 INITIALIZE_PASS_BEGIN(SpillPlacement, "spill-code-placement",
46 "Spill Code Placement Analysis", true, true)
47 INITIALIZE_PASS_DEPENDENCY(EdgeBundles)
48 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
49 INITIALIZE_PASS_END(SpillPlacement, "spill-code-placement",
50 "Spill Code Placement Analysis", true, true)
52 char &llvm::SpillPlacementID = SpillPlacement::ID;
54 void SpillPlacement::getAnalysisUsage(AnalysisUsage &AU) const {
56 AU.addRequired<MachineBlockFrequencyInfo>();
57 AU.addRequiredTransitive<EdgeBundles>();
58 AU.addRequiredTransitive<MachineLoopInfo>();
59 MachineFunctionPass::getAnalysisUsage(AU);
63 static BlockFrequency Threshold;
66 /// Decision threshold. A node gets the output value 0 if the weighted sum of
67 /// its inputs falls in the open interval (-Threshold;Threshold).
68 static BlockFrequency getThreshold() { return Threshold; }
70 /// \brief Set the threshold for a given entry frequency.
72 /// Set the threshold relative to \c Entry. Since the threshold is used as a
73 /// bound on the open interval (-Threshold;Threshold), 1 is the minimum
75 static void setThreshold(const BlockFrequency &Entry) {
76 // Apparently 2 is a good threshold when Entry==2^14, but we need to scale
77 // it. Divide by 2^13, rounding as appropriate.
78 uint64_t Freq = Entry.getFrequency();
79 uint64_t Scaled = (Freq >> 13) + bool(Freq & (1 << 12));
80 Threshold = std::max(UINT64_C(1), Scaled);
83 /// Node - Each edge bundle corresponds to a Hopfield node.
85 /// The node contains precomputed frequency data that only depends on the CFG,
86 /// but Bias and Links are computed each time placeSpills is called.
88 /// The node Value is positive when the variable should be in a register. The
89 /// value can change when linked nodes change, but convergence is very fast
90 /// because all weights are positive.
92 struct SpillPlacement::Node {
93 /// BiasN - Sum of blocks that prefer a spill.
95 /// BiasP - Sum of blocks that prefer a register.
98 /// Value - Output value of this node computed from the Bias and links.
99 /// This is always on of the values {-1, 0, 1}. A positive number means the
100 /// variable should go in a register through this bundle.
103 typedef SmallVector<std::pair<BlockFrequency, unsigned>, 4> LinkVector;
105 /// Links - (Weight, BundleNo) for all transparent blocks connecting to other
106 /// bundles. The weights are all positive block frequencies.
109 /// SumLinkWeights - Cached sum of the weights of all links + ThresHold.
110 BlockFrequency SumLinkWeights;
112 /// preferReg - Return true when this node prefers to be in a register.
113 bool preferReg() const {
114 // Undecided nodes (Value==0) go on the stack.
118 /// mustSpill - Return True if this node is so biased that it must spill.
119 bool mustSpill() const {
120 // We must spill if Bias < -sum(weights) or the MustSpill flag was set.
121 // BiasN is saturated when MustSpill is set, make sure this still returns
122 // true when the RHS saturates. Note that SumLinkWeights includes Threshold.
123 return BiasN >= BiasP + SumLinkWeights;
126 /// clear - Reset per-query data, but preserve frequencies that only depend on
129 BiasN = BiasP = Value = 0;
130 SumLinkWeights = getThreshold();
134 /// addLink - Add a link to bundle b with weight w.
135 void addLink(unsigned b, BlockFrequency w) {
136 // Update cached sum.
139 // There can be multiple links to the same bundle, add them up.
140 for (LinkVector::iterator I = Links.begin(), E = Links.end(); I != E; ++I)
141 if (I->second == b) {
145 // This must be the first link to b.
146 Links.push_back(std::make_pair(w, b));
149 /// addBias - Bias this node.
150 void addBias(BlockFrequency freq, BorderConstraint direction) {
161 BiasN = BlockFrequency::getMaxFrequency();
166 /// update - Recompute Value from Bias and Links. Return true when node
167 /// preference changes.
168 bool update(const Node nodes[]) {
169 // Compute the weighted sum of inputs.
170 BlockFrequency SumN = BiasN;
171 BlockFrequency SumP = BiasP;
172 for (LinkVector::iterator I = Links.begin(), E = Links.end(); I != E; ++I) {
173 if (nodes[I->second].Value == -1)
175 else if (nodes[I->second].Value == 1)
179 // Each weighted sum is going to be less than the total frequency of the
180 // bundle. Ideally, we should simply set Value = sign(SumP - SumN), but we
181 // will add a dead zone around 0 for two reasons:
183 // 1. It avoids arbitrary bias when all links are 0 as is possible during
184 // initial iterations.
185 // 2. It helps tame rounding errors when the links nominally sum to 0.
187 bool Before = preferReg();
188 if (SumN >= SumP + getThreshold())
190 else if (SumP >= SumN + getThreshold())
194 return Before != preferReg();
198 bool SpillPlacement::runOnMachineFunction(MachineFunction &mf) {
200 bundles = &getAnalysis<EdgeBundles>();
201 loops = &getAnalysis<MachineLoopInfo>();
203 assert(!nodes && "Leaking node array");
204 nodes = new Node[bundles->getNumBundles()];
206 // Compute total ingoing and outgoing block frequencies for all bundles.
207 BlockFrequencies.resize(mf.getNumBlockIDs());
208 MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
209 setThreshold(MBFI->getEntryFreq());
210 for (MachineFunction::iterator I = mf.begin(), E = mf.end(); I != E; ++I) {
211 unsigned Num = I->getNumber();
212 BlockFrequencies[Num] = MBFI->getBlockFreq(I);
215 // We never change the function.
219 void SpillPlacement::releaseMemory() {
224 /// activate - mark node n as active if it wasn't already.
225 void SpillPlacement::activate(unsigned n) {
226 if (ActiveNodes->test(n))
231 // Very large bundles usually come from big switches, indirect branches,
232 // landing pads, or loops with many 'continue' statements. It is difficult to
233 // allocate registers when so many different blocks are involved.
235 // Give a small negative bias to large bundles such that a substantial
236 // fraction of the connected blocks need to be interested before we consider
237 // expanding the region through the bundle. This helps compile time by
238 // limiting the number of blocks visited and the number of links in the
240 if (bundles->getBlocks(n).size() > 100) {
242 nodes[n].BiasN = (MBFI->getEntryFreq() / 16);
247 /// addConstraints - Compute node biases and weights from a set of constraints.
248 /// Set a bit in NodeMask for each active node.
249 void SpillPlacement::addConstraints(ArrayRef<BlockConstraint> LiveBlocks) {
250 for (ArrayRef<BlockConstraint>::iterator I = LiveBlocks.begin(),
251 E = LiveBlocks.end(); I != E; ++I) {
252 BlockFrequency Freq = BlockFrequencies[I->Number];
255 if (I->Entry != DontCare) {
256 unsigned ib = bundles->getBundle(I->Number, 0);
258 nodes[ib].addBias(Freq, I->Entry);
261 // Live-out from block?
262 if (I->Exit != DontCare) {
263 unsigned ob = bundles->getBundle(I->Number, 1);
265 nodes[ob].addBias(Freq, I->Exit);
270 /// addPrefSpill - Same as addConstraints(PrefSpill)
271 void SpillPlacement::addPrefSpill(ArrayRef<unsigned> Blocks, bool Strong) {
272 for (ArrayRef<unsigned>::iterator I = Blocks.begin(), E = Blocks.end();
274 BlockFrequency Freq = BlockFrequencies[*I];
277 unsigned ib = bundles->getBundle(*I, 0);
278 unsigned ob = bundles->getBundle(*I, 1);
281 nodes[ib].addBias(Freq, PrefSpill);
282 nodes[ob].addBias(Freq, PrefSpill);
286 void SpillPlacement::addLinks(ArrayRef<unsigned> Links) {
287 for (ArrayRef<unsigned>::iterator I = Links.begin(), E = Links.end(); I != E;
289 unsigned Number = *I;
290 unsigned ib = bundles->getBundle(Number, 0);
291 unsigned ob = bundles->getBundle(Number, 1);
293 // Ignore self-loops.
298 if (nodes[ib].Links.empty() && !nodes[ib].mustSpill())
299 Linked.push_back(ib);
300 if (nodes[ob].Links.empty() && !nodes[ob].mustSpill())
301 Linked.push_back(ob);
302 BlockFrequency Freq = BlockFrequencies[Number];
303 nodes[ib].addLink(ob, Freq);
304 nodes[ob].addLink(ib, Freq);
308 bool SpillPlacement::scanActiveBundles() {
310 RecentPositive.clear();
311 for (int n = ActiveNodes->find_first(); n>=0; n = ActiveNodes->find_next(n)) {
312 nodes[n].update(nodes);
313 // A node that must spill, or a node without any links is not going to
314 // change its value ever again, so exclude it from iterations.
315 if (nodes[n].mustSpill())
317 if (!nodes[n].Links.empty())
319 if (nodes[n].preferReg())
320 RecentPositive.push_back(n);
322 return !RecentPositive.empty();
325 /// iterate - Repeatedly update the Hopfield nodes until stability or the
326 /// maximum number of iterations is reached.
327 /// @param Linked - Numbers of linked nodes that need updating.
328 void SpillPlacement::iterate() {
329 // First update the recently positive nodes. They have likely received new
330 // negative bias that will turn them off.
331 while (!RecentPositive.empty())
332 nodes[RecentPositive.pop_back_val()].update(nodes);
337 // Run up to 10 iterations. The edge bundle numbering is closely related to
338 // basic block numbering, so there is a strong tendency towards chains of
339 // linked nodes with sequential numbers. By scanning the linked nodes
340 // backwards and forwards, we make it very likely that a single node can
341 // affect the entire network in a single iteration. That means very fast
342 // convergence, usually in a single iteration.
343 for (unsigned iteration = 0; iteration != 10; ++iteration) {
344 // Scan backwards, skipping the last node when iteration is not zero. When
345 // iteration is not zero, the last node was just updated.
346 bool Changed = false;
347 for (SmallVectorImpl<unsigned>::const_reverse_iterator I =
348 iteration == 0 ? Linked.rbegin() : std::next(Linked.rbegin()),
349 E = Linked.rend(); I != E; ++I) {
351 if (nodes[n].update(nodes)) {
353 if (nodes[n].preferReg())
354 RecentPositive.push_back(n);
357 if (!Changed || !RecentPositive.empty())
360 // Scan forwards, skipping the first node which was just updated.
362 for (SmallVectorImpl<unsigned>::const_iterator I =
363 std::next(Linked.begin()), E = Linked.end(); I != E; ++I) {
365 if (nodes[n].update(nodes)) {
367 if (nodes[n].preferReg())
368 RecentPositive.push_back(n);
371 if (!Changed || !RecentPositive.empty())
376 void SpillPlacement::prepare(BitVector &RegBundles) {
378 RecentPositive.clear();
379 // Reuse RegBundles as our ActiveNodes vector.
380 ActiveNodes = &RegBundles;
381 ActiveNodes->clear();
382 ActiveNodes->resize(bundles->getNumBundles());
386 SpillPlacement::finish() {
387 assert(ActiveNodes && "Call prepare() first");
389 // Write preferences back to ActiveNodes.
391 for (int n = ActiveNodes->find_first(); n>=0; n = ActiveNodes->find_next(n))
392 if (!nodes[n].preferReg()) {
393 ActiveNodes->reset(n);