1 //===- llvm/CodeGen/VirtRegMap.cpp - Virtual Register Map -----------------===// 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 // This file implements the VirtRegMap class. 10 // 11 // It also contains implementations of the Spiller interface, which, given a 12 // virtual register map and a machine function, eliminates all virtual 13 // references by replacing them with physical register references - adding spill 14 // code as necessary. 15 // 16 //===----------------------------------------------------------------------===// 17 18 #include "llvm/CodeGen/VirtRegMap.h" 19 #include "LiveDebugVariables.h" 20 #include "llvm/ADT/SmallVector.h" 21 #include "llvm/ADT/Statistic.h" 22 #include "llvm/CodeGen/LiveInterval.h" 23 #include "llvm/CodeGen/LiveIntervals.h" 24 #include "llvm/CodeGen/LiveStacks.h" 25 #include "llvm/CodeGen/MachineBasicBlock.h" 26 #include "llvm/CodeGen/MachineFrameInfo.h" 27 #include "llvm/CodeGen/MachineFunction.h" 28 #include "llvm/CodeGen/MachineFunctionPass.h" 29 #include "llvm/CodeGen/MachineInstr.h" 30 #include "llvm/CodeGen/MachineOperand.h" 31 #include "llvm/CodeGen/MachineRegisterInfo.h" 32 #include "llvm/CodeGen/SlotIndexes.h" 33 #include "llvm/CodeGen/TargetInstrInfo.h" 34 #include "llvm/CodeGen/TargetOpcodes.h" 35 #include "llvm/CodeGen/TargetRegisterInfo.h" 36 #include "llvm/CodeGen/TargetSubtargetInfo.h" 37 #include "llvm/Config/llvm-config.h" 38 #include "llvm/MC/LaneBitmask.h" 39 #include "llvm/Pass.h" 40 #include "llvm/Support/Compiler.h" 41 #include "llvm/Support/Debug.h" 42 #include "llvm/Support/raw_ostream.h" 43 #include <cassert> 44 #include <iterator> 45 #include <utility> 46 47 using namespace llvm; 48 49 #define DEBUG_TYPE "regalloc" 50 51 STATISTIC(NumSpillSlots, "Number of spill slots allocated"); 52 STATISTIC(NumIdCopies, "Number of identity moves eliminated after rewriting"); 53 54 //===----------------------------------------------------------------------===// 55 // VirtRegMap implementation 56 //===----------------------------------------------------------------------===// 57 58 char VirtRegMap::ID = 0; 59 60 INITIALIZE_PASS(VirtRegMap, "virtregmap", "Virtual Register Map", false, false) 61 62 bool VirtRegMap::runOnMachineFunction(MachineFunction &mf) { 63 MRI = &mf.getRegInfo(); 64 TII = mf.getSubtarget().getInstrInfo(); 65 TRI = mf.getSubtarget().getRegisterInfo(); 66 MF = &mf; 67 68 Virt2PhysMap.clear(); 69 Virt2StackSlotMap.clear(); 70 Virt2SplitMap.clear(); 71 Virt2ShapeMap.clear(); 72 73 grow(); 74 return false; 75 } 76 77 void VirtRegMap::grow() { 78 unsigned NumRegs = MF->getRegInfo().getNumVirtRegs(); 79 Virt2PhysMap.resize(NumRegs); 80 Virt2StackSlotMap.resize(NumRegs); 81 Virt2SplitMap.resize(NumRegs); 82 } 83 84 void VirtRegMap::assignVirt2Phys(Register virtReg, MCPhysReg physReg) { 85 assert(virtReg.isVirtual() && Register::isPhysicalRegister(physReg)); 86 assert(Virt2PhysMap[virtReg.id()] == NO_PHYS_REG && 87 "attempt to assign physical register to already mapped " 88 "virtual register"); 89 assert(!getRegInfo().isReserved(physReg) && 90 "Attempt to map virtReg to a reserved physReg"); 91 Virt2PhysMap[virtReg.id()] = physReg; 92 } 93 94 unsigned VirtRegMap::createSpillSlot(const TargetRegisterClass *RC) { 95 unsigned Size = TRI->getSpillSize(*RC); 96 Align Alignment = TRI->getSpillAlign(*RC); 97 int SS = MF->getFrameInfo().CreateSpillStackObject(Size, Alignment); 98 ++NumSpillSlots; 99 return SS; 100 } 101 102 bool VirtRegMap::hasPreferredPhys(Register VirtReg) const { 103 Register Hint = MRI->getSimpleHint(VirtReg); 104 if (!Hint.isValid()) 105 return false; 106 if (Hint.isVirtual()) 107 Hint = getPhys(Hint); 108 return Register(getPhys(VirtReg)) == Hint; 109 } 110 111 bool VirtRegMap::hasKnownPreference(Register VirtReg) const { 112 std::pair<unsigned, unsigned> Hint = MRI->getRegAllocationHint(VirtReg); 113 if (Register::isPhysicalRegister(Hint.second)) 114 return true; 115 if (Register::isVirtualRegister(Hint.second)) 116 return hasPhys(Hint.second); 117 return false; 118 } 119 120 int VirtRegMap::assignVirt2StackSlot(Register virtReg) { 121 assert(virtReg.isVirtual()); 122 assert(Virt2StackSlotMap[virtReg.id()] == NO_STACK_SLOT && 123 "attempt to assign stack slot to already spilled register"); 124 const TargetRegisterClass* RC = MF->getRegInfo().getRegClass(virtReg); 125 return Virt2StackSlotMap[virtReg.id()] = createSpillSlot(RC); 126 } 127 128 void VirtRegMap::assignVirt2StackSlot(Register virtReg, int SS) { 129 assert(virtReg.isVirtual()); 130 assert(Virt2StackSlotMap[virtReg.id()] == NO_STACK_SLOT && 131 "attempt to assign stack slot to already spilled register"); 132 assert((SS >= 0 || 133 (SS >= MF->getFrameInfo().getObjectIndexBegin())) && 134 "illegal fixed frame index"); 135 Virt2StackSlotMap[virtReg.id()] = SS; 136 } 137 138 void VirtRegMap::print(raw_ostream &OS, const Module*) const { 139 OS << "********** REGISTER MAP **********\n"; 140 for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) { 141 unsigned Reg = Register::index2VirtReg(i); 142 if (Virt2PhysMap[Reg] != (unsigned)VirtRegMap::NO_PHYS_REG) { 143 OS << '[' << printReg(Reg, TRI) << " -> " 144 << printReg(Virt2PhysMap[Reg], TRI) << "] " 145 << TRI->getRegClassName(MRI->getRegClass(Reg)) << "\n"; 146 } 147 } 148 149 for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) { 150 unsigned Reg = Register::index2VirtReg(i); 151 if (Virt2StackSlotMap[Reg] != VirtRegMap::NO_STACK_SLOT) { 152 OS << '[' << printReg(Reg, TRI) << " -> fi#" << Virt2StackSlotMap[Reg] 153 << "] " << TRI->getRegClassName(MRI->getRegClass(Reg)) << "\n"; 154 } 155 } 156 OS << '\n'; 157 } 158 159 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 160 LLVM_DUMP_METHOD void VirtRegMap::dump() const { 161 print(dbgs()); 162 } 163 #endif 164 165 //===----------------------------------------------------------------------===// 166 // VirtRegRewriter 167 //===----------------------------------------------------------------------===// 168 // 169 // The VirtRegRewriter is the last of the register allocator passes. 170 // It rewrites virtual registers to physical registers as specified in the 171 // VirtRegMap analysis. It also updates live-in information on basic blocks 172 // according to LiveIntervals. 173 // 174 namespace { 175 176 class VirtRegRewriter : public MachineFunctionPass { 177 MachineFunction *MF; 178 const TargetRegisterInfo *TRI; 179 const TargetInstrInfo *TII; 180 MachineRegisterInfo *MRI; 181 SlotIndexes *Indexes; 182 LiveIntervals *LIS; 183 VirtRegMap *VRM; 184 LiveDebugVariables *DebugVars; 185 DenseSet<Register> RewriteRegs; 186 bool ClearVirtRegs; 187 188 void rewrite(); 189 void addMBBLiveIns(); 190 bool readsUndefSubreg(const MachineOperand &MO) const; 191 void addLiveInsForSubRanges(const LiveInterval &LI, MCRegister PhysReg) const; 192 void handleIdentityCopy(MachineInstr &MI); 193 void expandCopyBundle(MachineInstr &MI) const; 194 bool subRegLiveThrough(const MachineInstr &MI, MCRegister SuperPhysReg) const; 195 196 public: 197 static char ID; 198 VirtRegRewriter(bool ClearVirtRegs_ = true) : 199 MachineFunctionPass(ID), 200 ClearVirtRegs(ClearVirtRegs_) {} 201 202 void getAnalysisUsage(AnalysisUsage &AU) const override; 203 204 bool runOnMachineFunction(MachineFunction&) override; 205 206 MachineFunctionProperties getSetProperties() const override { 207 if (ClearVirtRegs) { 208 return MachineFunctionProperties().set( 209 MachineFunctionProperties::Property::NoVRegs); 210 } 211 212 return MachineFunctionProperties(); 213 } 214 }; 215 216 } // end anonymous namespace 217 218 char VirtRegRewriter::ID = 0; 219 220 char &llvm::VirtRegRewriterID = VirtRegRewriter::ID; 221 222 INITIALIZE_PASS_BEGIN(VirtRegRewriter, "virtregrewriter", 223 "Virtual Register Rewriter", false, false) 224 INITIALIZE_PASS_DEPENDENCY(SlotIndexes) 225 INITIALIZE_PASS_DEPENDENCY(LiveIntervals) 226 INITIALIZE_PASS_DEPENDENCY(LiveDebugVariables) 227 INITIALIZE_PASS_DEPENDENCY(LiveStacks) 228 INITIALIZE_PASS_DEPENDENCY(VirtRegMap) 229 INITIALIZE_PASS_END(VirtRegRewriter, "virtregrewriter", 230 "Virtual Register Rewriter", false, false) 231 232 void VirtRegRewriter::getAnalysisUsage(AnalysisUsage &AU) const { 233 AU.setPreservesCFG(); 234 AU.addRequired<LiveIntervals>(); 235 AU.addPreserved<LiveIntervals>(); 236 AU.addRequired<SlotIndexes>(); 237 AU.addPreserved<SlotIndexes>(); 238 AU.addRequired<LiveDebugVariables>(); 239 AU.addRequired<LiveStacks>(); 240 AU.addPreserved<LiveStacks>(); 241 AU.addRequired<VirtRegMap>(); 242 243 if (!ClearVirtRegs) 244 AU.addPreserved<LiveDebugVariables>(); 245 246 MachineFunctionPass::getAnalysisUsage(AU); 247 } 248 249 bool VirtRegRewriter::runOnMachineFunction(MachineFunction &fn) { 250 MF = &fn; 251 TRI = MF->getSubtarget().getRegisterInfo(); 252 TII = MF->getSubtarget().getInstrInfo(); 253 MRI = &MF->getRegInfo(); 254 Indexes = &getAnalysis<SlotIndexes>(); 255 LIS = &getAnalysis<LiveIntervals>(); 256 VRM = &getAnalysis<VirtRegMap>(); 257 DebugVars = getAnalysisIfAvailable<LiveDebugVariables>(); 258 LLVM_DEBUG(dbgs() << "********** REWRITE VIRTUAL REGISTERS **********\n" 259 << "********** Function: " << MF->getName() << '\n'); 260 LLVM_DEBUG(VRM->dump()); 261 262 // Add kill flags while we still have virtual registers. 263 LIS->addKillFlags(VRM); 264 265 // Live-in lists on basic blocks are required for physregs. 266 addMBBLiveIns(); 267 268 // Rewrite virtual registers. 269 rewrite(); 270 271 if (DebugVars && ClearVirtRegs) { 272 // Write out new DBG_VALUE instructions. 273 274 // We only do this if ClearVirtRegs is specified since this should be the 275 // final run of the pass and we don't want to emit them multiple times. 276 DebugVars->emitDebugValues(VRM); 277 278 // All machine operands and other references to virtual registers have been 279 // replaced. Remove the virtual registers and release all the transient data. 280 VRM->clearAllVirt(); 281 MRI->clearVirtRegs(); 282 } 283 284 return true; 285 } 286 287 void VirtRegRewriter::addLiveInsForSubRanges(const LiveInterval &LI, 288 MCRegister PhysReg) const { 289 assert(!LI.empty()); 290 assert(LI.hasSubRanges()); 291 292 using SubRangeIteratorPair = 293 std::pair<const LiveInterval::SubRange *, LiveInterval::const_iterator>; 294 295 SmallVector<SubRangeIteratorPair, 4> SubRanges; 296 SlotIndex First; 297 SlotIndex Last; 298 for (const LiveInterval::SubRange &SR : LI.subranges()) { 299 SubRanges.push_back(std::make_pair(&SR, SR.begin())); 300 if (!First.isValid() || SR.segments.front().start < First) 301 First = SR.segments.front().start; 302 if (!Last.isValid() || SR.segments.back().end > Last) 303 Last = SR.segments.back().end; 304 } 305 306 // Check all mbb start positions between First and Last while 307 // simulatenously advancing an iterator for each subrange. 308 for (SlotIndexes::MBBIndexIterator MBBI = Indexes->findMBBIndex(First); 309 MBBI != Indexes->MBBIndexEnd() && MBBI->first <= Last; ++MBBI) { 310 SlotIndex MBBBegin = MBBI->first; 311 // Advance all subrange iterators so that their end position is just 312 // behind MBBBegin (or the iterator is at the end). 313 LaneBitmask LaneMask; 314 for (auto &RangeIterPair : SubRanges) { 315 const LiveInterval::SubRange *SR = RangeIterPair.first; 316 LiveInterval::const_iterator &SRI = RangeIterPair.second; 317 while (SRI != SR->end() && SRI->end <= MBBBegin) 318 ++SRI; 319 if (SRI == SR->end()) 320 continue; 321 if (SRI->start <= MBBBegin) 322 LaneMask |= SR->LaneMask; 323 } 324 if (LaneMask.none()) 325 continue; 326 MachineBasicBlock *MBB = MBBI->second; 327 MBB->addLiveIn(PhysReg, LaneMask); 328 } 329 } 330 331 // Compute MBB live-in lists from virtual register live ranges and their 332 // assignments. 333 void VirtRegRewriter::addMBBLiveIns() { 334 for (unsigned Idx = 0, IdxE = MRI->getNumVirtRegs(); Idx != IdxE; ++Idx) { 335 Register VirtReg = Register::index2VirtReg(Idx); 336 if (MRI->reg_nodbg_empty(VirtReg)) 337 continue; 338 LiveInterval &LI = LIS->getInterval(VirtReg); 339 if (LI.empty() || LIS->intervalIsInOneMBB(LI)) 340 continue; 341 // This is a virtual register that is live across basic blocks. Its 342 // assigned PhysReg must be marked as live-in to those blocks. 343 Register PhysReg = VRM->getPhys(VirtReg); 344 if (PhysReg == VirtRegMap::NO_PHYS_REG) { 345 // There may be no physical register assigned if only some register 346 // classes were already allocated. 347 assert(!ClearVirtRegs && "Unmapped virtual register"); 348 continue; 349 } 350 351 if (LI.hasSubRanges()) { 352 addLiveInsForSubRanges(LI, PhysReg); 353 } else { 354 // Go over MBB begin positions and see if we have segments covering them. 355 // The following works because segments and the MBBIndex list are both 356 // sorted by slot indexes. 357 SlotIndexes::MBBIndexIterator I = Indexes->MBBIndexBegin(); 358 for (const auto &Seg : LI) { 359 I = Indexes->advanceMBBIndex(I, Seg.start); 360 for (; I != Indexes->MBBIndexEnd() && I->first < Seg.end; ++I) { 361 MachineBasicBlock *MBB = I->second; 362 MBB->addLiveIn(PhysReg); 363 } 364 } 365 } 366 } 367 368 // Sort and unique MBB LiveIns as we've not checked if SubReg/PhysReg were in 369 // each MBB's LiveIns set before calling addLiveIn on them. 370 for (MachineBasicBlock &MBB : *MF) 371 MBB.sortUniqueLiveIns(); 372 } 373 374 /// Returns true if the given machine operand \p MO only reads undefined lanes. 375 /// The function only works for use operands with a subregister set. 376 bool VirtRegRewriter::readsUndefSubreg(const MachineOperand &MO) const { 377 // Shortcut if the operand is already marked undef. 378 if (MO.isUndef()) 379 return true; 380 381 Register Reg = MO.getReg(); 382 const LiveInterval &LI = LIS->getInterval(Reg); 383 const MachineInstr &MI = *MO.getParent(); 384 SlotIndex BaseIndex = LIS->getInstructionIndex(MI); 385 // This code is only meant to handle reading undefined subregisters which 386 // we couldn't properly detect before. 387 assert(LI.liveAt(BaseIndex) && 388 "Reads of completely dead register should be marked undef already"); 389 unsigned SubRegIdx = MO.getSubReg(); 390 assert(SubRegIdx != 0 && LI.hasSubRanges()); 391 LaneBitmask UseMask = TRI->getSubRegIndexLaneMask(SubRegIdx); 392 // See if any of the relevant subregister liveranges is defined at this point. 393 for (const LiveInterval::SubRange &SR : LI.subranges()) { 394 if ((SR.LaneMask & UseMask).any() && SR.liveAt(BaseIndex)) 395 return false; 396 } 397 return true; 398 } 399 400 void VirtRegRewriter::handleIdentityCopy(MachineInstr &MI) { 401 if (!MI.isIdentityCopy()) 402 return; 403 LLVM_DEBUG(dbgs() << "Identity copy: " << MI); 404 ++NumIdCopies; 405 406 Register DstReg = MI.getOperand(0).getReg(); 407 408 // We may have deferred allocation of the virtual register, and the rewrite 409 // regs code doesn't handle the liveness update. 410 if (DstReg.isVirtual()) 411 return; 412 413 RewriteRegs.insert(DstReg); 414 415 // Copies like: 416 // %r0 = COPY undef %r0 417 // %al = COPY %al, implicit-def %eax 418 // give us additional liveness information: The target (super-)register 419 // must not be valid before this point. Replace the COPY with a KILL 420 // instruction to maintain this information. 421 if (MI.getOperand(1).isUndef() || MI.getNumOperands() > 2) { 422 MI.setDesc(TII->get(TargetOpcode::KILL)); 423 LLVM_DEBUG(dbgs() << " replace by: " << MI); 424 return; 425 } 426 427 if (Indexes) 428 Indexes->removeSingleMachineInstrFromMaps(MI); 429 MI.eraseFromBundle(); 430 LLVM_DEBUG(dbgs() << " deleted.\n"); 431 } 432 433 /// The liverange splitting logic sometimes produces bundles of copies when 434 /// subregisters are involved. Expand these into a sequence of copy instructions 435 /// after processing the last in the bundle. Does not update LiveIntervals 436 /// which we shouldn't need for this instruction anymore. 437 void VirtRegRewriter::expandCopyBundle(MachineInstr &MI) const { 438 if (!MI.isCopy() && !MI.isKill()) 439 return; 440 441 if (MI.isBundledWithPred() && !MI.isBundledWithSucc()) { 442 SmallVector<MachineInstr *, 2> MIs({&MI}); 443 444 // Only do this when the complete bundle is made out of COPYs and KILLs. 445 MachineBasicBlock &MBB = *MI.getParent(); 446 for (MachineBasicBlock::reverse_instr_iterator I = 447 std::next(MI.getReverseIterator()), E = MBB.instr_rend(); 448 I != E && I->isBundledWithSucc(); ++I) { 449 if (!I->isCopy() && !I->isKill()) 450 return; 451 MIs.push_back(&*I); 452 } 453 MachineInstr *FirstMI = MIs.back(); 454 455 auto anyRegsAlias = [](const MachineInstr *Dst, 456 ArrayRef<MachineInstr *> Srcs, 457 const TargetRegisterInfo *TRI) { 458 for (const MachineInstr *Src : Srcs) 459 if (Src != Dst) 460 if (TRI->regsOverlap(Dst->getOperand(0).getReg(), 461 Src->getOperand(1).getReg())) 462 return true; 463 return false; 464 }; 465 466 // If any of the destination registers in the bundle of copies alias any of 467 // the source registers, try to schedule the instructions to avoid any 468 // clobbering. 469 for (int E = MIs.size(), PrevE = E; E > 1; PrevE = E) { 470 for (int I = E; I--; ) 471 if (!anyRegsAlias(MIs[I], makeArrayRef(MIs).take_front(E), TRI)) { 472 if (I + 1 != E) 473 std::swap(MIs[I], MIs[E - 1]); 474 --E; 475 } 476 if (PrevE == E) { 477 MF->getFunction().getContext().emitError( 478 "register rewriting failed: cycle in copy bundle"); 479 break; 480 } 481 } 482 483 MachineInstr *BundleStart = FirstMI; 484 for (MachineInstr *BundledMI : llvm::reverse(MIs)) { 485 // If instruction is in the middle of the bundle, move it before the 486 // bundle starts, otherwise, just unbundle it. When we get to the last 487 // instruction, the bundle will have been completely undone. 488 if (BundledMI != BundleStart) { 489 BundledMI->removeFromBundle(); 490 MBB.insert(BundleStart, BundledMI); 491 } else if (BundledMI->isBundledWithSucc()) { 492 BundledMI->unbundleFromSucc(); 493 BundleStart = &*std::next(BundledMI->getIterator()); 494 } 495 496 if (Indexes && BundledMI != FirstMI) 497 Indexes->insertMachineInstrInMaps(*BundledMI); 498 } 499 } 500 } 501 502 /// Check whether (part of) \p SuperPhysReg is live through \p MI. 503 /// \pre \p MI defines a subregister of a virtual register that 504 /// has been assigned to \p SuperPhysReg. 505 bool VirtRegRewriter::subRegLiveThrough(const MachineInstr &MI, 506 MCRegister SuperPhysReg) const { 507 SlotIndex MIIndex = LIS->getInstructionIndex(MI); 508 SlotIndex BeforeMIUses = MIIndex.getBaseIndex(); 509 SlotIndex AfterMIDefs = MIIndex.getBoundaryIndex(); 510 for (MCRegUnitIterator Unit(SuperPhysReg, TRI); Unit.isValid(); ++Unit) { 511 const LiveRange &UnitRange = LIS->getRegUnit(*Unit); 512 // If the regunit is live both before and after MI, 513 // we assume it is live through. 514 // Generally speaking, this is not true, because something like 515 // "RU = op RU" would match that description. 516 // However, we know that we are trying to assess whether 517 // a def of a virtual reg, vreg, is live at the same time of RU. 518 // If we are in the "RU = op RU" situation, that means that vreg 519 // is defined at the same time as RU (i.e., "vreg, RU = op RU"). 520 // Thus, vreg and RU interferes and vreg cannot be assigned to 521 // SuperPhysReg. Therefore, this situation cannot happen. 522 if (UnitRange.liveAt(AfterMIDefs) && UnitRange.liveAt(BeforeMIUses)) 523 return true; 524 } 525 return false; 526 } 527 528 void VirtRegRewriter::rewrite() { 529 bool NoSubRegLiveness = !MRI->subRegLivenessEnabled(); 530 SmallVector<Register, 8> SuperDeads; 531 SmallVector<Register, 8> SuperDefs; 532 SmallVector<Register, 8> SuperKills; 533 534 for (MachineFunction::iterator MBBI = MF->begin(), MBBE = MF->end(); 535 MBBI != MBBE; ++MBBI) { 536 LLVM_DEBUG(MBBI->print(dbgs(), Indexes)); 537 for (MachineBasicBlock::instr_iterator 538 MII = MBBI->instr_begin(), MIE = MBBI->instr_end(); MII != MIE;) { 539 MachineInstr *MI = &*MII; 540 ++MII; 541 542 for (MachineInstr::mop_iterator MOI = MI->operands_begin(), 543 MOE = MI->operands_end(); MOI != MOE; ++MOI) { 544 MachineOperand &MO = *MOI; 545 546 // Make sure MRI knows about registers clobbered by regmasks. 547 if (MO.isRegMask()) 548 MRI->addPhysRegsUsedFromRegMask(MO.getRegMask()); 549 550 if (!MO.isReg() || !MO.getReg().isVirtual()) 551 continue; 552 Register VirtReg = MO.getReg(); 553 MCRegister PhysReg = VRM->getPhys(VirtReg); 554 if (PhysReg == VirtRegMap::NO_PHYS_REG) 555 continue; 556 557 assert(Register(PhysReg).isPhysical()); 558 559 RewriteRegs.insert(PhysReg); 560 assert(!MRI->isReserved(PhysReg) && "Reserved register assignment"); 561 562 // Preserve semantics of sub-register operands. 563 unsigned SubReg = MO.getSubReg(); 564 if (SubReg != 0) { 565 if (NoSubRegLiveness || !MRI->shouldTrackSubRegLiveness(VirtReg)) { 566 // A virtual register kill refers to the whole register, so we may 567 // have to add implicit killed operands for the super-register. A 568 // partial redef always kills and redefines the super-register. 569 if ((MO.readsReg() && (MO.isDef() || MO.isKill())) || 570 (MO.isDef() && subRegLiveThrough(*MI, PhysReg))) 571 SuperKills.push_back(PhysReg); 572 573 if (MO.isDef()) { 574 // Also add implicit defs for the super-register. 575 if (MO.isDead()) 576 SuperDeads.push_back(PhysReg); 577 else 578 SuperDefs.push_back(PhysReg); 579 } 580 } else { 581 if (MO.isUse()) { 582 if (readsUndefSubreg(MO)) 583 // We need to add an <undef> flag if the subregister is 584 // completely undefined (and we are not adding super-register 585 // defs). 586 MO.setIsUndef(true); 587 } else if (!MO.isDead()) { 588 assert(MO.isDef()); 589 } 590 } 591 592 // The def undef and def internal flags only make sense for 593 // sub-register defs, and we are substituting a full physreg. An 594 // implicit killed operand from the SuperKills list will represent the 595 // partial read of the super-register. 596 if (MO.isDef()) { 597 MO.setIsUndef(false); 598 MO.setIsInternalRead(false); 599 } 600 601 // PhysReg operands cannot have subregister indexes. 602 PhysReg = TRI->getSubReg(PhysReg, SubReg); 603 assert(PhysReg.isValid() && "Invalid SubReg for physical register"); 604 MO.setSubReg(0); 605 } 606 // Rewrite. Note we could have used MachineOperand::substPhysReg(), but 607 // we need the inlining here. 608 MO.setReg(PhysReg); 609 MO.setIsRenamable(true); 610 } 611 612 // Add any missing super-register kills after rewriting the whole 613 // instruction. 614 while (!SuperKills.empty()) 615 MI->addRegisterKilled(SuperKills.pop_back_val(), TRI, true); 616 617 while (!SuperDeads.empty()) 618 MI->addRegisterDead(SuperDeads.pop_back_val(), TRI, true); 619 620 while (!SuperDefs.empty()) 621 MI->addRegisterDefined(SuperDefs.pop_back_val(), TRI); 622 623 LLVM_DEBUG(dbgs() << "> " << *MI); 624 625 expandCopyBundle(*MI); 626 627 // We can remove identity copies right now. 628 handleIdentityCopy(*MI); 629 } 630 } 631 632 if (LIS) { 633 // Don't bother maintaining accurate LiveIntervals for registers which were 634 // already allocated. 635 for (Register PhysReg : RewriteRegs) { 636 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); 637 ++Units) { 638 LIS->removeRegUnit(*Units); 639 } 640 } 641 } 642 643 RewriteRegs.clear(); 644 } 645 646 FunctionPass *llvm::createVirtRegRewriter(bool ClearVirtRegs) { 647 return new VirtRegRewriter(ClearVirtRegs); 648 } 649