blob: adab2b01d8000a8d0a86df6db951aba6c4c2c0cd [file] [log] [blame]
Evan Chengb1290a62008-10-02 18:29:27 +00001//===------ RegAllocPBQP.cpp ---- PBQP Register Allocator -------*- C++ -*-===//
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//===----------------------------------------------------------------------===//
Misha Brukman2a835f92009-01-08 15:50:22 +00009//
Evan Chengb1290a62008-10-02 18:29:27 +000010// This file contains a Partitioned Boolean Quadratic Programming (PBQP) based
11// register allocator for LLVM. This allocator works by constructing a PBQP
12// problem representing the register allocation problem under consideration,
13// solving this using a PBQP solver, and mapping the solution back to a
14// register assignment. If any variables are selected for spilling then spill
Misha Brukman2a835f92009-01-08 15:50:22 +000015// code is inserted and the process repeated.
Evan Chengb1290a62008-10-02 18:29:27 +000016//
17// The PBQP solver (pbqp.c) provided for this allocator uses a heuristic tuned
18// for register allocation. For more information on PBQP for register
Misha Brukmance07e992009-01-08 16:40:25 +000019// allocation, see the following papers:
Evan Chengb1290a62008-10-02 18:29:27 +000020//
21// (1) Hames, L. and Scholz, B. 2006. Nearly optimal register allocation with
22// PBQP. In Proceedings of the 7th Joint Modular Languages Conference
23// (JMLC'06). LNCS, vol. 4228. Springer, New York, NY, USA. 346-361.
24//
25// (2) Scholz, B., Eckstein, E. 2002. Register allocation for irregular
26// architectures. In Proceedings of the Joint Conference on Languages,
27// Compilers and Tools for Embedded Systems (LCTES'02), ACM Press, New York,
28// NY, USA, 139-148.
Misha Brukman2a835f92009-01-08 15:50:22 +000029//
Evan Chengb1290a62008-10-02 18:29:27 +000030//===----------------------------------------------------------------------===//
31
Evan Chengb1290a62008-10-02 18:29:27 +000032#define DEBUG_TYPE "regalloc"
33
34#include "PBQP.h"
35#include "VirtRegMap.h"
Owen Anderson1ed5b712009-03-11 22:31:21 +000036#include "Spiller.h"
Evan Chengb1290a62008-10-02 18:29:27 +000037#include "llvm/CodeGen/LiveIntervalAnalysis.h"
Lang Hames27601ef2008-11-16 12:12:54 +000038#include "llvm/CodeGen/LiveStackAnalysis.h"
Misha Brukman2a835f92009-01-08 15:50:22 +000039#include "llvm/CodeGen/MachineFunctionPass.h"
Evan Chengb1290a62008-10-02 18:29:27 +000040#include "llvm/CodeGen/MachineLoopInfo.h"
Misha Brukman2a835f92009-01-08 15:50:22 +000041#include "llvm/CodeGen/MachineRegisterInfo.h"
42#include "llvm/CodeGen/RegAllocRegistry.h"
43#include "llvm/CodeGen/RegisterCoalescer.h"
Evan Chengb1290a62008-10-02 18:29:27 +000044#include "llvm/Support/Debug.h"
Misha Brukman2a835f92009-01-08 15:50:22 +000045#include "llvm/Target/TargetInstrInfo.h"
46#include "llvm/Target/TargetMachine.h"
47#include <limits>
Evan Chengb1290a62008-10-02 18:29:27 +000048#include <map>
Misha Brukman2a835f92009-01-08 15:50:22 +000049#include <memory>
Evan Chengb1290a62008-10-02 18:29:27 +000050#include <set>
51#include <vector>
Evan Chengb1290a62008-10-02 18:29:27 +000052
53using namespace llvm;
54
55static RegisterRegAlloc
Dan Gohmanb8cab922008-10-14 20:25:08 +000056registerPBQPRepAlloc("pbqp", "PBQP register allocator",
Evan Chengb1290a62008-10-02 18:29:27 +000057 createPBQPRegisterAllocator);
58
Evan Chengb1290a62008-10-02 18:29:27 +000059namespace {
60
61 //!
62 //! PBQP based allocators solve the register allocation problem by mapping
63 //! register allocation problems to Partitioned Boolean Quadratic
64 //! Programming problems.
65 class VISIBILITY_HIDDEN PBQPRegAlloc : public MachineFunctionPass {
66 public:
67
68 static char ID;
Misha Brukman2a835f92009-01-08 15:50:22 +000069
Evan Chengb1290a62008-10-02 18:29:27 +000070 //! Construct a PBQP register allocator.
71 PBQPRegAlloc() : MachineFunctionPass((intptr_t)&ID) {}
72
73 //! Return the pass name.
74 virtual const char* getPassName() const throw() {
75 return "PBQP Register Allocator";
76 }
77
78 //! PBQP analysis usage.
79 virtual void getAnalysisUsage(AnalysisUsage &au) const {
80 au.addRequired<LiveIntervals>();
Lang Hames27601ef2008-11-16 12:12:54 +000081 au.addRequiredTransitive<RegisterCoalescer>();
82 au.addRequired<LiveStacks>();
83 au.addPreserved<LiveStacks>();
Evan Chengb1290a62008-10-02 18:29:27 +000084 au.addRequired<MachineLoopInfo>();
Lang Hames27601ef2008-11-16 12:12:54 +000085 au.addPreserved<MachineLoopInfo>();
Sanjiv Gupta12a9dc82009-03-17 15:46:15 +000086 au.addRequired<VirtRegMap>();
Evan Chengb1290a62008-10-02 18:29:27 +000087 MachineFunctionPass::getAnalysisUsage(au);
88 }
89
90 //! Perform register allocation
91 virtual bool runOnMachineFunction(MachineFunction &MF);
92
93 private:
94 typedef std::map<const LiveInterval*, unsigned> LI2NodeMap;
95 typedef std::vector<const LiveInterval*> Node2LIMap;
96 typedef std::vector<unsigned> AllowedSet;
97 typedef std::vector<AllowedSet> AllowedSetMap;
Lang Hames27601ef2008-11-16 12:12:54 +000098 typedef std::set<unsigned> RegSet;
99 typedef std::pair<unsigned, unsigned> RegPair;
100 typedef std::map<RegPair, PBQPNum> CoalesceMap;
101
102 typedef std::set<LiveInterval*> LiveIntervalSet;
Evan Chengb1290a62008-10-02 18:29:27 +0000103
104 MachineFunction *mf;
105 const TargetMachine *tm;
106 const TargetRegisterInfo *tri;
107 const TargetInstrInfo *tii;
108 const MachineLoopInfo *loopInfo;
109 MachineRegisterInfo *mri;
110
Lang Hames27601ef2008-11-16 12:12:54 +0000111 LiveIntervals *lis;
112 LiveStacks *lss;
Evan Chengb1290a62008-10-02 18:29:27 +0000113 VirtRegMap *vrm;
114
115 LI2NodeMap li2Node;
116 Node2LIMap node2LI;
117 AllowedSetMap allowedSets;
Lang Hames27601ef2008-11-16 12:12:54 +0000118 LiveIntervalSet vregIntervalsToAlloc,
119 emptyVRegIntervals;
Evan Chengb1290a62008-10-02 18:29:27 +0000120
Misha Brukman2a835f92009-01-08 15:50:22 +0000121
Evan Chengb1290a62008-10-02 18:29:27 +0000122 //! Builds a PBQP cost vector.
Lang Hames27601ef2008-11-16 12:12:54 +0000123 template <typename RegContainer>
124 PBQPVector* buildCostVector(unsigned vReg,
125 const RegContainer &allowed,
126 const CoalesceMap &cealesces,
Evan Chengb1290a62008-10-02 18:29:27 +0000127 PBQPNum spillCost) const;
128
Evan Cheng17a82ea2008-10-03 17:11:58 +0000129 //! \brief Builds a PBQP interference matrix.
Evan Chengb1290a62008-10-02 18:29:27 +0000130 //!
131 //! @return Either a pointer to a non-zero PBQP matrix representing the
132 //! allocation option costs, or a null pointer for a zero matrix.
133 //!
134 //! Expects allowed sets for two interfering LiveIntervals. These allowed
135 //! sets should contain only allocable registers from the LiveInterval's
136 //! register class, with any interfering pre-colored registers removed.
Lang Hames27601ef2008-11-16 12:12:54 +0000137 template <typename RegContainer>
138 PBQPMatrix* buildInterferenceMatrix(const RegContainer &allowed1,
139 const RegContainer &allowed2) const;
Evan Chengb1290a62008-10-02 18:29:27 +0000140
141 //!
142 //! Expects allowed sets for two potentially coalescable LiveIntervals,
143 //! and an estimated benefit due to coalescing. The allowed sets should
144 //! contain only allocable registers from the LiveInterval's register
145 //! classes, with any interfering pre-colored registers removed.
Lang Hames27601ef2008-11-16 12:12:54 +0000146 template <typename RegContainer>
147 PBQPMatrix* buildCoalescingMatrix(const RegContainer &allowed1,
148 const RegContainer &allowed2,
Evan Chengb1290a62008-10-02 18:29:27 +0000149 PBQPNum cBenefit) const;
150
Lang Hames27601ef2008-11-16 12:12:54 +0000151 //! \brief Finds coalescing opportunities and returns them as a map.
Evan Chengb1290a62008-10-02 18:29:27 +0000152 //!
Lang Hames27601ef2008-11-16 12:12:54 +0000153 //! Any entries in the map are guaranteed coalescable, even if their
154 //! corresponding live intervals overlap.
155 CoalesceMap findCoalesces();
Evan Chengb1290a62008-10-02 18:29:27 +0000156
Lang Hames27601ef2008-11-16 12:12:54 +0000157 //! \brief Finds the initial set of vreg intervals to allocate.
158 void findVRegIntervalsToAlloc();
Evan Chengb1290a62008-10-02 18:29:27 +0000159
160 //! \brief Constructs a PBQP problem representation of the register
161 //! allocation problem for this function.
162 //!
163 //! @return a PBQP solver object for the register allocation problem.
164 pbqp* constructPBQPProblem();
165
Lang Hames27601ef2008-11-16 12:12:54 +0000166 //! \brief Adds a stack interval if the given live interval has been
167 //! spilled. Used to support stack slot coloring.
168 void addStackInterval(const LiveInterval *spilled, float &weight);
169
Evan Chengb1290a62008-10-02 18:29:27 +0000170 //! \brief Given a solved PBQP problem maps this solution back to a register
171 //! assignment.
Misha Brukman2a835f92009-01-08 15:50:22 +0000172 bool mapPBQPToRegAlloc(pbqp *problem);
Evan Chengb1290a62008-10-02 18:29:27 +0000173
Lang Hames27601ef2008-11-16 12:12:54 +0000174 //! \brief Postprocessing before final spilling. Sets basic block "live in"
175 //! variables.
176 void finalizeAlloc() const;
177
Evan Chengb1290a62008-10-02 18:29:27 +0000178 };
179
180 char PBQPRegAlloc::ID = 0;
181}
182
183
Lang Hames27601ef2008-11-16 12:12:54 +0000184template <typename RegContainer>
185PBQPVector* PBQPRegAlloc::buildCostVector(unsigned vReg,
186 const RegContainer &allowed,
187 const CoalesceMap &coalesces,
Evan Chengb1290a62008-10-02 18:29:27 +0000188 PBQPNum spillCost) const {
189
Lang Hames27601ef2008-11-16 12:12:54 +0000190 typedef typename RegContainer::const_iterator AllowedItr;
191
Evan Chengb1290a62008-10-02 18:29:27 +0000192 // Allocate vector. Additional element (0th) used for spill option
193 PBQPVector *v = new PBQPVector(allowed.size() + 1);
194
195 (*v)[0] = spillCost;
196
Lang Hames27601ef2008-11-16 12:12:54 +0000197 // Iterate over the allowed registers inserting coalesce benefits if there
198 // are any.
199 unsigned ai = 0;
200 for (AllowedItr itr = allowed.begin(), end = allowed.end();
201 itr != end; ++itr, ++ai) {
202
203 unsigned pReg = *itr;
204
205 CoalesceMap::const_iterator cmItr =
206 coalesces.find(RegPair(vReg, pReg));
207
208 // No coalesce - on to the next preg.
209 if (cmItr == coalesces.end())
210 continue;
Misha Brukman2a835f92009-01-08 15:50:22 +0000211
212 // We have a coalesce - insert the benefit.
213 (*v)[ai + 1] = -cmItr->second;
Lang Hames27601ef2008-11-16 12:12:54 +0000214 }
215
Evan Chengb1290a62008-10-02 18:29:27 +0000216 return v;
217}
218
Lang Hames27601ef2008-11-16 12:12:54 +0000219template <typename RegContainer>
Evan Chengb1290a62008-10-02 18:29:27 +0000220PBQPMatrix* PBQPRegAlloc::buildInterferenceMatrix(
Lang Hames27601ef2008-11-16 12:12:54 +0000221 const RegContainer &allowed1, const RegContainer &allowed2) const {
Evan Chengb1290a62008-10-02 18:29:27 +0000222
Lang Hames27601ef2008-11-16 12:12:54 +0000223 typedef typename RegContainer::const_iterator RegContainerIterator;
Evan Chengb1290a62008-10-02 18:29:27 +0000224
225 // Construct a PBQP matrix representing the cost of allocation options. The
226 // rows and columns correspond to the allocation options for the two live
227 // intervals. Elements will be infinite where corresponding registers alias,
228 // since we cannot allocate aliasing registers to interfering live intervals.
229 // All other elements (non-aliasing combinations) will have zero cost. Note
230 // that the spill option (element 0,0) has zero cost, since we can allocate
231 // both intervals to memory safely (the cost for each individual allocation
232 // to memory is accounted for by the cost vectors for each live interval).
233 PBQPMatrix *m = new PBQPMatrix(allowed1.size() + 1, allowed2.size() + 1);
Misha Brukman2a835f92009-01-08 15:50:22 +0000234
Evan Chengb1290a62008-10-02 18:29:27 +0000235 // Assume this is a zero matrix until proven otherwise. Zero matrices occur
236 // between interfering live ranges with non-overlapping register sets (e.g.
237 // non-overlapping reg classes, or disjoint sets of allowed regs within the
238 // same class). The term "overlapping" is used advisedly: sets which do not
239 // intersect, but contain registers which alias, will have non-zero matrices.
240 // We optimize zero matrices away to improve solver speed.
241 bool isZeroMatrix = true;
242
243
244 // Row index. Starts at 1, since the 0th row is for the spill option, which
245 // is always zero.
Misha Brukman2a835f92009-01-08 15:50:22 +0000246 unsigned ri = 1;
Evan Chengb1290a62008-10-02 18:29:27 +0000247
Misha Brukman2a835f92009-01-08 15:50:22 +0000248 // Iterate over allowed sets, insert infinities where required.
Lang Hames27601ef2008-11-16 12:12:54 +0000249 for (RegContainerIterator a1Itr = allowed1.begin(), a1End = allowed1.end();
Evan Chengb1290a62008-10-02 18:29:27 +0000250 a1Itr != a1End; ++a1Itr) {
251
252 // Column index, starts at 1 as for row index.
253 unsigned ci = 1;
254 unsigned reg1 = *a1Itr;
255
Lang Hames27601ef2008-11-16 12:12:54 +0000256 for (RegContainerIterator a2Itr = allowed2.begin(), a2End = allowed2.end();
Evan Chengb1290a62008-10-02 18:29:27 +0000257 a2Itr != a2End; ++a2Itr) {
258
259 unsigned reg2 = *a2Itr;
260
261 // If the row/column regs are identical or alias insert an infinity.
262 if ((reg1 == reg2) || tri->areAliases(reg1, reg2)) {
263 (*m)[ri][ci] = std::numeric_limits<PBQPNum>::infinity();
264 isZeroMatrix = false;
265 }
266
267 ++ci;
268 }
269
270 ++ri;
271 }
272
273 // If this turns out to be a zero matrix...
274 if (isZeroMatrix) {
275 // free it and return null.
276 delete m;
277 return 0;
278 }
279
280 // ...otherwise return the cost matrix.
281 return m;
282}
283
Lang Hames27601ef2008-11-16 12:12:54 +0000284template <typename RegContainer>
285PBQPMatrix* PBQPRegAlloc::buildCoalescingMatrix(
286 const RegContainer &allowed1, const RegContainer &allowed2,
287 PBQPNum cBenefit) const {
Evan Chengb1290a62008-10-02 18:29:27 +0000288
Lang Hames27601ef2008-11-16 12:12:54 +0000289 typedef typename RegContainer::const_iterator RegContainerIterator;
290
291 // Construct a PBQP Matrix representing the benefits of coalescing. As with
292 // interference matrices the rows and columns represent allowed registers
293 // for the LiveIntervals which are (potentially) to be coalesced. The amount
294 // -cBenefit will be placed in any element representing the same register
295 // for both intervals.
296 PBQPMatrix *m = new PBQPMatrix(allowed1.size() + 1, allowed2.size() + 1);
297
298 // Reset costs to zero.
299 m->reset(0);
300
301 // Assume the matrix is zero till proven otherwise. Zero matrices will be
302 // optimized away as in the interference case.
303 bool isZeroMatrix = true;
304
305 // Row index. Starts at 1, since the 0th row is for the spill option, which
306 // is always zero.
307 unsigned ri = 1;
308
309 // Iterate over the allowed sets, insert coalescing benefits where
310 // appropriate.
311 for (RegContainerIterator a1Itr = allowed1.begin(), a1End = allowed1.end();
312 a1Itr != a1End; ++a1Itr) {
313
314 // Column index, starts at 1 as for row index.
315 unsigned ci = 1;
316 unsigned reg1 = *a1Itr;
317
318 for (RegContainerIterator a2Itr = allowed2.begin(), a2End = allowed2.end();
319 a2Itr != a2End; ++a2Itr) {
320
321 // If the row and column represent the same register insert a beneficial
322 // cost to preference this allocation - it would allow us to eliminate a
Misha Brukman2a835f92009-01-08 15:50:22 +0000323 // move instruction.
Lang Hames27601ef2008-11-16 12:12:54 +0000324 if (reg1 == *a2Itr) {
325 (*m)[ri][ci] = -cBenefit;
326 isZeroMatrix = false;
327 }
328
329 ++ci;
330 }
331
332 ++ri;
333 }
334
335 // If this turns out to be a zero matrix...
336 if (isZeroMatrix) {
337 // ...free it and return null.
338 delete m;
339 return 0;
340 }
341
342 return m;
343}
344
345PBQPRegAlloc::CoalesceMap PBQPRegAlloc::findCoalesces() {
346
347 typedef MachineFunction::const_iterator MFIterator;
348 typedef MachineBasicBlock::const_iterator MBBIterator;
349 typedef LiveInterval::const_vni_iterator VNIIterator;
Misha Brukman2a835f92009-01-08 15:50:22 +0000350
Lang Hames27601ef2008-11-16 12:12:54 +0000351 CoalesceMap coalescesFound;
352
353 // To find coalesces we need to iterate over the function looking for
354 // copy instructions.
355 for (MFIterator bbItr = mf->begin(), bbEnd = mf->end();
Evan Chengb1290a62008-10-02 18:29:27 +0000356 bbItr != bbEnd; ++bbItr) {
357
358 const MachineBasicBlock *mbb = &*bbItr;
Evan Chengb1290a62008-10-02 18:29:27 +0000359
Lang Hames27601ef2008-11-16 12:12:54 +0000360 for (MBBIterator iItr = mbb->begin(), iEnd = mbb->end();
361 iItr != iEnd; ++iItr) {
Evan Chengb1290a62008-10-02 18:29:27 +0000362
363 const MachineInstr *instr = &*iItr;
Evan Cheng04ee5a12009-01-20 19:12:24 +0000364 unsigned srcReg, dstReg, srcSubReg, dstSubReg;
Evan Chengb1290a62008-10-02 18:29:27 +0000365
Lang Hames27601ef2008-11-16 12:12:54 +0000366 // If this isn't a copy then continue to the next instruction.
Evan Cheng04ee5a12009-01-20 19:12:24 +0000367 if (!tii->isMoveInstr(*instr, srcReg, dstReg, srcSubReg, dstSubReg))
Lang Hames27601ef2008-11-16 12:12:54 +0000368 continue;
Evan Chengb1290a62008-10-02 18:29:27 +0000369
Lang Hames27601ef2008-11-16 12:12:54 +0000370 // If the registers are already the same our job is nice and easy.
371 if (dstReg == srcReg)
372 continue;
Evan Chengb1290a62008-10-02 18:29:27 +0000373
Lang Hames27601ef2008-11-16 12:12:54 +0000374 bool srcRegIsPhysical = TargetRegisterInfo::isPhysicalRegister(srcReg),
375 dstRegIsPhysical = TargetRegisterInfo::isPhysicalRegister(dstReg);
376
377 // If both registers are physical then we can't coalesce.
378 if (srcRegIsPhysical && dstRegIsPhysical)
379 continue;
Misha Brukman2a835f92009-01-08 15:50:22 +0000380
Lang Hames27601ef2008-11-16 12:12:54 +0000381 // If it's a copy that includes a virtual register but the source and
382 // destination classes differ then we can't coalesce, so continue with
383 // the next instruction.
384 const TargetRegisterClass *srcRegClass = srcRegIsPhysical ?
385 tri->getPhysicalRegisterRegClass(srcReg) : mri->getRegClass(srcReg);
386
387 const TargetRegisterClass *dstRegClass = dstRegIsPhysical ?
388 tri->getPhysicalRegisterRegClass(dstReg) : mri->getRegClass(dstReg);
389
390 if (srcRegClass != dstRegClass)
391 continue;
392
393 // We also need any physical regs to be allocable, coalescing with
394 // a non-allocable register is invalid.
395 if (srcRegIsPhysical) {
396 if (std::find(srcRegClass->allocation_order_begin(*mf),
397 srcRegClass->allocation_order_end(*mf), srcReg) ==
398 srcRegClass->allocation_order_end(*mf))
Evan Chengb1290a62008-10-02 18:29:27 +0000399 continue;
Evan Chengb1290a62008-10-02 18:29:27 +0000400 }
401
Lang Hames27601ef2008-11-16 12:12:54 +0000402 if (dstRegIsPhysical) {
403 if (std::find(dstRegClass->allocation_order_begin(*mf),
404 dstRegClass->allocation_order_end(*mf), dstReg) ==
405 dstRegClass->allocation_order_end(*mf))
406 continue;
407 }
408
409 // If we've made it here we have a copy with compatible register classes.
Misha Brukman2a835f92009-01-08 15:50:22 +0000410 // We can probably coalesce, but we need to consider overlap.
Lang Hames27601ef2008-11-16 12:12:54 +0000411 const LiveInterval *srcLI = &lis->getInterval(srcReg),
412 *dstLI = &lis->getInterval(dstReg);
413
414 if (srcLI->overlaps(*dstLI)) {
415 // Even in the case of an overlap we might still be able to coalesce,
416 // but we need to make sure that no definition of either range occurs
417 // while the other range is live.
418
419 // Otherwise start by assuming we're ok.
420 bool badDef = false;
421
422 // Test all defs of the source range.
Misha Brukman2a835f92009-01-08 15:50:22 +0000423 for (VNIIterator
Lang Hames27601ef2008-11-16 12:12:54 +0000424 vniItr = srcLI->vni_begin(), vniEnd = srcLI->vni_end();
425 vniItr != vniEnd; ++vniItr) {
426
427 // If we find a def that kills the coalescing opportunity then
428 // record it and break from the loop.
429 if (dstLI->liveAt((*vniItr)->def)) {
430 badDef = true;
431 break;
432 }
433 }
434
435 // If we have a bad def give up, continue to the next instruction.
436 if (badDef)
437 continue;
Misha Brukman2a835f92009-01-08 15:50:22 +0000438
Lang Hames27601ef2008-11-16 12:12:54 +0000439 // Otherwise test definitions of the destination range.
440 for (VNIIterator
441 vniItr = dstLI->vni_begin(), vniEnd = dstLI->vni_end();
442 vniItr != vniEnd; ++vniItr) {
Misha Brukman2a835f92009-01-08 15:50:22 +0000443
Lang Hames27601ef2008-11-16 12:12:54 +0000444 // We want to make sure we skip the copy instruction itself.
445 if ((*vniItr)->copy == instr)
446 continue;
447
448 if (srcLI->liveAt((*vniItr)->def)) {
449 badDef = true;
450 break;
451 }
452 }
Misha Brukman2a835f92009-01-08 15:50:22 +0000453
Lang Hames27601ef2008-11-16 12:12:54 +0000454 // As before a bad def we give up and continue to the next instr.
455 if (badDef)
456 continue;
457 }
458
459 // If we make it to here then either the ranges didn't overlap, or they
460 // did, but none of their definitions would prevent us from coalescing.
461 // We're good to go with the coalesce.
462
463 float cBenefit = powf(10.0f, loopInfo->getLoopDepth(mbb)) / 5.0;
Misha Brukman2a835f92009-01-08 15:50:22 +0000464
Lang Hames27601ef2008-11-16 12:12:54 +0000465 coalescesFound[RegPair(srcReg, dstReg)] = cBenefit;
466 coalescesFound[RegPair(dstReg, srcReg)] = cBenefit;
Evan Chengb1290a62008-10-02 18:29:27 +0000467 }
468
469 }
470
Lang Hames27601ef2008-11-16 12:12:54 +0000471 return coalescesFound;
472}
473
474void PBQPRegAlloc::findVRegIntervalsToAlloc() {
475
476 // Iterate over all live ranges.
477 for (LiveIntervals::iterator itr = lis->begin(), end = lis->end();
478 itr != end; ++itr) {
479
480 // Ignore physical ones.
481 if (TargetRegisterInfo::isPhysicalRegister(itr->first))
482 continue;
483
484 LiveInterval *li = itr->second;
485
486 // If this live interval is non-empty we will use pbqp to allocate it.
487 // Empty intervals we allocate in a simple post-processing stage in
488 // finalizeAlloc.
489 if (!li->empty()) {
490 vregIntervalsToAlloc.insert(li);
491 }
492 else {
493 emptyVRegIntervals.insert(li);
494 }
495 }
Evan Chengb1290a62008-10-02 18:29:27 +0000496}
497
498pbqp* PBQPRegAlloc::constructPBQPProblem() {
499
500 typedef std::vector<const LiveInterval*> LIVector;
Lang Hames27601ef2008-11-16 12:12:54 +0000501 typedef std::vector<unsigned> RegVector;
Evan Chengb1290a62008-10-02 18:29:27 +0000502
Lang Hames27601ef2008-11-16 12:12:54 +0000503 // This will store the physical intervals for easy reference.
504 LIVector physIntervals;
Evan Chengb1290a62008-10-02 18:29:27 +0000505
506 // Start by clearing the old node <-> live interval mappings & allowed sets
507 li2Node.clear();
508 node2LI.clear();
509 allowedSets.clear();
510
Lang Hames27601ef2008-11-16 12:12:54 +0000511 // Populate physIntervals, update preg use:
512 for (LiveIntervals::iterator itr = lis->begin(), end = lis->end();
Evan Chengb1290a62008-10-02 18:29:27 +0000513 itr != end; ++itr) {
514
Evan Chengb1290a62008-10-02 18:29:27 +0000515 if (TargetRegisterInfo::isPhysicalRegister(itr->first)) {
516 physIntervals.push_back(itr->second);
517 mri->setPhysRegUsed(itr->second->reg);
518 }
Evan Chengb1290a62008-10-02 18:29:27 +0000519 }
520
Lang Hames27601ef2008-11-16 12:12:54 +0000521 // Iterate over vreg intervals, construct live interval <-> node number
522 // mappings.
Misha Brukman2a835f92009-01-08 15:50:22 +0000523 for (LiveIntervalSet::const_iterator
Lang Hames27601ef2008-11-16 12:12:54 +0000524 itr = vregIntervalsToAlloc.begin(), end = vregIntervalsToAlloc.end();
525 itr != end; ++itr) {
526 const LiveInterval *li = *itr;
527
528 li2Node[li] = node2LI.size();
529 node2LI.push_back(li);
530 }
531
532 // Get the set of potential coalesces.
533 CoalesceMap coalesces(findCoalesces());
Evan Chengb1290a62008-10-02 18:29:27 +0000534
535 // Construct a PBQP solver for this problem
Lang Hames27601ef2008-11-16 12:12:54 +0000536 pbqp *solver = alloc_pbqp(vregIntervalsToAlloc.size());
Evan Chengb1290a62008-10-02 18:29:27 +0000537
538 // Resize allowedSets container appropriately.
Lang Hames27601ef2008-11-16 12:12:54 +0000539 allowedSets.resize(vregIntervalsToAlloc.size());
Evan Chengb1290a62008-10-02 18:29:27 +0000540
541 // Iterate over virtual register intervals to compute allowed sets...
542 for (unsigned node = 0; node < node2LI.size(); ++node) {
543
544 // Grab pointers to the interval and its register class.
545 const LiveInterval *li = node2LI[node];
546 const TargetRegisterClass *liRC = mri->getRegClass(li->reg);
Misha Brukman2a835f92009-01-08 15:50:22 +0000547
Evan Chengb1290a62008-10-02 18:29:27 +0000548 // Start by assuming all allocable registers in the class are allowed...
Lang Hames27601ef2008-11-16 12:12:54 +0000549 RegVector liAllowed(liRC->allocation_order_begin(*mf),
550 liRC->allocation_order_end(*mf));
Evan Chengb1290a62008-10-02 18:29:27 +0000551
Lang Hames27601ef2008-11-16 12:12:54 +0000552 // Eliminate the physical registers which overlap with this range, along
553 // with all their aliases.
554 for (LIVector::iterator pItr = physIntervals.begin(),
555 pEnd = physIntervals.end(); pItr != pEnd; ++pItr) {
Evan Chengb1290a62008-10-02 18:29:27 +0000556
Lang Hames27601ef2008-11-16 12:12:54 +0000557 if (!li->overlaps(**pItr))
558 continue;
Evan Chengb1290a62008-10-02 18:29:27 +0000559
Lang Hames27601ef2008-11-16 12:12:54 +0000560 unsigned pReg = (*pItr)->reg;
Evan Chengb1290a62008-10-02 18:29:27 +0000561
Lang Hames27601ef2008-11-16 12:12:54 +0000562 // If we get here then the live intervals overlap, but we're still ok
563 // if they're coalescable.
564 if (coalesces.find(RegPair(li->reg, pReg)) != coalesces.end())
565 continue;
Evan Chengb1290a62008-10-02 18:29:27 +0000566
Lang Hames27601ef2008-11-16 12:12:54 +0000567 // If we get here then we have a genuine exclusion.
Evan Chengb1290a62008-10-02 18:29:27 +0000568
Lang Hames27601ef2008-11-16 12:12:54 +0000569 // Remove the overlapping reg...
570 RegVector::iterator eraseItr =
571 std::find(liAllowed.begin(), liAllowed.end(), pReg);
Misha Brukman2a835f92009-01-08 15:50:22 +0000572
Lang Hames27601ef2008-11-16 12:12:54 +0000573 if (eraseItr != liAllowed.end())
574 liAllowed.erase(eraseItr);
Evan Chengb1290a62008-10-02 18:29:27 +0000575
Lang Hames27601ef2008-11-16 12:12:54 +0000576 const unsigned *aliasItr = tri->getAliasSet(pReg);
577
578 if (aliasItr != 0) {
579 // ...and its aliases.
580 for (; *aliasItr != 0; ++aliasItr) {
581 RegVector::iterator eraseItr =
582 std::find(liAllowed.begin(), liAllowed.end(), *aliasItr);
Misha Brukman2a835f92009-01-08 15:50:22 +0000583
Lang Hames27601ef2008-11-16 12:12:54 +0000584 if (eraseItr != liAllowed.end()) {
585 liAllowed.erase(eraseItr);
Evan Chengb1290a62008-10-02 18:29:27 +0000586 }
Evan Chengb1290a62008-10-02 18:29:27 +0000587 }
Evan Chengb1290a62008-10-02 18:29:27 +0000588 }
Evan Chengb1290a62008-10-02 18:29:27 +0000589 }
590
591 // Copy the allowed set into a member vector for use when constructing cost
592 // vectors & matrices, and mapping PBQP solutions back to assignments.
593 allowedSets[node] = AllowedSet(liAllowed.begin(), liAllowed.end());
594
595 // Set the spill cost to the interval weight, or epsilon if the
596 // interval weight is zero
Misha Brukman2a835f92009-01-08 15:50:22 +0000597 PBQPNum spillCost = (li->weight != 0.0) ?
Evan Chengb1290a62008-10-02 18:29:27 +0000598 li->weight : std::numeric_limits<PBQPNum>::min();
599
600 // Build a cost vector for this interval.
601 add_pbqp_nodecosts(solver, node,
Lang Hames27601ef2008-11-16 12:12:54 +0000602 buildCostVector(li->reg, allowedSets[node], coalesces,
603 spillCost));
Evan Chengb1290a62008-10-02 18:29:27 +0000604
605 }
606
Lang Hames27601ef2008-11-16 12:12:54 +0000607
Evan Chengb1290a62008-10-02 18:29:27 +0000608 // Now add the cost matrices...
609 for (unsigned node1 = 0; node1 < node2LI.size(); ++node1) {
Evan Chengb1290a62008-10-02 18:29:27 +0000610 const LiveInterval *li = node2LI[node1];
611
Evan Chengb1290a62008-10-02 18:29:27 +0000612 // Test for live range overlaps and insert interference matrices.
613 for (unsigned node2 = node1 + 1; node2 < node2LI.size(); ++node2) {
614 const LiveInterval *li2 = node2LI[node2];
615
Lang Hames27601ef2008-11-16 12:12:54 +0000616 CoalesceMap::const_iterator cmItr =
617 coalesces.find(RegPair(li->reg, li2->reg));
Evan Chengb1290a62008-10-02 18:29:27 +0000618
Lang Hames27601ef2008-11-16 12:12:54 +0000619 PBQPMatrix *m = 0;
Evan Chengb1290a62008-10-02 18:29:27 +0000620
Lang Hames27601ef2008-11-16 12:12:54 +0000621 if (cmItr != coalesces.end()) {
622 m = buildCoalescingMatrix(allowedSets[node1], allowedSets[node2],
623 cmItr->second);
624 }
625 else if (li->overlaps(*li2)) {
626 m = buildInterferenceMatrix(allowedSets[node1], allowedSets[node2]);
627 }
Misha Brukman2a835f92009-01-08 15:50:22 +0000628
Lang Hames27601ef2008-11-16 12:12:54 +0000629 if (m != 0) {
630 add_pbqp_edgecosts(solver, node1, node2, m);
631 delete m;
Evan Chengb1290a62008-10-02 18:29:27 +0000632 }
633 }
634 }
635
636 // We're done, PBQP problem constructed - return it.
Misha Brukman2a835f92009-01-08 15:50:22 +0000637 return solver;
Evan Chengb1290a62008-10-02 18:29:27 +0000638}
639
Lang Hames27601ef2008-11-16 12:12:54 +0000640void PBQPRegAlloc::addStackInterval(const LiveInterval *spilled, float &weight) {
641 int stackSlot = vrm->getStackSlot(spilled->reg);
Misha Brukman2a835f92009-01-08 15:50:22 +0000642
643 if (stackSlot == VirtRegMap::NO_STACK_SLOT)
Lang Hames27601ef2008-11-16 12:12:54 +0000644 return;
645
646 LiveInterval &stackInterval = lss->getOrCreateInterval(stackSlot);
647 stackInterval.weight += weight;
648
649 VNInfo *vni;
650 if (stackInterval.getNumValNums() != 0)
651 vni = stackInterval.getValNumInfo(0);
652 else
653 vni = stackInterval.getNextValue(-0U, 0, lss->getVNInfoAllocator());
654
655 LiveInterval &rhsInterval = lis->getInterval(spilled->reg);
656 stackInterval.MergeRangesInAsValue(rhsInterval, vni);
657}
658
Evan Chengb1290a62008-10-02 18:29:27 +0000659bool PBQPRegAlloc::mapPBQPToRegAlloc(pbqp *problem) {
Misha Brukman2a835f92009-01-08 15:50:22 +0000660
Evan Chengb1290a62008-10-02 18:29:27 +0000661 // Set to true if we have any spills
662 bool anotherRoundNeeded = false;
663
664 // Clear the existing allocation.
665 vrm->clearAllVirt();
Misha Brukman2a835f92009-01-08 15:50:22 +0000666
Evan Chengb1290a62008-10-02 18:29:27 +0000667 // Iterate over the nodes mapping the PBQP solution to a register assignment.
668 for (unsigned node = 0; node < node2LI.size(); ++node) {
Lang Hames27601ef2008-11-16 12:12:54 +0000669 unsigned virtReg = node2LI[node]->reg,
Evan Chengb1290a62008-10-02 18:29:27 +0000670 allocSelection = get_pbqp_solution(problem, node);
671
672 // If the PBQP solution is non-zero it's a physical register...
673 if (allocSelection != 0) {
674 // Get the physical reg, subtracting 1 to account for the spill option.
675 unsigned physReg = allowedSets[node][allocSelection - 1];
676
Lang Hames27601ef2008-11-16 12:12:54 +0000677 DOUT << "VREG " << virtReg << " -> " << tri->getName(physReg) << "\n";
678
679 assert(physReg != 0);
680
Evan Chengb1290a62008-10-02 18:29:27 +0000681 // Add to the virt reg map and update the used phys regs.
Lang Hames27601ef2008-11-16 12:12:54 +0000682 vrm->assignVirt2Phys(virtReg, physReg);
Evan Chengb1290a62008-10-02 18:29:27 +0000683 }
684 // ...Otherwise it's a spill.
685 else {
686
687 // Make sure we ignore this virtual reg on the next round
688 // of allocation
Lang Hames27601ef2008-11-16 12:12:54 +0000689 vregIntervalsToAlloc.erase(&lis->getInterval(virtReg));
Evan Chengb1290a62008-10-02 18:29:27 +0000690
Lang Hames27601ef2008-11-16 12:12:54 +0000691 float ssWeight;
Evan Chengb1290a62008-10-02 18:29:27 +0000692
693 // Insert spill ranges for this live range
Lang Hames27601ef2008-11-16 12:12:54 +0000694 const LiveInterval *spillInterval = node2LI[node];
695 double oldSpillWeight = spillInterval->weight;
Evan Chengb1290a62008-10-02 18:29:27 +0000696 SmallVector<LiveInterval*, 8> spillIs;
697 std::vector<LiveInterval*> newSpills =
Lang Hames27601ef2008-11-16 12:12:54 +0000698 lis->addIntervalsForSpills(*spillInterval, spillIs, loopInfo, *vrm,
699 ssWeight);
700 addStackInterval(spillInterval, ssWeight);
701
702 DOUT << "VREG " << virtReg << " -> SPILLED (Cost: "
703 << oldSpillWeight << ", New vregs: ";
704
705 // Copy any newly inserted live intervals into the list of regs to
706 // allocate.
707 for (std::vector<LiveInterval*>::const_iterator
708 itr = newSpills.begin(), end = newSpills.end();
709 itr != end; ++itr) {
710
711 assert(!(*itr)->empty() && "Empty spill range.");
712
713 DOUT << (*itr)->reg << " ";
714
715 vregIntervalsToAlloc.insert(*itr);
716 }
717
718 DOUT << ")\n";
Evan Chengb1290a62008-10-02 18:29:27 +0000719
720 // We need another round if spill intervals were added.
721 anotherRoundNeeded |= !newSpills.empty();
722 }
723 }
724
725 return !anotherRoundNeeded;
726}
727
Lang Hames27601ef2008-11-16 12:12:54 +0000728void PBQPRegAlloc::finalizeAlloc() const {
729 typedef LiveIntervals::iterator LIIterator;
730 typedef LiveInterval::Ranges::const_iterator LRIterator;
731
732 // First allocate registers for the empty intervals.
Argyrios Kyrtzidis3713c0b2008-11-19 12:56:21 +0000733 for (LiveIntervalSet::const_iterator
Lang Hames27601ef2008-11-16 12:12:54 +0000734 itr = emptyVRegIntervals.begin(), end = emptyVRegIntervals.end();
735 itr != end; ++itr) {
Misha Brukman2a835f92009-01-08 15:50:22 +0000736 LiveInterval *li = *itr;
Lang Hames27601ef2008-11-16 12:12:54 +0000737
738 unsigned physReg = li->preference;
739
740 if (physReg == 0) {
741 const TargetRegisterClass *liRC = mri->getRegClass(li->reg);
Misha Brukman2a835f92009-01-08 15:50:22 +0000742 physReg = *liRC->allocation_order_begin(*mf);
Lang Hames27601ef2008-11-16 12:12:54 +0000743 }
Misha Brukman2a835f92009-01-08 15:50:22 +0000744
745 vrm->assignVirt2Phys(li->reg, physReg);
Lang Hames27601ef2008-11-16 12:12:54 +0000746 }
Misha Brukman2a835f92009-01-08 15:50:22 +0000747
Lang Hames27601ef2008-11-16 12:12:54 +0000748 // Finally iterate over the basic blocks to compute and set the live-in sets.
749 SmallVector<MachineBasicBlock*, 8> liveInMBBs;
750 MachineBasicBlock *entryMBB = &*mf->begin();
751
752 for (LIIterator liItr = lis->begin(), liEnd = lis->end();
753 liItr != liEnd; ++liItr) {
754
755 const LiveInterval *li = liItr->second;
756 unsigned reg = 0;
Misha Brukman2a835f92009-01-08 15:50:22 +0000757
Lang Hames27601ef2008-11-16 12:12:54 +0000758 // Get the physical register for this interval
759 if (TargetRegisterInfo::isPhysicalRegister(li->reg)) {
760 reg = li->reg;
761 }
762 else if (vrm->isAssignedReg(li->reg)) {
763 reg = vrm->getPhys(li->reg);
764 }
765 else {
766 // Ranges which are assigned a stack slot only are ignored.
767 continue;
768 }
769
770 // Iterate over the ranges of the current interval...
771 for (LRIterator lrItr = li->begin(), lrEnd = li->end();
772 lrItr != lrEnd; ++lrItr) {
Misha Brukman2a835f92009-01-08 15:50:22 +0000773
Lang Hames27601ef2008-11-16 12:12:54 +0000774 // Find the set of basic blocks which this range is live into...
775 if (lis->findLiveInMBBs(lrItr->start, lrItr->end, liveInMBBs)) {
776 // And add the physreg for this interval to their live-in sets.
777 for (unsigned i = 0; i < liveInMBBs.size(); ++i) {
778 if (liveInMBBs[i] != entryMBB) {
779 if (!liveInMBBs[i]->isLiveIn(reg)) {
780 liveInMBBs[i]->addLiveIn(reg);
781 }
782 }
783 }
784 liveInMBBs.clear();
785 }
786 }
787 }
Misha Brukman2a835f92009-01-08 15:50:22 +0000788
Lang Hames27601ef2008-11-16 12:12:54 +0000789}
790
Evan Chengb1290a62008-10-02 18:29:27 +0000791bool PBQPRegAlloc::runOnMachineFunction(MachineFunction &MF) {
Lang Hames27601ef2008-11-16 12:12:54 +0000792
Evan Chengb1290a62008-10-02 18:29:27 +0000793 mf = &MF;
794 tm = &mf->getTarget();
795 tri = tm->getRegisterInfo();
Lang Hames27601ef2008-11-16 12:12:54 +0000796 tii = tm->getInstrInfo();
Evan Chengb1290a62008-10-02 18:29:27 +0000797 mri = &mf->getRegInfo();
798
Lang Hames27601ef2008-11-16 12:12:54 +0000799 lis = &getAnalysis<LiveIntervals>();
800 lss = &getAnalysis<LiveStacks>();
Evan Chengb1290a62008-10-02 18:29:27 +0000801 loopInfo = &getAnalysis<MachineLoopInfo>();
802
Owen Anderson49c8aa02009-03-13 05:55:11 +0000803 vrm = &getAnalysis<VirtRegMap>();
Evan Chengb1290a62008-10-02 18:29:27 +0000804
Lang Hames27601ef2008-11-16 12:12:54 +0000805 DOUT << "PBQP Register Allocating for " << mf->getFunction()->getName() << "\n";
806
Evan Chengb1290a62008-10-02 18:29:27 +0000807 // Allocator main loop:
Misha Brukman2a835f92009-01-08 15:50:22 +0000808 //
Evan Chengb1290a62008-10-02 18:29:27 +0000809 // * Map current regalloc problem to a PBQP problem
810 // * Solve the PBQP problem
811 // * Map the solution back to a register allocation
812 // * Spill if necessary
Misha Brukman2a835f92009-01-08 15:50:22 +0000813 //
Evan Chengb1290a62008-10-02 18:29:27 +0000814 // This process is continued till no more spills are generated.
815
Lang Hames27601ef2008-11-16 12:12:54 +0000816 // Find the vreg intervals in need of allocation.
817 findVRegIntervalsToAlloc();
Misha Brukman2a835f92009-01-08 15:50:22 +0000818
Lang Hames27601ef2008-11-16 12:12:54 +0000819 // If there aren't any then we're done here.
820 if (vregIntervalsToAlloc.empty() && emptyVRegIntervals.empty())
821 return true;
Evan Chengb1290a62008-10-02 18:29:27 +0000822
Lang Hames27601ef2008-11-16 12:12:54 +0000823 // If there are non-empty intervals allocate them using pbqp.
824 if (!vregIntervalsToAlloc.empty()) {
Evan Chengb1290a62008-10-02 18:29:27 +0000825
Lang Hames27601ef2008-11-16 12:12:54 +0000826 bool pbqpAllocComplete = false;
827 unsigned round = 0;
828
829 while (!pbqpAllocComplete) {
830 DOUT << " PBQP Regalloc round " << round << ":\n";
831
832 pbqp *problem = constructPBQPProblem();
Misha Brukman2a835f92009-01-08 15:50:22 +0000833
Lang Hames27601ef2008-11-16 12:12:54 +0000834 solve_pbqp(problem);
Misha Brukman2a835f92009-01-08 15:50:22 +0000835
Lang Hames27601ef2008-11-16 12:12:54 +0000836 pbqpAllocComplete = mapPBQPToRegAlloc(problem);
837
Misha Brukman2a835f92009-01-08 15:50:22 +0000838 free_pbqp(problem);
Lang Hames27601ef2008-11-16 12:12:54 +0000839
840 ++round;
841 }
Evan Chengb1290a62008-10-02 18:29:27 +0000842 }
843
Lang Hames27601ef2008-11-16 12:12:54 +0000844 // Finalise allocation, allocate empty ranges.
845 finalizeAlloc();
Evan Chengb1290a62008-10-02 18:29:27 +0000846
Lang Hames27601ef2008-11-16 12:12:54 +0000847 vregIntervalsToAlloc.clear();
848 emptyVRegIntervals.clear();
849 li2Node.clear();
850 node2LI.clear();
851 allowedSets.clear();
852
853 DOUT << "Post alloc VirtRegMap:\n" << *vrm << "\n";
854
855 // Run spiller
Evan Chengb1290a62008-10-02 18:29:27 +0000856 std::auto_ptr<Spiller> spiller(createSpiller());
Evan Chengb1290a62008-10-02 18:29:27 +0000857 spiller->runOnMachineFunction(*mf, *vrm);
Lang Hames27601ef2008-11-16 12:12:54 +0000858
Misha Brukman2a835f92009-01-08 15:50:22 +0000859 return true;
Evan Chengb1290a62008-10-02 18:29:27 +0000860}
861
862FunctionPass* llvm::createPBQPRegisterAllocator() {
863 return new PBQPRegAlloc();
864}
865
866
867#undef DEBUG_TYPE