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