6326edab3490fd3824d7cade29efbb7cec5020b6
[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/LiveVariables.h"
21 #include "llvm/CodeGen/MachineFrameInfo.h"
22 #include "llvm/CodeGen/MachineInstr.h"
23 #include "llvm/CodeGen/MachineLoopInfo.h"
24 #include "llvm/CodeGen/MachineRegisterInfo.h"
25 #include "llvm/CodeGen/Passes.h"
26 #include "llvm/CodeGen/RegisterCoalescer.h"
27 #include "llvm/Target/TargetInstrInfo.h"
28 #include "llvm/Target/TargetMachine.h"
29 #include "llvm/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(numCommutes , "Number of instruction commuting performed");
40 STATISTIC(numExtends  , "Number of copies extended");
41 STATISTIC(numPeep     , "Number of identity moves eliminated after coalescing");
42 STATISTIC(numAborts   , "Number of times interval joining aborted");
43
44 char SimpleRegisterCoalescing::ID = 0;
45 namespace {
46   static cl::opt<bool>
47   EnableJoining("join-liveintervals",
48                 cl::desc("Coalesce copies (default=true)"),
49                 cl::init(true));
50
51   static cl::opt<bool>
52   NewHeuristic("new-coalescer-heuristic",
53                 cl::desc("Use new coalescer heuristic"),
54                 cl::init(false));
55
56   RegisterPass<SimpleRegisterCoalescing> 
57   X("simple-register-coalescing", "Simple Register Coalescing");
58
59   // Declare that we implement the RegisterCoalescer interface
60   RegisterAnalysisGroup<RegisterCoalescer, true/*The Default*/> V(X);
61 }
62
63 const PassInfo *llvm::SimpleRegisterCoalescingID = X.getPassInfo();
64
65 void SimpleRegisterCoalescing::getAnalysisUsage(AnalysisUsage &AU) const {
66   AU.addPreserved<LiveIntervals>();
67   AU.addPreserved<MachineLoopInfo>();
68   AU.addPreservedID(MachineDominatorsID);
69   AU.addPreservedID(PHIEliminationID);
70   AU.addPreservedID(TwoAddressInstructionPassID);
71   AU.addRequired<LiveVariables>();
72   AU.addRequired<LiveIntervals>();
73   AU.addRequired<MachineLoopInfo>();
74   MachineFunctionPass::getAnalysisUsage(AU);
75 }
76
77 /// AdjustCopiesBackFrom - We found a non-trivially-coalescable copy with IntA
78 /// being the source and IntB being the dest, thus this defines a value number
79 /// in IntB.  If the source value number (in IntA) is defined by a copy from B,
80 /// see if we can merge these two pieces of B into a single value number,
81 /// eliminating a copy.  For example:
82 ///
83 ///  A3 = B0
84 ///    ...
85 ///  B1 = A3      <- this copy
86 ///
87 /// In this case, B0 can be extended to where the B1 copy lives, allowing the B1
88 /// value number to be replaced with B0 (which simplifies the B liveinterval).
89 ///
90 /// This returns true if an interval was modified.
91 ///
92 bool SimpleRegisterCoalescing::AdjustCopiesBackFrom(LiveInterval &IntA,
93                                                     LiveInterval &IntB,
94                                                     MachineInstr *CopyMI) {
95   unsigned CopyIdx = li_->getDefIndex(li_->getInstructionIndex(CopyMI));
96
97   // BValNo is a value number in B that is defined by a copy from A.  'B3' in
98   // the example above.
99   LiveInterval::iterator BLR = IntB.FindLiveRangeContaining(CopyIdx);
100   VNInfo *BValNo = BLR->valno;
101   
102   // Get the location that B is defined at.  Two options: either this value has
103   // an unknown definition point or it is defined at CopyIdx.  If unknown, we 
104   // can't process it.
105   if (!BValNo->copy) return false;
106   assert(BValNo->def == CopyIdx && "Copy doesn't define the value?");
107   
108   // AValNo is the value number in A that defines the copy, A3 in the example.
109   LiveInterval::iterator ALR = IntA.FindLiveRangeContaining(CopyIdx-1);
110   VNInfo *AValNo = ALR->valno;
111   
112   // If AValNo is defined as a copy from IntB, we can potentially process this.  
113   // Get the instruction that defines this value number.
114   unsigned SrcReg = li_->getVNInfoSourceReg(AValNo);
115   if (!SrcReg) return false;  // Not defined by a copy.
116     
117   // If the value number is not defined by a copy instruction, ignore it.
118
119   // If the source register comes from an interval other than IntB, we can't
120   // handle this.
121   if (SrcReg != IntB.reg) return false;
122   
123   // Get the LiveRange in IntB that this value number starts with.
124   LiveInterval::iterator ValLR = IntB.FindLiveRangeContaining(AValNo->def-1);
125   
126   // Make sure that the end of the live range is inside the same block as
127   // CopyMI.
128   MachineInstr *ValLREndInst = li_->getInstructionFromIndex(ValLR->end-1);
129   if (!ValLREndInst || 
130       ValLREndInst->getParent() != CopyMI->getParent()) return false;
131
132   // Okay, we now know that ValLR ends in the same block that the CopyMI
133   // live-range starts.  If there are no intervening live ranges between them in
134   // IntB, we can merge them.
135   if (ValLR+1 != BLR) return false;
136
137   // If a live interval is a physical register, conservatively check if any
138   // of its sub-registers is overlapping the live interval of the virtual
139   // register. If so, do not coalesce.
140   if (TargetRegisterInfo::isPhysicalRegister(IntB.reg) &&
141       *tri_->getSubRegisters(IntB.reg)) {
142     for (const unsigned* SR = tri_->getSubRegisters(IntB.reg); *SR; ++SR)
143       if (li_->hasInterval(*SR) && IntA.overlaps(li_->getInterval(*SR))) {
144         DOUT << "Interfere with sub-register ";
145         DEBUG(li_->getInterval(*SR).print(DOUT, tri_));
146         return false;
147       }
148   }
149   
150   DOUT << "\nExtending: "; IntB.print(DOUT, tri_);
151   
152   unsigned FillerStart = ValLR->end, FillerEnd = BLR->start;
153   // We are about to delete CopyMI, so need to remove it as the 'instruction
154   // that defines this value #'. Update the the valnum with the new defining
155   // instruction #.
156   BValNo->def  = FillerStart;
157   BValNo->copy = NULL;
158   
159   // Okay, we can merge them.  We need to insert a new liverange:
160   // [ValLR.end, BLR.begin) of either value number, then we merge the
161   // two value numbers.
162   IntB.addRange(LiveRange(FillerStart, FillerEnd, BValNo));
163
164   // If the IntB live range is assigned to a physical register, and if that
165   // physreg has aliases, 
166   if (TargetRegisterInfo::isPhysicalRegister(IntB.reg)) {
167     // Update the liveintervals of sub-registers.
168     for (const unsigned *AS = tri_->getSubRegisters(IntB.reg); *AS; ++AS) {
169       LiveInterval &AliasLI = li_->getInterval(*AS);
170       AliasLI.addRange(LiveRange(FillerStart, FillerEnd,
171               AliasLI.getNextValue(FillerStart, 0, li_->getVNInfoAllocator())));
172     }
173   }
174
175   // Okay, merge "B1" into the same value number as "B0".
176   if (BValNo != ValLR->valno)
177     IntB.MergeValueNumberInto(BValNo, ValLR->valno);
178   DOUT << "   result = "; IntB.print(DOUT, tri_);
179   DOUT << "\n";
180
181   // If the source instruction was killing the source register before the
182   // merge, unset the isKill marker given the live range has been extended.
183   int UIdx = ValLREndInst->findRegisterUseOperandIdx(IntB.reg, true);
184   if (UIdx != -1)
185     ValLREndInst->getOperand(UIdx).setIsKill(false);
186
187   ++numExtends;
188   return true;
189 }
190
191 /// HasOtherReachingDefs - Return true if there are definitions of IntB
192 /// other than BValNo val# that can reach uses of AValno val# of IntA.
193 bool SimpleRegisterCoalescing::HasOtherReachingDefs(LiveInterval &IntA,
194                                                     LiveInterval &IntB,
195                                                     VNInfo *AValNo,
196                                                     VNInfo *BValNo) {
197   for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
198        AI != AE; ++AI) {
199     if (AI->valno != AValNo) continue;
200     LiveInterval::Ranges::iterator BI =
201       std::upper_bound(IntB.ranges.begin(), IntB.ranges.end(), AI->start);
202     if (BI != IntB.ranges.begin())
203       --BI;
204     for (; BI != IntB.ranges.end() && AI->end >= BI->start; ++BI) {
205       if (BI->valno == BValNo)
206         continue;
207       if (BI->start <= AI->start && BI->end > AI->start)
208         return true;
209       if (BI->start > AI->start && BI->start < AI->end)
210         return true;
211     }
212   }
213   return false;
214 }
215
216 /// RemoveCopyByCommutingDef - We found a non-trivially-coalescable copy with IntA
217 /// being the source and IntB being the dest, thus this defines a value number
218 /// in IntB.  If the source value number (in IntA) is defined by a commutable
219 /// instruction and its other operand is coalesced to the copy dest register,
220 /// see if we can transform the copy into a noop by commuting the definition. For
221 /// example,
222 ///
223 ///  A3 = op A2 B0<kill>
224 ///    ...
225 ///  B1 = A3      <- this copy
226 ///    ...
227 ///     = op A3   <- more uses
228 ///
229 /// ==>
230 ///
231 ///  B2 = op B0 A2<kill>
232 ///    ...
233 ///  B1 = B2      <- now an identify copy
234 ///    ...
235 ///     = op B2   <- more uses
236 ///
237 /// This returns true if an interval was modified.
238 ///
239 bool SimpleRegisterCoalescing::RemoveCopyByCommutingDef(LiveInterval &IntA,
240                                                         LiveInterval &IntB,
241                                                         MachineInstr *CopyMI) {
242   unsigned CopyIdx = li_->getDefIndex(li_->getInstructionIndex(CopyMI));
243
244   // FIXME: For now, only eliminate the copy by commuting its def when the
245   // source register is a virtual register. We want to guard against cases
246   // where the copy is a back edge copy and commuting the def lengthen the
247   // live interval of the source register to the entire loop.
248   if (TargetRegisterInfo::isPhysicalRegister(IntA.reg))
249     return false;
250
251   // BValNo is a value number in B that is defined by a copy from A. 'B3' in
252   // the example above.
253   LiveInterval::iterator BLR = IntB.FindLiveRangeContaining(CopyIdx);
254   VNInfo *BValNo = BLR->valno;
255   
256   // Get the location that B is defined at.  Two options: either this value has
257   // an unknown definition point or it is defined at CopyIdx.  If unknown, we 
258   // can't process it.
259   if (!BValNo->copy) return false;
260   assert(BValNo->def == CopyIdx && "Copy doesn't define the value?");
261   
262   // AValNo is the value number in A that defines the copy, A3 in the example.
263   LiveInterval::iterator ALR = IntA.FindLiveRangeContaining(CopyIdx-1);
264   VNInfo *AValNo = ALR->valno;
265   // If other defs can reach uses of this def, then it's not safe to perform
266   // the optimization.
267   if (AValNo->def == ~0U || AValNo->def == ~1U || AValNo->hasPHIKill)
268     return false;
269   MachineInstr *DefMI = li_->getInstructionFromIndex(AValNo->def);
270   const TargetInstrDesc &TID = DefMI->getDesc();
271   unsigned NewDstIdx;
272   if (!TID.isCommutable() ||
273       !tii_->CommuteChangesDestination(DefMI, NewDstIdx))
274     return false;
275
276   MachineOperand &NewDstMO = DefMI->getOperand(NewDstIdx);
277   unsigned NewReg = NewDstMO.getReg();
278   if (NewReg != IntB.reg || !NewDstMO.isKill())
279     return false;
280
281   // Make sure there are no other definitions of IntB that would reach the
282   // uses which the new definition can reach.
283   if (HasOtherReachingDefs(IntA, IntB, AValNo, BValNo))
284     return false;
285
286   // At this point we have decided that it is legal to do this
287   // transformation.  Start by commuting the instruction.
288   MachineBasicBlock *MBB = DefMI->getParent();
289   MachineInstr *NewMI = tii_->commuteInstruction(DefMI);
290   if (!NewMI)
291     return false;
292   if (NewMI != DefMI) {
293     li_->ReplaceMachineInstrInMaps(DefMI, NewMI);
294     MBB->insert(DefMI, NewMI);
295     MBB->erase(DefMI);
296   }
297   unsigned OpIdx = NewMI->findRegisterUseOperandIdx(IntA.reg, false);
298   NewMI->getOperand(OpIdx).setIsKill();
299
300   bool BHasPHIKill = BValNo->hasPHIKill;
301   SmallVector<VNInfo*, 4> BDeadValNos;
302   SmallVector<unsigned, 4> BKills;
303   std::map<unsigned, unsigned> BExtend;
304
305   // If ALR and BLR overlaps and end of BLR extends beyond end of ALR, e.g.
306   // A = or A, B
307   // ...
308   // B = A
309   // ...
310   // C = A<kill>
311   // ...
312   //   = B
313   //
314   // then do not add kills of A to the newly created B interval.
315   bool Extended = BLR->end > ALR->end && ALR->end != ALR->start;
316   if (Extended)
317     BExtend[ALR->end] = BLR->end;
318
319   // Update uses of IntA of the specific Val# with IntB.
320   for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(IntA.reg),
321          UE = mri_->use_end(); UI != UE;) {
322     MachineOperand &UseMO = UI.getOperand();
323     MachineInstr *UseMI = &*UI;
324     ++UI;
325     if (JoinedCopies.count(UseMI))
326       continue;
327     unsigned UseIdx = li_->getInstructionIndex(UseMI);
328     LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx);
329     if (ULR->valno != AValNo)
330       continue;
331     UseMO.setReg(NewReg);
332     if (UseMI == CopyMI)
333       continue;
334     if (UseMO.isKill()) {
335       if (Extended)
336         UseMO.setIsKill(false);
337       else
338         BKills.push_back(li_->getUseIndex(UseIdx)+1);
339     }
340     unsigned SrcReg, DstReg;
341     if (!tii_->isMoveInstr(*UseMI, SrcReg, DstReg))
342       continue;
343     if (DstReg == IntB.reg) {
344       // This copy will become a noop. If it's defining a new val#,
345       // remove that val# as well. However this live range is being
346       // extended to the end of the existing live range defined by the copy.
347       unsigned DefIdx = li_->getDefIndex(UseIdx);
348       LiveInterval::iterator DLR = IntB.FindLiveRangeContaining(DefIdx);
349       BHasPHIKill |= DLR->valno->hasPHIKill;
350       assert(DLR->valno->def == DefIdx);
351       BDeadValNos.push_back(DLR->valno);
352       BExtend[DLR->start] = DLR->end;
353       JoinedCopies.insert(UseMI);
354       // If this is a kill but it's going to be removed, the last use
355       // of the same val# is the new kill.
356       if (UseMO.isKill())
357         BKills.pop_back();
358     }
359   }
360
361   // We need to insert a new liverange: [ALR.start, LastUse). It may be we can
362   // simply extend BLR if CopyMI doesn't end the range.
363   DOUT << "\nExtending: "; IntB.print(DOUT, tri_);
364
365   IntB.removeValNo(BValNo);
366   for (unsigned i = 0, e = BDeadValNos.size(); i != e; ++i)
367     IntB.removeValNo(BDeadValNos[i]);
368   VNInfo *ValNo = IntB.getNextValue(AValNo->def, 0, li_->getVNInfoAllocator());
369   for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
370        AI != AE; ++AI) {
371     if (AI->valno != AValNo) continue;
372     unsigned End = AI->end;
373     std::map<unsigned, unsigned>::iterator EI = BExtend.find(End);
374     if (EI != BExtend.end())
375       End = EI->second;
376     IntB.addRange(LiveRange(AI->start, End, ValNo));
377   }
378   IntB.addKills(ValNo, BKills);
379   ValNo->hasPHIKill = BHasPHIKill;
380
381   DOUT << "   result = "; IntB.print(DOUT, tri_);
382   DOUT << "\n";
383
384   DOUT << "\nShortening: "; IntA.print(DOUT, tri_);
385   IntA.removeValNo(AValNo);
386   DOUT << "   result = "; IntA.print(DOUT, tri_);
387   DOUT << "\n";
388
389   ++numCommutes;
390   return true;
391 }
392
393 /// isBackEdgeCopy - Returns true if CopyMI is a back edge copy.
394 ///
395 bool SimpleRegisterCoalescing::isBackEdgeCopy(MachineInstr *CopyMI,
396                                               unsigned DstReg) {
397   MachineBasicBlock *MBB = CopyMI->getParent();
398   const MachineLoop *L = loopInfo->getLoopFor(MBB);
399   if (!L)
400     return false;
401   if (MBB != L->getLoopLatch())
402     return false;
403
404   LiveInterval &LI = li_->getInterval(DstReg);
405   unsigned DefIdx = li_->getInstructionIndex(CopyMI);
406   LiveInterval::const_iterator DstLR =
407     LI.FindLiveRangeContaining(li_->getDefIndex(DefIdx));
408   if (DstLR == LI.end())
409     return false;
410   unsigned KillIdx = li_->getInstructionIndex(&MBB->back()) + InstrSlots::NUM;
411   if (DstLR->valno->kills.size() == 1 &&
412       DstLR->valno->kills[0] == KillIdx && DstLR->valno->hasPHIKill)
413     return true;
414   return false;
415 }
416
417 /// UpdateRegDefsUses - Replace all defs and uses of SrcReg to DstReg and
418 /// update the subregister number if it is not zero. If DstReg is a
419 /// physical register and the existing subregister number of the def / use
420 /// being updated is not zero, make sure to set it to the correct physical
421 /// subregister.
422 void
423 SimpleRegisterCoalescing::UpdateRegDefsUses(unsigned SrcReg, unsigned DstReg,
424                                             unsigned SubIdx) {
425   bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
426   if (DstIsPhys && SubIdx) {
427     // Figure out the real physical register we are updating with.
428     DstReg = tri_->getSubReg(DstReg, SubIdx);
429     SubIdx = 0;
430   }
431
432   for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(SrcReg),
433          E = mri_->reg_end(); I != E; ) {
434     MachineOperand &O = I.getOperand();
435     MachineInstr *UseMI = &*I;
436     ++I;
437     if (DstIsPhys) {
438       unsigned UseSubIdx = O.getSubReg();
439       unsigned UseDstReg = DstReg;
440       if (UseSubIdx)
441         UseDstReg = tri_->getSubReg(DstReg, UseSubIdx);
442       O.setReg(UseDstReg);
443       O.setSubReg(0);
444     } else {
445       unsigned OldSubIdx = O.getSubReg();
446       // Sub-register indexes goes from small to large. e.g.
447       // RAX: 0 -> AL, 1 -> AH, 2 -> AX, 3 -> EAX
448       // EAX: 0 -> AL, 1 -> AH, 2 -> AX
449       // So RAX's sub-register 2 is AX, RAX's sub-regsiter 3 is EAX, whose
450       // sub-register 2 is also AX.
451       if (SubIdx && OldSubIdx && SubIdx != OldSubIdx)
452         assert(OldSubIdx < SubIdx && "Conflicting sub-register index!");
453       else if (SubIdx)
454         O.setSubReg(SubIdx);
455       // Remove would-be duplicated kill marker.
456       if (O.isKill() && UseMI->killsRegister(DstReg))
457         O.setIsKill(false);
458       O.setReg(DstReg);
459     }
460   }
461 }
462
463 /// RemoveUnnecessaryKills - Remove kill markers that are no longer accurate
464 /// due to live range lengthening as the result of coalescing.
465 void SimpleRegisterCoalescing::RemoveUnnecessaryKills(unsigned Reg,
466                                                       LiveInterval &LI) {
467   for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(Reg),
468          UE = mri_->use_end(); UI != UE; ++UI) {
469     MachineOperand &UseMO = UI.getOperand();
470     if (UseMO.isKill()) {
471       MachineInstr *UseMI = UseMO.getParent();
472       unsigned SReg, DReg;
473       if (!tii_->isMoveInstr(*UseMI, SReg, DReg))
474         continue;
475       unsigned UseIdx = li_->getUseIndex(li_->getInstructionIndex(UseMI));
476       if (JoinedCopies.count(UseMI))
477         continue;
478       LiveInterval::const_iterator UI = LI.FindLiveRangeContaining(UseIdx);
479       assert(UI != LI.end());
480       if (!LI.isKill(UI->valno, UseIdx+1))
481         UseMO.setIsKill(false);
482     }
483   }
484 }
485
486 /// removeRange - Wrapper for LiveInterval::removeRange. This removes a range
487 /// from a physical register live interval as well as from the live intervals
488 /// of its sub-registers.
489 static void removeRange(LiveInterval &li, unsigned Start, unsigned End,
490                         LiveIntervals *li_, const TargetRegisterInfo *tri_) {
491   li.removeRange(Start, End, true);
492   if (TargetRegisterInfo::isPhysicalRegister(li.reg)) {
493     for (const unsigned* SR = tri_->getSubRegisters(li.reg); *SR; ++SR) {
494       if (!li_->hasInterval(*SR))
495         continue;
496       LiveInterval &sli = li_->getInterval(*SR);
497       unsigned RemoveEnd = Start;
498       while (RemoveEnd != End) {
499         LiveInterval::iterator LR = sli.FindLiveRangeContaining(Start);
500         if (LR == sli.end())
501           break;
502         RemoveEnd = (LR->end < End) ? LR->end : End;
503         sli.removeRange(Start, RemoveEnd, true);
504         Start = RemoveEnd;
505       }
506     }
507   }
508 }
509
510 /// removeIntervalIfEmpty - Check if the live interval of a physical register
511 /// is empty, if so remove it and also remove the empty intervals of its
512 /// sub-registers.
513 static void removeIntervalIfEmpty(LiveInterval &li, LiveIntervals *li_,
514                                   const TargetRegisterInfo *tri_) {
515   if (li.empty()) {
516     li_->removeInterval(li.reg);
517     if (TargetRegisterInfo::isPhysicalRegister(li.reg))
518       for (const unsigned* SR = tri_->getSubRegisters(li.reg); *SR; ++SR) {
519         if (!li_->hasInterval(*SR))
520           continue;
521         LiveInterval &sli = li_->getInterval(*SR);
522         if (sli.empty())
523           li_->removeInterval(*SR);
524       }
525   }
526 }
527
528 /// ShortenDeadCopyLiveRange - Shorten a live range defined by a dead copy.
529 ///
530 void SimpleRegisterCoalescing::ShortenDeadCopyLiveRange(LiveInterval &li,
531                                                         MachineInstr *CopyMI) {
532   unsigned CopyIdx = li_->getInstructionIndex(CopyMI);
533   LiveInterval::iterator MLR =
534     li.FindLiveRangeContaining(li_->getDefIndex(CopyIdx));
535   if (MLR == li.end())
536     return;  // Already removed by ShortenDeadCopySrcLiveRange.
537   unsigned RemoveStart = MLR->start;
538   unsigned RemoveEnd = MLR->end;
539   // Remove the liverange that's defined by this.
540   if (RemoveEnd == li_->getDefIndex(CopyIdx)+1) {
541     removeRange(li, RemoveStart, RemoveEnd, li_, tri_);
542     removeIntervalIfEmpty(li, li_, tri_);
543   }
544 }
545
546 /// ShortenDeadCopyLiveRange - Shorten a live range as it's artificially
547 /// extended by a dead copy. Mark the last use (if any) of the val# as kill
548 /// as ends the live range there. If there isn't another use, then this
549 /// live range is dead.
550 void
551 SimpleRegisterCoalescing::ShortenDeadCopySrcLiveRange(LiveInterval &li,
552                                                       MachineInstr *CopyMI) {
553   unsigned CopyIdx = li_->getInstructionIndex(CopyMI);
554   if (CopyIdx == 0) {
555     // FIXME: special case: function live in. It can be a general case if the
556     // first instruction index starts at > 0 value.
557     assert(TargetRegisterInfo::isPhysicalRegister(li.reg));
558     // Live-in to the function but dead. Remove it from entry live-in set.
559     mf_->begin()->removeLiveIn(li.reg);
560     LiveInterval::iterator LR = li.FindLiveRangeContaining(CopyIdx);
561     removeRange(li, LR->start, LR->end, li_, tri_);
562     removeIntervalIfEmpty(li, li_, tri_);
563     return;
564   }
565
566   LiveInterval::iterator LR = li.FindLiveRangeContaining(CopyIdx-1);
567   if (LR == li.end())
568     // Livein but defined by a phi.
569     return;
570
571   unsigned RemoveStart = LR->start;
572   unsigned RemoveEnd = li_->getDefIndex(CopyIdx)+1;
573   if (LR->end > RemoveEnd)
574     // More uses past this copy? Nothing to do.
575     return;
576
577   unsigned LastUseIdx;
578   MachineOperand *LastUse =
579     lastRegisterUse(LR->start, CopyIdx-1, li.reg, LastUseIdx);
580   if (LastUse) {
581     // There are uses before the copy, just shorten the live range to the end
582     // of last use.
583     LastUse->setIsKill();
584     MachineInstr *LastUseMI = LastUse->getParent();
585     removeRange(li, li_->getDefIndex(LastUseIdx), LR->end, li_, tri_);
586     unsigned SrcReg, DstReg;
587     if (tii_->isMoveInstr(*LastUseMI, SrcReg, DstReg) &&
588         DstReg == li.reg) {
589       // Last use is itself an identity code.
590       int DeadIdx = LastUseMI->findRegisterDefOperandIdx(li.reg, false, tri_);
591       LastUseMI->getOperand(DeadIdx).setIsDead();
592     }
593     return;
594   }
595
596   // Is it livein?
597   MachineBasicBlock *CopyMBB = CopyMI->getParent();
598   unsigned MBBStart = li_->getMBBStartIdx(CopyMBB);
599   if (LR->start <= MBBStart && LR->end > MBBStart) {
600     if (LR->start == 0) {
601       assert(TargetRegisterInfo::isPhysicalRegister(li.reg));
602       // Live-in to the function but dead. Remove it from entry live-in set.
603       mf_->begin()->removeLiveIn(li.reg);
604     }
605     removeRange(li, LR->start, LR->end, li_, tri_);
606     // FIXME: Shorten intervals in BBs that reaches this BB.
607   } else {
608     // Not livein into BB.
609     MachineInstr *DefMI =
610       li_->getInstructionFromIndex(li_->getDefIndex(RemoveStart));
611     if (DefMI && DefMI != CopyMI) {
612       int DeadIdx = DefMI->findRegisterDefOperandIdx(li.reg, false, tri_);
613       if (DeadIdx != -1) {
614         DefMI->getOperand(DeadIdx).setIsDead();
615         // A dead def should have a single cycle interval.
616         ++RemoveStart;
617       }
618     }
619     removeRange(li, RemoveStart, LR->end, li_, tri_);
620   }
621
622   removeIntervalIfEmpty(li, li_, tri_);
623 }
624
625 /// JoinCopy - Attempt to join intervals corresponding to SrcReg/DstReg,
626 /// which are the src/dst of the copy instruction CopyMI.  This returns true
627 /// if the copy was successfully coalesced away. If it is not currently
628 /// possible to coalesce this interval, but it may be possible if other
629 /// things get coalesced, then it returns true by reference in 'Again'.
630 bool SimpleRegisterCoalescing::JoinCopy(CopyRec &TheCopy, bool &Again) {
631   MachineInstr *CopyMI = TheCopy.MI;
632
633   Again = false;
634   if (JoinedCopies.count(CopyMI))
635     return false; // Already done.
636
637   DOUT << li_->getInstructionIndex(CopyMI) << '\t' << *CopyMI;
638
639   unsigned SrcReg;
640   unsigned DstReg;
641   bool isExtSubReg = CopyMI->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG;
642   unsigned SubIdx = 0;
643   if (isExtSubReg) {
644     DstReg = CopyMI->getOperand(0).getReg();
645     SrcReg = CopyMI->getOperand(1).getReg();
646   } else if (!tii_->isMoveInstr(*CopyMI, SrcReg, DstReg)) {
647     assert(0 && "Unrecognized copy instruction!");
648     return false;
649   }
650
651   // If they are already joined we continue.
652   if (SrcReg == DstReg) {
653     DOUT << "\tCopy already coalesced.\n";
654     return false;  // Not coalescable.
655   }
656   
657   bool SrcIsPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
658   bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
659
660   // If they are both physical registers, we cannot join them.
661   if (SrcIsPhys && DstIsPhys) {
662     DOUT << "\tCan not coalesce physregs.\n";
663     return false;  // Not coalescable.
664   }
665   
666   // We only join virtual registers with allocatable physical registers.
667   if (SrcIsPhys && !allocatableRegs_[SrcReg]) {
668     DOUT << "\tSrc reg is unallocatable physreg.\n";
669     return false;  // Not coalescable.
670   }
671   if (DstIsPhys && !allocatableRegs_[DstReg]) {
672     DOUT << "\tDst reg is unallocatable physreg.\n";
673     return false;  // Not coalescable.
674   }
675
676   unsigned RealDstReg = 0;
677   if (isExtSubReg) {
678     SubIdx = CopyMI->getOperand(2).getImm();
679     if (SrcIsPhys) {
680       // r1024 = EXTRACT_SUBREG EAX, 0 then r1024 is really going to be
681       // coalesced with AX.
682       SrcReg = tri_->getSubReg(SrcReg, SubIdx);
683       SubIdx = 0;
684     } else if (DstIsPhys) {
685       // If this is a extract_subreg where dst is a physical register, e.g.
686       // cl = EXTRACT_SUBREG reg1024, 1
687       // then create and update the actual physical register allocated to RHS.
688       const TargetRegisterClass *RC = mri_->getRegClass(SrcReg);
689       for (const unsigned *SRs = tri_->getSuperRegisters(DstReg);
690            unsigned SR = *SRs; ++SRs) {
691         if (DstReg == tri_->getSubReg(SR, SubIdx) &&
692             RC->contains(SR)) {
693           RealDstReg = SR;
694           break;
695         }
696       }
697       assert(RealDstReg && "Invalid extra_subreg instruction!");
698
699       // For this type of EXTRACT_SUBREG, conservatively
700       // check if the live interval of the source register interfere with the
701       // actual super physical register we are trying to coalesce with.
702       LiveInterval &RHS = li_->getInterval(SrcReg);
703       if (li_->hasInterval(RealDstReg) &&
704           RHS.overlaps(li_->getInterval(RealDstReg))) {
705         DOUT << "Interfere with register ";
706         DEBUG(li_->getInterval(RealDstReg).print(DOUT, tri_));
707         return false; // Not coalescable
708       }
709       for (const unsigned* SR = tri_->getSubRegisters(RealDstReg); *SR; ++SR)
710         if (li_->hasInterval(*SR) && RHS.overlaps(li_->getInterval(*SR))) {
711           DOUT << "Interfere with sub-register ";
712           DEBUG(li_->getInterval(*SR).print(DOUT, tri_));
713           return false; // Not coalescable
714         }
715       SubIdx = 0;
716     } else {
717       unsigned SrcSize= li_->getInterval(SrcReg).getSize() / InstrSlots::NUM;
718       unsigned DstSize= li_->getInterval(DstReg).getSize() / InstrSlots::NUM;
719       const TargetRegisterClass *RC = mri_->getRegClass(DstReg);
720       unsigned Threshold = allocatableRCRegs_[RC].count();
721       // Be conservative. If both sides are virtual registers, do not coalesce
722       // if this will cause a high use density interval to target a smaller set
723       // of registers.
724       if (DstSize > Threshold || SrcSize > Threshold) {
725         LiveVariables::VarInfo &svi = lv_->getVarInfo(SrcReg);
726         LiveVariables::VarInfo &dvi = lv_->getVarInfo(DstReg);
727         if ((float)dvi.NumUses / DstSize < (float)svi.NumUses / SrcSize) {
728           Again = true;  // May be possible to coalesce later.
729           return false;
730         }
731       }
732     }
733   } else if (differingRegisterClasses(SrcReg, DstReg)) {
734     // FIXME: What if the resul of a EXTRACT_SUBREG is then coalesced
735     // with another? If it's the resulting destination register, then
736     // the subidx must be propagated to uses (but only those defined
737     // by the EXTRACT_SUBREG). If it's being coalesced into another
738     // register, it should be safe because register is assumed to have
739     // the register class of the super-register.
740
741     // If they are not of the same register class, we cannot join them.
742     DOUT << "\tSrc/Dest are different register classes.\n";
743     // Allow the coalescer to try again in case either side gets coalesced to
744     // a physical register that's compatible with the other side. e.g.
745     // r1024 = MOV32to32_ r1025
746     // but later r1024 is assigned EAX then r1025 may be coalesced with EAX.
747     Again = true;  // May be possible to coalesce later.
748     return false;
749   }
750   
751   LiveInterval &SrcInt = li_->getInterval(SrcReg);
752   LiveInterval &DstInt = li_->getInterval(DstReg);
753   assert(SrcInt.reg == SrcReg && DstInt.reg == DstReg &&
754          "Register mapping is horribly broken!");
755
756   DOUT << "\t\tInspecting "; SrcInt.print(DOUT, tri_);
757   DOUT << " and "; DstInt.print(DOUT, tri_);
758   DOUT << ": ";
759
760   // Check if it is necessary to propagate "isDead" property.
761   MachineOperand *mopd = CopyMI->findRegisterDefOperand(DstReg, false);
762   bool isDead = mopd->isDead();
763
764   // We need to be careful about coalescing a source physical register with a
765   // virtual register. Once the coalescing is done, it cannot be broken and
766   // these are not spillable! If the destination interval uses are far away,
767   // think twice about coalescing them!
768   if (!isDead && (SrcIsPhys || DstIsPhys) && !isExtSubReg) {
769     LiveInterval &JoinVInt = SrcIsPhys ? DstInt : SrcInt;
770     unsigned JoinVReg = SrcIsPhys ? DstReg : SrcReg;
771     unsigned JoinPReg = SrcIsPhys ? SrcReg : DstReg;
772     const TargetRegisterClass *RC = mri_->getRegClass(JoinVReg);
773     unsigned Threshold = allocatableRCRegs_[RC].count() * 2;
774     if (TheCopy.isBackEdge)
775       Threshold *= 2; // Favors back edge copies.
776
777     // If the virtual register live interval is long but it has low use desity,
778     // do not join them, instead mark the physical register as its allocation
779     // preference.
780     unsigned Length = JoinVInt.getSize() / InstrSlots::NUM;
781     LiveVariables::VarInfo &vi = lv_->getVarInfo(JoinVReg);
782     if (Length > Threshold &&
783         (((float)vi.NumUses / Length) < (1.0 / Threshold))) {
784       JoinVInt.preference = JoinPReg;
785       ++numAborts;
786       DOUT << "\tMay tie down a physical register, abort!\n";
787       Again = true;  // May be possible to coalesce later.
788       return false;
789     }
790   }
791
792   // Okay, attempt to join these two intervals.  On failure, this returns false.
793   // Otherwise, if one of the intervals being joined is a physreg, this method
794   // always canonicalizes DstInt to be it.  The output "SrcInt" will not have
795   // been modified, so we can use this information below to update aliases.
796   bool Swapped = false;
797   if (!JoinIntervals(DstInt, SrcInt, Swapped)) {
798     // Coalescing failed.
799     
800     // If we can eliminate the copy without merging the live ranges, do so now.
801     if (!isExtSubReg &&
802         (AdjustCopiesBackFrom(SrcInt, DstInt, CopyMI) ||
803          RemoveCopyByCommutingDef(SrcInt, DstInt, CopyMI))) {
804       JoinedCopies.insert(CopyMI);
805       return true;
806     }
807     
808     // Otherwise, we are unable to join the intervals.
809     DOUT << "Interference!\n";
810     Again = true;  // May be possible to coalesce later.
811     return false;
812   }
813
814   LiveInterval *ResSrcInt = &SrcInt;
815   LiveInterval *ResDstInt = &DstInt;
816   if (Swapped) {
817     std::swap(SrcReg, DstReg);
818     std::swap(ResSrcInt, ResDstInt);
819   }
820   assert(TargetRegisterInfo::isVirtualRegister(SrcReg) &&
821          "LiveInterval::join didn't work right!");
822                                
823   // If we're about to merge live ranges into a physical register live range,
824   // we have to update any aliased register's live ranges to indicate that they
825   // have clobbered values for this range.
826   if (TargetRegisterInfo::isPhysicalRegister(DstReg)) {
827     // If this is a extract_subreg where dst is a physical register, e.g.
828     // cl = EXTRACT_SUBREG reg1024, 1
829     // then create and update the actual physical register allocated to RHS.
830     if (RealDstReg) {
831       LiveInterval &RealDstInt = li_->getOrCreateInterval(RealDstReg);
832       SmallSet<const VNInfo*, 4> CopiedValNos;
833       for (LiveInterval::Ranges::const_iterator I = ResSrcInt->ranges.begin(),
834              E = ResSrcInt->ranges.end(); I != E; ++I) {
835         LiveInterval::const_iterator DstLR =
836           ResDstInt->FindLiveRangeContaining(I->start);
837         assert(DstLR != ResDstInt->end() && "Invalid joined interval!");
838         const VNInfo *DstValNo = DstLR->valno;
839         if (CopiedValNos.insert(DstValNo)) {
840           VNInfo *ValNo = RealDstInt.getNextValue(DstValNo->def, DstValNo->copy,
841                                                   li_->getVNInfoAllocator());
842           ValNo->hasPHIKill = DstValNo->hasPHIKill;
843           RealDstInt.addKills(ValNo, DstValNo->kills);
844           RealDstInt.MergeValueInAsValue(*ResDstInt, DstValNo, ValNo);
845         }
846       }
847       DstReg = RealDstReg;
848     }
849
850     // Update the liveintervals of sub-registers.
851     for (const unsigned *AS = tri_->getSubRegisters(DstReg); *AS; ++AS)
852       li_->getOrCreateInterval(*AS).MergeInClobberRanges(*ResSrcInt,
853                                                  li_->getVNInfoAllocator());
854   } else {
855     // Merge use info if the destination is a virtual register.
856     LiveVariables::VarInfo& dVI = lv_->getVarInfo(DstReg);
857     LiveVariables::VarInfo& sVI = lv_->getVarInfo(SrcReg);
858     dVI.NumUses += sVI.NumUses;
859   }
860
861   // If this is a EXTRACT_SUBREG, make sure the result of coalescing is the
862   // larger super-register.
863   if (isExtSubReg && !SrcIsPhys && !DstIsPhys) {
864     if (!Swapped) {
865       ResSrcInt->Copy(*ResDstInt, li_->getVNInfoAllocator());
866       std::swap(SrcReg, DstReg);
867       std::swap(ResSrcInt, ResDstInt);
868     }
869   }
870
871   if (NewHeuristic) {
872     // Add all copies that define val# in the source interval into the queue.
873     for (LiveInterval::const_vni_iterator i = ResSrcInt->vni_begin(),
874            e = ResSrcInt->vni_end(); i != e; ++i) {
875       const VNInfo *vni = *i;
876       if (!vni->def || vni->def == ~1U || vni->def == ~0U)
877         continue;
878       MachineInstr *CopyMI = li_->getInstructionFromIndex(vni->def);
879       unsigned NewSrcReg, NewDstReg;
880       if (CopyMI &&
881           JoinedCopies.count(CopyMI) == 0 &&
882           tii_->isMoveInstr(*CopyMI, NewSrcReg, NewDstReg)) {
883         unsigned LoopDepth = loopInfo->getLoopDepth(CopyMI->getParent());
884         JoinQueue->push(CopyRec(CopyMI, LoopDepth,
885                                 isBackEdgeCopy(CopyMI, DstReg)));
886       }
887     }
888   }
889
890   DOUT << "\n\t\tJoined.  Result = "; ResDstInt->print(DOUT, tri_);
891   DOUT << "\n";
892
893   // Remember to delete the copy instruction.
894   JoinedCopies.insert(CopyMI);
895
896   // Some live range has been lengthened due to colaescing, eliminate the
897   // unnecessary kills.
898   RemoveUnnecessaryKills(SrcReg, *ResDstInt);
899   if (TargetRegisterInfo::isVirtualRegister(DstReg))
900     RemoveUnnecessaryKills(DstReg, *ResDstInt);
901
902   // SrcReg is guarateed to be the register whose live interval that is
903   // being merged.
904   li_->removeInterval(SrcReg);
905   UpdateRegDefsUses(SrcReg, DstReg, SubIdx);
906
907   ++numJoins;
908   return true;
909 }
910
911 /// ComputeUltimateVN - Assuming we are going to join two live intervals,
912 /// compute what the resultant value numbers for each value in the input two
913 /// ranges will be.  This is complicated by copies between the two which can
914 /// and will commonly cause multiple value numbers to be merged into one.
915 ///
916 /// VN is the value number that we're trying to resolve.  InstDefiningValue
917 /// keeps track of the new InstDefiningValue assignment for the result
918 /// LiveInterval.  ThisFromOther/OtherFromThis are sets that keep track of
919 /// whether a value in this or other is a copy from the opposite set.
920 /// ThisValNoAssignments/OtherValNoAssignments keep track of value #'s that have
921 /// already been assigned.
922 ///
923 /// ThisFromOther[x] - If x is defined as a copy from the other interval, this
924 /// contains the value number the copy is from.
925 ///
926 static unsigned ComputeUltimateVN(VNInfo *VNI,
927                                   SmallVector<VNInfo*, 16> &NewVNInfo,
928                                   DenseMap<VNInfo*, VNInfo*> &ThisFromOther,
929                                   DenseMap<VNInfo*, VNInfo*> &OtherFromThis,
930                                   SmallVector<int, 16> &ThisValNoAssignments,
931                                   SmallVector<int, 16> &OtherValNoAssignments) {
932   unsigned VN = VNI->id;
933
934   // If the VN has already been computed, just return it.
935   if (ThisValNoAssignments[VN] >= 0)
936     return ThisValNoAssignments[VN];
937 //  assert(ThisValNoAssignments[VN] != -2 && "Cyclic case?");
938
939   // If this val is not a copy from the other val, then it must be a new value
940   // number in the destination.
941   DenseMap<VNInfo*, VNInfo*>::iterator I = ThisFromOther.find(VNI);
942   if (I == ThisFromOther.end()) {
943     NewVNInfo.push_back(VNI);
944     return ThisValNoAssignments[VN] = NewVNInfo.size()-1;
945   }
946   VNInfo *OtherValNo = I->second;
947
948   // Otherwise, this *is* a copy from the RHS.  If the other side has already
949   // been computed, return it.
950   if (OtherValNoAssignments[OtherValNo->id] >= 0)
951     return ThisValNoAssignments[VN] = OtherValNoAssignments[OtherValNo->id];
952   
953   // Mark this value number as currently being computed, then ask what the
954   // ultimate value # of the other value is.
955   ThisValNoAssignments[VN] = -2;
956   unsigned UltimateVN =
957     ComputeUltimateVN(OtherValNo, NewVNInfo, OtherFromThis, ThisFromOther,
958                       OtherValNoAssignments, ThisValNoAssignments);
959   return ThisValNoAssignments[VN] = UltimateVN;
960 }
961
962 static bool InVector(VNInfo *Val, const SmallVector<VNInfo*, 8> &V) {
963   return std::find(V.begin(), V.end(), Val) != V.end();
964 }
965
966 /// SimpleJoin - Attempt to joint the specified interval into this one. The
967 /// caller of this method must guarantee that the RHS only contains a single
968 /// value number and that the RHS is not defined by a copy from this
969 /// interval.  This returns false if the intervals are not joinable, or it
970 /// joins them and returns true.
971 bool SimpleRegisterCoalescing::SimpleJoin(LiveInterval &LHS, LiveInterval &RHS){
972   assert(RHS.containsOneValue());
973   
974   // Some number (potentially more than one) value numbers in the current
975   // interval may be defined as copies from the RHS.  Scan the overlapping
976   // portions of the LHS and RHS, keeping track of this and looking for
977   // overlapping live ranges that are NOT defined as copies.  If these exist, we
978   // cannot coalesce.
979   
980   LiveInterval::iterator LHSIt = LHS.begin(), LHSEnd = LHS.end();
981   LiveInterval::iterator RHSIt = RHS.begin(), RHSEnd = RHS.end();
982   
983   if (LHSIt->start < RHSIt->start) {
984     LHSIt = std::upper_bound(LHSIt, LHSEnd, RHSIt->start);
985     if (LHSIt != LHS.begin()) --LHSIt;
986   } else if (RHSIt->start < LHSIt->start) {
987     RHSIt = std::upper_bound(RHSIt, RHSEnd, LHSIt->start);
988     if (RHSIt != RHS.begin()) --RHSIt;
989   }
990   
991   SmallVector<VNInfo*, 8> EliminatedLHSVals;
992   
993   while (1) {
994     // Determine if these live intervals overlap.
995     bool Overlaps = false;
996     if (LHSIt->start <= RHSIt->start)
997       Overlaps = LHSIt->end > RHSIt->start;
998     else
999       Overlaps = RHSIt->end > LHSIt->start;
1000     
1001     // If the live intervals overlap, there are two interesting cases: if the
1002     // LHS interval is defined by a copy from the RHS, it's ok and we record
1003     // that the LHS value # is the same as the RHS.  If it's not, then we cannot
1004     // coalesce these live ranges and we bail out.
1005     if (Overlaps) {
1006       // If we haven't already recorded that this value # is safe, check it.
1007       if (!InVector(LHSIt->valno, EliminatedLHSVals)) {
1008         // Copy from the RHS?
1009         unsigned SrcReg = li_->getVNInfoSourceReg(LHSIt->valno);
1010         if (SrcReg != RHS.reg)
1011           return false;    // Nope, bail out.
1012         
1013         EliminatedLHSVals.push_back(LHSIt->valno);
1014       }
1015       
1016       // We know this entire LHS live range is okay, so skip it now.
1017       if (++LHSIt == LHSEnd) break;
1018       continue;
1019     }
1020     
1021     if (LHSIt->end < RHSIt->end) {
1022       if (++LHSIt == LHSEnd) break;
1023     } else {
1024       // One interesting case to check here.  It's possible that we have
1025       // something like "X3 = Y" which defines a new value number in the LHS,
1026       // and is the last use of this liverange of the RHS.  In this case, we
1027       // want to notice this copy (so that it gets coalesced away) even though
1028       // the live ranges don't actually overlap.
1029       if (LHSIt->start == RHSIt->end) {
1030         if (InVector(LHSIt->valno, EliminatedLHSVals)) {
1031           // We already know that this value number is going to be merged in
1032           // if coalescing succeeds.  Just skip the liverange.
1033           if (++LHSIt == LHSEnd) break;
1034         } else {
1035           // Otherwise, if this is a copy from the RHS, mark it as being merged
1036           // in.
1037           if (li_->getVNInfoSourceReg(LHSIt->valno) == RHS.reg) {
1038             EliminatedLHSVals.push_back(LHSIt->valno);
1039
1040             // We know this entire LHS live range is okay, so skip it now.
1041             if (++LHSIt == LHSEnd) break;
1042           }
1043         }
1044       }
1045       
1046       if (++RHSIt == RHSEnd) break;
1047     }
1048   }
1049   
1050   // If we got here, we know that the coalescing will be successful and that
1051   // the value numbers in EliminatedLHSVals will all be merged together.  Since
1052   // the most common case is that EliminatedLHSVals has a single number, we
1053   // optimize for it: if there is more than one value, we merge them all into
1054   // the lowest numbered one, then handle the interval as if we were merging
1055   // with one value number.
1056   VNInfo *LHSValNo;
1057   if (EliminatedLHSVals.size() > 1) {
1058     // Loop through all the equal value numbers merging them into the smallest
1059     // one.
1060     VNInfo *Smallest = EliminatedLHSVals[0];
1061     for (unsigned i = 1, e = EliminatedLHSVals.size(); i != e; ++i) {
1062       if (EliminatedLHSVals[i]->id < Smallest->id) {
1063         // Merge the current notion of the smallest into the smaller one.
1064         LHS.MergeValueNumberInto(Smallest, EliminatedLHSVals[i]);
1065         Smallest = EliminatedLHSVals[i];
1066       } else {
1067         // Merge into the smallest.
1068         LHS.MergeValueNumberInto(EliminatedLHSVals[i], Smallest);
1069       }
1070     }
1071     LHSValNo = Smallest;
1072   } else {
1073     assert(!EliminatedLHSVals.empty() && "No copies from the RHS?");
1074     LHSValNo = EliminatedLHSVals[0];
1075   }
1076   
1077   // Okay, now that there is a single LHS value number that we're merging the
1078   // RHS into, update the value number info for the LHS to indicate that the
1079   // value number is defined where the RHS value number was.
1080   const VNInfo *VNI = RHS.getValNumInfo(0);
1081   LHSValNo->def  = VNI->def;
1082   LHSValNo->copy = VNI->copy;
1083   
1084   // Okay, the final step is to loop over the RHS live intervals, adding them to
1085   // the LHS.
1086   LHSValNo->hasPHIKill |= VNI->hasPHIKill;
1087   LHS.addKills(LHSValNo, VNI->kills);
1088   LHS.MergeRangesInAsValue(RHS, LHSValNo);
1089   LHS.weight += RHS.weight;
1090   if (RHS.preference && !LHS.preference)
1091     LHS.preference = RHS.preference;
1092   
1093   return true;
1094 }
1095
1096 /// JoinIntervals - Attempt to join these two intervals.  On failure, this
1097 /// returns false.  Otherwise, if one of the intervals being joined is a
1098 /// physreg, this method always canonicalizes LHS to be it.  The output
1099 /// "RHS" will not have been modified, so we can use this information
1100 /// below to update aliases.
1101 bool SimpleRegisterCoalescing::JoinIntervals(LiveInterval &LHS,
1102                                              LiveInterval &RHS, bool &Swapped) {
1103   // Compute the final value assignment, assuming that the live ranges can be
1104   // coalesced.
1105   SmallVector<int, 16> LHSValNoAssignments;
1106   SmallVector<int, 16> RHSValNoAssignments;
1107   DenseMap<VNInfo*, VNInfo*> LHSValsDefinedFromRHS;
1108   DenseMap<VNInfo*, VNInfo*> RHSValsDefinedFromLHS;
1109   SmallVector<VNInfo*, 16> NewVNInfo;
1110                           
1111   // If a live interval is a physical register, conservatively check if any
1112   // of its sub-registers is overlapping the live interval of the virtual
1113   // register. If so, do not coalesce.
1114   if (TargetRegisterInfo::isPhysicalRegister(LHS.reg) &&
1115       *tri_->getSubRegisters(LHS.reg)) {
1116     for (const unsigned* SR = tri_->getSubRegisters(LHS.reg); *SR; ++SR)
1117       if (li_->hasInterval(*SR) && RHS.overlaps(li_->getInterval(*SR))) {
1118         DOUT << "Interfere with sub-register ";
1119         DEBUG(li_->getInterval(*SR).print(DOUT, tri_));
1120         return false;
1121       }
1122   } else if (TargetRegisterInfo::isPhysicalRegister(RHS.reg) &&
1123              *tri_->getSubRegisters(RHS.reg)) {
1124     for (const unsigned* SR = tri_->getSubRegisters(RHS.reg); *SR; ++SR)
1125       if (li_->hasInterval(*SR) && LHS.overlaps(li_->getInterval(*SR))) {
1126         DOUT << "Interfere with sub-register ";
1127         DEBUG(li_->getInterval(*SR).print(DOUT, tri_));
1128         return false;
1129       }
1130   }
1131                           
1132   // Compute ultimate value numbers for the LHS and RHS values.
1133   if (RHS.containsOneValue()) {
1134     // Copies from a liveinterval with a single value are simple to handle and
1135     // very common, handle the special case here.  This is important, because
1136     // often RHS is small and LHS is large (e.g. a physreg).
1137     
1138     // Find out if the RHS is defined as a copy from some value in the LHS.
1139     int RHSVal0DefinedFromLHS = -1;
1140     int RHSValID = -1;
1141     VNInfo *RHSValNoInfo = NULL;
1142     VNInfo *RHSValNoInfo0 = RHS.getValNumInfo(0);
1143     unsigned RHSSrcReg = li_->getVNInfoSourceReg(RHSValNoInfo0);
1144     if ((RHSSrcReg == 0 || RHSSrcReg != LHS.reg)) {
1145       // If RHS is not defined as a copy from the LHS, we can use simpler and
1146       // faster checks to see if the live ranges are coalescable.  This joiner
1147       // can't swap the LHS/RHS intervals though.
1148       if (!TargetRegisterInfo::isPhysicalRegister(RHS.reg)) {
1149         return SimpleJoin(LHS, RHS);
1150       } else {
1151         RHSValNoInfo = RHSValNoInfo0;
1152       }
1153     } else {
1154       // It was defined as a copy from the LHS, find out what value # it is.
1155       RHSValNoInfo = LHS.getLiveRangeContaining(RHSValNoInfo0->def-1)->valno;
1156       RHSValID = RHSValNoInfo->id;
1157       RHSVal0DefinedFromLHS = RHSValID;
1158     }
1159     
1160     LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
1161     RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
1162     NewVNInfo.resize(LHS.getNumValNums(), NULL);
1163     
1164     // Okay, *all* of the values in LHS that are defined as a copy from RHS
1165     // should now get updated.
1166     for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1167          i != e; ++i) {
1168       VNInfo *VNI = *i;
1169       unsigned VN = VNI->id;
1170       if (unsigned LHSSrcReg = li_->getVNInfoSourceReg(VNI)) {
1171         if (LHSSrcReg != RHS.reg) {
1172           // If this is not a copy from the RHS, its value number will be
1173           // unmodified by the coalescing.
1174           NewVNInfo[VN] = VNI;
1175           LHSValNoAssignments[VN] = VN;
1176         } else if (RHSValID == -1) {
1177           // Otherwise, it is a copy from the RHS, and we don't already have a
1178           // value# for it.  Keep the current value number, but remember it.
1179           LHSValNoAssignments[VN] = RHSValID = VN;
1180           NewVNInfo[VN] = RHSValNoInfo;
1181           LHSValsDefinedFromRHS[VNI] = RHSValNoInfo0;
1182         } else {
1183           // Otherwise, use the specified value #.
1184           LHSValNoAssignments[VN] = RHSValID;
1185           if (VN == (unsigned)RHSValID) {  // Else this val# is dead.
1186             NewVNInfo[VN] = RHSValNoInfo;
1187             LHSValsDefinedFromRHS[VNI] = RHSValNoInfo0;
1188           }
1189         }
1190       } else {
1191         NewVNInfo[VN] = VNI;
1192         LHSValNoAssignments[VN] = VN;
1193       }
1194     }
1195     
1196     assert(RHSValID != -1 && "Didn't find value #?");
1197     RHSValNoAssignments[0] = RHSValID;
1198     if (RHSVal0DefinedFromLHS != -1) {
1199       // This path doesn't go through ComputeUltimateVN so just set
1200       // it to anything.
1201       RHSValsDefinedFromLHS[RHSValNoInfo0] = (VNInfo*)1;
1202     }
1203   } else {
1204     // Loop over the value numbers of the LHS, seeing if any are defined from
1205     // the RHS.
1206     for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1207          i != e; ++i) {
1208       VNInfo *VNI = *i;
1209       if (VNI->def == ~1U || VNI->copy == 0)  // Src not defined by a copy?
1210         continue;
1211       
1212       // DstReg is known to be a register in the LHS interval.  If the src is
1213       // from the RHS interval, we can use its value #.
1214       if (li_->getVNInfoSourceReg(VNI) != RHS.reg)
1215         continue;
1216       
1217       // Figure out the value # from the RHS.
1218       LHSValsDefinedFromRHS[VNI]=RHS.getLiveRangeContaining(VNI->def-1)->valno;
1219     }
1220     
1221     // Loop over the value numbers of the RHS, seeing if any are defined from
1222     // the LHS.
1223     for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
1224          i != e; ++i) {
1225       VNInfo *VNI = *i;
1226       if (VNI->def == ~1U || VNI->copy == 0)  // Src not defined by a copy?
1227         continue;
1228       
1229       // DstReg is known to be a register in the RHS interval.  If the src is
1230       // from the LHS interval, we can use its value #.
1231       if (li_->getVNInfoSourceReg(VNI) != LHS.reg)
1232         continue;
1233       
1234       // Figure out the value # from the LHS.
1235       RHSValsDefinedFromLHS[VNI]=LHS.getLiveRangeContaining(VNI->def-1)->valno;
1236     }
1237     
1238     LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
1239     RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
1240     NewVNInfo.reserve(LHS.getNumValNums() + RHS.getNumValNums());
1241     
1242     for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1243          i != e; ++i) {
1244       VNInfo *VNI = *i;
1245       unsigned VN = VNI->id;
1246       if (LHSValNoAssignments[VN] >= 0 || VNI->def == ~1U) 
1247         continue;
1248       ComputeUltimateVN(VNI, NewVNInfo,
1249                         LHSValsDefinedFromRHS, RHSValsDefinedFromLHS,
1250                         LHSValNoAssignments, RHSValNoAssignments);
1251     }
1252     for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
1253          i != e; ++i) {
1254       VNInfo *VNI = *i;
1255       unsigned VN = VNI->id;
1256       if (RHSValNoAssignments[VN] >= 0 || VNI->def == ~1U)
1257         continue;
1258       // If this value number isn't a copy from the LHS, it's a new number.
1259       if (RHSValsDefinedFromLHS.find(VNI) == RHSValsDefinedFromLHS.end()) {
1260         NewVNInfo.push_back(VNI);
1261         RHSValNoAssignments[VN] = NewVNInfo.size()-1;
1262         continue;
1263       }
1264       
1265       ComputeUltimateVN(VNI, NewVNInfo,
1266                         RHSValsDefinedFromLHS, LHSValsDefinedFromRHS,
1267                         RHSValNoAssignments, LHSValNoAssignments);
1268     }
1269   }
1270   
1271   // Armed with the mappings of LHS/RHS values to ultimate values, walk the
1272   // interval lists to see if these intervals are coalescable.
1273   LiveInterval::const_iterator I = LHS.begin();
1274   LiveInterval::const_iterator IE = LHS.end();
1275   LiveInterval::const_iterator J = RHS.begin();
1276   LiveInterval::const_iterator JE = RHS.end();
1277   
1278   // Skip ahead until the first place of potential sharing.
1279   if (I->start < J->start) {
1280     I = std::upper_bound(I, IE, J->start);
1281     if (I != LHS.begin()) --I;
1282   } else if (J->start < I->start) {
1283     J = std::upper_bound(J, JE, I->start);
1284     if (J != RHS.begin()) --J;
1285   }
1286   
1287   while (1) {
1288     // Determine if these two live ranges overlap.
1289     bool Overlaps;
1290     if (I->start < J->start) {
1291       Overlaps = I->end > J->start;
1292     } else {
1293       Overlaps = J->end > I->start;
1294     }
1295
1296     // If so, check value # info to determine if they are really different.
1297     if (Overlaps) {
1298       // If the live range overlap will map to the same value number in the
1299       // result liverange, we can still coalesce them.  If not, we can't.
1300       if (LHSValNoAssignments[I->valno->id] !=
1301           RHSValNoAssignments[J->valno->id])
1302         return false;
1303     }
1304     
1305     if (I->end < J->end) {
1306       ++I;
1307       if (I == IE) break;
1308     } else {
1309       ++J;
1310       if (J == JE) break;
1311     }
1312   }
1313
1314   // Update kill info. Some live ranges are extended due to copy coalescing.
1315   for (DenseMap<VNInfo*, VNInfo*>::iterator I = LHSValsDefinedFromRHS.begin(),
1316          E = LHSValsDefinedFromRHS.end(); I != E; ++I) {
1317     VNInfo *VNI = I->first;
1318     unsigned LHSValID = LHSValNoAssignments[VNI->id];
1319     LiveInterval::removeKill(NewVNInfo[LHSValID], VNI->def);
1320     NewVNInfo[LHSValID]->hasPHIKill |= VNI->hasPHIKill;
1321     RHS.addKills(NewVNInfo[LHSValID], VNI->kills);
1322   }
1323
1324   // Update kill info. Some live ranges are extended due to copy coalescing.
1325   for (DenseMap<VNInfo*, VNInfo*>::iterator I = RHSValsDefinedFromLHS.begin(),
1326          E = RHSValsDefinedFromLHS.end(); I != E; ++I) {
1327     VNInfo *VNI = I->first;
1328     unsigned RHSValID = RHSValNoAssignments[VNI->id];
1329     LiveInterval::removeKill(NewVNInfo[RHSValID], VNI->def);
1330     NewVNInfo[RHSValID]->hasPHIKill |= VNI->hasPHIKill;
1331     LHS.addKills(NewVNInfo[RHSValID], VNI->kills);
1332   }
1333
1334   // If we get here, we know that we can coalesce the live ranges.  Ask the
1335   // intervals to coalesce themselves now.
1336   if ((RHS.ranges.size() > LHS.ranges.size() &&
1337       TargetRegisterInfo::isVirtualRegister(LHS.reg)) ||
1338       TargetRegisterInfo::isPhysicalRegister(RHS.reg)) {
1339     RHS.join(LHS, &RHSValNoAssignments[0], &LHSValNoAssignments[0], NewVNInfo);
1340     Swapped = true;
1341   } else {
1342     LHS.join(RHS, &LHSValNoAssignments[0], &RHSValNoAssignments[0], NewVNInfo);
1343     Swapped = false;
1344   }
1345   return true;
1346 }
1347
1348 namespace {
1349   // DepthMBBCompare - Comparison predicate that sort first based on the loop
1350   // depth of the basic block (the unsigned), and then on the MBB number.
1351   struct DepthMBBCompare {
1352     typedef std::pair<unsigned, MachineBasicBlock*> DepthMBBPair;
1353     bool operator()(const DepthMBBPair &LHS, const DepthMBBPair &RHS) const {
1354       if (LHS.first > RHS.first) return true;   // Deeper loops first
1355       return LHS.first == RHS.first &&
1356         LHS.second->getNumber() < RHS.second->getNumber();
1357     }
1358   };
1359 }
1360
1361 /// getRepIntervalSize - Returns the size of the interval that represents the
1362 /// specified register.
1363 template<class SF>
1364 unsigned JoinPriorityQueue<SF>::getRepIntervalSize(unsigned Reg) {
1365   return Rc->getRepIntervalSize(Reg);
1366 }
1367
1368 /// CopyRecSort::operator - Join priority queue sorting function.
1369 ///
1370 bool CopyRecSort::operator()(CopyRec left, CopyRec right) const {
1371   // Inner loops first.
1372   if (left.LoopDepth > right.LoopDepth)
1373     return false;
1374   else if (left.LoopDepth == right.LoopDepth)
1375     if (left.isBackEdge && !right.isBackEdge)
1376       return false;
1377   return true;
1378 }
1379
1380 void SimpleRegisterCoalescing::CopyCoalesceInMBB(MachineBasicBlock *MBB,
1381                                                std::vector<CopyRec> &TryAgain) {
1382   DOUT << ((Value*)MBB->getBasicBlock())->getName() << ":\n";
1383
1384   std::vector<CopyRec> VirtCopies;
1385   std::vector<CopyRec> PhysCopies;
1386   unsigned LoopDepth = loopInfo->getLoopDepth(MBB);
1387   for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end();
1388        MII != E;) {
1389     MachineInstr *Inst = MII++;
1390     
1391     // If this isn't a copy nor a extract_subreg, we can't join intervals.
1392     unsigned SrcReg, DstReg;
1393     if (Inst->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG) {
1394       DstReg = Inst->getOperand(0).getReg();
1395       SrcReg = Inst->getOperand(1).getReg();
1396     } else if (!tii_->isMoveInstr(*Inst, SrcReg, DstReg))
1397       continue;
1398
1399     bool SrcIsPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
1400     bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
1401     if (NewHeuristic) {
1402       JoinQueue->push(CopyRec(Inst, LoopDepth, isBackEdgeCopy(Inst, DstReg)));
1403     } else {
1404       if (SrcIsPhys || DstIsPhys)
1405         PhysCopies.push_back(CopyRec(Inst, 0, false));
1406       else
1407         VirtCopies.push_back(CopyRec(Inst, 0, false));
1408     }
1409   }
1410
1411   if (NewHeuristic)
1412     return;
1413
1414   // Try coalescing physical register + virtual register first.
1415   for (unsigned i = 0, e = PhysCopies.size(); i != e; ++i) {
1416     CopyRec &TheCopy = PhysCopies[i];
1417     bool Again = false;
1418     if (!JoinCopy(TheCopy, Again))
1419       if (Again)
1420         TryAgain.push_back(TheCopy);
1421   }
1422   for (unsigned i = 0, e = VirtCopies.size(); i != e; ++i) {
1423     CopyRec &TheCopy = VirtCopies[i];
1424     bool Again = false;
1425     if (!JoinCopy(TheCopy, Again))
1426       if (Again)
1427         TryAgain.push_back(TheCopy);
1428   }
1429 }
1430
1431 void SimpleRegisterCoalescing::joinIntervals() {
1432   DOUT << "********** JOINING INTERVALS ***********\n";
1433
1434   if (NewHeuristic)
1435     JoinQueue = new JoinPriorityQueue<CopyRecSort>(this);
1436
1437   std::vector<CopyRec> TryAgainList;
1438   if (loopInfo->begin() == loopInfo->end()) {
1439     // If there are no loops in the function, join intervals in function order.
1440     for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();
1441          I != E; ++I)
1442       CopyCoalesceInMBB(I, TryAgainList);
1443   } else {
1444     // Otherwise, join intervals in inner loops before other intervals.
1445     // Unfortunately we can't just iterate over loop hierarchy here because
1446     // there may be more MBB's than BB's.  Collect MBB's for sorting.
1447
1448     // Join intervals in the function prolog first. We want to join physical
1449     // registers with virtual registers before the intervals got too long.
1450     std::vector<std::pair<unsigned, MachineBasicBlock*> > MBBs;
1451     for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();I != E;++I){
1452       MachineBasicBlock *MBB = I;
1453       MBBs.push_back(std::make_pair(loopInfo->getLoopDepth(MBB), I));
1454     }
1455
1456     // Sort by loop depth.
1457     std::sort(MBBs.begin(), MBBs.end(), DepthMBBCompare());
1458
1459     // Finally, join intervals in loop nest order.
1460     for (unsigned i = 0, e = MBBs.size(); i != e; ++i)
1461       CopyCoalesceInMBB(MBBs[i].second, TryAgainList);
1462   }
1463   
1464   // Joining intervals can allow other intervals to be joined.  Iteratively join
1465   // until we make no progress.
1466   if (NewHeuristic) {
1467     SmallVector<CopyRec, 16> TryAgain;
1468     bool ProgressMade = true;
1469     while (ProgressMade) {
1470       ProgressMade = false;
1471       while (!JoinQueue->empty()) {
1472         CopyRec R = JoinQueue->pop();
1473         bool Again = false;
1474         bool Success = JoinCopy(R, Again);
1475         if (Success)
1476           ProgressMade = true;
1477         else if (Again)
1478           TryAgain.push_back(R);
1479       }
1480
1481       if (ProgressMade) {
1482         while (!TryAgain.empty()) {
1483           JoinQueue->push(TryAgain.back());
1484           TryAgain.pop_back();
1485         }
1486       }
1487     }
1488   } else {
1489     bool ProgressMade = true;
1490     while (ProgressMade) {
1491       ProgressMade = false;
1492
1493       for (unsigned i = 0, e = TryAgainList.size(); i != e; ++i) {
1494         CopyRec &TheCopy = TryAgainList[i];
1495         if (TheCopy.MI) {
1496           bool Again = false;
1497           bool Success = JoinCopy(TheCopy, Again);
1498           if (Success || !Again) {
1499             TheCopy.MI = 0;   // Mark this one as done.
1500             ProgressMade = true;
1501           }
1502         }
1503       }
1504     }
1505   }
1506
1507   if (NewHeuristic)
1508     delete JoinQueue;  
1509 }
1510
1511 /// Return true if the two specified registers belong to different register
1512 /// classes.  The registers may be either phys or virt regs.
1513 bool SimpleRegisterCoalescing::differingRegisterClasses(unsigned RegA,
1514                                                         unsigned RegB) const {
1515
1516   // Get the register classes for the first reg.
1517   if (TargetRegisterInfo::isPhysicalRegister(RegA)) {
1518     assert(TargetRegisterInfo::isVirtualRegister(RegB) &&
1519            "Shouldn't consider two physregs!");
1520     return !mri_->getRegClass(RegB)->contains(RegA);
1521   }
1522
1523   // Compare against the regclass for the second reg.
1524   const TargetRegisterClass *RegClass = mri_->getRegClass(RegA);
1525   if (TargetRegisterInfo::isVirtualRegister(RegB))
1526     return RegClass != mri_->getRegClass(RegB);
1527   else
1528     return !RegClass->contains(RegB);
1529 }
1530
1531 /// lastRegisterUse - Returns the last use of the specific register between
1532 /// cycles Start and End or NULL if there are no uses.
1533 MachineOperand *
1534 SimpleRegisterCoalescing::lastRegisterUse(unsigned Start, unsigned End,
1535                                           unsigned Reg, unsigned &UseIdx) const{
1536   UseIdx = 0;
1537   if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1538     MachineOperand *LastUse = NULL;
1539     for (MachineRegisterInfo::use_iterator I = mri_->use_begin(Reg),
1540            E = mri_->use_end(); I != E; ++I) {
1541       MachineOperand &Use = I.getOperand();
1542       MachineInstr *UseMI = Use.getParent();
1543       unsigned Idx = li_->getInstructionIndex(UseMI);
1544       if (Idx >= Start && Idx < End && Idx >= UseIdx) {
1545         LastUse = &Use;
1546         UseIdx = Idx;
1547       }
1548     }
1549     return LastUse;
1550   }
1551
1552   int e = (End-1) / InstrSlots::NUM * InstrSlots::NUM;
1553   int s = Start;
1554   while (e >= s) {
1555     // Skip deleted instructions
1556     MachineInstr *MI = li_->getInstructionFromIndex(e);
1557     while ((e - InstrSlots::NUM) >= s && !MI) {
1558       e -= InstrSlots::NUM;
1559       MI = li_->getInstructionFromIndex(e);
1560     }
1561     if (e < s || MI == NULL)
1562       return NULL;
1563
1564     for (unsigned i = 0, NumOps = MI->getNumOperands(); i != NumOps; ++i) {
1565       MachineOperand &Use = MI->getOperand(i);
1566       if (Use.isRegister() && Use.isUse() && Use.getReg() &&
1567           tri_->regsOverlap(Use.getReg(), Reg)) {
1568         UseIdx = e;
1569         return &Use;
1570       }
1571     }
1572
1573     e -= InstrSlots::NUM;
1574   }
1575
1576   return NULL;
1577 }
1578
1579
1580 void SimpleRegisterCoalescing::printRegName(unsigned reg) const {
1581   if (TargetRegisterInfo::isPhysicalRegister(reg))
1582     cerr << tri_->getName(reg);
1583   else
1584     cerr << "%reg" << reg;
1585 }
1586
1587 void SimpleRegisterCoalescing::releaseMemory() {
1588   JoinedCopies.clear();
1589 }
1590
1591 static bool isZeroLengthInterval(LiveInterval *li) {
1592   for (LiveInterval::Ranges::const_iterator
1593          i = li->ranges.begin(), e = li->ranges.end(); i != e; ++i)
1594     if (i->end - i->start > LiveIntervals::InstrSlots::NUM)
1595       return false;
1596   return true;
1597 }
1598
1599 bool SimpleRegisterCoalescing::runOnMachineFunction(MachineFunction &fn) {
1600   mf_ = &fn;
1601   mri_ = &fn.getRegInfo();
1602   tm_ = &fn.getTarget();
1603   tri_ = tm_->getRegisterInfo();
1604   tii_ = tm_->getInstrInfo();
1605   li_ = &getAnalysis<LiveIntervals>();
1606   lv_ = &getAnalysis<LiveVariables>();
1607   loopInfo = &getAnalysis<MachineLoopInfo>();
1608
1609   DOUT << "********** SIMPLE REGISTER COALESCING **********\n"
1610        << "********** Function: "
1611        << ((Value*)mf_->getFunction())->getName() << '\n';
1612
1613   allocatableRegs_ = tri_->getAllocatableSet(fn);
1614   for (TargetRegisterInfo::regclass_iterator I = tri_->regclass_begin(),
1615          E = tri_->regclass_end(); I != E; ++I)
1616     allocatableRCRegs_.insert(std::make_pair(*I,
1617                                              tri_->getAllocatableSet(fn, *I)));
1618
1619   // Join (coalesce) intervals if requested.
1620   if (EnableJoining) {
1621     joinIntervals();
1622     DOUT << "********** INTERVALS POST JOINING **********\n";
1623     for (LiveIntervals::iterator I = li_->begin(), E = li_->end(); I != E; ++I){
1624       I->second.print(DOUT, tri_);
1625       DOUT << "\n";
1626     }
1627
1628     // Delete all coalesced copies.
1629     for (SmallPtrSet<MachineInstr*,32>::iterator I = JoinedCopies.begin(),
1630            E = JoinedCopies.end(); I != E; ++I) {
1631       MachineInstr *CopyMI = *I;
1632       unsigned SrcReg, DstReg;
1633       tii_->isMoveInstr(*CopyMI, SrcReg, DstReg);
1634       if (CopyMI->registerDefIsDead(DstReg)) {
1635         LiveInterval &li = li_->getInterval(DstReg);
1636         ShortenDeadCopySrcLiveRange(li, CopyMI);
1637         ShortenDeadCopyLiveRange(li, CopyMI);
1638       }
1639       li_->RemoveMachineInstrFromMaps(*I);
1640       (*I)->eraseFromParent();
1641       ++numPeep;
1642     }
1643   }
1644
1645   // Perform a final pass over the instructions and compute spill weights
1646   // and remove identity moves.
1647   for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
1648        mbbi != mbbe; ++mbbi) {
1649     MachineBasicBlock* mbb = mbbi;
1650     unsigned loopDepth = loopInfo->getLoopDepth(mbb);
1651
1652     for (MachineBasicBlock::iterator mii = mbb->begin(), mie = mbb->end();
1653          mii != mie; ) {
1654       // if the move will be an identity move delete it
1655       unsigned srcReg, dstReg;
1656       if (tii_->isMoveInstr(*mii, srcReg, dstReg) && srcReg == dstReg) {
1657         if (li_->hasInterval(srcReg)) {
1658           LiveInterval &RegInt = li_->getInterval(srcReg);
1659           // If def of this move instruction is dead, remove its live range
1660           // from the dstination register's live interval.
1661           if (mii->registerDefIsDead(dstReg)) {
1662             ShortenDeadCopySrcLiveRange(RegInt, mii);
1663             ShortenDeadCopyLiveRange(RegInt, mii);
1664           }
1665         }
1666         li_->RemoveMachineInstrFromMaps(mii);
1667         mii = mbbi->erase(mii);
1668         ++numPeep;
1669       } else {
1670         SmallSet<unsigned, 4> UniqueUses;
1671         for (unsigned i = 0, e = mii->getNumOperands(); i != e; ++i) {
1672           const MachineOperand &mop = mii->getOperand(i);
1673           if (mop.isRegister() && mop.getReg() &&
1674               TargetRegisterInfo::isVirtualRegister(mop.getReg())) {
1675             unsigned reg = mop.getReg();
1676             // Multiple uses of reg by the same instruction. It should not
1677             // contribute to spill weight again.
1678             if (UniqueUses.count(reg) != 0)
1679               continue;
1680             LiveInterval &RegInt = li_->getInterval(reg);
1681             RegInt.weight +=
1682               li_->getSpillWeight(mop.isDef(), mop.isUse(), loopDepth);
1683             UniqueUses.insert(reg);
1684           }
1685         }
1686         ++mii;
1687       }
1688     }
1689   }
1690
1691   for (LiveIntervals::iterator I = li_->begin(), E = li_->end(); I != E; ++I) {
1692     LiveInterval &LI = I->second;
1693     if (TargetRegisterInfo::isVirtualRegister(LI.reg)) {
1694       // If the live interval length is essentially zero, i.e. in every live
1695       // range the use follows def immediately, it doesn't make sense to spill
1696       // it and hope it will be easier to allocate for this li.
1697       if (isZeroLengthInterval(&LI))
1698         LI.weight = HUGE_VALF;
1699       else {
1700         bool isLoad = false;
1701         if (li_->isReMaterializable(LI, isLoad)) {
1702           // If all of the definitions of the interval are re-materializable,
1703           // it is a preferred candidate for spilling. If non of the defs are
1704           // loads, then it's potentially very cheap to re-materialize.
1705           // FIXME: this gets much more complicated once we support non-trivial
1706           // re-materialization.
1707           if (isLoad)
1708             LI.weight *= 0.9F;
1709           else
1710             LI.weight *= 0.5F;
1711         }
1712       }
1713
1714       // Slightly prefer live interval that has been assigned a preferred reg.
1715       if (LI.preference)
1716         LI.weight *= 1.01F;
1717
1718       // Divide the weight of the interval by its size.  This encourages 
1719       // spilling of intervals that are large and have few uses, and
1720       // discourages spilling of small intervals with many uses.
1721       LI.weight /= LI.getSize();
1722     }
1723   }
1724
1725   DEBUG(dump());
1726   return true;
1727 }
1728
1729 /// print - Implement the dump method.
1730 void SimpleRegisterCoalescing::print(std::ostream &O, const Module* m) const {
1731    li_->print(O, m);
1732 }
1733
1734 RegisterCoalescer* llvm::createSimpleRegisterCoalescer() {
1735   return new SimpleRegisterCoalescing();
1736 }
1737
1738 // Make sure that anything that uses RegisterCoalescer pulls in this file...
1739 DEFINING_FILE_FOR(SimpleRegisterCoalescing)