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/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"
40 #include <algorithm>
41 using namespace llvm;
42 
43 #define DEBUG_TYPE "regalloc"
44 
45 STATISTIC(NumSpillSlots, "Number of spill slots allocated");
46 STATISTIC(NumIdCopies,   "Number of identity moves eliminated after rewriting");
47 
48 //===----------------------------------------------------------------------===//
49 //  VirtRegMap implementation
50 //===----------------------------------------------------------------------===//
51 
52 char VirtRegMap::ID = 0;
53 
54 INITIALIZE_PASS(VirtRegMap, "virtregmap", "Virtual Register Map", false, false)
55 
56 bool VirtRegMap::runOnMachineFunction(MachineFunction &mf) {
57   MRI = &mf.getRegInfo();
58   TII = mf.getSubtarget().getInstrInfo();
59   TRI = mf.getSubtarget().getRegisterInfo();
60   MF = &mf;
61 
62   Virt2PhysMap.clear();
63   Virt2StackSlotMap.clear();
64   Virt2SplitMap.clear();
65 
66   grow();
67   return false;
68 }
69 
70 void VirtRegMap::grow() {
71   unsigned NumRegs = MF->getRegInfo().getNumVirtRegs();
72   Virt2PhysMap.resize(NumRegs);
73   Virt2StackSlotMap.resize(NumRegs);
74   Virt2SplitMap.resize(NumRegs);
75 }
76 
77 unsigned VirtRegMap::createSpillSlot(const TargetRegisterClass *RC) {
78   int SS = MF->getFrameInfo()->CreateSpillStackObject(RC->getSize(),
79                                                       RC->getAlignment());
80   ++NumSpillSlots;
81   return SS;
82 }
83 
84 bool VirtRegMap::hasPreferredPhys(unsigned VirtReg) {
85   unsigned Hint = MRI->getSimpleHint(VirtReg);
86   if (!Hint)
87     return 0;
88   if (TargetRegisterInfo::isVirtualRegister(Hint))
89     Hint = getPhys(Hint);
90   return getPhys(VirtReg) == Hint;
91 }
92 
93 bool VirtRegMap::hasKnownPreference(unsigned VirtReg) {
94   std::pair<unsigned, unsigned> Hint = MRI->getRegAllocationHint(VirtReg);
95   if (TargetRegisterInfo::isPhysicalRegister(Hint.second))
96     return true;
97   if (TargetRegisterInfo::isVirtualRegister(Hint.second))
98     return hasPhys(Hint.second);
99   return false;
100 }
101 
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);
108 }
109 
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");
114   assert((SS >= 0 ||
115           (SS >= MF->getFrameInfo()->getObjectIndexBegin())) &&
116          "illegal fixed frame index");
117   Virt2StackSlotMap[virtReg] = SS;
118 }
119 
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";
128     }
129   }
130 
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";
136     }
137   }
138   OS << '\n';
139 }
140 
141 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
142 LLVM_DUMP_METHOD void VirtRegMap::dump() const {
143   print(dbgs());
144 }
145 #endif
146 
147 //===----------------------------------------------------------------------===//
148 //                              VirtRegRewriter
149 //===----------------------------------------------------------------------===//
150 //
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.
155 //
156 namespace {
157 class VirtRegRewriter : public MachineFunctionPass {
158   MachineFunction *MF;
159   const TargetMachine *TM;
160   const TargetRegisterInfo *TRI;
161   const TargetInstrInfo *TII;
162   MachineRegisterInfo *MRI;
163   SlotIndexes *Indexes;
164   LiveIntervals *LIS;
165   VirtRegMap *VRM;
166 
167   void rewrite();
168   void addMBBLiveIns();
169   bool readsUndefSubreg(const MachineOperand &MO) const;
170   void addLiveInsForSubRanges(const LiveInterval &LI, unsigned PhysReg) const;
171 
172 public:
173   static char ID;
174   VirtRegRewriter() : MachineFunctionPass(ID) {}
175 
176   void getAnalysisUsage(AnalysisUsage &AU) const override;
177 
178   bool runOnMachineFunction(MachineFunction&) override;
179   MachineFunctionProperties getSetProperties() const override {
180     return MachineFunctionProperties().set(
181         MachineFunctionProperties::Property::AllVRegsAllocated);
182   }
183 };
184 } // end anonymous namespace
185 
186 char &llvm::VirtRegRewriterID = VirtRegRewriter::ID;
187 
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)
197 
198 char VirtRegRewriter::ID = 0;
199 
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);
210 }
211 
212 bool VirtRegRewriter::runOnMachineFunction(MachineFunction &fn) {
213   MF = &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');
224   DEBUG(VRM->dump());
225 
226   // Add kill flags while we still have virtual registers.
227   LIS->addKillFlags(VRM);
228 
229   // Live-in lists on basic blocks are required for physregs.
230   addMBBLiveIns();
231 
232   // Rewrite virtual registers.
233   rewrite();
234 
235   // Write out new DBG_VALUE instructions.
236   getAnalysis<LiveDebugVariables>().emitDebugValues(VRM);
237 
238   // All machine operands and other references to virtual registers have been
239   // replaced. Remove the virtual registers and release all the transient data.
240   VRM->clearAllVirt();
241   MRI->clearVirtRegs();
242   return true;
243 }
244 
245 void VirtRegRewriter::addLiveInsForSubRanges(const LiveInterval &LI,
246                                              unsigned PhysReg) const {
247   assert(!LI.empty());
248   assert(LI.hasSubRanges());
249 
250   typedef std::pair<const LiveInterval::SubRange *,
251                     LiveInterval::const_iterator> SubRangeIteratorPair;
252   SmallVector<SubRangeIteratorPair, 4> SubRanges;
253   SlotIndex First;
254   SlotIndex Last;
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;
261   }
262 
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 = 0;
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)
275         ++SRI;
276       if (SRI == SR->end())
277         continue;
278       if (SRI->start <= MBBBegin)
279         LaneMask |= SR->LaneMask;
280     }
281     if (LaneMask == 0)
282       continue;
283     MachineBasicBlock *MBB = MBBI->second;
284     MBB->addLiveIn(PhysReg, LaneMask);
285   }
286 }
287 
288 // Compute MBB live-in lists from virtual register live ranges and their
289 // assignments.
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))
294       continue;
295     LiveInterval &LI = LIS->getInterval(VirtReg);
296     if (LI.empty() || LIS->intervalIsInOneMBB(LI))
297       continue;
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.");
302 
303     if (LI.hasSubRanges()) {
304       addLiveInsForSubRanges(LI, PhysReg);
305     } else {
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);
315         }
316       }
317     }
318   }
319 
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();
324 }
325 
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.
330   if (MO.isUndef())
331     return true;
332 
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   LaneBitmask UseMask = TRI->getSubRegIndexLaneMask(SubRegIdx);
343   // See if any of the relevant subregister liveranges is defined at this point.
344   for (const LiveInterval::SubRange &SR : LI.subranges()) {
345     if ((SR.LaneMask & UseMask) != 0 && SR.liveAt(BaseIndex))
346       return false;
347   }
348   return true;
349 }
350 
351 void VirtRegRewriter::rewrite() {
352   bool NoSubRegLiveness = !MRI->subRegLivenessEnabled();
353   SmallVector<unsigned, 8> SuperDeads;
354   SmallVector<unsigned, 8> SuperDefs;
355   SmallVector<unsigned, 8> SuperKills;
356 
357   for (MachineFunction::iterator MBBI = MF->begin(), MBBE = MF->end();
358        MBBI != MBBE; ++MBBI) {
359     DEBUG(MBBI->print(dbgs(), Indexes));
360     for (MachineBasicBlock::instr_iterator
361            MII = MBBI->instr_begin(), MIE = MBBI->instr_end(); MII != MIE;) {
362       MachineInstr *MI = &*MII;
363       ++MII;
364 
365       for (MachineInstr::mop_iterator MOI = MI->operands_begin(),
366            MOE = MI->operands_end(); MOI != MOE; ++MOI) {
367         MachineOperand &MO = *MOI;
368 
369         // Make sure MRI knows about registers clobbered by regmasks.
370         if (MO.isRegMask())
371           MRI->addPhysRegsUsedFromRegMask(MO.getRegMask());
372 
373         if (!MO.isReg() || !TargetRegisterInfo::isVirtualRegister(MO.getReg()))
374           continue;
375         unsigned VirtReg = MO.getReg();
376         unsigned PhysReg = VRM->getPhys(VirtReg);
377         assert(PhysReg != VirtRegMap::NO_PHYS_REG &&
378                "Instruction uses unmapped VirtReg");
379         assert(!MRI->isReserved(PhysReg) && "Reserved register assignment");
380 
381         // Preserve semantics of sub-register operands.
382         unsigned SubReg = MO.getSubReg();
383         if (SubReg != 0) {
384           if (NoSubRegLiveness) {
385             // A virtual register kill refers to the whole register, so we may
386             // have to add <imp-use,kill> operands for the super-register.  A
387             // partial redef always kills and redefines the super-register.
388             if (MO.readsReg() && (MO.isDef() || MO.isKill()))
389               SuperKills.push_back(PhysReg);
390 
391             if (MO.isDef()) {
392               // Also add implicit defs for the super-register.
393               if (MO.isDead())
394                 SuperDeads.push_back(PhysReg);
395               else
396                 SuperDefs.push_back(PhysReg);
397             }
398           } else {
399             if (MO.isUse()) {
400               if (readsUndefSubreg(MO))
401                 // We need to add an <undef> flag if the subregister is
402                 // completely undefined (and we are not adding super-register
403                 // defs).
404                 MO.setIsUndef(true);
405             } else if (!MO.isDead()) {
406               assert(MO.isDef());
407             }
408           }
409 
410           // The <def,undef> flag only makes sense for sub-register defs, and
411           // we are substituting a full physreg.  An <imp-use,kill> operand
412           // from the SuperKills list will represent the partial read of the
413           // super-register.
414           if (MO.isDef())
415             MO.setIsUndef(false);
416 
417           // PhysReg operands cannot have subregister indexes.
418           PhysReg = TRI->getSubReg(PhysReg, SubReg);
419           assert(PhysReg && "Invalid SubReg for physical register");
420           MO.setSubReg(0);
421         }
422         // Rewrite. Note we could have used MachineOperand::substPhysReg(), but
423         // we need the inlining here.
424         MO.setReg(PhysReg);
425       }
426 
427       // Add any missing super-register kills after rewriting the whole
428       // instruction.
429       while (!SuperKills.empty())
430         MI->addRegisterKilled(SuperKills.pop_back_val(), TRI, true);
431 
432       while (!SuperDeads.empty())
433         MI->addRegisterDead(SuperDeads.pop_back_val(), TRI, true);
434 
435       while (!SuperDefs.empty())
436         MI->addRegisterDefined(SuperDefs.pop_back_val(), TRI);
437 
438       DEBUG(dbgs() << "> " << *MI);
439 
440       // Finally, remove any identity copies.
441       if (MI->isIdentityCopy()) {
442         ++NumIdCopies;
443         DEBUG(dbgs() << "Deleting identity copy.\n");
444         if (Indexes)
445           Indexes->removeMachineInstrFromMaps(*MI);
446         // It's safe to erase MI because MII has already been incremented.
447         MI->eraseFromParent();
448       }
449     }
450   }
451 }
452