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