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 #include "llvm/CodeGen/VirtRegMap.h"
20 #include "LiveDebugVariables.h"
21 #include "llvm/ADT/STLExtras.h"
22 #include "llvm/ADT/SparseSet.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/IR/Function.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/Target/TargetInstrInfo.h"
37 #include "llvm/Target/TargetMachine.h"
38 #include "llvm/Target/TargetRegisterInfo.h"
39 #include "llvm/Target/TargetSubtargetInfo.h"
43 #define DEBUG_TYPE "regalloc"
45 STATISTIC(NumSpillSlots, "Number of spill slots allocated");
46 STATISTIC(NumIdCopies, "Number of identity moves eliminated after rewriting");
48 //===----------------------------------------------------------------------===//
49 // VirtRegMap implementation
50 //===----------------------------------------------------------------------===//
52 char VirtRegMap::ID = 0;
54 INITIALIZE_PASS(VirtRegMap, "virtregmap", "Virtual Register Map", false, false)
56 bool VirtRegMap::runOnMachineFunction(MachineFunction &mf) {
57 MRI = &mf.getRegInfo();
58 TII = mf.getSubtarget().getInstrInfo();
59 TRI = mf.getSubtarget().getRegisterInfo();
63 Virt2StackSlotMap.clear();
64 Virt2SplitMap.clear();
70 void VirtRegMap::grow() {
71 unsigned NumRegs = MF->getRegInfo().getNumVirtRegs();
72 Virt2PhysMap.resize(NumRegs);
73 Virt2StackSlotMap.resize(NumRegs);
74 Virt2SplitMap.resize(NumRegs);
77 unsigned VirtRegMap::createSpillSlot(const TargetRegisterClass *RC) {
78 int SS = MF->getFrameInfo()->CreateSpillStackObject(RC->getSize(),
84 bool VirtRegMap::hasPreferredPhys(unsigned VirtReg) {
85 unsigned Hint = MRI->getSimpleHint(VirtReg);
88 if (TargetRegisterInfo::isVirtualRegister(Hint))
90 return getPhys(VirtReg) == Hint;
93 bool VirtRegMap::hasKnownPreference(unsigned VirtReg) {
94 std::pair<unsigned, unsigned> Hint = MRI->getRegAllocationHint(VirtReg);
95 if (TargetRegisterInfo::isPhysicalRegister(Hint.second))
97 if (TargetRegisterInfo::isVirtualRegister(Hint.second))
98 return hasPhys(Hint.second);
102 int VirtRegMap::assignVirt2StackSlot(unsigned virtReg) {
103 assert(TargetRegisterInfo::isVirtualRegister(virtReg));
104 assert(Virt2StackSlotMap[virtReg] == NO_STACK_SLOT &&
105 "attempt to assign stack slot to already spilled register");
106 const TargetRegisterClass* RC = MF->getRegInfo().getRegClass(virtReg);
107 return Virt2StackSlotMap[virtReg] = createSpillSlot(RC);
110 void VirtRegMap::assignVirt2StackSlot(unsigned virtReg, int SS) {
111 assert(TargetRegisterInfo::isVirtualRegister(virtReg));
112 assert(Virt2StackSlotMap[virtReg] == NO_STACK_SLOT &&
113 "attempt to assign stack slot to already spilled register");
115 (SS >= MF->getFrameInfo()->getObjectIndexBegin())) &&
116 "illegal fixed frame index");
117 Virt2StackSlotMap[virtReg] = SS;
120 void VirtRegMap::print(raw_ostream &OS, const Module*) const {
121 OS << "********** REGISTER MAP **********\n";
122 for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
123 unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
124 if (Virt2PhysMap[Reg] != (unsigned)VirtRegMap::NO_PHYS_REG) {
125 OS << '[' << PrintReg(Reg, TRI) << " -> "
126 << PrintReg(Virt2PhysMap[Reg], TRI) << "] "
127 << TRI->getRegClassName(MRI->getRegClass(Reg)) << "\n";
131 for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
132 unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
133 if (Virt2StackSlotMap[Reg] != VirtRegMap::NO_STACK_SLOT) {
134 OS << '[' << PrintReg(Reg, TRI) << " -> fi#" << Virt2StackSlotMap[Reg]
135 << "] " << TRI->getRegClassName(MRI->getRegClass(Reg)) << "\n";
141 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
142 void VirtRegMap::dump() const {
147 //===----------------------------------------------------------------------===//
149 //===----------------------------------------------------------------------===//
151 // The VirtRegRewriter is the last of the register allocator passes.
152 // It rewrites virtual registers to physical registers as specified in the
153 // VirtRegMap analysis. It also updates live-in information on basic blocks
154 // according to LiveIntervals.
157 class VirtRegRewriter : public MachineFunctionPass {
159 const TargetMachine *TM;
160 const TargetRegisterInfo *TRI;
161 const TargetInstrInfo *TII;
162 MachineRegisterInfo *MRI;
163 SlotIndexes *Indexes;
168 void addMBBLiveIns();
169 bool readsUndefSubreg(const MachineOperand &MO) const;
170 void addLiveInsForSubRanges(const LiveInterval &LI, unsigned PhysReg) const;
174 VirtRegRewriter() : MachineFunctionPass(ID) {}
176 void getAnalysisUsage(AnalysisUsage &AU) const override;
178 bool runOnMachineFunction(MachineFunction&) override;
180 } // end anonymous namespace
182 char &llvm::VirtRegRewriterID = VirtRegRewriter::ID;
184 INITIALIZE_PASS_BEGIN(VirtRegRewriter, "virtregrewriter",
185 "Virtual Register Rewriter", false, false)
186 INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
187 INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
188 INITIALIZE_PASS_DEPENDENCY(LiveDebugVariables)
189 INITIALIZE_PASS_DEPENDENCY(LiveStacks)
190 INITIALIZE_PASS_DEPENDENCY(VirtRegMap)
191 INITIALIZE_PASS_END(VirtRegRewriter, "virtregrewriter",
192 "Virtual Register Rewriter", false, false)
194 char VirtRegRewriter::ID = 0;
196 void VirtRegRewriter::getAnalysisUsage(AnalysisUsage &AU) const {
197 AU.setPreservesCFG();
198 AU.addRequired<LiveIntervals>();
199 AU.addRequired<SlotIndexes>();
200 AU.addPreserved<SlotIndexes>();
201 AU.addRequired<LiveDebugVariables>();
202 AU.addRequired<LiveStacks>();
203 AU.addPreserved<LiveStacks>();
204 AU.addRequired<VirtRegMap>();
205 MachineFunctionPass::getAnalysisUsage(AU);
208 bool VirtRegRewriter::runOnMachineFunction(MachineFunction &fn) {
210 TM = &MF->getTarget();
211 TRI = MF->getSubtarget().getRegisterInfo();
212 TII = MF->getSubtarget().getInstrInfo();
213 MRI = &MF->getRegInfo();
214 Indexes = &getAnalysis<SlotIndexes>();
215 LIS = &getAnalysis<LiveIntervals>();
216 VRM = &getAnalysis<VirtRegMap>();
217 DEBUG(dbgs() << "********** REWRITE VIRTUAL REGISTERS **********\n"
218 << "********** Function: "
219 << MF->getName() << '\n');
222 // Add kill flags while we still have virtual registers.
223 LIS->addKillFlags(VRM);
225 // Live-in lists on basic blocks are required for physregs.
228 // Rewrite virtual registers.
231 // Write out new DBG_VALUE instructions.
232 getAnalysis<LiveDebugVariables>().emitDebugValues(VRM);
234 // All machine operands and other references to virtual registers have been
235 // replaced. Remove the virtual registers and release all the transient data.
237 MRI->clearVirtRegs();
241 void VirtRegRewriter::addLiveInsForSubRanges(const LiveInterval &LI,
242 unsigned PhysReg) const {
244 assert(LI.hasSubRanges());
246 typedef std::pair<const LiveInterval::SubRange *,
247 LiveInterval::const_iterator> SubRangeIteratorPair;
248 SmallVector<SubRangeIteratorPair, 4> SubRanges;
251 for (const LiveInterval::SubRange &SR : LI.subranges()) {
252 SubRanges.push_back(std::make_pair(&SR, SR.begin()));
253 if (!First.isValid() || SR.segments.front().start < First)
254 First = SR.segments.front().start;
255 if (!Last.isValid() || SR.segments.back().end > Last)
256 Last = SR.segments.back().end;
259 // Check all mbb start positions between First and Last while
260 // simulatenously advancing an iterator for each subrange.
261 for (SlotIndexes::MBBIndexIterator MBBI = Indexes->findMBBIndex(First);
262 MBBI != Indexes->MBBIndexEnd() && MBBI->first <= Last; ++MBBI) {
263 SlotIndex MBBBegin = MBBI->first;
264 // Advance all subrange iterators so that their end position is just
265 // behind MBBBegin (or the iterator is at the end).
266 unsigned LaneMask = 0;
267 for (auto &RangeIterPair : SubRanges) {
268 const LiveInterval::SubRange *SR = RangeIterPair.first;
269 LiveInterval::const_iterator &SRI = RangeIterPair.second;
270 while (SRI != SR->end() && SRI->end <= MBBBegin)
272 if (SRI == SR->end())
274 if (SRI->start <= MBBBegin)
275 LaneMask |= SR->LaneMask;
279 MachineBasicBlock *MBB = MBBI->second;
280 for (MCSubRegIndexIterator SR(PhysReg, TRI); SR.isValid(); ++SR) {
281 unsigned SubReg = SR.getSubReg();
282 unsigned SubRegIndex = SR.getSubRegIndex();
283 unsigned SubRegLaneMask = TRI->getSubRegIndexLaneMask(SubRegIndex);
284 if ((SubRegLaneMask & LaneMask) != 0)
285 MBB->addLiveIn(SubReg);
290 // Compute MBB live-in lists from virtual register live ranges and their
292 void VirtRegRewriter::addMBBLiveIns() {
293 for (unsigned Idx = 0, IdxE = MRI->getNumVirtRegs(); Idx != IdxE; ++Idx) {
294 unsigned VirtReg = TargetRegisterInfo::index2VirtReg(Idx);
295 if (MRI->reg_nodbg_empty(VirtReg))
297 LiveInterval &LI = LIS->getInterval(VirtReg);
298 if (LI.empty() || LIS->intervalIsInOneMBB(LI))
300 // This is a virtual register that is live across basic blocks. Its
301 // assigned PhysReg must be marked as live-in to those blocks.
302 unsigned PhysReg = VRM->getPhys(VirtReg);
303 assert(PhysReg != VirtRegMap::NO_PHYS_REG && "Unmapped virtual register.");
305 if (LI.hasSubRanges()) {
306 addLiveInsForSubRanges(LI, PhysReg);
308 // Go over MBB begin positions and see if we have segments covering them.
309 // The following works because segments and the MBBIndex list are both
310 // sorted by slot indexes.
311 SlotIndexes::MBBIndexIterator I = Indexes->MBBIndexBegin();
312 for (const auto &Seg : LI) {
313 I = Indexes->advanceMBBIndex(I, Seg.start);
314 for (; I != Indexes->MBBIndexEnd() && I->first < Seg.end; ++I) {
315 MachineBasicBlock *MBB = I->second;
316 MBB->addLiveIn(PhysReg);
322 // Sort and unique MBB LiveIns as we've not checked if SubReg/PhysReg were in
323 // each MBB's LiveIns set before calling addLiveIn on them.
324 for (MachineBasicBlock &MBB : *MF)
325 MBB.sortUniqueLiveIns();
328 /// Returns true if the given machine operand \p MO only reads undefined lanes.
329 /// The function only works for use operands with a subregister set.
330 bool VirtRegRewriter::readsUndefSubreg(const MachineOperand &MO) const {
331 // Shortcut if the operand is already marked undef.
335 unsigned Reg = MO.getReg();
336 const LiveInterval &LI = LIS->getInterval(Reg);
337 const MachineInstr &MI = *MO.getParent();
338 SlotIndex BaseIndex = LIS->getInstructionIndex(&MI);
339 // This code is only meant to handle reading undefined subregisters which
340 // we couldn't properly detect before.
341 assert(LI.liveAt(BaseIndex) &&
342 "Reads of completely dead register should be marked undef already");
343 unsigned SubRegIdx = MO.getSubReg();
344 unsigned UseMask = TRI->getSubRegIndexLaneMask(SubRegIdx);
345 // See if any of the relevant subregister liveranges is defined at this point.
346 for (const LiveInterval::SubRange &SR : LI.subranges()) {
347 if ((SR.LaneMask & UseMask) != 0 && SR.liveAt(BaseIndex))
353 void VirtRegRewriter::rewrite() {
354 bool NoSubRegLiveness = !MRI->subRegLivenessEnabled();
355 SmallVector<unsigned, 8> SuperDeads;
356 SmallVector<unsigned, 8> SuperDefs;
357 SmallVector<unsigned, 8> SuperKills;
359 for (MachineFunction::iterator MBBI = MF->begin(), MBBE = MF->end();
360 MBBI != MBBE; ++MBBI) {
361 DEBUG(MBBI->print(dbgs(), Indexes));
362 for (MachineBasicBlock::instr_iterator
363 MII = MBBI->instr_begin(), MIE = MBBI->instr_end(); MII != MIE;) {
364 MachineInstr *MI = MII;
367 for (MachineInstr::mop_iterator MOI = MI->operands_begin(),
368 MOE = MI->operands_end(); MOI != MOE; ++MOI) {
369 MachineOperand &MO = *MOI;
371 // Make sure MRI knows about registers clobbered by regmasks.
373 MRI->addPhysRegsUsedFromRegMask(MO.getRegMask());
375 if (!MO.isReg() || !TargetRegisterInfo::isVirtualRegister(MO.getReg()))
377 unsigned VirtReg = MO.getReg();
378 unsigned PhysReg = VRM->getPhys(VirtReg);
379 assert(PhysReg != VirtRegMap::NO_PHYS_REG &&
380 "Instruction uses unmapped VirtReg");
381 assert(!MRI->isReserved(PhysReg) && "Reserved register assignment");
383 // Preserve semantics of sub-register operands.
384 unsigned SubReg = MO.getSubReg();
386 if (NoSubRegLiveness) {
387 // A virtual register kill refers to the whole register, so we may
388 // have to add <imp-use,kill> operands for the super-register. A
389 // partial redef always kills and redefines the super-register.
390 if (MO.readsReg() && (MO.isDef() || MO.isKill()))
391 SuperKills.push_back(PhysReg);
394 // Also add implicit defs for the super-register.
396 SuperDeads.push_back(PhysReg);
398 SuperDefs.push_back(PhysReg);
402 if (readsUndefSubreg(MO))
403 // We need to add an <undef> flag if the subregister is
404 // completely undefined (and we are not adding super-register
407 } else if (!MO.isDead()) {
409 // Things get tricky when we ran out of lane mask bits and
410 // merged multiple lanes into the overflow bit: In this case
411 // our subregister liveness tracking isn't precise and we can't
412 // know what subregister parts are undefined, fall back to the
413 // implicit super-register def then.
414 unsigned LaneMask = TRI->getSubRegIndexLaneMask(SubReg);
415 if (TargetRegisterInfo::isImpreciseLaneMask(LaneMask))
416 SuperDefs.push_back(PhysReg);
420 // The <def,undef> flag only makes sense for sub-register defs, and
421 // we are substituting a full physreg. An <imp-use,kill> operand
422 // from the SuperKills list will represent the partial read of the
425 MO.setIsUndef(false);
427 // PhysReg operands cannot have subregister indexes.
428 PhysReg = TRI->getSubReg(PhysReg, SubReg);
429 assert(PhysReg && "Invalid SubReg for physical register");
432 // Rewrite. Note we could have used MachineOperand::substPhysReg(), but
433 // we need the inlining here.
437 // Add any missing super-register kills after rewriting the whole
439 while (!SuperKills.empty())
440 MI->addRegisterKilled(SuperKills.pop_back_val(), TRI, true);
442 while (!SuperDeads.empty())
443 MI->addRegisterDead(SuperDeads.pop_back_val(), TRI, true);
445 while (!SuperDefs.empty())
446 MI->addRegisterDefined(SuperDefs.pop_back_val(), TRI);
448 DEBUG(dbgs() << "> " << *MI);
450 // Finally, remove any identity copies.
451 if (MI->isIdentityCopy()) {
453 DEBUG(dbgs() << "Deleting identity copy.\n");
455 Indexes->removeMachineInstrFromMaps(MI);
456 // It's safe to erase MI because MII has already been incremented.
457 MI->eraseFromParent();