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