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