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