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