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