Add support for the llvm.memmove intrinsic
[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 joined intervals");
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 += 2;
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         for (MachineBasicBlock::const_iterator mi = mbb->begin(),
113                  mie = mbb->end(); mi != mie; ++mi) {
114             for (int i = mi->getNumOperands() - 1; i >= 0; --i) {
115                 const MachineOperand& mop = mi->getOperand(i);
116                 if (mop.isRegister() &&
117                     MRegisterInfo::isVirtualRegister(mop.getReg())) {
118                     unsigned reg = mop.getAllocatedRegNum();
119                     Reg2IntervalMap::iterator r2iit = r2iMap_.find(reg);
120                     assert(r2iit != r2iMap_.end());
121                     r2iit->second->weight += pow(10.0F, loopDepth);
122                 }
123             }
124         }
125     }
126
127     // join intervals if requested
128     if (join) joinIntervals();
129
130     numIntervals += intervals_.size();
131
132     intervals_.sort(StartPointComp());
133     DEBUG(std::copy(intervals_.begin(), intervals_.end(),
134                     std::ostream_iterator<Interval>(std::cerr, "\n")));
135     return true;
136 }
137
138 void LiveIntervals::printRegName(unsigned reg) const
139 {
140     if (MRegisterInfo::isPhysicalRegister(reg))
141         std::cerr << mri_->getName(reg);
142     else
143         std::cerr << '%' << reg;
144 }
145
146 void LiveIntervals::handleVirtualRegisterDef(MachineBasicBlock* mbb,
147                                              MachineBasicBlock::iterator mi,
148                                              unsigned reg)
149 {
150     DEBUG(std::cerr << "\t\tregister: ";printRegName(reg); std::cerr << '\n');
151
152     LiveVariables::VarInfo& vi = lv_->getVarInfo(reg);
153
154     Interval* interval = 0;
155     Reg2IntervalMap::iterator r2iit = r2iMap_.lower_bound(reg);
156     if (r2iit == r2iMap_.end() || r2iit->first != reg) {
157         // add new interval
158         intervals_.push_back(Interval(reg));
159         // update interval index for this register
160         r2iMap_.insert(r2iit, std::make_pair(reg, --intervals_.end()));
161         interval = &intervals_.back();
162
163         // iterate over all of the blocks that the variable is
164         // completely live in, adding them to the live
165         // interval. obviously we only need to do this once.
166         for (unsigned i = 0, e = vi.AliveBlocks.size(); i != e; ++i) {
167             if (vi.AliveBlocks[i]) {
168                 MachineBasicBlock* mbb = lv_->getIndexMachineBasicBlock(i);
169                 if (!mbb->empty()) {
170                     interval->addRange(getInstructionIndex(&mbb->front()),
171                                        getInstructionIndex(&mbb->back()) + 1);
172                 }
173             }
174         }
175     }
176     else {
177         interval = &*r2iit->second;
178     }
179
180     // we consider defs to happen at the second time slot of the
181     // instruction
182     unsigned instrIndex = getInstructionIndex(mi) + 1;
183
184     bool killedInDefiningBasicBlock = false;
185     for (int i = 0, e = vi.Kills.size(); i != e; ++i) {
186         MachineBasicBlock* killerBlock = vi.Kills[i].first;
187         MachineInstr* killerInstr = vi.Kills[i].second;
188         unsigned start = (mbb == killerBlock ?
189                           instrIndex :
190                           getInstructionIndex(&killerBlock->front()));
191         unsigned end = (killerInstr == mi ?
192                         instrIndex + 1 : // dead
193                         getInstructionIndex(killerInstr) + 1); // killed
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     // we consider defs to happen at the second time slot of the
220     // instruction
221     unsigned start, end;
222     start = end = getInstructionIndex(mi) + 1;
223
224     // a variable can be dead by the instruction defining it
225     for (KillIter ki = lv_->dead_begin(mi), ke = lv_->dead_end(mi);
226          ki != ke; ++ki) {
227         if (reg == ki->second) {
228             DEBUG(std::cerr << " dead\n");
229             ++end;
230             goto exit;
231         }
232     }
233
234     // a variable can only be killed by subsequent instructions
235     do {
236         ++mi;
237         end += 2;
238         for (KillIter ki = lv_->killed_begin(mi), ke = lv_->killed_end(mi);
239              ki != ke; ++ki) {
240             if (reg == ki->second) {
241                 DEBUG(std::cerr << " killed\n");
242                 goto exit;
243             }
244         }
245     } while (mi != e);
246
247 exit:
248     assert(start < end && "did not find end of interval?");
249
250     Reg2IntervalMap::iterator r2iit = r2iMap_.lower_bound(reg);
251     if (r2iit != r2iMap_.end() && r2iit->first == reg) {
252         r2iit->second->addRange(start, end);
253     }
254     else {
255         intervals_.push_back(Interval(reg));
256         // update interval index for this register
257         r2iMap_.insert(r2iit, std::make_pair(reg, --intervals_.end()));
258         intervals_.back().addRange(start, end);
259     }
260 }
261
262 void LiveIntervals::handleRegisterDef(MachineBasicBlock* mbb,
263                                       MachineBasicBlock::iterator mi,
264                                       unsigned reg)
265 {
266     if (MRegisterInfo::isPhysicalRegister(reg)) {
267         if (lv_->getAllocatablePhysicalRegisters()[reg]) {
268             handlePhysicalRegisterDef(mbb, mi, reg);
269             for (const unsigned* as = mri_->getAliasSet(reg); *as; ++as)
270                 handlePhysicalRegisterDef(mbb, mi, *as);
271         }
272     }
273     else {
274         handleVirtualRegisterDef(mbb, mi, reg);
275     }
276 }
277
278 unsigned LiveIntervals::getInstructionIndex(MachineInstr* instr) const
279 {
280     assert(mi2iMap_.find(instr) != mi2iMap_.end() &&
281            "instruction not assigned a number");
282     return mi2iMap_.find(instr)->second;
283 }
284
285 /// computeIntervals - computes the live intervals for virtual
286 /// registers. for some ordering of the machine instructions [1,N] a
287 /// live interval is an interval [i, j) where 1 <= i <= j < N for
288 /// which a variable is live
289 void LiveIntervals::computeIntervals()
290 {
291     DEBUG(std::cerr << "computing live intervals:\n");
292
293     for (MbbIndex2MbbMap::iterator
294              it = mbbi2mbbMap_.begin(), itEnd = mbbi2mbbMap_.end();
295          it != itEnd; ++it) {
296         MachineBasicBlock* mbb = it->second;
297         DEBUG(std::cerr << "machine basic block: "
298               << mbb->getBasicBlock()->getName() << "\n");
299
300         for (MachineBasicBlock::iterator mi = mbb->begin(), miEnd = mbb->end();
301              mi != miEnd; ++mi) {
302             const TargetInstrDescriptor& tid =
303                 tm_->getInstrInfo().get(mi->getOpcode());
304             DEBUG(std::cerr << "\t[" << getInstructionIndex(mi) << "] ";
305                   mi->print(std::cerr, *tm_););
306
307             // handle implicit defs
308             for (const unsigned* id = tid.ImplicitDefs; *id; ++id)
309                 handleRegisterDef(mbb, mi, *id);
310
311             // handle explicit defs
312             for (int i = mi->getNumOperands() - 1; i >= 0; --i) {
313                 MachineOperand& mop = mi->getOperand(i);
314                 // handle register defs - build intervals
315                 if (mop.isRegister() && mop.isDef())
316                     handleRegisterDef(mbb, mi, mop.getAllocatedRegNum());
317             }
318         }
319     }
320 }
321
322 unsigned LiveIntervals::rep(unsigned reg)
323 {
324     Reg2RegMap::iterator it = r2rMap_.find(reg);
325     if (it != r2rMap_.end())
326         return it->second = rep(it->second);
327     return reg;
328 }
329
330 void LiveIntervals::joinIntervals()
331 {
332     DEBUG(std::cerr << "joining compatible intervals:\n");
333
334     const TargetInstrInfo& tii = tm_->getInstrInfo();
335
336     for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
337          mbbi != mbbe; ++mbbi) {
338         MachineBasicBlock* mbb = mbbi;
339         DEBUG(std::cerr << "machine basic block: "
340               << mbb->getBasicBlock()->getName() << "\n");
341
342         for (MachineBasicBlock::iterator mi = mbb->begin(), mie = mbb->end();
343              mi != mie; ++mi) {
344             const TargetInstrDescriptor& tid =
345                 tm_->getInstrInfo().get(mi->getOpcode());
346             DEBUG(std::cerr << "\t\tinstruction["
347                   << getInstructionIndex(mi) << "]: ";
348                   mi->print(std::cerr, *tm_););
349
350             // we only join virtual registers with allocatable
351             // physical registers since we do not have liveness information
352             // on not allocatable physical registers
353             unsigned regA, regB;
354             if (tii.isMoveInstr(*mi, regA, regB) &&
355                 (MRegisterInfo::isVirtualRegister(regA) ||
356                  lv_->getAllocatablePhysicalRegisters()[regA]) &&
357                 (MRegisterInfo::isVirtualRegister(regB) ||
358                  lv_->getAllocatablePhysicalRegisters()[regB])) {
359
360                 // get representative registers
361                 regA = rep(regA);
362                 regB = rep(regB);
363
364                 // if they are already joined we continue
365                 if (regA == regB)
366                     continue;
367
368                 Reg2IntervalMap::iterator r2iA = r2iMap_.find(regA);
369                 assert(r2iA != r2iMap_.end());
370                 Reg2IntervalMap::iterator r2iB = r2iMap_.find(regB);
371                 assert(r2iB != r2iMap_.end());
372
373                 Intervals::iterator intA = r2iA->second;
374                 Intervals::iterator intB = r2iB->second;
375
376                 // both A and B are virtual registers
377                 if (MRegisterInfo::isVirtualRegister(intA->reg) &&
378                     MRegisterInfo::isVirtualRegister(intB->reg)) {
379
380                     const TargetRegisterClass *rcA, *rcB;
381                     rcA = mf_->getSSARegMap()->getRegClass(intA->reg);
382                     rcB = mf_->getSSARegMap()->getRegClass(intB->reg);
383                     assert(rcA == rcB && "registers must be of the same class");
384
385                     // if their intervals do not overlap we join them
386                     if (!intB->overlaps(*intA)) {
387                         intA->join(*intB);
388                         r2iB->second = r2iA->second;
389                         r2rMap_.insert(std::make_pair(intB->reg, intA->reg));
390                         intervals_.erase(intB);
391                         ++numJoined;
392                     }
393                 }
394                 else if (MRegisterInfo::isPhysicalRegister(intA->reg) ^
395                          MRegisterInfo::isPhysicalRegister(intB->reg)) {
396                     if (MRegisterInfo::isPhysicalRegister(intB->reg)) {
397                         std::swap(regA, regB);
398                         std::swap(intA, intB);
399                         std::swap(r2iA, r2iB);
400                     }
401
402                     assert(MRegisterInfo::isPhysicalRegister(intA->reg) &&
403                            MRegisterInfo::isVirtualRegister(intB->reg) &&
404                            "A must be physical and B must be virtual");
405
406                     if (!intA->overlaps(*intB) &&
407                          !overlapsAliases(*intA, *intB)) {
408                         intA->join(*intB);
409                         r2iB->second = r2iA->second;
410                         r2rMap_.insert(std::make_pair(intB->reg, intA->reg));
411                         intervals_.erase(intB);
412                         ++numJoined;
413                     }
414                 }
415             }
416         }
417     }
418 }
419
420 bool LiveIntervals::overlapsAliases(const Interval& lhs,
421                                     const Interval& rhs) const
422 {
423     assert(MRegisterInfo::isPhysicalRegister(lhs.reg) &&
424            "first interval must describe a physical register");
425
426     for (const unsigned* as = mri_->getAliasSet(lhs.reg); *as; ++as) {
427         Reg2IntervalMap::const_iterator r2i = r2iMap_.find(*as);
428         assert(r2i != r2iMap_.end() && "alias does not have interval?");
429         if (rhs.overlaps(*r2i->second))
430             return true;
431     }
432
433     return false;
434 }
435
436 LiveIntervals::Interval::Interval(unsigned r)
437     : reg(r),
438       weight((MRegisterInfo::isPhysicalRegister(r) ?
439               std::numeric_limits<float>::max() : 0.0F))
440 {
441
442 }
443
444 // An example for liveAt():
445 //
446 // this = [1,2), liveAt(0) will return false. The instruction defining
447 // this spans slots [0,1]. Since it is a definition we say that it is
448 // live in the second slot onwards. By ending the lifetime of this
449 // interval at 2 it means that it is not used at all. liveAt(1)
450 // returns true which means that this clobbers a register at
451 // instruction at 0.
452 //
453 // this = [1,4), liveAt(0) will return false and liveAt(2) will return
454 // true.  The variable is defined at instruction 0 and last used at 2.
455 bool LiveIntervals::Interval::liveAt(unsigned index) const
456 {
457     Range dummy(index, index+1);
458     Ranges::const_iterator r = std::upper_bound(ranges.begin(),
459                                                 ranges.end(),
460                                                 dummy);
461     if (r == ranges.begin())
462         return false;
463
464     --r;
465     return index >= r->first && index < r->second;
466 }
467
468 // An example for overlaps():
469 //
470 // 0: A = ...
471 // 2: B = ...
472 // 4: C = A + B ;; last use of A
473 //
474 // The live intervals should look like:
475 //
476 // A = [1, 5)
477 // B = [3, x)
478 // C = [5, y)
479 //
480 // A->overlaps(C) should return false since we want to be able to join
481 // A and C.
482 bool LiveIntervals::Interval::overlaps(const Interval& other) const
483 {
484     Ranges::const_iterator i = ranges.begin();
485     Ranges::const_iterator ie = ranges.end();
486     Ranges::const_iterator j = other.ranges.begin();
487     Ranges::const_iterator je = other.ranges.end();
488     if (i->first < j->first) {
489         i = std::upper_bound(i, ie, *j);
490         if (i != ranges.begin()) --i;
491     }
492     else if (j->first < i->first) {
493         j = std::upper_bound(j, je, *i);
494         if (j != other.ranges.begin()) --j;
495     }
496
497     while (i != ie && j != je) {
498         if (i->first == j->first) {
499             return true;
500         }
501         else {
502             if (i->first > j->first) {
503                 swap(i, j);
504                 swap(ie, je);
505             }
506             assert(i->first < j->first);
507
508             if (i->second > j->first) {
509                 return true;
510             }
511             else {
512                 ++i;
513             }
514         }
515     }
516
517     return false;
518 }
519
520 void LiveIntervals::Interval::addRange(unsigned start, unsigned end)
521 {
522     assert(start < end && "Invalid range to add!");
523     DEBUG(std::cerr << "\t\t\tadding range: [" << start <<','<< end << ") -> ");
524     //assert(start < end && "invalid range?");
525     Range range = std::make_pair(start, end);
526     Ranges::iterator it =
527         ranges.insert(std::upper_bound(ranges.begin(), ranges.end(), range),
528                       range);
529
530     it = mergeRangesForward(it);
531     it = mergeRangesBackward(it);
532     DEBUG(std::cerr << "\t\t\t\tafter merging: " << *this << '\n');
533 }
534
535 void LiveIntervals::Interval::join(const LiveIntervals::Interval& other)
536 {
537     DEBUG(std::cerr << "\t\t\t\tjoining intervals: "
538           << other << " and " << *this << '\n');
539     Ranges::iterator cur = ranges.begin();
540
541     for (Ranges::const_iterator i = other.ranges.begin(),
542              e = other.ranges.end(); i != e; ++i) {
543         cur = ranges.insert(std::upper_bound(cur, ranges.end(), *i), *i);
544         cur = mergeRangesForward(cur);
545         cur = mergeRangesBackward(cur);
546     }
547     if (MRegisterInfo::isVirtualRegister(reg))
548         weight += other.weight;
549
550     DEBUG(std::cerr << "\t\t\t\tafter merging: " << *this << '\n');
551 }
552
553 LiveIntervals::Interval::Ranges::iterator
554 LiveIntervals::Interval::mergeRangesForward(Ranges::iterator it)
555 {
556     for (Ranges::iterator next = it + 1;
557          next != ranges.end() && it->second >= next->first; ) {
558         it->second = std::max(it->second, next->second);
559         next = ranges.erase(next);
560     }
561     return it;
562 }
563
564 LiveIntervals::Interval::Ranges::iterator
565 LiveIntervals::Interval::mergeRangesBackward(Ranges::iterator it)
566 {
567     while (it != ranges.begin()) {
568         Ranges::iterator prev = it - 1;
569         if (it->first > prev->second) break;
570
571         it->first = std::min(it->first, prev->first);
572         it->second = std::max(it->second, prev->second);
573         it = ranges.erase(prev);
574     }
575
576     return it;
577 }
578
579 std::ostream& llvm::operator<<(std::ostream& os,
580                                const LiveIntervals::Interval& li)
581 {
582     os << "%reg" << li.reg << ',' << li.weight << " = ";
583     for (LiveIntervals::Interval::Ranges::const_iterator
584              i = li.ranges.begin(), e = li.ranges.end(); i != e; ++i) {
585         os << "[" << i->first << "," << i->second << ")";
586     }
587     return os;
588 }