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