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, LaneBitmask LaneMask) {
35 for (MCRegUnitMaskIterator RUI(Reg, TRI); RUI.isValid(); ++RUI) {
36 LaneBitmask UnitMask = (*RUI).second;
37 if (UnitMask == 0 || (LaneMask & UnitMask) != 0)
38 RegUnitsAvailable.reset((*RUI).first);
42 void RegScavenger::initRegState() {
43 for (SmallVectorImpl<ScavengedInfo>::iterator I = Scavenged.begin(),
44 IE = Scavenged.end(); I != IE; ++I) {
49 // All register units start out unused.
50 RegUnitsAvailable.set();
55 // Live-in registers are in use.
56 for (const auto &LI : MBB->liveins())
57 setRegUsed(LI.PhysReg, LI.LaneMask);
59 // Pristine CSRs are also unavailable.
60 const MachineFunction &MF = *MBB->getParent();
61 BitVector PR = MF.getFrameInfo()->getPristineRegs(MF);
62 for (int I = PR.find_first(); I>0; I = PR.find_next(I))
66 void RegScavenger::enterBasicBlock(MachineBasicBlock *mbb) {
67 MachineFunction &MF = *mbb->getParent();
68 TII = MF.getSubtarget().getInstrInfo();
69 TRI = MF.getSubtarget().getRegisterInfo();
70 MRI = &MF.getRegInfo();
72 assert((NumRegUnits == 0 || NumRegUnits == TRI->getNumRegUnits()) &&
75 // It is not possible to use the register scavenger after late optimization
76 // passes that don't preserve accurate liveness information.
77 assert(MRI->tracksLiveness() &&
78 "Cannot use register scavenger with inaccurate liveness");
82 NumRegUnits = TRI->getNumRegUnits();
83 RegUnitsAvailable.resize(NumRegUnits);
84 KillRegUnits.resize(NumRegUnits);
85 DefRegUnits.resize(NumRegUnits);
86 TmpRegUnits.resize(NumRegUnits);
95 void RegScavenger::addRegUnits(BitVector &BV, unsigned Reg) {
96 for (MCRegUnitIterator RUI(Reg, TRI); RUI.isValid(); ++RUI)
100 void RegScavenger::determineKillsAndDefs() {
101 assert(Tracking && "Must be tracking to determine kills and defs");
103 MachineInstr *MI = MBBI;
104 assert(!MI->isDebugValue() && "Debug values have no kills or defs");
106 // Find out which registers are early clobbered, killed, defined, and marked
107 // def-dead in this instruction.
108 KillRegUnits.reset();
110 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
111 const MachineOperand &MO = MI->getOperand(i);
112 if (MO.isRegMask()) {
115 for (unsigned RU = 0, RUEnd = TRI->getNumRegUnits(); RU != RUEnd; ++RU) {
116 for (MCRegUnitRootIterator RURI(RU, TRI); RURI.isValid(); ++RURI) {
117 if (MO.clobbersPhysReg(*RURI)) {
125 KillRegUnits |= TmpRegUnits;
129 unsigned Reg = MO.getReg();
130 if (!Reg || TargetRegisterInfo::isVirtualRegister(Reg) || isReserved(Reg))
134 // Ignore undef uses.
138 addRegUnits(KillRegUnits, Reg);
142 addRegUnits(KillRegUnits, Reg);
144 addRegUnits(DefRegUnits, Reg);
149 void RegScavenger::unprocess() {
150 assert(Tracking && "Cannot unprocess because we're not tracking");
152 MachineInstr *MI = MBBI;
153 if (!MI->isDebugValue()) {
154 determineKillsAndDefs();
156 // Commit the changes.
157 setUsed(KillRegUnits);
158 setUnused(DefRegUnits);
161 if (MBBI == MBB->begin()) {
162 MBBI = MachineBasicBlock::iterator(nullptr);
168 void RegScavenger::forward() {
174 assert(MBBI != MBB->end() && "Already past the end of the basic block!");
175 MBBI = std::next(MBBI);
177 assert(MBBI != MBB->end() && "Already at the end of the basic block!");
179 MachineInstr *MI = MBBI;
181 for (SmallVectorImpl<ScavengedInfo>::iterator I = Scavenged.begin(),
182 IE = Scavenged.end(); I != IE; ++I) {
183 if (I->Restore != MI)
187 I->Restore = nullptr;
190 if (MI->isDebugValue())
193 determineKillsAndDefs();
195 // Verify uses and defs.
197 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
198 const MachineOperand &MO = MI->getOperand(i);
201 unsigned Reg = MO.getReg();
202 if (!Reg || TargetRegisterInfo::isVirtualRegister(Reg) || isReserved(Reg))
207 if (!isRegUsed(Reg)) {
208 // Check if it's partial live: e.g.
209 // D0 = insert_subreg D0<undef>, S0
211 // The problem is the insert_subreg could be eliminated. The use of
212 // D0 is using a partially undef value. This is not *incorrect* since
213 // S1 is can be freely clobbered.
214 // Ideally we would like a way to model this, but leaving the
215 // insert_subreg around causes both correctness and performance issues.
216 bool SubUsed = false;
217 for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs)
218 if (isRegUsed(*SubRegs)) {
222 bool SuperUsed = false;
223 for (MCSuperRegIterator SR(Reg, TRI); SR.isValid(); ++SR) {
224 if (isRegUsed(*SR)) {
229 if (!SubUsed && !SuperUsed) {
230 MBB->getParent()->verify(nullptr, "In Register Scavenger");
231 llvm_unreachable("Using an undefined register!");
239 // FIXME: Enable this once we've figured out how to correctly transfer
240 // implicit kills during codegen passes like the coalescer.
241 assert((KillRegs.test(Reg) || isUnused(Reg) ||
242 isLiveInButUnusedBefore(Reg, MI, MBB, TRI, MRI)) &&
243 "Re-defining a live register!");
249 // Commit the changes.
250 setUnused(KillRegUnits);
251 setUsed(DefRegUnits);
254 bool RegScavenger::isRegUsed(unsigned Reg, bool includeReserved) const {
255 if (includeReserved && isReserved(Reg))
257 for (MCRegUnitIterator RUI(Reg, TRI); RUI.isValid(); ++RUI)
258 if (!RegUnitsAvailable.test(*RUI))
263 unsigned RegScavenger::FindUnusedReg(const TargetRegisterClass *RC) const {
264 for (TargetRegisterClass::iterator I = RC->begin(), E = RC->end();
266 if (!isRegUsed(*I)) {
267 DEBUG(dbgs() << "Scavenger found unused reg: " << TRI->getName(*I) <<
274 /// getRegsAvailable - Return all available registers in the register class
276 BitVector RegScavenger::getRegsAvailable(const TargetRegisterClass *RC) {
277 BitVector Mask(TRI->getNumRegs());
278 for (TargetRegisterClass::iterator I = RC->begin(), E = RC->end();
285 /// findSurvivorReg - Return the candidate register that is unused for the
286 /// longest after StartMII. UseMI is set to the instruction where the search
289 /// No more than InstrLimit instructions are inspected.
291 unsigned RegScavenger::findSurvivorReg(MachineBasicBlock::iterator StartMI,
292 BitVector &Candidates,
294 MachineBasicBlock::iterator &UseMI) {
295 int Survivor = Candidates.find_first();
296 assert(Survivor > 0 && "No candidates for scavenging");
298 MachineBasicBlock::iterator ME = MBB->getFirstTerminator();
299 assert(StartMI != ME && "MI already at terminator");
300 MachineBasicBlock::iterator RestorePointMI = StartMI;
301 MachineBasicBlock::iterator MI = StartMI;
303 bool inVirtLiveRange = false;
304 for (++MI; InstrLimit > 0 && MI != ME; ++MI, --InstrLimit) {
305 if (MI->isDebugValue()) {
306 ++InstrLimit; // Don't count debug instructions
309 bool isVirtKillInsn = false;
310 bool isVirtDefInsn = false;
311 // Remove any candidates touched by instruction.
312 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
313 const MachineOperand &MO = MI->getOperand(i);
315 Candidates.clearBitsNotInMask(MO.getRegMask());
316 if (!MO.isReg() || MO.isUndef() || !MO.getReg())
318 if (TargetRegisterInfo::isVirtualRegister(MO.getReg())) {
320 isVirtDefInsn = true;
321 else if (MO.isKill())
322 isVirtKillInsn = true;
325 for (MCRegAliasIterator AI(MO.getReg(), TRI, true); AI.isValid(); ++AI)
326 Candidates.reset(*AI);
328 // If we're not in a virtual reg's live range, this is a valid
330 if (!inVirtLiveRange) RestorePointMI = MI;
332 // Update whether we're in the live range of a virtual register
333 if (isVirtKillInsn) inVirtLiveRange = false;
334 if (isVirtDefInsn) inVirtLiveRange = true;
336 // Was our survivor untouched by this instruction?
337 if (Candidates.test(Survivor))
340 // All candidates gone?
341 if (Candidates.none())
344 Survivor = Candidates.find_first();
346 // If we ran off the end, that's where we want to restore.
347 if (MI == ME) RestorePointMI = ME;
348 assert (RestorePointMI != StartMI &&
349 "No available scavenger restore location!");
351 // We ran out of candidates, so stop the search.
352 UseMI = RestorePointMI;
356 static unsigned getFrameIndexOperandNum(MachineInstr *MI) {
358 while (!MI->getOperand(i).isFI()) {
360 assert(i < MI->getNumOperands() &&
361 "Instr doesn't have FrameIndex operand!");
366 unsigned RegScavenger::scavengeRegister(const TargetRegisterClass *RC,
367 MachineBasicBlock::iterator I,
369 // Consider all allocatable registers in the register class initially
370 BitVector Candidates =
371 TRI->getAllocatableSet(*I->getParent()->getParent(), RC);
373 // Exclude all the registers being used by the instruction.
374 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
375 MachineOperand &MO = I->getOperand(i);
376 if (MO.isReg() && MO.getReg() != 0 && !(MO.isUse() && MO.isUndef()) &&
377 !TargetRegisterInfo::isVirtualRegister(MO.getReg()))
378 Candidates.reset(MO.getReg());
381 // Try to find a register that's unused if there is one, as then we won't
383 BitVector Available = getRegsAvailable(RC);
384 Available &= Candidates;
386 Candidates = Available;
388 // Find the register whose use is furthest away.
389 MachineBasicBlock::iterator UseMI;
390 unsigned SReg = findSurvivorReg(I, Candidates, 25, UseMI);
392 // If we found an unused register there is no reason to spill it.
393 if (!isRegUsed(SReg)) {
394 DEBUG(dbgs() << "Scavenged register: " << TRI->getName(SReg) << "\n");
398 // Find an available scavenging slot.
400 for (SI = 0; SI < Scavenged.size(); ++SI)
401 if (Scavenged[SI].Reg == 0)
404 if (SI == Scavenged.size()) {
405 // We need to scavenge a register but have no spill slot, the target
406 // must know how to do it (if not, we'll assert below).
407 Scavenged.push_back(ScavengedInfo());
410 // Avoid infinite regress
411 Scavenged[SI].Reg = SReg;
413 // If the target knows how to save/restore the register, let it do so;
414 // otherwise, use the emergency stack spill slot.
415 if (!TRI->saveScavengerRegister(*MBB, I, UseMI, RC, SReg)) {
416 // Spill the scavenged register before I.
417 assert(Scavenged[SI].FrameIndex >= 0 &&
418 "Cannot scavenge register without an emergency spill slot!");
419 TII->storeRegToStackSlot(*MBB, I, SReg, true, Scavenged[SI].FrameIndex,
421 MachineBasicBlock::iterator II = std::prev(I);
423 unsigned FIOperandNum = getFrameIndexOperandNum(II);
424 TRI->eliminateFrameIndex(II, SPAdj, FIOperandNum, this);
426 // Restore the scavenged register before its use (or first terminator).
427 TII->loadRegFromStackSlot(*MBB, UseMI, SReg, Scavenged[SI].FrameIndex,
429 II = std::prev(UseMI);
431 FIOperandNum = getFrameIndexOperandNum(II);
432 TRI->eliminateFrameIndex(II, SPAdj, FIOperandNum, this);
435 Scavenged[SI].Restore = std::prev(UseMI);
437 // Doing this here leads to infinite regress.
438 // Scavenged[SI].Reg = SReg;
440 DEBUG(dbgs() << "Scavenged register (with spill): " << TRI->getName(SReg) <<