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