Rename SSARegMap -> MachineRegisterInfo in keeping with the idea
[oota-llvm.git] / lib / CodeGen / VirtRegMap.cpp
1 //===-- llvm/CodeGen/VirtRegMap.cpp - Virtual Register Map ----------------===//
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 // This file implements the VirtRegMap class.
11 //
12 // It also contains implementations of the the Spiller interface, which, given a
13 // virtual register map and a machine function, eliminates all virtual
14 // references by replacing them with physical register references - adding spill
15 // code as necessary.
16 //
17 //===----------------------------------------------------------------------===//
18
19 #define DEBUG_TYPE "spiller"
20 #include "VirtRegMap.h"
21 #include "llvm/Function.h"
22 #include "llvm/CodeGen/MachineFrameInfo.h"
23 #include "llvm/CodeGen/MachineFunction.h"
24 #include "llvm/CodeGen/MachineRegisterInfo.h"
25 #include "llvm/Target/TargetMachine.h"
26 #include "llvm/Target/TargetInstrInfo.h"
27 #include "llvm/Support/CommandLine.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/Support/Compiler.h"
30 #include "llvm/ADT/BitVector.h"
31 #include "llvm/ADT/Statistic.h"
32 #include "llvm/ADT/STLExtras.h"
33 #include "llvm/ADT/SmallSet.h"
34 #include <algorithm>
35 using namespace llvm;
36
37 STATISTIC(NumSpills, "Number of register spills");
38 STATISTIC(NumReMats, "Number of re-materialization");
39 STATISTIC(NumDRM   , "Number of re-materializable defs elided");
40 STATISTIC(NumStores, "Number of stores added");
41 STATISTIC(NumLoads , "Number of loads added");
42 STATISTIC(NumReused, "Number of values reused");
43 STATISTIC(NumDSE   , "Number of dead stores elided");
44 STATISTIC(NumDCE   , "Number of copies elided");
45
46 namespace {
47   enum SpillerName { simple, local };
48
49   static cl::opt<SpillerName>
50   SpillerOpt("spiller",
51              cl::desc("Spiller to use: (default: local)"),
52              cl::Prefix,
53              cl::values(clEnumVal(simple, "  simple spiller"),
54                         clEnumVal(local,  "  local spiller"),
55                         clEnumValEnd),
56              cl::init(local));
57 }
58
59 //===----------------------------------------------------------------------===//
60 //  VirtRegMap implementation
61 //===----------------------------------------------------------------------===//
62
63 VirtRegMap::VirtRegMap(MachineFunction &mf)
64   : TII(*mf.getTarget().getInstrInfo()), MF(mf), 
65     Virt2PhysMap(NO_PHYS_REG), Virt2StackSlotMap(NO_STACK_SLOT),
66     Virt2ReMatIdMap(NO_STACK_SLOT), Virt2SplitMap(0),
67     Virt2SplitKillMap(0), ReMatMap(NULL), ReMatId(MAX_STACK_SLOT+1) {
68   grow();
69 }
70
71 void VirtRegMap::grow() {
72   unsigned LastVirtReg = MF.getRegInfo().getLastVirtReg();
73   Virt2PhysMap.grow(LastVirtReg);
74   Virt2StackSlotMap.grow(LastVirtReg);
75   Virt2ReMatIdMap.grow(LastVirtReg);
76   Virt2SplitMap.grow(LastVirtReg);
77   Virt2SplitKillMap.grow(LastVirtReg);
78   ReMatMap.grow(LastVirtReg);
79 }
80
81 int VirtRegMap::assignVirt2StackSlot(unsigned virtReg) {
82   assert(MRegisterInfo::isVirtualRegister(virtReg));
83   assert(Virt2StackSlotMap[virtReg] == NO_STACK_SLOT &&
84          "attempt to assign stack slot to already spilled register");
85   const TargetRegisterClass* RC = MF.getRegInfo().getRegClass(virtReg);
86   int frameIndex = MF.getFrameInfo()->CreateStackObject(RC->getSize(),
87                                                         RC->getAlignment());
88   Virt2StackSlotMap[virtReg] = frameIndex;
89   ++NumSpills;
90   return frameIndex;
91 }
92
93 void VirtRegMap::assignVirt2StackSlot(unsigned virtReg, int frameIndex) {
94   assert(MRegisterInfo::isVirtualRegister(virtReg));
95   assert(Virt2StackSlotMap[virtReg] == NO_STACK_SLOT &&
96          "attempt to assign stack slot to already spilled register");
97   assert((frameIndex >= 0 ||
98           (frameIndex >= MF.getFrameInfo()->getObjectIndexBegin())) &&
99          "illegal fixed frame index");
100   Virt2StackSlotMap[virtReg] = frameIndex;
101 }
102
103 int VirtRegMap::assignVirtReMatId(unsigned virtReg) {
104   assert(MRegisterInfo::isVirtualRegister(virtReg));
105   assert(Virt2ReMatIdMap[virtReg] == NO_STACK_SLOT &&
106          "attempt to assign re-mat id to already spilled register");
107   Virt2ReMatIdMap[virtReg] = ReMatId;
108   return ReMatId++;
109 }
110
111 void VirtRegMap::assignVirtReMatId(unsigned virtReg, int id) {
112   assert(MRegisterInfo::isVirtualRegister(virtReg));
113   assert(Virt2ReMatIdMap[virtReg] == NO_STACK_SLOT &&
114          "attempt to assign re-mat id to already spilled register");
115   Virt2ReMatIdMap[virtReg] = id;
116 }
117
118 void VirtRegMap::virtFolded(unsigned VirtReg, MachineInstr *OldMI,
119                             MachineInstr *NewMI, ModRef MRInfo) {
120   // Move previous memory references folded to new instruction.
121   MI2VirtMapTy::iterator IP = MI2VirtMap.lower_bound(NewMI);
122   for (MI2VirtMapTy::iterator I = MI2VirtMap.lower_bound(OldMI),
123          E = MI2VirtMap.end(); I != E && I->first == OldMI; ) {
124     MI2VirtMap.insert(IP, std::make_pair(NewMI, I->second));
125     MI2VirtMap.erase(I++);
126   }
127
128   // add new memory reference
129   MI2VirtMap.insert(IP, std::make_pair(NewMI, std::make_pair(VirtReg, MRInfo)));
130 }
131
132 void VirtRegMap::virtFolded(unsigned VirtReg, MachineInstr *MI, ModRef MRInfo) {
133   MI2VirtMapTy::iterator IP = MI2VirtMap.lower_bound(MI);
134   MI2VirtMap.insert(IP, std::make_pair(MI, std::make_pair(VirtReg, MRInfo)));
135 }
136
137 void VirtRegMap::print(std::ostream &OS) const {
138   const MRegisterInfo* MRI = MF.getTarget().getRegisterInfo();
139
140   OS << "********** REGISTER MAP **********\n";
141   for (unsigned i = MRegisterInfo::FirstVirtualRegister,
142          e = MF.getRegInfo().getLastVirtReg(); i <= e; ++i) {
143     if (Virt2PhysMap[i] != (unsigned)VirtRegMap::NO_PHYS_REG)
144       OS << "[reg" << i << " -> " << MRI->getName(Virt2PhysMap[i]) << "]\n";
145
146   }
147
148   for (unsigned i = MRegisterInfo::FirstVirtualRegister,
149          e = MF.getRegInfo().getLastVirtReg(); i <= e; ++i)
150     if (Virt2StackSlotMap[i] != VirtRegMap::NO_STACK_SLOT)
151       OS << "[reg" << i << " -> fi#" << Virt2StackSlotMap[i] << "]\n";
152   OS << '\n';
153 }
154
155 void VirtRegMap::dump() const {
156   print(DOUT);
157 }
158
159
160 //===----------------------------------------------------------------------===//
161 // Simple Spiller Implementation
162 //===----------------------------------------------------------------------===//
163
164 Spiller::~Spiller() {}
165
166 namespace {
167   struct VISIBILITY_HIDDEN SimpleSpiller : public Spiller {
168     bool runOnMachineFunction(MachineFunction& mf, VirtRegMap &VRM);
169   };
170 }
171
172 bool SimpleSpiller::runOnMachineFunction(MachineFunction &MF, VirtRegMap &VRM) {
173   DOUT << "********** REWRITE MACHINE CODE **********\n";
174   DOUT << "********** Function: " << MF.getFunction()->getName() << '\n';
175   const TargetMachine &TM = MF.getTarget();
176   const MRegisterInfo &MRI = *TM.getRegisterInfo();
177
178   // LoadedRegs - Keep track of which vregs are loaded, so that we only load
179   // each vreg once (in the case where a spilled vreg is used by multiple
180   // operands).  This is always smaller than the number of operands to the
181   // current machine instr, so it should be small.
182   std::vector<unsigned> LoadedRegs;
183
184   for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
185        MBBI != E; ++MBBI) {
186     DOUT << MBBI->getBasicBlock()->getName() << ":\n";
187     MachineBasicBlock &MBB = *MBBI;
188     for (MachineBasicBlock::iterator MII = MBB.begin(),
189            E = MBB.end(); MII != E; ++MII) {
190       MachineInstr &MI = *MII;
191       for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
192         MachineOperand &MO = MI.getOperand(i);
193         if (MO.isRegister() && MO.getReg())
194           if (MRegisterInfo::isVirtualRegister(MO.getReg())) {
195             unsigned VirtReg = MO.getReg();
196             unsigned PhysReg = VRM.getPhys(VirtReg);
197             if (!VRM.isAssignedReg(VirtReg)) {
198               int StackSlot = VRM.getStackSlot(VirtReg);
199               const TargetRegisterClass* RC =
200                 MF.getRegInfo().getRegClass(VirtReg);
201
202               if (MO.isUse() &&
203                   std::find(LoadedRegs.begin(), LoadedRegs.end(), VirtReg)
204                   == LoadedRegs.end()) {
205                 MRI.loadRegFromStackSlot(MBB, &MI, PhysReg, StackSlot, RC);
206                 LoadedRegs.push_back(VirtReg);
207                 ++NumLoads;
208                 DOUT << '\t' << *prior(MII);
209               }
210
211               if (MO.isDef()) {
212                 MRI.storeRegToStackSlot(MBB, next(MII), PhysReg, true,
213                                         StackSlot, RC);
214                 ++NumStores;
215               }
216             }
217             MF.getRegInfo().setPhysRegUsed(PhysReg);
218             MI.getOperand(i).setReg(PhysReg);
219           } else {
220             MF.getRegInfo().setPhysRegUsed(MO.getReg());
221           }
222       }
223
224       DOUT << '\t' << MI;
225       LoadedRegs.clear();
226     }
227   }
228   return true;
229 }
230
231 //===----------------------------------------------------------------------===//
232 //  Local Spiller Implementation
233 //===----------------------------------------------------------------------===//
234
235 namespace {
236   class AvailableSpills;
237
238   /// LocalSpiller - This spiller does a simple pass over the machine basic
239   /// block to attempt to keep spills in registers as much as possible for
240   /// blocks that have low register pressure (the vreg may be spilled due to
241   /// register pressure in other blocks).
242   class VISIBILITY_HIDDEN LocalSpiller : public Spiller {
243     MachineRegisterInfo *RegInfo;
244     const MRegisterInfo *MRI;
245     const TargetInstrInfo *TII;
246   public:
247     bool runOnMachineFunction(MachineFunction &MF, VirtRegMap &VRM) {
248       RegInfo = &MF.getRegInfo(); 
249       MRI = MF.getTarget().getRegisterInfo();
250       TII = MF.getTarget().getInstrInfo();
251       DOUT << "\n**** Local spiller rewriting function '"
252            << MF.getFunction()->getName() << "':\n";
253       DOUT << "**** Machine Instrs (NOTE! Does not include spills and reloads!)"
254               " ****\n";
255       DEBUG(MF.dump());
256
257       for (MachineFunction::iterator MBB = MF.begin(), E = MF.end();
258            MBB != E; ++MBB)
259         RewriteMBB(*MBB, VRM);
260
261       DOUT << "**** Post Machine Instrs ****\n";
262       DEBUG(MF.dump());
263
264       return true;
265     }
266   private:
267     bool PrepForUnfoldOpti(MachineBasicBlock &MBB,
268                            MachineBasicBlock::iterator &MII,
269                            std::vector<MachineInstr*> &MaybeDeadStores,
270                            AvailableSpills &Spills, BitVector &RegKills,
271                            std::vector<MachineOperand*> &KillOps,
272                            VirtRegMap &VRM);
273     void SpillRegToStackSlot(MachineBasicBlock &MBB,
274                              MachineBasicBlock::iterator &MII,
275                              int Idx, unsigned PhysReg, int StackSlot,
276                              const TargetRegisterClass *RC,
277                              bool isAvailable, MachineInstr *&LastStore,
278                              AvailableSpills &Spills,
279                              SmallSet<MachineInstr*, 4> &ReMatDefs,
280                              BitVector &RegKills,
281                              std::vector<MachineOperand*> &KillOps,
282                              VirtRegMap &VRM);
283     void RewriteMBB(MachineBasicBlock &MBB, VirtRegMap &VRM);
284   };
285 }
286
287 /// AvailableSpills - As the local spiller is scanning and rewriting an MBB from
288 /// top down, keep track of which spills slots or remat are available in each
289 /// register.
290 ///
291 /// Note that not all physregs are created equal here.  In particular, some
292 /// physregs are reloads that we are allowed to clobber or ignore at any time.
293 /// Other physregs are values that the register allocated program is using that
294 /// we cannot CHANGE, but we can read if we like.  We keep track of this on a 
295 /// per-stack-slot / remat id basis as the low bit in the value of the
296 /// SpillSlotsAvailable entries.  The predicate 'canClobberPhysReg()' checks
297 /// this bit and addAvailable sets it if.
298 namespace {
299 class VISIBILITY_HIDDEN AvailableSpills {
300   const MRegisterInfo *MRI;
301   const TargetInstrInfo *TII;
302
303   // SpillSlotsOrReMatsAvailable - This map keeps track of all of the spilled
304   // or remat'ed virtual register values that are still available, due to being
305   // loaded or stored to, but not invalidated yet.
306   std::map<int, unsigned> SpillSlotsOrReMatsAvailable;
307     
308   // PhysRegsAvailable - This is the inverse of SpillSlotsOrReMatsAvailable,
309   // indicating which stack slot values are currently held by a physreg.  This
310   // is used to invalidate entries in SpillSlotsOrReMatsAvailable when a
311   // physreg is modified.
312   std::multimap<unsigned, int> PhysRegsAvailable;
313   
314   void disallowClobberPhysRegOnly(unsigned PhysReg);
315
316   void ClobberPhysRegOnly(unsigned PhysReg);
317 public:
318   AvailableSpills(const MRegisterInfo *mri, const TargetInstrInfo *tii)
319     : MRI(mri), TII(tii) {
320   }
321   
322   const MRegisterInfo *getRegInfo() const { return MRI; }
323
324   /// getSpillSlotOrReMatPhysReg - If the specified stack slot or remat is
325   /// available in a  physical register, return that PhysReg, otherwise
326   /// return 0.
327   unsigned getSpillSlotOrReMatPhysReg(int Slot) const {
328     std::map<int, unsigned>::const_iterator I =
329       SpillSlotsOrReMatsAvailable.find(Slot);
330     if (I != SpillSlotsOrReMatsAvailable.end()) {
331       return I->second >> 1;  // Remove the CanClobber bit.
332     }
333     return 0;
334   }
335
336   /// addAvailable - Mark that the specified stack slot / remat is available in
337   /// the specified physreg.  If CanClobber is true, the physreg can be modified
338   /// at any time without changing the semantics of the program.
339   void addAvailable(int SlotOrReMat, MachineInstr *MI, unsigned Reg,
340                     bool CanClobber = true) {
341     // If this stack slot is thought to be available in some other physreg, 
342     // remove its record.
343     ModifyStackSlotOrReMat(SlotOrReMat);
344     
345     PhysRegsAvailable.insert(std::make_pair(Reg, SlotOrReMat));
346     SpillSlotsOrReMatsAvailable[SlotOrReMat]= (Reg << 1) | (unsigned)CanClobber;
347   
348     if (SlotOrReMat > VirtRegMap::MAX_STACK_SLOT)
349       DOUT << "Remembering RM#" << SlotOrReMat-VirtRegMap::MAX_STACK_SLOT-1;
350     else
351       DOUT << "Remembering SS#" << SlotOrReMat;
352     DOUT << " in physreg " << MRI->getName(Reg) << "\n";
353   }
354
355   /// canClobberPhysReg - Return true if the spiller is allowed to change the 
356   /// value of the specified stackslot register if it desires.  The specified
357   /// stack slot must be available in a physreg for this query to make sense.
358   bool canClobberPhysReg(int SlotOrReMat) const {
359     assert(SpillSlotsOrReMatsAvailable.count(SlotOrReMat) &&
360            "Value not available!");
361     return SpillSlotsOrReMatsAvailable.find(SlotOrReMat)->second & 1;
362   }
363
364   /// disallowClobberPhysReg - Unset the CanClobber bit of the specified
365   /// stackslot register. The register is still available but is no longer
366   /// allowed to be modifed.
367   void disallowClobberPhysReg(unsigned PhysReg);
368   
369   /// ClobberPhysReg - This is called when the specified physreg changes
370   /// value.  We use this to invalidate any info about stuff that lives in
371   /// it and any of its aliases.
372   void ClobberPhysReg(unsigned PhysReg);
373
374   /// ModifyStackSlotOrReMat - This method is called when the value in a stack
375   /// slot changes.  This removes information about which register the previous
376   /// value for this slot lives in (as the previous value is dead now).
377   void ModifyStackSlotOrReMat(int SlotOrReMat);
378 };
379 }
380
381 /// disallowClobberPhysRegOnly - Unset the CanClobber bit of the specified
382 /// stackslot register. The register is still available but is no longer
383 /// allowed to be modifed.
384 void AvailableSpills::disallowClobberPhysRegOnly(unsigned PhysReg) {
385   std::multimap<unsigned, int>::iterator I =
386     PhysRegsAvailable.lower_bound(PhysReg);
387   while (I != PhysRegsAvailable.end() && I->first == PhysReg) {
388     int SlotOrReMat = I->second;
389     I++;
390     assert((SpillSlotsOrReMatsAvailable[SlotOrReMat] >> 1) == PhysReg &&
391            "Bidirectional map mismatch!");
392     SpillSlotsOrReMatsAvailable[SlotOrReMat] &= ~1;
393     DOUT << "PhysReg " << MRI->getName(PhysReg)
394          << " copied, it is available for use but can no longer be modified\n";
395   }
396 }
397
398 /// disallowClobberPhysReg - Unset the CanClobber bit of the specified
399 /// stackslot register and its aliases. The register and its aliases may
400 /// still available but is no longer allowed to be modifed.
401 void AvailableSpills::disallowClobberPhysReg(unsigned PhysReg) {
402   for (const unsigned *AS = MRI->getAliasSet(PhysReg); *AS; ++AS)
403     disallowClobberPhysRegOnly(*AS);
404   disallowClobberPhysRegOnly(PhysReg);
405 }
406
407 /// ClobberPhysRegOnly - This is called when the specified physreg changes
408 /// value.  We use this to invalidate any info about stuff we thing lives in it.
409 void AvailableSpills::ClobberPhysRegOnly(unsigned PhysReg) {
410   std::multimap<unsigned, int>::iterator I =
411     PhysRegsAvailable.lower_bound(PhysReg);
412   while (I != PhysRegsAvailable.end() && I->first == PhysReg) {
413     int SlotOrReMat = I->second;
414     PhysRegsAvailable.erase(I++);
415     assert((SpillSlotsOrReMatsAvailable[SlotOrReMat] >> 1) == PhysReg &&
416            "Bidirectional map mismatch!");
417     SpillSlotsOrReMatsAvailable.erase(SlotOrReMat);
418     DOUT << "PhysReg " << MRI->getName(PhysReg)
419          << " clobbered, invalidating ";
420     if (SlotOrReMat > VirtRegMap::MAX_STACK_SLOT)
421       DOUT << "RM#" << SlotOrReMat-VirtRegMap::MAX_STACK_SLOT-1 << "\n";
422     else
423       DOUT << "SS#" << SlotOrReMat << "\n";
424   }
425 }
426
427 /// ClobberPhysReg - This is called when the specified physreg changes
428 /// value.  We use this to invalidate any info about stuff we thing lives in
429 /// it and any of its aliases.
430 void AvailableSpills::ClobberPhysReg(unsigned PhysReg) {
431   for (const unsigned *AS = MRI->getAliasSet(PhysReg); *AS; ++AS)
432     ClobberPhysRegOnly(*AS);
433   ClobberPhysRegOnly(PhysReg);
434 }
435
436 /// ModifyStackSlotOrReMat - This method is called when the value in a stack
437 /// slot changes.  This removes information about which register the previous
438 /// value for this slot lives in (as the previous value is dead now).
439 void AvailableSpills::ModifyStackSlotOrReMat(int SlotOrReMat) {
440   std::map<int, unsigned>::iterator It =
441     SpillSlotsOrReMatsAvailable.find(SlotOrReMat);
442   if (It == SpillSlotsOrReMatsAvailable.end()) return;
443   unsigned Reg = It->second >> 1;
444   SpillSlotsOrReMatsAvailable.erase(It);
445   
446   // This register may hold the value of multiple stack slots, only remove this
447   // stack slot from the set of values the register contains.
448   std::multimap<unsigned, int>::iterator I = PhysRegsAvailable.lower_bound(Reg);
449   for (; ; ++I) {
450     assert(I != PhysRegsAvailable.end() && I->first == Reg &&
451            "Map inverse broken!");
452     if (I->second == SlotOrReMat) break;
453   }
454   PhysRegsAvailable.erase(I);
455 }
456
457
458
459 /// InvalidateKills - MI is going to be deleted. If any of its operands are
460 /// marked kill, then invalidate the information.
461 static void InvalidateKills(MachineInstr &MI, BitVector &RegKills,
462                             std::vector<MachineOperand*> &KillOps,
463                             SmallVector<unsigned, 2> *KillRegs = NULL) {
464   for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
465     MachineOperand &MO = MI.getOperand(i);
466     if (!MO.isRegister() || !MO.isUse() || !MO.isKill())
467       continue;
468     unsigned Reg = MO.getReg();
469     if (KillRegs)
470       KillRegs->push_back(Reg);
471     if (KillOps[Reg] == &MO) {
472       RegKills.reset(Reg);
473       KillOps[Reg] = NULL;
474     }
475   }
476 }
477
478 /// InvalidateKill - A MI that defines the specified register is being deleted,
479 /// invalidate the register kill information.
480 static void InvalidateKill(unsigned Reg, BitVector &RegKills,
481                            std::vector<MachineOperand*> &KillOps) {
482   if (RegKills[Reg]) {
483     KillOps[Reg]->setIsKill(false);
484     KillOps[Reg] = NULL;
485     RegKills.reset(Reg);
486   }
487 }
488
489 /// InvalidateRegDef - If the def operand of the specified def MI is now dead
490 /// (since it's spill instruction is removed), mark it isDead. Also checks if
491 /// the def MI has other definition operands that are not dead. Returns it by
492 /// reference.
493 static bool InvalidateRegDef(MachineBasicBlock::iterator I,
494                              MachineInstr &NewDef, unsigned Reg,
495                              bool &HasLiveDef) {
496   // Due to remat, it's possible this reg isn't being reused. That is,
497   // the def of this reg (by prev MI) is now dead.
498   MachineInstr *DefMI = I;
499   MachineOperand *DefOp = NULL;
500   for (unsigned i = 0, e = DefMI->getNumOperands(); i != e; ++i) {
501     MachineOperand &MO = DefMI->getOperand(i);
502     if (MO.isRegister() && MO.isDef()) {
503       if (MO.getReg() == Reg)
504         DefOp = &MO;
505       else if (!MO.isDead())
506         HasLiveDef = true;
507     }
508   }
509   if (!DefOp)
510     return false;
511
512   bool FoundUse = false, Done = false;
513   MachineBasicBlock::iterator E = NewDef;
514   ++I; ++E;
515   for (; !Done && I != E; ++I) {
516     MachineInstr *NMI = I;
517     for (unsigned j = 0, ee = NMI->getNumOperands(); j != ee; ++j) {
518       MachineOperand &MO = NMI->getOperand(j);
519       if (!MO.isRegister() || MO.getReg() != Reg)
520         continue;
521       if (MO.isUse())
522         FoundUse = true;
523       Done = true; // Stop after scanning all the operands of this MI.
524     }
525   }
526   if (!FoundUse) {
527     // Def is dead!
528     DefOp->setIsDead();
529     return true;
530   }
531   return false;
532 }
533
534 /// UpdateKills - Track and update kill info. If a MI reads a register that is
535 /// marked kill, then it must be due to register reuse. Transfer the kill info
536 /// over.
537 static void UpdateKills(MachineInstr &MI, BitVector &RegKills,
538                         std::vector<MachineOperand*> &KillOps) {
539   const TargetInstrDescriptor *TID = MI.getInstrDescriptor();
540   for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
541     MachineOperand &MO = MI.getOperand(i);
542     if (!MO.isRegister() || !MO.isUse())
543       continue;
544     unsigned Reg = MO.getReg();
545     if (Reg == 0)
546       continue;
547     
548     if (RegKills[Reg]) {
549       // That can't be right. Register is killed but not re-defined and it's
550       // being reused. Let's fix that.
551       KillOps[Reg]->setIsKill(false);
552       KillOps[Reg] = NULL;
553       RegKills.reset(Reg);
554       if (i < TID->numOperands &&
555           TID->getOperandConstraint(i, TOI::TIED_TO) == -1)
556         // Unless it's a two-address operand, this is the new kill.
557         MO.setIsKill();
558     }
559     if (MO.isKill()) {
560       RegKills.set(Reg);
561       KillOps[Reg] = &MO;
562     }
563   }
564
565   for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
566     const MachineOperand &MO = MI.getOperand(i);
567     if (!MO.isRegister() || !MO.isDef())
568       continue;
569     unsigned Reg = MO.getReg();
570     RegKills.reset(Reg);
571     KillOps[Reg] = NULL;
572   }
573 }
574
575
576 // ReusedOp - For each reused operand, we keep track of a bit of information, in
577 // case we need to rollback upon processing a new operand.  See comments below.
578 namespace {
579   struct ReusedOp {
580     // The MachineInstr operand that reused an available value.
581     unsigned Operand;
582
583     // StackSlotOrReMat - The spill slot or remat id of the value being reused.
584     unsigned StackSlotOrReMat;
585
586     // PhysRegReused - The physical register the value was available in.
587     unsigned PhysRegReused;
588
589     // AssignedPhysReg - The physreg that was assigned for use by the reload.
590     unsigned AssignedPhysReg;
591     
592     // VirtReg - The virtual register itself.
593     unsigned VirtReg;
594
595     ReusedOp(unsigned o, unsigned ss, unsigned prr, unsigned apr,
596              unsigned vreg)
597       : Operand(o), StackSlotOrReMat(ss), PhysRegReused(prr),
598         AssignedPhysReg(apr), VirtReg(vreg) {}
599   };
600   
601   /// ReuseInfo - This maintains a collection of ReuseOp's for each operand that
602   /// is reused instead of reloaded.
603   class VISIBILITY_HIDDEN ReuseInfo {
604     MachineInstr &MI;
605     std::vector<ReusedOp> Reuses;
606     BitVector PhysRegsClobbered;
607   public:
608     ReuseInfo(MachineInstr &mi, const MRegisterInfo *mri) : MI(mi) {
609       PhysRegsClobbered.resize(mri->getNumRegs());
610     }
611     
612     bool hasReuses() const {
613       return !Reuses.empty();
614     }
615     
616     /// addReuse - If we choose to reuse a virtual register that is already
617     /// available instead of reloading it, remember that we did so.
618     void addReuse(unsigned OpNo, unsigned StackSlotOrReMat,
619                   unsigned PhysRegReused, unsigned AssignedPhysReg,
620                   unsigned VirtReg) {
621       // If the reload is to the assigned register anyway, no undo will be
622       // required.
623       if (PhysRegReused == AssignedPhysReg) return;
624       
625       // Otherwise, remember this.
626       Reuses.push_back(ReusedOp(OpNo, StackSlotOrReMat, PhysRegReused, 
627                                 AssignedPhysReg, VirtReg));
628     }
629
630     void markClobbered(unsigned PhysReg) {
631       PhysRegsClobbered.set(PhysReg);
632     }
633
634     bool isClobbered(unsigned PhysReg) const {
635       return PhysRegsClobbered.test(PhysReg);
636     }
637     
638     /// GetRegForReload - We are about to emit a reload into PhysReg.  If there
639     /// is some other operand that is using the specified register, either pick
640     /// a new register to use, or evict the previous reload and use this reg. 
641     unsigned GetRegForReload(unsigned PhysReg, MachineInstr *MI,
642                              AvailableSpills &Spills,
643                              std::vector<MachineInstr*> &MaybeDeadStores,
644                              SmallSet<unsigned, 8> &Rejected,
645                              BitVector &RegKills,
646                              std::vector<MachineOperand*> &KillOps,
647                              VirtRegMap &VRM) {
648       if (Reuses.empty()) return PhysReg;  // This is most often empty.
649
650       for (unsigned ro = 0, e = Reuses.size(); ro != e; ++ro) {
651         ReusedOp &Op = Reuses[ro];
652         // If we find some other reuse that was supposed to use this register
653         // exactly for its reload, we can change this reload to use ITS reload
654         // register. That is, unless its reload register has already been
655         // considered and subsequently rejected because it has also been reused
656         // by another operand.
657         if (Op.PhysRegReused == PhysReg &&
658             Rejected.count(Op.AssignedPhysReg) == 0) {
659           // Yup, use the reload register that we didn't use before.
660           unsigned NewReg = Op.AssignedPhysReg;
661           Rejected.insert(PhysReg);
662           return GetRegForReload(NewReg, MI, Spills, MaybeDeadStores, Rejected,
663                                  RegKills, KillOps, VRM);
664         } else {
665           // Otherwise, we might also have a problem if a previously reused
666           // value aliases the new register.  If so, codegen the previous reload
667           // and use this one.          
668           unsigned PRRU = Op.PhysRegReused;
669           const MRegisterInfo *MRI = Spills.getRegInfo();
670           if (MRI->areAliases(PRRU, PhysReg)) {
671             // Okay, we found out that an alias of a reused register
672             // was used.  This isn't good because it means we have
673             // to undo a previous reuse.
674             MachineBasicBlock *MBB = MI->getParent();
675             const TargetRegisterClass *AliasRC =
676               MBB->getParent()->getRegInfo().getRegClass(Op.VirtReg);
677
678             // Copy Op out of the vector and remove it, we're going to insert an
679             // explicit load for it.
680             ReusedOp NewOp = Op;
681             Reuses.erase(Reuses.begin()+ro);
682
683             // Ok, we're going to try to reload the assigned physreg into the
684             // slot that we were supposed to in the first place.  However, that
685             // register could hold a reuse.  Check to see if it conflicts or
686             // would prefer us to use a different register.
687             unsigned NewPhysReg = GetRegForReload(NewOp.AssignedPhysReg,
688                                                   MI, Spills, MaybeDeadStores,
689                                               Rejected, RegKills, KillOps, VRM);
690             
691             if (NewOp.StackSlotOrReMat > VirtRegMap::MAX_STACK_SLOT) {
692               MRI->reMaterialize(*MBB, MI, NewPhysReg,
693                                  VRM.getReMaterializedMI(NewOp.VirtReg));
694               ++NumReMats;
695             } else {
696               MRI->loadRegFromStackSlot(*MBB, MI, NewPhysReg,
697                                         NewOp.StackSlotOrReMat, AliasRC);
698               // Any stores to this stack slot are not dead anymore.
699               MaybeDeadStores[NewOp.StackSlotOrReMat] = NULL;            
700               ++NumLoads;
701             }
702             Spills.ClobberPhysReg(NewPhysReg);
703             Spills.ClobberPhysReg(NewOp.PhysRegReused);
704             
705             MI->getOperand(NewOp.Operand).setReg(NewPhysReg);
706             
707             Spills.addAvailable(NewOp.StackSlotOrReMat, MI, NewPhysReg);
708             MachineBasicBlock::iterator MII = MI;
709             --MII;
710             UpdateKills(*MII, RegKills, KillOps);
711             DOUT << '\t' << *MII;
712             
713             DOUT << "Reuse undone!\n";
714             --NumReused;
715             
716             // Finally, PhysReg is now available, go ahead and use it.
717             return PhysReg;
718           }
719         }
720       }
721       return PhysReg;
722     }
723
724     /// GetRegForReload - Helper for the above GetRegForReload(). Add a
725     /// 'Rejected' set to remember which registers have been considered and
726     /// rejected for the reload. This avoids infinite looping in case like
727     /// this:
728     /// t1 := op t2, t3
729     /// t2 <- assigned r0 for use by the reload but ended up reuse r1
730     /// t3 <- assigned r1 for use by the reload but ended up reuse r0
731     /// t1 <- desires r1
732     ///       sees r1 is taken by t2, tries t2's reload register r0
733     ///       sees r0 is taken by t3, tries t3's reload register r1
734     ///       sees r1 is taken by t2, tries t2's reload register r0 ...
735     unsigned GetRegForReload(unsigned PhysReg, MachineInstr *MI,
736                              AvailableSpills &Spills,
737                              std::vector<MachineInstr*> &MaybeDeadStores,
738                              BitVector &RegKills,
739                              std::vector<MachineOperand*> &KillOps,
740                              VirtRegMap &VRM) {
741       SmallSet<unsigned, 8> Rejected;
742       return GetRegForReload(PhysReg, MI, Spills, MaybeDeadStores, Rejected,
743                              RegKills, KillOps, VRM);
744     }
745   };
746 }
747
748 /// PrepForUnfoldOpti - Turn a store folding instruction into a load folding
749 /// instruction. e.g.
750 ///     xorl  %edi, %eax
751 ///     movl  %eax, -32(%ebp)
752 ///     movl  -36(%ebp), %eax
753 ///     orl   %eax, -32(%ebp)
754 /// ==>
755 ///     xorl  %edi, %eax
756 ///     orl   -36(%ebp), %eax
757 ///     mov   %eax, -32(%ebp)
758 /// This enables unfolding optimization for a subsequent instruction which will
759 /// also eliminate the newly introduced store instruction.
760 bool LocalSpiller::PrepForUnfoldOpti(MachineBasicBlock &MBB,
761                                      MachineBasicBlock::iterator &MII,
762                                     std::vector<MachineInstr*> &MaybeDeadStores,
763                                      AvailableSpills &Spills,
764                                      BitVector &RegKills,
765                                      std::vector<MachineOperand*> &KillOps,
766                                      VirtRegMap &VRM) {
767   MachineFunction &MF = *MBB.getParent();
768   MachineInstr &MI = *MII;
769   unsigned UnfoldedOpc = 0;
770   unsigned UnfoldPR = 0;
771   unsigned UnfoldVR = 0;
772   int FoldedSS = VirtRegMap::NO_STACK_SLOT;
773   VirtRegMap::MI2VirtMapTy::const_iterator I, End;
774   for (tie(I, End) = VRM.getFoldedVirts(&MI); I != End; ++I) {
775     // Only transform a MI that folds a single register.
776     if (UnfoldedOpc)
777       return false;
778     UnfoldVR = I->second.first;
779     VirtRegMap::ModRef MR = I->second.second;
780     if (VRM.isAssignedReg(UnfoldVR))
781       continue;
782     // If this reference is not a use, any previous store is now dead.
783     // Otherwise, the store to this stack slot is not dead anymore.
784     FoldedSS = VRM.getStackSlot(UnfoldVR);
785     MachineInstr* DeadStore = MaybeDeadStores[FoldedSS];
786     if (DeadStore && (MR & VirtRegMap::isModRef)) {
787       unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(FoldedSS);
788       if (!PhysReg ||
789           DeadStore->findRegisterUseOperandIdx(PhysReg, true) == -1)
790         continue;
791       UnfoldPR = PhysReg;
792       UnfoldedOpc = MRI->getOpcodeAfterMemoryUnfold(MI.getOpcode(),
793                                                     false, true);
794     }
795   }
796
797   if (!UnfoldedOpc)
798     return false;
799
800   for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
801     MachineOperand &MO = MI.getOperand(i);
802     if (!MO.isRegister() || MO.getReg() == 0 || !MO.isUse())
803       continue;
804     unsigned VirtReg = MO.getReg();
805     if (MRegisterInfo::isPhysicalRegister(VirtReg) || MO.getSubReg())
806       continue;
807     if (VRM.isAssignedReg(VirtReg)) {
808       unsigned PhysReg = VRM.getPhys(VirtReg);
809       if (PhysReg && MRI->regsOverlap(PhysReg, UnfoldPR))
810         return false;
811     } else if (VRM.isReMaterialized(VirtReg))
812       continue;
813     int SS = VRM.getStackSlot(VirtReg);
814     unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SS);
815     if (PhysReg) {
816       if (MRI->regsOverlap(PhysReg, UnfoldPR))
817         return false;
818       continue;
819     }
820     PhysReg = VRM.getPhys(VirtReg);
821     if (!MRI->regsOverlap(PhysReg, UnfoldPR))
822       continue;
823
824     // Ok, we'll need to reload the value into a register which makes
825     // it impossible to perform the store unfolding optimization later.
826     // Let's see if it is possible to fold the load if the store is
827     // unfolded. This allows us to perform the store unfolding
828     // optimization.
829     SmallVector<MachineInstr*, 4> NewMIs;
830     if (MRI->unfoldMemoryOperand(MF, &MI, UnfoldVR, false, false, NewMIs)) {
831       assert(NewMIs.size() == 1);
832       MachineInstr *NewMI = NewMIs.back();
833       NewMIs.clear();
834       int Idx = NewMI->findRegisterUseOperandIdx(VirtReg);
835       assert(Idx != -1);
836       SmallVector<unsigned, 2> Ops;
837       Ops.push_back(Idx);
838       MachineInstr *FoldedMI = MRI->foldMemoryOperand(NewMI, Ops, SS);
839       if (FoldedMI) {
840         if (!VRM.hasPhys(UnfoldVR))
841           VRM.assignVirt2Phys(UnfoldVR, UnfoldPR);
842         VRM.virtFolded(VirtReg, FoldedMI, VirtRegMap::isRef);
843         MII = MBB.insert(MII, FoldedMI);
844         VRM.RemoveMachineInstrFromMaps(&MI);
845         MBB.erase(&MI);
846         return true;
847       }
848       delete NewMI;
849     }
850   }
851   return false;
852 }
853
854 /// findSuperReg - Find the SubReg's super-register of given register class
855 /// where its SubIdx sub-register is SubReg.
856 static unsigned findSuperReg(const TargetRegisterClass *RC, unsigned SubReg,
857                              unsigned SubIdx, const MRegisterInfo *MRI) {
858   for (TargetRegisterClass::iterator I = RC->begin(), E = RC->end();
859        I != E; ++I) {
860     unsigned Reg = *I;
861     if (MRI->getSubReg(Reg, SubIdx) == SubReg)
862       return Reg;
863   }
864   return 0;
865 }
866
867 /// SpillRegToStackSlot - Spill a register to a specified stack slot. Check if
868 /// the last store to the same slot is now dead. If so, remove the last store.
869 void LocalSpiller::SpillRegToStackSlot(MachineBasicBlock &MBB,
870                                   MachineBasicBlock::iterator &MII,
871                                   int Idx, unsigned PhysReg, int StackSlot,
872                                   const TargetRegisterClass *RC,
873                                   bool isAvailable, MachineInstr *&LastStore,
874                                   AvailableSpills &Spills,
875                                   SmallSet<MachineInstr*, 4> &ReMatDefs,
876                                   BitVector &RegKills,
877                                   std::vector<MachineOperand*> &KillOps,
878                                   VirtRegMap &VRM) {
879   MRI->storeRegToStackSlot(MBB, next(MII), PhysReg, true, StackSlot, RC);
880   DOUT << "Store:\t" << *next(MII);
881
882   // If there is a dead store to this stack slot, nuke it now.
883   if (LastStore) {
884     DOUT << "Removed dead store:\t" << *LastStore;
885     ++NumDSE;
886     SmallVector<unsigned, 2> KillRegs;
887     InvalidateKills(*LastStore, RegKills, KillOps, &KillRegs);
888     MachineBasicBlock::iterator PrevMII = LastStore;
889     bool CheckDef = PrevMII != MBB.begin();
890     if (CheckDef)
891       --PrevMII;
892     MBB.erase(LastStore);
893     VRM.RemoveMachineInstrFromMaps(LastStore);
894     if (CheckDef) {
895       // Look at defs of killed registers on the store. Mark the defs
896       // as dead since the store has been deleted and they aren't
897       // being reused.
898       for (unsigned j = 0, ee = KillRegs.size(); j != ee; ++j) {
899         bool HasOtherDef = false;
900         if (InvalidateRegDef(PrevMII, *MII, KillRegs[j], HasOtherDef)) {
901           MachineInstr *DeadDef = PrevMII;
902           if (ReMatDefs.count(DeadDef) && !HasOtherDef) {
903             // FIXME: This assumes a remat def does not have side
904             // effects.
905             MBB.erase(DeadDef);
906             VRM.RemoveMachineInstrFromMaps(DeadDef);
907             ++NumDRM;
908           }
909         }
910       }
911     }
912   }
913
914   LastStore = next(MII);
915
916   // If the stack slot value was previously available in some other
917   // register, change it now.  Otherwise, make the register available,
918   // in PhysReg.
919   Spills.ModifyStackSlotOrReMat(StackSlot);
920   Spills.ClobberPhysReg(PhysReg);
921   Spills.addAvailable(StackSlot, LastStore, PhysReg, isAvailable);
922   ++NumStores;
923 }
924
925 /// rewriteMBB - Keep track of which spills are available even after the
926 /// register allocator is done with them.  If possible, avid reloading vregs.
927 void LocalSpiller::RewriteMBB(MachineBasicBlock &MBB, VirtRegMap &VRM) {
928   DOUT << MBB.getBasicBlock()->getName() << ":\n";
929
930   MachineFunction &MF = *MBB.getParent();
931
932   // Spills - Keep track of which spilled values are available in physregs so
933   // that we can choose to reuse the physregs instead of emitting reloads.
934   AvailableSpills Spills(MRI, TII);
935   
936   // MaybeDeadStores - When we need to write a value back into a stack slot,
937   // keep track of the inserted store.  If the stack slot value is never read
938   // (because the value was used from some available register, for example), and
939   // subsequently stored to, the original store is dead.  This map keeps track
940   // of inserted stores that are not used.  If we see a subsequent store to the
941   // same stack slot, the original store is deleted.
942   std::vector<MachineInstr*> MaybeDeadStores;
943   MaybeDeadStores.resize(MF.getFrameInfo()->getObjectIndexEnd(), NULL);
944
945   // ReMatDefs - These are rematerializable def MIs which are not deleted.
946   SmallSet<MachineInstr*, 4> ReMatDefs;
947
948   // Keep track of kill information.
949   BitVector RegKills(MRI->getNumRegs());
950   std::vector<MachineOperand*>  KillOps;
951   KillOps.resize(MRI->getNumRegs(), NULL);
952
953   for (MachineBasicBlock::iterator MII = MBB.begin(), E = MBB.end();
954        MII != E; ) {
955     MachineBasicBlock::iterator NextMII = MII; ++NextMII;
956
957     VirtRegMap::MI2VirtMapTy::const_iterator I, End;
958     bool Erased = false;
959     bool BackTracked = false;
960     if (PrepForUnfoldOpti(MBB, MII,
961                           MaybeDeadStores, Spills, RegKills, KillOps, VRM))
962       NextMII = next(MII);
963
964     MachineInstr &MI = *MII;
965     const TargetInstrDescriptor *TID = MI.getInstrDescriptor();
966
967     // Insert restores here if asked to.
968     if (VRM.isRestorePt(&MI)) {
969       std::vector<unsigned> &RestoreRegs = VRM.getRestorePtRestores(&MI);
970       for (unsigned i = 0, e = RestoreRegs.size(); i != e; ++i) {
971         unsigned VirtReg = RestoreRegs[i];
972         if (!VRM.getPreSplitReg(VirtReg))
973           continue; // Split interval spilled again.
974         unsigned Phys = VRM.getPhys(VirtReg);
975         RegInfo->setPhysRegUsed(Phys);
976         if (VRM.isReMaterialized(VirtReg)) {
977           MRI->reMaterialize(MBB, &MI, Phys,
978                              VRM.getReMaterializedMI(VirtReg));
979           ++NumReMats;
980         } else {
981           const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
982           MRI->loadRegFromStackSlot(MBB, &MI, Phys, VRM.getStackSlot(VirtReg),
983                                     RC);
984           ++NumLoads;
985         }
986         // This invalidates Phys.
987         Spills.ClobberPhysReg(Phys);
988         UpdateKills(*prior(MII), RegKills, KillOps);
989         DOUT << '\t' << *prior(MII);
990       }
991     }
992
993     // Insert spills here if asked to.
994     if (VRM.isSpillPt(&MI)) {
995       std::vector<std::pair<unsigned,bool> > &SpillRegs =
996         VRM.getSpillPtSpills(&MI);
997       for (unsigned i = 0, e = SpillRegs.size(); i != e; ++i) {
998         unsigned VirtReg = SpillRegs[i].first;
999         bool isKill = SpillRegs[i].second;
1000         if (!VRM.getPreSplitReg(VirtReg))
1001           continue; // Split interval spilled again.
1002         const TargetRegisterClass *RC = RegInfo->getRegClass(VirtReg);
1003         unsigned Phys = VRM.getPhys(VirtReg);
1004         int StackSlot = VRM.getStackSlot(VirtReg);
1005         MRI->storeRegToStackSlot(MBB, next(MII), Phys, isKill, StackSlot, RC);
1006         MachineInstr *StoreMI = next(MII);
1007         DOUT << "Store:\t" << StoreMI;
1008         VRM.virtFolded(VirtReg, StoreMI, VirtRegMap::isMod);
1009       }
1010       NextMII = next(MII);
1011     }
1012
1013     /// ReusedOperands - Keep track of operand reuse in case we need to undo
1014     /// reuse.
1015     ReuseInfo ReusedOperands(MI, MRI);
1016     // Process all of the spilled uses and all non spilled reg references.
1017     for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1018       MachineOperand &MO = MI.getOperand(i);
1019       if (!MO.isRegister() || MO.getReg() == 0)
1020         continue;   // Ignore non-register operands.
1021       
1022       unsigned VirtReg = MO.getReg();
1023       if (MRegisterInfo::isPhysicalRegister(VirtReg)) {
1024         // Ignore physregs for spilling, but remember that it is used by this
1025         // function.
1026         RegInfo->setPhysRegUsed(VirtReg);
1027         continue;
1028       }
1029       
1030       assert(MRegisterInfo::isVirtualRegister(VirtReg) &&
1031              "Not a virtual or a physical register?");
1032
1033       unsigned SubIdx = MO.getSubReg();
1034       if (VRM.isAssignedReg(VirtReg)) {
1035         // This virtual register was assigned a physreg!
1036         unsigned Phys = VRM.getPhys(VirtReg);
1037         RegInfo->setPhysRegUsed(Phys);
1038         if (MO.isDef())
1039           ReusedOperands.markClobbered(Phys);
1040         unsigned RReg = SubIdx ? MRI->getSubReg(Phys, SubIdx) : Phys;
1041         MI.getOperand(i).setReg(RReg);
1042         continue;
1043       }
1044       
1045       // This virtual register is now known to be a spilled value.
1046       if (!MO.isUse())
1047         continue;  // Handle defs in the loop below (handle use&def here though)
1048
1049       bool DoReMat = VRM.isReMaterialized(VirtReg);
1050       int SSorRMId = DoReMat
1051         ? VRM.getReMatId(VirtReg) : VRM.getStackSlot(VirtReg);
1052       int ReuseSlot = SSorRMId;
1053
1054       // Check to see if this stack slot is available.
1055       unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SSorRMId);
1056
1057       // If this is a sub-register use, make sure the reuse register is in the
1058       // right register class. For example, for x86 not all of the 32-bit
1059       // registers have accessible sub-registers.
1060       // Similarly so for EXTRACT_SUBREG. Consider this:
1061       // EDI = op
1062       // MOV32_mr fi#1, EDI
1063       // ...
1064       //       = EXTRACT_SUBREG fi#1
1065       // fi#1 is available in EDI, but it cannot be reused because it's not in
1066       // the right register file.
1067       if (PhysReg &&
1068           (SubIdx || MI.getOpcode() == TargetInstrInfo::EXTRACT_SUBREG)) {
1069         const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
1070         if (!RC->contains(PhysReg))
1071           PhysReg = 0;
1072       }
1073
1074       if (PhysReg) {
1075         // This spilled operand might be part of a two-address operand.  If this
1076         // is the case, then changing it will necessarily require changing the 
1077         // def part of the instruction as well.  However, in some cases, we
1078         // aren't allowed to modify the reused register.  If none of these cases
1079         // apply, reuse it.
1080         bool CanReuse = true;
1081         int ti = TID->getOperandConstraint(i, TOI::TIED_TO);
1082         if (ti != -1 &&
1083             MI.getOperand(ti).isRegister() && 
1084             MI.getOperand(ti).getReg() == VirtReg) {
1085           // Okay, we have a two address operand.  We can reuse this physreg as
1086           // long as we are allowed to clobber the value and there isn't an
1087           // earlier def that has already clobbered the physreg.
1088           CanReuse = Spills.canClobberPhysReg(ReuseSlot) &&
1089             !ReusedOperands.isClobbered(PhysReg);
1090         }
1091         
1092         if (CanReuse) {
1093           // If this stack slot value is already available, reuse it!
1094           if (ReuseSlot > VirtRegMap::MAX_STACK_SLOT)
1095             DOUT << "Reusing RM#" << ReuseSlot-VirtRegMap::MAX_STACK_SLOT-1;
1096           else
1097             DOUT << "Reusing SS#" << ReuseSlot;
1098           DOUT << " from physreg "
1099                << MRI->getName(PhysReg) << " for vreg"
1100                << VirtReg <<" instead of reloading into physreg "
1101                << MRI->getName(VRM.getPhys(VirtReg)) << "\n";
1102           unsigned RReg = SubIdx ? MRI->getSubReg(PhysReg, SubIdx) : PhysReg;
1103           MI.getOperand(i).setReg(RReg);
1104
1105           // The only technical detail we have is that we don't know that
1106           // PhysReg won't be clobbered by a reloaded stack slot that occurs
1107           // later in the instruction.  In particular, consider 'op V1, V2'.
1108           // If V1 is available in physreg R0, we would choose to reuse it
1109           // here, instead of reloading it into the register the allocator
1110           // indicated (say R1).  However, V2 might have to be reloaded
1111           // later, and it might indicate that it needs to live in R0.  When
1112           // this occurs, we need to have information available that
1113           // indicates it is safe to use R1 for the reload instead of R0.
1114           //
1115           // To further complicate matters, we might conflict with an alias,
1116           // or R0 and R1 might not be compatible with each other.  In this
1117           // case, we actually insert a reload for V1 in R1, ensuring that
1118           // we can get at R0 or its alias.
1119           ReusedOperands.addReuse(i, ReuseSlot, PhysReg,
1120                                   VRM.getPhys(VirtReg), VirtReg);
1121           if (ti != -1)
1122             // Only mark it clobbered if this is a use&def operand.
1123             ReusedOperands.markClobbered(PhysReg);
1124           ++NumReused;
1125
1126           if (MI.getOperand(i).isKill() &&
1127               ReuseSlot <= VirtRegMap::MAX_STACK_SLOT) {
1128             // This was the last use and the spilled value is still available
1129             // for reuse. That means the spill was unnecessary!
1130             MachineInstr* DeadStore = MaybeDeadStores[ReuseSlot];
1131             if (DeadStore) {
1132               DOUT << "Removed dead store:\t" << *DeadStore;
1133               InvalidateKills(*DeadStore, RegKills, KillOps);
1134               VRM.RemoveMachineInstrFromMaps(DeadStore);
1135               MBB.erase(DeadStore);
1136               MaybeDeadStores[ReuseSlot] = NULL;
1137               ++NumDSE;
1138             }
1139           }
1140           continue;
1141         }  // CanReuse
1142         
1143         // Otherwise we have a situation where we have a two-address instruction
1144         // whose mod/ref operand needs to be reloaded.  This reload is already
1145         // available in some register "PhysReg", but if we used PhysReg as the
1146         // operand to our 2-addr instruction, the instruction would modify
1147         // PhysReg.  This isn't cool if something later uses PhysReg and expects
1148         // to get its initial value.
1149         //
1150         // To avoid this problem, and to avoid doing a load right after a store,
1151         // we emit a copy from PhysReg into the designated register for this
1152         // operand.
1153         unsigned DesignatedReg = VRM.getPhys(VirtReg);
1154         assert(DesignatedReg && "Must map virtreg to physreg!");
1155
1156         // Note that, if we reused a register for a previous operand, the
1157         // register we want to reload into might not actually be
1158         // available.  If this occurs, use the register indicated by the
1159         // reuser.
1160         if (ReusedOperands.hasReuses())
1161           DesignatedReg = ReusedOperands.GetRegForReload(DesignatedReg, &MI, 
1162                                Spills, MaybeDeadStores, RegKills, KillOps, VRM);
1163         
1164         // If the mapped designated register is actually the physreg we have
1165         // incoming, we don't need to inserted a dead copy.
1166         if (DesignatedReg == PhysReg) {
1167           // If this stack slot value is already available, reuse it!
1168           if (ReuseSlot > VirtRegMap::MAX_STACK_SLOT)
1169             DOUT << "Reusing RM#" << ReuseSlot-VirtRegMap::MAX_STACK_SLOT-1;
1170           else
1171             DOUT << "Reusing SS#" << ReuseSlot;
1172           DOUT << " from physreg " << MRI->getName(PhysReg) << " for vreg"
1173                << VirtReg
1174                << " instead of reloading into same physreg.\n";
1175           unsigned RReg = SubIdx ? MRI->getSubReg(PhysReg, SubIdx) : PhysReg;
1176           MI.getOperand(i).setReg(RReg);
1177           ReusedOperands.markClobbered(RReg);
1178           ++NumReused;
1179           continue;
1180         }
1181         
1182         const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
1183         RegInfo->setPhysRegUsed(DesignatedReg);
1184         ReusedOperands.markClobbered(DesignatedReg);
1185         MRI->copyRegToReg(MBB, &MI, DesignatedReg, PhysReg, RC, RC);
1186
1187         MachineInstr *CopyMI = prior(MII);
1188         UpdateKills(*CopyMI, RegKills, KillOps);
1189
1190         // This invalidates DesignatedReg.
1191         Spills.ClobberPhysReg(DesignatedReg);
1192         
1193         Spills.addAvailable(ReuseSlot, &MI, DesignatedReg);
1194         unsigned RReg =
1195           SubIdx ? MRI->getSubReg(DesignatedReg, SubIdx) : DesignatedReg;
1196         MI.getOperand(i).setReg(RReg);
1197         DOUT << '\t' << *prior(MII);
1198         ++NumReused;
1199         continue;
1200       } // if (PhysReg)
1201       
1202       // Otherwise, reload it and remember that we have it.
1203       PhysReg = VRM.getPhys(VirtReg);
1204       assert(PhysReg && "Must map virtreg to physreg!");
1205
1206       // Note that, if we reused a register for a previous operand, the
1207       // register we want to reload into might not actually be
1208       // available.  If this occurs, use the register indicated by the
1209       // reuser.
1210       if (ReusedOperands.hasReuses())
1211         PhysReg = ReusedOperands.GetRegForReload(PhysReg, &MI, 
1212                                Spills, MaybeDeadStores, RegKills, KillOps, VRM);
1213       
1214       RegInfo->setPhysRegUsed(PhysReg);
1215       ReusedOperands.markClobbered(PhysReg);
1216       if (DoReMat) {
1217         MRI->reMaterialize(MBB, &MI, PhysReg, VRM.getReMaterializedMI(VirtReg));
1218         ++NumReMats;
1219       } else {
1220         const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
1221         MRI->loadRegFromStackSlot(MBB, &MI, PhysReg, SSorRMId, RC);
1222         ++NumLoads;
1223       }
1224       // This invalidates PhysReg.
1225       Spills.ClobberPhysReg(PhysReg);
1226
1227       // Any stores to this stack slot are not dead anymore.
1228       if (!DoReMat)
1229         MaybeDeadStores[SSorRMId] = NULL;
1230       Spills.addAvailable(SSorRMId, &MI, PhysReg);
1231       // Assumes this is the last use. IsKill will be unset if reg is reused
1232       // unless it's a two-address operand.
1233       if (TID->getOperandConstraint(i, TOI::TIED_TO) == -1)
1234         MI.getOperand(i).setIsKill();
1235       unsigned RReg = SubIdx ? MRI->getSubReg(PhysReg, SubIdx) : PhysReg;
1236       MI.getOperand(i).setReg(RReg);
1237       UpdateKills(*prior(MII), RegKills, KillOps);
1238       DOUT << '\t' << *prior(MII);
1239     }
1240
1241     DOUT << '\t' << MI;
1242
1243
1244     // If we have folded references to memory operands, make sure we clear all
1245     // physical registers that may contain the value of the spilled virtual
1246     // register
1247     SmallSet<int, 2> FoldedSS;
1248     for (tie(I, End) = VRM.getFoldedVirts(&MI); I != End; ++I) {
1249       unsigned VirtReg = I->second.first;
1250       VirtRegMap::ModRef MR = I->second.second;
1251       DOUT << "Folded vreg: " << VirtReg << "  MR: " << MR;
1252
1253       int SS = VRM.getStackSlot(VirtReg);
1254       if (SS == VirtRegMap::NO_STACK_SLOT)
1255         continue;
1256       FoldedSS.insert(SS);
1257       DOUT << " - StackSlot: " << SS << "\n";
1258       
1259       // If this folded instruction is just a use, check to see if it's a
1260       // straight load from the virt reg slot.
1261       if ((MR & VirtRegMap::isRef) && !(MR & VirtRegMap::isMod)) {
1262         int FrameIdx;
1263         unsigned DestReg = TII->isLoadFromStackSlot(&MI, FrameIdx);
1264         if (DestReg && FrameIdx == SS) {
1265           // If this spill slot is available, turn it into a copy (or nothing)
1266           // instead of leaving it as a load!
1267           if (unsigned InReg = Spills.getSpillSlotOrReMatPhysReg(SS)) {
1268             DOUT << "Promoted Load To Copy: " << MI;
1269             if (DestReg != InReg) {
1270               const TargetRegisterClass *RC = RegInfo->getRegClass(VirtReg);
1271               MRI->copyRegToReg(MBB, &MI, DestReg, InReg, RC, RC);
1272               // Revisit the copy so we make sure to notice the effects of the
1273               // operation on the destreg (either needing to RA it if it's 
1274               // virtual or needing to clobber any values if it's physical).
1275               NextMII = &MI;
1276               --NextMII;  // backtrack to the copy.
1277               BackTracked = true;
1278             } else {
1279               DOUT << "Removing now-noop copy: " << MI;
1280               // Unset last kill since it's being reused.
1281               InvalidateKill(InReg, RegKills, KillOps);
1282             }
1283
1284             VRM.RemoveMachineInstrFromMaps(&MI);
1285             MBB.erase(&MI);
1286             Erased = true;
1287             goto ProcessNextInst;
1288           }
1289         } else {
1290           unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SS);
1291           SmallVector<MachineInstr*, 4> NewMIs;
1292           if (PhysReg &&
1293               MRI->unfoldMemoryOperand(MF, &MI, PhysReg, false, false, NewMIs)) {
1294             MBB.insert(MII, NewMIs[0]);
1295             VRM.RemoveMachineInstrFromMaps(&MI);
1296             MBB.erase(&MI);
1297             Erased = true;
1298             --NextMII;  // backtrack to the unfolded instruction.
1299             BackTracked = true;
1300             goto ProcessNextInst;
1301           }
1302         }
1303       }
1304
1305       // If this reference is not a use, any previous store is now dead.
1306       // Otherwise, the store to this stack slot is not dead anymore.
1307       MachineInstr* DeadStore = MaybeDeadStores[SS];
1308       if (DeadStore) {
1309         bool isDead = !(MR & VirtRegMap::isRef);
1310         MachineInstr *NewStore = NULL;
1311         if (MR & VirtRegMap::isModRef) {
1312           unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SS);
1313           SmallVector<MachineInstr*, 4> NewMIs;
1314           // We can reuse this physreg as long as we are allowed to clobber
1315           // the value and there isn't an earlier def that has already clobbered
1316           // the physreg.
1317           if (PhysReg &&
1318               !TII->isStoreToStackSlot(&MI, SS) && // Not profitable!
1319               DeadStore->findRegisterUseOperandIdx(PhysReg, true) != -1 &&
1320               MRI->unfoldMemoryOperand(MF, &MI, PhysReg, false, true, NewMIs)) {
1321             MBB.insert(MII, NewMIs[0]);
1322             NewStore = NewMIs[1];
1323             MBB.insert(MII, NewStore);
1324             VRM.RemoveMachineInstrFromMaps(&MI);
1325             MBB.erase(&MI);
1326             Erased = true;
1327             --NextMII;
1328             --NextMII;  // backtrack to the unfolded instruction.
1329             BackTracked = true;
1330             isDead = true;
1331           }
1332         }
1333
1334         if (isDead) {  // Previous store is dead.
1335           // If we get here, the store is dead, nuke it now.
1336           DOUT << "Removed dead store:\t" << *DeadStore;
1337           InvalidateKills(*DeadStore, RegKills, KillOps);
1338           VRM.RemoveMachineInstrFromMaps(DeadStore);
1339           MBB.erase(DeadStore);
1340           if (!NewStore)
1341             ++NumDSE;
1342         }
1343
1344         MaybeDeadStores[SS] = NULL;
1345         if (NewStore) {
1346           // Treat this store as a spill merged into a copy. That makes the
1347           // stack slot value available.
1348           VRM.virtFolded(VirtReg, NewStore, VirtRegMap::isMod);
1349           goto ProcessNextInst;
1350         }
1351       }
1352
1353       // If the spill slot value is available, and this is a new definition of
1354       // the value, the value is not available anymore.
1355       if (MR & VirtRegMap::isMod) {
1356         // Notice that the value in this stack slot has been modified.
1357         Spills.ModifyStackSlotOrReMat(SS);
1358         
1359         // If this is *just* a mod of the value, check to see if this is just a
1360         // store to the spill slot (i.e. the spill got merged into the copy). If
1361         // so, realize that the vreg is available now, and add the store to the
1362         // MaybeDeadStore info.
1363         int StackSlot;
1364         if (!(MR & VirtRegMap::isRef)) {
1365           if (unsigned SrcReg = TII->isStoreToStackSlot(&MI, StackSlot)) {
1366             assert(MRegisterInfo::isPhysicalRegister(SrcReg) &&
1367                    "Src hasn't been allocated yet?");
1368             // Okay, this is certainly a store of SrcReg to [StackSlot].  Mark
1369             // this as a potentially dead store in case there is a subsequent
1370             // store into the stack slot without a read from it.
1371             MaybeDeadStores[StackSlot] = &MI;
1372
1373             // If the stack slot value was previously available in some other
1374             // register, change it now.  Otherwise, make the register available,
1375             // in PhysReg.
1376             Spills.addAvailable(StackSlot, &MI, SrcReg, false/*don't clobber*/);
1377           }
1378         }
1379       }
1380     }
1381
1382     // Process all of the spilled defs.
1383     for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1384       MachineOperand &MO = MI.getOperand(i);
1385       if (!(MO.isRegister() && MO.getReg() && MO.isDef()))
1386         continue;
1387
1388       unsigned VirtReg = MO.getReg();
1389       if (!MRegisterInfo::isVirtualRegister(VirtReg)) {
1390         // Check to see if this is a noop copy.  If so, eliminate the
1391         // instruction before considering the dest reg to be changed.
1392         unsigned Src, Dst;
1393         if (TII->isMoveInstr(MI, Src, Dst) && Src == Dst) {
1394           ++NumDCE;
1395           DOUT << "Removing now-noop copy: " << MI;
1396           MBB.erase(&MI);
1397           Erased = true;
1398           VRM.RemoveMachineInstrFromMaps(&MI);
1399           Spills.disallowClobberPhysReg(VirtReg);
1400           goto ProcessNextInst;
1401         }
1402           
1403         // If it's not a no-op copy, it clobbers the value in the destreg.
1404         Spills.ClobberPhysReg(VirtReg);
1405         ReusedOperands.markClobbered(VirtReg);
1406  
1407         // Check to see if this instruction is a load from a stack slot into
1408         // a register.  If so, this provides the stack slot value in the reg.
1409         int FrameIdx;
1410         if (unsigned DestReg = TII->isLoadFromStackSlot(&MI, FrameIdx)) {
1411           assert(DestReg == VirtReg && "Unknown load situation!");
1412
1413           // If it is a folded reference, then it's not safe to clobber.
1414           bool Folded = FoldedSS.count(FrameIdx);
1415           // Otherwise, if it wasn't available, remember that it is now!
1416           Spills.addAvailable(FrameIdx, &MI, DestReg, !Folded);
1417           goto ProcessNextInst;
1418         }
1419             
1420         continue;
1421       }
1422
1423       unsigned SubIdx = MO.getSubReg();
1424       bool DoReMat = VRM.isReMaterialized(VirtReg);
1425       if (DoReMat)
1426         ReMatDefs.insert(&MI);
1427
1428       // The only vregs left are stack slot definitions.
1429       int StackSlot = VRM.getStackSlot(VirtReg);
1430       const TargetRegisterClass *RC = RegInfo->getRegClass(VirtReg);
1431
1432       // If this def is part of a two-address operand, make sure to execute
1433       // the store from the correct physical register.
1434       unsigned PhysReg;
1435       int TiedOp = MI.getInstrDescriptor()->findTiedToSrcOperand(i);
1436       if (TiedOp != -1) {
1437         PhysReg = MI.getOperand(TiedOp).getReg();
1438         if (SubIdx) {
1439           unsigned SuperReg = findSuperReg(RC, PhysReg, SubIdx, MRI);
1440           assert(SuperReg && MRI->getSubReg(SuperReg, SubIdx) == PhysReg &&
1441                  "Can't find corresponding super-register!");
1442           PhysReg = SuperReg;
1443         }
1444       } else {
1445         PhysReg = VRM.getPhys(VirtReg);
1446         if (ReusedOperands.isClobbered(PhysReg)) {
1447           // Another def has taken the assigned physreg. It must have been a
1448           // use&def which got it due to reuse. Undo the reuse!
1449           PhysReg = ReusedOperands.GetRegForReload(PhysReg, &MI, 
1450                                Spills, MaybeDeadStores, RegKills, KillOps, VRM);
1451         }
1452       }
1453
1454       RegInfo->setPhysRegUsed(PhysReg);
1455       unsigned RReg = SubIdx ? MRI->getSubReg(PhysReg, SubIdx) : PhysReg;
1456       ReusedOperands.markClobbered(RReg);
1457       MI.getOperand(i).setReg(RReg);
1458
1459       if (!MO.isDead()) {
1460         MachineInstr *&LastStore = MaybeDeadStores[StackSlot];
1461         SpillRegToStackSlot(MBB, MII, -1, PhysReg, StackSlot, RC, true,
1462                           LastStore, Spills, ReMatDefs, RegKills, KillOps, VRM);
1463         NextMII = next(MII);
1464
1465         // Check to see if this is a noop copy.  If so, eliminate the
1466         // instruction before considering the dest reg to be changed.
1467         {
1468           unsigned Src, Dst;
1469           if (TII->isMoveInstr(MI, Src, Dst) && Src == Dst) {
1470             ++NumDCE;
1471             DOUT << "Removing now-noop copy: " << MI;
1472             MBB.erase(&MI);
1473             Erased = true;
1474             VRM.RemoveMachineInstrFromMaps(&MI);
1475             UpdateKills(*LastStore, RegKills, KillOps);
1476             goto ProcessNextInst;
1477           }
1478         }
1479       }    
1480     }
1481   ProcessNextInst:
1482     if (!Erased && !BackTracked) {
1483       for (MachineBasicBlock::iterator II = MI; II != NextMII; ++II)
1484         UpdateKills(*II, RegKills, KillOps);
1485     }
1486     MII = NextMII;
1487   }
1488 }
1489
1490 llvm::Spiller* llvm::createSpiller() {
1491   switch (SpillerOpt) {
1492   default: assert(0 && "Unreachable!");
1493   case local:
1494     return new LocalSpiller();
1495   case simple:
1496     return new SimpleSpiller();
1497   }
1498 }