Spiller may unfold load / mod / store instructions as an optimization when the would...
[oota-llvm.git] / lib / CodeGen / Spiller.cpp
1 //===-- llvm/CodeGen/Spiller.cpp -  Spiller -------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9
10 #define DEBUG_TYPE "spiller"
11 #include "Spiller.h"
12 #include "llvm/Support/Compiler.h"
13 #include "llvm/ADT/DepthFirstIterator.h"
14 #include "llvm/ADT/Statistic.h"
15 #include "llvm/ADT/STLExtras.h"
16 #include <algorithm>
17 using namespace llvm;
18
19 STATISTIC(NumDSE     , "Number of dead stores elided");
20 STATISTIC(NumDSS     , "Number of dead spill slots removed");
21 STATISTIC(NumCommutes, "Number of instructions commuted");
22 STATISTIC(NumDRM     , "Number of re-materializable defs elided");
23 STATISTIC(NumStores  , "Number of stores added");
24 STATISTIC(NumPSpills , "Number of physical register spills");
25 STATISTIC(NumOmitted , "Number of reloads omited");
26 STATISTIC(NumCopified, "Number of available reloads turned into copies");
27 STATISTIC(NumReMats  , "Number of re-materialization");
28 STATISTIC(NumLoads   , "Number of loads added");
29 STATISTIC(NumReused  , "Number of values reused");
30 STATISTIC(NumDCE     , "Number of copies elided");
31 STATISTIC(NumSUnfold , "Number of stores unfolded");
32
33 namespace {
34   enum SpillerName { simple, local };
35 }
36
37 static cl::opt<SpillerName>
38 SpillerOpt("spiller",
39            cl::desc("Spiller to use: (default: local)"),
40            cl::Prefix,
41            cl::values(clEnumVal(simple, "simple spiller"),
42                       clEnumVal(local,  "local spiller"),
43                       clEnumValEnd),
44            cl::init(local));
45
46 // ****************************** //
47 // Simple Spiller Implementation  //
48 // ****************************** //
49
50 Spiller::~Spiller() {}
51
52 bool SimpleSpiller::runOnMachineFunction(MachineFunction &MF, VirtRegMap &VRM) {
53   DOUT << "********** REWRITE MACHINE CODE **********\n";
54   DOUT << "********** Function: " << MF.getFunction()->getName() << '\n';
55   const TargetMachine &TM = MF.getTarget();
56   const TargetInstrInfo &TII = *TM.getInstrInfo();
57   const TargetRegisterInfo &TRI = *TM.getRegisterInfo();
58
59
60   // LoadedRegs - Keep track of which vregs are loaded, so that we only load
61   // each vreg once (in the case where a spilled vreg is used by multiple
62   // operands).  This is always smaller than the number of operands to the
63   // current machine instr, so it should be small.
64   std::vector<unsigned> LoadedRegs;
65
66   for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
67        MBBI != E; ++MBBI) {
68     DOUT << MBBI->getBasicBlock()->getName() << ":\n";
69     MachineBasicBlock &MBB = *MBBI;
70     for (MachineBasicBlock::iterator MII = MBB.begin(), E = MBB.end();
71          MII != E; ++MII) {
72       MachineInstr &MI = *MII;
73       for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
74         MachineOperand &MO = MI.getOperand(i);
75         if (MO.isReg() && MO.getReg()) {
76           if (TargetRegisterInfo::isVirtualRegister(MO.getReg())) {
77             unsigned VirtReg = MO.getReg();
78             unsigned SubIdx = MO.getSubReg();
79             unsigned PhysReg = VRM.getPhys(VirtReg);
80             unsigned RReg = SubIdx ? TRI.getSubReg(PhysReg, SubIdx) : PhysReg;
81             if (!VRM.isAssignedReg(VirtReg)) {
82               int StackSlot = VRM.getStackSlot(VirtReg);
83               const TargetRegisterClass* RC = 
84                                            MF.getRegInfo().getRegClass(VirtReg);
85               
86               if (MO.isUse() &&
87                   std::find(LoadedRegs.begin(), LoadedRegs.end(), VirtReg)
88                            == LoadedRegs.end()) {
89                 TII.loadRegFromStackSlot(MBB, &MI, PhysReg, StackSlot, RC);
90                 MachineInstr *LoadMI = prior(MII);
91                 VRM.addSpillSlotUse(StackSlot, LoadMI);
92                 LoadedRegs.push_back(VirtReg);
93                 ++NumLoads;
94                 DOUT << '\t' << *LoadMI;
95               }
96
97               if (MO.isDef()) {
98                 TII.storeRegToStackSlot(MBB, next(MII), PhysReg, true,   
99                                         StackSlot, RC);
100                 MachineInstr *StoreMI = next(MII);
101                 VRM.addSpillSlotUse(StackSlot, StoreMI);
102                 ++NumStores;
103               }
104             }
105             MF.getRegInfo().setPhysRegUsed(RReg);
106             MI.getOperand(i).setReg(RReg);
107           } else {
108             MF.getRegInfo().setPhysRegUsed(MO.getReg());
109           }
110         }
111       }
112
113       DOUT << '\t' << MI;
114       LoadedRegs.clear();
115     }
116   }
117   return true;
118 }
119
120 // ****************** //
121 // Utility Functions  //
122 // ****************** //
123
124 /// InvalidateKill - A MI that defines the specified register is being deleted,
125 /// invalidate the register kill information.
126 static void InvalidateKill(unsigned Reg, BitVector &RegKills,
127                            std::vector<MachineOperand*> &KillOps) {
128   if (RegKills[Reg]) {
129     KillOps[Reg]->setIsKill(false);
130     KillOps[Reg] = NULL;
131     RegKills.reset(Reg);
132   }
133 }
134
135 /// findSinglePredSuccessor - Return via reference a vector of machine basic
136 /// blocks each of which is a successor of the specified BB and has no other
137 /// predecessor.
138 static void findSinglePredSuccessor(MachineBasicBlock *MBB,
139                                    SmallVectorImpl<MachineBasicBlock *> &Succs) {
140   for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
141          SE = MBB->succ_end(); SI != SE; ++SI) {
142     MachineBasicBlock *SuccMBB = *SI;
143     if (SuccMBB->pred_size() == 1)
144       Succs.push_back(SuccMBB);
145   }
146 }
147
148 /// InvalidateKills - MI is going to be deleted. If any of its operands are
149 /// marked kill, then invalidate the information.
150 static void InvalidateKills(MachineInstr &MI, BitVector &RegKills,
151                             std::vector<MachineOperand*> &KillOps,
152                             SmallVector<unsigned, 2> *KillRegs = NULL) {
153   for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
154     MachineOperand &MO = MI.getOperand(i);
155     if (!MO.isReg() || !MO.isUse() || !MO.isKill())
156       continue;
157     unsigned Reg = MO.getReg();
158     if (TargetRegisterInfo::isVirtualRegister(Reg))
159       continue;
160     if (KillRegs)
161       KillRegs->push_back(Reg);
162     assert(Reg < KillOps.size());
163     if (KillOps[Reg] == &MO) {
164       RegKills.reset(Reg);
165       KillOps[Reg] = NULL;
166     }
167   }
168 }
169
170 /// InvalidateRegDef - If the def operand of the specified def MI is now dead
171 /// (since it's spill instruction is removed), mark it isDead. Also checks if
172 /// the def MI has other definition operands that are not dead. Returns it by
173 /// reference.
174 static bool InvalidateRegDef(MachineBasicBlock::iterator I,
175                              MachineInstr &NewDef, unsigned Reg,
176                              bool &HasLiveDef) {
177   // Due to remat, it's possible this reg isn't being reused. That is,
178   // the def of this reg (by prev MI) is now dead.
179   MachineInstr *DefMI = I;
180   MachineOperand *DefOp = NULL;
181   for (unsigned i = 0, e = DefMI->getNumOperands(); i != e; ++i) {
182     MachineOperand &MO = DefMI->getOperand(i);
183     if (MO.isReg() && MO.isDef()) {
184       if (MO.getReg() == Reg)
185         DefOp = &MO;
186       else if (!MO.isDead())
187         HasLiveDef = true;
188     }
189   }
190   if (!DefOp)
191     return false;
192
193   bool FoundUse = false, Done = false;
194   MachineBasicBlock::iterator E = &NewDef;
195   ++I; ++E;
196   for (; !Done && I != E; ++I) {
197     MachineInstr *NMI = I;
198     for (unsigned j = 0, ee = NMI->getNumOperands(); j != ee; ++j) {
199       MachineOperand &MO = NMI->getOperand(j);
200       if (!MO.isReg() || MO.getReg() != Reg)
201         continue;
202       if (MO.isUse())
203         FoundUse = true;
204       Done = true; // Stop after scanning all the operands of this MI.
205     }
206   }
207   if (!FoundUse) {
208     // Def is dead!
209     DefOp->setIsDead();
210     return true;
211   }
212   return false;
213 }
214
215 /// UpdateKills - Track and update kill info. If a MI reads a register that is
216 /// marked kill, then it must be due to register reuse. Transfer the kill info
217 /// over.
218 static void UpdateKills(MachineInstr &MI, BitVector &RegKills,
219                         std::vector<MachineOperand*> &KillOps,
220                         const TargetRegisterInfo* TRI) {
221   const TargetInstrDesc &TID = MI.getDesc();
222   for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
223     MachineOperand &MO = MI.getOperand(i);
224     if (!MO.isReg() || !MO.isUse())
225       continue;
226     unsigned Reg = MO.getReg();
227     if (Reg == 0)
228       continue;
229     
230     if (RegKills[Reg] && KillOps[Reg]->getParent() != &MI) {
231       // That can't be right. Register is killed but not re-defined and it's
232       // being reused. Let's fix that.
233       KillOps[Reg]->setIsKill(false);
234       KillOps[Reg] = NULL;
235       RegKills.reset(Reg);
236       if (i < TID.getNumOperands() &&
237           TID.getOperandConstraint(i, TOI::TIED_TO) == -1)
238         // Unless it's a two-address operand, this is the new kill.
239         MO.setIsKill();
240     }
241     if (MO.isKill()) {
242       RegKills.set(Reg);
243       KillOps[Reg] = &MO;
244     }
245   }
246
247   for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
248     const MachineOperand &MO = MI.getOperand(i);
249     if (!MO.isReg() || !MO.isDef())
250       continue;
251     unsigned Reg = MO.getReg();
252     RegKills.reset(Reg);
253     KillOps[Reg] = NULL;
254     // It also defines (or partially define) aliases.
255     for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS) {
256       RegKills.reset(*AS);
257       KillOps[*AS] = NULL;
258     }
259   }
260 }
261
262 /// ReMaterialize - Re-materialize definition for Reg targetting DestReg.
263 ///
264 static void ReMaterialize(MachineBasicBlock &MBB,
265                           MachineBasicBlock::iterator &MII,
266                           unsigned DestReg, unsigned Reg,
267                           const TargetInstrInfo *TII,
268                           const TargetRegisterInfo *TRI,
269                           VirtRegMap &VRM) {
270   TII->reMaterialize(MBB, MII, DestReg, VRM.getReMaterializedMI(Reg));
271   MachineInstr *NewMI = prior(MII);
272   for (unsigned i = 0, e = NewMI->getNumOperands(); i != e; ++i) {
273     MachineOperand &MO = NewMI->getOperand(i);
274     if (!MO.isReg() || MO.getReg() == 0)
275       continue;
276     unsigned VirtReg = MO.getReg();
277     if (TargetRegisterInfo::isPhysicalRegister(VirtReg))
278       continue;
279     assert(MO.isUse());
280     unsigned SubIdx = MO.getSubReg();
281     unsigned Phys = VRM.getPhys(VirtReg);
282     assert(Phys);
283     unsigned RReg = SubIdx ? TRI->getSubReg(Phys, SubIdx) : Phys;
284     MO.setReg(RReg);
285   }
286   ++NumReMats;
287 }
288
289 /// findSuperReg - Find the SubReg's super-register of given register class
290 /// where its SubIdx sub-register is SubReg.
291 static unsigned findSuperReg(const TargetRegisterClass *RC, unsigned SubReg,
292                              unsigned SubIdx, const TargetRegisterInfo *TRI) {
293   for (TargetRegisterClass::iterator I = RC->begin(), E = RC->end();
294        I != E; ++I) {
295     unsigned Reg = *I;
296     if (TRI->getSubReg(Reg, SubIdx) == SubReg)
297       return Reg;
298   }
299   return 0;
300 }
301
302 // ******************************** //
303 // Available Spills Implementation  //
304 // ******************************** //
305
306 /// disallowClobberPhysRegOnly - Unset the CanClobber bit of the specified
307 /// stackslot register. The register is still available but is no longer
308 /// allowed to be modifed.
309 void AvailableSpills::disallowClobberPhysRegOnly(unsigned PhysReg) {
310   std::multimap<unsigned, int>::iterator I =
311     PhysRegsAvailable.lower_bound(PhysReg);
312   while (I != PhysRegsAvailable.end() && I->first == PhysReg) {
313     int SlotOrReMat = I->second;
314     I++;
315     assert((SpillSlotsOrReMatsAvailable[SlotOrReMat] >> 1) == PhysReg &&
316            "Bidirectional map mismatch!");
317     SpillSlotsOrReMatsAvailable[SlotOrReMat] &= ~1;
318     DOUT << "PhysReg " << TRI->getName(PhysReg)
319          << " copied, it is available for use but can no longer be modified\n";
320   }
321 }
322
323 /// disallowClobberPhysReg - Unset the CanClobber bit of the specified
324 /// stackslot register and its aliases. The register and its aliases may
325 /// still available but is no longer allowed to be modifed.
326 void AvailableSpills::disallowClobberPhysReg(unsigned PhysReg) {
327   for (const unsigned *AS = TRI->getAliasSet(PhysReg); *AS; ++AS)
328     disallowClobberPhysRegOnly(*AS);
329   disallowClobberPhysRegOnly(PhysReg);
330 }
331
332 /// ClobberPhysRegOnly - This is called when the specified physreg changes
333 /// value.  We use this to invalidate any info about stuff we thing lives in it.
334 void AvailableSpills::ClobberPhysRegOnly(unsigned PhysReg) {
335   std::multimap<unsigned, int>::iterator I =
336     PhysRegsAvailable.lower_bound(PhysReg);
337   while (I != PhysRegsAvailable.end() && I->first == PhysReg) {
338     int SlotOrReMat = I->second;
339     PhysRegsAvailable.erase(I++);
340     assert((SpillSlotsOrReMatsAvailable[SlotOrReMat] >> 1) == PhysReg &&
341            "Bidirectional map mismatch!");
342     SpillSlotsOrReMatsAvailable.erase(SlotOrReMat);
343     DOUT << "PhysReg " << TRI->getName(PhysReg)
344          << " clobbered, invalidating ";
345     if (SlotOrReMat > VirtRegMap::MAX_STACK_SLOT)
346       DOUT << "RM#" << SlotOrReMat-VirtRegMap::MAX_STACK_SLOT-1 << "\n";
347     else
348       DOUT << "SS#" << SlotOrReMat << "\n";
349   }
350 }
351
352 /// ClobberPhysReg - This is called when the specified physreg changes
353 /// value.  We use this to invalidate any info about stuff we thing lives in
354 /// it and any of its aliases.
355 void AvailableSpills::ClobberPhysReg(unsigned PhysReg) {
356   for (const unsigned *AS = TRI->getAliasSet(PhysReg); *AS; ++AS)
357     ClobberPhysRegOnly(*AS);
358   ClobberPhysRegOnly(PhysReg);
359 }
360
361 /// AddAvailableRegsToLiveIn - Availability information is being kept coming
362 /// into the specified MBB. Add available physical registers as potential
363 /// live-in's. If they are reused in the MBB, they will be added to the
364 /// live-in set to make register scavenger and post-allocation scheduler.
365 void AvailableSpills::AddAvailableRegsToLiveIn(MachineBasicBlock &MBB,
366                                         BitVector &RegKills,
367                                         std::vector<MachineOperand*> &KillOps) {
368   std::set<unsigned> NotAvailable;
369   for (std::multimap<unsigned, int>::iterator
370          I = PhysRegsAvailable.begin(), E = PhysRegsAvailable.end();
371        I != E; ++I) {
372     unsigned Reg = I->first;
373     const TargetRegisterClass* RC = TRI->getPhysicalRegisterRegClass(Reg);
374     // FIXME: A temporary workaround. We can't reuse available value if it's
375     // not safe to move the def of the virtual register's class. e.g.
376     // X86::RFP* register classes. Do not add it as a live-in.
377     if (!TII->isSafeToMoveRegClassDefs(RC))
378       // This is no longer available.
379       NotAvailable.insert(Reg);
380     else {
381       MBB.addLiveIn(Reg);
382       InvalidateKill(Reg, RegKills, KillOps);
383     }
384
385     // Skip over the same register.
386     std::multimap<unsigned, int>::iterator NI = next(I);
387     while (NI != E && NI->first == Reg) {
388       ++I;
389       ++NI;
390     }
391   }
392
393   for (std::set<unsigned>::iterator I = NotAvailable.begin(),
394          E = NotAvailable.end(); I != E; ++I) {
395     ClobberPhysReg(*I);
396     for (const unsigned *SubRegs = TRI->getSubRegisters(*I);
397        *SubRegs; ++SubRegs)
398       ClobberPhysReg(*SubRegs);
399   }
400 }
401
402 /// ModifyStackSlotOrReMat - This method is called when the value in a stack
403 /// slot changes.  This removes information about which register the previous
404 /// value for this slot lives in (as the previous value is dead now).
405 void AvailableSpills::ModifyStackSlotOrReMat(int SlotOrReMat) {
406   std::map<int, unsigned>::iterator It =
407     SpillSlotsOrReMatsAvailable.find(SlotOrReMat);
408   if (It == SpillSlotsOrReMatsAvailable.end()) return;
409   unsigned Reg = It->second >> 1;
410   SpillSlotsOrReMatsAvailable.erase(It);
411   
412   // This register may hold the value of multiple stack slots, only remove this
413   // stack slot from the set of values the register contains.
414   std::multimap<unsigned, int>::iterator I = PhysRegsAvailable.lower_bound(Reg);
415   for (; ; ++I) {
416     assert(I != PhysRegsAvailable.end() && I->first == Reg &&
417            "Map inverse broken!");
418     if (I->second == SlotOrReMat) break;
419   }
420   PhysRegsAvailable.erase(I);
421 }
422
423 // ************************** //
424 // Reuse Info Implementation  //
425 // ************************** //
426
427 /// GetRegForReload - We are about to emit a reload into PhysReg.  If there
428 /// is some other operand that is using the specified register, either pick
429 /// a new register to use, or evict the previous reload and use this reg.
430 unsigned ReuseInfo::GetRegForReload(unsigned PhysReg, MachineInstr *MI,
431                          AvailableSpills &Spills,
432                          std::vector<MachineInstr*> &MaybeDeadStores,
433                          SmallSet<unsigned, 8> &Rejected,
434                          BitVector &RegKills,
435                          std::vector<MachineOperand*> &KillOps,
436                          VirtRegMap &VRM) {
437   const TargetInstrInfo* TII = MI->getParent()->getParent()->getTarget()
438                                .getInstrInfo();
439   
440   if (Reuses.empty()) return PhysReg;  // This is most often empty.
441
442   for (unsigned ro = 0, e = Reuses.size(); ro != e; ++ro) {
443     ReusedOp &Op = Reuses[ro];
444     // If we find some other reuse that was supposed to use this register
445     // exactly for its reload, we can change this reload to use ITS reload
446     // register. That is, unless its reload register has already been
447     // considered and subsequently rejected because it has also been reused
448     // by another operand.
449     if (Op.PhysRegReused == PhysReg &&
450         Rejected.count(Op.AssignedPhysReg) == 0) {
451       // Yup, use the reload register that we didn't use before.
452       unsigned NewReg = Op.AssignedPhysReg;
453       Rejected.insert(PhysReg);
454       return GetRegForReload(NewReg, MI, Spills, MaybeDeadStores, Rejected,
455                              RegKills, KillOps, VRM);
456     } else {
457       // Otherwise, we might also have a problem if a previously reused
458       // value aliases the new register.  If so, codegen the previous reload
459       // and use this one.          
460       unsigned PRRU = Op.PhysRegReused;
461       const TargetRegisterInfo *TRI = Spills.getRegInfo();
462       if (TRI->areAliases(PRRU, PhysReg)) {
463         // Okay, we found out that an alias of a reused register
464         // was used.  This isn't good because it means we have
465         // to undo a previous reuse.
466         MachineBasicBlock *MBB = MI->getParent();
467         const TargetRegisterClass *AliasRC =
468           MBB->getParent()->getRegInfo().getRegClass(Op.VirtReg);
469
470         // Copy Op out of the vector and remove it, we're going to insert an
471         // explicit load for it.
472         ReusedOp NewOp = Op;
473         Reuses.erase(Reuses.begin()+ro);
474
475         // Ok, we're going to try to reload the assigned physreg into the
476         // slot that we were supposed to in the first place.  However, that
477         // register could hold a reuse.  Check to see if it conflicts or
478         // would prefer us to use a different register.
479         unsigned NewPhysReg = GetRegForReload(NewOp.AssignedPhysReg,
480                                               MI, Spills, MaybeDeadStores,
481                                           Rejected, RegKills, KillOps, VRM);
482         
483         MachineBasicBlock::iterator MII = MI;
484         if (NewOp.StackSlotOrReMat > VirtRegMap::MAX_STACK_SLOT) {
485           ReMaterialize(*MBB, MII, NewPhysReg, NewOp.VirtReg, TII, TRI,VRM);
486         } else {
487           TII->loadRegFromStackSlot(*MBB, MII, NewPhysReg,
488                                     NewOp.StackSlotOrReMat, AliasRC);
489           MachineInstr *LoadMI = prior(MII);
490           VRM.addSpillSlotUse(NewOp.StackSlotOrReMat, LoadMI);
491           // Any stores to this stack slot are not dead anymore.
492           MaybeDeadStores[NewOp.StackSlotOrReMat] = NULL;            
493           ++NumLoads;
494         }
495         Spills.ClobberPhysReg(NewPhysReg);
496         Spills.ClobberPhysReg(NewOp.PhysRegReused);
497
498         unsigned SubIdx = MI->getOperand(NewOp.Operand).getSubReg();
499         unsigned RReg = SubIdx ? TRI->getSubReg(NewPhysReg, SubIdx) : NewPhysReg;
500         MI->getOperand(NewOp.Operand).setReg(RReg);
501         
502         Spills.addAvailable(NewOp.StackSlotOrReMat, NewPhysReg);
503         --MII;
504         UpdateKills(*MII, RegKills, KillOps, TRI);
505         DOUT << '\t' << *MII;
506         
507         DOUT << "Reuse undone!\n";
508         --NumReused;
509         
510         // Finally, PhysReg is now available, go ahead and use it.
511         return PhysReg;
512       }
513     }
514   }
515   return PhysReg;
516 }
517
518 // ***************************** //
519 // Local Spiller Implementation  //
520 // ***************************** //
521
522 bool LocalSpiller::runOnMachineFunction(MachineFunction &MF, VirtRegMap &VRM) {
523   RegInfo = &MF.getRegInfo(); 
524   TRI = MF.getTarget().getRegisterInfo();
525   TII = MF.getTarget().getInstrInfo();
526   DOUT << "\n**** Local spiller rewriting function '"
527        << MF.getFunction()->getName() << "':\n";
528   DOUT << "**** Machine Instrs (NOTE! Does not include spills and reloads!)"
529           " ****\n";
530   DEBUG(MF.dump());
531
532   // Spills - Keep track of which spilled values are available in physregs
533   // so that we can choose to reuse the physregs instead of emitting
534   // reloads. This is usually refreshed per basic block.
535   AvailableSpills Spills(TRI, TII);
536
537   // Keep track of kill information.
538   BitVector RegKills(TRI->getNumRegs());
539   std::vector<MachineOperand*> KillOps;
540   KillOps.resize(TRI->getNumRegs(), NULL);
541
542   // SingleEntrySuccs - Successor blocks which have a single predecessor.
543   SmallVector<MachineBasicBlock*, 4> SinglePredSuccs;
544   SmallPtrSet<MachineBasicBlock*,16> EarlyVisited;
545
546   // Traverse the basic blocks depth first.
547   MachineBasicBlock *Entry = MF.begin();
548   SmallPtrSet<MachineBasicBlock*,16> Visited;
549   for (df_ext_iterator<MachineBasicBlock*,
550          SmallPtrSet<MachineBasicBlock*,16> >
551          DFI = df_ext_begin(Entry, Visited), E = df_ext_end(Entry, Visited);
552        DFI != E; ++DFI) {
553     MachineBasicBlock *MBB = *DFI;
554     if (!EarlyVisited.count(MBB))
555       RewriteMBB(*MBB, VRM, Spills, RegKills, KillOps);
556
557     // If this MBB is the only predecessor of a successor. Keep the
558     // availability information and visit it next.
559     do {
560       // Keep visiting single predecessor successor as long as possible.
561       SinglePredSuccs.clear();
562       findSinglePredSuccessor(MBB, SinglePredSuccs);
563       if (SinglePredSuccs.empty())
564         MBB = 0;
565       else {
566         // FIXME: More than one successors, each of which has MBB has
567         // the only predecessor.
568         MBB = SinglePredSuccs[0];
569         if (!Visited.count(MBB) && EarlyVisited.insert(MBB)) {
570           Spills.AddAvailableRegsToLiveIn(*MBB, RegKills, KillOps);
571           RewriteMBB(*MBB, VRM, Spills, RegKills, KillOps);
572         }
573       }
574     } while (MBB);
575
576     // Clear the availability info.
577     Spills.clear();
578   }
579
580   DOUT << "**** Post Machine Instrs ****\n";
581   DEBUG(MF.dump());
582
583   // Mark unused spill slots.
584   MachineFrameInfo *MFI = MF.getFrameInfo();
585   int SS = VRM.getLowSpillSlot();
586   if (SS != VirtRegMap::NO_STACK_SLOT)
587     for (int e = VRM.getHighSpillSlot(); SS <= e; ++SS)
588       if (!VRM.isSpillSlotUsed(SS)) {
589         MFI->RemoveStackObject(SS);
590         ++NumDSS;
591       }
592
593   return true;
594 }
595
596
597 /// PrepForUnfoldOpti - Turn a store folding instruction into a load folding
598 /// instruction. e.g.
599 ///     xorl  %edi, %eax
600 ///     movl  %eax, -32(%ebp)
601 ///     movl  -36(%ebp), %eax
602 ///     orl   %eax, -32(%ebp)
603 /// ==>
604 ///     xorl  %edi, %eax
605 ///     orl   -36(%ebp), %eax
606 ///     mov   %eax, -32(%ebp)
607 /// This enables unfolding optimization for a subsequent instruction which will
608 /// also eliminate the newly introduced store instruction.
609 bool LocalSpiller::PrepForUnfoldOpti(MachineBasicBlock &MBB,
610                                     MachineBasicBlock::iterator &MII,
611                                     std::vector<MachineInstr*> &MaybeDeadStores,
612                                     AvailableSpills &Spills,
613                                     BitVector &RegKills,
614                                     std::vector<MachineOperand*> &KillOps,
615                                     VirtRegMap &VRM) {
616   MachineFunction &MF = *MBB.getParent();
617   MachineInstr &MI = *MII;
618   unsigned UnfoldedOpc = 0;
619   unsigned UnfoldPR = 0;
620   unsigned UnfoldVR = 0;
621   int FoldedSS = VirtRegMap::NO_STACK_SLOT;
622   VirtRegMap::MI2VirtMapTy::const_iterator I, End;
623   for (tie(I, End) = VRM.getFoldedVirts(&MI); I != End; ) {
624     // Only transform a MI that folds a single register.
625     if (UnfoldedOpc)
626       return false;
627     UnfoldVR = I->second.first;
628     VirtRegMap::ModRef MR = I->second.second;
629     // MI2VirtMap be can updated which invalidate the iterator.
630     // Increment the iterator first.
631     ++I; 
632     if (VRM.isAssignedReg(UnfoldVR))
633       continue;
634     // If this reference is not a use, any previous store is now dead.
635     // Otherwise, the store to this stack slot is not dead anymore.
636     FoldedSS = VRM.getStackSlot(UnfoldVR);
637     MachineInstr* DeadStore = MaybeDeadStores[FoldedSS];
638     if (DeadStore && (MR & VirtRegMap::isModRef)) {
639       unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(FoldedSS);
640       if (!PhysReg || !DeadStore->readsRegister(PhysReg))
641         continue;
642       UnfoldPR = PhysReg;
643       UnfoldedOpc = TII->getOpcodeAfterMemoryUnfold(MI.getOpcode(),
644                                                     false, true);
645     }
646   }
647
648   if (!UnfoldedOpc)
649     return false;
650
651   for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
652     MachineOperand &MO = MI.getOperand(i);
653     if (!MO.isReg() || MO.getReg() == 0 || !MO.isUse())
654       continue;
655     unsigned VirtReg = MO.getReg();
656     if (TargetRegisterInfo::isPhysicalRegister(VirtReg) || MO.getSubReg())
657       continue;
658     if (VRM.isAssignedReg(VirtReg)) {
659       unsigned PhysReg = VRM.getPhys(VirtReg);
660       if (PhysReg && TRI->regsOverlap(PhysReg, UnfoldPR))
661         return false;
662     } else if (VRM.isReMaterialized(VirtReg))
663       continue;
664     int SS = VRM.getStackSlot(VirtReg);
665     unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SS);
666     if (PhysReg) {
667       if (TRI->regsOverlap(PhysReg, UnfoldPR))
668         return false;
669       continue;
670     }
671     if (VRM.hasPhys(VirtReg)) {
672       PhysReg = VRM.getPhys(VirtReg);
673       if (!TRI->regsOverlap(PhysReg, UnfoldPR))
674         continue;
675     }
676
677     // Ok, we'll need to reload the value into a register which makes
678     // it impossible to perform the store unfolding optimization later.
679     // Let's see if it is possible to fold the load if the store is
680     // unfolded. This allows us to perform the store unfolding
681     // optimization.
682     SmallVector<MachineInstr*, 4> NewMIs;
683     if (TII->unfoldMemoryOperand(MF, &MI, UnfoldVR, false, false, NewMIs)) {
684       assert(NewMIs.size() == 1);
685       MachineInstr *NewMI = NewMIs.back();
686       NewMIs.clear();
687       int Idx = NewMI->findRegisterUseOperandIdx(VirtReg, false);
688       assert(Idx != -1);
689       SmallVector<unsigned, 1> Ops;
690       Ops.push_back(Idx);
691       MachineInstr *FoldedMI = TII->foldMemoryOperand(MF, NewMI, Ops, SS);
692       if (FoldedMI) {
693         VRM.addSpillSlotUse(SS, FoldedMI);
694         if (!VRM.hasPhys(UnfoldVR))
695           VRM.assignVirt2Phys(UnfoldVR, UnfoldPR);
696         VRM.virtFolded(VirtReg, FoldedMI, VirtRegMap::isRef);
697         MII = MBB.insert(MII, FoldedMI);
698         InvalidateKills(MI, RegKills, KillOps);
699         VRM.RemoveMachineInstrFromMaps(&MI);
700         MBB.erase(&MI);
701         MF.DeleteMachineInstr(NewMI);
702         return true;
703       }
704       MF.DeleteMachineInstr(NewMI);
705     }
706   }
707   return false;
708 }
709
710 /// CommuteToFoldReload -
711 /// Look for
712 /// r1 = load fi#1
713 /// r1 = op r1, r2<kill>
714 /// store r1, fi#1
715 ///
716 /// If op is commutable and r2 is killed, then we can xform these to
717 /// r2 = op r2, fi#1
718 /// store r2, fi#1
719 bool LocalSpiller::CommuteToFoldReload(MachineBasicBlock &MBB,
720                                     MachineBasicBlock::iterator &MII,
721                                     unsigned VirtReg, unsigned SrcReg, int SS,
722                                     AvailableSpills &Spills,
723                                     BitVector &RegKills,
724                                     std::vector<MachineOperand*> &KillOps,
725                                     const TargetRegisterInfo *TRI,
726                                     VirtRegMap &VRM) {
727   if (MII == MBB.begin() || !MII->killsRegister(SrcReg))
728     return false;
729
730   MachineFunction &MF = *MBB.getParent();
731   MachineInstr &MI = *MII;
732   MachineBasicBlock::iterator DefMII = prior(MII);
733   MachineInstr *DefMI = DefMII;
734   const TargetInstrDesc &TID = DefMI->getDesc();
735   unsigned NewDstIdx;
736   if (DefMII != MBB.begin() &&
737       TID.isCommutable() &&
738       TII->CommuteChangesDestination(DefMI, NewDstIdx)) {
739     MachineOperand &NewDstMO = DefMI->getOperand(NewDstIdx);
740     unsigned NewReg = NewDstMO.getReg();
741     if (!NewDstMO.isKill() || TRI->regsOverlap(NewReg, SrcReg))
742       return false;
743     MachineInstr *ReloadMI = prior(DefMII);
744     int FrameIdx;
745     unsigned DestReg = TII->isLoadFromStackSlot(ReloadMI, FrameIdx);
746     if (DestReg != SrcReg || FrameIdx != SS)
747       return false;
748     int UseIdx = DefMI->findRegisterUseOperandIdx(DestReg, false);
749     if (UseIdx == -1)
750       return false;
751     int DefIdx = TID.getOperandConstraint(UseIdx, TOI::TIED_TO);
752     if (DefIdx == -1)
753       return false;
754     assert(DefMI->getOperand(DefIdx).isReg() &&
755            DefMI->getOperand(DefIdx).getReg() == SrcReg);
756
757     // Now commute def instruction.
758     MachineInstr *CommutedMI = TII->commuteInstruction(DefMI, true);
759     if (!CommutedMI)
760       return false;
761     SmallVector<unsigned, 1> Ops;
762     Ops.push_back(NewDstIdx);
763     MachineInstr *FoldedMI = TII->foldMemoryOperand(MF, CommutedMI, Ops, SS);
764     // Not needed since foldMemoryOperand returns new MI.
765     MF.DeleteMachineInstr(CommutedMI);
766     if (!FoldedMI)
767       return false;
768
769     VRM.addSpillSlotUse(SS, FoldedMI);
770     VRM.virtFolded(VirtReg, FoldedMI, VirtRegMap::isRef);
771     // Insert new def MI and spill MI.
772     const TargetRegisterClass* RC = MF.getRegInfo().getRegClass(VirtReg);
773     TII->storeRegToStackSlot(MBB, &MI, NewReg, true, SS, RC);
774     MII = prior(MII);
775     MachineInstr *StoreMI = MII;
776     VRM.addSpillSlotUse(SS, StoreMI);
777     VRM.virtFolded(VirtReg, StoreMI, VirtRegMap::isMod);
778     MII = MBB.insert(MII, FoldedMI);  // Update MII to backtrack.
779
780     // Delete all 3 old instructions.
781     InvalidateKills(*ReloadMI, RegKills, KillOps);
782     VRM.RemoveMachineInstrFromMaps(ReloadMI);
783     MBB.erase(ReloadMI);
784     InvalidateKills(*DefMI, RegKills, KillOps);
785     VRM.RemoveMachineInstrFromMaps(DefMI);
786     MBB.erase(DefMI);
787     InvalidateKills(MI, RegKills, KillOps);
788     VRM.RemoveMachineInstrFromMaps(&MI);
789     MBB.erase(&MI);
790
791     // If NewReg was previously holding value of some SS, it's now clobbered.
792     // This has to be done now because it's a physical register. When this
793     // instruction is re-visited, it's ignored.
794     Spills.ClobberPhysReg(NewReg);
795
796     ++NumCommutes;
797     return true;
798   }
799
800   return false;
801 }
802
803 /// SpillRegToStackSlot - Spill a register to a specified stack slot. Check if
804 /// the last store to the same slot is now dead. If so, remove the last store.
805 void LocalSpiller::SpillRegToStackSlot(MachineBasicBlock &MBB,
806                                   MachineBasicBlock::iterator &MII,
807                                   int Idx, unsigned PhysReg, int StackSlot,
808                                   const TargetRegisterClass *RC,
809                                   bool isAvailable, MachineInstr *&LastStore,
810                                   AvailableSpills &Spills,
811                                   SmallSet<MachineInstr*, 4> &ReMatDefs,
812                                   BitVector &RegKills,
813                                   std::vector<MachineOperand*> &KillOps,
814                                   VirtRegMap &VRM) {
815   TII->storeRegToStackSlot(MBB, next(MII), PhysReg, true, StackSlot, RC);
816   MachineInstr *StoreMI = next(MII);
817   VRM.addSpillSlotUse(StackSlot, StoreMI);
818   DOUT << "Store:\t" << *StoreMI;
819
820   // If there is a dead store to this stack slot, nuke it now.
821   if (LastStore) {
822     DOUT << "Removed dead store:\t" << *LastStore;
823     ++NumDSE;
824     SmallVector<unsigned, 2> KillRegs;
825     InvalidateKills(*LastStore, RegKills, KillOps, &KillRegs);
826     MachineBasicBlock::iterator PrevMII = LastStore;
827     bool CheckDef = PrevMII != MBB.begin();
828     if (CheckDef)
829       --PrevMII;
830     VRM.RemoveMachineInstrFromMaps(LastStore);
831     MBB.erase(LastStore);
832     if (CheckDef) {
833       // Look at defs of killed registers on the store. Mark the defs
834       // as dead since the store has been deleted and they aren't
835       // being reused.
836       for (unsigned j = 0, ee = KillRegs.size(); j != ee; ++j) {
837         bool HasOtherDef = false;
838         if (InvalidateRegDef(PrevMII, *MII, KillRegs[j], HasOtherDef)) {
839           MachineInstr *DeadDef = PrevMII;
840           if (ReMatDefs.count(DeadDef) && !HasOtherDef) {
841             // FIXME: This assumes a remat def does not have side
842             // effects.
843             VRM.RemoveMachineInstrFromMaps(DeadDef);
844             MBB.erase(DeadDef);
845             ++NumDRM;
846           }
847         }
848       }
849     }
850   }
851
852   LastStore = next(MII);
853
854   // If the stack slot value was previously available in some other
855   // register, change it now.  Otherwise, make the register available,
856   // in PhysReg.
857   Spills.ModifyStackSlotOrReMat(StackSlot);
858   Spills.ClobberPhysReg(PhysReg);
859   Spills.addAvailable(StackSlot, PhysReg, isAvailable);
860   ++NumStores;
861 }
862
863 /// TransferDeadness - A identity copy definition is dead and it's being
864 /// removed. Find the last def or use and mark it as dead / kill.
865 void LocalSpiller::TransferDeadness(MachineBasicBlock *MBB, unsigned CurDist,
866                                     unsigned Reg, BitVector &RegKills,
867                                     std::vector<MachineOperand*> &KillOps) {
868   int LastUDDist = -1;
869   MachineInstr *LastUDMI = NULL;
870   for (MachineRegisterInfo::reg_iterator RI = RegInfo->reg_begin(Reg),
871          RE = RegInfo->reg_end(); RI != RE; ++RI) {
872     MachineInstr *UDMI = &*RI;
873     if (UDMI->getParent() != MBB)
874       continue;
875     DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(UDMI);
876     if (DI == DistanceMap.end() || DI->second > CurDist)
877       continue;
878     if ((int)DI->second < LastUDDist)
879       continue;
880     LastUDDist = DI->second;
881     LastUDMI = UDMI;
882   }
883
884   if (LastUDMI) {
885     const TargetInstrDesc &TID = LastUDMI->getDesc();
886     MachineOperand *LastUD = NULL;
887     for (unsigned i = 0, e = LastUDMI->getNumOperands(); i != e; ++i) {
888       MachineOperand &MO = LastUDMI->getOperand(i);
889       if (!MO.isReg() || MO.getReg() != Reg)
890         continue;
891       if (!LastUD || (LastUD->isUse() && MO.isDef()))
892         LastUD = &MO;
893       if (TID.getOperandConstraint(i, TOI::TIED_TO) != -1)
894         return;
895     }
896     if (LastUD->isDef())
897       LastUD->setIsDead();
898     else {
899       LastUD->setIsKill();
900       RegKills.set(Reg);
901       KillOps[Reg] = LastUD;
902     }
903   }
904 }
905
906 /// rewriteMBB - Keep track of which spills are available even after the
907 /// register allocator is done with them.  If possible, avid reloading vregs.
908 void LocalSpiller::RewriteMBB(MachineBasicBlock &MBB, VirtRegMap &VRM,
909                               AvailableSpills &Spills, BitVector &RegKills,
910                               std::vector<MachineOperand*> &KillOps) {
911   DOUT << "\n**** Local spiller rewriting MBB '"
912        << MBB.getBasicBlock()->getName() << ":\n";
913
914   MachineFunction &MF = *MBB.getParent();
915   
916   // MaybeDeadStores - When we need to write a value back into a stack slot,
917   // keep track of the inserted store.  If the stack slot value is never read
918   // (because the value was used from some available register, for example), and
919   // subsequently stored to, the original store is dead.  This map keeps track
920   // of inserted stores that are not used.  If we see a subsequent store to the
921   // same stack slot, the original store is deleted.
922   std::vector<MachineInstr*> MaybeDeadStores;
923   MaybeDeadStores.resize(MF.getFrameInfo()->getObjectIndexEnd(), NULL);
924
925   // ReMatDefs - These are rematerializable def MIs which are not deleted.
926   SmallSet<MachineInstr*, 4> ReMatDefs;
927
928   // Clear kill info.
929   SmallSet<unsigned, 2> KilledMIRegs;
930   RegKills.reset();
931   KillOps.clear();
932   KillOps.resize(TRI->getNumRegs(), NULL);
933
934   unsigned Dist = 0;
935   DistanceMap.clear();
936   for (MachineBasicBlock::iterator MII = MBB.begin(), E = MBB.end();
937        MII != E; ) {
938     MachineBasicBlock::iterator NextMII = MII; ++NextMII;
939
940     VirtRegMap::MI2VirtMapTy::const_iterator I, End;
941     bool Erased = false;
942     bool BackTracked = false;
943     if (PrepForUnfoldOpti(MBB, MII,
944                           MaybeDeadStores, Spills, RegKills, KillOps, VRM))
945       NextMII = next(MII);
946
947     MachineInstr &MI = *MII;
948     const TargetInstrDesc &TID = MI.getDesc();
949
950     if (VRM.hasEmergencySpills(&MI)) {
951       // Spill physical register(s) in the rare case the allocator has run out
952       // of registers to allocate.
953       SmallSet<int, 4> UsedSS;
954       std::vector<unsigned> &EmSpills = VRM.getEmergencySpills(&MI);
955       for (unsigned i = 0, e = EmSpills.size(); i != e; ++i) {
956         unsigned PhysReg = EmSpills[i];
957         const TargetRegisterClass *RC =
958           TRI->getPhysicalRegisterRegClass(PhysReg);
959         assert(RC && "Unable to determine register class!");
960         int SS = VRM.getEmergencySpillSlot(RC);
961         if (UsedSS.count(SS))
962           assert(0 && "Need to spill more than one physical registers!");
963         UsedSS.insert(SS);
964         TII->storeRegToStackSlot(MBB, MII, PhysReg, true, SS, RC);
965         MachineInstr *StoreMI = prior(MII);
966         VRM.addSpillSlotUse(SS, StoreMI);
967         TII->loadRegFromStackSlot(MBB, next(MII), PhysReg, SS, RC);
968         MachineInstr *LoadMI = next(MII);
969         VRM.addSpillSlotUse(SS, LoadMI);
970         ++NumPSpills;
971       }
972       NextMII = next(MII);
973     }
974
975     // Insert restores here if asked to.
976     if (VRM.isRestorePt(&MI)) {
977       std::vector<unsigned> &RestoreRegs = VRM.getRestorePtRestores(&MI);
978       for (unsigned i = 0, e = RestoreRegs.size(); i != e; ++i) {
979         unsigned VirtReg = RestoreRegs[e-i-1];  // Reverse order.
980         if (!VRM.getPreSplitReg(VirtReg))
981           continue; // Split interval spilled again.
982         unsigned Phys = VRM.getPhys(VirtReg);
983         RegInfo->setPhysRegUsed(Phys);
984
985         // Check if the value being restored if available. If so, it must be
986         // from a predecessor BB that fallthrough into this BB. We do not
987         // expect:
988         // BB1:
989         // r1 = load fi#1
990         // ...
991         //    = r1<kill>
992         // ... # r1 not clobbered
993         // ...
994         //    = load fi#1
995         bool DoReMat = VRM.isReMaterialized(VirtReg);
996         int SSorRMId = DoReMat
997           ? VRM.getReMatId(VirtReg) : VRM.getStackSlot(VirtReg);
998         const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
999         unsigned InReg = Spills.getSpillSlotOrReMatPhysReg(SSorRMId);
1000         if (InReg == Phys) {
1001           // If the value is already available in the expected register, save
1002           // a reload / remat.
1003           if (SSorRMId)
1004             DOUT << "Reusing RM#" << SSorRMId-VirtRegMap::MAX_STACK_SLOT-1;
1005           else
1006             DOUT << "Reusing SS#" << SSorRMId;
1007           DOUT << " from physreg "
1008                << TRI->getName(InReg) << " for vreg"
1009                << VirtReg <<" instead of reloading into physreg "
1010                << TRI->getName(Phys) << "\n";
1011           ++NumOmitted;
1012           continue;
1013         } else if (InReg && InReg != Phys) {
1014           if (SSorRMId)
1015             DOUT << "Reusing RM#" << SSorRMId-VirtRegMap::MAX_STACK_SLOT-1;
1016           else
1017             DOUT << "Reusing SS#" << SSorRMId;
1018           DOUT << " from physreg "
1019                << TRI->getName(InReg) << " for vreg"
1020                << VirtReg <<" by copying it into physreg "
1021                << TRI->getName(Phys) << "\n";
1022
1023           // If the reloaded / remat value is available in another register,
1024           // copy it to the desired register.
1025           TII->copyRegToReg(MBB, &MI, Phys, InReg, RC, RC);
1026
1027           // This invalidates Phys.
1028           Spills.ClobberPhysReg(Phys);
1029           // Remember it's available.
1030           Spills.addAvailable(SSorRMId, Phys);
1031
1032           // Mark is killed.
1033           MachineInstr *CopyMI = prior(MII);
1034           MachineOperand *KillOpnd = CopyMI->findRegisterUseOperand(InReg);
1035           KillOpnd->setIsKill();
1036           UpdateKills(*CopyMI, RegKills, KillOps, TRI);
1037
1038           DOUT << '\t' << *CopyMI;
1039           ++NumCopified;
1040           continue;
1041         }
1042
1043         if (VRM.isReMaterialized(VirtReg)) {
1044           ReMaterialize(MBB, MII, Phys, VirtReg, TII, TRI, VRM);
1045         } else {
1046           const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
1047           TII->loadRegFromStackSlot(MBB, &MI, Phys, SSorRMId, RC);
1048           MachineInstr *LoadMI = prior(MII);
1049           VRM.addSpillSlotUse(SSorRMId, LoadMI);
1050           ++NumLoads;
1051         }
1052
1053         // This invalidates Phys.
1054         Spills.ClobberPhysReg(Phys);
1055         // Remember it's available.
1056         Spills.addAvailable(SSorRMId, Phys);
1057
1058         UpdateKills(*prior(MII), RegKills, KillOps, TRI);
1059         DOUT << '\t' << *prior(MII);
1060       }
1061     }
1062
1063     // Insert spills here if asked to.
1064     if (VRM.isSpillPt(&MI)) {
1065       std::vector<std::pair<unsigned,bool> > &SpillRegs =
1066         VRM.getSpillPtSpills(&MI);
1067       for (unsigned i = 0, e = SpillRegs.size(); i != e; ++i) {
1068         unsigned VirtReg = SpillRegs[i].first;
1069         bool isKill = SpillRegs[i].second;
1070         if (!VRM.getPreSplitReg(VirtReg))
1071           continue; // Split interval spilled again.
1072         const TargetRegisterClass *RC = RegInfo->getRegClass(VirtReg);
1073         unsigned Phys = VRM.getPhys(VirtReg);
1074         int StackSlot = VRM.getStackSlot(VirtReg);
1075         TII->storeRegToStackSlot(MBB, next(MII), Phys, isKill, StackSlot, RC);
1076         MachineInstr *StoreMI = next(MII);
1077         VRM.addSpillSlotUse(StackSlot, StoreMI);
1078         DOUT << "Store:\t" << *StoreMI;
1079         VRM.virtFolded(VirtReg, StoreMI, VirtRegMap::isMod);
1080       }
1081       NextMII = next(MII);
1082     }
1083
1084     /// ReusedOperands - Keep track of operand reuse in case we need to undo
1085     /// reuse.
1086     ReuseInfo ReusedOperands(MI, TRI);
1087     SmallVector<unsigned, 4> VirtUseOps;
1088     for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1089       MachineOperand &MO = MI.getOperand(i);
1090       if (!MO.isReg() || MO.getReg() == 0)
1091         continue;   // Ignore non-register operands.
1092       
1093       unsigned VirtReg = MO.getReg();
1094       if (TargetRegisterInfo::isPhysicalRegister(VirtReg)) {
1095         // Ignore physregs for spilling, but remember that it is used by this
1096         // function.
1097         RegInfo->setPhysRegUsed(VirtReg);
1098         continue;
1099       }
1100
1101       // We want to process implicit virtual register uses first.
1102       if (MO.isImplicit())
1103         // If the virtual register is implicitly defined, emit a implicit_def
1104         // before so scavenger knows it's "defined".
1105         VirtUseOps.insert(VirtUseOps.begin(), i);
1106       else
1107         VirtUseOps.push_back(i);
1108     }
1109
1110     // Process all of the spilled uses and all non spilled reg references.
1111     SmallVector<int, 2> PotentialDeadStoreSlots;
1112     KilledMIRegs.clear();
1113     for (unsigned j = 0, e = VirtUseOps.size(); j != e; ++j) {
1114       unsigned i = VirtUseOps[j];
1115       MachineOperand &MO = MI.getOperand(i);
1116       unsigned VirtReg = MO.getReg();
1117       assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
1118              "Not a virtual register?");
1119
1120       unsigned SubIdx = MO.getSubReg();
1121       if (VRM.isAssignedReg(VirtReg)) {
1122         // This virtual register was assigned a physreg!
1123         unsigned Phys = VRM.getPhys(VirtReg);
1124         RegInfo->setPhysRegUsed(Phys);
1125         if (MO.isDef())
1126           ReusedOperands.markClobbered(Phys);
1127         unsigned RReg = SubIdx ? TRI->getSubReg(Phys, SubIdx) : Phys;
1128         MI.getOperand(i).setReg(RReg);
1129         if (VRM.isImplicitlyDefined(VirtReg))
1130           BuildMI(MBB, &MI, MI.getDebugLoc(),
1131                   TII->get(TargetInstrInfo::IMPLICIT_DEF), RReg);
1132         continue;
1133       }
1134       
1135       // This virtual register is now known to be a spilled value.
1136       if (!MO.isUse())
1137         continue;  // Handle defs in the loop below (handle use&def here though)
1138
1139       bool DoReMat = VRM.isReMaterialized(VirtReg);
1140       int SSorRMId = DoReMat
1141         ? VRM.getReMatId(VirtReg) : VRM.getStackSlot(VirtReg);
1142       int ReuseSlot = SSorRMId;
1143
1144       // Check to see if this stack slot is available.
1145       unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SSorRMId);
1146
1147       // If this is a sub-register use, make sure the reuse register is in the
1148       // right register class. For example, for x86 not all of the 32-bit
1149       // registers have accessible sub-registers.
1150       // Similarly so for EXTRACT_SUBREG. Consider this:
1151       // EDI = op
1152       // MOV32_mr fi#1, EDI
1153       // ...
1154       //       = EXTRACT_SUBREG fi#1
1155       // fi#1 is available in EDI, but it cannot be reused because it's not in
1156       // the right register file.
1157       if (PhysReg &&
1158           (SubIdx || MI.getOpcode() == TargetInstrInfo::EXTRACT_SUBREG)) {
1159         const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
1160         if (!RC->contains(PhysReg))
1161           PhysReg = 0;
1162       }
1163
1164       if (PhysReg) {
1165         // This spilled operand might be part of a two-address operand.  If this
1166         // is the case, then changing it will necessarily require changing the 
1167         // def part of the instruction as well.  However, in some cases, we
1168         // aren't allowed to modify the reused register.  If none of these cases
1169         // apply, reuse it.
1170         bool CanReuse = true;
1171         int ti = TID.getOperandConstraint(i, TOI::TIED_TO);
1172         if (ti != -1) {
1173           // Okay, we have a two address operand.  We can reuse this physreg as
1174           // long as we are allowed to clobber the value and there isn't an
1175           // earlier def that has already clobbered the physreg.
1176           CanReuse = !ReusedOperands.isClobbered(PhysReg) &&
1177             Spills.canClobberPhysReg(PhysReg);
1178         }
1179         
1180         if (CanReuse) {
1181           // If this stack slot value is already available, reuse it!
1182           if (ReuseSlot > VirtRegMap::MAX_STACK_SLOT)
1183             DOUT << "Reusing RM#" << ReuseSlot-VirtRegMap::MAX_STACK_SLOT-1;
1184           else
1185             DOUT << "Reusing SS#" << ReuseSlot;
1186           DOUT << " from physreg "
1187                << TRI->getName(PhysReg) << " for vreg"
1188                << VirtReg <<" instead of reloading into physreg "
1189                << TRI->getName(VRM.getPhys(VirtReg)) << "\n";
1190           unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
1191           MI.getOperand(i).setReg(RReg);
1192
1193           // The only technical detail we have is that we don't know that
1194           // PhysReg won't be clobbered by a reloaded stack slot that occurs
1195           // later in the instruction.  In particular, consider 'op V1, V2'.
1196           // If V1 is available in physreg R0, we would choose to reuse it
1197           // here, instead of reloading it into the register the allocator
1198           // indicated (say R1).  However, V2 might have to be reloaded
1199           // later, and it might indicate that it needs to live in R0.  When
1200           // this occurs, we need to have information available that
1201           // indicates it is safe to use R1 for the reload instead of R0.
1202           //
1203           // To further complicate matters, we might conflict with an alias,
1204           // or R0 and R1 might not be compatible with each other.  In this
1205           // case, we actually insert a reload for V1 in R1, ensuring that
1206           // we can get at R0 or its alias.
1207           ReusedOperands.addReuse(i, ReuseSlot, PhysReg,
1208                                   VRM.getPhys(VirtReg), VirtReg);
1209           if (ti != -1)
1210             // Only mark it clobbered if this is a use&def operand.
1211             ReusedOperands.markClobbered(PhysReg);
1212           ++NumReused;
1213
1214           if (MI.getOperand(i).isKill() &&
1215               ReuseSlot <= VirtRegMap::MAX_STACK_SLOT) {
1216
1217             // The store of this spilled value is potentially dead, but we
1218             // won't know for certain until we've confirmed that the re-use
1219             // above is valid, which means waiting until the other operands
1220             // are processed. For now we just track the spill slot, we'll
1221             // remove it after the other operands are processed if valid.
1222
1223             PotentialDeadStoreSlots.push_back(ReuseSlot);
1224           }
1225
1226           // Mark is isKill if it's there no other uses of the same virtual
1227           // register and it's not a two-address operand. IsKill will be
1228           // unset if reg is reused.
1229           if (ti == -1 && KilledMIRegs.count(VirtReg) == 0) {
1230             MI.getOperand(i).setIsKill();
1231             KilledMIRegs.insert(VirtReg);
1232           }
1233
1234           continue;
1235         }  // CanReuse
1236         
1237         // Otherwise we have a situation where we have a two-address instruction
1238         // whose mod/ref operand needs to be reloaded.  This reload is already
1239         // available in some register "PhysReg", but if we used PhysReg as the
1240         // operand to our 2-addr instruction, the instruction would modify
1241         // PhysReg.  This isn't cool if something later uses PhysReg and expects
1242         // to get its initial value.
1243         //
1244         // To avoid this problem, and to avoid doing a load right after a store,
1245         // we emit a copy from PhysReg into the designated register for this
1246         // operand.
1247         unsigned DesignatedReg = VRM.getPhys(VirtReg);
1248         assert(DesignatedReg && "Must map virtreg to physreg!");
1249
1250         // Note that, if we reused a register for a previous operand, the
1251         // register we want to reload into might not actually be
1252         // available.  If this occurs, use the register indicated by the
1253         // reuser.
1254         if (ReusedOperands.hasReuses())
1255           DesignatedReg = ReusedOperands.GetRegForReload(DesignatedReg, &MI, 
1256                                Spills, MaybeDeadStores, RegKills, KillOps, VRM);
1257         
1258         // If the mapped designated register is actually the physreg we have
1259         // incoming, we don't need to inserted a dead copy.
1260         if (DesignatedReg == PhysReg) {
1261           // If this stack slot value is already available, reuse it!
1262           if (ReuseSlot > VirtRegMap::MAX_STACK_SLOT)
1263             DOUT << "Reusing RM#" << ReuseSlot-VirtRegMap::MAX_STACK_SLOT-1;
1264           else
1265             DOUT << "Reusing SS#" << ReuseSlot;
1266           DOUT << " from physreg " << TRI->getName(PhysReg)
1267                << " for vreg" << VirtReg
1268                << " instead of reloading into same physreg.\n";
1269           unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
1270           MI.getOperand(i).setReg(RReg);
1271           ReusedOperands.markClobbered(RReg);
1272           ++NumReused;
1273           continue;
1274         }
1275         
1276         const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
1277         RegInfo->setPhysRegUsed(DesignatedReg);
1278         ReusedOperands.markClobbered(DesignatedReg);
1279         TII->copyRegToReg(MBB, &MI, DesignatedReg, PhysReg, RC, RC);
1280
1281         MachineInstr *CopyMI = prior(MII);
1282         UpdateKills(*CopyMI, RegKills, KillOps, TRI);
1283
1284         // This invalidates DesignatedReg.
1285         Spills.ClobberPhysReg(DesignatedReg);
1286         
1287         Spills.addAvailable(ReuseSlot, DesignatedReg);
1288         unsigned RReg =
1289           SubIdx ? TRI->getSubReg(DesignatedReg, SubIdx) : DesignatedReg;
1290         MI.getOperand(i).setReg(RReg);
1291         DOUT << '\t' << *prior(MII);
1292         ++NumReused;
1293         continue;
1294       } // if (PhysReg)
1295       
1296       // Otherwise, reload it and remember that we have it.
1297       PhysReg = VRM.getPhys(VirtReg);
1298       assert(PhysReg && "Must map virtreg to physreg!");
1299
1300       // Note that, if we reused a register for a previous operand, the
1301       // register we want to reload into might not actually be
1302       // available.  If this occurs, use the register indicated by the
1303       // reuser.
1304       if (ReusedOperands.hasReuses())
1305         PhysReg = ReusedOperands.GetRegForReload(PhysReg, &MI, 
1306                                Spills, MaybeDeadStores, RegKills, KillOps, VRM);
1307       
1308       RegInfo->setPhysRegUsed(PhysReg);
1309       ReusedOperands.markClobbered(PhysReg);
1310       if (DoReMat) {
1311         ReMaterialize(MBB, MII, PhysReg, VirtReg, TII, TRI, VRM);
1312       } else {
1313         const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
1314         TII->loadRegFromStackSlot(MBB, &MI, PhysReg, SSorRMId, RC);
1315         MachineInstr *LoadMI = prior(MII);
1316         VRM.addSpillSlotUse(SSorRMId, LoadMI);
1317         ++NumLoads;
1318       }
1319       // This invalidates PhysReg.
1320       Spills.ClobberPhysReg(PhysReg);
1321
1322       // Any stores to this stack slot are not dead anymore.
1323       if (!DoReMat)
1324         MaybeDeadStores[SSorRMId] = NULL;
1325       Spills.addAvailable(SSorRMId, PhysReg);
1326       // Assumes this is the last use. IsKill will be unset if reg is reused
1327       // unless it's a two-address operand.
1328       if (TID.getOperandConstraint(i, TOI::TIED_TO) == -1 &&
1329           KilledMIRegs.count(VirtReg) == 0) {
1330         MI.getOperand(i).setIsKill();
1331         KilledMIRegs.insert(VirtReg);
1332       }
1333       unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
1334       MI.getOperand(i).setReg(RReg);
1335       UpdateKills(*prior(MII), RegKills, KillOps, TRI);
1336       DOUT << '\t' << *prior(MII);
1337     }
1338
1339     // Ok - now we can remove stores that have been confirmed dead.
1340     for (unsigned j = 0, e = PotentialDeadStoreSlots.size(); j != e; ++j) {
1341       // This was the last use and the spilled value is still available
1342       // for reuse. That means the spill was unnecessary!
1343       int PDSSlot = PotentialDeadStoreSlots[j];
1344       MachineInstr* DeadStore = MaybeDeadStores[PDSSlot];
1345       if (DeadStore) {
1346         DOUT << "Removed dead store:\t" << *DeadStore;
1347         InvalidateKills(*DeadStore, RegKills, KillOps);
1348         VRM.RemoveMachineInstrFromMaps(DeadStore);
1349         MBB.erase(DeadStore);
1350         MaybeDeadStores[PDSSlot] = NULL;
1351         ++NumDSE;
1352       }
1353     }
1354
1355
1356     DOUT << '\t' << MI;
1357
1358
1359     // If we have folded references to memory operands, make sure we clear all
1360     // physical registers that may contain the value of the spilled virtual
1361     // register
1362     SmallSet<int, 2> FoldedSS;
1363     for (tie(I, End) = VRM.getFoldedVirts(&MI); I != End; ) {
1364       unsigned VirtReg = I->second.first;
1365       VirtRegMap::ModRef MR = I->second.second;
1366       DOUT << "Folded vreg: " << VirtReg << "  MR: " << MR;
1367
1368       // MI2VirtMap be can updated which invalidate the iterator.
1369       // Increment the iterator first.
1370       ++I;
1371       int SS = VRM.getStackSlot(VirtReg);
1372       if (SS == VirtRegMap::NO_STACK_SLOT)
1373         continue;
1374       FoldedSS.insert(SS);
1375       DOUT << " - StackSlot: " << SS << "\n";
1376       
1377       // If this folded instruction is just a use, check to see if it's a
1378       // straight load from the virt reg slot.
1379       if ((MR & VirtRegMap::isRef) && !(MR & VirtRegMap::isMod)) {
1380         int FrameIdx;
1381         unsigned DestReg = TII->isLoadFromStackSlot(&MI, FrameIdx);
1382         if (DestReg && FrameIdx == SS) {
1383           // If this spill slot is available, turn it into a copy (or nothing)
1384           // instead of leaving it as a load!
1385           if (unsigned InReg = Spills.getSpillSlotOrReMatPhysReg(SS)) {
1386             DOUT << "Promoted Load To Copy: " << MI;
1387             if (DestReg != InReg) {
1388               const TargetRegisterClass *RC = RegInfo->getRegClass(VirtReg);
1389               TII->copyRegToReg(MBB, &MI, DestReg, InReg, RC, RC);
1390               MachineOperand *DefMO = MI.findRegisterDefOperand(DestReg);
1391               unsigned SubIdx = DefMO->getSubReg();
1392               // Revisit the copy so we make sure to notice the effects of the
1393               // operation on the destreg (either needing to RA it if it's 
1394               // virtual or needing to clobber any values if it's physical).
1395               NextMII = &MI;
1396               --NextMII;  // backtrack to the copy.
1397               // Propagate the sub-register index over.
1398               if (SubIdx) {
1399                 DefMO = NextMII->findRegisterDefOperand(DestReg);
1400                 DefMO->setSubReg(SubIdx);
1401               }
1402
1403               // Mark is killed.
1404               MachineOperand *KillOpnd = NextMII->findRegisterUseOperand(InReg);
1405               KillOpnd->setIsKill();
1406
1407               BackTracked = true;
1408             } else {
1409               DOUT << "Removing now-noop copy: " << MI;
1410               // Unset last kill since it's being reused.
1411               InvalidateKill(InReg, RegKills, KillOps);
1412               Spills.disallowClobberPhysReg(InReg);
1413             }
1414
1415             InvalidateKills(MI, RegKills, KillOps);
1416             VRM.RemoveMachineInstrFromMaps(&MI);
1417             MBB.erase(&MI);
1418             Erased = true;
1419             goto ProcessNextInst;
1420           }
1421         } else {
1422           unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SS);
1423           SmallVector<MachineInstr*, 4> NewMIs;
1424           if (PhysReg &&
1425               TII->unfoldMemoryOperand(MF, &MI, PhysReg, false, false, NewMIs)) {
1426             MBB.insert(MII, NewMIs[0]);
1427             InvalidateKills(MI, RegKills, KillOps);
1428             VRM.RemoveMachineInstrFromMaps(&MI);
1429             MBB.erase(&MI);
1430             Erased = true;
1431             --NextMII;  // backtrack to the unfolded instruction.
1432             BackTracked = true;
1433             goto ProcessNextInst;
1434           }
1435         }
1436       }
1437
1438       // If this reference is not a use, any previous store is now dead.
1439       // Otherwise, the store to this stack slot is not dead anymore.
1440       MachineInstr* DeadStore = MaybeDeadStores[SS];
1441       if (DeadStore) {
1442         bool isDead = !(MR & VirtRegMap::isRef);
1443         MachineInstr *NewStore = NULL;
1444         if (MR & VirtRegMap::isModRef) {
1445           unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SS);
1446           SmallVector<MachineInstr*, 4> NewMIs;
1447           // We can reuse this physreg as long as we are allowed to clobber
1448           // the value and there isn't an earlier def that has already clobbered
1449           // the physreg.
1450           if (PhysReg &&
1451               !ReusedOperands.isClobbered(PhysReg) &&
1452               Spills.canClobberPhysReg(PhysReg) &&
1453               !TII->isStoreToStackSlot(&MI, SS)) { // Not profitable!
1454             MachineOperand *KillOpnd =
1455               DeadStore->findRegisterUseOperand(PhysReg, true);
1456             // Note, if the store is storing a sub-register, it's possible the
1457             // super-register is needed below.
1458             if (KillOpnd && !KillOpnd->getSubReg() &&
1459                 TII->unfoldMemoryOperand(MF, &MI, PhysReg, false, true,NewMIs)){
1460               MBB.insert(MII, NewMIs[0]);
1461               NewStore = NewMIs[1];
1462               MBB.insert(MII, NewStore);
1463               VRM.addSpillSlotUse(SS, NewStore);
1464               InvalidateKills(MI, RegKills, KillOps);
1465               VRM.RemoveMachineInstrFromMaps(&MI);
1466               MBB.erase(&MI);
1467               Erased = true;
1468               --NextMII;
1469               --NextMII;  // backtrack to the unfolded instruction.
1470               BackTracked = true;
1471               isDead = true;
1472               ++NumSUnfold;
1473             }
1474           }
1475         }
1476
1477         if (isDead) {  // Previous store is dead.
1478           // If we get here, the store is dead, nuke it now.
1479           DOUT << "Removed dead store:\t" << *DeadStore;
1480           InvalidateKills(*DeadStore, RegKills, KillOps);
1481           VRM.RemoveMachineInstrFromMaps(DeadStore);
1482           MBB.erase(DeadStore);
1483           if (!NewStore)
1484             ++NumDSE;
1485         }
1486
1487         MaybeDeadStores[SS] = NULL;
1488         if (NewStore) {
1489           // Treat this store as a spill merged into a copy. That makes the
1490           // stack slot value available.
1491           VRM.virtFolded(VirtReg, NewStore, VirtRegMap::isMod);
1492           goto ProcessNextInst;
1493         }
1494       }
1495
1496       // If the spill slot value is available, and this is a new definition of
1497       // the value, the value is not available anymore.
1498       if (MR & VirtRegMap::isMod) {
1499         // Notice that the value in this stack slot has been modified.
1500         Spills.ModifyStackSlotOrReMat(SS);
1501         
1502         // If this is *just* a mod of the value, check to see if this is just a
1503         // store to the spill slot (i.e. the spill got merged into the copy). If
1504         // so, realize that the vreg is available now, and add the store to the
1505         // MaybeDeadStore info.
1506         int StackSlot;
1507         if (!(MR & VirtRegMap::isRef)) {
1508           if (unsigned SrcReg = TII->isStoreToStackSlot(&MI, StackSlot)) {
1509             assert(TargetRegisterInfo::isPhysicalRegister(SrcReg) &&
1510                    "Src hasn't been allocated yet?");
1511
1512             if (CommuteToFoldReload(MBB, MII, VirtReg, SrcReg, StackSlot,
1513                                     Spills, RegKills, KillOps, TRI, VRM)) {
1514               NextMII = next(MII);
1515               BackTracked = true;
1516               goto ProcessNextInst;
1517             }
1518
1519             // Okay, this is certainly a store of SrcReg to [StackSlot].  Mark
1520             // this as a potentially dead store in case there is a subsequent
1521             // store into the stack slot without a read from it.
1522             MaybeDeadStores[StackSlot] = &MI;
1523
1524             // If the stack slot value was previously available in some other
1525             // register, change it now.  Otherwise, make the register
1526             // available in PhysReg.
1527             Spills.addAvailable(StackSlot, SrcReg, MI.killsRegister(SrcReg));
1528           }
1529         }
1530       }
1531     }
1532
1533     // Process all of the spilled defs.
1534     for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1535       MachineOperand &MO = MI.getOperand(i);
1536       if (!(MO.isReg() && MO.getReg() && MO.isDef()))
1537         continue;
1538
1539       unsigned VirtReg = MO.getReg();
1540       if (!TargetRegisterInfo::isVirtualRegister(VirtReg)) {
1541         // Check to see if this is a noop copy.  If so, eliminate the
1542         // instruction before considering the dest reg to be changed.
1543         unsigned Src, Dst, SrcSR, DstSR;
1544         if (TII->isMoveInstr(MI, Src, Dst, SrcSR, DstSR) && Src == Dst) {
1545           ++NumDCE;
1546           DOUT << "Removing now-noop copy: " << MI;
1547           SmallVector<unsigned, 2> KillRegs;
1548           InvalidateKills(MI, RegKills, KillOps, &KillRegs);
1549           if (MO.isDead() && !KillRegs.empty()) {
1550             // Source register or an implicit super/sub-register use is killed.
1551             assert(KillRegs[0] == Dst ||
1552                    TRI->isSubRegister(KillRegs[0], Dst) ||
1553                    TRI->isSuperRegister(KillRegs[0], Dst));
1554             // Last def is now dead.
1555             TransferDeadness(&MBB, Dist, Src, RegKills, KillOps);
1556           }
1557           VRM.RemoveMachineInstrFromMaps(&MI);
1558           MBB.erase(&MI);
1559           Erased = true;
1560           Spills.disallowClobberPhysReg(VirtReg);
1561           goto ProcessNextInst;
1562         }
1563           
1564         // If it's not a no-op copy, it clobbers the value in the destreg.
1565         Spills.ClobberPhysReg(VirtReg);
1566         ReusedOperands.markClobbered(VirtReg);
1567  
1568         // Check to see if this instruction is a load from a stack slot into
1569         // a register.  If so, this provides the stack slot value in the reg.
1570         int FrameIdx;
1571         if (unsigned DestReg = TII->isLoadFromStackSlot(&MI, FrameIdx)) {
1572           assert(DestReg == VirtReg && "Unknown load situation!");
1573
1574           // If it is a folded reference, then it's not safe to clobber.
1575           bool Folded = FoldedSS.count(FrameIdx);
1576           // Otherwise, if it wasn't available, remember that it is now!
1577           Spills.addAvailable(FrameIdx, DestReg, !Folded);
1578           goto ProcessNextInst;
1579         }
1580             
1581         continue;
1582       }
1583
1584       unsigned SubIdx = MO.getSubReg();
1585       bool DoReMat = VRM.isReMaterialized(VirtReg);
1586       if (DoReMat)
1587         ReMatDefs.insert(&MI);
1588
1589       // The only vregs left are stack slot definitions.
1590       int StackSlot = VRM.getStackSlot(VirtReg);
1591       const TargetRegisterClass *RC = RegInfo->getRegClass(VirtReg);
1592
1593       // If this def is part of a two-address operand, make sure to execute
1594       // the store from the correct physical register.
1595       unsigned PhysReg;
1596       int TiedOp = MI.getDesc().findTiedToSrcOperand(i);
1597       if (TiedOp != -1) {
1598         PhysReg = MI.getOperand(TiedOp).getReg();
1599         if (SubIdx) {
1600           unsigned SuperReg = findSuperReg(RC, PhysReg, SubIdx, TRI);
1601           assert(SuperReg && TRI->getSubReg(SuperReg, SubIdx) == PhysReg &&
1602                  "Can't find corresponding super-register!");
1603           PhysReg = SuperReg;
1604         }
1605       } else {
1606         PhysReg = VRM.getPhys(VirtReg);
1607         if (ReusedOperands.isClobbered(PhysReg)) {
1608           // Another def has taken the assigned physreg. It must have been a
1609           // use&def which got it due to reuse. Undo the reuse!
1610           PhysReg = ReusedOperands.GetRegForReload(PhysReg, &MI, 
1611                                Spills, MaybeDeadStores, RegKills, KillOps, VRM);
1612         }
1613       }
1614
1615       assert(PhysReg && "VR not assigned a physical register?");
1616       RegInfo->setPhysRegUsed(PhysReg);
1617       unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
1618       ReusedOperands.markClobbered(RReg);
1619       MI.getOperand(i).setReg(RReg);
1620
1621       if (!MO.isDead()) {
1622         MachineInstr *&LastStore = MaybeDeadStores[StackSlot];
1623         SpillRegToStackSlot(MBB, MII, -1, PhysReg, StackSlot, RC, true,
1624                           LastStore, Spills, ReMatDefs, RegKills, KillOps, VRM);
1625         NextMII = next(MII);
1626
1627         // Check to see if this is a noop copy.  If so, eliminate the
1628         // instruction before considering the dest reg to be changed.
1629         {
1630           unsigned Src, Dst, SrcSR, DstSR;
1631           if (TII->isMoveInstr(MI, Src, Dst, SrcSR, DstSR) && Src == Dst) {
1632             ++NumDCE;
1633             DOUT << "Removing now-noop copy: " << MI;
1634             InvalidateKills(MI, RegKills, KillOps);
1635             VRM.RemoveMachineInstrFromMaps(&MI);
1636             MBB.erase(&MI);
1637             Erased = true;
1638             UpdateKills(*LastStore, RegKills, KillOps, TRI);
1639             goto ProcessNextInst;
1640           }
1641         }
1642       }    
1643     }
1644   ProcessNextInst:
1645     DistanceMap.insert(std::make_pair(&MI, Dist++));
1646     if (!Erased && !BackTracked) {
1647       for (MachineBasicBlock::iterator II = &MI; II != NextMII; ++II)
1648         UpdateKills(*II, RegKills, KillOps, TRI);
1649     }
1650     MII = NextMII;
1651   }
1652
1653 }
1654
1655 llvm::Spiller* llvm::createSpiller() {
1656   switch (SpillerOpt) {
1657   default: assert(0 && "Unreachable!");
1658   case local:
1659     return new LocalSpiller();
1660   case simple:
1661     return new SimpleSpiller();
1662   }
1663 }