1 //===-- LiveIntervals.cpp - Live Interval Analysis ------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source 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 "liveintervals"
19 #include "LiveIntervals.h"
20 #include "llvm/Value.h"
21 #include "llvm/Analysis/LoopInfo.h"
22 #include "llvm/CodeGen/LiveVariables.h"
23 #include "llvm/CodeGen/MachineFrameInfo.h"
24 #include "llvm/CodeGen/MachineInstr.h"
25 #include "llvm/CodeGen/Passes.h"
26 #include "llvm/CodeGen/SSARegMap.h"
27 #include "llvm/Target/MRegisterInfo.h"
28 #include "llvm/Target/TargetInstrInfo.h"
29 #include "llvm/Target/TargetMachine.h"
30 #include "Support/CommandLine.h"
31 #include "Support/Debug.h"
32 #include "Support/Statistic.h"
33 #include "Support/STLExtras.h"
34 #include "VirtRegMap.h"
41 RegisterAnalysis<LiveIntervals> X("liveintervals",
42 "Live Interval Analysis");
44 Statistic<> numIntervals
45 ("liveintervals", "Number of original intervals");
47 Statistic<> numIntervalsAfter
48 ("liveintervals", "Number of intervals after coalescing");
51 ("liveintervals", "Number of interval joins performed");
54 ("liveintervals", "Number of identity moves eliminated after coalescing");
57 ("liveintervals", "Number of loads/stores folded into instructions");
60 join("join-liveintervals",
61 cl::desc("Join compatible live intervals"),
65 void LiveIntervals::getAnalysisUsage(AnalysisUsage &AU) const
67 AU.addPreserved<LiveVariables>();
68 AU.addRequired<LiveVariables>();
69 AU.addPreservedID(PHIEliminationID);
70 AU.addRequiredID(PHIEliminationID);
71 AU.addRequiredID(TwoAddressInstructionPassID);
72 AU.addRequired<LoopInfo>();
73 MachineFunctionPass::getAnalysisUsage(AU);
76 void LiveIntervals::releaseMemory()
87 /// runOnMachineFunction - Register allocate the whole function
89 bool LiveIntervals::runOnMachineFunction(MachineFunction &fn) {
91 tm_ = &fn.getTarget();
92 mri_ = tm_->getRegisterInfo();
93 lv_ = &getAnalysis<LiveVariables>();
95 // number MachineInstrs
97 for (MachineFunction::iterator mbb = mf_->begin(), mbbEnd = mf_->end();
98 mbb != mbbEnd; ++mbb) {
99 unsigned mbbIdx = lv_->getMachineBasicBlockIndex(mbb);
100 bool inserted = mbbi2mbbMap_.insert(std::make_pair(mbbIdx,
102 assert(inserted && "multiple index -> MachineBasicBlock");
104 for (MachineBasicBlock::iterator mi = mbb->begin(), miEnd = mbb->end();
106 inserted = mi2iMap_.insert(std::make_pair(mi, miIndex)).second;
107 assert(inserted && "multiple MachineInstr -> index mappings");
108 i2miMap_.push_back(mi);
109 miIndex += InstrSlots::NUM;
115 numIntervals += intervals_.size();
117 // join intervals if requested
118 if (join) joinIntervals();
120 numIntervalsAfter += intervals_.size();
122 // perform a final pass over the instructions and compute spill
123 // weights, coalesce virtual registers and remove identity moves
124 const LoopInfo& loopInfo = getAnalysis<LoopInfo>();
125 const TargetInstrInfo& tii = tm_->getInstrInfo();
127 for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
128 mbbi != mbbe; ++mbbi) {
129 MachineBasicBlock* mbb = mbbi;
130 unsigned loopDepth = loopInfo.getLoopDepth(mbb->getBasicBlock());
132 for (MachineBasicBlock::iterator mii = mbb->begin(), mie = mbb->end();
134 // if the move will be an identity move delete it
135 unsigned srcReg, dstReg;
136 if (tii.isMoveInstr(*mii, srcReg, dstReg) &&
137 rep(srcReg) == rep(dstReg)) {
138 // remove from def list
139 Interval& interval = getOrCreateInterval(rep(dstReg));
140 unsigned defIndex = getInstructionIndex(mii);
141 Interval::Defs::iterator d = std::lower_bound(
142 interval.defs.begin(), interval.defs.end(), defIndex);
143 assert(*d == defIndex && "Def index not found in def list!");
144 interval.defs.erase(d);
145 // remove index -> MachineInstr and
146 // MachineInstr -> index mappings
147 Mi2IndexMap::iterator mi2i = mi2iMap_.find(mii);
148 if (mi2i != mi2iMap_.end()) {
149 i2miMap_[mi2i->second/InstrSlots::NUM] = 0;
150 mi2iMap_.erase(mi2i);
152 mii = mbbi->erase(mii);
156 for (unsigned i = 0; i < mii->getNumOperands(); ++i) {
157 const MachineOperand& mop = mii->getOperand(i);
158 if (mop.isRegister() && mop.getReg() &&
159 MRegisterInfo::isVirtualRegister(mop.getReg())) {
160 // replace register with representative register
161 unsigned reg = rep(mop.getReg());
162 mii->SetMachineOperandReg(i, reg);
164 Reg2IntervalMap::iterator r2iit = r2iMap_.find(reg);
165 assert(r2iit != r2iMap_.end());
166 r2iit->second->weight +=
167 (mop.isUse() + mop.isDef()) * pow(10.0F, loopDepth);
175 intervals_.sort(StartPointComp());
176 DEBUG(std::cerr << "********** INTERVALS **********\n");
177 DEBUG(std::copy(intervals_.begin(), intervals_.end(),
178 std::ostream_iterator<Interval>(std::cerr, "\n")));
179 DEBUG(std::cerr << "********** MACHINEINSTRS **********\n");
181 for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
182 mbbi != mbbe; ++mbbi) {
183 std::cerr << ((Value*)mbbi->getBasicBlock())->getName() << ":\n";
184 for (MachineBasicBlock::iterator mii = mbbi->begin(),
185 mie = mbbi->end(); mii != mie; ++mii) {
186 std::cerr << getInstructionIndex(mii) << '\t';
187 mii->print(std::cerr, *tm_);
194 void LiveIntervals::updateSpilledInterval(Interval& li,
198 assert(li.weight != HUGE_VAL &&
199 "attempt to spill already spilled interval!");
200 Interval::Ranges oldRanges;
201 swap(oldRanges, li.ranges);
203 DEBUG(std::cerr << "\t\t\t\tupdating interval: " << li);
205 for (Interval::Ranges::iterator i = oldRanges.begin(), e = oldRanges.end();
207 unsigned index = getBaseIndex(i->first);
208 unsigned end = getBaseIndex(i->second-1) + InstrSlots::NUM;
209 for (; index < end; index += InstrSlots::NUM) {
210 // skip deleted instructions
211 while (!getInstructionFromIndex(index)) index += InstrSlots::NUM;
212 MachineBasicBlock::iterator mi = getInstructionFromIndex(index);
215 for (unsigned i = 0; i < mi->getNumOperands(); ++i) {
216 MachineOperand& mop = mi->getOperand(i);
217 if (mop.isRegister() && mop.getReg() == li.reg) {
218 if (MachineInstr* fmi =
219 mri_->foldMemoryOperand(mi, i, slot)) {
220 lv_->instructionChanged(mi, fmi);
221 vrm.virtFolded(li.reg, mi, fmi);
223 i2miMap_[index/InstrSlots::NUM] = fmi;
224 mi2iMap_[fmi] = index;
225 MachineBasicBlock& mbb = *mi->getParent();
226 mi = mbb.insert(mbb.erase(mi), fmi);
231 // This is tricky. We need to add information in
232 // the interval about the spill code so we have to
233 // use our extra load/store slots.
235 // If we have a use we are going to have a load so
236 // we start the interval from the load slot
237 // onwards. Otherwise we start from the def slot.
238 unsigned start = (mop.isUse() ?
239 getLoadIndex(index) :
241 // If we have a def we are going to have a store
242 // right after it so we end the interval after the
243 // use of the next instruction. Otherwise we end
244 // after the use of this instruction.
245 unsigned end = 1 + (mop.isDef() ?
246 getUseIndex(index+InstrSlots::NUM) :
248 li.addRange(start, end);
254 // the new spill weight is now infinity as it cannot be spilled again
255 li.weight = HUGE_VAL;
256 DEBUG(std::cerr << '\n');
257 DEBUG(std::cerr << "\t\t\t\tupdated interval: " << li << '\n');
260 void LiveIntervals::printRegName(unsigned reg) const
262 if (MRegisterInfo::isPhysicalRegister(reg))
263 std::cerr << mri_->getName(reg);
265 std::cerr << "%reg" << reg;
268 void LiveIntervals::handleVirtualRegisterDef(MachineBasicBlock* mbb,
269 MachineBasicBlock::iterator mi,
272 DEBUG(std::cerr << "\t\tregister: "; printRegName(interval.reg));
273 LiveVariables::VarInfo& vi = lv_->getVarInfo(interval.reg);
275 // iterate over all of the blocks that the variable is completely
276 // live in, adding them to the live interval. obviously we only
277 // need to do this once.
278 if (interval.empty()) {
279 for (unsigned i = 0, e = vi.AliveBlocks.size(); i != e; ++i) {
280 if (vi.AliveBlocks[i]) {
281 MachineBasicBlock* mbb = lv_->getIndexMachineBasicBlock(i);
284 getInstructionIndex(&mbb->front()),
285 getInstructionIndex(&mbb->back()) + InstrSlots::NUM);
291 unsigned baseIndex = getInstructionIndex(mi);
292 interval.defs.push_back(baseIndex);
294 bool killedInDefiningBasicBlock = false;
295 for (int i = 0, e = vi.Kills.size(); i != e; ++i) {
296 MachineBasicBlock* killerBlock = vi.Kills[i].first;
297 MachineInstr* killerInstr = vi.Kills[i].second;
298 unsigned start = (mbb == killerBlock ?
299 getDefIndex(baseIndex) :
300 getInstructionIndex(&killerBlock->front()));
301 unsigned end = (killerInstr == mi ?
305 getUseIndex(getInstructionIndex(killerInstr))+1);
306 // we do not want to add invalid ranges. these can happen when
307 // a variable has its latest use and is redefined later on in
308 // the same basic block (common with variables introduced by
311 killedInDefiningBasicBlock |= mbb == killerBlock;
312 interval.addRange(start, end);
316 if (!killedInDefiningBasicBlock) {
317 unsigned end = getInstructionIndex(&mbb->back()) + InstrSlots::NUM;
318 interval.addRange(getDefIndex(baseIndex), end);
320 DEBUG(std::cerr << '\n');
323 void LiveIntervals::handlePhysicalRegisterDef(MachineBasicBlock* mbb,
324 MachineBasicBlock::iterator mi,
327 DEBUG(std::cerr << "\t\tregister: "; printRegName(interval.reg));
328 typedef LiveVariables::killed_iterator KillIter;
330 MachineBasicBlock::iterator e = mbb->end();
331 unsigned baseIndex = getInstructionIndex(mi);
332 interval.defs.push_back(baseIndex);
333 unsigned start = getDefIndex(baseIndex);
334 unsigned end = start;
336 // a variable can be dead by the instruction defining it
337 for (KillIter ki = lv_->dead_begin(mi), ke = lv_->dead_end(mi);
339 if (interval.reg == ki->second) {
340 DEBUG(std::cerr << " dead");
341 end = getDefIndex(start) + 1;
346 // a variable can only be killed by subsequent instructions
349 baseIndex += InstrSlots::NUM;
350 for (KillIter ki = lv_->killed_begin(mi), ke = lv_->killed_end(mi);
352 if (interval.reg == ki->second) {
353 DEBUG(std::cerr << " killed");
354 end = getUseIndex(baseIndex) + 1;
361 assert(start < end && "did not find end of interval?");
362 interval.addRange(start, end);
363 DEBUG(std::cerr << '\n');
366 void LiveIntervals::handleRegisterDef(MachineBasicBlock* mbb,
367 MachineBasicBlock::iterator mi,
370 if (MRegisterInfo::isPhysicalRegister(reg)) {
371 if (lv_->getAllocatablePhysicalRegisters()[reg]) {
372 handlePhysicalRegisterDef(mbb, mi, getOrCreateInterval(reg));
373 for (const unsigned* as = mri_->getAliasSet(reg); *as; ++as)
374 handlePhysicalRegisterDef(mbb, mi, getOrCreateInterval(*as));
378 handleVirtualRegisterDef(mbb, mi, getOrCreateInterval(reg));
381 unsigned LiveIntervals::getInstructionIndex(MachineInstr* instr) const
383 Mi2IndexMap::const_iterator it = mi2iMap_.find(instr);
384 return (it == mi2iMap_.end() ?
385 std::numeric_limits<unsigned>::max() :
389 MachineInstr* LiveIntervals::getInstructionFromIndex(unsigned index) const
391 index /= InstrSlots::NUM; // convert index to vector index
392 assert(index < i2miMap_.size() &&
393 "index does not correspond to an instruction");
394 return i2miMap_[index];
397 /// computeIntervals - computes the live intervals for virtual
398 /// registers. for some ordering of the machine instructions [1,N] a
399 /// live interval is an interval [i, j) where 1 <= i <= j < N for
400 /// which a variable is live
401 void LiveIntervals::computeIntervals()
403 DEBUG(std::cerr << "********** COMPUTING LIVE INTERVALS **********\n");
404 DEBUG(std::cerr << "********** Function: "
405 << ((Value*)mf_->getFunction())->getName() << '\n');
407 for (MbbIndex2MbbMap::iterator
408 it = mbbi2mbbMap_.begin(), itEnd = mbbi2mbbMap_.end();
410 MachineBasicBlock* mbb = it->second;
411 DEBUG(std::cerr << ((Value*)mbb->getBasicBlock())->getName() << ":\n");
413 for (MachineBasicBlock::iterator mi = mbb->begin(), miEnd = mbb->end();
415 const TargetInstrDescriptor& tid =
416 tm_->getInstrInfo().get(mi->getOpcode());
417 DEBUG(std::cerr << getInstructionIndex(mi) << "\t";
418 mi->print(std::cerr, *tm_));
420 // handle implicit defs
421 for (const unsigned* id = tid.ImplicitDefs; *id; ++id)
422 handleRegisterDef(mbb, mi, *id);
424 // handle explicit defs
425 for (int i = mi->getNumOperands() - 1; i >= 0; --i) {
426 MachineOperand& mop = mi->getOperand(i);
427 // handle register defs - build intervals
428 if (mop.isRegister() && mop.getReg() && mop.isDef())
429 handleRegisterDef(mbb, mi, mop.getReg());
435 unsigned LiveIntervals::rep(unsigned reg)
437 Reg2RegMap::iterator it = r2rMap_.find(reg);
438 if (it != r2rMap_.end())
439 return it->second = rep(it->second);
443 void LiveIntervals::joinIntervals()
445 DEBUG(std::cerr << "********** JOINING INTERVALS ***********\n");
447 const TargetInstrInfo& tii = tm_->getInstrInfo();
449 for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
450 mbbi != mbbe; ++mbbi) {
451 MachineBasicBlock* mbb = mbbi;
452 DEBUG(std::cerr << ((Value*)mbb->getBasicBlock())->getName() << ":\n");
454 for (MachineBasicBlock::iterator mi = mbb->begin(), mie = mbb->end();
456 const TargetInstrDescriptor& tid =
457 tm_->getInstrInfo().get(mi->getOpcode());
458 DEBUG(std::cerr << getInstructionIndex(mi) << '\t';
459 mi->print(std::cerr, *tm_););
461 // we only join virtual registers with allocatable
462 // physical registers since we do not have liveness information
463 // on not allocatable physical registers
465 if (tii.isMoveInstr(*mi, regA, regB) &&
466 (MRegisterInfo::isVirtualRegister(regA) ||
467 lv_->getAllocatablePhysicalRegisters()[regA]) &&
468 (MRegisterInfo::isVirtualRegister(regB) ||
469 lv_->getAllocatablePhysicalRegisters()[regB])) {
471 // get representative registers
475 // if they are already joined we continue
479 Reg2IntervalMap::iterator r2iA = r2iMap_.find(regA);
480 assert(r2iA != r2iMap_.end());
481 Reg2IntervalMap::iterator r2iB = r2iMap_.find(regB);
482 assert(r2iB != r2iMap_.end());
484 Intervals::iterator intA = r2iA->second;
485 Intervals::iterator intB = r2iB->second;
487 // both A and B are virtual registers
488 if (MRegisterInfo::isVirtualRegister(intA->reg) &&
489 MRegisterInfo::isVirtualRegister(intB->reg)) {
491 const TargetRegisterClass *rcA, *rcB;
492 rcA = mf_->getSSARegMap()->getRegClass(intA->reg);
493 rcB = mf_->getSSARegMap()->getRegClass(intB->reg);
494 assert(rcA == rcB && "registers must be of the same class");
496 // if their intervals do not overlap we join them
497 if (!intB->overlaps(*intA)) {
499 r2iB->second = r2iA->second;
500 r2rMap_.insert(std::make_pair(intB->reg, intA->reg));
501 intervals_.erase(intB);
504 else if (MRegisterInfo::isPhysicalRegister(intA->reg) ^
505 MRegisterInfo::isPhysicalRegister(intB->reg)) {
506 if (MRegisterInfo::isPhysicalRegister(intB->reg)) {
507 std::swap(regA, regB);
508 std::swap(intA, intB);
509 std::swap(r2iA, r2iB);
512 assert(MRegisterInfo::isPhysicalRegister(intA->reg) &&
513 MRegisterInfo::isVirtualRegister(intB->reg) &&
514 "A must be physical and B must be virtual");
516 if (!intA->overlaps(*intB) &&
517 !overlapsAliases(*intA, *intB)) {
519 r2iB->second = r2iA->second;
520 r2rMap_.insert(std::make_pair(intB->reg, intA->reg));
521 intervals_.erase(intB);
529 bool LiveIntervals::overlapsAliases(const Interval& lhs,
530 const Interval& rhs) const
532 assert(MRegisterInfo::isPhysicalRegister(lhs.reg) &&
533 "first interval must describe a physical register");
535 for (const unsigned* as = mri_->getAliasSet(lhs.reg); *as; ++as) {
536 Reg2IntervalMap::const_iterator r2i = r2iMap_.find(*as);
537 assert(r2i != r2iMap_.end() && "alias does not have interval?");
538 if (rhs.overlaps(*r2i->second))
545 LiveIntervals::Interval& LiveIntervals::getOrCreateInterval(unsigned reg)
547 Reg2IntervalMap::iterator r2iit = r2iMap_.lower_bound(reg);
548 if (r2iit == r2iMap_.end() || r2iit->first != reg) {
549 intervals_.push_back(Interval(reg));
550 r2iit = r2iMap_.insert(r2iit, std::make_pair(reg, --intervals_.end()));
553 return *r2iit->second;
556 LiveIntervals::Interval::Interval(unsigned r)
558 weight((MRegisterInfo::isPhysicalRegister(r) ? HUGE_VAL : 0.0F))
562 bool LiveIntervals::Interval::spilled() const
564 return (weight == HUGE_VAL &&
565 MRegisterInfo::isVirtualRegister(reg));
568 // An example for liveAt():
570 // this = [1,4), liveAt(0) will return false. The instruction defining
571 // this spans slots [0,3]. The interval belongs to an spilled
572 // definition of the variable it represents. This is because slot 1 is
573 // used (def slot) and spans up to slot 3 (store slot).
575 bool LiveIntervals::Interval::liveAt(unsigned index) const
577 Range dummy(index, index+1);
578 Ranges::const_iterator r = std::upper_bound(ranges.begin(),
581 if (r == ranges.begin())
585 return index >= r->first && index < r->second;
588 // An example for overlaps():
592 // 8: C = A + B ;; last use of A
594 // The live intervals should look like:
600 // A->overlaps(C) should return false since we want to be able to join
602 bool LiveIntervals::Interval::overlaps(const Interval& other) const
604 Ranges::const_iterator i = ranges.begin();
605 Ranges::const_iterator ie = ranges.end();
606 Ranges::const_iterator j = other.ranges.begin();
607 Ranges::const_iterator je = other.ranges.end();
608 if (i->first < j->first) {
609 i = std::upper_bound(i, ie, *j);
610 if (i != ranges.begin()) --i;
612 else if (j->first < i->first) {
613 j = std::upper_bound(j, je, *i);
614 if (j != other.ranges.begin()) --j;
617 while (i != ie && j != je) {
618 if (i->first == j->first) {
622 if (i->first > j->first) {
626 assert(i->first < j->first);
628 if (i->second > j->first) {
640 void LiveIntervals::Interval::addRange(unsigned start, unsigned end)
642 assert(start < end && "Invalid range to add!");
643 DEBUG(std::cerr << " +[" << start << ',' << end << ")");
644 //assert(start < end && "invalid range?");
645 Range range = std::make_pair(start, end);
646 Ranges::iterator it =
647 ranges.insert(std::upper_bound(ranges.begin(), ranges.end(), range),
650 it = mergeRangesForward(it);
651 it = mergeRangesBackward(it);
654 void LiveIntervals::Interval::join(const LiveIntervals::Interval& other)
656 DEBUG(std::cerr << "\t\tjoining " << *this << " with " << other << '\n');
657 Ranges::iterator cur = ranges.begin();
659 for (Ranges::const_iterator i = other.ranges.begin(),
660 e = other.ranges.end(); i != e; ++i) {
661 cur = ranges.insert(std::upper_bound(cur, ranges.end(), *i), *i);
662 cur = mergeRangesForward(cur);
663 cur = mergeRangesBackward(cur);
665 weight += other.weight;
667 std::set_union(defs.begin(), defs.end(),
668 other.defs.begin(), other.defs.end(),
669 std::back_inserter(u));
674 LiveIntervals::Interval::Ranges::iterator
675 LiveIntervals::Interval::mergeRangesForward(Ranges::iterator it)
678 while ((n = next(it)) != ranges.end()) {
679 if (n->first > it->second)
681 it->second = std::max(it->second, n->second);
687 LiveIntervals::Interval::Ranges::iterator
688 LiveIntervals::Interval::mergeRangesBackward(Ranges::iterator it)
690 while (it != ranges.begin()) {
691 Ranges::iterator p = prior(it);
692 if (it->first > p->second)
695 it->first = std::min(it->first, p->first);
696 it->second = std::max(it->second, p->second);
697 it = ranges.erase(p);
703 std::ostream& llvm::operator<<(std::ostream& os,
704 const LiveIntervals::Interval& li)
706 os << "%reg" << li.reg << ',' << li.weight;
708 return os << "EMPTY";
710 os << " {" << li.defs.front();
711 for (LiveIntervals::Interval::Defs::const_iterator
712 i = next(li.defs.begin()), e = li.defs.end(); i != e; ++i)
717 for (LiveIntervals::Interval::Ranges::const_iterator
718 i = li.ranges.begin(), e = li.ranges.end(); i != e; ++i) {
719 os << "[" << i->first << "," << i->second << ")";