Rename TRI::getAllocationOrder() to getRawAllocationOrder().
[oota-llvm.git] / include / llvm / Target / TargetRegisterInfo.h
1 //=== Target/TargetRegisterInfo.h - Target Register Information -*- 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 describes an abstract interface used to get information about a
11 // target machines register file.  This information is used for a variety of
12 // purposed, especially register allocation.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #ifndef LLVM_TARGET_TARGETREGISTERINFO_H
17 #define LLVM_TARGET_TARGETREGISTERINFO_H
18
19 #include "llvm/CodeGen/MachineBasicBlock.h"
20 #include "llvm/CodeGen/ValueTypes.h"
21 #include "llvm/ADT/ArrayRef.h"
22 #include "llvm/ADT/DenseSet.h"
23 #include <cassert>
24 #include <functional>
25
26 namespace llvm {
27
28 class BitVector;
29 class MachineFunction;
30 class MachineMove;
31 class RegScavenger;
32 template<class T> class SmallVectorImpl;
33 class raw_ostream;
34
35 /// TargetRegisterDesc - This record contains all of the information known about
36 /// a particular register.  The Overlaps field contains a pointer to a zero
37 /// terminated array of registers that this register aliases, starting with
38 /// itself. This is needed for architectures like X86 which have AL alias AX
39 /// alias EAX. The SubRegs field is a zero terminated array of registers that
40 /// are sub-registers of the specific register, e.g. AL, AH are sub-registers of
41 /// AX. The SuperRegs field is a zero terminated array of registers that are
42 /// super-registers of the specific register, e.g. RAX, EAX, are super-registers
43 /// of AX.
44 ///
45 struct TargetRegisterDesc {
46   const char     *Name;         // Printable name for the reg (for debugging)
47   const unsigned *Overlaps;     // Overlapping registers, described above
48   const unsigned *SubRegs;      // Sub-register set, described above
49   const unsigned *SuperRegs;    // Super-register set, described above
50   unsigned CostPerUse;          // Extra cost of instructions using register.
51   bool inAllocatableClass;      // Register belongs to an allocatable regclass.
52 };
53
54 class TargetRegisterClass {
55 public:
56   typedef const unsigned* iterator;
57   typedef const unsigned* const_iterator;
58
59   typedef const EVT* vt_iterator;
60   typedef const TargetRegisterClass* const * sc_iterator;
61 private:
62   unsigned ID;
63   const char *Name;
64   const vt_iterator VTs;
65   const sc_iterator SubClasses;
66   const sc_iterator SuperClasses;
67   const sc_iterator SubRegClasses;
68   const sc_iterator SuperRegClasses;
69   const unsigned RegSize, Alignment;    // Size & Alignment of register in bytes
70   const int CopyCost;
71   const bool Allocatable;
72   const iterator RegsBegin, RegsEnd;
73   DenseSet<unsigned> RegSet;
74 public:
75   TargetRegisterClass(unsigned id,
76                       const char *name,
77                       const EVT *vts,
78                       const TargetRegisterClass * const *subcs,
79                       const TargetRegisterClass * const *supcs,
80                       const TargetRegisterClass * const *subregcs,
81                       const TargetRegisterClass * const *superregcs,
82                       unsigned RS, unsigned Al, int CC, bool Allocable,
83                       iterator RB, iterator RE)
84     : ID(id), Name(name), VTs(vts), SubClasses(subcs), SuperClasses(supcs),
85     SubRegClasses(subregcs), SuperRegClasses(superregcs),
86     RegSize(RS), Alignment(Al), CopyCost(CC), Allocatable(Allocable),
87     RegsBegin(RB), RegsEnd(RE) {
88       for (iterator I = RegsBegin, E = RegsEnd; I != E; ++I)
89         RegSet.insert(*I);
90     }
91   virtual ~TargetRegisterClass() {}     // Allow subclasses
92
93   /// getID() - Return the register class ID number.
94   ///
95   unsigned getID() const { return ID; }
96
97   /// getName() - Return the register class name for debugging.
98   ///
99   const char *getName() const { return Name; }
100
101   /// begin/end - Return all of the registers in this class.
102   ///
103   iterator       begin() const { return RegsBegin; }
104   iterator         end() const { return RegsEnd; }
105
106   /// getNumRegs - Return the number of registers in this class.
107   ///
108   unsigned getNumRegs() const { return (unsigned)(RegsEnd-RegsBegin); }
109
110   /// getRegister - Return the specified register in the class.
111   ///
112   unsigned getRegister(unsigned i) const {
113     assert(i < getNumRegs() && "Register number out of range!");
114     return RegsBegin[i];
115   }
116
117   /// contains - Return true if the specified register is included in this
118   /// register class.  This does not include virtual registers.
119   bool contains(unsigned Reg) const {
120     return RegSet.count(Reg);
121   }
122
123   /// contains - Return true if both registers are in this class.
124   bool contains(unsigned Reg1, unsigned Reg2) const {
125     return contains(Reg1) && contains(Reg2);
126   }
127
128   /// hasType - return true if this TargetRegisterClass has the ValueType vt.
129   ///
130   bool hasType(EVT vt) const {
131     for(int i = 0; VTs[i] != MVT::Other; ++i)
132       if (VTs[i] == vt)
133         return true;
134     return false;
135   }
136
137   /// vt_begin / vt_end - Loop over all of the value types that can be
138   /// represented by values in this register class.
139   vt_iterator vt_begin() const {
140     return VTs;
141   }
142
143   vt_iterator vt_end() const {
144     vt_iterator I = VTs;
145     while (*I != MVT::Other) ++I;
146     return I;
147   }
148
149   /// subregclasses_begin / subregclasses_end - Loop over all of
150   /// the subreg register classes of this register class.
151   sc_iterator subregclasses_begin() const {
152     return SubRegClasses;
153   }
154
155   sc_iterator subregclasses_end() const {
156     sc_iterator I = SubRegClasses;
157     while (*I != NULL) ++I;
158     return I;
159   }
160
161   /// getSubRegisterRegClass - Return the register class of subregisters with
162   /// index SubIdx, or NULL if no such class exists.
163   const TargetRegisterClass* getSubRegisterRegClass(unsigned SubIdx) const {
164     assert(SubIdx>0 && "Invalid subregister index");
165     return SubRegClasses[SubIdx-1];
166   }
167
168   /// superregclasses_begin / superregclasses_end - Loop over all of
169   /// the superreg register classes of this register class.
170   sc_iterator superregclasses_begin() const {
171     return SuperRegClasses;
172   }
173
174   sc_iterator superregclasses_end() const {
175     sc_iterator I = SuperRegClasses;
176     while (*I != NULL) ++I;
177     return I;
178   }
179
180   /// hasSubClass - return true if the specified TargetRegisterClass
181   /// is a proper subset of this TargetRegisterClass.
182   bool hasSubClass(const TargetRegisterClass *cs) const {
183     for (int i = 0; SubClasses[i] != NULL; ++i)
184       if (SubClasses[i] == cs)
185         return true;
186     return false;
187   }
188
189   /// hasSubClassEq - Returns true if RC is a subclass of or equal to this
190   /// class.
191   bool hasSubClassEq(const TargetRegisterClass *RC) const {
192     return RC == this || hasSubClass(RC);
193   }
194
195   /// subclasses_begin / subclasses_end - Loop over all of the classes
196   /// that are proper subsets of this register class.
197   sc_iterator subclasses_begin() const {
198     return SubClasses;
199   }
200
201   sc_iterator subclasses_end() const {
202     sc_iterator I = SubClasses;
203     while (*I != NULL) ++I;
204     return I;
205   }
206
207   /// hasSuperClass - return true if the specified TargetRegisterClass is a
208   /// proper superset of this TargetRegisterClass.
209   bool hasSuperClass(const TargetRegisterClass *cs) const {
210     for (int i = 0; SuperClasses[i] != NULL; ++i)
211       if (SuperClasses[i] == cs)
212         return true;
213     return false;
214   }
215
216   /// hasSuperClassEq - Returns true if RC is a superclass of or equal to this
217   /// class.
218   bool hasSuperClassEq(const TargetRegisterClass *RC) const {
219     return RC == this || hasSuperClass(RC);
220   }
221
222   /// superclasses_begin / superclasses_end - Loop over all of the classes
223   /// that are proper supersets of this register class.
224   sc_iterator superclasses_begin() const {
225     return SuperClasses;
226   }
227
228   sc_iterator superclasses_end() const {
229     sc_iterator I = SuperClasses;
230     while (*I != NULL) ++I;
231     return I;
232   }
233
234   /// isASubClass - return true if this TargetRegisterClass is a subset
235   /// class of at least one other TargetRegisterClass.
236   bool isASubClass() const {
237     return SuperClasses[0] != 0;
238   }
239
240   /// allocation_order_begin/end - These methods define a range of registers
241   /// which specify the registers in this class that are valid to register
242   /// allocate, and the preferred order to allocate them in.  For example,
243   /// callee saved registers should be at the end of the list, because it is
244   /// cheaper to allocate caller saved registers.
245   ///
246   /// These methods take a MachineFunction argument, which can be used to tune
247   /// the allocatable registers based on the characteristics of the function,
248   /// subtarget, or other criteria.
249   ///
250   /// Register allocators should account for the fact that an allocation
251   /// order iterator may return a reserved register and always check
252   /// if the register is allocatable (getAllocatableSet()) before using it.
253   ///
254   /// By default, these methods return all registers in the class.
255   ///
256   virtual iterator allocation_order_begin(const MachineFunction &MF) const {
257     return begin();
258   }
259   virtual iterator allocation_order_end(const MachineFunction &MF)   const {
260     return end();
261   }
262
263   /// getRawAllocationOrder - Returns the preferred order for allocating
264   /// registers from this register class in MF. The raw order comes directly
265   /// from the .td file and may include reserved registers that are not
266   /// allocatable. Register allocators should also make sure to allocate
267   /// callee-saved registers only after all the volatiles are used. The
268   /// RegisterClassInfo class provides filtered allocation orders with
269   /// callee-saved registers moved to the end.
270   ///
271   /// The MachineFunction argument can be used to tune the allocatable
272   /// registers based on the characteristics of the function, subtarget, or
273   /// other criteria.
274   ///
275   /// By default, this method returns all registers in the class.
276   ///
277   virtual
278   ArrayRef<unsigned> getRawAllocationOrder(const MachineFunction &MF) const {
279     iterator B = allocation_order_begin(MF);
280     iterator E = allocation_order_end(MF);
281     return ArrayRef<unsigned>(B, E - B);
282   }
283
284   /// getSize - Return the size of the register in bytes, which is also the size
285   /// of a stack slot allocated to hold a spilled copy of this register.
286   unsigned getSize() const { return RegSize; }
287
288   /// getAlignment - Return the minimum required alignment for a register of
289   /// this class.
290   unsigned getAlignment() const { return Alignment; }
291
292   /// getCopyCost - Return the cost of copying a value between two registers in
293   /// this class. A negative number means the register class is very expensive
294   /// to copy e.g. status flag register classes.
295   int getCopyCost() const { return CopyCost; }
296
297   /// isAllocatable - Return true if this register class may be used to create
298   /// virtual registers.
299   bool isAllocatable() const { return Allocatable; }
300 };
301
302
303 /// TargetRegisterInfo base class - We assume that the target defines a static
304 /// array of TargetRegisterDesc objects that represent all of the machine
305 /// registers that the target has.  As such, we simply have to track a pointer
306 /// to this array so that we can turn register number into a register
307 /// descriptor.
308 ///
309 class TargetRegisterInfo {
310 public:
311   typedef const TargetRegisterClass * const * regclass_iterator;
312 private:
313   const TargetRegisterDesc *Desc;             // Pointer to the descriptor array
314   const char *const *SubRegIndexNames;        // Names of subreg indexes.
315   unsigned NumRegs;                           // Number of entries in the array
316
317   regclass_iterator RegClassBegin, RegClassEnd;   // List of regclasses
318
319   int CallFrameSetupOpcode, CallFrameDestroyOpcode;
320
321 protected:
322   TargetRegisterInfo(const TargetRegisterDesc *D, unsigned NR,
323                      regclass_iterator RegClassBegin,
324                      regclass_iterator RegClassEnd,
325                      const char *const *subregindexnames,
326                      int CallFrameSetupOpcode = -1,
327                      int CallFrameDestroyOpcode = -1);
328   virtual ~TargetRegisterInfo();
329 public:
330
331   // Register numbers can represent physical registers, virtual registers, and
332   // sometimes stack slots. The unsigned values are divided into these ranges:
333   //
334   //   0           Not a register, can be used as a sentinel.
335   //   [1;2^30)    Physical registers assigned by TableGen.
336   //   [2^30;2^31) Stack slots. (Rarely used.)
337   //   [2^31;2^32) Virtual registers assigned by MachineRegisterInfo.
338   //
339   // Further sentinels can be allocated from the small negative integers.
340   // DenseMapInfo<unsigned> uses -1u and -2u.
341
342   /// isStackSlot - Sometimes it is useful the be able to store a non-negative
343   /// frame index in a variable that normally holds a register. isStackSlot()
344   /// returns true if Reg is in the range used for stack slots.
345   ///
346   /// Note that isVirtualRegister() and isPhysicalRegister() cannot handle stack
347   /// slots, so if a variable may contains a stack slot, always check
348   /// isStackSlot() first.
349   ///
350   static bool isStackSlot(unsigned Reg) {
351     return int(Reg) >= (1 << 30);
352   }
353
354   /// stackSlot2Index - Compute the frame index from a register value
355   /// representing a stack slot.
356   static int stackSlot2Index(unsigned Reg) {
357     assert(isStackSlot(Reg) && "Not a stack slot");
358     return int(Reg - (1u << 30));
359   }
360
361   /// index2StackSlot - Convert a non-negative frame index to a stack slot
362   /// register value.
363   static unsigned index2StackSlot(int FI) {
364     assert(FI >= 0 && "Cannot hold a negative frame index.");
365     return FI + (1u << 30);
366   }
367
368   /// isPhysicalRegister - Return true if the specified register number is in
369   /// the physical register namespace.
370   static bool isPhysicalRegister(unsigned Reg) {
371     assert(!isStackSlot(Reg) && "Not a register! Check isStackSlot() first.");
372     return int(Reg) > 0;
373   }
374
375   /// isVirtualRegister - Return true if the specified register number is in
376   /// the virtual register namespace.
377   static bool isVirtualRegister(unsigned Reg) {
378     assert(!isStackSlot(Reg) && "Not a register! Check isStackSlot() first.");
379     return int(Reg) < 0;
380   }
381
382   /// virtReg2Index - Convert a virtual register number to a 0-based index.
383   /// The first virtual register in a function will get the index 0.
384   static unsigned virtReg2Index(unsigned Reg) {
385     assert(isVirtualRegister(Reg) && "Not a virtual register");
386     return Reg & ~(1u << 31);
387   }
388
389   /// index2VirtReg - Convert a 0-based index to a virtual register number.
390   /// This is the inverse operation of VirtReg2IndexFunctor below.
391   static unsigned index2VirtReg(unsigned Index) {
392     return Index | (1u << 31);
393   }
394
395   /// getMinimalPhysRegClass - Returns the Register Class of a physical
396   /// register of the given type, picking the most sub register class of
397   /// the right type that contains this physreg.
398   const TargetRegisterClass *
399     getMinimalPhysRegClass(unsigned Reg, EVT VT = MVT::Other) const;
400
401   /// getAllocatableSet - Returns a bitset indexed by register number
402   /// indicating if a register is allocatable or not. If a register class is
403   /// specified, returns the subset for the class.
404   BitVector getAllocatableSet(const MachineFunction &MF,
405                               const TargetRegisterClass *RC = NULL) const;
406
407   const TargetRegisterDesc &operator[](unsigned RegNo) const {
408     assert(RegNo < NumRegs &&
409            "Attempting to access record for invalid register number!");
410     return Desc[RegNo];
411   }
412
413   /// Provide a get method, equivalent to [], but more useful if we have a
414   /// pointer to this object.
415   ///
416   const TargetRegisterDesc &get(unsigned RegNo) const {
417     return operator[](RegNo);
418   }
419
420   /// getAliasSet - Return the set of registers aliased by the specified
421   /// register, or a null list of there are none.  The list returned is zero
422   /// terminated.
423   ///
424   const unsigned *getAliasSet(unsigned RegNo) const {
425     // The Overlaps set always begins with Reg itself.
426     return get(RegNo).Overlaps + 1;
427   }
428
429   /// getOverlaps - Return a list of registers that overlap Reg, including
430   /// itself. This is the same as the alias set except Reg is included in the
431   /// list.
432   /// These are exactly the registers in { x | regsOverlap(x, Reg) }.
433   ///
434   const unsigned *getOverlaps(unsigned RegNo) const {
435     return get(RegNo).Overlaps;
436   }
437
438   /// getSubRegisters - Return the list of registers that are sub-registers of
439   /// the specified register, or a null list of there are none. The list
440   /// returned is zero terminated and sorted according to super-sub register
441   /// relations. e.g. X86::RAX's sub-register list is EAX, AX, AL, AH.
442   ///
443   const unsigned *getSubRegisters(unsigned RegNo) const {
444     return get(RegNo).SubRegs;
445   }
446
447   /// getSuperRegisters - Return the list of registers that are super-registers
448   /// of the specified register, or a null list of there are none. The list
449   /// returned is zero terminated and sorted according to super-sub register
450   /// relations. e.g. X86::AL's super-register list is AX, EAX, RAX.
451   ///
452   const unsigned *getSuperRegisters(unsigned RegNo) const {
453     return get(RegNo).SuperRegs;
454   }
455
456   /// getName - Return the human-readable symbolic target-specific name for the
457   /// specified physical register.
458   const char *getName(unsigned RegNo) const {
459     return get(RegNo).Name;
460   }
461
462   /// getCostPerUse - Return the additional cost of using this register instead
463   /// of other registers in its class.
464   unsigned getCostPerUse(unsigned RegNo) const {
465     return get(RegNo).CostPerUse;
466   }
467
468   /// getNumRegs - Return the number of registers this target has (useful for
469   /// sizing arrays holding per register information)
470   unsigned getNumRegs() const {
471     return NumRegs;
472   }
473
474   /// getSubRegIndexName - Return the human-readable symbolic target-specific
475   /// name for the specified SubRegIndex.
476   const char *getSubRegIndexName(unsigned SubIdx) const {
477     assert(SubIdx && "This is not a subregister index");
478     return SubRegIndexNames[SubIdx-1];
479   }
480
481   /// regsOverlap - Returns true if the two registers are equal or alias each
482   /// other. The registers may be virtual register.
483   bool regsOverlap(unsigned regA, unsigned regB) const {
484     if (regA == regB) return true;
485     if (isVirtualRegister(regA) || isVirtualRegister(regB))
486       return false;
487     for (const unsigned *regList = getOverlaps(regA)+1; *regList; ++regList) {
488       if (*regList == regB) return true;
489     }
490     return false;
491   }
492
493   /// isSubRegister - Returns true if regB is a sub-register of regA.
494   ///
495   bool isSubRegister(unsigned regA, unsigned regB) const {
496     return isSuperRegister(regB, regA);
497   }
498
499   /// isSuperRegister - Returns true if regB is a super-register of regA.
500   ///
501   bool isSuperRegister(unsigned regA, unsigned regB) const {
502     for (const unsigned *regList = getSuperRegisters(regA); *regList;++regList){
503       if (*regList == regB) return true;
504     }
505     return false;
506   }
507
508   /// getCalleeSavedRegs - Return a null-terminated list of all of the
509   /// callee saved registers on this target. The register should be in the
510   /// order of desired callee-save stack frame offset. The first register is
511   /// closed to the incoming stack pointer if stack grows down, and vice versa.
512   virtual const unsigned* getCalleeSavedRegs(const MachineFunction *MF = 0)
513                                                                       const = 0;
514
515
516   /// getReservedRegs - Returns a bitset indexed by physical register number
517   /// indicating if a register is a special register that has particular uses
518   /// and should be considered unavailable at all times, e.g. SP, RA. This is
519   /// used by register scavenger to determine what registers are free.
520   virtual BitVector getReservedRegs(const MachineFunction &MF) const = 0;
521
522   /// getSubReg - Returns the physical register number of sub-register "Index"
523   /// for physical register RegNo. Return zero if the sub-register does not
524   /// exist.
525   virtual unsigned getSubReg(unsigned RegNo, unsigned Index) const = 0;
526
527   /// getSubRegIndex - For a given register pair, return the sub-register index
528   /// if the second register is a sub-register of the first. Return zero
529   /// otherwise.
530   virtual unsigned getSubRegIndex(unsigned RegNo, unsigned SubRegNo) const = 0;
531
532   /// getMatchingSuperReg - Return a super-register of the specified register
533   /// Reg so its sub-register of index SubIdx is Reg.
534   unsigned getMatchingSuperReg(unsigned Reg, unsigned SubIdx,
535                                const TargetRegisterClass *RC) const {
536     for (const unsigned *SRs = getSuperRegisters(Reg); unsigned SR = *SRs;++SRs)
537       if (Reg == getSubReg(SR, SubIdx) && RC->contains(SR))
538         return SR;
539     return 0;
540   }
541
542   /// canCombineSubRegIndices - Given a register class and a list of
543   /// subregister indices, return true if it's possible to combine the
544   /// subregister indices into one that corresponds to a larger
545   /// subregister. Return the new subregister index by reference. Note the
546   /// new index may be zero if the given subregisters can be combined to
547   /// form the whole register.
548   virtual bool canCombineSubRegIndices(const TargetRegisterClass *RC,
549                                        SmallVectorImpl<unsigned> &SubIndices,
550                                        unsigned &NewSubIdx) const {
551     return 0;
552   }
553
554   /// getMatchingSuperRegClass - Return a subclass of the specified register
555   /// class A so that each register in it has a sub-register of the
556   /// specified sub-register index which is in the specified register class B.
557   virtual const TargetRegisterClass *
558   getMatchingSuperRegClass(const TargetRegisterClass *A,
559                            const TargetRegisterClass *B, unsigned Idx) const {
560     return 0;
561   }
562
563   /// composeSubRegIndices - Return the subregister index you get from composing
564   /// two subregister indices.
565   ///
566   /// If R:a:b is the same register as R:c, then composeSubRegIndices(a, b)
567   /// returns c. Note that composeSubRegIndices does not tell you about illegal
568   /// compositions. If R does not have a subreg a, or R:a does not have a subreg
569   /// b, composeSubRegIndices doesn't tell you.
570   ///
571   /// The ARM register Q0 has two D subregs dsub_0:D0 and dsub_1:D1. It also has
572   /// ssub_0:S0 - ssub_3:S3 subregs.
573   /// If you compose subreg indices dsub_1, ssub_0 you get ssub_2.
574   ///
575   virtual unsigned composeSubRegIndices(unsigned a, unsigned b) const {
576     // This default implementation is correct for most targets.
577     return b;
578   }
579
580   //===--------------------------------------------------------------------===//
581   // Register Class Information
582   //
583
584   /// Register class iterators
585   ///
586   regclass_iterator regclass_begin() const { return RegClassBegin; }
587   regclass_iterator regclass_end() const { return RegClassEnd; }
588
589   unsigned getNumRegClasses() const {
590     return (unsigned)(regclass_end()-regclass_begin());
591   }
592
593   /// getRegClass - Returns the register class associated with the enumeration
594   /// value.  See class TargetOperandInfo.
595   const TargetRegisterClass *getRegClass(unsigned i) const {
596     assert(i < getNumRegClasses() && "Register Class ID out of range");
597     return RegClassBegin[i];
598   }
599
600   /// getPointerRegClass - Returns a TargetRegisterClass used for pointer
601   /// values.  If a target supports multiple different pointer register classes,
602   /// kind specifies which one is indicated.
603   virtual const TargetRegisterClass *getPointerRegClass(unsigned Kind=0) const {
604     assert(0 && "Target didn't implement getPointerRegClass!");
605     return 0; // Must return a value in order to compile with VS 2005
606   }
607
608   /// getCrossCopyRegClass - Returns a legal register class to copy a register
609   /// in the specified class to or from. If it is possible to copy the register
610   /// directly without using a cross register class copy, return the specified
611   /// RC. Returns NULL if it is not possible to copy between a two registers of
612   /// the specified class.
613   virtual const TargetRegisterClass *
614   getCrossCopyRegClass(const TargetRegisterClass *RC) const {
615     return RC;
616   }
617
618   /// getLargestLegalSuperClass - Returns the largest super class of RC that is
619   /// legal to use in the current sub-target and has the same spill size.
620   /// The returned register class can be used to create virtual registers which
621   /// means that all its registers can be copied and spilled.
622   virtual const TargetRegisterClass*
623   getLargestLegalSuperClass(const TargetRegisterClass *RC) const {
624     /// The default implementation is very conservative and doesn't allow the
625     /// register allocator to inflate register classes.
626     return RC;
627   }
628
629   /// getRegPressureLimit - Return the register pressure "high water mark" for
630   /// the specific register class. The scheduler is in high register pressure
631   /// mode (for the specific register class) if it goes over the limit.
632   virtual unsigned getRegPressureLimit(const TargetRegisterClass *RC,
633                                        MachineFunction &MF) const {
634     return 0;
635   }
636
637   /// getRawAllocationOrder - Returns the register allocation order for a
638   /// specified register class with a target-dependent hint. The returned list
639   /// may contain reserved registers that cannot be allocated.
640   ///
641   /// Register allocators need only call this function to resolve
642   /// target-dependent hints, but it should work without hinting as well.
643   virtual ArrayRef<unsigned>
644   getRawAllocationOrder(const TargetRegisterClass *RC,
645                         unsigned HintType, unsigned HintReg,
646                         const MachineFunction &MF) const {
647     return RC->getRawAllocationOrder(MF);
648   }
649
650   /// ResolveRegAllocHint - Resolves the specified register allocation hint
651   /// to a physical register. Returns the physical register if it is successful.
652   virtual unsigned ResolveRegAllocHint(unsigned Type, unsigned Reg,
653                                        const MachineFunction &MF) const {
654     if (Type == 0 && Reg && isPhysicalRegister(Reg))
655       return Reg;
656     return 0;
657   }
658
659   /// avoidWriteAfterWrite - Return true if the register allocator should avoid
660   /// writing a register from RC in two consecutive instructions.
661   /// This can avoid pipeline stalls on certain architectures.
662   /// It does cause increased register pressure, though.
663   virtual bool avoidWriteAfterWrite(const TargetRegisterClass *RC) const {
664     return false;
665   }
666
667   /// UpdateRegAllocHint - A callback to allow target a chance to update
668   /// register allocation hints when a register is "changed" (e.g. coalesced)
669   /// to another register. e.g. On ARM, some virtual registers should target
670   /// register pairs, if one of pair is coalesced to another register, the
671   /// allocation hint of the other half of the pair should be changed to point
672   /// to the new register.
673   virtual void UpdateRegAllocHint(unsigned Reg, unsigned NewReg,
674                                   MachineFunction &MF) const {
675     // Do nothing.
676   }
677
678   /// requiresRegisterScavenging - returns true if the target requires (and can
679   /// make use of) the register scavenger.
680   virtual bool requiresRegisterScavenging(const MachineFunction &MF) const {
681     return false;
682   }
683
684   /// useFPForScavengingIndex - returns true if the target wants to use
685   /// frame pointer based accesses to spill to the scavenger emergency spill
686   /// slot.
687   virtual bool useFPForScavengingIndex(const MachineFunction &MF) const {
688     return true;
689   }
690
691   /// requiresFrameIndexScavenging - returns true if the target requires post
692   /// PEI scavenging of registers for materializing frame index constants.
693   virtual bool requiresFrameIndexScavenging(const MachineFunction &MF) const {
694     return false;
695   }
696
697   /// requiresVirtualBaseRegisters - Returns true if the target wants the
698   /// LocalStackAllocation pass to be run and virtual base registers
699   /// used for more efficient stack access.
700   virtual bool requiresVirtualBaseRegisters(const MachineFunction &MF) const {
701     return false;
702   }
703
704   /// hasReservedSpillSlot - Return true if target has reserved a spill slot in
705   /// the stack frame of the given function for the specified register. e.g. On
706   /// x86, if the frame register is required, the first fixed stack object is
707   /// reserved as its spill slot. This tells PEI not to create a new stack frame
708   /// object for the given register. It should be called only after
709   /// processFunctionBeforeCalleeSavedScan().
710   virtual bool hasReservedSpillSlot(const MachineFunction &MF, unsigned Reg,
711                                     int &FrameIdx) const {
712     return false;
713   }
714
715   /// needsStackRealignment - true if storage within the function requires the
716   /// stack pointer to be aligned more than the normal calling convention calls
717   /// for.
718   virtual bool needsStackRealignment(const MachineFunction &MF) const {
719     return false;
720   }
721
722   /// getFrameIndexInstrOffset - Get the offset from the referenced frame
723   /// index in the instruction, if there is one.
724   virtual int64_t getFrameIndexInstrOffset(const MachineInstr *MI,
725                                            int Idx) const {
726     return 0;
727   }
728
729   /// needsFrameBaseReg - Returns true if the instruction's frame index
730   /// reference would be better served by a base register other than FP
731   /// or SP. Used by LocalStackFrameAllocation to determine which frame index
732   /// references it should create new base registers for.
733   virtual bool needsFrameBaseReg(MachineInstr *MI, int64_t Offset) const {
734     return false;
735   }
736
737   /// materializeFrameBaseRegister - Insert defining instruction(s) for
738   /// BaseReg to be a pointer to FrameIdx before insertion point I.
739   virtual void materializeFrameBaseRegister(MachineBasicBlock *MBB,
740                                             unsigned BaseReg, int FrameIdx,
741                                             int64_t Offset) const {
742     assert(0 && "materializeFrameBaseRegister does not exist on this target");
743   }
744
745   /// resolveFrameIndex - Resolve a frame index operand of an instruction
746   /// to reference the indicated base register plus offset instead.
747   virtual void resolveFrameIndex(MachineBasicBlock::iterator I,
748                                  unsigned BaseReg, int64_t Offset) const {
749     assert(0 && "resolveFrameIndex does not exist on this target");
750   }
751
752   /// isFrameOffsetLegal - Determine whether a given offset immediate is
753   /// encodable to resolve a frame index.
754   virtual bool isFrameOffsetLegal(const MachineInstr *MI,
755                                   int64_t Offset) const {
756     assert(0 && "isFrameOffsetLegal does not exist on this target");
757     return false; // Must return a value in order to compile with VS 2005
758   }
759
760   /// getCallFrameSetup/DestroyOpcode - These methods return the opcode of the
761   /// frame setup/destroy instructions if they exist (-1 otherwise).  Some
762   /// targets use pseudo instructions in order to abstract away the difference
763   /// between operating with a frame pointer and operating without, through the
764   /// use of these two instructions.
765   ///
766   int getCallFrameSetupOpcode() const { return CallFrameSetupOpcode; }
767   int getCallFrameDestroyOpcode() const { return CallFrameDestroyOpcode; }
768
769   /// eliminateCallFramePseudoInstr - This method is called during prolog/epilog
770   /// code insertion to eliminate call frame setup and destroy pseudo
771   /// instructions (but only if the Target is using them).  It is responsible
772   /// for eliminating these instructions, replacing them with concrete
773   /// instructions.  This method need only be implemented if using call frame
774   /// setup/destroy pseudo instructions.
775   ///
776   virtual void
777   eliminateCallFramePseudoInstr(MachineFunction &MF,
778                                 MachineBasicBlock &MBB,
779                                 MachineBasicBlock::iterator MI) const {
780     assert(getCallFrameSetupOpcode()== -1 && getCallFrameDestroyOpcode()== -1 &&
781            "eliminateCallFramePseudoInstr must be implemented if using"
782            " call frame setup/destroy pseudo instructions!");
783     assert(0 && "Call Frame Pseudo Instructions do not exist on this target!");
784   }
785
786
787   /// saveScavengerRegister - Spill the register so it can be used by the
788   /// register scavenger. Return true if the register was spilled, false
789   /// otherwise. If this function does not spill the register, the scavenger
790   /// will instead spill it to the emergency spill slot.
791   ///
792   virtual bool saveScavengerRegister(MachineBasicBlock &MBB,
793                                      MachineBasicBlock::iterator I,
794                                      MachineBasicBlock::iterator &UseMI,
795                                      const TargetRegisterClass *RC,
796                                      unsigned Reg) const {
797     return false;
798   }
799
800   /// eliminateFrameIndex - This method must be overriden to eliminate abstract
801   /// frame indices from instructions which may use them.  The instruction
802   /// referenced by the iterator contains an MO_FrameIndex operand which must be
803   /// eliminated by this method.  This method may modify or replace the
804   /// specified instruction, as long as it keeps the iterator pointing at the
805   /// finished product. SPAdj is the SP adjustment due to call frame setup
806   /// instruction.
807   virtual void eliminateFrameIndex(MachineBasicBlock::iterator MI,
808                                    int SPAdj, RegScavenger *RS=NULL) const = 0;
809
810   //===--------------------------------------------------------------------===//
811   /// Debug information queries.
812
813   /// getDwarfRegNum - Map a target register to an equivalent dwarf register
814   /// number.  Returns -1 if there is no equivalent value.  The second
815   /// parameter allows targets to use different numberings for EH info and
816   /// debugging info.
817   virtual int getDwarfRegNum(unsigned RegNum, bool isEH) const = 0;
818
819   virtual int getLLVMRegNum(unsigned RegNum, bool isEH) const = 0;
820
821   /// getFrameRegister - This method should return the register used as a base
822   /// for values allocated in the current stack frame.
823   virtual unsigned getFrameRegister(const MachineFunction &MF) const = 0;
824
825   /// getRARegister - This method should return the register where the return
826   /// address can be found.
827   virtual unsigned getRARegister() const = 0;
828
829   /// getSEHRegNum - Map a target register to an equivalent SEH register
830   /// number.  Returns -1 if there is no equivalent value.
831   virtual int getSEHRegNum(unsigned i) const {
832     return i;
833   }
834 };
835
836
837 // This is useful when building IndexedMaps keyed on virtual registers
838 struct VirtReg2IndexFunctor : public std::unary_function<unsigned, unsigned> {
839   unsigned operator()(unsigned Reg) const {
840     return TargetRegisterInfo::virtReg2Index(Reg);
841   }
842 };
843
844 /// getCommonSubClass - find the largest common subclass of A and B. Return NULL
845 /// if there is no common subclass.
846 const TargetRegisterClass *getCommonSubClass(const TargetRegisterClass *A,
847                                              const TargetRegisterClass *B);
848
849 /// PrintReg - Helper class for printing registers on a raw_ostream.
850 /// Prints virtual and physical registers with or without a TRI instance.
851 ///
852 /// The format is:
853 ///   %noreg          - NoRegister
854 ///   %vreg5          - a virtual register.
855 ///   %vreg5:sub_8bit - a virtual register with sub-register index (with TRI).
856 ///   %EAX            - a physical register
857 ///   %physreg17      - a physical register when no TRI instance given.
858 ///
859 /// Usage: OS << PrintReg(Reg, TRI) << '\n';
860 ///
861 class PrintReg {
862   const TargetRegisterInfo *TRI;
863   unsigned Reg;
864   unsigned SubIdx;
865 public:
866   PrintReg(unsigned reg, const TargetRegisterInfo *tri = 0, unsigned subidx = 0)
867     : TRI(tri), Reg(reg), SubIdx(subidx) {}
868   void print(raw_ostream&) const;
869 };
870
871 static inline raw_ostream &operator<<(raw_ostream &OS, const PrintReg &PR) {
872   PR.print(OS);
873   return OS;
874 }
875
876 } // End llvm namespace
877
878 #endif