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