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