1 //===-- lib/Codegen/MachineRegisterInfo.cpp -------------------------------===// 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 // Implementation of the MachineRegisterInfo class. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "llvm/CodeGen/MachineRegisterInfo.h" 15 #include "llvm/CodeGen/MachineInstrBuilder.h" 16 #include "llvm/IR/Function.h" 17 #include "llvm/Support/raw_os_ostream.h" 18 #include "llvm/Target/TargetInstrInfo.h" 19 #include "llvm/Target/TargetMachine.h" 20 #include "llvm/Target/TargetSubtargetInfo.h" 21 22 using namespace llvm; 23 24 static cl::opt<bool> EnableSubRegLiveness("enable-subreg-liveness", cl::Hidden, 25 cl::init(true), cl::desc("Enable subregister liveness tracking.")); 26 27 // Pin the vtable to this file. 28 void MachineRegisterInfo::Delegate::anchor() {} 29 30 MachineRegisterInfo::MachineRegisterInfo(MachineFunction *MF) 31 : MF(MF), TheDelegate(nullptr), 32 TracksSubRegLiveness(MF->getSubtarget().enableSubRegLiveness() && 33 EnableSubRegLiveness) { 34 unsigned NumRegs = getTargetRegisterInfo()->getNumRegs(); 35 VRegInfo.reserve(256); 36 RegAllocHints.reserve(256); 37 UsedPhysRegMask.resize(NumRegs); 38 PhysRegUseDefLists.reset(new MachineOperand*[NumRegs]()); 39 } 40 41 /// setRegClass - Set the register class of the specified virtual register. 42 /// 43 void 44 MachineRegisterInfo::setRegClass(unsigned Reg, const TargetRegisterClass *RC) { 45 assert(RC && RC->isAllocatable() && "Invalid RC for virtual register"); 46 VRegInfo[Reg].first = RC; 47 } 48 49 void MachineRegisterInfo::setRegBank(unsigned Reg, 50 const RegisterBank &RegBank) { 51 VRegInfo[Reg].first = &RegBank; 52 } 53 54 const TargetRegisterClass * 55 MachineRegisterInfo::constrainRegClass(unsigned Reg, 56 const TargetRegisterClass *RC, 57 unsigned MinNumRegs) { 58 const TargetRegisterClass *OldRC = getRegClass(Reg); 59 if (OldRC == RC) 60 return RC; 61 const TargetRegisterClass *NewRC = 62 getTargetRegisterInfo()->getCommonSubClass(OldRC, RC); 63 if (!NewRC || NewRC == OldRC) 64 return NewRC; 65 if (NewRC->getNumRegs() < MinNumRegs) 66 return nullptr; 67 setRegClass(Reg, NewRC); 68 return NewRC; 69 } 70 71 bool 72 MachineRegisterInfo::recomputeRegClass(unsigned Reg) { 73 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo(); 74 const TargetRegisterClass *OldRC = getRegClass(Reg); 75 const TargetRegisterClass *NewRC = 76 getTargetRegisterInfo()->getLargestLegalSuperClass(OldRC, *MF); 77 78 // Stop early if there is no room to grow. 79 if (NewRC == OldRC) 80 return false; 81 82 // Accumulate constraints from all uses. 83 for (MachineOperand &MO : reg_nodbg_operands(Reg)) { 84 // Apply the effect of the given operand to NewRC. 85 MachineInstr *MI = MO.getParent(); 86 unsigned OpNo = &MO - &MI->getOperand(0); 87 NewRC = MI->getRegClassConstraintEffect(OpNo, NewRC, TII, 88 getTargetRegisterInfo()); 89 if (!NewRC || NewRC == OldRC) 90 return false; 91 } 92 setRegClass(Reg, NewRC); 93 return true; 94 } 95 96 unsigned MachineRegisterInfo::createIncompleteVirtualRegister() { 97 unsigned Reg = TargetRegisterInfo::index2VirtReg(getNumVirtRegs()); 98 VRegInfo.grow(Reg); 99 RegAllocHints.grow(Reg); 100 return Reg; 101 } 102 103 /// createVirtualRegister - Create and return a new virtual register in the 104 /// function with the specified register class. 105 /// 106 unsigned 107 MachineRegisterInfo::createVirtualRegister(const TargetRegisterClass *RegClass){ 108 assert(RegClass && "Cannot create register without RegClass!"); 109 assert(RegClass->isAllocatable() && 110 "Virtual register RegClass must be allocatable."); 111 112 // New virtual register number. 113 unsigned Reg = createIncompleteVirtualRegister(); 114 VRegInfo[Reg].first = RegClass; 115 if (TheDelegate) 116 TheDelegate->MRI_NoteNewVirtualRegister(Reg); 117 return Reg; 118 } 119 120 LLT MachineRegisterInfo::getType(unsigned VReg) const { 121 VRegToTypeMap::const_iterator TypeIt = getVRegToType().find(VReg); 122 return TypeIt != getVRegToType().end() ? TypeIt->second : LLT{}; 123 } 124 125 void MachineRegisterInfo::setType(unsigned VReg, LLT Ty) { 126 // Check that VReg doesn't have a class. 127 assert((getRegClassOrRegBank(VReg).isNull() || 128 !getRegClassOrRegBank(VReg).is<const TargetRegisterClass *>()) && 129 "Can't set the size of a non-generic virtual register"); 130 getVRegToType()[VReg] = Ty; 131 } 132 133 unsigned 134 MachineRegisterInfo::createGenericVirtualRegister(LLT Ty) { 135 // New virtual register number. 136 unsigned Reg = createIncompleteVirtualRegister(); 137 // FIXME: Should we use a dummy register class? 138 VRegInfo[Reg].first = static_cast<RegisterBank *>(nullptr); 139 getVRegToType()[Reg] = Ty; 140 if (TheDelegate) 141 TheDelegate->MRI_NoteNewVirtualRegister(Reg); 142 return Reg; 143 } 144 145 void MachineRegisterInfo::clearVirtRegTypes() { 146 getVRegToType().clear(); 147 } 148 149 /// clearVirtRegs - Remove all virtual registers (after physreg assignment). 150 void MachineRegisterInfo::clearVirtRegs() { 151 #ifndef NDEBUG 152 for (unsigned i = 0, e = getNumVirtRegs(); i != e; ++i) { 153 unsigned Reg = TargetRegisterInfo::index2VirtReg(i); 154 if (!VRegInfo[Reg].second) 155 continue; 156 verifyUseList(Reg); 157 llvm_unreachable("Remaining virtual register operands"); 158 } 159 #endif 160 VRegInfo.clear(); 161 for (auto &I : LiveIns) 162 I.second = 0; 163 } 164 165 void MachineRegisterInfo::verifyUseList(unsigned Reg) const { 166 #ifndef NDEBUG 167 bool Valid = true; 168 for (MachineOperand &M : reg_operands(Reg)) { 169 MachineOperand *MO = &M; 170 MachineInstr *MI = MO->getParent(); 171 if (!MI) { 172 errs() << PrintReg(Reg, getTargetRegisterInfo()) 173 << " use list MachineOperand " << MO 174 << " has no parent instruction.\n"; 175 Valid = false; 176 continue; 177 } 178 MachineOperand *MO0 = &MI->getOperand(0); 179 unsigned NumOps = MI->getNumOperands(); 180 if (!(MO >= MO0 && MO < MO0+NumOps)) { 181 errs() << PrintReg(Reg, getTargetRegisterInfo()) 182 << " use list MachineOperand " << MO 183 << " doesn't belong to parent MI: " << *MI; 184 Valid = false; 185 } 186 if (!MO->isReg()) { 187 errs() << PrintReg(Reg, getTargetRegisterInfo()) 188 << " MachineOperand " << MO << ": " << *MO 189 << " is not a register\n"; 190 Valid = false; 191 } 192 if (MO->getReg() != Reg) { 193 errs() << PrintReg(Reg, getTargetRegisterInfo()) 194 << " use-list MachineOperand " << MO << ": " 195 << *MO << " is the wrong register\n"; 196 Valid = false; 197 } 198 } 199 assert(Valid && "Invalid use list"); 200 #endif 201 } 202 203 void MachineRegisterInfo::verifyUseLists() const { 204 #ifndef NDEBUG 205 for (unsigned i = 0, e = getNumVirtRegs(); i != e; ++i) 206 verifyUseList(TargetRegisterInfo::index2VirtReg(i)); 207 for (unsigned i = 1, e = getTargetRegisterInfo()->getNumRegs(); i != e; ++i) 208 verifyUseList(i); 209 #endif 210 } 211 212 /// Add MO to the linked list of operands for its register. 213 void MachineRegisterInfo::addRegOperandToUseList(MachineOperand *MO) { 214 assert(!MO->isOnRegUseList() && "Already on list"); 215 MachineOperand *&HeadRef = getRegUseDefListHead(MO->getReg()); 216 MachineOperand *const Head = HeadRef; 217 218 // Head points to the first list element. 219 // Next is NULL on the last list element. 220 // Prev pointers are circular, so Head->Prev == Last. 221 222 // Head is NULL for an empty list. 223 if (!Head) { 224 MO->Contents.Reg.Prev = MO; 225 MO->Contents.Reg.Next = nullptr; 226 HeadRef = MO; 227 return; 228 } 229 assert(MO->getReg() == Head->getReg() && "Different regs on the same list!"); 230 231 // Insert MO between Last and Head in the circular Prev chain. 232 MachineOperand *Last = Head->Contents.Reg.Prev; 233 assert(Last && "Inconsistent use list"); 234 assert(MO->getReg() == Last->getReg() && "Different regs on the same list!"); 235 Head->Contents.Reg.Prev = MO; 236 MO->Contents.Reg.Prev = Last; 237 238 // Def operands always precede uses. This allows def_iterator to stop early. 239 // Insert def operands at the front, and use operands at the back. 240 if (MO->isDef()) { 241 // Insert def at the front. 242 MO->Contents.Reg.Next = Head; 243 HeadRef = MO; 244 } else { 245 // Insert use at the end. 246 MO->Contents.Reg.Next = nullptr; 247 Last->Contents.Reg.Next = MO; 248 } 249 } 250 251 /// Remove MO from its use-def list. 252 void MachineRegisterInfo::removeRegOperandFromUseList(MachineOperand *MO) { 253 assert(MO->isOnRegUseList() && "Operand not on use list"); 254 MachineOperand *&HeadRef = getRegUseDefListHead(MO->getReg()); 255 MachineOperand *const Head = HeadRef; 256 assert(Head && "List already empty"); 257 258 // Unlink this from the doubly linked list of operands. 259 MachineOperand *Next = MO->Contents.Reg.Next; 260 MachineOperand *Prev = MO->Contents.Reg.Prev; 261 262 // Prev links are circular, next link is NULL instead of looping back to Head. 263 if (MO == Head) 264 HeadRef = Next; 265 else 266 Prev->Contents.Reg.Next = Next; 267 268 (Next ? Next : Head)->Contents.Reg.Prev = Prev; 269 270 MO->Contents.Reg.Prev = nullptr; 271 MO->Contents.Reg.Next = nullptr; 272 } 273 274 /// Move NumOps operands from Src to Dst, updating use-def lists as needed. 275 /// 276 /// The Dst range is assumed to be uninitialized memory. (Or it may contain 277 /// operands that won't be destroyed, which is OK because the MO destructor is 278 /// trivial anyway). 279 /// 280 /// The Src and Dst ranges may overlap. 281 void MachineRegisterInfo::moveOperands(MachineOperand *Dst, 282 MachineOperand *Src, 283 unsigned NumOps) { 284 assert(Src != Dst && NumOps && "Noop moveOperands"); 285 286 // Copy backwards if Dst is within the Src range. 287 int Stride = 1; 288 if (Dst >= Src && Dst < Src + NumOps) { 289 Stride = -1; 290 Dst += NumOps - 1; 291 Src += NumOps - 1; 292 } 293 294 // Copy one operand at a time. 295 do { 296 new (Dst) MachineOperand(*Src); 297 298 // Dst takes Src's place in the use-def chain. 299 if (Src->isReg()) { 300 MachineOperand *&Head = getRegUseDefListHead(Src->getReg()); 301 MachineOperand *Prev = Src->Contents.Reg.Prev; 302 MachineOperand *Next = Src->Contents.Reg.Next; 303 assert(Head && "List empty, but operand is chained"); 304 assert(Prev && "Operand was not on use-def list"); 305 306 // Prev links are circular, next link is NULL instead of looping back to 307 // Head. 308 if (Src == Head) 309 Head = Dst; 310 else 311 Prev->Contents.Reg.Next = Dst; 312 313 // Update Prev pointer. This also works when Src was pointing to itself 314 // in a 1-element list. In that case Head == Dst. 315 (Next ? Next : Head)->Contents.Reg.Prev = Dst; 316 } 317 318 Dst += Stride; 319 Src += Stride; 320 } while (--NumOps); 321 } 322 323 /// replaceRegWith - Replace all instances of FromReg with ToReg in the 324 /// machine function. This is like llvm-level X->replaceAllUsesWith(Y), 325 /// except that it also changes any definitions of the register as well. 326 /// If ToReg is a physical register we apply the sub register to obtain the 327 /// final/proper physical register. 328 void MachineRegisterInfo::replaceRegWith(unsigned FromReg, unsigned ToReg) { 329 assert(FromReg != ToReg && "Cannot replace a reg with itself"); 330 331 const TargetRegisterInfo *TRI = getTargetRegisterInfo(); 332 333 // TODO: This could be more efficient by bulk changing the operands. 334 for (reg_iterator I = reg_begin(FromReg), E = reg_end(); I != E; ) { 335 MachineOperand &O = *I; 336 ++I; 337 if (TargetRegisterInfo::isPhysicalRegister(ToReg)) { 338 O.substPhysReg(ToReg, *TRI); 339 } else { 340 O.setReg(ToReg); 341 } 342 } 343 } 344 345 /// getVRegDef - Return the machine instr that defines the specified virtual 346 /// register or null if none is found. This assumes that the code is in SSA 347 /// form, so there should only be one definition. 348 MachineInstr *MachineRegisterInfo::getVRegDef(unsigned Reg) const { 349 // Since we are in SSA form, we can use the first definition. 350 def_instr_iterator I = def_instr_begin(Reg); 351 assert((I.atEnd() || std::next(I) == def_instr_end()) && 352 "getVRegDef assumes a single definition or no definition"); 353 return !I.atEnd() ? &*I : nullptr; 354 } 355 356 /// getUniqueVRegDef - Return the unique machine instr that defines the 357 /// specified virtual register or null if none is found. If there are 358 /// multiple definitions or no definition, return null. 359 MachineInstr *MachineRegisterInfo::getUniqueVRegDef(unsigned Reg) const { 360 if (def_empty(Reg)) return nullptr; 361 def_instr_iterator I = def_instr_begin(Reg); 362 if (std::next(I) != def_instr_end()) 363 return nullptr; 364 return &*I; 365 } 366 367 bool MachineRegisterInfo::hasOneNonDBGUse(unsigned RegNo) const { 368 use_nodbg_iterator UI = use_nodbg_begin(RegNo); 369 if (UI == use_nodbg_end()) 370 return false; 371 return ++UI == use_nodbg_end(); 372 } 373 374 /// clearKillFlags - Iterate over all the uses of the given register and 375 /// clear the kill flag from the MachineOperand. This function is used by 376 /// optimization passes which extend register lifetimes and need only 377 /// preserve conservative kill flag information. 378 void MachineRegisterInfo::clearKillFlags(unsigned Reg) const { 379 for (MachineOperand &MO : use_operands(Reg)) 380 MO.setIsKill(false); 381 } 382 383 bool MachineRegisterInfo::isLiveIn(unsigned Reg) const { 384 for (livein_iterator I = livein_begin(), E = livein_end(); I != E; ++I) 385 if (I->first == Reg || I->second == Reg) 386 return true; 387 return false; 388 } 389 390 /// getLiveInPhysReg - If VReg is a live-in virtual register, return the 391 /// corresponding live-in physical register. 392 unsigned MachineRegisterInfo::getLiveInPhysReg(unsigned VReg) const { 393 for (livein_iterator I = livein_begin(), E = livein_end(); I != E; ++I) 394 if (I->second == VReg) 395 return I->first; 396 return 0; 397 } 398 399 /// getLiveInVirtReg - If PReg is a live-in physical register, return the 400 /// corresponding live-in physical register. 401 unsigned MachineRegisterInfo::getLiveInVirtReg(unsigned PReg) const { 402 for (livein_iterator I = livein_begin(), E = livein_end(); I != E; ++I) 403 if (I->first == PReg) 404 return I->second; 405 return 0; 406 } 407 408 /// EmitLiveInCopies - Emit copies to initialize livein virtual registers 409 /// into the given entry block. 410 void 411 MachineRegisterInfo::EmitLiveInCopies(MachineBasicBlock *EntryMBB, 412 const TargetRegisterInfo &TRI, 413 const TargetInstrInfo &TII) { 414 // Emit the copies into the top of the block. 415 for (unsigned i = 0, e = LiveIns.size(); i != e; ++i) 416 if (LiveIns[i].second) { 417 if (use_empty(LiveIns[i].second)) { 418 // The livein has no uses. Drop it. 419 // 420 // It would be preferable to have isel avoid creating live-in 421 // records for unused arguments in the first place, but it's 422 // complicated by the debug info code for arguments. 423 LiveIns.erase(LiveIns.begin() + i); 424 --i; --e; 425 } else { 426 // Emit a copy. 427 BuildMI(*EntryMBB, EntryMBB->begin(), DebugLoc(), 428 TII.get(TargetOpcode::COPY), LiveIns[i].second) 429 .addReg(LiveIns[i].first); 430 431 // Add the register to the entry block live-in set. 432 EntryMBB->addLiveIn(LiveIns[i].first); 433 } 434 } else { 435 // Add the register to the entry block live-in set. 436 EntryMBB->addLiveIn(LiveIns[i].first); 437 } 438 } 439 440 LaneBitmask MachineRegisterInfo::getMaxLaneMaskForVReg(unsigned Reg) const { 441 // Lane masks are only defined for vregs. 442 assert(TargetRegisterInfo::isVirtualRegister(Reg)); 443 const TargetRegisterClass &TRC = *getRegClass(Reg); 444 return TRC.getLaneMask(); 445 } 446 447 #ifndef NDEBUG 448 void MachineRegisterInfo::dumpUses(unsigned Reg) const { 449 for (MachineInstr &I : use_instructions(Reg)) 450 I.dump(); 451 } 452 #endif 453 454 void MachineRegisterInfo::freezeReservedRegs(const MachineFunction &MF) { 455 ReservedRegs = getTargetRegisterInfo()->getReservedRegs(MF); 456 assert(ReservedRegs.size() == getTargetRegisterInfo()->getNumRegs() && 457 "Invalid ReservedRegs vector from target"); 458 } 459 460 bool MachineRegisterInfo::isConstantPhysReg(unsigned PhysReg) const { 461 assert(TargetRegisterInfo::isPhysicalRegister(PhysReg)); 462 463 const TargetRegisterInfo *TRI = getTargetRegisterInfo(); 464 if (TRI->isConstantPhysReg(PhysReg)) 465 return true; 466 467 // Check if any overlapping register is modified, or allocatable so it may be 468 // used later. 469 for (MCRegAliasIterator AI(PhysReg, TRI, true); 470 AI.isValid(); ++AI) 471 if (!def_empty(*AI) || isAllocatable(*AI)) 472 return false; 473 return true; 474 } 475 476 /// markUsesInDebugValueAsUndef - Mark every DBG_VALUE referencing the 477 /// specified register as undefined which causes the DBG_VALUE to be 478 /// deleted during LiveDebugVariables analysis. 479 void MachineRegisterInfo::markUsesInDebugValueAsUndef(unsigned Reg) const { 480 // Mark any DBG_VALUE that uses Reg as undef (but don't delete it.) 481 MachineRegisterInfo::use_instr_iterator nextI; 482 for (use_instr_iterator I = use_instr_begin(Reg), E = use_instr_end(); 483 I != E; I = nextI) { 484 nextI = std::next(I); // I is invalidated by the setReg 485 MachineInstr *UseMI = &*I; 486 if (UseMI->isDebugValue()) 487 UseMI->getOperand(0).setReg(0U); 488 } 489 } 490 491 static const Function *getCalledFunction(const MachineInstr &MI) { 492 for (const MachineOperand &MO : MI.operands()) { 493 if (!MO.isGlobal()) 494 continue; 495 const Function *Func = dyn_cast<Function>(MO.getGlobal()); 496 if (Func != nullptr) 497 return Func; 498 } 499 return nullptr; 500 } 501 502 static bool isNoReturnDef(const MachineOperand &MO) { 503 // Anything which is not a noreturn function is a real def. 504 const MachineInstr &MI = *MO.getParent(); 505 if (!MI.isCall()) 506 return false; 507 const MachineBasicBlock &MBB = *MI.getParent(); 508 if (!MBB.succ_empty()) 509 return false; 510 const MachineFunction &MF = *MBB.getParent(); 511 // We need to keep correct unwind information even if the function will 512 // not return, since the runtime may need it. 513 if (MF.getFunction()->hasFnAttribute(Attribute::UWTable)) 514 return false; 515 const Function *Called = getCalledFunction(MI); 516 return !(Called == nullptr || !Called->hasFnAttribute(Attribute::NoReturn) || 517 !Called->hasFnAttribute(Attribute::NoUnwind)); 518 } 519 520 bool MachineRegisterInfo::isPhysRegModified(unsigned PhysReg, 521 bool SkipNoReturnDef) const { 522 if (UsedPhysRegMask.test(PhysReg)) 523 return true; 524 const TargetRegisterInfo *TRI = getTargetRegisterInfo(); 525 for (MCRegAliasIterator AI(PhysReg, TRI, true); AI.isValid(); ++AI) { 526 for (const MachineOperand &MO : make_range(def_begin(*AI), def_end())) { 527 if (!SkipNoReturnDef && isNoReturnDef(MO)) 528 continue; 529 return true; 530 } 531 } 532 return false; 533 } 534 535 bool MachineRegisterInfo::isPhysRegUsed(unsigned PhysReg) const { 536 if (UsedPhysRegMask.test(PhysReg)) 537 return true; 538 const TargetRegisterInfo *TRI = getTargetRegisterInfo(); 539 for (MCRegAliasIterator AliasReg(PhysReg, TRI, true); AliasReg.isValid(); 540 ++AliasReg) { 541 if (!reg_nodbg_empty(*AliasReg)) 542 return true; 543 } 544 return false; 545 } 546