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