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/CodeGen/TargetRegisterInfo.h"
15 #include "llvm/ADT/ArrayRef.h"
16 #include "llvm/ADT/BitVector.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/StringExtras.h"
19 #include "llvm/CodeGen/MachineFrameInfo.h"
20 #include "llvm/CodeGen/MachineFunction.h"
21 #include "llvm/CodeGen/MachineRegisterInfo.h"
22 #include "llvm/CodeGen/MachineValueType.h"
23 #include "llvm/CodeGen/TargetFrameLowering.h"
24 #include "llvm/CodeGen/TargetSubtargetInfo.h"
25 #include "llvm/CodeGen/VirtRegMap.h"
26 #include "llvm/IR/Attributes.h"
27 #include "llvm/IR/Function.h"
28 #include "llvm/MC/MCRegisterInfo.h"
29 #include "llvm/Support/Compiler.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/Support/MathExtras.h"
32 #include "llvm/Support/Printable.h"
33 #include "llvm/Support/raw_ostream.h"
37 #define DEBUG_TYPE "target-reg-info"
41 TargetRegisterInfo::TargetRegisterInfo(const TargetRegisterInfoDesc *ID,
42 regclass_iterator RCB, regclass_iterator RCE,
43 const char *const *SRINames,
44 const LaneBitmask *SRILaneMasks,
45 LaneBitmask SRICoveringLanes,
46 const RegClassInfo *const RCIs,
48 : InfoDesc(ID), SubRegIndexNames(SRINames),
49 SubRegIndexLaneMasks(SRILaneMasks),
50 RegClassBegin(RCB), RegClassEnd(RCE),
51 CoveringLanes(SRICoveringLanes),
52 RCInfos(RCIs), HwMode(Mode) {
55 TargetRegisterInfo::~TargetRegisterInfo() = default;
57 void TargetRegisterInfo::markSuperRegs(BitVector &RegisterSet, unsigned Reg)
59 for (MCSuperRegIterator AI(Reg, this, true); AI.isValid(); ++AI)
63 bool TargetRegisterInfo::checkAllSuperRegsMarked(const BitVector &RegisterSet,
64 ArrayRef<MCPhysReg> Exceptions) const {
65 // Check that all super registers of reserved regs are reserved as well.
66 BitVector Checked(getNumRegs());
67 for (unsigned Reg : RegisterSet.set_bits()) {
70 for (MCSuperRegIterator SR(Reg, this); SR.isValid(); ++SR) {
71 if (!RegisterSet[*SR] && !is_contained(Exceptions, Reg)) {
72 dbgs() << "Error: Super register " << printReg(*SR, this)
73 << " of reserved register " << printReg(Reg, this)
74 << " is not reserved.\n";
78 // We transitively check superregs. So we can remember this for later
79 // to avoid compiletime explosion in deep register hierarchies.
88 Printable printReg(unsigned Reg, const TargetRegisterInfo *TRI,
90 return Printable([Reg, TRI, SubIdx](raw_ostream &OS) {
93 else if (TargetRegisterInfo::isStackSlot(Reg))
94 OS << "SS#" << TargetRegisterInfo::stackSlot2Index(Reg);
95 else if (TargetRegisterInfo::isVirtualRegister(Reg))
96 OS << '%' << TargetRegisterInfo::virtReg2Index(Reg);
98 OS << '%' << "physreg" << Reg;
99 else if (Reg < TRI->getNumRegs()) {
101 printLowerCase(TRI->getName(Reg), OS);
103 llvm_unreachable("Register kind is unsupported.");
107 OS << ':' << TRI->getSubRegIndexName(SubIdx);
109 OS << ":sub(" << SubIdx << ')';
114 Printable printRegUnit(unsigned Unit, const TargetRegisterInfo *TRI) {
115 return Printable([Unit, TRI](raw_ostream &OS) {
116 // Generic printout when TRI is missing.
118 OS << "Unit~" << Unit;
122 // Check for invalid register units.
123 if (Unit >= TRI->getNumRegUnits()) {
124 OS << "BadUnit~" << Unit;
128 // Normal units have at least one root.
129 MCRegUnitRootIterator Roots(Unit, TRI);
130 assert(Roots.isValid() && "Unit has no roots.");
131 OS << TRI->getName(*Roots);
132 for (++Roots; Roots.isValid(); ++Roots)
133 OS << '~' << TRI->getName(*Roots);
137 Printable printVRegOrUnit(unsigned Unit, const TargetRegisterInfo *TRI) {
138 return Printable([Unit, TRI](raw_ostream &OS) {
139 if (TRI && TRI->isVirtualRegister(Unit)) {
140 OS << '%' << TargetRegisterInfo::virtReg2Index(Unit);
142 OS << printRegUnit(Unit, TRI);
147 Printable printRegClassOrBank(unsigned Reg, const MachineRegisterInfo &RegInfo,
148 const TargetRegisterInfo *TRI) {
149 return Printable([Reg, &RegInfo, TRI](raw_ostream &OS) {
150 if (RegInfo.getRegClassOrNull(Reg))
151 OS << StringRef(TRI->getRegClassName(RegInfo.getRegClass(Reg))).lower();
152 else if (RegInfo.getRegBankOrNull(Reg))
153 OS << StringRef(RegInfo.getRegBankOrNull(Reg)->getName()).lower();
156 assert((RegInfo.def_empty(Reg) || RegInfo.getType(Reg).isValid()) &&
157 "Generic registers must have a valid type");
162 } // end namespace llvm
164 /// getAllocatableClass - Return the maximal subclass of the given register
165 /// class that is alloctable, or NULL.
166 const TargetRegisterClass *
167 TargetRegisterInfo::getAllocatableClass(const TargetRegisterClass *RC) const {
168 if (!RC || RC->isAllocatable())
171 for (BitMaskClassIterator It(RC->getSubClassMask(), *this); It.isValid();
173 const TargetRegisterClass *SubRC = getRegClass(It.getID());
174 if (SubRC->isAllocatable())
180 /// getMinimalPhysRegClass - Returns the Register Class of a physical
181 /// register of the given type, picking the most sub register class of
182 /// the right type that contains this physreg.
183 const TargetRegisterClass *
184 TargetRegisterInfo::getMinimalPhysRegClass(unsigned reg, MVT VT) const {
185 assert(isPhysicalRegister(reg) && "reg must be a physical register");
187 // Pick the most sub register class of the right type that contains
189 const TargetRegisterClass* BestRC = nullptr;
190 for (const TargetRegisterClass* RC : regclasses()) {
191 if ((VT == MVT::Other || isTypeLegalForClass(*RC, VT)) &&
192 RC->contains(reg) && (!BestRC || BestRC->hasSubClass(RC)))
196 assert(BestRC && "Couldn't find the register class");
200 /// getAllocatableSetForRC - Toggle the bits that represent allocatable
201 /// registers for the specific register class.
202 static void getAllocatableSetForRC(const MachineFunction &MF,
203 const TargetRegisterClass *RC, BitVector &R){
204 assert(RC->isAllocatable() && "invalid for nonallocatable sets");
205 ArrayRef<MCPhysReg> Order = RC->getRawAllocationOrder(MF);
206 for (unsigned i = 0; i != Order.size(); ++i)
210 BitVector TargetRegisterInfo::getAllocatableSet(const MachineFunction &MF,
211 const TargetRegisterClass *RC) const {
212 BitVector Allocatable(getNumRegs());
214 // A register class with no allocatable subclass returns an empty set.
215 const TargetRegisterClass *SubClass = getAllocatableClass(RC);
217 getAllocatableSetForRC(MF, SubClass, Allocatable);
219 for (const TargetRegisterClass *C : regclasses())
220 if (C->isAllocatable())
221 getAllocatableSetForRC(MF, C, Allocatable);
224 // Mask out the reserved registers
225 BitVector Reserved = getReservedRegs(MF);
226 Allocatable &= Reserved.flip();
232 const TargetRegisterClass *firstCommonClass(const uint32_t *A,
234 const TargetRegisterInfo *TRI,
235 const MVT::SimpleValueType SVT =
236 MVT::SimpleValueType::Any) {
238 for (unsigned I = 0, E = TRI->getNumRegClasses(); I < E; I += 32)
239 if (unsigned Common = *A++ & *B++) {
240 const TargetRegisterClass *RC =
241 TRI->getRegClass(I + countTrailingZeros(Common));
242 if (SVT == MVT::SimpleValueType::Any || TRI->isTypeLegalForClass(*RC, VT))
248 const TargetRegisterClass *
249 TargetRegisterInfo::getCommonSubClass(const TargetRegisterClass *A,
250 const TargetRegisterClass *B,
251 const MVT::SimpleValueType SVT) const {
252 // First take care of the trivial cases.
258 // Register classes are ordered topologically, so the largest common
259 // sub-class it the common sub-class with the smallest ID.
260 return firstCommonClass(A->getSubClassMask(), B->getSubClassMask(), this, SVT);
263 const TargetRegisterClass *
264 TargetRegisterInfo::getMatchingSuperRegClass(const TargetRegisterClass *A,
265 const TargetRegisterClass *B,
266 unsigned Idx) const {
267 assert(A && B && "Missing register class");
268 assert(Idx && "Bad sub-register index");
270 // Find Idx in the list of super-register indices.
271 for (SuperRegClassIterator RCI(B, this); RCI.isValid(); ++RCI)
272 if (RCI.getSubReg() == Idx)
273 // The bit mask contains all register classes that are projected into B
274 // by Idx. Find a class that is also a sub-class of A.
275 return firstCommonClass(RCI.getMask(), A->getSubClassMask(), this);
279 const TargetRegisterClass *TargetRegisterInfo::
280 getCommonSuperRegClass(const TargetRegisterClass *RCA, unsigned SubA,
281 const TargetRegisterClass *RCB, unsigned SubB,
282 unsigned &PreA, unsigned &PreB) const {
283 assert(RCA && SubA && RCB && SubB && "Invalid arguments");
285 // Search all pairs of sub-register indices that project into RCA and RCB
286 // respectively. This is quadratic, but usually the sets are very small. On
287 // most targets like X86, there will only be a single sub-register index
288 // (e.g., sub_16bit projecting into GR16).
290 // The worst case is a register class like DPR on ARM.
291 // We have indices dsub_0..dsub_7 projecting into that class.
293 // It is very common that one register class is a sub-register of the other.
294 // Arrange for RCA to be the larger register so the answer will be found in
295 // the first iteration. This makes the search linear for the most common
297 const TargetRegisterClass *BestRC = nullptr;
298 unsigned *BestPreA = &PreA;
299 unsigned *BestPreB = &PreB;
300 if (getRegSizeInBits(*RCA) < getRegSizeInBits(*RCB)) {
302 std::swap(SubA, SubB);
303 std::swap(BestPreA, BestPreB);
306 // Also terminate the search one we have found a register class as small as
308 unsigned MinSize = getRegSizeInBits(*RCA);
310 for (SuperRegClassIterator IA(RCA, this, true); IA.isValid(); ++IA) {
311 unsigned FinalA = composeSubRegIndices(IA.getSubReg(), SubA);
312 for (SuperRegClassIterator IB(RCB, this, true); IB.isValid(); ++IB) {
313 // Check if a common super-register class exists for this index pair.
314 const TargetRegisterClass *RC =
315 firstCommonClass(IA.getMask(), IB.getMask(), this);
316 if (!RC || getRegSizeInBits(*RC) < MinSize)
319 // The indexes must compose identically: PreA+SubA == PreB+SubB.
320 unsigned FinalB = composeSubRegIndices(IB.getSubReg(), SubB);
321 if (FinalA != FinalB)
324 // Is RC a better candidate than BestRC?
325 if (BestRC && getRegSizeInBits(*RC) >= getRegSizeInBits(*BestRC))
328 // Yes, RC is the smallest super-register seen so far.
330 *BestPreA = IA.getSubReg();
331 *BestPreB = IB.getSubReg();
333 // Bail early if we reached MinSize. We won't find a better candidate.
334 if (getRegSizeInBits(*BestRC) == MinSize)
341 /// \brief Check if the registers defined by the pair (RegisterClass, SubReg)
342 /// share the same register file.
343 static bool shareSameRegisterFile(const TargetRegisterInfo &TRI,
344 const TargetRegisterClass *DefRC,
346 const TargetRegisterClass *SrcRC,
347 unsigned SrcSubReg) {
348 // Same register class.
352 // Both operands are sub registers. Check if they share a register class.
353 unsigned SrcIdx, DefIdx;
354 if (SrcSubReg && DefSubReg) {
355 return TRI.getCommonSuperRegClass(SrcRC, SrcSubReg, DefRC, DefSubReg,
356 SrcIdx, DefIdx) != nullptr;
359 // At most one of the register is a sub register, make it Src to avoid
360 // duplicating the test.
362 std::swap(DefSubReg, SrcSubReg);
363 std::swap(DefRC, SrcRC);
366 // One of the register is a sub register, check if we can get a superclass.
368 return TRI.getMatchingSuperRegClass(SrcRC, DefRC, SrcSubReg) != nullptr;
371 return TRI.getCommonSubClass(DefRC, SrcRC) != nullptr;
374 bool TargetRegisterInfo::shouldRewriteCopySrc(const TargetRegisterClass *DefRC,
376 const TargetRegisterClass *SrcRC,
377 unsigned SrcSubReg) const {
378 // If this source does not incur a cross register bank copy, use it.
379 return shareSameRegisterFile(*this, DefRC, DefSubReg, SrcRC, SrcSubReg);
382 // Compute target-independent register allocator hints to help eliminate copies.
384 TargetRegisterInfo::getRegAllocationHints(unsigned VirtReg,
385 ArrayRef<MCPhysReg> Order,
386 SmallVectorImpl<MCPhysReg> &Hints,
387 const MachineFunction &MF,
388 const VirtRegMap *VRM,
389 const LiveRegMatrix *Matrix) const {
390 const MachineRegisterInfo &MRI = MF.getRegInfo();
391 const std::pair<unsigned, SmallVector<unsigned, 4>> &Hints_MRI =
392 MRI.getRegAllocationHints(VirtReg);
394 // First hint may be a target hint.
395 bool Skip = (Hints_MRI.first != 0);
396 for (auto Reg : Hints_MRI.second) {
402 // Target-independent hints are either a physical or a virtual register.
404 if (VRM && isVirtualRegister(Phys))
405 Phys = VRM->getPhys(Phys);
407 // Check that Phys is a valid hint in VirtReg's register class.
408 if (!isPhysicalRegister(Phys))
410 if (MRI.isReserved(Phys))
412 // Check that Phys is in the allocation order. We shouldn't heed hints
413 // from VirtReg's register class if they aren't in the allocation order. The
414 // target probably has a reason for removing the register.
415 if (!is_contained(Order, Phys))
418 // All clear, tell the register allocator to prefer this register.
419 Hints.push_back(Phys);
424 bool TargetRegisterInfo::canRealignStack(const MachineFunction &MF) const {
425 return !MF.getFunction().hasFnAttribute("no-realign-stack");
428 bool TargetRegisterInfo::needsStackRealignment(
429 const MachineFunction &MF) const {
430 const MachineFrameInfo &MFI = MF.getFrameInfo();
431 const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering();
432 const Function &F = MF.getFunction();
433 unsigned StackAlign = TFI->getStackAlignment();
434 bool requiresRealignment = ((MFI.getMaxAlignment() > StackAlign) ||
435 F.hasFnAttribute(Attribute::StackAlignment));
436 if (F.hasFnAttribute("stackrealign") || requiresRealignment) {
437 if (canRealignStack(MF))
439 DEBUG(dbgs() << "Can't realign function's stack: " << F.getName() << "\n");
444 bool TargetRegisterInfo::regmaskSubsetEqual(const uint32_t *mask0,
445 const uint32_t *mask1) const {
446 unsigned N = (getNumRegs()+31) / 32;
447 for (unsigned I = 0; I < N; ++I)
448 if ((mask0[I] & mask1[I]) != mask0[I])
453 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
455 void TargetRegisterInfo::dumpReg(unsigned Reg, unsigned SubRegIndex,
456 const TargetRegisterInfo *TRI) {
457 dbgs() << printReg(Reg, TRI, SubRegIndex) << "\n";