1//===- TargetRegisterInfo.cpp - Target Register Information Implementation ===//
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 implements the TargetRegisterInfo interface.
11//
12//===----------------------------------------------------------------------===//
13
14#include "llvm/Target/TargetRegisterInfo.h"
15#include "llvm/ADT/BitVector.h"
16#include "llvm/CodeGen/MachineFunction.h"
17#include "llvm/CodeGen/MachineRegisterInfo.h"
18#include "llvm/CodeGen/VirtRegMap.h"
19#include "llvm/Support/raw_ostream.h"
20
21using namespace llvm;
22
23TargetRegisterInfo::TargetRegisterInfo(const TargetRegisterInfoDesc *ID,
24                             regclass_iterator RCB, regclass_iterator RCE,
25                             const char *const *SRINames,
26                             const unsigned *SRILaneMasks)
27  : InfoDesc(ID), SubRegIndexNames(SRINames),
28    SubRegIndexLaneMasks(SRILaneMasks),
29    RegClassBegin(RCB), RegClassEnd(RCE) {
30}
31
32TargetRegisterInfo::~TargetRegisterInfo() {}
33
34void PrintReg::print(raw_ostream &OS) const {
35  if (!Reg)
36    OS << "%noreg";
37  else if (TargetRegisterInfo::isStackSlot(Reg))
38    OS << "SS#" << TargetRegisterInfo::stackSlot2Index(Reg);
39  else if (TargetRegisterInfo::isVirtualRegister(Reg))
40    OS << "%vreg" << TargetRegisterInfo::virtReg2Index(Reg);
41  else if (TRI && Reg < TRI->getNumRegs())
42    OS << '%' << TRI->getName(Reg);
43  else
44    OS << "%physreg" << Reg;
45  if (SubIdx) {
46    if (TRI)
47      OS << ':' << TRI->getSubRegIndexName(SubIdx);
48    else
49      OS << ":sub(" << SubIdx << ')';
50  }
51}
52
53void PrintRegUnit::print(raw_ostream &OS) const {
54  // Generic printout when TRI is missing.
55  if (!TRI) {
56    OS << "Unit~" << Unit;
57    return;
58  }
59
60  // Check for invalid register units.
61  if (Unit >= TRI->getNumRegUnits()) {
62    OS << "BadUnit~" << Unit;
63    return;
64  }
65
66  // Normal units have at least one root.
67  MCRegUnitRootIterator Roots(Unit, TRI);
68  assert(Roots.isValid() && "Unit has no roots.");
69  OS << TRI->getName(*Roots);
70  for (++Roots; Roots.isValid(); ++Roots)
71    OS << '~' << TRI->getName(*Roots);
72}
73
74/// getAllocatableClass - Return the maximal subclass of the given register
75/// class that is alloctable, or NULL.
76const TargetRegisterClass *
77TargetRegisterInfo::getAllocatableClass(const TargetRegisterClass *RC) const {
78  if (!RC || RC->isAllocatable())
79    return RC;
80
81  const unsigned *SubClass = RC->getSubClassMask();
82  for (unsigned Base = 0, BaseE = getNumRegClasses();
83       Base < BaseE; Base += 32) {
84    unsigned Idx = Base;
85    for (unsigned Mask = *SubClass++; Mask; Mask >>= 1) {
86      unsigned Offset = CountTrailingZeros_32(Mask);
87      const TargetRegisterClass *SubRC = getRegClass(Idx + Offset);
88      if (SubRC->isAllocatable())
89        return SubRC;
90      Mask >>= Offset;
91      Idx += Offset + 1;
92    }
93  }
94  return NULL;
95}
96
97/// getMinimalPhysRegClass - Returns the Register Class of a physical
98/// register of the given type, picking the most sub register class of
99/// the right type that contains this physreg.
100const TargetRegisterClass *
101TargetRegisterInfo::getMinimalPhysRegClass(unsigned reg, EVT VT) const {
102  assert(isPhysicalRegister(reg) && "reg must be a physical register");
103
104  // Pick the most sub register class of the right type that contains
105  // this physreg.
106  const TargetRegisterClass* BestRC = 0;
107  for (regclass_iterator I = regclass_begin(), E = regclass_end(); I != E; ++I){
108    const TargetRegisterClass* RC = *I;
109    if ((VT == MVT::Other || RC->hasType(VT)) && RC->contains(reg) &&
110        (!BestRC || BestRC->hasSubClass(RC)))
111      BestRC = RC;
112  }
113
114  assert(BestRC && "Couldn't find the register class");
115  return BestRC;
116}
117
118/// getAllocatableSetForRC - Toggle the bits that represent allocatable
119/// registers for the specific register class.
120static void getAllocatableSetForRC(const MachineFunction &MF,
121                                   const TargetRegisterClass *RC, BitVector &R){
122  assert(RC->isAllocatable() && "invalid for nonallocatable sets");
123  ArrayRef<uint16_t> Order = RC->getRawAllocationOrder(MF);
124  for (unsigned i = 0; i != Order.size(); ++i)
125    R.set(Order[i]);
126}
127
128BitVector TargetRegisterInfo::getAllocatableSet(const MachineFunction &MF,
129                                          const TargetRegisterClass *RC) const {
130  BitVector Allocatable(getNumRegs());
131  if (RC) {
132    // A register class with no allocatable subclass returns an empty set.
133    const TargetRegisterClass *SubClass = getAllocatableClass(RC);
134    if (SubClass)
135      getAllocatableSetForRC(MF, SubClass, Allocatable);
136  } else {
137    for (TargetRegisterInfo::regclass_iterator I = regclass_begin(),
138         E = regclass_end(); I != E; ++I)
139      if ((*I)->isAllocatable())
140        getAllocatableSetForRC(MF, *I, Allocatable);
141  }
142
143  // Mask out the reserved registers
144  BitVector Reserved = getReservedRegs(MF);
145  Allocatable &= Reserved.flip();
146
147  return Allocatable;
148}
149
150static inline
151const TargetRegisterClass *firstCommonClass(const uint32_t *A,
152                                            const uint32_t *B,
153                                            const TargetRegisterInfo *TRI) {
154  for (unsigned I = 0, E = TRI->getNumRegClasses(); I < E; I += 32)
155    if (unsigned Common = *A++ & *B++)
156      return TRI->getRegClass(I + CountTrailingZeros_32(Common));
157  return 0;
158}
159
160const TargetRegisterClass *
161TargetRegisterInfo::getCommonSubClass(const TargetRegisterClass *A,
162                                      const TargetRegisterClass *B) const {
163  // First take care of the trivial cases.
164  if (A == B)
165    return A;
166  if (!A || !B)
167    return 0;
168
169  // Register classes are ordered topologically, so the largest common
170  // sub-class it the common sub-class with the smallest ID.
171  return firstCommonClass(A->getSubClassMask(), B->getSubClassMask(), this);
172}
173
174const TargetRegisterClass *
175TargetRegisterInfo::getMatchingSuperRegClass(const TargetRegisterClass *A,
176                                             const TargetRegisterClass *B,
177                                             unsigned Idx) const {
178  assert(A && B && "Missing register class");
179  assert(Idx && "Bad sub-register index");
180
181  // Find Idx in the list of super-register indices.
182  for (SuperRegClassIterator RCI(B, this); RCI.isValid(); ++RCI)
183    if (RCI.getSubReg() == Idx)
184      // The bit mask contains all register classes that are projected into B
185      // by Idx. Find a class that is also a sub-class of A.
186      return firstCommonClass(RCI.getMask(), A->getSubClassMask(), this);
187  return 0;
188}
189
190const TargetRegisterClass *TargetRegisterInfo::
191getCommonSuperRegClass(const TargetRegisterClass *RCA, unsigned SubA,
192                       const TargetRegisterClass *RCB, unsigned SubB,
193                       unsigned &PreA, unsigned &PreB) const {
194  assert(RCA && SubA && RCB && SubB && "Invalid arguments");
195
196  // Search all pairs of sub-register indices that project into RCA and RCB
197  // respectively. This is quadratic, but usually the sets are very small. On
198  // most targets like X86, there will only be a single sub-register index
199  // (e.g., sub_16bit projecting into GR16).
200  //
201  // The worst case is a register class like DPR on ARM.
202  // We have indices dsub_0..dsub_7 projecting into that class.
203  //
204  // It is very common that one register class is a sub-register of the other.
205  // Arrange for RCA to be the larger register so the answer will be found in
206  // the first iteration. This makes the search linear for the most common
207  // case.
208  const TargetRegisterClass *BestRC = 0;
209  unsigned *BestPreA = &PreA;
210  unsigned *BestPreB = &PreB;
211  if (RCA->getSize() < RCB->getSize()) {
212    std::swap(RCA, RCB);
213    std::swap(SubA, SubB);
214    std::swap(BestPreA, BestPreB);
215  }
216
217  // Also terminate the search one we have found a register class as small as
218  // RCA.
219  unsigned MinSize = RCA->getSize();
220
221  for (SuperRegClassIterator IA(RCA, this, true); IA.isValid(); ++IA) {
222    unsigned FinalA = composeSubRegIndices(IA.getSubReg(), SubA);
223    for (SuperRegClassIterator IB(RCB, this, true); IB.isValid(); ++IB) {
224      // Check if a common super-register class exists for this index pair.
225      const TargetRegisterClass *RC =
226        firstCommonClass(IA.getMask(), IB.getMask(), this);
227      if (!RC || RC->getSize() < MinSize)
228        continue;
229
230      // The indexes must compose identically: PreA+SubA == PreB+SubB.
231      unsigned FinalB = composeSubRegIndices(IB.getSubReg(), SubB);
232      if (FinalA != FinalB)
233        continue;
234
235      // Is RC a better candidate than BestRC?
236      if (BestRC && RC->getSize() >= BestRC->getSize())
237        continue;
238
239      // Yes, RC is the smallest super-register seen so far.
240      BestRC = RC;
241      *BestPreA = IA.getSubReg();
242      *BestPreB = IB.getSubReg();
243
244      // Bail early if we reached MinSize. We won't find a better candidate.
245      if (BestRC->getSize() == MinSize)
246        return BestRC;
247    }
248  }
249  return BestRC;
250}
251
252// Compute target-independent register allocator hints to help eliminate copies.
253void
254TargetRegisterInfo::getRegAllocationHints(unsigned VirtReg,
255                                          ArrayRef<MCPhysReg> Order,
256                                          SmallVectorImpl<MCPhysReg> &Hints,
257                                          const MachineFunction &MF,
258                                          const VirtRegMap *VRM) const {
259  const MachineRegisterInfo &MRI = MF.getRegInfo();
260  std::pair<unsigned, unsigned> Hint = MRI.getRegAllocationHint(VirtReg);
261
262  // Hints with HintType != 0 were set by target-dependent code.
263  // Such targets must provide their own implementation of
264  // TRI::getRegAllocationHints to interpret those hint types.
265  assert(Hint.first == 0 && "Target must implement TRI::getRegAllocationHints");
266
267  // Target-independent hints are either a physical or a virtual register.
268  unsigned Phys = Hint.second;
269  if (VRM && isVirtualRegister(Phys))
270    Phys = VRM->getPhys(Phys);
271
272  // Check that Phys is a valid hint in VirtReg's register class.
273  if (!isPhysicalRegister(Phys))
274    return;
275  if (MRI.isReserved(Phys))
276    return;
277  // Check that Phys is in the allocation order. We shouldn't heed hints
278  // from VirtReg's register class if they aren't in the allocation order. The
279  // target probably has a reason for removing the register.
280  if (std::find(Order.begin(), Order.end(), Phys) == Order.end())
281    return;
282
283  // All clear, tell the register allocator to prefer this register.
284  Hints.push_back(Phys);
285}
286