- Remove the previous check which broke coalescer-commute3.ll
[oota-llvm.git] / lib / CodeGen / SimpleRegisterCoalescing.cpp
1 //===-- SimpleRegisterCoalescing.cpp - Register Coalescing ----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements a simple register coalescing pass that attempts to
11 // aggressively coalesce every register copy that it can.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "regcoalescing"
16 #include "SimpleRegisterCoalescing.h"
17 #include "VirtRegMap.h"
18 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
19 #include "llvm/Value.h"
20 #include "llvm/CodeGen/LiveVariables.h"
21 #include "llvm/CodeGen/MachineFrameInfo.h"
22 #include "llvm/CodeGen/MachineInstr.h"
23 #include "llvm/CodeGen/MachineLoopInfo.h"
24 #include "llvm/CodeGen/MachineRegisterInfo.h"
25 #include "llvm/CodeGen/Passes.h"
26 #include "llvm/CodeGen/RegisterCoalescer.h"
27 #include "llvm/Target/TargetInstrInfo.h"
28 #include "llvm/Target/TargetMachine.h"
29 #include "llvm/Support/CommandLine.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/ADT/SmallSet.h"
32 #include "llvm/ADT/Statistic.h"
33 #include "llvm/ADT/STLExtras.h"
34 #include <algorithm>
35 #include <cmath>
36 using namespace llvm;
37
38 STATISTIC(numJoins    , "Number of interval joins performed");
39 STATISTIC(numCommutes , "Number of instruction commuting performed");
40 STATISTIC(numExtends  , "Number of copies extended");
41 STATISTIC(numPeep     , "Number of identity moves eliminated after coalescing");
42 STATISTIC(numAborts   , "Number of times interval joining aborted");
43
44 char SimpleRegisterCoalescing::ID = 0;
45 namespace {
46   static cl::opt<bool>
47   EnableJoining("join-liveintervals",
48                 cl::desc("Coalesce copies (default=true)"),
49                 cl::init(true));
50
51   static cl::opt<bool>
52   NewHeuristic("new-coalescer-heuristic",
53                 cl::desc("Use new coalescer heuristic"),
54                 cl::init(false));
55
56   static cl::opt<bool>
57   CommuteDef("coalescer-commute-instrs",
58              cl::init(false), cl::Hidden);
59
60   RegisterPass<SimpleRegisterCoalescing> 
61   X("simple-register-coalescing", "Simple Register Coalescing");
62
63   // Declare that we implement the RegisterCoalescer interface
64   RegisterAnalysisGroup<RegisterCoalescer, true/*The Default*/> V(X);
65 }
66
67 const PassInfo *llvm::SimpleRegisterCoalescingID = X.getPassInfo();
68
69 void SimpleRegisterCoalescing::getAnalysisUsage(AnalysisUsage &AU) const {
70   AU.addPreserved<LiveIntervals>();
71   AU.addPreserved<MachineLoopInfo>();
72   AU.addPreservedID(MachineDominatorsID);
73   AU.addPreservedID(PHIEliminationID);
74   AU.addPreservedID(TwoAddressInstructionPassID);
75   AU.addRequired<LiveVariables>();
76   AU.addRequired<LiveIntervals>();
77   AU.addRequired<MachineLoopInfo>();
78   MachineFunctionPass::getAnalysisUsage(AU);
79 }
80
81 /// AdjustCopiesBackFrom - We found a non-trivially-coalescable copy with IntA
82 /// being the source and IntB being the dest, thus this defines a value number
83 /// in IntB.  If the source value number (in IntA) is defined by a copy from B,
84 /// see if we can merge these two pieces of B into a single value number,
85 /// eliminating a copy.  For example:
86 ///
87 ///  A3 = B0
88 ///    ...
89 ///  B1 = A3      <- this copy
90 ///
91 /// In this case, B0 can be extended to where the B1 copy lives, allowing the B1
92 /// value number to be replaced with B0 (which simplifies the B liveinterval).
93 ///
94 /// This returns true if an interval was modified.
95 ///
96 bool SimpleRegisterCoalescing::AdjustCopiesBackFrom(LiveInterval &IntA,
97                                                     LiveInterval &IntB,
98                                                     MachineInstr *CopyMI) {
99   unsigned CopyIdx = li_->getDefIndex(li_->getInstructionIndex(CopyMI));
100
101   // BValNo is a value number in B that is defined by a copy from A.  'B3' in
102   // the example above.
103   LiveInterval::iterator BLR = IntB.FindLiveRangeContaining(CopyIdx);
104   VNInfo *BValNo = BLR->valno;
105   
106   // Get the location that B is defined at.  Two options: either this value has
107   // an unknown definition point or it is defined at CopyIdx.  If unknown, we 
108   // can't process it.
109   if (!BValNo->copy) return false;
110   assert(BValNo->def == CopyIdx && "Copy doesn't define the value?");
111   
112   // AValNo is the value number in A that defines the copy, A3 in the example.
113   LiveInterval::iterator ALR = IntA.FindLiveRangeContaining(CopyIdx-1);
114   VNInfo *AValNo = ALR->valno;
115   
116   // If AValNo is defined as a copy from IntB, we can potentially process this.  
117   // Get the instruction that defines this value number.
118   unsigned SrcReg = li_->getVNInfoSourceReg(AValNo);
119   if (!SrcReg) return false;  // Not defined by a copy.
120     
121   // If the value number is not defined by a copy instruction, ignore it.
122
123   // If the source register comes from an interval other than IntB, we can't
124   // handle this.
125   if (SrcReg != IntB.reg) return false;
126   
127   // Get the LiveRange in IntB that this value number starts with.
128   LiveInterval::iterator ValLR = IntB.FindLiveRangeContaining(AValNo->def-1);
129   
130   // Make sure that the end of the live range is inside the same block as
131   // CopyMI.
132   MachineInstr *ValLREndInst = li_->getInstructionFromIndex(ValLR->end-1);
133   if (!ValLREndInst || 
134       ValLREndInst->getParent() != CopyMI->getParent()) return false;
135
136   // Okay, we now know that ValLR ends in the same block that the CopyMI
137   // live-range starts.  If there are no intervening live ranges between them in
138   // IntB, we can merge them.
139   if (ValLR+1 != BLR) return false;
140
141   // If a live interval is a physical register, conservatively check if any
142   // of its sub-registers is overlapping the live interval of the virtual
143   // register. If so, do not coalesce.
144   if (TargetRegisterInfo::isPhysicalRegister(IntB.reg) &&
145       *tri_->getSubRegisters(IntB.reg)) {
146     for (const unsigned* SR = tri_->getSubRegisters(IntB.reg); *SR; ++SR)
147       if (li_->hasInterval(*SR) && IntA.overlaps(li_->getInterval(*SR))) {
148         DOUT << "Interfere with sub-register ";
149         DEBUG(li_->getInterval(*SR).print(DOUT, tri_));
150         return false;
151       }
152   }
153   
154   DOUT << "\nExtending: "; IntB.print(DOUT, tri_);
155   
156   unsigned FillerStart = ValLR->end, FillerEnd = BLR->start;
157   // We are about to delete CopyMI, so need to remove it as the 'instruction
158   // that defines this value #'. Update the the valnum with the new defining
159   // instruction #.
160   BValNo->def  = FillerStart;
161   BValNo->copy = NULL;
162   
163   // Okay, we can merge them.  We need to insert a new liverange:
164   // [ValLR.end, BLR.begin) of either value number, then we merge the
165   // two value numbers.
166   IntB.addRange(LiveRange(FillerStart, FillerEnd, BValNo));
167
168   // If the IntB live range is assigned to a physical register, and if that
169   // physreg has aliases, 
170   if (TargetRegisterInfo::isPhysicalRegister(IntB.reg)) {
171     // Update the liveintervals of sub-registers.
172     for (const unsigned *AS = tri_->getSubRegisters(IntB.reg); *AS; ++AS) {
173       LiveInterval &AliasLI = li_->getInterval(*AS);
174       AliasLI.addRange(LiveRange(FillerStart, FillerEnd,
175               AliasLI.getNextValue(FillerStart, 0, li_->getVNInfoAllocator())));
176     }
177   }
178
179   // Okay, merge "B1" into the same value number as "B0".
180   if (BValNo != ValLR->valno)
181     IntB.MergeValueNumberInto(BValNo, ValLR->valno);
182   DOUT << "   result = "; IntB.print(DOUT, tri_);
183   DOUT << "\n";
184
185   // If the source instruction was killing the source register before the
186   // merge, unset the isKill marker given the live range has been extended.
187   int UIdx = ValLREndInst->findRegisterUseOperandIdx(IntB.reg, true);
188   if (UIdx != -1)
189     ValLREndInst->getOperand(UIdx).setIsKill(false);
190
191   ++numExtends;
192   return true;
193 }
194
195 /// HasOtherReachingDefs - Return true if there are definitions of IntB
196 /// other than BValNo val# that can reach uses of AValno val# of IntA.
197 bool SimpleRegisterCoalescing::HasOtherReachingDefs(LiveInterval &IntA,
198                                                     LiveInterval &IntB,
199                                                     VNInfo *AValNo,
200                                                     VNInfo *BValNo) {
201   for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
202        AI != AE; ++AI) {
203     if (AI->valno != AValNo) continue;
204     LiveInterval::Ranges::iterator BI =
205       std::upper_bound(IntB.ranges.begin(), IntB.ranges.end(), AI->start);
206     if (BI != IntB.ranges.begin())
207       --BI;
208     for (; BI != IntB.ranges.end() && AI->end >= BI->start; ++BI) {
209       if (BI->valno == BValNo)
210         continue;
211       if (BI->start <= AI->start && BI->end > AI->start)
212         return true;
213       if (BI->start > AI->start && BI->start < AI->end)
214         return true;
215     }
216   }
217   return false;
218 }
219
220 /// RemoveCopyByCommutingDef - We found a non-trivially-coalescable copy with IntA
221 /// being the source and IntB being the dest, thus this defines a value number
222 /// in IntB.  If the source value number (in IntA) is defined by a commutable
223 /// instruction and its other operand is coalesced to the copy dest register,
224 /// see if we can transform the copy into a noop by commuting the definition. For
225 /// example,
226 ///
227 ///  A3 = op A2 B0<kill>
228 ///    ...
229 ///  B1 = A3      <- this copy
230 ///    ...
231 ///     = op A3   <- more uses
232 ///
233 /// ==>
234 ///
235 ///  B2 = op B0 A2<kill>
236 ///    ...
237 ///  B1 = B2      <- now an identify copy
238 ///    ...
239 ///     = op B2   <- more uses
240 ///
241 /// This returns true if an interval was modified.
242 ///
243 bool SimpleRegisterCoalescing::RemoveCopyByCommutingDef(LiveInterval &IntA,
244                                                         LiveInterval &IntB,
245                                                         MachineInstr *CopyMI) {
246   if (!CommuteDef) return false;
247
248   unsigned CopyIdx = li_->getDefIndex(li_->getInstructionIndex(CopyMI));
249
250   // FIXME: For now, only eliminate the copy by commuting its def when the
251   // source register is a virtual register. We want to guard against cases
252   // where the copy is a back edge copy and commuting the def lengthen the
253   // live interval of the source register to the entire loop.
254   if (TargetRegisterInfo::isPhysicalRegister(IntA.reg))
255     return false;
256
257   // BValNo is a value number in B that is defined by a copy from A. 'B3' in
258   // the example above.
259   LiveInterval::iterator BLR = IntB.FindLiveRangeContaining(CopyIdx);
260   VNInfo *BValNo = BLR->valno;
261   
262   // Get the location that B is defined at.  Two options: either this value has
263   // an unknown definition point or it is defined at CopyIdx.  If unknown, we 
264   // can't process it.
265   if (!BValNo->copy) return false;
266   assert(BValNo->def == CopyIdx && "Copy doesn't define the value?");
267   
268   // AValNo is the value number in A that defines the copy, A3 in the example.
269   LiveInterval::iterator ALR = IntA.FindLiveRangeContaining(CopyIdx-1);
270   VNInfo *AValNo = ALR->valno;
271   // If other defs can reach uses of this def, then it's not safe to perform
272   // the optimization.
273   if (AValNo->def == ~0U || AValNo->def == ~1U || AValNo->hasPHIKill)
274     return false;
275   MachineInstr *DefMI = li_->getInstructionFromIndex(AValNo->def);
276   const TargetInstrDesc &TID = DefMI->getDesc();
277   unsigned NewDstIdx;
278   if (!TID.isCommutable() ||
279       !tii_->CommuteChangesDestination(DefMI, NewDstIdx))
280     return false;
281
282   MachineOperand &NewDstMO = DefMI->getOperand(NewDstIdx);
283   unsigned NewReg = NewDstMO.getReg();
284   if (NewReg != IntB.reg || !NewDstMO.isKill())
285     return false;
286
287   // Make sure there are no other definitions of IntB that would reach the
288   // uses which the new definition can reach.
289   if (HasOtherReachingDefs(IntA, IntB, AValNo, BValNo))
290     return false;
291
292   // At this point we have decided that it is legal to do this
293   // transformation.  Start by commuting the instruction.
294   MachineBasicBlock *MBB = DefMI->getParent();
295   MachineInstr *NewMI = tii_->commuteInstruction(DefMI);
296   if (!NewMI)
297     return false;
298   if (NewMI != DefMI) {
299     li_->ReplaceMachineInstrInMaps(DefMI, NewMI);
300     MBB->insert(DefMI, NewMI);
301     MBB->erase(DefMI);
302   }
303   unsigned OpIdx = NewMI->findRegisterUseOperandIdx(IntA.reg);
304   NewMI->getOperand(OpIdx).setIsKill();
305
306   // Update uses of IntA of the specific Val# with IntB.
307   bool BHasPHIKill = BValNo->hasPHIKill;
308   SmallVector<VNInfo*, 4> BDeadValNos;
309   SmallVector<unsigned, 4> BKills;
310   std::map<unsigned, unsigned> BExtend;
311   for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(IntA.reg),
312          UE = mri_->use_end(); UI != UE;) {
313     MachineOperand &UseMO = UI.getOperand();
314     MachineInstr *UseMI = &*UI;
315     ++UI;
316     if (JoinedCopies.count(UseMI))
317       continue;
318     unsigned UseIdx = li_->getInstructionIndex(UseMI);
319     LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx);
320     if (ULR->valno != AValNo)
321       continue;
322     UseMO.setReg(NewReg);
323     if (UseMI == CopyMI)
324       continue;
325     if (UseMO.isKill())
326       BKills.push_back(li_->getUseIndex(UseIdx)+1);
327     unsigned SrcReg, DstReg;
328     if (!tii_->isMoveInstr(*UseMI, SrcReg, DstReg))
329       continue;
330     if (DstReg == IntB.reg) {
331       // This copy will become a noop. If it's defining a new val#,
332       // remove that val# as well. However this live range is being
333       // extended to the end of the existing live range defined by the copy.
334       unsigned DefIdx = li_->getDefIndex(UseIdx);
335       LiveInterval::iterator DLR = IntB.FindLiveRangeContaining(DefIdx);
336       BHasPHIKill |= DLR->valno->hasPHIKill;
337       assert(DLR->valno->def == DefIdx);
338       BDeadValNos.push_back(DLR->valno);
339       BExtend[DLR->start] = DLR->end;
340       JoinedCopies.insert(UseMI);
341       // If this is a kill but it's going to be removed, the last use
342       // of the same val# is the new kill.
343       if (UseMO.isKill()) {
344         BKills.pop_back();
345       }
346     }
347   }
348
349   // We need to insert a new liverange: [ALR.start, LastUse). It may be we can
350   // simply extend BLR if CopyMI doesn't end the range.
351   DOUT << "\nExtending: "; IntB.print(DOUT, tri_);
352
353   IntB.removeValNo(BValNo);
354   for (unsigned i = 0, e = BDeadValNos.size(); i != e; ++i)
355     IntB.removeValNo(BDeadValNos[i]);
356   VNInfo *ValNo = IntB.getNextValue(ALR->start, 0, li_->getVNInfoAllocator());
357   for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
358        AI != AE; ++AI) {
359     if (AI->valno != AValNo) continue;
360     unsigned End = AI->end;
361     std::map<unsigned, unsigned>::iterator EI = BExtend.find(End);
362     if (EI != BExtend.end())
363       End = EI->second;
364     IntB.addRange(LiveRange(AI->start, End, ValNo));
365   }
366   IntB.addKills(ValNo, BKills);
367   ValNo->hasPHIKill = BHasPHIKill;
368
369   DOUT << "   result = "; IntB.print(DOUT, tri_);
370   DOUT << "\n";
371
372   DOUT << "\nShortening: "; IntA.print(DOUT, tri_);
373   IntA.removeValNo(AValNo);
374   DOUT << "   result = "; IntA.print(DOUT, tri_);
375   DOUT << "\n";
376
377   ++numCommutes;
378   return true;
379 }
380
381 /// RemoveUnnecessaryKills - Remove kill markers that are no longer accurate
382 /// due to live range lengthening as the result of coalescing.
383 void SimpleRegisterCoalescing::RemoveUnnecessaryKills(unsigned Reg,
384                                                       LiveInterval &LI) {
385   for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(Reg),
386          UE = mri_->use_end(); UI != UE; ++UI) {
387     MachineOperand &UseMO = UI.getOperand();
388     if (UseMO.isKill()) {
389       MachineInstr *UseMI = UseMO.getParent();
390       unsigned UseIdx = li_->getUseIndex(li_->getInstructionIndex(UseMI));
391       if (JoinedCopies.count(UseMI))
392         continue;
393       LiveInterval::const_iterator UI = LI.FindLiveRangeContaining(UseIdx);
394       assert(UI != LI.end());
395       if (!LI.isKill(UI->valno, UseIdx+1))
396         UseMO.setIsKill(false);
397     }
398   }
399 }
400
401 /// isBackEdgeCopy - Returns true if CopyMI is a back edge copy.
402 ///
403 bool SimpleRegisterCoalescing::isBackEdgeCopy(MachineInstr *CopyMI,
404                                               unsigned DstReg) {
405   MachineBasicBlock *MBB = CopyMI->getParent();
406   const MachineLoop *L = loopInfo->getLoopFor(MBB);
407   if (!L)
408     return false;
409   if (MBB != L->getLoopLatch())
410     return false;
411
412   LiveInterval &LI = li_->getInterval(DstReg);
413   unsigned DefIdx = li_->getInstructionIndex(CopyMI);
414   LiveInterval::const_iterator DstLR =
415     LI.FindLiveRangeContaining(li_->getDefIndex(DefIdx));
416   if (DstLR == LI.end())
417     return false;
418   unsigned KillIdx = li_->getInstructionIndex(&MBB->back()) + InstrSlots::NUM;
419   if (DstLR->valno->kills.size() == 1 &&
420       DstLR->valno->kills[0] == KillIdx && DstLR->valno->hasPHIKill)
421     return true;
422   return false;
423 }
424
425 /// UpdateRegDefsUses - Replace all defs and uses of SrcReg to DstReg and
426 /// update the subregister number if it is not zero. If DstReg is a
427 /// physical register and the existing subregister number of the def / use
428 /// being updated is not zero, make sure to set it to the correct physical
429 /// subregister.
430 void
431 SimpleRegisterCoalescing::UpdateRegDefsUses(unsigned SrcReg, unsigned DstReg,
432                                             unsigned SubIdx) {
433   bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
434   if (DstIsPhys && SubIdx) {
435     // Figure out the real physical register we are updating with.
436     DstReg = tri_->getSubReg(DstReg, SubIdx);
437     SubIdx = 0;
438   }
439
440   for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(SrcReg),
441          E = mri_->reg_end(); I != E; ) {
442     MachineOperand &O = I.getOperand();
443     ++I;
444     if (DstIsPhys) {
445       unsigned UseSubIdx = O.getSubReg();
446       unsigned UseDstReg = DstReg;
447       if (UseSubIdx)
448         UseDstReg = tri_->getSubReg(DstReg, UseSubIdx);
449       O.setReg(UseDstReg);
450       O.setSubReg(0);
451     } else {
452       unsigned OldSubIdx = O.getSubReg();
453       assert((!SubIdx || !OldSubIdx) && "Conflicting sub-register index!");
454       if (SubIdx)
455         O.setSubReg(SubIdx);
456       O.setReg(DstReg);
457     }
458   }
459 }
460
461 /// JoinCopy - Attempt to join intervals corresponding to SrcReg/DstReg,
462 /// which are the src/dst of the copy instruction CopyMI.  This returns true
463 /// if the copy was successfully coalesced away. If it is not currently
464 /// possible to coalesce this interval, but it may be possible if other
465 /// things get coalesced, then it returns true by reference in 'Again'.
466 bool SimpleRegisterCoalescing::JoinCopy(CopyRec &TheCopy, bool &Again) {
467   MachineInstr *CopyMI = TheCopy.MI;
468
469   Again = false;
470   if (JoinedCopies.count(CopyMI))
471     return false; // Already done.
472
473   DOUT << li_->getInstructionIndex(CopyMI) << '\t' << *CopyMI;
474
475   unsigned SrcReg;
476   unsigned DstReg;
477   bool isExtSubReg = CopyMI->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG;
478   unsigned SubIdx = 0;
479   if (isExtSubReg) {
480     DstReg = CopyMI->getOperand(0).getReg();
481     SrcReg = CopyMI->getOperand(1).getReg();
482   } else if (!tii_->isMoveInstr(*CopyMI, SrcReg, DstReg)) {
483     assert(0 && "Unrecognized copy instruction!");
484     return false;
485   }
486
487   // If they are already joined we continue.
488   if (SrcReg == DstReg) {
489     DOUT << "\tCopy already coalesced.\n";
490     return false;  // Not coalescable.
491   }
492   
493   bool SrcIsPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
494   bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
495
496   // If they are both physical registers, we cannot join them.
497   if (SrcIsPhys && DstIsPhys) {
498     DOUT << "\tCan not coalesce physregs.\n";
499     return false;  // Not coalescable.
500   }
501   
502   // We only join virtual registers with allocatable physical registers.
503   if (SrcIsPhys && !allocatableRegs_[SrcReg]) {
504     DOUT << "\tSrc reg is unallocatable physreg.\n";
505     return false;  // Not coalescable.
506   }
507   if (DstIsPhys && !allocatableRegs_[DstReg]) {
508     DOUT << "\tDst reg is unallocatable physreg.\n";
509     return false;  // Not coalescable.
510   }
511
512   unsigned RealDstReg = 0;
513   if (isExtSubReg) {
514     SubIdx = CopyMI->getOperand(2).getImm();
515     if (SrcIsPhys) {
516       // r1024 = EXTRACT_SUBREG EAX, 0 then r1024 is really going to be
517       // coalesced with AX.
518       SrcReg = tri_->getSubReg(SrcReg, SubIdx);
519       SubIdx = 0;
520     } else if (DstIsPhys) {
521       // If this is a extract_subreg where dst is a physical register, e.g.
522       // cl = EXTRACT_SUBREG reg1024, 1
523       // then create and update the actual physical register allocated to RHS.
524       const TargetRegisterClass *RC = mri_->getRegClass(SrcReg);
525       for (const unsigned *SRs = tri_->getSuperRegisters(DstReg);
526            unsigned SR = *SRs; ++SRs) {
527         if (DstReg == tri_->getSubReg(SR, SubIdx) &&
528             RC->contains(SR)) {
529           RealDstReg = SR;
530           break;
531         }
532       }
533       assert(RealDstReg && "Invalid extra_subreg instruction!");
534
535       // For this type of EXTRACT_SUBREG, conservatively
536       // check if the live interval of the source register interfere with the
537       // actual super physical register we are trying to coalesce with.
538       LiveInterval &RHS = li_->getInterval(SrcReg);
539       if (li_->hasInterval(RealDstReg) &&
540           RHS.overlaps(li_->getInterval(RealDstReg))) {
541         DOUT << "Interfere with register ";
542         DEBUG(li_->getInterval(RealDstReg).print(DOUT, tri_));
543         return false; // Not coalescable
544       }
545       for (const unsigned* SR = tri_->getSubRegisters(RealDstReg); *SR; ++SR)
546         if (li_->hasInterval(*SR) && RHS.overlaps(li_->getInterval(*SR))) {
547           DOUT << "Interfere with sub-register ";
548           DEBUG(li_->getInterval(*SR).print(DOUT, tri_));
549           return false; // Not coalescable
550         }
551       SubIdx = 0;
552     } else {
553       unsigned SrcSize= li_->getInterval(SrcReg).getSize() / InstrSlots::NUM;
554       unsigned DstSize= li_->getInterval(DstReg).getSize() / InstrSlots::NUM;
555       const TargetRegisterClass *RC = mri_->getRegClass(DstReg);
556       unsigned Threshold = allocatableRCRegs_[RC].count();
557       // Be conservative. If both sides are virtual registers, do not coalesce
558       // if this will cause a high use density interval to target a smaller set
559       // of registers.
560       if (DstSize > Threshold || SrcSize > Threshold) {
561         LiveVariables::VarInfo &svi = lv_->getVarInfo(SrcReg);
562         LiveVariables::VarInfo &dvi = lv_->getVarInfo(DstReg);
563         if ((float)dvi.NumUses / DstSize < (float)svi.NumUses / SrcSize) {
564           Again = true;  // May be possible to coalesce later.
565           return false;
566         }
567       }
568     }
569   } else if (differingRegisterClasses(SrcReg, DstReg)) {
570     // FIXME: What if the resul of a EXTRACT_SUBREG is then coalesced
571     // with another? If it's the resulting destination register, then
572     // the subidx must be propagated to uses (but only those defined
573     // by the EXTRACT_SUBREG). If it's being coalesced into another
574     // register, it should be safe because register is assumed to have
575     // the register class of the super-register.
576
577     // If they are not of the same register class, we cannot join them.
578     DOUT << "\tSrc/Dest are different register classes.\n";
579     // Allow the coalescer to try again in case either side gets coalesced to
580     // a physical register that's compatible with the other side. e.g.
581     // r1024 = MOV32to32_ r1025
582     // but later r1024 is assigned EAX then r1025 may be coalesced with EAX.
583     Again = true;  // May be possible to coalesce later.
584     return false;
585   }
586   
587   LiveInterval &SrcInt = li_->getInterval(SrcReg);
588   LiveInterval &DstInt = li_->getInterval(DstReg);
589   assert(SrcInt.reg == SrcReg && DstInt.reg == DstReg &&
590          "Register mapping is horribly broken!");
591
592   DOUT << "\t\tInspecting "; SrcInt.print(DOUT, tri_);
593   DOUT << " and "; DstInt.print(DOUT, tri_);
594   DOUT << ": ";
595
596   // Check if it is necessary to propagate "isDead" property before intervals
597   // are joined.
598   MachineOperand *mopd = CopyMI->findRegisterDefOperand(DstReg);
599   bool isDead = mopd->isDead();
600   bool isShorten = false;
601   unsigned SrcStart = 0, RemoveStart = 0;
602   unsigned SrcEnd = 0, RemoveEnd = 0;
603   if (isDead) {
604     unsigned CopyIdx = li_->getInstructionIndex(CopyMI);
605     LiveInterval::iterator SrcLR =
606       SrcInt.FindLiveRangeContaining(li_->getUseIndex(CopyIdx));
607     RemoveStart = SrcStart = SrcLR->start;
608     RemoveEnd   = SrcEnd   = SrcLR->end;
609     // The instruction which defines the src is only truly dead if there are
610     // no intermediate uses and there isn't a use beyond the copy.
611     // FIXME: find the last use, mark is kill and shorten the live range.
612     if (SrcEnd > li_->getDefIndex(CopyIdx)) {
613       isDead = false;
614     } else {
615       unsigned LastUseIdx;
616       MachineOperand *LastUse =
617         lastRegisterUse(SrcStart, CopyIdx, SrcReg, LastUseIdx);
618       if (LastUse) {
619         // Shorten the liveinterval to the end of last use.
620         LastUse->setIsKill();
621         isDead = false;
622         isShorten = true;
623         RemoveStart = li_->getDefIndex(LastUseIdx);
624         RemoveEnd = SrcEnd;
625       } else {
626         MachineInstr *SrcMI = li_->getInstructionFromIndex(SrcStart);
627         if (SrcMI) {
628           MachineOperand *mops = findDefOperand(SrcMI, SrcReg);
629           if (mops)
630             // A dead def should have a single cycle interval.
631             ++RemoveStart;
632         }
633       }
634     }
635   }
636
637   // We need to be careful about coalescing a source physical register with a
638   // virtual register. Once the coalescing is done, it cannot be broken and
639   // these are not spillable! If the destination interval uses are far away,
640   // think twice about coalescing them!
641   if (!mopd->isDead() && (SrcIsPhys || DstIsPhys) && !isExtSubReg) {
642     LiveInterval &JoinVInt = SrcIsPhys ? DstInt : SrcInt;
643     unsigned JoinVReg = SrcIsPhys ? DstReg : SrcReg;
644     unsigned JoinPReg = SrcIsPhys ? SrcReg : DstReg;
645     const TargetRegisterClass *RC = mri_->getRegClass(JoinVReg);
646     unsigned Threshold = allocatableRCRegs_[RC].count() * 2;
647     if (TheCopy.isBackEdge)
648       Threshold *= 2; // Favors back edge copies.
649
650     // If the virtual register live interval is long but it has low use desity,
651     // do not join them, instead mark the physical register as its allocation
652     // preference.
653     unsigned Length = JoinVInt.getSize() / InstrSlots::NUM;
654     LiveVariables::VarInfo &vi = lv_->getVarInfo(JoinVReg);
655     if (Length > Threshold &&
656         (((float)vi.NumUses / Length) < (1.0 / Threshold))) {
657       JoinVInt.preference = JoinPReg;
658       ++numAborts;
659       DOUT << "\tMay tie down a physical register, abort!\n";
660       Again = true;  // May be possible to coalesce later.
661       return false;
662     }
663   }
664
665   // Okay, attempt to join these two intervals.  On failure, this returns false.
666   // Otherwise, if one of the intervals being joined is a physreg, this method
667   // always canonicalizes DstInt to be it.  The output "SrcInt" will not have
668   // been modified, so we can use this information below to update aliases.
669   bool Swapped = false;
670   if (JoinIntervals(DstInt, SrcInt, Swapped)) {
671     if (isDead) {
672       // Result of the copy is dead. Propagate this property.
673       if (SrcStart == 0) {
674         assert(TargetRegisterInfo::isPhysicalRegister(SrcReg) &&
675                "Live-in must be a physical register!");
676         // Live-in to the function but dead. Remove it from entry live-in set.
677         // JoinIntervals may end up swapping the two intervals.
678         mf_->begin()->removeLiveIn(SrcReg);
679       } else {
680         MachineInstr *SrcMI = li_->getInstructionFromIndex(SrcStart);
681         if (SrcMI) {
682           MachineOperand *mops = findDefOperand(SrcMI, SrcReg);
683           if (mops)
684             mops->setIsDead();
685         }
686       }
687     }
688
689     if (isShorten || isDead) {
690       // Shorten the destination live interval.
691       if (Swapped)
692         SrcInt.removeRange(RemoveStart, RemoveEnd, true);
693     }
694   } else {
695     // Coalescing failed.
696     
697     // If we can eliminate the copy without merging the live ranges, do so now.
698     if (!isExtSubReg &&
699         (AdjustCopiesBackFrom(SrcInt, DstInt, CopyMI) ||
700          RemoveCopyByCommutingDef(SrcInt, DstInt, CopyMI))) {
701       JoinedCopies.insert(CopyMI);
702       return true;
703     }
704     
705     // Otherwise, we are unable to join the intervals.
706     DOUT << "Interference!\n";
707     Again = true;  // May be possible to coalesce later.
708     return false;
709   }
710
711   LiveInterval *ResSrcInt = &SrcInt;
712   LiveInterval *ResDstInt = &DstInt;
713   if (Swapped) {
714     std::swap(SrcReg, DstReg);
715     std::swap(ResSrcInt, ResDstInt);
716   }
717   assert(TargetRegisterInfo::isVirtualRegister(SrcReg) &&
718          "LiveInterval::join didn't work right!");
719                                
720   // If we're about to merge live ranges into a physical register live range,
721   // we have to update any aliased register's live ranges to indicate that they
722   // have clobbered values for this range.
723   if (TargetRegisterInfo::isPhysicalRegister(DstReg)) {
724     // Unset unnecessary kills.
725     if (!ResDstInt->containsOneValue()) {
726       for (LiveInterval::Ranges::const_iterator I = ResSrcInt->begin(),
727              E = ResSrcInt->end(); I != E; ++I)
728         unsetRegisterKills(I->start, I->end, DstReg);
729     }
730
731     // If this is a extract_subreg where dst is a physical register, e.g.
732     // cl = EXTRACT_SUBREG reg1024, 1
733     // then create and update the actual physical register allocated to RHS.
734     if (RealDstReg) {
735       LiveInterval &RealDstInt = li_->getOrCreateInterval(RealDstReg);
736       SmallSet<const VNInfo*, 4> CopiedValNos;
737       for (LiveInterval::Ranges::const_iterator I = ResSrcInt->ranges.begin(),
738              E = ResSrcInt->ranges.end(); I != E; ++I) {
739         LiveInterval::const_iterator DstLR =
740           ResDstInt->FindLiveRangeContaining(I->start);
741         assert(DstLR != ResDstInt->end() && "Invalid joined interval!");
742         const VNInfo *DstValNo = DstLR->valno;
743         if (CopiedValNos.insert(DstValNo)) {
744           VNInfo *ValNo = RealDstInt.getNextValue(DstValNo->def, DstValNo->copy,
745                                                   li_->getVNInfoAllocator());
746           ValNo->hasPHIKill = DstValNo->hasPHIKill;
747           RealDstInt.addKills(ValNo, DstValNo->kills);
748           RealDstInt.MergeValueInAsValue(*ResDstInt, DstValNo, ValNo);
749         }
750       }
751       DstReg = RealDstReg;
752     }
753
754     // Update the liveintervals of sub-registers.
755     for (const unsigned *AS = tri_->getSubRegisters(DstReg); *AS; ++AS)
756       li_->getOrCreateInterval(*AS).MergeInClobberRanges(*ResSrcInt,
757                                                  li_->getVNInfoAllocator());
758   } else {
759     // Merge use info if the destination is a virtual register.
760     LiveVariables::VarInfo& dVI = lv_->getVarInfo(DstReg);
761     LiveVariables::VarInfo& sVI = lv_->getVarInfo(SrcReg);
762     dVI.NumUses += sVI.NumUses;
763   }
764
765   // If this is a EXTRACT_SUBREG, make sure the result of coalescing is the
766   // larger super-register.
767   if (isExtSubReg && !SrcIsPhys && !DstIsPhys) {
768     if (!Swapped) {
769       ResSrcInt->Copy(*ResDstInt, li_->getVNInfoAllocator());
770       std::swap(SrcReg, DstReg);
771       std::swap(ResSrcInt, ResDstInt);
772     }
773   }
774
775   if (NewHeuristic) {
776     // Add all copies that define val# in the source interval into the queue.
777     for (LiveInterval::const_vni_iterator i = ResSrcInt->vni_begin(),
778            e = ResSrcInt->vni_end(); i != e; ++i) {
779       const VNInfo *vni = *i;
780       if (!vni->def || vni->def == ~1U || vni->def == ~0U)
781         continue;
782       MachineInstr *CopyMI = li_->getInstructionFromIndex(vni->def);
783       unsigned NewSrcReg, NewDstReg;
784       if (CopyMI &&
785           JoinedCopies.count(CopyMI) == 0 &&
786           tii_->isMoveInstr(*CopyMI, NewSrcReg, NewDstReg)) {
787         unsigned LoopDepth = loopInfo->getLoopDepth(CopyMI->getParent());
788         JoinQueue->push(CopyRec(CopyMI, LoopDepth,
789                                 isBackEdgeCopy(CopyMI, DstReg)));
790       }
791     }
792   }
793
794   DOUT << "\n\t\tJoined.  Result = "; ResDstInt->print(DOUT, tri_);
795   DOUT << "\n";
796
797   // Remember to delete the copy instruction.
798   JoinedCopies.insert(CopyMI);
799
800   // Some live range has been lengthened due to colaescing, eliminate the
801   // unnecessary kills.
802   RemoveUnnecessaryKills(SrcReg, *ResDstInt);
803   if (TargetRegisterInfo::isVirtualRegister(DstReg))
804     RemoveUnnecessaryKills(DstReg, *ResDstInt);
805
806   // SrcReg is guarateed to be the register whose live interval that is
807   // being merged.
808   li_->removeInterval(SrcReg);
809   UpdateRegDefsUses(SrcReg, DstReg, SubIdx);
810
811   ++numJoins;
812   return true;
813 }
814
815 /// ComputeUltimateVN - Assuming we are going to join two live intervals,
816 /// compute what the resultant value numbers for each value in the input two
817 /// ranges will be.  This is complicated by copies between the two which can
818 /// and will commonly cause multiple value numbers to be merged into one.
819 ///
820 /// VN is the value number that we're trying to resolve.  InstDefiningValue
821 /// keeps track of the new InstDefiningValue assignment for the result
822 /// LiveInterval.  ThisFromOther/OtherFromThis are sets that keep track of
823 /// whether a value in this or other is a copy from the opposite set.
824 /// ThisValNoAssignments/OtherValNoAssignments keep track of value #'s that have
825 /// already been assigned.
826 ///
827 /// ThisFromOther[x] - If x is defined as a copy from the other interval, this
828 /// contains the value number the copy is from.
829 ///
830 static unsigned ComputeUltimateVN(VNInfo *VNI,
831                                   SmallVector<VNInfo*, 16> &NewVNInfo,
832                                   DenseMap<VNInfo*, VNInfo*> &ThisFromOther,
833                                   DenseMap<VNInfo*, VNInfo*> &OtherFromThis,
834                                   SmallVector<int, 16> &ThisValNoAssignments,
835                                   SmallVector<int, 16> &OtherValNoAssignments) {
836   unsigned VN = VNI->id;
837
838   // If the VN has already been computed, just return it.
839   if (ThisValNoAssignments[VN] >= 0)
840     return ThisValNoAssignments[VN];
841 //  assert(ThisValNoAssignments[VN] != -2 && "Cyclic case?");
842
843   // If this val is not a copy from the other val, then it must be a new value
844   // number in the destination.
845   DenseMap<VNInfo*, VNInfo*>::iterator I = ThisFromOther.find(VNI);
846   if (I == ThisFromOther.end()) {
847     NewVNInfo.push_back(VNI);
848     return ThisValNoAssignments[VN] = NewVNInfo.size()-1;
849   }
850   VNInfo *OtherValNo = I->second;
851
852   // Otherwise, this *is* a copy from the RHS.  If the other side has already
853   // been computed, return it.
854   if (OtherValNoAssignments[OtherValNo->id] >= 0)
855     return ThisValNoAssignments[VN] = OtherValNoAssignments[OtherValNo->id];
856   
857   // Mark this value number as currently being computed, then ask what the
858   // ultimate value # of the other value is.
859   ThisValNoAssignments[VN] = -2;
860   unsigned UltimateVN =
861     ComputeUltimateVN(OtherValNo, NewVNInfo, OtherFromThis, ThisFromOther,
862                       OtherValNoAssignments, ThisValNoAssignments);
863   return ThisValNoAssignments[VN] = UltimateVN;
864 }
865
866 static bool InVector(VNInfo *Val, const SmallVector<VNInfo*, 8> &V) {
867   return std::find(V.begin(), V.end(), Val) != V.end();
868 }
869
870 /// SimpleJoin - Attempt to joint the specified interval into this one. The
871 /// caller of this method must guarantee that the RHS only contains a single
872 /// value number and that the RHS is not defined by a copy from this
873 /// interval.  This returns false if the intervals are not joinable, or it
874 /// joins them and returns true.
875 bool SimpleRegisterCoalescing::SimpleJoin(LiveInterval &LHS, LiveInterval &RHS){
876   assert(RHS.containsOneValue());
877   
878   // Some number (potentially more than one) value numbers in the current
879   // interval may be defined as copies from the RHS.  Scan the overlapping
880   // portions of the LHS and RHS, keeping track of this and looking for
881   // overlapping live ranges that are NOT defined as copies.  If these exist, we
882   // cannot coalesce.
883   
884   LiveInterval::iterator LHSIt = LHS.begin(), LHSEnd = LHS.end();
885   LiveInterval::iterator RHSIt = RHS.begin(), RHSEnd = RHS.end();
886   
887   if (LHSIt->start < RHSIt->start) {
888     LHSIt = std::upper_bound(LHSIt, LHSEnd, RHSIt->start);
889     if (LHSIt != LHS.begin()) --LHSIt;
890   } else if (RHSIt->start < LHSIt->start) {
891     RHSIt = std::upper_bound(RHSIt, RHSEnd, LHSIt->start);
892     if (RHSIt != RHS.begin()) --RHSIt;
893   }
894   
895   SmallVector<VNInfo*, 8> EliminatedLHSVals;
896   
897   while (1) {
898     // Determine if these live intervals overlap.
899     bool Overlaps = false;
900     if (LHSIt->start <= RHSIt->start)
901       Overlaps = LHSIt->end > RHSIt->start;
902     else
903       Overlaps = RHSIt->end > LHSIt->start;
904     
905     // If the live intervals overlap, there are two interesting cases: if the
906     // LHS interval is defined by a copy from the RHS, it's ok and we record
907     // that the LHS value # is the same as the RHS.  If it's not, then we cannot
908     // coalesce these live ranges and we bail out.
909     if (Overlaps) {
910       // If we haven't already recorded that this value # is safe, check it.
911       if (!InVector(LHSIt->valno, EliminatedLHSVals)) {
912         // Copy from the RHS?
913         unsigned SrcReg = li_->getVNInfoSourceReg(LHSIt->valno);
914         if (SrcReg != RHS.reg)
915           return false;    // Nope, bail out.
916         
917         EliminatedLHSVals.push_back(LHSIt->valno);
918       }
919       
920       // We know this entire LHS live range is okay, so skip it now.
921       if (++LHSIt == LHSEnd) break;
922       continue;
923     }
924     
925     if (LHSIt->end < RHSIt->end) {
926       if (++LHSIt == LHSEnd) break;
927     } else {
928       // One interesting case to check here.  It's possible that we have
929       // something like "X3 = Y" which defines a new value number in the LHS,
930       // and is the last use of this liverange of the RHS.  In this case, we
931       // want to notice this copy (so that it gets coalesced away) even though
932       // the live ranges don't actually overlap.
933       if (LHSIt->start == RHSIt->end) {
934         if (InVector(LHSIt->valno, EliminatedLHSVals)) {
935           // We already know that this value number is going to be merged in
936           // if coalescing succeeds.  Just skip the liverange.
937           if (++LHSIt == LHSEnd) break;
938         } else {
939           // Otherwise, if this is a copy from the RHS, mark it as being merged
940           // in.
941           if (li_->getVNInfoSourceReg(LHSIt->valno) == RHS.reg) {
942             EliminatedLHSVals.push_back(LHSIt->valno);
943
944             // We know this entire LHS live range is okay, so skip it now.
945             if (++LHSIt == LHSEnd) break;
946           }
947         }
948       }
949       
950       if (++RHSIt == RHSEnd) break;
951     }
952   }
953   
954   // If we got here, we know that the coalescing will be successful and that
955   // the value numbers in EliminatedLHSVals will all be merged together.  Since
956   // the most common case is that EliminatedLHSVals has a single number, we
957   // optimize for it: if there is more than one value, we merge them all into
958   // the lowest numbered one, then handle the interval as if we were merging
959   // with one value number.
960   VNInfo *LHSValNo;
961   if (EliminatedLHSVals.size() > 1) {
962     // Loop through all the equal value numbers merging them into the smallest
963     // one.
964     VNInfo *Smallest = EliminatedLHSVals[0];
965     for (unsigned i = 1, e = EliminatedLHSVals.size(); i != e; ++i) {
966       if (EliminatedLHSVals[i]->id < Smallest->id) {
967         // Merge the current notion of the smallest into the smaller one.
968         LHS.MergeValueNumberInto(Smallest, EliminatedLHSVals[i]);
969         Smallest = EliminatedLHSVals[i];
970       } else {
971         // Merge into the smallest.
972         LHS.MergeValueNumberInto(EliminatedLHSVals[i], Smallest);
973       }
974     }
975     LHSValNo = Smallest;
976   } else {
977     assert(!EliminatedLHSVals.empty() && "No copies from the RHS?");
978     LHSValNo = EliminatedLHSVals[0];
979   }
980   
981   // Okay, now that there is a single LHS value number that we're merging the
982   // RHS into, update the value number info for the LHS to indicate that the
983   // value number is defined where the RHS value number was.
984   const VNInfo *VNI = RHS.getValNumInfo(0);
985   LHSValNo->def  = VNI->def;
986   LHSValNo->copy = VNI->copy;
987   
988   // Okay, the final step is to loop over the RHS live intervals, adding them to
989   // the LHS.
990   LHSValNo->hasPHIKill |= VNI->hasPHIKill;
991   LHS.addKills(LHSValNo, VNI->kills);
992   LHS.MergeRangesInAsValue(RHS, LHSValNo);
993   LHS.weight += RHS.weight;
994   if (RHS.preference && !LHS.preference)
995     LHS.preference = RHS.preference;
996   
997   return true;
998 }
999
1000 /// JoinIntervals - Attempt to join these two intervals.  On failure, this
1001 /// returns false.  Otherwise, if one of the intervals being joined is a
1002 /// physreg, this method always canonicalizes LHS to be it.  The output
1003 /// "RHS" will not have been modified, so we can use this information
1004 /// below to update aliases.
1005 bool SimpleRegisterCoalescing::JoinIntervals(LiveInterval &LHS,
1006                                              LiveInterval &RHS, bool &Swapped) {
1007   // Compute the final value assignment, assuming that the live ranges can be
1008   // coalesced.
1009   SmallVector<int, 16> LHSValNoAssignments;
1010   SmallVector<int, 16> RHSValNoAssignments;
1011   DenseMap<VNInfo*, VNInfo*> LHSValsDefinedFromRHS;
1012   DenseMap<VNInfo*, VNInfo*> RHSValsDefinedFromLHS;
1013   SmallVector<VNInfo*, 16> NewVNInfo;
1014                           
1015   // If a live interval is a physical register, conservatively check if any
1016   // of its sub-registers is overlapping the live interval of the virtual
1017   // register. If so, do not coalesce.
1018   if (TargetRegisterInfo::isPhysicalRegister(LHS.reg) &&
1019       *tri_->getSubRegisters(LHS.reg)) {
1020     for (const unsigned* SR = tri_->getSubRegisters(LHS.reg); *SR; ++SR)
1021       if (li_->hasInterval(*SR) && RHS.overlaps(li_->getInterval(*SR))) {
1022         DOUT << "Interfere with sub-register ";
1023         DEBUG(li_->getInterval(*SR).print(DOUT, tri_));
1024         return false;
1025       }
1026   } else if (TargetRegisterInfo::isPhysicalRegister(RHS.reg) &&
1027              *tri_->getSubRegisters(RHS.reg)) {
1028     for (const unsigned* SR = tri_->getSubRegisters(RHS.reg); *SR; ++SR)
1029       if (li_->hasInterval(*SR) && LHS.overlaps(li_->getInterval(*SR))) {
1030         DOUT << "Interfere with sub-register ";
1031         DEBUG(li_->getInterval(*SR).print(DOUT, tri_));
1032         return false;
1033       }
1034   }
1035                           
1036   // Compute ultimate value numbers for the LHS and RHS values.
1037   if (RHS.containsOneValue()) {
1038     // Copies from a liveinterval with a single value are simple to handle and
1039     // very common, handle the special case here.  This is important, because
1040     // often RHS is small and LHS is large (e.g. a physreg).
1041     
1042     // Find out if the RHS is defined as a copy from some value in the LHS.
1043     int RHSVal0DefinedFromLHS = -1;
1044     int RHSValID = -1;
1045     VNInfo *RHSValNoInfo = NULL;
1046     VNInfo *RHSValNoInfo0 = RHS.getValNumInfo(0);
1047     unsigned RHSSrcReg = li_->getVNInfoSourceReg(RHSValNoInfo0);
1048     if ((RHSSrcReg == 0 || RHSSrcReg != LHS.reg)) {
1049       // If RHS is not defined as a copy from the LHS, we can use simpler and
1050       // faster checks to see if the live ranges are coalescable.  This joiner
1051       // can't swap the LHS/RHS intervals though.
1052       if (!TargetRegisterInfo::isPhysicalRegister(RHS.reg)) {
1053         return SimpleJoin(LHS, RHS);
1054       } else {
1055         RHSValNoInfo = RHSValNoInfo0;
1056       }
1057     } else {
1058       // It was defined as a copy from the LHS, find out what value # it is.
1059       RHSValNoInfo = LHS.getLiveRangeContaining(RHSValNoInfo0->def-1)->valno;
1060       RHSValID = RHSValNoInfo->id;
1061       RHSVal0DefinedFromLHS = RHSValID;
1062     }
1063     
1064     LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
1065     RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
1066     NewVNInfo.resize(LHS.getNumValNums(), NULL);
1067     
1068     // Okay, *all* of the values in LHS that are defined as a copy from RHS
1069     // should now get updated.
1070     for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1071          i != e; ++i) {
1072       VNInfo *VNI = *i;
1073       unsigned VN = VNI->id;
1074       if (unsigned LHSSrcReg = li_->getVNInfoSourceReg(VNI)) {
1075         if (LHSSrcReg != RHS.reg) {
1076           // If this is not a copy from the RHS, its value number will be
1077           // unmodified by the coalescing.
1078           NewVNInfo[VN] = VNI;
1079           LHSValNoAssignments[VN] = VN;
1080         } else if (RHSValID == -1) {
1081           // Otherwise, it is a copy from the RHS, and we don't already have a
1082           // value# for it.  Keep the current value number, but remember it.
1083           LHSValNoAssignments[VN] = RHSValID = VN;
1084           NewVNInfo[VN] = RHSValNoInfo;
1085           LHSValsDefinedFromRHS[VNI] = RHSValNoInfo0;
1086         } else {
1087           // Otherwise, use the specified value #.
1088           LHSValNoAssignments[VN] = RHSValID;
1089           if (VN == (unsigned)RHSValID) {  // Else this val# is dead.
1090             NewVNInfo[VN] = RHSValNoInfo;
1091             LHSValsDefinedFromRHS[VNI] = RHSValNoInfo0;
1092           }
1093         }
1094       } else {
1095         NewVNInfo[VN] = VNI;
1096         LHSValNoAssignments[VN] = VN;
1097       }
1098     }
1099     
1100     assert(RHSValID != -1 && "Didn't find value #?");
1101     RHSValNoAssignments[0] = RHSValID;
1102     if (RHSVal0DefinedFromLHS != -1) {
1103       // This path doesn't go through ComputeUltimateVN so just set
1104       // it to anything.
1105       RHSValsDefinedFromLHS[RHSValNoInfo0] = (VNInfo*)1;
1106     }
1107   } else {
1108     // Loop over the value numbers of the LHS, seeing if any are defined from
1109     // the RHS.
1110     for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1111          i != e; ++i) {
1112       VNInfo *VNI = *i;
1113       if (VNI->def == ~1U || VNI->copy == 0)  // Src not defined by a copy?
1114         continue;
1115       
1116       // DstReg is known to be a register in the LHS interval.  If the src is
1117       // from the RHS interval, we can use its value #.
1118       if (li_->getVNInfoSourceReg(VNI) != RHS.reg)
1119         continue;
1120       
1121       // Figure out the value # from the RHS.
1122       LHSValsDefinedFromRHS[VNI]=RHS.getLiveRangeContaining(VNI->def-1)->valno;
1123     }
1124     
1125     // Loop over the value numbers of the RHS, seeing if any are defined from
1126     // the LHS.
1127     for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
1128          i != e; ++i) {
1129       VNInfo *VNI = *i;
1130       if (VNI->def == ~1U || VNI->copy == 0)  // Src not defined by a copy?
1131         continue;
1132       
1133       // DstReg is known to be a register in the RHS interval.  If the src is
1134       // from the LHS interval, we can use its value #.
1135       if (li_->getVNInfoSourceReg(VNI) != LHS.reg)
1136         continue;
1137       
1138       // Figure out the value # from the LHS.
1139       RHSValsDefinedFromLHS[VNI]=LHS.getLiveRangeContaining(VNI->def-1)->valno;
1140     }
1141     
1142     LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
1143     RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
1144     NewVNInfo.reserve(LHS.getNumValNums() + RHS.getNumValNums());
1145     
1146     for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1147          i != e; ++i) {
1148       VNInfo *VNI = *i;
1149       unsigned VN = VNI->id;
1150       if (LHSValNoAssignments[VN] >= 0 || VNI->def == ~1U) 
1151         continue;
1152       ComputeUltimateVN(VNI, NewVNInfo,
1153                         LHSValsDefinedFromRHS, RHSValsDefinedFromLHS,
1154                         LHSValNoAssignments, RHSValNoAssignments);
1155     }
1156     for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
1157          i != e; ++i) {
1158       VNInfo *VNI = *i;
1159       unsigned VN = VNI->id;
1160       if (RHSValNoAssignments[VN] >= 0 || VNI->def == ~1U)
1161         continue;
1162       // If this value number isn't a copy from the LHS, it's a new number.
1163       if (RHSValsDefinedFromLHS.find(VNI) == RHSValsDefinedFromLHS.end()) {
1164         NewVNInfo.push_back(VNI);
1165         RHSValNoAssignments[VN] = NewVNInfo.size()-1;
1166         continue;
1167       }
1168       
1169       ComputeUltimateVN(VNI, NewVNInfo,
1170                         RHSValsDefinedFromLHS, LHSValsDefinedFromRHS,
1171                         RHSValNoAssignments, LHSValNoAssignments);
1172     }
1173   }
1174   
1175   // Armed with the mappings of LHS/RHS values to ultimate values, walk the
1176   // interval lists to see if these intervals are coalescable.
1177   LiveInterval::const_iterator I = LHS.begin();
1178   LiveInterval::const_iterator IE = LHS.end();
1179   LiveInterval::const_iterator J = RHS.begin();
1180   LiveInterval::const_iterator JE = RHS.end();
1181   
1182   // Skip ahead until the first place of potential sharing.
1183   if (I->start < J->start) {
1184     I = std::upper_bound(I, IE, J->start);
1185     if (I != LHS.begin()) --I;
1186   } else if (J->start < I->start) {
1187     J = std::upper_bound(J, JE, I->start);
1188     if (J != RHS.begin()) --J;
1189   }
1190   
1191   while (1) {
1192     // Determine if these two live ranges overlap.
1193     bool Overlaps;
1194     if (I->start < J->start) {
1195       Overlaps = I->end > J->start;
1196     } else {
1197       Overlaps = J->end > I->start;
1198     }
1199
1200     // If so, check value # info to determine if they are really different.
1201     if (Overlaps) {
1202       // If the live range overlap will map to the same value number in the
1203       // result liverange, we can still coalesce them.  If not, we can't.
1204       if (LHSValNoAssignments[I->valno->id] !=
1205           RHSValNoAssignments[J->valno->id])
1206         return false;
1207     }
1208     
1209     if (I->end < J->end) {
1210       ++I;
1211       if (I == IE) break;
1212     } else {
1213       ++J;
1214       if (J == JE) break;
1215     }
1216   }
1217
1218   // Update kill info. Some live ranges are extended due to copy coalescing.
1219   for (DenseMap<VNInfo*, VNInfo*>::iterator I = LHSValsDefinedFromRHS.begin(),
1220          E = LHSValsDefinedFromRHS.end(); I != E; ++I) {
1221     VNInfo *VNI = I->first;
1222     unsigned LHSValID = LHSValNoAssignments[VNI->id];
1223     LiveInterval::removeKill(NewVNInfo[LHSValID], VNI->def);
1224     NewVNInfo[LHSValID]->hasPHIKill |= VNI->hasPHIKill;
1225     RHS.addKills(NewVNInfo[LHSValID], VNI->kills);
1226   }
1227
1228   // Update kill info. Some live ranges are extended due to copy coalescing.
1229   for (DenseMap<VNInfo*, VNInfo*>::iterator I = RHSValsDefinedFromLHS.begin(),
1230          E = RHSValsDefinedFromLHS.end(); I != E; ++I) {
1231     VNInfo *VNI = I->first;
1232     unsigned RHSValID = RHSValNoAssignments[VNI->id];
1233     LiveInterval::removeKill(NewVNInfo[RHSValID], VNI->def);
1234     NewVNInfo[RHSValID]->hasPHIKill |= VNI->hasPHIKill;
1235     LHS.addKills(NewVNInfo[RHSValID], VNI->kills);
1236   }
1237
1238   // If we get here, we know that we can coalesce the live ranges.  Ask the
1239   // intervals to coalesce themselves now.
1240   if ((RHS.ranges.size() > LHS.ranges.size() &&
1241       TargetRegisterInfo::isVirtualRegister(LHS.reg)) ||
1242       TargetRegisterInfo::isPhysicalRegister(RHS.reg)) {
1243     RHS.join(LHS, &RHSValNoAssignments[0], &LHSValNoAssignments[0], NewVNInfo);
1244     Swapped = true;
1245   } else {
1246     LHS.join(RHS, &LHSValNoAssignments[0], &RHSValNoAssignments[0], NewVNInfo);
1247     Swapped = false;
1248   }
1249   return true;
1250 }
1251
1252 namespace {
1253   // DepthMBBCompare - Comparison predicate that sort first based on the loop
1254   // depth of the basic block (the unsigned), and then on the MBB number.
1255   struct DepthMBBCompare {
1256     typedef std::pair<unsigned, MachineBasicBlock*> DepthMBBPair;
1257     bool operator()(const DepthMBBPair &LHS, const DepthMBBPair &RHS) const {
1258       if (LHS.first > RHS.first) return true;   // Deeper loops first
1259       return LHS.first == RHS.first &&
1260         LHS.second->getNumber() < RHS.second->getNumber();
1261     }
1262   };
1263 }
1264
1265 /// getRepIntervalSize - Returns the size of the interval that represents the
1266 /// specified register.
1267 template<class SF>
1268 unsigned JoinPriorityQueue<SF>::getRepIntervalSize(unsigned Reg) {
1269   return Rc->getRepIntervalSize(Reg);
1270 }
1271
1272 /// CopyRecSort::operator - Join priority queue sorting function.
1273 ///
1274 bool CopyRecSort::operator()(CopyRec left, CopyRec right) const {
1275   // Inner loops first.
1276   if (left.LoopDepth > right.LoopDepth)
1277     return false;
1278   else if (left.LoopDepth == right.LoopDepth)
1279     if (left.isBackEdge && !right.isBackEdge)
1280       return false;
1281   return true;
1282 }
1283
1284 void SimpleRegisterCoalescing::CopyCoalesceInMBB(MachineBasicBlock *MBB,
1285                                                std::vector<CopyRec> &TryAgain) {
1286   DOUT << ((Value*)MBB->getBasicBlock())->getName() << ":\n";
1287
1288   std::vector<CopyRec> VirtCopies;
1289   std::vector<CopyRec> PhysCopies;
1290   unsigned LoopDepth = loopInfo->getLoopDepth(MBB);
1291   for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end();
1292        MII != E;) {
1293     MachineInstr *Inst = MII++;
1294     
1295     // If this isn't a copy nor a extract_subreg, we can't join intervals.
1296     unsigned SrcReg, DstReg;
1297     if (Inst->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG) {
1298       DstReg = Inst->getOperand(0).getReg();
1299       SrcReg = Inst->getOperand(1).getReg();
1300     } else if (!tii_->isMoveInstr(*Inst, SrcReg, DstReg))
1301       continue;
1302
1303     bool SrcIsPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
1304     bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
1305     if (NewHeuristic) {
1306       JoinQueue->push(CopyRec(Inst, LoopDepth, isBackEdgeCopy(Inst, DstReg)));
1307     } else {
1308       if (SrcIsPhys || DstIsPhys)
1309         PhysCopies.push_back(CopyRec(Inst, 0, false));
1310       else
1311         VirtCopies.push_back(CopyRec(Inst, 0, false));
1312     }
1313   }
1314
1315   if (NewHeuristic)
1316     return;
1317
1318   // Try coalescing physical register + virtual register first.
1319   for (unsigned i = 0, e = PhysCopies.size(); i != e; ++i) {
1320     CopyRec &TheCopy = PhysCopies[i];
1321     bool Again = false;
1322     if (!JoinCopy(TheCopy, Again))
1323       if (Again)
1324         TryAgain.push_back(TheCopy);
1325   }
1326   for (unsigned i = 0, e = VirtCopies.size(); i != e; ++i) {
1327     CopyRec &TheCopy = VirtCopies[i];
1328     bool Again = false;
1329     if (!JoinCopy(TheCopy, Again))
1330       if (Again)
1331         TryAgain.push_back(TheCopy);
1332   }
1333 }
1334
1335 void SimpleRegisterCoalescing::joinIntervals() {
1336   DOUT << "********** JOINING INTERVALS ***********\n";
1337
1338   if (NewHeuristic)
1339     JoinQueue = new JoinPriorityQueue<CopyRecSort>(this);
1340
1341   std::vector<CopyRec> TryAgainList;
1342   if (loopInfo->begin() == loopInfo->end()) {
1343     // If there are no loops in the function, join intervals in function order.
1344     for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();
1345          I != E; ++I)
1346       CopyCoalesceInMBB(I, TryAgainList);
1347   } else {
1348     // Otherwise, join intervals in inner loops before other intervals.
1349     // Unfortunately we can't just iterate over loop hierarchy here because
1350     // there may be more MBB's than BB's.  Collect MBB's for sorting.
1351
1352     // Join intervals in the function prolog first. We want to join physical
1353     // registers with virtual registers before the intervals got too long.
1354     std::vector<std::pair<unsigned, MachineBasicBlock*> > MBBs;
1355     for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();I != E;++I){
1356       MachineBasicBlock *MBB = I;
1357       MBBs.push_back(std::make_pair(loopInfo->getLoopDepth(MBB), I));
1358     }
1359
1360     // Sort by loop depth.
1361     std::sort(MBBs.begin(), MBBs.end(), DepthMBBCompare());
1362
1363     // Finally, join intervals in loop nest order.
1364     for (unsigned i = 0, e = MBBs.size(); i != e; ++i)
1365       CopyCoalesceInMBB(MBBs[i].second, TryAgainList);
1366   }
1367   
1368   // Joining intervals can allow other intervals to be joined.  Iteratively join
1369   // until we make no progress.
1370   if (NewHeuristic) {
1371     SmallVector<CopyRec, 16> TryAgain;
1372     bool ProgressMade = true;
1373     while (ProgressMade) {
1374       ProgressMade = false;
1375       while (!JoinQueue->empty()) {
1376         CopyRec R = JoinQueue->pop();
1377         bool Again = false;
1378         bool Success = JoinCopy(R, Again);
1379         if (Success)
1380           ProgressMade = true;
1381         else if (Again)
1382           TryAgain.push_back(R);
1383       }
1384
1385       if (ProgressMade) {
1386         while (!TryAgain.empty()) {
1387           JoinQueue->push(TryAgain.back());
1388           TryAgain.pop_back();
1389         }
1390       }
1391     }
1392   } else {
1393     bool ProgressMade = true;
1394     while (ProgressMade) {
1395       ProgressMade = false;
1396
1397       for (unsigned i = 0, e = TryAgainList.size(); i != e; ++i) {
1398         CopyRec &TheCopy = TryAgainList[i];
1399         if (TheCopy.MI) {
1400           bool Again = false;
1401           bool Success = JoinCopy(TheCopy, Again);
1402           if (Success || !Again) {
1403             TheCopy.MI = 0;   // Mark this one as done.
1404             ProgressMade = true;
1405           }
1406         }
1407       }
1408     }
1409   }
1410
1411   if (NewHeuristic)
1412     delete JoinQueue;  
1413 }
1414
1415 /// Return true if the two specified registers belong to different register
1416 /// classes.  The registers may be either phys or virt regs.
1417 bool SimpleRegisterCoalescing::differingRegisterClasses(unsigned RegA,
1418                                                         unsigned RegB) const {
1419
1420   // Get the register classes for the first reg.
1421   if (TargetRegisterInfo::isPhysicalRegister(RegA)) {
1422     assert(TargetRegisterInfo::isVirtualRegister(RegB) &&
1423            "Shouldn't consider two physregs!");
1424     return !mri_->getRegClass(RegB)->contains(RegA);
1425   }
1426
1427   // Compare against the regclass for the second reg.
1428   const TargetRegisterClass *RegClass = mri_->getRegClass(RegA);
1429   if (TargetRegisterInfo::isVirtualRegister(RegB))
1430     return RegClass != mri_->getRegClass(RegB);
1431   else
1432     return !RegClass->contains(RegB);
1433 }
1434
1435 /// lastRegisterUse - Returns the last use of the specific register between
1436 /// cycles Start and End or NULL if there are no uses.
1437 MachineOperand *
1438 SimpleRegisterCoalescing::lastRegisterUse(unsigned Start, unsigned End,
1439                                           unsigned Reg, unsigned &UseIdx) const{
1440   UseIdx = 0;
1441   if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1442     MachineOperand *LastUse = NULL;
1443     for (MachineRegisterInfo::use_iterator I = mri_->use_begin(Reg),
1444            E = mri_->use_end(); I != E; ++I) {
1445       MachineOperand &Use = I.getOperand();
1446       MachineInstr *UseMI = Use.getParent();
1447       unsigned Idx = li_->getInstructionIndex(UseMI);
1448       if (Idx >= Start && Idx < End && Idx >= UseIdx) {
1449         LastUse = &Use;
1450         UseIdx = Idx;
1451       }
1452     }
1453     return LastUse;
1454   }
1455
1456   int e = (End-1) / InstrSlots::NUM * InstrSlots::NUM;
1457   int s = Start;
1458   while (e >= s) {
1459     // Skip deleted instructions
1460     MachineInstr *MI = li_->getInstructionFromIndex(e);
1461     while ((e - InstrSlots::NUM) >= s && !MI) {
1462       e -= InstrSlots::NUM;
1463       MI = li_->getInstructionFromIndex(e);
1464     }
1465     if (e < s || MI == NULL)
1466       return NULL;
1467
1468     for (unsigned i = 0, NumOps = MI->getNumOperands(); i != NumOps; ++i) {
1469       MachineOperand &Use = MI->getOperand(i);
1470       if (Use.isRegister() && Use.isUse() && Use.getReg() &&
1471           tri_->regsOverlap(Use.getReg(), Reg)) {
1472         UseIdx = e;
1473         return &Use;
1474       }
1475     }
1476
1477     e -= InstrSlots::NUM;
1478   }
1479
1480   return NULL;
1481 }
1482
1483
1484 /// findDefOperand - Returns the MachineOperand that is a def of the specific
1485 /// register. It returns NULL if the def is not found.
1486 MachineOperand *SimpleRegisterCoalescing::findDefOperand(MachineInstr *MI,
1487                                                          unsigned Reg) const {
1488   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1489     MachineOperand &MO = MI->getOperand(i);
1490     if (MO.isRegister() && MO.isDef() &&
1491         tri_->regsOverlap(MO.getReg(), Reg))
1492       return &MO;
1493   }
1494   return NULL;
1495 }
1496
1497 /// unsetRegisterKills - Unset IsKill property of all uses of specific register
1498 /// between cycles Start and End.
1499 void SimpleRegisterCoalescing::unsetRegisterKills(unsigned Start, unsigned End,
1500                                                   unsigned Reg) {
1501   int e = (End-1) / InstrSlots::NUM * InstrSlots::NUM;
1502   int s = Start;
1503   while (e >= s) {
1504     // Skip deleted instructions
1505     MachineInstr *MI = li_->getInstructionFromIndex(e);
1506     while ((e - InstrSlots::NUM) >= s && !MI) {
1507       e -= InstrSlots::NUM;
1508       MI = li_->getInstructionFromIndex(e);
1509     }
1510     if (e < s || MI == NULL)
1511       return;
1512
1513     for (unsigned i = 0, NumOps = MI->getNumOperands(); i != NumOps; ++i) {
1514       MachineOperand &MO = MI->getOperand(i);
1515       if (MO.isRegister() && MO.isKill() && MO.getReg() &&
1516           tri_->regsOverlap(MO.getReg(), Reg)) {
1517         MO.setIsKill(false);
1518       }
1519     }
1520
1521     e -= InstrSlots::NUM;
1522   }
1523 }
1524
1525 void SimpleRegisterCoalescing::printRegName(unsigned reg) const {
1526   if (TargetRegisterInfo::isPhysicalRegister(reg))
1527     cerr << tri_->getName(reg);
1528   else
1529     cerr << "%reg" << reg;
1530 }
1531
1532 void SimpleRegisterCoalescing::releaseMemory() {
1533   JoinedCopies.clear();
1534 }
1535
1536 static bool isZeroLengthInterval(LiveInterval *li) {
1537   for (LiveInterval::Ranges::const_iterator
1538          i = li->ranges.begin(), e = li->ranges.end(); i != e; ++i)
1539     if (i->end - i->start > LiveIntervals::InstrSlots::NUM)
1540       return false;
1541   return true;
1542 }
1543
1544 bool SimpleRegisterCoalescing::runOnMachineFunction(MachineFunction &fn) {
1545   mf_ = &fn;
1546   mri_ = &fn.getRegInfo();
1547   tm_ = &fn.getTarget();
1548   tri_ = tm_->getRegisterInfo();
1549   tii_ = tm_->getInstrInfo();
1550   li_ = &getAnalysis<LiveIntervals>();
1551   lv_ = &getAnalysis<LiveVariables>();
1552   loopInfo = &getAnalysis<MachineLoopInfo>();
1553
1554   DOUT << "********** SIMPLE REGISTER COALESCING **********\n"
1555        << "********** Function: "
1556        << ((Value*)mf_->getFunction())->getName() << '\n';
1557
1558   allocatableRegs_ = tri_->getAllocatableSet(fn);
1559   for (TargetRegisterInfo::regclass_iterator I = tri_->regclass_begin(),
1560          E = tri_->regclass_end(); I != E; ++I)
1561     allocatableRCRegs_.insert(std::make_pair(*I,
1562                                              tri_->getAllocatableSet(fn, *I)));
1563
1564   // Join (coalesce) intervals if requested.
1565   if (EnableJoining) {
1566     joinIntervals();
1567     DOUT << "********** INTERVALS POST JOINING **********\n";
1568     for (LiveIntervals::iterator I = li_->begin(), E = li_->end(); I != E; ++I){
1569       I->second.print(DOUT, tri_);
1570       DOUT << "\n";
1571     }
1572
1573     // Delete all coalesced copies.
1574     for (SmallPtrSet<MachineInstr*,32>::iterator I = JoinedCopies.begin(),
1575            E = JoinedCopies.end(); I != E; ++I) {
1576       li_->RemoveMachineInstrFromMaps(*I);
1577       (*I)->eraseFromParent();
1578       ++numPeep;
1579     }
1580   }
1581
1582   // Perform a final pass over the instructions and compute spill weights
1583   // and remove identity moves.
1584   for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
1585        mbbi != mbbe; ++mbbi) {
1586     MachineBasicBlock* mbb = mbbi;
1587     unsigned loopDepth = loopInfo->getLoopDepth(mbb);
1588
1589     for (MachineBasicBlock::iterator mii = mbb->begin(), mie = mbb->end();
1590          mii != mie; ) {
1591       // if the move will be an identity move delete it
1592       unsigned srcReg, dstReg;
1593       if (tii_->isMoveInstr(*mii, srcReg, dstReg) && srcReg == dstReg) {
1594         // remove from def list
1595         LiveInterval &RegInt = li_->getOrCreateInterval(srcReg);
1596         MachineOperand *MO = mii->findRegisterDefOperand(dstReg);
1597         // If def of this move instruction is dead, remove its live range from
1598         // the dstination register's live interval.
1599         if (MO->isDead()) {
1600           unsigned MoveIdx = li_->getDefIndex(li_->getInstructionIndex(mii));
1601           LiveInterval::iterator MLR = RegInt.FindLiveRangeContaining(MoveIdx);
1602           RegInt.removeRange(MLR->start, MoveIdx+1, true);
1603           if (RegInt.empty())
1604             li_->removeInterval(srcReg);
1605         }
1606         li_->RemoveMachineInstrFromMaps(mii);
1607         mii = mbbi->erase(mii);
1608         ++numPeep;
1609       } else {
1610         SmallSet<unsigned, 4> UniqueUses;
1611         for (unsigned i = 0, e = mii->getNumOperands(); i != e; ++i) {
1612           const MachineOperand &mop = mii->getOperand(i);
1613           if (mop.isRegister() && mop.getReg() &&
1614               TargetRegisterInfo::isVirtualRegister(mop.getReg())) {
1615             unsigned reg = mop.getReg();
1616             // Multiple uses of reg by the same instruction. It should not
1617             // contribute to spill weight again.
1618             if (UniqueUses.count(reg) != 0)
1619               continue;
1620             LiveInterval &RegInt = li_->getInterval(reg);
1621             RegInt.weight +=
1622               li_->getSpillWeight(mop.isDef(), mop.isUse(), loopDepth);
1623             UniqueUses.insert(reg);
1624           }
1625         }
1626         ++mii;
1627       }
1628     }
1629   }
1630
1631   for (LiveIntervals::iterator I = li_->begin(), E = li_->end(); I != E; ++I) {
1632     LiveInterval &LI = I->second;
1633     if (TargetRegisterInfo::isVirtualRegister(LI.reg)) {
1634       // If the live interval length is essentially zero, i.e. in every live
1635       // range the use follows def immediately, it doesn't make sense to spill
1636       // it and hope it will be easier to allocate for this li.
1637       if (isZeroLengthInterval(&LI))
1638         LI.weight = HUGE_VALF;
1639       else {
1640         bool isLoad = false;
1641         if (li_->isReMaterializable(LI, isLoad)) {
1642           // If all of the definitions of the interval are re-materializable,
1643           // it is a preferred candidate for spilling. If non of the defs are
1644           // loads, then it's potentially very cheap to re-materialize.
1645           // FIXME: this gets much more complicated once we support non-trivial
1646           // re-materialization.
1647           if (isLoad)
1648             LI.weight *= 0.9F;
1649           else
1650             LI.weight *= 0.5F;
1651         }
1652       }
1653
1654       // Slightly prefer live interval that has been assigned a preferred reg.
1655       if (LI.preference)
1656         LI.weight *= 1.01F;
1657
1658       // Divide the weight of the interval by its size.  This encourages 
1659       // spilling of intervals that are large and have few uses, and
1660       // discourages spilling of small intervals with many uses.
1661       LI.weight /= LI.getSize();
1662     }
1663   }
1664
1665   DEBUG(dump());
1666   return true;
1667 }
1668
1669 /// print - Implement the dump method.
1670 void SimpleRegisterCoalescing::print(std::ostream &O, const Module* m) const {
1671    li_->print(O, m);
1672 }
1673
1674 RegisterCoalescer* llvm::createSimpleRegisterCoalescer() {
1675   return new SimpleRegisterCoalescing();
1676 }
1677
1678 // Make sure that anything that uses RegisterCoalescer pulls in this file...
1679 DEFINING_FILE_FOR(SimpleRegisterCoalescing)