Home | History | Annotate | Download | only in CodeGen
      1 //===---------- SplitKit.cpp - Toolkit for splitting live ranges ----------===//
      2 //
      3 //                     The LLVM Compiler Infrastructure
      4 //
      5 // This file is distributed under the University of Illinois Open Source
      6 // License. See LICENSE.TXT for details.
      7 //
      8 //===----------------------------------------------------------------------===//
      9 //
     10 // This file contains the SplitAnalysis class as well as mutator functions for
     11 // live range splitting.
     12 //
     13 //===----------------------------------------------------------------------===//
     14 
     15 #define DEBUG_TYPE "regalloc"
     16 #include "SplitKit.h"
     17 #include "VirtRegMap.h"
     18 #include "llvm/ADT/Statistic.h"
     19 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
     20 #include "llvm/CodeGen/LiveRangeEdit.h"
     21 #include "llvm/CodeGen/MachineDominators.h"
     22 #include "llvm/CodeGen/MachineInstrBuilder.h"
     23 #include "llvm/CodeGen/MachineLoopInfo.h"
     24 #include "llvm/CodeGen/MachineRegisterInfo.h"
     25 #include "llvm/Support/Debug.h"
     26 #include "llvm/Support/raw_ostream.h"
     27 #include "llvm/Target/TargetInstrInfo.h"
     28 #include "llvm/Target/TargetMachine.h"
     29 
     30 using namespace llvm;
     31 
     32 STATISTIC(NumFinished, "Number of splits finished");
     33 STATISTIC(NumSimple,   "Number of splits that were simple");
     34 STATISTIC(NumCopies,   "Number of copies inserted for splitting");
     35 STATISTIC(NumRemats,   "Number of rematerialized defs for splitting");
     36 STATISTIC(NumRepairs,  "Number of invalid live ranges repaired");
     37 
     38 //===----------------------------------------------------------------------===//
     39 //                                 Split Analysis
     40 //===----------------------------------------------------------------------===//
     41 
     42 SplitAnalysis::SplitAnalysis(const VirtRegMap &vrm,
     43                              const LiveIntervals &lis,
     44                              const MachineLoopInfo &mli)
     45   : MF(vrm.getMachineFunction()),
     46     VRM(vrm),
     47     LIS(lis),
     48     Loops(mli),
     49     TII(*MF.getTarget().getInstrInfo()),
     50     CurLI(0),
     51     LastSplitPoint(MF.getNumBlockIDs()) {}
     52 
     53 void SplitAnalysis::clear() {
     54   UseSlots.clear();
     55   UseBlocks.clear();
     56   ThroughBlocks.clear();
     57   CurLI = 0;
     58   DidRepairRange = false;
     59 }
     60 
     61 SlotIndex SplitAnalysis::computeLastSplitPoint(unsigned Num) {
     62   const MachineBasicBlock *MBB = MF.getBlockNumbered(Num);
     63   const MachineBasicBlock *LPad = MBB->getLandingPadSuccessor();
     64   std::pair<SlotIndex, SlotIndex> &LSP = LastSplitPoint[Num];
     65   SlotIndex MBBEnd = LIS.getMBBEndIdx(MBB);
     66 
     67   // Compute split points on the first call. The pair is independent of the
     68   // current live interval.
     69   if (!LSP.first.isValid()) {
     70     MachineBasicBlock::const_iterator FirstTerm = MBB->getFirstTerminator();
     71     if (FirstTerm == MBB->end())
     72       LSP.first = MBBEnd;
     73     else
     74       LSP.first = LIS.getInstructionIndex(FirstTerm);
     75 
     76     // If there is a landing pad successor, also find the call instruction.
     77     if (!LPad)
     78       return LSP.first;
     79     // There may not be a call instruction (?) in which case we ignore LPad.
     80     LSP.second = LSP.first;
     81     for (MachineBasicBlock::const_iterator I = MBB->end(), E = MBB->begin();
     82          I != E;) {
     83       --I;
     84       if (I->isCall()) {
     85         LSP.second = LIS.getInstructionIndex(I);
     86         break;
     87       }
     88     }
     89   }
     90 
     91   // If CurLI is live into a landing pad successor, move the last split point
     92   // back to the call that may throw.
     93   if (!LPad || !LSP.second || !LIS.isLiveInToMBB(*CurLI, LPad))
     94     return LSP.first;
     95 
     96   // Find the value leaving MBB.
     97   const VNInfo *VNI = CurLI->getVNInfoBefore(MBBEnd);
     98   if (!VNI)
     99     return LSP.first;
    100 
    101   // If the value leaving MBB was defined after the call in MBB, it can't
    102   // really be live-in to the landing pad.  This can happen if the landing pad
    103   // has a PHI, and this register is undef on the exceptional edge.
    104   // <rdar://problem/10664933>
    105   if (!SlotIndex::isEarlierInstr(VNI->def, LSP.second) && VNI->def < MBBEnd)
    106     return LSP.first;
    107 
    108   // Value is properly live-in to the landing pad.
    109   // Only allow splits before the call.
    110   return LSP.second;
    111 }
    112 
    113 MachineBasicBlock::iterator
    114 SplitAnalysis::getLastSplitPointIter(MachineBasicBlock *MBB) {
    115   SlotIndex LSP = getLastSplitPoint(MBB->getNumber());
    116   if (LSP == LIS.getMBBEndIdx(MBB))
    117     return MBB->end();
    118   return LIS.getInstructionFromIndex(LSP);
    119 }
    120 
    121 /// analyzeUses - Count instructions, basic blocks, and loops using CurLI.
    122 void SplitAnalysis::analyzeUses() {
    123   assert(UseSlots.empty() && "Call clear first");
    124 
    125   // First get all the defs from the interval values. This provides the correct
    126   // slots for early clobbers.
    127   for (LiveInterval::const_vni_iterator I = CurLI->vni_begin(),
    128        E = CurLI->vni_end(); I != E; ++I)
    129     if (!(*I)->isPHIDef() && !(*I)->isUnused())
    130       UseSlots.push_back((*I)->def);
    131 
    132   // Get use slots form the use-def chain.
    133   const MachineRegisterInfo &MRI = MF.getRegInfo();
    134   for (MachineRegisterInfo::use_nodbg_iterator
    135        I = MRI.use_nodbg_begin(CurLI->reg), E = MRI.use_nodbg_end(); I != E;
    136        ++I)
    137     if (!I.getOperand().isUndef())
    138       UseSlots.push_back(LIS.getInstructionIndex(&*I).getRegSlot());
    139 
    140   array_pod_sort(UseSlots.begin(), UseSlots.end());
    141 
    142   // Remove duplicates, keeping the smaller slot for each instruction.
    143   // That is what we want for early clobbers.
    144   UseSlots.erase(std::unique(UseSlots.begin(), UseSlots.end(),
    145                              SlotIndex::isSameInstr),
    146                  UseSlots.end());
    147 
    148   // Compute per-live block info.
    149   if (!calcLiveBlockInfo()) {
    150     // FIXME: calcLiveBlockInfo found inconsistencies in the live range.
    151     // I am looking at you, RegisterCoalescer!
    152     DidRepairRange = true;
    153     ++NumRepairs;
    154     DEBUG(dbgs() << "*** Fixing inconsistent live interval! ***\n");
    155     const_cast<LiveIntervals&>(LIS)
    156       .shrinkToUses(const_cast<LiveInterval*>(CurLI));
    157     UseBlocks.clear();
    158     ThroughBlocks.clear();
    159     bool fixed = calcLiveBlockInfo();
    160     (void)fixed;
    161     assert(fixed && "Couldn't fix broken live interval");
    162   }
    163 
    164   DEBUG(dbgs() << "Analyze counted "
    165                << UseSlots.size() << " instrs in "
    166                << UseBlocks.size() << " blocks, through "
    167                << NumThroughBlocks << " blocks.\n");
    168 }
    169 
    170 /// calcLiveBlockInfo - Fill the LiveBlocks array with information about blocks
    171 /// where CurLI is live.
    172 bool SplitAnalysis::calcLiveBlockInfo() {
    173   ThroughBlocks.resize(MF.getNumBlockIDs());
    174   NumThroughBlocks = NumGapBlocks = 0;
    175   if (CurLI->empty())
    176     return true;
    177 
    178   LiveInterval::const_iterator LVI = CurLI->begin();
    179   LiveInterval::const_iterator LVE = CurLI->end();
    180 
    181   SmallVectorImpl<SlotIndex>::const_iterator UseI, UseE;
    182   UseI = UseSlots.begin();
    183   UseE = UseSlots.end();
    184 
    185   // Loop over basic blocks where CurLI is live.
    186   MachineFunction::iterator MFI = LIS.getMBBFromIndex(LVI->start);
    187   for (;;) {
    188     BlockInfo BI;
    189     BI.MBB = MFI;
    190     SlotIndex Start, Stop;
    191     tie(Start, Stop) = LIS.getSlotIndexes()->getMBBRange(BI.MBB);
    192 
    193     // If the block contains no uses, the range must be live through. At one
    194     // point, RegisterCoalescer could create dangling ranges that ended
    195     // mid-block.
    196     if (UseI == UseE || *UseI >= Stop) {
    197       ++NumThroughBlocks;
    198       ThroughBlocks.set(BI.MBB->getNumber());
    199       // The range shouldn't end mid-block if there are no uses. This shouldn't
    200       // happen.
    201       if (LVI->end < Stop)
    202         return false;
    203     } else {
    204       // This block has uses. Find the first and last uses in the block.
    205       BI.FirstInstr = *UseI;
    206       assert(BI.FirstInstr >= Start);
    207       do ++UseI;
    208       while (UseI != UseE && *UseI < Stop);
    209       BI.LastInstr = UseI[-1];
    210       assert(BI.LastInstr < Stop);
    211 
    212       // LVI is the first live segment overlapping MBB.
    213       BI.LiveIn = LVI->start <= Start;
    214 
    215       // When not live in, the first use should be a def.
    216       if (!BI.LiveIn) {
    217         assert(LVI->start == LVI->valno->def && "Dangling LiveRange start");
    218         assert(LVI->start == BI.FirstInstr && "First instr should be a def");
    219         BI.FirstDef = BI.FirstInstr;
    220       }
    221 
    222       // Look for gaps in the live range.
    223       BI.LiveOut = true;
    224       while (LVI->end < Stop) {
    225         SlotIndex LastStop = LVI->end;
    226         if (++LVI == LVE || LVI->start >= Stop) {
    227           BI.LiveOut = false;
    228           BI.LastInstr = LastStop;
    229           break;
    230         }
    231 
    232         if (LastStop < LVI->start) {
    233           // There is a gap in the live range. Create duplicate entries for the
    234           // live-in snippet and the live-out snippet.
    235           ++NumGapBlocks;
    236 
    237           // Push the Live-in part.
    238           BI.LiveOut = false;
    239           UseBlocks.push_back(BI);
    240           UseBlocks.back().LastInstr = LastStop;
    241 
    242           // Set up BI for the live-out part.
    243           BI.LiveIn = false;
    244           BI.LiveOut = true;
    245           BI.FirstInstr = BI.FirstDef = LVI->start;
    246         }
    247 
    248         // A LiveRange that starts in the middle of the block must be a def.
    249         assert(LVI->start == LVI->valno->def && "Dangling LiveRange start");
    250         if (!BI.FirstDef)
    251           BI.FirstDef = LVI->start;
    252       }
    253 
    254       UseBlocks.push_back(BI);
    255 
    256       // LVI is now at LVE or LVI->end >= Stop.
    257       if (LVI == LVE)
    258         break;
    259     }
    260 
    261     // Live segment ends exactly at Stop. Move to the next segment.
    262     if (LVI->end == Stop && ++LVI == LVE)
    263       break;
    264 
    265     // Pick the next basic block.
    266     if (LVI->start < Stop)
    267       ++MFI;
    268     else
    269       MFI = LIS.getMBBFromIndex(LVI->start);
    270   }
    271 
    272   assert(getNumLiveBlocks() == countLiveBlocks(CurLI) && "Bad block count");
    273   return true;
    274 }
    275 
    276 unsigned SplitAnalysis::countLiveBlocks(const LiveInterval *cli) const {
    277   if (cli->empty())
    278     return 0;
    279   LiveInterval *li = const_cast<LiveInterval*>(cli);
    280   LiveInterval::iterator LVI = li->begin();
    281   LiveInterval::iterator LVE = li->end();
    282   unsigned Count = 0;
    283 
    284   // Loop over basic blocks where li is live.
    285   MachineFunction::const_iterator MFI = LIS.getMBBFromIndex(LVI->start);
    286   SlotIndex Stop = LIS.getMBBEndIdx(MFI);
    287   for (;;) {
    288     ++Count;
    289     LVI = li->advanceTo(LVI, Stop);
    290     if (LVI == LVE)
    291       return Count;
    292     do {
    293       ++MFI;
    294       Stop = LIS.getMBBEndIdx(MFI);
    295     } while (Stop <= LVI->start);
    296   }
    297 }
    298 
    299 bool SplitAnalysis::isOriginalEndpoint(SlotIndex Idx) const {
    300   unsigned OrigReg = VRM.getOriginal(CurLI->reg);
    301   const LiveInterval &Orig = LIS.getInterval(OrigReg);
    302   assert(!Orig.empty() && "Splitting empty interval?");
    303   LiveInterval::const_iterator I = Orig.find(Idx);
    304 
    305   // Range containing Idx should begin at Idx.
    306   if (I != Orig.end() && I->start <= Idx)
    307     return I->start == Idx;
    308 
    309   // Range does not contain Idx, previous must end at Idx.
    310   return I != Orig.begin() && (--I)->end == Idx;
    311 }
    312 
    313 void SplitAnalysis::analyze(const LiveInterval *li) {
    314   clear();
    315   CurLI = li;
    316   analyzeUses();
    317 }
    318 
    319 
    320 //===----------------------------------------------------------------------===//
    321 //                               Split Editor
    322 //===----------------------------------------------------------------------===//
    323 
    324 /// Create a new SplitEditor for editing the LiveInterval analyzed by SA.
    325 SplitEditor::SplitEditor(SplitAnalysis &sa,
    326                          LiveIntervals &lis,
    327                          VirtRegMap &vrm,
    328                          MachineDominatorTree &mdt)
    329   : SA(sa), LIS(lis), VRM(vrm),
    330     MRI(vrm.getMachineFunction().getRegInfo()),
    331     MDT(mdt),
    332     TII(*vrm.getMachineFunction().getTarget().getInstrInfo()),
    333     TRI(*vrm.getMachineFunction().getTarget().getRegisterInfo()),
    334     Edit(0),
    335     OpenIdx(0),
    336     SpillMode(SM_Partition),
    337     RegAssign(Allocator)
    338 {}
    339 
    340 void SplitEditor::reset(LiveRangeEdit &LRE, ComplementSpillMode SM) {
    341   Edit = &LRE;
    342   SpillMode = SM;
    343   OpenIdx = 0;
    344   RegAssign.clear();
    345   Values.clear();
    346 
    347   // Reset the LiveRangeCalc instances needed for this spill mode.
    348   LRCalc[0].reset(&VRM.getMachineFunction());
    349   if (SpillMode)
    350     LRCalc[1].reset(&VRM.getMachineFunction());
    351 
    352   // We don't need an AliasAnalysis since we will only be performing
    353   // cheap-as-a-copy remats anyway.
    354   Edit->anyRematerializable(0);
    355 }
    356 
    357 void SplitEditor::dump() const {
    358   if (RegAssign.empty()) {
    359     dbgs() << " empty\n";
    360     return;
    361   }
    362 
    363   for (RegAssignMap::const_iterator I = RegAssign.begin(); I.valid(); ++I)
    364     dbgs() << " [" << I.start() << ';' << I.stop() << "):" << I.value();
    365   dbgs() << '\n';
    366 }
    367 
    368 VNInfo *SplitEditor::defValue(unsigned RegIdx,
    369                               const VNInfo *ParentVNI,
    370                               SlotIndex Idx) {
    371   assert(ParentVNI && "Mapping  NULL value");
    372   assert(Idx.isValid() && "Invalid SlotIndex");
    373   assert(Edit->getParent().getVNInfoAt(Idx) == ParentVNI && "Bad Parent VNI");
    374   LiveInterval *LI = Edit->get(RegIdx);
    375 
    376   // Create a new value.
    377   VNInfo *VNI = LI->getNextValue(Idx, LIS.getVNInfoAllocator());
    378 
    379   // Use insert for lookup, so we can add missing values with a second lookup.
    380   std::pair<ValueMap::iterator, bool> InsP =
    381     Values.insert(std::make_pair(std::make_pair(RegIdx, ParentVNI->id),
    382                                  ValueForcePair(VNI, false)));
    383 
    384   // This was the first time (RegIdx, ParentVNI) was mapped.
    385   // Keep it as a simple def without any liveness.
    386   if (InsP.second)
    387     return VNI;
    388 
    389   // If the previous value was a simple mapping, add liveness for it now.
    390   if (VNInfo *OldVNI = InsP.first->second.getPointer()) {
    391     SlotIndex Def = OldVNI->def;
    392     LI->addRange(LiveRange(Def, Def.getDeadSlot(), OldVNI));
    393     // No longer a simple mapping.  Switch to a complex, non-forced mapping.
    394     InsP.first->second = ValueForcePair();
    395   }
    396 
    397   // This is a complex mapping, add liveness for VNI
    398   SlotIndex Def = VNI->def;
    399   LI->addRange(LiveRange(Def, Def.getDeadSlot(), VNI));
    400 
    401   return VNI;
    402 }
    403 
    404 void SplitEditor::forceRecompute(unsigned RegIdx, const VNInfo *ParentVNI) {
    405   assert(ParentVNI && "Mapping  NULL value");
    406   ValueForcePair &VFP = Values[std::make_pair(RegIdx, ParentVNI->id)];
    407   VNInfo *VNI = VFP.getPointer();
    408 
    409   // ParentVNI was either unmapped or already complex mapped. Either way, just
    410   // set the force bit.
    411   if (!VNI) {
    412     VFP.setInt(true);
    413     return;
    414   }
    415 
    416   // This was previously a single mapping. Make sure the old def is represented
    417   // by a trivial live range.
    418   SlotIndex Def = VNI->def;
    419   Edit->get(RegIdx)->addRange(LiveRange(Def, Def.getDeadSlot(), VNI));
    420   // Mark as complex mapped, forced.
    421   VFP = ValueForcePair(0, true);
    422 }
    423 
    424 VNInfo *SplitEditor::defFromParent(unsigned RegIdx,
    425                                    VNInfo *ParentVNI,
    426                                    SlotIndex UseIdx,
    427                                    MachineBasicBlock &MBB,
    428                                    MachineBasicBlock::iterator I) {
    429   MachineInstr *CopyMI = 0;
    430   SlotIndex Def;
    431   LiveInterval *LI = Edit->get(RegIdx);
    432 
    433   // We may be trying to avoid interference that ends at a deleted instruction,
    434   // so always begin RegIdx 0 early and all others late.
    435   bool Late = RegIdx != 0;
    436 
    437   // Attempt cheap-as-a-copy rematerialization.
    438   LiveRangeEdit::Remat RM(ParentVNI);
    439   if (Edit->canRematerializeAt(RM, UseIdx, true)) {
    440     Def = Edit->rematerializeAt(MBB, I, LI->reg, RM, TRI, Late);
    441     ++NumRemats;
    442   } else {
    443     // Can't remat, just insert a copy from parent.
    444     CopyMI = BuildMI(MBB, I, DebugLoc(), TII.get(TargetOpcode::COPY), LI->reg)
    445                .addReg(Edit->getReg());
    446     Def = LIS.getSlotIndexes()->insertMachineInstrInMaps(CopyMI, Late)
    447             .getRegSlot();
    448     ++NumCopies;
    449   }
    450 
    451   // Define the value in Reg.
    452   return defValue(RegIdx, ParentVNI, Def);
    453 }
    454 
    455 /// Create a new virtual register and live interval.
    456 unsigned SplitEditor::openIntv() {
    457   // Create the complement as index 0.
    458   if (Edit->empty())
    459     Edit->create();
    460 
    461   // Create the open interval.
    462   OpenIdx = Edit->size();
    463   Edit->create();
    464   return OpenIdx;
    465 }
    466 
    467 void SplitEditor::selectIntv(unsigned Idx) {
    468   assert(Idx != 0 && "Cannot select the complement interval");
    469   assert(Idx < Edit->size() && "Can only select previously opened interval");
    470   DEBUG(dbgs() << "    selectIntv " << OpenIdx << " -> " << Idx << '\n');
    471   OpenIdx = Idx;
    472 }
    473 
    474 SlotIndex SplitEditor::enterIntvBefore(SlotIndex Idx) {
    475   assert(OpenIdx && "openIntv not called before enterIntvBefore");
    476   DEBUG(dbgs() << "    enterIntvBefore " << Idx);
    477   Idx = Idx.getBaseIndex();
    478   VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(Idx);
    479   if (!ParentVNI) {
    480     DEBUG(dbgs() << ": not live\n");
    481     return Idx;
    482   }
    483   DEBUG(dbgs() << ": valno " << ParentVNI->id << '\n');
    484   MachineInstr *MI = LIS.getInstructionFromIndex(Idx);
    485   assert(MI && "enterIntvBefore called with invalid index");
    486 
    487   VNInfo *VNI = defFromParent(OpenIdx, ParentVNI, Idx, *MI->getParent(), MI);
    488   return VNI->def;
    489 }
    490 
    491 SlotIndex SplitEditor::enterIntvAfter(SlotIndex Idx) {
    492   assert(OpenIdx && "openIntv not called before enterIntvAfter");
    493   DEBUG(dbgs() << "    enterIntvAfter " << Idx);
    494   Idx = Idx.getBoundaryIndex();
    495   VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(Idx);
    496   if (!ParentVNI) {
    497     DEBUG(dbgs() << ": not live\n");
    498     return Idx;
    499   }
    500   DEBUG(dbgs() << ": valno " << ParentVNI->id << '\n');
    501   MachineInstr *MI = LIS.getInstructionFromIndex(Idx);
    502   assert(MI && "enterIntvAfter called with invalid index");
    503 
    504   VNInfo *VNI = defFromParent(OpenIdx, ParentVNI, Idx, *MI->getParent(),
    505                               llvm::next(MachineBasicBlock::iterator(MI)));
    506   return VNI->def;
    507 }
    508 
    509 SlotIndex SplitEditor::enterIntvAtEnd(MachineBasicBlock &MBB) {
    510   assert(OpenIdx && "openIntv not called before enterIntvAtEnd");
    511   SlotIndex End = LIS.getMBBEndIdx(&MBB);
    512   SlotIndex Last = End.getPrevSlot();
    513   DEBUG(dbgs() << "    enterIntvAtEnd BB#" << MBB.getNumber() << ", " << Last);
    514   VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(Last);
    515   if (!ParentVNI) {
    516     DEBUG(dbgs() << ": not live\n");
    517     return End;
    518   }
    519   DEBUG(dbgs() << ": valno " << ParentVNI->id);
    520   VNInfo *VNI = defFromParent(OpenIdx, ParentVNI, Last, MBB,
    521                               SA.getLastSplitPointIter(&MBB));
    522   RegAssign.insert(VNI->def, End, OpenIdx);
    523   DEBUG(dump());
    524   return VNI->def;
    525 }
    526 
    527 /// useIntv - indicate that all instructions in MBB should use OpenLI.
    528 void SplitEditor::useIntv(const MachineBasicBlock &MBB) {
    529   useIntv(LIS.getMBBStartIdx(&MBB), LIS.getMBBEndIdx(&MBB));
    530 }
    531 
    532 void SplitEditor::useIntv(SlotIndex Start, SlotIndex End) {
    533   assert(OpenIdx && "openIntv not called before useIntv");
    534   DEBUG(dbgs() << "    useIntv [" << Start << ';' << End << "):");
    535   RegAssign.insert(Start, End, OpenIdx);
    536   DEBUG(dump());
    537 }
    538 
    539 SlotIndex SplitEditor::leaveIntvAfter(SlotIndex Idx) {
    540   assert(OpenIdx && "openIntv not called before leaveIntvAfter");
    541   DEBUG(dbgs() << "    leaveIntvAfter " << Idx);
    542 
    543   // The interval must be live beyond the instruction at Idx.
    544   SlotIndex Boundary = Idx.getBoundaryIndex();
    545   VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(Boundary);
    546   if (!ParentVNI) {
    547     DEBUG(dbgs() << ": not live\n");
    548     return Boundary.getNextSlot();
    549   }
    550   DEBUG(dbgs() << ": valno " << ParentVNI->id << '\n');
    551   MachineInstr *MI = LIS.getInstructionFromIndex(Boundary);
    552   assert(MI && "No instruction at index");
    553 
    554   // In spill mode, make live ranges as short as possible by inserting the copy
    555   // before MI.  This is only possible if that instruction doesn't redefine the
    556   // value.  The inserted COPY is not a kill, and we don't need to recompute
    557   // the source live range.  The spiller also won't try to hoist this copy.
    558   if (SpillMode && !SlotIndex::isSameInstr(ParentVNI->def, Idx) &&
    559       MI->readsVirtualRegister(Edit->getReg())) {
    560     forceRecompute(0, ParentVNI);
    561     defFromParent(0, ParentVNI, Idx, *MI->getParent(), MI);
    562     return Idx;
    563   }
    564 
    565   VNInfo *VNI = defFromParent(0, ParentVNI, Boundary, *MI->getParent(),
    566                               llvm::next(MachineBasicBlock::iterator(MI)));
    567   return VNI->def;
    568 }
    569 
    570 SlotIndex SplitEditor::leaveIntvBefore(SlotIndex Idx) {
    571   assert(OpenIdx && "openIntv not called before leaveIntvBefore");
    572   DEBUG(dbgs() << "    leaveIntvBefore " << Idx);
    573 
    574   // The interval must be live into the instruction at Idx.
    575   Idx = Idx.getBaseIndex();
    576   VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(Idx);
    577   if (!ParentVNI) {
    578     DEBUG(dbgs() << ": not live\n");
    579     return Idx.getNextSlot();
    580   }
    581   DEBUG(dbgs() << ": valno " << ParentVNI->id << '\n');
    582 
    583   MachineInstr *MI = LIS.getInstructionFromIndex(Idx);
    584   assert(MI && "No instruction at index");
    585   VNInfo *VNI = defFromParent(0, ParentVNI, Idx, *MI->getParent(), MI);
    586   return VNI->def;
    587 }
    588 
    589 SlotIndex SplitEditor::leaveIntvAtTop(MachineBasicBlock &MBB) {
    590   assert(OpenIdx && "openIntv not called before leaveIntvAtTop");
    591   SlotIndex Start = LIS.getMBBStartIdx(&MBB);
    592   DEBUG(dbgs() << "    leaveIntvAtTop BB#" << MBB.getNumber() << ", " << Start);
    593 
    594   VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(Start);
    595   if (!ParentVNI) {
    596     DEBUG(dbgs() << ": not live\n");
    597     return Start;
    598   }
    599 
    600   VNInfo *VNI = defFromParent(0, ParentVNI, Start, MBB,
    601                               MBB.SkipPHIsAndLabels(MBB.begin()));
    602   RegAssign.insert(Start, VNI->def, OpenIdx);
    603   DEBUG(dump());
    604   return VNI->def;
    605 }
    606 
    607 void SplitEditor::overlapIntv(SlotIndex Start, SlotIndex End) {
    608   assert(OpenIdx && "openIntv not called before overlapIntv");
    609   const VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(Start);
    610   assert(ParentVNI == Edit->getParent().getVNInfoBefore(End) &&
    611          "Parent changes value in extended range");
    612   assert(LIS.getMBBFromIndex(Start) == LIS.getMBBFromIndex(End) &&
    613          "Range cannot span basic blocks");
    614 
    615   // The complement interval will be extended as needed by LRCalc.extend().
    616   if (ParentVNI)
    617     forceRecompute(0, ParentVNI);
    618   DEBUG(dbgs() << "    overlapIntv [" << Start << ';' << End << "):");
    619   RegAssign.insert(Start, End, OpenIdx);
    620   DEBUG(dump());
    621 }
    622 
    623 //===----------------------------------------------------------------------===//
    624 //                                  Spill modes
    625 //===----------------------------------------------------------------------===//
    626 
    627 void SplitEditor::removeBackCopies(SmallVectorImpl<VNInfo*> &Copies) {
    628   LiveInterval *LI = Edit->get(0);
    629   DEBUG(dbgs() << "Removing " << Copies.size() << " back-copies.\n");
    630   RegAssignMap::iterator AssignI;
    631   AssignI.setMap(RegAssign);
    632 
    633   for (unsigned i = 0, e = Copies.size(); i != e; ++i) {
    634     VNInfo *VNI = Copies[i];
    635     SlotIndex Def = VNI->def;
    636     MachineInstr *MI = LIS.getInstructionFromIndex(Def);
    637     assert(MI && "No instruction for back-copy");
    638 
    639     MachineBasicBlock *MBB = MI->getParent();
    640     MachineBasicBlock::iterator MBBI(MI);
    641     bool AtBegin;
    642     do AtBegin = MBBI == MBB->begin();
    643     while (!AtBegin && (--MBBI)->isDebugValue());
    644 
    645     DEBUG(dbgs() << "Removing " << Def << '\t' << *MI);
    646     LI->removeValNo(VNI);
    647     LIS.RemoveMachineInstrFromMaps(MI);
    648     MI->eraseFromParent();
    649 
    650     // Adjust RegAssign if a register assignment is killed at VNI->def.  We
    651     // want to avoid calculating the live range of the source register if
    652     // possible.
    653     AssignI.find(VNI->def.getPrevSlot());
    654     if (!AssignI.valid() || AssignI.start() >= Def)
    655       continue;
    656     // If MI doesn't kill the assigned register, just leave it.
    657     if (AssignI.stop() != Def)
    658       continue;
    659     unsigned RegIdx = AssignI.value();
    660     if (AtBegin || !MBBI->readsVirtualRegister(Edit->getReg())) {
    661       DEBUG(dbgs() << "  cannot find simple kill of RegIdx " << RegIdx << '\n');
    662       forceRecompute(RegIdx, Edit->getParent().getVNInfoAt(Def));
    663     } else {
    664       SlotIndex Kill = LIS.getInstructionIndex(MBBI).getRegSlot();
    665       DEBUG(dbgs() << "  move kill to " << Kill << '\t' << *MBBI);
    666       AssignI.setStop(Kill);
    667     }
    668   }
    669 }
    670 
    671 MachineBasicBlock*
    672 SplitEditor::findShallowDominator(MachineBasicBlock *MBB,
    673                                   MachineBasicBlock *DefMBB) {
    674   if (MBB == DefMBB)
    675     return MBB;
    676   assert(MDT.dominates(DefMBB, MBB) && "MBB must be dominated by the def.");
    677 
    678   const MachineLoopInfo &Loops = SA.Loops;
    679   const MachineLoop *DefLoop = Loops.getLoopFor(DefMBB);
    680   MachineDomTreeNode *DefDomNode = MDT[DefMBB];
    681 
    682   // Best candidate so far.
    683   MachineBasicBlock *BestMBB = MBB;
    684   unsigned BestDepth = UINT_MAX;
    685 
    686   for (;;) {
    687     const MachineLoop *Loop = Loops.getLoopFor(MBB);
    688 
    689     // MBB isn't in a loop, it doesn't get any better.  All dominators have a
    690     // higher frequency by definition.
    691     if (!Loop) {
    692       DEBUG(dbgs() << "Def in BB#" << DefMBB->getNumber() << " dominates BB#"
    693                    << MBB->getNumber() << " at depth 0\n");
    694       return MBB;
    695     }
    696 
    697     // We'll never be able to exit the DefLoop.
    698     if (Loop == DefLoop) {
    699       DEBUG(dbgs() << "Def in BB#" << DefMBB->getNumber() << " dominates BB#"
    700                    << MBB->getNumber() << " in the same loop\n");
    701       return MBB;
    702     }
    703 
    704     // Least busy dominator seen so far.
    705     unsigned Depth = Loop->getLoopDepth();
    706     if (Depth < BestDepth) {
    707       BestMBB = MBB;
    708       BestDepth = Depth;
    709       DEBUG(dbgs() << "Def in BB#" << DefMBB->getNumber() << " dominates BB#"
    710                    << MBB->getNumber() << " at depth " << Depth << '\n');
    711     }
    712 
    713     // Leave loop by going to the immediate dominator of the loop header.
    714     // This is a bigger stride than simply walking up the dominator tree.
    715     MachineDomTreeNode *IDom = MDT[Loop->getHeader()]->getIDom();
    716 
    717     // Too far up the dominator tree?
    718     if (!IDom || !MDT.dominates(DefDomNode, IDom))
    719       return BestMBB;
    720 
    721     MBB = IDom->getBlock();
    722   }
    723 }
    724 
    725 void SplitEditor::hoistCopiesForSize() {
    726   // Get the complement interval, always RegIdx 0.
    727   LiveInterval *LI = Edit->get(0);
    728   LiveInterval *Parent = &Edit->getParent();
    729 
    730   // Track the nearest common dominator for all back-copies for each ParentVNI,
    731   // indexed by ParentVNI->id.
    732   typedef std::pair<MachineBasicBlock*, SlotIndex> DomPair;
    733   SmallVector<DomPair, 8> NearestDom(Parent->getNumValNums());
    734 
    735   // Find the nearest common dominator for parent values with multiple
    736   // back-copies.  If a single back-copy dominates, put it in DomPair.second.
    737   for (LiveInterval::vni_iterator VI = LI->vni_begin(), VE = LI->vni_end();
    738        VI != VE; ++VI) {
    739     VNInfo *VNI = *VI;
    740     VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(VNI->def);
    741     assert(ParentVNI && "Parent not live at complement def");
    742 
    743     // Don't hoist remats.  The complement is probably going to disappear
    744     // completely anyway.
    745     if (Edit->didRematerialize(ParentVNI))
    746       continue;
    747 
    748     MachineBasicBlock *ValMBB = LIS.getMBBFromIndex(VNI->def);
    749     DomPair &Dom = NearestDom[ParentVNI->id];
    750 
    751     // Keep directly defined parent values.  This is either a PHI or an
    752     // instruction in the complement range.  All other copies of ParentVNI
    753     // should be eliminated.
    754     if (VNI->def == ParentVNI->def) {
    755       DEBUG(dbgs() << "Direct complement def at " << VNI->def << '\n');
    756       Dom = DomPair(ValMBB, VNI->def);
    757       continue;
    758     }
    759     // Skip the singly mapped values.  There is nothing to gain from hoisting a
    760     // single back-copy.
    761     if (Values.lookup(std::make_pair(0, ParentVNI->id)).getPointer()) {
    762       DEBUG(dbgs() << "Single complement def at " << VNI->def << '\n');
    763       continue;
    764     }
    765 
    766     if (!Dom.first) {
    767       // First time we see ParentVNI.  VNI dominates itself.
    768       Dom = DomPair(ValMBB, VNI->def);
    769     } else if (Dom.first == ValMBB) {
    770       // Two defs in the same block.  Pick the earlier def.
    771       if (!Dom.second.isValid() || VNI->def < Dom.second)
    772         Dom.second = VNI->def;
    773     } else {
    774       // Different basic blocks. Check if one dominates.
    775       MachineBasicBlock *Near =
    776         MDT.findNearestCommonDominator(Dom.first, ValMBB);
    777       if (Near == ValMBB)
    778         // Def ValMBB dominates.
    779         Dom = DomPair(ValMBB, VNI->def);
    780       else if (Near != Dom.first)
    781         // None dominate. Hoist to common dominator, need new def.
    782         Dom = DomPair(Near, SlotIndex());
    783     }
    784 
    785     DEBUG(dbgs() << "Multi-mapped complement " << VNI->id << '@' << VNI->def
    786                  << " for parent " << ParentVNI->id << '@' << ParentVNI->def
    787                  << " hoist to BB#" << Dom.first->getNumber() << ' '
    788                  << Dom.second << '\n');
    789   }
    790 
    791   // Insert the hoisted copies.
    792   for (unsigned i = 0, e = Parent->getNumValNums(); i != e; ++i) {
    793     DomPair &Dom = NearestDom[i];
    794     if (!Dom.first || Dom.second.isValid())
    795       continue;
    796     // This value needs a hoisted copy inserted at the end of Dom.first.
    797     VNInfo *ParentVNI = Parent->getValNumInfo(i);
    798     MachineBasicBlock *DefMBB = LIS.getMBBFromIndex(ParentVNI->def);
    799     // Get a less loopy dominator than Dom.first.
    800     Dom.first = findShallowDominator(Dom.first, DefMBB);
    801     SlotIndex Last = LIS.getMBBEndIdx(Dom.first).getPrevSlot();
    802     Dom.second =
    803       defFromParent(0, ParentVNI, Last, *Dom.first,
    804                     SA.getLastSplitPointIter(Dom.first))->def;
    805   }
    806 
    807   // Remove redundant back-copies that are now known to be dominated by another
    808   // def with the same value.
    809   SmallVector<VNInfo*, 8> BackCopies;
    810   for (LiveInterval::vni_iterator VI = LI->vni_begin(), VE = LI->vni_end();
    811        VI != VE; ++VI) {
    812     VNInfo *VNI = *VI;
    813     VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(VNI->def);
    814     const DomPair &Dom = NearestDom[ParentVNI->id];
    815     if (!Dom.first || Dom.second == VNI->def)
    816       continue;
    817     BackCopies.push_back(VNI);
    818     forceRecompute(0, ParentVNI);
    819   }
    820   removeBackCopies(BackCopies);
    821 }
    822 
    823 
    824 /// transferValues - Transfer all possible values to the new live ranges.
    825 /// Values that were rematerialized are left alone, they need LRCalc.extend().
    826 bool SplitEditor::transferValues() {
    827   bool Skipped = false;
    828   RegAssignMap::const_iterator AssignI = RegAssign.begin();
    829   for (LiveInterval::const_iterator ParentI = Edit->getParent().begin(),
    830          ParentE = Edit->getParent().end(); ParentI != ParentE; ++ParentI) {
    831     DEBUG(dbgs() << "  blit " << *ParentI << ':');
    832     VNInfo *ParentVNI = ParentI->valno;
    833     // RegAssign has holes where RegIdx 0 should be used.
    834     SlotIndex Start = ParentI->start;
    835     AssignI.advanceTo(Start);
    836     do {
    837       unsigned RegIdx;
    838       SlotIndex End = ParentI->end;
    839       if (!AssignI.valid()) {
    840         RegIdx = 0;
    841       } else if (AssignI.start() <= Start) {
    842         RegIdx = AssignI.value();
    843         if (AssignI.stop() < End) {
    844           End = AssignI.stop();
    845           ++AssignI;
    846         }
    847       } else {
    848         RegIdx = 0;
    849         End = std::min(End, AssignI.start());
    850       }
    851 
    852       // The interval [Start;End) is continuously mapped to RegIdx, ParentVNI.
    853       DEBUG(dbgs() << " [" << Start << ';' << End << ")=" << RegIdx);
    854       LiveInterval *LI = Edit->get(RegIdx);
    855 
    856       // Check for a simply defined value that can be blitted directly.
    857       ValueForcePair VFP = Values.lookup(std::make_pair(RegIdx, ParentVNI->id));
    858       if (VNInfo *VNI = VFP.getPointer()) {
    859         DEBUG(dbgs() << ':' << VNI->id);
    860         LI->addRange(LiveRange(Start, End, VNI));
    861         Start = End;
    862         continue;
    863       }
    864 
    865       // Skip values with forced recomputation.
    866       if (VFP.getInt()) {
    867         DEBUG(dbgs() << "(recalc)");
    868         Skipped = true;
    869         Start = End;
    870         continue;
    871       }
    872 
    873       LiveRangeCalc &LRC = getLRCalc(RegIdx);
    874 
    875       // This value has multiple defs in RegIdx, but it wasn't rematerialized,
    876       // so the live range is accurate. Add live-in blocks in [Start;End) to the
    877       // LiveInBlocks.
    878       MachineFunction::iterator MBB = LIS.getMBBFromIndex(Start);
    879       SlotIndex BlockStart, BlockEnd;
    880       tie(BlockStart, BlockEnd) = LIS.getSlotIndexes()->getMBBRange(MBB);
    881 
    882       // The first block may be live-in, or it may have its own def.
    883       if (Start != BlockStart) {
    884         VNInfo *VNI = LI->extendInBlock(BlockStart, std::min(BlockEnd, End));
    885         assert(VNI && "Missing def for complex mapped value");
    886         DEBUG(dbgs() << ':' << VNI->id << "*BB#" << MBB->getNumber());
    887         // MBB has its own def. Is it also live-out?
    888         if (BlockEnd <= End)
    889           LRC.setLiveOutValue(MBB, VNI);
    890 
    891         // Skip to the next block for live-in.
    892         ++MBB;
    893         BlockStart = BlockEnd;
    894       }
    895 
    896       // Handle the live-in blocks covered by [Start;End).
    897       assert(Start <= BlockStart && "Expected live-in block");
    898       while (BlockStart < End) {
    899         DEBUG(dbgs() << ">BB#" << MBB->getNumber());
    900         BlockEnd = LIS.getMBBEndIdx(MBB);
    901         if (BlockStart == ParentVNI->def) {
    902           // This block has the def of a parent PHI, so it isn't live-in.
    903           assert(ParentVNI->isPHIDef() && "Non-phi defined at block start?");
    904           VNInfo *VNI = LI->extendInBlock(BlockStart, std::min(BlockEnd, End));
    905           assert(VNI && "Missing def for complex mapped parent PHI");
    906           if (End >= BlockEnd)
    907             LRC.setLiveOutValue(MBB, VNI); // Live-out as well.
    908         } else {
    909           // This block needs a live-in value.  The last block covered may not
    910           // be live-out.
    911           if (End < BlockEnd)
    912             LRC.addLiveInBlock(LI, MDT[MBB], End);
    913           else {
    914             // Live-through, and we don't know the value.
    915             LRC.addLiveInBlock(LI, MDT[MBB]);
    916             LRC.setLiveOutValue(MBB, 0);
    917           }
    918         }
    919         BlockStart = BlockEnd;
    920         ++MBB;
    921       }
    922       Start = End;
    923     } while (Start != ParentI->end);
    924     DEBUG(dbgs() << '\n');
    925   }
    926 
    927   LRCalc[0].calculateValues(LIS.getSlotIndexes(), &MDT,
    928                             &LIS.getVNInfoAllocator());
    929   if (SpillMode)
    930     LRCalc[1].calculateValues(LIS.getSlotIndexes(), &MDT,
    931                               &LIS.getVNInfoAllocator());
    932 
    933   return Skipped;
    934 }
    935 
    936 void SplitEditor::extendPHIKillRanges() {
    937     // Extend live ranges to be live-out for successor PHI values.
    938   for (LiveInterval::const_vni_iterator I = Edit->getParent().vni_begin(),
    939        E = Edit->getParent().vni_end(); I != E; ++I) {
    940     const VNInfo *PHIVNI = *I;
    941     if (PHIVNI->isUnused() || !PHIVNI->isPHIDef())
    942       continue;
    943     unsigned RegIdx = RegAssign.lookup(PHIVNI->def);
    944     LiveInterval *LI = Edit->get(RegIdx);
    945     LiveRangeCalc &LRC = getLRCalc(RegIdx);
    946     MachineBasicBlock *MBB = LIS.getMBBFromIndex(PHIVNI->def);
    947     for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
    948          PE = MBB->pred_end(); PI != PE; ++PI) {
    949       SlotIndex End = LIS.getMBBEndIdx(*PI);
    950       SlotIndex LastUse = End.getPrevSlot();
    951       // The predecessor may not have a live-out value. That is OK, like an
    952       // undef PHI operand.
    953       if (Edit->getParent().liveAt(LastUse)) {
    954         assert(RegAssign.lookup(LastUse) == RegIdx &&
    955                "Different register assignment in phi predecessor");
    956         LRC.extend(LI, End,
    957                    LIS.getSlotIndexes(), &MDT, &LIS.getVNInfoAllocator());
    958       }
    959     }
    960   }
    961 }
    962 
    963 /// rewriteAssigned - Rewrite all uses of Edit->getReg().
    964 void SplitEditor::rewriteAssigned(bool ExtendRanges) {
    965   for (MachineRegisterInfo::reg_iterator RI = MRI.reg_begin(Edit->getReg()),
    966        RE = MRI.reg_end(); RI != RE;) {
    967     MachineOperand &MO = RI.getOperand();
    968     MachineInstr *MI = MO.getParent();
    969     ++RI;
    970     // LiveDebugVariables should have handled all DBG_VALUE instructions.
    971     if (MI->isDebugValue()) {
    972       DEBUG(dbgs() << "Zapping " << *MI);
    973       MO.setReg(0);
    974       continue;
    975     }
    976 
    977     // <undef> operands don't really read the register, so it doesn't matter
    978     // which register we choose.  When the use operand is tied to a def, we must
    979     // use the same register as the def, so just do that always.
    980     SlotIndex Idx = LIS.getInstructionIndex(MI);
    981     if (MO.isDef() || MO.isUndef())
    982       Idx = Idx.getRegSlot(MO.isEarlyClobber());
    983 
    984     // Rewrite to the mapped register at Idx.
    985     unsigned RegIdx = RegAssign.lookup(Idx);
    986     LiveInterval *LI = Edit->get(RegIdx);
    987     MO.setReg(LI->reg);
    988     DEBUG(dbgs() << "  rewr BB#" << MI->getParent()->getNumber() << '\t'
    989                  << Idx << ':' << RegIdx << '\t' << *MI);
    990 
    991     // Extend liveness to Idx if the instruction reads reg.
    992     if (!ExtendRanges || MO.isUndef())
    993       continue;
    994 
    995     // Skip instructions that don't read Reg.
    996     if (MO.isDef()) {
    997       if (!MO.getSubReg() && !MO.isEarlyClobber())
    998         continue;
    999       // We may wan't to extend a live range for a partial redef, or for a use
   1000       // tied to an early clobber.
   1001       Idx = Idx.getPrevSlot();
   1002       if (!Edit->getParent().liveAt(Idx))
   1003         continue;
   1004     } else
   1005       Idx = Idx.getRegSlot(true);
   1006 
   1007     getLRCalc(RegIdx).extend(LI, Idx.getNextSlot(), LIS.getSlotIndexes(),
   1008                              &MDT, &LIS.getVNInfoAllocator());
   1009   }
   1010 }
   1011 
   1012 void SplitEditor::deleteRematVictims() {
   1013   SmallVector<MachineInstr*, 8> Dead;
   1014   for (LiveRangeEdit::iterator I = Edit->begin(), E = Edit->end(); I != E; ++I){
   1015     LiveInterval *LI = *I;
   1016     for (LiveInterval::const_iterator LII = LI->begin(), LIE = LI->end();
   1017            LII != LIE; ++LII) {
   1018       // Dead defs end at the dead slot.
   1019       if (LII->end != LII->valno->def.getDeadSlot())
   1020         continue;
   1021       MachineInstr *MI = LIS.getInstructionFromIndex(LII->valno->def);
   1022       assert(MI && "Missing instruction for dead def");
   1023       MI->addRegisterDead(LI->reg, &TRI);
   1024 
   1025       if (!MI->allDefsAreDead())
   1026         continue;
   1027 
   1028       DEBUG(dbgs() << "All defs dead: " << *MI);
   1029       Dead.push_back(MI);
   1030     }
   1031   }
   1032 
   1033   if (Dead.empty())
   1034     return;
   1035 
   1036   Edit->eliminateDeadDefs(Dead);
   1037 }
   1038 
   1039 void SplitEditor::finish(SmallVectorImpl<unsigned> *LRMap) {
   1040   ++NumFinished;
   1041 
   1042   // At this point, the live intervals in Edit contain VNInfos corresponding to
   1043   // the inserted copies.
   1044 
   1045   // Add the original defs from the parent interval.
   1046   for (LiveInterval::const_vni_iterator I = Edit->getParent().vni_begin(),
   1047          E = Edit->getParent().vni_end(); I != E; ++I) {
   1048     const VNInfo *ParentVNI = *I;
   1049     if (ParentVNI->isUnused())
   1050       continue;
   1051     unsigned RegIdx = RegAssign.lookup(ParentVNI->def);
   1052     VNInfo *VNI = defValue(RegIdx, ParentVNI, ParentVNI->def);
   1053     VNI->setIsPHIDef(ParentVNI->isPHIDef());
   1054 
   1055     // Force rematted values to be recomputed everywhere.
   1056     // The new live ranges may be truncated.
   1057     if (Edit->didRematerialize(ParentVNI))
   1058       for (unsigned i = 0, e = Edit->size(); i != e; ++i)
   1059         forceRecompute(i, ParentVNI);
   1060   }
   1061 
   1062   // Hoist back-copies to the complement interval when in spill mode.
   1063   switch (SpillMode) {
   1064   case SM_Partition:
   1065     // Leave all back-copies as is.
   1066     break;
   1067   case SM_Size:
   1068     hoistCopiesForSize();
   1069     break;
   1070   case SM_Speed:
   1071     llvm_unreachable("Spill mode 'speed' not implemented yet");
   1072   }
   1073 
   1074   // Transfer the simply mapped values, check if any are skipped.
   1075   bool Skipped = transferValues();
   1076   if (Skipped)
   1077     extendPHIKillRanges();
   1078   else
   1079     ++NumSimple;
   1080 
   1081   // Rewrite virtual registers, possibly extending ranges.
   1082   rewriteAssigned(Skipped);
   1083 
   1084   // Delete defs that were rematted everywhere.
   1085   if (Skipped)
   1086     deleteRematVictims();
   1087 
   1088   // Get rid of unused values and set phi-kill flags.
   1089   for (LiveRangeEdit::iterator I = Edit->begin(), E = Edit->end(); I != E; ++I)
   1090     (*I)->RenumberValues(LIS);
   1091 
   1092   // Provide a reverse mapping from original indices to Edit ranges.
   1093   if (LRMap) {
   1094     LRMap->clear();
   1095     for (unsigned i = 0, e = Edit->size(); i != e; ++i)
   1096       LRMap->push_back(i);
   1097   }
   1098 
   1099   // Now check if any registers were separated into multiple components.
   1100   ConnectedVNInfoEqClasses ConEQ(LIS);
   1101   for (unsigned i = 0, e = Edit->size(); i != e; ++i) {
   1102     // Don't use iterators, they are invalidated by create() below.
   1103     LiveInterval *li = Edit->get(i);
   1104     unsigned NumComp = ConEQ.Classify(li);
   1105     if (NumComp <= 1)
   1106       continue;
   1107     DEBUG(dbgs() << "  " << NumComp << " components: " << *li << '\n');
   1108     SmallVector<LiveInterval*, 8> dups;
   1109     dups.push_back(li);
   1110     for (unsigned j = 1; j != NumComp; ++j)
   1111       dups.push_back(&Edit->create());
   1112     ConEQ.Distribute(&dups[0], MRI);
   1113     // The new intervals all map back to i.
   1114     if (LRMap)
   1115       LRMap->resize(Edit->size(), i);
   1116   }
   1117 
   1118   // Calculate spill weight and allocation hints for new intervals.
   1119   Edit->calculateRegClassAndHint(VRM.getMachineFunction(), SA.Loops);
   1120 
   1121   assert(!LRMap || LRMap->size() == Edit->size());
   1122 }
   1123 
   1124 
   1125 //===----------------------------------------------------------------------===//
   1126 //                            Single Block Splitting
   1127 //===----------------------------------------------------------------------===//
   1128 
   1129 bool SplitAnalysis::shouldSplitSingleBlock(const BlockInfo &BI,
   1130                                            bool SingleInstrs) const {
   1131   // Always split for multiple instructions.
   1132   if (!BI.isOneInstr())
   1133     return true;
   1134   // Don't split for single instructions unless explicitly requested.
   1135   if (!SingleInstrs)
   1136     return false;
   1137   // Splitting a live-through range always makes progress.
   1138   if (BI.LiveIn && BI.LiveOut)
   1139     return true;
   1140   // No point in isolating a copy. It has no register class constraints.
   1141   if (LIS.getInstructionFromIndex(BI.FirstInstr)->isCopyLike())
   1142     return false;
   1143   // Finally, don't isolate an end point that was created by earlier splits.
   1144   return isOriginalEndpoint(BI.FirstInstr);
   1145 }
   1146 
   1147 void SplitEditor::splitSingleBlock(const SplitAnalysis::BlockInfo &BI) {
   1148   openIntv();
   1149   SlotIndex LastSplitPoint = SA.getLastSplitPoint(BI.MBB->getNumber());
   1150   SlotIndex SegStart = enterIntvBefore(std::min(BI.FirstInstr,
   1151     LastSplitPoint));
   1152   if (!BI.LiveOut || BI.LastInstr < LastSplitPoint) {
   1153     useIntv(SegStart, leaveIntvAfter(BI.LastInstr));
   1154   } else {
   1155       // The last use is after the last valid split point.
   1156     SlotIndex SegStop = leaveIntvBefore(LastSplitPoint);
   1157     useIntv(SegStart, SegStop);
   1158     overlapIntv(SegStop, BI.LastInstr);
   1159   }
   1160 }
   1161 
   1162 
   1163 //===----------------------------------------------------------------------===//
   1164 //                    Global Live Range Splitting Support
   1165 //===----------------------------------------------------------------------===//
   1166 
   1167 // These methods support a method of global live range splitting that uses a
   1168 // global algorithm to decide intervals for CFG edges. They will insert split
   1169 // points and color intervals in basic blocks while avoiding interference.
   1170 //
   1171 // Note that splitSingleBlock is also useful for blocks where both CFG edges
   1172 // are on the stack.
   1173 
   1174 void SplitEditor::splitLiveThroughBlock(unsigned MBBNum,
   1175                                         unsigned IntvIn, SlotIndex LeaveBefore,
   1176                                         unsigned IntvOut, SlotIndex EnterAfter){
   1177   SlotIndex Start, Stop;
   1178   tie(Start, Stop) = LIS.getSlotIndexes()->getMBBRange(MBBNum);
   1179 
   1180   DEBUG(dbgs() << "BB#" << MBBNum << " [" << Start << ';' << Stop
   1181                << ") intf " << LeaveBefore << '-' << EnterAfter
   1182                << ", live-through " << IntvIn << " -> " << IntvOut);
   1183 
   1184   assert((IntvIn || IntvOut) && "Use splitSingleBlock for isolated blocks");
   1185 
   1186   assert((!LeaveBefore || LeaveBefore < Stop) && "Interference after block");
   1187   assert((!IntvIn || !LeaveBefore || LeaveBefore > Start) && "Impossible intf");
   1188   assert((!EnterAfter || EnterAfter >= Start) && "Interference before block");
   1189 
   1190   MachineBasicBlock *MBB = VRM.getMachineFunction().getBlockNumbered(MBBNum);
   1191 
   1192   if (!IntvOut) {
   1193     DEBUG(dbgs() << ", spill on entry.\n");
   1194     //
   1195     //        <<<<<<<<<    Possible LeaveBefore interference.
   1196     //    |-----------|    Live through.
   1197     //    -____________    Spill on entry.
   1198     //
   1199     selectIntv(IntvIn);
   1200     SlotIndex Idx = leaveIntvAtTop(*MBB);
   1201     assert((!LeaveBefore || Idx <= LeaveBefore) && "Interference");
   1202     (void)Idx;
   1203     return;
   1204   }
   1205 
   1206   if (!IntvIn) {
   1207     DEBUG(dbgs() << ", reload on exit.\n");
   1208     //
   1209     //    >>>>>>>          Possible EnterAfter interference.
   1210     //    |-----------|    Live through.
   1211     //    ___________--    Reload on exit.
   1212     //
   1213     selectIntv(IntvOut);
   1214     SlotIndex Idx = enterIntvAtEnd(*MBB);
   1215     assert((!EnterAfter || Idx >= EnterAfter) && "Interference");
   1216     (void)Idx;
   1217     return;
   1218   }
   1219 
   1220   if (IntvIn == IntvOut && !LeaveBefore && !EnterAfter) {
   1221     DEBUG(dbgs() << ", straight through.\n");
   1222     //
   1223     //    |-----------|    Live through.
   1224     //    -------------    Straight through, same intv, no interference.
   1225     //
   1226     selectIntv(IntvOut);
   1227     useIntv(Start, Stop);
   1228     return;
   1229   }
   1230 
   1231   // We cannot legally insert splits after LSP.
   1232   SlotIndex LSP = SA.getLastSplitPoint(MBBNum);
   1233   assert((!IntvOut || !EnterAfter || EnterAfter < LSP) && "Impossible intf");
   1234 
   1235   if (IntvIn != IntvOut && (!LeaveBefore || !EnterAfter ||
   1236                   LeaveBefore.getBaseIndex() > EnterAfter.getBoundaryIndex())) {
   1237     DEBUG(dbgs() << ", switch avoiding interference.\n");
   1238     //
   1239     //    >>>>     <<<<    Non-overlapping EnterAfter/LeaveBefore interference.
   1240     //    |-----------|    Live through.
   1241     //    ------=======    Switch intervals between interference.
   1242     //
   1243     selectIntv(IntvOut);
   1244     SlotIndex Idx;
   1245     if (LeaveBefore && LeaveBefore < LSP) {
   1246       Idx = enterIntvBefore(LeaveBefore);
   1247       useIntv(Idx, Stop);
   1248     } else {
   1249       Idx = enterIntvAtEnd(*MBB);
   1250     }
   1251     selectIntv(IntvIn);
   1252     useIntv(Start, Idx);
   1253     assert((!LeaveBefore || Idx <= LeaveBefore) && "Interference");
   1254     assert((!EnterAfter || Idx >= EnterAfter) && "Interference");
   1255     return;
   1256   }
   1257 
   1258   DEBUG(dbgs() << ", create local intv for interference.\n");
   1259   //
   1260   //    >>><><><><<<<    Overlapping EnterAfter/LeaveBefore interference.
   1261   //    |-----------|    Live through.
   1262   //    ==---------==    Switch intervals before/after interference.
   1263   //
   1264   assert(LeaveBefore <= EnterAfter && "Missed case");
   1265 
   1266   selectIntv(IntvOut);
   1267   SlotIndex Idx = enterIntvAfter(EnterAfter);
   1268   useIntv(Idx, Stop);
   1269   assert((!EnterAfter || Idx >= EnterAfter) && "Interference");
   1270 
   1271   selectIntv(IntvIn);
   1272   Idx = leaveIntvBefore(LeaveBefore);
   1273   useIntv(Start, Idx);
   1274   assert((!LeaveBefore || Idx <= LeaveBefore) && "Interference");
   1275 }
   1276 
   1277 
   1278 void SplitEditor::splitRegInBlock(const SplitAnalysis::BlockInfo &BI,
   1279                                   unsigned IntvIn, SlotIndex LeaveBefore) {
   1280   SlotIndex Start, Stop;
   1281   tie(Start, Stop) = LIS.getSlotIndexes()->getMBBRange(BI.MBB);
   1282 
   1283   DEBUG(dbgs() << "BB#" << BI.MBB->getNumber() << " [" << Start << ';' << Stop
   1284                << "), uses " << BI.FirstInstr << '-' << BI.LastInstr
   1285                << ", reg-in " << IntvIn << ", leave before " << LeaveBefore
   1286                << (BI.LiveOut ? ", stack-out" : ", killed in block"));
   1287 
   1288   assert(IntvIn && "Must have register in");
   1289   assert(BI.LiveIn && "Must be live-in");
   1290   assert((!LeaveBefore || LeaveBefore > Start) && "Bad interference");
   1291 
   1292   if (!BI.LiveOut && (!LeaveBefore || LeaveBefore >= BI.LastInstr)) {
   1293     DEBUG(dbgs() << " before interference.\n");
   1294     //
   1295     //               <<<    Interference after kill.
   1296     //     |---o---x   |    Killed in block.
   1297     //     =========        Use IntvIn everywhere.
   1298     //
   1299     selectIntv(IntvIn);
   1300     useIntv(Start, BI.LastInstr);
   1301     return;
   1302   }
   1303 
   1304   SlotIndex LSP = SA.getLastSplitPoint(BI.MBB->getNumber());
   1305 
   1306   if (!LeaveBefore || LeaveBefore > BI.LastInstr.getBoundaryIndex()) {
   1307     //
   1308     //               <<<    Possible interference after last use.
   1309     //     |---o---o---|    Live-out on stack.
   1310     //     =========____    Leave IntvIn after last use.
   1311     //
   1312     //                 <    Interference after last use.
   1313     //     |---o---o--o|    Live-out on stack, late last use.
   1314     //     ============     Copy to stack after LSP, overlap IntvIn.
   1315     //            \_____    Stack interval is live-out.
   1316     //
   1317     if (BI.LastInstr < LSP) {
   1318       DEBUG(dbgs() << ", spill after last use before interference.\n");
   1319       selectIntv(IntvIn);
   1320       SlotIndex Idx = leaveIntvAfter(BI.LastInstr);
   1321       useIntv(Start, Idx);
   1322       assert((!LeaveBefore || Idx <= LeaveBefore) && "Interference");
   1323     } else {
   1324       DEBUG(dbgs() << ", spill before last split point.\n");
   1325       selectIntv(IntvIn);
   1326       SlotIndex Idx = leaveIntvBefore(LSP);
   1327       overlapIntv(Idx, BI.LastInstr);
   1328       useIntv(Start, Idx);
   1329       assert((!LeaveBefore || Idx <= LeaveBefore) && "Interference");
   1330     }
   1331     return;
   1332   }
   1333 
   1334   // The interference is overlapping somewhere we wanted to use IntvIn. That
   1335   // means we need to create a local interval that can be allocated a
   1336   // different register.
   1337   unsigned LocalIntv = openIntv();
   1338   (void)LocalIntv;
   1339   DEBUG(dbgs() << ", creating local interval " << LocalIntv << ".\n");
   1340 
   1341   if (!BI.LiveOut || BI.LastInstr < LSP) {
   1342     //
   1343     //           <<<<<<<    Interference overlapping uses.
   1344     //     |---o---o---|    Live-out on stack.
   1345     //     =====----____    Leave IntvIn before interference, then spill.
   1346     //
   1347     SlotIndex To = leaveIntvAfter(BI.LastInstr);
   1348     SlotIndex From = enterIntvBefore(LeaveBefore);
   1349     useIntv(From, To);
   1350     selectIntv(IntvIn);
   1351     useIntv(Start, From);
   1352     assert((!LeaveBefore || From <= LeaveBefore) && "Interference");
   1353     return;
   1354   }
   1355 
   1356   //           <<<<<<<    Interference overlapping uses.
   1357   //     |---o---o--o|    Live-out on stack, late last use.
   1358   //     =====-------     Copy to stack before LSP, overlap LocalIntv.
   1359   //            \_____    Stack interval is live-out.
   1360   //
   1361   SlotIndex To = leaveIntvBefore(LSP);
   1362   overlapIntv(To, BI.LastInstr);
   1363   SlotIndex From = enterIntvBefore(std::min(To, LeaveBefore));
   1364   useIntv(From, To);
   1365   selectIntv(IntvIn);
   1366   useIntv(Start, From);
   1367   assert((!LeaveBefore || From <= LeaveBefore) && "Interference");
   1368 }
   1369 
   1370 void SplitEditor::splitRegOutBlock(const SplitAnalysis::BlockInfo &BI,
   1371                                    unsigned IntvOut, SlotIndex EnterAfter) {
   1372   SlotIndex Start, Stop;
   1373   tie(Start, Stop) = LIS.getSlotIndexes()->getMBBRange(BI.MBB);
   1374 
   1375   DEBUG(dbgs() << "BB#" << BI.MBB->getNumber() << " [" << Start << ';' << Stop
   1376                << "), uses " << BI.FirstInstr << '-' << BI.LastInstr
   1377                << ", reg-out " << IntvOut << ", enter after " << EnterAfter
   1378                << (BI.LiveIn ? ", stack-in" : ", defined in block"));
   1379 
   1380   SlotIndex LSP = SA.getLastSplitPoint(BI.MBB->getNumber());
   1381 
   1382   assert(IntvOut && "Must have register out");
   1383   assert(BI.LiveOut && "Must be live-out");
   1384   assert((!EnterAfter || EnterAfter < LSP) && "Bad interference");
   1385 
   1386   if (!BI.LiveIn && (!EnterAfter || EnterAfter <= BI.FirstInstr)) {
   1387     DEBUG(dbgs() << " after interference.\n");
   1388     //
   1389     //    >>>>             Interference before def.
   1390     //    |   o---o---|    Defined in block.
   1391     //        =========    Use IntvOut everywhere.
   1392     //
   1393     selectIntv(IntvOut);
   1394     useIntv(BI.FirstInstr, Stop);
   1395     return;
   1396   }
   1397 
   1398   if (!EnterAfter || EnterAfter < BI.FirstInstr.getBaseIndex()) {
   1399     DEBUG(dbgs() << ", reload after interference.\n");
   1400     //
   1401     //    >>>>             Interference before def.
   1402     //    |---o---o---|    Live-through, stack-in.
   1403     //    ____=========    Enter IntvOut before first use.
   1404     //
   1405     selectIntv(IntvOut);
   1406     SlotIndex Idx = enterIntvBefore(std::min(LSP, BI.FirstInstr));
   1407     useIntv(Idx, Stop);
   1408     assert((!EnterAfter || Idx >= EnterAfter) && "Interference");
   1409     return;
   1410   }
   1411 
   1412   // The interference is overlapping somewhere we wanted to use IntvOut. That
   1413   // means we need to create a local interval that can be allocated a
   1414   // different register.
   1415   DEBUG(dbgs() << ", interference overlaps uses.\n");
   1416   //
   1417   //    >>>>>>>          Interference overlapping uses.
   1418   //    |---o---o---|    Live-through, stack-in.
   1419   //    ____---======    Create local interval for interference range.
   1420   //
   1421   selectIntv(IntvOut);
   1422   SlotIndex Idx = enterIntvAfter(EnterAfter);
   1423   useIntv(Idx, Stop);
   1424   assert((!EnterAfter || Idx >= EnterAfter) && "Interference");
   1425 
   1426   openIntv();
   1427   SlotIndex From = enterIntvBefore(std::min(Idx, BI.FirstInstr));
   1428   useIntv(From, Idx);
   1429 }
   1430