1 //===------ 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 //===----------------------------------------------------------------------===// 9 // 10 // 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 15 // code is inserted and the process repeated. 16 // 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 19 // allocation, see the following papers: 20 // 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. 29 // 30 //===----------------------------------------------------------------------===// 31 32 #include "llvm/CodeGen/RegAllocPBQP.h" 33 #include "RegisterCoalescer.h" 34 #include "Spiller.h" 35 #include "llvm/Analysis/AliasAnalysis.h" 36 #include "llvm/CodeGen/CalcSpillWeights.h" 37 #include "llvm/CodeGen/LiveIntervalAnalysis.h" 38 #include "llvm/CodeGen/LiveRangeEdit.h" 39 #include "llvm/CodeGen/LiveStackAnalysis.h" 40 #include "llvm/CodeGen/MachineBlockFrequencyInfo.h" 41 #include "llvm/CodeGen/MachineDominators.h" 42 #include "llvm/CodeGen/MachineFunctionPass.h" 43 #include "llvm/CodeGen/MachineLoopInfo.h" 44 #include "llvm/CodeGen/MachineRegisterInfo.h" 45 #include "llvm/CodeGen/RegAllocRegistry.h" 46 #include "llvm/CodeGen/VirtRegMap.h" 47 #include "llvm/IR/Module.h" 48 #include "llvm/Support/Debug.h" 49 #include "llvm/Support/FileSystem.h" 50 #include "llvm/Support/raw_ostream.h" 51 #include "llvm/Target/TargetInstrInfo.h" 52 #include "llvm/Target/TargetSubtargetInfo.h" 53 #include <limits> 54 #include <memory> 55 #include <queue> 56 #include <set> 57 #include <sstream> 58 #include <vector> 59 60 using namespace llvm; 61 62 #define DEBUG_TYPE "regalloc" 63 64 static RegisterRegAlloc 65 RegisterPBQPRepAlloc("pbqp", "PBQP register allocator", 66 createDefaultPBQPRegisterAllocator); 67 68 static cl::opt<bool> 69 PBQPCoalescing("pbqp-coalescing", 70 cl::desc("Attempt coalescing during PBQP register allocation."), 71 cl::init(false), cl::Hidden); 72 73 #ifndef NDEBUG 74 static cl::opt<bool> 75 PBQPDumpGraphs("pbqp-dump-graphs", 76 cl::desc("Dump graphs for each function/round in the compilation unit."), 77 cl::init(false), cl::Hidden); 78 #endif 79 80 namespace { 81 82 /// 83 /// PBQP based allocators solve the register allocation problem by mapping 84 /// register allocation problems to Partitioned Boolean Quadratic 85 /// Programming problems. 86 class RegAllocPBQP : public MachineFunctionPass { 87 public: 88 89 static char ID; 90 91 /// Construct a PBQP register allocator. 92 RegAllocPBQP(char *cPassID = nullptr) 93 : MachineFunctionPass(ID), customPassID(cPassID) { 94 initializeSlotIndexesPass(*PassRegistry::getPassRegistry()); 95 initializeLiveIntervalsPass(*PassRegistry::getPassRegistry()); 96 initializeLiveStacksPass(*PassRegistry::getPassRegistry()); 97 initializeVirtRegMapPass(*PassRegistry::getPassRegistry()); 98 } 99 100 /// Return the pass name. 101 const char* getPassName() const override { 102 return "PBQP Register Allocator"; 103 } 104 105 /// PBQP analysis usage. 106 void getAnalysisUsage(AnalysisUsage &au) const override; 107 108 /// Perform register allocation 109 bool runOnMachineFunction(MachineFunction &MF) override; 110 111 private: 112 113 typedef std::map<const LiveInterval*, unsigned> LI2NodeMap; 114 typedef std::vector<const LiveInterval*> Node2LIMap; 115 typedef std::vector<unsigned> AllowedSet; 116 typedef std::vector<AllowedSet> AllowedSetMap; 117 typedef std::pair<unsigned, unsigned> RegPair; 118 typedef std::map<RegPair, PBQP::PBQPNum> CoalesceMap; 119 typedef std::set<unsigned> RegSet; 120 121 char *customPassID; 122 123 RegSet VRegsToAlloc, EmptyIntervalVRegs; 124 125 /// \brief Finds the initial set of vreg intervals to allocate. 126 void findVRegIntervalsToAlloc(const MachineFunction &MF, LiveIntervals &LIS); 127 128 /// \brief Constructs an initial graph. 129 void initializeGraph(PBQPRAGraph &G); 130 131 /// \brief Given a solved PBQP problem maps this solution back to a register 132 /// assignment. 133 bool mapPBQPToRegAlloc(const PBQPRAGraph &G, 134 const PBQP::Solution &Solution, 135 VirtRegMap &VRM, 136 Spiller &VRegSpiller); 137 138 /// \brief Postprocessing before final spilling. Sets basic block "live in" 139 /// variables. 140 void finalizeAlloc(MachineFunction &MF, LiveIntervals &LIS, 141 VirtRegMap &VRM) const; 142 143 }; 144 145 char RegAllocPBQP::ID = 0; 146 147 /// @brief Set spill costs for each node in the PBQP reg-alloc graph. 148 class SpillCosts : public PBQPRAConstraint { 149 public: 150 void apply(PBQPRAGraph &G) override { 151 LiveIntervals &LIS = G.getMetadata().LIS; 152 153 // A minimum spill costs, so that register constraints can can be set 154 // without normalization in the [0.0:MinSpillCost( interval. 155 const PBQP::PBQPNum MinSpillCost = 10.0; 156 157 for (auto NId : G.nodeIds()) { 158 PBQP::PBQPNum SpillCost = 159 LIS.getInterval(G.getNodeMetadata(NId).getVReg()).weight; 160 if (SpillCost == 0.0) 161 SpillCost = std::numeric_limits<PBQP::PBQPNum>::min(); 162 else 163 SpillCost += MinSpillCost; 164 PBQPRAGraph::RawVector NodeCosts(G.getNodeCosts(NId)); 165 NodeCosts[PBQP::RegAlloc::getSpillOptionIdx()] = SpillCost; 166 G.setNodeCosts(NId, std::move(NodeCosts)); 167 } 168 } 169 }; 170 171 /// @brief Add interference edges between overlapping vregs. 172 class Interference : public PBQPRAConstraint { 173 private: 174 175 typedef const PBQP::RegAlloc::AllowedRegVector* AllowedRegVecPtr; 176 typedef std::pair<AllowedRegVecPtr, AllowedRegVecPtr> IMatrixKey; 177 typedef DenseMap<IMatrixKey, PBQPRAGraph::MatrixPtr> IMatrixCache; 178 179 // Holds (Interval, CurrentSegmentID, and NodeId). The first two are required 180 // for the fast interference graph construction algorithm. The last is there 181 // to save us from looking up node ids via the VRegToNode map in the graph 182 // metadata. 183 typedef std::tuple<LiveInterval*, size_t, PBQP::GraphBase::NodeId> 184 IntervalInfo; 185 186 static SlotIndex getStartPoint(const IntervalInfo &I) { 187 return std::get<0>(I)->segments[std::get<1>(I)].start; 188 } 189 190 static SlotIndex getEndPoint(const IntervalInfo &I) { 191 return std::get<0>(I)->segments[std::get<1>(I)].end; 192 } 193 194 static PBQP::GraphBase::NodeId getNodeId(const IntervalInfo &I) { 195 return std::get<2>(I); 196 } 197 198 static bool lowestStartPoint(const IntervalInfo &I1, 199 const IntervalInfo &I2) { 200 // Condition reversed because priority queue has the *highest* element at 201 // the front, rather than the lowest. 202 return getStartPoint(I1) > getStartPoint(I2); 203 } 204 205 static bool lowestEndPoint(const IntervalInfo &I1, 206 const IntervalInfo &I2) { 207 SlotIndex E1 = getEndPoint(I1); 208 SlotIndex E2 = getEndPoint(I2); 209 210 if (E1 < E2) 211 return true; 212 213 if (E1 > E2) 214 return false; 215 216 // If two intervals end at the same point, we need a way to break the tie or 217 // the set will assume they're actually equal and refuse to insert a 218 // "duplicate". Just compare the vregs - fast and guaranteed unique. 219 return std::get<0>(I1)->reg < std::get<0>(I2)->reg; 220 } 221 222 static bool isAtLastSegment(const IntervalInfo &I) { 223 return std::get<1>(I) == std::get<0>(I)->size() - 1; 224 } 225 226 static IntervalInfo nextSegment(const IntervalInfo &I) { 227 return std::make_tuple(std::get<0>(I), std::get<1>(I) + 1, std::get<2>(I)); 228 } 229 230 public: 231 232 void apply(PBQPRAGraph &G) override { 233 // The following is loosely based on the linear scan algorithm introduced in 234 // "Linear Scan Register Allocation" by Poletto and Sarkar. This version 235 // isn't linear, because the size of the active set isn't bound by the 236 // number of registers, but rather the size of the largest clique in the 237 // graph. Still, we expect this to be better than N^2. 238 LiveIntervals &LIS = G.getMetadata().LIS; 239 240 // Interferenc matrices are incredibly regular - they're only a function of 241 // the allowed sets, so we cache them to avoid the overhead of constructing 242 // and uniquing them. 243 IMatrixCache C; 244 245 typedef std::set<IntervalInfo, decltype(&lowestEndPoint)> IntervalSet; 246 typedef std::priority_queue<IntervalInfo, std::vector<IntervalInfo>, 247 decltype(&lowestStartPoint)> IntervalQueue; 248 IntervalSet Active(lowestEndPoint); 249 IntervalQueue Inactive(lowestStartPoint); 250 251 // Start by building the inactive set. 252 for (auto NId : G.nodeIds()) { 253 unsigned VReg = G.getNodeMetadata(NId).getVReg(); 254 LiveInterval &LI = LIS.getInterval(VReg); 255 assert(!LI.empty() && "PBQP graph contains node for empty interval"); 256 Inactive.push(std::make_tuple(&LI, 0, NId)); 257 } 258 259 while (!Inactive.empty()) { 260 // Tentatively grab the "next" interval - this choice may be overriden 261 // below. 262 IntervalInfo Cur = Inactive.top(); 263 264 // Retire any active intervals that end before Cur starts. 265 IntervalSet::iterator RetireItr = Active.begin(); 266 while (RetireItr != Active.end() && 267 (getEndPoint(*RetireItr) <= getStartPoint(Cur))) { 268 // If this interval has subsequent segments, add the next one to the 269 // inactive list. 270 if (!isAtLastSegment(*RetireItr)) 271 Inactive.push(nextSegment(*RetireItr)); 272 273 ++RetireItr; 274 } 275 Active.erase(Active.begin(), RetireItr); 276 277 // One of the newly retired segments may actually start before the 278 // Cur segment, so re-grab the front of the inactive list. 279 Cur = Inactive.top(); 280 Inactive.pop(); 281 282 // At this point we know that Cur overlaps all active intervals. Add the 283 // interference edges. 284 PBQP::GraphBase::NodeId NId = getNodeId(Cur); 285 for (const auto &A : Active) { 286 PBQP::GraphBase::NodeId MId = getNodeId(A); 287 288 // Check that we haven't already added this edge 289 // FIXME: findEdge is expensive in the worst case (O(max_clique(G))). 290 // It might be better to replace this with a local bit-matrix. 291 if (G.findEdge(NId, MId) != PBQPRAGraph::invalidEdgeId()) 292 continue; 293 294 // This is a new edge - add it to the graph. 295 createInterferenceEdge(G, NId, MId, C); 296 } 297 298 // Finally, add Cur to the Active set. 299 Active.insert(Cur); 300 } 301 } 302 303 private: 304 305 void createInterferenceEdge(PBQPRAGraph &G, PBQPRAGraph::NodeId NId, 306 PBQPRAGraph::NodeId MId, IMatrixCache &C) { 307 308 const TargetRegisterInfo &TRI = 309 *G.getMetadata().MF.getSubtarget().getRegisterInfo(); 310 311 const auto &NRegs = G.getNodeMetadata(NId).getAllowedRegs(); 312 const auto &MRegs = G.getNodeMetadata(MId).getAllowedRegs(); 313 314 // Try looking the edge costs up in the IMatrixCache first. 315 IMatrixKey K(&NRegs, &MRegs); 316 IMatrixCache::iterator I = C.find(K); 317 if (I != C.end()) { 318 G.addEdgeBypassingCostAllocator(NId, MId, I->second); 319 return; 320 } 321 322 PBQPRAGraph::RawMatrix M(NRegs.size() + 1, MRegs.size() + 1, 0); 323 for (unsigned I = 0; I != NRegs.size(); ++I) { 324 unsigned PRegN = NRegs[I]; 325 for (unsigned J = 0; J != MRegs.size(); ++J) { 326 unsigned PRegM = MRegs[J]; 327 if (TRI.regsOverlap(PRegN, PRegM)) 328 M[I + 1][J + 1] = std::numeric_limits<PBQP::PBQPNum>::infinity(); 329 } 330 } 331 332 PBQPRAGraph::EdgeId EId = G.addEdge(NId, MId, std::move(M)); 333 C[K] = G.getEdgeCostsPtr(EId); 334 } 335 }; 336 337 338 class Coalescing : public PBQPRAConstraint { 339 public: 340 void apply(PBQPRAGraph &G) override { 341 MachineFunction &MF = G.getMetadata().MF; 342 MachineBlockFrequencyInfo &MBFI = G.getMetadata().MBFI; 343 CoalescerPair CP(*MF.getSubtarget().getRegisterInfo()); 344 345 // Scan the machine function and add a coalescing cost whenever CoalescerPair 346 // gives the Ok. 347 for (const auto &MBB : MF) { 348 for (const auto &MI : MBB) { 349 350 // Skip not-coalescable or already coalesced copies. 351 if (!CP.setRegisters(&MI) || CP.getSrcReg() == CP.getDstReg()) 352 continue; 353 354 unsigned DstReg = CP.getDstReg(); 355 unsigned SrcReg = CP.getSrcReg(); 356 357 const float Scale = 1.0f / MBFI.getEntryFreq(); 358 PBQP::PBQPNum CBenefit = MBFI.getBlockFreq(&MBB).getFrequency() * Scale; 359 360 if (CP.isPhys()) { 361 if (!MF.getRegInfo().isAllocatable(DstReg)) 362 continue; 363 364 PBQPRAGraph::NodeId NId = G.getMetadata().getNodeIdForVReg(SrcReg); 365 366 const PBQPRAGraph::NodeMetadata::AllowedRegVector &Allowed = 367 G.getNodeMetadata(NId).getAllowedRegs(); 368 369 unsigned PRegOpt = 0; 370 while (PRegOpt < Allowed.size() && Allowed[PRegOpt] != DstReg) 371 ++PRegOpt; 372 373 if (PRegOpt < Allowed.size()) { 374 PBQPRAGraph::RawVector NewCosts(G.getNodeCosts(NId)); 375 NewCosts[PRegOpt + 1] -= CBenefit; 376 G.setNodeCosts(NId, std::move(NewCosts)); 377 } 378 } else { 379 PBQPRAGraph::NodeId N1Id = G.getMetadata().getNodeIdForVReg(DstReg); 380 PBQPRAGraph::NodeId N2Id = G.getMetadata().getNodeIdForVReg(SrcReg); 381 const PBQPRAGraph::NodeMetadata::AllowedRegVector *Allowed1 = 382 &G.getNodeMetadata(N1Id).getAllowedRegs(); 383 const PBQPRAGraph::NodeMetadata::AllowedRegVector *Allowed2 = 384 &G.getNodeMetadata(N2Id).getAllowedRegs(); 385 386 PBQPRAGraph::EdgeId EId = G.findEdge(N1Id, N2Id); 387 if (EId == G.invalidEdgeId()) { 388 PBQPRAGraph::RawMatrix Costs(Allowed1->size() + 1, 389 Allowed2->size() + 1, 0); 390 addVirtRegCoalesce(Costs, *Allowed1, *Allowed2, CBenefit); 391 G.addEdge(N1Id, N2Id, std::move(Costs)); 392 } else { 393 if (G.getEdgeNode1Id(EId) == N2Id) { 394 std::swap(N1Id, N2Id); 395 std::swap(Allowed1, Allowed2); 396 } 397 PBQPRAGraph::RawMatrix Costs(G.getEdgeCosts(EId)); 398 addVirtRegCoalesce(Costs, *Allowed1, *Allowed2, CBenefit); 399 G.setEdgeCosts(EId, std::move(Costs)); 400 } 401 } 402 } 403 } 404 } 405 406 private: 407 408 void addVirtRegCoalesce( 409 PBQPRAGraph::RawMatrix &CostMat, 410 const PBQPRAGraph::NodeMetadata::AllowedRegVector &Allowed1, 411 const PBQPRAGraph::NodeMetadata::AllowedRegVector &Allowed2, 412 PBQP::PBQPNum Benefit) { 413 assert(CostMat.getRows() == Allowed1.size() + 1 && "Size mismatch."); 414 assert(CostMat.getCols() == Allowed2.size() + 1 && "Size mismatch."); 415 for (unsigned I = 0; I != Allowed1.size(); ++I) { 416 unsigned PReg1 = Allowed1[I]; 417 for (unsigned J = 0; J != Allowed2.size(); ++J) { 418 unsigned PReg2 = Allowed2[J]; 419 if (PReg1 == PReg2) 420 CostMat[I + 1][J + 1] -= Benefit; 421 } 422 } 423 } 424 425 }; 426 427 } // End anonymous namespace. 428 429 // Out-of-line destructor/anchor for PBQPRAConstraint. 430 PBQPRAConstraint::~PBQPRAConstraint() {} 431 void PBQPRAConstraint::anchor() {} 432 void PBQPRAConstraintList::anchor() {} 433 434 void RegAllocPBQP::getAnalysisUsage(AnalysisUsage &au) const { 435 au.setPreservesCFG(); 436 au.addRequired<AliasAnalysis>(); 437 au.addPreserved<AliasAnalysis>(); 438 au.addRequired<SlotIndexes>(); 439 au.addPreserved<SlotIndexes>(); 440 au.addRequired<LiveIntervals>(); 441 au.addPreserved<LiveIntervals>(); 442 //au.addRequiredID(SplitCriticalEdgesID); 443 if (customPassID) 444 au.addRequiredID(*customPassID); 445 au.addRequired<LiveStacks>(); 446 au.addPreserved<LiveStacks>(); 447 au.addRequired<MachineBlockFrequencyInfo>(); 448 au.addPreserved<MachineBlockFrequencyInfo>(); 449 au.addRequired<MachineLoopInfo>(); 450 au.addPreserved<MachineLoopInfo>(); 451 au.addRequired<MachineDominatorTree>(); 452 au.addPreserved<MachineDominatorTree>(); 453 au.addRequired<VirtRegMap>(); 454 au.addPreserved<VirtRegMap>(); 455 MachineFunctionPass::getAnalysisUsage(au); 456 } 457 458 void RegAllocPBQP::findVRegIntervalsToAlloc(const MachineFunction &MF, 459 LiveIntervals &LIS) { 460 const MachineRegisterInfo &MRI = MF.getRegInfo(); 461 462 // Iterate over all live ranges. 463 for (unsigned I = 0, E = MRI.getNumVirtRegs(); I != E; ++I) { 464 unsigned Reg = TargetRegisterInfo::index2VirtReg(I); 465 if (MRI.reg_nodbg_empty(Reg)) 466 continue; 467 LiveInterval &LI = LIS.getInterval(Reg); 468 469 // If this live interval is non-empty we will use pbqp to allocate it. 470 // Empty intervals we allocate in a simple post-processing stage in 471 // finalizeAlloc. 472 if (!LI.empty()) { 473 VRegsToAlloc.insert(LI.reg); 474 } else { 475 EmptyIntervalVRegs.insert(LI.reg); 476 } 477 } 478 } 479 480 static bool isACalleeSavedRegister(unsigned reg, const TargetRegisterInfo &TRI, 481 const MachineFunction &MF) { 482 const MCPhysReg *CSR = TRI.getCalleeSavedRegs(&MF); 483 for (unsigned i = 0; CSR[i] != 0; ++i) 484 if (TRI.regsOverlap(reg, CSR[i])) 485 return true; 486 return false; 487 } 488 489 void RegAllocPBQP::initializeGraph(PBQPRAGraph &G) { 490 MachineFunction &MF = G.getMetadata().MF; 491 492 LiveIntervals &LIS = G.getMetadata().LIS; 493 const MachineRegisterInfo &MRI = G.getMetadata().MF.getRegInfo(); 494 const TargetRegisterInfo &TRI = 495 *G.getMetadata().MF.getSubtarget().getRegisterInfo(); 496 497 for (auto VReg : VRegsToAlloc) { 498 const TargetRegisterClass *TRC = MRI.getRegClass(VReg); 499 LiveInterval &VRegLI = LIS.getInterval(VReg); 500 501 // Record any overlaps with regmask operands. 502 BitVector RegMaskOverlaps; 503 LIS.checkRegMaskInterference(VRegLI, RegMaskOverlaps); 504 505 // Compute an initial allowed set for the current vreg. 506 std::vector<unsigned> VRegAllowed; 507 ArrayRef<MCPhysReg> RawPRegOrder = TRC->getRawAllocationOrder(MF); 508 for (unsigned I = 0; I != RawPRegOrder.size(); ++I) { 509 unsigned PReg = RawPRegOrder[I]; 510 if (MRI.isReserved(PReg)) 511 continue; 512 513 // vregLI crosses a regmask operand that clobbers preg. 514 if (!RegMaskOverlaps.empty() && !RegMaskOverlaps.test(PReg)) 515 continue; 516 517 // vregLI overlaps fixed regunit interference. 518 bool Interference = false; 519 for (MCRegUnitIterator Units(PReg, &TRI); Units.isValid(); ++Units) { 520 if (VRegLI.overlaps(LIS.getRegUnit(*Units))) { 521 Interference = true; 522 break; 523 } 524 } 525 if (Interference) 526 continue; 527 528 // preg is usable for this virtual register. 529 VRegAllowed.push_back(PReg); 530 } 531 532 PBQPRAGraph::RawVector NodeCosts(VRegAllowed.size() + 1, 0); 533 534 // Tweak cost of callee saved registers, as using then force spilling and 535 // restoring them. This would only happen in the prologue / epilogue though. 536 for (unsigned i = 0; i != VRegAllowed.size(); ++i) 537 if (isACalleeSavedRegister(VRegAllowed[i], TRI, MF)) 538 NodeCosts[1 + i] += 1.0; 539 540 PBQPRAGraph::NodeId NId = G.addNode(std::move(NodeCosts)); 541 G.getNodeMetadata(NId).setVReg(VReg); 542 G.getNodeMetadata(NId).setAllowedRegs( 543 G.getMetadata().getAllowedRegs(std::move(VRegAllowed))); 544 G.getMetadata().setNodeIdForVReg(VReg, NId); 545 } 546 } 547 548 bool RegAllocPBQP::mapPBQPToRegAlloc(const PBQPRAGraph &G, 549 const PBQP::Solution &Solution, 550 VirtRegMap &VRM, 551 Spiller &VRegSpiller) { 552 MachineFunction &MF = G.getMetadata().MF; 553 LiveIntervals &LIS = G.getMetadata().LIS; 554 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 555 (void)TRI; 556 557 // Set to true if we have any spills 558 bool AnotherRoundNeeded = false; 559 560 // Clear the existing allocation. 561 VRM.clearAllVirt(); 562 563 // Iterate over the nodes mapping the PBQP solution to a register 564 // assignment. 565 for (auto NId : G.nodeIds()) { 566 unsigned VReg = G.getNodeMetadata(NId).getVReg(); 567 unsigned AllocOption = Solution.getSelection(NId); 568 569 if (AllocOption != PBQP::RegAlloc::getSpillOptionIdx()) { 570 unsigned PReg = G.getNodeMetadata(NId).getAllowedRegs()[AllocOption - 1]; 571 DEBUG(dbgs() << "VREG " << PrintReg(VReg, &TRI) << " -> " 572 << TRI.getName(PReg) << "\n"); 573 assert(PReg != 0 && "Invalid preg selected."); 574 VRM.assignVirt2Phys(VReg, PReg); 575 } else { 576 VRegsToAlloc.erase(VReg); 577 SmallVector<unsigned, 8> NewSpills; 578 LiveRangeEdit LRE(&LIS.getInterval(VReg), NewSpills, MF, LIS, &VRM); 579 VRegSpiller.spill(LRE); 580 581 DEBUG(dbgs() << "VREG " << PrintReg(VReg, &TRI) << " -> SPILLED (Cost: " 582 << LRE.getParent().weight << ", New vregs: "); 583 584 // Copy any newly inserted live intervals into the list of regs to 585 // allocate. 586 for (LiveRangeEdit::iterator I = LRE.begin(), E = LRE.end(); 587 I != E; ++I) { 588 LiveInterval &LI = LIS.getInterval(*I); 589 assert(!LI.empty() && "Empty spill range."); 590 DEBUG(dbgs() << PrintReg(LI.reg, &TRI) << " "); 591 VRegsToAlloc.insert(LI.reg); 592 } 593 594 DEBUG(dbgs() << ")\n"); 595 596 // We need another round if spill intervals were added. 597 AnotherRoundNeeded |= !LRE.empty(); 598 } 599 } 600 601 return !AnotherRoundNeeded; 602 } 603 604 void RegAllocPBQP::finalizeAlloc(MachineFunction &MF, 605 LiveIntervals &LIS, 606 VirtRegMap &VRM) const { 607 MachineRegisterInfo &MRI = MF.getRegInfo(); 608 609 // First allocate registers for the empty intervals. 610 for (RegSet::const_iterator 611 I = EmptyIntervalVRegs.begin(), E = EmptyIntervalVRegs.end(); 612 I != E; ++I) { 613 LiveInterval &LI = LIS.getInterval(*I); 614 615 unsigned PReg = MRI.getSimpleHint(LI.reg); 616 617 if (PReg == 0) { 618 const TargetRegisterClass &RC = *MRI.getRegClass(LI.reg); 619 PReg = RC.getRawAllocationOrder(MF).front(); 620 } 621 622 VRM.assignVirt2Phys(LI.reg, PReg); 623 } 624 } 625 626 static inline float normalizePBQPSpillWeight(float UseDefFreq, unsigned Size, 627 unsigned NumInstr) { 628 // All intervals have a spill weight that is mostly proportional to the number 629 // of uses, with uses in loops having a bigger weight. 630 return NumInstr * normalizeSpillWeight(UseDefFreq, Size, 1); 631 } 632 633 bool RegAllocPBQP::runOnMachineFunction(MachineFunction &MF) { 634 LiveIntervals &LIS = getAnalysis<LiveIntervals>(); 635 MachineBlockFrequencyInfo &MBFI = 636 getAnalysis<MachineBlockFrequencyInfo>(); 637 638 calculateSpillWeightsAndHints(LIS, MF, getAnalysis<MachineLoopInfo>(), MBFI, 639 normalizePBQPSpillWeight); 640 641 VirtRegMap &VRM = getAnalysis<VirtRegMap>(); 642 643 std::unique_ptr<Spiller> VRegSpiller(createInlineSpiller(*this, MF, VRM)); 644 645 MF.getRegInfo().freezeReservedRegs(MF); 646 647 DEBUG(dbgs() << "PBQP Register Allocating for " << MF.getName() << "\n"); 648 649 // Allocator main loop: 650 // 651 // * Map current regalloc problem to a PBQP problem 652 // * Solve the PBQP problem 653 // * Map the solution back to a register allocation 654 // * Spill if necessary 655 // 656 // This process is continued till no more spills are generated. 657 658 // Find the vreg intervals in need of allocation. 659 findVRegIntervalsToAlloc(MF, LIS); 660 661 #ifndef NDEBUG 662 const Function &F = *MF.getFunction(); 663 std::string FullyQualifiedName = 664 F.getParent()->getModuleIdentifier() + "." + F.getName().str(); 665 #endif 666 667 // If there are non-empty intervals allocate them using pbqp. 668 if (!VRegsToAlloc.empty()) { 669 670 const TargetSubtargetInfo &Subtarget = MF.getSubtarget(); 671 std::unique_ptr<PBQPRAConstraintList> ConstraintsRoot = 672 llvm::make_unique<PBQPRAConstraintList>(); 673 ConstraintsRoot->addConstraint(llvm::make_unique<SpillCosts>()); 674 ConstraintsRoot->addConstraint(llvm::make_unique<Interference>()); 675 if (PBQPCoalescing) 676 ConstraintsRoot->addConstraint(llvm::make_unique<Coalescing>()); 677 ConstraintsRoot->addConstraint(Subtarget.getCustomPBQPConstraints()); 678 679 bool PBQPAllocComplete = false; 680 unsigned Round = 0; 681 682 while (!PBQPAllocComplete) { 683 DEBUG(dbgs() << " PBQP Regalloc round " << Round << ":\n"); 684 685 PBQPRAGraph G(PBQPRAGraph::GraphMetadata(MF, LIS, MBFI)); 686 initializeGraph(G); 687 ConstraintsRoot->apply(G); 688 689 #ifndef NDEBUG 690 if (PBQPDumpGraphs) { 691 std::ostringstream RS; 692 RS << Round; 693 std::string GraphFileName = FullyQualifiedName + "." + RS.str() + 694 ".pbqpgraph"; 695 std::error_code EC; 696 raw_fd_ostream OS(GraphFileName, EC, sys::fs::F_Text); 697 DEBUG(dbgs() << "Dumping graph for round " << Round << " to \"" 698 << GraphFileName << "\"\n"); 699 G.dumpToStream(OS); 700 } 701 #endif 702 703 PBQP::Solution Solution = PBQP::RegAlloc::solve(G); 704 PBQPAllocComplete = mapPBQPToRegAlloc(G, Solution, VRM, *VRegSpiller); 705 ++Round; 706 } 707 } 708 709 // Finalise allocation, allocate empty ranges. 710 finalizeAlloc(MF, LIS, VRM); 711 VRegsToAlloc.clear(); 712 EmptyIntervalVRegs.clear(); 713 714 DEBUG(dbgs() << "Post alloc VirtRegMap:\n" << VRM << "\n"); 715 716 return true; 717 } 718 719 FunctionPass *llvm::createPBQPRegisterAllocator(char *customPassID) { 720 return new RegAllocPBQP(customPassID); 721 } 722 723 FunctionPass* llvm::createDefaultPBQPRegisterAllocator() { 724 return createPBQPRegisterAllocator(); 725 } 726 727 #undef DEBUG_TYPE 728