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