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