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