Home | History | Annotate | Line # | Download | only in CodeGen
      1 //===- SplitKit.cpp - Toolkit for splitting live ranges -------------------===//
      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 contains the SplitAnalysis class as well as mutator functions for
     10 // live range splitting.
     11 //
     12 //===----------------------------------------------------------------------===//
     13 
     14 #include "SplitKit.h"
     15 #include "llvm/ADT/None.h"
     16 #include "llvm/ADT/STLExtras.h"
     17 #include "llvm/ADT/Statistic.h"
     18 #include "llvm/Analysis/AliasAnalysis.h"
     19 #include "llvm/CodeGen/LiveRangeEdit.h"
     20 #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
     21 #include "llvm/CodeGen/MachineDominators.h"
     22 #include "llvm/CodeGen/MachineInstr.h"
     23 #include "llvm/CodeGen/MachineInstrBuilder.h"
     24 #include "llvm/CodeGen/MachineLoopInfo.h"
     25 #include "llvm/CodeGen/MachineOperand.h"
     26 #include "llvm/CodeGen/MachineRegisterInfo.h"
     27 #include "llvm/CodeGen/TargetInstrInfo.h"
     28 #include "llvm/CodeGen/TargetOpcodes.h"
     29 #include "llvm/CodeGen/TargetRegisterInfo.h"
     30 #include "llvm/CodeGen/TargetSubtargetInfo.h"
     31 #include "llvm/CodeGen/VirtRegMap.h"
     32 #include "llvm/Config/llvm-config.h"
     33 #include "llvm/IR/DebugLoc.h"
     34 #include "llvm/Support/Allocator.h"
     35 #include "llvm/Support/BlockFrequency.h"
     36 #include "llvm/Support/Debug.h"
     37 #include "llvm/Support/ErrorHandling.h"
     38 #include "llvm/Support/raw_ostream.h"
     39 #include <algorithm>
     40 #include <cassert>
     41 #include <iterator>
     42 #include <limits>
     43 #include <tuple>
     44 
     45 using namespace llvm;
     46 
     47 #define DEBUG_TYPE "regalloc"
     48 
     49 STATISTIC(NumFinished, "Number of splits finished");
     50 STATISTIC(NumSimple,   "Number of splits that were simple");
     51 STATISTIC(NumCopies,   "Number of copies inserted for splitting");
     52 STATISTIC(NumRemats,   "Number of rematerialized defs for splitting");
     53 STATISTIC(NumRepairs,  "Number of invalid live ranges repaired");
     54 
     55 //===----------------------------------------------------------------------===//
     56 //                     Last Insert Point Analysis
     57 //===----------------------------------------------------------------------===//
     58 
     59 InsertPointAnalysis::InsertPointAnalysis(const LiveIntervals &lis,
     60                                          unsigned BBNum)
     61     : LIS(lis), LastInsertPoint(BBNum) {}
     62 
     63 SlotIndex
     64 InsertPointAnalysis::computeLastInsertPoint(const LiveInterval &CurLI,
     65                                             const MachineBasicBlock &MBB) {
     66   unsigned Num = MBB.getNumber();
     67   std::pair<SlotIndex, SlotIndex> &LIP = LastInsertPoint[Num];
     68   SlotIndex MBBEnd = LIS.getMBBEndIdx(&MBB);
     69 
     70   SmallVector<const MachineBasicBlock *, 1> ExceptionalSuccessors;
     71   bool EHPadSuccessor = false;
     72   for (const MachineBasicBlock *SMBB : MBB.successors()) {
     73     if (SMBB->isEHPad()) {
     74       ExceptionalSuccessors.push_back(SMBB);
     75       EHPadSuccessor = true;
     76     } else if (SMBB->isInlineAsmBrIndirectTarget())
     77       ExceptionalSuccessors.push_back(SMBB);
     78   }
     79 
     80   // Compute insert points on the first call. The pair is independent of the
     81   // current live interval.
     82   if (!LIP.first.isValid()) {
     83     MachineBasicBlock::const_iterator FirstTerm = MBB.getFirstTerminator();
     84     if (FirstTerm == MBB.end())
     85       LIP.first = MBBEnd;
     86     else
     87       LIP.first = LIS.getInstructionIndex(*FirstTerm);
     88 
     89     // If there is a landing pad or inlineasm_br successor, also find the
     90     // instruction. If there is no such instruction, we don't need to do
     91     // anything special.  We assume there cannot be multiple instructions that
     92     // are Calls with EHPad successors or INLINEASM_BR in a block. Further, we
     93     // assume that if there are any, they will be after any other call
     94     // instructions in the block.
     95     if (ExceptionalSuccessors.empty())
     96       return LIP.first;
     97     for (const MachineInstr &MI : llvm::reverse(MBB)) {
     98       if ((EHPadSuccessor && MI.isCall()) ||
     99           MI.getOpcode() == TargetOpcode::INLINEASM_BR) {
    100         LIP.second = LIS.getInstructionIndex(MI);
    101         break;
    102       }
    103     }
    104   }
    105 
    106   // If CurLI is live into a landing pad successor, move the last insert point
    107   // back to the call that may throw.
    108   if (!LIP.second)
    109     return LIP.first;
    110 
    111   if (none_of(ExceptionalSuccessors, [&](const MachineBasicBlock *EHPad) {
    112         return LIS.isLiveInToMBB(CurLI, EHPad);
    113       }))
    114     return LIP.first;
    115 
    116   // Find the value leaving MBB.
    117   const VNInfo *VNI = CurLI.getVNInfoBefore(MBBEnd);
    118   if (!VNI)
    119     return LIP.first;
    120 
    121   // The def of statepoint instruction is a gc relocation and it should be alive
    122   // in landing pad. So we cannot split interval after statepoint instruction.
    123   if (SlotIndex::isSameInstr(VNI->def, LIP.second))
    124     if (auto *I = LIS.getInstructionFromIndex(LIP.second))
    125       if (I->getOpcode() == TargetOpcode::STATEPOINT)
    126         return LIP.second;
    127 
    128   // If the value leaving MBB was defined after the call in MBB, it can't
    129   // really be live-in to the landing pad.  This can happen if the landing pad
    130   // has a PHI, and this register is undef on the exceptional edge.
    131   // <rdar://problem/10664933>
    132   if (!SlotIndex::isEarlierInstr(VNI->def, LIP.second) && VNI->def < MBBEnd)
    133     return LIP.first;
    134 
    135   // Value is properly live-in to the landing pad.
    136   // Only allow inserts before the call.
    137   return LIP.second;
    138 }
    139 
    140 MachineBasicBlock::iterator
    141 InsertPointAnalysis::getLastInsertPointIter(const LiveInterval &CurLI,
    142                                             MachineBasicBlock &MBB) {
    143   SlotIndex LIP = getLastInsertPoint(CurLI, MBB);
    144   if (LIP == LIS.getMBBEndIdx(&MBB))
    145     return MBB.end();
    146   return LIS.getInstructionFromIndex(LIP);
    147 }
    148 
    149 //===----------------------------------------------------------------------===//
    150 //                                 Split Analysis
    151 //===----------------------------------------------------------------------===//
    152 
    153 SplitAnalysis::SplitAnalysis(const VirtRegMap &vrm, const LiveIntervals &lis,
    154                              const MachineLoopInfo &mli)
    155     : MF(vrm.getMachineFunction()), VRM(vrm), LIS(lis), Loops(mli),
    156       TII(*MF.getSubtarget().getInstrInfo()), IPA(lis, MF.getNumBlockIDs()) {}
    157 
    158 void SplitAnalysis::clear() {
    159   UseSlots.clear();
    160   UseBlocks.clear();
    161   ThroughBlocks.clear();
    162   CurLI = nullptr;
    163   DidRepairRange = false;
    164 }
    165 
    166 /// analyzeUses - Count instructions, basic blocks, and loops using CurLI.
    167 void SplitAnalysis::analyzeUses() {
    168   assert(UseSlots.empty() && "Call clear first");
    169 
    170   // First get all the defs from the interval values. This provides the correct
    171   // slots for early clobbers.
    172   for (const VNInfo *VNI : CurLI->valnos)
    173     if (!VNI->isPHIDef() && !VNI->isUnused())
    174       UseSlots.push_back(VNI->def);
    175 
    176   // Get use slots form the use-def chain.
    177   const MachineRegisterInfo &MRI = MF.getRegInfo();
    178   for (MachineOperand &MO : MRI.use_nodbg_operands(CurLI->reg()))
    179     if (!MO.isUndef())
    180       UseSlots.push_back(LIS.getInstructionIndex(*MO.getParent()).getRegSlot());
    181 
    182   array_pod_sort(UseSlots.begin(), UseSlots.end());
    183 
    184   // Remove duplicates, keeping the smaller slot for each instruction.
    185   // That is what we want for early clobbers.
    186   UseSlots.erase(std::unique(UseSlots.begin(), UseSlots.end(),
    187                              SlotIndex::isSameInstr),
    188                  UseSlots.end());
    189 
    190   // Compute per-live block info.
    191   if (!calcLiveBlockInfo()) {
    192     // FIXME: calcLiveBlockInfo found inconsistencies in the live range.
    193     // I am looking at you, RegisterCoalescer!
    194     DidRepairRange = true;
    195     ++NumRepairs;
    196     LLVM_DEBUG(dbgs() << "*** Fixing inconsistent live interval! ***\n");
    197     const_cast<LiveIntervals&>(LIS)
    198       .shrinkToUses(const_cast<LiveInterval*>(CurLI));
    199     UseBlocks.clear();
    200     ThroughBlocks.clear();
    201     bool fixed = calcLiveBlockInfo();
    202     (void)fixed;
    203     assert(fixed && "Couldn't fix broken live interval");
    204   }
    205 
    206   LLVM_DEBUG(dbgs() << "Analyze counted " << UseSlots.size() << " instrs in "
    207                     << UseBlocks.size() << " blocks, through "
    208                     << NumThroughBlocks << " blocks.\n");
    209 }
    210 
    211 /// calcLiveBlockInfo - Fill the LiveBlocks array with information about blocks
    212 /// where CurLI is live.
    213 bool SplitAnalysis::calcLiveBlockInfo() {
    214   ThroughBlocks.resize(MF.getNumBlockIDs());
    215   NumThroughBlocks = NumGapBlocks = 0;
    216   if (CurLI->empty())
    217     return true;
    218 
    219   LiveInterval::const_iterator LVI = CurLI->begin();
    220   LiveInterval::const_iterator LVE = CurLI->end();
    221 
    222   SmallVectorImpl<SlotIndex>::const_iterator UseI, UseE;
    223   UseI = UseSlots.begin();
    224   UseE = UseSlots.end();
    225 
    226   // Loop over basic blocks where CurLI is live.
    227   MachineFunction::iterator MFI =
    228       LIS.getMBBFromIndex(LVI->start)->getIterator();
    229   while (true) {
    230     BlockInfo BI;
    231     BI.MBB = &*MFI;
    232     SlotIndex Start, Stop;
    233     std::tie(Start, Stop) = LIS.getSlotIndexes()->getMBBRange(BI.MBB);
    234 
    235     // If the block contains no uses, the range must be live through. At one
    236     // point, RegisterCoalescer could create dangling ranges that ended
    237     // mid-block.
    238     if (UseI == UseE || *UseI >= Stop) {
    239       ++NumThroughBlocks;
    240       ThroughBlocks.set(BI.MBB->getNumber());
    241       // The range shouldn't end mid-block if there are no uses. This shouldn't
    242       // happen.
    243       if (LVI->end < Stop)
    244         return false;
    245     } else {
    246       // This block has uses. Find the first and last uses in the block.
    247       BI.FirstInstr = *UseI;
    248       assert(BI.FirstInstr >= Start);
    249       do ++UseI;
    250       while (UseI != UseE && *UseI < Stop);
    251       BI.LastInstr = UseI[-1];
    252       assert(BI.LastInstr < Stop);
    253 
    254       // LVI is the first live segment overlapping MBB.
    255       BI.LiveIn = LVI->start <= Start;
    256 
    257       // When not live in, the first use should be a def.
    258       if (!BI.LiveIn) {
    259         assert(LVI->start == LVI->valno->def && "Dangling Segment start");
    260         assert(LVI->start == BI.FirstInstr && "First instr should be a def");
    261         BI.FirstDef = BI.FirstInstr;
    262       }
    263 
    264       // Look for gaps in the live range.
    265       BI.LiveOut = true;
    266       while (LVI->end < Stop) {
    267         SlotIndex LastStop = LVI->end;
    268         if (++LVI == LVE || LVI->start >= Stop) {
    269           BI.LiveOut = false;
    270           BI.LastInstr = LastStop;
    271           break;
    272         }
    273 
    274         if (LastStop < LVI->start) {
    275           // There is a gap in the live range. Create duplicate entries for the
    276           // live-in snippet and the live-out snippet.
    277           ++NumGapBlocks;
    278 
    279           // Push the Live-in part.
    280           BI.LiveOut = false;
    281           UseBlocks.push_back(BI);
    282           UseBlocks.back().LastInstr = LastStop;
    283 
    284           // Set up BI for the live-out part.
    285           BI.LiveIn = false;
    286           BI.LiveOut = true;
    287           BI.FirstInstr = BI.FirstDef = LVI->start;
    288         }
    289 
    290         // A Segment that starts in the middle of the block must be a def.
    291         assert(LVI->start == LVI->valno->def && "Dangling Segment start");
    292         if (!BI.FirstDef)
    293           BI.FirstDef = LVI->start;
    294       }
    295 
    296       UseBlocks.push_back(BI);
    297 
    298       // LVI is now at LVE or LVI->end >= Stop.
    299       if (LVI == LVE)
    300         break;
    301     }
    302 
    303     // Live segment ends exactly at Stop. Move to the next segment.
    304     if (LVI->end == Stop && ++LVI == LVE)
    305       break;
    306 
    307     // Pick the next basic block.
    308     if (LVI->start < Stop)
    309       ++MFI;
    310     else
    311       MFI = LIS.getMBBFromIndex(LVI->start)->getIterator();
    312   }
    313 
    314   assert(getNumLiveBlocks() == countLiveBlocks(CurLI) && "Bad block count");
    315   return true;
    316 }
    317 
    318 unsigned SplitAnalysis::countLiveBlocks(const LiveInterval *cli) const {
    319   if (cli->empty())
    320     return 0;
    321   LiveInterval *li = const_cast<LiveInterval*>(cli);
    322   LiveInterval::iterator LVI = li->begin();
    323   LiveInterval::iterator LVE = li->end();
    324   unsigned Count = 0;
    325 
    326   // Loop over basic blocks where li is live.
    327   MachineFunction::const_iterator MFI =
    328       LIS.getMBBFromIndex(LVI->start)->getIterator();
    329   SlotIndex Stop = LIS.getMBBEndIdx(&*MFI);
    330   while (true) {
    331     ++Count;
    332     LVI = li->advanceTo(LVI, Stop);
    333     if (LVI == LVE)
    334       return Count;
    335     do {
    336       ++MFI;
    337       Stop = LIS.getMBBEndIdx(&*MFI);
    338     } while (Stop <= LVI->start);
    339   }
    340 }
    341 
    342 bool SplitAnalysis::isOriginalEndpoint(SlotIndex Idx) const {
    343   unsigned OrigReg = VRM.getOriginal(CurLI->reg());
    344   const LiveInterval &Orig = LIS.getInterval(OrigReg);
    345   assert(!Orig.empty() && "Splitting empty interval?");
    346   LiveInterval::const_iterator I = Orig.find(Idx);
    347 
    348   // Range containing Idx should begin at Idx.
    349   if (I != Orig.end() && I->start <= Idx)
    350     return I->start == Idx;
    351 
    352   // Range does not contain Idx, previous must end at Idx.
    353   return I != Orig.begin() && (--I)->end == Idx;
    354 }
    355 
    356 void SplitAnalysis::analyze(const LiveInterval *li) {
    357   clear();
    358   CurLI = li;
    359   analyzeUses();
    360 }
    361 
    362 //===----------------------------------------------------------------------===//
    363 //                               Split Editor
    364 //===----------------------------------------------------------------------===//
    365 
    366 /// Create a new SplitEditor for editing the LiveInterval analyzed by SA.
    367 SplitEditor::SplitEditor(SplitAnalysis &SA, AliasAnalysis &AA,
    368                          LiveIntervals &LIS, VirtRegMap &VRM,
    369                          MachineDominatorTree &MDT,
    370                          MachineBlockFrequencyInfo &MBFI, VirtRegAuxInfo &VRAI)
    371     : SA(SA), AA(AA), LIS(LIS), VRM(VRM),
    372       MRI(VRM.getMachineFunction().getRegInfo()), MDT(MDT),
    373       TII(*VRM.getMachineFunction().getSubtarget().getInstrInfo()),
    374       TRI(*VRM.getMachineFunction().getSubtarget().getRegisterInfo()),
    375       MBFI(MBFI), VRAI(VRAI), RegAssign(Allocator) {}
    376 
    377 void SplitEditor::reset(LiveRangeEdit &LRE, ComplementSpillMode SM) {
    378   Edit = &LRE;
    379   SpillMode = SM;
    380   OpenIdx = 0;
    381   RegAssign.clear();
    382   Values.clear();
    383 
    384   // Reset the LiveIntervalCalc instances needed for this spill mode.
    385   LICalc[0].reset(&VRM.getMachineFunction(), LIS.getSlotIndexes(), &MDT,
    386                   &LIS.getVNInfoAllocator());
    387   if (SpillMode)
    388     LICalc[1].reset(&VRM.getMachineFunction(), LIS.getSlotIndexes(), &MDT,
    389                     &LIS.getVNInfoAllocator());
    390 
    391   // We don't need an AliasAnalysis since we will only be performing
    392   // cheap-as-a-copy remats anyway.
    393   Edit->anyRematerializable(nullptr);
    394 }
    395 
    396 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
    397 LLVM_DUMP_METHOD void SplitEditor::dump() const {
    398   if (RegAssign.empty()) {
    399     dbgs() << " empty\n";
    400     return;
    401   }
    402 
    403   for (RegAssignMap::const_iterator I = RegAssign.begin(); I.valid(); ++I)
    404     dbgs() << " [" << I.start() << ';' << I.stop() << "):" << I.value();
    405   dbgs() << '\n';
    406 }
    407 #endif
    408 
    409 LiveInterval::SubRange &SplitEditor::getSubRangeForMaskExact(LaneBitmask LM,
    410                                                              LiveInterval &LI) {
    411   for (LiveInterval::SubRange &S : LI.subranges())
    412     if (S.LaneMask == LM)
    413       return S;
    414   llvm_unreachable("SubRange for this mask not found");
    415 }
    416 
    417 LiveInterval::SubRange &SplitEditor::getSubRangeForMask(LaneBitmask LM,
    418                                                         LiveInterval &LI) {
    419   for (LiveInterval::SubRange &S : LI.subranges())
    420     if ((S.LaneMask & LM) == LM)
    421       return S;
    422   llvm_unreachable("SubRange for this mask not found");
    423 }
    424 
    425 void SplitEditor::addDeadDef(LiveInterval &LI, VNInfo *VNI, bool Original) {
    426   if (!LI.hasSubRanges()) {
    427     LI.createDeadDef(VNI);
    428     return;
    429   }
    430 
    431   SlotIndex Def = VNI->def;
    432   if (Original) {
    433     // If we are transferring a def from the original interval, make sure
    434     // to only update the subranges for which the original subranges had
    435     // a def at this location.
    436     for (LiveInterval::SubRange &S : LI.subranges()) {
    437       auto &PS = getSubRangeForMask(S.LaneMask, Edit->getParent());
    438       VNInfo *PV = PS.getVNInfoAt(Def);
    439       if (PV != nullptr && PV->def == Def)
    440         S.createDeadDef(Def, LIS.getVNInfoAllocator());
    441     }
    442   } else {
    443     // This is a new def: either from rematerialization, or from an inserted
    444     // copy. Since rematerialization can regenerate a definition of a sub-
    445     // register, we need to check which subranges need to be updated.
    446     const MachineInstr *DefMI = LIS.getInstructionFromIndex(Def);
    447     assert(DefMI != nullptr);
    448     LaneBitmask LM;
    449     for (const MachineOperand &DefOp : DefMI->defs()) {
    450       Register R = DefOp.getReg();
    451       if (R != LI.reg())
    452         continue;
    453       if (unsigned SR = DefOp.getSubReg())
    454         LM |= TRI.getSubRegIndexLaneMask(SR);
    455       else {
    456         LM = MRI.getMaxLaneMaskForVReg(R);
    457         break;
    458       }
    459     }
    460     for (LiveInterval::SubRange &S : LI.subranges())
    461       if ((S.LaneMask & LM).any())
    462         S.createDeadDef(Def, LIS.getVNInfoAllocator());
    463   }
    464 }
    465 
    466 VNInfo *SplitEditor::defValue(unsigned RegIdx,
    467                               const VNInfo *ParentVNI,
    468                               SlotIndex Idx,
    469                               bool Original) {
    470   assert(ParentVNI && "Mapping  NULL value");
    471   assert(Idx.isValid() && "Invalid SlotIndex");
    472   assert(Edit->getParent().getVNInfoAt(Idx) == ParentVNI && "Bad Parent VNI");
    473   LiveInterval *LI = &LIS.getInterval(Edit->get(RegIdx));
    474 
    475   // Create a new value.
    476   VNInfo *VNI = LI->getNextValue(Idx, LIS.getVNInfoAllocator());
    477 
    478   bool Force = LI->hasSubRanges();
    479   ValueForcePair FP(Force ? nullptr : VNI, Force);
    480   // Use insert for lookup, so we can add missing values with a second lookup.
    481   std::pair<ValueMap::iterator, bool> InsP =
    482     Values.insert(std::make_pair(std::make_pair(RegIdx, ParentVNI->id), FP));
    483 
    484   // This was the first time (RegIdx, ParentVNI) was mapped, and it is not
    485   // forced. Keep it as a simple def without any liveness.
    486   if (!Force && InsP.second)
    487     return VNI;
    488 
    489   // If the previous value was a simple mapping, add liveness for it now.
    490   if (VNInfo *OldVNI = InsP.first->second.getPointer()) {
    491     addDeadDef(*LI, OldVNI, Original);
    492 
    493     // No longer a simple mapping.  Switch to a complex mapping. If the
    494     // interval has subranges, make it a forced mapping.
    495     InsP.first->second = ValueForcePair(nullptr, Force);
    496   }
    497 
    498   // This is a complex mapping, add liveness for VNI
    499   addDeadDef(*LI, VNI, Original);
    500   return VNI;
    501 }
    502 
    503 void SplitEditor::forceRecompute(unsigned RegIdx, const VNInfo &ParentVNI) {
    504   ValueForcePair &VFP = Values[std::make_pair(RegIdx, ParentVNI.id)];
    505   VNInfo *VNI = VFP.getPointer();
    506 
    507   // ParentVNI was either unmapped or already complex mapped. Either way, just
    508   // set the force bit.
    509   if (!VNI) {
    510     VFP.setInt(true);
    511     return;
    512   }
    513 
    514   // This was previously a single mapping. Make sure the old def is represented
    515   // by a trivial live range.
    516   addDeadDef(LIS.getInterval(Edit->get(RegIdx)), VNI, false);
    517 
    518   // Mark as complex mapped, forced.
    519   VFP = ValueForcePair(nullptr, true);
    520 }
    521 
    522 SlotIndex SplitEditor::buildSingleSubRegCopy(Register FromReg, Register ToReg,
    523     MachineBasicBlock &MBB, MachineBasicBlock::iterator InsertBefore,
    524     unsigned SubIdx, LiveInterval &DestLI, bool Late, SlotIndex Def) {
    525   const MCInstrDesc &Desc = TII.get(TargetOpcode::COPY);
    526   bool FirstCopy = !Def.isValid();
    527   MachineInstr *CopyMI = BuildMI(MBB, InsertBefore, DebugLoc(), Desc)
    528       .addReg(ToReg, RegState::Define | getUndefRegState(FirstCopy)
    529               | getInternalReadRegState(!FirstCopy), SubIdx)
    530       .addReg(FromReg, 0, SubIdx);
    531 
    532   BumpPtrAllocator &Allocator = LIS.getVNInfoAllocator();
    533   SlotIndexes &Indexes = *LIS.getSlotIndexes();
    534   if (FirstCopy) {
    535     Def = Indexes.insertMachineInstrInMaps(*CopyMI, Late).getRegSlot();
    536   } else {
    537     CopyMI->bundleWithPred();
    538   }
    539   LaneBitmask LaneMask = TRI.getSubRegIndexLaneMask(SubIdx);
    540   DestLI.refineSubRanges(Allocator, LaneMask,
    541                          [Def, &Allocator](LiveInterval::SubRange &SR) {
    542                            SR.createDeadDef(Def, Allocator);
    543                          },
    544                          Indexes, TRI);
    545   return Def;
    546 }
    547 
    548 SlotIndex SplitEditor::buildCopy(Register FromReg, Register ToReg,
    549     LaneBitmask LaneMask, MachineBasicBlock &MBB,
    550     MachineBasicBlock::iterator InsertBefore, bool Late, unsigned RegIdx) {
    551   const MCInstrDesc &Desc = TII.get(TargetOpcode::COPY);
    552   if (LaneMask.all() || LaneMask == MRI.getMaxLaneMaskForVReg(FromReg)) {
    553     // The full vreg is copied.
    554     MachineInstr *CopyMI =
    555         BuildMI(MBB, InsertBefore, DebugLoc(), Desc, ToReg).addReg(FromReg);
    556     SlotIndexes &Indexes = *LIS.getSlotIndexes();
    557     return Indexes.insertMachineInstrInMaps(*CopyMI, Late).getRegSlot();
    558   }
    559 
    560   // Only a subset of lanes needs to be copied. The following is a simple
    561   // heuristic to construct a sequence of COPYs. We could add a target
    562   // specific callback if this turns out to be suboptimal.
    563   LiveInterval &DestLI = LIS.getInterval(Edit->get(RegIdx));
    564 
    565   // First pass: Try to find a perfectly matching subregister index. If none
    566   // exists find the one covering the most lanemask bits.
    567   const TargetRegisterClass *RC = MRI.getRegClass(FromReg);
    568   assert(RC == MRI.getRegClass(ToReg) && "Should have same reg class");
    569 
    570   SmallVector<unsigned, 8> Indexes;
    571 
    572   // Abort if we cannot possibly implement the COPY with the given indexes.
    573   if (!TRI.getCoveringSubRegIndexes(MRI, RC, LaneMask, Indexes))
    574     report_fatal_error("Impossible to implement partial COPY");
    575 
    576   SlotIndex Def;
    577   for (unsigned BestIdx : Indexes) {
    578     Def = buildSingleSubRegCopy(FromReg, ToReg, MBB, InsertBefore, BestIdx,
    579                                 DestLI, Late, Def);
    580   }
    581 
    582   return Def;
    583 }
    584 
    585 VNInfo *SplitEditor::defFromParent(unsigned RegIdx,
    586                                    VNInfo *ParentVNI,
    587                                    SlotIndex UseIdx,
    588                                    MachineBasicBlock &MBB,
    589                                    MachineBasicBlock::iterator I) {
    590   SlotIndex Def;
    591   LiveInterval *LI = &LIS.getInterval(Edit->get(RegIdx));
    592 
    593   // We may be trying to avoid interference that ends at a deleted instruction,
    594   // so always begin RegIdx 0 early and all others late.
    595   bool Late = RegIdx != 0;
    596 
    597   // Attempt cheap-as-a-copy rematerialization.
    598   unsigned Original = VRM.getOriginal(Edit->get(RegIdx));
    599   LiveInterval &OrigLI = LIS.getInterval(Original);
    600   VNInfo *OrigVNI = OrigLI.getVNInfoAt(UseIdx);
    601 
    602   Register Reg = LI->reg();
    603   bool DidRemat = false;
    604   if (OrigVNI) {
    605     LiveRangeEdit::Remat RM(ParentVNI);
    606     RM.OrigMI = LIS.getInstructionFromIndex(OrigVNI->def);
    607     if (Edit->canRematerializeAt(RM, OrigVNI, UseIdx, true)) {
    608       Def = Edit->rematerializeAt(MBB, I, Reg, RM, TRI, Late);
    609       ++NumRemats;
    610       DidRemat = true;
    611     }
    612   }
    613   if (!DidRemat) {
    614     LaneBitmask LaneMask;
    615     if (OrigLI.hasSubRanges()) {
    616       LaneMask = LaneBitmask::getNone();
    617       for (LiveInterval::SubRange &S : OrigLI.subranges()) {
    618         if (S.liveAt(UseIdx))
    619           LaneMask |= S.LaneMask;
    620       }
    621     } else {
    622       LaneMask = LaneBitmask::getAll();
    623     }
    624 
    625     if (LaneMask.none()) {
    626       const MCInstrDesc &Desc = TII.get(TargetOpcode::IMPLICIT_DEF);
    627       MachineInstr *ImplicitDef = BuildMI(MBB, I, DebugLoc(), Desc, Reg);
    628       SlotIndexes &Indexes = *LIS.getSlotIndexes();
    629       Def = Indexes.insertMachineInstrInMaps(*ImplicitDef, Late).getRegSlot();
    630     } else {
    631       ++NumCopies;
    632       Def = buildCopy(Edit->getReg(), Reg, LaneMask, MBB, I, Late, RegIdx);
    633     }
    634   }
    635 
    636   // Define the value in Reg.
    637   return defValue(RegIdx, ParentVNI, Def, false);
    638 }
    639 
    640 /// Create a new virtual register and live interval.
    641 unsigned SplitEditor::openIntv() {
    642   // Create the complement as index 0.
    643   if (Edit->empty())
    644     Edit->createEmptyInterval();
    645 
    646   // Create the open interval.
    647   OpenIdx = Edit->size();
    648   Edit->createEmptyInterval();
    649   return OpenIdx;
    650 }
    651 
    652 void SplitEditor::selectIntv(unsigned Idx) {
    653   assert(Idx != 0 && "Cannot select the complement interval");
    654   assert(Idx < Edit->size() && "Can only select previously opened interval");
    655   LLVM_DEBUG(dbgs() << "    selectIntv " << OpenIdx << " -> " << Idx << '\n');
    656   OpenIdx = Idx;
    657 }
    658 
    659 SlotIndex SplitEditor::enterIntvBefore(SlotIndex Idx) {
    660   assert(OpenIdx && "openIntv not called before enterIntvBefore");
    661   LLVM_DEBUG(dbgs() << "    enterIntvBefore " << Idx);
    662   Idx = Idx.getBaseIndex();
    663   VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(Idx);
    664   if (!ParentVNI) {
    665     LLVM_DEBUG(dbgs() << ": not live\n");
    666     return Idx;
    667   }
    668   LLVM_DEBUG(dbgs() << ": valno " << ParentVNI->id << '\n');
    669   MachineInstr *MI = LIS.getInstructionFromIndex(Idx);
    670   assert(MI && "enterIntvBefore called with invalid index");
    671 
    672   VNInfo *VNI = defFromParent(OpenIdx, ParentVNI, Idx, *MI->getParent(), MI);
    673   return VNI->def;
    674 }
    675 
    676 SlotIndex SplitEditor::enterIntvAfter(SlotIndex Idx) {
    677   assert(OpenIdx && "openIntv not called before enterIntvAfter");
    678   LLVM_DEBUG(dbgs() << "    enterIntvAfter " << Idx);
    679   Idx = Idx.getBoundaryIndex();
    680   VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(Idx);
    681   if (!ParentVNI) {
    682     LLVM_DEBUG(dbgs() << ": not live\n");
    683     return Idx;
    684   }
    685   LLVM_DEBUG(dbgs() << ": valno " << ParentVNI->id << '\n');
    686   MachineInstr *MI = LIS.getInstructionFromIndex(Idx);
    687   assert(MI && "enterIntvAfter called with invalid index");
    688 
    689   VNInfo *VNI = defFromParent(OpenIdx, ParentVNI, Idx, *MI->getParent(),
    690                               std::next(MachineBasicBlock::iterator(MI)));
    691   return VNI->def;
    692 }
    693 
    694 SlotIndex SplitEditor::enterIntvAtEnd(MachineBasicBlock &MBB) {
    695   assert(OpenIdx && "openIntv not called before enterIntvAtEnd");
    696   SlotIndex End = LIS.getMBBEndIdx(&MBB);
    697   SlotIndex Last = End.getPrevSlot();
    698   LLVM_DEBUG(dbgs() << "    enterIntvAtEnd " << printMBBReference(MBB) << ", "
    699                     << Last);
    700   VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(Last);
    701   if (!ParentVNI) {
    702     LLVM_DEBUG(dbgs() << ": not live\n");
    703     return End;
    704   }
    705   SlotIndex LSP = SA.getLastSplitPoint(&MBB);
    706   if (LSP < Last) {
    707     // It could be that the use after LSP is a def, and thus the ParentVNI
    708     // just selected starts at that def.  For this case to exist, the def
    709     // must be part of a tied def/use pair (as otherwise we'd have split
    710     // distinct live ranges into individual live intervals), and thus we
    711     // can insert the def into the VNI of the use and the tied def/use
    712     // pair can live in the resulting interval.
    713     Last = LSP;
    714     ParentVNI = Edit->getParent().getVNInfoAt(Last);
    715     if (!ParentVNI) {
    716       // undef use --> undef tied def
    717       LLVM_DEBUG(dbgs() << ": tied use not live\n");
    718       return End;
    719     }
    720   }
    721 
    722   LLVM_DEBUG(dbgs() << ": valno " << ParentVNI->id);
    723   VNInfo *VNI = defFromParent(OpenIdx, ParentVNI, Last, MBB,
    724                               SA.getLastSplitPointIter(&MBB));
    725   RegAssign.insert(VNI->def, End, OpenIdx);
    726   LLVM_DEBUG(dump());
    727   return VNI->def;
    728 }
    729 
    730 /// useIntv - indicate that all instructions in MBB should use OpenLI.
    731 void SplitEditor::useIntv(const MachineBasicBlock &MBB) {
    732   useIntv(LIS.getMBBStartIdx(&MBB), LIS.getMBBEndIdx(&MBB));
    733 }
    734 
    735 void SplitEditor::useIntv(SlotIndex Start, SlotIndex End) {
    736   assert(OpenIdx && "openIntv not called before useIntv");
    737   LLVM_DEBUG(dbgs() << "    useIntv [" << Start << ';' << End << "):");
    738   RegAssign.insert(Start, End, OpenIdx);
    739   LLVM_DEBUG(dump());
    740 }
    741 
    742 SlotIndex SplitEditor::leaveIntvAfter(SlotIndex Idx) {
    743   assert(OpenIdx && "openIntv not called before leaveIntvAfter");
    744   LLVM_DEBUG(dbgs() << "    leaveIntvAfter " << Idx);
    745 
    746   // The interval must be live beyond the instruction at Idx.
    747   SlotIndex Boundary = Idx.getBoundaryIndex();
    748   VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(Boundary);
    749   if (!ParentVNI) {
    750     LLVM_DEBUG(dbgs() << ": not live\n");
    751     return Boundary.getNextSlot();
    752   }
    753   LLVM_DEBUG(dbgs() << ": valno " << ParentVNI->id << '\n');
    754   MachineInstr *MI = LIS.getInstructionFromIndex(Boundary);
    755   assert(MI && "No instruction at index");
    756 
    757   // In spill mode, make live ranges as short as possible by inserting the copy
    758   // before MI.  This is only possible if that instruction doesn't redefine the
    759   // value.  The inserted COPY is not a kill, and we don't need to recompute
    760   // the source live range.  The spiller also won't try to hoist this copy.
    761   if (SpillMode && !SlotIndex::isSameInstr(ParentVNI->def, Idx) &&
    762       MI->readsVirtualRegister(Edit->getReg())) {
    763     forceRecompute(0, *ParentVNI);
    764     defFromParent(0, ParentVNI, Idx, *MI->getParent(), MI);
    765     return Idx;
    766   }
    767 
    768   VNInfo *VNI = defFromParent(0, ParentVNI, Boundary, *MI->getParent(),
    769                               std::next(MachineBasicBlock::iterator(MI)));
    770   return VNI->def;
    771 }
    772 
    773 SlotIndex SplitEditor::leaveIntvBefore(SlotIndex Idx) {
    774   assert(OpenIdx && "openIntv not called before leaveIntvBefore");
    775   LLVM_DEBUG(dbgs() << "    leaveIntvBefore " << Idx);
    776 
    777   // The interval must be live into the instruction at Idx.
    778   Idx = Idx.getBaseIndex();
    779   VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(Idx);
    780   if (!ParentVNI) {
    781     LLVM_DEBUG(dbgs() << ": not live\n");
    782     return Idx.getNextSlot();
    783   }
    784   LLVM_DEBUG(dbgs() << ": valno " << ParentVNI->id << '\n');
    785 
    786   MachineInstr *MI = LIS.getInstructionFromIndex(Idx);
    787   assert(MI && "No instruction at index");
    788   VNInfo *VNI = defFromParent(0, ParentVNI, Idx, *MI->getParent(), MI);
    789   return VNI->def;
    790 }
    791 
    792 SlotIndex SplitEditor::leaveIntvAtTop(MachineBasicBlock &MBB) {
    793   assert(OpenIdx && "openIntv not called before leaveIntvAtTop");
    794   SlotIndex Start = LIS.getMBBStartIdx(&MBB);
    795   LLVM_DEBUG(dbgs() << "    leaveIntvAtTop " << printMBBReference(MBB) << ", "
    796                     << Start);
    797 
    798   VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(Start);
    799   if (!ParentVNI) {
    800     LLVM_DEBUG(dbgs() << ": not live\n");
    801     return Start;
    802   }
    803 
    804   VNInfo *VNI = defFromParent(0, ParentVNI, Start, MBB,
    805                               MBB.SkipPHIsLabelsAndDebug(MBB.begin()));
    806   RegAssign.insert(Start, VNI->def, OpenIdx);
    807   LLVM_DEBUG(dump());
    808   return VNI->def;
    809 }
    810 
    811 static bool hasTiedUseOf(MachineInstr &MI, unsigned Reg) {
    812   return any_of(MI.defs(), [Reg](const MachineOperand &MO) {
    813     return MO.isReg() && MO.isTied() && MO.getReg() == Reg;
    814   });
    815 }
    816 
    817 void SplitEditor::overlapIntv(SlotIndex Start, SlotIndex End) {
    818   assert(OpenIdx && "openIntv not called before overlapIntv");
    819   const VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(Start);
    820   assert(ParentVNI == Edit->getParent().getVNInfoBefore(End) &&
    821          "Parent changes value in extended range");
    822   assert(LIS.getMBBFromIndex(Start) == LIS.getMBBFromIndex(End) &&
    823          "Range cannot span basic blocks");
    824 
    825   // The complement interval will be extended as needed by LICalc.extend().
    826   if (ParentVNI)
    827     forceRecompute(0, *ParentVNI);
    828 
    829   // If the last use is tied to a def, we can't mark it as live for the
    830   // interval which includes only the use.  That would cause the tied pair
    831   // to end up in two different intervals.
    832   if (auto *MI = LIS.getInstructionFromIndex(End))
    833     if (hasTiedUseOf(*MI, Edit->getReg())) {
    834       LLVM_DEBUG(dbgs() << "skip overlap due to tied def at end\n");
    835       return;
    836     }
    837 
    838   LLVM_DEBUG(dbgs() << "    overlapIntv [" << Start << ';' << End << "):");
    839   RegAssign.insert(Start, End, OpenIdx);
    840   LLVM_DEBUG(dump());
    841 }
    842 
    843 //===----------------------------------------------------------------------===//
    844 //                                  Spill modes
    845 //===----------------------------------------------------------------------===//
    846 
    847 void SplitEditor::removeBackCopies(SmallVectorImpl<VNInfo*> &Copies) {
    848   LiveInterval *LI = &LIS.getInterval(Edit->get(0));
    849   LLVM_DEBUG(dbgs() << "Removing " << Copies.size() << " back-copies.\n");
    850   RegAssignMap::iterator AssignI;
    851   AssignI.setMap(RegAssign);
    852 
    853   for (const VNInfo *C : Copies) {
    854     SlotIndex Def = C->def;
    855     MachineInstr *MI = LIS.getInstructionFromIndex(Def);
    856     assert(MI && "No instruction for back-copy");
    857 
    858     MachineBasicBlock *MBB = MI->getParent();
    859     MachineBasicBlock::iterator MBBI(MI);
    860     bool AtBegin;
    861     do AtBegin = MBBI == MBB->begin();
    862     while (!AtBegin && (--MBBI)->isDebugOrPseudoInstr());
    863 
    864     LLVM_DEBUG(dbgs() << "Removing " << Def << '\t' << *MI);
    865     LIS.removeVRegDefAt(*LI, Def);
    866     LIS.RemoveMachineInstrFromMaps(*MI);
    867     MI->eraseFromParent();
    868 
    869     // Adjust RegAssign if a register assignment is killed at Def. We want to
    870     // avoid calculating the live range of the source register if possible.
    871     AssignI.find(Def.getPrevSlot());
    872     if (!AssignI.valid() || AssignI.start() >= Def)
    873       continue;
    874     // If MI doesn't kill the assigned register, just leave it.
    875     if (AssignI.stop() != Def)
    876       continue;
    877     unsigned RegIdx = AssignI.value();
    878     // We could hoist back-copy right after another back-copy. As a result
    879     // MMBI points to copy instruction which is actually dead now.
    880     // We cannot set its stop to MBBI which will be the same as start and
    881     // interval does not support that.
    882     SlotIndex Kill =
    883         AtBegin ? SlotIndex() : LIS.getInstructionIndex(*MBBI).getRegSlot();
    884     if (AtBegin || !MBBI->readsVirtualRegister(Edit->getReg()) ||
    885         Kill <= AssignI.start()) {
    886       LLVM_DEBUG(dbgs() << "  cannot find simple kill of RegIdx " << RegIdx
    887                         << '\n');
    888       forceRecompute(RegIdx, *Edit->getParent().getVNInfoAt(Def));
    889     } else {
    890       LLVM_DEBUG(dbgs() << "  move kill to " << Kill << '\t' << *MBBI);
    891       AssignI.setStop(Kill);
    892     }
    893   }
    894 }
    895 
    896 MachineBasicBlock*
    897 SplitEditor::findShallowDominator(MachineBasicBlock *MBB,
    898                                   MachineBasicBlock *DefMBB) {
    899   if (MBB == DefMBB)
    900     return MBB;
    901   assert(MDT.dominates(DefMBB, MBB) && "MBB must be dominated by the def.");
    902 
    903   const MachineLoopInfo &Loops = SA.Loops;
    904   const MachineLoop *DefLoop = Loops.getLoopFor(DefMBB);
    905   MachineDomTreeNode *DefDomNode = MDT[DefMBB];
    906 
    907   // Best candidate so far.
    908   MachineBasicBlock *BestMBB = MBB;
    909   unsigned BestDepth = std::numeric_limits<unsigned>::max();
    910 
    911   while (true) {
    912     const MachineLoop *Loop = Loops.getLoopFor(MBB);
    913 
    914     // MBB isn't in a loop, it doesn't get any better.  All dominators have a
    915     // higher frequency by definition.
    916     if (!Loop) {
    917       LLVM_DEBUG(dbgs() << "Def in " << printMBBReference(*DefMBB)
    918                         << " dominates " << printMBBReference(*MBB)
    919                         << " at depth 0\n");
    920       return MBB;
    921     }
    922 
    923     // We'll never be able to exit the DefLoop.
    924     if (Loop == DefLoop) {
    925       LLVM_DEBUG(dbgs() << "Def in " << printMBBReference(*DefMBB)
    926                         << " dominates " << printMBBReference(*MBB)
    927                         << " in the same loop\n");
    928       return MBB;
    929     }
    930 
    931     // Least busy dominator seen so far.
    932     unsigned Depth = Loop->getLoopDepth();
    933     if (Depth < BestDepth) {
    934       BestMBB = MBB;
    935       BestDepth = Depth;
    936       LLVM_DEBUG(dbgs() << "Def in " << printMBBReference(*DefMBB)
    937                         << " dominates " << printMBBReference(*MBB)
    938                         << " at depth " << Depth << '\n');
    939     }
    940 
    941     // Leave loop by going to the immediate dominator of the loop header.
    942     // This is a bigger stride than simply walking up the dominator tree.
    943     MachineDomTreeNode *IDom = MDT[Loop->getHeader()]->getIDom();
    944 
    945     // Too far up the dominator tree?
    946     if (!IDom || !MDT.dominates(DefDomNode, IDom))
    947       return BestMBB;
    948 
    949     MBB = IDom->getBlock();
    950   }
    951 }
    952 
    953 void SplitEditor::computeRedundantBackCopies(
    954     DenseSet<unsigned> &NotToHoistSet, SmallVectorImpl<VNInfo *> &BackCopies) {
    955   LiveInterval *LI = &LIS.getInterval(Edit->get(0));
    956   LiveInterval *Parent = &Edit->getParent();
    957   SmallVector<SmallPtrSet<VNInfo *, 8>, 8> EqualVNs(Parent->getNumValNums());
    958   SmallPtrSet<VNInfo *, 8> DominatedVNIs;
    959 
    960   // Aggregate VNIs having the same value as ParentVNI.
    961   for (VNInfo *VNI : LI->valnos) {
    962     if (VNI->isUnused())
    963       continue;
    964     VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(VNI->def);
    965     EqualVNs[ParentVNI->id].insert(VNI);
    966   }
    967 
    968   // For VNI aggregation of each ParentVNI, collect dominated, i.e.,
    969   // redundant VNIs to BackCopies.
    970   for (unsigned i = 0, e = Parent->getNumValNums(); i != e; ++i) {
    971     VNInfo *ParentVNI = Parent->getValNumInfo(i);
    972     if (!NotToHoistSet.count(ParentVNI->id))
    973       continue;
    974     SmallPtrSetIterator<VNInfo *> It1 = EqualVNs[ParentVNI->id].begin();
    975     SmallPtrSetIterator<VNInfo *> It2 = It1;
    976     for (; It1 != EqualVNs[ParentVNI->id].end(); ++It1) {
    977       It2 = It1;
    978       for (++It2; It2 != EqualVNs[ParentVNI->id].end(); ++It2) {
    979         if (DominatedVNIs.count(*It1) || DominatedVNIs.count(*It2))
    980           continue;
    981 
    982         MachineBasicBlock *MBB1 = LIS.getMBBFromIndex((*It1)->def);
    983         MachineBasicBlock *MBB2 = LIS.getMBBFromIndex((*It2)->def);
    984         if (MBB1 == MBB2) {
    985           DominatedVNIs.insert((*It1)->def < (*It2)->def ? (*It2) : (*It1));
    986         } else if (MDT.dominates(MBB1, MBB2)) {
    987           DominatedVNIs.insert(*It2);
    988         } else if (MDT.dominates(MBB2, MBB1)) {
    989           DominatedVNIs.insert(*It1);
    990         }
    991       }
    992     }
    993     if (!DominatedVNIs.empty()) {
    994       forceRecompute(0, *ParentVNI);
    995       append_range(BackCopies, DominatedVNIs);
    996       DominatedVNIs.clear();
    997     }
    998   }
    999 }
   1000 
   1001 /// For SM_Size mode, find a common dominator for all the back-copies for
   1002 /// the same ParentVNI and hoist the backcopies to the dominator BB.
   1003 /// For SM_Speed mode, if the common dominator is hot and it is not beneficial
   1004 /// to do the hoisting, simply remove the dominated backcopies for the same
   1005 /// ParentVNI.
   1006 void SplitEditor::hoistCopies() {
   1007   // Get the complement interval, always RegIdx 0.
   1008   LiveInterval *LI = &LIS.getInterval(Edit->get(0));
   1009   LiveInterval *Parent = &Edit->getParent();
   1010 
   1011   // Track the nearest common dominator for all back-copies for each ParentVNI,
   1012   // indexed by ParentVNI->id.
   1013   using DomPair = std::pair<MachineBasicBlock *, SlotIndex>;
   1014   SmallVector<DomPair, 8> NearestDom(Parent->getNumValNums());
   1015   // The total cost of all the back-copies for each ParentVNI.
   1016   SmallVector<BlockFrequency, 8> Costs(Parent->getNumValNums());
   1017   // The ParentVNI->id set for which hoisting back-copies are not beneficial
   1018   // for Speed.
   1019   DenseSet<unsigned> NotToHoistSet;
   1020 
   1021   // Find the nearest common dominator for parent values with multiple
   1022   // back-copies.  If a single back-copy dominates, put it in DomPair.second.
   1023   for (VNInfo *VNI : LI->valnos) {
   1024     if (VNI->isUnused())
   1025       continue;
   1026     VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(VNI->def);
   1027     assert(ParentVNI && "Parent not live at complement def");
   1028 
   1029     // Don't hoist remats.  The complement is probably going to disappear
   1030     // completely anyway.
   1031     if (Edit->didRematerialize(ParentVNI))
   1032       continue;
   1033 
   1034     MachineBasicBlock *ValMBB = LIS.getMBBFromIndex(VNI->def);
   1035 
   1036     DomPair &Dom = NearestDom[ParentVNI->id];
   1037 
   1038     // Keep directly defined parent values.  This is either a PHI or an
   1039     // instruction in the complement range.  All other copies of ParentVNI
   1040     // should be eliminated.
   1041     if (VNI->def == ParentVNI->def) {
   1042       LLVM_DEBUG(dbgs() << "Direct complement def at " << VNI->def << '\n');
   1043       Dom = DomPair(ValMBB, VNI->def);
   1044       continue;
   1045     }
   1046     // Skip the singly mapped values.  There is nothing to gain from hoisting a
   1047     // single back-copy.
   1048     if (Values.lookup(std::make_pair(0, ParentVNI->id)).getPointer()) {
   1049       LLVM_DEBUG(dbgs() << "Single complement def at " << VNI->def << '\n');
   1050       continue;
   1051     }
   1052 
   1053     if (!Dom.first) {
   1054       // First time we see ParentVNI.  VNI dominates itself.
   1055       Dom = DomPair(ValMBB, VNI->def);
   1056     } else if (Dom.first == ValMBB) {
   1057       // Two defs in the same block.  Pick the earlier def.
   1058       if (!Dom.second.isValid() || VNI->def < Dom.second)
   1059         Dom.second = VNI->def;
   1060     } else {
   1061       // Different basic blocks. Check if one dominates.
   1062       MachineBasicBlock *Near =
   1063         MDT.findNearestCommonDominator(Dom.first, ValMBB);
   1064       if (Near == ValMBB)
   1065         // Def ValMBB dominates.
   1066         Dom = DomPair(ValMBB, VNI->def);
   1067       else if (Near != Dom.first)
   1068         // None dominate. Hoist to common dominator, need new def.
   1069         Dom = DomPair(Near, SlotIndex());
   1070       Costs[ParentVNI->id] += MBFI.getBlockFreq(ValMBB);
   1071     }
   1072 
   1073     LLVM_DEBUG(dbgs() << "Multi-mapped complement " << VNI->id << '@'
   1074                       << VNI->def << " for parent " << ParentVNI->id << '@'
   1075                       << ParentVNI->def << " hoist to "
   1076                       << printMBBReference(*Dom.first) << ' ' << Dom.second
   1077                       << '\n');
   1078   }
   1079 
   1080   // Insert the hoisted copies.
   1081   for (unsigned i = 0, e = Parent->getNumValNums(); i != e; ++i) {
   1082     DomPair &Dom = NearestDom[i];
   1083     if (!Dom.first || Dom.second.isValid())
   1084       continue;
   1085     // This value needs a hoisted copy inserted at the end of Dom.first.
   1086     VNInfo *ParentVNI = Parent->getValNumInfo(i);
   1087     MachineBasicBlock *DefMBB = LIS.getMBBFromIndex(ParentVNI->def);
   1088     // Get a less loopy dominator than Dom.first.
   1089     Dom.first = findShallowDominator(Dom.first, DefMBB);
   1090     if (SpillMode == SM_Speed &&
   1091         MBFI.getBlockFreq(Dom.first) > Costs[ParentVNI->id]) {
   1092       NotToHoistSet.insert(ParentVNI->id);
   1093       continue;
   1094     }
   1095     SlotIndex LSP = SA.getLastSplitPoint(Dom.first);
   1096     if (LSP <= ParentVNI->def) {
   1097       NotToHoistSet.insert(ParentVNI->id);
   1098       continue;
   1099     }
   1100     Dom.second = defFromParent(0, ParentVNI, LSP, *Dom.first,
   1101                                SA.getLastSplitPointIter(Dom.first))->def;
   1102   }
   1103 
   1104   // Remove redundant back-copies that are now known to be dominated by another
   1105   // def with the same value.
   1106   SmallVector<VNInfo*, 8> BackCopies;
   1107   for (VNInfo *VNI : LI->valnos) {
   1108     if (VNI->isUnused())
   1109       continue;
   1110     VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(VNI->def);
   1111     const DomPair &Dom = NearestDom[ParentVNI->id];
   1112     if (!Dom.first || Dom.second == VNI->def ||
   1113         NotToHoistSet.count(ParentVNI->id))
   1114       continue;
   1115     BackCopies.push_back(VNI);
   1116     forceRecompute(0, *ParentVNI);
   1117   }
   1118 
   1119   // If it is not beneficial to hoist all the BackCopies, simply remove
   1120   // redundant BackCopies in speed mode.
   1121   if (SpillMode == SM_Speed && !NotToHoistSet.empty())
   1122     computeRedundantBackCopies(NotToHoistSet, BackCopies);
   1123 
   1124   removeBackCopies(BackCopies);
   1125 }
   1126 
   1127 /// transferValues - Transfer all possible values to the new live ranges.
   1128 /// Values that were rematerialized are left alone, they need LICalc.extend().
   1129 bool SplitEditor::transferValues() {
   1130   bool Skipped = false;
   1131   RegAssignMap::const_iterator AssignI = RegAssign.begin();
   1132   for (const LiveRange::Segment &S : Edit->getParent()) {
   1133     LLVM_DEBUG(dbgs() << "  blit " << S << ':');
   1134     VNInfo *ParentVNI = S.valno;
   1135     // RegAssign has holes where RegIdx 0 should be used.
   1136     SlotIndex Start = S.start;
   1137     AssignI.advanceTo(Start);
   1138     do {
   1139       unsigned RegIdx;
   1140       SlotIndex End = S.end;
   1141       if (!AssignI.valid()) {
   1142         RegIdx = 0;
   1143       } else if (AssignI.start() <= Start) {
   1144         RegIdx = AssignI.value();
   1145         if (AssignI.stop() < End) {
   1146           End = AssignI.stop();
   1147           ++AssignI;
   1148         }
   1149       } else {
   1150         RegIdx = 0;
   1151         End = std::min(End, AssignI.start());
   1152       }
   1153 
   1154       // The interval [Start;End) is continuously mapped to RegIdx, ParentVNI.
   1155       LLVM_DEBUG(dbgs() << " [" << Start << ';' << End << ")=" << RegIdx << '('
   1156                         << printReg(Edit->get(RegIdx)) << ')');
   1157       LiveInterval &LI = LIS.getInterval(Edit->get(RegIdx));
   1158 
   1159       // Check for a simply defined value that can be blitted directly.
   1160       ValueForcePair VFP = Values.lookup(std::make_pair(RegIdx, ParentVNI->id));
   1161       if (VNInfo *VNI = VFP.getPointer()) {
   1162         LLVM_DEBUG(dbgs() << ':' << VNI->id);
   1163         LI.addSegment(LiveInterval::Segment(Start, End, VNI));
   1164         Start = End;
   1165         continue;
   1166       }
   1167 
   1168       // Skip values with forced recomputation.
   1169       if (VFP.getInt()) {
   1170         LLVM_DEBUG(dbgs() << "(recalc)");
   1171         Skipped = true;
   1172         Start = End;
   1173         continue;
   1174       }
   1175 
   1176       LiveIntervalCalc &LIC = getLICalc(RegIdx);
   1177 
   1178       // This value has multiple defs in RegIdx, but it wasn't rematerialized,
   1179       // so the live range is accurate. Add live-in blocks in [Start;End) to the
   1180       // LiveInBlocks.
   1181       MachineFunction::iterator MBB = LIS.getMBBFromIndex(Start)->getIterator();
   1182       SlotIndex BlockStart, BlockEnd;
   1183       std::tie(BlockStart, BlockEnd) = LIS.getSlotIndexes()->getMBBRange(&*MBB);
   1184 
   1185       // The first block may be live-in, or it may have its own def.
   1186       if (Start != BlockStart) {
   1187         VNInfo *VNI = LI.extendInBlock(BlockStart, std::min(BlockEnd, End));
   1188         assert(VNI && "Missing def for complex mapped value");
   1189         LLVM_DEBUG(dbgs() << ':' << VNI->id << "*" << printMBBReference(*MBB));
   1190         // MBB has its own def. Is it also live-out?
   1191         if (BlockEnd <= End)
   1192           LIC.setLiveOutValue(&*MBB, VNI);
   1193 
   1194         // Skip to the next block for live-in.
   1195         ++MBB;
   1196         BlockStart = BlockEnd;
   1197       }
   1198 
   1199       // Handle the live-in blocks covered by [Start;End).
   1200       assert(Start <= BlockStart && "Expected live-in block");
   1201       while (BlockStart < End) {
   1202         LLVM_DEBUG(dbgs() << ">" << printMBBReference(*MBB));
   1203         BlockEnd = LIS.getMBBEndIdx(&*MBB);
   1204         if (BlockStart == ParentVNI->def) {
   1205           // This block has the def of a parent PHI, so it isn't live-in.
   1206           assert(ParentVNI->isPHIDef() && "Non-phi defined at block start?");
   1207           VNInfo *VNI = LI.extendInBlock(BlockStart, std::min(BlockEnd, End));
   1208           assert(VNI && "Missing def for complex mapped parent PHI");
   1209           if (End >= BlockEnd)
   1210             LIC.setLiveOutValue(&*MBB, VNI); // Live-out as well.
   1211         } else {
   1212           // This block needs a live-in value.  The last block covered may not
   1213           // be live-out.
   1214           if (End < BlockEnd)
   1215             LIC.addLiveInBlock(LI, MDT[&*MBB], End);
   1216           else {
   1217             // Live-through, and we don't know the value.
   1218             LIC.addLiveInBlock(LI, MDT[&*MBB]);
   1219             LIC.setLiveOutValue(&*MBB, nullptr);
   1220           }
   1221         }
   1222         BlockStart = BlockEnd;
   1223         ++MBB;
   1224       }
   1225       Start = End;
   1226     } while (Start != S.end);
   1227     LLVM_DEBUG(dbgs() << '\n');
   1228   }
   1229 
   1230   LICalc[0].calculateValues();
   1231   if (SpillMode)
   1232     LICalc[1].calculateValues();
   1233 
   1234   return Skipped;
   1235 }
   1236 
   1237 static bool removeDeadSegment(SlotIndex Def, LiveRange &LR) {
   1238   const LiveRange::Segment *Seg = LR.getSegmentContaining(Def);
   1239   if (Seg == nullptr)
   1240     return true;
   1241   if (Seg->end != Def.getDeadSlot())
   1242     return false;
   1243   // This is a dead PHI. Remove it.
   1244   LR.removeSegment(*Seg, true);
   1245   return true;
   1246 }
   1247 
   1248 void SplitEditor::extendPHIRange(MachineBasicBlock &B, LiveIntervalCalc &LIC,
   1249                                  LiveRange &LR, LaneBitmask LM,
   1250                                  ArrayRef<SlotIndex> Undefs) {
   1251   for (MachineBasicBlock *P : B.predecessors()) {
   1252     SlotIndex End = LIS.getMBBEndIdx(P);
   1253     SlotIndex LastUse = End.getPrevSlot();
   1254     // The predecessor may not have a live-out value. That is OK, like an
   1255     // undef PHI operand.
   1256     LiveInterval &PLI = Edit->getParent();
   1257     // Need the cast because the inputs to ?: would otherwise be deemed
   1258     // "incompatible": SubRange vs LiveInterval.
   1259     LiveRange &PSR = !LM.all() ? getSubRangeForMaskExact(LM, PLI)
   1260                                : static_cast<LiveRange &>(PLI);
   1261     if (PSR.liveAt(LastUse))
   1262       LIC.extend(LR, End, /*PhysReg=*/0, Undefs);
   1263   }
   1264 }
   1265 
   1266 void SplitEditor::extendPHIKillRanges() {
   1267   // Extend live ranges to be live-out for successor PHI values.
   1268 
   1269   // Visit each PHI def slot in the parent live interval. If the def is dead,
   1270   // remove it. Otherwise, extend the live interval to reach the end indexes
   1271   // of all predecessor blocks.
   1272 
   1273   LiveInterval &ParentLI = Edit->getParent();
   1274   for (const VNInfo *V : ParentLI.valnos) {
   1275     if (V->isUnused() || !V->isPHIDef())
   1276       continue;
   1277 
   1278     unsigned RegIdx = RegAssign.lookup(V->def);
   1279     LiveInterval &LI = LIS.getInterval(Edit->get(RegIdx));
   1280     LiveIntervalCalc &LIC = getLICalc(RegIdx);
   1281     MachineBasicBlock &B = *LIS.getMBBFromIndex(V->def);
   1282     if (!removeDeadSegment(V->def, LI))
   1283       extendPHIRange(B, LIC, LI, LaneBitmask::getAll(), /*Undefs=*/{});
   1284   }
   1285 
   1286   SmallVector<SlotIndex, 4> Undefs;
   1287   LiveIntervalCalc SubLIC;
   1288 
   1289   for (LiveInterval::SubRange &PS : ParentLI.subranges()) {
   1290     for (const VNInfo *V : PS.valnos) {
   1291       if (V->isUnused() || !V->isPHIDef())
   1292         continue;
   1293       unsigned RegIdx = RegAssign.lookup(V->def);
   1294       LiveInterval &LI = LIS.getInterval(Edit->get(RegIdx));
   1295       LiveInterval::SubRange &S = getSubRangeForMaskExact(PS.LaneMask, LI);
   1296       if (removeDeadSegment(V->def, S))
   1297         continue;
   1298 
   1299       MachineBasicBlock &B = *LIS.getMBBFromIndex(V->def);
   1300       SubLIC.reset(&VRM.getMachineFunction(), LIS.getSlotIndexes(), &MDT,
   1301                    &LIS.getVNInfoAllocator());
   1302       Undefs.clear();
   1303       LI.computeSubRangeUndefs(Undefs, PS.LaneMask, MRI, *LIS.getSlotIndexes());
   1304       extendPHIRange(B, SubLIC, S, PS.LaneMask, Undefs);
   1305     }
   1306   }
   1307 }
   1308 
   1309 /// rewriteAssigned - Rewrite all uses of Edit->getReg().
   1310 void SplitEditor::rewriteAssigned(bool ExtendRanges) {
   1311   struct ExtPoint {
   1312     ExtPoint(const MachineOperand &O, unsigned R, SlotIndex N)
   1313       : MO(O), RegIdx(R), Next(N) {}
   1314 
   1315     MachineOperand MO;
   1316     unsigned RegIdx;
   1317     SlotIndex Next;
   1318   };
   1319 
   1320   SmallVector<ExtPoint,4> ExtPoints;
   1321 
   1322   for (MachineOperand &MO :
   1323        llvm::make_early_inc_range(MRI.reg_operands(Edit->getReg()))) {
   1324     MachineInstr *MI = MO.getParent();
   1325     // LiveDebugVariables should have handled all DBG_VALUE instructions.
   1326     if (MI->isDebugValue()) {
   1327       LLVM_DEBUG(dbgs() << "Zapping " << *MI);
   1328       MO.setReg(0);
   1329       continue;
   1330     }
   1331 
   1332     // <undef> operands don't really read the register, so it doesn't matter
   1333     // which register we choose.  When the use operand is tied to a def, we must
   1334     // use the same register as the def, so just do that always.
   1335     SlotIndex Idx = LIS.getInstructionIndex(*MI);
   1336     if (MO.isDef() || MO.isUndef())
   1337       Idx = Idx.getRegSlot(MO.isEarlyClobber());
   1338 
   1339     // Rewrite to the mapped register at Idx.
   1340     unsigned RegIdx = RegAssign.lookup(Idx);
   1341     LiveInterval &LI = LIS.getInterval(Edit->get(RegIdx));
   1342     MO.setReg(LI.reg());
   1343     LLVM_DEBUG(dbgs() << "  rewr " << printMBBReference(*MI->getParent())
   1344                       << '\t' << Idx << ':' << RegIdx << '\t' << *MI);
   1345 
   1346     // Extend liveness to Idx if the instruction reads reg.
   1347     if (!ExtendRanges || MO.isUndef())
   1348       continue;
   1349 
   1350     // Skip instructions that don't read Reg.
   1351     if (MO.isDef()) {
   1352       if (!MO.getSubReg() && !MO.isEarlyClobber())
   1353         continue;
   1354       // We may want to extend a live range for a partial redef, or for a use
   1355       // tied to an early clobber.
   1356       Idx = Idx.getPrevSlot();
   1357       if (!Edit->getParent().liveAt(Idx))
   1358         continue;
   1359     } else
   1360       Idx = Idx.getRegSlot(true);
   1361 
   1362     SlotIndex Next = Idx.getNextSlot();
   1363     if (LI.hasSubRanges()) {
   1364       // We have to delay extending subranges until we have seen all operands
   1365       // defining the register. This is because a <def,read-undef> operand
   1366       // will create an "undef" point, and we cannot extend any subranges
   1367       // until all of them have been accounted for.
   1368       if (MO.isUse())
   1369         ExtPoints.push_back(ExtPoint(MO, RegIdx, Next));
   1370     } else {
   1371       LiveIntervalCalc &LIC = getLICalc(RegIdx);
   1372       LIC.extend(LI, Next, 0, ArrayRef<SlotIndex>());
   1373     }
   1374   }
   1375 
   1376   for (ExtPoint &EP : ExtPoints) {
   1377     LiveInterval &LI = LIS.getInterval(Edit->get(EP.RegIdx));
   1378     assert(LI.hasSubRanges());
   1379 
   1380     LiveIntervalCalc SubLIC;
   1381     Register Reg = EP.MO.getReg(), Sub = EP.MO.getSubReg();
   1382     LaneBitmask LM = Sub != 0 ? TRI.getSubRegIndexLaneMask(Sub)
   1383                               : MRI.getMaxLaneMaskForVReg(Reg);
   1384     for (LiveInterval::SubRange &S : LI.subranges()) {
   1385       if ((S.LaneMask & LM).none())
   1386         continue;
   1387       // The problem here can be that the new register may have been created
   1388       // for a partially defined original register. For example:
   1389       //   %0:subreg_hireg<def,read-undef> = ...
   1390       //   ...
   1391       //   %1 = COPY %0
   1392       if (S.empty())
   1393         continue;
   1394       SubLIC.reset(&VRM.getMachineFunction(), LIS.getSlotIndexes(), &MDT,
   1395                    &LIS.getVNInfoAllocator());
   1396       SmallVector<SlotIndex, 4> Undefs;
   1397       LI.computeSubRangeUndefs(Undefs, S.LaneMask, MRI, *LIS.getSlotIndexes());
   1398       SubLIC.extend(S, EP.Next, 0, Undefs);
   1399     }
   1400   }
   1401 
   1402   for (Register R : *Edit) {
   1403     LiveInterval &LI = LIS.getInterval(R);
   1404     if (!LI.hasSubRanges())
   1405       continue;
   1406     LI.clear();
   1407     LI.removeEmptySubRanges();
   1408     LIS.constructMainRangeFromSubranges(LI);
   1409   }
   1410 }
   1411 
   1412 void SplitEditor::deleteRematVictims() {
   1413   SmallVector<MachineInstr*, 8> Dead;
   1414   for (const Register &R : *Edit) {
   1415     LiveInterval *LI = &LIS.getInterval(R);
   1416     for (const LiveRange::Segment &S : LI->segments) {
   1417       // Dead defs end at the dead slot.
   1418       if (S.end != S.valno->def.getDeadSlot())
   1419         continue;
   1420       if (S.valno->isPHIDef())
   1421         continue;
   1422       MachineInstr *MI = LIS.getInstructionFromIndex(S.valno->def);
   1423       assert(MI && "Missing instruction for dead def");
   1424       MI->addRegisterDead(LI->reg(), &TRI);
   1425 
   1426       if (!MI->allDefsAreDead())
   1427         continue;
   1428 
   1429       LLVM_DEBUG(dbgs() << "All defs dead: " << *MI);
   1430       Dead.push_back(MI);
   1431     }
   1432   }
   1433 
   1434   if (Dead.empty())
   1435     return;
   1436 
   1437   Edit->eliminateDeadDefs(Dead, None, &AA);
   1438 }
   1439 
   1440 void SplitEditor::forceRecomputeVNI(const VNInfo &ParentVNI) {
   1441   // Fast-path for common case.
   1442   if (!ParentVNI.isPHIDef()) {
   1443     for (unsigned I = 0, E = Edit->size(); I != E; ++I)
   1444       forceRecompute(I, ParentVNI);
   1445     return;
   1446   }
   1447 
   1448   // Trace value through phis.
   1449   SmallPtrSet<const VNInfo *, 8> Visited; ///< whether VNI was/is in worklist.
   1450   SmallVector<const VNInfo *, 4> WorkList;
   1451   Visited.insert(&ParentVNI);
   1452   WorkList.push_back(&ParentVNI);
   1453 
   1454   const LiveInterval &ParentLI = Edit->getParent();
   1455   const SlotIndexes &Indexes = *LIS.getSlotIndexes();
   1456   do {
   1457     const VNInfo &VNI = *WorkList.back();
   1458     WorkList.pop_back();
   1459     for (unsigned I = 0, E = Edit->size(); I != E; ++I)
   1460       forceRecompute(I, VNI);
   1461     if (!VNI.isPHIDef())
   1462       continue;
   1463 
   1464     MachineBasicBlock &MBB = *Indexes.getMBBFromIndex(VNI.def);
   1465     for (const MachineBasicBlock *Pred : MBB.predecessors()) {
   1466       SlotIndex PredEnd = Indexes.getMBBEndIdx(Pred);
   1467       VNInfo *PredVNI = ParentLI.getVNInfoBefore(PredEnd);
   1468       assert(PredVNI && "Value available in PhiVNI predecessor");
   1469       if (Visited.insert(PredVNI).second)
   1470         WorkList.push_back(PredVNI);
   1471     }
   1472   } while(!WorkList.empty());
   1473 }
   1474 
   1475 void SplitEditor::finish(SmallVectorImpl<unsigned> *LRMap) {
   1476   ++NumFinished;
   1477 
   1478   // At this point, the live intervals in Edit contain VNInfos corresponding to
   1479   // the inserted copies.
   1480 
   1481   // Add the original defs from the parent interval.
   1482   for (const VNInfo *ParentVNI : Edit->getParent().valnos) {
   1483     if (ParentVNI->isUnused())
   1484       continue;
   1485     unsigned RegIdx = RegAssign.lookup(ParentVNI->def);
   1486     defValue(RegIdx, ParentVNI, ParentVNI->def, true);
   1487 
   1488     // Force rematted values to be recomputed everywhere.
   1489     // The new live ranges may be truncated.
   1490     if (Edit->didRematerialize(ParentVNI))
   1491       forceRecomputeVNI(*ParentVNI);
   1492   }
   1493 
   1494   // Hoist back-copies to the complement interval when in spill mode.
   1495   switch (SpillMode) {
   1496   case SM_Partition:
   1497     // Leave all back-copies as is.
   1498     break;
   1499   case SM_Size:
   1500   case SM_Speed:
   1501     // hoistCopies will behave differently between size and speed.
   1502     hoistCopies();
   1503   }
   1504 
   1505   // Transfer the simply mapped values, check if any are skipped.
   1506   bool Skipped = transferValues();
   1507 
   1508   // Rewrite virtual registers, possibly extending ranges.
   1509   rewriteAssigned(Skipped);
   1510 
   1511   if (Skipped)
   1512     extendPHIKillRanges();
   1513   else
   1514     ++NumSimple;
   1515 
   1516   // Delete defs that were rematted everywhere.
   1517   if (Skipped)
   1518     deleteRematVictims();
   1519 
   1520   // Get rid of unused values and set phi-kill flags.
   1521   for (Register Reg : *Edit) {
   1522     LiveInterval &LI = LIS.getInterval(Reg);
   1523     LI.removeEmptySubRanges();
   1524     LI.RenumberValues();
   1525   }
   1526 
   1527   // Provide a reverse mapping from original indices to Edit ranges.
   1528   if (LRMap) {
   1529     LRMap->clear();
   1530     for (unsigned i = 0, e = Edit->size(); i != e; ++i)
   1531       LRMap->push_back(i);
   1532   }
   1533 
   1534   // Now check if any registers were separated into multiple components.
   1535   ConnectedVNInfoEqClasses ConEQ(LIS);
   1536   for (unsigned i = 0, e = Edit->size(); i != e; ++i) {
   1537     // Don't use iterators, they are invalidated by create() below.
   1538     Register VReg = Edit->get(i);
   1539     LiveInterval &LI = LIS.getInterval(VReg);
   1540     SmallVector<LiveInterval*, 8> SplitLIs;
   1541     LIS.splitSeparateComponents(LI, SplitLIs);
   1542     Register Original = VRM.getOriginal(VReg);
   1543     for (LiveInterval *SplitLI : SplitLIs)
   1544       VRM.setIsSplitFromReg(SplitLI->reg(), Original);
   1545 
   1546     // The new intervals all map back to i.
   1547     if (LRMap)
   1548       LRMap->resize(Edit->size(), i);
   1549   }
   1550 
   1551   // Calculate spill weight and allocation hints for new intervals.
   1552   Edit->calculateRegClassAndHint(VRM.getMachineFunction(), VRAI);
   1553 
   1554   assert(!LRMap || LRMap->size() == Edit->size());
   1555 }
   1556 
   1557 //===----------------------------------------------------------------------===//
   1558 //                            Single Block Splitting
   1559 //===----------------------------------------------------------------------===//
   1560 
   1561 bool SplitAnalysis::shouldSplitSingleBlock(const BlockInfo &BI,
   1562                                            bool SingleInstrs) const {
   1563   // Always split for multiple instructions.
   1564   if (!BI.isOneInstr())
   1565     return true;
   1566   // Don't split for single instructions unless explicitly requested.
   1567   if (!SingleInstrs)
   1568     return false;
   1569   // Splitting a live-through range always makes progress.
   1570   if (BI.LiveIn && BI.LiveOut)
   1571     return true;
   1572   // No point in isolating a copy. It has no register class constraints.
   1573   if (LIS.getInstructionFromIndex(BI.FirstInstr)->isCopyLike())
   1574     return false;
   1575   // Finally, don't isolate an end point that was created by earlier splits.
   1576   return isOriginalEndpoint(BI.FirstInstr);
   1577 }
   1578 
   1579 void SplitEditor::splitSingleBlock(const SplitAnalysis::BlockInfo &BI) {
   1580   openIntv();
   1581   SlotIndex LastSplitPoint = SA.getLastSplitPoint(BI.MBB);
   1582   SlotIndex SegStart = enterIntvBefore(std::min(BI.FirstInstr,
   1583     LastSplitPoint));
   1584   if (!BI.LiveOut || BI.LastInstr < LastSplitPoint) {
   1585     useIntv(SegStart, leaveIntvAfter(BI.LastInstr));
   1586   } else {
   1587       // The last use is after the last valid split point.
   1588     SlotIndex SegStop = leaveIntvBefore(LastSplitPoint);
   1589     useIntv(SegStart, SegStop);
   1590     overlapIntv(SegStop, BI.LastInstr);
   1591   }
   1592 }
   1593 
   1594 //===----------------------------------------------------------------------===//
   1595 //                    Global Live Range Splitting Support
   1596 //===----------------------------------------------------------------------===//
   1597 
   1598 // These methods support a method of global live range splitting that uses a
   1599 // global algorithm to decide intervals for CFG edges. They will insert split
   1600 // points and color intervals in basic blocks while avoiding interference.
   1601 //
   1602 // Note that splitSingleBlock is also useful for blocks where both CFG edges
   1603 // are on the stack.
   1604 
   1605 void SplitEditor::splitLiveThroughBlock(unsigned MBBNum,
   1606                                         unsigned IntvIn, SlotIndex LeaveBefore,
   1607                                         unsigned IntvOut, SlotIndex EnterAfter){
   1608   SlotIndex Start, Stop;
   1609   std::tie(Start, Stop) = LIS.getSlotIndexes()->getMBBRange(MBBNum);
   1610 
   1611   LLVM_DEBUG(dbgs() << "%bb." << MBBNum << " [" << Start << ';' << Stop
   1612                     << ") intf " << LeaveBefore << '-' << EnterAfter
   1613                     << ", live-through " << IntvIn << " -> " << IntvOut);
   1614 
   1615   assert((IntvIn || IntvOut) && "Use splitSingleBlock for isolated blocks");
   1616 
   1617   assert((!LeaveBefore || LeaveBefore < Stop) && "Interference after block");
   1618   assert((!IntvIn || !LeaveBefore || LeaveBefore > Start) && "Impossible intf");
   1619   assert((!EnterAfter || EnterAfter >= Start) && "Interference before block");
   1620 
   1621   MachineBasicBlock *MBB = VRM.getMachineFunction().getBlockNumbered(MBBNum);
   1622 
   1623   if (!IntvOut) {
   1624     LLVM_DEBUG(dbgs() << ", spill on entry.\n");
   1625     //
   1626     //        <<<<<<<<<    Possible LeaveBefore interference.
   1627     //    |-----------|    Live through.
   1628     //    -____________    Spill on entry.
   1629     //
   1630     selectIntv(IntvIn);
   1631     SlotIndex Idx = leaveIntvAtTop(*MBB);
   1632     assert((!LeaveBefore || Idx <= LeaveBefore) && "Interference");
   1633     (void)Idx;
   1634     return;
   1635   }
   1636 
   1637   if (!IntvIn) {
   1638     LLVM_DEBUG(dbgs() << ", reload on exit.\n");
   1639     //
   1640     //    >>>>>>>          Possible EnterAfter interference.
   1641     //    |-----------|    Live through.
   1642     //    ___________--    Reload on exit.
   1643     //
   1644     selectIntv(IntvOut);
   1645     SlotIndex Idx = enterIntvAtEnd(*MBB);
   1646     assert((!EnterAfter || Idx >= EnterAfter) && "Interference");
   1647     (void)Idx;
   1648     return;
   1649   }
   1650 
   1651   if (IntvIn == IntvOut && !LeaveBefore && !EnterAfter) {
   1652     LLVM_DEBUG(dbgs() << ", straight through.\n");
   1653     //
   1654     //    |-----------|    Live through.
   1655     //    -------------    Straight through, same intv, no interference.
   1656     //
   1657     selectIntv(IntvOut);
   1658     useIntv(Start, Stop);
   1659     return;
   1660   }
   1661 
   1662   // We cannot legally insert splits after LSP.
   1663   SlotIndex LSP = SA.getLastSplitPoint(MBBNum);
   1664   assert((!IntvOut || !EnterAfter || EnterAfter < LSP) && "Impossible intf");
   1665 
   1666   if (IntvIn != IntvOut && (!LeaveBefore || !EnterAfter ||
   1667                   LeaveBefore.getBaseIndex() > EnterAfter.getBoundaryIndex())) {
   1668     LLVM_DEBUG(dbgs() << ", switch avoiding interference.\n");
   1669     //
   1670     //    >>>>     <<<<    Non-overlapping EnterAfter/LeaveBefore interference.
   1671     //    |-----------|    Live through.
   1672     //    ------=======    Switch intervals between interference.
   1673     //
   1674     selectIntv(IntvOut);
   1675     SlotIndex Idx;
   1676     if (LeaveBefore && LeaveBefore < LSP) {
   1677       Idx = enterIntvBefore(LeaveBefore);
   1678       useIntv(Idx, Stop);
   1679     } else {
   1680       Idx = enterIntvAtEnd(*MBB);
   1681     }
   1682     selectIntv(IntvIn);
   1683     useIntv(Start, Idx);
   1684     assert((!LeaveBefore || Idx <= LeaveBefore) && "Interference");
   1685     assert((!EnterAfter || Idx >= EnterAfter) && "Interference");
   1686     return;
   1687   }
   1688 
   1689   LLVM_DEBUG(dbgs() << ", create local intv for interference.\n");
   1690   //
   1691   //    >>><><><><<<<    Overlapping EnterAfter/LeaveBefore interference.
   1692   //    |-----------|    Live through.
   1693   //    ==---------==    Switch intervals before/after interference.
   1694   //
   1695   assert(LeaveBefore <= EnterAfter && "Missed case");
   1696 
   1697   selectIntv(IntvOut);
   1698   SlotIndex Idx = enterIntvAfter(EnterAfter);
   1699   useIntv(Idx, Stop);
   1700   assert((!EnterAfter || Idx >= EnterAfter) && "Interference");
   1701 
   1702   selectIntv(IntvIn);
   1703   Idx = leaveIntvBefore(LeaveBefore);
   1704   useIntv(Start, Idx);
   1705   assert((!LeaveBefore || Idx <= LeaveBefore) && "Interference");
   1706 }
   1707 
   1708 void SplitEditor::splitRegInBlock(const SplitAnalysis::BlockInfo &BI,
   1709                                   unsigned IntvIn, SlotIndex LeaveBefore) {
   1710   SlotIndex Start, Stop;
   1711   std::tie(Start, Stop) = LIS.getSlotIndexes()->getMBBRange(BI.MBB);
   1712 
   1713   LLVM_DEBUG(dbgs() << printMBBReference(*BI.MBB) << " [" << Start << ';'
   1714                     << Stop << "), uses " << BI.FirstInstr << '-'
   1715                     << BI.LastInstr << ", reg-in " << IntvIn
   1716                     << ", leave before " << LeaveBefore
   1717                     << (BI.LiveOut ? ", stack-out" : ", killed in block"));
   1718 
   1719   assert(IntvIn && "Must have register in");
   1720   assert(BI.LiveIn && "Must be live-in");
   1721   assert((!LeaveBefore || LeaveBefore > Start) && "Bad interference");
   1722 
   1723   if (!BI.LiveOut && (!LeaveBefore || LeaveBefore >= BI.LastInstr)) {
   1724     LLVM_DEBUG(dbgs() << " before interference.\n");
   1725     //
   1726     //               <<<    Interference after kill.
   1727     //     |---o---x   |    Killed in block.
   1728     //     =========        Use IntvIn everywhere.
   1729     //
   1730     selectIntv(IntvIn);
   1731     useIntv(Start, BI.LastInstr);
   1732     return;
   1733   }
   1734 
   1735   SlotIndex LSP = SA.getLastSplitPoint(BI.MBB);
   1736 
   1737   if (!LeaveBefore || LeaveBefore > BI.LastInstr.getBoundaryIndex()) {
   1738     //
   1739     //               <<<    Possible interference after last use.
   1740     //     |---o---o---|    Live-out on stack.
   1741     //     =========____    Leave IntvIn after last use.
   1742     //
   1743     //                 <    Interference after last use.
   1744     //     |---o---o--o|    Live-out on stack, late last use.
   1745     //     ============     Copy to stack after LSP, overlap IntvIn.
   1746     //            \_____    Stack interval is live-out.
   1747     //
   1748     if (BI.LastInstr < LSP) {
   1749       LLVM_DEBUG(dbgs() << ", spill after last use before interference.\n");
   1750       selectIntv(IntvIn);
   1751       SlotIndex Idx = leaveIntvAfter(BI.LastInstr);
   1752       useIntv(Start, Idx);
   1753       assert((!LeaveBefore || Idx <= LeaveBefore) && "Interference");
   1754     } else {
   1755       LLVM_DEBUG(dbgs() << ", spill before last split point.\n");
   1756       selectIntv(IntvIn);
   1757       SlotIndex Idx = leaveIntvBefore(LSP);
   1758       overlapIntv(Idx, BI.LastInstr);
   1759       useIntv(Start, Idx);
   1760       assert((!LeaveBefore || Idx <= LeaveBefore) && "Interference");
   1761     }
   1762     return;
   1763   }
   1764 
   1765   // The interference is overlapping somewhere we wanted to use IntvIn. That
   1766   // means we need to create a local interval that can be allocated a
   1767   // different register.
   1768   unsigned LocalIntv = openIntv();
   1769   (void)LocalIntv;
   1770   LLVM_DEBUG(dbgs() << ", creating local interval " << LocalIntv << ".\n");
   1771 
   1772   if (!BI.LiveOut || BI.LastInstr < LSP) {
   1773     //
   1774     //           <<<<<<<    Interference overlapping uses.
   1775     //     |---o---o---|    Live-out on stack.
   1776     //     =====----____    Leave IntvIn before interference, then spill.
   1777     //
   1778     SlotIndex To = leaveIntvAfter(BI.LastInstr);
   1779     SlotIndex From = enterIntvBefore(LeaveBefore);
   1780     useIntv(From, To);
   1781     selectIntv(IntvIn);
   1782     useIntv(Start, From);
   1783     assert((!LeaveBefore || From <= LeaveBefore) && "Interference");
   1784     return;
   1785   }
   1786 
   1787   //           <<<<<<<    Interference overlapping uses.
   1788   //     |---o---o--o|    Live-out on stack, late last use.
   1789   //     =====-------     Copy to stack before LSP, overlap LocalIntv.
   1790   //            \_____    Stack interval is live-out.
   1791   //
   1792   SlotIndex To = leaveIntvBefore(LSP);
   1793   overlapIntv(To, BI.LastInstr);
   1794   SlotIndex From = enterIntvBefore(std::min(To, LeaveBefore));
   1795   useIntv(From, To);
   1796   selectIntv(IntvIn);
   1797   useIntv(Start, From);
   1798   assert((!LeaveBefore || From <= LeaveBefore) && "Interference");
   1799 }
   1800 
   1801 void SplitEditor::splitRegOutBlock(const SplitAnalysis::BlockInfo &BI,
   1802                                    unsigned IntvOut, SlotIndex EnterAfter) {
   1803   SlotIndex Start, Stop;
   1804   std::tie(Start, Stop) = LIS.getSlotIndexes()->getMBBRange(BI.MBB);
   1805 
   1806   LLVM_DEBUG(dbgs() << printMBBReference(*BI.MBB) << " [" << Start << ';'
   1807                     << Stop << "), uses " << BI.FirstInstr << '-'
   1808                     << BI.LastInstr << ", reg-out " << IntvOut
   1809                     << ", enter after " << EnterAfter
   1810                     << (BI.LiveIn ? ", stack-in" : ", defined in block"));
   1811 
   1812   SlotIndex LSP = SA.getLastSplitPoint(BI.MBB);
   1813 
   1814   assert(IntvOut && "Must have register out");
   1815   assert(BI.LiveOut && "Must be live-out");
   1816   assert((!EnterAfter || EnterAfter < LSP) && "Bad interference");
   1817 
   1818   if (!BI.LiveIn && (!EnterAfter || EnterAfter <= BI.FirstInstr)) {
   1819     LLVM_DEBUG(dbgs() << " after interference.\n");
   1820     //
   1821     //    >>>>             Interference before def.
   1822     //    |   o---o---|    Defined in block.
   1823     //        =========    Use IntvOut everywhere.
   1824     //
   1825     selectIntv(IntvOut);
   1826     useIntv(BI.FirstInstr, Stop);
   1827     return;
   1828   }
   1829 
   1830   if (!EnterAfter || EnterAfter < BI.FirstInstr.getBaseIndex()) {
   1831     LLVM_DEBUG(dbgs() << ", reload after interference.\n");
   1832     //
   1833     //    >>>>             Interference before def.
   1834     //    |---o---o---|    Live-through, stack-in.
   1835     //    ____=========    Enter IntvOut before first use.
   1836     //
   1837     selectIntv(IntvOut);
   1838     SlotIndex Idx = enterIntvBefore(std::min(LSP, BI.FirstInstr));
   1839     useIntv(Idx, Stop);
   1840     assert((!EnterAfter || Idx >= EnterAfter) && "Interference");
   1841     return;
   1842   }
   1843 
   1844   // The interference is overlapping somewhere we wanted to use IntvOut. That
   1845   // means we need to create a local interval that can be allocated a
   1846   // different register.
   1847   LLVM_DEBUG(dbgs() << ", interference overlaps uses.\n");
   1848   //
   1849   //    >>>>>>>          Interference overlapping uses.
   1850   //    |---o---o---|    Live-through, stack-in.
   1851   //    ____---======    Create local interval for interference range.
   1852   //
   1853   selectIntv(IntvOut);
   1854   SlotIndex Idx = enterIntvAfter(EnterAfter);
   1855   useIntv(Idx, Stop);
   1856   assert((!EnterAfter || Idx >= EnterAfter) && "Interference");
   1857 
   1858   openIntv();
   1859   SlotIndex From = enterIntvBefore(std::min(Idx, BI.FirstInstr));
   1860   useIntv(From, Idx);
   1861 }
   1862 
   1863 void SplitAnalysis::BlockInfo::print(raw_ostream &OS) const {
   1864   OS << "{" << printMBBReference(*MBB) << ", "
   1865      << "uses " << FirstInstr << " to " << LastInstr << ", "
   1866      << "1st def " << FirstDef << ", "
   1867      << (LiveIn ? "live in" : "dead in") << ", "
   1868      << (LiveOut ? "live out" : "dead out") << "}";
   1869 }
   1870 
   1871 void SplitAnalysis::BlockInfo::dump() const {
   1872   print(dbgs());
   1873   dbgs() << "\n";
   1874 }
   1875