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 #define DEBUG_TYPE "reg-scavenging"
18 #include "llvm/CodeGen/RegisterScavenging.h"
19 #include "llvm/CodeGen/MachineBasicBlock.h"
20 #include "llvm/CodeGen/MachineFrameInfo.h"
21 #include "llvm/CodeGen/MachineFunction.h"
22 #include "llvm/CodeGen/MachineInstr.h"
23 #include "llvm/CodeGen/MachineRegisterInfo.h"
24 #include "llvm/Support/Debug.h"
25 #include "llvm/Support/ErrorHandling.h"
26 #include "llvm/Support/raw_ostream.h"
27 #include "llvm/Target/TargetInstrInfo.h"
28 #include "llvm/Target/TargetMachine.h"
29 #include "llvm/Target/TargetRegisterInfo.h"
32 /// setUsed - Set the register and its sub-registers as being used.
33 void RegScavenger::setUsed(unsigned Reg) {
34 for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
35 SubRegs.isValid(); ++SubRegs)
36 RegsAvailable.reset(*SubRegs);
39 bool RegScavenger::isAliasUsed(unsigned Reg) const {
40 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
41 if (isUsed(*AI, *AI == Reg))
46 void RegScavenger::initRegState() {
47 for (SmallVectorImpl<ScavengedInfo>::iterator I = Scavenged.begin(),
48 IE = Scavenged.end(); I != IE; ++I) {
53 // All registers started out unused.
59 // Live-in registers are in use.
60 for (MachineBasicBlock::livein_iterator I = MBB->livein_begin(),
61 E = MBB->livein_end(); I != E; ++I)
64 // Pristine CSRs are also unavailable.
65 BitVector PR = MBB->getParent()->getFrameInfo()->getPristineRegs(MBB);
66 for (int I = PR.find_first(); I>0; I = PR.find_next(I))
70 void RegScavenger::enterBasicBlock(MachineBasicBlock *mbb) {
71 MachineFunction &MF = *mbb->getParent();
72 const TargetMachine &TM = MF.getTarget();
73 TII = TM.getInstrInfo();
74 TRI = TM.getRegisterInfo();
75 MRI = &MF.getRegInfo();
77 assert((NumPhysRegs == 0 || NumPhysRegs == TRI->getNumRegs()) &&
80 // It is not possible to use the register scavenger after late optimization
81 // passes that don't preserve accurate liveness information.
82 assert(MRI->tracksLiveness() &&
83 "Cannot use register scavenger with inaccurate liveness");
87 NumPhysRegs = TRI->getNumRegs();
88 RegsAvailable.resize(NumPhysRegs);
89 KillRegs.resize(NumPhysRegs);
90 DefRegs.resize(NumPhysRegs);
92 // Create callee-saved registers bitvector.
93 CalleeSavedRegs.resize(NumPhysRegs);
94 const uint16_t *CSRegs = TRI->getCalleeSavedRegs(&MF);
96 for (unsigned i = 0; CSRegs[i]; ++i)
97 CalleeSavedRegs.set(CSRegs[i]);
106 void RegScavenger::addRegWithSubRegs(BitVector &BV, unsigned Reg) {
107 for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
108 SubRegs.isValid(); ++SubRegs)
112 void RegScavenger::determineKillsAndDefs() {
113 assert(Tracking && "Must be tracking to determine kills and defs");
115 MachineInstr *MI = MBBI;
116 assert(!MI->isDebugValue() && "Debug values have no kills or defs");
118 // Find out which registers are early clobbered, killed, defined, and marked
119 // def-dead in this instruction.
120 // FIXME: The scavenger is not predication aware. If the instruction is
121 // predicated, conservatively assume "kill" markers do not actually kill the
122 // register. Similarly ignores "dead" markers.
123 bool isPred = TII->isPredicated(MI);
126 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
127 const MachineOperand &MO = MI->getOperand(i);
129 (isPred ? DefRegs : KillRegs).setBitsNotInMask(MO.getRegMask());
132 unsigned Reg = MO.getReg();
133 if (!Reg || TargetRegisterInfo::isVirtualRegister(Reg) || isReserved(Reg))
137 // Ignore undef uses.
140 if (!isPred && MO.isKill())
141 addRegWithSubRegs(KillRegs, Reg);
144 if (!isPred && MO.isDead())
145 addRegWithSubRegs(KillRegs, Reg);
147 addRegWithSubRegs(DefRegs, Reg);
152 void RegScavenger::unprocess() {
153 assert(Tracking && "Cannot unprocess because we're not tracking");
155 MachineInstr *MI = MBBI;
156 if (!MI->isDebugValue()) {
157 determineKillsAndDefs();
159 // Commit the changes.
164 if (MBBI == MBB->begin()) {
165 MBBI = MachineBasicBlock::iterator(NULL);
171 void RegScavenger::forward() {
177 assert(MBBI != MBB->end() && "Already past the end of the basic block!");
178 MBBI = llvm::next(MBBI);
180 assert(MBBI != MBB->end() && "Already at the end of the basic block!");
182 MachineInstr *MI = MBBI;
184 for (SmallVectorImpl<ScavengedInfo>::iterator I = Scavenged.begin(),
185 IE = Scavenged.end(); I != IE; ++I) {
186 if (I->Restore != MI)
193 if (MI->isDebugValue())
196 determineKillsAndDefs();
198 // Verify uses and defs.
200 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
201 const MachineOperand &MO = MI->getOperand(i);
204 unsigned Reg = MO.getReg();
205 if (!Reg || TargetRegisterInfo::isVirtualRegister(Reg) || isReserved(Reg))
211 // Check if it's partial live: e.g.
212 // D0 = insert_subreg D0<undef>, S0
214 // The problem is the insert_subreg could be eliminated. The use of
215 // D0 is using a partially undef value. This is not *incorrect* since
216 // S1 is can be freely clobbered.
217 // Ideally we would like a way to model this, but leaving the
218 // insert_subreg around causes both correctness and performance issues.
219 bool SubUsed = false;
220 for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs)
221 if (isUsed(*SubRegs)) {
226 MBB->getParent()->verify(NULL, "In Register Scavenger");
227 llvm_unreachable("Using an undefined register!");
234 // FIXME: Enable this once we've figured out how to correctly transfer
235 // implicit kills during codegen passes like the coalescer.
236 assert((KillRegs.test(Reg) || isUnused(Reg) ||
237 isLiveInButUnusedBefore(Reg, MI, MBB, TRI, MRI)) &&
238 "Re-defining a live register!");
244 // Commit the changes.
249 void RegScavenger::getRegsUsed(BitVector &used, bool includeReserved) {
250 used = RegsAvailable;
253 used |= MRI->getReservedRegs();
255 used.reset(MRI->getReservedRegs());
258 unsigned RegScavenger::FindUnusedReg(const TargetRegisterClass *RC) const {
259 for (TargetRegisterClass::iterator I = RC->begin(), E = RC->end();
261 if (!isAliasUsed(*I)) {
262 DEBUG(dbgs() << "Scavenger found unused reg: " << TRI->getName(*I) <<
269 /// getRegsAvailable - Return all available registers in the register class
271 BitVector RegScavenger::getRegsAvailable(const TargetRegisterClass *RC) {
272 BitVector Mask(TRI->getNumRegs());
273 for (TargetRegisterClass::iterator I = RC->begin(), E = RC->end();
275 if (!isAliasUsed(*I))
280 /// findSurvivorReg - Return the candidate register that is unused for the
281 /// longest after StargMII. UseMI is set to the instruction where the search
284 /// No more than InstrLimit instructions are inspected.
286 unsigned RegScavenger::findSurvivorReg(MachineBasicBlock::iterator StartMI,
287 BitVector &Candidates,
289 MachineBasicBlock::iterator &UseMI) {
290 int Survivor = Candidates.find_first();
291 assert(Survivor > 0 && "No candidates for scavenging");
293 MachineBasicBlock::iterator ME = MBB->getFirstTerminator();
294 assert(StartMI != ME && "MI already at terminator");
295 MachineBasicBlock::iterator RestorePointMI = StartMI;
296 MachineBasicBlock::iterator MI = StartMI;
298 bool inVirtLiveRange = false;
299 for (++MI; InstrLimit > 0 && MI != ME; ++MI, --InstrLimit) {
300 if (MI->isDebugValue()) {
301 ++InstrLimit; // Don't count debug instructions
304 bool isVirtKillInsn = false;
305 bool isVirtDefInsn = false;
306 // Remove any candidates touched by instruction.
307 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
308 const MachineOperand &MO = MI->getOperand(i);
310 Candidates.clearBitsNotInMask(MO.getRegMask());
311 if (!MO.isReg() || MO.isUndef() || !MO.getReg())
313 if (TargetRegisterInfo::isVirtualRegister(MO.getReg())) {
315 isVirtDefInsn = true;
316 else if (MO.isKill())
317 isVirtKillInsn = true;
320 for (MCRegAliasIterator AI(MO.getReg(), TRI, true); AI.isValid(); ++AI)
321 Candidates.reset(*AI);
323 // If we're not in a virtual reg's live range, this is a valid
325 if (!inVirtLiveRange) RestorePointMI = MI;
327 // Update whether we're in the live range of a virtual register
328 if (isVirtKillInsn) inVirtLiveRange = false;
329 if (isVirtDefInsn) inVirtLiveRange = true;
331 // Was our survivor untouched by this instruction?
332 if (Candidates.test(Survivor))
335 // All candidates gone?
336 if (Candidates.none())
339 Survivor = Candidates.find_first();
341 // If we ran off the end, that's where we want to restore.
342 if (MI == ME) RestorePointMI = ME;
343 assert (RestorePointMI != StartMI &&
344 "No available scavenger restore location!");
346 // We ran out of candidates, so stop the search.
347 UseMI = RestorePointMI;
351 static unsigned getFrameIndexOperandNum(MachineInstr *MI) {
353 while (!MI->getOperand(i).isFI()) {
355 assert(i < MI->getNumOperands() &&
356 "Instr doesn't have FrameIndex operand!");
361 unsigned RegScavenger::scavengeRegister(const TargetRegisterClass *RC,
362 MachineBasicBlock::iterator I,
364 // Consider all allocatable registers in the register class initially
365 BitVector Candidates =
366 TRI->getAllocatableSet(*I->getParent()->getParent(), RC);
368 // Exclude all the registers being used by the instruction.
369 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
370 MachineOperand &MO = I->getOperand(i);
371 if (MO.isReg() && MO.getReg() != 0 && !(MO.isUse() && MO.isUndef()) &&
372 !TargetRegisterInfo::isVirtualRegister(MO.getReg()))
373 Candidates.reset(MO.getReg());
376 // Try to find a register that's unused if there is one, as then we won't
377 // have to spill. Search explicitly rather than masking out based on
378 // RegsAvailable, as RegsAvailable does not take aliases into account.
379 // That's what getRegsAvailable() is for.
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 (!isAliasUsed(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 = prior(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,
428 FIOperandNum = getFrameIndexOperandNum(II);
429 TRI->eliminateFrameIndex(II, SPAdj, FIOperandNum, this);
432 Scavenged[SI].Restore = prior(UseMI);
434 // Doing this here leads to infinite regress.
435 // Scavenged[SI].Reg = SReg;
437 DEBUG(dbgs() << "Scavenged register (with spill): " << TRI->getName(SReg) <<