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 "llvm/Value.h"
21 #include "llvm/Analysis/AliasAnalysis.h"
22 #include "llvm/CodeGen/LiveVariables.h"
23 #include "llvm/CodeGen/MachineInstr.h"
24 #include "llvm/CodeGen/MachineLoopInfo.h"
25 #include "llvm/CodeGen/MachineRegisterInfo.h"
26 #include "llvm/CodeGen/Passes.h"
27 #include "llvm/CodeGen/ProcessImplicitDefs.h"
28 #include "llvm/Target/TargetRegisterInfo.h"
29 #include "llvm/Target/TargetInstrInfo.h"
30 #include "llvm/Target/TargetMachine.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/ADT/Statistic.h"
36 #include "llvm/ADT/STLExtras.h"
42 // Hidden options for help debugging.
43 static cl::opt<bool> DisableReMat("disable-rematerialization",
44 cl::init(false), cl::Hidden);
46 STATISTIC(numIntervals , "Number of original intervals");
48 char LiveIntervals::ID = 0;
49 INITIALIZE_PASS_BEGIN(LiveIntervals, "liveintervals",
50 "Live Interval Analysis", false, false)
51 INITIALIZE_PASS_DEPENDENCY(LiveVariables)
52 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
53 INITIALIZE_PASS_DEPENDENCY(PHIElimination)
54 INITIALIZE_PASS_DEPENDENCY(TwoAddressInstructionPass)
55 INITIALIZE_PASS_DEPENDENCY(ProcessImplicitDefs)
56 INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
57 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
58 INITIALIZE_PASS_END(LiveIntervals, "liveintervals",
59 "Live Interval Analysis", false, false)
61 void LiveIntervals::getAnalysisUsage(AnalysisUsage &AU) const {
63 AU.addRequired<AliasAnalysis>();
64 AU.addPreserved<AliasAnalysis>();
65 AU.addRequired<LiveVariables>();
66 AU.addPreserved<LiveVariables>();
67 AU.addRequired<MachineLoopInfo>();
68 AU.addPreserved<MachineLoopInfo>();
69 AU.addPreservedID(MachineDominatorsID);
72 AU.addPreservedID(PHIEliminationID);
73 AU.addRequiredID(PHIEliminationID);
76 AU.addRequiredID(TwoAddressInstructionPassID);
77 AU.addPreserved<ProcessImplicitDefs>();
78 AU.addRequired<ProcessImplicitDefs>();
79 AU.addPreserved<SlotIndexes>();
80 AU.addRequiredTransitive<SlotIndexes>();
81 MachineFunctionPass::getAnalysisUsage(AU);
84 void LiveIntervals::releaseMemory() {
85 // Free the live intervals themselves.
86 for (DenseMap<unsigned, LiveInterval*>::iterator I = r2iMap_.begin(),
87 E = r2iMap_.end(); I != E; ++I)
92 // Release VNInfo memory regions, VNInfo objects don't need to be dtor'd.
93 VNInfoAllocator.Reset();
96 /// runOnMachineFunction - Register allocate the whole function
98 bool LiveIntervals::runOnMachineFunction(MachineFunction &fn) {
100 mri_ = &mf_->getRegInfo();
101 tm_ = &fn.getTarget();
102 tri_ = tm_->getRegisterInfo();
103 tii_ = tm_->getInstrInfo();
104 aa_ = &getAnalysis<AliasAnalysis>();
105 lv_ = &getAnalysis<LiveVariables>();
106 indexes_ = &getAnalysis<SlotIndexes>();
107 allocatableRegs_ = tri_->getAllocatableSet(fn);
111 numIntervals += getNumIntervals();
117 /// print - Implement the dump method.
118 void LiveIntervals::print(raw_ostream &OS, const Module* ) const {
119 OS << "********** INTERVALS **********\n";
120 for (const_iterator I = begin(), E = end(); I != E; ++I) {
121 I->second->print(OS, tri_);
128 void LiveIntervals::printInstrs(raw_ostream &OS) const {
129 OS << "********** MACHINEINSTRS **********\n";
130 mf_->print(OS, indexes_);
133 void LiveIntervals::dumpInstrs() const {
138 bool MultipleDefsBySameMI(const MachineInstr &MI, unsigned MOIdx) {
139 unsigned Reg = MI.getOperand(MOIdx).getReg();
140 for (unsigned i = MOIdx+1, e = MI.getNumOperands(); i < e; ++i) {
141 const MachineOperand &MO = MI.getOperand(i);
144 if (MO.getReg() == Reg && MO.isDef()) {
145 assert(MI.getOperand(MOIdx).getSubReg() != MO.getSubReg() &&
146 MI.getOperand(MOIdx).getSubReg() &&
147 (MO.getSubReg() || MO.isImplicit()));
154 /// isPartialRedef - Return true if the specified def at the specific index is
155 /// partially re-defining the specified live interval. A common case of this is
156 /// a definition of the sub-register.
157 bool LiveIntervals::isPartialRedef(SlotIndex MIIdx, MachineOperand &MO,
158 LiveInterval &interval) {
159 if (!MO.getSubReg() || MO.isEarlyClobber())
162 SlotIndex RedefIndex = MIIdx.getRegSlot();
163 const LiveRange *OldLR =
164 interval.getLiveRangeContaining(RedefIndex.getRegSlot(true));
165 MachineInstr *DefMI = getInstructionFromIndex(OldLR->valno->def);
167 return DefMI->findRegisterDefOperandIdx(interval.reg) != -1;
172 void LiveIntervals::handleVirtualRegisterDef(MachineBasicBlock *mbb,
173 MachineBasicBlock::iterator mi,
177 LiveInterval &interval) {
178 DEBUG(dbgs() << "\t\tregister: " << PrintReg(interval.reg, tri_));
180 // Virtual registers may be defined multiple times (due to phi
181 // elimination and 2-addr elimination). Much of what we do only has to be
182 // done once for the vreg. We use an empty interval to detect the first
183 // time we see a vreg.
184 LiveVariables::VarInfo& vi = lv_->getVarInfo(interval.reg);
185 if (interval.empty()) {
186 // Get the Idx of the defining instructions.
187 SlotIndex defIndex = MIIdx.getRegSlot(MO.isEarlyClobber());
189 // Make sure the first definition is not a partial redefinition. Add an
190 // <imp-def> of the full register.
191 // FIXME: LiveIntervals shouldn't modify the code like this. Whoever
192 // created the machine instruction should annotate it with <undef> flags
193 // as needed. Then we can simply assert here. The REG_SEQUENCE lowering
194 // is the main suspect.
195 if (MO.getSubReg()) {
196 mi->addRegisterDefined(interval.reg);
197 // Mark all defs of interval.reg on this instruction as reading <undef>.
198 for (unsigned i = MOIdx, e = mi->getNumOperands(); i != e; ++i) {
199 MachineOperand &MO2 = mi->getOperand(i);
200 if (MO2.isReg() && MO2.getReg() == interval.reg && MO2.getSubReg())
205 VNInfo *ValNo = interval.getNextValue(defIndex, VNInfoAllocator);
206 assert(ValNo->id == 0 && "First value in interval is not 0?");
208 // Loop over all of the blocks that the vreg is defined in. There are
209 // two cases we have to handle here. The most common case is a vreg
210 // whose lifetime is contained within a basic block. In this case there
211 // will be a single kill, in MBB, which comes after the definition.
212 if (vi.Kills.size() == 1 && vi.Kills[0]->getParent() == mbb) {
213 // FIXME: what about dead vars?
215 if (vi.Kills[0] != mi)
216 killIdx = getInstructionIndex(vi.Kills[0]).getRegSlot();
218 killIdx = defIndex.getDeadSlot();
220 // If the kill happens after the definition, we have an intra-block
222 if (killIdx > defIndex) {
223 assert(vi.AliveBlocks.empty() &&
224 "Shouldn't be alive across any blocks!");
225 LiveRange LR(defIndex, killIdx, ValNo);
226 interval.addRange(LR);
227 DEBUG(dbgs() << " +" << LR << "\n");
232 // The other case we handle is when a virtual register lives to the end
233 // of the defining block, potentially live across some blocks, then is
234 // live into some number of blocks, but gets killed. Start by adding a
235 // range that goes from this definition to the end of the defining block.
236 LiveRange NewLR(defIndex, getMBBEndIdx(mbb), ValNo);
237 DEBUG(dbgs() << " +" << NewLR);
238 interval.addRange(NewLR);
240 bool PHIJoin = lv_->isPHIJoin(interval.reg);
243 // A phi join register is killed at the end of the MBB and revived as a new
244 // valno in the killing blocks.
245 assert(vi.AliveBlocks.empty() && "Phi join can't pass through blocks");
246 DEBUG(dbgs() << " phi-join");
247 ValNo->setHasPHIKill(true);
249 // Iterate over all of the blocks that the variable is completely
250 // live in, adding [insrtIndex(begin), instrIndex(end)+4) to the
252 for (SparseBitVector<>::iterator I = vi.AliveBlocks.begin(),
253 E = vi.AliveBlocks.end(); I != E; ++I) {
254 MachineBasicBlock *aliveBlock = mf_->getBlockNumbered(*I);
255 LiveRange LR(getMBBStartIdx(aliveBlock), getMBBEndIdx(aliveBlock), ValNo);
256 interval.addRange(LR);
257 DEBUG(dbgs() << " +" << LR);
261 // Finally, this virtual register is live from the start of any killing
262 // block to the 'use' slot of the killing instruction.
263 for (unsigned i = 0, e = vi.Kills.size(); i != e; ++i) {
264 MachineInstr *Kill = vi.Kills[i];
265 SlotIndex Start = getMBBStartIdx(Kill->getParent());
266 SlotIndex killIdx = getInstructionIndex(Kill).getRegSlot();
268 // Create interval with one of a NEW value number. Note that this value
269 // number isn't actually defined by an instruction, weird huh? :)
271 assert(getInstructionFromIndex(Start) == 0 &&
272 "PHI def index points at actual instruction.");
273 ValNo = interval.getNextValue(Start, VNInfoAllocator);
274 ValNo->setIsPHIDef(true);
276 LiveRange LR(Start, killIdx, ValNo);
277 interval.addRange(LR);
278 DEBUG(dbgs() << " +" << LR);
282 if (MultipleDefsBySameMI(*mi, MOIdx))
283 // Multiple defs of the same virtual register by the same instruction.
284 // e.g. %reg1031:5<def>, %reg1031:6<def> = VLD1q16 %reg1024<kill>, ...
285 // This is likely due to elimination of REG_SEQUENCE instructions. Return
286 // here since there is nothing to do.
289 // If this is the second time we see a virtual register definition, it
290 // must be due to phi elimination or two addr elimination. If this is
291 // the result of two address elimination, then the vreg is one of the
292 // def-and-use register operand.
294 // It may also be partial redef like this:
295 // 80 %reg1041:6<def> = VSHRNv4i16 %reg1034<kill>, 12, pred:14, pred:%reg0
296 // 120 %reg1041:5<def> = VSHRNv4i16 %reg1039<kill>, 12, pred:14, pred:%reg0
297 bool PartReDef = isPartialRedef(MIIdx, MO, interval);
298 if (PartReDef || mi->isRegTiedToUseOperand(MOIdx)) {
299 // If this is a two-address definition, then we have already processed
300 // the live range. The only problem is that we didn't realize there
301 // are actually two values in the live interval. Because of this we
302 // need to take the LiveRegion that defines this register and split it
304 SlotIndex RedefIndex = MIIdx.getRegSlot(MO.isEarlyClobber());
306 const LiveRange *OldLR =
307 interval.getLiveRangeContaining(RedefIndex.getRegSlot(true));
308 VNInfo *OldValNo = OldLR->valno;
309 SlotIndex DefIndex = OldValNo->def.getRegSlot();
311 // Delete the previous value, which should be short and continuous,
312 // because the 2-addr copy must be in the same MBB as the redef.
313 interval.removeRange(DefIndex, RedefIndex);
315 // The new value number (#1) is defined by the instruction we claimed
317 VNInfo *ValNo = interval.createValueCopy(OldValNo, VNInfoAllocator);
319 // Value#0 is now defined by the 2-addr instruction.
320 OldValNo->def = RedefIndex;
322 // Add the new live interval which replaces the range for the input copy.
323 LiveRange LR(DefIndex, RedefIndex, ValNo);
324 DEBUG(dbgs() << " replace range with " << LR);
325 interval.addRange(LR);
327 // If this redefinition is dead, we need to add a dummy unit live
328 // range covering the def slot.
330 interval.addRange(LiveRange(RedefIndex, RedefIndex.getDeadSlot(),
334 dbgs() << " RESULT: ";
335 interval.print(dbgs(), tri_);
337 } else if (lv_->isPHIJoin(interval.reg)) {
338 // In the case of PHI elimination, each variable definition is only
339 // live until the end of the block. We've already taken care of the
340 // rest of the live range.
342 SlotIndex defIndex = MIIdx.getRegSlot();
343 if (MO.isEarlyClobber())
344 defIndex = MIIdx.getRegSlot(true);
346 VNInfo *ValNo = interval.getNextValue(defIndex, VNInfoAllocator);
348 SlotIndex killIndex = getMBBEndIdx(mbb);
349 LiveRange LR(defIndex, killIndex, ValNo);
350 interval.addRange(LR);
351 ValNo->setHasPHIKill(true);
352 DEBUG(dbgs() << " phi-join +" << LR);
354 llvm_unreachable("Multiply defined register");
358 DEBUG(dbgs() << '\n');
361 void LiveIntervals::handlePhysicalRegisterDef(MachineBasicBlock *MBB,
362 MachineBasicBlock::iterator mi,
365 LiveInterval &interval) {
366 // A physical register cannot be live across basic block, so its
367 // lifetime must end somewhere in its defining basic block.
368 DEBUG(dbgs() << "\t\tregister: " << PrintReg(interval.reg, tri_));
370 SlotIndex baseIndex = MIIdx;
371 SlotIndex start = baseIndex.getRegSlot(MO.isEarlyClobber());
372 SlotIndex end = start;
374 // If it is not used after definition, it is considered dead at
375 // the instruction defining it. Hence its interval is:
376 // [defSlot(def), defSlot(def)+1)
377 // For earlyclobbers, the defSlot was pushed back one; the extra
378 // advance below compensates.
380 DEBUG(dbgs() << " dead");
381 end = start.getDeadSlot();
385 // If it is not dead on definition, it must be killed by a
386 // subsequent instruction. Hence its interval is:
387 // [defSlot(def), useSlot(kill)+1)
388 baseIndex = baseIndex.getNextIndex();
389 while (++mi != MBB->end()) {
391 if (mi->isDebugValue())
393 if (getInstructionFromIndex(baseIndex) == 0)
394 baseIndex = indexes_->getNextNonNullIndex(baseIndex);
396 if (mi->killsRegister(interval.reg, tri_)) {
397 DEBUG(dbgs() << " killed");
398 end = baseIndex.getRegSlot();
401 int DefIdx = mi->findRegisterDefOperandIdx(interval.reg,false,false,tri_);
403 if (mi->isRegTiedToUseOperand(DefIdx)) {
404 // Two-address instruction.
405 end = baseIndex.getRegSlot();
407 // Another instruction redefines the register before it is ever read.
408 // Then the register is essentially dead at the instruction that
409 // defines it. Hence its interval is:
410 // [defSlot(def), defSlot(def)+1)
411 DEBUG(dbgs() << " dead");
412 end = start.getDeadSlot();
418 baseIndex = baseIndex.getNextIndex();
421 // The only case we should have a dead physreg here without a killing or
422 // instruction where we know it's dead is if it is live-in to the function
423 // and never used. Another possible case is the implicit use of the
424 // physical register has been deleted by two-address pass.
425 end = start.getDeadSlot();
428 assert(start < end && "did not find end of interval?");
430 // Already exists? Extend old live interval.
431 VNInfo *ValNo = interval.getVNInfoAt(start);
432 bool Extend = ValNo != 0;
434 ValNo = interval.getNextValue(start, VNInfoAllocator);
435 if (Extend && MO.isEarlyClobber())
436 ValNo->setHasRedefByEC(true);
437 LiveRange LR(start, end, ValNo);
438 interval.addRange(LR);
439 DEBUG(dbgs() << " +" << LR << '\n');
442 void LiveIntervals::handleRegisterDef(MachineBasicBlock *MBB,
443 MachineBasicBlock::iterator MI,
447 if (TargetRegisterInfo::isVirtualRegister(MO.getReg()))
448 handleVirtualRegisterDef(MBB, MI, MIIdx, MO, MOIdx,
449 getOrCreateInterval(MO.getReg()));
451 handlePhysicalRegisterDef(MBB, MI, MIIdx, MO,
452 getOrCreateInterval(MO.getReg()));
455 void LiveIntervals::handleLiveInRegister(MachineBasicBlock *MBB,
457 LiveInterval &interval, bool isAlias) {
458 DEBUG(dbgs() << "\t\tlivein register: " << PrintReg(interval.reg, tri_));
460 // Look for kills, if it reaches a def before it's killed, then it shouldn't
461 // be considered a livein.
462 MachineBasicBlock::iterator mi = MBB->begin();
463 MachineBasicBlock::iterator E = MBB->end();
464 // Skip over DBG_VALUE at the start of the MBB.
465 if (mi != E && mi->isDebugValue()) {
466 while (++mi != E && mi->isDebugValue())
469 // MBB is empty except for DBG_VALUE's.
473 SlotIndex baseIndex = MIIdx;
474 SlotIndex start = baseIndex;
475 if (getInstructionFromIndex(baseIndex) == 0)
476 baseIndex = indexes_->getNextNonNullIndex(baseIndex);
478 SlotIndex end = baseIndex;
479 bool SeenDefUse = false;
482 if (mi->killsRegister(interval.reg, tri_)) {
483 DEBUG(dbgs() << " killed");
484 end = baseIndex.getRegSlot();
487 } else if (mi->definesRegister(interval.reg, tri_)) {
488 // Another instruction redefines the register before it is ever read.
489 // Then the register is essentially dead at the instruction that defines
490 // it. Hence its interval is:
491 // [defSlot(def), defSlot(def)+1)
492 DEBUG(dbgs() << " dead");
493 end = start.getDeadSlot();
498 while (++mi != E && mi->isDebugValue())
499 // Skip over DBG_VALUE.
502 baseIndex = indexes_->getNextNonNullIndex(baseIndex);
505 // Live-in register might not be used at all.
508 DEBUG(dbgs() << " dead");
509 end = MIIdx.getDeadSlot();
511 DEBUG(dbgs() << " live through");
512 end = getMBBEndIdx(MBB);
516 SlotIndex defIdx = getMBBStartIdx(MBB);
517 assert(getInstructionFromIndex(defIdx) == 0 &&
518 "PHI def index points at actual instruction.");
519 VNInfo *vni = interval.getNextValue(defIdx, VNInfoAllocator);
520 vni->setIsPHIDef(true);
521 LiveRange LR(start, end, vni);
523 interval.addRange(LR);
524 DEBUG(dbgs() << " +" << LR << '\n');
527 /// computeIntervals - computes the live intervals for virtual
528 /// registers. for some ordering of the machine instructions [1,N] a
529 /// live interval is an interval [i, j) where 1 <= i <= j < N for
530 /// which a variable is live
531 void LiveIntervals::computeIntervals() {
532 DEBUG(dbgs() << "********** COMPUTING LIVE INTERVALS **********\n"
533 << "********** Function: "
534 << ((Value*)mf_->getFunction())->getName() << '\n');
536 SmallVector<unsigned, 8> UndefUses;
537 for (MachineFunction::iterator MBBI = mf_->begin(), E = mf_->end();
539 MachineBasicBlock *MBB = MBBI;
543 // Track the index of the current machine instr.
544 SlotIndex MIIndex = getMBBStartIdx(MBB);
545 DEBUG(dbgs() << "BB#" << MBB->getNumber()
546 << ":\t\t# derived from " << MBB->getName() << "\n");
548 // Create intervals for live-ins to this BB first.
549 for (MachineBasicBlock::livein_iterator LI = MBB->livein_begin(),
550 LE = MBB->livein_end(); LI != LE; ++LI) {
551 handleLiveInRegister(MBB, MIIndex, getOrCreateInterval(*LI));
554 // Skip over empty initial indices.
555 if (getInstructionFromIndex(MIIndex) == 0)
556 MIIndex = indexes_->getNextNonNullIndex(MIIndex);
558 for (MachineBasicBlock::iterator MI = MBB->begin(), miEnd = MBB->end();
560 DEBUG(dbgs() << MIIndex << "\t" << *MI);
561 if (MI->isDebugValue())
565 for (int i = MI->getNumOperands() - 1; i >= 0; --i) {
566 MachineOperand &MO = MI->getOperand(i);
567 if (!MO.isReg() || !MO.getReg())
570 // handle register defs - build intervals
572 handleRegisterDef(MBB, MI, MIIndex, MO, i);
573 else if (MO.isUndef())
574 UndefUses.push_back(MO.getReg());
577 // Move to the next instr slot.
578 MIIndex = indexes_->getNextNonNullIndex(MIIndex);
582 // Create empty intervals for registers defined by implicit_def's (except
583 // for those implicit_def that define values which are liveout of their
585 for (unsigned i = 0, e = UndefUses.size(); i != e; ++i) {
586 unsigned UndefReg = UndefUses[i];
587 (void)getOrCreateInterval(UndefReg);
591 LiveInterval* LiveIntervals::createInterval(unsigned reg) {
592 float Weight = TargetRegisterInfo::isPhysicalRegister(reg) ? HUGE_VALF : 0.0F;
593 return new LiveInterval(reg, Weight);
596 /// dupInterval - Duplicate a live interval. The caller is responsible for
597 /// managing the allocated memory.
598 LiveInterval* LiveIntervals::dupInterval(LiveInterval *li) {
599 LiveInterval *NewLI = createInterval(li->reg);
600 NewLI->Copy(*li, mri_, getVNInfoAllocator());
604 /// shrinkToUses - After removing some uses of a register, shrink its live
605 /// range to just the remaining uses. This method does not compute reaching
606 /// defs for new uses, and it doesn't remove dead defs.
607 bool LiveIntervals::shrinkToUses(LiveInterval *li,
608 SmallVectorImpl<MachineInstr*> *dead) {
609 DEBUG(dbgs() << "Shrink: " << *li << '\n');
610 assert(TargetRegisterInfo::isVirtualRegister(li->reg)
611 && "Can only shrink virtual registers");
612 // Find all the values used, including PHI kills.
613 SmallVector<std::pair<SlotIndex, VNInfo*>, 16> WorkList;
615 // Blocks that have already been added to WorkList as live-out.
616 SmallPtrSet<MachineBasicBlock*, 16> LiveOut;
618 // Visit all instructions reading li->reg.
619 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(li->reg);
620 MachineInstr *UseMI = I.skipInstruction();) {
621 if (UseMI->isDebugValue() || !UseMI->readsVirtualRegister(li->reg))
623 SlotIndex Idx = getInstructionIndex(UseMI).getRegSlot();
624 // Note: This intentionally picks up the wrong VNI in case of an EC redef.
626 VNInfo *VNI = li->getVNInfoBefore(Idx);
628 // This shouldn't happen: readsVirtualRegister returns true, but there is
629 // no live value. It is likely caused by a target getting <undef> flags
631 DEBUG(dbgs() << Idx << '\t' << *UseMI
632 << "Warning: Instr claims to read non-existent value in "
636 // Special case: An early-clobber tied operand reads and writes the
637 // register one slot early. The getVNInfoBefore call above would have
638 // picked up the value defined by UseMI. Adjust the kill slot and value.
639 if (SlotIndex::isSameInstr(VNI->def, Idx)) {
641 VNI = li->getVNInfoBefore(Idx);
642 assert(VNI && "Early-clobber tied value not available");
644 WorkList.push_back(std::make_pair(Idx, VNI));
647 // Create a new live interval with only minimal live segments per def.
648 LiveInterval NewLI(li->reg, 0);
649 for (LiveInterval::vni_iterator I = li->vni_begin(), E = li->vni_end();
654 NewLI.addRange(LiveRange(VNI->def, VNI->def.getDeadSlot(), VNI));
657 // Keep track of the PHIs that are in use.
658 SmallPtrSet<VNInfo*, 8> UsedPHIs;
660 // Extend intervals to reach all uses in WorkList.
661 while (!WorkList.empty()) {
662 SlotIndex Idx = WorkList.back().first;
663 VNInfo *VNI = WorkList.back().second;
665 const MachineBasicBlock *MBB = getMBBFromIndex(Idx.getPrevSlot());
666 SlotIndex BlockStart = getMBBStartIdx(MBB);
668 // Extend the live range for VNI to be live at Idx.
669 if (VNInfo *ExtVNI = NewLI.extendInBlock(BlockStart, Idx)) {
671 assert(ExtVNI == VNI && "Unexpected existing value number");
672 // Is this a PHIDef we haven't seen before?
673 if (!VNI->isPHIDef() || VNI->def != BlockStart || !UsedPHIs.insert(VNI))
675 // The PHI is live, make sure the predecessors are live-out.
676 for (MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(),
677 PE = MBB->pred_end(); PI != PE; ++PI) {
678 if (!LiveOut.insert(*PI))
680 SlotIndex Stop = getMBBEndIdx(*PI);
681 // A predecessor is not required to have a live-out value for a PHI.
682 if (VNInfo *PVNI = li->getVNInfoBefore(Stop))
683 WorkList.push_back(std::make_pair(Stop, PVNI));
688 // VNI is live-in to MBB.
689 DEBUG(dbgs() << " live-in at " << BlockStart << '\n');
690 NewLI.addRange(LiveRange(BlockStart, Idx, VNI));
692 // Make sure VNI is live-out from the predecessors.
693 for (MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(),
694 PE = MBB->pred_end(); PI != PE; ++PI) {
695 if (!LiveOut.insert(*PI))
697 SlotIndex Stop = getMBBEndIdx(*PI);
698 assert(li->getVNInfoBefore(Stop) == VNI &&
699 "Wrong value out of predecessor");
700 WorkList.push_back(std::make_pair(Stop, VNI));
704 // Handle dead values.
705 bool CanSeparate = false;
706 for (LiveInterval::vni_iterator I = li->vni_begin(), E = li->vni_end();
711 LiveInterval::iterator LII = NewLI.FindLiveRangeContaining(VNI->def);
712 assert(LII != NewLI.end() && "Missing live range for PHI");
713 if (LII->end != VNI->def.getDeadSlot())
715 if (VNI->isPHIDef()) {
716 // This is a dead PHI. Remove it.
717 VNI->setIsUnused(true);
718 NewLI.removeRange(*LII);
719 DEBUG(dbgs() << "Dead PHI at " << VNI->def << " may separate interval\n");
722 // This is a dead def. Make sure the instruction knows.
723 MachineInstr *MI = getInstructionFromIndex(VNI->def);
724 assert(MI && "No instruction defining live value");
725 MI->addRegisterDead(li->reg, tri_);
726 if (dead && MI->allDefsAreDead()) {
727 DEBUG(dbgs() << "All defs dead: " << VNI->def << '\t' << *MI);
733 // Move the trimmed ranges back.
734 li->ranges.swap(NewLI.ranges);
735 DEBUG(dbgs() << "Shrunk: " << *li << '\n');
740 //===----------------------------------------------------------------------===//
741 // Register allocator hooks.
744 void LiveIntervals::addKillFlags() {
745 for (iterator I = begin(), E = end(); I != E; ++I) {
746 unsigned Reg = I->first;
747 if (TargetRegisterInfo::isPhysicalRegister(Reg))
749 if (mri_->reg_nodbg_empty(Reg))
751 LiveInterval *LI = I->second;
753 // Every instruction that kills Reg corresponds to a live range end point.
754 for (LiveInterval::iterator RI = LI->begin(), RE = LI->end(); RI != RE;
756 // A block index indicates an MBB edge.
757 if (RI->end.isBlock())
759 MachineInstr *MI = getInstructionFromIndex(RI->end);
762 MI->addRegisterKilled(Reg, NULL);
768 static bool intervalRangesSane(const LiveInterval& li) {
773 SlotIndex lastEnd = li.begin()->start;
774 for (LiveInterval::const_iterator lrItr = li.begin(), lrEnd = li.end();
775 lrItr != lrEnd; ++lrItr) {
776 const LiveRange& lr = *lrItr;
777 if (lastEnd > lr.start || lr.start >= lr.end)
786 template <typename DefSetT>
787 static void handleMoveDefs(LiveIntervals& lis, SlotIndex origIdx,
788 SlotIndex miIdx, const DefSetT& defs) {
789 for (typename DefSetT::const_iterator defItr = defs.begin(),
791 defItr != defEnd; ++defItr) {
792 unsigned def = *defItr;
793 LiveInterval& li = lis.getInterval(def);
794 LiveRange* lr = li.getLiveRangeContaining(origIdx.getRegSlot());
795 assert(lr != 0 && "No range for def?");
796 lr->start = miIdx.getRegSlot();
797 lr->valno->def = miIdx.getRegSlot();
798 assert(intervalRangesSane(li) && "Broke live interval moving def.");
802 template <typename DeadDefSetT>
803 static void handleMoveDeadDefs(LiveIntervals& lis, SlotIndex origIdx,
804 SlotIndex miIdx, const DeadDefSetT& deadDefs) {
805 for (typename DeadDefSetT::const_iterator deadDefItr = deadDefs.begin(),
806 deadDefEnd = deadDefs.end();
807 deadDefItr != deadDefEnd; ++deadDefItr) {
808 unsigned deadDef = *deadDefItr;
809 LiveInterval& li = lis.getInterval(deadDef);
810 LiveRange* lr = li.getLiveRangeContaining(origIdx.getRegSlot());
811 assert(lr != 0 && "No range for dead def?");
812 assert(lr->start == origIdx.getRegSlot() && "Bad dead range start?");
813 assert(lr->end == origIdx.getDeadSlot() && "Bad dead range end?");
814 assert(lr->valno->def == origIdx.getRegSlot() && "Bad dead valno def.");
816 t.start = miIdx.getRegSlot();
817 t.valno->def = miIdx.getRegSlot();
818 t.end = miIdx.getDeadSlot();
821 assert(intervalRangesSane(li) && "Broke live interval moving dead def.");
825 template <typename ECSetT>
826 static void handleMoveECs(LiveIntervals& lis, SlotIndex origIdx,
827 SlotIndex miIdx, const ECSetT& ecs) {
828 for (typename ECSetT::const_iterator ecItr = ecs.begin(), ecEnd = ecs.end();
829 ecItr != ecEnd; ++ecItr) {
830 unsigned ec = *ecItr;
831 LiveInterval& li = lis.getInterval(ec);
832 LiveRange* lr = li.getLiveRangeContaining(origIdx.getRegSlot(true));
833 assert(lr != 0 && "No range for early clobber?");
834 assert(lr->start == origIdx.getRegSlot(true) && "Bad EC range start?");
835 assert(lr->end == origIdx.getRegSlot() && "Bad EC range end.");
836 assert(lr->valno->def == origIdx.getRegSlot(true) && "Bad EC valno def.");
838 t.start = miIdx.getRegSlot(true);
839 t.valno->def = miIdx.getRegSlot(true);
840 t.end = miIdx.getRegSlot();
843 assert(intervalRangesSane(li) && "Broke live interval moving EC.");
847 template <typename UseSetT>
848 static void handleMoveUses(const MachineBasicBlock *mbb,
849 const MachineRegisterInfo& mri,
850 const BitVector& reservedRegs, LiveIntervals &lis,
851 SlotIndex origIdx, SlotIndex miIdx,
852 const UseSetT &uses) {
853 bool movingUp = miIdx < origIdx;
854 for (typename UseSetT::const_iterator usesItr = uses.begin(),
855 usesEnd = uses.end();
856 usesItr != usesEnd; ++usesItr) {
857 unsigned use = *usesItr;
858 if (!lis.hasInterval(use))
860 if (TargetRegisterInfo::isPhysicalRegister(use) && reservedRegs.test(use))
862 LiveInterval& li = lis.getInterval(use);
863 LiveRange* lr = li.getLiveRangeBefore(origIdx.getRegSlot());
864 assert(lr != 0 && "No range for use?");
865 bool liveThrough = lr->end > origIdx.getRegSlot();
868 // If moving up and liveThrough - nothing to do.
869 // If not live through we need to extend the range to the last use
870 // between the old location and the new one.
872 SlotIndex lastUseInRange = miIdx.getRegSlot();
873 for (MachineRegisterInfo::use_iterator useI = mri.use_begin(use),
874 useE = mri.use_end();
875 useI != useE; ++useI) {
876 const MachineInstr* mopI = &*useI;
877 const MachineOperand& mop = useI.getOperand();
878 SlotIndex instSlot = lis.getSlotIndexes()->getInstructionIndex(mopI);
879 SlotIndex opSlot = instSlot.getRegSlot(mop.isEarlyClobber());
880 if (opSlot >= lastUseInRange && opSlot < origIdx) {
881 lastUseInRange = opSlot;
884 lr->end = lastUseInRange;
887 // Moving down is easy - the existing live range end tells us where
890 // Easy fix - just update the range endpoint.
891 lr->end = miIdx.getRegSlot();
893 bool liveOut = lr->end >= lis.getSlotIndexes()->getMBBEndIdx(mbb);
894 if (!liveOut && miIdx.getRegSlot() > lr->end) {
895 lr->end = miIdx.getRegSlot();
899 assert(intervalRangesSane(li) && "Broke live interval moving use.");
903 void LiveIntervals::moveInstr(MachineBasicBlock::iterator insertPt,
905 MachineBasicBlock* mbb = mi->getParent();
906 assert((insertPt == mbb->end() || insertPt->getParent() == mbb) &&
907 "Cannot handle moves across basic block boundaries.");
908 assert(&*insertPt != mi && "No-op move requested?");
909 assert(!mi->isInsideBundle() && "Can't handle bundled instructions yet.");
911 // Grab the original instruction index.
912 SlotIndex origIdx = indexes_->getInstructionIndex(mi);
914 // Move the machine instr and obtain its new index.
915 indexes_->removeMachineInstrFromMaps(mi);
917 mbb->insert(insertPt, mi);
918 SlotIndex miIdx = indexes_->insertMachineInstrInMaps(mi);
920 // Pick the direction.
921 bool movingUp = miIdx < origIdx;
923 // Collect the operands.
924 DenseSet<unsigned> uses, defs, deadDefs, ecs;
925 for (MachineInstr::mop_iterator mopItr = mi->operands_begin(),
926 mopEnd = mi->operands_end();
927 mopItr != mopEnd; ++mopItr) {
928 const MachineOperand& mop = *mopItr;
930 if (!mop.isReg() || mop.getReg() == 0)
932 unsigned reg = mop.getReg();
934 assert(mop.readsReg());
937 if (mop.readsReg() && !ecs.count(reg)) {
942 assert(!defs.count(reg) && "Can't mix defs with dead-defs.");
943 deadDefs.insert(reg);
944 } else if (mop.isEarlyClobber()) {
948 assert(!deadDefs.count(reg) && "Can't mix defs with dead-defs.");
954 BitVector reservedRegs(tri_->getReservedRegs(*mbb->getParent()));
957 handleMoveUses(mbb, *mri_, reservedRegs, *this, origIdx, miIdx, uses);
958 handleMoveECs(*this, origIdx, miIdx, ecs);
959 handleMoveDeadDefs(*this, origIdx, miIdx, deadDefs);
960 handleMoveDefs(*this, origIdx, miIdx, defs);
962 handleMoveDefs(*this, origIdx, miIdx, defs);
963 handleMoveDeadDefs(*this, origIdx, miIdx, deadDefs);
964 handleMoveECs(*this, origIdx, miIdx, ecs);
965 handleMoveUses(mbb, *mri_, reservedRegs, *this, origIdx, miIdx, uses);
969 /// getReMatImplicitUse - If the remat definition MI has one (for now, we only
970 /// allow one) virtual register operand, then its uses are implicitly using
971 /// the register. Returns the virtual register.
972 unsigned LiveIntervals::getReMatImplicitUse(const LiveInterval &li,
973 MachineInstr *MI) const {
975 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
976 MachineOperand &MO = MI->getOperand(i);
977 if (!MO.isReg() || !MO.isUse())
979 unsigned Reg = MO.getReg();
980 if (Reg == 0 || Reg == li.reg)
983 if (TargetRegisterInfo::isPhysicalRegister(Reg) &&
984 !allocatableRegs_[Reg])
987 break; // Found vreg operand - leave the loop.
992 /// isValNoAvailableAt - Return true if the val# of the specified interval
993 /// which reaches the given instruction also reaches the specified use index.
994 bool LiveIntervals::isValNoAvailableAt(const LiveInterval &li, MachineInstr *MI,
995 SlotIndex UseIdx) const {
996 VNInfo *UValNo = li.getVNInfoAt(UseIdx);
997 return UValNo && UValNo == li.getVNInfoAt(getInstructionIndex(MI));
1000 /// isReMaterializable - Returns true if the definition MI of the specified
1001 /// val# of the specified interval is re-materializable.
1003 LiveIntervals::isReMaterializable(const LiveInterval &li,
1004 const VNInfo *ValNo, MachineInstr *MI,
1005 const SmallVectorImpl<LiveInterval*> *SpillIs,
1010 if (!tii_->isTriviallyReMaterializable(MI, aa_))
1013 // Target-specific code can mark an instruction as being rematerializable
1014 // if it has one virtual reg use, though it had better be something like
1015 // a PIC base register which is likely to be live everywhere.
1016 unsigned ImpUse = getReMatImplicitUse(li, MI);
1018 const LiveInterval &ImpLi = getInterval(ImpUse);
1019 for (MachineRegisterInfo::use_nodbg_iterator
1020 ri = mri_->use_nodbg_begin(li.reg), re = mri_->use_nodbg_end();
1022 MachineInstr *UseMI = &*ri;
1023 SlotIndex UseIdx = getInstructionIndex(UseMI);
1024 if (li.getVNInfoAt(UseIdx) != ValNo)
1026 if (!isValNoAvailableAt(ImpLi, MI, UseIdx))
1030 // If a register operand of the re-materialized instruction is going to
1031 // be spilled next, then it's not legal to re-materialize this instruction.
1033 for (unsigned i = 0, e = SpillIs->size(); i != e; ++i)
1034 if (ImpUse == (*SpillIs)[i]->reg)
1040 /// isReMaterializable - Returns true if every definition of MI of every
1041 /// val# of the specified interval is re-materializable.
1043 LiveIntervals::isReMaterializable(const LiveInterval &li,
1044 const SmallVectorImpl<LiveInterval*> *SpillIs,
1047 for (LiveInterval::const_vni_iterator i = li.vni_begin(), e = li.vni_end();
1049 const VNInfo *VNI = *i;
1050 if (VNI->isUnused())
1051 continue; // Dead val#.
1052 // Is the def for the val# rematerializable?
1053 MachineInstr *ReMatDefMI = getInstructionFromIndex(VNI->def);
1056 bool DefIsLoad = false;
1058 !isReMaterializable(li, VNI, ReMatDefMI, SpillIs, DefIsLoad))
1060 isLoad |= DefIsLoad;
1065 bool LiveIntervals::intervalIsInOneMBB(const LiveInterval &li) const {
1066 LiveInterval::Ranges::const_iterator itr = li.ranges.begin();
1068 MachineBasicBlock *mbb = indexes_->getMBBCoveringRange(itr->start, itr->end);
1073 for (++itr; itr != li.ranges.end(); ++itr) {
1074 MachineBasicBlock *mbb2 =
1075 indexes_->getMBBCoveringRange(itr->start, itr->end);
1085 LiveIntervals::getSpillWeight(bool isDef, bool isUse, unsigned loopDepth) {
1086 // Limit the loop depth ridiculousness.
1087 if (loopDepth > 200)
1090 // The loop depth is used to roughly estimate the number of times the
1091 // instruction is executed. Something like 10^d is simple, but will quickly
1092 // overflow a float. This expression behaves like 10^d for small d, but is
1093 // more tempered for large d. At d=200 we get 6.7e33 which leaves a bit of
1094 // headroom before overflow.
1095 // By the way, powf() might be unavailable here. For consistency,
1096 // We may take pow(double,double).
1097 float lc = std::pow(1 + (100.0 / (loopDepth + 10)), (double)loopDepth);
1099 return (isDef + isUse) * lc;
1102 LiveRange LiveIntervals::addLiveRangeToEndOfBlock(unsigned reg,
1103 MachineInstr* startInst) {
1104 LiveInterval& Interval = getOrCreateInterval(reg);
1105 VNInfo* VN = Interval.getNextValue(
1106 SlotIndex(getInstructionIndex(startInst).getRegSlot()),
1107 getVNInfoAllocator());
1108 VN->setHasPHIKill(true);
1110 SlotIndex(getInstructionIndex(startInst).getRegSlot()),
1111 getMBBEndIdx(startInst->getParent()), VN);
1112 Interval.addRange(LR);