Go back to passing the analyses around as parameters.
[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   RegisterPass<SimpleRegisterCoalescing> 
57   X("simple-register-coalescing", "Simple Register Coalescing");
58
59   // Declare that we implement the RegisterCoalescer interface
60   RegisterAnalysisGroup<RegisterCoalescer, true/*The Default*/> V(X);
61 }
62
63 const PassInfo *llvm::SimpleRegisterCoalescingID = X.getPassInfo();
64
65 void SimpleRegisterCoalescing::getAnalysisUsage(AnalysisUsage &AU) const {
66   AU.addPreserved<LiveIntervals>();
67   AU.addPreserved<MachineLoopInfo>();
68   AU.addPreservedID(MachineDominatorsID);
69   AU.addPreservedID(PHIEliminationID);
70   AU.addPreservedID(TwoAddressInstructionPassID);
71   AU.addRequired<LiveVariables>();
72   AU.addRequired<LiveIntervals>();
73   AU.addRequired<MachineLoopInfo>();
74   MachineFunctionPass::getAnalysisUsage(AU);
75 }
76
77 /// AdjustCopiesBackFrom - We found a non-trivially-coalescable copy with IntA
78 /// being the source and IntB being the dest, thus this defines a value number
79 /// in IntB.  If the source value number (in IntA) is defined by a copy from B,
80 /// see if we can merge these two pieces of B into a single value number,
81 /// eliminating a copy.  For example:
82 ///
83 ///  A3 = B0
84 ///    ...
85 ///  B1 = A3      <- this copy
86 ///
87 /// In this case, B0 can be extended to where the B1 copy lives, allowing the B1
88 /// value number to be replaced with B0 (which simplifies the B liveinterval).
89 ///
90 /// This returns true if an interval was modified.
91 ///
92 bool SimpleRegisterCoalescing::AdjustCopiesBackFrom(LiveInterval &IntA,
93                                                     LiveInterval &IntB,
94                                                     MachineInstr *CopyMI) {
95   unsigned CopyIdx = li_->getDefIndex(li_->getInstructionIndex(CopyMI));
96
97   // BValNo is a value number in B that is defined by a copy from A.  'B3' in
98   // the example above.
99   LiveInterval::iterator BLR = IntB.FindLiveRangeContaining(CopyIdx);
100   if (BLR == IntB.end()) // Should never happen!
101     return false;
102   VNInfo *BValNo = BLR->valno;
103   
104   // Get the location that B is defined at.  Two options: either this value has
105   // an unknown definition point or it is defined at CopyIdx.  If unknown, we 
106   // can't process it.
107   if (!BValNo->copy) return false;
108   assert(BValNo->def == CopyIdx && "Copy doesn't define the value?");
109   
110   // AValNo is the value number in A that defines the copy, A3 in the example.
111   LiveInterval::iterator ALR = IntA.FindLiveRangeContaining(CopyIdx-1);
112   if (ALR == IntA.end()) // Should never happen!
113     return false;
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   if (ValLR == IntB.end()) // Should never happen!
130     return false;
131   
132   // Make sure that the end of the live range is inside the same block as
133   // CopyMI.
134   MachineInstr *ValLREndInst = li_->getInstructionFromIndex(ValLR->end-1);
135   if (!ValLREndInst || 
136       ValLREndInst->getParent() != CopyMI->getParent()) return false;
137
138   // Okay, we now know that ValLR ends in the same block that the CopyMI
139   // live-range starts.  If there are no intervening live ranges between them in
140   // IntB, we can merge them.
141   if (ValLR+1 != BLR) return false;
142
143   // If a live interval is a physical register, conservatively check if any
144   // of its sub-registers is overlapping the live interval of the virtual
145   // register. If so, do not coalesce.
146   if (TargetRegisterInfo::isPhysicalRegister(IntB.reg) &&
147       *tri_->getSubRegisters(IntB.reg)) {
148     for (const unsigned* SR = tri_->getSubRegisters(IntB.reg); *SR; ++SR)
149       if (li_->hasInterval(*SR) && IntA.overlaps(li_->getInterval(*SR))) {
150         DOUT << "Interfere with sub-register ";
151         DEBUG(li_->getInterval(*SR).print(DOUT, tri_));
152         return false;
153       }
154   }
155   
156   DOUT << "\nExtending: "; IntB.print(DOUT, tri_);
157   
158   unsigned FillerStart = ValLR->end, FillerEnd = BLR->start;
159   // We are about to delete CopyMI, so need to remove it as the 'instruction
160   // that defines this value #'. Update the the valnum with the new defining
161   // instruction #.
162   BValNo->def  = FillerStart;
163   BValNo->copy = NULL;
164   
165   // Okay, we can merge them.  We need to insert a new liverange:
166   // [ValLR.end, BLR.begin) of either value number, then we merge the
167   // two value numbers.
168   IntB.addRange(LiveRange(FillerStart, FillerEnd, BValNo));
169
170   // If the IntB live range is assigned to a physical register, and if that
171   // physreg has aliases, 
172   if (TargetRegisterInfo::isPhysicalRegister(IntB.reg)) {
173     // Update the liveintervals of sub-registers.
174     for (const unsigned *AS = tri_->getSubRegisters(IntB.reg); *AS; ++AS) {
175       LiveInterval &AliasLI = li_->getInterval(*AS);
176       AliasLI.addRange(LiveRange(FillerStart, FillerEnd,
177               AliasLI.getNextValue(FillerStart, 0, li_->getVNInfoAllocator())));
178     }
179   }
180
181   // Okay, merge "B1" into the same value number as "B0".
182   if (BValNo != ValLR->valno)
183     IntB.MergeValueNumberInto(BValNo, ValLR->valno);
184   DOUT << "   result = "; IntB.print(DOUT, tri_);
185   DOUT << "\n";
186
187   // If the source instruction was killing the source register before the
188   // merge, unset the isKill marker given the live range has been extended.
189   int UIdx = ValLREndInst->findRegisterUseOperandIdx(IntB.reg, true);
190   if (UIdx != -1)
191     ValLREndInst->getOperand(UIdx).setIsKill(false);
192
193   ++numExtends;
194   return true;
195 }
196
197 /// HasOtherReachingDefs - Return true if there are definitions of IntB
198 /// other than BValNo val# that can reach uses of AValno val# of IntA.
199 bool SimpleRegisterCoalescing::HasOtherReachingDefs(LiveInterval &IntA,
200                                                     LiveInterval &IntB,
201                                                     VNInfo *AValNo,
202                                                     VNInfo *BValNo) {
203   for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
204        AI != AE; ++AI) {
205     if (AI->valno != AValNo) continue;
206     LiveInterval::Ranges::iterator BI =
207       std::upper_bound(IntB.ranges.begin(), IntB.ranges.end(), AI->start);
208     if (BI != IntB.ranges.begin())
209       --BI;
210     for (; BI != IntB.ranges.end() && AI->end >= BI->start; ++BI) {
211       if (BI->valno == BValNo)
212         continue;
213       if (BI->start <= AI->start && BI->end > AI->start)
214         return true;
215       if (BI->start > AI->start && BI->start < AI->end)
216         return true;
217     }
218   }
219   return false;
220 }
221
222 /// RemoveCopyByCommutingDef - We found a non-trivially-coalescable copy with IntA
223 /// being the source and IntB being the dest, thus this defines a value number
224 /// in IntB.  If the source value number (in IntA) is defined by a commutable
225 /// instruction and its other operand is coalesced to the copy dest register,
226 /// see if we can transform the copy into a noop by commuting the definition. For
227 /// example,
228 ///
229 ///  A3 = op A2 B0<kill>
230 ///    ...
231 ///  B1 = A3      <- this copy
232 ///    ...
233 ///     = op A3   <- more uses
234 ///
235 /// ==>
236 ///
237 ///  B2 = op B0 A2<kill>
238 ///    ...
239 ///  B1 = B2      <- now an identify copy
240 ///    ...
241 ///     = op B2   <- more uses
242 ///
243 /// This returns true if an interval was modified.
244 ///
245 bool SimpleRegisterCoalescing::RemoveCopyByCommutingDef(LiveInterval &IntA,
246                                                         LiveInterval &IntB,
247                                                         MachineInstr *CopyMI) {
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   if (BLR == IntB.end()) // Should never happen!
261     return false;
262   VNInfo *BValNo = BLR->valno;
263   
264   // Get the location that B is defined at.  Two options: either this value has
265   // an unknown definition point or it is defined at CopyIdx.  If unknown, we 
266   // can't process it.
267   if (!BValNo->copy) return false;
268   assert(BValNo->def == CopyIdx && "Copy doesn't define the value?");
269   
270   // AValNo is the value number in A that defines the copy, A3 in the example.
271   LiveInterval::iterator ALR = IntA.FindLiveRangeContaining(CopyIdx-1);
272   if (ALR == IntA.end()) // Should never happen!
273     return false;
274   VNInfo *AValNo = ALR->valno;
275   // If other defs can reach uses of this def, then it's not safe to perform
276   // the optimization.
277   if (AValNo->def == ~0U || AValNo->def == ~1U || AValNo->hasPHIKill)
278     return false;
279   MachineInstr *DefMI = li_->getInstructionFromIndex(AValNo->def);
280   const TargetInstrDesc &TID = DefMI->getDesc();
281   unsigned NewDstIdx;
282   if (!TID.isCommutable() ||
283       !tii_->CommuteChangesDestination(DefMI, NewDstIdx))
284     return false;
285
286   MachineOperand &NewDstMO = DefMI->getOperand(NewDstIdx);
287   unsigned NewReg = NewDstMO.getReg();
288   if (NewReg != IntB.reg || !NewDstMO.isKill())
289     return false;
290
291   // Make sure there are no other definitions of IntB that would reach the
292   // uses which the new definition can reach.
293   if (HasOtherReachingDefs(IntA, IntB, AValNo, BValNo))
294     return false;
295
296   // If some of the uses of IntA.reg is already coalesced away, return false.
297   // It's not possible to determine whether it's safe to perform the coalescing.
298   for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(IntA.reg),
299          UE = mri_->use_end(); UI != UE; ++UI) {
300     MachineInstr *UseMI = &*UI;
301     unsigned UseIdx = li_->getInstructionIndex(UseMI);
302     LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx);
303     if (ULR == IntA.end())
304       continue;
305     if (ULR->valno == AValNo && JoinedCopies.count(UseMI))
306       return false;
307   }
308
309   // At this point we have decided that it is legal to do this
310   // transformation.  Start by commuting the instruction.
311   MachineBasicBlock *MBB = DefMI->getParent();
312   MachineInstr *NewMI = tii_->commuteInstruction(DefMI);
313   if (!NewMI)
314     return false;
315   if (NewMI != DefMI) {
316     li_->ReplaceMachineInstrInMaps(DefMI, NewMI);
317     MBB->insert(DefMI, NewMI);
318     MBB->erase(DefMI);
319   }
320   unsigned OpIdx = NewMI->findRegisterUseOperandIdx(IntA.reg, false);
321   NewMI->getOperand(OpIdx).setIsKill();
322
323   bool BHasPHIKill = BValNo->hasPHIKill;
324   SmallVector<VNInfo*, 4> BDeadValNos;
325   SmallVector<unsigned, 4> BKills;
326   std::map<unsigned, unsigned> BExtend;
327
328   // If ALR and BLR overlaps and end of BLR extends beyond end of ALR, e.g.
329   // A = or A, B
330   // ...
331   // B = A
332   // ...
333   // C = A<kill>
334   // ...
335   //   = B
336   //
337   // then do not add kills of A to the newly created B interval.
338   bool Extended = BLR->end > ALR->end && ALR->end != ALR->start;
339   if (Extended)
340     BExtend[ALR->end] = BLR->end;
341
342   // Update uses of IntA of the specific Val# with IntB.
343   for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(IntA.reg),
344          UE = mri_->use_end(); UI != UE;) {
345     MachineOperand &UseMO = UI.getOperand();
346     MachineInstr *UseMI = &*UI;
347     ++UI;
348     if (JoinedCopies.count(UseMI))
349       continue;
350     unsigned UseIdx = li_->getInstructionIndex(UseMI);
351     LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx);
352     if (ULR == IntA.end() || ULR->valno != AValNo)
353       continue;
354     UseMO.setReg(NewReg);
355     if (UseMI == CopyMI)
356       continue;
357     if (UseMO.isKill()) {
358       if (Extended)
359         UseMO.setIsKill(false);
360       else
361         BKills.push_back(li_->getUseIndex(UseIdx)+1);
362     }
363     unsigned SrcReg, DstReg;
364     if (!tii_->isMoveInstr(*UseMI, SrcReg, DstReg))
365       continue;
366     if (DstReg == IntB.reg) {
367       // This copy will become a noop. If it's defining a new val#,
368       // remove that val# as well. However this live range is being
369       // extended to the end of the existing live range defined by the copy.
370       unsigned DefIdx = li_->getDefIndex(UseIdx);
371       const LiveRange *DLR = IntB.getLiveRangeContaining(DefIdx);
372       BHasPHIKill |= DLR->valno->hasPHIKill;
373       assert(DLR->valno->def == DefIdx);
374       BDeadValNos.push_back(DLR->valno);
375       BExtend[DLR->start] = DLR->end;
376       JoinedCopies.insert(UseMI);
377       // If this is a kill but it's going to be removed, the last use
378       // of the same val# is the new kill.
379       if (UseMO.isKill())
380         BKills.pop_back();
381     }
382   }
383
384   // We need to insert a new liverange: [ALR.start, LastUse). It may be we can
385   // simply extend BLR if CopyMI doesn't end the range.
386   DOUT << "\nExtending: "; IntB.print(DOUT, tri_);
387
388   IntB.removeValNo(BValNo);
389   for (unsigned i = 0, e = BDeadValNos.size(); i != e; ++i)
390     IntB.removeValNo(BDeadValNos[i]);
391   VNInfo *ValNo = IntB.getNextValue(AValNo->def, 0, li_->getVNInfoAllocator());
392   for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
393        AI != AE; ++AI) {
394     if (AI->valno != AValNo) continue;
395     unsigned End = AI->end;
396     std::map<unsigned, unsigned>::iterator EI = BExtend.find(End);
397     if (EI != BExtend.end())
398       End = EI->second;
399     IntB.addRange(LiveRange(AI->start, End, ValNo));
400   }
401   IntB.addKills(ValNo, BKills);
402   ValNo->hasPHIKill = BHasPHIKill;
403
404   DOUT << "   result = "; IntB.print(DOUT, tri_);
405   DOUT << "\n";
406
407   DOUT << "\nShortening: "; IntA.print(DOUT, tri_);
408   IntA.removeValNo(AValNo);
409   DOUT << "   result = "; IntA.print(DOUT, tri_);
410   DOUT << "\n";
411
412   ++numCommutes;
413   return true;
414 }
415
416 /// isBackEdgeCopy - Returns true if CopyMI is a back edge copy.
417 ///
418 bool SimpleRegisterCoalescing::isBackEdgeCopy(MachineInstr *CopyMI,
419                                               unsigned DstReg) const {
420   MachineBasicBlock *MBB = CopyMI->getParent();
421   const MachineLoop *L = loopInfo->getLoopFor(MBB);
422   if (!L)
423     return false;
424   if (MBB != L->getLoopLatch())
425     return false;
426
427   LiveInterval &LI = li_->getInterval(DstReg);
428   unsigned DefIdx = li_->getInstructionIndex(CopyMI);
429   LiveInterval::const_iterator DstLR =
430     LI.FindLiveRangeContaining(li_->getDefIndex(DefIdx));
431   if (DstLR == LI.end())
432     return false;
433   unsigned KillIdx = li_->getInstructionIndex(&MBB->back()) + InstrSlots::NUM;
434   if (DstLR->valno->kills.size() == 1 &&
435       DstLR->valno->kills[0] == KillIdx && DstLR->valno->hasPHIKill)
436     return true;
437   return false;
438 }
439
440 /// UpdateRegDefsUses - Replace all defs and uses of SrcReg to DstReg and
441 /// update the subregister number if it is not zero. If DstReg is a
442 /// physical register and the existing subregister number of the def / use
443 /// being updated is not zero, make sure to set it to the correct physical
444 /// subregister.
445 void
446 SimpleRegisterCoalescing::UpdateRegDefsUses(unsigned SrcReg, unsigned DstReg,
447                                             unsigned SubIdx) {
448   bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
449   if (DstIsPhys && SubIdx) {
450     // Figure out the real physical register we are updating with.
451     DstReg = tri_->getSubReg(DstReg, SubIdx);
452     SubIdx = 0;
453   }
454
455   for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(SrcReg),
456          E = mri_->reg_end(); I != E; ) {
457     MachineOperand &O = I.getOperand();
458     MachineInstr *UseMI = &*I;
459     ++I;
460     unsigned OldSubIdx = O.getSubReg();
461     if (DstIsPhys) {
462       unsigned UseDstReg = DstReg;
463       if (OldSubIdx)
464           UseDstReg = tri_->getSubReg(DstReg, OldSubIdx);
465       O.setReg(UseDstReg);
466       O.setSubReg(0);
467     } else {
468       // Sub-register indexes goes from small to large. e.g.
469       // RAX: 1 -> AL, 2 -> AX, 3 -> EAX
470       // EAX: 1 -> AL, 2 -> AX
471       // So RAX's sub-register 2 is AX, RAX's sub-regsiter 3 is EAX, whose
472       // sub-register 2 is also AX.
473       if (SubIdx && OldSubIdx && SubIdx != OldSubIdx)
474         assert(OldSubIdx < SubIdx && "Conflicting sub-register index!");
475       else if (SubIdx)
476         O.setSubReg(SubIdx);
477       // Remove would-be duplicated kill marker.
478       if (O.isKill() && UseMI->killsRegister(DstReg))
479         O.setIsKill(false);
480       O.setReg(DstReg);
481     }
482   }
483 }
484
485 /// RemoveDeadImpDef - Remove implicit_def instructions which are "re-defining"
486 /// registers due to insert_subreg coalescing. e.g.
487 /// r1024 = op
488 /// r1025 = implicit_def
489 /// r1025 = insert_subreg r1025, r1024
490 ///       = op r1025
491 /// =>
492 /// r1025 = op
493 /// r1025 = implicit_def
494 /// r1025 = insert_subreg r1025, r1025
495 ///       = op r1025
496 void
497 SimpleRegisterCoalescing::RemoveDeadImpDef(unsigned Reg, LiveInterval &LI) {
498   for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(Reg),
499          E = mri_->reg_end(); I != E; ) {
500     MachineOperand &O = I.getOperand();
501     MachineInstr *DefMI = &*I;
502     ++I;
503     if (!O.isDef())
504       continue;
505     if (DefMI->getOpcode() != TargetInstrInfo::IMPLICIT_DEF)
506       continue;
507     if (!LI.liveBeforeAndAt(li_->getInstructionIndex(DefMI)))
508       continue;
509     li_->RemoveMachineInstrFromMaps(DefMI);
510     DefMI->eraseFromParent();
511   }
512 }
513
514 /// RemoveUnnecessaryKills - Remove kill markers that are no longer accurate
515 /// due to live range lengthening as the result of coalescing.
516 void SimpleRegisterCoalescing::RemoveUnnecessaryKills(unsigned Reg,
517                                                       LiveInterval &LI) {
518   for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(Reg),
519          UE = mri_->use_end(); UI != UE; ++UI) {
520     MachineOperand &UseMO = UI.getOperand();
521     if (UseMO.isKill()) {
522       MachineInstr *UseMI = UseMO.getParent();
523       unsigned SReg, DReg;
524       if (!tii_->isMoveInstr(*UseMI, SReg, DReg))
525         continue;
526       unsigned UseIdx = li_->getUseIndex(li_->getInstructionIndex(UseMI));
527       if (JoinedCopies.count(UseMI))
528         continue;
529       const LiveRange *UI = LI.getLiveRangeContaining(UseIdx);
530       if (!LI.isKill(UI->valno, UseIdx+1))
531         UseMO.setIsKill(false);
532     }
533   }
534 }
535
536 /// removeRange - Wrapper for LiveInterval::removeRange. This removes a range
537 /// from a physical register live interval as well as from the live intervals
538 /// of its sub-registers.
539 static void removeRange(LiveInterval &li, unsigned Start, unsigned End,
540                         LiveIntervals *li_, const TargetRegisterInfo *tri_) {
541   li.removeRange(Start, End, true);
542   if (TargetRegisterInfo::isPhysicalRegister(li.reg)) {
543     for (const unsigned* SR = tri_->getSubRegisters(li.reg); *SR; ++SR) {
544       if (!li_->hasInterval(*SR))
545         continue;
546       LiveInterval &sli = li_->getInterval(*SR);
547       unsigned RemoveEnd = Start;
548       while (RemoveEnd != End) {
549         LiveInterval::iterator LR = sli.FindLiveRangeContaining(Start);
550         if (LR == sli.end())
551           break;
552         RemoveEnd = (LR->end < End) ? LR->end : End;
553         sli.removeRange(Start, RemoveEnd, true);
554         Start = RemoveEnd;
555       }
556     }
557   }
558 }
559
560 /// removeIntervalIfEmpty - Check if the live interval of a physical register
561 /// is empty, if so remove it and also remove the empty intervals of its
562 /// sub-registers. Return true if live interval is removed.
563 static bool removeIntervalIfEmpty(LiveInterval &li, LiveIntervals *li_,
564                                   const TargetRegisterInfo *tri_) {
565   if (li.empty()) {
566     if (TargetRegisterInfo::isPhysicalRegister(li.reg))
567       for (const unsigned* SR = tri_->getSubRegisters(li.reg); *SR; ++SR) {
568         if (!li_->hasInterval(*SR))
569           continue;
570         LiveInterval &sli = li_->getInterval(*SR);
571         if (sli.empty())
572           li_->removeInterval(*SR);
573       }
574     li_->removeInterval(li.reg);
575     return true;
576   }
577   return false;
578 }
579
580 /// ShortenDeadCopyLiveRange - Shorten a live range defined by a dead copy.
581 /// Return true if live interval is removed.
582 bool SimpleRegisterCoalescing::ShortenDeadCopyLiveRange(LiveInterval &li,
583                                                         MachineInstr *CopyMI) {
584   unsigned CopyIdx = li_->getInstructionIndex(CopyMI);
585   LiveInterval::iterator MLR =
586     li.FindLiveRangeContaining(li_->getDefIndex(CopyIdx));
587   if (MLR == li.end())
588     return false;  // Already removed by ShortenDeadCopySrcLiveRange.
589   unsigned RemoveStart = MLR->start;
590   unsigned RemoveEnd = MLR->end;
591   // Remove the liverange that's defined by this.
592   if (RemoveEnd == li_->getDefIndex(CopyIdx)+1) {
593     removeRange(li, RemoveStart, RemoveEnd, li_, tri_);
594     return removeIntervalIfEmpty(li, li_, tri_);
595   }
596   return false;
597 }
598
599 /// PropagateDeadness - Propagate the dead marker to the instruction which
600 /// defines the val#.
601 static void PropagateDeadness(LiveInterval &li, MachineInstr *CopyMI,
602                               unsigned &LRStart, LiveIntervals *li_,
603                               const TargetRegisterInfo* tri_) {
604   MachineInstr *DefMI =
605     li_->getInstructionFromIndex(li_->getDefIndex(LRStart));
606   if (DefMI && DefMI != CopyMI) {
607     int DeadIdx = DefMI->findRegisterDefOperandIdx(li.reg, false, tri_);
608     if (DeadIdx != -1) {
609       DefMI->getOperand(DeadIdx).setIsDead();
610       // A dead def should have a single cycle interval.
611       ++LRStart;
612     }
613   }
614 }
615
616 /// isSameOrFallThroughBB - Return true if MBB == SuccMBB or MBB simply
617 /// fallthoughs to SuccMBB.
618 static bool isSameOrFallThroughBB(MachineBasicBlock *MBB,
619                                   MachineBasicBlock *SuccMBB,
620                                   const TargetInstrInfo *tii_) {
621   if (MBB == SuccMBB)
622     return true;
623   MachineBasicBlock *TBB = 0, *FBB = 0;
624   std::vector<MachineOperand> Cond;
625   return !tii_->AnalyzeBranch(*MBB, TBB, FBB, Cond) && !TBB && !FBB &&
626     MBB->isSuccessor(SuccMBB);
627 }
628
629 /// ShortenDeadCopySrcLiveRange - Shorten a live range as it's artificially
630 /// extended by a dead copy. Mark the last use (if any) of the val# as kill as
631 /// ends the live range there. If there isn't another use, then this live range
632 /// is dead. Return true if live interval is removed.
633 bool
634 SimpleRegisterCoalescing::ShortenDeadCopySrcLiveRange(LiveInterval &li,
635                                                       MachineInstr *CopyMI) {
636   unsigned CopyIdx = li_->getInstructionIndex(CopyMI);
637   if (CopyIdx == 0) {
638     // FIXME: special case: function live in. It can be a general case if the
639     // first instruction index starts at > 0 value.
640     assert(TargetRegisterInfo::isPhysicalRegister(li.reg));
641     // Live-in to the function but dead. Remove it from entry live-in set.
642     if (mf_->begin()->isLiveIn(li.reg))
643       mf_->begin()->removeLiveIn(li.reg);
644     const LiveRange *LR = li.getLiveRangeContaining(CopyIdx);
645     removeRange(li, LR->start, LR->end, li_, tri_);
646     return removeIntervalIfEmpty(li, li_, tri_);
647   }
648
649   LiveInterval::iterator LR = li.FindLiveRangeContaining(CopyIdx-1);
650   if (LR == li.end())
651     // Livein but defined by a phi.
652     return false;
653
654   unsigned RemoveStart = LR->start;
655   unsigned RemoveEnd = li_->getDefIndex(CopyIdx)+1;
656   if (LR->end > RemoveEnd)
657     // More uses past this copy? Nothing to do.
658     return false;
659
660   MachineBasicBlock *CopyMBB = CopyMI->getParent();
661   unsigned MBBStart = li_->getMBBStartIdx(CopyMBB);
662   unsigned LastUseIdx;
663   MachineOperand *LastUse = lastRegisterUse(LR->start, CopyIdx-1, li.reg,
664                                             LastUseIdx);
665   if (LastUse) {
666     MachineInstr *LastUseMI = LastUse->getParent();
667     if (!isSameOrFallThroughBB(LastUseMI->getParent(), CopyMBB, tii_)) {
668       // r1024 = op
669       // ...
670       // BB1:
671       //       = r1024
672       //
673       // BB2:
674       // r1025<dead> = r1024<kill>
675       if (MBBStart < LR->end)
676         removeRange(li, MBBStart, LR->end, li_, tri_);
677       return false;
678     }
679
680     // There are uses before the copy, just shorten the live range to the end
681     // of last use.
682     LastUse->setIsKill();
683     removeRange(li, li_->getDefIndex(LastUseIdx), LR->end, li_, tri_);
684     unsigned SrcReg, DstReg;
685     if (tii_->isMoveInstr(*LastUseMI, SrcReg, DstReg) &&
686         DstReg == li.reg) {
687       // Last use is itself an identity code.
688       int DeadIdx = LastUseMI->findRegisterDefOperandIdx(li.reg, false, tri_);
689       LastUseMI->getOperand(DeadIdx).setIsDead();
690     }
691     return false;
692   }
693
694   // Is it livein?
695   if (LR->start <= MBBStart && LR->end > MBBStart) {
696     if (LR->start == 0) {
697       assert(TargetRegisterInfo::isPhysicalRegister(li.reg));
698       // Live-in to the function but dead. Remove it from entry live-in set.
699       mf_->begin()->removeLiveIn(li.reg);
700     }
701     // FIXME: Shorten intervals in BBs that reaches this BB.
702   }
703
704   if (LR->valno->def == RemoveStart)
705     // If the def MI defines the val#, propagate the dead marker.
706     PropagateDeadness(li, CopyMI, RemoveStart, li_, tri_);
707
708   removeRange(li, RemoveStart, LR->end, li_, tri_);
709   return removeIntervalIfEmpty(li, li_, tri_);
710 }
711
712 /// CanCoalesceWithImpDef - Returns true if the specified copy instruction
713 /// from an implicit def to another register can be coalesced away.
714 bool SimpleRegisterCoalescing::CanCoalesceWithImpDef(MachineInstr *CopyMI,
715                                                      LiveInterval &li,
716                                                      LiveInterval &ImpLi) const{
717   if (!CopyMI->killsRegister(ImpLi.reg))
718     return false;
719   unsigned CopyIdx = li_->getDefIndex(li_->getInstructionIndex(CopyMI));
720   LiveInterval::iterator LR = li.FindLiveRangeContaining(CopyIdx);
721   if (LR == li.end())
722     return false;
723   if (LR->valno->hasPHIKill)
724     return false;
725   if (LR->valno->def != CopyIdx)
726     return false;
727   // Make sure all of val# uses are copies.
728   for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(li.reg),
729          UE = mri_->use_end(); UI != UE;) {
730     MachineInstr *UseMI = &*UI;
731     ++UI;
732     if (JoinedCopies.count(UseMI))
733       continue;
734     unsigned UseIdx = li_->getUseIndex(li_->getInstructionIndex(UseMI));
735     LiveInterval::iterator ULR = li.FindLiveRangeContaining(UseIdx);
736     if (ULR == li.end() || ULR->valno != LR->valno)
737       continue;
738     // If the use is not a use, then it's not safe to coalesce the move.
739     unsigned SrcReg, DstReg;
740     if (!tii_->isMoveInstr(*UseMI, SrcReg, DstReg)) {
741       if (UseMI->getOpcode() == TargetInstrInfo::INSERT_SUBREG &&
742           UseMI->getOperand(1).getReg() == li.reg)
743         continue;
744       return false;
745     }
746   }
747   return true;
748 }
749
750
751 /// RemoveCopiesFromValNo - The specified value# is defined by an implicit
752 /// def and it is being removed. Turn all copies from this value# into
753 /// identity copies so they will be removed.
754 void SimpleRegisterCoalescing::RemoveCopiesFromValNo(LiveInterval &li,
755                                                      VNInfo *VNI) {
756   MachineInstr *ImpDef = NULL;
757   MachineOperand *LastUse = NULL;
758   unsigned LastUseIdx = li_->getUseIndex(VNI->def);
759   for (MachineRegisterInfo::reg_iterator RI = mri_->reg_begin(li.reg),
760          RE = mri_->reg_end(); RI != RE;) {
761     MachineOperand *MO = &RI.getOperand();
762     MachineInstr *MI = &*RI;
763     ++RI;
764     if (MO->isDef()) {
765       if (MI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF) {
766         assert(!ImpDef && "Multiple implicit_def defining same register?");
767         ImpDef = MI;
768       }
769       continue;
770     }
771     if (JoinedCopies.count(MI))
772       continue;
773     unsigned UseIdx = li_->getUseIndex(li_->getInstructionIndex(MI));
774     LiveInterval::iterator ULR = li.FindLiveRangeContaining(UseIdx);
775     if (ULR == li.end() || ULR->valno != VNI)
776       continue;
777     // If the use is a copy, turn it into an identity copy.
778     unsigned SrcReg, DstReg;
779     if (tii_->isMoveInstr(*MI, SrcReg, DstReg) && SrcReg == li.reg) {
780       // Each use MI may have multiple uses of this register. Change them all.
781       for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
782         MachineOperand &MO = MI->getOperand(i);
783         if (MO.isReg() && MO.getReg() == li.reg)
784           MO.setReg(DstReg);
785       }
786       JoinedCopies.insert(MI);
787     } else if (UseIdx > LastUseIdx) {
788       LastUseIdx = UseIdx;
789       LastUse = MO;
790     }
791   }
792   if (LastUse)
793     LastUse->setIsKill();
794   else {
795     // Remove dead implicit_def.
796     li_->RemoveMachineInstrFromMaps(ImpDef);
797     ImpDef->eraseFromParent();
798   }
799 }
800
801 static unsigned getMatchingSuperReg(unsigned Reg, unsigned SubIdx, 
802                                     const TargetRegisterClass *RC,
803                                     const TargetRegisterInfo* TRI) {
804   for (const unsigned *SRs = TRI->getSuperRegisters(Reg);
805        unsigned SR = *SRs; ++SRs)
806     if (Reg == TRI->getSubReg(SR, SubIdx) && RC->contains(SR))
807       return SR;
808   return 0;
809 }
810
811 /// JoinCopy - Attempt to join intervals corresponding to SrcReg/DstReg,
812 /// which are the src/dst of the copy instruction CopyMI.  This returns true
813 /// if the copy was successfully coalesced away. If it is not currently
814 /// possible to coalesce this interval, but it may be possible if other
815 /// things get coalesced, then it returns true by reference in 'Again'.
816 bool SimpleRegisterCoalescing::JoinCopy(CopyRec &TheCopy, bool &Again) {
817   MachineInstr *CopyMI = TheCopy.MI;
818
819   Again = false;
820   if (JoinedCopies.count(CopyMI))
821     return false; // Already done.
822
823   DOUT << li_->getInstructionIndex(CopyMI) << '\t' << *CopyMI;
824
825   unsigned SrcReg;
826   unsigned DstReg;
827   bool isExtSubReg = CopyMI->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG;
828   bool isInsSubReg = CopyMI->getOpcode() == TargetInstrInfo::INSERT_SUBREG;
829   unsigned SubIdx = 0;
830   if (isExtSubReg) {
831     DstReg = CopyMI->getOperand(0).getReg();
832     SrcReg = CopyMI->getOperand(1).getReg();
833   } else if (isInsSubReg) {
834     if (CopyMI->getOperand(2).getSubReg()) {
835       DOUT << "\tSource of insert_subreg is already coalesced "
836            << "to another register.\n";
837       return false;  // Not coalescable.
838     }
839     DstReg = CopyMI->getOperand(0).getReg();
840     SrcReg = CopyMI->getOperand(2).getReg();
841   } else if (!tii_->isMoveInstr(*CopyMI, SrcReg, DstReg)) {
842     assert(0 && "Unrecognized copy instruction!");
843     return false;
844   }
845
846   // If they are already joined we continue.
847   if (SrcReg == DstReg) {
848     DOUT << "\tCopy already coalesced.\n";
849     return false;  // Not coalescable.
850   }
851   
852   bool SrcIsPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
853   bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
854
855   // If they are both physical registers, we cannot join them.
856   if (SrcIsPhys && DstIsPhys) {
857     DOUT << "\tCan not coalesce physregs.\n";
858     return false;  // Not coalescable.
859   }
860   
861   // We only join virtual registers with allocatable physical registers.
862   if (SrcIsPhys && !allocatableRegs_[SrcReg]) {
863     DOUT << "\tSrc reg is unallocatable physreg.\n";
864     return false;  // Not coalescable.
865   }
866   if (DstIsPhys && !allocatableRegs_[DstReg]) {
867     DOUT << "\tDst reg is unallocatable physreg.\n";
868     return false;  // Not coalescable.
869   }
870
871   unsigned RealDstReg = 0;
872   unsigned RealSrcReg = 0;
873   if (isExtSubReg || isInsSubReg) {
874     SubIdx = CopyMI->getOperand(isExtSubReg ? 2 : 3).getImm();
875     if (SrcIsPhys && isExtSubReg) {
876       // r1024 = EXTRACT_SUBREG EAX, 0 then r1024 is really going to be
877       // coalesced with AX.
878       unsigned DstSubIdx = CopyMI->getOperand(0).getSubReg();
879       if (DstSubIdx) {
880         // r1024<2> = EXTRACT_SUBREG EAX, 2. Then r1024 has already been
881         // coalesced to a larger register so the subreg indices cancel out.
882         if (DstSubIdx != SubIdx) {
883           DOUT << "\t Sub-register indices mismatch.\n";
884           return false; // Not coalescable.
885         }
886       } else
887         SrcReg = tri_->getSubReg(SrcReg, SubIdx);
888       SubIdx = 0;
889     } else if (DstIsPhys && isInsSubReg) {
890       // EAX = INSERT_SUBREG EAX, r1024, 0
891       unsigned SrcSubIdx = CopyMI->getOperand(2).getSubReg();
892       if (SrcSubIdx) {
893         // EAX = INSERT_SUBREG EAX, r1024<2>, 2 Then r1024 has already been
894         // coalesced to a larger register so the subreg indices cancel out.
895         if (SrcSubIdx != SubIdx) {
896           DOUT << "\t Sub-register indices mismatch.\n";
897           return false; // Not coalescable.
898         }
899       } else
900         DstReg = tri_->getSubReg(DstReg, SubIdx);
901       SubIdx = 0;
902     } else if ((DstIsPhys && isExtSubReg) || (SrcIsPhys && isInsSubReg)) {
903       // If this is a extract_subreg where dst is a physical register, e.g.
904       // cl = EXTRACT_SUBREG reg1024, 1
905       // then create and update the actual physical register allocated to RHS.
906       // Ditto for
907       // reg1024 = INSERT_SUBREG r1024, cl, 1
908       if (CopyMI->getOperand(1).getSubReg()) {
909         DOUT << "\tSrc of extract_ / insert_subreg already coalesced with reg"
910              << " of a super-class.\n";
911         return false; // Not coalescable.
912       }
913       const TargetRegisterClass *RC =
914         mri_->getRegClass(isExtSubReg ? SrcReg : DstReg);
915       if (isExtSubReg) {
916         RealDstReg = getMatchingSuperReg(DstReg, SubIdx, RC, tri_);
917         assert(RealDstReg && "Invalid extra_subreg instruction!");
918       } else {
919         RealSrcReg = getMatchingSuperReg(SrcReg, SubIdx, RC, tri_);
920         assert(RealSrcReg && "Invalid extra_subreg instruction!");
921       }
922
923       // For this type of EXTRACT_SUBREG, conservatively
924       // check if the live interval of the source register interfere with the
925       // actual super physical register we are trying to coalesce with.
926       unsigned PhysReg = isExtSubReg ? RealDstReg : RealSrcReg;
927       LiveInterval &RHS = li_->getInterval(isExtSubReg ? SrcReg : DstReg);
928       if (li_->hasInterval(PhysReg) &&
929           RHS.overlaps(li_->getInterval(PhysReg))) {
930         DOUT << "Interfere with register ";
931         DEBUG(li_->getInterval(PhysReg).print(DOUT, tri_));
932         return false; // Not coalescable
933       }
934       for (const unsigned* SR = tri_->getSubRegisters(PhysReg); *SR; ++SR)
935         if (li_->hasInterval(*SR) && RHS.overlaps(li_->getInterval(*SR))) {
936           DOUT << "Interfere with sub-register ";
937           DEBUG(li_->getInterval(*SR).print(DOUT, tri_));
938           return false; // Not coalescable
939         }
940       SubIdx = 0;
941     } else {
942       unsigned OldSubIdx = isExtSubReg ? CopyMI->getOperand(0).getSubReg()
943         : CopyMI->getOperand(2).getSubReg();
944       if (OldSubIdx) {
945         if (OldSubIdx == SubIdx && !differingRegisterClasses(SrcReg, DstReg))
946           // r1024<2> = EXTRACT_SUBREG r1025, 2. Then r1024 has already been
947           // coalesced to a larger register so the subreg indices cancel out.
948           // Also check if the other larger register is of the same register
949           // class as the would be resulting register.
950           SubIdx = 0;
951         else {
952           DOUT << "\t Sub-register indices mismatch.\n";
953           return false; // Not coalescable.
954         }
955       }
956       if (SubIdx) {
957         unsigned LargeReg = isExtSubReg ? SrcReg : DstReg;
958         unsigned SmallReg = isExtSubReg ? DstReg : SrcReg;
959         unsigned LargeRegSize =
960           li_->getInterval(LargeReg).getSize() / InstrSlots::NUM;
961         unsigned SmallRegSize =
962           li_->getInterval(SmallReg).getSize() / InstrSlots::NUM;
963         const TargetRegisterClass *RC = mri_->getRegClass(SmallReg);
964         unsigned Threshold = allocatableRCRegs_[RC].count();
965         // Be conservative. If both sides are virtual registers, do not coalesce
966         // if this will cause a high use density interval to target a smaller
967         // set of registers.
968         if (SmallRegSize > Threshold || LargeRegSize > Threshold) {
969           LiveVariables::VarInfo &svi = lv_->getVarInfo(LargeReg);
970           LiveVariables::VarInfo &dvi = lv_->getVarInfo(SmallReg);
971           if ((float)dvi.NumUses / SmallRegSize <
972               (float)svi.NumUses / LargeRegSize) {
973             Again = true;  // May be possible to coalesce later.
974             return false;
975           }
976         }
977       }
978     }
979   } else if (differingRegisterClasses(SrcReg, DstReg)) {
980     // FIXME: What if the resul of a EXTRACT_SUBREG is then coalesced
981     // with another? If it's the resulting destination register, then
982     // the subidx must be propagated to uses (but only those defined
983     // by the EXTRACT_SUBREG). If it's being coalesced into another
984     // register, it should be safe because register is assumed to have
985     // the register class of the super-register.
986
987     // If they are not of the same register class, we cannot join them.
988     DOUT << "\tSrc/Dest are different register classes.\n";
989     // Allow the coalescer to try again in case either side gets coalesced to
990     // a physical register that's compatible with the other side. e.g.
991     // r1024 = MOV32to32_ r1025
992     // but later r1024 is assigned EAX then r1025 may be coalesced with EAX.
993     Again = true;  // May be possible to coalesce later.
994     return false;
995   }
996   
997   LiveInterval &SrcInt = li_->getInterval(SrcReg);
998   LiveInterval &DstInt = li_->getInterval(DstReg);
999   assert(SrcInt.reg == SrcReg && DstInt.reg == DstReg &&
1000          "Register mapping is horribly broken!");
1001
1002   DOUT << "\t\tInspecting "; SrcInt.print(DOUT, tri_);
1003   DOUT << " and "; DstInt.print(DOUT, tri_);
1004   DOUT << ": ";
1005
1006   // Check if it is necessary to propagate "isDead" property.
1007   if (!isExtSubReg && !isInsSubReg) {
1008     MachineOperand *mopd = CopyMI->findRegisterDefOperand(DstReg, false);
1009     bool isDead = mopd->isDead();
1010
1011     // We need to be careful about coalescing a source physical register with a
1012     // virtual register. Once the coalescing is done, it cannot be broken and
1013     // these are not spillable! If the destination interval uses are far away,
1014     // think twice about coalescing them!
1015     if (!isDead && (SrcIsPhys || DstIsPhys)) {
1016       LiveInterval &JoinVInt = SrcIsPhys ? DstInt : SrcInt;
1017       unsigned JoinVReg = SrcIsPhys ? DstReg : SrcReg;
1018       unsigned JoinPReg = SrcIsPhys ? SrcReg : DstReg;
1019       const TargetRegisterClass *RC = mri_->getRegClass(JoinVReg);
1020       unsigned Threshold = allocatableRCRegs_[RC].count() * 2;
1021       if (TheCopy.isBackEdge)
1022         Threshold *= 2; // Favors back edge copies.
1023
1024       // If the virtual register live interval is long but it has low use desity,
1025       // do not join them, instead mark the physical register as its allocation
1026       // preference.
1027       unsigned Length = JoinVInt.getSize() / InstrSlots::NUM;
1028       LiveVariables::VarInfo &vi = lv_->getVarInfo(JoinVReg);
1029       if (Length > Threshold &&
1030           (((float)vi.NumUses / Length) < (1.0 / Threshold))) {
1031         JoinVInt.preference = JoinPReg;
1032         ++numAborts;
1033         DOUT << "\tMay tie down a physical register, abort!\n";
1034         Again = true;  // May be possible to coalesce later.
1035         return false;
1036       }
1037     }
1038   }
1039
1040   // Okay, attempt to join these two intervals.  On failure, this returns false.
1041   // Otherwise, if one of the intervals being joined is a physreg, this method
1042   // always canonicalizes DstInt to be it.  The output "SrcInt" will not have
1043   // been modified, so we can use this information below to update aliases.
1044   bool Swapped = false;
1045   // If SrcInt is implicitly defined, it's safe to coalesce.
1046   bool isEmpty = SrcInt.empty();
1047   if (isEmpty && !CanCoalesceWithImpDef(CopyMI, DstInt, SrcInt)) {
1048     // Only coalesce an empty interval (defined by implicit_def) with
1049     // another interval which has a valno defined by the CopyMI and the CopyMI
1050     // is a kill of the implicit def.
1051     DOUT << "Not profitable!\n";
1052     return false;
1053   }
1054
1055   if (!isEmpty && !JoinIntervals(DstInt, SrcInt, Swapped)) {
1056     // Coalescing failed.
1057     
1058     // If we can eliminate the copy without merging the live ranges, do so now.
1059     if (!isExtSubReg && !isInsSubReg &&
1060         (AdjustCopiesBackFrom(SrcInt, DstInt, CopyMI) ||
1061          RemoveCopyByCommutingDef(SrcInt, DstInt, CopyMI))) {
1062       JoinedCopies.insert(CopyMI);
1063       return true;
1064     }
1065     
1066     // Otherwise, we are unable to join the intervals.
1067     DOUT << "Interference!\n";
1068     Again = true;  // May be possible to coalesce later.
1069     return false;
1070   }
1071
1072   LiveInterval *ResSrcInt = &SrcInt;
1073   LiveInterval *ResDstInt = &DstInt;
1074   if (Swapped) {
1075     std::swap(SrcReg, DstReg);
1076     std::swap(ResSrcInt, ResDstInt);
1077   }
1078   assert(TargetRegisterInfo::isVirtualRegister(SrcReg) &&
1079          "LiveInterval::join didn't work right!");
1080                                
1081   // If we're about to merge live ranges into a physical register live range,
1082   // we have to update any aliased register's live ranges to indicate that they
1083   // have clobbered values for this range.
1084   if (TargetRegisterInfo::isPhysicalRegister(DstReg)) {
1085     // If this is a extract_subreg where dst is a physical register, e.g.
1086     // cl = EXTRACT_SUBREG reg1024, 1
1087     // then create and update the actual physical register allocated to RHS.
1088     if (RealDstReg || RealSrcReg) {
1089       LiveInterval &RealInt =
1090         li_->getOrCreateInterval(RealDstReg ? RealDstReg : RealSrcReg);
1091       SmallSet<const VNInfo*, 4> CopiedValNos;
1092       for (LiveInterval::Ranges::const_iterator I = ResSrcInt->ranges.begin(),
1093              E = ResSrcInt->ranges.end(); I != E; ++I) {
1094         const LiveRange *DstLR = ResDstInt->getLiveRangeContaining(I->start);
1095         assert(DstLR  && "Invalid joined interval!");
1096         const VNInfo *DstValNo = DstLR->valno;
1097         if (CopiedValNos.insert(DstValNo)) {
1098           VNInfo *ValNo = RealInt.getNextValue(DstValNo->def, DstValNo->copy,
1099                                                li_->getVNInfoAllocator());
1100           ValNo->hasPHIKill = DstValNo->hasPHIKill;
1101           RealInt.addKills(ValNo, DstValNo->kills);
1102           RealInt.MergeValueInAsValue(*ResDstInt, DstValNo, ValNo);
1103         }
1104       }
1105       
1106       DstReg = RealDstReg ? RealDstReg : RealSrcReg;
1107     }
1108
1109     // Update the liveintervals of sub-registers.
1110     for (const unsigned *AS = tri_->getSubRegisters(DstReg); *AS; ++AS)
1111       li_->getOrCreateInterval(*AS).MergeInClobberRanges(*ResSrcInt,
1112                                                  li_->getVNInfoAllocator());
1113   } else {
1114     // Merge use info if the destination is a virtual register.
1115     LiveVariables::VarInfo& dVI = lv_->getVarInfo(DstReg);
1116     LiveVariables::VarInfo& sVI = lv_->getVarInfo(SrcReg);
1117     dVI.NumUses += sVI.NumUses;
1118   }
1119
1120   // If this is a EXTRACT_SUBREG, make sure the result of coalescing is the
1121   // larger super-register.
1122   if ((isExtSubReg || isInsSubReg) && !SrcIsPhys && !DstIsPhys) {
1123     if ((isExtSubReg && !Swapped) || (isInsSubReg && Swapped)) {
1124       ResSrcInt->Copy(*ResDstInt, li_->getVNInfoAllocator());
1125       std::swap(SrcReg, DstReg);
1126       std::swap(ResSrcInt, ResDstInt);
1127     }
1128   }
1129
1130   if (NewHeuristic) {
1131     // Add all copies that define val# in the source interval into the queue.
1132     for (LiveInterval::const_vni_iterator i = ResSrcInt->vni_begin(),
1133            e = ResSrcInt->vni_end(); i != e; ++i) {
1134       const VNInfo *vni = *i;
1135       if (!vni->def || vni->def == ~1U || vni->def == ~0U)
1136         continue;
1137       MachineInstr *CopyMI = li_->getInstructionFromIndex(vni->def);
1138       unsigned NewSrcReg, NewDstReg;
1139       if (CopyMI &&
1140           JoinedCopies.count(CopyMI) == 0 &&
1141           tii_->isMoveInstr(*CopyMI, NewSrcReg, NewDstReg)) {
1142         unsigned LoopDepth = loopInfo->getLoopDepth(CopyMI->getParent());
1143         JoinQueue->push(CopyRec(CopyMI, LoopDepth,
1144                                 isBackEdgeCopy(CopyMI, DstReg)));
1145       }
1146     }
1147   }
1148
1149   // Remember to delete the copy instruction.
1150   JoinedCopies.insert(CopyMI);
1151
1152   // Some live range has been lengthened due to colaescing, eliminate the
1153   // unnecessary kills.
1154   RemoveUnnecessaryKills(SrcReg, *ResDstInt);
1155   if (TargetRegisterInfo::isVirtualRegister(DstReg))
1156     RemoveUnnecessaryKills(DstReg, *ResDstInt);
1157
1158   // SrcReg is guarateed to be the register whose live interval that is
1159   // being merged.
1160   li_->removeInterval(SrcReg);
1161   if (isInsSubReg)
1162     // Avoid:
1163     // r1024 = op
1164     // r1024 = implicit_def
1165     // ...
1166     //       = r1024
1167     RemoveDeadImpDef(DstReg, *ResDstInt);
1168   UpdateRegDefsUses(SrcReg, DstReg, SubIdx);
1169
1170   if (isEmpty) {
1171     // Now the copy is being coalesced away, the val# previously defined
1172     // by the copy is being defined by an IMPLICIT_DEF which defines a zero
1173     // length interval. Remove the val#.
1174     unsigned CopyIdx = li_->getDefIndex(li_->getInstructionIndex(CopyMI));
1175     const LiveRange *LR = ResDstInt->getLiveRangeContaining(CopyIdx);
1176     VNInfo *ImpVal = LR->valno;
1177     assert(ImpVal->def == CopyIdx);
1178     unsigned NextDef = LR->end;
1179     RemoveCopiesFromValNo(*ResDstInt, ImpVal);
1180     ResDstInt->removeValNo(ImpVal);
1181     LR = ResDstInt->FindLiveRangeContaining(NextDef);
1182     if (LR != ResDstInt->end() && LR->valno->def == NextDef) {
1183       // Special case: vr1024 = implicit_def
1184       //               vr1024 = insert_subreg vr1024, vr1025, c
1185       // The insert_subreg becomes a "copy" that defines a val# which can itself
1186       // be coalesced away.
1187       MachineInstr *DefMI = li_->getInstructionFromIndex(NextDef);
1188       if (DefMI->getOpcode() == TargetInstrInfo::INSERT_SUBREG)
1189         LR->valno->copy = DefMI;
1190     }
1191   }
1192
1193   DOUT << "\n\t\tJoined.  Result = "; ResDstInt->print(DOUT, tri_);
1194   DOUT << "\n";
1195
1196   ++numJoins;
1197   return true;
1198 }
1199
1200 /// ComputeUltimateVN - Assuming we are going to join two live intervals,
1201 /// compute what the resultant value numbers for each value in the input two
1202 /// ranges will be.  This is complicated by copies between the two which can
1203 /// and will commonly cause multiple value numbers to be merged into one.
1204 ///
1205 /// VN is the value number that we're trying to resolve.  InstDefiningValue
1206 /// keeps track of the new InstDefiningValue assignment for the result
1207 /// LiveInterval.  ThisFromOther/OtherFromThis are sets that keep track of
1208 /// whether a value in this or other is a copy from the opposite set.
1209 /// ThisValNoAssignments/OtherValNoAssignments keep track of value #'s that have
1210 /// already been assigned.
1211 ///
1212 /// ThisFromOther[x] - If x is defined as a copy from the other interval, this
1213 /// contains the value number the copy is from.
1214 ///
1215 static unsigned ComputeUltimateVN(VNInfo *VNI,
1216                                   SmallVector<VNInfo*, 16> &NewVNInfo,
1217                                   DenseMap<VNInfo*, VNInfo*> &ThisFromOther,
1218                                   DenseMap<VNInfo*, VNInfo*> &OtherFromThis,
1219                                   SmallVector<int, 16> &ThisValNoAssignments,
1220                                   SmallVector<int, 16> &OtherValNoAssignments) {
1221   unsigned VN = VNI->id;
1222
1223   // If the VN has already been computed, just return it.
1224   if (ThisValNoAssignments[VN] >= 0)
1225     return ThisValNoAssignments[VN];
1226 //  assert(ThisValNoAssignments[VN] != -2 && "Cyclic case?");
1227
1228   // If this val is not a copy from the other val, then it must be a new value
1229   // number in the destination.
1230   DenseMap<VNInfo*, VNInfo*>::iterator I = ThisFromOther.find(VNI);
1231   if (I == ThisFromOther.end()) {
1232     NewVNInfo.push_back(VNI);
1233     return ThisValNoAssignments[VN] = NewVNInfo.size()-1;
1234   }
1235   VNInfo *OtherValNo = I->second;
1236
1237   // Otherwise, this *is* a copy from the RHS.  If the other side has already
1238   // been computed, return it.
1239   if (OtherValNoAssignments[OtherValNo->id] >= 0)
1240     return ThisValNoAssignments[VN] = OtherValNoAssignments[OtherValNo->id];
1241   
1242   // Mark this value number as currently being computed, then ask what the
1243   // ultimate value # of the other value is.
1244   ThisValNoAssignments[VN] = -2;
1245   unsigned UltimateVN =
1246     ComputeUltimateVN(OtherValNo, NewVNInfo, OtherFromThis, ThisFromOther,
1247                       OtherValNoAssignments, ThisValNoAssignments);
1248   return ThisValNoAssignments[VN] = UltimateVN;
1249 }
1250
1251 static bool InVector(VNInfo *Val, const SmallVector<VNInfo*, 8> &V) {
1252   return std::find(V.begin(), V.end(), Val) != V.end();
1253 }
1254
1255 /// RangeIsDefinedByCopyFromReg - Return true if the specified live range of
1256 /// the specified live interval is defined by a copy from the specified
1257 /// register.
1258 bool SimpleRegisterCoalescing::RangeIsDefinedByCopyFromReg(LiveInterval &li,
1259                                                            LiveRange *LR,
1260                                                            unsigned Reg) {
1261   unsigned SrcReg = li_->getVNInfoSourceReg(LR->valno);
1262   if (SrcReg == Reg)
1263     return true;
1264   if (LR->valno->def == ~0U &&
1265       TargetRegisterInfo::isPhysicalRegister(li.reg) &&
1266       *tri_->getSuperRegisters(li.reg)) {
1267     // It's a sub-register live interval, we may not have precise information.
1268     // Re-compute it.
1269     MachineInstr *DefMI = li_->getInstructionFromIndex(LR->start);
1270     unsigned SrcReg, DstReg;
1271     if (tii_->isMoveInstr(*DefMI, SrcReg, DstReg) &&
1272         DstReg == li.reg && SrcReg == Reg) {
1273       // Cache computed info.
1274       LR->valno->def  = LR->start;
1275       LR->valno->copy = DefMI;
1276       return true;
1277     }
1278   }
1279   return false;
1280 }
1281
1282 /// SimpleJoin - Attempt to joint the specified interval into this one. The
1283 /// caller of this method must guarantee that the RHS only contains a single
1284 /// value number and that the RHS is not defined by a copy from this
1285 /// interval.  This returns false if the intervals are not joinable, or it
1286 /// joins them and returns true.
1287 bool SimpleRegisterCoalescing::SimpleJoin(LiveInterval &LHS, LiveInterval &RHS){
1288   assert(RHS.containsOneValue());
1289   
1290   // Some number (potentially more than one) value numbers in the current
1291   // interval may be defined as copies from the RHS.  Scan the overlapping
1292   // portions of the LHS and RHS, keeping track of this and looking for
1293   // overlapping live ranges that are NOT defined as copies.  If these exist, we
1294   // cannot coalesce.
1295   
1296   LiveInterval::iterator LHSIt = LHS.begin(), LHSEnd = LHS.end();
1297   LiveInterval::iterator RHSIt = RHS.begin(), RHSEnd = RHS.end();
1298   
1299   if (LHSIt->start < RHSIt->start) {
1300     LHSIt = std::upper_bound(LHSIt, LHSEnd, RHSIt->start);
1301     if (LHSIt != LHS.begin()) --LHSIt;
1302   } else if (RHSIt->start < LHSIt->start) {
1303     RHSIt = std::upper_bound(RHSIt, RHSEnd, LHSIt->start);
1304     if (RHSIt != RHS.begin()) --RHSIt;
1305   }
1306   
1307   SmallVector<VNInfo*, 8> EliminatedLHSVals;
1308   
1309   while (1) {
1310     // Determine if these live intervals overlap.
1311     bool Overlaps = false;
1312     if (LHSIt->start <= RHSIt->start)
1313       Overlaps = LHSIt->end > RHSIt->start;
1314     else
1315       Overlaps = RHSIt->end > LHSIt->start;
1316     
1317     // If the live intervals overlap, there are two interesting cases: if the
1318     // LHS interval is defined by a copy from the RHS, it's ok and we record
1319     // that the LHS value # is the same as the RHS.  If it's not, then we cannot
1320     // coalesce these live ranges and we bail out.
1321     if (Overlaps) {
1322       // If we haven't already recorded that this value # is safe, check it.
1323       if (!InVector(LHSIt->valno, EliminatedLHSVals)) {
1324         // Copy from the RHS?
1325         if (!RangeIsDefinedByCopyFromReg(LHS, LHSIt, RHS.reg))
1326           return false;    // Nope, bail out.
1327         
1328         EliminatedLHSVals.push_back(LHSIt->valno);
1329       }
1330       
1331       // We know this entire LHS live range is okay, so skip it now.
1332       if (++LHSIt == LHSEnd) break;
1333       continue;
1334     }
1335     
1336     if (LHSIt->end < RHSIt->end) {
1337       if (++LHSIt == LHSEnd) break;
1338     } else {
1339       // One interesting case to check here.  It's possible that we have
1340       // something like "X3 = Y" which defines a new value number in the LHS,
1341       // and is the last use of this liverange of the RHS.  In this case, we
1342       // want to notice this copy (so that it gets coalesced away) even though
1343       // the live ranges don't actually overlap.
1344       if (LHSIt->start == RHSIt->end) {
1345         if (InVector(LHSIt->valno, EliminatedLHSVals)) {
1346           // We already know that this value number is going to be merged in
1347           // if coalescing succeeds.  Just skip the liverange.
1348           if (++LHSIt == LHSEnd) break;
1349         } else {
1350           // Otherwise, if this is a copy from the RHS, mark it as being merged
1351           // in.
1352           if (RangeIsDefinedByCopyFromReg(LHS, LHSIt, RHS.reg)) {
1353             EliminatedLHSVals.push_back(LHSIt->valno);
1354
1355             // We know this entire LHS live range is okay, so skip it now.
1356             if (++LHSIt == LHSEnd) break;
1357           }
1358         }
1359       }
1360       
1361       if (++RHSIt == RHSEnd) break;
1362     }
1363   }
1364   
1365   // If we got here, we know that the coalescing will be successful and that
1366   // the value numbers in EliminatedLHSVals will all be merged together.  Since
1367   // the most common case is that EliminatedLHSVals has a single number, we
1368   // optimize for it: if there is more than one value, we merge them all into
1369   // the lowest numbered one, then handle the interval as if we were merging
1370   // with one value number.
1371   VNInfo *LHSValNo;
1372   if (EliminatedLHSVals.size() > 1) {
1373     // Loop through all the equal value numbers merging them into the smallest
1374     // one.
1375     VNInfo *Smallest = EliminatedLHSVals[0];
1376     for (unsigned i = 1, e = EliminatedLHSVals.size(); i != e; ++i) {
1377       if (EliminatedLHSVals[i]->id < Smallest->id) {
1378         // Merge the current notion of the smallest into the smaller one.
1379         LHS.MergeValueNumberInto(Smallest, EliminatedLHSVals[i]);
1380         Smallest = EliminatedLHSVals[i];
1381       } else {
1382         // Merge into the smallest.
1383         LHS.MergeValueNumberInto(EliminatedLHSVals[i], Smallest);
1384       }
1385     }
1386     LHSValNo = Smallest;
1387   } else if (EliminatedLHSVals.empty()) {
1388     if (TargetRegisterInfo::isPhysicalRegister(LHS.reg) &&
1389         *tri_->getSuperRegisters(LHS.reg))
1390       // Imprecise sub-register information. Can't handle it.
1391       return false;
1392     assert(0 && "No copies from the RHS?");
1393   } else {
1394     LHSValNo = EliminatedLHSVals[0];
1395   }
1396   
1397   // Okay, now that there is a single LHS value number that we're merging the
1398   // RHS into, update the value number info for the LHS to indicate that the
1399   // value number is defined where the RHS value number was.
1400   const VNInfo *VNI = RHS.getValNumInfo(0);
1401   LHSValNo->def  = VNI->def;
1402   LHSValNo->copy = VNI->copy;
1403   
1404   // Okay, the final step is to loop over the RHS live intervals, adding them to
1405   // the LHS.
1406   LHSValNo->hasPHIKill |= VNI->hasPHIKill;
1407   LHS.addKills(LHSValNo, VNI->kills);
1408   LHS.MergeRangesInAsValue(RHS, LHSValNo);
1409   LHS.weight += RHS.weight;
1410   if (RHS.preference && !LHS.preference)
1411     LHS.preference = RHS.preference;
1412   
1413   return true;
1414 }
1415
1416 /// JoinIntervals - Attempt to join these two intervals.  On failure, this
1417 /// returns false.  Otherwise, if one of the intervals being joined is a
1418 /// physreg, this method always canonicalizes LHS to be it.  The output
1419 /// "RHS" will not have been modified, so we can use this information
1420 /// below to update aliases.
1421 bool SimpleRegisterCoalescing::JoinIntervals(LiveInterval &LHS,
1422                                              LiveInterval &RHS, bool &Swapped) {
1423   // Compute the final value assignment, assuming that the live ranges can be
1424   // coalesced.
1425   SmallVector<int, 16> LHSValNoAssignments;
1426   SmallVector<int, 16> RHSValNoAssignments;
1427   DenseMap<VNInfo*, VNInfo*> LHSValsDefinedFromRHS;
1428   DenseMap<VNInfo*, VNInfo*> RHSValsDefinedFromLHS;
1429   SmallVector<VNInfo*, 16> NewVNInfo;
1430                           
1431   // If a live interval is a physical register, conservatively check if any
1432   // of its sub-registers is overlapping the live interval of the virtual
1433   // register. If so, do not coalesce.
1434   if (TargetRegisterInfo::isPhysicalRegister(LHS.reg) &&
1435       *tri_->getSubRegisters(LHS.reg)) {
1436     for (const unsigned* SR = tri_->getSubRegisters(LHS.reg); *SR; ++SR)
1437       if (li_->hasInterval(*SR) && RHS.overlaps(li_->getInterval(*SR))) {
1438         DOUT << "Interfere with sub-register ";
1439         DEBUG(li_->getInterval(*SR).print(DOUT, tri_));
1440         return false;
1441       }
1442   } else if (TargetRegisterInfo::isPhysicalRegister(RHS.reg) &&
1443              *tri_->getSubRegisters(RHS.reg)) {
1444     for (const unsigned* SR = tri_->getSubRegisters(RHS.reg); *SR; ++SR)
1445       if (li_->hasInterval(*SR) && LHS.overlaps(li_->getInterval(*SR))) {
1446         DOUT << "Interfere with sub-register ";
1447         DEBUG(li_->getInterval(*SR).print(DOUT, tri_));
1448         return false;
1449       }
1450   }
1451                           
1452   // Compute ultimate value numbers for the LHS and RHS values.
1453   if (RHS.containsOneValue()) {
1454     // Copies from a liveinterval with a single value are simple to handle and
1455     // very common, handle the special case here.  This is important, because
1456     // often RHS is small and LHS is large (e.g. a physreg).
1457     
1458     // Find out if the RHS is defined as a copy from some value in the LHS.
1459     int RHSVal0DefinedFromLHS = -1;
1460     int RHSValID = -1;
1461     VNInfo *RHSValNoInfo = NULL;
1462     VNInfo *RHSValNoInfo0 = RHS.getValNumInfo(0);
1463     unsigned RHSSrcReg = li_->getVNInfoSourceReg(RHSValNoInfo0);
1464     if ((RHSSrcReg == 0 || RHSSrcReg != LHS.reg)) {
1465       // If RHS is not defined as a copy from the LHS, we can use simpler and
1466       // faster checks to see if the live ranges are coalescable.  This joiner
1467       // can't swap the LHS/RHS intervals though.
1468       if (!TargetRegisterInfo::isPhysicalRegister(RHS.reg)) {
1469         return SimpleJoin(LHS, RHS);
1470       } else {
1471         RHSValNoInfo = RHSValNoInfo0;
1472       }
1473     } else {
1474       // It was defined as a copy from the LHS, find out what value # it is.
1475       RHSValNoInfo = LHS.getLiveRangeContaining(RHSValNoInfo0->def-1)->valno;
1476       RHSValID = RHSValNoInfo->id;
1477       RHSVal0DefinedFromLHS = RHSValID;
1478     }
1479     
1480     LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
1481     RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
1482     NewVNInfo.resize(LHS.getNumValNums(), NULL);
1483     
1484     // Okay, *all* of the values in LHS that are defined as a copy from RHS
1485     // should now get updated.
1486     for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1487          i != e; ++i) {
1488       VNInfo *VNI = *i;
1489       unsigned VN = VNI->id;
1490       if (unsigned LHSSrcReg = li_->getVNInfoSourceReg(VNI)) {
1491         if (LHSSrcReg != RHS.reg) {
1492           // If this is not a copy from the RHS, its value number will be
1493           // unmodified by the coalescing.
1494           NewVNInfo[VN] = VNI;
1495           LHSValNoAssignments[VN] = VN;
1496         } else if (RHSValID == -1) {
1497           // Otherwise, it is a copy from the RHS, and we don't already have a
1498           // value# for it.  Keep the current value number, but remember it.
1499           LHSValNoAssignments[VN] = RHSValID = VN;
1500           NewVNInfo[VN] = RHSValNoInfo;
1501           LHSValsDefinedFromRHS[VNI] = RHSValNoInfo0;
1502         } else {
1503           // Otherwise, use the specified value #.
1504           LHSValNoAssignments[VN] = RHSValID;
1505           if (VN == (unsigned)RHSValID) {  // Else this val# is dead.
1506             NewVNInfo[VN] = RHSValNoInfo;
1507             LHSValsDefinedFromRHS[VNI] = RHSValNoInfo0;
1508           }
1509         }
1510       } else {
1511         NewVNInfo[VN] = VNI;
1512         LHSValNoAssignments[VN] = VN;
1513       }
1514     }
1515     
1516     assert(RHSValID != -1 && "Didn't find value #?");
1517     RHSValNoAssignments[0] = RHSValID;
1518     if (RHSVal0DefinedFromLHS != -1) {
1519       // This path doesn't go through ComputeUltimateVN so just set
1520       // it to anything.
1521       RHSValsDefinedFromLHS[RHSValNoInfo0] = (VNInfo*)1;
1522     }
1523   } else {
1524     // Loop over the value numbers of the LHS, seeing if any are defined from
1525     // the RHS.
1526     for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1527          i != e; ++i) {
1528       VNInfo *VNI = *i;
1529       if (VNI->def == ~1U || VNI->copy == 0)  // Src not defined by a copy?
1530         continue;
1531       
1532       // DstReg is known to be a register in the LHS interval.  If the src is
1533       // from the RHS interval, we can use its value #.
1534       if (li_->getVNInfoSourceReg(VNI) != RHS.reg)
1535         continue;
1536       
1537       // Figure out the value # from the RHS.
1538       LHSValsDefinedFromRHS[VNI]=RHS.getLiveRangeContaining(VNI->def-1)->valno;
1539     }
1540     
1541     // Loop over the value numbers of the RHS, seeing if any are defined from
1542     // the LHS.
1543     for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
1544          i != e; ++i) {
1545       VNInfo *VNI = *i;
1546       if (VNI->def == ~1U || VNI->copy == 0)  // Src not defined by a copy?
1547         continue;
1548       
1549       // DstReg is known to be a register in the RHS interval.  If the src is
1550       // from the LHS interval, we can use its value #.
1551       if (li_->getVNInfoSourceReg(VNI) != LHS.reg)
1552         continue;
1553       
1554       // Figure out the value # from the LHS.
1555       RHSValsDefinedFromLHS[VNI]=LHS.getLiveRangeContaining(VNI->def-1)->valno;
1556     }
1557     
1558     LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
1559     RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
1560     NewVNInfo.reserve(LHS.getNumValNums() + RHS.getNumValNums());
1561     
1562     for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1563          i != e; ++i) {
1564       VNInfo *VNI = *i;
1565       unsigned VN = VNI->id;
1566       if (LHSValNoAssignments[VN] >= 0 || VNI->def == ~1U) 
1567         continue;
1568       ComputeUltimateVN(VNI, NewVNInfo,
1569                         LHSValsDefinedFromRHS, RHSValsDefinedFromLHS,
1570                         LHSValNoAssignments, RHSValNoAssignments);
1571     }
1572     for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
1573          i != e; ++i) {
1574       VNInfo *VNI = *i;
1575       unsigned VN = VNI->id;
1576       if (RHSValNoAssignments[VN] >= 0 || VNI->def == ~1U)
1577         continue;
1578       // If this value number isn't a copy from the LHS, it's a new number.
1579       if (RHSValsDefinedFromLHS.find(VNI) == RHSValsDefinedFromLHS.end()) {
1580         NewVNInfo.push_back(VNI);
1581         RHSValNoAssignments[VN] = NewVNInfo.size()-1;
1582         continue;
1583       }
1584       
1585       ComputeUltimateVN(VNI, NewVNInfo,
1586                         RHSValsDefinedFromLHS, LHSValsDefinedFromRHS,
1587                         RHSValNoAssignments, LHSValNoAssignments);
1588     }
1589   }
1590   
1591   // Armed with the mappings of LHS/RHS values to ultimate values, walk the
1592   // interval lists to see if these intervals are coalescable.
1593   LiveInterval::const_iterator I = LHS.begin();
1594   LiveInterval::const_iterator IE = LHS.end();
1595   LiveInterval::const_iterator J = RHS.begin();
1596   LiveInterval::const_iterator JE = RHS.end();
1597   
1598   // Skip ahead until the first place of potential sharing.
1599   if (I->start < J->start) {
1600     I = std::upper_bound(I, IE, J->start);
1601     if (I != LHS.begin()) --I;
1602   } else if (J->start < I->start) {
1603     J = std::upper_bound(J, JE, I->start);
1604     if (J != RHS.begin()) --J;
1605   }
1606   
1607   while (1) {
1608     // Determine if these two live ranges overlap.
1609     bool Overlaps;
1610     if (I->start < J->start) {
1611       Overlaps = I->end > J->start;
1612     } else {
1613       Overlaps = J->end > I->start;
1614     }
1615
1616     // If so, check value # info to determine if they are really different.
1617     if (Overlaps) {
1618       // If the live range overlap will map to the same value number in the
1619       // result liverange, we can still coalesce them.  If not, we can't.
1620       if (LHSValNoAssignments[I->valno->id] !=
1621           RHSValNoAssignments[J->valno->id])
1622         return false;
1623     }
1624     
1625     if (I->end < J->end) {
1626       ++I;
1627       if (I == IE) break;
1628     } else {
1629       ++J;
1630       if (J == JE) break;
1631     }
1632   }
1633
1634   // Update kill info. Some live ranges are extended due to copy coalescing.
1635   for (DenseMap<VNInfo*, VNInfo*>::iterator I = LHSValsDefinedFromRHS.begin(),
1636          E = LHSValsDefinedFromRHS.end(); I != E; ++I) {
1637     VNInfo *VNI = I->first;
1638     unsigned LHSValID = LHSValNoAssignments[VNI->id];
1639     LiveInterval::removeKill(NewVNInfo[LHSValID], VNI->def);
1640     NewVNInfo[LHSValID]->hasPHIKill |= VNI->hasPHIKill;
1641     RHS.addKills(NewVNInfo[LHSValID], VNI->kills);
1642   }
1643
1644   // Update kill info. Some live ranges are extended due to copy coalescing.
1645   for (DenseMap<VNInfo*, VNInfo*>::iterator I = RHSValsDefinedFromLHS.begin(),
1646          E = RHSValsDefinedFromLHS.end(); I != E; ++I) {
1647     VNInfo *VNI = I->first;
1648     unsigned RHSValID = RHSValNoAssignments[VNI->id];
1649     LiveInterval::removeKill(NewVNInfo[RHSValID], VNI->def);
1650     NewVNInfo[RHSValID]->hasPHIKill |= VNI->hasPHIKill;
1651     LHS.addKills(NewVNInfo[RHSValID], VNI->kills);
1652   }
1653
1654   // If we get here, we know that we can coalesce the live ranges.  Ask the
1655   // intervals to coalesce themselves now.
1656   if ((RHS.ranges.size() > LHS.ranges.size() &&
1657       TargetRegisterInfo::isVirtualRegister(LHS.reg)) ||
1658       TargetRegisterInfo::isPhysicalRegister(RHS.reg)) {
1659     RHS.join(LHS, &RHSValNoAssignments[0], &LHSValNoAssignments[0], NewVNInfo);
1660     Swapped = true;
1661   } else {
1662     LHS.join(RHS, &LHSValNoAssignments[0], &RHSValNoAssignments[0], NewVNInfo);
1663     Swapped = false;
1664   }
1665   return true;
1666 }
1667
1668 namespace {
1669   // DepthMBBCompare - Comparison predicate that sort first based on the loop
1670   // depth of the basic block (the unsigned), and then on the MBB number.
1671   struct DepthMBBCompare {
1672     typedef std::pair<unsigned, MachineBasicBlock*> DepthMBBPair;
1673     bool operator()(const DepthMBBPair &LHS, const DepthMBBPair &RHS) const {
1674       if (LHS.first > RHS.first) return true;   // Deeper loops first
1675       return LHS.first == RHS.first &&
1676         LHS.second->getNumber() < RHS.second->getNumber();
1677     }
1678   };
1679 }
1680
1681 /// getRepIntervalSize - Returns the size of the interval that represents the
1682 /// specified register.
1683 template<class SF>
1684 unsigned JoinPriorityQueue<SF>::getRepIntervalSize(unsigned Reg) {
1685   return Rc->getRepIntervalSize(Reg);
1686 }
1687
1688 /// CopyRecSort::operator - Join priority queue sorting function.
1689 ///
1690 bool CopyRecSort::operator()(CopyRec left, CopyRec right) const {
1691   // Inner loops first.
1692   if (left.LoopDepth > right.LoopDepth)
1693     return false;
1694   else if (left.LoopDepth == right.LoopDepth)
1695     if (left.isBackEdge && !right.isBackEdge)
1696       return false;
1697   return true;
1698 }
1699
1700 void SimpleRegisterCoalescing::CopyCoalesceInMBB(MachineBasicBlock *MBB,
1701                                                std::vector<CopyRec> &TryAgain) {
1702   DOUT << ((Value*)MBB->getBasicBlock())->getName() << ":\n";
1703
1704   std::vector<CopyRec> VirtCopies;
1705   std::vector<CopyRec> PhysCopies;
1706   std::vector<CopyRec> ImpDefCopies;
1707   unsigned LoopDepth = loopInfo->getLoopDepth(MBB);
1708   for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end();
1709        MII != E;) {
1710     MachineInstr *Inst = MII++;
1711     
1712     // If this isn't a copy nor a extract_subreg, we can't join intervals.
1713     unsigned SrcReg, DstReg;
1714     if (Inst->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG) {
1715       DstReg = Inst->getOperand(0).getReg();
1716       SrcReg = Inst->getOperand(1).getReg();
1717     } else if (Inst->getOpcode() == TargetInstrInfo::INSERT_SUBREG) {
1718       DstReg = Inst->getOperand(0).getReg();
1719       SrcReg = Inst->getOperand(2).getReg();
1720     } else if (!tii_->isMoveInstr(*Inst, SrcReg, DstReg))
1721       continue;
1722
1723     bool SrcIsPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
1724     bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
1725     if (NewHeuristic) {
1726       JoinQueue->push(CopyRec(Inst, LoopDepth, isBackEdgeCopy(Inst, DstReg)));
1727     } else {
1728       if (li_->hasInterval(SrcReg) && li_->getInterval(SrcReg).empty())
1729         ImpDefCopies.push_back(CopyRec(Inst, 0, false));
1730       else if (SrcIsPhys || DstIsPhys)
1731         PhysCopies.push_back(CopyRec(Inst, 0, false));
1732       else
1733         VirtCopies.push_back(CopyRec(Inst, 0, false));
1734     }
1735   }
1736
1737   if (NewHeuristic)
1738     return;
1739
1740   // Try coalescing implicit copies first, followed by copies to / from
1741   // physical registers, then finally copies from virtual registers to
1742   // virtual registers.
1743   for (unsigned i = 0, e = ImpDefCopies.size(); i != e; ++i) {
1744     CopyRec &TheCopy = ImpDefCopies[i];
1745     bool Again = false;
1746     if (!JoinCopy(TheCopy, Again))
1747       if (Again)
1748         TryAgain.push_back(TheCopy);
1749   }
1750   for (unsigned i = 0, e = PhysCopies.size(); i != e; ++i) {
1751     CopyRec &TheCopy = PhysCopies[i];
1752     bool Again = false;
1753     if (!JoinCopy(TheCopy, Again))
1754       if (Again)
1755         TryAgain.push_back(TheCopy);
1756   }
1757   for (unsigned i = 0, e = VirtCopies.size(); i != e; ++i) {
1758     CopyRec &TheCopy = VirtCopies[i];
1759     bool Again = false;
1760     if (!JoinCopy(TheCopy, Again))
1761       if (Again)
1762         TryAgain.push_back(TheCopy);
1763   }
1764 }
1765
1766 void SimpleRegisterCoalescing::joinIntervals() {
1767   DOUT << "********** JOINING INTERVALS ***********\n";
1768
1769   if (NewHeuristic)
1770     JoinQueue = new JoinPriorityQueue<CopyRecSort>(this);
1771
1772   std::vector<CopyRec> TryAgainList;
1773   if (loopInfo->begin() == loopInfo->end()) {
1774     // If there are no loops in the function, join intervals in function order.
1775     for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();
1776          I != E; ++I)
1777       CopyCoalesceInMBB(I, TryAgainList);
1778   } else {
1779     // Otherwise, join intervals in inner loops before other intervals.
1780     // Unfortunately we can't just iterate over loop hierarchy here because
1781     // there may be more MBB's than BB's.  Collect MBB's for sorting.
1782
1783     // Join intervals in the function prolog first. We want to join physical
1784     // registers with virtual registers before the intervals got too long.
1785     std::vector<std::pair<unsigned, MachineBasicBlock*> > MBBs;
1786     for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();I != E;++I){
1787       MachineBasicBlock *MBB = I;
1788       MBBs.push_back(std::make_pair(loopInfo->getLoopDepth(MBB), I));
1789     }
1790
1791     // Sort by loop depth.
1792     std::sort(MBBs.begin(), MBBs.end(), DepthMBBCompare());
1793
1794     // Finally, join intervals in loop nest order.
1795     for (unsigned i = 0, e = MBBs.size(); i != e; ++i)
1796       CopyCoalesceInMBB(MBBs[i].second, TryAgainList);
1797   }
1798   
1799   // Joining intervals can allow other intervals to be joined.  Iteratively join
1800   // until we make no progress.
1801   if (NewHeuristic) {
1802     SmallVector<CopyRec, 16> TryAgain;
1803     bool ProgressMade = true;
1804     while (ProgressMade) {
1805       ProgressMade = false;
1806       while (!JoinQueue->empty()) {
1807         CopyRec R = JoinQueue->pop();
1808         bool Again = false;
1809         bool Success = JoinCopy(R, Again);
1810         if (Success)
1811           ProgressMade = true;
1812         else if (Again)
1813           TryAgain.push_back(R);
1814       }
1815
1816       if (ProgressMade) {
1817         while (!TryAgain.empty()) {
1818           JoinQueue->push(TryAgain.back());
1819           TryAgain.pop_back();
1820         }
1821       }
1822     }
1823   } else {
1824     bool ProgressMade = true;
1825     while (ProgressMade) {
1826       ProgressMade = false;
1827
1828       for (unsigned i = 0, e = TryAgainList.size(); i != e; ++i) {
1829         CopyRec &TheCopy = TryAgainList[i];
1830         if (TheCopy.MI) {
1831           bool Again = false;
1832           bool Success = JoinCopy(TheCopy, Again);
1833           if (Success || !Again) {
1834             TheCopy.MI = 0;   // Mark this one as done.
1835             ProgressMade = true;
1836           }
1837         }
1838       }
1839     }
1840   }
1841
1842   if (NewHeuristic)
1843     delete JoinQueue;  
1844 }
1845
1846 /// Return true if the two specified registers belong to different register
1847 /// classes.  The registers may be either phys or virt regs.
1848 bool SimpleRegisterCoalescing::differingRegisterClasses(unsigned RegA,
1849                                                         unsigned RegB) const {
1850
1851   // Get the register classes for the first reg.
1852   if (TargetRegisterInfo::isPhysicalRegister(RegA)) {
1853     assert(TargetRegisterInfo::isVirtualRegister(RegB) &&
1854            "Shouldn't consider two physregs!");
1855     return !mri_->getRegClass(RegB)->contains(RegA);
1856   }
1857
1858   // Compare against the regclass for the second reg.
1859   const TargetRegisterClass *RegClass = mri_->getRegClass(RegA);
1860   if (TargetRegisterInfo::isVirtualRegister(RegB))
1861     return RegClass != mri_->getRegClass(RegB);
1862   else
1863     return !RegClass->contains(RegB);
1864 }
1865
1866 /// lastRegisterUse - Returns the last use of the specific register between
1867 /// cycles Start and End or NULL if there are no uses.
1868 MachineOperand *
1869 SimpleRegisterCoalescing::lastRegisterUse(unsigned Start, unsigned End,
1870                                           unsigned Reg, unsigned &UseIdx) const{
1871   UseIdx = 0;
1872   if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1873     MachineOperand *LastUse = NULL;
1874     for (MachineRegisterInfo::use_iterator I = mri_->use_begin(Reg),
1875            E = mri_->use_end(); I != E; ++I) {
1876       MachineOperand &Use = I.getOperand();
1877       MachineInstr *UseMI = Use.getParent();
1878       unsigned SrcReg, DstReg;
1879       if (tii_->isMoveInstr(*UseMI, SrcReg, DstReg) && SrcReg == DstReg)
1880         // Ignore identity copies.
1881         continue;
1882       unsigned Idx = li_->getInstructionIndex(UseMI);
1883       if (Idx >= Start && Idx < End && Idx >= UseIdx) {
1884         LastUse = &Use;
1885         UseIdx = Idx;
1886       }
1887     }
1888     return LastUse;
1889   }
1890
1891   int e = (End-1) / InstrSlots::NUM * InstrSlots::NUM;
1892   int s = Start;
1893   while (e >= s) {
1894     // Skip deleted instructions
1895     MachineInstr *MI = li_->getInstructionFromIndex(e);
1896     while ((e - InstrSlots::NUM) >= s && !MI) {
1897       e -= InstrSlots::NUM;
1898       MI = li_->getInstructionFromIndex(e);
1899     }
1900     if (e < s || MI == NULL)
1901       return NULL;
1902
1903     // Ignore identity copies.
1904     unsigned SrcReg, DstReg;
1905     if (!(tii_->isMoveInstr(*MI, SrcReg, DstReg) && SrcReg == DstReg))
1906       for (unsigned i = 0, NumOps = MI->getNumOperands(); i != NumOps; ++i) {
1907         MachineOperand &Use = MI->getOperand(i);
1908         if (Use.isRegister() && Use.isUse() && Use.getReg() &&
1909             tri_->regsOverlap(Use.getReg(), Reg)) {
1910           UseIdx = e;
1911           return &Use;
1912         }
1913       }
1914
1915     e -= InstrSlots::NUM;
1916   }
1917
1918   return NULL;
1919 }
1920
1921
1922 void SimpleRegisterCoalescing::printRegName(unsigned reg) const {
1923   if (TargetRegisterInfo::isPhysicalRegister(reg))
1924     cerr << tri_->getName(reg);
1925   else
1926     cerr << "%reg" << reg;
1927 }
1928
1929 void SimpleRegisterCoalescing::releaseMemory() {
1930   JoinedCopies.clear();
1931 }
1932
1933 static bool isZeroLengthInterval(LiveInterval *li) {
1934   for (LiveInterval::Ranges::const_iterator
1935          i = li->ranges.begin(), e = li->ranges.end(); i != e; ++i)
1936     if (i->end - i->start > LiveIntervals::InstrSlots::NUM)
1937       return false;
1938   return true;
1939 }
1940
1941 /// TurnCopyIntoImpDef - If source of the specified copy is an implicit def,
1942 /// turn the copy into an implicit def.
1943 bool
1944 SimpleRegisterCoalescing::TurnCopyIntoImpDef(MachineBasicBlock::iterator &I,
1945                                              MachineBasicBlock *MBB,
1946                                              unsigned DstReg, unsigned SrcReg) {
1947   MachineInstr *CopyMI = &*I;
1948   unsigned CopyIdx = li_->getDefIndex(li_->getInstructionIndex(CopyMI));
1949   if (!li_->hasInterval(SrcReg))
1950     return false;
1951   LiveInterval &SrcInt = li_->getInterval(SrcReg);
1952   if (!SrcInt.empty())
1953     return false;
1954   if (!li_->hasInterval(DstReg))
1955     return false;
1956   LiveInterval &DstInt = li_->getInterval(DstReg);
1957   const LiveRange *DstLR = DstInt.getLiveRangeContaining(CopyIdx);
1958   DstInt.removeValNo(DstLR->valno);
1959   CopyMI->setDesc(tii_->get(TargetInstrInfo::IMPLICIT_DEF));
1960   for (int i = CopyMI->getNumOperands() - 1, e = 0; i > e; --i)
1961     CopyMI->RemoveOperand(i);
1962   bool NoUse = mri_->use_begin(SrcReg) == mri_->use_end();
1963   if (NoUse) {
1964     for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(SrcReg),
1965            E = mri_->reg_end(); I != E; ) {
1966       assert(I.getOperand().isDef());
1967       MachineInstr *DefMI = &*I;
1968       ++I;
1969       // The implicit_def source has no other uses, delete it.
1970       assert(DefMI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF);
1971       li_->RemoveMachineInstrFromMaps(DefMI);
1972       DefMI->eraseFromParent();
1973     }
1974   }
1975   ++I;
1976   return true;
1977 }
1978
1979
1980 bool SimpleRegisterCoalescing::runOnMachineFunction(MachineFunction &fn) {
1981   mf_ = &fn;
1982   mri_ = &fn.getRegInfo();
1983   tm_ = &fn.getTarget();
1984   tri_ = tm_->getRegisterInfo();
1985   tii_ = tm_->getInstrInfo();
1986   li_ = &getAnalysis<LiveIntervals>();
1987   lv_ = &getAnalysis<LiveVariables>();
1988   loopInfo = &getAnalysis<MachineLoopInfo>();
1989
1990   DOUT << "********** SIMPLE REGISTER COALESCING **********\n"
1991        << "********** Function: "
1992        << ((Value*)mf_->getFunction())->getName() << '\n';
1993
1994   allocatableRegs_ = tri_->getAllocatableSet(fn);
1995   for (TargetRegisterInfo::regclass_iterator I = tri_->regclass_begin(),
1996          E = tri_->regclass_end(); I != E; ++I)
1997     allocatableRCRegs_.insert(std::make_pair(*I,
1998                                              tri_->getAllocatableSet(fn, *I)));
1999
2000   // Join (coalesce) intervals if requested.
2001   if (EnableJoining) {
2002     joinIntervals();
2003     DOUT << "********** INTERVALS POST JOINING **********\n";
2004     for (LiveIntervals::iterator I = li_->begin(), E = li_->end(); I != E; ++I){
2005       I->second.print(DOUT, tri_);
2006       DOUT << "\n";
2007     }
2008   }
2009
2010   // Perform a final pass over the instructions and compute spill weights
2011   // and remove identity moves.
2012   for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
2013        mbbi != mbbe; ++mbbi) {
2014     MachineBasicBlock* mbb = mbbi;
2015     unsigned loopDepth = loopInfo->getLoopDepth(mbb);
2016
2017     for (MachineBasicBlock::iterator mii = mbb->begin(), mie = mbb->end();
2018          mii != mie; ) {
2019       MachineInstr *MI = mii;
2020       unsigned SrcReg, DstReg;
2021       if (JoinedCopies.count(MI)) {
2022         // Delete all coalesced copies.
2023         if (!tii_->isMoveInstr(*MI, SrcReg, DstReg)) {
2024           assert((MI->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG ||
2025                   MI->getOpcode() == TargetInstrInfo::INSERT_SUBREG) &&
2026                  "Unrecognized copy instruction");
2027           DstReg = MI->getOperand(0).getReg();
2028         }
2029         if (MI->registerDefIsDead(DstReg)) {
2030           LiveInterval &li = li_->getInterval(DstReg);
2031           if (!ShortenDeadCopySrcLiveRange(li, MI))
2032             ShortenDeadCopyLiveRange(li, MI);
2033         }
2034         li_->RemoveMachineInstrFromMaps(MI);
2035         mii = mbbi->erase(mii);
2036         ++numPeep;
2037         continue;
2038       }
2039
2040       // If the move will be an identity move delete it
2041       bool isMove = tii_->isMoveInstr(*mii, SrcReg, DstReg);
2042       if (isMove && SrcReg == DstReg) {
2043         if (li_->hasInterval(SrcReg)) {
2044           LiveInterval &RegInt = li_->getInterval(SrcReg);
2045           // If def of this move instruction is dead, remove its live range
2046           // from the dstination register's live interval.
2047           if (mii->registerDefIsDead(DstReg)) {
2048             if (!ShortenDeadCopySrcLiveRange(RegInt, mii))
2049               ShortenDeadCopyLiveRange(RegInt, mii);
2050           }
2051         }
2052         li_->RemoveMachineInstrFromMaps(mii);
2053         mii = mbbi->erase(mii);
2054         ++numPeep;
2055       } else if (!isMove || !TurnCopyIntoImpDef(mii, mbb, DstReg, SrcReg)) {
2056         SmallSet<unsigned, 4> UniqueUses;
2057         for (unsigned i = 0, e = mii->getNumOperands(); i != e; ++i) {
2058           const MachineOperand &mop = mii->getOperand(i);
2059           if (mop.isRegister() && mop.getReg() &&
2060               TargetRegisterInfo::isVirtualRegister(mop.getReg())) {
2061             unsigned reg = mop.getReg();
2062             // Multiple uses of reg by the same instruction. It should not
2063             // contribute to spill weight again.
2064             if (UniqueUses.count(reg) != 0)
2065               continue;
2066             LiveInterval &RegInt = li_->getInterval(reg);
2067             RegInt.weight +=
2068               li_->getSpillWeight(mop.isDef(), mop.isUse(), loopDepth);
2069             UniqueUses.insert(reg);
2070           }
2071         }
2072         ++mii;
2073       }
2074     }
2075   }
2076
2077   for (LiveIntervals::iterator I = li_->begin(), E = li_->end(); I != E; ++I) {
2078     LiveInterval &LI = I->second;
2079     if (TargetRegisterInfo::isVirtualRegister(LI.reg)) {
2080       // If the live interval length is essentially zero, i.e. in every live
2081       // range the use follows def immediately, it doesn't make sense to spill
2082       // it and hope it will be easier to allocate for this li.
2083       if (isZeroLengthInterval(&LI))
2084         LI.weight = HUGE_VALF;
2085       else {
2086         bool isLoad = false;
2087         if (li_->isReMaterializable(LI, isLoad)) {
2088           // If all of the definitions of the interval are re-materializable,
2089           // it is a preferred candidate for spilling. If non of the defs are
2090           // loads, then it's potentially very cheap to re-materialize.
2091           // FIXME: this gets much more complicated once we support non-trivial
2092           // re-materialization.
2093           if (isLoad)
2094             LI.weight *= 0.9F;
2095           else
2096             LI.weight *= 0.5F;
2097         }
2098       }
2099
2100       // Slightly prefer live interval that has been assigned a preferred reg.
2101       if (LI.preference)
2102         LI.weight *= 1.01F;
2103
2104       // Divide the weight of the interval by its size.  This encourages 
2105       // spilling of intervals that are large and have few uses, and
2106       // discourages spilling of small intervals with many uses.
2107       LI.weight /= LI.getSize();
2108     }
2109   }
2110
2111   DEBUG(dump());
2112   return true;
2113 }
2114
2115 /// print - Implement the dump method.
2116 void SimpleRegisterCoalescing::print(std::ostream &O, const Module* m) const {
2117    li_->print(O, m);
2118 }
2119
2120 RegisterCoalescer* llvm::createSimpleRegisterCoalescer() {
2121   return new SimpleRegisterCoalescing();
2122 }
2123
2124 // Make sure that anything that uses RegisterCoalescer pulls in this file...
2125 DEFINING_FILE_FOR(SimpleRegisterCoalescing)