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