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