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