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