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