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