1 //===-- RegisterScavenging.cpp - Machine register scavenging --------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 /// \file
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.
15 //
16 //===----------------------------------------------------------------------===//
17 
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/TargetRegisterInfo.h"
29 #include "llvm/Target/TargetSubtargetInfo.h"
30 using namespace llvm;
31 
32 #define DEBUG_TYPE "reg-scavenging"
33 
34 void RegScavenger::setRegUsed(unsigned Reg, LaneBitmask LaneMask) {
35   LiveUnits.addRegMasked(Reg, LaneMask);
36 }
37 
38 void RegScavenger::init(MachineBasicBlock &MBB) {
39   MachineFunction &MF = *MBB.getParent();
40   TII = MF.getSubtarget().getInstrInfo();
41   TRI = MF.getSubtarget().getRegisterInfo();
42   MRI = &MF.getRegInfo();
43   LiveUnits.init(*TRI);
44 
45   assert((NumRegUnits == 0 || NumRegUnits == TRI->getNumRegUnits()) &&
46          "Target changed?");
47 
48   // Self-initialize.
49   if (!this->MBB) {
50     NumRegUnits = TRI->getNumRegUnits();
51     KillRegUnits.resize(NumRegUnits);
52     DefRegUnits.resize(NumRegUnits);
53     TmpRegUnits.resize(NumRegUnits);
54   }
55   this->MBB = &MBB;
56 
57   for (SmallVectorImpl<ScavengedInfo>::iterator I = Scavenged.begin(),
58          IE = Scavenged.end(); I != IE; ++I) {
59     I->Reg = 0;
60     I->Restore = nullptr;
61   }
62 
63   Tracking = false;
64 }
65 
66 void RegScavenger::enterBasicBlock(MachineBasicBlock &MBB) {
67   init(MBB);
68   LiveUnits.addLiveIns(MBB);
69 }
70 
71 void RegScavenger::enterBasicBlockEnd(MachineBasicBlock &MBB) {
72   init(MBB);
73   LiveUnits.addLiveOuts(MBB);
74 
75   // Move internal iterator at the last instruction of the block.
76   if (MBB.begin() != MBB.end()) {
77     MBBI = std::prev(MBB.end());
78     Tracking = true;
79   }
80 }
81 
82 void RegScavenger::addRegUnits(BitVector &BV, unsigned Reg) {
83   for (MCRegUnitIterator RUI(Reg, TRI); RUI.isValid(); ++RUI)
84     BV.set(*RUI);
85 }
86 
87 void RegScavenger::removeRegUnits(BitVector &BV, unsigned Reg) {
88   for (MCRegUnitIterator RUI(Reg, TRI); RUI.isValid(); ++RUI)
89     BV.reset(*RUI);
90 }
91 
92 void RegScavenger::determineKillsAndDefs() {
93   assert(Tracking && "Must be tracking to determine kills and defs");
94 
95   MachineInstr &MI = *MBBI;
96   assert(!MI.isDebugValue() && "Debug values have no kills or defs");
97 
98   // Find out which registers are early clobbered, killed, defined, and marked
99   // def-dead in this instruction.
100   KillRegUnits.reset();
101   DefRegUnits.reset();
102   for (const MachineOperand &MO : MI.operands()) {
103     if (MO.isRegMask()) {
104       TmpRegUnits.clear();
105       for (unsigned RU = 0, RUEnd = TRI->getNumRegUnits(); RU != RUEnd; ++RU) {
106         for (MCRegUnitRootIterator RURI(RU, TRI); RURI.isValid(); ++RURI) {
107           if (MO.clobbersPhysReg(*RURI)) {
108             TmpRegUnits.set(RU);
109             break;
110           }
111         }
112       }
113 
114       // Apply the mask.
115       KillRegUnits |= TmpRegUnits;
116     }
117     if (!MO.isReg())
118       continue;
119     unsigned Reg = MO.getReg();
120     if (!TargetRegisterInfo::isPhysicalRegister(Reg) || isReserved(Reg))
121       continue;
122 
123     if (MO.isUse()) {
124       // Ignore undef uses.
125       if (MO.isUndef())
126         continue;
127       if (MO.isKill())
128         addRegUnits(KillRegUnits, Reg);
129     } else {
130       assert(MO.isDef());
131       if (MO.isDead())
132         addRegUnits(KillRegUnits, Reg);
133       else
134         addRegUnits(DefRegUnits, Reg);
135     }
136   }
137 }
138 
139 void RegScavenger::unprocess() {
140   assert(Tracking && "Cannot unprocess because we're not tracking");
141 
142   MachineInstr &MI = *MBBI;
143   if (!MI.isDebugValue()) {
144     determineKillsAndDefs();
145 
146     // Commit the changes.
147     setUsed(KillRegUnits);
148     setUnused(DefRegUnits);
149   }
150 
151   if (MBBI == MBB->begin()) {
152     MBBI = MachineBasicBlock::iterator(nullptr);
153     Tracking = false;
154   } else
155     --MBBI;
156 }
157 
158 void RegScavenger::forward() {
159   // Move ptr forward.
160   if (!Tracking) {
161     MBBI = MBB->begin();
162     Tracking = true;
163   } else {
164     assert(MBBI != MBB->end() && "Already past the end of the basic block!");
165     MBBI = std::next(MBBI);
166   }
167   assert(MBBI != MBB->end() && "Already at the end of the basic block!");
168 
169   MachineInstr &MI = *MBBI;
170 
171   for (SmallVectorImpl<ScavengedInfo>::iterator I = Scavenged.begin(),
172          IE = Scavenged.end(); I != IE; ++I) {
173     if (I->Restore != &MI)
174       continue;
175 
176     I->Reg = 0;
177     I->Restore = nullptr;
178   }
179 
180   if (MI.isDebugValue())
181     return;
182 
183   determineKillsAndDefs();
184 
185   // Verify uses and defs.
186 #ifndef NDEBUG
187   for (const MachineOperand &MO : MI.operands()) {
188     if (!MO.isReg())
189       continue;
190     unsigned Reg = MO.getReg();
191     if (!TargetRegisterInfo::isPhysicalRegister(Reg) || isReserved(Reg))
192       continue;
193     if (MO.isUse()) {
194       if (MO.isUndef())
195         continue;
196       if (!isRegUsed(Reg)) {
197         // Check if it's partial live: e.g.
198         // D0 = insert_subreg D0<undef>, S0
199         // ... D0
200         // The problem is the insert_subreg could be eliminated. The use of
201         // D0 is using a partially undef value. This is not *incorrect* since
202         // S1 is can be freely clobbered.
203         // Ideally we would like a way to model this, but leaving the
204         // insert_subreg around causes both correctness and performance issues.
205         bool SubUsed = false;
206         for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs)
207           if (isRegUsed(*SubRegs)) {
208             SubUsed = true;
209             break;
210           }
211         bool SuperUsed = false;
212         for (MCSuperRegIterator SR(Reg, TRI); SR.isValid(); ++SR) {
213           if (isRegUsed(*SR)) {
214             SuperUsed = true;
215             break;
216           }
217         }
218         if (!SubUsed && !SuperUsed) {
219           MBB->getParent()->verify(nullptr, "In Register Scavenger");
220           llvm_unreachable("Using an undefined register!");
221         }
222         (void)SubUsed;
223         (void)SuperUsed;
224       }
225     } else {
226       assert(MO.isDef());
227 #if 0
228       // FIXME: Enable this once we've figured out how to correctly transfer
229       // implicit kills during codegen passes like the coalescer.
230       assert((KillRegs.test(Reg) || isUnused(Reg) ||
231               isLiveInButUnusedBefore(Reg, MI, MBB, TRI, MRI)) &&
232              "Re-defining a live register!");
233 #endif
234     }
235   }
236 #endif // NDEBUG
237 
238   // Commit the changes.
239   setUnused(KillRegUnits);
240   setUsed(DefRegUnits);
241 }
242 
243 void RegScavenger::backward() {
244   assert(Tracking && "Must be tracking to determine kills and defs");
245 
246   const MachineInstr &MI = *MBBI;
247   LiveUnits.stepBackward(MI);
248 
249   if (MBBI == MBB->begin()) {
250     MBBI = MachineBasicBlock::iterator(nullptr);
251     Tracking = false;
252   } else
253     --MBBI;
254 }
255 
256 bool RegScavenger::isRegUsed(unsigned Reg, bool includeReserved) const {
257   if (isReserved(Reg))
258     return includeReserved;
259   return !LiveUnits.available(Reg);
260 }
261 
262 unsigned RegScavenger::FindUnusedReg(const TargetRegisterClass *RC) const {
263   for (unsigned Reg : *RC) {
264     if (!isRegUsed(Reg)) {
265       DEBUG(dbgs() << "Scavenger found unused reg: " << TRI->getName(Reg) <<
266             "\n");
267       return Reg;
268     }
269   }
270   return 0;
271 }
272 
273 BitVector RegScavenger::getRegsAvailable(const TargetRegisterClass *RC) {
274   BitVector Mask(TRI->getNumRegs());
275   for (unsigned Reg : *RC)
276     if (!isRegUsed(Reg))
277       Mask.set(Reg);
278   return Mask;
279 }
280 
281 unsigned RegScavenger::findSurvivorReg(MachineBasicBlock::iterator StartMI,
282                                        BitVector &Candidates,
283                                        unsigned InstrLimit,
284                                        MachineBasicBlock::iterator &UseMI) {
285   int Survivor = Candidates.find_first();
286   assert(Survivor > 0 && "No candidates for scavenging");
287 
288   MachineBasicBlock::iterator ME = MBB->getFirstTerminator();
289   assert(StartMI != ME && "MI already at terminator");
290   MachineBasicBlock::iterator RestorePointMI = StartMI;
291   MachineBasicBlock::iterator MI = StartMI;
292 
293   bool inVirtLiveRange = false;
294   for (++MI; InstrLimit > 0 && MI != ME; ++MI, --InstrLimit) {
295     if (MI->isDebugValue()) {
296       ++InstrLimit; // Don't count debug instructions
297       continue;
298     }
299     bool isVirtKillInsn = false;
300     bool isVirtDefInsn = false;
301     // Remove any candidates touched by instruction.
302     for (const MachineOperand &MO : MI->operands()) {
303       if (MO.isRegMask())
304         Candidates.clearBitsNotInMask(MO.getRegMask());
305       if (!MO.isReg() || MO.isUndef() || !MO.getReg())
306         continue;
307       if (TargetRegisterInfo::isVirtualRegister(MO.getReg())) {
308         if (MO.isDef())
309           isVirtDefInsn = true;
310         else if (MO.isKill())
311           isVirtKillInsn = true;
312         continue;
313       }
314       for (MCRegAliasIterator AI(MO.getReg(), TRI, true); AI.isValid(); ++AI)
315         Candidates.reset(*AI);
316     }
317     // If we're not in a virtual reg's live range, this is a valid
318     // restore point.
319     if (!inVirtLiveRange) RestorePointMI = MI;
320 
321     // Update whether we're in the live range of a virtual register
322     if (isVirtKillInsn) inVirtLiveRange = false;
323     if (isVirtDefInsn) inVirtLiveRange = true;
324 
325     // Was our survivor untouched by this instruction?
326     if (Candidates.test(Survivor))
327       continue;
328 
329     // All candidates gone?
330     if (Candidates.none())
331       break;
332 
333     Survivor = Candidates.find_first();
334   }
335   // If we ran off the end, that's where we want to restore.
336   if (MI == ME) RestorePointMI = ME;
337   assert(RestorePointMI != StartMI &&
338          "No available scavenger restore location!");
339 
340   // We ran out of candidates, so stop the search.
341   UseMI = RestorePointMI;
342   return Survivor;
343 }
344 
345 static unsigned getFrameIndexOperandNum(MachineInstr &MI) {
346   unsigned i = 0;
347   while (!MI.getOperand(i).isFI()) {
348     ++i;
349     assert(i < MI.getNumOperands() && "Instr doesn't have FrameIndex operand!");
350   }
351   return i;
352 }
353 
354 unsigned RegScavenger::scavengeRegister(const TargetRegisterClass *RC,
355                                         MachineBasicBlock::iterator I,
356                                         int SPAdj) {
357   MachineInstr &MI = *I;
358   const MachineFunction &MF = *MI.getParent()->getParent();
359   // Consider all allocatable registers in the register class initially
360   BitVector Candidates = TRI->getAllocatableSet(MF, RC);
361 
362   // Exclude all the registers being used by the instruction.
363   for (const MachineOperand &MO : MI.operands()) {
364     if (MO.isReg() && MO.getReg() != 0 && !(MO.isUse() && MO.isUndef()) &&
365         !TargetRegisterInfo::isVirtualRegister(MO.getReg()))
366       for (MCRegAliasIterator AI(MO.getReg(), TRI, true); AI.isValid(); ++AI)
367         Candidates.reset(*AI);
368   }
369 
370   // Try to find a register that's unused if there is one, as then we won't
371   // have to spill.
372   BitVector Available = getRegsAvailable(RC);
373   Available &= Candidates;
374   if (Available.any())
375     Candidates = Available;
376 
377   // Find the register whose use is furthest away.
378   MachineBasicBlock::iterator UseMI;
379   unsigned SReg = findSurvivorReg(I, Candidates, 25, UseMI);
380 
381   // If we found an unused register there is no reason to spill it.
382   if (!isRegUsed(SReg)) {
383     DEBUG(dbgs() << "Scavenged register: " << TRI->getName(SReg) << "\n");
384     return SReg;
385   }
386 
387   // Find an available scavenging slot with size and alignment matching
388   // the requirements of the class RC.
389   const MachineFrameInfo &MFI = MF.getFrameInfo();
390   unsigned NeedSize = RC->getSize();
391   unsigned NeedAlign = RC->getAlignment();
392 
393   unsigned SI = Scavenged.size(), Diff = UINT_MAX;
394   int FIB = MFI.getObjectIndexBegin(), FIE = MFI.getObjectIndexEnd();
395   for (unsigned I = 0; I < Scavenged.size(); ++I) {
396     if (Scavenged[I].Reg != 0)
397       continue;
398     // Verify that this slot is valid for this register.
399     int FI = Scavenged[I].FrameIndex;
400     if (FI < FIB || FI >= FIE)
401       continue;
402     unsigned S = MFI.getObjectSize(FI);
403     unsigned A = MFI.getObjectAlignment(FI);
404     if (NeedSize > S || NeedAlign > A)
405       continue;
406     // Avoid wasting slots with large size and/or large alignment. Pick one
407     // that is the best fit for this register class (in street metric).
408     // Picking a larger slot than necessary could happen if a slot for a
409     // larger register is reserved before a slot for a smaller one. When
410     // trying to spill a smaller register, the large slot would be found
411     // first, thus making it impossible to spill the larger register later.
412     unsigned D = (S-NeedSize) + (A-NeedAlign);
413     if (D < Diff) {
414       SI = I;
415       Diff = D;
416     }
417   }
418 
419   if (SI == Scavenged.size()) {
420     // We need to scavenge a register but have no spill slot, the target
421     // must know how to do it (if not, we'll assert below).
422     Scavenged.push_back(ScavengedInfo(FIE));
423   }
424 
425   // Avoid infinite regress
426   Scavenged[SI].Reg = SReg;
427 
428   // If the target knows how to save/restore the register, let it do so;
429   // otherwise, use the emergency stack spill slot.
430   if (!TRI->saveScavengerRegister(*MBB, I, UseMI, RC, SReg)) {
431     // Spill the scavenged register before I.
432     int FI = Scavenged[SI].FrameIndex;
433     if (FI < FIB || FI >= FIE) {
434       std::string Msg = std::string("Error while trying to spill ") +
435           TRI->getName(SReg) + " from class " + TRI->getRegClassName(RC) +
436           ": Cannot scavenge register without an emergency spill slot!";
437       report_fatal_error(Msg.c_str());
438     }
439     TII->storeRegToStackSlot(*MBB, I, SReg, true, Scavenged[SI].FrameIndex,
440                              RC, TRI);
441     MachineBasicBlock::iterator II = std::prev(I);
442 
443     unsigned FIOperandNum = getFrameIndexOperandNum(*II);
444     TRI->eliminateFrameIndex(II, SPAdj, FIOperandNum, this);
445 
446     // Restore the scavenged register before its use (or first terminator).
447     TII->loadRegFromStackSlot(*MBB, UseMI, SReg, Scavenged[SI].FrameIndex,
448                               RC, TRI);
449     II = std::prev(UseMI);
450 
451     FIOperandNum = getFrameIndexOperandNum(*II);
452     TRI->eliminateFrameIndex(II, SPAdj, FIOperandNum, this);
453   }
454 
455   Scavenged[SI].Restore = &*std::prev(UseMI);
456 
457   // Doing this here leads to infinite regress.
458   // Scavenged[SI].Reg = SReg;
459 
460   DEBUG(dbgs() << "Scavenged register (with spill): " << TRI->getName(SReg) <<
461         "\n");
462 
463   return SReg;
464 }
465