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 #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"
38 #include <algorithm>
39 using namespace llvm;
40 
41 #define DEBUG_TYPE "regalloc"
42 
43 STATISTIC(NumSpillSlots, "Number of spill slots allocated");
44 STATISTIC(NumIdCopies,   "Number of identity moves eliminated after rewriting");
45 
46 //===----------------------------------------------------------------------===//
47 //  VirtRegMap implementation
48 //===----------------------------------------------------------------------===//
49 
50 char VirtRegMap::ID = 0;
51 
52 INITIALIZE_PASS(VirtRegMap, "virtregmap", "Virtual Register Map", false, false)
53 
54 bool VirtRegMap::runOnMachineFunction(MachineFunction &mf) {
55   MRI = &mf.getRegInfo();
56   TII = mf.getSubtarget().getInstrInfo();
57   TRI = mf.getSubtarget().getRegisterInfo();
58   MF = &mf;
59 
60   Virt2PhysMap.clear();
61   Virt2StackSlotMap.clear();
62   Virt2SplitMap.clear();
63 
64   grow();
65   return false;
66 }
67 
68 void VirtRegMap::grow() {
69   unsigned NumRegs = MF->getRegInfo().getNumVirtRegs();
70   Virt2PhysMap.resize(NumRegs);
71   Virt2StackSlotMap.resize(NumRegs);
72   Virt2SplitMap.resize(NumRegs);
73 }
74 
75 unsigned VirtRegMap::createSpillSlot(const TargetRegisterClass *RC) {
76   int SS = MF->getFrameInfo()->CreateSpillStackObject(RC->getSize(),
77                                                       RC->getAlignment());
78   ++NumSpillSlots;
79   return SS;
80 }
81 
82 bool VirtRegMap::hasPreferredPhys(unsigned VirtReg) {
83   unsigned Hint = MRI->getSimpleHint(VirtReg);
84   if (!Hint)
85     return 0;
86   if (TargetRegisterInfo::isVirtualRegister(Hint))
87     Hint = getPhys(Hint);
88   return getPhys(VirtReg) == Hint;
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          << TRI->getRegClassName(MRI->getRegClass(Reg)) << "\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          << "] " << TRI->getRegClassName(MRI->getRegClass(Reg)) << "\n";
134     }
135   }
136   OS << '\n';
137 }
138 
139 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
140 LLVM_DUMP_METHOD 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   bool readsUndefSubreg(const MachineOperand &MO) const;
168   void addLiveInsForSubRanges(const LiveInterval &LI, unsigned PhysReg) const;
169 
170 public:
171   static char ID;
172   VirtRegRewriter() : MachineFunctionPass(ID) {}
173 
174   void getAnalysisUsage(AnalysisUsage &AU) const override;
175 
176   bool runOnMachineFunction(MachineFunction&) override;
177   MachineFunctionProperties getSetProperties() const override {
178     return MachineFunctionProperties().set(
179         MachineFunctionProperties::Property::AllVRegsAllocated);
180   }
181 };
182 } // end anonymous namespace
183 
184 char &llvm::VirtRegRewriterID = VirtRegRewriter::ID;
185 
186 INITIALIZE_PASS_BEGIN(VirtRegRewriter, "virtregrewriter",
187                       "Virtual Register Rewriter", false, false)
188 INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
189 INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
190 INITIALIZE_PASS_DEPENDENCY(LiveDebugVariables)
191 INITIALIZE_PASS_DEPENDENCY(LiveStacks)
192 INITIALIZE_PASS_DEPENDENCY(VirtRegMap)
193 INITIALIZE_PASS_END(VirtRegRewriter, "virtregrewriter",
194                     "Virtual Register Rewriter", false, false)
195 
196 char VirtRegRewriter::ID = 0;
197 
198 void VirtRegRewriter::getAnalysisUsage(AnalysisUsage &AU) const {
199   AU.setPreservesCFG();
200   AU.addRequired<LiveIntervals>();
201   AU.addRequired<SlotIndexes>();
202   AU.addPreserved<SlotIndexes>();
203   AU.addRequired<LiveDebugVariables>();
204   AU.addRequired<LiveStacks>();
205   AU.addPreserved<LiveStacks>();
206   AU.addRequired<VirtRegMap>();
207   MachineFunctionPass::getAnalysisUsage(AU);
208 }
209 
210 bool VirtRegRewriter::runOnMachineFunction(MachineFunction &fn) {
211   MF = &fn;
212   TM = &MF->getTarget();
213   TRI = MF->getSubtarget().getRegisterInfo();
214   TII = MF->getSubtarget().getInstrInfo();
215   MRI = &MF->getRegInfo();
216   Indexes = &getAnalysis<SlotIndexes>();
217   LIS = &getAnalysis<LiveIntervals>();
218   VRM = &getAnalysis<VirtRegMap>();
219   DEBUG(dbgs() << "********** REWRITE VIRTUAL REGISTERS **********\n"
220                << "********** Function: "
221                << MF->getName() << '\n');
222   DEBUG(VRM->dump());
223 
224   // Add kill flags while we still have virtual registers.
225   LIS->addKillFlags(VRM);
226 
227   // Live-in lists on basic blocks are required for physregs.
228   addMBBLiveIns();
229 
230   // Rewrite virtual registers.
231   rewrite();
232 
233   // Write out new DBG_VALUE instructions.
234   getAnalysis<LiveDebugVariables>().emitDebugValues(VRM);
235 
236   // All machine operands and other references to virtual registers have been
237   // replaced. Remove the virtual registers and release all the transient data.
238   VRM->clearAllVirt();
239   MRI->clearVirtRegs();
240   return true;
241 }
242 
243 void VirtRegRewriter::addLiveInsForSubRanges(const LiveInterval &LI,
244                                              unsigned PhysReg) const {
245   assert(!LI.empty());
246   assert(LI.hasSubRanges());
247 
248   typedef std::pair<const LiveInterval::SubRange *,
249                     LiveInterval::const_iterator> SubRangeIteratorPair;
250   SmallVector<SubRangeIteratorPair, 4> SubRanges;
251   SlotIndex First;
252   SlotIndex Last;
253   for (const LiveInterval::SubRange &SR : LI.subranges()) {
254     SubRanges.push_back(std::make_pair(&SR, SR.begin()));
255     if (!First.isValid() || SR.segments.front().start < First)
256       First = SR.segments.front().start;
257     if (!Last.isValid() || SR.segments.back().end > Last)
258       Last = SR.segments.back().end;
259   }
260 
261   // Check all mbb start positions between First and Last while
262   // simulatenously advancing an iterator for each subrange.
263   for (SlotIndexes::MBBIndexIterator MBBI = Indexes->findMBBIndex(First);
264        MBBI != Indexes->MBBIndexEnd() && MBBI->first <= Last; ++MBBI) {
265     SlotIndex MBBBegin = MBBI->first;
266     // Advance all subrange iterators so that their end position is just
267     // behind MBBBegin (or the iterator is at the end).
268     LaneBitmask LaneMask = 0;
269     for (auto &RangeIterPair : SubRanges) {
270       const LiveInterval::SubRange *SR = RangeIterPair.first;
271       LiveInterval::const_iterator &SRI = RangeIterPair.second;
272       while (SRI != SR->end() && SRI->end <= MBBBegin)
273         ++SRI;
274       if (SRI == SR->end())
275         continue;
276       if (SRI->start <= MBBBegin)
277         LaneMask |= SR->LaneMask;
278     }
279     if (LaneMask == 0)
280       continue;
281     MachineBasicBlock *MBB = MBBI->second;
282     MBB->addLiveIn(PhysReg, LaneMask);
283   }
284 }
285 
286 // Compute MBB live-in lists from virtual register live ranges and their
287 // assignments.
288 void VirtRegRewriter::addMBBLiveIns() {
289   for (unsigned Idx = 0, IdxE = MRI->getNumVirtRegs(); Idx != IdxE; ++Idx) {
290     unsigned VirtReg = TargetRegisterInfo::index2VirtReg(Idx);
291     if (MRI->reg_nodbg_empty(VirtReg))
292       continue;
293     LiveInterval &LI = LIS->getInterval(VirtReg);
294     if (LI.empty() || LIS->intervalIsInOneMBB(LI))
295       continue;
296     // This is a virtual register that is live across basic blocks. Its
297     // assigned PhysReg must be marked as live-in to those blocks.
298     unsigned PhysReg = VRM->getPhys(VirtReg);
299     assert(PhysReg != VirtRegMap::NO_PHYS_REG && "Unmapped virtual register.");
300 
301     if (LI.hasSubRanges()) {
302       addLiveInsForSubRanges(LI, PhysReg);
303     } else {
304       // Go over MBB begin positions and see if we have segments covering them.
305       // The following works because segments and the MBBIndex list are both
306       // sorted by slot indexes.
307       SlotIndexes::MBBIndexIterator I = Indexes->MBBIndexBegin();
308       for (const auto &Seg : LI) {
309         I = Indexes->advanceMBBIndex(I, Seg.start);
310         for (; I != Indexes->MBBIndexEnd() && I->first < Seg.end; ++I) {
311           MachineBasicBlock *MBB = I->second;
312           MBB->addLiveIn(PhysReg);
313         }
314       }
315     }
316   }
317 
318   // Sort and unique MBB LiveIns as we've not checked if SubReg/PhysReg were in
319   // each MBB's LiveIns set before calling addLiveIn on them.
320   for (MachineBasicBlock &MBB : *MF)
321     MBB.sortUniqueLiveIns();
322 }
323 
324 /// Returns true if the given machine operand \p MO only reads undefined lanes.
325 /// The function only works for use operands with a subregister set.
326 bool VirtRegRewriter::readsUndefSubreg(const MachineOperand &MO) const {
327   // Shortcut if the operand is already marked undef.
328   if (MO.isUndef())
329     return true;
330 
331   unsigned Reg = MO.getReg();
332   const LiveInterval &LI = LIS->getInterval(Reg);
333   const MachineInstr &MI = *MO.getParent();
334   SlotIndex BaseIndex = LIS->getInstructionIndex(MI);
335   // This code is only meant to handle reading undefined subregisters which
336   // we couldn't properly detect before.
337   assert(LI.liveAt(BaseIndex) &&
338          "Reads of completely dead register should be marked undef already");
339   unsigned SubRegIdx = MO.getSubReg();
340   LaneBitmask UseMask = TRI->getSubRegIndexLaneMask(SubRegIdx);
341   // See if any of the relevant subregister liveranges is defined at this point.
342   for (const LiveInterval::SubRange &SR : LI.subranges()) {
343     if ((SR.LaneMask & UseMask) != 0 && SR.liveAt(BaseIndex))
344       return false;
345   }
346   return true;
347 }
348 
349 void VirtRegRewriter::rewrite() {
350   bool NoSubRegLiveness = !MRI->subRegLivenessEnabled();
351   SmallVector<unsigned, 8> SuperDeads;
352   SmallVector<unsigned, 8> SuperDefs;
353   SmallVector<unsigned, 8> SuperKills;
354 
355   for (MachineFunction::iterator MBBI = MF->begin(), MBBE = MF->end();
356        MBBI != MBBE; ++MBBI) {
357     DEBUG(MBBI->print(dbgs(), Indexes));
358     for (MachineBasicBlock::instr_iterator
359            MII = MBBI->instr_begin(), MIE = MBBI->instr_end(); MII != MIE;) {
360       MachineInstr *MI = &*MII;
361       ++MII;
362 
363       for (MachineInstr::mop_iterator MOI = MI->operands_begin(),
364            MOE = MI->operands_end(); MOI != MOE; ++MOI) {
365         MachineOperand &MO = *MOI;
366 
367         // Make sure MRI knows about registers clobbered by regmasks.
368         if (MO.isRegMask())
369           MRI->addPhysRegsUsedFromRegMask(MO.getRegMask());
370 
371         if (!MO.isReg() || !TargetRegisterInfo::isVirtualRegister(MO.getReg()))
372           continue;
373         unsigned VirtReg = MO.getReg();
374         unsigned PhysReg = VRM->getPhys(VirtReg);
375         assert(PhysReg != VirtRegMap::NO_PHYS_REG &&
376                "Instruction uses unmapped VirtReg");
377         assert(!MRI->isReserved(PhysReg) && "Reserved register assignment");
378 
379         // Preserve semantics of sub-register operands.
380         unsigned SubReg = MO.getSubReg();
381         if (SubReg != 0) {
382           if (NoSubRegLiveness) {
383             // A virtual register kill refers to the whole register, so we may
384             // have to add <imp-use,kill> operands for the super-register.  A
385             // partial redef always kills and redefines the super-register.
386             if (MO.readsReg() && (MO.isDef() || MO.isKill()))
387               SuperKills.push_back(PhysReg);
388 
389             if (MO.isDef()) {
390               // Also add implicit defs for the super-register.
391               if (MO.isDead())
392                 SuperDeads.push_back(PhysReg);
393               else
394                 SuperDefs.push_back(PhysReg);
395             }
396           } else {
397             if (MO.isUse()) {
398               if (readsUndefSubreg(MO))
399                 // We need to add an <undef> flag if the subregister is
400                 // completely undefined (and we are not adding super-register
401                 // defs).
402                 MO.setIsUndef(true);
403             } else if (!MO.isDead()) {
404               assert(MO.isDef());
405             }
406           }
407 
408           // The <def,undef> flag only makes sense for sub-register defs, and
409           // we are substituting a full physreg.  An <imp-use,kill> operand
410           // from the SuperKills list will represent the partial read of the
411           // super-register.
412           if (MO.isDef())
413             MO.setIsUndef(false);
414 
415           // PhysReg operands cannot have subregister indexes.
416           PhysReg = TRI->getSubReg(PhysReg, SubReg);
417           assert(PhysReg && "Invalid SubReg for physical register");
418           MO.setSubReg(0);
419         }
420         // Rewrite. Note we could have used MachineOperand::substPhysReg(), but
421         // we need the inlining here.
422         MO.setReg(PhysReg);
423       }
424 
425       // Add any missing super-register kills after rewriting the whole
426       // instruction.
427       while (!SuperKills.empty())
428         MI->addRegisterKilled(SuperKills.pop_back_val(), TRI, true);
429 
430       while (!SuperDeads.empty())
431         MI->addRegisterDead(SuperDeads.pop_back_val(), TRI, true);
432 
433       while (!SuperDefs.empty())
434         MI->addRegisterDefined(SuperDefs.pop_back_val(), TRI);
435 
436       DEBUG(dbgs() << "> " << *MI);
437 
438       // Finally, remove any identity copies.
439       if (MI->isIdentityCopy()) {
440         ++NumIdCopies;
441         DEBUG(dbgs() << "Deleting identity copy.\n");
442         if (Indexes)
443           Indexes->removeMachineInstrFromMaps(*MI);
444         // It's safe to erase MI because MII has already been incremented.
445         MI->eraseFromParent();
446       }
447     }
448   }
449 }
450