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