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