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