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