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