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