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