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