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