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