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