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/TargetMachine.h"
28 #include "llvm/Target/TargetRegisterInfo.h"
29 #include "llvm/Target/TargetSubtargetInfo.h"
32 #define DEBUG_TYPE "reg-scavenging"
34 /// setUsed - Set the register and its sub-registers as being used.
35 void RegScavenger::setUsed(unsigned Reg) {
36 for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
37 SubRegs.isValid(); ++SubRegs)
38 RegsAvailable.reset(*SubRegs);
41 bool RegScavenger::isAliasUsed(unsigned Reg) const {
42 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
43 if (isUsed(*AI, *AI == Reg))
48 void RegScavenger::initRegState() {
49 for (SmallVectorImpl<ScavengedInfo>::iterator I = Scavenged.begin(),
50 IE = Scavenged.end(); I != IE; ++I) {
55 // All registers started out unused.
61 // Live-in registers are in use.
62 for (MachineBasicBlock::livein_iterator I = MBB->livein_begin(),
63 E = MBB->livein_end(); I != E; ++I)
66 // Pristine CSRs are also unavailable.
67 BitVector PR = MBB->getParent()->getFrameInfo()->getPristineRegs(MBB);
68 for (int I = PR.find_first(); I>0; I = PR.find_next(I))
72 void RegScavenger::enterBasicBlock(MachineBasicBlock *mbb) {
73 MachineFunction &MF = *mbb->getParent();
74 const TargetMachine &TM = MF.getTarget();
75 TII = TM.getSubtargetImpl()->getInstrInfo();
76 TRI = TM.getSubtargetImpl()->getRegisterInfo();
77 MRI = &MF.getRegInfo();
79 assert((NumPhysRegs == 0 || NumPhysRegs == TRI->getNumRegs()) &&
82 // It is not possible to use the register scavenger after late optimization
83 // passes that don't preserve accurate liveness information.
84 assert(MRI->tracksLiveness() &&
85 "Cannot use register scavenger with inaccurate liveness");
89 NumPhysRegs = TRI->getNumRegs();
90 RegsAvailable.resize(NumPhysRegs);
91 KillRegs.resize(NumPhysRegs);
92 DefRegs.resize(NumPhysRegs);
94 // Create callee-saved registers bitvector.
95 CalleeSavedRegs.resize(NumPhysRegs);
96 const MCPhysReg *CSRegs = TRI->getCalleeSavedRegs(&MF);
97 if (CSRegs != nullptr)
98 for (unsigned i = 0; CSRegs[i]; ++i)
99 CalleeSavedRegs.set(CSRegs[i]);
108 void RegScavenger::addRegWithSubRegs(BitVector &BV, unsigned Reg) {
109 for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
110 SubRegs.isValid(); ++SubRegs)
114 void RegScavenger::determineKillsAndDefs() {
115 assert(Tracking && "Must be tracking to determine kills and defs");
117 MachineInstr *MI = MBBI;
118 assert(!MI->isDebugValue() && "Debug values have no kills or defs");
120 // Find out which registers are early clobbered, killed, defined, and marked
121 // def-dead in this instruction.
122 // FIXME: The scavenger is not predication aware. If the instruction is
123 // predicated, conservatively assume "kill" markers do not actually kill the
124 // register. Similarly ignores "dead" markers.
125 bool isPred = TII->isPredicated(MI);
128 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
129 const MachineOperand &MO = MI->getOperand(i);
131 (isPred ? DefRegs : KillRegs).setBitsNotInMask(MO.getRegMask());
134 unsigned Reg = MO.getReg();
135 if (!Reg || TargetRegisterInfo::isVirtualRegister(Reg) || isReserved(Reg))
139 // Ignore undef uses.
142 if (!isPred && MO.isKill())
143 addRegWithSubRegs(KillRegs, Reg);
146 if (!isPred && MO.isDead())
147 addRegWithSubRegs(KillRegs, Reg);
149 addRegWithSubRegs(DefRegs, Reg);
154 void RegScavenger::unprocess() {
155 assert(Tracking && "Cannot unprocess because we're not tracking");
157 MachineInstr *MI = MBBI;
158 if (!MI->isDebugValue()) {
159 determineKillsAndDefs();
161 // Commit the changes.
166 if (MBBI == MBB->begin()) {
167 MBBI = MachineBasicBlock::iterator(nullptr);
173 void RegScavenger::forward() {
179 assert(MBBI != MBB->end() && "Already past the end of the basic block!");
180 MBBI = std::next(MBBI);
182 assert(MBBI != MBB->end() && "Already at the end of the basic block!");
184 MachineInstr *MI = MBBI;
186 for (SmallVectorImpl<ScavengedInfo>::iterator I = Scavenged.begin(),
187 IE = Scavenged.end(); I != IE; ++I) {
188 if (I->Restore != MI)
192 I->Restore = nullptr;
195 if (MI->isDebugValue())
198 determineKillsAndDefs();
200 // Verify uses and defs.
202 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
203 const MachineOperand &MO = MI->getOperand(i);
206 unsigned Reg = MO.getReg();
207 if (!Reg || TargetRegisterInfo::isVirtualRegister(Reg) || isReserved(Reg))
213 // Check if it's partial live: e.g.
214 // D0 = insert_subreg D0<undef>, S0
216 // The problem is the insert_subreg could be eliminated. The use of
217 // D0 is using a partially undef value. This is not *incorrect* since
218 // S1 is can be freely clobbered.
219 // Ideally we would like a way to model this, but leaving the
220 // insert_subreg around causes both correctness and performance issues.
221 bool SubUsed = false;
222 for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs)
223 if (isUsed(*SubRegs)) {
228 MBB->getParent()->verify(nullptr, "In Register Scavenger");
229 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.
251 void RegScavenger::getRegsUsed(BitVector &used, bool includeReserved) {
252 used = RegsAvailable;
255 used |= MRI->getReservedRegs();
257 used.reset(MRI->getReservedRegs());
260 unsigned RegScavenger::FindUnusedReg(const TargetRegisterClass *RC) const {
261 for (TargetRegisterClass::iterator I = RC->begin(), E = RC->end();
263 if (!isAliasUsed(*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();
277 if (!isAliasUsed(*I))
282 /// findSurvivorReg - Return the candidate register that is unused for the
283 /// longest after StargMII. 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
379 // have to spill. Search explicitly rather than masking out based on
380 // RegsAvailable, as RegsAvailable does not take aliases into account.
381 // That's what getRegsAvailable() is for.
382 BitVector Available = getRegsAvailable(RC);
383 Available &= Candidates;
385 Candidates = Available;
387 // Find the register whose use is furthest away.
388 MachineBasicBlock::iterator UseMI;
389 unsigned SReg = findSurvivorReg(I, Candidates, 25, UseMI);
391 // If we found an unused register there is no reason to spill it.
392 if (!isAliasUsed(SReg)) {
393 DEBUG(dbgs() << "Scavenged register: " << TRI->getName(SReg) << "\n");
397 // Find an available scavenging slot.
399 for (SI = 0; SI < Scavenged.size(); ++SI)
400 if (Scavenged[SI].Reg == 0)
403 if (SI == Scavenged.size()) {
404 // We need to scavenge a register but have no spill slot, the target
405 // must know how to do it (if not, we'll assert below).
406 Scavenged.push_back(ScavengedInfo());
409 // Avoid infinite regress
410 Scavenged[SI].Reg = SReg;
412 // If the target knows how to save/restore the register, let it do so;
413 // otherwise, use the emergency stack spill slot.
414 if (!TRI->saveScavengerRegister(*MBB, I, UseMI, RC, SReg)) {
415 // Spill the scavenged register before I.
416 assert(Scavenged[SI].FrameIndex >= 0 &&
417 "Cannot scavenge register without an emergency spill slot!");
418 TII->storeRegToStackSlot(*MBB, I, SReg, true, Scavenged[SI].FrameIndex,
420 MachineBasicBlock::iterator II = std::prev(I);
422 unsigned FIOperandNum = getFrameIndexOperandNum(II);
423 TRI->eliminateFrameIndex(II, SPAdj, FIOperandNum, this);
425 // Restore the scavenged register before its use (or first terminator).
426 TII->loadRegFromStackSlot(*MBB, UseMI, SReg, Scavenged[SI].FrameIndex,
428 II = std::prev(UseMI);
430 FIOperandNum = getFrameIndexOperandNum(II);
431 TRI->eliminateFrameIndex(II, SPAdj, FIOperandNum, this);
434 Scavenged[SI].Restore = std::prev(UseMI);
436 // Doing this here leads to infinite regress.
437 // Scavenged[SI].Reg = SReg;
439 DEBUG(dbgs() << "Scavenged register (with spill): " << TRI->getName(SReg) <<