LiveIntervalAnalysis.cpp revision bfe180af9eef1cf767f61f501ca325fcce2ae7ce
1//===-- LiveIntervalAnalysis.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/LiveIntervalAnalysis.h"
20#include "VirtRegMap.h"
21#include "llvm/Value.h"
22#include "llvm/Analysis/LoopInfo.h"
23#include "llvm/CodeGen/LiveVariables.h"
24#include "llvm/CodeGen/MachineFrameInfo.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/Support/CommandLine.h"
32#include "llvm/Support/Debug.h"
33#include "llvm/ADT/Statistic.h"
34#include "llvm/ADT/STLExtras.h"
35#include <algorithm>
36#include <cmath>
37#include <iostream>
38using namespace llvm;
39
40namespace {
41  RegisterPass<LiveIntervals> X("liveintervals", "Live Interval Analysis");
42
43  static Statistic<> numIntervals
44  ("liveintervals", "Number of original intervals");
45
46  static Statistic<> numIntervalsAfter
47  ("liveintervals", "Number of intervals after coalescing");
48
49  static Statistic<> numJoins
50  ("liveintervals", "Number of interval joins performed");
51
52  static Statistic<> numPeep
53  ("liveintervals", "Number of identity moves eliminated after coalescing");
54
55  static Statistic<> numFolded
56  ("liveintervals", "Number of loads/stores folded into instructions");
57
58  static cl::opt<bool>
59  EnableJoining("join-liveintervals",
60                cl::desc("Join compatible live intervals"),
61                cl::init(true));
62}
63
64void LiveIntervals::getAnalysisUsage(AnalysisUsage &AU) const {
65  AU.addRequired<LiveVariables>();
66  AU.addPreservedID(PHIEliminationID);
67  AU.addRequiredID(PHIEliminationID);
68  AU.addRequiredID(TwoAddressInstructionPassID);
69  AU.addRequired<LoopInfo>();
70  MachineFunctionPass::getAnalysisUsage(AU);
71}
72
73void LiveIntervals::releaseMemory() {
74  mi2iMap_.clear();
75  i2miMap_.clear();
76  r2iMap_.clear();
77  r2rMap_.clear();
78}
79
80
81static bool isZeroLengthInterval(LiveInterval *li) {
82  for (LiveInterval::Ranges::const_iterator
83         i = li->ranges.begin(), e = li->ranges.end(); i != e; ++i)
84    if (i->end - i->start > LiveIntervals::InstrSlots::NUM)
85      return false;
86  return true;
87}
88
89
90/// runOnMachineFunction - Register allocate the whole function
91///
92bool LiveIntervals::runOnMachineFunction(MachineFunction &fn) {
93  mf_ = &fn;
94  tm_ = &fn.getTarget();
95  mri_ = tm_->getRegisterInfo();
96  tii_ = tm_->getInstrInfo();
97  lv_ = &getAnalysis<LiveVariables>();
98  allocatableRegs_ = mri_->getAllocatableSet(fn);
99  r2rMap_.grow(mf_->getSSARegMap()->getLastVirtReg());
100
101  // If this function has any live ins, insert a dummy instruction at the
102  // beginning of the function that we will pretend "defines" the values.  This
103  // is to make the interval analysis simpler by providing a number.
104  if (fn.livein_begin() != fn.livein_end()) {
105    unsigned FirstLiveIn = fn.livein_begin()->first;
106
107    // Find a reg class that contains this live in.
108    const TargetRegisterClass *RC = 0;
109    for (MRegisterInfo::regclass_iterator RCI = mri_->regclass_begin(),
110           E = mri_->regclass_end(); RCI != E; ++RCI)
111      if ((*RCI)->contains(FirstLiveIn)) {
112        RC = *RCI;
113        break;
114      }
115
116    MachineInstr *OldFirstMI = fn.begin()->begin();
117    mri_->copyRegToReg(*fn.begin(), fn.begin()->begin(),
118                       FirstLiveIn, FirstLiveIn, RC);
119    assert(OldFirstMI != fn.begin()->begin() &&
120           "copyRetToReg didn't insert anything!");
121  }
122
123  // number MachineInstrs
124  unsigned miIndex = 0;
125  for (MachineFunction::iterator mbb = mf_->begin(), mbbEnd = mf_->end();
126       mbb != mbbEnd; ++mbb)
127    for (MachineBasicBlock::iterator mi = mbb->begin(), miEnd = mbb->end();
128         mi != miEnd; ++mi) {
129      bool inserted = mi2iMap_.insert(std::make_pair(mi, miIndex)).second;
130      assert(inserted && "multiple MachineInstr -> index mappings");
131      i2miMap_.push_back(mi);
132      miIndex += InstrSlots::NUM;
133    }
134
135  // Note intervals due to live-in values.
136  if (fn.livein_begin() != fn.livein_end()) {
137    MachineBasicBlock *Entry = fn.begin();
138    for (MachineFunction::livein_iterator I = fn.livein_begin(),
139           E = fn.livein_end(); I != E; ++I) {
140      handlePhysicalRegisterDef(Entry, Entry->begin(),
141                                getOrCreateInterval(I->first), 0);
142      for (const unsigned* AS = mri_->getAliasSet(I->first); *AS; ++AS)
143        handlePhysicalRegisterDef(Entry, Entry->begin(),
144                                  getOrCreateInterval(*AS), 0);
145    }
146  }
147
148  computeIntervals();
149
150  numIntervals += getNumIntervals();
151
152  DEBUG(std::cerr << "********** INTERVALS **********\n";
153        for (iterator I = begin(), E = end(); I != E; ++I) {
154          I->second.print(std::cerr, mri_);
155          std::cerr << "\n";
156        });
157
158  // join intervals if requested
159  if (EnableJoining) joinIntervals();
160
161  numIntervalsAfter += getNumIntervals();
162
163  // perform a final pass over the instructions and compute spill
164  // weights, coalesce virtual registers and remove identity moves
165  const LoopInfo& loopInfo = getAnalysis<LoopInfo>();
166
167  for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
168       mbbi != mbbe; ++mbbi) {
169    MachineBasicBlock* mbb = mbbi;
170    unsigned loopDepth = loopInfo.getLoopDepth(mbb->getBasicBlock());
171
172    for (MachineBasicBlock::iterator mii = mbb->begin(), mie = mbb->end();
173         mii != mie; ) {
174      // if the move will be an identity move delete it
175      unsigned srcReg, dstReg, RegRep;
176      if (tii_->isMoveInstr(*mii, srcReg, dstReg) &&
177          (RegRep = rep(srcReg)) == rep(dstReg)) {
178        // remove from def list
179        LiveInterval &interval = getOrCreateInterval(RegRep);
180        RemoveMachineInstrFromMaps(mii);
181        mii = mbbi->erase(mii);
182        ++numPeep;
183      }
184      else {
185        for (unsigned i = 0; i < mii->getNumOperands(); ++i) {
186          const MachineOperand& mop = mii->getOperand(i);
187          if (mop.isRegister() && mop.getReg() &&
188              MRegisterInfo::isVirtualRegister(mop.getReg())) {
189            // replace register with representative register
190            unsigned reg = rep(mop.getReg());
191            mii->getOperand(i).setReg(reg);
192
193            LiveInterval &RegInt = getInterval(reg);
194            RegInt.weight +=
195              (mop.isUse() + mop.isDef()) * pow(10.0F, (int)loopDepth);
196          }
197        }
198        ++mii;
199      }
200    }
201  }
202
203  for (iterator I = begin(), E = end(); I != E; ++I) {
204    LiveInterval &li = I->second;
205    if (MRegisterInfo::isVirtualRegister(li.reg)) {
206      // If the live interval length is essentially zero, i.e. in every live
207      // range the use follows def immediately, it doesn't make sense to spill
208      // it and hope it will be easier to allocate for this li.
209      if (isZeroLengthInterval(&li))
210        li.weight = float(HUGE_VAL);
211    }
212  }
213
214  DEBUG(dump());
215  return true;
216}
217
218/// print - Implement the dump method.
219void LiveIntervals::print(std::ostream &O, const Module* ) const {
220  O << "********** INTERVALS **********\n";
221  for (const_iterator I = begin(), E = end(); I != E; ++I) {
222    I->second.print(std::cerr, mri_);
223    std::cerr << "\n";
224  }
225
226  O << "********** MACHINEINSTRS **********\n";
227  for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
228       mbbi != mbbe; ++mbbi) {
229    O << ((Value*)mbbi->getBasicBlock())->getName() << ":\n";
230    for (MachineBasicBlock::iterator mii = mbbi->begin(),
231           mie = mbbi->end(); mii != mie; ++mii) {
232      O << getInstructionIndex(mii) << '\t' << *mii;
233    }
234  }
235}
236
237std::vector<LiveInterval*> LiveIntervals::
238addIntervalsForSpills(const LiveInterval &li, VirtRegMap &vrm, int slot) {
239  // since this is called after the analysis is done we don't know if
240  // LiveVariables is available
241  lv_ = getAnalysisToUpdate<LiveVariables>();
242
243  std::vector<LiveInterval*> added;
244
245  assert(li.weight != HUGE_VAL &&
246         "attempt to spill already spilled interval!");
247
248  DEBUG(std::cerr << "\t\t\t\tadding intervals for spills for interval: ";
249        li.print(std::cerr, mri_); std::cerr << '\n');
250
251  const TargetRegisterClass* rc = mf_->getSSARegMap()->getRegClass(li.reg);
252
253  for (LiveInterval::Ranges::const_iterator
254         i = li.ranges.begin(), e = li.ranges.end(); i != e; ++i) {
255    unsigned index = getBaseIndex(i->start);
256    unsigned end = getBaseIndex(i->end-1) + InstrSlots::NUM;
257    for (; index != end; index += InstrSlots::NUM) {
258      // skip deleted instructions
259      while (index != end && !getInstructionFromIndex(index))
260        index += InstrSlots::NUM;
261      if (index == end) break;
262
263      MachineInstr *MI = getInstructionFromIndex(index);
264
265      // NewRegLiveIn - This instruction might have multiple uses of the spilled
266      // register.  In this case, for the first use, keep track of the new vreg
267      // that we reload it into.  If we see a second use, reuse this vreg
268      // instead of creating live ranges for two reloads.
269      unsigned NewRegLiveIn = 0;
270
271    for_operand:
272      for (unsigned i = 0; i != MI->getNumOperands(); ++i) {
273        MachineOperand& mop = MI->getOperand(i);
274        if (mop.isRegister() && mop.getReg() == li.reg) {
275          if (NewRegLiveIn && mop.isUse()) {
276            // We already emitted a reload of this value, reuse it for
277            // subsequent operands.
278            MI->getOperand(i).setReg(NewRegLiveIn);
279            DEBUG(std::cerr << "\t\t\t\treused reload into reg" << NewRegLiveIn
280                            << " for operand #" << i << '\n');
281          } else if (MachineInstr* fmi = mri_->foldMemoryOperand(MI, i, slot)) {
282            // Attempt to fold the memory reference into the instruction.  If we
283            // can do this, we don't need to insert spill code.
284            if (lv_)
285              lv_->instructionChanged(MI, fmi);
286            MachineBasicBlock &MBB = *MI->getParent();
287            vrm.virtFolded(li.reg, MI, i, fmi);
288            mi2iMap_.erase(MI);
289            i2miMap_[index/InstrSlots::NUM] = fmi;
290            mi2iMap_[fmi] = index;
291            MI = MBB.insert(MBB.erase(MI), fmi);
292            ++numFolded;
293            // Folding the load/store can completely change the instruction in
294            // unpredictable ways, rescan it from the beginning.
295            goto for_operand;
296          } else {
297            // This is tricky. We need to add information in the interval about
298            // the spill code so we have to use our extra load/store slots.
299            //
300            // If we have a use we are going to have a load so we start the
301            // interval from the load slot onwards. Otherwise we start from the
302            // def slot.
303            unsigned start = (mop.isUse() ?
304                              getLoadIndex(index) :
305                              getDefIndex(index));
306            // If we have a def we are going to have a store right after it so
307            // we end the interval after the use of the next
308            // instruction. Otherwise we end after the use of this instruction.
309            unsigned end = 1 + (mop.isDef() ?
310                                getStoreIndex(index) :
311                                getUseIndex(index));
312
313            // create a new register for this spill
314            NewRegLiveIn = mf_->getSSARegMap()->createVirtualRegister(rc);
315            MI->getOperand(i).setReg(NewRegLiveIn);
316            vrm.grow();
317            vrm.assignVirt2StackSlot(NewRegLiveIn, slot);
318            LiveInterval& nI = getOrCreateInterval(NewRegLiveIn);
319            assert(nI.empty());
320
321            // the spill weight is now infinity as it
322            // cannot be spilled again
323            nI.weight = float(HUGE_VAL);
324            LiveRange LR(start, end, nI.getNextValue(~0U, 0));
325            DEBUG(std::cerr << " +" << LR);
326            nI.addRange(LR);
327            added.push_back(&nI);
328
329            // update live variables if it is available
330            if (lv_)
331              lv_->addVirtualRegisterKilled(NewRegLiveIn, MI);
332
333            // If this is a live in, reuse it for subsequent live-ins.  If it's
334            // a def, we can't do this.
335            if (!mop.isUse()) NewRegLiveIn = 0;
336
337            DEBUG(std::cerr << "\t\t\t\tadded new interval: ";
338                  nI.print(std::cerr, mri_); std::cerr << '\n');
339          }
340        }
341      }
342    }
343  }
344
345  return added;
346}
347
348void LiveIntervals::printRegName(unsigned reg) const {
349  if (MRegisterInfo::isPhysicalRegister(reg))
350    std::cerr << mri_->getName(reg);
351  else
352    std::cerr << "%reg" << reg;
353}
354
355void LiveIntervals::handleVirtualRegisterDef(MachineBasicBlock *mbb,
356                                             MachineBasicBlock::iterator mi,
357                                             LiveInterval &interval) {
358  DEBUG(std::cerr << "\t\tregister: "; printRegName(interval.reg));
359  LiveVariables::VarInfo& vi = lv_->getVarInfo(interval.reg);
360
361  // Virtual registers may be defined multiple times (due to phi
362  // elimination and 2-addr elimination).  Much of what we do only has to be
363  // done once for the vreg.  We use an empty interval to detect the first
364  // time we see a vreg.
365  if (interval.empty()) {
366    // Get the Idx of the defining instructions.
367    unsigned defIndex = getDefIndex(getInstructionIndex(mi));
368
369    unsigned ValNum;
370    unsigned SrcReg, DstReg;
371    if (!tii_->isMoveInstr(*mi, SrcReg, DstReg))
372      ValNum = interval.getNextValue(~0U, 0);
373    else
374      ValNum = interval.getNextValue(defIndex, SrcReg);
375
376    assert(ValNum == 0 && "First value in interval is not 0?");
377    ValNum = 0;  // Clue in the optimizer.
378
379    // Loop over all of the blocks that the vreg is defined in.  There are
380    // two cases we have to handle here.  The most common case is a vreg
381    // whose lifetime is contained within a basic block.  In this case there
382    // will be a single kill, in MBB, which comes after the definition.
383    if (vi.Kills.size() == 1 && vi.Kills[0]->getParent() == mbb) {
384      // FIXME: what about dead vars?
385      unsigned killIdx;
386      if (vi.Kills[0] != mi)
387        killIdx = getUseIndex(getInstructionIndex(vi.Kills[0]))+1;
388      else
389        killIdx = defIndex+1;
390
391      // If the kill happens after the definition, we have an intra-block
392      // live range.
393      if (killIdx > defIndex) {
394        assert(vi.AliveBlocks.empty() &&
395               "Shouldn't be alive across any blocks!");
396        LiveRange LR(defIndex, killIdx, ValNum);
397        interval.addRange(LR);
398        DEBUG(std::cerr << " +" << LR << "\n");
399        return;
400      }
401    }
402
403    // The other case we handle is when a virtual register lives to the end
404    // of the defining block, potentially live across some blocks, then is
405    // live into some number of blocks, but gets killed.  Start by adding a
406    // range that goes from this definition to the end of the defining block.
407    LiveRange NewLR(defIndex,
408                    getInstructionIndex(&mbb->back()) + InstrSlots::NUM,
409                    ValNum);
410    DEBUG(std::cerr << " +" << NewLR);
411    interval.addRange(NewLR);
412
413    // Iterate over all of the blocks that the variable is completely
414    // live in, adding [insrtIndex(begin), instrIndex(end)+4) to the
415    // live interval.
416    for (unsigned i = 0, e = vi.AliveBlocks.size(); i != e; ++i) {
417      if (vi.AliveBlocks[i]) {
418        MachineBasicBlock* mbb = mf_->getBlockNumbered(i);
419        if (!mbb->empty()) {
420          LiveRange LR(getInstructionIndex(&mbb->front()),
421                       getInstructionIndex(&mbb->back()) + InstrSlots::NUM,
422                       ValNum);
423          interval.addRange(LR);
424          DEBUG(std::cerr << " +" << LR);
425        }
426      }
427    }
428
429    // Finally, this virtual register is live from the start of any killing
430    // block to the 'use' slot of the killing instruction.
431    for (unsigned i = 0, e = vi.Kills.size(); i != e; ++i) {
432      MachineInstr *Kill = vi.Kills[i];
433      LiveRange LR(getInstructionIndex(Kill->getParent()->begin()),
434                   getUseIndex(getInstructionIndex(Kill))+1,
435                   ValNum);
436      interval.addRange(LR);
437      DEBUG(std::cerr << " +" << LR);
438    }
439
440  } else {
441    // If this is the second time we see a virtual register definition, it
442    // must be due to phi elimination or two addr elimination.  If this is
443    // the result of two address elimination, then the vreg is the first
444    // operand, and is a def-and-use.
445    if (mi->getOperand(0).isRegister() &&
446        mi->getOperand(0).getReg() == interval.reg &&
447        mi->getOperand(0).isDef() && mi->getOperand(0).isUse()) {
448      // If this is a two-address definition, then we have already processed
449      // the live range.  The only problem is that we didn't realize there
450      // are actually two values in the live interval.  Because of this we
451      // need to take the LiveRegion that defines this register and split it
452      // into two values.
453      unsigned DefIndex = getDefIndex(getInstructionIndex(vi.DefInst));
454      unsigned RedefIndex = getDefIndex(getInstructionIndex(mi));
455
456      // Delete the initial value, which should be short and continuous,
457      // because the 2-addr copy must be in the same MBB as the redef.
458      interval.removeRange(DefIndex, RedefIndex);
459
460      // Two-address vregs should always only be redefined once.  This means
461      // that at this point, there should be exactly one value number in it.
462      assert(interval.containsOneValue() && "Unexpected 2-addr liveint!");
463
464      // The new value number (#1) is defined by the instruction we claimed
465      // defined value #0.
466      unsigned ValNo = interval.getNextValue(0, 0);
467      interval.setValueNumberInfo(1, interval.getValNumInfo(0));
468
469      // Value#0 is now defined by the 2-addr instruction.
470      interval.setValueNumberInfo(0, std::make_pair(~0U, 0U));
471
472      // Add the new live interval which replaces the range for the input copy.
473      LiveRange LR(DefIndex, RedefIndex, ValNo);
474      DEBUG(std::cerr << " replace range with " << LR);
475      interval.addRange(LR);
476
477      // If this redefinition is dead, we need to add a dummy unit live
478      // range covering the def slot.
479      if (lv_->RegisterDefIsDead(mi, interval.reg))
480        interval.addRange(LiveRange(RedefIndex, RedefIndex+1, 0));
481
482      DEBUG(std::cerr << "RESULT: "; interval.print(std::cerr, mri_));
483
484    } else {
485      // Otherwise, this must be because of phi elimination.  If this is the
486      // first redefinition of the vreg that we have seen, go back and change
487      // the live range in the PHI block to be a different value number.
488      if (interval.containsOneValue()) {
489        assert(vi.Kills.size() == 1 &&
490               "PHI elimination vreg should have one kill, the PHI itself!");
491
492        // Remove the old range that we now know has an incorrect number.
493        MachineInstr *Killer = vi.Kills[0];
494        unsigned Start = getInstructionIndex(Killer->getParent()->begin());
495        unsigned End = getUseIndex(getInstructionIndex(Killer))+1;
496        DEBUG(std::cerr << "Removing [" << Start << "," << End << "] from: ";
497              interval.print(std::cerr, mri_); std::cerr << "\n");
498        interval.removeRange(Start, End);
499        DEBUG(std::cerr << "RESULT: "; interval.print(std::cerr, mri_));
500
501        // Replace the interval with one of a NEW value number.  Note that this
502        // value number isn't actually defined by an instruction, weird huh? :)
503        LiveRange LR(Start, End, interval.getNextValue(~0U, 0));
504        DEBUG(std::cerr << " replace range with " << LR);
505        interval.addRange(LR);
506        DEBUG(std::cerr << "RESULT: "; interval.print(std::cerr, mri_));
507      }
508
509      // In the case of PHI elimination, each variable definition is only
510      // live until the end of the block.  We've already taken care of the
511      // rest of the live range.
512      unsigned defIndex = getDefIndex(getInstructionIndex(mi));
513
514      unsigned ValNum;
515      unsigned SrcReg, DstReg;
516      if (!tii_->isMoveInstr(*mi, SrcReg, DstReg))
517        ValNum = interval.getNextValue(~0U, 0);
518      else
519        ValNum = interval.getNextValue(defIndex, SrcReg);
520
521      LiveRange LR(defIndex,
522                   getInstructionIndex(&mbb->back()) + InstrSlots::NUM, ValNum);
523      interval.addRange(LR);
524      DEBUG(std::cerr << " +" << LR);
525    }
526  }
527
528  DEBUG(std::cerr << '\n');
529}
530
531void LiveIntervals::handlePhysicalRegisterDef(MachineBasicBlock *MBB,
532                                              MachineBasicBlock::iterator mi,
533                                              LiveInterval &interval,
534                                              unsigned SrcReg) {
535  // A physical register cannot be live across basic block, so its
536  // lifetime must end somewhere in its defining basic block.
537  DEBUG(std::cerr << "\t\tregister: "; printRegName(interval.reg));
538  typedef LiveVariables::killed_iterator KillIter;
539
540  unsigned baseIndex = getInstructionIndex(mi);
541  unsigned start = getDefIndex(baseIndex);
542  unsigned end = start;
543
544  // If it is not used after definition, it is considered dead at
545  // the instruction defining it. Hence its interval is:
546  // [defSlot(def), defSlot(def)+1)
547  if (lv_->RegisterDefIsDead(mi, interval.reg)) {
548    DEBUG(std::cerr << " dead");
549    end = getDefIndex(start) + 1;
550    goto exit;
551  }
552
553  // If it is not dead on definition, it must be killed by a
554  // subsequent instruction. Hence its interval is:
555  // [defSlot(def), useSlot(kill)+1)
556  while (++mi != MBB->end()) {
557    baseIndex += InstrSlots::NUM;
558    if (lv_->KillsRegister(mi, interval.reg)) {
559      DEBUG(std::cerr << " killed");
560      end = getUseIndex(baseIndex) + 1;
561      goto exit;
562    }
563  }
564
565  // The only case we should have a dead physreg here without a killing or
566  // instruction where we know it's dead is if it is live-in to the function
567  // and never used.
568  assert(!SrcReg && "physreg was not killed in defining block!");
569  end = getDefIndex(start) + 1;  // It's dead.
570
571exit:
572  assert(start < end && "did not find end of interval?");
573
574  LiveRange LR(start, end, interval.getNextValue(SrcReg != 0 ? start : ~0U,
575                                                 SrcReg));
576  interval.addRange(LR);
577  DEBUG(std::cerr << " +" << LR << '\n');
578}
579
580void LiveIntervals::handleRegisterDef(MachineBasicBlock *MBB,
581                                      MachineBasicBlock::iterator MI,
582                                      unsigned reg) {
583  if (MRegisterInfo::isVirtualRegister(reg))
584    handleVirtualRegisterDef(MBB, MI, getOrCreateInterval(reg));
585  else if (allocatableRegs_[reg]) {
586    unsigned SrcReg, DstReg;
587    if (!tii_->isMoveInstr(*MI, SrcReg, DstReg))
588      SrcReg = 0;
589    handlePhysicalRegisterDef(MBB, MI, getOrCreateInterval(reg), SrcReg);
590    for (const unsigned* AS = mri_->getAliasSet(reg); *AS; ++AS)
591      handlePhysicalRegisterDef(MBB, MI, getOrCreateInterval(*AS), 0);
592  }
593}
594
595/// computeIntervals - computes the live intervals for virtual
596/// registers. for some ordering of the machine instructions [1,N] a
597/// live interval is an interval [i, j) where 1 <= i <= j < N for
598/// which a variable is live
599void LiveIntervals::computeIntervals() {
600  DEBUG(std::cerr << "********** COMPUTING LIVE INTERVALS **********\n");
601  DEBUG(std::cerr << "********** Function: "
602        << ((Value*)mf_->getFunction())->getName() << '\n');
603  bool IgnoreFirstInstr = mf_->livein_begin() != mf_->livein_end();
604
605  for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();
606       I != E; ++I) {
607    MachineBasicBlock* mbb = I;
608    DEBUG(std::cerr << ((Value*)mbb->getBasicBlock())->getName() << ":\n");
609
610    MachineBasicBlock::iterator mi = mbb->begin(), miEnd = mbb->end();
611    if (IgnoreFirstInstr) { ++mi; IgnoreFirstInstr = false; }
612    for (; mi != miEnd; ++mi) {
613      const TargetInstrDescriptor& tid =
614        tm_->getInstrInfo()->get(mi->getOpcode());
615      DEBUG(std::cerr << getInstructionIndex(mi) << "\t" << *mi);
616
617      // handle implicit defs
618      if (tid.ImplicitDefs) {
619        for (const unsigned* id = tid.ImplicitDefs; *id; ++id)
620          handleRegisterDef(mbb, mi, *id);
621      }
622
623      // handle explicit defs
624      for (int i = mi->getNumOperands() - 1; i >= 0; --i) {
625        MachineOperand& mop = mi->getOperand(i);
626        // handle register defs - build intervals
627        if (mop.isRegister() && mop.getReg() && mop.isDef())
628          handleRegisterDef(mbb, mi, mop.getReg());
629      }
630    }
631  }
632}
633
634/// AdjustCopiesBackFrom - We found a non-trivially-coallescable copy with IntA
635/// being the source and IntB being the dest, thus this defines a value number
636/// in IntB.  If the source value number (in IntA) is defined by a copy from B,
637/// see if we can merge these two pieces of B into a single value number,
638/// eliminating a copy.  For example:
639///
640///  A3 = B0
641///    ...
642///  B1 = A3      <- this copy
643///
644/// In this case, B0 can be extended to where the B1 copy lives, allowing the B1
645/// value number to be replaced with B0 (which simplifies the B liveinterval).
646///
647/// This returns true if an interval was modified.
648///
649bool LiveIntervals::AdjustCopiesBackFrom(LiveInterval &IntA, LiveInterval &IntB,
650                                         MachineInstr *CopyMI) {
651  unsigned CopyIdx = getDefIndex(getInstructionIndex(CopyMI));
652
653  // BValNo is a value number in B that is defined by a copy from A.  'B3' in
654  // the example above.
655  LiveInterval::iterator BLR = IntB.FindLiveRangeContaining(CopyIdx);
656  unsigned BValNo = BLR->ValId;
657
658  // Get the location that B is defined at.  Two options: either this value has
659  // an unknown definition point or it is defined at CopyIdx.  If unknown, we
660  // can't process it.
661  unsigned BValNoDefIdx = IntB.getInstForValNum(BValNo);
662  if (BValNoDefIdx == ~0U) return false;
663  assert(BValNoDefIdx == CopyIdx &&
664         "Copy doesn't define the value?");
665
666  // AValNo is the value number in A that defines the copy, A0 in the example.
667  LiveInterval::iterator AValLR = IntA.FindLiveRangeContaining(CopyIdx-1);
668  unsigned AValNo = AValLR->ValId;
669
670  // If AValNo is defined as a copy from IntB, we can potentially process this.
671
672  // Get the instruction that defines this value number.
673  unsigned SrcReg = IntA.getSrcRegForValNum(AValNo);
674  if (!SrcReg) return false;  // Not defined by a copy.
675
676  // If the value number is not defined by a copy instruction, ignore it.
677
678  // If the source register comes from an interval other than IntB, we can't
679  // handle this.
680  if (rep(SrcReg) != IntB.reg) return false;
681
682  // Get the LiveRange in IntB that this value number starts with.
683  unsigned AValNoInstIdx = IntA.getInstForValNum(AValNo);
684  LiveInterval::iterator ValLR = IntB.FindLiveRangeContaining(AValNoInstIdx-1);
685
686  // Make sure that the end of the live range is inside the same block as
687  // CopyMI.
688  MachineInstr *ValLREndInst = getInstructionFromIndex(ValLR->end-1);
689  if (!ValLREndInst ||
690      ValLREndInst->getParent() != CopyMI->getParent()) return false;
691
692  // Okay, we now know that ValLR ends in the same block that the CopyMI
693  // live-range starts.  If there are no intervening live ranges between them in
694  // IntB, we can merge them.
695  if (ValLR+1 != BLR) return false;
696
697  DEBUG(std::cerr << "\nExtending: "; IntB.print(std::cerr, mri_));
698
699  // We are about to delete CopyMI, so need to remove it as the 'instruction
700  // that defines this value #'.
701  IntB.setValueNumberInfo(BValNo, std::make_pair(~0U, 0));
702
703  // Okay, we can merge them.  We need to insert a new liverange:
704  // [ValLR.end, BLR.begin) of either value number, then we merge the
705  // two value numbers.
706  unsigned FillerStart = ValLR->end, FillerEnd = BLR->start;
707  IntB.addRange(LiveRange(FillerStart, FillerEnd, BValNo));
708
709  // If the IntB live range is assigned to a physical register, and if that
710  // physreg has aliases,
711  if (MRegisterInfo::isPhysicalRegister(IntB.reg)) {
712    for (const unsigned *AS = mri_->getAliasSet(IntB.reg); *AS; ++AS) {
713      LiveInterval &AliasLI = getInterval(*AS);
714      AliasLI.addRange(LiveRange(FillerStart, FillerEnd,
715                                 AliasLI.getNextValue(~0U, 0)));
716    }
717  }
718
719  // Okay, merge "B1" into the same value number as "B0".
720  if (BValNo != ValLR->ValId)
721    IntB.MergeValueNumberInto(BValNo, ValLR->ValId);
722  DEBUG(std::cerr << "   result = "; IntB.print(std::cerr, mri_);
723        std::cerr << "\n");
724
725  // Finally, delete the copy instruction.
726  RemoveMachineInstrFromMaps(CopyMI);
727  CopyMI->eraseFromParent();
728  ++numPeep;
729  return true;
730}
731
732
733/// JoinCopy - Attempt to join intervals corresponding to SrcReg/DstReg,
734/// which are the src/dst of the copy instruction CopyMI.  This returns true
735/// if the copy was successfully coallesced away, or if it is never possible
736/// to coallesce these this copy, due to register constraints.  It returns
737/// false if it is not currently possible to coallesce this interval, but
738/// it may be possible if other things get coallesced.
739bool LiveIntervals::JoinCopy(MachineInstr *CopyMI,
740                             unsigned SrcReg, unsigned DstReg) {
741
742
743  DEBUG(std::cerr << getInstructionIndex(CopyMI) << '\t' << *CopyMI);
744
745  // Get representative registers.
746  SrcReg = rep(SrcReg);
747  DstReg = rep(DstReg);
748
749  // If they are already joined we continue.
750  if (SrcReg == DstReg) {
751    DEBUG(std::cerr << "\tCopy already coallesced.\n");
752    return true;  // Not coallescable.
753  }
754
755  // If they are both physical registers, we cannot join them.
756  if (MRegisterInfo::isPhysicalRegister(SrcReg) &&
757      MRegisterInfo::isPhysicalRegister(DstReg)) {
758    DEBUG(std::cerr << "\tCan not coallesce physregs.\n");
759    return true;  // Not coallescable.
760  }
761
762  // We only join virtual registers with allocatable physical registers.
763  if (MRegisterInfo::isPhysicalRegister(SrcReg) && !allocatableRegs_[SrcReg]){
764    DEBUG(std::cerr << "\tSrc reg is unallocatable physreg.\n");
765    return true;  // Not coallescable.
766  }
767  if (MRegisterInfo::isPhysicalRegister(DstReg) && !allocatableRegs_[DstReg]){
768    DEBUG(std::cerr << "\tDst reg is unallocatable physreg.\n");
769    return true;  // Not coallescable.
770  }
771
772  // If they are not of the same register class, we cannot join them.
773  if (differingRegisterClasses(SrcReg, DstReg)) {
774    DEBUG(std::cerr << "\tSrc/Dest are different register classes.\n");
775    return true;  // Not coallescable.
776  }
777
778  LiveInterval &SrcInt = getInterval(SrcReg);
779  LiveInterval &DestInt = getInterval(DstReg);
780  assert(SrcInt.reg == SrcReg && DestInt.reg == DstReg &&
781         "Register mapping is horribly broken!");
782
783  DEBUG(std::cerr << "\t\tInspecting "; SrcInt.print(std::cerr, mri_);
784        std::cerr << " and "; DestInt.print(std::cerr, mri_);
785        std::cerr << ": ");
786
787  // Okay, attempt to join these two intervals.  On failure, this returns false.
788  // Otherwise, if one of the intervals being joined is a physreg, this method
789  // always canonicalizes DestInt to be it.  The output "SrcInt" will not have
790  // been modified, so we can use this information below to update aliases.
791  if (!JoinIntervals(DestInt, SrcInt)) {
792    // Coallescing failed.
793
794    // If we can eliminate the copy without merging the live ranges, do so now.
795    if (AdjustCopiesBackFrom(SrcInt, DestInt, CopyMI))
796      return true;
797
798    // Otherwise, we are unable to join the intervals.
799    DEBUG(std::cerr << "Interference!\n");
800    return false;
801  }
802
803  bool Swapped = SrcReg == DestInt.reg;
804  if (Swapped)
805    std::swap(SrcReg, DstReg);
806  assert(MRegisterInfo::isVirtualRegister(SrcReg) &&
807         "LiveInterval::join didn't work right!");
808
809  // If we're about to merge live ranges into a physical register live range,
810  // we have to update any aliased register's live ranges to indicate that they
811  // have clobbered values for this range.
812  if (MRegisterInfo::isPhysicalRegister(DstReg)) {
813    for (const unsigned *AS = mri_->getAliasSet(DstReg); *AS; ++AS)
814      getInterval(*AS).MergeInClobberRanges(SrcInt);
815  }
816
817  DEBUG(std::cerr << "\n\t\tJoined.  Result = "; DestInt.print(std::cerr, mri_);
818        std::cerr << "\n");
819
820  // If the intervals were swapped by Join, swap them back so that the register
821  // mapping (in the r2i map) is correct.
822  if (Swapped) SrcInt.swap(DestInt);
823  r2iMap_.erase(SrcReg);
824  r2rMap_[SrcReg] = DstReg;
825
826  // Finally, delete the copy instruction.
827  RemoveMachineInstrFromMaps(CopyMI);
828  CopyMI->eraseFromParent();
829  ++numPeep;
830  ++numJoins;
831  return true;
832}
833
834/// ComputeUltimateVN - Assuming we are going to join two live intervals,
835/// compute what the resultant value numbers for each value in the input two
836/// ranges will be.  This is complicated by copies between the two which can
837/// and will commonly cause multiple value numbers to be merged into one.
838///
839/// VN is the value number that we're trying to resolve.  InstDefiningValue
840/// keeps track of the new InstDefiningValue assignment for the result
841/// LiveInterval.  ThisFromOther/OtherFromThis are sets that keep track of
842/// whether a value in this or other is a copy from the opposite set.
843/// ThisValNoAssignments/OtherValNoAssignments keep track of value #'s that have
844/// already been assigned.
845///
846/// ThisFromOther[x] - If x is defined as a copy from the other interval, this
847/// contains the value number the copy is from.
848///
849static unsigned ComputeUltimateVN(unsigned VN,
850                                  SmallVector<std::pair<unsigned,
851                                                unsigned>, 16> &ValueNumberInfo,
852                                  SmallVector<int, 16> &ThisFromOther,
853                                  SmallVector<int, 16> &OtherFromThis,
854                                  SmallVector<int, 16> &ThisValNoAssignments,
855                                  SmallVector<int, 16> &OtherValNoAssignments,
856                                  LiveInterval &ThisLI, LiveInterval &OtherLI) {
857  // If the VN has already been computed, just return it.
858  if (ThisValNoAssignments[VN] >= 0)
859    return ThisValNoAssignments[VN];
860  assert(ThisValNoAssignments[VN] != -2 && "FIXME: Cyclic case, handle it!");
861
862  // If this val is not a copy from the other val, then it must be a new value
863  // number in the destination.
864  int OtherValNo = ThisFromOther[VN];
865  if (OtherValNo == -1) {
866    ValueNumberInfo.push_back(ThisLI.getValNumInfo(VN));
867    return ThisValNoAssignments[VN] = ValueNumberInfo.size()-1;
868  }
869
870  // Otherwise, this *is* a copy from the RHS.  Mark this value number as
871  // currently being computed, then ask what the ultimate value # of the other
872  // value is.
873  ThisValNoAssignments[VN] = -2;
874  unsigned UltimateVN =
875    ComputeUltimateVN(OtherValNo, ValueNumberInfo,
876                      OtherFromThis, ThisFromOther,
877                      OtherValNoAssignments, ThisValNoAssignments,
878                      OtherLI, ThisLI);
879  return ThisValNoAssignments[VN] = UltimateVN;
880}
881
882
883/// JoinIntervals - Attempt to join these two intervals.  On failure, this
884/// returns false.  Otherwise, if one of the intervals being joined is a
885/// physreg, this method always canonicalizes LHS to be it.  The output
886/// "RHS" will not have been modified, so we can use this information
887/// below to update aliases.
888bool LiveIntervals::JoinIntervals(LiveInterval &LHS, LiveInterval &RHS) {
889  // Loop over the value numbers of the LHS, seeing if any are defined from the
890  // RHS.
891  SmallVector<int, 16> LHSValsDefinedFromRHS;
892  LHSValsDefinedFromRHS.resize(LHS.getNumValNums(), -1);
893  for (unsigned VN = 0, e = LHS.getNumValNums(); VN != e; ++VN) {
894    unsigned ValSrcReg = LHS.getSrcRegForValNum(VN);
895    if (ValSrcReg == 0)  // Src not defined by a copy?
896      continue;
897
898    // DstReg is known to be a register in the LHS interval.  If the src is from
899    // the RHS interval, we can use its value #.
900    if (rep(ValSrcReg) != RHS.reg)
901      continue;
902
903    // Figure out the value # from the RHS.
904    unsigned ValInst = LHS.getInstForValNum(VN);
905    LHSValsDefinedFromRHS[VN] = RHS.getLiveRangeContaining(ValInst-1)->ValId;
906  }
907
908  // Loop over the value numbers of the RHS, seeing if any are defined from the
909  // LHS.
910  SmallVector<int, 16> RHSValsDefinedFromLHS;
911  RHSValsDefinedFromLHS.resize(RHS.getNumValNums(), -1);
912  for (unsigned VN = 0, e = RHS.getNumValNums(); VN != e; ++VN) {
913    unsigned ValSrcReg = RHS.getSrcRegForValNum(VN);
914    if (ValSrcReg == 0)  // Src not defined by a copy?
915      continue;
916
917    // DstReg is known to be a register in the RHS interval.  If the src is from
918    // the LHS interval, we can use its value #.
919    if (rep(ValSrcReg) != LHS.reg)
920      continue;
921
922    // Figure out the value # from the LHS.
923    unsigned ValInst = RHS.getInstForValNum(VN);
924    RHSValsDefinedFromLHS[VN] = LHS.getLiveRangeContaining(ValInst-1)->ValId;
925  }
926
927  // Now that we know the value mapping, compute the final value assignment,
928  // assuming that the live ranges can be coallesced.
929  SmallVector<int, 16> LHSValNoAssignments;
930  SmallVector<int, 16> RHSValNoAssignments;
931  SmallVector<std::pair<unsigned,unsigned>, 16> ValueNumberInfo;
932  LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
933  RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
934
935  // Compute ultimate value numbers for the LHS and RHS values.
936  for (unsigned VN = 0, e = LHS.getNumValNums(); VN != e; ++VN) {
937    if (LHS.getInstForValNum(VN) == ~2U) continue;
938    ComputeUltimateVN(VN, ValueNumberInfo,
939                      LHSValsDefinedFromRHS, RHSValsDefinedFromLHS,
940                      LHSValNoAssignments, RHSValNoAssignments, LHS, RHS);
941  }
942  for (unsigned VN = 0, e = RHS.getNumValNums(); VN != e; ++VN) {
943    if (RHS.getInstForValNum(VN) == ~2U) continue;
944    ComputeUltimateVN(VN, ValueNumberInfo,
945                      RHSValsDefinedFromLHS, LHSValsDefinedFromRHS,
946                      RHSValNoAssignments, LHSValNoAssignments, RHS, LHS);
947  }
948
949  // Armed with the mappings of LHS/RHS values to ultimate values, walk the
950  // interval lists to see if these intervals are coallescable.
951  LiveInterval::const_iterator I = LHS.begin();
952  LiveInterval::const_iterator IE = LHS.end();
953  LiveInterval::const_iterator J = RHS.begin();
954  LiveInterval::const_iterator JE = RHS.end();
955
956  // Skip ahead until the first place of potential sharing.
957  if (I->start < J->start) {
958    I = std::upper_bound(I, IE, J->start);
959    if (I != LHS.begin()) --I;
960  } else if (J->start < I->start) {
961    J = std::upper_bound(J, JE, I->start);
962    if (J != RHS.begin()) --J;
963  }
964
965  while (1) {
966    // Determine if these two live ranges overlap.
967    bool Overlaps;
968    if (I->start < J->start) {
969      Overlaps = I->end > J->start;
970    } else {
971      Overlaps = J->end > I->start;
972    }
973
974    // If so, check value # info to determine if they are really different.
975    if (Overlaps) {
976      // If the live range overlap will map to the same value number in the
977      // result liverange, we can still coallesce them.  If not, we can't.
978      if (LHSValNoAssignments[I->ValId] != RHSValNoAssignments[J->ValId])
979        return false;
980    }
981
982    if (I->end < J->end) {
983      ++I;
984      if (I == IE) break;
985    } else {
986      ++J;
987      if (J == JE) break;
988    }
989  }
990
991  // If we get here, we know that we can coallesce the live ranges.  Ask the
992  // intervals to coallesce themselves now.
993  LHS.join(RHS, &LHSValNoAssignments[0], &RHSValNoAssignments[0],
994           ValueNumberInfo);
995  return true;
996}
997
998
999namespace {
1000  // DepthMBBCompare - Comparison predicate that sort first based on the loop
1001  // depth of the basic block (the unsigned), and then on the MBB number.
1002  struct DepthMBBCompare {
1003    typedef std::pair<unsigned, MachineBasicBlock*> DepthMBBPair;
1004    bool operator()(const DepthMBBPair &LHS, const DepthMBBPair &RHS) const {
1005      if (LHS.first > RHS.first) return true;   // Deeper loops first
1006      return LHS.first == RHS.first &&
1007        LHS.second->getNumber() < RHS.second->getNumber();
1008    }
1009  };
1010}
1011
1012
1013void LiveIntervals::CopyCoallesceInMBB(MachineBasicBlock *MBB,
1014                                       std::vector<CopyRec> &TryAgain) {
1015  DEBUG(std::cerr << ((Value*)MBB->getBasicBlock())->getName() << ":\n");
1016
1017  for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end();
1018       MII != E;) {
1019    MachineInstr *Inst = MII++;
1020
1021    // If this isn't a copy, we can't join intervals.
1022    unsigned SrcReg, DstReg;
1023    if (!tii_->isMoveInstr(*Inst, SrcReg, DstReg)) continue;
1024
1025    if (!JoinCopy(Inst, SrcReg, DstReg))
1026      TryAgain.push_back(getCopyRec(Inst, SrcReg, DstReg));
1027  }
1028}
1029
1030
1031void LiveIntervals::joinIntervals() {
1032  DEBUG(std::cerr << "********** JOINING INTERVALS ***********\n");
1033
1034  std::vector<CopyRec> TryAgainList;
1035
1036  const LoopInfo &LI = getAnalysis<LoopInfo>();
1037  if (LI.begin() == LI.end()) {
1038    // If there are no loops in the function, join intervals in function order.
1039    for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();
1040         I != E; ++I)
1041      CopyCoallesceInMBB(I, TryAgainList);
1042  } else {
1043    // Otherwise, join intervals in inner loops before other intervals.
1044    // Unfortunately we can't just iterate over loop hierarchy here because
1045    // there may be more MBB's than BB's.  Collect MBB's for sorting.
1046    std::vector<std::pair<unsigned, MachineBasicBlock*> > MBBs;
1047    for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();
1048         I != E; ++I)
1049      MBBs.push_back(std::make_pair(LI.getLoopDepth(I->getBasicBlock()), I));
1050
1051    // Sort by loop depth.
1052    std::sort(MBBs.begin(), MBBs.end(), DepthMBBCompare());
1053
1054    // Finally, join intervals in loop nest order.
1055    for (unsigned i = 0, e = MBBs.size(); i != e; ++i)
1056      CopyCoallesceInMBB(MBBs[i].second, TryAgainList);
1057  }
1058
1059  // Joining intervals can allow other intervals to be joined.  Iteratively join
1060  // until we make no progress.
1061  bool ProgressMade = true;
1062  while (ProgressMade) {
1063    ProgressMade = false;
1064
1065    for (unsigned i = 0, e = TryAgainList.size(); i != e; ++i) {
1066      CopyRec &TheCopy = TryAgainList[i];
1067      if (TheCopy.MI &&
1068          JoinCopy(TheCopy.MI, TheCopy.SrcReg, TheCopy.DstReg)) {
1069        TheCopy.MI = 0;   // Mark this one as done.
1070        ProgressMade = true;
1071      }
1072    }
1073  }
1074
1075  DEBUG(std::cerr << "*** Register mapping ***\n");
1076  DEBUG(for (int i = 0, e = r2rMap_.size(); i != e; ++i)
1077          if (r2rMap_[i]) {
1078            std::cerr << "  reg " << i << " -> ";
1079            printRegName(r2rMap_[i]);
1080            std::cerr << "\n";
1081          });
1082}
1083
1084/// Return true if the two specified registers belong to different register
1085/// classes.  The registers may be either phys or virt regs.
1086bool LiveIntervals::differingRegisterClasses(unsigned RegA,
1087                                             unsigned RegB) const {
1088
1089  // Get the register classes for the first reg.
1090  if (MRegisterInfo::isPhysicalRegister(RegA)) {
1091    assert(MRegisterInfo::isVirtualRegister(RegB) &&
1092           "Shouldn't consider two physregs!");
1093    return !mf_->getSSARegMap()->getRegClass(RegB)->contains(RegA);
1094  }
1095
1096  // Compare against the regclass for the second reg.
1097  const TargetRegisterClass *RegClass = mf_->getSSARegMap()->getRegClass(RegA);
1098  if (MRegisterInfo::isVirtualRegister(RegB))
1099    return RegClass != mf_->getSSARegMap()->getRegClass(RegB);
1100  else
1101    return !RegClass->contains(RegB);
1102}
1103
1104LiveInterval LiveIntervals::createInterval(unsigned reg) {
1105  float Weight = MRegisterInfo::isPhysicalRegister(reg) ?
1106                       (float)HUGE_VAL : 0.0F;
1107  return LiveInterval(reg, Weight);
1108}
1109