[IndVars] Extract out eliminateIdentitySCEV, NFC
[oota-llvm.git] / lib / CodeGen / LiveIntervalAnalysis.cpp
1 //===-- LiveIntervalAnalysis.cpp - Live Interval Analysis -----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the LiveInterval analysis pass which is used
11 // by the Linear Scan Register allocator. This pass linearizes the
12 // basic blocks of the function in DFS order and uses the
13 // LiveVariables pass to conservatively compute live intervals for
14 // each virtual and physical register.
15 //
16 //===----------------------------------------------------------------------===//
17
18 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
19 #include "LiveRangeCalc.h"
20 #include "llvm/ADT/DenseSet.h"
21 #include "llvm/ADT/STLExtras.h"
22 #include "llvm/Analysis/AliasAnalysis.h"
23 #include "llvm/CodeGen/LiveVariables.h"
24 #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
25 #include "llvm/CodeGen/MachineDominators.h"
26 #include "llvm/CodeGen/MachineInstr.h"
27 #include "llvm/CodeGen/MachineRegisterInfo.h"
28 #include "llvm/CodeGen/Passes.h"
29 #include "llvm/CodeGen/VirtRegMap.h"
30 #include "llvm/IR/Value.h"
31 #include "llvm/Support/BlockFrequency.h"
32 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/ErrorHandling.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include "llvm/Target/TargetInstrInfo.h"
37 #include "llvm/Target/TargetRegisterInfo.h"
38 #include "llvm/Target/TargetSubtargetInfo.h"
39 #include <algorithm>
40 #include <cmath>
41 #include <limits>
42 using namespace llvm;
43
44 #define DEBUG_TYPE "regalloc"
45
46 char LiveIntervals::ID = 0;
47 char &llvm::LiveIntervalsID = LiveIntervals::ID;
48 INITIALIZE_PASS_BEGIN(LiveIntervals, "liveintervals",
49                 "Live Interval Analysis", false, false)
50 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
51 INITIALIZE_PASS_DEPENDENCY(LiveVariables)
52 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
53 INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
54 INITIALIZE_PASS_END(LiveIntervals, "liveintervals",
55                 "Live Interval Analysis", false, false)
56
57 #ifndef NDEBUG
58 static cl::opt<bool> EnablePrecomputePhysRegs(
59   "precompute-phys-liveness", cl::Hidden,
60   cl::desc("Eagerly compute live intervals for all physreg units."));
61 #else
62 static bool EnablePrecomputePhysRegs = false;
63 #endif // NDEBUG
64
65 static cl::opt<bool> EnableSubRegLiveness(
66   "enable-subreg-liveness", cl::Hidden, cl::init(true),
67   cl::desc("Enable subregister liveness tracking."));
68
69 namespace llvm {
70 cl::opt<bool> UseSegmentSetForPhysRegs(
71     "use-segment-set-for-physregs", cl::Hidden, cl::init(true),
72     cl::desc(
73         "Use segment set for the computation of the live ranges of physregs."));
74 }
75
76 void LiveIntervals::getAnalysisUsage(AnalysisUsage &AU) const {
77   AU.setPreservesCFG();
78   AU.addRequired<AAResultsWrapperPass>();
79   AU.addPreserved<AAResultsWrapperPass>();
80   // LiveVariables isn't really required by this analysis, it is only required
81   // here to make sure it is live during TwoAddressInstructionPass and
82   // PHIElimination. This is temporary.
83   AU.addRequired<LiveVariables>();
84   AU.addPreserved<LiveVariables>();
85   AU.addPreservedID(MachineLoopInfoID);
86   AU.addRequiredTransitiveID(MachineDominatorsID);
87   AU.addPreservedID(MachineDominatorsID);
88   AU.addPreserved<SlotIndexes>();
89   AU.addRequiredTransitive<SlotIndexes>();
90   MachineFunctionPass::getAnalysisUsage(AU);
91 }
92
93 LiveIntervals::LiveIntervals() : MachineFunctionPass(ID),
94   DomTree(nullptr), LRCalc(nullptr) {
95   initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
96 }
97
98 LiveIntervals::~LiveIntervals() {
99   delete LRCalc;
100 }
101
102 void LiveIntervals::releaseMemory() {
103   // Free the live intervals themselves.
104   for (unsigned i = 0, e = VirtRegIntervals.size(); i != e; ++i)
105     delete VirtRegIntervals[TargetRegisterInfo::index2VirtReg(i)];
106   VirtRegIntervals.clear();
107   RegMaskSlots.clear();
108   RegMaskBits.clear();
109   RegMaskBlocks.clear();
110
111   for (unsigned i = 0, e = RegUnitRanges.size(); i != e; ++i)
112     delete RegUnitRanges[i];
113   RegUnitRanges.clear();
114
115   // Release VNInfo memory regions, VNInfo objects don't need to be dtor'd.
116   VNInfoAllocator.Reset();
117 }
118
119 /// runOnMachineFunction - calculates LiveIntervals
120 ///
121 bool LiveIntervals::runOnMachineFunction(MachineFunction &fn) {
122   MF = &fn;
123   MRI = &MF->getRegInfo();
124   TRI = MF->getSubtarget().getRegisterInfo();
125   TII = MF->getSubtarget().getInstrInfo();
126   AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
127   Indexes = &getAnalysis<SlotIndexes>();
128   DomTree = &getAnalysis<MachineDominatorTree>();
129
130   if (EnableSubRegLiveness && MF->getSubtarget().enableSubRegLiveness())
131     MRI->enableSubRegLiveness(true);
132
133   if (!LRCalc)
134     LRCalc = new LiveRangeCalc();
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   DEBUG(dump());
150   return true;
151 }
152
153 /// print - Implement the dump method.
154 void LiveIntervals::print(raw_ostream &OS, const Module* ) const {
155   OS << "********** INTERVALS **********\n";
156
157   // Dump the regunits.
158   for (unsigned i = 0, e = RegUnitRanges.size(); i != e; ++i)
159     if (LiveRange *LR = RegUnitRanges[i])
160       OS << PrintRegUnit(i, TRI) << ' ' << *LR << '\n';
161
162   // Dump the virtregs.
163   for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
164     unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
165     if (hasInterval(Reg))
166       OS << getInterval(Reg) << '\n';
167   }
168
169   OS << "RegMasks:";
170   for (unsigned i = 0, e = RegMaskSlots.size(); i != e; ++i)
171     OS << ' ' << RegMaskSlots[i];
172   OS << '\n';
173
174   printInstrs(OS);
175 }
176
177 void LiveIntervals::printInstrs(raw_ostream &OS) const {
178   OS << "********** MACHINEINSTRS **********\n";
179   MF->print(OS, Indexes);
180 }
181
182 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
183 void LiveIntervals::dumpInstrs() const {
184   printInstrs(dbgs());
185 }
186 #endif
187
188 LiveInterval* LiveIntervals::createInterval(unsigned reg) {
189   float Weight = TargetRegisterInfo::isPhysicalRegister(reg) ?
190                   llvm::huge_valf : 0.0F;
191   return new LiveInterval(reg, Weight);
192 }
193
194
195 /// computeVirtRegInterval - Compute the live interval of a virtual register,
196 /// based on defs and uses.
197 void LiveIntervals::computeVirtRegInterval(LiveInterval &LI) {
198   assert(LRCalc && "LRCalc not initialized.");
199   assert(LI.empty() && "Should only compute empty intervals.");
200   bool ShouldTrackSubRegLiveness = MRI->shouldTrackSubRegLiveness(LI.reg);
201   LRCalc->reset(MF, getSlotIndexes(), DomTree, &getVNInfoAllocator());
202   LRCalc->calculate(LI, ShouldTrackSubRegLiveness);
203   bool SeparatedComponents = computeDeadValues(LI, nullptr);
204   if (SeparatedComponents) {
205     assert(ShouldTrackSubRegLiveness
206            && "Separated components should only occur for unused subreg defs");
207     SmallVector<LiveInterval*, 8> SplitLIs;
208     splitSeparateComponents(LI, SplitLIs);
209   }
210 }
211
212 void LiveIntervals::computeVirtRegs() {
213   for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
214     unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
215     if (MRI->reg_nodbg_empty(Reg))
216       continue;
217     createAndComputeVirtRegInterval(Reg);
218   }
219 }
220
221 void LiveIntervals::computeRegMasks() {
222   RegMaskBlocks.resize(MF->getNumBlockIDs());
223
224   // Find all instructions with regmask operands.
225   for (MachineFunction::iterator MBBI = MF->begin(), E = MF->end();
226        MBBI != E; ++MBBI) {
227     MachineBasicBlock *MBB = MBBI;
228     std::pair<unsigned, unsigned> &RMB = RegMaskBlocks[MBB->getNumber()];
229     RMB.first = RegMaskSlots.size();
230     for (MachineBasicBlock::iterator MI = MBB->begin(), ME = MBB->end();
231          MI != ME; ++MI)
232       for (const MachineOperand &MO : MI->operands()) {
233         if (!MO.isRegMask())
234           continue;
235           RegMaskSlots.push_back(Indexes->getInstructionIndex(MI).getRegSlot());
236           RegMaskBits.push_back(MO.getRegMask());
237       }
238     // Compute the number of register mask instructions in this block.
239     RMB.second = RegMaskSlots.size() - RMB.first;
240   }
241 }
242
243 //===----------------------------------------------------------------------===//
244 //                           Register Unit Liveness
245 //===----------------------------------------------------------------------===//
246 //
247 // Fixed interference typically comes from ABI boundaries: Function arguments
248 // and return values are passed in fixed registers, and so are exception
249 // pointers entering landing pads. Certain instructions require values to be
250 // present in specific registers. That is also represented through fixed
251 // interference.
252 //
253
254 /// computeRegUnitInterval - Compute the live range of a register unit, based
255 /// on the uses and defs of aliasing registers.  The range should be empty,
256 /// or contain only dead phi-defs from ABI blocks.
257 void LiveIntervals::computeRegUnitRange(LiveRange &LR, unsigned Unit) {
258   assert(LRCalc && "LRCalc not initialized.");
259   LRCalc->reset(MF, getSlotIndexes(), DomTree, &getVNInfoAllocator());
260
261   // The physregs aliasing Unit are the roots and their super-registers.
262   // Create all values as dead defs before extending to uses. Note that roots
263   // may share super-registers. That's OK because createDeadDefs() is
264   // idempotent. It is very rare for a register unit to have multiple roots, so
265   // uniquing super-registers is probably not worthwhile.
266   for (MCRegUnitRootIterator Roots(Unit, TRI); Roots.isValid(); ++Roots) {
267     for (MCSuperRegIterator Supers(*Roots, TRI, /*IncludeSelf=*/true);
268          Supers.isValid(); ++Supers) {
269       if (!MRI->reg_empty(*Supers))
270         LRCalc->createDeadDefs(LR, *Supers);
271     }
272   }
273
274   // Now extend LR to reach all uses.
275   // Ignore uses of reserved registers. We only track defs of those.
276   for (MCRegUnitRootIterator Roots(Unit, TRI); Roots.isValid(); ++Roots) {
277     for (MCSuperRegIterator Supers(*Roots, TRI, /*IncludeSelf=*/true);
278          Supers.isValid(); ++Supers) {
279       unsigned Reg = *Supers;
280       if (!MRI->isReserved(Reg) && !MRI->reg_empty(Reg))
281         LRCalc->extendToUses(LR, Reg);
282     }
283   }
284
285   // Flush the segment set to the segment vector.
286   if (UseSegmentSetForPhysRegs)
287     LR.flushSegmentSet();
288 }
289
290
291 /// computeLiveInRegUnits - Precompute the live ranges of any register units
292 /// that are live-in to an ABI block somewhere. Register values can appear
293 /// without a corresponding def when entering the entry block or a landing pad.
294 ///
295 void LiveIntervals::computeLiveInRegUnits() {
296   RegUnitRanges.resize(TRI->getNumRegUnits());
297   DEBUG(dbgs() << "Computing live-in reg-units in ABI blocks.\n");
298
299   // Keep track of the live range sets allocated.
300   SmallVector<unsigned, 8> NewRanges;
301
302   // Check all basic blocks for live-ins.
303   for (MachineFunction::const_iterator MFI = MF->begin(), MFE = MF->end();
304        MFI != MFE; ++MFI) {
305     const MachineBasicBlock *MBB = MFI;
306
307     // We only care about ABI blocks: Entry + landing pads.
308     if ((MFI != MF->begin() && !MBB->isEHPad()) || MBB->livein_empty())
309       continue;
310
311     // Create phi-defs at Begin for all live-in registers.
312     SlotIndex Begin = Indexes->getMBBStartIdx(MBB);
313     DEBUG(dbgs() << Begin << "\tBB#" << MBB->getNumber());
314     for (const auto &LI : MBB->liveins()) {
315       for (MCRegUnitIterator Units(LI.PhysReg, TRI); Units.isValid(); ++Units) {
316         unsigned Unit = *Units;
317         LiveRange *LR = RegUnitRanges[Unit];
318         if (!LR) {
319           // Use segment set to speed-up initial computation of the live range.
320           LR = RegUnitRanges[Unit] = new LiveRange(UseSegmentSetForPhysRegs);
321           NewRanges.push_back(Unit);
322         }
323         VNInfo *VNI = LR->createDeadDef(Begin, getVNInfoAllocator());
324         (void)VNI;
325         DEBUG(dbgs() << ' ' << PrintRegUnit(Unit, TRI) << '#' << VNI->id);
326       }
327     }
328     DEBUG(dbgs() << '\n');
329   }
330   DEBUG(dbgs() << "Created " << NewRanges.size() << " new intervals.\n");
331
332   // Compute the 'normal' part of the ranges.
333   for (unsigned i = 0, e = NewRanges.size(); i != e; ++i) {
334     unsigned Unit = NewRanges[i];
335     computeRegUnitRange(*RegUnitRanges[Unit], Unit);
336   }
337 }
338
339
340 static void createSegmentsForValues(LiveRange &LR,
341       iterator_range<LiveInterval::vni_iterator> VNIs) {
342   for (auto VNI : VNIs) {
343     if (VNI->isUnused())
344       continue;
345     SlotIndex Def = VNI->def;
346     LR.addSegment(LiveRange::Segment(Def, Def.getDeadSlot(), VNI));
347   }
348 }
349
350 typedef SmallVector<std::pair<SlotIndex, VNInfo*>, 16> ShrinkToUsesWorkList;
351
352 static void extendSegmentsToUses(LiveRange &LR, const SlotIndexes &Indexes,
353                                  ShrinkToUsesWorkList &WorkList,
354                                  const LiveRange &OldRange) {
355   // Keep track of the PHIs that are in use.
356   SmallPtrSet<VNInfo*, 8> UsedPHIs;
357   // Blocks that have already been added to WorkList as live-out.
358   SmallPtrSet<MachineBasicBlock*, 16> LiveOut;
359
360   // Extend intervals to reach all uses in WorkList.
361   while (!WorkList.empty()) {
362     SlotIndex Idx = WorkList.back().first;
363     VNInfo *VNI = WorkList.back().second;
364     WorkList.pop_back();
365     const MachineBasicBlock *MBB = Indexes.getMBBFromIndex(Idx.getPrevSlot());
366     SlotIndex BlockStart = Indexes.getMBBStartIdx(MBB);
367
368     // Extend the live range for VNI to be live at Idx.
369     if (VNInfo *ExtVNI = LR.extendInBlock(BlockStart, Idx)) {
370       assert(ExtVNI == VNI && "Unexpected existing value number");
371       (void)ExtVNI;
372       // Is this a PHIDef we haven't seen before?
373       if (!VNI->isPHIDef() || VNI->def != BlockStart ||
374           !UsedPHIs.insert(VNI).second)
375         continue;
376       // The PHI is live, make sure the predecessors are live-out.
377       for (auto &Pred : MBB->predecessors()) {
378         if (!LiveOut.insert(Pred).second)
379           continue;
380         SlotIndex Stop = Indexes.getMBBEndIdx(Pred);
381         // A predecessor is not required to have a live-out value for a PHI.
382         if (VNInfo *PVNI = OldRange.getVNInfoBefore(Stop))
383           WorkList.push_back(std::make_pair(Stop, PVNI));
384       }
385       continue;
386     }
387
388     // VNI is live-in to MBB.
389     DEBUG(dbgs() << " live-in at " << BlockStart << '\n');
390     LR.addSegment(LiveRange::Segment(BlockStart, Idx, VNI));
391
392     // Make sure VNI is live-out from the predecessors.
393     for (auto &Pred : MBB->predecessors()) {
394       if (!LiveOut.insert(Pred).second)
395         continue;
396       SlotIndex Stop = Indexes.getMBBEndIdx(Pred);
397       assert(OldRange.getVNInfoBefore(Stop) == VNI &&
398              "Wrong value out of predecessor");
399       WorkList.push_back(std::make_pair(Stop, VNI));
400     }
401   }
402 }
403
404 bool LiveIntervals::shrinkToUses(LiveInterval *li,
405                                  SmallVectorImpl<MachineInstr*> *dead) {
406   DEBUG(dbgs() << "Shrink: " << *li << '\n');
407   assert(TargetRegisterInfo::isVirtualRegister(li->reg)
408          && "Can only shrink virtual registers");
409
410   // Shrink subregister live ranges.
411   bool NeedsCleanup = false;
412   for (LiveInterval::SubRange &S : li->subranges()) {
413     shrinkToUses(S, li->reg);
414     if (S.empty())
415       NeedsCleanup = true;
416   }
417   if (NeedsCleanup)
418     li->removeEmptySubRanges();
419
420   // Find all the values used, including PHI kills.
421   ShrinkToUsesWorkList WorkList;
422
423   // Visit all instructions reading li->reg.
424   for (MachineRegisterInfo::reg_instr_iterator
425        I = MRI->reg_instr_begin(li->reg), E = MRI->reg_instr_end();
426        I != E; ) {
427     MachineInstr *UseMI = &*(I++);
428     if (UseMI->isDebugValue() || !UseMI->readsVirtualRegister(li->reg))
429       continue;
430     SlotIndex Idx = getInstructionIndex(UseMI).getRegSlot();
431     LiveQueryResult LRQ = li->Query(Idx);
432     VNInfo *VNI = LRQ.valueIn();
433     if (!VNI) {
434       // This shouldn't happen: readsVirtualRegister returns true, but there is
435       // no live value. It is likely caused by a target getting <undef> flags
436       // wrong.
437       DEBUG(dbgs() << Idx << '\t' << *UseMI
438                    << "Warning: Instr claims to read non-existent value in "
439                     << *li << '\n');
440       continue;
441     }
442     // Special case: An early-clobber tied operand reads and writes the
443     // register one slot early.
444     if (VNInfo *DefVNI = LRQ.valueDefined())
445       Idx = DefVNI->def;
446
447     WorkList.push_back(std::make_pair(Idx, VNI));
448   }
449
450   // Create new live ranges with only minimal live segments per def.
451   LiveRange NewLR;
452   createSegmentsForValues(NewLR, make_range(li->vni_begin(), li->vni_end()));
453   extendSegmentsToUses(NewLR, *Indexes, WorkList, *li);
454
455   // Move the trimmed segments back.
456   li->segments.swap(NewLR.segments);
457
458   // Handle dead values.
459   bool CanSeparate = computeDeadValues(*li, dead);
460   DEBUG(dbgs() << "Shrunk: " << *li << '\n');
461   return CanSeparate;
462 }
463
464 bool LiveIntervals::computeDeadValues(LiveInterval &LI,
465                                       SmallVectorImpl<MachineInstr*> *dead) {
466   bool MayHaveSplitComponents = false;
467   for (auto VNI : LI.valnos) {
468     if (VNI->isUnused())
469       continue;
470     SlotIndex Def = VNI->def;
471     LiveRange::iterator I = LI.FindSegmentContaining(Def);
472     assert(I != LI.end() && "Missing segment for VNI");
473
474     // Is the register live before? Otherwise we may have to add a read-undef
475     // flag for subregister defs.
476     bool DeadBeforeDef = false;
477     unsigned VReg = LI.reg;
478     if (MRI->shouldTrackSubRegLiveness(VReg)) {
479       if ((I == LI.begin() || std::prev(I)->end < Def) && !VNI->isPHIDef()) {
480         MachineInstr *MI = getInstructionFromIndex(Def);
481         MI->addRegisterDefReadUndef(VReg);
482         DeadBeforeDef = true;
483       }
484     }
485
486     if (I->end != Def.getDeadSlot())
487       continue;
488     if (VNI->isPHIDef()) {
489       // This is a dead PHI. Remove it.
490       VNI->markUnused();
491       LI.removeSegment(I);
492       DEBUG(dbgs() << "Dead PHI at " << Def << " may separate interval\n");
493       MayHaveSplitComponents = true;
494     } else {
495       // This is a dead def. Make sure the instruction knows.
496       MachineInstr *MI = getInstructionFromIndex(Def);
497       assert(MI && "No instruction defining live value");
498       MI->addRegisterDead(VReg, TRI);
499
500       // If we have a dead def that is completely separate from the rest of
501       // the liverange then we rewrite it to use a different VReg to not violate
502       // the rule that the liveness of a virtual register forms a connected
503       // component. This should only happen if subregister liveness is tracked.
504       if (DeadBeforeDef)
505         MayHaveSplitComponents = true;
506
507       if (dead && MI->allDefsAreDead()) {
508         DEBUG(dbgs() << "All defs dead: " << Def << '\t' << *MI);
509         dead->push_back(MI);
510       }
511     }
512   }
513   return MayHaveSplitComponents;
514 }
515
516 void LiveIntervals::shrinkToUses(LiveInterval::SubRange &SR, unsigned Reg)
517 {
518   DEBUG(dbgs() << "Shrink: " << SR << '\n');
519   assert(TargetRegisterInfo::isVirtualRegister(Reg)
520          && "Can only shrink virtual registers");
521   // Find all the values used, including PHI kills.
522   ShrinkToUsesWorkList WorkList;
523
524   // Visit all instructions reading Reg.
525   SlotIndex LastIdx;
526   for (MachineOperand &MO : MRI->reg_operands(Reg)) {
527     MachineInstr *UseMI = MO.getParent();
528     if (UseMI->isDebugValue())
529       continue;
530     // Maybe the operand is for a subregister we don't care about.
531     unsigned SubReg = MO.getSubReg();
532     if (SubReg != 0) {
533       LaneBitmask LaneMask = TRI->getSubRegIndexLaneMask(SubReg);
534       if ((LaneMask & SR.LaneMask) == 0)
535         continue;
536     }
537     // We only need to visit each instruction once.
538     SlotIndex Idx = getInstructionIndex(UseMI).getRegSlot();
539     if (Idx == LastIdx)
540       continue;
541     LastIdx = Idx;
542
543     LiveQueryResult LRQ = SR.Query(Idx);
544     VNInfo *VNI = LRQ.valueIn();
545     // For Subranges it is possible that only undef values are left in that
546     // part of the subregister, so there is no real liverange at the use
547     if (!VNI)
548       continue;
549
550     // Special case: An early-clobber tied operand reads and writes the
551     // register one slot early.
552     if (VNInfo *DefVNI = LRQ.valueDefined())
553       Idx = DefVNI->def;
554
555     WorkList.push_back(std::make_pair(Idx, VNI));
556   }
557
558   // Create a new live ranges with only minimal live segments per def.
559   LiveRange NewLR;
560   createSegmentsForValues(NewLR, make_range(SR.vni_begin(), SR.vni_end()));
561   extendSegmentsToUses(NewLR, *Indexes, WorkList, SR);
562
563   // Move the trimmed ranges back.
564   SR.segments.swap(NewLR.segments);
565
566   // Remove dead PHI value numbers
567   for (auto VNI : SR.valnos) {
568     if (VNI->isUnused())
569       continue;
570     const LiveRange::Segment *Segment = SR.getSegmentContaining(VNI->def);
571     assert(Segment != nullptr && "Missing segment for VNI");
572     if (Segment->end != VNI->def.getDeadSlot())
573       continue;
574     if (VNI->isPHIDef()) {
575       // This is a dead PHI. Remove it.
576       VNI->markUnused();
577       SR.removeSegment(*Segment);
578       DEBUG(dbgs() << "Dead PHI at " << VNI->def << " may separate interval\n");
579     }
580   }
581
582   DEBUG(dbgs() << "Shrunk: " << SR << '\n');
583 }
584
585 void LiveIntervals::extendToIndices(LiveRange &LR,
586                                     ArrayRef<SlotIndex> Indices) {
587   assert(LRCalc && "LRCalc not initialized.");
588   LRCalc->reset(MF, getSlotIndexes(), DomTree, &getVNInfoAllocator());
589   for (unsigned i = 0, e = Indices.size(); i != e; ++i)
590     LRCalc->extend(LR, Indices[i]);
591 }
592
593 void LiveIntervals::pruneValue(LiveRange &LR, SlotIndex Kill,
594                                SmallVectorImpl<SlotIndex> *EndPoints) {
595   LiveQueryResult LRQ = LR.Query(Kill);
596   VNInfo *VNI = LRQ.valueOutOrDead();
597   if (!VNI)
598     return;
599
600   MachineBasicBlock *KillMBB = Indexes->getMBBFromIndex(Kill);
601   SlotIndex MBBEnd = Indexes->getMBBEndIdx(KillMBB);
602
603   // If VNI isn't live out from KillMBB, the value is trivially pruned.
604   if (LRQ.endPoint() < MBBEnd) {
605     LR.removeSegment(Kill, LRQ.endPoint());
606     if (EndPoints) EndPoints->push_back(LRQ.endPoint());
607     return;
608   }
609
610   // VNI is live out of KillMBB.
611   LR.removeSegment(Kill, MBBEnd);
612   if (EndPoints) EndPoints->push_back(MBBEnd);
613
614   // Find all blocks that are reachable from KillMBB without leaving VNI's live
615   // range. It is possible that KillMBB itself is reachable, so start a DFS
616   // from each successor.
617   typedef SmallPtrSet<MachineBasicBlock*, 9> VisitedTy;
618   VisitedTy Visited;
619   for (MachineBasicBlock::succ_iterator
620        SuccI = KillMBB->succ_begin(), SuccE = KillMBB->succ_end();
621        SuccI != SuccE; ++SuccI) {
622     for (df_ext_iterator<MachineBasicBlock*, VisitedTy>
623          I = df_ext_begin(*SuccI, Visited), E = df_ext_end(*SuccI, Visited);
624          I != E;) {
625       MachineBasicBlock *MBB = *I;
626
627       // Check if VNI is live in to MBB.
628       SlotIndex MBBStart, MBBEnd;
629       std::tie(MBBStart, MBBEnd) = Indexes->getMBBRange(MBB);
630       LiveQueryResult LRQ = LR.Query(MBBStart);
631       if (LRQ.valueIn() != VNI) {
632         // This block isn't part of the VNI segment. Prune the search.
633         I.skipChildren();
634         continue;
635       }
636
637       // Prune the search if VNI is killed in MBB.
638       if (LRQ.endPoint() < MBBEnd) {
639         LR.removeSegment(MBBStart, LRQ.endPoint());
640         if (EndPoints) EndPoints->push_back(LRQ.endPoint());
641         I.skipChildren();
642         continue;
643       }
644
645       // VNI is live through MBB.
646       LR.removeSegment(MBBStart, MBBEnd);
647       if (EndPoints) EndPoints->push_back(MBBEnd);
648       ++I;
649     }
650   }
651 }
652
653 //===----------------------------------------------------------------------===//
654 // Register allocator hooks.
655 //
656
657 void LiveIntervals::addKillFlags(const VirtRegMap *VRM) {
658   // Keep track of regunit ranges.
659   SmallVector<std::pair<const LiveRange*, LiveRange::const_iterator>, 8> RU;
660   // Keep track of subregister ranges.
661   SmallVector<std::pair<const LiveInterval::SubRange*,
662                         LiveRange::const_iterator>, 4> SRs;
663
664   for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
665     unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
666     if (MRI->reg_nodbg_empty(Reg))
667       continue;
668     const LiveInterval &LI = getInterval(Reg);
669     if (LI.empty())
670       continue;
671
672     // Find the regunit intervals for the assigned register. They may overlap
673     // the virtual register live range, cancelling any kills.
674     RU.clear();
675     for (MCRegUnitIterator Units(VRM->getPhys(Reg), TRI); Units.isValid();
676          ++Units) {
677       const LiveRange &RURange = getRegUnit(*Units);
678       if (RURange.empty())
679         continue;
680       RU.push_back(std::make_pair(&RURange, RURange.find(LI.begin()->end)));
681     }
682
683     if (MRI->subRegLivenessEnabled()) {
684       SRs.clear();
685       for (const LiveInterval::SubRange &SR : LI.subranges()) {
686         SRs.push_back(std::make_pair(&SR, SR.find(LI.begin()->end)));
687       }
688     }
689
690     // Every instruction that kills Reg corresponds to a segment range end
691     // point.
692     for (LiveInterval::const_iterator RI = LI.begin(), RE = LI.end(); RI != RE;
693          ++RI) {
694       // A block index indicates an MBB edge.
695       if (RI->end.isBlock())
696         continue;
697       MachineInstr *MI = getInstructionFromIndex(RI->end);
698       if (!MI)
699         continue;
700
701       // Check if any of the regunits are live beyond the end of RI. That could
702       // happen when a physreg is defined as a copy of a virtreg:
703       //
704       //   %EAX = COPY %vreg5
705       //   FOO %vreg5         <--- MI, cancel kill because %EAX is live.
706       //   BAR %EAX<kill>
707       //
708       // There should be no kill flag on FOO when %vreg5 is rewritten as %EAX.
709       for (auto &RUP : RU) {
710         const LiveRange &RURange = *RUP.first;
711         LiveRange::const_iterator &I = RUP.second;
712         if (I == RURange.end())
713           continue;
714         I = RURange.advanceTo(I, RI->end);
715         if (I == RURange.end() || I->start >= RI->end)
716           continue;
717         // I is overlapping RI.
718         goto CancelKill;
719       }
720
721       if (MRI->subRegLivenessEnabled()) {
722         // When reading a partial undefined value we must not add a kill flag.
723         // The regalloc might have used the undef lane for something else.
724         // Example:
725         //     %vreg1 = ...              ; R32: %vreg1
726         //     %vreg2:high16 = ...       ; R64: %vreg2
727         //        = read %vreg2<kill>    ; R64: %vreg2
728         //        = read %vreg1          ; R32: %vreg1
729         // The <kill> flag is correct for %vreg2, but the register allocator may
730         // assign R0L to %vreg1, and R0 to %vreg2 because the low 32bits of R0
731         // are actually never written by %vreg2. After assignment the <kill>
732         // flag at the read instruction is invalid.
733         LaneBitmask DefinedLanesMask;
734         if (!SRs.empty()) {
735           // Compute a mask of lanes that are defined.
736           DefinedLanesMask = 0;
737           for (auto &SRP : SRs) {
738             const LiveInterval::SubRange &SR = *SRP.first;
739             LiveRange::const_iterator &I = SRP.second;
740             if (I == SR.end())
741               continue;
742             I = SR.advanceTo(I, RI->end);
743             if (I == SR.end() || I->start >= RI->end)
744               continue;
745             // I is overlapping RI
746             DefinedLanesMask |= SR.LaneMask;
747           }
748         } else
749           DefinedLanesMask = ~0u;
750
751         bool IsFullWrite = false;
752         for (const MachineOperand &MO : MI->operands()) {
753           if (!MO.isReg() || MO.getReg() != Reg)
754             continue;
755           if (MO.isUse()) {
756             // Reading any undefined lanes?
757             LaneBitmask UseMask = TRI->getSubRegIndexLaneMask(MO.getSubReg());
758             if ((UseMask & ~DefinedLanesMask) != 0)
759               goto CancelKill;
760           } else if (MO.getSubReg() == 0) {
761             // Writing to the full register?
762             assert(MO.isDef());
763             IsFullWrite = true;
764           }
765         }
766
767         // If an instruction writes to a subregister, a new segment starts in
768         // the LiveInterval. But as this is only overriding part of the register
769         // adding kill-flags is not correct here after registers have been
770         // assigned.
771         if (!IsFullWrite) {
772           // Next segment has to be adjacent in the subregister write case.
773           LiveRange::const_iterator N = std::next(RI);
774           if (N != LI.end() && N->start == RI->end)
775             goto CancelKill;
776         }
777       }
778
779       MI->addRegisterKilled(Reg, nullptr);
780       continue;
781 CancelKill:
782       MI->clearRegisterKills(Reg, nullptr);
783     }
784   }
785 }
786
787 MachineBasicBlock*
788 LiveIntervals::intervalIsInOneMBB(const LiveInterval &LI) const {
789   // A local live range must be fully contained inside the block, meaning it is
790   // defined and killed at instructions, not at block boundaries. It is not
791   // live in or or out of any block.
792   //
793   // It is technically possible to have a PHI-defined live range identical to a
794   // single block, but we are going to return false in that case.
795
796   SlotIndex Start = LI.beginIndex();
797   if (Start.isBlock())
798     return nullptr;
799
800   SlotIndex Stop = LI.endIndex();
801   if (Stop.isBlock())
802     return nullptr;
803
804   // getMBBFromIndex doesn't need to search the MBB table when both indexes
805   // belong to proper instructions.
806   MachineBasicBlock *MBB1 = Indexes->getMBBFromIndex(Start);
807   MachineBasicBlock *MBB2 = Indexes->getMBBFromIndex(Stop);
808   return MBB1 == MBB2 ? MBB1 : nullptr;
809 }
810
811 bool
812 LiveIntervals::hasPHIKill(const LiveInterval &LI, const VNInfo *VNI) const {
813   for (const VNInfo *PHI : LI.valnos) {
814     if (PHI->isUnused() || !PHI->isPHIDef())
815       continue;
816     const MachineBasicBlock *PHIMBB = getMBBFromIndex(PHI->def);
817     // Conservatively return true instead of scanning huge predecessor lists.
818     if (PHIMBB->pred_size() > 100)
819       return true;
820     for (MachineBasicBlock::const_pred_iterator
821          PI = PHIMBB->pred_begin(), PE = PHIMBB->pred_end(); PI != PE; ++PI)
822       if (VNI == LI.getVNInfoBefore(Indexes->getMBBEndIdx(*PI)))
823         return true;
824   }
825   return false;
826 }
827
828 float
829 LiveIntervals::getSpillWeight(bool isDef, bool isUse,
830                               const MachineBlockFrequencyInfo *MBFI,
831                               const MachineInstr *MI) {
832   BlockFrequency Freq = MBFI->getBlockFreq(MI->getParent());
833   const float Scale = 1.0f / MBFI->getEntryFreq();
834   return (isDef + isUse) * (Freq.getFrequency() * Scale);
835 }
836
837 LiveRange::Segment
838 LiveIntervals::addSegmentToEndOfBlock(unsigned reg, MachineInstr* startInst) {
839   LiveInterval& Interval = createEmptyInterval(reg);
840   VNInfo* VN = Interval.getNextValue(
841     SlotIndex(getInstructionIndex(startInst).getRegSlot()),
842     getVNInfoAllocator());
843   LiveRange::Segment S(
844      SlotIndex(getInstructionIndex(startInst).getRegSlot()),
845      getMBBEndIdx(startInst->getParent()), VN);
846   Interval.addSegment(S);
847
848   return S;
849 }
850
851
852 //===----------------------------------------------------------------------===//
853 //                          Register mask functions
854 //===----------------------------------------------------------------------===//
855
856 bool LiveIntervals::checkRegMaskInterference(LiveInterval &LI,
857                                              BitVector &UsableRegs) {
858   if (LI.empty())
859     return false;
860   LiveInterval::iterator LiveI = LI.begin(), LiveE = LI.end();
861
862   // Use a smaller arrays for local live ranges.
863   ArrayRef<SlotIndex> Slots;
864   ArrayRef<const uint32_t*> Bits;
865   if (MachineBasicBlock *MBB = intervalIsInOneMBB(LI)) {
866     Slots = getRegMaskSlotsInBlock(MBB->getNumber());
867     Bits = getRegMaskBitsInBlock(MBB->getNumber());
868   } else {
869     Slots = getRegMaskSlots();
870     Bits = getRegMaskBits();
871   }
872
873   // We are going to enumerate all the register mask slots contained in LI.
874   // Start with a binary search of RegMaskSlots to find a starting point.
875   ArrayRef<SlotIndex>::iterator SlotI =
876     std::lower_bound(Slots.begin(), Slots.end(), LiveI->start);
877   ArrayRef<SlotIndex>::iterator SlotE = Slots.end();
878
879   // No slots in range, LI begins after the last call.
880   if (SlotI == SlotE)
881     return false;
882
883   bool Found = false;
884   for (;;) {
885     assert(*SlotI >= LiveI->start);
886     // Loop over all slots overlapping this segment.
887     while (*SlotI < LiveI->end) {
888       // *SlotI overlaps LI. Collect mask bits.
889       if (!Found) {
890         // This is the first overlap. Initialize UsableRegs to all ones.
891         UsableRegs.clear();
892         UsableRegs.resize(TRI->getNumRegs(), true);
893         Found = true;
894       }
895       // Remove usable registers clobbered by this mask.
896       UsableRegs.clearBitsNotInMask(Bits[SlotI-Slots.begin()]);
897       if (++SlotI == SlotE)
898         return Found;
899     }
900     // *SlotI is beyond the current LI segment.
901     LiveI = LI.advanceTo(LiveI, *SlotI);
902     if (LiveI == LiveE)
903       return Found;
904     // Advance SlotI until it overlaps.
905     while (*SlotI < LiveI->start)
906       if (++SlotI == SlotE)
907         return Found;
908   }
909 }
910
911 //===----------------------------------------------------------------------===//
912 //                         IntervalUpdate class.
913 //===----------------------------------------------------------------------===//
914
915 // HMEditor is a toolkit used by handleMove to trim or extend live intervals.
916 class LiveIntervals::HMEditor {
917 private:
918   LiveIntervals& LIS;
919   const MachineRegisterInfo& MRI;
920   const TargetRegisterInfo& TRI;
921   SlotIndex OldIdx;
922   SlotIndex NewIdx;
923   SmallPtrSet<LiveRange*, 8> Updated;
924   bool UpdateFlags;
925
926 public:
927   HMEditor(LiveIntervals& LIS, const MachineRegisterInfo& MRI,
928            const TargetRegisterInfo& TRI,
929            SlotIndex OldIdx, SlotIndex NewIdx, bool UpdateFlags)
930     : LIS(LIS), MRI(MRI), TRI(TRI), OldIdx(OldIdx), NewIdx(NewIdx),
931       UpdateFlags(UpdateFlags) {}
932
933   // FIXME: UpdateFlags is a workaround that creates live intervals for all
934   // physregs, even those that aren't needed for regalloc, in order to update
935   // kill flags. This is wasteful. Eventually, LiveVariables will strip all kill
936   // flags, and postRA passes will use a live register utility instead.
937   LiveRange *getRegUnitLI(unsigned Unit) {
938     if (UpdateFlags)
939       return &LIS.getRegUnit(Unit);
940     return LIS.getCachedRegUnit(Unit);
941   }
942
943   /// Update all live ranges touched by MI, assuming a move from OldIdx to
944   /// NewIdx.
945   void updateAllRanges(MachineInstr *MI) {
946     DEBUG(dbgs() << "handleMove " << OldIdx << " -> " << NewIdx << ": " << *MI);
947     bool hasRegMask = false;
948     for (MachineOperand &MO : MI->operands()) {
949       if (MO.isRegMask())
950         hasRegMask = true;
951       if (!MO.isReg())
952         continue;
953       // Aggressively clear all kill flags.
954       // They are reinserted by VirtRegRewriter.
955       if (MO.isUse())
956         MO.setIsKill(false);
957
958       unsigned Reg = MO.getReg();
959       if (!Reg)
960         continue;
961       if (TargetRegisterInfo::isVirtualRegister(Reg)) {
962         LiveInterval &LI = LIS.getInterval(Reg);
963         if (LI.hasSubRanges()) {
964           unsigned SubReg = MO.getSubReg();
965           LaneBitmask LaneMask = TRI.getSubRegIndexLaneMask(SubReg);
966           for (LiveInterval::SubRange &S : LI.subranges()) {
967             if ((S.LaneMask & LaneMask) == 0)
968               continue;
969             updateRange(S, Reg, S.LaneMask);
970           }
971         }
972         updateRange(LI, Reg, 0);
973         continue;
974       }
975
976       // For physregs, only update the regunits that actually have a
977       // precomputed live range.
978       for (MCRegUnitIterator Units(Reg, &TRI); Units.isValid(); ++Units)
979         if (LiveRange *LR = getRegUnitLI(*Units))
980           updateRange(*LR, *Units, 0);
981     }
982     if (hasRegMask)
983       updateRegMaskSlots();
984   }
985
986 private:
987   /// Update a single live range, assuming an instruction has been moved from
988   /// OldIdx to NewIdx.
989   void updateRange(LiveRange &LR, unsigned Reg, LaneBitmask LaneMask) {
990     if (!Updated.insert(&LR).second)
991       return;
992     DEBUG({
993       dbgs() << "     ";
994       if (TargetRegisterInfo::isVirtualRegister(Reg)) {
995         dbgs() << PrintReg(Reg);
996         if (LaneMask != 0)
997           dbgs() << " L" << PrintLaneMask(LaneMask);
998       } else {
999         dbgs() << PrintRegUnit(Reg, &TRI);
1000       }
1001       dbgs() << ":\t" << LR << '\n';
1002     });
1003     if (SlotIndex::isEarlierInstr(OldIdx, NewIdx))
1004       handleMoveDown(LR);
1005     else
1006       handleMoveUp(LR, Reg, LaneMask);
1007     DEBUG(dbgs() << "        -->\t" << LR << '\n');
1008     LR.verify();
1009   }
1010
1011   /// Update LR to reflect an instruction has been moved downwards from OldIdx
1012   /// to NewIdx.
1013   ///
1014   /// 1. Live def at OldIdx:
1015   ///    Move def to NewIdx, assert endpoint after NewIdx.
1016   ///
1017   /// 2. Live def at OldIdx, killed at NewIdx:
1018   ///    Change to dead def at NewIdx.
1019   ///    (Happens when bundling def+kill together).
1020   ///
1021   /// 3. Dead def at OldIdx:
1022   ///    Move def to NewIdx, possibly across another live value.
1023   ///
1024   /// 4. Def at OldIdx AND at NewIdx:
1025   ///    Remove segment [OldIdx;NewIdx) and value defined at OldIdx.
1026   ///    (Happens when bundling multiple defs together).
1027   ///
1028   /// 5. Value read at OldIdx, killed before NewIdx:
1029   ///    Extend kill to NewIdx.
1030   ///
1031   void handleMoveDown(LiveRange &LR) {
1032     // First look for a kill at OldIdx.
1033     LiveRange::iterator I = LR.find(OldIdx.getBaseIndex());
1034     LiveRange::iterator E = LR.end();
1035     // Is LR even live at OldIdx?
1036     if (I == E || SlotIndex::isEarlierInstr(OldIdx, I->start))
1037       return;
1038
1039     // Handle a live-in value.
1040     if (!SlotIndex::isSameInstr(I->start, OldIdx)) {
1041       bool isKill = SlotIndex::isSameInstr(OldIdx, I->end);
1042       // If the live-in value already extends to NewIdx, there is nothing to do.
1043       if (!SlotIndex::isEarlierInstr(I->end, NewIdx))
1044         return;
1045       // Aggressively remove all kill flags from the old kill point.
1046       // Kill flags shouldn't be used while live intervals exist, they will be
1047       // reinserted by VirtRegRewriter.
1048       if (MachineInstr *KillMI = LIS.getInstructionFromIndex(I->end))
1049         for (MIBundleOperands MO(KillMI); MO.isValid(); ++MO)
1050           if (MO->isReg() && MO->isUse())
1051             MO->setIsKill(false);
1052       // Adjust I->end to reach NewIdx. This may temporarily make LR invalid by
1053       // overlapping ranges. Case 5 above.
1054       I->end = NewIdx.getRegSlot(I->end.isEarlyClobber());
1055       // If this was a kill, there may also be a def. Otherwise we're done.
1056       if (!isKill)
1057         return;
1058       ++I;
1059     }
1060
1061     // Check for a def at OldIdx.
1062     if (I == E || !SlotIndex::isSameInstr(OldIdx, I->start))
1063       return;
1064     // We have a def at OldIdx.
1065     VNInfo *DefVNI = I->valno;
1066     assert(DefVNI->def == I->start && "Inconsistent def");
1067     DefVNI->def = NewIdx.getRegSlot(I->start.isEarlyClobber());
1068     // If the defined value extends beyond NewIdx, just move the def down.
1069     // This is case 1 above.
1070     if (SlotIndex::isEarlierInstr(NewIdx, I->end)) {
1071       I->start = DefVNI->def;
1072       return;
1073     }
1074     // The remaining possibilities are now:
1075     // 2. Live def at OldIdx, killed at NewIdx: isSameInstr(I->end, NewIdx).
1076     // 3. Dead def at OldIdx: I->end = OldIdx.getDeadSlot().
1077     // In either case, it is possible that there is an existing def at NewIdx.
1078     assert((I->end == OldIdx.getDeadSlot() ||
1079             SlotIndex::isSameInstr(I->end, NewIdx)) &&
1080             "Cannot move def below kill");
1081     LiveRange::iterator NewI = LR.advanceTo(I, NewIdx.getRegSlot());
1082     if (NewI != E && SlotIndex::isSameInstr(NewI->start, NewIdx)) {
1083       // There is an existing def at NewIdx, case 4 above. The def at OldIdx is
1084       // coalesced into that value.
1085       assert(NewI->valno != DefVNI && "Multiple defs of value?");
1086       LR.removeValNo(DefVNI);
1087       return;
1088     }
1089     // There was no existing def at NewIdx. Turn *I into a dead def at NewIdx.
1090     // If the def at OldIdx was dead, we allow it to be moved across other LR
1091     // values. The new range should be placed immediately before NewI, move any
1092     // intermediate ranges up.
1093     assert(NewI != I && "Inconsistent iterators");
1094     std::copy(std::next(I), NewI, I);
1095     *std::prev(NewI)
1096       = LiveRange::Segment(DefVNI->def, NewIdx.getDeadSlot(), DefVNI);
1097   }
1098
1099   /// Update LR to reflect an instruction has been moved upwards from OldIdx
1100   /// to NewIdx.
1101   ///
1102   /// 1. Live def at OldIdx:
1103   ///    Hoist def to NewIdx.
1104   ///
1105   /// 2. Dead def at OldIdx:
1106   ///    Hoist def+end to NewIdx, possibly move across other values.
1107   ///
1108   /// 3. Dead def at OldIdx AND existing def at NewIdx:
1109   ///    Remove value defined at OldIdx, coalescing it with existing value.
1110   ///
1111   /// 4. Live def at OldIdx AND existing def at NewIdx:
1112   ///    Remove value defined at NewIdx, hoist OldIdx def to NewIdx.
1113   ///    (Happens when bundling multiple defs together).
1114   ///
1115   /// 5. Value killed at OldIdx:
1116   ///    Hoist kill to NewIdx, then scan for last kill between NewIdx and
1117   ///    OldIdx.
1118   ///
1119   void handleMoveUp(LiveRange &LR, unsigned Reg, LaneBitmask LaneMask) {
1120     // First look for a kill at OldIdx.
1121     LiveRange::iterator I = LR.find(OldIdx.getBaseIndex());
1122     LiveRange::iterator E = LR.end();
1123     // Is LR even live at OldIdx?
1124     if (I == E || SlotIndex::isEarlierInstr(OldIdx, I->start))
1125       return;
1126
1127     // Handle a live-in value.
1128     if (!SlotIndex::isSameInstr(I->start, OldIdx)) {
1129       // If the live-in value isn't killed here, there is nothing to do.
1130       if (!SlotIndex::isSameInstr(OldIdx, I->end))
1131         return;
1132       // Adjust I->end to end at NewIdx. If we are hoisting a kill above
1133       // another use, we need to search for that use. Case 5 above.
1134       I->end = NewIdx.getRegSlot(I->end.isEarlyClobber());
1135       ++I;
1136       // If OldIdx also defines a value, there couldn't have been another use.
1137       if (I == E || !SlotIndex::isSameInstr(I->start, OldIdx)) {
1138         // No def, search for the new kill.
1139         // This can never be an early clobber kill since there is no def.
1140         std::prev(I)->end = findLastUseBefore(Reg, LaneMask).getRegSlot();
1141         return;
1142       }
1143     }
1144
1145     // Now deal with the def at OldIdx.
1146     assert(I != E && SlotIndex::isSameInstr(I->start, OldIdx) && "No def?");
1147     VNInfo *DefVNI = I->valno;
1148     assert(DefVNI->def == I->start && "Inconsistent def");
1149     DefVNI->def = NewIdx.getRegSlot(I->start.isEarlyClobber());
1150
1151     // Check for an existing def at NewIdx.
1152     LiveRange::iterator NewI = LR.find(NewIdx.getRegSlot());
1153     if (SlotIndex::isSameInstr(NewI->start, NewIdx)) {
1154       assert(NewI->valno != DefVNI && "Same value defined more than once?");
1155       // There is an existing def at NewIdx.
1156       if (I->end.isDead()) {
1157         // Case 3: Remove the dead def at OldIdx.
1158         LR.removeValNo(DefVNI);
1159         return;
1160       }
1161       // Case 4: Replace def at NewIdx with live def at OldIdx.
1162       I->start = DefVNI->def;
1163       LR.removeValNo(NewI->valno);
1164       return;
1165     }
1166
1167     // There is no existing def at NewIdx. Hoist DefVNI.
1168     if (!I->end.isDead()) {
1169       // Leave the end point of a live def.
1170       I->start = DefVNI->def;
1171       return;
1172     }
1173
1174     // DefVNI is a dead def. It may have been moved across other values in LR,
1175     // so move I up to NewI. Slide [NewI;I) down one position.
1176     std::copy_backward(NewI, I, std::next(I));
1177     *NewI = LiveRange::Segment(DefVNI->def, NewIdx.getDeadSlot(), DefVNI);
1178   }
1179
1180   void updateRegMaskSlots() {
1181     SmallVectorImpl<SlotIndex>::iterator RI =
1182       std::lower_bound(LIS.RegMaskSlots.begin(), LIS.RegMaskSlots.end(),
1183                        OldIdx);
1184     assert(RI != LIS.RegMaskSlots.end() && *RI == OldIdx.getRegSlot() &&
1185            "No RegMask at OldIdx.");
1186     *RI = NewIdx.getRegSlot();
1187     assert((RI == LIS.RegMaskSlots.begin() ||
1188             SlotIndex::isEarlierInstr(*std::prev(RI), *RI)) &&
1189            "Cannot move regmask instruction above another call");
1190     assert((std::next(RI) == LIS.RegMaskSlots.end() ||
1191             SlotIndex::isEarlierInstr(*RI, *std::next(RI))) &&
1192            "Cannot move regmask instruction below another call");
1193   }
1194
1195   // Return the last use of reg between NewIdx and OldIdx.
1196   SlotIndex findLastUseBefore(unsigned Reg, LaneBitmask LaneMask) {
1197
1198     if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1199       SlotIndex LastUse = NewIdx;
1200       for (MachineOperand &MO : MRI.use_nodbg_operands(Reg)) {
1201         unsigned SubReg = MO.getSubReg();
1202         if (SubReg != 0 && LaneMask != 0
1203             && (TRI.getSubRegIndexLaneMask(SubReg) & LaneMask) == 0)
1204           continue;
1205
1206         const MachineInstr *MI = MO.getParent();
1207         SlotIndex InstSlot = LIS.getSlotIndexes()->getInstructionIndex(MI);
1208         if (InstSlot > LastUse && InstSlot < OldIdx)
1209           LastUse = InstSlot;
1210       }
1211       return LastUse;
1212     }
1213
1214     // This is a regunit interval, so scanning the use list could be very
1215     // expensive. Scan upwards from OldIdx instead.
1216     assert(NewIdx < OldIdx && "Expected upwards move");
1217     SlotIndexes *Indexes = LIS.getSlotIndexes();
1218     MachineBasicBlock *MBB = Indexes->getMBBFromIndex(NewIdx);
1219
1220     // OldIdx may not correspond to an instruction any longer, so set MII to
1221     // point to the next instruction after OldIdx, or MBB->end().
1222     MachineBasicBlock::iterator MII = MBB->end();
1223     if (MachineInstr *MI = Indexes->getInstructionFromIndex(
1224                            Indexes->getNextNonNullIndex(OldIdx)))
1225       if (MI->getParent() == MBB)
1226         MII = MI;
1227
1228     MachineBasicBlock::iterator Begin = MBB->begin();
1229     while (MII != Begin) {
1230       if ((--MII)->isDebugValue())
1231         continue;
1232       SlotIndex Idx = Indexes->getInstructionIndex(MII);
1233
1234       // Stop searching when NewIdx is reached.
1235       if (!SlotIndex::isEarlierInstr(NewIdx, Idx))
1236         return NewIdx;
1237
1238       // Check if MII uses Reg.
1239       for (MIBundleOperands MO(MII); MO.isValid(); ++MO)
1240         if (MO->isReg() &&
1241             TargetRegisterInfo::isPhysicalRegister(MO->getReg()) &&
1242             TRI.hasRegUnit(MO->getReg(), Reg))
1243           return Idx;
1244     }
1245     // Didn't reach NewIdx. It must be the first instruction in the block.
1246     return NewIdx;
1247   }
1248 };
1249
1250 void LiveIntervals::handleMove(MachineInstr* MI, bool UpdateFlags) {
1251   assert(!MI->isBundled() && "Can't handle bundled instructions yet.");
1252   SlotIndex OldIndex = Indexes->getInstructionIndex(MI);
1253   Indexes->removeMachineInstrFromMaps(MI);
1254   SlotIndex NewIndex = Indexes->insertMachineInstrInMaps(MI);
1255   assert(getMBBStartIdx(MI->getParent()) <= OldIndex &&
1256          OldIndex < getMBBEndIdx(MI->getParent()) &&
1257          "Cannot handle moves across basic block boundaries.");
1258
1259   HMEditor HME(*this, *MRI, *TRI, OldIndex, NewIndex, UpdateFlags);
1260   HME.updateAllRanges(MI);
1261 }
1262
1263 void LiveIntervals::handleMoveIntoBundle(MachineInstr* MI,
1264                                          MachineInstr* BundleStart,
1265                                          bool UpdateFlags) {
1266   SlotIndex OldIndex = Indexes->getInstructionIndex(MI);
1267   SlotIndex NewIndex = Indexes->getInstructionIndex(BundleStart);
1268   HMEditor HME(*this, *MRI, *TRI, OldIndex, NewIndex, UpdateFlags);
1269   HME.updateAllRanges(MI);
1270 }
1271
1272 void LiveIntervals::repairOldRegInRange(const MachineBasicBlock::iterator Begin,
1273                                         const MachineBasicBlock::iterator End,
1274                                         const SlotIndex endIdx,
1275                                         LiveRange &LR, const unsigned Reg,
1276                                         LaneBitmask LaneMask) {
1277   LiveInterval::iterator LII = LR.find(endIdx);
1278   SlotIndex lastUseIdx;
1279   if (LII != LR.end() && LII->start < endIdx)
1280     lastUseIdx = LII->end;
1281   else
1282     --LII;
1283
1284   for (MachineBasicBlock::iterator I = End; I != Begin;) {
1285     --I;
1286     MachineInstr *MI = I;
1287     if (MI->isDebugValue())
1288       continue;
1289
1290     SlotIndex instrIdx = getInstructionIndex(MI);
1291     bool isStartValid = getInstructionFromIndex(LII->start);
1292     bool isEndValid = getInstructionFromIndex(LII->end);
1293
1294     // FIXME: This doesn't currently handle early-clobber or multiple removed
1295     // defs inside of the region to repair.
1296     for (MachineInstr::mop_iterator OI = MI->operands_begin(),
1297          OE = MI->operands_end(); OI != OE; ++OI) {
1298       const MachineOperand &MO = *OI;
1299       if (!MO.isReg() || MO.getReg() != Reg)
1300         continue;
1301
1302       unsigned SubReg = MO.getSubReg();
1303       LaneBitmask Mask = TRI->getSubRegIndexLaneMask(SubReg);
1304       if ((Mask & LaneMask) == 0)
1305         continue;
1306
1307       if (MO.isDef()) {
1308         if (!isStartValid) {
1309           if (LII->end.isDead()) {
1310             SlotIndex prevStart;
1311             if (LII != LR.begin())
1312               prevStart = std::prev(LII)->start;
1313
1314             // FIXME: This could be more efficient if there was a
1315             // removeSegment method that returned an iterator.
1316             LR.removeSegment(*LII, true);
1317             if (prevStart.isValid())
1318               LII = LR.find(prevStart);
1319             else
1320               LII = LR.begin();
1321           } else {
1322             LII->start = instrIdx.getRegSlot();
1323             LII->valno->def = instrIdx.getRegSlot();
1324             if (MO.getSubReg() && !MO.isUndef())
1325               lastUseIdx = instrIdx.getRegSlot();
1326             else
1327               lastUseIdx = SlotIndex();
1328             continue;
1329           }
1330         }
1331
1332         if (!lastUseIdx.isValid()) {
1333           VNInfo *VNI = LR.getNextValue(instrIdx.getRegSlot(), VNInfoAllocator);
1334           LiveRange::Segment S(instrIdx.getRegSlot(),
1335                                instrIdx.getDeadSlot(), VNI);
1336           LII = LR.addSegment(S);
1337         } else if (LII->start != instrIdx.getRegSlot()) {
1338           VNInfo *VNI = LR.getNextValue(instrIdx.getRegSlot(), VNInfoAllocator);
1339           LiveRange::Segment S(instrIdx.getRegSlot(), lastUseIdx, VNI);
1340           LII = LR.addSegment(S);
1341         }
1342
1343         if (MO.getSubReg() && !MO.isUndef())
1344           lastUseIdx = instrIdx.getRegSlot();
1345         else
1346           lastUseIdx = SlotIndex();
1347       } else if (MO.isUse()) {
1348         // FIXME: This should probably be handled outside of this branch,
1349         // either as part of the def case (for defs inside of the region) or
1350         // after the loop over the region.
1351         if (!isEndValid && !LII->end.isBlock())
1352           LII->end = instrIdx.getRegSlot();
1353         if (!lastUseIdx.isValid())
1354           lastUseIdx = instrIdx.getRegSlot();
1355       }
1356     }
1357   }
1358 }
1359
1360 void
1361 LiveIntervals::repairIntervalsInRange(MachineBasicBlock *MBB,
1362                                       MachineBasicBlock::iterator Begin,
1363                                       MachineBasicBlock::iterator End,
1364                                       ArrayRef<unsigned> OrigRegs) {
1365   // Find anchor points, which are at the beginning/end of blocks or at
1366   // instructions that already have indexes.
1367   while (Begin != MBB->begin() && !Indexes->hasIndex(Begin))
1368     --Begin;
1369   while (End != MBB->end() && !Indexes->hasIndex(End))
1370     ++End;
1371
1372   SlotIndex endIdx;
1373   if (End == MBB->end())
1374     endIdx = getMBBEndIdx(MBB).getPrevSlot();
1375   else
1376     endIdx = getInstructionIndex(End);
1377
1378   Indexes->repairIndexesInRange(MBB, Begin, End);
1379
1380   for (MachineBasicBlock::iterator I = End; I != Begin;) {
1381     --I;
1382     MachineInstr *MI = I;
1383     if (MI->isDebugValue())
1384       continue;
1385     for (MachineInstr::const_mop_iterator MOI = MI->operands_begin(),
1386          MOE = MI->operands_end(); MOI != MOE; ++MOI) {
1387       if (MOI->isReg() &&
1388           TargetRegisterInfo::isVirtualRegister(MOI->getReg()) &&
1389           !hasInterval(MOI->getReg())) {
1390         createAndComputeVirtRegInterval(MOI->getReg());
1391       }
1392     }
1393   }
1394
1395   for (unsigned i = 0, e = OrigRegs.size(); i != e; ++i) {
1396     unsigned Reg = OrigRegs[i];
1397     if (!TargetRegisterInfo::isVirtualRegister(Reg))
1398       continue;
1399
1400     LiveInterval &LI = getInterval(Reg);
1401     // FIXME: Should we support undefs that gain defs?
1402     if (!LI.hasAtLeastOneValue())
1403       continue;
1404
1405     for (LiveInterval::SubRange &S : LI.subranges()) {
1406       repairOldRegInRange(Begin, End, endIdx, S, Reg, S.LaneMask);
1407     }
1408     repairOldRegInRange(Begin, End, endIdx, LI, Reg);
1409   }
1410 }
1411
1412 void LiveIntervals::removePhysRegDefAt(unsigned Reg, SlotIndex Pos) {
1413   for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units) {
1414     if (LiveRange *LR = getCachedRegUnit(*Units))
1415       if (VNInfo *VNI = LR->getVNInfoAt(Pos))
1416         LR->removeValNo(VNI);
1417   }
1418 }
1419
1420 void LiveIntervals::removeVRegDefAt(LiveInterval &LI, SlotIndex Pos) {
1421   VNInfo *VNI = LI.getVNInfoAt(Pos);
1422   if (VNI == nullptr)
1423     return;
1424   LI.removeValNo(VNI);
1425
1426   // Also remove the value in subranges.
1427   for (LiveInterval::SubRange &S : LI.subranges()) {
1428     if (VNInfo *SVNI = S.getVNInfoAt(Pos))
1429       S.removeValNo(SVNI);
1430   }
1431   LI.removeEmptySubRanges();
1432 }
1433
1434 void LiveIntervals::splitSeparateComponents(LiveInterval &LI,
1435     SmallVectorImpl<LiveInterval*> &SplitLIs) {
1436   ConnectedVNInfoEqClasses ConEQ(*this);
1437   unsigned NumComp = ConEQ.Classify(&LI);
1438   if (NumComp <= 1)
1439     return;
1440   DEBUG(dbgs() << "  Split " << NumComp << " components: " << LI << '\n');
1441   unsigned Reg = LI.reg;
1442   const TargetRegisterClass *RegClass = MRI->getRegClass(Reg);
1443   for (unsigned I = 1; I < NumComp; ++I) {
1444     unsigned NewVReg = MRI->createVirtualRegister(RegClass);
1445     LiveInterval &NewLI = createEmptyInterval(NewVReg);
1446     SplitLIs.push_back(&NewLI);
1447   }
1448   ConEQ.Distribute(LI, SplitLIs.data(), *MRI);
1449 }