1 //===- MC/MCRegisterInfo.h - Target Register Description --------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file describes an abstract interface used to get information about a
10 // target machines register file.  This information is used for a variety of
11 // purposed, especially register allocation.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #ifndef LLVM_MC_MCREGISTERINFO_H
16 #define LLVM_MC_MCREGISTERINFO_H
17 
18 #include "llvm/ADT/DenseMap.h"
19 #include "llvm/ADT/iterator.h"
20 #include "llvm/ADT/iterator_range.h"
21 #include "llvm/MC/LaneBitmask.h"
22 #include "llvm/MC/MCRegister.h"
23 #include <cassert>
24 #include <cstdint>
25 #include <iterator>
26 #include <utility>
27 
28 namespace llvm {
29 
30 class MipsABIInfo; // To update RA after creation
31 
32 /// MCRegisterClass - Base class of TargetRegisterClass.
33 class MCRegisterClass {
34 public:
35   using iterator = const MCPhysReg*;
36   using const_iterator = const MCPhysReg*;
37 
38   const iterator RegsBegin;
39   const uint8_t *const RegSet;
40   const uint32_t NameIdx;
41   const uint16_t RegsSize;
42   const uint16_t RegSetSize;
43   const uint16_t ID;
44   const int8_t CopyCost;
45   const bool Allocatable;
46 
47   /// getID() - Return the register class ID number.
48   ///
getID()49   unsigned getID() const { return ID; }
50 
51   /// begin/end - Return all of the registers in this class.
52   ///
begin()53   iterator       begin() const { return RegsBegin; }
end()54   iterator         end() const { return RegsBegin + RegsSize; }
55 
56   /// getNumRegs - Return the number of registers in this class.
57   ///
getNumRegs()58   unsigned getNumRegs() const { return RegsSize; }
59 
60   /// getRegister - Return the specified register in the class.
61   ///
getRegister(unsigned i)62   unsigned getRegister(unsigned i) const {
63     assert(i < getNumRegs() && "Register number out of range!");
64     return RegsBegin[i];
65   }
66 
67   /// contains - Return true if the specified register is included in this
68   /// register class.  This does not include virtual registers.
contains(MCRegister Reg)69   bool contains(MCRegister Reg) const {
70     unsigned RegNo = unsigned(Reg);
71     unsigned InByte = RegNo % 8;
72     unsigned Byte = RegNo / 8;
73     if (Byte >= RegSetSize)
74       return false;
75     return (RegSet[Byte] & (1 << InByte)) != 0;
76   }
77 
78   /// contains - Return true if both registers are in this class.
contains(MCRegister Reg1,MCRegister Reg2)79   bool contains(MCRegister Reg1, MCRegister Reg2) const {
80     return contains(Reg1) && contains(Reg2);
81   }
82 
83   /// getCopyCost - Return the cost of copying a value between two registers in
84   /// this class. A negative number means the register class is very expensive
85   /// to copy e.g. status flag register classes.
getCopyCost()86   int getCopyCost() const { return CopyCost; }
87 
88   /// isAllocatable - Return true if this register class may be used to create
89   /// virtual registers.
isAllocatable()90   bool isAllocatable() const { return Allocatable; }
91 };
92 
93 /// MCRegisterDesc - This record contains information about a particular
94 /// register.  The SubRegs field is a zero terminated array of registers that
95 /// are sub-registers of the specific register, e.g. AL, AH are sub-registers
96 /// of AX. The SuperRegs field is a zero terminated array of registers that are
97 /// super-registers of the specific register, e.g. RAX, EAX, are
98 /// super-registers of AX.
99 ///
100 struct MCRegisterDesc {
101   uint32_t Name;      // Printable name for the reg (for debugging)
102   uint32_t SubRegs;   // Sub-register set, described above
103   uint32_t SuperRegs; // Super-register set, described above
104 
105   // Offset into MCRI::SubRegIndices of a list of sub-register indices for each
106   // sub-register in SubRegs.
107   uint32_t SubRegIndices;
108 
109   // RegUnits - Points to the list of register units. The low 4 bits holds the
110   // Scale, the high bits hold an offset into DiffLists. See MCRegUnitIterator.
111   uint32_t RegUnits;
112 
113   /// Index into list with lane mask sequences. The sequence contains a lanemask
114   /// for every register unit.
115   uint16_t RegUnitLaneMasks;
116 };
117 
118 /// MCRegisterInfo base class - We assume that the target defines a static
119 /// array of MCRegisterDesc objects that represent all of the machine
120 /// registers that the target has.  As such, we simply have to track a pointer
121 /// to this array so that we can turn register number into a register
122 /// descriptor.
123 ///
124 /// Note this class is designed to be a base class of TargetRegisterInfo, which
125 /// is the interface used by codegen. However, specific targets *should never*
126 /// specialize this class. MCRegisterInfo should only contain getters to access
127 /// TableGen generated physical register data. It must not be extended with
128 /// virtual methods.
129 ///
130 class MCRegisterInfo {
131 public:
132   using regclass_iterator = const MCRegisterClass *;
133 
134   /// DwarfLLVMRegPair - Emitted by tablegen so Dwarf<->LLVM reg mappings can be
135   /// performed with a binary search.
136   struct DwarfLLVMRegPair {
137     unsigned FromReg;
138     unsigned ToReg;
139 
140     bool operator<(DwarfLLVMRegPair RHS) const { return FromReg < RHS.FromReg; }
141   };
142 
143   /// SubRegCoveredBits - Emitted by tablegen: bit range covered by a subreg
144   /// index, -1 in any being invalid.
145   struct SubRegCoveredBits {
146     uint16_t Offset;
147     uint16_t Size;
148   };
149 
150 private:
151   const MCRegisterDesc *Desc;                 // Pointer to the descriptor array
152   unsigned NumRegs;                           // Number of entries in the array
153   MCRegister RAReg;                           // Return address register
154   MCRegister PCReg;                           // Program counter register
155   const MCRegisterClass *Classes;             // Pointer to the regclass array
156   unsigned NumClasses;                        // Number of entries in the array
157   unsigned NumRegUnits;                       // Number of regunits.
158   const MCPhysReg (*RegUnitRoots)[2];         // Pointer to regunit root table.
159   const MCPhysReg *DiffLists;                 // Pointer to the difflists array
160   const LaneBitmask *RegUnitMaskSequences;    // Pointer to lane mask sequences
161                                               // for register units.
162   const char *RegStrings;                     // Pointer to the string table.
163   const char *RegClassStrings;                // Pointer to the class strings.
164   const uint16_t *SubRegIndices;              // Pointer to the subreg lookup
165                                               // array.
166   const SubRegCoveredBits *SubRegIdxRanges;   // Pointer to the subreg covered
167                                               // bit ranges array.
168   unsigned NumSubRegIndices;                  // Number of subreg indices.
169   const uint16_t *RegEncodingTable;           // Pointer to array of register
170                                               // encodings.
171 
172   unsigned L2DwarfRegsSize;
173   unsigned EHL2DwarfRegsSize;
174   unsigned Dwarf2LRegsSize;
175   unsigned EHDwarf2LRegsSize;
176   const DwarfLLVMRegPair *L2DwarfRegs;        // LLVM to Dwarf regs mapping
177   const DwarfLLVMRegPair *EHL2DwarfRegs;      // LLVM to Dwarf regs mapping EH
178   const DwarfLLVMRegPair *Dwarf2LRegs;        // Dwarf to LLVM regs mapping
179   const DwarfLLVMRegPair *EHDwarf2LRegs;      // Dwarf to LLVM regs mapping EH
180   DenseMap<MCRegister, int> L2SEHRegs;        // LLVM to SEH regs mapping
181   DenseMap<MCRegister, int> L2CVRegs;         // LLVM to CV regs mapping
182 
183 public:
184   // Forward declaration to become a friend class of DiffListIterator.
185   template <class SubT> class mc_difflist_iterator;
186 
187   /// DiffListIterator - Base iterator class that can traverse the
188   /// differentially encoded register and regunit lists in DiffLists.
189   /// Don't use this class directly, use one of the specialized sub-classes
190   /// defined below.
191   class DiffListIterator {
192     uint16_t Val = 0;
193     const MCPhysReg *List = nullptr;
194 
195   protected:
196     /// Create an invalid iterator. Call init() to point to something useful.
197     DiffListIterator() = default;
198 
199     /// init - Point the iterator to InitVal, decoding subsequent values from
200     /// DiffList. The iterator will initially point to InitVal, sub-classes are
201     /// responsible for skipping the seed value if it is not part of the list.
init(MCPhysReg InitVal,const MCPhysReg * DiffList)202     void init(MCPhysReg InitVal, const MCPhysReg *DiffList) {
203       Val = InitVal;
204       List = DiffList;
205     }
206 
207     /// advance - Move to the next list position, return the applied
208     /// differential. This function does not detect the end of the list, that
209     /// is the caller's responsibility (by checking for a 0 return value).
advance()210     MCRegister advance() {
211       assert(isValid() && "Cannot move off the end of the list.");
212       MCPhysReg D = *List++;
213       Val += D;
214       return D;
215     }
216 
217   public:
218     /// isValid - returns true if this iterator is not yet at the end.
isValid()219     bool isValid() const { return List; }
220 
221     /// Dereference the iterator to get the value at the current position.
222     MCRegister operator*() const { return Val; }
223 
224     /// Pre-increment to move to the next position.
225     void operator++() {
226       // The end of the list is encoded as a 0 differential.
227       if (!advance())
228         List = nullptr;
229     }
230 
231     template <class SubT> friend class MCRegisterInfo::mc_difflist_iterator;
232   };
233 
234   /// Forward iterator using DiffListIterator.
235   template <class SubT>
236   class mc_difflist_iterator
237       : public iterator_facade_base<mc_difflist_iterator<SubT>,
238                                     std::forward_iterator_tag, MCPhysReg> {
239     MCRegisterInfo::DiffListIterator Iter;
240     /// Current value as MCPhysReg, so we can return a reference to it.
241     MCPhysReg Val;
242 
243   protected:
mc_difflist_iterator(MCRegisterInfo::DiffListIterator Iter)244     mc_difflist_iterator(MCRegisterInfo::DiffListIterator Iter) : Iter(Iter) {}
245 
246     // Allow conversion between instantiations where valid.
mc_difflist_iterator(MCRegister Reg,const MCPhysReg * DiffList)247     mc_difflist_iterator(MCRegister Reg, const MCPhysReg *DiffList) {
248       Iter.init(Reg, DiffList);
249       Val = *Iter;
250     }
251 
252   public:
253     // Allow default construction to build variables, but this doesn't build
254     // a useful iterator.
255     mc_difflist_iterator() = default;
256 
257     /// Return an iterator past the last element.
end()258     static SubT end() {
259       SubT End;
260       End.Iter.List = nullptr;
261       return End;
262     }
263 
264     bool operator==(const mc_difflist_iterator &Arg) const {
265       return Iter.List == Arg.Iter.List;
266     }
267 
268     const MCPhysReg &operator*() const { return Val; }
269 
270     using mc_difflist_iterator::iterator_facade_base::operator++;
271     void operator++() {
272       assert(Iter.List && "Cannot increment the end iterator!");
273       ++Iter;
274       Val = *Iter;
275     }
276   };
277 
278   /// Forward iterator over all sub-registers.
279   /// TODO: Replace remaining uses of MCSubRegIterator.
280   class mc_subreg_iterator : public mc_difflist_iterator<mc_subreg_iterator> {
281   public:
mc_subreg_iterator(MCRegisterInfo::DiffListIterator Iter)282     mc_subreg_iterator(MCRegisterInfo::DiffListIterator Iter)
283         : mc_difflist_iterator(Iter) {}
284     mc_subreg_iterator() = default;
mc_subreg_iterator(MCRegister Reg,const MCRegisterInfo * MCRI)285     mc_subreg_iterator(MCRegister Reg, const MCRegisterInfo *MCRI)
286         : mc_difflist_iterator(Reg, MCRI->DiffLists + MCRI->get(Reg).SubRegs) {}
287   };
288 
289   /// Forward iterator over all super-registers.
290   /// TODO: Replace remaining uses of MCSuperRegIterator.
291   class mc_superreg_iterator
292       : public mc_difflist_iterator<mc_superreg_iterator> {
293   public:
mc_superreg_iterator(MCRegisterInfo::DiffListIterator Iter)294     mc_superreg_iterator(MCRegisterInfo::DiffListIterator Iter)
295         : mc_difflist_iterator(Iter) {}
296     mc_superreg_iterator() = default;
mc_superreg_iterator(MCRegister Reg,const MCRegisterInfo * MCRI)297     mc_superreg_iterator(MCRegister Reg, const MCRegisterInfo *MCRI)
298         : mc_difflist_iterator(Reg,
299                                MCRI->DiffLists + MCRI->get(Reg).SuperRegs) {}
300   };
301 
302   /// Return an iterator range over all sub-registers of \p Reg, excluding \p
303   /// Reg.
subregs(MCRegister Reg)304   iterator_range<mc_subreg_iterator> subregs(MCRegister Reg) const {
305     return make_range(std::next(mc_subreg_iterator(Reg, this)),
306                       mc_subreg_iterator::end());
307   }
308 
309   /// Return an iterator range over all sub-registers of \p Reg, including \p
310   /// Reg.
subregs_inclusive(MCRegister Reg)311   iterator_range<mc_subreg_iterator> subregs_inclusive(MCRegister Reg) const {
312     return make_range({Reg, this}, mc_subreg_iterator::end());
313   }
314 
315   /// Return an iterator range over all super-registers of \p Reg, excluding \p
316   /// Reg.
superregs(MCRegister Reg)317   iterator_range<mc_superreg_iterator> superregs(MCRegister Reg) const {
318     return make_range(std::next(mc_superreg_iterator(Reg, this)),
319                       mc_superreg_iterator::end());
320   }
321 
322   /// Return an iterator range over all super-registers of \p Reg, including \p
323   /// Reg.
324   iterator_range<mc_superreg_iterator>
superregs_inclusive(MCRegister Reg)325   superregs_inclusive(MCRegister Reg) const {
326     return make_range({Reg, this}, mc_superreg_iterator::end());
327   }
328 
329   /// Return an iterator range over all sub- and super-registers of \p Reg,
330   /// including \p Reg.
331   detail::concat_range<const MCPhysReg, iterator_range<mc_subreg_iterator>,
332                        iterator_range<mc_superreg_iterator>>
sub_and_superregs_inclusive(MCRegister Reg)333   sub_and_superregs_inclusive(MCRegister Reg) const {
334     return concat<const MCPhysReg>(subregs_inclusive(Reg), superregs(Reg));
335   }
336 
337   // These iterators are allowed to sub-class DiffListIterator and access
338   // internal list pointers.
339   friend class MCSubRegIterator;
340   friend class MCSubRegIndexIterator;
341   friend class MCSuperRegIterator;
342   friend class MCRegUnitIterator;
343   friend class MCRegUnitMaskIterator;
344   friend class MCRegUnitRootIterator;
345   friend class MipsABIInfo; // Hack to update RA register after creation
346 
347   /// Initialize MCRegisterInfo, called by TableGen
348   /// auto-generated routines. *DO NOT USE*.
InitMCRegisterInfo(const MCRegisterDesc * D,unsigned NR,unsigned RA,unsigned PC,const MCRegisterClass * C,unsigned NC,const MCPhysReg (* RURoots)[2],unsigned NRU,const MCPhysReg * DL,const LaneBitmask * RUMS,const char * Strings,const char * ClassStrings,const uint16_t * SubIndices,unsigned NumIndices,const SubRegCoveredBits * SubIdxRanges,const uint16_t * RET)349   void InitMCRegisterInfo(const MCRegisterDesc *D, unsigned NR, unsigned RA,
350                           unsigned PC,
351                           const MCRegisterClass *C, unsigned NC,
352                           const MCPhysReg (*RURoots)[2],
353                           unsigned NRU,
354                           const MCPhysReg *DL,
355                           const LaneBitmask *RUMS,
356                           const char *Strings,
357                           const char *ClassStrings,
358                           const uint16_t *SubIndices,
359                           unsigned NumIndices,
360                           const SubRegCoveredBits *SubIdxRanges,
361                           const uint16_t *RET) {
362     Desc = D;
363     NumRegs = NR;
364     RAReg = RA;
365     PCReg = PC;
366     Classes = C;
367     DiffLists = DL;
368     RegUnitMaskSequences = RUMS;
369     RegStrings = Strings;
370     RegClassStrings = ClassStrings;
371     NumClasses = NC;
372     RegUnitRoots = RURoots;
373     NumRegUnits = NRU;
374     SubRegIndices = SubIndices;
375     NumSubRegIndices = NumIndices;
376     SubRegIdxRanges = SubIdxRanges;
377     RegEncodingTable = RET;
378 
379     // Initialize DWARF register mapping variables
380     EHL2DwarfRegs = nullptr;
381     EHL2DwarfRegsSize = 0;
382     L2DwarfRegs = nullptr;
383     L2DwarfRegsSize = 0;
384     EHDwarf2LRegs = nullptr;
385     EHDwarf2LRegsSize = 0;
386     Dwarf2LRegs = nullptr;
387     Dwarf2LRegsSize = 0;
388   }
389 
390   /// Used to initialize LLVM register to Dwarf
391   /// register number mapping. Called by TableGen auto-generated routines.
392   /// *DO NOT USE*.
mapLLVMRegsToDwarfRegs(const DwarfLLVMRegPair * Map,unsigned Size,bool isEH)393   void mapLLVMRegsToDwarfRegs(const DwarfLLVMRegPair *Map, unsigned Size,
394                               bool isEH) {
395     if (isEH) {
396       EHL2DwarfRegs = Map;
397       EHL2DwarfRegsSize = Size;
398     } else {
399       L2DwarfRegs = Map;
400       L2DwarfRegsSize = Size;
401     }
402   }
403 
404   /// Used to initialize Dwarf register to LLVM
405   /// register number mapping. Called by TableGen auto-generated routines.
406   /// *DO NOT USE*.
mapDwarfRegsToLLVMRegs(const DwarfLLVMRegPair * Map,unsigned Size,bool isEH)407   void mapDwarfRegsToLLVMRegs(const DwarfLLVMRegPair *Map, unsigned Size,
408                               bool isEH) {
409     if (isEH) {
410       EHDwarf2LRegs = Map;
411       EHDwarf2LRegsSize = Size;
412     } else {
413       Dwarf2LRegs = Map;
414       Dwarf2LRegsSize = Size;
415     }
416   }
417 
418   /// mapLLVMRegToSEHReg - Used to initialize LLVM register to SEH register
419   /// number mapping. By default the SEH register number is just the same
420   /// as the LLVM register number.
421   /// FIXME: TableGen these numbers. Currently this requires target specific
422   /// initialization code.
mapLLVMRegToSEHReg(MCRegister LLVMReg,int SEHReg)423   void mapLLVMRegToSEHReg(MCRegister LLVMReg, int SEHReg) {
424     L2SEHRegs[LLVMReg] = SEHReg;
425   }
426 
mapLLVMRegToCVReg(MCRegister LLVMReg,int CVReg)427   void mapLLVMRegToCVReg(MCRegister LLVMReg, int CVReg) {
428     L2CVRegs[LLVMReg] = CVReg;
429   }
430 
431   /// This method should return the register where the return
432   /// address can be found.
getRARegister()433   MCRegister getRARegister() const {
434     return RAReg;
435   }
436 
437   /// Return the register which is the program counter.
getProgramCounter()438   MCRegister getProgramCounter() const {
439     return PCReg;
440   }
441 
442   const MCRegisterDesc &operator[](MCRegister RegNo) const {
443     assert(RegNo < NumRegs &&
444            "Attempting to access record for invalid register number!");
445     return Desc[RegNo];
446   }
447 
448   /// Provide a get method, equivalent to [], but more useful with a
449   /// pointer to this object.
get(MCRegister RegNo)450   const MCRegisterDesc &get(MCRegister RegNo) const {
451     return operator[](RegNo);
452   }
453 
454   /// Returns the physical register number of sub-register "Index"
455   /// for physical register RegNo. Return zero if the sub-register does not
456   /// exist.
457   MCRegister getSubReg(MCRegister Reg, unsigned Idx) const;
458 
459   /// Return a super-register of the specified register
460   /// Reg so its sub-register of index SubIdx is Reg.
461   MCRegister getMatchingSuperReg(MCRegister Reg, unsigned SubIdx,
462                                  const MCRegisterClass *RC) const;
463 
464   /// For a given register pair, return the sub-register index
465   /// if the second register is a sub-register of the first. Return zero
466   /// otherwise.
467   unsigned getSubRegIndex(MCRegister RegNo, MCRegister SubRegNo) const;
468 
469   /// Get the size of the bit range covered by a sub-register index.
470   /// If the index isn't continuous, return the sum of the sizes of its parts.
471   /// If the index is used to access subregisters of different sizes, return -1.
472   unsigned getSubRegIdxSize(unsigned Idx) const;
473 
474   /// Get the offset of the bit range covered by a sub-register index.
475   /// If an Offset doesn't make sense (the index isn't continuous, or is used to
476   /// access sub-registers at different offsets), return -1.
477   unsigned getSubRegIdxOffset(unsigned Idx) const;
478 
479   /// Return the human-readable symbolic target-specific name for the
480   /// specified physical register.
getName(MCRegister RegNo)481   const char *getName(MCRegister RegNo) const {
482     return RegStrings + get(RegNo).Name;
483   }
484 
485   /// Return the number of registers this target has (useful for
486   /// sizing arrays holding per register information)
getNumRegs()487   unsigned getNumRegs() const {
488     return NumRegs;
489   }
490 
491   /// Return the number of sub-register indices
492   /// understood by the target. Index 0 is reserved for the no-op sub-register,
493   /// while 1 to getNumSubRegIndices() - 1 represent real sub-registers.
getNumSubRegIndices()494   unsigned getNumSubRegIndices() const {
495     return NumSubRegIndices;
496   }
497 
498   /// Return the number of (native) register units in the
499   /// target. Register units are numbered from 0 to getNumRegUnits() - 1. They
500   /// can be accessed through MCRegUnitIterator defined below.
getNumRegUnits()501   unsigned getNumRegUnits() const {
502     return NumRegUnits;
503   }
504 
505   /// Map a target register to an equivalent dwarf register
506   /// number.  Returns -1 if there is no equivalent value.  The second
507   /// parameter allows targets to use different numberings for EH info and
508   /// debugging info.
509   int getDwarfRegNum(MCRegister RegNum, bool isEH) const;
510 
511   /// Map a dwarf register back to a target register. Returns None is there is
512   /// no mapping.
513   Optional<unsigned> getLLVMRegNum(unsigned RegNum, bool isEH) const;
514 
515   /// Map a target EH register number to an equivalent DWARF register
516   /// number.
517   int getDwarfRegNumFromDwarfEHRegNum(unsigned RegNum) const;
518 
519   /// Map a target register to an equivalent SEH register
520   /// number.  Returns LLVM register number if there is no equivalent value.
521   int getSEHRegNum(MCRegister RegNum) const;
522 
523   /// Map a target register to an equivalent CodeView register
524   /// number.
525   int getCodeViewRegNum(MCRegister RegNum) const;
526 
regclass_begin()527   regclass_iterator regclass_begin() const { return Classes; }
regclass_end()528   regclass_iterator regclass_end() const { return Classes+NumClasses; }
regclasses()529   iterator_range<regclass_iterator> regclasses() const {
530     return make_range(regclass_begin(), regclass_end());
531   }
532 
getNumRegClasses()533   unsigned getNumRegClasses() const {
534     return (unsigned)(regclass_end()-regclass_begin());
535   }
536 
537   /// Returns the register class associated with the enumeration
538   /// value.  See class MCOperandInfo.
getRegClass(unsigned i)539   const MCRegisterClass& getRegClass(unsigned i) const {
540     assert(i < getNumRegClasses() && "Register Class ID out of range");
541     return Classes[i];
542   }
543 
getRegClassName(const MCRegisterClass * Class)544   const char *getRegClassName(const MCRegisterClass *Class) const {
545     return RegClassStrings + Class->NameIdx;
546   }
547 
548    /// Returns the encoding for RegNo
getEncodingValue(MCRegister RegNo)549   uint16_t getEncodingValue(MCRegister RegNo) const {
550     assert(RegNo < NumRegs &&
551            "Attempting to get encoding for invalid register number!");
552     return RegEncodingTable[RegNo];
553   }
554 
555   /// Returns true if RegB is a sub-register of RegA.
isSubRegister(MCRegister RegA,MCRegister RegB)556   bool isSubRegister(MCRegister RegA, MCRegister RegB) const {
557     return isSuperRegister(RegB, RegA);
558   }
559 
560   /// Returns true if RegB is a super-register of RegA.
561   bool isSuperRegister(MCRegister RegA, MCRegister RegB) const;
562 
563   /// Returns true if RegB is a sub-register of RegA or if RegB == RegA.
isSubRegisterEq(MCRegister RegA,MCRegister RegB)564   bool isSubRegisterEq(MCRegister RegA, MCRegister RegB) const {
565     return isSuperRegisterEq(RegB, RegA);
566   }
567 
568   /// Returns true if RegB is a super-register of RegA or if
569   /// RegB == RegA.
isSuperRegisterEq(MCRegister RegA,MCRegister RegB)570   bool isSuperRegisterEq(MCRegister RegA, MCRegister RegB) const {
571     return RegA == RegB || isSuperRegister(RegA, RegB);
572   }
573 
574   /// Returns true if RegB is a super-register or sub-register of RegA
575   /// or if RegB == RegA.
isSuperOrSubRegisterEq(MCRegister RegA,MCRegister RegB)576   bool isSuperOrSubRegisterEq(MCRegister RegA, MCRegister RegB) const {
577     return isSubRegisterEq(RegA, RegB) || isSuperRegister(RegA, RegB);
578   }
579 };
580 
581 //===----------------------------------------------------------------------===//
582 //                          Register List Iterators
583 //===----------------------------------------------------------------------===//
584 
585 // MCRegisterInfo provides lists of super-registers, sub-registers, and
586 // aliasing registers. Use these iterator classes to traverse the lists.
587 
588 /// MCSubRegIterator enumerates all sub-registers of Reg.
589 /// If IncludeSelf is set, Reg itself is included in the list.
590 class MCSubRegIterator : public MCRegisterInfo::DiffListIterator {
591 public:
592   MCSubRegIterator(MCRegister Reg, const MCRegisterInfo *MCRI,
593                    bool IncludeSelf = false) {
594     init(Reg, MCRI->DiffLists + MCRI->get(Reg).SubRegs);
595     // Initially, the iterator points to Reg itself.
596     if (!IncludeSelf)
597       ++*this;
598   }
599 };
600 
601 /// Iterator that enumerates the sub-registers of a Reg and the associated
602 /// sub-register indices.
603 class MCSubRegIndexIterator {
604   MCSubRegIterator SRIter;
605   const uint16_t *SRIndex;
606 
607 public:
608   /// Constructs an iterator that traverses subregisters and their
609   /// associated subregister indices.
MCSubRegIndexIterator(MCRegister Reg,const MCRegisterInfo * MCRI)610   MCSubRegIndexIterator(MCRegister Reg, const MCRegisterInfo *MCRI)
611     : SRIter(Reg, MCRI) {
612     SRIndex = MCRI->SubRegIndices + MCRI->get(Reg).SubRegIndices;
613   }
614 
615   /// Returns current sub-register.
getSubReg()616   MCRegister getSubReg() const {
617     return *SRIter;
618   }
619 
620   /// Returns sub-register index of the current sub-register.
getSubRegIndex()621   unsigned getSubRegIndex() const {
622     return *SRIndex;
623   }
624 
625   /// Returns true if this iterator is not yet at the end.
isValid()626   bool isValid() const { return SRIter.isValid(); }
627 
628   /// Moves to the next position.
629   void operator++() {
630     ++SRIter;
631     ++SRIndex;
632   }
633 };
634 
635 /// MCSuperRegIterator enumerates all super-registers of Reg.
636 /// If IncludeSelf is set, Reg itself is included in the list.
637 class MCSuperRegIterator : public MCRegisterInfo::DiffListIterator {
638 public:
639   MCSuperRegIterator() = default;
640 
641   MCSuperRegIterator(MCRegister Reg, const MCRegisterInfo *MCRI,
642                      bool IncludeSelf = false) {
643     init(Reg, MCRI->DiffLists + MCRI->get(Reg).SuperRegs);
644     // Initially, the iterator points to Reg itself.
645     if (!IncludeSelf)
646       ++*this;
647   }
648 };
649 
650 // Definition for isSuperRegister. Put it down here since it needs the
651 // iterator defined above in addition to the MCRegisterInfo class itself.
isSuperRegister(MCRegister RegA,MCRegister RegB)652 inline bool MCRegisterInfo::isSuperRegister(MCRegister RegA, MCRegister RegB) const{
653   for (MCSuperRegIterator I(RegA, this); I.isValid(); ++I)
654     if (*I == RegB)
655       return true;
656   return false;
657 }
658 
659 //===----------------------------------------------------------------------===//
660 //                               Register Units
661 //===----------------------------------------------------------------------===//
662 
663 // Register units are used to compute register aliasing. Every register has at
664 // least one register unit, but it can have more. Two registers overlap if and
665 // only if they have a common register unit.
666 //
667 // A target with a complicated sub-register structure will typically have many
668 // fewer register units than actual registers. MCRI::getNumRegUnits() returns
669 // the number of register units in the target.
670 
671 // MCRegUnitIterator enumerates a list of register units for Reg. The list is
672 // in ascending numerical order.
673 class MCRegUnitIterator : public MCRegisterInfo::DiffListIterator {
674 public:
675   /// MCRegUnitIterator - Create an iterator that traverses the register units
676   /// in Reg.
677   MCRegUnitIterator() = default;
678 
MCRegUnitIterator(MCRegister Reg,const MCRegisterInfo * MCRI)679   MCRegUnitIterator(MCRegister Reg, const MCRegisterInfo *MCRI) {
680     assert(Reg && "Null register has no regunits");
681     // Decode the RegUnits MCRegisterDesc field.
682     unsigned RU = MCRI->get(Reg).RegUnits;
683     unsigned Scale = RU & 15;
684     unsigned Offset = RU >> 4;
685 
686     // Initialize the iterator to Reg * Scale, and the List pointer to
687     // DiffLists + Offset.
688     init(Reg * Scale, MCRI->DiffLists + Offset);
689 
690     // That may not be a valid unit, we need to advance by one to get the real
691     // unit number. The first differential can be 0 which would normally
692     // terminate the list, but since we know every register has at least one
693     // unit, we can allow a 0 differential here.
694     advance();
695   }
696 };
697 
698 /// MCRegUnitMaskIterator enumerates a list of register units and their
699 /// associated lane masks for Reg. The register units are in ascending
700 /// numerical order.
701 class MCRegUnitMaskIterator {
702   MCRegUnitIterator RUIter;
703   const LaneBitmask *MaskListIter;
704 
705 public:
706   MCRegUnitMaskIterator() = default;
707 
708   /// Constructs an iterator that traverses the register units and their
709   /// associated LaneMasks in Reg.
MCRegUnitMaskIterator(MCRegister Reg,const MCRegisterInfo * MCRI)710   MCRegUnitMaskIterator(MCRegister Reg, const MCRegisterInfo *MCRI)
711     : RUIter(Reg, MCRI) {
712       uint16_t Idx = MCRI->get(Reg).RegUnitLaneMasks;
713       MaskListIter = &MCRI->RegUnitMaskSequences[Idx];
714   }
715 
716   /// Returns a (RegUnit, LaneMask) pair.
717   std::pair<unsigned,LaneBitmask> operator*() const {
718     return std::make_pair(*RUIter, *MaskListIter);
719   }
720 
721   /// Returns true if this iterator is not yet at the end.
isValid()722   bool isValid() const { return RUIter.isValid(); }
723 
724   /// Moves to the next position.
725   void operator++() {
726     ++MaskListIter;
727     ++RUIter;
728   }
729 };
730 
731 // Each register unit has one or two root registers. The complete set of
732 // registers containing a register unit is the union of the roots and their
733 // super-registers. All registers aliasing Unit can be visited like this:
734 //
735 //   for (MCRegUnitRootIterator RI(Unit, MCRI); RI.isValid(); ++RI) {
736 //     for (MCSuperRegIterator SI(*RI, MCRI, true); SI.isValid(); ++SI)
737 //       visit(*SI);
738 //    }
739 
740 /// MCRegUnitRootIterator enumerates the root registers of a register unit.
741 class MCRegUnitRootIterator {
742   uint16_t Reg0 = 0;
743   uint16_t Reg1 = 0;
744 
745 public:
746   MCRegUnitRootIterator() = default;
747 
MCRegUnitRootIterator(unsigned RegUnit,const MCRegisterInfo * MCRI)748   MCRegUnitRootIterator(unsigned RegUnit, const MCRegisterInfo *MCRI) {
749     assert(RegUnit < MCRI->getNumRegUnits() && "Invalid register unit");
750     Reg0 = MCRI->RegUnitRoots[RegUnit][0];
751     Reg1 = MCRI->RegUnitRoots[RegUnit][1];
752   }
753 
754   /// Dereference to get the current root register.
755   unsigned operator*() const {
756     return Reg0;
757   }
758 
759   /// Check if the iterator is at the end of the list.
isValid()760   bool isValid() const {
761     return Reg0;
762   }
763 
764   /// Preincrement to move to the next root register.
765   void operator++() {
766     assert(isValid() && "Cannot move off the end of the list.");
767     Reg0 = Reg1;
768     Reg1 = 0;
769   }
770 };
771 
772 /// MCRegAliasIterator enumerates all registers aliasing Reg.  If IncludeSelf is
773 /// set, Reg itself is included in the list.  This iterator does not guarantee
774 /// any ordering or that entries are unique.
775 class MCRegAliasIterator {
776 private:
777   MCRegister Reg;
778   const MCRegisterInfo *MCRI;
779   bool IncludeSelf;
780 
781   MCRegUnitIterator RI;
782   MCRegUnitRootIterator RRI;
783   MCSuperRegIterator SI;
784 
785 public:
MCRegAliasIterator(MCRegister Reg,const MCRegisterInfo * MCRI,bool IncludeSelf)786   MCRegAliasIterator(MCRegister Reg, const MCRegisterInfo *MCRI,
787                      bool IncludeSelf)
788     : Reg(Reg), MCRI(MCRI), IncludeSelf(IncludeSelf) {
789     // Initialize the iterators.
790     for (RI = MCRegUnitIterator(Reg, MCRI); RI.isValid(); ++RI) {
791       for (RRI = MCRegUnitRootIterator(*RI, MCRI); RRI.isValid(); ++RRI) {
792         for (SI = MCSuperRegIterator(*RRI, MCRI, true); SI.isValid(); ++SI) {
793           if (!(!IncludeSelf && Reg == *SI))
794             return;
795         }
796       }
797     }
798   }
799 
isValid()800   bool isValid() const { return RI.isValid(); }
801 
802   MCRegister operator*() const {
803     assert(SI.isValid() && "Cannot dereference an invalid iterator.");
804     return *SI;
805   }
806 
advance()807   void advance() {
808     // Assuming SI is valid.
809     ++SI;
810     if (SI.isValid()) return;
811 
812     ++RRI;
813     if (RRI.isValid()) {
814       SI = MCSuperRegIterator(*RRI, MCRI, true);
815       return;
816     }
817 
818     ++RI;
819     if (RI.isValid()) {
820       RRI = MCRegUnitRootIterator(*RI, MCRI);
821       SI = MCSuperRegIterator(*RRI, MCRI, true);
822     }
823   }
824 
825   void operator++() {
826     assert(isValid() && "Cannot move off the end of the list.");
827     do advance();
828     while (!IncludeSelf && isValid() && *SI == Reg);
829   }
830 };
831 
832 } // end namespace llvm
833 
834 #endif // LLVM_MC_MCREGISTERINFO_H
835