MCRegisterInfo.h revision 303c909d5bb014fbeec395090eb467d724969195
1//=== MC/MCRegisterInfo.h - Target Register Description ---------*- C++ -*-===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file describes an abstract interface used to get information about a
11// target machines register file.  This information is used for a variety of
12// purposed, especially register allocation.
13//
14//===----------------------------------------------------------------------===//
15
16#ifndef LLVM_MC_MCREGISTERINFO_H
17#define LLVM_MC_MCREGISTERINFO_H
18
19#include "llvm/ADT/DenseMap.h"
20#include "llvm/Support/ErrorHandling.h"
21#include <cassert>
22
23namespace llvm {
24
25/// MCRegisterClass - Base class of TargetRegisterClass.
26class MCRegisterClass {
27public:
28  typedef const uint16_t* iterator;
29  typedef const uint16_t* const_iterator;
30
31  const char *Name;
32  const iterator RegsBegin;
33  const uint8_t *const RegSet;
34  const uint16_t RegsSize;
35  const uint16_t RegSetSize;
36  const uint16_t ID;
37  const uint16_t RegSize, Alignment; // Size & Alignment of register in bytes
38  const int8_t CopyCost;
39  const bool Allocatable;
40
41  /// getID() - Return the register class ID number.
42  ///
43  unsigned getID() const { return ID; }
44
45  /// getName() - Return the register class name for debugging.
46  ///
47  const char *getName() const { return Name; }
48
49  /// begin/end - Return all of the registers in this class.
50  ///
51  iterator       begin() const { return RegsBegin; }
52  iterator         end() const { return RegsBegin + RegsSize; }
53
54  /// getNumRegs - Return the number of registers in this class.
55  ///
56  unsigned getNumRegs() const { return RegsSize; }
57
58  /// getRegister - Return the specified register in the class.
59  ///
60  unsigned getRegister(unsigned i) const {
61    assert(i < getNumRegs() && "Register number out of range!");
62    return RegsBegin[i];
63  }
64
65  /// contains - Return true if the specified register is included in this
66  /// register class.  This does not include virtual registers.
67  bool contains(unsigned Reg) const {
68    unsigned InByte = Reg % 8;
69    unsigned Byte = Reg / 8;
70    if (Byte >= RegSetSize)
71      return false;
72    return (RegSet[Byte] & (1 << InByte)) != 0;
73  }
74
75  /// contains - Return true if both registers are in this class.
76  bool contains(unsigned Reg1, unsigned Reg2) const {
77    return contains(Reg1) && contains(Reg2);
78  }
79
80  /// getSize - Return the size of the register in bytes, which is also the size
81  /// of a stack slot allocated to hold a spilled copy of this register.
82  unsigned getSize() const { return RegSize; }
83
84  /// getAlignment - Return the minimum required alignment for a register of
85  /// this class.
86  unsigned getAlignment() const { return Alignment; }
87
88  /// getCopyCost - Return the cost of copying a value between two registers in
89  /// this class. A negative number means the register class is very expensive
90  /// to copy e.g. status flag register classes.
91  int getCopyCost() const { return CopyCost; }
92
93  /// isAllocatable - Return true if this register class may be used to create
94  /// virtual registers.
95  bool isAllocatable() const { return Allocatable; }
96};
97
98/// MCRegisterDesc - This record contains all of the information known about
99/// a particular register.  The Overlaps field contains a pointer to a zero
100/// terminated array of registers that this register aliases, starting with
101/// itself. This is needed for architectures like X86 which have AL alias AX
102/// alias EAX. The SubRegs field is a zero terminated array of registers that
103/// are sub-registers of the specific register, e.g. AL, AH are sub-registers of
104/// AX. The SuperRegs field is a zero terminated array of registers that are
105/// super-registers of the specific register, e.g. RAX, EAX, are super-registers
106/// of AX.
107///
108struct MCRegisterDesc {
109  uint32_t Name;      // Printable name for the reg (for debugging)
110  uint32_t Overlaps;  // Overlapping registers, described above
111  uint32_t SubRegs;   // Sub-register set, described above
112  uint32_t SuperRegs; // Super-register set, described above
113
114  // RegUnits - Points to the list of register units. The low 4 bits holds the
115  // Scale, the high bits hold an offset into DiffLists. See MCRegUnitIterator.
116  uint32_t RegUnits;
117};
118
119/// MCRegisterInfo base class - We assume that the target defines a static
120/// array of MCRegisterDesc objects that represent all of the machine
121/// registers that the target has.  As such, we simply have to track a pointer
122/// to this array so that we can turn register number into a register
123/// descriptor.
124///
125/// Note this class is designed to be a base class of TargetRegisterInfo, which
126/// is the interface used by codegen. However, specific targets *should never*
127/// specialize this class. MCRegisterInfo should only contain getters to access
128/// TableGen generated physical register data. It must not be extended with
129/// virtual methods.
130///
131class MCRegisterInfo {
132public:
133  typedef const MCRegisterClass *regclass_iterator;
134
135  /// DwarfLLVMRegPair - Emitted by tablegen so Dwarf<->LLVM reg mappings can be
136  /// performed with a binary search.
137  struct DwarfLLVMRegPair {
138    unsigned FromReg;
139    unsigned ToReg;
140
141    bool operator<(DwarfLLVMRegPair RHS) const { return FromReg < RHS.FromReg; }
142  };
143private:
144  const MCRegisterDesc *Desc;                 // Pointer to the descriptor array
145  unsigned NumRegs;                           // Number of entries in the array
146  unsigned RAReg;                             // Return address register
147  const MCRegisterClass *Classes;             // Pointer to the regclass array
148  unsigned NumClasses;                        // Number of entries in the array
149  unsigned NumRegUnits;                       // Number of regunits.
150  const uint16_t (*RegUnitRoots)[2];          // Pointer to regunit root table.
151  const uint16_t *DiffLists;                  // Pointer to the difflists array
152  const char *RegStrings;                     // Pointer to the string table.
153  const uint16_t *SubRegIndices;              // Pointer to the subreg lookup
154                                              // array.
155  unsigned NumSubRegIndices;                  // Number of subreg indices.
156  const uint16_t *RegEncodingTable;           // Pointer to array of register
157                                              // encodings.
158
159  unsigned L2DwarfRegsSize;
160  unsigned EHL2DwarfRegsSize;
161  unsigned Dwarf2LRegsSize;
162  unsigned EHDwarf2LRegsSize;
163  const DwarfLLVMRegPair *L2DwarfRegs;        // LLVM to Dwarf regs mapping
164  const DwarfLLVMRegPair *EHL2DwarfRegs;      // LLVM to Dwarf regs mapping EH
165  const DwarfLLVMRegPair *Dwarf2LRegs;        // Dwarf to LLVM regs mapping
166  const DwarfLLVMRegPair *EHDwarf2LRegs;      // Dwarf to LLVM regs mapping EH
167  DenseMap<unsigned, int> L2SEHRegs;          // LLVM to SEH regs mapping
168
169public:
170  /// DiffListIterator - Base iterator class that can traverse the
171  /// differentially encoded register and regunit lists in DiffLists.
172  /// Don't use this class directly, use one of the specialized sub-classes
173  /// defined below.
174  class DiffListIterator {
175    uint16_t Val;
176    const uint16_t *List;
177
178  protected:
179    /// Create an invalid iterator. Call init() to point to something useful.
180    DiffListIterator() : Val(0), List(0) {}
181
182    /// init - Point the iterator to InitVal, decoding subsequent values from
183    /// DiffList. The iterator will initially point to InitVal, sub-classes are
184    /// responsible for skipping the seed value if it is not part of the list.
185    void init(uint16_t InitVal, const uint16_t *DiffList) {
186      Val = InitVal;
187      List = DiffList;
188    }
189
190    /// advance - Move to the next list position, return the applied
191    /// differential. This function does not detect the end of the list, that
192    /// is the caller's responsibility (by checking for a 0 return value).
193    unsigned advance() {
194      assert(isValid() && "Cannot move off the end of the list.");
195      uint16_t D = *List++;
196      Val += D;
197      return D;
198    }
199
200  public:
201
202    /// isValid - returns true if this iterator is not yet at the end.
203    bool isValid() const { return List; }
204
205    /// Dereference the iterator to get the value at the current position.
206    unsigned operator*() const { return Val; }
207
208    /// Pre-increment to move to the next position.
209    void operator++() {
210      // The end of the list is encoded as a 0 differential.
211      if (!advance())
212        List = 0;
213    }
214  };
215
216  // These iterators are allowed to sub-class DiffListIterator and access
217  // internal list pointers.
218  friend class MCSubRegIterator;
219  friend class MCSuperRegIterator;
220  friend class MCRegAliasIterator;
221  friend class MCRegUnitIterator;
222  friend class MCRegUnitRootIterator;
223
224  /// InitMCRegisterInfo - Initialize MCRegisterInfo, called by TableGen
225  /// auto-generated routines. *DO NOT USE*.
226  void InitMCRegisterInfo(const MCRegisterDesc *D, unsigned NR, unsigned RA,
227                          const MCRegisterClass *C, unsigned NC,
228                          const uint16_t (*RURoots)[2],
229                          unsigned NRU,
230                          const uint16_t *DL,
231                          const char *Strings,
232                          const uint16_t *SubIndices,
233                          unsigned NumIndices,
234                          const uint16_t *RET) {
235    Desc = D;
236    NumRegs = NR;
237    RAReg = RA;
238    Classes = C;
239    DiffLists = DL;
240    RegStrings = Strings;
241    NumClasses = NC;
242    RegUnitRoots = RURoots;
243    NumRegUnits = NRU;
244    SubRegIndices = SubIndices;
245    NumSubRegIndices = NumIndices;
246    RegEncodingTable = RET;
247  }
248
249  /// mapLLVMRegsToDwarfRegs - Used to initialize LLVM register to Dwarf
250  /// register number mapping. Called by TableGen auto-generated routines.
251  /// *DO NOT USE*.
252  void mapLLVMRegsToDwarfRegs(const DwarfLLVMRegPair *Map, unsigned Size,
253                              bool isEH) {
254    if (isEH) {
255      EHL2DwarfRegs = Map;
256      EHL2DwarfRegsSize = Size;
257    } else {
258      L2DwarfRegs = Map;
259      L2DwarfRegsSize = Size;
260    }
261  }
262
263  /// mapDwarfRegsToLLVMRegs - Used to initialize Dwarf register to LLVM
264  /// register number mapping. Called by TableGen auto-generated routines.
265  /// *DO NOT USE*.
266  void mapDwarfRegsToLLVMRegs(const DwarfLLVMRegPair *Map, unsigned Size,
267                              bool isEH) {
268    if (isEH) {
269      EHDwarf2LRegs = Map;
270      EHDwarf2LRegsSize = Size;
271    } else {
272      Dwarf2LRegs = Map;
273      Dwarf2LRegsSize = Size;
274    }
275  }
276
277  /// mapLLVMRegToSEHReg - Used to initialize LLVM register to SEH register
278  /// number mapping. By default the SEH register number is just the same
279  /// as the LLVM register number.
280  /// FIXME: TableGen these numbers. Currently this requires target specific
281  /// initialization code.
282  void mapLLVMRegToSEHReg(unsigned LLVMReg, int SEHReg) {
283    L2SEHRegs[LLVMReg] = SEHReg;
284  }
285
286  /// getRARegister - This method should return the register where the return
287  /// address can be found.
288  unsigned getRARegister() const {
289    return RAReg;
290  }
291
292  const MCRegisterDesc &operator[](unsigned RegNo) const {
293    assert(RegNo < NumRegs &&
294           "Attempting to access record for invalid register number!");
295    return Desc[RegNo];
296  }
297
298  /// Provide a get method, equivalent to [], but more useful if we have a
299  /// pointer to this object.
300  ///
301  const MCRegisterDesc &get(unsigned RegNo) const {
302    return operator[](RegNo);
303  }
304
305  /// getSubReg - Returns the physical register number of sub-register "Index"
306  /// for physical register RegNo. Return zero if the sub-register does not
307  /// exist.
308  unsigned getSubReg(unsigned Reg, unsigned Idx) const {
309    return *(SubRegIndices + (Reg - 1) * NumSubRegIndices + Idx - 1);
310  }
311
312  /// getMatchingSuperReg - Return a super-register of the specified register
313  /// Reg so its sub-register of index SubIdx is Reg.
314  unsigned getMatchingSuperReg(unsigned Reg, unsigned SubIdx,
315                               const MCRegisterClass *RC) const;
316
317  /// getSubRegIndex - For a given register pair, return the sub-register index
318  /// if the second register is a sub-register of the first. Return zero
319  /// otherwise.
320  unsigned getSubRegIndex(unsigned RegNo, unsigned SubRegNo) const {
321    for (unsigned I = 1; I <= NumSubRegIndices; ++I)
322      if (getSubReg(RegNo, I) == SubRegNo)
323        return I;
324    return 0;
325  }
326
327  /// getName - Return the human-readable symbolic target-specific name for the
328  /// specified physical register.
329  const char *getName(unsigned RegNo) const {
330    return RegStrings + get(RegNo).Name;
331  }
332
333  /// getNumRegs - Return the number of registers this target has (useful for
334  /// sizing arrays holding per register information)
335  unsigned getNumRegs() const {
336    return NumRegs;
337  }
338
339  /// getNumRegUnits - Return the number of (native) register units in the
340  /// target. Register units are numbered from 0 to getNumRegUnits() - 1. They
341  /// can be accessed through MCRegUnitIterator defined below.
342  unsigned getNumRegUnits() const {
343    return NumRegUnits;
344  }
345
346  /// getDwarfRegNum - Map a target register to an equivalent dwarf register
347  /// number.  Returns -1 if there is no equivalent value.  The second
348  /// parameter allows targets to use different numberings for EH info and
349  /// debugging info.
350  int getDwarfRegNum(unsigned RegNum, bool isEH) const {
351    const DwarfLLVMRegPair *M = isEH ? EHL2DwarfRegs : L2DwarfRegs;
352    unsigned Size = isEH ? EHL2DwarfRegsSize : L2DwarfRegsSize;
353
354    DwarfLLVMRegPair Key = { RegNum, 0 };
355    const DwarfLLVMRegPair *I = std::lower_bound(M, M+Size, Key);
356    if (I == M+Size || I->FromReg != RegNum)
357      return -1;
358    return I->ToReg;
359  }
360
361  /// getLLVMRegNum - Map a dwarf register back to a target register.
362  ///
363  int getLLVMRegNum(unsigned RegNum, bool isEH) const {
364    const DwarfLLVMRegPair *M = isEH ? EHDwarf2LRegs : Dwarf2LRegs;
365    unsigned Size = isEH ? EHDwarf2LRegsSize : Dwarf2LRegsSize;
366
367    DwarfLLVMRegPair Key = { RegNum, 0 };
368    const DwarfLLVMRegPair *I = std::lower_bound(M, M+Size, Key);
369    assert(I != M+Size && I->FromReg == RegNum && "Invalid RegNum");
370    return I->ToReg;
371  }
372
373  /// getSEHRegNum - Map a target register to an equivalent SEH register
374  /// number.  Returns LLVM register number if there is no equivalent value.
375  int getSEHRegNum(unsigned RegNum) const {
376    const DenseMap<unsigned, int>::const_iterator I = L2SEHRegs.find(RegNum);
377    if (I == L2SEHRegs.end()) return (int)RegNum;
378    return I->second;
379  }
380
381  regclass_iterator regclass_begin() const { return Classes; }
382  regclass_iterator regclass_end() const { return Classes+NumClasses; }
383
384  unsigned getNumRegClasses() const {
385    return (unsigned)(regclass_end()-regclass_begin());
386  }
387
388  /// getRegClass - Returns the register class associated with the enumeration
389  /// value.  See class MCOperandInfo.
390  const MCRegisterClass getRegClass(unsigned i) const {
391    assert(i < getNumRegClasses() && "Register Class ID out of range");
392    return Classes[i];
393  }
394
395   /// getEncodingValue - Returns the encoding for RegNo
396  uint16_t getEncodingValue(unsigned RegNo) const {
397    assert(RegNo < NumRegs &&
398           "Attempting to get encoding for invalid register number!");
399    return RegEncodingTable[RegNo];
400  }
401
402};
403
404//===----------------------------------------------------------------------===//
405//                          Register List Iterators
406//===----------------------------------------------------------------------===//
407
408// MCRegisterInfo provides lists of super-registers, sub-registers, and
409// aliasing registers. Use these iterator classes to traverse the lists.
410
411/// MCSubRegIterator enumerates all sub-registers of Reg.
412class MCSubRegIterator : public MCRegisterInfo::DiffListIterator {
413public:
414  MCSubRegIterator(unsigned Reg, const MCRegisterInfo *MCRI) {
415    init(Reg, MCRI->DiffLists + MCRI->get(Reg).SubRegs);
416    ++*this;
417  }
418};
419
420/// MCSuperRegIterator enumerates all super-registers of Reg.
421class MCSuperRegIterator : public MCRegisterInfo::DiffListIterator {
422public:
423  MCSuperRegIterator(unsigned Reg, const MCRegisterInfo *MCRI) {
424    init(Reg, MCRI->DiffLists + MCRI->get(Reg).SuperRegs);
425    ++*this;
426  }
427};
428
429/// MCRegAliasIterator enumerates all registers aliasing Reg.
430/// If IncludeSelf is set, Reg itself is included in the list.
431class MCRegAliasIterator : public MCRegisterInfo::DiffListIterator {
432public:
433  MCRegAliasIterator(unsigned Reg, const MCRegisterInfo *MCRI,
434                     bool IncludeSelf) {
435    init(Reg, MCRI->DiffLists + MCRI->get(Reg).Overlaps);
436    // Initially, the iterator points to Reg itself.
437    if (!IncludeSelf)
438      ++*this;
439  }
440};
441
442inline
443unsigned MCRegisterInfo::getMatchingSuperReg(unsigned Reg, unsigned SubIdx,
444                                             const MCRegisterClass *RC) const {
445    for (MCSuperRegIterator Supers(Reg, this); Supers.isValid(); ++Supers)
446      if (Reg == getSubReg(*Supers, SubIdx) && RC->contains(*Supers))
447        return *Supers;
448    return 0;
449}
450
451//===----------------------------------------------------------------------===//
452//                               Register Units
453//===----------------------------------------------------------------------===//
454
455// Register units are used to compute register aliasing. Every register has at
456// least one register unit, but it can have more. Two registers overlap if and
457// only if they have a common register unit.
458//
459// A target with a complicated sub-register structure will typically have many
460// fewer register units than actual registers. MCRI::getNumRegUnits() returns
461// the number of register units in the target.
462
463// MCRegUnitIterator enumerates a list of register units for Reg. The list is
464// in ascending numerical order.
465class MCRegUnitIterator : public MCRegisterInfo::DiffListIterator {
466public:
467  /// MCRegUnitIterator - Create an iterator that traverses the register units
468  /// in Reg.
469  MCRegUnitIterator(unsigned Reg, const MCRegisterInfo *MCRI) {
470    // Decode the RegUnits MCRegisterDesc field.
471    unsigned RU = MCRI->get(Reg).RegUnits;
472    unsigned Scale = RU & 15;
473    unsigned Offset = RU >> 4;
474
475    // Initialize the iterator to Reg * Scale, and the List pointer to
476    // DiffLists + Offset.
477    init(Reg * Scale, MCRI->DiffLists + Offset);
478
479    // That may not be a valid unit, we need to advance by one to get the real
480    // unit number. The first differential can be 0 which would normally
481    // terminate the list, but since we know every register has at least one
482    // unit, we can allow a 0 differential here.
483    advance();
484  }
485};
486
487// Each register unit has one or two root registers. The complete set of
488// registers containing a register unit is the union of the roots and their
489// super-registers. All registers aliasing Unit can be visited like this:
490//
491//   for (MCRegUnitRootIterator RI(Unit, MCRI); RI.isValid(); ++RI) {
492//     unsigned Root = *RI;
493//     visit(Root);
494//     for (MCSuperRegIterator SI(Root, MCRI); SI.isValid(); ++SI)
495//       visit(*SI);
496//    }
497
498/// MCRegUnitRootIterator enumerates the root registers of a register unit.
499class MCRegUnitRootIterator {
500  uint16_t Reg0;
501  uint16_t Reg1;
502public:
503  MCRegUnitRootIterator(unsigned RegUnit, const MCRegisterInfo *MCRI) {
504    assert(RegUnit < MCRI->getNumRegUnits() && "Invalid register unit");
505    Reg0 = MCRI->RegUnitRoots[RegUnit][0];
506    Reg1 = MCRI->RegUnitRoots[RegUnit][1];
507  }
508
509  /// Dereference to get the current root register.
510  unsigned operator*() const {
511    return Reg0;
512  }
513
514  /// isValid - Check if the iterator is at the end of the list.
515  bool isValid() const {
516    return Reg0;
517  }
518
519  /// Preincrement to move to the next root register.
520  void operator++() {
521    assert(isValid() && "Cannot move off the end of the list.");
522    Reg0 = Reg1;
523    Reg1 = 0;
524  }
525};
526
527} // End llvm namespace
528
529#endif
530