Added MachineRegisterInfo::hasOneDef()
[oota-llvm.git] / include / llvm / CodeGen / MachineRegisterInfo.h
1 //===-- llvm/CodeGen/MachineRegisterInfo.h ----------------------*- C++ -*-===//
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 // This file defines the MachineRegisterInfo class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #ifndef LLVM_CODEGEN_MACHINEREGISTERINFO_H
15 #define LLVM_CODEGEN_MACHINEREGISTERINFO_H
16
17 #include "llvm/Target/TargetRegisterInfo.h"
18 #include "llvm/CodeGen/MachineInstrBundle.h"
19 #include "llvm/ADT/BitVector.h"
20 #include "llvm/ADT/IndexedMap.h"
21 #include <vector>
22
23 namespace llvm {
24
25 /// MachineRegisterInfo - Keep track of information for virtual and physical
26 /// registers, including vreg register classes, use/def chains for registers,
27 /// etc.
28 class MachineRegisterInfo {
29   const TargetRegisterInfo *const TRI;
30
31   /// IsSSA - True when the machine function is in SSA form and virtual
32   /// registers have a single def.
33   bool IsSSA;
34
35   /// TracksLiveness - True while register liveness is being tracked accurately.
36   /// Basic block live-in lists, kill flags, and implicit defs may not be
37   /// accurate when after this flag is cleared.
38   bool TracksLiveness;
39
40   /// VRegInfo - Information we keep for each virtual register.
41   ///
42   /// Each element in this list contains the register class of the vreg and the
43   /// start of the use/def list for the register.
44   IndexedMap<std::pair<const TargetRegisterClass*, MachineOperand*>,
45              VirtReg2IndexFunctor> VRegInfo;
46
47   /// RegAllocHints - This vector records register allocation hints for virtual
48   /// registers. For each virtual register, it keeps a register and hint type
49   /// pair making up the allocation hint. Hint type is target specific except
50   /// for the value 0 which means the second value of the pair is the preferred
51   /// register for allocation. For example, if the hint is <0, 1024>, it means
52   /// the allocator should prefer the physical register allocated to the virtual
53   /// register of the hint.
54   IndexedMap<std::pair<unsigned, unsigned>, VirtReg2IndexFunctor> RegAllocHints;
55
56   /// PhysRegUseDefLists - This is an array of the head of the use/def list for
57   /// physical registers.
58   MachineOperand **PhysRegUseDefLists;
59
60   /// UsedPhysRegs - This is a bit vector that is computed and set by the
61   /// register allocator, and must be kept up to date by passes that run after
62   /// register allocation (though most don't modify this).  This is used
63   /// so that the code generator knows which callee save registers to save and
64   /// for other target specific uses.
65   /// This vector only has bits set for registers explicitly used, not their
66   /// aliases.
67   BitVector UsedPhysRegs;
68
69   /// UsedPhysRegMask - Additional used physregs, but including aliases.
70   BitVector UsedPhysRegMask;
71
72   /// ReservedRegs - This is a bit vector of reserved registers.  The target
73   /// may change its mind about which registers should be reserved.  This
74   /// vector is the frozen set of reserved registers when register allocation
75   /// started.
76   BitVector ReservedRegs;
77
78   /// AllocatableRegs - From TRI->getAllocatableSet.
79   mutable BitVector AllocatableRegs;
80
81   /// LiveIns/LiveOuts - Keep track of the physical registers that are
82   /// livein/liveout of the function.  Live in values are typically arguments in
83   /// registers, live out values are typically return values in registers.
84   /// LiveIn values are allowed to have virtual registers associated with them,
85   /// stored in the second element.
86   std::vector<std::pair<unsigned, unsigned> > LiveIns;
87   std::vector<unsigned> LiveOuts;
88
89   MachineRegisterInfo(const MachineRegisterInfo&); // DO NOT IMPLEMENT
90   void operator=(const MachineRegisterInfo&);      // DO NOT IMPLEMENT
91 public:
92   explicit MachineRegisterInfo(const TargetRegisterInfo &TRI);
93   ~MachineRegisterInfo();
94
95   //===--------------------------------------------------------------------===//
96   // Function State
97   //===--------------------------------------------------------------------===//
98
99   // isSSA - Returns true when the machine function is in SSA form. Early
100   // passes require the machine function to be in SSA form where every virtual
101   // register has a single defining instruction.
102   //
103   // The TwoAddressInstructionPass and PHIElimination passes take the machine
104   // function out of SSA form when they introduce multiple defs per virtual
105   // register.
106   bool isSSA() const { return IsSSA; }
107
108   // leaveSSA - Indicates that the machine function is no longer in SSA form.
109   void leaveSSA() { IsSSA = false; }
110
111   /// tracksLiveness - Returns true when tracking register liveness accurately.
112   ///
113   /// While this flag is true, register liveness information in basic block
114   /// live-in lists and machine instruction operands is accurate. This means it
115   /// can be used to change the code in ways that affect the values in
116   /// registers, for example by the register scavenger.
117   ///
118   /// When this flag is false, liveness is no longer reliable.
119   bool tracksLiveness() const { return TracksLiveness; }
120
121   /// invalidateLiveness - Indicates that register liveness is no longer being
122   /// tracked accurately.
123   ///
124   /// This should be called by late passes that invalidate the liveness
125   /// information.
126   void invalidateLiveness() { TracksLiveness = false; }
127
128   //===--------------------------------------------------------------------===//
129   // Register Info
130   //===--------------------------------------------------------------------===//
131
132   /// reg_begin/reg_end - Provide iteration support to walk over all definitions
133   /// and uses of a register within the MachineFunction that corresponds to this
134   /// MachineRegisterInfo object.
135   template<bool Uses, bool Defs, bool SkipDebug>
136   class defusechain_iterator;
137
138   /// reg_iterator/reg_begin/reg_end - Walk all defs and uses of the specified
139   /// register.
140   typedef defusechain_iterator<true,true,false> reg_iterator;
141   reg_iterator reg_begin(unsigned RegNo) const {
142     return reg_iterator(getRegUseDefListHead(RegNo));
143   }
144   static reg_iterator reg_end() { return reg_iterator(0); }
145
146   /// reg_empty - Return true if there are no instructions using or defining the
147   /// specified register (it may be live-in).
148   bool reg_empty(unsigned RegNo) const { return reg_begin(RegNo) == reg_end(); }
149
150   /// reg_nodbg_iterator/reg_nodbg_begin/reg_nodbg_end - Walk all defs and uses
151   /// of the specified register, skipping those marked as Debug.
152   typedef defusechain_iterator<true,true,true> reg_nodbg_iterator;
153   reg_nodbg_iterator reg_nodbg_begin(unsigned RegNo) const {
154     return reg_nodbg_iterator(getRegUseDefListHead(RegNo));
155   }
156   static reg_nodbg_iterator reg_nodbg_end() { return reg_nodbg_iterator(0); }
157
158   /// reg_nodbg_empty - Return true if the only instructions using or defining
159   /// Reg are Debug instructions.
160   bool reg_nodbg_empty(unsigned RegNo) const {
161     return reg_nodbg_begin(RegNo) == reg_nodbg_end();
162   }
163
164   /// def_iterator/def_begin/def_end - Walk all defs of the specified register.
165   typedef defusechain_iterator<false,true,false> def_iterator;
166   def_iterator def_begin(unsigned RegNo) const {
167     return def_iterator(getRegUseDefListHead(RegNo));
168   }
169   static def_iterator def_end() { return def_iterator(0); }
170
171   /// def_empty - Return true if there are no instructions defining the
172   /// specified register (it may be live-in).
173   bool def_empty(unsigned RegNo) const { return def_begin(RegNo) == def_end(); }
174
175   /// hasOneDef - Return true if there is exactly one instruction defining the
176   /// specified register.
177   bool hasOneDef(unsigned RegNo) const {
178     def_iterator DI = def_begin(RegNo);
179     if (DI == def_end())
180       return false;
181     return ++DI == def_end();
182   }
183
184   /// use_iterator/use_begin/use_end - Walk all uses of the specified register.
185   typedef defusechain_iterator<true,false,false> use_iterator;
186   use_iterator use_begin(unsigned RegNo) const {
187     return use_iterator(getRegUseDefListHead(RegNo));
188   }
189   static use_iterator use_end() { return use_iterator(0); }
190
191   /// use_empty - Return true if there are no instructions using the specified
192   /// register.
193   bool use_empty(unsigned RegNo) const { return use_begin(RegNo) == use_end(); }
194
195   /// hasOneUse - Return true if there is exactly one instruction using the
196   /// specified register.
197   bool hasOneUse(unsigned RegNo) const {
198     use_iterator UI = use_begin(RegNo);
199     if (UI == use_end())
200       return false;
201     return ++UI == use_end();
202   }
203
204   /// use_nodbg_iterator/use_nodbg_begin/use_nodbg_end - Walk all uses of the
205   /// specified register, skipping those marked as Debug.
206   typedef defusechain_iterator<true,false,true> use_nodbg_iterator;
207   use_nodbg_iterator use_nodbg_begin(unsigned RegNo) const {
208     return use_nodbg_iterator(getRegUseDefListHead(RegNo));
209   }
210   static use_nodbg_iterator use_nodbg_end() { return use_nodbg_iterator(0); }
211
212   /// use_nodbg_empty - Return true if there are no non-Debug instructions
213   /// using the specified register.
214   bool use_nodbg_empty(unsigned RegNo) const {
215     return use_nodbg_begin(RegNo) == use_nodbg_end();
216   }
217
218   /// hasOneNonDBGUse - Return true if there is exactly one non-Debug
219   /// instruction using the specified register.
220   bool hasOneNonDBGUse(unsigned RegNo) const;
221
222   /// replaceRegWith - Replace all instances of FromReg with ToReg in the
223   /// machine function.  This is like llvm-level X->replaceAllUsesWith(Y),
224   /// except that it also changes any definitions of the register as well.
225   ///
226   /// Note that it is usually necessary to first constrain ToReg's register
227   /// class to match the FromReg constraints using:
228   ///
229   ///   constrainRegClass(ToReg, getRegClass(FromReg))
230   ///
231   /// That function will return NULL if the virtual registers have incompatible
232   /// constraints.
233   void replaceRegWith(unsigned FromReg, unsigned ToReg);
234
235   /// getRegUseDefListHead - Return the head pointer for the register use/def
236   /// list for the specified virtual or physical register.
237   MachineOperand *&getRegUseDefListHead(unsigned RegNo) {
238     if (TargetRegisterInfo::isVirtualRegister(RegNo))
239       return VRegInfo[RegNo].second;
240     return PhysRegUseDefLists[RegNo];
241   }
242
243   MachineOperand *getRegUseDefListHead(unsigned RegNo) const {
244     if (TargetRegisterInfo::isVirtualRegister(RegNo))
245       return VRegInfo[RegNo].second;
246     return PhysRegUseDefLists[RegNo];
247   }
248
249   /// getVRegDef - Return the machine instr that defines the specified virtual
250   /// register or null if none is found.  This assumes that the code is in SSA
251   /// form, so there should only be one definition.
252   MachineInstr *getVRegDef(unsigned Reg) const;
253
254   /// getUniqueVRegDef - Return the unique machine instr that defines the
255   /// specified virtual register or null if none is found.  If there are
256   /// multiple definitions or no definition, return null.
257   MachineInstr *getUniqueVRegDef(unsigned Reg) const;
258
259   /// clearKillFlags - Iterate over all the uses of the given register and
260   /// clear the kill flag from the MachineOperand. This function is used by
261   /// optimization passes which extend register lifetimes and need only
262   /// preserve conservative kill flag information.
263   void clearKillFlags(unsigned Reg) const;
264
265 #ifndef NDEBUG
266   void dumpUses(unsigned RegNo) const;
267 #endif
268
269   /// isConstantPhysReg - Returns true if PhysReg is unallocatable and constant
270   /// throughout the function.  It is safe to move instructions that read such
271   /// a physreg.
272   bool isConstantPhysReg(unsigned PhysReg, const MachineFunction &MF) const;
273
274   //===--------------------------------------------------------------------===//
275   // Virtual Register Info
276   //===--------------------------------------------------------------------===//
277
278   /// getRegClass - Return the register class of the specified virtual register.
279   ///
280   const TargetRegisterClass *getRegClass(unsigned Reg) const {
281     return VRegInfo[Reg].first;
282   }
283
284   /// setRegClass - Set the register class of the specified virtual register.
285   ///
286   void setRegClass(unsigned Reg, const TargetRegisterClass *RC);
287
288   /// constrainRegClass - Constrain the register class of the specified virtual
289   /// register to be a common subclass of RC and the current register class,
290   /// but only if the new class has at least MinNumRegs registers.  Return the
291   /// new register class, or NULL if no such class exists.
292   /// This should only be used when the constraint is known to be trivial, like
293   /// GR32 -> GR32_NOSP. Beware of increasing register pressure.
294   ///
295   const TargetRegisterClass *constrainRegClass(unsigned Reg,
296                                                const TargetRegisterClass *RC,
297                                                unsigned MinNumRegs = 0);
298
299   /// recomputeRegClass - Try to find a legal super-class of Reg's register
300   /// class that still satisfies the constraints from the instructions using
301   /// Reg.  Returns true if Reg was upgraded.
302   ///
303   /// This method can be used after constraints have been removed from a
304   /// virtual register, for example after removing instructions or splitting
305   /// the live range.
306   ///
307   bool recomputeRegClass(unsigned Reg, const TargetMachine&);
308
309   /// createVirtualRegister - Create and return a new virtual register in the
310   /// function with the specified register class.
311   ///
312   unsigned createVirtualRegister(const TargetRegisterClass *RegClass);
313
314   /// getNumVirtRegs - Return the number of virtual registers created.
315   ///
316   unsigned getNumVirtRegs() const { return VRegInfo.size(); }
317
318   /// clearVirtRegs - Remove all virtual registers (after physreg assignment).
319   void clearVirtRegs();
320
321   /// setRegAllocationHint - Specify a register allocation hint for the
322   /// specified virtual register.
323   void setRegAllocationHint(unsigned Reg, unsigned Type, unsigned PrefReg) {
324     RegAllocHints[Reg].first  = Type;
325     RegAllocHints[Reg].second = PrefReg;
326   }
327
328   /// getRegAllocationHint - Return the register allocation hint for the
329   /// specified virtual register.
330   std::pair<unsigned, unsigned>
331   getRegAllocationHint(unsigned Reg) const {
332     return RegAllocHints[Reg];
333   }
334
335   /// getSimpleHint - Return the preferred register allocation hint, or 0 if a
336   /// standard simple hint (Type == 0) is not set.
337   unsigned getSimpleHint(unsigned Reg) const {
338     std::pair<unsigned, unsigned> Hint = getRegAllocationHint(Reg);
339     return Hint.first ? 0 : Hint.second;
340   }
341
342
343   //===--------------------------------------------------------------------===//
344   // Physical Register Use Info
345   //===--------------------------------------------------------------------===//
346
347   /// isPhysRegUsed - Return true if the specified register is used in this
348   /// function.  This only works after register allocation.
349   bool isPhysRegUsed(unsigned Reg) const {
350     return UsedPhysRegs.test(Reg) || UsedPhysRegMask.test(Reg);
351   }
352
353   /// isPhysRegOrOverlapUsed - Return true if Reg or any overlapping register
354   /// is used in this function.
355   bool isPhysRegOrOverlapUsed(unsigned Reg) const {
356     if (UsedPhysRegMask.test(Reg))
357       return true;
358     for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
359       if (UsedPhysRegs.test(*AI))
360         return true;
361     return false;
362   }
363
364   /// setPhysRegUsed - Mark the specified register used in this function.
365   /// This should only be called during and after register allocation.
366   void setPhysRegUsed(unsigned Reg) { UsedPhysRegs.set(Reg); }
367
368   /// addPhysRegsUsed - Mark the specified registers used in this function.
369   /// This should only be called during and after register allocation.
370   void addPhysRegsUsed(const BitVector &Regs) { UsedPhysRegs |= Regs; }
371
372   /// addPhysRegsUsedFromRegMask - Mark any registers not in RegMask as used.
373   /// This corresponds to the bit mask attached to register mask operands.
374   void addPhysRegsUsedFromRegMask(const uint32_t *RegMask) {
375     UsedPhysRegMask.setBitsNotInMask(RegMask);
376   }
377
378   /// setPhysRegUnused - Mark the specified register unused in this function.
379   /// This should only be called during and after register allocation.
380   void setPhysRegUnused(unsigned Reg) {
381     UsedPhysRegs.reset(Reg);
382     UsedPhysRegMask.reset(Reg);
383   }
384
385
386   //===--------------------------------------------------------------------===//
387   // Reserved Register Info
388   //===--------------------------------------------------------------------===//
389   //
390   // The set of reserved registers must be invariant during register
391   // allocation.  For example, the target cannot suddenly decide it needs a
392   // frame pointer when the register allocator has already used the frame
393   // pointer register for something else.
394   //
395   // These methods can be used by target hooks like hasFP() to avoid changing
396   // the reserved register set during register allocation.
397
398   /// freezeReservedRegs - Called by the register allocator to freeze the set
399   /// of reserved registers before allocation begins.
400   void freezeReservedRegs(const MachineFunction&);
401
402   /// reservedRegsFrozen - Returns true after freezeReservedRegs() was called
403   /// to ensure the set of reserved registers stays constant.
404   bool reservedRegsFrozen() const {
405     return !ReservedRegs.empty();
406   }
407
408   /// canReserveReg - Returns true if PhysReg can be used as a reserved
409   /// register.  Any register can be reserved before freezeReservedRegs() is
410   /// called.
411   bool canReserveReg(unsigned PhysReg) const {
412     return !reservedRegsFrozen() || ReservedRegs.test(PhysReg);
413   }
414
415
416   //===--------------------------------------------------------------------===//
417   // LiveIn/LiveOut Management
418   //===--------------------------------------------------------------------===//
419
420   /// addLiveIn/Out - Add the specified register as a live in/out.  Note that it
421   /// is an error to add the same register to the same set more than once.
422   void addLiveIn(unsigned Reg, unsigned vreg = 0) {
423     LiveIns.push_back(std::make_pair(Reg, vreg));
424   }
425   void addLiveOut(unsigned Reg) { LiveOuts.push_back(Reg); }
426
427   // Iteration support for live in/out sets.  These sets are kept in sorted
428   // order by their register number.
429   typedef std::vector<std::pair<unsigned,unsigned> >::const_iterator
430   livein_iterator;
431   typedef std::vector<unsigned>::const_iterator liveout_iterator;
432   livein_iterator livein_begin() const { return LiveIns.begin(); }
433   livein_iterator livein_end()   const { return LiveIns.end(); }
434   bool            livein_empty() const { return LiveIns.empty(); }
435   liveout_iterator liveout_begin() const { return LiveOuts.begin(); }
436   liveout_iterator liveout_end()   const { return LiveOuts.end(); }
437   bool             liveout_empty() const { return LiveOuts.empty(); }
438
439   bool isLiveIn(unsigned Reg) const;
440   bool isLiveOut(unsigned Reg) const;
441
442   /// getLiveInPhysReg - If VReg is a live-in virtual register, return the
443   /// corresponding live-in physical register.
444   unsigned getLiveInPhysReg(unsigned VReg) const;
445
446   /// getLiveInVirtReg - If PReg is a live-in physical register, return the
447   /// corresponding live-in physical register.
448   unsigned getLiveInVirtReg(unsigned PReg) const;
449
450   /// EmitLiveInCopies - Emit copies to initialize livein virtual registers
451   /// into the given entry block.
452   void EmitLiveInCopies(MachineBasicBlock *EntryMBB,
453                         const TargetRegisterInfo &TRI,
454                         const TargetInstrInfo &TII);
455
456 private:
457   void HandleVRegListReallocation();
458
459 public:
460   /// defusechain_iterator - This class provides iterator support for machine
461   /// operands in the function that use or define a specific register.  If
462   /// ReturnUses is true it returns uses of registers, if ReturnDefs is true it
463   /// returns defs.  If neither are true then you are silly and it always
464   /// returns end().  If SkipDebug is true it skips uses marked Debug
465   /// when incrementing.
466   template<bool ReturnUses, bool ReturnDefs, bool SkipDebug>
467   class defusechain_iterator
468     : public std::iterator<std::forward_iterator_tag, MachineInstr, ptrdiff_t> {
469     MachineOperand *Op;
470     explicit defusechain_iterator(MachineOperand *op) : Op(op) {
471       // If the first node isn't one we're interested in, advance to one that
472       // we are interested in.
473       if (op) {
474         if ((!ReturnUses && op->isUse()) ||
475             (!ReturnDefs && op->isDef()) ||
476             (SkipDebug && op->isDebug()))
477           ++*this;
478       }
479     }
480     friend class MachineRegisterInfo;
481   public:
482     typedef std::iterator<std::forward_iterator_tag,
483                           MachineInstr, ptrdiff_t>::reference reference;
484     typedef std::iterator<std::forward_iterator_tag,
485                           MachineInstr, ptrdiff_t>::pointer pointer;
486
487     defusechain_iterator(const defusechain_iterator &I) : Op(I.Op) {}
488     defusechain_iterator() : Op(0) {}
489
490     bool operator==(const defusechain_iterator &x) const {
491       return Op == x.Op;
492     }
493     bool operator!=(const defusechain_iterator &x) const {
494       return !operator==(x);
495     }
496
497     /// atEnd - return true if this iterator is equal to reg_end() on the value.
498     bool atEnd() const { return Op == 0; }
499
500     // Iterator traversal: forward iteration only
501     defusechain_iterator &operator++() {          // Preincrement
502       assert(Op && "Cannot increment end iterator!");
503       Op = Op->getNextOperandForReg();
504
505       // If this is an operand we don't care about, skip it.
506       while (Op && ((!ReturnUses && Op->isUse()) ||
507                     (!ReturnDefs && Op->isDef()) ||
508                     (SkipDebug && Op->isDebug())))
509         Op = Op->getNextOperandForReg();
510
511       return *this;
512     }
513     defusechain_iterator operator++(int) {        // Postincrement
514       defusechain_iterator tmp = *this; ++*this; return tmp;
515     }
516
517     /// skipInstruction - move forward until reaching a different instruction.
518     /// Return the skipped instruction that is no longer pointed to, or NULL if
519     /// already pointing to end().
520     MachineInstr *skipInstruction() {
521       if (!Op) return 0;
522       MachineInstr *MI = Op->getParent();
523       do ++*this;
524       while (Op && Op->getParent() == MI);
525       return MI;
526     }
527
528     MachineInstr *skipBundle() {
529       if (!Op) return 0;
530       MachineInstr *MI = getBundleStart(Op->getParent());
531       do ++*this;
532       while (Op && getBundleStart(Op->getParent()) == MI);
533       return MI;
534     }
535
536     MachineOperand &getOperand() const {
537       assert(Op && "Cannot dereference end iterator!");
538       return *Op;
539     }
540
541     /// getOperandNo - Return the operand # of this MachineOperand in its
542     /// MachineInstr.
543     unsigned getOperandNo() const {
544       assert(Op && "Cannot dereference end iterator!");
545       return Op - &Op->getParent()->getOperand(0);
546     }
547
548     // Retrieve a reference to the current operand.
549     MachineInstr &operator*() const {
550       assert(Op && "Cannot dereference end iterator!");
551       return *Op->getParent();
552     }
553
554     MachineInstr *operator->() const {
555       assert(Op && "Cannot dereference end iterator!");
556       return Op->getParent();
557     }
558   };
559
560 };
561
562 } // End llvm namespace
563
564 #endif