1 //===-- llvm/CodeGen/VirtRegMap.cpp - Virtual Register Map ----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the VirtRegMap class.
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
17 //===----------------------------------------------------------------------===//
19 #define DEBUG_TYPE "regalloc"
20 #include "VirtRegMap.h"
21 #include "LiveDebugVariables.h"
22 #include "llvm/Function.h"
23 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineFunction.h"
26 #include "llvm/CodeGen/MachineInstrBuilder.h"
27 #include "llvm/CodeGen/MachineRegisterInfo.h"
28 #include "llvm/CodeGen/Passes.h"
29 #include "llvm/Target/TargetMachine.h"
30 #include "llvm/Target/TargetInstrInfo.h"
31 #include "llvm/Target/TargetRegisterInfo.h"
32 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Support/Compiler.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include "llvm/ADT/Statistic.h"
37 #include "llvm/ADT/STLExtras.h"
41 STATISTIC(NumSpillSlots, "Number of spill slots allocated");
42 STATISTIC(NumIdCopies, "Number of identity moves eliminated after rewriting");
44 //===----------------------------------------------------------------------===//
45 // VirtRegMap implementation
46 //===----------------------------------------------------------------------===//
48 char VirtRegMap::ID = 0;
50 INITIALIZE_PASS(VirtRegMap, "virtregmap", "Virtual Register Map", false, false)
52 bool VirtRegMap::runOnMachineFunction(MachineFunction &mf) {
53 MRI = &mf.getRegInfo();
54 TII = mf.getTarget().getInstrInfo();
55 TRI = mf.getTarget().getRegisterInfo();
59 Virt2StackSlotMap.clear();
60 Virt2SplitMap.clear();
66 void VirtRegMap::grow() {
67 unsigned NumRegs = MF->getRegInfo().getNumVirtRegs();
68 Virt2PhysMap.resize(NumRegs);
69 Virt2StackSlotMap.resize(NumRegs);
70 Virt2SplitMap.resize(NumRegs);
73 unsigned VirtRegMap::createSpillSlot(const TargetRegisterClass *RC) {
74 int SS = MF->getFrameInfo()->CreateSpillStackObject(RC->getSize(),
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);
86 return (TargetRegisterInfo::isPhysicalRegister(physReg))
88 return TRI->ResolveRegAllocHint(Hint.first, physReg, *MF);
91 int VirtRegMap::assignVirt2StackSlot(unsigned virtReg) {
92 assert(TargetRegisterInfo::isVirtualRegister(virtReg));
93 assert(Virt2StackSlotMap[virtReg] == NO_STACK_SLOT &&
94 "attempt to assign stack slot to already spilled register");
95 const TargetRegisterClass* RC = MF->getRegInfo().getRegClass(virtReg);
96 return Virt2StackSlotMap[virtReg] = createSpillSlot(RC);
99 void VirtRegMap::assignVirt2StackSlot(unsigned virtReg, int SS) {
100 assert(TargetRegisterInfo::isVirtualRegister(virtReg));
101 assert(Virt2StackSlotMap[virtReg] == NO_STACK_SLOT &&
102 "attempt to assign stack slot to already spilled register");
104 (SS >= MF->getFrameInfo()->getObjectIndexBegin())) &&
105 "illegal fixed frame index");
106 Virt2StackSlotMap[virtReg] = SS;
109 void VirtRegMap::print(raw_ostream &OS, const Module*) const {
110 OS << "********** REGISTER MAP **********\n";
111 for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
112 unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
113 if (Virt2PhysMap[Reg] != (unsigned)VirtRegMap::NO_PHYS_REG) {
114 OS << '[' << PrintReg(Reg, TRI) << " -> "
115 << PrintReg(Virt2PhysMap[Reg], TRI) << "] "
116 << MRI->getRegClass(Reg)->getName() << "\n";
120 for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
121 unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
122 if (Virt2StackSlotMap[Reg] != VirtRegMap::NO_STACK_SLOT) {
123 OS << '[' << PrintReg(Reg, TRI) << " -> fi#" << Virt2StackSlotMap[Reg]
124 << "] " << MRI->getRegClass(Reg)->getName() << "\n";
130 void VirtRegMap::dump() const {
134 //===----------------------------------------------------------------------===//
136 //===----------------------------------------------------------------------===//
138 // The VirtRegRewriter is the last of the register allocator passes.
139 // It rewrites virtual registers to physical registers as specified in the
140 // VirtRegMap analysis. It also updates live-in information on basic blocks
141 // according to LiveIntervals.
144 class VirtRegRewriter : public MachineFunctionPass {
146 const TargetMachine *TM;
147 const TargetRegisterInfo *TRI;
148 const TargetInstrInfo *TII;
149 MachineRegisterInfo *MRI;
150 SlotIndexes *Indexes;
155 void addMBBLiveIns();
158 VirtRegRewriter() : MachineFunctionPass(ID) {}
160 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
162 virtual bool runOnMachineFunction(MachineFunction&);
164 } // end anonymous namespace
166 char &llvm::VirtRegRewriterID = VirtRegRewriter::ID;
168 INITIALIZE_PASS_BEGIN(VirtRegRewriter, "virtregrewriter",
169 "Virtual Register Rewriter", false, false)
170 INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
171 INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
172 INITIALIZE_PASS_DEPENDENCY(LiveDebugVariables)
173 INITIALIZE_PASS_DEPENDENCY(VirtRegMap)
174 INITIALIZE_PASS_END(VirtRegRewriter, "virtregrewriter",
175 "Virtual Register Rewriter", false, false)
177 char VirtRegRewriter::ID = 0;
179 void VirtRegRewriter::getAnalysisUsage(AnalysisUsage &AU) const {
180 AU.setPreservesCFG();
181 AU.addRequired<LiveIntervals>();
182 AU.addRequired<SlotIndexes>();
183 AU.addPreserved<SlotIndexes>();
184 AU.addRequired<LiveDebugVariables>();
185 AU.addRequired<VirtRegMap>();
186 MachineFunctionPass::getAnalysisUsage(AU);
189 bool VirtRegRewriter::runOnMachineFunction(MachineFunction &fn) {
191 TM = &MF->getTarget();
192 TRI = TM->getRegisterInfo();
193 TII = TM->getInstrInfo();
194 MRI = &MF->getRegInfo();
195 Indexes = &getAnalysis<SlotIndexes>();
196 LIS = &getAnalysis<LiveIntervals>();
197 VRM = &getAnalysis<VirtRegMap>();
198 DEBUG(dbgs() << "********** REWRITE VIRTUAL REGISTERS **********\n"
199 << "********** Function: "
200 << MF->getFunction()->getName() << '\n');
203 // Add kill flags while we still have virtual registers.
206 // Live-in lists on basic blocks are required for physregs.
209 // Rewrite virtual registers.
212 // Write out new DBG_VALUE instructions.
213 getAnalysis<LiveDebugVariables>().emitDebugValues(VRM);
215 // All machine operands and other references to virtual registers have been
216 // replaced. Remove the virtual registers and release all the transient data.
218 MRI->clearVirtRegs();
222 // Compute MBB live-in lists from virtual register live ranges and their
224 void VirtRegRewriter::addMBBLiveIns() {
225 SmallVector<MachineBasicBlock*, 16> LiveIn;
226 for (unsigned Idx = 0, IdxE = MRI->getNumVirtRegs(); Idx != IdxE; ++Idx) {
227 unsigned VirtReg = TargetRegisterInfo::index2VirtReg(Idx);
228 if (MRI->reg_nodbg_empty(VirtReg))
230 LiveInterval &LI = LIS->getInterval(VirtReg);
231 if (LI.empty() || LIS->intervalIsInOneMBB(LI))
233 // This is a virtual register that is live across basic blocks. Its
234 // assigned PhysReg must be marked as live-in to those blocks.
235 unsigned PhysReg = VRM->getPhys(VirtReg);
236 assert(PhysReg != VirtRegMap::NO_PHYS_REG && "Unmapped virtual register.");
238 // Scan the segments of LI.
239 for (LiveInterval::const_iterator I = LI.begin(), E = LI.end(); I != E;
241 if (!Indexes->findLiveInMBBs(I->start, I->end, LiveIn))
243 for (unsigned i = 0, e = LiveIn.size(); i != e; ++i)
244 if (!LiveIn[i]->isLiveIn(PhysReg))
245 LiveIn[i]->addLiveIn(PhysReg);
251 void VirtRegRewriter::rewrite() {
252 SmallVector<unsigned, 8> SuperDeads;
253 SmallVector<unsigned, 8> SuperDefs;
254 SmallVector<unsigned, 8> SuperKills;
256 BitVector Reserved = TRI->getReservedRegs(*MF);
259 for (MachineFunction::iterator MBBI = MF->begin(), MBBE = MF->end();
260 MBBI != MBBE; ++MBBI) {
261 DEBUG(MBBI->print(dbgs(), Indexes));
262 for (MachineBasicBlock::instr_iterator
263 MII = MBBI->instr_begin(), MIE = MBBI->instr_end(); MII != MIE;) {
264 MachineInstr *MI = MII;
267 for (MachineInstr::mop_iterator MOI = MI->operands_begin(),
268 MOE = MI->operands_end(); MOI != MOE; ++MOI) {
269 MachineOperand &MO = *MOI;
271 // Make sure MRI knows about registers clobbered by regmasks.
273 MRI->addPhysRegsUsedFromRegMask(MO.getRegMask());
275 if (!MO.isReg() || !TargetRegisterInfo::isVirtualRegister(MO.getReg()))
277 unsigned VirtReg = MO.getReg();
278 unsigned PhysReg = VRM->getPhys(VirtReg);
279 assert(PhysReg != VirtRegMap::NO_PHYS_REG &&
280 "Instruction uses unmapped VirtReg");
281 assert(!Reserved.test(PhysReg) && "Reserved register assignment");
283 // Preserve semantics of sub-register operands.
284 if (MO.getSubReg()) {
285 // A virtual register kill refers to the whole register, so we may
286 // have to add <imp-use,kill> operands for the super-register. A
287 // partial redef always kills and redefines the super-register.
288 if (MO.readsReg() && (MO.isDef() || MO.isKill()))
289 SuperKills.push_back(PhysReg);
292 // The <def,undef> flag only makes sense for sub-register defs, and
293 // we are substituting a full physreg. An <imp-use,kill> operand
294 // from the SuperKills list will represent the partial read of the
296 MO.setIsUndef(false);
298 // Also add implicit defs for the super-register.
300 SuperDeads.push_back(PhysReg);
302 SuperDefs.push_back(PhysReg);
305 // PhysReg operands cannot have subregister indexes.
306 PhysReg = TRI->getSubReg(PhysReg, MO.getSubReg());
307 assert(PhysReg && "Invalid SubReg for physical register");
310 // Rewrite. Note we could have used MachineOperand::substPhysReg(), but
311 // we need the inlining here.
315 // Add any missing super-register kills after rewriting the whole
317 while (!SuperKills.empty())
318 MI->addRegisterKilled(SuperKills.pop_back_val(), TRI, true);
320 while (!SuperDeads.empty())
321 MI->addRegisterDead(SuperDeads.pop_back_val(), TRI, true);
323 while (!SuperDefs.empty())
324 MI->addRegisterDefined(SuperDefs.pop_back_val(), TRI);
326 DEBUG(dbgs() << "> " << *MI);
328 // Finally, remove any identity copies.
329 if (MI->isIdentityCopy()) {
331 if (MI->getNumOperands() == 2) {
332 DEBUG(dbgs() << "Deleting identity copy.\n");
334 Indexes->removeMachineInstrFromMaps(MI);
335 // It's safe to erase MI because MII has already been incremented.
336 MI->eraseFromParent();
338 // Transform identity copy to a KILL to deal with subregisters.
339 MI->setDesc(TII->get(TargetOpcode::KILL));
340 DEBUG(dbgs() << "Identity copy: " << *MI);
346 // Tell MRI about physical registers in use.
347 for (unsigned Reg = 1, RegE = TRI->getNumRegs(); Reg != RegE; ++Reg)
348 if (!MRI->reg_nodbg_empty(Reg))
349 MRI->setPhysRegUsed(Reg);