xref: /freebsd/contrib/llvm-project/llvm/lib/CodeGen/LiveIntervals.cpp (revision 577b62c2bacc7dfa228591ca3da361e1bc398301)
1 //===- LiveIntervals.cpp - Live Interval Analysis -------------------------===//
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 /// \file This file implements the LiveInterval analysis pass which is used
10 /// by the Linear Scan Register allocator. This pass linearizes the
11 /// basic blocks of the function in DFS order and computes live intervals for
12 /// each virtual and physical register.
13 //
14 //===----------------------------------------------------------------------===//
15 
16 #include "llvm/CodeGen/LiveIntervals.h"
17 #include "llvm/ADT/ArrayRef.h"
18 #include "llvm/ADT/DepthFirstIterator.h"
19 #include "llvm/ADT/SmallPtrSet.h"
20 #include "llvm/ADT/SmallVector.h"
21 #include "llvm/ADT/iterator_range.h"
22 #include "llvm/CodeGen/LiveInterval.h"
23 #include "llvm/CodeGen/LiveIntervalCalc.h"
24 #include "llvm/CodeGen/LiveVariables.h"
25 #include "llvm/CodeGen/MachineBasicBlock.h"
26 #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
27 #include "llvm/CodeGen/MachineDominators.h"
28 #include "llvm/CodeGen/MachineFunction.h"
29 #include "llvm/CodeGen/MachineInstr.h"
30 #include "llvm/CodeGen/MachineInstrBundle.h"
31 #include "llvm/CodeGen/MachineOperand.h"
32 #include "llvm/CodeGen/MachineRegisterInfo.h"
33 #include "llvm/CodeGen/Passes.h"
34 #include "llvm/CodeGen/SlotIndexes.h"
35 #include "llvm/CodeGen/StackMaps.h"
36 #include "llvm/CodeGen/TargetRegisterInfo.h"
37 #include "llvm/CodeGen/TargetSubtargetInfo.h"
38 #include "llvm/CodeGen/VirtRegMap.h"
39 #include "llvm/Config/llvm-config.h"
40 #include "llvm/IR/Statepoint.h"
41 #include "llvm/MC/LaneBitmask.h"
42 #include "llvm/MC/MCRegisterInfo.h"
43 #include "llvm/Pass.h"
44 #include "llvm/Support/CommandLine.h"
45 #include "llvm/Support/Compiler.h"
46 #include "llvm/Support/Debug.h"
47 #include "llvm/Support/MathExtras.h"
48 #include "llvm/Support/raw_ostream.h"
49 #include <algorithm>
50 #include <cassert>
51 #include <cstdint>
52 #include <iterator>
53 #include <tuple>
54 #include <utility>
55 
56 using namespace llvm;
57 
58 #define DEBUG_TYPE "regalloc"
59 
60 char LiveIntervals::ID = 0;
61 char &llvm::LiveIntervalsID = LiveIntervals::ID;
62 INITIALIZE_PASS_BEGIN(LiveIntervals, "liveintervals", "Live Interval Analysis",
63                       false, false)
64 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
65 INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
66 INITIALIZE_PASS_END(LiveIntervals, "liveintervals",
67                 "Live Interval Analysis", false, false)
68 
69 #ifndef NDEBUG
70 static cl::opt<bool> EnablePrecomputePhysRegs(
71   "precompute-phys-liveness", cl::Hidden,
72   cl::desc("Eagerly compute live intervals for all physreg units."));
73 #else
74 static bool EnablePrecomputePhysRegs = false;
75 #endif // NDEBUG
76 
77 namespace llvm {
78 
79 cl::opt<bool> UseSegmentSetForPhysRegs(
80     "use-segment-set-for-physregs", cl::Hidden, cl::init(true),
81     cl::desc(
82         "Use segment set for the computation of the live ranges of physregs."));
83 
84 } // end namespace llvm
85 
86 void LiveIntervals::getAnalysisUsage(AnalysisUsage &AU) const {
87   AU.setPreservesCFG();
88   AU.addPreserved<LiveVariables>();
89   AU.addPreservedID(MachineLoopInfoID);
90   AU.addRequiredTransitiveID(MachineDominatorsID);
91   AU.addPreservedID(MachineDominatorsID);
92   AU.addPreserved<SlotIndexes>();
93   AU.addRequiredTransitive<SlotIndexes>();
94   MachineFunctionPass::getAnalysisUsage(AU);
95 }
96 
97 LiveIntervals::LiveIntervals() : MachineFunctionPass(ID) {
98   initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
99 }
100 
101 LiveIntervals::~LiveIntervals() { delete LICalc; }
102 
103 void LiveIntervals::releaseMemory() {
104   // Free the live intervals themselves.
105   for (unsigned i = 0, e = VirtRegIntervals.size(); i != e; ++i)
106     delete VirtRegIntervals[Register::index2VirtReg(i)];
107   VirtRegIntervals.clear();
108   RegMaskSlots.clear();
109   RegMaskBits.clear();
110   RegMaskBlocks.clear();
111 
112   for (LiveRange *LR : RegUnitRanges)
113     delete LR;
114   RegUnitRanges.clear();
115 
116   // Release VNInfo memory regions, VNInfo objects don't need to be dtor'd.
117   VNInfoAllocator.Reset();
118 }
119 
120 bool LiveIntervals::runOnMachineFunction(MachineFunction &fn) {
121   MF = &fn;
122   MRI = &MF->getRegInfo();
123   TRI = MF->getSubtarget().getRegisterInfo();
124   TII = MF->getSubtarget().getInstrInfo();
125   Indexes = &getAnalysis<SlotIndexes>();
126   DomTree = &getAnalysis<MachineDominatorTree>();
127 
128   if (!LICalc)
129     LICalc = new LiveIntervalCalc();
130 
131   // Allocate space for all virtual registers.
132   VirtRegIntervals.resize(MRI->getNumVirtRegs());
133 
134   computeVirtRegs();
135   computeRegMasks();
136   computeLiveInRegUnits();
137 
138   if (EnablePrecomputePhysRegs) {
139     // For stress testing, precompute live ranges of all physical register
140     // units, including reserved registers.
141     for (unsigned i = 0, e = TRI->getNumRegUnits(); i != e; ++i)
142       getRegUnit(i);
143   }
144   LLVM_DEBUG(dump());
145   return false;
146 }
147 
148 void LiveIntervals::print(raw_ostream &OS, const Module* ) const {
149   OS << "********** INTERVALS **********\n";
150 
151   // Dump the regunits.
152   for (unsigned Unit = 0, UnitE = RegUnitRanges.size(); Unit != UnitE; ++Unit)
153     if (LiveRange *LR = RegUnitRanges[Unit])
154       OS << printRegUnit(Unit, TRI) << ' ' << *LR << '\n';
155 
156   // Dump the virtregs.
157   for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
158     Register Reg = Register::index2VirtReg(i);
159     if (hasInterval(Reg))
160       OS << getInterval(Reg) << '\n';
161   }
162 
163   OS << "RegMasks:";
164   for (SlotIndex Idx : RegMaskSlots)
165     OS << ' ' << Idx;
166   OS << '\n';
167 
168   printInstrs(OS);
169 }
170 
171 void LiveIntervals::printInstrs(raw_ostream &OS) const {
172   OS << "********** MACHINEINSTRS **********\n";
173   MF->print(OS, Indexes);
174 }
175 
176 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
177 LLVM_DUMP_METHOD void LiveIntervals::dumpInstrs() const {
178   printInstrs(dbgs());
179 }
180 #endif
181 
182 LiveInterval *LiveIntervals::createInterval(Register reg) {
183   float Weight = Register::isPhysicalRegister(reg) ? huge_valf : 0.0F;
184   return new LiveInterval(reg, Weight);
185 }
186 
187 /// Compute the live interval of a virtual register, based on defs and uses.
188 bool LiveIntervals::computeVirtRegInterval(LiveInterval &LI) {
189   assert(LICalc && "LICalc not initialized.");
190   assert(LI.empty() && "Should only compute empty intervals.");
191   LICalc->reset(MF, getSlotIndexes(), DomTree, &getVNInfoAllocator());
192   LICalc->calculate(LI, MRI->shouldTrackSubRegLiveness(LI.reg()));
193   return computeDeadValues(LI, nullptr);
194 }
195 
196 void LiveIntervals::computeVirtRegs() {
197   for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
198     Register Reg = Register::index2VirtReg(i);
199     if (MRI->reg_nodbg_empty(Reg))
200       continue;
201     LiveInterval &LI = createEmptyInterval(Reg);
202     bool NeedSplit = computeVirtRegInterval(LI);
203     if (NeedSplit) {
204       SmallVector<LiveInterval*, 8> SplitLIs;
205       splitSeparateComponents(LI, SplitLIs);
206     }
207   }
208 }
209 
210 void LiveIntervals::computeRegMasks() {
211   RegMaskBlocks.resize(MF->getNumBlockIDs());
212 
213   // Find all instructions with regmask operands.
214   for (const MachineBasicBlock &MBB : *MF) {
215     std::pair<unsigned, unsigned> &RMB = RegMaskBlocks[MBB.getNumber()];
216     RMB.first = RegMaskSlots.size();
217 
218     // Some block starts, such as EH funclets, create masks.
219     if (const uint32_t *Mask = MBB.getBeginClobberMask(TRI)) {
220       RegMaskSlots.push_back(Indexes->getMBBStartIdx(&MBB));
221       RegMaskBits.push_back(Mask);
222     }
223 
224     // Unwinders may clobber additional registers.
225     // FIXME: This functionality can possibly be merged into
226     // MachineBasicBlock::getBeginClobberMask().
227     if (MBB.isEHPad())
228       if (auto *Mask = TRI->getCustomEHPadPreservedMask(*MBB.getParent())) {
229         RegMaskSlots.push_back(Indexes->getMBBStartIdx(&MBB));
230         RegMaskBits.push_back(Mask);
231       }
232 
233     for (const MachineInstr &MI : MBB) {
234       for (const MachineOperand &MO : MI.operands()) {
235         if (!MO.isRegMask())
236           continue;
237         RegMaskSlots.push_back(Indexes->getInstructionIndex(MI).getRegSlot());
238         RegMaskBits.push_back(MO.getRegMask());
239       }
240     }
241 
242     // Some block ends, such as funclet returns, create masks. Put the mask on
243     // the last instruction of the block, because MBB slot index intervals are
244     // half-open.
245     if (const uint32_t *Mask = MBB.getEndClobberMask(TRI)) {
246       assert(!MBB.empty() && "empty return block?");
247       RegMaskSlots.push_back(
248           Indexes->getInstructionIndex(MBB.back()).getRegSlot());
249       RegMaskBits.push_back(Mask);
250     }
251 
252     // Compute the number of register mask instructions in this block.
253     RMB.second = RegMaskSlots.size() - RMB.first;
254   }
255 }
256 
257 //===----------------------------------------------------------------------===//
258 //                           Register Unit Liveness
259 //===----------------------------------------------------------------------===//
260 //
261 // Fixed interference typically comes from ABI boundaries: Function arguments
262 // and return values are passed in fixed registers, and so are exception
263 // pointers entering landing pads. Certain instructions require values to be
264 // present in specific registers. That is also represented through fixed
265 // interference.
266 //
267 
268 /// Compute the live range of a register unit, based on the uses and defs of
269 /// aliasing registers.  The range should be empty, or contain only dead
270 /// phi-defs from ABI blocks.
271 void LiveIntervals::computeRegUnitRange(LiveRange &LR, unsigned Unit) {
272   assert(LICalc && "LICalc not initialized.");
273   LICalc->reset(MF, getSlotIndexes(), DomTree, &getVNInfoAllocator());
274 
275   // The physregs aliasing Unit are the roots and their super-registers.
276   // Create all values as dead defs before extending to uses. Note that roots
277   // may share super-registers. That's OK because createDeadDefs() is
278   // idempotent. It is very rare for a register unit to have multiple roots, so
279   // uniquing super-registers is probably not worthwhile.
280   bool IsReserved = false;
281   for (MCRegUnitRootIterator Root(Unit, TRI); Root.isValid(); ++Root) {
282     bool IsRootReserved = true;
283     for (MCSuperRegIterator Super(*Root, TRI, /*IncludeSelf=*/true);
284          Super.isValid(); ++Super) {
285       MCRegister Reg = *Super;
286       if (!MRI->reg_empty(Reg))
287         LICalc->createDeadDefs(LR, Reg);
288       // A register unit is considered reserved if all its roots and all their
289       // super registers are reserved.
290       if (!MRI->isReserved(Reg))
291         IsRootReserved = false;
292     }
293     IsReserved |= IsRootReserved;
294   }
295   assert(IsReserved == MRI->isReservedRegUnit(Unit) &&
296          "reserved computation mismatch");
297 
298   // Now extend LR to reach all uses.
299   // Ignore uses of reserved registers. We only track defs of those.
300   if (!IsReserved) {
301     for (MCRegUnitRootIterator Root(Unit, TRI); Root.isValid(); ++Root) {
302       for (MCSuperRegIterator Super(*Root, TRI, /*IncludeSelf=*/true);
303            Super.isValid(); ++Super) {
304         MCRegister Reg = *Super;
305         if (!MRI->reg_empty(Reg))
306           LICalc->extendToUses(LR, Reg);
307       }
308     }
309   }
310 
311   // Flush the segment set to the segment vector.
312   if (UseSegmentSetForPhysRegs)
313     LR.flushSegmentSet();
314 }
315 
316 /// Precompute the live ranges of any register units that are live-in to an ABI
317 /// block somewhere. Register values can appear without a corresponding def when
318 /// entering the entry block or a landing pad.
319 void LiveIntervals::computeLiveInRegUnits() {
320   RegUnitRanges.resize(TRI->getNumRegUnits());
321   LLVM_DEBUG(dbgs() << "Computing live-in reg-units in ABI blocks.\n");
322 
323   // Keep track of the live range sets allocated.
324   SmallVector<unsigned, 8> NewRanges;
325 
326   // Check all basic blocks for live-ins.
327   for (const MachineBasicBlock &MBB : *MF) {
328     // We only care about ABI blocks: Entry + landing pads.
329     if ((&MBB != &MF->front() && !MBB.isEHPad()) || MBB.livein_empty())
330       continue;
331 
332     // Create phi-defs at Begin for all live-in registers.
333     SlotIndex Begin = Indexes->getMBBStartIdx(&MBB);
334     LLVM_DEBUG(dbgs() << Begin << "\t" << printMBBReference(MBB));
335     for (const auto &LI : MBB.liveins()) {
336       for (MCRegUnitIterator Units(LI.PhysReg, TRI); Units.isValid(); ++Units) {
337         unsigned Unit = *Units;
338         LiveRange *LR = RegUnitRanges[Unit];
339         if (!LR) {
340           // Use segment set to speed-up initial computation of the live range.
341           LR = RegUnitRanges[Unit] = new LiveRange(UseSegmentSetForPhysRegs);
342           NewRanges.push_back(Unit);
343         }
344         VNInfo *VNI = LR->createDeadDef(Begin, getVNInfoAllocator());
345         (void)VNI;
346         LLVM_DEBUG(dbgs() << ' ' << printRegUnit(Unit, TRI) << '#' << VNI->id);
347       }
348     }
349     LLVM_DEBUG(dbgs() << '\n');
350   }
351   LLVM_DEBUG(dbgs() << "Created " << NewRanges.size() << " new intervals.\n");
352 
353   // Compute the 'normal' part of the ranges.
354   for (unsigned Unit : NewRanges)
355     computeRegUnitRange(*RegUnitRanges[Unit], Unit);
356 }
357 
358 static void createSegmentsForValues(LiveRange &LR,
359     iterator_range<LiveInterval::vni_iterator> VNIs) {
360   for (VNInfo *VNI : VNIs) {
361     if (VNI->isUnused())
362       continue;
363     SlotIndex Def = VNI->def;
364     LR.addSegment(LiveRange::Segment(Def, Def.getDeadSlot(), VNI));
365   }
366 }
367 
368 void LiveIntervals::extendSegmentsToUses(LiveRange &Segments,
369                                          ShrinkToUsesWorkList &WorkList,
370                                          Register Reg, LaneBitmask LaneMask) {
371   // Keep track of the PHIs that are in use.
372   SmallPtrSet<VNInfo*, 8> UsedPHIs;
373   // Blocks that have already been added to WorkList as live-out.
374   SmallPtrSet<const MachineBasicBlock*, 16> LiveOut;
375 
376   auto getSubRange = [](const LiveInterval &I, LaneBitmask M)
377         -> const LiveRange& {
378     if (M.none())
379       return I;
380     for (const LiveInterval::SubRange &SR : I.subranges()) {
381       if ((SR.LaneMask & M).any()) {
382         assert(SR.LaneMask == M && "Expecting lane masks to match exactly");
383         return SR;
384       }
385     }
386     llvm_unreachable("Subrange for mask not found");
387   };
388 
389   const LiveInterval &LI = getInterval(Reg);
390   const LiveRange &OldRange = getSubRange(LI, LaneMask);
391 
392   // Extend intervals to reach all uses in WorkList.
393   while (!WorkList.empty()) {
394     SlotIndex Idx = WorkList.back().first;
395     VNInfo *VNI = WorkList.back().second;
396     WorkList.pop_back();
397     const MachineBasicBlock *MBB = Indexes->getMBBFromIndex(Idx.getPrevSlot());
398     SlotIndex BlockStart = Indexes->getMBBStartIdx(MBB);
399 
400     // Extend the live range for VNI to be live at Idx.
401     if (VNInfo *ExtVNI = Segments.extendInBlock(BlockStart, Idx)) {
402       assert(ExtVNI == VNI && "Unexpected existing value number");
403       (void)ExtVNI;
404       // Is this a PHIDef we haven't seen before?
405       if (!VNI->isPHIDef() || VNI->def != BlockStart ||
406           !UsedPHIs.insert(VNI).second)
407         continue;
408       // The PHI is live, make sure the predecessors are live-out.
409       for (const MachineBasicBlock *Pred : MBB->predecessors()) {
410         if (!LiveOut.insert(Pred).second)
411           continue;
412         SlotIndex Stop = Indexes->getMBBEndIdx(Pred);
413         // A predecessor is not required to have a live-out value for a PHI.
414         if (VNInfo *PVNI = OldRange.getVNInfoBefore(Stop))
415           WorkList.push_back(std::make_pair(Stop, PVNI));
416       }
417       continue;
418     }
419 
420     // VNI is live-in to MBB.
421     LLVM_DEBUG(dbgs() << " live-in at " << BlockStart << '\n');
422     Segments.addSegment(LiveRange::Segment(BlockStart, Idx, VNI));
423 
424     // Make sure VNI is live-out from the predecessors.
425     for (const MachineBasicBlock *Pred : MBB->predecessors()) {
426       if (!LiveOut.insert(Pred).second)
427         continue;
428       SlotIndex Stop = Indexes->getMBBEndIdx(Pred);
429       if (VNInfo *OldVNI = OldRange.getVNInfoBefore(Stop)) {
430         assert(OldVNI == VNI && "Wrong value out of predecessor");
431         (void)OldVNI;
432         WorkList.push_back(std::make_pair(Stop, VNI));
433       } else {
434 #ifndef NDEBUG
435         // There was no old VNI. Verify that Stop is jointly dominated
436         // by <undef>s for this live range.
437         assert(LaneMask.any() &&
438                "Missing value out of predecessor for main range");
439         SmallVector<SlotIndex,8> Undefs;
440         LI.computeSubRangeUndefs(Undefs, LaneMask, *MRI, *Indexes);
441         assert(LiveRangeCalc::isJointlyDominated(Pred, Undefs, *Indexes) &&
442                "Missing value out of predecessor for subrange");
443 #endif
444       }
445     }
446   }
447 }
448 
449 bool LiveIntervals::shrinkToUses(LiveInterval *li,
450                                  SmallVectorImpl<MachineInstr*> *dead) {
451   LLVM_DEBUG(dbgs() << "Shrink: " << *li << '\n');
452   assert(Register::isVirtualRegister(li->reg()) &&
453          "Can only shrink virtual registers");
454 
455   // Shrink subregister live ranges.
456   bool NeedsCleanup = false;
457   for (LiveInterval::SubRange &S : li->subranges()) {
458     shrinkToUses(S, li->reg());
459     if (S.empty())
460       NeedsCleanup = true;
461   }
462   if (NeedsCleanup)
463     li->removeEmptySubRanges();
464 
465   // Find all the values used, including PHI kills.
466   ShrinkToUsesWorkList WorkList;
467 
468   // Visit all instructions reading li->reg().
469   Register Reg = li->reg();
470   for (MachineInstr &UseMI : MRI->reg_instructions(Reg)) {
471     if (UseMI.isDebugInstr() || !UseMI.readsVirtualRegister(Reg))
472       continue;
473     SlotIndex Idx = getInstructionIndex(UseMI).getRegSlot();
474     LiveQueryResult LRQ = li->Query(Idx);
475     VNInfo *VNI = LRQ.valueIn();
476     if (!VNI) {
477       // This shouldn't happen: readsVirtualRegister returns true, but there is
478       // no live value. It is likely caused by a target getting <undef> flags
479       // wrong.
480       LLVM_DEBUG(
481           dbgs() << Idx << '\t' << UseMI
482                  << "Warning: Instr claims to read non-existent value in "
483                  << *li << '\n');
484       continue;
485     }
486     // Special case: An early-clobber tied operand reads and writes the
487     // register one slot early.
488     if (VNInfo *DefVNI = LRQ.valueDefined())
489       Idx = DefVNI->def;
490 
491     WorkList.push_back(std::make_pair(Idx, VNI));
492   }
493 
494   // Create new live ranges with only minimal live segments per def.
495   LiveRange NewLR;
496   createSegmentsForValues(NewLR, li->vnis());
497   extendSegmentsToUses(NewLR, WorkList, Reg, LaneBitmask::getNone());
498 
499   // Move the trimmed segments back.
500   li->segments.swap(NewLR.segments);
501 
502   // Handle dead values.
503   bool CanSeparate = computeDeadValues(*li, dead);
504   LLVM_DEBUG(dbgs() << "Shrunk: " << *li << '\n');
505   return CanSeparate;
506 }
507 
508 bool LiveIntervals::computeDeadValues(LiveInterval &LI,
509                                       SmallVectorImpl<MachineInstr*> *dead) {
510   bool MayHaveSplitComponents = false;
511   bool HaveDeadDef = false;
512 
513   for (VNInfo *VNI : LI.valnos) {
514     if (VNI->isUnused())
515       continue;
516     SlotIndex Def = VNI->def;
517     LiveRange::iterator I = LI.FindSegmentContaining(Def);
518     assert(I != LI.end() && "Missing segment for VNI");
519 
520     // Is the register live before? Otherwise we may have to add a read-undef
521     // flag for subregister defs.
522     Register VReg = LI.reg();
523     if (MRI->shouldTrackSubRegLiveness(VReg)) {
524       if ((I == LI.begin() || std::prev(I)->end < Def) && !VNI->isPHIDef()) {
525         MachineInstr *MI = getInstructionFromIndex(Def);
526         MI->setRegisterDefReadUndef(VReg);
527       }
528     }
529 
530     if (I->end != Def.getDeadSlot())
531       continue;
532     if (VNI->isPHIDef()) {
533       // This is a dead PHI. Remove it.
534       VNI->markUnused();
535       LI.removeSegment(I);
536       LLVM_DEBUG(dbgs() << "Dead PHI at " << Def << " may separate interval\n");
537       MayHaveSplitComponents = true;
538     } else {
539       // This is a dead def. Make sure the instruction knows.
540       MachineInstr *MI = getInstructionFromIndex(Def);
541       assert(MI && "No instruction defining live value");
542       MI->addRegisterDead(LI.reg(), TRI);
543       if (HaveDeadDef)
544         MayHaveSplitComponents = true;
545       HaveDeadDef = true;
546 
547       if (dead && MI->allDefsAreDead()) {
548         LLVM_DEBUG(dbgs() << "All defs dead: " << Def << '\t' << *MI);
549         dead->push_back(MI);
550       }
551     }
552   }
553   return MayHaveSplitComponents;
554 }
555 
556 void LiveIntervals::shrinkToUses(LiveInterval::SubRange &SR, Register Reg) {
557   LLVM_DEBUG(dbgs() << "Shrink: " << SR << '\n');
558   assert(Register::isVirtualRegister(Reg) &&
559          "Can only shrink virtual registers");
560   // Find all the values used, including PHI kills.
561   ShrinkToUsesWorkList WorkList;
562 
563   // Visit all instructions reading Reg.
564   SlotIndex LastIdx;
565   for (MachineOperand &MO : MRI->use_nodbg_operands(Reg)) {
566     // Skip "undef" uses.
567     if (!MO.readsReg())
568       continue;
569     // Maybe the operand is for a subregister we don't care about.
570     unsigned SubReg = MO.getSubReg();
571     if (SubReg != 0) {
572       LaneBitmask LaneMask = TRI->getSubRegIndexLaneMask(SubReg);
573       if ((LaneMask & SR.LaneMask).none())
574         continue;
575     }
576     // We only need to visit each instruction once.
577     MachineInstr *UseMI = MO.getParent();
578     SlotIndex Idx = getInstructionIndex(*UseMI).getRegSlot();
579     if (Idx == LastIdx)
580       continue;
581     LastIdx = Idx;
582 
583     LiveQueryResult LRQ = SR.Query(Idx);
584     VNInfo *VNI = LRQ.valueIn();
585     // For Subranges it is possible that only undef values are left in that
586     // part of the subregister, so there is no real liverange at the use
587     if (!VNI)
588       continue;
589 
590     // Special case: An early-clobber tied operand reads and writes the
591     // register one slot early.
592     if (VNInfo *DefVNI = LRQ.valueDefined())
593       Idx = DefVNI->def;
594 
595     WorkList.push_back(std::make_pair(Idx, VNI));
596   }
597 
598   // Create a new live ranges with only minimal live segments per def.
599   LiveRange NewLR;
600   createSegmentsForValues(NewLR, SR.vnis());
601   extendSegmentsToUses(NewLR, WorkList, Reg, SR.LaneMask);
602 
603   // Move the trimmed ranges back.
604   SR.segments.swap(NewLR.segments);
605 
606   // Remove dead PHI value numbers
607   for (VNInfo *VNI : SR.valnos) {
608     if (VNI->isUnused())
609       continue;
610     const LiveRange::Segment *Segment = SR.getSegmentContaining(VNI->def);
611     assert(Segment != nullptr && "Missing segment for VNI");
612     if (Segment->end != VNI->def.getDeadSlot())
613       continue;
614     if (VNI->isPHIDef()) {
615       // This is a dead PHI. Remove it.
616       LLVM_DEBUG(dbgs() << "Dead PHI at " << VNI->def
617                         << " may separate interval\n");
618       VNI->markUnused();
619       SR.removeSegment(*Segment);
620     }
621   }
622 
623   LLVM_DEBUG(dbgs() << "Shrunk: " << SR << '\n');
624 }
625 
626 void LiveIntervals::extendToIndices(LiveRange &LR,
627                                     ArrayRef<SlotIndex> Indices,
628                                     ArrayRef<SlotIndex> Undefs) {
629   assert(LICalc && "LICalc not initialized.");
630   LICalc->reset(MF, getSlotIndexes(), DomTree, &getVNInfoAllocator());
631   for (SlotIndex Idx : Indices)
632     LICalc->extend(LR, Idx, /*PhysReg=*/0, Undefs);
633 }
634 
635 void LiveIntervals::pruneValue(LiveRange &LR, SlotIndex Kill,
636                                SmallVectorImpl<SlotIndex> *EndPoints) {
637   LiveQueryResult LRQ = LR.Query(Kill);
638   VNInfo *VNI = LRQ.valueOutOrDead();
639   if (!VNI)
640     return;
641 
642   MachineBasicBlock *KillMBB = Indexes->getMBBFromIndex(Kill);
643   SlotIndex MBBEnd = Indexes->getMBBEndIdx(KillMBB);
644 
645   // If VNI isn't live out from KillMBB, the value is trivially pruned.
646   if (LRQ.endPoint() < MBBEnd) {
647     LR.removeSegment(Kill, LRQ.endPoint());
648     if (EndPoints) EndPoints->push_back(LRQ.endPoint());
649     return;
650   }
651 
652   // VNI is live out of KillMBB.
653   LR.removeSegment(Kill, MBBEnd);
654   if (EndPoints) EndPoints->push_back(MBBEnd);
655 
656   // Find all blocks that are reachable from KillMBB without leaving VNI's live
657   // range. It is possible that KillMBB itself is reachable, so start a DFS
658   // from each successor.
659   using VisitedTy = df_iterator_default_set<MachineBasicBlock*,9>;
660   VisitedTy Visited;
661   for (MachineBasicBlock *Succ : KillMBB->successors()) {
662     for (df_ext_iterator<MachineBasicBlock*, VisitedTy>
663          I = df_ext_begin(Succ, Visited), E = df_ext_end(Succ, Visited);
664          I != E;) {
665       MachineBasicBlock *MBB = *I;
666 
667       // Check if VNI is live in to MBB.
668       SlotIndex MBBStart, MBBEnd;
669       std::tie(MBBStart, MBBEnd) = Indexes->getMBBRange(MBB);
670       LiveQueryResult LRQ = LR.Query(MBBStart);
671       if (LRQ.valueIn() != VNI) {
672         // This block isn't part of the VNI segment. Prune the search.
673         I.skipChildren();
674         continue;
675       }
676 
677       // Prune the search if VNI is killed in MBB.
678       if (LRQ.endPoint() < MBBEnd) {
679         LR.removeSegment(MBBStart, LRQ.endPoint());
680         if (EndPoints) EndPoints->push_back(LRQ.endPoint());
681         I.skipChildren();
682         continue;
683       }
684 
685       // VNI is live through MBB.
686       LR.removeSegment(MBBStart, MBBEnd);
687       if (EndPoints) EndPoints->push_back(MBBEnd);
688       ++I;
689     }
690   }
691 }
692 
693 //===----------------------------------------------------------------------===//
694 // Register allocator hooks.
695 //
696 
697 void LiveIntervals::addKillFlags(const VirtRegMap *VRM) {
698   // Keep track of regunit ranges.
699   SmallVector<std::pair<const LiveRange*, LiveRange::const_iterator>, 8> RU;
700 
701   for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
702     Register Reg = Register::index2VirtReg(i);
703     if (MRI->reg_nodbg_empty(Reg))
704       continue;
705     const LiveInterval &LI = getInterval(Reg);
706     if (LI.empty())
707       continue;
708 
709     // Target may have not allocated this yet.
710     Register PhysReg = VRM->getPhys(Reg);
711     if (!PhysReg)
712       continue;
713 
714     // Find the regunit intervals for the assigned register. They may overlap
715     // the virtual register live range, cancelling any kills.
716     RU.clear();
717     for (MCRegUnitIterator Unit(PhysReg, TRI); Unit.isValid();
718          ++Unit) {
719       const LiveRange &RURange = getRegUnit(*Unit);
720       if (RURange.empty())
721         continue;
722       RU.push_back(std::make_pair(&RURange, RURange.find(LI.begin()->end)));
723     }
724     // Every instruction that kills Reg corresponds to a segment range end
725     // point.
726     for (LiveInterval::const_iterator RI = LI.begin(), RE = LI.end(); RI != RE;
727          ++RI) {
728       // A block index indicates an MBB edge.
729       if (RI->end.isBlock())
730         continue;
731       MachineInstr *MI = getInstructionFromIndex(RI->end);
732       if (!MI)
733         continue;
734 
735       // Check if any of the regunits are live beyond the end of RI. That could
736       // happen when a physreg is defined as a copy of a virtreg:
737       //
738       //   %eax = COPY %5
739       //   FOO %5             <--- MI, cancel kill because %eax is live.
740       //   BAR killed %eax
741       //
742       // There should be no kill flag on FOO when %5 is rewritten as %eax.
743       for (auto &RUP : RU) {
744         const LiveRange &RURange = *RUP.first;
745         LiveRange::const_iterator &I = RUP.second;
746         if (I == RURange.end())
747           continue;
748         I = RURange.advanceTo(I, RI->end);
749         if (I == RURange.end() || I->start >= RI->end)
750           continue;
751         // I is overlapping RI.
752         goto CancelKill;
753       }
754 
755       if (MRI->subRegLivenessEnabled()) {
756         // When reading a partial undefined value we must not add a kill flag.
757         // The regalloc might have used the undef lane for something else.
758         // Example:
759         //     %1 = ...                  ; R32: %1
760         //     %2:high16 = ...           ; R64: %2
761         //        = read killed %2        ; R64: %2
762         //        = read %1              ; R32: %1
763         // The <kill> flag is correct for %2, but the register allocator may
764         // assign R0L to %1, and R0 to %2 because the low 32bits of R0
765         // are actually never written by %2. After assignment the <kill>
766         // flag at the read instruction is invalid.
767         LaneBitmask DefinedLanesMask;
768         if (LI.hasSubRanges()) {
769           // Compute a mask of lanes that are defined.
770           DefinedLanesMask = LaneBitmask::getNone();
771           for (const LiveInterval::SubRange &SR : LI.subranges())
772             for (const LiveRange::Segment &Segment : SR.segments) {
773               if (Segment.start >= RI->end)
774                 break;
775               if (Segment.end == RI->end) {
776                 DefinedLanesMask |= SR.LaneMask;
777                 break;
778               }
779             }
780         } else
781           DefinedLanesMask = LaneBitmask::getAll();
782 
783         bool IsFullWrite = false;
784         for (const MachineOperand &MO : MI->operands()) {
785           if (!MO.isReg() || MO.getReg() != Reg)
786             continue;
787           if (MO.isUse()) {
788             // Reading any undefined lanes?
789             unsigned SubReg = MO.getSubReg();
790             LaneBitmask UseMask = SubReg ? TRI->getSubRegIndexLaneMask(SubReg)
791                                          : MRI->getMaxLaneMaskForVReg(Reg);
792             if ((UseMask & ~DefinedLanesMask).any())
793               goto CancelKill;
794           } else if (MO.getSubReg() == 0) {
795             // Writing to the full register?
796             assert(MO.isDef());
797             IsFullWrite = true;
798           }
799         }
800 
801         // If an instruction writes to a subregister, a new segment starts in
802         // the LiveInterval. But as this is only overriding part of the register
803         // adding kill-flags is not correct here after registers have been
804         // assigned.
805         if (!IsFullWrite) {
806           // Next segment has to be adjacent in the subregister write case.
807           LiveRange::const_iterator N = std::next(RI);
808           if (N != LI.end() && N->start == RI->end)
809             goto CancelKill;
810         }
811       }
812 
813       MI->addRegisterKilled(Reg, nullptr);
814       continue;
815 CancelKill:
816       MI->clearRegisterKills(Reg, nullptr);
817     }
818   }
819 }
820 
821 MachineBasicBlock*
822 LiveIntervals::intervalIsInOneMBB(const LiveInterval &LI) const {
823   assert(!LI.empty() && "LiveInterval is empty.");
824 
825   // A local live range must be fully contained inside the block, meaning it is
826   // defined and killed at instructions, not at block boundaries. It is not
827   // live in or out of any block.
828   //
829   // It is technically possible to have a PHI-defined live range identical to a
830   // single block, but we are going to return false in that case.
831 
832   SlotIndex Start = LI.beginIndex();
833   if (Start.isBlock())
834     return nullptr;
835 
836   SlotIndex Stop = LI.endIndex();
837   if (Stop.isBlock())
838     return nullptr;
839 
840   // getMBBFromIndex doesn't need to search the MBB table when both indexes
841   // belong to proper instructions.
842   MachineBasicBlock *MBB1 = Indexes->getMBBFromIndex(Start);
843   MachineBasicBlock *MBB2 = Indexes->getMBBFromIndex(Stop);
844   return MBB1 == MBB2 ? MBB1 : nullptr;
845 }
846 
847 bool
848 LiveIntervals::hasPHIKill(const LiveInterval &LI, const VNInfo *VNI) const {
849   for (const VNInfo *PHI : LI.valnos) {
850     if (PHI->isUnused() || !PHI->isPHIDef())
851       continue;
852     const MachineBasicBlock *PHIMBB = getMBBFromIndex(PHI->def);
853     // Conservatively return true instead of scanning huge predecessor lists.
854     if (PHIMBB->pred_size() > 100)
855       return true;
856     for (const MachineBasicBlock *Pred : PHIMBB->predecessors())
857       if (VNI == LI.getVNInfoBefore(Indexes->getMBBEndIdx(Pred)))
858         return true;
859   }
860   return false;
861 }
862 
863 float LiveIntervals::getSpillWeight(bool isDef, bool isUse,
864                                     const MachineBlockFrequencyInfo *MBFI,
865                                     const MachineInstr &MI) {
866   return getSpillWeight(isDef, isUse, MBFI, MI.getParent());
867 }
868 
869 float LiveIntervals::getSpillWeight(bool isDef, bool isUse,
870                                     const MachineBlockFrequencyInfo *MBFI,
871                                     const MachineBasicBlock *MBB) {
872   return (isDef + isUse) * MBFI->getBlockFreqRelativeToEntryBlock(MBB);
873 }
874 
875 LiveRange::Segment
876 LiveIntervals::addSegmentToEndOfBlock(Register Reg, MachineInstr &startInst) {
877   LiveInterval &Interval = createEmptyInterval(Reg);
878   VNInfo *VN = Interval.getNextValue(
879       SlotIndex(getInstructionIndex(startInst).getRegSlot()),
880       getVNInfoAllocator());
881   LiveRange::Segment S(SlotIndex(getInstructionIndex(startInst).getRegSlot()),
882                        getMBBEndIdx(startInst.getParent()), VN);
883   Interval.addSegment(S);
884 
885   return S;
886 }
887 
888 //===----------------------------------------------------------------------===//
889 //                          Register mask functions
890 //===----------------------------------------------------------------------===//
891 /// Check whether use of reg in MI is live-through. Live-through means that
892 /// the value is alive on exit from Machine instruction. The example of such
893 /// use is a deopt value in statepoint instruction.
894 static bool hasLiveThroughUse(const MachineInstr *MI, Register Reg) {
895   if (MI->getOpcode() != TargetOpcode::STATEPOINT)
896     return false;
897   StatepointOpers SO(MI);
898   if (SO.getFlags() & (uint64_t)StatepointFlags::DeoptLiveIn)
899     return false;
900   for (unsigned Idx = SO.getNumDeoptArgsIdx(), E = SO.getNumGCPtrIdx(); Idx < E;
901        ++Idx) {
902     const MachineOperand &MO = MI->getOperand(Idx);
903     if (MO.isReg() && MO.getReg() == Reg)
904       return true;
905   }
906   return false;
907 }
908 
909 bool LiveIntervals::checkRegMaskInterference(const LiveInterval &LI,
910                                              BitVector &UsableRegs) {
911   if (LI.empty())
912     return false;
913   LiveInterval::const_iterator LiveI = LI.begin(), LiveE = LI.end();
914 
915   // Use a smaller arrays for local live ranges.
916   ArrayRef<SlotIndex> Slots;
917   ArrayRef<const uint32_t*> Bits;
918   if (MachineBasicBlock *MBB = intervalIsInOneMBB(LI)) {
919     Slots = getRegMaskSlotsInBlock(MBB->getNumber());
920     Bits = getRegMaskBitsInBlock(MBB->getNumber());
921   } else {
922     Slots = getRegMaskSlots();
923     Bits = getRegMaskBits();
924   }
925 
926   // We are going to enumerate all the register mask slots contained in LI.
927   // Start with a binary search of RegMaskSlots to find a starting point.
928   ArrayRef<SlotIndex>::iterator SlotI = llvm::lower_bound(Slots, LiveI->start);
929   ArrayRef<SlotIndex>::iterator SlotE = Slots.end();
930 
931   // No slots in range, LI begins after the last call.
932   if (SlotI == SlotE)
933     return false;
934 
935   bool Found = false;
936   // Utility to union regmasks.
937   auto unionBitMask = [&](unsigned Idx) {
938       if (!Found) {
939         // This is the first overlap. Initialize UsableRegs to all ones.
940         UsableRegs.clear();
941         UsableRegs.resize(TRI->getNumRegs(), true);
942         Found = true;
943       }
944       // Remove usable registers clobbered by this mask.
945       UsableRegs.clearBitsNotInMask(Bits[Idx]);
946   };
947   while (true) {
948     assert(*SlotI >= LiveI->start);
949     // Loop over all slots overlapping this segment.
950     while (*SlotI < LiveI->end) {
951       // *SlotI overlaps LI. Collect mask bits.
952       unionBitMask(SlotI - Slots.begin());
953       if (++SlotI == SlotE)
954         return Found;
955     }
956     // If segment ends with live-through use we need to collect its regmask.
957     if (*SlotI == LiveI->end)
958       if (MachineInstr *MI = getInstructionFromIndex(*SlotI))
959         if (hasLiveThroughUse(MI, LI.reg()))
960           unionBitMask(SlotI++ - Slots.begin());
961     // *SlotI is beyond the current LI segment.
962     // Special advance implementation to not miss next LiveI->end.
963     if (++LiveI == LiveE || SlotI == SlotE || *SlotI > LI.endIndex())
964       return Found;
965     while (LiveI->end < *SlotI)
966       ++LiveI;
967     // Advance SlotI until it overlaps.
968     while (*SlotI < LiveI->start)
969       if (++SlotI == SlotE)
970         return Found;
971   }
972 }
973 
974 //===----------------------------------------------------------------------===//
975 //                         IntervalUpdate class.
976 //===----------------------------------------------------------------------===//
977 
978 /// Toolkit used by handleMove to trim or extend live intervals.
979 class LiveIntervals::HMEditor {
980 private:
981   LiveIntervals& LIS;
982   const MachineRegisterInfo& MRI;
983   const TargetRegisterInfo& TRI;
984   SlotIndex OldIdx;
985   SlotIndex NewIdx;
986   SmallPtrSet<LiveRange*, 8> Updated;
987   bool UpdateFlags;
988 
989 public:
990   HMEditor(LiveIntervals& LIS, const MachineRegisterInfo& MRI,
991            const TargetRegisterInfo& TRI,
992            SlotIndex OldIdx, SlotIndex NewIdx, bool UpdateFlags)
993     : LIS(LIS), MRI(MRI), TRI(TRI), OldIdx(OldIdx), NewIdx(NewIdx),
994       UpdateFlags(UpdateFlags) {}
995 
996   // FIXME: UpdateFlags is a workaround that creates live intervals for all
997   // physregs, even those that aren't needed for regalloc, in order to update
998   // kill flags. This is wasteful. Eventually, LiveVariables will strip all kill
999   // flags, and postRA passes will use a live register utility instead.
1000   LiveRange *getRegUnitLI(unsigned Unit) {
1001     if (UpdateFlags && !MRI.isReservedRegUnit(Unit))
1002       return &LIS.getRegUnit(Unit);
1003     return LIS.getCachedRegUnit(Unit);
1004   }
1005 
1006   /// Update all live ranges touched by MI, assuming a move from OldIdx to
1007   /// NewIdx.
1008   void updateAllRanges(MachineInstr *MI) {
1009     LLVM_DEBUG(dbgs() << "handleMove " << OldIdx << " -> " << NewIdx << ": "
1010                       << *MI);
1011     bool hasRegMask = false;
1012     for (MachineOperand &MO : MI->operands()) {
1013       if (MO.isRegMask())
1014         hasRegMask = true;
1015       if (!MO.isReg())
1016         continue;
1017       if (MO.isUse()) {
1018         if (!MO.readsReg())
1019           continue;
1020         // Aggressively clear all kill flags.
1021         // They are reinserted by VirtRegRewriter.
1022         MO.setIsKill(false);
1023       }
1024 
1025       Register Reg = MO.getReg();
1026       if (!Reg)
1027         continue;
1028       if (Register::isVirtualRegister(Reg)) {
1029         LiveInterval &LI = LIS.getInterval(Reg);
1030         if (LI.hasSubRanges()) {
1031           unsigned SubReg = MO.getSubReg();
1032           LaneBitmask LaneMask = SubReg ? TRI.getSubRegIndexLaneMask(SubReg)
1033                                         : MRI.getMaxLaneMaskForVReg(Reg);
1034           for (LiveInterval::SubRange &S : LI.subranges()) {
1035             if ((S.LaneMask & LaneMask).none())
1036               continue;
1037             updateRange(S, Reg, S.LaneMask);
1038           }
1039         }
1040         updateRange(LI, Reg, LaneBitmask::getNone());
1041         // If main range has a hole and we are moving a subrange use across
1042         // the hole updateRange() cannot properly handle it since it only
1043         // gets the LiveRange and not the whole LiveInterval. As a result
1044         // we may end up with a main range not covering all subranges.
1045         // This is extremely rare case, so let's check and reconstruct the
1046         // main range.
1047         if (LI.hasSubRanges()) {
1048           unsigned SubReg = MO.getSubReg();
1049           LaneBitmask LaneMask = SubReg ? TRI.getSubRegIndexLaneMask(SubReg)
1050                                         : MRI.getMaxLaneMaskForVReg(Reg);
1051           for (LiveInterval::SubRange &S : LI.subranges()) {
1052             if ((S.LaneMask & LaneMask).none() || LI.covers(S))
1053               continue;
1054             LI.clear();
1055             LIS.constructMainRangeFromSubranges(LI);
1056             break;
1057           }
1058         }
1059 
1060         continue;
1061       }
1062 
1063       // For physregs, only update the regunits that actually have a
1064       // precomputed live range.
1065       for (MCRegUnitIterator Units(Reg.asMCReg(), &TRI); Units.isValid();
1066            ++Units)
1067         if (LiveRange *LR = getRegUnitLI(*Units))
1068           updateRange(*LR, *Units, LaneBitmask::getNone());
1069     }
1070     if (hasRegMask)
1071       updateRegMaskSlots();
1072   }
1073 
1074 private:
1075   /// Update a single live range, assuming an instruction has been moved from
1076   /// OldIdx to NewIdx.
1077   void updateRange(LiveRange &LR, Register Reg, LaneBitmask LaneMask) {
1078     if (!Updated.insert(&LR).second)
1079       return;
1080     LLVM_DEBUG({
1081       dbgs() << "     ";
1082       if (Register::isVirtualRegister(Reg)) {
1083         dbgs() << printReg(Reg);
1084         if (LaneMask.any())
1085           dbgs() << " L" << PrintLaneMask(LaneMask);
1086       } else {
1087         dbgs() << printRegUnit(Reg, &TRI);
1088       }
1089       dbgs() << ":\t" << LR << '\n';
1090     });
1091     if (SlotIndex::isEarlierInstr(OldIdx, NewIdx))
1092       handleMoveDown(LR);
1093     else
1094       handleMoveUp(LR, Reg, LaneMask);
1095     LLVM_DEBUG(dbgs() << "        -->\t" << LR << '\n');
1096     LR.verify();
1097   }
1098 
1099   /// Update LR to reflect an instruction has been moved downwards from OldIdx
1100   /// to NewIdx (OldIdx < NewIdx).
1101   void handleMoveDown(LiveRange &LR) {
1102     LiveRange::iterator E = LR.end();
1103     // Segment going into OldIdx.
1104     LiveRange::iterator OldIdxIn = LR.find(OldIdx.getBaseIndex());
1105 
1106     // No value live before or after OldIdx? Nothing to do.
1107     if (OldIdxIn == E || SlotIndex::isEarlierInstr(OldIdx, OldIdxIn->start))
1108       return;
1109 
1110     LiveRange::iterator OldIdxOut;
1111     // Do we have a value live-in to OldIdx?
1112     if (SlotIndex::isEarlierInstr(OldIdxIn->start, OldIdx)) {
1113       // If the live-in value already extends to NewIdx, there is nothing to do.
1114       if (SlotIndex::isEarlierEqualInstr(NewIdx, OldIdxIn->end))
1115         return;
1116       // Aggressively remove all kill flags from the old kill point.
1117       // Kill flags shouldn't be used while live intervals exist, they will be
1118       // reinserted by VirtRegRewriter.
1119       if (MachineInstr *KillMI = LIS.getInstructionFromIndex(OldIdxIn->end))
1120         for (MachineOperand &MOP : mi_bundle_ops(*KillMI))
1121           if (MOP.isReg() && MOP.isUse())
1122             MOP.setIsKill(false);
1123 
1124       // Is there a def before NewIdx which is not OldIdx?
1125       LiveRange::iterator Next = std::next(OldIdxIn);
1126       if (Next != E && !SlotIndex::isSameInstr(OldIdx, Next->start) &&
1127           SlotIndex::isEarlierInstr(Next->start, NewIdx)) {
1128         // If we are here then OldIdx was just a use but not a def. We only have
1129         // to ensure liveness extends to NewIdx.
1130         LiveRange::iterator NewIdxIn =
1131           LR.advanceTo(Next, NewIdx.getBaseIndex());
1132         // Extend the segment before NewIdx if necessary.
1133         if (NewIdxIn == E ||
1134             !SlotIndex::isEarlierInstr(NewIdxIn->start, NewIdx)) {
1135           LiveRange::iterator Prev = std::prev(NewIdxIn);
1136           Prev->end = NewIdx.getRegSlot();
1137         }
1138         // Extend OldIdxIn.
1139         OldIdxIn->end = Next->start;
1140         return;
1141       }
1142 
1143       // Adjust OldIdxIn->end to reach NewIdx. This may temporarily make LR
1144       // invalid by overlapping ranges.
1145       bool isKill = SlotIndex::isSameInstr(OldIdx, OldIdxIn->end);
1146       OldIdxIn->end = NewIdx.getRegSlot(OldIdxIn->end.isEarlyClobber());
1147       // If this was not a kill, then there was no def and we're done.
1148       if (!isKill)
1149         return;
1150 
1151       // Did we have a Def at OldIdx?
1152       OldIdxOut = Next;
1153       if (OldIdxOut == E || !SlotIndex::isSameInstr(OldIdx, OldIdxOut->start))
1154         return;
1155     } else {
1156       OldIdxOut = OldIdxIn;
1157     }
1158 
1159     // If we are here then there is a Definition at OldIdx. OldIdxOut points
1160     // to the segment starting there.
1161     assert(OldIdxOut != E && SlotIndex::isSameInstr(OldIdx, OldIdxOut->start) &&
1162            "No def?");
1163     VNInfo *OldIdxVNI = OldIdxOut->valno;
1164     assert(OldIdxVNI->def == OldIdxOut->start && "Inconsistent def");
1165 
1166     // If the defined value extends beyond NewIdx, just move the beginning
1167     // of the segment to NewIdx.
1168     SlotIndex NewIdxDef = NewIdx.getRegSlot(OldIdxOut->start.isEarlyClobber());
1169     if (SlotIndex::isEarlierInstr(NewIdxDef, OldIdxOut->end)) {
1170       OldIdxVNI->def = NewIdxDef;
1171       OldIdxOut->start = OldIdxVNI->def;
1172       return;
1173     }
1174 
1175     // If we are here then we have a Definition at OldIdx which ends before
1176     // NewIdx.
1177 
1178     // Is there an existing Def at NewIdx?
1179     LiveRange::iterator AfterNewIdx
1180       = LR.advanceTo(OldIdxOut, NewIdx.getRegSlot());
1181     bool OldIdxDefIsDead = OldIdxOut->end.isDead();
1182     if (!OldIdxDefIsDead &&
1183         SlotIndex::isEarlierInstr(OldIdxOut->end, NewIdxDef)) {
1184       // OldIdx is not a dead def, and NewIdxDef is inside a new interval.
1185       VNInfo *DefVNI;
1186       if (OldIdxOut != LR.begin() &&
1187           !SlotIndex::isEarlierInstr(std::prev(OldIdxOut)->end,
1188                                      OldIdxOut->start)) {
1189         // There is no gap between OldIdxOut and its predecessor anymore,
1190         // merge them.
1191         LiveRange::iterator IPrev = std::prev(OldIdxOut);
1192         DefVNI = OldIdxVNI;
1193         IPrev->end = OldIdxOut->end;
1194       } else {
1195         // The value is live in to OldIdx
1196         LiveRange::iterator INext = std::next(OldIdxOut);
1197         assert(INext != E && "Must have following segment");
1198         // We merge OldIdxOut and its successor. As we're dealing with subreg
1199         // reordering, there is always a successor to OldIdxOut in the same BB
1200         // We don't need INext->valno anymore and will reuse for the new segment
1201         // we create later.
1202         DefVNI = OldIdxVNI;
1203         INext->start = OldIdxOut->end;
1204         INext->valno->def = INext->start;
1205       }
1206       // If NewIdx is behind the last segment, extend that and append a new one.
1207       if (AfterNewIdx == E) {
1208         // OldIdxOut is undef at this point, Slide (OldIdxOut;AfterNewIdx] up
1209         // one position.
1210         //    |-  ?/OldIdxOut -| |- X0 -| ... |- Xn -| end
1211         // => |- X0/OldIdxOut -| ... |- Xn -| |- undef/NewS -| end
1212         std::copy(std::next(OldIdxOut), E, OldIdxOut);
1213         // The last segment is undefined now, reuse it for a dead def.
1214         LiveRange::iterator NewSegment = std::prev(E);
1215         *NewSegment = LiveRange::Segment(NewIdxDef, NewIdxDef.getDeadSlot(),
1216                                          DefVNI);
1217         DefVNI->def = NewIdxDef;
1218 
1219         LiveRange::iterator Prev = std::prev(NewSegment);
1220         Prev->end = NewIdxDef;
1221       } else {
1222         // OldIdxOut is undef at this point, Slide (OldIdxOut;AfterNewIdx] up
1223         // one position.
1224         //    |-  ?/OldIdxOut -| |- X0 -| ... |- Xn/AfterNewIdx -| |- Next -|
1225         // => |- X0/OldIdxOut -| ... |- Xn -| |- Xn/AfterNewIdx -| |- Next -|
1226         std::copy(std::next(OldIdxOut), std::next(AfterNewIdx), OldIdxOut);
1227         LiveRange::iterator Prev = std::prev(AfterNewIdx);
1228         // We have two cases:
1229         if (SlotIndex::isEarlierInstr(Prev->start, NewIdxDef)) {
1230           // Case 1: NewIdx is inside a liverange. Split this liverange at
1231           // NewIdxDef into the segment "Prev" followed by "NewSegment".
1232           LiveRange::iterator NewSegment = AfterNewIdx;
1233           *NewSegment = LiveRange::Segment(NewIdxDef, Prev->end, Prev->valno);
1234           Prev->valno->def = NewIdxDef;
1235 
1236           *Prev = LiveRange::Segment(Prev->start, NewIdxDef, DefVNI);
1237           DefVNI->def = Prev->start;
1238         } else {
1239           // Case 2: NewIdx is in a lifetime hole. Keep AfterNewIdx as is and
1240           // turn Prev into a segment from NewIdx to AfterNewIdx->start.
1241           *Prev = LiveRange::Segment(NewIdxDef, AfterNewIdx->start, DefVNI);
1242           DefVNI->def = NewIdxDef;
1243           assert(DefVNI != AfterNewIdx->valno);
1244         }
1245       }
1246       return;
1247     }
1248 
1249     if (AfterNewIdx != E &&
1250         SlotIndex::isSameInstr(AfterNewIdx->start, NewIdxDef)) {
1251       // There is an existing def at NewIdx. The def at OldIdx is coalesced into
1252       // that value.
1253       assert(AfterNewIdx->valno != OldIdxVNI && "Multiple defs of value?");
1254       LR.removeValNo(OldIdxVNI);
1255     } else {
1256       // There was no existing def at NewIdx. We need to create a dead def
1257       // at NewIdx. Shift segments over the old OldIdxOut segment, this frees
1258       // a new segment at the place where we want to construct the dead def.
1259       //    |- OldIdxOut -| |- X0 -| ... |- Xn -| |- AfterNewIdx -|
1260       // => |- X0/OldIdxOut -| ... |- Xn -| |- undef/NewS. -| |- AfterNewIdx -|
1261       assert(AfterNewIdx != OldIdxOut && "Inconsistent iterators");
1262       std::copy(std::next(OldIdxOut), AfterNewIdx, OldIdxOut);
1263       // We can reuse OldIdxVNI now.
1264       LiveRange::iterator NewSegment = std::prev(AfterNewIdx);
1265       VNInfo *NewSegmentVNI = OldIdxVNI;
1266       NewSegmentVNI->def = NewIdxDef;
1267       *NewSegment = LiveRange::Segment(NewIdxDef, NewIdxDef.getDeadSlot(),
1268                                        NewSegmentVNI);
1269     }
1270   }
1271 
1272   /// Update LR to reflect an instruction has been moved upwards from OldIdx
1273   /// to NewIdx (NewIdx < OldIdx).
1274   void handleMoveUp(LiveRange &LR, Register Reg, LaneBitmask LaneMask) {
1275     LiveRange::iterator E = LR.end();
1276     // Segment going into OldIdx.
1277     LiveRange::iterator OldIdxIn = LR.find(OldIdx.getBaseIndex());
1278 
1279     // No value live before or after OldIdx? Nothing to do.
1280     if (OldIdxIn == E || SlotIndex::isEarlierInstr(OldIdx, OldIdxIn->start))
1281       return;
1282 
1283     LiveRange::iterator OldIdxOut;
1284     // Do we have a value live-in to OldIdx?
1285     if (SlotIndex::isEarlierInstr(OldIdxIn->start, OldIdx)) {
1286       // If the live-in value isn't killed here, then we have no Def at
1287       // OldIdx, moreover the value must be live at NewIdx so there is nothing
1288       // to do.
1289       bool isKill = SlotIndex::isSameInstr(OldIdx, OldIdxIn->end);
1290       if (!isKill)
1291         return;
1292 
1293       // At this point we have to move OldIdxIn->end back to the nearest
1294       // previous use or (dead-)def but no further than NewIdx.
1295       SlotIndex DefBeforeOldIdx
1296         = std::max(OldIdxIn->start.getDeadSlot(),
1297                    NewIdx.getRegSlot(OldIdxIn->end.isEarlyClobber()));
1298       OldIdxIn->end = findLastUseBefore(DefBeforeOldIdx, Reg, LaneMask);
1299 
1300       // Did we have a Def at OldIdx? If not we are done now.
1301       OldIdxOut = std::next(OldIdxIn);
1302       if (OldIdxOut == E || !SlotIndex::isSameInstr(OldIdx, OldIdxOut->start))
1303         return;
1304     } else {
1305       OldIdxOut = OldIdxIn;
1306       OldIdxIn = OldIdxOut != LR.begin() ? std::prev(OldIdxOut) : E;
1307     }
1308 
1309     // If we are here then there is a Definition at OldIdx. OldIdxOut points
1310     // to the segment starting there.
1311     assert(OldIdxOut != E && SlotIndex::isSameInstr(OldIdx, OldIdxOut->start) &&
1312            "No def?");
1313     VNInfo *OldIdxVNI = OldIdxOut->valno;
1314     assert(OldIdxVNI->def == OldIdxOut->start && "Inconsistent def");
1315     bool OldIdxDefIsDead = OldIdxOut->end.isDead();
1316 
1317     // Is there an existing def at NewIdx?
1318     SlotIndex NewIdxDef = NewIdx.getRegSlot(OldIdxOut->start.isEarlyClobber());
1319     LiveRange::iterator NewIdxOut = LR.find(NewIdx.getRegSlot());
1320     if (SlotIndex::isSameInstr(NewIdxOut->start, NewIdx)) {
1321       assert(NewIdxOut->valno != OldIdxVNI &&
1322              "Same value defined more than once?");
1323       // If OldIdx was a dead def remove it.
1324       if (!OldIdxDefIsDead) {
1325         // Remove segment starting at NewIdx and move begin of OldIdxOut to
1326         // NewIdx so it can take its place.
1327         OldIdxVNI->def = NewIdxDef;
1328         OldIdxOut->start = NewIdxDef;
1329         LR.removeValNo(NewIdxOut->valno);
1330       } else {
1331         // Simply remove the dead def at OldIdx.
1332         LR.removeValNo(OldIdxVNI);
1333       }
1334     } else {
1335       // Previously nothing was live after NewIdx, so all we have to do now is
1336       // move the begin of OldIdxOut to NewIdx.
1337       if (!OldIdxDefIsDead) {
1338         // Do we have any intermediate Defs between OldIdx and NewIdx?
1339         if (OldIdxIn != E &&
1340             SlotIndex::isEarlierInstr(NewIdxDef, OldIdxIn->start)) {
1341           // OldIdx is not a dead def and NewIdx is before predecessor start.
1342           LiveRange::iterator NewIdxIn = NewIdxOut;
1343           assert(NewIdxIn == LR.find(NewIdx.getBaseIndex()));
1344           const SlotIndex SplitPos = NewIdxDef;
1345           OldIdxVNI = OldIdxIn->valno;
1346 
1347           SlotIndex NewDefEndPoint = std::next(NewIdxIn)->end;
1348           LiveRange::iterator Prev = std::prev(OldIdxIn);
1349           if (OldIdxIn != LR.begin() &&
1350               SlotIndex::isEarlierInstr(NewIdx, Prev->end)) {
1351             // If the segment before OldIdx read a value defined earlier than
1352             // NewIdx, the moved instruction also reads and forwards that
1353             // value. Extend the lifetime of the new def point.
1354 
1355             // Extend to where the previous range started, unless there is
1356             // another redef first.
1357             NewDefEndPoint = std::min(OldIdxIn->start,
1358                                       std::next(NewIdxOut)->start);
1359           }
1360 
1361           // Merge the OldIdxIn and OldIdxOut segments into OldIdxOut.
1362           OldIdxOut->valno->def = OldIdxIn->start;
1363           *OldIdxOut = LiveRange::Segment(OldIdxIn->start, OldIdxOut->end,
1364                                           OldIdxOut->valno);
1365           // OldIdxIn and OldIdxVNI are now undef and can be overridden.
1366           // We Slide [NewIdxIn, OldIdxIn) down one position.
1367           //    |- X0/NewIdxIn -| ... |- Xn-1 -||- Xn/OldIdxIn -||- OldIdxOut -|
1368           // => |- undef/NexIdxIn -| |- X0 -| ... |- Xn-1 -| |- Xn/OldIdxOut -|
1369           std::copy_backward(NewIdxIn, OldIdxIn, OldIdxOut);
1370           // NewIdxIn is now considered undef so we can reuse it for the moved
1371           // value.
1372           LiveRange::iterator NewSegment = NewIdxIn;
1373           LiveRange::iterator Next = std::next(NewSegment);
1374           if (SlotIndex::isEarlierInstr(Next->start, NewIdx)) {
1375             // There is no gap between NewSegment and its predecessor.
1376             *NewSegment = LiveRange::Segment(Next->start, SplitPos,
1377                                              Next->valno);
1378 
1379             *Next = LiveRange::Segment(SplitPos, NewDefEndPoint, OldIdxVNI);
1380             Next->valno->def = SplitPos;
1381           } else {
1382             // There is a gap between NewSegment and its predecessor
1383             // Value becomes live in.
1384             *NewSegment = LiveRange::Segment(SplitPos, Next->start, OldIdxVNI);
1385             NewSegment->valno->def = SplitPos;
1386           }
1387         } else {
1388           // Leave the end point of a live def.
1389           OldIdxOut->start = NewIdxDef;
1390           OldIdxVNI->def = NewIdxDef;
1391           if (OldIdxIn != E && SlotIndex::isEarlierInstr(NewIdx, OldIdxIn->end))
1392             OldIdxIn->end = NewIdxDef;
1393         }
1394       } else if (OldIdxIn != E
1395           && SlotIndex::isEarlierInstr(NewIdxOut->start, NewIdx)
1396           && SlotIndex::isEarlierInstr(NewIdx, NewIdxOut->end)) {
1397         // OldIdxVNI is a dead def that has been moved into the middle of
1398         // another value in LR. That can happen when LR is a whole register,
1399         // but the dead def is a write to a subreg that is dead at NewIdx.
1400         // The dead def may have been moved across other values
1401         // in LR, so move OldIdxOut up to NewIdxOut. Slide [NewIdxOut;OldIdxOut)
1402         // down one position.
1403         //    |- X0/NewIdxOut -| ... |- Xn-1 -| |- Xn/OldIdxOut -| |- next - |
1404         // => |- X0/NewIdxOut -| |- X0 -| ... |- Xn-1 -| |- next -|
1405         std::copy_backward(NewIdxOut, OldIdxOut, std::next(OldIdxOut));
1406         // Modify the segment at NewIdxOut and the following segment to meet at
1407         // the point of the dead def, with the following segment getting
1408         // OldIdxVNI as its value number.
1409         *NewIdxOut = LiveRange::Segment(
1410             NewIdxOut->start, NewIdxDef.getRegSlot(), NewIdxOut->valno);
1411         *(NewIdxOut + 1) = LiveRange::Segment(
1412             NewIdxDef.getRegSlot(), (NewIdxOut + 1)->end, OldIdxVNI);
1413         OldIdxVNI->def = NewIdxDef;
1414         // Modify subsequent segments to be defined by the moved def OldIdxVNI.
1415         for (auto *Idx = NewIdxOut + 2; Idx <= OldIdxOut; ++Idx)
1416           Idx->valno = OldIdxVNI;
1417         // Aggressively remove all dead flags from the former dead definition.
1418         // Kill/dead flags shouldn't be used while live intervals exist; they
1419         // will be reinserted by VirtRegRewriter.
1420         if (MachineInstr *KillMI = LIS.getInstructionFromIndex(NewIdx))
1421           for (MIBundleOperands MO(*KillMI); MO.isValid(); ++MO)
1422             if (MO->isReg() && !MO->isUse())
1423               MO->setIsDead(false);
1424       } else {
1425         // OldIdxVNI is a dead def. It may have been moved across other values
1426         // in LR, so move OldIdxOut up to NewIdxOut. Slide [NewIdxOut;OldIdxOut)
1427         // down one position.
1428         //    |- X0/NewIdxOut -| ... |- Xn-1 -| |- Xn/OldIdxOut -| |- next - |
1429         // => |- undef/NewIdxOut -| |- X0 -| ... |- Xn-1 -| |- next -|
1430         std::copy_backward(NewIdxOut, OldIdxOut, std::next(OldIdxOut));
1431         // OldIdxVNI can be reused now to build a new dead def segment.
1432         LiveRange::iterator NewSegment = NewIdxOut;
1433         VNInfo *NewSegmentVNI = OldIdxVNI;
1434         *NewSegment = LiveRange::Segment(NewIdxDef, NewIdxDef.getDeadSlot(),
1435                                          NewSegmentVNI);
1436         NewSegmentVNI->def = NewIdxDef;
1437       }
1438     }
1439   }
1440 
1441   void updateRegMaskSlots() {
1442     SmallVectorImpl<SlotIndex>::iterator RI =
1443         llvm::lower_bound(LIS.RegMaskSlots, OldIdx);
1444     assert(RI != LIS.RegMaskSlots.end() && *RI == OldIdx.getRegSlot() &&
1445            "No RegMask at OldIdx.");
1446     *RI = NewIdx.getRegSlot();
1447     assert((RI == LIS.RegMaskSlots.begin() ||
1448             SlotIndex::isEarlierInstr(*std::prev(RI), *RI)) &&
1449            "Cannot move regmask instruction above another call");
1450     assert((std::next(RI) == LIS.RegMaskSlots.end() ||
1451             SlotIndex::isEarlierInstr(*RI, *std::next(RI))) &&
1452            "Cannot move regmask instruction below another call");
1453   }
1454 
1455   // Return the last use of reg between NewIdx and OldIdx.
1456   SlotIndex findLastUseBefore(SlotIndex Before, Register Reg,
1457                               LaneBitmask LaneMask) {
1458     if (Register::isVirtualRegister(Reg)) {
1459       SlotIndex LastUse = Before;
1460       for (MachineOperand &MO : MRI.use_nodbg_operands(Reg)) {
1461         if (MO.isUndef())
1462           continue;
1463         unsigned SubReg = MO.getSubReg();
1464         if (SubReg != 0 && LaneMask.any()
1465             && (TRI.getSubRegIndexLaneMask(SubReg) & LaneMask).none())
1466           continue;
1467 
1468         const MachineInstr &MI = *MO.getParent();
1469         SlotIndex InstSlot = LIS.getSlotIndexes()->getInstructionIndex(MI);
1470         if (InstSlot > LastUse && InstSlot < OldIdx)
1471           LastUse = InstSlot.getRegSlot();
1472       }
1473       return LastUse;
1474     }
1475 
1476     // This is a regunit interval, so scanning the use list could be very
1477     // expensive. Scan upwards from OldIdx instead.
1478     assert(Before < OldIdx && "Expected upwards move");
1479     SlotIndexes *Indexes = LIS.getSlotIndexes();
1480     MachineBasicBlock *MBB = Indexes->getMBBFromIndex(Before);
1481 
1482     // OldIdx may not correspond to an instruction any longer, so set MII to
1483     // point to the next instruction after OldIdx, or MBB->end().
1484     MachineBasicBlock::iterator MII = MBB->end();
1485     if (MachineInstr *MI = Indexes->getInstructionFromIndex(
1486                            Indexes->getNextNonNullIndex(OldIdx)))
1487       if (MI->getParent() == MBB)
1488         MII = MI;
1489 
1490     MachineBasicBlock::iterator Begin = MBB->begin();
1491     while (MII != Begin) {
1492       if ((--MII)->isDebugOrPseudoInstr())
1493         continue;
1494       SlotIndex Idx = Indexes->getInstructionIndex(*MII);
1495 
1496       // Stop searching when Before is reached.
1497       if (!SlotIndex::isEarlierInstr(Before, Idx))
1498         return Before;
1499 
1500       // Check if MII uses Reg.
1501       for (MIBundleOperands MO(*MII); MO.isValid(); ++MO)
1502         if (MO->isReg() && !MO->isUndef() &&
1503             Register::isPhysicalRegister(MO->getReg()) &&
1504             TRI.hasRegUnit(MO->getReg(), Reg))
1505           return Idx.getRegSlot();
1506     }
1507     // Didn't reach Before. It must be the first instruction in the block.
1508     return Before;
1509   }
1510 };
1511 
1512 void LiveIntervals::handleMove(MachineInstr &MI, bool UpdateFlags) {
1513   // It is fine to move a bundle as a whole, but not an individual instruction
1514   // inside it.
1515   assert((!MI.isBundled() || MI.getOpcode() == TargetOpcode::BUNDLE) &&
1516          "Cannot move instruction in bundle");
1517   SlotIndex OldIndex = Indexes->getInstructionIndex(MI);
1518   Indexes->removeMachineInstrFromMaps(MI);
1519   SlotIndex NewIndex = Indexes->insertMachineInstrInMaps(MI);
1520   assert(getMBBStartIdx(MI.getParent()) <= OldIndex &&
1521          OldIndex < getMBBEndIdx(MI.getParent()) &&
1522          "Cannot handle moves across basic block boundaries.");
1523 
1524   HMEditor HME(*this, *MRI, *TRI, OldIndex, NewIndex, UpdateFlags);
1525   HME.updateAllRanges(&MI);
1526 }
1527 
1528 void LiveIntervals::handleMoveIntoNewBundle(MachineInstr &BundleStart,
1529                                             bool UpdateFlags) {
1530   assert((BundleStart.getOpcode() == TargetOpcode::BUNDLE) &&
1531          "Bundle start is not a bundle");
1532   SmallVector<SlotIndex, 16> ToProcess;
1533   const SlotIndex NewIndex = Indexes->insertMachineInstrInMaps(BundleStart);
1534   auto BundleEnd = getBundleEnd(BundleStart.getIterator());
1535 
1536   auto I = BundleStart.getIterator();
1537   I++;
1538   while (I != BundleEnd) {
1539     if (!Indexes->hasIndex(*I))
1540       continue;
1541     SlotIndex OldIndex = Indexes->getInstructionIndex(*I, true);
1542     ToProcess.push_back(OldIndex);
1543     Indexes->removeMachineInstrFromMaps(*I, true);
1544     I++;
1545   }
1546   for (SlotIndex OldIndex : ToProcess) {
1547     HMEditor HME(*this, *MRI, *TRI, OldIndex, NewIndex, UpdateFlags);
1548     HME.updateAllRanges(&BundleStart);
1549   }
1550 
1551   // Fix up dead defs
1552   const SlotIndex Index = getInstructionIndex(BundleStart);
1553   for (unsigned Idx = 0, E = BundleStart.getNumOperands(); Idx != E; ++Idx) {
1554     MachineOperand &MO = BundleStart.getOperand(Idx);
1555     if (!MO.isReg())
1556       continue;
1557     Register Reg = MO.getReg();
1558     if (Reg.isVirtual() && hasInterval(Reg) && !MO.isUndef()) {
1559       LiveInterval &LI = getInterval(Reg);
1560       LiveQueryResult LRQ = LI.Query(Index);
1561       if (LRQ.isDeadDef())
1562         MO.setIsDead();
1563     }
1564   }
1565 }
1566 
1567 void LiveIntervals::repairOldRegInRange(const MachineBasicBlock::iterator Begin,
1568                                         const MachineBasicBlock::iterator End,
1569                                         const SlotIndex EndIdx, LiveRange &LR,
1570                                         const Register Reg,
1571                                         LaneBitmask LaneMask) {
1572   LiveInterval::iterator LII = LR.find(EndIdx);
1573   SlotIndex lastUseIdx;
1574   if (LII != LR.end() && LII->start < EndIdx) {
1575     lastUseIdx = LII->end;
1576   } else if (LII == LR.begin()) {
1577     // We may not have a liverange at all if this is a subregister untouched
1578     // between \p Begin and \p End.
1579   } else {
1580     --LII;
1581   }
1582 
1583   for (MachineBasicBlock::iterator I = End; I != Begin;) {
1584     --I;
1585     MachineInstr &MI = *I;
1586     if (MI.isDebugOrPseudoInstr())
1587       continue;
1588 
1589     SlotIndex instrIdx = getInstructionIndex(MI);
1590     bool isStartValid = getInstructionFromIndex(LII->start);
1591     bool isEndValid = getInstructionFromIndex(LII->end);
1592 
1593     // FIXME: This doesn't currently handle early-clobber or multiple removed
1594     // defs inside of the region to repair.
1595     for (const MachineOperand &MO : MI.operands()) {
1596       if (!MO.isReg() || MO.getReg() != Reg)
1597         continue;
1598 
1599       unsigned SubReg = MO.getSubReg();
1600       LaneBitmask Mask = TRI->getSubRegIndexLaneMask(SubReg);
1601       if ((Mask & LaneMask).none())
1602         continue;
1603 
1604       if (MO.isDef()) {
1605         if (!isStartValid) {
1606           if (LII->end.isDead()) {
1607             LII = LR.removeSegment(LII, true);
1608             if (LII != LR.begin())
1609               --LII;
1610           } else {
1611             LII->start = instrIdx.getRegSlot();
1612             LII->valno->def = instrIdx.getRegSlot();
1613             if (MO.getSubReg() && !MO.isUndef())
1614               lastUseIdx = instrIdx.getRegSlot();
1615             else
1616               lastUseIdx = SlotIndex();
1617             continue;
1618           }
1619         }
1620 
1621         if (!lastUseIdx.isValid()) {
1622           VNInfo *VNI = LR.getNextValue(instrIdx.getRegSlot(), VNInfoAllocator);
1623           LiveRange::Segment S(instrIdx.getRegSlot(),
1624                                instrIdx.getDeadSlot(), VNI);
1625           LII = LR.addSegment(S);
1626         } else if (LII->start != instrIdx.getRegSlot()) {
1627           VNInfo *VNI = LR.getNextValue(instrIdx.getRegSlot(), VNInfoAllocator);
1628           LiveRange::Segment S(instrIdx.getRegSlot(), lastUseIdx, VNI);
1629           LII = LR.addSegment(S);
1630         }
1631 
1632         if (MO.getSubReg() && !MO.isUndef())
1633           lastUseIdx = instrIdx.getRegSlot();
1634         else
1635           lastUseIdx = SlotIndex();
1636       } else if (MO.isUse()) {
1637         // FIXME: This should probably be handled outside of this branch,
1638         // either as part of the def case (for defs inside of the region) or
1639         // after the loop over the region.
1640         if (!isEndValid && !LII->end.isBlock())
1641           LII->end = instrIdx.getRegSlot();
1642         if (!lastUseIdx.isValid())
1643           lastUseIdx = instrIdx.getRegSlot();
1644       }
1645     }
1646   }
1647 
1648   bool isStartValid = getInstructionFromIndex(LII->start);
1649   if (!isStartValid && LII->end.isDead())
1650     LR.removeSegment(*LII, true);
1651 }
1652 
1653 void
1654 LiveIntervals::repairIntervalsInRange(MachineBasicBlock *MBB,
1655                                       MachineBasicBlock::iterator Begin,
1656                                       MachineBasicBlock::iterator End,
1657                                       ArrayRef<Register> OrigRegs) {
1658   // Find anchor points, which are at the beginning/end of blocks or at
1659   // instructions that already have indexes.
1660   while (Begin != MBB->begin() && !Indexes->hasIndex(*std::prev(Begin)))
1661     --Begin;
1662   while (End != MBB->end() && !Indexes->hasIndex(*End))
1663     ++End;
1664 
1665   SlotIndex EndIdx;
1666   if (End == MBB->end())
1667     EndIdx = getMBBEndIdx(MBB).getPrevSlot();
1668   else
1669     EndIdx = getInstructionIndex(*End);
1670 
1671   Indexes->repairIndexesInRange(MBB, Begin, End);
1672 
1673   // Make sure a live interval exists for all register operands in the range.
1674   SmallVector<Register> RegsToRepair(OrigRegs.begin(), OrigRegs.end());
1675   for (MachineBasicBlock::iterator I = End; I != Begin;) {
1676     --I;
1677     MachineInstr &MI = *I;
1678     if (MI.isDebugOrPseudoInstr())
1679       continue;
1680     for (const MachineOperand &MO : MI.operands()) {
1681       if (MO.isReg() && MO.getReg().isVirtual()) {
1682         Register Reg = MO.getReg();
1683         // If the new instructions refer to subregs but the old instructions did
1684         // not, throw away any old live interval so it will be recomputed with
1685         // subranges.
1686         if (MO.getSubReg() && hasInterval(Reg) &&
1687             !getInterval(Reg).hasSubRanges() &&
1688             MRI->shouldTrackSubRegLiveness(Reg))
1689           removeInterval(Reg);
1690         if (!hasInterval(Reg)) {
1691           createAndComputeVirtRegInterval(Reg);
1692           // Don't bother to repair a freshly calculated live interval.
1693           erase_value(RegsToRepair, Reg);
1694         }
1695       }
1696     }
1697   }
1698 
1699   for (Register Reg : RegsToRepair) {
1700     if (!Reg.isVirtual())
1701       continue;
1702 
1703     LiveInterval &LI = getInterval(Reg);
1704     // FIXME: Should we support undefs that gain defs?
1705     if (!LI.hasAtLeastOneValue())
1706       continue;
1707 
1708     for (LiveInterval::SubRange &S : LI.subranges())
1709       repairOldRegInRange(Begin, End, EndIdx, S, Reg, S.LaneMask);
1710     LI.removeEmptySubRanges();
1711 
1712     repairOldRegInRange(Begin, End, EndIdx, LI, Reg);
1713   }
1714 }
1715 
1716 void LiveIntervals::removePhysRegDefAt(MCRegister Reg, SlotIndex Pos) {
1717   for (MCRegUnitIterator Unit(Reg, TRI); Unit.isValid(); ++Unit) {
1718     if (LiveRange *LR = getCachedRegUnit(*Unit))
1719       if (VNInfo *VNI = LR->getVNInfoAt(Pos))
1720         LR->removeValNo(VNI);
1721   }
1722 }
1723 
1724 void LiveIntervals::removeVRegDefAt(LiveInterval &LI, SlotIndex Pos) {
1725   // LI may not have the main range computed yet, but its subranges may
1726   // be present.
1727   VNInfo *VNI = LI.getVNInfoAt(Pos);
1728   if (VNI != nullptr) {
1729     assert(VNI->def.getBaseIndex() == Pos.getBaseIndex());
1730     LI.removeValNo(VNI);
1731   }
1732 
1733   // Also remove the value defined in subranges.
1734   for (LiveInterval::SubRange &S : LI.subranges()) {
1735     if (VNInfo *SVNI = S.getVNInfoAt(Pos))
1736       if (SVNI->def.getBaseIndex() == Pos.getBaseIndex())
1737         S.removeValNo(SVNI);
1738   }
1739   LI.removeEmptySubRanges();
1740 }
1741 
1742 void LiveIntervals::splitSeparateComponents(LiveInterval &LI,
1743     SmallVectorImpl<LiveInterval*> &SplitLIs) {
1744   ConnectedVNInfoEqClasses ConEQ(*this);
1745   unsigned NumComp = ConEQ.Classify(LI);
1746   if (NumComp <= 1)
1747     return;
1748   LLVM_DEBUG(dbgs() << "  Split " << NumComp << " components: " << LI << '\n');
1749   Register Reg = LI.reg();
1750   const TargetRegisterClass *RegClass = MRI->getRegClass(Reg);
1751   for (unsigned I = 1; I < NumComp; ++I) {
1752     Register NewVReg = MRI->createVirtualRegister(RegClass);
1753     LiveInterval &NewLI = createEmptyInterval(NewVReg);
1754     SplitLIs.push_back(&NewLI);
1755   }
1756   ConEQ.Distribute(LI, SplitLIs.data(), *MRI);
1757 }
1758 
1759 void LiveIntervals::constructMainRangeFromSubranges(LiveInterval &LI) {
1760   assert(LICalc && "LICalc not initialized.");
1761   LICalc->reset(MF, getSlotIndexes(), DomTree, &getVNInfoAllocator());
1762   LICalc->constructMainRangeFromSubranges(LI);
1763 }
1764