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