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