c1d6ee7ff0c24686aa96fcb752bfaeadfb8c0db8
[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
671           // The only technical detail we have is that we don't know that
672           // PhysReg won't be clobbered by a reloaded stack slot that occurs
673           // later in the instruction.  In particular, consider 'op V1, V2'.
674           // If V1 is available in physreg R0, we would choose to reuse it
675           // here, instead of reloading it into the register the allocator
676           // indicated (say R1).  However, V2 might have to be reloaded
677           // later, and it might indicate that it needs to live in R0.  When
678           // this occurs, we need to have information available that
679           // indicates it is safe to use R1 for the reload instead of R0.
680           //
681           // To further complicate matters, we might conflict with an alias,
682           // or R0 and R1 might not be compatible with each other.  In this
683           // case, we actually insert a reload for V1 in R1, ensuring that
684           // we can get at R0 or its alias.
685           ReusedOperands.addReuse(i, StackSlot, PhysReg,
686                                   VRM.getPhys(VirtReg), VirtReg);
687           if (ti != -1)
688             // Only mark it clobbered if this is a use&def operand.
689             ReusedOperands.markClobbered(PhysReg);
690           ++NumReused;
691           continue;
692         }
693         
694         // Otherwise we have a situation where we have a two-address instruction
695         // whose mod/ref operand needs to be reloaded.  This reload is already
696         // available in some register "PhysReg", but if we used PhysReg as the
697         // operand to our 2-addr instruction, the instruction would modify
698         // PhysReg.  This isn't cool if something later uses PhysReg and expects
699         // to get its initial value.
700         //
701         // To avoid this problem, and to avoid doing a load right after a store,
702         // we emit a copy from PhysReg into the designated register for this
703         // operand.
704         unsigned DesignatedReg = VRM.getPhys(VirtReg);
705         assert(DesignatedReg && "Must map virtreg to physreg!");
706
707         // Note that, if we reused a register for a previous operand, the
708         // register we want to reload into might not actually be
709         // available.  If this occurs, use the register indicated by the
710         // reuser.
711         if (ReusedOperands.hasReuses())
712           DesignatedReg = ReusedOperands.GetRegForReload(DesignatedReg, &MI, 
713                                                       Spills, MaybeDeadStores);
714         
715         // If the mapped designated register is actually the physreg we have
716         // incoming, we don't need to inserted a dead copy.
717         if (DesignatedReg == PhysReg) {
718           // If this stack slot value is already available, reuse it!
719           DOUT << "Reusing SS#" << StackSlot << " from physreg "
720                << MRI->getName(PhysReg) << " for vreg"
721                << VirtReg
722                << " instead of reloading into same physreg.\n";
723           MI.getOperand(i).setReg(PhysReg);
724           ReusedOperands.markClobbered(PhysReg);
725           ++NumReused;
726           continue;
727         }
728         
729         const TargetRegisterClass* RC =
730           MBB.getParent()->getSSARegMap()->getRegClass(VirtReg);
731
732         PhysRegsUsed[DesignatedReg] = true;
733         ReusedOperands.markClobbered(DesignatedReg);
734         MRI->copyRegToReg(MBB, &MI, DesignatedReg, PhysReg, RC);
735         
736         // This invalidates DesignatedReg.
737         Spills.ClobberPhysReg(DesignatedReg);
738         
739         Spills.addAvailable(StackSlot, &MI, DesignatedReg);
740         MI.getOperand(i).setReg(DesignatedReg);
741         DOUT << '\t' << *prior(MII);
742         ++NumReused;
743         continue;
744       }
745       
746       // Otherwise, reload it and remember that we have it.
747       PhysReg = VRM.getPhys(VirtReg);
748       assert(PhysReg && "Must map virtreg to physreg!");
749       const TargetRegisterClass* RC =
750         MBB.getParent()->getSSARegMap()->getRegClass(VirtReg);
751
752       // Note that, if we reused a register for a previous operand, the
753       // register we want to reload into might not actually be
754       // available.  If this occurs, use the register indicated by the
755       // reuser.
756       if (ReusedOperands.hasReuses())
757         PhysReg = ReusedOperands.GetRegForReload(PhysReg, &MI, 
758                                                  Spills, MaybeDeadStores);
759       
760       PhysRegsUsed[PhysReg] = true;
761       ReusedOperands.markClobbered(PhysReg);
762       MRI->loadRegFromStackSlot(MBB, &MI, PhysReg, StackSlot, RC);
763       // This invalidates PhysReg.
764       Spills.ClobberPhysReg(PhysReg);
765
766       // Any stores to this stack slot are not dead anymore.
767       MaybeDeadStores.erase(StackSlot);
768       Spills.addAvailable(StackSlot, &MI, PhysReg);
769       ++NumLoads;
770       MI.getOperand(i).setReg(PhysReg);
771       DOUT << '\t' << *prior(MII);
772     }
773
774     DOUT << '\t' << MI;
775
776     // If we have folded references to memory operands, make sure we clear all
777     // physical registers that may contain the value of the spilled virtual
778     // register
779     VirtRegMap::MI2VirtMapTy::const_iterator I, End;
780     for (tie(I, End) = VRM.getFoldedVirts(&MI); I != End; ++I) {
781       DOUT << "Folded vreg: " << I->second.first << "  MR: "
782            << I->second.second;
783       unsigned VirtReg = I->second.first;
784       VirtRegMap::ModRef MR = I->second.second;
785       if (!VRM.hasStackSlot(VirtReg)) {
786         DOUT << ": No stack slot!\n";
787         continue;
788       }
789       int SS = VRM.getStackSlot(VirtReg);
790       DOUT << " - StackSlot: " << SS << "\n";
791       
792       // If this folded instruction is just a use, check to see if it's a
793       // straight load from the virt reg slot.
794       if ((MR & VirtRegMap::isRef) && !(MR & VirtRegMap::isMod)) {
795         int FrameIdx;
796         if (unsigned DestReg = TII->isLoadFromStackSlot(&MI, FrameIdx)) {
797           if (FrameIdx == SS) {
798             // If this spill slot is available, turn it into a copy (or nothing)
799             // instead of leaving it as a load!
800             MachineInstr *Dummy = NULL;
801             if (unsigned InReg = Spills.getSpillSlotPhysReg(SS, Dummy)) {
802               DOUT << "Promoted Load To Copy: " << MI;
803               MachineFunction &MF = *MBB.getParent();
804               if (DestReg != InReg) {
805                 MRI->copyRegToReg(MBB, &MI, DestReg, InReg,
806                                   MF.getSSARegMap()->getRegClass(VirtReg));
807                 // Revisit the copy so we make sure to notice the effects of the
808                 // operation on the destreg (either needing to RA it if it's 
809                 // virtual or needing to clobber any values if it's physical).
810                 NextMII = &MI;
811                 --NextMII;  // backtrack to the copy.
812               }
813               VRM.RemoveFromFoldedVirtMap(&MI);
814               MBB.erase(&MI);
815               goto ProcessNextInst;
816             }
817           }
818         }
819       }
820
821       // If this reference is not a use, any previous store is now dead.
822       // Otherwise, the store to this stack slot is not dead anymore.
823       std::map<int, MachineInstr*>::iterator MDSI = MaybeDeadStores.find(SS);
824       if (MDSI != MaybeDeadStores.end()) {
825         if (MR & VirtRegMap::isRef)   // Previous store is not dead.
826           MaybeDeadStores.erase(MDSI);
827         else {
828           // If we get here, the store is dead, nuke it now.
829           assert(VirtRegMap::isMod && "Can't be modref!");
830           DOUT << "Removed dead store:\t" << *MDSI->second;
831           MBB.erase(MDSI->second);
832           VRM.RemoveFromFoldedVirtMap(MDSI->second);
833           MaybeDeadStores.erase(MDSI);
834           ++NumDSE;
835         }
836       }
837
838       // If the spill slot value is available, and this is a new definition of
839       // the value, the value is not available anymore.
840       if (MR & VirtRegMap::isMod) {
841         // Notice that the value in this stack slot has been modified.
842         Spills.ModifyStackSlot(SS);
843         
844         // If this is *just* a mod of the value, check to see if this is just a
845         // store to the spill slot (i.e. the spill got merged into the copy). If
846         // so, realize that the vreg is available now, and add the store to the
847         // MaybeDeadStore info.
848         int StackSlot;
849         if (!(MR & VirtRegMap::isRef)) {
850           if (unsigned SrcReg = TII->isStoreToStackSlot(&MI, StackSlot)) {
851             assert(MRegisterInfo::isPhysicalRegister(SrcReg) &&
852                    "Src hasn't been allocated yet?");
853             // Okay, this is certainly a store of SrcReg to [StackSlot].  Mark
854             // this as a potentially dead store in case there is a subsequent
855             // store into the stack slot without a read from it.
856             MaybeDeadStores[StackSlot] = &MI;
857
858             // If the stack slot value was previously available in some other
859             // register, change it now.  Otherwise, make the register available,
860             // in PhysReg.
861             Spills.addAvailable(StackSlot, &MI, SrcReg, false/*don't clobber*/);
862           }
863         }
864       }
865     }
866
867     // Process all of the spilled defs.
868     for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
869       MachineOperand &MO = MI.getOperand(i);
870       if (MO.isRegister() && MO.getReg() && MO.isDef()) {
871         unsigned VirtReg = MO.getReg();
872
873         if (!MRegisterInfo::isVirtualRegister(VirtReg)) {
874           // Check to see if this is a noop copy.  If so, eliminate the
875           // instruction before considering the dest reg to be changed.
876           unsigned Src, Dst;
877           if (TII->isMoveInstr(MI, Src, Dst) && Src == Dst) {
878             ++NumDCE;
879             DOUT << "Removing now-noop copy: " << MI;
880             MBB.erase(&MI);
881             VRM.RemoveFromFoldedVirtMap(&MI);
882             Spills.disallowClobberPhysReg(VirtReg);
883             goto ProcessNextInst;
884           }
885           
886           // If it's not a no-op copy, it clobbers the value in the destreg.
887           Spills.ClobberPhysReg(VirtReg);
888           ReusedOperands.markClobbered(VirtReg);
889  
890           // Check to see if this instruction is a load from a stack slot into
891           // a register.  If so, this provides the stack slot value in the reg.
892           int FrameIdx;
893           if (unsigned DestReg = TII->isLoadFromStackSlot(&MI, FrameIdx)) {
894             assert(DestReg == VirtReg && "Unknown load situation!");
895             
896             // Otherwise, if it wasn't available, remember that it is now!
897             Spills.addAvailable(FrameIdx, &MI, DestReg);
898             goto ProcessNextInst;
899           }
900             
901           continue;
902         }
903
904         // The only vregs left are stack slot definitions.
905         int StackSlot = VRM.getStackSlot(VirtReg);
906         const TargetRegisterClass *RC =
907           MBB.getParent()->getSSARegMap()->getRegClass(VirtReg);
908
909         // If this def is part of a two-address operand, make sure to execute
910         // the store from the correct physical register.
911         unsigned PhysReg;
912         int TiedOp = MI.getInstrDescriptor()->findTiedToSrcOperand(i);
913         if (TiedOp != -1)
914           PhysReg = MI.getOperand(TiedOp).getReg();
915         else {
916           PhysReg = VRM.getPhys(VirtReg);
917           if (ReusedOperands.isClobbered(PhysReg)) {
918             // Another def has taken the assigned physreg. It must have been a
919             // use&def which got it due to reuse. Undo the reuse!
920             PhysReg = ReusedOperands.GetRegForReload(PhysReg, &MI, 
921                                                      Spills, MaybeDeadStores);
922           }
923         }
924
925         PhysRegsUsed[PhysReg] = true;
926         ReusedOperands.markClobbered(PhysReg);
927         MRI->storeRegToStackSlot(MBB, next(MII), PhysReg, StackSlot, RC);
928         DOUT << "Store:\t" << *next(MII);
929         MI.getOperand(i).setReg(PhysReg);
930
931         // If there is a dead store to this stack slot, nuke it now.
932         MachineInstr *&LastStore = MaybeDeadStores[StackSlot];
933         if (LastStore) {
934           DOUT << "Removed dead store:\t" << *LastStore;
935           ++NumDSE;
936           MBB.erase(LastStore);
937           VRM.RemoveFromFoldedVirtMap(LastStore);
938         }
939         LastStore = next(MII);
940
941         // If the stack slot value was previously available in some other
942         // register, change it now.  Otherwise, make the register available,
943         // in PhysReg.
944         Spills.ModifyStackSlot(StackSlot);
945         Spills.ClobberPhysReg(PhysReg);
946         Spills.addAvailable(StackSlot, LastStore, PhysReg);
947         ++NumStores;
948
949         // Check to see if this is a noop copy.  If so, eliminate the
950         // instruction before considering the dest reg to be changed.
951         {
952           unsigned Src, Dst;
953           if (TII->isMoveInstr(MI, Src, Dst) && Src == Dst) {
954             ++NumDCE;
955             DOUT << "Removing now-noop copy: " << MI;
956             MBB.erase(&MI);
957             VRM.RemoveFromFoldedVirtMap(&MI);
958             goto ProcessNextInst;
959           }
960         }        
961       }
962     }
963   ProcessNextInst:
964     MII = NextMII;
965   }
966 }
967
968
969
970 llvm::Spiller* llvm::createSpiller() {
971   switch (SpillerOpt) {
972   default: assert(0 && "Unreachable!");
973   case local:
974     return new LocalSpiller();
975   case simple:
976     return new SimpleSpiller();
977   }
978 }