1 //===- LiveIntervals.cpp - Live Interval Analysis -------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 /// \file This file implements the LiveInterval analysis pass which is used 10 /// by the Linear Scan Register allocator. This pass linearizes the 11 /// basic blocks of the function in DFS order and computes live intervals for 12 /// each virtual and physical register. 13 // 14 //===----------------------------------------------------------------------===// 15 16 #include "llvm/CodeGen/LiveIntervals.h" 17 #include "LiveRangeCalc.h" 18 #include "llvm/ADT/ArrayRef.h" 19 #include "llvm/ADT/DepthFirstIterator.h" 20 #include "llvm/ADT/SmallPtrSet.h" 21 #include "llvm/ADT/SmallVector.h" 22 #include "llvm/ADT/iterator_range.h" 23 #include "llvm/Analysis/AliasAnalysis.h" 24 #include "llvm/CodeGen/LiveInterval.h" 25 #include "llvm/CodeGen/LiveVariables.h" 26 #include "llvm/CodeGen/MachineBasicBlock.h" 27 #include "llvm/CodeGen/MachineBlockFrequencyInfo.h" 28 #include "llvm/CodeGen/MachineDominators.h" 29 #include "llvm/CodeGen/MachineFunction.h" 30 #include "llvm/CodeGen/MachineInstr.h" 31 #include "llvm/CodeGen/MachineInstrBundle.h" 32 #include "llvm/CodeGen/MachineOperand.h" 33 #include "llvm/CodeGen/MachineRegisterInfo.h" 34 #include "llvm/CodeGen/Passes.h" 35 #include "llvm/CodeGen/SlotIndexes.h" 36 #include "llvm/CodeGen/TargetRegisterInfo.h" 37 #include "llvm/CodeGen/TargetSubtargetInfo.h" 38 #include "llvm/CodeGen/VirtRegMap.h" 39 #include "llvm/Config/llvm-config.h" 40 #include "llvm/MC/LaneBitmask.h" 41 #include "llvm/MC/MCRegisterInfo.h" 42 #include "llvm/Pass.h" 43 #include "llvm/Support/BlockFrequency.h" 44 #include "llvm/Support/CommandLine.h" 45 #include "llvm/Support/Compiler.h" 46 #include "llvm/Support/Debug.h" 47 #include "llvm/Support/MathExtras.h" 48 #include "llvm/Support/raw_ostream.h" 49 #include <algorithm> 50 #include <cassert> 51 #include <cstdint> 52 #include <iterator> 53 #include <tuple> 54 #include <utility> 55 56 using namespace llvm; 57 58 #define DEBUG_TYPE "regalloc" 59 60 char LiveIntervals::ID = 0; 61 char &llvm::LiveIntervalsID = LiveIntervals::ID; 62 INITIALIZE_PASS_BEGIN(LiveIntervals, "liveintervals", 63 "Live Interval Analysis", false, false) 64 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass) 65 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree) 66 INITIALIZE_PASS_DEPENDENCY(SlotIndexes) 67 INITIALIZE_PASS_END(LiveIntervals, "liveintervals", 68 "Live Interval Analysis", false, false) 69 70 #ifndef NDEBUG 71 static cl::opt<bool> EnablePrecomputePhysRegs( 72 "precompute-phys-liveness", cl::Hidden, 73 cl::desc("Eagerly compute live intervals for all physreg units.")); 74 #else 75 static bool EnablePrecomputePhysRegs = false; 76 #endif // NDEBUG 77 78 namespace llvm { 79 80 cl::opt<bool> UseSegmentSetForPhysRegs( 81 "use-segment-set-for-physregs", cl::Hidden, cl::init(true), 82 cl::desc( 83 "Use segment set for the computation of the live ranges of physregs.")); 84 85 } // end namespace llvm 86 87 void LiveIntervals::getAnalysisUsage(AnalysisUsage &AU) const { 88 AU.setPreservesCFG(); 89 AU.addRequired<AAResultsWrapperPass>(); 90 AU.addPreserved<AAResultsWrapperPass>(); 91 AU.addPreserved<LiveVariables>(); 92 AU.addPreservedID(MachineLoopInfoID); 93 AU.addRequiredTransitiveID(MachineDominatorsID); 94 AU.addPreservedID(MachineDominatorsID); 95 AU.addPreserved<SlotIndexes>(); 96 AU.addRequiredTransitive<SlotIndexes>(); 97 MachineFunctionPass::getAnalysisUsage(AU); 98 } 99 100 LiveIntervals::LiveIntervals() : MachineFunctionPass(ID) { 101 initializeLiveIntervalsPass(*PassRegistry::getPassRegistry()); 102 } 103 104 LiveIntervals::~LiveIntervals() { 105 delete LRCalc; 106 } 107 108 void LiveIntervals::releaseMemory() { 109 // Free the live intervals themselves. 110 for (unsigned i = 0, e = VirtRegIntervals.size(); i != e; ++i) 111 delete VirtRegIntervals[Register::index2VirtReg(i)]; 112 VirtRegIntervals.clear(); 113 RegMaskSlots.clear(); 114 RegMaskBits.clear(); 115 RegMaskBlocks.clear(); 116 117 for (LiveRange *LR : RegUnitRanges) 118 delete LR; 119 RegUnitRanges.clear(); 120 121 // Release VNInfo memory regions, VNInfo objects don't need to be dtor'd. 122 VNInfoAllocator.Reset(); 123 } 124 125 bool LiveIntervals::runOnMachineFunction(MachineFunction &fn) { 126 MF = &fn; 127 MRI = &MF->getRegInfo(); 128 TRI = MF->getSubtarget().getRegisterInfo(); 129 TII = MF->getSubtarget().getInstrInfo(); 130 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults(); 131 Indexes = &getAnalysis<SlotIndexes>(); 132 DomTree = &getAnalysis<MachineDominatorTree>(); 133 134 if (!LRCalc) 135 LRCalc = new LiveRangeCalc(); 136 137 // Allocate space for all virtual registers. 138 VirtRegIntervals.resize(MRI->getNumVirtRegs()); 139 140 computeVirtRegs(); 141 computeRegMasks(); 142 computeLiveInRegUnits(); 143 144 if (EnablePrecomputePhysRegs) { 145 // For stress testing, precompute live ranges of all physical register 146 // units, including reserved registers. 147 for (unsigned i = 0, e = TRI->getNumRegUnits(); i != e; ++i) 148 getRegUnit(i); 149 } 150 LLVM_DEBUG(dump()); 151 return true; 152 } 153 154 void LiveIntervals::print(raw_ostream &OS, const Module* ) const { 155 OS << "********** INTERVALS **********\n"; 156 157 // Dump the regunits. 158 for (unsigned Unit = 0, UnitE = RegUnitRanges.size(); Unit != UnitE; ++Unit) 159 if (LiveRange *LR = RegUnitRanges[Unit]) 160 OS << printRegUnit(Unit, TRI) << ' ' << *LR << '\n'; 161 162 // Dump the virtregs. 163 for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) { 164 unsigned Reg = Register::index2VirtReg(i); 165 if (hasInterval(Reg)) 166 OS << getInterval(Reg) << '\n'; 167 } 168 169 OS << "RegMasks:"; 170 for (SlotIndex Idx : RegMaskSlots) 171 OS << ' ' << Idx; 172 OS << '\n'; 173 174 printInstrs(OS); 175 } 176 177 void LiveIntervals::printInstrs(raw_ostream &OS) const { 178 OS << "********** MACHINEINSTRS **********\n"; 179 MF->print(OS, Indexes); 180 } 181 182 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 183 LLVM_DUMP_METHOD void LiveIntervals::dumpInstrs() const { 184 printInstrs(dbgs()); 185 } 186 #endif 187 188 LiveInterval* LiveIntervals::createInterval(unsigned reg) { 189 float Weight = Register::isPhysicalRegister(reg) ? huge_valf : 0.0F; 190 return new LiveInterval(reg, Weight); 191 } 192 193 /// Compute the live interval of a virtual register, based on defs and uses. 194 void LiveIntervals::computeVirtRegInterval(LiveInterval &LI) { 195 assert(LRCalc && "LRCalc not initialized."); 196 assert(LI.empty() && "Should only compute empty intervals."); 197 LRCalc->reset(MF, getSlotIndexes(), DomTree, &getVNInfoAllocator()); 198 LRCalc->calculate(LI, MRI->shouldTrackSubRegLiveness(LI.reg)); 199 200 if (computeDeadValues(LI, nullptr)) { 201 SmallVector<LiveInterval *, 4> SplitIntervals; 202 splitSeparateComponents(LI, SplitIntervals); 203 } 204 } 205 206 void LiveIntervals::computeVirtRegs() { 207 for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) { 208 unsigned Reg = Register::index2VirtReg(i); 209 if (MRI->reg_nodbg_empty(Reg)) 210 continue; 211 createAndComputeVirtRegInterval(Reg); 212 } 213 } 214 215 void LiveIntervals::computeRegMasks() { 216 RegMaskBlocks.resize(MF->getNumBlockIDs()); 217 218 // Find all instructions with regmask operands. 219 for (const MachineBasicBlock &MBB : *MF) { 220 std::pair<unsigned, unsigned> &RMB = RegMaskBlocks[MBB.getNumber()]; 221 RMB.first = RegMaskSlots.size(); 222 223 // Some block starts, such as EH funclets, create masks. 224 if (const uint32_t *Mask = MBB.getBeginClobberMask(TRI)) { 225 RegMaskSlots.push_back(Indexes->getMBBStartIdx(&MBB)); 226 RegMaskBits.push_back(Mask); 227 } 228 229 for (const MachineInstr &MI : MBB) { 230 for (const MachineOperand &MO : MI.operands()) { 231 if (!MO.isRegMask()) 232 continue; 233 RegMaskSlots.push_back(Indexes->getInstructionIndex(MI).getRegSlot()); 234 RegMaskBits.push_back(MO.getRegMask()); 235 } 236 } 237 238 // Some block ends, such as funclet returns, create masks. Put the mask on 239 // the last instruction of the block, because MBB slot index intervals are 240 // half-open. 241 if (const uint32_t *Mask = MBB.getEndClobberMask(TRI)) { 242 assert(!MBB.empty() && "empty return block?"); 243 RegMaskSlots.push_back( 244 Indexes->getInstructionIndex(MBB.back()).getRegSlot()); 245 RegMaskBits.push_back(Mask); 246 } 247 248 // Compute the number of register mask instructions in this block. 249 RMB.second = RegMaskSlots.size() - RMB.first; 250 } 251 } 252 253 //===----------------------------------------------------------------------===// 254 // Register Unit Liveness 255 //===----------------------------------------------------------------------===// 256 // 257 // Fixed interference typically comes from ABI boundaries: Function arguments 258 // and return values are passed in fixed registers, and so are exception 259 // pointers entering landing pads. Certain instructions require values to be 260 // present in specific registers. That is also represented through fixed 261 // interference. 262 // 263 264 /// Compute the live range of a register unit, based on the uses and defs of 265 /// aliasing registers. The range should be empty, or contain only dead 266 /// phi-defs from ABI blocks. 267 void LiveIntervals::computeRegUnitRange(LiveRange &LR, unsigned Unit) { 268 assert(LRCalc && "LRCalc not initialized."); 269 LRCalc->reset(MF, getSlotIndexes(), DomTree, &getVNInfoAllocator()); 270 271 // The physregs aliasing Unit are the roots and their super-registers. 272 // Create all values as dead defs before extending to uses. Note that roots 273 // may share super-registers. That's OK because createDeadDefs() is 274 // idempotent. It is very rare for a register unit to have multiple roots, so 275 // uniquing super-registers is probably not worthwhile. 276 bool IsReserved = false; 277 for (MCRegUnitRootIterator Root(Unit, TRI); Root.isValid(); ++Root) { 278 bool IsRootReserved = true; 279 for (MCSuperRegIterator Super(*Root, TRI, /*IncludeSelf=*/true); 280 Super.isValid(); ++Super) { 281 unsigned Reg = *Super; 282 if (!MRI->reg_empty(Reg)) 283 LRCalc->createDeadDefs(LR, Reg); 284 // A register unit is considered reserved if all its roots and all their 285 // super registers are reserved. 286 if (!MRI->isReserved(Reg)) 287 IsRootReserved = false; 288 } 289 IsReserved |= IsRootReserved; 290 } 291 assert(IsReserved == MRI->isReservedRegUnit(Unit) && 292 "reserved computation mismatch"); 293 294 // Now extend LR to reach all uses. 295 // Ignore uses of reserved registers. We only track defs of those. 296 if (!IsReserved) { 297 for (MCRegUnitRootIterator Root(Unit, TRI); Root.isValid(); ++Root) { 298 for (MCSuperRegIterator Super(*Root, TRI, /*IncludeSelf=*/true); 299 Super.isValid(); ++Super) { 300 unsigned Reg = *Super; 301 if (!MRI->reg_empty(Reg)) 302 LRCalc->extendToUses(LR, Reg); 303 } 304 } 305 } 306 307 // Flush the segment set to the segment vector. 308 if (UseSegmentSetForPhysRegs) 309 LR.flushSegmentSet(); 310 } 311 312 /// Precompute the live ranges of any register units that are live-in to an ABI 313 /// block somewhere. Register values can appear without a corresponding def when 314 /// entering the entry block or a landing pad. 315 void LiveIntervals::computeLiveInRegUnits() { 316 RegUnitRanges.resize(TRI->getNumRegUnits()); 317 LLVM_DEBUG(dbgs() << "Computing live-in reg-units in ABI blocks.\n"); 318 319 // Keep track of the live range sets allocated. 320 SmallVector<unsigned, 8> NewRanges; 321 322 // Check all basic blocks for live-ins. 323 for (const MachineBasicBlock &MBB : *MF) { 324 // We only care about ABI blocks: Entry + landing pads. 325 if ((&MBB != &MF->front() && !MBB.isEHPad()) || MBB.livein_empty()) 326 continue; 327 328 // Create phi-defs at Begin for all live-in registers. 329 SlotIndex Begin = Indexes->getMBBStartIdx(&MBB); 330 LLVM_DEBUG(dbgs() << Begin << "\t" << printMBBReference(MBB)); 331 for (const auto &LI : MBB.liveins()) { 332 for (MCRegUnitIterator Units(LI.PhysReg, TRI); Units.isValid(); ++Units) { 333 unsigned Unit = *Units; 334 LiveRange *LR = RegUnitRanges[Unit]; 335 if (!LR) { 336 // Use segment set to speed-up initial computation of the live range. 337 LR = RegUnitRanges[Unit] = new LiveRange(UseSegmentSetForPhysRegs); 338 NewRanges.push_back(Unit); 339 } 340 VNInfo *VNI = LR->createDeadDef(Begin, getVNInfoAllocator()); 341 (void)VNI; 342 LLVM_DEBUG(dbgs() << ' ' << printRegUnit(Unit, TRI) << '#' << VNI->id); 343 } 344 } 345 LLVM_DEBUG(dbgs() << '\n'); 346 } 347 LLVM_DEBUG(dbgs() << "Created " << NewRanges.size() << " new intervals.\n"); 348 349 // Compute the 'normal' part of the ranges. 350 for (unsigned Unit : NewRanges) 351 computeRegUnitRange(*RegUnitRanges[Unit], Unit); 352 } 353 354 static void createSegmentsForValues(LiveRange &LR, 355 iterator_range<LiveInterval::vni_iterator> VNIs) { 356 for (VNInfo *VNI : VNIs) { 357 if (VNI->isUnused()) 358 continue; 359 SlotIndex Def = VNI->def; 360 LR.addSegment(LiveRange::Segment(Def, Def.getDeadSlot(), VNI)); 361 } 362 } 363 364 void LiveIntervals::extendSegmentsToUses(LiveRange &Segments, 365 ShrinkToUsesWorkList &WorkList, 366 unsigned Reg, LaneBitmask LaneMask) { 367 // Keep track of the PHIs that are in use. 368 SmallPtrSet<VNInfo*, 8> UsedPHIs; 369 // Blocks that have already been added to WorkList as live-out. 370 SmallPtrSet<const MachineBasicBlock*, 16> LiveOut; 371 372 auto getSubRange = [](const LiveInterval &I, LaneBitmask M) 373 -> const LiveRange& { 374 if (M.none()) 375 return I; 376 for (const LiveInterval::SubRange &SR : I.subranges()) { 377 if ((SR.LaneMask & M).any()) { 378 assert(SR.LaneMask == M && "Expecting lane masks to match exactly"); 379 return SR; 380 } 381 } 382 llvm_unreachable("Subrange for mask not found"); 383 }; 384 385 const LiveInterval &LI = getInterval(Reg); 386 const LiveRange &OldRange = getSubRange(LI, LaneMask); 387 388 // Extend intervals to reach all uses in WorkList. 389 while (!WorkList.empty()) { 390 SlotIndex Idx = WorkList.back().first; 391 VNInfo *VNI = WorkList.back().second; 392 WorkList.pop_back(); 393 const MachineBasicBlock *MBB = Indexes->getMBBFromIndex(Idx.getPrevSlot()); 394 SlotIndex BlockStart = Indexes->getMBBStartIdx(MBB); 395 396 // Extend the live range for VNI to be live at Idx. 397 if (VNInfo *ExtVNI = Segments.extendInBlock(BlockStart, Idx)) { 398 assert(ExtVNI == VNI && "Unexpected existing value number"); 399 (void)ExtVNI; 400 // Is this a PHIDef we haven't seen before? 401 if (!VNI->isPHIDef() || VNI->def != BlockStart || 402 !UsedPHIs.insert(VNI).second) 403 continue; 404 // The PHI is live, make sure the predecessors are live-out. 405 for (const MachineBasicBlock *Pred : MBB->predecessors()) { 406 if (!LiveOut.insert(Pred).second) 407 continue; 408 SlotIndex Stop = Indexes->getMBBEndIdx(Pred); 409 // A predecessor is not required to have a live-out value for a PHI. 410 if (VNInfo *PVNI = OldRange.getVNInfoBefore(Stop)) 411 WorkList.push_back(std::make_pair(Stop, PVNI)); 412 } 413 continue; 414 } 415 416 // VNI is live-in to MBB. 417 LLVM_DEBUG(dbgs() << " live-in at " << BlockStart << '\n'); 418 Segments.addSegment(LiveRange::Segment(BlockStart, Idx, VNI)); 419 420 // Make sure VNI is live-out from the predecessors. 421 for (const MachineBasicBlock *Pred : MBB->predecessors()) { 422 if (!LiveOut.insert(Pred).second) 423 continue; 424 SlotIndex Stop = Indexes->getMBBEndIdx(Pred); 425 if (VNInfo *OldVNI = OldRange.getVNInfoBefore(Stop)) { 426 assert(OldVNI == VNI && "Wrong value out of predecessor"); 427 (void)OldVNI; 428 WorkList.push_back(std::make_pair(Stop, VNI)); 429 } else { 430 #ifndef NDEBUG 431 // There was no old VNI. Verify that Stop is jointly dominated 432 // by <undef>s for this live range. 433 assert(LaneMask.any() && 434 "Missing value out of predecessor for main range"); 435 SmallVector<SlotIndex,8> Undefs; 436 LI.computeSubRangeUndefs(Undefs, LaneMask, *MRI, *Indexes); 437 assert(LiveRangeCalc::isJointlyDominated(Pred, Undefs, *Indexes) && 438 "Missing value out of predecessor for subrange"); 439 #endif 440 } 441 } 442 } 443 } 444 445 bool LiveIntervals::shrinkToUses(LiveInterval *li, 446 SmallVectorImpl<MachineInstr*> *dead) { 447 LLVM_DEBUG(dbgs() << "Shrink: " << *li << '\n'); 448 assert(Register::isVirtualRegister(li->reg) && 449 "Can only shrink virtual registers"); 450 451 // Shrink subregister live ranges. 452 bool NeedsCleanup = false; 453 for (LiveInterval::SubRange &S : li->subranges()) { 454 shrinkToUses(S, li->reg); 455 if (S.empty()) 456 NeedsCleanup = true; 457 } 458 if (NeedsCleanup) 459 li->removeEmptySubRanges(); 460 461 // Find all the values used, including PHI kills. 462 ShrinkToUsesWorkList WorkList; 463 464 // Visit all instructions reading li->reg. 465 unsigned Reg = li->reg; 466 for (MachineInstr &UseMI : MRI->reg_instructions(Reg)) { 467 if (UseMI.isDebugValue() || !UseMI.readsVirtualRegister(Reg)) 468 continue; 469 SlotIndex Idx = getInstructionIndex(UseMI).getRegSlot(); 470 LiveQueryResult LRQ = li->Query(Idx); 471 VNInfo *VNI = LRQ.valueIn(); 472 if (!VNI) { 473 // This shouldn't happen: readsVirtualRegister returns true, but there is 474 // no live value. It is likely caused by a target getting <undef> flags 475 // wrong. 476 LLVM_DEBUG( 477 dbgs() << Idx << '\t' << UseMI 478 << "Warning: Instr claims to read non-existent value in " 479 << *li << '\n'); 480 continue; 481 } 482 // Special case: An early-clobber tied operand reads and writes the 483 // register one slot early. 484 if (VNInfo *DefVNI = LRQ.valueDefined()) 485 Idx = DefVNI->def; 486 487 WorkList.push_back(std::make_pair(Idx, VNI)); 488 } 489 490 // Create new live ranges with only minimal live segments per def. 491 LiveRange NewLR; 492 createSegmentsForValues(NewLR, make_range(li->vni_begin(), li->vni_end())); 493 extendSegmentsToUses(NewLR, WorkList, Reg, LaneBitmask::getNone()); 494 495 // Move the trimmed segments back. 496 li->segments.swap(NewLR.segments); 497 498 // Handle dead values. 499 bool CanSeparate = computeDeadValues(*li, dead); 500 LLVM_DEBUG(dbgs() << "Shrunk: " << *li << '\n'); 501 return CanSeparate; 502 } 503 504 bool LiveIntervals::computeDeadValues(LiveInterval &LI, 505 SmallVectorImpl<MachineInstr*> *dead) { 506 bool MayHaveSplitComponents = false; 507 bool HaveDeadDef = false; 508 509 for (VNInfo *VNI : LI.valnos) { 510 if (VNI->isUnused()) 511 continue; 512 SlotIndex Def = VNI->def; 513 LiveRange::iterator I = LI.FindSegmentContaining(Def); 514 assert(I != LI.end() && "Missing segment for VNI"); 515 516 // Is the register live before? Otherwise we may have to add a read-undef 517 // flag for subregister defs. 518 unsigned VReg = LI.reg; 519 if (MRI->shouldTrackSubRegLiveness(VReg)) { 520 if ((I == LI.begin() || std::prev(I)->end < Def) && !VNI->isPHIDef()) { 521 MachineInstr *MI = getInstructionFromIndex(Def); 522 MI->setRegisterDefReadUndef(VReg); 523 } 524 } 525 526 if (I->end != Def.getDeadSlot()) 527 continue; 528 if (VNI->isPHIDef()) { 529 // This is a dead PHI. Remove it. 530 VNI->markUnused(); 531 LI.removeSegment(I); 532 LLVM_DEBUG(dbgs() << "Dead PHI at " << Def << " may separate interval\n"); 533 MayHaveSplitComponents = true; 534 } else { 535 // This is a dead def. Make sure the instruction knows. 536 MachineInstr *MI = getInstructionFromIndex(Def); 537 assert(MI && "No instruction defining live value"); 538 MI->addRegisterDead(LI.reg, TRI); 539 if (HaveDeadDef) 540 MayHaveSplitComponents = true; 541 HaveDeadDef = true; 542 543 if (dead && MI->allDefsAreDead()) { 544 LLVM_DEBUG(dbgs() << "All defs dead: " << Def << '\t' << *MI); 545 dead->push_back(MI); 546 } 547 } 548 } 549 return MayHaveSplitComponents; 550 } 551 552 void LiveIntervals::shrinkToUses(LiveInterval::SubRange &SR, unsigned Reg) { 553 LLVM_DEBUG(dbgs() << "Shrink: " << SR << '\n'); 554 assert(Register::isVirtualRegister(Reg) && 555 "Can only shrink virtual registers"); 556 // Find all the values used, including PHI kills. 557 ShrinkToUsesWorkList WorkList; 558 559 // Visit all instructions reading Reg. 560 SlotIndex LastIdx; 561 for (MachineOperand &MO : MRI->use_nodbg_operands(Reg)) { 562 // Skip "undef" uses. 563 if (!MO.readsReg()) 564 continue; 565 // Maybe the operand is for a subregister we don't care about. 566 unsigned SubReg = MO.getSubReg(); 567 if (SubReg != 0) { 568 LaneBitmask LaneMask = TRI->getSubRegIndexLaneMask(SubReg); 569 if ((LaneMask & SR.LaneMask).none()) 570 continue; 571 } 572 // We only need to visit each instruction once. 573 MachineInstr *UseMI = MO.getParent(); 574 SlotIndex Idx = getInstructionIndex(*UseMI).getRegSlot(); 575 if (Idx == LastIdx) 576 continue; 577 LastIdx = Idx; 578 579 LiveQueryResult LRQ = SR.Query(Idx); 580 VNInfo *VNI = LRQ.valueIn(); 581 // For Subranges it is possible that only undef values are left in that 582 // part of the subregister, so there is no real liverange at the use 583 if (!VNI) 584 continue; 585 586 // Special case: An early-clobber tied operand reads and writes the 587 // register one slot early. 588 if (VNInfo *DefVNI = LRQ.valueDefined()) 589 Idx = DefVNI->def; 590 591 WorkList.push_back(std::make_pair(Idx, VNI)); 592 } 593 594 // Create a new live ranges with only minimal live segments per def. 595 LiveRange NewLR; 596 createSegmentsForValues(NewLR, make_range(SR.vni_begin(), SR.vni_end())); 597 extendSegmentsToUses(NewLR, WorkList, Reg, SR.LaneMask); 598 599 // Move the trimmed ranges back. 600 SR.segments.swap(NewLR.segments); 601 602 // Remove dead PHI value numbers 603 for (VNInfo *VNI : SR.valnos) { 604 if (VNI->isUnused()) 605 continue; 606 const LiveRange::Segment *Segment = SR.getSegmentContaining(VNI->def); 607 assert(Segment != nullptr && "Missing segment for VNI"); 608 if (Segment->end != VNI->def.getDeadSlot()) 609 continue; 610 if (VNI->isPHIDef()) { 611 // This is a dead PHI. Remove it. 612 LLVM_DEBUG(dbgs() << "Dead PHI at " << VNI->def 613 << " may separate interval\n"); 614 VNI->markUnused(); 615 SR.removeSegment(*Segment); 616 } 617 } 618 619 LLVM_DEBUG(dbgs() << "Shrunk: " << SR << '\n'); 620 } 621 622 void LiveIntervals::extendToIndices(LiveRange &LR, 623 ArrayRef<SlotIndex> Indices, 624 ArrayRef<SlotIndex> Undefs) { 625 assert(LRCalc && "LRCalc not initialized."); 626 LRCalc->reset(MF, getSlotIndexes(), DomTree, &getVNInfoAllocator()); 627 for (SlotIndex Idx : Indices) 628 LRCalc->extend(LR, Idx, /*PhysReg=*/0, Undefs); 629 } 630 631 void LiveIntervals::pruneValue(LiveRange &LR, SlotIndex Kill, 632 SmallVectorImpl<SlotIndex> *EndPoints) { 633 LiveQueryResult LRQ = LR.Query(Kill); 634 VNInfo *VNI = LRQ.valueOutOrDead(); 635 if (!VNI) 636 return; 637 638 MachineBasicBlock *KillMBB = Indexes->getMBBFromIndex(Kill); 639 SlotIndex MBBEnd = Indexes->getMBBEndIdx(KillMBB); 640 641 // If VNI isn't live out from KillMBB, the value is trivially pruned. 642 if (LRQ.endPoint() < MBBEnd) { 643 LR.removeSegment(Kill, LRQ.endPoint()); 644 if (EndPoints) EndPoints->push_back(LRQ.endPoint()); 645 return; 646 } 647 648 // VNI is live out of KillMBB. 649 LR.removeSegment(Kill, MBBEnd); 650 if (EndPoints) EndPoints->push_back(MBBEnd); 651 652 // Find all blocks that are reachable from KillMBB without leaving VNI's live 653 // range. It is possible that KillMBB itself is reachable, so start a DFS 654 // from each successor. 655 using VisitedTy = df_iterator_default_set<MachineBasicBlock*,9>; 656 VisitedTy Visited; 657 for (MachineBasicBlock *Succ : KillMBB->successors()) { 658 for (df_ext_iterator<MachineBasicBlock*, VisitedTy> 659 I = df_ext_begin(Succ, Visited), E = df_ext_end(Succ, Visited); 660 I != E;) { 661 MachineBasicBlock *MBB = *I; 662 663 // Check if VNI is live in to MBB. 664 SlotIndex MBBStart, MBBEnd; 665 std::tie(MBBStart, MBBEnd) = Indexes->getMBBRange(MBB); 666 LiveQueryResult LRQ = LR.Query(MBBStart); 667 if (LRQ.valueIn() != VNI) { 668 // This block isn't part of the VNI segment. Prune the search. 669 I.skipChildren(); 670 continue; 671 } 672 673 // Prune the search if VNI is killed in MBB. 674 if (LRQ.endPoint() < MBBEnd) { 675 LR.removeSegment(MBBStart, LRQ.endPoint()); 676 if (EndPoints) EndPoints->push_back(LRQ.endPoint()); 677 I.skipChildren(); 678 continue; 679 } 680 681 // VNI is live through MBB. 682 LR.removeSegment(MBBStart, MBBEnd); 683 if (EndPoints) EndPoints->push_back(MBBEnd); 684 ++I; 685 } 686 } 687 } 688 689 //===----------------------------------------------------------------------===// 690 // Register allocator hooks. 691 // 692 693 void LiveIntervals::addKillFlags(const VirtRegMap *VRM) { 694 // Keep track of regunit ranges. 695 SmallVector<std::pair<const LiveRange*, LiveRange::const_iterator>, 8> RU; 696 // Keep track of subregister ranges. 697 SmallVector<std::pair<const LiveInterval::SubRange*, 698 LiveRange::const_iterator>, 4> SRs; 699 700 for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) { 701 unsigned Reg = Register::index2VirtReg(i); 702 if (MRI->reg_nodbg_empty(Reg)) 703 continue; 704 const LiveInterval &LI = getInterval(Reg); 705 if (LI.empty()) 706 continue; 707 708 // Find the regunit intervals for the assigned register. They may overlap 709 // the virtual register live range, cancelling any kills. 710 RU.clear(); 711 for (MCRegUnitIterator Unit(VRM->getPhys(Reg), TRI); Unit.isValid(); 712 ++Unit) { 713 const LiveRange &RURange = getRegUnit(*Unit); 714 if (RURange.empty()) 715 continue; 716 RU.push_back(std::make_pair(&RURange, RURange.find(LI.begin()->end))); 717 } 718 719 if (MRI->subRegLivenessEnabled()) { 720 SRs.clear(); 721 for (const LiveInterval::SubRange &SR : LI.subranges()) { 722 SRs.push_back(std::make_pair(&SR, SR.find(LI.begin()->end))); 723 } 724 } 725 726 // Every instruction that kills Reg corresponds to a segment range end 727 // point. 728 for (LiveInterval::const_iterator RI = LI.begin(), RE = LI.end(); RI != RE; 729 ++RI) { 730 // A block index indicates an MBB edge. 731 if (RI->end.isBlock()) 732 continue; 733 MachineInstr *MI = getInstructionFromIndex(RI->end); 734 if (!MI) 735 continue; 736 737 // Check if any of the regunits are live beyond the end of RI. That could 738 // happen when a physreg is defined as a copy of a virtreg: 739 // 740 // %eax = COPY %5 741 // FOO %5 <--- MI, cancel kill because %eax is live. 742 // BAR killed %eax 743 // 744 // There should be no kill flag on FOO when %5 is rewritten as %eax. 745 for (auto &RUP : RU) { 746 const LiveRange &RURange = *RUP.first; 747 LiveRange::const_iterator &I = RUP.second; 748 if (I == RURange.end()) 749 continue; 750 I = RURange.advanceTo(I, RI->end); 751 if (I == RURange.end() || I->start >= RI->end) 752 continue; 753 // I is overlapping RI. 754 goto CancelKill; 755 } 756 757 if (MRI->subRegLivenessEnabled()) { 758 // When reading a partial undefined value we must not add a kill flag. 759 // The regalloc might have used the undef lane for something else. 760 // Example: 761 // %1 = ... ; R32: %1 762 // %2:high16 = ... ; R64: %2 763 // = read killed %2 ; R64: %2 764 // = read %1 ; R32: %1 765 // The <kill> flag is correct for %2, but the register allocator may 766 // assign R0L to %1, and R0 to %2 because the low 32bits of R0 767 // are actually never written by %2. After assignment the <kill> 768 // flag at the read instruction is invalid. 769 LaneBitmask DefinedLanesMask; 770 if (!SRs.empty()) { 771 // Compute a mask of lanes that are defined. 772 DefinedLanesMask = LaneBitmask::getNone(); 773 for (auto &SRP : SRs) { 774 const LiveInterval::SubRange &SR = *SRP.first; 775 LiveRange::const_iterator &I = SRP.second; 776 if (I == SR.end()) 777 continue; 778 I = SR.advanceTo(I, RI->end); 779 if (I == SR.end() || I->start >= RI->end) 780 continue; 781 // I is overlapping RI 782 DefinedLanesMask |= SR.LaneMask; 783 } 784 } else 785 DefinedLanesMask = LaneBitmask::getAll(); 786 787 bool IsFullWrite = false; 788 for (const MachineOperand &MO : MI->operands()) { 789 if (!MO.isReg() || MO.getReg() != Reg) 790 continue; 791 if (MO.isUse()) { 792 // Reading any undefined lanes? 793 LaneBitmask UseMask = TRI->getSubRegIndexLaneMask(MO.getSubReg()); 794 if ((UseMask & ~DefinedLanesMask).any()) 795 goto CancelKill; 796 } else if (MO.getSubReg() == 0) { 797 // Writing to the full register? 798 assert(MO.isDef()); 799 IsFullWrite = true; 800 } 801 } 802 803 // If an instruction writes to a subregister, a new segment starts in 804 // the LiveInterval. But as this is only overriding part of the register 805 // adding kill-flags is not correct here after registers have been 806 // assigned. 807 if (!IsFullWrite) { 808 // Next segment has to be adjacent in the subregister write case. 809 LiveRange::const_iterator N = std::next(RI); 810 if (N != LI.end() && N->start == RI->end) 811 goto CancelKill; 812 } 813 } 814 815 MI->addRegisterKilled(Reg, nullptr); 816 continue; 817 CancelKill: 818 MI->clearRegisterKills(Reg, nullptr); 819 } 820 } 821 } 822 823 MachineBasicBlock* 824 LiveIntervals::intervalIsInOneMBB(const LiveInterval &LI) const { 825 // A local live range must be fully contained inside the block, meaning it is 826 // defined and killed at instructions, not at block boundaries. It is not 827 // live in or out of any block. 828 // 829 // It is technically possible to have a PHI-defined live range identical to a 830 // single block, but we are going to return false in that case. 831 832 SlotIndex Start = LI.beginIndex(); 833 if (Start.isBlock()) 834 return nullptr; 835 836 SlotIndex Stop = LI.endIndex(); 837 if (Stop.isBlock()) 838 return nullptr; 839 840 // getMBBFromIndex doesn't need to search the MBB table when both indexes 841 // belong to proper instructions. 842 MachineBasicBlock *MBB1 = Indexes->getMBBFromIndex(Start); 843 MachineBasicBlock *MBB2 = Indexes->getMBBFromIndex(Stop); 844 return MBB1 == MBB2 ? MBB1 : nullptr; 845 } 846 847 bool 848 LiveIntervals::hasPHIKill(const LiveInterval &LI, const VNInfo *VNI) const { 849 for (const VNInfo *PHI : LI.valnos) { 850 if (PHI->isUnused() || !PHI->isPHIDef()) 851 continue; 852 const MachineBasicBlock *PHIMBB = getMBBFromIndex(PHI->def); 853 // Conservatively return true instead of scanning huge predecessor lists. 854 if (PHIMBB->pred_size() > 100) 855 return true; 856 for (const MachineBasicBlock *Pred : PHIMBB->predecessors()) 857 if (VNI == LI.getVNInfoBefore(Indexes->getMBBEndIdx(Pred))) 858 return true; 859 } 860 return false; 861 } 862 863 float LiveIntervals::getSpillWeight(bool isDef, bool isUse, 864 const MachineBlockFrequencyInfo *MBFI, 865 const MachineInstr &MI) { 866 return getSpillWeight(isDef, isUse, MBFI, MI.getParent()); 867 } 868 869 float LiveIntervals::getSpillWeight(bool isDef, bool isUse, 870 const MachineBlockFrequencyInfo *MBFI, 871 const MachineBasicBlock *MBB) { 872 BlockFrequency Freq = MBFI->getBlockFreq(MBB); 873 const float Scale = 1.0f / MBFI->getEntryFreq(); 874 return (isDef + isUse) * (Freq.getFrequency() * Scale); 875 } 876 877 LiveRange::Segment 878 LiveIntervals::addSegmentToEndOfBlock(unsigned reg, MachineInstr &startInst) { 879 LiveInterval& Interval = createEmptyInterval(reg); 880 VNInfo *VN = Interval.getNextValue( 881 SlotIndex(getInstructionIndex(startInst).getRegSlot()), 882 getVNInfoAllocator()); 883 LiveRange::Segment S(SlotIndex(getInstructionIndex(startInst).getRegSlot()), 884 getMBBEndIdx(startInst.getParent()), VN); 885 Interval.addSegment(S); 886 887 return S; 888 } 889 890 //===----------------------------------------------------------------------===// 891 // Register mask functions 892 //===----------------------------------------------------------------------===// 893 894 bool LiveIntervals::checkRegMaskInterference(LiveInterval &LI, 895 BitVector &UsableRegs) { 896 if (LI.empty()) 897 return false; 898 LiveInterval::iterator LiveI = LI.begin(), LiveE = LI.end(); 899 900 // Use a smaller arrays for local live ranges. 901 ArrayRef<SlotIndex> Slots; 902 ArrayRef<const uint32_t*> Bits; 903 if (MachineBasicBlock *MBB = intervalIsInOneMBB(LI)) { 904 Slots = getRegMaskSlotsInBlock(MBB->getNumber()); 905 Bits = getRegMaskBitsInBlock(MBB->getNumber()); 906 } else { 907 Slots = getRegMaskSlots(); 908 Bits = getRegMaskBits(); 909 } 910 911 // We are going to enumerate all the register mask slots contained in LI. 912 // Start with a binary search of RegMaskSlots to find a starting point. 913 ArrayRef<SlotIndex>::iterator SlotI = llvm::lower_bound(Slots, LiveI->start); 914 ArrayRef<SlotIndex>::iterator SlotE = Slots.end(); 915 916 // No slots in range, LI begins after the last call. 917 if (SlotI == SlotE) 918 return false; 919 920 bool Found = false; 921 while (true) { 922 assert(*SlotI >= LiveI->start); 923 // Loop over all slots overlapping this segment. 924 while (*SlotI < LiveI->end) { 925 // *SlotI overlaps LI. Collect mask bits. 926 if (!Found) { 927 // This is the first overlap. Initialize UsableRegs to all ones. 928 UsableRegs.clear(); 929 UsableRegs.resize(TRI->getNumRegs(), true); 930 Found = true; 931 } 932 // Remove usable registers clobbered by this mask. 933 UsableRegs.clearBitsNotInMask(Bits[SlotI-Slots.begin()]); 934 if (++SlotI == SlotE) 935 return Found; 936 } 937 // *SlotI is beyond the current LI segment. 938 LiveI = LI.advanceTo(LiveI, *SlotI); 939 if (LiveI == LiveE) 940 return Found; 941 // Advance SlotI until it overlaps. 942 while (*SlotI < LiveI->start) 943 if (++SlotI == SlotE) 944 return Found; 945 } 946 } 947 948 //===----------------------------------------------------------------------===// 949 // IntervalUpdate class. 950 //===----------------------------------------------------------------------===// 951 952 /// Toolkit used by handleMove to trim or extend live intervals. 953 class LiveIntervals::HMEditor { 954 private: 955 LiveIntervals& LIS; 956 const MachineRegisterInfo& MRI; 957 const TargetRegisterInfo& TRI; 958 SlotIndex OldIdx; 959 SlotIndex NewIdx; 960 SmallPtrSet<LiveRange*, 8> Updated; 961 bool UpdateFlags; 962 963 public: 964 HMEditor(LiveIntervals& LIS, const MachineRegisterInfo& MRI, 965 const TargetRegisterInfo& TRI, 966 SlotIndex OldIdx, SlotIndex NewIdx, bool UpdateFlags) 967 : LIS(LIS), MRI(MRI), TRI(TRI), OldIdx(OldIdx), NewIdx(NewIdx), 968 UpdateFlags(UpdateFlags) {} 969 970 // FIXME: UpdateFlags is a workaround that creates live intervals for all 971 // physregs, even those that aren't needed for regalloc, in order to update 972 // kill flags. This is wasteful. Eventually, LiveVariables will strip all kill 973 // flags, and postRA passes will use a live register utility instead. 974 LiveRange *getRegUnitLI(unsigned Unit) { 975 if (UpdateFlags && !MRI.isReservedRegUnit(Unit)) 976 return &LIS.getRegUnit(Unit); 977 return LIS.getCachedRegUnit(Unit); 978 } 979 980 /// Update all live ranges touched by MI, assuming a move from OldIdx to 981 /// NewIdx. 982 void updateAllRanges(MachineInstr *MI) { 983 LLVM_DEBUG(dbgs() << "handleMove " << OldIdx << " -> " << NewIdx << ": " 984 << *MI); 985 bool hasRegMask = false; 986 for (MachineOperand &MO : MI->operands()) { 987 if (MO.isRegMask()) 988 hasRegMask = true; 989 if (!MO.isReg()) 990 continue; 991 if (MO.isUse()) { 992 if (!MO.readsReg()) 993 continue; 994 // Aggressively clear all kill flags. 995 // They are reinserted by VirtRegRewriter. 996 MO.setIsKill(false); 997 } 998 999 Register Reg = MO.getReg(); 1000 if (!Reg) 1001 continue; 1002 if (Register::isVirtualRegister(Reg)) { 1003 LiveInterval &LI = LIS.getInterval(Reg); 1004 if (LI.hasSubRanges()) { 1005 unsigned SubReg = MO.getSubReg(); 1006 LaneBitmask LaneMask = SubReg ? TRI.getSubRegIndexLaneMask(SubReg) 1007 : MRI.getMaxLaneMaskForVReg(Reg); 1008 for (LiveInterval::SubRange &S : LI.subranges()) { 1009 if ((S.LaneMask & LaneMask).none()) 1010 continue; 1011 updateRange(S, Reg, S.LaneMask); 1012 } 1013 } 1014 updateRange(LI, Reg, LaneBitmask::getNone()); 1015 continue; 1016 } 1017 1018 // For physregs, only update the regunits that actually have a 1019 // precomputed live range. 1020 for (MCRegUnitIterator Units(Reg, &TRI); Units.isValid(); ++Units) 1021 if (LiveRange *LR = getRegUnitLI(*Units)) 1022 updateRange(*LR, *Units, LaneBitmask::getNone()); 1023 } 1024 if (hasRegMask) 1025 updateRegMaskSlots(); 1026 } 1027 1028 private: 1029 /// Update a single live range, assuming an instruction has been moved from 1030 /// OldIdx to NewIdx. 1031 void updateRange(LiveRange &LR, unsigned Reg, LaneBitmask LaneMask) { 1032 if (!Updated.insert(&LR).second) 1033 return; 1034 LLVM_DEBUG({ 1035 dbgs() << " "; 1036 if (Register::isVirtualRegister(Reg)) { 1037 dbgs() << printReg(Reg); 1038 if (LaneMask.any()) 1039 dbgs() << " L" << PrintLaneMask(LaneMask); 1040 } else { 1041 dbgs() << printRegUnit(Reg, &TRI); 1042 } 1043 dbgs() << ":\t" << LR << '\n'; 1044 }); 1045 if (SlotIndex::isEarlierInstr(OldIdx, NewIdx)) 1046 handleMoveDown(LR); 1047 else 1048 handleMoveUp(LR, Reg, LaneMask); 1049 LLVM_DEBUG(dbgs() << " -->\t" << LR << '\n'); 1050 LR.verify(); 1051 } 1052 1053 /// Update LR to reflect an instruction has been moved downwards from OldIdx 1054 /// to NewIdx (OldIdx < NewIdx). 1055 void handleMoveDown(LiveRange &LR) { 1056 LiveRange::iterator E = LR.end(); 1057 // Segment going into OldIdx. 1058 LiveRange::iterator OldIdxIn = LR.find(OldIdx.getBaseIndex()); 1059 1060 // No value live before or after OldIdx? Nothing to do. 1061 if (OldIdxIn == E || SlotIndex::isEarlierInstr(OldIdx, OldIdxIn->start)) 1062 return; 1063 1064 LiveRange::iterator OldIdxOut; 1065 // Do we have a value live-in to OldIdx? 1066 if (SlotIndex::isEarlierInstr(OldIdxIn->start, OldIdx)) { 1067 // If the live-in value already extends to NewIdx, there is nothing to do. 1068 if (SlotIndex::isEarlierEqualInstr(NewIdx, OldIdxIn->end)) 1069 return; 1070 // Aggressively remove all kill flags from the old kill point. 1071 // Kill flags shouldn't be used while live intervals exist, they will be 1072 // reinserted by VirtRegRewriter. 1073 if (MachineInstr *KillMI = LIS.getInstructionFromIndex(OldIdxIn->end)) 1074 for (MIBundleOperands MO(*KillMI); MO.isValid(); ++MO) 1075 if (MO->isReg() && MO->isUse()) 1076 MO->setIsKill(false); 1077 1078 // Is there a def before NewIdx which is not OldIdx? 1079 LiveRange::iterator Next = std::next(OldIdxIn); 1080 if (Next != E && !SlotIndex::isSameInstr(OldIdx, Next->start) && 1081 SlotIndex::isEarlierInstr(Next->start, NewIdx)) { 1082 // If we are here then OldIdx was just a use but not a def. We only have 1083 // to ensure liveness extends to NewIdx. 1084 LiveRange::iterator NewIdxIn = 1085 LR.advanceTo(Next, NewIdx.getBaseIndex()); 1086 // Extend the segment before NewIdx if necessary. 1087 if (NewIdxIn == E || 1088 !SlotIndex::isEarlierInstr(NewIdxIn->start, NewIdx)) { 1089 LiveRange::iterator Prev = std::prev(NewIdxIn); 1090 Prev->end = NewIdx.getRegSlot(); 1091 } 1092 // Extend OldIdxIn. 1093 OldIdxIn->end = Next->start; 1094 return; 1095 } 1096 1097 // Adjust OldIdxIn->end to reach NewIdx. This may temporarily make LR 1098 // invalid by overlapping ranges. 1099 bool isKill = SlotIndex::isSameInstr(OldIdx, OldIdxIn->end); 1100 OldIdxIn->end = NewIdx.getRegSlot(OldIdxIn->end.isEarlyClobber()); 1101 // If this was not a kill, then there was no def and we're done. 1102 if (!isKill) 1103 return; 1104 1105 // Did we have a Def at OldIdx? 1106 OldIdxOut = Next; 1107 if (OldIdxOut == E || !SlotIndex::isSameInstr(OldIdx, OldIdxOut->start)) 1108 return; 1109 } else { 1110 OldIdxOut = OldIdxIn; 1111 } 1112 1113 // If we are here then there is a Definition at OldIdx. OldIdxOut points 1114 // to the segment starting there. 1115 assert(OldIdxOut != E && SlotIndex::isSameInstr(OldIdx, OldIdxOut->start) && 1116 "No def?"); 1117 VNInfo *OldIdxVNI = OldIdxOut->valno; 1118 assert(OldIdxVNI->def == OldIdxOut->start && "Inconsistent def"); 1119 1120 // If the defined value extends beyond NewIdx, just move the beginning 1121 // of the segment to NewIdx. 1122 SlotIndex NewIdxDef = NewIdx.getRegSlot(OldIdxOut->start.isEarlyClobber()); 1123 if (SlotIndex::isEarlierInstr(NewIdxDef, OldIdxOut->end)) { 1124 OldIdxVNI->def = NewIdxDef; 1125 OldIdxOut->start = OldIdxVNI->def; 1126 return; 1127 } 1128 1129 // If we are here then we have a Definition at OldIdx which ends before 1130 // NewIdx. 1131 1132 // Is there an existing Def at NewIdx? 1133 LiveRange::iterator AfterNewIdx 1134 = LR.advanceTo(OldIdxOut, NewIdx.getRegSlot()); 1135 bool OldIdxDefIsDead = OldIdxOut->end.isDead(); 1136 if (!OldIdxDefIsDead && 1137 SlotIndex::isEarlierInstr(OldIdxOut->end, NewIdxDef)) { 1138 // OldIdx is not a dead def, and NewIdxDef is inside a new interval. 1139 VNInfo *DefVNI; 1140 if (OldIdxOut != LR.begin() && 1141 !SlotIndex::isEarlierInstr(std::prev(OldIdxOut)->end, 1142 OldIdxOut->start)) { 1143 // There is no gap between OldIdxOut and its predecessor anymore, 1144 // merge them. 1145 LiveRange::iterator IPrev = std::prev(OldIdxOut); 1146 DefVNI = OldIdxVNI; 1147 IPrev->end = OldIdxOut->end; 1148 } else { 1149 // The value is live in to OldIdx 1150 LiveRange::iterator INext = std::next(OldIdxOut); 1151 assert(INext != E && "Must have following segment"); 1152 // We merge OldIdxOut and its successor. As we're dealing with subreg 1153 // reordering, there is always a successor to OldIdxOut in the same BB 1154 // We don't need INext->valno anymore and will reuse for the new segment 1155 // we create later. 1156 DefVNI = OldIdxVNI; 1157 INext->start = OldIdxOut->end; 1158 INext->valno->def = INext->start; 1159 } 1160 // If NewIdx is behind the last segment, extend that and append a new one. 1161 if (AfterNewIdx == E) { 1162 // OldIdxOut is undef at this point, Slide (OldIdxOut;AfterNewIdx] up 1163 // one position. 1164 // |- ?/OldIdxOut -| |- X0 -| ... |- Xn -| end 1165 // => |- X0/OldIdxOut -| ... |- Xn -| |- undef/NewS -| end 1166 std::copy(std::next(OldIdxOut), E, OldIdxOut); 1167 // The last segment is undefined now, reuse it for a dead def. 1168 LiveRange::iterator NewSegment = std::prev(E); 1169 *NewSegment = LiveRange::Segment(NewIdxDef, NewIdxDef.getDeadSlot(), 1170 DefVNI); 1171 DefVNI->def = NewIdxDef; 1172 1173 LiveRange::iterator Prev = std::prev(NewSegment); 1174 Prev->end = NewIdxDef; 1175 } else { 1176 // OldIdxOut is undef at this point, Slide (OldIdxOut;AfterNewIdx] up 1177 // one position. 1178 // |- ?/OldIdxOut -| |- X0 -| ... |- Xn/AfterNewIdx -| |- Next -| 1179 // => |- X0/OldIdxOut -| ... |- Xn -| |- Xn/AfterNewIdx -| |- Next -| 1180 std::copy(std::next(OldIdxOut), std::next(AfterNewIdx), OldIdxOut); 1181 LiveRange::iterator Prev = std::prev(AfterNewIdx); 1182 // We have two cases: 1183 if (SlotIndex::isEarlierInstr(Prev->start, NewIdxDef)) { 1184 // Case 1: NewIdx is inside a liverange. Split this liverange at 1185 // NewIdxDef into the segment "Prev" followed by "NewSegment". 1186 LiveRange::iterator NewSegment = AfterNewIdx; 1187 *NewSegment = LiveRange::Segment(NewIdxDef, Prev->end, Prev->valno); 1188 Prev->valno->def = NewIdxDef; 1189 1190 *Prev = LiveRange::Segment(Prev->start, NewIdxDef, DefVNI); 1191 DefVNI->def = Prev->start; 1192 } else { 1193 // Case 2: NewIdx is in a lifetime hole. Keep AfterNewIdx as is and 1194 // turn Prev into a segment from NewIdx to AfterNewIdx->start. 1195 *Prev = LiveRange::Segment(NewIdxDef, AfterNewIdx->start, DefVNI); 1196 DefVNI->def = NewIdxDef; 1197 assert(DefVNI != AfterNewIdx->valno); 1198 } 1199 } 1200 return; 1201 } 1202 1203 if (AfterNewIdx != E && 1204 SlotIndex::isSameInstr(AfterNewIdx->start, NewIdxDef)) { 1205 // There is an existing def at NewIdx. The def at OldIdx is coalesced into 1206 // that value. 1207 assert(AfterNewIdx->valno != OldIdxVNI && "Multiple defs of value?"); 1208 LR.removeValNo(OldIdxVNI); 1209 } else { 1210 // There was no existing def at NewIdx. We need to create a dead def 1211 // at NewIdx. Shift segments over the old OldIdxOut segment, this frees 1212 // a new segment at the place where we want to construct the dead def. 1213 // |- OldIdxOut -| |- X0 -| ... |- Xn -| |- AfterNewIdx -| 1214 // => |- X0/OldIdxOut -| ... |- Xn -| |- undef/NewS. -| |- AfterNewIdx -| 1215 assert(AfterNewIdx != OldIdxOut && "Inconsistent iterators"); 1216 std::copy(std::next(OldIdxOut), AfterNewIdx, OldIdxOut); 1217 // We can reuse OldIdxVNI now. 1218 LiveRange::iterator NewSegment = std::prev(AfterNewIdx); 1219 VNInfo *NewSegmentVNI = OldIdxVNI; 1220 NewSegmentVNI->def = NewIdxDef; 1221 *NewSegment = LiveRange::Segment(NewIdxDef, NewIdxDef.getDeadSlot(), 1222 NewSegmentVNI); 1223 } 1224 } 1225 1226 /// Update LR to reflect an instruction has been moved upwards from OldIdx 1227 /// to NewIdx (NewIdx < OldIdx). 1228 void handleMoveUp(LiveRange &LR, unsigned Reg, LaneBitmask LaneMask) { 1229 LiveRange::iterator E = LR.end(); 1230 // Segment going into OldIdx. 1231 LiveRange::iterator OldIdxIn = LR.find(OldIdx.getBaseIndex()); 1232 1233 // No value live before or after OldIdx? Nothing to do. 1234 if (OldIdxIn == E || SlotIndex::isEarlierInstr(OldIdx, OldIdxIn->start)) 1235 return; 1236 1237 LiveRange::iterator OldIdxOut; 1238 // Do we have a value live-in to OldIdx? 1239 if (SlotIndex::isEarlierInstr(OldIdxIn->start, OldIdx)) { 1240 // If the live-in value isn't killed here, then we have no Def at 1241 // OldIdx, moreover the value must be live at NewIdx so there is nothing 1242 // to do. 1243 bool isKill = SlotIndex::isSameInstr(OldIdx, OldIdxIn->end); 1244 if (!isKill) 1245 return; 1246 1247 // At this point we have to move OldIdxIn->end back to the nearest 1248 // previous use or (dead-)def but no further than NewIdx. 1249 SlotIndex DefBeforeOldIdx 1250 = std::max(OldIdxIn->start.getDeadSlot(), 1251 NewIdx.getRegSlot(OldIdxIn->end.isEarlyClobber())); 1252 OldIdxIn->end = findLastUseBefore(DefBeforeOldIdx, Reg, LaneMask); 1253 1254 // Did we have a Def at OldIdx? If not we are done now. 1255 OldIdxOut = std::next(OldIdxIn); 1256 if (OldIdxOut == E || !SlotIndex::isSameInstr(OldIdx, OldIdxOut->start)) 1257 return; 1258 } else { 1259 OldIdxOut = OldIdxIn; 1260 OldIdxIn = OldIdxOut != LR.begin() ? std::prev(OldIdxOut) : E; 1261 } 1262 1263 // If we are here then there is a Definition at OldIdx. OldIdxOut points 1264 // to the segment starting there. 1265 assert(OldIdxOut != E && SlotIndex::isSameInstr(OldIdx, OldIdxOut->start) && 1266 "No def?"); 1267 VNInfo *OldIdxVNI = OldIdxOut->valno; 1268 assert(OldIdxVNI->def == OldIdxOut->start && "Inconsistent def"); 1269 bool OldIdxDefIsDead = OldIdxOut->end.isDead(); 1270 1271 // Is there an existing def at NewIdx? 1272 SlotIndex NewIdxDef = NewIdx.getRegSlot(OldIdxOut->start.isEarlyClobber()); 1273 LiveRange::iterator NewIdxOut = LR.find(NewIdx.getRegSlot()); 1274 if (SlotIndex::isSameInstr(NewIdxOut->start, NewIdx)) { 1275 assert(NewIdxOut->valno != OldIdxVNI && 1276 "Same value defined more than once?"); 1277 // If OldIdx was a dead def remove it. 1278 if (!OldIdxDefIsDead) { 1279 // Remove segment starting at NewIdx and move begin of OldIdxOut to 1280 // NewIdx so it can take its place. 1281 OldIdxVNI->def = NewIdxDef; 1282 OldIdxOut->start = NewIdxDef; 1283 LR.removeValNo(NewIdxOut->valno); 1284 } else { 1285 // Simply remove the dead def at OldIdx. 1286 LR.removeValNo(OldIdxVNI); 1287 } 1288 } else { 1289 // Previously nothing was live after NewIdx, so all we have to do now is 1290 // move the begin of OldIdxOut to NewIdx. 1291 if (!OldIdxDefIsDead) { 1292 // Do we have any intermediate Defs between OldIdx and NewIdx? 1293 if (OldIdxIn != E && 1294 SlotIndex::isEarlierInstr(NewIdxDef, OldIdxIn->start)) { 1295 // OldIdx is not a dead def and NewIdx is before predecessor start. 1296 LiveRange::iterator NewIdxIn = NewIdxOut; 1297 assert(NewIdxIn == LR.find(NewIdx.getBaseIndex())); 1298 const SlotIndex SplitPos = NewIdxDef; 1299 OldIdxVNI = OldIdxIn->valno; 1300 1301 // Merge the OldIdxIn and OldIdxOut segments into OldIdxOut. 1302 OldIdxOut->valno->def = OldIdxIn->start; 1303 *OldIdxOut = LiveRange::Segment(OldIdxIn->start, OldIdxOut->end, 1304 OldIdxOut->valno); 1305 // OldIdxIn and OldIdxVNI are now undef and can be overridden. 1306 // We Slide [NewIdxIn, OldIdxIn) down one position. 1307 // |- X0/NewIdxIn -| ... |- Xn-1 -||- Xn/OldIdxIn -||- OldIdxOut -| 1308 // => |- undef/NexIdxIn -| |- X0 -| ... |- Xn-1 -| |- Xn/OldIdxOut -| 1309 std::copy_backward(NewIdxIn, OldIdxIn, OldIdxOut); 1310 // NewIdxIn is now considered undef so we can reuse it for the moved 1311 // value. 1312 LiveRange::iterator NewSegment = NewIdxIn; 1313 LiveRange::iterator Next = std::next(NewSegment); 1314 if (SlotIndex::isEarlierInstr(Next->start, NewIdx)) { 1315 // There is no gap between NewSegment and its predecessor. 1316 *NewSegment = LiveRange::Segment(Next->start, SplitPos, 1317 Next->valno); 1318 *Next = LiveRange::Segment(SplitPos, Next->end, OldIdxVNI); 1319 Next->valno->def = SplitPos; 1320 } else { 1321 // There is a gap between NewSegment and its predecessor 1322 // Value becomes live in. 1323 *NewSegment = LiveRange::Segment(SplitPos, Next->start, OldIdxVNI); 1324 NewSegment->valno->def = SplitPos; 1325 } 1326 } else { 1327 // Leave the end point of a live def. 1328 OldIdxOut->start = NewIdxDef; 1329 OldIdxVNI->def = NewIdxDef; 1330 if (OldIdxIn != E && SlotIndex::isEarlierInstr(NewIdx, OldIdxIn->end)) 1331 OldIdxIn->end = NewIdx.getRegSlot(); 1332 } 1333 } else if (OldIdxIn != E 1334 && SlotIndex::isEarlierInstr(NewIdxOut->start, NewIdx) 1335 && SlotIndex::isEarlierInstr(NewIdx, NewIdxOut->end)) { 1336 // OldIdxVNI is a dead def that has been moved into the middle of 1337 // another value in LR. That can happen when LR is a whole register, 1338 // but the dead def is a write to a subreg that is dead at NewIdx. 1339 // The dead def may have been moved across other values 1340 // in LR, so move OldIdxOut up to NewIdxOut. Slide [NewIdxOut;OldIdxOut) 1341 // down one position. 1342 // |- X0/NewIdxOut -| ... |- Xn-1 -| |- Xn/OldIdxOut -| |- next - | 1343 // => |- X0/NewIdxOut -| |- X0 -| ... |- Xn-1 -| |- next -| 1344 std::copy_backward(NewIdxOut, OldIdxOut, std::next(OldIdxOut)); 1345 // Modify the segment at NewIdxOut and the following segment to meet at 1346 // the point of the dead def, with the following segment getting 1347 // OldIdxVNI as its value number. 1348 *NewIdxOut = LiveRange::Segment( 1349 NewIdxOut->start, NewIdxDef.getRegSlot(), NewIdxOut->valno); 1350 *(NewIdxOut + 1) = LiveRange::Segment( 1351 NewIdxDef.getRegSlot(), (NewIdxOut + 1)->end, OldIdxVNI); 1352 OldIdxVNI->def = NewIdxDef; 1353 // Modify subsequent segments to be defined by the moved def OldIdxVNI. 1354 for (auto Idx = NewIdxOut + 2; Idx <= OldIdxOut; ++Idx) 1355 Idx->valno = OldIdxVNI; 1356 // Aggressively remove all dead flags from the former dead definition. 1357 // Kill/dead flags shouldn't be used while live intervals exist; they 1358 // will be reinserted by VirtRegRewriter. 1359 if (MachineInstr *KillMI = LIS.getInstructionFromIndex(NewIdx)) 1360 for (MIBundleOperands MO(*KillMI); MO.isValid(); ++MO) 1361 if (MO->isReg() && !MO->isUse()) 1362 MO->setIsDead(false); 1363 } else { 1364 // OldIdxVNI is a dead def. It may have been moved across other values 1365 // in LR, so move OldIdxOut up to NewIdxOut. Slide [NewIdxOut;OldIdxOut) 1366 // down one position. 1367 // |- X0/NewIdxOut -| ... |- Xn-1 -| |- Xn/OldIdxOut -| |- next - | 1368 // => |- undef/NewIdxOut -| |- X0 -| ... |- Xn-1 -| |- next -| 1369 std::copy_backward(NewIdxOut, OldIdxOut, std::next(OldIdxOut)); 1370 // OldIdxVNI can be reused now to build a new dead def segment. 1371 LiveRange::iterator NewSegment = NewIdxOut; 1372 VNInfo *NewSegmentVNI = OldIdxVNI; 1373 *NewSegment = LiveRange::Segment(NewIdxDef, NewIdxDef.getDeadSlot(), 1374 NewSegmentVNI); 1375 NewSegmentVNI->def = NewIdxDef; 1376 } 1377 } 1378 } 1379 1380 void updateRegMaskSlots() { 1381 SmallVectorImpl<SlotIndex>::iterator RI = 1382 llvm::lower_bound(LIS.RegMaskSlots, OldIdx); 1383 assert(RI != LIS.RegMaskSlots.end() && *RI == OldIdx.getRegSlot() && 1384 "No RegMask at OldIdx."); 1385 *RI = NewIdx.getRegSlot(); 1386 assert((RI == LIS.RegMaskSlots.begin() || 1387 SlotIndex::isEarlierInstr(*std::prev(RI), *RI)) && 1388 "Cannot move regmask instruction above another call"); 1389 assert((std::next(RI) == LIS.RegMaskSlots.end() || 1390 SlotIndex::isEarlierInstr(*RI, *std::next(RI))) && 1391 "Cannot move regmask instruction below another call"); 1392 } 1393 1394 // Return the last use of reg between NewIdx and OldIdx. 1395 SlotIndex findLastUseBefore(SlotIndex Before, unsigned Reg, 1396 LaneBitmask LaneMask) { 1397 if (Register::isVirtualRegister(Reg)) { 1398 SlotIndex LastUse = Before; 1399 for (MachineOperand &MO : MRI.use_nodbg_operands(Reg)) { 1400 if (MO.isUndef()) 1401 continue; 1402 unsigned SubReg = MO.getSubReg(); 1403 if (SubReg != 0 && LaneMask.any() 1404 && (TRI.getSubRegIndexLaneMask(SubReg) & LaneMask).none()) 1405 continue; 1406 1407 const MachineInstr &MI = *MO.getParent(); 1408 SlotIndex InstSlot = LIS.getSlotIndexes()->getInstructionIndex(MI); 1409 if (InstSlot > LastUse && InstSlot < OldIdx) 1410 LastUse = InstSlot.getRegSlot(); 1411 } 1412 return LastUse; 1413 } 1414 1415 // This is a regunit interval, so scanning the use list could be very 1416 // expensive. Scan upwards from OldIdx instead. 1417 assert(Before < OldIdx && "Expected upwards move"); 1418 SlotIndexes *Indexes = LIS.getSlotIndexes(); 1419 MachineBasicBlock *MBB = Indexes->getMBBFromIndex(Before); 1420 1421 // OldIdx may not correspond to an instruction any longer, so set MII to 1422 // point to the next instruction after OldIdx, or MBB->end(). 1423 MachineBasicBlock::iterator MII = MBB->end(); 1424 if (MachineInstr *MI = Indexes->getInstructionFromIndex( 1425 Indexes->getNextNonNullIndex(OldIdx))) 1426 if (MI->getParent() == MBB) 1427 MII = MI; 1428 1429 MachineBasicBlock::iterator Begin = MBB->begin(); 1430 while (MII != Begin) { 1431 if ((--MII)->isDebugInstr()) 1432 continue; 1433 SlotIndex Idx = Indexes->getInstructionIndex(*MII); 1434 1435 // Stop searching when Before is reached. 1436 if (!SlotIndex::isEarlierInstr(Before, Idx)) 1437 return Before; 1438 1439 // Check if MII uses Reg. 1440 for (MIBundleOperands MO(*MII); MO.isValid(); ++MO) 1441 if (MO->isReg() && !MO->isUndef() && 1442 Register::isPhysicalRegister(MO->getReg()) && 1443 TRI.hasRegUnit(MO->getReg(), Reg)) 1444 return Idx.getRegSlot(); 1445 } 1446 // Didn't reach Before. It must be the first instruction in the block. 1447 return Before; 1448 } 1449 }; 1450 1451 void LiveIntervals::handleMove(MachineInstr &MI, bool UpdateFlags) { 1452 // It is fine to move a bundle as a whole, but not an individual instruction 1453 // inside it. 1454 assert((!MI.isBundled() || MI.getOpcode() == TargetOpcode::BUNDLE) && 1455 "Cannot move instruction in bundle"); 1456 SlotIndex OldIndex = Indexes->getInstructionIndex(MI); 1457 Indexes->removeMachineInstrFromMaps(MI); 1458 SlotIndex NewIndex = Indexes->insertMachineInstrInMaps(MI); 1459 assert(getMBBStartIdx(MI.getParent()) <= OldIndex && 1460 OldIndex < getMBBEndIdx(MI.getParent()) && 1461 "Cannot handle moves across basic block boundaries."); 1462 1463 HMEditor HME(*this, *MRI, *TRI, OldIndex, NewIndex, UpdateFlags); 1464 HME.updateAllRanges(&MI); 1465 } 1466 1467 void LiveIntervals::handleMoveIntoBundle(MachineInstr &MI, 1468 MachineInstr &BundleStart, 1469 bool UpdateFlags) { 1470 SlotIndex OldIndex = Indexes->getInstructionIndex(MI); 1471 SlotIndex NewIndex = Indexes->getInstructionIndex(BundleStart); 1472 HMEditor HME(*this, *MRI, *TRI, OldIndex, NewIndex, UpdateFlags); 1473 HME.updateAllRanges(&MI); 1474 } 1475 1476 void LiveIntervals::repairOldRegInRange(const MachineBasicBlock::iterator Begin, 1477 const MachineBasicBlock::iterator End, 1478 const SlotIndex endIdx, 1479 LiveRange &LR, const unsigned Reg, 1480 LaneBitmask LaneMask) { 1481 LiveInterval::iterator LII = LR.find(endIdx); 1482 SlotIndex lastUseIdx; 1483 if (LII == LR.begin()) { 1484 // This happens when the function is called for a subregister that only 1485 // occurs _after_ the range that is to be repaired. 1486 return; 1487 } 1488 if (LII != LR.end() && LII->start < endIdx) 1489 lastUseIdx = LII->end; 1490 else 1491 --LII; 1492 1493 for (MachineBasicBlock::iterator I = End; I != Begin;) { 1494 --I; 1495 MachineInstr &MI = *I; 1496 if (MI.isDebugInstr()) 1497 continue; 1498 1499 SlotIndex instrIdx = getInstructionIndex(MI); 1500 bool isStartValid = getInstructionFromIndex(LII->start); 1501 bool isEndValid = getInstructionFromIndex(LII->end); 1502 1503 // FIXME: This doesn't currently handle early-clobber or multiple removed 1504 // defs inside of the region to repair. 1505 for (MachineInstr::mop_iterator OI = MI.operands_begin(), 1506 OE = MI.operands_end(); 1507 OI != OE; ++OI) { 1508 const MachineOperand &MO = *OI; 1509 if (!MO.isReg() || MO.getReg() != Reg) 1510 continue; 1511 1512 unsigned SubReg = MO.getSubReg(); 1513 LaneBitmask Mask = TRI->getSubRegIndexLaneMask(SubReg); 1514 if ((Mask & LaneMask).none()) 1515 continue; 1516 1517 if (MO.isDef()) { 1518 if (!isStartValid) { 1519 if (LII->end.isDead()) { 1520 SlotIndex prevStart; 1521 if (LII != LR.begin()) 1522 prevStart = std::prev(LII)->start; 1523 1524 // FIXME: This could be more efficient if there was a 1525 // removeSegment method that returned an iterator. 1526 LR.removeSegment(*LII, true); 1527 if (prevStart.isValid()) 1528 LII = LR.find(prevStart); 1529 else 1530 LII = LR.begin(); 1531 } else { 1532 LII->start = instrIdx.getRegSlot(); 1533 LII->valno->def = instrIdx.getRegSlot(); 1534 if (MO.getSubReg() && !MO.isUndef()) 1535 lastUseIdx = instrIdx.getRegSlot(); 1536 else 1537 lastUseIdx = SlotIndex(); 1538 continue; 1539 } 1540 } 1541 1542 if (!lastUseIdx.isValid()) { 1543 VNInfo *VNI = LR.getNextValue(instrIdx.getRegSlot(), VNInfoAllocator); 1544 LiveRange::Segment S(instrIdx.getRegSlot(), 1545 instrIdx.getDeadSlot(), VNI); 1546 LII = LR.addSegment(S); 1547 } else if (LII->start != instrIdx.getRegSlot()) { 1548 VNInfo *VNI = LR.getNextValue(instrIdx.getRegSlot(), VNInfoAllocator); 1549 LiveRange::Segment S(instrIdx.getRegSlot(), lastUseIdx, VNI); 1550 LII = LR.addSegment(S); 1551 } 1552 1553 if (MO.getSubReg() && !MO.isUndef()) 1554 lastUseIdx = instrIdx.getRegSlot(); 1555 else 1556 lastUseIdx = SlotIndex(); 1557 } else if (MO.isUse()) { 1558 // FIXME: This should probably be handled outside of this branch, 1559 // either as part of the def case (for defs inside of the region) or 1560 // after the loop over the region. 1561 if (!isEndValid && !LII->end.isBlock()) 1562 LII->end = instrIdx.getRegSlot(); 1563 if (!lastUseIdx.isValid()) 1564 lastUseIdx = instrIdx.getRegSlot(); 1565 } 1566 } 1567 } 1568 } 1569 1570 void 1571 LiveIntervals::repairIntervalsInRange(MachineBasicBlock *MBB, 1572 MachineBasicBlock::iterator Begin, 1573 MachineBasicBlock::iterator End, 1574 ArrayRef<unsigned> OrigRegs) { 1575 // Find anchor points, which are at the beginning/end of blocks or at 1576 // instructions that already have indexes. 1577 while (Begin != MBB->begin() && !Indexes->hasIndex(*Begin)) 1578 --Begin; 1579 while (End != MBB->end() && !Indexes->hasIndex(*End)) 1580 ++End; 1581 1582 SlotIndex endIdx; 1583 if (End == MBB->end()) 1584 endIdx = getMBBEndIdx(MBB).getPrevSlot(); 1585 else 1586 endIdx = getInstructionIndex(*End); 1587 1588 Indexes->repairIndexesInRange(MBB, Begin, End); 1589 1590 for (MachineBasicBlock::iterator I = End; I != Begin;) { 1591 --I; 1592 MachineInstr &MI = *I; 1593 if (MI.isDebugInstr()) 1594 continue; 1595 for (MachineInstr::const_mop_iterator MOI = MI.operands_begin(), 1596 MOE = MI.operands_end(); 1597 MOI != MOE; ++MOI) { 1598 if (MOI->isReg() && Register::isVirtualRegister(MOI->getReg()) && 1599 !hasInterval(MOI->getReg())) { 1600 createAndComputeVirtRegInterval(MOI->getReg()); 1601 } 1602 } 1603 } 1604 1605 for (unsigned Reg : OrigRegs) { 1606 if (!Register::isVirtualRegister(Reg)) 1607 continue; 1608 1609 LiveInterval &LI = getInterval(Reg); 1610 // FIXME: Should we support undefs that gain defs? 1611 if (!LI.hasAtLeastOneValue()) 1612 continue; 1613 1614 for (LiveInterval::SubRange &S : LI.subranges()) 1615 repairOldRegInRange(Begin, End, endIdx, S, Reg, S.LaneMask); 1616 1617 repairOldRegInRange(Begin, End, endIdx, LI, Reg); 1618 } 1619 } 1620 1621 void LiveIntervals::removePhysRegDefAt(unsigned Reg, SlotIndex Pos) { 1622 for (MCRegUnitIterator Unit(Reg, TRI); Unit.isValid(); ++Unit) { 1623 if (LiveRange *LR = getCachedRegUnit(*Unit)) 1624 if (VNInfo *VNI = LR->getVNInfoAt(Pos)) 1625 LR->removeValNo(VNI); 1626 } 1627 } 1628 1629 void LiveIntervals::removeVRegDefAt(LiveInterval &LI, SlotIndex Pos) { 1630 // LI may not have the main range computed yet, but its subranges may 1631 // be present. 1632 VNInfo *VNI = LI.getVNInfoAt(Pos); 1633 if (VNI != nullptr) { 1634 assert(VNI->def.getBaseIndex() == Pos.getBaseIndex()); 1635 LI.removeValNo(VNI); 1636 } 1637 1638 // Also remove the value defined in subranges. 1639 for (LiveInterval::SubRange &S : LI.subranges()) { 1640 if (VNInfo *SVNI = S.getVNInfoAt(Pos)) 1641 if (SVNI->def.getBaseIndex() == Pos.getBaseIndex()) 1642 S.removeValNo(SVNI); 1643 } 1644 LI.removeEmptySubRanges(); 1645 } 1646 1647 void LiveIntervals::splitSeparateComponents(LiveInterval &LI, 1648 SmallVectorImpl<LiveInterval*> &SplitLIs) { 1649 ConnectedVNInfoEqClasses ConEQ(*this); 1650 unsigned NumComp = ConEQ.Classify(LI); 1651 if (NumComp <= 1) 1652 return; 1653 LLVM_DEBUG(dbgs() << " Split " << NumComp << " components: " << LI << '\n'); 1654 unsigned Reg = LI.reg; 1655 const TargetRegisterClass *RegClass = MRI->getRegClass(Reg); 1656 for (unsigned I = 1; I < NumComp; ++I) { 1657 Register NewVReg = MRI->createVirtualRegister(RegClass); 1658 LiveInterval &NewLI = createEmptyInterval(NewVReg); 1659 SplitLIs.push_back(&NewLI); 1660 } 1661 ConEQ.Distribute(LI, SplitLIs.data(), *MRI); 1662 } 1663 1664 void LiveIntervals::constructMainRangeFromSubranges(LiveInterval &LI) { 1665 assert(LRCalc && "LRCalc not initialized."); 1666 LRCalc->reset(MF, getSlotIndexes(), DomTree, &getVNInfoAllocator()); 1667 LRCalc->constructMainRangeFromSubranges(LI); 1668 } 1669