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