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 "VirtRegMap.h"
21 #include "llvm/Value.h"
22 #include "llvm/Analysis/AliasAnalysis.h"
23 #include "llvm/CodeGen/CalcSpillWeights.h"
24 #include "llvm/CodeGen/LiveVariables.h"
25 #include "llvm/CodeGen/MachineFrameInfo.h"
26 #include "llvm/CodeGen/MachineInstr.h"
27 #include "llvm/CodeGen/MachineInstrBuilder.h"
28 #include "llvm/CodeGen/MachineLoopInfo.h"
29 #include "llvm/CodeGen/MachineMemOperand.h"
30 #include "llvm/CodeGen/MachineRegisterInfo.h"
31 #include "llvm/CodeGen/Passes.h"
32 #include "llvm/CodeGen/ProcessImplicitDefs.h"
33 #include "llvm/Target/TargetRegisterInfo.h"
34 #include "llvm/Target/TargetInstrInfo.h"
35 #include "llvm/Target/TargetMachine.h"
36 #include "llvm/Target/TargetOptions.h"
37 #include "llvm/Support/CommandLine.h"
38 #include "llvm/Support/Debug.h"
39 #include "llvm/Support/ErrorHandling.h"
40 #include "llvm/Support/raw_ostream.h"
41 #include "llvm/ADT/DepthFirstIterator.h"
42 #include "llvm/ADT/SmallSet.h"
43 #include "llvm/ADT/Statistic.h"
44 #include "llvm/ADT/STLExtras.h"
50 // Hidden options for help debugging.
51 static cl::opt<bool> DisableReMat("disable-rematerialization",
52 cl::init(false), cl::Hidden);
54 STATISTIC(numIntervals , "Number of original intervals");
56 char LiveIntervals::ID = 0;
57 INITIALIZE_PASS_BEGIN(LiveIntervals, "liveintervals",
58 "Live Interval Analysis", false, false)
59 INITIALIZE_PASS_DEPENDENCY(LiveVariables)
60 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
61 INITIALIZE_PASS_DEPENDENCY(PHIElimination)
62 INITIALIZE_PASS_DEPENDENCY(TwoAddressInstructionPass)
63 INITIALIZE_PASS_DEPENDENCY(ProcessImplicitDefs)
64 INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
65 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
66 INITIALIZE_PASS_END(LiveIntervals, "liveintervals",
67 "Live Interval Analysis", false, false)
69 void LiveIntervals::getAnalysisUsage(AnalysisUsage &AU) const {
71 AU.addRequired<AliasAnalysis>();
72 AU.addPreserved<AliasAnalysis>();
73 AU.addRequired<LiveVariables>();
74 AU.addPreserved<LiveVariables>();
75 AU.addRequired<MachineLoopInfo>();
76 AU.addPreserved<MachineLoopInfo>();
77 AU.addPreservedID(MachineDominatorsID);
80 AU.addPreservedID(PHIEliminationID);
81 AU.addRequiredID(PHIEliminationID);
84 AU.addRequiredID(TwoAddressInstructionPassID);
85 AU.addPreserved<ProcessImplicitDefs>();
86 AU.addRequired<ProcessImplicitDefs>();
87 AU.addPreserved<SlotIndexes>();
88 AU.addRequiredTransitive<SlotIndexes>();
89 MachineFunctionPass::getAnalysisUsage(AU);
92 void LiveIntervals::releaseMemory() {
93 // Free the live intervals themselves.
94 for (DenseMap<unsigned, LiveInterval*>::iterator I = r2iMap_.begin(),
95 E = r2iMap_.end(); I != E; ++I)
100 // Release VNInfo memory regions, VNInfo objects don't need to be dtor'd.
101 VNInfoAllocator.Reset();
104 /// runOnMachineFunction - Register allocate the whole function
106 bool LiveIntervals::runOnMachineFunction(MachineFunction &fn) {
108 mri_ = &mf_->getRegInfo();
109 tm_ = &fn.getTarget();
110 tri_ = tm_->getRegisterInfo();
111 tii_ = tm_->getInstrInfo();
112 aa_ = &getAnalysis<AliasAnalysis>();
113 lv_ = &getAnalysis<LiveVariables>();
114 indexes_ = &getAnalysis<SlotIndexes>();
115 allocatableRegs_ = tri_->getAllocatableSet(fn);
119 numIntervals += getNumIntervals();
125 /// print - Implement the dump method.
126 void LiveIntervals::print(raw_ostream &OS, const Module* ) const {
127 OS << "********** INTERVALS **********\n";
128 for (const_iterator I = begin(), E = end(); I != E; ++I) {
129 I->second->print(OS, tri_);
136 void LiveIntervals::printInstrs(raw_ostream &OS) const {
137 OS << "********** MACHINEINSTRS **********\n";
138 mf_->print(OS, indexes_);
141 void LiveIntervals::dumpInstrs() const {
146 bool MultipleDefsBySameMI(const MachineInstr &MI, unsigned MOIdx) {
147 unsigned Reg = MI.getOperand(MOIdx).getReg();
148 for (unsigned i = MOIdx+1, e = MI.getNumOperands(); i < e; ++i) {
149 const MachineOperand &MO = MI.getOperand(i);
152 if (MO.getReg() == Reg && MO.isDef()) {
153 assert(MI.getOperand(MOIdx).getSubReg() != MO.getSubReg() &&
154 MI.getOperand(MOIdx).getSubReg() &&
155 (MO.getSubReg() || MO.isImplicit()));
162 /// isPartialRedef - Return true if the specified def at the specific index is
163 /// partially re-defining the specified live interval. A common case of this is
164 /// a definition of the sub-register.
165 bool LiveIntervals::isPartialRedef(SlotIndex MIIdx, MachineOperand &MO,
166 LiveInterval &interval) {
167 if (!MO.getSubReg() || MO.isEarlyClobber())
170 SlotIndex RedefIndex = MIIdx.getRegSlot();
171 const LiveRange *OldLR =
172 interval.getLiveRangeContaining(RedefIndex.getRegSlot(true));
173 MachineInstr *DefMI = getInstructionFromIndex(OldLR->valno->def);
175 return DefMI->findRegisterDefOperandIdx(interval.reg) != -1;
180 void LiveIntervals::handleVirtualRegisterDef(MachineBasicBlock *mbb,
181 MachineBasicBlock::iterator mi,
185 LiveInterval &interval) {
186 DEBUG(dbgs() << "\t\tregister: " << PrintReg(interval.reg, tri_));
188 // Virtual registers may be defined multiple times (due to phi
189 // elimination and 2-addr elimination). Much of what we do only has to be
190 // done once for the vreg. We use an empty interval to detect the first
191 // time we see a vreg.
192 LiveVariables::VarInfo& vi = lv_->getVarInfo(interval.reg);
193 if (interval.empty()) {
194 // Get the Idx of the defining instructions.
195 SlotIndex defIndex = MIIdx.getRegSlot(MO.isEarlyClobber());
197 // Make sure the first definition is not a partial redefinition. Add an
198 // <imp-def> of the full register.
199 // FIXME: LiveIntervals shouldn't modify the code like this. Whoever
200 // created the machine instruction should annotate it with <undef> flags
201 // as needed. Then we can simply assert here. The REG_SEQUENCE lowering
202 // is the main suspect.
203 if (MO.getSubReg()) {
204 mi->addRegisterDefined(interval.reg);
205 // Mark all defs of interval.reg on this instruction as reading <undef>.
206 for (unsigned i = MOIdx, e = mi->getNumOperands(); i != e; ++i) {
207 MachineOperand &MO2 = mi->getOperand(i);
208 if (MO2.isReg() && MO2.getReg() == interval.reg && MO2.getSubReg())
213 MachineInstr *CopyMI = NULL;
214 if (mi->isCopyLike()) {
218 VNInfo *ValNo = interval.getNextValue(defIndex, CopyMI, VNInfoAllocator);
219 assert(ValNo->id == 0 && "First value in interval is not 0?");
221 // Loop over all of the blocks that the vreg is defined in. There are
222 // two cases we have to handle here. The most common case is a vreg
223 // whose lifetime is contained within a basic block. In this case there
224 // will be a single kill, in MBB, which comes after the definition.
225 if (vi.Kills.size() == 1 && vi.Kills[0]->getParent() == mbb) {
226 // FIXME: what about dead vars?
228 if (vi.Kills[0] != mi)
229 killIdx = getInstructionIndex(vi.Kills[0]).getRegSlot();
231 killIdx = defIndex.getDeadSlot();
233 // If the kill happens after the definition, we have an intra-block
235 if (killIdx > defIndex) {
236 assert(vi.AliveBlocks.empty() &&
237 "Shouldn't be alive across any blocks!");
238 LiveRange LR(defIndex, killIdx, ValNo);
239 interval.addRange(LR);
240 DEBUG(dbgs() << " +" << LR << "\n");
245 // The other case we handle is when a virtual register lives to the end
246 // of the defining block, potentially live across some blocks, then is
247 // live into some number of blocks, but gets killed. Start by adding a
248 // range that goes from this definition to the end of the defining block.
249 LiveRange NewLR(defIndex, getMBBEndIdx(mbb), ValNo);
250 DEBUG(dbgs() << " +" << NewLR);
251 interval.addRange(NewLR);
253 bool PHIJoin = lv_->isPHIJoin(interval.reg);
256 // A phi join register is killed at the end of the MBB and revived as a new
257 // valno in the killing blocks.
258 assert(vi.AliveBlocks.empty() && "Phi join can't pass through blocks");
259 DEBUG(dbgs() << " phi-join");
260 ValNo->setHasPHIKill(true);
262 // Iterate over all of the blocks that the variable is completely
263 // live in, adding [insrtIndex(begin), instrIndex(end)+4) to the
265 for (SparseBitVector<>::iterator I = vi.AliveBlocks.begin(),
266 E = vi.AliveBlocks.end(); I != E; ++I) {
267 MachineBasicBlock *aliveBlock = mf_->getBlockNumbered(*I);
268 LiveRange LR(getMBBStartIdx(aliveBlock), getMBBEndIdx(aliveBlock), ValNo);
269 interval.addRange(LR);
270 DEBUG(dbgs() << " +" << LR);
274 // Finally, this virtual register is live from the start of any killing
275 // block to the 'use' slot of the killing instruction.
276 for (unsigned i = 0, e = vi.Kills.size(); i != e; ++i) {
277 MachineInstr *Kill = vi.Kills[i];
278 SlotIndex Start = getMBBStartIdx(Kill->getParent());
279 SlotIndex killIdx = getInstructionIndex(Kill).getRegSlot();
281 // Create interval with one of a NEW value number. Note that this value
282 // number isn't actually defined by an instruction, weird huh? :)
284 assert(getInstructionFromIndex(Start) == 0 &&
285 "PHI def index points at actual instruction.");
286 ValNo = interval.getNextValue(Start, 0, VNInfoAllocator);
287 ValNo->setIsPHIDef(true);
289 LiveRange LR(Start, killIdx, ValNo);
290 interval.addRange(LR);
291 DEBUG(dbgs() << " +" << LR);
295 if (MultipleDefsBySameMI(*mi, MOIdx))
296 // Multiple defs of the same virtual register by the same instruction.
297 // e.g. %reg1031:5<def>, %reg1031:6<def> = VLD1q16 %reg1024<kill>, ...
298 // This is likely due to elimination of REG_SEQUENCE instructions. Return
299 // here since there is nothing to do.
302 // If this is the second time we see a virtual register definition, it
303 // must be due to phi elimination or two addr elimination. If this is
304 // the result of two address elimination, then the vreg is one of the
305 // def-and-use register operand.
307 // It may also be partial redef like this:
308 // 80 %reg1041:6<def> = VSHRNv4i16 %reg1034<kill>, 12, pred:14, pred:%reg0
309 // 120 %reg1041:5<def> = VSHRNv4i16 %reg1039<kill>, 12, pred:14, pred:%reg0
310 bool PartReDef = isPartialRedef(MIIdx, MO, interval);
311 if (PartReDef || mi->isRegTiedToUseOperand(MOIdx)) {
312 // If this is a two-address definition, then we have already processed
313 // the live range. The only problem is that we didn't realize there
314 // are actually two values in the live interval. Because of this we
315 // need to take the LiveRegion that defines this register and split it
317 SlotIndex RedefIndex = MIIdx.getRegSlot(MO.isEarlyClobber());
319 const LiveRange *OldLR =
320 interval.getLiveRangeContaining(RedefIndex.getRegSlot(true));
321 VNInfo *OldValNo = OldLR->valno;
322 SlotIndex DefIndex = OldValNo->def.getRegSlot();
324 // Delete the previous value, which should be short and continuous,
325 // because the 2-addr copy must be in the same MBB as the redef.
326 interval.removeRange(DefIndex, RedefIndex);
328 // The new value number (#1) is defined by the instruction we claimed
330 VNInfo *ValNo = interval.createValueCopy(OldValNo, VNInfoAllocator);
332 // Value#0 is now defined by the 2-addr instruction.
333 OldValNo->def = RedefIndex;
334 OldValNo->setCopy(0);
336 // A re-def may be a copy. e.g. %reg1030:6<def> = VMOVD %reg1026, ...
337 if (PartReDef && mi->isCopyLike())
338 OldValNo->setCopy(&*mi);
340 // Add the new live interval which replaces the range for the input copy.
341 LiveRange LR(DefIndex, RedefIndex, ValNo);
342 DEBUG(dbgs() << " replace range with " << LR);
343 interval.addRange(LR);
345 // If this redefinition is dead, we need to add a dummy unit live
346 // range covering the def slot.
348 interval.addRange(LiveRange(RedefIndex, RedefIndex.getDeadSlot(),
352 dbgs() << " RESULT: ";
353 interval.print(dbgs(), tri_);
355 } else if (lv_->isPHIJoin(interval.reg)) {
356 // In the case of PHI elimination, each variable definition is only
357 // live until the end of the block. We've already taken care of the
358 // rest of the live range.
360 SlotIndex defIndex = MIIdx.getRegSlot();
361 if (MO.isEarlyClobber())
362 defIndex = MIIdx.getRegSlot(true);
365 MachineInstr *CopyMI = NULL;
366 if (mi->isCopyLike())
368 ValNo = interval.getNextValue(defIndex, CopyMI, VNInfoAllocator);
370 SlotIndex killIndex = getMBBEndIdx(mbb);
371 LiveRange LR(defIndex, killIndex, ValNo);
372 interval.addRange(LR);
373 ValNo->setHasPHIKill(true);
374 DEBUG(dbgs() << " phi-join +" << LR);
376 llvm_unreachable("Multiply defined register");
380 DEBUG(dbgs() << '\n');
383 void LiveIntervals::handlePhysicalRegisterDef(MachineBasicBlock *MBB,
384 MachineBasicBlock::iterator mi,
387 LiveInterval &interval,
388 MachineInstr *CopyMI) {
389 // A physical register cannot be live across basic block, so its
390 // lifetime must end somewhere in its defining basic block.
391 DEBUG(dbgs() << "\t\tregister: " << PrintReg(interval.reg, tri_));
393 SlotIndex baseIndex = MIIdx;
394 SlotIndex start = baseIndex.getRegSlot(MO.isEarlyClobber());
395 SlotIndex end = start;
397 // If it is not used after definition, it is considered dead at
398 // the instruction defining it. Hence its interval is:
399 // [defSlot(def), defSlot(def)+1)
400 // For earlyclobbers, the defSlot was pushed back one; the extra
401 // advance below compensates.
403 DEBUG(dbgs() << " dead");
404 end = start.getDeadSlot();
408 // If it is not dead on definition, it must be killed by a
409 // subsequent instruction. Hence its interval is:
410 // [defSlot(def), useSlot(kill)+1)
411 baseIndex = baseIndex.getNextIndex();
412 while (++mi != MBB->end()) {
414 if (mi->isDebugValue())
416 if (getInstructionFromIndex(baseIndex) == 0)
417 baseIndex = indexes_->getNextNonNullIndex(baseIndex);
419 if (mi->killsRegister(interval.reg, tri_)) {
420 DEBUG(dbgs() << " killed");
421 end = baseIndex.getRegSlot();
424 int DefIdx = mi->findRegisterDefOperandIdx(interval.reg,false,false,tri_);
426 if (mi->isRegTiedToUseOperand(DefIdx)) {
427 // Two-address instruction.
428 end = baseIndex.getRegSlot();
430 // Another instruction redefines the register before it is ever read.
431 // Then the register is essentially dead at the instruction that
432 // defines it. Hence its interval is:
433 // [defSlot(def), defSlot(def)+1)
434 DEBUG(dbgs() << " dead");
435 end = start.getDeadSlot();
441 baseIndex = baseIndex.getNextIndex();
444 // The only case we should have a dead physreg here without a killing or
445 // instruction where we know it's dead is if it is live-in to the function
446 // and never used. Another possible case is the implicit use of the
447 // physical register has been deleted by two-address pass.
448 end = start.getDeadSlot();
451 assert(start < end && "did not find end of interval?");
453 // Already exists? Extend old live interval.
454 VNInfo *ValNo = interval.getVNInfoAt(start);
455 bool Extend = ValNo != 0;
457 ValNo = interval.getNextValue(start, CopyMI, VNInfoAllocator);
458 if (Extend && MO.isEarlyClobber())
459 ValNo->setHasRedefByEC(true);
460 LiveRange LR(start, end, ValNo);
461 interval.addRange(LR);
462 DEBUG(dbgs() << " +" << LR << '\n');
465 void LiveIntervals::handleRegisterDef(MachineBasicBlock *MBB,
466 MachineBasicBlock::iterator MI,
470 if (TargetRegisterInfo::isVirtualRegister(MO.getReg()))
471 handleVirtualRegisterDef(MBB, MI, MIIdx, MO, MOIdx,
472 getOrCreateInterval(MO.getReg()));
474 MachineInstr *CopyMI = NULL;
475 if (MI->isCopyLike())
477 handlePhysicalRegisterDef(MBB, MI, MIIdx, MO,
478 getOrCreateInterval(MO.getReg()), CopyMI);
482 void LiveIntervals::handleLiveInRegister(MachineBasicBlock *MBB,
484 LiveInterval &interval, bool isAlias) {
485 DEBUG(dbgs() << "\t\tlivein register: " << PrintReg(interval.reg, tri_));
487 // Look for kills, if it reaches a def before it's killed, then it shouldn't
488 // be considered a livein.
489 MachineBasicBlock::iterator mi = MBB->begin();
490 MachineBasicBlock::iterator E = MBB->end();
491 // Skip over DBG_VALUE at the start of the MBB.
492 if (mi != E && mi->isDebugValue()) {
493 while (++mi != E && mi->isDebugValue())
496 // MBB is empty except for DBG_VALUE's.
500 SlotIndex baseIndex = MIIdx;
501 SlotIndex start = baseIndex;
502 if (getInstructionFromIndex(baseIndex) == 0)
503 baseIndex = indexes_->getNextNonNullIndex(baseIndex);
505 SlotIndex end = baseIndex;
506 bool SeenDefUse = false;
509 if (mi->killsRegister(interval.reg, tri_)) {
510 DEBUG(dbgs() << " killed");
511 end = baseIndex.getRegSlot();
514 } else if (mi->definesRegister(interval.reg, tri_)) {
515 // Another instruction redefines the register before it is ever read.
516 // Then the register is essentially dead at the instruction that defines
517 // it. Hence its interval is:
518 // [defSlot(def), defSlot(def)+1)
519 DEBUG(dbgs() << " dead");
520 end = start.getDeadSlot();
525 while (++mi != E && mi->isDebugValue())
526 // Skip over DBG_VALUE.
529 baseIndex = indexes_->getNextNonNullIndex(baseIndex);
532 // Live-in register might not be used at all.
535 DEBUG(dbgs() << " dead");
536 end = MIIdx.getDeadSlot();
538 DEBUG(dbgs() << " live through");
539 end = getMBBEndIdx(MBB);
543 SlotIndex defIdx = getMBBStartIdx(MBB);
544 assert(getInstructionFromIndex(defIdx) == 0 &&
545 "PHI def index points at actual instruction.");
547 interval.getNextValue(defIdx, 0, VNInfoAllocator);
548 vni->setIsPHIDef(true);
549 LiveRange LR(start, end, vni);
551 interval.addRange(LR);
552 DEBUG(dbgs() << " +" << LR << '\n');
555 /// computeIntervals - computes the live intervals for virtual
556 /// registers. for some ordering of the machine instructions [1,N] a
557 /// live interval is an interval [i, j) where 1 <= i <= j < N for
558 /// which a variable is live
559 void LiveIntervals::computeIntervals() {
560 DEBUG(dbgs() << "********** COMPUTING LIVE INTERVALS **********\n"
561 << "********** Function: "
562 << ((Value*)mf_->getFunction())->getName() << '\n');
564 SmallVector<unsigned, 8> UndefUses;
565 for (MachineFunction::iterator MBBI = mf_->begin(), E = mf_->end();
567 MachineBasicBlock *MBB = MBBI;
571 // Track the index of the current machine instr.
572 SlotIndex MIIndex = getMBBStartIdx(MBB);
573 DEBUG(dbgs() << "BB#" << MBB->getNumber()
574 << ":\t\t# derived from " << MBB->getName() << "\n");
576 // Create intervals for live-ins to this BB first.
577 for (MachineBasicBlock::livein_iterator LI = MBB->livein_begin(),
578 LE = MBB->livein_end(); LI != LE; ++LI) {
579 handleLiveInRegister(MBB, MIIndex, getOrCreateInterval(*LI));
582 // Skip over empty initial indices.
583 if (getInstructionFromIndex(MIIndex) == 0)
584 MIIndex = indexes_->getNextNonNullIndex(MIIndex);
586 for (MachineBasicBlock::iterator MI = MBB->begin(), miEnd = MBB->end();
588 DEBUG(dbgs() << MIIndex << "\t" << *MI);
589 if (MI->isDebugValue())
593 for (int i = MI->getNumOperands() - 1; i >= 0; --i) {
594 MachineOperand &MO = MI->getOperand(i);
595 if (!MO.isReg() || !MO.getReg())
598 // handle register defs - build intervals
600 handleRegisterDef(MBB, MI, MIIndex, MO, i);
601 else if (MO.isUndef())
602 UndefUses.push_back(MO.getReg());
605 // Move to the next instr slot.
606 MIIndex = indexes_->getNextNonNullIndex(MIIndex);
610 // Create empty intervals for registers defined by implicit_def's (except
611 // for those implicit_def that define values which are liveout of their
613 for (unsigned i = 0, e = UndefUses.size(); i != e; ++i) {
614 unsigned UndefReg = UndefUses[i];
615 (void)getOrCreateInterval(UndefReg);
619 LiveInterval* LiveIntervals::createInterval(unsigned reg) {
620 float Weight = TargetRegisterInfo::isPhysicalRegister(reg) ? HUGE_VALF : 0.0F;
621 return new LiveInterval(reg, Weight);
624 /// dupInterval - Duplicate a live interval. The caller is responsible for
625 /// managing the allocated memory.
626 LiveInterval* LiveIntervals::dupInterval(LiveInterval *li) {
627 LiveInterval *NewLI = createInterval(li->reg);
628 NewLI->Copy(*li, mri_, getVNInfoAllocator());
632 /// shrinkToUses - After removing some uses of a register, shrink its live
633 /// range to just the remaining uses. This method does not compute reaching
634 /// defs for new uses, and it doesn't remove dead defs.
635 bool LiveIntervals::shrinkToUses(LiveInterval *li,
636 SmallVectorImpl<MachineInstr*> *dead) {
637 DEBUG(dbgs() << "Shrink: " << *li << '\n');
638 assert(TargetRegisterInfo::isVirtualRegister(li->reg)
639 && "Can only shrink virtual registers");
640 // Find all the values used, including PHI kills.
641 SmallVector<std::pair<SlotIndex, VNInfo*>, 16> WorkList;
643 // Blocks that have already been added to WorkList as live-out.
644 SmallPtrSet<MachineBasicBlock*, 16> LiveOut;
646 // Visit all instructions reading li->reg.
647 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(li->reg);
648 MachineInstr *UseMI = I.skipInstruction();) {
649 if (UseMI->isDebugValue() || !UseMI->readsVirtualRegister(li->reg))
651 SlotIndex Idx = getInstructionIndex(UseMI).getRegSlot();
652 // Note: This intentionally picks up the wrong VNI in case of an EC redef.
654 VNInfo *VNI = li->getVNInfoBefore(Idx);
656 // This shouldn't happen: readsVirtualRegister returns true, but there is
657 // no live value. It is likely caused by a target getting <undef> flags
659 DEBUG(dbgs() << Idx << '\t' << *UseMI
660 << "Warning: Instr claims to read non-existent value in "
664 // Special case: An early-clobber tied operand reads and writes the
665 // register one slot early. The getVNInfoBefore call above would have
666 // picked up the value defined by UseMI. Adjust the kill slot and value.
667 if (SlotIndex::isSameInstr(VNI->def, Idx)) {
669 VNI = li->getVNInfoBefore(Idx);
670 assert(VNI && "Early-clobber tied value not available");
672 WorkList.push_back(std::make_pair(Idx, VNI));
675 // Create a new live interval with only minimal live segments per def.
676 LiveInterval NewLI(li->reg, 0);
677 for (LiveInterval::vni_iterator I = li->vni_begin(), E = li->vni_end();
682 NewLI.addRange(LiveRange(VNI->def, VNI->def.getDeadSlot(), VNI));
685 // Keep track of the PHIs that are in use.
686 SmallPtrSet<VNInfo*, 8> UsedPHIs;
688 // Extend intervals to reach all uses in WorkList.
689 while (!WorkList.empty()) {
690 SlotIndex Idx = WorkList.back().first;
691 VNInfo *VNI = WorkList.back().second;
693 const MachineBasicBlock *MBB = getMBBFromIndex(Idx.getPrevSlot());
694 SlotIndex BlockStart = getMBBStartIdx(MBB);
696 // Extend the live range for VNI to be live at Idx.
697 if (VNInfo *ExtVNI = NewLI.extendInBlock(BlockStart, Idx)) {
699 assert(ExtVNI == VNI && "Unexpected existing value number");
700 // Is this a PHIDef we haven't seen before?
701 if (!VNI->isPHIDef() || VNI->def != BlockStart || !UsedPHIs.insert(VNI))
703 // The PHI is live, make sure the predecessors are live-out.
704 for (MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(),
705 PE = MBB->pred_end(); PI != PE; ++PI) {
706 if (!LiveOut.insert(*PI))
708 SlotIndex Stop = getMBBEndIdx(*PI);
709 // A predecessor is not required to have a live-out value for a PHI.
710 if (VNInfo *PVNI = li->getVNInfoBefore(Stop))
711 WorkList.push_back(std::make_pair(Stop, PVNI));
716 // VNI is live-in to MBB.
717 DEBUG(dbgs() << " live-in at " << BlockStart << '\n');
718 NewLI.addRange(LiveRange(BlockStart, Idx, VNI));
720 // Make sure VNI is live-out from the predecessors.
721 for (MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(),
722 PE = MBB->pred_end(); PI != PE; ++PI) {
723 if (!LiveOut.insert(*PI))
725 SlotIndex Stop = getMBBEndIdx(*PI);
726 assert(li->getVNInfoBefore(Stop) == VNI &&
727 "Wrong value out of predecessor");
728 WorkList.push_back(std::make_pair(Stop, VNI));
732 // Handle dead values.
733 bool CanSeparate = false;
734 for (LiveInterval::vni_iterator I = li->vni_begin(), E = li->vni_end();
739 LiveInterval::iterator LII = NewLI.FindLiveRangeContaining(VNI->def);
740 assert(LII != NewLI.end() && "Missing live range for PHI");
741 if (LII->end != VNI->def.getDeadSlot())
743 if (VNI->isPHIDef()) {
744 // This is a dead PHI. Remove it.
745 VNI->setIsUnused(true);
746 NewLI.removeRange(*LII);
747 DEBUG(dbgs() << "Dead PHI at " << VNI->def << " may separate interval\n");
750 // This is a dead def. Make sure the instruction knows.
751 MachineInstr *MI = getInstructionFromIndex(VNI->def);
752 assert(MI && "No instruction defining live value");
753 MI->addRegisterDead(li->reg, tri_);
754 if (dead && MI->allDefsAreDead()) {
755 DEBUG(dbgs() << "All defs dead: " << VNI->def << '\t' << *MI);
761 // Move the trimmed ranges back.
762 li->ranges.swap(NewLI.ranges);
763 DEBUG(dbgs() << "Shrunk: " << *li << '\n');
768 //===----------------------------------------------------------------------===//
769 // Register allocator hooks.
772 void LiveIntervals::addKillFlags() {
773 for (iterator I = begin(), E = end(); I != E; ++I) {
774 unsigned Reg = I->first;
775 if (TargetRegisterInfo::isPhysicalRegister(Reg))
777 if (mri_->reg_nodbg_empty(Reg))
779 LiveInterval *LI = I->second;
781 // Every instruction that kills Reg corresponds to a live range end point.
782 for (LiveInterval::iterator RI = LI->begin(), RE = LI->end(); RI != RE;
784 // A block index indicates an MBB edge.
785 if (RI->end.isBlock())
787 MachineInstr *MI = getInstructionFromIndex(RI->end);
790 MI->addRegisterKilled(Reg, NULL);
796 static bool intervalRangesSane(const LiveInterval& li) {
801 SlotIndex lastEnd = li.begin()->start;
802 for (LiveInterval::const_iterator lrItr = li.begin(), lrEnd = li.end();
803 lrItr != lrEnd; ++lrItr) {
804 const LiveRange& lr = *lrItr;
805 if (lastEnd > lr.start || lr.start >= lr.end)
814 template <typename DefSetT>
815 static void handleMoveDefs(LiveIntervals& lis, SlotIndex origIdx,
816 SlotIndex miIdx, const DefSetT& defs) {
817 for (typename DefSetT::const_iterator defItr = defs.begin(),
819 defItr != defEnd; ++defItr) {
820 unsigned def = *defItr;
821 LiveInterval& li = lis.getInterval(def);
822 LiveRange* lr = li.getLiveRangeContaining(origIdx.getRegSlot());
823 assert(lr != 0 && "No range for def?");
824 lr->start = miIdx.getRegSlot();
825 lr->valno->def = miIdx.getRegSlot();
826 assert(intervalRangesSane(li) && "Broke live interval moving def.");
830 template <typename DeadDefSetT>
831 static void handleMoveDeadDefs(LiveIntervals& lis, SlotIndex origIdx,
832 SlotIndex miIdx, const DeadDefSetT& deadDefs) {
833 for (typename DeadDefSetT::const_iterator deadDefItr = deadDefs.begin(),
834 deadDefEnd = deadDefs.end();
835 deadDefItr != deadDefEnd; ++deadDefItr) {
836 unsigned deadDef = *deadDefItr;
837 LiveInterval& li = lis.getInterval(deadDef);
838 LiveRange* lr = li.getLiveRangeContaining(origIdx.getRegSlot());
839 assert(lr != 0 && "No range for dead def?");
840 assert(lr->start == origIdx.getRegSlot() && "Bad dead range start?");
841 assert(lr->end == origIdx.getDeadSlot() && "Bad dead range end?");
842 assert(lr->valno->def == origIdx.getRegSlot() && "Bad dead valno def.");
844 t.start = miIdx.getRegSlot();
845 t.valno->def = miIdx.getRegSlot();
846 t.end = miIdx.getDeadSlot();
849 assert(intervalRangesSane(li) && "Broke live interval moving dead def.");
853 template <typename ECSetT>
854 static void handleMoveECs(LiveIntervals& lis, SlotIndex origIdx,
855 SlotIndex miIdx, const ECSetT& ecs) {
856 for (typename ECSetT::const_iterator ecItr = ecs.begin(), ecEnd = ecs.end();
857 ecItr != ecEnd; ++ecItr) {
858 unsigned ec = *ecItr;
859 LiveInterval& li = lis.getInterval(ec);
860 LiveRange* lr = li.getLiveRangeContaining(origIdx.getRegSlot(true));
861 assert(lr != 0 && "No range for early clobber?");
862 assert(lr->start == origIdx.getRegSlot(true) && "Bad EC range start?");
863 assert(lr->end == origIdx.getRegSlot() && "Bad EC range end.");
864 assert(lr->valno->def == origIdx.getRegSlot(true) && "Bad EC valno def.");
866 t.start = miIdx.getRegSlot(true);
867 t.valno->def = miIdx.getRegSlot(true);
868 t.end = miIdx.getRegSlot();
871 assert(intervalRangesSane(li) && "Broke live interval moving EC.");
875 template <typename UseSetT>
876 static void handleMoveUses(const MachineBasicBlock *mbb,
877 const MachineRegisterInfo& mri,
878 const BitVector& reservedRegs, LiveIntervals &lis,
879 SlotIndex origIdx, SlotIndex miIdx,
880 const UseSetT &uses) {
881 bool movingUp = miIdx < origIdx;
882 for (typename UseSetT::const_iterator usesItr = uses.begin(),
883 usesEnd = uses.end();
884 usesItr != usesEnd; ++usesItr) {
885 unsigned use = *usesItr;
886 if (!lis.hasInterval(use))
888 if (TargetRegisterInfo::isPhysicalRegister(use) && reservedRegs.test(use))
890 LiveInterval& li = lis.getInterval(use);
891 LiveRange* lr = li.getLiveRangeBefore(origIdx.getRegSlot());
892 assert(lr != 0 && "No range for use?");
893 bool liveThrough = lr->end > origIdx.getRegSlot();
896 // If moving up and liveThrough - nothing to do.
897 // If not live through we need to extend the range to the last use
898 // between the old location and the new one.
900 SlotIndex lastUseInRange = miIdx.getRegSlot();
901 for (MachineRegisterInfo::use_iterator useI = mri.use_begin(use),
902 useE = mri.use_end();
903 useI != useE; ++useI) {
904 const MachineInstr* mopI = &*useI;
905 const MachineOperand& mop = useI.getOperand();
906 SlotIndex instSlot = lis.getSlotIndexes()->getInstructionIndex(mopI);
907 SlotIndex opSlot = instSlot.getRegSlot(mop.isEarlyClobber());
908 if (opSlot >= lastUseInRange && opSlot < origIdx) {
909 lastUseInRange = opSlot;
912 lr->end = lastUseInRange;
915 // Moving down is easy - the existing live range end tells us where
918 // Easy fix - just update the range endpoint.
919 lr->end = miIdx.getRegSlot();
921 bool liveOut = lr->end >= lis.getSlotIndexes()->getMBBEndIdx(mbb);
922 if (!liveOut && miIdx.getRegSlot() > lr->end) {
923 lr->end = miIdx.getRegSlot();
927 assert(intervalRangesSane(li) && "Broke live interval moving use.");
931 void LiveIntervals::moveInstr(MachineBasicBlock::iterator insertPt,
933 MachineBasicBlock* mbb = mi->getParent();
934 assert((insertPt == mbb->end() || insertPt->getParent() == mbb) &&
935 "Cannot handle moves across basic block boundaries.");
936 assert(&*insertPt != mi && "No-op move requested?");
937 assert(!mi->isInsideBundle() && "Can't handle bundled instructions yet.");
939 // Grab the original instruction index.
940 SlotIndex origIdx = indexes_->getInstructionIndex(mi);
942 // Move the machine instr and obtain its new index.
943 indexes_->removeMachineInstrFromMaps(mi);
945 mbb->insert(insertPt, mi);
946 SlotIndex miIdx = indexes_->insertMachineInstrInMaps(mi);
948 // Pick the direction.
949 bool movingUp = miIdx < origIdx;
951 // Collect the operands.
952 DenseSet<unsigned> uses, defs, deadDefs, ecs;
953 for (MachineInstr::mop_iterator mopItr = mi->operands_begin(),
954 mopEnd = mi->operands_end();
955 mopItr != mopEnd; ++mopItr) {
956 const MachineOperand& mop = *mopItr;
958 if (!mop.isReg() || mop.getReg() == 0)
960 unsigned reg = mop.getReg();
962 assert(mop.readsReg());
965 if (mop.readsReg() && !ecs.count(reg)) {
970 assert(!defs.count(reg) && "Can't mix defs with dead-defs.");
971 deadDefs.insert(reg);
972 } else if (mop.isEarlyClobber()) {
976 assert(!deadDefs.count(reg) && "Can't mix defs with dead-defs.");
982 BitVector reservedRegs(tri_->getReservedRegs(*mbb->getParent()));
985 handleMoveUses(mbb, *mri_, reservedRegs, *this, origIdx, miIdx, uses);
986 handleMoveECs(*this, origIdx, miIdx, ecs);
987 handleMoveDeadDefs(*this, origIdx, miIdx, deadDefs);
988 handleMoveDefs(*this, origIdx, miIdx, defs);
990 handleMoveDefs(*this, origIdx, miIdx, defs);
991 handleMoveDeadDefs(*this, origIdx, miIdx, deadDefs);
992 handleMoveECs(*this, origIdx, miIdx, ecs);
993 handleMoveUses(mbb, *mri_, reservedRegs, *this, origIdx, miIdx, uses);
997 /// getReMatImplicitUse - If the remat definition MI has one (for now, we only
998 /// allow one) virtual register operand, then its uses are implicitly using
999 /// the register. Returns the virtual register.
1000 unsigned LiveIntervals::getReMatImplicitUse(const LiveInterval &li,
1001 MachineInstr *MI) const {
1003 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1004 MachineOperand &MO = MI->getOperand(i);
1005 if (!MO.isReg() || !MO.isUse())
1007 unsigned Reg = MO.getReg();
1008 if (Reg == 0 || Reg == li.reg)
1011 if (TargetRegisterInfo::isPhysicalRegister(Reg) &&
1012 !allocatableRegs_[Reg])
1014 RegOp = MO.getReg();
1015 break; // Found vreg operand - leave the loop.
1020 /// isValNoAvailableAt - Return true if the val# of the specified interval
1021 /// which reaches the given instruction also reaches the specified use index.
1022 bool LiveIntervals::isValNoAvailableAt(const LiveInterval &li, MachineInstr *MI,
1023 SlotIndex UseIdx) const {
1024 VNInfo *UValNo = li.getVNInfoAt(UseIdx);
1025 return UValNo && UValNo == li.getVNInfoAt(getInstructionIndex(MI));
1028 /// isReMaterializable - Returns true if the definition MI of the specified
1029 /// val# of the specified interval is re-materializable.
1031 LiveIntervals::isReMaterializable(const LiveInterval &li,
1032 const VNInfo *ValNo, MachineInstr *MI,
1033 const SmallVectorImpl<LiveInterval*> *SpillIs,
1038 if (!tii_->isTriviallyReMaterializable(MI, aa_))
1041 // Target-specific code can mark an instruction as being rematerializable
1042 // if it has one virtual reg use, though it had better be something like
1043 // a PIC base register which is likely to be live everywhere.
1044 unsigned ImpUse = getReMatImplicitUse(li, MI);
1046 const LiveInterval &ImpLi = getInterval(ImpUse);
1047 for (MachineRegisterInfo::use_nodbg_iterator
1048 ri = mri_->use_nodbg_begin(li.reg), re = mri_->use_nodbg_end();
1050 MachineInstr *UseMI = &*ri;
1051 SlotIndex UseIdx = getInstructionIndex(UseMI);
1052 if (li.getVNInfoAt(UseIdx) != ValNo)
1054 if (!isValNoAvailableAt(ImpLi, MI, UseIdx))
1058 // If a register operand of the re-materialized instruction is going to
1059 // be spilled next, then it's not legal to re-materialize this instruction.
1061 for (unsigned i = 0, e = SpillIs->size(); i != e; ++i)
1062 if (ImpUse == (*SpillIs)[i]->reg)
1068 /// isReMaterializable - Returns true if every definition of MI of every
1069 /// val# of the specified interval is re-materializable.
1071 LiveIntervals::isReMaterializable(const LiveInterval &li,
1072 const SmallVectorImpl<LiveInterval*> *SpillIs,
1075 for (LiveInterval::const_vni_iterator i = li.vni_begin(), e = li.vni_end();
1077 const VNInfo *VNI = *i;
1078 if (VNI->isUnused())
1079 continue; // Dead val#.
1080 // Is the def for the val# rematerializable?
1081 MachineInstr *ReMatDefMI = getInstructionFromIndex(VNI->def);
1084 bool DefIsLoad = false;
1086 !isReMaterializable(li, VNI, ReMatDefMI, SpillIs, DefIsLoad))
1088 isLoad |= DefIsLoad;
1093 bool LiveIntervals::intervalIsInOneMBB(const LiveInterval &li) const {
1094 LiveInterval::Ranges::const_iterator itr = li.ranges.begin();
1096 MachineBasicBlock *mbb = indexes_->getMBBCoveringRange(itr->start, itr->end);
1101 for (++itr; itr != li.ranges.end(); ++itr) {
1102 MachineBasicBlock *mbb2 =
1103 indexes_->getMBBCoveringRange(itr->start, itr->end);
1113 LiveIntervals::getSpillWeight(bool isDef, bool isUse, unsigned loopDepth) {
1114 // Limit the loop depth ridiculousness.
1115 if (loopDepth > 200)
1118 // The loop depth is used to roughly estimate the number of times the
1119 // instruction is executed. Something like 10^d is simple, but will quickly
1120 // overflow a float. This expression behaves like 10^d for small d, but is
1121 // more tempered for large d. At d=200 we get 6.7e33 which leaves a bit of
1122 // headroom before overflow.
1123 // By the way, powf() might be unavailable here. For consistency,
1124 // We may take pow(double,double).
1125 float lc = std::pow(1 + (100.0 / (loopDepth + 10)), (double)loopDepth);
1127 return (isDef + isUse) * lc;
1130 LiveRange LiveIntervals::addLiveRangeToEndOfBlock(unsigned reg,
1131 MachineInstr* startInst) {
1132 LiveInterval& Interval = getOrCreateInterval(reg);
1133 VNInfo* VN = Interval.getNextValue(
1134 SlotIndex(getInstructionIndex(startInst).getRegSlot()),
1135 startInst, getVNInfoAllocator());
1136 VN->setHasPHIKill(true);
1138 SlotIndex(getInstructionIndex(startInst).getRegSlot()),
1139 getMBBEndIdx(startInst->getParent()), VN);
1140 Interval.addRange(LR);