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