e69d3e4fa78aa0887568b6ddd48fc83a33067b36
[oota-llvm.git] / lib / CodeGen / SimpleRegisterCoalescing.cpp
1 //===-- SimpleRegisterCoalescing.cpp - Register Coalescing ----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements a simple register coalescing pass that attempts to
11 // aggressively coalesce every register copy that it can.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "regcoalescing"
16 #include "SimpleRegisterCoalescing.h"
17 #include "VirtRegMap.h"
18 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
19 #include "llvm/Value.h"
20 #include "llvm/Analysis/AliasAnalysis.h"
21 #include "llvm/CodeGen/MachineFrameInfo.h"
22 #include "llvm/CodeGen/MachineInstr.h"
23 #include "llvm/CodeGen/MachineLoopInfo.h"
24 #include "llvm/CodeGen/MachineRegisterInfo.h"
25 #include "llvm/CodeGen/Passes.h"
26 #include "llvm/CodeGen/RegisterCoalescer.h"
27 #include "llvm/Target/TargetInstrInfo.h"
28 #include "llvm/Target/TargetMachine.h"
29 #include "llvm/Target/TargetOptions.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include "llvm/ADT/OwningPtr.h"
35 #include "llvm/ADT/SmallSet.h"
36 #include "llvm/ADT/Statistic.h"
37 #include "llvm/ADT/STLExtras.h"
38 #include <algorithm>
39 #include <cmath>
40 using namespace llvm;
41
42 STATISTIC(numJoins    , "Number of interval joins performed");
43 STATISTIC(numCrossRCs , "Number of cross class joins performed");
44 STATISTIC(numCommutes , "Number of instruction commuting performed");
45 STATISTIC(numExtends  , "Number of copies extended");
46 STATISTIC(NumReMats   , "Number of instructions re-materialized");
47 STATISTIC(numPeep     , "Number of identity moves eliminated after coalescing");
48 STATISTIC(numAborts   , "Number of times interval joining aborted");
49 STATISTIC(numDeadValNo, "Number of valno def marked dead");
50
51 char SimpleRegisterCoalescing::ID = 0;
52 static cl::opt<bool>
53 EnableJoining("join-liveintervals",
54               cl::desc("Coalesce copies (default=true)"),
55               cl::init(true));
56
57 static cl::opt<bool>
58 DisableCrossClassJoin("disable-cross-class-join",
59                cl::desc("Avoid coalescing cross register class copies"),
60                cl::init(false), cl::Hidden);
61
62 static RegisterPass<SimpleRegisterCoalescing>
63 X("simple-register-coalescing", "Simple Register Coalescing");
64
65 // Declare that we implement the RegisterCoalescer interface
66 static RegisterAnalysisGroup<RegisterCoalescer, true/*The Default*/> V(X);
67
68 const PassInfo *const llvm::SimpleRegisterCoalescingID = &X;
69
70 void SimpleRegisterCoalescing::getAnalysisUsage(AnalysisUsage &AU) const {
71   AU.setPreservesCFG();
72   AU.addRequired<AliasAnalysis>();
73   AU.addRequired<LiveIntervals>();
74   AU.addPreserved<LiveIntervals>();
75   AU.addPreserved<SlotIndexes>();
76   AU.addRequired<MachineLoopInfo>();
77   AU.addPreserved<MachineLoopInfo>();
78   AU.addPreservedID(MachineDominatorsID);
79   if (StrongPHIElim)
80     AU.addPreservedID(StrongPHIEliminationID);
81   else
82     AU.addPreservedID(PHIEliminationID);
83   AU.addPreservedID(TwoAddressInstructionPassID);
84   MachineFunctionPass::getAnalysisUsage(AU);
85 }
86
87 /// AdjustCopiesBackFrom - We found a non-trivially-coalescable copy with IntA
88 /// being the source and IntB being the dest, thus this defines a value number
89 /// in IntB.  If the source value number (in IntA) is defined by a copy from B,
90 /// see if we can merge these two pieces of B into a single value number,
91 /// eliminating a copy.  For example:
92 ///
93 ///  A3 = B0
94 ///    ...
95 ///  B1 = A3      <- this copy
96 ///
97 /// In this case, B0 can be extended to where the B1 copy lives, allowing the B1
98 /// value number to be replaced with B0 (which simplifies the B liveinterval).
99 ///
100 /// This returns true if an interval was modified.
101 ///
102 bool SimpleRegisterCoalescing::AdjustCopiesBackFrom(const CoalescerPair &CP,
103                                                     MachineInstr *CopyMI) {
104   // Bail if there is no dst interval - can happen when merging physical subreg
105   // operations.
106   if (!li_->hasInterval(CP.getDstReg()))
107     return false;
108
109   LiveInterval &IntA =
110     li_->getInterval(CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg());
111   LiveInterval &IntB =
112     li_->getInterval(CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg());
113   SlotIndex CopyIdx = li_->getInstructionIndex(CopyMI).getDefIndex();
114
115   // BValNo is a value number in B that is defined by a copy from A.  'B3' in
116   // the example above.
117   LiveInterval::iterator BLR = IntB.FindLiveRangeContaining(CopyIdx);
118   if (BLR == IntB.end()) return false;
119   VNInfo *BValNo = BLR->valno;
120
121   // Get the location that B is defined at.  Two options: either this value has
122   // an unknown definition point or it is defined at CopyIdx.  If unknown, we
123   // can't process it.
124   if (!BValNo->getCopy()) return false;
125   assert(BValNo->def == CopyIdx && "Copy doesn't define the value?");
126
127   // AValNo is the value number in A that defines the copy, A3 in the example.
128   SlotIndex CopyUseIdx = CopyIdx.getUseIndex();
129   LiveInterval::iterator ALR = IntA.FindLiveRangeContaining(CopyUseIdx);
130   // The live range might not exist after fun with physreg coalescing.
131   if (ALR == IntA.end()) return false;
132   VNInfo *AValNo = ALR->valno;
133   // If it's re-defined by an early clobber somewhere in the live range, then
134   // it's not safe to eliminate the copy. FIXME: This is a temporary workaround.
135   // See PR3149:
136   // 172     %ECX<def> = MOV32rr %reg1039<kill>
137   // 180     INLINEASM <es:subl $5,$1
138   //         sbbl $3,$0>, 10, %EAX<def>, 14, %ECX<earlyclobber,def>, 9,
139   //         %EAX<kill>,
140   // 36, <fi#0>, 1, %reg0, 0, 9, %ECX<kill>, 36, <fi#1>, 1, %reg0, 0
141   // 188     %EAX<def> = MOV32rr %EAX<kill>
142   // 196     %ECX<def> = MOV32rr %ECX<kill>
143   // 204     %ECX<def> = MOV32rr %ECX<kill>
144   // 212     %EAX<def> = MOV32rr %EAX<kill>
145   // 220     %EAX<def> = MOV32rr %EAX
146   // 228     %reg1039<def> = MOV32rr %ECX<kill>
147   // The early clobber operand ties ECX input to the ECX def.
148   //
149   // The live interval of ECX is represented as this:
150   // %reg20,inf = [46,47:1)[174,230:0)  0@174-(230) 1@46-(47)
151   // The coalescer has no idea there was a def in the middle of [174,230].
152   if (AValNo->hasRedefByEC())
153     return false;
154
155   // If AValNo is defined as a copy from IntB, we can potentially process this.
156   // Get the instruction that defines this value number.
157   if (!CP.isCoalescable(AValNo->getCopy()))
158     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   if (ValLR == IntB.end())
164     return false;
165
166   // Make sure that the end of the live range is inside the same block as
167   // CopyMI.
168   MachineInstr *ValLREndInst =
169     li_->getInstructionFromIndex(ValLR->end.getPrevSlot());
170   if (!ValLREndInst || ValLREndInst->getParent() != CopyMI->getParent())
171     return false;
172
173   // Okay, we now know that ValLR ends in the same block that the CopyMI
174   // live-range starts.  If there are no intervening live ranges between them in
175   // IntB, we can merge them.
176   if (ValLR+1 != BLR) return false;
177
178   // If a live interval is a physical register, conservatively check if any
179   // of its sub-registers is overlapping the live interval of the virtual
180   // register. If so, do not coalesce.
181   if (TargetRegisterInfo::isPhysicalRegister(IntB.reg) &&
182       *tri_->getSubRegisters(IntB.reg)) {
183     for (const unsigned* SR = tri_->getSubRegisters(IntB.reg); *SR; ++SR)
184       if (li_->hasInterval(*SR) && IntA.overlaps(li_->getInterval(*SR))) {
185         DEBUG({
186             dbgs() << "\t\tInterfere with sub-register ";
187             li_->getInterval(*SR).print(dbgs(), tri_);
188           });
189         return false;
190       }
191   }
192
193   DEBUG({
194       dbgs() << "Extending: ";
195       IntB.print(dbgs(), tri_);
196     });
197
198   SlotIndex FillerStart = ValLR->end, FillerEnd = BLR->start;
199   // We are about to delete CopyMI, so need to remove it as the 'instruction
200   // that defines this value #'. Update the valnum with the new defining
201   // instruction #.
202   BValNo->def  = FillerStart;
203   BValNo->setCopy(0);
204
205   // Okay, we can merge them.  We need to insert a new liverange:
206   // [ValLR.end, BLR.begin) of either value number, then we merge the
207   // two value numbers.
208   IntB.addRange(LiveRange(FillerStart, FillerEnd, BValNo));
209
210   // If the IntB live range is assigned to a physical register, and if that
211   // physreg has sub-registers, update their live intervals as well.
212   if (TargetRegisterInfo::isPhysicalRegister(IntB.reg)) {
213     for (const unsigned *SR = tri_->getSubRegisters(IntB.reg); *SR; ++SR) {
214       if (!li_->hasInterval(*SR))
215         continue;
216       LiveInterval &SRLI = li_->getInterval(*SR);
217       SRLI.addRange(LiveRange(FillerStart, FillerEnd,
218                               SRLI.getNextValue(FillerStart, 0, true,
219                                                 li_->getVNInfoAllocator())));
220     }
221   }
222
223   // Okay, merge "B1" into the same value number as "B0".
224   if (BValNo != ValLR->valno) {
225     IntB.MergeValueNumberInto(BValNo, ValLR->valno);
226   }
227   DEBUG({
228       dbgs() << "   result = ";
229       IntB.print(dbgs(), tri_);
230       dbgs() << "\n";
231     });
232
233   // If the source instruction was killing the source register before the
234   // merge, unset the isKill marker given the live range has been extended.
235   int UIdx = ValLREndInst->findRegisterUseOperandIdx(IntB.reg, true);
236   if (UIdx != -1) {
237     ValLREndInst->getOperand(UIdx).setIsKill(false);
238   }
239
240   // If the copy instruction was killing the destination register before the
241   // merge, find the last use and trim the live range. That will also add the
242   // isKill marker.
243   if (ALR->end == CopyIdx)
244     TrimLiveIntervalToLastUse(CopyUseIdx, CopyMI->getParent(), IntA, ALR);
245
246   ++numExtends;
247   return true;
248 }
249
250 /// HasOtherReachingDefs - Return true if there are definitions of IntB
251 /// other than BValNo val# that can reach uses of AValno val# of IntA.
252 bool SimpleRegisterCoalescing::HasOtherReachingDefs(LiveInterval &IntA,
253                                                     LiveInterval &IntB,
254                                                     VNInfo *AValNo,
255                                                     VNInfo *BValNo) {
256   for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
257        AI != AE; ++AI) {
258     if (AI->valno != AValNo) continue;
259     LiveInterval::Ranges::iterator BI =
260       std::upper_bound(IntB.ranges.begin(), IntB.ranges.end(), AI->start);
261     if (BI != IntB.ranges.begin())
262       --BI;
263     for (; BI != IntB.ranges.end() && AI->end >= BI->start; ++BI) {
264       if (BI->valno == BValNo)
265         continue;
266       // When BValNo is null, we're looking for a dummy clobber-value for a subreg.
267       if (!BValNo && !BI->valno->isDefAccurate() && !BI->valno->getCopy())
268         continue;
269       if (BI->start <= AI->start && BI->end > AI->start)
270         return true;
271       if (BI->start > AI->start && BI->start < AI->end)
272         return true;
273     }
274   }
275   return false;
276 }
277
278 static void
279 TransferImplicitOps(MachineInstr *MI, MachineInstr *NewMI) {
280   for (unsigned i = MI->getDesc().getNumOperands(), e = MI->getNumOperands();
281        i != e; ++i) {
282     MachineOperand &MO = MI->getOperand(i);
283     if (MO.isReg() && MO.isImplicit())
284       NewMI->addOperand(MO);
285   }
286 }
287
288 /// RemoveCopyByCommutingDef - We found a non-trivially-coalescable copy with
289 /// IntA being the source and IntB being the dest, thus this defines a value
290 /// number in IntB.  If the source value number (in IntA) is defined by a
291 /// commutable instruction and its other operand is coalesced to the copy dest
292 /// register, see if we can transform the copy into a noop by commuting the
293 /// definition. For example,
294 ///
295 ///  A3 = op A2 B0<kill>
296 ///    ...
297 ///  B1 = A3      <- this copy
298 ///    ...
299 ///     = op A3   <- more uses
300 ///
301 /// ==>
302 ///
303 ///  B2 = op B0 A2<kill>
304 ///    ...
305 ///  B1 = B2      <- now an identify copy
306 ///    ...
307 ///     = op B2   <- more uses
308 ///
309 /// This returns true if an interval was modified.
310 ///
311 bool SimpleRegisterCoalescing::RemoveCopyByCommutingDef(const CoalescerPair &CP,
312                                                         MachineInstr *CopyMI) {
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 (CP.isPhys() && CP.isFlipped())
318     return false;
319
320   // Bail if there is no dst interval.
321   if (!li_->hasInterval(CP.getDstReg()))
322     return false;
323
324   SlotIndex CopyIdx =
325     li_->getInstructionIndex(CopyMI).getDefIndex();
326
327   LiveInterval &IntA =
328     li_->getInterval(CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg());
329   LiveInterval &IntB =
330     li_->getInterval(CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg());
331
332   // BValNo is a value number in B that is defined by a copy from A. 'B3' in
333   // the example above.
334   LiveInterval::iterator BLR = IntB.FindLiveRangeContaining(CopyIdx);
335   if (BLR == IntB.end()) return false;
336   VNInfo *BValNo = BLR->valno;
337
338   // Get the location that B is defined at.  Two options: either this value has
339   // an unknown definition point or it is defined at CopyIdx.  If unknown, we
340   // can't process it.
341   if (!BValNo->getCopy()) return false;
342   assert(BValNo->def == CopyIdx && "Copy doesn't define the value?");
343
344   // AValNo is the value number in A that defines the copy, A3 in the example.
345   LiveInterval::iterator ALR =
346     IntA.FindLiveRangeContaining(CopyIdx.getUseIndex()); // 
347
348   assert(ALR != IntA.end() && "Live range not found!");
349   VNInfo *AValNo = ALR->valno;
350   // If other defs can reach uses of this def, then it's not safe to perform
351   // the optimization. FIXME: Do isPHIDef and isDefAccurate both need to be
352   // tested?
353   if (AValNo->isPHIDef() || !AValNo->isDefAccurate() ||
354       AValNo->isUnused() || AValNo->hasPHIKill())
355     return false;
356   MachineInstr *DefMI = li_->getInstructionFromIndex(AValNo->def);
357   if (!DefMI)
358     return false;
359   const TargetInstrDesc &TID = DefMI->getDesc();
360   if (!TID.isCommutable())
361     return false;
362   // If DefMI is a two-address instruction then commuting it will change the
363   // destination register.
364   int DefIdx = DefMI->findRegisterDefOperandIdx(IntA.reg);
365   assert(DefIdx != -1);
366   unsigned UseOpIdx;
367   if (!DefMI->isRegTiedToUseOperand(DefIdx, &UseOpIdx))
368     return false;
369   unsigned Op1, Op2, NewDstIdx;
370   if (!tii_->findCommutedOpIndices(DefMI, Op1, Op2))
371     return false;
372   if (Op1 == UseOpIdx)
373     NewDstIdx = Op2;
374   else if (Op2 == UseOpIdx)
375     NewDstIdx = Op1;
376   else
377     return false;
378
379   MachineOperand &NewDstMO = DefMI->getOperand(NewDstIdx);
380   unsigned NewReg = NewDstMO.getReg();
381   if (NewReg != IntB.reg || !NewDstMO.isKill())
382     return false;
383
384   // Make sure there are no other definitions of IntB that would reach the
385   // uses which the new definition can reach.
386   if (HasOtherReachingDefs(IntA, IntB, AValNo, BValNo))
387     return false;
388
389   bool BHasSubRegs = false;
390   if (TargetRegisterInfo::isPhysicalRegister(IntB.reg))
391     BHasSubRegs = *tri_->getSubRegisters(IntB.reg);
392
393   // Abort if the subregisters of IntB.reg have values that are not simply the
394   // clobbers from the superreg.
395   if (BHasSubRegs)
396     for (const unsigned *SR = tri_->getSubRegisters(IntB.reg); *SR; ++SR)
397       if (li_->hasInterval(*SR) &&
398           HasOtherReachingDefs(IntA, li_->getInterval(*SR), AValNo, 0))
399         return false;
400
401   // If some of the uses of IntA.reg is already coalesced away, return false.
402   // It's not possible to determine whether it's safe to perform the coalescing.
403   for (MachineRegisterInfo::use_nodbg_iterator UI = 
404          mri_->use_nodbg_begin(IntA.reg), 
405        UE = mri_->use_nodbg_end(); UI != UE; ++UI) {
406     MachineInstr *UseMI = &*UI;
407     SlotIndex UseIdx = li_->getInstructionIndex(UseMI);
408     LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx);
409     if (ULR == IntA.end())
410       continue;
411     if (ULR->valno == AValNo && JoinedCopies.count(UseMI))
412       return false;
413   }
414
415   // At this point we have decided that it is legal to do this
416   // transformation.  Start by commuting the instruction.
417   MachineBasicBlock *MBB = DefMI->getParent();
418   MachineInstr *NewMI = tii_->commuteInstruction(DefMI);
419   if (!NewMI)
420     return false;
421   if (NewMI != DefMI) {
422     li_->ReplaceMachineInstrInMaps(DefMI, NewMI);
423     MBB->insert(DefMI, NewMI);
424     MBB->erase(DefMI);
425   }
426   unsigned OpIdx = NewMI->findRegisterUseOperandIdx(IntA.reg, false);
427   NewMI->getOperand(OpIdx).setIsKill();
428
429   bool BHasPHIKill = BValNo->hasPHIKill();
430   SmallVector<VNInfo*, 4> BDeadValNos;
431   std::map<SlotIndex, SlotIndex> BExtend;
432
433   // If ALR and BLR overlaps and end of BLR extends beyond end of ALR, e.g.
434   // A = or A, B
435   // ...
436   // B = A
437   // ...
438   // C = A<kill>
439   // ...
440   //   = B
441   bool Extended = BLR->end > ALR->end && ALR->end != ALR->start;
442   if (Extended)
443     BExtend[ALR->end] = BLR->end;
444
445   // Update uses of IntA of the specific Val# with IntB.
446   for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(IntA.reg),
447          UE = mri_->use_end(); UI != UE;) {
448     MachineOperand &UseMO = UI.getOperand();
449     MachineInstr *UseMI = &*UI;
450     ++UI;
451     if (JoinedCopies.count(UseMI))
452       continue;
453     if (UseMI->isDebugValue()) {
454       // FIXME These don't have an instruction index.  Not clear we have enough
455       // info to decide whether to do this replacement or not.  For now do it.
456       UseMO.setReg(NewReg);
457       continue;
458     }
459     SlotIndex UseIdx = li_->getInstructionIndex(UseMI).getUseIndex();
460     LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx);
461     if (ULR == IntA.end() || ULR->valno != AValNo)
462       continue;
463     if (TargetRegisterInfo::isPhysicalRegister(NewReg))
464       UseMO.substPhysReg(NewReg, *tri_);
465     else
466       UseMO.setReg(NewReg);
467     if (UseMI == CopyMI)
468       continue;
469     if (UseMO.isKill()) {
470       if (Extended)
471         UseMO.setIsKill(false);
472     }
473     unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
474     if (UseMI->isCopy()) {
475       if (UseMI->getOperand(0).getReg() != IntB.reg ||
476           UseMI->getOperand(0).getSubReg())
477         continue;
478     } else if (tii_->isMoveInstr(*UseMI, SrcReg, DstReg, SrcSubIdx, DstSubIdx)){
479       if (DstReg != IntB.reg || DstSubIdx)
480         continue;
481     } else
482       continue;
483     // This copy will become a noop. If it's defining a new val#,
484     // remove that val# as well. However this live range is being
485     // extended to the end of the existing live range defined by the copy.
486     SlotIndex DefIdx = UseIdx.getDefIndex();
487     const LiveRange *DLR = IntB.getLiveRangeContaining(DefIdx);
488     if (!DLR)
489       continue;
490     BHasPHIKill |= DLR->valno->hasPHIKill();
491     assert(DLR->valno->def == DefIdx);
492     BDeadValNos.push_back(DLR->valno);
493     BExtend[DLR->start] = DLR->end;
494     JoinedCopies.insert(UseMI);
495   }
496
497   // We need to insert a new liverange: [ALR.start, LastUse). It may be we can
498   // simply extend BLR if CopyMI doesn't end the range.
499   DEBUG({
500       dbgs() << "Extending: ";
501       IntB.print(dbgs(), tri_);
502     });
503
504   // Remove val#'s defined by copies that will be coalesced away.
505   for (unsigned i = 0, e = BDeadValNos.size(); i != e; ++i) {
506     VNInfo *DeadVNI = BDeadValNos[i];
507     if (BHasSubRegs) {
508       for (const unsigned *SR = tri_->getSubRegisters(IntB.reg); *SR; ++SR) {
509         if (!li_->hasInterval(*SR))
510           continue;
511         LiveInterval &SRLI = li_->getInterval(*SR);
512         if (const LiveRange *SRLR = SRLI.getLiveRangeContaining(DeadVNI->def))
513           SRLI.removeValNo(SRLR->valno);
514       }
515     }
516     IntB.removeValNo(BDeadValNos[i]);
517   }
518
519   // Extend BValNo by merging in IntA live ranges of AValNo. Val# definition
520   // is updated.
521   VNInfo *ValNo = BValNo;
522   ValNo->def = AValNo->def;
523   ValNo->setCopy(0);
524   for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
525        AI != AE; ++AI) {
526     if (AI->valno != AValNo) continue;
527     SlotIndex End = AI->end;
528     std::map<SlotIndex, SlotIndex>::iterator
529       EI = BExtend.find(End);
530     if (EI != BExtend.end())
531       End = EI->second;
532     IntB.addRange(LiveRange(AI->start, End, ValNo));
533   }
534   ValNo->setHasPHIKill(BHasPHIKill);
535
536   DEBUG({
537       dbgs() << "   result = ";
538       IntB.print(dbgs(), tri_);
539       dbgs() << "\nShortening: ";
540       IntA.print(dbgs(), tri_);
541     });
542
543   IntA.removeValNo(AValNo);
544
545   DEBUG({
546       dbgs() << "   result = ";
547       IntA.print(dbgs(), tri_);
548       dbgs() << '\n';
549     });
550
551   ++numCommutes;
552   return true;
553 }
554
555 /// isSameOrFallThroughBB - Return true if MBB == SuccMBB or MBB simply
556 /// fallthoughs to SuccMBB.
557 static bool isSameOrFallThroughBB(MachineBasicBlock *MBB,
558                                   MachineBasicBlock *SuccMBB,
559                                   const TargetInstrInfo *tii_) {
560   if (MBB == SuccMBB)
561     return true;
562   MachineBasicBlock *TBB = 0, *FBB = 0;
563   SmallVector<MachineOperand, 4> Cond;
564   return !tii_->AnalyzeBranch(*MBB, TBB, FBB, Cond) && !TBB && !FBB &&
565     MBB->isSuccessor(SuccMBB);
566 }
567
568 /// removeRange - Wrapper for LiveInterval::removeRange. This removes a range
569 /// from a physical register live interval as well as from the live intervals
570 /// of its sub-registers.
571 static void removeRange(LiveInterval &li,
572                         SlotIndex Start, SlotIndex End,
573                         LiveIntervals *li_, const TargetRegisterInfo *tri_) {
574   li.removeRange(Start, End, true);
575   if (TargetRegisterInfo::isPhysicalRegister(li.reg)) {
576     for (const unsigned* SR = tri_->getSubRegisters(li.reg); *SR; ++SR) {
577       if (!li_->hasInterval(*SR))
578         continue;
579       LiveInterval &sli = li_->getInterval(*SR);
580       SlotIndex RemoveStart = Start;
581       SlotIndex RemoveEnd = Start;
582
583       while (RemoveEnd != End) {
584         LiveInterval::iterator LR = sli.FindLiveRangeContaining(RemoveStart);
585         if (LR == sli.end())
586           break;
587         RemoveEnd = (LR->end < End) ? LR->end : End;
588         sli.removeRange(RemoveStart, RemoveEnd, true);
589         RemoveStart = RemoveEnd;
590       }
591     }
592   }
593 }
594
595 /// TrimLiveIntervalToLastUse - If there is a last use in the same basic block
596 /// as the copy instruction, trim the live interval to the last use and return
597 /// true.
598 bool
599 SimpleRegisterCoalescing::TrimLiveIntervalToLastUse(SlotIndex CopyIdx,
600                                                     MachineBasicBlock *CopyMBB,
601                                                     LiveInterval &li,
602                                                     const LiveRange *LR) {
603   SlotIndex MBBStart = li_->getMBBStartIdx(CopyMBB);
604   SlotIndex LastUseIdx;
605   MachineOperand *LastUse =
606     lastRegisterUse(LR->start, CopyIdx.getPrevSlot(), li.reg, LastUseIdx);
607   if (LastUse) {
608     MachineInstr *LastUseMI = LastUse->getParent();
609     if (!isSameOrFallThroughBB(LastUseMI->getParent(), CopyMBB, tii_)) {
610       // r1024 = op
611       // ...
612       // BB1:
613       //       = r1024
614       //
615       // BB2:
616       // r1025<dead> = r1024<kill>
617       if (MBBStart < LR->end)
618         removeRange(li, MBBStart, LR->end, li_, tri_);
619       return true;
620     }
621
622     // There are uses before the copy, just shorten the live range to the end
623     // of last use.
624     LastUse->setIsKill();
625     removeRange(li, LastUseIdx.getDefIndex(), LR->end, li_, tri_);
626     if (LastUseMI->isCopy()) {
627       MachineOperand &DefMO = LastUseMI->getOperand(0);
628       if (DefMO.getReg() == li.reg && !DefMO.getSubReg())
629         DefMO.setIsDead();
630     }
631     unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
632     if (tii_->isMoveInstr(*LastUseMI, SrcReg, DstReg, SrcSubIdx, DstSubIdx) &&
633         DstReg == li.reg && DstSubIdx == 0) {
634       // Last use is itself an identity code.
635       int DeadIdx = LastUseMI->findRegisterDefOperandIdx(li.reg,
636                                                          false, false, tri_);
637       LastUseMI->getOperand(DeadIdx).setIsDead();
638     }
639     return true;
640   }
641
642   // Is it livein?
643   if (LR->start <= MBBStart && LR->end > MBBStart) {
644     if (LR->start == li_->getZeroIndex()) {
645       assert(TargetRegisterInfo::isPhysicalRegister(li.reg));
646       // Live-in to the function but dead. Remove it from entry live-in set.
647       mf_->begin()->removeLiveIn(li.reg);
648     }
649     // FIXME: Shorten intervals in BBs that reaches this BB.
650   }
651
652   return false;
653 }
654
655 /// ReMaterializeTrivialDef - If the source of a copy is defined by a trivial
656 /// computation, replace the copy by rematerialize the definition.
657 bool SimpleRegisterCoalescing::ReMaterializeTrivialDef(LiveInterval &SrcInt,
658                                                        unsigned DstReg,
659                                                        unsigned DstSubIdx,
660                                                        MachineInstr *CopyMI) {
661   SlotIndex CopyIdx = li_->getInstructionIndex(CopyMI).getUseIndex();
662   LiveInterval::iterator SrcLR = SrcInt.FindLiveRangeContaining(CopyIdx);
663   assert(SrcLR != SrcInt.end() && "Live range not found!");
664   VNInfo *ValNo = SrcLR->valno;
665   // If other defs can reach uses of this def, then it's not safe to perform
666   // the optimization. FIXME: Do isPHIDef and isDefAccurate both need to be
667   // tested?
668   if (ValNo->isPHIDef() || !ValNo->isDefAccurate() ||
669       ValNo->isUnused() || ValNo->hasPHIKill())
670     return false;
671   MachineInstr *DefMI = li_->getInstructionFromIndex(ValNo->def);
672   assert(DefMI && "Defining instruction disappeared");
673   const TargetInstrDesc &TID = DefMI->getDesc();
674   if (!TID.isAsCheapAsAMove())
675     return false;
676   if (!tii_->isTriviallyReMaterializable(DefMI, AA))
677     return false;
678   bool SawStore = false;
679   if (!DefMI->isSafeToMove(tii_, AA, SawStore))
680     return false;
681   if (TID.getNumDefs() != 1)
682     return false;
683   if (!DefMI->isImplicitDef()) {
684     // Make sure the copy destination register class fits the instruction
685     // definition register class. The mismatch can happen as a result of earlier
686     // extract_subreg, insert_subreg, subreg_to_reg coalescing.
687     const TargetRegisterClass *RC = TID.OpInfo[0].getRegClass(tri_);
688     if (TargetRegisterInfo::isVirtualRegister(DstReg)) {
689       if (mri_->getRegClass(DstReg) != RC)
690         return false;
691     } else if (!RC->contains(DstReg))
692       return false;
693   }
694
695   // If destination register has a sub-register index on it, make sure it mtches
696   // the instruction register class.
697   if (DstSubIdx) {
698     const TargetInstrDesc &TID = DefMI->getDesc();
699     if (TID.getNumDefs() != 1)
700       return false;
701     const TargetRegisterClass *DstRC = mri_->getRegClass(DstReg);
702     const TargetRegisterClass *DstSubRC =
703       DstRC->getSubRegisterRegClass(DstSubIdx);
704     const TargetRegisterClass *DefRC = TID.OpInfo[0].getRegClass(tri_);
705     if (DefRC == DstRC)
706       DstSubIdx = 0;
707     else if (DefRC != DstSubRC)
708       return false;
709   }
710
711   RemoveCopyFlag(DstReg, CopyMI);
712
713   // If copy kills the source register, find the last use and propagate
714   // kill.
715   bool checkForDeadDef = false;
716   MachineBasicBlock *MBB = CopyMI->getParent();
717   if (SrcLR->end == CopyIdx.getDefIndex())
718     if (!TrimLiveIntervalToLastUse(CopyIdx, MBB, SrcInt, SrcLR)) {
719       checkForDeadDef = true;
720     }
721
722   MachineBasicBlock::iterator MII =
723     llvm::next(MachineBasicBlock::iterator(CopyMI));
724   tii_->reMaterialize(*MBB, MII, DstReg, DstSubIdx, DefMI, *tri_);
725   MachineInstr *NewMI = prior(MII);
726
727   if (checkForDeadDef) {
728     // PR4090 fix: Trim interval failed because there was no use of the
729     // source interval in this MBB. If the def is in this MBB too then we
730     // should mark it dead:
731     if (DefMI->getParent() == MBB) {
732       DefMI->addRegisterDead(SrcInt.reg, tri_);
733       SrcLR->end = SrcLR->start.getNextSlot();
734     }
735   }
736
737   // CopyMI may have implicit operands, transfer them over to the newly
738   // rematerialized instruction. And update implicit def interval valnos.
739   for (unsigned i = CopyMI->getDesc().getNumOperands(),
740          e = CopyMI->getNumOperands(); i != e; ++i) {
741     MachineOperand &MO = CopyMI->getOperand(i);
742     if (MO.isReg() && MO.isImplicit())
743       NewMI->addOperand(MO);
744     if (MO.isDef())
745       RemoveCopyFlag(MO.getReg(), CopyMI);
746   }
747
748   TransferImplicitOps(CopyMI, NewMI);
749   li_->ReplaceMachineInstrInMaps(CopyMI, NewMI);
750   CopyMI->eraseFromParent();
751   ReMatCopies.insert(CopyMI);
752   ReMatDefs.insert(DefMI);
753   DEBUG(dbgs() << "Remat: " << *NewMI);
754   ++NumReMats;
755   return true;
756 }
757
758 /// UpdateRegDefsUses - Replace all defs and uses of SrcReg to DstReg and
759 /// update the subregister number if it is not zero. If DstReg is a
760 /// physical register and the existing subregister number of the def / use
761 /// being updated is not zero, make sure to set it to the correct physical
762 /// subregister.
763 void
764 SimpleRegisterCoalescing::UpdateRegDefsUses(const CoalescerPair &CP) {
765   bool DstIsPhys = CP.isPhys();
766   unsigned SrcReg = CP.getSrcReg();
767   unsigned DstReg = CP.getDstReg();
768   unsigned SubIdx = CP.getSubIdx();
769
770   for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(SrcReg);
771        MachineInstr *UseMI = I.skipInstruction();) {
772     // A PhysReg copy that won't be coalesced can perhaps be rematerialized
773     // instead.
774     if (DstIsPhys) {
775       unsigned CopySrcReg, CopyDstReg, CopySrcSubIdx, CopyDstSubIdx;
776       if (tii_->isMoveInstr(*UseMI, CopySrcReg, CopyDstReg,
777                             CopySrcSubIdx, CopyDstSubIdx) &&
778           CopySrcSubIdx == 0 && CopyDstSubIdx == 0 &&
779           CopySrcReg != CopyDstReg && CopySrcReg == SrcReg &&
780           CopyDstReg != DstReg && !JoinedCopies.count(UseMI) &&
781           ReMaterializeTrivialDef(li_->getInterval(SrcReg), CopyDstReg, 0,
782                                   UseMI))
783         continue;
784
785       if (UseMI->isCopy() &&
786           !UseMI->getOperand(1).getSubReg() &&
787           !UseMI->getOperand(0).getSubReg() &&
788           UseMI->getOperand(1).getReg() == SrcReg &&
789           UseMI->getOperand(0).getReg() != SrcReg &&
790           UseMI->getOperand(0).getReg() != DstReg &&
791           !JoinedCopies.count(UseMI) &&
792           ReMaterializeTrivialDef(li_->getInterval(SrcReg),
793                                   UseMI->getOperand(0).getReg(), 0, UseMI))
794         continue;
795     }
796
797     SmallVector<unsigned,8> Ops;
798     bool Reads, Writes;
799     tie(Reads, Writes) = UseMI->readsWritesVirtualRegister(SrcReg, &Ops);
800     bool Kills = false, Deads = false;
801
802     // Replace SrcReg with DstReg in all UseMI operands.
803     for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
804       MachineOperand &MO = UseMI->getOperand(Ops[i]);
805       Kills |= MO.isKill();
806       Deads |= MO.isDead();
807
808       if (DstIsPhys)
809         MO.substPhysReg(DstReg, *tri_);
810       else
811         MO.substVirtReg(DstReg, SubIdx, *tri_);
812     }
813
814     // This instruction is a copy that will be removed.
815     if (JoinedCopies.count(UseMI))
816       continue;
817
818     if (SubIdx) {
819       // If UseMI was a simple SrcReg def, make sure we didn't turn it into a
820       // read-modify-write of DstReg.
821       if (Deads)
822         UseMI->addRegisterDead(DstReg, tri_);
823       else if (!Reads && Writes)
824         UseMI->addRegisterDefined(DstReg, tri_);
825
826       // Kill flags apply to the whole physical register.
827       if (DstIsPhys && Kills)
828         UseMI->addRegisterKilled(DstReg, tri_);
829     }
830
831     DEBUG({
832         dbgs() << "\t\tupdated: ";
833         if (!UseMI->isDebugValue())
834           dbgs() << li_->getInstructionIndex(UseMI) << "\t";
835         dbgs() << *UseMI;
836       });
837
838
839     // After updating the operand, check if the machine instruction has
840     // become a copy. If so, update its val# information.
841     const TargetInstrDesc &TID = UseMI->getDesc();
842     if (DstIsPhys || TID.getNumDefs() != 1 || TID.getNumOperands() <= 2)
843       continue;
844
845     unsigned CopySrcReg, CopyDstReg, CopySrcSubIdx, CopyDstSubIdx;
846     if (tii_->isMoveInstr(*UseMI, CopySrcReg, CopyDstReg,
847                           CopySrcSubIdx, CopyDstSubIdx) &&
848         CopySrcReg != CopyDstReg &&
849         (TargetRegisterInfo::isVirtualRegister(CopyDstReg) ||
850          allocatableRegs_[CopyDstReg])) {
851       LiveInterval &LI = li_->getInterval(CopyDstReg);
852       SlotIndex DefIdx =
853         li_->getInstructionIndex(UseMI).getDefIndex();
854       if (const LiveRange *DLR = LI.getLiveRangeContaining(DefIdx)) {
855         if (DLR->valno->def == DefIdx)
856           DLR->valno->setCopy(UseMI);
857       }
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 void SimpleRegisterCoalescing::RemoveCopyFlag(unsigned DstReg,
915                                               const MachineInstr *CopyMI) {
916   SlotIndex DefIdx = li_->getInstructionIndex(CopyMI).getDefIndex();
917   if (li_->hasInterval(DstReg)) {
918     LiveInterval &LI = li_->getInterval(DstReg);
919     if (const LiveRange *LR = LI.getLiveRangeContaining(DefIdx))
920       if (LR->valno->getCopy() == CopyMI)
921         LR->valno->setCopy(0);
922   }
923   if (!TargetRegisterInfo::isPhysicalRegister(DstReg))
924     return;
925   for (const unsigned* AS = tri_->getAliasSet(DstReg); *AS; ++AS) {
926     if (!li_->hasInterval(*AS))
927       continue;
928     LiveInterval &LI = li_->getInterval(*AS);
929     if (const LiveRange *LR = LI.getLiveRangeContaining(DefIdx))
930       if (LR->valno->getCopy() == CopyMI)
931         LR->valno->setCopy(0);
932   }
933 }
934
935 /// PropagateDeadness - Propagate the dead marker to the instruction which
936 /// defines the val#.
937 static void PropagateDeadness(LiveInterval &li, MachineInstr *CopyMI,
938                               SlotIndex &LRStart, LiveIntervals *li_,
939                               const TargetRegisterInfo* tri_) {
940   MachineInstr *DefMI =
941     li_->getInstructionFromIndex(LRStart.getDefIndex());
942   if (DefMI && DefMI != CopyMI) {
943     int DeadIdx = DefMI->findRegisterDefOperandIdx(li.reg);
944     if (DeadIdx != -1)
945       DefMI->getOperand(DeadIdx).setIsDead();
946     else
947       DefMI->addOperand(MachineOperand::CreateReg(li.reg,
948                    /*def*/true, /*implicit*/true, /*kill*/false, /*dead*/true));
949     LRStart = LRStart.getNextSlot();
950   }
951 }
952
953 /// ShortenDeadCopySrcLiveRange - Shorten a live range as it's artificially
954 /// extended by a dead copy. Mark the last use (if any) of the val# as kill as
955 /// ends the live range there. If there isn't another use, then this live range
956 /// is dead. Return true if live interval is removed.
957 bool
958 SimpleRegisterCoalescing::ShortenDeadCopySrcLiveRange(LiveInterval &li,
959                                                       MachineInstr *CopyMI) {
960   SlotIndex CopyIdx = li_->getInstructionIndex(CopyMI);
961   if (CopyIdx == SlotIndex()) {
962     // FIXME: special case: function live in. It can be a general case if the
963     // first instruction index starts at > 0 value.
964     assert(TargetRegisterInfo::isPhysicalRegister(li.reg));
965     // Live-in to the function but dead. Remove it from entry live-in set.
966     if (mf_->begin()->isLiveIn(li.reg))
967       mf_->begin()->removeLiveIn(li.reg);
968     if (const LiveRange *LR = li.getLiveRangeContaining(CopyIdx))
969       removeRange(li, LR->start, LR->end, li_, tri_);
970     return removeIntervalIfEmpty(li, li_, tri_);
971   }
972
973   LiveInterval::iterator LR =
974     li.FindLiveRangeContaining(CopyIdx.getPrevIndex().getStoreIndex());
975   if (LR == li.end())
976     // Livein but defined by a phi.
977     return false;
978
979   SlotIndex RemoveStart = LR->start;
980   SlotIndex RemoveEnd = CopyIdx.getStoreIndex();
981   if (LR->end > RemoveEnd)
982     // More uses past this copy? Nothing to do.
983     return false;
984
985   // If there is a last use in the same bb, we can't remove the live range.
986   // Shorten the live interval and return.
987   MachineBasicBlock *CopyMBB = CopyMI->getParent();
988   if (TrimLiveIntervalToLastUse(CopyIdx, CopyMBB, li, LR))
989     return false;
990
991   // There are other kills of the val#. Nothing to do.
992   if (!li.isOnlyLROfValNo(LR))
993     return false;
994
995   MachineBasicBlock *StartMBB = li_->getMBBFromIndex(RemoveStart);
996   if (!isSameOrFallThroughBB(StartMBB, CopyMBB, tii_))
997     // If the live range starts in another mbb and the copy mbb is not a fall
998     // through mbb, then we can only cut the range from the beginning of the
999     // copy mbb.
1000     RemoveStart = li_->getMBBStartIdx(CopyMBB).getNextIndex().getBaseIndex();
1001
1002   if (LR->valno->def == RemoveStart) {
1003     // If the def MI defines the val# and this copy is the only kill of the
1004     // val#, then propagate the dead marker.
1005     PropagateDeadness(li, CopyMI, RemoveStart, li_, tri_);
1006     ++numDeadValNo;
1007   }
1008
1009   removeRange(li, RemoveStart, RemoveEnd, li_, tri_);
1010   return removeIntervalIfEmpty(li, li_, tri_);
1011 }
1012
1013
1014 /// isWinToJoinCrossClass - Return true if it's profitable to coalesce
1015 /// two virtual registers from different register classes.
1016 bool
1017 SimpleRegisterCoalescing::isWinToJoinCrossClass(unsigned SrcReg,
1018                                                 unsigned DstReg,
1019                                              const TargetRegisterClass *SrcRC,
1020                                              const TargetRegisterClass *DstRC,
1021                                              const TargetRegisterClass *NewRC) {
1022   unsigned NewRCCount = allocatableRCRegs_[NewRC].count();
1023   // This heuristics is good enough in practice, but it's obviously not *right*.
1024   // 4 is a magic number that works well enough for x86, ARM, etc. It filter
1025   // out all but the most restrictive register classes.
1026   if (NewRCCount > 4 ||
1027       // Early exit if the function is fairly small, coalesce aggressively if
1028       // that's the case. For really special register classes with 3 or
1029       // fewer registers, be a bit more careful.
1030       (li_->getFuncInstructionCount() / NewRCCount) < 8)
1031     return true;
1032   LiveInterval &SrcInt = li_->getInterval(SrcReg);
1033   LiveInterval &DstInt = li_->getInterval(DstReg);
1034   unsigned SrcSize = li_->getApproximateInstructionCount(SrcInt);
1035   unsigned DstSize = li_->getApproximateInstructionCount(DstInt);
1036   if (SrcSize <= NewRCCount && DstSize <= NewRCCount)
1037     return true;
1038   // Estimate *register use density*. If it doubles or more, abort.
1039   unsigned SrcUses = std::distance(mri_->use_nodbg_begin(SrcReg),
1040                                    mri_->use_nodbg_end());
1041   unsigned DstUses = std::distance(mri_->use_nodbg_begin(DstReg),
1042                                    mri_->use_nodbg_end());
1043   unsigned NewUses = SrcUses + DstUses;
1044   unsigned NewSize = SrcSize + DstSize;
1045   if (SrcRC != NewRC && SrcSize > NewRCCount) {
1046     unsigned SrcRCCount = allocatableRCRegs_[SrcRC].count();
1047     if (NewUses*SrcSize*SrcRCCount > 2*SrcUses*NewSize*NewRCCount)
1048       return false;
1049   }
1050   if (DstRC != NewRC && DstSize > NewRCCount) {
1051     unsigned DstRCCount = allocatableRCRegs_[DstRC].count();
1052     if (NewUses*DstSize*DstRCCount > 2*DstUses*NewSize*NewRCCount)
1053       return false;
1054   }
1055   return true;
1056 }
1057
1058
1059 /// JoinCopy - Attempt to join intervals corresponding to SrcReg/DstReg,
1060 /// which are the src/dst of the copy instruction CopyMI.  This returns true
1061 /// if the copy was successfully coalesced away. If it is not currently
1062 /// possible to coalesce this interval, but it may be possible if other
1063 /// things get coalesced, then it returns true by reference in 'Again'.
1064 bool SimpleRegisterCoalescing::JoinCopy(CopyRec &TheCopy, bool &Again) {
1065   MachineInstr *CopyMI = TheCopy.MI;
1066
1067   Again = false;
1068   if (JoinedCopies.count(CopyMI) || ReMatCopies.count(CopyMI))
1069     return false; // Already done.
1070
1071   DEBUG(dbgs() << li_->getInstructionIndex(CopyMI) << '\t' << *CopyMI);
1072
1073   CoalescerPair CP(*tii_, *tri_);
1074   if (!CP.setRegisters(CopyMI)) {
1075     DEBUG(dbgs() << "\tNot coalescable.\n");
1076     return false;
1077   }
1078
1079   // If they are already joined we continue.
1080   if (CP.getSrcReg() == CP.getDstReg()) {
1081     DEBUG(dbgs() << "\tCopy already coalesced.\n");
1082     return false;  // Not coalescable.
1083   }
1084
1085   DEBUG(dbgs() << "\tConsidering merging %reg" << CP.getSrcReg());
1086
1087   // Enforce policies.
1088   if (CP.isPhys()) {
1089     DEBUG(dbgs() <<" with physreg %" << tri_->getName(CP.getDstReg()) << "\n");
1090     // Only coalesce to allocatable physreg.
1091     if (!allocatableRegs_[CP.getDstReg()]) {
1092       DEBUG(dbgs() << "\tRegister is an unallocatable physreg.\n");
1093       return false;  // Not coalescable.
1094     }
1095   } else {
1096     DEBUG({
1097       dbgs() << " with reg%" << CP.getDstReg();
1098       if (CP.getSubIdx())
1099         dbgs() << ":" << tri_->getSubRegIndexName(CP.getSubIdx());
1100       dbgs() << " to " << CP.getNewRC()->getName() << "\n";
1101     });
1102
1103     // Avoid constraining virtual register regclass too much.
1104     if (CP.isCrossClass()) {
1105       if (DisableCrossClassJoin) {
1106         DEBUG(dbgs() << "\tCross-class joins disabled.\n");
1107         return false;
1108       }
1109       if (!isWinToJoinCrossClass(CP.getSrcReg(), CP.getDstReg(),
1110                                  mri_->getRegClass(CP.getSrcReg()),
1111                                  mri_->getRegClass(CP.getDstReg()),
1112                                  CP.getNewRC())) {
1113         DEBUG(dbgs() << "\tAvoid coalescing to constrained register class: "
1114                      << CP.getNewRC()->getName() << ".\n");
1115         Again = true;  // May be possible to coalesce later.
1116         return false;
1117       }
1118     }
1119
1120     // When possible, let DstReg be the larger interval.
1121     if (!CP.getSubIdx() && li_->getInterval(CP.getSrcReg()).ranges.size() >
1122                            li_->getInterval(CP.getDstReg()).ranges.size())
1123       CP.flip();
1124   }
1125
1126   // We need to be careful about coalescing a source physical register with a
1127   // virtual register. Once the coalescing is done, it cannot be broken and
1128   // these are not spillable! If the destination interval uses are far away,
1129   // think twice about coalescing them!
1130   // FIXME: Why are we skipping this test for partial copies?
1131   //        CodeGen/X86/phys_subreg_coalesce-3.ll needs it.
1132   if (!CP.isPartial() && CP.isPhys()) {
1133     LiveInterval &JoinVInt = li_->getInterval(CP.getSrcReg());
1134
1135     // Don't join with physregs that have a ridiculous number of live
1136     // ranges. The data structure performance is really bad when that
1137     // happens.
1138     if (li_->hasInterval(CP.getDstReg()) &&
1139         li_->getInterval(CP.getDstReg()).ranges.size() > 1000) {
1140       mri_->setRegAllocationHint(CP.getSrcReg(), 0, CP.getDstReg());
1141       ++numAborts;
1142       DEBUG(dbgs()
1143            << "\tPhysical register live interval too complicated, abort!\n");
1144       return false;
1145     }
1146
1147     const TargetRegisterClass *RC = mri_->getRegClass(CP.getSrcReg());
1148     unsigned Threshold = allocatableRCRegs_[RC].count() * 2;
1149     unsigned Length = li_->getApproximateInstructionCount(JoinVInt);
1150     if (Length > Threshold &&
1151         std::distance(mri_->use_nodbg_begin(CP.getSrcReg()),
1152                       mri_->use_nodbg_end()) * Threshold < Length) {
1153       // Before giving up coalescing, if definition of source is defined by
1154       // trivial computation, try rematerializing it.
1155       if (!CP.isFlipped() &&
1156           ReMaterializeTrivialDef(JoinVInt, CP.getDstReg(), 0, CopyMI))
1157         return true;
1158
1159       mri_->setRegAllocationHint(CP.getSrcReg(), 0, CP.getDstReg());
1160       ++numAborts;
1161       DEBUG(dbgs() << "\tMay tie down a physical register, abort!\n");
1162       Again = true;  // May be possible to coalesce later.
1163       return false;
1164     }
1165   }
1166
1167   // Okay, attempt to join these two intervals.  On failure, this returns false.
1168   // Otherwise, if one of the intervals being joined is a physreg, this method
1169   // always canonicalizes DstInt to be it.  The output "SrcInt" will not have
1170   // been modified, so we can use this information below to update aliases.
1171   if (!JoinIntervals(CP)) {
1172     // Coalescing failed.
1173
1174     // If definition of source is defined by trivial computation, try
1175     // rematerializing it.
1176     if (!CP.isFlipped() &&
1177         ReMaterializeTrivialDef(li_->getInterval(CP.getSrcReg()),
1178                                 CP.getDstReg(), 0, CopyMI))
1179       return true;
1180
1181     // If we can eliminate the copy without merging the live ranges, do so now.
1182     if (!CP.isPartial()) {
1183       if (AdjustCopiesBackFrom(CP, CopyMI) ||
1184           RemoveCopyByCommutingDef(CP, CopyMI)) {
1185         JoinedCopies.insert(CopyMI);
1186         DEBUG(dbgs() << "\tTrivial!\n");
1187         return true;
1188       }
1189     }
1190
1191     // Otherwise, we are unable to join the intervals.
1192     DEBUG(dbgs() << "\tInterference!\n");
1193     Again = true;  // May be possible to coalesce later.
1194     return false;
1195   }
1196
1197   // Coalescing to a virtual register that is of a sub-register class of the
1198   // other. Make sure the resulting register is set to the right register class.
1199   if (CP.isCrossClass()) {
1200     ++numCrossRCs;
1201     mri_->setRegClass(CP.getDstReg(), CP.getNewRC());
1202   }
1203
1204   // Remember to delete the copy instruction.
1205   JoinedCopies.insert(CopyMI);
1206
1207   UpdateRegDefsUses(CP);
1208
1209   // If we have extended the live range of a physical register, make sure we
1210   // update live-in lists as well.
1211   if (CP.isPhys()) {
1212     SmallVector<MachineBasicBlock*, 16> BlockSeq;
1213     // JoinIntervals invalidates the VNInfos in SrcInt, but we only need the
1214     // ranges for this, and they are preserved.
1215     LiveInterval &SrcInt = li_->getInterval(CP.getSrcReg());
1216     for (LiveInterval::const_iterator I = SrcInt.begin(), E = SrcInt.end();
1217          I != E; ++I ) {
1218       li_->findLiveInMBBs(I->start, I->end, BlockSeq);
1219       for (unsigned idx = 0, size = BlockSeq.size(); idx != size; ++idx) {
1220         MachineBasicBlock &block = *BlockSeq[idx];
1221         if (!block.isLiveIn(CP.getDstReg()))
1222           block.addLiveIn(CP.getDstReg());
1223       }
1224       BlockSeq.clear();
1225     }
1226   }
1227
1228   // SrcReg is guarateed to be the register whose live interval that is
1229   // being merged.
1230   li_->removeInterval(CP.getSrcReg());
1231
1232   // Update regalloc hint.
1233   tri_->UpdateRegAllocHint(CP.getSrcReg(), CP.getDstReg(), *mf_);
1234
1235   DEBUG({
1236     LiveInterval &DstInt = li_->getInterval(CP.getDstReg());
1237     dbgs() << "\tJoined. Result = ";
1238     DstInt.print(dbgs(), tri_);
1239     dbgs() << "\n";
1240   });
1241
1242   ++numJoins;
1243   return true;
1244 }
1245
1246 /// ComputeUltimateVN - Assuming we are going to join two live intervals,
1247 /// compute what the resultant value numbers for each value in the input two
1248 /// ranges will be.  This is complicated by copies between the two which can
1249 /// and will commonly cause multiple value numbers to be merged into one.
1250 ///
1251 /// VN is the value number that we're trying to resolve.  InstDefiningValue
1252 /// keeps track of the new InstDefiningValue assignment for the result
1253 /// LiveInterval.  ThisFromOther/OtherFromThis are sets that keep track of
1254 /// whether a value in this or other is a copy from the opposite set.
1255 /// ThisValNoAssignments/OtherValNoAssignments keep track of value #'s that have
1256 /// already been assigned.
1257 ///
1258 /// ThisFromOther[x] - If x is defined as a copy from the other interval, this
1259 /// contains the value number the copy is from.
1260 ///
1261 static unsigned ComputeUltimateVN(VNInfo *VNI,
1262                                   SmallVector<VNInfo*, 16> &NewVNInfo,
1263                                   DenseMap<VNInfo*, VNInfo*> &ThisFromOther,
1264                                   DenseMap<VNInfo*, VNInfo*> &OtherFromThis,
1265                                   SmallVector<int, 16> &ThisValNoAssignments,
1266                                   SmallVector<int, 16> &OtherValNoAssignments) {
1267   unsigned VN = VNI->id;
1268
1269   // If the VN has already been computed, just return it.
1270   if (ThisValNoAssignments[VN] >= 0)
1271     return ThisValNoAssignments[VN];
1272   assert(ThisValNoAssignments[VN] != -2 && "Cyclic value numbers");
1273
1274   // If this val is not a copy from the other val, then it must be a new value
1275   // number in the destination.
1276   DenseMap<VNInfo*, VNInfo*>::iterator I = ThisFromOther.find(VNI);
1277   if (I == ThisFromOther.end()) {
1278     NewVNInfo.push_back(VNI);
1279     return ThisValNoAssignments[VN] = NewVNInfo.size()-1;
1280   }
1281   VNInfo *OtherValNo = I->second;
1282
1283   // Otherwise, this *is* a copy from the RHS.  If the other side has already
1284   // been computed, return it.
1285   if (OtherValNoAssignments[OtherValNo->id] >= 0)
1286     return ThisValNoAssignments[VN] = OtherValNoAssignments[OtherValNo->id];
1287
1288   // Mark this value number as currently being computed, then ask what the
1289   // ultimate value # of the other value is.
1290   ThisValNoAssignments[VN] = -2;
1291   unsigned UltimateVN =
1292     ComputeUltimateVN(OtherValNo, NewVNInfo, OtherFromThis, ThisFromOther,
1293                       OtherValNoAssignments, ThisValNoAssignments);
1294   return ThisValNoAssignments[VN] = UltimateVN;
1295 }
1296
1297 /// JoinIntervals - Attempt to join these two intervals.  On failure, this
1298 /// returns false.
1299 bool SimpleRegisterCoalescing::JoinIntervals(CoalescerPair &CP) {
1300   LiveInterval &RHS = li_->getInterval(CP.getSrcReg());
1301   DEBUG({ dbgs() << "\t\tRHS = "; RHS.print(dbgs(), tri_); dbgs() << "\n"; });
1302
1303   // If a live interval is a physical register, check for interference with any
1304   // aliases. The interference check implemented here is a bit more conservative
1305   // than the full interfeence check below. We allow overlapping live ranges
1306   // only when one is a copy of the other.
1307   if (CP.isPhys()) {
1308     for (const unsigned *AS = tri_->getAliasSet(CP.getDstReg()); *AS; ++AS){
1309       if (!li_->hasInterval(*AS))
1310         continue;
1311       const LiveInterval &LHS = li_->getInterval(*AS);
1312       LiveInterval::const_iterator LI = LHS.begin();
1313       for (LiveInterval::const_iterator RI = RHS.begin(), RE = RHS.end();
1314            RI != RE; ++RI) {
1315         LI = std::lower_bound(LI, LHS.end(), RI->start);
1316         // Does LHS have an overlapping live range starting before RI?
1317         if ((LI != LHS.begin() && LI[-1].end > RI->start) &&
1318             (RI->start != RI->valno->def ||
1319              !CP.isCoalescable(li_->getInstructionFromIndex(RI->start)))) {
1320           DEBUG({
1321             dbgs() << "\t\tInterference from alias: ";
1322             LHS.print(dbgs(), tri_);
1323             dbgs() << "\n\t\tOverlap at " << RI->start << " and no copy.\n";
1324           });
1325           return false;
1326         }
1327
1328         // Check that LHS ranges beginning in this range are copies.
1329         for (; LI != LHS.end() && LI->start < RI->end; ++LI) {
1330           if (LI->start != LI->valno->def ||
1331               !CP.isCoalescable(li_->getInstructionFromIndex(LI->start))) {
1332             DEBUG({
1333               dbgs() << "\t\tInterference from alias: ";
1334               LHS.print(dbgs(), tri_);
1335               dbgs() << "\n\t\tDef at " << LI->start << " is not a copy.\n";
1336             });
1337             return false;
1338           }
1339         }
1340       }
1341     }
1342   }
1343
1344   // Compute the final value assignment, assuming that the live ranges can be
1345   // coalesced.
1346   SmallVector<int, 16> LHSValNoAssignments;
1347   SmallVector<int, 16> RHSValNoAssignments;
1348   DenseMap<VNInfo*, VNInfo*> LHSValsDefinedFromRHS;
1349   DenseMap<VNInfo*, VNInfo*> RHSValsDefinedFromLHS;
1350   SmallVector<VNInfo*, 16> NewVNInfo;
1351
1352   LiveInterval &LHS = li_->getOrCreateInterval(CP.getDstReg());
1353   DEBUG({ dbgs() << "\t\tLHS = "; LHS.print(dbgs(), tri_); dbgs() << "\n"; });
1354
1355   // Loop over the value numbers of the LHS, seeing if any are defined from
1356   // the RHS.
1357   for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1358        i != e; ++i) {
1359     VNInfo *VNI = *i;
1360     if (VNI->isUnused() || VNI->getCopy() == 0)  // Src not defined by a copy?
1361       continue;
1362
1363     // Never join with a register that has EarlyClobber redefs.
1364     if (VNI->hasRedefByEC())
1365       return false;
1366
1367     // DstReg is known to be a register in the LHS interval.  If the src is
1368     // from the RHS interval, we can use its value #.
1369     if (!CP.isCoalescable(VNI->getCopy()))
1370       continue;
1371
1372     // Figure out the value # from the RHS.
1373     LiveRange *lr = RHS.getLiveRangeContaining(VNI->def.getPrevSlot());
1374     // The copy could be to an aliased physreg.
1375     if (!lr) continue;
1376     LHSValsDefinedFromRHS[VNI] = lr->valno;
1377   }
1378
1379   // Loop over the value numbers of the RHS, seeing if any are defined from
1380   // the LHS.
1381   for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
1382        i != e; ++i) {
1383     VNInfo *VNI = *i;
1384     if (VNI->isUnused() || VNI->getCopy() == 0)  // Src not defined by a copy?
1385       continue;
1386
1387     // Never join with a register that has EarlyClobber redefs.
1388     if (VNI->hasRedefByEC())
1389       return false;
1390
1391     // DstReg is known to be a register in the RHS interval.  If the src is
1392     // from the LHS interval, we can use its value #.
1393     if (!CP.isCoalescable(VNI->getCopy()))
1394       continue;
1395
1396     // Figure out the value # from the LHS.
1397     LiveRange *lr = LHS.getLiveRangeContaining(VNI->def.getPrevSlot());
1398     // The copy could be to an aliased physreg.
1399     if (!lr) continue;
1400     RHSValsDefinedFromLHS[VNI] = lr->valno;
1401   }
1402
1403   LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
1404   RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
1405   NewVNInfo.reserve(LHS.getNumValNums() + RHS.getNumValNums());
1406
1407   for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1408        i != e; ++i) {
1409     VNInfo *VNI = *i;
1410     unsigned VN = VNI->id;
1411     if (LHSValNoAssignments[VN] >= 0 || VNI->isUnused())
1412       continue;
1413     ComputeUltimateVN(VNI, NewVNInfo,
1414                       LHSValsDefinedFromRHS, RHSValsDefinedFromLHS,
1415                       LHSValNoAssignments, RHSValNoAssignments);
1416   }
1417   for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
1418        i != e; ++i) {
1419     VNInfo *VNI = *i;
1420     unsigned VN = VNI->id;
1421     if (RHSValNoAssignments[VN] >= 0 || VNI->isUnused())
1422       continue;
1423     // If this value number isn't a copy from the LHS, it's a new number.
1424     if (RHSValsDefinedFromLHS.find(VNI) == RHSValsDefinedFromLHS.end()) {
1425       NewVNInfo.push_back(VNI);
1426       RHSValNoAssignments[VN] = NewVNInfo.size()-1;
1427       continue;
1428     }
1429
1430     ComputeUltimateVN(VNI, NewVNInfo,
1431                       RHSValsDefinedFromLHS, LHSValsDefinedFromRHS,
1432                       RHSValNoAssignments, LHSValNoAssignments);
1433   }
1434
1435   // Armed with the mappings of LHS/RHS values to ultimate values, walk the
1436   // interval lists to see if these intervals are coalescable.
1437   LiveInterval::const_iterator I = LHS.begin();
1438   LiveInterval::const_iterator IE = LHS.end();
1439   LiveInterval::const_iterator J = RHS.begin();
1440   LiveInterval::const_iterator JE = RHS.end();
1441
1442   // Skip ahead until the first place of potential sharing.
1443   if (I != IE && J != JE) {
1444     if (I->start < J->start) {
1445       I = std::upper_bound(I, IE, J->start);
1446       if (I != LHS.begin()) --I;
1447     } else if (J->start < I->start) {
1448       J = std::upper_bound(J, JE, I->start);
1449       if (J != RHS.begin()) --J;
1450     }
1451   }
1452
1453   while (I != IE && J != JE) {
1454     // Determine if these two live ranges overlap.
1455     bool Overlaps;
1456     if (I->start < J->start) {
1457       Overlaps = I->end > J->start;
1458     } else {
1459       Overlaps = J->end > I->start;
1460     }
1461
1462     // If so, check value # info to determine if they are really different.
1463     if (Overlaps) {
1464       // If the live range overlap will map to the same value number in the
1465       // result liverange, we can still coalesce them.  If not, we can't.
1466       if (LHSValNoAssignments[I->valno->id] !=
1467           RHSValNoAssignments[J->valno->id])
1468         return false;
1469       // If it's re-defined by an early clobber somewhere in the live range,
1470       // then conservatively abort coalescing.
1471       if (NewVNInfo[LHSValNoAssignments[I->valno->id]]->hasRedefByEC())
1472         return false;
1473     }
1474
1475     if (I->end < J->end)
1476       ++I;
1477     else
1478       ++J;
1479   }
1480
1481   // Update kill info. Some live ranges are extended due to copy coalescing.
1482   for (DenseMap<VNInfo*, VNInfo*>::iterator I = LHSValsDefinedFromRHS.begin(),
1483          E = LHSValsDefinedFromRHS.end(); I != E; ++I) {
1484     VNInfo *VNI = I->first;
1485     unsigned LHSValID = LHSValNoAssignments[VNI->id];
1486     if (VNI->hasPHIKill())
1487       NewVNInfo[LHSValID]->setHasPHIKill(true);
1488   }
1489
1490   // Update kill info. Some live ranges are extended due to copy coalescing.
1491   for (DenseMap<VNInfo*, VNInfo*>::iterator I = RHSValsDefinedFromLHS.begin(),
1492          E = RHSValsDefinedFromLHS.end(); I != E; ++I) {
1493     VNInfo *VNI = I->first;
1494     unsigned RHSValID = RHSValNoAssignments[VNI->id];
1495     if (VNI->hasPHIKill())
1496       NewVNInfo[RHSValID]->setHasPHIKill(true);
1497   }
1498
1499   if (LHSValNoAssignments.empty())
1500     LHSValNoAssignments.push_back(-1);
1501   if (RHSValNoAssignments.empty())
1502     RHSValNoAssignments.push_back(-1);
1503
1504   // If we get here, we know that we can coalesce the live ranges.  Ask the
1505   // intervals to coalesce themselves now.
1506   LHS.join(RHS, &LHSValNoAssignments[0], &RHSValNoAssignments[0], NewVNInfo,
1507            mri_);
1508   return true;
1509 }
1510
1511 namespace {
1512   // DepthMBBCompare - Comparison predicate that sort first based on the loop
1513   // depth of the basic block (the unsigned), and then on the MBB number.
1514   struct DepthMBBCompare {
1515     typedef std::pair<unsigned, MachineBasicBlock*> DepthMBBPair;
1516     bool operator()(const DepthMBBPair &LHS, const DepthMBBPair &RHS) const {
1517       // Deeper loops first
1518       if (LHS.first != RHS.first)
1519         return LHS.first > RHS.first;
1520
1521       // Prefer blocks that are more connected in the CFG. This takes care of
1522       // the most difficult copies first while intervals are short.
1523       unsigned cl = LHS.second->pred_size() + LHS.second->succ_size();
1524       unsigned cr = RHS.second->pred_size() + RHS.second->succ_size();
1525       if (cl != cr)
1526         return cl > cr;
1527
1528       // As a last resort, sort by block number.
1529       return LHS.second->getNumber() < RHS.second->getNumber();
1530     }
1531   };
1532 }
1533
1534 void SimpleRegisterCoalescing::CopyCoalesceInMBB(MachineBasicBlock *MBB,
1535                                                std::vector<CopyRec> &TryAgain) {
1536   DEBUG(dbgs() << MBB->getName() << ":\n");
1537
1538   std::vector<CopyRec> VirtCopies;
1539   std::vector<CopyRec> PhysCopies;
1540   std::vector<CopyRec> ImpDefCopies;
1541   for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end();
1542        MII != E;) {
1543     MachineInstr *Inst = MII++;
1544
1545     // If this isn't a copy nor a extract_subreg, we can't join intervals.
1546     unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
1547     bool isInsUndef = false;
1548     if (Inst->isCopy()) {
1549       DstReg = Inst->getOperand(0).getReg();
1550       SrcReg = Inst->getOperand(1).getReg();
1551     } else if (Inst->isSubregToReg()) {
1552       DstReg = Inst->getOperand(0).getReg();
1553       SrcReg = Inst->getOperand(2).getReg();
1554     } else if (!tii_->isMoveInstr(*Inst, SrcReg, DstReg, SrcSubIdx, DstSubIdx))
1555       continue;
1556
1557     bool SrcIsPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
1558     bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
1559     if (isInsUndef ||
1560         (li_->hasInterval(SrcReg) && li_->getInterval(SrcReg).empty()))
1561       ImpDefCopies.push_back(CopyRec(Inst, 0));
1562     else if (SrcIsPhys || DstIsPhys)
1563       PhysCopies.push_back(CopyRec(Inst, 0));
1564     else
1565       VirtCopies.push_back(CopyRec(Inst, 0));
1566   }
1567
1568   // Try coalescing implicit copies and insert_subreg <undef> first,
1569   // followed by copies to / from physical registers, then finally copies
1570   // from virtual registers to virtual registers.
1571   for (unsigned i = 0, e = ImpDefCopies.size(); i != e; ++i) {
1572     CopyRec &TheCopy = ImpDefCopies[i];
1573     bool Again = false;
1574     if (!JoinCopy(TheCopy, Again))
1575       if (Again)
1576         TryAgain.push_back(TheCopy);
1577   }
1578   for (unsigned i = 0, e = PhysCopies.size(); i != e; ++i) {
1579     CopyRec &TheCopy = PhysCopies[i];
1580     bool Again = false;
1581     if (!JoinCopy(TheCopy, Again))
1582       if (Again)
1583         TryAgain.push_back(TheCopy);
1584   }
1585   for (unsigned i = 0, e = VirtCopies.size(); i != e; ++i) {
1586     CopyRec &TheCopy = VirtCopies[i];
1587     bool Again = false;
1588     if (!JoinCopy(TheCopy, Again))
1589       if (Again)
1590         TryAgain.push_back(TheCopy);
1591   }
1592 }
1593
1594 void SimpleRegisterCoalescing::joinIntervals() {
1595   DEBUG(dbgs() << "********** JOINING INTERVALS ***********\n");
1596
1597   std::vector<CopyRec> TryAgainList;
1598   if (loopInfo->empty()) {
1599     // If there are no loops in the function, join intervals in function order.
1600     for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();
1601          I != E; ++I)
1602       CopyCoalesceInMBB(I, TryAgainList);
1603   } else {
1604     // Otherwise, join intervals in inner loops before other intervals.
1605     // Unfortunately we can't just iterate over loop hierarchy here because
1606     // there may be more MBB's than BB's.  Collect MBB's for sorting.
1607
1608     // Join intervals in the function prolog first. We want to join physical
1609     // registers with virtual registers before the intervals got too long.
1610     std::vector<std::pair<unsigned, MachineBasicBlock*> > MBBs;
1611     for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();I != E;++I){
1612       MachineBasicBlock *MBB = I;
1613       MBBs.push_back(std::make_pair(loopInfo->getLoopDepth(MBB), I));
1614     }
1615
1616     // Sort by loop depth.
1617     std::sort(MBBs.begin(), MBBs.end(), DepthMBBCompare());
1618
1619     // Finally, join intervals in loop nest order.
1620     for (unsigned i = 0, e = MBBs.size(); i != e; ++i)
1621       CopyCoalesceInMBB(MBBs[i].second, TryAgainList);
1622   }
1623
1624   // Joining intervals can allow other intervals to be joined.  Iteratively join
1625   // until we make no progress.
1626   bool ProgressMade = true;
1627   while (ProgressMade) {
1628     ProgressMade = false;
1629
1630     for (unsigned i = 0, e = TryAgainList.size(); i != e; ++i) {
1631       CopyRec &TheCopy = TryAgainList[i];
1632       if (!TheCopy.MI)
1633         continue;
1634
1635       bool Again = false;
1636       bool Success = JoinCopy(TheCopy, Again);
1637       if (Success || !Again) {
1638         TheCopy.MI = 0;   // Mark this one as done.
1639         ProgressMade = true;
1640       }
1641     }
1642   }
1643 }
1644
1645 /// Return true if the two specified registers belong to different register
1646 /// classes.  The registers may be either phys or virt regs.
1647 bool
1648 SimpleRegisterCoalescing::differingRegisterClasses(unsigned RegA,
1649                                                    unsigned RegB) const {
1650   // Get the register classes for the first reg.
1651   if (TargetRegisterInfo::isPhysicalRegister(RegA)) {
1652     assert(TargetRegisterInfo::isVirtualRegister(RegB) &&
1653            "Shouldn't consider two physregs!");
1654     return !mri_->getRegClass(RegB)->contains(RegA);
1655   }
1656
1657   // Compare against the regclass for the second reg.
1658   const TargetRegisterClass *RegClassA = mri_->getRegClass(RegA);
1659   if (TargetRegisterInfo::isVirtualRegister(RegB)) {
1660     const TargetRegisterClass *RegClassB = mri_->getRegClass(RegB);
1661     return RegClassA != RegClassB;
1662   }
1663   return !RegClassA->contains(RegB);
1664 }
1665
1666 /// lastRegisterUse - Returns the last (non-debug) use of the specific register
1667 /// between cycles Start and End or NULL if there are no uses.
1668 MachineOperand *
1669 SimpleRegisterCoalescing::lastRegisterUse(SlotIndex Start,
1670                                           SlotIndex End,
1671                                           unsigned Reg,
1672                                           SlotIndex &UseIdx) const{
1673   UseIdx = SlotIndex();
1674   if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1675     MachineOperand *LastUse = NULL;
1676     for (MachineRegisterInfo::use_nodbg_iterator I = mri_->use_nodbg_begin(Reg),
1677            E = mri_->use_nodbg_end(); I != E; ++I) {
1678       MachineOperand &Use = I.getOperand();
1679       MachineInstr *UseMI = Use.getParent();
1680       if (UseMI->isIdentityCopy())
1681         continue;
1682       unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
1683       if (tii_->isMoveInstr(*UseMI, SrcReg, DstReg, SrcSubIdx, DstSubIdx) &&
1684           SrcReg == DstReg && SrcSubIdx == DstSubIdx)
1685         // Ignore identity copies.
1686         continue;
1687       SlotIndex Idx = li_->getInstructionIndex(UseMI);
1688       // FIXME: Should this be Idx != UseIdx? SlotIndex() will return something
1689       // that compares higher than any other interval.
1690       if (Idx >= Start && Idx < End && Idx >= UseIdx) {
1691         LastUse = &Use;
1692         UseIdx = Idx.getUseIndex();
1693       }
1694     }
1695     return LastUse;
1696   }
1697
1698   SlotIndex s = Start;
1699   SlotIndex e = End.getPrevSlot().getBaseIndex();
1700   while (e >= s) {
1701     // Skip deleted instructions
1702     MachineInstr *MI = li_->getInstructionFromIndex(e);
1703     while (e != SlotIndex() && e.getPrevIndex() >= s && !MI) {
1704       e = e.getPrevIndex();
1705       MI = li_->getInstructionFromIndex(e);
1706     }
1707     if (e < s || MI == NULL)
1708       return NULL;
1709
1710     // Ignore identity copies.
1711     unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
1712     if (!MI->isIdentityCopy() &&
1713         !(tii_->isMoveInstr(*MI, SrcReg, DstReg, SrcSubIdx, DstSubIdx) &&
1714           SrcReg == DstReg && SrcSubIdx == DstSubIdx))
1715       for (unsigned i = 0, NumOps = MI->getNumOperands(); i != NumOps; ++i) {
1716         MachineOperand &Use = MI->getOperand(i);
1717         if (Use.isReg() && Use.isUse() && Use.getReg() &&
1718             tri_->regsOverlap(Use.getReg(), Reg)) {
1719           UseIdx = e.getUseIndex();
1720           return &Use;
1721         }
1722       }
1723
1724     e = e.getPrevIndex();
1725   }
1726
1727   return NULL;
1728 }
1729
1730 void SimpleRegisterCoalescing::releaseMemory() {
1731   JoinedCopies.clear();
1732   ReMatCopies.clear();
1733   ReMatDefs.clear();
1734 }
1735
1736 bool SimpleRegisterCoalescing::runOnMachineFunction(MachineFunction &fn) {
1737   mf_ = &fn;
1738   mri_ = &fn.getRegInfo();
1739   tm_ = &fn.getTarget();
1740   tri_ = tm_->getRegisterInfo();
1741   tii_ = tm_->getInstrInfo();
1742   li_ = &getAnalysis<LiveIntervals>();
1743   AA = &getAnalysis<AliasAnalysis>();
1744   loopInfo = &getAnalysis<MachineLoopInfo>();
1745
1746   DEBUG(dbgs() << "********** SIMPLE REGISTER COALESCING **********\n"
1747                << "********** Function: "
1748                << ((Value*)mf_->getFunction())->getName() << '\n');
1749
1750   allocatableRegs_ = tri_->getAllocatableSet(fn);
1751   for (TargetRegisterInfo::regclass_iterator I = tri_->regclass_begin(),
1752          E = tri_->regclass_end(); I != E; ++I)
1753     allocatableRCRegs_.insert(std::make_pair(*I,
1754                                              tri_->getAllocatableSet(fn, *I)));
1755
1756   // Join (coalesce) intervals if requested.
1757   if (EnableJoining) {
1758     joinIntervals();
1759     DEBUG({
1760         dbgs() << "********** INTERVALS POST JOINING **********\n";
1761         for (LiveIntervals::iterator I = li_->begin(), E = li_->end();
1762              I != E; ++I){
1763           I->second->print(dbgs(), tri_);
1764           dbgs() << "\n";
1765         }
1766       });
1767   }
1768
1769   // Perform a final pass over the instructions and compute spill weights
1770   // and remove identity moves.
1771   SmallVector<unsigned, 4> DeadDefs;
1772   for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
1773        mbbi != mbbe; ++mbbi) {
1774     MachineBasicBlock* mbb = mbbi;
1775     for (MachineBasicBlock::iterator mii = mbb->begin(), mie = mbb->end();
1776          mii != mie; ) {
1777       MachineInstr *MI = mii;
1778       unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
1779       if (JoinedCopies.count(MI)) {
1780         // Delete all coalesced copies.
1781         bool DoDelete = true;
1782         if (!tii_->isMoveInstr(*MI, SrcReg, DstReg, SrcSubIdx, DstSubIdx)) {
1783           assert(MI->isCopyLike() && "Unrecognized copy instruction");
1784           SrcReg = MI->getOperand(MI->isSubregToReg() ? 2 : 1).getReg();
1785           if (TargetRegisterInfo::isPhysicalRegister(SrcReg))
1786             // Do not delete extract_subreg, insert_subreg of physical
1787             // registers unless the definition is dead. e.g.
1788             // %DO<def> = INSERT_SUBREG %D0<undef>, %S0<kill>, 1
1789             // or else the scavenger may complain. LowerSubregs will
1790             // delete them later.
1791             DoDelete = false;
1792         }
1793         if (MI->allDefsAreDead()) {
1794           LiveInterval &li = li_->getInterval(SrcReg);
1795           if (!ShortenDeadCopySrcLiveRange(li, MI))
1796             ShortenDeadCopyLiveRange(li, MI);
1797           DoDelete = true;
1798         }
1799         if (!DoDelete)
1800           mii = llvm::next(mii);
1801         else {
1802           li_->RemoveMachineInstrFromMaps(MI);
1803           mii = mbbi->erase(mii);
1804           ++numPeep;
1805         }
1806         continue;
1807       }
1808
1809       // Now check if this is a remat'ed def instruction which is now dead.
1810       if (ReMatDefs.count(MI)) {
1811         bool isDead = true;
1812         for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1813           const MachineOperand &MO = MI->getOperand(i);
1814           if (!MO.isReg())
1815             continue;
1816           unsigned Reg = MO.getReg();
1817           if (!Reg)
1818             continue;
1819           if (TargetRegisterInfo::isVirtualRegister(Reg))
1820             DeadDefs.push_back(Reg);
1821           if (MO.isDead())
1822             continue;
1823           if (TargetRegisterInfo::isPhysicalRegister(Reg) ||
1824               !mri_->use_nodbg_empty(Reg)) {
1825             isDead = false;
1826             break;
1827           }
1828         }
1829         if (isDead) {
1830           while (!DeadDefs.empty()) {
1831             unsigned DeadDef = DeadDefs.back();
1832             DeadDefs.pop_back();
1833             RemoveDeadDef(li_->getInterval(DeadDef), MI);
1834           }
1835           li_->RemoveMachineInstrFromMaps(mii);
1836           mii = mbbi->erase(mii);
1837           continue;
1838         } else
1839           DeadDefs.clear();
1840       }
1841
1842       // If the move will be an identity move delete it
1843       bool isMove= tii_->isMoveInstr(*MI, SrcReg, DstReg, SrcSubIdx, DstSubIdx);
1844       if (MI->isIdentityCopy() ||
1845           (isMove && SrcReg == DstReg && SrcSubIdx == DstSubIdx)) {
1846         if (li_->hasInterval(SrcReg)) {
1847           LiveInterval &RegInt = li_->getInterval(SrcReg);
1848           // If def of this move instruction is dead, remove its live range
1849           // from the destination register's live interval.
1850           if (MI->allDefsAreDead()) {
1851             if (!ShortenDeadCopySrcLiveRange(RegInt, MI))
1852               ShortenDeadCopyLiveRange(RegInt, MI);
1853           }
1854         }
1855         li_->RemoveMachineInstrFromMaps(MI);
1856         mii = mbbi->erase(mii);
1857         ++numPeep;
1858         continue;
1859       }
1860
1861       ++mii;
1862
1863       // Check for now unnecessary kill flags.
1864       if (li_->isNotInMIMap(MI)) continue;
1865       SlotIndex DefIdx = li_->getInstructionIndex(MI).getDefIndex();
1866       for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1867         MachineOperand &MO = MI->getOperand(i);
1868         if (!MO.isReg() || !MO.isKill()) continue;
1869         unsigned reg = MO.getReg();
1870         if (!reg || !li_->hasInterval(reg)) continue;
1871         if (!li_->getInterval(reg).killedAt(DefIdx))
1872           MO.setIsKill(false);
1873       }
1874     }
1875   }
1876
1877   DEBUG(dump());
1878   return true;
1879 }
1880
1881 /// print - Implement the dump method.
1882 void SimpleRegisterCoalescing::print(raw_ostream &O, const Module* m) const {
1883    li_->print(O, m);
1884 }
1885
1886 RegisterCoalescer* llvm::createSimpleRegisterCoalescer() {
1887   return new SimpleRegisterCoalescing();
1888 }
1889
1890 // Make sure that anything that uses RegisterCoalescer pulls in this file...
1891 DEFINING_FILE_FOR(SimpleRegisterCoalescing)