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