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/SmallSet.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/TargetFrameLowering.h"
23 #include "llvm/CodeGen/TargetSubtargetInfo.h"
24 #include "llvm/CodeGen/VirtRegMap.h"
25 #include "llvm/Config/llvm-config.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/MachineValueType.h"
32 #include "llvm/Support/MathExtras.h"
33 #include "llvm/Support/Printable.h"
34 #include "llvm/Support/raw_ostream.h"
38 #define DEBUG_TYPE "target-reg-info"
42 TargetRegisterInfo::TargetRegisterInfo(const TargetRegisterInfoDesc
*ID
,
43 regclass_iterator RCB
, regclass_iterator RCE
,
44 const char *const *SRINames
,
45 const LaneBitmask
*SRILaneMasks
,
46 LaneBitmask SRICoveringLanes
,
47 const RegClassInfo
*const RCIs
,
49 : InfoDesc(ID
), SubRegIndexNames(SRINames
),
50 SubRegIndexLaneMasks(SRILaneMasks
),
51 RegClassBegin(RCB
), RegClassEnd(RCE
),
52 CoveringLanes(SRICoveringLanes
),
53 RCInfos(RCIs
), HwMode(Mode
) {
56 TargetRegisterInfo::~TargetRegisterInfo() = default;
58 void TargetRegisterInfo::markSuperRegs(BitVector
&RegisterSet
, unsigned Reg
)
60 for (MCSuperRegIterator
AI(Reg
, this, true); AI
.isValid(); ++AI
)
64 bool TargetRegisterInfo::checkAllSuperRegsMarked(const BitVector
&RegisterSet
,
65 ArrayRef
<MCPhysReg
> Exceptions
) const {
66 // Check that all super registers of reserved regs are reserved as well.
67 BitVector
Checked(getNumRegs());
68 for (unsigned Reg
: RegisterSet
.set_bits()) {
71 for (MCSuperRegIterator
SR(Reg
, this); SR
.isValid(); ++SR
) {
72 if (!RegisterSet
[*SR
] && !is_contained(Exceptions
, Reg
)) {
73 dbgs() << "Error: Super register " << printReg(*SR
, this)
74 << " of reserved register " << printReg(Reg
, this)
75 << " is not reserved.\n";
79 // We transitively check superregs. So we can remember this for later
80 // to avoid compiletime explosion in deep register hierarchies.
89 Printable
printReg(Register Reg
, const TargetRegisterInfo
*TRI
,
90 unsigned SubIdx
, const MachineRegisterInfo
*MRI
) {
91 return Printable([Reg
, TRI
, SubIdx
, MRI
](raw_ostream
&OS
) {
94 else if (Register::isStackSlot(Reg
))
95 OS
<< "SS#" << Register::stackSlot2Index(Reg
);
96 else if (Register::isVirtualRegister(Reg
)) {
97 StringRef Name
= MRI
? MRI
->getVRegName(Reg
) : "";
101 OS
<< '%' << Register::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 (Register::isVirtualRegister(Unit
)) {
146 OS
<< '%' << Register::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(Register::isPhysicalRegister(reg
) &&
192 "reg must be a physical register");
194 // Pick the most sub register class of the right type that contains
196 const TargetRegisterClass
* BestRC
= nullptr;
197 for (const TargetRegisterClass
* RC
: regclasses()) {
198 if ((VT
== MVT::Other
|| isTypeLegalForClass(*RC
, VT
)) &&
199 RC
->contains(reg
) && (!BestRC
|| BestRC
->hasSubClass(RC
)))
203 assert(BestRC
&& "Couldn't find the register class");
207 /// getAllocatableSetForRC - Toggle the bits that represent allocatable
208 /// registers for the specific register class.
209 static void getAllocatableSetForRC(const MachineFunction
&MF
,
210 const TargetRegisterClass
*RC
, BitVector
&R
){
211 assert(RC
->isAllocatable() && "invalid for nonallocatable sets");
212 ArrayRef
<MCPhysReg
> Order
= RC
->getRawAllocationOrder(MF
);
213 for (unsigned i
= 0; i
!= Order
.size(); ++i
)
217 BitVector
TargetRegisterInfo::getAllocatableSet(const MachineFunction
&MF
,
218 const TargetRegisterClass
*RC
) const {
219 BitVector
Allocatable(getNumRegs());
221 // A register class with no allocatable subclass returns an empty set.
222 const TargetRegisterClass
*SubClass
= getAllocatableClass(RC
);
224 getAllocatableSetForRC(MF
, SubClass
, Allocatable
);
226 for (const TargetRegisterClass
*C
: regclasses())
227 if (C
->isAllocatable())
228 getAllocatableSetForRC(MF
, C
, Allocatable
);
231 // Mask out the reserved registers
232 BitVector Reserved
= getReservedRegs(MF
);
233 Allocatable
&= Reserved
.flip();
239 const TargetRegisterClass
*firstCommonClass(const uint32_t *A
,
241 const TargetRegisterInfo
*TRI
) {
242 for (unsigned I
= 0, E
= TRI
->getNumRegClasses(); I
< E
; I
+= 32)
243 if (unsigned Common
= *A
++ & *B
++)
244 return TRI
->getRegClass(I
+ countTrailingZeros(Common
));
248 const TargetRegisterClass
*
249 TargetRegisterInfo::getCommonSubClass(const TargetRegisterClass
*A
,
250 const TargetRegisterClass
*B
) const {
251 // First take care of the trivial cases.
257 // Register classes are ordered topologically, so the largest common
258 // sub-class it the common sub-class with the smallest ID.
259 return firstCommonClass(A
->getSubClassMask(), B
->getSubClassMask(), this);
262 const TargetRegisterClass
*
263 TargetRegisterInfo::getMatchingSuperRegClass(const TargetRegisterClass
*A
,
264 const TargetRegisterClass
*B
,
265 unsigned Idx
) const {
266 assert(A
&& B
&& "Missing register class");
267 assert(Idx
&& "Bad sub-register index");
269 // Find Idx in the list of super-register indices.
270 for (SuperRegClassIterator
RCI(B
, this); RCI
.isValid(); ++RCI
)
271 if (RCI
.getSubReg() == Idx
)
272 // The bit mask contains all register classes that are projected into B
273 // by Idx. Find a class that is also a sub-class of A.
274 return firstCommonClass(RCI
.getMask(), A
->getSubClassMask(), this);
278 const TargetRegisterClass
*TargetRegisterInfo::
279 getCommonSuperRegClass(const TargetRegisterClass
*RCA
, unsigned SubA
,
280 const TargetRegisterClass
*RCB
, unsigned SubB
,
281 unsigned &PreA
, unsigned &PreB
) const {
282 assert(RCA
&& SubA
&& RCB
&& SubB
&& "Invalid arguments");
284 // Search all pairs of sub-register indices that project into RCA and RCB
285 // respectively. This is quadratic, but usually the sets are very small. On
286 // most targets like X86, there will only be a single sub-register index
287 // (e.g., sub_16bit projecting into GR16).
289 // The worst case is a register class like DPR on ARM.
290 // We have indices dsub_0..dsub_7 projecting into that class.
292 // It is very common that one register class is a sub-register of the other.
293 // Arrange for RCA to be the larger register so the answer will be found in
294 // the first iteration. This makes the search linear for the most common
296 const TargetRegisterClass
*BestRC
= nullptr;
297 unsigned *BestPreA
= &PreA
;
298 unsigned *BestPreB
= &PreB
;
299 if (getRegSizeInBits(*RCA
) < getRegSizeInBits(*RCB
)) {
301 std::swap(SubA
, SubB
);
302 std::swap(BestPreA
, BestPreB
);
305 // Also terminate the search one we have found a register class as small as
307 unsigned MinSize
= getRegSizeInBits(*RCA
);
309 for (SuperRegClassIterator
IA(RCA
, this, true); IA
.isValid(); ++IA
) {
310 unsigned FinalA
= composeSubRegIndices(IA
.getSubReg(), SubA
);
311 for (SuperRegClassIterator
IB(RCB
, this, true); IB
.isValid(); ++IB
) {
312 // Check if a common super-register class exists for this index pair.
313 const TargetRegisterClass
*RC
=
314 firstCommonClass(IA
.getMask(), IB
.getMask(), this);
315 if (!RC
|| getRegSizeInBits(*RC
) < MinSize
)
318 // The indexes must compose identically: PreA+SubA == PreB+SubB.
319 unsigned FinalB
= composeSubRegIndices(IB
.getSubReg(), SubB
);
320 if (FinalA
!= FinalB
)
323 // Is RC a better candidate than BestRC?
324 if (BestRC
&& getRegSizeInBits(*RC
) >= getRegSizeInBits(*BestRC
))
327 // Yes, RC is the smallest super-register seen so far.
329 *BestPreA
= IA
.getSubReg();
330 *BestPreB
= IB
.getSubReg();
332 // Bail early if we reached MinSize. We won't find a better candidate.
333 if (getRegSizeInBits(*BestRC
) == MinSize
)
340 /// Check if the registers defined by the pair (RegisterClass, SubReg)
341 /// share the same register file.
342 static bool shareSameRegisterFile(const TargetRegisterInfo
&TRI
,
343 const TargetRegisterClass
*DefRC
,
345 const TargetRegisterClass
*SrcRC
,
346 unsigned SrcSubReg
) {
347 // Same register class.
351 // Both operands are sub registers. Check if they share a register class.
352 unsigned SrcIdx
, DefIdx
;
353 if (SrcSubReg
&& DefSubReg
) {
354 return TRI
.getCommonSuperRegClass(SrcRC
, SrcSubReg
, DefRC
, DefSubReg
,
355 SrcIdx
, DefIdx
) != nullptr;
358 // At most one of the register is a sub register, make it Src to avoid
359 // duplicating the test.
361 std::swap(DefSubReg
, SrcSubReg
);
362 std::swap(DefRC
, SrcRC
);
365 // One of the register is a sub register, check if we can get a superclass.
367 return TRI
.getMatchingSuperRegClass(SrcRC
, DefRC
, SrcSubReg
) != nullptr;
370 return TRI
.getCommonSubClass(DefRC
, SrcRC
) != nullptr;
373 bool TargetRegisterInfo::shouldRewriteCopySrc(const TargetRegisterClass
*DefRC
,
375 const TargetRegisterClass
*SrcRC
,
376 unsigned SrcSubReg
) const {
377 // If this source does not incur a cross register bank copy, use it.
378 return shareSameRegisterFile(*this, DefRC
, DefSubReg
, SrcRC
, SrcSubReg
);
381 // Compute target-independent register allocator hints to help eliminate copies.
383 TargetRegisterInfo::getRegAllocationHints(unsigned VirtReg
,
384 ArrayRef
<MCPhysReg
> Order
,
385 SmallVectorImpl
<MCPhysReg
> &Hints
,
386 const MachineFunction
&MF
,
387 const VirtRegMap
*VRM
,
388 const LiveRegMatrix
*Matrix
) const {
389 const MachineRegisterInfo
&MRI
= MF
.getRegInfo();
390 const std::pair
<unsigned, SmallVector
<unsigned, 4>> &Hints_MRI
=
391 MRI
.getRegAllocationHints(VirtReg
);
393 SmallSet
<unsigned, 32> HintedRegs
;
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
&& Register::isVirtualRegister(Phys
))
405 Phys
= VRM
->getPhys(Phys
);
407 // Don't add the same reg twice (Hints_MRI may contain multiple virtual
408 // registers allocated to the same physreg).
409 if (!HintedRegs
.insert(Phys
).second
)
411 // Check that Phys is a valid hint in VirtReg's register class.
412 if (!Register::isPhysicalRegister(Phys
))
414 if (MRI
.isReserved(Phys
))
416 // Check that Phys is in the allocation order. We shouldn't heed hints
417 // from VirtReg's register class if they aren't in the allocation order. The
418 // target probably has a reason for removing the register.
419 if (!is_contained(Order
, Phys
))
422 // All clear, tell the register allocator to prefer this register.
423 Hints
.push_back(Phys
);
428 bool TargetRegisterInfo::isCalleeSavedPhysReg(
429 unsigned PhysReg
, const MachineFunction
&MF
) const {
432 const uint32_t *callerPreservedRegs
=
433 getCallPreservedMask(MF
, MF
.getFunction().getCallingConv());
434 if (callerPreservedRegs
) {
435 assert(Register::isPhysicalRegister(PhysReg
) &&
436 "Expected physical register");
437 return (callerPreservedRegs
[PhysReg
/ 32] >> PhysReg
% 32) & 1;
442 bool TargetRegisterInfo::canRealignStack(const MachineFunction
&MF
) const {
443 return !MF
.getFunction().hasFnAttribute("no-realign-stack");
446 bool TargetRegisterInfo::needsStackRealignment(
447 const MachineFunction
&MF
) const {
448 const MachineFrameInfo
&MFI
= MF
.getFrameInfo();
449 const TargetFrameLowering
*TFI
= MF
.getSubtarget().getFrameLowering();
450 const Function
&F
= MF
.getFunction();
451 unsigned StackAlign
= TFI
->getStackAlignment();
452 bool requiresRealignment
= ((MFI
.getMaxAlignment() > StackAlign
) ||
453 F
.hasFnAttribute(Attribute::StackAlignment
));
454 if (F
.hasFnAttribute("stackrealign") || requiresRealignment
) {
455 if (canRealignStack(MF
))
457 LLVM_DEBUG(dbgs() << "Can't realign function's stack: " << F
.getName()
463 bool TargetRegisterInfo::regmaskSubsetEqual(const uint32_t *mask0
,
464 const uint32_t *mask1
) const {
465 unsigned N
= (getNumRegs()+31) / 32;
466 for (unsigned I
= 0; I
< N
; ++I
)
467 if ((mask0
[I
] & mask1
[I
]) != mask0
[I
])
472 unsigned TargetRegisterInfo::getRegSizeInBits(unsigned Reg
,
473 const MachineRegisterInfo
&MRI
) const {
474 const TargetRegisterClass
*RC
{};
475 if (Register::isPhysicalRegister(Reg
)) {
476 // The size is not directly available for physical registers.
477 // Instead, we need to access a register class that contains Reg and
478 // get the size of that register class.
479 RC
= getMinimalPhysRegClass(Reg
);
481 LLT Ty
= MRI
.getType(Reg
);
482 unsigned RegSize
= Ty
.isValid() ? Ty
.getSizeInBits() : 0;
483 // If Reg is not a generic register, query the register class to
487 // Since Reg is not a generic register, it must have a register class.
488 RC
= MRI
.getRegClass(Reg
);
490 assert(RC
&& "Unable to deduce the register class");
491 return getRegSizeInBits(*RC
);
495 TargetRegisterInfo::lookThruCopyLike(unsigned SrcReg
,
496 const MachineRegisterInfo
*MRI
) const {
498 const MachineInstr
*MI
= MRI
->getVRegDef(SrcReg
);
499 if (!MI
->isCopyLike())
504 CopySrcReg
= MI
->getOperand(1).getReg();
506 assert(MI
->isSubregToReg() && "Bad opcode for lookThruCopyLike");
507 CopySrcReg
= MI
->getOperand(2).getReg();
510 if (!Register::isVirtualRegister(CopySrcReg
))
517 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
519 void TargetRegisterInfo::dumpReg(unsigned Reg
, unsigned SubRegIndex
,
520 const TargetRegisterInfo
*TRI
) {
521 dbgs() << printReg(Reg
, TRI
, SubRegIndex
) << "\n";