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 "llvm/CodeGen/VirtRegMap.h"
21 #include "LiveDebugVariables.h"
22 #include "llvm/ADT/STLExtras.h"
23 #include "llvm/ADT/SparseSet.h"
24 #include "llvm/ADT/Statistic.h"
25 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
26 #include "llvm/CodeGen/LiveStackAnalysis.h"
27 #include "llvm/CodeGen/MachineFrameInfo.h"
28 #include "llvm/CodeGen/MachineFunction.h"
29 #include "llvm/CodeGen/MachineInstrBuilder.h"
30 #include "llvm/CodeGen/MachineRegisterInfo.h"
31 #include "llvm/CodeGen/Passes.h"
32 #include "llvm/IR/Function.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/Compiler.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/raw_ostream.h"
37 #include "llvm/Target/TargetInstrInfo.h"
38 #include "llvm/Target/TargetMachine.h"
39 #include "llvm/Target/TargetRegisterInfo.h"
43 STATISTIC(NumSpillSlots, "Number of spill slots allocated");
44 STATISTIC(NumIdCopies, "Number of identity moves eliminated after rewriting");
46 //===----------------------------------------------------------------------===//
47 // VirtRegMap implementation
48 //===----------------------------------------------------------------------===//
50 char VirtRegMap::ID = 0;
52 INITIALIZE_PASS(VirtRegMap, "virtregmap", "Virtual Register Map", false, false)
54 bool VirtRegMap::runOnMachineFunction(MachineFunction &mf) {
55 MRI = &mf.getRegInfo();
56 TII = mf.getTarget().getInstrInfo();
57 TRI = mf.getTarget().getRegisterInfo();
61 Virt2StackSlotMap.clear();
62 Virt2SplitMap.clear();
68 void VirtRegMap::grow() {
69 unsigned NumRegs = MF->getRegInfo().getNumVirtRegs();
70 Virt2PhysMap.resize(NumRegs);
71 Virt2StackSlotMap.resize(NumRegs);
72 Virt2SplitMap.resize(NumRegs);
75 unsigned VirtRegMap::createSpillSlot(const TargetRegisterClass *RC) {
76 int SS = MF->getFrameInfo()->CreateSpillStackObject(RC->getSize(),
82 bool VirtRegMap::hasPreferredPhys(unsigned VirtReg) {
83 unsigned Hint = MRI->getSimpleHint(VirtReg);
86 if (TargetRegisterInfo::isVirtualRegister(Hint))
88 return getPhys(VirtReg) == Hint;
91 bool VirtRegMap::hasKnownPreference(unsigned VirtReg) {
92 std::pair<unsigned, unsigned> Hint = MRI->getRegAllocationHint(VirtReg);
93 if (TargetRegisterInfo::isPhysicalRegister(Hint.second))
95 if (TargetRegisterInfo::isVirtualRegister(Hint.second))
96 return hasPhys(Hint.second);
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);
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");
113 (SS >= MF->getFrameInfo()->getObjectIndexBegin())) &&
114 "illegal fixed frame index");
115 Virt2StackSlotMap[virtReg] = SS;
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";
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";
139 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
140 void VirtRegMap::dump() const {
145 //===----------------------------------------------------------------------===//
147 //===----------------------------------------------------------------------===//
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.
155 class VirtRegRewriter : public MachineFunctionPass {
157 const TargetMachine *TM;
158 const TargetRegisterInfo *TRI;
159 const TargetInstrInfo *TII;
160 MachineRegisterInfo *MRI;
161 SlotIndexes *Indexes;
164 SparseSet<unsigned> PhysRegs;
167 void addMBBLiveIns();
170 VirtRegRewriter() : MachineFunctionPass(ID) {}
172 void getAnalysisUsage(AnalysisUsage &AU) const override;
174 bool runOnMachineFunction(MachineFunction&) override;
176 } // end anonymous namespace
178 char &llvm::VirtRegRewriterID = VirtRegRewriter::ID;
180 INITIALIZE_PASS_BEGIN(VirtRegRewriter, "virtregrewriter",
181 "Virtual Register Rewriter", false, false)
182 INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
183 INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
184 INITIALIZE_PASS_DEPENDENCY(LiveDebugVariables)
185 INITIALIZE_PASS_DEPENDENCY(LiveStacks)
186 INITIALIZE_PASS_DEPENDENCY(VirtRegMap)
187 INITIALIZE_PASS_END(VirtRegRewriter, "virtregrewriter",
188 "Virtual Register Rewriter", false, false)
190 char VirtRegRewriter::ID = 0;
192 void VirtRegRewriter::getAnalysisUsage(AnalysisUsage &AU) const {
193 AU.setPreservesCFG();
194 AU.addRequired<LiveIntervals>();
195 AU.addRequired<SlotIndexes>();
196 AU.addPreserved<SlotIndexes>();
197 AU.addRequired<LiveDebugVariables>();
198 AU.addRequired<LiveStacks>();
199 AU.addPreserved<LiveStacks>();
200 AU.addRequired<VirtRegMap>();
201 MachineFunctionPass::getAnalysisUsage(AU);
204 bool VirtRegRewriter::runOnMachineFunction(MachineFunction &fn) {
206 TM = &MF->getTarget();
207 TRI = TM->getRegisterInfo();
208 TII = TM->getInstrInfo();
209 MRI = &MF->getRegInfo();
210 Indexes = &getAnalysis<SlotIndexes>();
211 LIS = &getAnalysis<LiveIntervals>();
212 VRM = &getAnalysis<VirtRegMap>();
213 DEBUG(dbgs() << "********** REWRITE VIRTUAL REGISTERS **********\n"
214 << "********** Function: "
215 << MF->getName() << '\n');
218 // Add kill flags while we still have virtual registers.
219 LIS->addKillFlags(VRM);
221 // Live-in lists on basic blocks are required for physregs.
224 // Rewrite virtual registers.
227 // Write out new DBG_VALUE instructions.
228 getAnalysis<LiveDebugVariables>().emitDebugValues(VRM);
230 // All machine operands and other references to virtual registers have been
231 // replaced. Remove the virtual registers and release all the transient data.
233 MRI->clearVirtRegs();
237 // Compute MBB live-in lists from virtual register live ranges and their
239 void VirtRegRewriter::addMBBLiveIns() {
240 SmallVector<MachineBasicBlock*, 16> LiveIn;
241 for (unsigned Idx = 0, IdxE = MRI->getNumVirtRegs(); Idx != IdxE; ++Idx) {
242 unsigned VirtReg = TargetRegisterInfo::index2VirtReg(Idx);
243 if (MRI->reg_nodbg_empty(VirtReg))
245 LiveInterval &LI = LIS->getInterval(VirtReg);
246 if (LI.empty() || LIS->intervalIsInOneMBB(LI))
248 // This is a virtual register that is live across basic blocks. Its
249 // assigned PhysReg must be marked as live-in to those blocks.
250 unsigned PhysReg = VRM->getPhys(VirtReg);
251 assert(PhysReg != VirtRegMap::NO_PHYS_REG && "Unmapped virtual register.");
253 // Scan the segments of LI.
254 for (LiveInterval::const_iterator I = LI.begin(), E = LI.end(); I != E;
256 if (!Indexes->findLiveInMBBs(I->start, I->end, LiveIn))
258 for (unsigned i = 0, e = LiveIn.size(); i != e; ++i)
259 if (!LiveIn[i]->isLiveIn(PhysReg))
260 LiveIn[i]->addLiveIn(PhysReg);
266 void VirtRegRewriter::rewrite() {
267 SmallVector<unsigned, 8> SuperDeads;
268 SmallVector<unsigned, 8> SuperDefs;
269 SmallVector<unsigned, 8> SuperKills;
270 SmallPtrSet<const MachineInstr *, 4> NoReturnInsts;
272 // Here we have a SparseSet to hold which PhysRegs are actually encountered
273 // in the MF we are about to iterate over so that later when we call
274 // setPhysRegUsed, we are only doing it for physRegs that were actually found
275 // in the program and not for all of the possible physRegs for the given
276 // target architecture. If the target has a lot of physRegs, then for a small
277 // program there will be a significant compile time reduction here.
279 PhysRegs.setUniverse(TRI->getNumRegs());
281 // The function with uwtable should guarantee that the stack unwinder
282 // can unwind the stack to the previous frame. Thus, we can't apply the
283 // noreturn optimization if the caller function has uwtable attribute.
284 bool HasUWTable = MF->getFunction()->hasFnAttribute(Attribute::UWTable);
286 for (MachineFunction::iterator MBBI = MF->begin(), MBBE = MF->end();
287 MBBI != MBBE; ++MBBI) {
288 DEBUG(MBBI->print(dbgs(), Indexes));
289 bool IsExitBB = MBBI->succ_empty();
290 for (MachineBasicBlock::instr_iterator
291 MII = MBBI->instr_begin(), MIE = MBBI->instr_end(); MII != MIE;) {
292 MachineInstr *MI = MII;
295 // Check if this instruction is a call to a noreturn function. If this
296 // is a call to noreturn function and we don't need the stack unwinding
297 // functionality (i.e. this function does not have uwtable attribute and
298 // the callee function has the nounwind attribute), then we can ignore
299 // the definitions set by this instruction.
300 if (!HasUWTable && IsExitBB && MI->isCall()) {
301 for (MachineInstr::mop_iterator MOI = MI->operands_begin(),
302 MOE = MI->operands_end(); MOI != MOE; ++MOI) {
303 MachineOperand &MO = *MOI;
306 const Function *Func = dyn_cast<Function>(MO.getGlobal());
307 if (!Func || !Func->hasFnAttribute(Attribute::NoReturn) ||
308 // We need to keep correct unwind information
309 // even if the function will not return, since the
310 // runtime may need it.
311 !Func->hasFnAttribute(Attribute::NoUnwind))
313 NoReturnInsts.insert(MI);
318 for (MachineInstr::mop_iterator MOI = MI->operands_begin(),
319 MOE = MI->operands_end(); MOI != MOE; ++MOI) {
320 MachineOperand &MO = *MOI;
322 // Make sure MRI knows about registers clobbered by regmasks.
324 MRI->addPhysRegsUsedFromRegMask(MO.getRegMask());
326 // If we encounter a VirtReg or PhysReg then get at the PhysReg and add
327 // it to the physreg bitset. Later we use only the PhysRegs that were
328 // actually encountered in the MF to populate the MRI's used physregs.
329 if (MO.isReg() && MO.getReg())
331 TargetRegisterInfo::isVirtualRegister(MO.getReg()) ?
332 VRM->getPhys(MO.getReg()) :
335 if (!MO.isReg() || !TargetRegisterInfo::isVirtualRegister(MO.getReg()))
337 unsigned VirtReg = MO.getReg();
338 unsigned PhysReg = VRM->getPhys(VirtReg);
339 assert(PhysReg != VirtRegMap::NO_PHYS_REG &&
340 "Instruction uses unmapped VirtReg");
341 assert(!MRI->isReserved(PhysReg) && "Reserved register assignment");
343 // Preserve semantics of sub-register operands.
344 if (MO.getSubReg()) {
345 // A virtual register kill refers to the whole register, so we may
346 // have to add <imp-use,kill> operands for the super-register. A
347 // partial redef always kills and redefines the super-register.
348 if (MO.readsReg() && (MO.isDef() || MO.isKill()))
349 SuperKills.push_back(PhysReg);
352 // The <def,undef> flag only makes sense for sub-register defs, and
353 // we are substituting a full physreg. An <imp-use,kill> operand
354 // from the SuperKills list will represent the partial read of the
356 MO.setIsUndef(false);
358 // Also add implicit defs for the super-register.
360 SuperDeads.push_back(PhysReg);
362 SuperDefs.push_back(PhysReg);
365 // PhysReg operands cannot have subregister indexes.
366 PhysReg = TRI->getSubReg(PhysReg, MO.getSubReg());
367 assert(PhysReg && "Invalid SubReg for physical register");
370 // Rewrite. Note we could have used MachineOperand::substPhysReg(), but
371 // we need the inlining here.
375 // Add any missing super-register kills after rewriting the whole
377 while (!SuperKills.empty())
378 MI->addRegisterKilled(SuperKills.pop_back_val(), TRI, true);
380 while (!SuperDeads.empty())
381 MI->addRegisterDead(SuperDeads.pop_back_val(), TRI, true);
383 while (!SuperDefs.empty())
384 MI->addRegisterDefined(SuperDefs.pop_back_val(), TRI);
386 DEBUG(dbgs() << "> " << *MI);
388 // Finally, remove any identity copies.
389 if (MI->isIdentityCopy()) {
391 if (MI->getNumOperands() == 2) {
392 DEBUG(dbgs() << "Deleting identity copy.\n");
394 Indexes->removeMachineInstrFromMaps(MI);
395 // It's safe to erase MI because MII has already been incremented.
396 MI->eraseFromParent();
398 // Transform identity copy to a KILL to deal with subregisters.
399 MI->setDesc(TII->get(TargetOpcode::KILL));
400 DEBUG(dbgs() << "Identity copy: " << *MI);
406 // Tell MRI about physical registers in use.
407 if (NoReturnInsts.empty()) {
408 for (SparseSet<unsigned>::iterator
409 RegI = PhysRegs.begin(), E = PhysRegs.end(); RegI != E; ++RegI)
410 if (!MRI->reg_nodbg_empty(*RegI))
411 MRI->setPhysRegUsed(*RegI);
413 for (SparseSet<unsigned>::iterator
414 I = PhysRegs.begin(), E = PhysRegs.end(); I != E; ++I) {
416 if (MRI->reg_nodbg_empty(Reg))
418 // Check if this register has a use that will impact the rest of the
419 // code. Uses in debug and noreturn instructions do not impact the
421 for (MachineRegisterInfo::reg_nodbg_iterator It =
422 MRI->reg_nodbg_begin(Reg),
423 EndIt = MRI->reg_nodbg_end(); It != EndIt; ++It) {
424 if (!NoReturnInsts.count(&(*It))) {
425 MRI->setPhysRegUsed(Reg);