1 //==- TargetRegisterInfo.cpp - Target Register Information Implementation --==//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This file implements the TargetRegisterInfo interface.
11 //===----------------------------------------------------------------------===//
13 #include "llvm/CodeGen/TargetRegisterInfo.h"
14 #include "llvm/ADT/ArrayRef.h"
15 #include "llvm/ADT/BitVector.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/ADT/StringExtras.h"
18 #include "llvm/CodeGen/MachineFrameInfo.h"
19 #include "llvm/CodeGen/MachineFunction.h"
20 #include "llvm/CodeGen/MachineRegisterInfo.h"
21 #include "llvm/CodeGen/TargetFrameLowering.h"
22 #include "llvm/CodeGen/TargetSubtargetInfo.h"
23 #include "llvm/CodeGen/VirtRegMap.h"
24 #include "llvm/Config/llvm-config.h"
25 #include "llvm/IR/Attributes.h"
26 #include "llvm/IR/Function.h"
27 #include "llvm/MC/MCRegisterInfo.h"
28 #include "llvm/Support/Compiler.h"
29 #include "llvm/Support/Debug.h"
30 #include "llvm/Support/MachineValueType.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
,
89 unsigned SubIdx
, const MachineRegisterInfo
*MRI
) {
90 return Printable([Reg
, TRI
, SubIdx
, MRI
](raw_ostream
&OS
) {
93 else if (TargetRegisterInfo::isStackSlot(Reg
))
94 OS
<< "SS#" << TargetRegisterInfo::stackSlot2Index(Reg
);
95 else if (TargetRegisterInfo::isVirtualRegister(Reg
)) {
96 StringRef Name
= MRI
? MRI
->getVRegName(Reg
) : "";
100 OS
<< '%' << TargetRegisterInfo::virtReg2Index(Reg
);
104 OS
<< '$' << "physreg" << Reg
;
105 else if (Reg
< TRI
->getNumRegs()) {
107 printLowerCase(TRI
->getName(Reg
), OS
);
109 llvm_unreachable("Register kind is unsupported.");
113 OS
<< ':' << TRI
->getSubRegIndexName(SubIdx
);
115 OS
<< ":sub(" << SubIdx
<< ')';
120 Printable
printRegUnit(unsigned Unit
, const TargetRegisterInfo
*TRI
) {
121 return Printable([Unit
, TRI
](raw_ostream
&OS
) {
122 // Generic printout when TRI is missing.
124 OS
<< "Unit~" << Unit
;
128 // Check for invalid register units.
129 if (Unit
>= TRI
->getNumRegUnits()) {
130 OS
<< "BadUnit~" << Unit
;
134 // Normal units have at least one root.
135 MCRegUnitRootIterator
Roots(Unit
, TRI
);
136 assert(Roots
.isValid() && "Unit has no roots.");
137 OS
<< TRI
->getName(*Roots
);
138 for (++Roots
; Roots
.isValid(); ++Roots
)
139 OS
<< '~' << TRI
->getName(*Roots
);
143 Printable
printVRegOrUnit(unsigned Unit
, const TargetRegisterInfo
*TRI
) {
144 return Printable([Unit
, TRI
](raw_ostream
&OS
) {
145 if (TRI
&& TRI
->isVirtualRegister(Unit
)) {
146 OS
<< '%' << TargetRegisterInfo::virtReg2Index(Unit
);
148 OS
<< printRegUnit(Unit
, TRI
);
153 Printable
printRegClassOrBank(unsigned Reg
, const MachineRegisterInfo
&RegInfo
,
154 const TargetRegisterInfo
*TRI
) {
155 return Printable([Reg
, &RegInfo
, TRI
](raw_ostream
&OS
) {
156 if (RegInfo
.getRegClassOrNull(Reg
))
157 OS
<< StringRef(TRI
->getRegClassName(RegInfo
.getRegClass(Reg
))).lower();
158 else if (RegInfo
.getRegBankOrNull(Reg
))
159 OS
<< StringRef(RegInfo
.getRegBankOrNull(Reg
)->getName()).lower();
162 assert((RegInfo
.def_empty(Reg
) || RegInfo
.getType(Reg
).isValid()) &&
163 "Generic registers must have a valid type");
168 } // end namespace llvm
170 /// getAllocatableClass - Return the maximal subclass of the given register
171 /// class that is alloctable, or NULL.
172 const TargetRegisterClass
*
173 TargetRegisterInfo::getAllocatableClass(const TargetRegisterClass
*RC
) const {
174 if (!RC
|| RC
->isAllocatable())
177 for (BitMaskClassIterator
It(RC
->getSubClassMask(), *this); It
.isValid();
179 const TargetRegisterClass
*SubRC
= getRegClass(It
.getID());
180 if (SubRC
->isAllocatable())
186 /// getMinimalPhysRegClass - Returns the Register Class of a physical
187 /// register of the given type, picking the most sub register class of
188 /// the right type that contains this physreg.
189 const TargetRegisterClass
*
190 TargetRegisterInfo::getMinimalPhysRegClass(unsigned reg
, MVT VT
) const {
191 assert(isPhysicalRegister(reg
) && "reg must be a physical register");
193 // Pick the most sub register class of the right type that contains
195 const TargetRegisterClass
* BestRC
= nullptr;
196 for (const TargetRegisterClass
* RC
: regclasses()) {
197 if ((VT
== MVT::Other
|| isTypeLegalForClass(*RC
, VT
)) &&
198 RC
->contains(reg
) && (!BestRC
|| BestRC
->hasSubClass(RC
)))
202 assert(BestRC
&& "Couldn't find the register class");
206 /// getAllocatableSetForRC - Toggle the bits that represent allocatable
207 /// registers for the specific register class.
208 static void getAllocatableSetForRC(const MachineFunction
&MF
,
209 const TargetRegisterClass
*RC
, BitVector
&R
){
210 assert(RC
->isAllocatable() && "invalid for nonallocatable sets");
211 ArrayRef
<MCPhysReg
> Order
= RC
->getRawAllocationOrder(MF
);
212 for (unsigned i
= 0; i
!= Order
.size(); ++i
)
216 BitVector
TargetRegisterInfo::getAllocatableSet(const MachineFunction
&MF
,
217 const TargetRegisterClass
*RC
) const {
218 BitVector
Allocatable(getNumRegs());
220 // A register class with no allocatable subclass returns an empty set.
221 const TargetRegisterClass
*SubClass
= getAllocatableClass(RC
);
223 getAllocatableSetForRC(MF
, SubClass
, Allocatable
);
225 for (const TargetRegisterClass
*C
: regclasses())
226 if (C
->isAllocatable())
227 getAllocatableSetForRC(MF
, C
, Allocatable
);
230 // Mask out the reserved registers
231 BitVector Reserved
= getReservedRegs(MF
);
232 Allocatable
&= Reserved
.flip();
238 const TargetRegisterClass
*firstCommonClass(const uint32_t *A
,
240 const TargetRegisterInfo
*TRI
,
241 const MVT::SimpleValueType SVT
=
242 MVT::SimpleValueType::Any
) {
244 for (unsigned I
= 0, E
= TRI
->getNumRegClasses(); I
< E
; I
+= 32)
245 if (unsigned Common
= *A
++ & *B
++) {
246 const TargetRegisterClass
*RC
=
247 TRI
->getRegClass(I
+ countTrailingZeros(Common
));
248 if (SVT
== MVT::SimpleValueType::Any
|| TRI
->isTypeLegalForClass(*RC
, VT
))
254 const TargetRegisterClass
*
255 TargetRegisterInfo::getCommonSubClass(const TargetRegisterClass
*A
,
256 const TargetRegisterClass
*B
,
257 const MVT::SimpleValueType SVT
) const {
258 // First take care of the trivial cases.
264 // Register classes are ordered topologically, so the largest common
265 // sub-class it the common sub-class with the smallest ID.
266 return firstCommonClass(A
->getSubClassMask(), B
->getSubClassMask(), this, SVT
);
269 const TargetRegisterClass
*
270 TargetRegisterInfo::getMatchingSuperRegClass(const TargetRegisterClass
*A
,
271 const TargetRegisterClass
*B
,
272 unsigned Idx
) const {
273 assert(A
&& B
&& "Missing register class");
274 assert(Idx
&& "Bad sub-register index");
276 // Find Idx in the list of super-register indices.
277 for (SuperRegClassIterator
RCI(B
, this); RCI
.isValid(); ++RCI
)
278 if (RCI
.getSubReg() == Idx
)
279 // The bit mask contains all register classes that are projected into B
280 // by Idx. Find a class that is also a sub-class of A.
281 return firstCommonClass(RCI
.getMask(), A
->getSubClassMask(), this);
285 const TargetRegisterClass
*TargetRegisterInfo::
286 getCommonSuperRegClass(const TargetRegisterClass
*RCA
, unsigned SubA
,
287 const TargetRegisterClass
*RCB
, unsigned SubB
,
288 unsigned &PreA
, unsigned &PreB
) const {
289 assert(RCA
&& SubA
&& RCB
&& SubB
&& "Invalid arguments");
291 // Search all pairs of sub-register indices that project into RCA and RCB
292 // respectively. This is quadratic, but usually the sets are very small. On
293 // most targets like X86, there will only be a single sub-register index
294 // (e.g., sub_16bit projecting into GR16).
296 // The worst case is a register class like DPR on ARM.
297 // We have indices dsub_0..dsub_7 projecting into that class.
299 // It is very common that one register class is a sub-register of the other.
300 // Arrange for RCA to be the larger register so the answer will be found in
301 // the first iteration. This makes the search linear for the most common
303 const TargetRegisterClass
*BestRC
= nullptr;
304 unsigned *BestPreA
= &PreA
;
305 unsigned *BestPreB
= &PreB
;
306 if (getRegSizeInBits(*RCA
) < getRegSizeInBits(*RCB
)) {
308 std::swap(SubA
, SubB
);
309 std::swap(BestPreA
, BestPreB
);
312 // Also terminate the search one we have found a register class as small as
314 unsigned MinSize
= getRegSizeInBits(*RCA
);
316 for (SuperRegClassIterator
IA(RCA
, this, true); IA
.isValid(); ++IA
) {
317 unsigned FinalA
= composeSubRegIndices(IA
.getSubReg(), SubA
);
318 for (SuperRegClassIterator
IB(RCB
, this, true); IB
.isValid(); ++IB
) {
319 // Check if a common super-register class exists for this index pair.
320 const TargetRegisterClass
*RC
=
321 firstCommonClass(IA
.getMask(), IB
.getMask(), this);
322 if (!RC
|| getRegSizeInBits(*RC
) < MinSize
)
325 // The indexes must compose identically: PreA+SubA == PreB+SubB.
326 unsigned FinalB
= composeSubRegIndices(IB
.getSubReg(), SubB
);
327 if (FinalA
!= FinalB
)
330 // Is RC a better candidate than BestRC?
331 if (BestRC
&& getRegSizeInBits(*RC
) >= getRegSizeInBits(*BestRC
))
334 // Yes, RC is the smallest super-register seen so far.
336 *BestPreA
= IA
.getSubReg();
337 *BestPreB
= IB
.getSubReg();
339 // Bail early if we reached MinSize. We won't find a better candidate.
340 if (getRegSizeInBits(*BestRC
) == MinSize
)
347 /// Check if the registers defined by the pair (RegisterClass, SubReg)
348 /// share the same register file.
349 static bool shareSameRegisterFile(const TargetRegisterInfo
&TRI
,
350 const TargetRegisterClass
*DefRC
,
352 const TargetRegisterClass
*SrcRC
,
353 unsigned SrcSubReg
) {
354 // Same register class.
358 // Both operands are sub registers. Check if they share a register class.
359 unsigned SrcIdx
, DefIdx
;
360 if (SrcSubReg
&& DefSubReg
) {
361 return TRI
.getCommonSuperRegClass(SrcRC
, SrcSubReg
, DefRC
, DefSubReg
,
362 SrcIdx
, DefIdx
) != nullptr;
365 // At most one of the register is a sub register, make it Src to avoid
366 // duplicating the test.
368 std::swap(DefSubReg
, SrcSubReg
);
369 std::swap(DefRC
, SrcRC
);
372 // One of the register is a sub register, check if we can get a superclass.
374 return TRI
.getMatchingSuperRegClass(SrcRC
, DefRC
, SrcSubReg
) != nullptr;
377 return TRI
.getCommonSubClass(DefRC
, SrcRC
) != nullptr;
380 bool TargetRegisterInfo::shouldRewriteCopySrc(const TargetRegisterClass
*DefRC
,
382 const TargetRegisterClass
*SrcRC
,
383 unsigned SrcSubReg
) const {
384 // If this source does not incur a cross register bank copy, use it.
385 return shareSameRegisterFile(*this, DefRC
, DefSubReg
, SrcRC
, SrcSubReg
);
388 // Compute target-independent register allocator hints to help eliminate copies.
390 TargetRegisterInfo::getRegAllocationHints(unsigned VirtReg
,
391 ArrayRef
<MCPhysReg
> Order
,
392 SmallVectorImpl
<MCPhysReg
> &Hints
,
393 const MachineFunction
&MF
,
394 const VirtRegMap
*VRM
,
395 const LiveRegMatrix
*Matrix
) const {
396 const MachineRegisterInfo
&MRI
= MF
.getRegInfo();
397 const std::pair
<unsigned, SmallVector
<unsigned, 4>> &Hints_MRI
=
398 MRI
.getRegAllocationHints(VirtReg
);
400 // First hint may be a target hint.
401 bool Skip
= (Hints_MRI
.first
!= 0);
402 for (auto Reg
: Hints_MRI
.second
) {
408 // Target-independent hints are either a physical or a virtual register.
410 if (VRM
&& isVirtualRegister(Phys
))
411 Phys
= VRM
->getPhys(Phys
);
413 // Check that Phys is a valid hint in VirtReg's register class.
414 if (!isPhysicalRegister(Phys
))
416 if (MRI
.isReserved(Phys
))
418 // Check that Phys is in the allocation order. We shouldn't heed hints
419 // from VirtReg's register class if they aren't in the allocation order. The
420 // target probably has a reason for removing the register.
421 if (!is_contained(Order
, Phys
))
424 // All clear, tell the register allocator to prefer this register.
425 Hints
.push_back(Phys
);
430 bool TargetRegisterInfo::canRealignStack(const MachineFunction
&MF
) const {
431 return !MF
.getFunction().hasFnAttribute("no-realign-stack");
434 bool TargetRegisterInfo::needsStackRealignment(
435 const MachineFunction
&MF
) const {
436 const MachineFrameInfo
&MFI
= MF
.getFrameInfo();
437 const TargetFrameLowering
*TFI
= MF
.getSubtarget().getFrameLowering();
438 const Function
&F
= MF
.getFunction();
439 unsigned StackAlign
= TFI
->getStackAlignment();
440 bool requiresRealignment
= ((MFI
.getMaxAlignment() > StackAlign
) ||
441 F
.hasFnAttribute(Attribute::StackAlignment
));
442 if (F
.hasFnAttribute("stackrealign") || requiresRealignment
) {
443 if (canRealignStack(MF
))
445 LLVM_DEBUG(dbgs() << "Can't realign function's stack: " << F
.getName()
451 bool TargetRegisterInfo::regmaskSubsetEqual(const uint32_t *mask0
,
452 const uint32_t *mask1
) const {
453 unsigned N
= (getNumRegs()+31) / 32;
454 for (unsigned I
= 0; I
< N
; ++I
)
455 if ((mask0
[I
] & mask1
[I
]) != mask0
[I
])
460 unsigned TargetRegisterInfo::getRegSizeInBits(unsigned Reg
,
461 const MachineRegisterInfo
&MRI
) const {
462 const TargetRegisterClass
*RC
{};
463 if (isPhysicalRegister(Reg
)) {
464 // The size is not directly available for physical registers.
465 // Instead, we need to access a register class that contains Reg and
466 // get the size of that register class.
467 RC
= getMinimalPhysRegClass(Reg
);
469 LLT Ty
= MRI
.getType(Reg
);
470 unsigned RegSize
= Ty
.isValid() ? Ty
.getSizeInBits() : 0;
471 // If Reg is not a generic register, query the register class to
475 // Since Reg is not a generic register, it must have a register class.
476 RC
= MRI
.getRegClass(Reg
);
478 assert(RC
&& "Unable to deduce the register class");
479 return getRegSizeInBits(*RC
);
483 TargetRegisterInfo::lookThruCopyLike(unsigned SrcReg
,
484 const MachineRegisterInfo
*MRI
) const {
486 const MachineInstr
*MI
= MRI
->getVRegDef(SrcReg
);
487 if (!MI
->isCopyLike())
492 CopySrcReg
= MI
->getOperand(1).getReg();
494 assert(MI
->isSubregToReg() && "Bad opcode for lookThruCopyLike");
495 CopySrcReg
= MI
->getOperand(2).getReg();
498 if (!isVirtualRegister(CopySrcReg
))
505 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
507 void TargetRegisterInfo::dumpReg(unsigned Reg
, unsigned SubRegIndex
,
508 const TargetRegisterInfo
*TRI
) {
509 dbgs() << printReg(Reg
, TRI
, SubRegIndex
) << "\n";