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