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