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/Statistic.h"
23 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
24 #include "llvm/CodeGen/LiveStackAnalysis.h"
25 #include "llvm/CodeGen/MachineFrameInfo.h"
26 #include "llvm/CodeGen/MachineFunction.h"
27 #include "llvm/CodeGen/MachineInstrBuilder.h"
28 #include "llvm/CodeGen/MachineRegisterInfo.h"
29 #include "llvm/CodeGen/Passes.h"
30 #include "llvm/IR/Function.h"
31 #include "llvm/Support/Compiler.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include "llvm/Target/TargetInstrInfo.h"
35 #include "llvm/Target/TargetMachine.h"
36 #include "llvm/Target/TargetRegisterInfo.h"
37 #include "llvm/Target/TargetSubtargetInfo.h"
41 #define DEBUG_TYPE "regalloc"
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.getSubtarget().getInstrInfo();
57 TRI = mf.getSubtarget().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 << TRI->getRegClassName(MRI->getRegClass(Reg)) << "\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 << "] " << TRI->getRegClassName(MRI->getRegClass(Reg)) << "\n";
139 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
140 LLVM_DUMP_METHOD 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;
166 void addMBBLiveIns();
167 bool readsUndefSubreg(const MachineOperand &MO) const;
168 void addLiveInsForSubRanges(const LiveInterval &LI, unsigned PhysReg) const;
169 void handleIdentityCopy(MachineInstr &MI) const;
170 void expandCopyBundle(MachineInstr &MI) const;
174 VirtRegRewriter() : MachineFunctionPass(ID) {}
176 void getAnalysisUsage(AnalysisUsage &AU) const override;
178 bool runOnMachineFunction(MachineFunction&) override;
179 MachineFunctionProperties getSetProperties() const override {
180 return MachineFunctionProperties().set(
181 MachineFunctionProperties::Property::NoVRegs);
184 } // end anonymous namespace
186 char &llvm::VirtRegRewriterID = VirtRegRewriter::ID;
188 INITIALIZE_PASS_BEGIN(VirtRegRewriter, "virtregrewriter",
189 "Virtual Register Rewriter", false, false)
190 INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
191 INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
192 INITIALIZE_PASS_DEPENDENCY(LiveDebugVariables)
193 INITIALIZE_PASS_DEPENDENCY(LiveStacks)
194 INITIALIZE_PASS_DEPENDENCY(VirtRegMap)
195 INITIALIZE_PASS_END(VirtRegRewriter, "virtregrewriter",
196 "Virtual Register Rewriter", false, false)
198 char VirtRegRewriter::ID = 0;
200 void VirtRegRewriter::getAnalysisUsage(AnalysisUsage &AU) const {
201 AU.setPreservesCFG();
202 AU.addRequired<LiveIntervals>();
203 AU.addRequired<SlotIndexes>();
204 AU.addPreserved<SlotIndexes>();
205 AU.addRequired<LiveDebugVariables>();
206 AU.addRequired<LiveStacks>();
207 AU.addPreserved<LiveStacks>();
208 AU.addRequired<VirtRegMap>();
209 MachineFunctionPass::getAnalysisUsage(AU);
212 bool VirtRegRewriter::runOnMachineFunction(MachineFunction &fn) {
214 TM = &MF->getTarget();
215 TRI = MF->getSubtarget().getRegisterInfo();
216 TII = MF->getSubtarget().getInstrInfo();
217 MRI = &MF->getRegInfo();
218 Indexes = &getAnalysis<SlotIndexes>();
219 LIS = &getAnalysis<LiveIntervals>();
220 VRM = &getAnalysis<VirtRegMap>();
221 DEBUG(dbgs() << "********** REWRITE VIRTUAL REGISTERS **********\n"
222 << "********** Function: "
223 << MF->getName() << '\n');
226 // Add kill flags while we still have virtual registers.
227 LIS->addKillFlags(VRM);
229 // Live-in lists on basic blocks are required for physregs.
232 // Rewrite virtual registers.
235 // Write out new DBG_VALUE instructions.
236 getAnalysis<LiveDebugVariables>().emitDebugValues(VRM);
238 // All machine operands and other references to virtual registers have been
239 // replaced. Remove the virtual registers and release all the transient data.
241 MRI->clearVirtRegs();
245 void VirtRegRewriter::addLiveInsForSubRanges(const LiveInterval &LI,
246 unsigned PhysReg) const {
248 assert(LI.hasSubRanges());
250 typedef std::pair<const LiveInterval::SubRange *,
251 LiveInterval::const_iterator> SubRangeIteratorPair;
252 SmallVector<SubRangeIteratorPair, 4> SubRanges;
255 for (const LiveInterval::SubRange &SR : LI.subranges()) {
256 SubRanges.push_back(std::make_pair(&SR, SR.begin()));
257 if (!First.isValid() || SR.segments.front().start < First)
258 First = SR.segments.front().start;
259 if (!Last.isValid() || SR.segments.back().end > Last)
260 Last = SR.segments.back().end;
263 // Check all mbb start positions between First and Last while
264 // simulatenously advancing an iterator for each subrange.
265 for (SlotIndexes::MBBIndexIterator MBBI = Indexes->findMBBIndex(First);
266 MBBI != Indexes->MBBIndexEnd() && MBBI->first <= Last; ++MBBI) {
267 SlotIndex MBBBegin = MBBI->first;
268 // Advance all subrange iterators so that their end position is just
269 // behind MBBBegin (or the iterator is at the end).
270 LaneBitmask LaneMask;
271 for (auto &RangeIterPair : SubRanges) {
272 const LiveInterval::SubRange *SR = RangeIterPair.first;
273 LiveInterval::const_iterator &SRI = RangeIterPair.second;
274 while (SRI != SR->end() && SRI->end <= MBBBegin)
276 if (SRI == SR->end())
278 if (SRI->start <= MBBBegin)
279 LaneMask |= SR->LaneMask;
283 MachineBasicBlock *MBB = MBBI->second;
284 MBB->addLiveIn(PhysReg, LaneMask);
288 // Compute MBB live-in lists from virtual register live ranges and their
290 void VirtRegRewriter::addMBBLiveIns() {
291 for (unsigned Idx = 0, IdxE = MRI->getNumVirtRegs(); Idx != IdxE; ++Idx) {
292 unsigned VirtReg = TargetRegisterInfo::index2VirtReg(Idx);
293 if (MRI->reg_nodbg_empty(VirtReg))
295 LiveInterval &LI = LIS->getInterval(VirtReg);
296 if (LI.empty() || LIS->intervalIsInOneMBB(LI))
298 // This is a virtual register that is live across basic blocks. Its
299 // assigned PhysReg must be marked as live-in to those blocks.
300 unsigned PhysReg = VRM->getPhys(VirtReg);
301 assert(PhysReg != VirtRegMap::NO_PHYS_REG && "Unmapped virtual register.");
303 if (LI.hasSubRanges()) {
304 addLiveInsForSubRanges(LI, PhysReg);
306 // Go over MBB begin positions and see if we have segments covering them.
307 // The following works because segments and the MBBIndex list are both
308 // sorted by slot indexes.
309 SlotIndexes::MBBIndexIterator I = Indexes->MBBIndexBegin();
310 for (const auto &Seg : LI) {
311 I = Indexes->advanceMBBIndex(I, Seg.start);
312 for (; I != Indexes->MBBIndexEnd() && I->first < Seg.end; ++I) {
313 MachineBasicBlock *MBB = I->second;
314 MBB->addLiveIn(PhysReg);
320 // Sort and unique MBB LiveIns as we've not checked if SubReg/PhysReg were in
321 // each MBB's LiveIns set before calling addLiveIn on them.
322 for (MachineBasicBlock &MBB : *MF)
323 MBB.sortUniqueLiveIns();
326 /// Returns true if the given machine operand \p MO only reads undefined lanes.
327 /// The function only works for use operands with a subregister set.
328 bool VirtRegRewriter::readsUndefSubreg(const MachineOperand &MO) const {
329 // Shortcut if the operand is already marked undef.
333 unsigned Reg = MO.getReg();
334 const LiveInterval &LI = LIS->getInterval(Reg);
335 const MachineInstr &MI = *MO.getParent();
336 SlotIndex BaseIndex = LIS->getInstructionIndex(MI);
337 // This code is only meant to handle reading undefined subregisters which
338 // we couldn't properly detect before.
339 assert(LI.liveAt(BaseIndex) &&
340 "Reads of completely dead register should be marked undef already");
341 unsigned SubRegIdx = MO.getSubReg();
342 assert(SubRegIdx != 0 && LI.hasSubRanges());
343 LaneBitmask UseMask = TRI->getSubRegIndexLaneMask(SubRegIdx);
344 // See if any of the relevant subregister liveranges is defined at this point.
345 for (const LiveInterval::SubRange &SR : LI.subranges()) {
346 if ((SR.LaneMask & UseMask).any() && SR.liveAt(BaseIndex))
352 void VirtRegRewriter::handleIdentityCopy(MachineInstr &MI) const {
353 if (!MI.isIdentityCopy())
355 DEBUG(dbgs() << "Identity copy: " << MI);
359 // %R0 = COPY %R0<undef>
360 // %AL = COPY %AL, %EAX<imp-def>
361 // give us additional liveness information: The target (super-)register
362 // must not be valid before this point. Replace the COPY with a KILL
363 // instruction to maintain this information.
364 if (MI.getOperand(0).isUndef() || MI.getNumOperands() > 2) {
365 MI.setDesc(TII->get(TargetOpcode::KILL));
366 DEBUG(dbgs() << " replace by: " << MI);
371 Indexes->removeSingleMachineInstrFromMaps(MI);
372 MI.eraseFromBundle();
373 DEBUG(dbgs() << " deleted.\n");
376 /// The liverange splitting logic sometimes produces bundles of copies when
377 /// subregisters are involved. Expand these into a sequence of copy instructions
378 /// after processing the last in the bundle. Does not update LiveIntervals
379 /// which we shouldn't need for this instruction anymore.
380 void VirtRegRewriter::expandCopyBundle(MachineInstr &MI) const {
384 if (MI.isBundledWithPred() && !MI.isBundledWithSucc()) {
385 // Only do this when the complete bundle is made out of COPYs.
386 MachineBasicBlock &MBB = *MI.getParent();
387 for (MachineBasicBlock::reverse_instr_iterator I =
388 std::next(MI.getReverseIterator()), E = MBB.instr_rend();
389 I != E && I->isBundledWithSucc(); ++I) {
394 for (MachineBasicBlock::reverse_instr_iterator I = MI.getReverseIterator();
395 I->isBundledWithPred(); ) {
396 MachineInstr &MI = *I;
399 MI.unbundleFromPred();
401 Indexes->insertMachineInstrInMaps(MI);
406 void VirtRegRewriter::rewrite() {
407 bool NoSubRegLiveness = !MRI->subRegLivenessEnabled();
408 SmallVector<unsigned, 8> SuperDeads;
409 SmallVector<unsigned, 8> SuperDefs;
410 SmallVector<unsigned, 8> SuperKills;
412 for (MachineFunction::iterator MBBI = MF->begin(), MBBE = MF->end();
413 MBBI != MBBE; ++MBBI) {
414 DEBUG(MBBI->print(dbgs(), Indexes));
415 for (MachineBasicBlock::instr_iterator
416 MII = MBBI->instr_begin(), MIE = MBBI->instr_end(); MII != MIE;) {
417 MachineInstr *MI = &*MII;
420 for (MachineInstr::mop_iterator MOI = MI->operands_begin(),
421 MOE = MI->operands_end(); MOI != MOE; ++MOI) {
422 MachineOperand &MO = *MOI;
424 // Make sure MRI knows about registers clobbered by regmasks.
426 MRI->addPhysRegsUsedFromRegMask(MO.getRegMask());
428 if (!MO.isReg() || !TargetRegisterInfo::isVirtualRegister(MO.getReg()))
430 unsigned VirtReg = MO.getReg();
431 unsigned PhysReg = VRM->getPhys(VirtReg);
432 assert(PhysReg != VirtRegMap::NO_PHYS_REG &&
433 "Instruction uses unmapped VirtReg");
434 assert(!MRI->isReserved(PhysReg) && "Reserved register assignment");
436 // Preserve semantics of sub-register operands.
437 unsigned SubReg = MO.getSubReg();
439 if (NoSubRegLiveness) {
440 // A virtual register kill refers to the whole register, so we may
441 // have to add <imp-use,kill> operands for the super-register. A
442 // partial redef always kills and redefines the super-register.
443 if (MO.readsReg() && (MO.isDef() || MO.isKill()))
444 SuperKills.push_back(PhysReg);
447 // Also add implicit defs for the super-register.
449 SuperDeads.push_back(PhysReg);
451 SuperDefs.push_back(PhysReg);
455 if (readsUndefSubreg(MO))
456 // We need to add an <undef> flag if the subregister is
457 // completely undefined (and we are not adding super-register
460 } else if (!MO.isDead()) {
465 // The <def,undef> and <def,internal> flags only make sense for
466 // sub-register defs, and we are substituting a full physreg. An
467 // <imp-use,kill> operand from the SuperKills list will represent the
468 // partial read of the super-register.
470 MO.setIsUndef(false);
471 MO.setIsInternalRead(false);
474 // PhysReg operands cannot have subregister indexes.
475 PhysReg = TRI->getSubReg(PhysReg, SubReg);
476 assert(PhysReg && "Invalid SubReg for physical register");
479 // Rewrite. Note we could have used MachineOperand::substPhysReg(), but
480 // we need the inlining here.
484 // Add any missing super-register kills after rewriting the whole
486 while (!SuperKills.empty())
487 MI->addRegisterKilled(SuperKills.pop_back_val(), TRI, true);
489 while (!SuperDeads.empty())
490 MI->addRegisterDead(SuperDeads.pop_back_val(), TRI, true);
492 while (!SuperDefs.empty())
493 MI->addRegisterDefined(SuperDefs.pop_back_val(), TRI);
495 DEBUG(dbgs() << "> " << *MI);
497 expandCopyBundle(*MI);
499 // We can remove identity copies right now.
500 handleIdentityCopy(*MI);