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