LLVM 20.0.0git
RegAllocBase.cpp
Go to the documentation of this file.
1//===- RegAllocBase.cpp - Register Allocator Base Class -------------------===//
2//
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
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines the RegAllocBase class which provides common functionality
10// for LiveIntervalUnion-based register allocators.
11//
12//===----------------------------------------------------------------------===//
13
14#include "RegAllocBase.h"
16#include "llvm/ADT/Statistic.h"
27#include "llvm/IR/Module.h"
28#include "llvm/Pass.h"
30#include "llvm/Support/Debug.h"
32#include "llvm/Support/Timer.h"
34#include <cassert>
35
36using namespace llvm;
37
38#define DEBUG_TYPE "regalloc"
39
40STATISTIC(NumNewQueued, "Number of new live ranges queued");
41
42// Temporary verification option until we can put verification inside
43// MachineVerifier.
46 cl::Hidden, cl::desc("Verify during register allocation"));
47
48const char RegAllocBase::TimerGroupName[] = "regalloc";
49const char RegAllocBase::TimerGroupDescription[] = "Register Allocation";
51
52//===----------------------------------------------------------------------===//
53// RegAllocBase Implementation
54//===----------------------------------------------------------------------===//
55
56// Pin the vtable to this file.
57void RegAllocBase::anchor() {}
58
60 LiveRegMatrix &mat) {
61 TRI = &vrm.getTargetRegInfo();
62 MRI = &vrm.getRegInfo();
63 VRM = &vrm;
64 LIS = &lis;
65 Matrix = &mat;
68}
69
70// Visit all the live registers. If they are already assigned to a physical
71// register, unify them with the corresponding LiveIntervalUnion, otherwise push
72// them on the priority queue for later assignment.
73void RegAllocBase::seedLiveRegs() {
74 NamedRegionTimer T("seed", "Seed Live Regs", TimerGroupName,
76 for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
78 if (MRI->reg_nodbg_empty(Reg))
79 continue;
80 enqueue(&LIS->getInterval(Reg));
81 }
82}
83
84// Top-level driver to manage the queue of unassigned VirtRegs and call the
85// selectOrSplit implementation.
87 seedLiveRegs();
88
89 // Continue assigning vregs one at a time to available physical registers.
90 while (const LiveInterval *VirtReg = dequeue()) {
91 assert(!VRM->hasPhys(VirtReg->reg()) && "Register already assigned");
92
93 // Unused registers can appear when the spiller coalesces snippets.
94 if (MRI->reg_nodbg_empty(VirtReg->reg())) {
95 LLVM_DEBUG(dbgs() << "Dropping unused " << *VirtReg << '\n');
96 aboutToRemoveInterval(*VirtReg);
97 LIS->removeInterval(VirtReg->reg());
98 continue;
99 }
100
101 // Invalidate all interference queries, live ranges could have changed.
103
104 // selectOrSplit requests the allocator to return an available physical
105 // register if possible and populate a list of new live intervals that
106 // result from splitting.
107 LLVM_DEBUG(dbgs() << "\nselectOrSplit "
108 << TRI->getRegClassName(MRI->getRegClass(VirtReg->reg()))
109 << ':' << *VirtReg << '\n');
110
111 using VirtRegVec = SmallVector<Register, 4>;
112
113 VirtRegVec SplitVRegs;
114 MCRegister AvailablePhysReg = selectOrSplit(*VirtReg, SplitVRegs);
115
116 if (AvailablePhysReg == ~0u) {
117 // selectOrSplit failed to find a register!
118 // Probably caused by an inline asm.
119 MachineInstr *MI = nullptr;
120 for (MachineInstr &MIR : MRI->reg_instructions(VirtReg->reg())) {
121 MI = &MIR;
122 if (MI->isInlineAsm())
123 break;
124 }
125
126 const TargetRegisterClass *RC = MRI->getRegClass(VirtReg->reg());
127 AvailablePhysReg = getErrorAssignment(*RC, MI);
128
129 // Keep going after reporting the error.
130 VRM->assignVirt2Phys(VirtReg->reg(), AvailablePhysReg);
131 } else if (AvailablePhysReg)
132 Matrix->assign(*VirtReg, AvailablePhysReg);
133
134 for (Register Reg : SplitVRegs) {
135 assert(LIS->hasInterval(Reg));
136
137 LiveInterval *SplitVirtReg = &LIS->getInterval(Reg);
138 assert(!VRM->hasPhys(SplitVirtReg->reg()) && "Register already assigned");
139 if (MRI->reg_nodbg_empty(SplitVirtReg->reg())) {
140 assert(SplitVirtReg->empty() && "Non-empty but used interval");
141 LLVM_DEBUG(dbgs() << "not queueing unused " << *SplitVirtReg << '\n');
142 aboutToRemoveInterval(*SplitVirtReg);
143 LIS->removeInterval(SplitVirtReg->reg());
144 continue;
145 }
146 LLVM_DEBUG(dbgs() << "queuing new interval: " << *SplitVirtReg << "\n");
147 assert(SplitVirtReg->reg().isVirtual() &&
148 "expect split value in virtual register");
149 enqueue(SplitVirtReg);
150 ++NumNewQueued;
151 }
152 }
153}
154
157 for (auto *DeadInst : DeadRemats) {
159 DeadInst->eraseFromParent();
160 }
161 DeadRemats.clear();
162}
163
165 const Register Reg = LI->reg();
166
167 assert(Reg.isVirtual() && "Can only enqueue virtual registers");
168
169 if (VRM->hasPhys(Reg))
170 return;
171
172 if (shouldAllocateRegister(Reg)) {
173 LLVM_DEBUG(dbgs() << "Enqueuing " << printReg(Reg, TRI) << '\n');
174 enqueueImpl(LI);
175 } else {
176 LLVM_DEBUG(dbgs() << "Not enqueueing " << printReg(Reg, TRI)
177 << " in skipped register class\n");
178 }
179}
180
182 const MachineInstr *CtxMI) {
184
185 // Avoid printing the error for every single instance of the register. It
186 // would be better if this were per register class.
187 bool EmitError = !MF.getProperties().hasProperty(
189 if (EmitError)
191
192 const Function &Fn = MF.getFunction();
193 LLVMContext &Context = Fn.getContext();
194
195 ArrayRef<MCPhysReg> AllocOrder = RegClassInfo.getOrder(&RC);
196 if (AllocOrder.empty()) {
197 // If the allocation order is empty, it likely means all registers in the
198 // class are reserved. We still to need to pick something, so look at the
199 // underlying class.
200 ArrayRef<MCPhysReg> RawRegs = RC.getRegisters();
201
202 if (EmitError) {
204 "no registers from class available to allocate", Fn,
205 CtxMI ? CtxMI->getDebugLoc() : DiagnosticLocation()));
206 }
207
208 assert(!RawRegs.empty() && "register classes cannot have no registers");
209 return RawRegs.front();
210 }
211
212 if (EmitError) {
213 if (CtxMI && CtxMI->isInlineAsm()) {
214 CtxMI->emitInlineAsmError(
215 "inline assembly requires more registers than available");
216 } else {
218 "ran out of registers during register allocation", Fn,
219 CtxMI ? CtxMI->getDebugLoc() : DiagnosticLocation()));
220 }
221 }
222
223 return AllocOrder.front();
224}
#define LLVM_DEBUG(...)
Definition: Debug.h:106
IRTranslator LLVM IR MI
Module.h This file contains the declarations for the Module class.
static cl::opt< bool, true > VerifyRegAlloc("verify-regalloc", cl::location(RegAllocBase::VerifyEnabled), cl::Hidden, cl::desc("Verify during register allocation"))
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition: Statistic.h:166
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
const T & front() const
front - Get the first element.
Definition: ArrayRef.h:171
bool empty() const
empty - Check if the array is empty.
Definition: ArrayRef.h:163
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function.
Definition: Function.cpp:369
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:67
void diagnose(const DiagnosticInfo &DI)
Report a message to the currently installed diagnostic handler.
LiveInterval - This class represents the liveness of a register, or stack slot.
Definition: LiveInterval.h:687
Register reg() const
Definition: LiveInterval.h:718
bool hasInterval(Register Reg) const
void RemoveMachineInstrFromMaps(MachineInstr &MI)
LiveInterval & getInterval(Register Reg)
void removeInterval(Register Reg)
Interval removal.
bool empty() const
Definition: LiveInterval.h:382
void invalidateVirtRegs()
Invalidate cached interference queries after modifying virtual register live ranges.
Definition: LiveRegMatrix.h:85
void assign(const LiveInterval &VirtReg, MCRegister PhysReg)
Assign VirtReg to PhysReg.
Wrapper class representing physical registers. Should be passed by value.
Definition: MCRegister.h:33
MachineFunctionProperties & set(Property P)
bool hasProperty(Property P) const
Function & getFunction()
Return the LLVM function that this machine code represents.
const MachineFunctionProperties & getProperties() const
Get the function properties.
Representation of each machine instruction.
Definition: MachineInstr.h:69
bool isInlineAsm() const
const DebugLoc & getDebugLoc() const
Returns the debug location id of this MachineInstr.
Definition: MachineInstr.h:499
void emitInlineAsmError(const Twine &ErrMsg) const
Emit an error referring to the source location of this instruction.
void freezeReservedRegs()
freezeReservedRegs - Called by the register allocator to freeze the set of reserved registers before ...
const TargetRegisterClass * getRegClass(Register Reg) const
Return the register class of the specified virtual register.
bool reg_nodbg_empty(Register RegNo) const
reg_nodbg_empty - Return true if the only instructions using or defining Reg are Debug instructions.
iterator_range< reg_instr_iterator > reg_instructions(Register Reg) const
unsigned getNumVirtRegs() const
getNumVirtRegs - Return the number of virtual registers created.
virtual void aboutToRemoveInterval(const LiveInterval &LI)
Method called when the allocator is about to remove a LiveInterval.
Definition: RegAllocBase.h:137
virtual MCRegister selectOrSplit(const LiveInterval &VirtReg, SmallVectorImpl< Register > &splitLVRs)=0
MCPhysReg getErrorAssignment(const TargetRegisterClass &RC, const MachineInstr *CtxMI=nullptr)
Query a physical register to use as a filler in contexts where the allocation has failed.
void enqueue(const LiveInterval *LI)
enqueue - Add VirtReg to the priority queue of unassigned registers.
void init(VirtRegMap &vrm, LiveIntervals &lis, LiveRegMatrix &mat)
SmallPtrSet< MachineInstr *, 32 > DeadRemats
Inst which is a def of an original reg and whose defs are already all dead after remat is saved in De...
Definition: RegAllocBase.h:82
virtual Spiller & spiller()=0
const TargetRegisterInfo * TRI
Definition: RegAllocBase.h:66
LiveIntervals * LIS
Definition: RegAllocBase.h:69
static const char TimerGroupName[]
Definition: RegAllocBase.h:133
static const char TimerGroupDescription[]
Definition: RegAllocBase.h:134
LiveRegMatrix * Matrix
Definition: RegAllocBase.h:70
virtual const LiveInterval * dequeue()=0
dequeue - Return the next unassigned register, or NULL.
virtual void postOptimization()
VirtRegMap * VRM
Definition: RegAllocBase.h:68
RegisterClassInfo RegClassInfo
Definition: RegAllocBase.h:71
MachineRegisterInfo * MRI
Definition: RegAllocBase.h:67
virtual void enqueueImpl(const LiveInterval *LI)=0
enqueue - Add VirtReg to the priority queue of unassigned registers.
bool shouldAllocateRegister(Register Reg)
Get whether a given register should be allocated.
Definition: RegAllocBase.h:93
static bool VerifyEnabled
VerifyEnabled - True when -verify-regalloc is given.
Definition: RegAllocBase.h:141
void runOnMachineFunction(const MachineFunction &MF)
runOnFunction - Prepare to answer questions about MF.
ArrayRef< MCPhysReg > getOrder(const TargetRegisterClass *RC) const
getOrder - Returns the preferred allocation order for RC.
Wrapper class representing virtual and physical registers.
Definition: Register.h:19
static Register index2VirtReg(unsigned Index)
Convert a 0-based index to a virtual register number.
Definition: Register.h:84
constexpr bool isVirtual() const
Return true if the specified register number is in the virtual register namespace.
Definition: Register.h:91
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1196
virtual void postOptimization()
Definition: Spiller.h:43
ArrayRef< MCPhysReg > getRegisters() const
const char * getRegClassName(const TargetRegisterClass *Class) const
Returns the name of the register class.
MachineRegisterInfo & getRegInfo() const
Definition: VirtRegMap.h:79
MachineFunction & getMachineFunction() const
Definition: VirtRegMap.h:74
bool hasPhys(Register virtReg) const
returns true if the specified virtual register is mapped to a physical register
Definition: VirtRegMap.h:86
const TargetRegisterInfo & getTargetRegInfo() const
Definition: VirtRegMap.h:80
void assignVirt2Phys(Register virtReg, MCPhysReg physReg)
creates a mapping for the specified virtual register to the specified physical register
Definition: VirtRegMap.cpp:86
LocationClass< Ty > location(Ty &L)
Definition: CommandLine.h:463
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
bool TimePassesIsEnabled
If the user specifies the -time-passes argument on an LLVM tool command line then the value of this b...
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:163
Printable printReg(Register Reg, const TargetRegisterInfo *TRI=nullptr, unsigned SubIdx=0, const MachineRegisterInfo *MRI=nullptr)
Prints virtual and physical registers with or without a TRI instance.
This class is basically a combination of TimeRegion and Timer.
Definition: Timer.h:163