1326938Sdim//==- CodeGen/TargetRegisterInfo.h - Target Register Information -*- C++ -*-==//
2326938Sdim//
3353358Sdim// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4353358Sdim// See https://llvm.org/LICENSE.txt for license information.
5353358Sdim// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6326938Sdim//
7326938Sdim//===----------------------------------------------------------------------===//
8326938Sdim//
9326938Sdim// This file describes an abstract interface used to get information about a
10326938Sdim// target machines register file.  This information is used for a variety of
11326938Sdim// purposed, especially register allocation.
12326938Sdim//
13326938Sdim//===----------------------------------------------------------------------===//
14326938Sdim
15326938Sdim#ifndef LLVM_CODEGEN_TARGETREGISTERINFO_H
16326938Sdim#define LLVM_CODEGEN_TARGETREGISTERINFO_H
17326938Sdim
18326938Sdim#include "llvm/ADT/ArrayRef.h"
19326938Sdim#include "llvm/ADT/SmallVector.h"
20326938Sdim#include "llvm/ADT/StringRef.h"
21326938Sdim#include "llvm/ADT/iterator_range.h"
22326938Sdim#include "llvm/CodeGen/MachineBasicBlock.h"
23326938Sdim#include "llvm/IR/CallingConv.h"
24326938Sdim#include "llvm/MC/LaneBitmask.h"
25326938Sdim#include "llvm/MC/MCRegisterInfo.h"
26326938Sdim#include "llvm/Support/ErrorHandling.h"
27341825Sdim#include "llvm/Support/MachineValueType.h"
28326938Sdim#include "llvm/Support/MathExtras.h"
29326938Sdim#include "llvm/Support/Printable.h"
30326938Sdim#include <cassert>
31326938Sdim#include <cstdint>
32326938Sdim#include <functional>
33326938Sdim
34326938Sdimnamespace llvm {
35326938Sdim
36326938Sdimclass BitVector;
37326938Sdimclass LiveRegMatrix;
38326938Sdimclass MachineFunction;
39326938Sdimclass MachineInstr;
40326938Sdimclass RegScavenger;
41326938Sdimclass VirtRegMap;
42326938Sdimclass LiveIntervals;
43326938Sdim
44326938Sdimclass TargetRegisterClass {
45326938Sdimpublic:
46326938Sdim  using iterator = const MCPhysReg *;
47326938Sdim  using const_iterator = const MCPhysReg *;
48326938Sdim  using sc_iterator = const TargetRegisterClass* const *;
49326938Sdim
50326938Sdim  // Instance variables filled by tablegen, do not use!
51326938Sdim  const MCRegisterClass *MC;
52326938Sdim  const uint32_t *SubClassMask;
53326938Sdim  const uint16_t *SuperRegIndices;
54326938Sdim  const LaneBitmask LaneMask;
55326938Sdim  /// Classes with a higher priority value are assigned first by register
56326938Sdim  /// allocators using a greedy heuristic. The value is in the range [0,63].
57326938Sdim  const uint8_t AllocationPriority;
58326938Sdim  /// Whether the class supports two (or more) disjunct subregister indices.
59326938Sdim  const bool HasDisjunctSubRegs;
60326938Sdim  /// Whether a combination of subregisters can cover every register in the
61326938Sdim  /// class. See also the CoveredBySubRegs description in Target.td.
62326938Sdim  const bool CoveredBySubRegs;
63326938Sdim  const sc_iterator SuperClasses;
64326938Sdim  ArrayRef<MCPhysReg> (*OrderFunc)(const MachineFunction&);
65326938Sdim
66326938Sdim  /// Return the register class ID number.
67326938Sdim  unsigned getID() const { return MC->getID(); }
68326938Sdim
69326938Sdim  /// begin/end - Return all of the registers in this class.
70326938Sdim  ///
71326938Sdim  iterator       begin() const { return MC->begin(); }
72326938Sdim  iterator         end() const { return MC->end(); }
73326938Sdim
74326938Sdim  /// Return the number of registers in this class.
75326938Sdim  unsigned getNumRegs() const { return MC->getNumRegs(); }
76326938Sdim
77326938Sdim  iterator_range<SmallVectorImpl<MCPhysReg>::const_iterator>
78326938Sdim  getRegisters() const {
79326938Sdim    return make_range(MC->begin(), MC->end());
80326938Sdim  }
81326938Sdim
82326938Sdim  /// Return the specified register in the class.
83326938Sdim  unsigned getRegister(unsigned i) const {
84326938Sdim    return MC->getRegister(i);
85326938Sdim  }
86326938Sdim
87326938Sdim  /// Return true if the specified register is included in this register class.
88326938Sdim  /// This does not include virtual registers.
89326938Sdim  bool contains(unsigned Reg) const {
90360784Sdim    /// FIXME: Historically this function has returned false when given vregs
91360784Sdim    ///        but it should probably only receive physical registers
92360784Sdim    if (!Register::isPhysicalRegister(Reg))
93360784Sdim      return false;
94326938Sdim    return MC->contains(Reg);
95326938Sdim  }
96326938Sdim
97326938Sdim  /// Return true if both registers are in this class.
98326938Sdim  bool contains(unsigned Reg1, unsigned Reg2) const {
99360784Sdim    /// FIXME: Historically this function has returned false when given a vregs
100360784Sdim    ///        but it should probably only receive physical registers
101360784Sdim    if (!Register::isPhysicalRegister(Reg1) ||
102360784Sdim        !Register::isPhysicalRegister(Reg2))
103360784Sdim      return false;
104326938Sdim    return MC->contains(Reg1, Reg2);
105326938Sdim  }
106326938Sdim
107326938Sdim  /// Return the cost of copying a value between two registers in this class.
108326938Sdim  /// A negative number means the register class is very expensive
109326938Sdim  /// to copy e.g. status flag register classes.
110326938Sdim  int getCopyCost() const { return MC->getCopyCost(); }
111326938Sdim
112326938Sdim  /// Return true if this register class may be used to create virtual
113326938Sdim  /// registers.
114326938Sdim  bool isAllocatable() const { return MC->isAllocatable(); }
115326938Sdim
116326938Sdim  /// Return true if the specified TargetRegisterClass
117326938Sdim  /// is a proper sub-class of this TargetRegisterClass.
118326938Sdim  bool hasSubClass(const TargetRegisterClass *RC) const {
119326938Sdim    return RC != this && hasSubClassEq(RC);
120326938Sdim  }
121326938Sdim
122326938Sdim  /// Returns true if RC is a sub-class of or equal to this class.
123326938Sdim  bool hasSubClassEq(const TargetRegisterClass *RC) const {
124326938Sdim    unsigned ID = RC->getID();
125326938Sdim    return (SubClassMask[ID / 32] >> (ID % 32)) & 1;
126326938Sdim  }
127326938Sdim
128326938Sdim  /// Return true if the specified TargetRegisterClass is a
129326938Sdim  /// proper super-class of this TargetRegisterClass.
130326938Sdim  bool hasSuperClass(const TargetRegisterClass *RC) const {
131326938Sdim    return RC->hasSubClass(this);
132326938Sdim  }
133326938Sdim
134326938Sdim  /// Returns true if RC is a super-class of or equal to this class.
135326938Sdim  bool hasSuperClassEq(const TargetRegisterClass *RC) const {
136326938Sdim    return RC->hasSubClassEq(this);
137326938Sdim  }
138326938Sdim
139326938Sdim  /// Returns a bit vector of subclasses, including this one.
140326938Sdim  /// The vector is indexed by class IDs.
141326938Sdim  ///
142326938Sdim  /// To use it, consider the returned array as a chunk of memory that
143326938Sdim  /// contains an array of bits of size NumRegClasses. Each 32-bit chunk
144326938Sdim  /// contains a bitset of the ID of the subclasses in big-endian style.
145326938Sdim
146326938Sdim  /// I.e., the representation of the memory from left to right at the
147326938Sdim  /// bit level looks like:
148326938Sdim  /// [31 30 ... 1 0] [ 63 62 ... 33 32] ...
149326938Sdim  ///                     [ XXX NumRegClasses NumRegClasses - 1 ... ]
150326938Sdim  /// Where the number represents the class ID and XXX bits that
151326938Sdim  /// should be ignored.
152326938Sdim  ///
153326938Sdim  /// See the implementation of hasSubClassEq for an example of how it
154326938Sdim  /// can be used.
155326938Sdim  const uint32_t *getSubClassMask() const {
156326938Sdim    return SubClassMask;
157326938Sdim  }
158326938Sdim
159326938Sdim  /// Returns a 0-terminated list of sub-register indices that project some
160326938Sdim  /// super-register class into this register class. The list has an entry for
161326938Sdim  /// each Idx such that:
162326938Sdim  ///
163326938Sdim  ///   There exists SuperRC where:
164326938Sdim  ///     For all Reg in SuperRC:
165326938Sdim  ///       this->contains(Reg:Idx)
166326938Sdim  const uint16_t *getSuperRegIndices() const {
167326938Sdim    return SuperRegIndices;
168326938Sdim  }
169326938Sdim
170326938Sdim  /// Returns a NULL-terminated list of super-classes.  The
171326938Sdim  /// classes are ordered by ID which is also a topological ordering from large
172326938Sdim  /// to small classes.  The list does NOT include the current class.
173326938Sdim  sc_iterator getSuperClasses() const {
174326938Sdim    return SuperClasses;
175326938Sdim  }
176326938Sdim
177326938Sdim  /// Return true if this TargetRegisterClass is a subset
178326938Sdim  /// class of at least one other TargetRegisterClass.
179326938Sdim  bool isASubClass() const {
180326938Sdim    return SuperClasses[0] != nullptr;
181326938Sdim  }
182326938Sdim
183326938Sdim  /// Returns the preferred order for allocating registers from this register
184326938Sdim  /// class in MF. The raw order comes directly from the .td file and may
185326938Sdim  /// include reserved registers that are not allocatable.
186326938Sdim  /// Register allocators should also make sure to allocate
187326938Sdim  /// callee-saved registers only after all the volatiles are used. The
188326938Sdim  /// RegisterClassInfo class provides filtered allocation orders with
189326938Sdim  /// callee-saved registers moved to the end.
190326938Sdim  ///
191326938Sdim  /// The MachineFunction argument can be used to tune the allocatable
192326938Sdim  /// registers based on the characteristics of the function, subtarget, or
193326938Sdim  /// other criteria.
194326938Sdim  ///
195326938Sdim  /// By default, this method returns all registers in the class.
196326938Sdim  ArrayRef<MCPhysReg> getRawAllocationOrder(const MachineFunction &MF) const {
197326938Sdim    return OrderFunc ? OrderFunc(MF) : makeArrayRef(begin(), getNumRegs());
198326938Sdim  }
199326938Sdim
200326938Sdim  /// Returns the combination of all lane masks of register in this class.
201326938Sdim  /// The lane masks of the registers are the combination of all lane masks
202326938Sdim  /// of their subregisters. Returns 1 if there are no subregisters.
203326938Sdim  LaneBitmask getLaneMask() const {
204326938Sdim    return LaneMask;
205326938Sdim  }
206326938Sdim};
207326938Sdim
208326938Sdim/// Extra information, not in MCRegisterDesc, about registers.
209326938Sdim/// These are used by codegen, not by MC.
210326938Sdimstruct TargetRegisterInfoDesc {
211326938Sdim  unsigned CostPerUse;          // Extra cost of instructions using register.
212326938Sdim  bool inAllocatableClass;      // Register belongs to an allocatable regclass.
213326938Sdim};
214326938Sdim
215326938Sdim/// Each TargetRegisterClass has a per register weight, and weight
216326938Sdim/// limit which must be less than the limits of its pressure sets.
217326938Sdimstruct RegClassWeight {
218326938Sdim  unsigned RegWeight;
219326938Sdim  unsigned WeightLimit;
220326938Sdim};
221326938Sdim
222326938Sdim/// TargetRegisterInfo base class - We assume that the target defines a static
223326938Sdim/// array of TargetRegisterDesc objects that represent all of the machine
224326938Sdim/// registers that the target has.  As such, we simply have to track a pointer
225326938Sdim/// to this array so that we can turn register number into a register
226326938Sdim/// descriptor.
227326938Sdim///
228326938Sdimclass TargetRegisterInfo : public MCRegisterInfo {
229326938Sdimpublic:
230326938Sdim  using regclass_iterator = const TargetRegisterClass * const *;
231326938Sdim  using vt_iterator = const MVT::SimpleValueType *;
232326938Sdim  struct RegClassInfo {
233326938Sdim    unsigned RegSize, SpillSize, SpillAlignment;
234326938Sdim    vt_iterator VTList;
235326938Sdim  };
236326938Sdimprivate:
237326938Sdim  const TargetRegisterInfoDesc *InfoDesc;     // Extra desc array for codegen
238326938Sdim  const char *const *SubRegIndexNames;        // Names of subreg indexes.
239326938Sdim  // Pointer to array of lane masks, one per sub-reg index.
240326938Sdim  const LaneBitmask *SubRegIndexLaneMasks;
241326938Sdim
242326938Sdim  regclass_iterator RegClassBegin, RegClassEnd;   // List of regclasses
243326938Sdim  LaneBitmask CoveringLanes;
244326938Sdim  const RegClassInfo *const RCInfos;
245326938Sdim  unsigned HwMode;
246326938Sdim
247326938Sdimprotected:
248326938Sdim  TargetRegisterInfo(const TargetRegisterInfoDesc *ID,
249341825Sdim                     regclass_iterator RCB,
250341825Sdim                     regclass_iterator RCE,
251326938Sdim                     const char *const *SRINames,
252326938Sdim                     const LaneBitmask *SRILaneMasks,
253326938Sdim                     LaneBitmask CoveringLanes,
254341825Sdim                     const RegClassInfo *const RCIs,
255326938Sdim                     unsigned Mode = 0);
256326938Sdim  virtual ~TargetRegisterInfo();
257326938Sdim
258326938Sdimpublic:
259326938Sdim  // Register numbers can represent physical registers, virtual registers, and
260326938Sdim  // sometimes stack slots. The unsigned values are divided into these ranges:
261326938Sdim  //
262326938Sdim  //   0           Not a register, can be used as a sentinel.
263326938Sdim  //   [1;2^30)    Physical registers assigned by TableGen.
264326938Sdim  //   [2^30;2^31) Stack slots. (Rarely used.)
265326938Sdim  //   [2^31;2^32) Virtual registers assigned by MachineRegisterInfo.
266326938Sdim  //
267326938Sdim  // Further sentinels can be allocated from the small negative integers.
268326938Sdim  // DenseMapInfo<unsigned> uses -1u and -2u.
269326938Sdim
270326938Sdim  /// Return the size in bits of a register from class RC.
271326938Sdim  unsigned getRegSizeInBits(const TargetRegisterClass &RC) const {
272326938Sdim    return getRegClassInfo(RC).RegSize;
273326938Sdim  }
274326938Sdim
275326938Sdim  /// Return the size in bytes of the stack slot allocated to hold a spilled
276326938Sdim  /// copy of a register from class RC.
277326938Sdim  unsigned getSpillSize(const TargetRegisterClass &RC) const {
278326938Sdim    return getRegClassInfo(RC).SpillSize / 8;
279326938Sdim  }
280326938Sdim
281326938Sdim  /// Return the minimum required alignment in bytes for a spill slot for
282326938Sdim  /// a register of this class.
283326938Sdim  unsigned getSpillAlignment(const TargetRegisterClass &RC) const {
284326938Sdim    return getRegClassInfo(RC).SpillAlignment / 8;
285326938Sdim  }
286326938Sdim
287326938Sdim  /// Return true if the given TargetRegisterClass has the ValueType T.
288326938Sdim  bool isTypeLegalForClass(const TargetRegisterClass &RC, MVT T) const {
289326938Sdim    for (auto I = legalclasstypes_begin(RC); *I != MVT::Other; ++I)
290326938Sdim      if (MVT(*I) == T)
291326938Sdim        return true;
292326938Sdim    return false;
293326938Sdim  }
294326938Sdim
295326938Sdim  /// Loop over all of the value types that can be represented by values
296326938Sdim  /// in the given register class.
297326938Sdim  vt_iterator legalclasstypes_begin(const TargetRegisterClass &RC) const {
298326938Sdim    return getRegClassInfo(RC).VTList;
299326938Sdim  }
300326938Sdim
301326938Sdim  vt_iterator legalclasstypes_end(const TargetRegisterClass &RC) const {
302326938Sdim    vt_iterator I = legalclasstypes_begin(RC);
303326938Sdim    while (*I != MVT::Other)
304326938Sdim      ++I;
305326938Sdim    return I;
306326938Sdim  }
307326938Sdim
308326938Sdim  /// Returns the Register Class of a physical register of the given type,
309326938Sdim  /// picking the most sub register class of the right type that contains this
310326938Sdim  /// physreg.
311326938Sdim  const TargetRegisterClass *
312326938Sdim    getMinimalPhysRegClass(unsigned Reg, MVT VT = MVT::Other) const;
313326938Sdim
314326938Sdim  /// Return the maximal subclass of the given register class that is
315326938Sdim  /// allocatable or NULL.
316326938Sdim  const TargetRegisterClass *
317326938Sdim    getAllocatableClass(const TargetRegisterClass *RC) const;
318326938Sdim
319326938Sdim  /// Returns a bitset indexed by register number indicating if a register is
320326938Sdim  /// allocatable or not. If a register class is specified, returns the subset
321326938Sdim  /// for the class.
322326938Sdim  BitVector getAllocatableSet(const MachineFunction &MF,
323326938Sdim                              const TargetRegisterClass *RC = nullptr) const;
324326938Sdim
325326938Sdim  /// Return the additional cost of using this register instead
326326938Sdim  /// of other registers in its class.
327326938Sdim  unsigned getCostPerUse(unsigned RegNo) const {
328326938Sdim    return InfoDesc[RegNo].CostPerUse;
329326938Sdim  }
330326938Sdim
331326938Sdim  /// Return true if the register is in the allocation of any register class.
332326938Sdim  bool isInAllocatableClass(unsigned RegNo) const {
333326938Sdim    return InfoDesc[RegNo].inAllocatableClass;
334326938Sdim  }
335326938Sdim
336326938Sdim  /// Return the human-readable symbolic target-specific
337326938Sdim  /// name for the specified SubRegIndex.
338326938Sdim  const char *getSubRegIndexName(unsigned SubIdx) const {
339326938Sdim    assert(SubIdx && SubIdx < getNumSubRegIndices() &&
340326938Sdim           "This is not a subregister index");
341326938Sdim    return SubRegIndexNames[SubIdx-1];
342326938Sdim  }
343326938Sdim
344326938Sdim  /// Return a bitmask representing the parts of a register that are covered by
345326938Sdim  /// SubIdx \see LaneBitmask.
346326938Sdim  ///
347326938Sdim  /// SubIdx == 0 is allowed, it has the lane mask ~0u.
348326938Sdim  LaneBitmask getSubRegIndexLaneMask(unsigned SubIdx) const {
349326938Sdim    assert(SubIdx < getNumSubRegIndices() && "This is not a subregister index");
350326938Sdim    return SubRegIndexLaneMasks[SubIdx];
351326938Sdim  }
352326938Sdim
353326938Sdim  /// The lane masks returned by getSubRegIndexLaneMask() above can only be
354326938Sdim  /// used to determine if sub-registers overlap - they can't be used to
355326938Sdim  /// determine if a set of sub-registers completely cover another
356326938Sdim  /// sub-register.
357326938Sdim  ///
358326938Sdim  /// The X86 general purpose registers have two lanes corresponding to the
359326938Sdim  /// sub_8bit and sub_8bit_hi sub-registers. Both sub_32bit and sub_16bit have
360326938Sdim  /// lane masks '3', but the sub_16bit sub-register doesn't fully cover the
361326938Sdim  /// sub_32bit sub-register.
362326938Sdim  ///
363326938Sdim  /// On the other hand, the ARM NEON lanes fully cover their registers: The
364326938Sdim  /// dsub_0 sub-register is completely covered by the ssub_0 and ssub_1 lanes.
365326938Sdim  /// This is related to the CoveredBySubRegs property on register definitions.
366326938Sdim  ///
367326938Sdim  /// This function returns a bit mask of lanes that completely cover their
368326938Sdim  /// sub-registers. More precisely, given:
369326938Sdim  ///
370326938Sdim  ///   Covering = getCoveringLanes();
371326938Sdim  ///   MaskA = getSubRegIndexLaneMask(SubA);
372326938Sdim  ///   MaskB = getSubRegIndexLaneMask(SubB);
373326938Sdim  ///
374326938Sdim  /// If (MaskA & ~(MaskB & Covering)) == 0, then SubA is completely covered by
375326938Sdim  /// SubB.
376326938Sdim  LaneBitmask getCoveringLanes() const { return CoveringLanes; }
377326938Sdim
378326938Sdim  /// Returns true if the two registers are equal or alias each other.
379326938Sdim  /// The registers may be virtual registers.
380360784Sdim  bool regsOverlap(Register regA, Register regB) const {
381326938Sdim    if (regA == regB) return true;
382360784Sdim    if (regA.isVirtual() || regB.isVirtual())
383326938Sdim      return false;
384326938Sdim
385326938Sdim    // Regunits are numerically ordered. Find a common unit.
386326938Sdim    MCRegUnitIterator RUA(regA, this);
387326938Sdim    MCRegUnitIterator RUB(regB, this);
388326938Sdim    do {
389326938Sdim      if (*RUA == *RUB) return true;
390326938Sdim      if (*RUA < *RUB) ++RUA;
391326938Sdim      else             ++RUB;
392326938Sdim    } while (RUA.isValid() && RUB.isValid());
393326938Sdim    return false;
394326938Sdim  }
395326938Sdim
396326938Sdim  /// Returns true if Reg contains RegUnit.
397326938Sdim  bool hasRegUnit(unsigned Reg, unsigned RegUnit) const {
398326938Sdim    for (MCRegUnitIterator Units(Reg, this); Units.isValid(); ++Units)
399326938Sdim      if (*Units == RegUnit)
400326938Sdim        return true;
401326938Sdim    return false;
402326938Sdim  }
403326938Sdim
404341825Sdim  /// Returns the original SrcReg unless it is the target of a copy-like
405341825Sdim  /// operation, in which case we chain backwards through all such operations
406341825Sdim  /// to the ultimate source register.  If a physical register is encountered,
407341825Sdim  /// we stop the search.
408341825Sdim  virtual unsigned lookThruCopyLike(unsigned SrcReg,
409341825Sdim                                    const MachineRegisterInfo *MRI) const;
410341825Sdim
411326938Sdim  /// Return a null-terminated list of all of the callee-saved registers on
412326938Sdim  /// this target. The register should be in the order of desired callee-save
413326938Sdim  /// stack frame offset. The first register is closest to the incoming stack
414326938Sdim  /// pointer if stack grows down, and vice versa.
415326938Sdim  /// Notice: This function does not take into account disabled CSRs.
416341825Sdim  ///         In most cases you will want to use instead the function
417326938Sdim  ///         getCalleeSavedRegs that is implemented in MachineRegisterInfo.
418326938Sdim  virtual const MCPhysReg*
419326938Sdim  getCalleeSavedRegs(const MachineFunction *MF) const = 0;
420326938Sdim
421326938Sdim  /// Return a mask of call-preserved registers for the given calling convention
422326938Sdim  /// on the current function. The mask should include all call-preserved
423326938Sdim  /// aliases. This is used by the register allocator to determine which
424326938Sdim  /// registers can be live across a call.
425326938Sdim  ///
426326938Sdim  /// The mask is an array containing (TRI::getNumRegs()+31)/32 entries.
427326938Sdim  /// A set bit indicates that all bits of the corresponding register are
428326938Sdim  /// preserved across the function call.  The bit mask is expected to be
429326938Sdim  /// sub-register complete, i.e. if A is preserved, so are all its
430326938Sdim  /// sub-registers.
431326938Sdim  ///
432326938Sdim  /// Bits are numbered from the LSB, so the bit for physical register Reg can
433326938Sdim  /// be found as (Mask[Reg / 32] >> Reg % 32) & 1.
434326938Sdim  ///
435326938Sdim  /// A NULL pointer means that no register mask will be used, and call
436326938Sdim  /// instructions should use implicit-def operands to indicate call clobbered
437326938Sdim  /// registers.
438326938Sdim  ///
439326938Sdim  virtual const uint32_t *getCallPreservedMask(const MachineFunction &MF,
440326938Sdim                                               CallingConv::ID) const {
441326938Sdim    // The default mask clobbers everything.  All targets should override.
442326938Sdim    return nullptr;
443326938Sdim  }
444326938Sdim
445326938Sdim  /// Return a register mask that clobbers everything.
446326938Sdim  virtual const uint32_t *getNoPreservedMask() const {
447326938Sdim    llvm_unreachable("target does not provide no preserved mask");
448326938Sdim  }
449326938Sdim
450360784Sdim  /// Return a list of all of the registers which are clobbered "inside" a call
451360784Sdim  /// to the given function. For example, these might be needed for PLT
452360784Sdim  /// sequences of long-branch veneers.
453360784Sdim  virtual ArrayRef<MCPhysReg>
454360784Sdim  getIntraCallClobberedRegs(const MachineFunction *MF) const {
455360784Sdim    return {};
456360784Sdim  }
457360784Sdim
458326938Sdim  /// Return true if all bits that are set in mask \p mask0 are also set in
459326938Sdim  /// \p mask1.
460326938Sdim  bool regmaskSubsetEqual(const uint32_t *mask0, const uint32_t *mask1) const;
461326938Sdim
462326938Sdim  /// Return all the call-preserved register masks defined for this target.
463326938Sdim  virtual ArrayRef<const uint32_t *> getRegMasks() const = 0;
464326938Sdim  virtual ArrayRef<const char *> getRegMaskNames() const = 0;
465326938Sdim
466326938Sdim  /// Returns a bitset indexed by physical register number indicating if a
467326938Sdim  /// register is a special register that has particular uses and should be
468326938Sdim  /// considered unavailable at all times, e.g. stack pointer, return address.
469326938Sdim  /// A reserved register:
470326938Sdim  /// - is not allocatable
471326938Sdim  /// - is considered always live
472326938Sdim  /// - is ignored by liveness tracking
473326938Sdim  /// It is often necessary to reserve the super registers of a reserved
474326938Sdim  /// register as well, to avoid them getting allocated indirectly. You may use
475326938Sdim  /// markSuperRegs() and checkAllSuperRegsMarked() in this case.
476326938Sdim  virtual BitVector getReservedRegs(const MachineFunction &MF) const = 0;
477326938Sdim
478344779Sdim  /// Returns false if we can't guarantee that Physreg, specified as an IR asm
479344779Sdim  /// clobber constraint, will be preserved across the statement.
480344779Sdim  virtual bool isAsmClobberable(const MachineFunction &MF,
481344779Sdim                               unsigned PhysReg) const {
482344779Sdim    return true;
483344779Sdim  }
484344779Sdim
485326938Sdim  /// Returns true if PhysReg is unallocatable and constant throughout the
486326938Sdim  /// function.  Used by MachineRegisterInfo::isConstantPhysReg().
487326938Sdim  virtual bool isConstantPhysReg(unsigned PhysReg) const { return false; }
488326938Sdim
489353358Sdim  /// Returns true if the register class is considered divergent.
490353358Sdim  virtual bool isDivergentRegClass(const TargetRegisterClass *RC) const {
491353358Sdim    return false;
492353358Sdim  }
493353358Sdim
494326938Sdim  /// Physical registers that may be modified within a function but are
495326938Sdim  /// guaranteed to be restored before any uses. This is useful for targets that
496326938Sdim  /// have call sequences where a GOT register may be updated by the caller
497326938Sdim  /// prior to a call and is guaranteed to be restored (also by the caller)
498341825Sdim  /// after the call.
499326938Sdim  virtual bool isCallerPreservedPhysReg(unsigned PhysReg,
500326938Sdim                                        const MachineFunction &MF) const {
501326938Sdim    return false;
502326938Sdim  }
503326938Sdim
504360784Sdim  /// This is a wrapper around getCallPreservedMask().
505360784Sdim  /// Return true if the register is preserved after the call.
506360784Sdim  virtual bool isCalleeSavedPhysReg(unsigned PhysReg,
507360784Sdim                                    const MachineFunction &MF) const;
508360784Sdim
509326938Sdim  /// Prior to adding the live-out mask to a stackmap or patchpoint
510326938Sdim  /// instruction, provide the target the opportunity to adjust it (mainly to
511326938Sdim  /// remove pseudo-registers that should be ignored).
512326938Sdim  virtual void adjustStackMapLiveOutMask(uint32_t *Mask) const {}
513326938Sdim
514326938Sdim  /// Return a super-register of the specified register
515326938Sdim  /// Reg so its sub-register of index SubIdx is Reg.
516326938Sdim  unsigned getMatchingSuperReg(unsigned Reg, unsigned SubIdx,
517326938Sdim                               const TargetRegisterClass *RC) const {
518326938Sdim    return MCRegisterInfo::getMatchingSuperReg(Reg, SubIdx, RC->MC);
519326938Sdim  }
520326938Sdim
521326938Sdim  /// Return a subclass of the specified register
522326938Sdim  /// class A so that each register in it has a sub-register of the
523326938Sdim  /// specified sub-register index which is in the specified register class B.
524326938Sdim  ///
525326938Sdim  /// TableGen will synthesize missing A sub-classes.
526326938Sdim  virtual const TargetRegisterClass *
527326938Sdim  getMatchingSuperRegClass(const TargetRegisterClass *A,
528326938Sdim                           const TargetRegisterClass *B, unsigned Idx) const;
529326938Sdim
530326938Sdim  // For a copy-like instruction that defines a register of class DefRC with
531326938Sdim  // subreg index DefSubReg, reading from another source with class SrcRC and
532326938Sdim  // subregister SrcSubReg return true if this is a preferable copy
533326938Sdim  // instruction or an earlier use should be used.
534326938Sdim  virtual bool shouldRewriteCopySrc(const TargetRegisterClass *DefRC,
535326938Sdim                                    unsigned DefSubReg,
536326938Sdim                                    const TargetRegisterClass *SrcRC,
537326938Sdim                                    unsigned SrcSubReg) const;
538326938Sdim
539326938Sdim  /// Returns the largest legal sub-class of RC that
540326938Sdim  /// supports the sub-register index Idx.
541326938Sdim  /// If no such sub-class exists, return NULL.
542326938Sdim  /// If all registers in RC already have an Idx sub-register, return RC.
543326938Sdim  ///
544326938Sdim  /// TableGen generates a version of this function that is good enough in most
545326938Sdim  /// cases.  Targets can override if they have constraints that TableGen
546326938Sdim  /// doesn't understand.  For example, the x86 sub_8bit sub-register index is
547326938Sdim  /// supported by the full GR32 register class in 64-bit mode, but only by the
548326938Sdim  /// GR32_ABCD regiister class in 32-bit mode.
549326938Sdim  ///
550326938Sdim  /// TableGen will synthesize missing RC sub-classes.
551326938Sdim  virtual const TargetRegisterClass *
552326938Sdim  getSubClassWithSubReg(const TargetRegisterClass *RC, unsigned Idx) const {
553326938Sdim    assert(Idx == 0 && "Target has no sub-registers");
554326938Sdim    return RC;
555326938Sdim  }
556326938Sdim
557326938Sdim  /// Return the subregister index you get from composing
558326938Sdim  /// two subregister indices.
559326938Sdim  ///
560326938Sdim  /// The special null sub-register index composes as the identity.
561326938Sdim  ///
562326938Sdim  /// If R:a:b is the same register as R:c, then composeSubRegIndices(a, b)
563326938Sdim  /// returns c. Note that composeSubRegIndices does not tell you about illegal
564326938Sdim  /// compositions. If R does not have a subreg a, or R:a does not have a subreg
565326938Sdim  /// b, composeSubRegIndices doesn't tell you.
566326938Sdim  ///
567326938Sdim  /// The ARM register Q0 has two D subregs dsub_0:D0 and dsub_1:D1. It also has
568326938Sdim  /// ssub_0:S0 - ssub_3:S3 subregs.
569326938Sdim  /// If you compose subreg indices dsub_1, ssub_0 you get ssub_2.
570326938Sdim  unsigned composeSubRegIndices(unsigned a, unsigned b) const {
571326938Sdim    if (!a) return b;
572326938Sdim    if (!b) return a;
573326938Sdim    return composeSubRegIndicesImpl(a, b);
574326938Sdim  }
575326938Sdim
576326938Sdim  /// Transforms a LaneMask computed for one subregister to the lanemask that
577326938Sdim  /// would have been computed when composing the subsubregisters with IdxA
578326938Sdim  /// first. @sa composeSubRegIndices()
579326938Sdim  LaneBitmask composeSubRegIndexLaneMask(unsigned IdxA,
580326938Sdim                                         LaneBitmask Mask) const {
581326938Sdim    if (!IdxA)
582326938Sdim      return Mask;
583326938Sdim    return composeSubRegIndexLaneMaskImpl(IdxA, Mask);
584326938Sdim  }
585326938Sdim
586326938Sdim  /// Transform a lanemask given for a virtual register to the corresponding
587326938Sdim  /// lanemask before using subregister with index \p IdxA.
588326938Sdim  /// This is the reverse of composeSubRegIndexLaneMask(), assuming Mask is a
589326938Sdim  /// valie lane mask (no invalid bits set) the following holds:
590326938Sdim  /// X0 = composeSubRegIndexLaneMask(Idx, Mask)
591326938Sdim  /// X1 = reverseComposeSubRegIndexLaneMask(Idx, X0)
592326938Sdim  /// => X1 == Mask
593326938Sdim  LaneBitmask reverseComposeSubRegIndexLaneMask(unsigned IdxA,
594326938Sdim                                                LaneBitmask LaneMask) const {
595326938Sdim    if (!IdxA)
596326938Sdim      return LaneMask;
597326938Sdim    return reverseComposeSubRegIndexLaneMaskImpl(IdxA, LaneMask);
598326938Sdim  }
599326938Sdim
600326938Sdim  /// Debugging helper: dump register in human readable form to dbgs() stream.
601326938Sdim  static void dumpReg(unsigned Reg, unsigned SubRegIndex = 0,
602326938Sdim                      const TargetRegisterInfo* TRI = nullptr);
603326938Sdim
604326938Sdimprotected:
605326938Sdim  /// Overridden by TableGen in targets that have sub-registers.
606326938Sdim  virtual unsigned composeSubRegIndicesImpl(unsigned, unsigned) const {
607326938Sdim    llvm_unreachable("Target has no sub-registers");
608326938Sdim  }
609326938Sdim
610326938Sdim  /// Overridden by TableGen in targets that have sub-registers.
611326938Sdim  virtual LaneBitmask
612326938Sdim  composeSubRegIndexLaneMaskImpl(unsigned, LaneBitmask) const {
613326938Sdim    llvm_unreachable("Target has no sub-registers");
614326938Sdim  }
615326938Sdim
616326938Sdim  virtual LaneBitmask reverseComposeSubRegIndexLaneMaskImpl(unsigned,
617326938Sdim                                                            LaneBitmask) const {
618326938Sdim    llvm_unreachable("Target has no sub-registers");
619326938Sdim  }
620326938Sdim
621326938Sdimpublic:
622326938Sdim  /// Find a common super-register class if it exists.
623326938Sdim  ///
624326938Sdim  /// Find a register class, SuperRC and two sub-register indices, PreA and
625326938Sdim  /// PreB, such that:
626326938Sdim  ///
627326938Sdim  ///   1. PreA + SubA == PreB + SubB  (using composeSubRegIndices()), and
628326938Sdim  ///
629326938Sdim  ///   2. For all Reg in SuperRC: Reg:PreA in RCA and Reg:PreB in RCB, and
630326938Sdim  ///
631326938Sdim  ///   3. SuperRC->getSize() >= max(RCA->getSize(), RCB->getSize()).
632326938Sdim  ///
633326938Sdim  /// SuperRC will be chosen such that no super-class of SuperRC satisfies the
634326938Sdim  /// requirements, and there is no register class with a smaller spill size
635326938Sdim  /// that satisfies the requirements.
636326938Sdim  ///
637326938Sdim  /// SubA and SubB must not be 0. Use getMatchingSuperRegClass() instead.
638326938Sdim  ///
639326938Sdim  /// Either of the PreA and PreB sub-register indices may be returned as 0. In
640326938Sdim  /// that case, the returned register class will be a sub-class of the
641326938Sdim  /// corresponding argument register class.
642326938Sdim  ///
643326938Sdim  /// The function returns NULL if no register class can be found.
644326938Sdim  const TargetRegisterClass*
645326938Sdim  getCommonSuperRegClass(const TargetRegisterClass *RCA, unsigned SubA,
646326938Sdim                         const TargetRegisterClass *RCB, unsigned SubB,
647326938Sdim                         unsigned &PreA, unsigned &PreB) const;
648326938Sdim
649326938Sdim  //===--------------------------------------------------------------------===//
650326938Sdim  // Register Class Information
651326938Sdim  //
652326938Sdimprotected:
653326938Sdim  const RegClassInfo &getRegClassInfo(const TargetRegisterClass &RC) const {
654326938Sdim    return RCInfos[getNumRegClasses() * HwMode + RC.getID()];
655326938Sdim  }
656326938Sdim
657326938Sdimpublic:
658326938Sdim  /// Register class iterators
659326938Sdim  regclass_iterator regclass_begin() const { return RegClassBegin; }
660326938Sdim  regclass_iterator regclass_end() const { return RegClassEnd; }
661326938Sdim  iterator_range<regclass_iterator> regclasses() const {
662326938Sdim    return make_range(regclass_begin(), regclass_end());
663326938Sdim  }
664326938Sdim
665326938Sdim  unsigned getNumRegClasses() const {
666326938Sdim    return (unsigned)(regclass_end()-regclass_begin());
667326938Sdim  }
668326938Sdim
669326938Sdim  /// Returns the register class associated with the enumeration value.
670326938Sdim  /// See class MCOperandInfo.
671326938Sdim  const TargetRegisterClass *getRegClass(unsigned i) const {
672326938Sdim    assert(i < getNumRegClasses() && "Register Class ID out of range");
673326938Sdim    return RegClassBegin[i];
674326938Sdim  }
675326938Sdim
676326938Sdim  /// Returns the name of the register class.
677326938Sdim  const char *getRegClassName(const TargetRegisterClass *Class) const {
678326938Sdim    return MCRegisterInfo::getRegClassName(Class->MC);
679326938Sdim  }
680326938Sdim
681326938Sdim  /// Find the largest common subclass of A and B.
682326938Sdim  /// Return NULL if there is no common subclass.
683326938Sdim  const TargetRegisterClass *
684326938Sdim  getCommonSubClass(const TargetRegisterClass *A,
685360784Sdim                    const TargetRegisterClass *B) const;
686326938Sdim
687326938Sdim  /// Returns a TargetRegisterClass used for pointer values.
688326938Sdim  /// If a target supports multiple different pointer register classes,
689326938Sdim  /// kind specifies which one is indicated.
690326938Sdim  virtual const TargetRegisterClass *
691326938Sdim  getPointerRegClass(const MachineFunction &MF, unsigned Kind=0) const {
692326938Sdim    llvm_unreachable("Target didn't implement getPointerRegClass!");
693326938Sdim  }
694326938Sdim
695326938Sdim  /// Returns a legal register class to copy a register in the specified class
696326938Sdim  /// to or from. If it is possible to copy the register directly without using
697326938Sdim  /// a cross register class copy, return the specified RC. Returns NULL if it
698326938Sdim  /// is not possible to copy between two registers of the specified class.
699326938Sdim  virtual const TargetRegisterClass *
700326938Sdim  getCrossCopyRegClass(const TargetRegisterClass *RC) const {
701326938Sdim    return RC;
702326938Sdim  }
703326938Sdim
704326938Sdim  /// Returns the largest super class of RC that is legal to use in the current
705326938Sdim  /// sub-target and has the same spill size.
706326938Sdim  /// The returned register class can be used to create virtual registers which
707326938Sdim  /// means that all its registers can be copied and spilled.
708326938Sdim  virtual const TargetRegisterClass *
709326938Sdim  getLargestLegalSuperClass(const TargetRegisterClass *RC,
710326938Sdim                            const MachineFunction &) const {
711326938Sdim    /// The default implementation is very conservative and doesn't allow the
712326938Sdim    /// register allocator to inflate register classes.
713326938Sdim    return RC;
714326938Sdim  }
715326938Sdim
716326938Sdim  /// Return the register pressure "high water mark" for the specific register
717326938Sdim  /// class. The scheduler is in high register pressure mode (for the specific
718326938Sdim  /// register class) if it goes over the limit.
719326938Sdim  ///
720326938Sdim  /// Note: this is the old register pressure model that relies on a manually
721326938Sdim  /// specified representative register class per value type.
722326938Sdim  virtual unsigned getRegPressureLimit(const TargetRegisterClass *RC,
723326938Sdim                                       MachineFunction &MF) const {
724326938Sdim    return 0;
725326938Sdim  }
726326938Sdim
727326938Sdim  /// Return a heuristic for the machine scheduler to compare the profitability
728326938Sdim  /// of increasing one register pressure set versus another.  The scheduler
729326938Sdim  /// will prefer increasing the register pressure of the set which returns
730326938Sdim  /// the largest value for this function.
731326938Sdim  virtual unsigned getRegPressureSetScore(const MachineFunction &MF,
732326938Sdim                                          unsigned PSetID) const {
733326938Sdim    return PSetID;
734326938Sdim  }
735326938Sdim
736326938Sdim  /// Get the weight in units of pressure for this register class.
737326938Sdim  virtual const RegClassWeight &getRegClassWeight(
738326938Sdim    const TargetRegisterClass *RC) const = 0;
739326938Sdim
740341825Sdim  /// Returns size in bits of a phys/virtual/generic register.
741341825Sdim  unsigned getRegSizeInBits(unsigned Reg, const MachineRegisterInfo &MRI) const;
742341825Sdim
743326938Sdim  /// Get the weight in units of pressure for this register unit.
744326938Sdim  virtual unsigned getRegUnitWeight(unsigned RegUnit) const = 0;
745326938Sdim
746326938Sdim  /// Get the number of dimensions of register pressure.
747326938Sdim  virtual unsigned getNumRegPressureSets() const = 0;
748326938Sdim
749326938Sdim  /// Get the name of this register unit pressure set.
750326938Sdim  virtual const char *getRegPressureSetName(unsigned Idx) const = 0;
751326938Sdim
752326938Sdim  /// Get the register unit pressure limit for this dimension.
753326938Sdim  /// This limit must be adjusted dynamically for reserved registers.
754326938Sdim  virtual unsigned getRegPressureSetLimit(const MachineFunction &MF,
755326938Sdim                                          unsigned Idx) const = 0;
756326938Sdim
757326938Sdim  /// Get the dimensions of register pressure impacted by this register class.
758326938Sdim  /// Returns a -1 terminated array of pressure set IDs.
759326938Sdim  virtual const int *getRegClassPressureSets(
760326938Sdim    const TargetRegisterClass *RC) const = 0;
761326938Sdim
762326938Sdim  /// Get the dimensions of register pressure impacted by this register unit.
763326938Sdim  /// Returns a -1 terminated array of pressure set IDs.
764326938Sdim  virtual const int *getRegUnitPressureSets(unsigned RegUnit) const = 0;
765326938Sdim
766326938Sdim  /// Get a list of 'hint' registers that the register allocator should try
767326938Sdim  /// first when allocating a physical register for the virtual register
768326938Sdim  /// VirtReg. These registers are effectively moved to the front of the
769326938Sdim  /// allocation order. If true is returned, regalloc will try to only use
770326938Sdim  /// hints to the greatest extent possible even if it means spilling.
771326938Sdim  ///
772326938Sdim  /// The Order argument is the allocation order for VirtReg's register class
773326938Sdim  /// as returned from RegisterClassInfo::getOrder(). The hint registers must
774326938Sdim  /// come from Order, and they must not be reserved.
775326938Sdim  ///
776326938Sdim  /// The default implementation of this function will only add target
777326938Sdim  /// independent register allocation hints. Targets that override this
778326938Sdim  /// function should typically call this default implementation as well and
779326938Sdim  /// expect to see generic copy hints added.
780326938Sdim  virtual bool getRegAllocationHints(unsigned VirtReg,
781326938Sdim                                     ArrayRef<MCPhysReg> Order,
782326938Sdim                                     SmallVectorImpl<MCPhysReg> &Hints,
783326938Sdim                                     const MachineFunction &MF,
784326938Sdim                                     const VirtRegMap *VRM = nullptr,
785326938Sdim                                     const LiveRegMatrix *Matrix = nullptr)
786326938Sdim    const;
787326938Sdim
788326938Sdim  /// A callback to allow target a chance to update register allocation hints
789326938Sdim  /// when a register is "changed" (e.g. coalesced) to another register.
790326938Sdim  /// e.g. On ARM, some virtual registers should target register pairs,
791326938Sdim  /// if one of pair is coalesced to another register, the allocation hint of
792326938Sdim  /// the other half of the pair should be changed to point to the new register.
793326938Sdim  virtual void updateRegAllocHint(unsigned Reg, unsigned NewReg,
794326938Sdim                                  MachineFunction &MF) const {
795326938Sdim    // Do nothing.
796326938Sdim  }
797326938Sdim
798326938Sdim  /// Allow the target to reverse allocation order of local live ranges. This
799326938Sdim  /// will generally allocate shorter local live ranges first. For targets with
800326938Sdim  /// many registers, this could reduce regalloc compile time by a large
801326938Sdim  /// factor. It is disabled by default for three reasons:
802326938Sdim  /// (1) Top-down allocation is simpler and easier to debug for targets that
803326938Sdim  /// don't benefit from reversing the order.
804326938Sdim  /// (2) Bottom-up allocation could result in poor evicition decisions on some
805326938Sdim  /// targets affecting the performance of compiled code.
806326938Sdim  /// (3) Bottom-up allocation is no longer guaranteed to optimally color.
807326938Sdim  virtual bool reverseLocalAssignment() const { return false; }
808326938Sdim
809326938Sdim  /// Allow the target to override the cost of using a callee-saved register for
810326938Sdim  /// the first time. Default value of 0 means we will use a callee-saved
811326938Sdim  /// register if it is available.
812326938Sdim  virtual unsigned getCSRFirstUseCost() const { return 0; }
813326938Sdim
814326938Sdim  /// Returns true if the target requires (and can make use of) the register
815326938Sdim  /// scavenger.
816326938Sdim  virtual bool requiresRegisterScavenging(const MachineFunction &MF) const {
817326938Sdim    return false;
818326938Sdim  }
819326938Sdim
820326938Sdim  /// Returns true if the target wants to use frame pointer based accesses to
821326938Sdim  /// spill to the scavenger emergency spill slot.
822326938Sdim  virtual bool useFPForScavengingIndex(const MachineFunction &MF) const {
823326938Sdim    return true;
824326938Sdim  }
825326938Sdim
826326938Sdim  /// Returns true if the target requires post PEI scavenging of registers for
827326938Sdim  /// materializing frame index constants.
828326938Sdim  virtual bool requiresFrameIndexScavenging(const MachineFunction &MF) const {
829326938Sdim    return false;
830326938Sdim  }
831326938Sdim
832326938Sdim  /// Returns true if the target requires using the RegScavenger directly for
833326938Sdim  /// frame elimination despite using requiresFrameIndexScavenging.
834326938Sdim  virtual bool requiresFrameIndexReplacementScavenging(
835326938Sdim      const MachineFunction &MF) const {
836326938Sdim    return false;
837326938Sdim  }
838326938Sdim
839326938Sdim  /// Returns true if the target wants the LocalStackAllocation pass to be run
840326938Sdim  /// and virtual base registers used for more efficient stack access.
841326938Sdim  virtual bool requiresVirtualBaseRegisters(const MachineFunction &MF) const {
842326938Sdim    return false;
843326938Sdim  }
844326938Sdim
845326938Sdim  /// Return true if target has reserved a spill slot in the stack frame of
846326938Sdim  /// the given function for the specified register. e.g. On x86, if the frame
847326938Sdim  /// register is required, the first fixed stack object is reserved as its
848326938Sdim  /// spill slot. This tells PEI not to create a new stack frame
849326938Sdim  /// object for the given register. It should be called only after
850326938Sdim  /// determineCalleeSaves().
851326938Sdim  virtual bool hasReservedSpillSlot(const MachineFunction &MF, unsigned Reg,
852326938Sdim                                    int &FrameIdx) const {
853326938Sdim    return false;
854326938Sdim  }
855326938Sdim
856326938Sdim  /// Returns true if the live-ins should be tracked after register allocation.
857326938Sdim  virtual bool trackLivenessAfterRegAlloc(const MachineFunction &MF) const {
858326938Sdim    return false;
859326938Sdim  }
860326938Sdim
861326938Sdim  /// True if the stack can be realigned for the target.
862326938Sdim  virtual bool canRealignStack(const MachineFunction &MF) const;
863326938Sdim
864326938Sdim  /// True if storage within the function requires the stack pointer to be
865326938Sdim  /// aligned more than the normal calling convention calls for.
866326938Sdim  /// This cannot be overriden by the target, but canRealignStack can be
867326938Sdim  /// overridden.
868326938Sdim  bool needsStackRealignment(const MachineFunction &MF) const;
869326938Sdim
870326938Sdim  /// Get the offset from the referenced frame index in the instruction,
871326938Sdim  /// if there is one.
872326938Sdim  virtual int64_t getFrameIndexInstrOffset(const MachineInstr *MI,
873326938Sdim                                           int Idx) const {
874326938Sdim    return 0;
875326938Sdim  }
876326938Sdim
877326938Sdim  /// Returns true if the instruction's frame index reference would be better
878326938Sdim  /// served by a base register other than FP or SP.
879326938Sdim  /// Used by LocalStackFrameAllocation to determine which frame index
880326938Sdim  /// references it should create new base registers for.
881326938Sdim  virtual bool needsFrameBaseReg(MachineInstr *MI, int64_t Offset) const {
882326938Sdim    return false;
883326938Sdim  }
884326938Sdim
885326938Sdim  /// Insert defining instruction(s) for BaseReg to be a pointer to FrameIdx
886326938Sdim  /// before insertion point I.
887326938Sdim  virtual void materializeFrameBaseRegister(MachineBasicBlock *MBB,
888326938Sdim                                            unsigned BaseReg, int FrameIdx,
889326938Sdim                                            int64_t Offset) const {
890326938Sdim    llvm_unreachable("materializeFrameBaseRegister does not exist on this "
891326938Sdim                     "target");
892326938Sdim  }
893326938Sdim
894326938Sdim  /// Resolve a frame index operand of an instruction
895326938Sdim  /// to reference the indicated base register plus offset instead.
896326938Sdim  virtual void resolveFrameIndex(MachineInstr &MI, unsigned BaseReg,
897326938Sdim                                 int64_t Offset) const {
898326938Sdim    llvm_unreachable("resolveFrameIndex does not exist on this target");
899326938Sdim  }
900326938Sdim
901326938Sdim  /// Determine whether a given base register plus offset immediate is
902326938Sdim  /// encodable to resolve a frame index.
903326938Sdim  virtual bool isFrameOffsetLegal(const MachineInstr *MI, unsigned BaseReg,
904326938Sdim                                  int64_t Offset) const {
905326938Sdim    llvm_unreachable("isFrameOffsetLegal does not exist on this target");
906326938Sdim  }
907326938Sdim
908326938Sdim  /// Spill the register so it can be used by the register scavenger.
909326938Sdim  /// Return true if the register was spilled, false otherwise.
910326938Sdim  /// If this function does not spill the register, the scavenger
911326938Sdim  /// will instead spill it to the emergency spill slot.
912326938Sdim  virtual bool saveScavengerRegister(MachineBasicBlock &MBB,
913326938Sdim                                     MachineBasicBlock::iterator I,
914326938Sdim                                     MachineBasicBlock::iterator &UseMI,
915326938Sdim                                     const TargetRegisterClass *RC,
916326938Sdim                                     unsigned Reg) const {
917326938Sdim    return false;
918326938Sdim  }
919326938Sdim
920326938Sdim  /// This method must be overriden to eliminate abstract frame indices from
921326938Sdim  /// instructions which may use them. The instruction referenced by the
922326938Sdim  /// iterator contains an MO_FrameIndex operand which must be eliminated by
923326938Sdim  /// this method. This method may modify or replace the specified instruction,
924326938Sdim  /// as long as it keeps the iterator pointing at the finished product.
925326938Sdim  /// SPAdj is the SP adjustment due to call frame setup instruction.
926326938Sdim  /// FIOperandNum is the FI operand number.
927326938Sdim  virtual void eliminateFrameIndex(MachineBasicBlock::iterator MI,
928326938Sdim                                   int SPAdj, unsigned FIOperandNum,
929326938Sdim                                   RegScavenger *RS = nullptr) const = 0;
930326938Sdim
931326938Sdim  /// Return the assembly name for \p Reg.
932326938Sdim  virtual StringRef getRegAsmName(unsigned Reg) const {
933326938Sdim    // FIXME: We are assuming that the assembly name is equal to the TableGen
934326938Sdim    // name converted to lower case
935326938Sdim    //
936326938Sdim    // The TableGen name is the name of the definition for this register in the
937326938Sdim    // target's tablegen files.  For example, the TableGen name of
938326938Sdim    // def EAX : Register <...>; is "EAX"
939326938Sdim    return StringRef(getName(Reg));
940326938Sdim  }
941326938Sdim
942326938Sdim  //===--------------------------------------------------------------------===//
943326938Sdim  /// Subtarget Hooks
944326938Sdim
945341825Sdim  /// SrcRC and DstRC will be morphed into NewRC if this returns true.
946326938Sdim  virtual bool shouldCoalesce(MachineInstr *MI,
947326938Sdim                              const TargetRegisterClass *SrcRC,
948326938Sdim                              unsigned SubReg,
949326938Sdim                              const TargetRegisterClass *DstRC,
950326938Sdim                              unsigned DstSubReg,
951326938Sdim                              const TargetRegisterClass *NewRC,
952326938Sdim                              LiveIntervals &LIS) const
953326938Sdim  { return true; }
954326938Sdim
955326938Sdim  //===--------------------------------------------------------------------===//
956326938Sdim  /// Debug information queries.
957326938Sdim
958326938Sdim  /// getFrameRegister - This method should return the register used as a base
959326938Sdim  /// for values allocated in the current stack frame.
960353358Sdim  virtual Register getFrameRegister(const MachineFunction &MF) const = 0;
961326938Sdim
962326938Sdim  /// Mark a register and all its aliases as reserved in the given set.
963326938Sdim  void markSuperRegs(BitVector &RegisterSet, unsigned Reg) const;
964326938Sdim
965326938Sdim  /// Returns true if for every register in the set all super registers are part
966326938Sdim  /// of the set as well.
967326938Sdim  bool checkAllSuperRegsMarked(const BitVector &RegisterSet,
968326938Sdim      ArrayRef<MCPhysReg> Exceptions = ArrayRef<MCPhysReg>()) const;
969341825Sdim
970341825Sdim  virtual const TargetRegisterClass *
971341825Sdim  getConstrainedRegClassForOperand(const MachineOperand &MO,
972341825Sdim                                   const MachineRegisterInfo &MRI) const {
973341825Sdim    return nullptr;
974341825Sdim  }
975360784Sdim
976360784Sdim  /// Returns the physical register number of sub-register "Index"
977360784Sdim  /// for physical register RegNo. Return zero if the sub-register does not
978360784Sdim  /// exist.
979360784Sdim  inline Register getSubReg(MCRegister Reg, unsigned Idx) const {
980360784Sdim    return static_cast<const MCRegisterInfo *>(this)->getSubReg(Reg, Idx);
981360784Sdim  }
982326938Sdim};
983326938Sdim
984326938Sdim//===----------------------------------------------------------------------===//
985326938Sdim//                           SuperRegClassIterator
986326938Sdim//===----------------------------------------------------------------------===//
987326938Sdim//
988326938Sdim// Iterate over the possible super-registers for a given register class. The
989326938Sdim// iterator will visit a list of pairs (Idx, Mask) corresponding to the
990326938Sdim// possible classes of super-registers.
991326938Sdim//
992326938Sdim// Each bit mask will have at least one set bit, and each set bit in Mask
993326938Sdim// corresponds to a SuperRC such that:
994326938Sdim//
995326938Sdim//   For all Reg in SuperRC: Reg:Idx is in RC.
996326938Sdim//
997326938Sdim// The iterator can include (O, RC->getSubClassMask()) as the first entry which
998326938Sdim// also satisfies the above requirement, assuming Reg:0 == Reg.
999326938Sdim//
1000326938Sdimclass SuperRegClassIterator {
1001326938Sdim  const unsigned RCMaskWords;
1002326938Sdim  unsigned SubReg = 0;
1003326938Sdim  const uint16_t *Idx;
1004326938Sdim  const uint32_t *Mask;
1005326938Sdim
1006326938Sdimpublic:
1007326938Sdim  /// Create a SuperRegClassIterator that visits all the super-register classes
1008326938Sdim  /// of RC. When IncludeSelf is set, also include the (0, sub-classes) entry.
1009326938Sdim  SuperRegClassIterator(const TargetRegisterClass *RC,
1010326938Sdim                        const TargetRegisterInfo *TRI,
1011326938Sdim                        bool IncludeSelf = false)
1012326938Sdim    : RCMaskWords((TRI->getNumRegClasses() + 31) / 32),
1013326938Sdim      Idx(RC->getSuperRegIndices()), Mask(RC->getSubClassMask()) {
1014326938Sdim    if (!IncludeSelf)
1015326938Sdim      ++*this;
1016326938Sdim  }
1017326938Sdim
1018326938Sdim  /// Returns true if this iterator is still pointing at a valid entry.
1019326938Sdim  bool isValid() const { return Idx; }
1020326938Sdim
1021326938Sdim  /// Returns the current sub-register index.
1022326938Sdim  unsigned getSubReg() const { return SubReg; }
1023326938Sdim
1024326938Sdim  /// Returns the bit mask of register classes that getSubReg() projects into
1025326938Sdim  /// RC.
1026326938Sdim  /// See TargetRegisterClass::getSubClassMask() for how to use it.
1027326938Sdim  const uint32_t *getMask() const { return Mask; }
1028326938Sdim
1029326938Sdim  /// Advance iterator to the next entry.
1030326938Sdim  void operator++() {
1031326938Sdim    assert(isValid() && "Cannot move iterator past end.");
1032326938Sdim    Mask += RCMaskWords;
1033326938Sdim    SubReg = *Idx++;
1034326938Sdim    if (!SubReg)
1035326938Sdim      Idx = nullptr;
1036326938Sdim  }
1037326938Sdim};
1038326938Sdim
1039326938Sdim//===----------------------------------------------------------------------===//
1040326938Sdim//                           BitMaskClassIterator
1041326938Sdim//===----------------------------------------------------------------------===//
1042326938Sdim/// This class encapuslates the logic to iterate over bitmask returned by
1043326938Sdim/// the various RegClass related APIs.
1044326938Sdim/// E.g., this class can be used to iterate over the subclasses provided by
1045326938Sdim/// TargetRegisterClass::getSubClassMask or SuperRegClassIterator::getMask.
1046326938Sdimclass BitMaskClassIterator {
1047326938Sdim  /// Total number of register classes.
1048326938Sdim  const unsigned NumRegClasses;
1049326938Sdim  /// Base index of CurrentChunk.
1050326938Sdim  /// In other words, the number of bit we read to get at the
1051326938Sdim  /// beginning of that chunck.
1052326938Sdim  unsigned Base = 0;
1053326938Sdim  /// Adjust base index of CurrentChunk.
1054326938Sdim  /// Base index + how many bit we read within CurrentChunk.
1055326938Sdim  unsigned Idx = 0;
1056326938Sdim  /// Current register class ID.
1057326938Sdim  unsigned ID = 0;
1058326938Sdim  /// Mask we are iterating over.
1059326938Sdim  const uint32_t *Mask;
1060326938Sdim  /// Current chunk of the Mask we are traversing.
1061326938Sdim  uint32_t CurrentChunk;
1062326938Sdim
1063326938Sdim  /// Move ID to the next set bit.
1064326938Sdim  void moveToNextID() {
1065326938Sdim    // If the current chunk of memory is empty, move to the next one,
1066326938Sdim    // while making sure we do not go pass the number of register
1067326938Sdim    // classes.
1068326938Sdim    while (!CurrentChunk) {
1069326938Sdim      // Move to the next chunk.
1070326938Sdim      Base += 32;
1071326938Sdim      if (Base >= NumRegClasses) {
1072326938Sdim        ID = NumRegClasses;
1073326938Sdim        return;
1074326938Sdim      }
1075326938Sdim      CurrentChunk = *++Mask;
1076326938Sdim      Idx = Base;
1077326938Sdim    }
1078326938Sdim    // Otherwise look for the first bit set from the right
1079326938Sdim    // (representation of the class ID is big endian).
1080326938Sdim    // See getSubClassMask for more details on the representation.
1081326938Sdim    unsigned Offset = countTrailingZeros(CurrentChunk);
1082326938Sdim    // Add the Offset to the adjusted base number of this chunk: Idx.
1083326938Sdim    // This is the ID of the register class.
1084326938Sdim    ID = Idx + Offset;
1085326938Sdim
1086326938Sdim    // Consume the zeros, if any, and the bit we just read
1087326938Sdim    // so that we are at the right spot for the next call.
1088326938Sdim    // Do not do Offset + 1 because Offset may be 31 and 32
1089326938Sdim    // will be UB for the shift, though in that case we could
1090326938Sdim    // have make the chunk being equal to 0, but that would
1091326938Sdim    // have introduced a if statement.
1092326938Sdim    moveNBits(Offset);
1093326938Sdim    moveNBits(1);
1094326938Sdim  }
1095326938Sdim
1096326938Sdim  /// Move \p NumBits Bits forward in CurrentChunk.
1097326938Sdim  void moveNBits(unsigned NumBits) {
1098326938Sdim    assert(NumBits < 32 && "Undefined behavior spotted!");
1099326938Sdim    // Consume the bit we read for the next call.
1100326938Sdim    CurrentChunk >>= NumBits;
1101326938Sdim    // Adjust the base for the chunk.
1102326938Sdim    Idx += NumBits;
1103326938Sdim  }
1104326938Sdim
1105326938Sdimpublic:
1106326938Sdim  /// Create a BitMaskClassIterator that visits all the register classes
1107326938Sdim  /// represented by \p Mask.
1108326938Sdim  ///
1109326938Sdim  /// \pre \p Mask != nullptr
1110326938Sdim  BitMaskClassIterator(const uint32_t *Mask, const TargetRegisterInfo &TRI)
1111326938Sdim      : NumRegClasses(TRI.getNumRegClasses()), Mask(Mask), CurrentChunk(*Mask) {
1112326938Sdim    // Move to the first ID.
1113326938Sdim    moveToNextID();
1114326938Sdim  }
1115326938Sdim
1116326938Sdim  /// Returns true if this iterator is still pointing at a valid entry.
1117326938Sdim  bool isValid() const { return getID() != NumRegClasses; }
1118326938Sdim
1119326938Sdim  /// Returns the current register class ID.
1120326938Sdim  unsigned getID() const { return ID; }
1121326938Sdim
1122326938Sdim  /// Advance iterator to the next entry.
1123326938Sdim  void operator++() {
1124326938Sdim    assert(isValid() && "Cannot move iterator past end.");
1125326938Sdim    moveToNextID();
1126326938Sdim  }
1127326938Sdim};
1128326938Sdim
1129326938Sdim// This is useful when building IndexedMaps keyed on virtual registers
1130326938Sdimstruct VirtReg2IndexFunctor {
1131326938Sdim  using argument_type = unsigned;
1132326938Sdim  unsigned operator()(unsigned Reg) const {
1133360784Sdim    return Register::virtReg2Index(Reg);
1134326938Sdim  }
1135326938Sdim};
1136326938Sdim
1137326938Sdim/// Prints virtual and physical registers with or without a TRI instance.
1138326938Sdim///
1139326938Sdim/// The format is:
1140326938Sdim///   %noreg          - NoRegister
1141326938Sdim///   %5              - a virtual register.
1142326938Sdim///   %5:sub_8bit     - a virtual register with sub-register index (with TRI).
1143326938Sdim///   %eax            - a physical register
1144326938Sdim///   %physreg17      - a physical register when no TRI instance given.
1145326938Sdim///
1146326938Sdim/// Usage: OS << printReg(Reg, TRI, SubRegIdx) << '\n';
1147360784SdimPrintable printReg(Register Reg, const TargetRegisterInfo *TRI = nullptr,
1148341825Sdim                   unsigned SubIdx = 0,
1149341825Sdim                   const MachineRegisterInfo *MRI = nullptr);
1150326938Sdim
1151326938Sdim/// Create Printable object to print register units on a \ref raw_ostream.
1152326938Sdim///
1153326938Sdim/// Register units are named after their root registers:
1154326938Sdim///
1155326938Sdim///   al      - Single root.
1156326938Sdim///   fp0~st7 - Dual roots.
1157326938Sdim///
1158326938Sdim/// Usage: OS << printRegUnit(Unit, TRI) << '\n';
1159326938SdimPrintable printRegUnit(unsigned Unit, const TargetRegisterInfo *TRI);
1160326938Sdim
1161341825Sdim/// Create Printable object to print virtual registers and physical
1162326938Sdim/// registers on a \ref raw_ostream.
1163326938SdimPrintable printVRegOrUnit(unsigned VRegOrUnit, const TargetRegisterInfo *TRI);
1164326938Sdim
1165341825Sdim/// Create Printable object to print register classes or register banks
1166326938Sdim/// on a \ref raw_ostream.
1167326938SdimPrintable printRegClassOrBank(unsigned Reg, const MachineRegisterInfo &RegInfo,
1168326938Sdim                              const TargetRegisterInfo *TRI);
1169326938Sdim
1170326938Sdim} // end namespace llvm
1171326938Sdim
1172326938Sdim#endif // LLVM_CODEGEN_TARGETREGISTERINFO_H
1173