all but CAS working on x86
[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(true), 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 /// isBackEdgeCopy - Returns true if CopyMI is a back edge copy.
389 ///
390 bool SimpleRegisterCoalescing::isBackEdgeCopy(MachineInstr *CopyMI,
391                                               unsigned DstReg) {
392   MachineBasicBlock *MBB = CopyMI->getParent();
393   const MachineLoop *L = loopInfo->getLoopFor(MBB);
394   if (!L)
395     return false;
396   if (MBB != L->getLoopLatch())
397     return false;
398
399   LiveInterval &LI = li_->getInterval(DstReg);
400   unsigned DefIdx = li_->getInstructionIndex(CopyMI);
401   LiveInterval::const_iterator DstLR =
402     LI.FindLiveRangeContaining(li_->getDefIndex(DefIdx));
403   if (DstLR == LI.end())
404     return false;
405   unsigned KillIdx = li_->getInstructionIndex(&MBB->back()) + InstrSlots::NUM;
406   if (DstLR->valno->kills.size() == 1 &&
407       DstLR->valno->kills[0] == KillIdx && DstLR->valno->hasPHIKill)
408     return true;
409   return false;
410 }
411
412 /// UpdateRegDefsUses - Replace all defs and uses of SrcReg to DstReg and
413 /// update the subregister number if it is not zero. If DstReg is a
414 /// physical register and the existing subregister number of the def / use
415 /// being updated is not zero, make sure to set it to the correct physical
416 /// subregister.
417 void
418 SimpleRegisterCoalescing::UpdateRegDefsUses(unsigned SrcReg, unsigned DstReg,
419                                             unsigned SubIdx) {
420   bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
421   if (DstIsPhys && SubIdx) {
422     // Figure out the real physical register we are updating with.
423     DstReg = tri_->getSubReg(DstReg, SubIdx);
424     SubIdx = 0;
425   }
426
427   for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(SrcReg),
428          E = mri_->reg_end(); I != E; ) {
429     MachineOperand &O = I.getOperand();
430     ++I;
431     if (DstIsPhys) {
432       unsigned UseSubIdx = O.getSubReg();
433       unsigned UseDstReg = DstReg;
434       if (UseSubIdx)
435         UseDstReg = tri_->getSubReg(DstReg, UseSubIdx);
436       O.setReg(UseDstReg);
437       O.setSubReg(0);
438     } else {
439       unsigned OldSubIdx = O.getSubReg();
440       // Sub-register indexes goes from small to large. e.g.
441       // RAX: 0 -> AL, 1 -> AH, 2 -> AX, 3 -> EAX
442       // EAX: 0 -> AL, 1 -> AH, 2 -> AX
443       // So RAX's sub-register 2 is AX, RAX's sub-regsiter 3 is EAX, whose
444       // sub-register 2 is also AX.
445       if (SubIdx && OldSubIdx && SubIdx != OldSubIdx)
446         assert(OldSubIdx < SubIdx && "Conflicting sub-register index!");
447       else if (SubIdx)
448         O.setSubReg(SubIdx);
449       O.setReg(DstReg);
450     }
451   }
452 }
453
454 /// JoinCopy - Attempt to join intervals corresponding to SrcReg/DstReg,
455 /// which are the src/dst of the copy instruction CopyMI.  This returns true
456 /// if the copy was successfully coalesced away. If it is not currently
457 /// possible to coalesce this interval, but it may be possible if other
458 /// things get coalesced, then it returns true by reference in 'Again'.
459 bool SimpleRegisterCoalescing::JoinCopy(CopyRec &TheCopy, bool &Again) {
460   MachineInstr *CopyMI = TheCopy.MI;
461
462   Again = false;
463   if (JoinedCopies.count(CopyMI))
464     return false; // Already done.
465
466   DOUT << li_->getInstructionIndex(CopyMI) << '\t' << *CopyMI;
467
468   unsigned SrcReg;
469   unsigned DstReg;
470   bool isExtSubReg = CopyMI->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG;
471   unsigned SubIdx = 0;
472   if (isExtSubReg) {
473     DstReg = CopyMI->getOperand(0).getReg();
474     SrcReg = CopyMI->getOperand(1).getReg();
475   } else if (!tii_->isMoveInstr(*CopyMI, SrcReg, DstReg)) {
476     assert(0 && "Unrecognized copy instruction!");
477     return false;
478   }
479
480   // If they are already joined we continue.
481   if (SrcReg == DstReg) {
482     DOUT << "\tCopy already coalesced.\n";
483     return false;  // Not coalescable.
484   }
485   
486   bool SrcIsPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
487   bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
488
489   // If they are both physical registers, we cannot join them.
490   if (SrcIsPhys && DstIsPhys) {
491     DOUT << "\tCan not coalesce physregs.\n";
492     return false;  // Not coalescable.
493   }
494   
495   // We only join virtual registers with allocatable physical registers.
496   if (SrcIsPhys && !allocatableRegs_[SrcReg]) {
497     DOUT << "\tSrc reg is unallocatable physreg.\n";
498     return false;  // Not coalescable.
499   }
500   if (DstIsPhys && !allocatableRegs_[DstReg]) {
501     DOUT << "\tDst reg is unallocatable physreg.\n";
502     return false;  // Not coalescable.
503   }
504
505   unsigned RealDstReg = 0;
506   if (isExtSubReg) {
507     SubIdx = CopyMI->getOperand(2).getImm();
508     if (SrcIsPhys) {
509       // r1024 = EXTRACT_SUBREG EAX, 0 then r1024 is really going to be
510       // coalesced with AX.
511       SrcReg = tri_->getSubReg(SrcReg, SubIdx);
512       SubIdx = 0;
513     } else if (DstIsPhys) {
514       // If this is a extract_subreg where dst is a physical register, e.g.
515       // cl = EXTRACT_SUBREG reg1024, 1
516       // then create and update the actual physical register allocated to RHS.
517       const TargetRegisterClass *RC = mri_->getRegClass(SrcReg);
518       for (const unsigned *SRs = tri_->getSuperRegisters(DstReg);
519            unsigned SR = *SRs; ++SRs) {
520         if (DstReg == tri_->getSubReg(SR, SubIdx) &&
521             RC->contains(SR)) {
522           RealDstReg = SR;
523           break;
524         }
525       }
526       assert(RealDstReg && "Invalid extra_subreg instruction!");
527
528       // For this type of EXTRACT_SUBREG, conservatively
529       // check if the live interval of the source register interfere with the
530       // actual super physical register we are trying to coalesce with.
531       LiveInterval &RHS = li_->getInterval(SrcReg);
532       if (li_->hasInterval(RealDstReg) &&
533           RHS.overlaps(li_->getInterval(RealDstReg))) {
534         DOUT << "Interfere with register ";
535         DEBUG(li_->getInterval(RealDstReg).print(DOUT, tri_));
536         return false; // Not coalescable
537       }
538       for (const unsigned* SR = tri_->getSubRegisters(RealDstReg); *SR; ++SR)
539         if (li_->hasInterval(*SR) && RHS.overlaps(li_->getInterval(*SR))) {
540           DOUT << "Interfere with sub-register ";
541           DEBUG(li_->getInterval(*SR).print(DOUT, tri_));
542           return false; // Not coalescable
543         }
544       SubIdx = 0;
545     } else {
546       unsigned SrcSize= li_->getInterval(SrcReg).getSize() / InstrSlots::NUM;
547       unsigned DstSize= li_->getInterval(DstReg).getSize() / InstrSlots::NUM;
548       const TargetRegisterClass *RC = mri_->getRegClass(DstReg);
549       unsigned Threshold = allocatableRCRegs_[RC].count();
550       // Be conservative. If both sides are virtual registers, do not coalesce
551       // if this will cause a high use density interval to target a smaller set
552       // of registers.
553       if (DstSize > Threshold || SrcSize > Threshold) {
554         LiveVariables::VarInfo &svi = lv_->getVarInfo(SrcReg);
555         LiveVariables::VarInfo &dvi = lv_->getVarInfo(DstReg);
556         if ((float)dvi.NumUses / DstSize < (float)svi.NumUses / SrcSize) {
557           Again = true;  // May be possible to coalesce later.
558           return false;
559         }
560       }
561     }
562   } else if (differingRegisterClasses(SrcReg, DstReg)) {
563     // FIXME: What if the resul of a EXTRACT_SUBREG is then coalesced
564     // with another? If it's the resulting destination register, then
565     // the subidx must be propagated to uses (but only those defined
566     // by the EXTRACT_SUBREG). If it's being coalesced into another
567     // register, it should be safe because register is assumed to have
568     // the register class of the super-register.
569
570     // If they are not of the same register class, we cannot join them.
571     DOUT << "\tSrc/Dest are different register classes.\n";
572     // Allow the coalescer to try again in case either side gets coalesced to
573     // a physical register that's compatible with the other side. e.g.
574     // r1024 = MOV32to32_ r1025
575     // but later r1024 is assigned EAX then r1025 may be coalesced with EAX.
576     Again = true;  // May be possible to coalesce later.
577     return false;
578   }
579   
580   LiveInterval &SrcInt = li_->getInterval(SrcReg);
581   LiveInterval &DstInt = li_->getInterval(DstReg);
582   assert(SrcInt.reg == SrcReg && DstInt.reg == DstReg &&
583          "Register mapping is horribly broken!");
584
585   DOUT << "\t\tInspecting "; SrcInt.print(DOUT, tri_);
586   DOUT << " and "; DstInt.print(DOUT, tri_);
587   DOUT << ": ";
588
589   // Check if it is necessary to propagate "isDead" property before intervals
590   // are joined.
591   MachineOperand *mopd = CopyMI->findRegisterDefOperand(DstReg);
592   bool isDead = mopd->isDead();
593   bool isShorten = false;
594   unsigned SrcStart = 0, RemoveStart = 0;
595   unsigned SrcEnd = 0, RemoveEnd = 0;
596   if (isDead) {
597     unsigned CopyIdx = li_->getInstructionIndex(CopyMI);
598     LiveInterval::iterator SrcLR =
599       SrcInt.FindLiveRangeContaining(li_->getUseIndex(CopyIdx));
600     RemoveStart = SrcStart = SrcLR->start;
601     RemoveEnd   = SrcEnd   = SrcLR->end;
602     // The instruction which defines the src is only truly dead if there are
603     // no intermediate uses and there isn't a use beyond the copy.
604     // FIXME: find the last use, mark is kill and shorten the live range.
605     if (SrcEnd > li_->getDefIndex(CopyIdx)) {
606       isDead = false;
607     } else {
608       unsigned LastUseIdx;
609       MachineOperand *LastUse =
610         lastRegisterUse(SrcStart, CopyIdx, SrcReg, LastUseIdx);
611       if (LastUse) {
612         // Shorten the liveinterval to the end of last use.
613         LastUse->setIsKill();
614         isDead = false;
615         isShorten = true;
616         RemoveStart = li_->getDefIndex(LastUseIdx);
617         RemoveEnd = SrcEnd;
618       } else {
619         MachineInstr *SrcMI = li_->getInstructionFromIndex(SrcStart);
620         if (SrcMI) {
621           MachineOperand *mops = findDefOperand(SrcMI, SrcReg);
622           if (mops)
623             // A dead def should have a single cycle interval.
624             ++RemoveStart;
625         }
626       }
627     }
628   }
629
630   // We need to be careful about coalescing a source physical register with a
631   // virtual register. Once the coalescing is done, it cannot be broken and
632   // these are not spillable! If the destination interval uses are far away,
633   // think twice about coalescing them!
634   if (!mopd->isDead() && (SrcIsPhys || DstIsPhys) && !isExtSubReg) {
635     LiveInterval &JoinVInt = SrcIsPhys ? DstInt : SrcInt;
636     unsigned JoinVReg = SrcIsPhys ? DstReg : SrcReg;
637     unsigned JoinPReg = SrcIsPhys ? SrcReg : DstReg;
638     const TargetRegisterClass *RC = mri_->getRegClass(JoinVReg);
639     unsigned Threshold = allocatableRCRegs_[RC].count() * 2;
640     if (TheCopy.isBackEdge)
641       Threshold *= 2; // Favors back edge copies.
642
643     // If the virtual register live interval is long but it has low use desity,
644     // do not join them, instead mark the physical register as its allocation
645     // preference.
646     unsigned Length = JoinVInt.getSize() / InstrSlots::NUM;
647     LiveVariables::VarInfo &vi = lv_->getVarInfo(JoinVReg);
648     if (Length > Threshold &&
649         (((float)vi.NumUses / Length) < (1.0 / Threshold))) {
650       JoinVInt.preference = JoinPReg;
651       ++numAborts;
652       DOUT << "\tMay tie down a physical register, abort!\n";
653       Again = true;  // May be possible to coalesce later.
654       return false;
655     }
656   }
657
658   // Okay, attempt to join these two intervals.  On failure, this returns false.
659   // Otherwise, if one of the intervals being joined is a physreg, this method
660   // always canonicalizes DstInt to be it.  The output "SrcInt" will not have
661   // been modified, so we can use this information below to update aliases.
662   bool Swapped = false;
663   if (JoinIntervals(DstInt, SrcInt, Swapped)) {
664     if (isDead) {
665       // Result of the copy is dead. Propagate this property.
666       if (SrcStart == 0) {
667         assert(TargetRegisterInfo::isPhysicalRegister(SrcReg) &&
668                "Live-in must be a physical register!");
669         // Live-in to the function but dead. Remove it from entry live-in set.
670         // JoinIntervals may end up swapping the two intervals.
671         mf_->begin()->removeLiveIn(SrcReg);
672       } else {
673         MachineInstr *SrcMI = li_->getInstructionFromIndex(SrcStart);
674         if (SrcMI) {
675           MachineOperand *mops = findDefOperand(SrcMI, SrcReg);
676           if (mops)
677             mops->setIsDead();
678         }
679       }
680     }
681
682     if (isShorten || isDead) {
683       // Shorten the destination live interval.
684       if (Swapped)
685         SrcInt.removeRange(RemoveStart, RemoveEnd, true);
686     }
687   } else {
688     // Coalescing failed.
689     
690     // If we can eliminate the copy without merging the live ranges, do so now.
691     if (!isExtSubReg &&
692         (AdjustCopiesBackFrom(SrcInt, DstInt, CopyMI) ||
693          RemoveCopyByCommutingDef(SrcInt, DstInt, CopyMI))) {
694       JoinedCopies.insert(CopyMI);
695       return true;
696     }
697     
698     // Otherwise, we are unable to join the intervals.
699     DOUT << "Interference!\n";
700     Again = true;  // May be possible to coalesce later.
701     return false;
702   }
703
704   LiveInterval *ResSrcInt = &SrcInt;
705   LiveInterval *ResDstInt = &DstInt;
706   if (Swapped) {
707     std::swap(SrcReg, DstReg);
708     std::swap(ResSrcInt, ResDstInt);
709   }
710   assert(TargetRegisterInfo::isVirtualRegister(SrcReg) &&
711          "LiveInterval::join didn't work right!");
712                                
713   // If we're about to merge live ranges into a physical register live range,
714   // we have to update any aliased register's live ranges to indicate that they
715   // have clobbered values for this range.
716   if (TargetRegisterInfo::isPhysicalRegister(DstReg)) {
717     // If this is a extract_subreg where dst is a physical register, e.g.
718     // cl = EXTRACT_SUBREG reg1024, 1
719     // then create and update the actual physical register allocated to RHS.
720     if (RealDstReg) {
721       LiveInterval &RealDstInt = li_->getOrCreateInterval(RealDstReg);
722       SmallSet<const VNInfo*, 4> CopiedValNos;
723       for (LiveInterval::Ranges::const_iterator I = ResSrcInt->ranges.begin(),
724              E = ResSrcInt->ranges.end(); I != E; ++I) {
725         LiveInterval::const_iterator DstLR =
726           ResDstInt->FindLiveRangeContaining(I->start);
727         assert(DstLR != ResDstInt->end() && "Invalid joined interval!");
728         const VNInfo *DstValNo = DstLR->valno;
729         if (CopiedValNos.insert(DstValNo)) {
730           VNInfo *ValNo = RealDstInt.getNextValue(DstValNo->def, DstValNo->copy,
731                                                   li_->getVNInfoAllocator());
732           ValNo->hasPHIKill = DstValNo->hasPHIKill;
733           RealDstInt.addKills(ValNo, DstValNo->kills);
734           RealDstInt.MergeValueInAsValue(*ResDstInt, DstValNo, ValNo);
735         }
736       }
737       DstReg = RealDstReg;
738     }
739
740     // Update the liveintervals of sub-registers.
741     for (const unsigned *AS = tri_->getSubRegisters(DstReg); *AS; ++AS)
742       li_->getOrCreateInterval(*AS).MergeInClobberRanges(*ResSrcInt,
743                                                  li_->getVNInfoAllocator());
744   } else {
745     // Merge use info if the destination is a virtual register.
746     LiveVariables::VarInfo& dVI = lv_->getVarInfo(DstReg);
747     LiveVariables::VarInfo& sVI = lv_->getVarInfo(SrcReg);
748     dVI.NumUses += sVI.NumUses;
749   }
750
751   // If this is a EXTRACT_SUBREG, make sure the result of coalescing is the
752   // larger super-register.
753   if (isExtSubReg && !SrcIsPhys && !DstIsPhys) {
754     if (!Swapped) {
755       ResSrcInt->Copy(*ResDstInt, li_->getVNInfoAllocator());
756       std::swap(SrcReg, DstReg);
757       std::swap(ResSrcInt, ResDstInt);
758     }
759   }
760
761   if (NewHeuristic) {
762     // Add all copies that define val# in the source interval into the queue.
763     for (LiveInterval::const_vni_iterator i = ResSrcInt->vni_begin(),
764            e = ResSrcInt->vni_end(); i != e; ++i) {
765       const VNInfo *vni = *i;
766       if (!vni->def || vni->def == ~1U || vni->def == ~0U)
767         continue;
768       MachineInstr *CopyMI = li_->getInstructionFromIndex(vni->def);
769       unsigned NewSrcReg, NewDstReg;
770       if (CopyMI &&
771           JoinedCopies.count(CopyMI) == 0 &&
772           tii_->isMoveInstr(*CopyMI, NewSrcReg, NewDstReg)) {
773         unsigned LoopDepth = loopInfo->getLoopDepth(CopyMI->getParent());
774         JoinQueue->push(CopyRec(CopyMI, LoopDepth,
775                                 isBackEdgeCopy(CopyMI, DstReg)));
776       }
777     }
778   }
779
780   DOUT << "\n\t\tJoined.  Result = "; ResDstInt->print(DOUT, tri_);
781   DOUT << "\n";
782
783   // Remember to delete the copy instruction.
784   JoinedCopies.insert(CopyMI);
785
786   // SrcReg is guarateed to be the register whose live interval that is
787   // being merged.
788   li_->removeInterval(SrcReg);
789   UpdateRegDefsUses(SrcReg, DstReg, SubIdx);
790
791   ++numJoins;
792   return true;
793 }
794
795 /// ComputeUltimateVN - Assuming we are going to join two live intervals,
796 /// compute what the resultant value numbers for each value in the input two
797 /// ranges will be.  This is complicated by copies between the two which can
798 /// and will commonly cause multiple value numbers to be merged into one.
799 ///
800 /// VN is the value number that we're trying to resolve.  InstDefiningValue
801 /// keeps track of the new InstDefiningValue assignment for the result
802 /// LiveInterval.  ThisFromOther/OtherFromThis are sets that keep track of
803 /// whether a value in this or other is a copy from the opposite set.
804 /// ThisValNoAssignments/OtherValNoAssignments keep track of value #'s that have
805 /// already been assigned.
806 ///
807 /// ThisFromOther[x] - If x is defined as a copy from the other interval, this
808 /// contains the value number the copy is from.
809 ///
810 static unsigned ComputeUltimateVN(VNInfo *VNI,
811                                   SmallVector<VNInfo*, 16> &NewVNInfo,
812                                   DenseMap<VNInfo*, VNInfo*> &ThisFromOther,
813                                   DenseMap<VNInfo*, VNInfo*> &OtherFromThis,
814                                   SmallVector<int, 16> &ThisValNoAssignments,
815                                   SmallVector<int, 16> &OtherValNoAssignments) {
816   unsigned VN = VNI->id;
817
818   // If the VN has already been computed, just return it.
819   if (ThisValNoAssignments[VN] >= 0)
820     return ThisValNoAssignments[VN];
821 //  assert(ThisValNoAssignments[VN] != -2 && "Cyclic case?");
822
823   // If this val is not a copy from the other val, then it must be a new value
824   // number in the destination.
825   DenseMap<VNInfo*, VNInfo*>::iterator I = ThisFromOther.find(VNI);
826   if (I == ThisFromOther.end()) {
827     NewVNInfo.push_back(VNI);
828     return ThisValNoAssignments[VN] = NewVNInfo.size()-1;
829   }
830   VNInfo *OtherValNo = I->second;
831
832   // Otherwise, this *is* a copy from the RHS.  If the other side has already
833   // been computed, return it.
834   if (OtherValNoAssignments[OtherValNo->id] >= 0)
835     return ThisValNoAssignments[VN] = OtherValNoAssignments[OtherValNo->id];
836   
837   // Mark this value number as currently being computed, then ask what the
838   // ultimate value # of the other value is.
839   ThisValNoAssignments[VN] = -2;
840   unsigned UltimateVN =
841     ComputeUltimateVN(OtherValNo, NewVNInfo, OtherFromThis, ThisFromOther,
842                       OtherValNoAssignments, ThisValNoAssignments);
843   return ThisValNoAssignments[VN] = UltimateVN;
844 }
845
846 static bool InVector(VNInfo *Val, const SmallVector<VNInfo*, 8> &V) {
847   return std::find(V.begin(), V.end(), Val) != V.end();
848 }
849
850 /// SimpleJoin - Attempt to joint the specified interval into this one. The
851 /// caller of this method must guarantee that the RHS only contains a single
852 /// value number and that the RHS is not defined by a copy from this
853 /// interval.  This returns false if the intervals are not joinable, or it
854 /// joins them and returns true.
855 bool SimpleRegisterCoalescing::SimpleJoin(LiveInterval &LHS, LiveInterval &RHS){
856   assert(RHS.containsOneValue());
857   
858   // Some number (potentially more than one) value numbers in the current
859   // interval may be defined as copies from the RHS.  Scan the overlapping
860   // portions of the LHS and RHS, keeping track of this and looking for
861   // overlapping live ranges that are NOT defined as copies.  If these exist, we
862   // cannot coalesce.
863   
864   LiveInterval::iterator LHSIt = LHS.begin(), LHSEnd = LHS.end();
865   LiveInterval::iterator RHSIt = RHS.begin(), RHSEnd = RHS.end();
866   
867   if (LHSIt->start < RHSIt->start) {
868     LHSIt = std::upper_bound(LHSIt, LHSEnd, RHSIt->start);
869     if (LHSIt != LHS.begin()) --LHSIt;
870   } else if (RHSIt->start < LHSIt->start) {
871     RHSIt = std::upper_bound(RHSIt, RHSEnd, LHSIt->start);
872     if (RHSIt != RHS.begin()) --RHSIt;
873   }
874   
875   SmallVector<VNInfo*, 8> EliminatedLHSVals;
876   
877   while (1) {
878     // Determine if these live intervals overlap.
879     bool Overlaps = false;
880     if (LHSIt->start <= RHSIt->start)
881       Overlaps = LHSIt->end > RHSIt->start;
882     else
883       Overlaps = RHSIt->end > LHSIt->start;
884     
885     // If the live intervals overlap, there are two interesting cases: if the
886     // LHS interval is defined by a copy from the RHS, it's ok and we record
887     // that the LHS value # is the same as the RHS.  If it's not, then we cannot
888     // coalesce these live ranges and we bail out.
889     if (Overlaps) {
890       // If we haven't already recorded that this value # is safe, check it.
891       if (!InVector(LHSIt->valno, EliminatedLHSVals)) {
892         // Copy from the RHS?
893         unsigned SrcReg = li_->getVNInfoSourceReg(LHSIt->valno);
894         if (SrcReg != RHS.reg)
895           return false;    // Nope, bail out.
896         
897         EliminatedLHSVals.push_back(LHSIt->valno);
898       }
899       
900       // We know this entire LHS live range is okay, so skip it now.
901       if (++LHSIt == LHSEnd) break;
902       continue;
903     }
904     
905     if (LHSIt->end < RHSIt->end) {
906       if (++LHSIt == LHSEnd) break;
907     } else {
908       // One interesting case to check here.  It's possible that we have
909       // something like "X3 = Y" which defines a new value number in the LHS,
910       // and is the last use of this liverange of the RHS.  In this case, we
911       // want to notice this copy (so that it gets coalesced away) even though
912       // the live ranges don't actually overlap.
913       if (LHSIt->start == RHSIt->end) {
914         if (InVector(LHSIt->valno, EliminatedLHSVals)) {
915           // We already know that this value number is going to be merged in
916           // if coalescing succeeds.  Just skip the liverange.
917           if (++LHSIt == LHSEnd) break;
918         } else {
919           // Otherwise, if this is a copy from the RHS, mark it as being merged
920           // in.
921           if (li_->getVNInfoSourceReg(LHSIt->valno) == RHS.reg) {
922             EliminatedLHSVals.push_back(LHSIt->valno);
923
924             // We know this entire LHS live range is okay, so skip it now.
925             if (++LHSIt == LHSEnd) break;
926           }
927         }
928       }
929       
930       if (++RHSIt == RHSEnd) break;
931     }
932   }
933   
934   // If we got here, we know that the coalescing will be successful and that
935   // the value numbers in EliminatedLHSVals will all be merged together.  Since
936   // the most common case is that EliminatedLHSVals has a single number, we
937   // optimize for it: if there is more than one value, we merge them all into
938   // the lowest numbered one, then handle the interval as if we were merging
939   // with one value number.
940   VNInfo *LHSValNo;
941   if (EliminatedLHSVals.size() > 1) {
942     // Loop through all the equal value numbers merging them into the smallest
943     // one.
944     VNInfo *Smallest = EliminatedLHSVals[0];
945     for (unsigned i = 1, e = EliminatedLHSVals.size(); i != e; ++i) {
946       if (EliminatedLHSVals[i]->id < Smallest->id) {
947         // Merge the current notion of the smallest into the smaller one.
948         LHS.MergeValueNumberInto(Smallest, EliminatedLHSVals[i]);
949         Smallest = EliminatedLHSVals[i];
950       } else {
951         // Merge into the smallest.
952         LHS.MergeValueNumberInto(EliminatedLHSVals[i], Smallest);
953       }
954     }
955     LHSValNo = Smallest;
956   } else {
957     assert(!EliminatedLHSVals.empty() && "No copies from the RHS?");
958     LHSValNo = EliminatedLHSVals[0];
959   }
960   
961   // Okay, now that there is a single LHS value number that we're merging the
962   // RHS into, update the value number info for the LHS to indicate that the
963   // value number is defined where the RHS value number was.
964   const VNInfo *VNI = RHS.getValNumInfo(0);
965   LHSValNo->def  = VNI->def;
966   LHSValNo->copy = VNI->copy;
967   
968   // Okay, the final step is to loop over the RHS live intervals, adding them to
969   // the LHS.
970   LHSValNo->hasPHIKill |= VNI->hasPHIKill;
971   LHS.addKills(LHSValNo, VNI->kills);
972   LHS.MergeRangesInAsValue(RHS, LHSValNo);
973   LHS.weight += RHS.weight;
974   if (RHS.preference && !LHS.preference)
975     LHS.preference = RHS.preference;
976   
977   return true;
978 }
979
980 /// JoinIntervals - Attempt to join these two intervals.  On failure, this
981 /// returns false.  Otherwise, if one of the intervals being joined is a
982 /// physreg, this method always canonicalizes LHS to be it.  The output
983 /// "RHS" will not have been modified, so we can use this information
984 /// below to update aliases.
985 bool SimpleRegisterCoalescing::JoinIntervals(LiveInterval &LHS,
986                                              LiveInterval &RHS, bool &Swapped) {
987   // Compute the final value assignment, assuming that the live ranges can be
988   // coalesced.
989   SmallVector<int, 16> LHSValNoAssignments;
990   SmallVector<int, 16> RHSValNoAssignments;
991   DenseMap<VNInfo*, VNInfo*> LHSValsDefinedFromRHS;
992   DenseMap<VNInfo*, VNInfo*> RHSValsDefinedFromLHS;
993   SmallVector<VNInfo*, 16> NewVNInfo;
994                           
995   // If a live interval is a physical register, conservatively check if any
996   // of its sub-registers is overlapping the live interval of the virtual
997   // register. If so, do not coalesce.
998   if (TargetRegisterInfo::isPhysicalRegister(LHS.reg) &&
999       *tri_->getSubRegisters(LHS.reg)) {
1000     for (const unsigned* SR = tri_->getSubRegisters(LHS.reg); *SR; ++SR)
1001       if (li_->hasInterval(*SR) && RHS.overlaps(li_->getInterval(*SR))) {
1002         DOUT << "Interfere with sub-register ";
1003         DEBUG(li_->getInterval(*SR).print(DOUT, tri_));
1004         return false;
1005       }
1006   } else if (TargetRegisterInfo::isPhysicalRegister(RHS.reg) &&
1007              *tri_->getSubRegisters(RHS.reg)) {
1008     for (const unsigned* SR = tri_->getSubRegisters(RHS.reg); *SR; ++SR)
1009       if (li_->hasInterval(*SR) && LHS.overlaps(li_->getInterval(*SR))) {
1010         DOUT << "Interfere with sub-register ";
1011         DEBUG(li_->getInterval(*SR).print(DOUT, tri_));
1012         return false;
1013       }
1014   }
1015                           
1016   // Compute ultimate value numbers for the LHS and RHS values.
1017   if (RHS.containsOneValue()) {
1018     // Copies from a liveinterval with a single value are simple to handle and
1019     // very common, handle the special case here.  This is important, because
1020     // often RHS is small and LHS is large (e.g. a physreg).
1021     
1022     // Find out if the RHS is defined as a copy from some value in the LHS.
1023     int RHSVal0DefinedFromLHS = -1;
1024     int RHSValID = -1;
1025     VNInfo *RHSValNoInfo = NULL;
1026     VNInfo *RHSValNoInfo0 = RHS.getValNumInfo(0);
1027     unsigned RHSSrcReg = li_->getVNInfoSourceReg(RHSValNoInfo0);
1028     if ((RHSSrcReg == 0 || RHSSrcReg != LHS.reg)) {
1029       // If RHS is not defined as a copy from the LHS, we can use simpler and
1030       // faster checks to see if the live ranges are coalescable.  This joiner
1031       // can't swap the LHS/RHS intervals though.
1032       if (!TargetRegisterInfo::isPhysicalRegister(RHS.reg)) {
1033         return SimpleJoin(LHS, RHS);
1034       } else {
1035         RHSValNoInfo = RHSValNoInfo0;
1036       }
1037     } else {
1038       // It was defined as a copy from the LHS, find out what value # it is.
1039       RHSValNoInfo = LHS.getLiveRangeContaining(RHSValNoInfo0->def-1)->valno;
1040       RHSValID = RHSValNoInfo->id;
1041       RHSVal0DefinedFromLHS = RHSValID;
1042     }
1043     
1044     LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
1045     RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
1046     NewVNInfo.resize(LHS.getNumValNums(), NULL);
1047     
1048     // Okay, *all* of the values in LHS that are defined as a copy from RHS
1049     // should now get updated.
1050     for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1051          i != e; ++i) {
1052       VNInfo *VNI = *i;
1053       unsigned VN = VNI->id;
1054       if (unsigned LHSSrcReg = li_->getVNInfoSourceReg(VNI)) {
1055         if (LHSSrcReg != RHS.reg) {
1056           // If this is not a copy from the RHS, its value number will be
1057           // unmodified by the coalescing.
1058           NewVNInfo[VN] = VNI;
1059           LHSValNoAssignments[VN] = VN;
1060         } else if (RHSValID == -1) {
1061           // Otherwise, it is a copy from the RHS, and we don't already have a
1062           // value# for it.  Keep the current value number, but remember it.
1063           LHSValNoAssignments[VN] = RHSValID = VN;
1064           NewVNInfo[VN] = RHSValNoInfo;
1065           LHSValsDefinedFromRHS[VNI] = RHSValNoInfo0;
1066         } else {
1067           // Otherwise, use the specified value #.
1068           LHSValNoAssignments[VN] = RHSValID;
1069           if (VN == (unsigned)RHSValID) {  // Else this val# is dead.
1070             NewVNInfo[VN] = RHSValNoInfo;
1071             LHSValsDefinedFromRHS[VNI] = RHSValNoInfo0;
1072           }
1073         }
1074       } else {
1075         NewVNInfo[VN] = VNI;
1076         LHSValNoAssignments[VN] = VN;
1077       }
1078     }
1079     
1080     assert(RHSValID != -1 && "Didn't find value #?");
1081     RHSValNoAssignments[0] = RHSValID;
1082     if (RHSVal0DefinedFromLHS != -1) {
1083       // This path doesn't go through ComputeUltimateVN so just set
1084       // it to anything.
1085       RHSValsDefinedFromLHS[RHSValNoInfo0] = (VNInfo*)1;
1086     }
1087   } else {
1088     // Loop over the value numbers of the LHS, seeing if any are defined from
1089     // the RHS.
1090     for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1091          i != e; ++i) {
1092       VNInfo *VNI = *i;
1093       if (VNI->def == ~1U || VNI->copy == 0)  // Src not defined by a copy?
1094         continue;
1095       
1096       // DstReg is known to be a register in the LHS interval.  If the src is
1097       // from the RHS interval, we can use its value #.
1098       if (li_->getVNInfoSourceReg(VNI) != RHS.reg)
1099         continue;
1100       
1101       // Figure out the value # from the RHS.
1102       LHSValsDefinedFromRHS[VNI]=RHS.getLiveRangeContaining(VNI->def-1)->valno;
1103     }
1104     
1105     // Loop over the value numbers of the RHS, seeing if any are defined from
1106     // the LHS.
1107     for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
1108          i != e; ++i) {
1109       VNInfo *VNI = *i;
1110       if (VNI->def == ~1U || VNI->copy == 0)  // Src not defined by a copy?
1111         continue;
1112       
1113       // DstReg is known to be a register in the RHS interval.  If the src is
1114       // from the LHS interval, we can use its value #.
1115       if (li_->getVNInfoSourceReg(VNI) != LHS.reg)
1116         continue;
1117       
1118       // Figure out the value # from the LHS.
1119       RHSValsDefinedFromLHS[VNI]=LHS.getLiveRangeContaining(VNI->def-1)->valno;
1120     }
1121     
1122     LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
1123     RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
1124     NewVNInfo.reserve(LHS.getNumValNums() + RHS.getNumValNums());
1125     
1126     for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1127          i != e; ++i) {
1128       VNInfo *VNI = *i;
1129       unsigned VN = VNI->id;
1130       if (LHSValNoAssignments[VN] >= 0 || VNI->def == ~1U) 
1131         continue;
1132       ComputeUltimateVN(VNI, NewVNInfo,
1133                         LHSValsDefinedFromRHS, RHSValsDefinedFromLHS,
1134                         LHSValNoAssignments, RHSValNoAssignments);
1135     }
1136     for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
1137          i != e; ++i) {
1138       VNInfo *VNI = *i;
1139       unsigned VN = VNI->id;
1140       if (RHSValNoAssignments[VN] >= 0 || VNI->def == ~1U)
1141         continue;
1142       // If this value number isn't a copy from the LHS, it's a new number.
1143       if (RHSValsDefinedFromLHS.find(VNI) == RHSValsDefinedFromLHS.end()) {
1144         NewVNInfo.push_back(VNI);
1145         RHSValNoAssignments[VN] = NewVNInfo.size()-1;
1146         continue;
1147       }
1148       
1149       ComputeUltimateVN(VNI, NewVNInfo,
1150                         RHSValsDefinedFromLHS, LHSValsDefinedFromRHS,
1151                         RHSValNoAssignments, LHSValNoAssignments);
1152     }
1153   }
1154   
1155   // Armed with the mappings of LHS/RHS values to ultimate values, walk the
1156   // interval lists to see if these intervals are coalescable.
1157   LiveInterval::const_iterator I = LHS.begin();
1158   LiveInterval::const_iterator IE = LHS.end();
1159   LiveInterval::const_iterator J = RHS.begin();
1160   LiveInterval::const_iterator JE = RHS.end();
1161   
1162   // Skip ahead until the first place of potential sharing.
1163   if (I->start < J->start) {
1164     I = std::upper_bound(I, IE, J->start);
1165     if (I != LHS.begin()) --I;
1166   } else if (J->start < I->start) {
1167     J = std::upper_bound(J, JE, I->start);
1168     if (J != RHS.begin()) --J;
1169   }
1170   
1171   while (1) {
1172     // Determine if these two live ranges overlap.
1173     bool Overlaps;
1174     if (I->start < J->start) {
1175       Overlaps = I->end > J->start;
1176     } else {
1177       Overlaps = J->end > I->start;
1178     }
1179
1180     // If so, check value # info to determine if they are really different.
1181     if (Overlaps) {
1182       // If the live range overlap will map to the same value number in the
1183       // result liverange, we can still coalesce them.  If not, we can't.
1184       if (LHSValNoAssignments[I->valno->id] !=
1185           RHSValNoAssignments[J->valno->id])
1186         return false;
1187     }
1188     
1189     if (I->end < J->end) {
1190       ++I;
1191       if (I == IE) break;
1192     } else {
1193       ++J;
1194       if (J == JE) break;
1195     }
1196   }
1197
1198   // Update kill info. Some live ranges are extended due to copy coalescing.
1199   for (DenseMap<VNInfo*, VNInfo*>::iterator I = LHSValsDefinedFromRHS.begin(),
1200          E = LHSValsDefinedFromRHS.end(); I != E; ++I) {
1201     VNInfo *VNI = I->first;
1202     unsigned LHSValID = LHSValNoAssignments[VNI->id];
1203     LiveInterval::removeKill(NewVNInfo[LHSValID], VNI->def);
1204     NewVNInfo[LHSValID]->hasPHIKill |= VNI->hasPHIKill;
1205     RHS.addKills(NewVNInfo[LHSValID], VNI->kills);
1206   }
1207
1208   // Update kill info. Some live ranges are extended due to copy coalescing.
1209   for (DenseMap<VNInfo*, VNInfo*>::iterator I = RHSValsDefinedFromLHS.begin(),
1210          E = RHSValsDefinedFromLHS.end(); I != E; ++I) {
1211     VNInfo *VNI = I->first;
1212     unsigned RHSValID = RHSValNoAssignments[VNI->id];
1213     LiveInterval::removeKill(NewVNInfo[RHSValID], VNI->def);
1214     NewVNInfo[RHSValID]->hasPHIKill |= VNI->hasPHIKill;
1215     LHS.addKills(NewVNInfo[RHSValID], VNI->kills);
1216   }
1217
1218   // If we get here, we know that we can coalesce the live ranges.  Ask the
1219   // intervals to coalesce themselves now.
1220   if ((RHS.ranges.size() > LHS.ranges.size() &&
1221       TargetRegisterInfo::isVirtualRegister(LHS.reg)) ||
1222       TargetRegisterInfo::isPhysicalRegister(RHS.reg)) {
1223     RHS.join(LHS, &RHSValNoAssignments[0], &LHSValNoAssignments[0], NewVNInfo);
1224     Swapped = true;
1225   } else {
1226     LHS.join(RHS, &LHSValNoAssignments[0], &RHSValNoAssignments[0], NewVNInfo);
1227     Swapped = false;
1228   }
1229   return true;
1230 }
1231
1232 namespace {
1233   // DepthMBBCompare - Comparison predicate that sort first based on the loop
1234   // depth of the basic block (the unsigned), and then on the MBB number.
1235   struct DepthMBBCompare {
1236     typedef std::pair<unsigned, MachineBasicBlock*> DepthMBBPair;
1237     bool operator()(const DepthMBBPair &LHS, const DepthMBBPair &RHS) const {
1238       if (LHS.first > RHS.first) return true;   // Deeper loops first
1239       return LHS.first == RHS.first &&
1240         LHS.second->getNumber() < RHS.second->getNumber();
1241     }
1242   };
1243 }
1244
1245 /// getRepIntervalSize - Returns the size of the interval that represents the
1246 /// specified register.
1247 template<class SF>
1248 unsigned JoinPriorityQueue<SF>::getRepIntervalSize(unsigned Reg) {
1249   return Rc->getRepIntervalSize(Reg);
1250 }
1251
1252 /// CopyRecSort::operator - Join priority queue sorting function.
1253 ///
1254 bool CopyRecSort::operator()(CopyRec left, CopyRec right) const {
1255   // Inner loops first.
1256   if (left.LoopDepth > right.LoopDepth)
1257     return false;
1258   else if (left.LoopDepth == right.LoopDepth)
1259     if (left.isBackEdge && !right.isBackEdge)
1260       return false;
1261   return true;
1262 }
1263
1264 void SimpleRegisterCoalescing::CopyCoalesceInMBB(MachineBasicBlock *MBB,
1265                                                std::vector<CopyRec> &TryAgain) {
1266   DOUT << ((Value*)MBB->getBasicBlock())->getName() << ":\n";
1267
1268   std::vector<CopyRec> VirtCopies;
1269   std::vector<CopyRec> PhysCopies;
1270   unsigned LoopDepth = loopInfo->getLoopDepth(MBB);
1271   for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end();
1272        MII != E;) {
1273     MachineInstr *Inst = MII++;
1274     
1275     // If this isn't a copy nor a extract_subreg, we can't join intervals.
1276     unsigned SrcReg, DstReg;
1277     if (Inst->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG) {
1278       DstReg = Inst->getOperand(0).getReg();
1279       SrcReg = Inst->getOperand(1).getReg();
1280     } else if (!tii_->isMoveInstr(*Inst, SrcReg, DstReg))
1281       continue;
1282
1283     bool SrcIsPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
1284     bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
1285     if (NewHeuristic) {
1286       JoinQueue->push(CopyRec(Inst, LoopDepth, isBackEdgeCopy(Inst, DstReg)));
1287     } else {
1288       if (SrcIsPhys || DstIsPhys)
1289         PhysCopies.push_back(CopyRec(Inst, 0, false));
1290       else
1291         VirtCopies.push_back(CopyRec(Inst, 0, false));
1292     }
1293   }
1294
1295   if (NewHeuristic)
1296     return;
1297
1298   // Try coalescing physical register + virtual register first.
1299   for (unsigned i = 0, e = PhysCopies.size(); i != e; ++i) {
1300     CopyRec &TheCopy = PhysCopies[i];
1301     bool Again = false;
1302     if (!JoinCopy(TheCopy, Again))
1303       if (Again)
1304         TryAgain.push_back(TheCopy);
1305   }
1306   for (unsigned i = 0, e = VirtCopies.size(); i != e; ++i) {
1307     CopyRec &TheCopy = VirtCopies[i];
1308     bool Again = false;
1309     if (!JoinCopy(TheCopy, Again))
1310       if (Again)
1311         TryAgain.push_back(TheCopy);
1312   }
1313 }
1314
1315 void SimpleRegisterCoalescing::joinIntervals() {
1316   DOUT << "********** JOINING INTERVALS ***********\n";
1317
1318   if (NewHeuristic)
1319     JoinQueue = new JoinPriorityQueue<CopyRecSort>(this);
1320
1321   std::vector<CopyRec> TryAgainList;
1322   if (loopInfo->begin() == loopInfo->end()) {
1323     // If there are no loops in the function, join intervals in function order.
1324     for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();
1325          I != E; ++I)
1326       CopyCoalesceInMBB(I, TryAgainList);
1327   } else {
1328     // Otherwise, join intervals in inner loops before other intervals.
1329     // Unfortunately we can't just iterate over loop hierarchy here because
1330     // there may be more MBB's than BB's.  Collect MBB's for sorting.
1331
1332     // Join intervals in the function prolog first. We want to join physical
1333     // registers with virtual registers before the intervals got too long.
1334     std::vector<std::pair<unsigned, MachineBasicBlock*> > MBBs;
1335     for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();I != E;++I){
1336       MachineBasicBlock *MBB = I;
1337       MBBs.push_back(std::make_pair(loopInfo->getLoopDepth(MBB), I));
1338     }
1339
1340     // Sort by loop depth.
1341     std::sort(MBBs.begin(), MBBs.end(), DepthMBBCompare());
1342
1343     // Finally, join intervals in loop nest order.
1344     for (unsigned i = 0, e = MBBs.size(); i != e; ++i)
1345       CopyCoalesceInMBB(MBBs[i].second, TryAgainList);
1346   }
1347   
1348   // Joining intervals can allow other intervals to be joined.  Iteratively join
1349   // until we make no progress.
1350   if (NewHeuristic) {
1351     SmallVector<CopyRec, 16> TryAgain;
1352     bool ProgressMade = true;
1353     while (ProgressMade) {
1354       ProgressMade = false;
1355       while (!JoinQueue->empty()) {
1356         CopyRec R = JoinQueue->pop();
1357         bool Again = false;
1358         bool Success = JoinCopy(R, Again);
1359         if (Success)
1360           ProgressMade = true;
1361         else if (Again)
1362           TryAgain.push_back(R);
1363       }
1364
1365       if (ProgressMade) {
1366         while (!TryAgain.empty()) {
1367           JoinQueue->push(TryAgain.back());
1368           TryAgain.pop_back();
1369         }
1370       }
1371     }
1372   } else {
1373     bool ProgressMade = true;
1374     while (ProgressMade) {
1375       ProgressMade = false;
1376
1377       for (unsigned i = 0, e = TryAgainList.size(); i != e; ++i) {
1378         CopyRec &TheCopy = TryAgainList[i];
1379         if (TheCopy.MI) {
1380           bool Again = false;
1381           bool Success = JoinCopy(TheCopy, Again);
1382           if (Success || !Again) {
1383             TheCopy.MI = 0;   // Mark this one as done.
1384             ProgressMade = true;
1385           }
1386         }
1387       }
1388     }
1389   }
1390
1391   if (NewHeuristic)
1392     delete JoinQueue;  
1393 }
1394
1395 /// Return true if the two specified registers belong to different register
1396 /// classes.  The registers may be either phys or virt regs.
1397 bool SimpleRegisterCoalescing::differingRegisterClasses(unsigned RegA,
1398                                                         unsigned RegB) const {
1399
1400   // Get the register classes for the first reg.
1401   if (TargetRegisterInfo::isPhysicalRegister(RegA)) {
1402     assert(TargetRegisterInfo::isVirtualRegister(RegB) &&
1403            "Shouldn't consider two physregs!");
1404     return !mri_->getRegClass(RegB)->contains(RegA);
1405   }
1406
1407   // Compare against the regclass for the second reg.
1408   const TargetRegisterClass *RegClass = mri_->getRegClass(RegA);
1409   if (TargetRegisterInfo::isVirtualRegister(RegB))
1410     return RegClass != mri_->getRegClass(RegB);
1411   else
1412     return !RegClass->contains(RegB);
1413 }
1414
1415 /// lastRegisterUse - Returns the last use of the specific register between
1416 /// cycles Start and End or NULL if there are no uses.
1417 MachineOperand *
1418 SimpleRegisterCoalescing::lastRegisterUse(unsigned Start, unsigned End,
1419                                           unsigned Reg, unsigned &UseIdx) const{
1420   UseIdx = 0;
1421   if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1422     MachineOperand *LastUse = NULL;
1423     for (MachineRegisterInfo::use_iterator I = mri_->use_begin(Reg),
1424            E = mri_->use_end(); I != E; ++I) {
1425       MachineOperand &Use = I.getOperand();
1426       MachineInstr *UseMI = Use.getParent();
1427       unsigned Idx = li_->getInstructionIndex(UseMI);
1428       if (Idx >= Start && Idx < End && Idx >= UseIdx) {
1429         LastUse = &Use;
1430         UseIdx = Idx;
1431       }
1432     }
1433     return LastUse;
1434   }
1435
1436   int e = (End-1) / InstrSlots::NUM * InstrSlots::NUM;
1437   int s = Start;
1438   while (e >= s) {
1439     // Skip deleted instructions
1440     MachineInstr *MI = li_->getInstructionFromIndex(e);
1441     while ((e - InstrSlots::NUM) >= s && !MI) {
1442       e -= InstrSlots::NUM;
1443       MI = li_->getInstructionFromIndex(e);
1444     }
1445     if (e < s || MI == NULL)
1446       return NULL;
1447
1448     for (unsigned i = 0, NumOps = MI->getNumOperands(); i != NumOps; ++i) {
1449       MachineOperand &Use = MI->getOperand(i);
1450       if (Use.isRegister() && Use.isUse() && Use.getReg() &&
1451           tri_->regsOverlap(Use.getReg(), Reg)) {
1452         UseIdx = e;
1453         return &Use;
1454       }
1455     }
1456
1457     e -= InstrSlots::NUM;
1458   }
1459
1460   return NULL;
1461 }
1462
1463
1464 /// findDefOperand - Returns the MachineOperand that is a def of the specific
1465 /// register. It returns NULL if the def is not found.
1466 /// FIXME: Move to MachineInstr.
1467 MachineOperand *SimpleRegisterCoalescing::findDefOperand(MachineInstr *MI,
1468                                                          unsigned Reg) const {
1469   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1470     MachineOperand &MO = MI->getOperand(i);
1471     if (MO.isRegister() && MO.isDef() &&
1472         tri_->regsOverlap(MO.getReg(), Reg))
1473       return &MO;
1474   }
1475   return NULL;
1476 }
1477
1478 /// RemoveUnnecessaryKills - Remove kill markers that are no longer accurate
1479 /// due to live range lengthening as the result of coalescing.
1480 void SimpleRegisterCoalescing::printRegName(unsigned reg) const {
1481   if (TargetRegisterInfo::isPhysicalRegister(reg))
1482     cerr << tri_->getName(reg);
1483   else
1484     cerr << "%reg" << reg;
1485 }
1486
1487 void SimpleRegisterCoalescing::releaseMemory() {
1488   JoinedCopies.clear();
1489 }
1490
1491 static bool isZeroLengthInterval(LiveInterval *li) {
1492   for (LiveInterval::Ranges::const_iterator
1493          i = li->ranges.begin(), e = li->ranges.end(); i != e; ++i)
1494     if (i->end - i->start > LiveIntervals::InstrSlots::NUM)
1495       return false;
1496   return true;
1497 }
1498
1499 bool SimpleRegisterCoalescing::runOnMachineFunction(MachineFunction &fn) {
1500   mf_ = &fn;
1501   mri_ = &fn.getRegInfo();
1502   tm_ = &fn.getTarget();
1503   tri_ = tm_->getRegisterInfo();
1504   tii_ = tm_->getInstrInfo();
1505   li_ = &getAnalysis<LiveIntervals>();
1506   lv_ = &getAnalysis<LiveVariables>();
1507   loopInfo = &getAnalysis<MachineLoopInfo>();
1508
1509   DOUT << "********** SIMPLE REGISTER COALESCING **********\n"
1510        << "********** Function: "
1511        << ((Value*)mf_->getFunction())->getName() << '\n';
1512
1513   allocatableRegs_ = tri_->getAllocatableSet(fn);
1514   for (TargetRegisterInfo::regclass_iterator I = tri_->regclass_begin(),
1515          E = tri_->regclass_end(); I != E; ++I)
1516     allocatableRCRegs_.insert(std::make_pair(*I,
1517                                              tri_->getAllocatableSet(fn, *I)));
1518
1519   // Join (coalesce) intervals if requested.
1520   if (EnableJoining) {
1521     joinIntervals();
1522     DOUT << "********** INTERVALS POST JOINING **********\n";
1523     for (LiveIntervals::iterator I = li_->begin(), E = li_->end(); I != E; ++I){
1524       I->second.print(DOUT, tri_);
1525       DOUT << "\n";
1526     }
1527
1528     // Delete all coalesced copies.
1529     for (SmallPtrSet<MachineInstr*,32>::iterator I = JoinedCopies.begin(),
1530            E = JoinedCopies.end(); I != E; ++I) {
1531       li_->RemoveMachineInstrFromMaps(*I);
1532       (*I)->eraseFromParent();
1533       ++numPeep;
1534     }
1535   }
1536
1537   // Perform a final pass over the instructions and compute spill weights
1538   // and remove identity moves.
1539   for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
1540        mbbi != mbbe; ++mbbi) {
1541     MachineBasicBlock* mbb = mbbi;
1542     unsigned loopDepth = loopInfo->getLoopDepth(mbb);
1543
1544     for (MachineBasicBlock::iterator mii = mbb->begin(), mie = mbb->end();
1545          mii != mie; ) {
1546       // if the move will be an identity move delete it
1547       unsigned srcReg, dstReg;
1548       if (tii_->isMoveInstr(*mii, srcReg, dstReg) && srcReg == dstReg) {
1549         // remove from def list
1550         LiveInterval &RegInt = li_->getOrCreateInterval(srcReg);
1551         MachineOperand *MO = mii->findRegisterDefOperand(dstReg);
1552         // If def of this move instruction is dead, remove its live range from
1553         // the dstination register's live interval.
1554         if (MO->isDead()) {
1555           unsigned MoveIdx = li_->getDefIndex(li_->getInstructionIndex(mii));
1556           LiveInterval::iterator MLR = RegInt.FindLiveRangeContaining(MoveIdx);
1557           RegInt.removeRange(MLR->start, MoveIdx+1, true);
1558           if (RegInt.empty())
1559             li_->removeInterval(srcReg);
1560         }
1561         li_->RemoveMachineInstrFromMaps(mii);
1562         mii = mbbi->erase(mii);
1563         ++numPeep;
1564       } else {
1565         SmallSet<unsigned, 4> UniqueUses;
1566         for (unsigned i = 0, e = mii->getNumOperands(); i != e; ++i) {
1567           const MachineOperand &mop = mii->getOperand(i);
1568           if (mop.isRegister() && mop.getReg() &&
1569               TargetRegisterInfo::isVirtualRegister(mop.getReg())) {
1570             unsigned reg = mop.getReg();
1571             // Multiple uses of reg by the same instruction. It should not
1572             // contribute to spill weight again.
1573             if (UniqueUses.count(reg) != 0)
1574               continue;
1575             LiveInterval &RegInt = li_->getInterval(reg);
1576             RegInt.weight +=
1577               li_->getSpillWeight(mop.isDef(), mop.isUse(), loopDepth);
1578             UniqueUses.insert(reg);
1579           }
1580         }
1581         ++mii;
1582       }
1583     }
1584   }
1585
1586   for (LiveIntervals::iterator I = li_->begin(), E = li_->end(); I != E; ++I) {
1587     LiveInterval &LI = I->second;
1588     if (TargetRegisterInfo::isVirtualRegister(LI.reg)) {
1589       // If the live interval length is essentially zero, i.e. in every live
1590       // range the use follows def immediately, it doesn't make sense to spill
1591       // it and hope it will be easier to allocate for this li.
1592       if (isZeroLengthInterval(&LI))
1593         LI.weight = HUGE_VALF;
1594       else {
1595         bool isLoad = false;
1596         if (li_->isReMaterializable(LI, isLoad)) {
1597           // If all of the definitions of the interval are re-materializable,
1598           // it is a preferred candidate for spilling. If non of the defs are
1599           // loads, then it's potentially very cheap to re-materialize.
1600           // FIXME: this gets much more complicated once we support non-trivial
1601           // re-materialization.
1602           if (isLoad)
1603             LI.weight *= 0.9F;
1604           else
1605             LI.weight *= 0.5F;
1606         }
1607       }
1608
1609       // Slightly prefer live interval that has been assigned a preferred reg.
1610       if (LI.preference)
1611         LI.weight *= 1.01F;
1612
1613       // Divide the weight of the interval by its size.  This encourages 
1614       // spilling of intervals that are large and have few uses, and
1615       // discourages spilling of small intervals with many uses.
1616       LI.weight /= LI.getSize();
1617     }
1618   }
1619
1620   DEBUG(dump());
1621   return true;
1622 }
1623
1624 /// print - Implement the dump method.
1625 void SimpleRegisterCoalescing::print(std::ostream &O, const Module* m) const {
1626    li_->print(O, m);
1627 }
1628
1629 RegisterCoalescer* llvm::createSimpleRegisterCoalescer() {
1630   return new SimpleRegisterCoalescing();
1631 }
1632
1633 // Make sure that anything that uses RegisterCoalescer pulls in this file...
1634 DEFINING_FILE_FOR(SimpleRegisterCoalescing)