dcfad6641453622e87384cb9d15a6f29efee9e63
[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 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 "regalloc"
20 #include "llvm/CodeGen/VirtRegMap.h"
21 #include "LiveDebugVariables.h"
22 #include "llvm/ADT/STLExtras.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
25 #include "llvm/CodeGen/LiveStackAnalysis.h"
26 #include "llvm/CodeGen/MachineFrameInfo.h"
27 #include "llvm/CodeGen/MachineFunction.h"
28 #include "llvm/CodeGen/MachineInstrBuilder.h"
29 #include "llvm/CodeGen/MachineRegisterInfo.h"
30 #include "llvm/CodeGen/Passes.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/Compiler.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include "llvm/Target/TargetInstrInfo.h"
36 #include "llvm/Target/TargetMachine.h"
37 #include "llvm/Target/TargetRegisterInfo.h"
38 #include <algorithm>
39 using namespace llvm;
40
41 STATISTIC(NumSpillSlots, "Number of spill slots allocated");
42 STATISTIC(NumIdCopies,   "Number of identity moves eliminated after rewriting");
43
44 //===----------------------------------------------------------------------===//
45 //  VirtRegMap implementation
46 //===----------------------------------------------------------------------===//
47
48 char VirtRegMap::ID = 0;
49
50 INITIALIZE_PASS(VirtRegMap, "virtregmap", "Virtual Register Map", false, false)
51
52 bool VirtRegMap::runOnMachineFunction(MachineFunction &mf) {
53   MRI = &mf.getRegInfo();
54   TII = mf.getTarget().getInstrInfo();
55   TRI = mf.getTarget().getRegisterInfo();
56   MF = &mf;
57
58   Virt2PhysMap.clear();
59   Virt2StackSlotMap.clear();
60   Virt2SplitMap.clear();
61
62   grow();
63   return false;
64 }
65
66 void VirtRegMap::grow() {
67   unsigned NumRegs = MF->getRegInfo().getNumVirtRegs();
68   Virt2PhysMap.resize(NumRegs);
69   Virt2StackSlotMap.resize(NumRegs);
70   Virt2SplitMap.resize(NumRegs);
71 }
72
73 unsigned VirtRegMap::createSpillSlot(const TargetRegisterClass *RC) {
74   int SS = MF->getFrameInfo()->CreateSpillStackObject(RC->getSize(),
75                                                       RC->getAlignment());
76   ++NumSpillSlots;
77   return SS;
78 }
79
80 unsigned VirtRegMap::getRegAllocPref(unsigned virtReg) {
81   std::pair<unsigned, unsigned> Hint = MRI->getRegAllocationHint(virtReg);
82   unsigned physReg = Hint.second;
83   if (TargetRegisterInfo::isVirtualRegister(physReg) && hasPhys(physReg))
84     physReg = getPhys(physReg);
85   if (Hint.first == 0)
86     return (TargetRegisterInfo::isPhysicalRegister(physReg))
87       ? physReg : 0;
88   return TRI->ResolveRegAllocHint(Hint.first, physReg, *MF);
89 }
90
91 bool VirtRegMap::hasKnownPreference(unsigned VirtReg) {
92   std::pair<unsigned, unsigned> Hint = MRI->getRegAllocationHint(VirtReg);
93   if (TargetRegisterInfo::isPhysicalRegister(Hint.second))
94     return true;
95   if (TargetRegisterInfo::isVirtualRegister(Hint.second))
96     return hasPhys(Hint.second);
97   return false;
98 }
99
100 int VirtRegMap::assignVirt2StackSlot(unsigned virtReg) {
101   assert(TargetRegisterInfo::isVirtualRegister(virtReg));
102   assert(Virt2StackSlotMap[virtReg] == NO_STACK_SLOT &&
103          "attempt to assign stack slot to already spilled register");
104   const TargetRegisterClass* RC = MF->getRegInfo().getRegClass(virtReg);
105   return Virt2StackSlotMap[virtReg] = createSpillSlot(RC);
106 }
107
108 void VirtRegMap::assignVirt2StackSlot(unsigned virtReg, int SS) {
109   assert(TargetRegisterInfo::isVirtualRegister(virtReg));
110   assert(Virt2StackSlotMap[virtReg] == NO_STACK_SLOT &&
111          "attempt to assign stack slot to already spilled register");
112   assert((SS >= 0 ||
113           (SS >= MF->getFrameInfo()->getObjectIndexBegin())) &&
114          "illegal fixed frame index");
115   Virt2StackSlotMap[virtReg] = SS;
116 }
117
118 void VirtRegMap::print(raw_ostream &OS, const Module*) const {
119   OS << "********** REGISTER MAP **********\n";
120   for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
121     unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
122     if (Virt2PhysMap[Reg] != (unsigned)VirtRegMap::NO_PHYS_REG) {
123       OS << '[' << PrintReg(Reg, TRI) << " -> "
124          << PrintReg(Virt2PhysMap[Reg], TRI) << "] "
125          << MRI->getRegClass(Reg)->getName() << "\n";
126     }
127   }
128
129   for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
130     unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
131     if (Virt2StackSlotMap[Reg] != VirtRegMap::NO_STACK_SLOT) {
132       OS << '[' << PrintReg(Reg, TRI) << " -> fi#" << Virt2StackSlotMap[Reg]
133          << "] " << MRI->getRegClass(Reg)->getName() << "\n";
134     }
135   }
136   OS << '\n';
137 }
138
139 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
140 void VirtRegMap::dump() const {
141   print(dbgs());
142 }
143 #endif
144
145 //===----------------------------------------------------------------------===//
146 //                              VirtRegRewriter
147 //===----------------------------------------------------------------------===//
148 //
149 // The VirtRegRewriter is the last of the register allocator passes.
150 // It rewrites virtual registers to physical registers as specified in the
151 // VirtRegMap analysis. It also updates live-in information on basic blocks
152 // according to LiveIntervals.
153 //
154 namespace {
155 class VirtRegRewriter : public MachineFunctionPass {
156   MachineFunction *MF;
157   const TargetMachine *TM;
158   const TargetRegisterInfo *TRI;
159   const TargetInstrInfo *TII;
160   MachineRegisterInfo *MRI;
161   SlotIndexes *Indexes;
162   LiveIntervals *LIS;
163   VirtRegMap *VRM;
164
165   void rewrite();
166   void addMBBLiveIns();
167 public:
168   static char ID;
169   VirtRegRewriter() : MachineFunctionPass(ID) {}
170
171   virtual void getAnalysisUsage(AnalysisUsage &AU) const;
172
173   virtual bool runOnMachineFunction(MachineFunction&);
174 };
175 } // end anonymous namespace
176
177 char &llvm::VirtRegRewriterID = VirtRegRewriter::ID;
178
179 INITIALIZE_PASS_BEGIN(VirtRegRewriter, "virtregrewriter",
180                       "Virtual Register Rewriter", false, false)
181 INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
182 INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
183 INITIALIZE_PASS_DEPENDENCY(LiveDebugVariables)
184 INITIALIZE_PASS_DEPENDENCY(LiveStacks)
185 INITIALIZE_PASS_DEPENDENCY(VirtRegMap)
186 INITIALIZE_PASS_END(VirtRegRewriter, "virtregrewriter",
187                     "Virtual Register Rewriter", false, false)
188
189 char VirtRegRewriter::ID = 0;
190
191 void VirtRegRewriter::getAnalysisUsage(AnalysisUsage &AU) const {
192   AU.setPreservesCFG();
193   AU.addRequired<LiveIntervals>();
194   AU.addRequired<SlotIndexes>();
195   AU.addPreserved<SlotIndexes>();
196   AU.addRequired<LiveDebugVariables>();
197   AU.addRequired<LiveStacks>();
198   AU.addPreserved<LiveStacks>();
199   AU.addRequired<VirtRegMap>();
200   MachineFunctionPass::getAnalysisUsage(AU);
201 }
202
203 bool VirtRegRewriter::runOnMachineFunction(MachineFunction &fn) {
204   MF = &fn;
205   TM = &MF->getTarget();
206   TRI = TM->getRegisterInfo();
207   TII = TM->getInstrInfo();
208   MRI = &MF->getRegInfo();
209   Indexes = &getAnalysis<SlotIndexes>();
210   LIS = &getAnalysis<LiveIntervals>();
211   VRM = &getAnalysis<VirtRegMap>();
212   DEBUG(dbgs() << "********** REWRITE VIRTUAL REGISTERS **********\n"
213                << "********** Function: "
214                << MF->getName() << '\n');
215   DEBUG(VRM->dump());
216
217   // Add kill flags while we still have virtual registers.
218   LIS->addKillFlags(VRM);
219
220   // Live-in lists on basic blocks are required for physregs.
221   addMBBLiveIns();
222
223   // Rewrite virtual registers.
224   rewrite();
225
226   // Write out new DBG_VALUE instructions.
227   getAnalysis<LiveDebugVariables>().emitDebugValues(VRM);
228
229   // All machine operands and other references to virtual registers have been
230   // replaced. Remove the virtual registers and release all the transient data.
231   VRM->clearAllVirt();
232   MRI->clearVirtRegs();
233   return true;
234 }
235
236 // Compute MBB live-in lists from virtual register live ranges and their
237 // assignments.
238 void VirtRegRewriter::addMBBLiveIns() {
239   SmallVector<MachineBasicBlock*, 16> LiveIn;
240   for (unsigned Idx = 0, IdxE = MRI->getNumVirtRegs(); Idx != IdxE; ++Idx) {
241     unsigned VirtReg = TargetRegisterInfo::index2VirtReg(Idx);
242     if (MRI->reg_nodbg_empty(VirtReg))
243       continue;
244     LiveInterval &LI = LIS->getInterval(VirtReg);
245     if (LI.empty() || LIS->intervalIsInOneMBB(LI))
246       continue;
247     // This is a virtual register that is live across basic blocks. Its
248     // assigned PhysReg must be marked as live-in to those blocks.
249     unsigned PhysReg = VRM->getPhys(VirtReg);
250     assert(PhysReg != VirtRegMap::NO_PHYS_REG && "Unmapped virtual register.");
251
252     // Scan the segments of LI.
253     for (LiveInterval::const_iterator I = LI.begin(), E = LI.end(); I != E;
254          ++I) {
255       if (!Indexes->findLiveInMBBs(I->start, I->end, LiveIn))
256         continue;
257       for (unsigned i = 0, e = LiveIn.size(); i != e; ++i)
258         if (!LiveIn[i]->isLiveIn(PhysReg))
259           LiveIn[i]->addLiveIn(PhysReg);
260       LiveIn.clear();
261     }
262   }
263 }
264
265 void VirtRegRewriter::rewrite() {
266   SmallVector<unsigned, 8> SuperDeads;
267   SmallVector<unsigned, 8> SuperDefs;
268   SmallVector<unsigned, 8> SuperKills;
269
270   for (MachineFunction::iterator MBBI = MF->begin(), MBBE = MF->end();
271        MBBI != MBBE; ++MBBI) {
272     DEBUG(MBBI->print(dbgs(), Indexes));
273     for (MachineBasicBlock::instr_iterator
274            MII = MBBI->instr_begin(), MIE = MBBI->instr_end(); MII != MIE;) {
275       MachineInstr *MI = MII;
276       ++MII;
277
278       for (MachineInstr::mop_iterator MOI = MI->operands_begin(),
279            MOE = MI->operands_end(); MOI != MOE; ++MOI) {
280         MachineOperand &MO = *MOI;
281
282         // Make sure MRI knows about registers clobbered by regmasks.
283         if (MO.isRegMask())
284           MRI->addPhysRegsUsedFromRegMask(MO.getRegMask());
285
286         if (!MO.isReg() || !TargetRegisterInfo::isVirtualRegister(MO.getReg()))
287           continue;
288         unsigned VirtReg = MO.getReg();
289         unsigned PhysReg = VRM->getPhys(VirtReg);
290         assert(PhysReg != VirtRegMap::NO_PHYS_REG &&
291                "Instruction uses unmapped VirtReg");
292         assert(!MRI->isReserved(PhysReg) && "Reserved register assignment");
293
294         // Preserve semantics of sub-register operands.
295         if (MO.getSubReg()) {
296           // A virtual register kill refers to the whole register, so we may
297           // have to add <imp-use,kill> operands for the super-register.  A
298           // partial redef always kills and redefines the super-register.
299           if (MO.readsReg() && (MO.isDef() || MO.isKill()))
300             SuperKills.push_back(PhysReg);
301
302           if (MO.isDef()) {
303             // The <def,undef> flag only makes sense for sub-register defs, and
304             // we are substituting a full physreg.  An <imp-use,kill> operand
305             // from the SuperKills list will represent the partial read of the
306             // super-register.
307             MO.setIsUndef(false);
308
309             // Also add implicit defs for the super-register.
310             if (MO.isDead())
311               SuperDeads.push_back(PhysReg);
312             else
313               SuperDefs.push_back(PhysReg);
314           }
315
316           // PhysReg operands cannot have subregister indexes.
317           PhysReg = TRI->getSubReg(PhysReg, MO.getSubReg());
318           assert(PhysReg && "Invalid SubReg for physical register");
319           MO.setSubReg(0);
320         }
321         // Rewrite. Note we could have used MachineOperand::substPhysReg(), but
322         // we need the inlining here.
323         MO.setReg(PhysReg);
324       }
325
326       // Add any missing super-register kills after rewriting the whole
327       // instruction.
328       while (!SuperKills.empty())
329         MI->addRegisterKilled(SuperKills.pop_back_val(), TRI, true);
330
331       while (!SuperDeads.empty())
332         MI->addRegisterDead(SuperDeads.pop_back_val(), TRI, true);
333
334       while (!SuperDefs.empty())
335         MI->addRegisterDefined(SuperDefs.pop_back_val(), TRI);
336
337       DEBUG(dbgs() << "> " << *MI);
338
339       // Finally, remove any identity copies.
340       if (MI->isIdentityCopy()) {
341         ++NumIdCopies;
342         if (MI->getNumOperands() == 2) {
343           DEBUG(dbgs() << "Deleting identity copy.\n");
344           if (Indexes)
345             Indexes->removeMachineInstrFromMaps(MI);
346           // It's safe to erase MI because MII has already been incremented.
347           MI->eraseFromParent();
348         } else {
349           // Transform identity copy to a KILL to deal with subregisters.
350           MI->setDesc(TII->get(TargetOpcode::KILL));
351           DEBUG(dbgs() << "Identity copy: " << *MI);
352         }
353       }
354     }
355   }
356
357   // Tell MRI about physical registers in use.
358   for (unsigned Reg = 1, RegE = TRI->getNumRegs(); Reg != RegE; ++Reg)
359     if (!MRI->reg_nodbg_empty(Reg))
360       MRI->setPhysRegUsed(Reg);
361 }