Merge into undefined lanes under -new-coalescer.
[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 "VirtRegMap.h"
20
21 #include "llvm/Pass.h"
22 #include "llvm/Value.h"
23 #include "llvm/ADT/OwningPtr.h"
24 #include "llvm/ADT/STLExtras.h"
25 #include "llvm/ADT/SmallSet.h"
26 #include "llvm/ADT/Statistic.h"
27 #include "llvm/Analysis/AliasAnalysis.h"
28 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
29 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
30 #include "llvm/CodeGen/LiveRangeEdit.h"
31 #include "llvm/CodeGen/MachineFrameInfo.h"
32 #include "llvm/CodeGen/MachineInstr.h"
33 #include "llvm/CodeGen/MachineInstr.h"
34 #include "llvm/CodeGen/MachineLoopInfo.h"
35 #include "llvm/CodeGen/MachineRegisterInfo.h"
36 #include "llvm/CodeGen/MachineRegisterInfo.h"
37 #include "llvm/CodeGen/Passes.h"
38 #include "llvm/CodeGen/RegisterClassInfo.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(NumInflated , "Number of register classes inflated");
58
59 static cl::opt<bool>
60 EnableJoining("join-liveintervals",
61               cl::desc("Coalesce copies (default=true)"),
62               cl::init(true));
63
64 static cl::opt<bool>
65 VerifyCoalescing("verify-coalescing",
66          cl::desc("Verify machine instrs before and after register coalescing"),
67          cl::Hidden);
68
69 // Temporary option for testing new coalescer algo.
70 static cl::opt<bool>
71 NewCoalescer("new-coalescer", cl::Hidden,
72              cl::desc("Use new coalescer algorithm"));
73
74 namespace {
75   class RegisterCoalescer : public MachineFunctionPass,
76                             private LiveRangeEdit::Delegate {
77     MachineFunction* MF;
78     MachineRegisterInfo* MRI;
79     const TargetMachine* TM;
80     const TargetRegisterInfo* TRI;
81     const TargetInstrInfo* TII;
82     LiveIntervals *LIS;
83     LiveDebugVariables *LDV;
84     const MachineLoopInfo* Loops;
85     AliasAnalysis *AA;
86     RegisterClassInfo RegClassInfo;
87
88     /// WorkList - Copy instructions yet to be coalesced.
89     SmallVector<MachineInstr*, 8> WorkList;
90
91     /// ErasedInstrs - Set of instruction pointers that have been erased, and
92     /// that may be present in WorkList.
93     SmallPtrSet<MachineInstr*, 8> ErasedInstrs;
94
95     /// Dead instructions that are about to be deleted.
96     SmallVector<MachineInstr*, 8> DeadDefs;
97
98     /// Virtual registers to be considered for register class inflation.
99     SmallVector<unsigned, 8> InflateRegs;
100
101     /// Recursively eliminate dead defs in DeadDefs.
102     void eliminateDeadDefs();
103
104     /// LiveRangeEdit callback.
105     void LRE_WillEraseInstruction(MachineInstr *MI);
106
107     /// joinAllIntervals - join compatible live intervals
108     void joinAllIntervals();
109
110     /// copyCoalesceInMBB - Coalesce copies in the specified MBB, putting
111     /// copies that cannot yet be coalesced into WorkList.
112     void copyCoalesceInMBB(MachineBasicBlock *MBB);
113
114     /// copyCoalesceWorkList - Try to coalesce all copies in WorkList after
115     /// position From. Return true if any progress was made.
116     bool copyCoalesceWorkList(unsigned From = 0);
117
118     /// joinCopy - Attempt to join intervals corresponding to SrcReg/DstReg,
119     /// which are the src/dst of the copy instruction CopyMI.  This returns
120     /// true if the copy was successfully coalesced away. If it is not
121     /// currently possible to coalesce this interval, but it may be possible if
122     /// other things get coalesced, then it returns true by reference in
123     /// 'Again'.
124     bool joinCopy(MachineInstr *TheCopy, bool &Again);
125
126     /// joinIntervals - Attempt to join these two intervals.  On failure, this
127     /// returns false.  The output "SrcInt" will not have been modified, so we
128     /// can use this information below to update aliases.
129     bool joinIntervals(CoalescerPair &CP);
130
131     /// Attempt joining two virtual registers. Return true on success.
132     bool joinVirtRegs(CoalescerPair &CP);
133
134     /// Attempt joining with a reserved physreg.
135     bool joinReservedPhysReg(CoalescerPair &CP);
136
137     /// adjustCopiesBackFrom - We found a non-trivially-coalescable copy. If
138     /// the source value number is defined by a copy from the destination reg
139     /// see if we can merge these two destination reg valno# into a single
140     /// value number, eliminating a copy.
141     bool adjustCopiesBackFrom(const CoalescerPair &CP, MachineInstr *CopyMI);
142
143     /// hasOtherReachingDefs - Return true if there are definitions of IntB
144     /// other than BValNo val# that can reach uses of AValno val# of IntA.
145     bool hasOtherReachingDefs(LiveInterval &IntA, LiveInterval &IntB,
146                               VNInfo *AValNo, VNInfo *BValNo);
147
148     /// removeCopyByCommutingDef - We found a non-trivially-coalescable copy.
149     /// If the source value number is defined by a commutable instruction and
150     /// its other operand is coalesced to the copy dest register, see if we
151     /// can transform the copy into a noop by commuting the definition.
152     bool removeCopyByCommutingDef(const CoalescerPair &CP,MachineInstr *CopyMI);
153
154     /// reMaterializeTrivialDef - If the source of a copy is defined by a
155     /// trivial computation, replace the copy by rematerialize the definition.
156     bool reMaterializeTrivialDef(LiveInterval &SrcInt, unsigned DstReg,
157                                  MachineInstr *CopyMI);
158
159     /// canJoinPhys - Return true if a physreg copy should be joined.
160     bool canJoinPhys(CoalescerPair &CP);
161
162     /// updateRegDefsUses - Replace all defs and uses of SrcReg to DstReg and
163     /// update the subregister number if it is not zero. If DstReg is a
164     /// physical register and the existing subregister number of the def / use
165     /// being updated is not zero, make sure to set it to the correct physical
166     /// subregister.
167     void updateRegDefsUses(unsigned SrcReg, unsigned DstReg, unsigned SubIdx);
168
169     /// eliminateUndefCopy - Handle copies of undef values.
170     bool eliminateUndefCopy(MachineInstr *CopyMI, const CoalescerPair &CP);
171
172   public:
173     static char ID; // Class identification, replacement for typeinfo
174     RegisterCoalescer() : MachineFunctionPass(ID) {
175       initializeRegisterCoalescerPass(*PassRegistry::getPassRegistry());
176     }
177
178     virtual void getAnalysisUsage(AnalysisUsage &AU) const;
179
180     virtual void releaseMemory();
181
182     /// runOnMachineFunction - pass entry point
183     virtual bool runOnMachineFunction(MachineFunction&);
184
185     /// print - Implement the dump method.
186     virtual void print(raw_ostream &O, const Module* = 0) const;
187   };
188 } /// end anonymous namespace
189
190 char &llvm::RegisterCoalescerID = RegisterCoalescer::ID;
191
192 INITIALIZE_PASS_BEGIN(RegisterCoalescer, "simple-register-coalescing",
193                       "Simple Register Coalescing", false, false)
194 INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
195 INITIALIZE_PASS_DEPENDENCY(LiveDebugVariables)
196 INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
197 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
198 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
199 INITIALIZE_PASS_END(RegisterCoalescer, "simple-register-coalescing",
200                     "Simple Register Coalescing", false, false)
201
202 char RegisterCoalescer::ID = 0;
203
204 static unsigned compose(const TargetRegisterInfo &tri, unsigned a, unsigned b) {
205   if (!a) return b;
206   if (!b) return a;
207   return tri.composeSubRegIndices(a, b);
208 }
209
210 static bool isMoveInstr(const TargetRegisterInfo &tri, const MachineInstr *MI,
211                         unsigned &Src, unsigned &Dst,
212                         unsigned &SrcSub, unsigned &DstSub) {
213   if (MI->isCopy()) {
214     Dst = MI->getOperand(0).getReg();
215     DstSub = MI->getOperand(0).getSubReg();
216     Src = MI->getOperand(1).getReg();
217     SrcSub = MI->getOperand(1).getSubReg();
218   } else if (MI->isSubregToReg()) {
219     Dst = MI->getOperand(0).getReg();
220     DstSub = compose(tri, MI->getOperand(0).getSubReg(),
221                      MI->getOperand(3).getImm());
222     Src = MI->getOperand(2).getReg();
223     SrcSub = MI->getOperand(2).getSubReg();
224   } else
225     return false;
226   return true;
227 }
228
229 bool CoalescerPair::setRegisters(const MachineInstr *MI) {
230   SrcReg = DstReg = 0;
231   SrcIdx = DstIdx = 0;
232   NewRC = 0;
233   Flipped = CrossClass = false;
234
235   unsigned Src, Dst, SrcSub, DstSub;
236   if (!isMoveInstr(TRI, MI, Src, Dst, SrcSub, DstSub))
237     return false;
238   Partial = SrcSub || DstSub;
239
240   // If one register is a physreg, it must be Dst.
241   if (TargetRegisterInfo::isPhysicalRegister(Src)) {
242     if (TargetRegisterInfo::isPhysicalRegister(Dst))
243       return false;
244     std::swap(Src, Dst);
245     std::swap(SrcSub, DstSub);
246     Flipped = true;
247   }
248
249   const MachineRegisterInfo &MRI = MI->getParent()->getParent()->getRegInfo();
250
251   if (TargetRegisterInfo::isPhysicalRegister(Dst)) {
252     // Eliminate DstSub on a physreg.
253     if (DstSub) {
254       Dst = TRI.getSubReg(Dst, DstSub);
255       if (!Dst) return false;
256       DstSub = 0;
257     }
258
259     // Eliminate SrcSub by picking a corresponding Dst superregister.
260     if (SrcSub) {
261       Dst = TRI.getMatchingSuperReg(Dst, SrcSub, MRI.getRegClass(Src));
262       if (!Dst) return false;
263       SrcSub = 0;
264     } else if (!MRI.getRegClass(Src)->contains(Dst)) {
265       return false;
266     }
267   } else {
268     // Both registers are virtual.
269     const TargetRegisterClass *SrcRC = MRI.getRegClass(Src);
270     const TargetRegisterClass *DstRC = MRI.getRegClass(Dst);
271
272     // Both registers have subreg indices.
273     if (SrcSub && DstSub) {
274       // Copies between different sub-registers are never coalescable.
275       if (Src == Dst && SrcSub != DstSub)
276         return false;
277
278       NewRC = TRI.getCommonSuperRegClass(SrcRC, SrcSub, DstRC, DstSub,
279                                          SrcIdx, DstIdx);
280       if (!NewRC)
281         return false;
282     } else if (DstSub) {
283       // SrcReg will be merged with a sub-register of DstReg.
284       SrcIdx = DstSub;
285       NewRC = TRI.getMatchingSuperRegClass(DstRC, SrcRC, DstSub);
286     } else if (SrcSub) {
287       // DstReg will be merged with a sub-register of SrcReg.
288       DstIdx = SrcSub;
289       NewRC = TRI.getMatchingSuperRegClass(SrcRC, DstRC, SrcSub);
290     } else {
291       // This is a straight copy without sub-registers.
292       NewRC = TRI.getCommonSubClass(DstRC, SrcRC);
293     }
294
295     // The combined constraint may be impossible to satisfy.
296     if (!NewRC)
297       return false;
298
299     // Prefer SrcReg to be a sub-register of DstReg.
300     // FIXME: Coalescer should support subregs symmetrically.
301     if (DstIdx && !SrcIdx) {
302       std::swap(Src, Dst);
303       std::swap(SrcIdx, DstIdx);
304       Flipped = !Flipped;
305     }
306
307     CrossClass = NewRC != DstRC || NewRC != SrcRC;
308   }
309   // Check our invariants
310   assert(TargetRegisterInfo::isVirtualRegister(Src) && "Src must be virtual");
311   assert(!(TargetRegisterInfo::isPhysicalRegister(Dst) && DstSub) &&
312          "Cannot have a physical SubIdx");
313   SrcReg = Src;
314   DstReg = Dst;
315   return true;
316 }
317
318 bool CoalescerPair::flip() {
319   if (TargetRegisterInfo::isPhysicalRegister(DstReg))
320     return false;
321   std::swap(SrcReg, DstReg);
322   std::swap(SrcIdx, DstIdx);
323   Flipped = !Flipped;
324   return true;
325 }
326
327 bool CoalescerPair::isCoalescable(const MachineInstr *MI) const {
328   if (!MI)
329     return false;
330   unsigned Src, Dst, SrcSub, DstSub;
331   if (!isMoveInstr(TRI, MI, Src, Dst, SrcSub, DstSub))
332     return false;
333
334   // Find the virtual register that is SrcReg.
335   if (Dst == SrcReg) {
336     std::swap(Src, Dst);
337     std::swap(SrcSub, DstSub);
338   } else if (Src != SrcReg) {
339     return false;
340   }
341
342   // Now check that Dst matches DstReg.
343   if (TargetRegisterInfo::isPhysicalRegister(DstReg)) {
344     if (!TargetRegisterInfo::isPhysicalRegister(Dst))
345       return false;
346     assert(!DstIdx && !SrcIdx && "Inconsistent CoalescerPair state.");
347     // DstSub could be set for a physreg from INSERT_SUBREG.
348     if (DstSub)
349       Dst = TRI.getSubReg(Dst, DstSub);
350     // Full copy of Src.
351     if (!SrcSub)
352       return DstReg == Dst;
353     // This is a partial register copy. Check that the parts match.
354     return TRI.getSubReg(DstReg, SrcSub) == Dst;
355   } else {
356     // DstReg is virtual.
357     if (DstReg != Dst)
358       return false;
359     // Registers match, do the subregisters line up?
360     return compose(TRI, SrcIdx, SrcSub) == compose(TRI, DstIdx, DstSub);
361   }
362 }
363
364 void RegisterCoalescer::getAnalysisUsage(AnalysisUsage &AU) const {
365   AU.setPreservesCFG();
366   AU.addRequired<AliasAnalysis>();
367   AU.addRequired<LiveIntervals>();
368   AU.addPreserved<LiveIntervals>();
369   AU.addRequired<LiveDebugVariables>();
370   AU.addPreserved<LiveDebugVariables>();
371   AU.addPreserved<SlotIndexes>();
372   AU.addRequired<MachineLoopInfo>();
373   AU.addPreserved<MachineLoopInfo>();
374   AU.addPreservedID(MachineDominatorsID);
375   MachineFunctionPass::getAnalysisUsage(AU);
376 }
377
378 void RegisterCoalescer::eliminateDeadDefs() {
379   SmallVector<LiveInterval*, 8> NewRegs;
380   LiveRangeEdit(0, NewRegs, *MF, *LIS, 0, this).eliminateDeadDefs(DeadDefs);
381 }
382
383 // Callback from eliminateDeadDefs().
384 void RegisterCoalescer::LRE_WillEraseInstruction(MachineInstr *MI) {
385   // MI may be in WorkList. Make sure we don't visit it.
386   ErasedInstrs.insert(MI);
387 }
388
389 /// adjustCopiesBackFrom - We found a non-trivially-coalescable copy with IntA
390 /// being the source and IntB being the dest, thus this defines a value number
391 /// in IntB.  If the source value number (in IntA) is defined by a copy from B,
392 /// see if we can merge these two pieces of B into a single value number,
393 /// eliminating a copy.  For example:
394 ///
395 ///  A3 = B0
396 ///    ...
397 ///  B1 = A3      <- this copy
398 ///
399 /// In this case, B0 can be extended to where the B1 copy lives, allowing the B1
400 /// value number to be replaced with B0 (which simplifies the B liveinterval).
401 ///
402 /// This returns true if an interval was modified.
403 ///
404 bool RegisterCoalescer::adjustCopiesBackFrom(const CoalescerPair &CP,
405                                              MachineInstr *CopyMI) {
406   assert(!CP.isPartial() && "This doesn't work for partial copies.");
407   assert(!CP.isPhys() && "This doesn't work for physreg copies.");
408
409   LiveInterval &IntA =
410     LIS->getInterval(CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg());
411   LiveInterval &IntB =
412     LIS->getInterval(CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg());
413   SlotIndex CopyIdx = LIS->getInstructionIndex(CopyMI).getRegSlot();
414
415   // BValNo is a value number in B that is defined by a copy from A.  'B3' in
416   // the example above.
417   LiveInterval::iterator BLR = IntB.FindLiveRangeContaining(CopyIdx);
418   if (BLR == IntB.end()) return false;
419   VNInfo *BValNo = BLR->valno;
420
421   // Get the location that B is defined at.  Two options: either this value has
422   // an unknown definition point or it is defined at CopyIdx.  If unknown, we
423   // can't process it.
424   if (BValNo->def != CopyIdx) return false;
425
426   // AValNo is the value number in A that defines the copy, A3 in the example.
427   SlotIndex CopyUseIdx = CopyIdx.getRegSlot(true);
428   LiveInterval::iterator ALR = IntA.FindLiveRangeContaining(CopyUseIdx);
429   // The live range might not exist after fun with physreg coalescing.
430   if (ALR == IntA.end()) return false;
431   VNInfo *AValNo = ALR->valno;
432
433   // If AValNo is defined as a copy from IntB, we can potentially process this.
434   // Get the instruction that defines this value number.
435   MachineInstr *ACopyMI = LIS->getInstructionFromIndex(AValNo->def);
436   if (!CP.isCoalescable(ACopyMI))
437     return false;
438
439   // Get the LiveRange in IntB that this value number starts with.
440   LiveInterval::iterator ValLR =
441     IntB.FindLiveRangeContaining(AValNo->def.getPrevSlot());
442   if (ValLR == IntB.end())
443     return false;
444
445   // Make sure that the end of the live range is inside the same block as
446   // CopyMI.
447   MachineInstr *ValLREndInst =
448     LIS->getInstructionFromIndex(ValLR->end.getPrevSlot());
449   if (!ValLREndInst || ValLREndInst->getParent() != CopyMI->getParent())
450     return false;
451
452   // Okay, we now know that ValLR ends in the same block that the CopyMI
453   // live-range starts.  If there are no intervening live ranges between them in
454   // IntB, we can merge them.
455   if (ValLR+1 != BLR) return false;
456
457   DEBUG(dbgs() << "Extending: " << PrintReg(IntB.reg, TRI));
458
459   SlotIndex FillerStart = ValLR->end, FillerEnd = BLR->start;
460   // We are about to delete CopyMI, so need to remove it as the 'instruction
461   // that defines this value #'. Update the valnum with the new defining
462   // instruction #.
463   BValNo->def = FillerStart;
464
465   // Okay, we can merge them.  We need to insert a new liverange:
466   // [ValLR.end, BLR.begin) of either value number, then we merge the
467   // two value numbers.
468   IntB.addRange(LiveRange(FillerStart, FillerEnd, BValNo));
469
470   // Okay, merge "B1" into the same value number as "B0".
471   if (BValNo != ValLR->valno)
472     IntB.MergeValueNumberInto(BValNo, ValLR->valno);
473   DEBUG(dbgs() << "   result = " << IntB << '\n');
474
475   // If the source instruction was killing the source register before the
476   // merge, unset the isKill marker given the live range has been extended.
477   int UIdx = ValLREndInst->findRegisterUseOperandIdx(IntB.reg, true);
478   if (UIdx != -1) {
479     ValLREndInst->getOperand(UIdx).setIsKill(false);
480   }
481
482   // Rewrite the copy. If the copy instruction was killing the destination
483   // register before the merge, find the last use and trim the live range. That
484   // will also add the isKill marker.
485   CopyMI->substituteRegister(IntA.reg, IntB.reg, 0, *TRI);
486   if (ALR->end == CopyIdx)
487     LIS->shrinkToUses(&IntA);
488
489   ++numExtends;
490   return true;
491 }
492
493 /// hasOtherReachingDefs - Return true if there are definitions of IntB
494 /// other than BValNo val# that can reach uses of AValno val# of IntA.
495 bool RegisterCoalescer::hasOtherReachingDefs(LiveInterval &IntA,
496                                              LiveInterval &IntB,
497                                              VNInfo *AValNo,
498                                              VNInfo *BValNo) {
499   // If AValNo has PHI kills, conservatively assume that IntB defs can reach
500   // the PHI values.
501   if (LIS->hasPHIKill(IntA, AValNo))
502     return true;
503
504   for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
505        AI != AE; ++AI) {
506     if (AI->valno != AValNo) continue;
507     LiveInterval::Ranges::iterator BI =
508       std::upper_bound(IntB.ranges.begin(), IntB.ranges.end(), AI->start);
509     if (BI != IntB.ranges.begin())
510       --BI;
511     for (; BI != IntB.ranges.end() && AI->end >= BI->start; ++BI) {
512       if (BI->valno == BValNo)
513         continue;
514       if (BI->start <= AI->start && BI->end > AI->start)
515         return true;
516       if (BI->start > AI->start && BI->start < AI->end)
517         return true;
518     }
519   }
520   return false;
521 }
522
523 /// removeCopyByCommutingDef - We found a non-trivially-coalescable copy with
524 /// IntA being the source and IntB being the dest, thus this defines a value
525 /// number in IntB.  If the source value number (in IntA) is defined by a
526 /// commutable instruction and its other operand is coalesced to the copy dest
527 /// register, see if we can transform the copy into a noop by commuting the
528 /// definition. For example,
529 ///
530 ///  A3 = op A2 B0<kill>
531 ///    ...
532 ///  B1 = A3      <- this copy
533 ///    ...
534 ///     = op A3   <- more uses
535 ///
536 /// ==>
537 ///
538 ///  B2 = op B0 A2<kill>
539 ///    ...
540 ///  B1 = B2      <- now an identify copy
541 ///    ...
542 ///     = op B2   <- more uses
543 ///
544 /// This returns true if an interval was modified.
545 ///
546 bool RegisterCoalescer::removeCopyByCommutingDef(const CoalescerPair &CP,
547                                                  MachineInstr *CopyMI) {
548   assert (!CP.isPhys());
549
550   SlotIndex CopyIdx = LIS->getInstructionIndex(CopyMI).getRegSlot();
551
552   LiveInterval &IntA =
553     LIS->getInterval(CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg());
554   LiveInterval &IntB =
555     LIS->getInterval(CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg());
556
557   // BValNo is a value number in B that is defined by a copy from A. 'B3' in
558   // the example above.
559   VNInfo *BValNo = IntB.getVNInfoAt(CopyIdx);
560   if (!BValNo || BValNo->def != CopyIdx)
561     return false;
562
563   assert(BValNo->def == CopyIdx && "Copy doesn't define the value?");
564
565   // AValNo is the value number in A that defines the copy, A3 in the example.
566   VNInfo *AValNo = IntA.getVNInfoAt(CopyIdx.getRegSlot(true));
567   assert(AValNo && "COPY source not live");
568   if (AValNo->isPHIDef() || AValNo->isUnused())
569     return false;
570   MachineInstr *DefMI = LIS->getInstructionFromIndex(AValNo->def);
571   if (!DefMI)
572     return false;
573   if (!DefMI->isCommutable())
574     return false;
575   // If DefMI is a two-address instruction then commuting it will change the
576   // destination register.
577   int DefIdx = DefMI->findRegisterDefOperandIdx(IntA.reg);
578   assert(DefIdx != -1);
579   unsigned UseOpIdx;
580   if (!DefMI->isRegTiedToUseOperand(DefIdx, &UseOpIdx))
581     return false;
582   unsigned Op1, Op2, NewDstIdx;
583   if (!TII->findCommutedOpIndices(DefMI, Op1, Op2))
584     return false;
585   if (Op1 == UseOpIdx)
586     NewDstIdx = Op2;
587   else if (Op2 == UseOpIdx)
588     NewDstIdx = Op1;
589   else
590     return false;
591
592   MachineOperand &NewDstMO = DefMI->getOperand(NewDstIdx);
593   unsigned NewReg = NewDstMO.getReg();
594   if (NewReg != IntB.reg || !LiveRangeQuery(IntB, AValNo->def).isKill())
595     return false;
596
597   // Make sure there are no other definitions of IntB that would reach the
598   // uses which the new definition can reach.
599   if (hasOtherReachingDefs(IntA, IntB, AValNo, BValNo))
600     return false;
601
602   // If some of the uses of IntA.reg is already coalesced away, return false.
603   // It's not possible to determine whether it's safe to perform the coalescing.
604   for (MachineRegisterInfo::use_nodbg_iterator UI =
605          MRI->use_nodbg_begin(IntA.reg),
606        UE = MRI->use_nodbg_end(); UI != UE; ++UI) {
607     MachineInstr *UseMI = &*UI;
608     SlotIndex UseIdx = LIS->getInstructionIndex(UseMI);
609     LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx);
610     if (ULR == IntA.end() || ULR->valno != AValNo)
611       continue;
612     // If this use is tied to a def, we can't rewrite the register.
613     if (UseMI->isRegTiedToDefOperand(UI.getOperandNo()))
614       return false;
615   }
616
617   DEBUG(dbgs() << "\tremoveCopyByCommutingDef: " << AValNo->def << '\t'
618                << *DefMI);
619
620   // At this point we have decided that it is legal to do this
621   // transformation.  Start by commuting the instruction.
622   MachineBasicBlock *MBB = DefMI->getParent();
623   MachineInstr *NewMI = TII->commuteInstruction(DefMI);
624   if (!NewMI)
625     return false;
626   if (TargetRegisterInfo::isVirtualRegister(IntA.reg) &&
627       TargetRegisterInfo::isVirtualRegister(IntB.reg) &&
628       !MRI->constrainRegClass(IntB.reg, MRI->getRegClass(IntA.reg)))
629     return false;
630   if (NewMI != DefMI) {
631     LIS->ReplaceMachineInstrInMaps(DefMI, NewMI);
632     MachineBasicBlock::iterator Pos = DefMI;
633     MBB->insert(Pos, NewMI);
634     MBB->erase(DefMI);
635   }
636   unsigned OpIdx = NewMI->findRegisterUseOperandIdx(IntA.reg, false);
637   NewMI->getOperand(OpIdx).setIsKill();
638
639   // If ALR and BLR overlaps and end of BLR extends beyond end of ALR, e.g.
640   // A = or A, B
641   // ...
642   // B = A
643   // ...
644   // C = A<kill>
645   // ...
646   //   = B
647
648   // Update uses of IntA of the specific Val# with IntB.
649   for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(IntA.reg),
650          UE = MRI->use_end(); UI != UE;) {
651     MachineOperand &UseMO = UI.getOperand();
652     MachineInstr *UseMI = &*UI;
653     ++UI;
654     if (UseMI->isDebugValue()) {
655       // FIXME These don't have an instruction index.  Not clear we have enough
656       // info to decide whether to do this replacement or not.  For now do it.
657       UseMO.setReg(NewReg);
658       continue;
659     }
660     SlotIndex UseIdx = LIS->getInstructionIndex(UseMI).getRegSlot(true);
661     LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx);
662     if (ULR == IntA.end() || ULR->valno != AValNo)
663       continue;
664     // Kill flags are no longer accurate. They are recomputed after RA.
665     UseMO.setIsKill(false);
666     if (TargetRegisterInfo::isPhysicalRegister(NewReg))
667       UseMO.substPhysReg(NewReg, *TRI);
668     else
669       UseMO.setReg(NewReg);
670     if (UseMI == CopyMI)
671       continue;
672     if (!UseMI->isCopy())
673       continue;
674     if (UseMI->getOperand(0).getReg() != IntB.reg ||
675         UseMI->getOperand(0).getSubReg())
676       continue;
677
678     // This copy will become a noop. If it's defining a new val#, merge it into
679     // BValNo.
680     SlotIndex DefIdx = UseIdx.getRegSlot();
681     VNInfo *DVNI = IntB.getVNInfoAt(DefIdx);
682     if (!DVNI)
683       continue;
684     DEBUG(dbgs() << "\t\tnoop: " << DefIdx << '\t' << *UseMI);
685     assert(DVNI->def == DefIdx);
686     BValNo = IntB.MergeValueNumberInto(BValNo, DVNI);
687     ErasedInstrs.insert(UseMI);
688     LIS->RemoveMachineInstrFromMaps(UseMI);
689     UseMI->eraseFromParent();
690   }
691
692   // Extend BValNo by merging in IntA live ranges of AValNo. Val# definition
693   // is updated.
694   VNInfo *ValNo = BValNo;
695   ValNo->def = AValNo->def;
696   for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
697        AI != AE; ++AI) {
698     if (AI->valno != AValNo) continue;
699     IntB.addRange(LiveRange(AI->start, AI->end, ValNo));
700   }
701   DEBUG(dbgs() << "\t\textended: " << IntB << '\n');
702
703   IntA.removeValNo(AValNo);
704   DEBUG(dbgs() << "\t\ttrimmed:  " << IntA << '\n');
705   ++numCommutes;
706   return true;
707 }
708
709 /// reMaterializeTrivialDef - If the source of a copy is defined by a trivial
710 /// computation, replace the copy by rematerialize the definition.
711 bool RegisterCoalescer::reMaterializeTrivialDef(LiveInterval &SrcInt,
712                                                 unsigned DstReg,
713                                                 MachineInstr *CopyMI) {
714   SlotIndex CopyIdx = LIS->getInstructionIndex(CopyMI).getRegSlot(true);
715   LiveInterval::iterator SrcLR = SrcInt.FindLiveRangeContaining(CopyIdx);
716   assert(SrcLR != SrcInt.end() && "Live range not found!");
717   VNInfo *ValNo = SrcLR->valno;
718   if (ValNo->isPHIDef() || ValNo->isUnused())
719     return false;
720   MachineInstr *DefMI = LIS->getInstructionFromIndex(ValNo->def);
721   if (!DefMI)
722     return false;
723   assert(DefMI && "Defining instruction disappeared");
724   if (!DefMI->isAsCheapAsAMove())
725     return false;
726   if (!TII->isTriviallyReMaterializable(DefMI, AA))
727     return false;
728   bool SawStore = false;
729   if (!DefMI->isSafeToMove(TII, AA, SawStore))
730     return false;
731   const MCInstrDesc &MCID = DefMI->getDesc();
732   if (MCID.getNumDefs() != 1)
733     return false;
734   if (!DefMI->isImplicitDef()) {
735     // Make sure the copy destination register class fits the instruction
736     // definition register class. The mismatch can happen as a result of earlier
737     // extract_subreg, insert_subreg, subreg_to_reg coalescing.
738     const TargetRegisterClass *RC = TII->getRegClass(MCID, 0, TRI, *MF);
739     if (TargetRegisterInfo::isVirtualRegister(DstReg)) {
740       if (MRI->getRegClass(DstReg) != RC)
741         return false;
742     } else if (!RC->contains(DstReg))
743       return false;
744   }
745
746   MachineBasicBlock *MBB = CopyMI->getParent();
747   MachineBasicBlock::iterator MII =
748     llvm::next(MachineBasicBlock::iterator(CopyMI));
749   TII->reMaterialize(*MBB, MII, DstReg, 0, DefMI, *TRI);
750   MachineInstr *NewMI = prior(MII);
751
752   // NewMI may have dead implicit defs (E.g. EFLAGS for MOV<bits>r0 on X86).
753   // We need to remember these so we can add intervals once we insert
754   // NewMI into SlotIndexes.
755   SmallVector<unsigned, 4> NewMIImplDefs;
756   for (unsigned i = NewMI->getDesc().getNumOperands(),
757          e = NewMI->getNumOperands(); i != e; ++i) {
758     MachineOperand &MO = NewMI->getOperand(i);
759     if (MO.isReg()) {
760       assert(MO.isDef() && MO.isImplicit() && MO.isDead() &&
761              TargetRegisterInfo::isPhysicalRegister(MO.getReg()));
762       NewMIImplDefs.push_back(MO.getReg());
763     }
764   }
765
766   // CopyMI may have implicit operands, transfer them over to the newly
767   // rematerialized instruction. And update implicit def interval valnos.
768   for (unsigned i = CopyMI->getDesc().getNumOperands(),
769          e = CopyMI->getNumOperands(); i != e; ++i) {
770     MachineOperand &MO = CopyMI->getOperand(i);
771     if (MO.isReg()) {
772       assert(MO.isImplicit() && "No explicit operands after implict operands.");
773       // Discard VReg implicit defs.
774       if (TargetRegisterInfo::isPhysicalRegister(MO.getReg())) {
775         NewMI->addOperand(MO);
776       }
777     }
778   }
779
780   LIS->ReplaceMachineInstrInMaps(CopyMI, NewMI);
781
782   SlotIndex NewMIIdx = LIS->getInstructionIndex(NewMI);
783   for (unsigned i = 0, e = NewMIImplDefs.size(); i != e; ++i) {
784     unsigned Reg = NewMIImplDefs[i];
785     for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units)
786       if (LiveInterval *LI = LIS->getCachedRegUnit(*Units))
787         LI->createDeadDef(NewMIIdx.getRegSlot(), LIS->getVNInfoAllocator());
788   }
789
790   CopyMI->eraseFromParent();
791   ErasedInstrs.insert(CopyMI);
792   DEBUG(dbgs() << "Remat: " << *NewMI);
793   ++NumReMats;
794
795   // The source interval can become smaller because we removed a use.
796   LIS->shrinkToUses(&SrcInt, &DeadDefs);
797   if (!DeadDefs.empty())
798     eliminateDeadDefs();
799
800   return true;
801 }
802
803 /// eliminateUndefCopy - ProcessImpicitDefs may leave some copies of <undef>
804 /// values, it only removes local variables. When we have a copy like:
805 ///
806 ///   %vreg1 = COPY %vreg2<undef>
807 ///
808 /// We delete the copy and remove the corresponding value number from %vreg1.
809 /// Any uses of that value number are marked as <undef>.
810 bool RegisterCoalescer::eliminateUndefCopy(MachineInstr *CopyMI,
811                                            const CoalescerPair &CP) {
812   SlotIndex Idx = LIS->getInstructionIndex(CopyMI);
813   LiveInterval *SrcInt = &LIS->getInterval(CP.getSrcReg());
814   if (SrcInt->liveAt(Idx))
815     return false;
816   LiveInterval *DstInt = &LIS->getInterval(CP.getDstReg());
817   if (DstInt->liveAt(Idx))
818     return false;
819
820   // No intervals are live-in to CopyMI - it is undef.
821   if (CP.isFlipped())
822     DstInt = SrcInt;
823   SrcInt = 0;
824
825   VNInfo *DeadVNI = DstInt->getVNInfoAt(Idx.getRegSlot());
826   assert(DeadVNI && "No value defined in DstInt");
827   DstInt->removeValNo(DeadVNI);
828
829   // Find new undef uses.
830   for (MachineRegisterInfo::reg_nodbg_iterator
831          I = MRI->reg_nodbg_begin(DstInt->reg), E = MRI->reg_nodbg_end();
832        I != E; ++I) {
833     MachineOperand &MO = I.getOperand();
834     if (MO.isDef() || MO.isUndef())
835       continue;
836     MachineInstr *MI = MO.getParent();
837     SlotIndex Idx = LIS->getInstructionIndex(MI);
838     if (DstInt->liveAt(Idx))
839       continue;
840     MO.setIsUndef(true);
841     DEBUG(dbgs() << "\tnew undef: " << Idx << '\t' << *MI);
842   }
843   return true;
844 }
845
846 /// updateRegDefsUses - Replace all defs and uses of SrcReg to DstReg and
847 /// update the subregister number if it is not zero. If DstReg is a
848 /// physical register and the existing subregister number of the def / use
849 /// being updated is not zero, make sure to set it to the correct physical
850 /// subregister.
851 void RegisterCoalescer::updateRegDefsUses(unsigned SrcReg,
852                                           unsigned DstReg,
853                                           unsigned SubIdx) {
854   bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
855   LiveInterval *DstInt = DstIsPhys ? 0 : &LIS->getInterval(DstReg);
856
857   // Update LiveDebugVariables.
858   LDV->renameRegister(SrcReg, DstReg, SubIdx);
859
860   for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(SrcReg);
861        MachineInstr *UseMI = I.skipInstruction();) {
862     SmallVector<unsigned,8> Ops;
863     bool Reads, Writes;
864     tie(Reads, Writes) = UseMI->readsWritesVirtualRegister(SrcReg, &Ops);
865
866     // If SrcReg wasn't read, it may still be the case that DstReg is live-in
867     // because SrcReg is a sub-register.
868     if (DstInt && !Reads && SubIdx)
869       Reads = DstInt->liveAt(LIS->getInstructionIndex(UseMI));
870
871     // Replace SrcReg with DstReg in all UseMI operands.
872     for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
873       MachineOperand &MO = UseMI->getOperand(Ops[i]);
874
875       // Adjust <undef> flags in case of sub-register joins. We don't want to
876       // turn a full def into a read-modify-write sub-register def and vice
877       // versa.
878       if (SubIdx && MO.isDef())
879         MO.setIsUndef(!Reads);
880
881       if (DstIsPhys)
882         MO.substPhysReg(DstReg, *TRI);
883       else
884         MO.substVirtReg(DstReg, SubIdx, *TRI);
885     }
886
887     DEBUG({
888         dbgs() << "\t\tupdated: ";
889         if (!UseMI->isDebugValue())
890           dbgs() << LIS->getInstructionIndex(UseMI) << "\t";
891         dbgs() << *UseMI;
892       });
893   }
894 }
895
896 /// canJoinPhys - Return true if a copy involving a physreg should be joined.
897 bool RegisterCoalescer::canJoinPhys(CoalescerPair &CP) {
898   /// Always join simple intervals that are defined by a single copy from a
899   /// reserved register. This doesn't increase register pressure, so it is
900   /// always beneficial.
901   if (!RegClassInfo.isReserved(CP.getDstReg())) {
902     DEBUG(dbgs() << "\tCan only merge into reserved registers.\n");
903     return false;
904   }
905
906   LiveInterval &JoinVInt = LIS->getInterval(CP.getSrcReg());
907   if (CP.isFlipped() && JoinVInt.containsOneValue())
908     return true;
909
910   DEBUG(dbgs() << "\tCannot join defs into reserved register.\n");
911   return false;
912 }
913
914 /// joinCopy - Attempt to join intervals corresponding to SrcReg/DstReg,
915 /// which are the src/dst of the copy instruction CopyMI.  This returns true
916 /// if the copy was successfully coalesced away. If it is not currently
917 /// possible to coalesce this interval, but it may be possible if other
918 /// things get coalesced, then it returns true by reference in 'Again'.
919 bool RegisterCoalescer::joinCopy(MachineInstr *CopyMI, bool &Again) {
920
921   Again = false;
922   DEBUG(dbgs() << LIS->getInstructionIndex(CopyMI) << '\t' << *CopyMI);
923
924   CoalescerPair CP(*TRI);
925   if (!CP.setRegisters(CopyMI)) {
926     DEBUG(dbgs() << "\tNot coalescable.\n");
927     return false;
928   }
929
930   // Dead code elimination. This really should be handled by MachineDCE, but
931   // sometimes dead copies slip through, and we can't generate invalid live
932   // ranges.
933   if (!CP.isPhys() && CopyMI->allDefsAreDead()) {
934     DEBUG(dbgs() << "\tCopy is dead.\n");
935     DeadDefs.push_back(CopyMI);
936     eliminateDeadDefs();
937     return true;
938   }
939
940   // Eliminate undefs.
941   if (!CP.isPhys() && eliminateUndefCopy(CopyMI, CP)) {
942     DEBUG(dbgs() << "\tEliminated copy of <undef> value.\n");
943     LIS->RemoveMachineInstrFromMaps(CopyMI);
944     CopyMI->eraseFromParent();
945     return false;  // Not coalescable.
946   }
947
948   // Coalesced copies are normally removed immediately, but transformations
949   // like removeCopyByCommutingDef() can inadvertently create identity copies.
950   // When that happens, just join the values and remove the copy.
951   if (CP.getSrcReg() == CP.getDstReg()) {
952     LiveInterval &LI = LIS->getInterval(CP.getSrcReg());
953     DEBUG(dbgs() << "\tCopy already coalesced: " << LI << '\n');
954     LiveRangeQuery LRQ(LI, LIS->getInstructionIndex(CopyMI));
955     if (VNInfo *DefVNI = LRQ.valueDefined()) {
956       VNInfo *ReadVNI = LRQ.valueIn();
957       assert(ReadVNI && "No value before copy and no <undef> flag.");
958       assert(ReadVNI != DefVNI && "Cannot read and define the same value.");
959       LI.MergeValueNumberInto(DefVNI, ReadVNI);
960       DEBUG(dbgs() << "\tMerged values:          " << LI << '\n');
961     }
962     LIS->RemoveMachineInstrFromMaps(CopyMI);
963     CopyMI->eraseFromParent();
964     return true;
965   }
966
967   // Enforce policies.
968   if (CP.isPhys()) {
969     DEBUG(dbgs() << "\tConsidering merging " << PrintReg(CP.getSrcReg(), TRI)
970                  << " with " << PrintReg(CP.getDstReg(), TRI, CP.getSrcIdx())
971                  << '\n');
972     if (!canJoinPhys(CP)) {
973       // Before giving up coalescing, if definition of source is defined by
974       // trivial computation, try rematerializing it.
975       if (!CP.isFlipped() &&
976           reMaterializeTrivialDef(LIS->getInterval(CP.getSrcReg()),
977                                   CP.getDstReg(), CopyMI))
978         return true;
979       return false;
980     }
981   } else {
982     DEBUG({
983       dbgs() << "\tConsidering merging to " << CP.getNewRC()->getName()
984              << " with ";
985       if (CP.getDstIdx() && CP.getSrcIdx())
986         dbgs() << PrintReg(CP.getDstReg()) << " in "
987                << TRI->getSubRegIndexName(CP.getDstIdx()) << " and "
988                << PrintReg(CP.getSrcReg()) << " in "
989                << TRI->getSubRegIndexName(CP.getSrcIdx()) << '\n';
990       else
991         dbgs() << PrintReg(CP.getSrcReg(), TRI) << " in "
992                << PrintReg(CP.getDstReg(), TRI, CP.getSrcIdx()) << '\n';
993     });
994
995     // When possible, let DstReg be the larger interval.
996     if (!CP.isPartial() && LIS->getInterval(CP.getSrcReg()).ranges.size() >
997                            LIS->getInterval(CP.getDstReg()).ranges.size())
998       CP.flip();
999   }
1000
1001   // Okay, attempt to join these two intervals.  On failure, this returns false.
1002   // Otherwise, if one of the intervals being joined is a physreg, this method
1003   // always canonicalizes DstInt to be it.  The output "SrcInt" will not have
1004   // been modified, so we can use this information below to update aliases.
1005   if (!joinIntervals(CP)) {
1006     // Coalescing failed.
1007
1008     // If definition of source is defined by trivial computation, try
1009     // rematerializing it.
1010     if (!CP.isFlipped() &&
1011         reMaterializeTrivialDef(LIS->getInterval(CP.getSrcReg()),
1012                                 CP.getDstReg(), CopyMI))
1013       return true;
1014
1015     // If we can eliminate the copy without merging the live ranges, do so now.
1016     if (!CP.isPartial() && !CP.isPhys()) {
1017       if (adjustCopiesBackFrom(CP, CopyMI) ||
1018           removeCopyByCommutingDef(CP, CopyMI)) {
1019         LIS->RemoveMachineInstrFromMaps(CopyMI);
1020         CopyMI->eraseFromParent();
1021         DEBUG(dbgs() << "\tTrivial!\n");
1022         return true;
1023       }
1024     }
1025
1026     // Otherwise, we are unable to join the intervals.
1027     DEBUG(dbgs() << "\tInterference!\n");
1028     Again = true;  // May be possible to coalesce later.
1029     return false;
1030   }
1031
1032   // Coalescing to a virtual register that is of a sub-register class of the
1033   // other. Make sure the resulting register is set to the right register class.
1034   if (CP.isCrossClass()) {
1035     ++numCrossRCs;
1036     MRI->setRegClass(CP.getDstReg(), CP.getNewRC());
1037   }
1038
1039   // Removing sub-register copies can ease the register class constraints.
1040   // Make sure we attempt to inflate the register class of DstReg.
1041   if (!CP.isPhys() && RegClassInfo.isProperSubClass(CP.getNewRC()))
1042     InflateRegs.push_back(CP.getDstReg());
1043
1044   // CopyMI has been erased by joinIntervals at this point. Remove it from
1045   // ErasedInstrs since copyCoalesceWorkList() won't add a successful join back
1046   // to the work list. This keeps ErasedInstrs from growing needlessly.
1047   ErasedInstrs.erase(CopyMI);
1048
1049   // Rewrite all SrcReg operands to DstReg.
1050   // Also update DstReg operands to include DstIdx if it is set.
1051   if (CP.getDstIdx())
1052     updateRegDefsUses(CP.getDstReg(), CP.getDstReg(), CP.getDstIdx());
1053   updateRegDefsUses(CP.getSrcReg(), CP.getDstReg(), CP.getSrcIdx());
1054
1055   // SrcReg is guaranteed to be the register whose live interval that is
1056   // being merged.
1057   LIS->removeInterval(CP.getSrcReg());
1058
1059   // Update regalloc hint.
1060   TRI->UpdateRegAllocHint(CP.getSrcReg(), CP.getDstReg(), *MF);
1061
1062   DEBUG({
1063     dbgs() << "\tJoined. Result = " << PrintReg(CP.getDstReg(), TRI);
1064     if (!CP.isPhys())
1065       dbgs() << LIS->getInterval(CP.getDstReg());
1066      dbgs() << '\n';
1067   });
1068
1069   ++numJoins;
1070   return true;
1071 }
1072
1073 /// Attempt joining with a reserved physreg.
1074 bool RegisterCoalescer::joinReservedPhysReg(CoalescerPair &CP) {
1075   assert(CP.isPhys() && "Must be a physreg copy");
1076   assert(RegClassInfo.isReserved(CP.getDstReg()) && "Not a reserved register");
1077   LiveInterval &RHS = LIS->getInterval(CP.getSrcReg());
1078   DEBUG(dbgs() << "\t\tRHS = " << PrintReg(CP.getSrcReg()) << ' ' << RHS
1079                << '\n');
1080
1081   assert(CP.isFlipped() && RHS.containsOneValue() &&
1082          "Invalid join with reserved register");
1083
1084   // Optimization for reserved registers like ESP. We can only merge with a
1085   // reserved physreg if RHS has a single value that is a copy of CP.DstReg().
1086   // The live range of the reserved register will look like a set of dead defs
1087   // - we don't properly track the live range of reserved registers.
1088
1089   // Deny any overlapping intervals.  This depends on all the reserved
1090   // register live ranges to look like dead defs.
1091   for (MCRegUnitIterator UI(CP.getDstReg(), TRI); UI.isValid(); ++UI)
1092     if (RHS.overlaps(LIS->getRegUnit(*UI))) {
1093       DEBUG(dbgs() << "\t\tInterference: " << PrintRegUnit(*UI, TRI) << '\n');
1094       return false;
1095     }
1096
1097   // Skip any value computations, we are not adding new values to the
1098   // reserved register.  Also skip merging the live ranges, the reserved
1099   // register live range doesn't need to be accurate as long as all the
1100   // defs are there.
1101
1102   // Delete the identity copy.
1103   MachineInstr *CopyMI = MRI->getVRegDef(RHS.reg);
1104   LIS->RemoveMachineInstrFromMaps(CopyMI);
1105   CopyMI->eraseFromParent();
1106
1107   // We don't track kills for reserved registers.
1108   MRI->clearKillFlags(CP.getSrcReg());
1109
1110   return true;
1111 }
1112
1113 //===----------------------------------------------------------------------===//
1114 //                 Interference checking and interval joining
1115 //===----------------------------------------------------------------------===//
1116 //
1117 // In the easiest case, the two live ranges being joined are disjoint, and
1118 // there is no interference to consider. It is quite common, though, to have
1119 // overlapping live ranges, and we need to check if the interference can be
1120 // resolved.
1121 //
1122 // The live range of a single SSA value forms a sub-tree of the dominator tree.
1123 // This means that two SSA values overlap if and only if the def of one value
1124 // is contained in the live range of the other value. As a special case, the
1125 // overlapping values can be defined at the same index.
1126 //
1127 // The interference from an overlapping def can be resolved in these cases:
1128 //
1129 // 1. Coalescable copies. The value is defined by a copy that would become an
1130 //    identity copy after joining SrcReg and DstReg. The copy instruction will
1131 //    be removed, and the value will be merged with the source value.
1132 //
1133 //    There can be several copies back and forth, causing many values to be
1134 //    merged into one. We compute a list of ultimate values in the joined live
1135 //    range as well as a mappings from the old value numbers.
1136 //
1137 // 2. IMPLICIT_DEF. This instruction is only inserted to ensure all PHI
1138 //    predecessors have a live out value. It doesn't cause real interference,
1139 //    and can be merged into the value it overlaps. Like a coalescable copy, it
1140 //    can be erased after joining.
1141 //
1142 // 3. Copy of external value. The overlapping def may be a copy of a value that
1143 //    is already in the other register. This is like a coalescable copy, but
1144 //    the live range of the source register must be trimmed after erasing the
1145 //    copy instruction:
1146 //
1147 //      %src = COPY %ext
1148 //      %dst = COPY %ext  <-- Remove this COPY, trim the live range of %ext.
1149 //
1150 // 4. Clobbering undefined lanes. Vector registers are sometimes built by
1151 //    defining one lane at a time:
1152 //
1153 //      %dst:ssub0<def,read-undef> = FOO
1154 //      %src = BAR
1155 //      %dst:ssub1<def> = COPY %src
1156 //
1157 //    The live range of %src overlaps the %dst value defined by FOO, but
1158 //    merging %src into %dst:ssub1 is only going to clobber the ssub1 lane
1159 //    which was undef anyway.
1160 //
1161 //    The value mapping is more complicated in this case. The final live range
1162 //    will have different value numbers for both FOO and BAR, but there is no
1163 //    simple mapping from old to new values. It may even be necessary to add
1164 //    new PHI values.
1165 //
1166 // 5. Clobbering dead lanes. A def may clobber a lane of a vector register that
1167 //    is live, but never read. This can happen because we don't compute
1168 //    individual live ranges per lane.
1169 //
1170 //      %dst<def> = FOO
1171 //      %src = BAR
1172 //      %dst:ssub1<def> = COPY %src
1173 //
1174 //    This kind of interference is only resolved locally. If the clobbered
1175 //    lane value escapes the block, the join is aborted.
1176
1177 namespace {
1178 /// Track information about values in a single virtual register about to be
1179 /// joined. Objects of this class are always created in pairs - one for each
1180 /// side of the CoalescerPair.
1181 class JoinVals {
1182   LiveInterval &LI;
1183
1184   // Location of this register in the final joined register.
1185   // Either CP.DstIdx or CP.SrcIdx.
1186   unsigned SubIdx;
1187
1188   // Values that will be present in the final live range.
1189   SmallVectorImpl<VNInfo*> &NewVNInfo;
1190
1191   const CoalescerPair &CP;
1192   LiveIntervals *LIS;
1193   SlotIndexes *Indexes;
1194   const TargetRegisterInfo *TRI;
1195
1196   // Value number assignments. Maps value numbers in LI to entries in NewVNInfo.
1197   // This is suitable for passing to LiveInterval::join().
1198   SmallVector<int, 8> Assignments;
1199
1200   // Conflict resolution for overlapping values.
1201   enum ConflictResolution {
1202     // No overlap, simply keep this value.
1203     CR_Keep,
1204
1205     // Merge this value into OtherVNI and erase the defining instruction.
1206     // Used for IMPLICIT_DEF, coalescable copies, and copies from external
1207     // values.
1208     CR_Erase,
1209
1210     // Merge this value into OtherVNI but keep the defining instruction.
1211     // This is for the special case where OtherVNI is defined by the same
1212     // instruction.
1213     CR_Merge,
1214
1215     // Keep this value, and have it replace OtherVNI where possible. This
1216     // complicates value mapping since OtherVNI maps to two different values
1217     // before and after this def.
1218     // Used when clobbering undefined or dead lanes.
1219     CR_Replace,
1220
1221     // Unresolved conflict. Visit later when all values have been mapped.
1222     CR_Unresolved,
1223
1224     // Unresolvable conflict. Abort the join.
1225     CR_Impossible
1226   };
1227
1228   // Per-value info for LI. The lane bit masks are all relative to the final
1229   // joined register, so they can be compared directly between SrcReg and
1230   // DstReg.
1231   struct Val {
1232     ConflictResolution Resolution;
1233
1234     // Lanes written by this def, 0 for unanalyzed values.
1235     unsigned WriteLanes;
1236
1237     // Lanes with defined values in this register. Other lanes are undef and
1238     // safe to clobber.
1239     unsigned ValidLanes;
1240
1241     // Value in LI being redefined by this def.
1242     VNInfo *RedefVNI;
1243
1244     // Value in the other live range that overlaps this def, if any.
1245     VNInfo *OtherVNI;
1246
1247     Val() : Resolution(CR_Keep), WriteLanes(0), ValidLanes(0),
1248             RedefVNI(0), OtherVNI(0) {}
1249
1250     bool isAnalyzed() const { return WriteLanes != 0; }
1251   };
1252
1253   // One entry per value number in LI.
1254   SmallVector<Val, 8> Vals;
1255
1256   unsigned computeWriteLanes(const MachineInstr *DefMI, bool &Redef);
1257   VNInfo *stripCopies(VNInfo *VNI);
1258   ConflictResolution analyzeValue(unsigned ValNo, JoinVals &Other);
1259   void computeAssignment(unsigned ValNo, JoinVals &Other);
1260
1261 public:
1262   JoinVals(LiveInterval &li, unsigned subIdx,
1263            SmallVectorImpl<VNInfo*> &newVNInfo,
1264            const CoalescerPair &cp,
1265            LiveIntervals *lis,
1266            const TargetRegisterInfo *tri)
1267     : LI(li), SubIdx(subIdx), NewVNInfo(newVNInfo), CP(cp), LIS(lis),
1268       Indexes(LIS->getSlotIndexes()), TRI(tri),
1269       Assignments(LI.getNumValNums(), -1), Vals(LI.getNumValNums())
1270   {}
1271
1272   /// Analyze defs in LI and compute a value mapping in NewVNInfo.
1273   /// Returns false if any conflicts were impossible to resolve.
1274   bool mapValues(JoinVals &Other);
1275
1276   /// Try to resolve conflicts that require all values to be mapped.
1277   /// Returns false if any conflicts were impossible to resolve.
1278   bool resolveConflicts(JoinVals &Other);
1279
1280   /// Prune the live range of values in Other.LI where they would conflict with
1281   /// CR_Replace values in LI. Collect end points for restoring the live range
1282   /// after joining.
1283   void pruneValues(JoinVals &Other, SmallVectorImpl<SlotIndex> &EndPoints);
1284
1285   /// Erase any machine instructions that have been coalesced away.
1286   /// Add erased instructions to ErasedInstrs.
1287   /// Add foreign virtual registers to ShrinkRegs if their live range ended at
1288   /// the erased instrs.
1289   void eraseInstrs(SmallPtrSet<MachineInstr*, 8> &ErasedInstrs,
1290                    SmallVectorImpl<unsigned> &ShrinkRegs);
1291
1292   /// Get the value assignments suitable for passing to LiveInterval::join.
1293   const int *getAssignments() const { return &Assignments[0]; }
1294 };
1295 } // end anonymous namespace
1296
1297 /// Compute the bitmask of lanes actually written by DefMI.
1298 /// Set Redef if there are any partial register definitions that depend on the
1299 /// previous value of the register.
1300 unsigned JoinVals::computeWriteLanes(const MachineInstr *DefMI, bool &Redef) {
1301   unsigned L = 0;
1302   for (ConstMIOperands MO(DefMI); MO.isValid(); ++MO) {
1303     if (!MO->isReg() || MO->getReg() != LI.reg || !MO->isDef())
1304       continue;
1305     L |= TRI->getSubRegIndexLaneMask(compose(*TRI, SubIdx, MO->getSubReg()));
1306     if (MO->readsReg())
1307       Redef = true;
1308   }
1309   return L;
1310 }
1311
1312 /// Find the ultimate value that VNI was copied from.
1313 VNInfo *JoinVals::stripCopies(VNInfo *VNI) {
1314   while (!VNI->isPHIDef()) {
1315     MachineInstr *MI = Indexes->getInstructionFromIndex(VNI->def);
1316     assert(MI && "No defining instruction");
1317     if (!MI->isFullCopy())
1318       break;
1319     unsigned Reg = MI->getOperand(1).getReg();
1320     if (!TargetRegisterInfo::isVirtualRegister(Reg))
1321       break;
1322     LiveRangeQuery LRQ(LIS->getInterval(Reg), VNI->def);
1323     if (!LRQ.valueIn())
1324       break;
1325     VNI = LRQ.valueIn();
1326   }
1327   return VNI;
1328 }
1329
1330 /// Analyze ValNo in this live range, and set all fields of Vals[ValNo].
1331 /// Return a conflict resolution when possible, but leave the hard cases as
1332 /// CR_Unresolved.
1333 /// Recursively calls computeAssignment() on this and Other, guaranteeing that
1334 /// both OtherVNI and RedefVNI have been analyzed and mapped before returning.
1335 /// The recursion always goes upwards in the dominator tree, making loops
1336 /// impossible.
1337 JoinVals::ConflictResolution
1338 JoinVals::analyzeValue(unsigned ValNo, JoinVals &Other) {
1339   Val &V = Vals[ValNo];
1340   assert(!V.isAnalyzed() && "Value has already been analyzed!");
1341   VNInfo *VNI = LI.getValNumInfo(ValNo);
1342   if (VNI->isUnused()) {
1343     V.WriteLanes = ~0u;
1344     return CR_Keep;
1345   }
1346
1347   // Get the instruction defining this value, compute the lanes written.
1348   const MachineInstr *DefMI = 0;
1349   if (VNI->isPHIDef()) {
1350     // Conservatively assume that all lanes in a PHI are valid.
1351     V.ValidLanes = V.WriteLanes = TRI->getSubRegIndexLaneMask(SubIdx);
1352   } else {
1353     DefMI = Indexes->getInstructionFromIndex(VNI->def);
1354     bool Redef = false;
1355     V.ValidLanes = V.WriteLanes = computeWriteLanes(DefMI, Redef);
1356
1357     // If this is a read-modify-write instruction, there may be more valid
1358     // lanes than the ones written by this instruction.
1359     // This only covers partial redef operands. DefMI may have normal use
1360     // operands reading the register. They don't contribute valid lanes.
1361     //
1362     // This adds ssub1 to the set of valid lanes in %src:
1363     //
1364     //   %src:ssub1<def> = FOO
1365     //
1366     // This leaves only ssub1 valid, making any other lanes undef:
1367     //
1368     //   %src:ssub1<def,read-undef> = FOO %src:ssub2
1369     //
1370     // The <read-undef> flag on the def operand means that old lane values are
1371     // not important.
1372     if (Redef) {
1373       V.RedefVNI = LiveRangeQuery(LI, VNI->def).valueIn();
1374       assert(V.RedefVNI && "Instruction is reading nonexistent value");
1375       computeAssignment(V.RedefVNI->id, Other);
1376       V.ValidLanes |= Vals[V.RedefVNI->id].ValidLanes;
1377     }
1378
1379     // An IMPLICIT_DEF writes undef values.
1380     if (DefMI->isImplicitDef())
1381       V.ValidLanes &= ~V.WriteLanes;
1382   }
1383
1384   // Find the value in Other that overlaps VNI->def, if any.
1385   LiveRangeQuery OtherLRQ(Other.LI, VNI->def);
1386
1387   // It is possible that both values are defined by the same instruction, or
1388   // the values are PHIs defined in the same block. When that happens, the two
1389   // values should be merged into one, but not into any preceding value.
1390   // The first value defined or visited gets CR_Keep, the other gets CR_Merge.
1391   if (VNInfo *OtherVNI = OtherLRQ.valueDefined()) {
1392     DEBUG(dbgs() << "\t\tDouble def: " << VNI->def << '\n');
1393     assert(SlotIndex::isSameInstr(VNI->def, OtherVNI->def) && "Broken LRQ");
1394
1395     // One value stays, the other is merged. Keep the earlier one, or the first
1396     // one we see.
1397     if (OtherVNI->def < VNI->def)
1398       Other.computeAssignment(OtherVNI->id, *this);
1399     else if (VNI->def < OtherVNI->def && OtherLRQ.valueIn()) {
1400       // This is an early-clobber def overlapping a live-in value in the other
1401       // register. Not mergeable.
1402       V.OtherVNI = OtherLRQ.valueIn();
1403       return CR_Impossible;
1404     }
1405     V.OtherVNI = OtherVNI;
1406     Val &OtherV = Other.Vals[OtherVNI->id];
1407     // Keep this value, check for conflicts when analyzing OtherVNI.
1408     if (!OtherV.isAnalyzed())
1409       return CR_Keep;
1410     // Both sides have been analyzed now. Do they conflict?
1411     if (V.ValidLanes & OtherV.ValidLanes)
1412       // Overlapping lanes can't be resolved now, maybe later.
1413       return CR_Unresolved;
1414     else
1415       return CR_Merge;
1416   }
1417
1418   // No simultaneous def. Is Other live at the def?
1419   V.OtherVNI = OtherLRQ.valueIn();
1420   if (!V.OtherVNI)
1421     // No overlap, no conflict.
1422     return CR_Keep;
1423
1424   assert(!SlotIndex::isSameInstr(VNI->def, V.OtherVNI->def) && "Broken LRQ");
1425
1426   // We have overlapping values, or possibly a kill of Other.
1427   // Recursively compute assignments up the dominator tree.
1428   Other.computeAssignment(V.OtherVNI->id, *this);
1429   const Val &OtherV = Other.Vals[V.OtherVNI->id];
1430
1431   // Don't attempt resolving PHI values for now.
1432   if (VNI->isPHIDef())
1433     return CR_Impossible;
1434
1435   // Check for simple erasable conflicts.
1436   if (DefMI->isImplicitDef())
1437     return CR_Erase;
1438
1439   // Include the non-conflict where DefMI is a coalescable copy that kills
1440   // OtherVNI. We still want the copy erased and value numbers merged.
1441   if (CP.isCoalescable(DefMI)) {
1442     // Some of the lanes copied from OtherVNI may be undef, making them undef
1443     // here too.
1444     V.ValidLanes &= ~V.WriteLanes | OtherV.ValidLanes;
1445     return CR_Erase;
1446   }
1447
1448   // This may not be a real conflict if DefMI simply kills Other and defines
1449   // VNI.
1450   if (OtherLRQ.isKill() && OtherLRQ.endPoint() <= VNI->def)
1451     return CR_Keep;
1452
1453   // Handle the case where VNI and OtherVNI can be proven to be identical:
1454   //
1455   //   %other = COPY %ext
1456   //   %this  = COPY %ext <-- Erase this copy
1457   //
1458   if (DefMI->isFullCopy() && !CP.isPartial() &&
1459       stripCopies(VNI) == stripCopies(V.OtherVNI))
1460     return CR_Erase;
1461
1462   // If the lanes written by this instruction were all undef in OtherVNI, it is
1463   // still safe to join the live ranges. This can't be done with a simple value
1464   // mapping, though - OtherVNI will map to multiple values:
1465   //
1466   //   1 %dst:ssub0 = FOO                <-- OtherVNI
1467   //   2 %src = BAR                      <-- VNI
1468   //   3 %dst:ssub1 = COPY %src<kill>    <-- Eliminate this copy.
1469   //   4 BAZ %dst<kill>
1470   //   5 QUUX %src<kill>
1471   //
1472   // Here OtherVNI will map to itself in [1;2), but to VNI in [2;5). CR_Replace
1473   // handles this complex value mapping.
1474   if ((V.WriteLanes & OtherV.ValidLanes) == 0)
1475     return CR_Replace;
1476
1477   // FIXME: Identify CR_Replace opportunities where the clobbered lanes are
1478   // dead.
1479   return CR_Impossible;
1480 }
1481
1482 /// Compute the value assignment for ValNo in LI.
1483 /// This may be called recursively by analyzeValue(), but never for a ValNo on
1484 /// the stack.
1485 void JoinVals::computeAssignment(unsigned ValNo, JoinVals &Other) {
1486   Val &V = Vals[ValNo];
1487   if (V.isAnalyzed()) {
1488     // Recursion should always move up the dominator tree, so ValNo is not
1489     // supposed to reappear before it has been assigned.
1490     assert(Assignments[ValNo] != -1 && "Bad recursion?");
1491     return;
1492   }
1493   switch ((V.Resolution = analyzeValue(ValNo, Other))) {
1494   case CR_Erase:
1495   case CR_Merge:
1496     // Merge this ValNo into OtherVNI.
1497     assert(V.OtherVNI && "OtherVNI not assigned, can't merge.");
1498     assert(Other.Vals[V.OtherVNI->id].isAnalyzed() && "Missing recursion");
1499     Assignments[ValNo] = Other.Assignments[V.OtherVNI->id];
1500     DEBUG(dbgs() << "\t\tmerge " << PrintReg(LI.reg) << ':' << ValNo << '@'
1501                  << LI.getValNumInfo(ValNo)->def << " into "
1502                  << PrintReg(Other.LI.reg) << ':' << V.OtherVNI->id << '@'
1503                  << V.OtherVNI->def << " --> @"
1504                  << NewVNInfo[Assignments[ValNo]]->def << '\n');
1505     break;
1506   default:
1507     // This value number needs to go in the final joined live range.
1508     Assignments[ValNo] = NewVNInfo.size();
1509     NewVNInfo.push_back(LI.getValNumInfo(ValNo));
1510     break;
1511   }
1512 }
1513
1514 bool JoinVals::mapValues(JoinVals &Other) {
1515   for (unsigned i = 0, e = LI.getNumValNums(); i != e; ++i) {
1516     computeAssignment(i, Other);
1517     if (Vals[i].Resolution == CR_Impossible) {
1518       DEBUG(dbgs() << "\t\tinterference at " << PrintReg(LI.reg) << ':' << i
1519                    << '@' << LI.getValNumInfo(i)->def << '\n');
1520       return false;
1521     }
1522   }
1523   return true;
1524 }
1525
1526 bool JoinVals::resolveConflicts(JoinVals &Other) {
1527   for (unsigned i = 0, e = LI.getNumValNums(); i != e; ++i) {
1528     assert (Vals[i].Resolution != CR_Impossible && "Unresolvable conflict");
1529     if (Vals[i].Resolution != CR_Unresolved)
1530       continue;
1531     // FIXME: Actually resolve dead lane conflicts.
1532     DEBUG(dbgs() << "\t\tconflict at " << PrintReg(LI.reg) << ':' << i
1533                  << '@' << LI.getValNumInfo(i)->def << '\n');
1534     return false;
1535   }
1536   return true;
1537 }
1538
1539 void JoinVals::pruneValues(JoinVals &Other,
1540                            SmallVectorImpl<SlotIndex> &EndPoints) {
1541   for (unsigned i = 0, e = LI.getNumValNums(); i != e; ++i) {
1542     if (Vals[i].Resolution != CR_Replace)
1543       continue;
1544     SlotIndex Def = LI.getValNumInfo(i)->def;
1545     LIS->pruneValue(&Other.LI, Def, &EndPoints);
1546     DEBUG(dbgs() << "\t\tpruned " << PrintReg(Other.LI.reg) << " at " << Def
1547                  << ": " << Other.LI << '\n');
1548   }
1549 }
1550
1551 void JoinVals::eraseInstrs(SmallPtrSet<MachineInstr*, 8> &ErasedInstrs,
1552                            SmallVectorImpl<unsigned> &ShrinkRegs) {
1553   for (unsigned i = 0, e = LI.getNumValNums(); i != e; ++i) {
1554     if (Vals[i].Resolution != CR_Erase)
1555       continue;
1556     SlotIndex Def = LI.getValNumInfo(i)->def;
1557     MachineInstr *MI = Indexes->getInstructionFromIndex(Def);
1558     assert(MI && "No instruction to erase");
1559     if (MI->isCopy()) {
1560       unsigned Reg = MI->getOperand(1).getReg();
1561       if (TargetRegisterInfo::isVirtualRegister(Reg) &&
1562           Reg != CP.getSrcReg() && Reg != CP.getDstReg())
1563         ShrinkRegs.push_back(Reg);
1564     }
1565     ErasedInstrs.insert(MI);
1566     DEBUG(dbgs() << "\t\terased:\t" << Def << '\t' << *MI);
1567     LIS->RemoveMachineInstrFromMaps(MI);
1568     MI->eraseFromParent();
1569   }
1570 }
1571
1572 bool RegisterCoalescer::joinVirtRegs(CoalescerPair &CP) {
1573   SmallVector<VNInfo*, 16> NewVNInfo;
1574   LiveInterval &RHS = LIS->getInterval(CP.getSrcReg());
1575   LiveInterval &LHS = LIS->getInterval(CP.getDstReg());
1576   JoinVals RHSVals(RHS, CP.getSrcIdx(), NewVNInfo, CP, LIS, TRI);
1577   JoinVals LHSVals(LHS, CP.getDstIdx(), NewVNInfo, CP, LIS, TRI);
1578
1579   DEBUG(dbgs() << "\t\tRHS = " << PrintReg(CP.getSrcReg()) << ' ' << RHS
1580                << "\n\t\tLHS = " << PrintReg(CP.getDstReg()) << ' ' << LHS
1581                << '\n');
1582
1583   // First compute NewVNInfo and the simple value mappings.
1584   // Detect impossible conflicts early.
1585   if (!LHSVals.mapValues(RHSVals) || !RHSVals.mapValues(LHSVals))
1586     return false;
1587
1588   // Some conflicts can only be resolved after all values have been mapped.
1589   if (!LHSVals.resolveConflicts(RHSVals) || !RHSVals.resolveConflicts(LHSVals))
1590     return false;
1591
1592   // All clear, the live ranges can be merged.
1593
1594   // The merging algorithm in LiveInterval::join() can't handle conflicting
1595   // value mappings, so we need to remove any live ranges that overlap a
1596   // CR_Replace resolution. Collect a set of end points that can be used to
1597   // restore the live range after joining.
1598   SmallVector<SlotIndex, 8> EndPoints;
1599   LHSVals.pruneValues(RHSVals, EndPoints);
1600   RHSVals.pruneValues(LHSVals, EndPoints);
1601
1602   // Erase COPY and IMPLICIT_DEF instructions. This may cause some external
1603   // registers to require trimming.
1604   SmallVector<unsigned, 8> ShrinkRegs;
1605   LHSVals.eraseInstrs(ErasedInstrs, ShrinkRegs);
1606   RHSVals.eraseInstrs(ErasedInstrs, ShrinkRegs);
1607   while (!ShrinkRegs.empty())
1608     LIS->shrinkToUses(&LIS->getInterval(ShrinkRegs.pop_back_val()));
1609
1610   // Join RHS into LHS.
1611   LHS.join(RHS, LHSVals.getAssignments(), RHSVals.getAssignments(), NewVNInfo,
1612            MRI);
1613
1614   // Kill flags are going to be wrong if the live ranges were overlapping.
1615   // Eventually, we should simply clear all kill flags when computing live
1616   // ranges. They are reinserted after register allocation.
1617   MRI->clearKillFlags(LHS.reg);
1618   MRI->clearKillFlags(RHS.reg);
1619
1620   if (EndPoints.empty())
1621     return true;
1622
1623   // Recompute the parts of the live range we had to remove because of
1624   // CR_Replace conflicts.
1625   DEBUG(dbgs() << "\t\trestoring liveness to " << EndPoints.size()
1626                << " points: " << LHS << '\n');
1627   LIS->extendToIndices(&LHS, EndPoints);
1628   return true;
1629 }
1630
1631 /// ComputeUltimateVN - Assuming we are going to join two live intervals,
1632 /// compute what the resultant value numbers for each value in the input two
1633 /// ranges will be.  This is complicated by copies between the two which can
1634 /// and will commonly cause multiple value numbers to be merged into one.
1635 ///
1636 /// VN is the value number that we're trying to resolve.  InstDefiningValue
1637 /// keeps track of the new InstDefiningValue assignment for the result
1638 /// LiveInterval.  ThisFromOther/OtherFromThis are sets that keep track of
1639 /// whether a value in this or other is a copy from the opposite set.
1640 /// ThisValNoAssignments/OtherValNoAssignments keep track of value #'s that have
1641 /// already been assigned.
1642 ///
1643 /// ThisFromOther[x] - If x is defined as a copy from the other interval, this
1644 /// contains the value number the copy is from.
1645 ///
1646 static unsigned ComputeUltimateVN(VNInfo *VNI,
1647                                   SmallVector<VNInfo*, 16> &NewVNInfo,
1648                                   DenseMap<VNInfo*, VNInfo*> &ThisFromOther,
1649                                   DenseMap<VNInfo*, VNInfo*> &OtherFromThis,
1650                                   SmallVector<int, 16> &ThisValNoAssignments,
1651                                   SmallVector<int, 16> &OtherValNoAssignments) {
1652   unsigned VN = VNI->id;
1653
1654   // If the VN has already been computed, just return it.
1655   if (ThisValNoAssignments[VN] >= 0)
1656     return ThisValNoAssignments[VN];
1657   assert(ThisValNoAssignments[VN] != -2 && "Cyclic value numbers");
1658
1659   // If this val is not a copy from the other val, then it must be a new value
1660   // number in the destination.
1661   DenseMap<VNInfo*, VNInfo*>::iterator I = ThisFromOther.find(VNI);
1662   if (I == ThisFromOther.end()) {
1663     NewVNInfo.push_back(VNI);
1664     return ThisValNoAssignments[VN] = NewVNInfo.size()-1;
1665   }
1666   VNInfo *OtherValNo = I->second;
1667
1668   // Otherwise, this *is* a copy from the RHS.  If the other side has already
1669   // been computed, return it.
1670   if (OtherValNoAssignments[OtherValNo->id] >= 0)
1671     return ThisValNoAssignments[VN] = OtherValNoAssignments[OtherValNo->id];
1672
1673   // Mark this value number as currently being computed, then ask what the
1674   // ultimate value # of the other value is.
1675   ThisValNoAssignments[VN] = -2;
1676   unsigned UltimateVN =
1677     ComputeUltimateVN(OtherValNo, NewVNInfo, OtherFromThis, ThisFromOther,
1678                       OtherValNoAssignments, ThisValNoAssignments);
1679   return ThisValNoAssignments[VN] = UltimateVN;
1680 }
1681
1682
1683 // Find out if we have something like
1684 // A = X
1685 // B = X
1686 // if so, we can pretend this is actually
1687 // A = X
1688 // B = A
1689 // which allows us to coalesce A and B.
1690 // VNI is the definition of B. LR is the life range of A that includes
1691 // the slot just before B. If we return true, we add "B = X" to DupCopies.
1692 // This implies that A dominates B.
1693 static bool RegistersDefinedFromSameValue(LiveIntervals &li,
1694                                           const TargetRegisterInfo &tri,
1695                                           CoalescerPair &CP,
1696                                           VNInfo *VNI,
1697                                           VNInfo *OtherVNI,
1698                                      SmallVector<MachineInstr*, 8> &DupCopies) {
1699   // FIXME: This is very conservative. For example, we don't handle
1700   // physical registers.
1701
1702   MachineInstr *MI = li.getInstructionFromIndex(VNI->def);
1703
1704   if (!MI || CP.isPartial() || CP.isPhys())
1705     return false;
1706
1707   unsigned A = CP.getDstReg();
1708   if (!TargetRegisterInfo::isVirtualRegister(A))
1709     return false;
1710
1711   unsigned B = CP.getSrcReg();
1712   if (!TargetRegisterInfo::isVirtualRegister(B))
1713     return false;
1714
1715   MachineInstr *OtherMI = li.getInstructionFromIndex(OtherVNI->def);
1716   if (!OtherMI)
1717     return false;
1718
1719   if (MI->isImplicitDef()) {
1720     DupCopies.push_back(MI);
1721     return true;
1722   } else {
1723     if (!MI->isFullCopy())
1724       return false;
1725     unsigned Src = MI->getOperand(1).getReg();
1726     if (!TargetRegisterInfo::isVirtualRegister(Src))
1727       return false;
1728     if (!OtherMI->isFullCopy())
1729       return false;
1730     unsigned OtherSrc = OtherMI->getOperand(1).getReg();
1731     if (!TargetRegisterInfo::isVirtualRegister(OtherSrc))
1732       return false;
1733
1734     if (Src != OtherSrc)
1735       return false;
1736
1737     // If the copies use two different value numbers of X, we cannot merge
1738     // A and B.
1739     LiveInterval &SrcInt = li.getInterval(Src);
1740     // getVNInfoBefore returns NULL for undef copies. In this case, the
1741     // optimization is still safe.
1742     if (SrcInt.getVNInfoBefore(OtherVNI->def) !=
1743         SrcInt.getVNInfoBefore(VNI->def))
1744       return false;
1745
1746     DupCopies.push_back(MI);
1747     return true;
1748   }
1749 }
1750
1751 /// joinIntervals - Attempt to join these two intervals.  On failure, this
1752 /// returns false.
1753 bool RegisterCoalescer::joinIntervals(CoalescerPair &CP) {
1754   // Handle physreg joins separately.
1755   if (CP.isPhys())
1756     return joinReservedPhysReg(CP);
1757
1758   if (NewCoalescer)
1759     return joinVirtRegs(CP);
1760
1761   LiveInterval &RHS = LIS->getInterval(CP.getSrcReg());
1762   DEBUG(dbgs() << "\t\tRHS = " << PrintReg(CP.getSrcReg()) << ' ' << RHS
1763                << '\n');
1764
1765   // Compute the final value assignment, assuming that the live ranges can be
1766   // coalesced.
1767   SmallVector<int, 16> LHSValNoAssignments;
1768   SmallVector<int, 16> RHSValNoAssignments;
1769   DenseMap<VNInfo*, VNInfo*> LHSValsDefinedFromRHS;
1770   DenseMap<VNInfo*, VNInfo*> RHSValsDefinedFromLHS;
1771   SmallVector<VNInfo*, 16> NewVNInfo;
1772
1773   SmallVector<MachineInstr*, 8> DupCopies;
1774   SmallVector<MachineInstr*, 8> DeadCopies;
1775
1776   LiveInterval &LHS = LIS->getOrCreateInterval(CP.getDstReg());
1777   DEBUG(dbgs() << "\t\tLHS = " << PrintReg(CP.getDstReg(), TRI) << ' ' << LHS
1778                << '\n');
1779
1780   // Loop over the value numbers of the LHS, seeing if any are defined from
1781   // the RHS.
1782   for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1783        i != e; ++i) {
1784     VNInfo *VNI = *i;
1785     if (VNI->isUnused() || VNI->isPHIDef())
1786       continue;
1787     MachineInstr *MI = LIS->getInstructionFromIndex(VNI->def);
1788     assert(MI && "Missing def");
1789     if (!MI->isCopyLike() && !MI->isImplicitDef()) // Src not defined by a copy?
1790       continue;
1791
1792     // Figure out the value # from the RHS.
1793     VNInfo *OtherVNI = RHS.getVNInfoBefore(VNI->def);
1794     // The copy could be to an aliased physreg.
1795     if (!OtherVNI)
1796       continue;
1797
1798     // DstReg is known to be a register in the LHS interval.  If the src is
1799     // from the RHS interval, we can use its value #.
1800     if (CP.isCoalescable(MI))
1801       DeadCopies.push_back(MI);
1802     else if (!RegistersDefinedFromSameValue(*LIS, *TRI, CP, VNI, OtherVNI,
1803                                             DupCopies))
1804       continue;
1805
1806     LHSValsDefinedFromRHS[VNI] = OtherVNI;
1807   }
1808
1809   // Loop over the value numbers of the RHS, seeing if any are defined from
1810   // the LHS.
1811   for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
1812        i != e; ++i) {
1813     VNInfo *VNI = *i;
1814     if (VNI->isUnused() || VNI->isPHIDef())
1815       continue;
1816     MachineInstr *MI = LIS->getInstructionFromIndex(VNI->def);
1817     assert(MI && "Missing def");
1818     if (!MI->isCopyLike() && !MI->isImplicitDef()) // Src not defined by a copy?
1819       continue;
1820
1821     // Figure out the value # from the LHS.
1822     VNInfo *OtherVNI = LHS.getVNInfoBefore(VNI->def);
1823     // The copy could be to an aliased physreg.
1824     if (!OtherVNI)
1825       continue;
1826
1827     // DstReg is known to be a register in the RHS interval.  If the src is
1828     // from the LHS interval, we can use its value #.
1829     if (CP.isCoalescable(MI))
1830       DeadCopies.push_back(MI);
1831     else if (!RegistersDefinedFromSameValue(*LIS, *TRI, CP, VNI, OtherVNI,
1832                                             DupCopies))
1833         continue;
1834
1835     RHSValsDefinedFromLHS[VNI] = OtherVNI;
1836   }
1837
1838   LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
1839   RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
1840   NewVNInfo.reserve(LHS.getNumValNums() + RHS.getNumValNums());
1841
1842   for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1843        i != e; ++i) {
1844     VNInfo *VNI = *i;
1845     unsigned VN = VNI->id;
1846     if (LHSValNoAssignments[VN] >= 0 || VNI->isUnused())
1847       continue;
1848     ComputeUltimateVN(VNI, NewVNInfo,
1849                       LHSValsDefinedFromRHS, RHSValsDefinedFromLHS,
1850                       LHSValNoAssignments, RHSValNoAssignments);
1851   }
1852   for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
1853        i != e; ++i) {
1854     VNInfo *VNI = *i;
1855     unsigned VN = VNI->id;
1856     if (RHSValNoAssignments[VN] >= 0 || VNI->isUnused())
1857       continue;
1858     // If this value number isn't a copy from the LHS, it's a new number.
1859     if (RHSValsDefinedFromLHS.find(VNI) == RHSValsDefinedFromLHS.end()) {
1860       NewVNInfo.push_back(VNI);
1861       RHSValNoAssignments[VN] = NewVNInfo.size()-1;
1862       continue;
1863     }
1864
1865     ComputeUltimateVN(VNI, NewVNInfo,
1866                       RHSValsDefinedFromLHS, LHSValsDefinedFromRHS,
1867                       RHSValNoAssignments, LHSValNoAssignments);
1868   }
1869
1870   // Armed with the mappings of LHS/RHS values to ultimate values, walk the
1871   // interval lists to see if these intervals are coalescable.
1872   LiveInterval::const_iterator I = LHS.begin();
1873   LiveInterval::const_iterator IE = LHS.end();
1874   LiveInterval::const_iterator J = RHS.begin();
1875   LiveInterval::const_iterator JE = RHS.end();
1876
1877   // Collect interval end points that will no longer be kills.
1878   SmallVector<MachineInstr*, 8> LHSOldKills;
1879   SmallVector<MachineInstr*, 8> RHSOldKills;
1880
1881   // Skip ahead until the first place of potential sharing.
1882   if (I != IE && J != JE) {
1883     if (I->start < J->start) {
1884       I = std::upper_bound(I, IE, J->start);
1885       if (I != LHS.begin()) --I;
1886     } else if (J->start < I->start) {
1887       J = std::upper_bound(J, JE, I->start);
1888       if (J != RHS.begin()) --J;
1889     }
1890   }
1891
1892   while (I != IE && J != JE) {
1893     // Determine if these two live ranges overlap.
1894     // If so, check value # info to determine if they are really different.
1895     if (I->end > J->start && J->end > I->start) {
1896       // If the live range overlap will map to the same value number in the
1897       // result liverange, we can still coalesce them.  If not, we can't.
1898       if (LHSValNoAssignments[I->valno->id] !=
1899           RHSValNoAssignments[J->valno->id])
1900         return false;
1901
1902       // Extended live ranges should no longer be killed.
1903       if (!I->end.isBlock() && I->end < J->end)
1904         if (MachineInstr *MI = LIS->getInstructionFromIndex(I->end))
1905           LHSOldKills.push_back(MI);
1906       if (!J->end.isBlock() && J->end < I->end)
1907         if (MachineInstr *MI = LIS->getInstructionFromIndex(J->end))
1908           RHSOldKills.push_back(MI);
1909     }
1910
1911     if (I->end < J->end)
1912       ++I;
1913     else
1914       ++J;
1915   }
1916
1917   // Clear kill flags where live ranges are extended.
1918   while (!LHSOldKills.empty())
1919     LHSOldKills.pop_back_val()->clearRegisterKills(LHS.reg, TRI);
1920   while (!RHSOldKills.empty())
1921     RHSOldKills.pop_back_val()->clearRegisterKills(RHS.reg, TRI);
1922
1923   if (LHSValNoAssignments.empty())
1924     LHSValNoAssignments.push_back(-1);
1925   if (RHSValNoAssignments.empty())
1926     RHSValNoAssignments.push_back(-1);
1927
1928   // Now erase all the redundant copies.
1929   for (unsigned i = 0, e = DeadCopies.size(); i != e; ++i) {
1930     MachineInstr *MI = DeadCopies[i];
1931     if (!ErasedInstrs.insert(MI))
1932       continue;
1933     DEBUG(dbgs() << "\t\terased:\t" << LIS->getInstructionIndex(MI)
1934                  << '\t' << *MI);
1935     LIS->RemoveMachineInstrFromMaps(MI);
1936     MI->eraseFromParent();
1937   }
1938
1939   SmallVector<unsigned, 8> SourceRegisters;
1940   for (SmallVector<MachineInstr*, 8>::iterator I = DupCopies.begin(),
1941          E = DupCopies.end(); I != E; ++I) {
1942     MachineInstr *MI = *I;
1943     if (!ErasedInstrs.insert(MI))
1944       continue;
1945
1946     // If MI is a copy, then we have pretended that the assignment to B in
1947     // A = X
1948     // B = X
1949     // was actually a copy from A. Now that we decided to coalesce A and B,
1950     // transform the code into
1951     // A = X
1952     // In the case of the implicit_def, we just have to remove it.
1953     if (!MI->isImplicitDef()) {
1954       unsigned Src = MI->getOperand(1).getReg();
1955       SourceRegisters.push_back(Src);
1956     }
1957     LIS->RemoveMachineInstrFromMaps(MI);
1958     MI->eraseFromParent();
1959   }
1960
1961   // If B = X was the last use of X in a liverange, we have to shrink it now
1962   // that B = X is gone.
1963   for (SmallVector<unsigned, 8>::iterator I = SourceRegisters.begin(),
1964          E = SourceRegisters.end(); I != E; ++I) {
1965     LIS->shrinkToUses(&LIS->getInterval(*I));
1966   }
1967
1968   // If we get here, we know that we can coalesce the live ranges.  Ask the
1969   // intervals to coalesce themselves now.
1970   LHS.join(RHS, &LHSValNoAssignments[0], &RHSValNoAssignments[0], NewVNInfo,
1971            MRI);
1972   return true;
1973 }
1974
1975 namespace {
1976   // DepthMBBCompare - Comparison predicate that sort first based on the loop
1977   // depth of the basic block (the unsigned), and then on the MBB number.
1978   struct DepthMBBCompare {
1979     typedef std::pair<unsigned, MachineBasicBlock*> DepthMBBPair;
1980     bool operator()(const DepthMBBPair &LHS, const DepthMBBPair &RHS) const {
1981       // Deeper loops first
1982       if (LHS.first != RHS.first)
1983         return LHS.first > RHS.first;
1984
1985       // Prefer blocks that are more connected in the CFG. This takes care of
1986       // the most difficult copies first while intervals are short.
1987       unsigned cl = LHS.second->pred_size() + LHS.second->succ_size();
1988       unsigned cr = RHS.second->pred_size() + RHS.second->succ_size();
1989       if (cl != cr)
1990         return cl > cr;
1991
1992       // As a last resort, sort by block number.
1993       return LHS.second->getNumber() < RHS.second->getNumber();
1994     }
1995   };
1996 }
1997
1998 // Try joining WorkList copies starting from index From.
1999 // Null out any successful joins.
2000 bool RegisterCoalescer::copyCoalesceWorkList(unsigned From) {
2001   assert(From <= WorkList.size() && "Out of range");
2002   bool Progress = false;
2003   for (unsigned i = From, e = WorkList.size(); i != e; ++i) {
2004     if (!WorkList[i])
2005       continue;
2006     // Skip instruction pointers that have already been erased, for example by
2007     // dead code elimination.
2008     if (ErasedInstrs.erase(WorkList[i])) {
2009       WorkList[i] = 0;
2010       continue;
2011     }
2012     bool Again = false;
2013     bool Success = joinCopy(WorkList[i], Again);
2014     Progress |= Success;
2015     if (Success || !Again)
2016       WorkList[i] = 0;
2017   }
2018   return Progress;
2019 }
2020
2021 void
2022 RegisterCoalescer::copyCoalesceInMBB(MachineBasicBlock *MBB) {
2023   DEBUG(dbgs() << MBB->getName() << ":\n");
2024
2025   // Collect all copy-like instructions in MBB. Don't start coalescing anything
2026   // yet, it might invalidate the iterator.
2027   const unsigned PrevSize = WorkList.size();
2028   for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end();
2029        MII != E; ++MII)
2030     if (MII->isCopyLike())
2031       WorkList.push_back(MII);
2032
2033   // Try coalescing the collected copies immediately, and remove the nulls.
2034   // This prevents the WorkList from getting too large since most copies are
2035   // joinable on the first attempt.
2036   if (copyCoalesceWorkList(PrevSize))
2037     WorkList.erase(std::remove(WorkList.begin() + PrevSize, WorkList.end(),
2038                                (MachineInstr*)0), WorkList.end());
2039 }
2040
2041 void RegisterCoalescer::joinAllIntervals() {
2042   DEBUG(dbgs() << "********** JOINING INTERVALS ***********\n");
2043   assert(WorkList.empty() && "Old data still around.");
2044
2045   if (Loops->empty()) {
2046     // If there are no loops in the function, join intervals in function order.
2047     for (MachineFunction::iterator I = MF->begin(), E = MF->end();
2048          I != E; ++I)
2049       copyCoalesceInMBB(I);
2050   } else {
2051     // Otherwise, join intervals in inner loops before other intervals.
2052     // Unfortunately we can't just iterate over loop hierarchy here because
2053     // there may be more MBB's than BB's.  Collect MBB's for sorting.
2054
2055     // Join intervals in the function prolog first. We want to join physical
2056     // registers with virtual registers before the intervals got too long.
2057     std::vector<std::pair<unsigned, MachineBasicBlock*> > MBBs;
2058     for (MachineFunction::iterator I = MF->begin(), E = MF->end();I != E;++I){
2059       MachineBasicBlock *MBB = I;
2060       MBBs.push_back(std::make_pair(Loops->getLoopDepth(MBB), I));
2061     }
2062
2063     // Sort by loop depth.
2064     std::sort(MBBs.begin(), MBBs.end(), DepthMBBCompare());
2065
2066     // Finally, join intervals in loop nest order.
2067     for (unsigned i = 0, e = MBBs.size(); i != e; ++i)
2068       copyCoalesceInMBB(MBBs[i].second);
2069   }
2070
2071   // Joining intervals can allow other intervals to be joined.  Iteratively join
2072   // until we make no progress.
2073   while (copyCoalesceWorkList())
2074     /* empty */ ;
2075 }
2076
2077 void RegisterCoalescer::releaseMemory() {
2078   ErasedInstrs.clear();
2079   WorkList.clear();
2080   DeadDefs.clear();
2081   InflateRegs.clear();
2082 }
2083
2084 bool RegisterCoalescer::runOnMachineFunction(MachineFunction &fn) {
2085   MF = &fn;
2086   MRI = &fn.getRegInfo();
2087   TM = &fn.getTarget();
2088   TRI = TM->getRegisterInfo();
2089   TII = TM->getInstrInfo();
2090   LIS = &getAnalysis<LiveIntervals>();
2091   LDV = &getAnalysis<LiveDebugVariables>();
2092   AA = &getAnalysis<AliasAnalysis>();
2093   Loops = &getAnalysis<MachineLoopInfo>();
2094
2095   DEBUG(dbgs() << "********** SIMPLE REGISTER COALESCING **********\n"
2096                << "********** Function: " << MF->getName() << '\n');
2097
2098   if (VerifyCoalescing)
2099     MF->verify(this, "Before register coalescing");
2100
2101   RegClassInfo.runOnMachineFunction(fn);
2102
2103   // Join (coalesce) intervals if requested.
2104   if (EnableJoining)
2105     joinAllIntervals();
2106
2107   // After deleting a lot of copies, register classes may be less constrained.
2108   // Removing sub-register operands may allow GR32_ABCD -> GR32 and DPR_VFP2 ->
2109   // DPR inflation.
2110   array_pod_sort(InflateRegs.begin(), InflateRegs.end());
2111   InflateRegs.erase(std::unique(InflateRegs.begin(), InflateRegs.end()),
2112                     InflateRegs.end());
2113   DEBUG(dbgs() << "Trying to inflate " << InflateRegs.size() << " regs.\n");
2114   for (unsigned i = 0, e = InflateRegs.size(); i != e; ++i) {
2115     unsigned Reg = InflateRegs[i];
2116     if (MRI->reg_nodbg_empty(Reg))
2117       continue;
2118     if (MRI->recomputeRegClass(Reg, *TM)) {
2119       DEBUG(dbgs() << PrintReg(Reg) << " inflated to "
2120                    << MRI->getRegClass(Reg)->getName() << '\n');
2121       ++NumInflated;
2122     }
2123   }
2124
2125   DEBUG(dump());
2126   DEBUG(LDV->dump());
2127   if (VerifyCoalescing)
2128     MF->verify(this, "After register coalescing");
2129   return true;
2130 }
2131
2132 /// print - Implement the dump method.
2133 void RegisterCoalescer::print(raw_ostream &O, const Module* m) const {
2134    LIS->print(O, m);
2135 }