75389a412a0f712dc931b388cd09a5ee0597baeb
[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/CodeGen/MachineFrameInfo.h"
21 #include "llvm/CodeGen/MachineInstr.h"
22 #include "llvm/CodeGen/MachineLoopInfo.h"
23 #include "llvm/CodeGen/MachineRegisterInfo.h"
24 #include "llvm/CodeGen/Passes.h"
25 #include "llvm/CodeGen/RegisterCoalescer.h"
26 #include "llvm/Target/TargetInstrInfo.h"
27 #include "llvm/Target/TargetMachine.h"
28 #include "llvm/Target/TargetOptions.h"
29 #include "llvm/Support/CommandLine.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/ADT/SmallSet.h"
32 #include "llvm/ADT/Statistic.h"
33 #include "llvm/ADT/STLExtras.h"
34 #include <algorithm>
35 #include <cmath>
36 using namespace llvm;
37
38 STATISTIC(numJoins    , "Number of interval joins performed");
39 STATISTIC(numCrossRCs , "Number of cross class joins performed");
40 STATISTIC(numCommutes , "Number of instruction commuting performed");
41 STATISTIC(numExtends  , "Number of copies extended");
42 STATISTIC(NumReMats   , "Number of instructions re-materialized");
43 STATISTIC(numPeep     , "Number of identity moves eliminated after coalescing");
44 STATISTIC(numAborts   , "Number of times interval joining aborted");
45 STATISTIC(numDeadValNo, "Number of valno def marked dead");
46
47 char SimpleRegisterCoalescing::ID = 0;
48 static cl::opt<bool>
49 EnableJoining("join-liveintervals",
50               cl::desc("Coalesce copies (default=true)"),
51               cl::init(true));
52
53 static cl::opt<bool>
54 NewHeuristic("new-coalescer-heuristic",
55              cl::desc("Use new coalescer heuristic"),
56              cl::init(false), cl::Hidden);
57
58 static cl::opt<bool>
59 CrossClassJoin("join-cross-class-copies",
60                cl::desc("Coalesce cross register class copies"),
61                cl::init(false), cl::Hidden);
62
63 static RegisterPass<SimpleRegisterCoalescing> 
64 X("simple-register-coalescing", "Simple Register Coalescing");
65
66 // Declare that we implement the RegisterCoalescer interface
67 static RegisterAnalysisGroup<RegisterCoalescer, true/*The Default*/> V(X);
68
69 const PassInfo *const llvm::SimpleRegisterCoalescingID = &X;
70
71 void SimpleRegisterCoalescing::getAnalysisUsage(AnalysisUsage &AU) const {
72   AU.addRequired<LiveIntervals>();
73   AU.addPreserved<LiveIntervals>();
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(LiveInterval &IntA,
101                                                     LiveInterval &IntB,
102                                                     MachineInstr *CopyMI) {
103   unsigned CopyIdx = li_->getDefIndex(li_->getInstructionIndex(CopyMI));
104
105   // BValNo is a value number in B that is defined by a copy from A.  'B3' in
106   // the example above.
107   LiveInterval::iterator BLR = IntB.FindLiveRangeContaining(CopyIdx);
108   assert(BLR != IntB.end() && "Live range not found!");
109   VNInfo *BValNo = BLR->valno;
110   
111   // Get the location that B is defined at.  Two options: either this value has
112   // an unknown definition point or it is defined at CopyIdx.  If unknown, we 
113   // can't process it.
114   if (!BValNo->copy) return false;
115   assert(BValNo->def == CopyIdx && "Copy doesn't define the value?");
116   
117   // AValNo is the value number in A that defines the copy, A3 in the example.
118   LiveInterval::iterator ALR = IntA.FindLiveRangeContaining(CopyIdx-1);
119   assert(ALR != IntA.end() && "Live range not found!");
120   VNInfo *AValNo = ALR->valno;
121   // If it's re-defined by an early clobber somewhere in the live range, then
122   // it's not safe to eliminate the copy. FIXME: This is a temporary workaround.
123   // See PR3149:
124   // 172     %ECX<def> = MOV32rr %reg1039<kill>
125   // 180     INLINEASM <es:subl $5,$1
126   //         sbbl $3,$0>, 10, %EAX<def>, 14, %ECX<earlyclobber,def>, 9, %EAX<kill>,
127   // 36, <fi#0>, 1, %reg0, 0, 9, %ECX<kill>, 36, <fi#1>, 1, %reg0, 0
128   // 188     %EAX<def> = MOV32rr %EAX<kill>
129   // 196     %ECX<def> = MOV32rr %ECX<kill>
130   // 204     %ECX<def> = MOV32rr %ECX<kill>
131   // 212     %EAX<def> = MOV32rr %EAX<kill>
132   // 220     %EAX<def> = MOV32rr %EAX
133   // 228     %reg1039<def> = MOV32rr %ECX<kill>
134   // The early clobber operand ties ECX input to the ECX def.
135   //
136   // The live interval of ECX is represented as this:
137   // %reg20,inf = [46,47:1)[174,230:0)  0@174-(230) 1@46-(47)
138   // The coalescer has no idea there was a def in the middle of [174,230].
139   if (AValNo->redefByEC)
140     return false;
141   
142   // If AValNo is defined as a copy from IntB, we can potentially process this.  
143   // Get the instruction that defines this value number.
144   unsigned SrcReg = li_->getVNInfoSourceReg(AValNo);
145   if (!SrcReg) return false;  // Not defined by a copy.
146     
147   // If the value number is not defined by a copy instruction, ignore it.
148
149   // If the source register comes from an interval other than IntB, we can't
150   // handle this.
151   if (SrcReg != IntB.reg) return false;
152   
153   // Get the LiveRange in IntB that this value number starts with.
154   LiveInterval::iterator ValLR = IntB.FindLiveRangeContaining(AValNo->def-1);
155   assert(ValLR != IntB.end() && "Live range not found!");
156   
157   // Make sure that the end of the live range is inside the same block as
158   // CopyMI.
159   MachineInstr *ValLREndInst = li_->getInstructionFromIndex(ValLR->end-1);
160   if (!ValLREndInst || 
161       ValLREndInst->getParent() != CopyMI->getParent()) return false;
162
163   // Okay, we now know that ValLR ends in the same block that the CopyMI
164   // live-range starts.  If there are no intervening live ranges between them in
165   // IntB, we can merge them.
166   if (ValLR+1 != BLR) return false;
167
168   // If a live interval is a physical register, conservatively check if any
169   // of its sub-registers is overlapping the live interval of the virtual
170   // register. If so, do not coalesce.
171   if (TargetRegisterInfo::isPhysicalRegister(IntB.reg) &&
172       *tri_->getSubRegisters(IntB.reg)) {
173     for (const unsigned* SR = tri_->getSubRegisters(IntB.reg); *SR; ++SR)
174       if (li_->hasInterval(*SR) && IntA.overlaps(li_->getInterval(*SR))) {
175         DOUT << "Interfere with sub-register ";
176         DEBUG(li_->getInterval(*SR).print(DOUT, tri_));
177         return false;
178       }
179   }
180   
181   DOUT << "\nExtending: "; IntB.print(DOUT, tri_);
182   
183   unsigned FillerStart = ValLR->end, FillerEnd = BLR->start;
184   // We are about to delete CopyMI, so need to remove it as the 'instruction
185   // that defines this value #'. Update the the valnum with the new defining
186   // instruction #.
187   BValNo->def  = FillerStart;
188   BValNo->copy = NULL;
189   
190   // Okay, we can merge them.  We need to insert a new liverange:
191   // [ValLR.end, BLR.begin) of either value number, then we merge the
192   // two value numbers.
193   IntB.addRange(LiveRange(FillerStart, FillerEnd, BValNo));
194
195   // If the IntB live range is assigned to a physical register, and if that
196   // physreg has aliases, 
197   if (TargetRegisterInfo::isPhysicalRegister(IntB.reg)) {
198     // Update the liveintervals of sub-registers.
199     for (const unsigned *AS = tri_->getSubRegisters(IntB.reg); *AS; ++AS) {
200       LiveInterval &AliasLI = li_->getInterval(*AS);
201       AliasLI.addRange(LiveRange(FillerStart, FillerEnd,
202               AliasLI.getNextValue(FillerStart, 0, li_->getVNInfoAllocator())));
203     }
204   }
205
206   // Okay, merge "B1" into the same value number as "B0".
207   if (BValNo != ValLR->valno) {
208     IntB.addKills(ValLR->valno, BValNo->kills);
209     IntB.MergeValueNumberInto(BValNo, ValLR->valno);
210   }
211   DOUT << "   result = "; IntB.print(DOUT, tri_);
212   DOUT << "\n";
213
214   // If the source instruction was killing the source register before the
215   // merge, unset the isKill marker given the live range has been extended.
216   int UIdx = ValLREndInst->findRegisterUseOperandIdx(IntB.reg, true);
217   if (UIdx != -1) {
218     ValLREndInst->getOperand(UIdx).setIsKill(false);
219     IntB.removeKill(ValLR->valno, FillerStart);
220   }
221
222   ++numExtends;
223   return true;
224 }
225
226 /// HasOtherReachingDefs - Return true if there are definitions of IntB
227 /// other than BValNo val# that can reach uses of AValno val# of IntA.
228 bool SimpleRegisterCoalescing::HasOtherReachingDefs(LiveInterval &IntA,
229                                                     LiveInterval &IntB,
230                                                     VNInfo *AValNo,
231                                                     VNInfo *BValNo) {
232   for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
233        AI != AE; ++AI) {
234     if (AI->valno != AValNo) continue;
235     LiveInterval::Ranges::iterator BI =
236       std::upper_bound(IntB.ranges.begin(), IntB.ranges.end(), AI->start);
237     if (BI != IntB.ranges.begin())
238       --BI;
239     for (; BI != IntB.ranges.end() && AI->end >= BI->start; ++BI) {
240       if (BI->valno == BValNo)
241         continue;
242       if (BI->start <= AI->start && BI->end > AI->start)
243         return true;
244       if (BI->start > AI->start && BI->start < AI->end)
245         return true;
246     }
247   }
248   return false;
249 }
250
251 /// RemoveCopyByCommutingDef - We found a non-trivially-coalescable copy with IntA
252 /// being the source and IntB being the dest, thus this defines a value number
253 /// in IntB.  If the source value number (in IntA) is defined by a commutable
254 /// instruction and its other operand is coalesced to the copy dest register,
255 /// see if we can transform the copy into a noop by commuting the definition. For
256 /// example,
257 ///
258 ///  A3 = op A2 B0<kill>
259 ///    ...
260 ///  B1 = A3      <- this copy
261 ///    ...
262 ///     = op A3   <- more uses
263 ///
264 /// ==>
265 ///
266 ///  B2 = op B0 A2<kill>
267 ///    ...
268 ///  B1 = B2      <- now an identify copy
269 ///    ...
270 ///     = op B2   <- more uses
271 ///
272 /// This returns true if an interval was modified.
273 ///
274 bool SimpleRegisterCoalescing::RemoveCopyByCommutingDef(LiveInterval &IntA,
275                                                         LiveInterval &IntB,
276                                                         MachineInstr *CopyMI) {
277   unsigned CopyIdx = li_->getDefIndex(li_->getInstructionIndex(CopyMI));
278
279   // FIXME: For now, only eliminate the copy by commuting its def when the
280   // source register is a virtual register. We want to guard against cases
281   // where the copy is a back edge copy and commuting the def lengthen the
282   // live interval of the source register to the entire loop.
283   if (TargetRegisterInfo::isPhysicalRegister(IntA.reg))
284     return false;
285
286   // BValNo is a value number in B that is defined by a copy from A. 'B3' in
287   // the example above.
288   LiveInterval::iterator BLR = IntB.FindLiveRangeContaining(CopyIdx);
289   assert(BLR != IntB.end() && "Live range not found!");
290   VNInfo *BValNo = BLR->valno;
291   
292   // Get the location that B is defined at.  Two options: either this value has
293   // an unknown definition point or it is defined at CopyIdx.  If unknown, we 
294   // can't process it.
295   if (!BValNo->copy) return false;
296   assert(BValNo->def == CopyIdx && "Copy doesn't define the value?");
297   
298   // AValNo is the value number in A that defines the copy, A3 in the example.
299   LiveInterval::iterator ALR = IntA.FindLiveRangeContaining(CopyIdx-1);
300   assert(ALR != IntA.end() && "Live range not found!");
301   VNInfo *AValNo = ALR->valno;
302   // If other defs can reach uses of this def, then it's not safe to perform
303   // the optimization.
304   if (AValNo->def == ~0U || AValNo->def == ~1U || AValNo->hasPHIKill)
305     return false;
306   MachineInstr *DefMI = li_->getInstructionFromIndex(AValNo->def);
307   const TargetInstrDesc &TID = DefMI->getDesc();
308   unsigned NewDstIdx;
309   if (!TID.isCommutable() ||
310       !tii_->CommuteChangesDestination(DefMI, NewDstIdx))
311     return false;
312
313   MachineOperand &NewDstMO = DefMI->getOperand(NewDstIdx);
314   unsigned NewReg = NewDstMO.getReg();
315   if (NewReg != IntB.reg || !NewDstMO.isKill())
316     return false;
317
318   // Make sure there are no other definitions of IntB that would reach the
319   // uses which the new definition can reach.
320   if (HasOtherReachingDefs(IntA, IntB, AValNo, BValNo))
321     return false;
322
323   // If some of the uses of IntA.reg is already coalesced away, return false.
324   // It's not possible to determine whether it's safe to perform the coalescing.
325   for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(IntA.reg),
326          UE = mri_->use_end(); UI != UE; ++UI) {
327     MachineInstr *UseMI = &*UI;
328     unsigned UseIdx = li_->getInstructionIndex(UseMI);
329     LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx);
330     if (ULR == IntA.end())
331       continue;
332     if (ULR->valno == AValNo && JoinedCopies.count(UseMI))
333       return false;
334   }
335
336   // At this point we have decided that it is legal to do this
337   // transformation.  Start by commuting the instruction.
338   MachineBasicBlock *MBB = DefMI->getParent();
339   MachineInstr *NewMI = tii_->commuteInstruction(DefMI);
340   if (!NewMI)
341     return false;
342   if (NewMI != DefMI) {
343     li_->ReplaceMachineInstrInMaps(DefMI, NewMI);
344     MBB->insert(DefMI, NewMI);
345     MBB->erase(DefMI);
346   }
347   unsigned OpIdx = NewMI->findRegisterUseOperandIdx(IntA.reg, false);
348   NewMI->getOperand(OpIdx).setIsKill();
349
350   bool BHasPHIKill = BValNo->hasPHIKill;
351   SmallVector<VNInfo*, 4> BDeadValNos;
352   SmallVector<unsigned, 4> BKills;
353   std::map<unsigned, unsigned> BExtend;
354
355   // If ALR and BLR overlaps and end of BLR extends beyond end of ALR, e.g.
356   // A = or A, B
357   // ...
358   // B = A
359   // ...
360   // C = A<kill>
361   // ...
362   //   = B
363   //
364   // then do not add kills of A to the newly created B interval.
365   bool Extended = BLR->end > ALR->end && ALR->end != ALR->start;
366   if (Extended)
367     BExtend[ALR->end] = BLR->end;
368
369   // Update uses of IntA of the specific Val# with IntB.
370   for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(IntA.reg),
371          UE = mri_->use_end(); UI != UE;) {
372     MachineOperand &UseMO = UI.getOperand();
373     MachineInstr *UseMI = &*UI;
374     ++UI;
375     if (JoinedCopies.count(UseMI))
376       continue;
377     unsigned UseIdx = li_->getInstructionIndex(UseMI);
378     LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx);
379     if (ULR == IntA.end() || ULR->valno != AValNo)
380       continue;
381     UseMO.setReg(NewReg);
382     if (UseMI == CopyMI)
383       continue;
384     if (UseMO.isKill()) {
385       if (Extended)
386         UseMO.setIsKill(false);
387       else
388         BKills.push_back(li_->getUseIndex(UseIdx)+1);
389     }
390     unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
391     if (!tii_->isMoveInstr(*UseMI, SrcReg, DstReg, SrcSubIdx, DstSubIdx))
392       continue;
393     if (DstReg == IntB.reg) {
394       // This copy will become a noop. If it's defining a new val#,
395       // remove that val# as well. However this live range is being
396       // extended to the end of the existing live range defined by the copy.
397       unsigned DefIdx = li_->getDefIndex(UseIdx);
398       const LiveRange *DLR = IntB.getLiveRangeContaining(DefIdx);
399       BHasPHIKill |= DLR->valno->hasPHIKill;
400       assert(DLR->valno->def == DefIdx);
401       BDeadValNos.push_back(DLR->valno);
402       BExtend[DLR->start] = DLR->end;
403       JoinedCopies.insert(UseMI);
404       // If this is a kill but it's going to be removed, the last use
405       // of the same val# is the new kill.
406       if (UseMO.isKill())
407         BKills.pop_back();
408     }
409   }
410
411   // We need to insert a new liverange: [ALR.start, LastUse). It may be we can
412   // simply extend BLR if CopyMI doesn't end the range.
413   DOUT << "\nExtending: "; IntB.print(DOUT, tri_);
414
415   // Remove val#'s defined by copies that will be coalesced away.
416   for (unsigned i = 0, e = BDeadValNos.size(); i != e; ++i)
417     IntB.removeValNo(BDeadValNos[i]);
418
419   // Extend BValNo by merging in IntA live ranges of AValNo. Val# definition
420   // is updated. Kills are also updated.
421   VNInfo *ValNo = BValNo;
422   ValNo->def = AValNo->def;
423   ValNo->copy = NULL;
424   for (unsigned j = 0, ee = ValNo->kills.size(); j != ee; ++j) {
425     unsigned Kill = ValNo->kills[j];
426     if (Kill != BLR->end)
427       BKills.push_back(Kill);
428   }
429   ValNo->kills.clear();
430   for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
431        AI != AE; ++AI) {
432     if (AI->valno != AValNo) continue;
433     unsigned End = AI->end;
434     std::map<unsigned, unsigned>::iterator EI = BExtend.find(End);
435     if (EI != BExtend.end())
436       End = EI->second;
437     IntB.addRange(LiveRange(AI->start, End, ValNo));
438   }
439   IntB.addKills(ValNo, BKills);
440   ValNo->hasPHIKill = BHasPHIKill;
441
442   DOUT << "   result = "; IntB.print(DOUT, tri_);
443   DOUT << "\n";
444
445   DOUT << "\nShortening: "; IntA.print(DOUT, tri_);
446   IntA.removeValNo(AValNo);
447   DOUT << "   result = "; IntA.print(DOUT, tri_);
448   DOUT << "\n";
449
450   ++numCommutes;
451   return true;
452 }
453
454 /// isSameOrFallThroughBB - Return true if MBB == SuccMBB or MBB simply
455 /// fallthoughs to SuccMBB.
456 static bool isSameOrFallThroughBB(MachineBasicBlock *MBB,
457                                   MachineBasicBlock *SuccMBB,
458                                   const TargetInstrInfo *tii_) {
459   if (MBB == SuccMBB)
460     return true;
461   MachineBasicBlock *TBB = 0, *FBB = 0;
462   SmallVector<MachineOperand, 4> Cond;
463   return !tii_->AnalyzeBranch(*MBB, TBB, FBB, Cond) && !TBB && !FBB &&
464     MBB->isSuccessor(SuccMBB);
465 }
466
467 /// removeRange - Wrapper for LiveInterval::removeRange. This removes a range
468 /// from a physical register live interval as well as from the live intervals
469 /// of its sub-registers.
470 static void removeRange(LiveInterval &li, unsigned Start, unsigned End,
471                         LiveIntervals *li_, const TargetRegisterInfo *tri_) {
472   li.removeRange(Start, End, true);
473   if (TargetRegisterInfo::isPhysicalRegister(li.reg)) {
474     for (const unsigned* SR = tri_->getSubRegisters(li.reg); *SR; ++SR) {
475       if (!li_->hasInterval(*SR))
476         continue;
477       LiveInterval &sli = li_->getInterval(*SR);
478       unsigned RemoveEnd = Start;
479       while (RemoveEnd != End) {
480         LiveInterval::iterator LR = sli.FindLiveRangeContaining(Start);
481         if (LR == sli.end())
482           break;
483         RemoveEnd = (LR->end < End) ? LR->end : End;
484         sli.removeRange(Start, RemoveEnd, true);
485         Start = RemoveEnd;
486       }
487     }
488   }
489 }
490
491 /// TrimLiveIntervalToLastUse - If there is a last use in the same basic block
492 /// as the copy instruction, trim the ive interval to the last use and return
493 /// true.
494 bool
495 SimpleRegisterCoalescing::TrimLiveIntervalToLastUse(unsigned CopyIdx,
496                                                     MachineBasicBlock *CopyMBB,
497                                                     LiveInterval &li,
498                                                     const LiveRange *LR) {
499   unsigned MBBStart = li_->getMBBStartIdx(CopyMBB);
500   unsigned LastUseIdx;
501   MachineOperand *LastUse = lastRegisterUse(LR->start, CopyIdx-1, li.reg,
502                                             LastUseIdx);
503   if (LastUse) {
504     MachineInstr *LastUseMI = LastUse->getParent();
505     if (!isSameOrFallThroughBB(LastUseMI->getParent(), CopyMBB, tii_)) {
506       // r1024 = op
507       // ...
508       // BB1:
509       //       = r1024
510       //
511       // BB2:
512       // r1025<dead> = r1024<kill>
513       if (MBBStart < LR->end)
514         removeRange(li, MBBStart, LR->end, li_, tri_);
515       return true;
516     }
517
518     // There are uses before the copy, just shorten the live range to the end
519     // of last use.
520     LastUse->setIsKill();
521     removeRange(li, li_->getDefIndex(LastUseIdx), LR->end, li_, tri_);
522     unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
523     if (tii_->isMoveInstr(*LastUseMI, SrcReg, DstReg, SrcSubIdx, DstSubIdx) &&
524         DstReg == li.reg) {
525       // Last use is itself an identity code.
526       int DeadIdx = LastUseMI->findRegisterDefOperandIdx(li.reg, false, tri_);
527       LastUseMI->getOperand(DeadIdx).setIsDead();
528     }
529     return true;
530   }
531
532   // Is it livein?
533   if (LR->start <= MBBStart && LR->end > MBBStart) {
534     if (LR->start == 0) {
535       assert(TargetRegisterInfo::isPhysicalRegister(li.reg));
536       // Live-in to the function but dead. Remove it from entry live-in set.
537       mf_->begin()->removeLiveIn(li.reg);
538     }
539     // FIXME: Shorten intervals in BBs that reaches this BB.
540   }
541
542   return false;
543 }
544
545 /// ReMaterializeTrivialDef - If the source of a copy is defined by a trivial
546 /// computation, replace the copy by rematerialize the definition.
547 bool SimpleRegisterCoalescing::ReMaterializeTrivialDef(LiveInterval &SrcInt,
548                                                        unsigned DstReg,
549                                                        MachineInstr *CopyMI) {
550   unsigned CopyIdx = li_->getUseIndex(li_->getInstructionIndex(CopyMI));
551   LiveInterval::iterator SrcLR = SrcInt.FindLiveRangeContaining(CopyIdx);
552   assert(SrcLR != SrcInt.end() && "Live range not found!");
553   VNInfo *ValNo = SrcLR->valno;
554   // If other defs can reach uses of this def, then it's not safe to perform
555   // the optimization.
556   if (ValNo->def == ~0U || ValNo->def == ~1U || ValNo->hasPHIKill)
557     return false;
558   MachineInstr *DefMI = li_->getInstructionFromIndex(ValNo->def);
559   const TargetInstrDesc &TID = DefMI->getDesc();
560   if (!TID.isAsCheapAsAMove())
561     return false;
562   if (!DefMI->getDesc().isRematerializable() ||
563       !tii_->isTriviallyReMaterializable(DefMI))
564     return false;
565   bool SawStore = false;
566   if (!DefMI->isSafeToMove(tii_, SawStore))
567     return false;
568
569   unsigned DefIdx = li_->getDefIndex(CopyIdx);
570   const LiveRange *DLR= li_->getInterval(DstReg).getLiveRangeContaining(DefIdx);
571   DLR->valno->copy = NULL;
572   // Don't forget to update sub-register intervals.
573   if (TargetRegisterInfo::isPhysicalRegister(DstReg)) {
574     for (const unsigned* SR = tri_->getSubRegisters(DstReg); *SR; ++SR) {
575       if (!li_->hasInterval(*SR))
576         continue;
577       DLR = li_->getInterval(*SR).getLiveRangeContaining(DefIdx);
578       if (DLR && DLR->valno->copy == CopyMI)
579         DLR->valno->copy = NULL;
580     }
581   }
582
583   // If copy kills the source register, find the last use and propagate
584   // kill.
585   MachineBasicBlock *MBB = CopyMI->getParent();
586   if (CopyMI->killsRegister(SrcInt.reg))
587     TrimLiveIntervalToLastUse(CopyIdx, MBB, SrcInt, SrcLR);
588
589   MachineBasicBlock::iterator MII = next(MachineBasicBlock::iterator(CopyMI));
590   CopyMI->removeFromParent();
591   tii_->reMaterialize(*MBB, MII, DstReg, DefMI);
592   MachineInstr *NewMI = prior(MII);
593   // CopyMI may have implicit operands, transfer them over to the newly
594   // rematerialized instruction. And update implicit def interval valnos.
595   for (unsigned i = CopyMI->getDesc().getNumOperands(),
596          e = CopyMI->getNumOperands(); i != e; ++i) {
597     MachineOperand &MO = CopyMI->getOperand(i);
598     if (MO.isReg() && MO.isImplicit())
599       NewMI->addOperand(MO);
600     if (MO.isDef() && li_->hasInterval(MO.getReg())) {
601       unsigned Reg = MO.getReg();
602       DLR = li_->getInterval(Reg).getLiveRangeContaining(DefIdx);
603       if (DLR && DLR->valno->copy == CopyMI)
604         DLR->valno->copy = NULL;
605     }
606   }
607
608   li_->ReplaceMachineInstrInMaps(CopyMI, NewMI);
609   MBB->getParent()->DeleteMachineInstr(CopyMI);
610   ReMatCopies.insert(CopyMI);
611   ReMatDefs.insert(DefMI);
612   ++NumReMats;
613   return true;
614 }
615
616 /// isBackEdgeCopy - Returns true if CopyMI is a back edge copy.
617 ///
618 bool SimpleRegisterCoalescing::isBackEdgeCopy(MachineInstr *CopyMI,
619                                               unsigned DstReg) const {
620   MachineBasicBlock *MBB = CopyMI->getParent();
621   const MachineLoop *L = loopInfo->getLoopFor(MBB);
622   if (!L)
623     return false;
624   if (MBB != L->getLoopLatch())
625     return false;
626
627   LiveInterval &LI = li_->getInterval(DstReg);
628   unsigned DefIdx = li_->getInstructionIndex(CopyMI);
629   LiveInterval::const_iterator DstLR =
630     LI.FindLiveRangeContaining(li_->getDefIndex(DefIdx));
631   if (DstLR == LI.end())
632     return false;
633   unsigned KillIdx = li_->getMBBEndIdx(MBB) + 1;
634   if (DstLR->valno->kills.size() == 1 &&
635       DstLR->valno->kills[0] == KillIdx && DstLR->valno->hasPHIKill)
636     return true;
637   return false;
638 }
639
640 /// UpdateRegDefsUses - Replace all defs and uses of SrcReg to DstReg and
641 /// update the subregister number if it is not zero. If DstReg is a
642 /// physical register and the existing subregister number of the def / use
643 /// being updated is not zero, make sure to set it to the correct physical
644 /// subregister.
645 void
646 SimpleRegisterCoalescing::UpdateRegDefsUses(unsigned SrcReg, unsigned DstReg,
647                                             unsigned SubIdx) {
648   bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
649   if (DstIsPhys && SubIdx) {
650     // Figure out the real physical register we are updating with.
651     DstReg = tri_->getSubReg(DstReg, SubIdx);
652     SubIdx = 0;
653   }
654
655   for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(SrcReg),
656          E = mri_->reg_end(); I != E; ) {
657     MachineOperand &O = I.getOperand();
658     MachineInstr *UseMI = &*I;
659     ++I;
660     unsigned OldSubIdx = O.getSubReg();
661     if (DstIsPhys) {
662       unsigned UseDstReg = DstReg;
663       if (OldSubIdx)
664           UseDstReg = tri_->getSubReg(DstReg, OldSubIdx);
665
666       unsigned CopySrcReg, CopyDstReg, CopySrcSubIdx, CopyDstSubIdx;
667       if (tii_->isMoveInstr(*UseMI, CopySrcReg, CopyDstReg,
668                             CopySrcSubIdx, CopyDstSubIdx) &&
669           CopySrcReg != CopyDstReg &&
670           CopySrcReg == SrcReg && CopyDstReg != UseDstReg) {
671         // If the use is a copy and it won't be coalesced away, and its source
672         // is defined by a trivial computation, try to rematerialize it instead.
673         if (ReMaterializeTrivialDef(li_->getInterval(SrcReg), CopyDstReg,UseMI))
674           continue;
675       }
676
677       O.setReg(UseDstReg);
678       O.setSubReg(0);
679       continue;
680     }
681
682     // Sub-register indexes goes from small to large. e.g.
683     // RAX: 1 -> AL, 2 -> AX, 3 -> EAX
684     // EAX: 1 -> AL, 2 -> AX
685     // So RAX's sub-register 2 is AX, RAX's sub-regsiter 3 is EAX, whose
686     // sub-register 2 is also AX.
687     if (SubIdx && OldSubIdx && SubIdx != OldSubIdx)
688       assert(OldSubIdx < SubIdx && "Conflicting sub-register index!");
689     else if (SubIdx)
690       O.setSubReg(SubIdx);
691     // Remove would-be duplicated kill marker.
692     if (O.isKill() && UseMI->killsRegister(DstReg))
693       O.setIsKill(false);
694     O.setReg(DstReg);
695
696     // After updating the operand, check if the machine instruction has
697     // become a copy. If so, update its val# information.
698     const TargetInstrDesc &TID = UseMI->getDesc();
699     unsigned CopySrcReg, CopyDstReg, CopySrcSubIdx, CopyDstSubIdx;
700     if (TID.getNumDefs() == 1 && TID.getNumOperands() > 2 &&
701         tii_->isMoveInstr(*UseMI, CopySrcReg, CopyDstReg,
702                           CopySrcSubIdx, CopyDstSubIdx) &&
703         CopySrcReg != CopyDstReg &&
704         (TargetRegisterInfo::isVirtualRegister(CopyDstReg) ||
705          allocatableRegs_[CopyDstReg])) {
706       LiveInterval &LI = li_->getInterval(CopyDstReg);
707       unsigned DefIdx = li_->getDefIndex(li_->getInstructionIndex(UseMI));
708       const LiveRange *DLR = LI.getLiveRangeContaining(DefIdx);
709       if (DLR->valno->def == DefIdx)
710         DLR->valno->copy = UseMI;
711     }
712   }
713 }
714
715 /// RemoveDeadImpDef - Remove implicit_def instructions which are "re-defining"
716 /// registers due to insert_subreg coalescing. e.g.
717 /// r1024 = op
718 /// r1025 = implicit_def
719 /// r1025 = insert_subreg r1025, r1024
720 ///       = op r1025
721 /// =>
722 /// r1025 = op
723 /// r1025 = implicit_def
724 /// r1025 = insert_subreg r1025, r1025
725 ///       = op r1025
726 void
727 SimpleRegisterCoalescing::RemoveDeadImpDef(unsigned Reg, LiveInterval &LI) {
728   for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(Reg),
729          E = mri_->reg_end(); I != E; ) {
730     MachineOperand &O = I.getOperand();
731     MachineInstr *DefMI = &*I;
732     ++I;
733     if (!O.isDef())
734       continue;
735     if (DefMI->getOpcode() != TargetInstrInfo::IMPLICIT_DEF)
736       continue;
737     if (!LI.liveBeforeAndAt(li_->getInstructionIndex(DefMI)))
738       continue;
739     li_->RemoveMachineInstrFromMaps(DefMI);
740     DefMI->eraseFromParent();
741   }
742 }
743
744 /// RemoveUnnecessaryKills - Remove kill markers that are no longer accurate
745 /// due to live range lengthening as the result of coalescing.
746 void SimpleRegisterCoalescing::RemoveUnnecessaryKills(unsigned Reg,
747                                                       LiveInterval &LI) {
748   for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(Reg),
749          UE = mri_->use_end(); UI != UE; ++UI) {
750     MachineOperand &UseMO = UI.getOperand();
751     if (UseMO.isKill()) {
752       MachineInstr *UseMI = UseMO.getParent();
753       unsigned UseIdx = li_->getUseIndex(li_->getInstructionIndex(UseMI));
754       if (JoinedCopies.count(UseMI))
755         continue;
756       const LiveRange *UI = LI.getLiveRangeContaining(UseIdx);
757       if (!UI || !LI.isKill(UI->valno, UseIdx+1))
758         UseMO.setIsKill(false);
759     }
760   }
761 }
762
763 /// removeIntervalIfEmpty - Check if the live interval of a physical register
764 /// is empty, if so remove it and also remove the empty intervals of its
765 /// sub-registers. Return true if live interval is removed.
766 static bool removeIntervalIfEmpty(LiveInterval &li, LiveIntervals *li_,
767                                   const TargetRegisterInfo *tri_) {
768   if (li.empty()) {
769     if (TargetRegisterInfo::isPhysicalRegister(li.reg))
770       for (const unsigned* SR = tri_->getSubRegisters(li.reg); *SR; ++SR) {
771         if (!li_->hasInterval(*SR))
772           continue;
773         LiveInterval &sli = li_->getInterval(*SR);
774         if (sli.empty())
775           li_->removeInterval(*SR);
776       }
777     li_->removeInterval(li.reg);
778     return true;
779   }
780   return false;
781 }
782
783 /// ShortenDeadCopyLiveRange - Shorten a live range defined by a dead copy.
784 /// Return true if live interval is removed.
785 bool SimpleRegisterCoalescing::ShortenDeadCopyLiveRange(LiveInterval &li,
786                                                         MachineInstr *CopyMI) {
787   unsigned CopyIdx = li_->getInstructionIndex(CopyMI);
788   LiveInterval::iterator MLR =
789     li.FindLiveRangeContaining(li_->getDefIndex(CopyIdx));
790   if (MLR == li.end())
791     return false;  // Already removed by ShortenDeadCopySrcLiveRange.
792   unsigned RemoveStart = MLR->start;
793   unsigned RemoveEnd = MLR->end;
794   // Remove the liverange that's defined by this.
795   if (RemoveEnd == li_->getDefIndex(CopyIdx)+1) {
796     removeRange(li, RemoveStart, RemoveEnd, li_, tri_);
797     return removeIntervalIfEmpty(li, li_, tri_);
798   }
799   return false;
800 }
801
802 /// RemoveDeadDef - If a def of a live interval is now determined dead, remove
803 /// the val# it defines. If the live interval becomes empty, remove it as well.
804 bool SimpleRegisterCoalescing::RemoveDeadDef(LiveInterval &li,
805                                              MachineInstr *DefMI) {
806   unsigned DefIdx = li_->getDefIndex(li_->getInstructionIndex(DefMI));
807   LiveInterval::iterator MLR = li.FindLiveRangeContaining(DefIdx);
808   if (DefIdx != MLR->valno->def)
809     return false;
810   li.removeValNo(MLR->valno);
811   return removeIntervalIfEmpty(li, li_, tri_);
812 }
813
814 /// PropagateDeadness - Propagate the dead marker to the instruction which
815 /// defines the val#.
816 static void PropagateDeadness(LiveInterval &li, MachineInstr *CopyMI,
817                               unsigned &LRStart, LiveIntervals *li_,
818                               const TargetRegisterInfo* tri_) {
819   MachineInstr *DefMI =
820     li_->getInstructionFromIndex(li_->getDefIndex(LRStart));
821   if (DefMI && DefMI != CopyMI) {
822     int DeadIdx = DefMI->findRegisterDefOperandIdx(li.reg, false, tri_);
823     if (DeadIdx != -1) {
824       DefMI->getOperand(DeadIdx).setIsDead();
825       // A dead def should have a single cycle interval.
826       ++LRStart;
827     }
828   }
829 }
830
831 /// ShortenDeadCopySrcLiveRange - Shorten a live range as it's artificially
832 /// extended by a dead copy. Mark the last use (if any) of the val# as kill as
833 /// ends the live range there. If there isn't another use, then this live range
834 /// is dead. Return true if live interval is removed.
835 bool
836 SimpleRegisterCoalescing::ShortenDeadCopySrcLiveRange(LiveInterval &li,
837                                                       MachineInstr *CopyMI) {
838   unsigned CopyIdx = li_->getInstructionIndex(CopyMI);
839   if (CopyIdx == 0) {
840     // FIXME: special case: function live in. It can be a general case if the
841     // first instruction index starts at > 0 value.
842     assert(TargetRegisterInfo::isPhysicalRegister(li.reg));
843     // Live-in to the function but dead. Remove it from entry live-in set.
844     if (mf_->begin()->isLiveIn(li.reg))
845       mf_->begin()->removeLiveIn(li.reg);
846     const LiveRange *LR = li.getLiveRangeContaining(CopyIdx);
847     removeRange(li, LR->start, LR->end, li_, tri_);
848     return removeIntervalIfEmpty(li, li_, tri_);
849   }
850
851   LiveInterval::iterator LR = li.FindLiveRangeContaining(CopyIdx-1);
852   if (LR == li.end())
853     // Livein but defined by a phi.
854     return false;
855
856   unsigned RemoveStart = LR->start;
857   unsigned RemoveEnd = li_->getDefIndex(CopyIdx)+1;
858   if (LR->end > RemoveEnd)
859     // More uses past this copy? Nothing to do.
860     return false;
861
862   // If there is a last use in the same bb, we can't remove the live range.
863   // Shorten the live interval and return.
864   if (TrimLiveIntervalToLastUse(CopyIdx, CopyMI->getParent(), li, LR))
865     return false;
866
867   if (LR->valno->def == RemoveStart) {
868     // If the def MI defines the val# and this copy is the only kill of the
869     // val#, then propagate the dead marker.
870     if (li.isOnlyKill(LR->valno, RemoveEnd)) {
871       PropagateDeadness(li, CopyMI, RemoveStart, li_, tri_);
872       ++numDeadValNo;
873     } else
874       li.removeKill(LR->valno, RemoveEnd);
875   }
876
877   removeRange(li, RemoveStart, LR->end, li_, tri_);
878   return removeIntervalIfEmpty(li, li_, tri_);
879 }
880
881 /// CanCoalesceWithImpDef - Returns true if the specified copy instruction
882 /// from an implicit def to another register can be coalesced away.
883 bool SimpleRegisterCoalescing::CanCoalesceWithImpDef(MachineInstr *CopyMI,
884                                                      LiveInterval &li,
885                                                      LiveInterval &ImpLi) const{
886   if (!CopyMI->killsRegister(ImpLi.reg))
887     return false;
888   unsigned CopyIdx = li_->getDefIndex(li_->getInstructionIndex(CopyMI));
889   LiveInterval::iterator LR = li.FindLiveRangeContaining(CopyIdx);
890   if (LR == li.end())
891     return false;
892   if (LR->valno->hasPHIKill)
893     return false;
894   if (LR->valno->def != CopyIdx)
895     return false;
896   // Make sure all of val# uses are copies.
897   for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(li.reg),
898          UE = mri_->use_end(); UI != UE;) {
899     MachineInstr *UseMI = &*UI;
900     ++UI;
901     if (JoinedCopies.count(UseMI))
902       continue;
903     unsigned UseIdx = li_->getUseIndex(li_->getInstructionIndex(UseMI));
904     LiveInterval::iterator ULR = li.FindLiveRangeContaining(UseIdx);
905     if (ULR == li.end() || ULR->valno != LR->valno)
906       continue;
907     // If the use is not a use, then it's not safe to coalesce the move.
908     unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
909     if (!tii_->isMoveInstr(*UseMI, SrcReg, DstReg, SrcSubIdx, DstSubIdx)) {
910       if (UseMI->getOpcode() == TargetInstrInfo::INSERT_SUBREG &&
911           UseMI->getOperand(1).getReg() == li.reg)
912         continue;
913       return false;
914     }
915   }
916   return true;
917 }
918
919
920 /// RemoveCopiesFromValNo - The specified value# is defined by an implicit
921 /// def and it is being removed. Turn all copies from this value# into
922 /// identity copies so they will be removed.
923 void SimpleRegisterCoalescing::RemoveCopiesFromValNo(LiveInterval &li,
924                                                      VNInfo *VNI) {
925   SmallVector<MachineInstr*, 4> ImpDefs;
926   MachineOperand *LastUse = NULL;
927   unsigned LastUseIdx = li_->getUseIndex(VNI->def);
928   for (MachineRegisterInfo::reg_iterator RI = mri_->reg_begin(li.reg),
929          RE = mri_->reg_end(); RI != RE;) {
930     MachineOperand *MO = &RI.getOperand();
931     MachineInstr *MI = &*RI;
932     ++RI;
933     if (MO->isDef()) {
934       if (MI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF) {
935         ImpDefs.push_back(MI);
936       }
937       continue;
938     }
939     if (JoinedCopies.count(MI))
940       continue;
941     unsigned UseIdx = li_->getUseIndex(li_->getInstructionIndex(MI));
942     LiveInterval::iterator ULR = li.FindLiveRangeContaining(UseIdx);
943     if (ULR == li.end() || ULR->valno != VNI)
944       continue;
945     // If the use is a copy, turn it into an identity copy.
946     unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
947     if (tii_->isMoveInstr(*MI, SrcReg, DstReg, SrcSubIdx, DstSubIdx) &&
948         SrcReg == li.reg) {
949       // Each use MI may have multiple uses of this register. Change them all.
950       for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
951         MachineOperand &MO = MI->getOperand(i);
952         if (MO.isReg() && MO.getReg() == li.reg)
953           MO.setReg(DstReg);
954       }
955       JoinedCopies.insert(MI);
956     } else if (UseIdx > LastUseIdx) {
957       LastUseIdx = UseIdx;
958       LastUse = MO;
959     }
960   }
961   if (LastUse)
962     LastUse->setIsKill();
963   else {
964     // Remove dead implicit_def's.
965     while (!ImpDefs.empty()) {
966       MachineInstr *ImpDef = ImpDefs.back();
967       ImpDefs.pop_back();
968       li_->RemoveMachineInstrFromMaps(ImpDef);
969       ImpDef->eraseFromParent();
970     }
971   }
972 }
973
974 /// getMatchingSuperReg - Return a super-register of the specified register
975 /// Reg so its sub-register of index SubIdx is Reg.
976 static unsigned getMatchingSuperReg(unsigned Reg, unsigned SubIdx, 
977                                     const TargetRegisterClass *RC,
978                                     const TargetRegisterInfo* TRI) {
979   for (const unsigned *SRs = TRI->getSuperRegisters(Reg);
980        unsigned SR = *SRs; ++SRs)
981     if (Reg == TRI->getSubReg(SR, SubIdx) && RC->contains(SR))
982       return SR;
983   return 0;
984 }
985
986 /// isWinToJoinCrossClass - Return true if it's profitable to coalesce
987 /// two virtual registers from different register classes.
988 bool
989 SimpleRegisterCoalescing::isWinToJoinCrossClass(unsigned LargeReg,
990                                                 unsigned SmallReg,
991                                                 unsigned Threshold) {
992   // Then make sure the intervals are *short*.
993   LiveInterval &LargeInt = li_->getInterval(LargeReg);
994   LiveInterval &SmallInt = li_->getInterval(SmallReg);
995   unsigned LargeSize = li_->getApproximateInstructionCount(LargeInt);
996   unsigned SmallSize = li_->getApproximateInstructionCount(SmallInt);
997   if (SmallSize > Threshold || LargeSize > Threshold)
998     if ((float)std::distance(mri_->use_begin(SmallReg),
999                              mri_->use_end()) / SmallSize <
1000         (float)std::distance(mri_->use_begin(LargeReg),
1001                              mri_->use_end()) / LargeSize)
1002       return false;
1003   return true;
1004 }
1005
1006 /// HasIncompatibleSubRegDefUse - If we are trying to coalesce a virtual
1007 /// register with a physical register, check if any of the virtual register
1008 /// operand is a sub-register use or def. If so, make sure it won't result
1009 /// in an illegal extract_subreg or insert_subreg instruction. e.g.
1010 /// vr1024 = extract_subreg vr1025, 1
1011 /// ...
1012 /// vr1024 = mov8rr AH
1013 /// If vr1024 is coalesced with AH, the extract_subreg is now illegal since
1014 /// AH does not have a super-reg whose sub-register 1 is AH.
1015 bool
1016 SimpleRegisterCoalescing::HasIncompatibleSubRegDefUse(MachineInstr *CopyMI,
1017                                                       unsigned VirtReg,
1018                                                       unsigned PhysReg) {
1019   for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(VirtReg),
1020          E = mri_->reg_end(); I != E; ++I) {
1021     MachineOperand &O = I.getOperand();
1022     MachineInstr *MI = &*I;
1023     if (MI == CopyMI || JoinedCopies.count(MI))
1024       continue;
1025     unsigned SubIdx = O.getSubReg();
1026     if (SubIdx && !tri_->getSubReg(PhysReg, SubIdx))
1027       return true;
1028     if (MI->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG) {
1029       SubIdx = MI->getOperand(2).getImm();
1030       if (O.isUse() && !tri_->getSubReg(PhysReg, SubIdx))
1031         return true;
1032       if (O.isDef()) {
1033         unsigned SrcReg = MI->getOperand(1).getReg();
1034         const TargetRegisterClass *RC =
1035           TargetRegisterInfo::isPhysicalRegister(SrcReg)
1036           ? tri_->getPhysicalRegisterRegClass(SrcReg)
1037           : mri_->getRegClass(SrcReg);
1038         if (!getMatchingSuperReg(PhysReg, SubIdx, RC, tri_))
1039           return true;
1040       }
1041     }
1042     if (MI->getOpcode() == TargetInstrInfo::INSERT_SUBREG) {
1043       SubIdx = MI->getOperand(3).getImm();
1044       if (VirtReg == MI->getOperand(0).getReg()) {
1045         if (!tri_->getSubReg(PhysReg, SubIdx))
1046           return true;
1047       } else {
1048         unsigned DstReg = MI->getOperand(0).getReg();
1049         const TargetRegisterClass *RC =
1050           TargetRegisterInfo::isPhysicalRegister(DstReg)
1051           ? tri_->getPhysicalRegisterRegClass(DstReg)
1052           : mri_->getRegClass(DstReg);
1053         if (!getMatchingSuperReg(PhysReg, SubIdx, RC, tri_))
1054           return true;
1055       }
1056     }
1057   }
1058   return false;
1059 }
1060
1061
1062 /// CanJoinExtractSubRegToPhysReg - Return true if it's possible to coalesce
1063 /// an extract_subreg where dst is a physical register, e.g.
1064 /// cl = EXTRACT_SUBREG reg1024, 1
1065 bool
1066 SimpleRegisterCoalescing::CanJoinExtractSubRegToPhysReg(unsigned DstReg,
1067                                                unsigned SrcReg, unsigned SubIdx,
1068                                                unsigned &RealDstReg) {
1069   const TargetRegisterClass *RC = mri_->getRegClass(SrcReg);
1070   RealDstReg = getMatchingSuperReg(DstReg, SubIdx, RC, tri_);
1071   assert(RealDstReg && "Invalid extract_subreg instruction!");
1072
1073   // For this type of EXTRACT_SUBREG, conservatively
1074   // check if the live interval of the source register interfere with the
1075   // actual super physical register we are trying to coalesce with.
1076   LiveInterval &RHS = li_->getInterval(SrcReg);
1077   if (li_->hasInterval(RealDstReg) &&
1078       RHS.overlaps(li_->getInterval(RealDstReg))) {
1079     DOUT << "Interfere with register ";
1080     DEBUG(li_->getInterval(RealDstReg).print(DOUT, tri_));
1081     return false; // Not coalescable
1082   }
1083   for (const unsigned* SR = tri_->getSubRegisters(RealDstReg); *SR; ++SR)
1084     if (li_->hasInterval(*SR) && RHS.overlaps(li_->getInterval(*SR))) {
1085       DOUT << "Interfere with sub-register ";
1086       DEBUG(li_->getInterval(*SR).print(DOUT, tri_));
1087       return false; // Not coalescable
1088     }
1089   return true;
1090 }
1091
1092 /// CanJoinInsertSubRegToPhysReg - Return true if it's possible to coalesce
1093 /// an insert_subreg where src is a physical register, e.g.
1094 /// reg1024 = INSERT_SUBREG reg1024, c1, 0
1095 bool
1096 SimpleRegisterCoalescing::CanJoinInsertSubRegToPhysReg(unsigned DstReg,
1097                                                unsigned SrcReg, unsigned SubIdx,
1098                                                unsigned &RealSrcReg) {
1099   const TargetRegisterClass *RC = mri_->getRegClass(DstReg);
1100   RealSrcReg = getMatchingSuperReg(SrcReg, SubIdx, RC, tri_);
1101   assert(RealSrcReg && "Invalid extract_subreg instruction!");
1102
1103   LiveInterval &RHS = li_->getInterval(DstReg);
1104   if (li_->hasInterval(RealSrcReg) &&
1105       RHS.overlaps(li_->getInterval(RealSrcReg))) {
1106     DOUT << "Interfere with register ";
1107     DEBUG(li_->getInterval(RealSrcReg).print(DOUT, tri_));
1108     return false; // Not coalescable
1109   }
1110   for (const unsigned* SR = tri_->getSubRegisters(RealSrcReg); *SR; ++SR)
1111     if (li_->hasInterval(*SR) && RHS.overlaps(li_->getInterval(*SR))) {
1112       DOUT << "Interfere with sub-register ";
1113       DEBUG(li_->getInterval(*SR).print(DOUT, tri_));
1114       return false; // Not coalescable
1115     }
1116   return true;
1117 }
1118
1119 /// JoinCopy - Attempt to join intervals corresponding to SrcReg/DstReg,
1120 /// which are the src/dst of the copy instruction CopyMI.  This returns true
1121 /// if the copy was successfully coalesced away. If it is not currently
1122 /// possible to coalesce this interval, but it may be possible if other
1123 /// things get coalesced, then it returns true by reference in 'Again'.
1124 bool SimpleRegisterCoalescing::JoinCopy(CopyRec &TheCopy, bool &Again) {
1125   MachineInstr *CopyMI = TheCopy.MI;
1126
1127   Again = false;
1128   if (JoinedCopies.count(CopyMI) || ReMatCopies.count(CopyMI))
1129     return false; // Already done.
1130
1131   DOUT << li_->getInstructionIndex(CopyMI) << '\t' << *CopyMI;
1132
1133   unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
1134   bool isExtSubReg = CopyMI->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG;
1135   bool isInsSubReg = CopyMI->getOpcode() == TargetInstrInfo::INSERT_SUBREG;
1136   unsigned SubIdx = 0;
1137   if (isExtSubReg) {
1138     DstReg = CopyMI->getOperand(0).getReg();
1139     SrcReg = CopyMI->getOperand(1).getReg();
1140   } else if (isInsSubReg) {
1141     if (CopyMI->getOperand(2).getSubReg()) {
1142       DOUT << "\tSource of insert_subreg is already coalesced "
1143            << "to another register.\n";
1144       return false;  // Not coalescable.
1145     }
1146     DstReg = CopyMI->getOperand(0).getReg();
1147     SrcReg = CopyMI->getOperand(2).getReg();
1148   } else if (!tii_->isMoveInstr(*CopyMI, SrcReg, DstReg, SrcSubIdx, DstSubIdx)){
1149     assert(0 && "Unrecognized copy instruction!");
1150     return false;
1151   }
1152
1153   // If they are already joined we continue.
1154   if (SrcReg == DstReg) {
1155     DOUT << "\tCopy already coalesced.\n";
1156     return false;  // Not coalescable.
1157   }
1158   
1159   bool SrcIsPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
1160   bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
1161
1162   // If they are both physical registers, we cannot join them.
1163   if (SrcIsPhys && DstIsPhys) {
1164     DOUT << "\tCan not coalesce physregs.\n";
1165     return false;  // Not coalescable.
1166   }
1167   
1168   // We only join virtual registers with allocatable physical registers.
1169   if (SrcIsPhys && !allocatableRegs_[SrcReg]) {
1170     DOUT << "\tSrc reg is unallocatable physreg.\n";
1171     return false;  // Not coalescable.
1172   }
1173   if (DstIsPhys && !allocatableRegs_[DstReg]) {
1174     DOUT << "\tDst reg is unallocatable physreg.\n";
1175     return false;  // Not coalescable.
1176   }
1177
1178   // Should be non-null only when coalescing to a sub-register class.
1179   bool CrossRC = false;
1180   const TargetRegisterClass *NewRC = NULL;
1181   MachineBasicBlock *CopyMBB = CopyMI->getParent();
1182   unsigned RealDstReg = 0;
1183   unsigned RealSrcReg = 0;
1184   if (isExtSubReg || isInsSubReg) {
1185     SubIdx = CopyMI->getOperand(isExtSubReg ? 2 : 3).getImm();
1186     if (SrcIsPhys && isExtSubReg) {
1187       // r1024 = EXTRACT_SUBREG EAX, 0 then r1024 is really going to be
1188       // coalesced with AX.
1189       unsigned DstSubIdx = CopyMI->getOperand(0).getSubReg();
1190       if (DstSubIdx) {
1191         // r1024<2> = EXTRACT_SUBREG EAX, 2. Then r1024 has already been
1192         // coalesced to a larger register so the subreg indices cancel out.
1193         if (DstSubIdx != SubIdx) {
1194           DOUT << "\t Sub-register indices mismatch.\n";
1195           return false; // Not coalescable.
1196         }
1197       } else
1198         SrcReg = tri_->getSubReg(SrcReg, SubIdx);
1199       SubIdx = 0;
1200     } else if (DstIsPhys && isInsSubReg) {
1201       // EAX = INSERT_SUBREG EAX, r1024, 0
1202       unsigned SrcSubIdx = CopyMI->getOperand(2).getSubReg();
1203       if (SrcSubIdx) {
1204         // EAX = INSERT_SUBREG EAX, r1024<2>, 2 Then r1024 has already been
1205         // coalesced to a larger register so the subreg indices cancel out.
1206         if (SrcSubIdx != SubIdx) {
1207           DOUT << "\t Sub-register indices mismatch.\n";
1208           return false; // Not coalescable.
1209         }
1210       } else
1211         DstReg = tri_->getSubReg(DstReg, SubIdx);
1212       SubIdx = 0;
1213     } else if ((DstIsPhys && isExtSubReg) || (SrcIsPhys && isInsSubReg)) {
1214       if (CopyMI->getOperand(1).getSubReg()) {
1215         DOUT << "\tSrc of extract_subreg already coalesced with reg"
1216              << " of a super-class.\n";
1217         return false; // Not coalescable.
1218       }
1219
1220       if (isExtSubReg) {
1221         if (!CanJoinExtractSubRegToPhysReg(DstReg, SrcReg, SubIdx, RealDstReg))
1222           return false; // Not coalescable
1223       } else {
1224         if (!CanJoinInsertSubRegToPhysReg(DstReg, SrcReg, SubIdx, RealSrcReg))
1225           return false; // Not coalescable
1226       }
1227       SubIdx = 0;
1228     } else {
1229       unsigned OldSubIdx = isExtSubReg ? CopyMI->getOperand(0).getSubReg()
1230         : CopyMI->getOperand(2).getSubReg();
1231       if (OldSubIdx) {
1232         if (OldSubIdx == SubIdx && !differingRegisterClasses(SrcReg, DstReg))
1233           // r1024<2> = EXTRACT_SUBREG r1025, 2. Then r1024 has already been
1234           // coalesced to a larger register so the subreg indices cancel out.
1235           // Also check if the other larger register is of the same register
1236           // class as the would be resulting register.
1237           SubIdx = 0;
1238         else {
1239           DOUT << "\t Sub-register indices mismatch.\n";
1240           return false; // Not coalescable.
1241         }
1242       }
1243       if (SubIdx) {
1244         unsigned LargeReg = isExtSubReg ? SrcReg : DstReg;
1245         unsigned SmallReg = isExtSubReg ? DstReg : SrcReg;
1246         unsigned Limit= allocatableRCRegs_[mri_->getRegClass(SmallReg)].count();
1247         if (!isWinToJoinCrossClass(LargeReg, SmallReg, Limit)) {
1248           Again = true;  // May be possible to coalesce later.
1249           return false;
1250         }
1251       }
1252     }
1253   } else if (differingRegisterClasses(SrcReg, DstReg)) {
1254     if (!CrossClassJoin)
1255       return false;
1256     CrossRC = true;
1257
1258     // FIXME: What if the result of a EXTRACT_SUBREG is then coalesced
1259     // with another? If it's the resulting destination register, then
1260     // the subidx must be propagated to uses (but only those defined
1261     // by the EXTRACT_SUBREG). If it's being coalesced into another
1262     // register, it should be safe because register is assumed to have
1263     // the register class of the super-register.
1264
1265     // Process moves where one of the registers have a sub-register index.
1266     MachineOperand *DstMO = CopyMI->findRegisterDefOperand(DstReg);
1267     if (DstMO->getSubReg())
1268       // FIXME: Can we handle this?
1269       return false;
1270     MachineOperand *SrcMO = CopyMI->findRegisterUseOperand(SrcReg);
1271     SubIdx = SrcMO->getSubReg();
1272     if (SubIdx) {
1273       // This is not a extract_subreg but it looks like one.
1274       // e.g. %cl = MOV16rr %reg1024:2
1275       isExtSubReg = true;
1276       if (DstIsPhys) {
1277         if (!CanJoinExtractSubRegToPhysReg(DstReg, SrcReg, SubIdx,RealDstReg))
1278           return false; // Not coalescable
1279         SubIdx = 0;
1280       }
1281     }
1282
1283     const TargetRegisterClass *SrcRC= SrcIsPhys ? 0 : mri_->getRegClass(SrcReg);
1284     const TargetRegisterClass *DstRC= DstIsPhys ? 0 : mri_->getRegClass(DstReg);
1285     unsigned LargeReg = SrcReg;
1286     unsigned SmallReg = DstReg;
1287     unsigned Limit = 0;
1288
1289     // Now determine the register class of the joined register.
1290     if (isExtSubReg) {
1291       if (SubIdx && DstRC && DstRC->isASubClass()) {
1292         // This is a move to a sub-register class. However, the source is a
1293         // sub-register of a larger register class. We don't know what should
1294         // the register class be. FIXME.
1295         Again = true;
1296         return false;
1297       }
1298       Limit = allocatableRCRegs_[DstRC].count();
1299     } else if (!SrcIsPhys && !SrcIsPhys) {
1300       unsigned SrcSize = SrcRC->getSize();
1301       unsigned DstSize = DstRC->getSize();
1302       if (SrcSize < DstSize)
1303         // For example X86::MOVSD2PDrr copies from FR64 to VR128.
1304         NewRC = DstRC;
1305       else if (DstSize > SrcSize) {
1306         NewRC = SrcRC;
1307         std::swap(LargeReg, SmallReg);
1308       } else {
1309         unsigned SrcNumRegs = SrcRC->getNumRegs();
1310         unsigned DstNumRegs = DstRC->getNumRegs();
1311         if (DstNumRegs < SrcNumRegs)
1312           // Sub-register class?
1313           NewRC = DstRC;
1314         else if (SrcNumRegs < DstNumRegs) {
1315           NewRC = SrcRC;
1316           std::swap(LargeReg, SmallReg);
1317         } else
1318           // No idea what's the right register class to use.
1319           return false;
1320       }
1321     }
1322
1323     // If we are joining two virtual registers and the resulting register
1324     // class is more restrictive (fewer register, smaller size). Check if it's
1325     // worth doing the merge.
1326     if (!SrcIsPhys && !DstIsPhys &&
1327         (isExtSubReg || DstRC->isASubClass()) &&
1328         !isWinToJoinCrossClass(LargeReg, SmallReg,
1329                                allocatableRCRegs_[NewRC].count())) {
1330       DOUT << "\tSrc/Dest are different register classes.\n";
1331       // Allow the coalescer to try again in case either side gets coalesced to
1332       // a physical register that's compatible with the other side. e.g.
1333       // r1024 = MOV32to32_ r1025
1334       // But later r1024 is assigned EAX then r1025 may be coalesced with EAX.
1335       Again = true;  // May be possible to coalesce later.
1336       return false;
1337     }
1338   }
1339
1340   // Will it create illegal extract_subreg / insert_subreg?
1341   if (SrcIsPhys && HasIncompatibleSubRegDefUse(CopyMI, DstReg, SrcReg))
1342     return false;
1343   if (DstIsPhys && HasIncompatibleSubRegDefUse(CopyMI, SrcReg, DstReg))
1344     return false;
1345   
1346   LiveInterval &SrcInt = li_->getInterval(SrcReg);
1347   LiveInterval &DstInt = li_->getInterval(DstReg);
1348   assert(SrcInt.reg == SrcReg && DstInt.reg == DstReg &&
1349          "Register mapping is horribly broken!");
1350
1351   DOUT << "\t\tInspecting "; SrcInt.print(DOUT, tri_);
1352   DOUT << " and "; DstInt.print(DOUT, tri_);
1353   DOUT << ": ";
1354
1355   // Check if it is necessary to propagate "isDead" property.
1356   if (!isExtSubReg && !isInsSubReg) {
1357     MachineOperand *mopd = CopyMI->findRegisterDefOperand(DstReg, false);
1358     bool isDead = mopd->isDead();
1359
1360     // We need to be careful about coalescing a source physical register with a
1361     // virtual register. Once the coalescing is done, it cannot be broken and
1362     // these are not spillable! If the destination interval uses are far away,
1363     // think twice about coalescing them!
1364     if (!isDead && (SrcIsPhys || DstIsPhys)) {
1365       LiveInterval &JoinVInt = SrcIsPhys ? DstInt : SrcInt;
1366       unsigned JoinVReg = SrcIsPhys ? DstReg : SrcReg;
1367       unsigned JoinPReg = SrcIsPhys ? SrcReg : DstReg;
1368       const TargetRegisterClass *RC = mri_->getRegClass(JoinVReg);
1369       unsigned Threshold = allocatableRCRegs_[RC].count() * 2;
1370       if (TheCopy.isBackEdge)
1371         Threshold *= 2; // Favors back edge copies.
1372
1373       // If the virtual register live interval is long but it has low use desity,
1374       // do not join them, instead mark the physical register as its allocation
1375       // preference.
1376       unsigned Length = li_->getApproximateInstructionCount(JoinVInt);
1377       if (Length > Threshold &&
1378           (((float)std::distance(mri_->use_begin(JoinVReg), mri_->use_end())
1379             / Length) < (1.0 / Threshold))) {
1380         JoinVInt.preference = JoinPReg;
1381         ++numAborts;
1382         DOUT << "\tMay tie down a physical register, abort!\n";
1383         Again = true;  // May be possible to coalesce later.
1384         return false;
1385       }
1386     }
1387   }
1388
1389   // Okay, attempt to join these two intervals.  On failure, this returns false.
1390   // Otherwise, if one of the intervals being joined is a physreg, this method
1391   // always canonicalizes DstInt to be it.  The output "SrcInt" will not have
1392   // been modified, so we can use this information below to update aliases.
1393   bool Swapped = false;
1394   // If SrcInt is implicitly defined, it's safe to coalesce.
1395   bool isEmpty = SrcInt.empty();
1396   if (isEmpty && !CanCoalesceWithImpDef(CopyMI, DstInt, SrcInt)) {
1397     // Only coalesce an empty interval (defined by implicit_def) with
1398     // another interval which has a valno defined by the CopyMI and the CopyMI
1399     // is a kill of the implicit def.
1400     DOUT << "Not profitable!\n";
1401     return false;
1402   }
1403
1404   if (!isEmpty && !JoinIntervals(DstInt, SrcInt, Swapped)) {
1405     // Coalescing failed.
1406
1407     // If definition of source is defined by trivial computation, try
1408     // rematerializing it.
1409     if (!isExtSubReg && !isInsSubReg &&
1410         ReMaterializeTrivialDef(SrcInt, DstInt.reg, CopyMI))
1411       return true;
1412     
1413     // If we can eliminate the copy without merging the live ranges, do so now.
1414     if (!isExtSubReg && !isInsSubReg &&
1415         (AdjustCopiesBackFrom(SrcInt, DstInt, CopyMI) ||
1416          RemoveCopyByCommutingDef(SrcInt, DstInt, CopyMI))) {
1417       JoinedCopies.insert(CopyMI);
1418       return true;
1419     }
1420     
1421     // Otherwise, we are unable to join the intervals.
1422     DOUT << "Interference!\n";
1423     Again = true;  // May be possible to coalesce later.
1424     return false;
1425   }
1426
1427   LiveInterval *ResSrcInt = &SrcInt;
1428   LiveInterval *ResDstInt = &DstInt;
1429   if (Swapped) {
1430     std::swap(SrcReg, DstReg);
1431     std::swap(ResSrcInt, ResDstInt);
1432   }
1433   assert(TargetRegisterInfo::isVirtualRegister(SrcReg) &&
1434          "LiveInterval::join didn't work right!");
1435                                
1436   // If we're about to merge live ranges into a physical register live interval,
1437   // we have to update any aliased register's live ranges to indicate that they
1438   // have clobbered values for this range.
1439   if (TargetRegisterInfo::isPhysicalRegister(DstReg)) {
1440     // If this is a extract_subreg where dst is a physical register, e.g.
1441     // cl = EXTRACT_SUBREG reg1024, 1
1442     // then create and update the actual physical register allocated to RHS.
1443     if (RealDstReg || RealSrcReg) {
1444       LiveInterval &RealInt =
1445         li_->getOrCreateInterval(RealDstReg ? RealDstReg : RealSrcReg);
1446       SmallSet<const VNInfo*, 4> CopiedValNos;
1447       for (LiveInterval::Ranges::const_iterator I = ResSrcInt->ranges.begin(),
1448              E = ResSrcInt->ranges.end(); I != E; ++I) {
1449         const LiveRange *DstLR = ResDstInt->getLiveRangeContaining(I->start);
1450         assert(DstLR  && "Invalid joined interval!");
1451         const VNInfo *DstValNo = DstLR->valno;
1452         if (CopiedValNos.insert(DstValNo)) {
1453           VNInfo *ValNo = RealInt.getNextValue(DstValNo->def, DstValNo->copy,
1454                                                li_->getVNInfoAllocator());
1455           ValNo->hasPHIKill = DstValNo->hasPHIKill;
1456           RealInt.addKills(ValNo, DstValNo->kills);
1457           RealInt.MergeValueInAsValue(*ResDstInt, DstValNo, ValNo);
1458         }
1459       }
1460       
1461       DstReg = RealDstReg ? RealDstReg : RealSrcReg;
1462     }
1463
1464     // Update the liveintervals of sub-registers.
1465     for (const unsigned *AS = tri_->getSubRegisters(DstReg); *AS; ++AS)
1466       li_->getOrCreateInterval(*AS).MergeInClobberRanges(*ResSrcInt,
1467                                                  li_->getVNInfoAllocator());
1468   }
1469
1470   // If this is a EXTRACT_SUBREG, make sure the result of coalescing is the
1471   // larger super-register.
1472   if ((isExtSubReg || isInsSubReg) && !SrcIsPhys && !DstIsPhys) {
1473     if ((isExtSubReg && !Swapped) || (isInsSubReg && Swapped)) {
1474       ResSrcInt->Copy(*ResDstInt, li_->getVNInfoAllocator());
1475       std::swap(SrcReg, DstReg);
1476       std::swap(ResSrcInt, ResDstInt);
1477     }
1478   }
1479
1480   // Coalescing to a virtual register that is of a sub-register class of the
1481   // other. Make sure the resulting register is set to the right register class.
1482   if (CrossRC) {
1483       ++numCrossRCs;
1484     if (NewRC)
1485       mri_->setRegClass(DstReg, NewRC);
1486   }
1487
1488   if (NewHeuristic) {
1489     // Add all copies that define val# in the source interval into the queue.
1490     for (LiveInterval::const_vni_iterator i = ResSrcInt->vni_begin(),
1491            e = ResSrcInt->vni_end(); i != e; ++i) {
1492       const VNInfo *vni = *i;
1493       if (!vni->def || vni->def == ~1U || vni->def == ~0U)
1494         continue;
1495       MachineInstr *CopyMI = li_->getInstructionFromIndex(vni->def);
1496       unsigned NewSrcReg, NewDstReg, NewSrcSubIdx, NewDstSubIdx;
1497       if (CopyMI &&
1498           JoinedCopies.count(CopyMI) == 0 &&
1499           tii_->isMoveInstr(*CopyMI, NewSrcReg, NewDstReg,
1500                             NewSrcSubIdx, NewDstSubIdx)) {
1501         unsigned LoopDepth = loopInfo->getLoopDepth(CopyMBB);
1502         JoinQueue->push(CopyRec(CopyMI, LoopDepth,
1503                                 isBackEdgeCopy(CopyMI, DstReg)));
1504       }
1505     }
1506   }
1507
1508   // Remember to delete the copy instruction.
1509   JoinedCopies.insert(CopyMI);
1510
1511   // Some live range has been lengthened due to colaescing, eliminate the
1512   // unnecessary kills.
1513   RemoveUnnecessaryKills(SrcReg, *ResDstInt);
1514   if (TargetRegisterInfo::isVirtualRegister(DstReg))
1515     RemoveUnnecessaryKills(DstReg, *ResDstInt);
1516
1517   if (isInsSubReg)
1518     // Avoid:
1519     // r1024 = op
1520     // r1024 = implicit_def
1521     // ...
1522     //       = r1024
1523     RemoveDeadImpDef(DstReg, *ResDstInt);
1524   UpdateRegDefsUses(SrcReg, DstReg, SubIdx);
1525
1526   // SrcReg is guarateed to be the register whose live interval that is
1527   // being merged.
1528   li_->removeInterval(SrcReg);
1529
1530   if (isEmpty) {
1531     // Now the copy is being coalesced away, the val# previously defined
1532     // by the copy is being defined by an IMPLICIT_DEF which defines a zero
1533     // length interval. Remove the val#.
1534     unsigned CopyIdx = li_->getDefIndex(li_->getInstructionIndex(CopyMI));
1535     const LiveRange *LR = ResDstInt->getLiveRangeContaining(CopyIdx);
1536     VNInfo *ImpVal = LR->valno;
1537     assert(ImpVal->def == CopyIdx);
1538     unsigned NextDef = LR->end;
1539     RemoveCopiesFromValNo(*ResDstInt, ImpVal);
1540     ResDstInt->removeValNo(ImpVal);
1541     LR = ResDstInt->FindLiveRangeContaining(NextDef);
1542     if (LR != ResDstInt->end() && LR->valno->def == NextDef) {
1543       // Special case: vr1024 = implicit_def
1544       //               vr1024 = insert_subreg vr1024, vr1025, c
1545       // The insert_subreg becomes a "copy" that defines a val# which can itself
1546       // be coalesced away.
1547       MachineInstr *DefMI = li_->getInstructionFromIndex(NextDef);
1548       if (DefMI->getOpcode() == TargetInstrInfo::INSERT_SUBREG)
1549         LR->valno->copy = DefMI;
1550     }
1551   }
1552
1553   // If resulting interval has a preference that no longer fits because of subreg
1554   // coalescing, just clear the preference.
1555   if (ResDstInt->preference && (isExtSubReg || isInsSubReg) &&
1556       TargetRegisterInfo::isVirtualRegister(ResDstInt->reg)) {
1557     const TargetRegisterClass *RC = mri_->getRegClass(ResDstInt->reg);
1558     if (!RC->contains(ResDstInt->preference))
1559       ResDstInt->preference = 0;
1560   }
1561
1562   DOUT << "\n\t\tJoined.  Result = "; ResDstInt->print(DOUT, tri_);
1563   DOUT << "\n";
1564
1565   ++numJoins;
1566   return true;
1567 }
1568
1569 /// ComputeUltimateVN - Assuming we are going to join two live intervals,
1570 /// compute what the resultant value numbers for each value in the input two
1571 /// ranges will be.  This is complicated by copies between the two which can
1572 /// and will commonly cause multiple value numbers to be merged into one.
1573 ///
1574 /// VN is the value number that we're trying to resolve.  InstDefiningValue
1575 /// keeps track of the new InstDefiningValue assignment for the result
1576 /// LiveInterval.  ThisFromOther/OtherFromThis are sets that keep track of
1577 /// whether a value in this or other is a copy from the opposite set.
1578 /// ThisValNoAssignments/OtherValNoAssignments keep track of value #'s that have
1579 /// already been assigned.
1580 ///
1581 /// ThisFromOther[x] - If x is defined as a copy from the other interval, this
1582 /// contains the value number the copy is from.
1583 ///
1584 static unsigned ComputeUltimateVN(VNInfo *VNI,
1585                                   SmallVector<VNInfo*, 16> &NewVNInfo,
1586                                   DenseMap<VNInfo*, VNInfo*> &ThisFromOther,
1587                                   DenseMap<VNInfo*, VNInfo*> &OtherFromThis,
1588                                   SmallVector<int, 16> &ThisValNoAssignments,
1589                                   SmallVector<int, 16> &OtherValNoAssignments) {
1590   unsigned VN = VNI->id;
1591
1592   // If the VN has already been computed, just return it.
1593   if (ThisValNoAssignments[VN] >= 0)
1594     return ThisValNoAssignments[VN];
1595 //  assert(ThisValNoAssignments[VN] != -2 && "Cyclic case?");
1596
1597   // If this val is not a copy from the other val, then it must be a new value
1598   // number in the destination.
1599   DenseMap<VNInfo*, VNInfo*>::iterator I = ThisFromOther.find(VNI);
1600   if (I == ThisFromOther.end()) {
1601     NewVNInfo.push_back(VNI);
1602     return ThisValNoAssignments[VN] = NewVNInfo.size()-1;
1603   }
1604   VNInfo *OtherValNo = I->second;
1605
1606   // Otherwise, this *is* a copy from the RHS.  If the other side has already
1607   // been computed, return it.
1608   if (OtherValNoAssignments[OtherValNo->id] >= 0)
1609     return ThisValNoAssignments[VN] = OtherValNoAssignments[OtherValNo->id];
1610   
1611   // Mark this value number as currently being computed, then ask what the
1612   // ultimate value # of the other value is.
1613   ThisValNoAssignments[VN] = -2;
1614   unsigned UltimateVN =
1615     ComputeUltimateVN(OtherValNo, NewVNInfo, OtherFromThis, ThisFromOther,
1616                       OtherValNoAssignments, ThisValNoAssignments);
1617   return ThisValNoAssignments[VN] = UltimateVN;
1618 }
1619
1620 static bool InVector(VNInfo *Val, const SmallVector<VNInfo*, 8> &V) {
1621   return std::find(V.begin(), V.end(), Val) != V.end();
1622 }
1623
1624 /// RangeIsDefinedByCopyFromReg - Return true if the specified live range of
1625 /// the specified live interval is defined by a copy from the specified
1626 /// register.
1627 bool SimpleRegisterCoalescing::RangeIsDefinedByCopyFromReg(LiveInterval &li,
1628                                                            LiveRange *LR,
1629                                                            unsigned Reg) {
1630   unsigned SrcReg = li_->getVNInfoSourceReg(LR->valno);
1631   if (SrcReg == Reg)
1632     return true;
1633   if (LR->valno->def == ~0U &&
1634       TargetRegisterInfo::isPhysicalRegister(li.reg) &&
1635       *tri_->getSuperRegisters(li.reg)) {
1636     // It's a sub-register live interval, we may not have precise information.
1637     // Re-compute it.
1638     MachineInstr *DefMI = li_->getInstructionFromIndex(LR->start);
1639     unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
1640     if (DefMI &&
1641         tii_->isMoveInstr(*DefMI, SrcReg, DstReg, SrcSubIdx, DstSubIdx) &&
1642         DstReg == li.reg && SrcReg == Reg) {
1643       // Cache computed info.
1644       LR->valno->def  = LR->start;
1645       LR->valno->copy = DefMI;
1646       return true;
1647     }
1648   }
1649   return false;
1650 }
1651
1652 /// SimpleJoin - Attempt to joint the specified interval into this one. The
1653 /// caller of this method must guarantee that the RHS only contains a single
1654 /// value number and that the RHS is not defined by a copy from this
1655 /// interval.  This returns false if the intervals are not joinable, or it
1656 /// joins them and returns true.
1657 bool SimpleRegisterCoalescing::SimpleJoin(LiveInterval &LHS, LiveInterval &RHS){
1658   assert(RHS.containsOneValue());
1659   
1660   // Some number (potentially more than one) value numbers in the current
1661   // interval may be defined as copies from the RHS.  Scan the overlapping
1662   // portions of the LHS and RHS, keeping track of this and looking for
1663   // overlapping live ranges that are NOT defined as copies.  If these exist, we
1664   // cannot coalesce.
1665   
1666   LiveInterval::iterator LHSIt = LHS.begin(), LHSEnd = LHS.end();
1667   LiveInterval::iterator RHSIt = RHS.begin(), RHSEnd = RHS.end();
1668   
1669   if (LHSIt->start < RHSIt->start) {
1670     LHSIt = std::upper_bound(LHSIt, LHSEnd, RHSIt->start);
1671     if (LHSIt != LHS.begin()) --LHSIt;
1672   } else if (RHSIt->start < LHSIt->start) {
1673     RHSIt = std::upper_bound(RHSIt, RHSEnd, LHSIt->start);
1674     if (RHSIt != RHS.begin()) --RHSIt;
1675   }
1676   
1677   SmallVector<VNInfo*, 8> EliminatedLHSVals;
1678   
1679   while (1) {
1680     // Determine if these live intervals overlap.
1681     bool Overlaps = false;
1682     if (LHSIt->start <= RHSIt->start)
1683       Overlaps = LHSIt->end > RHSIt->start;
1684     else
1685       Overlaps = RHSIt->end > LHSIt->start;
1686     
1687     // If the live intervals overlap, there are two interesting cases: if the
1688     // LHS interval is defined by a copy from the RHS, it's ok and we record
1689     // that the LHS value # is the same as the RHS.  If it's not, then we cannot
1690     // coalesce these live ranges and we bail out.
1691     if (Overlaps) {
1692       // If we haven't already recorded that this value # is safe, check it.
1693       if (!InVector(LHSIt->valno, EliminatedLHSVals)) {
1694         // Copy from the RHS?
1695         if (!RangeIsDefinedByCopyFromReg(LHS, LHSIt, RHS.reg))
1696           return false;    // Nope, bail out.
1697
1698         if (LHSIt->contains(RHSIt->valno->def))
1699           // Here is an interesting situation:
1700           // BB1:
1701           //   vr1025 = copy vr1024
1702           //   ..
1703           // BB2:
1704           //   vr1024 = op 
1705           //          = vr1025
1706           // Even though vr1025 is copied from vr1024, it's not safe to
1707           // coalesced them since live range of vr1025 intersects the
1708           // def of vr1024. This happens because vr1025 is assigned the
1709           // value of the previous iteration of vr1024.
1710           return false;
1711         EliminatedLHSVals.push_back(LHSIt->valno);
1712       }
1713       
1714       // We know this entire LHS live range is okay, so skip it now.
1715       if (++LHSIt == LHSEnd) break;
1716       continue;
1717     }
1718     
1719     if (LHSIt->end < RHSIt->end) {
1720       if (++LHSIt == LHSEnd) break;
1721     } else {
1722       // One interesting case to check here.  It's possible that we have
1723       // something like "X3 = Y" which defines a new value number in the LHS,
1724       // and is the last use of this liverange of the RHS.  In this case, we
1725       // want to notice this copy (so that it gets coalesced away) even though
1726       // the live ranges don't actually overlap.
1727       if (LHSIt->start == RHSIt->end) {
1728         if (InVector(LHSIt->valno, EliminatedLHSVals)) {
1729           // We already know that this value number is going to be merged in
1730           // if coalescing succeeds.  Just skip the liverange.
1731           if (++LHSIt == LHSEnd) break;
1732         } else {
1733           // Otherwise, if this is a copy from the RHS, mark it as being merged
1734           // in.
1735           if (RangeIsDefinedByCopyFromReg(LHS, LHSIt, RHS.reg)) {
1736             if (LHSIt->contains(RHSIt->valno->def))
1737               // Here is an interesting situation:
1738               // BB1:
1739               //   vr1025 = copy vr1024
1740               //   ..
1741               // BB2:
1742               //   vr1024 = op 
1743               //          = vr1025
1744               // Even though vr1025 is copied from vr1024, it's not safe to
1745               // coalesced them since live range of vr1025 intersects the
1746               // def of vr1024. This happens because vr1025 is assigned the
1747               // value of the previous iteration of vr1024.
1748               return false;
1749             EliminatedLHSVals.push_back(LHSIt->valno);
1750
1751             // We know this entire LHS live range is okay, so skip it now.
1752             if (++LHSIt == LHSEnd) break;
1753           }
1754         }
1755       }
1756       
1757       if (++RHSIt == RHSEnd) break;
1758     }
1759   }
1760   
1761   // If we got here, we know that the coalescing will be successful and that
1762   // the value numbers in EliminatedLHSVals will all be merged together.  Since
1763   // the most common case is that EliminatedLHSVals has a single number, we
1764   // optimize for it: if there is more than one value, we merge them all into
1765   // the lowest numbered one, then handle the interval as if we were merging
1766   // with one value number.
1767   VNInfo *LHSValNo = NULL;
1768   if (EliminatedLHSVals.size() > 1) {
1769     // Loop through all the equal value numbers merging them into the smallest
1770     // one.
1771     VNInfo *Smallest = EliminatedLHSVals[0];
1772     for (unsigned i = 1, e = EliminatedLHSVals.size(); i != e; ++i) {
1773       if (EliminatedLHSVals[i]->id < Smallest->id) {
1774         // Merge the current notion of the smallest into the smaller one.
1775         LHS.MergeValueNumberInto(Smallest, EliminatedLHSVals[i]);
1776         Smallest = EliminatedLHSVals[i];
1777       } else {
1778         // Merge into the smallest.
1779         LHS.MergeValueNumberInto(EliminatedLHSVals[i], Smallest);
1780       }
1781     }
1782     LHSValNo = Smallest;
1783   } else if (EliminatedLHSVals.empty()) {
1784     if (TargetRegisterInfo::isPhysicalRegister(LHS.reg) &&
1785         *tri_->getSuperRegisters(LHS.reg))
1786       // Imprecise sub-register information. Can't handle it.
1787       return false;
1788     assert(0 && "No copies from the RHS?");
1789   } else {
1790     LHSValNo = EliminatedLHSVals[0];
1791   }
1792   
1793   // Okay, now that there is a single LHS value number that we're merging the
1794   // RHS into, update the value number info for the LHS to indicate that the
1795   // value number is defined where the RHS value number was.
1796   const VNInfo *VNI = RHS.getValNumInfo(0);
1797   LHSValNo->def  = VNI->def;
1798   LHSValNo->copy = VNI->copy;
1799   
1800   // Okay, the final step is to loop over the RHS live intervals, adding them to
1801   // the LHS.
1802   LHSValNo->hasPHIKill |= VNI->hasPHIKill;
1803   LHS.addKills(LHSValNo, VNI->kills);
1804   LHS.MergeRangesInAsValue(RHS, LHSValNo);
1805   LHS.weight += RHS.weight;
1806   if (RHS.preference && !LHS.preference)
1807     LHS.preference = RHS.preference;
1808   
1809   return true;
1810 }
1811
1812 /// JoinIntervals - Attempt to join these two intervals.  On failure, this
1813 /// returns false.  Otherwise, if one of the intervals being joined is a
1814 /// physreg, this method always canonicalizes LHS to be it.  The output
1815 /// "RHS" will not have been modified, so we can use this information
1816 /// below to update aliases.
1817 bool
1818 SimpleRegisterCoalescing::JoinIntervals(LiveInterval &LHS, LiveInterval &RHS,
1819                                         bool &Swapped) {
1820   // Compute the final value assignment, assuming that the live ranges can be
1821   // coalesced.
1822   SmallVector<int, 16> LHSValNoAssignments;
1823   SmallVector<int, 16> RHSValNoAssignments;
1824   DenseMap<VNInfo*, VNInfo*> LHSValsDefinedFromRHS;
1825   DenseMap<VNInfo*, VNInfo*> RHSValsDefinedFromLHS;
1826   SmallVector<VNInfo*, 16> NewVNInfo;
1827
1828   // If a live interval is a physical register, conservatively check if any
1829   // of its sub-registers is overlapping the live interval of the virtual
1830   // register. If so, do not coalesce.
1831   if (TargetRegisterInfo::isPhysicalRegister(LHS.reg) &&
1832       *tri_->getSubRegisters(LHS.reg)) {
1833     // If it's coalescing a virtual register to a physical register, estimate
1834     // its live interval length. This is the *cost* of scanning an entire live
1835     // interval. If the cost is low, we'll do an exhaustive check instead.
1836
1837     // If this is something like this:
1838     // BB1:
1839     // v1024 = op
1840     // ...
1841     // BB2:
1842     // ...
1843     // RAX   = v1024
1844     //
1845     // That is, the live interval of v1024 crosses a bb. Then we can't rely on
1846     // less conservative check. It's possible a sub-register is defined before
1847     // v1024 (or live in) and live out of BB1.
1848     if (RHS.containsOneValue() &&
1849         li_->intervalIsInOneMBB(RHS) &&
1850         li_->getApproximateInstructionCount(RHS) <= 10) {
1851       // Perform a more exhaustive check for some common cases.
1852       if (li_->conflictsWithPhysRegRef(RHS, LHS.reg, true, JoinedCopies))
1853         return false;
1854     } else {
1855       for (const unsigned* SR = tri_->getSubRegisters(LHS.reg); *SR; ++SR)
1856         if (li_->hasInterval(*SR) && RHS.overlaps(li_->getInterval(*SR))) {
1857           DOUT << "Interfere with sub-register ";
1858           DEBUG(li_->getInterval(*SR).print(DOUT, tri_));
1859           return false;
1860         }
1861     }
1862   } else if (TargetRegisterInfo::isPhysicalRegister(RHS.reg) &&
1863              *tri_->getSubRegisters(RHS.reg)) {
1864     if (LHS.containsOneValue() &&
1865         li_->getApproximateInstructionCount(LHS) <= 10) {
1866       // Perform a more exhaustive check for some common cases.
1867       if (li_->conflictsWithPhysRegRef(LHS, RHS.reg, false, JoinedCopies))
1868         return false;
1869     } else {
1870       for (const unsigned* SR = tri_->getSubRegisters(RHS.reg); *SR; ++SR)
1871         if (li_->hasInterval(*SR) && LHS.overlaps(li_->getInterval(*SR))) {
1872           DOUT << "Interfere with sub-register ";
1873           DEBUG(li_->getInterval(*SR).print(DOUT, tri_));
1874           return false;
1875         }
1876     }
1877   }
1878                           
1879   // Compute ultimate value numbers for the LHS and RHS values.
1880   if (RHS.containsOneValue()) {
1881     // Copies from a liveinterval with a single value are simple to handle and
1882     // very common, handle the special case here.  This is important, because
1883     // often RHS is small and LHS is large (e.g. a physreg).
1884     
1885     // Find out if the RHS is defined as a copy from some value in the LHS.
1886     int RHSVal0DefinedFromLHS = -1;
1887     int RHSValID = -1;
1888     VNInfo *RHSValNoInfo = NULL;
1889     VNInfo *RHSValNoInfo0 = RHS.getValNumInfo(0);
1890     unsigned RHSSrcReg = li_->getVNInfoSourceReg(RHSValNoInfo0);
1891     if (RHSSrcReg == 0 || RHSSrcReg != LHS.reg) {
1892       // If RHS is not defined as a copy from the LHS, we can use simpler and
1893       // faster checks to see if the live ranges are coalescable.  This joiner
1894       // can't swap the LHS/RHS intervals though.
1895       if (!TargetRegisterInfo::isPhysicalRegister(RHS.reg)) {
1896         return SimpleJoin(LHS, RHS);
1897       } else {
1898         RHSValNoInfo = RHSValNoInfo0;
1899       }
1900     } else {
1901       // It was defined as a copy from the LHS, find out what value # it is.
1902       RHSValNoInfo = LHS.getLiveRangeContaining(RHSValNoInfo0->def-1)->valno;
1903       RHSValID = RHSValNoInfo->id;
1904       RHSVal0DefinedFromLHS = RHSValID;
1905     }
1906     
1907     LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
1908     RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
1909     NewVNInfo.resize(LHS.getNumValNums(), NULL);
1910     
1911     // Okay, *all* of the values in LHS that are defined as a copy from RHS
1912     // should now get updated.
1913     for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1914          i != e; ++i) {
1915       VNInfo *VNI = *i;
1916       unsigned VN = VNI->id;
1917       if (unsigned LHSSrcReg = li_->getVNInfoSourceReg(VNI)) {
1918         if (LHSSrcReg != RHS.reg) {
1919           // If this is not a copy from the RHS, its value number will be
1920           // unmodified by the coalescing.
1921           NewVNInfo[VN] = VNI;
1922           LHSValNoAssignments[VN] = VN;
1923         } else if (RHSValID == -1) {
1924           // Otherwise, it is a copy from the RHS, and we don't already have a
1925           // value# for it.  Keep the current value number, but remember it.
1926           LHSValNoAssignments[VN] = RHSValID = VN;
1927           NewVNInfo[VN] = RHSValNoInfo;
1928           LHSValsDefinedFromRHS[VNI] = RHSValNoInfo0;
1929         } else {
1930           // Otherwise, use the specified value #.
1931           LHSValNoAssignments[VN] = RHSValID;
1932           if (VN == (unsigned)RHSValID) {  // Else this val# is dead.
1933             NewVNInfo[VN] = RHSValNoInfo;
1934             LHSValsDefinedFromRHS[VNI] = RHSValNoInfo0;
1935           }
1936         }
1937       } else {
1938         NewVNInfo[VN] = VNI;
1939         LHSValNoAssignments[VN] = VN;
1940       }
1941     }
1942     
1943     assert(RHSValID != -1 && "Didn't find value #?");
1944     RHSValNoAssignments[0] = RHSValID;
1945     if (RHSVal0DefinedFromLHS != -1) {
1946       // This path doesn't go through ComputeUltimateVN so just set
1947       // it to anything.
1948       RHSValsDefinedFromLHS[RHSValNoInfo0] = (VNInfo*)1;
1949     }
1950   } else {
1951     // Loop over the value numbers of the LHS, seeing if any are defined from
1952     // the RHS.
1953     for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1954          i != e; ++i) {
1955       VNInfo *VNI = *i;
1956       if (VNI->def == ~1U || VNI->copy == 0)  // Src not defined by a copy?
1957         continue;
1958       
1959       // DstReg is known to be a register in the LHS interval.  If the src is
1960       // from the RHS interval, we can use its value #.
1961       if (li_->getVNInfoSourceReg(VNI) != RHS.reg)
1962         continue;
1963       
1964       // Figure out the value # from the RHS.
1965       LHSValsDefinedFromRHS[VNI]=RHS.getLiveRangeContaining(VNI->def-1)->valno;
1966     }
1967     
1968     // Loop over the value numbers of the RHS, seeing if any are defined from
1969     // the LHS.
1970     for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
1971          i != e; ++i) {
1972       VNInfo *VNI = *i;
1973       if (VNI->def == ~1U || VNI->copy == 0)  // Src not defined by a copy?
1974         continue;
1975       
1976       // DstReg is known to be a register in the RHS interval.  If the src is
1977       // from the LHS interval, we can use its value #.
1978       if (li_->getVNInfoSourceReg(VNI) != LHS.reg)
1979         continue;
1980       
1981       // Figure out the value # from the LHS.
1982       RHSValsDefinedFromLHS[VNI]=LHS.getLiveRangeContaining(VNI->def-1)->valno;
1983     }
1984     
1985     LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
1986     RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
1987     NewVNInfo.reserve(LHS.getNumValNums() + RHS.getNumValNums());
1988     
1989     for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1990          i != e; ++i) {
1991       VNInfo *VNI = *i;
1992       unsigned VN = VNI->id;
1993       if (LHSValNoAssignments[VN] >= 0 || VNI->def == ~1U) 
1994         continue;
1995       ComputeUltimateVN(VNI, NewVNInfo,
1996                         LHSValsDefinedFromRHS, RHSValsDefinedFromLHS,
1997                         LHSValNoAssignments, RHSValNoAssignments);
1998     }
1999     for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
2000          i != e; ++i) {
2001       VNInfo *VNI = *i;
2002       unsigned VN = VNI->id;
2003       if (RHSValNoAssignments[VN] >= 0 || VNI->def == ~1U)
2004         continue;
2005       // If this value number isn't a copy from the LHS, it's a new number.
2006       if (RHSValsDefinedFromLHS.find(VNI) == RHSValsDefinedFromLHS.end()) {
2007         NewVNInfo.push_back(VNI);
2008         RHSValNoAssignments[VN] = NewVNInfo.size()-1;
2009         continue;
2010       }
2011       
2012       ComputeUltimateVN(VNI, NewVNInfo,
2013                         RHSValsDefinedFromLHS, LHSValsDefinedFromRHS,
2014                         RHSValNoAssignments, LHSValNoAssignments);
2015     }
2016   }
2017   
2018   // Armed with the mappings of LHS/RHS values to ultimate values, walk the
2019   // interval lists to see if these intervals are coalescable.
2020   LiveInterval::const_iterator I = LHS.begin();
2021   LiveInterval::const_iterator IE = LHS.end();
2022   LiveInterval::const_iterator J = RHS.begin();
2023   LiveInterval::const_iterator JE = RHS.end();
2024   
2025   // Skip ahead until the first place of potential sharing.
2026   if (I->start < J->start) {
2027     I = std::upper_bound(I, IE, J->start);
2028     if (I != LHS.begin()) --I;
2029   } else if (J->start < I->start) {
2030     J = std::upper_bound(J, JE, I->start);
2031     if (J != RHS.begin()) --J;
2032   }
2033   
2034   while (1) {
2035     // Determine if these two live ranges overlap.
2036     bool Overlaps;
2037     if (I->start < J->start) {
2038       Overlaps = I->end > J->start;
2039     } else {
2040       Overlaps = J->end > I->start;
2041     }
2042
2043     // If so, check value # info to determine if they are really different.
2044     if (Overlaps) {
2045       // If the live range overlap will map to the same value number in the
2046       // result liverange, we can still coalesce them.  If not, we can't.
2047       if (LHSValNoAssignments[I->valno->id] !=
2048           RHSValNoAssignments[J->valno->id])
2049         return false;
2050     }
2051     
2052     if (I->end < J->end) {
2053       ++I;
2054       if (I == IE) break;
2055     } else {
2056       ++J;
2057       if (J == JE) break;
2058     }
2059   }
2060
2061   // Update kill info. Some live ranges are extended due to copy coalescing.
2062   for (DenseMap<VNInfo*, VNInfo*>::iterator I = LHSValsDefinedFromRHS.begin(),
2063          E = LHSValsDefinedFromRHS.end(); I != E; ++I) {
2064     VNInfo *VNI = I->first;
2065     unsigned LHSValID = LHSValNoAssignments[VNI->id];
2066     LiveInterval::removeKill(NewVNInfo[LHSValID], VNI->def);
2067     NewVNInfo[LHSValID]->hasPHIKill |= VNI->hasPHIKill;
2068     RHS.addKills(NewVNInfo[LHSValID], VNI->kills);
2069   }
2070
2071   // Update kill info. Some live ranges are extended due to copy coalescing.
2072   for (DenseMap<VNInfo*, VNInfo*>::iterator I = RHSValsDefinedFromLHS.begin(),
2073          E = RHSValsDefinedFromLHS.end(); I != E; ++I) {
2074     VNInfo *VNI = I->first;
2075     unsigned RHSValID = RHSValNoAssignments[VNI->id];
2076     LiveInterval::removeKill(NewVNInfo[RHSValID], VNI->def);
2077     NewVNInfo[RHSValID]->hasPHIKill |= VNI->hasPHIKill;
2078     LHS.addKills(NewVNInfo[RHSValID], VNI->kills);
2079   }
2080
2081   // If we get here, we know that we can coalesce the live ranges.  Ask the
2082   // intervals to coalesce themselves now.
2083   if ((RHS.ranges.size() > LHS.ranges.size() &&
2084       TargetRegisterInfo::isVirtualRegister(LHS.reg)) ||
2085       TargetRegisterInfo::isPhysicalRegister(RHS.reg)) {
2086     RHS.join(LHS, &RHSValNoAssignments[0], &LHSValNoAssignments[0], NewVNInfo);
2087     Swapped = true;
2088   } else {
2089     LHS.join(RHS, &LHSValNoAssignments[0], &RHSValNoAssignments[0], NewVNInfo);
2090     Swapped = false;
2091   }
2092   return true;
2093 }
2094
2095 namespace {
2096   // DepthMBBCompare - Comparison predicate that sort first based on the loop
2097   // depth of the basic block (the unsigned), and then on the MBB number.
2098   struct DepthMBBCompare {
2099     typedef std::pair<unsigned, MachineBasicBlock*> DepthMBBPair;
2100     bool operator()(const DepthMBBPair &LHS, const DepthMBBPair &RHS) const {
2101       if (LHS.first > RHS.first) return true;   // Deeper loops first
2102       return LHS.first == RHS.first &&
2103         LHS.second->getNumber() < RHS.second->getNumber();
2104     }
2105   };
2106 }
2107
2108 /// getRepIntervalSize - Returns the size of the interval that represents the
2109 /// specified register.
2110 template<class SF>
2111 unsigned JoinPriorityQueue<SF>::getRepIntervalSize(unsigned Reg) {
2112   return Rc->getRepIntervalSize(Reg);
2113 }
2114
2115 /// CopyRecSort::operator - Join priority queue sorting function.
2116 ///
2117 bool CopyRecSort::operator()(CopyRec left, CopyRec right) const {
2118   // Inner loops first.
2119   if (left.LoopDepth > right.LoopDepth)
2120     return false;
2121   else if (left.LoopDepth == right.LoopDepth)
2122     if (left.isBackEdge && !right.isBackEdge)
2123       return false;
2124   return true;
2125 }
2126
2127 void SimpleRegisterCoalescing::CopyCoalesceInMBB(MachineBasicBlock *MBB,
2128                                                std::vector<CopyRec> &TryAgain) {
2129   DOUT << ((Value*)MBB->getBasicBlock())->getName() << ":\n";
2130
2131   std::vector<CopyRec> VirtCopies;
2132   std::vector<CopyRec> PhysCopies;
2133   std::vector<CopyRec> ImpDefCopies;
2134   unsigned LoopDepth = loopInfo->getLoopDepth(MBB);
2135   for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end();
2136        MII != E;) {
2137     MachineInstr *Inst = MII++;
2138     
2139     // If this isn't a copy nor a extract_subreg, we can't join intervals.
2140     unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
2141     if (Inst->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG) {
2142       DstReg = Inst->getOperand(0).getReg();
2143       SrcReg = Inst->getOperand(1).getReg();
2144     } else if (Inst->getOpcode() == TargetInstrInfo::INSERT_SUBREG) {
2145       DstReg = Inst->getOperand(0).getReg();
2146       SrcReg = Inst->getOperand(2).getReg();
2147     } else if (!tii_->isMoveInstr(*Inst, SrcReg, DstReg, SrcSubIdx, DstSubIdx))
2148       continue;
2149
2150     bool SrcIsPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
2151     bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
2152     if (NewHeuristic) {
2153       JoinQueue->push(CopyRec(Inst, LoopDepth, isBackEdgeCopy(Inst, DstReg)));
2154     } else {
2155       if (li_->hasInterval(SrcReg) && li_->getInterval(SrcReg).empty())
2156         ImpDefCopies.push_back(CopyRec(Inst, 0, false));
2157       else if (SrcIsPhys || DstIsPhys)
2158         PhysCopies.push_back(CopyRec(Inst, 0, false));
2159       else
2160         VirtCopies.push_back(CopyRec(Inst, 0, false));
2161     }
2162   }
2163
2164   if (NewHeuristic)
2165     return;
2166
2167   // Try coalescing implicit copies first, followed by copies to / from
2168   // physical registers, then finally copies from virtual registers to
2169   // virtual registers.
2170   for (unsigned i = 0, e = ImpDefCopies.size(); i != e; ++i) {
2171     CopyRec &TheCopy = ImpDefCopies[i];
2172     bool Again = false;
2173     if (!JoinCopy(TheCopy, Again))
2174       if (Again)
2175         TryAgain.push_back(TheCopy);
2176   }
2177   for (unsigned i = 0, e = PhysCopies.size(); i != e; ++i) {
2178     CopyRec &TheCopy = PhysCopies[i];
2179     bool Again = false;
2180     if (!JoinCopy(TheCopy, Again))
2181       if (Again)
2182         TryAgain.push_back(TheCopy);
2183   }
2184   for (unsigned i = 0, e = VirtCopies.size(); i != e; ++i) {
2185     CopyRec &TheCopy = VirtCopies[i];
2186     bool Again = false;
2187     if (!JoinCopy(TheCopy, Again))
2188       if (Again)
2189         TryAgain.push_back(TheCopy);
2190   }
2191 }
2192
2193 void SimpleRegisterCoalescing::joinIntervals() {
2194   DOUT << "********** JOINING INTERVALS ***********\n";
2195
2196   if (NewHeuristic)
2197     JoinQueue = new JoinPriorityQueue<CopyRecSort>(this);
2198
2199   std::vector<CopyRec> TryAgainList;
2200   if (loopInfo->empty()) {
2201     // If there are no loops in the function, join intervals in function order.
2202     for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();
2203          I != E; ++I)
2204       CopyCoalesceInMBB(I, TryAgainList);
2205   } else {
2206     // Otherwise, join intervals in inner loops before other intervals.
2207     // Unfortunately we can't just iterate over loop hierarchy here because
2208     // there may be more MBB's than BB's.  Collect MBB's for sorting.
2209
2210     // Join intervals in the function prolog first. We want to join physical
2211     // registers with virtual registers before the intervals got too long.
2212     std::vector<std::pair<unsigned, MachineBasicBlock*> > MBBs;
2213     for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();I != E;++I){
2214       MachineBasicBlock *MBB = I;
2215       MBBs.push_back(std::make_pair(loopInfo->getLoopDepth(MBB), I));
2216     }
2217
2218     // Sort by loop depth.
2219     std::sort(MBBs.begin(), MBBs.end(), DepthMBBCompare());
2220
2221     // Finally, join intervals in loop nest order.
2222     for (unsigned i = 0, e = MBBs.size(); i != e; ++i)
2223       CopyCoalesceInMBB(MBBs[i].second, TryAgainList);
2224   }
2225   
2226   // Joining intervals can allow other intervals to be joined.  Iteratively join
2227   // until we make no progress.
2228   if (NewHeuristic) {
2229     SmallVector<CopyRec, 16> TryAgain;
2230     bool ProgressMade = true;
2231     while (ProgressMade) {
2232       ProgressMade = false;
2233       while (!JoinQueue->empty()) {
2234         CopyRec R = JoinQueue->pop();
2235         bool Again = false;
2236         bool Success = JoinCopy(R, Again);
2237         if (Success)
2238           ProgressMade = true;
2239         else if (Again)
2240           TryAgain.push_back(R);
2241       }
2242
2243       if (ProgressMade) {
2244         while (!TryAgain.empty()) {
2245           JoinQueue->push(TryAgain.back());
2246           TryAgain.pop_back();
2247         }
2248       }
2249     }
2250   } else {
2251     bool ProgressMade = true;
2252     while (ProgressMade) {
2253       ProgressMade = false;
2254
2255       for (unsigned i = 0, e = TryAgainList.size(); i != e; ++i) {
2256         CopyRec &TheCopy = TryAgainList[i];
2257         if (TheCopy.MI) {
2258           bool Again = false;
2259           bool Success = JoinCopy(TheCopy, Again);
2260           if (Success || !Again) {
2261             TheCopy.MI = 0;   // Mark this one as done.
2262             ProgressMade = true;
2263           }
2264         }
2265       }
2266     }
2267   }
2268
2269   if (NewHeuristic)
2270     delete JoinQueue;  
2271 }
2272
2273 /// Return true if the two specified registers belong to different register
2274 /// classes.  The registers may be either phys or virt regs.
2275 bool
2276 SimpleRegisterCoalescing::differingRegisterClasses(unsigned RegA,
2277                                                    unsigned RegB) const {
2278   // Get the register classes for the first reg.
2279   if (TargetRegisterInfo::isPhysicalRegister(RegA)) {
2280     assert(TargetRegisterInfo::isVirtualRegister(RegB) &&
2281            "Shouldn't consider two physregs!");
2282     return !mri_->getRegClass(RegB)->contains(RegA);
2283   }
2284
2285   // Compare against the regclass for the second reg.
2286   const TargetRegisterClass *RegClassA = mri_->getRegClass(RegA);
2287   if (TargetRegisterInfo::isVirtualRegister(RegB)) {
2288     const TargetRegisterClass *RegClassB = mri_->getRegClass(RegB);
2289     return RegClassA != RegClassB;
2290   }
2291   return !RegClassA->contains(RegB);
2292 }
2293
2294 /// lastRegisterUse - Returns the last use of the specific register between
2295 /// cycles Start and End or NULL if there are no uses.
2296 MachineOperand *
2297 SimpleRegisterCoalescing::lastRegisterUse(unsigned Start, unsigned End,
2298                                           unsigned Reg, unsigned &UseIdx) const{
2299   UseIdx = 0;
2300   if (TargetRegisterInfo::isVirtualRegister(Reg)) {
2301     MachineOperand *LastUse = NULL;
2302     for (MachineRegisterInfo::use_iterator I = mri_->use_begin(Reg),
2303            E = mri_->use_end(); I != E; ++I) {
2304       MachineOperand &Use = I.getOperand();
2305       MachineInstr *UseMI = Use.getParent();
2306       unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
2307       if (tii_->isMoveInstr(*UseMI, SrcReg, DstReg, SrcSubIdx, DstSubIdx) &&
2308           SrcReg == DstReg)
2309         // Ignore identity copies.
2310         continue;
2311       unsigned Idx = li_->getInstructionIndex(UseMI);
2312       if (Idx >= Start && Idx < End && Idx >= UseIdx) {
2313         LastUse = &Use;
2314         UseIdx = Idx;
2315       }
2316     }
2317     return LastUse;
2318   }
2319
2320   int e = (End-1) / InstrSlots::NUM * InstrSlots::NUM;
2321   int s = Start;
2322   while (e >= s) {
2323     // Skip deleted instructions
2324     MachineInstr *MI = li_->getInstructionFromIndex(e);
2325     while ((e - InstrSlots::NUM) >= s && !MI) {
2326       e -= InstrSlots::NUM;
2327       MI = li_->getInstructionFromIndex(e);
2328     }
2329     if (e < s || MI == NULL)
2330       return NULL;
2331
2332     // Ignore identity copies.
2333     unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
2334     if (!(tii_->isMoveInstr(*MI, SrcReg, DstReg, SrcSubIdx, DstSubIdx) &&
2335           SrcReg == DstReg))
2336       for (unsigned i = 0, NumOps = MI->getNumOperands(); i != NumOps; ++i) {
2337         MachineOperand &Use = MI->getOperand(i);
2338         if (Use.isReg() && Use.isUse() && Use.getReg() &&
2339             tri_->regsOverlap(Use.getReg(), Reg)) {
2340           UseIdx = e;
2341           return &Use;
2342         }
2343       }
2344
2345     e -= InstrSlots::NUM;
2346   }
2347
2348   return NULL;
2349 }
2350
2351
2352 void SimpleRegisterCoalescing::printRegName(unsigned reg) const {
2353   if (TargetRegisterInfo::isPhysicalRegister(reg))
2354     cerr << tri_->getName(reg);
2355   else
2356     cerr << "%reg" << reg;
2357 }
2358
2359 void SimpleRegisterCoalescing::releaseMemory() {
2360   JoinedCopies.clear();
2361   ReMatCopies.clear();
2362   ReMatDefs.clear();
2363 }
2364
2365 static bool isZeroLengthInterval(LiveInterval *li) {
2366   for (LiveInterval::Ranges::const_iterator
2367          i = li->ranges.begin(), e = li->ranges.end(); i != e; ++i)
2368     if (i->end - i->start > LiveIntervals::InstrSlots::NUM)
2369       return false;
2370   return true;
2371 }
2372
2373 /// TurnCopyIntoImpDef - If source of the specified copy is an implicit def,
2374 /// turn the copy into an implicit def.
2375 bool
2376 SimpleRegisterCoalescing::TurnCopyIntoImpDef(MachineBasicBlock::iterator &I,
2377                                              MachineBasicBlock *MBB,
2378                                              unsigned DstReg, unsigned SrcReg) {
2379   MachineInstr *CopyMI = &*I;
2380   unsigned CopyIdx = li_->getDefIndex(li_->getInstructionIndex(CopyMI));
2381   if (!li_->hasInterval(SrcReg))
2382     return false;
2383   LiveInterval &SrcInt = li_->getInterval(SrcReg);
2384   if (!SrcInt.empty())
2385     return false;
2386   if (!li_->hasInterval(DstReg))
2387     return false;
2388   LiveInterval &DstInt = li_->getInterval(DstReg);
2389   const LiveRange *DstLR = DstInt.getLiveRangeContaining(CopyIdx);
2390   DstInt.removeValNo(DstLR->valno);
2391   CopyMI->setDesc(tii_->get(TargetInstrInfo::IMPLICIT_DEF));
2392   for (int i = CopyMI->getNumOperands() - 1, e = 0; i > e; --i)
2393     CopyMI->RemoveOperand(i);
2394   bool NoUse = mri_->use_empty(SrcReg);
2395   if (NoUse) {
2396     for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(SrcReg),
2397            E = mri_->reg_end(); I != E; ) {
2398       assert(I.getOperand().isDef());
2399       MachineInstr *DefMI = &*I;
2400       ++I;
2401       // The implicit_def source has no other uses, delete it.
2402       assert(DefMI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF);
2403       li_->RemoveMachineInstrFromMaps(DefMI);
2404       DefMI->eraseFromParent();
2405     }
2406   }
2407   ++I;
2408   return true;
2409 }
2410
2411
2412 bool SimpleRegisterCoalescing::runOnMachineFunction(MachineFunction &fn) {
2413   mf_ = &fn;
2414   mri_ = &fn.getRegInfo();
2415   tm_ = &fn.getTarget();
2416   tri_ = tm_->getRegisterInfo();
2417   tii_ = tm_->getInstrInfo();
2418   li_ = &getAnalysis<LiveIntervals>();
2419   loopInfo = &getAnalysis<MachineLoopInfo>();
2420
2421   DOUT << "********** SIMPLE REGISTER COALESCING **********\n"
2422        << "********** Function: "
2423        << ((Value*)mf_->getFunction())->getName() << '\n';
2424
2425   allocatableRegs_ = tri_->getAllocatableSet(fn);
2426   for (TargetRegisterInfo::regclass_iterator I = tri_->regclass_begin(),
2427          E = tri_->regclass_end(); I != E; ++I)
2428     allocatableRCRegs_.insert(std::make_pair(*I,
2429                                              tri_->getAllocatableSet(fn, *I)));
2430
2431   // Join (coalesce) intervals if requested.
2432   if (EnableJoining) {
2433     joinIntervals();
2434     DEBUG({
2435         DOUT << "********** INTERVALS POST JOINING **********\n";
2436         for (LiveIntervals::iterator I = li_->begin(), E = li_->end(); I != E; ++I){
2437           I->second->print(DOUT, tri_);
2438           DOUT << "\n";
2439         }
2440       });
2441   }
2442
2443   // Perform a final pass over the instructions and compute spill weights
2444   // and remove identity moves.
2445   SmallVector<unsigned, 4> DeadDefs;
2446   for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
2447        mbbi != mbbe; ++mbbi) {
2448     MachineBasicBlock* mbb = mbbi;
2449     unsigned loopDepth = loopInfo->getLoopDepth(mbb);
2450
2451     for (MachineBasicBlock::iterator mii = mbb->begin(), mie = mbb->end();
2452          mii != mie; ) {
2453       MachineInstr *MI = mii;
2454       unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
2455       if (JoinedCopies.count(MI)) {
2456         // Delete all coalesced copies.
2457         if (!tii_->isMoveInstr(*MI, SrcReg, DstReg, SrcSubIdx, DstSubIdx)) {
2458           assert((MI->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG ||
2459                   MI->getOpcode() == TargetInstrInfo::INSERT_SUBREG) &&
2460                  "Unrecognized copy instruction");
2461           DstReg = MI->getOperand(0).getReg();
2462         }
2463         if (MI->registerDefIsDead(DstReg)) {
2464           LiveInterval &li = li_->getInterval(DstReg);
2465           if (!ShortenDeadCopySrcLiveRange(li, MI))
2466             ShortenDeadCopyLiveRange(li, MI);
2467         }
2468         li_->RemoveMachineInstrFromMaps(MI);
2469         mii = mbbi->erase(mii);
2470         ++numPeep;
2471         continue;
2472       }
2473
2474       // Now check if this is a remat'ed def instruction which is now dead.
2475       if (ReMatDefs.count(MI)) {
2476         bool isDead = true;
2477         for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
2478           const MachineOperand &MO = MI->getOperand(i);
2479           if (!MO.isReg())
2480             continue;
2481           unsigned Reg = MO.getReg();
2482           if (!Reg)
2483             continue;
2484           if (TargetRegisterInfo::isVirtualRegister(Reg))
2485             DeadDefs.push_back(Reg);
2486           if (MO.isDead())
2487             continue;
2488           if (TargetRegisterInfo::isPhysicalRegister(Reg) ||
2489               !mri_->use_empty(Reg)) {
2490             isDead = false;
2491             break;
2492           }
2493         }
2494         if (isDead) {
2495           while (!DeadDefs.empty()) {
2496             unsigned DeadDef = DeadDefs.back();
2497             DeadDefs.pop_back();
2498             RemoveDeadDef(li_->getInterval(DeadDef), MI);
2499           }
2500           li_->RemoveMachineInstrFromMaps(mii);
2501           mii = mbbi->erase(mii);
2502           continue;
2503         } else
2504           DeadDefs.clear();
2505       }
2506
2507       // If the move will be an identity move delete it
2508       bool isMove= tii_->isMoveInstr(*MI, SrcReg, DstReg, SrcSubIdx, DstSubIdx);
2509       if (isMove && SrcReg == DstReg) {
2510         if (li_->hasInterval(SrcReg)) {
2511           LiveInterval &RegInt = li_->getInterval(SrcReg);
2512           // If def of this move instruction is dead, remove its live range
2513           // from the dstination register's live interval.
2514           if (MI->registerDefIsDead(DstReg)) {
2515             if (!ShortenDeadCopySrcLiveRange(RegInt, MI))
2516               ShortenDeadCopyLiveRange(RegInt, MI);
2517           }
2518         }
2519         li_->RemoveMachineInstrFromMaps(MI);
2520         mii = mbbi->erase(mii);
2521         ++numPeep;
2522       } else if (!isMove || !TurnCopyIntoImpDef(mii, mbb, DstReg, SrcReg)) {
2523         SmallSet<unsigned, 4> UniqueUses;
2524         for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
2525           const MachineOperand &mop = MI->getOperand(i);
2526           if (mop.isReg() && mop.getReg() &&
2527               TargetRegisterInfo::isVirtualRegister(mop.getReg())) {
2528             unsigned reg = mop.getReg();
2529             // Multiple uses of reg by the same instruction. It should not
2530             // contribute to spill weight again.
2531             if (UniqueUses.count(reg) != 0)
2532               continue;
2533             LiveInterval &RegInt = li_->getInterval(reg);
2534             RegInt.weight +=
2535               li_->getSpillWeight(mop.isDef(), mop.isUse(), loopDepth);
2536             UniqueUses.insert(reg);
2537           }
2538         }
2539         ++mii;
2540       }
2541     }
2542   }
2543
2544   for (LiveIntervals::iterator I = li_->begin(), E = li_->end(); I != E; ++I) {
2545     LiveInterval &LI = *I->second;
2546     if (TargetRegisterInfo::isVirtualRegister(LI.reg)) {
2547       // If the live interval length is essentially zero, i.e. in every live
2548       // range the use follows def immediately, it doesn't make sense to spill
2549       // it and hope it will be easier to allocate for this li.
2550       if (isZeroLengthInterval(&LI))
2551         LI.weight = HUGE_VALF;
2552       else {
2553         bool isLoad = false;
2554         SmallVector<LiveInterval*, 4> SpillIs;
2555         if (li_->isReMaterializable(LI, SpillIs, isLoad)) {
2556           // If all of the definitions of the interval are re-materializable,
2557           // it is a preferred candidate for spilling. If non of the defs are
2558           // loads, then it's potentially very cheap to re-materialize.
2559           // FIXME: this gets much more complicated once we support non-trivial
2560           // re-materialization.
2561           if (isLoad)
2562             LI.weight *= 0.9F;
2563           else
2564             LI.weight *= 0.5F;
2565         }
2566       }
2567
2568       // Slightly prefer live interval that has been assigned a preferred reg.
2569       if (LI.preference)
2570         LI.weight *= 1.01F;
2571
2572       // Divide the weight of the interval by its size.  This encourages 
2573       // spilling of intervals that are large and have few uses, and
2574       // discourages spilling of small intervals with many uses.
2575       LI.weight /= li_->getApproximateInstructionCount(LI) * InstrSlots::NUM;
2576     }
2577   }
2578
2579   DEBUG(dump());
2580   return true;
2581 }
2582
2583 /// print - Implement the dump method.
2584 void SimpleRegisterCoalescing::print(std::ostream &O, const Module* m) const {
2585    li_->print(O, m);
2586 }
2587
2588 RegisterCoalescer* llvm::createSimpleRegisterCoalescer() {
2589   return new SimpleRegisterCoalescing();
2590 }
2591
2592 // Make sure that anything that uses RegisterCoalescer pulls in this file...
2593 DEFINING_FILE_FOR(SimpleRegisterCoalescing)