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