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 //===----------------------------------------------------------------------===//
11 /// This file implements the machine register scavenger. It can provide
12 /// information, such as unused registers, at any point in a machine basic
13 /// block. It also provides a mechanism to make registers available by evicting
14 /// them to spill slots.
16 //===----------------------------------------------------------------------===//
18 #include "llvm/ADT/BitVector.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/CodeGen/RegisterScavenging.h"
21 #include "llvm/CodeGen/MachineBasicBlock.h"
22 #include "llvm/CodeGen/MachineFrameInfo.h"
23 #include "llvm/CodeGen/MachineFunction.h"
24 #include "llvm/CodeGen/MachineInstr.h"
25 #include "llvm/CodeGen/MachineOperand.h"
26 #include "llvm/MC/MCRegisterInfo.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/Support/ErrorHandling.h"
29 #include "llvm/Support/raw_ostream.h"
30 #include "llvm/Target/TargetInstrInfo.h"
31 #include "llvm/Target/TargetRegisterInfo.h"
32 #include "llvm/Target/TargetSubtargetInfo.h"
40 #define DEBUG_TYPE "reg-scavenging"
42 void RegScavenger::setRegUsed(unsigned Reg, LaneBitmask LaneMask) {
43 LiveUnits.addRegMasked(Reg, LaneMask);
46 void RegScavenger::init(MachineBasicBlock &MBB) {
47 MachineFunction &MF = *MBB.getParent();
48 TII = MF.getSubtarget().getInstrInfo();
49 TRI = MF.getSubtarget().getRegisterInfo();
50 MRI = &MF.getRegInfo();
53 assert((NumRegUnits == 0 || NumRegUnits == TRI->getNumRegUnits()) &&
58 NumRegUnits = TRI->getNumRegUnits();
59 KillRegUnits.resize(NumRegUnits);
60 DefRegUnits.resize(NumRegUnits);
61 TmpRegUnits.resize(NumRegUnits);
65 for (ScavengedInfo &SI : Scavenged) {
73 void RegScavenger::enterBasicBlock(MachineBasicBlock &MBB) {
75 LiveUnits.addLiveIns(MBB);
78 void RegScavenger::enterBasicBlockEnd(MachineBasicBlock &MBB) {
80 LiveUnits.addLiveOuts(MBB);
82 // Move internal iterator at the last instruction of the block.
83 if (MBB.begin() != MBB.end()) {
84 MBBI = std::prev(MBB.end());
89 void RegScavenger::addRegUnits(BitVector &BV, unsigned Reg) {
90 for (MCRegUnitIterator RUI(Reg, TRI); RUI.isValid(); ++RUI)
94 void RegScavenger::removeRegUnits(BitVector &BV, unsigned Reg) {
95 for (MCRegUnitIterator RUI(Reg, TRI); RUI.isValid(); ++RUI)
99 void RegScavenger::determineKillsAndDefs() {
100 assert(Tracking && "Must be tracking to determine kills and defs");
102 MachineInstr &MI = *MBBI;
103 assert(!MI.isDebugValue() && "Debug values have no kills or defs");
105 // Find out which registers are early clobbered, killed, defined, and marked
106 // def-dead in this instruction.
107 KillRegUnits.reset();
109 for (const MachineOperand &MO : MI.operands()) {
110 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 (!TargetRegisterInfo::isPhysicalRegister(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 (const MachineOperand &MO : MI.operands()) {
197 unsigned Reg = MO.getReg();
198 if (!TargetRegisterInfo::isPhysicalRegister(Reg) || isReserved(Reg))
203 if (!isRegUsed(Reg)) {
204 // Check if it's partial live: e.g.
205 // D0 = insert_subreg D0<undef>, S0
207 // The problem is the insert_subreg could be eliminated. The use of
208 // D0 is using a partially undef value. This is not *incorrect* since
209 // S1 is can be freely clobbered.
210 // Ideally we would like a way to model this, but leaving the
211 // insert_subreg around causes both correctness and performance issues.
212 bool SubUsed = false;
213 for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs)
214 if (isRegUsed(*SubRegs)) {
218 bool SuperUsed = false;
219 for (MCSuperRegIterator SR(Reg, TRI); SR.isValid(); ++SR) {
220 if (isRegUsed(*SR)) {
225 if (!SubUsed && !SuperUsed) {
226 MBB->getParent()->verify(nullptr, "In Register Scavenger");
227 llvm_unreachable("Using an undefined register!");
235 // FIXME: Enable this once we've figured out how to correctly transfer
236 // implicit kills during codegen passes like the coalescer.
237 assert((KillRegs.test(Reg) || isUnused(Reg) ||
238 isLiveInButUnusedBefore(Reg, MI, MBB, TRI, MRI)) &&
239 "Re-defining a live register!");
245 // Commit the changes.
246 setUnused(KillRegUnits);
247 setUsed(DefRegUnits);
250 void RegScavenger::backward() {
251 assert(Tracking && "Must be tracking to determine kills and defs");
253 const MachineInstr &MI = *MBBI;
254 LiveUnits.stepBackward(MI);
256 if (MBBI == MBB->begin()) {
257 MBBI = MachineBasicBlock::iterator(nullptr);
263 bool RegScavenger::isRegUsed(unsigned Reg, bool includeReserved) const {
265 return includeReserved;
266 return !LiveUnits.available(Reg);
269 unsigned RegScavenger::FindUnusedReg(const TargetRegisterClass *RC) const {
270 for (unsigned Reg : *RC) {
271 if (!isRegUsed(Reg)) {
272 DEBUG(dbgs() << "Scavenger found unused reg: " << TRI->getName(Reg) <<
280 BitVector RegScavenger::getRegsAvailable(const TargetRegisterClass *RC) {
281 BitVector Mask(TRI->getNumRegs());
282 for (unsigned Reg : *RC)
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 (const MachineOperand &MO : MI->operands()) {
311 Candidates.clearBitsNotInMask(MO.getRegMask());
312 if (!MO.isReg() || MO.isUndef() || !MO.getReg())
314 if (TargetRegisterInfo::isVirtualRegister(MO.getReg())) {
316 isVirtDefInsn = true;
317 else if (MO.isKill())
318 isVirtKillInsn = true;
321 for (MCRegAliasIterator AI(MO.getReg(), TRI, true); AI.isValid(); ++AI)
322 Candidates.reset(*AI);
324 // If we're not in a virtual reg's live range, this is a valid
326 if (!inVirtLiveRange) RestorePointMI = MI;
328 // Update whether we're in the live range of a virtual register
329 if (isVirtKillInsn) inVirtLiveRange = false;
330 if (isVirtDefInsn) inVirtLiveRange = true;
332 // Was our survivor untouched by this instruction?
333 if (Candidates.test(Survivor))
336 // All candidates gone?
337 if (Candidates.none())
340 Survivor = Candidates.find_first();
342 // If we ran off the end, that's where we want to restore.
343 if (MI == ME) RestorePointMI = ME;
344 assert(RestorePointMI != StartMI &&
345 "No available scavenger restore location!");
347 // We ran out of candidates, so stop the search.
348 UseMI = RestorePointMI;
352 static unsigned getFrameIndexOperandNum(MachineInstr &MI) {
354 while (!MI.getOperand(i).isFI()) {
356 assert(i < MI.getNumOperands() && "Instr doesn't have FrameIndex operand!");
361 unsigned RegScavenger::scavengeRegister(const TargetRegisterClass *RC,
362 MachineBasicBlock::iterator I,
364 MachineInstr &MI = *I;
365 const MachineFunction &MF = *MI.getParent()->getParent();
366 // Consider all allocatable registers in the register class initially
367 BitVector Candidates = TRI->getAllocatableSet(MF, RC);
369 // Exclude all the registers being used by the instruction.
370 for (const MachineOperand &MO : MI.operands()) {
371 if (MO.isReg() && MO.getReg() != 0 && !(MO.isUse() && MO.isUndef()) &&
372 !TargetRegisterInfo::isVirtualRegister(MO.getReg()))
373 for (MCRegAliasIterator AI(MO.getReg(), TRI, true); AI.isValid(); ++AI)
374 Candidates.reset(*AI);
377 // Try to find a register that's unused if there is one, as then we won't
379 BitVector Available = getRegsAvailable(RC);
380 Available &= Candidates;
382 Candidates = Available;
384 // Find the register whose use is furthest away.
385 MachineBasicBlock::iterator UseMI;
386 unsigned SReg = findSurvivorReg(I, Candidates, 25, UseMI);
388 // If we found an unused register there is no reason to spill it.
389 if (!isRegUsed(SReg)) {
390 DEBUG(dbgs() << "Scavenged register: " << TRI->getName(SReg) << "\n");
394 // Find an available scavenging slot with size and alignment matching
395 // the requirements of the class RC.
396 const MachineFrameInfo &MFI = MF.getFrameInfo();
397 unsigned NeedSize = TRI->getSpillSize(*RC);
398 unsigned NeedAlign = TRI->getSpillAlignment(*RC);
400 unsigned SI = Scavenged.size(), Diff = std::numeric_limits<unsigned>::max();
401 int FIB = MFI.getObjectIndexBegin(), FIE = MFI.getObjectIndexEnd();
402 for (unsigned I = 0; I < Scavenged.size(); ++I) {
403 if (Scavenged[I].Reg != 0)
405 // Verify that this slot is valid for this register.
406 int FI = Scavenged[I].FrameIndex;
407 if (FI < FIB || FI >= FIE)
409 unsigned S = MFI.getObjectSize(FI);
410 unsigned A = MFI.getObjectAlignment(FI);
411 if (NeedSize > S || NeedAlign > A)
413 // Avoid wasting slots with large size and/or large alignment. Pick one
414 // that is the best fit for this register class (in street metric).
415 // Picking a larger slot than necessary could happen if a slot for a
416 // larger register is reserved before a slot for a smaller one. When
417 // trying to spill a smaller register, the large slot would be found
418 // first, thus making it impossible to spill the larger register later.
419 unsigned D = (S-NeedSize) + (A-NeedAlign);
426 if (SI == Scavenged.size()) {
427 // We need to scavenge a register but have no spill slot, the target
428 // must know how to do it (if not, we'll assert below).
429 Scavenged.push_back(ScavengedInfo(FIE));
432 // Avoid infinite regress
433 Scavenged[SI].Reg = SReg;
435 // If the target knows how to save/restore the register, let it do so;
436 // otherwise, use the emergency stack spill slot.
437 if (!TRI->saveScavengerRegister(*MBB, I, UseMI, RC, SReg)) {
438 // Spill the scavenged register before I.
439 int FI = Scavenged[SI].FrameIndex;
440 if (FI < FIB || FI >= FIE) {
441 std::string Msg = std::string("Error while trying to spill ") +
442 TRI->getName(SReg) + " from class " + TRI->getRegClassName(RC) +
443 ": Cannot scavenge register without an emergency spill slot!";
444 report_fatal_error(Msg.c_str());
446 TII->storeRegToStackSlot(*MBB, I, SReg, true, Scavenged[SI].FrameIndex,
448 MachineBasicBlock::iterator II = std::prev(I);
450 unsigned FIOperandNum = getFrameIndexOperandNum(*II);
451 TRI->eliminateFrameIndex(II, SPAdj, FIOperandNum, this);
453 // Restore the scavenged register before its use (or first terminator).
454 TII->loadRegFromStackSlot(*MBB, UseMI, SReg, Scavenged[SI].FrameIndex,
456 II = std::prev(UseMI);
458 FIOperandNum = getFrameIndexOperandNum(*II);
459 TRI->eliminateFrameIndex(II, SPAdj, FIOperandNum, this);
462 Scavenged[SI].Restore = &*std::prev(UseMI);
464 // Doing this here leads to infinite regress.
465 // Scavenged[SI].Reg = SReg;
467 DEBUG(dbgs() << "Scavenged register (with spill): " << TRI->getName(SReg) <<