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