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