1 //===-- RegisterScavenging.cpp - Machine register scavenging --------------===//
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 machine register scavenger. It can provide
11 // information, such as unused registers, at any point in a machine basic block.
12 // It also provides a mechanism to make registers available by evicting them to
15 //===----------------------------------------------------------------------===//
17 #include "llvm/CodeGen/RegisterScavenging.h"
18 #include "llvm/CodeGen/MachineBasicBlock.h"
19 #include "llvm/CodeGen/MachineFrameInfo.h"
20 #include "llvm/CodeGen/MachineFunction.h"
21 #include "llvm/CodeGen/MachineInstr.h"
22 #include "llvm/CodeGen/MachineRegisterInfo.h"
23 #include "llvm/Support/Debug.h"
24 #include "llvm/Support/ErrorHandling.h"
25 #include "llvm/Support/raw_ostream.h"
26 #include "llvm/Target/TargetInstrInfo.h"
27 #include "llvm/Target/TargetRegisterInfo.h"
28 #include "llvm/Target/TargetSubtargetInfo.h"
31 #define DEBUG_TYPE "reg-scavenging"
33 /// setUsed - Set the register units of this register as used.
34 void RegScavenger::setRegUsed(unsigned Reg) {
35 for (MCRegUnitIterator RUI(Reg, TRI); RUI.isValid(); ++RUI)
36 RegUnitsAvailable.reset(*RUI);
39 void RegScavenger::initRegState() {
40 for (SmallVectorImpl<ScavengedInfo>::iterator I = Scavenged.begin(),
41 IE = Scavenged.end(); I != IE; ++I) {
46 // All register units start out unused.
47 RegUnitsAvailable.set();
52 // Live-in registers are in use.
53 for (unsigned LI : MBB->liveins())
56 // Pristine CSRs are also unavailable.
57 const MachineFunction &MF = *MBB->getParent();
58 BitVector PR = MF.getFrameInfo()->getPristineRegs(MF);
59 for (int I = PR.find_first(); I>0; I = PR.find_next(I))
63 void RegScavenger::enterBasicBlock(MachineBasicBlock *mbb) {
64 MachineFunction &MF = *mbb->getParent();
65 TII = MF.getSubtarget().getInstrInfo();
66 TRI = MF.getSubtarget().getRegisterInfo();
67 MRI = &MF.getRegInfo();
69 assert((NumRegUnits == 0 || NumRegUnits == TRI->getNumRegUnits()) &&
72 // It is not possible to use the register scavenger after late optimization
73 // passes that don't preserve accurate liveness information.
74 assert(MRI->tracksLiveness() &&
75 "Cannot use register scavenger with inaccurate liveness");
79 NumRegUnits = TRI->getNumRegUnits();
80 RegUnitsAvailable.resize(NumRegUnits);
81 KillRegUnits.resize(NumRegUnits);
82 DefRegUnits.resize(NumRegUnits);
83 TmpRegUnits.resize(NumRegUnits);
92 void RegScavenger::addRegUnits(BitVector &BV, unsigned Reg) {
93 for (MCRegUnitIterator RUI(Reg, TRI); RUI.isValid(); ++RUI)
97 void RegScavenger::determineKillsAndDefs() {
98 assert(Tracking && "Must be tracking to determine kills and defs");
100 MachineInstr *MI = MBBI;
101 assert(!MI->isDebugValue() && "Debug values have no kills or defs");
103 // Find out which registers are early clobbered, killed, defined, and marked
104 // def-dead in this instruction.
105 KillRegUnits.reset();
107 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
108 const MachineOperand &MO = MI->getOperand(i);
109 if (MO.isRegMask()) {
112 for (unsigned RU = 0, RUEnd = TRI->getNumRegUnits(); RU != RUEnd; ++RU) {
113 for (MCRegUnitRootIterator RURI(RU, TRI); RURI.isValid(); ++RURI) {
114 if (MO.clobbersPhysReg(*RURI)) {
122 KillRegUnits |= TmpRegUnits;
126 unsigned Reg = MO.getReg();
127 if (!Reg || TargetRegisterInfo::isVirtualRegister(Reg) || isReserved(Reg))
131 // Ignore undef uses.
135 addRegUnits(KillRegUnits, Reg);
139 addRegUnits(KillRegUnits, Reg);
141 addRegUnits(DefRegUnits, Reg);
146 void RegScavenger::unprocess() {
147 assert(Tracking && "Cannot unprocess because we're not tracking");
149 MachineInstr *MI = MBBI;
150 if (!MI->isDebugValue()) {
151 determineKillsAndDefs();
153 // Commit the changes.
154 setUsed(KillRegUnits);
155 setUnused(DefRegUnits);
158 if (MBBI == MBB->begin()) {
159 MBBI = MachineBasicBlock::iterator(nullptr);
165 void RegScavenger::forward() {
171 assert(MBBI != MBB->end() && "Already past the end of the basic block!");
172 MBBI = std::next(MBBI);
174 assert(MBBI != MBB->end() && "Already at the end of the basic block!");
176 MachineInstr *MI = MBBI;
178 for (SmallVectorImpl<ScavengedInfo>::iterator I = Scavenged.begin(),
179 IE = Scavenged.end(); I != IE; ++I) {
180 if (I->Restore != MI)
184 I->Restore = nullptr;
187 if (MI->isDebugValue())
190 determineKillsAndDefs();
192 // Verify uses and defs.
194 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
195 const MachineOperand &MO = MI->getOperand(i);
198 unsigned Reg = MO.getReg();
199 if (!Reg || TargetRegisterInfo::isVirtualRegister(Reg) || isReserved(Reg))
204 if (!isRegUsed(Reg)) {
205 // Check if it's partial live: e.g.
206 // D0 = insert_subreg D0<undef>, S0
208 // The problem is the insert_subreg could be eliminated. The use of
209 // D0 is using a partially undef value. This is not *incorrect* since
210 // S1 is can be freely clobbered.
211 // Ideally we would like a way to model this, but leaving the
212 // insert_subreg around causes both correctness and performance issues.
213 bool SubUsed = false;
214 for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs)
215 if (isRegUsed(*SubRegs)) {
219 bool SuperUsed = false;
220 for (MCSuperRegIterator SR(Reg, TRI); SR.isValid(); ++SR) {
221 if (isRegUsed(*SR)) {
226 if (!SubUsed && !SuperUsed) {
227 MBB->getParent()->verify(nullptr, "In Register Scavenger");
228 llvm_unreachable("Using an undefined register!");
236 // FIXME: Enable this once we've figured out how to correctly transfer
237 // implicit kills during codegen passes like the coalescer.
238 assert((KillRegs.test(Reg) || isUnused(Reg) ||
239 isLiveInButUnusedBefore(Reg, MI, MBB, TRI, MRI)) &&
240 "Re-defining a live register!");
246 // Commit the changes.
247 setUnused(KillRegUnits);
248 setUsed(DefRegUnits);
251 bool RegScavenger::isRegUsed(unsigned Reg, bool includeReserved) const {
252 if (includeReserved && isReserved(Reg))
254 for (MCRegUnitIterator RUI(Reg, TRI); RUI.isValid(); ++RUI)
255 if (!RegUnitsAvailable.test(*RUI))
260 unsigned RegScavenger::FindUnusedReg(const TargetRegisterClass *RC) const {
261 for (TargetRegisterClass::iterator I = RC->begin(), E = RC->end();
263 if (!isRegUsed(*I)) {
264 DEBUG(dbgs() << "Scavenger found unused reg: " << TRI->getName(*I) <<
271 /// getRegsAvailable - Return all available registers in the register class
273 BitVector RegScavenger::getRegsAvailable(const TargetRegisterClass *RC) {
274 BitVector Mask(TRI->getNumRegs());
275 for (TargetRegisterClass::iterator I = RC->begin(), E = RC->end();
282 /// findSurvivorReg - Return the candidate register that is unused for the
283 /// longest after StartMII. UseMI is set to the instruction where the search
286 /// No more than InstrLimit instructions are inspected.
288 unsigned RegScavenger::findSurvivorReg(MachineBasicBlock::iterator StartMI,
289 BitVector &Candidates,
291 MachineBasicBlock::iterator &UseMI) {
292 int Survivor = Candidates.find_first();
293 assert(Survivor > 0 && "No candidates for scavenging");
295 MachineBasicBlock::iterator ME = MBB->getFirstTerminator();
296 assert(StartMI != ME && "MI already at terminator");
297 MachineBasicBlock::iterator RestorePointMI = StartMI;
298 MachineBasicBlock::iterator MI = StartMI;
300 bool inVirtLiveRange = false;
301 for (++MI; InstrLimit > 0 && MI != ME; ++MI, --InstrLimit) {
302 if (MI->isDebugValue()) {
303 ++InstrLimit; // Don't count debug instructions
306 bool isVirtKillInsn = false;
307 bool isVirtDefInsn = false;
308 // Remove any candidates touched by instruction.
309 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
310 const MachineOperand &MO = MI->getOperand(i);
312 Candidates.clearBitsNotInMask(MO.getRegMask());
313 if (!MO.isReg() || MO.isUndef() || !MO.getReg())
315 if (TargetRegisterInfo::isVirtualRegister(MO.getReg())) {
317 isVirtDefInsn = true;
318 else if (MO.isKill())
319 isVirtKillInsn = true;
322 for (MCRegAliasIterator AI(MO.getReg(), TRI, true); AI.isValid(); ++AI)
323 Candidates.reset(*AI);
325 // If we're not in a virtual reg's live range, this is a valid
327 if (!inVirtLiveRange) RestorePointMI = MI;
329 // Update whether we're in the live range of a virtual register
330 if (isVirtKillInsn) inVirtLiveRange = false;
331 if (isVirtDefInsn) inVirtLiveRange = true;
333 // Was our survivor untouched by this instruction?
334 if (Candidates.test(Survivor))
337 // All candidates gone?
338 if (Candidates.none())
341 Survivor = Candidates.find_first();
343 // If we ran off the end, that's where we want to restore.
344 if (MI == ME) RestorePointMI = ME;
345 assert (RestorePointMI != StartMI &&
346 "No available scavenger restore location!");
348 // We ran out of candidates, so stop the search.
349 UseMI = RestorePointMI;
353 static unsigned getFrameIndexOperandNum(MachineInstr *MI) {
355 while (!MI->getOperand(i).isFI()) {
357 assert(i < MI->getNumOperands() &&
358 "Instr doesn't have FrameIndex operand!");
363 unsigned RegScavenger::scavengeRegister(const TargetRegisterClass *RC,
364 MachineBasicBlock::iterator I,
366 // Consider all allocatable registers in the register class initially
367 BitVector Candidates =
368 TRI->getAllocatableSet(*I->getParent()->getParent(), RC);
370 // Exclude all the registers being used by the instruction.
371 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
372 MachineOperand &MO = I->getOperand(i);
373 if (MO.isReg() && MO.getReg() != 0 && !(MO.isUse() && MO.isUndef()) &&
374 !TargetRegisterInfo::isVirtualRegister(MO.getReg()))
375 Candidates.reset(MO.getReg());
378 // Try to find a register that's unused if there is one, as then we won't
380 BitVector Available = getRegsAvailable(RC);
381 Available &= Candidates;
383 Candidates = Available;
385 // Find the register whose use is furthest away.
386 MachineBasicBlock::iterator UseMI;
387 unsigned SReg = findSurvivorReg(I, Candidates, 25, UseMI);
389 // If we found an unused register there is no reason to spill it.
390 if (!isRegUsed(SReg)) {
391 DEBUG(dbgs() << "Scavenged register: " << TRI->getName(SReg) << "\n");
395 // Find an available scavenging slot.
397 for (SI = 0; SI < Scavenged.size(); ++SI)
398 if (Scavenged[SI].Reg == 0)
401 if (SI == Scavenged.size()) {
402 // We need to scavenge a register but have no spill slot, the target
403 // must know how to do it (if not, we'll assert below).
404 Scavenged.push_back(ScavengedInfo());
407 // Avoid infinite regress
408 Scavenged[SI].Reg = SReg;
410 // If the target knows how to save/restore the register, let it do so;
411 // otherwise, use the emergency stack spill slot.
412 if (!TRI->saveScavengerRegister(*MBB, I, UseMI, RC, SReg)) {
413 // Spill the scavenged register before I.
414 assert(Scavenged[SI].FrameIndex >= 0 &&
415 "Cannot scavenge register without an emergency spill slot!");
416 TII->storeRegToStackSlot(*MBB, I, SReg, true, Scavenged[SI].FrameIndex,
418 MachineBasicBlock::iterator II = std::prev(I);
420 unsigned FIOperandNum = getFrameIndexOperandNum(II);
421 TRI->eliminateFrameIndex(II, SPAdj, FIOperandNum, this);
423 // Restore the scavenged register before its use (or first terminator).
424 TII->loadRegFromStackSlot(*MBB, UseMI, SReg, Scavenged[SI].FrameIndex,
426 II = std::prev(UseMI);
428 FIOperandNum = getFrameIndexOperandNum(II);
429 TRI->eliminateFrameIndex(II, SPAdj, FIOperandNum, this);
432 Scavenged[SI].Restore = std::prev(UseMI);
434 // Doing this here leads to infinite regress.
435 // Scavenged[SI].Reg = SReg;
437 DEBUG(dbgs() << "Scavenged register (with spill): " << TRI->getName(SReg) <<