1 //===-- RegisterPressure.cpp - Dynamic Register Pressure ------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements the RegisterPressure class which can be used to track 11 // MachineInstr level register pressure. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "llvm/CodeGen/RegisterPressure.h" 16 #include "llvm/CodeGen/LiveInterval.h" 17 #include "llvm/CodeGen/LiveIntervalAnalysis.h" 18 #include "llvm/CodeGen/MachineRegisterInfo.h" 19 #include "llvm/CodeGen/RegisterClassInfo.h" 20 #include "llvm/Support/Debug.h" 21 #include "llvm/Support/raw_ostream.h" 22 #include "llvm/Target/TargetMachine.h" 23 24 using namespace llvm; 25 26 /// Increase pressure for each pressure set provided by TargetRegisterInfo. 27 static void increaseSetPressure(std::vector<unsigned> &CurrSetPressure, 28 PSetIterator PSetI) { 29 unsigned Weight = PSetI.getWeight(); 30 for (; PSetI.isValid(); ++PSetI) 31 CurrSetPressure[*PSetI] += Weight; 32 } 33 34 /// Decrease pressure for each pressure set provided by TargetRegisterInfo. 35 static void decreaseSetPressure(std::vector<unsigned> &CurrSetPressure, 36 PSetIterator PSetI) { 37 unsigned Weight = PSetI.getWeight(); 38 for (; PSetI.isValid(); ++PSetI) { 39 assert(CurrSetPressure[*PSetI] >= Weight && "register pressure underflow"); 40 CurrSetPressure[*PSetI] -= Weight; 41 } 42 } 43 44 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 45 void llvm::dumpRegSetPressure(ArrayRef<unsigned> SetPressure, 46 const TargetRegisterInfo *TRI) { 47 bool Empty = true; 48 for (unsigned i = 0, e = SetPressure.size(); i < e; ++i) { 49 if (SetPressure[i] != 0) { 50 dbgs() << TRI->getRegPressureSetName(i) << "=" << SetPressure[i] << '\n'; 51 Empty = false; 52 } 53 } 54 if (Empty) 55 dbgs() << "\n"; 56 } 57 58 void RegisterPressure::dump(const TargetRegisterInfo *TRI) const { 59 dbgs() << "Max Pressure: "; 60 dumpRegSetPressure(MaxSetPressure, TRI); 61 dbgs() << "Live In: "; 62 for (unsigned i = 0, e = LiveInRegs.size(); i < e; ++i) 63 dbgs() << PrintReg(LiveInRegs[i], TRI) << " "; 64 dbgs() << '\n'; 65 dbgs() << "Live Out: "; 66 for (unsigned i = 0, e = LiveOutRegs.size(); i < e; ++i) 67 dbgs() << PrintReg(LiveOutRegs[i], TRI) << " "; 68 dbgs() << '\n'; 69 } 70 71 void RegPressureTracker::dump() const { 72 if (!isTopClosed() || !isBottomClosed()) { 73 dbgs() << "Curr Pressure: "; 74 dumpRegSetPressure(CurrSetPressure, TRI); 75 } 76 P.dump(TRI); 77 } 78 #endif 79 80 /// Increase the current pressure as impacted by these registers and bump 81 /// the high water mark if needed. 82 void RegPressureTracker::increaseRegPressure(ArrayRef<unsigned> RegUnits) { 83 for (unsigned i = 0, e = RegUnits.size(); i != e; ++i) { 84 PSetIterator PSetI = MRI->getPressureSets(RegUnits[i]); 85 unsigned Weight = PSetI.getWeight(); 86 for (; PSetI.isValid(); ++PSetI) { 87 CurrSetPressure[*PSetI] += Weight; 88 if (CurrSetPressure[*PSetI] > P.MaxSetPressure[*PSetI]) { 89 P.MaxSetPressure[*PSetI] = CurrSetPressure[*PSetI]; 90 } 91 } 92 } 93 } 94 95 /// Simply decrease the current pressure as impacted by these registers. 96 void RegPressureTracker::decreaseRegPressure(ArrayRef<unsigned> RegUnits) { 97 for (unsigned I = 0, E = RegUnits.size(); I != E; ++I) 98 decreaseSetPressure(CurrSetPressure, MRI->getPressureSets(RegUnits[I])); 99 } 100 101 /// Clear the result so it can be used for another round of pressure tracking. 102 void IntervalPressure::reset() { 103 TopIdx = BottomIdx = SlotIndex(); 104 MaxSetPressure.clear(); 105 LiveInRegs.clear(); 106 LiveOutRegs.clear(); 107 } 108 109 /// Clear the result so it can be used for another round of pressure tracking. 110 void RegionPressure::reset() { 111 TopPos = BottomPos = MachineBasicBlock::const_iterator(); 112 MaxSetPressure.clear(); 113 LiveInRegs.clear(); 114 LiveOutRegs.clear(); 115 } 116 117 /// If the current top is not less than or equal to the next index, open it. 118 /// We happen to need the SlotIndex for the next top for pressure update. 119 void IntervalPressure::openTop(SlotIndex NextTop) { 120 if (TopIdx <= NextTop) 121 return; 122 TopIdx = SlotIndex(); 123 LiveInRegs.clear(); 124 } 125 126 /// If the current top is the previous instruction (before receding), open it. 127 void RegionPressure::openTop(MachineBasicBlock::const_iterator PrevTop) { 128 if (TopPos != PrevTop) 129 return; 130 TopPos = MachineBasicBlock::const_iterator(); 131 LiveInRegs.clear(); 132 } 133 134 /// If the current bottom is not greater than the previous index, open it. 135 void IntervalPressure::openBottom(SlotIndex PrevBottom) { 136 if (BottomIdx > PrevBottom) 137 return; 138 BottomIdx = SlotIndex(); 139 LiveInRegs.clear(); 140 } 141 142 /// If the current bottom is the previous instr (before advancing), open it. 143 void RegionPressure::openBottom(MachineBasicBlock::const_iterator PrevBottom) { 144 if (BottomPos != PrevBottom) 145 return; 146 BottomPos = MachineBasicBlock::const_iterator(); 147 LiveInRegs.clear(); 148 } 149 150 const LiveInterval *RegPressureTracker::getInterval(unsigned Reg) const { 151 if (TargetRegisterInfo::isVirtualRegister(Reg)) 152 return &LIS->getInterval(Reg); 153 return LIS->getCachedRegUnit(Reg); 154 } 155 156 void RegPressureTracker::reset() { 157 MBB = 0; 158 LIS = 0; 159 160 CurrSetPressure.clear(); 161 LiveThruPressure.clear(); 162 P.MaxSetPressure.clear(); 163 164 if (RequireIntervals) 165 static_cast<IntervalPressure&>(P).reset(); 166 else 167 static_cast<RegionPressure&>(P).reset(); 168 169 LiveRegs.PhysRegs.clear(); 170 LiveRegs.VirtRegs.clear(); 171 UntiedDefs.clear(); 172 } 173 174 /// Setup the RegPressureTracker. 175 /// 176 /// TODO: Add support for pressure without LiveIntervals. 177 void RegPressureTracker::init(const MachineFunction *mf, 178 const RegisterClassInfo *rci, 179 const LiveIntervals *lis, 180 const MachineBasicBlock *mbb, 181 MachineBasicBlock::const_iterator pos, 182 bool ShouldTrackUntiedDefs) 183 { 184 reset(); 185 186 MF = mf; 187 TRI = MF->getTarget().getRegisterInfo(); 188 RCI = rci; 189 MRI = &MF->getRegInfo(); 190 MBB = mbb; 191 TrackUntiedDefs = ShouldTrackUntiedDefs; 192 193 if (RequireIntervals) { 194 assert(lis && "IntervalPressure requires LiveIntervals"); 195 LIS = lis; 196 } 197 198 CurrPos = pos; 199 CurrSetPressure.assign(TRI->getNumRegPressureSets(), 0); 200 201 P.MaxSetPressure = CurrSetPressure; 202 203 LiveRegs.PhysRegs.setUniverse(TRI->getNumRegs()); 204 LiveRegs.VirtRegs.setUniverse(MRI->getNumVirtRegs()); 205 if (TrackUntiedDefs) 206 UntiedDefs.setUniverse(MRI->getNumVirtRegs()); 207 } 208 209 /// Does this pressure result have a valid top position and live ins. 210 bool RegPressureTracker::isTopClosed() const { 211 if (RequireIntervals) 212 return static_cast<IntervalPressure&>(P).TopIdx.isValid(); 213 return (static_cast<RegionPressure&>(P).TopPos == 214 MachineBasicBlock::const_iterator()); 215 } 216 217 /// Does this pressure result have a valid bottom position and live outs. 218 bool RegPressureTracker::isBottomClosed() const { 219 if (RequireIntervals) 220 return static_cast<IntervalPressure&>(P).BottomIdx.isValid(); 221 return (static_cast<RegionPressure&>(P).BottomPos == 222 MachineBasicBlock::const_iterator()); 223 } 224 225 226 SlotIndex RegPressureTracker::getCurrSlot() const { 227 MachineBasicBlock::const_iterator IdxPos = CurrPos; 228 while (IdxPos != MBB->end() && IdxPos->isDebugValue()) 229 ++IdxPos; 230 if (IdxPos == MBB->end()) 231 return LIS->getMBBEndIdx(MBB); 232 return LIS->getInstructionIndex(IdxPos).getRegSlot(); 233 } 234 235 /// Set the boundary for the top of the region and summarize live ins. 236 void RegPressureTracker::closeTop() { 237 if (RequireIntervals) 238 static_cast<IntervalPressure&>(P).TopIdx = getCurrSlot(); 239 else 240 static_cast<RegionPressure&>(P).TopPos = CurrPos; 241 242 assert(P.LiveInRegs.empty() && "inconsistent max pressure result"); 243 P.LiveInRegs.reserve(LiveRegs.PhysRegs.size() + LiveRegs.VirtRegs.size()); 244 P.LiveInRegs.append(LiveRegs.PhysRegs.begin(), LiveRegs.PhysRegs.end()); 245 for (SparseSet<unsigned>::const_iterator I = 246 LiveRegs.VirtRegs.begin(), E = LiveRegs.VirtRegs.end(); I != E; ++I) 247 P.LiveInRegs.push_back(*I); 248 std::sort(P.LiveInRegs.begin(), P.LiveInRegs.end()); 249 P.LiveInRegs.erase(std::unique(P.LiveInRegs.begin(), P.LiveInRegs.end()), 250 P.LiveInRegs.end()); 251 } 252 253 /// Set the boundary for the bottom of the region and summarize live outs. 254 void RegPressureTracker::closeBottom() { 255 if (RequireIntervals) 256 static_cast<IntervalPressure&>(P).BottomIdx = getCurrSlot(); 257 else 258 static_cast<RegionPressure&>(P).BottomPos = CurrPos; 259 260 assert(P.LiveOutRegs.empty() && "inconsistent max pressure result"); 261 P.LiveOutRegs.reserve(LiveRegs.PhysRegs.size() + LiveRegs.VirtRegs.size()); 262 P.LiveOutRegs.append(LiveRegs.PhysRegs.begin(), LiveRegs.PhysRegs.end()); 263 for (SparseSet<unsigned>::const_iterator I = 264 LiveRegs.VirtRegs.begin(), E = LiveRegs.VirtRegs.end(); I != E; ++I) 265 P.LiveOutRegs.push_back(*I); 266 std::sort(P.LiveOutRegs.begin(), P.LiveOutRegs.end()); 267 P.LiveOutRegs.erase(std::unique(P.LiveOutRegs.begin(), P.LiveOutRegs.end()), 268 P.LiveOutRegs.end()); 269 } 270 271 /// Finalize the region boundaries and record live ins and live outs. 272 void RegPressureTracker::closeRegion() { 273 if (!isTopClosed() && !isBottomClosed()) { 274 assert(LiveRegs.PhysRegs.empty() && LiveRegs.VirtRegs.empty() && 275 "no region boundary"); 276 return; 277 } 278 if (!isBottomClosed()) 279 closeBottom(); 280 else if (!isTopClosed()) 281 closeTop(); 282 // If both top and bottom are closed, do nothing. 283 } 284 285 /// The register tracker is unaware of global liveness so ignores normal 286 /// live-thru ranges. However, two-address or coalesced chains can also lead 287 /// to live ranges with no holes. Count these to inform heuristics that we 288 /// can never drop below this pressure. 289 void RegPressureTracker::initLiveThru(const RegPressureTracker &RPTracker) { 290 LiveThruPressure.assign(TRI->getNumRegPressureSets(), 0); 291 assert(isBottomClosed() && "need bottom-up tracking to intialize."); 292 for (unsigned i = 0, e = P.LiveOutRegs.size(); i < e; ++i) { 293 unsigned Reg = P.LiveOutRegs[i]; 294 if (TargetRegisterInfo::isVirtualRegister(Reg) 295 && !RPTracker.hasUntiedDef(Reg)) { 296 increaseSetPressure(LiveThruPressure, MRI->getPressureSets(Reg)); 297 } 298 } 299 } 300 301 /// \brief Convenient wrapper for checking membership in RegisterOperands. 302 /// (std::count() doesn't have an early exit). 303 static bool containsReg(ArrayRef<unsigned> RegUnits, unsigned RegUnit) { 304 return std::find(RegUnits.begin(), RegUnits.end(), RegUnit) != RegUnits.end(); 305 } 306 307 /// Collect this instruction's unique uses and defs into SmallVectors for 308 /// processing defs and uses in order. 309 /// 310 /// FIXME: always ignore tied opers 311 class RegisterOperands { 312 const TargetRegisterInfo *TRI; 313 const MachineRegisterInfo *MRI; 314 bool IgnoreDead; 315 316 public: 317 SmallVector<unsigned, 8> Uses; 318 SmallVector<unsigned, 8> Defs; 319 SmallVector<unsigned, 8> DeadDefs; 320 321 RegisterOperands(const TargetRegisterInfo *tri, 322 const MachineRegisterInfo *mri, bool ID = false): 323 TRI(tri), MRI(mri), IgnoreDead(ID) {} 324 325 /// Push this operand's register onto the correct vector. 326 void collect(const MachineOperand &MO) { 327 if (!MO.isReg() || !MO.getReg()) 328 return; 329 if (MO.readsReg()) 330 pushRegUnits(MO.getReg(), Uses); 331 if (MO.isDef()) { 332 if (MO.isDead()) { 333 if (!IgnoreDead) 334 pushRegUnits(MO.getReg(), DeadDefs); 335 } 336 else 337 pushRegUnits(MO.getReg(), Defs); 338 } 339 } 340 341 protected: 342 void pushRegUnits(unsigned Reg, SmallVectorImpl<unsigned> &RegUnits) { 343 if (TargetRegisterInfo::isVirtualRegister(Reg)) { 344 if (containsReg(RegUnits, Reg)) 345 return; 346 RegUnits.push_back(Reg); 347 } 348 else if (MRI->isAllocatable(Reg)) { 349 for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units) { 350 if (containsReg(RegUnits, *Units)) 351 continue; 352 RegUnits.push_back(*Units); 353 } 354 } 355 } 356 }; 357 358 /// Collect physical and virtual register operands. 359 static void collectOperands(const MachineInstr *MI, 360 RegisterOperands &RegOpers) { 361 for (ConstMIBundleOperands OperI(MI); OperI.isValid(); ++OperI) 362 RegOpers.collect(*OperI); 363 364 // Remove redundant physreg dead defs. 365 SmallVectorImpl<unsigned>::iterator I = 366 std::remove_if(RegOpers.DeadDefs.begin(), RegOpers.DeadDefs.end(), 367 std::bind1st(std::ptr_fun(containsReg), RegOpers.Defs)); 368 RegOpers.DeadDefs.erase(I, RegOpers.DeadDefs.end()); 369 } 370 371 /// Initialize an array of N PressureDiffs. 372 void PressureDiffs::init(unsigned N) { 373 Size = N; 374 if (N <= Max) { 375 memset(PDiffArray, 0, N * sizeof(PressureDiff)); 376 return; 377 } 378 Max = Size; 379 free(PDiffArray); 380 PDiffArray = reinterpret_cast<PressureDiff*>(calloc(N, sizeof(PressureDiff))); 381 } 382 383 /// Add a change in pressure to the pressure diff of a given instruction. 384 void PressureDiff::addPressureChange(unsigned RegUnit, bool IsDec, 385 const MachineRegisterInfo *MRI) { 386 PSetIterator PSetI = MRI->getPressureSets(RegUnit); 387 int Weight = IsDec ? -PSetI.getWeight() : PSetI.getWeight(); 388 for (; PSetI.isValid(); ++PSetI) { 389 // Find an existing entry in the pressure diff for this PSet. 390 PressureDiff::iterator I = begin(), E = end(); 391 for (; I != E && I->isValid(); ++I) { 392 if (I->getPSet() >= *PSetI) 393 break; 394 } 395 // If all pressure sets are more constrained, skip the remaining PSets. 396 if (I == E) 397 break; 398 // Insert this PressureChange. 399 if (!I->isValid() || I->getPSet() != *PSetI) { 400 PressureChange PTmp = PressureChange(*PSetI); 401 for (PressureDiff::iterator J = I; J != E && PTmp.isValid(); ++J) 402 std::swap(*J,PTmp); 403 } 404 // Update the units for this pressure set. 405 I->setUnitInc(I->getUnitInc() + Weight); 406 } 407 } 408 409 /// Record the pressure difference induced by the given operand list. 410 static void collectPDiff(PressureDiff &PDiff, RegisterOperands &RegOpers, 411 const MachineRegisterInfo *MRI) { 412 assert(!PDiff.begin()->isValid() && "stale PDiff"); 413 414 for (unsigned i = 0, e = RegOpers.Defs.size(); i != e; ++i) 415 PDiff.addPressureChange(RegOpers.Defs[i], true, MRI); 416 417 for (unsigned i = 0, e = RegOpers.Uses.size(); i != e; ++i) 418 PDiff.addPressureChange(RegOpers.Uses[i], false, MRI); 419 } 420 421 /// Force liveness of registers. 422 void RegPressureTracker::addLiveRegs(ArrayRef<unsigned> Regs) { 423 for (unsigned i = 0, e = Regs.size(); i != e; ++i) { 424 if (LiveRegs.insert(Regs[i])) 425 increaseRegPressure(Regs[i]); 426 } 427 } 428 429 /// Add Reg to the live in set and increase max pressure. 430 void RegPressureTracker::discoverLiveIn(unsigned Reg) { 431 assert(!LiveRegs.contains(Reg) && "avoid bumping max pressure twice"); 432 if (containsReg(P.LiveInRegs, Reg)) 433 return; 434 435 // At live in discovery, unconditionally increase the high water mark. 436 P.LiveInRegs.push_back(Reg); 437 increaseSetPressure(P.MaxSetPressure, MRI->getPressureSets(Reg)); 438 } 439 440 /// Add Reg to the live out set and increase max pressure. 441 void RegPressureTracker::discoverLiveOut(unsigned Reg) { 442 assert(!LiveRegs.contains(Reg) && "avoid bumping max pressure twice"); 443 if (containsReg(P.LiveOutRegs, Reg)) 444 return; 445 446 // At live out discovery, unconditionally increase the high water mark. 447 P.LiveOutRegs.push_back(Reg); 448 increaseSetPressure(P.MaxSetPressure, MRI->getPressureSets(Reg)); 449 } 450 451 /// Recede across the previous instruction. If LiveUses is provided, record any 452 /// RegUnits that are made live by the current instruction's uses. This includes 453 /// registers that are both defined and used by the instruction. If a pressure 454 /// difference pointer is provided record the changes is pressure caused by this 455 /// instruction independent of liveness. 456 bool RegPressureTracker::recede(SmallVectorImpl<unsigned> *LiveUses, 457 PressureDiff *PDiff) { 458 // Check for the top of the analyzable region. 459 if (CurrPos == MBB->begin()) { 460 closeRegion(); 461 return false; 462 } 463 if (!isBottomClosed()) 464 closeBottom(); 465 466 // Open the top of the region using block iterators. 467 if (!RequireIntervals && isTopClosed()) 468 static_cast<RegionPressure&>(P).openTop(CurrPos); 469 470 // Find the previous instruction. 471 do 472 --CurrPos; 473 while (CurrPos != MBB->begin() && CurrPos->isDebugValue()); 474 475 if (CurrPos->isDebugValue()) { 476 closeRegion(); 477 return false; 478 } 479 SlotIndex SlotIdx; 480 if (RequireIntervals) 481 SlotIdx = LIS->getInstructionIndex(CurrPos).getRegSlot(); 482 483 // Open the top of the region using slot indexes. 484 if (RequireIntervals && isTopClosed()) 485 static_cast<IntervalPressure&>(P).openTop(SlotIdx); 486 487 RegisterOperands RegOpers(TRI, MRI); 488 collectOperands(CurrPos, RegOpers); 489 490 if (PDiff) 491 collectPDiff(*PDiff, RegOpers, MRI); 492 493 // Boost pressure for all dead defs together. 494 increaseRegPressure(RegOpers.DeadDefs); 495 decreaseRegPressure(RegOpers.DeadDefs); 496 497 // Kill liveness at live defs. 498 // TODO: consider earlyclobbers? 499 for (unsigned i = 0, e = RegOpers.Defs.size(); i < e; ++i) { 500 unsigned Reg = RegOpers.Defs[i]; 501 if (LiveRegs.erase(Reg)) 502 decreaseRegPressure(Reg); 503 else 504 discoverLiveOut(Reg); 505 } 506 507 // Generate liveness for uses. 508 for (unsigned i = 0, e = RegOpers.Uses.size(); i < e; ++i) { 509 unsigned Reg = RegOpers.Uses[i]; 510 if (!LiveRegs.contains(Reg)) { 511 // Adjust liveouts if LiveIntervals are available. 512 if (RequireIntervals) { 513 const LiveInterval *LI = getInterval(Reg); 514 // Check if this LR is killed and not redefined here. 515 if (LI) { 516 LiveRangeQuery LRQ(*LI, SlotIdx); 517 if (!LRQ.isKill() && !LRQ.valueDefined()) 518 discoverLiveOut(Reg); 519 } 520 } 521 increaseRegPressure(Reg); 522 LiveRegs.insert(Reg); 523 if (LiveUses && !containsReg(*LiveUses, Reg)) 524 LiveUses->push_back(Reg); 525 } 526 } 527 if (TrackUntiedDefs) { 528 for (unsigned i = 0, e = RegOpers.Defs.size(); i < e; ++i) { 529 unsigned Reg = RegOpers.Defs[i]; 530 if (TargetRegisterInfo::isVirtualRegister(Reg) && !LiveRegs.contains(Reg)) 531 UntiedDefs.insert(Reg); 532 } 533 } 534 return true; 535 } 536 537 /// Advance across the current instruction. 538 bool RegPressureTracker::advance() { 539 assert(!TrackUntiedDefs && "unsupported mode"); 540 541 // Check for the bottom of the analyzable region. 542 if (CurrPos == MBB->end()) { 543 closeRegion(); 544 return false; 545 } 546 if (!isTopClosed()) 547 closeTop(); 548 549 SlotIndex SlotIdx; 550 if (RequireIntervals) 551 SlotIdx = getCurrSlot(); 552 553 // Open the bottom of the region using slot indexes. 554 if (isBottomClosed()) { 555 if (RequireIntervals) 556 static_cast<IntervalPressure&>(P).openBottom(SlotIdx); 557 else 558 static_cast<RegionPressure&>(P).openBottom(CurrPos); 559 } 560 561 RegisterOperands RegOpers(TRI, MRI); 562 collectOperands(CurrPos, RegOpers); 563 564 for (unsigned i = 0, e = RegOpers.Uses.size(); i < e; ++i) { 565 unsigned Reg = RegOpers.Uses[i]; 566 // Discover live-ins. 567 bool isLive = LiveRegs.contains(Reg); 568 if (!isLive) 569 discoverLiveIn(Reg); 570 // Kill liveness at last uses. 571 bool lastUse = false; 572 if (RequireIntervals) { 573 const LiveInterval *LI = getInterval(Reg); 574 lastUse = LI && LiveRangeQuery(*LI, SlotIdx).isKill(); 575 } 576 else { 577 // Allocatable physregs are always single-use before register rewriting. 578 lastUse = !TargetRegisterInfo::isVirtualRegister(Reg); 579 } 580 if (lastUse && isLive) { 581 LiveRegs.erase(Reg); 582 decreaseRegPressure(Reg); 583 } 584 else if (!lastUse && !isLive) 585 increaseRegPressure(Reg); 586 } 587 588 // Generate liveness for defs. 589 for (unsigned i = 0, e = RegOpers.Defs.size(); i < e; ++i) { 590 unsigned Reg = RegOpers.Defs[i]; 591 if (LiveRegs.insert(Reg)) 592 increaseRegPressure(Reg); 593 } 594 595 // Boost pressure for all dead defs together. 596 increaseRegPressure(RegOpers.DeadDefs); 597 decreaseRegPressure(RegOpers.DeadDefs); 598 599 // Find the next instruction. 600 do 601 ++CurrPos; 602 while (CurrPos != MBB->end() && CurrPos->isDebugValue()); 603 return true; 604 } 605 606 /// Find the max change in excess pressure across all sets. 607 static void computeExcessPressureDelta(ArrayRef<unsigned> OldPressureVec, 608 ArrayRef<unsigned> NewPressureVec, 609 RegPressureDelta &Delta, 610 const RegisterClassInfo *RCI, 611 ArrayRef<unsigned> LiveThruPressureVec) { 612 Delta.Excess = PressureChange(); 613 for (unsigned i = 0, e = OldPressureVec.size(); i < e; ++i) { 614 unsigned POld = OldPressureVec[i]; 615 unsigned PNew = NewPressureVec[i]; 616 int PDiff = (int)PNew - (int)POld; 617 if (!PDiff) // No change in this set in the common case. 618 continue; 619 // Only consider change beyond the limit. 620 unsigned Limit = RCI->getRegPressureSetLimit(i); 621 if (!LiveThruPressureVec.empty()) 622 Limit += LiveThruPressureVec[i]; 623 624 if (Limit > POld) { 625 if (Limit > PNew) 626 PDiff = 0; // Under the limit 627 else 628 PDiff = PNew - Limit; // Just exceeded limit. 629 } 630 else if (Limit > PNew) 631 PDiff = Limit - POld; // Just obeyed limit. 632 633 if (PDiff) { 634 Delta.Excess = PressureChange(i); 635 Delta.Excess.setUnitInc(PDiff); 636 break; 637 } 638 } 639 } 640 641 /// Find the max change in max pressure that either surpasses a critical PSet 642 /// limit or exceeds the current MaxPressureLimit. 643 /// 644 /// FIXME: comparing each element of the old and new MaxPressure vectors here is 645 /// silly. It's done now to demonstrate the concept but will go away with a 646 /// RegPressureTracker API change to work with pressure differences. 647 static void computeMaxPressureDelta(ArrayRef<unsigned> OldMaxPressureVec, 648 ArrayRef<unsigned> NewMaxPressureVec, 649 ArrayRef<PressureChange> CriticalPSets, 650 ArrayRef<unsigned> MaxPressureLimit, 651 RegPressureDelta &Delta) { 652 Delta.CriticalMax = PressureChange(); 653 Delta.CurrentMax = PressureChange(); 654 655 unsigned CritIdx = 0, CritEnd = CriticalPSets.size(); 656 for (unsigned i = 0, e = OldMaxPressureVec.size(); i < e; ++i) { 657 unsigned POld = OldMaxPressureVec[i]; 658 unsigned PNew = NewMaxPressureVec[i]; 659 if (PNew == POld) // No change in this set in the common case. 660 continue; 661 662 if (!Delta.CriticalMax.isValid()) { 663 while (CritIdx != CritEnd && CriticalPSets[CritIdx].getPSet() < i) 664 ++CritIdx; 665 666 if (CritIdx != CritEnd && CriticalPSets[CritIdx].getPSet() == i) { 667 int PDiff = (int)PNew - (int)CriticalPSets[CritIdx].getUnitInc(); 668 if (PDiff > 0) { 669 Delta.CriticalMax = PressureChange(i); 670 Delta.CriticalMax.setUnitInc(PDiff); 671 } 672 } 673 } 674 // Find the first increase above MaxPressureLimit. 675 // (Ignores negative MDiff). 676 if (!Delta.CurrentMax.isValid() && PNew > MaxPressureLimit[i]) { 677 Delta.CurrentMax = PressureChange(i); 678 Delta.CurrentMax.setUnitInc(PNew - POld); 679 if (CritIdx == CritEnd || Delta.CriticalMax.isValid()) 680 break; 681 } 682 } 683 } 684 685 /// Record the upward impact of a single instruction on current register 686 /// pressure. Unlike the advance/recede pressure tracking interface, this does 687 /// not discover live in/outs. 688 /// 689 /// This is intended for speculative queries. It leaves pressure inconsistent 690 /// with the current position, so must be restored by the caller. 691 void RegPressureTracker::bumpUpwardPressure(const MachineInstr *MI) { 692 assert(!MI->isDebugValue() && "Expect a nondebug instruction."); 693 694 // Account for register pressure similar to RegPressureTracker::recede(). 695 RegisterOperands RegOpers(TRI, MRI, /*IgnoreDead=*/true); 696 collectOperands(MI, RegOpers); 697 698 // Boost max pressure for all dead defs together. 699 // Since CurrSetPressure and MaxSetPressure 700 increaseRegPressure(RegOpers.DeadDefs); 701 decreaseRegPressure(RegOpers.DeadDefs); 702 703 // Kill liveness at live defs. 704 for (unsigned i = 0, e = RegOpers.Defs.size(); i < e; ++i) { 705 unsigned Reg = RegOpers.Defs[i]; 706 if (!containsReg(RegOpers.Uses, Reg)) 707 decreaseRegPressure(Reg); 708 } 709 // Generate liveness for uses. 710 for (unsigned i = 0, e = RegOpers.Uses.size(); i < e; ++i) { 711 unsigned Reg = RegOpers.Uses[i]; 712 if (!LiveRegs.contains(Reg)) 713 increaseRegPressure(Reg); 714 } 715 } 716 717 /// Consider the pressure increase caused by traversing this instruction 718 /// bottom-up. Find the pressure set with the most change beyond its pressure 719 /// limit based on the tracker's current pressure, and return the change in 720 /// number of register units of that pressure set introduced by this 721 /// instruction. 722 /// 723 /// This assumes that the current LiveOut set is sufficient. 724 /// 725 /// FIXME: This is expensive for an on-the-fly query. We need to cache the 726 /// result per-SUnit with enough information to adjust for the current 727 /// scheduling position. But this works as a proof of concept. 728 void RegPressureTracker:: 729 getMaxUpwardPressureDelta(const MachineInstr *MI, PressureDiff *PDiff, 730 RegPressureDelta &Delta, 731 ArrayRef<PressureChange> CriticalPSets, 732 ArrayRef<unsigned> MaxPressureLimit) { 733 // Snapshot Pressure. 734 // FIXME: The snapshot heap space should persist. But I'm planning to 735 // summarize the pressure effect so we don't need to snapshot at all. 736 std::vector<unsigned> SavedPressure = CurrSetPressure; 737 std::vector<unsigned> SavedMaxPressure = P.MaxSetPressure; 738 739 bumpUpwardPressure(MI); 740 741 computeExcessPressureDelta(SavedPressure, CurrSetPressure, Delta, RCI, 742 LiveThruPressure); 743 computeMaxPressureDelta(SavedMaxPressure, P.MaxSetPressure, CriticalPSets, 744 MaxPressureLimit, Delta); 745 assert(Delta.CriticalMax.getUnitInc() >= 0 && 746 Delta.CurrentMax.getUnitInc() >= 0 && "cannot decrease max pressure"); 747 748 // Restore the tracker's state. 749 P.MaxSetPressure.swap(SavedMaxPressure); 750 CurrSetPressure.swap(SavedPressure); 751 752 #ifndef NDEBUG 753 if (!PDiff) 754 return; 755 756 // Check if the alternate algorithm yields the same result. 757 RegPressureDelta Delta2; 758 getUpwardPressureDelta(MI, *PDiff, Delta2, CriticalPSets, MaxPressureLimit); 759 if (Delta != Delta2) { 760 dbgs() << "DELTA: " << *MI; 761 if (Delta.Excess.isValid()) 762 dbgs() << "Excess1 " << TRI->getRegPressureSetName(Delta.Excess.getPSet()) 763 << " " << Delta.Excess.getUnitInc() << "\n"; 764 if (Delta.CriticalMax.isValid()) 765 dbgs() << "Critic1 " << TRI->getRegPressureSetName(Delta.CriticalMax.getPSet()) 766 << " " << Delta.CriticalMax.getUnitInc() << "\n"; 767 if (Delta.CurrentMax.isValid()) 768 dbgs() << "CurrMx1 " << TRI->getRegPressureSetName(Delta.CurrentMax.getPSet()) 769 << " " << Delta.CurrentMax.getUnitInc() << "\n"; 770 if (Delta2.Excess.isValid()) 771 dbgs() << "Excess2 " << TRI->getRegPressureSetName(Delta2.Excess.getPSet()) 772 << " " << Delta2.Excess.getUnitInc() << "\n"; 773 if (Delta2.CriticalMax.isValid()) 774 dbgs() << "Critic2 " << TRI->getRegPressureSetName(Delta2.CriticalMax.getPSet()) 775 << " " << Delta2.CriticalMax.getUnitInc() << "\n"; 776 if (Delta2.CurrentMax.isValid()) 777 dbgs() << "CurrMx2 " << TRI->getRegPressureSetName(Delta2.CurrentMax.getPSet()) 778 << " " << Delta2.CurrentMax.getUnitInc() << "\n"; 779 llvm_unreachable("RegP Delta Mismatch"); 780 } 781 #endif 782 } 783 784 /// This is a prototype of the fast version of querying register pressure that 785 /// does not directly depend on current liveness. It's still slow because we 786 /// recompute pressure change on-the-fly. This implementation only exists to 787 /// prove correctness. 788 /// 789 /// @param Delta captures information needed for heuristics. 790 /// 791 /// @param CriticalPSets Are the pressure sets that are known to exceed some 792 /// limit within the region, not necessarily at the current position. 793 /// 794 /// @param MaxPressureLimit Is the max pressure within the region, not 795 /// necessarily at the current position. 796 void RegPressureTracker:: 797 getUpwardPressureDelta(const MachineInstr *MI, /*const*/ PressureDiff &PDiff, 798 RegPressureDelta &Delta, 799 ArrayRef<PressureChange> CriticalPSets, 800 ArrayRef<unsigned> MaxPressureLimit) const { 801 unsigned CritIdx = 0, CritEnd = CriticalPSets.size(); 802 for (PressureDiff::const_iterator 803 PDiffI = PDiff.begin(), PDiffE = PDiff.end(); 804 PDiffI != PDiffE && PDiffI->isValid(); ++PDiffI) { 805 806 unsigned PSetID = PDiffI->getPSet(); 807 unsigned Limit = RCI->getRegPressureSetLimit(PSetID); 808 if (!LiveThruPressure.empty()) 809 Limit += LiveThruPressure[PSetID]; 810 811 unsigned POld = CurrSetPressure[PSetID]; 812 unsigned MOld = P.MaxSetPressure[PSetID]; 813 unsigned MNew = MOld; 814 // Ignore DeadDefs here because they aren't captured by PressureChange. 815 unsigned PNew = POld + PDiffI->getUnitInc(); 816 assert((PDiffI->getUnitInc() >= 0) == (PNew >= POld) && "PSet overflow"); 817 if (PNew > MOld) 818 MNew = PNew; 819 // Check if current pressure has exceeded the limit. 820 if (!Delta.Excess.isValid()) { 821 unsigned ExcessInc = 0; 822 if (PNew > Limit) 823 ExcessInc = POld > Limit ? PNew - POld : PNew - Limit; 824 else if (POld > Limit) 825 ExcessInc = Limit - POld; 826 if (ExcessInc) { 827 Delta.Excess = PressureChange(PSetID); 828 Delta.Excess.setUnitInc(ExcessInc); 829 } 830 } 831 // Check if max pressure has exceeded a critical pressure set max. 832 if (MNew == MOld) 833 continue; 834 if (!Delta.CriticalMax.isValid()) { 835 while (CritIdx != CritEnd && CriticalPSets[CritIdx].getPSet() < PSetID) 836 ++CritIdx; 837 838 if (CritIdx != CritEnd && CriticalPSets[CritIdx].getPSet() == PSetID) { 839 int CritInc = (int)MNew - (int)CriticalPSets[CritIdx].getUnitInc(); 840 if (CritInc > 0 && CritInc <= INT16_MAX) { 841 Delta.CriticalMax = PressureChange(PSetID); 842 Delta.CriticalMax.setUnitInc(CritInc); 843 } 844 } 845 } 846 // Check if max pressure has exceeded the current max. 847 if (!Delta.CurrentMax.isValid() && MNew > MaxPressureLimit[PSetID]) { 848 Delta.CurrentMax = PressureChange(PSetID); 849 Delta.CurrentMax.setUnitInc(MNew - MOld); 850 } 851 } 852 } 853 854 /// Helper to find a vreg use between two indices [PriorUseIdx, NextUseIdx). 855 static bool findUseBetween(unsigned Reg, 856 SlotIndex PriorUseIdx, SlotIndex NextUseIdx, 857 const MachineRegisterInfo *MRI, 858 const LiveIntervals *LIS) { 859 for (MachineRegisterInfo::use_nodbg_iterator 860 UI = MRI->use_nodbg_begin(Reg), UE = MRI->use_nodbg_end(); 861 UI != UE; UI.skipInstruction()) { 862 const MachineInstr* MI = &*UI; 863 if (MI->isDebugValue()) 864 continue; 865 SlotIndex InstSlot = LIS->getInstructionIndex(MI).getRegSlot(); 866 if (InstSlot >= PriorUseIdx && InstSlot < NextUseIdx) 867 return true; 868 } 869 return false; 870 } 871 872 /// Record the downward impact of a single instruction on current register 873 /// pressure. Unlike the advance/recede pressure tracking interface, this does 874 /// not discover live in/outs. 875 /// 876 /// This is intended for speculative queries. It leaves pressure inconsistent 877 /// with the current position, so must be restored by the caller. 878 void RegPressureTracker::bumpDownwardPressure(const MachineInstr *MI) { 879 assert(!MI->isDebugValue() && "Expect a nondebug instruction."); 880 881 // Account for register pressure similar to RegPressureTracker::recede(). 882 RegisterOperands RegOpers(TRI, MRI); 883 collectOperands(MI, RegOpers); 884 885 // Kill liveness at last uses. Assume allocatable physregs are single-use 886 // rather than checking LiveIntervals. 887 SlotIndex SlotIdx; 888 if (RequireIntervals) 889 SlotIdx = LIS->getInstructionIndex(MI).getRegSlot(); 890 891 for (unsigned i = 0, e = RegOpers.Uses.size(); i < e; ++i) { 892 unsigned Reg = RegOpers.Uses[i]; 893 if (RequireIntervals) { 894 // FIXME: allow the caller to pass in the list of vreg uses that remain 895 // to be bottom-scheduled to avoid searching uses at each query. 896 SlotIndex CurrIdx = getCurrSlot(); 897 const LiveInterval *LI = getInterval(Reg); 898 if (LI) { 899 LiveRangeQuery LRQ(*LI, SlotIdx); 900 if (LRQ.isKill() && !findUseBetween(Reg, CurrIdx, SlotIdx, MRI, LIS)) 901 decreaseRegPressure(Reg); 902 } 903 } 904 else if (!TargetRegisterInfo::isVirtualRegister(Reg)) { 905 // Allocatable physregs are always single-use before register rewriting. 906 decreaseRegPressure(Reg); 907 } 908 } 909 910 // Generate liveness for defs. 911 increaseRegPressure(RegOpers.Defs); 912 913 // Boost pressure for all dead defs together. 914 increaseRegPressure(RegOpers.DeadDefs); 915 decreaseRegPressure(RegOpers.DeadDefs); 916 } 917 918 /// Consider the pressure increase caused by traversing this instruction 919 /// top-down. Find the register class with the most change in its pressure limit 920 /// based on the tracker's current pressure, and return the number of excess 921 /// register units of that pressure set introduced by this instruction. 922 /// 923 /// This assumes that the current LiveIn set is sufficient. 924 void RegPressureTracker:: 925 getMaxDownwardPressureDelta(const MachineInstr *MI, RegPressureDelta &Delta, 926 ArrayRef<PressureChange> CriticalPSets, 927 ArrayRef<unsigned> MaxPressureLimit) { 928 // Snapshot Pressure. 929 std::vector<unsigned> SavedPressure = CurrSetPressure; 930 std::vector<unsigned> SavedMaxPressure = P.MaxSetPressure; 931 932 bumpDownwardPressure(MI); 933 934 computeExcessPressureDelta(SavedPressure, CurrSetPressure, Delta, RCI, 935 LiveThruPressure); 936 computeMaxPressureDelta(SavedMaxPressure, P.MaxSetPressure, CriticalPSets, 937 MaxPressureLimit, Delta); 938 assert(Delta.CriticalMax.getUnitInc() >= 0 && 939 Delta.CurrentMax.getUnitInc() >= 0 && "cannot decrease max pressure"); 940 941 // Restore the tracker's state. 942 P.MaxSetPressure.swap(SavedMaxPressure); 943 CurrSetPressure.swap(SavedPressure); 944 } 945 946 /// Get the pressure of each PSet after traversing this instruction bottom-up. 947 void RegPressureTracker:: 948 getUpwardPressure(const MachineInstr *MI, 949 std::vector<unsigned> &PressureResult, 950 std::vector<unsigned> &MaxPressureResult) { 951 // Snapshot pressure. 952 PressureResult = CurrSetPressure; 953 MaxPressureResult = P.MaxSetPressure; 954 955 bumpUpwardPressure(MI); 956 957 // Current pressure becomes the result. Restore current pressure. 958 P.MaxSetPressure.swap(MaxPressureResult); 959 CurrSetPressure.swap(PressureResult); 960 } 961 962 /// Get the pressure of each PSet after traversing this instruction top-down. 963 void RegPressureTracker:: 964 getDownwardPressure(const MachineInstr *MI, 965 std::vector<unsigned> &PressureResult, 966 std::vector<unsigned> &MaxPressureResult) { 967 // Snapshot pressure. 968 PressureResult = CurrSetPressure; 969 MaxPressureResult = P.MaxSetPressure; 970 971 bumpDownwardPressure(MI); 972 973 // Current pressure becomes the result. Restore current pressure. 974 P.MaxSetPressure.swap(MaxPressureResult); 975 CurrSetPressure.swap(PressureResult); 976 } 977