Convert the last getPhysicalRegisterRegClass in VirtRegRewriter.cpp to
[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, 0, ReMatDefMI, *TRI);
671   MachineInstr *NewMI = prior(MII);
672   for (unsigned i = 0, e = NewMI->getNumOperands(); i != e; ++i) {
673     MachineOperand &MO = NewMI->getOperand(i);
674     if (!MO.isReg() || MO.getReg() == 0)
675       continue;
676     unsigned VirtReg = MO.getReg();
677     if (TargetRegisterInfo::isPhysicalRegister(VirtReg))
678       continue;
679     assert(MO.isUse());
680     unsigned Phys = VRM.getPhys(VirtReg);
681     assert(Phys && "Virtual register is not assigned a register?");
682     substitutePhysReg(MO, Phys, *TRI);
683   }
684   ++NumReMats;
685 }
686
687 /// findSuperReg - Find the SubReg's super-register of given register class
688 /// where its SubIdx sub-register is SubReg.
689 static unsigned findSuperReg(const TargetRegisterClass *RC, unsigned SubReg,
690                              unsigned SubIdx, const TargetRegisterInfo *TRI) {
691   for (TargetRegisterClass::iterator I = RC->begin(), E = RC->end();
692        I != E; ++I) {
693     unsigned Reg = *I;
694     if (TRI->getSubReg(Reg, SubIdx) == SubReg)
695       return Reg;
696   }
697   return 0;
698 }
699
700 // ******************************** //
701 // Available Spills Implementation  //
702 // ******************************** //
703
704 /// disallowClobberPhysRegOnly - Unset the CanClobber bit of the specified
705 /// stackslot register. The register is still available but is no longer
706 /// allowed to be modifed.
707 void AvailableSpills::disallowClobberPhysRegOnly(unsigned PhysReg) {
708   std::multimap<unsigned, int>::iterator I =
709     PhysRegsAvailable.lower_bound(PhysReg);
710   while (I != PhysRegsAvailable.end() && I->first == PhysReg) {
711     int SlotOrReMat = I->second;
712     I++;
713     assert((SpillSlotsOrReMatsAvailable[SlotOrReMat] >> 1) == PhysReg &&
714            "Bidirectional map mismatch!");
715     SpillSlotsOrReMatsAvailable[SlotOrReMat] &= ~1;
716     DEBUG(dbgs() << "PhysReg " << TRI->getName(PhysReg)
717          << " copied, it is available for use but can no longer be modified\n");
718   }
719 }
720
721 /// disallowClobberPhysReg - Unset the CanClobber bit of the specified
722 /// stackslot register and its aliases. The register and its aliases may
723 /// still available but is no longer allowed to be modifed.
724 void AvailableSpills::disallowClobberPhysReg(unsigned PhysReg) {
725   for (const unsigned *AS = TRI->getAliasSet(PhysReg); *AS; ++AS)
726     disallowClobberPhysRegOnly(*AS);
727   disallowClobberPhysRegOnly(PhysReg);
728 }
729
730 /// ClobberPhysRegOnly - This is called when the specified physreg changes
731 /// value.  We use this to invalidate any info about stuff we thing lives in it.
732 void AvailableSpills::ClobberPhysRegOnly(unsigned PhysReg) {
733   std::multimap<unsigned, int>::iterator I =
734     PhysRegsAvailable.lower_bound(PhysReg);
735   while (I != PhysRegsAvailable.end() && I->first == PhysReg) {
736     int SlotOrReMat = I->second;
737     PhysRegsAvailable.erase(I++);
738     assert((SpillSlotsOrReMatsAvailable[SlotOrReMat] >> 1) == PhysReg &&
739            "Bidirectional map mismatch!");
740     SpillSlotsOrReMatsAvailable.erase(SlotOrReMat);
741     DEBUG(dbgs() << "PhysReg " << TRI->getName(PhysReg)
742           << " clobbered, invalidating ");
743     if (SlotOrReMat > VirtRegMap::MAX_STACK_SLOT)
744       DEBUG(dbgs() << "RM#" << SlotOrReMat-VirtRegMap::MAX_STACK_SLOT-1 <<"\n");
745     else
746       DEBUG(dbgs() << "SS#" << SlotOrReMat << "\n");
747   }
748 }
749
750 /// ClobberPhysReg - This is called when the specified physreg changes
751 /// value.  We use this to invalidate any info about stuff we thing lives in
752 /// it and any of its aliases.
753 void AvailableSpills::ClobberPhysReg(unsigned PhysReg) {
754   for (const unsigned *AS = TRI->getAliasSet(PhysReg); *AS; ++AS)
755     ClobberPhysRegOnly(*AS);
756   ClobberPhysRegOnly(PhysReg);
757 }
758
759 /// AddAvailableRegsToLiveIn - Availability information is being kept coming
760 /// into the specified MBB. Add available physical registers as potential
761 /// live-in's. If they are reused in the MBB, they will be added to the
762 /// live-in set to make register scavenger and post-allocation scheduler.
763 void AvailableSpills::AddAvailableRegsToLiveIn(MachineBasicBlock &MBB,
764                                         BitVector &RegKills,
765                                         std::vector<MachineOperand*> &KillOps) {
766   std::set<unsigned> NotAvailable;
767   for (std::multimap<unsigned, int>::iterator
768          I = PhysRegsAvailable.begin(), E = PhysRegsAvailable.end();
769        I != E; ++I) {
770     unsigned Reg = I->first;
771     const TargetRegisterClass* RC = TRI->getMinimalPhysRegClass(Reg);
772     // FIXME: A temporary workaround. We can't reuse available value if it's
773     // not safe to move the def of the virtual register's class. e.g.
774     // X86::RFP* register classes. Do not add it as a live-in.
775     if (!TII->isSafeToMoveRegClassDefs(RC))
776       // This is no longer available.
777       NotAvailable.insert(Reg);
778     else {
779       MBB.addLiveIn(Reg);
780       InvalidateKill(Reg, TRI, RegKills, KillOps);
781     }
782
783     // Skip over the same register.
784     std::multimap<unsigned, int>::iterator NI = llvm::next(I);
785     while (NI != E && NI->first == Reg) {
786       ++I;
787       ++NI;
788     }
789   }
790
791   for (std::set<unsigned>::iterator I = NotAvailable.begin(),
792          E = NotAvailable.end(); I != E; ++I) {
793     ClobberPhysReg(*I);
794     for (const unsigned *SubRegs = TRI->getSubRegisters(*I);
795        *SubRegs; ++SubRegs)
796       ClobberPhysReg(*SubRegs);
797   }
798 }
799
800 /// ModifyStackSlotOrReMat - This method is called when the value in a stack
801 /// slot changes.  This removes information about which register the previous
802 /// value for this slot lives in (as the previous value is dead now).
803 void AvailableSpills::ModifyStackSlotOrReMat(int SlotOrReMat) {
804   std::map<int, unsigned>::iterator It =
805     SpillSlotsOrReMatsAvailable.find(SlotOrReMat);
806   if (It == SpillSlotsOrReMatsAvailable.end()) return;
807   unsigned Reg = It->second >> 1;
808   SpillSlotsOrReMatsAvailable.erase(It);
809
810   // This register may hold the value of multiple stack slots, only remove this
811   // stack slot from the set of values the register contains.
812   std::multimap<unsigned, int>::iterator I = PhysRegsAvailable.lower_bound(Reg);
813   for (; ; ++I) {
814     assert(I != PhysRegsAvailable.end() && I->first == Reg &&
815            "Map inverse broken!");
816     if (I->second == SlotOrReMat) break;
817   }
818   PhysRegsAvailable.erase(I);
819 }
820
821 // ************************** //
822 // Reuse Info Implementation  //
823 // ************************** //
824
825 /// GetRegForReload - We are about to emit a reload into PhysReg.  If there
826 /// is some other operand that is using the specified register, either pick
827 /// a new register to use, or evict the previous reload and use this reg.
828 unsigned ReuseInfo::GetRegForReload(const TargetRegisterClass *RC,
829                          unsigned PhysReg,
830                          MachineFunction &MF,
831                          MachineInstr *MI, AvailableSpills &Spills,
832                          std::vector<MachineInstr*> &MaybeDeadStores,
833                          SmallSet<unsigned, 8> &Rejected,
834                          BitVector &RegKills,
835                          std::vector<MachineOperand*> &KillOps,
836                          VirtRegMap &VRM) {
837   const TargetInstrInfo* TII = MF.getTarget().getInstrInfo();
838   const TargetRegisterInfo *TRI = Spills.getRegInfo();
839
840   if (Reuses.empty()) return PhysReg;  // This is most often empty.
841
842   for (unsigned ro = 0, e = Reuses.size(); ro != e; ++ro) {
843     ReusedOp &Op = Reuses[ro];
844     // If we find some other reuse that was supposed to use this register
845     // exactly for its reload, we can change this reload to use ITS reload
846     // register. That is, unless its reload register has already been
847     // considered and subsequently rejected because it has also been reused
848     // by another operand.
849     if (Op.PhysRegReused == PhysReg &&
850         Rejected.count(Op.AssignedPhysReg) == 0 &&
851         RC->contains(Op.AssignedPhysReg)) {
852       // Yup, use the reload register that we didn't use before.
853       unsigned NewReg = Op.AssignedPhysReg;
854       Rejected.insert(PhysReg);
855       return GetRegForReload(RC, NewReg, MF, MI, Spills, MaybeDeadStores, Rejected,
856                              RegKills, KillOps, VRM);
857     } else {
858       // Otherwise, we might also have a problem if a previously reused
859       // value aliases the new register. If so, codegen the previous reload
860       // and use this one.
861       unsigned PRRU = Op.PhysRegReused;
862       if (TRI->regsOverlap(PRRU, PhysReg)) {
863         // Okay, we found out that an alias of a reused register
864         // was used.  This isn't good because it means we have
865         // to undo a previous reuse.
866         MachineBasicBlock *MBB = MI->getParent();
867         const TargetRegisterClass *AliasRC =
868           MBB->getParent()->getRegInfo().getRegClass(Op.VirtReg);
869
870         // Copy Op out of the vector and remove it, we're going to insert an
871         // explicit load for it.
872         ReusedOp NewOp = Op;
873         Reuses.erase(Reuses.begin()+ro);
874
875         // MI may be using only a sub-register of PhysRegUsed.
876         unsigned RealPhysRegUsed = MI->getOperand(NewOp.Operand).getReg();
877         unsigned SubIdx = 0;
878         assert(TargetRegisterInfo::isPhysicalRegister(RealPhysRegUsed) &&
879                "A reuse cannot be a virtual register");
880         if (PRRU != RealPhysRegUsed) {
881           // What was the sub-register index?
882           SubIdx = TRI->getSubRegIndex(PRRU, RealPhysRegUsed);
883           assert(SubIdx &&
884                  "Operand physreg is not a sub-register of PhysRegUsed");
885         }
886
887         // Ok, we're going to try to reload the assigned physreg into the
888         // slot that we were supposed to in the first place.  However, that
889         // register could hold a reuse.  Check to see if it conflicts or
890         // would prefer us to use a different register.
891         unsigned NewPhysReg = GetRegForReload(RC, NewOp.AssignedPhysReg,
892                                               MF, MI, Spills, MaybeDeadStores,
893                                               Rejected, RegKills, KillOps, VRM);
894
895         bool DoReMat = NewOp.StackSlotOrReMat > VirtRegMap::MAX_STACK_SLOT;
896         int SSorRMId = DoReMat
897           ? VRM.getReMatId(NewOp.VirtReg) : (int) NewOp.StackSlotOrReMat;
898
899         // Back-schedule reloads and remats.
900         MachineBasicBlock::iterator InsertLoc =
901           ComputeReloadLoc(MI, MBB->begin(), PhysReg, TRI,
902                            DoReMat, SSorRMId, TII, MF);
903
904         if (DoReMat) {
905           ReMaterialize(*MBB, InsertLoc, NewPhysReg, NewOp.VirtReg, TII,
906                         TRI, VRM);
907         } else {
908           TII->loadRegFromStackSlot(*MBB, InsertLoc, NewPhysReg,
909                                     NewOp.StackSlotOrReMat, AliasRC, TRI);
910           MachineInstr *LoadMI = prior(InsertLoc);
911           VRM.addSpillSlotUse(NewOp.StackSlotOrReMat, LoadMI);
912           // Any stores to this stack slot are not dead anymore.
913           MaybeDeadStores[NewOp.StackSlotOrReMat] = NULL;
914           ++NumLoads;
915         }
916         Spills.ClobberPhysReg(NewPhysReg);
917         Spills.ClobberPhysReg(NewOp.PhysRegReused);
918
919         unsigned RReg = SubIdx ? TRI->getSubReg(NewPhysReg, SubIdx) :NewPhysReg;
920         MI->getOperand(NewOp.Operand).setReg(RReg);
921         MI->getOperand(NewOp.Operand).setSubReg(0);
922
923         Spills.addAvailable(NewOp.StackSlotOrReMat, NewPhysReg);
924         UpdateKills(*prior(InsertLoc), TRI, RegKills, KillOps);
925         DEBUG(dbgs() << '\t' << *prior(InsertLoc));
926
927         DEBUG(dbgs() << "Reuse undone!\n");
928         --NumReused;
929
930         // Finally, PhysReg is now available, go ahead and use it.
931         return PhysReg;
932       }
933     }
934   }
935   return PhysReg;
936 }
937
938 // ************************************************************************ //
939
940 /// FoldsStackSlotModRef - Return true if the specified MI folds the specified
941 /// stack slot mod/ref. It also checks if it's possible to unfold the
942 /// instruction by having it define a specified physical register instead.
943 static bool FoldsStackSlotModRef(MachineInstr &MI, int SS, unsigned PhysReg,
944                                  const TargetInstrInfo *TII,
945                                  const TargetRegisterInfo *TRI,
946                                  VirtRegMap &VRM) {
947   if (VRM.hasEmergencySpills(&MI) || VRM.isSpillPt(&MI))
948     return false;
949
950   bool Found = false;
951   VirtRegMap::MI2VirtMapTy::const_iterator I, End;
952   for (tie(I, End) = VRM.getFoldedVirts(&MI); I != End; ++I) {
953     unsigned VirtReg = I->second.first;
954     VirtRegMap::ModRef MR = I->second.second;
955     if (MR & VirtRegMap::isModRef)
956       if (VRM.getStackSlot(VirtReg) == SS) {
957         Found= TII->getOpcodeAfterMemoryUnfold(MI.getOpcode(), true, true) != 0;
958         break;
959       }
960   }
961   if (!Found)
962     return false;
963
964   // Does the instruction uses a register that overlaps the scratch register?
965   for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
966     MachineOperand &MO = MI.getOperand(i);
967     if (!MO.isReg() || MO.getReg() == 0)
968       continue;
969     unsigned Reg = MO.getReg();
970     if (TargetRegisterInfo::isVirtualRegister(Reg)) {
971       if (!VRM.hasPhys(Reg))
972         continue;
973       Reg = VRM.getPhys(Reg);
974     }
975     if (TRI->regsOverlap(PhysReg, Reg))
976       return false;
977   }
978   return true;
979 }
980
981 /// FindFreeRegister - Find a free register of a given register class by looking
982 /// at (at most) the last two machine instructions.
983 static unsigned FindFreeRegister(MachineBasicBlock::iterator MII,
984                                  MachineBasicBlock &MBB,
985                                  const TargetRegisterClass *RC,
986                                  const TargetRegisterInfo *TRI,
987                                  BitVector &AllocatableRegs) {
988   BitVector Defs(TRI->getNumRegs());
989   BitVector Uses(TRI->getNumRegs());
990   SmallVector<unsigned, 4> LocalUses;
991   SmallVector<unsigned, 4> Kills;
992
993   // Take a look at 2 instructions at most.
994   unsigned Count = 0;
995   while (Count < 2) {
996     if (MII == MBB.begin())
997       break;
998     MachineInstr *PrevMI = prior(MII);
999     MII = PrevMI;
1000
1001     if (PrevMI->isDebugValue())
1002       continue; // Skip over dbg_value instructions.
1003     ++Count;
1004
1005     for (unsigned i = 0, e = PrevMI->getNumOperands(); i != e; ++i) {
1006       MachineOperand &MO = PrevMI->getOperand(i);
1007       if (!MO.isReg() || MO.getReg() == 0)
1008         continue;
1009       unsigned Reg = MO.getReg();
1010       if (MO.isDef()) {
1011         Defs.set(Reg);
1012         for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
1013           Defs.set(*AS);
1014       } else  {
1015         LocalUses.push_back(Reg);
1016         if (MO.isKill() && AllocatableRegs[Reg])
1017           Kills.push_back(Reg);
1018       }
1019     }
1020
1021     for (unsigned i = 0, e = Kills.size(); i != e; ++i) {
1022       unsigned Kill = Kills[i];
1023       if (!Defs[Kill] && !Uses[Kill] &&
1024           RC->contains(Kill))
1025         return Kill;
1026     }
1027     for (unsigned i = 0, e = LocalUses.size(); i != e; ++i) {
1028       unsigned Reg = LocalUses[i];
1029       Uses.set(Reg);
1030       for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
1031         Uses.set(*AS);
1032     }
1033   }
1034
1035   return 0;
1036 }
1037
1038 static
1039 void AssignPhysToVirtReg(MachineInstr *MI, unsigned VirtReg, unsigned PhysReg,
1040                          const TargetRegisterInfo &TRI) {
1041   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1042     MachineOperand &MO = MI->getOperand(i);
1043     if (MO.isReg() && MO.getReg() == VirtReg)
1044       substitutePhysReg(MO, PhysReg, TRI);
1045   }
1046 }
1047
1048 namespace {
1049
1050 struct RefSorter {
1051   bool operator()(const std::pair<MachineInstr*, int> &A,
1052                   const std::pair<MachineInstr*, int> &B) {
1053     return A.second < B.second;
1054   }
1055 };
1056
1057 // ***************************** //
1058 // Local Spiller Implementation  //
1059 // ***************************** //
1060
1061 class LocalRewriter : public VirtRegRewriter {
1062   MachineRegisterInfo *MRI;
1063   const TargetRegisterInfo *TRI;
1064   const TargetInstrInfo *TII;
1065   VirtRegMap *VRM;
1066   BitVector AllocatableRegs;
1067   DenseMap<MachineInstr*, unsigned> DistanceMap;
1068   DenseMap<int, SmallVector<MachineInstr*,4> > Slot2DbgValues;
1069
1070   MachineBasicBlock *MBB;       // Basic block currently being processed.
1071
1072 public:
1073
1074   bool runOnMachineFunction(MachineFunction &MF, VirtRegMap &VRM,
1075                             LiveIntervals* LIs);
1076
1077 private:
1078
1079   bool OptimizeByUnfold2(unsigned VirtReg, int SS,
1080                          MachineBasicBlock::iterator &MII,
1081                          std::vector<MachineInstr*> &MaybeDeadStores,
1082                          AvailableSpills &Spills,
1083                          BitVector &RegKills,
1084                          std::vector<MachineOperand*> &KillOps);
1085
1086   bool OptimizeByUnfold(MachineBasicBlock::iterator &MII,
1087                         std::vector<MachineInstr*> &MaybeDeadStores,
1088                         AvailableSpills &Spills,
1089                         BitVector &RegKills,
1090                         std::vector<MachineOperand*> &KillOps);
1091
1092   bool CommuteToFoldReload(MachineBasicBlock::iterator &MII,
1093                            unsigned VirtReg, unsigned SrcReg, int SS,
1094                            AvailableSpills &Spills,
1095                            BitVector &RegKills,
1096                            std::vector<MachineOperand*> &KillOps,
1097                            const TargetRegisterInfo *TRI);
1098
1099   void SpillRegToStackSlot(MachineBasicBlock::iterator &MII,
1100                            int Idx, unsigned PhysReg, int StackSlot,
1101                            const TargetRegisterClass *RC,
1102                            bool isAvailable, MachineInstr *&LastStore,
1103                            AvailableSpills &Spills,
1104                            SmallSet<MachineInstr*, 4> &ReMatDefs,
1105                            BitVector &RegKills,
1106                            std::vector<MachineOperand*> &KillOps);
1107
1108   void TransferDeadness(unsigned Reg, BitVector &RegKills,
1109                         std::vector<MachineOperand*> &KillOps);
1110
1111   bool InsertEmergencySpills(MachineInstr *MI);
1112
1113   bool InsertRestores(MachineInstr *MI,
1114                       AvailableSpills &Spills,
1115                       BitVector &RegKills,
1116                       std::vector<MachineOperand*> &KillOps);
1117
1118   bool InsertSpills(MachineInstr *MI);
1119
1120   void RewriteMBB(LiveIntervals *LIs,
1121                   AvailableSpills &Spills, BitVector &RegKills,
1122                   std::vector<MachineOperand*> &KillOps);
1123 };
1124 }
1125
1126 bool LocalRewriter::runOnMachineFunction(MachineFunction &MF, VirtRegMap &vrm,
1127                                          LiveIntervals* LIs) {
1128   MRI = &MF.getRegInfo();
1129   TRI = MF.getTarget().getRegisterInfo();
1130   TII = MF.getTarget().getInstrInfo();
1131   VRM = &vrm;
1132   AllocatableRegs = TRI->getAllocatableSet(MF);
1133   DEBUG(dbgs() << "\n**** Local spiller rewriting function '"
1134         << MF.getFunction()->getName() << "':\n");
1135   DEBUG(dbgs() << "**** Machine Instrs (NOTE! Does not include spills and"
1136         " reloads!) ****\n");
1137   DEBUG(MF.dump());
1138
1139   // Spills - Keep track of which spilled values are available in physregs
1140   // so that we can choose to reuse the physregs instead of emitting
1141   // reloads. This is usually refreshed per basic block.
1142   AvailableSpills Spills(TRI, TII);
1143
1144   // Keep track of kill information.
1145   BitVector RegKills(TRI->getNumRegs());
1146   std::vector<MachineOperand*> KillOps;
1147   KillOps.resize(TRI->getNumRegs(), NULL);
1148
1149   // SingleEntrySuccs - Successor blocks which have a single predecessor.
1150   SmallVector<MachineBasicBlock*, 4> SinglePredSuccs;
1151   SmallPtrSet<MachineBasicBlock*,16> EarlyVisited;
1152
1153   // Traverse the basic blocks depth first.
1154   MachineBasicBlock *Entry = MF.begin();
1155   SmallPtrSet<MachineBasicBlock*,16> Visited;
1156   for (df_ext_iterator<MachineBasicBlock*,
1157          SmallPtrSet<MachineBasicBlock*,16> >
1158          DFI = df_ext_begin(Entry, Visited), E = df_ext_end(Entry, Visited);
1159        DFI != E; ++DFI) {
1160     MBB = *DFI;
1161     if (!EarlyVisited.count(MBB))
1162       RewriteMBB(LIs, Spills, RegKills, KillOps);
1163
1164     // If this MBB is the only predecessor of a successor. Keep the
1165     // availability information and visit it next.
1166     do {
1167       // Keep visiting single predecessor successor as long as possible.
1168       SinglePredSuccs.clear();
1169       findSinglePredSuccessor(MBB, SinglePredSuccs);
1170       if (SinglePredSuccs.empty())
1171         MBB = 0;
1172       else {
1173         // FIXME: More than one successors, each of which has MBB has
1174         // the only predecessor.
1175         MBB = SinglePredSuccs[0];
1176         if (!Visited.count(MBB) && EarlyVisited.insert(MBB)) {
1177           Spills.AddAvailableRegsToLiveIn(*MBB, RegKills, KillOps);
1178           RewriteMBB(LIs, Spills, RegKills, KillOps);
1179         }
1180       }
1181     } while (MBB);
1182
1183     // Clear the availability info.
1184     Spills.clear();
1185   }
1186
1187   DEBUG(dbgs() << "**** Post Machine Instrs ****\n");
1188   DEBUG(MF.dump());
1189
1190   // Mark unused spill slots.
1191   MachineFrameInfo *MFI = MF.getFrameInfo();
1192   int SS = VRM->getLowSpillSlot();
1193   if (SS != VirtRegMap::NO_STACK_SLOT) {
1194     for (int e = VRM->getHighSpillSlot(); SS <= e; ++SS) {
1195       SmallVector<MachineInstr*, 4> &DbgValues = Slot2DbgValues[SS];
1196       if (!VRM->isSpillSlotUsed(SS)) {
1197         MFI->RemoveStackObject(SS);
1198         for (unsigned j = 0, ee = DbgValues.size(); j != ee; ++j) {
1199           MachineInstr *DVMI = DbgValues[j];
1200           MachineBasicBlock *DVMBB = DVMI->getParent();
1201           DEBUG(dbgs() << "Removing debug info referencing FI#" << SS << '\n');
1202           VRM->RemoveMachineInstrFromMaps(DVMI);
1203           DVMBB->erase(DVMI);
1204         }
1205         ++NumDSS;
1206       }
1207       DbgValues.clear();
1208     }
1209   }
1210   Slot2DbgValues.clear();
1211
1212   return true;
1213 }
1214
1215 /// OptimizeByUnfold2 - Unfold a series of load / store folding instructions if
1216 /// a scratch register is available.
1217 ///     xorq  %r12<kill>, %r13
1218 ///     addq  %rax, -184(%rbp)
1219 ///     addq  %r13, -184(%rbp)
1220 /// ==>
1221 ///     xorq  %r12<kill>, %r13
1222 ///     movq  -184(%rbp), %r12
1223 ///     addq  %rax, %r12
1224 ///     addq  %r13, %r12
1225 ///     movq  %r12, -184(%rbp)
1226 bool LocalRewriter::
1227 OptimizeByUnfold2(unsigned VirtReg, int SS,
1228                   MachineBasicBlock::iterator &MII,
1229                   std::vector<MachineInstr*> &MaybeDeadStores,
1230                   AvailableSpills &Spills,
1231                   BitVector &RegKills,
1232                   std::vector<MachineOperand*> &KillOps) {
1233
1234   MachineBasicBlock::iterator NextMII = llvm::next(MII);
1235   // Skip over dbg_value instructions.
1236   while (NextMII != MBB->end() && NextMII->isDebugValue())
1237     NextMII = llvm::next(NextMII);
1238   if (NextMII == MBB->end())
1239     return false;
1240
1241   if (TII->getOpcodeAfterMemoryUnfold(MII->getOpcode(), true, true) == 0)
1242     return false;
1243
1244   // Now let's see if the last couple of instructions happens to have freed up
1245   // a register.
1246   const TargetRegisterClass* RC = MRI->getRegClass(VirtReg);
1247   unsigned PhysReg = FindFreeRegister(MII, *MBB, RC, TRI, AllocatableRegs);
1248   if (!PhysReg)
1249     return false;
1250
1251   MachineFunction &MF = *MBB->getParent();
1252   TRI = MF.getTarget().getRegisterInfo();
1253   MachineInstr &MI = *MII;
1254   if (!FoldsStackSlotModRef(MI, SS, PhysReg, TII, TRI, *VRM))
1255     return false;
1256
1257   // If the next instruction also folds the same SS modref and can be unfoled,
1258   // then it's worthwhile to issue a load from SS into the free register and
1259   // then unfold these instructions.
1260   if (!FoldsStackSlotModRef(*NextMII, SS, PhysReg, TII, TRI, *VRM))
1261     return false;
1262
1263   // Back-schedule reloads and remats.
1264   ComputeReloadLoc(MII, MBB->begin(), PhysReg, TRI, false, SS, TII, MF);
1265
1266   // Load from SS to the spare physical register.
1267   TII->loadRegFromStackSlot(*MBB, MII, PhysReg, SS, RC, TRI);
1268   // This invalidates Phys.
1269   Spills.ClobberPhysReg(PhysReg);
1270   // Remember it's available.
1271   Spills.addAvailable(SS, PhysReg);
1272   MaybeDeadStores[SS] = NULL;
1273
1274   // Unfold current MI.
1275   SmallVector<MachineInstr*, 4> NewMIs;
1276   if (!TII->unfoldMemoryOperand(MF, &MI, VirtReg, false, false, NewMIs))
1277     llvm_unreachable("Unable unfold the load / store folding instruction!");
1278   assert(NewMIs.size() == 1);
1279   AssignPhysToVirtReg(NewMIs[0], VirtReg, PhysReg, *TRI);
1280   VRM->transferRestorePts(&MI, NewMIs[0]);
1281   MII = MBB->insert(MII, NewMIs[0]);
1282   InvalidateKills(MI, TRI, RegKills, KillOps);
1283   VRM->RemoveMachineInstrFromMaps(&MI);
1284   MBB->erase(&MI);
1285   ++NumModRefUnfold;
1286
1287   // Unfold next instructions that fold the same SS.
1288   do {
1289     MachineInstr &NextMI = *NextMII;
1290     NextMII = llvm::next(NextMII);
1291     NewMIs.clear();
1292     if (!TII->unfoldMemoryOperand(MF, &NextMI, VirtReg, false, false, NewMIs))
1293       llvm_unreachable("Unable unfold the load / store folding instruction!");
1294     assert(NewMIs.size() == 1);
1295     AssignPhysToVirtReg(NewMIs[0], VirtReg, PhysReg, *TRI);
1296     VRM->transferRestorePts(&NextMI, NewMIs[0]);
1297     MBB->insert(NextMII, NewMIs[0]);
1298     InvalidateKills(NextMI, TRI, RegKills, KillOps);
1299     VRM->RemoveMachineInstrFromMaps(&NextMI);
1300     MBB->erase(&NextMI);
1301     ++NumModRefUnfold;
1302     // Skip over dbg_value instructions.
1303     while (NextMII != MBB->end() && NextMII->isDebugValue())
1304       NextMII = llvm::next(NextMII);
1305     if (NextMII == MBB->end())
1306       break;
1307   } while (FoldsStackSlotModRef(*NextMII, SS, PhysReg, TII, TRI, *VRM));
1308
1309   // Store the value back into SS.
1310   TII->storeRegToStackSlot(*MBB, NextMII, PhysReg, true, SS, RC, TRI);
1311   MachineInstr *StoreMI = prior(NextMII);
1312   VRM->addSpillSlotUse(SS, StoreMI);
1313   VRM->virtFolded(VirtReg, StoreMI, VirtRegMap::isMod);
1314
1315   return true;
1316 }
1317
1318 /// OptimizeByUnfold - Turn a store folding instruction into a load folding
1319 /// instruction. e.g.
1320 ///     xorl  %edi, %eax
1321 ///     movl  %eax, -32(%ebp)
1322 ///     movl  -36(%ebp), %eax
1323 ///     orl   %eax, -32(%ebp)
1324 /// ==>
1325 ///     xorl  %edi, %eax
1326 ///     orl   -36(%ebp), %eax
1327 ///     mov   %eax, -32(%ebp)
1328 /// This enables unfolding optimization for a subsequent instruction which will
1329 /// also eliminate the newly introduced store instruction.
1330 bool LocalRewriter::
1331 OptimizeByUnfold(MachineBasicBlock::iterator &MII,
1332                  std::vector<MachineInstr*> &MaybeDeadStores,
1333                  AvailableSpills &Spills,
1334                  BitVector &RegKills,
1335                  std::vector<MachineOperand*> &KillOps) {
1336   MachineFunction &MF = *MBB->getParent();
1337   MachineInstr &MI = *MII;
1338   unsigned UnfoldedOpc = 0;
1339   unsigned UnfoldPR = 0;
1340   unsigned UnfoldVR = 0;
1341   int FoldedSS = VirtRegMap::NO_STACK_SLOT;
1342   VirtRegMap::MI2VirtMapTy::const_iterator I, End;
1343   for (tie(I, End) = VRM->getFoldedVirts(&MI); I != End; ) {
1344     // Only transform a MI that folds a single register.
1345     if (UnfoldedOpc)
1346       return false;
1347     UnfoldVR = I->second.first;
1348     VirtRegMap::ModRef MR = I->second.second;
1349     // MI2VirtMap be can updated which invalidate the iterator.
1350     // Increment the iterator first.
1351     ++I;
1352     if (VRM->isAssignedReg(UnfoldVR))
1353       continue;
1354     // If this reference is not a use, any previous store is now dead.
1355     // Otherwise, the store to this stack slot is not dead anymore.
1356     FoldedSS = VRM->getStackSlot(UnfoldVR);
1357     MachineInstr* DeadStore = MaybeDeadStores[FoldedSS];
1358     if (DeadStore && (MR & VirtRegMap::isModRef)) {
1359       unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(FoldedSS);
1360       if (!PhysReg || !DeadStore->readsRegister(PhysReg))
1361         continue;
1362       UnfoldPR = PhysReg;
1363       UnfoldedOpc = TII->getOpcodeAfterMemoryUnfold(MI.getOpcode(),
1364                                                     false, true);
1365     }
1366   }
1367
1368   if (!UnfoldedOpc) {
1369     if (!UnfoldVR)
1370       return false;
1371
1372     // Look for other unfolding opportunities.
1373     return OptimizeByUnfold2(UnfoldVR, FoldedSS, MII, MaybeDeadStores, Spills,
1374                              RegKills, KillOps);
1375   }
1376
1377   for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1378     MachineOperand &MO = MI.getOperand(i);
1379     if (!MO.isReg() || MO.getReg() == 0 || !MO.isUse())
1380       continue;
1381     unsigned VirtReg = MO.getReg();
1382     if (TargetRegisterInfo::isPhysicalRegister(VirtReg) || MO.getSubReg())
1383       continue;
1384     if (VRM->isAssignedReg(VirtReg)) {
1385       unsigned PhysReg = VRM->getPhys(VirtReg);
1386       if (PhysReg && TRI->regsOverlap(PhysReg, UnfoldPR))
1387         return false;
1388     } else if (VRM->isReMaterialized(VirtReg))
1389       continue;
1390     int SS = VRM->getStackSlot(VirtReg);
1391     unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SS);
1392     if (PhysReg) {
1393       if (TRI->regsOverlap(PhysReg, UnfoldPR))
1394         return false;
1395       continue;
1396     }
1397     if (VRM->hasPhys(VirtReg)) {
1398       PhysReg = VRM->getPhys(VirtReg);
1399       if (!TRI->regsOverlap(PhysReg, UnfoldPR))
1400         continue;
1401     }
1402
1403     // Ok, we'll need to reload the value into a register which makes
1404     // it impossible to perform the store unfolding optimization later.
1405     // Let's see if it is possible to fold the load if the store is
1406     // unfolded. This allows us to perform the store unfolding
1407     // optimization.
1408     SmallVector<MachineInstr*, 4> NewMIs;
1409     if (TII->unfoldMemoryOperand(MF, &MI, UnfoldVR, false, false, NewMIs)) {
1410       assert(NewMIs.size() == 1);
1411       MachineInstr *NewMI = NewMIs.back();
1412       MBB->insert(MII, NewMI);
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(NewMI, Ops, SS);
1419       NewMI->eraseFromParent();
1420       if (FoldedMI) {
1421         VRM->addSpillSlotUse(SS, FoldedMI);
1422         if (!VRM->hasPhys(UnfoldVR))
1423           VRM->assignVirt2Phys(UnfoldVR, UnfoldPR);
1424         VRM->virtFolded(VirtReg, FoldedMI, VirtRegMap::isRef);
1425         MII = FoldedMI;
1426         InvalidateKills(MI, TRI, RegKills, KillOps);
1427         VRM->RemoveMachineInstrFromMaps(&MI);
1428         MBB->erase(&MI);
1429         return true;
1430       }
1431     }
1432   }
1433
1434   return false;
1435 }
1436
1437 /// CommuteChangesDestination - We are looking for r0 = op r1, r2 and
1438 /// where SrcReg is r1 and it is tied to r0. Return true if after
1439 /// commuting this instruction it will be r0 = op r2, r1.
1440 static bool CommuteChangesDestination(MachineInstr *DefMI,
1441                                       const TargetInstrDesc &TID,
1442                                       unsigned SrcReg,
1443                                       const TargetInstrInfo *TII,
1444                                       unsigned &DstIdx) {
1445   if (TID.getNumDefs() != 1 && TID.getNumOperands() != 3)
1446     return false;
1447   if (!DefMI->getOperand(1).isReg() ||
1448       DefMI->getOperand(1).getReg() != SrcReg)
1449     return false;
1450   unsigned DefIdx;
1451   if (!DefMI->isRegTiedToDefOperand(1, &DefIdx) || DefIdx != 0)
1452     return false;
1453   unsigned SrcIdx1, SrcIdx2;
1454   if (!TII->findCommutedOpIndices(DefMI, SrcIdx1, SrcIdx2))
1455     return false;
1456   if (SrcIdx1 == 1 && SrcIdx2 == 2) {
1457     DstIdx = 2;
1458     return true;
1459   }
1460   return false;
1461 }
1462
1463 /// CommuteToFoldReload -
1464 /// Look for
1465 /// r1 = load fi#1
1466 /// r1 = op r1, r2<kill>
1467 /// store r1, fi#1
1468 ///
1469 /// If op is commutable and r2 is killed, then we can xform these to
1470 /// r2 = op r2, fi#1
1471 /// store r2, fi#1
1472 bool LocalRewriter::
1473 CommuteToFoldReload(MachineBasicBlock::iterator &MII,
1474                     unsigned VirtReg, unsigned SrcReg, int SS,
1475                     AvailableSpills &Spills,
1476                     BitVector &RegKills,
1477                     std::vector<MachineOperand*> &KillOps,
1478                     const TargetRegisterInfo *TRI) {
1479   if (MII == MBB->begin() || !MII->killsRegister(SrcReg))
1480     return false;
1481
1482   MachineInstr &MI = *MII;
1483   MachineBasicBlock::iterator DefMII = prior(MII);
1484   MachineInstr *DefMI = DefMII;
1485   const TargetInstrDesc &TID = DefMI->getDesc();
1486   unsigned NewDstIdx;
1487   if (DefMII != MBB->begin() &&
1488       TID.isCommutable() &&
1489       CommuteChangesDestination(DefMI, TID, SrcReg, TII, NewDstIdx)) {
1490     MachineOperand &NewDstMO = DefMI->getOperand(NewDstIdx);
1491     unsigned NewReg = NewDstMO.getReg();
1492     if (!NewDstMO.isKill() || TRI->regsOverlap(NewReg, SrcReg))
1493       return false;
1494     MachineInstr *ReloadMI = prior(DefMII);
1495     int FrameIdx;
1496     unsigned DestReg = TII->isLoadFromStackSlot(ReloadMI, FrameIdx);
1497     if (DestReg != SrcReg || FrameIdx != SS)
1498       return false;
1499     int UseIdx = DefMI->findRegisterUseOperandIdx(DestReg, false);
1500     if (UseIdx == -1)
1501       return false;
1502     unsigned DefIdx;
1503     if (!MI.isRegTiedToDefOperand(UseIdx, &DefIdx))
1504       return false;
1505     assert(DefMI->getOperand(DefIdx).isReg() &&
1506            DefMI->getOperand(DefIdx).getReg() == SrcReg);
1507
1508     // Now commute def instruction.
1509     MachineInstr *CommutedMI = TII->commuteInstruction(DefMI, true);
1510     if (!CommutedMI)
1511       return false;
1512     MBB->insert(MII, CommutedMI);
1513     SmallVector<unsigned, 1> Ops;
1514     Ops.push_back(NewDstIdx);
1515     MachineInstr *FoldedMI = TII->foldMemoryOperand(CommutedMI, Ops, SS);
1516     // Not needed since foldMemoryOperand returns new MI.
1517     CommutedMI->eraseFromParent();
1518     if (!FoldedMI)
1519       return false;
1520
1521     VRM->addSpillSlotUse(SS, FoldedMI);
1522     VRM->virtFolded(VirtReg, FoldedMI, VirtRegMap::isRef);
1523     // Insert new def MI and spill MI.
1524     const TargetRegisterClass* RC = MRI->getRegClass(VirtReg);
1525     TII->storeRegToStackSlot(*MBB, &MI, NewReg, true, SS, RC, TRI);
1526     MII = prior(MII);
1527     MachineInstr *StoreMI = MII;
1528     VRM->addSpillSlotUse(SS, StoreMI);
1529     VRM->virtFolded(VirtReg, StoreMI, VirtRegMap::isMod);
1530     MII = FoldedMI;  // Update MII to backtrack.
1531
1532     // Delete all 3 old instructions.
1533     InvalidateKills(*ReloadMI, TRI, RegKills, KillOps);
1534     VRM->RemoveMachineInstrFromMaps(ReloadMI);
1535     MBB->erase(ReloadMI);
1536     InvalidateKills(*DefMI, TRI, RegKills, KillOps);
1537     VRM->RemoveMachineInstrFromMaps(DefMI);
1538     MBB->erase(DefMI);
1539     InvalidateKills(MI, TRI, RegKills, KillOps);
1540     VRM->RemoveMachineInstrFromMaps(&MI);
1541     MBB->erase(&MI);
1542
1543     // If NewReg was previously holding value of some SS, it's now clobbered.
1544     // This has to be done now because it's a physical register. When this
1545     // instruction is re-visited, it's ignored.
1546     Spills.ClobberPhysReg(NewReg);
1547
1548     ++NumCommutes;
1549     return true;
1550   }
1551
1552   return false;
1553 }
1554
1555 /// SpillRegToStackSlot - Spill a register to a specified stack slot. Check if
1556 /// the last store to the same slot is now dead. If so, remove the last store.
1557 void LocalRewriter::
1558 SpillRegToStackSlot(MachineBasicBlock::iterator &MII,
1559                     int Idx, unsigned PhysReg, int StackSlot,
1560                     const TargetRegisterClass *RC,
1561                     bool isAvailable, MachineInstr *&LastStore,
1562                     AvailableSpills &Spills,
1563                     SmallSet<MachineInstr*, 4> &ReMatDefs,
1564                     BitVector &RegKills,
1565                     std::vector<MachineOperand*> &KillOps) {
1566
1567   MachineBasicBlock::iterator oldNextMII = llvm::next(MII);
1568   TII->storeRegToStackSlot(*MBB, llvm::next(MII), PhysReg, true, StackSlot, RC,
1569                            TRI);
1570   MachineInstr *StoreMI = prior(oldNextMII);
1571   VRM->addSpillSlotUse(StackSlot, StoreMI);
1572   DEBUG(dbgs() << "Store:\t" << *StoreMI);
1573
1574   // If there is a dead store to this stack slot, nuke it now.
1575   if (LastStore) {
1576     DEBUG(dbgs() << "Removed dead store:\t" << *LastStore);
1577     ++NumDSE;
1578     SmallVector<unsigned, 2> KillRegs;
1579     InvalidateKills(*LastStore, TRI, RegKills, KillOps, &KillRegs);
1580     MachineBasicBlock::iterator PrevMII = LastStore;
1581     bool CheckDef = PrevMII != MBB->begin();
1582     if (CheckDef)
1583       --PrevMII;
1584     VRM->RemoveMachineInstrFromMaps(LastStore);
1585     MBB->erase(LastStore);
1586     if (CheckDef) {
1587       // Look at defs of killed registers on the store. Mark the defs
1588       // as dead since the store has been deleted and they aren't
1589       // being reused.
1590       for (unsigned j = 0, ee = KillRegs.size(); j != ee; ++j) {
1591         bool HasOtherDef = false;
1592         if (InvalidateRegDef(PrevMII, *MII, KillRegs[j], HasOtherDef, TRI)) {
1593           MachineInstr *DeadDef = PrevMII;
1594           if (ReMatDefs.count(DeadDef) && !HasOtherDef) {
1595             // FIXME: This assumes a remat def does not have side effects.
1596             VRM->RemoveMachineInstrFromMaps(DeadDef);
1597             MBB->erase(DeadDef);
1598             ++NumDRM;
1599           }
1600         }
1601       }
1602     }
1603   }
1604
1605   // Allow for multi-instruction spill sequences, as on PPC Altivec.  Presume
1606   // the last of multiple instructions is the actual store.
1607   LastStore = prior(oldNextMII);
1608
1609   // If the stack slot value was previously available in some other
1610   // register, change it now.  Otherwise, make the register available,
1611   // in PhysReg.
1612   Spills.ModifyStackSlotOrReMat(StackSlot);
1613   Spills.ClobberPhysReg(PhysReg);
1614   Spills.addAvailable(StackSlot, PhysReg, isAvailable);
1615   ++NumStores;
1616 }
1617
1618 /// isSafeToDelete - Return true if this instruction doesn't produce any side
1619 /// effect and all of its defs are dead.
1620 static bool isSafeToDelete(MachineInstr &MI) {
1621   const TargetInstrDesc &TID = MI.getDesc();
1622   if (TID.mayLoad() || TID.mayStore() || TID.isCall() || TID.isTerminator() ||
1623       TID.isCall() || TID.isBarrier() || TID.isReturn() ||
1624       TID.hasUnmodeledSideEffects())
1625     return false;
1626   for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1627     MachineOperand &MO = MI.getOperand(i);
1628     if (!MO.isReg() || !MO.getReg())
1629       continue;
1630     if (MO.isDef() && !MO.isDead())
1631       return false;
1632     if (MO.isUse() && MO.isKill())
1633       // FIXME: We can't remove kill markers or else the scavenger will assert.
1634       // An alternative is to add a ADD pseudo instruction to replace kill
1635       // markers.
1636       return false;
1637   }
1638   return true;
1639 }
1640
1641 /// TransferDeadness - A identity copy definition is dead and it's being
1642 /// removed. Find the last def or use and mark it as dead / kill.
1643 void LocalRewriter::
1644 TransferDeadness(unsigned Reg, BitVector &RegKills,
1645                  std::vector<MachineOperand*> &KillOps) {
1646   SmallPtrSet<MachineInstr*, 4> Seens;
1647   SmallVector<std::pair<MachineInstr*, int>,8> Refs;
1648   for (MachineRegisterInfo::reg_iterator RI = MRI->reg_begin(Reg),
1649          RE = MRI->reg_end(); RI != RE; ++RI) {
1650     MachineInstr *UDMI = &*RI;
1651     if (UDMI->isDebugValue() || UDMI->getParent() != MBB)
1652       continue;
1653     DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(UDMI);
1654     if (DI == DistanceMap.end())
1655       continue;
1656     if (Seens.insert(UDMI))
1657       Refs.push_back(std::make_pair(UDMI, DI->second));
1658   }
1659
1660   if (Refs.empty())
1661     return;
1662   std::sort(Refs.begin(), Refs.end(), RefSorter());
1663
1664   while (!Refs.empty()) {
1665     MachineInstr *LastUDMI = Refs.back().first;
1666     Refs.pop_back();
1667
1668     MachineOperand *LastUD = NULL;
1669     for (unsigned i = 0, e = LastUDMI->getNumOperands(); i != e; ++i) {
1670       MachineOperand &MO = LastUDMI->getOperand(i);
1671       if (!MO.isReg() || MO.getReg() != Reg)
1672         continue;
1673       if (!LastUD || (LastUD->isUse() && MO.isDef()))
1674         LastUD = &MO;
1675       if (LastUDMI->isRegTiedToDefOperand(i))
1676         break;
1677     }
1678     if (LastUD->isDef()) {
1679       // If the instruction has no side effect, delete it and propagate
1680       // backward further. Otherwise, mark is dead and we are done.
1681       if (!isSafeToDelete(*LastUDMI)) {
1682         LastUD->setIsDead();
1683         break;
1684       }
1685       VRM->RemoveMachineInstrFromMaps(LastUDMI);
1686       MBB->erase(LastUDMI);
1687     } else {
1688       LastUD->setIsKill();
1689       RegKills.set(Reg);
1690       KillOps[Reg] = LastUD;
1691       break;
1692     }
1693   }
1694 }
1695
1696 /// InsertEmergencySpills - Insert emergency spills before MI if requested by
1697 /// VRM. Return true if spills were inserted.
1698 bool LocalRewriter::InsertEmergencySpills(MachineInstr *MI) {
1699   if (!VRM->hasEmergencySpills(MI))
1700     return false;
1701   MachineBasicBlock::iterator MII = MI;
1702   SmallSet<int, 4> UsedSS;
1703   std::vector<unsigned> &EmSpills = VRM->getEmergencySpills(MI);
1704   for (unsigned i = 0, e = EmSpills.size(); i != e; ++i) {
1705     unsigned PhysReg = EmSpills[i];
1706     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(PhysReg);
1707     assert(RC && "Unable to determine register class!");
1708     int SS = VRM->getEmergencySpillSlot(RC);
1709     if (UsedSS.count(SS))
1710       llvm_unreachable("Need to spill more than one physical registers!");
1711     UsedSS.insert(SS);
1712     TII->storeRegToStackSlot(*MBB, MII, PhysReg, true, SS, RC, TRI);
1713     MachineInstr *StoreMI = prior(MII);
1714     VRM->addSpillSlotUse(SS, StoreMI);
1715
1716     // Back-schedule reloads and remats.
1717     MachineBasicBlock::iterator InsertLoc =
1718       ComputeReloadLoc(llvm::next(MII), MBB->begin(), PhysReg, TRI, false, SS,
1719                        TII, *MBB->getParent());
1720
1721     TII->loadRegFromStackSlot(*MBB, InsertLoc, PhysReg, SS, RC, TRI);
1722
1723     MachineInstr *LoadMI = prior(InsertLoc);
1724     VRM->addSpillSlotUse(SS, LoadMI);
1725     ++NumPSpills;
1726     DistanceMap.insert(std::make_pair(LoadMI, DistanceMap.size()));
1727   }
1728   return true;
1729 }
1730
1731 /// InsertRestores - Restore registers before MI is requested by VRM. Return
1732 /// true is any instructions were inserted.
1733 bool LocalRewriter::InsertRestores(MachineInstr *MI,
1734                                    AvailableSpills &Spills,
1735                                    BitVector &RegKills,
1736                                    std::vector<MachineOperand*> &KillOps) {
1737   if (!VRM->isRestorePt(MI))
1738     return false;
1739   MachineBasicBlock::iterator MII = MI;
1740   std::vector<unsigned> &RestoreRegs = VRM->getRestorePtRestores(MI);
1741   for (unsigned i = 0, e = RestoreRegs.size(); i != e; ++i) {
1742     unsigned VirtReg = RestoreRegs[e-i-1];  // Reverse order.
1743     if (!VRM->getPreSplitReg(VirtReg))
1744       continue; // Split interval spilled again.
1745     unsigned Phys = VRM->getPhys(VirtReg);
1746     MRI->setPhysRegUsed(Phys);
1747
1748     // Check if the value being restored if available. If so, it must be
1749     // from a predecessor BB that fallthrough into this BB. We do not
1750     // expect:
1751     // BB1:
1752     // r1 = load fi#1
1753     // ...
1754     //    = r1<kill>
1755     // ... # r1 not clobbered
1756     // ...
1757     //    = load fi#1
1758     bool DoReMat = VRM->isReMaterialized(VirtReg);
1759     int SSorRMId = DoReMat
1760       ? VRM->getReMatId(VirtReg) : VRM->getStackSlot(VirtReg);
1761     unsigned InReg = Spills.getSpillSlotOrReMatPhysReg(SSorRMId);
1762     if (InReg == Phys) {
1763       // If the value is already available in the expected register, save
1764       // a reload / remat.
1765       if (SSorRMId)
1766         DEBUG(dbgs() << "Reusing RM#"
1767                      << SSorRMId-VirtRegMap::MAX_STACK_SLOT-1);
1768       else
1769         DEBUG(dbgs() << "Reusing SS#" << SSorRMId);
1770       DEBUG(dbgs() << " from physreg "
1771                    << TRI->getName(InReg) << " for vreg"
1772                    << VirtReg <<" instead of reloading into physreg "
1773                    << TRI->getName(Phys) << '\n');
1774       ++NumOmitted;
1775       continue;
1776     } else if (InReg && InReg != Phys) {
1777       if (SSorRMId)
1778         DEBUG(dbgs() << "Reusing RM#"
1779                      << SSorRMId-VirtRegMap::MAX_STACK_SLOT-1);
1780       else
1781         DEBUG(dbgs() << "Reusing SS#" << SSorRMId);
1782       DEBUG(dbgs() << " from physreg "
1783                    << TRI->getName(InReg) << " for vreg"
1784                    << VirtReg <<" by copying it into physreg "
1785                    << TRI->getName(Phys) << '\n');
1786
1787       // If the reloaded / remat value is available in another register,
1788       // copy it to the desired register.
1789
1790       // Back-schedule reloads and remats.
1791       MachineBasicBlock::iterator InsertLoc =
1792         ComputeReloadLoc(MII, MBB->begin(), Phys, TRI, DoReMat, SSorRMId, TII,
1793                          *MBB->getParent());
1794       MachineInstr *CopyMI = BuildMI(*MBB, InsertLoc, MI->getDebugLoc(),
1795                                      TII->get(TargetOpcode::COPY), Phys)
1796                                .addReg(InReg, RegState::Kill);
1797
1798       // This invalidates Phys.
1799       Spills.ClobberPhysReg(Phys);
1800       // Remember it's available.
1801       Spills.addAvailable(SSorRMId, Phys);
1802
1803       CopyMI->setAsmPrinterFlag(MachineInstr::ReloadReuse);
1804       UpdateKills(*CopyMI, TRI, RegKills, KillOps);
1805
1806       DEBUG(dbgs() << '\t' << *CopyMI);
1807       ++NumCopified;
1808       continue;
1809     }
1810
1811     // Back-schedule reloads and remats.
1812     MachineBasicBlock::iterator InsertLoc =
1813       ComputeReloadLoc(MII, MBB->begin(), Phys, TRI, DoReMat, SSorRMId, TII,
1814                        *MBB->getParent());
1815
1816     if (VRM->isReMaterialized(VirtReg)) {
1817       ReMaterialize(*MBB, InsertLoc, Phys, VirtReg, TII, TRI, *VRM);
1818     } else {
1819       const TargetRegisterClass* RC = MRI->getRegClass(VirtReg);
1820       TII->loadRegFromStackSlot(*MBB, InsertLoc, Phys, SSorRMId, RC, TRI);
1821       MachineInstr *LoadMI = prior(InsertLoc);
1822       VRM->addSpillSlotUse(SSorRMId, LoadMI);
1823       ++NumLoads;
1824       DistanceMap.insert(std::make_pair(LoadMI, DistanceMap.size()));
1825     }
1826
1827     // This invalidates Phys.
1828     Spills.ClobberPhysReg(Phys);
1829     // Remember it's available.
1830     Spills.addAvailable(SSorRMId, Phys);
1831
1832     UpdateKills(*prior(InsertLoc), TRI, RegKills, KillOps);
1833     DEBUG(dbgs() << '\t' << *prior(MII));
1834   }
1835   return true;
1836 }
1837
1838 /// InsertEmergencySpills - Insert spills after MI if requested by VRM. Return
1839 /// true if spills were inserted.
1840 bool LocalRewriter::InsertSpills(MachineInstr *MI) {
1841   if (!VRM->isSpillPt(MI))
1842     return false;
1843   MachineBasicBlock::iterator MII = MI;
1844   std::vector<std::pair<unsigned,bool> > &SpillRegs =
1845     VRM->getSpillPtSpills(MI);
1846   for (unsigned i = 0, e = SpillRegs.size(); i != e; ++i) {
1847     unsigned VirtReg = SpillRegs[i].first;
1848     bool isKill = SpillRegs[i].second;
1849     if (!VRM->getPreSplitReg(VirtReg))
1850       continue; // Split interval spilled again.
1851     const TargetRegisterClass *RC = MRI->getRegClass(VirtReg);
1852     unsigned Phys = VRM->getPhys(VirtReg);
1853     int StackSlot = VRM->getStackSlot(VirtReg);
1854     MachineBasicBlock::iterator oldNextMII = llvm::next(MII);
1855     TII->storeRegToStackSlot(*MBB, llvm::next(MII), Phys, isKill, StackSlot,
1856                              RC, TRI);
1857     MachineInstr *StoreMI = prior(oldNextMII);
1858     VRM->addSpillSlotUse(StackSlot, StoreMI);
1859     DEBUG(dbgs() << "Store:\t" << *StoreMI);
1860     VRM->virtFolded(VirtReg, StoreMI, VirtRegMap::isMod);
1861   }
1862   return true;
1863 }
1864
1865
1866 /// rewriteMBB - Keep track of which spills are available even after the
1867 /// register allocator is done with them.  If possible, avid reloading vregs.
1868 void
1869 LocalRewriter::RewriteMBB(LiveIntervals *LIs,
1870                           AvailableSpills &Spills, BitVector &RegKills,
1871                           std::vector<MachineOperand*> &KillOps) {
1872
1873   DEBUG(dbgs() << "\n**** Local spiller rewriting MBB '"
1874                << MBB->getName() << "':\n");
1875
1876   MachineFunction &MF = *MBB->getParent();
1877
1878   // MaybeDeadStores - When we need to write a value back into a stack slot,
1879   // keep track of the inserted store.  If the stack slot value is never read
1880   // (because the value was used from some available register, for example), and
1881   // subsequently stored to, the original store is dead.  This map keeps track
1882   // of inserted stores that are not used.  If we see a subsequent store to the
1883   // same stack slot, the original store is deleted.
1884   std::vector<MachineInstr*> MaybeDeadStores;
1885   MaybeDeadStores.resize(MF.getFrameInfo()->getObjectIndexEnd(), NULL);
1886
1887   // ReMatDefs - These are rematerializable def MIs which are not deleted.
1888   SmallSet<MachineInstr*, 4> ReMatDefs;
1889
1890   // Clear kill info.
1891   SmallSet<unsigned, 2> KilledMIRegs;
1892
1893   // Keep track of the registers we have already spilled in case there are
1894   // multiple defs of the same register in MI.
1895   SmallSet<unsigned, 8> SpilledMIRegs;
1896
1897   RegKills.reset();
1898   KillOps.clear();
1899   KillOps.resize(TRI->getNumRegs(), NULL);
1900
1901   DistanceMap.clear();
1902   for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end();
1903        MII != E; ) {
1904     MachineBasicBlock::iterator NextMII = llvm::next(MII);
1905
1906     if (OptimizeByUnfold(MII, MaybeDeadStores, Spills, RegKills, KillOps))
1907       NextMII = llvm::next(MII);
1908
1909     if (InsertEmergencySpills(MII))
1910       NextMII = llvm::next(MII);
1911
1912     InsertRestores(MII, Spills, RegKills, KillOps);
1913
1914     if (InsertSpills(MII))
1915       NextMII = llvm::next(MII);
1916
1917     VirtRegMap::MI2VirtMapTy::const_iterator I, End;
1918     bool Erased = false;
1919     bool BackTracked = false;
1920     MachineInstr &MI = *MII;
1921
1922     // Remember DbgValue's which reference stack slots.
1923     if (MI.isDebugValue() && MI.getOperand(0).isFI())
1924       Slot2DbgValues[MI.getOperand(0).getIndex()].push_back(&MI);
1925
1926     /// ReusedOperands - Keep track of operand reuse in case we need to undo
1927     /// reuse.
1928     ReuseInfo ReusedOperands(MI, TRI);
1929     SmallVector<unsigned, 4> VirtUseOps;
1930     for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1931       MachineOperand &MO = MI.getOperand(i);
1932       if (!MO.isReg() || MO.getReg() == 0)
1933         continue;   // Ignore non-register operands.
1934
1935       unsigned VirtReg = MO.getReg();
1936       if (TargetRegisterInfo::isPhysicalRegister(VirtReg)) {
1937         // Ignore physregs for spilling, but remember that it is used by this
1938         // function.
1939         MRI->setPhysRegUsed(VirtReg);
1940         continue;
1941       }
1942
1943       // We want to process implicit virtual register uses first.
1944       if (MO.isImplicit())
1945         // If the virtual register is implicitly defined, emit a implicit_def
1946         // before so scavenger knows it's "defined".
1947         // FIXME: This is a horrible hack done the by register allocator to
1948         // remat a definition with virtual register operand.
1949         VirtUseOps.insert(VirtUseOps.begin(), i);
1950       else
1951         VirtUseOps.push_back(i);
1952     }
1953
1954     // Process all of the spilled uses and all non spilled reg references.
1955     SmallVector<int, 2> PotentialDeadStoreSlots;
1956     KilledMIRegs.clear();
1957     for (unsigned j = 0, e = VirtUseOps.size(); j != e; ++j) {
1958       unsigned i = VirtUseOps[j];
1959       unsigned VirtReg = MI.getOperand(i).getReg();
1960       assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
1961              "Not a virtual register?");
1962
1963       unsigned SubIdx = MI.getOperand(i).getSubReg();
1964       if (VRM->isAssignedReg(VirtReg)) {
1965         // This virtual register was assigned a physreg!
1966         unsigned Phys = VRM->getPhys(VirtReg);
1967         MRI->setPhysRegUsed(Phys);
1968         if (MI.getOperand(i).isDef())
1969           ReusedOperands.markClobbered(Phys);
1970         substitutePhysReg(MI.getOperand(i), Phys, *TRI);
1971         if (VRM->isImplicitlyDefined(VirtReg))
1972           // FIXME: Is this needed?
1973           BuildMI(*MBB, &MI, MI.getDebugLoc(),
1974                   TII->get(TargetOpcode::IMPLICIT_DEF), Phys);
1975         continue;
1976       }
1977
1978       // This virtual register is now known to be a spilled value.
1979       if (!MI.getOperand(i).isUse())
1980         continue;  // Handle defs in the loop below (handle use&def here though)
1981
1982       bool AvoidReload = MI.getOperand(i).isUndef();
1983       // Check if it is defined by an implicit def. It should not be spilled.
1984       // Note, this is for correctness reason. e.g.
1985       // 8   %reg1024<def> = IMPLICIT_DEF
1986       // 12  %reg1024<def> = INSERT_SUBREG %reg1024<kill>, %reg1025, 2
1987       // The live range [12, 14) are not part of the r1024 live interval since
1988       // it's defined by an implicit def. It will not conflicts with live
1989       // interval of r1025. Now suppose both registers are spilled, you can
1990       // easily see a situation where both registers are reloaded before
1991       // the INSERT_SUBREG and both target registers that would overlap.
1992       bool DoReMat = VRM->isReMaterialized(VirtReg);
1993       int SSorRMId = DoReMat
1994         ? VRM->getReMatId(VirtReg) : VRM->getStackSlot(VirtReg);
1995       int ReuseSlot = SSorRMId;
1996
1997       // Check to see if this stack slot is available.
1998       unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SSorRMId);
1999
2000       // If this is a sub-register use, make sure the reuse register is in the
2001       // right register class. For example, for x86 not all of the 32-bit
2002       // registers have accessible sub-registers.
2003       // Similarly so for EXTRACT_SUBREG. Consider this:
2004       // EDI = op
2005       // MOV32_mr fi#1, EDI
2006       // ...
2007       //       = EXTRACT_SUBREG fi#1
2008       // fi#1 is available in EDI, but it cannot be reused because it's not in
2009       // the right register file.
2010       if (PhysReg && !AvoidReload && SubIdx) {
2011         const TargetRegisterClass* RC = MRI->getRegClass(VirtReg);
2012         if (!RC->contains(PhysReg))
2013           PhysReg = 0;
2014       }
2015
2016       if (PhysReg && !AvoidReload) {
2017         // This spilled operand might be part of a two-address operand.  If this
2018         // is the case, then changing it will necessarily require changing the
2019         // def part of the instruction as well.  However, in some cases, we
2020         // aren't allowed to modify the reused register.  If none of these cases
2021         // apply, reuse it.
2022         bool CanReuse = true;
2023         bool isTied = MI.isRegTiedToDefOperand(i);
2024         if (isTied) {
2025           // Okay, we have a two address operand.  We can reuse this physreg as
2026           // long as we are allowed to clobber the value and there isn't an
2027           // earlier def that has already clobbered the physreg.
2028           CanReuse = !ReusedOperands.isClobbered(PhysReg) &&
2029             Spills.canClobberPhysReg(PhysReg);
2030         }
2031         // If this is an asm, and PhysReg is used elsewhere as an earlyclobber
2032         // operand, we can't also use it as an input.  (Outputs always come
2033         // before inputs, so we can stop looking at i.)
2034         if (MI.isInlineAsm()) {
2035           for (unsigned k=0; k<i; ++k) {
2036             MachineOperand &MOk = MI.getOperand(k);
2037             if (MOk.isReg() && MOk.getReg()==PhysReg && MOk.isEarlyClobber()) {
2038               CanReuse = false;
2039               break;
2040             }
2041           }
2042         }
2043
2044         if (CanReuse) {
2045           // If this stack slot value is already available, reuse it!
2046           if (ReuseSlot > VirtRegMap::MAX_STACK_SLOT)
2047             DEBUG(dbgs() << "Reusing RM#"
2048                   << ReuseSlot-VirtRegMap::MAX_STACK_SLOT-1);
2049           else
2050             DEBUG(dbgs() << "Reusing SS#" << ReuseSlot);
2051           DEBUG(dbgs() << " from physreg "
2052                 << TRI->getName(PhysReg) << " for vreg"
2053                 << VirtReg <<" instead of reloading into physreg "
2054                 << TRI->getName(VRM->getPhys(VirtReg)) << '\n');
2055           unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
2056           MI.getOperand(i).setReg(RReg);
2057           MI.getOperand(i).setSubReg(0);
2058
2059           // The only technical detail we have is that we don't know that
2060           // PhysReg won't be clobbered by a reloaded stack slot that occurs
2061           // later in the instruction.  In particular, consider 'op V1, V2'.
2062           // If V1 is available in physreg R0, we would choose to reuse it
2063           // here, instead of reloading it into the register the allocator
2064           // indicated (say R1).  However, V2 might have to be reloaded
2065           // later, and it might indicate that it needs to live in R0.  When
2066           // this occurs, we need to have information available that
2067           // indicates it is safe to use R1 for the reload instead of R0.
2068           //
2069           // To further complicate matters, we might conflict with an alias,
2070           // or R0 and R1 might not be compatible with each other.  In this
2071           // case, we actually insert a reload for V1 in R1, ensuring that
2072           // we can get at R0 or its alias.
2073           ReusedOperands.addReuse(i, ReuseSlot, PhysReg,
2074                                   VRM->getPhys(VirtReg), VirtReg);
2075           if (isTied)
2076             // Only mark it clobbered if this is a use&def operand.
2077             ReusedOperands.markClobbered(PhysReg);
2078           ++NumReused;
2079
2080           if (MI.getOperand(i).isKill() &&
2081               ReuseSlot <= VirtRegMap::MAX_STACK_SLOT) {
2082
2083             // The store of this spilled value is potentially dead, but we
2084             // won't know for certain until we've confirmed that the re-use
2085             // above is valid, which means waiting until the other operands
2086             // are processed. For now we just track the spill slot, we'll
2087             // remove it after the other operands are processed if valid.
2088
2089             PotentialDeadStoreSlots.push_back(ReuseSlot);
2090           }
2091
2092           // Mark is isKill if it's there no other uses of the same virtual
2093           // register and it's not a two-address operand. IsKill will be
2094           // unset if reg is reused.
2095           if (!isTied && KilledMIRegs.count(VirtReg) == 0) {
2096             MI.getOperand(i).setIsKill();
2097             KilledMIRegs.insert(VirtReg);
2098           }
2099
2100           continue;
2101         }  // CanReuse
2102
2103         // Otherwise we have a situation where we have a two-address instruction
2104         // whose mod/ref operand needs to be reloaded.  This reload is already
2105         // available in some register "PhysReg", but if we used PhysReg as the
2106         // operand to our 2-addr instruction, the instruction would modify
2107         // PhysReg.  This isn't cool if something later uses PhysReg and expects
2108         // to get its initial value.
2109         //
2110         // To avoid this problem, and to avoid doing a load right after a store,
2111         // we emit a copy from PhysReg into the designated register for this
2112         // operand.
2113         //
2114         // This case also applies to an earlyclobber'd PhysReg.
2115         unsigned DesignatedReg = VRM->getPhys(VirtReg);
2116         assert(DesignatedReg && "Must map virtreg to physreg!");
2117
2118         // Note that, if we reused a register for a previous operand, the
2119         // register we want to reload into might not actually be
2120         // available.  If this occurs, use the register indicated by the
2121         // reuser.
2122         if (ReusedOperands.hasReuses())
2123           DesignatedReg = ReusedOperands.
2124             GetRegForReload(VirtReg, DesignatedReg, &MI, Spills,
2125                             MaybeDeadStores, RegKills, KillOps, *VRM);
2126
2127         // If the mapped designated register is actually the physreg we have
2128         // incoming, we don't need to inserted a dead copy.
2129         if (DesignatedReg == PhysReg) {
2130           // If this stack slot value is already available, reuse it!
2131           if (ReuseSlot > VirtRegMap::MAX_STACK_SLOT)
2132             DEBUG(dbgs() << "Reusing RM#"
2133                   << ReuseSlot-VirtRegMap::MAX_STACK_SLOT-1);
2134           else
2135             DEBUG(dbgs() << "Reusing SS#" << ReuseSlot);
2136           DEBUG(dbgs() << " from physreg " << TRI->getName(PhysReg)
2137                 << " for vreg" << VirtReg
2138                 << " instead of reloading into same physreg.\n");
2139           unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
2140           MI.getOperand(i).setReg(RReg);
2141           MI.getOperand(i).setSubReg(0);
2142           ReusedOperands.markClobbered(RReg);
2143           ++NumReused;
2144           continue;
2145         }
2146
2147         MRI->setPhysRegUsed(DesignatedReg);
2148         ReusedOperands.markClobbered(DesignatedReg);
2149
2150         // Back-schedule reloads and remats.
2151         MachineBasicBlock::iterator InsertLoc =
2152           ComputeReloadLoc(&MI, MBB->begin(), PhysReg, TRI, DoReMat,
2153                            SSorRMId, TII, MF);
2154         MachineInstr *CopyMI = BuildMI(*MBB, InsertLoc, MI.getDebugLoc(),
2155                                        TII->get(TargetOpcode::COPY),
2156                                        DesignatedReg).addReg(PhysReg);
2157         CopyMI->setAsmPrinterFlag(MachineInstr::ReloadReuse);
2158         UpdateKills(*CopyMI, TRI, RegKills, KillOps);
2159
2160         // This invalidates DesignatedReg.
2161         Spills.ClobberPhysReg(DesignatedReg);
2162
2163         Spills.addAvailable(ReuseSlot, DesignatedReg);
2164         unsigned RReg =
2165           SubIdx ? TRI->getSubReg(DesignatedReg, SubIdx) : DesignatedReg;
2166         MI.getOperand(i).setReg(RReg);
2167         MI.getOperand(i).setSubReg(0);
2168         DEBUG(dbgs() << '\t' << *prior(MII));
2169         ++NumReused;
2170         continue;
2171       } // if (PhysReg)
2172
2173         // Otherwise, reload it and remember that we have it.
2174       PhysReg = VRM->getPhys(VirtReg);
2175       assert(PhysReg && "Must map virtreg to physreg!");
2176
2177       // Note that, if we reused a register for a previous operand, the
2178       // register we want to reload into might not actually be
2179       // available.  If this occurs, use the register indicated by the
2180       // reuser.
2181       if (ReusedOperands.hasReuses())
2182         PhysReg = ReusedOperands.GetRegForReload(VirtReg, PhysReg, &MI,
2183                     Spills, MaybeDeadStores, RegKills, KillOps, *VRM);
2184
2185       MRI->setPhysRegUsed(PhysReg);
2186       ReusedOperands.markClobbered(PhysReg);
2187       if (AvoidReload)
2188         ++NumAvoided;
2189       else {
2190         // Back-schedule reloads and remats.
2191         MachineBasicBlock::iterator InsertLoc =
2192           ComputeReloadLoc(MII, MBB->begin(), PhysReg, TRI, DoReMat,
2193                            SSorRMId, TII, MF);
2194
2195         if (DoReMat) {
2196           ReMaterialize(*MBB, InsertLoc, PhysReg, VirtReg, TII, TRI, *VRM);
2197         } else {
2198           const TargetRegisterClass* RC = MRI->getRegClass(VirtReg);
2199           TII->loadRegFromStackSlot(*MBB, InsertLoc, PhysReg, SSorRMId, RC,TRI);
2200           MachineInstr *LoadMI = prior(InsertLoc);
2201           VRM->addSpillSlotUse(SSorRMId, LoadMI);
2202           ++NumLoads;
2203           DistanceMap.insert(std::make_pair(LoadMI, DistanceMap.size()));
2204         }
2205         // This invalidates PhysReg.
2206         Spills.ClobberPhysReg(PhysReg);
2207
2208         // Any stores to this stack slot are not dead anymore.
2209         if (!DoReMat)
2210           MaybeDeadStores[SSorRMId] = NULL;
2211         Spills.addAvailable(SSorRMId, PhysReg);
2212         // Assumes this is the last use. IsKill will be unset if reg is reused
2213         // unless it's a two-address operand.
2214         if (!MI.isRegTiedToDefOperand(i) &&
2215             KilledMIRegs.count(VirtReg) == 0) {
2216           MI.getOperand(i).setIsKill();
2217           KilledMIRegs.insert(VirtReg);
2218         }
2219
2220         UpdateKills(*prior(InsertLoc), TRI, RegKills, KillOps);
2221         DEBUG(dbgs() << '\t' << *prior(InsertLoc));
2222       }
2223       unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
2224       MI.getOperand(i).setReg(RReg);
2225       MI.getOperand(i).setSubReg(0);
2226     }
2227
2228     // Ok - now we can remove stores that have been confirmed dead.
2229     for (unsigned j = 0, e = PotentialDeadStoreSlots.size(); j != e; ++j) {
2230       // This was the last use and the spilled value is still available
2231       // for reuse. That means the spill was unnecessary!
2232       int PDSSlot = PotentialDeadStoreSlots[j];
2233       MachineInstr* DeadStore = MaybeDeadStores[PDSSlot];
2234       if (DeadStore) {
2235         DEBUG(dbgs() << "Removed dead store:\t" << *DeadStore);
2236         InvalidateKills(*DeadStore, TRI, RegKills, KillOps);
2237         VRM->RemoveMachineInstrFromMaps(DeadStore);
2238         MBB->erase(DeadStore);
2239         MaybeDeadStores[PDSSlot] = NULL;
2240         ++NumDSE;
2241       }
2242     }
2243
2244
2245     DEBUG(dbgs() << '\t' << MI);
2246
2247
2248     // If we have folded references to memory operands, make sure we clear all
2249     // physical registers that may contain the value of the spilled virtual
2250     // register
2251     SmallSet<int, 2> FoldedSS;
2252     for (tie(I, End) = VRM->getFoldedVirts(&MI); I != End; ) {
2253       unsigned VirtReg = I->second.first;
2254       VirtRegMap::ModRef MR = I->second.second;
2255       DEBUG(dbgs() << "Folded vreg: " << VirtReg << "  MR: " << MR);
2256
2257       // MI2VirtMap be can updated which invalidate the iterator.
2258       // Increment the iterator first.
2259       ++I;
2260       int SS = VRM->getStackSlot(VirtReg);
2261       if (SS == VirtRegMap::NO_STACK_SLOT)
2262         continue;
2263       FoldedSS.insert(SS);
2264       DEBUG(dbgs() << " - StackSlot: " << SS << "\n");
2265
2266       // If this folded instruction is just a use, check to see if it's a
2267       // straight load from the virt reg slot.
2268       if ((MR & VirtRegMap::isRef) && !(MR & VirtRegMap::isMod)) {
2269         int FrameIdx;
2270         unsigned DestReg = TII->isLoadFromStackSlot(&MI, FrameIdx);
2271         if (DestReg && FrameIdx == SS) {
2272           // If this spill slot is available, turn it into a copy (or nothing)
2273           // instead of leaving it as a load!
2274           if (unsigned InReg = Spills.getSpillSlotOrReMatPhysReg(SS)) {
2275             DEBUG(dbgs() << "Promoted Load To Copy: " << MI);
2276             if (DestReg != InReg) {
2277               MachineOperand *DefMO = MI.findRegisterDefOperand(DestReg);
2278               MachineInstr *CopyMI = BuildMI(*MBB, &MI, MI.getDebugLoc(),
2279                                              TII->get(TargetOpcode::COPY))
2280                 .addReg(DestReg, RegState::Define, DefMO->getSubReg())
2281                 .addReg(InReg, RegState::Kill);
2282               // Revisit the copy so we make sure to notice the effects of the
2283               // operation on the destreg (either needing to RA it if it's
2284               // virtual or needing to clobber any values if it's physical).
2285               NextMII = CopyMI;
2286               NextMII->setAsmPrinterFlag(MachineInstr::ReloadReuse);
2287               BackTracked = true;
2288             } else {
2289               DEBUG(dbgs() << "Removing now-noop copy: " << MI);
2290               // Unset last kill since it's being reused.
2291               InvalidateKill(InReg, TRI, RegKills, KillOps);
2292               Spills.disallowClobberPhysReg(InReg);
2293             }
2294
2295             InvalidateKills(MI, TRI, RegKills, KillOps);
2296             VRM->RemoveMachineInstrFromMaps(&MI);
2297             MBB->erase(&MI);
2298             Erased = true;
2299             goto ProcessNextInst;
2300           }
2301         } else {
2302           unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SS);
2303           SmallVector<MachineInstr*, 4> NewMIs;
2304           if (PhysReg &&
2305               TII->unfoldMemoryOperand(MF, &MI, PhysReg, false, false, NewMIs)) {
2306             MBB->insert(MII, NewMIs[0]);
2307             InvalidateKills(MI, TRI, RegKills, KillOps);
2308             VRM->RemoveMachineInstrFromMaps(&MI);
2309             MBB->erase(&MI);
2310             Erased = true;
2311             --NextMII;  // backtrack to the unfolded instruction.
2312             BackTracked = true;
2313             goto ProcessNextInst;
2314           }
2315         }
2316       }
2317
2318       // If this reference is not a use, any previous store is now dead.
2319       // Otherwise, the store to this stack slot is not dead anymore.
2320       MachineInstr* DeadStore = MaybeDeadStores[SS];
2321       if (DeadStore) {
2322         bool isDead = !(MR & VirtRegMap::isRef);
2323         MachineInstr *NewStore = NULL;
2324         if (MR & VirtRegMap::isModRef) {
2325           unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SS);
2326           SmallVector<MachineInstr*, 4> NewMIs;
2327           // We can reuse this physreg as long as we are allowed to clobber
2328           // the value and there isn't an earlier def that has already clobbered
2329           // the physreg.
2330           if (PhysReg &&
2331               !ReusedOperands.isClobbered(PhysReg) &&
2332               Spills.canClobberPhysReg(PhysReg) &&
2333               !TII->isStoreToStackSlot(&MI, SS)) { // Not profitable!
2334             MachineOperand *KillOpnd =
2335               DeadStore->findRegisterUseOperand(PhysReg, true);
2336             // Note, if the store is storing a sub-register, it's possible the
2337             // super-register is needed below.
2338             if (KillOpnd && !KillOpnd->getSubReg() &&
2339                 TII->unfoldMemoryOperand(MF, &MI, PhysReg, false, true,NewMIs)){
2340               MBB->insert(MII, NewMIs[0]);
2341               NewStore = NewMIs[1];
2342               MBB->insert(MII, NewStore);
2343               VRM->addSpillSlotUse(SS, NewStore);
2344               InvalidateKills(MI, TRI, RegKills, KillOps);
2345               VRM->RemoveMachineInstrFromMaps(&MI);
2346               MBB->erase(&MI);
2347               Erased = true;
2348               --NextMII;
2349               --NextMII;  // backtrack to the unfolded instruction.
2350               BackTracked = true;
2351               isDead = true;
2352               ++NumSUnfold;
2353             }
2354           }
2355         }
2356
2357         if (isDead) {  // Previous store is dead.
2358           // If we get here, the store is dead, nuke it now.
2359           DEBUG(dbgs() << "Removed dead store:\t" << *DeadStore);
2360           InvalidateKills(*DeadStore, TRI, RegKills, KillOps);
2361           VRM->RemoveMachineInstrFromMaps(DeadStore);
2362           MBB->erase(DeadStore);
2363           if (!NewStore)
2364             ++NumDSE;
2365         }
2366
2367         MaybeDeadStores[SS] = NULL;
2368         if (NewStore) {
2369           // Treat this store as a spill merged into a copy. That makes the
2370           // stack slot value available.
2371           VRM->virtFolded(VirtReg, NewStore, VirtRegMap::isMod);
2372           goto ProcessNextInst;
2373         }
2374       }
2375
2376       // If the spill slot value is available, and this is a new definition of
2377       // the value, the value is not available anymore.
2378       if (MR & VirtRegMap::isMod) {
2379         // Notice that the value in this stack slot has been modified.
2380         Spills.ModifyStackSlotOrReMat(SS);
2381
2382         // If this is *just* a mod of the value, check to see if this is just a
2383         // store to the spill slot (i.e. the spill got merged into the copy). If
2384         // so, realize that the vreg is available now, and add the store to the
2385         // MaybeDeadStore info.
2386         int StackSlot;
2387         if (!(MR & VirtRegMap::isRef)) {
2388           if (unsigned SrcReg = TII->isStoreToStackSlot(&MI, StackSlot)) {
2389             assert(TargetRegisterInfo::isPhysicalRegister(SrcReg) &&
2390                    "Src hasn't been allocated yet?");
2391
2392             if (CommuteToFoldReload(MII, VirtReg, SrcReg, StackSlot,
2393                                     Spills, RegKills, KillOps, TRI)) {
2394               NextMII = llvm::next(MII);
2395               BackTracked = true;
2396               goto ProcessNextInst;
2397             }
2398
2399             // Okay, this is certainly a store of SrcReg to [StackSlot].  Mark
2400             // this as a potentially dead store in case there is a subsequent
2401             // store into the stack slot without a read from it.
2402             MaybeDeadStores[StackSlot] = &MI;
2403
2404             // If the stack slot value was previously available in some other
2405             // register, change it now.  Otherwise, make the register
2406             // available in PhysReg.
2407             Spills.addAvailable(StackSlot, SrcReg, MI.killsRegister(SrcReg));
2408           }
2409         }
2410       }
2411     }
2412
2413     // Process all of the spilled defs.
2414     SpilledMIRegs.clear();
2415     for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
2416       MachineOperand &MO = MI.getOperand(i);
2417       if (!(MO.isReg() && MO.getReg() && MO.isDef()))
2418         continue;
2419
2420       unsigned VirtReg = MO.getReg();
2421       if (!TargetRegisterInfo::isVirtualRegister(VirtReg)) {
2422         // Check to see if this is a noop copy.  If so, eliminate the
2423         // instruction before considering the dest reg to be changed.
2424         // Also check if it's copying from an "undef", if so, we can't
2425         // eliminate this or else the undef marker is lost and it will
2426         // confuses the scavenger. This is extremely rare.
2427         if (MI.isIdentityCopy() && !MI.getOperand(1).isUndef() &&
2428             MI.getNumOperands() == 2) {
2429           ++NumDCE;
2430           DEBUG(dbgs() << "Removing now-noop copy: " << MI);
2431           SmallVector<unsigned, 2> KillRegs;
2432           InvalidateKills(MI, TRI, RegKills, KillOps, &KillRegs);
2433           if (MO.isDead() && !KillRegs.empty()) {
2434             // Source register or an implicit super/sub-register use is killed.
2435             assert(TRI->regsOverlap(KillRegs[0], MI.getOperand(0).getReg()));
2436             // Last def is now dead.
2437             TransferDeadness(MI.getOperand(1).getReg(), RegKills, KillOps);
2438           }
2439           VRM->RemoveMachineInstrFromMaps(&MI);
2440           MBB->erase(&MI);
2441           Erased = true;
2442           Spills.disallowClobberPhysReg(VirtReg);
2443           goto ProcessNextInst;
2444         }
2445         unsigned Src, Dst, SrcSR, DstSR;
2446         if (TII->isMoveInstr(MI, Src, Dst, SrcSR, DstSR) &&
2447             Src == Dst && SrcSR == DstSR &&
2448             !MI.findRegisterUseOperand(Src)->isUndef()) {
2449           ++NumDCE;
2450           DEBUG(dbgs() << "Removing now-noop copy: " << MI);
2451           SmallVector<unsigned, 2> KillRegs;
2452           InvalidateKills(MI, TRI, RegKills, KillOps, &KillRegs);
2453           if (MO.isDead() && !KillRegs.empty()) {
2454             // Source register or an implicit super/sub-register use is killed.
2455             assert(KillRegs[0] == Dst ||
2456                    TRI->isSubRegister(KillRegs[0], Dst) ||
2457                    TRI->isSuperRegister(KillRegs[0], Dst));
2458             // Last def is now dead.
2459             TransferDeadness(Src, RegKills, KillOps);
2460           }
2461           VRM->RemoveMachineInstrFromMaps(&MI);
2462           MBB->erase(&MI);
2463           Erased = true;
2464           Spills.disallowClobberPhysReg(VirtReg);
2465           goto ProcessNextInst;
2466         }
2467
2468         // If it's not a no-op copy, it clobbers the value in the destreg.
2469         Spills.ClobberPhysReg(VirtReg);
2470         ReusedOperands.markClobbered(VirtReg);
2471
2472         // Check to see if this instruction is a load from a stack slot into
2473         // a register.  If so, this provides the stack slot value in the reg.
2474         int FrameIdx;
2475         if (unsigned DestReg = TII->isLoadFromStackSlot(&MI, FrameIdx)) {
2476           assert(DestReg == VirtReg && "Unknown load situation!");
2477
2478           // If it is a folded reference, then it's not safe to clobber.
2479           bool Folded = FoldedSS.count(FrameIdx);
2480           // Otherwise, if it wasn't available, remember that it is now!
2481           Spills.addAvailable(FrameIdx, DestReg, !Folded);
2482           goto ProcessNextInst;
2483         }
2484
2485         continue;
2486       }
2487
2488       unsigned SubIdx = MO.getSubReg();
2489       bool DoReMat = VRM->isReMaterialized(VirtReg);
2490       if (DoReMat)
2491         ReMatDefs.insert(&MI);
2492
2493       // The only vregs left are stack slot definitions.
2494       int StackSlot = VRM->getStackSlot(VirtReg);
2495       const TargetRegisterClass *RC = MRI->getRegClass(VirtReg);
2496
2497       // If this def is part of a two-address operand, make sure to execute
2498       // the store from the correct physical register.
2499       unsigned PhysReg;
2500       unsigned TiedOp;
2501       if (MI.isRegTiedToUseOperand(i, &TiedOp)) {
2502         PhysReg = MI.getOperand(TiedOp).getReg();
2503         if (SubIdx) {
2504           unsigned SuperReg = findSuperReg(RC, PhysReg, SubIdx, TRI);
2505           assert(SuperReg && TRI->getSubReg(SuperReg, SubIdx) == PhysReg &&
2506                  "Can't find corresponding super-register!");
2507           PhysReg = SuperReg;
2508         }
2509       } else {
2510         PhysReg = VRM->getPhys(VirtReg);
2511         if (ReusedOperands.isClobbered(PhysReg)) {
2512           // Another def has taken the assigned physreg. It must have been a
2513           // use&def which got it due to reuse. Undo the reuse!
2514           PhysReg = ReusedOperands.GetRegForReload(VirtReg, PhysReg, &MI,
2515                       Spills, MaybeDeadStores, RegKills, KillOps, *VRM);
2516         }
2517       }
2518
2519       assert(PhysReg && "VR not assigned a physical register?");
2520       MRI->setPhysRegUsed(PhysReg);
2521       unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
2522       ReusedOperands.markClobbered(RReg);
2523       MI.getOperand(i).setReg(RReg);
2524       MI.getOperand(i).setSubReg(0);
2525
2526       if (!MO.isDead() && SpilledMIRegs.insert(VirtReg)) {
2527         MachineInstr *&LastStore = MaybeDeadStores[StackSlot];
2528         SpillRegToStackSlot(MII, -1, PhysReg, StackSlot, RC, true,
2529           LastStore, Spills, ReMatDefs, RegKills, KillOps);
2530         NextMII = llvm::next(MII);
2531
2532         // Check to see if this is a noop copy.  If so, eliminate the
2533         // instruction before considering the dest reg to be changed.
2534         if (MI.isIdentityCopy()) {
2535           ++NumDCE;
2536           DEBUG(dbgs() << "Removing now-noop copy: " << MI);
2537           InvalidateKills(MI, TRI, RegKills, KillOps);
2538           VRM->RemoveMachineInstrFromMaps(&MI);
2539           MBB->erase(&MI);
2540           Erased = true;
2541           UpdateKills(*LastStore, TRI, RegKills, KillOps);
2542           goto ProcessNextInst;
2543         }
2544         {
2545           unsigned Src, Dst, SrcSR, DstSR;
2546           if (TII->isMoveInstr(MI, Src, Dst, SrcSR, DstSR) &&
2547               Src == Dst && SrcSR == DstSR) {
2548             ++NumDCE;
2549             DEBUG(dbgs() << "Removing now-noop copy: " << MI);
2550             InvalidateKills(MI, TRI, RegKills, KillOps);
2551             VRM->RemoveMachineInstrFromMaps(&MI);
2552             MBB->erase(&MI);
2553             Erased = true;
2554             UpdateKills(*LastStore, TRI, RegKills, KillOps);
2555             goto ProcessNextInst;
2556           }
2557         }
2558       }
2559     }
2560     ProcessNextInst:
2561     // Delete dead instructions without side effects.
2562     if (!Erased && !BackTracked && isSafeToDelete(MI)) {
2563       InvalidateKills(MI, TRI, RegKills, KillOps);
2564       VRM->RemoveMachineInstrFromMaps(&MI);
2565       MBB->erase(&MI);
2566       Erased = true;
2567     }
2568     if (!Erased)
2569       DistanceMap.insert(std::make_pair(&MI, DistanceMap.size()));
2570     if (!Erased && !BackTracked) {
2571       for (MachineBasicBlock::iterator II = &MI; II != NextMII; ++II)
2572         UpdateKills(*II, TRI, RegKills, KillOps);
2573     }
2574     MII = NextMII;
2575   }
2576
2577 }
2578
2579 llvm::VirtRegRewriter* llvm::createVirtRegRewriter() {
2580   switch (RewriterOpt) {
2581   default: llvm_unreachable("Unreachable!");
2582   case local:
2583     return new LocalRewriter();
2584   case trivial:
2585     return new TrivialRewriter();
2586   }
2587 }