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