c965d8715b00edc264229885928cc452cff13822
[oota-llvm.git] / lib / CodeGen / RegisterScavenging.cpp
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 // 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
13 // spill slots.
14 //
15 //===----------------------------------------------------------------------===//
16
17 #define DEBUG_TYPE "reg-scavenging"
18 #include "llvm/CodeGen/RegisterScavenging.h"
19 #include "llvm/CodeGen/MachineFrameInfo.h"
20 #include "llvm/CodeGen/MachineFunction.h"
21 #include "llvm/CodeGen/MachineBasicBlock.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/TargetRegisterInfo.h"
28 #include "llvm/Target/TargetInstrInfo.h"
29 #include "llvm/Target/TargetMachine.h"
30 #include "llvm/ADT/DenseMap.h"
31 #include "llvm/ADT/SmallPtrSet.h"
32 #include "llvm/ADT/SmallVector.h"
33 #include "llvm/ADT/STLExtras.h"
34 using namespace llvm;
35
36 /// setUsed - Set the register and its sub-registers as being used.
37 void RegScavenger::setUsed(unsigned Reg) {
38   RegsAvailable.reset(Reg);
39
40   for (const uint16_t *SubRegs = TRI->getSubRegisters(Reg);
41        unsigned SubReg = *SubRegs; ++SubRegs)
42     RegsAvailable.reset(SubReg);
43 }
44
45 bool RegScavenger::isAliasUsed(unsigned Reg) const {
46   for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
47     if (isUsed(*AI))
48       return true;
49   return false;
50 }
51
52 void RegScavenger::initRegState() {
53   ScavengedReg = 0;
54   ScavengedRC = NULL;
55   ScavengeRestore = NULL;
56
57   // All registers started out unused.
58   RegsAvailable.set();
59
60   if (!MBB)
61     return;
62
63   // Live-in registers are in use.
64   for (MachineBasicBlock::livein_iterator I = MBB->livein_begin(),
65          E = MBB->livein_end(); I != E; ++I)
66     setUsed(*I);
67
68   // Pristine CSRs are also unavailable.
69   BitVector PR = MBB->getParent()->getFrameInfo()->getPristineRegs(MBB);
70   for (int I = PR.find_first(); I>0; I = PR.find_next(I))
71     setUsed(I);
72 }
73
74 void RegScavenger::enterBasicBlock(MachineBasicBlock *mbb) {
75   MachineFunction &MF = *mbb->getParent();
76   const TargetMachine &TM = MF.getTarget();
77   TII = TM.getInstrInfo();
78   TRI = TM.getRegisterInfo();
79   MRI = &MF.getRegInfo();
80
81   assert((NumPhysRegs == 0 || NumPhysRegs == TRI->getNumRegs()) &&
82          "Target changed?");
83
84   // It is not possible to use the register scavenger after late optimization
85   // passes that don't preserve accurate liveness information.
86   assert(MRI->tracksLiveness() &&
87          "Cannot use register scavenger with inaccurate liveness");
88
89   // Self-initialize.
90   if (!MBB) {
91     NumPhysRegs = TRI->getNumRegs();
92     RegsAvailable.resize(NumPhysRegs);
93     KillRegs.resize(NumPhysRegs);
94     DefRegs.resize(NumPhysRegs);
95
96     // Create reserved registers bitvector.
97     ReservedRegs = TRI->getReservedRegs(MF);
98
99     // Create callee-saved registers bitvector.
100     CalleeSavedRegs.resize(NumPhysRegs);
101     const uint16_t *CSRegs = TRI->getCalleeSavedRegs(&MF);
102     if (CSRegs != NULL)
103       for (unsigned i = 0; CSRegs[i]; ++i)
104         CalleeSavedRegs.set(CSRegs[i]);
105   }
106
107   MBB = mbb;
108   initRegState();
109
110   Tracking = false;
111 }
112
113 void RegScavenger::addRegWithSubRegs(BitVector &BV, unsigned Reg) {
114   BV.set(Reg);
115   for (const uint16_t *R = TRI->getSubRegisters(Reg); *R; R++)
116     BV.set(*R);
117 }
118
119 void RegScavenger::forward() {
120   // Move ptr forward.
121   if (!Tracking) {
122     MBBI = MBB->begin();
123     Tracking = true;
124   } else {
125     assert(MBBI != MBB->end() && "Already past the end of the basic block!");
126     MBBI = llvm::next(MBBI);
127   }
128   assert(MBBI != MBB->end() && "Already at the end of the basic block!");
129
130   MachineInstr *MI = MBBI;
131
132   if (MI == ScavengeRestore) {
133     ScavengedReg = 0;
134     ScavengedRC = NULL;
135     ScavengeRestore = NULL;
136   }
137
138   if (MI->isDebugValue())
139     return;
140
141   // Find out which registers are early clobbered, killed, defined, and marked
142   // def-dead in this instruction.
143   // FIXME: The scavenger is not predication aware. If the instruction is
144   // predicated, conservatively assume "kill" markers do not actually kill the
145   // register. Similarly ignores "dead" markers.
146   bool isPred = TII->isPredicated(MI);
147   KillRegs.reset();
148   DefRegs.reset();
149   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
150     const MachineOperand &MO = MI->getOperand(i);
151     if (MO.isRegMask())
152       (isPred ? DefRegs : KillRegs).setBitsNotInMask(MO.getRegMask());
153     if (!MO.isReg())
154       continue;
155     unsigned Reg = MO.getReg();
156     if (!Reg || isReserved(Reg))
157       continue;
158
159     if (MO.isUse()) {
160       // Ignore undef uses.
161       if (MO.isUndef())
162         continue;
163       if (!isPred && MO.isKill())
164         addRegWithSubRegs(KillRegs, Reg);
165     } else {
166       assert(MO.isDef());
167       if (!isPred && MO.isDead())
168         addRegWithSubRegs(KillRegs, Reg);
169       else
170         addRegWithSubRegs(DefRegs, Reg);
171     }
172   }
173
174   // Verify uses and defs.
175 #ifndef NDEBUG
176   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
177     const MachineOperand &MO = MI->getOperand(i);
178     if (!MO.isReg())
179       continue;
180     unsigned Reg = MO.getReg();
181     if (!Reg || isReserved(Reg))
182       continue;
183     if (MO.isUse()) {
184       if (MO.isUndef())
185         continue;
186       if (!isUsed(Reg)) {
187         // Check if it's partial live: e.g.
188         // D0 = insert_subreg D0<undef>, S0
189         // ... D0
190         // The problem is the insert_subreg could be eliminated. The use of
191         // D0 is using a partially undef value. This is not *incorrect* since
192         // S1 is can be freely clobbered.
193         // Ideally we would like a way to model this, but leaving the
194         // insert_subreg around causes both correctness and performance issues.
195         bool SubUsed = false;
196         for (const uint16_t *SubRegs = TRI->getSubRegisters(Reg);
197              unsigned SubReg = *SubRegs; ++SubRegs)
198           if (isUsed(SubReg)) {
199             SubUsed = true;
200             break;
201           }
202         if (!SubUsed) {
203           MBB->getParent()->verify(NULL, "In Register Scavenger");
204           llvm_unreachable("Using an undefined register!");
205         }
206         (void)SubUsed;
207       }
208     } else {
209       assert(MO.isDef());
210 #if 0
211       // FIXME: Enable this once we've figured out how to correctly transfer
212       // implicit kills during codegen passes like the coalescer.
213       assert((KillRegs.test(Reg) || isUnused(Reg) ||
214               isLiveInButUnusedBefore(Reg, MI, MBB, TRI, MRI)) &&
215              "Re-defining a live register!");
216 #endif
217     }
218   }
219 #endif // NDEBUG
220
221   // Commit the changes.
222   setUnused(KillRegs);
223   setUsed(DefRegs);
224 }
225
226 void RegScavenger::getRegsUsed(BitVector &used, bool includeReserved) {
227   used = RegsAvailable;
228   used.flip();
229   if (includeReserved)
230     used |= ReservedRegs;
231   else
232     used.reset(ReservedRegs);
233 }
234
235 unsigned RegScavenger::FindUnusedReg(const TargetRegisterClass *RC) const {
236   for (TargetRegisterClass::iterator I = RC->begin(), E = RC->end();
237        I != E; ++I)
238     if (!isAliasUsed(*I)) {
239       DEBUG(dbgs() << "Scavenger found unused reg: " << TRI->getName(*I) <<
240             "\n");
241       return *I;
242     }
243   return 0;
244 }
245
246 /// getRegsAvailable - Return all available registers in the register class
247 /// in Mask.
248 BitVector RegScavenger::getRegsAvailable(const TargetRegisterClass *RC) {
249   BitVector Mask(TRI->getNumRegs());
250   for (TargetRegisterClass::iterator I = RC->begin(), E = RC->end();
251        I != E; ++I)
252     if (!isAliasUsed(*I))
253       Mask.set(*I);
254   return Mask;
255 }
256
257 /// findSurvivorReg - Return the candidate register that is unused for the
258 /// longest after StargMII. UseMI is set to the instruction where the search
259 /// stopped.
260 ///
261 /// No more than InstrLimit instructions are inspected.
262 ///
263 unsigned RegScavenger::findSurvivorReg(MachineBasicBlock::iterator StartMI,
264                                        BitVector &Candidates,
265                                        unsigned InstrLimit,
266                                        MachineBasicBlock::iterator &UseMI) {
267   int Survivor = Candidates.find_first();
268   assert(Survivor > 0 && "No candidates for scavenging");
269
270   MachineBasicBlock::iterator ME = MBB->getFirstTerminator();
271   assert(StartMI != ME && "MI already at terminator");
272   MachineBasicBlock::iterator RestorePointMI = StartMI;
273   MachineBasicBlock::iterator MI = StartMI;
274
275   bool inVirtLiveRange = false;
276   for (++MI; InstrLimit > 0 && MI != ME; ++MI, --InstrLimit) {
277     if (MI->isDebugValue()) {
278       ++InstrLimit; // Don't count debug instructions
279       continue;
280     }
281     bool isVirtKillInsn = false;
282     bool isVirtDefInsn = false;
283     // Remove any candidates touched by instruction.
284     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
285       const MachineOperand &MO = MI->getOperand(i);
286       if (MO.isRegMask())
287         Candidates.clearBitsNotInMask(MO.getRegMask());
288       if (!MO.isReg() || MO.isUndef() || !MO.getReg())
289         continue;
290       if (TargetRegisterInfo::isVirtualRegister(MO.getReg())) {
291         if (MO.isDef())
292           isVirtDefInsn = true;
293         else if (MO.isKill())
294           isVirtKillInsn = true;
295         continue;
296       }
297       for (MCRegAliasIterator AI(MO.getReg(), TRI, true); AI.isValid(); ++AI)
298         Candidates.reset(*AI);
299     }
300     // If we're not in a virtual reg's live range, this is a valid
301     // restore point.
302     if (!inVirtLiveRange) RestorePointMI = MI;
303
304     // Update whether we're in the live range of a virtual register
305     if (isVirtKillInsn) inVirtLiveRange = false;
306     if (isVirtDefInsn) inVirtLiveRange = true;
307
308     // Was our survivor untouched by this instruction?
309     if (Candidates.test(Survivor))
310       continue;
311
312     // All candidates gone?
313     if (Candidates.none())
314       break;
315
316     Survivor = Candidates.find_first();
317   }
318   // If we ran off the end, that's where we want to restore.
319   if (MI == ME) RestorePointMI = ME;
320   assert (RestorePointMI != StartMI &&
321           "No available scavenger restore location!");
322
323   // We ran out of candidates, so stop the search.
324   UseMI = RestorePointMI;
325   return Survivor;
326 }
327
328 unsigned RegScavenger::scavengeRegister(const TargetRegisterClass *RC,
329                                         MachineBasicBlock::iterator I,
330                                         int SPAdj) {
331   // Consider all allocatable registers in the register class initially
332   BitVector Candidates =
333     TRI->getAllocatableSet(*I->getParent()->getParent(), RC);
334
335   // Exclude all the registers being used by the instruction.
336   for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
337     MachineOperand &MO = I->getOperand(i);
338     if (MO.isReg() && MO.getReg() != 0 &&
339         !TargetRegisterInfo::isVirtualRegister(MO.getReg()))
340       Candidates.reset(MO.getReg());
341   }
342
343   // Try to find a register that's unused if there is one, as then we won't
344   // have to spill. Search explicitly rather than masking out based on
345   // RegsAvailable, as RegsAvailable does not take aliases into account.
346   // That's what getRegsAvailable() is for.
347   BitVector Available = getRegsAvailable(RC);
348   Available &= Candidates;
349   if (Available.any())
350     Candidates = Available;
351
352   // Find the register whose use is furthest away.
353   MachineBasicBlock::iterator UseMI;
354   unsigned SReg = findSurvivorReg(I, Candidates, 25, UseMI);
355
356   // If we found an unused register there is no reason to spill it.
357   if (!isAliasUsed(SReg)) {
358     DEBUG(dbgs() << "Scavenged register: " << TRI->getName(SReg) << "\n");
359     return SReg;
360   }
361
362   assert(ScavengedReg == 0 &&
363          "Scavenger slot is live, unable to scavenge another register!");
364
365   // Avoid infinite regress
366   ScavengedReg = SReg;
367
368   // If the target knows how to save/restore the register, let it do so;
369   // otherwise, use the emergency stack spill slot.
370   if (!TRI->saveScavengerRegister(*MBB, I, UseMI, RC, SReg)) {
371     // Spill the scavenged register before I.
372     assert(ScavengingFrameIndex >= 0 &&
373            "Cannot scavenge register without an emergency spill slot!");
374     TII->storeRegToStackSlot(*MBB, I, SReg, true, ScavengingFrameIndex, RC,TRI);
375     MachineBasicBlock::iterator II = prior(I);
376     TRI->eliminateFrameIndex(II, SPAdj, this);
377
378     // Restore the scavenged register before its use (or first terminator).
379     TII->loadRegFromStackSlot(*MBB, UseMI, SReg, ScavengingFrameIndex, RC, TRI);
380     II = prior(UseMI);
381     TRI->eliminateFrameIndex(II, SPAdj, this);
382   }
383
384   ScavengeRestore = prior(UseMI);
385
386   // Doing this here leads to infinite regress.
387   // ScavengedReg = SReg;
388   ScavengedRC = RC;
389
390   DEBUG(dbgs() << "Scavenged register (with spill): " << TRI->getName(SReg) <<
391         "\n");
392
393   return SReg;
394 }