Watch out for cases like this:
[oota-llvm.git] / lib / CodeGen / LiveIntervalAnalysis.cpp
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 using namespace llvm;
38
39 STATISTIC(numIntervals, "Number of original intervals");
40 STATISTIC(numIntervalsAfter, "Number of intervals after coalescing");
41 STATISTIC(numJoins    , "Number of interval joins performed");
42 STATISTIC(numPeep     , "Number of identity moves eliminated after coalescing");
43 STATISTIC(numFolded   , "Number of loads/stores folded into instructions");
44
45 namespace {
46   RegisterPass<LiveIntervals> X("liveintervals", "Live Interval Analysis");
47
48   static cl::opt<bool>
49   EnableJoining("join-liveintervals",
50                 cl::desc("Coallesce copies (default=true)"),
51                 cl::init(true));
52 }
53
54 void LiveIntervals::getAnalysisUsage(AnalysisUsage &AU) const {
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   mi2iMap_.clear();
65   i2miMap_.clear();
66   r2iMap_.clear();
67   r2rMap_.clear();
68   JoinedLIs.clear();
69 }
70
71
72 static bool isZeroLengthInterval(LiveInterval *li) {
73   for (LiveInterval::Ranges::const_iterator
74          i = li->ranges.begin(), e = li->ranges.end(); i != e; ++i)
75     if (i->end - i->start > LiveIntervals::InstrSlots::NUM)
76       return false;
77   return true;
78 }
79
80
81 /// runOnMachineFunction - Register allocate the whole function
82 ///
83 bool LiveIntervals::runOnMachineFunction(MachineFunction &fn) {
84   mf_ = &fn;
85   tm_ = &fn.getTarget();
86   mri_ = tm_->getRegisterInfo();
87   tii_ = tm_->getInstrInfo();
88   lv_ = &getAnalysis<LiveVariables>();
89   allocatableRegs_ = mri_->getAllocatableSet(fn);
90   r2rMap_.grow(mf_->getSSARegMap()->getLastVirtReg());
91
92   // Number MachineInstrs and MachineBasicBlocks.
93   // Initialize MBB indexes to a sentinal.
94   MBB2IdxMap.resize(mf_->getNumBlockIDs(), ~0U);
95   
96   unsigned MIIndex = 0;
97   for (MachineFunction::iterator MBB = mf_->begin(), E = mf_->end();
98        MBB != E; ++MBB) {
99     // Set the MBB2IdxMap entry for this MBB.
100     MBB2IdxMap[MBB->getNumber()] = MIIndex;
101
102     for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
103          I != E; ++I) {
104       bool inserted = mi2iMap_.insert(std::make_pair(I, MIIndex)).second;
105       assert(inserted && "multiple MachineInstr -> index mappings");
106       i2miMap_.push_back(I);
107       MIIndex += InstrSlots::NUM;
108     }
109   }
110
111   computeIntervals();
112
113   numIntervals += getNumIntervals();
114
115   DOUT << "********** INTERVALS **********\n";
116   for (iterator I = begin(), E = end(); I != E; ++I) {
117     I->second.print(DOUT, mri_);
118     DOUT << "\n";
119   }
120
121   // Join (coallesce) intervals if requested.
122   if (EnableJoining) joinIntervals();
123
124   numIntervalsAfter += getNumIntervals();
125   
126
127   // perform a final pass over the instructions and compute spill
128   // weights, coalesce virtual registers and remove identity moves.
129   const LoopInfo &loopInfo = getAnalysis<LoopInfo>();
130
131   for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
132        mbbi != mbbe; ++mbbi) {
133     MachineBasicBlock* mbb = mbbi;
134     unsigned loopDepth = loopInfo.getLoopDepth(mbb->getBasicBlock());
135
136     for (MachineBasicBlock::iterator mii = mbb->begin(), mie = mbb->end();
137          mii != mie; ) {
138       // if the move will be an identity move delete it
139       unsigned srcReg, dstReg, RegRep;
140       if (tii_->isMoveInstr(*mii, srcReg, dstReg) &&
141           (RegRep = rep(srcReg)) == rep(dstReg)) {
142         // remove from def list
143         LiveInterval &RegInt = getOrCreateInterval(RegRep);
144         MachineOperand *MO = mii->findRegisterDefOperand(dstReg);
145         // If def of this move instruction is dead, remove its live range from
146         // the dstination register's live interval.
147         if (MO->isDead()) {
148           unsigned MoveIdx = getDefIndex(getInstructionIndex(mii));
149           LiveInterval::iterator MLR = RegInt.FindLiveRangeContaining(MoveIdx);
150           RegInt.removeRange(MLR->start, MoveIdx+1);
151           if (RegInt.empty())
152             removeInterval(RegRep);
153         }
154         RemoveMachineInstrFromMaps(mii);
155         mii = mbbi->erase(mii);
156         ++numPeep;
157       }
158       else {
159         for (unsigned i = 0, e = mii->getNumOperands(); i != e; ++i) {
160           const MachineOperand &mop = mii->getOperand(i);
161           if (mop.isRegister() && mop.getReg() &&
162               MRegisterInfo::isVirtualRegister(mop.getReg())) {
163             // replace register with representative register
164             unsigned reg = rep(mop.getReg());
165             mii->getOperand(i).setReg(reg);
166
167             LiveInterval &RegInt = getInterval(reg);
168             RegInt.weight +=
169               (mop.isUse() + mop.isDef()) * pow(10.0F, (int)loopDepth);
170           }
171         }
172         ++mii;
173       }
174     }
175   }
176
177   for (iterator I = begin(), E = end(); I != E; ++I) {
178     LiveInterval &LI = I->second;
179     if (MRegisterInfo::isVirtualRegister(LI.reg)) {
180       // If the live interval length is essentially zero, i.e. in every live
181       // range the use follows def immediately, it doesn't make sense to spill
182       // it and hope it will be easier to allocate for this li.
183       if (isZeroLengthInterval(&LI))
184         LI.weight = HUGE_VALF;
185       
186       // Divide the weight of the interval by its size.  This encourages 
187       // spilling of intervals that are large and have few uses, and
188       // discourages spilling of small intervals with many uses.
189       unsigned Size = 0;
190       for (LiveInterval::iterator II = LI.begin(), E = LI.end(); II != E;++II)
191         Size += II->end - II->start;
192       
193       LI.weight /= Size;
194     }
195   }
196
197   DEBUG(dump());
198   return true;
199 }
200
201 /// print - Implement the dump method.
202 void LiveIntervals::print(std::ostream &O, const Module* ) const {
203   O << "********** INTERVALS **********\n";
204   for (const_iterator I = begin(), E = end(); I != E; ++I) {
205     I->second.print(DOUT, mri_);
206     DOUT << "\n";
207   }
208
209   O << "********** MACHINEINSTRS **********\n";
210   for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
211        mbbi != mbbe; ++mbbi) {
212     O << ((Value*)mbbi->getBasicBlock())->getName() << ":\n";
213     for (MachineBasicBlock::iterator mii = mbbi->begin(),
214            mie = mbbi->end(); mii != mie; ++mii) {
215       O << getInstructionIndex(mii) << '\t' << *mii;
216     }
217   }
218 }
219
220 /// CreateNewLiveInterval - Create a new live interval with the given live
221 /// ranges. The new live interval will have an infinite spill weight.
222 LiveInterval&
223 LiveIntervals::CreateNewLiveInterval(const LiveInterval *LI,
224                                      const std::vector<LiveRange> &LRs) {
225   const TargetRegisterClass *RC = mf_->getSSARegMap()->getRegClass(LI->reg);
226
227   // Create a new virtual register for the spill interval.
228   unsigned NewVReg = mf_->getSSARegMap()->createVirtualRegister(RC);
229
230   // Replace the old virtual registers in the machine operands with the shiny
231   // new one.
232   for (std::vector<LiveRange>::const_iterator
233          I = LRs.begin(), E = LRs.end(); I != E; ++I) {
234     unsigned Index = getBaseIndex(I->start);
235     unsigned End = getBaseIndex(I->end - 1) + InstrSlots::NUM;
236
237     for (; Index != End; Index += InstrSlots::NUM) {
238       // Skip deleted instructions
239       while (Index != End && !getInstructionFromIndex(Index))
240         Index += InstrSlots::NUM;
241
242       if (Index == End) break;
243
244       MachineInstr *MI = getInstructionFromIndex(Index);
245
246       for (unsigned J = 0, e = MI->getNumOperands(); J != e; ++J) {
247         MachineOperand &MOp = MI->getOperand(J);
248         if (MOp.isRegister() && rep(MOp.getReg()) == LI->reg)
249           MOp.setReg(NewVReg);
250       }
251     }
252   }
253
254   LiveInterval &NewLI = getOrCreateInterval(NewVReg);
255
256   // The spill weight is now infinity as it cannot be spilled again
257   NewLI.weight = float(HUGE_VAL);
258
259   for (std::vector<LiveRange>::const_iterator
260          I = LRs.begin(), E = LRs.end(); I != E; ++I) {
261     DOUT << "  Adding live range " << *I << " to new interval\n";
262     NewLI.addRange(*I);
263   }
264             
265   DOUT << "Created new live interval " << NewLI << "\n";
266   return NewLI;
267 }
268
269 std::vector<LiveInterval*> LiveIntervals::
270 addIntervalsForSpills(const LiveInterval &li, VirtRegMap &vrm, int slot) {
271   // since this is called after the analysis is done we don't know if
272   // LiveVariables is available
273   lv_ = getAnalysisToUpdate<LiveVariables>();
274
275   std::vector<LiveInterval*> added;
276
277   assert(li.weight != HUGE_VALF &&
278          "attempt to spill already spilled interval!");
279
280   DOUT << "\t\t\t\tadding intervals for spills for interval: ";
281   li.print(DOUT, mri_);
282   DOUT << '\n';
283
284   const TargetRegisterClass* rc = mf_->getSSARegMap()->getRegClass(li.reg);
285
286   for (LiveInterval::Ranges::const_iterator
287          i = li.ranges.begin(), e = li.ranges.end(); i != e; ++i) {
288     unsigned index = getBaseIndex(i->start);
289     unsigned end = getBaseIndex(i->end-1) + InstrSlots::NUM;
290     for (; index != end; index += InstrSlots::NUM) {
291       // skip deleted instructions
292       while (index != end && !getInstructionFromIndex(index))
293         index += InstrSlots::NUM;
294       if (index == end) break;
295
296       MachineInstr *MI = getInstructionFromIndex(index);
297
298     RestartInstruction:
299       for (unsigned i = 0; i != MI->getNumOperands(); ++i) {
300         MachineOperand& mop = MI->getOperand(i);
301         if (mop.isRegister() && mop.getReg() == li.reg) {
302           if (MachineInstr *fmi = mri_->foldMemoryOperand(MI, i, slot)) {
303             // Attempt to fold the memory reference into the instruction.  If we
304             // can do this, we don't need to insert spill code.
305             if (lv_)
306               lv_->instructionChanged(MI, fmi);
307             MachineBasicBlock &MBB = *MI->getParent();
308             vrm.virtFolded(li.reg, MI, i, fmi);
309             mi2iMap_.erase(MI);
310             i2miMap_[index/InstrSlots::NUM] = fmi;
311             mi2iMap_[fmi] = index;
312             MI = MBB.insert(MBB.erase(MI), fmi);
313             ++numFolded;
314             // Folding the load/store can completely change the instruction in
315             // unpredictable ways, rescan it from the beginning.
316             goto RestartInstruction;
317           } else {
318             // Create a new virtual register for the spill interval.
319             unsigned NewVReg = mf_->getSSARegMap()->createVirtualRegister(rc);
320             
321             // Scan all of the operands of this instruction rewriting operands
322             // to use NewVReg instead of li.reg as appropriate.  We do this for
323             // two reasons:
324             //
325             //   1. If the instr reads the same spilled vreg multiple times, we
326             //      want to reuse the NewVReg.
327             //   2. If the instr is a two-addr instruction, we are required to
328             //      keep the src/dst regs pinned.
329             //
330             // Keep track of whether we replace a use and/or def so that we can
331             // create the spill interval with the appropriate range. 
332             mop.setReg(NewVReg);
333             
334             bool HasUse = mop.isUse();
335             bool HasDef = mop.isDef();
336             for (unsigned j = i+1, e = MI->getNumOperands(); j != e; ++j) {
337               if (MI->getOperand(j).isReg() &&
338                   MI->getOperand(j).getReg() == li.reg) {
339                 MI->getOperand(j).setReg(NewVReg);
340                 HasUse |= MI->getOperand(j).isUse();
341                 HasDef |= MI->getOperand(j).isDef();
342               }
343             }
344
345             // create a new register for this spill
346             vrm.grow();
347             vrm.assignVirt2StackSlot(NewVReg, slot);
348             LiveInterval &nI = getOrCreateInterval(NewVReg);
349             assert(nI.empty());
350
351             // the spill weight is now infinity as it
352             // cannot be spilled again
353             nI.weight = HUGE_VALF;
354
355             if (HasUse) {
356               LiveRange LR(getLoadIndex(index), getUseIndex(index),
357                            nI.getNextValue(~0U, 0));
358               DOUT << " +" << LR;
359               nI.addRange(LR);
360             }
361             if (HasDef) {
362               LiveRange LR(getDefIndex(index), getStoreIndex(index),
363                            nI.getNextValue(~0U, 0));
364               DOUT << " +" << LR;
365               nI.addRange(LR);
366             }
367             
368             added.push_back(&nI);
369
370             // update live variables if it is available
371             if (lv_)
372               lv_->addVirtualRegisterKilled(NewVReg, MI);
373             
374             DOUT << "\t\t\t\tadded new interval: ";
375             nI.print(DOUT, mri_);
376             DOUT << '\n';
377           }
378         }
379       }
380     }
381   }
382
383   return added;
384 }
385
386 void LiveIntervals::printRegName(unsigned reg) const {
387   if (MRegisterInfo::isPhysicalRegister(reg))
388     cerr << mri_->getName(reg);
389   else
390     cerr << "%reg" << reg;
391 }
392
393 /// isReDefinedByTwoAddr - Returns true if the Reg re-definition is due to
394 /// two addr elimination.
395 static bool isReDefinedByTwoAddr(MachineInstr *MI, unsigned Reg,
396                                 const TargetInstrInfo *TII) {
397   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
398     MachineOperand &MO1 = MI->getOperand(i);
399     if (MO1.isRegister() && MO1.isDef() && MO1.getReg() == Reg) {
400       for (unsigned j = i+1; j < e; ++j) {
401         MachineOperand &MO2 = MI->getOperand(j);
402         if (MO2.isRegister() && MO2.isUse() && MO2.getReg() == Reg &&
403             MI->getInstrDescriptor()->
404             getOperandConstraint(j, TOI::TIED_TO) == (int)i)
405           return true;
406       }
407     }
408   }
409   return false;
410 }
411
412 void LiveIntervals::handleVirtualRegisterDef(MachineBasicBlock *mbb,
413                                              MachineBasicBlock::iterator mi,
414                                              unsigned MIIdx,
415                                              LiveInterval &interval) {
416   DOUT << "\t\tregister: "; DEBUG(printRegName(interval.reg));
417   LiveVariables::VarInfo& vi = lv_->getVarInfo(interval.reg);
418
419   // Virtual registers may be defined multiple times (due to phi
420   // elimination and 2-addr elimination).  Much of what we do only has to be
421   // done once for the vreg.  We use an empty interval to detect the first
422   // time we see a vreg.
423   if (interval.empty()) {
424     // Get the Idx of the defining instructions.
425     unsigned defIndex = getDefIndex(MIIdx);
426
427     unsigned ValNum;
428     unsigned SrcReg, DstReg;
429     if (!tii_->isMoveInstr(*mi, SrcReg, DstReg))
430       ValNum = interval.getNextValue(~0U, 0);
431     else
432       ValNum = interval.getNextValue(defIndex, SrcReg);
433     
434     assert(ValNum == 0 && "First value in interval is not 0?");
435     ValNum = 0;  // Clue in the optimizer.
436
437     // Loop over all of the blocks that the vreg is defined in.  There are
438     // two cases we have to handle here.  The most common case is a vreg
439     // whose lifetime is contained within a basic block.  In this case there
440     // will be a single kill, in MBB, which comes after the definition.
441     if (vi.Kills.size() == 1 && vi.Kills[0]->getParent() == mbb) {
442       // FIXME: what about dead vars?
443       unsigned killIdx;
444       if (vi.Kills[0] != mi)
445         killIdx = getUseIndex(getInstructionIndex(vi.Kills[0]))+1;
446       else
447         killIdx = defIndex+1;
448
449       // If the kill happens after the definition, we have an intra-block
450       // live range.
451       if (killIdx > defIndex) {
452         assert(vi.AliveBlocks.none() &&
453                "Shouldn't be alive across any blocks!");
454         LiveRange LR(defIndex, killIdx, ValNum);
455         interval.addRange(LR);
456         DOUT << " +" << LR << "\n";
457         return;
458       }
459     }
460
461     // The other case we handle is when a virtual register lives to the end
462     // of the defining block, potentially live across some blocks, then is
463     // live into some number of blocks, but gets killed.  Start by adding a
464     // range that goes from this definition to the end of the defining block.
465     LiveRange NewLR(defIndex,
466                     getInstructionIndex(&mbb->back()) + InstrSlots::NUM,
467                     ValNum);
468     DOUT << " +" << NewLR;
469     interval.addRange(NewLR);
470
471     // Iterate over all of the blocks that the variable is completely
472     // live in, adding [insrtIndex(begin), instrIndex(end)+4) to the
473     // live interval.
474     for (unsigned i = 0, e = vi.AliveBlocks.size(); i != e; ++i) {
475       if (vi.AliveBlocks[i]) {
476         MachineBasicBlock *MBB = mf_->getBlockNumbered(i);
477         if (!MBB->empty()) {
478           LiveRange LR(getMBBStartIdx(i),
479                        getInstructionIndex(&MBB->back()) + InstrSlots::NUM,
480                        ValNum);
481           interval.addRange(LR);
482           DOUT << " +" << LR;
483         }
484       }
485     }
486
487     // Finally, this virtual register is live from the start of any killing
488     // block to the 'use' slot of the killing instruction.
489     for (unsigned i = 0, e = vi.Kills.size(); i != e; ++i) {
490       MachineInstr *Kill = vi.Kills[i];
491       LiveRange LR(getMBBStartIdx(Kill->getParent()),
492                    getUseIndex(getInstructionIndex(Kill))+1,
493                    ValNum);
494       interval.addRange(LR);
495       DOUT << " +" << LR;
496     }
497
498   } else {
499     // If this is the second time we see a virtual register definition, it
500     // must be due to phi elimination or two addr elimination.  If this is
501     // the result of two address elimination, then the vreg is one of the
502     // def-and-use register operand.
503     if (isReDefinedByTwoAddr(mi, interval.reg, tii_)) {
504       // If this is a two-address definition, then we have already processed
505       // the live range.  The only problem is that we didn't realize there
506       // are actually two values in the live interval.  Because of this we
507       // need to take the LiveRegion that defines this register and split it
508       // into two values.
509       unsigned DefIndex = getDefIndex(getInstructionIndex(vi.DefInst));
510       unsigned RedefIndex = getDefIndex(MIIdx);
511
512       // Delete the initial value, which should be short and continuous,
513       // because the 2-addr copy must be in the same MBB as the redef.
514       interval.removeRange(DefIndex, RedefIndex);
515
516       // Two-address vregs should always only be redefined once.  This means
517       // that at this point, there should be exactly one value number in it.
518       assert(interval.containsOneValue() && "Unexpected 2-addr liveint!");
519
520       // The new value number (#1) is defined by the instruction we claimed
521       // defined value #0.
522       unsigned ValNo = interval.getNextValue(0, 0);
523       interval.setValueNumberInfo(1, interval.getValNumInfo(0));
524       
525       // Value#0 is now defined by the 2-addr instruction.
526       interval.setValueNumberInfo(0, std::make_pair(~0U, 0U));
527       
528       // Add the new live interval which replaces the range for the input copy.
529       LiveRange LR(DefIndex, RedefIndex, ValNo);
530       DOUT << " replace range with " << LR;
531       interval.addRange(LR);
532
533       // If this redefinition is dead, we need to add a dummy unit live
534       // range covering the def slot.
535       if (lv_->RegisterDefIsDead(mi, interval.reg))
536         interval.addRange(LiveRange(RedefIndex, RedefIndex+1, 0));
537
538       DOUT << "RESULT: ";
539       interval.print(DOUT, mri_);
540
541     } else {
542       // Otherwise, this must be because of phi elimination.  If this is the
543       // first redefinition of the vreg that we have seen, go back and change
544       // the live range in the PHI block to be a different value number.
545       if (interval.containsOneValue()) {
546         assert(vi.Kills.size() == 1 &&
547                "PHI elimination vreg should have one kill, the PHI itself!");
548
549         // Remove the old range that we now know has an incorrect number.
550         MachineInstr *Killer = vi.Kills[0];
551         unsigned Start = getMBBStartIdx(Killer->getParent());
552         unsigned End = getUseIndex(getInstructionIndex(Killer))+1;
553         DOUT << "Removing [" << Start << "," << End << "] from: ";
554         interval.print(DOUT, mri_); DOUT << "\n";
555         interval.removeRange(Start, End);
556         DOUT << "RESULT: "; interval.print(DOUT, mri_);
557
558         // Replace the interval with one of a NEW value number.  Note that this
559         // value number isn't actually defined by an instruction, weird huh? :)
560         LiveRange LR(Start, End, interval.getNextValue(~0U, 0));
561         DOUT << " replace range with " << LR;
562         interval.addRange(LR);
563         DOUT << "RESULT: "; interval.print(DOUT, mri_);
564       }
565
566       // In the case of PHI elimination, each variable definition is only
567       // live until the end of the block.  We've already taken care of the
568       // rest of the live range.
569       unsigned defIndex = getDefIndex(MIIdx);
570       
571       unsigned ValNum;
572       unsigned SrcReg, DstReg;
573       if (!tii_->isMoveInstr(*mi, SrcReg, DstReg))
574         ValNum = interval.getNextValue(~0U, 0);
575       else
576         ValNum = interval.getNextValue(defIndex, SrcReg);
577       
578       LiveRange LR(defIndex,
579                    getInstructionIndex(&mbb->back()) + InstrSlots::NUM, ValNum);
580       interval.addRange(LR);
581       DOUT << " +" << LR;
582     }
583   }
584
585   DOUT << '\n';
586 }
587
588 void LiveIntervals::handlePhysicalRegisterDef(MachineBasicBlock *MBB,
589                                               MachineBasicBlock::iterator mi,
590                                               unsigned MIIdx,
591                                               LiveInterval &interval,
592                                               unsigned SrcReg) {
593   // A physical register cannot be live across basic block, so its
594   // lifetime must end somewhere in its defining basic block.
595   DOUT << "\t\tregister: "; DEBUG(printRegName(interval.reg));
596
597   unsigned baseIndex = MIIdx;
598   unsigned start = getDefIndex(baseIndex);
599   unsigned end = start;
600
601   // If it is not used after definition, it is considered dead at
602   // the instruction defining it. Hence its interval is:
603   // [defSlot(def), defSlot(def)+1)
604   if (lv_->RegisterDefIsDead(mi, interval.reg)) {
605     DOUT << " dead";
606     end = getDefIndex(start) + 1;
607     goto exit;
608   }
609
610   // If it is not dead on definition, it must be killed by a
611   // subsequent instruction. Hence its interval is:
612   // [defSlot(def), useSlot(kill)+1)
613   while (++mi != MBB->end()) {
614     baseIndex += InstrSlots::NUM;
615     if (lv_->KillsRegister(mi, interval.reg)) {
616       DOUT << " killed";
617       end = getUseIndex(baseIndex) + 1;
618       goto exit;
619     } else if (lv_->ModifiesRegister(mi, interval.reg)) {
620       // Another instruction redefines the register before it is ever read.
621       // Then the register is essentially dead at the instruction that defines
622       // it. Hence its interval is:
623       // [defSlot(def), defSlot(def)+1)
624       DOUT << " dead";
625       end = getDefIndex(start) + 1;
626       goto exit;
627     }
628   }
629   
630   // The only case we should have a dead physreg here without a killing or
631   // instruction where we know it's dead is if it is live-in to the function
632   // and never used.
633   assert(!SrcReg && "physreg was not killed in defining block!");
634   end = getDefIndex(start) + 1;  // It's dead.
635
636 exit:
637   assert(start < end && "did not find end of interval?");
638
639   LiveRange LR(start, end, interval.getNextValue(SrcReg != 0 ? start : ~0U,
640                                                  SrcReg));
641   interval.addRange(LR);
642   DOUT << " +" << LR << '\n';
643 }
644
645 void LiveIntervals::handleRegisterDef(MachineBasicBlock *MBB,
646                                       MachineBasicBlock::iterator MI,
647                                       unsigned MIIdx,
648                                       unsigned reg) {
649   if (MRegisterInfo::isVirtualRegister(reg))
650     handleVirtualRegisterDef(MBB, MI, MIIdx, getOrCreateInterval(reg));
651   else if (allocatableRegs_[reg]) {
652     unsigned SrcReg, DstReg;
653     if (!tii_->isMoveInstr(*MI, SrcReg, DstReg))
654       SrcReg = 0;
655     handlePhysicalRegisterDef(MBB, MI, MIIdx, getOrCreateInterval(reg), SrcReg);
656     for (const unsigned* AS = mri_->getAliasSet(reg); *AS; ++AS)
657       handlePhysicalRegisterDef(MBB, MI, MIIdx, getOrCreateInterval(*AS), 0);
658   }
659 }
660
661 void LiveIntervals::handleLiveInRegister(MachineBasicBlock *MBB,
662                                          unsigned MIIdx,
663                                          LiveInterval &interval) {
664   DOUT << "\t\tlivein register: "; DEBUG(printRegName(interval.reg));
665
666   // Look for kills, if it reaches a def before it's killed, then it shouldn't
667   // be considered a livein.
668   MachineBasicBlock::iterator mi = MBB->begin();
669   unsigned baseIndex = MIIdx;
670   unsigned start = baseIndex;
671   unsigned end = start;
672   while (mi != MBB->end()) {
673     if (lv_->KillsRegister(mi, interval.reg)) {
674       DOUT << " killed";
675       end = getUseIndex(baseIndex) + 1;
676       goto exit;
677     } else if (lv_->ModifiesRegister(mi, interval.reg)) {
678       // Another instruction redefines the register before it is ever read.
679       // Then the register is essentially dead at the instruction that defines
680       // it. Hence its interval is:
681       // [defSlot(def), defSlot(def)+1)
682       DOUT << " dead";
683       end = getDefIndex(start) + 1;
684       goto exit;
685     }
686
687     baseIndex += InstrSlots::NUM;
688     ++mi;
689   }
690
691 exit:
692   assert(start < end && "did not find end of interval?");
693
694   LiveRange LR(start, end, interval.getNextValue(~0U, 0));
695   DOUT << " +" << LR << '\n';
696   interval.addRange(LR);
697 }
698
699 /// computeIntervals - computes the live intervals for virtual
700 /// registers. for some ordering of the machine instructions [1,N] a
701 /// live interval is an interval [i, j) where 1 <= i <= j < N for
702 /// which a variable is live
703 void LiveIntervals::computeIntervals() {
704   DOUT << "********** COMPUTING LIVE INTERVALS **********\n"
705        << "********** Function: "
706        << ((Value*)mf_->getFunction())->getName() << '\n';
707   // Track the index of the current machine instr.
708   unsigned MIIndex = 0;
709   for (MachineFunction::iterator MBBI = mf_->begin(), E = mf_->end();
710        MBBI != E; ++MBBI) {
711     MachineBasicBlock *MBB = MBBI;
712     DOUT << ((Value*)MBB->getBasicBlock())->getName() << ":\n";
713
714     MachineBasicBlock::iterator MI = MBB->begin(), miEnd = MBB->end();
715
716     if (MBB->livein_begin() != MBB->livein_end()) {
717       // Create intervals for live-ins to this BB first.
718       for (MachineBasicBlock::const_livein_iterator LI = MBB->livein_begin(),
719              LE = MBB->livein_end(); LI != LE; ++LI) {
720         handleLiveInRegister(MBB, MIIndex, getOrCreateInterval(*LI));
721         for (const unsigned* AS = mri_->getAliasSet(*LI); *AS; ++AS)
722           handleLiveInRegister(MBB, MIIndex, getOrCreateInterval(*AS));
723       }
724     }
725     
726     for (; MI != miEnd; ++MI) {
727       DOUT << MIIndex << "\t" << *MI;
728
729       // Handle defs.
730       for (int i = MI->getNumOperands() - 1; i >= 0; --i) {
731         MachineOperand &MO = MI->getOperand(i);
732         // handle register defs - build intervals
733         if (MO.isRegister() && MO.getReg() && MO.isDef())
734           handleRegisterDef(MBB, MI, MIIndex, MO.getReg());
735       }
736       
737       MIIndex += InstrSlots::NUM;
738     }
739   }
740 }
741
742 /// AdjustCopiesBackFrom - We found a non-trivially-coallescable copy with IntA
743 /// being the source and IntB being the dest, thus this defines a value number
744 /// in IntB.  If the source value number (in IntA) is defined by a copy from B,
745 /// see if we can merge these two pieces of B into a single value number,
746 /// eliminating a copy.  For example:
747 ///
748 ///  A3 = B0
749 ///    ...
750 ///  B1 = A3      <- this copy
751 ///
752 /// In this case, B0 can be extended to where the B1 copy lives, allowing the B1
753 /// value number to be replaced with B0 (which simplifies the B liveinterval).
754 ///
755 /// This returns true if an interval was modified.
756 ///
757 bool LiveIntervals::AdjustCopiesBackFrom(LiveInterval &IntA, LiveInterval &IntB,
758                                          MachineInstr *CopyMI) {
759   unsigned CopyIdx = getDefIndex(getInstructionIndex(CopyMI));
760
761   // BValNo is a value number in B that is defined by a copy from A.  'B3' in
762   // the example above.
763   LiveInterval::iterator BLR = IntB.FindLiveRangeContaining(CopyIdx);
764   unsigned BValNo = BLR->ValId;
765   
766   // Get the location that B is defined at.  Two options: either this value has
767   // an unknown definition point or it is defined at CopyIdx.  If unknown, we 
768   // can't process it.
769   unsigned BValNoDefIdx = IntB.getInstForValNum(BValNo);
770   if (BValNoDefIdx == ~0U) return false;
771   assert(BValNoDefIdx == CopyIdx &&
772          "Copy doesn't define the value?");
773   
774   // AValNo is the value number in A that defines the copy, A0 in the example.
775   LiveInterval::iterator AValLR = IntA.FindLiveRangeContaining(CopyIdx-1);
776   unsigned AValNo = AValLR->ValId;
777   
778   // If AValNo is defined as a copy from IntB, we can potentially process this.
779   
780   // Get the instruction that defines this value number.
781   unsigned SrcReg = IntA.getSrcRegForValNum(AValNo);
782   if (!SrcReg) return false;  // Not defined by a copy.
783     
784   // If the value number is not defined by a copy instruction, ignore it.
785     
786   // If the source register comes from an interval other than IntB, we can't
787   // handle this.
788   if (rep(SrcReg) != IntB.reg) return false;
789   
790   // Get the LiveRange in IntB that this value number starts with.
791   unsigned AValNoInstIdx = IntA.getInstForValNum(AValNo);
792   LiveInterval::iterator ValLR = IntB.FindLiveRangeContaining(AValNoInstIdx-1);
793   
794   // Make sure that the end of the live range is inside the same block as
795   // CopyMI.
796   MachineInstr *ValLREndInst = getInstructionFromIndex(ValLR->end-1);
797   if (!ValLREndInst || 
798       ValLREndInst->getParent() != CopyMI->getParent()) return false;
799
800   // Okay, we now know that ValLR ends in the same block that the CopyMI
801   // live-range starts.  If there are no intervening live ranges between them in
802   // IntB, we can merge them.
803   if (ValLR+1 != BLR) return false;
804   
805   DOUT << "\nExtending: "; IntB.print(DOUT, mri_);
806   
807   // We are about to delete CopyMI, so need to remove it as the 'instruction
808   // that defines this value #'.
809   IntB.setValueNumberInfo(BValNo, std::make_pair(~0U, 0));
810   
811   // Okay, we can merge them.  We need to insert a new liverange:
812   // [ValLR.end, BLR.begin) of either value number, then we merge the
813   // two value numbers.
814   unsigned FillerStart = ValLR->end, FillerEnd = BLR->start;
815   IntB.addRange(LiveRange(FillerStart, FillerEnd, BValNo));
816
817   // If the IntB live range is assigned to a physical register, and if that
818   // physreg has aliases, 
819   if (MRegisterInfo::isPhysicalRegister(IntB.reg)) {
820     for (const unsigned *AS = mri_->getAliasSet(IntB.reg); *AS; ++AS) {
821       LiveInterval &AliasLI = getInterval(*AS);
822       AliasLI.addRange(LiveRange(FillerStart, FillerEnd,
823                                  AliasLI.getNextValue(~0U, 0)));
824     }
825   }
826
827   // Okay, merge "B1" into the same value number as "B0".
828   if (BValNo != ValLR->ValId)
829     IntB.MergeValueNumberInto(BValNo, ValLR->ValId);
830   DOUT << "   result = "; IntB.print(DOUT, mri_);
831   DOUT << "\n";
832
833   // If the source instruction was killing the source register before the
834   // merge, unset the isKill marker given the live range has been extended.
835   MachineOperand *MOK = ValLREndInst->findRegisterUseOperand(IntB.reg, true);
836   if (MOK)
837     MOK->unsetIsKill();
838   
839   // Finally, delete the copy instruction.
840   RemoveMachineInstrFromMaps(CopyMI);
841   CopyMI->eraseFromParent();
842   ++numPeep;
843   return true;
844 }
845
846 /// JoinCopy - Attempt to join intervals corresponding to SrcReg/DstReg,
847 /// which are the src/dst of the copy instruction CopyMI.  This returns true
848 /// if the copy was successfully coallesced away, or if it is never possible
849 /// to coallesce these this copy, due to register constraints.  It returns
850 /// false if it is not currently possible to coallesce this interval, but
851 /// it may be possible if other things get coallesced.
852 bool LiveIntervals::JoinCopy(MachineInstr *CopyMI,
853                              unsigned SrcReg, unsigned DstReg) {
854   DOUT << getInstructionIndex(CopyMI) << '\t' << *CopyMI;
855
856   // Get representative registers.
857   unsigned repSrcReg = rep(SrcReg);
858   unsigned repDstReg = rep(DstReg);
859   
860   // If they are already joined we continue.
861   if (repSrcReg == repDstReg) {
862     DOUT << "\tCopy already coallesced.\n";
863     return true;  // Not coallescable.
864   }
865   
866   // If they are both physical registers, we cannot join them.
867   if (MRegisterInfo::isPhysicalRegister(repSrcReg) &&
868       MRegisterInfo::isPhysicalRegister(repDstReg)) {
869     DOUT << "\tCan not coallesce physregs.\n";
870     return true;  // Not coallescable.
871   }
872   
873   // We only join virtual registers with allocatable physical registers.
874   if (MRegisterInfo::isPhysicalRegister(repSrcReg) &&
875       !allocatableRegs_[repSrcReg]) {
876     DOUT << "\tSrc reg is unallocatable physreg.\n";
877     return true;  // Not coallescable.
878   }
879   if (MRegisterInfo::isPhysicalRegister(repDstReg) &&
880       !allocatableRegs_[repDstReg]) {
881     DOUT << "\tDst reg is unallocatable physreg.\n";
882     return true;  // Not coallescable.
883   }
884   
885   // If they are not of the same register class, we cannot join them.
886   if (differingRegisterClasses(repSrcReg, repDstReg)) {
887     DOUT << "\tSrc/Dest are different register classes.\n";
888     return true;  // Not coallescable.
889   }
890   
891   LiveInterval &SrcInt = getInterval(repSrcReg);
892   LiveInterval &DestInt = getInterval(repDstReg);
893   assert(SrcInt.reg == repSrcReg && DestInt.reg == repDstReg &&
894          "Register mapping is horribly broken!");
895   
896   DOUT << "\t\tInspecting "; SrcInt.print(DOUT, mri_);
897   DOUT << " and "; DestInt.print(DOUT, mri_);
898   DOUT << ": ";
899
900   // Check if it is necessary to propagate "isDead" property before intervals
901   // are joined.
902   MachineOperand *mopd = CopyMI->findRegisterDefOperand(DstReg);
903   bool isDead = mopd->isDead();
904   bool isShorten = false;
905   unsigned SrcStart = 0;
906   unsigned SrcEnd = 0;
907   if (isDead) {
908     unsigned CopyIdx = getInstructionIndex(CopyMI);
909     LiveInterval::iterator SrcLR =
910       SrcInt.FindLiveRangeContaining(getUseIndex(CopyIdx));
911     SrcStart = SrcLR->start;
912     SrcEnd   = SrcLR->end;
913     // The instruction which defines the src is only truly dead if there are
914     // no intermediate uses and there isn't a use beyond the copy.
915     // FIXME: find the last use, mark is kill and shorten the live range.
916     if (SrcEnd > getDefIndex(CopyIdx))
917       isDead = false;
918     else {
919       MachineOperand *MOU;
920       MachineInstr *LastUse =
921         lastRegisterUse(repSrcReg, SrcStart, CopyIdx, MOU);
922       if (LastUse) {
923         // Shorten the liveinterval to the end of last use.
924         MOU->setIsKill();
925         isDead = false;
926         isShorten = true;
927         SrcEnd = getUseIndex(getInstructionIndex(LastUse));
928       }
929     }
930     if (isDead)
931       isShorten = true;
932   }
933
934   // Okay, attempt to join these two intervals.  On failure, this returns false.
935   // Otherwise, if one of the intervals being joined is a physreg, this method
936   // always canonicalizes DestInt to be it.  The output "SrcInt" will not have
937   // been modified, so we can use this information below to update aliases.
938   if (JoinIntervals(DestInt, SrcInt)) {
939     if (isDead) {
940       // Result of the copy is dead. Propagate this property.
941       if (SrcStart == 0) {
942         assert(MRegisterInfo::isPhysicalRegister(repSrcReg) &&
943                "Live-in must be a physical register!");
944         // Live-in to the function but dead. Remove it from entry live-in set.
945         // JoinIntervals may end up swapping the two intervals.
946         mf_->begin()->removeLiveIn(repSrcReg);
947       } else {
948         MachineInstr *SrcMI = getInstructionFromIndex(SrcStart);
949         if (SrcMI) {
950           MachineOperand *mops = SrcMI->findRegisterDefOperand(SrcReg);
951           if (mops)
952             // FIXME: mops == NULL means SrcMI defines a subregister?
953             mops->setIsDead();
954         }
955       }
956     }
957
958     if (isShorten) {
959       // Shorten the live interval.
960       LiveInterval &LiveInInt = (repSrcReg == DestInt.reg) ? DestInt : SrcInt;
961       LiveInInt.removeRange(SrcStart, SrcEnd);
962     }
963   } else {
964     // Coallescing failed.
965     
966     // If we can eliminate the copy without merging the live ranges, do so now.
967     if (AdjustCopiesBackFrom(SrcInt, DestInt, CopyMI))
968       return true;
969
970     // Otherwise, we are unable to join the intervals.
971     DOUT << "Interference!\n";
972     return false;
973   }
974
975   bool Swapped = repSrcReg == DestInt.reg;
976   if (Swapped)
977     std::swap(repSrcReg, repDstReg);
978   assert(MRegisterInfo::isVirtualRegister(repSrcReg) &&
979          "LiveInterval::join didn't work right!");
980                                
981   // If we're about to merge live ranges into a physical register live range,
982   // we have to update any aliased register's live ranges to indicate that they
983   // have clobbered values for this range.
984   if (MRegisterInfo::isPhysicalRegister(repDstReg)) {
985     for (const unsigned *AS = mri_->getAliasSet(repDstReg); *AS; ++AS)
986       getInterval(*AS).MergeInClobberRanges(SrcInt);
987   }
988
989   DOUT << "\n\t\tJoined.  Result = "; DestInt.print(DOUT, mri_);
990   DOUT << "\n";
991
992   // Remember these liveintervals have been joined.
993   JoinedLIs.set(repSrcReg - MRegisterInfo::FirstVirtualRegister);
994   if (MRegisterInfo::isVirtualRegister(repDstReg))
995     JoinedLIs.set(repDstReg - MRegisterInfo::FirstVirtualRegister);
996
997   // If the intervals were swapped by Join, swap them back so that the register
998   // mapping (in the r2i map) is correct.
999   if (Swapped) SrcInt.swap(DestInt);
1000   removeInterval(repSrcReg);
1001   r2rMap_[repSrcReg] = repDstReg;
1002
1003   // Finally, delete the copy instruction.
1004   RemoveMachineInstrFromMaps(CopyMI);
1005   CopyMI->eraseFromParent();
1006   ++numPeep;
1007   ++numJoins;
1008   return true;
1009 }
1010
1011 /// ComputeUltimateVN - Assuming we are going to join two live intervals,
1012 /// compute what the resultant value numbers for each value in the input two
1013 /// ranges will be.  This is complicated by copies between the two which can
1014 /// and will commonly cause multiple value numbers to be merged into one.
1015 ///
1016 /// VN is the value number that we're trying to resolve.  InstDefiningValue
1017 /// keeps track of the new InstDefiningValue assignment for the result
1018 /// LiveInterval.  ThisFromOther/OtherFromThis are sets that keep track of
1019 /// whether a value in this or other is a copy from the opposite set.
1020 /// ThisValNoAssignments/OtherValNoAssignments keep track of value #'s that have
1021 /// already been assigned.
1022 ///
1023 /// ThisFromOther[x] - If x is defined as a copy from the other interval, this
1024 /// contains the value number the copy is from.
1025 ///
1026 static unsigned ComputeUltimateVN(unsigned VN,
1027                                   SmallVector<std::pair<unsigned,
1028                                                 unsigned>, 16> &ValueNumberInfo,
1029                                   SmallVector<int, 16> &ThisFromOther,
1030                                   SmallVector<int, 16> &OtherFromThis,
1031                                   SmallVector<int, 16> &ThisValNoAssignments,
1032                                   SmallVector<int, 16> &OtherValNoAssignments,
1033                                   LiveInterval &ThisLI, LiveInterval &OtherLI) {
1034   // If the VN has already been computed, just return it.
1035   if (ThisValNoAssignments[VN] >= 0)
1036     return ThisValNoAssignments[VN];
1037 //  assert(ThisValNoAssignments[VN] != -2 && "Cyclic case?");
1038   
1039   // If this val is not a copy from the other val, then it must be a new value
1040   // number in the destination.
1041   int OtherValNo = ThisFromOther[VN];
1042   if (OtherValNo == -1) {
1043     ValueNumberInfo.push_back(ThisLI.getValNumInfo(VN));
1044     return ThisValNoAssignments[VN] = ValueNumberInfo.size()-1;
1045   }
1046
1047   // Otherwise, this *is* a copy from the RHS.  If the other side has already
1048   // been computed, return it.
1049   if (OtherValNoAssignments[OtherValNo] >= 0)
1050     return ThisValNoAssignments[VN] = OtherValNoAssignments[OtherValNo];
1051   
1052   // Mark this value number as currently being computed, then ask what the
1053   // ultimate value # of the other value is.
1054   ThisValNoAssignments[VN] = -2;
1055   unsigned UltimateVN =
1056     ComputeUltimateVN(OtherValNo, ValueNumberInfo,
1057                       OtherFromThis, ThisFromOther,
1058                       OtherValNoAssignments, ThisValNoAssignments,
1059                       OtherLI, ThisLI);
1060   return ThisValNoAssignments[VN] = UltimateVN;
1061 }
1062
1063 static bool InVector(unsigned Val, const SmallVector<unsigned, 8> &V) {
1064   return std::find(V.begin(), V.end(), Val) != V.end();
1065 }
1066
1067 /// SimpleJoin - Attempt to joint the specified interval into this one. The
1068 /// caller of this method must guarantee that the RHS only contains a single
1069 /// value number and that the RHS is not defined by a copy from this
1070 /// interval.  This returns false if the intervals are not joinable, or it
1071 /// joins them and returns true.
1072 bool LiveIntervals::SimpleJoin(LiveInterval &LHS, LiveInterval &RHS) {
1073   assert(RHS.containsOneValue());
1074   
1075   // Some number (potentially more than one) value numbers in the current
1076   // interval may be defined as copies from the RHS.  Scan the overlapping
1077   // portions of the LHS and RHS, keeping track of this and looking for
1078   // overlapping live ranges that are NOT defined as copies.  If these exist, we
1079   // cannot coallesce.
1080   
1081   LiveInterval::iterator LHSIt = LHS.begin(), LHSEnd = LHS.end();
1082   LiveInterval::iterator RHSIt = RHS.begin(), RHSEnd = RHS.end();
1083   
1084   if (LHSIt->start < RHSIt->start) {
1085     LHSIt = std::upper_bound(LHSIt, LHSEnd, RHSIt->start);
1086     if (LHSIt != LHS.begin()) --LHSIt;
1087   } else if (RHSIt->start < LHSIt->start) {
1088     RHSIt = std::upper_bound(RHSIt, RHSEnd, LHSIt->start);
1089     if (RHSIt != RHS.begin()) --RHSIt;
1090   }
1091   
1092   SmallVector<unsigned, 8> EliminatedLHSVals;
1093   
1094   while (1) {
1095     // Determine if these live intervals overlap.
1096     bool Overlaps = false;
1097     if (LHSIt->start <= RHSIt->start)
1098       Overlaps = LHSIt->end > RHSIt->start;
1099     else
1100       Overlaps = RHSIt->end > LHSIt->start;
1101     
1102     // If the live intervals overlap, there are two interesting cases: if the
1103     // LHS interval is defined by a copy from the RHS, it's ok and we record
1104     // that the LHS value # is the same as the RHS.  If it's not, then we cannot
1105     // coallesce these live ranges and we bail out.
1106     if (Overlaps) {
1107       // If we haven't already recorded that this value # is safe, check it.
1108       if (!InVector(LHSIt->ValId, EliminatedLHSVals)) {
1109         // Copy from the RHS?
1110         unsigned SrcReg = LHS.getSrcRegForValNum(LHSIt->ValId);
1111         if (rep(SrcReg) != RHS.reg)
1112           return false;    // Nope, bail out.
1113         
1114         EliminatedLHSVals.push_back(LHSIt->ValId);
1115       }
1116       
1117       // We know this entire LHS live range is okay, so skip it now.
1118       if (++LHSIt == LHSEnd) break;
1119       continue;
1120     }
1121     
1122     if (LHSIt->end < RHSIt->end) {
1123       if (++LHSIt == LHSEnd) break;
1124     } else {
1125       // One interesting case to check here.  It's possible that we have
1126       // something like "X3 = Y" which defines a new value number in the LHS,
1127       // and is the last use of this liverange of the RHS.  In this case, we
1128       // want to notice this copy (so that it gets coallesced away) even though
1129       // the live ranges don't actually overlap.
1130       if (LHSIt->start == RHSIt->end) {
1131         if (InVector(LHSIt->ValId, EliminatedLHSVals)) {
1132           // We already know that this value number is going to be merged in
1133           // if coallescing succeeds.  Just skip the liverange.
1134           if (++LHSIt == LHSEnd) break;
1135         } else {
1136           // Otherwise, if this is a copy from the RHS, mark it as being merged
1137           // in.
1138           if (rep(LHS.getSrcRegForValNum(LHSIt->ValId)) == RHS.reg) {
1139             EliminatedLHSVals.push_back(LHSIt->ValId);
1140
1141             // We know this entire LHS live range is okay, so skip it now.
1142             if (++LHSIt == LHSEnd) break;
1143           }
1144         }
1145       }
1146       
1147       if (++RHSIt == RHSEnd) break;
1148     }
1149   }
1150   
1151   // If we got here, we know that the coallescing will be successful and that
1152   // the value numbers in EliminatedLHSVals will all be merged together.  Since
1153   // the most common case is that EliminatedLHSVals has a single number, we
1154   // optimize for it: if there is more than one value, we merge them all into
1155   // the lowest numbered one, then handle the interval as if we were merging
1156   // with one value number.
1157   unsigned LHSValNo;
1158   if (EliminatedLHSVals.size() > 1) {
1159     // Loop through all the equal value numbers merging them into the smallest
1160     // one.
1161     unsigned Smallest = EliminatedLHSVals[0];
1162     for (unsigned i = 1, e = EliminatedLHSVals.size(); i != e; ++i) {
1163       if (EliminatedLHSVals[i] < Smallest) {
1164         // Merge the current notion of the smallest into the smaller one.
1165         LHS.MergeValueNumberInto(Smallest, EliminatedLHSVals[i]);
1166         Smallest = EliminatedLHSVals[i];
1167       } else {
1168         // Merge into the smallest.
1169         LHS.MergeValueNumberInto(EliminatedLHSVals[i], Smallest);
1170       }
1171     }
1172     LHSValNo = Smallest;
1173   } else {
1174     assert(!EliminatedLHSVals.empty() && "No copies from the RHS?");
1175     LHSValNo = EliminatedLHSVals[0];
1176   }
1177   
1178   // Okay, now that there is a single LHS value number that we're merging the
1179   // RHS into, update the value number info for the LHS to indicate that the
1180   // value number is defined where the RHS value number was.
1181   LHS.setValueNumberInfo(LHSValNo, RHS.getValNumInfo(0));
1182   
1183   // Okay, the final step is to loop over the RHS live intervals, adding them to
1184   // the LHS.
1185   LHS.MergeRangesInAsValue(RHS, LHSValNo);
1186   LHS.weight += RHS.weight;
1187   
1188   return true;
1189 }
1190
1191 /// JoinIntervals - Attempt to join these two intervals.  On failure, this
1192 /// returns false.  Otherwise, if one of the intervals being joined is a
1193 /// physreg, this method always canonicalizes LHS to be it.  The output
1194 /// "RHS" will not have been modified, so we can use this information
1195 /// below to update aliases.
1196 bool LiveIntervals::JoinIntervals(LiveInterval &LHS, LiveInterval &RHS) {
1197   // Compute the final value assignment, assuming that the live ranges can be
1198   // coallesced.
1199   SmallVector<int, 16> LHSValNoAssignments;
1200   SmallVector<int, 16> RHSValNoAssignments;
1201   SmallVector<std::pair<unsigned,unsigned>, 16> ValueNumberInfo;
1202                           
1203   // Compute ultimate value numbers for the LHS and RHS values.
1204   if (RHS.containsOneValue()) {
1205     // Copies from a liveinterval with a single value are simple to handle and
1206     // very common, handle the special case here.  This is important, because
1207     // often RHS is small and LHS is large (e.g. a physreg).
1208     
1209     // Find out if the RHS is defined as a copy from some value in the LHS.
1210     int RHSValID = -1;
1211     std::pair<unsigned,unsigned> RHSValNoInfo;
1212     unsigned RHSSrcReg = RHS.getSrcRegForValNum(0);
1213     if ((RHSSrcReg == 0 || rep(RHSSrcReg) != LHS.reg)) {
1214       // If RHS is not defined as a copy from the LHS, we can use simpler and
1215       // faster checks to see if the live ranges are coallescable.  This joiner
1216       // can't swap the LHS/RHS intervals though.
1217       if (!MRegisterInfo::isPhysicalRegister(RHS.reg)) {
1218         return SimpleJoin(LHS, RHS);
1219       } else {
1220         RHSValNoInfo = RHS.getValNumInfo(0);
1221       }
1222     } else {
1223       // It was defined as a copy from the LHS, find out what value # it is.
1224       unsigned ValInst = RHS.getInstForValNum(0);
1225       RHSValID = LHS.getLiveRangeContaining(ValInst-1)->ValId;
1226       RHSValNoInfo = LHS.getValNumInfo(RHSValID);
1227     }
1228     
1229     LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
1230     RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
1231     ValueNumberInfo.resize(LHS.getNumValNums());
1232     
1233     // Okay, *all* of the values in LHS that are defined as a copy from RHS
1234     // should now get updated.
1235     for (unsigned VN = 0, e = LHS.getNumValNums(); VN != e; ++VN) {
1236       if (unsigned LHSSrcReg = LHS.getSrcRegForValNum(VN)) {
1237         if (rep(LHSSrcReg) != RHS.reg) {
1238           // If this is not a copy from the RHS, its value number will be
1239           // unmodified by the coallescing.
1240           ValueNumberInfo[VN] = LHS.getValNumInfo(VN);
1241           LHSValNoAssignments[VN] = VN;
1242         } else if (RHSValID == -1) {
1243           // Otherwise, it is a copy from the RHS, and we don't already have a
1244           // value# for it.  Keep the current value number, but remember it.
1245           LHSValNoAssignments[VN] = RHSValID = VN;
1246           ValueNumberInfo[VN] = RHSValNoInfo;
1247         } else {
1248           // Otherwise, use the specified value #.
1249           LHSValNoAssignments[VN] = RHSValID;
1250           if (VN != (unsigned)RHSValID)
1251             ValueNumberInfo[VN].first = ~1U;
1252           else
1253             ValueNumberInfo[VN] = RHSValNoInfo;
1254         }
1255       } else {
1256         ValueNumberInfo[VN] = LHS.getValNumInfo(VN);
1257         LHSValNoAssignments[VN] = VN;
1258       }
1259     }
1260     
1261     assert(RHSValID != -1 && "Didn't find value #?");
1262     RHSValNoAssignments[0] = RHSValID;
1263     
1264   } else {
1265     // Loop over the value numbers of the LHS, seeing if any are defined from
1266     // the RHS.
1267     SmallVector<int, 16> LHSValsDefinedFromRHS;
1268     LHSValsDefinedFromRHS.resize(LHS.getNumValNums(), -1);
1269     for (unsigned VN = 0, e = LHS.getNumValNums(); VN != e; ++VN) {
1270       unsigned ValSrcReg = LHS.getSrcRegForValNum(VN);
1271       if (ValSrcReg == 0)  // Src not defined by a copy?
1272         continue;
1273       
1274       // DstReg is known to be a register in the LHS interval.  If the src is
1275       // from the RHS interval, we can use its value #.
1276       if (rep(ValSrcReg) != RHS.reg)
1277         continue;
1278       
1279       // Figure out the value # from the RHS.
1280       unsigned ValInst = LHS.getInstForValNum(VN);
1281       LHSValsDefinedFromRHS[VN] = RHS.getLiveRangeContaining(ValInst-1)->ValId;
1282     }
1283     
1284     // Loop over the value numbers of the RHS, seeing if any are defined from
1285     // the LHS.
1286     SmallVector<int, 16> RHSValsDefinedFromLHS;
1287     RHSValsDefinedFromLHS.resize(RHS.getNumValNums(), -1);
1288     for (unsigned VN = 0, e = RHS.getNumValNums(); VN != e; ++VN) {
1289       unsigned ValSrcReg = RHS.getSrcRegForValNum(VN);
1290       if (ValSrcReg == 0)  // Src not defined by a copy?
1291         continue;
1292       
1293       // DstReg is known to be a register in the RHS interval.  If the src is
1294       // from the LHS interval, we can use its value #.
1295       if (rep(ValSrcReg) != LHS.reg)
1296         continue;
1297       
1298       // Figure out the value # from the LHS.
1299       unsigned ValInst = RHS.getInstForValNum(VN);
1300       RHSValsDefinedFromLHS[VN] = LHS.getLiveRangeContaining(ValInst-1)->ValId;
1301     }
1302     
1303     LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
1304     RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
1305     ValueNumberInfo.reserve(LHS.getNumValNums() + RHS.getNumValNums());
1306     
1307     for (unsigned VN = 0, e = LHS.getNumValNums(); VN != e; ++VN) {
1308       if (LHSValNoAssignments[VN] >= 0 || LHS.getInstForValNum(VN) == ~2U) 
1309         continue;
1310       ComputeUltimateVN(VN, ValueNumberInfo,
1311                         LHSValsDefinedFromRHS, RHSValsDefinedFromLHS,
1312                         LHSValNoAssignments, RHSValNoAssignments, LHS, RHS);
1313     }
1314     for (unsigned VN = 0, e = RHS.getNumValNums(); VN != e; ++VN) {
1315       if (RHSValNoAssignments[VN] >= 0 || RHS.getInstForValNum(VN) == ~2U)
1316         continue;
1317       // If this value number isn't a copy from the LHS, it's a new number.
1318       if (RHSValsDefinedFromLHS[VN] == -1) {
1319         ValueNumberInfo.push_back(RHS.getValNumInfo(VN));
1320         RHSValNoAssignments[VN] = ValueNumberInfo.size()-1;
1321         continue;
1322       }
1323       
1324       ComputeUltimateVN(VN, ValueNumberInfo,
1325                         RHSValsDefinedFromLHS, LHSValsDefinedFromRHS,
1326                         RHSValNoAssignments, LHSValNoAssignments, RHS, LHS);
1327     }
1328   }
1329   
1330   // Armed with the mappings of LHS/RHS values to ultimate values, walk the
1331   // interval lists to see if these intervals are coallescable.
1332   LiveInterval::const_iterator I = LHS.begin();
1333   LiveInterval::const_iterator IE = LHS.end();
1334   LiveInterval::const_iterator J = RHS.begin();
1335   LiveInterval::const_iterator JE = RHS.end();
1336   
1337   // Skip ahead until the first place of potential sharing.
1338   if (I->start < J->start) {
1339     I = std::upper_bound(I, IE, J->start);
1340     if (I != LHS.begin()) --I;
1341   } else if (J->start < I->start) {
1342     J = std::upper_bound(J, JE, I->start);
1343     if (J != RHS.begin()) --J;
1344   }
1345   
1346   while (1) {
1347     // Determine if these two live ranges overlap.
1348     bool Overlaps;
1349     if (I->start < J->start) {
1350       Overlaps = I->end > J->start;
1351     } else {
1352       Overlaps = J->end > I->start;
1353     }
1354
1355     // If so, check value # info to determine if they are really different.
1356     if (Overlaps) {
1357       // If the live range overlap will map to the same value number in the
1358       // result liverange, we can still coallesce them.  If not, we can't.
1359       if (LHSValNoAssignments[I->ValId] != RHSValNoAssignments[J->ValId])
1360         return false;
1361     }
1362     
1363     if (I->end < J->end) {
1364       ++I;
1365       if (I == IE) break;
1366     } else {
1367       ++J;
1368       if (J == JE) break;
1369     }
1370   }
1371
1372   // If we get here, we know that we can coallesce the live ranges.  Ask the
1373   // intervals to coallesce themselves now.
1374   LHS.join(RHS, &LHSValNoAssignments[0], &RHSValNoAssignments[0],
1375            ValueNumberInfo);
1376   return true;
1377 }
1378
1379
1380 namespace {
1381   // DepthMBBCompare - Comparison predicate that sort first based on the loop
1382   // depth of the basic block (the unsigned), and then on the MBB number.
1383   struct DepthMBBCompare {
1384     typedef std::pair<unsigned, MachineBasicBlock*> DepthMBBPair;
1385     bool operator()(const DepthMBBPair &LHS, const DepthMBBPair &RHS) const {
1386       if (LHS.first > RHS.first) return true;   // Deeper loops first
1387       return LHS.first == RHS.first &&
1388         LHS.second->getNumber() < RHS.second->getNumber();
1389     }
1390   };
1391 }
1392
1393
1394 void LiveIntervals::CopyCoallesceInMBB(MachineBasicBlock *MBB,
1395                                        std::vector<CopyRec> &TryAgain) {
1396   DOUT << ((Value*)MBB->getBasicBlock())->getName() << ":\n";
1397   
1398   for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end();
1399        MII != E;) {
1400     MachineInstr *Inst = MII++;
1401     
1402     // If this isn't a copy, we can't join intervals.
1403     unsigned SrcReg, DstReg;
1404     if (!tii_->isMoveInstr(*Inst, SrcReg, DstReg)) continue;
1405     
1406     if (!JoinCopy(Inst, SrcReg, DstReg))
1407       TryAgain.push_back(getCopyRec(Inst, SrcReg, DstReg));
1408   }
1409 }
1410
1411
1412 void LiveIntervals::joinIntervals() {
1413   DOUT << "********** JOINING INTERVALS ***********\n";
1414
1415   JoinedLIs.resize(getNumIntervals());
1416   JoinedLIs.reset();
1417
1418   std::vector<CopyRec> TryAgainList;
1419   const LoopInfo &LI = getAnalysis<LoopInfo>();
1420   if (LI.begin() == LI.end()) {
1421     // If there are no loops in the function, join intervals in function order.
1422     for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();
1423          I != E; ++I)
1424       CopyCoallesceInMBB(I, TryAgainList);
1425   } else {
1426     // Otherwise, join intervals in inner loops before other intervals.
1427     // Unfortunately we can't just iterate over loop hierarchy here because
1428     // there may be more MBB's than BB's.  Collect MBB's for sorting.
1429     std::vector<std::pair<unsigned, MachineBasicBlock*> > MBBs;
1430     for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();
1431          I != E; ++I)
1432       MBBs.push_back(std::make_pair(LI.getLoopDepth(I->getBasicBlock()), I));
1433
1434     // Sort by loop depth.
1435     std::sort(MBBs.begin(), MBBs.end(), DepthMBBCompare());
1436
1437     // Finally, join intervals in loop nest order.
1438     for (unsigned i = 0, e = MBBs.size(); i != e; ++i)
1439       CopyCoallesceInMBB(MBBs[i].second, TryAgainList);
1440   }
1441   
1442   // Joining intervals can allow other intervals to be joined.  Iteratively join
1443   // until we make no progress.
1444   bool ProgressMade = true;
1445   while (ProgressMade) {
1446     ProgressMade = false;
1447
1448     for (unsigned i = 0, e = TryAgainList.size(); i != e; ++i) {
1449       CopyRec &TheCopy = TryAgainList[i];
1450       if (TheCopy.MI &&
1451           JoinCopy(TheCopy.MI, TheCopy.SrcReg, TheCopy.DstReg)) {
1452         TheCopy.MI = 0;   // Mark this one as done.
1453         ProgressMade = true;
1454       }
1455     }
1456   }
1457
1458   // Some live range has been lengthened due to colaescing, eliminate the
1459   // unnecessary kills.
1460   int RegNum = JoinedLIs.find_first();
1461   while (RegNum != -1) {
1462     unsigned Reg = RegNum + MRegisterInfo::FirstVirtualRegister;
1463     unsigned repReg = rep(Reg);
1464     LiveInterval &LI = getInterval(repReg);
1465     LiveVariables::VarInfo& svi = lv_->getVarInfo(Reg);
1466     for (unsigned i = 0, e = svi.Kills.size(); i != e; ++i) {
1467       MachineInstr *Kill = svi.Kills[i];
1468       // Suppose vr1 = op vr2, x
1469       // and vr1 and vr2 are coalesced. vr2 should still be marked kill
1470       // unless it is a two-address operand.
1471       if (isRemoved(Kill) || hasRegisterDef(Kill, repReg))
1472         continue;
1473       if (LI.liveAt(getInstructionIndex(Kill) + InstrSlots::NUM))
1474         unsetRegisterKill(Kill, repReg);
1475     }
1476     RegNum = JoinedLIs.find_next(RegNum);
1477   }
1478   
1479   DOUT << "*** Register mapping ***\n";
1480   for (int i = 0, e = r2rMap_.size(); i != e; ++i)
1481     if (r2rMap_[i]) {
1482       DOUT << "  reg " << i << " -> ";
1483       DEBUG(printRegName(r2rMap_[i]));
1484       DOUT << "\n";
1485     }
1486 }
1487
1488 /// Return true if the two specified registers belong to different register
1489 /// classes.  The registers may be either phys or virt regs.
1490 bool LiveIntervals::differingRegisterClasses(unsigned RegA,
1491                                              unsigned RegB) const {
1492
1493   // Get the register classes for the first reg.
1494   if (MRegisterInfo::isPhysicalRegister(RegA)) {
1495     assert(MRegisterInfo::isVirtualRegister(RegB) &&
1496            "Shouldn't consider two physregs!");
1497     return !mf_->getSSARegMap()->getRegClass(RegB)->contains(RegA);
1498   }
1499
1500   // Compare against the regclass for the second reg.
1501   const TargetRegisterClass *RegClass = mf_->getSSARegMap()->getRegClass(RegA);
1502   if (MRegisterInfo::isVirtualRegister(RegB))
1503     return RegClass != mf_->getSSARegMap()->getRegClass(RegB);
1504   else
1505     return !RegClass->contains(RegB);
1506 }
1507
1508 /// lastRegisterUse - Returns the last use of the specific register between
1509 /// cycles Start and End. It also returns the use operand by reference. It
1510 /// returns NULL if there are no uses.
1511 MachineInstr *
1512 LiveIntervals::lastRegisterUse(unsigned Reg, unsigned Start, unsigned End,
1513                                MachineOperand *&MOU) {
1514   int e = (End-1) / InstrSlots::NUM * InstrSlots::NUM;
1515   int s = Start;
1516   while (e >= s) {
1517     // Skip deleted instructions
1518     MachineInstr *MI = getInstructionFromIndex(e);
1519     while ((e - InstrSlots::NUM) >= s && !MI) {
1520       e -= InstrSlots::NUM;
1521       MI = getInstructionFromIndex(e);
1522     }
1523     if (e < s || MI == NULL)
1524       return NULL;
1525
1526     for (unsigned i = 0, NumOps = MI->getNumOperands(); i != NumOps; ++i) {
1527       MachineOperand &MO = MI->getOperand(i);
1528       if (MO.isReg() && MO.isUse() && MO.getReg() &&
1529           mri_->regsOverlap(rep(MO.getReg()), Reg)) {
1530         MOU = &MO;
1531         return MI;
1532       }
1533     }
1534
1535     e -= InstrSlots::NUM;
1536   }
1537
1538   return NULL;
1539 }
1540
1541 /// unsetRegisterKill - Unset IsKill property of all uses of specific register
1542 /// of the specific instruction.
1543 void LiveIntervals::unsetRegisterKill(MachineInstr *MI, unsigned Reg) {
1544   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1545     MachineOperand &MO = MI->getOperand(i);
1546     if (MO.isReg() && MO.isUse() && MO.isKill() && MO.getReg() &&
1547         mri_->regsOverlap(rep(MO.getReg()), Reg))
1548       MO.unsetIsKill();
1549   }
1550 }
1551
1552 /// hasRegisterDef - True if the instruction defines the specific register.
1553 ///
1554 bool LiveIntervals::hasRegisterDef(MachineInstr *MI, unsigned Reg) {
1555   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1556     MachineOperand &MO = MI->getOperand(i);
1557     if (MO.isReg() && MO.isDef() &&
1558         mri_->regsOverlap(rep(MO.getReg()), Reg))
1559       return true;
1560   }
1561   return false;
1562 }
1563
1564 LiveInterval LiveIntervals::createInterval(unsigned reg) {
1565   float Weight = MRegisterInfo::isPhysicalRegister(reg) ?
1566                        HUGE_VALF : 0.0F;
1567   return LiveInterval(reg, Weight);
1568 }