LLVM API Documentation

SplitKit.cpp
Go to the documentation of this file.
00001 //===---------- SplitKit.cpp - Toolkit for splitting live ranges ----------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file contains the SplitAnalysis class as well as mutator functions for
00011 // live range splitting.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 
00015 #include "SplitKit.h"
00016 #include "llvm/ADT/Statistic.h"
00017 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
00018 #include "llvm/CodeGen/LiveRangeEdit.h"
00019 #include "llvm/CodeGen/MachineDominators.h"
00020 #include "llvm/CodeGen/MachineInstrBuilder.h"
00021 #include "llvm/CodeGen/MachineLoopInfo.h"
00022 #include "llvm/CodeGen/MachineRegisterInfo.h"
00023 #include "llvm/CodeGen/VirtRegMap.h"
00024 #include "llvm/Support/Debug.h"
00025 #include "llvm/Support/raw_ostream.h"
00026 #include "llvm/Target/TargetInstrInfo.h"
00027 #include "llvm/Target/TargetMachine.h"
00028 
00029 using namespace llvm;
00030 
00031 #define DEBUG_TYPE "regalloc"
00032 
00033 STATISTIC(NumFinished, "Number of splits finished");
00034 STATISTIC(NumSimple,   "Number of splits that were simple");
00035 STATISTIC(NumCopies,   "Number of copies inserted for splitting");
00036 STATISTIC(NumRemats,   "Number of rematerialized defs for splitting");
00037 STATISTIC(NumRepairs,  "Number of invalid live ranges repaired");
00038 
00039 //===----------------------------------------------------------------------===//
00040 //                                 Split Analysis
00041 //===----------------------------------------------------------------------===//
00042 
00043 SplitAnalysis::SplitAnalysis(const VirtRegMap &vrm, const LiveIntervals &lis,
00044                              const MachineLoopInfo &mli)
00045     : MF(vrm.getMachineFunction()), VRM(vrm), LIS(lis), Loops(mli),
00046       TII(*MF.getSubtarget().getInstrInfo()), CurLI(nullptr),
00047       LastSplitPoint(MF.getNumBlockIDs()) {}
00048 
00049 void SplitAnalysis::clear() {
00050   UseSlots.clear();
00051   UseBlocks.clear();
00052   ThroughBlocks.clear();
00053   CurLI = nullptr;
00054   DidRepairRange = false;
00055 }
00056 
00057 SlotIndex SplitAnalysis::computeLastSplitPoint(unsigned Num) {
00058   const MachineBasicBlock *MBB = MF.getBlockNumbered(Num);
00059   const MachineBasicBlock *LPad = MBB->getLandingPadSuccessor();
00060   std::pair<SlotIndex, SlotIndex> &LSP = LastSplitPoint[Num];
00061   SlotIndex MBBEnd = LIS.getMBBEndIdx(MBB);
00062 
00063   // Compute split points on the first call. The pair is independent of the
00064   // current live interval.
00065   if (!LSP.first.isValid()) {
00066     MachineBasicBlock::const_iterator FirstTerm = MBB->getFirstTerminator();
00067     if (FirstTerm == MBB->end())
00068       LSP.first = MBBEnd;
00069     else
00070       LSP.first = LIS.getInstructionIndex(FirstTerm);
00071 
00072     // If there is a landing pad successor, also find the call instruction.
00073     if (!LPad)
00074       return LSP.first;
00075     // There may not be a call instruction (?) in which case we ignore LPad.
00076     LSP.second = LSP.first;
00077     for (MachineBasicBlock::const_iterator I = MBB->end(), E = MBB->begin();
00078          I != E;) {
00079       --I;
00080       if (I->isCall()) {
00081         LSP.second = LIS.getInstructionIndex(I);
00082         break;
00083       }
00084     }
00085   }
00086 
00087   // If CurLI is live into a landing pad successor, move the last split point
00088   // back to the call that may throw.
00089   if (!LPad || !LSP.second || !LIS.isLiveInToMBB(*CurLI, LPad))
00090     return LSP.first;
00091 
00092   // Find the value leaving MBB.
00093   const VNInfo *VNI = CurLI->getVNInfoBefore(MBBEnd);
00094   if (!VNI)
00095     return LSP.first;
00096 
00097   // If the value leaving MBB was defined after the call in MBB, it can't
00098   // really be live-in to the landing pad.  This can happen if the landing pad
00099   // has a PHI, and this register is undef on the exceptional edge.
00100   // <rdar://problem/10664933>
00101   if (!SlotIndex::isEarlierInstr(VNI->def, LSP.second) && VNI->def < MBBEnd)
00102     return LSP.first;
00103 
00104   // Value is properly live-in to the landing pad.
00105   // Only allow splits before the call.
00106   return LSP.second;
00107 }
00108 
00109 MachineBasicBlock::iterator
00110 SplitAnalysis::getLastSplitPointIter(MachineBasicBlock *MBB) {
00111   SlotIndex LSP = getLastSplitPoint(MBB->getNumber());
00112   if (LSP == LIS.getMBBEndIdx(MBB))
00113     return MBB->end();
00114   return LIS.getInstructionFromIndex(LSP);
00115 }
00116 
00117 /// analyzeUses - Count instructions, basic blocks, and loops using CurLI.
00118 void SplitAnalysis::analyzeUses() {
00119   assert(UseSlots.empty() && "Call clear first");
00120 
00121   // First get all the defs from the interval values. This provides the correct
00122   // slots for early clobbers.
00123   for (LiveInterval::const_vni_iterator I = CurLI->vni_begin(),
00124        E = CurLI->vni_end(); I != E; ++I)
00125     if (!(*I)->isPHIDef() && !(*I)->isUnused())
00126       UseSlots.push_back((*I)->def);
00127 
00128   // Get use slots form the use-def chain.
00129   const MachineRegisterInfo &MRI = MF.getRegInfo();
00130   for (MachineOperand &MO : MRI.use_nodbg_operands(CurLI->reg))
00131     if (!MO.isUndef())
00132       UseSlots.push_back(LIS.getInstructionIndex(MO.getParent()).getRegSlot());
00133 
00134   array_pod_sort(UseSlots.begin(), UseSlots.end());
00135 
00136   // Remove duplicates, keeping the smaller slot for each instruction.
00137   // That is what we want for early clobbers.
00138   UseSlots.erase(std::unique(UseSlots.begin(), UseSlots.end(),
00139                              SlotIndex::isSameInstr),
00140                  UseSlots.end());
00141 
00142   // Compute per-live block info.
00143   if (!calcLiveBlockInfo()) {
00144     // FIXME: calcLiveBlockInfo found inconsistencies in the live range.
00145     // I am looking at you, RegisterCoalescer!
00146     DidRepairRange = true;
00147     ++NumRepairs;
00148     DEBUG(dbgs() << "*** Fixing inconsistent live interval! ***\n");
00149     const_cast<LiveIntervals&>(LIS)
00150       .shrinkToUses(const_cast<LiveInterval*>(CurLI));
00151     UseBlocks.clear();
00152     ThroughBlocks.clear();
00153     bool fixed = calcLiveBlockInfo();
00154     (void)fixed;
00155     assert(fixed && "Couldn't fix broken live interval");
00156   }
00157 
00158   DEBUG(dbgs() << "Analyze counted "
00159                << UseSlots.size() << " instrs in "
00160                << UseBlocks.size() << " blocks, through "
00161                << NumThroughBlocks << " blocks.\n");
00162 }
00163 
00164 /// calcLiveBlockInfo - Fill the LiveBlocks array with information about blocks
00165 /// where CurLI is live.
00166 bool SplitAnalysis::calcLiveBlockInfo() {
00167   ThroughBlocks.resize(MF.getNumBlockIDs());
00168   NumThroughBlocks = NumGapBlocks = 0;
00169   if (CurLI->empty())
00170     return true;
00171 
00172   LiveInterval::const_iterator LVI = CurLI->begin();
00173   LiveInterval::const_iterator LVE = CurLI->end();
00174 
00175   SmallVectorImpl<SlotIndex>::const_iterator UseI, UseE;
00176   UseI = UseSlots.begin();
00177   UseE = UseSlots.end();
00178 
00179   // Loop over basic blocks where CurLI is live.
00180   MachineFunction::iterator MFI = LIS.getMBBFromIndex(LVI->start);
00181   for (;;) {
00182     BlockInfo BI;
00183     BI.MBB = MFI;
00184     SlotIndex Start, Stop;
00185     std::tie(Start, Stop) = LIS.getSlotIndexes()->getMBBRange(BI.MBB);
00186 
00187     // If the block contains no uses, the range must be live through. At one
00188     // point, RegisterCoalescer could create dangling ranges that ended
00189     // mid-block.
00190     if (UseI == UseE || *UseI >= Stop) {
00191       ++NumThroughBlocks;
00192       ThroughBlocks.set(BI.MBB->getNumber());
00193       // The range shouldn't end mid-block if there are no uses. This shouldn't
00194       // happen.
00195       if (LVI->end < Stop)
00196         return false;
00197     } else {
00198       // This block has uses. Find the first and last uses in the block.
00199       BI.FirstInstr = *UseI;
00200       assert(BI.FirstInstr >= Start);
00201       do ++UseI;
00202       while (UseI != UseE && *UseI < Stop);
00203       BI.LastInstr = UseI[-1];
00204       assert(BI.LastInstr < Stop);
00205 
00206       // LVI is the first live segment overlapping MBB.
00207       BI.LiveIn = LVI->start <= Start;
00208 
00209       // When not live in, the first use should be a def.
00210       if (!BI.LiveIn) {
00211         assert(LVI->start == LVI->valno->def && "Dangling Segment start");
00212         assert(LVI->start == BI.FirstInstr && "First instr should be a def");
00213         BI.FirstDef = BI.FirstInstr;
00214       }
00215 
00216       // Look for gaps in the live range.
00217       BI.LiveOut = true;
00218       while (LVI->end < Stop) {
00219         SlotIndex LastStop = LVI->end;
00220         if (++LVI == LVE || LVI->start >= Stop) {
00221           BI.LiveOut = false;
00222           BI.LastInstr = LastStop;
00223           break;
00224         }
00225 
00226         if (LastStop < LVI->start) {
00227           // There is a gap in the live range. Create duplicate entries for the
00228           // live-in snippet and the live-out snippet.
00229           ++NumGapBlocks;
00230 
00231           // Push the Live-in part.
00232           BI.LiveOut = false;
00233           UseBlocks.push_back(BI);
00234           UseBlocks.back().LastInstr = LastStop;
00235 
00236           // Set up BI for the live-out part.
00237           BI.LiveIn = false;
00238           BI.LiveOut = true;
00239           BI.FirstInstr = BI.FirstDef = LVI->start;
00240         }
00241 
00242         // A Segment that starts in the middle of the block must be a def.
00243         assert(LVI->start == LVI->valno->def && "Dangling Segment start");
00244         if (!BI.FirstDef)
00245           BI.FirstDef = LVI->start;
00246       }
00247 
00248       UseBlocks.push_back(BI);
00249 
00250       // LVI is now at LVE or LVI->end >= Stop.
00251       if (LVI == LVE)
00252         break;
00253     }
00254 
00255     // Live segment ends exactly at Stop. Move to the next segment.
00256     if (LVI->end == Stop && ++LVI == LVE)
00257       break;
00258 
00259     // Pick the next basic block.
00260     if (LVI->start < Stop)
00261       ++MFI;
00262     else
00263       MFI = LIS.getMBBFromIndex(LVI->start);
00264   }
00265 
00266   assert(getNumLiveBlocks() == countLiveBlocks(CurLI) && "Bad block count");
00267   return true;
00268 }
00269 
00270 unsigned SplitAnalysis::countLiveBlocks(const LiveInterval *cli) const {
00271   if (cli->empty())
00272     return 0;
00273   LiveInterval *li = const_cast<LiveInterval*>(cli);
00274   LiveInterval::iterator LVI = li->begin();
00275   LiveInterval::iterator LVE = li->end();
00276   unsigned Count = 0;
00277 
00278   // Loop over basic blocks where li is live.
00279   MachineFunction::const_iterator MFI = LIS.getMBBFromIndex(LVI->start);
00280   SlotIndex Stop = LIS.getMBBEndIdx(MFI);
00281   for (;;) {
00282     ++Count;
00283     LVI = li->advanceTo(LVI, Stop);
00284     if (LVI == LVE)
00285       return Count;
00286     do {
00287       ++MFI;
00288       Stop = LIS.getMBBEndIdx(MFI);
00289     } while (Stop <= LVI->start);
00290   }
00291 }
00292 
00293 bool SplitAnalysis::isOriginalEndpoint(SlotIndex Idx) const {
00294   unsigned OrigReg = VRM.getOriginal(CurLI->reg);
00295   const LiveInterval &Orig = LIS.getInterval(OrigReg);
00296   assert(!Orig.empty() && "Splitting empty interval?");
00297   LiveInterval::const_iterator I = Orig.find(Idx);
00298 
00299   // Range containing Idx should begin at Idx.
00300   if (I != Orig.end() && I->start <= Idx)
00301     return I->start == Idx;
00302 
00303   // Range does not contain Idx, previous must end at Idx.
00304   return I != Orig.begin() && (--I)->end == Idx;
00305 }
00306 
00307 void SplitAnalysis::analyze(const LiveInterval *li) {
00308   clear();
00309   CurLI = li;
00310   analyzeUses();
00311 }
00312 
00313 
00314 //===----------------------------------------------------------------------===//
00315 //                               Split Editor
00316 //===----------------------------------------------------------------------===//
00317 
00318 /// Create a new SplitEditor for editing the LiveInterval analyzed by SA.
00319 SplitEditor::SplitEditor(SplitAnalysis &sa, LiveIntervals &lis, VirtRegMap &vrm,
00320                          MachineDominatorTree &mdt,
00321                          MachineBlockFrequencyInfo &mbfi)
00322     : SA(sa), LIS(lis), VRM(vrm), MRI(vrm.getMachineFunction().getRegInfo()),
00323       MDT(mdt), TII(*vrm.getMachineFunction()
00324                          .getTarget()
00325                          .getSubtargetImpl()
00326                          ->getInstrInfo()),
00327       TRI(*vrm.getMachineFunction()
00328                .getTarget()
00329                .getSubtargetImpl()
00330                ->getRegisterInfo()),
00331       MBFI(mbfi), Edit(nullptr), OpenIdx(0), SpillMode(SM_Partition),
00332       RegAssign(Allocator) {}
00333 
00334 void SplitEditor::reset(LiveRangeEdit &LRE, ComplementSpillMode SM) {
00335   Edit = &LRE;
00336   SpillMode = SM;
00337   OpenIdx = 0;
00338   RegAssign.clear();
00339   Values.clear();
00340 
00341   // Reset the LiveRangeCalc instances needed for this spill mode.
00342   LRCalc[0].reset(&VRM.getMachineFunction(), LIS.getSlotIndexes(), &MDT,
00343                   &LIS.getVNInfoAllocator());
00344   if (SpillMode)
00345     LRCalc[1].reset(&VRM.getMachineFunction(), LIS.getSlotIndexes(), &MDT,
00346                     &LIS.getVNInfoAllocator());
00347 
00348   // We don't need an AliasAnalysis since we will only be performing
00349   // cheap-as-a-copy remats anyway.
00350   Edit->anyRematerializable(nullptr);
00351 }
00352 
00353 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
00354 void SplitEditor::dump() const {
00355   if (RegAssign.empty()) {
00356     dbgs() << " empty\n";
00357     return;
00358   }
00359 
00360   for (RegAssignMap::const_iterator I = RegAssign.begin(); I.valid(); ++I)
00361     dbgs() << " [" << I.start() << ';' << I.stop() << "):" << I.value();
00362   dbgs() << '\n';
00363 }
00364 #endif
00365 
00366 VNInfo *SplitEditor::defValue(unsigned RegIdx,
00367                               const VNInfo *ParentVNI,
00368                               SlotIndex Idx) {
00369   assert(ParentVNI && "Mapping  NULL value");
00370   assert(Idx.isValid() && "Invalid SlotIndex");
00371   assert(Edit->getParent().getVNInfoAt(Idx) == ParentVNI && "Bad Parent VNI");
00372   LiveInterval *LI = &LIS.getInterval(Edit->get(RegIdx));
00373 
00374   // Create a new value.
00375   VNInfo *VNI = LI->getNextValue(Idx, LIS.getVNInfoAllocator());
00376 
00377   // Use insert for lookup, so we can add missing values with a second lookup.
00378   std::pair<ValueMap::iterator, bool> InsP =
00379     Values.insert(std::make_pair(std::make_pair(RegIdx, ParentVNI->id),
00380                                  ValueForcePair(VNI, false)));
00381 
00382   // This was the first time (RegIdx, ParentVNI) was mapped.
00383   // Keep it as a simple def without any liveness.
00384   if (InsP.second)
00385     return VNI;
00386 
00387   // If the previous value was a simple mapping, add liveness for it now.
00388   if (VNInfo *OldVNI = InsP.first->second.getPointer()) {
00389     SlotIndex Def = OldVNI->def;
00390     LI->addSegment(LiveInterval::Segment(Def, Def.getDeadSlot(), OldVNI));
00391     // No longer a simple mapping.  Switch to a complex, non-forced mapping.
00392     InsP.first->second = ValueForcePair();
00393   }
00394 
00395   // This is a complex mapping, add liveness for VNI
00396   SlotIndex Def = VNI->def;
00397   LI->addSegment(LiveInterval::Segment(Def, Def.getDeadSlot(), VNI));
00398 
00399   return VNI;
00400 }
00401 
00402 void SplitEditor::forceRecompute(unsigned RegIdx, const VNInfo *ParentVNI) {
00403   assert(ParentVNI && "Mapping  NULL value");
00404   ValueForcePair &VFP = Values[std::make_pair(RegIdx, ParentVNI->id)];
00405   VNInfo *VNI = VFP.getPointer();
00406 
00407   // ParentVNI was either unmapped or already complex mapped. Either way, just
00408   // set the force bit.
00409   if (!VNI) {
00410     VFP.setInt(true);
00411     return;
00412   }
00413 
00414   // This was previously a single mapping. Make sure the old def is represented
00415   // by a trivial live range.
00416   SlotIndex Def = VNI->def;
00417   LiveInterval *LI = &LIS.getInterval(Edit->get(RegIdx));
00418   LI->addSegment(LiveInterval::Segment(Def, Def.getDeadSlot(), VNI));
00419   // Mark as complex mapped, forced.
00420   VFP = ValueForcePair(nullptr, true);
00421 }
00422 
00423 VNInfo *SplitEditor::defFromParent(unsigned RegIdx,
00424                                    VNInfo *ParentVNI,
00425                                    SlotIndex UseIdx,
00426                                    MachineBasicBlock &MBB,
00427                                    MachineBasicBlock::iterator I) {
00428   MachineInstr *CopyMI = nullptr;
00429   SlotIndex Def;
00430   LiveInterval *LI = &LIS.getInterval(Edit->get(RegIdx));
00431 
00432   // We may be trying to avoid interference that ends at a deleted instruction,
00433   // so always begin RegIdx 0 early and all others late.
00434   bool Late = RegIdx != 0;
00435 
00436   // Attempt cheap-as-a-copy rematerialization.
00437   LiveRangeEdit::Remat RM(ParentVNI);
00438   if (Edit->canRematerializeAt(RM, UseIdx, true)) {
00439     Def = Edit->rematerializeAt(MBB, I, LI->reg, RM, TRI, Late);
00440     ++NumRemats;
00441   } else {
00442     // Can't remat, just insert a copy from parent.
00443     CopyMI = BuildMI(MBB, I, DebugLoc(), TII.get(TargetOpcode::COPY), LI->reg)
00444                .addReg(Edit->getReg());
00445     Def = LIS.getSlotIndexes()->insertMachineInstrInMaps(CopyMI, Late)
00446             .getRegSlot();
00447     ++NumCopies;
00448   }
00449 
00450   // Define the value in Reg.
00451   return defValue(RegIdx, ParentVNI, Def);
00452 }
00453 
00454 /// Create a new virtual register and live interval.
00455 unsigned SplitEditor::openIntv() {
00456   // Create the complement as index 0.
00457   if (Edit->empty())
00458     Edit->createEmptyInterval();
00459 
00460   // Create the open interval.
00461   OpenIdx = Edit->size();
00462   Edit->createEmptyInterval();
00463   return OpenIdx;
00464 }
00465 
00466 void SplitEditor::selectIntv(unsigned Idx) {
00467   assert(Idx != 0 && "Cannot select the complement interval");
00468   assert(Idx < Edit->size() && "Can only select previously opened interval");
00469   DEBUG(dbgs() << "    selectIntv " << OpenIdx << " -> " << Idx << '\n');
00470   OpenIdx = Idx;
00471 }
00472 
00473 SlotIndex SplitEditor::enterIntvBefore(SlotIndex Idx) {
00474   assert(OpenIdx && "openIntv not called before enterIntvBefore");
00475   DEBUG(dbgs() << "    enterIntvBefore " << Idx);
00476   Idx = Idx.getBaseIndex();
00477   VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(Idx);
00478   if (!ParentVNI) {
00479     DEBUG(dbgs() << ": not live\n");
00480     return Idx;
00481   }
00482   DEBUG(dbgs() << ": valno " << ParentVNI->id << '\n');
00483   MachineInstr *MI = LIS.getInstructionFromIndex(Idx);
00484   assert(MI && "enterIntvBefore called with invalid index");
00485 
00486   VNInfo *VNI = defFromParent(OpenIdx, ParentVNI, Idx, *MI->getParent(), MI);
00487   return VNI->def;
00488 }
00489 
00490 SlotIndex SplitEditor::enterIntvAfter(SlotIndex Idx) {
00491   assert(OpenIdx && "openIntv not called before enterIntvAfter");
00492   DEBUG(dbgs() << "    enterIntvAfter " << Idx);
00493   Idx = Idx.getBoundaryIndex();
00494   VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(Idx);
00495   if (!ParentVNI) {
00496     DEBUG(dbgs() << ": not live\n");
00497     return Idx;
00498   }
00499   DEBUG(dbgs() << ": valno " << ParentVNI->id << '\n');
00500   MachineInstr *MI = LIS.getInstructionFromIndex(Idx);
00501   assert(MI && "enterIntvAfter called with invalid index");
00502 
00503   VNInfo *VNI = defFromParent(OpenIdx, ParentVNI, Idx, *MI->getParent(),
00504                               std::next(MachineBasicBlock::iterator(MI)));
00505   return VNI->def;
00506 }
00507 
00508 SlotIndex SplitEditor::enterIntvAtEnd(MachineBasicBlock &MBB) {
00509   assert(OpenIdx && "openIntv not called before enterIntvAtEnd");
00510   SlotIndex End = LIS.getMBBEndIdx(&MBB);
00511   SlotIndex Last = End.getPrevSlot();
00512   DEBUG(dbgs() << "    enterIntvAtEnd BB#" << MBB.getNumber() << ", " << Last);
00513   VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(Last);
00514   if (!ParentVNI) {
00515     DEBUG(dbgs() << ": not live\n");
00516     return End;
00517   }
00518   DEBUG(dbgs() << ": valno " << ParentVNI->id);
00519   VNInfo *VNI = defFromParent(OpenIdx, ParentVNI, Last, MBB,
00520                               SA.getLastSplitPointIter(&MBB));
00521   RegAssign.insert(VNI->def, End, OpenIdx);
00522   DEBUG(dump());
00523   return VNI->def;
00524 }
00525 
00526 /// useIntv - indicate that all instructions in MBB should use OpenLI.
00527 void SplitEditor::useIntv(const MachineBasicBlock &MBB) {
00528   useIntv(LIS.getMBBStartIdx(&MBB), LIS.getMBBEndIdx(&MBB));
00529 }
00530 
00531 void SplitEditor::useIntv(SlotIndex Start, SlotIndex End) {
00532   assert(OpenIdx && "openIntv not called before useIntv");
00533   DEBUG(dbgs() << "    useIntv [" << Start << ';' << End << "):");
00534   RegAssign.insert(Start, End, OpenIdx);
00535   DEBUG(dump());
00536 }
00537 
00538 SlotIndex SplitEditor::leaveIntvAfter(SlotIndex Idx) {
00539   assert(OpenIdx && "openIntv not called before leaveIntvAfter");
00540   DEBUG(dbgs() << "    leaveIntvAfter " << Idx);
00541 
00542   // The interval must be live beyond the instruction at Idx.
00543   SlotIndex Boundary = Idx.getBoundaryIndex();
00544   VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(Boundary);
00545   if (!ParentVNI) {
00546     DEBUG(dbgs() << ": not live\n");
00547     return Boundary.getNextSlot();
00548   }
00549   DEBUG(dbgs() << ": valno " << ParentVNI->id << '\n');
00550   MachineInstr *MI = LIS.getInstructionFromIndex(Boundary);
00551   assert(MI && "No instruction at index");
00552 
00553   // In spill mode, make live ranges as short as possible by inserting the copy
00554   // before MI.  This is only possible if that instruction doesn't redefine the
00555   // value.  The inserted COPY is not a kill, and we don't need to recompute
00556   // the source live range.  The spiller also won't try to hoist this copy.
00557   if (SpillMode && !SlotIndex::isSameInstr(ParentVNI->def, Idx) &&
00558       MI->readsVirtualRegister(Edit->getReg())) {
00559     forceRecompute(0, ParentVNI);
00560     defFromParent(0, ParentVNI, Idx, *MI->getParent(), MI);
00561     return Idx;
00562   }
00563 
00564   VNInfo *VNI = defFromParent(0, ParentVNI, Boundary, *MI->getParent(),
00565                               std::next(MachineBasicBlock::iterator(MI)));
00566   return VNI->def;
00567 }
00568 
00569 SlotIndex SplitEditor::leaveIntvBefore(SlotIndex Idx) {
00570   assert(OpenIdx && "openIntv not called before leaveIntvBefore");
00571   DEBUG(dbgs() << "    leaveIntvBefore " << Idx);
00572 
00573   // The interval must be live into the instruction at Idx.
00574   Idx = Idx.getBaseIndex();
00575   VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(Idx);
00576   if (!ParentVNI) {
00577     DEBUG(dbgs() << ": not live\n");
00578     return Idx.getNextSlot();
00579   }
00580   DEBUG(dbgs() << ": valno " << ParentVNI->id << '\n');
00581 
00582   MachineInstr *MI = LIS.getInstructionFromIndex(Idx);
00583   assert(MI && "No instruction at index");
00584   VNInfo *VNI = defFromParent(0, ParentVNI, Idx, *MI->getParent(), MI);
00585   return VNI->def;
00586 }
00587 
00588 SlotIndex SplitEditor::leaveIntvAtTop(MachineBasicBlock &MBB) {
00589   assert(OpenIdx && "openIntv not called before leaveIntvAtTop");
00590   SlotIndex Start = LIS.getMBBStartIdx(&MBB);
00591   DEBUG(dbgs() << "    leaveIntvAtTop BB#" << MBB.getNumber() << ", " << Start);
00592 
00593   VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(Start);
00594   if (!ParentVNI) {
00595     DEBUG(dbgs() << ": not live\n");
00596     return Start;
00597   }
00598 
00599   VNInfo *VNI = defFromParent(0, ParentVNI, Start, MBB,
00600                               MBB.SkipPHIsAndLabels(MBB.begin()));
00601   RegAssign.insert(Start, VNI->def, OpenIdx);
00602   DEBUG(dump());
00603   return VNI->def;
00604 }
00605 
00606 void SplitEditor::overlapIntv(SlotIndex Start, SlotIndex End) {
00607   assert(OpenIdx && "openIntv not called before overlapIntv");
00608   const VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(Start);
00609   assert(ParentVNI == Edit->getParent().getVNInfoBefore(End) &&
00610          "Parent changes value in extended range");
00611   assert(LIS.getMBBFromIndex(Start) == LIS.getMBBFromIndex(End) &&
00612          "Range cannot span basic blocks");
00613 
00614   // The complement interval will be extended as needed by LRCalc.extend().
00615   if (ParentVNI)
00616     forceRecompute(0, ParentVNI);
00617   DEBUG(dbgs() << "    overlapIntv [" << Start << ';' << End << "):");
00618   RegAssign.insert(Start, End, OpenIdx);
00619   DEBUG(dump());
00620 }
00621 
00622 //===----------------------------------------------------------------------===//
00623 //                                  Spill modes
00624 //===----------------------------------------------------------------------===//
00625 
00626 void SplitEditor::removeBackCopies(SmallVectorImpl<VNInfo*> &Copies) {
00627   LiveInterval *LI = &LIS.getInterval(Edit->get(0));
00628   DEBUG(dbgs() << "Removing " << Copies.size() << " back-copies.\n");
00629   RegAssignMap::iterator AssignI;
00630   AssignI.setMap(RegAssign);
00631 
00632   for (unsigned i = 0, e = Copies.size(); i != e; ++i) {
00633     VNInfo *VNI = Copies[i];
00634     SlotIndex Def = VNI->def;
00635     MachineInstr *MI = LIS.getInstructionFromIndex(Def);
00636     assert(MI && "No instruction for back-copy");
00637 
00638     MachineBasicBlock *MBB = MI->getParent();
00639     MachineBasicBlock::iterator MBBI(MI);
00640     bool AtBegin;
00641     do AtBegin = MBBI == MBB->begin();
00642     while (!AtBegin && (--MBBI)->isDebugValue());
00643 
00644     DEBUG(dbgs() << "Removing " << Def << '\t' << *MI);
00645     LI->removeValNo(VNI);
00646     LIS.RemoveMachineInstrFromMaps(MI);
00647     MI->eraseFromParent();
00648 
00649     // Adjust RegAssign if a register assignment is killed at VNI->def.  We
00650     // want to avoid calculating the live range of the source register if
00651     // possible.
00652     AssignI.find(Def.getPrevSlot());
00653     if (!AssignI.valid() || AssignI.start() >= Def)
00654       continue;
00655     // If MI doesn't kill the assigned register, just leave it.
00656     if (AssignI.stop() != Def)
00657       continue;
00658     unsigned RegIdx = AssignI.value();
00659     if (AtBegin || !MBBI->readsVirtualRegister(Edit->getReg())) {
00660       DEBUG(dbgs() << "  cannot find simple kill of RegIdx " << RegIdx << '\n');
00661       forceRecompute(RegIdx, Edit->getParent().getVNInfoAt(Def));
00662     } else {
00663       SlotIndex Kill = LIS.getInstructionIndex(MBBI).getRegSlot();
00664       DEBUG(dbgs() << "  move kill to " << Kill << '\t' << *MBBI);
00665       AssignI.setStop(Kill);
00666     }
00667   }
00668 }
00669 
00670 MachineBasicBlock*
00671 SplitEditor::findShallowDominator(MachineBasicBlock *MBB,
00672                                   MachineBasicBlock *DefMBB) {
00673   if (MBB == DefMBB)
00674     return MBB;
00675   assert(MDT.dominates(DefMBB, MBB) && "MBB must be dominated by the def.");
00676 
00677   const MachineLoopInfo &Loops = SA.Loops;
00678   const MachineLoop *DefLoop = Loops.getLoopFor(DefMBB);
00679   MachineDomTreeNode *DefDomNode = MDT[DefMBB];
00680 
00681   // Best candidate so far.
00682   MachineBasicBlock *BestMBB = MBB;
00683   unsigned BestDepth = UINT_MAX;
00684 
00685   for (;;) {
00686     const MachineLoop *Loop = Loops.getLoopFor(MBB);
00687 
00688     // MBB isn't in a loop, it doesn't get any better.  All dominators have a
00689     // higher frequency by definition.
00690     if (!Loop) {
00691       DEBUG(dbgs() << "Def in BB#" << DefMBB->getNumber() << " dominates BB#"
00692                    << MBB->getNumber() << " at depth 0\n");
00693       return MBB;
00694     }
00695 
00696     // We'll never be able to exit the DefLoop.
00697     if (Loop == DefLoop) {
00698       DEBUG(dbgs() << "Def in BB#" << DefMBB->getNumber() << " dominates BB#"
00699                    << MBB->getNumber() << " in the same loop\n");
00700       return MBB;
00701     }
00702 
00703     // Least busy dominator seen so far.
00704     unsigned Depth = Loop->getLoopDepth();
00705     if (Depth < BestDepth) {
00706       BestMBB = MBB;
00707       BestDepth = Depth;
00708       DEBUG(dbgs() << "Def in BB#" << DefMBB->getNumber() << " dominates BB#"
00709                    << MBB->getNumber() << " at depth " << Depth << '\n');
00710     }
00711 
00712     // Leave loop by going to the immediate dominator of the loop header.
00713     // This is a bigger stride than simply walking up the dominator tree.
00714     MachineDomTreeNode *IDom = MDT[Loop->getHeader()]->getIDom();
00715 
00716     // Too far up the dominator tree?
00717     if (!IDom || !MDT.dominates(DefDomNode, IDom))
00718       return BestMBB;
00719 
00720     MBB = IDom->getBlock();
00721   }
00722 }
00723 
00724 void SplitEditor::hoistCopiesForSize() {
00725   // Get the complement interval, always RegIdx 0.
00726   LiveInterval *LI = &LIS.getInterval(Edit->get(0));
00727   LiveInterval *Parent = &Edit->getParent();
00728 
00729   // Track the nearest common dominator for all back-copies for each ParentVNI,
00730   // indexed by ParentVNI->id.
00731   typedef std::pair<MachineBasicBlock*, SlotIndex> DomPair;
00732   SmallVector<DomPair, 8> NearestDom(Parent->getNumValNums());
00733 
00734   // Find the nearest common dominator for parent values with multiple
00735   // back-copies.  If a single back-copy dominates, put it in DomPair.second.
00736   for (LiveInterval::vni_iterator VI = LI->vni_begin(), VE = LI->vni_end();
00737        VI != VE; ++VI) {
00738     VNInfo *VNI = *VI;
00739     if (VNI->isUnused())
00740       continue;
00741     VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(VNI->def);
00742     assert(ParentVNI && "Parent not live at complement def");
00743 
00744     // Don't hoist remats.  The complement is probably going to disappear
00745     // completely anyway.
00746     if (Edit->didRematerialize(ParentVNI))
00747       continue;
00748 
00749     MachineBasicBlock *ValMBB = LIS.getMBBFromIndex(VNI->def);
00750     DomPair &Dom = NearestDom[ParentVNI->id];
00751 
00752     // Keep directly defined parent values.  This is either a PHI or an
00753     // instruction in the complement range.  All other copies of ParentVNI
00754     // should be eliminated.
00755     if (VNI->def == ParentVNI->def) {
00756       DEBUG(dbgs() << "Direct complement def at " << VNI->def << '\n');
00757       Dom = DomPair(ValMBB, VNI->def);
00758       continue;
00759     }
00760     // Skip the singly mapped values.  There is nothing to gain from hoisting a
00761     // single back-copy.
00762     if (Values.lookup(std::make_pair(0, ParentVNI->id)).getPointer()) {
00763       DEBUG(dbgs() << "Single complement def at " << VNI->def << '\n');
00764       continue;
00765     }
00766 
00767     if (!Dom.first) {
00768       // First time we see ParentVNI.  VNI dominates itself.
00769       Dom = DomPair(ValMBB, VNI->def);
00770     } else if (Dom.first == ValMBB) {
00771       // Two defs in the same block.  Pick the earlier def.
00772       if (!Dom.second.isValid() || VNI->def < Dom.second)
00773         Dom.second = VNI->def;
00774     } else {
00775       // Different basic blocks. Check if one dominates.
00776       MachineBasicBlock *Near =
00777         MDT.findNearestCommonDominator(Dom.first, ValMBB);
00778       if (Near == ValMBB)
00779         // Def ValMBB dominates.
00780         Dom = DomPair(ValMBB, VNI->def);
00781       else if (Near != Dom.first)
00782         // None dominate. Hoist to common dominator, need new def.
00783         Dom = DomPair(Near, SlotIndex());
00784     }
00785 
00786     DEBUG(dbgs() << "Multi-mapped complement " << VNI->id << '@' << VNI->def
00787                  << " for parent " << ParentVNI->id << '@' << ParentVNI->def
00788                  << " hoist to BB#" << Dom.first->getNumber() << ' '
00789                  << Dom.second << '\n');
00790   }
00791 
00792   // Insert the hoisted copies.
00793   for (unsigned i = 0, e = Parent->getNumValNums(); i != e; ++i) {
00794     DomPair &Dom = NearestDom[i];
00795     if (!Dom.first || Dom.second.isValid())
00796       continue;
00797     // This value needs a hoisted copy inserted at the end of Dom.first.
00798     VNInfo *ParentVNI = Parent->getValNumInfo(i);
00799     MachineBasicBlock *DefMBB = LIS.getMBBFromIndex(ParentVNI->def);
00800     // Get a less loopy dominator than Dom.first.
00801     Dom.first = findShallowDominator(Dom.first, DefMBB);
00802     SlotIndex Last = LIS.getMBBEndIdx(Dom.first).getPrevSlot();
00803     Dom.second =
00804       defFromParent(0, ParentVNI, Last, *Dom.first,
00805                     SA.getLastSplitPointIter(Dom.first))->def;
00806   }
00807 
00808   // Remove redundant back-copies that are now known to be dominated by another
00809   // def with the same value.
00810   SmallVector<VNInfo*, 8> BackCopies;
00811   for (LiveInterval::vni_iterator VI = LI->vni_begin(), VE = LI->vni_end();
00812        VI != VE; ++VI) {
00813     VNInfo *VNI = *VI;
00814     if (VNI->isUnused())
00815       continue;
00816     VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(VNI->def);
00817     const DomPair &Dom = NearestDom[ParentVNI->id];
00818     if (!Dom.first || Dom.second == VNI->def)
00819       continue;
00820     BackCopies.push_back(VNI);
00821     forceRecompute(0, ParentVNI);
00822   }
00823   removeBackCopies(BackCopies);
00824 }
00825 
00826 
00827 /// transferValues - Transfer all possible values to the new live ranges.
00828 /// Values that were rematerialized are left alone, they need LRCalc.extend().
00829 bool SplitEditor::transferValues() {
00830   bool Skipped = false;
00831   RegAssignMap::const_iterator AssignI = RegAssign.begin();
00832   for (LiveInterval::const_iterator ParentI = Edit->getParent().begin(),
00833          ParentE = Edit->getParent().end(); ParentI != ParentE; ++ParentI) {
00834     DEBUG(dbgs() << "  blit " << *ParentI << ':');
00835     VNInfo *ParentVNI = ParentI->valno;
00836     // RegAssign has holes where RegIdx 0 should be used.
00837     SlotIndex Start = ParentI->start;
00838     AssignI.advanceTo(Start);
00839     do {
00840       unsigned RegIdx;
00841       SlotIndex End = ParentI->end;
00842       if (!AssignI.valid()) {
00843         RegIdx = 0;
00844       } else if (AssignI.start() <= Start) {
00845         RegIdx = AssignI.value();
00846         if (AssignI.stop() < End) {
00847           End = AssignI.stop();
00848           ++AssignI;
00849         }
00850       } else {
00851         RegIdx = 0;
00852         End = std::min(End, AssignI.start());
00853       }
00854 
00855       // The interval [Start;End) is continuously mapped to RegIdx, ParentVNI.
00856       DEBUG(dbgs() << " [" << Start << ';' << End << ")=" << RegIdx);
00857       LiveRange &LR = LIS.getInterval(Edit->get(RegIdx));
00858 
00859       // Check for a simply defined value that can be blitted directly.
00860       ValueForcePair VFP = Values.lookup(std::make_pair(RegIdx, ParentVNI->id));
00861       if (VNInfo *VNI = VFP.getPointer()) {
00862         DEBUG(dbgs() << ':' << VNI->id);
00863         LR.addSegment(LiveInterval::Segment(Start, End, VNI));
00864         Start = End;
00865         continue;
00866       }
00867 
00868       // Skip values with forced recomputation.
00869       if (VFP.getInt()) {
00870         DEBUG(dbgs() << "(recalc)");
00871         Skipped = true;
00872         Start = End;
00873         continue;
00874       }
00875 
00876       LiveRangeCalc &LRC = getLRCalc(RegIdx);
00877 
00878       // This value has multiple defs in RegIdx, but it wasn't rematerialized,
00879       // so the live range is accurate. Add live-in blocks in [Start;End) to the
00880       // LiveInBlocks.
00881       MachineFunction::iterator MBB = LIS.getMBBFromIndex(Start);
00882       SlotIndex BlockStart, BlockEnd;
00883       std::tie(BlockStart, BlockEnd) = LIS.getSlotIndexes()->getMBBRange(MBB);
00884 
00885       // The first block may be live-in, or it may have its own def.
00886       if (Start != BlockStart) {
00887         VNInfo *VNI = LR.extendInBlock(BlockStart, std::min(BlockEnd, End));
00888         assert(VNI && "Missing def for complex mapped value");
00889         DEBUG(dbgs() << ':' << VNI->id << "*BB#" << MBB->getNumber());
00890         // MBB has its own def. Is it also live-out?
00891         if (BlockEnd <= End)
00892           LRC.setLiveOutValue(MBB, VNI);
00893 
00894         // Skip to the next block for live-in.
00895         ++MBB;
00896         BlockStart = BlockEnd;
00897       }
00898 
00899       // Handle the live-in blocks covered by [Start;End).
00900       assert(Start <= BlockStart && "Expected live-in block");
00901       while (BlockStart < End) {
00902         DEBUG(dbgs() << ">BB#" << MBB->getNumber());
00903         BlockEnd = LIS.getMBBEndIdx(MBB);
00904         if (BlockStart == ParentVNI->def) {
00905           // This block has the def of a parent PHI, so it isn't live-in.
00906           assert(ParentVNI->isPHIDef() && "Non-phi defined at block start?");
00907           VNInfo *VNI = LR.extendInBlock(BlockStart, std::min(BlockEnd, End));
00908           assert(VNI && "Missing def for complex mapped parent PHI");
00909           if (End >= BlockEnd)
00910             LRC.setLiveOutValue(MBB, VNI); // Live-out as well.
00911         } else {
00912           // This block needs a live-in value.  The last block covered may not
00913           // be live-out.
00914           if (End < BlockEnd)
00915             LRC.addLiveInBlock(LR, MDT[MBB], End);
00916           else {
00917             // Live-through, and we don't know the value.
00918             LRC.addLiveInBlock(LR, MDT[MBB]);
00919             LRC.setLiveOutValue(MBB, nullptr);
00920           }
00921         }
00922         BlockStart = BlockEnd;
00923         ++MBB;
00924       }
00925       Start = End;
00926     } while (Start != ParentI->end);
00927     DEBUG(dbgs() << '\n');
00928   }
00929 
00930   LRCalc[0].calculateValues();
00931   if (SpillMode)
00932     LRCalc[1].calculateValues();
00933 
00934   return Skipped;
00935 }
00936 
00937 void SplitEditor::extendPHIKillRanges() {
00938     // Extend live ranges to be live-out for successor PHI values.
00939   for (LiveInterval::const_vni_iterator I = Edit->getParent().vni_begin(),
00940        E = Edit->getParent().vni_end(); I != E; ++I) {
00941     const VNInfo *PHIVNI = *I;
00942     if (PHIVNI->isUnused() || !PHIVNI->isPHIDef())
00943       continue;
00944     unsigned RegIdx = RegAssign.lookup(PHIVNI->def);
00945     LiveRange &LR = LIS.getInterval(Edit->get(RegIdx));
00946     LiveRangeCalc &LRC = getLRCalc(RegIdx);
00947     MachineBasicBlock *MBB = LIS.getMBBFromIndex(PHIVNI->def);
00948     for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
00949          PE = MBB->pred_end(); PI != PE; ++PI) {
00950       SlotIndex End = LIS.getMBBEndIdx(*PI);
00951       SlotIndex LastUse = End.getPrevSlot();
00952       // The predecessor may not have a live-out value. That is OK, like an
00953       // undef PHI operand.
00954       if (Edit->getParent().liveAt(LastUse)) {
00955         assert(RegAssign.lookup(LastUse) == RegIdx &&
00956                "Different register assignment in phi predecessor");
00957         LRC.extend(LR, End);
00958       }
00959     }
00960   }
00961 }
00962 
00963 /// rewriteAssigned - Rewrite all uses of Edit->getReg().
00964 void SplitEditor::rewriteAssigned(bool ExtendRanges) {
00965   for (MachineRegisterInfo::reg_iterator RI = MRI.reg_begin(Edit->getReg()),
00966        RE = MRI.reg_end(); RI != RE;) {
00967     MachineOperand &MO = *RI;
00968     MachineInstr *MI = MO.getParent();
00969     ++RI;
00970     // LiveDebugVariables should have handled all DBG_VALUE instructions.
00971     if (MI->isDebugValue()) {
00972       DEBUG(dbgs() << "Zapping " << *MI);
00973       MO.setReg(0);
00974       continue;
00975     }
00976 
00977     // <undef> operands don't really read the register, so it doesn't matter
00978     // which register we choose.  When the use operand is tied to a def, we must
00979     // use the same register as the def, so just do that always.
00980     SlotIndex Idx = LIS.getInstructionIndex(MI);
00981     if (MO.isDef() || MO.isUndef())
00982       Idx = Idx.getRegSlot(MO.isEarlyClobber());
00983 
00984     // Rewrite to the mapped register at Idx.
00985     unsigned RegIdx = RegAssign.lookup(Idx);
00986     LiveInterval *LI = &LIS.getInterval(Edit->get(RegIdx));
00987     MO.setReg(LI->reg);
00988     DEBUG(dbgs() << "  rewr BB#" << MI->getParent()->getNumber() << '\t'
00989                  << Idx << ':' << RegIdx << '\t' << *MI);
00990 
00991     // Extend liveness to Idx if the instruction reads reg.
00992     if (!ExtendRanges || MO.isUndef())
00993       continue;
00994 
00995     // Skip instructions that don't read Reg.
00996     if (MO.isDef()) {
00997       if (!MO.getSubReg() && !MO.isEarlyClobber())
00998         continue;
00999       // We may wan't to extend a live range for a partial redef, or for a use
01000       // tied to an early clobber.
01001       Idx = Idx.getPrevSlot();
01002       if (!Edit->getParent().liveAt(Idx))
01003         continue;
01004     } else
01005       Idx = Idx.getRegSlot(true);
01006 
01007     getLRCalc(RegIdx).extend(*LI, Idx.getNextSlot());
01008   }
01009 }
01010 
01011 void SplitEditor::deleteRematVictims() {
01012   SmallVector<MachineInstr*, 8> Dead;
01013   for (LiveRangeEdit::iterator I = Edit->begin(), E = Edit->end(); I != E; ++I){
01014     LiveInterval *LI = &LIS.getInterval(*I);
01015     for (LiveInterval::const_iterator LII = LI->begin(), LIE = LI->end();
01016            LII != LIE; ++LII) {
01017       // Dead defs end at the dead slot.
01018       if (LII->end != LII->valno->def.getDeadSlot())
01019         continue;
01020       MachineInstr *MI = LIS.getInstructionFromIndex(LII->valno->def);
01021       assert(MI && "Missing instruction for dead def");
01022       MI->addRegisterDead(LI->reg, &TRI);
01023 
01024       if (!MI->allDefsAreDead())
01025         continue;
01026 
01027       DEBUG(dbgs() << "All defs dead: " << *MI);
01028       Dead.push_back(MI);
01029     }
01030   }
01031 
01032   if (Dead.empty())
01033     return;
01034 
01035   Edit->eliminateDeadDefs(Dead);
01036 }
01037 
01038 void SplitEditor::finish(SmallVectorImpl<unsigned> *LRMap) {
01039   ++NumFinished;
01040 
01041   // At this point, the live intervals in Edit contain VNInfos corresponding to
01042   // the inserted copies.
01043 
01044   // Add the original defs from the parent interval.
01045   for (LiveInterval::const_vni_iterator I = Edit->getParent().vni_begin(),
01046          E = Edit->getParent().vni_end(); I != E; ++I) {
01047     const VNInfo *ParentVNI = *I;
01048     if (ParentVNI->isUnused())
01049       continue;
01050     unsigned RegIdx = RegAssign.lookup(ParentVNI->def);
01051     defValue(RegIdx, ParentVNI, ParentVNI->def);
01052 
01053     // Force rematted values to be recomputed everywhere.
01054     // The new live ranges may be truncated.
01055     if (Edit->didRematerialize(ParentVNI))
01056       for (unsigned i = 0, e = Edit->size(); i != e; ++i)
01057         forceRecompute(i, ParentVNI);
01058   }
01059 
01060   // Hoist back-copies to the complement interval when in spill mode.
01061   switch (SpillMode) {
01062   case SM_Partition:
01063     // Leave all back-copies as is.
01064     break;
01065   case SM_Size:
01066     hoistCopiesForSize();
01067     break;
01068   case SM_Speed:
01069     llvm_unreachable("Spill mode 'speed' not implemented yet");
01070   }
01071 
01072   // Transfer the simply mapped values, check if any are skipped.
01073   bool Skipped = transferValues();
01074   if (Skipped)
01075     extendPHIKillRanges();
01076   else
01077     ++NumSimple;
01078 
01079   // Rewrite virtual registers, possibly extending ranges.
01080   rewriteAssigned(Skipped);
01081 
01082   // Delete defs that were rematted everywhere.
01083   if (Skipped)
01084     deleteRematVictims();
01085 
01086   // Get rid of unused values and set phi-kill flags.
01087   for (LiveRangeEdit::iterator I = Edit->begin(), E = Edit->end(); I != E; ++I) {
01088     LiveInterval &LI = LIS.getInterval(*I);
01089     LI.RenumberValues();
01090   }
01091 
01092   // Provide a reverse mapping from original indices to Edit ranges.
01093   if (LRMap) {
01094     LRMap->clear();
01095     for (unsigned i = 0, e = Edit->size(); i != e; ++i)
01096       LRMap->push_back(i);
01097   }
01098 
01099   // Now check if any registers were separated into multiple components.
01100   ConnectedVNInfoEqClasses ConEQ(LIS);
01101   for (unsigned i = 0, e = Edit->size(); i != e; ++i) {
01102     // Don't use iterators, they are invalidated by create() below.
01103     LiveInterval *li = &LIS.getInterval(Edit->get(i));
01104     unsigned NumComp = ConEQ.Classify(li);
01105     if (NumComp <= 1)
01106       continue;
01107     DEBUG(dbgs() << "  " << NumComp << " components: " << *li << '\n');
01108     SmallVector<LiveInterval*, 8> dups;
01109     dups.push_back(li);
01110     for (unsigned j = 1; j != NumComp; ++j)
01111       dups.push_back(&Edit->createEmptyInterval());
01112     ConEQ.Distribute(&dups[0], MRI);
01113     // The new intervals all map back to i.
01114     if (LRMap)
01115       LRMap->resize(Edit->size(), i);
01116   }
01117 
01118   // Calculate spill weight and allocation hints for new intervals.
01119   Edit->calculateRegClassAndHint(VRM.getMachineFunction(), SA.Loops, MBFI);
01120 
01121   assert(!LRMap || LRMap->size() == Edit->size());
01122 }
01123 
01124 
01125 //===----------------------------------------------------------------------===//
01126 //                            Single Block Splitting
01127 //===----------------------------------------------------------------------===//
01128 
01129 bool SplitAnalysis::shouldSplitSingleBlock(const BlockInfo &BI,
01130                                            bool SingleInstrs) const {
01131   // Always split for multiple instructions.
01132   if (!BI.isOneInstr())
01133     return true;
01134   // Don't split for single instructions unless explicitly requested.
01135   if (!SingleInstrs)
01136     return false;
01137   // Splitting a live-through range always makes progress.
01138   if (BI.LiveIn && BI.LiveOut)
01139     return true;
01140   // No point in isolating a copy. It has no register class constraints.
01141   if (LIS.getInstructionFromIndex(BI.FirstInstr)->isCopyLike())
01142     return false;
01143   // Finally, don't isolate an end point that was created by earlier splits.
01144   return isOriginalEndpoint(BI.FirstInstr);
01145 }
01146 
01147 void SplitEditor::splitSingleBlock(const SplitAnalysis::BlockInfo &BI) {
01148   openIntv();
01149   SlotIndex LastSplitPoint = SA.getLastSplitPoint(BI.MBB->getNumber());
01150   SlotIndex SegStart = enterIntvBefore(std::min(BI.FirstInstr,
01151     LastSplitPoint));
01152   if (!BI.LiveOut || BI.LastInstr < LastSplitPoint) {
01153     useIntv(SegStart, leaveIntvAfter(BI.LastInstr));
01154   } else {
01155       // The last use is after the last valid split point.
01156     SlotIndex SegStop = leaveIntvBefore(LastSplitPoint);
01157     useIntv(SegStart, SegStop);
01158     overlapIntv(SegStop, BI.LastInstr);
01159   }
01160 }
01161 
01162 
01163 //===----------------------------------------------------------------------===//
01164 //                    Global Live Range Splitting Support
01165 //===----------------------------------------------------------------------===//
01166 
01167 // These methods support a method of global live range splitting that uses a
01168 // global algorithm to decide intervals for CFG edges. They will insert split
01169 // points and color intervals in basic blocks while avoiding interference.
01170 //
01171 // Note that splitSingleBlock is also useful for blocks where both CFG edges
01172 // are on the stack.
01173 
01174 void SplitEditor::splitLiveThroughBlock(unsigned MBBNum,
01175                                         unsigned IntvIn, SlotIndex LeaveBefore,
01176                                         unsigned IntvOut, SlotIndex EnterAfter){
01177   SlotIndex Start, Stop;
01178   std::tie(Start, Stop) = LIS.getSlotIndexes()->getMBBRange(MBBNum);
01179 
01180   DEBUG(dbgs() << "BB#" << MBBNum << " [" << Start << ';' << Stop
01181                << ") intf " << LeaveBefore << '-' << EnterAfter
01182                << ", live-through " << IntvIn << " -> " << IntvOut);
01183 
01184   assert((IntvIn || IntvOut) && "Use splitSingleBlock for isolated blocks");
01185 
01186   assert((!LeaveBefore || LeaveBefore < Stop) && "Interference after block");
01187   assert((!IntvIn || !LeaveBefore || LeaveBefore > Start) && "Impossible intf");
01188   assert((!EnterAfter || EnterAfter >= Start) && "Interference before block");
01189 
01190   MachineBasicBlock *MBB = VRM.getMachineFunction().getBlockNumbered(MBBNum);
01191 
01192   if (!IntvOut) {
01193     DEBUG(dbgs() << ", spill on entry.\n");
01194     //
01195     //        <<<<<<<<<    Possible LeaveBefore interference.
01196     //    |-----------|    Live through.
01197     //    -____________    Spill on entry.
01198     //
01199     selectIntv(IntvIn);
01200     SlotIndex Idx = leaveIntvAtTop(*MBB);
01201     assert((!LeaveBefore || Idx <= LeaveBefore) && "Interference");
01202     (void)Idx;
01203     return;
01204   }
01205 
01206   if (!IntvIn) {
01207     DEBUG(dbgs() << ", reload on exit.\n");
01208     //
01209     //    >>>>>>>          Possible EnterAfter interference.
01210     //    |-----------|    Live through.
01211     //    ___________--    Reload on exit.
01212     //
01213     selectIntv(IntvOut);
01214     SlotIndex Idx = enterIntvAtEnd(*MBB);
01215     assert((!EnterAfter || Idx >= EnterAfter) && "Interference");
01216     (void)Idx;
01217     return;
01218   }
01219 
01220   if (IntvIn == IntvOut && !LeaveBefore && !EnterAfter) {
01221     DEBUG(dbgs() << ", straight through.\n");
01222     //
01223     //    |-----------|    Live through.
01224     //    -------------    Straight through, same intv, no interference.
01225     //
01226     selectIntv(IntvOut);
01227     useIntv(Start, Stop);
01228     return;
01229   }
01230 
01231   // We cannot legally insert splits after LSP.
01232   SlotIndex LSP = SA.getLastSplitPoint(MBBNum);
01233   assert((!IntvOut || !EnterAfter || EnterAfter < LSP) && "Impossible intf");
01234 
01235   if (IntvIn != IntvOut && (!LeaveBefore || !EnterAfter ||
01236                   LeaveBefore.getBaseIndex() > EnterAfter.getBoundaryIndex())) {
01237     DEBUG(dbgs() << ", switch avoiding interference.\n");
01238     //
01239     //    >>>>     <<<<    Non-overlapping EnterAfter/LeaveBefore interference.
01240     //    |-----------|    Live through.
01241     //    ------=======    Switch intervals between interference.
01242     //
01243     selectIntv(IntvOut);
01244     SlotIndex Idx;
01245     if (LeaveBefore && LeaveBefore < LSP) {
01246       Idx = enterIntvBefore(LeaveBefore);
01247       useIntv(Idx, Stop);
01248     } else {
01249       Idx = enterIntvAtEnd(*MBB);
01250     }
01251     selectIntv(IntvIn);
01252     useIntv(Start, Idx);
01253     assert((!LeaveBefore || Idx <= LeaveBefore) && "Interference");
01254     assert((!EnterAfter || Idx >= EnterAfter) && "Interference");
01255     return;
01256   }
01257 
01258   DEBUG(dbgs() << ", create local intv for interference.\n");
01259   //
01260   //    >>><><><><<<<    Overlapping EnterAfter/LeaveBefore interference.
01261   //    |-----------|    Live through.
01262   //    ==---------==    Switch intervals before/after interference.
01263   //
01264   assert(LeaveBefore <= EnterAfter && "Missed case");
01265 
01266   selectIntv(IntvOut);
01267   SlotIndex Idx = enterIntvAfter(EnterAfter);
01268   useIntv(Idx, Stop);
01269   assert((!EnterAfter || Idx >= EnterAfter) && "Interference");
01270 
01271   selectIntv(IntvIn);
01272   Idx = leaveIntvBefore(LeaveBefore);
01273   useIntv(Start, Idx);
01274   assert((!LeaveBefore || Idx <= LeaveBefore) && "Interference");
01275 }
01276 
01277 
01278 void SplitEditor::splitRegInBlock(const SplitAnalysis::BlockInfo &BI,
01279                                   unsigned IntvIn, SlotIndex LeaveBefore) {
01280   SlotIndex Start, Stop;
01281   std::tie(Start, Stop) = LIS.getSlotIndexes()->getMBBRange(BI.MBB);
01282 
01283   DEBUG(dbgs() << "BB#" << BI.MBB->getNumber() << " [" << Start << ';' << Stop
01284                << "), uses " << BI.FirstInstr << '-' << BI.LastInstr
01285                << ", reg-in " << IntvIn << ", leave before " << LeaveBefore
01286                << (BI.LiveOut ? ", stack-out" : ", killed in block"));
01287 
01288   assert(IntvIn && "Must have register in");
01289   assert(BI.LiveIn && "Must be live-in");
01290   assert((!LeaveBefore || LeaveBefore > Start) && "Bad interference");
01291 
01292   if (!BI.LiveOut && (!LeaveBefore || LeaveBefore >= BI.LastInstr)) {
01293     DEBUG(dbgs() << " before interference.\n");
01294     //
01295     //               <<<    Interference after kill.
01296     //     |---o---x   |    Killed in block.
01297     //     =========        Use IntvIn everywhere.
01298     //
01299     selectIntv(IntvIn);
01300     useIntv(Start, BI.LastInstr);
01301     return;
01302   }
01303 
01304   SlotIndex LSP = SA.getLastSplitPoint(BI.MBB->getNumber());
01305 
01306   if (!LeaveBefore || LeaveBefore > BI.LastInstr.getBoundaryIndex()) {
01307     //
01308     //               <<<    Possible interference after last use.
01309     //     |---o---o---|    Live-out on stack.
01310     //     =========____    Leave IntvIn after last use.
01311     //
01312     //                 <    Interference after last use.
01313     //     |---o---o--o|    Live-out on stack, late last use.
01314     //     ============     Copy to stack after LSP, overlap IntvIn.
01315     //            \_____    Stack interval is live-out.
01316     //
01317     if (BI.LastInstr < LSP) {
01318       DEBUG(dbgs() << ", spill after last use before interference.\n");
01319       selectIntv(IntvIn);
01320       SlotIndex Idx = leaveIntvAfter(BI.LastInstr);
01321       useIntv(Start, Idx);
01322       assert((!LeaveBefore || Idx <= LeaveBefore) && "Interference");
01323     } else {
01324       DEBUG(dbgs() << ", spill before last split point.\n");
01325       selectIntv(IntvIn);
01326       SlotIndex Idx = leaveIntvBefore(LSP);
01327       overlapIntv(Idx, BI.LastInstr);
01328       useIntv(Start, Idx);
01329       assert((!LeaveBefore || Idx <= LeaveBefore) && "Interference");
01330     }
01331     return;
01332   }
01333 
01334   // The interference is overlapping somewhere we wanted to use IntvIn. That
01335   // means we need to create a local interval that can be allocated a
01336   // different register.
01337   unsigned LocalIntv = openIntv();
01338   (void)LocalIntv;
01339   DEBUG(dbgs() << ", creating local interval " << LocalIntv << ".\n");
01340 
01341   if (!BI.LiveOut || BI.LastInstr < LSP) {
01342     //
01343     //           <<<<<<<    Interference overlapping uses.
01344     //     |---o---o---|    Live-out on stack.
01345     //     =====----____    Leave IntvIn before interference, then spill.
01346     //
01347     SlotIndex To = leaveIntvAfter(BI.LastInstr);
01348     SlotIndex From = enterIntvBefore(LeaveBefore);
01349     useIntv(From, To);
01350     selectIntv(IntvIn);
01351     useIntv(Start, From);
01352     assert((!LeaveBefore || From <= LeaveBefore) && "Interference");
01353     return;
01354   }
01355 
01356   //           <<<<<<<    Interference overlapping uses.
01357   //     |---o---o--o|    Live-out on stack, late last use.
01358   //     =====-------     Copy to stack before LSP, overlap LocalIntv.
01359   //            \_____    Stack interval is live-out.
01360   //
01361   SlotIndex To = leaveIntvBefore(LSP);
01362   overlapIntv(To, BI.LastInstr);
01363   SlotIndex From = enterIntvBefore(std::min(To, LeaveBefore));
01364   useIntv(From, To);
01365   selectIntv(IntvIn);
01366   useIntv(Start, From);
01367   assert((!LeaveBefore || From <= LeaveBefore) && "Interference");
01368 }
01369 
01370 void SplitEditor::splitRegOutBlock(const SplitAnalysis::BlockInfo &BI,
01371                                    unsigned IntvOut, SlotIndex EnterAfter) {
01372   SlotIndex Start, Stop;
01373   std::tie(Start, Stop) = LIS.getSlotIndexes()->getMBBRange(BI.MBB);
01374 
01375   DEBUG(dbgs() << "BB#" << BI.MBB->getNumber() << " [" << Start << ';' << Stop
01376                << "), uses " << BI.FirstInstr << '-' << BI.LastInstr
01377                << ", reg-out " << IntvOut << ", enter after " << EnterAfter
01378                << (BI.LiveIn ? ", stack-in" : ", defined in block"));
01379 
01380   SlotIndex LSP = SA.getLastSplitPoint(BI.MBB->getNumber());
01381 
01382   assert(IntvOut && "Must have register out");
01383   assert(BI.LiveOut && "Must be live-out");
01384   assert((!EnterAfter || EnterAfter < LSP) && "Bad interference");
01385 
01386   if (!BI.LiveIn && (!EnterAfter || EnterAfter <= BI.FirstInstr)) {
01387     DEBUG(dbgs() << " after interference.\n");
01388     //
01389     //    >>>>             Interference before def.
01390     //    |   o---o---|    Defined in block.
01391     //        =========    Use IntvOut everywhere.
01392     //
01393     selectIntv(IntvOut);
01394     useIntv(BI.FirstInstr, Stop);
01395     return;
01396   }
01397 
01398   if (!EnterAfter || EnterAfter < BI.FirstInstr.getBaseIndex()) {
01399     DEBUG(dbgs() << ", reload after interference.\n");
01400     //
01401     //    >>>>             Interference before def.
01402     //    |---o---o---|    Live-through, stack-in.
01403     //    ____=========    Enter IntvOut before first use.
01404     //
01405     selectIntv(IntvOut);
01406     SlotIndex Idx = enterIntvBefore(std::min(LSP, BI.FirstInstr));
01407     useIntv(Idx, Stop);
01408     assert((!EnterAfter || Idx >= EnterAfter) && "Interference");
01409     return;
01410   }
01411 
01412   // The interference is overlapping somewhere we wanted to use IntvOut. That
01413   // means we need to create a local interval that can be allocated a
01414   // different register.
01415   DEBUG(dbgs() << ", interference overlaps uses.\n");
01416   //
01417   //    >>>>>>>          Interference overlapping uses.
01418   //    |---o---o---|    Live-through, stack-in.
01419   //    ____---======    Create local interval for interference range.
01420   //
01421   selectIntv(IntvOut);
01422   SlotIndex Idx = enterIntvAfter(EnterAfter);
01423   useIntv(Idx, Stop);
01424   assert((!EnterAfter || Idx >= EnterAfter) && "Interference");
01425 
01426   openIntv();
01427   SlotIndex From = enterIntvBefore(std::min(Idx, BI.FirstInstr));
01428   useIntv(From, Idx);
01429 }