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