84ae3badc42e6c1ae313d39a43f7541b57d686f8
[oota-llvm.git] / lib / CodeGen / LiveIntervalAnalysis.cpp
1 //===-- LiveIntervals.cpp - Live Interval Analysis ------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
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.
7 //
8 //===----------------------------------------------------------------------===//
9 //
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.
15 //
16 //===----------------------------------------------------------------------===//
17
18 #define DEBUG_TYPE "liveintervals"
19 #include "llvm/CodeGen/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 <cmath>
34 #include <iostream>
35 #include <limits>
36
37 using namespace llvm;
38
39 namespace {
40     RegisterAnalysis<LiveIntervals> X("liveintervals",
41                                       "Live Interval Analysis");
42
43     Statistic<> numIntervals("liveintervals", "Number of intervals");
44     Statistic<> numJoined   ("liveintervals", "Number of intervals joined");
45
46     cl::opt<bool>
47     join("join-liveintervals",
48          cl::desc("Join compatible live intervals"),
49          cl::init(true));
50 };
51
52 void LiveIntervals::getAnalysisUsage(AnalysisUsage &AU) const
53 {
54     AU.addPreserved<LiveVariables>();
55     AU.addRequired<LiveVariables>();
56     AU.addPreservedID(PHIEliminationID);
57     AU.addRequiredID(PHIEliminationID);
58     AU.addRequiredID(TwoAddressInstructionPassID);
59     AU.addRequired<LoopInfo>();
60     MachineFunctionPass::getAnalysisUsage(AU);
61 }
62
63 void LiveIntervals::releaseMemory()
64 {
65     mbbi2mbbMap_.clear();
66     mi2iMap_.clear();
67     r2iMap_.clear();
68     r2iMap_.clear();
69     r2rMap_.clear();
70     intervals_.clear();
71 }
72
73
74 /// runOnMachineFunction - Register allocate the whole function
75 ///
76 bool LiveIntervals::runOnMachineFunction(MachineFunction &fn) {
77     DEBUG(std::cerr << "Machine Function\n");
78     mf_ = &fn;
79     tm_ = &fn.getTarget();
80     mri_ = tm_->getRegisterInfo();
81     lv_ = &getAnalysis<LiveVariables>();
82
83     // number MachineInstrs
84     unsigned miIndex = 0;
85     for (MachineFunction::iterator mbb = mf_->begin(), mbbEnd = mf_->end();
86          mbb != mbbEnd; ++mbb) {
87         const std::pair<MachineBasicBlock*, unsigned>& entry =
88             lv_->getMachineBasicBlockInfo(mbb);
89         bool inserted = mbbi2mbbMap_.insert(std::make_pair(entry.second,
90                                                            entry.first)).second;
91         assert(inserted && "multiple index -> MachineBasicBlock");
92
93         for (MachineBasicBlock::iterator mi = mbb->begin(), miEnd = mbb->end();
94              mi != miEnd; ++mi) {
95             inserted = mi2iMap_.insert(std::make_pair(*mi, miIndex)).second;
96             assert(inserted && "multiple MachineInstr -> index mappings");
97             ++miIndex;
98         }
99     }
100
101     computeIntervals();
102
103     // compute spill weights
104     const LoopInfo& loopInfo = getAnalysis<LoopInfo>();
105     const TargetInstrInfo& tii = tm_->getInstrInfo();
106
107     for (MachineFunction::const_iterator mbbi = mf_->begin(),
108              mbbe = mf_->end(); mbbi != mbbe; ++mbbi) {
109         const MachineBasicBlock* mbb = mbbi;
110         unsigned loopDepth = loopInfo.getLoopDepth(mbb->getBasicBlock());
111
112         if (loopDepth) {
113             for (MachineBasicBlock::const_iterator mii = mbb->begin(),
114                      mie = mbb->end(); mii != mie; ++mii) {
115                 MachineInstr* mi = *mii;
116
117                 for (int i = mi->getNumOperands() - 1; i >= 0; --i) {
118                     MachineOperand& mop = mi->getOperand(i);
119
120                     if (!mop.isVirtualRegister())
121                         continue;
122
123                     unsigned reg = mop.getAllocatedRegNum();
124                     Reg2IntervalMap::iterator r2iit = r2iMap_.find(reg);
125                     assert(r2iit != r2iMap_.end());
126                     r2iit->second->weight += pow(10.0F, loopDepth);
127                 }
128             }
129         }
130     }
131
132     // join intervals if requested
133     if (join) joinIntervals();
134
135     numIntervals += intervals_.size();
136
137     intervals_.sort(StartPointComp());
138     DEBUG(std::copy(intervals_.begin(), intervals_.end(),
139                     std::ostream_iterator<Interval>(std::cerr, "\n")));
140     return true;
141 }
142
143 void LiveIntervals::printRegName(unsigned reg) const
144 {
145     if (MRegisterInfo::isPhysicalRegister(reg))
146         std::cerr << mri_->getName(reg);
147     else
148         std::cerr << '%' << reg;
149 }
150
151 void LiveIntervals::handleVirtualRegisterDef(MachineBasicBlock* mbb,
152                                              MachineBasicBlock::iterator mi,
153                                              unsigned reg)
154 {
155     DEBUG(std::cerr << "\t\tregister: ";printRegName(reg); std::cerr << '\n');
156
157     unsigned instrIndex = getInstructionIndex(*mi);
158
159     LiveVariables::VarInfo& vi = lv_->getVarInfo(reg);
160
161     Interval* interval = 0;
162     Reg2IntervalMap::iterator r2iit = r2iMap_.lower_bound(reg);
163     if (r2iit == r2iMap_.end() || r2iit->first != reg) {
164         // add new interval
165         intervals_.push_back(Interval(reg));
166         // update interval index for this register
167         r2iMap_.insert(r2iit, std::make_pair(reg, --intervals_.end()));
168         interval = &intervals_.back();
169     }
170     else {
171         interval = &*r2iit->second;
172     }
173
174     // iterate over all of the blocks that the variable is completely
175     // live in, adding them to the live interval
176     for (unsigned i = 0, e = vi.AliveBlocks.size(); i != e; ++i) {
177         if (vi.AliveBlocks[i]) {
178             MachineBasicBlock* mbb = lv_->getIndexMachineBasicBlock(i);
179             if (!mbb->empty()) {
180                 interval->addRange(getInstructionIndex(mbb->front()),
181                                    getInstructionIndex(mbb->back()) + 1);
182             }
183         }
184     }
185
186     bool killedInDefiningBasicBlock = false;
187     for (int i = 0, e = vi.Kills.size(); i != e; ++i) {
188         MachineBasicBlock* killerBlock = vi.Kills[i].first;
189         MachineInstr* killerInstr = vi.Kills[i].second;
190         unsigned start = (mbb == killerBlock ?
191                           instrIndex :
192                           getInstructionIndex(killerBlock->front()));
193         unsigned end = getInstructionIndex(killerInstr) + 1;
194         // we do not want to add invalid ranges. these can happen when
195         // a variable has its latest use and is redefined later on in
196         // the same basic block (common with variables introduced by
197         // PHI elimination)
198         if (start < end) {
199             killedInDefiningBasicBlock |= mbb == killerBlock;
200             interval->addRange(start, end);
201         }
202     }
203
204     if (!killedInDefiningBasicBlock) {
205         unsigned end = getInstructionIndex(mbb->back()) + 1;
206         interval->addRange(instrIndex, end);
207     }
208 }
209
210 void LiveIntervals::handlePhysicalRegisterDef(MachineBasicBlock* mbb,
211                                               MachineBasicBlock::iterator mi,
212                                               unsigned reg)
213 {
214     typedef LiveVariables::killed_iterator KillIter;
215
216     DEBUG(std::cerr << "\t\tregister: "; printRegName(reg));
217
218     MachineBasicBlock::iterator e = mbb->end();
219     unsigned start = getInstructionIndex(*mi);
220     unsigned end = start + 1;
221
222     // a variable can be dead by the instruction defining it
223     for (KillIter ki = lv_->dead_begin(*mi), ke = lv_->dead_end(*mi);
224          ki != ke; ++ki) {
225         if (reg == ki->second) {
226             DEBUG(std::cerr << " dead\n");
227             goto exit;
228         }
229     }
230
231     // a variable can only be killed by subsequent instructions
232     do {
233         ++mi;
234         ++end;
235         for (KillIter ki = lv_->killed_begin(*mi), ke = lv_->killed_end(*mi);
236              ki != ke; ++ki) {
237             if (reg == ki->second) {
238                 DEBUG(std::cerr << " killed\n");
239                 goto exit;
240             }
241         }
242     } while (mi != e);
243
244 exit:
245     assert(start < end && "did not find end of interval?");
246
247     Reg2IntervalMap::iterator r2iit = r2iMap_.lower_bound(reg);
248     if (r2iit != r2iMap_.end() && r2iit->first == reg) {
249         r2iit->second->addRange(start, end);
250     }
251     else {
252         intervals_.push_back(Interval(reg));
253         // update interval index for this register
254         r2iMap_.insert(r2iit, std::make_pair(reg, --intervals_.end()));
255         intervals_.back().addRange(start, end);
256     }
257 }
258
259 void LiveIntervals::handleRegisterDef(MachineBasicBlock* mbb,
260                                       MachineBasicBlock::iterator mi,
261                                       unsigned reg)
262 {
263     if (MRegisterInfo::isPhysicalRegister(reg)) {
264         if (lv_->getAllocatablePhysicalRegisters()[reg]) {
265             handlePhysicalRegisterDef(mbb, mi, reg);
266             for (const unsigned* as = mri_->getAliasSet(reg); *as; ++as)
267                 handlePhysicalRegisterDef(mbb, mi, *as);
268         }
269     }
270     else {
271         handleVirtualRegisterDef(mbb, mi, reg);
272     }
273 }
274
275 unsigned LiveIntervals::getInstructionIndex(MachineInstr* instr) const
276 {
277     assert(mi2iMap_.find(instr) != mi2iMap_.end() &&
278            "instruction not assigned a number");
279     return mi2iMap_.find(instr)->second;
280 }
281
282 /// computeIntervals - computes the live intervals for virtual
283 /// registers. for some ordering of the machine instructions [1,N] a
284 /// live interval is an interval [i, j) where 1 <= i <= j < N for
285 /// which a variable is live
286 void LiveIntervals::computeIntervals()
287 {
288     DEBUG(std::cerr << "computing live intervals:\n");
289
290     for (MbbIndex2MbbMap::iterator
291              it = mbbi2mbbMap_.begin(), itEnd = mbbi2mbbMap_.end();
292          it != itEnd; ++it) {
293         MachineBasicBlock* mbb = it->second;
294         DEBUG(std::cerr << "machine basic block: "
295               << mbb->getBasicBlock()->getName() << "\n");
296
297         for (MachineBasicBlock::iterator mi = mbb->begin(), miEnd = mbb->end();
298              mi != miEnd; ++mi) {
299             MachineInstr* instr = *mi;
300             const TargetInstrDescriptor& tid =
301                 tm_->getInstrInfo().get(instr->getOpcode());
302             DEBUG(std::cerr << "\t[" << getInstructionIndex(instr) << "] ";
303                   instr->print(std::cerr, *tm_););
304
305             // handle implicit defs
306             for (const unsigned* id = tid.ImplicitDefs; *id; ++id)
307                 handleRegisterDef(mbb, mi, *id);
308
309             // handle explicit defs
310             for (int i = instr->getNumOperands() - 1; i >= 0; --i) {
311                 MachineOperand& mop = instr->getOperand(i);
312                 // handle register defs - build intervals
313                 if (mop.isRegister() && mop.isDef())
314                     handleRegisterDef(mbb, mi, mop.getAllocatedRegNum());
315             }
316         }
317     }
318 }
319
320 unsigned LiveIntervals::rep(unsigned reg)
321 {
322     Reg2RegMap::iterator it = r2rMap_.find(reg);
323     if (it != r2rMap_.end())
324         return it->second = rep(it->second);
325     return reg;
326 }
327
328 void LiveIntervals::joinIntervals()
329 {
330     DEBUG(std::cerr << "joining compatible intervals:\n");
331
332     const TargetInstrInfo& tii = tm_->getInstrInfo();
333
334     for (MachineFunction::const_iterator mbbi = mf_->begin(),
335              mbbe = mf_->end(); mbbi != mbbe; ++mbbi) {
336         const MachineBasicBlock* mbb = mbbi;
337         DEBUG(std::cerr << "machine basic block: "
338               << mbb->getBasicBlock()->getName() << "\n");
339
340         for (MachineBasicBlock::const_iterator mii = mbb->begin(),
341                  mie = mbb->end(); mii != mie; ++mii) {
342             MachineInstr* mi = *mii;
343             const TargetInstrDescriptor& tid =
344                 tm_->getInstrInfo().get(mi->getOpcode());
345             DEBUG(std::cerr << "\t\tinstruction["
346                   << getInstructionIndex(mi) << "]: ";
347                   mi->print(std::cerr, *tm_););
348
349             // we only join virtual registers with allocatable
350             // physical registers since we do not have liveness information
351             // on not allocatable physical registers
352             unsigned regA, regB;
353             if (tii.isMoveInstr(*mi, regA, regB) &&
354                 (MRegisterInfo::isVirtualRegister(regA) ||
355                  lv_->getAllocatablePhysicalRegisters()[regA]) &&
356                 (MRegisterInfo::isVirtualRegister(regB) ||
357                  lv_->getAllocatablePhysicalRegisters()[regB])) {
358
359                 // get representative registers
360                 regA = rep(regA);
361                 regB = rep(regB);
362
363                 // if they are already joined we continue
364                 if (regA == regB)
365                     continue;
366
367                 Reg2IntervalMap::iterator r2iA = r2iMap_.find(regA);
368                 assert(r2iA != r2iMap_.end());
369                 Reg2IntervalMap::iterator r2iB = r2iMap_.find(regB);
370                 assert(r2iB != r2iMap_.end());
371
372                 Intervals::iterator intA = r2iA->second;
373                 Intervals::iterator intB = r2iB->second;
374
375                 // both A and B are virtual registers
376                 if (MRegisterInfo::isVirtualRegister(intA->reg) &&
377                     MRegisterInfo::isVirtualRegister(intB->reg)) {
378
379                     const TargetRegisterClass *rcA, *rcB;
380                     rcA = mf_->getSSARegMap()->getRegClass(intA->reg);
381                     rcB = mf_->getSSARegMap()->getRegClass(intB->reg);
382                     assert(rcA == rcB && "registers must be of the same class");
383
384                     // if their intervals do not overlap we join them
385                     if (!intB->overlaps(*intA)) {
386                         intA->join(*intB);
387                         r2iB->second = r2iA->second;
388                         r2rMap_.insert(std::make_pair(intB->reg, intA->reg));
389                         intervals_.erase(intB);
390                         ++numJoined;
391                     }
392                 }
393                 else if (MRegisterInfo::isPhysicalRegister(intA->reg) xor
394                          MRegisterInfo::isPhysicalRegister(intB->reg)) {
395                     if (MRegisterInfo::isPhysicalRegister(intB->reg)) {
396                         std::swap(regA, regB);
397                         std::swap(intA, intB);
398                         std::swap(r2iA, r2iB);
399                     }
400
401                     assert(MRegisterInfo::isPhysicalRegister(intA->reg) &&
402                            MRegisterInfo::isVirtualRegister(intB->reg) &&
403                            "A must be physical and B must be virtual");
404                     assert(intA->reg != intB->reg);
405                     if (!intA->overlaps(*intB) &&
406                          !overlapsAliases(*intA, *intB)) {
407                         intA->join(*intB);
408                         r2iB->second = r2iA->second;
409                         r2rMap_.insert(std::make_pair(intB->reg, intA->reg));
410                         intervals_.erase(intB);
411                         ++numJoined;
412                     }
413                 }
414             }
415         }
416     }
417 }
418
419 bool LiveIntervals::overlapsAliases(const Interval& lhs,
420                                     const Interval& rhs) const
421 {
422     assert(MRegisterInfo::isPhysicalRegister(lhs.reg) &&
423            "first interval must describe a physical register");
424
425     for (const unsigned* as = mri_->getAliasSet(lhs.reg); *as; ++as) {
426         Reg2IntervalMap::const_iterator r2i = r2iMap_.find(*as);
427         assert(r2i != r2iMap_.end() && "alias does not have interval?");
428         if (rhs.overlaps(*r2i->second))
429             return true;
430     }
431
432     return false;
433 }
434
435 LiveIntervals::Interval::Interval(unsigned r)
436     : reg(r),
437       weight((MRegisterInfo::isPhysicalRegister(r) ?
438               std::numeric_limits<float>::max() : 0.0F))
439 {
440
441 }
442
443 // This example is provided becaues liveAt() is non-obvious:
444 //
445 // this = [1,2), liveAt(1) will return false. The idea is that the
446 // variable is defined in 1 and not live after definition. So it was
447 // dead to begin with (defined but never used).
448 //
449 // this = [1,3), liveAt(2) will return false. The variable is used at
450 // 2 but 2 is the last use so the variable's allocated register is
451 // available for reuse.
452 bool LiveIntervals::Interval::liveAt(unsigned index) const
453 {
454     Range dummy(index, index+1);
455     Ranges::const_iterator r = std::upper_bound(ranges.begin(),
456                                                 ranges.end(),
457                                                 dummy);
458     if (r == ranges.begin())
459         return false;
460
461     --r;
462     return index >= r->first && index < (r->second - 1);
463 }
464
465 // This example is provided because overlaps() is non-obvious:
466 //
467 // 0: A = ...
468 // 1: B = ...
469 // 2: C = A + B ;; last use of A
470 //
471 // The live intervals should look like:
472 //
473 // A = [0, 3)
474 // B = [1, x)
475 // C = [2, y)
476 //
477 // A->overlaps(C) should return false since we want to be able to join
478 // A and C.
479 bool LiveIntervals::Interval::overlaps(const Interval& other) const
480 {
481     Ranges::const_iterator i = ranges.begin();
482     Ranges::const_iterator ie = ranges.end();
483     Ranges::const_iterator j = other.ranges.begin();
484     Ranges::const_iterator je = other.ranges.end();
485     if (i->first < j->first) {
486         i = std::upper_bound(i, ie, *j);
487         if (i != ranges.begin()) --i;
488     }
489     else if (j->first < i->first) {
490         j = std::upper_bound(j, je, *i);
491         if (j != other.ranges.begin()) --j;
492     }
493
494     while (i != ie && j != je) {
495         if (i->first == j->first) {
496             return true;
497         }
498         else {
499             if (i->first > j->first) {
500                 swap(i, j);
501                 swap(ie, je);
502             }
503             assert(i->first < j->first);
504
505             if ((i->second - 1) > j->first) {
506                 return true;
507             }
508             else {
509                 ++i;
510             }
511         }
512     }
513
514     return false;
515 }
516
517 void LiveIntervals::Interval::addRange(unsigned start, unsigned end)
518 {
519     assert(start < end && "Invalid range to add!");
520     DEBUG(std::cerr << "\t\t\tadding range: [" << start <<','<< end << ") -> ");
521     //assert(start < end && "invalid range?");
522     Range range = std::make_pair(start, end);
523     Ranges::iterator it =
524         ranges.insert(std::upper_bound(ranges.begin(), ranges.end(), range),
525                       range);
526
527     it = mergeRangesForward(it);
528     it = mergeRangesBackward(it);
529     DEBUG(std::cerr << "\t\t\t\tafter merging: " << *this << '\n');
530 }
531
532 void LiveIntervals::Interval::join(const LiveIntervals::Interval& other)
533 {
534     DEBUG(std::cerr << "\t\t\t\tjoining intervals: "
535           << other << " and " << *this << '\n');
536     Ranges::iterator cur = ranges.begin();
537
538     for (Ranges::const_iterator i = other.ranges.begin(),
539              e = other.ranges.end(); i != e; ++i) {
540         cur = ranges.insert(std::upper_bound(cur, ranges.end(), *i), *i);
541         cur = mergeRangesForward(cur);
542         cur = mergeRangesBackward(cur);
543     }
544     if (MRegisterInfo::isVirtualRegister(reg))
545         weight += other.weight;
546
547     DEBUG(std::cerr << "\t\t\t\tafter merging: " << *this << '\n');
548 }
549
550 LiveIntervals::Interval::Ranges::iterator
551 LiveIntervals::Interval::mergeRangesForward(Ranges::iterator it)
552 {
553     for (Ranges::iterator next = it + 1;
554          next != ranges.end() && it->second >= next->first; ) {
555         it->second = std::max(it->second, next->second);
556         next = ranges.erase(next);
557     }
558     return it;
559 }
560
561 LiveIntervals::Interval::Ranges::iterator
562 LiveIntervals::Interval::mergeRangesBackward(Ranges::iterator it)
563 {
564     while (it != ranges.begin()) {
565         Ranges::iterator prev = it - 1;
566         if (it->first > prev->second) break;
567
568         it->first = std::min(it->first, prev->first);
569         it->second = std::max(it->second, prev->second);
570         it = ranges.erase(prev);
571     }
572
573     return it;
574 }
575
576 std::ostream& llvm::operator<<(std::ostream& os,
577                                const LiveIntervals::Interval& li)
578 {
579     os << "%reg" << li.reg << ',' << li.weight << " = ";
580     for (LiveIntervals::Interval::Ranges::const_iterator
581              i = li.ranges.begin(), e = li.ranges.end(); i != e; ++i) {
582         os << "[" << i->first << "," << i->second << ")";
583     }
584     return os;
585 }