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