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/CommandLine.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include "llvm/Target/TargetInstrInfo.h"
36 #include "llvm/Target/TargetMachine.h"
37 #include "llvm/Target/TargetRegisterInfo.h"
43 char LiveIntervals::ID = 0;
44 char &llvm::LiveIntervalsID = LiveIntervals::ID;
45 INITIALIZE_PASS_BEGIN(LiveIntervals, "liveintervals",
46 "Live Interval Analysis", false, false)
47 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
48 INITIALIZE_PASS_DEPENDENCY(LiveVariables)
49 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
50 INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
51 INITIALIZE_PASS_END(LiveIntervals, "liveintervals",
52 "Live Interval Analysis", false, false)
54 void LiveIntervals::getAnalysisUsage(AnalysisUsage &AU) const {
56 AU.addRequired<AliasAnalysis>();
57 AU.addPreserved<AliasAnalysis>();
58 // LiveVariables isn't really required by this analysis, it is only required
59 // here to make sure it is live during TwoAddressInstructionPass and
60 // PHIElimination. This is temporary.
61 AU.addRequired<LiveVariables>();
62 AU.addPreserved<LiveVariables>();
63 AU.addPreservedID(MachineLoopInfoID);
64 AU.addRequiredTransitiveID(MachineDominatorsID);
65 AU.addPreservedID(MachineDominatorsID);
66 AU.addPreserved<SlotIndexes>();
67 AU.addRequiredTransitive<SlotIndexes>();
68 MachineFunctionPass::getAnalysisUsage(AU);
71 LiveIntervals::LiveIntervals() : MachineFunctionPass(ID),
72 DomTree(0), LRCalc(0) {
73 initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
76 LiveIntervals::~LiveIntervals() {
80 void LiveIntervals::releaseMemory() {
81 // Free the live intervals themselves.
82 for (unsigned i = 0, e = VirtRegIntervals.size(); i != e; ++i)
83 delete VirtRegIntervals[TargetRegisterInfo::index2VirtReg(i)];
84 VirtRegIntervals.clear();
87 RegMaskBlocks.clear();
89 for (unsigned i = 0, e = RegUnitIntervals.size(); i != e; ++i)
90 delete RegUnitIntervals[i];
91 RegUnitIntervals.clear();
93 // Release VNInfo memory regions, VNInfo objects don't need to be dtor'd.
94 VNInfoAllocator.Reset();
97 /// runOnMachineFunction - Register allocate the whole function
99 bool LiveIntervals::runOnMachineFunction(MachineFunction &fn) {
101 MRI = &MF->getRegInfo();
102 TM = &fn.getTarget();
103 TRI = TM->getRegisterInfo();
104 TII = TM->getInstrInfo();
105 AA = &getAnalysis<AliasAnalysis>();
106 Indexes = &getAnalysis<SlotIndexes>();
107 DomTree = &getAnalysis<MachineDominatorTree>();
109 LRCalc = new LiveRangeCalc();
111 // Allocate space for all virtual registers.
112 VirtRegIntervals.resize(MRI->getNumVirtRegs());
116 computeLiveInRegUnits();
122 /// print - Implement the dump method.
123 void LiveIntervals::print(raw_ostream &OS, const Module* ) const {
124 OS << "********** INTERVALS **********\n";
126 // Dump the regunits.
127 for (unsigned i = 0, e = RegUnitIntervals.size(); i != e; ++i)
128 if (LiveInterval *LI = RegUnitIntervals[i])
129 OS << PrintRegUnit(i, TRI) << " = " << *LI << '\n';
131 // Dump the virtregs.
132 for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
133 unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
134 if (hasInterval(Reg))
135 OS << PrintReg(Reg) << " = " << getInterval(Reg) << '\n';
139 for (unsigned i = 0, e = RegMaskSlots.size(); i != e; ++i)
140 OS << ' ' << RegMaskSlots[i];
146 void LiveIntervals::printInstrs(raw_ostream &OS) const {
147 OS << "********** MACHINEINSTRS **********\n";
148 MF->print(OS, Indexes);
151 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
152 void LiveIntervals::dumpInstrs() const {
157 LiveInterval* LiveIntervals::createInterval(unsigned reg) {
158 float Weight = TargetRegisterInfo::isPhysicalRegister(reg) ? HUGE_VALF : 0.0F;
159 return new LiveInterval(reg, Weight);
163 /// computeVirtRegInterval - Compute the live interval of a virtual register,
164 /// based on defs and uses.
165 void LiveIntervals::computeVirtRegInterval(LiveInterval *LI) {
166 assert(LRCalc && "LRCalc not initialized.");
167 assert(LI->empty() && "Should only compute empty intervals.");
168 LRCalc->reset(MF, getSlotIndexes(), DomTree, &getVNInfoAllocator());
169 LRCalc->createDeadDefs(LI);
170 LRCalc->extendToUses(LI);
173 void LiveIntervals::computeVirtRegs() {
174 for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
175 unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
176 if (MRI->reg_nodbg_empty(Reg))
178 LiveInterval *LI = createInterval(Reg);
179 VirtRegIntervals[Reg] = LI;
180 computeVirtRegInterval(LI);
184 void LiveIntervals::computeRegMasks() {
185 RegMaskBlocks.resize(MF->getNumBlockIDs());
187 // Find all instructions with regmask operands.
188 for (MachineFunction::iterator MBBI = MF->begin(), E = MF->end();
190 MachineBasicBlock *MBB = MBBI;
191 std::pair<unsigned, unsigned> &RMB = RegMaskBlocks[MBB->getNumber()];
192 RMB.first = RegMaskSlots.size();
193 for (MachineBasicBlock::iterator MI = MBB->begin(), ME = MBB->end();
195 for (MIOperands MO(MI); MO.isValid(); ++MO) {
196 if (!MO->isRegMask())
198 RegMaskSlots.push_back(Indexes->getInstructionIndex(MI).getRegSlot());
199 RegMaskBits.push_back(MO->getRegMask());
201 // Compute the number of register mask instructions in this block.
202 RMB.second = RegMaskSlots.size() - RMB.first;
206 //===----------------------------------------------------------------------===//
207 // Register Unit Liveness
208 //===----------------------------------------------------------------------===//
210 // Fixed interference typically comes from ABI boundaries: Function arguments
211 // and return values are passed in fixed registers, and so are exception
212 // pointers entering landing pads. Certain instructions require values to be
213 // present in specific registers. That is also represented through fixed
217 /// computeRegUnitInterval - Compute the live interval of a register unit, based
218 /// on the uses and defs of aliasing registers. The interval should be empty,
219 /// or contain only dead phi-defs from ABI blocks.
220 void LiveIntervals::computeRegUnitInterval(LiveInterval *LI) {
221 unsigned Unit = LI->reg;
223 assert(LRCalc && "LRCalc not initialized.");
224 LRCalc->reset(MF, getSlotIndexes(), DomTree, &getVNInfoAllocator());
226 // The physregs aliasing Unit are the roots and their super-registers.
227 // Create all values as dead defs before extending to uses. Note that roots
228 // may share super-registers. That's OK because createDeadDefs() is
229 // idempotent. It is very rare for a register unit to have multiple roots, so
230 // uniquing super-registers is probably not worthwhile.
231 for (MCRegUnitRootIterator Roots(Unit, TRI); Roots.isValid(); ++Roots) {
232 unsigned Root = *Roots;
233 if (!MRI->reg_empty(Root))
234 LRCalc->createDeadDefs(LI, Root);
235 for (MCSuperRegIterator Supers(Root, TRI); Supers.isValid(); ++Supers) {
236 if (!MRI->reg_empty(*Supers))
237 LRCalc->createDeadDefs(LI, *Supers);
241 // Now extend LI to reach all uses.
242 // Ignore uses of reserved registers. We only track defs of those.
243 for (MCRegUnitRootIterator Roots(Unit, TRI); Roots.isValid(); ++Roots) {
244 unsigned Root = *Roots;
245 if (!MRI->isReserved(Root) && !MRI->reg_empty(Root))
246 LRCalc->extendToUses(LI, Root);
247 for (MCSuperRegIterator Supers(Root, TRI); Supers.isValid(); ++Supers) {
248 unsigned Reg = *Supers;
249 if (!MRI->isReserved(Reg) && !MRI->reg_empty(Reg))
250 LRCalc->extendToUses(LI, Reg);
256 /// computeLiveInRegUnits - Precompute the live ranges of any register units
257 /// that are live-in to an ABI block somewhere. Register values can appear
258 /// without a corresponding def when entering the entry block or a landing pad.
260 void LiveIntervals::computeLiveInRegUnits() {
261 RegUnitIntervals.resize(TRI->getNumRegUnits());
262 DEBUG(dbgs() << "Computing live-in reg-units in ABI blocks.\n");
264 // Keep track of the intervals allocated.
265 SmallVector<LiveInterval*, 8> NewIntvs;
267 // Check all basic blocks for live-ins.
268 for (MachineFunction::const_iterator MFI = MF->begin(), MFE = MF->end();
270 const MachineBasicBlock *MBB = MFI;
272 // We only care about ABI blocks: Entry + landing pads.
273 if ((MFI != MF->begin() && !MBB->isLandingPad()) || MBB->livein_empty())
276 // Create phi-defs at Begin for all live-in registers.
277 SlotIndex Begin = Indexes->getMBBStartIdx(MBB);
278 DEBUG(dbgs() << Begin << "\tBB#" << MBB->getNumber());
279 for (MachineBasicBlock::livein_iterator LII = MBB->livein_begin(),
280 LIE = MBB->livein_end(); LII != LIE; ++LII) {
281 for (MCRegUnitIterator Units(*LII, TRI); Units.isValid(); ++Units) {
282 unsigned Unit = *Units;
283 LiveInterval *Intv = RegUnitIntervals[Unit];
285 Intv = RegUnitIntervals[Unit] = new LiveInterval(Unit, HUGE_VALF);
286 NewIntvs.push_back(Intv);
288 VNInfo *VNI = Intv->createDeadDef(Begin, getVNInfoAllocator());
290 DEBUG(dbgs() << ' ' << PrintRegUnit(Unit, TRI) << '#' << VNI->id);
293 DEBUG(dbgs() << '\n');
295 DEBUG(dbgs() << "Created " << NewIntvs.size() << " new intervals.\n");
297 // Compute the 'normal' part of the intervals.
298 for (unsigned i = 0, e = NewIntvs.size(); i != e; ++i)
299 computeRegUnitInterval(NewIntvs[i]);
303 /// shrinkToUses - After removing some uses of a register, shrink its live
304 /// range to just the remaining uses. This method does not compute reaching
305 /// defs for new uses, and it doesn't remove dead defs.
306 bool LiveIntervals::shrinkToUses(LiveInterval *li,
307 SmallVectorImpl<MachineInstr*> *dead) {
308 DEBUG(dbgs() << "Shrink: " << *li << '\n');
309 assert(TargetRegisterInfo::isVirtualRegister(li->reg)
310 && "Can only shrink virtual registers");
311 // Find all the values used, including PHI kills.
312 SmallVector<std::pair<SlotIndex, VNInfo*>, 16> WorkList;
314 // Blocks that have already been added to WorkList as live-out.
315 SmallPtrSet<MachineBasicBlock*, 16> LiveOut;
317 // Visit all instructions reading li->reg.
318 for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(li->reg);
319 MachineInstr *UseMI = I.skipInstruction();) {
320 if (UseMI->isDebugValue() || !UseMI->readsVirtualRegister(li->reg))
322 SlotIndex Idx = getInstructionIndex(UseMI).getRegSlot();
323 LiveRangeQuery LRQ(*li, Idx);
324 VNInfo *VNI = LRQ.valueIn();
326 // This shouldn't happen: readsVirtualRegister returns true, but there is
327 // no live value. It is likely caused by a target getting <undef> flags
329 DEBUG(dbgs() << Idx << '\t' << *UseMI
330 << "Warning: Instr claims to read non-existent value in "
334 // Special case: An early-clobber tied operand reads and writes the
335 // register one slot early.
336 if (VNInfo *DefVNI = LRQ.valueDefined())
339 WorkList.push_back(std::make_pair(Idx, VNI));
342 // Create a new live interval with only minimal live segments per def.
343 LiveInterval NewLI(li->reg, 0);
344 for (LiveInterval::vni_iterator I = li->vni_begin(), E = li->vni_end();
349 NewLI.addRange(LiveRange(VNI->def, VNI->def.getDeadSlot(), VNI));
352 // Keep track of the PHIs that are in use.
353 SmallPtrSet<VNInfo*, 8> UsedPHIs;
355 // Extend intervals to reach all uses in WorkList.
356 while (!WorkList.empty()) {
357 SlotIndex Idx = WorkList.back().first;
358 VNInfo *VNI = WorkList.back().second;
360 const MachineBasicBlock *MBB = getMBBFromIndex(Idx.getPrevSlot());
361 SlotIndex BlockStart = getMBBStartIdx(MBB);
363 // Extend the live range for VNI to be live at Idx.
364 if (VNInfo *ExtVNI = NewLI.extendInBlock(BlockStart, Idx)) {
366 assert(ExtVNI == VNI && "Unexpected existing value number");
367 // Is this a PHIDef we haven't seen before?
368 if (!VNI->isPHIDef() || VNI->def != BlockStart || !UsedPHIs.insert(VNI))
370 // The PHI is live, make sure the predecessors are live-out.
371 for (MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(),
372 PE = MBB->pred_end(); PI != PE; ++PI) {
373 if (!LiveOut.insert(*PI))
375 SlotIndex Stop = getMBBEndIdx(*PI);
376 // A predecessor is not required to have a live-out value for a PHI.
377 if (VNInfo *PVNI = li->getVNInfoBefore(Stop))
378 WorkList.push_back(std::make_pair(Stop, PVNI));
383 // VNI is live-in to MBB.
384 DEBUG(dbgs() << " live-in at " << BlockStart << '\n');
385 NewLI.addRange(LiveRange(BlockStart, Idx, VNI));
387 // Make sure VNI is live-out from the predecessors.
388 for (MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(),
389 PE = MBB->pred_end(); PI != PE; ++PI) {
390 if (!LiveOut.insert(*PI))
392 SlotIndex Stop = getMBBEndIdx(*PI);
393 assert(li->getVNInfoBefore(Stop) == VNI &&
394 "Wrong value out of predecessor");
395 WorkList.push_back(std::make_pair(Stop, VNI));
399 // Handle dead values.
400 bool CanSeparate = false;
401 for (LiveInterval::vni_iterator I = li->vni_begin(), E = li->vni_end();
406 LiveInterval::iterator LII = NewLI.FindLiveRangeContaining(VNI->def);
407 assert(LII != NewLI.end() && "Missing live range for PHI");
408 if (LII->end != VNI->def.getDeadSlot())
410 if (VNI->isPHIDef()) {
411 // This is a dead PHI. Remove it.
413 NewLI.removeRange(*LII);
414 DEBUG(dbgs() << "Dead PHI at " << VNI->def << " may separate interval\n");
417 // This is a dead def. Make sure the instruction knows.
418 MachineInstr *MI = getInstructionFromIndex(VNI->def);
419 assert(MI && "No instruction defining live value");
420 MI->addRegisterDead(li->reg, TRI);
421 if (dead && MI->allDefsAreDead()) {
422 DEBUG(dbgs() << "All defs dead: " << VNI->def << '\t' << *MI);
428 // Move the trimmed ranges back.
429 li->ranges.swap(NewLI.ranges);
430 DEBUG(dbgs() << "Shrunk: " << *li << '\n');
434 void LiveIntervals::extendToIndices(LiveInterval *LI,
435 ArrayRef<SlotIndex> Indices) {
436 assert(LRCalc && "LRCalc not initialized.");
437 LRCalc->reset(MF, getSlotIndexes(), DomTree, &getVNInfoAllocator());
438 for (unsigned i = 0, e = Indices.size(); i != e; ++i)
439 LRCalc->extend(LI, Indices[i]);
442 void LiveIntervals::pruneValue(LiveInterval *LI, SlotIndex Kill,
443 SmallVectorImpl<SlotIndex> *EndPoints) {
444 LiveRangeQuery LRQ(*LI, Kill);
445 VNInfo *VNI = LRQ.valueOut();
449 MachineBasicBlock *KillMBB = Indexes->getMBBFromIndex(Kill);
450 SlotIndex MBBStart, MBBEnd;
451 tie(MBBStart, MBBEnd) = Indexes->getMBBRange(KillMBB);
453 // If VNI isn't live out from KillMBB, the value is trivially pruned.
454 if (LRQ.endPoint() < MBBEnd) {
455 LI->removeRange(Kill, LRQ.endPoint());
456 if (EndPoints) EndPoints->push_back(LRQ.endPoint());
460 // VNI is live out of KillMBB.
461 LI->removeRange(Kill, MBBEnd);
462 if (EndPoints) EndPoints->push_back(MBBEnd);
464 // Find all blocks that are reachable from KillMBB without leaving VNI's live
465 // range. It is possible that KillMBB itself is reachable, so start a DFS
466 // from each successor.
467 typedef SmallPtrSet<MachineBasicBlock*, 9> VisitedTy;
469 for (MachineBasicBlock::succ_iterator
470 SuccI = KillMBB->succ_begin(), SuccE = KillMBB->succ_end();
471 SuccI != SuccE; ++SuccI) {
472 for (df_ext_iterator<MachineBasicBlock*, VisitedTy>
473 I = df_ext_begin(*SuccI, Visited), E = df_ext_end(*SuccI, Visited);
475 MachineBasicBlock *MBB = *I;
477 // Check if VNI is live in to MBB.
478 tie(MBBStart, MBBEnd) = Indexes->getMBBRange(MBB);
479 LiveRangeQuery LRQ(*LI, MBBStart);
480 if (LRQ.valueIn() != VNI) {
481 // This block isn't part of the VNI live range. Prune the search.
486 // Prune the search if VNI is killed in MBB.
487 if (LRQ.endPoint() < MBBEnd) {
488 LI->removeRange(MBBStart, LRQ.endPoint());
489 if (EndPoints) EndPoints->push_back(LRQ.endPoint());
494 // VNI is live through MBB.
495 LI->removeRange(MBBStart, MBBEnd);
496 if (EndPoints) EndPoints->push_back(MBBEnd);
502 //===----------------------------------------------------------------------===//
503 // Register allocator hooks.
506 void LiveIntervals::addKillFlags(const VirtRegMap *VRM) {
507 // Keep track of regunit ranges.
508 SmallVector<std::pair<LiveInterval*, LiveInterval::iterator>, 8> RU;
510 for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
511 unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
512 if (MRI->reg_nodbg_empty(Reg))
514 LiveInterval *LI = &getInterval(Reg);
518 // Find the regunit intervals for the assigned register. They may overlap
519 // the virtual register live range, cancelling any kills.
521 for (MCRegUnitIterator Units(VRM->getPhys(Reg), TRI); Units.isValid();
523 LiveInterval *RUInt = &getRegUnit(*Units);
526 RU.push_back(std::make_pair(RUInt, RUInt->find(LI->begin()->end)));
529 // Every instruction that kills Reg corresponds to a live range end point.
530 for (LiveInterval::iterator RI = LI->begin(), RE = LI->end(); RI != RE;
532 // A block index indicates an MBB edge.
533 if (RI->end.isBlock())
535 MachineInstr *MI = getInstructionFromIndex(RI->end);
539 // Check if any of the reguints are live beyond the end of RI. That could
540 // happen when a physreg is defined as a copy of a virtreg:
542 // %EAX = COPY %vreg5
543 // FOO %vreg5 <--- MI, cancel kill because %EAX is live.
546 // There should be no kill flag on FOO when %vreg5 is rewritten as %EAX.
547 bool CancelKill = false;
548 for (unsigned u = 0, e = RU.size(); u != e; ++u) {
549 LiveInterval *RInt = RU[u].first;
550 LiveInterval::iterator &I = RU[u].second;
551 if (I == RInt->end())
553 I = RInt->advanceTo(I, RI->end);
554 if (I == RInt->end() || I->start >= RI->end)
556 // I is overlapping RI.
561 MI->clearRegisterKills(Reg, NULL);
563 MI->addRegisterKilled(Reg, NULL);
569 LiveIntervals::intervalIsInOneMBB(const LiveInterval &LI) const {
570 // A local live range must be fully contained inside the block, meaning it is
571 // defined and killed at instructions, not at block boundaries. It is not
572 // live in or or out of any block.
574 // It is technically possible to have a PHI-defined live range identical to a
575 // single block, but we are going to return false in that case.
577 SlotIndex Start = LI.beginIndex();
581 SlotIndex Stop = LI.endIndex();
585 // getMBBFromIndex doesn't need to search the MBB table when both indexes
586 // belong to proper instructions.
587 MachineBasicBlock *MBB1 = Indexes->getMBBFromIndex(Start);
588 MachineBasicBlock *MBB2 = Indexes->getMBBFromIndex(Stop);
589 return MBB1 == MBB2 ? MBB1 : NULL;
593 LiveIntervals::hasPHIKill(const LiveInterval &LI, const VNInfo *VNI) const {
594 for (LiveInterval::const_vni_iterator I = LI.vni_begin(), E = LI.vni_end();
596 const VNInfo *PHI = *I;
597 if (PHI->isUnused() || !PHI->isPHIDef())
599 const MachineBasicBlock *PHIMBB = getMBBFromIndex(PHI->def);
600 // Conservatively return true instead of scanning huge predecessor lists.
601 if (PHIMBB->pred_size() > 100)
603 for (MachineBasicBlock::const_pred_iterator
604 PI = PHIMBB->pred_begin(), PE = PHIMBB->pred_end(); PI != PE; ++PI)
605 if (VNI == LI.getVNInfoBefore(Indexes->getMBBEndIdx(*PI)))
612 LiveIntervals::getSpillWeight(bool isDef, bool isUse, unsigned loopDepth) {
613 // Limit the loop depth ridiculousness.
617 // The loop depth is used to roughly estimate the number of times the
618 // instruction is executed. Something like 10^d is simple, but will quickly
619 // overflow a float. This expression behaves like 10^d for small d, but is
620 // more tempered for large d. At d=200 we get 6.7e33 which leaves a bit of
621 // headroom before overflow.
622 // By the way, powf() might be unavailable here. For consistency,
623 // We may take pow(double,double).
624 float lc = std::pow(1 + (100.0 / (loopDepth + 10)), (double)loopDepth);
626 return (isDef + isUse) * lc;
629 LiveRange LiveIntervals::addLiveRangeToEndOfBlock(unsigned reg,
630 MachineInstr* startInst) {
631 LiveInterval& Interval = getOrCreateInterval(reg);
632 VNInfo* VN = Interval.getNextValue(
633 SlotIndex(getInstructionIndex(startInst).getRegSlot()),
634 getVNInfoAllocator());
636 SlotIndex(getInstructionIndex(startInst).getRegSlot()),
637 getMBBEndIdx(startInst->getParent()), VN);
638 Interval.addRange(LR);
644 //===----------------------------------------------------------------------===//
645 // Register mask functions
646 //===----------------------------------------------------------------------===//
648 bool LiveIntervals::checkRegMaskInterference(LiveInterval &LI,
649 BitVector &UsableRegs) {
652 LiveInterval::iterator LiveI = LI.begin(), LiveE = LI.end();
654 // Use a smaller arrays for local live ranges.
655 ArrayRef<SlotIndex> Slots;
656 ArrayRef<const uint32_t*> Bits;
657 if (MachineBasicBlock *MBB = intervalIsInOneMBB(LI)) {
658 Slots = getRegMaskSlotsInBlock(MBB->getNumber());
659 Bits = getRegMaskBitsInBlock(MBB->getNumber());
661 Slots = getRegMaskSlots();
662 Bits = getRegMaskBits();
665 // We are going to enumerate all the register mask slots contained in LI.
666 // Start with a binary search of RegMaskSlots to find a starting point.
667 ArrayRef<SlotIndex>::iterator SlotI =
668 std::lower_bound(Slots.begin(), Slots.end(), LiveI->start);
669 ArrayRef<SlotIndex>::iterator SlotE = Slots.end();
671 // No slots in range, LI begins after the last call.
677 assert(*SlotI >= LiveI->start);
678 // Loop over all slots overlapping this segment.
679 while (*SlotI < LiveI->end) {
680 // *SlotI overlaps LI. Collect mask bits.
682 // This is the first overlap. Initialize UsableRegs to all ones.
684 UsableRegs.resize(TRI->getNumRegs(), true);
687 // Remove usable registers clobbered by this mask.
688 UsableRegs.clearBitsNotInMask(Bits[SlotI-Slots.begin()]);
689 if (++SlotI == SlotE)
692 // *SlotI is beyond the current LI segment.
693 LiveI = LI.advanceTo(LiveI, *SlotI);
696 // Advance SlotI until it overlaps.
697 while (*SlotI < LiveI->start)
698 if (++SlotI == SlotE)
703 //===----------------------------------------------------------------------===//
704 // IntervalUpdate class.
705 //===----------------------------------------------------------------------===//
707 // HMEditor is a toolkit used by handleMove to trim or extend live intervals.
708 class LiveIntervals::HMEditor {
711 const MachineRegisterInfo& MRI;
712 const TargetRegisterInfo& TRI;
715 SmallPtrSet<LiveInterval*, 8> Updated;
719 HMEditor(LiveIntervals& LIS, const MachineRegisterInfo& MRI,
720 const TargetRegisterInfo& TRI,
721 SlotIndex OldIdx, SlotIndex NewIdx, bool UpdateFlags)
722 : LIS(LIS), MRI(MRI), TRI(TRI), OldIdx(OldIdx), NewIdx(NewIdx),
723 UpdateFlags(UpdateFlags) {}
725 // FIXME: UpdateFlags is a workaround that creates live intervals for all
726 // physregs, even those that aren't needed for regalloc, in order to update
727 // kill flags. This is wasteful. Eventually, LiveVariables will strip all kill
728 // flags, and postRA passes will use a live register utility instead.
729 LiveInterval *getRegUnitLI(unsigned Unit) {
731 return &LIS.getRegUnit(Unit);
732 return LIS.getCachedRegUnit(Unit);
735 /// Update all live ranges touched by MI, assuming a move from OldIdx to
737 void updateAllRanges(MachineInstr *MI) {
738 DEBUG(dbgs() << "handleMove " << OldIdx << " -> " << NewIdx << ": " << *MI);
739 bool hasRegMask = false;
740 for (MIOperands MO(MI); MO.isValid(); ++MO) {
745 // Aggressively clear all kill flags.
746 // They are reinserted by VirtRegRewriter.
748 MO->setIsKill(false);
750 unsigned Reg = MO->getReg();
753 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
754 updateRange(LIS.getInterval(Reg));
758 // For physregs, only update the regunits that actually have a
759 // precomputed live range.
760 for (MCRegUnitIterator Units(Reg, &TRI); Units.isValid(); ++Units)
761 if (LiveInterval *LI = getRegUnitLI(*Units))
765 updateRegMaskSlots();
769 /// Update a single live range, assuming an instruction has been moved from
770 /// OldIdx to NewIdx.
771 void updateRange(LiveInterval &LI) {
772 if (!Updated.insert(&LI))
776 if (TargetRegisterInfo::isVirtualRegister(LI.reg))
777 dbgs() << PrintReg(LI.reg);
779 dbgs() << PrintRegUnit(LI.reg, &TRI);
780 dbgs() << ":\t" << LI << '\n';
782 if (SlotIndex::isEarlierInstr(OldIdx, NewIdx))
786 DEBUG(dbgs() << " -->\t" << LI << '\n');
790 /// Update LI to reflect an instruction has been moved downwards from OldIdx
793 /// 1. Live def at OldIdx:
794 /// Move def to NewIdx, assert endpoint after NewIdx.
796 /// 2. Live def at OldIdx, killed at NewIdx:
797 /// Change to dead def at NewIdx.
798 /// (Happens when bundling def+kill together).
800 /// 3. Dead def at OldIdx:
801 /// Move def to NewIdx, possibly across another live value.
803 /// 4. Def at OldIdx AND at NewIdx:
804 /// Remove live range [OldIdx;NewIdx) and value defined at OldIdx.
805 /// (Happens when bundling multiple defs together).
807 /// 5. Value read at OldIdx, killed before NewIdx:
808 /// Extend kill to NewIdx.
810 void handleMoveDown(LiveInterval &LI) {
811 // First look for a kill at OldIdx.
812 LiveInterval::iterator I = LI.find(OldIdx.getBaseIndex());
813 LiveInterval::iterator E = LI.end();
814 // Is LI even live at OldIdx?
815 if (I == E || SlotIndex::isEarlierInstr(OldIdx, I->start))
818 // Handle a live-in value.
819 if (!SlotIndex::isSameInstr(I->start, OldIdx)) {
820 bool isKill = SlotIndex::isSameInstr(OldIdx, I->end);
821 // If the live-in value already extends to NewIdx, there is nothing to do.
822 if (!SlotIndex::isEarlierInstr(I->end, NewIdx))
824 // Aggressively remove all kill flags from the old kill point.
825 // Kill flags shouldn't be used while live intervals exist, they will be
826 // reinserted by VirtRegRewriter.
827 if (MachineInstr *KillMI = LIS.getInstructionFromIndex(I->end))
828 for (MIBundleOperands MO(KillMI); MO.isValid(); ++MO)
829 if (MO->isReg() && MO->isUse())
830 MO->setIsKill(false);
831 // Adjust I->end to reach NewIdx. This may temporarily make LI invalid by
832 // overlapping ranges. Case 5 above.
833 I->end = NewIdx.getRegSlot(I->end.isEarlyClobber());
834 // If this was a kill, there may also be a def. Otherwise we're done.
840 // Check for a def at OldIdx.
841 if (I == E || !SlotIndex::isSameInstr(OldIdx, I->start))
843 // We have a def at OldIdx.
844 VNInfo *DefVNI = I->valno;
845 assert(DefVNI->def == I->start && "Inconsistent def");
846 DefVNI->def = NewIdx.getRegSlot(I->start.isEarlyClobber());
847 // If the defined value extends beyond NewIdx, just move the def down.
848 // This is case 1 above.
849 if (SlotIndex::isEarlierInstr(NewIdx, I->end)) {
850 I->start = DefVNI->def;
853 // The remaining possibilities are now:
854 // 2. Live def at OldIdx, killed at NewIdx: isSameInstr(I->end, NewIdx).
855 // 3. Dead def at OldIdx: I->end = OldIdx.getDeadSlot().
856 // In either case, it is possible that there is an existing def at NewIdx.
857 assert((I->end == OldIdx.getDeadSlot() ||
858 SlotIndex::isSameInstr(I->end, NewIdx)) &&
859 "Cannot move def below kill");
860 LiveInterval::iterator NewI = LI.advanceTo(I, NewIdx.getRegSlot());
861 if (NewI != E && SlotIndex::isSameInstr(NewI->start, NewIdx)) {
862 // There is an existing def at NewIdx, case 4 above. The def at OldIdx is
863 // coalesced into that value.
864 assert(NewI->valno != DefVNI && "Multiple defs of value?");
865 LI.removeValNo(DefVNI);
868 // There was no existing def at NewIdx. Turn *I into a dead def at NewIdx.
869 // If the def at OldIdx was dead, we allow it to be moved across other LI
870 // values. The new range should be placed immediately before NewI, move any
871 // intermediate ranges up.
872 assert(NewI != I && "Inconsistent iterators");
873 std::copy(llvm::next(I), NewI, I);
874 *llvm::prior(NewI) = LiveRange(DefVNI->def, NewIdx.getDeadSlot(), DefVNI);
877 /// Update LI to reflect an instruction has been moved upwards from OldIdx
880 /// 1. Live def at OldIdx:
881 /// Hoist def to NewIdx.
883 /// 2. Dead def at OldIdx:
884 /// Hoist def+end to NewIdx, possibly move across other values.
886 /// 3. Dead def at OldIdx AND existing def at NewIdx:
887 /// Remove value defined at OldIdx, coalescing it with existing value.
889 /// 4. Live def at OldIdx AND existing def at NewIdx:
890 /// Remove value defined at NewIdx, hoist OldIdx def to NewIdx.
891 /// (Happens when bundling multiple defs together).
893 /// 5. Value killed at OldIdx:
894 /// Hoist kill to NewIdx, then scan for last kill between NewIdx and
897 void handleMoveUp(LiveInterval &LI) {
898 // First look for a kill at OldIdx.
899 LiveInterval::iterator I = LI.find(OldIdx.getBaseIndex());
900 LiveInterval::iterator E = LI.end();
901 // Is LI even live at OldIdx?
902 if (I == E || SlotIndex::isEarlierInstr(OldIdx, I->start))
905 // Handle a live-in value.
906 if (!SlotIndex::isSameInstr(I->start, OldIdx)) {
907 // If the live-in value isn't killed here, there is nothing to do.
908 if (!SlotIndex::isSameInstr(OldIdx, I->end))
910 // Adjust I->end to end at NewIdx. If we are hoisting a kill above
911 // another use, we need to search for that use. Case 5 above.
912 I->end = NewIdx.getRegSlot(I->end.isEarlyClobber());
914 // If OldIdx also defines a value, there couldn't have been another use.
915 if (I == E || !SlotIndex::isSameInstr(I->start, OldIdx)) {
916 // No def, search for the new kill.
917 // This can never be an early clobber kill since there is no def.
918 llvm::prior(I)->end = findLastUseBefore(LI.reg).getRegSlot();
923 // Now deal with the def at OldIdx.
924 assert(I != E && SlotIndex::isSameInstr(I->start, OldIdx) && "No def?");
925 VNInfo *DefVNI = I->valno;
926 assert(DefVNI->def == I->start && "Inconsistent def");
927 DefVNI->def = NewIdx.getRegSlot(I->start.isEarlyClobber());
929 // Check for an existing def at NewIdx.
930 LiveInterval::iterator NewI = LI.find(NewIdx.getRegSlot());
931 if (SlotIndex::isSameInstr(NewI->start, NewIdx)) {
932 assert(NewI->valno != DefVNI && "Same value defined more than once?");
933 // There is an existing def at NewIdx.
934 if (I->end.isDead()) {
935 // Case 3: Remove the dead def at OldIdx.
936 LI.removeValNo(DefVNI);
939 // Case 4: Replace def at NewIdx with live def at OldIdx.
940 I->start = DefVNI->def;
941 LI.removeValNo(NewI->valno);
945 // There is no existing def at NewIdx. Hoist DefVNI.
946 if (!I->end.isDead()) {
947 // Leave the end point of a live def.
948 I->start = DefVNI->def;
952 // DefVNI is a dead def. It may have been moved across other values in LI,
953 // so move I up to NewI. Slide [NewI;I) down one position.
954 std::copy_backward(NewI, I, llvm::next(I));
955 *NewI = LiveRange(DefVNI->def, NewIdx.getDeadSlot(), DefVNI);
958 void updateRegMaskSlots() {
959 SmallVectorImpl<SlotIndex>::iterator RI =
960 std::lower_bound(LIS.RegMaskSlots.begin(), LIS.RegMaskSlots.end(),
962 assert(RI != LIS.RegMaskSlots.end() && *RI == OldIdx.getRegSlot() &&
963 "No RegMask at OldIdx.");
964 *RI = NewIdx.getRegSlot();
965 assert((RI == LIS.RegMaskSlots.begin() ||
966 SlotIndex::isEarlierInstr(*llvm::prior(RI), *RI)) &&
967 "Cannot move regmask instruction above another call");
968 assert((llvm::next(RI) == LIS.RegMaskSlots.end() ||
969 SlotIndex::isEarlierInstr(*RI, *llvm::next(RI))) &&
970 "Cannot move regmask instruction below another call");
973 // Return the last use of reg between NewIdx and OldIdx.
974 SlotIndex findLastUseBefore(unsigned Reg) {
976 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
977 SlotIndex LastUse = NewIdx;
978 for (MachineRegisterInfo::use_nodbg_iterator
979 UI = MRI.use_nodbg_begin(Reg),
980 UE = MRI.use_nodbg_end();
981 UI != UE; UI.skipInstruction()) {
982 const MachineInstr* MI = &*UI;
983 SlotIndex InstSlot = LIS.getSlotIndexes()->getInstructionIndex(MI);
984 if (InstSlot > LastUse && InstSlot < OldIdx)
990 // This is a regunit interval, so scanning the use list could be very
991 // expensive. Scan upwards from OldIdx instead.
992 assert(NewIdx < OldIdx && "Expected upwards move");
993 SlotIndexes *Indexes = LIS.getSlotIndexes();
994 MachineBasicBlock *MBB = Indexes->getMBBFromIndex(NewIdx);
996 // OldIdx may not correspond to an instruction any longer, so set MII to
997 // point to the next instruction after OldIdx, or MBB->end().
998 MachineBasicBlock::iterator MII = MBB->end();
999 if (MachineInstr *MI = Indexes->getInstructionFromIndex(
1000 Indexes->getNextNonNullIndex(OldIdx)))
1001 if (MI->getParent() == MBB)
1004 MachineBasicBlock::iterator Begin = MBB->begin();
1005 while (MII != Begin) {
1006 if ((--MII)->isDebugValue())
1008 SlotIndex Idx = Indexes->getInstructionIndex(MII);
1010 // Stop searching when NewIdx is reached.
1011 if (!SlotIndex::isEarlierInstr(NewIdx, Idx))
1014 // Check if MII uses Reg.
1015 for (MIBundleOperands MO(MII); MO.isValid(); ++MO)
1017 TargetRegisterInfo::isPhysicalRegister(MO->getReg()) &&
1018 TRI.hasRegUnit(MO->getReg(), Reg))
1021 // Didn't reach NewIdx. It must be the first instruction in the block.
1026 void LiveIntervals::handleMove(MachineInstr* MI, bool UpdateFlags) {
1027 assert(!MI->isBundled() && "Can't handle bundled instructions yet.");
1028 SlotIndex OldIndex = Indexes->getInstructionIndex(MI);
1029 Indexes->removeMachineInstrFromMaps(MI);
1030 SlotIndex NewIndex = Indexes->insertMachineInstrInMaps(MI);
1031 assert(getMBBStartIdx(MI->getParent()) <= OldIndex &&
1032 OldIndex < getMBBEndIdx(MI->getParent()) &&
1033 "Cannot handle moves across basic block boundaries.");
1035 HMEditor HME(*this, *MRI, *TRI, OldIndex, NewIndex, UpdateFlags);
1036 HME.updateAllRanges(MI);
1039 void LiveIntervals::handleMoveIntoBundle(MachineInstr* MI,
1040 MachineInstr* BundleStart,
1042 SlotIndex OldIndex = Indexes->getInstructionIndex(MI);
1043 SlotIndex NewIndex = Indexes->getInstructionIndex(BundleStart);
1044 HMEditor HME(*this, *MRI, *TRI, OldIndex, NewIndex, UpdateFlags);
1045 HME.updateAllRanges(MI);
1049 LiveIntervals::repairIntervalsInRange(MachineBasicBlock *MBB,
1050 MachineBasicBlock::iterator Begin,
1051 MachineBasicBlock::iterator End,
1052 ArrayRef<unsigned> OrigRegs) {
1053 // Find anchor points, which are at the beginning/end of blocks or at
1054 // instructions that already have indexes.
1055 while (Begin != MBB->begin() && !Indexes->hasIndex(Begin))
1057 while (End != MBB->end() && !Indexes->hasIndex(End))
1061 if (End == MBB->end())
1062 endIdx = getMBBEndIdx(MBB).getPrevSlot();
1064 endIdx = getInstructionIndex(End);
1066 Indexes->repairIndexesInRange(MBB, Begin, End);
1068 for (MachineBasicBlock::iterator I = End; I != Begin;) {
1070 MachineInstr *MI = I;
1071 if (MI->isDebugValue())
1073 for (MachineInstr::const_mop_iterator MOI = MI->operands_begin(),
1074 MOE = MI->operands_end(); MOI != MOE; ++MOI) {
1076 TargetRegisterInfo::isVirtualRegister(MOI->getReg()) &&
1077 !hasInterval(MOI->getReg())) {
1078 LiveInterval &LI = getOrCreateInterval(MOI->getReg());
1079 computeVirtRegInterval(&LI);
1084 for (unsigned i = 0, e = OrigRegs.size(); i != e; ++i) {
1085 unsigned Reg = OrigRegs[i];
1086 if (!TargetRegisterInfo::isVirtualRegister(Reg))
1089 LiveInterval &LI = getInterval(Reg);
1090 // FIXME: Should we support undefs that gain defs?
1091 if (!LI.hasAtLeastOneValue())
1094 LiveInterval::iterator LII = LI.find(endIdx);
1095 SlotIndex lastUseIdx;
1096 if (LII != LI.end() && LII->start < endIdx)
1097 lastUseIdx = LII->end;
1101 for (MachineBasicBlock::iterator I = End; I != Begin;) {
1103 MachineInstr *MI = I;
1104 if (MI->isDebugValue())
1107 SlotIndex instrIdx = getInstructionIndex(MI);
1108 bool isStartValid = getInstructionFromIndex(LII->start);
1109 bool isEndValid = getInstructionFromIndex(LII->end);
1111 // FIXME: This doesn't currently handle early-clobber or multiple removed
1112 // defs inside of the region to repair.
1113 for (MachineInstr::mop_iterator OI = MI->operands_begin(),
1114 OE = MI->operands_end(); OI != OE; ++OI) {
1115 const MachineOperand &MO = *OI;
1116 if (!MO.isReg() || MO.getReg() != Reg)
1120 if (!isStartValid) {
1121 if (LII->end.isDead()) {
1122 SlotIndex prevStart;
1123 if (LII != LI.begin())
1124 prevStart = llvm::prior(LII)->start;
1126 // FIXME: This could be more efficient if there was a removeRange
1127 // method that returned an iterator.
1128 LI.removeRange(*LII, true);
1129 if (prevStart.isValid())
1130 LII = LI.find(prevStart);
1134 LII->start = instrIdx.getRegSlot();
1135 LII->valno->def = instrIdx.getRegSlot();
1136 if (MO.getSubReg() && !MO.isUndef())
1137 lastUseIdx = instrIdx.getRegSlot();
1139 lastUseIdx = SlotIndex();
1144 if (!lastUseIdx.isValid()) {
1145 VNInfo *VNI = LI.getNextValue(instrIdx.getRegSlot(),
1147 LiveRange LR(instrIdx.getRegSlot(), instrIdx.getDeadSlot(), VNI);
1148 LII = LI.addRange(LR);
1149 } else if (LII->start != instrIdx.getRegSlot()) {
1150 VNInfo *VNI = LI.getNextValue(instrIdx.getRegSlot(),
1152 LiveRange LR(instrIdx.getRegSlot(), lastUseIdx, VNI);
1153 LII = LI.addRange(LR);
1156 if (MO.getSubReg() && !MO.isUndef())
1157 lastUseIdx = instrIdx.getRegSlot();
1159 lastUseIdx = SlotIndex();
1160 } else if (MO.isUse()) {
1161 // FIXME: This should probably be handled outside of this branch,
1162 // either as part of the def case (for defs inside of the region) or
1163 // after the loop over the region.
1164 if (!isEndValid && !LII->end.isBlock())
1165 LII->end = instrIdx.getRegSlot();
1166 if (!lastUseIdx.isValid())
1167 lastUseIdx = instrIdx.getRegSlot();