1 //===-- LiveIntervalAnalysis.cpp - Live Interval Analysis -----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the LiveInterval analysis pass which is used
11 // by the Linear Scan Register allocator. This pass linearizes the
12 // basic blocks of the function in DFS order and uses the
13 // LiveVariables pass to conservatively compute live intervals for
14 // each virtual and physical register.
16 //===----------------------------------------------------------------------===//
18 #define DEBUG_TYPE "regalloc"
19 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
20 #include "LiveRangeCalc.h"
21 #include "llvm/ADT/DenseSet.h"
22 #include "llvm/ADT/STLExtras.h"
23 #include "llvm/Analysis/AliasAnalysis.h"
24 #include "llvm/CodeGen/LiveVariables.h"
25 #include "llvm/CodeGen/MachineDominators.h"
26 #include "llvm/CodeGen/MachineInstr.h"
27 #include "llvm/CodeGen/MachineRegisterInfo.h"
28 #include "llvm/CodeGen/Passes.h"
29 #include "llvm/CodeGen/VirtRegMap.h"
30 #include "llvm/IR/Value.h"
31 #include "llvm/Support/BlockFrequency.h"
32 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/ErrorHandling.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include "llvm/Target/TargetInstrInfo.h"
37 #include "llvm/Target/TargetMachine.h"
38 #include "llvm/Target/TargetRegisterInfo.h"
44 char LiveIntervals::ID = 0;
45 char &llvm::LiveIntervalsID = LiveIntervals::ID;
46 INITIALIZE_PASS_BEGIN(LiveIntervals, "liveintervals",
47 "Live Interval Analysis", false, false)
48 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
49 INITIALIZE_PASS_DEPENDENCY(LiveVariables)
50 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
51 INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
52 INITIALIZE_PASS_END(LiveIntervals, "liveintervals",
53 "Live Interval Analysis", false, false)
55 void LiveIntervals::getAnalysisUsage(AnalysisUsage &AU) const {
57 AU.addRequired<AliasAnalysis>();
58 AU.addPreserved<AliasAnalysis>();
59 // LiveVariables isn't really required by this analysis, it is only required
60 // here to make sure it is live during TwoAddressInstructionPass and
61 // PHIElimination. This is temporary.
62 AU.addRequired<LiveVariables>();
63 AU.addPreserved<LiveVariables>();
64 AU.addPreservedID(MachineLoopInfoID);
65 AU.addRequiredTransitiveID(MachineDominatorsID);
66 AU.addPreservedID(MachineDominatorsID);
67 AU.addPreserved<SlotIndexes>();
68 AU.addRequiredTransitive<SlotIndexes>();
69 MachineFunctionPass::getAnalysisUsage(AU);
72 LiveIntervals::LiveIntervals() : MachineFunctionPass(ID),
73 DomTree(0), LRCalc(0) {
74 initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
77 LiveIntervals::~LiveIntervals() {
81 void LiveIntervals::releaseMemory() {
82 // Free the live intervals themselves.
83 for (unsigned i = 0, e = VirtRegIntervals.size(); i != e; ++i)
84 delete VirtRegIntervals[TargetRegisterInfo::index2VirtReg(i)];
85 VirtRegIntervals.clear();
88 RegMaskBlocks.clear();
90 for (unsigned i = 0, e = RegUnitIntervals.size(); i != e; ++i)
91 delete RegUnitIntervals[i];
92 RegUnitIntervals.clear();
94 // Release VNInfo memory regions, VNInfo objects don't need to be dtor'd.
95 VNInfoAllocator.Reset();
98 /// runOnMachineFunction - Register allocate the whole function
100 bool LiveIntervals::runOnMachineFunction(MachineFunction &fn) {
102 MRI = &MF->getRegInfo();
103 TM = &fn.getTarget();
104 TRI = TM->getRegisterInfo();
105 TII = TM->getInstrInfo();
106 AA = &getAnalysis<AliasAnalysis>();
107 Indexes = &getAnalysis<SlotIndexes>();
108 DomTree = &getAnalysis<MachineDominatorTree>();
110 LRCalc = new LiveRangeCalc();
112 // Allocate space for all virtual registers.
113 VirtRegIntervals.resize(MRI->getNumVirtRegs());
117 computeLiveInRegUnits();
123 /// print - Implement the dump method.
124 void LiveIntervals::print(raw_ostream &OS, const Module* ) const {
125 OS << "********** INTERVALS **********\n";
127 // Dump the regunits.
128 for (unsigned i = 0, e = RegUnitIntervals.size(); i != e; ++i)
129 if (LiveInterval *LI = RegUnitIntervals[i])
130 OS << PrintRegUnit(i, TRI) << " = " << *LI << '\n';
132 // Dump the virtregs.
133 for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
134 unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
135 if (hasInterval(Reg))
136 OS << PrintReg(Reg) << " = " << getInterval(Reg) << '\n';
140 for (unsigned i = 0, e = RegMaskSlots.size(); i != e; ++i)
141 OS << ' ' << RegMaskSlots[i];
147 void LiveIntervals::printInstrs(raw_ostream &OS) const {
148 OS << "********** MACHINEINSTRS **********\n";
149 MF->print(OS, Indexes);
152 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
153 void LiveIntervals::dumpInstrs() const {
158 LiveInterval* LiveIntervals::createInterval(unsigned reg) {
159 float Weight = TargetRegisterInfo::isPhysicalRegister(reg) ? HUGE_VALF : 0.0F;
160 return new LiveInterval(reg, Weight);
164 /// computeVirtRegInterval - Compute the live interval of a virtual register,
165 /// based on defs and uses.
166 void LiveIntervals::computeVirtRegInterval(LiveInterval *LI) {
167 assert(LRCalc && "LRCalc not initialized.");
168 assert(LI->empty() && "Should only compute empty intervals.");
169 LRCalc->reset(MF, getSlotIndexes(), DomTree, &getVNInfoAllocator());
170 LRCalc->createDeadDefs(LI);
171 LRCalc->extendToUses(LI);
174 void LiveIntervals::computeVirtRegs() {
175 for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
176 unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
177 if (MRI->reg_nodbg_empty(Reg))
179 LiveInterval *LI = createInterval(Reg);
180 VirtRegIntervals[Reg] = LI;
181 computeVirtRegInterval(LI);
185 void LiveIntervals::computeRegMasks() {
186 RegMaskBlocks.resize(MF->getNumBlockIDs());
188 // Find all instructions with regmask operands.
189 for (MachineFunction::iterator MBBI = MF->begin(), E = MF->end();
191 MachineBasicBlock *MBB = MBBI;
192 std::pair<unsigned, unsigned> &RMB = RegMaskBlocks[MBB->getNumber()];
193 RMB.first = RegMaskSlots.size();
194 for (MachineBasicBlock::iterator MI = MBB->begin(), ME = MBB->end();
196 for (MIOperands MO(MI); MO.isValid(); ++MO) {
197 if (!MO->isRegMask())
199 RegMaskSlots.push_back(Indexes->getInstructionIndex(MI).getRegSlot());
200 RegMaskBits.push_back(MO->getRegMask());
202 // Compute the number of register mask instructions in this block.
203 RMB.second = RegMaskSlots.size() - RMB.first;
207 //===----------------------------------------------------------------------===//
208 // Register Unit Liveness
209 //===----------------------------------------------------------------------===//
211 // Fixed interference typically comes from ABI boundaries: Function arguments
212 // and return values are passed in fixed registers, and so are exception
213 // pointers entering landing pads. Certain instructions require values to be
214 // present in specific registers. That is also represented through fixed
218 /// computeRegUnitInterval - Compute the live interval of a register unit, based
219 /// on the uses and defs of aliasing registers. The interval should be empty,
220 /// or contain only dead phi-defs from ABI blocks.
221 void LiveIntervals::computeRegUnitInterval(LiveInterval *LI) {
222 unsigned Unit = LI->reg;
224 assert(LRCalc && "LRCalc not initialized.");
225 LRCalc->reset(MF, getSlotIndexes(), DomTree, &getVNInfoAllocator());
227 // The physregs aliasing Unit are the roots and their super-registers.
228 // Create all values as dead defs before extending to uses. Note that roots
229 // may share super-registers. That's OK because createDeadDefs() is
230 // idempotent. It is very rare for a register unit to have multiple roots, so
231 // uniquing super-registers is probably not worthwhile.
232 for (MCRegUnitRootIterator Roots(Unit, TRI); Roots.isValid(); ++Roots) {
233 for (MCSuperRegIterator Supers(*Roots, TRI, /*IncludeSelf=*/true);
234 Supers.isValid(); ++Supers) {
235 if (!MRI->reg_empty(*Supers))
236 LRCalc->createDeadDefs(LI, *Supers);
240 // Now extend LI to reach all uses.
241 // Ignore uses of reserved registers. We only track defs of those.
242 for (MCRegUnitRootIterator Roots(Unit, TRI); Roots.isValid(); ++Roots) {
243 for (MCSuperRegIterator Supers(*Roots, TRI, /*IncludeSelf=*/true);
244 Supers.isValid(); ++Supers) {
245 unsigned Reg = *Supers;
246 if (!MRI->isReserved(Reg) && !MRI->reg_empty(Reg))
247 LRCalc->extendToUses(LI, Reg);
253 /// computeLiveInRegUnits - Precompute the live ranges of any register units
254 /// that are live-in to an ABI block somewhere. Register values can appear
255 /// without a corresponding def when entering the entry block or a landing pad.
257 void LiveIntervals::computeLiveInRegUnits() {
258 RegUnitIntervals.resize(TRI->getNumRegUnits());
259 DEBUG(dbgs() << "Computing live-in reg-units in ABI blocks.\n");
261 // Keep track of the intervals allocated.
262 SmallVector<LiveInterval*, 8> NewIntvs;
264 // Check all basic blocks for live-ins.
265 for (MachineFunction::const_iterator MFI = MF->begin(), MFE = MF->end();
267 const MachineBasicBlock *MBB = MFI;
269 // We only care about ABI blocks: Entry + landing pads.
270 if ((MFI != MF->begin() && !MBB->isLandingPad()) || MBB->livein_empty())
273 // Create phi-defs at Begin for all live-in registers.
274 SlotIndex Begin = Indexes->getMBBStartIdx(MBB);
275 DEBUG(dbgs() << Begin << "\tBB#" << MBB->getNumber());
276 for (MachineBasicBlock::livein_iterator LII = MBB->livein_begin(),
277 LIE = MBB->livein_end(); LII != LIE; ++LII) {
278 for (MCRegUnitIterator Units(*LII, TRI); Units.isValid(); ++Units) {
279 unsigned Unit = *Units;
280 LiveInterval *Intv = RegUnitIntervals[Unit];
282 Intv = RegUnitIntervals[Unit] = new LiveInterval(Unit, HUGE_VALF);
283 NewIntvs.push_back(Intv);
285 VNInfo *VNI = Intv->createDeadDef(Begin, getVNInfoAllocator());
287 DEBUG(dbgs() << ' ' << PrintRegUnit(Unit, TRI) << '#' << VNI->id);
290 DEBUG(dbgs() << '\n');
292 DEBUG(dbgs() << "Created " << NewIntvs.size() << " new intervals.\n");
294 // Compute the 'normal' part of the intervals.
295 for (unsigned i = 0, e = NewIntvs.size(); i != e; ++i)
296 computeRegUnitInterval(NewIntvs[i]);
300 /// shrinkToUses - After removing some uses of a register, shrink its live
301 /// range to just the remaining uses. This method does not compute reaching
302 /// defs for new uses, and it doesn't remove dead defs.
303 bool LiveIntervals::shrinkToUses(LiveInterval *li,
304 SmallVectorImpl<MachineInstr*> *dead) {
305 DEBUG(dbgs() << "Shrink: " << *li << '\n');
306 assert(TargetRegisterInfo::isVirtualRegister(li->reg)
307 && "Can only shrink virtual registers");
308 // Find all the values used, including PHI kills.
309 SmallVector<std::pair<SlotIndex, VNInfo*>, 16> WorkList;
311 // Blocks that have already been added to WorkList as live-out.
312 SmallPtrSet<MachineBasicBlock*, 16> LiveOut;
314 // Visit all instructions reading li->reg.
315 for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(li->reg);
316 MachineInstr *UseMI = I.skipInstruction();) {
317 if (UseMI->isDebugValue() || !UseMI->readsVirtualRegister(li->reg))
319 SlotIndex Idx = getInstructionIndex(UseMI).getRegSlot();
320 LiveRangeQuery LRQ(*li, Idx);
321 VNInfo *VNI = LRQ.valueIn();
323 // This shouldn't happen: readsVirtualRegister returns true, but there is
324 // no live value. It is likely caused by a target getting <undef> flags
326 DEBUG(dbgs() << Idx << '\t' << *UseMI
327 << "Warning: Instr claims to read non-existent value in "
331 // Special case: An early-clobber tied operand reads and writes the
332 // register one slot early.
333 if (VNInfo *DefVNI = LRQ.valueDefined())
336 WorkList.push_back(std::make_pair(Idx, VNI));
339 // Create a new live interval with only minimal live segments per def.
340 LiveInterval NewLI(li->reg, 0);
341 for (LiveInterval::vni_iterator I = li->vni_begin(), E = li->vni_end();
346 NewLI.addRange(LiveRange(VNI->def, VNI->def.getDeadSlot(), VNI));
349 // Keep track of the PHIs that are in use.
350 SmallPtrSet<VNInfo*, 8> UsedPHIs;
352 // Extend intervals to reach all uses in WorkList.
353 while (!WorkList.empty()) {
354 SlotIndex Idx = WorkList.back().first;
355 VNInfo *VNI = WorkList.back().second;
357 const MachineBasicBlock *MBB = getMBBFromIndex(Idx.getPrevSlot());
358 SlotIndex BlockStart = getMBBStartIdx(MBB);
360 // Extend the live range for VNI to be live at Idx.
361 if (VNInfo *ExtVNI = NewLI.extendInBlock(BlockStart, Idx)) {
363 assert(ExtVNI == VNI && "Unexpected existing value number");
364 // Is this a PHIDef we haven't seen before?
365 if (!VNI->isPHIDef() || VNI->def != BlockStart || !UsedPHIs.insert(VNI))
367 // The PHI is live, make sure the predecessors are live-out.
368 for (MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(),
369 PE = MBB->pred_end(); PI != PE; ++PI) {
370 if (!LiveOut.insert(*PI))
372 SlotIndex Stop = getMBBEndIdx(*PI);
373 // A predecessor is not required to have a live-out value for a PHI.
374 if (VNInfo *PVNI = li->getVNInfoBefore(Stop))
375 WorkList.push_back(std::make_pair(Stop, PVNI));
380 // VNI is live-in to MBB.
381 DEBUG(dbgs() << " live-in at " << BlockStart << '\n');
382 NewLI.addRange(LiveRange(BlockStart, Idx, VNI));
384 // Make sure VNI is live-out from the predecessors.
385 for (MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(),
386 PE = MBB->pred_end(); PI != PE; ++PI) {
387 if (!LiveOut.insert(*PI))
389 SlotIndex Stop = getMBBEndIdx(*PI);
390 assert(li->getVNInfoBefore(Stop) == VNI &&
391 "Wrong value out of predecessor");
392 WorkList.push_back(std::make_pair(Stop, VNI));
396 // Handle dead values.
397 bool CanSeparate = false;
398 for (LiveInterval::vni_iterator I = li->vni_begin(), E = li->vni_end();
403 LiveInterval::iterator LII = NewLI.FindLiveRangeContaining(VNI->def);
404 assert(LII != NewLI.end() && "Missing live range for PHI");
405 if (LII->end != VNI->def.getDeadSlot())
407 if (VNI->isPHIDef()) {
408 // This is a dead PHI. Remove it.
410 NewLI.removeRange(*LII);
411 DEBUG(dbgs() << "Dead PHI at " << VNI->def << " may separate interval\n");
414 // This is a dead def. Make sure the instruction knows.
415 MachineInstr *MI = getInstructionFromIndex(VNI->def);
416 assert(MI && "No instruction defining live value");
417 MI->addRegisterDead(li->reg, TRI);
418 if (dead && MI->allDefsAreDead()) {
419 DEBUG(dbgs() << "All defs dead: " << VNI->def << '\t' << *MI);
425 // Move the trimmed ranges back.
426 li->ranges.swap(NewLI.ranges);
427 DEBUG(dbgs() << "Shrunk: " << *li << '\n');
431 void LiveIntervals::extendToIndices(LiveInterval *LI,
432 ArrayRef<SlotIndex> Indices) {
433 assert(LRCalc && "LRCalc not initialized.");
434 LRCalc->reset(MF, getSlotIndexes(), DomTree, &getVNInfoAllocator());
435 for (unsigned i = 0, e = Indices.size(); i != e; ++i)
436 LRCalc->extend(LI, Indices[i]);
439 void LiveIntervals::pruneValue(LiveInterval *LI, SlotIndex Kill,
440 SmallVectorImpl<SlotIndex> *EndPoints) {
441 LiveRangeQuery LRQ(*LI, Kill);
442 VNInfo *VNI = LRQ.valueOut();
446 MachineBasicBlock *KillMBB = Indexes->getMBBFromIndex(Kill);
447 SlotIndex MBBStart, MBBEnd;
448 tie(MBBStart, MBBEnd) = Indexes->getMBBRange(KillMBB);
450 // If VNI isn't live out from KillMBB, the value is trivially pruned.
451 if (LRQ.endPoint() < MBBEnd) {
452 LI->removeRange(Kill, LRQ.endPoint());
453 if (EndPoints) EndPoints->push_back(LRQ.endPoint());
457 // VNI is live out of KillMBB.
458 LI->removeRange(Kill, MBBEnd);
459 if (EndPoints) EndPoints->push_back(MBBEnd);
461 // Find all blocks that are reachable from KillMBB without leaving VNI's live
462 // range. It is possible that KillMBB itself is reachable, so start a DFS
463 // from each successor.
464 typedef SmallPtrSet<MachineBasicBlock*, 9> VisitedTy;
466 for (MachineBasicBlock::succ_iterator
467 SuccI = KillMBB->succ_begin(), SuccE = KillMBB->succ_end();
468 SuccI != SuccE; ++SuccI) {
469 for (df_ext_iterator<MachineBasicBlock*, VisitedTy>
470 I = df_ext_begin(*SuccI, Visited), E = df_ext_end(*SuccI, Visited);
472 MachineBasicBlock *MBB = *I;
474 // Check if VNI is live in to MBB.
475 tie(MBBStart, MBBEnd) = Indexes->getMBBRange(MBB);
476 LiveRangeQuery LRQ(*LI, MBBStart);
477 if (LRQ.valueIn() != VNI) {
478 // This block isn't part of the VNI live range. Prune the search.
483 // Prune the search if VNI is killed in MBB.
484 if (LRQ.endPoint() < MBBEnd) {
485 LI->removeRange(MBBStart, LRQ.endPoint());
486 if (EndPoints) EndPoints->push_back(LRQ.endPoint());
491 // VNI is live through MBB.
492 LI->removeRange(MBBStart, MBBEnd);
493 if (EndPoints) EndPoints->push_back(MBBEnd);
499 //===----------------------------------------------------------------------===//
500 // Register allocator hooks.
503 void LiveIntervals::addKillFlags(const VirtRegMap *VRM) {
504 // Keep track of regunit ranges.
505 SmallVector<std::pair<LiveInterval*, LiveInterval::iterator>, 8> RU;
507 for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
508 unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
509 if (MRI->reg_nodbg_empty(Reg))
511 LiveInterval *LI = &getInterval(Reg);
515 // Find the regunit intervals for the assigned register. They may overlap
516 // the virtual register live range, cancelling any kills.
518 for (MCRegUnitIterator Units(VRM->getPhys(Reg), TRI); Units.isValid();
520 LiveInterval *RUInt = &getRegUnit(*Units);
523 RU.push_back(std::make_pair(RUInt, RUInt->find(LI->begin()->end)));
526 // Every instruction that kills Reg corresponds to a live range end point.
527 for (LiveInterval::iterator RI = LI->begin(), RE = LI->end(); RI != RE;
529 // A block index indicates an MBB edge.
530 if (RI->end.isBlock())
532 MachineInstr *MI = getInstructionFromIndex(RI->end);
536 // Check if any of the reguints are live beyond the end of RI. That could
537 // happen when a physreg is defined as a copy of a virtreg:
539 // %EAX = COPY %vreg5
540 // FOO %vreg5 <--- MI, cancel kill because %EAX is live.
543 // There should be no kill flag on FOO when %vreg5 is rewritten as %EAX.
544 bool CancelKill = false;
545 for (unsigned u = 0, e = RU.size(); u != e; ++u) {
546 LiveInterval *RInt = RU[u].first;
547 LiveInterval::iterator &I = RU[u].second;
548 if (I == RInt->end())
550 I = RInt->advanceTo(I, RI->end);
551 if (I == RInt->end() || I->start >= RI->end)
553 // I is overlapping RI.
558 MI->clearRegisterKills(Reg, NULL);
560 MI->addRegisterKilled(Reg, NULL);
566 LiveIntervals::intervalIsInOneMBB(const LiveInterval &LI) const {
567 // A local live range must be fully contained inside the block, meaning it is
568 // defined and killed at instructions, not at block boundaries. It is not
569 // live in or or out of any block.
571 // It is technically possible to have a PHI-defined live range identical to a
572 // single block, but we are going to return false in that case.
574 SlotIndex Start = LI.beginIndex();
578 SlotIndex Stop = LI.endIndex();
582 // getMBBFromIndex doesn't need to search the MBB table when both indexes
583 // belong to proper instructions.
584 MachineBasicBlock *MBB1 = Indexes->getMBBFromIndex(Start);
585 MachineBasicBlock *MBB2 = Indexes->getMBBFromIndex(Stop);
586 return MBB1 == MBB2 ? MBB1 : NULL;
590 LiveIntervals::hasPHIKill(const LiveInterval &LI, const VNInfo *VNI) const {
591 for (LiveInterval::const_vni_iterator I = LI.vni_begin(), E = LI.vni_end();
593 const VNInfo *PHI = *I;
594 if (PHI->isUnused() || !PHI->isPHIDef())
596 const MachineBasicBlock *PHIMBB = getMBBFromIndex(PHI->def);
597 // Conservatively return true instead of scanning huge predecessor lists.
598 if (PHIMBB->pred_size() > 100)
600 for (MachineBasicBlock::const_pred_iterator
601 PI = PHIMBB->pred_begin(), PE = PHIMBB->pred_end(); PI != PE; ++PI)
602 if (VNI == LI.getVNInfoBefore(Indexes->getMBBEndIdx(*PI)))
609 LiveIntervals::getSpillWeight(bool isDef, bool isUse, BlockFrequency freq) {
610 const float Scale = 1.0f / BlockFrequency::getEntryFrequency();
611 return (isDef + isUse) * (freq.getFrequency() * Scale);
614 LiveRange LiveIntervals::addLiveRangeToEndOfBlock(unsigned reg,
615 MachineInstr* startInst) {
616 LiveInterval& Interval = getOrCreateInterval(reg);
617 VNInfo* VN = Interval.getNextValue(
618 SlotIndex(getInstructionIndex(startInst).getRegSlot()),
619 getVNInfoAllocator());
621 SlotIndex(getInstructionIndex(startInst).getRegSlot()),
622 getMBBEndIdx(startInst->getParent()), VN);
623 Interval.addRange(LR);
629 //===----------------------------------------------------------------------===//
630 // Register mask functions
631 //===----------------------------------------------------------------------===//
633 bool LiveIntervals::checkRegMaskInterference(LiveInterval &LI,
634 BitVector &UsableRegs) {
637 LiveInterval::iterator LiveI = LI.begin(), LiveE = LI.end();
639 // Use a smaller arrays for local live ranges.
640 ArrayRef<SlotIndex> Slots;
641 ArrayRef<const uint32_t*> Bits;
642 if (MachineBasicBlock *MBB = intervalIsInOneMBB(LI)) {
643 Slots = getRegMaskSlotsInBlock(MBB->getNumber());
644 Bits = getRegMaskBitsInBlock(MBB->getNumber());
646 Slots = getRegMaskSlots();
647 Bits = getRegMaskBits();
650 // We are going to enumerate all the register mask slots contained in LI.
651 // Start with a binary search of RegMaskSlots to find a starting point.
652 ArrayRef<SlotIndex>::iterator SlotI =
653 std::lower_bound(Slots.begin(), Slots.end(), LiveI->start);
654 ArrayRef<SlotIndex>::iterator SlotE = Slots.end();
656 // No slots in range, LI begins after the last call.
662 assert(*SlotI >= LiveI->start);
663 // Loop over all slots overlapping this segment.
664 while (*SlotI < LiveI->end) {
665 // *SlotI overlaps LI. Collect mask bits.
667 // This is the first overlap. Initialize UsableRegs to all ones.
669 UsableRegs.resize(TRI->getNumRegs(), true);
672 // Remove usable registers clobbered by this mask.
673 UsableRegs.clearBitsNotInMask(Bits[SlotI-Slots.begin()]);
674 if (++SlotI == SlotE)
677 // *SlotI is beyond the current LI segment.
678 LiveI = LI.advanceTo(LiveI, *SlotI);
681 // Advance SlotI until it overlaps.
682 while (*SlotI < LiveI->start)
683 if (++SlotI == SlotE)
688 //===----------------------------------------------------------------------===//
689 // IntervalUpdate class.
690 //===----------------------------------------------------------------------===//
692 // HMEditor is a toolkit used by handleMove to trim or extend live intervals.
693 class LiveIntervals::HMEditor {
696 const MachineRegisterInfo& MRI;
697 const TargetRegisterInfo& TRI;
700 SmallPtrSet<LiveInterval*, 8> Updated;
704 HMEditor(LiveIntervals& LIS, const MachineRegisterInfo& MRI,
705 const TargetRegisterInfo& TRI,
706 SlotIndex OldIdx, SlotIndex NewIdx, bool UpdateFlags)
707 : LIS(LIS), MRI(MRI), TRI(TRI), OldIdx(OldIdx), NewIdx(NewIdx),
708 UpdateFlags(UpdateFlags) {}
710 // FIXME: UpdateFlags is a workaround that creates live intervals for all
711 // physregs, even those that aren't needed for regalloc, in order to update
712 // kill flags. This is wasteful. Eventually, LiveVariables will strip all kill
713 // flags, and postRA passes will use a live register utility instead.
714 LiveInterval *getRegUnitLI(unsigned Unit) {
716 return &LIS.getRegUnit(Unit);
717 return LIS.getCachedRegUnit(Unit);
720 /// Update all live ranges touched by MI, assuming a move from OldIdx to
722 void updateAllRanges(MachineInstr *MI) {
723 DEBUG(dbgs() << "handleMove " << OldIdx << " -> " << NewIdx << ": " << *MI);
724 bool hasRegMask = false;
725 for (MIOperands MO(MI); MO.isValid(); ++MO) {
730 // Aggressively clear all kill flags.
731 // They are reinserted by VirtRegRewriter.
733 MO->setIsKill(false);
735 unsigned Reg = MO->getReg();
738 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
739 updateRange(LIS.getInterval(Reg));
743 // For physregs, only update the regunits that actually have a
744 // precomputed live range.
745 for (MCRegUnitIterator Units(Reg, &TRI); Units.isValid(); ++Units)
746 if (LiveInterval *LI = getRegUnitLI(*Units))
750 updateRegMaskSlots();
754 /// Update a single live range, assuming an instruction has been moved from
755 /// OldIdx to NewIdx.
756 void updateRange(LiveInterval &LI) {
757 if (!Updated.insert(&LI))
761 if (TargetRegisterInfo::isVirtualRegister(LI.reg))
762 dbgs() << PrintReg(LI.reg);
764 dbgs() << PrintRegUnit(LI.reg, &TRI);
765 dbgs() << ":\t" << LI << '\n';
767 if (SlotIndex::isEarlierInstr(OldIdx, NewIdx))
771 DEBUG(dbgs() << " -->\t" << LI << '\n');
775 /// Update LI to reflect an instruction has been moved downwards from OldIdx
778 /// 1. Live def at OldIdx:
779 /// Move def to NewIdx, assert endpoint after NewIdx.
781 /// 2. Live def at OldIdx, killed at NewIdx:
782 /// Change to dead def at NewIdx.
783 /// (Happens when bundling def+kill together).
785 /// 3. Dead def at OldIdx:
786 /// Move def to NewIdx, possibly across another live value.
788 /// 4. Def at OldIdx AND at NewIdx:
789 /// Remove live range [OldIdx;NewIdx) and value defined at OldIdx.
790 /// (Happens when bundling multiple defs together).
792 /// 5. Value read at OldIdx, killed before NewIdx:
793 /// Extend kill to NewIdx.
795 void handleMoveDown(LiveInterval &LI) {
796 // First look for a kill at OldIdx.
797 LiveInterval::iterator I = LI.find(OldIdx.getBaseIndex());
798 LiveInterval::iterator E = LI.end();
799 // Is LI even live at OldIdx?
800 if (I == E || SlotIndex::isEarlierInstr(OldIdx, I->start))
803 // Handle a live-in value.
804 if (!SlotIndex::isSameInstr(I->start, OldIdx)) {
805 bool isKill = SlotIndex::isSameInstr(OldIdx, I->end);
806 // If the live-in value already extends to NewIdx, there is nothing to do.
807 if (!SlotIndex::isEarlierInstr(I->end, NewIdx))
809 // Aggressively remove all kill flags from the old kill point.
810 // Kill flags shouldn't be used while live intervals exist, they will be
811 // reinserted by VirtRegRewriter.
812 if (MachineInstr *KillMI = LIS.getInstructionFromIndex(I->end))
813 for (MIBundleOperands MO(KillMI); MO.isValid(); ++MO)
814 if (MO->isReg() && MO->isUse())
815 MO->setIsKill(false);
816 // Adjust I->end to reach NewIdx. This may temporarily make LI invalid by
817 // overlapping ranges. Case 5 above.
818 I->end = NewIdx.getRegSlot(I->end.isEarlyClobber());
819 // If this was a kill, there may also be a def. Otherwise we're done.
825 // Check for a def at OldIdx.
826 if (I == E || !SlotIndex::isSameInstr(OldIdx, I->start))
828 // We have a def at OldIdx.
829 VNInfo *DefVNI = I->valno;
830 assert(DefVNI->def == I->start && "Inconsistent def");
831 DefVNI->def = NewIdx.getRegSlot(I->start.isEarlyClobber());
832 // If the defined value extends beyond NewIdx, just move the def down.
833 // This is case 1 above.
834 if (SlotIndex::isEarlierInstr(NewIdx, I->end)) {
835 I->start = DefVNI->def;
838 // The remaining possibilities are now:
839 // 2. Live def at OldIdx, killed at NewIdx: isSameInstr(I->end, NewIdx).
840 // 3. Dead def at OldIdx: I->end = OldIdx.getDeadSlot().
841 // In either case, it is possible that there is an existing def at NewIdx.
842 assert((I->end == OldIdx.getDeadSlot() ||
843 SlotIndex::isSameInstr(I->end, NewIdx)) &&
844 "Cannot move def below kill");
845 LiveInterval::iterator NewI = LI.advanceTo(I, NewIdx.getRegSlot());
846 if (NewI != E && SlotIndex::isSameInstr(NewI->start, NewIdx)) {
847 // There is an existing def at NewIdx, case 4 above. The def at OldIdx is
848 // coalesced into that value.
849 assert(NewI->valno != DefVNI && "Multiple defs of value?");
850 LI.removeValNo(DefVNI);
853 // There was no existing def at NewIdx. Turn *I into a dead def at NewIdx.
854 // If the def at OldIdx was dead, we allow it to be moved across other LI
855 // values. The new range should be placed immediately before NewI, move any
856 // intermediate ranges up.
857 assert(NewI != I && "Inconsistent iterators");
858 std::copy(llvm::next(I), NewI, I);
859 *llvm::prior(NewI) = LiveRange(DefVNI->def, NewIdx.getDeadSlot(), DefVNI);
862 /// Update LI to reflect an instruction has been moved upwards from OldIdx
865 /// 1. Live def at OldIdx:
866 /// Hoist def to NewIdx.
868 /// 2. Dead def at OldIdx:
869 /// Hoist def+end to NewIdx, possibly move across other values.
871 /// 3. Dead def at OldIdx AND existing def at NewIdx:
872 /// Remove value defined at OldIdx, coalescing it with existing value.
874 /// 4. Live def at OldIdx AND existing def at NewIdx:
875 /// Remove value defined at NewIdx, hoist OldIdx def to NewIdx.
876 /// (Happens when bundling multiple defs together).
878 /// 5. Value killed at OldIdx:
879 /// Hoist kill to NewIdx, then scan for last kill between NewIdx and
882 void handleMoveUp(LiveInterval &LI) {
883 // First look for a kill at OldIdx.
884 LiveInterval::iterator I = LI.find(OldIdx.getBaseIndex());
885 LiveInterval::iterator E = LI.end();
886 // Is LI even live at OldIdx?
887 if (I == E || SlotIndex::isEarlierInstr(OldIdx, I->start))
890 // Handle a live-in value.
891 if (!SlotIndex::isSameInstr(I->start, OldIdx)) {
892 // If the live-in value isn't killed here, there is nothing to do.
893 if (!SlotIndex::isSameInstr(OldIdx, I->end))
895 // Adjust I->end to end at NewIdx. If we are hoisting a kill above
896 // another use, we need to search for that use. Case 5 above.
897 I->end = NewIdx.getRegSlot(I->end.isEarlyClobber());
899 // If OldIdx also defines a value, there couldn't have been another use.
900 if (I == E || !SlotIndex::isSameInstr(I->start, OldIdx)) {
901 // No def, search for the new kill.
902 // This can never be an early clobber kill since there is no def.
903 llvm::prior(I)->end = findLastUseBefore(LI.reg).getRegSlot();
908 // Now deal with the def at OldIdx.
909 assert(I != E && SlotIndex::isSameInstr(I->start, OldIdx) && "No def?");
910 VNInfo *DefVNI = I->valno;
911 assert(DefVNI->def == I->start && "Inconsistent def");
912 DefVNI->def = NewIdx.getRegSlot(I->start.isEarlyClobber());
914 // Check for an existing def at NewIdx.
915 LiveInterval::iterator NewI = LI.find(NewIdx.getRegSlot());
916 if (SlotIndex::isSameInstr(NewI->start, NewIdx)) {
917 assert(NewI->valno != DefVNI && "Same value defined more than once?");
918 // There is an existing def at NewIdx.
919 if (I->end.isDead()) {
920 // Case 3: Remove the dead def at OldIdx.
921 LI.removeValNo(DefVNI);
924 // Case 4: Replace def at NewIdx with live def at OldIdx.
925 I->start = DefVNI->def;
926 LI.removeValNo(NewI->valno);
930 // There is no existing def at NewIdx. Hoist DefVNI.
931 if (!I->end.isDead()) {
932 // Leave the end point of a live def.
933 I->start = DefVNI->def;
937 // DefVNI is a dead def. It may have been moved across other values in LI,
938 // so move I up to NewI. Slide [NewI;I) down one position.
939 std::copy_backward(NewI, I, llvm::next(I));
940 *NewI = LiveRange(DefVNI->def, NewIdx.getDeadSlot(), DefVNI);
943 void updateRegMaskSlots() {
944 SmallVectorImpl<SlotIndex>::iterator RI =
945 std::lower_bound(LIS.RegMaskSlots.begin(), LIS.RegMaskSlots.end(),
947 assert(RI != LIS.RegMaskSlots.end() && *RI == OldIdx.getRegSlot() &&
948 "No RegMask at OldIdx.");
949 *RI = NewIdx.getRegSlot();
950 assert((RI == LIS.RegMaskSlots.begin() ||
951 SlotIndex::isEarlierInstr(*llvm::prior(RI), *RI)) &&
952 "Cannot move regmask instruction above another call");
953 assert((llvm::next(RI) == LIS.RegMaskSlots.end() ||
954 SlotIndex::isEarlierInstr(*RI, *llvm::next(RI))) &&
955 "Cannot move regmask instruction below another call");
958 // Return the last use of reg between NewIdx and OldIdx.
959 SlotIndex findLastUseBefore(unsigned Reg) {
961 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
962 SlotIndex LastUse = NewIdx;
963 for (MachineRegisterInfo::use_nodbg_iterator
964 UI = MRI.use_nodbg_begin(Reg),
965 UE = MRI.use_nodbg_end();
966 UI != UE; UI.skipInstruction()) {
967 const MachineInstr* MI = &*UI;
968 SlotIndex InstSlot = LIS.getSlotIndexes()->getInstructionIndex(MI);
969 if (InstSlot > LastUse && InstSlot < OldIdx)
975 // This is a regunit interval, so scanning the use list could be very
976 // expensive. Scan upwards from OldIdx instead.
977 assert(NewIdx < OldIdx && "Expected upwards move");
978 SlotIndexes *Indexes = LIS.getSlotIndexes();
979 MachineBasicBlock *MBB = Indexes->getMBBFromIndex(NewIdx);
981 // OldIdx may not correspond to an instruction any longer, so set MII to
982 // point to the next instruction after OldIdx, or MBB->end().
983 MachineBasicBlock::iterator MII = MBB->end();
984 if (MachineInstr *MI = Indexes->getInstructionFromIndex(
985 Indexes->getNextNonNullIndex(OldIdx)))
986 if (MI->getParent() == MBB)
989 MachineBasicBlock::iterator Begin = MBB->begin();
990 while (MII != Begin) {
991 if ((--MII)->isDebugValue())
993 SlotIndex Idx = Indexes->getInstructionIndex(MII);
995 // Stop searching when NewIdx is reached.
996 if (!SlotIndex::isEarlierInstr(NewIdx, Idx))
999 // Check if MII uses Reg.
1000 for (MIBundleOperands MO(MII); MO.isValid(); ++MO)
1002 TargetRegisterInfo::isPhysicalRegister(MO->getReg()) &&
1003 TRI.hasRegUnit(MO->getReg(), Reg))
1006 // Didn't reach NewIdx. It must be the first instruction in the block.
1011 void LiveIntervals::handleMove(MachineInstr* MI, bool UpdateFlags) {
1012 assert(!MI->isBundled() && "Can't handle bundled instructions yet.");
1013 SlotIndex OldIndex = Indexes->getInstructionIndex(MI);
1014 Indexes->removeMachineInstrFromMaps(MI);
1015 SlotIndex NewIndex = Indexes->insertMachineInstrInMaps(MI);
1016 assert(getMBBStartIdx(MI->getParent()) <= OldIndex &&
1017 OldIndex < getMBBEndIdx(MI->getParent()) &&
1018 "Cannot handle moves across basic block boundaries.");
1020 HMEditor HME(*this, *MRI, *TRI, OldIndex, NewIndex, UpdateFlags);
1021 HME.updateAllRanges(MI);
1024 void LiveIntervals::handleMoveIntoBundle(MachineInstr* MI,
1025 MachineInstr* BundleStart,
1027 SlotIndex OldIndex = Indexes->getInstructionIndex(MI);
1028 SlotIndex NewIndex = Indexes->getInstructionIndex(BundleStart);
1029 HMEditor HME(*this, *MRI, *TRI, OldIndex, NewIndex, UpdateFlags);
1030 HME.updateAllRanges(MI);
1034 LiveIntervals::repairIntervalsInRange(MachineBasicBlock *MBB,
1035 MachineBasicBlock::iterator Begin,
1036 MachineBasicBlock::iterator End,
1037 ArrayRef<unsigned> OrigRegs) {
1038 // Find anchor points, which are at the beginning/end of blocks or at
1039 // instructions that already have indexes.
1040 while (Begin != MBB->begin() && !Indexes->hasIndex(Begin))
1042 while (End != MBB->end() && !Indexes->hasIndex(End))
1046 if (End == MBB->end())
1047 endIdx = getMBBEndIdx(MBB).getPrevSlot();
1049 endIdx = getInstructionIndex(End);
1051 Indexes->repairIndexesInRange(MBB, Begin, End);
1053 for (MachineBasicBlock::iterator I = End; I != Begin;) {
1055 MachineInstr *MI = I;
1056 if (MI->isDebugValue())
1058 for (MachineInstr::const_mop_iterator MOI = MI->operands_begin(),
1059 MOE = MI->operands_end(); MOI != MOE; ++MOI) {
1061 TargetRegisterInfo::isVirtualRegister(MOI->getReg()) &&
1062 !hasInterval(MOI->getReg())) {
1063 LiveInterval &LI = getOrCreateInterval(MOI->getReg());
1064 computeVirtRegInterval(&LI);
1069 for (unsigned i = 0, e = OrigRegs.size(); i != e; ++i) {
1070 unsigned Reg = OrigRegs[i];
1071 if (!TargetRegisterInfo::isVirtualRegister(Reg))
1074 LiveInterval &LI = getInterval(Reg);
1075 // FIXME: Should we support undefs that gain defs?
1076 if (!LI.hasAtLeastOneValue())
1079 LiveInterval::iterator LII = LI.find(endIdx);
1080 SlotIndex lastUseIdx;
1081 if (LII != LI.end() && LII->start < endIdx)
1082 lastUseIdx = LII->end;
1086 for (MachineBasicBlock::iterator I = End; I != Begin;) {
1088 MachineInstr *MI = I;
1089 if (MI->isDebugValue())
1092 SlotIndex instrIdx = getInstructionIndex(MI);
1093 bool isStartValid = getInstructionFromIndex(LII->start);
1094 bool isEndValid = getInstructionFromIndex(LII->end);
1096 // FIXME: This doesn't currently handle early-clobber or multiple removed
1097 // defs inside of the region to repair.
1098 for (MachineInstr::mop_iterator OI = MI->operands_begin(),
1099 OE = MI->operands_end(); OI != OE; ++OI) {
1100 const MachineOperand &MO = *OI;
1101 if (!MO.isReg() || MO.getReg() != Reg)
1105 if (!isStartValid) {
1106 if (LII->end.isDead()) {
1107 SlotIndex prevStart;
1108 if (LII != LI.begin())
1109 prevStart = llvm::prior(LII)->start;
1111 // FIXME: This could be more efficient if there was a removeRange
1112 // method that returned an iterator.
1113 LI.removeRange(*LII, true);
1114 if (prevStart.isValid())
1115 LII = LI.find(prevStart);
1119 LII->start = instrIdx.getRegSlot();
1120 LII->valno->def = instrIdx.getRegSlot();
1121 if (MO.getSubReg() && !MO.isUndef())
1122 lastUseIdx = instrIdx.getRegSlot();
1124 lastUseIdx = SlotIndex();
1129 if (!lastUseIdx.isValid()) {
1130 VNInfo *VNI = LI.getNextValue(instrIdx.getRegSlot(),
1132 LiveRange LR(instrIdx.getRegSlot(), instrIdx.getDeadSlot(), VNI);
1133 LII = LI.addRange(LR);
1134 } else if (LII->start != instrIdx.getRegSlot()) {
1135 VNInfo *VNI = LI.getNextValue(instrIdx.getRegSlot(),
1137 LiveRange LR(instrIdx.getRegSlot(), lastUseIdx, VNI);
1138 LII = LI.addRange(LR);
1141 if (MO.getSubReg() && !MO.isUndef())
1142 lastUseIdx = instrIdx.getRegSlot();
1144 lastUseIdx = SlotIndex();
1145 } else if (MO.isUse()) {
1146 // FIXME: This should probably be handled outside of this branch,
1147 // either as part of the def case (for defs inside of the region) or
1148 // after the loop over the region.
1149 if (!isEndValid && !LII->end.isBlock())
1150 LII->end = instrIdx.getRegSlot();
1151 if (!lastUseIdx.isValid())
1152 lastUseIdx = instrIdx.getRegSlot();