LLVM API Documentation
00001 //===------ RegAllocPBQP.cpp ---- PBQP Register Allocator -------*- C++ -*-===// 00002 // 00003 // The LLVM Compiler Infrastructure 00004 // 00005 // This file is distributed under the University of Illinois Open Source 00006 // License. See LICENSE.TXT for details. 00007 // 00008 //===----------------------------------------------------------------------===// 00009 // 00010 // This file contains a Partitioned Boolean Quadratic Programming (PBQP) based 00011 // register allocator for LLVM. This allocator works by constructing a PBQP 00012 // problem representing the register allocation problem under consideration, 00013 // solving this using a PBQP solver, and mapping the solution back to a 00014 // register assignment. If any variables are selected for spilling then spill 00015 // code is inserted and the process repeated. 00016 // 00017 // The PBQP solver (pbqp.c) provided for this allocator uses a heuristic tuned 00018 // for register allocation. For more information on PBQP for register 00019 // allocation, see the following papers: 00020 // 00021 // (1) Hames, L. and Scholz, B. 2006. Nearly optimal register allocation with 00022 // PBQP. In Proceedings of the 7th Joint Modular Languages Conference 00023 // (JMLC'06). LNCS, vol. 4228. Springer, New York, NY, USA. 346-361. 00024 // 00025 // (2) Scholz, B., Eckstein, E. 2002. Register allocation for irregular 00026 // architectures. In Proceedings of the Joint Conference on Languages, 00027 // Compilers and Tools for Embedded Systems (LCTES'02), ACM Press, New York, 00028 // NY, USA, 139-148. 00029 // 00030 //===----------------------------------------------------------------------===// 00031 00032 #define DEBUG_TYPE "regalloc" 00033 00034 #include "PBQP.h" 00035 #include "VirtRegMap.h" 00036 #include "llvm/CodeGen/LiveIntervalAnalysis.h" 00037 #include "llvm/CodeGen/LiveStackAnalysis.h" 00038 #include "llvm/CodeGen/MachineFunctionPass.h" 00039 #include "llvm/CodeGen/MachineLoopInfo.h" 00040 #include "llvm/CodeGen/MachineRegisterInfo.h" 00041 #include "llvm/CodeGen/RegAllocRegistry.h" 00042 #include "llvm/CodeGen/RegisterCoalescer.h" 00043 #include "llvm/Support/Debug.h" 00044 #include "llvm/Target/TargetInstrInfo.h" 00045 #include "llvm/Target/TargetMachine.h" 00046 #include <limits> 00047 #include <map> 00048 #include <memory> 00049 #include <set> 00050 #include <vector> 00051 00052 using namespace llvm; 00053 00054 static RegisterRegAlloc 00055 registerPBQPRepAlloc("pbqp", "PBQP register allocator", 00056 createPBQPRegisterAllocator); 00057 00058 namespace { 00059 00060 //! 00061 //! PBQP based allocators solve the register allocation problem by mapping 00062 //! register allocation problems to Partitioned Boolean Quadratic 00063 //! Programming problems. 00064 class VISIBILITY_HIDDEN PBQPRegAlloc : public MachineFunctionPass { 00065 public: 00066 00067 static char ID; 00068 00069 //! Construct a PBQP register allocator. 00070 PBQPRegAlloc() : MachineFunctionPass((intptr_t)&ID) {} 00071 00072 //! Return the pass name. 00073 virtual const char* getPassName() const throw() { 00074 return "PBQP Register Allocator"; 00075 } 00076 00077 //! PBQP analysis usage. 00078 virtual void getAnalysisUsage(AnalysisUsage &au) const { 00079 au.addRequired<LiveIntervals>(); 00080 au.addRequiredTransitive<RegisterCoalescer>(); 00081 au.addRequired<LiveStacks>(); 00082 au.addPreserved<LiveStacks>(); 00083 au.addRequired<MachineLoopInfo>(); 00084 au.addPreserved<MachineLoopInfo>(); 00085 MachineFunctionPass::getAnalysisUsage(au); 00086 } 00087 00088 //! Perform register allocation 00089 virtual bool runOnMachineFunction(MachineFunction &MF); 00090 00091 private: 00092 typedef std::map<const LiveInterval*, unsigned> LI2NodeMap; 00093 typedef std::vector<const LiveInterval*> Node2LIMap; 00094 typedef std::vector<unsigned> AllowedSet; 00095 typedef std::vector<AllowedSet> AllowedSetMap; 00096 typedef std::set<unsigned> RegSet; 00097 typedef std::pair<unsigned, unsigned> RegPair; 00098 typedef std::map<RegPair, PBQPNum> CoalesceMap; 00099 00100 typedef std::set<LiveInterval*> LiveIntervalSet; 00101 00102 MachineFunction *mf; 00103 const TargetMachine *tm; 00104 const TargetRegisterInfo *tri; 00105 const TargetInstrInfo *tii; 00106 const MachineLoopInfo *loopInfo; 00107 MachineRegisterInfo *mri; 00108 00109 LiveIntervals *lis; 00110 LiveStacks *lss; 00111 VirtRegMap *vrm; 00112 00113 LI2NodeMap li2Node; 00114 Node2LIMap node2LI; 00115 AllowedSetMap allowedSets; 00116 LiveIntervalSet vregIntervalsToAlloc, 00117 emptyVRegIntervals; 00118 00119 00120 //! Builds a PBQP cost vector. 00121 template <typename RegContainer> 00122 PBQPVector* buildCostVector(unsigned vReg, 00123 const RegContainer &allowed, 00124 const CoalesceMap &cealesces, 00125 PBQPNum spillCost) const; 00126 00127 //! \brief Builds a PBQP interference matrix. 00128 //! 00129 //! @return Either a pointer to a non-zero PBQP matrix representing the 00130 //! allocation option costs, or a null pointer for a zero matrix. 00131 //! 00132 //! Expects allowed sets for two interfering LiveIntervals. These allowed 00133 //! sets should contain only allocable registers from the LiveInterval's 00134 //! register class, with any interfering pre-colored registers removed. 00135 template <typename RegContainer> 00136 PBQPMatrix* buildInterferenceMatrix(const RegContainer &allowed1, 00137 const RegContainer &allowed2) const; 00138 00139 //! 00140 //! Expects allowed sets for two potentially coalescable LiveIntervals, 00141 //! and an estimated benefit due to coalescing. The allowed sets should 00142 //! contain only allocable registers from the LiveInterval's register 00143 //! classes, with any interfering pre-colored registers removed. 00144 template <typename RegContainer> 00145 PBQPMatrix* buildCoalescingMatrix(const RegContainer &allowed1, 00146 const RegContainer &allowed2, 00147 PBQPNum cBenefit) const; 00148 00149 //! \brief Finds coalescing opportunities and returns them as a map. 00150 //! 00151 //! Any entries in the map are guaranteed coalescable, even if their 00152 //! corresponding live intervals overlap. 00153 CoalesceMap findCoalesces(); 00154 00155 //! \brief Finds the initial set of vreg intervals to allocate. 00156 void findVRegIntervalsToAlloc(); 00157 00158 //! \brief Constructs a PBQP problem representation of the register 00159 //! allocation problem for this function. 00160 //! 00161 //! @return a PBQP solver object for the register allocation problem. 00162 pbqp* constructPBQPProblem(); 00163 00164 //! \brief Adds a stack interval if the given live interval has been 00165 //! spilled. Used to support stack slot coloring. 00166 void addStackInterval(const LiveInterval *spilled, float &weight); 00167 00168 //! \brief Given a solved PBQP problem maps this solution back to a register 00169 //! assignment. 00170 bool mapPBQPToRegAlloc(pbqp *problem); 00171 00172 //! \brief Postprocessing before final spilling. Sets basic block "live in" 00173 //! variables. 00174 void finalizeAlloc() const; 00175 00176 }; 00177 00178 char PBQPRegAlloc::ID = 0; 00179 } 00180 00181 00182 template <typename RegContainer> 00183 PBQPVector* PBQPRegAlloc::buildCostVector(unsigned vReg, 00184 const RegContainer &allowed, 00185 const CoalesceMap &coalesces, 00186 PBQPNum spillCost) const { 00187 00188 typedef typename RegContainer::const_iterator AllowedItr; 00189 00190 // Allocate vector. Additional element (0th) used for spill option 00191 PBQPVector *v = new PBQPVector(allowed.size() + 1); 00192 00193 (*v)[0] = spillCost; 00194 00195 // Iterate over the allowed registers inserting coalesce benefits if there 00196 // are any. 00197 unsigned ai = 0; 00198 for (AllowedItr itr = allowed.begin(), end = allowed.end(); 00199 itr != end; ++itr, ++ai) { 00200 00201 unsigned pReg = *itr; 00202 00203 CoalesceMap::const_iterator cmItr = 00204 coalesces.find(RegPair(vReg, pReg)); 00205 00206 // No coalesce - on to the next preg. 00207 if (cmItr == coalesces.end()) 00208 continue; 00209 00210 // We have a coalesce - insert the benefit. 00211 (*v)[ai + 1] = -cmItr->second; 00212 } 00213 00214 return v; 00215 } 00216 00217 template <typename RegContainer> 00218 PBQPMatrix* PBQPRegAlloc::buildInterferenceMatrix( 00219 const RegContainer &allowed1, const RegContainer &allowed2) const { 00220 00221 typedef typename RegContainer::const_iterator RegContainerIterator; 00222 00223 // Construct a PBQP matrix representing the cost of allocation options. The 00224 // rows and columns correspond to the allocation options for the two live 00225 // intervals. Elements will be infinite where corresponding registers alias, 00226 // since we cannot allocate aliasing registers to interfering live intervals. 00227 // All other elements (non-aliasing combinations) will have zero cost. Note 00228 // that the spill option (element 0,0) has zero cost, since we can allocate 00229 // both intervals to memory safely (the cost for each individual allocation 00230 // to memory is accounted for by the cost vectors for each live interval). 00231 PBQPMatrix *m = new PBQPMatrix(allowed1.size() + 1, allowed2.size() + 1); 00232 00233 // Assume this is a zero matrix until proven otherwise. Zero matrices occur 00234 // between interfering live ranges with non-overlapping register sets (e.g. 00235 // non-overlapping reg classes, or disjoint sets of allowed regs within the 00236 // same class). The term "overlapping" is used advisedly: sets which do not 00237 // intersect, but contain registers which alias, will have non-zero matrices. 00238 // We optimize zero matrices away to improve solver speed. 00239 bool isZeroMatrix = true; 00240 00241 00242 // Row index. Starts at 1, since the 0th row is for the spill option, which 00243 // is always zero. 00244 unsigned ri = 1; 00245 00246 // Iterate over allowed sets, insert infinities where required. 00247 for (RegContainerIterator a1Itr = allowed1.begin(), a1End = allowed1.end(); 00248 a1Itr != a1End; ++a1Itr) { 00249 00250 // Column index, starts at 1 as for row index. 00251 unsigned ci = 1; 00252 unsigned reg1 = *a1Itr; 00253 00254 for (RegContainerIterator a2Itr = allowed2.begin(), a2End = allowed2.end(); 00255 a2Itr != a2End; ++a2Itr) { 00256 00257 unsigned reg2 = *a2Itr; 00258 00259 // If the row/column regs are identical or alias insert an infinity. 00260 if ((reg1 == reg2) || tri->areAliases(reg1, reg2)) { 00261 (*m)[ri][ci] = std::numeric_limits<PBQPNum>::infinity(); 00262 isZeroMatrix = false; 00263 } 00264 00265 ++ci; 00266 } 00267 00268 ++ri; 00269 } 00270 00271 // If this turns out to be a zero matrix... 00272 if (isZeroMatrix) { 00273 // free it and return null. 00274 delete m; 00275 return 0; 00276 } 00277 00278 // ...otherwise return the cost matrix. 00279 return m; 00280 } 00281 00282 template <typename RegContainer> 00283 PBQPMatrix* PBQPRegAlloc::buildCoalescingMatrix( 00284 const RegContainer &allowed1, const RegContainer &allowed2, 00285 PBQPNum cBenefit) const { 00286 00287 typedef typename RegContainer::const_iterator RegContainerIterator; 00288 00289 // Construct a PBQP Matrix representing the benefits of coalescing. As with 00290 // interference matrices the rows and columns represent allowed registers 00291 // for the LiveIntervals which are (potentially) to be coalesced. The amount 00292 // -cBenefit will be placed in any element representing the same register 00293 // for both intervals. 00294 PBQPMatrix *m = new PBQPMatrix(allowed1.size() + 1, allowed2.size() + 1); 00295 00296 // Reset costs to zero. 00297 m->reset(0); 00298 00299 // Assume the matrix is zero till proven otherwise. Zero matrices will be 00300 // optimized away as in the interference case. 00301 bool isZeroMatrix = true; 00302 00303 // Row index. Starts at 1, since the 0th row is for the spill option, which 00304 // is always zero. 00305 unsigned ri = 1; 00306 00307 // Iterate over the allowed sets, insert coalescing benefits where 00308 // appropriate. 00309 for (RegContainerIterator a1Itr = allowed1.begin(), a1End = allowed1.end(); 00310 a1Itr != a1End; ++a1Itr) { 00311 00312 // Column index, starts at 1 as for row index. 00313 unsigned ci = 1; 00314 unsigned reg1 = *a1Itr; 00315 00316 for (RegContainerIterator a2Itr = allowed2.begin(), a2End = allowed2.end(); 00317 a2Itr != a2End; ++a2Itr) { 00318 00319 // If the row and column represent the same register insert a beneficial 00320 // cost to preference this allocation - it would allow us to eliminate a 00321 // move instruction. 00322 if (reg1 == *a2Itr) { 00323 (*m)[ri][ci] = -cBenefit; 00324 isZeroMatrix = false; 00325 } 00326 00327 ++ci; 00328 } 00329 00330 ++ri; 00331 } 00332 00333 // If this turns out to be a zero matrix... 00334 if (isZeroMatrix) { 00335 // ...free it and return null. 00336 delete m; 00337 return 0; 00338 } 00339 00340 return m; 00341 } 00342 00343 PBQPRegAlloc::CoalesceMap PBQPRegAlloc::findCoalesces() { 00344 00345 typedef MachineFunction::const_iterator MFIterator; 00346 typedef MachineBasicBlock::const_iterator MBBIterator; 00347 typedef LiveInterval::const_vni_iterator VNIIterator; 00348 00349 CoalesceMap coalescesFound; 00350 00351 // To find coalesces we need to iterate over the function looking for 00352 // copy instructions. 00353 for (MFIterator bbItr = mf->begin(), bbEnd = mf->end(); 00354 bbItr != bbEnd; ++bbItr) { 00355 00356 const MachineBasicBlock *mbb = &*bbItr; 00357 00358 for (MBBIterator iItr = mbb->begin(), iEnd = mbb->end(); 00359 iItr != iEnd; ++iItr) { 00360 00361 const MachineInstr *instr = &*iItr; 00362 unsigned srcReg, dstReg, srcSubReg, dstSubReg; 00363 00364 // If this isn't a copy then continue to the next instruction. 00365 if (!tii->isMoveInstr(*instr, srcReg, dstReg, srcSubReg, dstSubReg)) 00366 continue; 00367 00368 // If the registers are already the same our job is nice and easy. 00369 if (dstReg == srcReg) 00370 continue; 00371 00372 bool srcRegIsPhysical = TargetRegisterInfo::isPhysicalRegister(srcReg), 00373 dstRegIsPhysical = TargetRegisterInfo::isPhysicalRegister(dstReg); 00374 00375 // If both registers are physical then we can't coalesce. 00376 if (srcRegIsPhysical && dstRegIsPhysical) 00377 continue; 00378 00379 // If it's a copy that includes a virtual register but the source and 00380 // destination classes differ then we can't coalesce, so continue with 00381 // the next instruction. 00382 const TargetRegisterClass *srcRegClass = srcRegIsPhysical ? 00383 tri->getPhysicalRegisterRegClass(srcReg) : mri->getRegClass(srcReg); 00384 00385 const TargetRegisterClass *dstRegClass = dstRegIsPhysical ? 00386 tri->getPhysicalRegisterRegClass(dstReg) : mri->getRegClass(dstReg); 00387 00388 if (srcRegClass != dstRegClass) 00389 continue; 00390 00391 // We also need any physical regs to be allocable, coalescing with 00392 // a non-allocable register is invalid. 00393 if (srcRegIsPhysical) { 00394 if (std::find(srcRegClass->allocation_order_begin(*mf), 00395 srcRegClass->allocation_order_end(*mf), srcReg) == 00396 srcRegClass->allocation_order_end(*mf)) 00397 continue; 00398 } 00399 00400 if (dstRegIsPhysical) { 00401 if (std::find(dstRegClass->allocation_order_begin(*mf), 00402 dstRegClass->allocation_order_end(*mf), dstReg) == 00403 dstRegClass->allocation_order_end(*mf)) 00404 continue; 00405 } 00406 00407 // If we've made it here we have a copy with compatible register classes. 00408 // We can probably coalesce, but we need to consider overlap. 00409 const LiveInterval *srcLI = &lis->getInterval(srcReg), 00410 *dstLI = &lis->getInterval(dstReg); 00411 00412 if (srcLI->overlaps(*dstLI)) { 00413 // Even in the case of an overlap we might still be able to coalesce, 00414 // but we need to make sure that no definition of either range occurs 00415 // while the other range is live. 00416 00417 // Otherwise start by assuming we're ok. 00418 bool badDef = false; 00419 00420 // Test all defs of the source range. 00421 for (VNIIterator 00422 vniItr = srcLI->vni_begin(), vniEnd = srcLI->vni_end(); 00423 vniItr != vniEnd; ++vniItr) { 00424 00425 // If we find a def that kills the coalescing opportunity then 00426 // record it and break from the loop. 00427 if (dstLI->liveAt((*vniItr)->def)) { 00428 badDef = true; 00429 break; 00430 } 00431 } 00432 00433 // If we have a bad def give up, continue to the next instruction. 00434 if (badDef) 00435 continue; 00436 00437 // Otherwise test definitions of the destination range. 00438 for (VNIIterator 00439 vniItr = dstLI->vni_begin(), vniEnd = dstLI->vni_end(); 00440 vniItr != vniEnd; ++vniItr) { 00441 00442 // We want to make sure we skip the copy instruction itself. 00443 if ((*vniItr)->copy == instr) 00444 continue; 00445 00446 if (srcLI->liveAt((*vniItr)->def)) { 00447 badDef = true; 00448 break; 00449 } 00450 } 00451 00452 // As before a bad def we give up and continue to the next instr. 00453 if (badDef) 00454 continue; 00455 } 00456 00457 // If we make it to here then either the ranges didn't overlap, or they 00458 // did, but none of their definitions would prevent us from coalescing. 00459 // We're good to go with the coalesce. 00460 00461 float cBenefit = powf(10.0f, loopInfo->getLoopDepth(mbb)) / 5.0; 00462 00463 coalescesFound[RegPair(srcReg, dstReg)] = cBenefit; 00464 coalescesFound[RegPair(dstReg, srcReg)] = cBenefit; 00465 } 00466 00467 } 00468 00469 return coalescesFound; 00470 } 00471 00472 void PBQPRegAlloc::findVRegIntervalsToAlloc() { 00473 00474 // Iterate over all live ranges. 00475 for (LiveIntervals::iterator itr = lis->begin(), end = lis->end(); 00476 itr != end; ++itr) { 00477 00478 // Ignore physical ones. 00479 if (TargetRegisterInfo::isPhysicalRegister(itr->first)) 00480 continue; 00481 00482 LiveInterval *li = itr->second; 00483 00484 // If this live interval is non-empty we will use pbqp to allocate it. 00485 // Empty intervals we allocate in a simple post-processing stage in 00486 // finalizeAlloc. 00487 if (!li->empty()) { 00488 vregIntervalsToAlloc.insert(li); 00489 } 00490 else { 00491 emptyVRegIntervals.insert(li); 00492 } 00493 } 00494 } 00495 00496 pbqp* PBQPRegAlloc::constructPBQPProblem() { 00497 00498 typedef std::vector<const LiveInterval*> LIVector; 00499 typedef std::vector<unsigned> RegVector; 00500 00501 // This will store the physical intervals for easy reference. 00502 LIVector physIntervals; 00503 00504 // Start by clearing the old node <-> live interval mappings & allowed sets 00505 li2Node.clear(); 00506 node2LI.clear(); 00507 allowedSets.clear(); 00508 00509 // Populate physIntervals, update preg use: 00510 for (LiveIntervals::iterator itr = lis->begin(), end = lis->end(); 00511 itr != end; ++itr) { 00512 00513 if (TargetRegisterInfo::isPhysicalRegister(itr->first)) { 00514 physIntervals.push_back(itr->second); 00515 mri->setPhysRegUsed(itr->second->reg); 00516 } 00517 } 00518 00519 // Iterate over vreg intervals, construct live interval <-> node number 00520 // mappings. 00521 for (LiveIntervalSet::const_iterator 00522 itr = vregIntervalsToAlloc.begin(), end = vregIntervalsToAlloc.end(); 00523 itr != end; ++itr) { 00524 const LiveInterval *li = *itr; 00525 00526 li2Node[li] = node2LI.size(); 00527 node2LI.push_back(li); 00528 } 00529 00530 // Get the set of potential coalesces. 00531 CoalesceMap coalesces(findCoalesces()); 00532 00533 // Construct a PBQP solver for this problem 00534 pbqp *solver = alloc_pbqp(vregIntervalsToAlloc.size()); 00535 00536 // Resize allowedSets container appropriately. 00537 allowedSets.resize(vregIntervalsToAlloc.size()); 00538 00539 // Iterate over virtual register intervals to compute allowed sets... 00540 for (unsigned node = 0; node < node2LI.size(); ++node) { 00541 00542 // Grab pointers to the interval and its register class. 00543 const LiveInterval *li = node2LI[node]; 00544 const TargetRegisterClass *liRC = mri->getRegClass(li->reg); 00545 00546 // Start by assuming all allocable registers in the class are allowed... 00547 RegVector liAllowed(liRC->allocation_order_begin(*mf), 00548 liRC->allocation_order_end(*mf)); 00549 00550 // Eliminate the physical registers which overlap with this range, along 00551 // with all their aliases. 00552 for (LIVector::iterator pItr = physIntervals.begin(), 00553 pEnd = physIntervals.end(); pItr != pEnd; ++pItr) { 00554 00555 if (!li->overlaps(**pItr)) 00556 continue; 00557 00558 unsigned pReg = (*pItr)->reg; 00559 00560 // If we get here then the live intervals overlap, but we're still ok 00561 // if they're coalescable. 00562 if (coalesces.find(RegPair(li->reg, pReg)) != coalesces.end()) 00563 continue; 00564 00565 // If we get here then we have a genuine exclusion. 00566 00567 // Remove the overlapping reg... 00568 RegVector::iterator eraseItr = 00569 std::find(liAllowed.begin(), liAllowed.end(), pReg); 00570 00571 if (eraseItr != liAllowed.end()) 00572 liAllowed.erase(eraseItr); 00573 00574 const unsigned *aliasItr = tri->getAliasSet(pReg); 00575 00576 if (aliasItr != 0) { 00577 // ...and its aliases. 00578 for (; *aliasItr != 0; ++aliasItr) { 00579 RegVector::iterator eraseItr = 00580 std::find(liAllowed.begin(), liAllowed.end(), *aliasItr); 00581 00582 if (eraseItr != liAllowed.end()) { 00583 liAllowed.erase(eraseItr); 00584 } 00585 } 00586 } 00587 } 00588 00589 // Copy the allowed set into a member vector for use when constructing cost 00590 // vectors & matrices, and mapping PBQP solutions back to assignments. 00591 allowedSets[node] = AllowedSet(liAllowed.begin(), liAllowed.end()); 00592 00593 // Set the spill cost to the interval weight, or epsilon if the 00594 // interval weight is zero 00595 PBQPNum spillCost = (li->weight != 0.0) ? 00596 li->weight : std::numeric_limits<PBQPNum>::min(); 00597 00598 // Build a cost vector for this interval. 00599 add_pbqp_nodecosts(solver, node, 00600 buildCostVector(li->reg, allowedSets[node], coalesces, 00601 spillCost)); 00602 00603 } 00604 00605 00606 // Now add the cost matrices... 00607 for (unsigned node1 = 0; node1 < node2LI.size(); ++node1) { 00608 const LiveInterval *li = node2LI[node1]; 00609 00610 // Test for live range overlaps and insert interference matrices. 00611 for (unsigned node2 = node1 + 1; node2 < node2LI.size(); ++node2) { 00612 const LiveInterval *li2 = node2LI[node2]; 00613 00614 CoalesceMap::const_iterator cmItr = 00615 coalesces.find(RegPair(li->reg, li2->reg)); 00616 00617 PBQPMatrix *m = 0; 00618 00619 if (cmItr != coalesces.end()) { 00620 m = buildCoalescingMatrix(allowedSets[node1], allowedSets[node2], 00621 cmItr->second); 00622 } 00623 else if (li->overlaps(*li2)) { 00624 m = buildInterferenceMatrix(allowedSets[node1], allowedSets[node2]); 00625 } 00626 00627 if (m != 0) { 00628 add_pbqp_edgecosts(solver, node1, node2, m); 00629 delete m; 00630 } 00631 } 00632 } 00633 00634 // We're done, PBQP problem constructed - return it. 00635 return solver; 00636 } 00637 00638 void PBQPRegAlloc::addStackInterval(const LiveInterval *spilled, float &weight) { 00639 int stackSlot = vrm->getStackSlot(spilled->reg); 00640 00641 if (stackSlot == VirtRegMap::NO_STACK_SLOT) 00642 return; 00643 00644 LiveInterval &stackInterval = lss->getOrCreateInterval(stackSlot); 00645 stackInterval.weight += weight; 00646 00647 VNInfo *vni; 00648 if (stackInterval.getNumValNums() != 0) 00649 vni = stackInterval.getValNumInfo(0); 00650 else 00651 vni = stackInterval.getNextValue(-0U, 0, lss->getVNInfoAllocator()); 00652 00653 LiveInterval &rhsInterval = lis->getInterval(spilled->reg); 00654 stackInterval.MergeRangesInAsValue(rhsInterval, vni); 00655 } 00656 00657 bool PBQPRegAlloc::mapPBQPToRegAlloc(pbqp *problem) { 00658 00659 // Set to true if we have any spills 00660 bool anotherRoundNeeded = false; 00661 00662 // Clear the existing allocation. 00663 vrm->clearAllVirt(); 00664 00665 // Iterate over the nodes mapping the PBQP solution to a register assignment. 00666 for (unsigned node = 0; node < node2LI.size(); ++node) { 00667 unsigned virtReg = node2LI[node]->reg, 00668 allocSelection = get_pbqp_solution(problem, node); 00669 00670 // If the PBQP solution is non-zero it's a physical register... 00671 if (allocSelection != 0) { 00672 // Get the physical reg, subtracting 1 to account for the spill option. 00673 unsigned physReg = allowedSets[node][allocSelection - 1]; 00674 00675 DOUT << "VREG " << virtReg << " -> " << tri->getName(physReg) << "\n"; 00676 00677 assert(physReg != 0); 00678 00679 // Add to the virt reg map and update the used phys regs. 00680 vrm->assignVirt2Phys(virtReg, physReg); 00681 } 00682 // ...Otherwise it's a spill. 00683 else { 00684 00685 // Make sure we ignore this virtual reg on the next round 00686 // of allocation 00687 vregIntervalsToAlloc.erase(&lis->getInterval(virtReg)); 00688 00689 float ssWeight; 00690 00691 // Insert spill ranges for this live range 00692 const LiveInterval *spillInterval = node2LI[node]; 00693 double oldSpillWeight = spillInterval->weight; 00694 SmallVector<LiveInterval*, 8> spillIs; 00695 std::vector<LiveInterval*> newSpills = 00696 lis->addIntervalsForSpills(*spillInterval, spillIs, loopInfo, *vrm, 00697 ssWeight); 00698 addStackInterval(spillInterval, ssWeight); 00699 00700 DOUT << "VREG " << virtReg << " -> SPILLED (Cost: " 00701 << oldSpillWeight << ", New vregs: "; 00702 00703 // Copy any newly inserted live intervals into the list of regs to 00704 // allocate. 00705 for (std::vector<LiveInterval*>::const_iterator 00706 itr = newSpills.begin(), end = newSpills.end(); 00707 itr != end; ++itr) { 00708 00709 assert(!(*itr)->empty() && "Empty spill range."); 00710 00711 DOUT << (*itr)->reg << " "; 00712 00713 vregIntervalsToAlloc.insert(*itr); 00714 } 00715 00716 DOUT << ")\n"; 00717 00718 // We need another round if spill intervals were added. 00719 anotherRoundNeeded |= !newSpills.empty(); 00720 } 00721 } 00722 00723 return !anotherRoundNeeded; 00724 } 00725 00726 void PBQPRegAlloc::finalizeAlloc() const { 00727 typedef LiveIntervals::iterator LIIterator; 00728 typedef LiveInterval::Ranges::const_iterator LRIterator; 00729 00730 // First allocate registers for the empty intervals. 00731 for (LiveIntervalSet::const_iterator 00732 itr = emptyVRegIntervals.begin(), end = emptyVRegIntervals.end(); 00733 itr != end; ++itr) { 00734 LiveInterval *li = *itr; 00735 00736 unsigned physReg = li->preference; 00737 00738 if (physReg == 0) { 00739 const TargetRegisterClass *liRC = mri->getRegClass(li->reg); 00740 physReg = *liRC->allocation_order_begin(*mf); 00741 } 00742 00743 vrm->assignVirt2Phys(li->reg, physReg); 00744 } 00745 00746 // Finally iterate over the basic blocks to compute and set the live-in sets. 00747 SmallVector<MachineBasicBlock*, 8> liveInMBBs; 00748 MachineBasicBlock *entryMBB = &*mf->begin(); 00749 00750 for (LIIterator liItr = lis->begin(), liEnd = lis->end(); 00751 liItr != liEnd; ++liItr) { 00752 00753 const LiveInterval *li = liItr->second; 00754 unsigned reg = 0; 00755 00756 // Get the physical register for this interval 00757 if (TargetRegisterInfo::isPhysicalRegister(li->reg)) { 00758 reg = li->reg; 00759 } 00760 else if (vrm->isAssignedReg(li->reg)) { 00761 reg = vrm->getPhys(li->reg); 00762 } 00763 else { 00764 // Ranges which are assigned a stack slot only are ignored. 00765 continue; 00766 } 00767 00768 // Iterate over the ranges of the current interval... 00769 for (LRIterator lrItr = li->begin(), lrEnd = li->end(); 00770 lrItr != lrEnd; ++lrItr) { 00771 00772 // Find the set of basic blocks which this range is live into... 00773 if (lis->findLiveInMBBs(lrItr->start, lrItr->end, liveInMBBs)) { 00774 // And add the physreg for this interval to their live-in sets. 00775 for (unsigned i = 0; i < liveInMBBs.size(); ++i) { 00776 if (liveInMBBs[i] != entryMBB) { 00777 if (!liveInMBBs[i]->isLiveIn(reg)) { 00778 liveInMBBs[i]->addLiveIn(reg); 00779 } 00780 } 00781 } 00782 liveInMBBs.clear(); 00783 } 00784 } 00785 } 00786 00787 } 00788 00789 bool PBQPRegAlloc::runOnMachineFunction(MachineFunction &MF) { 00790 00791 mf = &MF; 00792 tm = &mf->getTarget(); 00793 tri = tm->getRegisterInfo(); 00794 tii = tm->getInstrInfo(); 00795 mri = &mf->getRegInfo(); 00796 00797 lis = &getAnalysis<LiveIntervals>(); 00798 lss = &getAnalysis<LiveStacks>(); 00799 loopInfo = &getAnalysis<MachineLoopInfo>(); 00800 00801 std::auto_ptr<VirtRegMap> vrmAutoPtr(new VirtRegMap(*mf)); 00802 vrm = vrmAutoPtr.get(); 00803 00804 DOUT << "PBQP Register Allocating for " << mf->getFunction()->getName() << "\n"; 00805 00806 // Allocator main loop: 00807 // 00808 // * Map current regalloc problem to a PBQP problem 00809 // * Solve the PBQP problem 00810 // * Map the solution back to a register allocation 00811 // * Spill if necessary 00812 // 00813 // This process is continued till no more spills are generated. 00814 00815 // Find the vreg intervals in need of allocation. 00816 findVRegIntervalsToAlloc(); 00817 00818 // If there aren't any then we're done here. 00819 if (vregIntervalsToAlloc.empty() && emptyVRegIntervals.empty()) 00820 return true; 00821 00822 // If there are non-empty intervals allocate them using pbqp. 00823 if (!vregIntervalsToAlloc.empty()) { 00824 00825 bool pbqpAllocComplete = false; 00826 unsigned round = 0; 00827 00828 while (!pbqpAllocComplete) { 00829 DOUT << " PBQP Regalloc round " << round << ":\n"; 00830 00831 pbqp *problem = constructPBQPProblem(); 00832 00833 solve_pbqp(problem); 00834 00835 pbqpAllocComplete = mapPBQPToRegAlloc(problem); 00836 00837 free_pbqp(problem); 00838 00839 ++round; 00840 } 00841 } 00842 00843 // Finalise allocation, allocate empty ranges. 00844 finalizeAlloc(); 00845 00846 vregIntervalsToAlloc.clear(); 00847 emptyVRegIntervals.clear(); 00848 li2Node.clear(); 00849 node2LI.clear(); 00850 allowedSets.clear(); 00851 00852 DOUT << "Post alloc VirtRegMap:\n" << *vrm << "\n"; 00853 00854 // Run spiller 00855 std::auto_ptr<Spiller> spiller(createSpiller()); 00856 spiller->runOnMachineFunction(*mf, *vrm); 00857 00858 return true; 00859 } 00860 00861 FunctionPass* llvm::createPBQPRegisterAllocator() { 00862 return new PBQPRegAlloc(); 00863 } 00864 00865 00866 #undef DEBUG_TYPE