8e6ff027e97e911cceeaf9c6c8bb5ca95e088be1
[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 was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source 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/SSARegMap.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/ADT/Statistic.h"
30 #include "llvm/ADT/STLExtras.h"
31 using namespace llvm;
32
33 namespace {
34   Statistic<> NumSpills("spiller", "Number of register spills");
35   Statistic<> NumStores("spiller", "Number of stores added");
36   Statistic<> NumLoads ("spiller", "Number of loads added");
37   Statistic<> NumReused("spiller", "Number of values reused");
38   Statistic<> NumDSE   ("spiller", "Number of dead stores elided");
39
40   enum SpillerName { simple, local };
41
42   cl::opt<SpillerName>
43   SpillerOpt("spiller",
44              cl::desc("Spiller to use: (default: local)"),
45              cl::Prefix,
46              cl::values(clEnumVal(simple, "  simple spiller"),
47                         clEnumVal(local,  "  local spiller"),
48                         clEnumValEnd),
49              cl::init(local));
50 }
51
52 //===----------------------------------------------------------------------===//
53 //  VirtRegMap implementation
54 //===----------------------------------------------------------------------===//
55
56 void VirtRegMap::grow() {
57   Virt2PhysMap.grow(MF.getSSARegMap()->getLastVirtReg());
58   Virt2StackSlotMap.grow(MF.getSSARegMap()->getLastVirtReg());
59 }
60
61 int VirtRegMap::assignVirt2StackSlot(unsigned virtReg) {
62   assert(MRegisterInfo::isVirtualRegister(virtReg));
63   assert(Virt2StackSlotMap[virtReg] == NO_STACK_SLOT &&
64          "attempt to assign stack slot to already spilled register");
65   const TargetRegisterClass* RC = MF.getSSARegMap()->getRegClass(virtReg);
66   int frameIndex = MF.getFrameInfo()->CreateStackObject(RC->getSize(),
67                                                         RC->getAlignment());
68   Virt2StackSlotMap[virtReg] = frameIndex;
69   ++NumSpills;
70   return frameIndex;
71 }
72
73 void VirtRegMap::assignVirt2StackSlot(unsigned virtReg, int frameIndex) {
74   assert(MRegisterInfo::isVirtualRegister(virtReg));
75   assert(Virt2StackSlotMap[virtReg] == NO_STACK_SLOT &&
76          "attempt to assign stack slot to already spilled register");
77   Virt2StackSlotMap[virtReg] = frameIndex;
78 }
79
80 void VirtRegMap::virtFolded(unsigned virtReg,
81                             MachineInstr* oldMI,
82                             MachineInstr* newMI) {
83   // move previous memory references folded to new instruction
84   std::vector<MI2VirtMapTy::mapped_type> regs;
85   for (MI2VirtMapTy::iterator I = MI2VirtMap.lower_bound(oldMI), 
86          E = MI2VirtMap.end(); I != E && I->first == oldMI; ) {
87     regs.push_back(I->second);
88     MI2VirtMap.erase(I++);
89   }
90
91   MI2VirtMapTy::iterator IP = MI2VirtMap.lower_bound(newMI);
92   for (unsigned i = 0, e = regs.size(); i != e; ++i)
93     MI2VirtMap.insert(IP, std::make_pair(newMI, regs[i]));
94
95   // add new memory reference
96   MI2VirtMap.insert(IP, std::make_pair(newMI, virtReg));
97 }
98
99 void VirtRegMap::print(std::ostream &OS) const {
100   const MRegisterInfo* MRI = MF.getTarget().getRegisterInfo();
101
102   OS << "********** REGISTER MAP **********\n";
103   for (unsigned i = MRegisterInfo::FirstVirtualRegister,
104          e = MF.getSSARegMap()->getLastVirtReg(); i <= e; ++i) {
105     if (Virt2PhysMap[i] != (unsigned)VirtRegMap::NO_PHYS_REG)
106       OS << "[reg" << i << " -> " << MRI->getName(Virt2PhysMap[i]) << "]\n";
107          
108   }
109
110   for (unsigned i = MRegisterInfo::FirstVirtualRegister,
111          e = MF.getSSARegMap()->getLastVirtReg(); i <= e; ++i)
112     if (Virt2StackSlotMap[i] != VirtRegMap::NO_STACK_SLOT)
113       OS << "[reg" << i << " -> fi#" << Virt2StackSlotMap[i] << "]\n";
114   OS << '\n';
115 }
116
117 void VirtRegMap::dump() const { print(std::cerr); }
118
119
120 //===----------------------------------------------------------------------===//
121 // Simple Spiller Implementation
122 //===----------------------------------------------------------------------===//
123
124 Spiller::~Spiller() {}
125
126 namespace {
127   struct SimpleSpiller : public Spiller {
128     bool runOnMachineFunction(MachineFunction& mf, const VirtRegMap &VRM);
129   };
130 }
131
132 bool SimpleSpiller::runOnMachineFunction(MachineFunction& MF,
133                                          const VirtRegMap& VRM) {
134   DEBUG(std::cerr << "********** REWRITE MACHINE CODE **********\n");
135   DEBUG(std::cerr << "********** Function: "
136                   << MF.getFunction()->getName() << '\n');
137   const TargetMachine& TM = MF.getTarget();
138   const MRegisterInfo& MRI = *TM.getRegisterInfo();
139
140   // LoadedRegs - Keep track of which vregs are loaded, so that we only load
141   // each vreg once (in the case where a spilled vreg is used by multiple
142   // operands).  This is always smaller than the number of operands to the
143   // current machine instr, so it should be small.
144   std::vector<unsigned> LoadedRegs;
145
146   for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
147        MBBI != E; ++MBBI) {
148     DEBUG(std::cerr << MBBI->getBasicBlock()->getName() << ":\n");
149     MachineBasicBlock &MBB = *MBBI;
150     for (MachineBasicBlock::iterator MII = MBB.begin(),
151            E = MBB.end(); MII != E; ++MII) {
152       MachineInstr &MI = *MII;
153       for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
154         MachineOperand &MO = MI.getOperand(i);
155         if (MO.isRegister() && MO.getReg() &&
156             MRegisterInfo::isVirtualRegister(MO.getReg())) {
157           unsigned VirtReg = MO.getReg();
158           unsigned PhysReg = VRM.getPhys(VirtReg);
159           if (VRM.hasStackSlot(VirtReg)) {
160             int StackSlot = VRM.getStackSlot(VirtReg);
161
162             if (MO.isUse() &&
163                 std::find(LoadedRegs.begin(), LoadedRegs.end(), VirtReg)
164                            == LoadedRegs.end()) {
165               MRI.loadRegFromStackSlot(MBB, &MI, PhysReg, StackSlot);
166               LoadedRegs.push_back(VirtReg);
167               ++NumLoads;
168               DEBUG(std::cerr << '\t' << *prior(MII));
169             }
170
171             if (MO.isDef()) {
172               MRI.storeRegToStackSlot(MBB, next(MII), PhysReg, StackSlot);
173               ++NumStores;
174             }
175           }
176           MI.SetMachineOperandReg(i, PhysReg);
177         }
178       }
179       DEBUG(std::cerr << '\t' << MI);
180       LoadedRegs.clear();
181     }
182   }
183   return true;
184 }
185
186 //===----------------------------------------------------------------------===//
187 //  Local Spiller Implementation
188 //===----------------------------------------------------------------------===//
189
190 namespace {
191   /// LocalSpiller - This spiller does a simple pass over the machine basic
192   /// block to attempt to keep spills in registers as much as possible for
193   /// blocks that have low register pressure (the vreg may be spilled due to
194   /// register pressure in other blocks).
195   class LocalSpiller : public Spiller {
196     const MRegisterInfo *MRI;
197     const TargetInstrInfo *TII;
198   public:
199     bool runOnMachineFunction(MachineFunction &MF, const VirtRegMap &VRM) {
200       MRI = MF.getTarget().getRegisterInfo();
201       TII = MF.getTarget().getInstrInfo();
202       DEBUG(std::cerr << "\n**** Local spiller rewriting function '"
203                       << MF.getFunction()->getName() << "':\n");
204
205       for (MachineFunction::iterator MBB = MF.begin(), E = MF.end();
206            MBB != E; ++MBB)
207         RewriteMBB(*MBB, VRM);
208       return true;
209     }
210   private:
211     void RewriteMBB(MachineBasicBlock &MBB, const VirtRegMap &VRM);
212     void ClobberPhysReg(unsigned PR, std::map<int, unsigned> &SpillSlots,
213                         std::map<unsigned, int> &PhysRegs);
214     void ClobberPhysRegOnly(unsigned PR, std::map<int, unsigned> &SpillSlots,
215                             std::map<unsigned, int> &PhysRegs);
216   };
217 }
218
219 void LocalSpiller::ClobberPhysRegOnly(unsigned PhysReg,
220                                       std::map<int, unsigned> &SpillSlots,
221                                       std::map<unsigned, int> &PhysRegs) {
222   std::map<unsigned, int>::iterator I = PhysRegs.find(PhysReg);
223   if (I != PhysRegs.end()) {
224     int Slot = I->second;
225     PhysRegs.erase(I);
226     assert(SpillSlots[Slot] == PhysReg && "Bidirectional map mismatch!");
227     SpillSlots.erase(Slot);
228     DEBUG(std::cerr << "PhysReg " << MRI->getName(PhysReg)
229           << " clobbered, invalidating SS#" << Slot << "\n");
230
231   }
232 }
233
234 void LocalSpiller::ClobberPhysReg(unsigned PhysReg,
235                                   std::map<int, unsigned> &SpillSlots,
236                                   std::map<unsigned, int> &PhysRegs) {
237   for (const unsigned *AS = MRI->getAliasSet(PhysReg); *AS; ++AS)
238     ClobberPhysRegOnly(*AS, SpillSlots, PhysRegs);
239   ClobberPhysRegOnly(PhysReg, SpillSlots, PhysRegs);
240 }
241
242
243 // ReusedOp - For each reused operand, we keep track of a bit of information, in
244 // case we need to rollback upon processing a new operand.  See comments below.
245 namespace {
246   struct ReusedOp {
247     // The MachineInstr operand that reused an available value.
248     unsigned Operand;
249     
250     // StackSlot - The spill slot of the value being reused.
251     unsigned StackSlot;
252     
253     // PhysRegReused - The physical register the value was available in.
254     unsigned PhysRegReused;
255     
256     // AssignedPhysReg - The physreg that was assigned for use by the reload.
257     unsigned AssignedPhysReg;
258     
259     ReusedOp(unsigned o, unsigned ss, unsigned prr, unsigned apr)
260       : Operand(o), StackSlot(ss), PhysRegReused(prr), AssignedPhysReg(apr) {}
261   };
262 }
263
264
265 /// rewriteMBB - Keep track of which spills are available even after the
266 /// register allocator is done with them.  If possible, avoid reloading vregs.
267 void LocalSpiller::RewriteMBB(MachineBasicBlock &MBB, const VirtRegMap &VRM) {
268
269   // SpillSlotsAvailable - This map keeps track of all of the spilled virtual
270   // register values that are still available, due to being loaded to stored to,
271   // but not invalidated yet.
272   std::map<int, unsigned> SpillSlotsAvailable;
273
274   // PhysRegsAvailable - This is the inverse of SpillSlotsAvailable, indicating
275   // which physregs are in use holding a stack slot value.
276   std::map<unsigned, int> PhysRegsAvailable;
277
278   DEBUG(std::cerr << MBB.getBasicBlock()->getName() << ":\n");
279
280   std::vector<ReusedOp> ReusedOperands;
281
282   // DefAndUseVReg - When we see a def&use operand that is spilled, keep track
283   // of it.  ".first" is the machine operand index (should always be 0 for now),
284   // and ".second" is the virtual register that is spilled.
285   std::vector<std::pair<unsigned, unsigned> > DefAndUseVReg;
286
287   // MaybeDeadStores - When we need to write a value back into a stack slot,
288   // keep track of the inserted store.  If the stack slot value is never read
289   // (because the value was used from some available register, for example), and
290   // subsequently stored to, the original store is dead.  This map keeps track
291   // of inserted stores that are not used.  If we see a subsequent store to the
292   // same stack slot, the original store is deleted.
293   std::map<int, MachineInstr*> MaybeDeadStores;
294
295   for (MachineBasicBlock::iterator MII = MBB.begin(), E = MBB.end();
296        MII != E; ) {
297     MachineInstr &MI = *MII;
298     MachineBasicBlock::iterator NextMII = MII; ++NextMII;
299
300     ReusedOperands.clear();
301     DefAndUseVReg.clear();
302
303     // Process all of the spilled uses and all non spilled reg references.
304     for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
305       MachineOperand &MO = MI.getOperand(i);
306       if (MO.isRegister() && MO.getReg() &&
307           MRegisterInfo::isVirtualRegister(MO.getReg())) {
308         unsigned VirtReg = MO.getReg();
309
310         if (!VRM.hasStackSlot(VirtReg)) {
311           // This virtual register was assigned a physreg!
312           MI.SetMachineOperandReg(i, VRM.getPhys(VirtReg));
313         } else {
314           // Is this virtual register a spilled value?
315           if (MO.isUse()) {
316             int StackSlot = VRM.getStackSlot(VirtReg);
317             unsigned PhysReg;
318
319             // Check to see if this stack slot is available.
320             std::map<int, unsigned>::iterator SSI =
321               SpillSlotsAvailable.find(StackSlot);
322             if (SSI != SpillSlotsAvailable.end()) {
323               // If this stack slot value is already available, reuse it!
324               PhysReg = SSI->second;
325               MI.SetMachineOperandReg(i, PhysReg);
326               DEBUG(std::cerr << "Reusing SS#" << StackSlot << " from physreg "
327                               << MRI->getName(SSI->second) << "\n");
328
329               // The only technical detail we have is that we don't know that
330               // PhysReg won't be clobbered by a reloaded stack slot that occurs
331               // later in the instruction.  In particular, consider 'op V1, V2'.
332               // If V1 is available in physreg R0, we would choose to reuse it
333               // here, instead of reloading it into the register the allocator
334               // indicated (say R1).  However, V2 might have to be reloaded
335               // later, and it might indicate that it needs to live in R0.  When
336               // this occurs, we need to have information available that
337               // indicates it is safe to use R1 for the reload instead of R0.
338               //
339               // To further complicate matters, we might conflict with an alias,
340               // or R0 and R1 might not be compatible with each other.  In this
341               // case, we actually insert a reload for V1 in R1, ensuring that
342               // we can get at R0 or its alias.
343               ReusedOperands.push_back(ReusedOp(i, StackSlot, PhysReg,
344                                                 VRM.getPhys(VirtReg)));
345               ++NumReused;
346             } else {
347               // Otherwise, reload it and remember that we have it.
348               PhysReg = VRM.getPhys(VirtReg);
349
350               // Note that, if we reused a register for a previous operand, the
351               // register we want to reload into might not actually be
352               // available.  If this occurs, use the register indicated by the
353               // reuser.
354               if (!ReusedOperands.empty())   // This is most often empty.
355                 for (unsigned ro = 0, e = ReusedOperands.size(); ro != e; ++ro)
356                   if (ReusedOperands[ro].PhysRegReused == PhysReg) {
357                     // Yup, use the reload register that we didn't use before.
358                     PhysReg = ReusedOperands[ro].AssignedPhysReg;
359                     break;
360                   } else {
361                     ReusedOp &Op = ReusedOperands[ro];
362                     unsigned PRRU = Op.PhysRegReused;
363                     for (const unsigned *AS = MRI->getAliasSet(PRRU); *AS; ++AS)
364                       if (*AS == PhysReg) {
365                         // Okay, we found out that an alias of a reused register
366                         // was used.  This isn't good because it means we have
367                         // to undo a previous reuse.
368                         MRI->loadRegFromStackSlot(MBB, &MI, Op.AssignedPhysReg, 
369                                                   Op.StackSlot);
370                         ClobberPhysReg(Op.AssignedPhysReg, SpillSlotsAvailable,
371                                        PhysRegsAvailable);
372
373                         // Any stores to this stack slot are not dead anymore.
374                         MaybeDeadStores.erase(Op.StackSlot);
375
376                         MI.SetMachineOperandReg(Op.Operand, Op.AssignedPhysReg);
377                         PhysRegsAvailable[Op.AssignedPhysReg] = Op.StackSlot;
378                         SpillSlotsAvailable[Op.StackSlot] = Op.AssignedPhysReg;
379                         PhysRegsAvailable.erase(Op.PhysRegReused);
380                         DEBUG(std::cerr << "Remembering SS#" << Op.StackSlot
381                               << " in physreg "
382                               << MRI->getName(Op.AssignedPhysReg) << "\n");
383                         ++NumLoads;
384                         DEBUG(std::cerr << '\t' << *prior(MII));
385
386                         DEBUG(std::cerr << "Reuse undone!\n");
387                         ReusedOperands.erase(ReusedOperands.begin()+ro);
388                         --NumReused;
389                         goto ContinueReload;
390                       }
391                   }
392             ContinueReload:
393
394               MRI->loadRegFromStackSlot(MBB, &MI, PhysReg, StackSlot);
395               // This invalidates PhysReg.
396               ClobberPhysReg(PhysReg, SpillSlotsAvailable, PhysRegsAvailable);
397
398               // Any stores to this stack slot are not dead anymore.
399               MaybeDeadStores.erase(StackSlot);
400
401               MI.SetMachineOperandReg(i, PhysReg);
402               PhysRegsAvailable[PhysReg] = StackSlot;
403               SpillSlotsAvailable[StackSlot] = PhysReg;
404               DEBUG(std::cerr << "Remembering SS#" << StackSlot <<" in physreg "
405                               << MRI->getName(PhysReg) << "\n");
406               ++NumLoads;
407               DEBUG(std::cerr << '\t' << *prior(MII));
408             }
409
410             // If this is both a def and a use, we need to emit a store to the
411             // stack slot after the instruction.  Keep track of D&U operands
412             // because we already changed it to a physreg here.
413             if (MO.isDef()) {
414               // Remember that this was a def-and-use operand, and that the
415               // stack slot is live after this instruction executes.
416               DefAndUseVReg.push_back(std::make_pair(i, VirtReg));
417             }
418           }
419         }
420       }
421     }
422
423     // Loop over all of the implicit defs, clearing them from our available
424     // sets.
425     const TargetInstrDescriptor &InstrDesc = TII->get(MI.getOpcode());
426     for (const unsigned* ImpDef = InstrDesc.ImplicitDefs; *ImpDef; ++ImpDef)
427       ClobberPhysReg(*ImpDef, SpillSlotsAvailable, PhysRegsAvailable);
428
429     DEBUG(std::cerr << '\t' << MI);
430
431     // If we have folded references to memory operands, make sure we clear all
432     // physical registers that may contain the value of the spilled virtual
433     // register
434     VirtRegMap::MI2VirtMapTy::const_iterator I, E;
435     for (tie(I, E) = VRM.getFoldedVirts(&MI); I != E; ++I) {
436       DEBUG(std::cerr << "Folded vreg: " << I->second);
437       if (VRM.hasStackSlot(I->second)) {
438         int SS = VRM.getStackSlot(I->second);
439         DEBUG(std::cerr << " - StackSlot: " << SS << "\n");
440
441         // Any stores to this stack slot are not dead anymore.
442         MaybeDeadStores.erase(SS);
443
444         std::map<int, unsigned>::iterator I = SpillSlotsAvailable.find(SS);
445         if (I != SpillSlotsAvailable.end()) {
446           PhysRegsAvailable.erase(I->second);
447           SpillSlotsAvailable.erase(I);
448         }
449       } else {
450         DEBUG(std::cerr << ": No stack slot!\n");
451       }
452     }
453
454     // Process all of the spilled defs.
455     for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
456       MachineOperand &MO = MI.getOperand(i);
457       if (MO.isRegister() && MO.getReg() && MO.isDef()) {
458         unsigned VirtReg = MO.getReg();
459
460         bool TakenCareOf = false;
461         if (!MRegisterInfo::isVirtualRegister(VirtReg)) {
462           // Check to see if this is a def-and-use vreg operand that we do need
463           // to insert a store for.
464           bool OpTakenCareOf = false;
465           if (MO.isUse() && !DefAndUseVReg.empty()) {
466             for (unsigned dau = 0, e = DefAndUseVReg.size(); dau != e; ++dau)
467               if (DefAndUseVReg[dau].first == i) {
468                 VirtReg = DefAndUseVReg[dau].second;
469                 OpTakenCareOf = true;
470                 break;
471               }
472           }
473           
474           if (!OpTakenCareOf) {
475             ClobberPhysReg(VirtReg, SpillSlotsAvailable, PhysRegsAvailable);
476             TakenCareOf = true;
477           }
478         }  
479
480         if (!TakenCareOf) {
481           // The only vregs left are stack slot definitions.
482           int StackSlot    = VRM.getStackSlot(VirtReg);
483           unsigned PhysReg;
484
485           // If this is a def&use operand, and we used a different physreg for
486           // it than the one assigned, make sure to execute the store from the
487           // correct physical register.
488           if (MO.getReg() == VirtReg)
489             PhysReg = VRM.getPhys(VirtReg);
490           else
491             PhysReg = MO.getReg();
492
493           MRI->storeRegToStackSlot(MBB, next(MII), PhysReg, StackSlot);
494           DEBUG(std::cerr << "Store:\t" << *next(MII));
495           MI.SetMachineOperandReg(i, PhysReg);
496
497           // If there is a dead store to this stack slot, nuke it now.
498           MachineInstr *&LastStore = MaybeDeadStores[StackSlot];
499           if (LastStore) {
500             ++NumDSE;
501             MBB.erase(LastStore);
502           }
503           LastStore = next(MII);
504
505           // If the stack slot value was previously available in some other
506           // register, change it now.  Otherwise, make the register available,
507           // in PhysReg.
508           std::map<int, unsigned>::iterator SSA =
509             SpillSlotsAvailable.find(StackSlot);
510           if (SSA != SpillSlotsAvailable.end()) {
511             // Remove the record for physreg.
512             PhysRegsAvailable.erase(SSA->second);
513             SpillSlotsAvailable.erase(SSA);
514           }
515           ClobberPhysReg(PhysReg, SpillSlotsAvailable, PhysRegsAvailable);
516
517           PhysRegsAvailable[PhysReg] = StackSlot;
518           SpillSlotsAvailable[StackSlot] = PhysReg;
519           DEBUG(std::cerr << "Updating SS#" << StackSlot <<" in physreg "
520                           << MRI->getName(PhysReg) << "\n");
521
522           ++NumStores;
523           VirtReg = PhysReg;
524         }
525       }
526     }
527     MII = NextMII;
528   }
529 }
530
531
532
533 llvm::Spiller* llvm::createSpiller() {
534   switch (SpillerOpt) {
535   default: assert(0 && "Unreachable!");
536   case local:
537     return new LocalSpiller();
538   case simple:
539     return new SimpleSpiller();
540   }
541 }