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