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"
15#include "llvm/ADT/SmallVector.h"
16#include "llvm/ADT/Statistic.h"
17#include "llvm/CodeGen/LiveInterval.h"
18#include "llvm/CodeGen/LiveIntervals.h"
19#include "llvm/CodeGen/LiveRegMatrix.h"
20#include "llvm/CodeGen/MachineInstr.h"
21#include "llvm/CodeGen/MachineModuleInfo.h"
22#include "llvm/CodeGen/MachineRegisterInfo.h"
23#include "llvm/CodeGen/Spiller.h"
24#include "llvm/CodeGen/TargetRegisterInfo.h"
25#include "llvm/CodeGen/VirtRegMap.h"
26#include "llvm/IR/DiagnosticInfo.h"
27#include "llvm/IR/Module.h"
28#include "llvm/IR/PassTimingInfo.h"
29#include "llvm/Pass.h"
30#include "llvm/Support/CommandLine.h"
31#include "llvm/Support/Debug.h"
32#include "llvm/Support/ErrorHandling.h"
33#include "llvm/Support/Timer.h"
34#include "llvm/Support/raw_ostream.h"
35#include <cassert>
36
37using namespace llvm;
38
39#define DEBUG_TYPE "regalloc"
40
41STATISTIC(NumNewQueued, "Number of new live ranges queued");
42
43// Temporary verification option until we can put verification inside
44// MachineVerifier.
45static cl::opt<bool, true>
46 VerifyRegAlloc("verify-regalloc", cl::location(L&: RegAllocBase::VerifyEnabled),
47 cl::Hidden, cl::desc("Verify during register allocation"));
48
49const char RegAllocBase::TimerGroupName[] = "regalloc";
50const char RegAllocBase::TimerGroupDescription[] = "Register Allocation";
51bool RegAllocBase::VerifyEnabled = false;
52
53//===----------------------------------------------------------------------===//
54// RegAllocBase Implementation
55//===----------------------------------------------------------------------===//
56
57// Pin the vtable to this file.
58void RegAllocBase::anchor() {}
59
60void RegAllocBase::init(VirtRegMap &vrm, LiveIntervals &lis,
61 LiveRegMatrix &mat) {
62 TRI = &vrm.getTargetRegInfo();
63 MRI = &vrm.getRegInfo();
64 VRM = &vrm;
65 LIS = &lis;
66 Matrix = &mat;
67 MRI->freezeReservedRegs();
68 RegClassInfo.runOnMachineFunction(MF: vrm.getMachineFunction());
69 FailedVRegs.clear();
70}
71
72// Visit all the live registers. If they are already assigned to a physical
73// register, unify them with the corresponding LiveIntervalUnion, otherwise push
74// them on the priority queue for later assignment.
75void RegAllocBase::seedLiveRegs() {
76 NamedRegionTimer T("seed", "Seed Live Regs", TimerGroupName,
77 TimerGroupDescription, TimePassesIsEnabled);
78 for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
79 Register Reg = Register::index2VirtReg(Index: i);
80 if (MRI->reg_nodbg_empty(RegNo: Reg))
81 continue;
82 enqueue(LI: &LIS->getInterval(Reg));
83 }
84}
85
86// Top-level driver to manage the queue of unassigned VirtRegs and call the
87// selectOrSplit implementation.
88void RegAllocBase::allocatePhysRegs() {
89 seedLiveRegs();
90
91 // Continue assigning vregs one at a time to available physical registers.
92 while (const LiveInterval *VirtReg = dequeue()) {
93 assert(!VRM->hasPhys(VirtReg->reg()) && "Register already assigned");
94
95 // Unused registers can appear when the spiller coalesces snippets.
96 if (MRI->reg_nodbg_empty(RegNo: VirtReg->reg())) {
97 LLVM_DEBUG(dbgs() << "Dropping unused " << *VirtReg << '\n');
98 aboutToRemoveInterval(LI: *VirtReg);
99 LIS->removeInterval(Reg: VirtReg->reg());
100 continue;
101 }
102
103 // Invalidate all interference queries, live ranges could have changed.
104 Matrix->invalidateVirtRegs();
105
106 // selectOrSplit requests the allocator to return an available physical
107 // register if possible and populate a list of new live intervals that
108 // result from splitting.
109 LLVM_DEBUG(dbgs() << "\nselectOrSplit "
110 << TRI->getRegClassName(MRI->getRegClass(VirtReg->reg()))
111 << ':' << *VirtReg << '\n');
112
113 using VirtRegVec = SmallVector<Register, 4>;
114
115 VirtRegVec SplitVRegs;
116 MCRegister AvailablePhysReg = selectOrSplit(VirtReg: *VirtReg, splitLVRs&: SplitVRegs);
117
118 if (AvailablePhysReg == ~0u) {
119 // selectOrSplit failed to find a register!
120 // Probably caused by an inline asm.
121 MachineInstr *MI = nullptr;
122 for (MachineInstr &MIR : MRI->reg_instructions(Reg: VirtReg->reg())) {
123 MI = &MIR;
124 if (MI->isInlineAsm())
125 break;
126 }
127
128 const TargetRegisterClass *RC = MRI->getRegClass(Reg: VirtReg->reg());
129 AvailablePhysReg = getErrorAssignment(RC: *RC, CtxMI: MI);
130
131 // Keep going after reporting the error.
132 cleanupFailedVReg(FailedVReg: VirtReg->reg(), PhysReg: AvailablePhysReg, SplitRegs&: SplitVRegs);
133 } else if (AvailablePhysReg)
134 Matrix->assign(VirtReg: *VirtReg, PhysReg: AvailablePhysReg);
135
136 for (Register Reg : SplitVRegs) {
137 assert(LIS->hasInterval(Reg));
138
139 LiveInterval *SplitVirtReg = &LIS->getInterval(Reg);
140 assert(!VRM->hasPhys(SplitVirtReg->reg()) && "Register already assigned");
141 if (MRI->reg_nodbg_empty(RegNo: SplitVirtReg->reg())) {
142 assert(SplitVirtReg->empty() && "Non-empty but used interval");
143 LLVM_DEBUG(dbgs() << "not queueing unused " << *SplitVirtReg << '\n');
144 aboutToRemoveInterval(LI: *SplitVirtReg);
145 LIS->removeInterval(Reg: SplitVirtReg->reg());
146 continue;
147 }
148 LLVM_DEBUG(dbgs() << "queuing new interval: " << *SplitVirtReg << "\n");
149 assert(SplitVirtReg->reg().isVirtual() &&
150 "expect split value in virtual register");
151 enqueue(LI: SplitVirtReg);
152 ++NumNewQueued;
153 }
154 }
155}
156
157void RegAllocBase::postOptimization() {
158 spiller().postOptimization();
159
160 // Verify LiveRegMatrix after spilling (no dangling pointers).
161 assert(Matrix->isValid() && "LiveRegMatrix validation failed");
162
163 for (auto *DeadInst : DeadRemats) {
164 LIS->RemoveMachineInstrFromMaps(MI&: *DeadInst);
165 DeadInst->eraseFromParent();
166 }
167 DeadRemats.clear();
168}
169
170void RegAllocBase::cleanupFailedVReg(Register FailedReg, MCRegister PhysReg,
171 SmallVectorImpl<Register> &SplitRegs) {
172 // We still should produce valid IR. Kill all the uses and reduce the live
173 // ranges so that we don't think it's possible to introduce kill flags later
174 // which will fail the verifier.
175 for (MachineOperand &MO : MRI->reg_operands(Reg: FailedReg)) {
176 if (MO.readsReg())
177 MO.setIsUndef(true);
178 }
179
180 if (!MRI->isReserved(PhysReg)) {
181 // Physical liveness for any aliasing registers is now unreliable, so delete
182 // the uses.
183 for (MCRegAliasIterator Aliases(PhysReg, TRI, true); Aliases.isValid();
184 ++Aliases) {
185 for (MachineOperand &MO : MRI->reg_operands(Reg: *Aliases)) {
186 if (MO.readsReg())
187 MO.setIsUndef(true);
188 }
189 }
190 }
191
192 // Directly perform the rewrite, and do not leave it to VirtRegRewriter as
193 // usual. This avoids trying to manage illegal overlapping assignments in
194 // LiveRegMatrix.
195 MRI->replaceRegWith(FromReg: FailedReg, ToReg: PhysReg);
196 LIS->removeInterval(Reg: FailedReg);
197}
198
199void RegAllocBase::enqueue(const LiveInterval *LI) {
200 const Register Reg = LI->reg();
201
202 assert(Reg.isVirtual() && "Can only enqueue virtual registers");
203
204 if (VRM->hasPhys(virtReg: Reg))
205 return;
206
207 if (shouldAllocateRegister(Reg)) {
208 LLVM_DEBUG(dbgs() << "Enqueuing " << printReg(Reg, TRI) << '\n');
209 enqueueImpl(LI);
210 } else {
211 LLVM_DEBUG(dbgs() << "Not enqueueing " << printReg(Reg, TRI)
212 << " in skipped register class\n");
213 }
214}
215
216MCPhysReg RegAllocBase::getErrorAssignment(const TargetRegisterClass &RC,
217 const MachineInstr *CtxMI) {
218 MachineFunction &MF = VRM->getMachineFunction();
219
220 // Avoid printing the error for every single instance of the register. It
221 // would be better if this were per register class.
222 bool EmitError = !MF.getProperties().hasFailedRegAlloc();
223 if (EmitError)
224 MF.getProperties().setFailedRegAlloc();
225
226 const Function &Fn = MF.getFunction();
227 LLVMContext &Context = Fn.getContext();
228
229 ArrayRef<MCPhysReg> AllocOrder = RegClassInfo.getOrder(RC: &RC);
230 if (AllocOrder.empty()) {
231 // If the allocation order is empty, it likely means all registers in the
232 // class are reserved. We still to need to pick something, so look at the
233 // underlying class.
234 ArrayRef<MCPhysReg> RawRegs = RC.getRegisters();
235
236 if (EmitError) {
237 Context.diagnose(DI: DiagnosticInfoRegAllocFailure(
238 "no registers from class available to allocate", Fn,
239 CtxMI ? CtxMI->getDebugLoc() : DiagnosticLocation()));
240 }
241
242 assert(!RawRegs.empty() && "register classes cannot have no registers");
243 return RawRegs.front();
244 }
245
246 if (EmitError) {
247 if (CtxMI && CtxMI->isInlineAsm()) {
248 CtxMI->emitInlineAsmError(
249 ErrMsg: "inline assembly requires more registers than available");
250 } else {
251 Context.diagnose(DI: DiagnosticInfoRegAllocFailure(
252 "ran out of registers during register allocation", Fn,
253 CtxMI ? CtxMI->getDebugLoc() : DiagnosticLocation()));
254 }
255 }
256
257 return AllocOrder.front();
258}
259