MIR Serialization: Serialize the register mask machine operands.
[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   /// Return all the call-preserved register masks defined for this target.
473   virtual ArrayRef<const uint32_t *> getRegMasks() const = 0;
474   virtual ArrayRef<const char *> getRegMaskNames() const = 0;
475
476   /// getReservedRegs - Returns a bitset indexed by physical register number
477   /// indicating if a register is a special register that has particular uses
478   /// and should be considered unavailable at all times, e.g. SP, RA. This is
479   /// used by register scavenger to determine what registers are free.
480   virtual BitVector getReservedRegs(const MachineFunction &MF) const = 0;
481
482   /// Prior to adding the live-out mask to a stackmap or patchpoint
483   /// instruction, provide the target the opportunity to adjust it (mainly to
484   /// remove pseudo-registers that should be ignored).
485   virtual void adjustStackMapLiveOutMask(uint32_t *Mask) const { }
486
487   /// getMatchingSuperReg - Return a super-register of the specified register
488   /// Reg so its sub-register of index SubIdx is Reg.
489   unsigned getMatchingSuperReg(unsigned Reg, unsigned SubIdx,
490                                const TargetRegisterClass *RC) const {
491     return MCRegisterInfo::getMatchingSuperReg(Reg, SubIdx, RC->MC);
492   }
493
494   /// getMatchingSuperRegClass - Return a subclass of the specified register
495   /// class A so that each register in it has a sub-register of the
496   /// specified sub-register index which is in the specified register class B.
497   ///
498   /// TableGen will synthesize missing A sub-classes.
499   virtual const TargetRegisterClass *
500   getMatchingSuperRegClass(const TargetRegisterClass *A,
501                            const TargetRegisterClass *B, unsigned Idx) const;
502
503   /// getSubClassWithSubReg - Returns the largest legal sub-class of RC that
504   /// supports the sub-register index Idx.
505   /// If no such sub-class exists, return NULL.
506   /// If all registers in RC already have an Idx sub-register, return RC.
507   ///
508   /// TableGen generates a version of this function that is good enough in most
509   /// cases.  Targets can override if they have constraints that TableGen
510   /// doesn't understand.  For example, the x86 sub_8bit sub-register index is
511   /// supported by the full GR32 register class in 64-bit mode, but only by the
512   /// GR32_ABCD regiister class in 32-bit mode.
513   ///
514   /// TableGen will synthesize missing RC sub-classes.
515   virtual const TargetRegisterClass *
516   getSubClassWithSubReg(const TargetRegisterClass *RC, unsigned Idx) const {
517     assert(Idx == 0 && "Target has no sub-registers");
518     return RC;
519   }
520
521   /// composeSubRegIndices - Return the subregister index you get from composing
522   /// two subregister indices.
523   ///
524   /// The special null sub-register index composes as the identity.
525   ///
526   /// If R:a:b is the same register as R:c, then composeSubRegIndices(a, b)
527   /// returns c. Note that composeSubRegIndices does not tell you about illegal
528   /// compositions. If R does not have a subreg a, or R:a does not have a subreg
529   /// b, composeSubRegIndices doesn't tell you.
530   ///
531   /// The ARM register Q0 has two D subregs dsub_0:D0 and dsub_1:D1. It also has
532   /// ssub_0:S0 - ssub_3:S3 subregs.
533   /// If you compose subreg indices dsub_1, ssub_0 you get ssub_2.
534   ///
535   unsigned composeSubRegIndices(unsigned a, unsigned b) const {
536     if (!a) return b;
537     if (!b) return a;
538     return composeSubRegIndicesImpl(a, b);
539   }
540
541   /// Transforms a LaneMask computed for one subregister to the lanemask that
542   /// would have been computed when composing the subsubregisters with IdxA
543   /// first. @sa composeSubRegIndices()
544   unsigned composeSubRegIndexLaneMask(unsigned IdxA, unsigned LaneMask) const {
545     if (!IdxA)
546       return LaneMask;
547     return composeSubRegIndexLaneMaskImpl(IdxA, LaneMask);
548   }
549
550   /// Debugging helper: dump register in human readable form to dbgs() stream.
551   static void dumpReg(unsigned Reg, unsigned SubRegIndex = 0,
552                       const TargetRegisterInfo* TRI = nullptr);
553
554 protected:
555   /// Overridden by TableGen in targets that have sub-registers.
556   virtual unsigned composeSubRegIndicesImpl(unsigned, unsigned) const {
557     llvm_unreachable("Target has no sub-registers");
558   }
559
560   /// Overridden by TableGen in targets that have sub-registers.
561   virtual unsigned
562   composeSubRegIndexLaneMaskImpl(unsigned, unsigned) const {
563     llvm_unreachable("Target has no sub-registers");
564   }
565
566 public:
567   /// getCommonSuperRegClass - Find a common super-register class if it exists.
568   ///
569   /// Find a register class, SuperRC and two sub-register indices, PreA and
570   /// PreB, such that:
571   ///
572   ///   1. PreA + SubA == PreB + SubB  (using composeSubRegIndices()), and
573   ///
574   ///   2. For all Reg in SuperRC: Reg:PreA in RCA and Reg:PreB in RCB, and
575   ///
576   ///   3. SuperRC->getSize() >= max(RCA->getSize(), RCB->getSize()).
577   ///
578   /// SuperRC will be chosen such that no super-class of SuperRC satisfies the
579   /// requirements, and there is no register class with a smaller spill size
580   /// that satisfies the requirements.
581   ///
582   /// SubA and SubB must not be 0. Use getMatchingSuperRegClass() instead.
583   ///
584   /// Either of the PreA and PreB sub-register indices may be returned as 0. In
585   /// that case, the returned register class will be a sub-class of the
586   /// corresponding argument register class.
587   ///
588   /// The function returns NULL if no register class can be found.
589   ///
590   const TargetRegisterClass*
591   getCommonSuperRegClass(const TargetRegisterClass *RCA, unsigned SubA,
592                          const TargetRegisterClass *RCB, unsigned SubB,
593                          unsigned &PreA, unsigned &PreB) const;
594
595   //===--------------------------------------------------------------------===//
596   // Register Class Information
597   //
598
599   /// Register class iterators
600   ///
601   regclass_iterator regclass_begin() const { return RegClassBegin; }
602   regclass_iterator regclass_end() const { return RegClassEnd; }
603
604   unsigned getNumRegClasses() const {
605     return (unsigned)(regclass_end()-regclass_begin());
606   }
607
608   /// getRegClass - Returns the register class associated with the enumeration
609   /// value.  See class MCOperandInfo.
610   const TargetRegisterClass *getRegClass(unsigned i) const {
611     assert(i < getNumRegClasses() && "Register Class ID out of range");
612     return RegClassBegin[i];
613   }
614
615   /// getRegClassName - Returns the name of the register class.
616   const char *getRegClassName(const TargetRegisterClass *Class) const {
617     return MCRegisterInfo::getRegClassName(Class->MC);
618   }
619
620   /// getCommonSubClass - find the largest common subclass of A and B. Return
621   /// NULL if there is no common subclass.
622   const TargetRegisterClass *
623   getCommonSubClass(const TargetRegisterClass *A,
624                     const TargetRegisterClass *B) const;
625
626   /// getPointerRegClass - Returns a TargetRegisterClass used for pointer
627   /// values.  If a target supports multiple different pointer register classes,
628   /// kind specifies which one is indicated.
629   virtual const TargetRegisterClass *
630   getPointerRegClass(const MachineFunction &MF, unsigned Kind=0) const {
631     llvm_unreachable("Target didn't implement getPointerRegClass!");
632   }
633
634   /// getCrossCopyRegClass - Returns a legal register class to copy a register
635   /// in the specified class to or from. If it is possible to copy the register
636   /// directly without using a cross register class copy, return the specified
637   /// RC. Returns NULL if it is not possible to copy between a two registers of
638   /// the specified class.
639   virtual const TargetRegisterClass *
640   getCrossCopyRegClass(const TargetRegisterClass *RC) const {
641     return RC;
642   }
643
644   /// getLargestLegalSuperClass - Returns the largest super class of RC that is
645   /// legal to use in the current sub-target and has the same spill size.
646   /// The returned register class can be used to create virtual registers which
647   /// means that all its registers can be copied and spilled.
648   virtual const TargetRegisterClass *
649   getLargestLegalSuperClass(const TargetRegisterClass *RC,
650                             const MachineFunction &) const {
651     /// The default implementation is very conservative and doesn't allow the
652     /// register allocator to inflate register classes.
653     return RC;
654   }
655
656   /// getRegPressureLimit - Return the register pressure "high water mark" for
657   /// the specific register class. The scheduler is in high register pressure
658   /// mode (for the specific register class) if it goes over the limit.
659   ///
660   /// Note: this is the old register pressure model that relies on a manually
661   /// specified representative register class per value type.
662   virtual unsigned getRegPressureLimit(const TargetRegisterClass *RC,
663                                        MachineFunction &MF) const {
664     return 0;
665   }
666
667   /// Get the weight in units of pressure for this register class.
668   virtual const RegClassWeight &getRegClassWeight(
669     const TargetRegisterClass *RC) const = 0;
670
671   /// Get the weight in units of pressure for this register unit.
672   virtual unsigned getRegUnitWeight(unsigned RegUnit) const = 0;
673
674   /// Get the number of dimensions of register pressure.
675   virtual unsigned getNumRegPressureSets() const = 0;
676
677   /// Get the name of this register unit pressure set.
678   virtual const char *getRegPressureSetName(unsigned Idx) const = 0;
679
680   /// Get the register unit pressure limit for this dimension.
681   /// This limit must be adjusted dynamically for reserved registers.
682   virtual unsigned getRegPressureSetLimit(const MachineFunction &MF,
683                                           unsigned Idx) const = 0;
684
685   /// Get the dimensions of register pressure impacted by this register class.
686   /// Returns a -1 terminated array of pressure set IDs.
687   virtual const int *getRegClassPressureSets(
688     const TargetRegisterClass *RC) const = 0;
689
690   /// Get the dimensions of register pressure impacted by this register unit.
691   /// Returns a -1 terminated array of pressure set IDs.
692   virtual const int *getRegUnitPressureSets(unsigned RegUnit) const = 0;
693
694   /// Get a list of 'hint' registers that the register allocator should try
695   /// first when allocating a physical register for the virtual register
696   /// VirtReg. These registers are effectively moved to the front of the
697   /// allocation order.
698   ///
699   /// The Order argument is the allocation order for VirtReg's register class
700   /// as returned from RegisterClassInfo::getOrder(). The hint registers must
701   /// come from Order, and they must not be reserved.
702   ///
703   /// The default implementation of this function can resolve
704   /// target-independent hints provided to MRI::setRegAllocationHint with
705   /// HintType == 0. Targets that override this function should defer to the
706   /// default implementation if they have no reason to change the allocation
707   /// order for VirtReg. There may be target-independent hints.
708   virtual void getRegAllocationHints(unsigned VirtReg,
709                                      ArrayRef<MCPhysReg> Order,
710                                      SmallVectorImpl<MCPhysReg> &Hints,
711                                      const MachineFunction &MF,
712                                      const VirtRegMap *VRM = nullptr) const;
713
714   /// updateRegAllocHint - A callback to allow target a chance to update
715   /// register allocation hints when a register is "changed" (e.g. coalesced)
716   /// to another register. e.g. On ARM, some virtual registers should target
717   /// register pairs, if one of pair is coalesced to another register, the
718   /// allocation hint of the other half of the pair should be changed to point
719   /// to the new register.
720   virtual void updateRegAllocHint(unsigned Reg, unsigned NewReg,
721                                   MachineFunction &MF) const {
722     // Do nothing.
723   }
724
725   /// Allow the target to reverse allocation order of local live ranges. This
726   /// will generally allocate shorter local live ranges first. For targets with
727   /// many registers, this could reduce regalloc compile time by a large
728   /// factor. It is disabled by default for three reasons:
729   /// (1) Top-down allocation is simpler and easier to debug for targets that
730   /// don't benefit from reversing the order.
731   /// (2) Bottom-up allocation could result in poor evicition decisions on some
732   /// targets affecting the performance of compiled code.
733   /// (3) Bottom-up allocation is no longer guaranteed to optimally color.
734   virtual bool reverseLocalAssignment() const { return false; }
735
736   /// Allow the target to override the cost of using a callee-saved register for
737   /// the first time. Default value of 0 means we will use a callee-saved
738   /// register if it is available.
739   virtual unsigned getCSRFirstUseCost() const { return 0; }
740
741   /// requiresRegisterScavenging - returns true if the target requires (and can
742   /// make use of) the register scavenger.
743   virtual bool requiresRegisterScavenging(const MachineFunction &MF) const {
744     return false;
745   }
746
747   /// useFPForScavengingIndex - returns true if the target wants to use
748   /// frame pointer based accesses to spill to the scavenger emergency spill
749   /// slot.
750   virtual bool useFPForScavengingIndex(const MachineFunction &MF) const {
751     return true;
752   }
753
754   /// requiresFrameIndexScavenging - returns true if the target requires post
755   /// PEI scavenging of registers for materializing frame index constants.
756   virtual bool requiresFrameIndexScavenging(const MachineFunction &MF) const {
757     return false;
758   }
759
760   /// requiresVirtualBaseRegisters - Returns true if the target wants the
761   /// LocalStackAllocation pass to be run and virtual base registers
762   /// used for more efficient stack access.
763   virtual bool requiresVirtualBaseRegisters(const MachineFunction &MF) const {
764     return false;
765   }
766
767   /// hasReservedSpillSlot - Return true if target has reserved a spill slot in
768   /// the stack frame of the given function for the specified register. e.g. On
769   /// x86, if the frame register is required, the first fixed stack object is
770   /// reserved as its spill slot. This tells PEI not to create a new stack frame
771   /// object for the given register. It should be called only after
772   /// processFunctionBeforeCalleeSavedScan().
773   virtual bool hasReservedSpillSlot(const MachineFunction &MF, unsigned Reg,
774                                     int &FrameIdx) const {
775     return false;
776   }
777
778   /// trackLivenessAfterRegAlloc - returns true if the live-ins should be tracked
779   /// after register allocation.
780   virtual bool trackLivenessAfterRegAlloc(const MachineFunction &MF) const {
781     return false;
782   }
783
784   /// needsStackRealignment - true if storage within the function requires the
785   /// stack pointer to be aligned more than the normal calling convention calls
786   /// for.
787   virtual bool needsStackRealignment(const MachineFunction &MF) const {
788     return false;
789   }
790
791   /// getFrameIndexInstrOffset - Get the offset from the referenced frame
792   /// index in the instruction, if there is one.
793   virtual int64_t getFrameIndexInstrOffset(const MachineInstr *MI,
794                                            int Idx) const {
795     return 0;
796   }
797
798   /// needsFrameBaseReg - Returns true if the instruction's frame index
799   /// reference would be better served by a base register other than FP
800   /// or SP. Used by LocalStackFrameAllocation to determine which frame index
801   /// references it should create new base registers for.
802   virtual bool needsFrameBaseReg(MachineInstr *MI, int64_t Offset) const {
803     return false;
804   }
805
806   /// materializeFrameBaseRegister - Insert defining instruction(s) for
807   /// BaseReg to be a pointer to FrameIdx before insertion point I.
808   virtual void materializeFrameBaseRegister(MachineBasicBlock *MBB,
809                                             unsigned BaseReg, int FrameIdx,
810                                             int64_t Offset) const {
811     llvm_unreachable("materializeFrameBaseRegister does not exist on this "
812                      "target");
813   }
814
815   /// resolveFrameIndex - Resolve a frame index operand of an instruction
816   /// to reference the indicated base register plus offset instead.
817   virtual void resolveFrameIndex(MachineInstr &MI, unsigned BaseReg,
818                                  int64_t Offset) const {
819     llvm_unreachable("resolveFrameIndex does not exist on this target");
820   }
821
822   /// isFrameOffsetLegal - Determine whether a given base register plus offset
823   /// immediate is encodable to resolve a frame index.
824   virtual bool isFrameOffsetLegal(const MachineInstr *MI, unsigned BaseReg,
825                                   int64_t Offset) const {
826     llvm_unreachable("isFrameOffsetLegal does not exist on this target");
827   }
828
829
830   /// saveScavengerRegister - Spill the register so it can be used by the
831   /// register scavenger. Return true if the register was spilled, false
832   /// otherwise. If this function does not spill the register, the scavenger
833   /// will instead spill it to the emergency spill slot.
834   ///
835   virtual bool saveScavengerRegister(MachineBasicBlock &MBB,
836                                      MachineBasicBlock::iterator I,
837                                      MachineBasicBlock::iterator &UseMI,
838                                      const TargetRegisterClass *RC,
839                                      unsigned Reg) const {
840     return false;
841   }
842
843   /// eliminateFrameIndex - This method must be overriden to eliminate abstract
844   /// frame indices from instructions which may use them.  The instruction
845   /// referenced by the iterator contains an MO_FrameIndex operand which must be
846   /// eliminated by this method.  This method may modify or replace the
847   /// specified instruction, as long as it keeps the iterator pointing at the
848   /// finished product.  SPAdj is the SP adjustment due to call frame setup
849   /// instruction.  FIOperandNum is the FI operand number.
850   virtual void eliminateFrameIndex(MachineBasicBlock::iterator MI,
851                                    int SPAdj, unsigned FIOperandNum,
852                                    RegScavenger *RS = nullptr) const = 0;
853
854   //===--------------------------------------------------------------------===//
855   /// Subtarget Hooks
856
857   /// \brief SrcRC and DstRC will be morphed into NewRC if this returns true.
858   virtual bool shouldCoalesce(MachineInstr *MI,
859                               const TargetRegisterClass *SrcRC,
860                               unsigned SubReg,
861                               const TargetRegisterClass *DstRC,
862                               unsigned DstSubReg,
863                               const TargetRegisterClass *NewRC) const
864   { return true; }
865
866   //===--------------------------------------------------------------------===//
867   /// Debug information queries.
868
869   /// getFrameRegister - This method should return the register used as a base
870   /// for values allocated in the current stack frame.
871   virtual unsigned getFrameRegister(const MachineFunction &MF) const = 0;
872 };
873
874
875 //===----------------------------------------------------------------------===//
876 //                           SuperRegClassIterator
877 //===----------------------------------------------------------------------===//
878 //
879 // Iterate over the possible super-registers for a given register class. The
880 // iterator will visit a list of pairs (Idx, Mask) corresponding to the
881 // possible classes of super-registers.
882 //
883 // Each bit mask will have at least one set bit, and each set bit in Mask
884 // corresponds to a SuperRC such that:
885 //
886 //   For all Reg in SuperRC: Reg:Idx is in RC.
887 //
888 // The iterator can include (O, RC->getSubClassMask()) as the first entry which
889 // also satisfies the above requirement, assuming Reg:0 == Reg.
890 //
891 class SuperRegClassIterator {
892   const unsigned RCMaskWords;
893   unsigned SubReg;
894   const uint16_t *Idx;
895   const uint32_t *Mask;
896
897 public:
898   /// Create a SuperRegClassIterator that visits all the super-register classes
899   /// of RC. When IncludeSelf is set, also include the (0, sub-classes) entry.
900   SuperRegClassIterator(const TargetRegisterClass *RC,
901                         const TargetRegisterInfo *TRI,
902                         bool IncludeSelf = false)
903     : RCMaskWords((TRI->getNumRegClasses() + 31) / 32),
904       SubReg(0),
905       Idx(RC->getSuperRegIndices()),
906       Mask(RC->getSubClassMask()) {
907     if (!IncludeSelf)
908       ++*this;
909   }
910
911   /// Returns true if this iterator is still pointing at a valid entry.
912   bool isValid() const { return Idx; }
913
914   /// Returns the current sub-register index.
915   unsigned getSubReg() const { return SubReg; }
916
917   /// Returns the bit mask if register classes that getSubReg() projects into
918   /// RC.
919   const uint32_t *getMask() const { return Mask; }
920
921   /// Advance iterator to the next entry.
922   void operator++() {
923     assert(isValid() && "Cannot move iterator past end.");
924     Mask += RCMaskWords;
925     SubReg = *Idx++;
926     if (!SubReg)
927       Idx = nullptr;
928   }
929 };
930
931 // This is useful when building IndexedMaps keyed on virtual registers
932 struct VirtReg2IndexFunctor : public std::unary_function<unsigned, unsigned> {
933   unsigned operator()(unsigned Reg) const {
934     return TargetRegisterInfo::virtReg2Index(Reg);
935   }
936 };
937
938 /// PrintReg - Helper class for printing registers on a raw_ostream.
939 /// Prints virtual and physical registers with or without a TRI instance.
940 ///
941 /// The format is:
942 ///   %noreg          - NoRegister
943 ///   %vreg5          - a virtual register.
944 ///   %vreg5:sub_8bit - a virtual register with sub-register index (with TRI).
945 ///   %EAX            - a physical register
946 ///   %physreg17      - a physical register when no TRI instance given.
947 ///
948 /// Usage: OS << PrintReg(Reg, TRI) << '\n';
949 ///
950 class PrintReg {
951   const TargetRegisterInfo *TRI;
952   unsigned Reg;
953   unsigned SubIdx;
954 public:
955   explicit PrintReg(unsigned reg, const TargetRegisterInfo *tri = nullptr,
956                     unsigned subidx = 0)
957     : TRI(tri), Reg(reg), SubIdx(subidx) {}
958   void print(raw_ostream&) const;
959 };
960
961 static inline raw_ostream &operator<<(raw_ostream &OS, const PrintReg &PR) {
962   PR.print(OS);
963   return OS;
964 }
965
966 /// PrintRegUnit - Helper class for printing register units on a raw_ostream.
967 ///
968 /// Register units are named after their root registers:
969 ///
970 ///   AL      - Single root.
971 ///   FP0~ST7 - Dual roots.
972 ///
973 /// Usage: OS << PrintRegUnit(Unit, TRI) << '\n';
974 ///
975 class PrintRegUnit {
976 protected:
977   const TargetRegisterInfo *TRI;
978   unsigned Unit;
979 public:
980   PrintRegUnit(unsigned unit, const TargetRegisterInfo *tri)
981     : TRI(tri), Unit(unit) {}
982   void print(raw_ostream&) const;
983 };
984
985 static inline raw_ostream &operator<<(raw_ostream &OS, const PrintRegUnit &PR) {
986   PR.print(OS);
987   return OS;
988 }
989
990 /// PrintVRegOrUnit - It is often convenient to track virtual registers and
991 /// physical register units in the same list.
992 class PrintVRegOrUnit : protected PrintRegUnit {
993 public:
994   PrintVRegOrUnit(unsigned VRegOrUnit, const TargetRegisterInfo *tri)
995     : PrintRegUnit(VRegOrUnit, tri) {}
996   void print(raw_ostream&) const;
997 };
998
999 static inline raw_ostream &operator<<(raw_ostream &OS,
1000                                       const PrintVRegOrUnit &PR) {
1001   PR.print(OS);
1002   return OS;
1003 }
1004
1005 } // End llvm namespace
1006
1007 #endif