Revert "raw_ostream: << operator for callables with raw_stream argument"
[oota-llvm.git] / lib / CodeGen / TargetRegisterInfo.cpp
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/ADT/BitVector.h"
15 #include "llvm/CodeGen/MachineFrameInfo.h"
16 #include "llvm/CodeGen/MachineFunction.h"
17 #include "llvm/CodeGen/MachineRegisterInfo.h"
18 #include "llvm/CodeGen/VirtRegMap.h"
19 #include "llvm/IR/Function.h"
20 #include "llvm/Support/Debug.h"
21 #include "llvm/Support/Format.h"
22 #include "llvm/Support/raw_ostream.h"
23 #include "llvm/Target/TargetFrameLowering.h"
24 #include "llvm/Target/TargetRegisterInfo.h"
25
26 #define DEBUG_TYPE "target-reg-info"
27
28 using namespace llvm;
29
30 TargetRegisterInfo::TargetRegisterInfo(const TargetRegisterInfoDesc *ID,
31                              regclass_iterator RCB, regclass_iterator RCE,
32                              const char *const *SRINames,
33                              const unsigned *SRILaneMasks,
34                              unsigned SRICoveringLanes)
35   : InfoDesc(ID), SubRegIndexNames(SRINames),
36     SubRegIndexLaneMasks(SRILaneMasks),
37     RegClassBegin(RCB), RegClassEnd(RCE),
38     CoveringLanes(SRICoveringLanes) {
39 }
40
41 TargetRegisterInfo::~TargetRegisterInfo() {}
42
43 void PrintReg::print(raw_ostream &OS) const {
44   if (!Reg)
45     OS << "%noreg";
46   else if (TargetRegisterInfo::isStackSlot(Reg))
47     OS << "SS#" << TargetRegisterInfo::stackSlot2Index(Reg);
48   else if (TargetRegisterInfo::isVirtualRegister(Reg))
49     OS << "%vreg" << TargetRegisterInfo::virtReg2Index(Reg);
50   else if (TRI && Reg < TRI->getNumRegs())
51     OS << '%' << TRI->getName(Reg);
52   else
53     OS << "%physreg" << Reg;
54   if (SubIdx) {
55     if (TRI)
56       OS << ':' << TRI->getSubRegIndexName(SubIdx);
57     else
58       OS << ":sub(" << SubIdx << ')';
59   }
60 }
61
62 void PrintRegUnit::print(raw_ostream &OS) const {
63   // Generic printout when TRI is missing.
64   if (!TRI) {
65     OS << "Unit~" << Unit;
66     return;
67   }
68
69   // Check for invalid register units.
70   if (Unit >= TRI->getNumRegUnits()) {
71     OS << "BadUnit~" << Unit;
72     return;
73   }
74
75   // Normal units have at least one root.
76   MCRegUnitRootIterator Roots(Unit, TRI);
77   assert(Roots.isValid() && "Unit has no roots.");
78   OS << TRI->getName(*Roots);
79   for (++Roots; Roots.isValid(); ++Roots)
80     OS << '~' << TRI->getName(*Roots);
81 }
82
83 void PrintVRegOrUnit::print(raw_ostream &OS) const {
84   if (TRI && TRI->isVirtualRegister(Unit)) {
85     OS << "%vreg" << TargetRegisterInfo::virtReg2Index(Unit);
86     return;
87   }
88   PrintRegUnit::print(OS);
89 }
90
91 void PrintLaneMask::print(raw_ostream &OS) const {
92   OS << format("%08X", LaneMask);
93 }
94
95 /// getAllocatableClass - Return the maximal subclass of the given register
96 /// class that is alloctable, or NULL.
97 const TargetRegisterClass *
98 TargetRegisterInfo::getAllocatableClass(const TargetRegisterClass *RC) const {
99   if (!RC || RC->isAllocatable())
100     return RC;
101
102   const unsigned *SubClass = RC->getSubClassMask();
103   for (unsigned Base = 0, BaseE = getNumRegClasses();
104        Base < BaseE; Base += 32) {
105     unsigned Idx = Base;
106     for (unsigned Mask = *SubClass++; Mask; Mask >>= 1) {
107       unsigned Offset = countTrailingZeros(Mask);
108       const TargetRegisterClass *SubRC = getRegClass(Idx + Offset);
109       if (SubRC->isAllocatable())
110         return SubRC;
111       Mask >>= Offset;
112       Idx += Offset + 1;
113     }
114   }
115   return nullptr;
116 }
117
118 /// getMinimalPhysRegClass - Returns the Register Class of a physical
119 /// register of the given type, picking the most sub register class of
120 /// the right type that contains this physreg.
121 const TargetRegisterClass *
122 TargetRegisterInfo::getMinimalPhysRegClass(unsigned reg, MVT VT) const {
123   assert(isPhysicalRegister(reg) && "reg must be a physical register");
124
125   // Pick the most sub register class of the right type that contains
126   // this physreg.
127   const TargetRegisterClass* BestRC = nullptr;
128   for (regclass_iterator I = regclass_begin(), E = regclass_end(); I != E; ++I){
129     const TargetRegisterClass* RC = *I;
130     if ((VT == MVT::Other || RC->hasType(VT)) && RC->contains(reg) &&
131         (!BestRC || BestRC->hasSubClass(RC)))
132       BestRC = RC;
133   }
134
135   assert(BestRC && "Couldn't find the register class");
136   return BestRC;
137 }
138
139 /// getAllocatableSetForRC - Toggle the bits that represent allocatable
140 /// registers for the specific register class.
141 static void getAllocatableSetForRC(const MachineFunction &MF,
142                                    const TargetRegisterClass *RC, BitVector &R){
143   assert(RC->isAllocatable() && "invalid for nonallocatable sets");
144   ArrayRef<MCPhysReg> Order = RC->getRawAllocationOrder(MF);
145   for (unsigned i = 0; i != Order.size(); ++i)
146     R.set(Order[i]);
147 }
148
149 BitVector TargetRegisterInfo::getAllocatableSet(const MachineFunction &MF,
150                                           const TargetRegisterClass *RC) const {
151   BitVector Allocatable(getNumRegs());
152   if (RC) {
153     // A register class with no allocatable subclass returns an empty set.
154     const TargetRegisterClass *SubClass = getAllocatableClass(RC);
155     if (SubClass)
156       getAllocatableSetForRC(MF, SubClass, Allocatable);
157   } else {
158     for (TargetRegisterInfo::regclass_iterator I = regclass_begin(),
159          E = regclass_end(); I != E; ++I)
160       if ((*I)->isAllocatable())
161         getAllocatableSetForRC(MF, *I, Allocatable);
162   }
163
164   // Mask out the reserved registers
165   BitVector Reserved = getReservedRegs(MF);
166   Allocatable &= Reserved.flip();
167
168   return Allocatable;
169 }
170
171 static inline
172 const TargetRegisterClass *firstCommonClass(const uint32_t *A,
173                                             const uint32_t *B,
174                                             const TargetRegisterInfo *TRI,
175                                             const MVT::SimpleValueType SVT =
176                                             MVT::SimpleValueType::Any) {
177   const MVT VT(SVT);
178   for (unsigned I = 0, E = TRI->getNumRegClasses(); I < E; I += 32)
179     if (unsigned Common = *A++ & *B++) {
180       const TargetRegisterClass *RC =
181           TRI->getRegClass(I + countTrailingZeros(Common));
182       if (SVT == MVT::SimpleValueType::Any || RC->hasType(VT))
183         return RC;
184     }
185   return nullptr;
186 }
187
188 const TargetRegisterClass *
189 TargetRegisterInfo::getCommonSubClass(const TargetRegisterClass *A,
190                                       const TargetRegisterClass *B,
191                                       const MVT::SimpleValueType SVT) const {
192   // First take care of the trivial cases.
193   if (A == B)
194     return A;
195   if (!A || !B)
196     return nullptr;
197
198   // Register classes are ordered topologically, so the largest common
199   // sub-class it the common sub-class with the smallest ID.
200   return firstCommonClass(A->getSubClassMask(), B->getSubClassMask(), this, SVT);
201 }
202
203 const TargetRegisterClass *
204 TargetRegisterInfo::getMatchingSuperRegClass(const TargetRegisterClass *A,
205                                              const TargetRegisterClass *B,
206                                              unsigned Idx) const {
207   assert(A && B && "Missing register class");
208   assert(Idx && "Bad sub-register index");
209
210   // Find Idx in the list of super-register indices.
211   for (SuperRegClassIterator RCI(B, this); RCI.isValid(); ++RCI)
212     if (RCI.getSubReg() == Idx)
213       // The bit mask contains all register classes that are projected into B
214       // by Idx. Find a class that is also a sub-class of A.
215       return firstCommonClass(RCI.getMask(), A->getSubClassMask(), this);
216   return nullptr;
217 }
218
219 const TargetRegisterClass *TargetRegisterInfo::
220 getCommonSuperRegClass(const TargetRegisterClass *RCA, unsigned SubA,
221                        const TargetRegisterClass *RCB, unsigned SubB,
222                        unsigned &PreA, unsigned &PreB) const {
223   assert(RCA && SubA && RCB && SubB && "Invalid arguments");
224
225   // Search all pairs of sub-register indices that project into RCA and RCB
226   // respectively. This is quadratic, but usually the sets are very small. On
227   // most targets like X86, there will only be a single sub-register index
228   // (e.g., sub_16bit projecting into GR16).
229   //
230   // The worst case is a register class like DPR on ARM.
231   // We have indices dsub_0..dsub_7 projecting into that class.
232   //
233   // It is very common that one register class is a sub-register of the other.
234   // Arrange for RCA to be the larger register so the answer will be found in
235   // the first iteration. This makes the search linear for the most common
236   // case.
237   const TargetRegisterClass *BestRC = nullptr;
238   unsigned *BestPreA = &PreA;
239   unsigned *BestPreB = &PreB;
240   if (RCA->getSize() < RCB->getSize()) {
241     std::swap(RCA, RCB);
242     std::swap(SubA, SubB);
243     std::swap(BestPreA, BestPreB);
244   }
245
246   // Also terminate the search one we have found a register class as small as
247   // RCA.
248   unsigned MinSize = RCA->getSize();
249
250   for (SuperRegClassIterator IA(RCA, this, true); IA.isValid(); ++IA) {
251     unsigned FinalA = composeSubRegIndices(IA.getSubReg(), SubA);
252     for (SuperRegClassIterator IB(RCB, this, true); IB.isValid(); ++IB) {
253       // Check if a common super-register class exists for this index pair.
254       const TargetRegisterClass *RC =
255         firstCommonClass(IA.getMask(), IB.getMask(), this);
256       if (!RC || RC->getSize() < MinSize)
257         continue;
258
259       // The indexes must compose identically: PreA+SubA == PreB+SubB.
260       unsigned FinalB = composeSubRegIndices(IB.getSubReg(), SubB);
261       if (FinalA != FinalB)
262         continue;
263
264       // Is RC a better candidate than BestRC?
265       if (BestRC && RC->getSize() >= BestRC->getSize())
266         continue;
267
268       // Yes, RC is the smallest super-register seen so far.
269       BestRC = RC;
270       *BestPreA = IA.getSubReg();
271       *BestPreB = IB.getSubReg();
272
273       // Bail early if we reached MinSize. We won't find a better candidate.
274       if (BestRC->getSize() == MinSize)
275         return BestRC;
276     }
277   }
278   return BestRC;
279 }
280
281 /// \brief Check if the registers defined by the pair (RegisterClass, SubReg)
282 /// share the same register file.
283 static bool shareSameRegisterFile(const TargetRegisterInfo &TRI,
284                                   const TargetRegisterClass *DefRC,
285                                   unsigned DefSubReg,
286                                   const TargetRegisterClass *SrcRC,
287                                   unsigned SrcSubReg) {
288   // Same register class.
289   if (DefRC == SrcRC)
290     return true;
291
292   // Both operands are sub registers. Check if they share a register class.
293   unsigned SrcIdx, DefIdx;
294   if (SrcSubReg && DefSubReg) {
295     return TRI.getCommonSuperRegClass(SrcRC, SrcSubReg, DefRC, DefSubReg,
296                                       SrcIdx, DefIdx) != nullptr;
297   }
298
299   // At most one of the register is a sub register, make it Src to avoid
300   // duplicating the test.
301   if (!SrcSubReg) {
302     std::swap(DefSubReg, SrcSubReg);
303     std::swap(DefRC, SrcRC);
304   }
305
306   // One of the register is a sub register, check if we can get a superclass.
307   if (SrcSubReg)
308     return TRI.getMatchingSuperRegClass(SrcRC, DefRC, SrcSubReg) != nullptr;
309
310   // Plain copy.
311   return TRI.getCommonSubClass(DefRC, SrcRC) != nullptr;
312 }
313
314 bool TargetRegisterInfo::shouldRewriteCopySrc(const TargetRegisterClass *DefRC,
315                                               unsigned DefSubReg,
316                                               const TargetRegisterClass *SrcRC,
317                                               unsigned SrcSubReg) const {
318   // If this source does not incur a cross register bank copy, use it.
319   return shareSameRegisterFile(*this, DefRC, DefSubReg, SrcRC, SrcSubReg);
320 }
321
322 // Compute target-independent register allocator hints to help eliminate copies.
323 void
324 TargetRegisterInfo::getRegAllocationHints(unsigned VirtReg,
325                                           ArrayRef<MCPhysReg> Order,
326                                           SmallVectorImpl<MCPhysReg> &Hints,
327                                           const MachineFunction &MF,
328                                           const VirtRegMap *VRM,
329                                           const LiveRegMatrix *Matrix) const {
330   const MachineRegisterInfo &MRI = MF.getRegInfo();
331   std::pair<unsigned, unsigned> Hint = MRI.getRegAllocationHint(VirtReg);
332
333   // Hints with HintType != 0 were set by target-dependent code.
334   // Such targets must provide their own implementation of
335   // TRI::getRegAllocationHints to interpret those hint types.
336   assert(Hint.first == 0 && "Target must implement TRI::getRegAllocationHints");
337
338   // Target-independent hints are either a physical or a virtual register.
339   unsigned Phys = Hint.second;
340   if (VRM && isVirtualRegister(Phys))
341     Phys = VRM->getPhys(Phys);
342
343   // Check that Phys is a valid hint in VirtReg's register class.
344   if (!isPhysicalRegister(Phys))
345     return;
346   if (MRI.isReserved(Phys))
347     return;
348   // Check that Phys is in the allocation order. We shouldn't heed hints
349   // from VirtReg's register class if they aren't in the allocation order. The
350   // target probably has a reason for removing the register.
351   if (std::find(Order.begin(), Order.end(), Phys) == Order.end())
352     return;
353
354   // All clear, tell the register allocator to prefer this register.
355   Hints.push_back(Phys);
356 }
357
358 bool TargetRegisterInfo::canRealignStack(const MachineFunction &MF) const {
359   return !MF.getFunction()->hasFnAttribute("no-realign-stack");
360 }
361
362 bool TargetRegisterInfo::needsStackRealignment(
363     const MachineFunction &MF) const {
364   const MachineFrameInfo *MFI = MF.getFrameInfo();
365   const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering();
366   const Function *F = MF.getFunction();
367   unsigned StackAlign = TFI->getStackAlignment();
368   bool requiresRealignment = ((MFI->getMaxAlignment() > StackAlign) ||
369                               F->hasFnAttribute(Attribute::StackAlignment));
370   if (MF.getFunction()->hasFnAttribute("stackrealign") || requiresRealignment) {
371     if (canRealignStack(MF))
372       return true;
373     DEBUG(dbgs() << "Can't realign function's stack: " << F->getName() << "\n");
374   }
375   return false;
376 }
377
378 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
379 void
380 TargetRegisterInfo::dumpReg(unsigned Reg, unsigned SubRegIndex,
381                             const TargetRegisterInfo *TRI) {
382   dbgs() << PrintReg(Reg, TRI, SubRegIndex) << "\n";
383 }
384 #endif