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