significantly simplify the VirtRegMap code by pulling the SpillSlotsAvailable
[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/ADT/Statistic.h"
30 #include "llvm/ADT/STLExtras.h"
31 #include <algorithm>
32 #include <iostream>
33 using namespace llvm;
34
35 namespace {
36   Statistic<> NumSpills("spiller", "Number of register spills");
37   Statistic<> NumStores("spiller", "Number of stores added");
38   Statistic<> NumLoads ("spiller", "Number of loads added");
39   Statistic<> NumReused("spiller", "Number of values reused");
40   Statistic<> NumDSE   ("spiller", "Number of dead stores elided");
41   Statistic<> NumDCE   ("spiller", "Number of copies elided");
42
43   enum SpillerName { simple, local };
44
45   cl::opt<SpillerName>
46   SpillerOpt("spiller",
47              cl::desc("Spiller to use: (default: local)"),
48              cl::Prefix,
49              cl::values(clEnumVal(simple, "  simple spiller"),
50                         clEnumVal(local,  "  local spiller"),
51                         clEnumValEnd),
52              cl::init(local));
53 }
54
55 //===----------------------------------------------------------------------===//
56 //  VirtRegMap implementation
57 //===----------------------------------------------------------------------===//
58
59 void VirtRegMap::grow() {
60   Virt2PhysMap.grow(MF.getSSARegMap()->getLastVirtReg());
61   Virt2StackSlotMap.grow(MF.getSSARegMap()->getLastVirtReg());
62 }
63
64 int VirtRegMap::assignVirt2StackSlot(unsigned virtReg) {
65   assert(MRegisterInfo::isVirtualRegister(virtReg));
66   assert(Virt2StackSlotMap[virtReg] == NO_STACK_SLOT &&
67          "attempt to assign stack slot to already spilled register");
68   const TargetRegisterClass* RC = MF.getSSARegMap()->getRegClass(virtReg);
69   int frameIndex = MF.getFrameInfo()->CreateStackObject(RC->getSize(),
70                                                         RC->getAlignment());
71   Virt2StackSlotMap[virtReg] = frameIndex;
72   ++NumSpills;
73   return frameIndex;
74 }
75
76 void VirtRegMap::assignVirt2StackSlot(unsigned virtReg, int frameIndex) {
77   assert(MRegisterInfo::isVirtualRegister(virtReg));
78   assert(Virt2StackSlotMap[virtReg] == NO_STACK_SLOT &&
79          "attempt to assign stack slot to already spilled register");
80   Virt2StackSlotMap[virtReg] = frameIndex;
81 }
82
83 void VirtRegMap::virtFolded(unsigned VirtReg, MachineInstr *OldMI,
84                             unsigned OpNo, MachineInstr *NewMI) {
85   // Move previous memory references folded to new instruction.
86   MI2VirtMapTy::iterator IP = MI2VirtMap.lower_bound(NewMI);
87   for (MI2VirtMapTy::iterator I = MI2VirtMap.lower_bound(OldMI),
88          E = MI2VirtMap.end(); I != E && I->first == OldMI; ) {
89     MI2VirtMap.insert(IP, std::make_pair(NewMI, I->second));
90     MI2VirtMap.erase(I++);
91   }
92
93   ModRef MRInfo;
94   if (!OldMI->getOperand(OpNo).isDef()) {
95     assert(OldMI->getOperand(OpNo).isUse() && "Operand is not use or def?");
96     MRInfo = isRef;
97   } else {
98     MRInfo = OldMI->getOperand(OpNo).isUse() ? isModRef : isMod;
99   }
100
101   // add new memory reference
102   MI2VirtMap.insert(IP, std::make_pair(NewMI, std::make_pair(VirtReg, MRInfo)));
103 }
104
105 void VirtRegMap::print(std::ostream &OS) const {
106   const MRegisterInfo* MRI = MF.getTarget().getRegisterInfo();
107
108   OS << "********** REGISTER MAP **********\n";
109   for (unsigned i = MRegisterInfo::FirstVirtualRegister,
110          e = MF.getSSARegMap()->getLastVirtReg(); i <= e; ++i) {
111     if (Virt2PhysMap[i] != (unsigned)VirtRegMap::NO_PHYS_REG)
112       OS << "[reg" << i << " -> " << MRI->getName(Virt2PhysMap[i]) << "]\n";
113
114   }
115
116   for (unsigned i = MRegisterInfo::FirstVirtualRegister,
117          e = MF.getSSARegMap()->getLastVirtReg(); i <= e; ++i)
118     if (Virt2StackSlotMap[i] != VirtRegMap::NO_STACK_SLOT)
119       OS << "[reg" << i << " -> fi#" << Virt2StackSlotMap[i] << "]\n";
120   OS << '\n';
121 }
122
123 void VirtRegMap::dump() const { print(std::cerr); }
124
125
126 //===----------------------------------------------------------------------===//
127 // Simple Spiller Implementation
128 //===----------------------------------------------------------------------===//
129
130 Spiller::~Spiller() {}
131
132 namespace {
133   struct SimpleSpiller : public Spiller {
134     bool runOnMachineFunction(MachineFunction& mf, const VirtRegMap &VRM);
135   };
136 }
137
138 bool SimpleSpiller::runOnMachineFunction(MachineFunction &MF,
139                                          const VirtRegMap &VRM) {
140   DEBUG(std::cerr << "********** REWRITE MACHINE CODE **********\n");
141   DEBUG(std::cerr << "********** Function: "
142                   << MF.getFunction()->getName() << '\n');
143   const TargetMachine &TM = MF.getTarget();
144   const MRegisterInfo &MRI = *TM.getRegisterInfo();
145   bool *PhysRegsUsed = MF.getUsedPhysregs();
146
147   // LoadedRegs - Keep track of which vregs are loaded, so that we only load
148   // each vreg once (in the case where a spilled vreg is used by multiple
149   // operands).  This is always smaller than the number of operands to the
150   // current machine instr, so it should be small.
151   std::vector<unsigned> LoadedRegs;
152
153   for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
154        MBBI != E; ++MBBI) {
155     DEBUG(std::cerr << MBBI->getBasicBlock()->getName() << ":\n");
156     MachineBasicBlock &MBB = *MBBI;
157     for (MachineBasicBlock::iterator MII = MBB.begin(),
158            E = MBB.end(); MII != E; ++MII) {
159       MachineInstr &MI = *MII;
160       for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
161         MachineOperand &MO = MI.getOperand(i);
162         if (MO.isRegister() && MO.getReg())
163           if (MRegisterInfo::isVirtualRegister(MO.getReg())) {
164             unsigned VirtReg = MO.getReg();
165             unsigned PhysReg = VRM.getPhys(VirtReg);
166             if (VRM.hasStackSlot(VirtReg)) {
167               int StackSlot = VRM.getStackSlot(VirtReg);
168               const TargetRegisterClass* RC =
169                 MF.getSSARegMap()->getRegClass(VirtReg);
170
171               if (MO.isUse() &&
172                   std::find(LoadedRegs.begin(), LoadedRegs.end(), VirtReg)
173                   == LoadedRegs.end()) {
174                 MRI.loadRegFromStackSlot(MBB, &MI, PhysReg, StackSlot, RC);
175                 LoadedRegs.push_back(VirtReg);
176                 ++NumLoads;
177                 DEBUG(std::cerr << '\t' << *prior(MII));
178               }
179
180               if (MO.isDef()) {
181                 MRI.storeRegToStackSlot(MBB, next(MII), PhysReg, StackSlot, RC);
182                 ++NumStores;
183               }
184             }
185             PhysRegsUsed[PhysReg] = true;
186             MI.SetMachineOperandReg(i, PhysReg);
187           } else {
188             PhysRegsUsed[MO.getReg()] = true;
189           }
190       }
191
192       DEBUG(std::cerr << '\t' << MI);
193       LoadedRegs.clear();
194     }
195   }
196   return true;
197 }
198
199 //===----------------------------------------------------------------------===//
200 //  Local Spiller Implementation
201 //===----------------------------------------------------------------------===//
202
203 namespace {
204   /// LocalSpiller - This spiller does a simple pass over the machine basic
205   /// block to attempt to keep spills in registers as much as possible for
206   /// blocks that have low register pressure (the vreg may be spilled due to
207   /// register pressure in other blocks).
208   class LocalSpiller : public Spiller {
209     const MRegisterInfo *MRI;
210     const TargetInstrInfo *TII;
211   public:
212     bool runOnMachineFunction(MachineFunction &MF, const VirtRegMap &VRM) {
213       MRI = MF.getTarget().getRegisterInfo();
214       TII = MF.getTarget().getInstrInfo();
215       DEBUG(std::cerr << "\n**** Local spiller rewriting function '"
216                       << MF.getFunction()->getName() << "':\n");
217
218       for (MachineFunction::iterator MBB = MF.begin(), E = MF.end();
219            MBB != E; ++MBB)
220         RewriteMBB(*MBB, VRM);
221       return true;
222     }
223   private:
224     void RewriteMBB(MachineBasicBlock &MBB, const VirtRegMap &VRM);
225     void ClobberPhysReg(unsigned PR, std::map<int, unsigned> &SpillSlots,
226                         std::multimap<unsigned, int> &PhysRegs);
227     void ClobberPhysRegOnly(unsigned PR, std::map<int, unsigned> &SpillSlots,
228                             std::multimap<unsigned, int> &PhysRegs);
229     void ModifyStackSlot(int Slot, std::map<int, unsigned> &SpillSlots,
230                          std::multimap<unsigned, int> &PhysRegs);
231   };
232 }
233
234 /// AvailableSpills - As the local spiller is scanning and rewriting an MBB from
235 /// top down, keep track of which spills slots are available in each register.
236 class AvailableSpills {
237   const MRegisterInfo *MRI;
238   const TargetInstrInfo *TII;
239
240   // SpillSlotsAvailable - This map keeps track of all of the spilled virtual
241   // register values that are still available, due to being loaded or stored to,
242   // but not invalidated yet.
243   std::map<int, unsigned> SpillSlotsAvailable;
244     
245   // PhysRegsAvailable - This is the inverse of SpillSlotsAvailable, indicating
246   // which stack slot values are currently held by a physreg.  This is used to
247   // invalidate entries in SpillSlotsAvailable when a physreg is modified.
248   std::multimap<unsigned, int> PhysRegsAvailable;
249   
250   void ClobberPhysRegOnly(unsigned PhysReg);
251 public:
252   AvailableSpills(const MRegisterInfo *mri, const TargetInstrInfo *tii)
253     : MRI(mri), TII(tii) {
254   }
255   
256   /// getSpillSlotPhysReg - If the specified stack slot is available in a 
257   /// physical register, return that PhysReg, otherwise return 0.
258   unsigned getSpillSlotPhysReg(int Slot) const {
259     std::map<int, unsigned>::const_iterator I = SpillSlotsAvailable.find(Slot);
260     if (I != SpillSlotsAvailable.end())
261       return I->second;
262     return 0;
263   }
264
265   /// addAvailable - Mark that the specified stack slot is available in the
266   /// specified physreg.
267   void addAvailable(int Slot, unsigned Reg) {
268     PhysRegsAvailable.insert(std::make_pair(Reg, Slot));
269     SpillSlotsAvailable[Slot] = Reg;
270   
271     DEBUG(std::cerr << "Remembering SS#" << Slot << " in physreg "
272                     << MRI->getName(Reg) << "\n");
273   }
274   
275   
276   /// ClobberPhysReg - This is called when the specified physreg changes
277   /// value.  We use this to invalidate any info about stuff we thing lives in
278   /// it and any of its aliases.
279   void ClobberPhysReg(unsigned PhysReg);
280
281   /// ModifyStackSlot - This method is called when the value in a stack slot
282   /// changes.  This removes information about which register the previous value
283   /// for this slot lives in (as the previous value is dead now).
284   void ModifyStackSlot(int Slot);
285 };
286
287 /// ClobberPhysRegOnly - This is called when the specified physreg changes
288 /// value.  We use this to invalidate any info about stuff we thing lives in it.
289 void AvailableSpills::ClobberPhysRegOnly(unsigned PhysReg) {
290   std::multimap<unsigned, int>::iterator I =
291     PhysRegsAvailable.lower_bound(PhysReg);
292   while (I != PhysRegsAvailable.end() && I->first == PhysReg) {
293     int Slot = I->second;
294     PhysRegsAvailable.erase(I++);
295     assert(SpillSlotsAvailable[Slot] == PhysReg &&
296            "Bidirectional map mismatch!");
297     SpillSlotsAvailable.erase(Slot);
298     DEBUG(std::cerr << "PhysReg " << MRI->getName(PhysReg)
299                     << " clobbered, invalidating SS#" << Slot << "\n");
300   }
301 }
302
303 /// ClobberPhysReg - This is called when the specified physreg changes
304 /// value.  We use this to invalidate any info about stuff we thing lives in
305 /// it and any of its aliases.
306 void AvailableSpills::ClobberPhysReg(unsigned PhysReg) {
307   for (const unsigned *AS = MRI->getAliasSet(PhysReg); *AS; ++AS)
308     ClobberPhysRegOnly(*AS);
309   ClobberPhysRegOnly(PhysReg);
310 }
311
312 /// ModifyStackSlot - This method is called when the value in a stack slot
313 /// changes.  This removes information about which register the previous value
314 /// for this slot lives in (as the previous value is dead now).
315 void AvailableSpills::ModifyStackSlot(int Slot) {
316   std::map<int, unsigned>::iterator It = SpillSlotsAvailable.find(Slot);
317   if (It == SpillSlotsAvailable.end()) return;
318   unsigned Reg = It->second;
319   SpillSlotsAvailable.erase(It);
320   
321   // This register may hold the value of multiple stack slots, only remove this
322   // stack slot from the set of values the register contains.
323   std::multimap<unsigned, int>::iterator I = PhysRegsAvailable.lower_bound(Reg);
324   for (; ; ++I) {
325     assert(I != PhysRegsAvailable.end() && I->first == Reg &&
326            "Map inverse broken!");
327     if (I->second == Slot) break;
328   }
329   PhysRegsAvailable.erase(I);
330 }
331
332
333
334 // ReusedOp - For each reused operand, we keep track of a bit of information, in
335 // case we need to rollback upon processing a new operand.  See comments below.
336 namespace {
337   struct ReusedOp {
338     // The MachineInstr operand that reused an available value.
339     unsigned Operand;
340
341     // StackSlot - The spill slot of the value being reused.
342     unsigned StackSlot;
343
344     // PhysRegReused - The physical register the value was available in.
345     unsigned PhysRegReused;
346
347     // AssignedPhysReg - The physreg that was assigned for use by the reload.
348     unsigned AssignedPhysReg;
349     
350     // VirtReg - The virtual register itself.
351     unsigned VirtReg;
352
353     ReusedOp(unsigned o, unsigned ss, unsigned prr, unsigned apr,
354              unsigned vreg)
355       : Operand(o), StackSlot(ss), PhysRegReused(prr), AssignedPhysReg(apr),
356       VirtReg(vreg) {}
357   };
358 }
359
360
361 /// rewriteMBB - Keep track of which spills are available even after the
362 /// register allocator is done with them.  If possible, avoid reloading vregs.
363 void LocalSpiller::RewriteMBB(MachineBasicBlock &MBB, const VirtRegMap &VRM) {
364
365   DEBUG(std::cerr << MBB.getBasicBlock()->getName() << ":\n");
366
367   // Spills - Keep track of which spilled values are available in physregs so
368   // that we can choose to reuse the physregs instead of emitting reloads.
369   AvailableSpills Spills(MRI, TII);
370   
371   std::vector<ReusedOp> ReusedOperands;
372
373   // DefAndUseVReg - When we see a def&use operand that is spilled, keep track
374   // of it.  ".first" is the machine operand index (should always be 0 for now),
375   // and ".second" is the virtual register that is spilled.
376   std::vector<std::pair<unsigned, unsigned> > DefAndUseVReg;
377
378   // MaybeDeadStores - When we need to write a value back into a stack slot,
379   // keep track of the inserted store.  If the stack slot value is never read
380   // (because the value was used from some available register, for example), and
381   // subsequently stored to, the original store is dead.  This map keeps track
382   // of inserted stores that are not used.  If we see a subsequent store to the
383   // same stack slot, the original store is deleted.
384   std::map<int, MachineInstr*> MaybeDeadStores;
385
386   bool *PhysRegsUsed = MBB.getParent()->getUsedPhysregs();
387
388   for (MachineBasicBlock::iterator MII = MBB.begin(), E = MBB.end();
389        MII != E; ) {
390     MachineInstr &MI = *MII;
391     MachineBasicBlock::iterator NextMII = MII; ++NextMII;
392
393     ReusedOperands.clear();
394     DefAndUseVReg.clear();
395
396     // Process all of the spilled uses and all non spilled reg references.
397     for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
398       MachineOperand &MO = MI.getOperand(i);
399       if (!MO.isRegister() || MO.getReg() == 0)
400         continue;   // Ignore non-register operands.
401       
402       if (MRegisterInfo::isPhysicalRegister(MO.getReg())) {
403         // Ignore physregs for spilling, but remember that it is used by this
404         // function.
405         PhysRegsUsed[MO.getReg()] = true;
406         continue;
407       }
408       
409       assert(MRegisterInfo::isVirtualRegister(MO.getReg()) &&
410              "Not a virtual or a physical register?");
411       
412       unsigned VirtReg = MO.getReg();
413       if (!VRM.hasStackSlot(VirtReg)) {
414         // This virtual register was assigned a physreg!
415         unsigned Phys = VRM.getPhys(VirtReg);
416         PhysRegsUsed[Phys] = true;
417         MI.SetMachineOperandReg(i, Phys);
418         continue;
419       }
420       
421       // This virtual register is now known to be a spilled value.
422       if (!MO.isUse())
423         continue;  // Handle defs in the loop below (handle use&def here though)
424
425       // If this is both a def and a use, we need to emit a store to the
426       // stack slot after the instruction.  Keep track of D&U operands
427       // because we are about to change it to a physreg here.
428       if (MO.isDef()) {
429         // Remember that this was a def-and-use operand, and that the
430         // stack slot is live after this instruction executes.
431         DefAndUseVReg.push_back(std::make_pair(i, VirtReg));
432       }
433       
434       int StackSlot = VRM.getStackSlot(VirtReg);
435       unsigned PhysReg;
436
437       // Check to see if this stack slot is available.
438       if ((PhysReg = Spills.getSpillSlotPhysReg(StackSlot))) {
439         // If this stack slot value is already available, reuse it!
440         DEBUG(std::cerr << "Reusing SS#" << StackSlot << " from physreg "
441                         << MRI->getName(PhysReg) << " for vreg"
442                         << VirtReg <<" instead of reloading into physreg "
443                         << MRI->getName(VRM.getPhys(VirtReg)) << "\n");
444         MI.SetMachineOperandReg(i, PhysReg);
445
446         // The only technical detail we have is that we don't know that
447         // PhysReg won't be clobbered by a reloaded stack slot that occurs
448         // later in the instruction.  In particular, consider 'op V1, V2'.
449         // If V1 is available in physreg R0, we would choose to reuse it
450         // here, instead of reloading it into the register the allocator
451         // indicated (say R1).  However, V2 might have to be reloaded
452         // later, and it might indicate that it needs to live in R0.  When
453         // this occurs, we need to have information available that
454         // indicates it is safe to use R1 for the reload instead of R0.
455         //
456         // To further complicate matters, we might conflict with an alias,
457         // or R0 and R1 might not be compatible with each other.  In this
458         // case, we actually insert a reload for V1 in R1, ensuring that
459         // we can get at R0 or its alias.
460         ReusedOperands.push_back(ReusedOp(i, StackSlot, PhysReg,
461                                           VRM.getPhys(VirtReg), VirtReg));
462         ++NumReused;
463         continue;
464       }
465       
466       // Otherwise, reload it and remember that we have it.
467       PhysReg = VRM.getPhys(VirtReg);
468       assert(PhysReg && "Must map virtreg to physreg!");
469       const TargetRegisterClass* RC =
470         MBB.getParent()->getSSARegMap()->getRegClass(VirtReg);
471
472     RecheckRegister:
473       // Note that, if we reused a register for a previous operand, the
474       // register we want to reload into might not actually be
475       // available.  If this occurs, use the register indicated by the
476       // reuser.
477       if (!ReusedOperands.empty())   // This is most often empty.
478         for (unsigned ro = 0, e = ReusedOperands.size(); ro != e; ++ro)
479           if (ReusedOperands[ro].PhysRegReused == PhysReg) {
480             // Yup, use the reload register that we didn't use before.
481             PhysReg = ReusedOperands[ro].AssignedPhysReg;
482             goto RecheckRegister;
483           } else {
484             ReusedOp &Op = ReusedOperands[ro];
485             unsigned PRRU = Op.PhysRegReused;
486             if (MRI->areAliases(PRRU, PhysReg)) {
487               // Okay, we found out that an alias of a reused register
488               // was used.  This isn't good because it means we have
489               // to undo a previous reuse.
490               const TargetRegisterClass *AliasRC =
491                 MBB.getParent()->getSSARegMap()->getRegClass(Op.VirtReg);
492               MRI->loadRegFromStackSlot(MBB, &MI, Op.AssignedPhysReg,
493                                         Op.StackSlot, AliasRC);
494               Spills.ClobberPhysReg(Op.AssignedPhysReg);
495               Spills.ClobberPhysReg(Op.PhysRegReused);
496               
497               // Any stores to this stack slot are not dead anymore.
498               MaybeDeadStores.erase(Op.StackSlot);
499
500               MI.SetMachineOperandReg(Op.Operand, Op.AssignedPhysReg);
501               
502               Spills.addAvailable(Op.StackSlot, Op.AssignedPhysReg);
503               ++NumLoads;
504               DEBUG(std::cerr << '\t' << *prior(MII));
505
506               DEBUG(std::cerr << "Reuse undone!\n");
507               ReusedOperands.erase(ReusedOperands.begin()+ro);
508               --NumReused;
509               goto ContinueReload;
510             }
511           }
512     ContinueReload:
513       PhysRegsUsed[PhysReg] = true;
514       MRI->loadRegFromStackSlot(MBB, &MI, PhysReg, StackSlot, RC);
515       // This invalidates PhysReg.
516       Spills.ClobberPhysReg(PhysReg);
517
518       // Any stores to this stack slot are not dead anymore.
519       MaybeDeadStores.erase(StackSlot);
520       Spills.addAvailable(StackSlot, PhysReg);
521       ++NumLoads;
522       MI.SetMachineOperandReg(i, PhysReg);
523       DEBUG(std::cerr << '\t' << *prior(MII));
524     }
525
526     // Loop over all of the implicit defs, clearing them from our available
527     // sets.
528     for (const unsigned *ImpDef = TII->getImplicitDefs(MI.getOpcode());
529          *ImpDef; ++ImpDef) {
530       PhysRegsUsed[*ImpDef] = true;
531       Spills.ClobberPhysReg(*ImpDef);
532     }
533
534     DEBUG(std::cerr << '\t' << MI);
535
536     // If we have folded references to memory operands, make sure we clear all
537     // physical registers that may contain the value of the spilled virtual
538     // register
539     VirtRegMap::MI2VirtMapTy::const_iterator I, End;
540     for (tie(I, End) = VRM.getFoldedVirts(&MI); I != End; ++I) {
541       DEBUG(std::cerr << "Folded vreg: " << I->second.first << "  MR: "
542                       << I->second.second);
543       unsigned VirtReg = I->second.first;
544       VirtRegMap::ModRef MR = I->second.second;
545       if (!VRM.hasStackSlot(VirtReg)) {
546         DEBUG(std::cerr << ": No stack slot!\n");
547         continue;
548       }
549       int SS = VRM.getStackSlot(VirtReg);
550       DEBUG(std::cerr << " - StackSlot: " << SS << "\n");
551       
552       // If this folded instruction is just a use, check to see if it's a
553       // straight load from the virt reg slot.
554       if ((MR & VirtRegMap::isRef) && !(MR & VirtRegMap::isMod)) {
555         int FrameIdx;
556         if (unsigned DestReg = TII->isLoadFromStackSlot(&MI, FrameIdx)) {
557           // If this spill slot is available, turn it into a copy (or nothing)
558           // instead of leaving it as a load!
559           unsigned InReg;
560           if (FrameIdx == SS && (InReg = Spills.getSpillSlotPhysReg(SS))) {
561             DEBUG(std::cerr << "Promoted Load To Copy: " << MI);
562             MachineFunction &MF = *MBB.getParent();
563             if (DestReg != InReg) {
564               MRI->copyRegToReg(MBB, &MI, DestReg, InReg,
565                                 MF.getSSARegMap()->getRegClass(VirtReg));
566               // Revisit the copy so we make sure to notice the effects of the
567               // operation on the destreg (either needing to RA it if it's 
568               // virtual or needing to clobber any values if it's physical).
569               NextMII = &MI;
570               --NextMII;  // backtrack to the copy.
571             }
572             MBB.erase(&MI);
573             goto ProcessNextInst;
574           }
575         }
576       }
577
578       // If this reference is not a use, any previous store is now dead.
579       // Otherwise, the store to this stack slot is not dead anymore.
580       std::map<int, MachineInstr*>::iterator MDSI = MaybeDeadStores.find(SS);
581       if (MDSI != MaybeDeadStores.end()) {
582         if (MR & VirtRegMap::isRef)   // Previous store is not dead.
583           MaybeDeadStores.erase(MDSI);
584         else {
585           // If we get here, the store is dead, nuke it now.
586           assert(MR == VirtRegMap::isMod && "Can't be modref!");
587           MBB.erase(MDSI->second);
588           MaybeDeadStores.erase(MDSI);
589           ++NumDSE;
590         }
591       }
592
593       // If the spill slot value is available, and this is a new definition of
594       // the value, the value is not available anymore.
595       if (MR & VirtRegMap::isMod) {
596         // Notice that the value in this stack slot has been modified.
597         Spills.ModifyStackSlot(SS);
598         
599         // If this is *just* a mod of the value, check to see if this is just a
600         // store to the spill slot (i.e. the spill got merged into the copy). If
601         // so, realize that the vreg is available now, and add the store to the
602         // MaybeDeadStore info.
603         int StackSlot;
604         if (!(MR & VirtRegMap::isRef)) {
605           if (unsigned SrcReg = TII->isStoreToStackSlot(&MI, StackSlot)) {
606             assert(MRegisterInfo::isPhysicalRegister(SrcReg) &&
607                    "Src hasn't been allocated yet?");
608             // Okay, this is certainly a store of SrcReg to [StackSlot].  Mark
609             // this as a potentially dead store in case there is a subsequent
610             // store into the stack slot without a read from it.
611             MaybeDeadStores[StackSlot] = &MI;
612
613             // If the stack slot value was previously available in some other
614             // register, change it now.  Otherwise, make the register available,
615             // in PhysReg.
616             Spills.addAvailable(StackSlot, SrcReg);
617           }
618         }
619       }
620     }
621
622     // Process all of the spilled defs.
623     for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
624       MachineOperand &MO = MI.getOperand(i);
625       if (MO.isRegister() && MO.getReg() && MO.isDef()) {
626         unsigned VirtReg = MO.getReg();
627
628         if (!MRegisterInfo::isVirtualRegister(VirtReg)) {
629           // Check to see if this is a def-and-use vreg operand that we do need
630           // to insert a store for.
631           bool OpTakenCareOf = false;
632           if (MO.isUse() && !DefAndUseVReg.empty()) {
633             for (unsigned dau = 0, e = DefAndUseVReg.size(); dau != e; ++dau)
634               if (DefAndUseVReg[dau].first == i) {
635                 VirtReg = DefAndUseVReg[dau].second;
636                 OpTakenCareOf = true;
637                 break;
638               }
639           }
640
641           if (!OpTakenCareOf) {
642             // Check to see if this is a noop copy.  If so, eliminate the
643             // instruction before considering the dest reg to be changed.
644             unsigned Src, Dst;
645             if (TII->isMoveInstr(MI, Src, Dst) && Src == Dst) {
646               ++NumDCE;
647               DEBUG(std::cerr << "Removing now-noop copy: " << MI);
648               MBB.erase(&MI);
649               goto ProcessNextInst;
650             }
651             Spills.ClobberPhysReg(VirtReg);
652             continue;
653           }
654         }
655
656         // The only vregs left are stack slot definitions.
657         int StackSlot = VRM.getStackSlot(VirtReg);
658         const TargetRegisterClass *RC =
659           MBB.getParent()->getSSARegMap()->getRegClass(VirtReg);
660         unsigned PhysReg;
661
662         // If this is a def&use operand, and we used a different physreg for
663         // it than the one assigned, make sure to execute the store from the
664         // correct physical register.
665         if (MO.getReg() == VirtReg)
666           PhysReg = VRM.getPhys(VirtReg);
667         else
668           PhysReg = MO.getReg();
669
670         PhysRegsUsed[PhysReg] = true;
671         MRI->storeRegToStackSlot(MBB, next(MII), PhysReg, StackSlot, RC);
672         DEBUG(std::cerr << "Store:\t" << *next(MII));
673         MI.SetMachineOperandReg(i, PhysReg);
674
675         // Check to see if this is a noop copy.  If so, eliminate the
676         // instruction before considering the dest reg to be changed.
677         {
678           unsigned Src, Dst;
679           if (TII->isMoveInstr(MI, Src, Dst) && Src == Dst) {
680             ++NumDCE;
681             DEBUG(std::cerr << "Removing now-noop copy: " << MI);
682             MBB.erase(&MI);
683             goto ProcessNextInst;
684           }
685         }
686         
687         // If there is a dead store to this stack slot, nuke it now.
688         MachineInstr *&LastStore = MaybeDeadStores[StackSlot];
689         if (LastStore) {
690           DEBUG(std::cerr << " Killed store:\t" << *LastStore);
691           ++NumDSE;
692           MBB.erase(LastStore);
693         }
694         LastStore = next(MII);
695
696         // If the stack slot value was previously available in some other
697         // register, change it now.  Otherwise, make the register available,
698         // in PhysReg.
699         Spills.ModifyStackSlot(StackSlot);
700         Spills.ClobberPhysReg(PhysReg);
701
702         Spills.addAvailable(StackSlot, PhysReg);
703         ++NumStores;
704       }
705     }
706   ProcessNextInst:
707     MII = NextMII;
708   }
709 }
710
711
712
713 llvm::Spiller* llvm::createSpiller() {
714   switch (SpillerOpt) {
715   default: assert(0 && "Unreachable!");
716   case local:
717     return new LocalSpiller();
718   case simple:
719     return new SimpleSpiller();
720   }
721 }