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