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