abaa8bd212e94635cb84b48c6eb6d83b0112f432
[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   /// TransferDeadness - A identity copy definition is dead and it's being
1348   /// removed. Find the last def or use and mark it as dead / kill.
1349   void TransferDeadness(MachineBasicBlock *MBB, unsigned CurDist,
1350                         unsigned Reg, BitVector &RegKills,
1351                         std::vector<MachineOperand*> &KillOps,
1352                         VirtRegMap &VRM) {
1353     SmallPtrSet<MachineInstr*, 4> Seens;
1354     SmallVector<std::pair<MachineInstr*, int>,8> Refs;
1355     for (MachineRegisterInfo::reg_iterator RI = RegInfo->reg_begin(Reg),
1356            RE = RegInfo->reg_end(); RI != RE; ++RI) {
1357       MachineInstr *UDMI = &*RI;
1358       if (UDMI->getParent() != MBB)
1359         continue;
1360       DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(UDMI);
1361       if (DI == DistanceMap.end() || DI->second > CurDist)
1362         continue;
1363       if (Seens.insert(UDMI))
1364         Refs.push_back(std::make_pair(UDMI, DI->second));
1365     }
1366
1367     if (Refs.empty())
1368       return;
1369     std::sort(Refs.begin(), Refs.end(), RefSorter());
1370
1371     while (!Refs.empty()) {
1372       MachineInstr *LastUDMI = Refs.back().first;
1373       Refs.pop_back();
1374
1375       MachineOperand *LastUD = NULL;
1376       for (unsigned i = 0, e = LastUDMI->getNumOperands(); i != e; ++i) {
1377         MachineOperand &MO = LastUDMI->getOperand(i);
1378         if (!MO.isReg() || MO.getReg() != Reg)
1379           continue;
1380         if (!LastUD || (LastUD->isUse() && MO.isDef()))
1381           LastUD = &MO;
1382         if (LastUDMI->isRegTiedToDefOperand(i))
1383           break;
1384       }
1385       if (LastUD->isDef()) {
1386         // If the instruction has no side effect, delete it and propagate
1387         // backward further. Otherwise, mark is dead and we are done.
1388         const TargetInstrDesc &TID = LastUDMI->getDesc();
1389         if (TID.mayStore() || TID.isCall() || TID.isTerminator() ||
1390             TID.hasUnmodeledSideEffects()) {
1391           LastUD->setIsDead();
1392           break;
1393         }
1394         VRM.RemoveMachineInstrFromMaps(LastUDMI);
1395         MBB->erase(LastUDMI);
1396       } else {
1397         LastUD->setIsKill();
1398         RegKills.set(Reg);
1399         KillOps[Reg] = LastUD;
1400         break;
1401       }
1402     }
1403   }
1404
1405   /// rewriteMBB - Keep track of which spills are available even after the
1406   /// register allocator is done with them.  If possible, avid reloading vregs.
1407   void RewriteMBB(MachineBasicBlock &MBB, VirtRegMap &VRM,
1408                   LiveIntervals *LIs,
1409                   AvailableSpills &Spills, BitVector &RegKills,
1410                   std::vector<MachineOperand*> &KillOps) {
1411
1412     DOUT << "\n**** Local spiller rewriting MBB '"
1413          << MBB.getBasicBlock()->getName() << "':\n";
1414
1415     MachineFunction &MF = *MBB.getParent();
1416     
1417     // MaybeDeadStores - When we need to write a value back into a stack slot,
1418     // keep track of the inserted store.  If the stack slot value is never read
1419     // (because the value was used from some available register, for example), and
1420     // subsequently stored to, the original store is dead.  This map keeps track
1421     // of inserted stores that are not used.  If we see a subsequent store to the
1422     // same stack slot, the original store is deleted.
1423     std::vector<MachineInstr*> MaybeDeadStores;
1424     MaybeDeadStores.resize(MF.getFrameInfo()->getObjectIndexEnd(), NULL);
1425
1426     // ReMatDefs - These are rematerializable def MIs which are not deleted.
1427     SmallSet<MachineInstr*, 4> ReMatDefs;
1428
1429     // Clear kill info.
1430     SmallSet<unsigned, 2> KilledMIRegs;
1431     RegKills.reset();
1432     KillOps.clear();
1433     KillOps.resize(TRI->getNumRegs(), NULL);
1434
1435     unsigned Dist = 0;
1436     DistanceMap.clear();
1437     for (MachineBasicBlock::iterator MII = MBB.begin(), E = MBB.end();
1438          MII != E; ) {
1439       MachineBasicBlock::iterator NextMII = next(MII);
1440
1441       VirtRegMap::MI2VirtMapTy::const_iterator I, End;
1442       bool Erased = false;
1443       bool BackTracked = false;
1444       if (OptimizeByUnfold(MBB, MII,
1445                            MaybeDeadStores, Spills, RegKills, KillOps, VRM))
1446         NextMII = next(MII);
1447
1448       MachineInstr &MI = *MII;
1449
1450       if (VRM.hasEmergencySpills(&MI)) {
1451         // Spill physical register(s) in the rare case the allocator has run out
1452         // of registers to allocate.
1453         SmallSet<int, 4> UsedSS;
1454         std::vector<unsigned> &EmSpills = VRM.getEmergencySpills(&MI);
1455         for (unsigned i = 0, e = EmSpills.size(); i != e; ++i) {
1456           unsigned PhysReg = EmSpills[i];
1457           const TargetRegisterClass *RC =
1458             TRI->getPhysicalRegisterRegClass(PhysReg);
1459           assert(RC && "Unable to determine register class!");
1460           int SS = VRM.getEmergencySpillSlot(RC);
1461           if (UsedSS.count(SS))
1462             llvm_unreachable("Need to spill more than one physical registers!");
1463           UsedSS.insert(SS);
1464           TII->storeRegToStackSlot(MBB, MII, PhysReg, true, SS, RC);
1465           MachineInstr *StoreMI = prior(MII);
1466           VRM.addSpillSlotUse(SS, StoreMI);
1467           TII->loadRegFromStackSlot(MBB, next(MII), PhysReg, SS, RC);
1468           MachineInstr *LoadMI = next(MII);
1469           VRM.addSpillSlotUse(SS, LoadMI);
1470           ++NumPSpills;
1471         }
1472         NextMII = next(MII);
1473       }
1474
1475       // Insert restores here if asked to.
1476       if (VRM.isRestorePt(&MI)) {
1477         std::vector<unsigned> &RestoreRegs = VRM.getRestorePtRestores(&MI);
1478         for (unsigned i = 0, e = RestoreRegs.size(); i != e; ++i) {
1479           unsigned VirtReg = RestoreRegs[e-i-1];  // Reverse order.
1480           if (!VRM.getPreSplitReg(VirtReg))
1481             continue; // Split interval spilled again.
1482           unsigned Phys = VRM.getPhys(VirtReg);
1483           RegInfo->setPhysRegUsed(Phys);
1484
1485           // Check if the value being restored if available. If so, it must be
1486           // from a predecessor BB that fallthrough into this BB. We do not
1487           // expect:
1488           // BB1:
1489           // r1 = load fi#1
1490           // ...
1491           //    = r1<kill>
1492           // ... # r1 not clobbered
1493           // ...
1494           //    = load fi#1
1495           bool DoReMat = VRM.isReMaterialized(VirtReg);
1496           int SSorRMId = DoReMat
1497             ? VRM.getReMatId(VirtReg) : VRM.getStackSlot(VirtReg);
1498           const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
1499           unsigned InReg = Spills.getSpillSlotOrReMatPhysReg(SSorRMId);
1500           if (InReg == Phys) {
1501             // If the value is already available in the expected register, save
1502             // a reload / remat.
1503             if (SSorRMId)
1504               DOUT << "Reusing RM#" << SSorRMId-VirtRegMap::MAX_STACK_SLOT-1;
1505             else
1506               DOUT << "Reusing SS#" << SSorRMId;
1507             DOUT << " from physreg "
1508                  << TRI->getName(InReg) << " for vreg"
1509                  << VirtReg <<" instead of reloading into physreg "
1510                  << TRI->getName(Phys) << "\n";
1511             ++NumOmitted;
1512             continue;
1513           } else if (InReg && InReg != Phys) {
1514             if (SSorRMId)
1515               DOUT << "Reusing RM#" << SSorRMId-VirtRegMap::MAX_STACK_SLOT-1;
1516             else
1517               DOUT << "Reusing SS#" << SSorRMId;
1518             DOUT << " from physreg "
1519                  << TRI->getName(InReg) << " for vreg"
1520                  << VirtReg <<" by copying it into physreg "
1521                  << TRI->getName(Phys) << "\n";
1522
1523             // If the reloaded / remat value is available in another register,
1524             // copy it to the desired register.
1525             TII->copyRegToReg(MBB, &MI, Phys, InReg, RC, RC);
1526
1527             // This invalidates Phys.
1528             Spills.ClobberPhysReg(Phys);
1529             // Remember it's available.
1530             Spills.addAvailable(SSorRMId, Phys);
1531
1532             // Mark is killed.
1533             MachineInstr *CopyMI = prior(MII);
1534             MachineOperand *KillOpnd = CopyMI->findRegisterUseOperand(InReg);
1535             KillOpnd->setIsKill();
1536             UpdateKills(*CopyMI, TRI, RegKills, KillOps);
1537
1538             DOUT << '\t' << *CopyMI;
1539             ++NumCopified;
1540             continue;
1541           }
1542
1543           if (VRM.isReMaterialized(VirtReg)) {
1544             ReMaterialize(MBB, MII, Phys, VirtReg, TII, TRI, VRM);
1545           } else {
1546             const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
1547             TII->loadRegFromStackSlot(MBB, &MI, Phys, SSorRMId, RC);
1548             MachineInstr *LoadMI = prior(MII);
1549             VRM.addSpillSlotUse(SSorRMId, LoadMI);
1550             ++NumLoads;
1551           }
1552
1553           // This invalidates Phys.
1554           Spills.ClobberPhysReg(Phys);
1555           // Remember it's available.
1556           Spills.addAvailable(SSorRMId, Phys);
1557
1558           UpdateKills(*prior(MII), TRI, RegKills, KillOps);
1559           DOUT << '\t' << *prior(MII);
1560         }
1561       }
1562
1563       // Insert spills here if asked to.
1564       if (VRM.isSpillPt(&MI)) {
1565         std::vector<std::pair<unsigned,bool> > &SpillRegs =
1566           VRM.getSpillPtSpills(&MI);
1567         for (unsigned i = 0, e = SpillRegs.size(); i != e; ++i) {
1568           unsigned VirtReg = SpillRegs[i].first;
1569           bool isKill = SpillRegs[i].second;
1570           if (!VRM.getPreSplitReg(VirtReg))
1571             continue; // Split interval spilled again.
1572           const TargetRegisterClass *RC = RegInfo->getRegClass(VirtReg);
1573           unsigned Phys = VRM.getPhys(VirtReg);
1574           int StackSlot = VRM.getStackSlot(VirtReg);
1575           TII->storeRegToStackSlot(MBB, next(MII), Phys, isKill, StackSlot, RC);
1576           MachineInstr *StoreMI = next(MII);
1577           VRM.addSpillSlotUse(StackSlot, StoreMI);
1578           DOUT << "Store:\t" << *StoreMI;
1579           VRM.virtFolded(VirtReg, StoreMI, VirtRegMap::isMod);
1580         }
1581         NextMII = next(MII);
1582       }
1583
1584       /// ReusedOperands - Keep track of operand reuse in case we need to undo
1585       /// reuse.
1586       ReuseInfo ReusedOperands(MI, TRI);
1587       SmallVector<unsigned, 4> VirtUseOps;
1588       for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1589         MachineOperand &MO = MI.getOperand(i);
1590         if (!MO.isReg() || MO.getReg() == 0)
1591           continue;   // Ignore non-register operands.
1592         
1593         unsigned VirtReg = MO.getReg();
1594         if (TargetRegisterInfo::isPhysicalRegister(VirtReg)) {
1595           // Ignore physregs for spilling, but remember that it is used by this
1596           // function.
1597           RegInfo->setPhysRegUsed(VirtReg);
1598           continue;
1599         }
1600
1601         // We want to process implicit virtual register uses first.
1602         if (MO.isImplicit())
1603           // If the virtual register is implicitly defined, emit a implicit_def
1604           // before so scavenger knows it's "defined".
1605           // FIXME: This is a horrible hack done the by register allocator to
1606           // remat a definition with virtual register operand.
1607           VirtUseOps.insert(VirtUseOps.begin(), i);
1608         else
1609           VirtUseOps.push_back(i);
1610       }
1611
1612       // Process all of the spilled uses and all non spilled reg references.
1613       SmallVector<int, 2> PotentialDeadStoreSlots;
1614       KilledMIRegs.clear();
1615       for (unsigned j = 0, e = VirtUseOps.size(); j != e; ++j) {
1616         unsigned i = VirtUseOps[j];
1617         MachineOperand &MO = MI.getOperand(i);
1618         unsigned VirtReg = MO.getReg();
1619         assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
1620                "Not a virtual register?");
1621
1622         unsigned SubIdx = MO.getSubReg();
1623         if (VRM.isAssignedReg(VirtReg)) {
1624           // This virtual register was assigned a physreg!
1625           unsigned Phys = VRM.getPhys(VirtReg);
1626           RegInfo->setPhysRegUsed(Phys);
1627           if (MO.isDef())
1628             ReusedOperands.markClobbered(Phys);
1629           unsigned RReg = SubIdx ? TRI->getSubReg(Phys, SubIdx) : Phys;
1630           MI.getOperand(i).setReg(RReg);
1631           MI.getOperand(i).setSubReg(0);
1632           if (VRM.isImplicitlyDefined(VirtReg))
1633             // FIXME: Is this needed?
1634             BuildMI(MBB, &MI, MI.getDebugLoc(),
1635                     TII->get(TargetInstrInfo::IMPLICIT_DEF), RReg);
1636           continue;
1637         }
1638         
1639         // This virtual register is now known to be a spilled value.
1640         if (!MO.isUse())
1641           continue;  // Handle defs in the loop below (handle use&def here though)
1642
1643         bool AvoidReload = MO.isUndef();
1644         // Check if it is defined by an implicit def. It should not be spilled.
1645         // Note, this is for correctness reason. e.g.
1646         // 8   %reg1024<def> = IMPLICIT_DEF
1647         // 12  %reg1024<def> = INSERT_SUBREG %reg1024<kill>, %reg1025, 2
1648         // The live range [12, 14) are not part of the r1024 live interval since
1649         // it's defined by an implicit def. It will not conflicts with live
1650         // interval of r1025. Now suppose both registers are spilled, you can
1651         // easily see a situation where both registers are reloaded before
1652         // the INSERT_SUBREG and both target registers that would overlap.
1653         bool DoReMat = VRM.isReMaterialized(VirtReg);
1654         int SSorRMId = DoReMat
1655           ? VRM.getReMatId(VirtReg) : VRM.getStackSlot(VirtReg);
1656         int ReuseSlot = SSorRMId;
1657
1658         // Check to see if this stack slot is available.
1659         unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SSorRMId);
1660
1661         // If this is a sub-register use, make sure the reuse register is in the
1662         // right register class. For example, for x86 not all of the 32-bit
1663         // registers have accessible sub-registers.
1664         // Similarly so for EXTRACT_SUBREG. Consider this:
1665         // EDI = op
1666         // MOV32_mr fi#1, EDI
1667         // ...
1668         //       = EXTRACT_SUBREG fi#1
1669         // fi#1 is available in EDI, but it cannot be reused because it's not in
1670         // the right register file.
1671         if (PhysReg && !AvoidReload &&
1672             (SubIdx || MI.getOpcode() == TargetInstrInfo::EXTRACT_SUBREG)) {
1673           const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
1674           if (!RC->contains(PhysReg))
1675             PhysReg = 0;
1676         }
1677
1678         if (PhysReg && !AvoidReload) {
1679           // This spilled operand might be part of a two-address operand.  If this
1680           // is the case, then changing it will necessarily require changing the 
1681           // def part of the instruction as well.  However, in some cases, we
1682           // aren't allowed to modify the reused register.  If none of these cases
1683           // apply, reuse it.
1684           bool CanReuse = true;
1685           bool isTied = MI.isRegTiedToDefOperand(i);
1686           if (isTied) {
1687             // Okay, we have a two address operand.  We can reuse this physreg as
1688             // long as we are allowed to clobber the value and there isn't an
1689             // earlier def that has already clobbered the physreg.
1690             CanReuse = !ReusedOperands.isClobbered(PhysReg) &&
1691               Spills.canClobberPhysReg(PhysReg);
1692           }
1693           
1694           if (CanReuse) {
1695             // If this stack slot value is already available, reuse it!
1696             if (ReuseSlot > VirtRegMap::MAX_STACK_SLOT)
1697               DOUT << "Reusing RM#" << ReuseSlot-VirtRegMap::MAX_STACK_SLOT-1;
1698             else
1699               DOUT << "Reusing SS#" << ReuseSlot;
1700             DOUT << " from physreg "
1701                  << TRI->getName(PhysReg) << " for vreg"
1702                  << VirtReg <<" instead of reloading into physreg "
1703                  << TRI->getName(VRM.getPhys(VirtReg)) << "\n";
1704             unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
1705             MI.getOperand(i).setReg(RReg);
1706             MI.getOperand(i).setSubReg(0);
1707
1708             // The only technical detail we have is that we don't know that
1709             // PhysReg won't be clobbered by a reloaded stack slot that occurs
1710             // later in the instruction.  In particular, consider 'op V1, V2'.
1711             // If V1 is available in physreg R0, we would choose to reuse it
1712             // here, instead of reloading it into the register the allocator
1713             // indicated (say R1).  However, V2 might have to be reloaded
1714             // later, and it might indicate that it needs to live in R0.  When
1715             // this occurs, we need to have information available that
1716             // indicates it is safe to use R1 for the reload instead of R0.
1717             //
1718             // To further complicate matters, we might conflict with an alias,
1719             // or R0 and R1 might not be compatible with each other.  In this
1720             // case, we actually insert a reload for V1 in R1, ensuring that
1721             // we can get at R0 or its alias.
1722             ReusedOperands.addReuse(i, ReuseSlot, PhysReg,
1723                                     VRM.getPhys(VirtReg), VirtReg);
1724             if (isTied)
1725               // Only mark it clobbered if this is a use&def operand.
1726               ReusedOperands.markClobbered(PhysReg);
1727             ++NumReused;
1728
1729             if (MI.getOperand(i).isKill() &&
1730                 ReuseSlot <= VirtRegMap::MAX_STACK_SLOT) {
1731
1732               // The store of this spilled value is potentially dead, but we
1733               // won't know for certain until we've confirmed that the re-use
1734               // above is valid, which means waiting until the other operands
1735               // are processed. For now we just track the spill slot, we'll
1736               // remove it after the other operands are processed if valid.
1737
1738               PotentialDeadStoreSlots.push_back(ReuseSlot);
1739             }
1740
1741             // Mark is isKill if it's there no other uses of the same virtual
1742             // register and it's not a two-address operand. IsKill will be
1743             // unset if reg is reused.
1744             if (!isTied && KilledMIRegs.count(VirtReg) == 0) {
1745               MI.getOperand(i).setIsKill();
1746               KilledMIRegs.insert(VirtReg);
1747             }
1748
1749             continue;
1750           }  // CanReuse
1751           
1752           // Otherwise we have a situation where we have a two-address instruction
1753           // whose mod/ref operand needs to be reloaded.  This reload is already
1754           // available in some register "PhysReg", but if we used PhysReg as the
1755           // operand to our 2-addr instruction, the instruction would modify
1756           // PhysReg.  This isn't cool if something later uses PhysReg and expects
1757           // to get its initial value.
1758           //
1759           // To avoid this problem, and to avoid doing a load right after a store,
1760           // we emit a copy from PhysReg into the designated register for this
1761           // operand.
1762           unsigned DesignatedReg = VRM.getPhys(VirtReg);
1763           assert(DesignatedReg && "Must map virtreg to physreg!");
1764
1765           // Note that, if we reused a register for a previous operand, the
1766           // register we want to reload into might not actually be
1767           // available.  If this occurs, use the register indicated by the
1768           // reuser.
1769           if (ReusedOperands.hasReuses())
1770             DesignatedReg = ReusedOperands.GetRegForReload(DesignatedReg, &MI, 
1771                                  Spills, MaybeDeadStores, RegKills, KillOps, VRM);
1772           
1773           // If the mapped designated register is actually the physreg we have
1774           // incoming, we don't need to inserted a dead copy.
1775           if (DesignatedReg == PhysReg) {
1776             // If this stack slot value is already available, reuse it!
1777             if (ReuseSlot > VirtRegMap::MAX_STACK_SLOT)
1778               DOUT << "Reusing RM#" << ReuseSlot-VirtRegMap::MAX_STACK_SLOT-1;
1779             else
1780               DOUT << "Reusing SS#" << ReuseSlot;
1781             DOUT << " from physreg " << TRI->getName(PhysReg)
1782                  << " for vreg" << VirtReg
1783                  << " instead of reloading into same physreg.\n";
1784             unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
1785             MI.getOperand(i).setReg(RReg);
1786             MI.getOperand(i).setSubReg(0);
1787             ReusedOperands.markClobbered(RReg);
1788             ++NumReused;
1789             continue;
1790           }
1791           
1792           const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
1793           RegInfo->setPhysRegUsed(DesignatedReg);
1794           ReusedOperands.markClobbered(DesignatedReg);
1795           TII->copyRegToReg(MBB, &MI, DesignatedReg, PhysReg, RC, RC);
1796
1797           MachineInstr *CopyMI = prior(MII);
1798           UpdateKills(*CopyMI, TRI, RegKills, KillOps);
1799
1800           // This invalidates DesignatedReg.
1801           Spills.ClobberPhysReg(DesignatedReg);
1802           
1803           Spills.addAvailable(ReuseSlot, DesignatedReg);
1804           unsigned RReg =
1805             SubIdx ? TRI->getSubReg(DesignatedReg, SubIdx) : DesignatedReg;
1806           MI.getOperand(i).setReg(RReg);
1807           MI.getOperand(i).setSubReg(0);
1808           DOUT << '\t' << *prior(MII);
1809           ++NumReused;
1810           continue;
1811         } // if (PhysReg)
1812         
1813         // Otherwise, reload it and remember that we have it.
1814         PhysReg = VRM.getPhys(VirtReg);
1815         assert(PhysReg && "Must map virtreg to physreg!");
1816
1817         // Note that, if we reused a register for a previous operand, the
1818         // register we want to reload into might not actually be
1819         // available.  If this occurs, use the register indicated by the
1820         // reuser.
1821         if (ReusedOperands.hasReuses())
1822           PhysReg = ReusedOperands.GetRegForReload(PhysReg, &MI, 
1823                                  Spills, MaybeDeadStores, RegKills, KillOps, VRM);
1824         
1825         RegInfo->setPhysRegUsed(PhysReg);
1826         ReusedOperands.markClobbered(PhysReg);
1827         if (AvoidReload)
1828           ++NumAvoided;
1829         else {
1830           if (DoReMat) {
1831             ReMaterialize(MBB, MII, PhysReg, VirtReg, TII, TRI, VRM);
1832           } else {
1833             const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
1834             TII->loadRegFromStackSlot(MBB, &MI, PhysReg, SSorRMId, RC);
1835             MachineInstr *LoadMI = prior(MII);
1836             VRM.addSpillSlotUse(SSorRMId, LoadMI);
1837             ++NumLoads;
1838           }
1839           // This invalidates PhysReg.
1840           Spills.ClobberPhysReg(PhysReg);
1841
1842           // Any stores to this stack slot are not dead anymore.
1843           if (!DoReMat)
1844             MaybeDeadStores[SSorRMId] = NULL;
1845           Spills.addAvailable(SSorRMId, PhysReg);
1846           // Assumes this is the last use. IsKill will be unset if reg is reused
1847           // unless it's a two-address operand.
1848           if (!MI.isRegTiedToDefOperand(i) &&
1849               KilledMIRegs.count(VirtReg) == 0) {
1850             MI.getOperand(i).setIsKill();
1851             KilledMIRegs.insert(VirtReg);
1852           }
1853
1854           UpdateKills(*prior(MII), TRI, RegKills, KillOps);
1855           DOUT << '\t' << *prior(MII);
1856         }
1857         unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
1858         MI.getOperand(i).setReg(RReg);
1859         MI.getOperand(i).setSubReg(0);
1860       }
1861
1862       // Ok - now we can remove stores that have been confirmed dead.
1863       for (unsigned j = 0, e = PotentialDeadStoreSlots.size(); j != e; ++j) {
1864         // This was the last use and the spilled value is still available
1865         // for reuse. That means the spill was unnecessary!
1866         int PDSSlot = PotentialDeadStoreSlots[j];
1867         MachineInstr* DeadStore = MaybeDeadStores[PDSSlot];
1868         if (DeadStore) {
1869           DOUT << "Removed dead store:\t" << *DeadStore;
1870           InvalidateKills(*DeadStore, TRI, RegKills, KillOps);
1871           VRM.RemoveMachineInstrFromMaps(DeadStore);
1872           MBB.erase(DeadStore);
1873           MaybeDeadStores[PDSSlot] = NULL;
1874           ++NumDSE;
1875         }
1876       }
1877
1878
1879       DOUT << '\t' << MI;
1880
1881
1882       // If we have folded references to memory operands, make sure we clear all
1883       // physical registers that may contain the value of the spilled virtual
1884       // register
1885       SmallSet<int, 2> FoldedSS;
1886       for (tie(I, End) = VRM.getFoldedVirts(&MI); I != End; ) {
1887         unsigned VirtReg = I->second.first;
1888         VirtRegMap::ModRef MR = I->second.second;
1889         DOUT << "Folded vreg: " << VirtReg << "  MR: " << MR;
1890
1891         // MI2VirtMap be can updated which invalidate the iterator.
1892         // Increment the iterator first.
1893         ++I;
1894         int SS = VRM.getStackSlot(VirtReg);
1895         if (SS == VirtRegMap::NO_STACK_SLOT)
1896           continue;
1897         FoldedSS.insert(SS);
1898         DOUT << " - StackSlot: " << SS << "\n";
1899         
1900         // If this folded instruction is just a use, check to see if it's a
1901         // straight load from the virt reg slot.
1902         if ((MR & VirtRegMap::isRef) && !(MR & VirtRegMap::isMod)) {
1903           int FrameIdx;
1904           unsigned DestReg = TII->isLoadFromStackSlot(&MI, FrameIdx);
1905           if (DestReg && FrameIdx == SS) {
1906             // If this spill slot is available, turn it into a copy (or nothing)
1907             // instead of leaving it as a load!
1908             if (unsigned InReg = Spills.getSpillSlotOrReMatPhysReg(SS)) {
1909               DOUT << "Promoted Load To Copy: " << MI;
1910               if (DestReg != InReg) {
1911                 const TargetRegisterClass *RC = RegInfo->getRegClass(VirtReg);
1912                 TII->copyRegToReg(MBB, &MI, DestReg, InReg, RC, RC);
1913                 MachineOperand *DefMO = MI.findRegisterDefOperand(DestReg);
1914                 unsigned SubIdx = DefMO->getSubReg();
1915                 // Revisit the copy so we make sure to notice the effects of the
1916                 // operation on the destreg (either needing to RA it if it's 
1917                 // virtual or needing to clobber any values if it's physical).
1918                 NextMII = &MI;
1919                 --NextMII;  // backtrack to the copy.
1920                 // Propagate the sub-register index over.
1921                 if (SubIdx) {
1922                   DefMO = NextMII->findRegisterDefOperand(DestReg);
1923                   DefMO->setSubReg(SubIdx);
1924                 }
1925
1926                 // Mark is killed.
1927                 MachineOperand *KillOpnd = NextMII->findRegisterUseOperand(InReg);
1928                 KillOpnd->setIsKill();
1929
1930                 BackTracked = true;
1931               } else {
1932                 DOUT << "Removing now-noop copy: " << MI;
1933                 // Unset last kill since it's being reused.
1934                 InvalidateKill(InReg, TRI, RegKills, KillOps);
1935                 Spills.disallowClobberPhysReg(InReg);
1936               }
1937
1938               InvalidateKills(MI, TRI, RegKills, KillOps);
1939               VRM.RemoveMachineInstrFromMaps(&MI);
1940               MBB.erase(&MI);
1941               Erased = true;
1942               goto ProcessNextInst;
1943             }
1944           } else {
1945             unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SS);
1946             SmallVector<MachineInstr*, 4> NewMIs;
1947             if (PhysReg &&
1948                 TII->unfoldMemoryOperand(MF, &MI, PhysReg, false, false, NewMIs)) {
1949               MBB.insert(MII, NewMIs[0]);
1950               InvalidateKills(MI, TRI, RegKills, KillOps);
1951               VRM.RemoveMachineInstrFromMaps(&MI);
1952               MBB.erase(&MI);
1953               Erased = true;
1954               --NextMII;  // backtrack to the unfolded instruction.
1955               BackTracked = true;
1956               goto ProcessNextInst;
1957             }
1958           }
1959         }
1960
1961         // If this reference is not a use, any previous store is now dead.
1962         // Otherwise, the store to this stack slot is not dead anymore.
1963         MachineInstr* DeadStore = MaybeDeadStores[SS];
1964         if (DeadStore) {
1965           bool isDead = !(MR & VirtRegMap::isRef);
1966           MachineInstr *NewStore = NULL;
1967           if (MR & VirtRegMap::isModRef) {
1968             unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SS);
1969             SmallVector<MachineInstr*, 4> NewMIs;
1970             // We can reuse this physreg as long as we are allowed to clobber
1971             // the value and there isn't an earlier def that has already clobbered
1972             // the physreg.
1973             if (PhysReg &&
1974                 !ReusedOperands.isClobbered(PhysReg) &&
1975                 Spills.canClobberPhysReg(PhysReg) &&
1976                 !TII->isStoreToStackSlot(&MI, SS)) { // Not profitable!
1977               MachineOperand *KillOpnd =
1978                 DeadStore->findRegisterUseOperand(PhysReg, true);
1979               // Note, if the store is storing a sub-register, it's possible the
1980               // super-register is needed below.
1981               if (KillOpnd && !KillOpnd->getSubReg() &&
1982                   TII->unfoldMemoryOperand(MF, &MI, PhysReg, false, true,NewMIs)){
1983                 MBB.insert(MII, NewMIs[0]);
1984                 NewStore = NewMIs[1];
1985                 MBB.insert(MII, NewStore);
1986                 VRM.addSpillSlotUse(SS, NewStore);
1987                 InvalidateKills(MI, TRI, RegKills, KillOps);
1988                 VRM.RemoveMachineInstrFromMaps(&MI);
1989                 MBB.erase(&MI);
1990                 Erased = true;
1991                 --NextMII;
1992                 --NextMII;  // backtrack to the unfolded instruction.
1993                 BackTracked = true;
1994                 isDead = true;
1995                 ++NumSUnfold;
1996               }
1997             }
1998           }
1999
2000           if (isDead) {  // Previous store is dead.
2001             // If we get here, the store is dead, nuke it now.
2002             DOUT << "Removed dead store:\t" << *DeadStore;
2003             InvalidateKills(*DeadStore, TRI, RegKills, KillOps);
2004             VRM.RemoveMachineInstrFromMaps(DeadStore);
2005             MBB.erase(DeadStore);
2006             if (!NewStore)
2007               ++NumDSE;
2008           }
2009
2010           MaybeDeadStores[SS] = NULL;
2011           if (NewStore) {
2012             // Treat this store as a spill merged into a copy. That makes the
2013             // stack slot value available.
2014             VRM.virtFolded(VirtReg, NewStore, VirtRegMap::isMod);
2015             goto ProcessNextInst;
2016           }
2017         }
2018
2019         // If the spill slot value is available, and this is a new definition of
2020         // the value, the value is not available anymore.
2021         if (MR & VirtRegMap::isMod) {
2022           // Notice that the value in this stack slot has been modified.
2023           Spills.ModifyStackSlotOrReMat(SS);
2024           
2025           // If this is *just* a mod of the value, check to see if this is just a
2026           // store to the spill slot (i.e. the spill got merged into the copy). If
2027           // so, realize that the vreg is available now, and add the store to the
2028           // MaybeDeadStore info.
2029           int StackSlot;
2030           if (!(MR & VirtRegMap::isRef)) {
2031             if (unsigned SrcReg = TII->isStoreToStackSlot(&MI, StackSlot)) {
2032               assert(TargetRegisterInfo::isPhysicalRegister(SrcReg) &&
2033                      "Src hasn't been allocated yet?");
2034
2035               if (CommuteToFoldReload(MBB, MII, VirtReg, SrcReg, StackSlot,
2036                                       Spills, RegKills, KillOps, TRI, VRM)) {
2037                 NextMII = next(MII);
2038                 BackTracked = true;
2039                 goto ProcessNextInst;
2040               }
2041
2042               // Okay, this is certainly a store of SrcReg to [StackSlot].  Mark
2043               // this as a potentially dead store in case there is a subsequent
2044               // store into the stack slot without a read from it.
2045               MaybeDeadStores[StackSlot] = &MI;
2046
2047               // If the stack slot value was previously available in some other
2048               // register, change it now.  Otherwise, make the register
2049               // available in PhysReg.
2050               Spills.addAvailable(StackSlot, SrcReg, MI.killsRegister(SrcReg));
2051             }
2052           }
2053         }
2054       }
2055
2056       // Process all of the spilled defs.
2057       for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
2058         MachineOperand &MO = MI.getOperand(i);
2059         if (!(MO.isReg() && MO.getReg() && MO.isDef()))
2060           continue;
2061
2062         unsigned VirtReg = MO.getReg();
2063         if (!TargetRegisterInfo::isVirtualRegister(VirtReg)) {
2064           // Check to see if this is a noop copy.  If so, eliminate the
2065           // instruction before considering the dest reg to be changed.
2066           // Also check if it's copying from an "undef", if so, we can't
2067           // eliminate this or else the undef marker is lost and it will
2068           // confuses the scavenger. This is extremely rare.
2069           unsigned Src, Dst, SrcSR, DstSR;
2070           if (TII->isMoveInstr(MI, Src, Dst, SrcSR, DstSR) && Src == Dst &&
2071               !MI.findRegisterUseOperand(Src)->isUndef()) {
2072             ++NumDCE;
2073             DOUT << "Removing now-noop copy: " << MI;
2074             SmallVector<unsigned, 2> KillRegs;
2075             InvalidateKills(MI, TRI, RegKills, KillOps, &KillRegs);
2076             if (MO.isDead() && !KillRegs.empty()) {
2077               // Source register or an implicit super/sub-register use is killed.
2078               assert(KillRegs[0] == Dst ||
2079                      TRI->isSubRegister(KillRegs[0], Dst) ||
2080                      TRI->isSuperRegister(KillRegs[0], Dst));
2081               // Last def is now dead.
2082               TransferDeadness(&MBB, Dist, Src, RegKills, KillOps, VRM);
2083             }
2084             VRM.RemoveMachineInstrFromMaps(&MI);
2085             MBB.erase(&MI);
2086             Erased = true;
2087             Spills.disallowClobberPhysReg(VirtReg);
2088             goto ProcessNextInst;
2089           }
2090
2091           // If it's not a no-op copy, it clobbers the value in the destreg.
2092           Spills.ClobberPhysReg(VirtReg);
2093           ReusedOperands.markClobbered(VirtReg);
2094    
2095           // Check to see if this instruction is a load from a stack slot into
2096           // a register.  If so, this provides the stack slot value in the reg.
2097           int FrameIdx;
2098           if (unsigned DestReg = TII->isLoadFromStackSlot(&MI, FrameIdx)) {
2099             assert(DestReg == VirtReg && "Unknown load situation!");
2100
2101             // If it is a folded reference, then it's not safe to clobber.
2102             bool Folded = FoldedSS.count(FrameIdx);
2103             // Otherwise, if it wasn't available, remember that it is now!
2104             Spills.addAvailable(FrameIdx, DestReg, !Folded);
2105             goto ProcessNextInst;
2106           }
2107               
2108           continue;
2109         }
2110
2111         unsigned SubIdx = MO.getSubReg();
2112         bool DoReMat = VRM.isReMaterialized(VirtReg);
2113         if (DoReMat)
2114           ReMatDefs.insert(&MI);
2115
2116         // The only vregs left are stack slot definitions.
2117         int StackSlot = VRM.getStackSlot(VirtReg);
2118         const TargetRegisterClass *RC = RegInfo->getRegClass(VirtReg);
2119
2120         // If this def is part of a two-address operand, make sure to execute
2121         // the store from the correct physical register.
2122         unsigned PhysReg;
2123         unsigned TiedOp;
2124         if (MI.isRegTiedToUseOperand(i, &TiedOp)) {
2125           PhysReg = MI.getOperand(TiedOp).getReg();
2126           if (SubIdx) {
2127             unsigned SuperReg = findSuperReg(RC, PhysReg, SubIdx, TRI);
2128             assert(SuperReg && TRI->getSubReg(SuperReg, SubIdx) == PhysReg &&
2129                    "Can't find corresponding super-register!");
2130             PhysReg = SuperReg;
2131           }
2132         } else {
2133           PhysReg = VRM.getPhys(VirtReg);
2134           if (ReusedOperands.isClobbered(PhysReg)) {
2135             // Another def has taken the assigned physreg. It must have been a
2136             // use&def which got it due to reuse. Undo the reuse!
2137             PhysReg = ReusedOperands.GetRegForReload(PhysReg, &MI, 
2138                                  Spills, MaybeDeadStores, RegKills, KillOps, VRM);
2139           }
2140         }
2141
2142         assert(PhysReg && "VR not assigned a physical register?");
2143         RegInfo->setPhysRegUsed(PhysReg);
2144         unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
2145         ReusedOperands.markClobbered(RReg);
2146         MI.getOperand(i).setReg(RReg);
2147         MI.getOperand(i).setSubReg(0);
2148
2149         if (!MO.isDead()) {
2150           MachineInstr *&LastStore = MaybeDeadStores[StackSlot];
2151           SpillRegToStackSlot(MBB, MII, -1, PhysReg, StackSlot, RC, true,
2152                             LastStore, Spills, ReMatDefs, RegKills, KillOps, VRM);
2153           NextMII = next(MII);
2154
2155           // Check to see if this is a noop copy.  If so, eliminate the
2156           // instruction before considering the dest reg to be changed.
2157           {
2158             unsigned Src, Dst, SrcSR, DstSR;
2159             if (TII->isMoveInstr(MI, Src, Dst, SrcSR, DstSR) && Src == Dst) {
2160               ++NumDCE;
2161               DOUT << "Removing now-noop copy: " << MI;
2162               InvalidateKills(MI, TRI, RegKills, KillOps);
2163               VRM.RemoveMachineInstrFromMaps(&MI);
2164               MBB.erase(&MI);
2165               Erased = true;
2166               UpdateKills(*LastStore, TRI, RegKills, KillOps);
2167               goto ProcessNextInst;
2168             }
2169           }
2170         }    
2171       }
2172     ProcessNextInst:
2173       DistanceMap.insert(std::make_pair(&MI, Dist++));
2174       if (!Erased && !BackTracked) {
2175         for (MachineBasicBlock::iterator II = &MI; II != NextMII; ++II)
2176           UpdateKills(*II, TRI, RegKills, KillOps);
2177       }
2178       MII = NextMII;
2179     }
2180
2181   }
2182
2183 };
2184
2185 llvm::VirtRegRewriter* llvm::createVirtRegRewriter() {
2186   switch (RewriterOpt) {
2187   default: llvm_unreachable("Unreachable!");
2188   case local:
2189     return new LocalRewriter();
2190   case trivial:
2191     return new TrivialRewriter();
2192   }
2193 }