Replace TargetRegisterInfo::printReg with a PrintReg class that also works without...
[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 " << PrintReg(CP.getSrcReg(), tri_));
989
990   // Enforce policies.
991   if (CP.isPhys()) {
992     DEBUG(dbgs() <<" with physreg " << PrintReg(CP.getDstReg(), tri_) << "\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(dbgs() << " with " << PrintReg(CP.getDstReg(), tri_, CP.getSubIdx())
1000                  << " to " << CP.getNewRC()->getName() << "\n");
1001
1002     // Avoid constraining virtual register regclass too much.
1003     if (CP.isCrossClass()) {
1004       if (DisableCrossClassJoin) {
1005         DEBUG(dbgs() << "\tCross-class joins disabled.\n");
1006         return false;
1007       }
1008       if (!isWinToJoinCrossClass(CP.getSrcReg(), CP.getDstReg(),
1009                                  mri_->getRegClass(CP.getSrcReg()),
1010                                  mri_->getRegClass(CP.getDstReg()),
1011                                  CP.getNewRC())) {
1012         DEBUG(dbgs() << "\tAvoid coalescing to constrained register class: "
1013                      << CP.getNewRC()->getName() << ".\n");
1014         Again = true;  // May be possible to coalesce later.
1015         return false;
1016       }
1017     }
1018
1019     // When possible, let DstReg be the larger interval.
1020     if (!CP.getSubIdx() && li_->getInterval(CP.getSrcReg()).ranges.size() >
1021                            li_->getInterval(CP.getDstReg()).ranges.size())
1022       CP.flip();
1023   }
1024
1025   // We need to be careful about coalescing a source physical register with a
1026   // virtual register. Once the coalescing is done, it cannot be broken and
1027   // these are not spillable! If the destination interval uses are far away,
1028   // think twice about coalescing them!
1029   // FIXME: Why are we skipping this test for partial copies?
1030   //        CodeGen/X86/phys_subreg_coalesce-3.ll needs it.
1031   if (!CP.isPartial() && CP.isPhys()) {
1032     LiveInterval &JoinVInt = li_->getInterval(CP.getSrcReg());
1033
1034     // Don't join with physregs that have a ridiculous number of live
1035     // ranges. The data structure performance is really bad when that
1036     // happens.
1037     if (li_->hasInterval(CP.getDstReg()) &&
1038         li_->getInterval(CP.getDstReg()).ranges.size() > 1000) {
1039       ++numAborts;
1040       DEBUG(dbgs()
1041            << "\tPhysical register live interval too complicated, abort!\n");
1042       return false;
1043     }
1044
1045     const TargetRegisterClass *RC = mri_->getRegClass(CP.getSrcReg());
1046     unsigned Threshold = allocatableRCRegs_[RC].count() * 2;
1047     unsigned Length = li_->getApproximateInstructionCount(JoinVInt);
1048     if (Length > Threshold &&
1049         std::distance(mri_->use_nodbg_begin(CP.getSrcReg()),
1050                       mri_->use_nodbg_end()) * Threshold < Length) {
1051       // Before giving up coalescing, if definition of source is defined by
1052       // trivial computation, try rematerializing it.
1053       if (!CP.isFlipped() &&
1054           ReMaterializeTrivialDef(JoinVInt, CP.getDstReg(), 0, CopyMI))
1055         return true;
1056
1057       ++numAborts;
1058       DEBUG(dbgs() << "\tMay tie down a physical register, abort!\n");
1059       Again = true;  // May be possible to coalesce later.
1060       return false;
1061     }
1062   }
1063
1064   // Okay, attempt to join these two intervals.  On failure, this returns false.
1065   // Otherwise, if one of the intervals being joined is a physreg, this method
1066   // always canonicalizes DstInt to be it.  The output "SrcInt" will not have
1067   // been modified, so we can use this information below to update aliases.
1068   if (!JoinIntervals(CP)) {
1069     // Coalescing failed.
1070
1071     // If definition of source is defined by trivial computation, try
1072     // rematerializing it.
1073     if (!CP.isFlipped() &&
1074         ReMaterializeTrivialDef(li_->getInterval(CP.getSrcReg()),
1075                                 CP.getDstReg(), 0, CopyMI))
1076       return true;
1077
1078     // If we can eliminate the copy without merging the live ranges, do so now.
1079     if (!CP.isPartial()) {
1080       if (AdjustCopiesBackFrom(CP, CopyMI) ||
1081           RemoveCopyByCommutingDef(CP, CopyMI)) {
1082         JoinedCopies.insert(CopyMI);
1083         DEBUG(dbgs() << "\tTrivial!\n");
1084         return true;
1085       }
1086     }
1087
1088     // Otherwise, we are unable to join the intervals.
1089     DEBUG(dbgs() << "\tInterference!\n");
1090     Again = true;  // May be possible to coalesce later.
1091     return false;
1092   }
1093
1094   // Coalescing to a virtual register that is of a sub-register class of the
1095   // other. Make sure the resulting register is set to the right register class.
1096   if (CP.isCrossClass()) {
1097     ++numCrossRCs;
1098     mri_->setRegClass(CP.getDstReg(), CP.getNewRC());
1099   }
1100
1101   // Remember to delete the copy instruction.
1102   JoinedCopies.insert(CopyMI);
1103
1104   UpdateRegDefsUses(CP);
1105
1106   // If we have extended the live range of a physical register, make sure we
1107   // update live-in lists as well.
1108   if (CP.isPhys()) {
1109     SmallVector<MachineBasicBlock*, 16> BlockSeq;
1110     // JoinIntervals invalidates the VNInfos in SrcInt, but we only need the
1111     // ranges for this, and they are preserved.
1112     LiveInterval &SrcInt = li_->getInterval(CP.getSrcReg());
1113     for (LiveInterval::const_iterator I = SrcInt.begin(), E = SrcInt.end();
1114          I != E; ++I ) {
1115       li_->findLiveInMBBs(I->start, I->end, BlockSeq);
1116       for (unsigned idx = 0, size = BlockSeq.size(); idx != size; ++idx) {
1117         MachineBasicBlock &block = *BlockSeq[idx];
1118         if (!block.isLiveIn(CP.getDstReg()))
1119           block.addLiveIn(CP.getDstReg());
1120       }
1121       BlockSeq.clear();
1122     }
1123   }
1124
1125   // SrcReg is guarateed to be the register whose live interval that is
1126   // being merged.
1127   li_->removeInterval(CP.getSrcReg());
1128
1129   // Update regalloc hint.
1130   tri_->UpdateRegAllocHint(CP.getSrcReg(), CP.getDstReg(), *mf_);
1131
1132   DEBUG({
1133     LiveInterval &DstInt = li_->getInterval(CP.getDstReg());
1134     dbgs() << "\tJoined. Result = ";
1135     DstInt.print(dbgs(), tri_);
1136     dbgs() << "\n";
1137   });
1138
1139   ++numJoins;
1140   return true;
1141 }
1142
1143 /// ComputeUltimateVN - Assuming we are going to join two live intervals,
1144 /// compute what the resultant value numbers for each value in the input two
1145 /// ranges will be.  This is complicated by copies between the two which can
1146 /// and will commonly cause multiple value numbers to be merged into one.
1147 ///
1148 /// VN is the value number that we're trying to resolve.  InstDefiningValue
1149 /// keeps track of the new InstDefiningValue assignment for the result
1150 /// LiveInterval.  ThisFromOther/OtherFromThis are sets that keep track of
1151 /// whether a value in this or other is a copy from the opposite set.
1152 /// ThisValNoAssignments/OtherValNoAssignments keep track of value #'s that have
1153 /// already been assigned.
1154 ///
1155 /// ThisFromOther[x] - If x is defined as a copy from the other interval, this
1156 /// contains the value number the copy is from.
1157 ///
1158 static unsigned ComputeUltimateVN(VNInfo *VNI,
1159                                   SmallVector<VNInfo*, 16> &NewVNInfo,
1160                                   DenseMap<VNInfo*, VNInfo*> &ThisFromOther,
1161                                   DenseMap<VNInfo*, VNInfo*> &OtherFromThis,
1162                                   SmallVector<int, 16> &ThisValNoAssignments,
1163                                   SmallVector<int, 16> &OtherValNoAssignments) {
1164   unsigned VN = VNI->id;
1165
1166   // If the VN has already been computed, just return it.
1167   if (ThisValNoAssignments[VN] >= 0)
1168     return ThisValNoAssignments[VN];
1169   assert(ThisValNoAssignments[VN] != -2 && "Cyclic value numbers");
1170
1171   // If this val is not a copy from the other val, then it must be a new value
1172   // number in the destination.
1173   DenseMap<VNInfo*, VNInfo*>::iterator I = ThisFromOther.find(VNI);
1174   if (I == ThisFromOther.end()) {
1175     NewVNInfo.push_back(VNI);
1176     return ThisValNoAssignments[VN] = NewVNInfo.size()-1;
1177   }
1178   VNInfo *OtherValNo = I->second;
1179
1180   // Otherwise, this *is* a copy from the RHS.  If the other side has already
1181   // been computed, return it.
1182   if (OtherValNoAssignments[OtherValNo->id] >= 0)
1183     return ThisValNoAssignments[VN] = OtherValNoAssignments[OtherValNo->id];
1184
1185   // Mark this value number as currently being computed, then ask what the
1186   // ultimate value # of the other value is.
1187   ThisValNoAssignments[VN] = -2;
1188   unsigned UltimateVN =
1189     ComputeUltimateVN(OtherValNo, NewVNInfo, OtherFromThis, ThisFromOther,
1190                       OtherValNoAssignments, ThisValNoAssignments);
1191   return ThisValNoAssignments[VN] = UltimateVN;
1192 }
1193
1194 /// JoinIntervals - Attempt to join these two intervals.  On failure, this
1195 /// returns false.
1196 bool SimpleRegisterCoalescing::JoinIntervals(CoalescerPair &CP) {
1197   LiveInterval &RHS = li_->getInterval(CP.getSrcReg());
1198   DEBUG({ dbgs() << "\t\tRHS = "; RHS.print(dbgs(), tri_); dbgs() << "\n"; });
1199
1200   // If a live interval is a physical register, check for interference with any
1201   // aliases. The interference check implemented here is a bit more conservative
1202   // than the full interfeence check below. We allow overlapping live ranges
1203   // only when one is a copy of the other.
1204   if (CP.isPhys()) {
1205     for (const unsigned *AS = tri_->getAliasSet(CP.getDstReg()); *AS; ++AS){
1206       if (!li_->hasInterval(*AS))
1207         continue;
1208       const LiveInterval &LHS = li_->getInterval(*AS);
1209       LiveInterval::const_iterator LI = LHS.begin();
1210       for (LiveInterval::const_iterator RI = RHS.begin(), RE = RHS.end();
1211            RI != RE; ++RI) {
1212         LI = std::lower_bound(LI, LHS.end(), RI->start);
1213         // Does LHS have an overlapping live range starting before RI?
1214         if ((LI != LHS.begin() && LI[-1].end > RI->start) &&
1215             (RI->start != RI->valno->def ||
1216              !CP.isCoalescable(li_->getInstructionFromIndex(RI->start)))) {
1217           DEBUG({
1218             dbgs() << "\t\tInterference from alias: ";
1219             LHS.print(dbgs(), tri_);
1220             dbgs() << "\n\t\tOverlap at " << RI->start << " and no copy.\n";
1221           });
1222           return false;
1223         }
1224
1225         // Check that LHS ranges beginning in this range are copies.
1226         for (; LI != LHS.end() && LI->start < RI->end; ++LI) {
1227           if (LI->start != LI->valno->def ||
1228               !CP.isCoalescable(li_->getInstructionFromIndex(LI->start))) {
1229             DEBUG({
1230               dbgs() << "\t\tInterference from alias: ";
1231               LHS.print(dbgs(), tri_);
1232               dbgs() << "\n\t\tDef at " << LI->start << " is not a copy.\n";
1233             });
1234             return false;
1235           }
1236         }
1237       }
1238     }
1239   }
1240
1241   // Compute the final value assignment, assuming that the live ranges can be
1242   // coalesced.
1243   SmallVector<int, 16> LHSValNoAssignments;
1244   SmallVector<int, 16> RHSValNoAssignments;
1245   DenseMap<VNInfo*, VNInfo*> LHSValsDefinedFromRHS;
1246   DenseMap<VNInfo*, VNInfo*> RHSValsDefinedFromLHS;
1247   SmallVector<VNInfo*, 16> NewVNInfo;
1248
1249   LiveInterval &LHS = li_->getOrCreateInterval(CP.getDstReg());
1250   DEBUG({ dbgs() << "\t\tLHS = "; LHS.print(dbgs(), tri_); dbgs() << "\n"; });
1251
1252   // Loop over the value numbers of the LHS, seeing if any are defined from
1253   // the RHS.
1254   for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1255        i != e; ++i) {
1256     VNInfo *VNI = *i;
1257     if (VNI->isUnused() || !VNI->isDefByCopy())  // Src not defined by a copy?
1258       continue;
1259
1260     // Never join with a register that has EarlyClobber redefs.
1261     if (VNI->hasRedefByEC())
1262       return false;
1263
1264     // DstReg is known to be a register in the LHS interval.  If the src is
1265     // from the RHS interval, we can use its value #.
1266     if (!CP.isCoalescable(VNI->getCopy()))
1267       continue;
1268
1269     // Figure out the value # from the RHS.
1270     LiveRange *lr = RHS.getLiveRangeContaining(VNI->def.getPrevSlot());
1271     // The copy could be to an aliased physreg.
1272     if (!lr) continue;
1273     LHSValsDefinedFromRHS[VNI] = lr->valno;
1274   }
1275
1276   // Loop over the value numbers of the RHS, seeing if any are defined from
1277   // the LHS.
1278   for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
1279        i != e; ++i) {
1280     VNInfo *VNI = *i;
1281     if (VNI->isUnused() || !VNI->isDefByCopy())  // Src not defined by a copy?
1282       continue;
1283
1284     // Never join with a register that has EarlyClobber redefs.
1285     if (VNI->hasRedefByEC())
1286       return false;
1287
1288     // DstReg is known to be a register in the RHS interval.  If the src is
1289     // from the LHS interval, we can use its value #.
1290     if (!CP.isCoalescable(VNI->getCopy()))
1291       continue;
1292
1293     // Figure out the value # from the LHS.
1294     LiveRange *lr = LHS.getLiveRangeContaining(VNI->def.getPrevSlot());
1295     // The copy could be to an aliased physreg.
1296     if (!lr) continue;
1297     RHSValsDefinedFromLHS[VNI] = lr->valno;
1298   }
1299
1300   LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
1301   RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
1302   NewVNInfo.reserve(LHS.getNumValNums() + RHS.getNumValNums());
1303
1304   for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1305        i != e; ++i) {
1306     VNInfo *VNI = *i;
1307     unsigned VN = VNI->id;
1308     if (LHSValNoAssignments[VN] >= 0 || VNI->isUnused())
1309       continue;
1310     ComputeUltimateVN(VNI, NewVNInfo,
1311                       LHSValsDefinedFromRHS, RHSValsDefinedFromLHS,
1312                       LHSValNoAssignments, RHSValNoAssignments);
1313   }
1314   for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
1315        i != e; ++i) {
1316     VNInfo *VNI = *i;
1317     unsigned VN = VNI->id;
1318     if (RHSValNoAssignments[VN] >= 0 || VNI->isUnused())
1319       continue;
1320     // If this value number isn't a copy from the LHS, it's a new number.
1321     if (RHSValsDefinedFromLHS.find(VNI) == RHSValsDefinedFromLHS.end()) {
1322       NewVNInfo.push_back(VNI);
1323       RHSValNoAssignments[VN] = NewVNInfo.size()-1;
1324       continue;
1325     }
1326
1327     ComputeUltimateVN(VNI, NewVNInfo,
1328                       RHSValsDefinedFromLHS, LHSValsDefinedFromRHS,
1329                       RHSValNoAssignments, LHSValNoAssignments);
1330   }
1331
1332   // Armed with the mappings of LHS/RHS values to ultimate values, walk the
1333   // interval lists to see if these intervals are coalescable.
1334   LiveInterval::const_iterator I = LHS.begin();
1335   LiveInterval::const_iterator IE = LHS.end();
1336   LiveInterval::const_iterator J = RHS.begin();
1337   LiveInterval::const_iterator JE = RHS.end();
1338
1339   // Skip ahead until the first place of potential sharing.
1340   if (I != IE && J != JE) {
1341     if (I->start < J->start) {
1342       I = std::upper_bound(I, IE, J->start);
1343       if (I != LHS.begin()) --I;
1344     } else if (J->start < I->start) {
1345       J = std::upper_bound(J, JE, I->start);
1346       if (J != RHS.begin()) --J;
1347     }
1348   }
1349
1350   while (I != IE && J != JE) {
1351     // Determine if these two live ranges overlap.
1352     bool Overlaps;
1353     if (I->start < J->start) {
1354       Overlaps = I->end > J->start;
1355     } else {
1356       Overlaps = J->end > I->start;
1357     }
1358
1359     // If so, check value # info to determine if they are really different.
1360     if (Overlaps) {
1361       // If the live range overlap will map to the same value number in the
1362       // result liverange, we can still coalesce them.  If not, we can't.
1363       if (LHSValNoAssignments[I->valno->id] !=
1364           RHSValNoAssignments[J->valno->id])
1365         return false;
1366       // If it's re-defined by an early clobber somewhere in the live range,
1367       // then conservatively abort coalescing.
1368       if (NewVNInfo[LHSValNoAssignments[I->valno->id]]->hasRedefByEC())
1369         return false;
1370     }
1371
1372     if (I->end < J->end)
1373       ++I;
1374     else
1375       ++J;
1376   }
1377
1378   // Update kill info. Some live ranges are extended due to copy coalescing.
1379   for (DenseMap<VNInfo*, VNInfo*>::iterator I = LHSValsDefinedFromRHS.begin(),
1380          E = LHSValsDefinedFromRHS.end(); I != E; ++I) {
1381     VNInfo *VNI = I->first;
1382     unsigned LHSValID = LHSValNoAssignments[VNI->id];
1383     if (VNI->hasPHIKill())
1384       NewVNInfo[LHSValID]->setHasPHIKill(true);
1385   }
1386
1387   // Update kill info. Some live ranges are extended due to copy coalescing.
1388   for (DenseMap<VNInfo*, VNInfo*>::iterator I = RHSValsDefinedFromLHS.begin(),
1389          E = RHSValsDefinedFromLHS.end(); I != E; ++I) {
1390     VNInfo *VNI = I->first;
1391     unsigned RHSValID = RHSValNoAssignments[VNI->id];
1392     if (VNI->hasPHIKill())
1393       NewVNInfo[RHSValID]->setHasPHIKill(true);
1394   }
1395
1396   if (LHSValNoAssignments.empty())
1397     LHSValNoAssignments.push_back(-1);
1398   if (RHSValNoAssignments.empty())
1399     RHSValNoAssignments.push_back(-1);
1400
1401   // If we get here, we know that we can coalesce the live ranges.  Ask the
1402   // intervals to coalesce themselves now.
1403   LHS.join(RHS, &LHSValNoAssignments[0], &RHSValNoAssignments[0], NewVNInfo,
1404            mri_);
1405   return true;
1406 }
1407
1408 namespace {
1409   // DepthMBBCompare - Comparison predicate that sort first based on the loop
1410   // depth of the basic block (the unsigned), and then on the MBB number.
1411   struct DepthMBBCompare {
1412     typedef std::pair<unsigned, MachineBasicBlock*> DepthMBBPair;
1413     bool operator()(const DepthMBBPair &LHS, const DepthMBBPair &RHS) const {
1414       // Deeper loops first
1415       if (LHS.first != RHS.first)
1416         return LHS.first > RHS.first;
1417
1418       // Prefer blocks that are more connected in the CFG. This takes care of
1419       // the most difficult copies first while intervals are short.
1420       unsigned cl = LHS.second->pred_size() + LHS.second->succ_size();
1421       unsigned cr = RHS.second->pred_size() + RHS.second->succ_size();
1422       if (cl != cr)
1423         return cl > cr;
1424
1425       // As a last resort, sort by block number.
1426       return LHS.second->getNumber() < RHS.second->getNumber();
1427     }
1428   };
1429 }
1430
1431 void SimpleRegisterCoalescing::CopyCoalesceInMBB(MachineBasicBlock *MBB,
1432                                                std::vector<CopyRec> &TryAgain) {
1433   DEBUG(dbgs() << MBB->getName() << ":\n");
1434
1435   std::vector<CopyRec> VirtCopies;
1436   std::vector<CopyRec> PhysCopies;
1437   std::vector<CopyRec> ImpDefCopies;
1438   for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end();
1439        MII != E;) {
1440     MachineInstr *Inst = MII++;
1441
1442     // If this isn't a copy nor a extract_subreg, we can't join intervals.
1443     unsigned SrcReg, DstReg;
1444     if (Inst->isCopy()) {
1445       DstReg = Inst->getOperand(0).getReg();
1446       SrcReg = Inst->getOperand(1).getReg();
1447     } else if (Inst->isSubregToReg()) {
1448       DstReg = Inst->getOperand(0).getReg();
1449       SrcReg = Inst->getOperand(2).getReg();
1450     } else
1451       continue;
1452
1453     bool SrcIsPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
1454     bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
1455     if (li_->hasInterval(SrcReg) && li_->getInterval(SrcReg).empty())
1456       ImpDefCopies.push_back(CopyRec(Inst, 0));
1457     else if (SrcIsPhys || DstIsPhys)
1458       PhysCopies.push_back(CopyRec(Inst, 0));
1459     else
1460       VirtCopies.push_back(CopyRec(Inst, 0));
1461   }
1462
1463   // Try coalescing implicit copies and insert_subreg <undef> first,
1464   // followed by copies to / from physical registers, then finally copies
1465   // from virtual registers to virtual registers.
1466   for (unsigned i = 0, e = ImpDefCopies.size(); i != e; ++i) {
1467     CopyRec &TheCopy = ImpDefCopies[i];
1468     bool Again = false;
1469     if (!JoinCopy(TheCopy, Again))
1470       if (Again)
1471         TryAgain.push_back(TheCopy);
1472   }
1473   for (unsigned i = 0, e = PhysCopies.size(); i != e; ++i) {
1474     CopyRec &TheCopy = PhysCopies[i];
1475     bool Again = false;
1476     if (!JoinCopy(TheCopy, Again))
1477       if (Again)
1478         TryAgain.push_back(TheCopy);
1479   }
1480   for (unsigned i = 0, e = VirtCopies.size(); i != e; ++i) {
1481     CopyRec &TheCopy = VirtCopies[i];
1482     bool Again = false;
1483     if (!JoinCopy(TheCopy, Again))
1484       if (Again)
1485         TryAgain.push_back(TheCopy);
1486   }
1487 }
1488
1489 void SimpleRegisterCoalescing::joinIntervals() {
1490   DEBUG(dbgs() << "********** JOINING INTERVALS ***********\n");
1491
1492   std::vector<CopyRec> TryAgainList;
1493   if (loopInfo->empty()) {
1494     // If there are no loops in the function, join intervals in function order.
1495     for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();
1496          I != E; ++I)
1497       CopyCoalesceInMBB(I, TryAgainList);
1498   } else {
1499     // Otherwise, join intervals in inner loops before other intervals.
1500     // Unfortunately we can't just iterate over loop hierarchy here because
1501     // there may be more MBB's than BB's.  Collect MBB's for sorting.
1502
1503     // Join intervals in the function prolog first. We want to join physical
1504     // registers with virtual registers before the intervals got too long.
1505     std::vector<std::pair<unsigned, MachineBasicBlock*> > MBBs;
1506     for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();I != E;++I){
1507       MachineBasicBlock *MBB = I;
1508       MBBs.push_back(std::make_pair(loopInfo->getLoopDepth(MBB), I));
1509     }
1510
1511     // Sort by loop depth.
1512     std::sort(MBBs.begin(), MBBs.end(), DepthMBBCompare());
1513
1514     // Finally, join intervals in loop nest order.
1515     for (unsigned i = 0, e = MBBs.size(); i != e; ++i)
1516       CopyCoalesceInMBB(MBBs[i].second, TryAgainList);
1517   }
1518
1519   // Joining intervals can allow other intervals to be joined.  Iteratively join
1520   // until we make no progress.
1521   bool ProgressMade = true;
1522   while (ProgressMade) {
1523     ProgressMade = false;
1524
1525     for (unsigned i = 0, e = TryAgainList.size(); i != e; ++i) {
1526       CopyRec &TheCopy = TryAgainList[i];
1527       if (!TheCopy.MI)
1528         continue;
1529
1530       bool Again = false;
1531       bool Success = JoinCopy(TheCopy, Again);
1532       if (Success || !Again) {
1533         TheCopy.MI = 0;   // Mark this one as done.
1534         ProgressMade = true;
1535       }
1536     }
1537   }
1538 }
1539
1540 /// Return true if the two specified registers belong to different register
1541 /// classes.  The registers may be either phys or virt regs.
1542 bool
1543 SimpleRegisterCoalescing::differingRegisterClasses(unsigned RegA,
1544                                                    unsigned RegB) const {
1545   // Get the register classes for the first reg.
1546   if (TargetRegisterInfo::isPhysicalRegister(RegA)) {
1547     assert(TargetRegisterInfo::isVirtualRegister(RegB) &&
1548            "Shouldn't consider two physregs!");
1549     return !mri_->getRegClass(RegB)->contains(RegA);
1550   }
1551
1552   // Compare against the regclass for the second reg.
1553   const TargetRegisterClass *RegClassA = mri_->getRegClass(RegA);
1554   if (TargetRegisterInfo::isVirtualRegister(RegB)) {
1555     const TargetRegisterClass *RegClassB = mri_->getRegClass(RegB);
1556     return RegClassA != RegClassB;
1557   }
1558   return !RegClassA->contains(RegB);
1559 }
1560
1561 /// lastRegisterUse - Returns the last (non-debug) use of the specific register
1562 /// between cycles Start and End or NULL if there are no uses.
1563 MachineOperand *
1564 SimpleRegisterCoalescing::lastRegisterUse(SlotIndex Start,
1565                                           SlotIndex End,
1566                                           unsigned Reg,
1567                                           SlotIndex &UseIdx) const{
1568   UseIdx = SlotIndex();
1569   if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1570     MachineOperand *LastUse = NULL;
1571     for (MachineRegisterInfo::use_nodbg_iterator I = mri_->use_nodbg_begin(Reg),
1572            E = mri_->use_nodbg_end(); I != E; ++I) {
1573       MachineOperand &Use = I.getOperand();
1574       MachineInstr *UseMI = Use.getParent();
1575       if (UseMI->isIdentityCopy())
1576         continue;
1577       SlotIndex Idx = li_->getInstructionIndex(UseMI);
1578       // FIXME: Should this be Idx != UseIdx? SlotIndex() will return something
1579       // that compares higher than any other interval.
1580       if (Idx >= Start && Idx < End && Idx >= UseIdx) {
1581         LastUse = &Use;
1582         UseIdx = Idx.getUseIndex();
1583       }
1584     }
1585     return LastUse;
1586   }
1587
1588   SlotIndex s = Start;
1589   SlotIndex e = End.getPrevSlot().getBaseIndex();
1590   while (e >= s) {
1591     // Skip deleted instructions
1592     MachineInstr *MI = li_->getInstructionFromIndex(e);
1593     while (e != SlotIndex() && e.getPrevIndex() >= s && !MI) {
1594       e = e.getPrevIndex();
1595       MI = li_->getInstructionFromIndex(e);
1596     }
1597     if (e < s || MI == NULL)
1598       return NULL;
1599
1600     // Ignore identity copies.
1601     if (!MI->isIdentityCopy())
1602       for (unsigned i = 0, NumOps = MI->getNumOperands(); i != NumOps; ++i) {
1603         MachineOperand &Use = MI->getOperand(i);
1604         if (Use.isReg() && Use.isUse() && Use.getReg() &&
1605             tri_->regsOverlap(Use.getReg(), Reg)) {
1606           UseIdx = e.getUseIndex();
1607           return &Use;
1608         }
1609       }
1610
1611     e = e.getPrevIndex();
1612   }
1613
1614   return NULL;
1615 }
1616
1617 void SimpleRegisterCoalescing::releaseMemory() {
1618   JoinedCopies.clear();
1619   ReMatCopies.clear();
1620   ReMatDefs.clear();
1621 }
1622
1623 bool SimpleRegisterCoalescing::runOnMachineFunction(MachineFunction &fn) {
1624   mf_ = &fn;
1625   mri_ = &fn.getRegInfo();
1626   tm_ = &fn.getTarget();
1627   tri_ = tm_->getRegisterInfo();
1628   tii_ = tm_->getInstrInfo();
1629   li_ = &getAnalysis<LiveIntervals>();
1630   ldv_ = &getAnalysis<LiveDebugVariables>();
1631   AA = &getAnalysis<AliasAnalysis>();
1632   loopInfo = &getAnalysis<MachineLoopInfo>();
1633
1634   DEBUG(dbgs() << "********** SIMPLE REGISTER COALESCING **********\n"
1635                << "********** Function: "
1636                << ((Value*)mf_->getFunction())->getName() << '\n');
1637
1638   for (TargetRegisterInfo::regclass_iterator I = tri_->regclass_begin(),
1639          E = tri_->regclass_end(); I != E; ++I)
1640     allocatableRCRegs_.insert(std::make_pair(*I,
1641                                              tri_->getAllocatableSet(fn, *I)));
1642
1643   // Join (coalesce) intervals if requested.
1644   if (EnableJoining) {
1645     joinIntervals();
1646     DEBUG({
1647         dbgs() << "********** INTERVALS POST JOINING **********\n";
1648         for (LiveIntervals::iterator I = li_->begin(), E = li_->end();
1649              I != E; ++I){
1650           I->second->print(dbgs(), tri_);
1651           dbgs() << "\n";
1652         }
1653       });
1654   }
1655
1656   // Perform a final pass over the instructions and compute spill weights
1657   // and remove identity moves.
1658   SmallVector<unsigned, 4> DeadDefs;
1659   for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
1660        mbbi != mbbe; ++mbbi) {
1661     MachineBasicBlock* mbb = mbbi;
1662     for (MachineBasicBlock::iterator mii = mbb->begin(), mie = mbb->end();
1663          mii != mie; ) {
1664       MachineInstr *MI = mii;
1665       if (JoinedCopies.count(MI)) {
1666         // Delete all coalesced copies.
1667         bool DoDelete = true;
1668         assert(MI->isCopyLike() && "Unrecognized copy instruction");
1669         unsigned SrcReg = MI->getOperand(MI->isSubregToReg() ? 2 : 1).getReg();
1670         if (TargetRegisterInfo::isPhysicalRegister(SrcReg) &&
1671             MI->getNumOperands() > 2)
1672           // Do not delete extract_subreg, insert_subreg of physical
1673           // registers unless the definition is dead. e.g.
1674           // %DO<def> = INSERT_SUBREG %D0<undef>, %S0<kill>, 1
1675           // or else the scavenger may complain. LowerSubregs will
1676           // delete them later.
1677           DoDelete = false;
1678         
1679         if (MI->allDefsAreDead()) {
1680           LiveInterval &li = li_->getInterval(SrcReg);
1681           if (!ShortenDeadCopySrcLiveRange(li, MI))
1682             ShortenDeadCopyLiveRange(li, MI);
1683           DoDelete = true;
1684         }
1685         if (!DoDelete) {
1686           // We need the instruction to adjust liveness, so make it a KILL.
1687           if (MI->isSubregToReg()) {
1688             MI->RemoveOperand(3);
1689             MI->RemoveOperand(1);
1690           }
1691           MI->setDesc(tii_->get(TargetOpcode::KILL));
1692           mii = llvm::next(mii);
1693         } else {
1694           li_->RemoveMachineInstrFromMaps(MI);
1695           mii = mbbi->erase(mii);
1696           ++numPeep;
1697         }
1698         continue;
1699       }
1700
1701       // Now check if this is a remat'ed def instruction which is now dead.
1702       if (ReMatDefs.count(MI)) {
1703         bool isDead = true;
1704         for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1705           const MachineOperand &MO = MI->getOperand(i);
1706           if (!MO.isReg())
1707             continue;
1708           unsigned Reg = MO.getReg();
1709           if (!Reg)
1710             continue;
1711           if (TargetRegisterInfo::isVirtualRegister(Reg))
1712             DeadDefs.push_back(Reg);
1713           if (MO.isDead())
1714             continue;
1715           if (TargetRegisterInfo::isPhysicalRegister(Reg) ||
1716               !mri_->use_nodbg_empty(Reg)) {
1717             isDead = false;
1718             break;
1719           }
1720         }
1721         if (isDead) {
1722           while (!DeadDefs.empty()) {
1723             unsigned DeadDef = DeadDefs.back();
1724             DeadDefs.pop_back();
1725             RemoveDeadDef(li_->getInterval(DeadDef), MI);
1726           }
1727           li_->RemoveMachineInstrFromMaps(mii);
1728           mii = mbbi->erase(mii);
1729           continue;
1730         } else
1731           DeadDefs.clear();
1732       }
1733
1734       // If the move will be an identity move delete it
1735       if (MI->isIdentityCopy()) {
1736         unsigned SrcReg = MI->getOperand(1).getReg();
1737         if (li_->hasInterval(SrcReg)) {
1738           LiveInterval &RegInt = li_->getInterval(SrcReg);
1739           // If def of this move instruction is dead, remove its live range
1740           // from the destination register's live interval.
1741           if (MI->allDefsAreDead()) {
1742             if (!ShortenDeadCopySrcLiveRange(RegInt, MI))
1743               ShortenDeadCopyLiveRange(RegInt, MI);
1744           }
1745         }
1746         li_->RemoveMachineInstrFromMaps(MI);
1747         mii = mbbi->erase(mii);
1748         ++numPeep;
1749         continue;
1750       }
1751
1752       ++mii;
1753
1754       // Check for now unnecessary kill flags.
1755       if (li_->isNotInMIMap(MI)) continue;
1756       SlotIndex DefIdx = li_->getInstructionIndex(MI).getDefIndex();
1757       for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1758         MachineOperand &MO = MI->getOperand(i);
1759         if (!MO.isReg() || !MO.isKill()) continue;
1760         unsigned reg = MO.getReg();
1761         if (!reg || !li_->hasInterval(reg)) continue;
1762         if (!li_->getInterval(reg).killedAt(DefIdx)) {
1763           MO.setIsKill(false);
1764           continue;
1765         }
1766         // When leaving a kill flag on a physreg, check if any subregs should
1767         // remain alive.
1768         if (!TargetRegisterInfo::isPhysicalRegister(reg))
1769           continue;
1770         for (const unsigned *SR = tri_->getSubRegisters(reg);
1771              unsigned S = *SR; ++SR)
1772           if (li_->hasInterval(S) && li_->getInterval(S).liveAt(DefIdx))
1773             MI->addRegisterDefined(S, tri_);
1774       }
1775     }
1776   }
1777
1778   DEBUG(dump());
1779   DEBUG(ldv_->dump());
1780   return true;
1781 }
1782
1783 /// print - Implement the dump method.
1784 void SimpleRegisterCoalescing::print(raw_ostream &O, const Module* m) const {
1785    li_->print(O, m);
1786 }
1787
1788 RegisterCoalescer* llvm::createSimpleRegisterCoalescer() {
1789   return new SimpleRegisterCoalescing();
1790 }
1791
1792 // Make sure that anything that uses RegisterCoalescer pulls in this file...
1793 DEFINING_FILE_FOR(SimpleRegisterCoalescing)