xref: /openbsd-src/gnu/llvm/llvm/lib/CodeGen/VirtRegMap.cpp (revision d415bd752c734aee168c4ee86ff32e8cc249eb16)
109467b48Spatrick //===- llvm/CodeGen/VirtRegMap.cpp - Virtual Register Map -----------------===//
209467b48Spatrick //
309467b48Spatrick // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
409467b48Spatrick // See https://llvm.org/LICENSE.txt for license information.
509467b48Spatrick // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
609467b48Spatrick //
709467b48Spatrick //===----------------------------------------------------------------------===//
809467b48Spatrick //
909467b48Spatrick // This file implements the VirtRegMap class.
1009467b48Spatrick //
1109467b48Spatrick // It also contains implementations of the Spiller interface, which, given a
1209467b48Spatrick // virtual register map and a machine function, eliminates all virtual
1309467b48Spatrick // references by replacing them with physical register references - adding spill
1409467b48Spatrick // code as necessary.
1509467b48Spatrick //
1609467b48Spatrick //===----------------------------------------------------------------------===//
1709467b48Spatrick 
1809467b48Spatrick #include "llvm/CodeGen/VirtRegMap.h"
1909467b48Spatrick #include "LiveDebugVariables.h"
2009467b48Spatrick #include "llvm/ADT/SmallVector.h"
2109467b48Spatrick #include "llvm/ADT/Statistic.h"
2209467b48Spatrick #include "llvm/CodeGen/LiveInterval.h"
2309467b48Spatrick #include "llvm/CodeGen/LiveIntervals.h"
2409467b48Spatrick #include "llvm/CodeGen/LiveStacks.h"
2509467b48Spatrick #include "llvm/CodeGen/MachineBasicBlock.h"
2609467b48Spatrick #include "llvm/CodeGen/MachineFrameInfo.h"
2709467b48Spatrick #include "llvm/CodeGen/MachineFunction.h"
2809467b48Spatrick #include "llvm/CodeGen/MachineFunctionPass.h"
2909467b48Spatrick #include "llvm/CodeGen/MachineInstr.h"
3009467b48Spatrick #include "llvm/CodeGen/MachineOperand.h"
3109467b48Spatrick #include "llvm/CodeGen/MachineRegisterInfo.h"
3209467b48Spatrick #include "llvm/CodeGen/SlotIndexes.h"
3373471bf0Spatrick #include "llvm/CodeGen/TargetFrameLowering.h"
3409467b48Spatrick #include "llvm/CodeGen/TargetInstrInfo.h"
3509467b48Spatrick #include "llvm/CodeGen/TargetOpcodes.h"
3609467b48Spatrick #include "llvm/CodeGen/TargetRegisterInfo.h"
3709467b48Spatrick #include "llvm/CodeGen/TargetSubtargetInfo.h"
3809467b48Spatrick #include "llvm/Config/llvm-config.h"
3909467b48Spatrick #include "llvm/MC/LaneBitmask.h"
4009467b48Spatrick #include "llvm/Pass.h"
4109467b48Spatrick #include "llvm/Support/Compiler.h"
4209467b48Spatrick #include "llvm/Support/Debug.h"
4309467b48Spatrick #include "llvm/Support/raw_ostream.h"
4409467b48Spatrick #include <cassert>
4509467b48Spatrick #include <iterator>
4609467b48Spatrick #include <utility>
4709467b48Spatrick 
4809467b48Spatrick using namespace llvm;
4909467b48Spatrick 
5009467b48Spatrick #define DEBUG_TYPE "regalloc"
5109467b48Spatrick 
5209467b48Spatrick STATISTIC(NumSpillSlots, "Number of spill slots allocated");
5309467b48Spatrick STATISTIC(NumIdCopies,   "Number of identity moves eliminated after rewriting");
5409467b48Spatrick 
5509467b48Spatrick //===----------------------------------------------------------------------===//
5609467b48Spatrick //  VirtRegMap implementation
5709467b48Spatrick //===----------------------------------------------------------------------===//
5809467b48Spatrick 
5909467b48Spatrick char VirtRegMap::ID = 0;
6009467b48Spatrick 
6109467b48Spatrick INITIALIZE_PASS(VirtRegMap, "virtregmap", "Virtual Register Map", false, false)
6209467b48Spatrick 
runOnMachineFunction(MachineFunction & mf)6309467b48Spatrick bool VirtRegMap::runOnMachineFunction(MachineFunction &mf) {
6409467b48Spatrick   MRI = &mf.getRegInfo();
6509467b48Spatrick   TII = mf.getSubtarget().getInstrInfo();
6609467b48Spatrick   TRI = mf.getSubtarget().getRegisterInfo();
6709467b48Spatrick   MF = &mf;
6809467b48Spatrick 
6909467b48Spatrick   Virt2PhysMap.clear();
7009467b48Spatrick   Virt2StackSlotMap.clear();
7109467b48Spatrick   Virt2SplitMap.clear();
7273471bf0Spatrick   Virt2ShapeMap.clear();
7309467b48Spatrick 
7409467b48Spatrick   grow();
7509467b48Spatrick   return false;
7609467b48Spatrick }
7709467b48Spatrick 
grow()7809467b48Spatrick void VirtRegMap::grow() {
7909467b48Spatrick   unsigned NumRegs = MF->getRegInfo().getNumVirtRegs();
8009467b48Spatrick   Virt2PhysMap.resize(NumRegs);
8109467b48Spatrick   Virt2StackSlotMap.resize(NumRegs);
8209467b48Spatrick   Virt2SplitMap.resize(NumRegs);
8309467b48Spatrick }
8409467b48Spatrick 
assignVirt2Phys(Register virtReg,MCPhysReg physReg)8509467b48Spatrick void VirtRegMap::assignVirt2Phys(Register virtReg, MCPhysReg physReg) {
8609467b48Spatrick   assert(virtReg.isVirtual() && Register::isPhysicalRegister(physReg));
8709467b48Spatrick   assert(Virt2PhysMap[virtReg.id()] == NO_PHYS_REG &&
8809467b48Spatrick          "attempt to assign physical register to already mapped "
8909467b48Spatrick          "virtual register");
9009467b48Spatrick   assert(!getRegInfo().isReserved(physReg) &&
9109467b48Spatrick          "Attempt to map virtReg to a reserved physReg");
9209467b48Spatrick   Virt2PhysMap[virtReg.id()] = physReg;
9309467b48Spatrick }
9409467b48Spatrick 
createSpillSlot(const TargetRegisterClass * RC)9509467b48Spatrick unsigned VirtRegMap::createSpillSlot(const TargetRegisterClass *RC) {
9609467b48Spatrick   unsigned Size = TRI->getSpillSize(*RC);
97097a140dSpatrick   Align Alignment = TRI->getSpillAlign(*RC);
9873471bf0Spatrick   // Set preferred alignment if we are still able to realign the stack
9973471bf0Spatrick   auto &ST = MF->getSubtarget();
10073471bf0Spatrick   Align CurrentAlign = ST.getFrameLowering()->getStackAlign();
10173471bf0Spatrick   if (Alignment > CurrentAlign && !ST.getRegisterInfo()->canRealignStack(*MF)) {
10273471bf0Spatrick     Alignment = CurrentAlign;
10373471bf0Spatrick   }
104097a140dSpatrick   int SS = MF->getFrameInfo().CreateSpillStackObject(Size, Alignment);
10509467b48Spatrick   ++NumSpillSlots;
10609467b48Spatrick   return SS;
10709467b48Spatrick }
10809467b48Spatrick 
hasPreferredPhys(Register VirtReg) const10973471bf0Spatrick bool VirtRegMap::hasPreferredPhys(Register VirtReg) const {
11009467b48Spatrick   Register Hint = MRI->getSimpleHint(VirtReg);
11109467b48Spatrick   if (!Hint.isValid())
11209467b48Spatrick     return false;
11309467b48Spatrick   if (Hint.isVirtual())
11409467b48Spatrick     Hint = getPhys(Hint);
11573471bf0Spatrick   return Register(getPhys(VirtReg)) == Hint;
11609467b48Spatrick }
11709467b48Spatrick 
hasKnownPreference(Register VirtReg) const11873471bf0Spatrick bool VirtRegMap::hasKnownPreference(Register VirtReg) const {
11909467b48Spatrick   std::pair<unsigned, unsigned> Hint = MRI->getRegAllocationHint(VirtReg);
12009467b48Spatrick   if (Register::isPhysicalRegister(Hint.second))
12109467b48Spatrick     return true;
12209467b48Spatrick   if (Register::isVirtualRegister(Hint.second))
12309467b48Spatrick     return hasPhys(Hint.second);
12409467b48Spatrick   return false;
12509467b48Spatrick }
12609467b48Spatrick 
assignVirt2StackSlot(Register virtReg)12709467b48Spatrick int VirtRegMap::assignVirt2StackSlot(Register virtReg) {
12809467b48Spatrick   assert(virtReg.isVirtual());
12909467b48Spatrick   assert(Virt2StackSlotMap[virtReg.id()] == NO_STACK_SLOT &&
13009467b48Spatrick          "attempt to assign stack slot to already spilled register");
13109467b48Spatrick   const TargetRegisterClass* RC = MF->getRegInfo().getRegClass(virtReg);
13209467b48Spatrick   return Virt2StackSlotMap[virtReg.id()] = createSpillSlot(RC);
13309467b48Spatrick }
13409467b48Spatrick 
assignVirt2StackSlot(Register virtReg,int SS)13509467b48Spatrick void VirtRegMap::assignVirt2StackSlot(Register virtReg, int SS) {
13609467b48Spatrick   assert(virtReg.isVirtual());
13709467b48Spatrick   assert(Virt2StackSlotMap[virtReg.id()] == NO_STACK_SLOT &&
13809467b48Spatrick          "attempt to assign stack slot to already spilled register");
13909467b48Spatrick   assert((SS >= 0 ||
14009467b48Spatrick           (SS >= MF->getFrameInfo().getObjectIndexBegin())) &&
14109467b48Spatrick          "illegal fixed frame index");
14209467b48Spatrick   Virt2StackSlotMap[virtReg.id()] = SS;
14309467b48Spatrick }
14409467b48Spatrick 
print(raw_ostream & OS,const Module *) const14509467b48Spatrick void VirtRegMap::print(raw_ostream &OS, const Module*) const {
14609467b48Spatrick   OS << "********** REGISTER MAP **********\n";
14709467b48Spatrick   for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
148*d415bd75Srobert     Register Reg = Register::index2VirtReg(i);
14909467b48Spatrick     if (Virt2PhysMap[Reg] != (unsigned)VirtRegMap::NO_PHYS_REG) {
15009467b48Spatrick       OS << '[' << printReg(Reg, TRI) << " -> "
15109467b48Spatrick          << printReg(Virt2PhysMap[Reg], TRI) << "] "
15209467b48Spatrick          << TRI->getRegClassName(MRI->getRegClass(Reg)) << "\n";
15309467b48Spatrick     }
15409467b48Spatrick   }
15509467b48Spatrick 
15609467b48Spatrick   for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
157*d415bd75Srobert     Register Reg = Register::index2VirtReg(i);
15809467b48Spatrick     if (Virt2StackSlotMap[Reg] != VirtRegMap::NO_STACK_SLOT) {
15909467b48Spatrick       OS << '[' << printReg(Reg, TRI) << " -> fi#" << Virt2StackSlotMap[Reg]
16009467b48Spatrick          << "] " << TRI->getRegClassName(MRI->getRegClass(Reg)) << "\n";
16109467b48Spatrick     }
16209467b48Spatrick   }
16309467b48Spatrick   OS << '\n';
16409467b48Spatrick }
16509467b48Spatrick 
16609467b48Spatrick #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
dump() const16709467b48Spatrick LLVM_DUMP_METHOD void VirtRegMap::dump() const {
16809467b48Spatrick   print(dbgs());
16909467b48Spatrick }
17009467b48Spatrick #endif
17109467b48Spatrick 
17209467b48Spatrick //===----------------------------------------------------------------------===//
17309467b48Spatrick //                              VirtRegRewriter
17409467b48Spatrick //===----------------------------------------------------------------------===//
17509467b48Spatrick //
17609467b48Spatrick // The VirtRegRewriter is the last of the register allocator passes.
17709467b48Spatrick // It rewrites virtual registers to physical registers as specified in the
17809467b48Spatrick // VirtRegMap analysis. It also updates live-in information on basic blocks
17909467b48Spatrick // according to LiveIntervals.
18009467b48Spatrick //
18109467b48Spatrick namespace {
18209467b48Spatrick 
18309467b48Spatrick class VirtRegRewriter : public MachineFunctionPass {
18409467b48Spatrick   MachineFunction *MF;
18509467b48Spatrick   const TargetRegisterInfo *TRI;
18609467b48Spatrick   const TargetInstrInfo *TII;
18709467b48Spatrick   MachineRegisterInfo *MRI;
18809467b48Spatrick   SlotIndexes *Indexes;
18909467b48Spatrick   LiveIntervals *LIS;
19009467b48Spatrick   VirtRegMap *VRM;
19173471bf0Spatrick   LiveDebugVariables *DebugVars;
19273471bf0Spatrick   DenseSet<Register> RewriteRegs;
19373471bf0Spatrick   bool ClearVirtRegs;
19409467b48Spatrick 
19509467b48Spatrick   void rewrite();
19609467b48Spatrick   void addMBBLiveIns();
19709467b48Spatrick   bool readsUndefSubreg(const MachineOperand &MO) const;
19873471bf0Spatrick   void addLiveInsForSubRanges(const LiveInterval &LI, MCRegister PhysReg) const;
19973471bf0Spatrick   void handleIdentityCopy(MachineInstr &MI);
20009467b48Spatrick   void expandCopyBundle(MachineInstr &MI) const;
20173471bf0Spatrick   bool subRegLiveThrough(const MachineInstr &MI, MCRegister SuperPhysReg) const;
20209467b48Spatrick 
20309467b48Spatrick public:
20409467b48Spatrick   static char ID;
VirtRegRewriter(bool ClearVirtRegs_=true)20573471bf0Spatrick   VirtRegRewriter(bool ClearVirtRegs_ = true) :
20673471bf0Spatrick     MachineFunctionPass(ID),
20773471bf0Spatrick     ClearVirtRegs(ClearVirtRegs_) {}
20809467b48Spatrick 
20909467b48Spatrick   void getAnalysisUsage(AnalysisUsage &AU) const override;
21009467b48Spatrick 
21109467b48Spatrick   bool runOnMachineFunction(MachineFunction&) override;
21209467b48Spatrick 
getSetProperties() const21309467b48Spatrick   MachineFunctionProperties getSetProperties() const override {
21473471bf0Spatrick     if (ClearVirtRegs) {
21509467b48Spatrick       return MachineFunctionProperties().set(
21609467b48Spatrick         MachineFunctionProperties::Property::NoVRegs);
21709467b48Spatrick     }
21873471bf0Spatrick 
21973471bf0Spatrick     return MachineFunctionProperties();
22073471bf0Spatrick   }
22109467b48Spatrick };
22209467b48Spatrick 
22309467b48Spatrick } // end anonymous namespace
22409467b48Spatrick 
22509467b48Spatrick char VirtRegRewriter::ID = 0;
22609467b48Spatrick 
22709467b48Spatrick char &llvm::VirtRegRewriterID = VirtRegRewriter::ID;
22809467b48Spatrick 
22909467b48Spatrick INITIALIZE_PASS_BEGIN(VirtRegRewriter, "virtregrewriter",
23009467b48Spatrick                       "Virtual Register Rewriter", false, false)
INITIALIZE_PASS_DEPENDENCY(SlotIndexes)23109467b48Spatrick INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
23209467b48Spatrick INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
23309467b48Spatrick INITIALIZE_PASS_DEPENDENCY(LiveDebugVariables)
23409467b48Spatrick INITIALIZE_PASS_DEPENDENCY(LiveStacks)
23509467b48Spatrick INITIALIZE_PASS_DEPENDENCY(VirtRegMap)
23609467b48Spatrick INITIALIZE_PASS_END(VirtRegRewriter, "virtregrewriter",
23709467b48Spatrick                     "Virtual Register Rewriter", false, false)
23809467b48Spatrick 
23909467b48Spatrick void VirtRegRewriter::getAnalysisUsage(AnalysisUsage &AU) const {
24009467b48Spatrick   AU.setPreservesCFG();
24109467b48Spatrick   AU.addRequired<LiveIntervals>();
24273471bf0Spatrick   AU.addPreserved<LiveIntervals>();
24309467b48Spatrick   AU.addRequired<SlotIndexes>();
24409467b48Spatrick   AU.addPreserved<SlotIndexes>();
24509467b48Spatrick   AU.addRequired<LiveDebugVariables>();
24609467b48Spatrick   AU.addRequired<LiveStacks>();
24709467b48Spatrick   AU.addPreserved<LiveStacks>();
24809467b48Spatrick   AU.addRequired<VirtRegMap>();
24973471bf0Spatrick 
25073471bf0Spatrick   if (!ClearVirtRegs)
25173471bf0Spatrick     AU.addPreserved<LiveDebugVariables>();
25273471bf0Spatrick 
25309467b48Spatrick   MachineFunctionPass::getAnalysisUsage(AU);
25409467b48Spatrick }
25509467b48Spatrick 
runOnMachineFunction(MachineFunction & fn)25609467b48Spatrick bool VirtRegRewriter::runOnMachineFunction(MachineFunction &fn) {
25709467b48Spatrick   MF = &fn;
25809467b48Spatrick   TRI = MF->getSubtarget().getRegisterInfo();
25909467b48Spatrick   TII = MF->getSubtarget().getInstrInfo();
26009467b48Spatrick   MRI = &MF->getRegInfo();
26109467b48Spatrick   Indexes = &getAnalysis<SlotIndexes>();
26209467b48Spatrick   LIS = &getAnalysis<LiveIntervals>();
26309467b48Spatrick   VRM = &getAnalysis<VirtRegMap>();
26473471bf0Spatrick   DebugVars = getAnalysisIfAvailable<LiveDebugVariables>();
26509467b48Spatrick   LLVM_DEBUG(dbgs() << "********** REWRITE VIRTUAL REGISTERS **********\n"
26609467b48Spatrick                     << "********** Function: " << MF->getName() << '\n');
26709467b48Spatrick   LLVM_DEBUG(VRM->dump());
26809467b48Spatrick 
26909467b48Spatrick   // Add kill flags while we still have virtual registers.
27009467b48Spatrick   LIS->addKillFlags(VRM);
27109467b48Spatrick 
27209467b48Spatrick   // Live-in lists on basic blocks are required for physregs.
27309467b48Spatrick   addMBBLiveIns();
27409467b48Spatrick 
27509467b48Spatrick   // Rewrite virtual registers.
27609467b48Spatrick   rewrite();
27709467b48Spatrick 
27873471bf0Spatrick   if (DebugVars && ClearVirtRegs) {
27909467b48Spatrick     // Write out new DBG_VALUE instructions.
28073471bf0Spatrick 
28173471bf0Spatrick     // We only do this if ClearVirtRegs is specified since this should be the
28273471bf0Spatrick     // final run of the pass and we don't want to emit them multiple times.
28373471bf0Spatrick     DebugVars->emitDebugValues(VRM);
28409467b48Spatrick 
28509467b48Spatrick     // All machine operands and other references to virtual registers have been
28609467b48Spatrick     // replaced. Remove the virtual registers and release all the transient data.
28709467b48Spatrick     VRM->clearAllVirt();
28809467b48Spatrick     MRI->clearVirtRegs();
28973471bf0Spatrick   }
29073471bf0Spatrick 
29109467b48Spatrick   return true;
29209467b48Spatrick }
29309467b48Spatrick 
addLiveInsForSubRanges(const LiveInterval & LI,MCRegister PhysReg) const29409467b48Spatrick void VirtRegRewriter::addLiveInsForSubRanges(const LiveInterval &LI,
29573471bf0Spatrick                                              MCRegister PhysReg) const {
29609467b48Spatrick   assert(!LI.empty());
29709467b48Spatrick   assert(LI.hasSubRanges());
29809467b48Spatrick 
29909467b48Spatrick   using SubRangeIteratorPair =
30009467b48Spatrick       std::pair<const LiveInterval::SubRange *, LiveInterval::const_iterator>;
30109467b48Spatrick 
30209467b48Spatrick   SmallVector<SubRangeIteratorPair, 4> SubRanges;
30309467b48Spatrick   SlotIndex First;
30409467b48Spatrick   SlotIndex Last;
30509467b48Spatrick   for (const LiveInterval::SubRange &SR : LI.subranges()) {
30609467b48Spatrick     SubRanges.push_back(std::make_pair(&SR, SR.begin()));
30709467b48Spatrick     if (!First.isValid() || SR.segments.front().start < First)
30809467b48Spatrick       First = SR.segments.front().start;
30909467b48Spatrick     if (!Last.isValid() || SR.segments.back().end > Last)
31009467b48Spatrick       Last = SR.segments.back().end;
31109467b48Spatrick   }
31209467b48Spatrick 
31309467b48Spatrick   // Check all mbb start positions between First and Last while
31409467b48Spatrick   // simulatenously advancing an iterator for each subrange.
31509467b48Spatrick   for (SlotIndexes::MBBIndexIterator MBBI = Indexes->findMBBIndex(First);
31609467b48Spatrick        MBBI != Indexes->MBBIndexEnd() && MBBI->first <= Last; ++MBBI) {
31709467b48Spatrick     SlotIndex MBBBegin = MBBI->first;
31809467b48Spatrick     // Advance all subrange iterators so that their end position is just
31909467b48Spatrick     // behind MBBBegin (or the iterator is at the end).
32009467b48Spatrick     LaneBitmask LaneMask;
32109467b48Spatrick     for (auto &RangeIterPair : SubRanges) {
32209467b48Spatrick       const LiveInterval::SubRange *SR = RangeIterPair.first;
32309467b48Spatrick       LiveInterval::const_iterator &SRI = RangeIterPair.second;
32409467b48Spatrick       while (SRI != SR->end() && SRI->end <= MBBBegin)
32509467b48Spatrick         ++SRI;
32609467b48Spatrick       if (SRI == SR->end())
32709467b48Spatrick         continue;
32809467b48Spatrick       if (SRI->start <= MBBBegin)
32909467b48Spatrick         LaneMask |= SR->LaneMask;
33009467b48Spatrick     }
33109467b48Spatrick     if (LaneMask.none())
33209467b48Spatrick       continue;
33309467b48Spatrick     MachineBasicBlock *MBB = MBBI->second;
33409467b48Spatrick     MBB->addLiveIn(PhysReg, LaneMask);
33509467b48Spatrick   }
33609467b48Spatrick }
33709467b48Spatrick 
33809467b48Spatrick // Compute MBB live-in lists from virtual register live ranges and their
33909467b48Spatrick // assignments.
addMBBLiveIns()34009467b48Spatrick void VirtRegRewriter::addMBBLiveIns() {
34109467b48Spatrick   for (unsigned Idx = 0, IdxE = MRI->getNumVirtRegs(); Idx != IdxE; ++Idx) {
34209467b48Spatrick     Register VirtReg = Register::index2VirtReg(Idx);
34309467b48Spatrick     if (MRI->reg_nodbg_empty(VirtReg))
34409467b48Spatrick       continue;
34509467b48Spatrick     LiveInterval &LI = LIS->getInterval(VirtReg);
34609467b48Spatrick     if (LI.empty() || LIS->intervalIsInOneMBB(LI))
34709467b48Spatrick       continue;
34809467b48Spatrick     // This is a virtual register that is live across basic blocks. Its
34909467b48Spatrick     // assigned PhysReg must be marked as live-in to those blocks.
35009467b48Spatrick     Register PhysReg = VRM->getPhys(VirtReg);
35173471bf0Spatrick     if (PhysReg == VirtRegMap::NO_PHYS_REG) {
35273471bf0Spatrick       // There may be no physical register assigned if only some register
35373471bf0Spatrick       // classes were already allocated.
35473471bf0Spatrick       assert(!ClearVirtRegs && "Unmapped virtual register");
35573471bf0Spatrick       continue;
35673471bf0Spatrick     }
35709467b48Spatrick 
35809467b48Spatrick     if (LI.hasSubRanges()) {
35909467b48Spatrick       addLiveInsForSubRanges(LI, PhysReg);
36009467b48Spatrick     } else {
36109467b48Spatrick       // Go over MBB begin positions and see if we have segments covering them.
36209467b48Spatrick       // The following works because segments and the MBBIndex list are both
36309467b48Spatrick       // sorted by slot indexes.
36409467b48Spatrick       SlotIndexes::MBBIndexIterator I = Indexes->MBBIndexBegin();
36509467b48Spatrick       for (const auto &Seg : LI) {
36609467b48Spatrick         I = Indexes->advanceMBBIndex(I, Seg.start);
36709467b48Spatrick         for (; I != Indexes->MBBIndexEnd() && I->first < Seg.end; ++I) {
36809467b48Spatrick           MachineBasicBlock *MBB = I->second;
36909467b48Spatrick           MBB->addLiveIn(PhysReg);
37009467b48Spatrick         }
37109467b48Spatrick       }
37209467b48Spatrick     }
37309467b48Spatrick   }
37409467b48Spatrick 
37509467b48Spatrick   // Sort and unique MBB LiveIns as we've not checked if SubReg/PhysReg were in
37609467b48Spatrick   // each MBB's LiveIns set before calling addLiveIn on them.
37709467b48Spatrick   for (MachineBasicBlock &MBB : *MF)
37809467b48Spatrick     MBB.sortUniqueLiveIns();
37909467b48Spatrick }
38009467b48Spatrick 
38109467b48Spatrick /// Returns true if the given machine operand \p MO only reads undefined lanes.
38209467b48Spatrick /// The function only works for use operands with a subregister set.
readsUndefSubreg(const MachineOperand & MO) const38309467b48Spatrick bool VirtRegRewriter::readsUndefSubreg(const MachineOperand &MO) const {
38409467b48Spatrick   // Shortcut if the operand is already marked undef.
38509467b48Spatrick   if (MO.isUndef())
38609467b48Spatrick     return true;
38709467b48Spatrick 
38809467b48Spatrick   Register Reg = MO.getReg();
38909467b48Spatrick   const LiveInterval &LI = LIS->getInterval(Reg);
39009467b48Spatrick   const MachineInstr &MI = *MO.getParent();
39109467b48Spatrick   SlotIndex BaseIndex = LIS->getInstructionIndex(MI);
39209467b48Spatrick   // This code is only meant to handle reading undefined subregisters which
39309467b48Spatrick   // we couldn't properly detect before.
39409467b48Spatrick   assert(LI.liveAt(BaseIndex) &&
39509467b48Spatrick          "Reads of completely dead register should be marked undef already");
39609467b48Spatrick   unsigned SubRegIdx = MO.getSubReg();
39709467b48Spatrick   assert(SubRegIdx != 0 && LI.hasSubRanges());
39809467b48Spatrick   LaneBitmask UseMask = TRI->getSubRegIndexLaneMask(SubRegIdx);
39909467b48Spatrick   // See if any of the relevant subregister liveranges is defined at this point.
40009467b48Spatrick   for (const LiveInterval::SubRange &SR : LI.subranges()) {
40109467b48Spatrick     if ((SR.LaneMask & UseMask).any() && SR.liveAt(BaseIndex))
40209467b48Spatrick       return false;
40309467b48Spatrick   }
40409467b48Spatrick   return true;
40509467b48Spatrick }
40609467b48Spatrick 
handleIdentityCopy(MachineInstr & MI)40773471bf0Spatrick void VirtRegRewriter::handleIdentityCopy(MachineInstr &MI) {
40809467b48Spatrick   if (!MI.isIdentityCopy())
40909467b48Spatrick     return;
41009467b48Spatrick   LLVM_DEBUG(dbgs() << "Identity copy: " << MI);
41109467b48Spatrick   ++NumIdCopies;
41209467b48Spatrick 
41373471bf0Spatrick   Register DstReg = MI.getOperand(0).getReg();
41473471bf0Spatrick 
41573471bf0Spatrick   // We may have deferred allocation of the virtual register, and the rewrite
41673471bf0Spatrick   // regs code doesn't handle the liveness update.
41773471bf0Spatrick   if (DstReg.isVirtual())
41873471bf0Spatrick     return;
41973471bf0Spatrick 
42073471bf0Spatrick   RewriteRegs.insert(DstReg);
42173471bf0Spatrick 
42209467b48Spatrick   // Copies like:
42309467b48Spatrick   //    %r0 = COPY undef %r0
42409467b48Spatrick   //    %al = COPY %al, implicit-def %eax
42509467b48Spatrick   // give us additional liveness information: The target (super-)register
42609467b48Spatrick   // must not be valid before this point. Replace the COPY with a KILL
42709467b48Spatrick   // instruction to maintain this information.
42809467b48Spatrick   if (MI.getOperand(1).isUndef() || MI.getNumOperands() > 2) {
42909467b48Spatrick     MI.setDesc(TII->get(TargetOpcode::KILL));
43009467b48Spatrick     LLVM_DEBUG(dbgs() << "  replace by: " << MI);
43109467b48Spatrick     return;
43209467b48Spatrick   }
43309467b48Spatrick 
43409467b48Spatrick   if (Indexes)
43509467b48Spatrick     Indexes->removeSingleMachineInstrFromMaps(MI);
43609467b48Spatrick   MI.eraseFromBundle();
43709467b48Spatrick   LLVM_DEBUG(dbgs() << "  deleted.\n");
43809467b48Spatrick }
43909467b48Spatrick 
44009467b48Spatrick /// The liverange splitting logic sometimes produces bundles of copies when
44109467b48Spatrick /// subregisters are involved. Expand these into a sequence of copy instructions
44209467b48Spatrick /// after processing the last in the bundle. Does not update LiveIntervals
44309467b48Spatrick /// which we shouldn't need for this instruction anymore.
expandCopyBundle(MachineInstr & MI) const44409467b48Spatrick void VirtRegRewriter::expandCopyBundle(MachineInstr &MI) const {
44573471bf0Spatrick   if (!MI.isCopy() && !MI.isKill())
44609467b48Spatrick     return;
44709467b48Spatrick 
44809467b48Spatrick   if (MI.isBundledWithPred() && !MI.isBundledWithSucc()) {
44909467b48Spatrick     SmallVector<MachineInstr *, 2> MIs({&MI});
45009467b48Spatrick 
45173471bf0Spatrick     // Only do this when the complete bundle is made out of COPYs and KILLs.
45209467b48Spatrick     MachineBasicBlock &MBB = *MI.getParent();
45309467b48Spatrick     for (MachineBasicBlock::reverse_instr_iterator I =
45409467b48Spatrick          std::next(MI.getReverseIterator()), E = MBB.instr_rend();
45509467b48Spatrick          I != E && I->isBundledWithSucc(); ++I) {
45673471bf0Spatrick       if (!I->isCopy() && !I->isKill())
45709467b48Spatrick         return;
45809467b48Spatrick       MIs.push_back(&*I);
45909467b48Spatrick     }
46009467b48Spatrick     MachineInstr *FirstMI = MIs.back();
46109467b48Spatrick 
46209467b48Spatrick     auto anyRegsAlias = [](const MachineInstr *Dst,
46309467b48Spatrick                            ArrayRef<MachineInstr *> Srcs,
46409467b48Spatrick                            const TargetRegisterInfo *TRI) {
46509467b48Spatrick       for (const MachineInstr *Src : Srcs)
46609467b48Spatrick         if (Src != Dst)
46709467b48Spatrick           if (TRI->regsOverlap(Dst->getOperand(0).getReg(),
46809467b48Spatrick                                Src->getOperand(1).getReg()))
46909467b48Spatrick             return true;
47009467b48Spatrick       return false;
47109467b48Spatrick     };
47209467b48Spatrick 
47309467b48Spatrick     // If any of the destination registers in the bundle of copies alias any of
47409467b48Spatrick     // the source registers, try to schedule the instructions to avoid any
47509467b48Spatrick     // clobbering.
47609467b48Spatrick     for (int E = MIs.size(), PrevE = E; E > 1; PrevE = E) {
47709467b48Spatrick       for (int I = E; I--; )
478*d415bd75Srobert         if (!anyRegsAlias(MIs[I], ArrayRef(MIs).take_front(E), TRI)) {
47909467b48Spatrick           if (I + 1 != E)
48009467b48Spatrick             std::swap(MIs[I], MIs[E - 1]);
48109467b48Spatrick           --E;
48209467b48Spatrick         }
48309467b48Spatrick       if (PrevE == E) {
48409467b48Spatrick         MF->getFunction().getContext().emitError(
48509467b48Spatrick             "register rewriting failed: cycle in copy bundle");
48609467b48Spatrick         break;
48709467b48Spatrick       }
48809467b48Spatrick     }
48909467b48Spatrick 
49009467b48Spatrick     MachineInstr *BundleStart = FirstMI;
49109467b48Spatrick     for (MachineInstr *BundledMI : llvm::reverse(MIs)) {
49209467b48Spatrick       // If instruction is in the middle of the bundle, move it before the
49309467b48Spatrick       // bundle starts, otherwise, just unbundle it. When we get to the last
49409467b48Spatrick       // instruction, the bundle will have been completely undone.
49509467b48Spatrick       if (BundledMI != BundleStart) {
49609467b48Spatrick         BundledMI->removeFromBundle();
49773471bf0Spatrick         MBB.insert(BundleStart, BundledMI);
49809467b48Spatrick       } else if (BundledMI->isBundledWithSucc()) {
49909467b48Spatrick         BundledMI->unbundleFromSucc();
50009467b48Spatrick         BundleStart = &*std::next(BundledMI->getIterator());
50109467b48Spatrick       }
50209467b48Spatrick 
50309467b48Spatrick       if (Indexes && BundledMI != FirstMI)
50409467b48Spatrick         Indexes->insertMachineInstrInMaps(*BundledMI);
50509467b48Spatrick     }
50609467b48Spatrick   }
50709467b48Spatrick }
50809467b48Spatrick 
50909467b48Spatrick /// Check whether (part of) \p SuperPhysReg is live through \p MI.
51009467b48Spatrick /// \pre \p MI defines a subregister of a virtual register that
51109467b48Spatrick /// has been assigned to \p SuperPhysReg.
subRegLiveThrough(const MachineInstr & MI,MCRegister SuperPhysReg) const51209467b48Spatrick bool VirtRegRewriter::subRegLiveThrough(const MachineInstr &MI,
51373471bf0Spatrick                                         MCRegister SuperPhysReg) const {
51409467b48Spatrick   SlotIndex MIIndex = LIS->getInstructionIndex(MI);
51509467b48Spatrick   SlotIndex BeforeMIUses = MIIndex.getBaseIndex();
51609467b48Spatrick   SlotIndex AfterMIDefs = MIIndex.getBoundaryIndex();
51709467b48Spatrick   for (MCRegUnitIterator Unit(SuperPhysReg, TRI); Unit.isValid(); ++Unit) {
51809467b48Spatrick     const LiveRange &UnitRange = LIS->getRegUnit(*Unit);
51909467b48Spatrick     // If the regunit is live both before and after MI,
52009467b48Spatrick     // we assume it is live through.
52109467b48Spatrick     // Generally speaking, this is not true, because something like
52209467b48Spatrick     // "RU = op RU" would match that description.
52309467b48Spatrick     // However, we know that we are trying to assess whether
52409467b48Spatrick     // a def of a virtual reg, vreg, is live at the same time of RU.
52509467b48Spatrick     // If we are in the "RU = op RU" situation, that means that vreg
52609467b48Spatrick     // is defined at the same time as RU (i.e., "vreg, RU = op RU").
52709467b48Spatrick     // Thus, vreg and RU interferes and vreg cannot be assigned to
52809467b48Spatrick     // SuperPhysReg. Therefore, this situation cannot happen.
52909467b48Spatrick     if (UnitRange.liveAt(AfterMIDefs) && UnitRange.liveAt(BeforeMIUses))
53009467b48Spatrick       return true;
53109467b48Spatrick   }
53209467b48Spatrick   return false;
53309467b48Spatrick }
53409467b48Spatrick 
rewrite()53509467b48Spatrick void VirtRegRewriter::rewrite() {
53609467b48Spatrick   bool NoSubRegLiveness = !MRI->subRegLivenessEnabled();
53709467b48Spatrick   SmallVector<Register, 8> SuperDeads;
53809467b48Spatrick   SmallVector<Register, 8> SuperDefs;
53909467b48Spatrick   SmallVector<Register, 8> SuperKills;
54009467b48Spatrick 
54109467b48Spatrick   for (MachineFunction::iterator MBBI = MF->begin(), MBBE = MF->end();
54209467b48Spatrick        MBBI != MBBE; ++MBBI) {
54309467b48Spatrick     LLVM_DEBUG(MBBI->print(dbgs(), Indexes));
544*d415bd75Srobert     for (MachineInstr &MI : llvm::make_early_inc_range(MBBI->instrs())) {
545*d415bd75Srobert       for (MachineOperand &MO : MI.operands()) {
54609467b48Spatrick         // Make sure MRI knows about registers clobbered by regmasks.
54709467b48Spatrick         if (MO.isRegMask())
54809467b48Spatrick           MRI->addPhysRegsUsedFromRegMask(MO.getRegMask());
54909467b48Spatrick 
55009467b48Spatrick         if (!MO.isReg() || !MO.getReg().isVirtual())
55109467b48Spatrick           continue;
55209467b48Spatrick         Register VirtReg = MO.getReg();
55373471bf0Spatrick         MCRegister PhysReg = VRM->getPhys(VirtReg);
55473471bf0Spatrick         if (PhysReg == VirtRegMap::NO_PHYS_REG)
55573471bf0Spatrick           continue;
55673471bf0Spatrick 
55773471bf0Spatrick         assert(Register(PhysReg).isPhysical());
55873471bf0Spatrick 
55973471bf0Spatrick         RewriteRegs.insert(PhysReg);
56009467b48Spatrick         assert(!MRI->isReserved(PhysReg) && "Reserved register assignment");
56109467b48Spatrick 
56209467b48Spatrick         // Preserve semantics of sub-register operands.
56309467b48Spatrick         unsigned SubReg = MO.getSubReg();
56409467b48Spatrick         if (SubReg != 0) {
56509467b48Spatrick           if (NoSubRegLiveness || !MRI->shouldTrackSubRegLiveness(VirtReg)) {
56609467b48Spatrick             // A virtual register kill refers to the whole register, so we may
56709467b48Spatrick             // have to add implicit killed operands for the super-register.  A
56809467b48Spatrick             // partial redef always kills and redefines the super-register.
56909467b48Spatrick             if ((MO.readsReg() && (MO.isDef() || MO.isKill())) ||
570*d415bd75Srobert                 (MO.isDef() && subRegLiveThrough(MI, PhysReg)))
57109467b48Spatrick               SuperKills.push_back(PhysReg);
57209467b48Spatrick 
57309467b48Spatrick             if (MO.isDef()) {
57409467b48Spatrick               // Also add implicit defs for the super-register.
57509467b48Spatrick               if (MO.isDead())
57609467b48Spatrick                 SuperDeads.push_back(PhysReg);
57709467b48Spatrick               else
57809467b48Spatrick                 SuperDefs.push_back(PhysReg);
57909467b48Spatrick             }
58009467b48Spatrick           } else {
58109467b48Spatrick             if (MO.isUse()) {
58209467b48Spatrick               if (readsUndefSubreg(MO))
58309467b48Spatrick                 // We need to add an <undef> flag if the subregister is
58409467b48Spatrick                 // completely undefined (and we are not adding super-register
58509467b48Spatrick                 // defs).
58609467b48Spatrick                 MO.setIsUndef(true);
58709467b48Spatrick             } else if (!MO.isDead()) {
58809467b48Spatrick               assert(MO.isDef());
58909467b48Spatrick             }
59009467b48Spatrick           }
59109467b48Spatrick 
59209467b48Spatrick           // The def undef and def internal flags only make sense for
59309467b48Spatrick           // sub-register defs, and we are substituting a full physreg.  An
59409467b48Spatrick           // implicit killed operand from the SuperKills list will represent the
59509467b48Spatrick           // partial read of the super-register.
59609467b48Spatrick           if (MO.isDef()) {
59709467b48Spatrick             MO.setIsUndef(false);
59809467b48Spatrick             MO.setIsInternalRead(false);
59909467b48Spatrick           }
60009467b48Spatrick 
60109467b48Spatrick           // PhysReg operands cannot have subregister indexes.
60209467b48Spatrick           PhysReg = TRI->getSubReg(PhysReg, SubReg);
60309467b48Spatrick           assert(PhysReg.isValid() && "Invalid SubReg for physical register");
60409467b48Spatrick           MO.setSubReg(0);
60509467b48Spatrick         }
60609467b48Spatrick         // Rewrite. Note we could have used MachineOperand::substPhysReg(), but
60709467b48Spatrick         // we need the inlining here.
60809467b48Spatrick         MO.setReg(PhysReg);
60909467b48Spatrick         MO.setIsRenamable(true);
61009467b48Spatrick       }
61109467b48Spatrick 
61209467b48Spatrick       // Add any missing super-register kills after rewriting the whole
61309467b48Spatrick       // instruction.
61409467b48Spatrick       while (!SuperKills.empty())
615*d415bd75Srobert         MI.addRegisterKilled(SuperKills.pop_back_val(), TRI, true);
61609467b48Spatrick 
61709467b48Spatrick       while (!SuperDeads.empty())
618*d415bd75Srobert         MI.addRegisterDead(SuperDeads.pop_back_val(), TRI, true);
61909467b48Spatrick 
62009467b48Spatrick       while (!SuperDefs.empty())
621*d415bd75Srobert         MI.addRegisterDefined(SuperDefs.pop_back_val(), TRI);
62209467b48Spatrick 
623*d415bd75Srobert       LLVM_DEBUG(dbgs() << "> " << MI);
62409467b48Spatrick 
625*d415bd75Srobert       expandCopyBundle(MI);
62609467b48Spatrick 
62709467b48Spatrick       // We can remove identity copies right now.
628*d415bd75Srobert       handleIdentityCopy(MI);
62909467b48Spatrick     }
63009467b48Spatrick   }
63173471bf0Spatrick 
63273471bf0Spatrick   if (LIS) {
63373471bf0Spatrick     // Don't bother maintaining accurate LiveIntervals for registers which were
63473471bf0Spatrick     // already allocated.
63573471bf0Spatrick     for (Register PhysReg : RewriteRegs) {
63673471bf0Spatrick       for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid();
63773471bf0Spatrick            ++Units) {
63873471bf0Spatrick         LIS->removeRegUnit(*Units);
63973471bf0Spatrick       }
64073471bf0Spatrick     }
64173471bf0Spatrick   }
64273471bf0Spatrick 
64373471bf0Spatrick   RewriteRegs.clear();
64473471bf0Spatrick }
64573471bf0Spatrick 
createVirtRegRewriter(bool ClearVirtRegs)64673471bf0Spatrick FunctionPass *llvm::createVirtRegRewriter(bool ClearVirtRegs) {
64773471bf0Spatrick   return new VirtRegRewriter(ClearVirtRegs);
64809467b48Spatrick }
649