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/ADT/ArrayRef.h" 16 #include "llvm/ADT/SmallVector.h" 17 #include "llvm/ADT/STLExtras.h" 18 #include "llvm/CodeGen/LiveInterval.h" 19 #include "llvm/CodeGen/LiveIntervalAnalysis.h" 20 #include "llvm/CodeGen/MachineBasicBlock.h" 21 #include "llvm/CodeGen/MachineFunction.h" 22 #include "llvm/CodeGen/MachineInstr.h" 23 #include "llvm/CodeGen/MachineInstrBundle.h" 24 #include "llvm/CodeGen/MachineOperand.h" 25 #include "llvm/CodeGen/MachineRegisterInfo.h" 26 #include "llvm/CodeGen/RegisterClassInfo.h" 27 #include "llvm/CodeGen/RegisterPressure.h" 28 #include "llvm/CodeGen/SlotIndexes.h" 29 #include "llvm/MC/LaneBitmask.h" 30 #include "llvm/MC/MCRegisterInfo.h" 31 #include "llvm/Support/Compiler.h" 32 #include "llvm/Support/Debug.h" 33 #include "llvm/Support/ErrorHandling.h" 34 #include "llvm/Support/raw_ostream.h" 35 #include "llvm/Target/TargetRegisterInfo.h" 36 #include "llvm/Target/TargetSubtargetInfo.h" 37 #include <algorithm> 38 #include <cassert> 39 #include <cstdint> 40 #include <cstdlib> 41 #include <cstring> 42 #include <iterator> 43 #include <limits> 44 #include <utility> 45 #include <vector> 46 47 using namespace llvm; 48 49 /// Clamp lane masks to maximum posible value. 50 static void clampMasks(const MachineRegisterInfo &MRI, unsigned Reg, 51 LaneBitmask& LaneMask1, LaneBitmask& LaneMask2) { 52 if (TargetRegisterInfo::isVirtualRegister(Reg)) { 53 LaneBitmask Max = MRI.getMaxLaneMaskForVReg(Reg); 54 LaneMask1 &= Max; 55 LaneMask2 &= Max; 56 } 57 } 58 59 /// Increase pressure for each pressure set provided by TargetRegisterInfo. 60 static void increaseSetPressure(std::vector<unsigned> &CurrSetPressure, 61 const MachineRegisterInfo &MRI, unsigned Reg, 62 LaneBitmask PrevMask, LaneBitmask NewMask) { 63 assert((PrevMask & ~NewMask).none() && "Must not remove bits"); 64 65 clampMasks(MRI, Reg, PrevMask, NewMask); 66 if ((NewMask & ~PrevMask).none()) 67 return; 68 69 const TargetRegisterInfo *TRI = MRI.getTargetRegisterInfo(); 70 unsigned Weight = TRI->getRegUnitWeight(MRI, Reg, NewMask & ~PrevMask); 71 PSetIterator PSetI = MRI.getPressureSets(Reg); 72 for (; PSetI.isValid(); ++PSetI) 73 CurrSetPressure[*PSetI] += Weight; 74 } 75 76 /// Decrease pressure for each pressure set provided by TargetRegisterInfo. 77 static void decreaseSetPressure(std::vector<unsigned> &CurrSetPressure, 78 const MachineRegisterInfo &MRI, unsigned Reg, 79 LaneBitmask PrevMask, LaneBitmask NewMask) { 80 //assert((NewMask & !PrevMask) == 0 && "Must not add bits"); 81 clampMasks(MRI, Reg, PrevMask, NewMask); 82 if ((~NewMask & PrevMask).none()) 83 return; 84 85 const TargetRegisterInfo *TRI = MRI.getTargetRegisterInfo(); 86 unsigned Weight = TRI->getRegUnitWeight(MRI, Reg, ~NewMask & PrevMask); 87 PSetIterator PSetI = MRI.getPressureSets(Reg); 88 for (; PSetI.isValid(); ++PSetI) { 89 assert(CurrSetPressure[*PSetI] >= Weight && "register pressure underflow"); 90 CurrSetPressure[*PSetI] -= Weight; 91 } 92 } 93 94 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 95 LLVM_DUMP_METHOD 96 void llvm::dumpRegSetPressure(ArrayRef<unsigned> SetPressure, 97 const TargetRegisterInfo *TRI) { 98 bool Empty = true; 99 for (unsigned i = 0, e = SetPressure.size(); i < e; ++i) { 100 if (SetPressure[i] != 0) { 101 dbgs() << TRI->getRegPressureSetName(i) << "=" << SetPressure[i] << '\n'; 102 Empty = false; 103 } 104 } 105 if (Empty) 106 dbgs() << "\n"; 107 } 108 109 LLVM_DUMP_METHOD 110 void RegisterPressure::dump(const TargetRegisterInfo *TRI) const { 111 dbgs() << "Max Pressure: "; 112 dumpRegSetPressure(MaxSetPressure, TRI); 113 dbgs() << "Live In: "; 114 for (const RegisterMaskPair &P : LiveInRegs) { 115 dbgs() << PrintVRegOrUnit(P.RegUnit, TRI); 116 if (!P.LaneMask.all()) 117 dbgs() << ':' << PrintLaneMask(P.LaneMask); 118 dbgs() << ' '; 119 } 120 dbgs() << '\n'; 121 dbgs() << "Live Out: "; 122 for (const RegisterMaskPair &P : LiveOutRegs) { 123 dbgs() << PrintVRegOrUnit(P.RegUnit, TRI); 124 if (!P.LaneMask.all()) 125 dbgs() << ':' << PrintLaneMask(P.LaneMask); 126 dbgs() << ' '; 127 } 128 dbgs() << '\n'; 129 } 130 131 LLVM_DUMP_METHOD 132 void RegPressureTracker::dump() const { 133 if (!isTopClosed() || !isBottomClosed()) { 134 dbgs() << "Curr Pressure: "; 135 dumpRegSetPressure(CurrSetPressure, TRI); 136 } 137 P.dump(TRI); 138 } 139 140 LLVM_DUMP_METHOD 141 void PressureDiff::dump(const TargetRegisterInfo &TRI) const { 142 const char *sep = ""; 143 for (const PressureChange &Change : *this) { 144 if (!Change.isValid()) 145 break; 146 dbgs() << sep << TRI.getRegPressureSetName(Change.getPSet()) 147 << " " << Change.getUnitInc(); 148 sep = " "; 149 } 150 dbgs() << '\n'; 151 } 152 #endif 153 154 void RegPressureTracker::increaseRegPressure(unsigned RegUnit, 155 LaneBitmask PreviousMask, 156 LaneBitmask NewMask) { 157 clampMasks(*MRI, RegUnit, PreviousMask, NewMask); 158 if ((NewMask & ~PreviousMask).none()) 159 return; 160 161 const TargetRegisterInfo *TRI = MRI->getTargetRegisterInfo(); 162 unsigned Weight = TRI->getRegUnitWeight(*MRI, RegUnit, 163 NewMask & ~PreviousMask); 164 PSetIterator PSetI = MRI->getPressureSets(RegUnit); 165 for (; PSetI.isValid(); ++PSetI) { 166 CurrSetPressure[*PSetI] += Weight; 167 P.MaxSetPressure[*PSetI] = 168 std::max(P.MaxSetPressure[*PSetI], CurrSetPressure[*PSetI]); 169 } 170 } 171 172 void RegPressureTracker::decreaseRegPressure(unsigned RegUnit, 173 LaneBitmask PreviousMask, 174 LaneBitmask NewMask) { 175 decreaseSetPressure(CurrSetPressure, *MRI, RegUnit, PreviousMask, NewMask); 176 } 177 178 /// Clear the result so it can be used for another round of pressure tracking. 179 void IntervalPressure::reset() { 180 TopIdx = BottomIdx = SlotIndex(); 181 MaxSetPressure.clear(); 182 LiveInRegs.clear(); 183 LiveOutRegs.clear(); 184 } 185 186 /// Clear the result so it can be used for another round of pressure tracking. 187 void RegionPressure::reset() { 188 TopPos = BottomPos = MachineBasicBlock::const_iterator(); 189 MaxSetPressure.clear(); 190 LiveInRegs.clear(); 191 LiveOutRegs.clear(); 192 } 193 194 /// If the current top is not less than or equal to the next index, open it. 195 /// We happen to need the SlotIndex for the next top for pressure update. 196 void IntervalPressure::openTop(SlotIndex NextTop) { 197 if (TopIdx <= NextTop) 198 return; 199 TopIdx = SlotIndex(); 200 LiveInRegs.clear(); 201 } 202 203 /// If the current top is the previous instruction (before receding), open it. 204 void RegionPressure::openTop(MachineBasicBlock::const_iterator PrevTop) { 205 if (TopPos != PrevTop) 206 return; 207 TopPos = MachineBasicBlock::const_iterator(); 208 LiveInRegs.clear(); 209 } 210 211 /// If the current bottom is not greater than the previous index, open it. 212 void IntervalPressure::openBottom(SlotIndex PrevBottom) { 213 if (BottomIdx > PrevBottom) 214 return; 215 BottomIdx = SlotIndex(); 216 LiveInRegs.clear(); 217 } 218 219 /// If the current bottom is the previous instr (before advancing), open it. 220 void RegionPressure::openBottom(MachineBasicBlock::const_iterator PrevBottom) { 221 if (BottomPos != PrevBottom) 222 return; 223 BottomPos = MachineBasicBlock::const_iterator(); 224 LiveInRegs.clear(); 225 } 226 227 void LiveRegSet::init(const MachineRegisterInfo &MRI) { 228 const TargetRegisterInfo &TRI = *MRI.getTargetRegisterInfo(); 229 unsigned NumRegUnits = TRI.getNumRegs(); 230 unsigned NumVirtRegs = MRI.getNumVirtRegs(); 231 Regs.setUniverse(NumRegUnits + NumVirtRegs); 232 this->NumRegUnits = NumRegUnits; 233 } 234 235 void LiveRegSet::clear() { 236 Regs.clear(); 237 } 238 239 static const LiveRange *getLiveRange(const LiveIntervals &LIS, unsigned Reg) { 240 if (TargetRegisterInfo::isVirtualRegister(Reg)) 241 return &LIS.getInterval(Reg); 242 return LIS.getCachedRegUnit(Reg); 243 } 244 245 void RegPressureTracker::reset() { 246 MBB = nullptr; 247 LIS = nullptr; 248 249 CurrSetPressure.clear(); 250 LiveThruPressure.clear(); 251 P.MaxSetPressure.clear(); 252 253 if (RequireIntervals) 254 static_cast<IntervalPressure&>(P).reset(); 255 else 256 static_cast<RegionPressure&>(P).reset(); 257 258 LiveRegs.clear(); 259 UntiedDefs.clear(); 260 } 261 262 /// Setup the RegPressureTracker. 263 /// 264 /// TODO: Add support for pressure without LiveIntervals. 265 void RegPressureTracker::init(const MachineFunction *mf, 266 const RegisterClassInfo *rci, 267 const LiveIntervals *lis, 268 const MachineBasicBlock *mbb, 269 MachineBasicBlock::const_iterator pos, 270 bool TrackLaneMasks, bool TrackUntiedDefs) { 271 reset(); 272 273 MF = mf; 274 TRI = MF->getSubtarget().getRegisterInfo(); 275 RCI = rci; 276 MRI = &MF->getRegInfo(); 277 MBB = mbb; 278 this->TrackUntiedDefs = TrackUntiedDefs; 279 this->TrackLaneMasks = TrackLaneMasks; 280 281 if (RequireIntervals) { 282 assert(lis && "IntervalPressure requires LiveIntervals"); 283 LIS = lis; 284 } 285 286 CurrPos = pos; 287 CurrSetPressure.assign(TRI->getNumRegPressureSets(), 0); 288 289 P.MaxSetPressure = CurrSetPressure; 290 291 LiveRegs.init(*MRI); 292 if (TrackUntiedDefs) 293 UntiedDefs.setUniverse(MRI->getNumVirtRegs()); 294 } 295 296 /// Does this pressure result have a valid top position and live ins. 297 bool RegPressureTracker::isTopClosed() const { 298 if (RequireIntervals) 299 return static_cast<IntervalPressure&>(P).TopIdx.isValid(); 300 return (static_cast<RegionPressure&>(P).TopPos == 301 MachineBasicBlock::const_iterator()); 302 } 303 304 /// Does this pressure result have a valid bottom position and live outs. 305 bool RegPressureTracker::isBottomClosed() const { 306 if (RequireIntervals) 307 return static_cast<IntervalPressure&>(P).BottomIdx.isValid(); 308 return (static_cast<RegionPressure&>(P).BottomPos == 309 MachineBasicBlock::const_iterator()); 310 } 311 312 SlotIndex RegPressureTracker::getCurrSlot() const { 313 MachineBasicBlock::const_iterator IdxPos = 314 skipDebugInstructionsForward(CurrPos, MBB->end()); 315 if (IdxPos == MBB->end()) 316 return LIS->getMBBEndIdx(MBB); 317 return LIS->getInstructionIndex(*IdxPos).getRegSlot(); 318 } 319 320 /// Set the boundary for the top of the region and summarize live ins. 321 void RegPressureTracker::closeTop() { 322 if (RequireIntervals) 323 static_cast<IntervalPressure&>(P).TopIdx = getCurrSlot(); 324 else 325 static_cast<RegionPressure&>(P).TopPos = CurrPos; 326 327 assert(P.LiveInRegs.empty() && "inconsistent max pressure result"); 328 P.LiveInRegs.reserve(LiveRegs.size()); 329 LiveRegs.appendTo(P.LiveInRegs); 330 } 331 332 /// Set the boundary for the bottom of the region and summarize live outs. 333 void RegPressureTracker::closeBottom() { 334 if (RequireIntervals) 335 static_cast<IntervalPressure&>(P).BottomIdx = getCurrSlot(); 336 else 337 static_cast<RegionPressure&>(P).BottomPos = CurrPos; 338 339 assert(P.LiveOutRegs.empty() && "inconsistent max pressure result"); 340 P.LiveOutRegs.reserve(LiveRegs.size()); 341 LiveRegs.appendTo(P.LiveOutRegs); 342 } 343 344 /// Finalize the region boundaries and record live ins and live outs. 345 void RegPressureTracker::closeRegion() { 346 if (!isTopClosed() && !isBottomClosed()) { 347 assert(LiveRegs.size() == 0 && "no region boundary"); 348 return; 349 } 350 if (!isBottomClosed()) 351 closeBottom(); 352 else if (!isTopClosed()) 353 closeTop(); 354 // If both top and bottom are closed, do nothing. 355 } 356 357 /// The register tracker is unaware of global liveness so ignores normal 358 /// live-thru ranges. However, two-address or coalesced chains can also lead 359 /// to live ranges with no holes. Count these to inform heuristics that we 360 /// can never drop below this pressure. 361 void RegPressureTracker::initLiveThru(const RegPressureTracker &RPTracker) { 362 LiveThruPressure.assign(TRI->getNumRegPressureSets(), 0); 363 assert(isBottomClosed() && "need bottom-up tracking to intialize."); 364 for (const RegisterMaskPair &Pair : P.LiveOutRegs) { 365 unsigned RegUnit = Pair.RegUnit; 366 if (TargetRegisterInfo::isVirtualRegister(RegUnit) 367 && !RPTracker.hasUntiedDef(RegUnit)) 368 increaseSetPressure(LiveThruPressure, *MRI, RegUnit, 369 LaneBitmask::getNone(), Pair.LaneMask); 370 } 371 } 372 373 static LaneBitmask getRegLanes(ArrayRef<RegisterMaskPair> RegUnits, 374 unsigned RegUnit) { 375 auto I = llvm::find_if(RegUnits, [RegUnit](const RegisterMaskPair Other) { 376 return Other.RegUnit == RegUnit; 377 }); 378 if (I == RegUnits.end()) 379 return LaneBitmask::getNone(); 380 return I->LaneMask; 381 } 382 383 static void addRegLanes(SmallVectorImpl<RegisterMaskPair> &RegUnits, 384 RegisterMaskPair Pair) { 385 unsigned RegUnit = Pair.RegUnit; 386 assert(Pair.LaneMask.any()); 387 auto I = llvm::find_if(RegUnits, [RegUnit](const RegisterMaskPair Other) { 388 return Other.RegUnit == RegUnit; 389 }); 390 if (I == RegUnits.end()) { 391 RegUnits.push_back(Pair); 392 } else { 393 I->LaneMask |= Pair.LaneMask; 394 } 395 } 396 397 static void setRegZero(SmallVectorImpl<RegisterMaskPair> &RegUnits, 398 unsigned RegUnit) { 399 auto I = llvm::find_if(RegUnits, [RegUnit](const RegisterMaskPair Other) { 400 return Other.RegUnit == RegUnit; 401 }); 402 if (I == RegUnits.end()) { 403 RegUnits.push_back(RegisterMaskPair(RegUnit, LaneBitmask::getNone())); 404 } else { 405 I->LaneMask = LaneBitmask::getNone(); 406 } 407 } 408 409 static void removeRegLanes(SmallVectorImpl<RegisterMaskPair> &RegUnits, 410 RegisterMaskPair Pair) { 411 unsigned RegUnit = Pair.RegUnit; 412 assert(Pair.LaneMask.any()); 413 auto I = llvm::find_if(RegUnits, [RegUnit](const RegisterMaskPair Other) { 414 return Other.RegUnit == RegUnit; 415 }); 416 if (I != RegUnits.end()) { 417 I->LaneMask &= ~Pair.LaneMask; 418 if (I->LaneMask.none()) 419 RegUnits.erase(I); 420 } 421 } 422 423 static LaneBitmask getLanesWithProperty(const LiveIntervals &LIS, 424 const MachineRegisterInfo &MRI, bool TrackLaneMasks, unsigned RegUnit, 425 SlotIndex Pos, LaneBitmask SafeDefault, 426 bool(*Property)(const LiveRange &LR, SlotIndex Pos)) { 427 if (TargetRegisterInfo::isVirtualRegister(RegUnit)) { 428 const LiveInterval &LI = LIS.getInterval(RegUnit); 429 LaneBitmask Result; 430 if (TrackLaneMasks && LI.hasSubRanges()) { 431 for (const LiveInterval::SubRange &SR : LI.subranges()) { 432 if (Property(SR, Pos)) 433 Result |= SR.LaneMask; 434 } 435 } else if (Property(LI, Pos)) { 436 Result = TrackLaneMasks ? MRI.getMaxLaneMaskForVReg(RegUnit) 437 : LaneBitmask::getAll(); 438 } 439 440 return Result; 441 } else { 442 const LiveRange *LR = LIS.getCachedRegUnit(RegUnit); 443 // Be prepared for missing liveranges: We usually do not compute liveranges 444 // for physical registers on targets with many registers (GPUs). 445 if (LR == nullptr) 446 return SafeDefault; 447 return Property(*LR, Pos) ? LaneBitmask::getAll() : LaneBitmask::getNone(); 448 } 449 } 450 451 static LaneBitmask getLiveLanesAt(const LiveIntervals &LIS, 452 const MachineRegisterInfo &MRI, 453 bool TrackLaneMasks, unsigned RegUnit, 454 SlotIndex Pos) { 455 return getLanesWithProperty(LIS, MRI, TrackLaneMasks, RegUnit, Pos, 456 LaneBitmask::getAll(), 457 [](const LiveRange &LR, SlotIndex Pos) { 458 return LR.liveAt(Pos); 459 }); 460 } 461 462 463 namespace { 464 465 /// Collect this instruction's unique uses and defs into SmallVectors for 466 /// processing defs and uses in order. 467 /// 468 /// FIXME: always ignore tied opers 469 class RegisterOperandsCollector { 470 friend class llvm::RegisterOperands; 471 472 RegisterOperands &RegOpers; 473 const TargetRegisterInfo &TRI; 474 const MachineRegisterInfo &MRI; 475 bool IgnoreDead; 476 477 RegisterOperandsCollector(RegisterOperands &RegOpers, 478 const TargetRegisterInfo &TRI, 479 const MachineRegisterInfo &MRI, bool IgnoreDead) 480 : RegOpers(RegOpers), TRI(TRI), MRI(MRI), IgnoreDead(IgnoreDead) {} 481 482 void collectInstr(const MachineInstr &MI) const { 483 for (ConstMIBundleOperands OperI(MI); OperI.isValid(); ++OperI) 484 collectOperand(*OperI); 485 486 // Remove redundant physreg dead defs. 487 for (const RegisterMaskPair &P : RegOpers.Defs) 488 removeRegLanes(RegOpers.DeadDefs, P); 489 } 490 491 void collectInstrLanes(const MachineInstr &MI) const { 492 for (ConstMIBundleOperands OperI(MI); OperI.isValid(); ++OperI) 493 collectOperandLanes(*OperI); 494 495 // Remove redundant physreg dead defs. 496 for (const RegisterMaskPair &P : RegOpers.Defs) 497 removeRegLanes(RegOpers.DeadDefs, P); 498 } 499 500 /// Push this operand's register onto the correct vectors. 501 void collectOperand(const MachineOperand &MO) const { 502 if (!MO.isReg() || !MO.getReg()) 503 return; 504 unsigned Reg = MO.getReg(); 505 if (MO.isUse()) { 506 if (!MO.isUndef() && !MO.isInternalRead()) 507 pushReg(Reg, RegOpers.Uses); 508 } else { 509 assert(MO.isDef()); 510 // Subregister definitions may imply a register read. 511 if (MO.readsReg()) 512 pushReg(Reg, RegOpers.Uses); 513 514 if (MO.isDead()) { 515 if (!IgnoreDead) 516 pushReg(Reg, RegOpers.DeadDefs); 517 } else 518 pushReg(Reg, RegOpers.Defs); 519 } 520 } 521 522 void pushReg(unsigned Reg, 523 SmallVectorImpl<RegisterMaskPair> &RegUnits) const { 524 if (TargetRegisterInfo::isVirtualRegister(Reg)) { 525 addRegLanes(RegUnits, RegisterMaskPair(Reg, LaneBitmask::getAll())); 526 } else if (MRI.isAllocatable(Reg)) { 527 for (MCRegUnitIterator Units(Reg, &TRI); Units.isValid(); ++Units) 528 addRegLanes(RegUnits, RegisterMaskPair(*Units, LaneBitmask::getAll())); 529 } 530 } 531 532 void collectOperandLanes(const MachineOperand &MO) const { 533 if (!MO.isReg() || !MO.getReg()) 534 return; 535 unsigned Reg = MO.getReg(); 536 unsigned SubRegIdx = MO.getSubReg(); 537 if (MO.isUse()) { 538 if (!MO.isUndef() && !MO.isInternalRead()) 539 pushRegLanes(Reg, SubRegIdx, RegOpers.Uses); 540 } else { 541 assert(MO.isDef()); 542 // Treat read-undef subreg defs as definitions of the whole register. 543 if (MO.isUndef()) 544 SubRegIdx = 0; 545 546 if (MO.isDead()) { 547 if (!IgnoreDead) 548 pushRegLanes(Reg, SubRegIdx, RegOpers.DeadDefs); 549 } else 550 pushRegLanes(Reg, SubRegIdx, RegOpers.Defs); 551 } 552 } 553 554 void pushRegLanes(unsigned Reg, unsigned SubRegIdx, 555 SmallVectorImpl<RegisterMaskPair> &RegUnits) const { 556 if (TargetRegisterInfo::isVirtualRegister(Reg)) { 557 LaneBitmask LaneMask = SubRegIdx != 0 558 ? TRI.getSubRegIndexLaneMask(SubRegIdx) 559 : MRI.getMaxLaneMaskForVReg(Reg); 560 addRegLanes(RegUnits, RegisterMaskPair(Reg, LaneMask)); 561 } else if (MRI.isAllocatable(Reg)) { 562 for (MCRegUnitIterator Units(Reg, &TRI); Units.isValid(); ++Units) 563 addRegLanes(RegUnits, RegisterMaskPair(*Units, LaneBitmask::getAll())); 564 } 565 } 566 }; 567 568 } // end anonymous namespace 569 570 void RegisterOperands::collect(const MachineInstr &MI, 571 const TargetRegisterInfo &TRI, 572 const MachineRegisterInfo &MRI, 573 bool TrackLaneMasks, bool IgnoreDead) { 574 RegisterOperandsCollector Collector(*this, TRI, MRI, IgnoreDead); 575 if (TrackLaneMasks) 576 Collector.collectInstrLanes(MI); 577 else 578 Collector.collectInstr(MI); 579 } 580 581 void RegisterOperands::detectDeadDefs(const MachineInstr &MI, 582 const LiveIntervals &LIS) { 583 SlotIndex SlotIdx = LIS.getInstructionIndex(MI); 584 for (auto RI = Defs.begin(); RI != Defs.end(); /*empty*/) { 585 unsigned Reg = RI->RegUnit; 586 const LiveRange *LR = getLiveRange(LIS, Reg); 587 if (LR != nullptr) { 588 LiveQueryResult LRQ = LR->Query(SlotIdx); 589 if (LRQ.isDeadDef()) { 590 // LiveIntervals knows this is a dead even though it's MachineOperand is 591 // not flagged as such. 592 DeadDefs.push_back(*RI); 593 RI = Defs.erase(RI); 594 continue; 595 } 596 } 597 ++RI; 598 } 599 } 600 601 void RegisterOperands::adjustLaneLiveness(const LiveIntervals &LIS, 602 const MachineRegisterInfo &MRI, 603 SlotIndex Pos, 604 MachineInstr *AddFlagsMI) { 605 for (auto I = Defs.begin(); I != Defs.end(); ) { 606 LaneBitmask LiveAfter = getLiveLanesAt(LIS, MRI, true, I->RegUnit, 607 Pos.getDeadSlot()); 608 // If the the def is all that is live after the instruction, then in case 609 // of a subregister def we need a read-undef flag. 610 unsigned RegUnit = I->RegUnit; 611 if (TargetRegisterInfo::isVirtualRegister(RegUnit) && 612 AddFlagsMI != nullptr && (LiveAfter & ~I->LaneMask).none()) 613 AddFlagsMI->setRegisterDefReadUndef(RegUnit); 614 615 LaneBitmask ActualDef = I->LaneMask & LiveAfter; 616 if (ActualDef.none()) { 617 I = Defs.erase(I); 618 } else { 619 I->LaneMask = ActualDef; 620 ++I; 621 } 622 } 623 for (auto I = Uses.begin(); I != Uses.end(); ) { 624 LaneBitmask LiveBefore = getLiveLanesAt(LIS, MRI, true, I->RegUnit, 625 Pos.getBaseIndex()); 626 LaneBitmask LaneMask = I->LaneMask & LiveBefore; 627 if (LaneMask.none()) { 628 I = Uses.erase(I); 629 } else { 630 I->LaneMask = LaneMask; 631 ++I; 632 } 633 } 634 if (AddFlagsMI != nullptr) { 635 for (const RegisterMaskPair &P : DeadDefs) { 636 unsigned RegUnit = P.RegUnit; 637 if (!TargetRegisterInfo::isVirtualRegister(RegUnit)) 638 continue; 639 LaneBitmask LiveAfter = getLiveLanesAt(LIS, MRI, true, RegUnit, 640 Pos.getDeadSlot()); 641 if (LiveAfter.none()) 642 AddFlagsMI->setRegisterDefReadUndef(RegUnit); 643 } 644 } 645 } 646 647 /// Initialize an array of N PressureDiffs. 648 void PressureDiffs::init(unsigned N) { 649 Size = N; 650 if (N <= Max) { 651 memset(PDiffArray, 0, N * sizeof(PressureDiff)); 652 return; 653 } 654 Max = Size; 655 free(PDiffArray); 656 PDiffArray = reinterpret_cast<PressureDiff*>(calloc(N, sizeof(PressureDiff))); 657 } 658 659 void PressureDiffs::addInstruction(unsigned Idx, 660 const RegisterOperands &RegOpers, 661 const MachineRegisterInfo &MRI) { 662 PressureDiff &PDiff = (*this)[Idx]; 663 assert(!PDiff.begin()->isValid() && "stale PDiff"); 664 for (const RegisterMaskPair &P : RegOpers.Defs) 665 PDiff.addPressureChange(P, true, &MRI); 666 667 for (const RegisterMaskPair &P : RegOpers.Uses) 668 PDiff.addPressureChange(P, false, &MRI); 669 } 670 671 /// Add a change in pressure to the pressure diff of a given instruction. 672 void PressureDiff::addPressureChange(RegisterMaskPair P, bool IsDec, 673 const MachineRegisterInfo *MRI) { 674 const TargetRegisterInfo *TRI = MRI->getTargetRegisterInfo(); 675 int Weight = (int)TRI->getRegUnitWeight(*MRI, P.RegUnit, P.LaneMask); 676 PSetIterator PSetI = MRI->getPressureSets(P.RegUnit); 677 if (IsDec) Weight = -Weight; 678 for (; PSetI.isValid(); ++PSetI) { 679 // Find an existing entry in the pressure diff for this PSet. 680 PressureDiff::iterator I = nonconst_begin(), E = nonconst_end(); 681 for (; I != E && I->isValid(); ++I) { 682 if (I->getPSet() >= *PSetI) 683 break; 684 } 685 // If all pressure sets are more constrained, skip the remaining PSets. 686 if (I == E) 687 break; 688 // Insert this PressureChange. 689 if (!I->isValid() || I->getPSet() != *PSetI) { 690 PressureChange PTmp = PressureChange(*PSetI); 691 for (PressureDiff::iterator J = I; J != E && PTmp.isValid(); ++J) 692 std::swap(*J, PTmp); 693 } 694 // Update the units for this pressure set. 695 unsigned NewUnitInc = I->getUnitInc() + Weight; 696 if (NewUnitInc != 0) { 697 I->setUnitInc(NewUnitInc); 698 } else { 699 // Remove entry 700 PressureDiff::iterator J; 701 for (J = std::next(I); J != E && J->isValid(); ++J, ++I) 702 *I = *J; 703 if (J != E) 704 *I = *J; 705 } 706 } 707 } 708 709 /// Force liveness of registers. 710 void RegPressureTracker::addLiveRegs(ArrayRef<RegisterMaskPair> Regs) { 711 for (const RegisterMaskPair &P : Regs) { 712 LaneBitmask PrevMask = LiveRegs.insert(P); 713 LaneBitmask NewMask = PrevMask | P.LaneMask; 714 increaseRegPressure(P.RegUnit, PrevMask, NewMask); 715 } 716 } 717 718 void RegPressureTracker::discoverLiveInOrOut(RegisterMaskPair Pair, 719 SmallVectorImpl<RegisterMaskPair> &LiveInOrOut) { 720 assert(Pair.LaneMask.any()); 721 722 unsigned RegUnit = Pair.RegUnit; 723 auto I = llvm::find_if(LiveInOrOut, [RegUnit](const RegisterMaskPair &Other) { 724 return Other.RegUnit == RegUnit; 725 }); 726 LaneBitmask PrevMask; 727 LaneBitmask NewMask; 728 if (I == LiveInOrOut.end()) { 729 PrevMask = LaneBitmask::getNone(); 730 NewMask = Pair.LaneMask; 731 LiveInOrOut.push_back(Pair); 732 } else { 733 PrevMask = I->LaneMask; 734 NewMask = PrevMask | Pair.LaneMask; 735 I->LaneMask = NewMask; 736 } 737 increaseSetPressure(P.MaxSetPressure, *MRI, RegUnit, PrevMask, NewMask); 738 } 739 740 void RegPressureTracker::discoverLiveIn(RegisterMaskPair Pair) { 741 discoverLiveInOrOut(Pair, P.LiveInRegs); 742 } 743 744 void RegPressureTracker::discoverLiveOut(RegisterMaskPair Pair) { 745 discoverLiveInOrOut(Pair, P.LiveOutRegs); 746 } 747 748 void RegPressureTracker::bumpDeadDefs(ArrayRef<RegisterMaskPair> DeadDefs) { 749 for (const RegisterMaskPair &P : DeadDefs) { 750 unsigned Reg = P.RegUnit; 751 LaneBitmask LiveMask = LiveRegs.contains(Reg); 752 LaneBitmask BumpedMask = LiveMask | P.LaneMask; 753 increaseRegPressure(Reg, LiveMask, BumpedMask); 754 } 755 for (const RegisterMaskPair &P : DeadDefs) { 756 unsigned Reg = P.RegUnit; 757 LaneBitmask LiveMask = LiveRegs.contains(Reg); 758 LaneBitmask BumpedMask = LiveMask | P.LaneMask; 759 decreaseRegPressure(Reg, BumpedMask, LiveMask); 760 } 761 } 762 763 /// Recede across the previous instruction. If LiveUses is provided, record any 764 /// RegUnits that are made live by the current instruction's uses. This includes 765 /// registers that are both defined and used by the instruction. If a pressure 766 /// difference pointer is provided record the changes is pressure caused by this 767 /// instruction independent of liveness. 768 void RegPressureTracker::recede(const RegisterOperands &RegOpers, 769 SmallVectorImpl<RegisterMaskPair> *LiveUses) { 770 assert(!CurrPos->isDebugValue()); 771 772 // Boost pressure for all dead defs together. 773 bumpDeadDefs(RegOpers.DeadDefs); 774 775 // Kill liveness at live defs. 776 // TODO: consider earlyclobbers? 777 for (const RegisterMaskPair &Def : RegOpers.Defs) { 778 unsigned Reg = Def.RegUnit; 779 780 LaneBitmask PreviousMask = LiveRegs.erase(Def); 781 LaneBitmask NewMask = PreviousMask & ~Def.LaneMask; 782 783 LaneBitmask LiveOut = Def.LaneMask & ~PreviousMask; 784 if (LiveOut.any()) { 785 discoverLiveOut(RegisterMaskPair(Reg, LiveOut)); 786 // Retroactively model effects on pressure of the live out lanes. 787 increaseSetPressure(CurrSetPressure, *MRI, Reg, LaneBitmask::getNone(), 788 LiveOut); 789 PreviousMask = LiveOut; 790 } 791 792 if (NewMask.none()) { 793 // Add a 0 entry to LiveUses as a marker that the complete vreg has become 794 // dead. 795 if (TrackLaneMasks && LiveUses != nullptr) 796 setRegZero(*LiveUses, Reg); 797 } 798 799 decreaseRegPressure(Reg, PreviousMask, NewMask); 800 } 801 802 SlotIndex SlotIdx; 803 if (RequireIntervals) 804 SlotIdx = LIS->getInstructionIndex(*CurrPos).getRegSlot(); 805 806 // Generate liveness for uses. 807 for (const RegisterMaskPair &Use : RegOpers.Uses) { 808 unsigned Reg = Use.RegUnit; 809 assert(Use.LaneMask.any()); 810 LaneBitmask PreviousMask = LiveRegs.insert(Use); 811 LaneBitmask NewMask = PreviousMask | Use.LaneMask; 812 if (NewMask == PreviousMask) 813 continue; 814 815 // Did the register just become live? 816 if (PreviousMask.none()) { 817 if (LiveUses != nullptr) { 818 if (!TrackLaneMasks) { 819 addRegLanes(*LiveUses, RegisterMaskPair(Reg, NewMask)); 820 } else { 821 auto I = 822 llvm::find_if(*LiveUses, [Reg](const RegisterMaskPair Other) { 823 return Other.RegUnit == Reg; 824 }); 825 bool IsRedef = I != LiveUses->end(); 826 if (IsRedef) { 827 // ignore re-defs here... 828 assert(I->LaneMask.none()); 829 removeRegLanes(*LiveUses, RegisterMaskPair(Reg, NewMask)); 830 } else { 831 addRegLanes(*LiveUses, RegisterMaskPair(Reg, NewMask)); 832 } 833 } 834 } 835 836 // Discover live outs if this may be the first occurance of this register. 837 if (RequireIntervals) { 838 LaneBitmask LiveOut = getLiveThroughAt(Reg, SlotIdx); 839 if (LiveOut.any()) 840 discoverLiveOut(RegisterMaskPair(Reg, LiveOut)); 841 } 842 } 843 844 increaseRegPressure(Reg, PreviousMask, NewMask); 845 } 846 if (TrackUntiedDefs) { 847 for (const RegisterMaskPair &Def : RegOpers.Defs) { 848 unsigned RegUnit = Def.RegUnit; 849 if (TargetRegisterInfo::isVirtualRegister(RegUnit) && 850 (LiveRegs.contains(RegUnit) & Def.LaneMask).none()) 851 UntiedDefs.insert(RegUnit); 852 } 853 } 854 } 855 856 void RegPressureTracker::recedeSkipDebugValues() { 857 assert(CurrPos != MBB->begin()); 858 if (!isBottomClosed()) 859 closeBottom(); 860 861 // Open the top of the region using block iterators. 862 if (!RequireIntervals && isTopClosed()) 863 static_cast<RegionPressure&>(P).openTop(CurrPos); 864 865 // Find the previous instruction. 866 CurrPos = skipDebugInstructionsBackward(std::prev(CurrPos), MBB->begin()); 867 868 SlotIndex SlotIdx; 869 if (RequireIntervals) 870 SlotIdx = LIS->getInstructionIndex(*CurrPos).getRegSlot(); 871 872 // Open the top of the region using slot indexes. 873 if (RequireIntervals && isTopClosed()) 874 static_cast<IntervalPressure&>(P).openTop(SlotIdx); 875 } 876 877 void RegPressureTracker::recede(SmallVectorImpl<RegisterMaskPair> *LiveUses) { 878 recedeSkipDebugValues(); 879 880 const MachineInstr &MI = *CurrPos; 881 RegisterOperands RegOpers; 882 RegOpers.collect(MI, *TRI, *MRI, TrackLaneMasks, false); 883 if (TrackLaneMasks) { 884 SlotIndex SlotIdx = LIS->getInstructionIndex(*CurrPos).getRegSlot(); 885 RegOpers.adjustLaneLiveness(*LIS, *MRI, SlotIdx); 886 } else if (RequireIntervals) { 887 RegOpers.detectDeadDefs(MI, *LIS); 888 } 889 890 recede(RegOpers, LiveUses); 891 } 892 893 /// Advance across the current instruction. 894 void RegPressureTracker::advance(const RegisterOperands &RegOpers) { 895 assert(!TrackUntiedDefs && "unsupported mode"); 896 assert(CurrPos != MBB->end()); 897 if (!isTopClosed()) 898 closeTop(); 899 900 SlotIndex SlotIdx; 901 if (RequireIntervals) 902 SlotIdx = getCurrSlot(); 903 904 // Open the bottom of the region using slot indexes. 905 if (isBottomClosed()) { 906 if (RequireIntervals) 907 static_cast<IntervalPressure&>(P).openBottom(SlotIdx); 908 else 909 static_cast<RegionPressure&>(P).openBottom(CurrPos); 910 } 911 912 for (const RegisterMaskPair &Use : RegOpers.Uses) { 913 unsigned Reg = Use.RegUnit; 914 LaneBitmask LiveMask = LiveRegs.contains(Reg); 915 LaneBitmask LiveIn = Use.LaneMask & ~LiveMask; 916 if (LiveIn.any()) { 917 discoverLiveIn(RegisterMaskPair(Reg, LiveIn)); 918 increaseRegPressure(Reg, LiveMask, LiveMask | LiveIn); 919 LiveRegs.insert(RegisterMaskPair(Reg, LiveIn)); 920 } 921 // Kill liveness at last uses. 922 if (RequireIntervals) { 923 LaneBitmask LastUseMask = getLastUsedLanes(Reg, SlotIdx); 924 if (LastUseMask.any()) { 925 LiveRegs.erase(RegisterMaskPair(Reg, LastUseMask)); 926 decreaseRegPressure(Reg, LiveMask, LiveMask & ~LastUseMask); 927 } 928 } 929 } 930 931 // Generate liveness for defs. 932 for (const RegisterMaskPair &Def : RegOpers.Defs) { 933 LaneBitmask PreviousMask = LiveRegs.insert(Def); 934 LaneBitmask NewMask = PreviousMask | Def.LaneMask; 935 increaseRegPressure(Def.RegUnit, PreviousMask, NewMask); 936 } 937 938 // Boost pressure for all dead defs together. 939 bumpDeadDefs(RegOpers.DeadDefs); 940 941 // Find the next instruction. 942 CurrPos = skipDebugInstructionsForward(std::next(CurrPos), MBB->end()); 943 } 944 945 void RegPressureTracker::advance() { 946 const MachineInstr &MI = *CurrPos; 947 RegisterOperands RegOpers; 948 RegOpers.collect(MI, *TRI, *MRI, TrackLaneMasks, false); 949 if (TrackLaneMasks) { 950 SlotIndex SlotIdx = getCurrSlot(); 951 RegOpers.adjustLaneLiveness(*LIS, *MRI, SlotIdx); 952 } 953 advance(RegOpers); 954 } 955 956 /// Find the max change in excess pressure across all sets. 957 static void computeExcessPressureDelta(ArrayRef<unsigned> OldPressureVec, 958 ArrayRef<unsigned> NewPressureVec, 959 RegPressureDelta &Delta, 960 const RegisterClassInfo *RCI, 961 ArrayRef<unsigned> LiveThruPressureVec) { 962 Delta.Excess = PressureChange(); 963 for (unsigned i = 0, e = OldPressureVec.size(); i < e; ++i) { 964 unsigned POld = OldPressureVec[i]; 965 unsigned PNew = NewPressureVec[i]; 966 int PDiff = (int)PNew - (int)POld; 967 if (!PDiff) // No change in this set in the common case. 968 continue; 969 // Only consider change beyond the limit. 970 unsigned Limit = RCI->getRegPressureSetLimit(i); 971 if (!LiveThruPressureVec.empty()) 972 Limit += LiveThruPressureVec[i]; 973 974 if (Limit > POld) { 975 if (Limit > PNew) 976 PDiff = 0; // Under the limit 977 else 978 PDiff = PNew - Limit; // Just exceeded limit. 979 } else if (Limit > PNew) 980 PDiff = Limit - POld; // Just obeyed limit. 981 982 if (PDiff) { 983 Delta.Excess = PressureChange(i); 984 Delta.Excess.setUnitInc(PDiff); 985 break; 986 } 987 } 988 } 989 990 /// Find the max change in max pressure that either surpasses a critical PSet 991 /// limit or exceeds the current MaxPressureLimit. 992 /// 993 /// FIXME: comparing each element of the old and new MaxPressure vectors here is 994 /// silly. It's done now to demonstrate the concept but will go away with a 995 /// RegPressureTracker API change to work with pressure differences. 996 static void computeMaxPressureDelta(ArrayRef<unsigned> OldMaxPressureVec, 997 ArrayRef<unsigned> NewMaxPressureVec, 998 ArrayRef<PressureChange> CriticalPSets, 999 ArrayRef<unsigned> MaxPressureLimit, 1000 RegPressureDelta &Delta) { 1001 Delta.CriticalMax = PressureChange(); 1002 Delta.CurrentMax = PressureChange(); 1003 1004 unsigned CritIdx = 0, CritEnd = CriticalPSets.size(); 1005 for (unsigned i = 0, e = OldMaxPressureVec.size(); i < e; ++i) { 1006 unsigned POld = OldMaxPressureVec[i]; 1007 unsigned PNew = NewMaxPressureVec[i]; 1008 if (PNew == POld) // No change in this set in the common case. 1009 continue; 1010 1011 if (!Delta.CriticalMax.isValid()) { 1012 while (CritIdx != CritEnd && CriticalPSets[CritIdx].getPSet() < i) 1013 ++CritIdx; 1014 1015 if (CritIdx != CritEnd && CriticalPSets[CritIdx].getPSet() == i) { 1016 int PDiff = (int)PNew - (int)CriticalPSets[CritIdx].getUnitInc(); 1017 if (PDiff > 0) { 1018 Delta.CriticalMax = PressureChange(i); 1019 Delta.CriticalMax.setUnitInc(PDiff); 1020 } 1021 } 1022 } 1023 // Find the first increase above MaxPressureLimit. 1024 // (Ignores negative MDiff). 1025 if (!Delta.CurrentMax.isValid() && PNew > MaxPressureLimit[i]) { 1026 Delta.CurrentMax = PressureChange(i); 1027 Delta.CurrentMax.setUnitInc(PNew - POld); 1028 if (CritIdx == CritEnd || Delta.CriticalMax.isValid()) 1029 break; 1030 } 1031 } 1032 } 1033 1034 /// Record the upward impact of a single instruction on current register 1035 /// pressure. Unlike the advance/recede pressure tracking interface, this does 1036 /// not discover live in/outs. 1037 /// 1038 /// This is intended for speculative queries. It leaves pressure inconsistent 1039 /// with the current position, so must be restored by the caller. 1040 void RegPressureTracker::bumpUpwardPressure(const MachineInstr *MI) { 1041 assert(!MI->isDebugValue() && "Expect a nondebug instruction."); 1042 1043 SlotIndex SlotIdx; 1044 if (RequireIntervals) 1045 SlotIdx = LIS->getInstructionIndex(*MI).getRegSlot(); 1046 1047 // Account for register pressure similar to RegPressureTracker::recede(). 1048 RegisterOperands RegOpers; 1049 RegOpers.collect(*MI, *TRI, *MRI, TrackLaneMasks, /*IgnoreDead=*/true); 1050 assert(RegOpers.DeadDefs.size() == 0); 1051 if (TrackLaneMasks) 1052 RegOpers.adjustLaneLiveness(*LIS, *MRI, SlotIdx); 1053 else if (RequireIntervals) 1054 RegOpers.detectDeadDefs(*MI, *LIS); 1055 1056 // Boost max pressure for all dead defs together. 1057 // Since CurrSetPressure and MaxSetPressure 1058 bumpDeadDefs(RegOpers.DeadDefs); 1059 1060 // Kill liveness at live defs. 1061 for (const RegisterMaskPair &P : RegOpers.Defs) { 1062 unsigned Reg = P.RegUnit; 1063 LaneBitmask LiveLanes = LiveRegs.contains(Reg); 1064 LaneBitmask UseLanes = getRegLanes(RegOpers.Uses, Reg); 1065 LaneBitmask DefLanes = P.LaneMask; 1066 LaneBitmask LiveAfter = (LiveLanes & ~DefLanes) | UseLanes; 1067 decreaseRegPressure(Reg, LiveLanes, LiveAfter); 1068 } 1069 // Generate liveness for uses. 1070 for (const RegisterMaskPair &P : RegOpers.Uses) { 1071 unsigned Reg = P.RegUnit; 1072 LaneBitmask LiveLanes = LiveRegs.contains(Reg); 1073 LaneBitmask LiveAfter = LiveLanes | P.LaneMask; 1074 increaseRegPressure(Reg, LiveLanes, LiveAfter); 1075 } 1076 } 1077 1078 /// Consider the pressure increase caused by traversing this instruction 1079 /// bottom-up. Find the pressure set with the most change beyond its pressure 1080 /// limit based on the tracker's current pressure, and return the change in 1081 /// number of register units of that pressure set introduced by this 1082 /// instruction. 1083 /// 1084 /// This assumes that the current LiveOut set is sufficient. 1085 /// 1086 /// This is expensive for an on-the-fly query because it calls 1087 /// bumpUpwardPressure to recompute the pressure sets based on current 1088 /// liveness. This mainly exists to verify correctness, e.g. with 1089 /// -verify-misched. getUpwardPressureDelta is the fast version of this query 1090 /// that uses the per-SUnit cache of the PressureDiff. 1091 void RegPressureTracker:: 1092 getMaxUpwardPressureDelta(const MachineInstr *MI, PressureDiff *PDiff, 1093 RegPressureDelta &Delta, 1094 ArrayRef<PressureChange> CriticalPSets, 1095 ArrayRef<unsigned> MaxPressureLimit) { 1096 // Snapshot Pressure. 1097 // FIXME: The snapshot heap space should persist. But I'm planning to 1098 // summarize the pressure effect so we don't need to snapshot at all. 1099 std::vector<unsigned> SavedPressure = CurrSetPressure; 1100 std::vector<unsigned> SavedMaxPressure = P.MaxSetPressure; 1101 1102 bumpUpwardPressure(MI); 1103 1104 computeExcessPressureDelta(SavedPressure, CurrSetPressure, Delta, RCI, 1105 LiveThruPressure); 1106 computeMaxPressureDelta(SavedMaxPressure, P.MaxSetPressure, CriticalPSets, 1107 MaxPressureLimit, Delta); 1108 assert(Delta.CriticalMax.getUnitInc() >= 0 && 1109 Delta.CurrentMax.getUnitInc() >= 0 && "cannot decrease max pressure"); 1110 1111 // Restore the tracker's state. 1112 P.MaxSetPressure.swap(SavedMaxPressure); 1113 CurrSetPressure.swap(SavedPressure); 1114 1115 #ifndef NDEBUG 1116 if (!PDiff) 1117 return; 1118 1119 // Check if the alternate algorithm yields the same result. 1120 RegPressureDelta Delta2; 1121 getUpwardPressureDelta(MI, *PDiff, Delta2, CriticalPSets, MaxPressureLimit); 1122 if (Delta != Delta2) { 1123 dbgs() << "PDiff: "; 1124 PDiff->dump(*TRI); 1125 dbgs() << "DELTA: " << *MI; 1126 if (Delta.Excess.isValid()) 1127 dbgs() << "Excess1 " << TRI->getRegPressureSetName(Delta.Excess.getPSet()) 1128 << " " << Delta.Excess.getUnitInc() << "\n"; 1129 if (Delta.CriticalMax.isValid()) 1130 dbgs() << "Critic1 " << TRI->getRegPressureSetName(Delta.CriticalMax.getPSet()) 1131 << " " << Delta.CriticalMax.getUnitInc() << "\n"; 1132 if (Delta.CurrentMax.isValid()) 1133 dbgs() << "CurrMx1 " << TRI->getRegPressureSetName(Delta.CurrentMax.getPSet()) 1134 << " " << Delta.CurrentMax.getUnitInc() << "\n"; 1135 if (Delta2.Excess.isValid()) 1136 dbgs() << "Excess2 " << TRI->getRegPressureSetName(Delta2.Excess.getPSet()) 1137 << " " << Delta2.Excess.getUnitInc() << "\n"; 1138 if (Delta2.CriticalMax.isValid()) 1139 dbgs() << "Critic2 " << TRI->getRegPressureSetName(Delta2.CriticalMax.getPSet()) 1140 << " " << Delta2.CriticalMax.getUnitInc() << "\n"; 1141 if (Delta2.CurrentMax.isValid()) 1142 dbgs() << "CurrMx2 " << TRI->getRegPressureSetName(Delta2.CurrentMax.getPSet()) 1143 << " " << Delta2.CurrentMax.getUnitInc() << "\n"; 1144 llvm_unreachable("RegP Delta Mismatch"); 1145 } 1146 #endif 1147 } 1148 1149 /// This is the fast version of querying register pressure that does not 1150 /// directly depend on current liveness. 1151 /// 1152 /// @param Delta captures information needed for heuristics. 1153 /// 1154 /// @param CriticalPSets Are the pressure sets that are known to exceed some 1155 /// limit within the region, not necessarily at the current position. 1156 /// 1157 /// @param MaxPressureLimit Is the max pressure within the region, not 1158 /// necessarily at the current position. 1159 void RegPressureTracker:: 1160 getUpwardPressureDelta(const MachineInstr *MI, /*const*/ PressureDiff &PDiff, 1161 RegPressureDelta &Delta, 1162 ArrayRef<PressureChange> CriticalPSets, 1163 ArrayRef<unsigned> MaxPressureLimit) const { 1164 unsigned CritIdx = 0, CritEnd = CriticalPSets.size(); 1165 for (PressureDiff::const_iterator 1166 PDiffI = PDiff.begin(), PDiffE = PDiff.end(); 1167 PDiffI != PDiffE && PDiffI->isValid(); ++PDiffI) { 1168 1169 unsigned PSetID = PDiffI->getPSet(); 1170 unsigned Limit = RCI->getRegPressureSetLimit(PSetID); 1171 if (!LiveThruPressure.empty()) 1172 Limit += LiveThruPressure[PSetID]; 1173 1174 unsigned POld = CurrSetPressure[PSetID]; 1175 unsigned MOld = P.MaxSetPressure[PSetID]; 1176 unsigned MNew = MOld; 1177 // Ignore DeadDefs here because they aren't captured by PressureChange. 1178 unsigned PNew = POld + PDiffI->getUnitInc(); 1179 assert((PDiffI->getUnitInc() >= 0) == (PNew >= POld) 1180 && "PSet overflow/underflow"); 1181 if (PNew > MOld) 1182 MNew = PNew; 1183 // Check if current pressure has exceeded the limit. 1184 if (!Delta.Excess.isValid()) { 1185 unsigned ExcessInc = 0; 1186 if (PNew > Limit) 1187 ExcessInc = POld > Limit ? PNew - POld : PNew - Limit; 1188 else if (POld > Limit) 1189 ExcessInc = Limit - POld; 1190 if (ExcessInc) { 1191 Delta.Excess = PressureChange(PSetID); 1192 Delta.Excess.setUnitInc(ExcessInc); 1193 } 1194 } 1195 // Check if max pressure has exceeded a critical pressure set max. 1196 if (MNew == MOld) 1197 continue; 1198 if (!Delta.CriticalMax.isValid()) { 1199 while (CritIdx != CritEnd && CriticalPSets[CritIdx].getPSet() < PSetID) 1200 ++CritIdx; 1201 1202 if (CritIdx != CritEnd && CriticalPSets[CritIdx].getPSet() == PSetID) { 1203 int CritInc = (int)MNew - (int)CriticalPSets[CritIdx].getUnitInc(); 1204 if (CritInc > 0 && CritInc <= std::numeric_limits<int16_t>::max()) { 1205 Delta.CriticalMax = PressureChange(PSetID); 1206 Delta.CriticalMax.setUnitInc(CritInc); 1207 } 1208 } 1209 } 1210 // Check if max pressure has exceeded the current max. 1211 if (!Delta.CurrentMax.isValid() && MNew > MaxPressureLimit[PSetID]) { 1212 Delta.CurrentMax = PressureChange(PSetID); 1213 Delta.CurrentMax.setUnitInc(MNew - MOld); 1214 } 1215 } 1216 } 1217 1218 /// Helper to find a vreg use between two indices [PriorUseIdx, NextUseIdx). 1219 /// The query starts with a lane bitmask which gets lanes/bits removed for every 1220 /// use we find. 1221 static LaneBitmask findUseBetween(unsigned Reg, LaneBitmask LastUseMask, 1222 SlotIndex PriorUseIdx, SlotIndex NextUseIdx, 1223 const MachineRegisterInfo &MRI, 1224 const LiveIntervals *LIS) { 1225 const TargetRegisterInfo &TRI = *MRI.getTargetRegisterInfo(); 1226 for (const MachineOperand &MO : MRI.use_nodbg_operands(Reg)) { 1227 if (MO.isUndef()) 1228 continue; 1229 const MachineInstr *MI = MO.getParent(); 1230 SlotIndex InstSlot = LIS->getInstructionIndex(*MI).getRegSlot(); 1231 if (InstSlot >= PriorUseIdx && InstSlot < NextUseIdx) { 1232 unsigned SubRegIdx = MO.getSubReg(); 1233 LaneBitmask UseMask = TRI.getSubRegIndexLaneMask(SubRegIdx); 1234 LastUseMask &= ~UseMask; 1235 if (LastUseMask.none()) 1236 return LaneBitmask::getNone(); 1237 } 1238 } 1239 return LastUseMask; 1240 } 1241 1242 LaneBitmask RegPressureTracker::getLiveLanesAt(unsigned RegUnit, 1243 SlotIndex Pos) const { 1244 assert(RequireIntervals); 1245 return getLanesWithProperty(*LIS, *MRI, TrackLaneMasks, RegUnit, Pos, 1246 LaneBitmask::getAll(), 1247 [](const LiveRange &LR, SlotIndex Pos) { 1248 return LR.liveAt(Pos); 1249 }); 1250 } 1251 1252 LaneBitmask RegPressureTracker::getLastUsedLanes(unsigned RegUnit, 1253 SlotIndex Pos) const { 1254 assert(RequireIntervals); 1255 return getLanesWithProperty(*LIS, *MRI, TrackLaneMasks, RegUnit, 1256 Pos.getBaseIndex(), LaneBitmask::getNone(), 1257 [](const LiveRange &LR, SlotIndex Pos) { 1258 const LiveRange::Segment *S = LR.getSegmentContaining(Pos); 1259 return S != nullptr && S->end == Pos.getRegSlot(); 1260 }); 1261 } 1262 1263 LaneBitmask RegPressureTracker::getLiveThroughAt(unsigned RegUnit, 1264 SlotIndex Pos) const { 1265 assert(RequireIntervals); 1266 return getLanesWithProperty(*LIS, *MRI, TrackLaneMasks, RegUnit, Pos, 1267 LaneBitmask::getNone(), 1268 [](const LiveRange &LR, SlotIndex Pos) { 1269 const LiveRange::Segment *S = LR.getSegmentContaining(Pos); 1270 return S != nullptr && S->start < Pos.getRegSlot(true) && 1271 S->end != Pos.getDeadSlot(); 1272 }); 1273 } 1274 1275 /// Record the downward impact of a single instruction on current register 1276 /// pressure. Unlike the advance/recede pressure tracking interface, this does 1277 /// not discover live in/outs. 1278 /// 1279 /// This is intended for speculative queries. It leaves pressure inconsistent 1280 /// with the current position, so must be restored by the caller. 1281 void RegPressureTracker::bumpDownwardPressure(const MachineInstr *MI) { 1282 assert(!MI->isDebugValue() && "Expect a nondebug instruction."); 1283 1284 SlotIndex SlotIdx; 1285 if (RequireIntervals) 1286 SlotIdx = LIS->getInstructionIndex(*MI).getRegSlot(); 1287 1288 // Account for register pressure similar to RegPressureTracker::recede(). 1289 RegisterOperands RegOpers; 1290 RegOpers.collect(*MI, *TRI, *MRI, TrackLaneMasks, false); 1291 if (TrackLaneMasks) 1292 RegOpers.adjustLaneLiveness(*LIS, *MRI, SlotIdx); 1293 1294 if (RequireIntervals) { 1295 for (const RegisterMaskPair &Use : RegOpers.Uses) { 1296 unsigned Reg = Use.RegUnit; 1297 LaneBitmask LastUseMask = getLastUsedLanes(Reg, SlotIdx); 1298 if (LastUseMask.none()) 1299 continue; 1300 // The LastUseMask is queried from the liveness information of instruction 1301 // which may be further down the schedule. Some lanes may actually not be 1302 // last uses for the current position. 1303 // FIXME: allow the caller to pass in the list of vreg uses that remain 1304 // to be bottom-scheduled to avoid searching uses at each query. 1305 SlotIndex CurrIdx = getCurrSlot(); 1306 LastUseMask 1307 = findUseBetween(Reg, LastUseMask, CurrIdx, SlotIdx, *MRI, LIS); 1308 if (LastUseMask.none()) 1309 continue; 1310 1311 LaneBitmask LiveMask = LiveRegs.contains(Reg); 1312 LaneBitmask NewMask = LiveMask & ~LastUseMask; 1313 decreaseRegPressure(Reg, LiveMask, NewMask); 1314 } 1315 } 1316 1317 // Generate liveness for defs. 1318 for (const RegisterMaskPair &Def : RegOpers.Defs) { 1319 unsigned Reg = Def.RegUnit; 1320 LaneBitmask LiveMask = LiveRegs.contains(Reg); 1321 LaneBitmask NewMask = LiveMask | Def.LaneMask; 1322 increaseRegPressure(Reg, LiveMask, NewMask); 1323 } 1324 1325 // Boost pressure for all dead defs together. 1326 bumpDeadDefs(RegOpers.DeadDefs); 1327 } 1328 1329 /// Consider the pressure increase caused by traversing this instruction 1330 /// top-down. Find the register class with the most change in its pressure limit 1331 /// based on the tracker's current pressure, and return the number of excess 1332 /// register units of that pressure set introduced by this instruction. 1333 /// 1334 /// This assumes that the current LiveIn set is sufficient. 1335 /// 1336 /// This is expensive for an on-the-fly query because it calls 1337 /// bumpDownwardPressure to recompute the pressure sets based on current 1338 /// liveness. We don't yet have a fast version of downward pressure tracking 1339 /// analogous to getUpwardPressureDelta. 1340 void RegPressureTracker:: 1341 getMaxDownwardPressureDelta(const MachineInstr *MI, RegPressureDelta &Delta, 1342 ArrayRef<PressureChange> CriticalPSets, 1343 ArrayRef<unsigned> MaxPressureLimit) { 1344 // Snapshot Pressure. 1345 std::vector<unsigned> SavedPressure = CurrSetPressure; 1346 std::vector<unsigned> SavedMaxPressure = P.MaxSetPressure; 1347 1348 bumpDownwardPressure(MI); 1349 1350 computeExcessPressureDelta(SavedPressure, CurrSetPressure, Delta, RCI, 1351 LiveThruPressure); 1352 computeMaxPressureDelta(SavedMaxPressure, P.MaxSetPressure, CriticalPSets, 1353 MaxPressureLimit, Delta); 1354 assert(Delta.CriticalMax.getUnitInc() >= 0 && 1355 Delta.CurrentMax.getUnitInc() >= 0 && "cannot decrease max pressure"); 1356 1357 // Restore the tracker's state. 1358 P.MaxSetPressure.swap(SavedMaxPressure); 1359 CurrSetPressure.swap(SavedPressure); 1360 } 1361 1362 /// Get the pressure of each PSet after traversing this instruction bottom-up. 1363 void RegPressureTracker:: 1364 getUpwardPressure(const MachineInstr *MI, 1365 std::vector<unsigned> &PressureResult, 1366 std::vector<unsigned> &MaxPressureResult) { 1367 // Snapshot pressure. 1368 PressureResult = CurrSetPressure; 1369 MaxPressureResult = P.MaxSetPressure; 1370 1371 bumpUpwardPressure(MI); 1372 1373 // Current pressure becomes the result. Restore current pressure. 1374 P.MaxSetPressure.swap(MaxPressureResult); 1375 CurrSetPressure.swap(PressureResult); 1376 } 1377 1378 /// Get the pressure of each PSet after traversing this instruction top-down. 1379 void RegPressureTracker:: 1380 getDownwardPressure(const MachineInstr *MI, 1381 std::vector<unsigned> &PressureResult, 1382 std::vector<unsigned> &MaxPressureResult) { 1383 // Snapshot pressure. 1384 PressureResult = CurrSetPressure; 1385 MaxPressureResult = P.MaxSetPressure; 1386 1387 bumpDownwardPressure(MI); 1388 1389 // Current pressure becomes the result. Restore current pressure. 1390 P.MaxSetPressure.swap(MaxPressureResult); 1391 CurrSetPressure.swap(PressureResult); 1392 } 1393