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