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