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