xref: /llvm-project/llvm/lib/CodeGen/VirtRegMap.cpp (revision 0a44d3a57f03e8263f1509eb397201c9e07b21aa)
1 //===- llvm/CodeGen/VirtRegMap.cpp - Virtual Register Map -----------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the VirtRegMap class.
10 //
11 // It also contains implementations of the Spiller interface, which, given a
12 // virtual register map and a machine function, eliminates all virtual
13 // references by replacing them with physical register references - adding spill
14 // code as necessary.
15 //
16 //===----------------------------------------------------------------------===//
17 
18 #include "llvm/CodeGen/VirtRegMap.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/ADT/Statistic.h"
21 #include "llvm/CodeGen/LiveDebugVariables.h"
22 #include "llvm/CodeGen/LiveInterval.h"
23 #include "llvm/CodeGen/LiveIntervals.h"
24 #include "llvm/CodeGen/LiveRegMatrix.h"
25 #include "llvm/CodeGen/LiveStacks.h"
26 #include "llvm/CodeGen/MachineBasicBlock.h"
27 #include "llvm/CodeGen/MachineFrameInfo.h"
28 #include "llvm/CodeGen/MachineFunction.h"
29 #include "llvm/CodeGen/MachineFunctionPass.h"
30 #include "llvm/CodeGen/MachineInstr.h"
31 #include "llvm/CodeGen/MachineOperand.h"
32 #include "llvm/CodeGen/MachineRegisterInfo.h"
33 #include "llvm/CodeGen/SlotIndexes.h"
34 #include "llvm/CodeGen/TargetFrameLowering.h"
35 #include "llvm/CodeGen/TargetInstrInfo.h"
36 #include "llvm/CodeGen/TargetOpcodes.h"
37 #include "llvm/CodeGen/TargetRegisterInfo.h"
38 #include "llvm/CodeGen/TargetSubtargetInfo.h"
39 #include "llvm/Config/llvm-config.h"
40 #include "llvm/MC/LaneBitmask.h"
41 #include "llvm/Pass.h"
42 #include "llvm/Support/Compiler.h"
43 #include "llvm/Support/Debug.h"
44 #include "llvm/Support/raw_ostream.h"
45 #include <cassert>
46 #include <iterator>
47 #include <utility>
48 
49 using namespace llvm;
50 
51 #define DEBUG_TYPE "regalloc"
52 
53 STATISTIC(NumSpillSlots, "Number of spill slots allocated");
54 STATISTIC(NumIdCopies,   "Number of identity moves eliminated after rewriting");
55 
56 //===----------------------------------------------------------------------===//
57 //  VirtRegMap implementation
58 //===----------------------------------------------------------------------===//
59 
60 char VirtRegMapWrapperLegacy::ID = 0;
61 
62 INITIALIZE_PASS(VirtRegMapWrapperLegacy, "virtregmap", "Virtual Register Map",
63                 false, true)
64 
65 void VirtRegMap::init(MachineFunction &mf) {
66   MRI = &mf.getRegInfo();
67   TII = mf.getSubtarget().getInstrInfo();
68   TRI = mf.getSubtarget().getRegisterInfo();
69   MF = &mf;
70 
71   Virt2PhysMap.clear();
72   Virt2StackSlotMap.clear();
73   Virt2SplitMap.clear();
74   Virt2ShapeMap.clear();
75 
76   grow();
77 }
78 
79 void VirtRegMap::grow() {
80   unsigned NumRegs = MF->getRegInfo().getNumVirtRegs();
81   Virt2PhysMap.resize(NumRegs);
82   Virt2StackSlotMap.resize(NumRegs);
83   Virt2SplitMap.resize(NumRegs);
84 }
85 
86 void VirtRegMap::assignVirt2Phys(Register virtReg, MCRegister physReg) {
87   assert(virtReg.isVirtual() && physReg.isPhysical());
88   assert(!Virt2PhysMap[virtReg] &&
89          "attempt to assign physical register to already mapped "
90          "virtual register");
91   assert((!getRegInfo().isReserved(physReg) ||
92           MF->getProperties().hasProperty(
93               MachineFunctionProperties::Property::FailedRegAlloc)) &&
94          "Attempt to map virtReg to a reserved physReg");
95   Virt2PhysMap[virtReg] = physReg;
96 }
97 
98 unsigned VirtRegMap::createSpillSlot(const TargetRegisterClass *RC) {
99   unsigned Size = TRI->getSpillSize(*RC);
100   Align Alignment = TRI->getSpillAlign(*RC);
101   // Set preferred alignment if we are still able to realign the stack
102   auto &ST = MF->getSubtarget();
103   Align CurrentAlign = ST.getFrameLowering()->getStackAlign();
104   if (Alignment > CurrentAlign && !ST.getRegisterInfo()->canRealignStack(*MF)) {
105     Alignment = CurrentAlign;
106   }
107   int SS = MF->getFrameInfo().CreateSpillStackObject(Size, Alignment);
108   ++NumSpillSlots;
109   return SS;
110 }
111 
112 bool VirtRegMap::hasPreferredPhys(Register VirtReg) const {
113   Register Hint = MRI->getSimpleHint(VirtReg);
114   if (!Hint.isValid())
115     return false;
116   if (Hint.isVirtual())
117     Hint = getPhys(Hint);
118   return Register(getPhys(VirtReg)) == Hint;
119 }
120 
121 bool VirtRegMap::hasKnownPreference(Register VirtReg) const {
122   std::pair<unsigned, Register> Hint = MRI->getRegAllocationHint(VirtReg);
123   if (Hint.second.isPhysical())
124     return true;
125   if (Hint.second.isVirtual())
126     return hasPhys(Hint.second);
127   return false;
128 }
129 
130 int VirtRegMap::assignVirt2StackSlot(Register virtReg) {
131   assert(virtReg.isVirtual());
132   assert(Virt2StackSlotMap[virtReg] == NO_STACK_SLOT &&
133          "attempt to assign stack slot to already spilled register");
134   const TargetRegisterClass* RC = MF->getRegInfo().getRegClass(virtReg);
135   return Virt2StackSlotMap[virtReg] = createSpillSlot(RC);
136 }
137 
138 void VirtRegMap::assignVirt2StackSlot(Register virtReg, int SS) {
139   assert(virtReg.isVirtual());
140   assert(Virt2StackSlotMap[virtReg] == NO_STACK_SLOT &&
141          "attempt to assign stack slot to already spilled register");
142   assert((SS >= 0 ||
143           (SS >= MF->getFrameInfo().getObjectIndexBegin())) &&
144          "illegal fixed frame index");
145   Virt2StackSlotMap[virtReg] = SS;
146 }
147 
148 void VirtRegMap::print(raw_ostream &OS, const Module*) const {
149   OS << "********** REGISTER MAP **********\n";
150   for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
151     Register Reg = Register::index2VirtReg(i);
152     if (Virt2PhysMap[Reg]) {
153       OS << '[' << printReg(Reg, TRI) << " -> "
154          << printReg(Virt2PhysMap[Reg], TRI) << "] "
155          << TRI->getRegClassName(MRI->getRegClass(Reg)) << "\n";
156     }
157   }
158 
159   for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
160     Register Reg = Register::index2VirtReg(i);
161     if (Virt2StackSlotMap[Reg] != VirtRegMap::NO_STACK_SLOT) {
162       OS << '[' << printReg(Reg, TRI) << " -> fi#" << Virt2StackSlotMap[Reg]
163          << "] " << TRI->getRegClassName(MRI->getRegClass(Reg)) << "\n";
164     }
165   }
166   OS << '\n';
167 }
168 
169 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
170 LLVM_DUMP_METHOD void VirtRegMap::dump() const {
171   print(dbgs());
172 }
173 #endif
174 
175 AnalysisKey VirtRegMapAnalysis::Key;
176 
177 PreservedAnalyses
178 VirtRegMapPrinterPass::run(MachineFunction &MF,
179                            MachineFunctionAnalysisManager &MFAM) {
180   OS << MFAM.getResult<VirtRegMapAnalysis>(MF);
181   return PreservedAnalyses::all();
182 }
183 
184 VirtRegMap VirtRegMapAnalysis::run(MachineFunction &MF,
185                                    MachineFunctionAnalysisManager &MAM) {
186   VirtRegMap VRM;
187   VRM.init(MF);
188   return VRM;
189 }
190 
191 //===----------------------------------------------------------------------===//
192 //                              VirtRegRewriter
193 //===----------------------------------------------------------------------===//
194 //
195 // The VirtRegRewriter is the last of the register allocator passes.
196 // It rewrites virtual registers to physical registers as specified in the
197 // VirtRegMap analysis. It also updates live-in information on basic blocks
198 // according to LiveIntervals.
199 //
200 namespace {
201 
202 class VirtRegRewriter : public MachineFunctionPass {
203   MachineFunction *MF = nullptr;
204   const TargetRegisterInfo *TRI = nullptr;
205   const TargetInstrInfo *TII = nullptr;
206   MachineRegisterInfo *MRI = nullptr;
207   SlotIndexes *Indexes = nullptr;
208   LiveIntervals *LIS = nullptr;
209   LiveRegMatrix *LRM = nullptr;
210   VirtRegMap *VRM = nullptr;
211   LiveDebugVariables *DebugVars = nullptr;
212   DenseSet<Register> RewriteRegs;
213   bool ClearVirtRegs;
214 
215   void rewrite();
216   void addMBBLiveIns();
217   bool readsUndefSubreg(const MachineOperand &MO) const;
218   void addLiveInsForSubRanges(const LiveInterval &LI, MCRegister PhysReg) const;
219   void handleIdentityCopy(MachineInstr &MI);
220   void expandCopyBundle(MachineInstr &MI) const;
221   bool subRegLiveThrough(const MachineInstr &MI, MCRegister SuperPhysReg) const;
222   LaneBitmask liveOutUndefPhiLanesForUndefSubregDef(
223       const LiveInterval &LI, const MachineBasicBlock &MBB, unsigned SubReg,
224       MCRegister PhysReg, const MachineInstr &MI) const;
225 
226 public:
227   static char ID;
228   VirtRegRewriter(bool ClearVirtRegs_ = true) :
229     MachineFunctionPass(ID),
230     ClearVirtRegs(ClearVirtRegs_) {}
231 
232   void getAnalysisUsage(AnalysisUsage &AU) const override;
233 
234   bool runOnMachineFunction(MachineFunction&) override;
235 
236   MachineFunctionProperties getSetProperties() const override {
237     if (ClearVirtRegs) {
238       return MachineFunctionProperties().set(
239         MachineFunctionProperties::Property::NoVRegs);
240     }
241 
242     return MachineFunctionProperties();
243   }
244 };
245 
246 } // end anonymous namespace
247 
248 char VirtRegRewriter::ID = 0;
249 
250 char &llvm::VirtRegRewriterID = VirtRegRewriter::ID;
251 
252 INITIALIZE_PASS_BEGIN(VirtRegRewriter, "virtregrewriter",
253                       "Virtual Register Rewriter", false, false)
254 INITIALIZE_PASS_DEPENDENCY(SlotIndexesWrapperPass)
255 INITIALIZE_PASS_DEPENDENCY(LiveIntervalsWrapperPass)
256 INITIALIZE_PASS_DEPENDENCY(LiveDebugVariablesWrapperLegacy)
257 INITIALIZE_PASS_DEPENDENCY(LiveRegMatrixWrapperLegacy)
258 INITIALIZE_PASS_DEPENDENCY(LiveStacksWrapperLegacy)
259 INITIALIZE_PASS_DEPENDENCY(VirtRegMapWrapperLegacy)
260 INITIALIZE_PASS_END(VirtRegRewriter, "virtregrewriter",
261                     "Virtual Register Rewriter", false, false)
262 
263 void VirtRegRewriter::getAnalysisUsage(AnalysisUsage &AU) const {
264   AU.setPreservesCFG();
265   AU.addRequired<LiveIntervalsWrapperPass>();
266   AU.addPreserved<LiveIntervalsWrapperPass>();
267   AU.addRequired<SlotIndexesWrapperPass>();
268   AU.addPreserved<SlotIndexesWrapperPass>();
269   AU.addRequired<LiveDebugVariablesWrapperLegacy>();
270   AU.addRequired<LiveStacksWrapperLegacy>();
271   AU.addPreserved<LiveStacksWrapperLegacy>();
272   AU.addRequired<VirtRegMapWrapperLegacy>();
273   AU.addRequired<LiveRegMatrixWrapperLegacy>();
274 
275   if (!ClearVirtRegs)
276     AU.addPreserved<LiveDebugVariablesWrapperLegacy>();
277 
278   MachineFunctionPass::getAnalysisUsage(AU);
279 }
280 
281 bool VirtRegRewriter::runOnMachineFunction(MachineFunction &fn) {
282   MF = &fn;
283   TRI = MF->getSubtarget().getRegisterInfo();
284   TII = MF->getSubtarget().getInstrInfo();
285   MRI = &MF->getRegInfo();
286   Indexes = &getAnalysis<SlotIndexesWrapperPass>().getSI();
287   LIS = &getAnalysis<LiveIntervalsWrapperPass>().getLIS();
288   LRM = &getAnalysis<LiveRegMatrixWrapperLegacy>().getLRM();
289   VRM = &getAnalysis<VirtRegMapWrapperLegacy>().getVRM();
290   DebugVars = &getAnalysis<LiveDebugVariablesWrapperLegacy>().getLDV();
291   LLVM_DEBUG(dbgs() << "********** REWRITE VIRTUAL REGISTERS **********\n"
292                     << "********** Function: " << MF->getName() << '\n');
293   LLVM_DEBUG(VRM->dump());
294 
295   // Add kill flags while we still have virtual registers.
296   LIS->addKillFlags(VRM);
297 
298   // Live-in lists on basic blocks are required for physregs.
299   addMBBLiveIns();
300 
301   // Rewrite virtual registers.
302   rewrite();
303 
304   if (ClearVirtRegs) {
305     // Write out new DBG_VALUE instructions.
306 
307     // We only do this if ClearVirtRegs is specified since this should be the
308     // final run of the pass and we don't want to emit them multiple times.
309     DebugVars->emitDebugValues(VRM);
310 
311     // All machine operands and other references to virtual registers have been
312     // replaced. Remove the virtual registers and release all the transient data.
313     VRM->clearAllVirt();
314     MRI->clearVirtRegs();
315   }
316 
317   return true;
318 }
319 
320 void VirtRegRewriter::addLiveInsForSubRanges(const LiveInterval &LI,
321                                              MCRegister PhysReg) const {
322   assert(!LI.empty());
323   assert(LI.hasSubRanges());
324 
325   using SubRangeIteratorPair =
326       std::pair<const LiveInterval::SubRange *, LiveInterval::const_iterator>;
327 
328   SmallVector<SubRangeIteratorPair, 4> SubRanges;
329   SlotIndex First;
330   SlotIndex Last;
331   for (const LiveInterval::SubRange &SR : LI.subranges()) {
332     SubRanges.push_back(std::make_pair(&SR, SR.begin()));
333     if (!First.isValid() || SR.segments.front().start < First)
334       First = SR.segments.front().start;
335     if (!Last.isValid() || SR.segments.back().end > Last)
336       Last = SR.segments.back().end;
337   }
338 
339   // Check all mbb start positions between First and Last while
340   // simultaneously advancing an iterator for each subrange.
341   for (SlotIndexes::MBBIndexIterator MBBI = Indexes->getMBBLowerBound(First);
342        MBBI != Indexes->MBBIndexEnd() && MBBI->first <= Last; ++MBBI) {
343     SlotIndex MBBBegin = MBBI->first;
344     // Advance all subrange iterators so that their end position is just
345     // behind MBBBegin (or the iterator is at the end).
346     LaneBitmask LaneMask;
347     for (auto &RangeIterPair : SubRanges) {
348       const LiveInterval::SubRange *SR = RangeIterPair.first;
349       LiveInterval::const_iterator &SRI = RangeIterPair.second;
350       while (SRI != SR->end() && SRI->end <= MBBBegin)
351         ++SRI;
352       if (SRI == SR->end())
353         continue;
354       if (SRI->start <= MBBBegin)
355         LaneMask |= SR->LaneMask;
356     }
357     if (LaneMask.none())
358       continue;
359     MachineBasicBlock *MBB = MBBI->second;
360     MBB->addLiveIn(PhysReg, LaneMask);
361   }
362 }
363 
364 // Compute MBB live-in lists from virtual register live ranges and their
365 // assignments.
366 void VirtRegRewriter::addMBBLiveIns() {
367   for (unsigned Idx = 0, IdxE = MRI->getNumVirtRegs(); Idx != IdxE; ++Idx) {
368     Register VirtReg = Register::index2VirtReg(Idx);
369     if (MRI->reg_nodbg_empty(VirtReg))
370       continue;
371     LiveInterval &LI = LIS->getInterval(VirtReg);
372     if (LI.empty() || LIS->intervalIsInOneMBB(LI))
373       continue;
374     // This is a virtual register that is live across basic blocks. Its
375     // assigned PhysReg must be marked as live-in to those blocks.
376     MCRegister PhysReg = VRM->getPhys(VirtReg);
377     if (!PhysReg) {
378       // There may be no physical register assigned if only some register
379       // classes were already allocated.
380       assert(!ClearVirtRegs && "Unmapped virtual register");
381       continue;
382     }
383 
384     if (LI.hasSubRanges()) {
385       addLiveInsForSubRanges(LI, PhysReg);
386     } else {
387       // Go over MBB begin positions and see if we have segments covering them.
388       // The following works because segments and the MBBIndex list are both
389       // sorted by slot indexes.
390       SlotIndexes::MBBIndexIterator I = Indexes->MBBIndexBegin();
391       for (const auto &Seg : LI) {
392         I = Indexes->getMBBLowerBound(I, Seg.start);
393         for (; I != Indexes->MBBIndexEnd() && I->first < Seg.end; ++I) {
394           MachineBasicBlock *MBB = I->second;
395           MBB->addLiveIn(PhysReg);
396         }
397       }
398     }
399   }
400 
401   // Sort and unique MBB LiveIns as we've not checked if SubReg/PhysReg were in
402   // each MBB's LiveIns set before calling addLiveIn on them.
403   for (MachineBasicBlock &MBB : *MF)
404     MBB.sortUniqueLiveIns();
405 }
406 
407 /// Returns true if the given machine operand \p MO only reads undefined lanes.
408 /// The function only works for use operands with a subregister set.
409 bool VirtRegRewriter::readsUndefSubreg(const MachineOperand &MO) const {
410   // Shortcut if the operand is already marked undef.
411   if (MO.isUndef())
412     return true;
413 
414   Register Reg = MO.getReg();
415   const LiveInterval &LI = LIS->getInterval(Reg);
416   const MachineInstr &MI = *MO.getParent();
417   SlotIndex BaseIndex = LIS->getInstructionIndex(MI);
418   // This code is only meant to handle reading undefined subregisters which
419   // we couldn't properly detect before.
420   assert(LI.liveAt(BaseIndex) &&
421          "Reads of completely dead register should be marked undef already");
422   unsigned SubRegIdx = MO.getSubReg();
423   assert(SubRegIdx != 0 && LI.hasSubRanges());
424   LaneBitmask UseMask = TRI->getSubRegIndexLaneMask(SubRegIdx);
425   // See if any of the relevant subregister liveranges is defined at this point.
426   for (const LiveInterval::SubRange &SR : LI.subranges()) {
427     if ((SR.LaneMask & UseMask).any() && SR.liveAt(BaseIndex))
428       return false;
429   }
430   return true;
431 }
432 
433 void VirtRegRewriter::handleIdentityCopy(MachineInstr &MI) {
434   if (!MI.isIdentityCopy())
435     return;
436   LLVM_DEBUG(dbgs() << "Identity copy: " << MI);
437   ++NumIdCopies;
438 
439   Register DstReg = MI.getOperand(0).getReg();
440 
441   // We may have deferred allocation of the virtual register, and the rewrite
442   // regs code doesn't handle the liveness update.
443   if (DstReg.isVirtual())
444     return;
445 
446   RewriteRegs.insert(DstReg);
447 
448   // Copies like:
449   //    %r0 = COPY undef %r0
450   //    %al = COPY %al, implicit-def %eax
451   // give us additional liveness information: The target (super-)register
452   // must not be valid before this point. Replace the COPY with a KILL
453   // instruction to maintain this information.
454   if (MI.getOperand(1).isUndef() || MI.getNumOperands() > 2) {
455     MI.setDesc(TII->get(TargetOpcode::KILL));
456     LLVM_DEBUG(dbgs() << "  replace by: " << MI);
457     return;
458   }
459 
460   if (Indexes)
461     Indexes->removeSingleMachineInstrFromMaps(MI);
462   MI.eraseFromBundle();
463   LLVM_DEBUG(dbgs() << "  deleted.\n");
464 }
465 
466 /// The liverange splitting logic sometimes produces bundles of copies when
467 /// subregisters are involved. Expand these into a sequence of copy instructions
468 /// after processing the last in the bundle. Does not update LiveIntervals
469 /// which we shouldn't need for this instruction anymore.
470 void VirtRegRewriter::expandCopyBundle(MachineInstr &MI) const {
471   if (!MI.isCopy() && !MI.isKill())
472     return;
473 
474   if (MI.isBundledWithPred() && !MI.isBundledWithSucc()) {
475     SmallVector<MachineInstr *, 2> MIs({&MI});
476 
477     // Only do this when the complete bundle is made out of COPYs and KILLs.
478     MachineBasicBlock &MBB = *MI.getParent();
479     for (MachineBasicBlock::reverse_instr_iterator I =
480          std::next(MI.getReverseIterator()), E = MBB.instr_rend();
481          I != E && I->isBundledWithSucc(); ++I) {
482       if (!I->isCopy() && !I->isKill())
483         return;
484       MIs.push_back(&*I);
485     }
486     MachineInstr *FirstMI = MIs.back();
487 
488     auto anyRegsAlias = [](const MachineInstr *Dst,
489                            ArrayRef<MachineInstr *> Srcs,
490                            const TargetRegisterInfo *TRI) {
491       for (const MachineInstr *Src : Srcs)
492         if (Src != Dst)
493           if (TRI->regsOverlap(Dst->getOperand(0).getReg(),
494                                Src->getOperand(1).getReg()))
495             return true;
496       return false;
497     };
498 
499     // If any of the destination registers in the bundle of copies alias any of
500     // the source registers, try to schedule the instructions to avoid any
501     // clobbering.
502     for (int E = MIs.size(), PrevE = E; E > 1; PrevE = E) {
503       for (int I = E; I--; )
504         if (!anyRegsAlias(MIs[I], ArrayRef(MIs).take_front(E), TRI)) {
505           if (I + 1 != E)
506             std::swap(MIs[I], MIs[E - 1]);
507           --E;
508         }
509       if (PrevE == E) {
510         MF->getFunction().getContext().emitError(
511             "register rewriting failed: cycle in copy bundle");
512         break;
513       }
514     }
515 
516     MachineInstr *BundleStart = FirstMI;
517     for (MachineInstr *BundledMI : llvm::reverse(MIs)) {
518       // If instruction is in the middle of the bundle, move it before the
519       // bundle starts, otherwise, just unbundle it. When we get to the last
520       // instruction, the bundle will have been completely undone.
521       if (BundledMI != BundleStart) {
522         BundledMI->removeFromBundle();
523         MBB.insert(BundleStart, BundledMI);
524       } else if (BundledMI->isBundledWithSucc()) {
525         BundledMI->unbundleFromSucc();
526         BundleStart = &*std::next(BundledMI->getIterator());
527       }
528 
529       if (Indexes && BundledMI != FirstMI)
530         Indexes->insertMachineInstrInMaps(*BundledMI);
531     }
532   }
533 }
534 
535 /// Check whether (part of) \p SuperPhysReg is live through \p MI.
536 /// \pre \p MI defines a subregister of a virtual register that
537 /// has been assigned to \p SuperPhysReg.
538 bool VirtRegRewriter::subRegLiveThrough(const MachineInstr &MI,
539                                         MCRegister SuperPhysReg) const {
540   SlotIndex MIIndex = LIS->getInstructionIndex(MI);
541   SlotIndex BeforeMIUses = MIIndex.getBaseIndex();
542   SlotIndex AfterMIDefs = MIIndex.getBoundaryIndex();
543   for (MCRegUnit Unit : TRI->regunits(SuperPhysReg)) {
544     const LiveRange &UnitRange = LIS->getRegUnit(Unit);
545     // If the regunit is live both before and after MI,
546     // we assume it is live through.
547     // Generally speaking, this is not true, because something like
548     // "RU = op RU" would match that description.
549     // However, we know that we are trying to assess whether
550     // a def of a virtual reg, vreg, is live at the same time of RU.
551     // If we are in the "RU = op RU" situation, that means that vreg
552     // is defined at the same time as RU (i.e., "vreg, RU = op RU").
553     // Thus, vreg and RU interferes and vreg cannot be assigned to
554     // SuperPhysReg. Therefore, this situation cannot happen.
555     if (UnitRange.liveAt(AfterMIDefs) && UnitRange.liveAt(BeforeMIUses))
556       return true;
557   }
558   return false;
559 }
560 
561 /// Compute a lanemask for undef lanes which need to be preserved out of the
562 /// defining block for a register assignment for a subregister def. \p PhysReg
563 /// is assigned to \p LI, which is the main range.
564 LaneBitmask VirtRegRewriter::liveOutUndefPhiLanesForUndefSubregDef(
565     const LiveInterval &LI, const MachineBasicBlock &MBB, unsigned SubReg,
566     MCRegister PhysReg, const MachineInstr &MI) const {
567   LaneBitmask UndefMask = ~TRI->getSubRegIndexLaneMask(SubReg);
568   LaneBitmask LiveOutUndefLanes;
569 
570   for (const LiveInterval::SubRange &SR : LI.subranges()) {
571     // Figure out which lanes are undef live into a successor.
572     LaneBitmask NeedImpDefLanes = UndefMask & SR.LaneMask;
573     if (NeedImpDefLanes.any() && !LIS->isLiveOutOfMBB(SR, &MBB)) {
574       for (const MachineBasicBlock *Succ : MBB.successors()) {
575         if (LIS->isLiveInToMBB(SR, Succ))
576           LiveOutUndefLanes |= NeedImpDefLanes;
577       }
578     }
579   }
580 
581   SlotIndex MIIndex = LIS->getInstructionIndex(MI);
582   SlotIndex BeforeMIUses = MIIndex.getBaseIndex();
583   LaneBitmask InterferingLanes =
584       LRM->checkInterferenceLanes(BeforeMIUses, MIIndex.getRegSlot(), PhysReg);
585   LiveOutUndefLanes &= ~InterferingLanes;
586 
587   LLVM_DEBUG(if (LiveOutUndefLanes.any()) {
588     dbgs() << "Need live out undef defs for " << printReg(PhysReg)
589            << LiveOutUndefLanes << " from " << printMBBReference(MBB) << '\n';
590   });
591 
592   return LiveOutUndefLanes;
593 }
594 
595 void VirtRegRewriter::rewrite() {
596   bool NoSubRegLiveness = !MRI->subRegLivenessEnabled();
597   SmallVector<Register, 8> SuperDeads;
598   SmallVector<Register, 8> SuperDefs;
599   SmallVector<Register, 8> SuperKills;
600 
601   for (MachineFunction::iterator MBBI = MF->begin(), MBBE = MF->end();
602        MBBI != MBBE; ++MBBI) {
603     LLVM_DEBUG(MBBI->print(dbgs(), Indexes));
604     for (MachineInstr &MI : llvm::make_early_inc_range(MBBI->instrs())) {
605       for (MachineOperand &MO : MI.operands()) {
606         // Make sure MRI knows about registers clobbered by regmasks.
607         if (MO.isRegMask())
608           MRI->addPhysRegsUsedFromRegMask(MO.getRegMask());
609 
610         if (!MO.isReg() || !MO.getReg().isVirtual())
611           continue;
612         Register VirtReg = MO.getReg();
613         MCRegister PhysReg = VRM->getPhys(VirtReg);
614         if (!PhysReg)
615           continue;
616 
617         assert(Register(PhysReg).isPhysical());
618 
619         RewriteRegs.insert(PhysReg);
620         assert((!MRI->isReserved(PhysReg) ||
621                 MF->getProperties().hasProperty(
622                     MachineFunctionProperties::Property::FailedRegAlloc)) &&
623                "Reserved register assignment");
624 
625         // Preserve semantics of sub-register operands.
626         unsigned SubReg = MO.getSubReg();
627         if (SubReg != 0) {
628           if (NoSubRegLiveness || !MRI->shouldTrackSubRegLiveness(VirtReg)) {
629             // A virtual register kill refers to the whole register, so we may
630             // have to add implicit killed operands for the super-register.  A
631             // partial redef always kills and redefines the super-register.
632             if ((MO.readsReg() && (MO.isDef() || MO.isKill())) ||
633                 (MO.isDef() && subRegLiveThrough(MI, PhysReg)))
634               SuperKills.push_back(PhysReg);
635 
636             if (MO.isDef()) {
637               // Also add implicit defs for the super-register.
638               if (MO.isDead())
639                 SuperDeads.push_back(PhysReg);
640               else
641                 SuperDefs.push_back(PhysReg);
642             }
643           } else {
644             if (MO.isUse()) {
645               if (readsUndefSubreg(MO))
646                 // We need to add an <undef> flag if the subregister is
647                 // completely undefined (and we are not adding super-register
648                 // defs).
649                 MO.setIsUndef(true);
650             } else if (!MO.isDead()) {
651               assert(MO.isDef());
652               if (MO.isUndef()) {
653                 const LiveInterval &LI = LIS->getInterval(VirtReg);
654 
655                 LaneBitmask LiveOutUndefLanes =
656                     liveOutUndefPhiLanesForUndefSubregDef(LI, *MBBI, SubReg,
657                                                           PhysReg, MI);
658                 if (LiveOutUndefLanes.any()) {
659                   SmallVector<unsigned, 16> CoveringIndexes;
660 
661                   // TODO: Just use one super register def if none of the lanes
662                   // are needed?
663                   if (!TRI->getCoveringSubRegIndexes(MRI->getRegClass(VirtReg),
664                                                      LiveOutUndefLanes,
665                                                      CoveringIndexes))
666                     llvm_unreachable(
667                         "cannot represent required subregister defs");
668 
669                   // Try to represent the minimum needed live out def as a
670                   // sequence of subregister defs.
671                   //
672                   // FIXME: It would be better if we could directly represent
673                   // liveness with a lanemask instead of spamming operands.
674                   for (unsigned SubIdx : CoveringIndexes)
675                     SuperDefs.push_back(TRI->getSubReg(PhysReg, SubIdx));
676                 }
677               }
678             }
679           }
680 
681           // The def undef and def internal flags only make sense for
682           // sub-register defs, and we are substituting a full physreg.  An
683           // implicit killed operand from the SuperKills list will represent the
684           // partial read of the super-register.
685           if (MO.isDef()) {
686             MO.setIsUndef(false);
687             MO.setIsInternalRead(false);
688           }
689 
690           // PhysReg operands cannot have subregister indexes.
691           PhysReg = TRI->getSubReg(PhysReg, SubReg);
692           assert(PhysReg.isValid() && "Invalid SubReg for physical register");
693           MO.setSubReg(0);
694         }
695         // Rewrite. Note we could have used MachineOperand::substPhysReg(), but
696         // we need the inlining here.
697         MO.setReg(PhysReg);
698         MO.setIsRenamable(true);
699       }
700 
701       // Add any missing super-register kills after rewriting the whole
702       // instruction.
703       while (!SuperKills.empty())
704         MI.addRegisterKilled(SuperKills.pop_back_val(), TRI, true);
705 
706       while (!SuperDeads.empty())
707         MI.addRegisterDead(SuperDeads.pop_back_val(), TRI, true);
708 
709       while (!SuperDefs.empty())
710         MI.addRegisterDefined(SuperDefs.pop_back_val(), TRI);
711 
712       LLVM_DEBUG(dbgs() << "> " << MI);
713 
714       expandCopyBundle(MI);
715 
716       // We can remove identity copies right now.
717       handleIdentityCopy(MI);
718     }
719   }
720 
721   if (LIS) {
722     // Don't bother maintaining accurate LiveIntervals for registers which were
723     // already allocated.
724     for (Register PhysReg : RewriteRegs) {
725       for (MCRegUnit Unit : TRI->regunits(PhysReg)) {
726         LIS->removeRegUnit(Unit);
727       }
728     }
729   }
730 
731   RewriteRegs.clear();
732 }
733 
734 FunctionPass *llvm::createVirtRegRewriter(bool ClearVirtRegs) {
735   return new VirtRegRewriter(ClearVirtRegs);
736 }
737