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/Analysis/LoopInfo.h"
21 #include "llvm/CodeGen/LiveVariables.h"
22 #include "llvm/CodeGen/MachineFrameInfo.h"
23 #include "llvm/CodeGen/MachineInstr.h"
24 #include "llvm/CodeGen/Passes.h"
25 #include "llvm/CodeGen/SSARegMap.h"
26 #include "llvm/Target/MRegisterInfo.h"
27 #include "llvm/Target/TargetInstrInfo.h"
28 #include "llvm/Target/TargetMachine.h"
29 #include "llvm/Support/CFG.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"
42 RegisterAnalysis<LiveIntervals> X("liveintervals",
43 "Live Interval Analysis");
45 Statistic<> numIntervals
46 ("liveintervals", "Number of original intervals");
48 Statistic<> numIntervalsAfter
49 ("liveintervals", "Number of intervals after coalescing");
52 ("liveintervals", "Number of interval joins performed");
55 ("liveintervals", "Number of identity moves eliminated after coalescing");
58 ("liveintervals", "Number of loads/stores folded into instructions");
61 join("join-liveintervals",
62 cl::desc("Join compatible live intervals"),
66 void LiveIntervals::getAnalysisUsage(AnalysisUsage &AU) const
68 AU.addPreserved<LiveVariables>();
69 AU.addRequired<LiveVariables>();
70 AU.addPreservedID(PHIEliminationID);
71 AU.addRequiredID(PHIEliminationID);
72 AU.addRequiredID(TwoAddressInstructionPassID);
73 AU.addRequired<LoopInfo>();
74 MachineFunctionPass::getAnalysisUsage(AU);
77 void LiveIntervals::releaseMemory()
88 /// runOnMachineFunction - Register allocate the whole function
90 bool LiveIntervals::runOnMachineFunction(MachineFunction &fn) {
92 tm_ = &fn.getTarget();
93 mri_ = tm_->getRegisterInfo();
94 lv_ = &getAnalysis<LiveVariables>();
96 // number MachineInstrs
98 for (MachineFunction::iterator mbb = mf_->begin(), mbbEnd = mf_->end();
99 mbb != mbbEnd; ++mbb) {
100 const std::pair<MachineBasicBlock*, unsigned>& entry =
101 lv_->getMachineBasicBlockInfo(mbb);
102 bool inserted = mbbi2mbbMap_.insert(std::make_pair(entry.second,
103 entry.first)).second;
104 assert(inserted && "multiple index -> MachineBasicBlock");
106 for (MachineBasicBlock::iterator mi = mbb->begin(), miEnd = mbb->end();
108 inserted = mi2iMap_.insert(std::make_pair(mi, miIndex)).second;
109 assert(inserted && "multiple MachineInstr -> index mappings");
110 i2miMap_.push_back(mi);
111 miIndex += InstrSlots::NUM;
117 numIntervals += intervals_.size();
119 // join intervals if requested
120 if (join) joinIntervals();
122 numIntervalsAfter += intervals_.size();
124 // perform a final pass over the instructions and compute spill
125 // weights, coalesce virtual registers and remove identity moves
126 const LoopInfo& loopInfo = getAnalysis<LoopInfo>();
127 const TargetInstrInfo& tii = tm_->getInstrInfo();
129 for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
130 mbbi != mbbe; ++mbbi) {
131 MachineBasicBlock* mbb = mbbi;
132 unsigned loopDepth = loopInfo.getLoopDepth(mbb->getBasicBlock());
134 for (MachineBasicBlock::iterator mii = mbb->begin(), mie = mbb->end();
136 for (unsigned i = 0; i < mii->getNumOperands(); ++i) {
137 const MachineOperand& mop = mii->getOperand(i);
138 if (mop.isRegister() && mop.getReg()) {
139 // replace register with representative register
140 unsigned reg = rep(mop.getReg());
141 mii->SetMachineOperandReg(i, reg);
143 if (MRegisterInfo::isVirtualRegister(reg)) {
144 Reg2IntervalMap::iterator r2iit = r2iMap_.find(reg);
145 assert(r2iit != r2iMap_.end());
146 r2iit->second->weight += pow(10.0F, loopDepth);
151 // if the move is now an identity move delete it
152 unsigned srcReg, dstReg;
153 if (tii.isMoveInstr(*mii, srcReg, dstReg) && srcReg == dstReg) {
154 // remove index -> MachineInstr and
155 // MachineInstr -> index mappings
156 Mi2IndexMap::iterator mi2i = mi2iMap_.find(mii);
157 if (mi2i != mi2iMap_.end()) {
158 i2miMap_[mi2i->second/InstrSlots::NUM] = 0;
159 mi2iMap_.erase(mi2i);
161 mii = mbbi->erase(mii);
169 intervals_.sort(StartPointComp());
170 DEBUG(std::cerr << "********** INTERVALS **********\n");
171 DEBUG(std::copy(intervals_.begin(), intervals_.end(),
172 std::ostream_iterator<Interval>(std::cerr, "\n")));
173 DEBUG(std::cerr << "********** MACHINEINSTRS **********\n");
175 for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
176 mbbi != mbbe; ++mbbi) {
177 std::cerr << mbbi->getBasicBlock()->getName() << ":\n";
178 for (MachineBasicBlock::iterator mii = mbbi->begin(),
179 mie = mbbi->end(); mii != mie; ++mii) {
180 std::cerr << getInstructionIndex(mii) << '\t';
181 mii->print(std::cerr, *tm_);
188 void LiveIntervals::updateSpilledInterval(Interval& li,
192 assert(li.weight != std::numeric_limits<float>::infinity() &&
193 "attempt to spill already spilled interval!");
194 Interval::Ranges oldRanges;
195 swap(oldRanges, li.ranges);
197 DEBUG(std::cerr << "\t\t\t\tupdating interval: " << li);
199 for (Interval::Ranges::iterator i = oldRanges.begin(), e = oldRanges.end();
201 unsigned index = getBaseIndex(i->first);
202 unsigned end = getBaseIndex(i->second-1) + InstrSlots::NUM;
203 for (; index < end; index += InstrSlots::NUM) {
204 // skip deleted instructions
205 while (!getInstructionFromIndex(index)) index += InstrSlots::NUM;
206 MachineBasicBlock::iterator mi = getInstructionFromIndex(index);
209 for (unsigned i = 0; i < mi->getNumOperands(); ++i) {
210 MachineOperand& mop = mi->getOperand(i);
211 if (mop.isRegister() && mop.getReg() == li.reg) {
212 MachineInstr* old = mi;
213 if (mri_->foldMemoryOperand(mi, i, slot)) {
214 lv_->instructionChanged(old, mi);
215 vrm.virtFolded(li.reg, old, mi);
217 i2miMap_[index/InstrSlots::NUM] = mi;
218 mi2iMap_[mi] = index;
223 // This is tricky. We need to add information in
224 // the interval about the spill code so we have to
225 // use our extra load/store slots.
227 // If we have a use we are going to have a load so
228 // we start the interval from the load slot
229 // onwards. Otherwise we start from the def slot.
230 unsigned start = (mop.isUse() ?
231 getLoadIndex(index) :
233 // If we have a def we are going to have a store
234 // right after it so we end the interval after the
235 // use of the next instruction. Otherwise we end
236 // after the use of this instruction.
237 unsigned end = 1 + (mop.isDef() ?
238 getUseIndex(index+InstrSlots::NUM) :
240 li.addRange(start, end);
246 // the new spill weight is now infinity as it cannot be spilled again
247 li.weight = std::numeric_limits<float>::infinity();
248 DEBUG(std::cerr << '\n');
249 DEBUG(std::cerr << "\t\t\t\tupdated interval: " << li << '\n');
252 void LiveIntervals::printRegName(unsigned reg) const
254 if (MRegisterInfo::isPhysicalRegister(reg))
255 std::cerr << mri_->getName(reg);
257 std::cerr << "%reg" << reg;
260 void LiveIntervals::handleVirtualRegisterDef(MachineBasicBlock* mbb,
261 MachineBasicBlock::iterator mi,
264 DEBUG(std::cerr << "\t\tregister: "; printRegName(reg));
265 LiveVariables::VarInfo& vi = lv_->getVarInfo(reg);
267 Interval* interval = 0;
268 Reg2IntervalMap::iterator r2iit = r2iMap_.lower_bound(reg);
269 if (r2iit == r2iMap_.end() || r2iit->first != reg) {
271 intervals_.push_back(Interval(reg));
272 // update interval index for this register
273 r2iMap_.insert(r2iit, std::make_pair(reg, --intervals_.end()));
274 interval = &intervals_.back();
276 // iterate over all of the blocks that the variable is
277 // completely live in, adding them to the live
278 // interval. obviously we only need to do this once.
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 interval = &*r2iit->second;
294 unsigned baseIndex = getInstructionIndex(mi);
296 bool killedInDefiningBasicBlock = false;
297 for (int i = 0, e = vi.Kills.size(); i != e; ++i) {
298 MachineBasicBlock* killerBlock = vi.Kills[i].first;
299 MachineInstr* killerInstr = vi.Kills[i].second;
300 unsigned start = (mbb == killerBlock ?
301 getDefIndex(baseIndex) :
302 getInstructionIndex(&killerBlock->front()));
303 unsigned end = (killerInstr == mi ?
307 getUseIndex(getInstructionIndex(killerInstr))+1);
308 // we do not want to add invalid ranges. these can happen when
309 // a variable has its latest use and is redefined later on in
310 // the same basic block (common with variables introduced by
313 killedInDefiningBasicBlock |= mbb == killerBlock;
314 interval->addRange(start, end);
318 if (!killedInDefiningBasicBlock) {
319 unsigned end = getInstructionIndex(&mbb->back()) + InstrSlots::NUM;
320 interval->addRange(getDefIndex(baseIndex), end);
322 DEBUG(std::cerr << '\n');
325 void LiveIntervals::handlePhysicalRegisterDef(MachineBasicBlock* mbb,
326 MachineBasicBlock::iterator mi,
329 DEBUG(std::cerr << "\t\tregister: "; printRegName(reg));
330 typedef LiveVariables::killed_iterator KillIter;
332 MachineBasicBlock::iterator e = mbb->end();
333 unsigned baseIndex = getInstructionIndex(mi);
334 unsigned start = getDefIndex(baseIndex);
335 unsigned end = start;
337 // a variable can be dead by the instruction defining it
338 for (KillIter ki = lv_->dead_begin(mi), ke = lv_->dead_end(mi);
340 if (reg == ki->second) {
341 DEBUG(std::cerr << " dead");
342 end = getDefIndex(start) + 1;
347 // a variable can only be killed by subsequent instructions
350 baseIndex += InstrSlots::NUM;
351 for (KillIter ki = lv_->killed_begin(mi), ke = lv_->killed_end(mi);
353 if (reg == ki->second) {
354 DEBUG(std::cerr << " killed");
355 end = getUseIndex(baseIndex) + 1;
362 assert(start < end && "did not find end of interval?");
364 Reg2IntervalMap::iterator r2iit = r2iMap_.lower_bound(reg);
365 if (r2iit != r2iMap_.end() && r2iit->first == reg) {
366 r2iit->second->addRange(start, end);
369 intervals_.push_back(Interval(reg));
370 // update interval index for this register
371 r2iMap_.insert(r2iit, std::make_pair(reg, --intervals_.end()));
372 intervals_.back().addRange(start, end);
374 DEBUG(std::cerr << '\n');
377 void LiveIntervals::handleRegisterDef(MachineBasicBlock* mbb,
378 MachineBasicBlock::iterator mi,
381 if (MRegisterInfo::isPhysicalRegister(reg)) {
382 if (lv_->getAllocatablePhysicalRegisters()[reg]) {
383 handlePhysicalRegisterDef(mbb, mi, reg);
384 for (const unsigned* as = mri_->getAliasSet(reg); *as; ++as)
385 handlePhysicalRegisterDef(mbb, mi, *as);
389 handleVirtualRegisterDef(mbb, mi, reg);
393 unsigned LiveIntervals::getInstructionIndex(MachineInstr* instr) const
395 Mi2IndexMap::const_iterator it = mi2iMap_.find(instr);
396 return (it == mi2iMap_.end() ?
397 std::numeric_limits<unsigned>::max() :
401 MachineInstr* LiveIntervals::getInstructionFromIndex(unsigned index) const
403 index /= InstrSlots::NUM; // convert index to vector index
404 assert(index < i2miMap_.size() &&
405 "index does not correspond to an instruction");
406 return i2miMap_[index];
409 /// computeIntervals - computes the live intervals for virtual
410 /// registers. for some ordering of the machine instructions [1,N] a
411 /// live interval is an interval [i, j) where 1 <= i <= j < N for
412 /// which a variable is live
413 void LiveIntervals::computeIntervals()
415 DEBUG(std::cerr << "********** COMPUTING LIVE INTERVALS **********\n");
416 DEBUG(std::cerr << "********** Function: "
417 << mf_->getFunction()->getName() << '\n');
419 for (MbbIndex2MbbMap::iterator
420 it = mbbi2mbbMap_.begin(), itEnd = mbbi2mbbMap_.end();
422 MachineBasicBlock* mbb = it->second;
423 DEBUG(std::cerr << mbb->getBasicBlock()->getName() << ":\n");
425 for (MachineBasicBlock::iterator mi = mbb->begin(), miEnd = mbb->end();
427 const TargetInstrDescriptor& tid =
428 tm_->getInstrInfo().get(mi->getOpcode());
429 DEBUG(std::cerr << getInstructionIndex(mi) << "\t";
430 mi->print(std::cerr, *tm_));
432 // handle implicit defs
433 for (const unsigned* id = tid.ImplicitDefs; *id; ++id)
434 handleRegisterDef(mbb, mi, *id);
436 // handle explicit defs
437 for (int i = mi->getNumOperands() - 1; i >= 0; --i) {
438 MachineOperand& mop = mi->getOperand(i);
439 // handle register defs - build intervals
440 if (mop.isRegister() && mop.getReg() && mop.isDef())
441 handleRegisterDef(mbb, mi, mop.getReg());
447 unsigned LiveIntervals::rep(unsigned reg)
449 Reg2RegMap::iterator it = r2rMap_.find(reg);
450 if (it != r2rMap_.end())
451 return it->second = rep(it->second);
455 void LiveIntervals::joinIntervals()
457 DEBUG(std::cerr << "********** JOINING INTERVALS ***********\n");
459 const TargetInstrInfo& tii = tm_->getInstrInfo();
461 for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
462 mbbi != mbbe; ++mbbi) {
463 MachineBasicBlock* mbb = mbbi;
464 DEBUG(std::cerr << mbb->getBasicBlock()->getName() << ":\n");
466 for (MachineBasicBlock::iterator mi = mbb->begin(), mie = mbb->end();
468 const TargetInstrDescriptor& tid =
469 tm_->getInstrInfo().get(mi->getOpcode());
470 DEBUG(std::cerr << getInstructionIndex(mi) << '\t';
471 mi->print(std::cerr, *tm_););
473 // we only join virtual registers with allocatable
474 // physical registers since we do not have liveness information
475 // on not allocatable physical registers
477 if (tii.isMoveInstr(*mi, regA, regB) &&
478 (MRegisterInfo::isVirtualRegister(regA) ||
479 lv_->getAllocatablePhysicalRegisters()[regA]) &&
480 (MRegisterInfo::isVirtualRegister(regB) ||
481 lv_->getAllocatablePhysicalRegisters()[regB])) {
483 // get representative registers
487 // if they are already joined we continue
491 Reg2IntervalMap::iterator r2iA = r2iMap_.find(regA);
492 assert(r2iA != r2iMap_.end());
493 Reg2IntervalMap::iterator r2iB = r2iMap_.find(regB);
494 assert(r2iB != r2iMap_.end());
496 Intervals::iterator intA = r2iA->second;
497 Intervals::iterator intB = r2iB->second;
499 // both A and B are virtual registers
500 if (MRegisterInfo::isVirtualRegister(intA->reg) &&
501 MRegisterInfo::isVirtualRegister(intB->reg)) {
503 const TargetRegisterClass *rcA, *rcB;
504 rcA = mf_->getSSARegMap()->getRegClass(intA->reg);
505 rcB = mf_->getSSARegMap()->getRegClass(intB->reg);
506 assert(rcA == rcB && "registers must be of the same class");
508 // if their intervals do not overlap we join them
509 if (!intB->overlaps(*intA)) {
511 r2iB->second = r2iA->second;
512 r2rMap_.insert(std::make_pair(intB->reg, intA->reg));
513 intervals_.erase(intB);
516 else if (MRegisterInfo::isPhysicalRegister(intA->reg) ^
517 MRegisterInfo::isPhysicalRegister(intB->reg)) {
518 if (MRegisterInfo::isPhysicalRegister(intB->reg)) {
519 std::swap(regA, regB);
520 std::swap(intA, intB);
521 std::swap(r2iA, r2iB);
524 assert(MRegisterInfo::isPhysicalRegister(intA->reg) &&
525 MRegisterInfo::isVirtualRegister(intB->reg) &&
526 "A must be physical and B must be virtual");
528 if (!intA->overlaps(*intB) &&
529 !overlapsAliases(*intA, *intB)) {
531 r2iB->second = r2iA->second;
532 r2rMap_.insert(std::make_pair(intB->reg, intA->reg));
533 intervals_.erase(intB);
541 bool LiveIntervals::overlapsAliases(const Interval& lhs,
542 const Interval& rhs) const
544 assert(MRegisterInfo::isPhysicalRegister(lhs.reg) &&
545 "first interval must describe a physical register");
547 for (const unsigned* as = mri_->getAliasSet(lhs.reg); *as; ++as) {
548 Reg2IntervalMap::const_iterator r2i = r2iMap_.find(*as);
549 assert(r2i != r2iMap_.end() && "alias does not have interval?");
550 if (rhs.overlaps(*r2i->second))
557 LiveIntervals::Interval::Interval(unsigned r)
559 weight((MRegisterInfo::isPhysicalRegister(r) ?
560 std::numeric_limits<float>::infinity() : 0.0F))
565 bool LiveIntervals::Interval::spilled() const
567 return (weight == std::numeric_limits<float>::infinity() &&
568 MRegisterInfo::isVirtualRegister(reg));
571 // An example for liveAt():
573 // this = [1,4), liveAt(0) will return false. The instruction defining
574 // this spans slots [0,3]. The interval belongs to an spilled
575 // definition of the variable it represents. This is because slot 1 is
576 // used (def slot) and spans up to slot 3 (store slot).
578 bool LiveIntervals::Interval::liveAt(unsigned index) const
580 Range dummy(index, index+1);
581 Ranges::const_iterator r = std::upper_bound(ranges.begin(),
584 if (r == ranges.begin())
588 return index >= r->first && index < r->second;
591 // An example for overlaps():
595 // 8: C = A + B ;; last use of A
597 // The live intervals should look like:
603 // A->overlaps(C) should return false since we want to be able to join
605 bool LiveIntervals::Interval::overlaps(const Interval& other) const
607 Ranges::const_iterator i = ranges.begin();
608 Ranges::const_iterator ie = ranges.end();
609 Ranges::const_iterator j = other.ranges.begin();
610 Ranges::const_iterator je = other.ranges.end();
611 if (i->first < j->first) {
612 i = std::upper_bound(i, ie, *j);
613 if (i != ranges.begin()) --i;
615 else if (j->first < i->first) {
616 j = std::upper_bound(j, je, *i);
617 if (j != other.ranges.begin()) --j;
620 while (i != ie && j != je) {
621 if (i->first == j->first) {
625 if (i->first > j->first) {
629 assert(i->first < j->first);
631 if (i->second > j->first) {
643 void LiveIntervals::Interval::addRange(unsigned start, unsigned end)
645 assert(start < end && "Invalid range to add!");
646 DEBUG(std::cerr << " +[" << start << ',' << end << ")");
647 //assert(start < end && "invalid range?");
648 Range range = std::make_pair(start, end);
649 Ranges::iterator it =
650 ranges.insert(std::upper_bound(ranges.begin(), ranges.end(), range),
653 it = mergeRangesForward(it);
654 it = mergeRangesBackward(it);
657 void LiveIntervals::Interval::join(const LiveIntervals::Interval& other)
659 DEBUG(std::cerr << "\t\tjoining " << *this << " with " << other << '\n');
660 Ranges::iterator cur = ranges.begin();
662 for (Ranges::const_iterator i = other.ranges.begin(),
663 e = other.ranges.end(); i != e; ++i) {
664 cur = ranges.insert(std::upper_bound(cur, ranges.end(), *i), *i);
665 cur = mergeRangesForward(cur);
666 cur = mergeRangesBackward(cur);
668 weight += other.weight;
672 LiveIntervals::Interval::Ranges::iterator
673 LiveIntervals::Interval::mergeRangesForward(Ranges::iterator it)
676 while ((n = next(it)) != ranges.end()) {
677 if (n->first > it->second)
679 it->second = std::max(it->second, n->second);
685 LiveIntervals::Interval::Ranges::iterator
686 LiveIntervals::Interval::mergeRangesBackward(Ranges::iterator it)
688 while (it != ranges.begin()) {
689 Ranges::iterator p = prior(it);
690 if (it->first > p->second)
693 it->first = std::min(it->first, p->first);
694 it->second = std::max(it->second, p->second);
695 it = ranges.erase(p);
701 std::ostream& llvm::operator<<(std::ostream& os,
702 const LiveIntervals::Interval& li)
704 os << "%reg" << li.reg << ',' << li.weight << " = ";
706 return os << "EMPTY";
707 for (LiveIntervals::Interval::Ranges::const_iterator
708 i = li.ranges.begin(), e = li.ranges.end(); i != e; ++i) {
709 os << "[" << i->first << "," << i->second << ")";