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