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