No need to remove dead range from soon-to-be-dead live interval. Its val# may be...
[oota-llvm.git] / lib / CodeGen / SimpleRegisterCoalescing.cpp
1 //===-- SimpleRegisterCoalescing.cpp - Register Coalescing ----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source 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 "llvm/CodeGen/SimpleRegisterCoalescing.h"
17 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
18 #include "VirtRegMap.h"
19 #include "llvm/Value.h"
20 #include "llvm/Analysis/LoopInfo.h"
21 #include "llvm/CodeGen/LiveVariables.h"
22 #include "llvm/CodeGen/MachineFrameInfo.h"
23 #include "llvm/CodeGen/MachineInstr.h"
24 #include "llvm/CodeGen/Passes.h"
25 #include "llvm/CodeGen/SSARegMap.h"
26 #include "llvm/Target/MRegisterInfo.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(numPeep     , "Number of identity moves eliminated after coalescing");
40 STATISTIC(numAborts   , "Number of times interval joining aborted");
41
42 char SimpleRegisterCoalescing::ID = 0;
43 namespace {
44   static cl::opt<bool>
45   EnableJoining("join-liveintervals",
46                 cl::desc("Coalesce copies (default=true)"),
47                 cl::init(true));
48
49   RegisterPass<SimpleRegisterCoalescing> 
50   X("simple-register-coalescing", "Simple Register Coalescing");
51 }
52
53 const PassInfo *llvm::SimpleRegisterCoalescingID = X.getPassInfo();
54
55 void SimpleRegisterCoalescing::getAnalysisUsage(AnalysisUsage &AU) const {
56    //AU.addPreserved<LiveVariables>();
57   AU.addPreserved<LiveIntervals>();
58   AU.addPreservedID(PHIEliminationID);
59   AU.addPreservedID(TwoAddressInstructionPassID);
60   AU.addRequired<LiveVariables>();
61   AU.addRequired<LiveIntervals>();
62   AU.addRequired<LoopInfo>();
63   MachineFunctionPass::getAnalysisUsage(AU);
64 }
65
66 /// AdjustCopiesBackFrom - We found a non-trivially-coalescable copy with IntA
67 /// being the source and IntB being the dest, thus this defines a value number
68 /// in IntB.  If the source value number (in IntA) is defined by a copy from B,
69 /// see if we can merge these two pieces of B into a single value number,
70 /// eliminating a copy.  For example:
71 ///
72 ///  A3 = B0
73 ///    ...
74 ///  B1 = A3      <- this copy
75 ///
76 /// In this case, B0 can be extended to where the B1 copy lives, allowing the B1
77 /// value number to be replaced with B0 (which simplifies the B liveinterval).
78 ///
79 /// This returns true if an interval was modified.
80 ///
81 bool SimpleRegisterCoalescing::AdjustCopiesBackFrom(LiveInterval &IntA, LiveInterval &IntB,
82                                          MachineInstr *CopyMI) {
83   unsigned CopyIdx = li_->getDefIndex(li_->getInstructionIndex(CopyMI));
84
85   // BValNo is a value number in B that is defined by a copy from A.  'B3' in
86   // the example above.
87   LiveInterval::iterator BLR = IntB.FindLiveRangeContaining(CopyIdx);
88   unsigned BValNo = BLR->ValId;
89   
90   // Get the location that B is defined at.  Two options: either this value has
91   // an unknown definition point or it is defined at CopyIdx.  If unknown, we 
92   // can't process it.
93   unsigned BValNoDefIdx = IntB.getDefForValNum(BValNo);
94   if (!IntB.getSrcRegForValNum(BValNo)) return false;
95   assert(BValNoDefIdx == CopyIdx &&
96          "Copy doesn't define the value?");
97   
98   // AValNo is the value number in A that defines the copy, A0 in the example.
99   LiveInterval::iterator AValLR = IntA.FindLiveRangeContaining(CopyIdx-1);
100   unsigned AValNo = AValLR->ValId;
101   
102   // If AValNo is defined as a copy from IntB, we can potentially process this.
103   
104   // Get the instruction that defines this value number.
105   unsigned SrcReg = IntA.getSrcRegForValNum(AValNo);
106   if (!SrcReg) return false;  // Not defined by a copy.
107     
108   // If the value number is not defined by a copy instruction, ignore it.
109     
110   // If the source register comes from an interval other than IntB, we can't
111   // handle this.
112   if (rep(SrcReg) != IntB.reg) return false;
113   
114   // Get the LiveRange in IntB that this value number starts with.
115   unsigned AValNoInstIdx = IntA.getDefForValNum(AValNo);
116   LiveInterval::iterator ValLR = IntB.FindLiveRangeContaining(AValNoInstIdx-1);
117   
118   // Make sure that the end of the live range is inside the same block as
119   // CopyMI.
120   MachineInstr *ValLREndInst = li_->getInstructionFromIndex(ValLR->end-1);
121   if (!ValLREndInst || 
122       ValLREndInst->getParent() != CopyMI->getParent()) return false;
123
124   // Okay, we now know that ValLR ends in the same block that the CopyMI
125   // live-range starts.  If there are no intervening live ranges between them in
126   // IntB, we can merge them.
127   if (ValLR+1 != BLR) return false;
128   
129   DOUT << "\nExtending: "; IntB.print(DOUT, mri_);
130   
131   unsigned FillerStart = ValLR->end, FillerEnd = BLR->start;
132   // We are about to delete CopyMI, so need to remove it as the 'instruction
133   // that defines this value #'. Update the the valnum with the new defining
134   // instruction #.
135   IntB.setDefForValNum(BValNo, FillerStart);
136   IntB.setSrcRegForValNum(BValNo, 0);
137   
138   // Okay, we can merge them.  We need to insert a new liverange:
139   // [ValLR.end, BLR.begin) of either value number, then we merge the
140   // two value numbers.
141   IntB.addRange(LiveRange(FillerStart, FillerEnd, BValNo));
142
143   // If the IntB live range is assigned to a physical register, and if that
144   // physreg has aliases, 
145   if (MRegisterInfo::isPhysicalRegister(IntB.reg)) {
146     // Update the liveintervals of sub-registers.
147     for (const unsigned *AS = mri_->getSubRegisters(IntB.reg); *AS; ++AS) {
148       LiveInterval &AliasLI = li_->getInterval(*AS);
149       AliasLI.addRange(LiveRange(FillerStart, FillerEnd,
150                                  AliasLI.getNextValue(FillerStart, 0)));
151     }
152   }
153
154   // Okay, merge "B1" into the same value number as "B0".
155   if (BValNo != ValLR->ValId)
156     IntB.MergeValueNumberInto(BValNo, ValLR->ValId);
157   DOUT << "   result = "; IntB.print(DOUT, mri_);
158   DOUT << "\n";
159
160   // If the source instruction was killing the source register before the
161   // merge, unset the isKill marker given the live range has been extended.
162   int UIdx = ValLREndInst->findRegisterUseOperandIdx(IntB.reg, true);
163   if (UIdx != -1)
164     ValLREndInst->getOperand(UIdx).unsetIsKill();
165   
166   // Finally, delete the copy instruction.
167   li_->RemoveMachineInstrFromMaps(CopyMI);
168   CopyMI->eraseFromParent();
169   ++numPeep;
170   return true;
171 }
172
173 /// JoinCopy - Attempt to join intervals corresponding to SrcReg/DstReg,
174 /// which are the src/dst of the copy instruction CopyMI.  This returns true
175 /// if the copy was successfully coalesced away, or if it is never possible
176 /// to coalesce this copy, due to register constraints.  It returns
177 /// false if it is not currently possible to coalesce this interval, but
178 /// it may be possible if other things get coalesced.
179 bool SimpleRegisterCoalescing::JoinCopy(MachineInstr *CopyMI,
180                              unsigned SrcReg, unsigned DstReg, bool PhysOnly) {
181   DOUT << li_->getInstructionIndex(CopyMI) << '\t' << *CopyMI;
182
183   // Get representative registers.
184   unsigned repSrcReg = rep(SrcReg);
185   unsigned repDstReg = rep(DstReg);
186   
187   // If they are already joined we continue.
188   if (repSrcReg == repDstReg) {
189     DOUT << "\tCopy already coalesced.\n";
190     return true;  // Not coalescable.
191   }
192   
193   bool SrcIsPhys = MRegisterInfo::isPhysicalRegister(repSrcReg);
194   bool DstIsPhys = MRegisterInfo::isPhysicalRegister(repDstReg);
195   if (PhysOnly && !SrcIsPhys && !DstIsPhys)
196     // Only joining physical registers with virtual registers in this round.
197     return true;
198
199   // If they are both physical registers, we cannot join them.
200   if (SrcIsPhys && DstIsPhys) {
201     DOUT << "\tCan not coalesce physregs.\n";
202     return true;  // Not coalescable.
203   }
204   
205   // We only join virtual registers with allocatable physical registers.
206   if (SrcIsPhys && !allocatableRegs_[repSrcReg]) {
207     DOUT << "\tSrc reg is unallocatable physreg.\n";
208     return true;  // Not coalescable.
209   }
210   if (DstIsPhys && !allocatableRegs_[repDstReg]) {
211     DOUT << "\tDst reg is unallocatable physreg.\n";
212     return true;  // Not coalescable.
213   }
214   
215   // If they are not of the same register class, we cannot join them.
216   if (differingRegisterClasses(repSrcReg, repDstReg)) {
217     DOUT << "\tSrc/Dest are different register classes.\n";
218     return true;  // Not coalescable.
219   }
220   
221   LiveInterval &SrcInt = li_->getInterval(repSrcReg);
222   LiveInterval &DstInt = li_->getInterval(repDstReg);
223   assert(SrcInt.reg == repSrcReg && DstInt.reg == repDstReg &&
224          "Register mapping is horribly broken!");
225
226   DOUT << "\t\tInspecting "; SrcInt.print(DOUT, mri_);
227   DOUT << " and "; DstInt.print(DOUT, mri_);
228   DOUT << ": ";
229
230   // Check if it is necessary to propagate "isDead" property before intervals
231   // are joined.
232   MachineOperand *mopd = CopyMI->findRegisterDefOperand(DstReg);
233   bool isDead = mopd->isDead();
234   bool isShorten = false;
235   unsigned SrcStart = 0, RemoveStart = 0;
236   unsigned SrcEnd = 0, RemoveEnd = 0;
237   if (isDead) {
238     unsigned CopyIdx = li_->getInstructionIndex(CopyMI);
239     LiveInterval::iterator SrcLR =
240       SrcInt.FindLiveRangeContaining(li_->getUseIndex(CopyIdx));
241     RemoveStart = SrcStart = SrcLR->start;
242     RemoveEnd   = SrcEnd   = SrcLR->end;
243     // The instruction which defines the src is only truly dead if there are
244     // no intermediate uses and there isn't a use beyond the copy.
245     // FIXME: find the last use, mark is kill and shorten the live range.
246     if (SrcEnd > li_->getDefIndex(CopyIdx)) {
247       isDead = false;
248     } else {
249       MachineOperand *MOU;
250       MachineInstr *LastUse= lastRegisterUse(SrcStart, CopyIdx, repSrcReg, MOU);
251       if (LastUse) {
252         // Shorten the liveinterval to the end of last use.
253         MOU->setIsKill();
254         isDead = false;
255         isShorten = true;
256         RemoveStart = li_->getDefIndex(li_->getInstructionIndex(LastUse));
257         RemoveEnd   = SrcEnd;
258       } else {
259         MachineInstr *SrcMI = li_->getInstructionFromIndex(SrcStart);
260         if (SrcMI) {
261           MachineOperand *mops = findDefOperand(SrcMI, repSrcReg);
262           if (mops)
263             // A dead def should have a single cycle interval.
264             ++RemoveStart;
265         }
266       }
267     }
268   }
269
270   // We need to be careful about coalescing a source physical register with a
271   // virtual register. Once the coalescing is done, it cannot be broken and
272   // these are not spillable! If the destination interval uses are far away,
273   // think twice about coalescing them!
274   if (!mopd->isDead() && (SrcIsPhys || DstIsPhys)) {
275     LiveInterval &JoinVInt = SrcIsPhys ? DstInt : SrcInt;
276     unsigned JoinVReg = SrcIsPhys ? repDstReg : repSrcReg;
277     unsigned JoinPReg = SrcIsPhys ? repSrcReg : repDstReg;
278     const TargetRegisterClass *RC = mf_->getSSARegMap()->getRegClass(JoinVReg);
279     unsigned Threshold = allocatableRCRegs_[RC].count();
280
281     // If the virtual register live interval is long has it has low use desity,
282     // do not join them, instead mark the physical register as its allocation
283     // preference.
284     unsigned Length = JoinVInt.getSize() / InstrSlots::NUM;
285     LiveVariables::VarInfo &vi = lv_->getVarInfo(JoinVReg);
286     if (Length > Threshold &&
287         (((float)vi.NumUses / Length) < (1.0 / Threshold))) {
288       JoinVInt.preference = JoinPReg;
289       ++numAborts;
290       DOUT << "\tMay tie down a physical register, abort!\n";
291       return false;
292     }
293   }
294
295   // Okay, attempt to join these two intervals.  On failure, this returns false.
296   // Otherwise, if one of the intervals being joined is a physreg, this method
297   // always canonicalizes DstInt to be it.  The output "SrcInt" will not have
298   // been modified, so we can use this information below to update aliases.
299   if (JoinIntervals(DstInt, SrcInt)) {
300     if (isDead) {
301       // Result of the copy is dead. Propagate this property.
302       if (SrcStart == 0) {
303         assert(MRegisterInfo::isPhysicalRegister(repSrcReg) &&
304                "Live-in must be a physical register!");
305         // Live-in to the function but dead. Remove it from entry live-in set.
306         // JoinIntervals may end up swapping the two intervals.
307         mf_->begin()->removeLiveIn(repSrcReg);
308       } else {
309         MachineInstr *SrcMI = li_->getInstructionFromIndex(SrcStart);
310         if (SrcMI) {
311           MachineOperand *mops = findDefOperand(SrcMI, repSrcReg);
312           if (mops)
313             mops->setIsDead();
314         }
315       }
316     }
317
318     if (isShorten || isDead) {
319       // Shorten the destination live interval.
320       if (repSrcReg == DstInt.reg)
321         DstInt.removeRange(RemoveStart, RemoveEnd);
322     }
323   } else {
324     // Coalescing failed.
325     
326     // If we can eliminate the copy without merging the live ranges, do so now.
327     if (AdjustCopiesBackFrom(SrcInt, DstInt, CopyMI))
328       return true;
329
330     // Otherwise, we are unable to join the intervals.
331     DOUT << "Interference!\n";
332     return false;
333   }
334
335   bool Swapped = repSrcReg == DstInt.reg;
336   if (Swapped)
337     std::swap(repSrcReg, repDstReg);
338   assert(MRegisterInfo::isVirtualRegister(repSrcReg) &&
339          "LiveInterval::join didn't work right!");
340                                
341   // If we're about to merge live ranges into a physical register live range,
342   // we have to update any aliased register's live ranges to indicate that they
343   // have clobbered values for this range.
344   if (MRegisterInfo::isPhysicalRegister(repDstReg)) {
345     // Unset unnecessary kills.
346     if (!DstInt.containsOneValue()) {
347       for (LiveInterval::Ranges::const_iterator I = SrcInt.begin(),
348              E = SrcInt.end(); I != E; ++I)
349         unsetRegisterKills(I->start, I->end, repDstReg);
350     }
351
352     // Update the liveintervals of sub-registers.
353     for (const unsigned *AS = mri_->getSubRegisters(repDstReg); *AS; ++AS)
354       li_->getInterval(*AS).MergeInClobberRanges(SrcInt);
355   } else {
356     // Merge use info if the destination is a virtual register.
357     LiveVariables::VarInfo& dVI = lv_->getVarInfo(repDstReg);
358     LiveVariables::VarInfo& sVI = lv_->getVarInfo(repSrcReg);
359     dVI.NumUses += sVI.NumUses;
360   }
361
362   DOUT << "\n\t\tJoined.  Result = "; DstInt.print(DOUT, mri_);
363   DOUT << "\n";
364
365   // Remember these liveintervals have been joined.
366   JoinedLIs.set(repSrcReg - MRegisterInfo::FirstVirtualRegister);
367   if (MRegisterInfo::isVirtualRegister(repDstReg))
368     JoinedLIs.set(repDstReg - MRegisterInfo::FirstVirtualRegister);
369
370   // If the intervals were swapped by Join, swap them back so that the register
371   // mapping (in the r2i map) is correct.
372   if (Swapped) SrcInt.swap(DstInt);
373
374   // repSrcReg is guarateed to be the register whose live interval that is
375   // being merged.
376   li_->removeInterval(repSrcReg);
377   r2rMap_[repSrcReg] = repDstReg;
378
379   // Finally, delete the copy instruction.
380   li_->RemoveMachineInstrFromMaps(CopyMI);
381   CopyMI->eraseFromParent();
382   ++numPeep;
383   ++numJoins;
384   return true;
385 }
386
387 /// ComputeUltimateVN - Assuming we are going to join two live intervals,
388 /// compute what the resultant value numbers for each value in the input two
389 /// ranges will be.  This is complicated by copies between the two which can
390 /// and will commonly cause multiple value numbers to be merged into one.
391 ///
392 /// VN is the value number that we're trying to resolve.  InstDefiningValue
393 /// keeps track of the new InstDefiningValue assignment for the result
394 /// LiveInterval.  ThisFromOther/OtherFromThis are sets that keep track of
395 /// whether a value in this or other is a copy from the opposite set.
396 /// ThisValNoAssignments/OtherValNoAssignments keep track of value #'s that have
397 /// already been assigned.
398 ///
399 /// ThisFromOther[x] - If x is defined as a copy from the other interval, this
400 /// contains the value number the copy is from.
401 ///
402 static unsigned ComputeUltimateVN(unsigned VN,
403                         SmallVector<LiveInterval::VNInfo, 16> &ValueNumberInfo,
404                                   SmallVector<int, 16> &ThisFromOther,
405                                   SmallVector<int, 16> &OtherFromThis,
406                                   SmallVector<int, 16> &ThisValNoAssignments,
407                                   SmallVector<int, 16> &OtherValNoAssignments,
408                                   LiveInterval &ThisLI, LiveInterval &OtherLI) {
409   // If the VN has already been computed, just return it.
410   if (ThisValNoAssignments[VN] >= 0)
411     return ThisValNoAssignments[VN];
412 //  assert(ThisValNoAssignments[VN] != -2 && "Cyclic case?");
413   
414   // If this val is not a copy from the other val, then it must be a new value
415   // number in the destination.
416   int OtherValNo = ThisFromOther[VN];
417   if (OtherValNo == -1) {
418     ValueNumberInfo.push_back(ThisLI.getValNumInfo(VN));
419     return ThisValNoAssignments[VN] = ValueNumberInfo.size()-1;
420   }
421
422   // Otherwise, this *is* a copy from the RHS.  If the other side has already
423   // been computed, return it.
424   if (OtherValNoAssignments[OtherValNo] >= 0)
425     return ThisValNoAssignments[VN] = OtherValNoAssignments[OtherValNo];
426   
427   // Mark this value number as currently being computed, then ask what the
428   // ultimate value # of the other value is.
429   ThisValNoAssignments[VN] = -2;
430   unsigned UltimateVN =
431     ComputeUltimateVN(OtherValNo, ValueNumberInfo,
432                       OtherFromThis, ThisFromOther,
433                       OtherValNoAssignments, ThisValNoAssignments,
434                       OtherLI, ThisLI);
435   return ThisValNoAssignments[VN] = UltimateVN;
436 }
437
438 static bool InVector(unsigned Val, const SmallVector<unsigned, 8> &V) {
439   return std::find(V.begin(), V.end(), Val) != V.end();
440 }
441
442 /// SimpleJoin - Attempt to joint the specified interval into this one. The
443 /// caller of this method must guarantee that the RHS only contains a single
444 /// value number and that the RHS is not defined by a copy from this
445 /// interval.  This returns false if the intervals are not joinable, or it
446 /// joins them and returns true.
447 bool SimpleRegisterCoalescing::SimpleJoin(LiveInterval &LHS, LiveInterval &RHS) {
448   assert(RHS.containsOneValue());
449   
450   // Some number (potentially more than one) value numbers in the current
451   // interval may be defined as copies from the RHS.  Scan the overlapping
452   // portions of the LHS and RHS, keeping track of this and looking for
453   // overlapping live ranges that are NOT defined as copies.  If these exist, we
454   // cannot coalesce.
455   
456   LiveInterval::iterator LHSIt = LHS.begin(), LHSEnd = LHS.end();
457   LiveInterval::iterator RHSIt = RHS.begin(), RHSEnd = RHS.end();
458   
459   if (LHSIt->start < RHSIt->start) {
460     LHSIt = std::upper_bound(LHSIt, LHSEnd, RHSIt->start);
461     if (LHSIt != LHS.begin()) --LHSIt;
462   } else if (RHSIt->start < LHSIt->start) {
463     RHSIt = std::upper_bound(RHSIt, RHSEnd, LHSIt->start);
464     if (RHSIt != RHS.begin()) --RHSIt;
465   }
466   
467   SmallVector<unsigned, 8> EliminatedLHSVals;
468   
469   while (1) {
470     // Determine if these live intervals overlap.
471     bool Overlaps = false;
472     if (LHSIt->start <= RHSIt->start)
473       Overlaps = LHSIt->end > RHSIt->start;
474     else
475       Overlaps = RHSIt->end > LHSIt->start;
476     
477     // If the live intervals overlap, there are two interesting cases: if the
478     // LHS interval is defined by a copy from the RHS, it's ok and we record
479     // that the LHS value # is the same as the RHS.  If it's not, then we cannot
480     // coalesce these live ranges and we bail out.
481     if (Overlaps) {
482       // If we haven't already recorded that this value # is safe, check it.
483       if (!InVector(LHSIt->ValId, EliminatedLHSVals)) {
484         // Copy from the RHS?
485         unsigned SrcReg = LHS.getSrcRegForValNum(LHSIt->ValId);
486         if (rep(SrcReg) != RHS.reg)
487           return false;    // Nope, bail out.
488         
489         EliminatedLHSVals.push_back(LHSIt->ValId);
490       }
491       
492       // We know this entire LHS live range is okay, so skip it now.
493       if (++LHSIt == LHSEnd) break;
494       continue;
495     }
496     
497     if (LHSIt->end < RHSIt->end) {
498       if (++LHSIt == LHSEnd) break;
499     } else {
500       // One interesting case to check here.  It's possible that we have
501       // something like "X3 = Y" which defines a new value number in the LHS,
502       // and is the last use of this liverange of the RHS.  In this case, we
503       // want to notice this copy (so that it gets coalesced away) even though
504       // the live ranges don't actually overlap.
505       if (LHSIt->start == RHSIt->end) {
506         if (InVector(LHSIt->ValId, EliminatedLHSVals)) {
507           // We already know that this value number is going to be merged in
508           // if coalescing succeeds.  Just skip the liverange.
509           if (++LHSIt == LHSEnd) break;
510         } else {
511           // Otherwise, if this is a copy from the RHS, mark it as being merged
512           // in.
513           if (rep(LHS.getSrcRegForValNum(LHSIt->ValId)) == RHS.reg) {
514             EliminatedLHSVals.push_back(LHSIt->ValId);
515
516             // We know this entire LHS live range is okay, so skip it now.
517             if (++LHSIt == LHSEnd) break;
518           }
519         }
520       }
521       
522       if (++RHSIt == RHSEnd) break;
523     }
524   }
525   
526   // If we got here, we know that the coalescing will be successful and that
527   // the value numbers in EliminatedLHSVals will all be merged together.  Since
528   // the most common case is that EliminatedLHSVals has a single number, we
529   // optimize for it: if there is more than one value, we merge them all into
530   // the lowest numbered one, then handle the interval as if we were merging
531   // with one value number.
532   unsigned LHSValNo;
533   if (EliminatedLHSVals.size() > 1) {
534     // Loop through all the equal value numbers merging them into the smallest
535     // one.
536     unsigned Smallest = EliminatedLHSVals[0];
537     for (unsigned i = 1, e = EliminatedLHSVals.size(); i != e; ++i) {
538       if (EliminatedLHSVals[i] < Smallest) {
539         // Merge the current notion of the smallest into the smaller one.
540         LHS.MergeValueNumberInto(Smallest, EliminatedLHSVals[i]);
541         Smallest = EliminatedLHSVals[i];
542       } else {
543         // Merge into the smallest.
544         LHS.MergeValueNumberInto(EliminatedLHSVals[i], Smallest);
545       }
546     }
547     LHSValNo = Smallest;
548   } else {
549     assert(!EliminatedLHSVals.empty() && "No copies from the RHS?");
550     LHSValNo = EliminatedLHSVals[0];
551   }
552   
553   // Okay, now that there is a single LHS value number that we're merging the
554   // RHS into, update the value number info for the LHS to indicate that the
555   // value number is defined where the RHS value number was.
556   const LiveInterval::VNInfo VNI = RHS.getValNumInfo(0);
557   LHS.setDefForValNum(LHSValNo, VNI.def);
558   LHS.setSrcRegForValNum(LHSValNo, VNI.reg);
559   
560   // Okay, the final step is to loop over the RHS live intervals, adding them to
561   // the LHS.
562   LHS.MergeRangesInAsValue(RHS, LHSValNo);
563   LHS.addKillsForValNum(LHSValNo, VNI.kills);
564   LHS.weight += RHS.weight;
565   if (RHS.preference && !LHS.preference)
566     LHS.preference = RHS.preference;
567   
568   return true;
569 }
570
571 /// JoinIntervals - Attempt to join these two intervals.  On failure, this
572 /// returns false.  Otherwise, if one of the intervals being joined is a
573 /// physreg, this method always canonicalizes LHS to be it.  The output
574 /// "RHS" will not have been modified, so we can use this information
575 /// below to update aliases.
576 bool SimpleRegisterCoalescing::JoinIntervals(LiveInterval &LHS, LiveInterval &RHS) {
577   // Compute the final value assignment, assuming that the live ranges can be
578   // coalesced.
579   SmallVector<int, 16> LHSValNoAssignments;
580   SmallVector<int, 16> RHSValNoAssignments;
581   SmallVector<int, 16> LHSValsDefinedFromRHS;
582   SmallVector<int, 16> RHSValsDefinedFromLHS;
583   SmallVector<LiveInterval::VNInfo, 16> ValueNumberInfo;
584                           
585   // If a live interval is a physical register, conservatively check if any
586   // of its sub-registers is overlapping the live interval of the virtual
587   // register. If so, do not coalesce.
588   if (MRegisterInfo::isPhysicalRegister(LHS.reg) &&
589       *mri_->getSubRegisters(LHS.reg)) {
590     for (const unsigned* SR = mri_->getSubRegisters(LHS.reg); *SR; ++SR)
591       if (li_->hasInterval(*SR) && RHS.overlaps(li_->getInterval(*SR))) {
592         DOUT << "Interfere with sub-register ";
593         DEBUG(li_->getInterval(*SR).print(DOUT, mri_));
594         return false;
595       }
596   } else if (MRegisterInfo::isPhysicalRegister(RHS.reg) &&
597              *mri_->getSubRegisters(RHS.reg)) {
598     for (const unsigned* SR = mri_->getSubRegisters(RHS.reg); *SR; ++SR)
599       if (li_->hasInterval(*SR) && LHS.overlaps(li_->getInterval(*SR))) {
600         DOUT << "Interfere with sub-register ";
601         DEBUG(li_->getInterval(*SR).print(DOUT, mri_));
602         return false;
603       }
604   }
605                           
606   // Compute ultimate value numbers for the LHS and RHS values.
607   if (RHS.containsOneValue()) {
608     // Copies from a liveinterval with a single value are simple to handle and
609     // very common, handle the special case here.  This is important, because
610     // often RHS is small and LHS is large (e.g. a physreg).
611     
612     // Find out if the RHS is defined as a copy from some value in the LHS.
613     int RHSVal0DefinedFromLHS = -1;
614     int RHSValID = -1;
615     LiveInterval::VNInfo RHSValNoInfo;
616     unsigned RHSSrcReg = RHS.getSrcRegForValNum(0);
617     if ((RHSSrcReg == 0 || rep(RHSSrcReg) != LHS.reg)) {
618       // If RHS is not defined as a copy from the LHS, we can use simpler and
619       // faster checks to see if the live ranges are coalescable.  This joiner
620       // can't swap the LHS/RHS intervals though.
621       if (!MRegisterInfo::isPhysicalRegister(RHS.reg)) {
622         return SimpleJoin(LHS, RHS);
623       } else {
624         RHSValNoInfo = RHS.getValNumInfo(0);
625       }
626     } else {
627       // It was defined as a copy from the LHS, find out what value # it is.
628       unsigned ValInst = RHS.getDefForValNum(0);
629       RHSValID = LHS.getLiveRangeContaining(ValInst-1)->ValId;
630       RHSValNoInfo = LHS.getValNumInfo(RHSValID);
631       RHSVal0DefinedFromLHS = RHSValID;
632     }
633     
634     LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
635     RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
636     ValueNumberInfo.resize(LHS.getNumValNums());
637     
638     // Okay, *all* of the values in LHS that are defined as a copy from RHS
639     // should now get updated.
640     for (unsigned VN = 0, e = LHS.getNumValNums(); VN != e; ++VN) {
641       if (unsigned LHSSrcReg = LHS.getSrcRegForValNum(VN)) {
642         if (rep(LHSSrcReg) != RHS.reg) {
643           // If this is not a copy from the RHS, its value number will be
644           // unmodified by the coalescing.
645           ValueNumberInfo[VN] = LHS.getValNumInfo(VN);
646           LHSValNoAssignments[VN] = VN;
647         } else if (RHSValID == -1) {
648           // Otherwise, it is a copy from the RHS, and we don't already have a
649           // value# for it.  Keep the current value number, but remember it.
650           LHSValNoAssignments[VN] = RHSValID = VN;
651           ValueNumberInfo[VN] = RHSValNoInfo;
652           RHS.addKills(ValueNumberInfo[VN], LHS.getKillsForValNum(VN));
653         } else {
654           // Otherwise, use the specified value #.
655           LHSValNoAssignments[VN] = RHSValID;
656           if (VN != (unsigned)RHSValID)
657             ValueNumberInfo[VN].def = ~1U;  // Now this val# is dead.
658           else {
659             ValueNumberInfo[VN] = RHSValNoInfo;
660             RHS.addKills(ValueNumberInfo[VN], LHS.getKillsForValNum(VN));
661           }
662         }
663       } else {
664         ValueNumberInfo[VN] = LHS.getValNumInfo(VN);
665         LHSValNoAssignments[VN] = VN;
666       }
667     }
668     
669     assert(RHSValID != -1 && "Didn't find value #?");
670     RHSValNoAssignments[0] = RHSValID;
671     if (RHSVal0DefinedFromLHS != -1) {
672       int LHSValId = LHSValNoAssignments[RHSVal0DefinedFromLHS];
673       LHS.addKills(ValueNumberInfo[LHSValId], RHS.getKillsForValNum(0));
674     }
675   } else {
676     // Loop over the value numbers of the LHS, seeing if any are defined from
677     // the RHS.
678     LHSValsDefinedFromRHS.resize(LHS.getNumValNums(), -1);
679     for (unsigned VN = 0, e = LHS.getNumValNums(); VN != e; ++VN) {
680       unsigned ValSrcReg = LHS.getSrcRegForValNum(VN);
681       if (ValSrcReg == 0)  // Src not defined by a copy?
682         continue;
683       
684       // DstReg is known to be a register in the LHS interval.  If the src is
685       // from the RHS interval, we can use its value #.
686       if (rep(ValSrcReg) != RHS.reg)
687         continue;
688       
689       // Figure out the value # from the RHS.
690       unsigned ValInst = LHS.getDefForValNum(VN);
691       LHSValsDefinedFromRHS[VN] = RHS.getLiveRangeContaining(ValInst-1)->ValId;
692     }
693     
694     // Loop over the value numbers of the RHS, seeing if any are defined from
695     // the LHS.
696     RHSValsDefinedFromLHS.resize(RHS.getNumValNums(), -1);
697     for (unsigned VN = 0, e = RHS.getNumValNums(); VN != e; ++VN) {
698       unsigned ValSrcReg = RHS.getSrcRegForValNum(VN);
699       if (ValSrcReg == 0)  // Src not defined by a copy?
700         continue;
701       
702       // DstReg is known to be a register in the RHS interval.  If the src is
703       // from the LHS interval, we can use its value #.
704       if (rep(ValSrcReg) != LHS.reg)
705         continue;
706       
707       // Figure out the value # from the LHS.
708       unsigned ValInst = RHS.getDefForValNum(VN);
709       RHSValsDefinedFromLHS[VN] = LHS.getLiveRangeContaining(ValInst-1)->ValId;
710     }
711     
712     LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
713     RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
714     ValueNumberInfo.reserve(LHS.getNumValNums() + RHS.getNumValNums());
715     
716     for (unsigned VN = 0, e = LHS.getNumValNums(); VN != e; ++VN) {
717       if (LHSValNoAssignments[VN] >= 0 || LHS.getDefForValNum(VN) == ~1U) 
718         continue;
719       ComputeUltimateVN(VN, ValueNumberInfo,
720                         LHSValsDefinedFromRHS, RHSValsDefinedFromLHS,
721                         LHSValNoAssignments, RHSValNoAssignments, LHS, RHS);
722     }
723     for (unsigned VN = 0, e = RHS.getNumValNums(); VN != e; ++VN) {
724       if (RHSValNoAssignments[VN] >= 0 || RHS.getDefForValNum(VN) == ~1U)
725         continue;
726       // If this value number isn't a copy from the LHS, it's a new number.
727       if (RHSValsDefinedFromLHS[VN] == -1) {
728         ValueNumberInfo.push_back(RHS.getValNumInfo(VN));
729         RHSValNoAssignments[VN] = ValueNumberInfo.size()-1;
730         continue;
731       }
732       
733       ComputeUltimateVN(VN, ValueNumberInfo,
734                         RHSValsDefinedFromLHS, LHSValsDefinedFromRHS,
735                         RHSValNoAssignments, LHSValNoAssignments, RHS, LHS);
736     }
737   }
738   
739   // Armed with the mappings of LHS/RHS values to ultimate values, walk the
740   // interval lists to see if these intervals are coalescable.
741   LiveInterval::const_iterator I = LHS.begin();
742   LiveInterval::const_iterator IE = LHS.end();
743   LiveInterval::const_iterator J = RHS.begin();
744   LiveInterval::const_iterator JE = RHS.end();
745   
746   // Skip ahead until the first place of potential sharing.
747   if (I->start < J->start) {
748     I = std::upper_bound(I, IE, J->start);
749     if (I != LHS.begin()) --I;
750   } else if (J->start < I->start) {
751     J = std::upper_bound(J, JE, I->start);
752     if (J != RHS.begin()) --J;
753   }
754   
755   while (1) {
756     // Determine if these two live ranges overlap.
757     bool Overlaps;
758     if (I->start < J->start) {
759       Overlaps = I->end > J->start;
760     } else {
761       Overlaps = J->end > I->start;
762     }
763
764     // If so, check value # info to determine if they are really different.
765     if (Overlaps) {
766       // If the live range overlap will map to the same value number in the
767       // result liverange, we can still coalesce them.  If not, we can't.
768       if (LHSValNoAssignments[I->ValId] != RHSValNoAssignments[J->ValId])
769         return false;
770     }
771     
772     if (I->end < J->end) {
773       ++I;
774       if (I == IE) break;
775     } else {
776       ++J;
777       if (J == JE) break;
778     }
779   }
780
781   // Update kill info. Some live ranges are extended due to copy coalescing.
782   for (unsigned i = 0, e = RHSValsDefinedFromLHS.size(); i != e; ++i) {
783     int LHSValId = RHSValsDefinedFromLHS[i];
784     if (LHSValId == -1)
785       continue;
786     unsigned RHSValId = RHSValNoAssignments[i];
787     LHS.addKills(ValueNumberInfo[RHSValId], RHS.getKillsForValNum(i));
788   }
789   for (unsigned i = 0, e = LHSValsDefinedFromRHS.size(); i != e; ++i) {
790     int RHSValId = LHSValsDefinedFromRHS[i];
791     if (RHSValId == -1)
792       continue;
793     unsigned LHSValId = LHSValNoAssignments[i];
794     RHS.addKills(ValueNumberInfo[LHSValId], LHS.getKillsForValNum(i));
795   }
796
797   // If we get here, we know that we can coalesce the live ranges.  Ask the
798   // intervals to coalesce themselves now.
799   LHS.join(RHS, &LHSValNoAssignments[0], &RHSValNoAssignments[0],
800            ValueNumberInfo);
801   return true;
802 }
803
804 namespace {
805   // DepthMBBCompare - Comparison predicate that sort first based on the loop
806   // depth of the basic block (the unsigned), and then on the MBB number.
807   struct DepthMBBCompare {
808     typedef std::pair<unsigned, MachineBasicBlock*> DepthMBBPair;
809     bool operator()(const DepthMBBPair &LHS, const DepthMBBPair &RHS) const {
810       if (LHS.first > RHS.first) return true;   // Deeper loops first
811       return LHS.first == RHS.first &&
812         LHS.second->getNumber() < RHS.second->getNumber();
813     }
814   };
815 }
816
817 void SimpleRegisterCoalescing::CopyCoalesceInMBB(MachineBasicBlock *MBB,
818                                 std::vector<CopyRec> *TryAgain, bool PhysOnly) {
819   DOUT << ((Value*)MBB->getBasicBlock())->getName() << ":\n";
820   
821   for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end();
822        MII != E;) {
823     MachineInstr *Inst = MII++;
824     
825     // If this isn't a copy, we can't join intervals.
826     unsigned SrcReg, DstReg;
827     if (!tii_->isMoveInstr(*Inst, SrcReg, DstReg)) continue;
828     
829     if (TryAgain && !JoinCopy(Inst, SrcReg, DstReg, PhysOnly))
830       TryAgain->push_back(getCopyRec(Inst, SrcReg, DstReg));
831   }
832 }
833
834 void SimpleRegisterCoalescing::joinIntervals() {
835   DOUT << "********** JOINING INTERVALS ***********\n";
836
837   JoinedLIs.resize(li_->getNumIntervals());
838   JoinedLIs.reset();
839
840   std::vector<CopyRec> TryAgainList;
841   const LoopInfo &LI = getAnalysis<LoopInfo>();
842   if (LI.begin() == LI.end()) {
843     // If there are no loops in the function, join intervals in function order.
844     for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();
845          I != E; ++I)
846       CopyCoalesceInMBB(I, &TryAgainList);
847   } else {
848     // Otherwise, join intervals in inner loops before other intervals.
849     // Unfortunately we can't just iterate over loop hierarchy here because
850     // there may be more MBB's than BB's.  Collect MBB's for sorting.
851
852     // Join intervals in the function prolog first. We want to join physical
853     // registers with virtual registers before the intervals got too long.
854     std::vector<std::pair<unsigned, MachineBasicBlock*> > MBBs;
855     for (MachineFunction::iterator I = mf_->begin(), E = mf_->end(); I != E;++I)
856       MBBs.push_back(std::make_pair(LI.getLoopDepth(I->getBasicBlock()), I));
857
858     // Sort by loop depth.
859     std::sort(MBBs.begin(), MBBs.end(), DepthMBBCompare());
860
861     // Finally, join intervals in loop nest order.
862     for (unsigned i = 0, e = MBBs.size(); i != e; ++i)
863       CopyCoalesceInMBB(MBBs[i].second, NULL, true);
864     for (unsigned i = 0, e = MBBs.size(); i != e; ++i)
865       CopyCoalesceInMBB(MBBs[i].second, &TryAgainList, false);
866   }
867   
868   // Joining intervals can allow other intervals to be joined.  Iteratively join
869   // until we make no progress.
870   bool ProgressMade = true;
871   while (ProgressMade) {
872     ProgressMade = false;
873
874     for (unsigned i = 0, e = TryAgainList.size(); i != e; ++i) {
875       CopyRec &TheCopy = TryAgainList[i];
876       if (TheCopy.MI &&
877           JoinCopy(TheCopy.MI, TheCopy.SrcReg, TheCopy.DstReg)) {
878         TheCopy.MI = 0;   // Mark this one as done.
879         ProgressMade = true;
880       }
881     }
882   }
883
884   // Some live range has been lengthened due to colaescing, eliminate the
885   // unnecessary kills.
886   int RegNum = JoinedLIs.find_first();
887   while (RegNum != -1) {
888     unsigned Reg = RegNum + MRegisterInfo::FirstVirtualRegister;
889     unsigned repReg = rep(Reg);
890     LiveInterval &LI = li_->getInterval(repReg);
891     LiveVariables::VarInfo& svi = lv_->getVarInfo(Reg);
892     for (unsigned i = 0, e = svi.Kills.size(); i != e; ++i) {
893       MachineInstr *Kill = svi.Kills[i];
894       // Suppose vr1 = op vr2, x
895       // and vr1 and vr2 are coalesced. vr2 should still be marked kill
896       // unless it is a two-address operand.
897       if (li_->isRemoved(Kill) || hasRegisterDef(Kill, repReg))
898         continue;
899       if (LI.liveAt(li_->getInstructionIndex(Kill) + InstrSlots::NUM))
900         unsetRegisterKill(Kill, repReg);
901     }
902     RegNum = JoinedLIs.find_next(RegNum);
903   }
904   
905   DOUT << "*** Register mapping ***\n";
906   for (int i = 0, e = r2rMap_.size(); i != e; ++i)
907     if (r2rMap_[i]) {
908       DOUT << "  reg " << i << " -> ";
909       DEBUG(printRegName(r2rMap_[i]));
910       DOUT << "\n";
911     }
912 }
913
914 /// Return true if the two specified registers belong to different register
915 /// classes.  The registers may be either phys or virt regs.
916 bool SimpleRegisterCoalescing::differingRegisterClasses(unsigned RegA,
917                                              unsigned RegB) const {
918
919   // Get the register classes for the first reg.
920   if (MRegisterInfo::isPhysicalRegister(RegA)) {
921     assert(MRegisterInfo::isVirtualRegister(RegB) &&
922            "Shouldn't consider two physregs!");
923     return !mf_->getSSARegMap()->getRegClass(RegB)->contains(RegA);
924   }
925
926   // Compare against the regclass for the second reg.
927   const TargetRegisterClass *RegClass = mf_->getSSARegMap()->getRegClass(RegA);
928   if (MRegisterInfo::isVirtualRegister(RegB))
929     return RegClass != mf_->getSSARegMap()->getRegClass(RegB);
930   else
931     return !RegClass->contains(RegB);
932 }
933
934 /// lastRegisterUse - Returns the last use of the specific register between
935 /// cycles Start and End. It also returns the use operand by reference. It
936 /// returns NULL if there are no uses.
937 MachineInstr *
938 SimpleRegisterCoalescing::lastRegisterUse(unsigned Start, unsigned End, unsigned Reg,
939                                MachineOperand *&MOU) {
940   int e = (End-1) / InstrSlots::NUM * InstrSlots::NUM;
941   int s = Start;
942   while (e >= s) {
943     // Skip deleted instructions
944     MachineInstr *MI = li_->getInstructionFromIndex(e);
945     while ((e - InstrSlots::NUM) >= s && !MI) {
946       e -= InstrSlots::NUM;
947       MI = li_->getInstructionFromIndex(e);
948     }
949     if (e < s || MI == NULL)
950       return NULL;
951
952     for (unsigned i = 0, NumOps = MI->getNumOperands(); i != NumOps; ++i) {
953       MachineOperand &MO = MI->getOperand(i);
954       if (MO.isReg() && MO.isUse() && MO.getReg() &&
955           mri_->regsOverlap(rep(MO.getReg()), Reg)) {
956         MOU = &MO;
957         return MI;
958       }
959     }
960
961     e -= InstrSlots::NUM;
962   }
963
964   return NULL;
965 }
966
967
968 /// findDefOperand - Returns the MachineOperand that is a def of the specific
969 /// register. It returns NULL if the def is not found.
970 MachineOperand *SimpleRegisterCoalescing::findDefOperand(MachineInstr *MI, unsigned Reg) {
971   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
972     MachineOperand &MO = MI->getOperand(i);
973     if (MO.isReg() && MO.isDef() &&
974         mri_->regsOverlap(rep(MO.getReg()), Reg))
975       return &MO;
976   }
977   return NULL;
978 }
979
980 /// unsetRegisterKill - Unset IsKill property of all uses of specific register
981 /// of the specific instruction.
982 void SimpleRegisterCoalescing::unsetRegisterKill(MachineInstr *MI, unsigned Reg) {
983   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
984     MachineOperand &MO = MI->getOperand(i);
985     if (MO.isReg() && MO.isKill() && MO.getReg() &&
986         mri_->regsOverlap(rep(MO.getReg()), Reg))
987       MO.unsetIsKill();
988   }
989 }
990
991 /// unsetRegisterKills - Unset IsKill property of all uses of specific register
992 /// between cycles Start and End.
993 void SimpleRegisterCoalescing::unsetRegisterKills(unsigned Start, unsigned End,
994                                        unsigned Reg) {
995   int e = (End-1) / InstrSlots::NUM * InstrSlots::NUM;
996   int s = Start;
997   while (e >= s) {
998     // Skip deleted instructions
999     MachineInstr *MI = li_->getInstructionFromIndex(e);
1000     while ((e - InstrSlots::NUM) >= s && !MI) {
1001       e -= InstrSlots::NUM;
1002       MI = li_->getInstructionFromIndex(e);
1003     }
1004     if (e < s || MI == NULL)
1005       return;
1006
1007     for (unsigned i = 0, NumOps = MI->getNumOperands(); i != NumOps; ++i) {
1008       MachineOperand &MO = MI->getOperand(i);
1009       if (MO.isReg() && MO.isKill() && MO.getReg() &&
1010           mri_->regsOverlap(rep(MO.getReg()), Reg)) {
1011         MO.unsetIsKill();
1012       }
1013     }
1014
1015     e -= InstrSlots::NUM;
1016   }
1017 }
1018
1019 /// hasRegisterDef - True if the instruction defines the specific register.
1020 ///
1021 bool SimpleRegisterCoalescing::hasRegisterDef(MachineInstr *MI, unsigned Reg) {
1022   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1023     MachineOperand &MO = MI->getOperand(i);
1024     if (MO.isReg() && MO.isDef() &&
1025         mri_->regsOverlap(rep(MO.getReg()), Reg))
1026       return true;
1027   }
1028   return false;
1029 }
1030
1031 void SimpleRegisterCoalescing::printRegName(unsigned reg) const {
1032   if (MRegisterInfo::isPhysicalRegister(reg))
1033     cerr << mri_->getName(reg);
1034   else
1035     cerr << "%reg" << reg;
1036 }
1037
1038 void SimpleRegisterCoalescing::releaseMemory() {
1039    r2rMap_.clear();
1040    JoinedLIs.clear();
1041 }
1042
1043 static bool isZeroLengthInterval(LiveInterval *li) {
1044   for (LiveInterval::Ranges::const_iterator
1045          i = li->ranges.begin(), e = li->ranges.end(); i != e; ++i)
1046     if (i->end - i->start > LiveIntervals::InstrSlots::NUM)
1047       return false;
1048   return true;
1049 }
1050
1051 bool SimpleRegisterCoalescing::runOnMachineFunction(MachineFunction &fn) {
1052   mf_ = &fn;
1053   tm_ = &fn.getTarget();
1054   mri_ = tm_->getRegisterInfo();
1055   tii_ = tm_->getInstrInfo();
1056   li_ = &getAnalysis<LiveIntervals>();
1057   lv_ = &getAnalysis<LiveVariables>();
1058
1059   DOUT << "********** SIMPLE REGISTER COALESCING **********\n"
1060        << "********** Function: "
1061        << ((Value*)mf_->getFunction())->getName() << '\n';
1062
1063   allocatableRegs_ = mri_->getAllocatableSet(fn);
1064   for (MRegisterInfo::regclass_iterator I = mri_->regclass_begin(),
1065          E = mri_->regclass_end(); I != E; ++I)
1066     allocatableRCRegs_.insert(std::make_pair(*I,mri_->getAllocatableSet(fn, *I)));
1067
1068   r2rMap_.grow(mf_->getSSARegMap()->getLastVirtReg());
1069
1070   // Join (coalesce) intervals if requested.
1071   if (EnableJoining) {
1072     joinIntervals();
1073     DOUT << "********** INTERVALS POST JOINING **********\n";
1074     for (LiveIntervals::iterator I = li_->begin(), E = li_->end(); I != E; ++I) {
1075       I->second.print(DOUT, mri_);
1076       DOUT << "\n";
1077     }
1078   }
1079
1080   // perform a final pass over the instructions and compute spill
1081   // weights, coalesce virtual registers and remove identity moves.
1082   const LoopInfo &loopInfo = getAnalysis<LoopInfo>();
1083
1084   for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
1085        mbbi != mbbe; ++mbbi) {
1086     MachineBasicBlock* mbb = mbbi;
1087     unsigned loopDepth = loopInfo.getLoopDepth(mbb->getBasicBlock());
1088
1089     for (MachineBasicBlock::iterator mii = mbb->begin(), mie = mbb->end();
1090          mii != mie; ) {
1091       // if the move will be an identity move delete it
1092       unsigned srcReg, dstReg, RegRep;
1093       if (tii_->isMoveInstr(*mii, srcReg, dstReg) &&
1094           (RegRep = rep(srcReg)) == rep(dstReg)) {
1095         // remove from def list
1096         LiveInterval &RegInt = li_->getOrCreateInterval(RegRep);
1097         MachineOperand *MO = mii->findRegisterDefOperand(dstReg);
1098         // If def of this move instruction is dead, remove its live range from
1099         // the dstination register's live interval.
1100         if (MO->isDead()) {
1101           unsigned MoveIdx = li_->getDefIndex(li_->getInstructionIndex(mii));
1102           LiveInterval::iterator MLR = RegInt.FindLiveRangeContaining(MoveIdx);
1103           RegInt.removeRange(MLR->start, MoveIdx+1);
1104           if (RegInt.empty())
1105             li_->removeInterval(RegRep);
1106         }
1107         li_->RemoveMachineInstrFromMaps(mii);
1108         mii = mbbi->erase(mii);
1109         ++numPeep;
1110       } else {
1111         SmallSet<unsigned, 4> UniqueUses;
1112         for (unsigned i = 0, e = mii->getNumOperands(); i != e; ++i) {
1113           const MachineOperand &mop = mii->getOperand(i);
1114           if (mop.isRegister() && mop.getReg() &&
1115               MRegisterInfo::isVirtualRegister(mop.getReg())) {
1116             // replace register with representative register
1117             unsigned reg = rep(mop.getReg());
1118             mii->getOperand(i).setReg(reg);
1119
1120             // Multiple uses of reg by the same instruction. It should not
1121             // contribute to spill weight again.
1122             if (UniqueUses.count(reg) != 0)
1123               continue;
1124             LiveInterval &RegInt = li_->getInterval(reg);
1125             float w = (mop.isUse()+mop.isDef()) * powf(10.0F, (float)loopDepth);
1126             // If the definition instruction is re-materializable, its spill
1127             // weight is half of what it would have been normally unless it's
1128             // a load from fixed stack slot.
1129             int Dummy;
1130             if (RegInt.remat && !tii_->isLoadFromStackSlot(RegInt.remat, Dummy))
1131               w /= 2;
1132             RegInt.weight += w;
1133             UniqueUses.insert(reg);
1134           }
1135         }
1136         ++mii;
1137       }
1138     }
1139   }
1140
1141   for (LiveIntervals::iterator I = li_->begin(), E = li_->end(); I != E; ++I) {
1142     LiveInterval &LI = I->second;
1143     if (MRegisterInfo::isVirtualRegister(LI.reg)) {
1144       // If the live interval length is essentially zero, i.e. in every live
1145       // range the use follows def immediately, it doesn't make sense to spill
1146       // it and hope it will be easier to allocate for this li.
1147       if (isZeroLengthInterval(&LI))
1148         LI.weight = HUGE_VALF;
1149
1150       // Slightly prefer live interval that has been assigned a preferred reg.
1151       if (LI.preference)
1152         LI.weight *= 1.01F;
1153
1154       // Divide the weight of the interval by its size.  This encourages 
1155       // spilling of intervals that are large and have few uses, and
1156       // discourages spilling of small intervals with many uses.
1157       LI.weight /= LI.getSize();
1158     }
1159   }
1160
1161   DEBUG(dump());
1162   return true;
1163 }
1164
1165 /// print - Implement the dump method.
1166 void SimpleRegisterCoalescing::print(std::ostream &O, const Module* m) const {
1167    li_->print(O, m);
1168 }