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