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