TargetRegisterInfo.h revision eca1fcf3d2d8246c45648fea59bd21a4091f9115
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/ADT/ArrayRef.h"
20#include "llvm/CallingConv.h"
21#include "llvm/CodeGen/MachineBasicBlock.h"
22#include "llvm/CodeGen/ValueTypes.h"
23#include "llvm/MC/MCRegisterInfo.h"
24#include <cassert>
25#include <functional>
26
27namespace llvm {
28
29class BitVector;
30class MachineFunction;
31class RegScavenger;
32template<class T> class SmallVectorImpl;
33class VirtRegMap;
34class raw_ostream;
35
36class TargetRegisterClass {
37public:
38  typedef const MCPhysReg* iterator;
39  typedef const MCPhysReg* const_iterator;
40  typedef const MVT::SimpleValueType* vt_iterator;
41  typedef const TargetRegisterClass* const * sc_iterator;
42
43  // Instance variables filled by tablegen, do not use!
44  const MCRegisterClass *MC;
45  const vt_iterator VTs;
46  const uint32_t *SubClassMask;
47  const uint16_t *SuperRegIndices;
48  const sc_iterator SuperClasses;
49  ArrayRef<MCPhysReg> (*OrderFunc)(const MachineFunction&);
50
51  /// getID() - Return the register class ID number.
52  ///
53  unsigned getID() const { return MC->getID(); }
54
55  /// getName() - Return the register class name for debugging.
56  ///
57  const char *getName() const { return MC->getName(); }
58
59  /// begin/end - Return all of the registers in this class.
60  ///
61  iterator       begin() const { return MC->begin(); }
62  iterator         end() const { return MC->end(); }
63
64  /// getNumRegs - Return the number of registers in this class.
65  ///
66  unsigned getNumRegs() const { return MC->getNumRegs(); }
67
68  /// getRegister - Return the specified register in the class.
69  ///
70  unsigned getRegister(unsigned i) const {
71    return MC->getRegister(i);
72  }
73
74  /// contains - Return true if the specified register is included in this
75  /// register class.  This does not include virtual registers.
76  bool contains(unsigned Reg) const {
77    return MC->contains(Reg);
78  }
79
80  /// contains - Return true if both registers are in this class.
81  bool contains(unsigned Reg1, unsigned Reg2) const {
82    return MC->contains(Reg1, Reg2);
83  }
84
85  /// getSize - Return the size of the register in bytes, which is also the size
86  /// of a stack slot allocated to hold a spilled copy of this register.
87  unsigned getSize() const { return MC->getSize(); }
88
89  /// getAlignment - Return the minimum required alignment for a register of
90  /// this class.
91  unsigned getAlignment() const { return MC->getAlignment(); }
92
93  /// getCopyCost - Return the cost of copying a value between two registers in
94  /// this class. A negative number means the register class is very expensive
95  /// to copy e.g. status flag register classes.
96  int getCopyCost() const { return MC->getCopyCost(); }
97
98  /// isAllocatable - Return true if this register class may be used to create
99  /// virtual registers.
100  bool isAllocatable() const { return MC->isAllocatable(); }
101
102  /// hasType - return true if this TargetRegisterClass has the ValueType vt.
103  ///
104  bool hasType(EVT vt) const {
105    for(int i = 0; VTs[i] != MVT::Other; ++i)
106      if (EVT(VTs[i]) == vt)
107        return true;
108    return false;
109  }
110
111  /// vt_begin / vt_end - Loop over all of the value types that can be
112  /// represented by values in this register class.
113  vt_iterator vt_begin() const {
114    return VTs;
115  }
116
117  vt_iterator vt_end() const {
118    vt_iterator I = VTs;
119    while (*I != MVT::Other) ++I;
120    return I;
121  }
122
123  /// hasSubClass - return true if the specified TargetRegisterClass
124  /// is a proper sub-class of this TargetRegisterClass.
125  bool hasSubClass(const TargetRegisterClass *RC) const {
126    return RC != this && hasSubClassEq(RC);
127  }
128
129  /// hasSubClassEq - Returns true if RC is a sub-class of or equal to this
130  /// class.
131  bool hasSubClassEq(const TargetRegisterClass *RC) const {
132    unsigned ID = RC->getID();
133    return (SubClassMask[ID / 32] >> (ID % 32)) & 1;
134  }
135
136  /// hasSuperClass - return true if the specified TargetRegisterClass is a
137  /// proper super-class of this TargetRegisterClass.
138  bool hasSuperClass(const TargetRegisterClass *RC) const {
139    return RC->hasSubClass(this);
140  }
141
142  /// hasSuperClassEq - Returns true if RC is a super-class of or equal to this
143  /// class.
144  bool hasSuperClassEq(const TargetRegisterClass *RC) const {
145    return RC->hasSubClassEq(this);
146  }
147
148  /// getSubClassMask - Returns a bit vector of subclasses, including this one.
149  /// The vector is indexed by class IDs, see hasSubClassEq() above for how to
150  /// use it.
151  const uint32_t *getSubClassMask() const {
152    return SubClassMask;
153  }
154
155  /// getSuperRegIndices - Returns a 0-terminated list of sub-register indices
156  /// that project some super-register class into this register class. The list
157  /// has an entry for each Idx such that:
158  ///
159  ///   There exists SuperRC where:
160  ///     For all Reg in SuperRC:
161  ///       this->contains(Reg:Idx)
162  ///
163  const uint16_t *getSuperRegIndices() const {
164    return SuperRegIndices;
165  }
166
167  /// getSuperClasses - Returns a NULL terminated list of super-classes.  The
168  /// classes are ordered by ID which is also a topological ordering from large
169  /// to small classes.  The list does NOT include the current class.
170  sc_iterator getSuperClasses() const {
171    return SuperClasses;
172  }
173
174  /// isASubClass - return true if this TargetRegisterClass is a subset
175  /// class of at least one other TargetRegisterClass.
176  bool isASubClass() const {
177    return SuperClasses[0] != 0;
178  }
179
180  /// getRawAllocationOrder - Returns the preferred order for allocating
181  /// registers from this register class in MF. The raw order comes directly
182  /// from the .td file and may include reserved registers that are not
183  /// allocatable. Register allocators should also make sure to allocate
184  /// callee-saved registers only after all the volatiles are used. The
185  /// RegisterClassInfo class provides filtered allocation orders with
186  /// callee-saved registers moved to the end.
187  ///
188  /// The MachineFunction argument can be used to tune the allocatable
189  /// registers based on the characteristics of the function, subtarget, or
190  /// other criteria.
191  ///
192  /// By default, this method returns all registers in the class.
193  ///
194  ArrayRef<MCPhysReg> getRawAllocationOrder(const MachineFunction &MF) const {
195    return OrderFunc ? OrderFunc(MF) : makeArrayRef(begin(), getNumRegs());
196  }
197};
198
199/// TargetRegisterInfoDesc - Extra information, not in MCRegisterDesc, about
200/// registers. These are used by codegen, not by MC.
201struct TargetRegisterInfoDesc {
202  unsigned CostPerUse;          // Extra cost of instructions using register.
203  bool inAllocatableClass;      // Register belongs to an allocatable regclass.
204};
205
206/// Each TargetRegisterClass has a per register weight, and weight
207/// limit which must be less than the limits of its pressure sets.
208struct RegClassWeight {
209  unsigned RegWeight;
210  unsigned WeightLimit;
211};
212
213/// TargetRegisterInfo base class - We assume that the target defines a static
214/// array of TargetRegisterDesc objects that represent all of the machine
215/// registers that the target has.  As such, we simply have to track a pointer
216/// to this array so that we can turn register number into a register
217/// descriptor.
218///
219class TargetRegisterInfo : public MCRegisterInfo {
220public:
221  typedef const TargetRegisterClass * const * regclass_iterator;
222private:
223  const TargetRegisterInfoDesc *InfoDesc;     // Extra desc array for codegen
224  const char *const *SubRegIndexNames;        // Names of subreg indexes.
225  // Pointer to array of lane masks, one per sub-reg index.
226  const unsigned *SubRegIndexLaneMasks;
227
228  regclass_iterator RegClassBegin, RegClassEnd;   // List of regclasses
229
230protected:
231  TargetRegisterInfo(const TargetRegisterInfoDesc *ID,
232                     regclass_iterator RegClassBegin,
233                     regclass_iterator RegClassEnd,
234                     const char *const *SRINames,
235                     const unsigned *SRILaneMasks);
236  virtual ~TargetRegisterInfo();
237public:
238
239  // Register numbers can represent physical registers, virtual registers, and
240  // sometimes stack slots. The unsigned values are divided into these ranges:
241  //
242  //   0           Not a register, can be used as a sentinel.
243  //   [1;2^30)    Physical registers assigned by TableGen.
244  //   [2^30;2^31) Stack slots. (Rarely used.)
245  //   [2^31;2^32) Virtual registers assigned by MachineRegisterInfo.
246  //
247  // Further sentinels can be allocated from the small negative integers.
248  // DenseMapInfo<unsigned> uses -1u and -2u.
249
250  /// isStackSlot - Sometimes it is useful the be able to store a non-negative
251  /// frame index in a variable that normally holds a register. isStackSlot()
252  /// returns true if Reg is in the range used for stack slots.
253  ///
254  /// Note that isVirtualRegister() and isPhysicalRegister() cannot handle stack
255  /// slots, so if a variable may contains a stack slot, always check
256  /// isStackSlot() first.
257  ///
258  static bool isStackSlot(unsigned Reg) {
259    return int(Reg) >= (1 << 30);
260  }
261
262  /// stackSlot2Index - Compute the frame index from a register value
263  /// representing a stack slot.
264  static int stackSlot2Index(unsigned Reg) {
265    assert(isStackSlot(Reg) && "Not a stack slot");
266    return int(Reg - (1u << 30));
267  }
268
269  /// index2StackSlot - Convert a non-negative frame index to a stack slot
270  /// register value.
271  static unsigned index2StackSlot(int FI) {
272    assert(FI >= 0 && "Cannot hold a negative frame index.");
273    return FI + (1u << 30);
274  }
275
276  /// isPhysicalRegister - Return true if the specified register number is in
277  /// the physical register namespace.
278  static bool isPhysicalRegister(unsigned Reg) {
279    assert(!isStackSlot(Reg) && "Not a register! Check isStackSlot() first.");
280    return int(Reg) > 0;
281  }
282
283  /// isVirtualRegister - Return true if the specified register number is in
284  /// the virtual register namespace.
285  static bool isVirtualRegister(unsigned Reg) {
286    assert(!isStackSlot(Reg) && "Not a register! Check isStackSlot() first.");
287    return int(Reg) < 0;
288  }
289
290  /// virtReg2Index - Convert a virtual register number to a 0-based index.
291  /// The first virtual register in a function will get the index 0.
292  static unsigned virtReg2Index(unsigned Reg) {
293    assert(isVirtualRegister(Reg) && "Not a virtual register");
294    return Reg & ~(1u << 31);
295  }
296
297  /// index2VirtReg - Convert a 0-based index to a virtual register number.
298  /// This is the inverse operation of VirtReg2IndexFunctor below.
299  static unsigned index2VirtReg(unsigned Index) {
300    return Index | (1u << 31);
301  }
302
303  /// getMinimalPhysRegClass - Returns the Register Class of a physical
304  /// register of the given type, picking the most sub register class of
305  /// the right type that contains this physreg.
306  const TargetRegisterClass *
307    getMinimalPhysRegClass(unsigned Reg, EVT VT = MVT::Other) const;
308
309  /// getAllocatableClass - Return the maximal subclass of the given register
310  /// class that is alloctable, or NULL.
311  const TargetRegisterClass *
312    getAllocatableClass(const TargetRegisterClass *RC) const;
313
314  /// getAllocatableSet - Returns a bitset indexed by register number
315  /// indicating if a register is allocatable or not. If a register class is
316  /// specified, returns the subset for the class.
317  BitVector getAllocatableSet(const MachineFunction &MF,
318                              const TargetRegisterClass *RC = NULL) const;
319
320  /// getCostPerUse - Return the additional cost of using this register instead
321  /// of other registers in its class.
322  unsigned getCostPerUse(unsigned RegNo) const {
323    return InfoDesc[RegNo].CostPerUse;
324  }
325
326  /// isInAllocatableClass - Return true if the register is in the allocation
327  /// of any register class.
328  bool isInAllocatableClass(unsigned RegNo) const {
329    return InfoDesc[RegNo].inAllocatableClass;
330  }
331
332  /// getSubRegIndexName - Return the human-readable symbolic target-specific
333  /// name for the specified SubRegIndex.
334  const char *getSubRegIndexName(unsigned SubIdx) const {
335    assert(SubIdx && SubIdx < getNumSubRegIndices() &&
336           "This is not a subregister index");
337    return SubRegIndexNames[SubIdx-1];
338  }
339
340  /// getSubRegIndexLaneMask - Return a bitmask representing the parts of a
341  /// register that are covered by SubIdx.
342  ///
343  /// Lane masks for sub-register indices are similar to register units for
344  /// physical registers. The individual bits in a lane mask can't be assigned
345  /// any specific meaning. They can be used to check if two sub-register
346  /// indices overlap.
347  ///
348  /// If the target has a register such that:
349  ///
350  ///   getSubReg(Reg, A) overlaps getSubReg(Reg, B)
351  ///
352  /// then:
353  ///
354  ///   getSubRegIndexLaneMask(A) & getSubRegIndexLaneMask(B) != 0
355  ///
356  /// The converse is not necessarily true. If two lane masks have a common
357  /// bit, the corresponding sub-registers may not overlap, but it can be
358  /// assumed that they usually will.
359  unsigned getSubRegIndexLaneMask(unsigned SubIdx) const {
360    // SubIdx == 0 is allowed, it has the lane mask ~0u.
361    assert(SubIdx < getNumSubRegIndices() && "This is not a subregister index");
362    return SubRegIndexLaneMasks[SubIdx];
363  }
364
365  /// regsOverlap - Returns true if the two registers are equal or alias each
366  /// other. The registers may be virtual register.
367  bool regsOverlap(unsigned regA, unsigned regB) const {
368    if (regA == regB) return true;
369    if (isVirtualRegister(regA) || isVirtualRegister(regB))
370      return false;
371
372    // Regunits are numerically ordered. Find a common unit.
373    MCRegUnitIterator RUA(regA, this);
374    MCRegUnitIterator RUB(regB, this);
375    do {
376      if (*RUA == *RUB) return true;
377      if (*RUA < *RUB) ++RUA;
378      else             ++RUB;
379    } while (RUA.isValid() && RUB.isValid());
380    return false;
381  }
382
383  /// hasRegUnit - Returns true if Reg contains RegUnit.
384  bool hasRegUnit(unsigned Reg, unsigned RegUnit) const {
385    for (MCRegUnitIterator Units(Reg, this); Units.isValid(); ++Units)
386      if (*Units == RegUnit)
387        return true;
388    return false;
389  }
390
391  /// isSubRegister - Returns true if regB is a sub-register of regA.
392  ///
393  bool isSubRegister(unsigned regA, unsigned regB) const {
394    return isSuperRegister(regB, regA);
395  }
396
397  /// isSuperRegister - Returns true if regB is a super-register of regA.
398  ///
399  bool isSuperRegister(unsigned RegA, unsigned RegB) const {
400    for (MCSuperRegIterator I(RegA, this); I.isValid(); ++I)
401      if (*I == RegB)
402        return true;
403    return false;
404  }
405
406  /// getCalleeSavedRegs - Return a null-terminated list of all of the
407  /// callee saved registers on this target. The register should be in the
408  /// order of desired callee-save stack frame offset. The first register is
409  /// closest to the incoming stack pointer if stack grows down, and vice versa.
410  ///
411  virtual const MCPhysReg* getCalleeSavedRegs(const MachineFunction *MF = 0)
412                                                                      const = 0;
413
414  /// getCallPreservedMask - Return a mask of call-preserved registers for the
415  /// given calling convention on the current sub-target.  The mask should
416  /// include all call-preserved aliases.  This is used by the register
417  /// allocator to determine which registers can be live across a call.
418  ///
419  /// The mask is an array containing (TRI::getNumRegs()+31)/32 entries.
420  /// A set bit indicates that all bits of the corresponding register are
421  /// preserved across the function call.  The bit mask is expected to be
422  /// sub-register complete, i.e. if A is preserved, so are all its
423  /// sub-registers.
424  ///
425  /// Bits are numbered from the LSB, so the bit for physical register Reg can
426  /// be found as (Mask[Reg / 32] >> Reg % 32) & 1.
427  ///
428  /// A NULL pointer means that no register mask will be used, and call
429  /// instructions should use implicit-def operands to indicate call clobbered
430  /// registers.
431  ///
432  virtual const uint32_t *getCallPreservedMask(CallingConv::ID) const {
433    // The default mask clobbers everything.  All targets should override.
434    return 0;
435  }
436
437  /// getReservedRegs - Returns a bitset indexed by physical register number
438  /// indicating if a register is a special register that has particular uses
439  /// and should be considered unavailable at all times, e.g. SP, RA. This is
440  /// used by register scavenger to determine what registers are free.
441  virtual BitVector getReservedRegs(const MachineFunction &MF) const = 0;
442
443  /// getMatchingSuperReg - Return a super-register of the specified register
444  /// Reg so its sub-register of index SubIdx is Reg.
445  unsigned getMatchingSuperReg(unsigned Reg, unsigned SubIdx,
446                               const TargetRegisterClass *RC) const {
447    return MCRegisterInfo::getMatchingSuperReg(Reg, SubIdx, RC->MC);
448  }
449
450  /// getMatchingSuperRegClass - Return a subclass of the specified register
451  /// class A so that each register in it has a sub-register of the
452  /// specified sub-register index which is in the specified register class B.
453  ///
454  /// TableGen will synthesize missing A sub-classes.
455  virtual const TargetRegisterClass *
456  getMatchingSuperRegClass(const TargetRegisterClass *A,
457                           const TargetRegisterClass *B, unsigned Idx) const;
458
459  /// getSubClassWithSubReg - Returns the largest legal sub-class of RC that
460  /// supports the sub-register index Idx.
461  /// If no such sub-class exists, return NULL.
462  /// If all registers in RC already have an Idx sub-register, return RC.
463  ///
464  /// TableGen generates a version of this function that is good enough in most
465  /// cases.  Targets can override if they have constraints that TableGen
466  /// doesn't understand.  For example, the x86 sub_8bit sub-register index is
467  /// supported by the full GR32 register class in 64-bit mode, but only by the
468  /// GR32_ABCD regiister class in 32-bit mode.
469  ///
470  /// TableGen will synthesize missing RC sub-classes.
471  virtual const TargetRegisterClass *
472  getSubClassWithSubReg(const TargetRegisterClass *RC, unsigned Idx) const {
473    assert(Idx == 0 && "Target has no sub-registers");
474    return RC;
475  }
476
477  /// composeSubRegIndices - Return the subregister index you get from composing
478  /// two subregister indices.
479  ///
480  /// The special null sub-register index composes as the identity.
481  ///
482  /// If R:a:b is the same register as R:c, then composeSubRegIndices(a, b)
483  /// returns c. Note that composeSubRegIndices does not tell you about illegal
484  /// compositions. If R does not have a subreg a, or R:a does not have a subreg
485  /// b, composeSubRegIndices doesn't tell you.
486  ///
487  /// The ARM register Q0 has two D subregs dsub_0:D0 and dsub_1:D1. It also has
488  /// ssub_0:S0 - ssub_3:S3 subregs.
489  /// If you compose subreg indices dsub_1, ssub_0 you get ssub_2.
490  ///
491  unsigned composeSubRegIndices(unsigned a, unsigned b) const {
492    if (!a) return b;
493    if (!b) return a;
494    return composeSubRegIndicesImpl(a, b);
495  }
496
497protected:
498  /// Overridden by TableGen in targets that have sub-registers.
499  virtual unsigned composeSubRegIndicesImpl(unsigned, unsigned) const {
500    llvm_unreachable("Target has no sub-registers");
501  }
502
503public:
504  /// getCommonSuperRegClass - Find a common super-register class if it exists.
505  ///
506  /// Find a register class, SuperRC and two sub-register indices, PreA and
507  /// PreB, such that:
508  ///
509  ///   1. PreA + SubA == PreB + SubB  (using composeSubRegIndices()), and
510  ///
511  ///   2. For all Reg in SuperRC: Reg:PreA in RCA and Reg:PreB in RCB, and
512  ///
513  ///   3. SuperRC->getSize() >= max(RCA->getSize(), RCB->getSize()).
514  ///
515  /// SuperRC will be chosen such that no super-class of SuperRC satisfies the
516  /// requirements, and there is no register class with a smaller spill size
517  /// that satisfies the requirements.
518  ///
519  /// SubA and SubB must not be 0. Use getMatchingSuperRegClass() instead.
520  ///
521  /// Either of the PreA and PreB sub-register indices may be returned as 0. In
522  /// that case, the returned register class will be a sub-class of the
523  /// corresponding argument register class.
524  ///
525  /// The function returns NULL if no register class can be found.
526  ///
527  const TargetRegisterClass*
528  getCommonSuperRegClass(const TargetRegisterClass *RCA, unsigned SubA,
529                         const TargetRegisterClass *RCB, unsigned SubB,
530                         unsigned &PreA, unsigned &PreB) const;
531
532  //===--------------------------------------------------------------------===//
533  // Register Class Information
534  //
535
536  /// Register class iterators
537  ///
538  regclass_iterator regclass_begin() const { return RegClassBegin; }
539  regclass_iterator regclass_end() const { return RegClassEnd; }
540
541  unsigned getNumRegClasses() const {
542    return (unsigned)(regclass_end()-regclass_begin());
543  }
544
545  /// getRegClass - Returns the register class associated with the enumeration
546  /// value.  See class MCOperandInfo.
547  const TargetRegisterClass *getRegClass(unsigned i) const {
548    assert(i < getNumRegClasses() && "Register Class ID out of range");
549    return RegClassBegin[i];
550  }
551
552  /// getCommonSubClass - find the largest common subclass of A and B. Return
553  /// NULL if there is no common subclass.
554  const TargetRegisterClass *
555  getCommonSubClass(const TargetRegisterClass *A,
556                    const TargetRegisterClass *B) const;
557
558  /// getPointerRegClass - Returns a TargetRegisterClass used for pointer
559  /// values.  If a target supports multiple different pointer register classes,
560  /// kind specifies which one is indicated.
561  virtual const TargetRegisterClass *
562  getPointerRegClass(const MachineFunction &MF, unsigned Kind=0) const {
563    llvm_unreachable("Target didn't implement getPointerRegClass!");
564  }
565
566  /// getCrossCopyRegClass - Returns a legal register class to copy a register
567  /// in the specified class to or from. If it is possible to copy the register
568  /// directly without using a cross register class copy, return the specified
569  /// RC. Returns NULL if it is not possible to copy between a two registers of
570  /// the specified class.
571  virtual const TargetRegisterClass *
572  getCrossCopyRegClass(const TargetRegisterClass *RC) const {
573    return RC;
574  }
575
576  /// getLargestLegalSuperClass - Returns the largest super class of RC that is
577  /// legal to use in the current sub-target and has the same spill size.
578  /// The returned register class can be used to create virtual registers which
579  /// means that all its registers can be copied and spilled.
580  virtual const TargetRegisterClass*
581  getLargestLegalSuperClass(const TargetRegisterClass *RC) const {
582    /// The default implementation is very conservative and doesn't allow the
583    /// register allocator to inflate register classes.
584    return RC;
585  }
586
587  /// getRegPressureLimit - Return the register pressure "high water mark" for
588  /// the specific register class. The scheduler is in high register pressure
589  /// mode (for the specific register class) if it goes over the limit.
590  ///
591  /// Note: this is the old register pressure model that relies on a manually
592  /// specified representative register class per value type.
593  virtual unsigned getRegPressureLimit(const TargetRegisterClass *RC,
594                                       MachineFunction &MF) const {
595    return 0;
596  }
597
598  /// Get the weight in units of pressure for this register class.
599  virtual const RegClassWeight &getRegClassWeight(
600    const TargetRegisterClass *RC) const = 0;
601
602  /// Get the weight in units of pressure for this register unit.
603  virtual unsigned getRegUnitWeight(unsigned RegUnit) const = 0;
604
605  /// Get the number of dimensions of register pressure.
606  virtual unsigned getNumRegPressureSets() const = 0;
607
608  /// Get the name of this register unit pressure set.
609  virtual const char *getRegPressureSetName(unsigned Idx) const = 0;
610
611  /// Get the register unit pressure limit for this dimension.
612  /// This limit must be adjusted dynamically for reserved registers.
613  virtual unsigned getRegPressureSetLimit(unsigned Idx) const = 0;
614
615  /// Get the dimensions of register pressure impacted by this register class.
616  /// Returns a -1 terminated array of pressure set IDs.
617  virtual const int *getRegClassPressureSets(
618    const TargetRegisterClass *RC) const = 0;
619
620  /// Get the dimensions of register pressure impacted by this register unit.
621  /// Returns a -1 terminated array of pressure set IDs.
622  virtual const int *getRegUnitPressureSets(unsigned RegUnit) const = 0;
623
624  /// Get a list of 'hint' registers that the register allocator should try
625  /// first when allocating a physical register for the virtual register
626  /// VirtReg. These registers are effectively moved to the front of the
627  /// allocation order.
628  ///
629  /// The Order argument is the allocation order for VirtReg's register class
630  /// as returned from RegisterClassInfo::getOrder(). The hint registers must
631  /// come from Order, and they must not be reserved.
632  ///
633  /// The default implementation of this function can resolve
634  /// target-independent hints provided to MRI::setRegAllocationHint with
635  /// HintType == 0. Targets that override this function should defer to the
636  /// default implementation if they have no reason to change the allocation
637  /// order for VirtReg. There may be target-independent hints.
638  virtual void getRegAllocationHints(unsigned VirtReg,
639                                     ArrayRef<MCPhysReg> Order,
640                                     SmallVectorImpl<MCPhysReg> &Hints,
641                                     const MachineFunction &MF,
642                                     const VirtRegMap *VRM = 0) const;
643
644  /// getRawAllocationOrder - Returns the register allocation order for a
645  /// specified register class with a target-dependent hint. The returned list
646  /// may contain reserved registers that cannot be allocated.
647  ///
648  /// Register allocators need only call this function to resolve
649  /// target-dependent hints, but it should work without hinting as well.
650  virtual ArrayRef<MCPhysReg>
651  getRawAllocationOrder(const TargetRegisterClass *RC,
652                        unsigned HintType, unsigned HintReg,
653                        const MachineFunction &MF) const {
654    return RC->getRawAllocationOrder(MF);
655  }
656
657  /// ResolveRegAllocHint - Resolves the specified register allocation hint
658  /// to a physical register. Returns the physical register if it is successful.
659  virtual unsigned ResolveRegAllocHint(unsigned Type, unsigned Reg,
660                                       const MachineFunction &MF) const {
661    if (Type == 0 && Reg && isPhysicalRegister(Reg))
662      return Reg;
663    return 0;
664  }
665
666  /// avoidWriteAfterWrite - Return true if the register allocator should avoid
667  /// writing a register from RC in two consecutive instructions.
668  /// This can avoid pipeline stalls on certain architectures.
669  /// It does cause increased register pressure, though.
670  virtual bool avoidWriteAfterWrite(const TargetRegisterClass *RC) const {
671    return false;
672  }
673
674  /// UpdateRegAllocHint - A callback to allow target a chance to update
675  /// register allocation hints when a register is "changed" (e.g. coalesced)
676  /// to another register. e.g. On ARM, some virtual registers should target
677  /// register pairs, if one of pair is coalesced to another register, the
678  /// allocation hint of the other half of the pair should be changed to point
679  /// to the new register.
680  virtual void UpdateRegAllocHint(unsigned Reg, unsigned NewReg,
681                                  MachineFunction &MF) const {
682    // Do nothing.
683  }
684
685  /// requiresRegisterScavenging - returns true if the target requires (and can
686  /// make use of) the register scavenger.
687  virtual bool requiresRegisterScavenging(const MachineFunction &MF) const {
688    return false;
689  }
690
691  /// useFPForScavengingIndex - returns true if the target wants to use
692  /// frame pointer based accesses to spill to the scavenger emergency spill
693  /// slot.
694  virtual bool useFPForScavengingIndex(const MachineFunction &MF) const {
695    return true;
696  }
697
698  /// requiresFrameIndexScavenging - returns true if the target requires post
699  /// PEI scavenging of registers for materializing frame index constants.
700  virtual bool requiresFrameIndexScavenging(const MachineFunction &MF) const {
701    return false;
702  }
703
704  /// requiresVirtualBaseRegisters - Returns true if the target wants the
705  /// LocalStackAllocation pass to be run and virtual base registers
706  /// used for more efficient stack access.
707  virtual bool requiresVirtualBaseRegisters(const MachineFunction &MF) const {
708    return false;
709  }
710
711  /// hasReservedSpillSlot - Return true if target has reserved a spill slot in
712  /// the stack frame of the given function for the specified register. e.g. On
713  /// x86, if the frame register is required, the first fixed stack object is
714  /// reserved as its spill slot. This tells PEI not to create a new stack frame
715  /// object for the given register. It should be called only after
716  /// processFunctionBeforeCalleeSavedScan().
717  virtual bool hasReservedSpillSlot(const MachineFunction &MF, unsigned Reg,
718                                    int &FrameIdx) const {
719    return false;
720  }
721
722  /// trackLivenessAfterRegAlloc - returns true if the live-ins should be tracked
723  /// after register allocation.
724  virtual bool trackLivenessAfterRegAlloc(const MachineFunction &MF) const {
725    return false;
726  }
727
728  /// needsStackRealignment - true if storage within the function requires the
729  /// stack pointer to be aligned more than the normal calling convention calls
730  /// for.
731  virtual bool needsStackRealignment(const MachineFunction &MF) const {
732    return false;
733  }
734
735  /// getFrameIndexInstrOffset - Get the offset from the referenced frame
736  /// index in the instruction, if there is one.
737  virtual int64_t getFrameIndexInstrOffset(const MachineInstr *MI,
738                                           int Idx) const {
739    return 0;
740  }
741
742  /// needsFrameBaseReg - Returns true if the instruction's frame index
743  /// reference would be better served by a base register other than FP
744  /// or SP. Used by LocalStackFrameAllocation to determine which frame index
745  /// references it should create new base registers for.
746  virtual bool needsFrameBaseReg(MachineInstr *MI, int64_t Offset) const {
747    return false;
748  }
749
750  /// materializeFrameBaseRegister - Insert defining instruction(s) for
751  /// BaseReg to be a pointer to FrameIdx before insertion point I.
752  virtual void materializeFrameBaseRegister(MachineBasicBlock *MBB,
753                                            unsigned BaseReg, int FrameIdx,
754                                            int64_t Offset) const {
755    llvm_unreachable("materializeFrameBaseRegister does not exist on this "
756                     "target");
757  }
758
759  /// resolveFrameIndex - Resolve a frame index operand of an instruction
760  /// to reference the indicated base register plus offset instead.
761  virtual void resolveFrameIndex(MachineBasicBlock::iterator I,
762                                 unsigned BaseReg, int64_t Offset) const {
763    llvm_unreachable("resolveFrameIndex does not exist on this target");
764  }
765
766  /// isFrameOffsetLegal - Determine whether a given offset immediate is
767  /// encodable to resolve a frame index.
768  virtual bool isFrameOffsetLegal(const MachineInstr *MI,
769                                  int64_t Offset) const {
770    llvm_unreachable("isFrameOffsetLegal does not exist on this target");
771  }
772
773  /// eliminateCallFramePseudoInstr - This method is called during prolog/epilog
774  /// code insertion to eliminate call frame setup and destroy pseudo
775  /// instructions (but only if the Target is using them).  It is responsible
776  /// for eliminating these instructions, replacing them with concrete
777  /// instructions.  This method need only be implemented if using call frame
778  /// setup/destroy pseudo instructions.
779  ///
780  virtual void
781  eliminateCallFramePseudoInstr(MachineFunction &MF,
782                                MachineBasicBlock &MBB,
783                                MachineBasicBlock::iterator MI) const {
784    llvm_unreachable("Call Frame Pseudo Instructions do not exist on this "
785                     "target!");
786  }
787
788
789  /// saveScavengerRegister - Spill the register so it can be used by the
790  /// register scavenger. Return true if the register was spilled, false
791  /// otherwise. If this function does not spill the register, the scavenger
792  /// will instead spill it to the emergency spill slot.
793  ///
794  virtual bool saveScavengerRegister(MachineBasicBlock &MBB,
795                                     MachineBasicBlock::iterator I,
796                                     MachineBasicBlock::iterator &UseMI,
797                                     const TargetRegisterClass *RC,
798                                     unsigned Reg) const {
799    return false;
800  }
801
802  /// eliminateFrameIndex - This method must be overriden to eliminate abstract
803  /// frame indices from instructions which may use them.  The instruction
804  /// referenced by the iterator contains an MO_FrameIndex operand which must be
805  /// eliminated by this method.  This method may modify or replace the
806  /// specified instruction, as long as it keeps the iterator pointing at the
807  /// finished product. SPAdj is the SP adjustment due to call frame setup
808  /// instruction.
809  virtual void eliminateFrameIndex(MachineBasicBlock::iterator MI,
810                                   int SPAdj, RegScavenger *RS=NULL) const = 0;
811
812  //===--------------------------------------------------------------------===//
813  /// Debug information queries.
814
815  /// getFrameRegister - This method should return the register used as a base
816  /// for values allocated in the current stack frame.
817  virtual unsigned getFrameRegister(const MachineFunction &MF) const = 0;
818
819  /// getCompactUnwindRegNum - This function maps the register to the number for
820  /// compact unwind encoding. Return -1 if the register isn't valid.
821  virtual int getCompactUnwindRegNum(unsigned, bool) const {
822    return -1;
823  }
824};
825
826
827//===----------------------------------------------------------------------===//
828//                           SuperRegClassIterator
829//===----------------------------------------------------------------------===//
830//
831// Iterate over the possible super-registers for a given register class. The
832// iterator will visit a list of pairs (Idx, Mask) corresponding to the
833// possible classes of super-registers.
834//
835// Each bit mask will have at least one set bit, and each set bit in Mask
836// corresponds to a SuperRC such that:
837//
838//   For all Reg in SuperRC: Reg:Idx is in RC.
839//
840// The iterator can include (O, RC->getSubClassMask()) as the first entry which
841// also satisfies the above requirement, assuming Reg:0 == Reg.
842//
843class SuperRegClassIterator {
844  const unsigned RCMaskWords;
845  unsigned SubReg;
846  const uint16_t *Idx;
847  const uint32_t *Mask;
848
849public:
850  /// Create a SuperRegClassIterator that visits all the super-register classes
851  /// of RC. When IncludeSelf is set, also include the (0, sub-classes) entry.
852  SuperRegClassIterator(const TargetRegisterClass *RC,
853                        const TargetRegisterInfo *TRI,
854                        bool IncludeSelf = false)
855    : RCMaskWords((TRI->getNumRegClasses() + 31) / 32),
856      SubReg(0),
857      Idx(RC->getSuperRegIndices()),
858      Mask(RC->getSubClassMask()) {
859    if (!IncludeSelf)
860      ++*this;
861  }
862
863  /// Returns true if this iterator is still pointing at a valid entry.
864  bool isValid() const { return Idx; }
865
866  /// Returns the current sub-register index.
867  unsigned getSubReg() const { return SubReg; }
868
869  /// Returns the bit mask if register classes that getSubReg() projects into
870  /// RC.
871  const uint32_t *getMask() const { return Mask; }
872
873  /// Advance iterator to the next entry.
874  void operator++() {
875    assert(isValid() && "Cannot move iterator past end.");
876    Mask += RCMaskWords;
877    SubReg = *Idx++;
878    if (!SubReg)
879      Idx = 0;
880  }
881};
882
883// This is useful when building IndexedMaps keyed on virtual registers
884struct VirtReg2IndexFunctor : public std::unary_function<unsigned, unsigned> {
885  unsigned operator()(unsigned Reg) const {
886    return TargetRegisterInfo::virtReg2Index(Reg);
887  }
888};
889
890/// PrintReg - Helper class for printing registers on a raw_ostream.
891/// Prints virtual and physical registers with or without a TRI instance.
892///
893/// The format is:
894///   %noreg          - NoRegister
895///   %vreg5          - a virtual register.
896///   %vreg5:sub_8bit - a virtual register with sub-register index (with TRI).
897///   %EAX            - a physical register
898///   %physreg17      - a physical register when no TRI instance given.
899///
900/// Usage: OS << PrintReg(Reg, TRI) << '\n';
901///
902class PrintReg {
903  const TargetRegisterInfo *TRI;
904  unsigned Reg;
905  unsigned SubIdx;
906public:
907  explicit PrintReg(unsigned reg, const TargetRegisterInfo *tri = 0,
908                    unsigned subidx = 0)
909    : TRI(tri), Reg(reg), SubIdx(subidx) {}
910  void print(raw_ostream&) const;
911};
912
913static inline raw_ostream &operator<<(raw_ostream &OS, const PrintReg &PR) {
914  PR.print(OS);
915  return OS;
916}
917
918/// PrintRegUnit - Helper class for printing register units on a raw_ostream.
919///
920/// Register units are named after their root registers:
921///
922///   AL      - Single root.
923///   FP0~ST7 - Dual roots.
924///
925/// Usage: OS << PrintRegUnit(Unit, TRI) << '\n';
926///
927class PrintRegUnit {
928  const TargetRegisterInfo *TRI;
929  unsigned Unit;
930public:
931  PrintRegUnit(unsigned unit, const TargetRegisterInfo *tri)
932    : TRI(tri), Unit(unit) {}
933  void print(raw_ostream&) const;
934};
935
936static inline raw_ostream &operator<<(raw_ostream &OS, const PrintRegUnit &PR) {
937  PR.print(OS);
938  return OS;
939}
940
941} // End llvm namespace
942
943#endif
944