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