Refactor some code from being inline to being out in a new class with methods.
[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 ///
237 /// Note that not all physregs are created equal here.  In particular, some
238 /// physregs are reloads that we are allowed to clobber or ignore at any time.
239 /// Other physregs are values that the register allocated program is using that
240 /// we cannot CHANGE, but we can read if we like.  We keep track of this on a 
241 /// per-stack-slot basis as the low bit in the value of the SpillSlotsAvailable
242 /// entries.  The predicate 'canClobberPhysReg()' checks this bit and
243 /// addAvailable sets it if.
244 class AvailableSpills {
245   const MRegisterInfo *MRI;
246   const TargetInstrInfo *TII;
247
248   // SpillSlotsAvailable - This map keeps track of all of the spilled virtual
249   // register values that are still available, due to being loaded or stored to,
250   // but not invalidated yet.
251   std::map<int, unsigned> SpillSlotsAvailable;
252     
253   // PhysRegsAvailable - This is the inverse of SpillSlotsAvailable, indicating
254   // which stack slot values are currently held by a physreg.  This is used to
255   // invalidate entries in SpillSlotsAvailable when a physreg is modified.
256   std::multimap<unsigned, int> PhysRegsAvailable;
257   
258   void ClobberPhysRegOnly(unsigned PhysReg);
259 public:
260   AvailableSpills(const MRegisterInfo *mri, const TargetInstrInfo *tii)
261     : MRI(mri), TII(tii) {
262   }
263   
264   /// getSpillSlotPhysReg - If the specified stack slot is available in a 
265   /// physical register, return that PhysReg, otherwise return 0.
266   unsigned getSpillSlotPhysReg(int Slot) const {
267     std::map<int, unsigned>::const_iterator I = SpillSlotsAvailable.find(Slot);
268     if (I != SpillSlotsAvailable.end())
269       return I->second >> 1;  // Remove the CanClobber bit.
270     return 0;
271   }
272   
273   const MRegisterInfo *getRegInfo() const { return MRI; }
274
275   /// addAvailable - Mark that the specified stack slot is available in the
276   /// specified physreg.  If CanClobber is true, the physreg can be modified at
277   /// any time without changing the semantics of the program.
278   void addAvailable(int Slot, unsigned Reg, bool CanClobber = true) {
279     // If this stack slot is thought to be available in some other physreg, 
280     // remove its record.
281     ModifyStackSlot(Slot);
282     
283     PhysRegsAvailable.insert(std::make_pair(Reg, Slot));
284     SpillSlotsAvailable[Slot] = (Reg << 1) | (unsigned)CanClobber;
285   
286     DEBUG(std::cerr << "Remembering SS#" << Slot << " in physreg "
287                     << MRI->getName(Reg) << "\n");
288   }
289   
290   /// canClobberPhysReg - Return true if the spiller is allowed to change the 
291   /// value of the specified stackslot register if it desires.  The specified
292   /// stack slot must be available in a physreg for this query to make sense.
293   bool canClobberPhysReg(int Slot) const {
294     assert(SpillSlotsAvailable.count(Slot) && "Slot not available!");
295     return SpillSlotsAvailable.find(Slot)->second & 1;
296   }
297   
298   /// ClobberPhysReg - This is called when the specified physreg changes
299   /// value.  We use this to invalidate any info about stuff we thing lives in
300   /// it and any of its aliases.
301   void ClobberPhysReg(unsigned PhysReg);
302
303   /// ModifyStackSlot - This method is called when the value in a stack slot
304   /// changes.  This removes information about which register the previous value
305   /// for this slot lives in (as the previous value is dead now).
306   void ModifyStackSlot(int Slot);
307 };
308
309 /// ClobberPhysRegOnly - This is called when the specified physreg changes
310 /// value.  We use this to invalidate any info about stuff we thing lives in it.
311 void AvailableSpills::ClobberPhysRegOnly(unsigned PhysReg) {
312   std::multimap<unsigned, int>::iterator I =
313     PhysRegsAvailable.lower_bound(PhysReg);
314   while (I != PhysRegsAvailable.end() && I->first == PhysReg) {
315     int Slot = I->second;
316     PhysRegsAvailable.erase(I++);
317     assert((SpillSlotsAvailable[Slot] >> 1) == PhysReg &&
318            "Bidirectional map mismatch!");
319     SpillSlotsAvailable.erase(Slot);
320     DEBUG(std::cerr << "PhysReg " << MRI->getName(PhysReg)
321                     << " clobbered, invalidating SS#" << Slot << "\n");
322   }
323 }
324
325 /// ClobberPhysReg - This is called when the specified physreg changes
326 /// value.  We use this to invalidate any info about stuff we thing lives in
327 /// it and any of its aliases.
328 void AvailableSpills::ClobberPhysReg(unsigned PhysReg) {
329   for (const unsigned *AS = MRI->getAliasSet(PhysReg); *AS; ++AS)
330     ClobberPhysRegOnly(*AS);
331   ClobberPhysRegOnly(PhysReg);
332 }
333
334 /// ModifyStackSlot - This method is called when the value in a stack slot
335 /// changes.  This removes information about which register the previous value
336 /// for this slot lives in (as the previous value is dead now).
337 void AvailableSpills::ModifyStackSlot(int Slot) {
338   std::map<int, unsigned>::iterator It = SpillSlotsAvailable.find(Slot);
339   if (It == SpillSlotsAvailable.end()) return;
340   unsigned Reg = It->second >> 1;
341   SpillSlotsAvailable.erase(It);
342   
343   // This register may hold the value of multiple stack slots, only remove this
344   // stack slot from the set of values the register contains.
345   std::multimap<unsigned, int>::iterator I = PhysRegsAvailable.lower_bound(Reg);
346   for (; ; ++I) {
347     assert(I != PhysRegsAvailable.end() && I->first == Reg &&
348            "Map inverse broken!");
349     if (I->second == Slot) break;
350   }
351   PhysRegsAvailable.erase(I);
352 }
353
354
355
356 // ReusedOp - For each reused operand, we keep track of a bit of information, in
357 // case we need to rollback upon processing a new operand.  See comments below.
358 namespace {
359   struct ReusedOp {
360     // The MachineInstr operand that reused an available value.
361     unsigned Operand;
362
363     // StackSlot - The spill slot of the value being reused.
364     unsigned StackSlot;
365
366     // PhysRegReused - The physical register the value was available in.
367     unsigned PhysRegReused;
368
369     // AssignedPhysReg - The physreg that was assigned for use by the reload.
370     unsigned AssignedPhysReg;
371     
372     // VirtReg - The virtual register itself.
373     unsigned VirtReg;
374
375     ReusedOp(unsigned o, unsigned ss, unsigned prr, unsigned apr,
376              unsigned vreg)
377       : Operand(o), StackSlot(ss), PhysRegReused(prr), AssignedPhysReg(apr),
378       VirtReg(vreg) {}
379   };
380   
381   /// ReuseInfo - This maintains a collection of ReuseOp's for each operand that
382   /// is reused instead of reloaded.
383   class ReuseInfo {
384     MachineInstr &MI;
385     std::vector<ReusedOp> Reuses;
386   public:
387     ReuseInfo(MachineInstr &mi) : MI(mi) {}
388     
389     bool hasReuses() const {
390       return !Reuses.empty();
391     }
392     
393     /// addReuse - If we choose to reuse a virtual register that is already
394     /// available instead of reloading it, remember that we did so.
395     void addReuse(unsigned OpNo, unsigned StackSlot,
396                   unsigned PhysRegReused, unsigned AssignedPhysReg,
397                   unsigned VirtReg) {
398       // If the reload is to the assigned register anyway, no undo will be
399       // required.
400       if (PhysRegReused == AssignedPhysReg) return;
401       
402       // Otherwise, remember this.
403       Reuses.push_back(ReusedOp(OpNo, StackSlot, PhysRegReused, 
404                                 AssignedPhysReg, VirtReg));
405     }
406     
407     /// GetRegForReload - We are about to emit a reload into PhysReg.  If there
408     /// is some other operand that is using the specified register, either pick
409     /// a new register to use, or evict the previous reload and use this reg. 
410     unsigned GetRegForReload(unsigned PhysReg, MachineInstr *MI,
411                              AvailableSpills &Spills,
412                              std::map<int, MachineInstr*> &MaybeDeadStores) {
413       if (Reuses.empty()) return PhysReg;  // This is most often empty.
414
415       for (unsigned ro = 0, e = Reuses.size(); ro != e; ++ro) {
416         ReusedOp &Op = Reuses[ro];
417         // If we find some other reuse that was supposed to use this register
418         // exactly for its reload, we can change this reload to use ITS reload
419         // register.
420         if (Op.PhysRegReused == PhysReg) {
421           // Yup, use the reload register that we didn't use before.
422           return GetRegForReload(Op.AssignedPhysReg, MI, 
423                                  Spills, MaybeDeadStores);
424         } else {
425           // Otherwise, we might also have a problem if a previously reused
426           // value aliases the new register.  If so, codegen the previous reload
427           // and use this one.          
428           unsigned PRRU = Op.PhysRegReused;
429           const MRegisterInfo *MRI = Spills.getRegInfo();
430           if (MRI->areAliases(PRRU, PhysReg)) {
431             // Okay, we found out that an alias of a reused register
432             // was used.  This isn't good because it means we have
433             // to undo a previous reuse.
434             MachineBasicBlock *MBB = MI->getParent();
435             const TargetRegisterClass *AliasRC =
436             MBB->getParent()->getSSARegMap()->getRegClass(Op.VirtReg);
437             MRI->loadRegFromStackSlot(*MBB, MI, Op.AssignedPhysReg,
438                                       Op.StackSlot, AliasRC);
439             Spills.ClobberPhysReg(Op.AssignedPhysReg);
440             Spills.ClobberPhysReg(Op.PhysRegReused);
441             
442             // Any stores to this stack slot are not dead anymore.
443             MaybeDeadStores.erase(Op.StackSlot);
444             
445             MI->SetMachineOperandReg(Op.Operand, Op.AssignedPhysReg);
446             
447             Spills.addAvailable(Op.StackSlot, Op.AssignedPhysReg);
448             ++NumLoads;
449             DEBUG(MachineBasicBlock::iterator MII = MI;
450                   std::cerr << '\t' << *prior(MII));
451             
452             DEBUG(std::cerr << "Reuse undone!\n");
453             Reuses.erase(Reuses.begin()+ro);
454             --NumReused;
455             return PhysReg;
456           }
457         }
458       }
459       return PhysReg;
460     }
461   };
462 }
463
464
465 /// rewriteMBB - Keep track of which spills are available even after the
466 /// register allocator is done with them.  If possible, avoid reloading vregs.
467 void LocalSpiller::RewriteMBB(MachineBasicBlock &MBB, const VirtRegMap &VRM) {
468
469   DEBUG(std::cerr << MBB.getBasicBlock()->getName() << ":\n");
470
471   // Spills - Keep track of which spilled values are available in physregs so
472   // that we can choose to reuse the physregs instead of emitting reloads.
473   AvailableSpills Spills(MRI, TII);
474   
475   // DefAndUseVReg - When we see a def&use operand that is spilled, keep track
476   // of it.  ".first" is the machine operand index (should always be 0 for now),
477   // and ".second" is the virtual register that is spilled.
478   std::vector<std::pair<unsigned, unsigned> > DefAndUseVReg;
479
480   // MaybeDeadStores - When we need to write a value back into a stack slot,
481   // keep track of the inserted store.  If the stack slot value is never read
482   // (because the value was used from some available register, for example), and
483   // subsequently stored to, the original store is dead.  This map keeps track
484   // of inserted stores that are not used.  If we see a subsequent store to the
485   // same stack slot, the original store is deleted.
486   std::map<int, MachineInstr*> MaybeDeadStores;
487
488   bool *PhysRegsUsed = MBB.getParent()->getUsedPhysregs();
489
490   if (MBB.getBasicBlock()->getName() == "endif.3.i")
491     std::cerr << "HERE\n";
492   
493   for (MachineBasicBlock::iterator MII = MBB.begin(), E = MBB.end();
494        MII != E; ) {
495     MachineInstr &MI = *MII;
496     MachineBasicBlock::iterator NextMII = MII; ++NextMII;
497
498     /// ReusedOperands - Keep track of operand reuse in case we need to undo
499     /// reuse.
500     ReuseInfo ReusedOperands(MI);
501     
502     DefAndUseVReg.clear();
503
504     // Process all of the spilled uses and all non spilled reg references.
505     for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
506       MachineOperand &MO = MI.getOperand(i);
507       if (!MO.isRegister() || MO.getReg() == 0)
508         continue;   // Ignore non-register operands.
509       
510       if (MRegisterInfo::isPhysicalRegister(MO.getReg())) {
511         // Ignore physregs for spilling, but remember that it is used by this
512         // function.
513         PhysRegsUsed[MO.getReg()] = true;
514         continue;
515       }
516       
517       assert(MRegisterInfo::isVirtualRegister(MO.getReg()) &&
518              "Not a virtual or a physical register?");
519       
520       unsigned VirtReg = MO.getReg();
521       if (!VRM.hasStackSlot(VirtReg)) {
522         // This virtual register was assigned a physreg!
523         unsigned Phys = VRM.getPhys(VirtReg);
524         PhysRegsUsed[Phys] = true;
525         MI.SetMachineOperandReg(i, Phys);
526         continue;
527       }
528       
529       // This virtual register is now known to be a spilled value.
530       if (!MO.isUse())
531         continue;  // Handle defs in the loop below (handle use&def here though)
532
533       // If this is both a def and a use, we need to emit a store to the
534       // stack slot after the instruction.  Keep track of D&U operands
535       // because we are about to change it to a physreg here.
536       if (MO.isDef()) {
537         // Remember that this was a def-and-use operand, and that the
538         // stack slot is live after this instruction executes.
539         DefAndUseVReg.push_back(std::make_pair(i, VirtReg));
540       }
541       
542       int StackSlot = VRM.getStackSlot(VirtReg);
543       unsigned PhysReg;
544
545       // Check to see if this stack slot is available.
546       if ((PhysReg = Spills.getSpillSlotPhysReg(StackSlot)) &&
547           // Don't reuse it for a def&use operand if we aren't allowed to change
548           // the physreg!
549           (!MO.isDef() || Spills.canClobberPhysReg(StackSlot))) {
550         // If this stack slot value is already available, reuse it!
551         DEBUG(std::cerr << "Reusing SS#" << StackSlot << " from physreg "
552                         << MRI->getName(PhysReg) << " for vreg"
553                         << VirtReg <<" instead of reloading into physreg "
554                         << MRI->getName(VRM.getPhys(VirtReg)) << "\n");
555         MI.SetMachineOperandReg(i, PhysReg);
556
557         // The only technical detail we have is that we don't know that
558         // PhysReg won't be clobbered by a reloaded stack slot that occurs
559         // later in the instruction.  In particular, consider 'op V1, V2'.
560         // If V1 is available in physreg R0, we would choose to reuse it
561         // here, instead of reloading it into the register the allocator
562         // indicated (say R1).  However, V2 might have to be reloaded
563         // later, and it might indicate that it needs to live in R0.  When
564         // this occurs, we need to have information available that
565         // indicates it is safe to use R1 for the reload instead of R0.
566         //
567         // To further complicate matters, we might conflict with an alias,
568         // or R0 and R1 might not be compatible with each other.  In this
569         // case, we actually insert a reload for V1 in R1, ensuring that
570         // we can get at R0 or its alias.
571         ReusedOperands.addReuse(i, StackSlot, PhysReg,
572                                 VRM.getPhys(VirtReg), VirtReg);
573         ++NumReused;
574         continue;
575       }
576       
577       // Otherwise, reload it and remember that we have it.
578       PhysReg = VRM.getPhys(VirtReg);
579       assert(PhysReg && "Must map virtreg to physreg!");
580       const TargetRegisterClass* RC =
581         MBB.getParent()->getSSARegMap()->getRegClass(VirtReg);
582
583       // Note that, if we reused a register for a previous operand, the
584       // register we want to reload into might not actually be
585       // available.  If this occurs, use the register indicated by the
586       // reuser.
587       if (ReusedOperands.hasReuses())
588         PhysReg = ReusedOperands.GetRegForReload(PhysReg, &MI, 
589                                                  Spills, MaybeDeadStores);
590       
591       PhysRegsUsed[PhysReg] = true;
592       MRI->loadRegFromStackSlot(MBB, &MI, PhysReg, StackSlot, RC);
593       // This invalidates PhysReg.
594       Spills.ClobberPhysReg(PhysReg);
595
596       // Any stores to this stack slot are not dead anymore.
597       MaybeDeadStores.erase(StackSlot);
598       Spills.addAvailable(StackSlot, PhysReg);
599       ++NumLoads;
600       MI.SetMachineOperandReg(i, PhysReg);
601       DEBUG(std::cerr << '\t' << *prior(MII));
602     }
603
604     // Loop over all of the implicit defs, clearing them from our available
605     // sets.
606     for (const unsigned *ImpDef = TII->getImplicitDefs(MI.getOpcode());
607          *ImpDef; ++ImpDef) {
608       PhysRegsUsed[*ImpDef] = true;
609       Spills.ClobberPhysReg(*ImpDef);
610     }
611
612     DEBUG(std::cerr << '\t' << MI);
613
614     // If we have folded references to memory operands, make sure we clear all
615     // physical registers that may contain the value of the spilled virtual
616     // register
617     VirtRegMap::MI2VirtMapTy::const_iterator I, End;
618     for (tie(I, End) = VRM.getFoldedVirts(&MI); I != End; ++I) {
619       DEBUG(std::cerr << "Folded vreg: " << I->second.first << "  MR: "
620                       << I->second.second);
621       unsigned VirtReg = I->second.first;
622       VirtRegMap::ModRef MR = I->second.second;
623       if (!VRM.hasStackSlot(VirtReg)) {
624         DEBUG(std::cerr << ": No stack slot!\n");
625         continue;
626       }
627       int SS = VRM.getStackSlot(VirtReg);
628       DEBUG(std::cerr << " - StackSlot: " << SS << "\n");
629       
630       // If this folded instruction is just a use, check to see if it's a
631       // straight load from the virt reg slot.
632       if ((MR & VirtRegMap::isRef) && !(MR & VirtRegMap::isMod)) {
633         int FrameIdx;
634         if (unsigned DestReg = TII->isLoadFromStackSlot(&MI, FrameIdx)) {
635           // If this spill slot is available, turn it into a copy (or nothing)
636           // instead of leaving it as a load!
637           unsigned InReg;
638           if (FrameIdx == SS && (InReg = Spills.getSpillSlotPhysReg(SS))) {
639             DEBUG(std::cerr << "Promoted Load To Copy: " << MI);
640             MachineFunction &MF = *MBB.getParent();
641             if (DestReg != InReg) {
642               MRI->copyRegToReg(MBB, &MI, DestReg, InReg,
643                                 MF.getSSARegMap()->getRegClass(VirtReg));
644               // Revisit the copy so we make sure to notice the effects of the
645               // operation on the destreg (either needing to RA it if it's 
646               // virtual or needing to clobber any values if it's physical).
647               NextMII = &MI;
648               --NextMII;  // backtrack to the copy.
649             }
650             MBB.erase(&MI);
651             goto ProcessNextInst;
652           }
653         }
654       }
655
656       // If this reference is not a use, any previous store is now dead.
657       // Otherwise, the store to this stack slot is not dead anymore.
658       std::map<int, MachineInstr*>::iterator MDSI = MaybeDeadStores.find(SS);
659       if (MDSI != MaybeDeadStores.end()) {
660         if (MR & VirtRegMap::isRef)   // Previous store is not dead.
661           MaybeDeadStores.erase(MDSI);
662         else {
663           // If we get here, the store is dead, nuke it now.
664           assert(MR == VirtRegMap::isMod && "Can't be modref!");
665           MBB.erase(MDSI->second);
666           MaybeDeadStores.erase(MDSI);
667           ++NumDSE;
668         }
669       }
670
671       // If the spill slot value is available, and this is a new definition of
672       // the value, the value is not available anymore.
673       if (MR & VirtRegMap::isMod) {
674         // Notice that the value in this stack slot has been modified.
675         Spills.ModifyStackSlot(SS);
676         
677         // If this is *just* a mod of the value, check to see if this is just a
678         // store to the spill slot (i.e. the spill got merged into the copy). If
679         // so, realize that the vreg is available now, and add the store to the
680         // MaybeDeadStore info.
681         int StackSlot;
682         if (!(MR & VirtRegMap::isRef)) {
683           if (unsigned SrcReg = TII->isStoreToStackSlot(&MI, StackSlot)) {
684             assert(MRegisterInfo::isPhysicalRegister(SrcReg) &&
685                    "Src hasn't been allocated yet?");
686             // Okay, this is certainly a store of SrcReg to [StackSlot].  Mark
687             // this as a potentially dead store in case there is a subsequent
688             // store into the stack slot without a read from it.
689             MaybeDeadStores[StackSlot] = &MI;
690
691             // If the stack slot value was previously available in some other
692             // register, change it now.  Otherwise, make the register available,
693             // in PhysReg.
694             Spills.addAvailable(StackSlot, SrcReg, false /*don't clobber*/);
695           }
696         }
697       }
698     }
699
700     // Process all of the spilled defs.
701     for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
702       MachineOperand &MO = MI.getOperand(i);
703       if (MO.isRegister() && MO.getReg() && MO.isDef()) {
704         unsigned VirtReg = MO.getReg();
705
706         if (!MRegisterInfo::isVirtualRegister(VirtReg)) {
707           // Check to see if this is a def-and-use vreg operand that we do need
708           // to insert a store for.
709           bool OpTakenCareOf = false;
710           if (MO.isUse() && !DefAndUseVReg.empty()) {
711             for (unsigned dau = 0, e = DefAndUseVReg.size(); dau != e; ++dau)
712               if (DefAndUseVReg[dau].first == i) {
713                 VirtReg = DefAndUseVReg[dau].second;
714                 OpTakenCareOf = true;
715                 break;
716               }
717           }
718
719           if (!OpTakenCareOf) {
720             // Check to see if this is a noop copy.  If so, eliminate the
721             // instruction before considering the dest reg to be changed.
722             unsigned Src, Dst;
723             if (TII->isMoveInstr(MI, Src, Dst) && Src == Dst) {
724               ++NumDCE;
725               DEBUG(std::cerr << "Removing now-noop copy: " << MI);
726               MBB.erase(&MI);
727               goto ProcessNextInst;
728             }
729             Spills.ClobberPhysReg(VirtReg);
730             continue;
731           }
732         }
733
734         // The only vregs left are stack slot definitions.
735         int StackSlot = VRM.getStackSlot(VirtReg);
736         const TargetRegisterClass *RC =
737           MBB.getParent()->getSSARegMap()->getRegClass(VirtReg);
738         unsigned PhysReg;
739
740         // If this is a def&use operand, and we used a different physreg for
741         // it than the one assigned, make sure to execute the store from the
742         // correct physical register.
743         if (MO.getReg() == VirtReg)
744           PhysReg = VRM.getPhys(VirtReg);
745         else
746           PhysReg = MO.getReg();
747
748         PhysRegsUsed[PhysReg] = true;
749         MRI->storeRegToStackSlot(MBB, next(MII), PhysReg, StackSlot, RC);
750         DEBUG(std::cerr << "Store:\t" << *next(MII));
751         MI.SetMachineOperandReg(i, PhysReg);
752
753         // Check to see if this is a noop copy.  If so, eliminate the
754         // instruction before considering the dest reg to be changed.
755         {
756           unsigned Src, Dst;
757           if (TII->isMoveInstr(MI, Src, Dst) && Src == Dst) {
758             ++NumDCE;
759             DEBUG(std::cerr << "Removing now-noop copy: " << MI);
760             MBB.erase(&MI);
761             goto ProcessNextInst;
762           }
763         }
764         
765         // If there is a dead store to this stack slot, nuke it now.
766         MachineInstr *&LastStore = MaybeDeadStores[StackSlot];
767         if (LastStore) {
768           DEBUG(std::cerr << " Killed store:\t" << *LastStore);
769           ++NumDSE;
770           MBB.erase(LastStore);
771         }
772         LastStore = next(MII);
773
774         // If the stack slot value was previously available in some other
775         // register, change it now.  Otherwise, make the register available,
776         // in PhysReg.
777         Spills.ModifyStackSlot(StackSlot);
778         Spills.ClobberPhysReg(PhysReg);
779         Spills.addAvailable(StackSlot, PhysReg);
780         ++NumStores;
781       }
782     }
783   ProcessNextInst:
784     MII = NextMII;
785   }
786 }
787
788
789
790 llvm::Spiller* llvm::createSpiller() {
791   switch (SpillerOpt) {
792   default: assert(0 && "Unreachable!");
793   case local:
794     return new LocalSpiller();
795   case simple:
796     return new SimpleSpiller();
797   }
798 }