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 "llvm/CodeGen/LiveIntervals.h"
20 #include "llvm/Function.h"
21 #include "llvm/Analysis/LoopInfo.h"
22 #include "llvm/CodeGen/LiveVariables.h"
23 #include "llvm/CodeGen/MachineFrameInfo.h"
24 #include "llvm/CodeGen/MachineFunctionPass.h"
25 #include "llvm/CodeGen/MachineInstr.h"
26 #include "llvm/CodeGen/Passes.h"
27 #include "llvm/CodeGen/SSARegMap.h"
28 #include "llvm/Target/MRegisterInfo.h"
29 #include "llvm/Target/TargetInstrInfo.h"
30 #include "llvm/Target/TargetMachine.h"
31 #include "llvm/Target/TargetRegInfo.h"
32 #include "llvm/Support/CFG.h"
33 #include "Support/Debug.h"
34 #include "Support/DepthFirstIterator.h"
35 #include "Support/Statistic.h"
43 RegisterAnalysis<LiveIntervals> X("liveintervals",
44 "Live Interval Analysis");
46 Statistic<> numIntervals("liveintervals", "Number of intervals");
49 void LiveIntervals::getAnalysisUsage(AnalysisUsage &AU) const
51 AU.addPreserved<LiveVariables>();
52 AU.addRequired<LiveVariables>();
53 AU.addPreservedID(PHIEliminationID);
54 AU.addRequiredID(PHIEliminationID);
55 AU.addRequiredID(TwoAddressInstructionPassID);
56 AU.addRequired<LoopInfo>();
57 MachineFunctionPass::getAnalysisUsage(AU);
60 /// runOnMachineFunction - Register allocate the whole function
62 bool LiveIntervals::runOnMachineFunction(MachineFunction &fn) {
63 DEBUG(std::cerr << "Machine Function\n");
65 tm_ = &fn.getTarget();
66 mri_ = tm_->getRegisterInfo();
67 lv_ = &getAnalysis<LiveVariables>();
74 // number MachineInstrs
76 for (MachineFunction::iterator mbb = mf_->begin(), mbbEnd = mf_->end();
77 mbb != mbbEnd; ++mbb) {
78 const std::pair<MachineBasicBlock*, unsigned>& entry =
79 lv_->getMachineBasicBlockInfo(&*mbb);
80 bool inserted = mbbi2mbbMap_.insert(std::make_pair(entry.second,
82 assert(inserted && "multiple index -> MachineBasicBlock");
84 for (MachineBasicBlock::iterator mi = mbb->begin(), miEnd = mbb->end();
86 inserted = mi2iMap_.insert(std::make_pair(*mi, miIndex)).second;
87 assert(inserted && "multiple MachineInstr -> index mappings");
94 // compute spill weights
95 const LoopInfo& loopInfo = getAnalysis<LoopInfo>();
96 const TargetInstrInfo& tii = tm_->getInstrInfo();
98 for (MbbIndex2MbbMap::iterator
99 it = mbbi2mbbMap_.begin(), itEnd = mbbi2mbbMap_.end();
101 MachineBasicBlock* mbb = it->second;
103 unsigned loopDepth = loopInfo.getLoopDepth(mbb->getBasicBlock());
105 for (MachineBasicBlock::iterator mi = mbb->begin(), miEnd = mbb->end();
107 MachineInstr* instr = *mi;
108 for (int i = instr->getNumOperands() - 1; i >= 0; --i) {
109 MachineOperand& mop = instr->getOperand(i);
111 if (!mop.isVirtualRegister())
114 unsigned reg = mop.getAllocatedRegNum();
115 Reg2IntervalMap::iterator r2iit = r2iMap_.find(reg);
116 assert(r2iit != r2iMap_.end());
117 r2iit->second->weight += pow(10.0F, loopDepth);
122 numIntervals += intervals_.size();
127 void LiveIntervals::printRegName(unsigned reg) const
129 if (reg < MRegisterInfo::FirstVirtualRegister)
130 std::cerr << mri_->getName(reg);
132 std::cerr << '%' << reg;
135 void LiveIntervals::handleVirtualRegisterDef(MachineBasicBlock* mbb,
136 MachineBasicBlock::iterator mi,
139 DEBUG(std::cerr << "\t\tregister: ";printRegName(reg); std::cerr << '\n');
141 unsigned instrIndex = getInstructionIndex(*mi);
143 LiveVariables::VarInfo& vi = lv_->getVarInfo(reg);
145 Interval* interval = 0;
146 Reg2IntervalMap::iterator r2iit = r2iMap_.find(reg);
147 if (r2iit == r2iMap_.end()) {
149 intervals_.push_back(Interval(reg));
150 // update interval index for this register
152 r2iMap_.insert(std::make_pair(reg, --intervals_.end())).second;
154 interval = &intervals_.back();
157 interval = &*r2iit->second;
160 for (MbbIndex2MbbMap::iterator
161 it = mbbi2mbbMap_.begin(), itEnd = mbbi2mbbMap_.end();
163 unsigned liveBlockIndex = it->first;
164 MachineBasicBlock* liveBlock = it->second;
165 if (liveBlockIndex < vi.AliveBlocks.size() &&
166 vi.AliveBlocks[liveBlockIndex] &&
167 !liveBlock->empty()) {
168 unsigned start = getInstructionIndex(liveBlock->front());
169 unsigned end = getInstructionIndex(liveBlock->back()) + 1;
170 interval->addRange(start, end);
174 bool killedInDefiningBasicBlock = false;
175 for (int i = 0, e = vi.Kills.size(); i != e; ++i) {
176 MachineBasicBlock* killerBlock = vi.Kills[i].first;
177 MachineInstr* killerInstr = vi.Kills[i].second;
178 unsigned start = (mbb == killerBlock ?
180 getInstructionIndex(killerBlock->front()));
181 unsigned end = getInstructionIndex(killerInstr) + 1;
183 killedInDefiningBasicBlock |= mbb == killerBlock;
184 interval->addRange(start, end);
188 if (!killedInDefiningBasicBlock) {
189 unsigned end = getInstructionIndex(mbb->back()) + 1;
190 interval->addRange(instrIndex, end);
194 void LiveIntervals::handlePhysicalRegisterDef(MachineBasicBlock* mbb,
195 MachineBasicBlock::iterator mi,
198 DEBUG(std::cerr << "\t\tregister: "; printRegName(reg));
200 unsigned start = getInstructionIndex(*mi);
201 unsigned end = start;
203 // register can be dead by the instruction defining it but it can
204 // only be killed by subsequent instructions
206 for (LiveVariables::killed_iterator
207 ki = lv_->dead_begin(*mi),
208 ke = lv_->dead_end(*mi);
210 if (reg == ki->second) {
211 end = getInstructionIndex(ki->first) + 1;
212 DEBUG(std::cerr << " dead\n");
218 for (MachineBasicBlock::iterator e = mbb->end(); mi != e; ++mi) {
219 for (LiveVariables::killed_iterator
220 ki = lv_->dead_begin(*mi),
221 ke = lv_->dead_end(*mi);
223 if (reg == ki->second) {
224 end = getInstructionIndex(ki->first) + 1;
225 DEBUG(std::cerr << " dead\n");
230 for (LiveVariables::killed_iterator
231 ki = lv_->killed_begin(*mi),
232 ke = lv_->killed_end(*mi);
234 if (reg == ki->second) {
235 end = getInstructionIndex(ki->first) + 1;
236 DEBUG(std::cerr << " killed\n");
242 assert(start < end && "did not find end of interval?");
244 Reg2IntervalMap::iterator r2iit = r2iMap_.find(reg);
245 if (r2iit != r2iMap_.end()) {
246 Interval& interval = *r2iit->second;
247 interval.addRange(start, end);
250 intervals_.push_back(Interval(reg));
251 Interval& interval = intervals_.back();
252 // update interval index for this register
254 r2iMap_.insert(std::make_pair(reg, --intervals_.end())).second;
256 interval.addRange(start, end);
260 void LiveIntervals::handleRegisterDef(MachineBasicBlock* mbb,
261 MachineBasicBlock::iterator mi,
264 if (reg < MRegisterInfo::FirstVirtualRegister) {
265 if (lv_->getAllocatablePhysicalRegisters()[reg]) {
266 handlePhysicalRegisterDef(mbb, mi, reg);
267 for (const unsigned* as = mri_->getAliasSet(reg); *as; ++as)
268 handlePhysicalRegisterDef(mbb, mi, *as);
272 handleVirtualRegisterDef(mbb, mi, reg);
276 unsigned LiveIntervals::getInstructionIndex(MachineInstr* instr) const
278 assert(mi2iMap_.find(instr) != mi2iMap_.end() &&
279 "instruction not assigned a number");
280 return mi2iMap_.find(instr)->second;
283 /// computeIntervals - computes the live intervals for virtual
284 /// registers. for some ordering of the machine instructions [1,N] a
285 /// live interval is an interval [i, j] where 1 <= i <= j <= N for
286 /// which a variable is live
287 void LiveIntervals::computeIntervals()
289 DEBUG(std::cerr << "computing live intervals:\n");
291 for (MbbIndex2MbbMap::iterator
292 it = mbbi2mbbMap_.begin(), itEnd = mbbi2mbbMap_.end();
294 MachineBasicBlock* mbb = it->second;
295 DEBUG(std::cerr << "machine basic block: "
296 << mbb->getBasicBlock()->getName() << "\n");
298 for (MachineBasicBlock::iterator mi = mbb->begin(), miEnd = mbb->end();
300 MachineInstr* instr = *mi;
301 const TargetInstrDescriptor& tid =
302 tm_->getInstrInfo().get(instr->getOpcode());
303 DEBUG(std::cerr << "\t[" << getInstructionIndex(instr) << "] ";
304 instr->print(std::cerr, *tm_););
306 // handle implicit defs
307 for (const unsigned* id = tid.ImplicitDefs; *id; ++id)
308 handleRegisterDef(mbb, mi, *id);
310 // handle explicit defs
311 for (int i = instr->getNumOperands() - 1; i >= 0; --i) {
312 MachineOperand& mop = instr->getOperand(i);
314 if (!mop.isRegister())
317 // handle defs - build intervals
319 handleRegisterDef(mbb, mi, mop.getAllocatedRegNum());
324 intervals_.sort(StartPointComp());
325 DEBUG(std::copy(intervals_.begin(), intervals_.end(),
326 std::ostream_iterator<Interval>(std::cerr, "\n")));
329 LiveIntervals::Interval::Interval(unsigned r)
331 weight((r < MRegisterInfo::FirstVirtualRegister ?
332 std::numeric_limits<float>::max() : 0.0F))
337 void LiveIntervals::Interval::addRange(unsigned start, unsigned end)
339 DEBUG(std::cerr << "\t\t\tadding range: [" << start <<','<< end << ") -> ");
340 //assert(start < end && "invalid range?");
341 Range range = std::make_pair(start, end);
342 Ranges::iterator it =
343 ranges.insert(std::upper_bound(ranges.begin(), ranges.end(), range),
346 mergeRangesForward(it);
347 mergeRangesBackward(it);
348 DEBUG(std::cerr << *this << '\n');
351 void LiveIntervals::Interval::mergeRangesForward(Ranges::iterator it)
353 for (Ranges::iterator next = it + 1;
354 next != ranges.end() && it->second >= next->first; ) {
355 it->second = std::max(it->second, next->second);
356 next = ranges.erase(next);
360 void LiveIntervals::Interval::mergeRangesBackward(Ranges::iterator it)
362 for (Ranges::iterator prev = it - 1;
363 it != ranges.begin() && it->first <= prev->second; ) {
364 it->first = std::min(it->first, prev->first);
365 it->second = std::max(it->second, prev->second);
366 it = ranges.erase(prev);
371 bool LiveIntervals::Interval::liveAt(unsigned index) const
373 Ranges::const_iterator r = ranges.begin();
374 while (r != ranges.end() && index < (r->second - 1)) {
375 if (index >= r->first)
382 bool LiveIntervals::Interval::overlaps(const Interval& other) const
384 Ranges::const_iterator i = ranges.begin();
385 Ranges::const_iterator j = other.ranges.begin();
387 while (i != ranges.end() && j != other.ranges.end()) {
388 if (i->first < j->first) {
389 if ((i->second - 1) > j->first) {
396 else if (j->first < i->first) {
397 if ((j->second - 1) > i->first) {
412 std::ostream& llvm::operator<<(std::ostream& os,
413 const LiveIntervals::Interval& li)
415 os << "%reg" << li.reg << ',' << li.weight << " = ";
416 for (LiveIntervals::Interval::Ranges::const_iterator
417 i = li.ranges.begin(), e = li.ranges.end(); i != e; ++i) {
418 os << "[" << i->first << "," << i->second << ")";