One more case assuming that subregs have live ranges.
[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(const CoalescerPair &CP,
103                                                     MachineInstr *CopyMI) {
104   // Bail if there is no dst interval - can happen when merging physical subreg
105   // operations.
106   if (!li_->hasInterval(CP.getDstReg()))
107     return false;
108
109   LiveInterval &IntA =
110     li_->getInterval(CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg());
111   LiveInterval &IntB =
112     li_->getInterval(CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg());
113   SlotIndex CopyIdx = li_->getInstructionIndex(CopyMI).getDefIndex();
114
115   // BValNo is a value number in B that is defined by a copy from A.  'B3' in
116   // the example above.
117   LiveInterval::iterator BLR = IntB.FindLiveRangeContaining(CopyIdx);
118   if (BLR == IntB.end()) return false;
119   VNInfo *BValNo = BLR->valno;
120
121   // Get the location that B is defined at.  Two options: either this value has
122   // an unknown definition point or it is defined at CopyIdx.  If unknown, we
123   // can't process it.
124   if (!BValNo->getCopy()) return false;
125   assert(BValNo->def == CopyIdx && "Copy doesn't define the value?");
126
127   // AValNo is the value number in A that defines the copy, A3 in the example.
128   SlotIndex CopyUseIdx = CopyIdx.getUseIndex();
129   LiveInterval::iterator ALR = IntA.FindLiveRangeContaining(CopyUseIdx);
130   // The live range might not exist after fun with physreg coalescing.
131   if (ALR == IntA.end()) return false;
132   VNInfo *AValNo = ALR->valno;
133   // If it's re-defined by an early clobber somewhere in the live range, then
134   // it's not safe to eliminate the copy. FIXME: This is a temporary workaround.
135   // See PR3149:
136   // 172     %ECX<def> = MOV32rr %reg1039<kill>
137   // 180     INLINEASM <es:subl $5,$1
138   //         sbbl $3,$0>, 10, %EAX<def>, 14, %ECX<earlyclobber,def>, 9,
139   //         %EAX<kill>,
140   // 36, <fi#0>, 1, %reg0, 0, 9, %ECX<kill>, 36, <fi#1>, 1, %reg0, 0
141   // 188     %EAX<def> = MOV32rr %EAX<kill>
142   // 196     %ECX<def> = MOV32rr %ECX<kill>
143   // 204     %ECX<def> = MOV32rr %ECX<kill>
144   // 212     %EAX<def> = MOV32rr %EAX<kill>
145   // 220     %EAX<def> = MOV32rr %EAX
146   // 228     %reg1039<def> = MOV32rr %ECX<kill>
147   // The early clobber operand ties ECX input to the ECX def.
148   //
149   // The live interval of ECX is represented as this:
150   // %reg20,inf = [46,47:1)[174,230:0)  0@174-(230) 1@46-(47)
151   // The coalescer has no idea there was a def in the middle of [174,230].
152   if (AValNo->hasRedefByEC())
153     return false;
154
155   // If AValNo is defined as a copy from IntB, we can potentially process this.
156   // Get the instruction that defines this value number.
157   if (!CP.isCoalescable(AValNo->getCopy()))
158     return false;
159
160   // Get the LiveRange in IntB that this value number starts with.
161   LiveInterval::iterator ValLR =
162     IntB.FindLiveRangeContaining(AValNo->def.getPrevSlot());
163   if (ValLR == IntB.end())
164     return false;
165
166   // Make sure that the end of the live range is inside the same block as
167   // CopyMI.
168   MachineInstr *ValLREndInst =
169     li_->getInstructionFromIndex(ValLR->end.getPrevSlot());
170   if (!ValLREndInst || ValLREndInst->getParent() != CopyMI->getParent())
171     return false;
172
173   // Okay, we now know that ValLR ends in the same block that the CopyMI
174   // live-range starts.  If there are no intervening live ranges between them in
175   // IntB, we can merge them.
176   if (ValLR+1 != BLR) return false;
177
178   // If a live interval is a physical register, conservatively check if any
179   // of its sub-registers is overlapping the live interval of the virtual
180   // register. If so, do not coalesce.
181   if (TargetRegisterInfo::isPhysicalRegister(IntB.reg) &&
182       *tri_->getSubRegisters(IntB.reg)) {
183     for (const unsigned* SR = tri_->getSubRegisters(IntB.reg); *SR; ++SR)
184       if (li_->hasInterval(*SR) && IntA.overlaps(li_->getInterval(*SR))) {
185         DEBUG({
186             dbgs() << "\t\tInterfere with sub-register ";
187             li_->getInterval(*SR).print(dbgs(), tri_);
188           });
189         return false;
190       }
191   }
192
193   DEBUG({
194       dbgs() << "Extending: ";
195       IntB.print(dbgs(), tri_);
196     });
197
198   SlotIndex FillerStart = ValLR->end, FillerEnd = BLR->start;
199   // We are about to delete CopyMI, so need to remove it as the 'instruction
200   // that defines this value #'. Update the valnum with the new defining
201   // instruction #.
202   BValNo->def  = FillerStart;
203   BValNo->setCopy(0);
204
205   // Okay, we can merge them.  We need to insert a new liverange:
206   // [ValLR.end, BLR.begin) of either value number, then we merge the
207   // two value numbers.
208   IntB.addRange(LiveRange(FillerStart, FillerEnd, BValNo));
209
210   // If the IntB live range is assigned to a physical register, and if that
211   // physreg has sub-registers, update their live intervals as well.
212   if (TargetRegisterInfo::isPhysicalRegister(IntB.reg)) {
213     for (const unsigned *SR = tri_->getSubRegisters(IntB.reg); *SR; ++SR) {
214       LiveInterval &SRLI = li_->getInterval(*SR);
215       SRLI.addRange(LiveRange(FillerStart, FillerEnd,
216                               SRLI.getNextValue(FillerStart, 0, true,
217                                                 li_->getVNInfoAllocator())));
218     }
219   }
220
221   // Okay, merge "B1" into the same value number as "B0".
222   if (BValNo != ValLR->valno) {
223     IntB.MergeValueNumberInto(BValNo, ValLR->valno);
224   }
225   DEBUG({
226       dbgs() << "   result = ";
227       IntB.print(dbgs(), tri_);
228       dbgs() << "\n";
229     });
230
231   // If the source instruction was killing the source register before the
232   // merge, unset the isKill marker given the live range has been extended.
233   int UIdx = ValLREndInst->findRegisterUseOperandIdx(IntB.reg, true);
234   if (UIdx != -1) {
235     ValLREndInst->getOperand(UIdx).setIsKill(false);
236   }
237
238   // If the copy instruction was killing the destination register before the
239   // merge, find the last use and trim the live range. That will also add the
240   // isKill marker.
241   if (ALR->end == CopyIdx)
242     TrimLiveIntervalToLastUse(CopyUseIdx, CopyMI->getParent(), IntA, ALR);
243
244   ++numExtends;
245   return true;
246 }
247
248 /// HasOtherReachingDefs - Return true if there are definitions of IntB
249 /// other than BValNo val# that can reach uses of AValno val# of IntA.
250 bool SimpleRegisterCoalescing::HasOtherReachingDefs(LiveInterval &IntA,
251                                                     LiveInterval &IntB,
252                                                     VNInfo *AValNo,
253                                                     VNInfo *BValNo) {
254   for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
255        AI != AE; ++AI) {
256     if (AI->valno != AValNo) continue;
257     LiveInterval::Ranges::iterator BI =
258       std::upper_bound(IntB.ranges.begin(), IntB.ranges.end(), AI->start);
259     if (BI != IntB.ranges.begin())
260       --BI;
261     for (; BI != IntB.ranges.end() && AI->end >= BI->start; ++BI) {
262       if (BI->valno == BValNo)
263         continue;
264       // When BValNo is null, we're looking for a dummy clobber-value for a subreg.
265       if (!BValNo && !BI->valno->isDefAccurate() && !BI->valno->getCopy())
266         continue;
267       if (BI->start <= AI->start && BI->end > AI->start)
268         return true;
269       if (BI->start > AI->start && BI->start < AI->end)
270         return true;
271     }
272   }
273   return false;
274 }
275
276 static void
277 TransferImplicitOps(MachineInstr *MI, MachineInstr *NewMI) {
278   for (unsigned i = MI->getDesc().getNumOperands(), e = MI->getNumOperands();
279        i != e; ++i) {
280     MachineOperand &MO = MI->getOperand(i);
281     if (MO.isReg() && MO.isImplicit())
282       NewMI->addOperand(MO);
283   }
284 }
285
286 /// RemoveCopyByCommutingDef - We found a non-trivially-coalescable copy with
287 /// IntA being the source and IntB being the dest, thus this defines a value
288 /// number in IntB.  If the source value number (in IntA) is defined by a
289 /// commutable instruction and its other operand is coalesced to the copy dest
290 /// register, see if we can transform the copy into a noop by commuting the
291 /// definition. For example,
292 ///
293 ///  A3 = op A2 B0<kill>
294 ///    ...
295 ///  B1 = A3      <- this copy
296 ///    ...
297 ///     = op A3   <- more uses
298 ///
299 /// ==>
300 ///
301 ///  B2 = op B0 A2<kill>
302 ///    ...
303 ///  B1 = B2      <- now an identify copy
304 ///    ...
305 ///     = op B2   <- more uses
306 ///
307 /// This returns true if an interval was modified.
308 ///
309 bool SimpleRegisterCoalescing::RemoveCopyByCommutingDef(const CoalescerPair &CP,
310                                                         MachineInstr *CopyMI) {
311   // FIXME: For now, only eliminate the copy by commuting its def when the
312   // source register is a virtual register. We want to guard against cases
313   // where the copy is a back edge copy and commuting the def lengthen the
314   // live interval of the source register to the entire loop.
315   if (CP.isPhys() && CP.isFlipped())
316     return false;
317
318   // Bail if there is no dst interval.
319   if (!li_->hasInterval(CP.getDstReg()))
320     return false;
321
322   SlotIndex CopyIdx =
323     li_->getInstructionIndex(CopyMI).getDefIndex();
324
325   LiveInterval &IntA =
326     li_->getInterval(CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg());
327   LiveInterval &IntB =
328     li_->getInterval(CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg());
329
330   // BValNo is a value number in B that is defined by a copy from A. 'B3' in
331   // the example above.
332   LiveInterval::iterator BLR = IntB.FindLiveRangeContaining(CopyIdx);
333   if (BLR == IntB.end()) return false;
334   VNInfo *BValNo = BLR->valno;
335
336   // Get the location that B is defined at.  Two options: either this value has
337   // an unknown definition point or it is defined at CopyIdx.  If unknown, we
338   // can't process it.
339   if (!BValNo->getCopy()) return false;
340   assert(BValNo->def == CopyIdx && "Copy doesn't define the value?");
341
342   // AValNo is the value number in A that defines the copy, A3 in the example.
343   LiveInterval::iterator ALR =
344     IntA.FindLiveRangeContaining(CopyIdx.getUseIndex()); // 
345
346   assert(ALR != IntA.end() && "Live range not found!");
347   VNInfo *AValNo = ALR->valno;
348   // If other defs can reach uses of this def, then it's not safe to perform
349   // the optimization. FIXME: Do isPHIDef and isDefAccurate both need to be
350   // tested?
351   if (AValNo->isPHIDef() || !AValNo->isDefAccurate() ||
352       AValNo->isUnused() || AValNo->hasPHIKill())
353     return false;
354   MachineInstr *DefMI = li_->getInstructionFromIndex(AValNo->def);
355   if (!DefMI)
356     return false;
357   const TargetInstrDesc &TID = DefMI->getDesc();
358   if (!TID.isCommutable())
359     return false;
360   // If DefMI is a two-address instruction then commuting it will change the
361   // destination register.
362   int DefIdx = DefMI->findRegisterDefOperandIdx(IntA.reg);
363   assert(DefIdx != -1);
364   unsigned UseOpIdx;
365   if (!DefMI->isRegTiedToUseOperand(DefIdx, &UseOpIdx))
366     return false;
367   unsigned Op1, Op2, NewDstIdx;
368   if (!tii_->findCommutedOpIndices(DefMI, Op1, Op2))
369     return false;
370   if (Op1 == UseOpIdx)
371     NewDstIdx = Op2;
372   else if (Op2 == UseOpIdx)
373     NewDstIdx = Op1;
374   else
375     return false;
376
377   MachineOperand &NewDstMO = DefMI->getOperand(NewDstIdx);
378   unsigned NewReg = NewDstMO.getReg();
379   if (NewReg != IntB.reg || !NewDstMO.isKill())
380     return false;
381
382   // Make sure there are no other definitions of IntB that would reach the
383   // uses which the new definition can reach.
384   if (HasOtherReachingDefs(IntA, IntB, AValNo, BValNo))
385     return false;
386
387   bool BHasSubRegs = false;
388   if (TargetRegisterInfo::isPhysicalRegister(IntB.reg))
389     BHasSubRegs = *tri_->getSubRegisters(IntB.reg);
390
391   // Abort if the subregisters of IntB.reg have values that are not simply the
392   // clobbers from the superreg.
393   if (BHasSubRegs)
394     for (const unsigned *SR = tri_->getSubRegisters(IntB.reg); *SR; ++SR)
395       if (HasOtherReachingDefs(IntA, li_->getInterval(*SR), AValNo, 0))
396         return false;
397
398   // If some of the uses of IntA.reg is already coalesced away, return false.
399   // It's not possible to determine whether it's safe to perform the coalescing.
400   for (MachineRegisterInfo::use_nodbg_iterator UI = 
401          mri_->use_nodbg_begin(IntA.reg), 
402        UE = mri_->use_nodbg_end(); UI != UE; ++UI) {
403     MachineInstr *UseMI = &*UI;
404     SlotIndex UseIdx = li_->getInstructionIndex(UseMI);
405     LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx);
406     if (ULR == IntA.end())
407       continue;
408     if (ULR->valno == AValNo && JoinedCopies.count(UseMI))
409       return false;
410   }
411
412   // At this point we have decided that it is legal to do this
413   // transformation.  Start by commuting the instruction.
414   MachineBasicBlock *MBB = DefMI->getParent();
415   MachineInstr *NewMI = tii_->commuteInstruction(DefMI);
416   if (!NewMI)
417     return false;
418   if (NewMI != DefMI) {
419     li_->ReplaceMachineInstrInMaps(DefMI, NewMI);
420     MBB->insert(DefMI, NewMI);
421     MBB->erase(DefMI);
422   }
423   unsigned OpIdx = NewMI->findRegisterUseOperandIdx(IntA.reg, false);
424   NewMI->getOperand(OpIdx).setIsKill();
425
426   bool BHasPHIKill = BValNo->hasPHIKill();
427   SmallVector<VNInfo*, 4> BDeadValNos;
428   std::map<SlotIndex, SlotIndex> BExtend;
429
430   // If ALR and BLR overlaps and end of BLR extends beyond end of ALR, e.g.
431   // A = or A, B
432   // ...
433   // B = A
434   // ...
435   // C = A<kill>
436   // ...
437   //   = B
438   bool Extended = BLR->end > ALR->end && ALR->end != ALR->start;
439   if (Extended)
440     BExtend[ALR->end] = BLR->end;
441
442   // Update uses of IntA of the specific Val# with IntB.
443   for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(IntA.reg),
444          UE = mri_->use_end(); UI != UE;) {
445     MachineOperand &UseMO = UI.getOperand();
446     MachineInstr *UseMI = &*UI;
447     ++UI;
448     if (JoinedCopies.count(UseMI))
449       continue;
450     if (UseMI->isDebugValue()) {
451       // FIXME These don't have an instruction index.  Not clear we have enough
452       // info to decide whether to do this replacement or not.  For now do it.
453       UseMO.setReg(NewReg);
454       continue;
455     }
456     SlotIndex UseIdx = li_->getInstructionIndex(UseMI).getUseIndex();
457     LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx);
458     if (ULR == IntA.end() || ULR->valno != AValNo)
459       continue;
460     UseMO.setReg(NewReg);
461     if (UseMI == CopyMI)
462       continue;
463     if (UseMO.isKill()) {
464       if (Extended)
465         UseMO.setIsKill(false);
466     }
467     unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
468     if (UseMI->isCopy()) {
469       if (UseMI->getOperand(0).getReg() != IntB.reg ||
470           UseMI->getOperand(0).getSubReg())
471         continue;
472     } else if (tii_->isMoveInstr(*UseMI, SrcReg, DstReg, SrcSubIdx, DstSubIdx)){
473       if (DstReg != IntB.reg || DstSubIdx)
474         continue;
475     } else
476       continue;
477     // This copy will become a noop. If it's defining a new val#,
478     // remove that val# as well. However this live range is being
479     // extended to the end of the existing live range defined by the copy.
480     SlotIndex DefIdx = UseIdx.getDefIndex();
481     const LiveRange *DLR = IntB.getLiveRangeContaining(DefIdx);
482     BHasPHIKill |= DLR->valno->hasPHIKill();
483     assert(DLR->valno->def == DefIdx);
484     BDeadValNos.push_back(DLR->valno);
485     BExtend[DLR->start] = DLR->end;
486     JoinedCopies.insert(UseMI);
487   }
488
489   // We need to insert a new liverange: [ALR.start, LastUse). It may be we can
490   // simply extend BLR if CopyMI doesn't end the range.
491   DEBUG({
492       dbgs() << "Extending: ";
493       IntB.print(dbgs(), tri_);
494     });
495
496   // Remove val#'s defined by copies that will be coalesced away.
497   for (unsigned i = 0, e = BDeadValNos.size(); i != e; ++i) {
498     VNInfo *DeadVNI = BDeadValNos[i];
499     if (BHasSubRegs) {
500       for (const unsigned *SR = tri_->getSubRegisters(IntB.reg); *SR; ++SR) {
501         LiveInterval &SRLI = li_->getInterval(*SR);
502         if (const LiveRange *SRLR = SRLI.getLiveRangeContaining(DeadVNI->def))
503           SRLI.removeValNo(SRLR->valno);
504       }
505     }
506     IntB.removeValNo(BDeadValNos[i]);
507   }
508
509   // Extend BValNo by merging in IntA live ranges of AValNo. Val# definition
510   // is updated.
511   VNInfo *ValNo = BValNo;
512   ValNo->def = AValNo->def;
513   ValNo->setCopy(0);
514   for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
515        AI != AE; ++AI) {
516     if (AI->valno != AValNo) continue;
517     SlotIndex End = AI->end;
518     std::map<SlotIndex, SlotIndex>::iterator
519       EI = BExtend.find(End);
520     if (EI != BExtend.end())
521       End = EI->second;
522     IntB.addRange(LiveRange(AI->start, End, ValNo));
523   }
524   ValNo->setHasPHIKill(BHasPHIKill);
525
526   DEBUG({
527       dbgs() << "   result = ";
528       IntB.print(dbgs(), tri_);
529       dbgs() << "\nShortening: ";
530       IntA.print(dbgs(), tri_);
531     });
532
533   IntA.removeValNo(AValNo);
534
535   DEBUG({
536       dbgs() << "   result = ";
537       IntA.print(dbgs(), tri_);
538       dbgs() << '\n';
539     });
540
541   ++numCommutes;
542   return true;
543 }
544
545 /// isSameOrFallThroughBB - Return true if MBB == SuccMBB or MBB simply
546 /// fallthoughs to SuccMBB.
547 static bool isSameOrFallThroughBB(MachineBasicBlock *MBB,
548                                   MachineBasicBlock *SuccMBB,
549                                   const TargetInstrInfo *tii_) {
550   if (MBB == SuccMBB)
551     return true;
552   MachineBasicBlock *TBB = 0, *FBB = 0;
553   SmallVector<MachineOperand, 4> Cond;
554   return !tii_->AnalyzeBranch(*MBB, TBB, FBB, Cond) && !TBB && !FBB &&
555     MBB->isSuccessor(SuccMBB);
556 }
557
558 /// removeRange - Wrapper for LiveInterval::removeRange. This removes a range
559 /// from a physical register live interval as well as from the live intervals
560 /// of its sub-registers.
561 static void removeRange(LiveInterval &li,
562                         SlotIndex Start, SlotIndex End,
563                         LiveIntervals *li_, const TargetRegisterInfo *tri_) {
564   li.removeRange(Start, End, true);
565   if (TargetRegisterInfo::isPhysicalRegister(li.reg)) {
566     for (const unsigned* SR = tri_->getSubRegisters(li.reg); *SR; ++SR) {
567       if (!li_->hasInterval(*SR))
568         continue;
569       LiveInterval &sli = li_->getInterval(*SR);
570       SlotIndex RemoveStart = Start;
571       SlotIndex RemoveEnd = Start;
572
573       while (RemoveEnd != End) {
574         LiveInterval::iterator LR = sli.FindLiveRangeContaining(RemoveStart);
575         if (LR == sli.end())
576           break;
577         RemoveEnd = (LR->end < End) ? LR->end : End;
578         sli.removeRange(RemoveStart, RemoveEnd, true);
579         RemoveStart = RemoveEnd;
580       }
581     }
582   }
583 }
584
585 /// TrimLiveIntervalToLastUse - If there is a last use in the same basic block
586 /// as the copy instruction, trim the live interval to the last use and return
587 /// true.
588 bool
589 SimpleRegisterCoalescing::TrimLiveIntervalToLastUse(SlotIndex CopyIdx,
590                                                     MachineBasicBlock *CopyMBB,
591                                                     LiveInterval &li,
592                                                     const LiveRange *LR) {
593   SlotIndex MBBStart = li_->getMBBStartIdx(CopyMBB);
594   SlotIndex LastUseIdx;
595   MachineOperand *LastUse =
596     lastRegisterUse(LR->start, CopyIdx.getPrevSlot(), li.reg, LastUseIdx);
597   if (LastUse) {
598     MachineInstr *LastUseMI = LastUse->getParent();
599     if (!isSameOrFallThroughBB(LastUseMI->getParent(), CopyMBB, tii_)) {
600       // r1024 = op
601       // ...
602       // BB1:
603       //       = r1024
604       //
605       // BB2:
606       // r1025<dead> = r1024<kill>
607       if (MBBStart < LR->end)
608         removeRange(li, MBBStart, LR->end, li_, tri_);
609       return true;
610     }
611
612     // There are uses before the copy, just shorten the live range to the end
613     // of last use.
614     LastUse->setIsKill();
615     removeRange(li, LastUseIdx.getDefIndex(), LR->end, li_, tri_);
616     unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
617     if ((LastUseMI->isCopy() && !LastUseMI->getOperand(0).getSubReg()) ||
618         (tii_->isMoveInstr(*LastUseMI, SrcReg, DstReg, SrcSubIdx, DstSubIdx) &&
619          DstReg == li.reg && DstSubIdx == 0)) {
620       // Last use is itself an identity code.
621       int DeadIdx = LastUseMI->findRegisterDefOperandIdx(li.reg,
622                                                          false, false, tri_);
623       LastUseMI->getOperand(DeadIdx).setIsDead();
624     }
625     return true;
626   }
627
628   // Is it livein?
629   if (LR->start <= MBBStart && LR->end > MBBStart) {
630     if (LR->start == li_->getZeroIndex()) {
631       assert(TargetRegisterInfo::isPhysicalRegister(li.reg));
632       // Live-in to the function but dead. Remove it from entry live-in set.
633       mf_->begin()->removeLiveIn(li.reg);
634     }
635     // FIXME: Shorten intervals in BBs that reaches this BB.
636   }
637
638   return false;
639 }
640
641 /// ReMaterializeTrivialDef - If the source of a copy is defined by a trivial
642 /// computation, replace the copy by rematerialize the definition.
643 bool SimpleRegisterCoalescing::ReMaterializeTrivialDef(LiveInterval &SrcInt,
644                                                        unsigned DstReg,
645                                                        unsigned DstSubIdx,
646                                                        MachineInstr *CopyMI) {
647   SlotIndex CopyIdx = li_->getInstructionIndex(CopyMI).getUseIndex();
648   LiveInterval::iterator SrcLR = SrcInt.FindLiveRangeContaining(CopyIdx);
649   assert(SrcLR != SrcInt.end() && "Live range not found!");
650   VNInfo *ValNo = SrcLR->valno;
651   // If other defs can reach uses of this def, then it's not safe to perform
652   // the optimization. FIXME: Do isPHIDef and isDefAccurate both need to be
653   // tested?
654   if (ValNo->isPHIDef() || !ValNo->isDefAccurate() ||
655       ValNo->isUnused() || ValNo->hasPHIKill())
656     return false;
657   MachineInstr *DefMI = li_->getInstructionFromIndex(ValNo->def);
658   assert(DefMI && "Defining instruction disappeared");
659   const TargetInstrDesc &TID = DefMI->getDesc();
660   if (!TID.isAsCheapAsAMove())
661     return false;
662   if (!tii_->isTriviallyReMaterializable(DefMI, AA))
663     return false;
664   bool SawStore = false;
665   if (!DefMI->isSafeToMove(tii_, AA, SawStore))
666     return false;
667   if (TID.getNumDefs() != 1)
668     return false;
669   if (!DefMI->isImplicitDef()) {
670     // Make sure the copy destination register class fits the instruction
671     // definition register class. The mismatch can happen as a result of earlier
672     // extract_subreg, insert_subreg, subreg_to_reg coalescing.
673     const TargetRegisterClass *RC = TID.OpInfo[0].getRegClass(tri_);
674     if (TargetRegisterInfo::isVirtualRegister(DstReg)) {
675       if (mri_->getRegClass(DstReg) != RC)
676         return false;
677     } else if (!RC->contains(DstReg))
678       return false;
679   }
680
681   // If destination register has a sub-register index on it, make sure it mtches
682   // the instruction register class.
683   if (DstSubIdx) {
684     const TargetInstrDesc &TID = DefMI->getDesc();
685     if (TID.getNumDefs() != 1)
686       return false;
687     const TargetRegisterClass *DstRC = mri_->getRegClass(DstReg);
688     const TargetRegisterClass *DstSubRC =
689       DstRC->getSubRegisterRegClass(DstSubIdx);
690     const TargetRegisterClass *DefRC = TID.OpInfo[0].getRegClass(tri_);
691     if (DefRC == DstRC)
692       DstSubIdx = 0;
693     else if (DefRC != DstSubRC)
694       return false;
695   }
696
697   RemoveCopyFlag(DstReg, CopyMI);
698
699   // If copy kills the source register, find the last use and propagate
700   // kill.
701   bool checkForDeadDef = false;
702   MachineBasicBlock *MBB = CopyMI->getParent();
703   if (SrcLR->end == CopyIdx.getDefIndex())
704     if (!TrimLiveIntervalToLastUse(CopyIdx, MBB, SrcInt, SrcLR)) {
705       checkForDeadDef = true;
706     }
707
708   MachineBasicBlock::iterator MII =
709     llvm::next(MachineBasicBlock::iterator(CopyMI));
710   tii_->reMaterialize(*MBB, MII, DstReg, DstSubIdx, DefMI, *tri_);
711   MachineInstr *NewMI = prior(MII);
712
713   if (checkForDeadDef) {
714     // PR4090 fix: Trim interval failed because there was no use of the
715     // source interval in this MBB. If the def is in this MBB too then we
716     // should mark it dead:
717     if (DefMI->getParent() == MBB) {
718       DefMI->addRegisterDead(SrcInt.reg, tri_);
719       SrcLR->end = SrcLR->start.getNextSlot();
720     }
721   }
722
723   // CopyMI may have implicit operands, transfer them over to the newly
724   // rematerialized instruction. And update implicit def interval valnos.
725   for (unsigned i = CopyMI->getDesc().getNumOperands(),
726          e = CopyMI->getNumOperands(); i != e; ++i) {
727     MachineOperand &MO = CopyMI->getOperand(i);
728     if (MO.isReg() && MO.isImplicit())
729       NewMI->addOperand(MO);
730     if (MO.isDef())
731       RemoveCopyFlag(MO.getReg(), CopyMI);
732   }
733
734   TransferImplicitOps(CopyMI, NewMI);
735   li_->ReplaceMachineInstrInMaps(CopyMI, NewMI);
736   CopyMI->eraseFromParent();
737   ReMatCopies.insert(CopyMI);
738   ReMatDefs.insert(DefMI);
739   DEBUG(dbgs() << "Remat: " << *NewMI);
740   ++NumReMats;
741   return true;
742 }
743
744 /// UpdateRegDefsUses - Replace all defs and uses of SrcReg to DstReg and
745 /// update the subregister number if it is not zero. If DstReg is a
746 /// physical register and the existing subregister number of the def / use
747 /// being updated is not zero, make sure to set it to the correct physical
748 /// subregister.
749 void
750 SimpleRegisterCoalescing::UpdateRegDefsUses(const CoalescerPair &CP) {
751   bool DstIsPhys = CP.isPhys();
752   unsigned SrcReg = CP.getSrcReg();
753   unsigned DstReg = CP.getDstReg();
754   unsigned SubIdx = CP.getSubIdx();
755
756   for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(SrcReg);
757        MachineInstr *UseMI = I.skipInstruction();) {
758     // A PhysReg copy that won't be coalesced can perhaps be rematerialized
759     // instead.
760     if (DstIsPhys) {
761       unsigned CopySrcReg, CopyDstReg, CopySrcSubIdx, CopyDstSubIdx;
762       if (tii_->isMoveInstr(*UseMI, CopySrcReg, CopyDstReg,
763                             CopySrcSubIdx, CopyDstSubIdx) &&
764           CopySrcSubIdx == 0 && CopyDstSubIdx == 0 &&
765           CopySrcReg != CopyDstReg && CopySrcReg == SrcReg &&
766           CopyDstReg != DstReg && !JoinedCopies.count(UseMI) &&
767           ReMaterializeTrivialDef(li_->getInterval(SrcReg), CopyDstReg, 0,
768                                   UseMI))
769         continue;
770     }
771
772     SmallVector<unsigned,8> Ops;
773     bool Reads, Writes;
774     tie(Reads, Writes) = UseMI->readsWritesVirtualRegister(SrcReg, &Ops);
775     bool Kills = false, Deads = false;
776
777     // Replace SrcReg with DstReg in all UseMI operands.
778     for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
779       MachineOperand &MO = UseMI->getOperand(Ops[i]);
780       Kills |= MO.isKill();
781       Deads |= MO.isDead();
782
783       if (DstIsPhys)
784         MO.substPhysReg(DstReg, *tri_);
785       else
786         MO.substVirtReg(DstReg, SubIdx, *tri_);
787     }
788
789     // This instruction is a copy that will be removed.
790     if (JoinedCopies.count(UseMI))
791       continue;
792
793     if (SubIdx) {
794       // If UseMI was a simple SrcReg def, make sure we didn't turn it into a
795       // read-modify-write of DstReg.
796       if (Deads)
797         UseMI->addRegisterDead(DstReg, tri_);
798       else if (!Reads && Writes)
799         UseMI->addRegisterDefined(DstReg, tri_);
800
801       // Kill flags apply to the whole physical register.
802       if (DstIsPhys && Kills)
803         UseMI->addRegisterKilled(DstReg, tri_);
804     }
805
806     DEBUG({
807         dbgs() << "\t\tupdated: ";
808         if (!UseMI->isDebugValue())
809           dbgs() << li_->getInstructionIndex(UseMI) << "\t";
810         dbgs() << *UseMI;
811       });
812
813
814     // After updating the operand, check if the machine instruction has
815     // become a copy. If so, update its val# information.
816     const TargetInstrDesc &TID = UseMI->getDesc();
817     if (DstIsPhys || TID.getNumDefs() != 1 || TID.getNumOperands() <= 2)
818       continue;
819
820     unsigned CopySrcReg, CopyDstReg, CopySrcSubIdx, CopyDstSubIdx;
821     if (tii_->isMoveInstr(*UseMI, CopySrcReg, CopyDstReg,
822                           CopySrcSubIdx, CopyDstSubIdx) &&
823         CopySrcReg != CopyDstReg &&
824         (TargetRegisterInfo::isVirtualRegister(CopyDstReg) ||
825          allocatableRegs_[CopyDstReg])) {
826       LiveInterval &LI = li_->getInterval(CopyDstReg);
827       SlotIndex DefIdx =
828         li_->getInstructionIndex(UseMI).getDefIndex();
829       if (const LiveRange *DLR = LI.getLiveRangeContaining(DefIdx)) {
830         if (DLR->valno->def == DefIdx)
831           DLR->valno->setCopy(UseMI);
832       }
833     }
834   }
835 }
836
837 /// removeIntervalIfEmpty - Check if the live interval of a physical register
838 /// is empty, if so remove it and also remove the empty intervals of its
839 /// sub-registers. Return true if live interval is removed.
840 static bool removeIntervalIfEmpty(LiveInterval &li, LiveIntervals *li_,
841                                   const TargetRegisterInfo *tri_) {
842   if (li.empty()) {
843     if (TargetRegisterInfo::isPhysicalRegister(li.reg))
844       for (const unsigned* SR = tri_->getSubRegisters(li.reg); *SR; ++SR) {
845         if (!li_->hasInterval(*SR))
846           continue;
847         LiveInterval &sli = li_->getInterval(*SR);
848         if (sli.empty())
849           li_->removeInterval(*SR);
850       }
851     li_->removeInterval(li.reg);
852     return true;
853   }
854   return false;
855 }
856
857 /// ShortenDeadCopyLiveRange - Shorten a live range defined by a dead copy.
858 /// Return true if live interval is removed.
859 bool SimpleRegisterCoalescing::ShortenDeadCopyLiveRange(LiveInterval &li,
860                                                         MachineInstr *CopyMI) {
861   SlotIndex CopyIdx = li_->getInstructionIndex(CopyMI);
862   LiveInterval::iterator MLR =
863     li.FindLiveRangeContaining(CopyIdx.getDefIndex());
864   if (MLR == li.end())
865     return false;  // Already removed by ShortenDeadCopySrcLiveRange.
866   SlotIndex RemoveStart = MLR->start;
867   SlotIndex RemoveEnd = MLR->end;
868   SlotIndex DefIdx = CopyIdx.getDefIndex();
869   // Remove the liverange that's defined by this.
870   if (RemoveStart == DefIdx && RemoveEnd == DefIdx.getStoreIndex()) {
871     removeRange(li, RemoveStart, RemoveEnd, li_, tri_);
872     return removeIntervalIfEmpty(li, li_, tri_);
873   }
874   return false;
875 }
876
877 /// RemoveDeadDef - If a def of a live interval is now determined dead, remove
878 /// the val# it defines. If the live interval becomes empty, remove it as well.
879 bool SimpleRegisterCoalescing::RemoveDeadDef(LiveInterval &li,
880                                              MachineInstr *DefMI) {
881   SlotIndex DefIdx = li_->getInstructionIndex(DefMI).getDefIndex();
882   LiveInterval::iterator MLR = li.FindLiveRangeContaining(DefIdx);
883   if (DefIdx != MLR->valno->def)
884     return false;
885   li.removeValNo(MLR->valno);
886   return removeIntervalIfEmpty(li, li_, tri_);
887 }
888
889 void SimpleRegisterCoalescing::RemoveCopyFlag(unsigned DstReg,
890                                               const MachineInstr *CopyMI) {
891   SlotIndex DefIdx = li_->getInstructionIndex(CopyMI).getDefIndex();
892   if (li_->hasInterval(DstReg)) {
893     LiveInterval &LI = li_->getInterval(DstReg);
894     if (const LiveRange *LR = LI.getLiveRangeContaining(DefIdx))
895       if (LR->valno->getCopy() == CopyMI)
896         LR->valno->setCopy(0);
897   }
898   if (!TargetRegisterInfo::isPhysicalRegister(DstReg))
899     return;
900   for (const unsigned* AS = tri_->getAliasSet(DstReg); *AS; ++AS) {
901     if (!li_->hasInterval(*AS))
902       continue;
903     LiveInterval &LI = li_->getInterval(*AS);
904     if (const LiveRange *LR = LI.getLiveRangeContaining(DefIdx))
905       if (LR->valno->getCopy() == CopyMI)
906         LR->valno->setCopy(0);
907   }
908 }
909
910 /// PropagateDeadness - Propagate the dead marker to the instruction which
911 /// defines the val#.
912 static void PropagateDeadness(LiveInterval &li, MachineInstr *CopyMI,
913                               SlotIndex &LRStart, LiveIntervals *li_,
914                               const TargetRegisterInfo* tri_) {
915   MachineInstr *DefMI =
916     li_->getInstructionFromIndex(LRStart.getDefIndex());
917   if (DefMI && DefMI != CopyMI) {
918     int DeadIdx = DefMI->findRegisterDefOperandIdx(li.reg);
919     if (DeadIdx != -1)
920       DefMI->getOperand(DeadIdx).setIsDead();
921     else
922       DefMI->addOperand(MachineOperand::CreateReg(li.reg,
923                    /*def*/true, /*implicit*/true, /*kill*/false, /*dead*/true));
924     LRStart = LRStart.getNextSlot();
925   }
926 }
927
928 /// ShortenDeadCopySrcLiveRange - Shorten a live range as it's artificially
929 /// extended by a dead copy. Mark the last use (if any) of the val# as kill as
930 /// ends the live range there. If there isn't another use, then this live range
931 /// is dead. Return true if live interval is removed.
932 bool
933 SimpleRegisterCoalescing::ShortenDeadCopySrcLiveRange(LiveInterval &li,
934                                                       MachineInstr *CopyMI) {
935   SlotIndex CopyIdx = li_->getInstructionIndex(CopyMI);
936   if (CopyIdx == SlotIndex()) {
937     // FIXME: special case: function live in. It can be a general case if the
938     // first instruction index starts at > 0 value.
939     assert(TargetRegisterInfo::isPhysicalRegister(li.reg));
940     // Live-in to the function but dead. Remove it from entry live-in set.
941     if (mf_->begin()->isLiveIn(li.reg))
942       mf_->begin()->removeLiveIn(li.reg);
943     const LiveRange *LR = li.getLiveRangeContaining(CopyIdx);
944     removeRange(li, LR->start, LR->end, li_, tri_);
945     return removeIntervalIfEmpty(li, li_, tri_);
946   }
947
948   LiveInterval::iterator LR =
949     li.FindLiveRangeContaining(CopyIdx.getPrevIndex().getStoreIndex());
950   if (LR == li.end())
951     // Livein but defined by a phi.
952     return false;
953
954   SlotIndex RemoveStart = LR->start;
955   SlotIndex RemoveEnd = CopyIdx.getStoreIndex();
956   if (LR->end > RemoveEnd)
957     // More uses past this copy? Nothing to do.
958     return false;
959
960   // If there is a last use in the same bb, we can't remove the live range.
961   // Shorten the live interval and return.
962   MachineBasicBlock *CopyMBB = CopyMI->getParent();
963   if (TrimLiveIntervalToLastUse(CopyIdx, CopyMBB, li, LR))
964     return false;
965
966   // There are other kills of the val#. Nothing to do.
967   if (!li.isOnlyLROfValNo(LR))
968     return false;
969
970   MachineBasicBlock *StartMBB = li_->getMBBFromIndex(RemoveStart);
971   if (!isSameOrFallThroughBB(StartMBB, CopyMBB, tii_))
972     // If the live range starts in another mbb and the copy mbb is not a fall
973     // through mbb, then we can only cut the range from the beginning of the
974     // copy mbb.
975     RemoveStart = li_->getMBBStartIdx(CopyMBB).getNextIndex().getBaseIndex();
976
977   if (LR->valno->def == RemoveStart) {
978     // If the def MI defines the val# and this copy is the only kill of the
979     // val#, then propagate the dead marker.
980     PropagateDeadness(li, CopyMI, RemoveStart, li_, tri_);
981     ++numDeadValNo;
982   }
983
984   removeRange(li, RemoveStart, RemoveEnd, li_, tri_);
985   return removeIntervalIfEmpty(li, li_, tri_);
986 }
987
988
989 /// isWinToJoinCrossClass - Return true if it's profitable to coalesce
990 /// two virtual registers from different register classes.
991 bool
992 SimpleRegisterCoalescing::isWinToJoinCrossClass(unsigned SrcReg,
993                                                 unsigned DstReg,
994                                              const TargetRegisterClass *SrcRC,
995                                              const TargetRegisterClass *DstRC,
996                                              const TargetRegisterClass *NewRC) {
997   unsigned NewRCCount = allocatableRCRegs_[NewRC].count();
998   // This heuristics is good enough in practice, but it's obviously not *right*.
999   // 4 is a magic number that works well enough for x86, ARM, etc. It filter
1000   // out all but the most restrictive register classes.
1001   if (NewRCCount > 4 ||
1002       // Early exit if the function is fairly small, coalesce aggressively if
1003       // that's the case. For really special register classes with 3 or
1004       // fewer registers, be a bit more careful.
1005       (li_->getFuncInstructionCount() / NewRCCount) < 8)
1006     return true;
1007   LiveInterval &SrcInt = li_->getInterval(SrcReg);
1008   LiveInterval &DstInt = li_->getInterval(DstReg);
1009   unsigned SrcSize = li_->getApproximateInstructionCount(SrcInt);
1010   unsigned DstSize = li_->getApproximateInstructionCount(DstInt);
1011   if (SrcSize <= NewRCCount && DstSize <= NewRCCount)
1012     return true;
1013   // Estimate *register use density*. If it doubles or more, abort.
1014   unsigned SrcUses = std::distance(mri_->use_nodbg_begin(SrcReg),
1015                                    mri_->use_nodbg_end());
1016   unsigned DstUses = std::distance(mri_->use_nodbg_begin(DstReg),
1017                                    mri_->use_nodbg_end());
1018   unsigned NewUses = SrcUses + DstUses;
1019   unsigned NewSize = SrcSize + DstSize;
1020   if (SrcRC != NewRC && SrcSize > NewRCCount) {
1021     unsigned SrcRCCount = allocatableRCRegs_[SrcRC].count();
1022     if (NewUses*SrcSize*SrcRCCount > 2*SrcUses*NewSize*NewRCCount)
1023       return false;
1024   }
1025   if (DstRC != NewRC && DstSize > NewRCCount) {
1026     unsigned DstRCCount = allocatableRCRegs_[DstRC].count();
1027     if (NewUses*DstSize*DstRCCount > 2*DstUses*NewSize*NewRCCount)
1028       return false;
1029   }
1030   return true;
1031 }
1032
1033
1034 /// JoinCopy - Attempt to join intervals corresponding to SrcReg/DstReg,
1035 /// which are the src/dst of the copy instruction CopyMI.  This returns true
1036 /// if the copy was successfully coalesced away. If it is not currently
1037 /// possible to coalesce this interval, but it may be possible if other
1038 /// things get coalesced, then it returns true by reference in 'Again'.
1039 bool SimpleRegisterCoalescing::JoinCopy(CopyRec &TheCopy, bool &Again) {
1040   MachineInstr *CopyMI = TheCopy.MI;
1041
1042   Again = false;
1043   if (JoinedCopies.count(CopyMI) || ReMatCopies.count(CopyMI))
1044     return false; // Already done.
1045
1046   DEBUG(dbgs() << li_->getInstructionIndex(CopyMI) << '\t' << *CopyMI);
1047
1048   CoalescerPair CP(*tii_, *tri_);
1049   if (!CP.setRegisters(CopyMI)) {
1050     DEBUG(dbgs() << "\tNot coalescable.\n");
1051     return false;
1052   }
1053
1054   // If they are already joined we continue.
1055   if (CP.getSrcReg() == CP.getDstReg()) {
1056     DEBUG(dbgs() << "\tCopy already coalesced.\n");
1057     return false;  // Not coalescable.
1058   }
1059
1060   DEBUG(dbgs() << "\tConsidering merging %reg" << CP.getSrcReg());
1061
1062   // Enforce policies.
1063   if (CP.isPhys()) {
1064     DEBUG(dbgs() <<" with physreg %" << tri_->getName(CP.getDstReg()) << "\n");
1065     // Only coalesce to allocatable physreg.
1066     if (!allocatableRegs_[CP.getDstReg()]) {
1067       DEBUG(dbgs() << "\tRegister is an unallocatable physreg.\n");
1068       return false;  // Not coalescable.
1069     }
1070   } else {
1071     DEBUG({
1072       dbgs() << " with reg%" << CP.getDstReg();
1073       if (CP.getSubIdx())
1074         dbgs() << ":" << tri_->getSubRegIndexName(CP.getSubIdx());
1075       dbgs() << " to " << CP.getNewRC()->getName() << "\n";
1076     });
1077
1078     // Avoid constraining virtual register regclass too much.
1079     if (CP.isCrossClass()) {
1080       if (DisableCrossClassJoin) {
1081         DEBUG(dbgs() << "\tCross-class joins disabled.\n");
1082         return false;
1083       }
1084       if (!isWinToJoinCrossClass(CP.getSrcReg(), CP.getDstReg(),
1085                                  mri_->getRegClass(CP.getSrcReg()),
1086                                  mri_->getRegClass(CP.getDstReg()),
1087                                  CP.getNewRC())) {
1088         DEBUG(dbgs() << "\tAvoid coalescing to constrained register class: "
1089                      << CP.getNewRC()->getName() << ".\n");
1090         Again = true;  // May be possible to coalesce later.
1091         return false;
1092       }
1093     }
1094
1095     // When possible, let DstReg be the larger interval.
1096     if (!CP.getSubIdx() && li_->getInterval(CP.getSrcReg()).ranges.size() >
1097                            li_->getInterval(CP.getDstReg()).ranges.size())
1098       CP.flip();
1099   }
1100
1101   // We need to be careful about coalescing a source physical register with a
1102   // virtual register. Once the coalescing is done, it cannot be broken and
1103   // these are not spillable! If the destination interval uses are far away,
1104   // think twice about coalescing them!
1105   // FIXME: Why are we skipping this test for partial copies?
1106   //        CodeGen/X86/phys_subreg_coalesce-3.ll needs it.
1107   if (!CP.isPartial() && CP.isPhys()) {
1108     LiveInterval &JoinVInt = li_->getInterval(CP.getSrcReg());
1109
1110     // Don't join with physregs that have a ridiculous number of live
1111     // ranges. The data structure performance is really bad when that
1112     // happens.
1113     if (li_->hasInterval(CP.getDstReg()) &&
1114         li_->getInterval(CP.getDstReg()).ranges.size() > 1000) {
1115       mri_->setRegAllocationHint(CP.getSrcReg(), 0, CP.getDstReg());
1116       ++numAborts;
1117       DEBUG(dbgs()
1118            << "\tPhysical register live interval too complicated, abort!\n");
1119       return false;
1120     }
1121
1122     const TargetRegisterClass *RC = mri_->getRegClass(CP.getSrcReg());
1123     unsigned Threshold = allocatableRCRegs_[RC].count() * 2;
1124     unsigned Length = li_->getApproximateInstructionCount(JoinVInt);
1125     if (Length > Threshold &&
1126         std::distance(mri_->use_nodbg_begin(CP.getSrcReg()),
1127                       mri_->use_nodbg_end()) * Threshold < Length) {
1128       // Before giving up coalescing, if definition of source is defined by
1129       // trivial computation, try rematerializing it.
1130       if (!CP.isFlipped() &&
1131           ReMaterializeTrivialDef(JoinVInt, CP.getDstReg(), 0, CopyMI))
1132         return true;
1133
1134       mri_->setRegAllocationHint(CP.getSrcReg(), 0, CP.getDstReg());
1135       ++numAborts;
1136       DEBUG(dbgs() << "\tMay tie down a physical register, abort!\n");
1137       Again = true;  // May be possible to coalesce later.
1138       return false;
1139     }
1140   }
1141
1142   // Okay, attempt to join these two intervals.  On failure, this returns false.
1143   // Otherwise, if one of the intervals being joined is a physreg, this method
1144   // always canonicalizes DstInt to be it.  The output "SrcInt" will not have
1145   // been modified, so we can use this information below to update aliases.
1146   if (!JoinIntervals(CP)) {
1147     // Coalescing failed.
1148
1149     // If definition of source is defined by trivial computation, try
1150     // rematerializing it.
1151     if (!CP.isFlipped() &&
1152         ReMaterializeTrivialDef(li_->getInterval(CP.getSrcReg()),
1153                                 CP.getDstReg(), 0, CopyMI))
1154       return true;
1155
1156     // If we can eliminate the copy without merging the live ranges, do so now.
1157     if (!CP.isPartial()) {
1158       if (AdjustCopiesBackFrom(CP, CopyMI) ||
1159           RemoveCopyByCommutingDef(CP, CopyMI)) {
1160         JoinedCopies.insert(CopyMI);
1161         DEBUG(dbgs() << "\tTrivial!\n");
1162         return true;
1163       }
1164     }
1165
1166     // Otherwise, we are unable to join the intervals.
1167     DEBUG(dbgs() << "\tInterference!\n");
1168     Again = true;  // May be possible to coalesce later.
1169     return false;
1170   }
1171
1172   // Coalescing to a virtual register that is of a sub-register class of the
1173   // other. Make sure the resulting register is set to the right register class.
1174   if (CP.isCrossClass()) {
1175     ++numCrossRCs;
1176     mri_->setRegClass(CP.getDstReg(), CP.getNewRC());
1177   }
1178
1179   // Remember to delete the copy instruction.
1180   JoinedCopies.insert(CopyMI);
1181
1182   UpdateRegDefsUses(CP);
1183
1184   // If we have extended the live range of a physical register, make sure we
1185   // update live-in lists as well.
1186   if (CP.isPhys()) {
1187     SmallVector<MachineBasicBlock*, 16> BlockSeq;
1188     // JoinIntervals invalidates the VNInfos in SrcInt, but we only need the
1189     // ranges for this, and they are preserved.
1190     LiveInterval &SrcInt = li_->getInterval(CP.getSrcReg());
1191     for (LiveInterval::const_iterator I = SrcInt.begin(), E = SrcInt.end();
1192          I != E; ++I ) {
1193       li_->findLiveInMBBs(I->start, I->end, BlockSeq);
1194       for (unsigned idx = 0, size = BlockSeq.size(); idx != size; ++idx) {
1195         MachineBasicBlock &block = *BlockSeq[idx];
1196         if (!block.isLiveIn(CP.getDstReg()))
1197           block.addLiveIn(CP.getDstReg());
1198       }
1199       BlockSeq.clear();
1200     }
1201   }
1202
1203   // SrcReg is guarateed to be the register whose live interval that is
1204   // being merged.
1205   li_->removeInterval(CP.getSrcReg());
1206
1207   // Update regalloc hint.
1208   tri_->UpdateRegAllocHint(CP.getSrcReg(), CP.getDstReg(), *mf_);
1209
1210   DEBUG({
1211     LiveInterval &DstInt = li_->getInterval(CP.getDstReg());
1212     dbgs() << "\tJoined. Result = ";
1213     DstInt.print(dbgs(), tri_);
1214     dbgs() << "\n";
1215   });
1216
1217   ++numJoins;
1218   return true;
1219 }
1220
1221 /// ComputeUltimateVN - Assuming we are going to join two live intervals,
1222 /// compute what the resultant value numbers for each value in the input two
1223 /// ranges will be.  This is complicated by copies between the two which can
1224 /// and will commonly cause multiple value numbers to be merged into one.
1225 ///
1226 /// VN is the value number that we're trying to resolve.  InstDefiningValue
1227 /// keeps track of the new InstDefiningValue assignment for the result
1228 /// LiveInterval.  ThisFromOther/OtherFromThis are sets that keep track of
1229 /// whether a value in this or other is a copy from the opposite set.
1230 /// ThisValNoAssignments/OtherValNoAssignments keep track of value #'s that have
1231 /// already been assigned.
1232 ///
1233 /// ThisFromOther[x] - If x is defined as a copy from the other interval, this
1234 /// contains the value number the copy is from.
1235 ///
1236 static unsigned ComputeUltimateVN(VNInfo *VNI,
1237                                   SmallVector<VNInfo*, 16> &NewVNInfo,
1238                                   DenseMap<VNInfo*, VNInfo*> &ThisFromOther,
1239                                   DenseMap<VNInfo*, VNInfo*> &OtherFromThis,
1240                                   SmallVector<int, 16> &ThisValNoAssignments,
1241                                   SmallVector<int, 16> &OtherValNoAssignments) {
1242   unsigned VN = VNI->id;
1243
1244   // If the VN has already been computed, just return it.
1245   if (ThisValNoAssignments[VN] >= 0)
1246     return ThisValNoAssignments[VN];
1247   assert(ThisValNoAssignments[VN] != -2 && "Cyclic value numbers");
1248
1249   // If this val is not a copy from the other val, then it must be a new value
1250   // number in the destination.
1251   DenseMap<VNInfo*, VNInfo*>::iterator I = ThisFromOther.find(VNI);
1252   if (I == ThisFromOther.end()) {
1253     NewVNInfo.push_back(VNI);
1254     return ThisValNoAssignments[VN] = NewVNInfo.size()-1;
1255   }
1256   VNInfo *OtherValNo = I->second;
1257
1258   // Otherwise, this *is* a copy from the RHS.  If the other side has already
1259   // been computed, return it.
1260   if (OtherValNoAssignments[OtherValNo->id] >= 0)
1261     return ThisValNoAssignments[VN] = OtherValNoAssignments[OtherValNo->id];
1262
1263   // Mark this value number as currently being computed, then ask what the
1264   // ultimate value # of the other value is.
1265   ThisValNoAssignments[VN] = -2;
1266   unsigned UltimateVN =
1267     ComputeUltimateVN(OtherValNo, NewVNInfo, OtherFromThis, ThisFromOther,
1268                       OtherValNoAssignments, ThisValNoAssignments);
1269   return ThisValNoAssignments[VN] = UltimateVN;
1270 }
1271
1272 /// JoinIntervals - Attempt to join these two intervals.  On failure, this
1273 /// returns false.
1274 bool SimpleRegisterCoalescing::JoinIntervals(CoalescerPair &CP) {
1275   LiveInterval &RHS = li_->getInterval(CP.getSrcReg());
1276   DEBUG({ dbgs() << "\t\tRHS = "; RHS.print(dbgs(), tri_); dbgs() << "\n"; });
1277
1278   // If a live interval is a physical register, check for interference with any
1279   // aliases. The interference check implemented here is a bit more conservative
1280   // than the full interfeence check below. We allow overlapping live ranges
1281   // only when one is a copy of the other.
1282   if (CP.isPhys()) {
1283     for (const unsigned *AS = tri_->getAliasSet(CP.getDstReg()); *AS; ++AS){
1284       if (!li_->hasInterval(*AS))
1285         continue;
1286       const LiveInterval &LHS = li_->getInterval(*AS);
1287       LiveInterval::const_iterator LI = LHS.begin();
1288       for (LiveInterval::const_iterator RI = RHS.begin(), RE = RHS.end();
1289            RI != RE; ++RI) {
1290         LI = std::lower_bound(LI, LHS.end(), RI->start);
1291         // Does LHS have an overlapping live range starting before RI?
1292         if ((LI != LHS.begin() && LI[-1].end > RI->start) &&
1293             (RI->start != RI->valno->def ||
1294              !CP.isCoalescable(li_->getInstructionFromIndex(RI->start)))) {
1295           DEBUG({
1296             dbgs() << "\t\tInterference from alias: ";
1297             LHS.print(dbgs(), tri_);
1298             dbgs() << "\n\t\tOverlap at " << RI->start << " and no copy.\n";
1299           });
1300           return false;
1301         }
1302
1303         // Check that LHS ranges beginning in this range are copies.
1304         for (; LI != LHS.end() && LI->start < RI->end; ++LI) {
1305           if (LI->start != LI->valno->def ||
1306               !CP.isCoalescable(li_->getInstructionFromIndex(LI->start))) {
1307             DEBUG({
1308               dbgs() << "\t\tInterference from alias: ";
1309               LHS.print(dbgs(), tri_);
1310               dbgs() << "\n\t\tDef at " << LI->start << " is not a copy.\n";
1311             });
1312             return false;
1313           }
1314         }
1315       }
1316     }
1317   }
1318
1319   // Compute the final value assignment, assuming that the live ranges can be
1320   // coalesced.
1321   SmallVector<int, 16> LHSValNoAssignments;
1322   SmallVector<int, 16> RHSValNoAssignments;
1323   DenseMap<VNInfo*, VNInfo*> LHSValsDefinedFromRHS;
1324   DenseMap<VNInfo*, VNInfo*> RHSValsDefinedFromLHS;
1325   SmallVector<VNInfo*, 16> NewVNInfo;
1326
1327   LiveInterval &LHS = li_->getOrCreateInterval(CP.getDstReg());
1328   DEBUG({ dbgs() << "\t\tLHS = "; LHS.print(dbgs(), tri_); dbgs() << "\n"; });
1329
1330   // Loop over the value numbers of the LHS, seeing if any are defined from
1331   // the RHS.
1332   for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1333        i != e; ++i) {
1334     VNInfo *VNI = *i;
1335     if (VNI->isUnused() || VNI->getCopy() == 0)  // Src not defined by a copy?
1336       continue;
1337
1338     // Never join with a register that has EarlyClobber redefs.
1339     if (VNI->hasRedefByEC())
1340       return false;
1341
1342     // DstReg is known to be a register in the LHS interval.  If the src is
1343     // from the RHS interval, we can use its value #.
1344     if (!CP.isCoalescable(VNI->getCopy()))
1345       continue;
1346
1347     // Figure out the value # from the RHS.
1348     LiveRange *lr = RHS.getLiveRangeContaining(VNI->def.getPrevSlot());
1349     // The copy could be to an aliased physreg.
1350     if (!lr) continue;
1351     LHSValsDefinedFromRHS[VNI] = lr->valno;
1352   }
1353
1354   // Loop over the value numbers of the RHS, seeing if any are defined from
1355   // the LHS.
1356   for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
1357        i != e; ++i) {
1358     VNInfo *VNI = *i;
1359     if (VNI->isUnused() || VNI->getCopy() == 0)  // Src not defined by a copy?
1360       continue;
1361
1362     // Never join with a register that has EarlyClobber redefs.
1363     if (VNI->hasRedefByEC())
1364       return false;
1365
1366     // DstReg is known to be a register in the RHS interval.  If the src is
1367     // from the LHS interval, we can use its value #.
1368     if (!CP.isCoalescable(VNI->getCopy()))
1369       continue;
1370
1371     // Figure out the value # from the LHS.
1372     LiveRange *lr = LHS.getLiveRangeContaining(VNI->def.getPrevSlot());
1373     // The copy could be to an aliased physreg.
1374     if (!lr) continue;
1375     RHSValsDefinedFromLHS[VNI] = lr->valno;
1376   }
1377
1378   LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
1379   RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
1380   NewVNInfo.reserve(LHS.getNumValNums() + RHS.getNumValNums());
1381
1382   for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1383        i != e; ++i) {
1384     VNInfo *VNI = *i;
1385     unsigned VN = VNI->id;
1386     if (LHSValNoAssignments[VN] >= 0 || VNI->isUnused())
1387       continue;
1388     ComputeUltimateVN(VNI, NewVNInfo,
1389                       LHSValsDefinedFromRHS, RHSValsDefinedFromLHS,
1390                       LHSValNoAssignments, RHSValNoAssignments);
1391   }
1392   for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
1393        i != e; ++i) {
1394     VNInfo *VNI = *i;
1395     unsigned VN = VNI->id;
1396     if (RHSValNoAssignments[VN] >= 0 || VNI->isUnused())
1397       continue;
1398     // If this value number isn't a copy from the LHS, it's a new number.
1399     if (RHSValsDefinedFromLHS.find(VNI) == RHSValsDefinedFromLHS.end()) {
1400       NewVNInfo.push_back(VNI);
1401       RHSValNoAssignments[VN] = NewVNInfo.size()-1;
1402       continue;
1403     }
1404
1405     ComputeUltimateVN(VNI, NewVNInfo,
1406                       RHSValsDefinedFromLHS, LHSValsDefinedFromRHS,
1407                       RHSValNoAssignments, LHSValNoAssignments);
1408   }
1409
1410   // Armed with the mappings of LHS/RHS values to ultimate values, walk the
1411   // interval lists to see if these intervals are coalescable.
1412   LiveInterval::const_iterator I = LHS.begin();
1413   LiveInterval::const_iterator IE = LHS.end();
1414   LiveInterval::const_iterator J = RHS.begin();
1415   LiveInterval::const_iterator JE = RHS.end();
1416
1417   // Skip ahead until the first place of potential sharing.
1418   if (I != IE && J != JE) {
1419     if (I->start < J->start) {
1420       I = std::upper_bound(I, IE, J->start);
1421       if (I != LHS.begin()) --I;
1422     } else if (J->start < I->start) {
1423       J = std::upper_bound(J, JE, I->start);
1424       if (J != RHS.begin()) --J;
1425     }
1426   }
1427
1428   while (I != IE && J != JE) {
1429     // Determine if these two live ranges overlap.
1430     bool Overlaps;
1431     if (I->start < J->start) {
1432       Overlaps = I->end > J->start;
1433     } else {
1434       Overlaps = J->end > I->start;
1435     }
1436
1437     // If so, check value # info to determine if they are really different.
1438     if (Overlaps) {
1439       // If the live range overlap will map to the same value number in the
1440       // result liverange, we can still coalesce them.  If not, we can't.
1441       if (LHSValNoAssignments[I->valno->id] !=
1442           RHSValNoAssignments[J->valno->id])
1443         return false;
1444       // If it's re-defined by an early clobber somewhere in the live range,
1445       // then conservatively abort coalescing.
1446       if (NewVNInfo[LHSValNoAssignments[I->valno->id]]->hasRedefByEC())
1447         return false;
1448     }
1449
1450     if (I->end < J->end)
1451       ++I;
1452     else
1453       ++J;
1454   }
1455
1456   // Update kill info. Some live ranges are extended due to copy coalescing.
1457   for (DenseMap<VNInfo*, VNInfo*>::iterator I = LHSValsDefinedFromRHS.begin(),
1458          E = LHSValsDefinedFromRHS.end(); I != E; ++I) {
1459     VNInfo *VNI = I->first;
1460     unsigned LHSValID = LHSValNoAssignments[VNI->id];
1461     if (VNI->hasPHIKill())
1462       NewVNInfo[LHSValID]->setHasPHIKill(true);
1463   }
1464
1465   // Update kill info. Some live ranges are extended due to copy coalescing.
1466   for (DenseMap<VNInfo*, VNInfo*>::iterator I = RHSValsDefinedFromLHS.begin(),
1467          E = RHSValsDefinedFromLHS.end(); I != E; ++I) {
1468     VNInfo *VNI = I->first;
1469     unsigned RHSValID = RHSValNoAssignments[VNI->id];
1470     if (VNI->hasPHIKill())
1471       NewVNInfo[RHSValID]->setHasPHIKill(true);
1472   }
1473
1474   if (LHSValNoAssignments.empty())
1475     LHSValNoAssignments.push_back(-1);
1476   if (RHSValNoAssignments.empty())
1477     RHSValNoAssignments.push_back(-1);
1478
1479   // If we get here, we know that we can coalesce the live ranges.  Ask the
1480   // intervals to coalesce themselves now.
1481   LHS.join(RHS, &LHSValNoAssignments[0], &RHSValNoAssignments[0], NewVNInfo,
1482            mri_);
1483   return true;
1484 }
1485
1486 namespace {
1487   // DepthMBBCompare - Comparison predicate that sort first based on the loop
1488   // depth of the basic block (the unsigned), and then on the MBB number.
1489   struct DepthMBBCompare {
1490     typedef std::pair<unsigned, MachineBasicBlock*> DepthMBBPair;
1491     bool operator()(const DepthMBBPair &LHS, const DepthMBBPair &RHS) const {
1492       // Deeper loops first
1493       if (LHS.first != RHS.first)
1494         return LHS.first > RHS.first;
1495
1496       // Prefer blocks that are more connected in the CFG. This takes care of
1497       // the most difficult copies first while intervals are short.
1498       unsigned cl = LHS.second->pred_size() + LHS.second->succ_size();
1499       unsigned cr = RHS.second->pred_size() + RHS.second->succ_size();
1500       if (cl != cr)
1501         return cl > cr;
1502
1503       // As a last resort, sort by block number.
1504       return LHS.second->getNumber() < RHS.second->getNumber();
1505     }
1506   };
1507 }
1508
1509 void SimpleRegisterCoalescing::CopyCoalesceInMBB(MachineBasicBlock *MBB,
1510                                                std::vector<CopyRec> &TryAgain) {
1511   DEBUG(dbgs() << MBB->getName() << ":\n");
1512
1513   std::vector<CopyRec> VirtCopies;
1514   std::vector<CopyRec> PhysCopies;
1515   std::vector<CopyRec> ImpDefCopies;
1516   for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end();
1517        MII != E;) {
1518     MachineInstr *Inst = MII++;
1519
1520     // If this isn't a copy nor a extract_subreg, we can't join intervals.
1521     unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
1522     bool isInsUndef = false;
1523     if (Inst->isCopy() || Inst->isExtractSubreg()) {
1524       DstReg = Inst->getOperand(0).getReg();
1525       SrcReg = Inst->getOperand(1).getReg();
1526     } else if (Inst->isInsertSubreg()) {
1527       DstReg = Inst->getOperand(0).getReg();
1528       SrcReg = Inst->getOperand(2).getReg();
1529       if (Inst->getOperand(1).isUndef())
1530         isInsUndef = true;
1531     } else if (Inst->isInsertSubreg() || Inst->isSubregToReg()) {
1532       DstReg = Inst->getOperand(0).getReg();
1533       SrcReg = Inst->getOperand(2).getReg();
1534     } else if (!tii_->isMoveInstr(*Inst, SrcReg, DstReg, SrcSubIdx, DstSubIdx))
1535       continue;
1536
1537     bool SrcIsPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
1538     bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
1539     if (isInsUndef ||
1540         (li_->hasInterval(SrcReg) && li_->getInterval(SrcReg).empty()))
1541       ImpDefCopies.push_back(CopyRec(Inst, 0));
1542     else if (SrcIsPhys || DstIsPhys)
1543       PhysCopies.push_back(CopyRec(Inst, 0));
1544     else
1545       VirtCopies.push_back(CopyRec(Inst, 0));
1546   }
1547
1548   // Try coalescing implicit copies and insert_subreg <undef> first,
1549   // followed by copies to / from physical registers, then finally copies
1550   // from virtual registers to virtual registers.
1551   for (unsigned i = 0, e = ImpDefCopies.size(); i != e; ++i) {
1552     CopyRec &TheCopy = ImpDefCopies[i];
1553     bool Again = false;
1554     if (!JoinCopy(TheCopy, Again))
1555       if (Again)
1556         TryAgain.push_back(TheCopy);
1557   }
1558   for (unsigned i = 0, e = PhysCopies.size(); i != e; ++i) {
1559     CopyRec &TheCopy = PhysCopies[i];
1560     bool Again = false;
1561     if (!JoinCopy(TheCopy, Again))
1562       if (Again)
1563         TryAgain.push_back(TheCopy);
1564   }
1565   for (unsigned i = 0, e = VirtCopies.size(); i != e; ++i) {
1566     CopyRec &TheCopy = VirtCopies[i];
1567     bool Again = false;
1568     if (!JoinCopy(TheCopy, Again))
1569       if (Again)
1570         TryAgain.push_back(TheCopy);
1571   }
1572 }
1573
1574 void SimpleRegisterCoalescing::joinIntervals() {
1575   DEBUG(dbgs() << "********** JOINING INTERVALS ***********\n");
1576
1577   std::vector<CopyRec> TryAgainList;
1578   if (loopInfo->empty()) {
1579     // If there are no loops in the function, join intervals in function order.
1580     for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();
1581          I != E; ++I)
1582       CopyCoalesceInMBB(I, TryAgainList);
1583   } else {
1584     // Otherwise, join intervals in inner loops before other intervals.
1585     // Unfortunately we can't just iterate over loop hierarchy here because
1586     // there may be more MBB's than BB's.  Collect MBB's for sorting.
1587
1588     // Join intervals in the function prolog first. We want to join physical
1589     // registers with virtual registers before the intervals got too long.
1590     std::vector<std::pair<unsigned, MachineBasicBlock*> > MBBs;
1591     for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();I != E;++I){
1592       MachineBasicBlock *MBB = I;
1593       MBBs.push_back(std::make_pair(loopInfo->getLoopDepth(MBB), I));
1594     }
1595
1596     // Sort by loop depth.
1597     std::sort(MBBs.begin(), MBBs.end(), DepthMBBCompare());
1598
1599     // Finally, join intervals in loop nest order.
1600     for (unsigned i = 0, e = MBBs.size(); i != e; ++i)
1601       CopyCoalesceInMBB(MBBs[i].second, TryAgainList);
1602   }
1603
1604   // Joining intervals can allow other intervals to be joined.  Iteratively join
1605   // until we make no progress.
1606   bool ProgressMade = true;
1607   while (ProgressMade) {
1608     ProgressMade = false;
1609
1610     for (unsigned i = 0, e = TryAgainList.size(); i != e; ++i) {
1611       CopyRec &TheCopy = TryAgainList[i];
1612       if (!TheCopy.MI)
1613         continue;
1614
1615       bool Again = false;
1616       bool Success = JoinCopy(TheCopy, Again);
1617       if (Success || !Again) {
1618         TheCopy.MI = 0;   // Mark this one as done.
1619         ProgressMade = true;
1620       }
1621     }
1622   }
1623 }
1624
1625 /// Return true if the two specified registers belong to different register
1626 /// classes.  The registers may be either phys or virt regs.
1627 bool
1628 SimpleRegisterCoalescing::differingRegisterClasses(unsigned RegA,
1629                                                    unsigned RegB) const {
1630   // Get the register classes for the first reg.
1631   if (TargetRegisterInfo::isPhysicalRegister(RegA)) {
1632     assert(TargetRegisterInfo::isVirtualRegister(RegB) &&
1633            "Shouldn't consider two physregs!");
1634     return !mri_->getRegClass(RegB)->contains(RegA);
1635   }
1636
1637   // Compare against the regclass for the second reg.
1638   const TargetRegisterClass *RegClassA = mri_->getRegClass(RegA);
1639   if (TargetRegisterInfo::isVirtualRegister(RegB)) {
1640     const TargetRegisterClass *RegClassB = mri_->getRegClass(RegB);
1641     return RegClassA != RegClassB;
1642   }
1643   return !RegClassA->contains(RegB);
1644 }
1645
1646 /// lastRegisterUse - Returns the last (non-debug) use of the specific register
1647 /// between cycles Start and End or NULL if there are no uses.
1648 MachineOperand *
1649 SimpleRegisterCoalescing::lastRegisterUse(SlotIndex Start,
1650                                           SlotIndex End,
1651                                           unsigned Reg,
1652                                           SlotIndex &UseIdx) const{
1653   UseIdx = SlotIndex();
1654   if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1655     MachineOperand *LastUse = NULL;
1656     for (MachineRegisterInfo::use_nodbg_iterator I = mri_->use_nodbg_begin(Reg),
1657            E = mri_->use_nodbg_end(); I != E; ++I) {
1658       MachineOperand &Use = I.getOperand();
1659       MachineInstr *UseMI = Use.getParent();
1660       unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
1661       if (tii_->isMoveInstr(*UseMI, SrcReg, DstReg, SrcSubIdx, DstSubIdx) &&
1662           SrcReg == DstReg && SrcSubIdx == DstSubIdx)
1663         // Ignore identity copies.
1664         continue;
1665       SlotIndex Idx = li_->getInstructionIndex(UseMI);
1666       // FIXME: Should this be Idx != UseIdx? SlotIndex() will return something
1667       // that compares higher than any other interval.
1668       if (Idx >= Start && Idx < End && Idx >= UseIdx) {
1669         LastUse = &Use;
1670         UseIdx = Idx.getUseIndex();
1671       }
1672     }
1673     return LastUse;
1674   }
1675
1676   SlotIndex s = Start;
1677   SlotIndex e = End.getPrevSlot().getBaseIndex();
1678   while (e >= s) {
1679     // Skip deleted instructions
1680     MachineInstr *MI = li_->getInstructionFromIndex(e);
1681     while (e != SlotIndex() && e.getPrevIndex() >= s && !MI) {
1682       e = e.getPrevIndex();
1683       MI = li_->getInstructionFromIndex(e);
1684     }
1685     if (e < s || MI == NULL)
1686       return NULL;
1687
1688     // Ignore identity copies.
1689     unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
1690     if (!(tii_->isMoveInstr(*MI, SrcReg, DstReg, SrcSubIdx, DstSubIdx) &&
1691           SrcReg == DstReg && SrcSubIdx == DstSubIdx))
1692       for (unsigned i = 0, NumOps = MI->getNumOperands(); i != NumOps; ++i) {
1693         MachineOperand &Use = MI->getOperand(i);
1694         if (Use.isReg() && Use.isUse() && Use.getReg() &&
1695             tri_->regsOverlap(Use.getReg(), Reg)) {
1696           UseIdx = e.getUseIndex();
1697           return &Use;
1698         }
1699       }
1700
1701     e = e.getPrevIndex();
1702   }
1703
1704   return NULL;
1705 }
1706
1707 void SimpleRegisterCoalescing::releaseMemory() {
1708   JoinedCopies.clear();
1709   ReMatCopies.clear();
1710   ReMatDefs.clear();
1711 }
1712
1713 bool SimpleRegisterCoalescing::runOnMachineFunction(MachineFunction &fn) {
1714   mf_ = &fn;
1715   mri_ = &fn.getRegInfo();
1716   tm_ = &fn.getTarget();
1717   tri_ = tm_->getRegisterInfo();
1718   tii_ = tm_->getInstrInfo();
1719   li_ = &getAnalysis<LiveIntervals>();
1720   AA = &getAnalysis<AliasAnalysis>();
1721   loopInfo = &getAnalysis<MachineLoopInfo>();
1722
1723   DEBUG(dbgs() << "********** SIMPLE REGISTER COALESCING **********\n"
1724                << "********** Function: "
1725                << ((Value*)mf_->getFunction())->getName() << '\n');
1726
1727   allocatableRegs_ = tri_->getAllocatableSet(fn);
1728   for (TargetRegisterInfo::regclass_iterator I = tri_->regclass_begin(),
1729          E = tri_->regclass_end(); I != E; ++I)
1730     allocatableRCRegs_.insert(std::make_pair(*I,
1731                                              tri_->getAllocatableSet(fn, *I)));
1732
1733   // Join (coalesce) intervals if requested.
1734   if (EnableJoining) {
1735     joinIntervals();
1736     DEBUG({
1737         dbgs() << "********** INTERVALS POST JOINING **********\n";
1738         for (LiveIntervals::iterator I = li_->begin(), E = li_->end();
1739              I != E; ++I){
1740           I->second->print(dbgs(), tri_);
1741           dbgs() << "\n";
1742         }
1743       });
1744   }
1745
1746   // Perform a final pass over the instructions and compute spill weights
1747   // and remove identity moves.
1748   SmallVector<unsigned, 4> DeadDefs;
1749   for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
1750        mbbi != mbbe; ++mbbi) {
1751     MachineBasicBlock* mbb = mbbi;
1752     for (MachineBasicBlock::iterator mii = mbb->begin(), mie = mbb->end();
1753          mii != mie; ) {
1754       MachineInstr *MI = mii;
1755       unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
1756       if (JoinedCopies.count(MI)) {
1757         // Delete all coalesced copies.
1758         bool DoDelete = true;
1759         if (!tii_->isMoveInstr(*MI, SrcReg, DstReg, SrcSubIdx, DstSubIdx)) {
1760           assert(MI->isCopyLike() && "Unrecognized copy instruction");
1761           SrcReg = MI->getOperand(MI->isSubregToReg() ? 2 : 1).getReg();
1762           if (TargetRegisterInfo::isPhysicalRegister(SrcReg))
1763             // Do not delete extract_subreg, insert_subreg of physical
1764             // registers unless the definition is dead. e.g.
1765             // %DO<def> = INSERT_SUBREG %D0<undef>, %S0<kill>, 1
1766             // or else the scavenger may complain. LowerSubregs will
1767             // delete them later.
1768             DoDelete = false;
1769         }
1770         if (MI->allDefsAreDead()) {
1771           LiveInterval &li = li_->getInterval(SrcReg);
1772           if (!ShortenDeadCopySrcLiveRange(li, MI))
1773             ShortenDeadCopyLiveRange(li, MI);
1774           DoDelete = true;
1775         }
1776         if (!DoDelete)
1777           mii = llvm::next(mii);
1778         else {
1779           li_->RemoveMachineInstrFromMaps(MI);
1780           mii = mbbi->erase(mii);
1781           ++numPeep;
1782         }
1783         continue;
1784       }
1785
1786       // Now check if this is a remat'ed def instruction which is now dead.
1787       if (ReMatDefs.count(MI)) {
1788         bool isDead = true;
1789         for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1790           const MachineOperand &MO = MI->getOperand(i);
1791           if (!MO.isReg())
1792             continue;
1793           unsigned Reg = MO.getReg();
1794           if (!Reg)
1795             continue;
1796           if (TargetRegisterInfo::isVirtualRegister(Reg))
1797             DeadDefs.push_back(Reg);
1798           if (MO.isDead())
1799             continue;
1800           if (TargetRegisterInfo::isPhysicalRegister(Reg) ||
1801               !mri_->use_nodbg_empty(Reg)) {
1802             isDead = false;
1803             break;
1804           }
1805         }
1806         if (isDead) {
1807           while (!DeadDefs.empty()) {
1808             unsigned DeadDef = DeadDefs.back();
1809             DeadDefs.pop_back();
1810             RemoveDeadDef(li_->getInterval(DeadDef), MI);
1811           }
1812           li_->RemoveMachineInstrFromMaps(mii);
1813           mii = mbbi->erase(mii);
1814           continue;
1815         } else
1816           DeadDefs.clear();
1817       }
1818
1819       // If the move will be an identity move delete it
1820       bool isMove= tii_->isMoveInstr(*MI, SrcReg, DstReg, SrcSubIdx, DstSubIdx);
1821       if (isMove && SrcReg == DstReg && SrcSubIdx == DstSubIdx) {
1822         if (li_->hasInterval(SrcReg)) {
1823           LiveInterval &RegInt = li_->getInterval(SrcReg);
1824           // If def of this move instruction is dead, remove its live range
1825           // from the destination register's live interval.
1826           if (MI->allDefsAreDead()) {
1827             if (!ShortenDeadCopySrcLiveRange(RegInt, MI))
1828               ShortenDeadCopyLiveRange(RegInt, MI);
1829           }
1830         }
1831         li_->RemoveMachineInstrFromMaps(MI);
1832         mii = mbbi->erase(mii);
1833         ++numPeep;
1834         continue;
1835       }
1836
1837       ++mii;
1838
1839       // Check for now unnecessary kill flags.
1840       if (li_->isNotInMIMap(MI)) continue;
1841       SlotIndex DefIdx = li_->getInstructionIndex(MI).getDefIndex();
1842       for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1843         MachineOperand &MO = MI->getOperand(i);
1844         if (!MO.isReg() || !MO.isKill()) continue;
1845         unsigned reg = MO.getReg();
1846         if (!reg || !li_->hasInterval(reg)) continue;
1847         if (!li_->getInterval(reg).killedAt(DefIdx))
1848           MO.setIsKill(false);
1849       }
1850     }
1851   }
1852
1853   DEBUG(dump());
1854   return true;
1855 }
1856
1857 /// print - Implement the dump method.
1858 void SimpleRegisterCoalescing::print(raw_ostream &O, const Module* m) const {
1859    li_->print(O, m);
1860 }
1861
1862 RegisterCoalescer* llvm::createSimpleRegisterCoalescer() {
1863   return new SimpleRegisterCoalescing();
1864 }
1865
1866 // Make sure that anything that uses RegisterCoalescer pulls in this file...
1867 DEFINING_FILE_FOR(SimpleRegisterCoalescing)