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