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