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