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