Fixed some spiller bugs exposed by the recent two-address code changes. Now
[oota-llvm.git] / lib / CodeGen / VirtRegMap.cpp
1 //===-- llvm/CodeGen/VirtRegMap.cpp - Virtual Register Map ----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the VirtRegMap class.
11 //
12 // It also contains implementations of the the Spiller interface, which, given a
13 // virtual register map and a machine function, eliminates all virtual
14 // references by replacing them with physical register references - adding spill
15 // code as necessary.
16 //
17 //===----------------------------------------------------------------------===//
18
19 #define DEBUG_TYPE "spiller"
20 #include "VirtRegMap.h"
21 #include "llvm/Function.h"
22 #include "llvm/CodeGen/MachineFrameInfo.h"
23 #include "llvm/CodeGen/MachineFunction.h"
24 #include "llvm/CodeGen/SSARegMap.h"
25 #include "llvm/Target/TargetMachine.h"
26 #include "llvm/Target/TargetInstrInfo.h"
27 #include "llvm/Support/CommandLine.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/Support/Compiler.h"
30 #include "llvm/ADT/Statistic.h"
31 #include "llvm/ADT/STLExtras.h"
32 #include <algorithm>
33 #include <iostream>
34 using namespace llvm;
35
36 namespace {
37   static Statistic<> NumSpills("spiller", "Number of register spills");
38   static Statistic<> NumStores("spiller", "Number of stores added");
39   static Statistic<> NumLoads ("spiller", "Number of loads added");
40   static Statistic<> NumReused("spiller", "Number of values reused");
41   static Statistic<> NumDSE   ("spiller", "Number of dead stores elided");
42   static Statistic<> NumDCE   ("spiller", "Number of copies elided");
43
44   enum SpillerName { simple, local };
45
46   static cl::opt<SpillerName>
47   SpillerOpt("spiller",
48              cl::desc("Spiller to use: (default: local)"),
49              cl::Prefix,
50              cl::values(clEnumVal(simple, "  simple spiller"),
51                         clEnumVal(local,  "  local spiller"),
52                         clEnumValEnd),
53              cl::init(local));
54 }
55
56 //===----------------------------------------------------------------------===//
57 //  VirtRegMap implementation
58 //===----------------------------------------------------------------------===//
59
60 VirtRegMap::VirtRegMap(MachineFunction &mf)
61   : TII(*mf.getTarget().getInstrInfo()), MF(mf), 
62     Virt2PhysMap(NO_PHYS_REG), Virt2StackSlotMap(NO_STACK_SLOT) {
63   grow();
64 }
65
66 void VirtRegMap::grow() {
67   Virt2PhysMap.grow(MF.getSSARegMap()->getLastVirtReg());
68   Virt2StackSlotMap.grow(MF.getSSARegMap()->getLastVirtReg());
69 }
70
71 int VirtRegMap::assignVirt2StackSlot(unsigned virtReg) {
72   assert(MRegisterInfo::isVirtualRegister(virtReg));
73   assert(Virt2StackSlotMap[virtReg] == NO_STACK_SLOT &&
74          "attempt to assign stack slot to already spilled register");
75   const TargetRegisterClass* RC = MF.getSSARegMap()->getRegClass(virtReg);
76   int frameIndex = MF.getFrameInfo()->CreateStackObject(RC->getSize(),
77                                                         RC->getAlignment());
78   Virt2StackSlotMap[virtReg] = frameIndex;
79   ++NumSpills;
80   return frameIndex;
81 }
82
83 void VirtRegMap::assignVirt2StackSlot(unsigned virtReg, int frameIndex) {
84   assert(MRegisterInfo::isVirtualRegister(virtReg));
85   assert(Virt2StackSlotMap[virtReg] == NO_STACK_SLOT &&
86          "attempt to assign stack slot to already spilled register");
87   Virt2StackSlotMap[virtReg] = frameIndex;
88 }
89
90 void VirtRegMap::virtFolded(unsigned VirtReg, MachineInstr *OldMI,
91                             unsigned OpNo, MachineInstr *NewMI) {
92   // Move previous memory references folded to new instruction.
93   MI2VirtMapTy::iterator IP = MI2VirtMap.lower_bound(NewMI);
94   for (MI2VirtMapTy::iterator I = MI2VirtMap.lower_bound(OldMI),
95          E = MI2VirtMap.end(); I != E && I->first == OldMI; ) {
96     MI2VirtMap.insert(IP, std::make_pair(NewMI, I->second));
97     MI2VirtMap.erase(I++);
98   }
99
100   ModRef MRInfo;
101   if (TII.getOperandConstraint(OldMI->getOpcode(), OpNo,
102                                TargetInstrInfo::TIED_TO)) {
103     // Folded a two-address operand.
104     MRInfo = isModRef;
105   } else if (OldMI->getOperand(OpNo).isDef()) {
106     MRInfo = isMod;
107   } else {
108     MRInfo = isRef;
109   }
110
111   // add new memory reference
112   MI2VirtMap.insert(IP, std::make_pair(NewMI, std::make_pair(VirtReg, MRInfo)));
113 }
114
115 void VirtRegMap::print(std::ostream &OS) const {
116   const MRegisterInfo* MRI = MF.getTarget().getRegisterInfo();
117
118   OS << "********** REGISTER MAP **********\n";
119   for (unsigned i = MRegisterInfo::FirstVirtualRegister,
120          e = MF.getSSARegMap()->getLastVirtReg(); i <= e; ++i) {
121     if (Virt2PhysMap[i] != (unsigned)VirtRegMap::NO_PHYS_REG)
122       OS << "[reg" << i << " -> " << MRI->getName(Virt2PhysMap[i]) << "]\n";
123
124   }
125
126   for (unsigned i = MRegisterInfo::FirstVirtualRegister,
127          e = MF.getSSARegMap()->getLastVirtReg(); i <= e; ++i)
128     if (Virt2StackSlotMap[i] != VirtRegMap::NO_STACK_SLOT)
129       OS << "[reg" << i << " -> fi#" << Virt2StackSlotMap[i] << "]\n";
130   OS << '\n';
131 }
132
133 void VirtRegMap::dump() const { print(std::cerr); }
134
135
136 //===----------------------------------------------------------------------===//
137 // Simple Spiller Implementation
138 //===----------------------------------------------------------------------===//
139
140 Spiller::~Spiller() {}
141
142 namespace {
143   struct VISIBILITY_HIDDEN SimpleSpiller : public Spiller {
144     bool runOnMachineFunction(MachineFunction& mf, VirtRegMap &VRM);
145   };
146 }
147
148 bool SimpleSpiller::runOnMachineFunction(MachineFunction &MF, VirtRegMap &VRM) {
149   DEBUG(std::cerr << "********** REWRITE MACHINE CODE **********\n");
150   DEBUG(std::cerr << "********** Function: "
151                   << MF.getFunction()->getName() << '\n');
152   const TargetMachine &TM = MF.getTarget();
153   const MRegisterInfo &MRI = *TM.getRegisterInfo();
154   bool *PhysRegsUsed = MF.getUsedPhysregs();
155
156   // LoadedRegs - Keep track of which vregs are loaded, so that we only load
157   // each vreg once (in the case where a spilled vreg is used by multiple
158   // operands).  This is always smaller than the number of operands to the
159   // current machine instr, so it should be small.
160   std::vector<unsigned> LoadedRegs;
161
162   for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
163        MBBI != E; ++MBBI) {
164     DEBUG(std::cerr << MBBI->getBasicBlock()->getName() << ":\n");
165     MachineBasicBlock &MBB = *MBBI;
166     for (MachineBasicBlock::iterator MII = MBB.begin(),
167            E = MBB.end(); MII != E; ++MII) {
168       MachineInstr &MI = *MII;
169       for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
170         MachineOperand &MO = MI.getOperand(i);
171         if (MO.isRegister() && MO.getReg())
172           if (MRegisterInfo::isVirtualRegister(MO.getReg())) {
173             unsigned VirtReg = MO.getReg();
174             unsigned PhysReg = VRM.getPhys(VirtReg);
175             if (VRM.hasStackSlot(VirtReg)) {
176               int StackSlot = VRM.getStackSlot(VirtReg);
177               const TargetRegisterClass* RC =
178                 MF.getSSARegMap()->getRegClass(VirtReg);
179
180               if (MO.isUse() &&
181                   std::find(LoadedRegs.begin(), LoadedRegs.end(), VirtReg)
182                   == LoadedRegs.end()) {
183                 MRI.loadRegFromStackSlot(MBB, &MI, PhysReg, StackSlot, RC);
184                 LoadedRegs.push_back(VirtReg);
185                 ++NumLoads;
186                 DEBUG(std::cerr << '\t' << *prior(MII));
187               }
188
189               if (MO.isDef()) {
190                 MRI.storeRegToStackSlot(MBB, next(MII), PhysReg, StackSlot, RC);
191                 ++NumStores;
192               }
193             }
194             PhysRegsUsed[PhysReg] = true;
195             MI.getOperand(i).setReg(PhysReg);
196           } else {
197             PhysRegsUsed[MO.getReg()] = true;
198           }
199       }
200
201       DEBUG(std::cerr << '\t' << MI);
202       LoadedRegs.clear();
203     }
204   }
205   return true;
206 }
207
208 //===----------------------------------------------------------------------===//
209 //  Local Spiller Implementation
210 //===----------------------------------------------------------------------===//
211
212 namespace {
213   /// LocalSpiller - This spiller does a simple pass over the machine basic
214   /// block to attempt to keep spills in registers as much as possible for
215   /// blocks that have low register pressure (the vreg may be spilled due to
216   /// register pressure in other blocks).
217   class VISIBILITY_HIDDEN LocalSpiller : public Spiller {
218     const MRegisterInfo *MRI;
219     const TargetInstrInfo *TII;
220   public:
221     bool runOnMachineFunction(MachineFunction &MF, VirtRegMap &VRM) {
222       MRI = MF.getTarget().getRegisterInfo();
223       TII = MF.getTarget().getInstrInfo();
224       DEBUG(std::cerr << "\n**** Local spiller rewriting function '"
225                       << MF.getFunction()->getName() << "':\n");
226
227       for (MachineFunction::iterator MBB = MF.begin(), E = MF.end();
228            MBB != E; ++MBB)
229         RewriteMBB(*MBB, VRM);
230       return true;
231     }
232   private:
233     void RewriteMBB(MachineBasicBlock &MBB, VirtRegMap &VRM);
234     void ClobberPhysReg(unsigned PR, std::map<int, unsigned> &SpillSlots,
235                         std::multimap<unsigned, int> &PhysRegs);
236     void ClobberPhysRegOnly(unsigned PR, std::map<int, unsigned> &SpillSlots,
237                             std::multimap<unsigned, int> &PhysRegs);
238     void ModifyStackSlot(int Slot, std::map<int, unsigned> &SpillSlots,
239                          std::multimap<unsigned, int> &PhysRegs);
240   };
241 }
242
243 /// AvailableSpills - As the local spiller is scanning and rewriting an MBB from
244 /// top down, keep track of which spills slots are available in each register.
245 ///
246 /// Note that not all physregs are created equal here.  In particular, some
247 /// physregs are reloads that we are allowed to clobber or ignore at any time.
248 /// Other physregs are values that the register allocated program is using that
249 /// we cannot CHANGE, but we can read if we like.  We keep track of this on a 
250 /// per-stack-slot basis as the low bit in the value of the SpillSlotsAvailable
251 /// entries.  The predicate 'canClobberPhysReg()' checks this bit and
252 /// addAvailable sets it if.
253 namespace {
254 class VISIBILITY_HIDDEN AvailableSpills {
255   const MRegisterInfo *MRI;
256   const TargetInstrInfo *TII;
257
258   // SpillSlotsAvailable - This map keeps track of all of the spilled virtual
259   // register values that are still available, due to being loaded or stored to,
260   // but not invalidated yet.
261   std::map<int, unsigned> SpillSlotsAvailable;
262     
263   // PhysRegsAvailable - This is the inverse of SpillSlotsAvailable, indicating
264   // which stack slot values are currently held by a physreg.  This is used to
265   // invalidate entries in SpillSlotsAvailable when a physreg is modified.
266   std::multimap<unsigned, int> PhysRegsAvailable;
267   
268   void ClobberPhysRegOnly(unsigned PhysReg);
269 public:
270   AvailableSpills(const MRegisterInfo *mri, const TargetInstrInfo *tii)
271     : MRI(mri), TII(tii) {
272   }
273   
274   /// getSpillSlotPhysReg - If the specified stack slot is available in a 
275   /// physical register, return that PhysReg, otherwise return 0.
276   unsigned getSpillSlotPhysReg(int Slot) const {
277     std::map<int, unsigned>::const_iterator I = SpillSlotsAvailable.find(Slot);
278     if (I != SpillSlotsAvailable.end())
279       return I->second >> 1;  // Remove the CanClobber bit.
280     return 0;
281   }
282   
283   const MRegisterInfo *getRegInfo() const { return MRI; }
284
285   /// addAvailable - Mark that the specified stack slot is available in the
286   /// specified physreg.  If CanClobber is true, the physreg can be modified at
287   /// any time without changing the semantics of the program.
288   void addAvailable(int Slot, unsigned Reg, bool CanClobber = true) {
289     // If this stack slot is thought to be available in some other physreg, 
290     // remove its record.
291     ModifyStackSlot(Slot);
292     
293     PhysRegsAvailable.insert(std::make_pair(Reg, Slot));
294     SpillSlotsAvailable[Slot] = (Reg << 1) | (unsigned)CanClobber;
295   
296     DEBUG(std::cerr << "Remembering SS#" << Slot << " in physreg "
297                     << MRI->getName(Reg) << "\n");
298   }
299   
300   /// canClobberPhysReg - Return true if the spiller is allowed to change the 
301   /// value of the specified stackslot register if it desires.  The specified
302   /// stack slot must be available in a physreg for this query to make sense.
303   bool canClobberPhysReg(int Slot) const {
304     assert(SpillSlotsAvailable.count(Slot) && "Slot not available!");
305     return SpillSlotsAvailable.find(Slot)->second & 1;
306   }
307   
308   /// ClobberPhysReg - This is called when the specified physreg changes
309   /// value.  We use this to invalidate any info about stuff we thing lives in
310   /// it and any of its aliases.
311   void ClobberPhysReg(unsigned PhysReg);
312
313   /// ModifyStackSlot - This method is called when the value in a stack slot
314   /// changes.  This removes information about which register the previous value
315   /// for this slot lives in (as the previous value is dead now).
316   void ModifyStackSlot(int Slot);
317 };
318 }
319
320 /// ClobberPhysRegOnly - This is called when the specified physreg changes
321 /// value.  We use this to invalidate any info about stuff we thing lives in it.
322 void AvailableSpills::ClobberPhysRegOnly(unsigned PhysReg) {
323   std::multimap<unsigned, int>::iterator I =
324     PhysRegsAvailable.lower_bound(PhysReg);
325   while (I != PhysRegsAvailable.end() && I->first == PhysReg) {
326     int Slot = I->second;
327     PhysRegsAvailable.erase(I++);
328     assert((SpillSlotsAvailable[Slot] >> 1) == PhysReg &&
329            "Bidirectional map mismatch!");
330     SpillSlotsAvailable.erase(Slot);
331     DEBUG(std::cerr << "PhysReg " << MRI->getName(PhysReg)
332                     << " clobbered, invalidating SS#" << Slot << "\n");
333   }
334 }
335
336 /// ClobberPhysReg - This is called when the specified physreg changes
337 /// value.  We use this to invalidate any info about stuff we thing lives in
338 /// it and any of its aliases.
339 void AvailableSpills::ClobberPhysReg(unsigned PhysReg) {
340   for (const unsigned *AS = MRI->getAliasSet(PhysReg); *AS; ++AS)
341     ClobberPhysRegOnly(*AS);
342   ClobberPhysRegOnly(PhysReg);
343 }
344
345 /// ModifyStackSlot - This method is called when the value in a stack slot
346 /// changes.  This removes information about which register the previous value
347 /// for this slot lives in (as the previous value is dead now).
348 void AvailableSpills::ModifyStackSlot(int Slot) {
349   std::map<int, unsigned>::iterator It = SpillSlotsAvailable.find(Slot);
350   if (It == SpillSlotsAvailable.end()) return;
351   unsigned Reg = It->second >> 1;
352   SpillSlotsAvailable.erase(It);
353   
354   // This register may hold the value of multiple stack slots, only remove this
355   // stack slot from the set of values the register contains.
356   std::multimap<unsigned, int>::iterator I = PhysRegsAvailable.lower_bound(Reg);
357   for (; ; ++I) {
358     assert(I != PhysRegsAvailable.end() && I->first == Reg &&
359            "Map inverse broken!");
360     if (I->second == Slot) break;
361   }
362   PhysRegsAvailable.erase(I);
363 }
364
365
366
367 // ReusedOp - For each reused operand, we keep track of a bit of information, in
368 // case we need to rollback upon processing a new operand.  See comments below.
369 namespace {
370   struct ReusedOp {
371     // The MachineInstr operand that reused an available value.
372     unsigned Operand;
373
374     // StackSlot - The spill slot of the value being reused.
375     unsigned StackSlot;
376
377     // PhysRegReused - The physical register the value was available in.
378     unsigned PhysRegReused;
379
380     // AssignedPhysReg - The physreg that was assigned for use by the reload.
381     unsigned AssignedPhysReg;
382     
383     // VirtReg - The virtual register itself.
384     unsigned VirtReg;
385
386     ReusedOp(unsigned o, unsigned ss, unsigned prr, unsigned apr,
387              unsigned vreg)
388       : Operand(o), StackSlot(ss), PhysRegReused(prr), AssignedPhysReg(apr),
389       VirtReg(vreg) {}
390   };
391   
392   /// ReuseInfo - This maintains a collection of ReuseOp's for each operand that
393   /// is reused instead of reloaded.
394   class VISIBILITY_HIDDEN ReuseInfo {
395     MachineInstr &MI;
396     std::vector<ReusedOp> Reuses;
397     bool *PhysRegsClobbered;
398   public:
399     ReuseInfo(MachineInstr &mi, const MRegisterInfo *mri) : MI(mi) {
400       PhysRegsClobbered = new bool[mri->getNumRegs()];
401       std::fill(PhysRegsClobbered, PhysRegsClobbered+mri->getNumRegs(), false);
402     }
403     ~ReuseInfo() {
404       delete[] PhysRegsClobbered;
405     }
406     
407     bool hasReuses() const {
408       return !Reuses.empty();
409     }
410     
411     /// addReuse - If we choose to reuse a virtual register that is already
412     /// available instead of reloading it, remember that we did so.
413     void addReuse(unsigned OpNo, unsigned StackSlot,
414                   unsigned PhysRegReused, unsigned AssignedPhysReg,
415                   unsigned VirtReg) {
416       // If the reload is to the assigned register anyway, no undo will be
417       // required.
418       if (PhysRegReused == AssignedPhysReg) return;
419       
420       // Otherwise, remember this.
421       Reuses.push_back(ReusedOp(OpNo, StackSlot, PhysRegReused, 
422                                 AssignedPhysReg, VirtReg));
423     }
424
425     void markClobbered(unsigned PhysReg) {
426       PhysRegsClobbered[PhysReg] = true;
427     }
428
429     bool isClobbered(unsigned PhysReg) const {
430       return PhysRegsClobbered[PhysReg];
431     }
432     
433     /// GetRegForReload - We are about to emit a reload into PhysReg.  If there
434     /// is some other operand that is using the specified register, either pick
435     /// a new register to use, or evict the previous reload and use this reg. 
436     unsigned GetRegForReload(unsigned PhysReg, MachineInstr *MI,
437                              AvailableSpills &Spills,
438                              std::map<int, MachineInstr*> &MaybeDeadStores) {
439       if (Reuses.empty()) return PhysReg;  // This is most often empty.
440
441       for (unsigned ro = 0, e = Reuses.size(); ro != e; ++ro) {
442         ReusedOp &Op = Reuses[ro];
443         // If we find some other reuse that was supposed to use this register
444         // exactly for its reload, we can change this reload to use ITS reload
445         // register.
446         if (Op.PhysRegReused == PhysReg) {
447           // Yup, use the reload register that we didn't use before.
448           unsigned NewReg = Op.AssignedPhysReg;          
449           return GetRegForReload(NewReg, MI, Spills, MaybeDeadStores);
450         } else {
451           // Otherwise, we might also have a problem if a previously reused
452           // value aliases the new register.  If so, codegen the previous reload
453           // and use this one.          
454           unsigned PRRU = Op.PhysRegReused;
455           const MRegisterInfo *MRI = Spills.getRegInfo();
456           if (MRI->areAliases(PRRU, PhysReg)) {
457             // Okay, we found out that an alias of a reused register
458             // was used.  This isn't good because it means we have
459             // to undo a previous reuse.
460             MachineBasicBlock *MBB = MI->getParent();
461             const TargetRegisterClass *AliasRC =
462               MBB->getParent()->getSSARegMap()->getRegClass(Op.VirtReg);
463
464             // Copy Op out of the vector and remove it, we're going to insert an
465             // explicit load for it.
466             ReusedOp NewOp = Op;
467             Reuses.erase(Reuses.begin()+ro);
468
469             // Ok, we're going to try to reload the assigned physreg into the
470             // slot that we were supposed to in the first place.  However, that
471             // register could hold a reuse.  Check to see if it conflicts or
472             // would prefer us to use a different register.
473             unsigned NewPhysReg = GetRegForReload(NewOp.AssignedPhysReg,
474                                                   MI, Spills, MaybeDeadStores);
475             
476             MRI->loadRegFromStackSlot(*MBB, MI, NewPhysReg,
477                                       NewOp.StackSlot, AliasRC);
478             Spills.ClobberPhysReg(NewPhysReg);
479             Spills.ClobberPhysReg(NewOp.PhysRegReused);
480             
481             // Any stores to this stack slot are not dead anymore.
482             MaybeDeadStores.erase(NewOp.StackSlot);
483             
484             MI->getOperand(NewOp.Operand).setReg(NewPhysReg);
485             
486             Spills.addAvailable(NewOp.StackSlot, NewPhysReg);
487             ++NumLoads;
488             DEBUG(MachineBasicBlock::iterator MII = MI;
489                   std::cerr << '\t' << *prior(MII));
490             
491             DEBUG(std::cerr << "Reuse undone!\n");
492             --NumReused;
493             
494             // Finally, PhysReg is now available, go ahead and use it.
495             return PhysReg;
496           }
497         }
498       }
499       return PhysReg;
500     }
501   };
502 }
503
504
505 /// rewriteMBB - Keep track of which spills are available even after the
506 /// register allocator is done with them.  If possible, avoid reloading vregs.
507 void LocalSpiller::RewriteMBB(MachineBasicBlock &MBB, VirtRegMap &VRM) {
508
509   DEBUG(std::cerr << MBB.getBasicBlock()->getName() << ":\n");
510
511   // Spills - Keep track of which spilled values are available in physregs so
512   // that we can choose to reuse the physregs instead of emitting reloads.
513   AvailableSpills Spills(MRI, TII);
514   
515   // MaybeDeadStores - When we need to write a value back into a stack slot,
516   // keep track of the inserted store.  If the stack slot value is never read
517   // (because the value was used from some available register, for example), and
518   // subsequently stored to, the original store is dead.  This map keeps track
519   // of inserted stores that are not used.  If we see a subsequent store to the
520   // same stack slot, the original store is deleted.
521   std::map<int, MachineInstr*> MaybeDeadStores;
522
523   bool *PhysRegsUsed = MBB.getParent()->getUsedPhysregs();
524
525   for (MachineBasicBlock::iterator MII = MBB.begin(), E = MBB.end();
526        MII != E; ) {
527     MachineInstr &MI = *MII;
528     MachineBasicBlock::iterator NextMII = MII; ++NextMII;
529
530     /// ReusedOperands - Keep track of operand reuse in case we need to undo
531     /// reuse.
532     ReuseInfo ReusedOperands(MI, MRI);
533
534     // Loop over all of the implicit defs, clearing them from our available
535     // sets.
536     const unsigned *ImpDef = TII->getImplicitDefs(MI.getOpcode());
537     if (ImpDef) {
538       for ( ; *ImpDef; ++ImpDef) {
539         PhysRegsUsed[*ImpDef] = true;
540         ReusedOperands.markClobbered(*ImpDef);
541         Spills.ClobberPhysReg(*ImpDef);
542       }
543     }
544
545     // Process all of the spilled uses and all non spilled reg references.
546     for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
547       MachineOperand &MO = MI.getOperand(i);
548       if (!MO.isRegister() || MO.getReg() == 0)
549         continue;   // Ignore non-register operands.
550       
551       if (MRegisterInfo::isPhysicalRegister(MO.getReg())) {
552         // Ignore physregs for spilling, but remember that it is used by this
553         // function.
554         PhysRegsUsed[MO.getReg()] = true;
555         ReusedOperands.markClobbered(MO.getReg());
556         continue;
557       }
558       
559       assert(MRegisterInfo::isVirtualRegister(MO.getReg()) &&
560              "Not a virtual or a physical register?");
561       
562       unsigned VirtReg = MO.getReg();
563       if (!VRM.hasStackSlot(VirtReg)) {
564         // This virtual register was assigned a physreg!
565         unsigned Phys = VRM.getPhys(VirtReg);
566         PhysRegsUsed[Phys] = true;
567         if (MO.isDef())
568           ReusedOperands.markClobbered(Phys);
569         MI.getOperand(i).setReg(Phys);
570         continue;
571       }
572       
573       // This virtual register is now known to be a spilled value.
574       if (!MO.isUse())
575         continue;  // Handle defs in the loop below (handle use&def here though)
576
577       int StackSlot = VRM.getStackSlot(VirtReg);
578       unsigned PhysReg;
579
580       // Check to see if this stack slot is available.
581       if ((PhysReg = Spills.getSpillSlotPhysReg(StackSlot))) {
582
583         // This spilled operand might be part of a two-address operand.  If this
584         // is the case, then changing it will necessarily require changing the 
585         // def part of the instruction as well.  However, in some cases, we
586         // aren't allowed to modify the reused register.  If none of these cases
587         // apply, reuse it.
588         bool CanReuse = true;
589         int ti = TII->getOperandConstraint(MI.getOpcode(), i,
590                                            TargetInstrInfo::TIED_TO);
591         if (ti != -1 &&
592             MI.getOperand(ti).isReg() && 
593             MI.getOperand(ti).getReg() == VirtReg) {
594           // Okay, we have a two address operand.  We can reuse this physreg as
595           // long as we are allowed to clobber the value and there is an earlier
596           // def that has already clobbered the physreg.
597           CanReuse = Spills.canClobberPhysReg(StackSlot) &&
598             !ReusedOperands.isClobbered(PhysReg);
599         }
600         
601         if (CanReuse) {
602           // If this stack slot value is already available, reuse it!
603           DEBUG(std::cerr << "Reusing SS#" << StackSlot << " from physreg "
604                           << MRI->getName(PhysReg) << " for vreg"
605                           << VirtReg <<" instead of reloading into physreg "
606                           << MRI->getName(VRM.getPhys(VirtReg)) << "\n");
607           MI.getOperand(i).setReg(PhysReg);
608
609           // The only technical detail we have is that we don't know that
610           // PhysReg won't be clobbered by a reloaded stack slot that occurs
611           // later in the instruction.  In particular, consider 'op V1, V2'.
612           // If V1 is available in physreg R0, we would choose to reuse it
613           // here, instead of reloading it into the register the allocator
614           // indicated (say R1).  However, V2 might have to be reloaded
615           // later, and it might indicate that it needs to live in R0.  When
616           // this occurs, we need to have information available that
617           // indicates it is safe to use R1 for the reload instead of R0.
618           //
619           // To further complicate matters, we might conflict with an alias,
620           // or R0 and R1 might not be compatible with each other.  In this
621           // case, we actually insert a reload for V1 in R1, ensuring that
622           // we can get at R0 or its alias.
623           ReusedOperands.addReuse(i, StackSlot, PhysReg,
624                                   VRM.getPhys(VirtReg), VirtReg);
625           if (ti != -1)
626             // Only mark it clobbered if this is a use&def operand.
627             ReusedOperands.markClobbered(PhysReg);
628           ++NumReused;
629           continue;
630         }
631         
632         // Otherwise we have a situation where we have a two-address instruction
633         // whose mod/ref operand needs to be reloaded.  This reload is already
634         // available in some register "PhysReg", but if we used PhysReg as the
635         // operand to our 2-addr instruction, the instruction would modify
636         // PhysReg.  This isn't cool if something later uses PhysReg and expects
637         // to get its initial value.
638         //
639         // To avoid this problem, and to avoid doing a load right after a store,
640         // we emit a copy from PhysReg into the designated register for this
641         // operand.
642         unsigned DesignatedReg = VRM.getPhys(VirtReg);
643         assert(DesignatedReg && "Must map virtreg to physreg!");
644
645         // Note that, if we reused a register for a previous operand, the
646         // register we want to reload into might not actually be
647         // available.  If this occurs, use the register indicated by the
648         // reuser.
649         if (ReusedOperands.hasReuses())
650           DesignatedReg = ReusedOperands.GetRegForReload(DesignatedReg, &MI, 
651                                                       Spills, MaybeDeadStores);
652         
653         // If the mapped designated register is actually the physreg we have
654         // incoming, we don't need to inserted a dead copy.
655         if (DesignatedReg == PhysReg) {
656           // If this stack slot value is already available, reuse it!
657           DEBUG(std::cerr << "Reusing SS#" << StackSlot << " from physreg "
658                           << MRI->getName(PhysReg) << " for vreg"
659                           << VirtReg
660                           << " instead of reloading into same physreg.\n");
661           MI.getOperand(i).setReg(PhysReg);
662           ReusedOperands.markClobbered(PhysReg);
663           ++NumReused;
664           continue;
665         }
666         
667         const TargetRegisterClass* RC =
668           MBB.getParent()->getSSARegMap()->getRegClass(VirtReg);
669
670         PhysRegsUsed[DesignatedReg] = true;
671         ReusedOperands.markClobbered(DesignatedReg);
672         MRI->copyRegToReg(MBB, &MI, DesignatedReg, PhysReg, RC);
673         
674         // This invalidates DesignatedReg.
675         Spills.ClobberPhysReg(DesignatedReg);
676         
677         Spills.addAvailable(StackSlot, DesignatedReg);
678         MI.getOperand(i).setReg(DesignatedReg);
679         DEBUG(std::cerr << '\t' << *prior(MII));
680         ++NumReused;
681         continue;
682       }
683       
684       // Otherwise, reload it and remember that we have it.
685       PhysReg = VRM.getPhys(VirtReg);
686       assert(PhysReg && "Must map virtreg to physreg!");
687       const TargetRegisterClass* RC =
688         MBB.getParent()->getSSARegMap()->getRegClass(VirtReg);
689
690       // Note that, if we reused a register for a previous operand, the
691       // register we want to reload into might not actually be
692       // available.  If this occurs, use the register indicated by the
693       // reuser.
694       if (ReusedOperands.hasReuses())
695         PhysReg = ReusedOperands.GetRegForReload(PhysReg, &MI, 
696                                                  Spills, MaybeDeadStores);
697       
698       PhysRegsUsed[PhysReg] = true;
699       ReusedOperands.markClobbered(PhysReg);
700       MRI->loadRegFromStackSlot(MBB, &MI, PhysReg, StackSlot, RC);
701       // This invalidates PhysReg.
702       Spills.ClobberPhysReg(PhysReg);
703
704       // Any stores to this stack slot are not dead anymore.
705       MaybeDeadStores.erase(StackSlot);
706       Spills.addAvailable(StackSlot, PhysReg);
707       ++NumLoads;
708       MI.getOperand(i).setReg(PhysReg);
709       DEBUG(std::cerr << '\t' << *prior(MII));
710     }
711
712     DEBUG(std::cerr << '\t' << MI);
713
714     // If we have folded references to memory operands, make sure we clear all
715     // physical registers that may contain the value of the spilled virtual
716     // register
717     VirtRegMap::MI2VirtMapTy::const_iterator I, End;
718     for (tie(I, End) = VRM.getFoldedVirts(&MI); I != End; ++I) {
719       DEBUG(std::cerr << "Folded vreg: " << I->second.first << "  MR: "
720                       << I->second.second);
721       unsigned VirtReg = I->second.first;
722       VirtRegMap::ModRef MR = I->second.second;
723       if (!VRM.hasStackSlot(VirtReg)) {
724         DEBUG(std::cerr << ": No stack slot!\n");
725         continue;
726       }
727       int SS = VRM.getStackSlot(VirtReg);
728       DEBUG(std::cerr << " - StackSlot: " << SS << "\n");
729       
730       // If this folded instruction is just a use, check to see if it's a
731       // straight load from the virt reg slot.
732       if ((MR & VirtRegMap::isRef) && !(MR & VirtRegMap::isMod)) {
733         int FrameIdx;
734         if (unsigned DestReg = TII->isLoadFromStackSlot(&MI, FrameIdx)) {
735           if (FrameIdx == SS) {
736             // If this spill slot is available, turn it into a copy (or nothing)
737             // instead of leaving it as a load!
738             if (unsigned InReg = Spills.getSpillSlotPhysReg(SS)) {
739               DEBUG(std::cerr << "Promoted Load To Copy: " << MI);
740               MachineFunction &MF = *MBB.getParent();
741               if (DestReg != InReg) {
742                 MRI->copyRegToReg(MBB, &MI, DestReg, InReg,
743                                   MF.getSSARegMap()->getRegClass(VirtReg));
744                 // Revisit the copy so we make sure to notice the effects of the
745                 // operation on the destreg (either needing to RA it if it's 
746                 // virtual or needing to clobber any values if it's physical).
747                 NextMII = &MI;
748                 --NextMII;  // backtrack to the copy.
749               }
750               VRM.RemoveFromFoldedVirtMap(&MI);
751               MBB.erase(&MI);
752               goto ProcessNextInst;
753             }
754           }
755         }
756       }
757
758       // If this reference is not a use, any previous store is now dead.
759       // Otherwise, the store to this stack slot is not dead anymore.
760       std::map<int, MachineInstr*>::iterator MDSI = MaybeDeadStores.find(SS);
761       if (MDSI != MaybeDeadStores.end()) {
762         if (MR & VirtRegMap::isRef)   // Previous store is not dead.
763           MaybeDeadStores.erase(MDSI);
764         else {
765           // If we get here, the store is dead, nuke it now.
766           assert(VirtRegMap::isMod && "Can't be modref!");
767           DEBUG(std::cerr << "Removed dead store:\t" << *MDSI->second);
768           MBB.erase(MDSI->second);
769           VRM.RemoveFromFoldedVirtMap(MDSI->second);
770           MaybeDeadStores.erase(MDSI);
771           ++NumDSE;
772         }
773       }
774
775       // If the spill slot value is available, and this is a new definition of
776       // the value, the value is not available anymore.
777       if (MR & VirtRegMap::isMod) {
778         // Notice that the value in this stack slot has been modified.
779         Spills.ModifyStackSlot(SS);
780         
781         // If this is *just* a mod of the value, check to see if this is just a
782         // store to the spill slot (i.e. the spill got merged into the copy). If
783         // so, realize that the vreg is available now, and add the store to the
784         // MaybeDeadStore info.
785         int StackSlot;
786         if (!(MR & VirtRegMap::isRef)) {
787           if (unsigned SrcReg = TII->isStoreToStackSlot(&MI, StackSlot)) {
788             assert(MRegisterInfo::isPhysicalRegister(SrcReg) &&
789                    "Src hasn't been allocated yet?");
790             // Okay, this is certainly a store of SrcReg to [StackSlot].  Mark
791             // this as a potentially dead store in case there is a subsequent
792             // store into the stack slot without a read from it.
793             MaybeDeadStores[StackSlot] = &MI;
794
795             // If the stack slot value was previously available in some other
796             // register, change it now.  Otherwise, make the register available,
797             // in PhysReg.
798             Spills.addAvailable(StackSlot, SrcReg, false /*don't clobber*/);
799           }
800         }
801       }
802     }
803
804     // Process all of the spilled defs.
805     for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
806       MachineOperand &MO = MI.getOperand(i);
807       if (MO.isRegister() && MO.getReg() && MO.isDef()) {
808         unsigned VirtReg = MO.getReg();
809
810         if (!MRegisterInfo::isVirtualRegister(VirtReg)) {
811           // Check to see if this is a noop copy.  If so, eliminate the
812           // instruction before considering the dest reg to be changed.
813           unsigned Src, Dst;
814           if (TII->isMoveInstr(MI, Src, Dst) && Src == Dst) {
815             ++NumDCE;
816             DEBUG(std::cerr << "Removing now-noop copy: " << MI);
817             MBB.erase(&MI);
818             VRM.RemoveFromFoldedVirtMap(&MI);
819             goto ProcessNextInst;
820           }
821           
822           // If it's not a no-op copy, it clobbers the value in the destreg.
823           Spills.ClobberPhysReg(VirtReg);
824           ReusedOperands.markClobbered(VirtReg);
825  
826           // Check to see if this instruction is a load from a stack slot into
827           // a register.  If so, this provides the stack slot value in the reg.
828           int FrameIdx;
829           if (unsigned DestReg = TII->isLoadFromStackSlot(&MI, FrameIdx)) {
830             assert(DestReg == VirtReg && "Unknown load situation!");
831             
832             // Otherwise, if it wasn't available, remember that it is now!
833             Spills.addAvailable(FrameIdx, DestReg);
834             goto ProcessNextInst;
835           }
836             
837           continue;
838         }
839
840         // The only vregs left are stack slot definitions.
841         int StackSlot = VRM.getStackSlot(VirtReg);
842         const TargetRegisterClass *RC =
843           MBB.getParent()->getSSARegMap()->getRegClass(VirtReg);
844
845         // If this def is part of a two-address operand, make sure to execute
846         // the store from the correct physical register.
847         unsigned PhysReg;
848         int TiedOp = TII->findTiedToSrcOperand(MI.getOpcode(), i);
849         if (TiedOp != -1)
850           PhysReg = MI.getOperand(TiedOp).getReg();
851         else {
852           PhysReg = VRM.getPhys(VirtReg);
853           if (ReusedOperands.isClobbered(PhysReg)) {
854             // Another def has taken the assigned physreg. It must have been a
855             // use&def which got it due to reuse. Undo the reuse!
856             PhysReg = ReusedOperands.GetRegForReload(PhysReg, &MI, 
857                                                      Spills, MaybeDeadStores);
858           }
859         }
860
861         PhysRegsUsed[PhysReg] = true;
862         ReusedOperands.markClobbered(PhysReg);
863         MRI->storeRegToStackSlot(MBB, next(MII), PhysReg, StackSlot, RC);
864         DEBUG(std::cerr << "Store:\t" << *next(MII));
865         MI.getOperand(i).setReg(PhysReg);
866
867         // Check to see if this is a noop copy.  If so, eliminate the
868         // instruction before considering the dest reg to be changed.
869         {
870           unsigned Src, Dst;
871           if (TII->isMoveInstr(MI, Src, Dst) && Src == Dst) {
872             ++NumDCE;
873             DEBUG(std::cerr << "Removing now-noop copy: " << MI);
874             MBB.erase(&MI);
875             VRM.RemoveFromFoldedVirtMap(&MI);
876             goto ProcessNextInst;
877           }
878         }
879         
880         // If there is a dead store to this stack slot, nuke it now.
881         MachineInstr *&LastStore = MaybeDeadStores[StackSlot];
882         if (LastStore) {
883           DEBUG(std::cerr << "Removed dead store:\t" << *LastStore);
884           ++NumDSE;
885           MBB.erase(LastStore);
886           VRM.RemoveFromFoldedVirtMap(LastStore);
887         }
888         LastStore = next(MII);
889
890         // If the stack slot value was previously available in some other
891         // register, change it now.  Otherwise, make the register available,
892         // in PhysReg.
893         Spills.ModifyStackSlot(StackSlot);
894         Spills.ClobberPhysReg(PhysReg);
895         Spills.addAvailable(StackSlot, PhysReg);
896         ++NumStores;
897       }
898     }
899   ProcessNextInst:
900     MII = NextMII;
901   }
902 }
903
904
905
906 llvm::Spiller* llvm::createSpiller() {
907   switch (SpillerOpt) {
908   default: assert(0 && "Unreachable!");
909   case local:
910     return new LocalSpiller();
911   case simple:
912     return new SimpleSpiller();
913   }
914 }