1 //===- TargetRegisterInfo.cpp - Target Register Information Implementation ===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the TargetRegisterInfo interface.
12 //===----------------------------------------------------------------------===//
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"
26 #define DEBUG_TYPE "target-reg-info"
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) {
41 TargetRegisterInfo::~TargetRegisterInfo() {}
43 void PrintReg::print(raw_ostream &OS) const {
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);
53 OS << "%physreg" << Reg;
56 OS << ':' << TRI->getSubRegIndexName(SubIdx);
58 OS << ":sub(" << SubIdx << ')';
62 void PrintRegUnit::print(raw_ostream &OS) const {
63 // Generic printout when TRI is missing.
65 OS << "Unit~" << Unit;
69 // Check for invalid register units.
70 if (Unit >= TRI->getNumRegUnits()) {
71 OS << "BadUnit~" << Unit;
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);
83 void PrintVRegOrUnit::print(raw_ostream &OS) const {
84 if (TRI && TRI->isVirtualRegister(Unit)) {
85 OS << "%vreg" << TargetRegisterInfo::virtReg2Index(Unit);
88 PrintRegUnit::print(OS);
91 void PrintLaneMask::print(raw_ostream &OS) const {
92 OS << format("%08X", LaneMask);
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())
102 const unsigned *SubClass = RC->getSubClassMask();
103 for (unsigned Base = 0, BaseE = getNumRegClasses();
104 Base < BaseE; Base += 32) {
106 for (unsigned Mask = *SubClass++; Mask; Mask >>= 1) {
107 unsigned Offset = countTrailingZeros(Mask);
108 const TargetRegisterClass *SubRC = getRegClass(Idx + Offset);
109 if (SubRC->isAllocatable())
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");
125 // Pick the most sub register class of the right type that contains
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)))
135 assert(BestRC && "Couldn't find the register class");
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)
149 BitVector TargetRegisterInfo::getAllocatableSet(const MachineFunction &MF,
150 const TargetRegisterClass *RC) const {
151 BitVector Allocatable(getNumRegs());
153 // A register class with no allocatable subclass returns an empty set.
154 const TargetRegisterClass *SubClass = getAllocatableClass(RC);
156 getAllocatableSetForRC(MF, SubClass, Allocatable);
158 for (TargetRegisterInfo::regclass_iterator I = regclass_begin(),
159 E = regclass_end(); I != E; ++I)
160 if ((*I)->isAllocatable())
161 getAllocatableSetForRC(MF, *I, Allocatable);
164 // Mask out the reserved registers
165 BitVector Reserved = getReservedRegs(MF);
166 Allocatable &= Reserved.flip();
172 const TargetRegisterClass *firstCommonClass(const uint32_t *A,
174 const TargetRegisterInfo *TRI,
175 const MVT::SimpleValueType SVT =
176 MVT::SimpleValueType::Any) {
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))
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.
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);
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");
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);
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");
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).
230 // The worst case is a register class like DPR on ARM.
231 // We have indices dsub_0..dsub_7 projecting into that class.
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
237 const TargetRegisterClass *BestRC = nullptr;
238 unsigned *BestPreA = &PreA;
239 unsigned *BestPreB = &PreB;
240 if (RCA->getSize() < RCB->getSize()) {
242 std::swap(SubA, SubB);
243 std::swap(BestPreA, BestPreB);
246 // Also terminate the search one we have found a register class as small as
248 unsigned MinSize = RCA->getSize();
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)
259 // The indexes must compose identically: PreA+SubA == PreB+SubB.
260 unsigned FinalB = composeSubRegIndices(IB.getSubReg(), SubB);
261 if (FinalA != FinalB)
264 // Is RC a better candidate than BestRC?
265 if (BestRC && RC->getSize() >= BestRC->getSize())
268 // Yes, RC is the smallest super-register seen so far.
270 *BestPreA = IA.getSubReg();
271 *BestPreB = IB.getSubReg();
273 // Bail early if we reached MinSize. We won't find a better candidate.
274 if (BestRC->getSize() == MinSize)
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,
286 const TargetRegisterClass *SrcRC,
287 unsigned SrcSubReg) {
288 // Same register class.
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;
299 // At most one of the register is a sub register, make it Src to avoid
300 // duplicating the test.
302 std::swap(DefSubReg, SrcSubReg);
303 std::swap(DefRC, SrcRC);
306 // One of the register is a sub register, check if we can get a superclass.
308 return TRI.getMatchingSuperRegClass(SrcRC, DefRC, SrcSubReg) != nullptr;
311 return TRI.getCommonSubClass(DefRC, SrcRC) != nullptr;
314 bool TargetRegisterInfo::shouldRewriteCopySrc(const TargetRegisterClass *DefRC,
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);
322 // Compute target-independent register allocator hints to help eliminate copies.
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);
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");
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);
343 // Check that Phys is a valid hint in VirtReg's register class.
344 if (!isPhysicalRegister(Phys))
346 if (MRI.isReserved(Phys))
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())
354 // All clear, tell the register allocator to prefer this register.
355 Hints.push_back(Phys);
358 bool TargetRegisterInfo::canRealignStack(const MachineFunction &MF) const {
359 return !MF.getFunction()->hasFnAttribute("no-realign-stack");
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))
373 DEBUG(dbgs() << "Can't realign function's stack: " << F->getName() << "\n");
378 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
380 TargetRegisterInfo::dumpReg(unsigned Reg, unsigned SubRegIndex,
381 const TargetRegisterInfo *TRI) {
382 dbgs() << PrintReg(Reg, TRI, SubRegIndex) << "\n";