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