TargetRegisterInfo.h revision 54c47c1ce94b9e549ef768e80fd004788d13ce85
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
26namespace llvm {
27
28class BitVector;
29class MachineFunction;
30class MachineMove;
31class RegScavenger;
32template<class T> class SmallVectorImpl;
33class 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///
45struct 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
54class TargetRegisterClass {
55public:
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;
61private:
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;
74public:
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  /// getRawAllocationOrder - Returns the preferred order for allocating
241  /// registers from this register class in MF. The raw order comes directly
242  /// from the .td file and may include reserved registers that are not
243  /// allocatable. Register allocators should also make sure to allocate
244  /// callee-saved registers only after all the volatiles are used. The
245  /// RegisterClassInfo class provides filtered allocation orders with
246  /// callee-saved registers moved to the end.
247  ///
248  /// The MachineFunction argument can be used to tune the allocatable
249  /// registers based on the characteristics of the function, subtarget, or
250  /// other criteria.
251  ///
252  /// By default, this method returns all registers in the class.
253  ///
254  virtual
255  ArrayRef<unsigned> getRawAllocationOrder(const MachineFunction &MF) const {
256    return ArrayRef<unsigned>(begin(), getNumRegs());
257  }
258
259  /// getSize - Return the size of the register in bytes, which is also the size
260  /// of a stack slot allocated to hold a spilled copy of this register.
261  unsigned getSize() const { return RegSize; }
262
263  /// getAlignment - Return the minimum required alignment for a register of
264  /// this class.
265  unsigned getAlignment() const { return Alignment; }
266
267  /// getCopyCost - Return the cost of copying a value between two registers in
268  /// this class. A negative number means the register class is very expensive
269  /// to copy e.g. status flag register classes.
270  int getCopyCost() const { return CopyCost; }
271
272  /// isAllocatable - Return true if this register class may be used to create
273  /// virtual registers.
274  bool isAllocatable() const { return Allocatable; }
275};
276
277
278/// TargetRegisterInfo base class - We assume that the target defines a static
279/// array of TargetRegisterDesc objects that represent all of the machine
280/// registers that the target has.  As such, we simply have to track a pointer
281/// to this array so that we can turn register number into a register
282/// descriptor.
283///
284class TargetRegisterInfo {
285public:
286  typedef const TargetRegisterClass * const * regclass_iterator;
287private:
288  const TargetRegisterDesc *Desc;             // Pointer to the descriptor array
289  const char *const *SubRegIndexNames;        // Names of subreg indexes.
290  unsigned NumRegs;                           // Number of entries in the array
291
292  regclass_iterator RegClassBegin, RegClassEnd;   // List of regclasses
293
294  int CallFrameSetupOpcode, CallFrameDestroyOpcode;
295
296protected:
297  TargetRegisterInfo(const TargetRegisterDesc *D, unsigned NR,
298                     regclass_iterator RegClassBegin,
299                     regclass_iterator RegClassEnd,
300                     const char *const *subregindexnames,
301                     int CallFrameSetupOpcode = -1,
302                     int CallFrameDestroyOpcode = -1);
303  virtual ~TargetRegisterInfo();
304public:
305
306  // Register numbers can represent physical registers, virtual registers, and
307  // sometimes stack slots. The unsigned values are divided into these ranges:
308  //
309  //   0           Not a register, can be used as a sentinel.
310  //   [1;2^30)    Physical registers assigned by TableGen.
311  //   [2^30;2^31) Stack slots. (Rarely used.)
312  //   [2^31;2^32) Virtual registers assigned by MachineRegisterInfo.
313  //
314  // Further sentinels can be allocated from the small negative integers.
315  // DenseMapInfo<unsigned> uses -1u and -2u.
316
317  /// isStackSlot - Sometimes it is useful the be able to store a non-negative
318  /// frame index in a variable that normally holds a register. isStackSlot()
319  /// returns true if Reg is in the range used for stack slots.
320  ///
321  /// Note that isVirtualRegister() and isPhysicalRegister() cannot handle stack
322  /// slots, so if a variable may contains a stack slot, always check
323  /// isStackSlot() first.
324  ///
325  static bool isStackSlot(unsigned Reg) {
326    return int(Reg) >= (1 << 30);
327  }
328
329  /// stackSlot2Index - Compute the frame index from a register value
330  /// representing a stack slot.
331  static int stackSlot2Index(unsigned Reg) {
332    assert(isStackSlot(Reg) && "Not a stack slot");
333    return int(Reg - (1u << 30));
334  }
335
336  /// index2StackSlot - Convert a non-negative frame index to a stack slot
337  /// register value.
338  static unsigned index2StackSlot(int FI) {
339    assert(FI >= 0 && "Cannot hold a negative frame index.");
340    return FI + (1u << 30);
341  }
342
343  /// isPhysicalRegister - Return true if the specified register number is in
344  /// the physical register namespace.
345  static bool isPhysicalRegister(unsigned Reg) {
346    assert(!isStackSlot(Reg) && "Not a register! Check isStackSlot() first.");
347    return int(Reg) > 0;
348  }
349
350  /// isVirtualRegister - Return true if the specified register number is in
351  /// the virtual register namespace.
352  static bool isVirtualRegister(unsigned Reg) {
353    assert(!isStackSlot(Reg) && "Not a register! Check isStackSlot() first.");
354    return int(Reg) < 0;
355  }
356
357  /// virtReg2Index - Convert a virtual register number to a 0-based index.
358  /// The first virtual register in a function will get the index 0.
359  static unsigned virtReg2Index(unsigned Reg) {
360    assert(isVirtualRegister(Reg) && "Not a virtual register");
361    return Reg & ~(1u << 31);
362  }
363
364  /// index2VirtReg - Convert a 0-based index to a virtual register number.
365  /// This is the inverse operation of VirtReg2IndexFunctor below.
366  static unsigned index2VirtReg(unsigned Index) {
367    return Index | (1u << 31);
368  }
369
370  /// getMinimalPhysRegClass - Returns the Register Class of a physical
371  /// register of the given type, picking the most sub register class of
372  /// the right type that contains this physreg.
373  const TargetRegisterClass *
374    getMinimalPhysRegClass(unsigned Reg, EVT VT = MVT::Other) const;
375
376  /// getAllocatableSet - Returns a bitset indexed by register number
377  /// indicating if a register is allocatable or not. If a register class is
378  /// specified, returns the subset for the class.
379  BitVector getAllocatableSet(const MachineFunction &MF,
380                              const TargetRegisterClass *RC = NULL) const;
381
382  const TargetRegisterDesc &operator[](unsigned RegNo) const {
383    assert(RegNo < NumRegs &&
384           "Attempting to access record for invalid register number!");
385    return Desc[RegNo];
386  }
387
388  /// Provide a get method, equivalent to [], but more useful if we have a
389  /// pointer to this object.
390  ///
391  const TargetRegisterDesc &get(unsigned RegNo) const {
392    return operator[](RegNo);
393  }
394
395  /// getAliasSet - Return the set of registers aliased by the specified
396  /// register, or a null list of there are none.  The list returned is zero
397  /// terminated.
398  ///
399  const unsigned *getAliasSet(unsigned RegNo) const {
400    // The Overlaps set always begins with Reg itself.
401    return get(RegNo).Overlaps + 1;
402  }
403
404  /// getOverlaps - Return a list of registers that overlap Reg, including
405  /// itself. This is the same as the alias set except Reg is included in the
406  /// list.
407  /// These are exactly the registers in { x | regsOverlap(x, Reg) }.
408  ///
409  const unsigned *getOverlaps(unsigned RegNo) const {
410    return get(RegNo).Overlaps;
411  }
412
413  /// getSubRegisters - Return the list of registers that are sub-registers of
414  /// the specified register, or a null list of there are none. The list
415  /// returned is zero terminated and sorted according to super-sub register
416  /// relations. e.g. X86::RAX's sub-register list is EAX, AX, AL, AH.
417  ///
418  const unsigned *getSubRegisters(unsigned RegNo) const {
419    return get(RegNo).SubRegs;
420  }
421
422  /// getSuperRegisters - Return the list of registers that are super-registers
423  /// of the specified register, or a null list of there are none. The list
424  /// returned is zero terminated and sorted according to super-sub register
425  /// relations. e.g. X86::AL's super-register list is AX, EAX, RAX.
426  ///
427  const unsigned *getSuperRegisters(unsigned RegNo) const {
428    return get(RegNo).SuperRegs;
429  }
430
431  /// getName - Return the human-readable symbolic target-specific name for the
432  /// specified physical register.
433  const char *getName(unsigned RegNo) const {
434    return get(RegNo).Name;
435  }
436
437  /// getCostPerUse - Return the additional cost of using this register instead
438  /// of other registers in its class.
439  unsigned getCostPerUse(unsigned RegNo) const {
440    return get(RegNo).CostPerUse;
441  }
442
443  /// getNumRegs - Return the number of registers this target has (useful for
444  /// sizing arrays holding per register information)
445  unsigned getNumRegs() const {
446    return NumRegs;
447  }
448
449  /// getSubRegIndexName - Return the human-readable symbolic target-specific
450  /// name for the specified SubRegIndex.
451  const char *getSubRegIndexName(unsigned SubIdx) const {
452    assert(SubIdx && "This is not a subregister index");
453    return SubRegIndexNames[SubIdx-1];
454  }
455
456  /// regsOverlap - Returns true if the two registers are equal or alias each
457  /// other. The registers may be virtual register.
458  bool regsOverlap(unsigned regA, unsigned regB) const {
459    if (regA == regB) return true;
460    if (isVirtualRegister(regA) || isVirtualRegister(regB))
461      return false;
462    for (const unsigned *regList = getOverlaps(regA)+1; *regList; ++regList) {
463      if (*regList == regB) return true;
464    }
465    return false;
466  }
467
468  /// isSubRegister - Returns true if regB is a sub-register of regA.
469  ///
470  bool isSubRegister(unsigned regA, unsigned regB) const {
471    return isSuperRegister(regB, regA);
472  }
473
474  /// isSuperRegister - Returns true if regB is a super-register of regA.
475  ///
476  bool isSuperRegister(unsigned regA, unsigned regB) const {
477    for (const unsigned *regList = getSuperRegisters(regA); *regList;++regList){
478      if (*regList == regB) return true;
479    }
480    return false;
481  }
482
483  /// getCalleeSavedRegs - Return a null-terminated list of all of the
484  /// callee saved registers on this target. The register should be in the
485  /// order of desired callee-save stack frame offset. The first register is
486  /// closed to the incoming stack pointer if stack grows down, and vice versa.
487  virtual const unsigned* getCalleeSavedRegs(const MachineFunction *MF = 0)
488                                                                      const = 0;
489
490
491  /// getReservedRegs - Returns a bitset indexed by physical register number
492  /// indicating if a register is a special register that has particular uses
493  /// and should be considered unavailable at all times, e.g. SP, RA. This is
494  /// used by register scavenger to determine what registers are free.
495  virtual BitVector getReservedRegs(const MachineFunction &MF) const = 0;
496
497  /// getSubReg - Returns the physical register number of sub-register "Index"
498  /// for physical register RegNo. Return zero if the sub-register does not
499  /// exist.
500  virtual unsigned getSubReg(unsigned RegNo, unsigned Index) const = 0;
501
502  /// getSubRegIndex - For a given register pair, return the sub-register index
503  /// if the second register is a sub-register of the first. Return zero
504  /// otherwise.
505  virtual unsigned getSubRegIndex(unsigned RegNo, unsigned SubRegNo) const = 0;
506
507  /// getMatchingSuperReg - Return a super-register of the specified register
508  /// Reg so its sub-register of index SubIdx is Reg.
509  unsigned getMatchingSuperReg(unsigned Reg, unsigned SubIdx,
510                               const TargetRegisterClass *RC) const {
511    for (const unsigned *SRs = getSuperRegisters(Reg); unsigned SR = *SRs;++SRs)
512      if (Reg == getSubReg(SR, SubIdx) && RC->contains(SR))
513        return SR;
514    return 0;
515  }
516
517  /// canCombineSubRegIndices - Given a register class and a list of
518  /// subregister indices, return true if it's possible to combine the
519  /// subregister indices into one that corresponds to a larger
520  /// subregister. Return the new subregister index by reference. Note the
521  /// new index may be zero if the given subregisters can be combined to
522  /// form the whole register.
523  virtual bool canCombineSubRegIndices(const TargetRegisterClass *RC,
524                                       SmallVectorImpl<unsigned> &SubIndices,
525                                       unsigned &NewSubIdx) const {
526    return 0;
527  }
528
529  /// getMatchingSuperRegClass - Return a subclass of the specified register
530  /// class A so that each register in it has a sub-register of the
531  /// specified sub-register index which is in the specified register class B.
532  virtual const TargetRegisterClass *
533  getMatchingSuperRegClass(const TargetRegisterClass *A,
534                           const TargetRegisterClass *B, unsigned Idx) const {
535    return 0;
536  }
537
538  /// composeSubRegIndices - Return the subregister index you get from composing
539  /// two subregister indices.
540  ///
541  /// If R:a:b is the same register as R:c, then composeSubRegIndices(a, b)
542  /// returns c. Note that composeSubRegIndices does not tell you about illegal
543  /// compositions. If R does not have a subreg a, or R:a does not have a subreg
544  /// b, composeSubRegIndices doesn't tell you.
545  ///
546  /// The ARM register Q0 has two D subregs dsub_0:D0 and dsub_1:D1. It also has
547  /// ssub_0:S0 - ssub_3:S3 subregs.
548  /// If you compose subreg indices dsub_1, ssub_0 you get ssub_2.
549  ///
550  virtual unsigned composeSubRegIndices(unsigned a, unsigned b) const {
551    // This default implementation is correct for most targets.
552    return b;
553  }
554
555  //===--------------------------------------------------------------------===//
556  // Register Class Information
557  //
558
559  /// Register class iterators
560  ///
561  regclass_iterator regclass_begin() const { return RegClassBegin; }
562  regclass_iterator regclass_end() const { return RegClassEnd; }
563
564  unsigned getNumRegClasses() const {
565    return (unsigned)(regclass_end()-regclass_begin());
566  }
567
568  /// getRegClass - Returns the register class associated with the enumeration
569  /// value.  See class TargetOperandInfo.
570  const TargetRegisterClass *getRegClass(unsigned i) const {
571    assert(i < getNumRegClasses() && "Register Class ID out of range");
572    return RegClassBegin[i];
573  }
574
575  /// getPointerRegClass - Returns a TargetRegisterClass used for pointer
576  /// values.  If a target supports multiple different pointer register classes,
577  /// kind specifies which one is indicated.
578  virtual const TargetRegisterClass *getPointerRegClass(unsigned Kind=0) const {
579    assert(0 && "Target didn't implement getPointerRegClass!");
580    return 0; // Must return a value in order to compile with VS 2005
581  }
582
583  /// getCrossCopyRegClass - Returns a legal register class to copy a register
584  /// in the specified class to or from. If it is possible to copy the register
585  /// directly without using a cross register class copy, return the specified
586  /// RC. Returns NULL if it is not possible to copy between a two registers of
587  /// the specified class.
588  virtual const TargetRegisterClass *
589  getCrossCopyRegClass(const TargetRegisterClass *RC) const {
590    return RC;
591  }
592
593  /// getLargestLegalSuperClass - Returns the largest super class of RC that is
594  /// legal to use in the current sub-target and has the same spill size.
595  /// The returned register class can be used to create virtual registers which
596  /// means that all its registers can be copied and spilled.
597  virtual const TargetRegisterClass*
598  getLargestLegalSuperClass(const TargetRegisterClass *RC) const {
599    /// The default implementation is very conservative and doesn't allow the
600    /// register allocator to inflate register classes.
601    return RC;
602  }
603
604  /// getRegPressureLimit - Return the register pressure "high water mark" for
605  /// the specific register class. The scheduler is in high register pressure
606  /// mode (for the specific register class) if it goes over the limit.
607  virtual unsigned getRegPressureLimit(const TargetRegisterClass *RC,
608                                       MachineFunction &MF) const {
609    return 0;
610  }
611
612  /// getRawAllocationOrder - Returns the register allocation order for a
613  /// specified register class with a target-dependent hint. The returned list
614  /// may contain reserved registers that cannot be allocated.
615  ///
616  /// Register allocators need only call this function to resolve
617  /// target-dependent hints, but it should work without hinting as well.
618  virtual ArrayRef<unsigned>
619  getRawAllocationOrder(const TargetRegisterClass *RC,
620                        unsigned HintType, unsigned HintReg,
621                        const MachineFunction &MF) const {
622    return RC->getRawAllocationOrder(MF);
623  }
624
625  /// ResolveRegAllocHint - Resolves the specified register allocation hint
626  /// to a physical register. Returns the physical register if it is successful.
627  virtual unsigned ResolveRegAllocHint(unsigned Type, unsigned Reg,
628                                       const MachineFunction &MF) const {
629    if (Type == 0 && Reg && isPhysicalRegister(Reg))
630      return Reg;
631    return 0;
632  }
633
634  /// avoidWriteAfterWrite - Return true if the register allocator should avoid
635  /// writing a register from RC in two consecutive instructions.
636  /// This can avoid pipeline stalls on certain architectures.
637  /// It does cause increased register pressure, though.
638  virtual bool avoidWriteAfterWrite(const TargetRegisterClass *RC) const {
639    return false;
640  }
641
642  /// UpdateRegAllocHint - A callback to allow target a chance to update
643  /// register allocation hints when a register is "changed" (e.g. coalesced)
644  /// to another register. e.g. On ARM, some virtual registers should target
645  /// register pairs, if one of pair is coalesced to another register, the
646  /// allocation hint of the other half of the pair should be changed to point
647  /// to the new register.
648  virtual void UpdateRegAllocHint(unsigned Reg, unsigned NewReg,
649                                  MachineFunction &MF) const {
650    // Do nothing.
651  }
652
653  /// requiresRegisterScavenging - returns true if the target requires (and can
654  /// make use of) the register scavenger.
655  virtual bool requiresRegisterScavenging(const MachineFunction &MF) const {
656    return false;
657  }
658
659  /// useFPForScavengingIndex - returns true if the target wants to use
660  /// frame pointer based accesses to spill to the scavenger emergency spill
661  /// slot.
662  virtual bool useFPForScavengingIndex(const MachineFunction &MF) const {
663    return true;
664  }
665
666  /// requiresFrameIndexScavenging - returns true if the target requires post
667  /// PEI scavenging of registers for materializing frame index constants.
668  virtual bool requiresFrameIndexScavenging(const MachineFunction &MF) const {
669    return false;
670  }
671
672  /// requiresVirtualBaseRegisters - Returns true if the target wants the
673  /// LocalStackAllocation pass to be run and virtual base registers
674  /// used for more efficient stack access.
675  virtual bool requiresVirtualBaseRegisters(const MachineFunction &MF) const {
676    return false;
677  }
678
679  /// hasReservedSpillSlot - Return true if target has reserved a spill slot in
680  /// the stack frame of the given function for the specified register. e.g. On
681  /// x86, if the frame register is required, the first fixed stack object is
682  /// reserved as its spill slot. This tells PEI not to create a new stack frame
683  /// object for the given register. It should be called only after
684  /// processFunctionBeforeCalleeSavedScan().
685  virtual bool hasReservedSpillSlot(const MachineFunction &MF, unsigned Reg,
686                                    int &FrameIdx) const {
687    return false;
688  }
689
690  /// needsStackRealignment - true if storage within the function requires the
691  /// stack pointer to be aligned more than the normal calling convention calls
692  /// for.
693  virtual bool needsStackRealignment(const MachineFunction &MF) const {
694    return false;
695  }
696
697  /// getFrameIndexInstrOffset - Get the offset from the referenced frame
698  /// index in the instruction, if there is one.
699  virtual int64_t getFrameIndexInstrOffset(const MachineInstr *MI,
700                                           int Idx) const {
701    return 0;
702  }
703
704  /// needsFrameBaseReg - Returns true if the instruction's frame index
705  /// reference would be better served by a base register other than FP
706  /// or SP. Used by LocalStackFrameAllocation to determine which frame index
707  /// references it should create new base registers for.
708  virtual bool needsFrameBaseReg(MachineInstr *MI, int64_t Offset) const {
709    return false;
710  }
711
712  /// materializeFrameBaseRegister - Insert defining instruction(s) for
713  /// BaseReg to be a pointer to FrameIdx before insertion point I.
714  virtual void materializeFrameBaseRegister(MachineBasicBlock *MBB,
715                                            unsigned BaseReg, int FrameIdx,
716                                            int64_t Offset) const {
717    assert(0 && "materializeFrameBaseRegister does not exist on this target");
718  }
719
720  /// resolveFrameIndex - Resolve a frame index operand of an instruction
721  /// to reference the indicated base register plus offset instead.
722  virtual void resolveFrameIndex(MachineBasicBlock::iterator I,
723                                 unsigned BaseReg, int64_t Offset) const {
724    assert(0 && "resolveFrameIndex does not exist on this target");
725  }
726
727  /// isFrameOffsetLegal - Determine whether a given offset immediate is
728  /// encodable to resolve a frame index.
729  virtual bool isFrameOffsetLegal(const MachineInstr *MI,
730                                  int64_t Offset) const {
731    assert(0 && "isFrameOffsetLegal does not exist on this target");
732    return false; // Must return a value in order to compile with VS 2005
733  }
734
735  /// getCallFrameSetup/DestroyOpcode - These methods return the opcode of the
736  /// frame setup/destroy instructions if they exist (-1 otherwise).  Some
737  /// targets use pseudo instructions in order to abstract away the difference
738  /// between operating with a frame pointer and operating without, through the
739  /// use of these two instructions.
740  ///
741  int getCallFrameSetupOpcode() const { return CallFrameSetupOpcode; }
742  int getCallFrameDestroyOpcode() const { return CallFrameDestroyOpcode; }
743
744  /// eliminateCallFramePseudoInstr - This method is called during prolog/epilog
745  /// code insertion to eliminate call frame setup and destroy pseudo
746  /// instructions (but only if the Target is using them).  It is responsible
747  /// for eliminating these instructions, replacing them with concrete
748  /// instructions.  This method need only be implemented if using call frame
749  /// setup/destroy pseudo instructions.
750  ///
751  virtual void
752  eliminateCallFramePseudoInstr(MachineFunction &MF,
753                                MachineBasicBlock &MBB,
754                                MachineBasicBlock::iterator MI) const {
755    assert(getCallFrameSetupOpcode()== -1 && getCallFrameDestroyOpcode()== -1 &&
756           "eliminateCallFramePseudoInstr must be implemented if using"
757           " call frame setup/destroy pseudo instructions!");
758    assert(0 && "Call Frame Pseudo Instructions do not exist on this target!");
759  }
760
761
762  /// saveScavengerRegister - Spill the register so it can be used by the
763  /// register scavenger. Return true if the register was spilled, false
764  /// otherwise. If this function does not spill the register, the scavenger
765  /// will instead spill it to the emergency spill slot.
766  ///
767  virtual bool saveScavengerRegister(MachineBasicBlock &MBB,
768                                     MachineBasicBlock::iterator I,
769                                     MachineBasicBlock::iterator &UseMI,
770                                     const TargetRegisterClass *RC,
771                                     unsigned Reg) const {
772    return false;
773  }
774
775  /// eliminateFrameIndex - This method must be overriden to eliminate abstract
776  /// frame indices from instructions which may use them.  The instruction
777  /// referenced by the iterator contains an MO_FrameIndex operand which must be
778  /// eliminated by this method.  This method may modify or replace the
779  /// specified instruction, as long as it keeps the iterator pointing at the
780  /// finished product. SPAdj is the SP adjustment due to call frame setup
781  /// instruction.
782  virtual void eliminateFrameIndex(MachineBasicBlock::iterator MI,
783                                   int SPAdj, RegScavenger *RS=NULL) const = 0;
784
785  //===--------------------------------------------------------------------===//
786  /// Debug information queries.
787
788  /// getDwarfRegNum - Map a target register to an equivalent dwarf register
789  /// number.  Returns -1 if there is no equivalent value.  The second
790  /// parameter allows targets to use different numberings for EH info and
791  /// debugging info.
792  virtual int getDwarfRegNum(unsigned RegNum, bool isEH) const = 0;
793
794  virtual int getLLVMRegNum(unsigned RegNum, bool isEH) const = 0;
795
796  /// getFrameRegister - This method should return the register used as a base
797  /// for values allocated in the current stack frame.
798  virtual unsigned getFrameRegister(const MachineFunction &MF) const = 0;
799
800  /// getRARegister - This method should return the register where the return
801  /// address can be found.
802  virtual unsigned getRARegister() const = 0;
803
804  /// getSEHRegNum - Map a target register to an equivalent SEH register
805  /// number.  Returns -1 if there is no equivalent value.
806  virtual int getSEHRegNum(unsigned i) const {
807    return i;
808  }
809};
810
811
812// This is useful when building IndexedMaps keyed on virtual registers
813struct VirtReg2IndexFunctor : public std::unary_function<unsigned, unsigned> {
814  unsigned operator()(unsigned Reg) const {
815    return TargetRegisterInfo::virtReg2Index(Reg);
816  }
817};
818
819/// getCommonSubClass - find the largest common subclass of A and B. Return NULL
820/// if there is no common subclass.
821const TargetRegisterClass *getCommonSubClass(const TargetRegisterClass *A,
822                                             const TargetRegisterClass *B);
823
824/// PrintReg - Helper class for printing registers on a raw_ostream.
825/// Prints virtual and physical registers with or without a TRI instance.
826///
827/// The format is:
828///   %noreg          - NoRegister
829///   %vreg5          - a virtual register.
830///   %vreg5:sub_8bit - a virtual register with sub-register index (with TRI).
831///   %EAX            - a physical register
832///   %physreg17      - a physical register when no TRI instance given.
833///
834/// Usage: OS << PrintReg(Reg, TRI) << '\n';
835///
836class PrintReg {
837  const TargetRegisterInfo *TRI;
838  unsigned Reg;
839  unsigned SubIdx;
840public:
841  PrintReg(unsigned reg, const TargetRegisterInfo *tri = 0, unsigned subidx = 0)
842    : TRI(tri), Reg(reg), SubIdx(subidx) {}
843  void print(raw_ostream&) const;
844};
845
846static inline raw_ostream &operator<<(raw_ostream &OS, const PrintReg &PR) {
847  PR.print(OS);
848  return OS;
849}
850
851} // End llvm namespace
852
853#endif
854