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