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