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