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